UNPKG

@liveblocks/react-ui

Version:

A set of React pre-built components for the Liveblocks products. Liveblocks is the all-in-one toolkit to build collaborative products like Figma, Notion, and more.

81 lines (78 loc) 2.29 kB
import { Range, Editor, Transforms } from 'slate'; import { getCharacterBefore } from '../utils/get-character.js'; import { getMatchRange } from '../utils/get-match-range.js'; import { isEmptyString } from '../utils/is-empty-string.js'; const formatters = [ { type: "mark", mark: "bold", character: "*" }, { type: "mark", mark: "italic", character: "_" }, { type: "mark", mark: "strikethrough", character: "~" }, { type: "mark", mark: "code", character: "`" } ]; const markFormattingCharacters = formatters.filter((formatter) => formatter.type === "mark").map((formatter) => formatter.character); function formatMark(editor, text, formatter) { if (text !== formatter.character) { return false; } const match = getMatchRange(editor, editor.selection, [formatter.character]); if (!match || Range.isCollapsed(match)) { return false; } const formattingCharacter = getCharacterBefore(editor, match); if (!formattingCharacter || formattingCharacter.text !== formatter.character) { return false; } const beforeCharacter = getCharacterBefore(editor, formattingCharacter.range); if (beforeCharacter && !markFormattingCharacters.includes(beforeCharacter.text) && !isEmptyString(beforeCharacter.text)) { return false; } const matchText = Editor.string(editor, match); if (matchText.trim() !== matchText) { return false; } Transforms.select(editor, match); editor.addMark(formatter.mark, true); Transforms.collapse(editor, { edge: "end" }); editor.removeMark(formatter.mark); Transforms.delete(editor, { at: formattingCharacter.range }); return true; } function withAutoFormatting(editor) { const { insertText } = editor; editor.insertText = (text, options) => { if (!editor.selection || !Range.isCollapsed(editor.selection)) { return insertText(text, options); } let shouldInsertText = true; for (const formatter of formatters) { if (formatter.type === "mark") { if (formatMark(editor, text, formatter)) { shouldInsertText = false; } } } if (shouldInsertText) { insertText(text, options); } }; return editor; } export { withAutoFormatting }; //# sourceMappingURL=auto-formatting.js.map