An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Improve long text wrapping in mixed content https://github.com/siyuan-note/siyuan/issues/19679
Daniela3e1803225df
diff --git a/app/src/assets/scss/protyle/_wysiwyg.scss b/app/src/assets/scss/protyle/_wysiwyg.scssindex c8653b967d..96f628826b 100644--- a/app/src/assets/scss/protyle/_wysiwyg.scss+++ b/app/src/assets/scss/protyle/_wysiwyg.scss@@ -481,6 +481,7 @@}}+ span[data-inline-wrap="token"],span[data-inline-wrap][data-type~="code"],span[data-inline-wrap][data-type~="tag"],span[data-inline-wrap][data-type~="kbd"] {diff --git a/app/src/protyle/util/inlineElementBoundary.ts b/app/src/protyle/util/inlineElementBoundary.tsindex 77b975ac9c..21a12f7d38 100644--- a/app/src/protyle/util/inlineElementBoundary.ts+++ b/app/src/protyle/util/inlineElementBoundary.ts@@ -1,3 +1,5 @@+import {unwrapLongTextRuns} from "./longTextWrap";+const INLINE_BOUNDARY_ATTRIBUTE = "data-inline-boundary";const INLINE_WRAP_ATTRIBUTE = "data-inline-wrap";const SEMANTIC_INLINE_SELECTOR = 'span[data-type~="code"],span[data-type~="tag"],span[data-type~="kbd"]';@@ -83,6 +85,7 @@ export const restoreInlineElementBoundary = (element: HTMLElement) => {};export const restoreInlineElementBoundaries = (root: ParentNode) => {+ unwrapLongTextRuns(root);root.querySelectorAll(`[${INLINE_WRAP_ATTRIBUTE}]`).forEach(element =>element.removeAttribute(INLINE_WRAP_ATTRIBUTE));if (root instanceof HTMLElement) {diff --git a/app/src/protyle/util/inlineElementMarker.ts b/app/src/protyle/util/inlineElementMarker.tsindex 7ab8a8ef8e..46c4ce5081 100644--- a/app/src/protyle/util/inlineElementMarker.ts+++ b/app/src/protyle/util/inlineElementMarker.ts@@ -5,6 +5,7 @@ import {normalizeInlineElementBoundary,restoreInlineElementBoundary,restoreInlineElementBoundaries,+ restoreInlineElementBoundaryHTML,SEMANTIC_INLINE_HTML_REGEXP,} from "./inlineElementBoundary";@@ -216,7 +217,7 @@ export const transformSemanticInlineMarkers = (root: ParentNode, mode: TSemanticexport const transformSemanticInlineHTML = (html: string, mode: TSemanticInlineMarkerMode) => {if (!SEMANTIC_INLINE_HTML_REGEXP.test(html)) {- return html;+ return mode === "canonical" ? html : restoreInlineElementBoundaryHTML(html);}const template = document.createElement("template");template.innerHTML = html;diff --git a/app/src/protyle/util/longTextWrap.test.ts b/app/src/protyle/util/longTextWrap.test.tsnew file mode 100644index 0000000000..d8c0da47f6--- /dev/null+++ b/app/src/protyle/util/longTextWrap.test.ts@@ -0,0 +1,25 @@+import * as assert from "node:assert/strict";+import {describe, it} from "node:test";+import {getLongTextRanges} from "./longTextWrap";++describe("long text runs", () => {+ it("finds long runs after Chinese and spaces without including ordinary words", () => {+ const text = "测试" + "1".repeat(94) + " ordinary words " + "a".repeat(63) + " end";+ assert.deepEqual(getLongTextRanges(text).map(range => text.substring(range.start, range.end)),+ ["1".repeat(94), "a".repeat(63)]);+ assert.deepEqual(getLongTextRanges("test " + "3".repeat(32)), [{start: 5, end: 37}]);+ });++ it("counts each run independently at the threshold", () => {+ assert.deepEqual(getLongTextRanges("a".repeat(31) + " " + "b".repeat(31)), []);+ assert.deepEqual(getLongTextRanges("a".repeat(32)), [{start: 0, end: 32}]);+ assert.deepEqual(getLongTextRanges("ordinary words remain intact".repeat(4)), []);+ assert.deepEqual(getLongTextRanges("测试".repeat(32)), []);+ });++ it("preserves explicit joiners and locates runs after semantic prefixes", () => {+ assert.deepEqual(getLongTextRanges("\u2060" + "x".repeat(32)), [{start: 1, end: 33}]);+ assert.deepEqual(getLongTextRanges("x".repeat(32) + "\u2060" + "y".repeat(32)), []);+ assert.deepEqual(getLongTextRanges("x".repeat(32) + "\ufeff" + "y".repeat(32)), []);+ });+});diff --git a/app/src/protyle/util/longTextWrap.ts b/app/src/protyle/util/longTextWrap.tsnew file mode 100644index 0000000000..a6e9ca50cc--- /dev/null+++ b/app/src/protyle/util/longTextWrap.ts@@ -0,0 +1,209 @@+const LONG_TEXT_SELECTOR = 'span[data-inline-wrap="token"]';+const TEXT_CONTAINER_SELECTOR = "[contenteditable], [data-table-cell-content]";+const EXCLUDED_SELECTOR = 'pre, script, style, svg, textarea, [data-type="NodeCodeBlock"], ' ++ '[data-type="NodeHTMLBlock"], [data-type="NodeMathBlock"], [data-type~="inline-math"], ' ++ '[data-type~="img"], .protyle-attr, .protyle-action';++// 仅为至少 32 个连续字母、数字或下划线提供字符间断行,空格和中文两侧的普通单词保持完整。+export const getLongTextRanges = (text: string) => {+ const ranges: {start: number, end: number}[] = [];+ for (const token of text.matchAll(/(?:[^\s\u200b]|\ufeff)+/gu)) {+ const prefix = token[0].match(/^[\u2060\ufeff]+/u)?.[0].length || 0;+ const content = token[0].substring(prefix);+ // 用户在连续文本内设置的禁止断行字符优先于自动折行。+ if (/[\u2060\ufeff]/u.test(content)) {+ continue;+ }+ for (const match of content.matchAll(/[a-zA-Z0-9_]{32,}/g)) {+ const start = token.index + prefix + match.index;+ ranges.push({start, end: start + match[0].length});+ }+ }+ return ranges;+};++export const unwrapLongTextRuns = (root: ParentNode) => {+ const parents = new Set<Node>();+ const elements = Array.from(root.querySelectorAll<HTMLElement>(LONG_TEXT_SELECTOR));+ if (root instanceof HTMLElement && root.matches(LONG_TEXT_SELECTOR)) {+ elements.unshift(root);+ }+ elements.forEach(element => {+ element.removeAttribute("data-inline-wrap");+ // 格式操作可能把真实样式附加到显示节点,清理时保留这些用户设置。+ if (!element.hasAttribute("data-type") && !element.hasAttribute("style")) {+ if (element.parentNode) {+ parents.add(element.parentNode);+ }+ element.replaceWith(...Array.from(element.childNodes));+ }+ });+ parents.forEach(parent => parent.normalize());+};++const preserveSelection = (root: Element, update: () => void) => {+ const selection = root.ownerDocument.getSelection();+ const capture = (node: Node, offset: number) => {+ if (!node || !root.contains(node)) {+ return {node, offset};+ }+ const range = root.ownerDocument.createRange();+ range.selectNodeContents(root);+ range.setEnd(node, offset);+ return {node, offset, textOffset: range.toString().length};+ };+ const anchor = selection?.rangeCount ? capture(selection.anchorNode, selection.anchorOffset) : undefined;+ const focus = selection?.rangeCount ? capture(selection.focusNode, selection.focusOffset) : undefined;+ update();+ if (!anchor || !focus || (anchor.textOffset === undefined && focus.textOffset === undefined)) {+ return;+ }+ const resolve = (position: ReturnType<typeof capture>) => {+ if (position.textOffset === undefined) {+ return position;+ }+ let offset = position.textOffset;+ const walker = root.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_TEXT);+ let node: Node;+ while ((node = walker.nextNode())) {+ if (offset <= node.textContent.length) {+ return {node, offset};+ }+ offset -= node.textContent.length;+ }+ return {node: root, offset: root.childNodes.length};+ };+ const start = resolve(anchor);+ const end = resolve(focus);+ selection.setBaseAndExtent(start.node, start.offset, end.node, end.offset);+};++const normalizedContent = new WeakMap<Element, string>();++const wrapContainer = (root: Element) => {+ if (root.closest(EXCLUDED_SELECTOR) ||+ (!root.querySelector(LONG_TEXT_SELECTOR) && !/[a-zA-Z0-9_]{32}/.test(root.textContent || ""))) {+ return;+ }+ if (normalizedContent.get(root) === root.innerHTML) {+ return;+ }+ preserveSelection(root, () => {+ unwrapLongTextRuns(root);+ root.normalize();+ const nodes: {node: Text, start: number}[] = [];+ let text = "";+ const visit = (node: Node) => {+ if (node.nodeType === Node.TEXT_NODE) {+ nodes.push({node: node as Text, start: text.length});+ text += node.textContent;+ return;+ }+ if (node.nodeType !== Node.ELEMENT_NODE) {+ return;+ }+ const element = node as Element;+ if (element !== root && (element.matches(EXCLUDED_SELECTOR) ||+ element.matches('[data-inline-wrap]:not([data-inline-wrap="token"])'))) {+ text += "\n";+ return;+ }+ const boundary = /^(BR|DIV|P|TD|TH)$/u.test(element.tagName);+ if (boundary) {+ text += "\n";+ }+ Array.from(element.childNodes).forEach(visit);+ if (boundary) {+ text += "\n";+ }+ };+ visit(root);+ const ranges = getLongTextRanges(text);+ nodes.forEach(({node, start}) => {+ const matches = ranges.filter(range => range.start < start + node.length && range.end > start);+ if (matches.length === 0) {+ return;+ }+ const fragment = root.ownerDocument.createDocumentFragment();+ let offset = 0;+ matches.forEach(range => {+ const from = Math.max(0, range.start - start);+ const to = Math.min(node.length, range.end - start);+ if (from > offset) {+ fragment.append(node.data.substring(offset, from));+ }+ const span = root.ownerDocument.createElement("span");+ span.setAttribute("data-inline-wrap", "token");+ span.textContent = node.data.substring(from, to);+ fragment.append(span);+ offset = to;+ });+ if (offset < node.length) {+ fragment.append(node.data.substring(offset));+ }+ node.replaceWith(fragment);+ });+ });+ normalizedContent.set(root, root.innerHTML);+};++export const normalizeLongTextRuns = (root: ParentNode) => {+ const containers = Array.from(root.querySelectorAll(TEXT_CONTAINER_SELECTOR));+ if (root instanceof Element && (root.matches(TEXT_CONTAINER_SELECTOR) || root.closest(TEXT_CONTAINER_SELECTOR))) {+ containers.unshift(root);+ }+ // 外层可编辑区域已经包含其子区域,避免对同一段文字重复处理。+ const owners = new Set(containers);+ containers.filter(element => {+ let parent = element.parentElement;+ while (parent) {+ if (owners.has(parent)) {+ return false;+ }+ parent = parent.parentElement;+ }+ return true;+ })+ .forEach(wrapContainer);+};++const configuredEditors = new WeakSet<Element>();+const composingEditors = new WeakSet<Element>();+const inputDepth = new WeakMap<Element, number>();++export const suspendLongTextRuns = (editor: Element) => {+ inputDepth.set(editor, (inputDepth.get(editor) || 0) + 1);+ return () => {+ inputDepth.set(editor, inputDepth.get(editor) - 1);+ renderLongTextRuns(editor);+ };+};++export const renderLongTextRuns = (root: Element) => {+ const editor = root.closest(".protyle-wysiwyg");+ if (!editor) {+ normalizeLongTextRuns(root);+ return;+ }+ if (!configuredEditors.has(editor)) {+ configuredEditors.add(editor);+ const unwrapAtInput = (event: Event) => {+ const target = event.target instanceof Element ? event.target.closest(TEXT_CONTAINER_SELECTOR) : null;+ if (target?.querySelector(LONG_TEXT_SELECTOR)) {+ preserveSelection(target, () => unwrapLongTextRuns(target));+ }+ };+ // 输入期间使用原始文本节点,浏览器完成编辑后再更新显示节点,避免影响输入法和编辑器解析。+ editor.addEventListener("beforeinput", unwrapAtInput, true);+ editor.addEventListener("compositionstart", event => {+ composingEditors.add(editor);+ unwrapAtInput(event);+ }, true);+ editor.addEventListener("compositionend", () => {+ composingEditors.delete(editor);+ });+ }+ if (!composingEditors.has(editor) && !inputDepth.get(editor)) {+ normalizeLongTextRuns(root);+ }+};diff --git a/app/src/protyle/util/processCode.ts b/app/src/protyle/util/processCode.tsindex 12dbdf855d..aa91cf1565 100644--- a/app/src/protyle/util/processCode.ts+++ b/app/src/protyle/util/processCode.ts@@ -13,6 +13,7 @@ import {buildSemanticInlineHTML} from "./inlineElementMarker";import {renderTableCellRichElements} from "../render/tableCellRich";import {renderEmbedHeadings} from "../render/embedHeading";import {normalizeInlineElementBoundaries} from "./inlineElementBoundary";+import {renderLongTextRuns} from "./longTextWrap";export const processPasteCode = (html: string, text: string, originalTextHTML: string, protyle: IProtyle) => {const tempElement = document.createElement("div");@@ -63,6 +64,7 @@ const RENDER_MAP: Record<string, (previewPanel: Element) => void> = {export const processRender = (previewPanel: Element) => {normalizeInlineElementBoundaries(previewPanel);+ renderLongTextRuns(previewPanel);renderEmbedHeadings(previewPanel);renderTableCellRichElements(previewPanel);// 受限 Lite 编辑器只渲染公式,代码围栏始终作为源码编辑,不能执行图表或 HTML。diff --git a/app/src/protyle/util/tableCellRichLute.test.ts b/app/src/protyle/util/tableCellRichLute.test.tsindex d53fc0d3ef..e14cc21e1c 100644--- a/app/src/protyle/util/tableCellRichLute.test.ts+++ b/app/src/protyle/util/tableCellRichLute.test.ts@@ -262,7 +262,7 @@ test("table cells insert code through slash and Enter without losing soft breaks.replace(/^export (?:type )?\{[\s\S]*?\}(?: from "[^"]+")?;\r?\n/gm, "").replace(/^export /gm, ""), {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;const read = (file: string) => readFileSync(path.join(__dirname, file), "utf8");- const source = ["inlineElementBoundary.ts", "../toolbar/fontFamilyCore.ts", "../../util/escape.ts",+ const source = ["longTextWrap.ts", "inlineElementBoundary.ts", "../toolbar/fontFamilyCore.ts", "../../util/escape.ts","../render/setLute.ts", "../render/av/richTextValue.ts", "../render/av/richText.ts","../wysiwyg/taskListMarker.ts", "../wysiwyg/codeBlockEnter.ts", "tableCellRichLute.ts", "tableCellRichValue.ts","tableCellRich.ts"].map(file => compile(read(file))).join("\n");diff --git a/app/src/protyle/util/undoReplayFocus.test.ts b/app/src/protyle/util/undoReplayFocus.test.tsindex 7fc0112680..103f672909 100644--- a/app/src/protyle/util/undoReplayFocus.test.ts+++ b/app/src/protyle/util/undoReplayFocus.test.ts@@ -219,9 +219,10 @@ test("undo replay restores recorded carets across paragraphs, table cells and emconst source = compile(`class TableCutControl {${methods.map(method => method.getText(tableSource)).join("\n")}}`) +extract("tableCellRich.ts", ["clearTableCellContent"]) +compile(readFileSync(path.join(__dirname, "hasClosest.ts"), "utf8")) ++ moduleSource("longTextWrap.ts", ["unwrapLongTextRuns"]) +moduleSource("inlineElementBoundary.ts", ["getInlineElementBoundaryOffset", "getTextWithLegacyInlineBoundary","hasInlineElementBoundary", "normalizeInlineElementBoundary", "restoreInlineElementBoundary",- "restoreInlineElementBoundaries", "SEMANTIC_INLINE_HTML_REGEXP"]) ++ "restoreInlineElementBoundaries", "restoreInlineElementBoundaryHTML", "SEMANTIC_INLINE_HTML_REGEXP"]) +moduleSource("inlineElementMarker.ts", ["stripSemanticMarkersFromRangeText", "getMarkerAwareTextLength","getSemanticMarkerPrefixLengthForNode"]) +extract("tableCellRichValue.ts", ["TABLE_CELL_RICH_ATTRIBUTE"]) +diff --git a/app/src/protyle/wysiwyg/input.ts b/app/src/protyle/wysiwyg/input.tsindex 4f2136e5a3..192bac77e7 100644--- a/app/src/protyle/wysiwyg/input.ts+++ b/app/src/protyle/wysiwyg/input.ts@@ -5,6 +5,7 @@ import {transaction, turnsOneInto, updateTransaction, wrapBlockInBlockquote} froimport {mathRender} from "../render/mathRender";import {highlightRender} from "../render/highlightRender";import {restoreInlineElementBoundaryHTML} from "../util/inlineElementBoundary";+import {suspendLongTextRuns} from "../util/longTextWrap";import {fixAdjacentTags,getContenteditableElement,@@ -112,7 +113,7 @@ export const beforeBlockquoteInput = (protyle: IProtyle, event: InputEvent) => {return true;};-export const input = async (protyle: IProtyle, blockElement: HTMLElement, range: Range, needRender = true,+const inputBlock = async (protyle: IProtyle, blockElement: HTMLElement, range: Range, needRender = true,event?: InputEvent, inputOperations?: IInputOperations) => {if (!blockElement.parentElement) {// 不同 windows 版本下输入法会多次触发 input,导致 outerhtml 赋值的块丢失@@ -565,6 +566,15 @@ export const input = async (protyle: IProtyle, blockElement: HTMLElement, range:updateInput(html, protyle, id, inputOperations);};+export const input = async (...args: Parameters<typeof inputBlock>) => {+ const resume = suspendLongTextRuns(args[0].wysiwyg.element);+ try {+ await inputBlock(...args);+ } finally {+ resume();+ }+};+const updateInput = (html: string, protyle: IProtyle, id: string, inputOperations?: IInputOperations) => {const tempElement = document.createElement("template");tempElement.innerHTML = html;