scaling-swarms / frontend /src /editor /embeds /insert-position.ts
tfrere's picture
tfrere HF Staff
Cursor
feat(embed-studio): drafts with Apply to article, compare, data drawer
f7733a1
Raw History Blame Contribute Delete
2.18 kB
import type { Editor } from "@tiptap/core";
import * as Y from "yjs";
import {
absolutePositionToRelativePosition,
relativePositionToAbsolutePosition,
ySyncPluginKey,
} from "@tiptap/y-tiptap";
/**
* Where a new chart will be inserted, remembered as a Yjs relative position
* so co-authors' edits while the studio is open do not shift it.
*/
export type InsertAnchor = { rel: unknown } | { pos: number };
export function captureInsertAnchor(editor: Editor): InsertAnchor {
const pos = editor.state.selection.to;
const ystate = ySyncPluginKey.getState(editor.state);
if (!ystate?.binding) return { pos };
try {
const rel = absolutePositionToRelativePosition(pos, ystate.type, ystate.binding.mapping);
return { rel: Y.relativePositionToJSON(rel) };
} catch {
return { pos };
}
}
export function resolveInsertAnchor(editor: Editor, anchor: InsertAnchor | null | undefined): number {
const size = editor.state.doc.content.size;
if (!anchor) return Math.min(editor.state.selection.to, size);
if ("pos" in anchor) return Math.max(0, Math.min(anchor.pos, size));
const ystate = ySyncPluginKey.getState(editor.state);
if (ystate?.binding) {
try {
const pos = relativePositionToAbsolutePosition(
ystate.doc,
ystate.type,
Y.createRelativePositionFromJSON(anchor.rel),
ystate.binding.mapping,
);
if (pos !== null && pos !== undefined) return Math.max(0, Math.min(pos, size));
} catch {
// Anchor deleted with its paragraph: fall back to the end of the document.
}
}
return size;
}
/** Insert an htmlEmbed node after the block that contains `pos`. */
export function insertEmbedNode(
editor: Editor,
pos: number,
attrs: { src: string; title?: string; desc?: string },
): boolean {
const { state } = editor;
const $pos = state.doc.resolve(Math.max(0, Math.min(pos, state.doc.content.size)));
// Top-level insertion point: right after the top-level block holding pos.
const at = $pos.depth >= 1 ? $pos.after(1) : $pos.pos;
return editor
.chain()
.insertContentAt(at, { type: "htmlEmbed", attrs: { title: "", desc: "", ...attrs } })
.run();
}