智能选中文字

This commit is contained in:
董宏凯 committed 2026-05-16 22:00:34 +08:00
1 parent e8a31b5d37
commit da4a08dfe1
34 files changed
+3208 -541

No files matched your search

@@ -0,0 +1,51 @@
import type { Editor } from "@tiptap/react";
import type { WritingSelection } from "../types/selection";
/** Convert plain text (possibly multi-paragraph) to a list of Tiptap paragraph nodes. */
function textToNodes(schema: Editor["schema"], text: string) {
const paragraphs = text.split(/\n{2,}/);
return paragraphs
.map((p) => p.trim())
.filter(Boolean)
.map((p) => ({
type: "paragraph",
content: p ? [{ type: "text", text: p }] : [],
}));
}
/**
* Replace the selection range with the new text.
* Restores focus and places cursor after the inserted content.
*/
export function applyReplace(
editor: Editor,
selection: WritingSelection,
newText: string,
): void {
const { from, to } = selection;
const nodes = textToNodes(editor.schema, newText);
if (nodes.length === 0) return;
editor
.chain()
.focus()
.deleteRange({ from, to })
.insertContentAt(from, nodes)
.run();
}
/**
* Insert the new text as new paragraph(s) after the selection end.
* Original text is preserved.
*/
export function applyInsert(
editor: Editor,
selection: WritingSelection,
newText: string,
): void {
const { to } = selection;
const nodes = textToNodes(editor.schema, newText);
if (nodes.length === 0) return;
editor.chain().focus().insertContentAt(to, nodes).run();
}