Skip to content

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

:bug: Prevent empty first lines in inline code, tags, and keyboard text https://github.com/siyuan-note/siyuan/issues/19679

Daniel4ef5201e8007
diff --git a/app/src/boot/globalEvent/keydown.ts b/app/src/boot/globalEvent/keydown.ts
index 513d57838f..91aed010ed 100644
--- a/app/src/boot/globalEvent/keydown.ts
+++ b/app/src/boot/globalEvent/keydown.ts
@@ -1,5 +1,6 @@
import type {BlockQueryRequestInput} from "../../types/api";
import {isAbove} from "../../util/zIndex";
+import {stripSemanticMarkersFromRangeText} from "../../protyle/util/inlineElementMarker";
import {
copyPlainText,
isMac,
@@ -585,7 +586,7 @@ const editKeydown = (app: App, event: KeyboardEvent) => {
});
copyPlainText(html.trimEnd());
} else {
- copyPlainText(range.toString());
+ copyPlainText(stripSemanticMarkersFromRangeText(range));
}
event.preventDefault();
return true;
diff --git a/app/src/menus/protyle.ts b/app/src/menus/protyle.ts
index 9fb207026e..99c9c3564b 100644
--- a/app/src/menus/protyle.ts
+++ b/app/src/menus/protyle.ts
@@ -78,11 +78,13 @@ import {
TABLE_DEFAULT_COLUMN_WIDTH,
} from "../protyle/util/tableColumnWidth";
import {getParentDocumentID} from "../protyle/util/parentDocument";
+import {prepareInlineElementBoundaryMutation} from "../protyle/util/inlineElementBoundary";
import {getZoomFocusScrollAttr, shouldFocusAfterZoom} from "../protyle/util/focusRestore";
import {scrollCenter} from "../util/highlightById";
import {
getSemanticInlineVisibleText,
- normalizeSemanticInlineElement
+ normalizeSemanticInlineElement,
+ stripSemanticMarkersFromRangeText,
} from "../protyle/util/inlineElementMarker";
const renderAssetList = (element: Element, k: string, position: IPosition, exts: string[] = []) => {
@@ -775,7 +777,7 @@ export const contentMenu = (protyle: IProtyle, nodeElement: Element) => {
accelerator: window.siyuan.config.keymap.editor.general.copyPlainText.custom,
click() {
focusByRange(getEditorRange(nodeElement));
- copyPlainText(getSelection().getRangeAt(0).toString());
+ copyPlainText(stripSemanticMarkersFromRangeText(getSelection().getRangeAt(0)));
}
}).element);
if (protyle.disabled || captionElement) {
@@ -798,6 +800,7 @@ export const contentMenu = (protyle: IProtyle, nodeElement: Element) => {
label: window.siyuan.languages.delete,
click() {
const currentRange = getEditorRange(nodeElement);
+ prepareInlineElementBoundaryMutation(currentRange);
currentRange.insertNode(document.createElement("wbr"));
currentRange.extractContents();
focusByWbr(nodeElement, currentRange);
@@ -823,7 +826,7 @@ export const contentMenu = (protyle: IProtyle, nodeElement: Element) => {
id: "copyPlainText",
label: window.siyuan.languages.copyPlainText,
click() {
- copyPlainText(inlineElement.textContent);
+ copyPlainText(getSemanticInlineVisibleText(inlineElement));
}
}).element);
if (!protyle.disabled) {
diff --git a/app/src/protyle/render/av/richText.ts b/app/src/protyle/render/av/richText.ts
index 2480d76646..3b54b54d2a 100644
--- a/app/src/protyle/render/av/richText.ts
+++ b/app/src/protyle/render/av/richText.ts
@@ -1,6 +1,7 @@
import {escapeHtml} from "../../../util/escape";
import {highlightRender} from "../highlightRender";
import {getAgentLute} from "../setLute";
+import {restoreInlineElementBoundaries} from "../../util/inlineElementBoundary";
import {mathRender} from "../mathRender";
import {
createAVRichTextStyleBackslashEncoding,
@@ -142,6 +143,8 @@ export const getAVRichTextUnsupportedPasteBlocks = (blockDOM: string, images = f
export const sanitizeAVRichTextBlockDOM = (blockDOM: string, images = false) => {
const template = document.createElement("template");
template.innerHTML = blockDOM;
+ // 在过滤临时属性前恢复边界,避免把显示占位符当成富文本内容保存。
+ restoreInlineElementBoundaries(template.content);
template.content.querySelectorAll<HTMLElement>('[data-type^="Node"]').forEach((element) => {
const type = element.dataset.type;
if (!isSupportedAVRichTextBlock(element)) {
diff --git a/app/src/protyle/render/setLute.ts b/app/src/protyle/render/setLute.ts
index 7c0191dfc3..17c62b29e1 100644
--- a/app/src/protyle/render/setLute.ts
+++ b/app/src/protyle/render/setLute.ts
@@ -1,4 +1,5 @@
import {applyLuteMarkdownSyntax} from "./luteMarkdownSyntax";
+import {protectLuteInlineElementBoundaries} from "../util/inlineElementBoundary";
// Lute 配置全部读取全局 window.siyuan.config / window.siyuan.emojis,跨编辑器一致,
// 因此所有 Protyle 编辑器共用同一个 Lute 实例,将内存与初始化开销从 O(编辑器数) 降为 O(1)。
@@ -82,7 +83,7 @@ export const getAgentLute = (options: ILuteOptions): Lute => {
lute.SetExportNormalizeTaskListMarker(true);
lute.SetArbitraryTaskListItemMarker(true);
lute.SetEnsureListItemParagraph(true);
- return lute;
+ return protectLuteInlineElementBoundaries(lute);
};
/**
@@ -136,5 +137,5 @@ const setLute = (options: ILuteOptions) => {
lute.SetExportNormalizeTaskListMarker(true);
lute.SetArbitraryTaskListItemMarker(true);
lute.SetEnsureListItemParagraph(true); // 空列表项下创建子列表前补一个空段落
- return lute;
+ return protectLuteInlineElementBoundaries(lute);
};
diff --git a/app/src/protyle/toolbar/index.ts b/app/src/protyle/toolbar/index.ts
index 2705724963..043a4b1dbc 100644
--- a/app/src/protyle/toolbar/index.ts
+++ b/app/src/protyle/toolbar/index.ts
@@ -1,4 +1,5 @@
import {Divider} from "./Divider";
+import {prepareInlineElementBoundaryMutation} from "../util/inlineElementBoundary";
import {renderMultiSelectToolbar, updateMultiSelectToolbar} from "../../mobile/util/multiSelectToolbar";
import {selectAllLoadedBlocks} from "../wysiwyg/blockSelection";
import {showSelectAllIncompleteTip} from "../util/selectAllTip";
@@ -923,6 +924,7 @@ export class Toolbar {
for (let i = 0; i < attributes.length; i++) {
afterElement.setAttribute(attributes[i].name, attributes[i].value);
}
+ prepareInlineElementBoundaryMutation(this.range);
this.range.insertNode(document.createElement("wbr"));
html = nodeElement.outerHTML;
contents = this.range.extractContents();
@@ -947,6 +949,7 @@ export class Toolbar {
this.range.setStartBefore(this.range.startContainer.parentElement);
}
if (!html) {
+ prepareInlineElementBoundaryMutation(this.range);
this.range.insertNode(document.createElement("wbr"));
html = nodeElement.outerHTML;
contents = this.range.extractContents();
@@ -2425,6 +2428,7 @@ export class Toolbar {
this.subElement.classList.add("fn__none");
} else if (action === "delete") {
const currentRange = getEditorRange(nodeElement);
+ prepareInlineElementBoundaryMutation(currentRange);
currentRange.insertNode(document.createElement("wbr"));
const oldHTML = nodeElement.outerHTML;
currentRange.extractContents();
@@ -2450,7 +2454,7 @@ export class Toolbar {
this.subElement.classList.add("fn__none");
} else if (action === "copyPlainText") {
focusByRange(getEditorRange(nodeElement));
- copyPlainText(getSelection().getRangeAt(0).toString());
+ copyPlainText(stripSemanticMarkersFromRangeText(getSelection().getRangeAt(0)));
this.subElement.classList.add("fn__none");
} else if (action === "pasteAsPlainText") {
focusByRange(getEditorRange(nodeElement));
diff --git a/app/src/protyle/util/inlineElementBoundary.ts b/app/src/protyle/util/inlineElementBoundary.ts
new file mode 100644
index 0000000000..07344a45b0
--- /dev/null
+++ b/app/src/protyle/util/inlineElementBoundary.ts
@@ -0,0 +1,146 @@
+const INLINE_BOUNDARY_ATTRIBUTE = "data-inline-boundary";
+const SEMANTIC_INLINE_SELECTOR = 'span[data-type~="code"],span[data-type~="tag"],span[data-type~="kbd"]';
+export const SEMANTIC_INLINE_HTML_REGEXP = /<span\b[^>]*\bdata-type=(?:"(?:[^"]* )?(?:code|kbd|tag)(?: [^"]*)?"|'(?:[^']* )?(?:code|kbd|tag)(?: [^']*)?')/iu;
+const WORD_JOINER = "\u2060";
+const ZERO_WIDTH_SPACE = "\u200b";
+
+export const hasInlineElementBoundary = (element: Element | null | undefined) =>
+ element?.getAttribute(INLINE_BOUNDARY_ATTRIBUTE) === "true";
+
+export const getInlineElementBoundaryOffset = (node: Node) => {
+ if (node.nodeType !== Node.TEXT_NODE || !node.textContent?.endsWith(WORD_JOINER)) {
+ return -1;
+ }
+ let next = node.nextSibling;
+ while (next?.nodeName === "WBR") {
+ next = next.nextSibling;
+ }
+ return next?.nodeType === Node.ELEMENT_NODE && hasInlineElementBoundary(next as Element) ?
+ node.textContent.length - 1 : -1;
+};
+
+export const getTextWithLegacyInlineBoundary = (node: Node) => {
+ const text = node.textContent || "";
+ const offset = getInlineElementBoundaryOffset(node);
+ return offset < 0 ? text : text.substring(0, offset) + ZERO_WIDTH_SPACE + text.substring(offset + 1);
+};
+
+export const normalizeInlineElementBoundary = (element: HTMLElement) => {
+ if (!element.matches(SEMANTIC_INLINE_SELECTOR)) {
+ return;
+ }
+ let previous = element.previousSibling;
+ while (previous?.nodeName === "WBR") {
+ previous = previous.previousSibling;
+ }
+ if (previous?.nodeType !== Node.TEXT_NODE) {
+ return;
+ }
+ const text = getTextWithLegacyInlineBoundary(previous);
+ let sibling = previous.previousSibling;
+ while (sibling?.nodeName === "WBR" ||
+ (sibling?.nodeType === Node.TEXT_NODE && /^[\s\u200b]*$/u.test(sibling.textContent || ""))) {
+ sibling = sibling.previousSibling;
+ }
+ if (/[^\s\u200b]/u.test(text.substring(0, text.length - 1)) ||
+ (sibling && sibling.nodeName !== "BR")) {
+ // 正文后的元素保留断行机会,避免前面的单词与元素内的首个单词连成整体。
+ restoreInlineElementBoundary(element);
+ return;
+ }
+ if (previous.textContent?.endsWith(ZERO_WIDTH_SPACE)) {
+ // 行首光标占位符不提供断行机会,避免连续文本整体移到空白首行之后。
+ (previous as Text).replaceData(text.length - 1, 1, WORD_JOINER);
+ element.setAttribute(INLINE_BOUNDARY_ATTRIBUTE, "true");
+ }
+};
+
+export const normalizeInlineElementBoundaries = (root: ParentNode) => {
+ root.querySelectorAll<HTMLElement>(SEMANTIC_INLINE_SELECTOR).forEach(normalizeInlineElementBoundary);
+ if (root instanceof HTMLElement) {
+ normalizeInlineElementBoundary(root);
+ }
+};
+
+export const restoreInlineElementBoundary = (element: HTMLElement) => {
+ if (!hasInlineElementBoundary(element)) {
+ return;
+ }
+ let previous = element.previousSibling;
+ while (previous?.nodeName === "WBR") {
+ previous = previous.previousSibling;
+ }
+ if (previous && getInlineElementBoundaryOffset(previous) >= 0) {
+ (previous as Text).replaceData(getInlineElementBoundaryOffset(previous), 1, ZERO_WIDTH_SPACE);
+ }
+ element.removeAttribute(INLINE_BOUNDARY_ATTRIBUTE);
+};
+
+export const restoreInlineElementBoundaries = (root: ParentNode) => {
+ const elements = Array.from(root.querySelectorAll<HTMLElement>(`[${INLINE_BOUNDARY_ATTRIBUTE}]`));
+ if (root instanceof HTMLElement && hasInlineElementBoundary(root)) {
+ elements.unshift(root);
+ }
+ elements.forEach(restoreInlineElementBoundary);
+};
+
+export const prepareInlineElementBoundaryMutation = (range: Range) => {
+ const ancestor = range.commonAncestorContainer;
+ const root = ancestor.nodeType === Node.ELEMENT_NODE ? ancestor as HTMLElement : ancestor.parentElement;
+ if (!root) {
+ return;
+ }
+ const elements = Array.from(root.querySelectorAll<HTMLElement>(`[${INLINE_BOUNDARY_ATTRIBUTE}]`));
+ const inline = root.closest<HTMLElement>(`[${INLINE_BOUNDARY_ATTRIBUTE}]`);
+ if (inline) {
+ elements.unshift(inline);
+ }
+ const selected = elements.filter(element => range.intersectsNode(element));
+ if (selected.length === 0) {
+ return;
+ }
+ // 删除或替换元素前恢复其外部边界,避免元素消失后占位符失去归属。
+ selected.forEach(restoreInlineElementBoundary);
+ requestAnimationFrame(() => {
+ if (root.isConnected) {
+ normalizeInlineElementBoundaries(root);
+ }
+ });
+};
+
+export const restoreInlineElementBoundaryHTML = (html: string) => {
+ if (!html.includes(INLINE_BOUNDARY_ATTRIBUTE)) {
+ return html;
+ }
+ const template = document.createElement("template");
+ template.innerHTML = html;
+ restoreInlineElementBoundaries(template.content);
+ return template.innerHTML;
+};
+
+export const protectLuteInlineElementBoundaries = (lute: Lute): Lute => new Proxy(lute, {
+ get(target, property) {
+ const value = Reflect.get(target, property);
+ if (typeof property !== "string" || typeof value !== "function") {
+ return value;
+ }
+ const consumesHTML = property.startsWith("BlockDOM2") || property === "SpinBlockDOM" ||
+ property === "HTML2BlockDOM";
+ const producesBlockDOM = property.endsWith("BlockDOM") || property === "Md2BlockDOMWithAutoLink";
+ if (!consumesHTML && !producesBlockDOM) {
+ return value;
+ }
+ // Lute 与内核继续接收兼容的零宽空格边界,显示占位符不进入文档内容。
+ return (html: string, ...args: unknown[]) => {
+ const input = consumesHTML ? restoreInlineElementBoundaryHTML(html) : html;
+ const result = value.call(target, input, ...args);
+ if (producesBlockDOM && typeof result === "string" && SEMANTIC_INLINE_HTML_REGEXP.test(result)) {
+ const template = document.createElement("template");
+ template.innerHTML = result;
+ normalizeInlineElementBoundaries(template.content);
+ return template.innerHTML;
+ }
+ return result;
+ };
+ },
+});
diff --git a/app/src/protyle/util/inlineElementMarker.ts b/app/src/protyle/util/inlineElementMarker.ts
index 52178ae47d..7ab8a8ef8e 100644
--- a/app/src/protyle/util/inlineElementMarker.ts
+++ b/app/src/protyle/util/inlineElementMarker.ts
@@ -1,10 +1,19 @@
+import {
+ getInlineElementBoundaryOffset,
+ getTextWithLegacyInlineBoundary,
+ hasInlineElementBoundary,
+ normalizeInlineElementBoundary,
+ restoreInlineElementBoundary,
+ restoreInlineElementBoundaries,
+ SEMANTIC_INLINE_HTML_REGEXP,
+} from "./inlineElementBoundary";
+
export type TSemanticInlineMarkerMode = "canonical" | "legacy" | "remove";
const ZERO_WIDTH_SPACE = "\u200b";
const WORD_JOINER = "\u2060";
const SEMANTIC_INLINE_TYPES = new Set(["code", "kbd", "tag"]);
const INTERNAL_MARKERS = new Set([ZERO_WIDTH_SPACE, WORD_JOINER, "\ufeff"]);
-const SEMANTIC_INLINE_HTML_REGEXP = /<span\b[^>]*\bdata-type=(?:"(?:[^"]* )?(?:code|kbd|tag)(?: [^"]*)?"|'(?:[^']* )?(?:code|kbd|tag)(?: [^']*)?')/iu;
export const hasSemanticInlineType = (type: string | null | undefined) =>
(type || "").split(" ").some(item => SEMANTIC_INLINE_TYPES.has(item));
@@ -98,10 +107,14 @@ export const setSemanticInlineElementMarker = (element: HTMLElement, mode: TSema
};
const ensureLeftExternalBoundary = (element: HTMLElement) => {
- const previousSibling = element.previousSibling;
+ let previousSibling = element.previousSibling;
+ while (previousSibling?.nodeName === "WBR") {
+ previousSibling = previousSibling.previousSibling;
+ }
if (previousSibling?.nodeType === Node.TEXT_NODE) {
const textNode = previousSibling as Text;
- const normalizedText = textNode.data.replace(/\u200b+$/u, "") + ZERO_WIDTH_SPACE;
+ const normalizedText = getTextWithLegacyInlineBoundary(textNode).replace(/\u200b+$/u, "") +
+ (hasInlineElementBoundary(element) ? WORD_JOINER : ZERO_WIDTH_SPACE);
if (textNode.data !== normalizedText) {
textNode.data = normalizedText;
}
@@ -121,7 +134,10 @@ const ensureRightExternalBoundary = (element: HTMLElement) => {
const nextSibling = element.nextSibling;
if (nextSibling?.nodeType === Node.TEXT_NODE) {
const textNode = nextSibling as Text;
- const normalizedText = ZERO_WIDTH_SPACE + textNode.data.replace(/^\u200b+/u, "");
+ let normalizedText = ZERO_WIDTH_SPACE + getTextWithLegacyInlineBoundary(textNode).replace(/^\u200b+/u, "");
+ if (getInlineElementBoundaryOffset(textNode) >= 0) {
+ normalizedText = normalizedText.substring(0, normalizedText.length - 1) + WORD_JOINER;
+ }
if (textNode.data !== normalizedText) {
textNode.data = normalizedText;
}
@@ -145,10 +161,12 @@ export const normalizeSemanticInlineElement = (element: HTMLElement, ensureExter
if (ensureExternalBoundaries) {
ensureLeftExternalBoundary(element);
ensureRightExternalBoundary(element);
+ normalizeInlineElementBoundary(element);
}
};
export const removeSemanticInlineExternalBoundaries = (element: HTMLElement) => {
+ restoreInlineElementBoundary(element);
const previousSibling = element.previousSibling;
if (previousSibling?.nodeType === Node.TEXT_NODE && previousSibling.textContent?.endsWith(ZERO_WIDTH_SPACE)) {
const textNode = previousSibling as Text;
@@ -190,6 +208,9 @@ export const normalizeSemanticInlineElements = (root: ParentNode) => {
};
export const transformSemanticInlineMarkers = (root: ParentNode, mode: TSemanticInlineMarkerMode) => {
+ if (mode !== "canonical") {
+ restoreInlineElementBoundaries(root);
+ }
getSemanticInlineElements(root).forEach(element => setSemanticInlineElementMarker(element, mode));
};
@@ -235,7 +256,7 @@ export const getTextWithoutSemanticMarkers = (root: ParentNode) => {
const visit = (node: Node) => {
if (node.nodeType === Node.TEXT_NODE) {
text += isSemanticInlineMarkerTextNode(node) ?
- stripSemanticInternalMarkerPrefix(node.textContent || "") : node.textContent || "";
+ stripSemanticInternalMarkerPrefix(node.textContent || "") : getTextWithLegacyInlineBoundary(node);
return;
}
Array.from(node.childNodes).forEach(visit);
@@ -256,7 +277,12 @@ export const stripSemanticMarkersFromRangeText = (range: Range) => {
elements.unshift(ancestorElement);
}
const offsets: number[] = [];
+ const externalMarkers: {node: Text, offset: number}[] = [];
elements.forEach(element => {
+ const previous = element.previousSibling;
+ if (previous && getInlineElementBoundaryOffset(previous) >= 0) {
+ externalMarkers.push({node: previous as Text, offset: getInlineElementBoundaryOffset(previous)});
+ }
const textNode = getFirstTextNode(element);
const prefixLength = textNode ? getSemanticInternalMarkerPrefixLength(textNode.data) : 0;
for (let index = 0; textNode && index < prefixLength; index++) {
@@ -274,6 +300,18 @@ export const stripSemanticMarkersFromRangeText = (range: Range) => {
offsets.push(prefixRange.toString().length);
}
});
+ externalMarkers.forEach(({node, offset}) => {
+ const markerRange = node.ownerDocument.createRange();
+ markerRange.setStart(node, offset);
+ markerRange.setEnd(node, offset + 1);
+ if (range.compareBoundaryPoints(Range.START_TO_END, markerRange) <= 0 ||
+ range.compareBoundaryPoints(Range.END_TO_START, markerRange) >= 0) {
+ return;
+ }
+ const prefixRange = range.cloneRange();
+ prefixRange.setEnd(node, offset);
+ offsets.push(prefixRange.toString().length);
+ });
return removeTextOffsets(range.toString(), offsets);
};
@@ -281,7 +319,7 @@ export const getMarkerAwareTextLength = (root: Node, ignoreZWSP: boolean) => {
let length = 0;
const visit = (node: Node) => {
if (node.nodeType === Node.TEXT_NODE) {
- let text = node.textContent || "";
+ let text = getTextWithLegacyInlineBoundary(node);
if (isSemanticInlineMarkerTextNode(node)) {
text = stripSemanticInternalMarkerPrefix(text);
}
@@ -299,7 +337,7 @@ export const getMarkerAwareTextLength = (root: Node, ignoreZWSP: boolean) => {
const getAdjacentSemanticInline = (node: Node, previous: boolean) => {
let sibling = previous ? node.previousSibling : node.nextSibling;
- while (sibling?.nodeType === Node.TEXT_NODE && (sibling.textContent || "").split(ZERO_WIDTH_SPACE).join("") === "") {
+ while (sibling?.nodeType === Node.TEXT_NODE && getTextWithLegacyInlineBoundary(sibling).split(ZERO_WIDTH_SPACE).join("") === "") {
sibling = previous ? sibling.previousSibling : sibling.nextSibling;
}
return sibling?.nodeType === Node.ELEMENT_NODE && isSemanticInlineElement(sibling as Element) ?
@@ -329,7 +367,7 @@ const setRangeAtSemanticEnd = (range: Range, element: HTMLElement) => {
const setRangeBeforeLeftBoundary = (range: Range, element: HTMLElement) => {
const previousSibling = element.previousSibling;
if (previousSibling?.nodeType === Node.TEXT_NODE) {
- const text = previousSibling.textContent || "";
+ const text = getTextWithLegacyInlineBoundary(previousSibling);
range.setStart(previousSibling, text.length - (text.match(/\u200b+$/u)?.[0].length || 0));
} else {
range.setStartBefore(element);
@@ -341,7 +379,7 @@ const setRangeBeforeLeftBoundary = (range: Range, element: HTMLElement) => {
const setRangeAfterRightBoundary = (range: Range, element: HTMLElement) => {
const nextSibling = element.nextSibling;
if (nextSibling?.nodeType === Node.TEXT_NODE) {
- const text = nextSibling.textContent || "";
+ const text = getTextWithLegacyInlineBoundary(nextSibling);
range.setStart(nextSibling, text.match(/^\u200b+/u)?.[0].length || 0);
} else {
range.setStartAfter(element);
@@ -385,8 +423,8 @@ export const getEmptySemanticInlineForDelete = (range: Range, forward: boolean)
}
const adjacentSemantic = getAdjacentSemanticInline(textNode, !forward);
const atAdjacentBoundary = forward ?
- range.startOffset >= textNode.data.length - (textNode.data.match(/\u200b+$/u)?.[0].length || 0) :
- range.startOffset <= (textNode.data.match(/^\u200b+/u)?.[0].length || 0);
+ range.startOffset >= textNode.data.length - (getTextWithLegacyInlineBoundary(textNode).match(/\u200b+$/u)?.[0].length || 0) :
+ range.startOffset <= (getTextWithLegacyInlineBoundary(textNode).match(/^\u200b+/u)?.[0].length || 0);
if (atAdjacentBoundary && adjacentSemantic &&
stripSemanticInternalMarkerPrefix(adjacentSemantic.textContent || "") === "") {
return adjacentSemantic;
@@ -415,13 +453,13 @@ export const moveCaretAcrossSemanticMarker = (range: Range, direction: "left" |
return false;
}
if (direction === "right") {
- const trailingBoundaryLength = textNode.data.match(/\u200b+$/u)?.[0].length || 0;
+ const trailingBoundaryLength = getTextWithLegacyInlineBoundary(textNode).match(/\u200b+$/u)?.[0].length || 0;
const nextSemantic = getAdjacentSemanticInline(textNode, false);
if (nextSemantic && range.startOffset >= textNode.data.length - trailingBoundaryLength) {
return setRangeAtSemanticStart(range, nextSemantic);
}
} else {
- const leadingBoundaryLength = textNode.data.match(/^\u200b+/u)?.[0].length || 0;
+ const leadingBoundaryLength = getTextWithLegacyInlineBoundary(textNode).match(/^\u200b+/u)?.[0].length || 0;
const previousSemantic = getAdjacentSemanticInline(textNode, true);
if (previousSemantic && range.startOffset <= leadingBoundaryLength) {
return setRangeAtSemanticEnd(range, previousSemantic);
@@ -456,12 +494,12 @@ export const moveCaretForSemanticDelete = (range: Range, forward: boolean) => {
}
if (forward) {
const nextSemantic = getAdjacentSemanticInline(textNode, false);
- const boundaryLength = textNode.data.match(/\u200b+$/u)?.[0].length || 0;
+ const boundaryLength = getTextWithLegacyInlineBoundary(textNode).match(/\u200b+$/u)?.[0].length || 0;
if (nextSemantic && range.startOffset >= textNode.data.length - boundaryLength) {
return setRangeAtSemanticStart(range, nextSemantic);
}
const previousSemantic = getAdjacentSemanticInline(textNode, true);
- const leadingBoundaryLength = textNode.data.match(/^\u200b+/u)?.[0].length || 0;
+ const leadingBoundaryLength = getTextWithLegacyInlineBoundary(textNode).match(/^\u200b+/u)?.[0].length || 0;
if (previousSemantic && leadingBoundaryLength > 0 && range.startOffset < leadingBoundaryLength) {
range.setStart(textNode, leadingBoundaryLength);
range.collapse(true);
@@ -469,12 +507,12 @@ export const moveCaretForSemanticDelete = (range: Range, forward: boolean) => {
}
} else {
const previousSemantic = getAdjacentSemanticInline(textNode, true);
- const boundaryLength = textNode.data.match(/^\u200b+/u)?.[0].length || 0;
+ const boundaryLength = getTextWithLegacyInlineBoundary(textNode).match(/^\u200b+/u)?.[0].length || 0;
if (previousSemantic && range.startOffset <= boundaryLength) {
return setRangeAtSemanticEnd(range, previousSemantic);
}
const nextSemantic = getAdjacentSemanticInline(textNode, false);
- const trailingBoundaryLength = textNode.data.match(/\u200b+$/u)?.[0].length || 0;
+ const trailingBoundaryLength = getTextWithLegacyInlineBoundary(textNode).match(/\u200b+$/u)?.[0].length || 0;
if (nextSemantic && trailingBoundaryLength > 0 &&
range.startOffset > textNode.data.length - trailingBoundaryLength) {
range.setStart(textNode, textNode.data.length - trailingBoundaryLength);
diff --git a/app/src/protyle/util/insertHTML.ts b/app/src/protyle/util/insertHTML.ts
index 3bd65781c4..c509ae574d 100644
--- a/app/src/protyle/util/insertHTML.ts
+++ b/app/src/protyle/util/insertHTML.ts
@@ -1,3 +1,4 @@
+import {prepareInlineElementBoundaryMutation} from "./inlineElementBoundary";
import {
hasClosestBlock,
hasClosestByAttribute,
@@ -912,6 +913,7 @@ export const insertHTML = (html: string, protyle: IProtyle, isBlock = false,
isBlock = true;
}
const range = useProtyleRange ? protyle.toolbar.range : getEditorRange(protyle.wysiwyg.element);
+ prepareInlineElementBoundaryMutation(range);
const rangeStartBlockElement = hasClosestBlock(range.startContainer);
const rangeEndBlockElement = hasClosestBlock(range.endContainer);
if (!range.collapsed && rangeStartBlockElement && rangeEndBlockElement &&
diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.ts
index b38cb49eff..aa79cbff4b 100644
--- a/app/src/protyle/util/paste.ts
+++ b/app/src/protyle/util/paste.ts
@@ -1,6 +1,6 @@
import {Constants} from "../../constants";
import {escapeHtml} from "../../util/escape";
-import {getTableCellRichPlainText} from "./tableCellRich";
+import {getTableCellPlainText} from "./tableCellRich";
import {uploadFiles, uploadLocalFiles} from "../upload";
import type {IUploadInsertOptions} from "../upload";
import {
@@ -65,7 +65,7 @@ import {hasDataTransferFiles} from "../upload/localDropFiles";
import {resetPastedQueryEmbedRenderState} from "../render/embedRenderState";
import {getHostCapabilities, sanitizeKernelHTML} from "../../util/hostCapabilities";
import {eventBusHas, hasPluginSubscriber} from "../../plugin/EventBusCore";
-import {normalizeSemanticInlineElements, stripSemanticMarkersFromRangeText} from "./inlineElementMarker";
+import {getTextWithoutSemanticMarkers, normalizeSemanticInlineElements, stripSemanticMarkersFromRangeText} from "./inlineElementMarker";
import {
areProtylePluginExtensionsEnabled,
getProtyleBlockDOMSanitizer,
@@ -194,12 +194,12 @@ export const getPlainText = (blockElement: HTMLElement, isNested = false) => {
// 需在嵌入块后,代码块前
text += Lute.UnEscapeHTMLStr(blockElement.getAttribute("data-content"));
} else if (["NodeHeading", "NodeParagraph"].includes(dataType)) {
- text += blockElement.querySelector("[spellcheck]").textContent;
+ text += getTextWithoutSemanticMarkers(blockElement.querySelector("[spellcheck]"));
} else if ("NodeCodeBlock" === dataType) {
text += removeZWJ(blockElement.querySelector("[spellcheck]").textContent);
} else if (dataType === "NodeTable") {
blockElement.querySelectorAll("th, td").forEach((item) => {
- text += (item.hasAttribute("data-sy-table-cell-rich") ? getTableCellRichPlainText(item) : item.textContent.trim()) + "\t";
+ text += getTableCellPlainText(item).trim() + "\t";
if (!item.nextElementSibling) {
text = text.slice(0, -1) + "\n";
}
diff --git a/app/src/protyle/util/processCode.ts b/app/src/protyle/util/processCode.ts
index 9479bf1d81..a7b9807dae 100644
--- a/app/src/protyle/util/processCode.ts
+++ b/app/src/protyle/util/processCode.ts
@@ -12,6 +12,7 @@ import {customBlockRender} from "../../plugin/customBlockRender";
import {buildSemanticInlineHTML} from "./inlineElementMarker";
import {renderTableCellRichElements} from "../render/tableCellRich";
import {renderEmbedHeadings} from "../render/embedHeading";
+import {normalizeInlineElementBoundaries} from "./inlineElementBoundary";
export const processPasteCode = (html: string, text: string, originalTextHTML: string, protyle: IProtyle) => {
const tempElement = document.createElement("div");
@@ -62,6 +63,7 @@ const RENDER_MAP: Record<string, (previewPanel: Element) => void> = {
};
export const processRender = (previewPanel: Element) => {
+ normalizeInlineElementBoundaries(previewPanel);
renderEmbedHeadings(previewPanel);
renderTableCellRichElements(previewPanel);
// 受限 Lite 编辑器只渲染公式,代码围栏始终作为源码编辑,不能执行图表或 HTML。
diff --git a/app/src/protyle/util/selection.ts b/app/src/protyle/util/selection.ts
index 53ea167ad4..09b3d359e0 100644
--- a/app/src/protyle/util/selection.ts
+++ b/app/src/protyle/util/selection.ts
@@ -1,4 +1,5 @@
import {revealTabsForTarget} from "../render/tabsRender";
+import {getTextWithLegacyInlineBoundary} from "./inlineElementBoundary";
import {isHiddenTabContent} from "../render/tabsVisibility";
import {
getContenteditableElement,
@@ -882,7 +883,7 @@ export const setFirstNodeRange = (editElement: Element, range: Range) => {
};
const getDOMOffset = (textNode: Text, offset: number, skipZWSP: boolean) => {
- const text = textNode.data;
+ const text = getTextWithLegacyInlineBoundary(textNode);
const semanticPrefixLength = getSemanticMarkerPrefixLengthForNode(textNode);
let domOffset = 0;
let textOffset = 0;
diff --git a/app/src/protyle/util/tableCellRich.ts b/app/src/protyle/util/tableCellRich.ts
index d30a55fc5f..fb097aff43 100644
--- a/app/src/protyle/util/tableCellRich.ts
+++ b/app/src/protyle/util/tableCellRich.ts
@@ -1,5 +1,7 @@
import {getAVRichTextBlockDOM, getAVRichTextLute, sanitizeAVRichTextBlockDOM, serializeAVRichTextBlockDOM} from "../render/av/richText";
import {decodeTableCellRich, encodeTableCellRich, TABLE_CELL_RICH_ATTRIBUTE, TABLE_RICH_ATTRIBUTE} from "./tableCellRichValue";
+import {restoreInlineElementBoundaries} from "./inlineElementBoundary";
+import {getTextWithoutSemanticMarkers} from "./inlineElementMarker";
export const TABLE_CELL_INLINE_ATTRIBUTE = "data-sy-table-cell-inline";
@@ -8,7 +10,7 @@ export const updateTableCellContentLayout = (element: HTMLElement, blockDOM: str
element.classList.toggle("table__cell--inline", inline !== null);
const template = document.createElement("template");
template.innerHTML = inline || "";
- const empty = inline !== null && (template.content.textContent || "").replace(/\u200b/g, "") === "" &&
+ const empty = inline !== null && getTextWithoutSemanticMarkers(template.content).replace(/\u200b/g, "") === "" &&
!template.content.querySelector("br, img, [data-type~='inline-math']");
element.classList.toggle("table__cell--empty", empty);
};
@@ -16,6 +18,7 @@ export const updateTableCellContentLayout = (element: HTMLElement, blockDOM: str
export const getTableCellInlineHTML = (blockDOM: string): string | null => {
const template = document.createElement("template");
template.innerHTML = blockDOM;
+ restoreInlineElementBoundaries(template.content);
const blocks = Array.from(template.content.children);
if (blocks.length === 0) {
return "";
@@ -150,7 +153,16 @@ export const getTableCellRichPlainText = (cell: Element) => {
const template = document.createElement("template");
template.innerHTML = getTableCellRichInline(cell);
template.content.querySelectorAll("br").forEach(br => br.replaceWith("\n"));
- return (template.content.textContent || "").replace(/\u200b/g, "").trim();
+ return getTextWithoutSemanticMarkers(template.content).replace(/\u200b/g, "").trim();
+};
+
+export const getTableCellPlainText = (cell: Element) => {
+ if (cell.hasAttribute(TABLE_CELL_RICH_ATTRIBUTE)) {
+ return getTableCellRichPlainText(cell);
+ }
+ const clone = cell.cloneNode(true) as Element;
+ clone.querySelectorAll("br").forEach(br => br.replaceWith("\n"));
+ return getTextWithoutSemanticMarkers(clone).replace(/\u200b/g, "").replace(/\n+$/g, "");
};
export const renderTableCellRich = (cell: Element) => {
diff --git a/app/src/protyle/util/tableCellRichNavigation.ts b/app/src/protyle/util/tableCellRichNavigation.ts
index d2af8f6d90..9f3073f140 100644
--- a/app/src/protyle/util/tableCellRichNavigation.ts
+++ b/app/src/protyle/util/tableCellRichNavigation.ts
@@ -1,5 +1,6 @@
import {buildTableGrid, getVerticalTableCell} from "./table";
import {isCaretAtVerticalBoundary} from "../wysiwyg/verticalCaret";
+import {stripSemanticMarkersFromRangeText} from "./inlineElementMarker";
export const isTableCellCaretAtBoundary = (element: HTMLElement, range: Range, key: string) => {
if (!range.collapsed || !element.contains(range.startContainer)) {
@@ -21,7 +22,7 @@ export const isTableCellCaretAtBoundary = (element: HTMLElement, range: Range, k
} else {
remaining.setStart(range.startContainer, range.startOffset);
}
- return remaining.toString().replace(/\u200b/g, "") === "" &&
+ return stripSemanticMarkersFromRangeText(remaining).replace(/\u200b/g, "") === "" &&
!remaining.cloneContents().querySelector("br, img, [data-type='inline-math']");
};
diff --git a/app/src/protyle/util/tableControl.ts b/app/src/protyle/util/tableControl.ts
index ce010ff9cd..5d567e07ca 100644
--- a/app/src/protyle/util/tableControl.ts
+++ b/app/src/protyle/util/tableControl.ts
@@ -1,5 +1,5 @@
import {MenuItem} from "../../menus/Menu";
-import {clearTableCellContent, getTableCellRichPlainText, mergeTableCellContents} from "./tableCellRich";
+import {clearTableCellContent, getTableCellPlainText, mergeTableCellContents} from "./tableCellRich";
import {renderTableCellRichElements} from "../render/tableCellRich";
import {updateTransaction} from "../wysiwyg/transaction";
import {copyPlainText, encodeBase64, isMac, readClipboard} from "./compatibility";
@@ -179,9 +179,6 @@ const replaceCellTag = (cell: HTMLTableCellElement, tag: "th" | "td") => {
return newCell;
};
-const getCellText = (cell: HTMLTableCellElement) => cell.hasAttribute("data-sy-table-cell-rich") ?
- getTableCellRichPlainText(cell) : cell.innerText.replace(/\n+$/g, "");
-
export const getCommonTableCellStyle = (cells: HTMLTableCellElement[], property: string) => {
if (cells.length === 0) {
return undefined;
@@ -2706,7 +2703,7 @@ export class TableControl {
container.innerHTML = html;
const rows = Array.from(container.querySelectorAll("tr"));
const text = rows.map(row => Array.from(row.querySelectorAll("th, td")).filter(cell =>
- !cell.classList.contains("fn__none")).map(cell => getCellText(cell as HTMLTableCellElement)).join("\t")).join("\n");
+ !cell.classList.contains("fn__none")).map(cell => getTableCellPlainText(cell)).join("\t")).join("\n");
const textSiyuan = `<div data-node-id="${Lute.NewNodeID()}" data-type="NodeTable" class="table"><div contenteditable="true" spellcheck="false">${html}<div class="protyle-action__table"><div class="table__resize"></div><div class="table__select"></div></div></div><div class="protyle-attr" contenteditable="false">\u200b</div></div>`;
const textHTML = `<!--data-siyuan='${encodeBase64(textSiyuan)}'-->${removeZWJ(textSiyuan)}`;
return {text, textSiyuan, textHTML};
diff --git a/app/src/protyle/wysiwyg/getBlock.ts b/app/src/protyle/wysiwyg/getBlock.ts
index 5bc3321289..06b11c6a94 100644
--- a/app/src/protyle/wysiwyg/getBlock.ts
+++ b/app/src/protyle/wysiwyg/getBlock.ts
@@ -2,6 +2,7 @@ import {isHiddenTabContent} from "../render/tabsVisibility";
import {hasClosestBlock, hasClosestByClassName, isInEmbedBlock} from "../util/hasClosest";
import {Constants} from "../../constants";
import {getTextWithoutSemanticMarkers} from "../util/inlineElementMarker";
+import {getTextWithLegacyInlineBoundary} from "../util/inlineElementBoundary";
export interface IEmbedOperationContext {
resultElement: HTMLElement;
@@ -460,9 +461,9 @@ export const fixAdjacentTags = (editableElement: Element) => {
const tagSpan = node as HTMLElement;
if (tagSpan.tagName === "SPAN" &&
(tagSpan.getAttribute("data-type") || "").split(" ").includes("tag")) {
- // 向后查找跳过 ZWSP 文本节点和 <wbr> 后的下一个节点
+ // 向后查找,跳过光标边界文本节点和 <wbr>。
let after = next;
- while (after && ((after.nodeType === 3 && after.textContent === Constants.ZWSP) ||
+ while (after && ((after.nodeType === 3 && getTextWithLegacyInlineBoundary(after) === Constants.ZWSP) ||
(after.nodeType === 1 && (after as HTMLElement).tagName === "WBR"))) {
after = after.nextSibling;
}
diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.ts
index bd70ef82d2..cbe0413a0b 100644
--- a/app/src/protyle/wysiwyg/index.ts
+++ b/app/src/protyle/wysiwyg/index.ts
@@ -1,4 +1,5 @@
import {visibleTabsSelectionHTML} from "../render/tabsVisibility";
+import {prepareInlineElementBoundaryMutation} from "../util/inlineElementBoundary";
import {repairHiddenTabSelection} from "../util/tabsSelection";
import {isTabTextBoundary} from "./tabsBoundary";
import {captureCompositionText} from "./compositionCaret";
@@ -3312,6 +3313,7 @@ export class WYSIWYG {
updateTransaction(protyle, nodeElement, oldHTML);
} else {
const id = nodeElement.getAttribute("data-node-id");
+ prepareInlineElementBoundaryMutation(range);
setInsertWbrHTML(nodeElement, range, protyle);
const oldHTML = protyle.wysiwyg.lastHTMLs[id] || nodeElement.outerHTML;
const tempElement = document.createElement("div");
@@ -3958,6 +3960,9 @@ export class WYSIWYG {
}
});
this.element.addEventListener("keydown", (event: KeyboardEvent) => {
+ if ((event.key === "Backspace" || event.key === "Delete") && getSelection().rangeCount > 0) {
+ prepareInlineElementBoundaryMutation(getSelection().getRangeAt(0));
+ }
if (isInAndroid()) {
if (event.key === "Unidentified") {
mobileUnidentifiedInputRange = undefined;
@@ -4164,6 +4169,10 @@ export class WYSIWYG {
});
this.element.addEventListener("beforeinput", async (event: InputEvent) => {
+ if ((event.inputType.startsWith("insert") || event.inputType.startsWith("delete")) &&
+ getSelection().rangeCount > 0) {
+ prepareInlineElementBoundaryMutation(getSelection().getRangeAt(0));
+ }
if (!event.isComposing && ["deleteContentBackward", "deleteContentForward"].includes(event.inputType) &&
!getBlockSelectionModeElement(this.element) && !this.element.querySelector(".protyle-wysiwyg--select") &&
isTabTextBoundary(getEditorRange(this.element), event.inputType === "deleteContentBackward")) {
diff --git a/app/src/protyle/wysiwyg/input.ts b/app/src/protyle/wysiwyg/input.ts
index 43acfbffa8..4f2136e5a3 100644
--- a/app/src/protyle/wysiwyg/input.ts
+++ b/app/src/protyle/wysiwyg/input.ts
@@ -4,6 +4,7 @@ import * as dayjs from "dayjs";
import {transaction, turnsOneInto, updateTransaction, wrapBlockInBlockquote} from "./transaction";
import {mathRender} from "../render/mathRender";
import {highlightRender} from "../render/highlightRender";
+import {restoreInlineElementBoundaryHTML} from "../util/inlineElementBoundary";
import {
fixAdjacentTags,
getContenteditableElement,
@@ -402,6 +403,7 @@ export const input = async (protyle: IProtyle, blockElement: HTMLElement, range:
// 相邻标签之间插入空格区隔,避免 SpinBlockDOM 解析时合并为一个标签 https://github.com/siyuan-note/siyuan/issues/18191
// 使用迭代替换处理多个连续相邻标签(全局正则无法匹配重叠情况)
// 若中间含有 <wbr>(光标标记),替换后需保留 <wbr>,否则 focusByWbr 无法定位光标
+ html = restoreInlineElementBoundaryHTML(html);
let prevHTML: string;
do {
prevHTML = html;
diff --git a/app/src/protyle/wysiwyg/remove.ts b/app/src/protyle/wysiwyg/remove.ts
index 73ad174fa6..2d5b26c17f 100644
--- a/app/src/protyle/wysiwyg/remove.ts
+++ b/app/src/protyle/wysiwyg/remove.ts
@@ -1,4 +1,5 @@
import {isHiddenTabContent} from "../render/tabsVisibility";
+import {prepareInlineElementBoundaryMutation} from "../util/inlineElementBoundary";
import {captureTabsRemoval} from "./tabsRemoval";
import {
focusBlock,
@@ -394,6 +395,7 @@ const deleteCrossBlockRangeContents = (rangesByBlock: ReturnType<typeof getCross
.filter(refElement => refElement.getAttribute("data-type")?.split(" ").includes("block-ref") &&
refElement.getAttribute("data-subtype") === "d")
.map(refElement => [refElement, refElement.textContent] as const));
+ prepareInlineElementBoundaryMutation(item.range);
item.range.deleteContents();
dynamicRefTexts.forEach((text, refElement) => {
if (refElement.isConnected && refElement.textContent !== text) {
diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.ts
index 0cdd4fd2f9..47dcca821f 100644
--- a/app/src/protyle/wysiwyg/transaction.ts
+++ b/app/src/protyle/wysiwyg/transaction.ts
@@ -1,4 +1,5 @@
import {fetchPost, fetchSyncPost} from "../../util/fetch";
+import {restoreInlineElementBoundaryHTML} from "../util/inlineElementBoundary";
import {getEditorTransaction} from "../util/transactionContract";
import {
focusBlock,
@@ -2361,6 +2362,11 @@ export const transaction = (protyle: IProtyle, doOperations: IOperation[], undoO
}
cleanBlockSelectionModeOperations(doOperations);
cleanBlockSelectionModeOperations(undoOperations);
+ [doOperations, undoOperations].forEach(operations => operations?.forEach(operation => {
+ if ((operation.action === "update" || operation.action === "insert") && typeof operation.data === "string") {
+ operation.data = restoreInlineElementBoundaryHTML(operation.data);
+ }
+ }));
doOperations.forEach(operation => {
if (operation.action === "update" && typeof operation.data === "string") {
undoOperations?.filter((undo): undo is Extract<IOperation, {action: "update"}> =>