Files
deerflow-code/frontend-web/src/open-canvas/utils/apply-rewrite.ts
T
2026-05-16 22:00:34 +08:00

52 lines
1.3 KiB
TypeScript

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();
}