Skip to content

Commit

Permalink
feat(text): support soft break
Browse files Browse the repository at this point in the history
  • Loading branch information
pubuzhixing8 committed Dec 1, 2024
1 parent eb65ef8 commit 55d9d7d
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 15 deletions.
1 change: 1 addition & 0 deletions packages/react-text/src/plugins/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './with-text';
27 changes: 27 additions & 0 deletions packages/react-text/src/plugins/with-text.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { CLIPBOARD_FORMAT_KEY } from '@plait/text-plugins';
import { ReactEditor } from 'slate-react';

export const withText = <T extends ReactEditor>(editor: T) => {
const e = editor as T;
const { insertData } = e;

e.insertBreak = () => {
editor.insertText('\n');
};

e.insertData = (data: DataTransfer) => {
let text = data.getData('text/plain');
let plaitData = data.getData(`application/${CLIPBOARD_FORMAT_KEY}`);
if (!plaitData && text) {
if (text.endsWith('\n')) {
text = text.substring(0, text.length - 1);
}
text = text.trim().replace(/\t+/g, ' ');
e.insertText(text);
return;
}
insertData(data);
};

return e;
};
19 changes: 4 additions & 15 deletions packages/react-text/src/text.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Editable, RenderLeafProps, Slate, withReact } from 'slate-react';
import type { CustomText, TextProps } from '@plait/common';
import React, { useMemo, useCallback } from 'react';
import { withHistory } from 'slate-history';
import { withText } from './plugins/with-text';

import './styles/index.scss';

Expand All @@ -22,7 +23,7 @@ export const Text: React.FC<TextComponentProps> = (
);
const initialValue: Descendant[] = [text];
const editor = useMemo(() => {
const editor = withHistory(withReact(createEditor()));
const editor = withText(withHistory(withReact(createEditor())));
afterInit && afterInit(editor);
return editor;
}, []);
Expand All @@ -43,15 +44,7 @@ export const Text: React.FC<TextComponentProps> = (
renderElement={renderElement}
renderLeaf={renderLeaf}
readOnly={readonly === undefined ? true : readonly}
onKeyDown={(event) => {
// for (const hotkey in HOTKEYS) {
// if (isHotkey(hotkey, event as any)) {
// event.preventDefault();
// const mark = HOTKEYS[hotkey];
// toggleMark(editor, mark);
// }
// }
}}
onKeyDown={(event) => {}}
onCompositionStart={(event) => {
if (onComposition) {
onComposition(event as unknown as CompositionEvent);
Expand Down Expand Up @@ -86,11 +79,7 @@ const ParagraphElement = (props: {
);
};

const Leaf: React.FC<RenderLeafProps> = ({
children,
leaf,
attributes
}) => {
const Leaf: React.FC<RenderLeafProps> = ({ children, leaf, attributes }) => {
if ((leaf as CustomText).bold) {
children = <strong>{children}</strong>;
}
Expand Down

0 comments on commit 55d9d7d

Please sign in to comment.