Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Add Protyle tracked range APIs https://github.com/siyuan-note/siyuan/issues/19054

Danield43b3c8081cb
diff --git a/app/src/layout/dock/agent/AgentComposer.ts b/app/src/layout/dock/agent/AgentComposer.ts
index 902bbb5ec9..7545ef0a5c 100644
--- a/app/src/layout/dock/agent/AgentComposer.ts
+++ b/app/src/layout/dock/agent/AgentComposer.ts
@@ -12,6 +12,7 @@ import {isSkillHintRequestActive, shouldYieldSkillHint} from "./agentHintState";
import {uploadFiles} from "../../../protyle/upload";
import {previewImages} from "../../../protyle/preview/image";
import {removeCompressURL} from "../../../util/image";
+import {invalidateTrackedRanges} from "../../../protyle/util/trackedRange";
export interface AgentComposerData {
text: string;
@@ -239,6 +240,7 @@ export function mountComposer(host: HTMLElement, onSend: () => void, onChange?:
p.toolbar.subElement.setAttribute("data-position-boundary", "viewport");
const setEmptyContent = () => {
+ invalidateTrackedRanges(p);
wysiwyg.element.innerHTML = "";
const emptyElement = genEmptyElement(false, false);
emptyElement.firstElementChild.classList.add("protyle-wysiwyg--empty");
@@ -327,6 +329,7 @@ export function mountComposer(host: HTMLElement, onSend: () => void, onChange?:
event.stopPropagation();
const target = history.isBrowsing() ?
history.navigateUp() : history.beginBrowsing(wysiwyg.element.innerHTML);
+ invalidateTrackedRanges(p);
wysiwyg.element.innerHTML = p.lute.Md2BlockDOM(target);
return;
}
@@ -336,6 +339,7 @@ export function mountComposer(host: HTMLElement, onSend: () => void, onChange?:
event.preventDefault();
event.stopPropagation();
const target = history.navigateDown();
+ invalidateTrackedRanges(p);
if (history.isBrowsing()) {
p.wysiwyg.element.innerHTML = p.lute.Md2BlockDOM(target);
} else {
diff --git a/app/src/mobile/editor.ts b/app/src/mobile/editor.ts
index eef6eefa29..3938908b53 100644
--- a/app/src/mobile/editor.ts
+++ b/app/src/mobile/editor.ts
@@ -19,6 +19,7 @@ import {bindMobileBarsScroll, pauseMobileBarsScroll} from "./util/mobileBars";
import {forEachPluginSubscriber} from "../plugin/EventBusCore";
import {restoreMobileTopBarLayout, updateMobileTopBarLayout} from "./util/mobileTopBar";
import {stickyRow} from "../protyle/render/av/row";
+import {invalidateTrackedRanges} from "../protyle/util/trackedRange";
export const getCurrentEditor = () => {
return window.siyuan.mobile.popEditor || window.siyuan.mobile.editor;
@@ -195,6 +196,7 @@ export const loadMobileFileById = (app: App, id: string, action: TProtyleAction[
},
};
if (window.siyuan.mobile.editor) {
+ invalidateTrackedRanges(window.siyuan.mobile.editor.protyle);
window.siyuan.mobile.editor.protyle.notebookId = data.data.box;
window.siyuan.mobile.editor.protyle.title.element.removeAttribute("data-render");
addLoading(window.siyuan.mobile.editor.protyle);
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.ts
index 796c4e981e..f5a17818d0 100644
--- a/app/src/mobile/util/keyboardToolbar.ts
+++ b/app/src/mobile/util/keyboardToolbar.ts
@@ -12,6 +12,7 @@ import {getCurrentEditor} from "../editor";
import {convertFontSize, fontEvent, getFontNodeElements, getFontSizeInfo} from "../../protyle/toolbar/Font";
import {hideElements} from "../../protyle/ui/hideElements";
import {softEnter} from "../../protyle/wysiwyg/enter";
+import {endTrackedRangeInsertion, prepareTrackedRangeInsertion} from "../../protyle/util/trackedRange";
import {
isDisabledFeature,
isInAndroid,
@@ -1372,8 +1373,13 @@ export const initKeyboardToolbar = () => {
focusByRange(range);
return;
} else if (type === "softLine") {
- range.extractContents();
- softEnter(range, nodeElement, protyle);
+ const trackedRangeInsertion = prepareTrackedRangeInsertion(protyle, range);
+ try {
+ range.extractContents();
+ softEnter(range, nodeElement, protyle, trackedRangeInsertion);
+ } finally {
+ endTrackedRangeInsertion(trackedRangeInsertion);
+ }
focusByRange(range);
return;
} else if (type === "add") {
diff --git a/app/src/mobile/util/setEmpty.ts b/app/src/mobile/util/setEmpty.ts
index 0be26b5b9d..74f4fc3ac8 100644
--- a/app/src/mobile/util/setEmpty.ts
+++ b/app/src/mobile/util/setEmpty.ts
@@ -8,8 +8,15 @@ import type {App} from "../../index";
import {setTitle} from "../../util/processTitle";
import {clearMobileBarsScroll} from "./mobileBars";
import {updateMobileTopBarLayout} from "./mobileTopBar";
+import {invalidateTrackedRanges} from "../../protyle/util/trackedRange";
export const setEmpty = (app: App) => {
+ if (window.siyuan.mobile.editor?.protyle) {
+ invalidateTrackedRanges(window.siyuan.mobile.editor.protyle);
+ }
+ if (window.siyuan.mobile.popEditor?.protyle) {
+ invalidateTrackedRanges(window.siyuan.mobile.popEditor.protyle);
+ }
setTitle("", true);
clearMobileBarsScroll();
document.getElementById("mobileTopBar").classList.add("fn__none");
diff --git a/app/src/plugin/uninstall.ts b/app/src/plugin/uninstall.ts
index 14468766b9..2eef46d5a0 100644
--- a/app/src/plugin/uninstall.ts
+++ b/app/src/plugin/uninstall.ts
@@ -19,6 +19,7 @@ import {isWindow} from "../util/functions";
import {destroyEventBus} from "./EventBusCore";
import {unregisterPluginCommands} from "./commandAdapter";
import {sendGlobalShortcut} from "../boot/globalEvent/globalShortcut";
+import {releaseTrackedRangesByPlugin} from "../protyle/util/trackedRange";
const runCleanup = (plugin: Plugin, step: string, callback: () => unknown) => {
try {
@@ -36,6 +37,7 @@ const runCleanup = (plugin: Plugin, step: string, callback: () => unknown) => {
export const beginPluginTeardown = (plugin: Plugin) => {
runCleanup(plugin, "commands", () => unregisterPluginCommands(plugin));
runCleanup(plugin, "asset upload", () => cancelAssetUploadsByPlugin(plugin));
+ runCleanup(plugin, "tracked ranges", () => releaseTrackedRangesByPlugin(plugin));
};
export const destroyPlugin = (app: App, plugin: Plugin, isUninstall: boolean) => {
diff --git a/app/src/protyle/index.ts b/app/src/protyle/index.ts
index 7befd57bfb..e9f3615954 100644
--- a/app/src/protyle/index.ts
+++ b/app/src/protyle/index.ts
@@ -66,6 +66,12 @@ import {
queueDatabaseRowRefreshForOperations
} from "./render/av/databaseRowRefresh";
import {registerCustomBlockRoot} from "../plugin/customBlockRender";
+import {
+ invalidateTrackedRanges,
+ releaseTrackedRange,
+ resolveTrackedRange,
+ trackRange,
+} from "./util/trackedRange";
/// #if !MOBILE
const forSearchByEditor = (edit: Protyle, callback: (config: Config.IUILayoutTabSearchConfig, element: Element) => void) => {
@@ -113,6 +119,9 @@ export class Protyle {
const mergedOptions = getOptions.merge();
this.protyle = {
getInstance: () => this,
+ trackRange: (range, trackOptions) => this.trackRange(range, trackOptions),
+ resolveTrackedRange: (handle) => this.resolveTrackedRange(handle),
+ releaseTrackedRange: (handle) => this.releaseTrackedRange(handle),
app,
id: genUUID(),
disabled: false,
@@ -416,6 +425,7 @@ export class Protyle {
queueDatabaseRowRefreshForOperations(this.protyle.id, data.data[0]?.doOperations || []);
if (!this.protyle.preview.element.classList.contains("fn__none") &&
data.context?.rootIDs?.includes(this.protyle.block.rootID)) {
+ invalidateTrackedRanges(this.protyle);
this.protyle.preview.render(this.protyle);
return;
}
@@ -681,6 +691,18 @@ export class Protyle {
return getEditorRange(element);
}
+ public trackRange(range: Range, options: ITrackRangeOptions): ITrackedRangeHandle {
+ return trackRange(this.protyle, range, options);
+ }
+
+ public resolveTrackedRange(handle: ITrackedRangeHandle): TTrackedRangeResult {
+ return resolveTrackedRange(this.protyle, handle);
+ }
+
+ public releaseTrackedRange(handle: ITrackedRangeHandle): void {
+ releaseTrackedRange(this.protyle, handle);
+ }
+
public hasClosestBlock(element: Node) {
return hasClosestBlock(element);
}
diff --git a/app/src/protyle/util/destroy.ts b/app/src/protyle/util/destroy.ts
index 72a9a34d9f..b60007aab5 100644
--- a/app/src/protyle/util/destroy.ts
+++ b/app/src/protyle/util/destroy.ts
@@ -5,11 +5,13 @@ import {cancelAssetUploads} from "../upload/pluginEvent";
import {unmountBreadcrumbButtons} from "../../plugin/breadcrumbButton";
import {forEachPluginSubscriber} from "../../plugin/EventBusCore";
import {unregisterCustomBlockRoot} from "../../plugin/customBlockRender";
+import {destroyTrackedRanges} from "./trackedRange";
export const destroy = (protyle: IProtyle) => {
if (!protyle) {
return;
}
+ destroyTrackedRanges(protyle);
cancelAssetUploads(protyle);
unmountBreadcrumbButtons(protyle);
hideElements(["util"], protyle, true);
diff --git a/app/src/protyle/util/onGet.ts b/app/src/protyle/util/onGet.ts
index d4d1ebad91..24076141b1 100644
--- a/app/src/protyle/util/onGet.ts
+++ b/app/src/protyle/util/onGet.ts
@@ -35,6 +35,7 @@ import {hasFocusOffsets} from "./focusRestore";
import {isIPhone} from "./compatibility";
import {forEachPluginSubscriber} from "../../plugin/EventBusCore";
import {disposeCustomBlocksInElement, setCustomBlockRootReady} from "../../plugin/customBlockRender";
+import {invalidateTrackedRanges, invalidateTrackedRangesInElement} from "./trackedRange";
/// #if MOBILE
import {updateMobileTitleReadonly} from "./setEditMode";
/// #endif
@@ -66,6 +67,7 @@ export const onGet = (options: {
if (options.data.code === 1) {
// 其他报错
if (!options.action.includes(Constants.CB_GET_APPEND)) { // 向下加载时块可能还没有创建 https://github.com/siyuan-note/siyuan/issues/10851
+ invalidateTrackedRanges(options.protyle);
if (options.protyle.model) {
options.protyle.model.parent.parent.removeTab(options.protyle.model.parent.id);
} else {
@@ -76,8 +78,13 @@ export const onGet = (options: {
}
if (options.data.code === 3) {
// block not found
+ invalidateTrackedRanges(options.protyle);
return;
}
+ if (!options.action.includes(Constants.CB_GET_APPEND) &&
+ !options.action.includes(Constants.CB_GET_BEFORE)) {
+ invalidateTrackedRanges(options.protyle);
+ }
options.protyle.notebookId = options.data.data.box;
options.protyle.path = options.data.data.path;
@@ -267,6 +274,7 @@ const setHTML = (options: {
}
const lastRemoveTop = removeElement.getBoundingClientRect().top;
removeElements.forEach(item => {
+ invalidateTrackedRangesInElement(protyle, item);
disposeCustomBlocksInElement(item);
item.remove();
});
@@ -295,12 +303,14 @@ const setHTML = (options: {
scrollHeight -= lastElement.clientHeight + 8; // 大部分元素的 margin
}
removeElements.forEach((item) => {
+ invalidateTrackedRangesInElement(protyle, item);
disposeCustomBlocksInElement(item);
item.remove();
});
hideElements(["toolbar"], protyle);
}
} else {
+ invalidateTrackedRanges(protyle);
disposeCustomBlocksInElement(protyle.wysiwyg.element);
protyle.wysiwyg.element.innerHTML = options.content;
// 设置 innerHTML 会导致浏览器将 scrollTop 重置为 0,此处立即恢复以避免页面跳转到开头
diff --git a/app/src/protyle/util/reload.ts b/app/src/protyle/util/reload.ts
index 872f465d57..823e936135 100644
--- a/app/src/protyle/util/reload.ts
+++ b/app/src/protyle/util/reload.ts
@@ -9,8 +9,10 @@ import {isSupportCSSHL, searchMarkRender} from "../render/searchMarkRender";
import {hideKeyboardToolbar} from "../../mobile/util/keyboardToolbar";
/// #endif
import {restoreLuteMarkdownSyntax} from "./paste";
+import {invalidateTrackedRanges} from "./trackedRange";
export const reloadProtyle = (protyle: IProtyle, focus: boolean, updateReadonly?: boolean) => {
+ invalidateTrackedRanges(protyle);
/// #if MOBILE
hideKeyboardToolbar();
/// #endif
diff --git a/app/src/protyle/util/trackedRange.test.ts b/app/src/protyle/util/trackedRange.test.ts
new file mode 100644
index 0000000000..d5029cc416
--- /dev/null
+++ b/app/src/protyle/util/trackedRange.test.ts
@@ -0,0 +1,233 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {
+ hasOverlappingTrackedTokenContext,
+ hasTrackedTokenRangeAffinityChoice,
+ mapTrackedTokenRange,
+} from "./trackedRangeAnchor";
+
+describe("tracked range token mapping", () => {
+ it("keeps a collapsed before-affinity anchor ahead of inserted tokens", () => {
+ assert.deepEqual(mapTrackedTokenRange(
+ ["a", "b", "c", "d"],
+ ["a", "b", "inserted", "c", "d"],
+ {start: 2, end: 2},
+ true,
+ "before",
+ ), {start: 2, end: 2});
+ });
+
+ it("moves an after-affinity anchor behind inserted tokens", () => {
+ assert.deepEqual(mapTrackedTokenRange(
+ ["a", "b", "c", "d"],
+ ["a", "b", "inserted", "c", "d"],
+ {start: 2, end: 2},
+ true,
+ "after",
+ ), {start: 3, end: 3});
+ });
+
+ it("detects when an insertion at a collapsed anchor requires affinity", () => {
+ assert.equal(hasTrackedTokenRangeAffinityChoice(
+ ["a", "b", "c"],
+ ["a", "b", "inserted", "c"],
+ 2,
+ ), true);
+ });
+
+ it("does not require affinity for edits away from a collapsed anchor", () => {
+ assert.equal(hasTrackedTokenRangeAffinityChoice(
+ ["old", "a", "b"],
+ ["new", "a", "b"],
+ 2,
+ ), false);
+ });
+
+ it("rejects overlapping prefix and suffix interpretations without edit evidence", () => {
+ assert.equal(hasOverlappingTrackedTokenContext(["a", "a"], ["a", "b", "a", "a"]), true);
+ assert.equal(mapTrackedTokenRange(
+ ["a", "a"],
+ ["a", "b", "a", "a"],
+ {start: 0, end: 0},
+ true,
+ "after",
+ ), undefined);
+ assert.equal(mapTrackedTokenRange(
+ ["c", "b", "a"],
+ ["c", "b", "b", "a"],
+ {start: 1, end: 1},
+ true,
+ "after",
+ ), undefined);
+ });
+
+ it("does not redirect an anchor to an identical sibling inserted before its source", () => {
+ assert.equal(mapTrackedTokenRange(
+ ["editable-boundary", "text:a"],
+ ["editable-boundary", "text:a", "editable-boundary", "text:a"],
+ {start: 2, end: 2},
+ true,
+ "before",
+ ), undefined);
+ });
+
+ it("applies affinity to overlapping context when the edit position is known", () => {
+ assert.deepEqual(mapTrackedTokenRange(
+ ["c", "b", "a"],
+ ["c", "b", "b", "a"],
+ {start: 1, end: 1},
+ true,
+ "after",
+ true,
+ ), {start: 2, end: 2});
+ assert.deepEqual(mapTrackedTokenRange(
+ ["same", "same"],
+ ["same", "same", "same"],
+ {start: 1, end: 1},
+ true,
+ "after",
+ true,
+ ), {start: 2, end: 2});
+ });
+
+ it("maps a collapsed anchor when content immediately before it is deleted", () => {
+ assert.deepEqual(mapTrackedTokenRange(
+ ["a", "b", "c"],
+ ["a", "c"],
+ {start: 2, end: 2},
+ true,
+ "before",
+ ), {start: 1, end: 1});
+ });
+
+ it("maps a collapsed anchor when content immediately after it is deleted", () => {
+ assert.deepEqual(mapTrackedTokenRange(
+ ["a", "b", "c"],
+ ["a", "b"],
+ {start: 2, end: 2},
+ true,
+ "after",
+ ), {start: 2, end: 2});
+ });
+
+ it("keeps boundary insertions outside a protected target", () => {
+ assert.deepEqual(mapTrackedTokenRange(
+ ["a", "target", "c"],
+ ["a", "inserted", "target", "c"],
+ {start: 1, end: 2},
+ false,
+ "before",
+ ), {start: 2, end: 3});
+ assert.deepEqual(mapTrackedTokenRange(
+ ["a", "target", "c"],
+ ["a", "target", "inserted", "c"],
+ {start: 1, end: 2},
+ false,
+ "before",
+ ), {start: 1, end: 2});
+ });
+
+ it("invalidates a protected target modified internally", () => {
+ assert.equal(mapTrackedTokenRange(
+ ["a", "target-1", "target-2", "c"],
+ ["a", "target-1", "inserted", "target-2", "c"],
+ {start: 1, end: 3},
+ false,
+ "before",
+ ), undefined);
+ });
+
+ it("does not redirect a deleted target to an identical copy", () => {
+ assert.equal(mapTrackedTokenRange(
+ ["left", "target", "middle", "target", "right"],
+ ["left", "middle", "target", "right"],
+ {start: 1, end: 2},
+ false,
+ "before",
+ ), undefined);
+ });
+
+ it("does not treat a shifted duplicate as a stable prefix", () => {
+ assert.equal(mapTrackedTokenRange(
+ ["same", "same"],
+ ["same", "placeholder"],
+ {start: 0, end: 1},
+ false,
+ "before",
+ ), undefined);
+ assert.equal(mapTrackedTokenRange(
+ ["same", "editable-boundary", "same"],
+ ["same"],
+ {start: 0, end: 1},
+ false,
+ "before",
+ ), undefined);
+ });
+
+ it("distinguishes duplicate targets by their semantic context", () => {
+ assert.deepEqual(mapTrackedTokenRange(
+ ["left-a", "same", "right-a", "left-b", "same", "right-b"],
+ ["inserted", "left-a", "same", "right-a", "left-b", "same", "right-b"],
+ {start: 1, end: 2},
+ false,
+ "before",
+ ), {start: 2, end: 3});
+ });
+
+ it("rejects a duplicate that can impersonate a deleted target", () => {
+ assert.equal(mapTrackedTokenRange(
+ ["a", "target", "between", "target", "c"],
+ ["a", "target", "c"],
+ {start: 1, end: 2},
+ false,
+ "before",
+ ), undefined);
+ });
+
+ it("invalidates indistinguishable repeated content", () => {
+ assert.equal(mapTrackedTokenRange(
+ ["same", "same", "same"],
+ ["same", "same", "same", "same"],
+ {start: 1, end: 2},
+ false,
+ "before",
+ ), undefined);
+ });
+
+ it("maps content across an inserted block boundary", () => {
+ assert.deepEqual(mapTrackedTokenRange(
+ ["a", "b", "c", "d"],
+ ["a", "b", "editable-boundary", "c", "d"],
+ {start: 2, end: 4},
+ false,
+ "before",
+ ), {start: 3, end: 5});
+ assert.equal(mapTrackedTokenRange(
+ ["a", "b", "c", "d"],
+ ["a", "b", "editable-boundary", "c", "d"],
+ {start: 1, end: 3},
+ false,
+ "before",
+ ), undefined);
+ });
+
+ it("rejects affinity when a repeated collapsed anchor is ambiguous", () => {
+ assert.equal(mapTrackedTokenRange(
+ ["same", "same"],
+ ["same", "same", "same"],
+ {start: 1, end: 1},
+ true,
+ "after",
+ ), undefined);
+ });
+
+ it("runs in linear time for long repeated input", () => {
+ const before = Array.from({length: 100_000}, () => "same");
+ const after = before.concat("same");
+ const started = performance.now();
+ const result = mapTrackedTokenRange(before, after, {start: 50_000, end: 50_001}, false, "before");
+
+ assert.equal(result, undefined);
+ assert.ok(performance.now() - started < 2_000);
+ });
+});
diff --git a/app/src/protyle/util/trackedRange.ts b/app/src/protyle/util/trackedRange.ts
new file mode 100644
index 0000000000..df2e21939f
--- /dev/null
+++ b/app/src/protyle/util/trackedRange.ts
@@ -0,0 +1,1353 @@
+import type {Plugin} from "../../plugin";
+import {getContenteditableElement} from "../wysiwyg/getBlock";
+import {hasClosestBlock, isInEmbedBlock} from "./hasClosest";
+import {
+ getTrackedTokenBoundaryCandidates,
+ hasOverlappingTrackedTokenContext,
+ type ITrackedTokenRange,
+ mapTrackedTokenRange,
+} from "./trackedRangeAnchor";
+
+const EDITABLE_BOUNDARY_TOKEN = "editable-boundary";
+
+interface IBoundaryPoint {
+ node: Node;
+ offset: number;
+ depth: number;
+}
+
+interface IBoundaryPoints {
+ before: IBoundaryPoint;
+ after: IBoundaryPoint;
+}
+
+interface IEditableSnapshot {
+ block: HTMLElement;
+ editable: Element;
+ tokens: string[];
+ points: Array<IBoundaryPoints | undefined>;
+ pointIndexes: Map<Node, Map<number, number>>;
+ globalStart: number;
+}
+
+interface IRootStream {
+ roots: HTMLElement[];
+ snapshots: IEditableSnapshot[];
+ tokens: string[];
+}
+
+interface IRangeSnapshot {
+ stream: IRootStream;
+ snapshot: IEditableSnapshot;
+ start: number;
+ end: number;
+}
+
+interface ITrackedRangeState {
+ range: Range;
+ startContainer: Node;
+ endContainer: Node;
+ exactTarget?: Element;
+ collapsed: boolean;
+ affinity: "before" | "after";
+ targetTokens: string[];
+ tokens: string[];
+ start: number;
+ end: number;
+ sourceBlockID: string;
+ sourceAncestorIDs: string[];
+ rootIDs: string[];
+ rootBlockIDs: Set<string>;
+ syncedBlockIDs: Set<string>;
+ sourceLineageIDs: Set<string>;
+ sourceTransitions: Map<string, Set<string>>;
+ lineageIDs: Set<string>;
+ knownBlockIDs: Set<string>;
+ owner?: Plugin;
+ invalid: boolean;
+ pendingInsertion?: ITrackedRangeInsertion;
+ editEvidence: Set<IEditEvidence>;
+ provisionalInput?: IProvisionalInputIntent;
+}
+
+interface IEditEvidence {
+ includeAdjacentRoots: boolean;
+ applyAffinity: boolean;
+ trustLiveRange: boolean;
+ insertion?: ITrackedRangeInsertion;
+}
+
+interface IProvisionalInputIntent extends IEditEvidence {
+ editable: Element;
+ inputType: string;
+ invalidate: boolean;
+}
+
+export interface ITrackedRangeInsertion {
+ readonly id: object;
+}
+
+interface ITrackedRangeInsertionData {
+ protyle: IProtyle;
+ states: ITrackedRangeState[];
+ evidence: IEditEvidence;
+ active: boolean;
+}
+
+interface IOwnedHandle {
+ protyle: IProtyle;
+ handle: ITrackedRangeHandle;
+}
+
+interface IInputListeners {
+ element: HTMLElement;
+ beforeInputListener: (event: InputEvent) => void;
+ inputListener: (event: InputEvent) => void;
+}
+
+const trackedRanges = new WeakMap<IProtyle, Map<ITrackedRangeHandle, ITrackedRangeState>>();
+const ownedHandles = new WeakMap<Plugin, Set<IOwnedHandle>>();
+const unloadingPlugins = new WeakSet<Plugin>();
+const destroyedProtyles = new WeakSet<IProtyle>();
+const inputListeners = new WeakMap<IProtyle, IInputListeners>();
+const trackedRangeInsertions = new WeakMap<ITrackedRangeInsertion, ITrackedRangeInsertionData>();
+let handleSequence = 0;
+
+const IGNORED_ATTRIBUTES = new Set([
+ "aria-hidden",
+ "aria-label",
+ "class",
+ "contenteditable",
+ "data-editing",
+ "data-node-id",
+ "data-position",
+ "data-render",
+ "draggable",
+ "spellcheck",
+ "updated",
+]);
+
+const isTransientElement = (element: Element) => {
+ return element.tagName === "WBR" || element.classList.contains("protyle-action") ||
+ element.classList.contains("protyle-action__drag") ||
+ element.classList.contains("protyle-action__title");
+};
+
+const getElementSignature = (element: Element) => {
+ const attributes = Array.from(element.attributes)
+ .filter(attribute => !IGNORED_ATTRIBUTES.has(attribute.name) && !attribute.name.startsWith("aria-"))
+ .filter(attribute => !(attribute.name === "src" && element.hasAttribute("data-src")))
+ .filter(attribute => !(attribute.name === "href" && element.hasAttribute("data-href")))
+ .sort((first, second) => first.name.localeCompare(second.name))
+ .map(attribute => `${attribute.name}=${JSON.stringify(attribute.value)}`)
+ .join(";");
+ return `${element.tagName.toLowerCase()}[${attributes}]`;
+};
+
+const getAtomicSignature = (element: Element): string => {
+ const values = [`<${getElementSignature(element)}>`];
+ Array.from(element.childNodes).forEach(child => {
+ if (child.nodeType === Node.TEXT_NODE) {
+ const text = child.textContent?.split("\u200B").join("") || "";
+ if (text) {
+ values.push(JSON.stringify(text));
+ }
+ } else if (child.nodeType === Node.ELEMENT_NODE && !isTransientElement(child as Element)) {
+ values.push(getAtomicSignature(child as Element));
+ }
+ });
+ values.push(`</${element.tagName.toLowerCase()}>`);
+ return values.join("");
+};
+
+const isAtomicElement = (element: Element) => {
+ return element.tagName === "BR" || element.tagName === "IMG" || element.getAttribute("contenteditable") === "false";
+};
+
+const setBoundaryPoint = (snapshot: IEditableSnapshot, node: Node, offset: number, depth: number) => {
+ let indexes = snapshot.pointIndexes.get(node);
+ if (!indexes) {
+ indexes = new Map<number, number>();
+ snapshot.pointIndexes.set(node, indexes);
+ }
+ indexes.set(offset, snapshot.tokens.length);
+ const point = {node, offset, depth};
+ const current = snapshot.points[snapshot.tokens.length];
+ if (!current || depth < current.before.depth) {
+ snapshot.points[snapshot.tokens.length] = {before: point, after: point};
+ } else if (depth === current.before.depth) {
+ current.after = point;
+ }
+};
+
+const tokenizeNode = (snapshot: IEditableSnapshot, node: Node, depth: number) => {
+ if (node.nodeType === Node.TEXT_NODE) {
+ const text = node.textContent || "";
+ let offset = 0;
+ setBoundaryPoint(snapshot, node, offset, depth);
+ Array.from(text).forEach(character => {
+ const nextOffset = offset + character.length;
+ if (character !== "\u200B") {
+ snapshot.tokens.push(`text:${character}`);
+ }
+ offset = nextOffset;
+ setBoundaryPoint(snapshot, node, offset, depth);
+ });
+ return;
+ }
+ if (node.nodeType !== Node.ELEMENT_NODE) {
+ return;
+ }
+ const element = node as Element;
+ if (isTransientElement(element)) {
+ return;
+ }
+ if (isAtomicElement(element)) {
+ snapshot.tokens.push(`atomic:${getAtomicSignature(element)}`);
+ return;
+ }
+ snapshot.tokens.push(`open:${getElementSignature(element)}`);
+ setBoundaryPoint(snapshot, element, 0, depth);
+ Array.from(element.childNodes).forEach((child, index) => {
+ setBoundaryPoint(snapshot, element, index, depth);
+ tokenizeNode(snapshot, child, depth + 1);
+ setBoundaryPoint(snapshot, element, index + 1, depth);
+ });
+ snapshot.tokens.push(`close:${element.tagName.toLowerCase()}`);
+};
+
+const createEditableSnapshot = (block: HTMLElement, editable: Element): IEditableSnapshot => {
+ const snapshot: IEditableSnapshot = {
+ block,
+ editable,
+ tokens: [],
+ points: [],
+ pointIndexes: new Map(),
+ globalStart: 0,
+ };
+ setBoundaryPoint(snapshot, editable, 0, 0);
+ Array.from(editable.childNodes).forEach((child, index) => {
+ setBoundaryPoint(snapshot, editable, index, 0);
+ tokenizeNode(snapshot, child, 1);
+ setBoundaryPoint(snapshot, editable, index + 1, 0);
+ });
+ return snapshot;
+};
+
+const compareElements = (first: Element, second: Element) => {
+ if (first === second) {
+ return 0;
+ }
+ return first.compareDocumentPosition(second) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1;
+};
+
+const sortElements = <T extends Element>(elements: T[]) => {
+ return elements.sort(compareElements);
+};
+
+const getAncestorBlockIDs = (editorElement: Element, block: Element) => {
+ const ids: string[] = [];
+ let current: Element | null = block;
+ while (current && current !== editorElement) {
+ const id = current.getAttribute("data-node-id");
+ if (id) {
+ ids.push(id);
+ }
+ current = current.parentElement;
+ }
+ return ids;
+};
+
+const getTopLevelBlock = (editorElement: Element, block: Element) => {
+ let root = block as HTMLElement;
+ let current = block.parentElement;
+ while (current && current !== editorElement) {
+ if (current.hasAttribute("data-node-id")) {
+ root = current;
+ }
+ current = current.parentElement;
+ }
+ return root;
+};
+
+const getEditableSnapshots = (roots: HTMLElement[]) => {
+ const snapshots: IEditableSnapshot[] = [];
+ const seen = new Set<Element>();
+ roots.forEach(root => {
+ const blocks = [root, ...Array.from(root.querySelectorAll<HTMLElement>("[data-node-id]"))];
+ blocks.forEach(block => {
+ if (isInEmbedBlock(block, false)) {
+ return;
+ }
+ const editable = getContenteditableElement(block);
+ if (editable && hasClosestBlock(editable) === block && !seen.has(editable)) {
+ seen.add(editable);
+ snapshots.push(createEditableSnapshot(block, editable));
+ }
+ block.querySelectorAll<HTMLElement>(".callout-title").forEach(title => {
+ if (hasClosestBlock(title) === block && !seen.has(title)) {
+ seen.add(title);
+ snapshots.push(createEditableSnapshot(block, title));
+ }
+ });
+ });
+ });
+ return snapshots.sort((first, second) => compareElements(first.editable, second.editable));
+};
+
+const createRootStream = (roots: HTMLElement[]): IRootStream => {
+ roots = sortElements(Array.from(new Set(roots)));
+ const snapshots = getEditableSnapshots(roots);
+ const tokens: string[] = [];
+ snapshots.forEach((snapshot, index) => {
+ if (index > 0) {
+ tokens.push(EDITABLE_BOUNDARY_TOKEN);
+ }
+ snapshot.globalStart = tokens.length;
+ tokens.push(...snapshot.tokens);
+ });
+ return {roots, snapshots, tokens};
+};
+
+const getRootBlockIDs = (roots: HTMLElement[]) => {
+ const ids = new Set<string>();
+ roots.forEach(root => {
+ const blocks = [root, ...Array.from(root.querySelectorAll<HTMLElement>("[data-node-id]"))];
+ blocks.forEach(block => {
+ if (isInEmbedBlock(block, false)) {
+ return;
+ }
+ const id = block.getAttribute("data-node-id");
+ if (id) {
+ ids.add(id);
+ }
+ });
+ });
+ return ids;
+};
+
+const getRangeSnapshot = (protyle: IProtyle, range: Range): IRangeSnapshot | undefined => {
+ const editorElement = protyle.wysiwyg?.element;
+ if (!editorElement || !editorElement.contains(range.startContainer) || !editorElement.contains(range.endContainer)) {
+ return;
+ }
+ const startBlock = hasClosestBlock(range.startContainer);
+ const endBlock = hasClosestBlock(range.endContainer);
+ if (!startBlock || startBlock !== endBlock || isInEmbedBlock(startBlock, false) || protyle.options.backlinkData) {
+ return;
+ }
+ const startEditable = getContenteditableElement(startBlock, range.startContainer);
+ const endEditable = getContenteditableElement(endBlock, range.endContainer);
+ if (!startEditable || startEditable !== endEditable || !startEditable.contains(range.startContainer) ||
+ !startEditable.contains(range.endContainer)) {
+ return;
+ }
+ const root = getTopLevelBlock(editorElement, startBlock);
+ const stream = createRootStream([root]);
+ const snapshot = stream.snapshots.find(item => item.editable === startEditable);
+ if (!snapshot) {
+ return;
+ }
+ const localStart = snapshot.pointIndexes.get(range.startContainer)?.get(range.startOffset);
+ const localEnd = snapshot.pointIndexes.get(range.endContainer)?.get(range.endOffset);
+ if (typeof localStart !== "number" || typeof localEnd !== "number") {
+ return;
+ }
+ return {
+ stream,
+ snapshot,
+ start: snapshot.globalStart + localStart,
+ end: snapshot.globalStart + localEnd,
+ };
+};
+
+const getRangeSnapshotFromStream = (stream: IRootStream, range: Range): IRangeSnapshot | undefined => {
+ const snapshot = stream.snapshots.find(item => item.editable.contains(range.startContainer) &&
+ item.editable.contains(range.endContainer));
+ if (!snapshot) {
+ return;
+ }
+ const localStart = snapshot.pointIndexes.get(range.startContainer)?.get(range.startOffset);
+ const localEnd = snapshot.pointIndexes.get(range.endContainer)?.get(range.endOffset);
+ if (typeof localStart !== "number" || typeof localEnd !== "number") {
+ return;
+ }
+ return {
+ stream,
+ snapshot,
+ start: snapshot.globalStart + localStart,
+ end: snapshot.globalStart + localEnd,
+ };
+};
+
+const getExactlySelectedElement = (range: Range) => {
+ if (range.startContainer !== range.endContainer || range.startContainer.nodeType !== Node.ELEMENT_NODE ||
+ range.endOffset !== range.startOffset + 1) {
+ return;
+ }
+ const target = range.startContainer.childNodes[range.startOffset];
+ return target?.nodeType === Node.ELEMENT_NODE ? target as Element : undefined;
+};
+
+const getBoundaryPoint = (stream: IRootStream, index: number, affinity: "before" | "after") => {
+ const matches = stream.snapshots.filter(snapshot => index >= snapshot.globalStart &&
+ index <= snapshot.globalStart + snapshot.tokens.length);
+ if (matches.length === 0) {
+ return;
+ }
+ const snapshot = affinity === "before" ? matches[0] : matches[matches.length - 1];
+ return snapshot.points[index - snapshot.globalStart]?.[affinity];
+};
+
+const createRangeFromStream = (stream: IRootStream, start: number, end: number,
+ affinity: "before" | "after") => {
+ const startPoint = getBoundaryPoint(stream, start, start === end ? affinity : "after");
+ const endPoint = getBoundaryPoint(stream, end, start === end ? affinity : "before");
+ if (!startPoint || !endPoint) {
+ return;
+ }
+ const range = document.createRange();
+ try {
+ range.setStart(startPoint.node, startPoint.offset);
+ range.setEnd(endPoint.node, endPoint.offset);
+ } catch {
+ return;
+ }
+ return range;
+};
+
+const equalTokens = (first: string[], second: string[]) => {
+ return first.length === second.length && first.every((token, index) => token === second[index]);
+};
+
+const addSourceTransition = (state: ITrackedRangeState, first: string, second: string) => {
+ if (!first || !second || first === second) {
+ return;
+ }
+ [
+ {source: first, target: second},
+ {source: second, target: first},
+ ].forEach(edge => {
+ let targets = state.sourceTransitions.get(edge.source);
+ if (!targets) {
+ targets = new Set();
+ state.sourceTransitions.set(edge.source, targets);
+ }
+ targets.add(edge.target);
+ });
+};
+
+const updateState = (protyle: IProtyle, state: ITrackedRangeState, range: Range,
+ existingSnapshot?: IRangeSnapshot) => {
+ const rangeSnapshot = existingSnapshot || getRangeSnapshot(protyle, range);
+ if (!rangeSnapshot) {
+ return false;
+ }
+ const targetTokens = rangeSnapshot.stream.tokens.slice(rangeSnapshot.start, rangeSnapshot.end);
+ if (!state.collapsed && !equalTokens(state.targetTokens, targetTokens)) {
+ return false;
+ }
+ const trackedRange = range.cloneRange();
+ state.range = trackedRange;
+ state.startContainer = trackedRange.startContainer;
+ state.endContainer = trackedRange.endContainer;
+ state.exactTarget = getExactlySelectedElement(trackedRange);
+ state.tokens = rangeSnapshot.stream.tokens;
+ state.start = rangeSnapshot.start;
+ state.end = rangeSnapshot.end;
+ const previousSourceBlockID = state.sourceBlockID;
+ state.sourceBlockID = rangeSnapshot.snapshot.block.getAttribute("data-node-id") || "";
+ state.sourceAncestorIDs = getAncestorBlockIDs(protyle.wysiwyg.element, rangeSnapshot.snapshot.block);
+ state.rootIDs = rangeSnapshot.stream.roots.map(root => root.getAttribute("data-node-id") || "").filter(Boolean);
+ state.rootBlockIDs = getRootBlockIDs(rangeSnapshot.stream.roots);
+ addSourceTransition(state, previousSourceBlockID, state.sourceBlockID);
+ state.sourceLineageIDs.add(state.sourceBlockID);
+ [...state.sourceAncestorIDs, ...state.rootIDs].forEach(id => state.lineageIDs.add(id));
+ state.rootBlockIDs.forEach(id => state.knownBlockIDs.add(id));
+ return true;
+};
+
+const resolveExactTarget = (protyle: IProtyle, state: ITrackedRangeState) => {
+ if (!state.exactTarget?.isConnected) {
+ return;
+ }
+ if (!protyle.wysiwyg.element.contains(state.exactTarget)) {
+ state.invalid = true;
+ return;
+ }
+ const range = document.createRange();
+ range.selectNode(state.exactTarget);
+ if (!updateState(protyle, state, range)) {
+ state.invalid = true;
+ return;
+ }
+ return range;
+};
+
+const getLiveRange = (protyle: IProtyle, state: ITrackedRangeState, allowCollapsed = false) => {
+ const editorElement = protyle.wysiwyg.element;
+ if (!editorElement.contains(state.startContainer) || !editorElement.contains(state.endContainer) ||
+ !editorElement.contains(state.range.startContainer) || !editorElement.contains(state.range.endContainer) ||
+ state.range.collapsed !== state.collapsed || (state.collapsed && !allowCollapsed)) {
+ return;
+ }
+ return state.range.cloneRange();
+};
+
+const resolveLiveRange = (protyle: IProtyle, state: ITrackedRangeState, allowCollapsed = false) => {
+ const range = getLiveRange(protyle, state, allowCollapsed);
+ if (!range) {
+ return;
+ }
+ return updateState(protyle, state, range) ? range : undefined;
+};
+
+const getRootsForIDs = (editorElement: HTMLElement, ids: Set<string>) => {
+ const roots = new Set<HTMLElement>();
+ editorElement.querySelectorAll<HTMLElement>("[data-node-id]").forEach(block => {
+ if (ids.has(block.getAttribute("data-node-id") || "") && !isInEmbedBlock(block, false)) {
+ roots.add(getTopLevelBlock(editorElement, block));
+ }
+ });
+ return sortElements(Array.from(roots));
+};
+
+const addAdjacentUnknownRoots = (roots: HTMLElement[], state: ITrackedRangeState) => {
+ const expandedRoots = new Set(roots);
+ const addDirection = (root: HTMLElement, direction: "nextElementSibling" | "previousElementSibling") => {
+ let sibling = root[direction] as HTMLElement | null;
+ while (sibling?.hasAttribute("data-node-id")) {
+ const id = sibling.getAttribute("data-node-id") || "";
+ if (!id || state.knownBlockIDs.has(id)) {
+ break;
+ }
+ expandedRoots.add(sibling);
+ sibling = sibling[direction] as HTMLElement | null;
+ }
+ };
+ roots.forEach(root => {
+ addDirection(root, "previousElementSibling");
+ addDirection(root, "nextElementSibling");
+ });
+ return sortElements(Array.from(expandedRoots));
+};
+
+const getResolveStream = (protyle: IProtyle, state: ITrackedRangeState, includeAdjacentRoots: boolean) => {
+ const ids = new Set([...state.rootIDs, ...state.sourceAncestorIDs]);
+ let roots = getRootsForIDs(protyle.wysiwyg.element, ids);
+ if (roots.length === 0) {
+ return;
+ }
+ let stream = createRootStream(roots);
+ if (includeAdjacentRoots || !equalTokens(state.tokens, stream.tokens)) {
+ roots = addAdjacentUnknownRoots(roots, state);
+ stream = createRootStream(roots);
+ }
+ return stream;
+};
+
+const getProvisionalSourceIDs = (state: ITrackedRangeState, stream: IRootStream) => {
+ const currentBlockIDs = getRootBlockIDs(stream.roots);
+ return {
+ introduced: new Set(Array.from(currentBlockIDs).filter(id => !state.knownBlockIDs.has(id))),
+ restored: new Set(Array.from(currentBlockIDs).filter(id => state.sourceLineageIDs.has(id))),
+ };
+};
+
+const mapStateToStream = (protyle: IProtyle, state: ITrackedRangeState, stream: IRootStream,
+ introducedSourceIDs?: Set<string>, restoredSourceIDs?: Set<string>,
+ existingMappedRange?: ITrackedTokenRange) => {
+ const mapped = existingMappedRange || mapTrackedTokenRange(state.tokens, stream.tokens,
+ {start: state.start, end: state.end}, state.collapsed, state.affinity);
+ if (!mapped) {
+ return;
+ }
+ const range = createRangeFromStream(stream, mapped.start, mapped.end, state.affinity);
+ if (!range) {
+ return;
+ }
+ const snapshot = stream.snapshots.find(item => mapped.start >= item.globalStart &&
+ mapped.end <= item.globalStart + item.tokens.length && item.editable.contains(range.startContainer) &&
+ item.editable.contains(range.endContainer));
+ const sourceBlockID = snapshot?.block.getAttribute("data-node-id") || "";
+ if (!snapshot) {
+ return;
+ }
+ if (sourceBlockID !== state.sourceBlockID) {
+ const sourceStillExists = stream.snapshots.some(item =>
+ item.block.getAttribute("data-node-id") === state.sourceBlockID);
+ const isNewSplitSource = introducedSourceIDs?.has(sourceBlockID) &&
+ !state.syncedBlockIDs.has(sourceBlockID) && sourceStillExists;
+ const isRestoredSource = state.sourceTransitions.get(state.sourceBlockID)?.has(sourceBlockID) &&
+ restoredSourceIDs?.has(sourceBlockID) &&
+ (!sourceStillExists || !state.syncedBlockIDs.has(sourceBlockID));
+ if (!sourceBlockID || (!isNewSplitSource && !isRestoredSource)) {
+ return;
+ }
+ }
+ if (!updateState(protyle, state, range, {stream, snapshot, start: mapped.start, end: mapped.end})) {
+ return;
+ }
+ return range;
+};
+
+const resolveState = (protyle: IProtyle, state: ITrackedRangeState) => {
+ if (state.invalid || !protyle.wysiwyg?.element?.isConnected) {
+ return;
+ }
+ const exactRange = resolveExactTarget(protyle, state);
+ if (exactRange || state.invalid) {
+ return exactRange;
+ }
+ if (!state.collapsed) {
+ const liveRange = resolveLiveRange(protyle, state);
+ if (liveRange) {
+ return liveRange;
+ }
+ const stream = getResolveStream(protyle, state, false);
+ if (!stream) {
+ return;
+ }
+ const sourceIDs = getProvisionalSourceIDs(state, stream);
+ return mapStateToStream(protyle, state, stream, sourceIDs.introduced, sourceIDs.restored);
+ }
+ const hasAffinityEvidence = Array.from(state.editEvidence).some(evidence => evidence.applyAffinity);
+ const trustLiveRange = !hasAffinityEvidence &&
+ Array.from(state.editEvidence).some(evidence => evidence.trustLiveRange);
+ const includeAdjacentRoots = Array.from(state.editEvidence)
+ .some(evidence => evidence.includeAdjacentRoots);
+ const stream = getResolveStream(protyle, state, includeAdjacentRoots);
+ if (!stream) {
+ return;
+ }
+ if (equalTokens(state.tokens, stream.tokens)) {
+ const liveRange = getLiveRange(protyle, state, true);
+ const liveSnapshot = liveRange && getRangeSnapshotFromStream(stream, liveRange);
+ if (liveRange && liveSnapshot && updateState(protyle, state, liveRange, liveSnapshot)) {
+ Array.from(state.editEvidence).forEach(evidence => {
+ if (!evidence.insertion) {
+ state.editEvidence.delete(evidence);
+ }
+ });
+ return liveRange;
+ }
+ return mapStateToStream(protyle, state, stream);
+ }
+ if (state.editEvidence.size > 0) {
+ state.editEvidence.clear();
+ }
+ state.provisionalInput = undefined;
+ const mapped = mapTrackedTokenRange(state.tokens, stream.tokens, {start: state.start, end: state.end},
+ true, state.affinity, hasAffinityEvidence);
+ const liveRange = (!hasAffinityEvidence || trustLiveRange) && getLiveRange(protyle, state, true);
+ const liveSnapshot = liveRange && getRangeSnapshotFromStream(stream, liveRange);
+ const boundaryCandidates = getTrackedTokenBoundaryCandidates(state.tokens, stream.tokens, state.start);
+ const liveMatchesMapping = liveSnapshot && (trustLiveRange || (mapped ?
+ liveSnapshot.start === mapped.start && liveSnapshot.end === mapped.end :
+ hasOverlappingTrackedTokenContext(state.tokens, stream.tokens) &&
+ boundaryCandidates.length === 1 && boundaryCandidates.includes(liveSnapshot.start) &&
+ liveSnapshot.start === liveSnapshot.end));
+ if (liveRange && liveSnapshot && liveMatchesMapping && updateState(protyle, state, liveRange, liveSnapshot)) {
+ return liveRange;
+ }
+ const sourceIDs = getProvisionalSourceIDs(state, stream);
+ return mapStateToStream(protyle, state, stream, sourceIDs.introduced, sourceIDs.restored, mapped);
+};
+
+const getOperationIDs = (operation: IOperation) => {
+ return [
+ operation.id,
+ operation.blockID,
+ operation.parentID,
+ operation.previousID,
+ operation.nextID,
+ ...(operation.blockIDs || []),
+ ...(operation.srcIDs || []),
+ ].filter(Boolean) as string[];
+};
+
+const getOperationDataBlockIDs = (operation: IOperation) => {
+ const blockIDs: string[] = [];
+ if (typeof operation.data !== "string" || !operation.data.includes("data-node-id")) {
+ return blockIDs;
+ }
+ const template = document.createElement("template");
+ template.innerHTML = operation.data;
+ const firstElementID = template.content.firstElementChild?.getAttribute("data-node-id");
+ if (firstElementID) {
+ blockIDs.push(firstElementID);
+ }
+ template.content.querySelectorAll<HTMLElement>("[data-node-id]").forEach(block => {
+ const id = block.getAttribute("data-node-id");
+ if (id) {
+ blockIDs.push(id);
+ }
+ });
+ return blockIDs;
+};
+
+const rememberOperationReferences = (state: ITrackedRangeState, operations: IOperation[]) => {
+ operations.forEach(operation => {
+ if (!["insert", "move", "update"].includes(operation.action)) {
+ return;
+ }
+ [operation.id, operation.blockID, ...(operation.blockIDs || []), ...(operation.srcIDs || [])]
+ .filter(Boolean).forEach(id => state.knownBlockIDs.add(id));
+ });
+};
+
+const rememberOperationBlockIDs = (state: ITrackedRangeState, operations: IOperation[]) => {
+ rememberOperationReferences(state, operations);
+ operations.forEach(operation => {
+ if (["insert", "update"].includes(operation.action)) {
+ getOperationDataBlockIDs(operation).forEach(id => state.knownBlockIDs.add(id));
+ }
+ });
+};
+
+const getRelatedOperationIDs = (state: ITrackedRangeState, operations: IOperation[]) => {
+ const ids = new Set([state.sourceBlockID, ...state.sourceAncestorIDs, ...state.rootIDs, ...state.rootBlockIDs]);
+ const operationIDs = operations.map(getOperationIDs);
+ const operationIndexes = new Map<string, number[]>();
+ operationIDs.forEach((itemIDs, index) => {
+ itemIDs.forEach(id => {
+ let indexes = operationIndexes.get(id);
+ if (!indexes) {
+ indexes = [];
+ operationIndexes.set(id, indexes);
+ }
+ indexes.push(index);
+ });
+ });
+ const pendingIDs = Array.from(ids);
+ const visitedOperations = new Set<number>();
+ let related = false;
+ for (let pendingIndex = 0; pendingIndex < pendingIDs.length; pendingIndex++) {
+ operationIndexes.get(pendingIDs[pendingIndex])?.forEach(operationIndex => {
+ if (!visitedOperations.has(operationIndex)) {
+ visitedOperations.add(operationIndex);
+ related = true;
+ operationIDs[operationIndex].forEach(id => {
+ if (!ids.has(id)) {
+ ids.add(id);
+ pendingIDs.push(id);
+ }
+ });
+ }
+ });
+ }
+ if (!related) {
+ return;
+ }
+ state.lineageIDs.forEach(id => {
+ if (!ids.has(id) && operationIndexes.has(id)) {
+ ids.add(id);
+ pendingIDs.push(id);
+ }
+ });
+ for (let pendingIndex = 0; pendingIndex < pendingIDs.length; pendingIndex++) {
+ operationIndexes.get(pendingIDs[pendingIndex])?.forEach(operationIndex => {
+ if (!visitedOperations.has(operationIndex)) {
+ visitedOperations.add(operationIndex);
+ operationIDs[operationIndex].forEach(id => {
+ if (!ids.has(id)) {
+ ids.add(id);
+ pendingIDs.push(id);
+ }
+ });
+ }
+ });
+ }
+ return ids;
+};
+
+const getIntroducedBlockIDs = (state: ITrackedRangeState, operations: IOperation[], relatedIDs: Set<string>) => {
+ const ids = new Set<string>();
+ const lineageIDs = new Set([state.sourceBlockID, ...state.sourceAncestorIDs]);
+ const movedIDs = new Set<string>();
+ operations.forEach(operation => {
+ if (operation.action !== "move") {
+ return;
+ }
+ [operation.id, operation.blockID, ...(operation.blockIDs || []), ...(operation.srcIDs || [])]
+ .filter(Boolean).forEach(id => movedIDs.add(id));
+ });
+ const addID = (id?: string) => {
+ if (id && !state.knownBlockIDs.has(id) && !movedIDs.has(id)) {
+ ids.add(id);
+ }
+ };
+ operations.forEach(operation => {
+ if (operation.action !== "update" || !lineageIDs.has(operation.id) ||
+ !getOperationIDs(operation).some(id => relatedIDs.has(id))) {
+ return;
+ }
+ const dataBlockIDs = getOperationDataBlockIDs(operation);
+ if (!dataBlockIDs.includes(state.sourceBlockID)) {
+ return;
+ }
+ dataBlockIDs.forEach(addID);
+ });
+ const pending = operations.filter(operation => operation.action === "insert");
+ let added = true;
+ while (added) {
+ added = false;
+ for (let index = pending.length - 1; index >= 0; index--) {
+ const operation = pending[index];
+ if (![operation.parentID, operation.previousID, operation.nextID]
+ .some(id => id && (lineageIDs.has(id) || ids.has(id)))) {
+ continue;
+ }
+ const size = ids.size;
+ addID(operation.id);
+ getOperationDataBlockIDs(operation).forEach(addID);
+ if (ids.size > size) {
+ added = true;
+ }
+ pending.splice(index, 1);
+ }
+ }
+ return ids;
+};
+
+const getRestoredSourceIDs = (state: ITrackedRangeState, operations: IOperation[], relatedIDs: Set<string>) => {
+ const ids = new Set<string>();
+ const addLineageID = (id?: string) => {
+ if (id && state.sourceLineageIDs.has(id)) {
+ ids.add(id);
+ }
+ };
+ operations.forEach(operation => {
+ if (!getOperationIDs(operation).some(id => relatedIDs.has(id))) {
+ return;
+ }
+ if (["insert", "update", "move"].includes(operation.action)) {
+ addLineageID(operation.id);
+ addLineageID(operation.blockID);
+ operation.blockIDs?.forEach(addLineageID);
+ operation.srcIDs?.forEach(addLineageID);
+ }
+ if (!["insert", "update"].includes(operation.action) || typeof operation.data !== "string" ||
+ !operation.data.includes("data-node-id")) {
+ return;
+ }
+ const template = document.createElement("template");
+ template.innerHTML = operation.data;
+ addLineageID(template.content.firstElementChild?.getAttribute("data-node-id"));
+ template.content.querySelectorAll<HTMLElement>("[data-node-id]").forEach(block => {
+ addLineageID(block.getAttribute("data-node-id"));
+ });
+ });
+ return ids;
+};
+
+const getManager = (protyle: IProtyle) => {
+ let manager = trackedRanges.get(protyle);
+ if (!manager) {
+ manager = new Map();
+ trackedRanges.set(protyle, manager);
+ }
+ return manager;
+};
+
+const comparePoints = (firstNode: Node, firstOffset: number, secondNode: Node, secondOffset: number) => {
+ const first = document.createRange();
+ const second = document.createRange();
+ try {
+ first.setStart(firstNode, firstOffset);
+ first.collapse(true);
+ second.setStart(secondNode, secondOffset);
+ second.collapse(true);
+ return first.compareBoundaryPoints(Range.START_TO_START, second);
+ } catch {
+ return;
+ }
+};
+
+const rememberAdjacentRootIDs = (protyle: IProtyle, state: ITrackedRangeState) => {
+ const ids = new Set([...state.rootIDs, ...state.sourceAncestorIDs]);
+ getRootsForIDs(protyle.wysiwyg.element, ids).forEach(root => {
+ [root.previousElementSibling, root.nextElementSibling].forEach(sibling => {
+ const id = sibling?.getAttribute("data-node-id");
+ if (id) {
+ state.knownBlockIDs.add(id);
+ }
+ });
+ });
+};
+
+export const prepareTrackedRangeInsertion = (protyle: IProtyle, range: Range) => {
+ const insertion = Object.freeze({id: {}});
+ const states: ITrackedRangeState[] = [];
+ if (range.collapsed) {
+ trackedRanges.get(protyle)?.forEach(state => {
+ if (!state.invalid && !state.pendingInsertion && state.collapsed &&
+ comparePoints(range.startContainer, range.startOffset,
+ state.range.startContainer, state.range.startOffset) === 0) {
+ state.pendingInsertion = insertion;
+ states.push(state);
+ }
+ });
+ }
+ const evidence: IEditEvidence = {
+ includeAdjacentRoots: true,
+ applyAffinity: true,
+ trustLiveRange: false,
+ insertion,
+ };
+ trackedRangeInsertions.set(insertion, {protyle, states, evidence, active: false});
+ return insertion;
+};
+
+export const activateTrackedRangeInsertion = (insertion?: ITrackedRangeInsertion) => {
+ const data = insertion && trackedRangeInsertions.get(insertion);
+ if (!data || data.active) {
+ return;
+ }
+ data.active = true;
+ data.states.forEach(state => {
+ rememberAdjacentRootIDs(data.protyle, state);
+ state.editEvidence.add(data.evidence);
+ });
+};
+
+export const setTrackedRangeInsertionResult = (insertion: ITrackedRangeInsertion | undefined,
+ beforeRange: Range, afterRange: Range) => {
+ const data = insertion && trackedRangeInsertions.get(insertion);
+ if (!data?.active) {
+ return;
+ }
+ data.states.forEach(state => {
+ if (!state.invalid && !updateState(data.protyle, state,
+ state.affinity === "before" ? beforeRange : afterRange)) {
+ state.invalid = true;
+ }
+ });
+};
+
+export const endTrackedRangeInsertion = (insertion: ITrackedRangeInsertion) => {
+ const data = trackedRangeInsertions.get(insertion);
+ if (!data) {
+ return;
+ }
+ data.states.forEach(state => {
+ state.editEvidence.delete(data.evidence);
+ if (state.pendingInsertion === insertion) {
+ state.pendingInsertion = undefined;
+ }
+ });
+ trackedRangeInsertions.delete(insertion);
+};
+
+const editTouchesTrackedRange = (editRange: Range, trackedRange: Range) => {
+ if (trackedRange.collapsed) {
+ if (editRange.collapsed) {
+ return false;
+ }
+ const afterStart = comparePoints(editRange.startContainer, editRange.startOffset,
+ trackedRange.startContainer, trackedRange.startOffset);
+ const beforeEnd = comparePoints(editRange.endContainer, editRange.endOffset,
+ trackedRange.startContainer, trackedRange.startOffset);
+ return typeof afterStart === "number" && typeof beforeEnd === "number" && afterStart < 0 && beforeEnd > 0;
+ }
+ if (editRange.collapsed) {
+ const afterStart = comparePoints(trackedRange.startContainer, trackedRange.startOffset,
+ editRange.startContainer, editRange.startOffset);
+ const beforeEnd = comparePoints(trackedRange.endContainer, trackedRange.endOffset,
+ editRange.startContainer, editRange.startOffset);
+ return typeof afterStart === "number" && typeof beforeEnd === "number" && afterStart < 0 && beforeEnd > 0;
+ }
+ const startsBeforeTrackedEnd = comparePoints(editRange.startContainer, editRange.startOffset,
+ trackedRange.endContainer, trackedRange.endOffset);
+ const endsAfterTrackedStart = comparePoints(editRange.endContainer, editRange.endOffset,
+ trackedRange.startContainer, trackedRange.startOffset);
+ return typeof startsBeforeTrackedEnd === "number" && typeof endsAfterTrackedStart === "number" &&
+ startsBeforeTrackedEnd < 0 && endsAfterTrackedStart > 0;
+};
+
+const isInsertionAtTrackedRange = (event: InputEvent, editRange: Range, trackedRange: Range) => {
+ return trackedRange.collapsed && editRange.collapsed && event.inputType.startsWith("insert") &&
+ comparePoints(editRange.startContainer, editRange.startOffset,
+ trackedRange.startContainer, trackedRange.startOffset) === 0;
+};
+
+const getInputEditable = (protyle: IProtyle, target: EventTarget | null) => {
+ const targetNode = target as Node | null;
+ const targetElement = targetNode?.nodeType === Node.ELEMENT_NODE ? targetNode as Element : targetNode?.parentElement;
+ if (!targetNode || !protyle.wysiwyg.element.contains(targetNode) ||
+ targetElement?.closest("input, select, textarea, [contenteditable=\"false\"]")) {
+ return;
+ }
+ const targetBlock = hasClosestBlock(targetNode);
+ const targetEditable = targetBlock && getContenteditableElement(targetBlock, targetNode);
+ if (!targetEditable || !targetEditable.contains(targetNode)) {
+ return;
+ }
+ return targetEditable;
+};
+
+const getBeforeInputRanges = (event: InputEvent, targetEditable: Element) => {
+ const ranges: Range[] = [];
+ try {
+ event.getTargetRanges().forEach(targetRange => {
+ if (!targetEditable.contains(targetRange.startContainer) ||
+ !targetEditable.contains(targetRange.endContainer)) {
+ return;
+ }
+ const range = document.createRange();
+ range.setStart(targetRange.startContainer, targetRange.startOffset);
+ range.setEnd(targetRange.endContainer, targetRange.endOffset);
+ ranges.push(range);
+ });
+ } catch {
+ // 部分输入法不提供目标范围,下面使用当前选区兜底。
+ }
+ if (ranges.length === 0) {
+ const selection = document.getSelection();
+ if (selection?.rangeCount) {
+ const range = selection.getRangeAt(0);
+ if (targetEditable.contains(range.startContainer) && targetEditable.contains(range.endContainer)) {
+ ranges.push(range.cloneRange());
+ }
+ }
+ }
+ return ranges;
+};
+
+const ensureInputListeners = (protyle: IProtyle) => {
+ if (inputListeners.has(protyle)) {
+ return;
+ }
+ const element = protyle.wysiwyg.element;
+ const beforeInputListener = (event: InputEvent) => {
+ if (event.defaultPrevented || ["historyRedo", "historyUndo"].includes(event.inputType)) {
+ return;
+ }
+ const editable = getInputEditable(protyle, event.target);
+ if (!editable) {
+ return;
+ }
+ const ranges = getBeforeInputRanges(event, editable);
+ if (ranges.length === 0) {
+ return;
+ }
+ trackedRanges.get(protyle)?.forEach(state => {
+ let intent: IProvisionalInputIntent | undefined;
+ if (ranges.some(range => editTouchesTrackedRange(range, state.range))) {
+ intent = {
+ editable,
+ inputType: event.inputType,
+ includeAdjacentRoots: false,
+ applyAffinity: false,
+ trustLiveRange: false,
+ invalidate: true,
+ };
+ } else if (ranges.some(range => isInsertionAtTrackedRange(event, range, state.range))) {
+ rememberAdjacentRootIDs(protyle, state);
+ intent = {
+ editable,
+ inputType: event.inputType,
+ includeAdjacentRoots: ["insertLineBreak", "insertParagraph"].includes(event.inputType),
+ applyAffinity: true,
+ trustLiveRange: false,
+ invalidate: false,
+ };
+ } else if (editable.contains(state.range.startContainer) && editable.contains(state.range.endContainer)) {
+ intent = {
+ editable,
+ inputType: event.inputType,
+ includeAdjacentRoots: false,
+ applyAffinity: false,
+ trustLiveRange: true,
+ invalidate: false,
+ };
+ }
+ if (intent) {
+ state.provisionalInput = intent;
+ setTimeout(() => {
+ if (state.provisionalInput === intent) {
+ state.provisionalInput = undefined;
+ }
+ }, 0);
+ }
+ });
+ };
+ const inputListener = (event: InputEvent) => {
+ const editable = getInputEditable(protyle, event.target);
+ if (!editable) {
+ return;
+ }
+ trackedRanges.get(protyle)?.forEach((state, handle) => {
+ const intent = state.provisionalInput;
+ if (intent?.editable === editable && intent.inputType === event.inputType) {
+ state.provisionalInput = undefined;
+ if (intent.invalidate) {
+ removeTrackedRange(protyle, handle);
+ } else {
+ state.editEvidence.add(intent);
+ }
+ }
+ });
+ };
+ element.addEventListener("beforeinput", beforeInputListener, true);
+ element.addEventListener("input", inputListener, true);
+ inputListeners.set(protyle, {element, beforeInputListener, inputListener});
+};
+
+const removeInputListeners = (protyle: IProtyle) => {
+ const item = inputListeners.get(protyle);
+ if (!item) {
+ return;
+ }
+ item.element.removeEventListener("beforeinput", item.beforeInputListener, true);
+ item.element.removeEventListener("input", item.inputListener, true);
+ inputListeners.delete(protyle);
+};
+
+const removeTrackedRange = (protyle: IProtyle, handle: ITrackedRangeHandle) => {
+ const manager = trackedRanges.get(protyle);
+ const state = manager?.get(handle);
+ if (!state) {
+ return;
+ }
+ manager.delete(handle);
+ if (manager.size === 0) {
+ trackedRanges.delete(protyle);
+ removeInputListeners(protyle);
+ }
+ if (state.owner) {
+ const handles = ownedHandles.get(state.owner);
+ handles?.forEach(item => {
+ if (item.protyle === protyle && item.handle === handle) {
+ handles.delete(item);
+ }
+ });
+ if (handles?.size === 0) {
+ ownedHandles.delete(state.owner);
+ }
+ }
+};
+
+export const trackRange = (protyle: IProtyle, range: Range,
+ options: ITrackRangeOptions): ITrackedRangeHandle => {
+ if (destroyedProtyles.has(protyle)) {
+ throw new Error("Cannot track a range in a destroyed Protyle instance");
+ }
+ if (!options?.owner || !["function", "object"].includes(typeof options.owner)) {
+ throw new TypeError("The tracked range owner is required");
+ }
+ if (options.affinity && !["after", "before"].includes(options.affinity)) {
+ throw new TypeError("The tracked range affinity must be before or after");
+ }
+ if (unloadingPlugins.has(options.owner)) {
+ throw new Error("Cannot track a range for an unloaded plugin");
+ }
+ const rangeSnapshot = getRangeSnapshot(protyle, range);
+ if (!rangeSnapshot) {
+ throw new TypeError("The range must be inside one editable source block of this Protyle instance");
+ }
+ const targetTokens = rangeSnapshot.stream.tokens.slice(rangeSnapshot.start, rangeSnapshot.end);
+ if (!range.collapsed && targetTokens.length === 0) {
+ throw new TypeError("The tracked range must contain semantic content");
+ }
+ const handle = Object.freeze({id: `tracked-range-${++handleSequence}`});
+ const trackedRange = range.cloneRange();
+ const state: ITrackedRangeState = {
+ range: trackedRange,
+ startContainer: trackedRange.startContainer,
+ endContainer: trackedRange.endContainer,
+ exactTarget: getExactlySelectedElement(trackedRange),
+ collapsed: trackedRange.collapsed,
+ affinity: options.affinity || "before",
+ targetTokens,
+ tokens: rangeSnapshot.stream.tokens,
+ start: rangeSnapshot.start,
+ end: rangeSnapshot.end,
+ sourceBlockID: rangeSnapshot.snapshot.block.getAttribute("data-node-id") || "",
+ sourceAncestorIDs: getAncestorBlockIDs(protyle.wysiwyg.element, rangeSnapshot.snapshot.block),
+ rootIDs: rangeSnapshot.stream.roots.map(root => root.getAttribute("data-node-id") || "").filter(Boolean),
+ rootBlockIDs: getRootBlockIDs(rangeSnapshot.stream.roots),
+ syncedBlockIDs: getRootBlockIDs(rangeSnapshot.stream.roots),
+ sourceLineageIDs: new Set([rangeSnapshot.snapshot.block.getAttribute("data-node-id") || ""]),
+ sourceTransitions: new Map(),
+ lineageIDs: new Set([
+ ...getAncestorBlockIDs(protyle.wysiwyg.element, rangeSnapshot.snapshot.block),
+ ...rangeSnapshot.stream.roots.map(root => root.getAttribute("data-node-id") || "").filter(Boolean),
+ ]),
+ knownBlockIDs: getRootBlockIDs([protyle.wysiwyg.element]),
+ owner: options.owner,
+ invalid: false,
+ editEvidence: new Set(),
+ };
+ getManager(protyle).set(handle, state);
+ ensureInputListeners(protyle);
+ if (state.owner) {
+ let handles = ownedHandles.get(state.owner);
+ if (!handles) {
+ handles = new Set();
+ ownedHandles.set(state.owner, handles);
+ }
+ handles.add({protyle, handle});
+ }
+ return handle;
+};
+
+export const resolveTrackedRange = (protyle: IProtyle, handle: ITrackedRangeHandle): TTrackedRangeResult => {
+ const state = trackedRanges.get(protyle)?.get(handle);
+ if (!state) {
+ return {status: "invalid"};
+ }
+ const range = resolveState(protyle, state);
+ if (!range) {
+ removeTrackedRange(protyle, handle);
+ return {status: "invalid"};
+ }
+ return {status: "resolved", range: range.cloneRange()};
+};
+
+export const releaseTrackedRange = (protyle: IProtyle, handle: ITrackedRangeHandle) => {
+ removeTrackedRange(protyle, handle);
+};
+
+export const syncTrackedRanges = (protyle: IProtyle, operations: IOperation[],
+ insertion?: ITrackedRangeInsertion) => {
+ const manager = trackedRanges.get(protyle);
+ if (!manager || manager.size === 0 || operations.length === 0) {
+ return;
+ }
+ manager.forEach((state, handle) => {
+ if (state.invalid) {
+ removeTrackedRange(protyle, handle);
+ return;
+ }
+ const pendingInsertionData = state.pendingInsertion && trackedRangeInsertions.get(state.pendingInsertion);
+ const hasActivePendingInsertion = pendingInsertionData && state.editEvidence.has(pendingInsertionData.evidence);
+ if (hasActivePendingInsertion && state.pendingInsertion !== insertion) {
+ rememberOperationReferences(state, operations);
+ return;
+ }
+ const relatedIDs = getRelatedOperationIDs(state, operations);
+ if (!relatedIDs) {
+ rememberOperationBlockIDs(state, operations);
+ return;
+ }
+ const editEvidence = Array.from(state.editEvidence)
+ .filter(evidence => !evidence.insertion || evidence.insertion === insertion);
+ const applyAffinity = editEvidence.some(evidence => evidence.applyAffinity);
+ const trustLiveRange = !applyAffinity && editEvidence.some(evidence => evidence.trustLiveRange);
+ editEvidence.forEach(evidence => state.editEvidence.delete(evidence));
+ state.provisionalInput = undefined;
+ const roots = getRootsForIDs(protyle.wysiwyg.element, relatedIDs);
+ const introducedSourceIDs = getIntroducedBlockIDs(state, operations, relatedIDs);
+ const restoredSourceIDs = getRestoredSourceIDs(state, operations, relatedIDs);
+ const exactRange = resolveExactTarget(protyle, state);
+ if (state.invalid) {
+ removeTrackedRange(protyle, handle);
+ return;
+ }
+ if (exactRange) {
+ state.syncedBlockIDs = getRootBlockIDs(roots);
+ rememberOperationBlockIDs(state, operations);
+ return;
+ }
+ const liveRange = resolveLiveRange(protyle, state);
+ if (liveRange) {
+ state.syncedBlockIDs = getRootBlockIDs(roots);
+ rememberOperationBlockIDs(state, operations);
+ return;
+ }
+ rememberOperationBlockIDs(state, operations);
+ if (roots.length === 0) {
+ removeTrackedRange(protyle, handle);
+ return;
+ }
+ const stream = createRootStream(roots);
+ let mappedRange: ITrackedTokenRange | undefined;
+ if (state.collapsed) {
+ const boundaryCandidates = getTrackedTokenBoundaryCandidates(state.tokens, stream.tokens, state.start);
+ const hasAffinityEvidence = applyAffinity;
+ mappedRange = mapTrackedTokenRange(state.tokens, stream.tokens, {start: state.start, end: state.end},
+ true, state.affinity, hasAffinityEvidence);
+ const liveRange = (!hasAffinityEvidence || trustLiveRange) && getLiveRange(protyle, state, true);
+ const liveSnapshot = liveRange && getRangeSnapshotFromStream(stream, liveRange);
+ const liveMatchesMapping = liveSnapshot && (trustLiveRange || (mappedRange ?
+ liveSnapshot.start === mappedRange.start && liveSnapshot.end === mappedRange.end :
+ hasOverlappingTrackedTokenContext(state.tokens, stream.tokens) &&
+ boundaryCandidates.length === 1 && boundaryCandidates.includes(liveSnapshot.start) &&
+ liveSnapshot.start === liveSnapshot.end));
+ if (liveRange && liveSnapshot && liveMatchesMapping &&
+ updateState(protyle, state, liveRange, liveSnapshot)) {
+ state.syncedBlockIDs = getRootBlockIDs(stream.roots);
+ return;
+ }
+ }
+ if (mapStateToStream(protyle, state, stream, introducedSourceIDs, restoredSourceIDs, mappedRange)) {
+ state.syncedBlockIDs = getRootBlockIDs(stream.roots);
+ } else {
+ removeTrackedRange(protyle, handle);
+ }
+ });
+};
+
+export const invalidateTrackedRanges = (protyle: IProtyle) => {
+ Array.from(trackedRanges.get(protyle)?.keys() || []).forEach(handle => removeTrackedRange(protyle, handle));
+};
+
+export const invalidateTrackedRangesByOperations = (protyle: IProtyle, operations: IOperation[]) => {
+ const manager = trackedRanges.get(protyle);
+ if (!manager || manager.size === 0 || operations.length === 0) {
+ return;
+ }
+ if (operations.some(operation => operation.id === protyle.block.rootID &&
+ ["delete", "update"].includes(operation.action))) {
+ invalidateTrackedRanges(protyle);
+ return;
+ }
+ manager.forEach((state, handle) => {
+ if (!state.invalid && getRelatedOperationIDs(state, operations)) {
+ removeTrackedRange(protyle, handle);
+ }
+ });
+};
+
+export const invalidateTrackedRangesInElement = (protyle: IProtyle, element: Element) => {
+ const manager = trackedRanges.get(protyle);
+ if (!manager || manager.size === 0) {
+ return;
+ }
+ const ids = new Set<string>();
+ const elementID = element.getAttribute("data-node-id");
+ if (elementID) {
+ ids.add(elementID);
+ }
+ element.querySelectorAll<HTMLElement>("[data-node-id]").forEach(block => {
+ const id = block.getAttribute("data-node-id");
+ if (id) {
+ ids.add(id);
+ }
+ });
+ manager.forEach((state, handle) => {
+ if (state.invalid) {
+ removeTrackedRange(protyle, handle);
+ return;
+ }
+ if (element.contains(state.startContainer) || element.contains(state.endContainer) ||
+ (state.exactTarget && element.contains(state.exactTarget)) ||
+ [...state.sourceAncestorIDs, ...state.rootIDs].some(id => ids.has(id))) {
+ removeTrackedRange(protyle, handle);
+ }
+ });
+};
+
+export const destroyTrackedRanges = (protyle: IProtyle) => {
+ destroyedProtyles.add(protyle);
+ const handles = Array.from(trackedRanges.get(protyle)?.keys() || []);
+ handles.forEach(handle => releaseTrackedRange(protyle, handle));
+ trackedRanges.delete(protyle);
+};
+
+export const releaseTrackedRangesByPlugin = (plugin: Plugin) => {
+ unloadingPlugins.add(plugin);
+ Array.from(ownedHandles.get(plugin) || []).forEach(item => releaseTrackedRange(item.protyle, item.handle));
+ ownedHandles.delete(plugin);
+};
diff --git a/app/src/protyle/util/trackedRangeAnchor.ts b/app/src/protyle/util/trackedRangeAnchor.ts
new file mode 100644
index 0000000000..287462dfd9
--- /dev/null
+++ b/app/src/protyle/util/trackedRangeAnchor.ts
@@ -0,0 +1,242 @@
+export interface ITrackedTokenRange {
+ start: number;
+ end: number;
+}
+
+const MAX_CONTEXT_TOKEN_COUNT = 24;
+
+const getCommonPrefixLength = (before: string[], after: string[]) => {
+ const length = Math.min(before.length, after.length);
+ let index = 0;
+ while (index < length && before[index] === after[index]) {
+ index++;
+ }
+ return index;
+};
+
+const getCommonSuffixLength = (before: string[], after: string[]) => {
+ const length = Math.min(before.length, after.length);
+ let index = 0;
+ while (index < length && before[before.length - index - 1] === after[after.length - index - 1]) {
+ index++;
+ }
+ return index;
+};
+
+const getBoundaryCandidates = (beforeLength: number, afterLength: number, prefixLength: number,
+ suffixLength: number, position: number) => {
+ const candidates = new Set<number>();
+ if (position <= prefixLength) {
+ candidates.add(position);
+ }
+ if (position >= beforeLength - suffixLength) {
+ candidates.add(afterLength - (beforeLength - position));
+ }
+ return Array.from(candidates).sort((first, second) => first - second);
+};
+
+export const getTrackedTokenBoundaryCandidates = (before: string[], after: string[], position: number) => {
+ if (position < 0 || position > before.length) {
+ return [];
+ }
+ const prefixLength = getCommonPrefixLength(before, after);
+ const suffixLength = getCommonSuffixLength(before, after);
+ return getBoundaryCandidates(before.length, after.length, prefixLength, suffixLength, position);
+};
+
+export const hasTrackedTokenRangeAffinityChoice = (before: string[], after: string[], position: number) => {
+ return getTrackedTokenBoundaryCandidates(before, after, position).length > 1;
+};
+
+export const hasOverlappingTrackedTokenContext = (before: string[], after: string[]) => {
+ return getCommonPrefixLength(before, after) + getCommonSuffixLength(before, after) >
+ Math.min(before.length, after.length);
+};
+
+const equalTokens = (first: string[], second: string[]) => {
+ return first.length === second.length && first.every((token, index) => token === second[index]);
+};
+
+const countTokenOccurrences = (tokens: string[], pattern: string[], limit = 2) => {
+ if (pattern.length === 0 || pattern.length > tokens.length) {
+ return 0;
+ }
+ const failure = new Array<number>(pattern.length).fill(0);
+ for (let index = 1, matched = 0; index < pattern.length; index++) {
+ while (matched > 0 && pattern[index] !== pattern[matched]) {
+ matched = failure[matched - 1];
+ }
+ if (pattern[index] === pattern[matched]) {
+ matched++;
+ failure[index] = matched;
+ }
+ }
+ let count = 0;
+ for (let index = 0, matched = 0; index < tokens.length; index++) {
+ while (matched > 0 && tokens[index] !== pattern[matched]) {
+ matched = failure[matched - 1];
+ }
+ if (tokens[index] === pattern[matched]) {
+ matched++;
+ }
+ if (matched === pattern.length) {
+ count++;
+ if (count >= limit) {
+ return count;
+ }
+ matched = failure[matched - 1];
+ }
+ }
+ return count;
+};
+
+const isUniqueTokenSequenceAt = (tokens: string[], pattern: string[], start: number) => {
+ return start >= 0 && start + pattern.length <= tokens.length &&
+ equalTokens(tokens.slice(start, start + pattern.length), pattern) &&
+ countTokenOccurrences(tokens, pattern) === 1;
+};
+
+const hasUniqueTargetAnchor = (before: string[], after: string[], range: ITrackedTokenRange,
+ mapped: ITrackedTokenRange, prefixLength: number, suffixLength: number) => {
+ const target = before.slice(range.start, range.end);
+ if (!equalTokens(after.slice(mapped.start, mapped.end), target)) {
+ return false;
+ }
+ if (countTokenOccurrences(before, target) === 1 && countTokenOccurrences(after, target) === 1) {
+ return true;
+ }
+ const failure = new Array<number>(target.length).fill(0);
+ for (let index = 1, matched = 0; index < target.length; index++) {
+ while (matched > 0 && target[index] !== target[matched]) {
+ matched = failure[matched - 1];
+ }
+ if (target[index] === target[matched]) {
+ matched++;
+ failure[index] = matched;
+ }
+ }
+ let mappedSourceCount = 0;
+ for (let index = 0, matched = 0; index < before.length; index++) {
+ while (matched > 0 && before[index] !== target[matched]) {
+ matched = failure[matched - 1];
+ }
+ if (before[index] === target[matched]) {
+ matched++;
+ }
+ if (matched === target.length) {
+ const start = index - target.length + 1;
+ const end = start + target.length;
+ const startCandidates = getBoundaryCandidates(before.length, after.length, prefixLength,
+ suffixLength, start);
+ const endCandidates = getBoundaryCandidates(before.length, after.length, prefixLength,
+ suffixLength, end);
+ if (startCandidates.length > 0 && endCandidates.length > 0 &&
+ Math.max(...startCandidates) === mapped.start && Math.min(...endCandidates) === mapped.end) {
+ mappedSourceCount++;
+ if (mappedSourceCount > 1) {
+ return false;
+ }
+ }
+ matched = failure[matched - 1];
+ }
+ }
+ if (mappedSourceCount !== 1) {
+ return false;
+ }
+ const maxLeft = Math.min(MAX_CONTEXT_TOKEN_COUNT, range.start, mapped.start);
+ const maxRight = Math.min(MAX_CONTEXT_TOKEN_COUNT, before.length - range.end, after.length - mapped.end);
+ for (let contextLength = 1; contextLength <= Math.max(maxLeft, maxRight); contextLength++) {
+ const leftLength = Math.min(contextLength, maxLeft);
+ const rightLength = Math.min(contextLength, maxRight);
+ const contexts = [
+ {left: leftLength, right: 0},
+ {left: 0, right: rightLength},
+ {left: leftLength, right: rightLength},
+ ];
+ if (contexts.some(context => {
+ if (context.left + context.right === 0) {
+ return false;
+ }
+ const pattern = before.slice(range.start - context.left, range.end + context.right);
+ return isUniqueTokenSequenceAt(before, pattern, range.start - context.left) &&
+ isUniqueTokenSequenceAt(after, pattern, mapped.start - context.left);
+ })) {
+ return true;
+ }
+ }
+ return false;
+};
+
+const hasUniqueCollapsedAnchor = (before: string[], after: string[], position: number,
+ beforePosition: number, afterPosition: number, requireBothAnchors: boolean) => {
+ const maxLeft = Math.min(MAX_CONTEXT_TOKEN_COUNT, position, beforePosition);
+ const maxRight = Math.min(MAX_CONTEXT_TOKEN_COUNT, before.length - position, after.length - afterPosition);
+ let hasLeftAnchor = position === 0;
+ let hasRightAnchor = position === before.length;
+ for (let contextLength = 1; contextLength <= Math.max(maxLeft, maxRight); contextLength++) {
+ if (!hasLeftAnchor && contextLength <= maxLeft) {
+ const pattern = before.slice(position - contextLength, position);
+ if (isUniqueTokenSequenceAt(before, pattern, position - contextLength) &&
+ isUniqueTokenSequenceAt(after, pattern, beforePosition - contextLength)) {
+ hasLeftAnchor = true;
+ }
+ }
+ if (!hasRightAnchor && contextLength <= maxRight) {
+ const pattern = before.slice(position, position + contextLength);
+ if (isUniqueTokenSequenceAt(before, pattern, position) &&
+ isUniqueTokenSequenceAt(after, pattern, afterPosition)) {
+ hasRightAnchor = true;
+ }
+ }
+ if (requireBothAnchors ? hasLeftAnchor && hasRightAnchor : hasLeftAnchor || hasRightAnchor) {
+ return true;
+ }
+ }
+ return requireBothAnchors ? hasLeftAnchor && hasRightAnchor : hasLeftAnchor || hasRightAnchor;
+};
+
+/**
+ * 只映射由公共前后缀能够证明身份的范围。重复内容产生多个边界时,折叠范围按亲和性选择,
+ * 非折叠范围则向目标内部收紧;目标内容发生变化或身份仍有歧义时返回 undefined。
+ */
+export const mapTrackedTokenRange = (before: string[], after: string[], range: ITrackedTokenRange,
+ collapsed: boolean, affinity: "before" | "after",
+ hasAffinityEvidence = false) => {
+ if (range.start < 0 || range.end < range.start || range.end > before.length ||
+ collapsed !== (range.start === range.end)) {
+ return;
+ }
+ if (equalTokens(before, after)) {
+ return {start: range.start, end: range.end};
+ }
+ const prefixLength = getCommonPrefixLength(before, after);
+ const suffixLength = getCommonSuffixLength(before, after);
+ const startCandidates = getBoundaryCandidates(before.length, after.length, prefixLength, suffixLength, range.start);
+ const endCandidates = getBoundaryCandidates(before.length, after.length, prefixLength, suffixLength, range.end);
+ if (startCandidates.length === 0 || endCandidates.length === 0) {
+ return;
+ }
+ if (collapsed) {
+ const candidates = Array.from(new Set([...startCandidates, ...endCandidates]));
+ if (candidates.length > 1 && prefixLength + suffixLength > Math.min(before.length, after.length) &&
+ !hasAffinityEvidence) {
+ return;
+ }
+ const beforePosition = Math.min(...candidates);
+ const afterPosition = Math.max(...candidates);
+ if (!hasAffinityEvidence && !hasUniqueCollapsedAnchor(before, after, range.start, beforePosition,
+ afterPosition, candidates.length > 1)) {
+ return;
+ }
+ const position = affinity === "before" ? beforePosition : afterPosition;
+ return {start: position, end: position};
+ }
+ const start = Math.max(...startCandidates);
+ const end = Math.min(...endCandidates);
+ const mapped = {start, end};
+ if (start >= end || !equalTokens(before.slice(range.start, range.end), after.slice(start, end)) ||
+ !hasUniqueTargetAnchor(before, after, range, mapped, prefixLength, suffixLength)) {
+ return;
+ }
+ return mapped;
+};
diff --git a/app/src/protyle/wysiwyg/enter.ts b/app/src/protyle/wysiwyg/enter.ts
index 0f91a52fea..26fc3a44af 100644
--- a/app/src/protyle/wysiwyg/enter.ts
+++ b/app/src/protyle/wysiwyg/enter.ts
@@ -39,8 +39,14 @@ import {
getBlockSelectionModeElement
} from "./blockSelection";
import {getTextWithoutSemanticMarkers} from "../util/inlineElementMarker";
+import {
+ activateTrackedRangeInsertion,
+ setTrackedRangeInsertionResult,
+ type ITrackedRangeInsertion,
+} from "../util/trackedRange";
-export const enter = async (blockElement: HTMLElement, range: Range, protyle: IProtyle) => {
+export const enter = async (blockElement: HTMLElement, range: Range, protyle: IProtyle,
+ trackedRangeInsertion?: ITrackedRangeInsertion) => {
const selectionModeElement = getBlockSelectionModeElement(protyle.wysiwyg.element);
if (selectionModeElement) {
blockElement = selectionModeElement;
@@ -109,6 +115,7 @@ export const enter = async (blockElement: HTMLElement, range: Range, protyle: IP
trimStartHTML.replace(codeBlockMarkerRegExp, "`").replace(/^`{3,}/g, "").indexOf("`") > -1) {
// ```test` 不处理,正常渲染为段落块
} else if (blockElement.classList.contains("p")) { // https://github.com/siyuan-note/siyuan/issues/6953
+ activateTrackedRangeInsertion(trackedRangeInsertion);
range.insertNode(document.createElement("wbr"));
const oldHTML = blockElement.outerHTML;
// https://github.com/siyuan-note/siyuan/issues/16744
@@ -147,12 +154,13 @@ export const enter = async (blockElement: HTMLElement, range: Range, protyle: IP
protyle.toolbar.showRender(protyle, blockElement);
processRender(blockElement);
}
- updateTransaction(protyle, blockElement, oldHTML);
+ updateTransaction(protyle, blockElement, oldHTML, undefined, undefined, {trackedRangeInsertion});
return true;
}
}
// 代码块
if (blockElement.getAttribute("data-type") === "NodeCodeBlock") {
+ activateTrackedRangeInsertion(trackedRangeInsertion);
const wbrElement = document.createElement("wbr");
range.insertNode(wbrElement);
const oldHTML = blockElement.outerHTML;
@@ -166,7 +174,7 @@ export const enter = async (blockElement: HTMLElement, range: Range, protyle: IP
range.insertNode(wbrElement);
editableElement.parentElement.removeAttribute("data-render");
highlightRender(blockElement);
- updateTransaction(protyle, blockElement, oldHTML);
+ updateTransaction(protyle, blockElement, oldHTML, undefined, undefined, {trackedRangeInsertion});
scrollCenter(protyle);
return true;
}
@@ -179,6 +187,7 @@ export const enter = async (blockElement: HTMLElement, range: Range, protyle: IP
if (embedContext && !embedContext.boundaryElement.contains(getParentBlock(blockElement).parentElement)) {
return;
}
+ activateTrackedRangeInsertion(trackedRangeInsertion);
range.insertNode(document.createElement("wbr"));
const topElement = getTopEmptyElement(blockElement, embedContext?.boundaryElement);
const blockId = blockElement.getAttribute("data-node-id");
@@ -230,7 +239,7 @@ export const enter = async (blockElement: HTMLElement, range: Range, protyle: IP
enterDoOperations.push(...sbOperations.doOperations);
enterUndoOperations.splice(0, 0, ...sbOperations.undoOperations);
}
- transaction(protyle, enterDoOperations, enterUndoOperations);
+ transaction(protyle, enterDoOperations, enterUndoOperations, {trackedRangeInsertion});
focusByWbr(blockElement, range);
return true;
}
@@ -246,7 +255,8 @@ export const enter = async (blockElement: HTMLElement, range: Range, protyle: IP
if ("none" === embedListEnterMode) {
return;
}
- if ("list" === embedListEnterMode && await listEnter(protyle, blockElement, range)) {
+ if ("list" === embedListEnterMode &&
+ await listEnter(protyle, blockElement, range, trackedRangeInsertion)) {
return true;
}
}
@@ -262,6 +272,7 @@ export const enter = async (blockElement: HTMLElement, range: Range, protyle: IP
} else {
newElement = genEmptyElement(false, true);
}
+ activateTrackedRangeInsertion(trackedRangeInsertion);
blockElement.insertAdjacentElement("beforebegin", newElement);
const newId = newElement.getAttribute("data-node-id");
const doOperations: IOperation[] = [{
@@ -289,12 +300,13 @@ export const enter = async (blockElement: HTMLElement, range: Range, protyle: IP
doOperations.push(...mergeOperations.doOperations);
undoOperations.splice(0, 0, ...mergeOperations.undoOperations);
}
- transaction(protyle, doOperations, undoOperations);
+ transaction(protyle, doOperations, undoOperations, {trackedRangeInsertion});
newElement.querySelector("wbr").remove();
removeEmptyNode(newElement);
return true;
}
const undoFocusContext = getUndoFocusContext(protyle.wysiwyg.element, range);
+ activateTrackedRangeInsertion(trackedRangeInsertion);
range.insertNode(document.createElement("wbr"));
const html = blockElement.outerHTML;
const parentHTML = getParentBlock(blockElement).outerHTML;
@@ -432,7 +444,7 @@ export const enter = async (blockElement: HTMLElement, range: Range, protyle: IP
parentElement = parentElement.nextElementSibling as HTMLElement;
parentElement.previousElementSibling.remove();
mathRender(protyle.wysiwyg.element);
- updateTransaction(protyle, parentElement, parentHTML);
+ updateTransaction(protyle, parentElement, parentHTML, undefined, undefined, {trackedRangeInsertion});
focusByWbr(protyle.wysiwyg.element, range);
scrollCenter(protyle);
return true;
@@ -459,7 +471,7 @@ export const enter = async (blockElement: HTMLElement, range: Range, protyle: IP
doOperation.push(...sbOperations.doOperations);
undoOperation.splice(0, 0, ...sbOperations.undoOperations);
}
- transaction(protyle, doOperation, undoOperation);
+ transaction(protyle, doOperation, undoOperation, {trackedRangeInsertion});
focusByWbr(currentElement, range);
scrollCenter(protyle);
return true;
@@ -481,7 +493,8 @@ const getEmbedListEnterMode = (blockElement: HTMLElement, embedContext: IEmbedCh
return embedContext.boundaryElement.contains(exitsList ? listElement.parentElement : listElement) ? "list" : "none";
};
-const listEnter = async (protyle: IProtyle, blockElement: HTMLElement, range: Range) => {
+const listEnter = async (protyle: IProtyle, blockElement: HTMLElement, range: Range,
+ trackedRangeInsertion?: ITrackedRangeInsertion) => {
const listItemElement = blockElement.parentElement;
const editableElement = getContenteditableElement(blockElement);
const isPrimaryBlock = blockElement.previousElementSibling.classList.contains("protyle-action");
@@ -496,11 +509,11 @@ const listEnter = async (protyle: IProtyle, blockElement: HTMLElement, range: Ra
isPrimaryBlock // https://ld246.com/article/1651820644238
) {
if (listItemElement.nextElementSibling?.classList.contains("protyle-attr")) {
- await listOutdent(protyle, [blockElement.parentElement], range);
+ await listOutdent(protyle, [blockElement.parentElement], range, false, undefined, trackedRangeInsertion);
return true;
} else if (!listItemElement.parentElement.classList.contains("protyle-wysiwyg")) {
// 打断列表
- await breakList(protyle, blockElement, range);
+ await breakList(protyle, blockElement, range, trackedRangeInsertion);
return true;
}
}
@@ -514,6 +527,7 @@ const listEnter = async (protyle: IProtyle, blockElement: HTMLElement, range: Ra
return true;
}
// https://github.com/siyuan-note/siyuan/issues/8935
+ activateTrackedRangeInsertion(trackedRangeInsertion);
const wbrElement = document.createElement("wbr");
range.insertNode(wbrElement);
const listElement = listItemElement.parentElement;
@@ -537,7 +551,7 @@ const listEnter = async (protyle: IProtyle, blockElement: HTMLElement, range: Ra
if (listItemElement.getAttribute("data-subtype") === "o") {
updateListOrder(listElement, listStart);
}
- updateTransaction(protyle, listElement, html);
+ updateTransaction(protyle, listElement, html, undefined, undefined, {trackedRangeInsertion});
focusByWbr(newElement, range);
scrollCenter(protyle);
removeEmptyNode(newElement);
@@ -554,6 +568,7 @@ const listEnter = async (protyle: IProtyle, blockElement: HTMLElement, range: Ra
if (!listItemElement.isConnected) {
return true;
}
+ activateTrackedRangeInsertion(trackedRangeInsertion);
const subListElement = listItemElement.querySelector(".list");
let newElement;
if (subListElement && listItemElement.getAttribute("fold") !== "1" &&
@@ -573,7 +588,7 @@ const listEnter = async (protyle: IProtyle, blockElement: HTMLElement, range: Ra
if (subListElement.getAttribute("data-subtype") === "o") {
updateListOrder(subListElement, listStart);
}
- updateTransaction(protyle, listItemElement, html);
+ updateTransaction(protyle, listItemElement, html, undefined, undefined, {trackedRangeInsertion});
focusByWbr(listItemElement, range);
scrollCenter(protyle);
} else {
@@ -629,9 +644,10 @@ const listEnter = async (protyle: IProtyle, blockElement: HTMLElement, range: Ra
action: "update",
data: listItemHTML,
id: listItemElement.getAttribute("data-node-id")
- }, ...orderOperations.undoOperations]);
+ }, ...orderOperations.undoOperations], {trackedRangeInsertion});
} else {
- updateTransaction(protyle, listItemElement.parentElement, html);
+ updateTransaction(protyle, listItemElement.parentElement, html, undefined, undefined,
+ {trackedRangeInsertion});
}
focusByWbr(newElement, range);
scrollCenter(protyle);
@@ -721,9 +737,10 @@ const listEnter = async (protyle: IProtyle, blockElement: HTMLElement, range: Ra
action: "update",
id: listItemElement.getAttribute("data-node-id"),
data: listItemHTML
- }, ...orderOperations.undoOperations]);
+ }, ...orderOperations.undoOperations], {trackedRangeInsertion});
} else {
- updateTransaction(protyle, listItemElement.parentElement, oldHTML);
+ updateTransaction(protyle, listItemElement.parentElement, oldHTML, undefined, undefined,
+ {trackedRangeInsertion});
}
focusByWbr(newElement, range);
scrollCenter(protyle);
@@ -741,7 +758,8 @@ const removeEmptyNode = (newElement: Element) => {
}
};
-export const softEnter = (range: Range, nodeElement: HTMLElement, protyle: IProtyle) => {
+export const softEnter = (range: Range, nodeElement: HTMLElement, protyle: IProtyle,
+ trackedRangeInsertion?: ITrackedRangeInsertion) => {
let startElement = range.startContainer as HTMLElement;
const nextSibling = hasNextSibling(startElement) as Element;
if (nodeElement.getAttribute("data-type") === "NodeAttributeView") {
@@ -752,6 +770,7 @@ export const softEnter = (range: Range, nodeElement: HTMLElement, protyle: IProt
if (textPosition.end === range.endContainer.textContent.length) {
// 图片之前软换行 || 数学公式之前软换行 https://github.com/siyuan-note/siyuan/issues/13621
if (nextSibling.classList.contains("img") || nextSibling.getAttribute("data-type") === "inline-math") {
+ activateTrackedRangeInsertion(trackedRangeInsertion);
nextSibling.insertAdjacentHTML("beforebegin", "<wbr>");
const oldHTML = nodeElement.outerHTML;
nextSibling.previousElementSibling.remove();
@@ -760,7 +779,7 @@ export const softEnter = (range: Range, nodeElement: HTMLElement, protyle: IProt
startElement.after(newlineNode);
range.selectNode(newlineNode);
range.collapse(false);
- updateTransaction(protyle, nodeElement, oldHTML);
+ updateTransaction(protyle, nodeElement, oldHTML, undefined, undefined, {trackedRangeInsertion});
return true;
}
}
@@ -771,7 +790,7 @@ export const softEnter = (range: Range, nodeElement: HTMLElement, protyle: IProt
}
if (startElement && protyle.toolbar.getCurrentType(range).length > 0 &&
getSelectionOffset(startElement, startElement, range).end === startElement.textContent.length) {
- addNewLineToEnd(range, nodeElement, protyle, startElement);
+ addNewLineToEnd(range, nodeElement, protyle, startElement, trackedRangeInsertion);
return true;
}
if (isIPad() || isMobile()) {
@@ -782,13 +801,15 @@ export const softEnter = (range: Range, nodeElement: HTMLElement, protyle: IProt
document.execCommand("insertHTML", false, "\n");
return true;
}
- addNewLineToEnd(range, nodeElement, protyle, startElement);
+ addNewLineToEnd(range, nodeElement, protyle, startElement, trackedRangeInsertion);
return true;
}
return false;
};
-const addNewLineToEnd = (range: Range, nodeElement: HTMLElement, protyle: IProtyle, startElement: Element) => {
+const addNewLineToEnd = (range: Range, nodeElement: HTMLElement, protyle: IProtyle, startElement: Element,
+ trackedRangeInsertion?: ITrackedRangeInsertion) => {
+ activateTrackedRangeInsertion(trackedRangeInsertion);
const wbrElement = document.createElement("wbr");
if (startElement.nodeType === 3) {
range.insertNode(wbrElement);
@@ -804,6 +825,13 @@ const addNewLineToEnd = (range: Range, nodeElement: HTMLElement, protyle: IProty
}
const newlineNode = document.createTextNode("\n");
startElement.after(newlineNode);
+ const beforeRange = document.createRange();
+ beforeRange.setStartBefore(newlineNode);
+ beforeRange.collapse(true);
+ const afterRange = document.createRange();
+ afterRange.setStartAfter(newlineNode);
+ afterRange.collapse(true);
+ setTrackedRangeInsertionResult(trackedRangeInsertion, beforeRange, afterRange);
if (endNewlineNode) {
range.setStart(endNewlineNode, 0);
} else {
@@ -811,5 +839,5 @@ const addNewLineToEnd = (range: Range, nodeElement: HTMLElement, protyle: IProty
}
range.collapse(true);
focusByRange(range);
- updateTransaction(protyle, nodeElement, oldHTML);
+ updateTransaction(protyle, nodeElement, oldHTML, undefined, undefined, {trackedRangeInsertion});
};
diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.ts
index 8cc145ec38..afd33cd42f 100644
--- a/app/src/protyle/wysiwyg/keydown.ts
+++ b/app/src/protyle/wysiwyg/keydown.ts
@@ -28,6 +28,7 @@ import {
removeEmptySemanticInlineElement
} from "../util/inlineElementMarker";
import {hasUnloadedDocumentBlocks} from "../util/documentRange";
+import {endTrackedRangeInsertion, prepareTrackedRangeInsertion} from "../util/trackedRange";
import {
hasClosestBlock,
hasClosestByAttribute,
@@ -1583,10 +1584,17 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
}
// 软换行
- if (selectText === "" && matchHotKey("⇧↩", event) && softEnter(range, nodeElement, protyle)) {
- event.stopPropagation();
- event.preventDefault();
- return;
+ if (selectText === "" && matchHotKey("⇧↩", event)) {
+ const trackedRangeInsertion = prepareTrackedRangeInsertion(protyle, range);
+ try {
+ if (softEnter(range, nodeElement, protyle, trackedRangeInsertion)) {
+ event.stopPropagation();
+ event.preventDefault();
+ return;
+ }
+ } finally {
+ endTrackedRangeInsertion(trackedRangeInsertion);
+ }
}
// 代码块修改语言 https://github.com/siyuan-note/siyuan/issues/14126
@@ -1618,7 +1626,12 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
(matchHotKey("⇧↩", event) && nodeType === "NodeHeading")) {
event.stopPropagation();
event.preventDefault();
- await enter(nodeElement, range, protyle);
+ const trackedRangeInsertion = prepareTrackedRangeInsertion(protyle, range);
+ try {
+ await enter(nodeElement, range, protyle, trackedRangeInsertion);
+ } finally {
+ endTrackedRangeInsertion(trackedRangeInsertion);
+ }
if (blockSelectionModeElement) {
countBlockWord([], protyle.block.rootID);
}
diff --git a/app/src/protyle/wysiwyg/list.ts b/app/src/protyle/wysiwyg/list.ts
index 6850d88b68..0c50f4c6c2 100644
--- a/app/src/protyle/wysiwyg/list.ts
+++ b/app/src/protyle/wysiwyg/list.ts
@@ -23,6 +23,7 @@ import {fetchSyncPost} from "../../util/fetch";
import {Dialog} from "../../dialog";
import {isMobile} from "../../util/functions";
import {showMessage} from "../../dialog/message";
+import {activateTrackedRangeInsertion, type ITrackedRangeInsertion} from "../util/trackedRange";
const getLastChildBlock = (element: Element) => {
if (!element || !element.lastElementChild) {
@@ -941,7 +942,8 @@ export const listIndent = async (protyle: IProtyle, liItemElements: Element[], r
focusByWbr(protyle.wysiwyg.element, range);
};
-export const breakList = async (protyle: IProtyle, blockElement: Element, range: Range) => {
+export const breakList = async (protyle: IProtyle, blockElement: Element, range: Range,
+ trackedRangeInsertion?: ITrackedRangeInsertion) => {
const listItemElement = blockElement.parentElement;
if (!listItemElement.previousElementSibling) {
await removeBlock(protyle, blockElement, range, "Backspace");
@@ -955,6 +957,7 @@ export const breakList = async (protyle: IProtyle, blockElement: Element, range:
const doOperations: IOperation[] = [];
const undoOperations: IOperation[] = [];
+ activateTrackedRangeInsertion(trackedRangeInsertion);
range.insertNode(document.createElement("wbr"));
const newListId = Lute.NewNodeID();
let newListHTML = "";
@@ -1065,7 +1068,7 @@ export const breakList = async (protyle: IProtyle, blockElement: Element, range:
doOperations.push(...mergeOperations.doOperations);
undoOperations.splice(0, 0, ...mergeOperations.undoOperations);
}
- transaction(protyle, doOperations, undoOperations);
+ transaction(protyle, doOperations, undoOperations, {trackedRangeInsertion});
focusByWbr(protyle.wysiwyg.element, range);
};
@@ -1077,11 +1080,8 @@ export const breakList = async (protyle: IProtyle, blockElement: Element, range:
* @param isDelete
* @param deleteElement 末尾反向删除时才会传入
*/
-export const listOutdent = async (protyle: IProtyle, liItemElements: Element[], range: Range, isDelete = false, deleteElement?: Element) => {
- liItemElements.forEach(item => {
- item.removeAttribute("select-start");
- item.removeAttribute("select-end");
- });
+export const listOutdent = async (protyle: IProtyle, liItemElements: Element[], range: Range, isDelete = false,
+ deleteElement?: Element, trackedRangeInsertion?: ITrackedRangeInsertion) => {
if (!liItemElements[0].classList.contains("li")) {
if (liItemElements[0].parentElement.childElementCount === liItemElements.length + 2) {
liItemElements = [liItemElements[0].parentElement];
@@ -1119,6 +1119,11 @@ export const listOutdent = async (protyle: IProtyle, liItemElements: Element[],
liItemElements.some((item) => !item.isConnected)) {
return;
}
+ activateTrackedRangeInsertion(trackedRangeInsertion);
+ liItemElements.forEach(item => {
+ item.removeAttribute("select-start");
+ item.removeAttribute("select-end");
+ });
const movedListItemElements = [...liItemElements] as HTMLElement[];
if (parentLiItemElement.classList.contains("protyle-wysiwyg") || parentLiItemElement.classList.contains("sb") ||
parentLiItemElement.classList.contains("bq") || parentLiItemElement.classList.contains("callout")) {
@@ -1304,7 +1309,7 @@ export const listOutdent = async (protyle: IProtyle, liItemElements: Element[],
});
}
}
- transaction(protyle, topDoOperations, topUndoOperations);
+ transaction(protyle, topDoOperations, topUndoOperations, {trackedRangeInsertion});
focusByWbr(parentLiItemElement, range);
return;
}
@@ -1321,7 +1326,7 @@ export const listOutdent = async (protyle: IProtyle, liItemElements: Element[],
liItemElements[0].firstElementChild.remove();
liItemElements[0].lastElementChild.remove();
liElement.outerHTML = liItemElements[0].innerHTML;
- updateTransaction(protyle, parentLiItemElement, html);
+ updateTransaction(protyle, parentLiItemElement, html, undefined, undefined, {trackedRangeInsertion});
focusByWbr(parentLiItemElement, range);
return;
}
@@ -1564,12 +1569,12 @@ export const listOutdent = async (protyle: IProtyle, liItemElements: Element[],
appendFocusedOutdentListUpdate(focusedParentListElement, parentLiItemElement as HTMLElement,
movedListItemElements, doOperations, undoOperations);
}
- transaction(protyle, doOperations, undoOperations);
+ transaction(protyle, doOperations, undoOperations, {trackedRangeInsertion});
} else {
if (parentLiItemElement && parentLiItemElement.getAttribute("data-subtype") === "o") {
updateListOrder(parentParentElement);
}
- updateTransaction(protyle, parentParentElement, html);
+ updateTransaction(protyle, parentParentElement, html, undefined, undefined, {trackedRangeInsertion});
}
focusByWbr(parentParentElement, range);
};
diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.ts
index 411e83b99f..42172da301 100644
--- a/app/src/protyle/wysiwyg/transaction.ts
+++ b/app/src/protyle/wysiwyg/transaction.ts
@@ -65,6 +65,11 @@ import {
getBlockSelectionStatusIDs,
restoreBlockSelectionModeState
} from "./blockSelection";
+import {
+ invalidateTrackedRangesByOperations,
+ type ITrackedRangeInsertion,
+ syncTrackedRanges,
+} from "../util/trackedRange";
const cleanBlockSelectionModeOperations = (operations?: IOperation[]) => {
operations?.forEach(operation => {
@@ -173,6 +178,7 @@ const promiseTransaction = (options: {
skipSync: boolean,
callback?: () => void,
templateDocTreePlanID?: string,
+ trackedRangeInsertion?: ITrackedRangeInsertion,
}) => {
const protyle = options.protyle;
// 受影响的嵌入块需推迟到事务提交后再渲染,否则其查询请求会早于写入到达内核而拿到旧数据
@@ -528,6 +534,9 @@ const promiseTransaction = (options: {
focusByWbr(emptyElement, range);
}
}
+ if (!options.skipSync) {
+ syncTrackedRanges(protyle, options.doOperations, options.trackedRangeInsertion);
+ }
queueTransaction(protyle, () => fetchPost("/api/transactions", {
session: protyle.id,
app: Constants.SIYUAN_APPID,
@@ -721,10 +730,14 @@ const updateBlock = (updateElements: Element[], protyle: IProtyle, operation: IO
};
// 用于推送和撤销;普通模式在内核事务完成后回放,lite 模式仅更新本地 DOM。
-export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUndo: boolean) => {
+export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUndo: boolean,
+ preserveTrackedRanges = isUndo) => {
if (protyle.wysiwyg.element.firstElementChild?.classList.contains("protyle-password")) {
return;
}
+ if (!preserveTrackedRanges) {
+ invalidateTrackedRangesByOperations(protyle, operations);
+ }
invalidateViewFoldRequests(protyle);
const undoFocusContext = isUndo ? operations.find(item => item.context?.undoFocusId)?.context : undefined;
const undoFocusEmbedElement = undoFocusContext?.undoFocusEmbedId ? protyle.wysiwyg.element.querySelector(
@@ -1358,6 +1371,9 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd
return;
}
});
+ if (preserveTrackedRanges) {
+ syncTrackedRanges(protyle, operations);
+ }
void applyViewFoldStates(protyle);
pendingUndoEmbedElements.forEach(item => {
if (!item.isConnected) {
@@ -2057,7 +2073,7 @@ export const turnListsRecursively = async (options: {
transaction(options.protyle, doOperations.concat(doFoldOperations), undoOperations.concat(undoFoldOperations));
}
if (!hasViewFoldContext(options.protyle)) {
- onTransaction(options.protyle, doFoldOperations, false);
+ onTransaction(options.protyle, doFoldOperations, false, true);
}
focusByWbr(options.protyle.wysiwyg.element, getEditorRange(options.protyle.wysiwyg.element));
options.protyle.wysiwyg.element.querySelectorAll('[data-type~="block-ref"]').forEach(item => {
@@ -2181,6 +2197,7 @@ export const transaction = (protyle: IProtyle, doOperations: IOperation[], undoO
skipSync?: boolean,
callback?: () => void,
templateDocTreePlanID?: string,
+ trackedRangeInsertion?: ITrackedRangeInsertion,
}) => {
if (protyle) {
const prepared = prepareViewFoldTransaction(protyle, doOperations, undoOperations);
@@ -2214,6 +2231,9 @@ export const transaction = (protyle: IProtyle, doOperations: IOperation[], undoO
protyle.undo.add(doOperations, undoOperations, protyle);
}
if (protyle?.lite) {
+ if (!options?.skipSync) {
+ syncTrackedRanges(protyle, doOperations, options?.trackedRangeInsertion);
+ }
return;
}
promiseTransaction({
@@ -2223,6 +2243,7 @@ export const transaction = (protyle: IProtyle, doOperations: IOperation[], undoO
skipSync: options?.skipSync,
callback: options?.callback,
templateDocTreePlanID: options?.templateDocTreePlanID,
+ trackedRangeInsertion: options?.trackedRangeInsertion,
});
// 插入块后会导致高度变化,从而产生再次定位 https://github.com/siyuan-note/siyuan/issues/11798
doOperations.find(item => {
@@ -2328,7 +2349,7 @@ export const updateTransaction = (protyle: IProtyle, element: Element, oldHTML:
doOperations: IOperation[],
undoOperations: IOperation[],
context?: Record<string, string>,
- }) => {
+ }, options?: {trackedRangeInsertion?: ITrackedRangeInsertion}) => {
if (element.getAttribute("data-type") === "NodeSuperBlock") {
refreshSbResize(element);
}
@@ -2355,7 +2376,7 @@ export const updateTransaction = (protyle: IProtyle, element: Element, oldHTML:
doOperations.unshift(...additionalOperations.doOperations);
undoOperations.push(...additionalOperations.undoOperations);
}
- transaction(protyle, doOperations, undoOperations);
+ transaction(protyle, doOperations, undoOperations, options);
};
type TEmptyParagraphTarget = "code" | "table" | "line" | "math";
diff --git a/app/src/types/protyle.d.ts b/app/src/types/protyle.d.ts
index 8bf629718b..44c0a59b3c 100644
--- a/app/src/types/protyle.d.ts
+++ b/app/src/types/protyle.d.ts
@@ -531,6 +531,24 @@ interface IProtyleOptions {
lite?: boolean;
}
+interface ITrackedRangeHandle {
+ readonly id: string;
+}
+
+interface ITrackRangeOptions {
+ /** 用于在插件卸载时自动释放句柄 */
+ owner: import("../plugin").Plugin;
+ /** 同一位置插入新内容时,锚点保留在新内容之前还是之后,默认为 before */
+ affinity?: "before" | "after";
+}
+
+type TTrackedRangeResult = {
+ status: "resolved";
+ range: Range;
+} | {
+ status: "invalid";
+};
+
interface IProtyle {
highlight: {
mark: Highlight
@@ -540,6 +558,9 @@ interface IProtyle {
styleElement: HTMLStyleElement
}
getInstance: () => import("../protyle").Protyle,
+ trackRange: (range: Range, options: ITrackRangeOptions) => ITrackedRangeHandle,
+ resolveTrackedRange: (handle: ITrackedRangeHandle) => TTrackedRangeResult,
+ releaseTrackedRange: (handle: ITrackedRangeHandle) => void,
observerLoad?: ResizeObserver,
observer?: ResizeObserver,
app: import("../index").App,