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: Support rich text in database text fields https://github.com/siyuan-note/siyuan/issues/11553
Daniela1975349d0e5
diff --git a/app/src/assets/scss/business/_ai_agent.scss b/app/src/assets/scss/business/_ai_agent.scssindex a3eda747c8..746a43bd0a 100644--- a/app/src/assets/scss/business/_ai_agent.scss+++ b/app/src/assets/scss/business/_ai_agent.scss@@ -1206,7 +1206,8 @@}}-.protyle-hint--agent-overlay {+.protyle-hint--agent-overlay,+.protyle-hint--lite-overlay {font-size: var(--b3-font-size);}diff --git a/app/src/assets/scss/business/_av.scss b/app/src/assets/scss/business/_av.scssindex 28ac48316e..58374e03b8 100644--- a/app/src/assets/scss/business/_av.scss+++ b/app/src/assets/scss/business/_av.scss@@ -278,6 +278,62 @@left: 0;}+ &__richtext-mask {+ background: rgba(0, 0, 0, .08);+ }++ &__richtext-editor {+ position: absolute;+ display: flex;+ flex-direction: column;+ min-height: 240px;+ overflow: hidden;+ border: 1px solid var(--b3-border-color);+ border-radius: var(--b3-border-radius-b);+ background: var(--b3-theme-background);+ box-shadow: var(--b3-dialog-shadow);++ &--mobile {+ position: fixed;+ inset: env(safe-area-inset-top) 0 0;+ max-height: none;+ border: 0;+ border-radius: 0;+ }+ }++ &__richtext-host {+ min-height: 0;+ flex: 1;++ > .protyle,+ .protyle-content {+ height: 100%;+ }++ .protyle-content {+ overflow: auto;+ }++ .protyle-wysiwyg {+ min-height: 100%;+ padding: 12px;+ box-sizing: border-box;+ outline: none;+ font-size: var(--b3-font-size-editor);+ }+ }++ &__richtext-actions {+ display: flex;+ flex-shrink: 0;+ justify-content: flex-end;+ gap: 8px;+ padding: 8px;+ border-top: 1px solid var(--b3-border-color);+ background: var(--b3-theme-surface);+ }+&__scroll {overflow: auto hidden;position: relative;@@ -1059,6 +1115,40 @@&__celltext {overflow: hidden;+ &--rich {+ width: 100%;+ max-height: 8.125em;+ overflow: hidden;+ white-space: normal;+ font: inherit;++ > p,+ > blockquote,+ > ul,+ > ol,+ > .code-block,+ > .language-math {+ margin: 0;+ }++ li > p,+ > p,+ blockquote > p {+ min-height: 0;+ padding: 0;+ margin: 0;+ line-height: inherit;+ }++ > :not(:first-child) {+ margin-top: 4px;+ }+ }++ &--plain {+ white-space: pre-wrap;+ }+&--url,&--ref {border-bottom: .5px solid var(--b3-border-color);@@ -1081,6 +1171,10 @@}}+ &__cell[data-wrap="false"] > &__celltext--rich {+ max-height: 1.625em;+ }+&__checkbox {color: var(--b3-theme-on-surface);height: 1.625em;diff --git a/app/src/boot/globalEvent/click.ts b/app/src/boot/globalEvent/click.tsindex 23cfe1990d..88776741d0 100644--- a/app/src/boot/globalEvent/click.ts+++ b/app/src/boot/globalEvent/click.ts@@ -60,6 +60,7 @@ export const globalClick = (event: MouseEvent & { target: HTMLElement }) => {!hasClosestByClassName(event.target, "b3-dialog--open", true) &&!hasClosestByClassName(event.target, "b3-menu") &&!hasClosestByClassName(event.target, "block__popover") &&+ !hasClosestByClassName(event.target, "protyle-hint--lite-overlay") &&!hasClosestByClassName(event.target, "protyle-hint--agent-overlay") &&!hasClosestByClassName(event.target, "dock") &&!hasClosestByClassName(event.target, "layout--float", true)diff --git a/app/src/boot/globalEvent/mousemove.ts b/app/src/boot/globalEvent/mousemove.tsindex 518f616a76..51a8c6441b 100644--- a/app/src/boot/globalEvent/mousemove.ts+++ b/app/src/boot/globalEvent/mousemove.ts@@ -95,6 +95,7 @@ export const windowMouseMove = (event: MouseEvent) => {const inDockOverlay = hasClosestByClassName(target, "b3-menu") ||hasClosestByClassName(target, "tooltip") ||hasClosestByClassName(target, "block__popover") ||+ hasClosestByClassName(target, "protyle-hint--lite-overlay") ||hasClosestByClassName(target, "protyle-hint--agent-overlay") ||hasClosestByClassName(target, "b3-dialog", true);if (event.buttons !== 0 || inDockOverlay) {diff --git a/app/src/layout/dock/agent/AgentComposer.ts b/app/src/layout/dock/agent/AgentComposer.tsindex 7545ef0a5c..254deb373c 100644--- a/app/src/layout/dock/agent/AgentComposer.ts+++ b/app/src/layout/dock/agent/AgentComposer.ts@@ -1,18 +1,14 @@-import {Protyle} from "../../../protyle";import {Constants} from "../../../constants";-import type {App} from "../../../index";import {escapeHtml} from "../../../util/escape";import {fetchPost} from "../../../util/fetch";import {hintRef} from "../../../protyle/hint/extend";-import {genEmptyElement} from "../../../block/util";import {blockRender} from "../../../protyle/render/blockRender";-import {focusBlock} from "../../../protyle/util/selection";import {matchHotKey} from "../../../protyle/util/hotKey";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";+import {mountProtyleLiteFragment} from "../../../protyle/lite/fragmentEditor";export interface AgentComposerData {text: string;@@ -192,71 +188,45 @@ export function mountComposer(host: HTMLElement, onSend: () => void, onChange?:const L = window.siyuan.languages;const enableHistory = options.enableHistory !== false;- const app: App = window.siyuan.ws.app;- const protyle = new Protyle(app, host, {- lite: true,- blockId: "",- render: {- gutter: false,- breadcrumb: false,- scroll: false,- background: false,- title: false,+ const fragment = mountProtyleLiteFragment(host, {+ initialMarkdown: options.initialContent,+ initialBlockHTML: options.initialBlockHTML,+ placeholder: options.placeholder || L.agentInputPlaceholder,+ emptyClass: "agent-composer--empty",+ hintOverlayClass: AGENT_HINT_OVERLAY_CLASS,+ onChange,+ protyleOptions: {+ hint: {+ // / 技能菜单(覆盖默认的块插入菜单 hintSlash);[[ 块引用由 protyle 默认 extend 提供+ extend: [{+ key: "((",+ hint: hintAgentRef,+ }, {+ key: "【【",+ hint: hintAgentRef,+ }, {+ key: "((",+ hint: hintAgentRef,+ }, {+ key: "[[",+ hint: hintAgentRef,+ }, {+ key: "/",+ hint: hintSkill,+ }, {+ key: "、",+ hint: hintSkill,+ }],+ },},- hint: {- // / 技能菜单(覆盖默认的块插入菜单 hintSlash);[[ 块引用由 protyle 默认 extend 提供- extend: [{- key: "((",- hint: hintAgentRef,- }, {- key: "【【",- hint: hintAgentRef,- }, {- key: "((",- hint: hintAgentRef,- }, {- key: "[[",- hint: hintAgentRef,- }, {- key: "/",- hint: hintSkill,- }, {- key: "、",- hint: hintSkill,- }],+ afterSetContent: (protyle, element) => {+ resetEmbedBlocks(element);+ blockRender(protyle, element);},});-- // Protyle 实例的 protyle 属性才是 IProtyle(持有 wysiwyg/hint/lute 等)。- // 类方法(focus/insert/destroy)在 Protyle 实例上,内部数据属性在 IProtyle 上。- const p = protyle.protyle;+ const protyle = fragment.instance;+ const p = fragment.protyle;const wysiwyg = p.wysiwyg!;- const hintElement = p.hint.element;- // Hint 使用视口坐标定位,挂到顶层可避免受浮动 Dock 的变换坐标系和裁剪影响。- hintElement.classList.add(AGENT_HINT_OVERLAY_CLASS);- document.body.appendChild(hintElement);- wysiwyg.element.setAttribute("data-readonly", "false");- // 智能体输入区高度较小,工具栏子面板需以窗口而非编辑器作为垂直边界。- 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");- emptyElement.firstElementChild.setAttribute("placeholder", options.placeholder || L.agentInputPlaceholder);- wysiwyg.element.appendChild(emptyElement);- };- if (options.initialBlockHTML) {- wysiwyg.element.innerHTML = options.initialBlockHTML;- resetEmbedBlocks(wysiwyg.element);- blockRender(p, wysiwyg.element);- } else if (options.initialContent) {- wysiwyg.element.innerHTML = p.lute.Md2BlockDOM(options.initialContent);- blockRender(p, wysiwyg.element);- } else {- setEmptyContent();- }// 智能体输入框没有文档 ID,直接预览输入框中的图片,避免走依赖文档资源列表的默认逻辑。wysiwyg.element.addEventListener("dblclick", (event: MouseEvent) => {@@ -276,21 +246,6 @@ export function mountComposer(host: HTMLElement, onSend: () => void, onChange?:previewImages(srcList, currentSrc);}, true);- const updatePlaceholder = () => {- const isEmpty = (wysiwyg.element.textContent || "").replace(new RegExp(Constants.ZWSP, "g"), "").trim() === "";- wysiwyg.element.classList.toggle("agent-composer--empty", isEmpty);- };- updatePlaceholder();-- // Protyle 的粘贴、块删除和程序化插入会直接修改 DOM,不一定派发 input,需以实际 DOM 变化为准刷新状态。- const contentObserver = new MutationObserver(() => {- updatePlaceholder();- if (onChange) {- onChange();- }- });- contentObserver.observe(wysiwyg.element, {childList: true, characterData: true, subtree: true});-// capture 阶段拦截 hint 选择、发送快捷键、历史翻页;undo/redo 交给 protyle 的 keydown(调 LocalUndo)。wysiwyg.element.addEventListener("keydown", (event: KeyboardEvent) => {if (event.isComposing) {@@ -329,8 +284,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);+ fragment.setMarkdown(target);return;}}@@ -339,11 +293,10 @@ 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);+ fragment.setMarkdown(target);} else {- wysiwyg.element.innerHTML = target;+ fragment.setBlockHTML(target);}return;}@@ -356,30 +309,22 @@ export function mountComposer(host: HTMLElement, onSend: () => void, onChange?:}, true);const getMarkdown = (): string => {- const clone = wysiwyg.element.cloneNode(true) as HTMLElement;- clone.querySelectorAll(AGENT_SKILL_SELECTOR).forEach((skillElement) => {- skillElement.replaceWith(document.createTextNode(skillElement.textContent || ""));+ return fragment.getMarkdown((element) => {+ element.querySelectorAll(AGENT_SKILL_SELECTOR).forEach((skillElement) => {+ skillElement.replaceWith(document.createTextNode(skillElement.textContent || ""));+ });});- return p.lute.BlockDOM2StdMd(clone.innerHTML).trim();};const getBlockHTML = (): string => {- const clone = wysiwyg.element.cloneNode(true) as HTMLElement;- resetEmbedBlocks(clone);- return clone.innerHTML;+ return fragment.getBlockHTML(resetEmbedBlocks);};return {focus: (toEnd = false) => {- if (!toEnd || !focusBlock(wysiwyg.element.lastElementChild, wysiwyg.element, false)) {- protyle.focus();- }- },- destroy: () => {- contentObserver.disconnect();- protyle.destroy();- hintElement.remove();+ fragment.focus(toEnd);},+ destroy: fragment.destroy,getSendData: () => {const references: { id: string; title: string }[] = [];wysiwyg.element.querySelectorAll('[data-type~="block-ref"]').forEach((ref) => {@@ -391,9 +336,7 @@ export function mountComposer(host: HTMLElement, onSend: () => void, onChange?:return {text: getMarkdown(), blockHTML: getBlockHTML(), references};},clear: () => {- setEmptyContent();- p.undo.clear();- updatePlaceholder();+ fragment.clear();history.resetCursor();},pushHistory: (text: string) => history.push(text),diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.tsindex 7b459f2298..63b5459164 100644--- a/app/src/mobile/util/keyboardToolbar.ts+++ b/app/src/mobile/util/keyboardToolbar.ts@@ -861,9 +861,10 @@ export const showKeyboardToolbar = () => {}const toolbarElement = document.getElementById("keyboardToolbar");const selection = getSelection();- if (selection.rangeCount > 0 &&- hasClosestByClassName(selection.getRangeAt(0).startContainer, "agent-chat__composer-host", true)) {- // 智能体发送框自带操作栏,不能显示会作用于下层文档的移动端编辑工具栏。+ if (selection.rangeCount > 0 && (+ hasClosestByClassName(selection.getRangeAt(0).startContainer, "protyle-lite-fragment", true) ||+ hasClosestByClassName(selection.getRangeAt(0).startContainer, "agent-chat__composer-host", true))) {+ // Lite 编辑器使用自己的工具栏,不能显示会作用于下层文档的移动端编辑工具栏。window.dispatchEvent(new CustomEvent("siyuan-mobile-keyboard-change", {detail: true}));toolbarElement.classList.add("fn__none");return;diff --git a/app/src/protyle/hint/extend.ts b/app/src/protyle/hint/extend.tsindex 61ca2a5932..7fac1ca1c2 100644--- a/app/src/protyle/hint/extend.ts+++ b/app/src/protyle/hint/extend.ts@@ -44,6 +44,7 @@ import {import {confirmDialog} from "../../dialog/confirmDialog";import {buildSemanticInlineHTML} from "../util/inlineElementMarker";import {getHostCapabilities} from "../../util/hostCapabilities";+import {areProtylePluginExtensionsEnabled} from "../runtimeCapabilities";import {getBlockSelectionModeElement,getBlockSelectionStatusIDs,@@ -457,23 +458,25 @@ export const hintSlash = (key: string, protyle: IProtyle, sourceOrHideConfiguredentryKey: item.id || "",}));let hasPlugin = false;- protyle.app.plugins.forEach((plugin) => {- plugin.protyleSlash.forEach(slash => {- allList.push({- filter: slash.filter,- id: slash.id,- entryKey: getPluginSlashEntryKey(plugin.name, slash.id,- slash.html === "separator" ? "separator" : "entry"),- value: `plugin${Constants.ZWSP}${plugin.name}${Constants.ZWSP}${slash.id}`,- html: slash.html+ if (areProtylePluginExtensionsEnabled(protyle)) {+ protyle.app.plugins.forEach((plugin) => {+ plugin.protyleSlash.forEach(slash => {+ allList.push({+ filter: slash.filter,+ id: slash.id,+ entryKey: getPluginSlashEntryKey(plugin.name, slash.id,+ slash.html === "separator" ? "separator" : "entry"),+ value: `plugin${Constants.ZWSP}${plugin.name}${Constants.ZWSP}${slash.id}`,+ html: slash.html+ });+ hasPlugin = true;});- hasPlugin = true;});- });+ }if (!hasPlugin) {allList.pop();}- refreshSlashMenuCatalog(protyle.app.plugins);+ refreshSlashMenuCatalog(areProtylePluginExtensionsEnabled(protyle) ? protyle.app.plugins : []);return resolveSlashMenuItems(allList.filter((item) => {const builtinStyleID = slashBuiltinStyleIDs[item.entryKey];return getEntryCatalogNode(getSlashMenuEntryPath(item.entryKey)) &&diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.tsindex 016d329ae4..e351bebfee 100644--- a/app/src/protyle/hint/index.ts+++ b/app/src/protyle/hint/index.ts@@ -72,6 +72,7 @@ import {getMobileHintPosition} from "./mobileHintPosition";import {getVisibleViewportBounds} from "../../mobile/util/visibleViewport";import {getTopBarHeight} from "../../layout/getTopBarHeight";import {stripSemanticMarkersFromRangeText} from "../util/inlineElementMarker";+import {areProtylePluginExtensionsEnabled} from "../runtimeCapabilities";const genEmojiInsertHTML = (value: string) => {const kind = getIconValueKind(value);@@ -962,7 +963,7 @@ ${genHintItemHTML(item)}nodeElement.setAttribute("style", value.split(Constants.ZWSP)[1] || "");updateTransaction(protyle, nodeElement, html);return;- } else if (value.startsWith("plugin")) {+ } else if (value.startsWith("plugin") && areProtylePluginExtensionsEnabled(protyle)) {protyle.app.plugins.find((plugin) => {const ids = value.split(Constants.ZWSP);if (ids[1] === plugin.name) {diff --git a/app/src/protyle/index.ts b/app/src/protyle/index.tsindex 3b85dbd413..68fa7f6fe2 100644--- a/app/src/protyle/index.ts+++ b/app/src/protyle/index.ts@@ -73,6 +73,17 @@ import {resolveTrackedRange,trackRange,} from "./util/trackedRange";+import {+ applyProtyleLockedOptions,+ areProtyleRuntimePluginExtensionsEnabled,+ disableProtyleUpload,+ isProtyleCustomBlockRenderEnabled,+ registerProtyleRuntimeCapabilities,+ resolveProtyleLute,+} from "./runtimeCapabilities";+import type {ProtyleRuntimeCapabilities} from "./runtimeCapabilities";++export type {ProtyleRuntimeCapabilities} from "./runtimeCapabilities";/// #if !MOBILEconst forSearchByEditor = (edit: Protyle, callback: (config: Config.IUILayoutTabSearchConfig, element: Element) => void) => {@@ -108,16 +119,26 @@ export class Protyle {* @param id 要挂载 Protyle 的元素或者元素 ID。* @param options Protyle 参数*/- constructor(app: App, id: HTMLElement, options: IProtyleOptions) {+ constructor(app: App, id: HTMLElement, options: IProtyleOptions,+ runtimeCapabilities: ProtyleRuntimeCapabilities = {}) {this.version = Constants.SIYUAN_VERSION;let pluginsOptions: IProtyleOptions = options;- app.plugins.forEach(item => {- if (item.protyleOptions) {- pluginsOptions = merge(pluginsOptions, item.protyleOptions);- }- });+ if (areProtyleRuntimePluginExtensionsEnabled(runtimeCapabilities)) {+ app.plugins.forEach(item => {+ if (item.protyleOptions) {+ pluginsOptions = merge(pluginsOptions, item.protyleOptions);+ }+ });+ }+ pluginsOptions = applyProtyleLockedOptions(pluginsOptions, runtimeCapabilities.lockedOptions);const getOptions = new Options(pluginsOptions);const mergedOptions = getOptions.merge();+ if (runtimeCapabilities.upload === false) {+ mergedOptions.upload.url = "";+ mergedOptions.upload.linkToImgUrl = "";+ mergedOptions.upload.handler = undefined;+ mergedOptions.upload.file = undefined;+ }this.protyle = {getInstance: () => this,trackRange: (range, trackOptions) => this.trackRange(range, trackOptions),@@ -140,6 +161,10 @@ export class Protyle {styleElement: document.createElement("style"),}};+ registerProtyleRuntimeCapabilities(this.protyle, runtimeCapabilities);+ if (runtimeCapabilities.upload === false) {+ disableProtyleUpload(this.protyle);+ }if (isSupportCSSHL()) {const styleId = genUUID();@@ -176,21 +201,23 @@ export class Protyle {// lite 模式用前端操作日志 undo(不依赖 kernel),其余走 kernel 的 GlobalUndoLog。this.protyle.undo = this.protyle.lite ? new LocalUndo() : new Undo();this.protyle.wysiwyg = new WYSIWYG(this.protyle);- registerCustomBlockRoot(this.protyle.wysiwyg.element, {- disabled: () => this.protyle.disabled,- update: (element, oldHTML) => updateTransaction(this.protyle, element, oldHTML),- });+ if (isProtyleCustomBlockRenderEnabled(this.protyle)) {+ registerCustomBlockRoot(this.protyle.wysiwyg.element, {+ disabled: () => this.protyle.disabled,+ update: (element, oldHTML) => updateTransaction(this.protyle, element, oldHTML),+ });+ }this.protyle.toolbar = new Toolbar(this.protyle);this.protyle.scroll = new Scroll(this.protyle); // 不能使用 render.scroll 来判读是否初始化,除非重构后面用到的相关变量if (this.protyle.options.render.gutter) {this.protyle.gutter = new Gutter(this.protyle);}- if (mergedOptions.upload.url || mergedOptions.upload.handler) {+ if (runtimeCapabilities.upload !== false && (mergedOptions.upload.url || mergedOptions.upload.handler)) {this.protyle.upload = new Upload();}- this.init();- if (!mergedOptions.action.includes(Constants.CB_GET_HISTORY)) {+ this.init(runtimeCapabilities.lute);+ if (runtimeCapabilities.websocket !== false && !mergedOptions.action.includes(Constants.CB_GET_HISTORY)) {this.protyle.ws = new Model({app});this.protyle.ws.connect({id: this.protyle.id,@@ -578,15 +605,15 @@ export class Protyle {this.protyle.contentElement.classList.add("protyle-content--transition");}- private init() {- this.protyle.lute = getLute({+ private init(lute?: Lute) {+ this.protyle.lute = resolveProtyleLute(() => getLute({emojiSite: this.protyle.options.hint.emojiPath,emojis: this.protyle.options.hint.emoji,headingAnchor: false,listStyle: this.protyle.options.preview.markdown.listStyle,paragraphBeginningSpace: this.protyle.options.preview.markdown.paragraphBeginningSpace,sanitize: this.protyle.options.preview.markdown.sanitize,- });+ }), lute);this.protyle.preview = new Preview(this.protyle);@@ -600,7 +627,7 @@ export class Protyle {/** 上传是否还在进行中 */public isUploading() {- return this.protyle.upload.isUploading;+ return this.protyle.upload?.isUploading || false;}/** 清空 undo & redo 栈 */diff --git a/app/src/protyle/lite/fragmentEditor.ts b/app/src/protyle/lite/fragmentEditor.tsnew file mode 100644index 0000000000..19e7291972--- /dev/null+++ b/app/src/protyle/lite/fragmentEditor.ts@@ -0,0 +1,178 @@+import {genEmptyElement} from "../../block/util";+import type {App} from "../../index";+import {Constants} from "../../constants";+import {Protyle} from "../index";+import type {ProtyleRuntimeCapabilities} from "../runtimeCapabilities";+import {focusBlock} from "../util/selection";+import {invalidateTrackedRanges} from "../util/trackedRange";++export const PROTYLE_LITE_FRAGMENT_CLASS = "protyle-lite-fragment";+export const PROTYLE_LITE_HINT_OVERLAY_CLASS = "protyle-hint--lite-overlay";++export interface ProtyleLiteFragmentOptions {+ app?: App;+ initialMarkdown?: string;+ initialBlockHTML?: string;+ initialPlainText?: string;+ placeholder?: string;+ emptyClass?: string;+ hintOverlayClass?: string;+ protyleOptions?: Partial<IProtyleOptions>;+ runtimeCapabilities?: ProtyleRuntimeCapabilities;+ onChange?: () => void;+ afterSetContent?: (protyle: IProtyle, element: HTMLElement) => void;+}++export interface ProtyleLiteFragment {+ instance: Protyle;+ protyle: IProtyle;+ wysiwyg: HTMLElement;+ hintElement: HTMLElement;+ clear: () => void;+ destroy: () => void;+ focus: (toEnd?: boolean) => void;+ getBlockHTML: (prepareClone?: (element: HTMLElement) => void) => string;+ getMarkdown: (prepareClone?: (element: HTMLElement) => void) => string;+ getPlainText: (prepareClone?: (element: HTMLElement) => void) => string;+ isEmpty: () => boolean;+ setBlockHTML: (blockHTML: string) => void;+ setMarkdown: (markdown: string) => void;+ setPlainText: (plainText: string) => void;+}++const isEmptyContent = (element: HTMLElement) =>+ (element.textContent || "").replace(new RegExp(Constants.ZWSP, "g"), "").trim() === "";++export const mountProtyleLiteFragment = (host: HTMLElement,+ options: ProtyleLiteFragmentOptions = {}): ProtyleLiteFragment => {+ host.classList.add(PROTYLE_LITE_FRAGMENT_CLASS);+ const instance = new Protyle(options.app || window.siyuan.ws.app, host, {+ lite: true,+ blockId: "",+ render: {+ gutter: false,+ breadcrumb: false,+ scroll: false,+ background: false,+ title: false,+ },+ ...options.protyleOptions,+ }, options.runtimeCapabilities);+ const protyle = instance.protyle;+ const wysiwyg = protyle.wysiwyg.element;+ const hintElement = protyle.hint.element;+ hintElement.classList.add(PROTYLE_LITE_HINT_OVERLAY_CLASS);+ if (options.hintOverlayClass) {+ hintElement.classList.add(options.hintOverlayClass);+ }+ document.body.appendChild(hintElement);+ wysiwyg.setAttribute("data-readonly", "false");+ protyle.toolbar.subElement.setAttribute("data-position-boundary", "viewport");++ const updateEmptyState = () => {+ const empty = isEmptyContent(wysiwyg);+ if (options.emptyClass) {+ wysiwyg.classList.toggle(options.emptyClass, empty);+ }+ return empty;+ };+ const afterSetContent = () => {+ options.afterSetContent?.(protyle, wysiwyg);+ updateEmptyState();+ };+ const resetContent = () => {+ invalidateTrackedRanges(protyle);+ wysiwyg.innerHTML = "";+ };+ const setEmptyContent = () => {+ resetContent();+ const emptyElement = genEmptyElement(false, false);+ emptyElement.firstElementChild.classList.add("protyle-wysiwyg--empty");+ if (options.placeholder) {+ emptyElement.firstElementChild.setAttribute("placeholder", options.placeholder);+ }+ wysiwyg.appendChild(emptyElement);+ afterSetContent();+ };+ const setBlockHTML = (blockHTML: string) => {+ if (!blockHTML) {+ setEmptyContent();+ return;+ }+ resetContent();+ wysiwyg.innerHTML = blockHTML;+ afterSetContent();+ };+ const setMarkdown = (markdown: string) => {+ if (!markdown) {+ setEmptyContent();+ return;+ }+ setBlockHTML(protyle.lute.Md2BlockDOM(markdown));+ };+ const setPlainText = (plainText: string) => {+ if (!plainText) {+ setEmptyContent();+ return;+ }+ resetContent();+ plainText.replace(/\r\n?/g, "\n").split("\n").forEach((line) => {+ const blockElement = genEmptyElement(false, false);+ const editElement = blockElement.querySelector<HTMLElement>('[contenteditable="true"]');+ editElement.textContent = line;+ wysiwyg.appendChild(blockElement);+ });+ afterSetContent();+ };++ if (typeof options.initialBlockHTML === "string" && options.initialBlockHTML) {+ setBlockHTML(options.initialBlockHTML);+ } else if (typeof options.initialMarkdown === "string" && options.initialMarkdown) {+ setMarkdown(options.initialMarkdown);+ } else if (typeof options.initialPlainText === "string" && options.initialPlainText) {+ setPlainText(options.initialPlainText);+ } else {+ setEmptyContent();+ }++ const contentObserver = new MutationObserver(() => {+ updateEmptyState();+ options.onChange?.();+ });+ contentObserver.observe(wysiwyg, {childList: true, characterData: true, subtree: true});++ const cloneContent = (prepareClone?: (element: HTMLElement) => void) => {+ const clone = wysiwyg.cloneNode(true) as HTMLElement;+ prepareClone?.(clone);+ return clone;+ };++ return {+ instance,+ protyle,+ wysiwyg,+ hintElement,+ clear: () => {+ setEmptyContent();+ protyle.undo.clear();+ },+ destroy: () => {+ contentObserver.disconnect();+ instance.destroy();+ hintElement.remove();+ host.classList.remove(PROTYLE_LITE_FRAGMENT_CLASS);+ },+ focus: (toEnd = false) => {+ if (!toEnd || !focusBlock(wysiwyg.lastElementChild, wysiwyg, false)) {+ instance.focus();+ }+ },+ getBlockHTML: (prepareClone) => cloneContent(prepareClone).innerHTML,+ getMarkdown: (prepareClone) => protyle.lute.BlockDOM2StdMd(cloneContent(prepareClone).innerHTML).trim(),+ getPlainText: (prepareClone) => protyle.lute.BlockDOM2Content(cloneContent(prepareClone).innerHTML).trim(),+ isEmpty: () => isEmptyContent(wysiwyg),+ setBlockHTML,+ setMarkdown,+ setPlainText,+ };+};diff --git a/app/src/protyle/render/av/action.ts b/app/src/protyle/render/av/action.tsindex a62ec17220..8d2f2f2237 100644--- a/app/src/protyle/render/av/action.ts+++ b/app/src/protyle/render/av/action.ts@@ -67,6 +67,12 @@ import {getAVCurrentViewID} from "./viewVisibility";import {cloneAVCellValueSnapshot} from "./cellValue";import {formatAVItemLinks, genAVItemLink} from "./itemLink";import {openLink} from "../../../editor/openLink";+import {getAVRichTextSafeURL, renderAVRichTextElements} from "./richText";+/// #if !MOBILE+import {openGlobalSearch} from "../../../search/util";+/// #else+import {popSearch} from "../../../mobile/menu/search";+/// #endif/// #if MOBILEimport {activeBlur} from "../../../mobile/util/keyboardToolbar";/// #endif@@ -293,10 +299,50 @@ export const avClick = (protyle: IProtyle, event: MouseEvent & { target: HTMLEleevent.stopPropagation();return true;}+ const richTextElement = event.target.closest<HTMLElement>(".av__celltext--rich");+ if (richTextElement) {+ const blockRefElement = event.target.closest<HTMLElement>('[data-type~="block-ref"][data-id]');+ const fileAnnotationElement = event.target.closest<HTMLElement>('[data-type~="file-annotation-ref"][data-id]');+ const tagElement = event.target.closest<HTMLElement>('[data-type~="tag"]');+ const linkElement = event.target.closest<HTMLElement>('[data-type~="a"][data-href], a[href]');+ let href = "";+ if (blockRefElement && richTextElement.contains(blockRefElement)) {+ href = getAVRichTextSafeURL(`siyuan://blocks/${blockRefElement.dataset.id}`);+ } else if (fileAnnotationElement && richTextElement.contains(fileAnnotationElement)) {+ href = getAVRichTextSafeURL(fileAnnotationElement.dataset.id);+ } else if (tagElement && richTextElement.contains(tagElement)) {+ /// #if !MOBILE+ openGlobalSearch(protyle.app, `#${tagElement.textContent}#`, true, {method: 0});+ /// #else+ popSearch(protyle.app, {+ hasReplace: false,+ method: 0,+ hPath: "",+ idPath: [],+ k: `#${tagElement.textContent}#`,+ r: "",+ page: 1,+ });+ /// #endif+ event.preventDefault();+ event.stopPropagation();+ return true;+ } else if (linkElement && richTextElement.contains(linkElement)) {+ href = getAVRichTextSafeURL(linkElement.dataset.href || linkElement.getAttribute("href"));+ }+ if (href) {+ openLink(protyle.app, href, event, event.ctrlKey || event.metaKey);+ event.preventDefault();+ event.stopPropagation();+ return true;+ }+ }if (isOnlyMeta(event)) {return false;}- const blockElement = hasClosestBlock(event.target);+ // 富文本预览以 b3-typography 作为渲染边界,先回到单元格再查找数据库块。+ const cellElement = hasClosestByClassName(event.target, "av__cell");+ const blockElement = hasClosestBlock(cellElement || event.target);if (!blockElement) {return false;}@@ -1349,6 +1395,7 @@ export const updateAttrViewCellAnimation = (cellElement: HTMLElement, value: IAVaddDragFill(cellElement);}renderCellAttr(cellElement, value);+ renderAVRichTextElements(cellElement);}};diff --git a/app/src/protyle/render/av/attributeValue.ts b/app/src/protyle/render/av/attributeValue.tsindex e269755e80..b10ab09adc 100644--- a/app/src/protyle/render/av/attributeValue.ts+++ b/app/src/protyle/render/av/attributeValue.ts@@ -4,30 +4,16 @@ import {getFileTreeIconHTML} from "../../../emoji/fileTreeIcon";import {getCompressURL} from "../../../util/image";import {isBrowserRenderableImagePath} from "../../../util/imageURL";import {formatDateDisplay, formatDateValue} from "./dateFormat";-import {cloneAVCellValueSnapshot, getAVBlockRefSubtype, hasAVRenderTemplateResult} from "./cellValue";+import {+ cloneAVCellValueSnapshot,+ getAVBlockRefSubtype,+ hasAVRenderTemplateResult,+} from "./cellValue";import {getAVColorStyle} from "./color";import {getHostCapabilities} from "../../../util/hostCapabilities";+import {getAVRichTextPreviewHTML, getAVTextSource} from "./richText";-export const createEmptyAVValue = (keyID: string, type: TAVCol, blockID?: string) => ({- type,- keyID,- blockID,- block: {id: "", content: ""},- text: {content: ""},- number: {content: 0, isNotEmpty: false, formattedContent: ""},- url: {content: ""},- phone: {content: ""},- email: {content: ""},- template: {content: ""},- date: {isNotEmpty: false, isNotEmpty2: false},- created: {isNotEmpty: false},- updated: {isNotEmpty: false},- checkbox: {checked: false},- mSelect: [],- mAsset: [],- relation: {blockIDs: [], contents: []},- rollup: {contents: []},-} as IAVCellValue);+export {createEmptyAVValue} from "./cellValue";export const getAVTemplateHTML = (content: string) => {if (!getHostCapabilities().remoteKernel && window.siyuan.config.editor.allowHTMLBLockScript) {@@ -132,9 +118,15 @@ export const genAVValueHTML = (value: IAVCellValue, dateFormat: TAVDateFormat =case "block":html = `<input data-id="${value.block.id}" value="${escapeAttr(value.block.content)}" type="text" class="b3-text-field b3-text-field--text fn__flex-1" placeholder="${window.siyuan.languages.empty}">`;break;- case "text":- html = `<textarea style="resize: vertical" rows="${(value.text?.content || "").split("\n").length}" class="b3-text-field b3-text-field--text fn__flex-1" placeholder="${window.siyuan.languages.empty}">${escapeHtml(value.text?.content || "")}</textarea>`;+ case "text": {+ const source = getAVTextSource(value);+ if (source.kind === "rich") {+ html = `<div class="av__celltext av__celltext--rich b3-typography fn__flex-1" data-protyle-lite-render="safe" placeholder="${window.siyuan.languages.empty}">${getAVRichTextPreviewHTML(source.content)}</div>`;+ } else {+ html = `<div class="av__celltext av__celltext--plain fn__flex-1" placeholder="${window.siyuan.languages.empty}">${escapeHtml(source.content)}</div>`;+ }break;+ }case "number":html = `<span class="av__celltext" data-content="${value.number.isNotEmpty ? value.number.content : ""}" placeholder="${window.siyuan.languages.empty}">${value.number.formattedContent || (value.number.isNotEmpty ? value.number.content : "")}</span>`;break;@@ -245,7 +237,7 @@ export const genAVAttributeRowHTML = (options: {}) => {const value = options.value;const storedValue = cloneAVCellValueSnapshot(value);- const textInputType = ["url", "text", "email", "phone", "block"].includes(value.type);+ const textInputType = ["url", "email", "phone", "block"].includes(value.type);const hasOwnPlaceholder = ["text", "number", "date", "url", "phone", "template", "email"].includes(value.type);return `<div class="block__icons av__row" data-id="${options.nodeID}" data-col-id="${options.keyID}" data-empty="${options.empty}"${options.type === "block" ? ' data-primary="true"' : ""}><div class="block__icon" draggable="true"><svg><use xlink:href="#iconDrag"></use></svg></div>diff --git a/app/src/protyle/render/av/batchEdit.ts b/app/src/protyle/render/av/batchEdit.tsindex 60a88ee842..2ac296d837 100644--- a/app/src/protyle/render/av/batchEdit.ts+++ b/app/src/protyle/render/av/batchEdit.ts@@ -4,6 +4,7 @@ import {getAVData, getAVSelectedItemIDs} from "./virtualScroll";import {getFieldsByData} from "./view";import {TAVBatchEditMode} from "./batchValue";import {cloneAVCellValueSnapshot} from "./cellValue";+import {renderAVRichTextElements} from "./richText";const EDITABLE_FIELD_TYPES: TAVCol[] = ["block",@@ -134,6 +135,7 @@ const createEditProxy = (options: {cellElement.style.cssText = "position:absolute;inset:0;";cellElement.innerHTML = renderCell(displayValue, 0, options.data.view.showIcon, "table", options.field.options,options.field.dateFormat);+ renderAVRichTextElements(cellElement);return cellElement;};diff --git a/app/src/protyle/render/av/blockAttr.ts b/app/src/protyle/render/av/blockAttr.tsindex bd4f810b60..d196537316 100644--- a/app/src/protyle/render/av/blockAttr.ts+++ b/app/src/protyle/render/av/blockAttr.ts@@ -30,6 +30,12 @@ import {getLocalDropFiles, hasDataTransferFiles} from "../../upload/localDropFilimport {cloneAVCellValueSnapshot} from "./cellValue";import {getEditorFocusRange, restoreEditorFocusRange} from "../../util/editorFocus";import {getHostCapabilities} from "../../../util/hostCapabilities";+import {getAVRichTextSafeURL, renderAVRichTextElements} from "./richText";+/// #if !MOBILE+import {openGlobalSearch} from "../../../search/util";+/// #else+import {popSearch} from "../../../mobile/menu/search";+/// #endifinterface IAVAttributeTableData {avID: string;@@ -72,6 +78,53 @@ const handleTemplateInteraction = (protyle: IProtyle, event: MouseEvent) => {return true;};+const handleRichTextInteraction = (protyle: IProtyle, event: MouseEvent) => {+ const target = event.target as HTMLElement;+ const richTextElement = target.closest(".av__celltext--rich");+ if (!richTextElement) {+ return false;+ }+ const blockRefElement = target.closest<HTMLElement>('[data-type~="block-ref"][data-id]');+ const fileAnnotationElement = target.closest<HTMLElement>('[data-type~="file-annotation-ref"][data-id]');+ const tagElement = target.closest<HTMLElement>('[data-type~="tag"]');+ const linkElement = target.closest<HTMLElement>('[data-type~="a"][data-href], a[href]');+ if (blockRefElement && richTextElement.contains(blockRefElement)) {+ const link = getAVRichTextSafeURL(`siyuan://blocks/${blockRefElement.dataset.id}`);+ if (link) {+ openLink(protyle.app, link, event, event.ctrlKey || event.metaKey);+ }+ } else if (fileAnnotationElement && richTextElement.contains(fileAnnotationElement)) {+ const link = getAVRichTextSafeURL(fileAnnotationElement.dataset.id);+ if (link) {+ openLink(protyle.app, link, event, event.ctrlKey || event.metaKey);+ }+ } else if (tagElement && richTextElement.contains(tagElement)) {+ /// #if !MOBILE+ openGlobalSearch(protyle.app, `#${tagElement.textContent}#`, true, {method: 0});+ /// #else+ popSearch(protyle.app, {+ hasReplace: false,+ method: 0,+ hPath: "",+ idPath: [],+ k: `#${tagElement.textContent}#`,+ r: "",+ page: 1,+ });+ /// #endif+ } else if (linkElement && richTextElement.contains(linkElement)) {+ const link = getAVRichTextSafeURL(linkElement.dataset.href || linkElement.getAttribute("href"));+ if (link) {+ openLink(protyle.app, link, event, event.ctrlKey || event.metaKey);+ }+ } else {+ return false;+ }+ event.preventDefault();+ event.stopPropagation();+ return true;+};+export const renderAVAttribute = (element: HTMLElement, id: string, protyle: IProtyle, cb?: (element: HTMLElement) => void,row?: { avID: string, itemID: string, valueID: string }) => {const renderID = (++attributeViewRenderID).toString();@@ -316,7 +369,7 @@ export const renderAVAttribute = (element: HTMLElement, id: string, protyle: IPrevent.preventDefault();});element.addEventListener("click", (event) => {- if (handleTemplateInteraction(protyle, event)) {+ if (handleTemplateInteraction(protyle, event) || handleRichTextInteraction(protyle, event)) {return;}const databaseElement = hasClosestByClassName(event.target as HTMLElement, "popover__block");@@ -466,6 +519,7 @@ export const renderAVAttribute = (element: HTMLElement, id: string, protyle: IPr});element.innerHTML = html;}+ renderAVRichTextElements(element);tables.forEach((table: IAVAttributeTableData) => {const blockElement = element.querySelector<HTMLElement>(`[data-node-id="${id}"][data-av-id="${table.avID}"]`);if (blockElement) {@@ -554,7 +608,8 @@ const renderAttributeViewBacklinks = (element: HTMLElement, id: string, renderIDconst openEdit = (protyle: IProtyle, element: HTMLElement, event: MouseEvent) => {let target = event.target as HTMLElement;- const blockElement = hasClosestBlock(target);+ const valueElement = hasClosestByClassName(target, "custom-attr__avvalue");+ const blockElement = hasClosestBlock(valueElement || target);if (!blockElement) {return;}@@ -603,7 +658,8 @@ const openEdit = (protyle: IProtyle, element: HTMLElement, event: MouseEvent) =>event.preventDefault();break;} else if (["text", "url", "email", "phone", "block"].includes(type) &&- target.querySelector(":scope > .av__celltext--template")) {+ (target.querySelector(":scope > .av__celltext--template") ||+ (type === "text" && target.querySelector(":scope > .av__celltext")))) {popTextCell(protyle, [target], type as TAVCol);event.stopPropagation();event.preventDefault();diff --git a/app/src/protyle/render/av/cell.ts b/app/src/protyle/render/av/cell.tsindex 095ecb6079..db6d69ecae 100644--- a/app/src/protyle/render/av/cell.ts+++ b/app/src/protyle/render/av/cell.ts@@ -29,6 +29,8 @@ import {activeBlur} from "../../../mobile/util/keyboardToolbar";import {cellValueIsEmpty,cloneAVCellValueSnapshot,+ createAVCellUpdateOperation,+ createAVStableTextCell,genEmptyAVCellValue,genRelationAVCellValue,getAVBlockRefSubtype,@@ -46,6 +48,13 @@ import {setAVBatchDisplayValue} from "./batchValue";import {genAVDragFillValue, rebindAVCellValue} from "./dragFillValue";+import {+ getAVRichTextPreviewHTML,+ getAVTextCopyContent,+ getAVTextSource,+ renderAVRichTextElements,+} from "./richText";+import {openAVRichTextEditor} from "./richTextEditor";export {cellValueIsEmpty} from "./cellValue";@@ -53,10 +62,29 @@ const renderCellURL = (urlContent: string) => {return `<span class="av__celltext av__celltext--url" data-type="url" data-href="${escapeAttr(urlContent)}">${Lute.EscapeHTMLStr(urlContent)}</span>`;};+const getStoredCellValueByElement = (cellElement: HTMLElement) => {+ const valueElement = cellElement.dataset.cellValue ? cellElement :+ cellElement.querySelector<HTMLElement>("[data-cell-value]");+ if (!valueElement?.dataset.cellValue) {+ return;+ }+ try {+ return JSON.parse(decodeURIComponent(valueElement.dataset.cellValue)) as IAVCellValue;+ } catch {+ return;+ }+};+export const getCellText = (cellElement: HTMLElement | false) => {if (!cellElement) {return "";}+ const richTextElement = cellElement.matches(".av__celltext--rich[data-cell-value]") ? cellElement :+ cellElement.querySelector<HTMLElement>(".av__celltext--rich[data-cell-value]");+ const storedCellValue = richTextElement ? getStoredCellValueByElement(richTextElement) : undefined;+ if (storedCellValue?.type === "text" && getAVTextSource(storedCellValue).kind === "rich") {+ return getAVTextCopyContent(storedCellValue);+ }let cellText = "";const textElements = cellElement.querySelectorAll(".b3-chip, .av__celltext--ref, .av__celltext");if (textElements.length > 0) {@@ -76,19 +104,6 @@ export const getCellText = (cellElement: HTMLElement | false) => {return cellText;};-const getStoredCellValueByElement = (cellElement: HTMLElement) => {- const valueElement = cellElement.dataset.cellValue ? cellElement :- cellElement.querySelector<HTMLElement>("[data-cell-value]");- if (!valueElement?.dataset.cellValue) {- return;- }- try {- return JSON.parse(decodeURIComponent(valueElement.dataset.cellValue)) as IAVCellValue;- } catch {- return;- }-};-export const genCellValueByElement = (colType: TAVCol, cellElement: HTMLElement) => {const storedCellValue = getStoredCellValueByElement(cellElement);if (storedCellValue) {@@ -440,6 +455,34 @@ export const getTypeByCellElement = (cellElement: Element) => {return scrollElement.querySelector(".av__row--header").querySelector(`[data-col-id="${cellElement.getAttribute("data-col-id")}"]`).getAttribute("data-dtype") as TAVCol;};+const getStableTextCells = (cellElements: HTMLElement[], blockElement: HTMLElement) => {+ const viewType = blockElement.dataset.avType as TAVView;+ const stableCells: IAVSelectedCell[] = [];+ cellElements.forEach((cellElement) => {+ const rowID = getFieldIdByCellElement(cellElement, viewType);+ const colID = getColId(cellElement, viewType);+ const value = getStoredCellValueByElement(cellElement) || genCellValueByElement("text", cellElement);+ const rowElement = hasClosestByClassName(cellElement,+ viewType === "table" ? "av__row" : "av__gallery-item");+ const groupElement = hasClosestByClassName(cellElement, "av__body");+ const rowIndex = parseInt(rowElement ? rowElement.getAttribute("data-index") || "0" : "0") || 0;+ const stableCell = createAVStableTextCell({+ groupID: groupElement ? groupElement.getAttribute("data-group-id") || "" : "",+ rowID,+ colID,+ rowIndex,+ colIndex: Array.from(cellElement.parentElement?.querySelectorAll(":scope > .av__cell") || [])+ .indexOf(cellElement),+ cellID: cellElement.dataset.id,+ value,+ });+ if (stableCell) {+ stableCells.push(stableCell);+ }+ });+ return stableCells;+};+export const popTextCell = (protyle: IProtyle, cellElements: HTMLElement[], type?: TAVCol, options?: {scrollIntoView?: boolean;data?: IAV;@@ -475,6 +518,29 @@ export const popTextCell = (protyle: IProtyle, cellElements: HTMLElement[], typelet height = cellRect.height;const cssStyle = getComputedStyle(cellElements[0]);const storedCellValue = getStoredCellValueByElement(cellElements[0]);+ const hasRenderedTemplate = cellElements[0].matches(".av__celltext--template") ||+ Boolean(cellElements[0].querySelector(":scope > .av__celltext--template"));+ if (type === "text" && !hasRenderedTemplate) {+ const stableCells = getStableTextCells(cellElements, blockElement);+ if (stableCells.length > 0) {+ if (!options?.keepMenuOpen) {+ window.siyuan.menus.menu.remove();+ }+ openAVRichTextEditor({+ protyle,+ nodeElement: blockElement,+ anchorElement: cellElements[0],+ value: stableCells[0].cell.value,+ stableCells,+ onSave: (value, nodeElement, selectedCells) => {+ updateCellsValue(protyle, nodeElement, value, undefined, undefined, undefined,+ false, false, false, selectedCells);+ },+ onDestroy: options?.destroyCallback,+ });+ return;+ }+ }const inputTop = options?.positionByMenu ? cellRect.bottom : cellRect.top;let style = `font-family:${cssStyle.fontFamily};font-size:${cssStyle.fontSize};line-height:${cssStyle.lineHeight};padding:${cssStyle.padding};position:absolute;top: ${inputTop}px;`;if (contentElement && !options?.positionByMenu) {@@ -833,7 +899,7 @@ export const updateCellsValue = async (protyle: IProtyle, nodeElement: HTMLElemecontinue;}const readonly = ["created", "updated", "template", "rollup", "lineNumber"].includes(type);- const cellId = source.selectedCell?.cell.id || item?.dataset.id;+ const cellId = source.selectedCell?.cell.id || item?.dataset.id || "";const colId = source.selectedCell?.colID || (item ? getColId(item, viewType) : "");const renderedOldValue = source.selectedCell?.cell.value ||(item ? genCellValueByElement(type, item) : undefined);@@ -863,7 +929,7 @@ export const updateCellsValue = async (protyle: IProtyle, nodeElement: HTMLEleme}json[json.length - 1].push(oldValue);}- if (readonly || !cellId) {+ if (readonly) {continue;}let newValue = value;@@ -999,23 +1065,21 @@ export const updateCellsValue = async (protyle: IProtyle, nodeElement: HTMLElemecellValue.date.formattedContent = formatDateValue(cellValue.date, column?.dateFormat);}if (forceOperation || !objEquals(cellValue, oldValue)) {- doOperations.push({- action: "updateAttrViewCell",- id: cellId,+ doOperations.push(createAVCellUpdateOperation({+ valueID: cellId,avID,keyID: colId,rowID,data: cellValue- });+ }));- undoOperations.push({- action: "updateAttrViewCell",- id: cellId,+ undoOperations.push(createAVCellUpdateOperation({+ valueID: cellId,avID,keyID: colId,rowID,data: oldValue- });+ }));if (updateElements) {if (!isCustomAttr && item) {updateAttrViewCellAnimation(item, cellValue);@@ -1067,6 +1131,7 @@ export const updateAttrViewCellInOtherElements = (protyle: IProtyle, avID: strincellElement.parentElement.dataset.empty = cellValueIsEmpty(value, true, renderTemplate).toString();cellElement.innerHTML = genAVValueHTML(value, cellElement.dataset.dateFormat as TAVDateFormat,renderTemplate);+ renderAVRichTextElements(cellElement);}if (value.type === "block") {const databaseRowElement = cellElement.closest<HTMLElement>(".protyle-db-row");@@ -1143,7 +1208,13 @@ export const renderCell = (cellValue: IAVCellValue, rowIndex = 0, showIcon = tru} else if ("template" === cellValue.type) {text = `<span class="av__celltext av__celltext--template">${cellValue ? getAVTemplateHTML(cellValue.template.content || "") : ""}</span>`;} else if ("text" === cellValue.type) {- text = `<span class="av__celltext">${cellValue ? Lute.EscapeHTMLStr(cellValue.text.content || "") : ""}</span>`;+ const source = getAVTextSource(cellValue);+ if (source.kind === "rich") {+ const storedValue = cloneAVCellValueSnapshot(cellValue);+ text = `<div class="av__celltext av__celltext--rich b3-typography" data-protyle-lite-render="safe" data-cell-value="${escapeAttr(encodeURIComponent(JSON.stringify(storedValue)))}">${getAVRichTextPreviewHTML(source.content)}</div>`;+ } else {+ text = `<span class="av__celltext">${cellValue ? Lute.EscapeHTMLStr(cellValue.text.content || "") : ""}</span>`;+ }} else if (["email", "phone"].includes(cellValue.type)) {text = `<span class="av__celltext av__celltext--url" data-type="${cellValue.type}">${cellValue ? Lute.EscapeHTMLStr(cellValue[cellValue.type as "email"].content || "") : ""}</span>`;} else if ("url" === cellValue.type) {@@ -1252,6 +1323,10 @@ export const renderCell = (cellValue: IAVCellValue, rowIndex = 0, showIcon = tru};export const getCellValueText = (value: IAVCellValue, column?: IAVColumn, rowIndex = 0) => {+ if (value.type === "text" && !hasAVRenderTemplateResult(value, column?.renderTemplate) &&+ getAVTextSource(value).kind === "rich") {+ return getAVTextCopyContent(value);+ }const cellElement = document.createElement("div");cellElement.innerHTML = renderCell(value, rowIndex, true, "table", column?.options, column?.dateFormat,column?.renderTemplate);@@ -1425,6 +1500,7 @@ export const dragFillCellsValue = (protyle: IProtyle, nodeElement: HTMLElement,item.element.innerHTML = renderCell(data, 0, showIcon, "table", undefined,item.element.dataset.dateFormat as TAVDateFormat);renderCellAttr(item.element, data);+ renderAVRichTextElements(item.element);updateAVSelectedCellValue(nodeElement, rowID, keyID, data);delete item.colId;delete item.element;diff --git a/app/src/protyle/render/av/cellValue.test.ts b/app/src/protyle/render/av/cellValue.test.tsindex c102f72230..e9877971b7 100644--- a/app/src/protyle/render/av/cellValue.test.ts+++ b/app/src/protyle/render/av/cellValue.test.ts@@ -3,11 +3,16 @@ import * as assert from "node:assert/strict";import {cellValueIsEmpty,cloneAVCellValueSnapshot,+ createAVCellUpdateOperation,+ createAVStableTextCell,+ createEmptyAVValue,genRelationAVCellValue,getAVBlockRefSubtype,getConvertedEmptyAVCellValue,hasAVRenderTemplateResult,} from "./cellValue";+import {createAVRichTextValue} from "./richTextValue";+import {rebindAVCellValue} from "./dragFillValue";describe("getAVBlockRefSubtype", () => {it("uses only a valid dynamic subtype and safely falls back to static", () => {@@ -110,6 +115,57 @@ describe("cloneAVCellValueSnapshot", () => {});});+describe("empty attribute view text identity", () => {+ it("opens an empty attribute text value using its row and column identity", () => {+ const emptyValue = createEmptyAVValue("text-key", "text", "item-row");+ const stableCell = createAVStableTextCell({+ rowID: emptyValue.blockID,+ colID: emptyValue.keyID,+ value: emptyValue,+ });++ assert.equal(Object.prototype.hasOwnProperty.call(emptyValue, "id"), false);+ assert.ok(stableCell);+ assert.equal(stableCell.rowID, "item-row");+ assert.equal(stableCell.colID, "text-key");+ assert.equal(stableCell.cell.id, "");+ assert.deepEqual(stableCell.cell.value.text, {content: ""});+ });++ it("constructs rich do and undo values without fabricating a value ID", () => {+ const oldValue = createEmptyAVValue("text-key", "text", "item-row");+ const richValue = createAVRichTextValue("**Rich**", "Rich", oldValue);+ const target = {id: "", keyID: "text-key", blockID: "item-row"};+ const doValue = rebindAVCellValue(richValue, target);+ const doOperation = createAVCellUpdateOperation({+ valueID: target.id,+ avID: "attribute-view",+ keyID: target.keyID,+ rowID: target.blockID,+ data: doValue,+ });+ const undoOperation = createAVCellUpdateOperation({+ valueID: target.id,+ avID: "attribute-view",+ keyID: target.keyID,+ rowID: target.blockID,+ data: oldValue,+ });++ assert.equal(doOperation.id, "");+ assert.equal(doOperation.keyID, "text-key");+ assert.equal(doOperation.rowID, "item-row");+ assert.deepEqual((doOperation.data as IAVCellValue).text, {+ content: "Rich",+ rich: {spec: 1, format: "kramdown", content: "**Rich**"},+ });+ assert.equal((doOperation.data as IAVCellValue).id, "");+ assert.equal(undoOperation.id, "");+ assert.deepEqual((undoOperation.data as IAVCellValue).text, {content: ""});+ assert.equal(Object.prototype.hasOwnProperty.call(undoOperation.data, "id"), false);+ });+});+describe("getConvertedEmptyAVCellValue", () => {const emptyBlockValue: IAVCellValue = {type: "block",diff --git a/app/src/protyle/render/av/cellValue.ts b/app/src/protyle/render/av/cellValue.tsindex a407153c5d..e6e4eedf3a 100644--- a/app/src/protyle/render/av/cellValue.ts+++ b/app/src/protyle/render/av/cellValue.ts@@ -1,5 +1,28 @@+import type {IAVSelectedCell} from "./selectionState";+export const getAVBlockRefSubtype = (value?: IAVCellValue): "s" | "d" => value?.block?.refSubtype === "d" ? "d" : "s";+export const createEmptyAVValue = (keyID: string, type: TAVCol, blockID?: string) => ({+ type,+ keyID,+ blockID,+ block: {id: "", content: ""},+ text: {content: ""},+ number: {content: 0, isNotEmpty: false, formattedContent: ""},+ url: {content: ""},+ phone: {content: ""},+ email: {content: ""},+ template: {content: ""},+ date: {isNotEmpty: false, isNotEmpty2: false},+ created: {isNotEmpty: false},+ updated: {isNotEmpty: false},+ checkbox: {checked: false},+ mSelect: [],+ mAsset: [],+ relation: {blockIDs: [], contents: []},+ rollup: {contents: []},+} as IAVCellValue);+export const hasAVRenderTemplateResult = (value: IAVCellValue, renderTemplate?: string) =>value.type !== "template" &&(typeof value.renderedContent === "string" || Boolean(renderTemplate?.trim()));@@ -97,6 +120,56 @@ export const cloneAVCellValueSnapshot = (value: IAVCellValue): IAVCellValue => {return snapshot;};+export const createAVStableTextCell = (options: {+ groupID?: string;+ rowID?: string;+ colID?: string;+ rowIndex?: number;+ colIndex?: number;+ cellID?: string;+ value: IAVCellValue;+}): IAVSelectedCell | undefined => {+ const rowID = options.rowID || "";+ const colID = options.colID || "";+ if (!rowID || !colID) {+ return;+ }+ const value = cloneAVCellValueSnapshot(options.value);+ return {+ groupID: options.groupID || "",+ rowID,+ colID,+ rowIndex: options.rowIndex ?? 0,+ colIndex: options.colIndex ?? -1,+ cell: {+ id: value.id || options.cellID || "",+ color: "",+ bgColor: "",+ value,+ valueType: "text",+ },+ column: {+ id: colID,+ type: "text",+ } as IAVColumn,+ };+};++export const createAVCellUpdateOperation = (options: {+ valueID?: string;+ avID?: string;+ keyID: string;+ rowID: string;+ data: IAVCellValue;+}): IOperation => ({+ action: "updateAttrViewCell",+ id: options.valueID || "",+ avID: options.avID,+ keyID: options.keyID,+ rowID: options.rowID,+ data: options.data,+});+export const getConvertedEmptyAVCellValue = (colType: TAVCol, value: IAVCellValue) => {if (colType === value.type || !cellValueIsEmpty(value)) {return;diff --git a/app/src/protyle/render/av/gallery/item.ts b/app/src/protyle/render/av/gallery/item.tsindex 336ce0ed89..443cfd7ae1 100644--- a/app/src/protyle/render/av/gallery/item.ts+++ b/app/src/protyle/render/av/gallery/item.ts@@ -2,6 +2,7 @@ import {genCellValue, getTypeByCellElement, renderCell, renderCellAttr} from "..import {fetchPost} from "../../../../util/fetch";import {setPage} from "../row";import {clearSelect} from "../../../util/clear";+import {renderAVRichTextElements} from "../richText";export const insertGalleryItemAnimation = (options: {blockElement: HTMLElement;@@ -95,6 +96,7 @@ ${fieldType === "block" ? ' data-detached="true"' : ""}>${renderCell(genCellValucellItem.innerHTML = renderCell(cellValue, undefined, false, type, undefined,cellItem.dataset.dateFormat as TAVDateFormat);renderCellAttr(cellItem, cellValue);+ renderAVRichTextElements(cellItem);}});});diff --git a/app/src/protyle/render/av/gallery/render.ts b/app/src/protyle/render/av/gallery/render.tsindex 7174f2d9f3..bae4f12c7e 100644--- a/app/src/protyle/render/av/gallery/render.ts+++ b/app/src/protyle/render/av/gallery/render.ts@@ -22,6 +22,7 @@ import {} from "../locate";import {getCardStyle} from "./style";import {setGroupFoldedStates} from "../groupFold";+import {renderAVRichTextElements} from "../richText";interface IIds {groupId: string,@@ -115,6 +116,7 @@ export const afterRenderGallery = (options: ITableOptions) => {if (view.coverFrom === 1 || view.coverFrom === 3) {processRender(options.blockElement);}+ renderAVRichTextElements(options.blockElement);if (typeof options.resetData.oldOffset === "number") {options.protyle.contentElement.scrollTop = options.resetData.oldOffset;}diff --git a/app/src/protyle/render/av/newItemTemplate.ts b/app/src/protyle/render/av/newItemTemplate.tsindex 1ff8a1fe56..0d698a881c 100644--- a/app/src/protyle/render/av/newItemTemplate.ts+++ b/app/src/protyle/render/av/newItemTemplate.ts@@ -15,6 +15,7 @@ import {hasClosestByClassName} from "../../util/hasClosest";import * as dayjs from "dayjs";import {getAVBlockRefSubtype} from "./cellValue";import {getAVColorStyle} from "./color";+import {createAVPlainTextEditValue} from "./richTextValue";interface ICreatePosition {previousID?: string;@@ -89,8 +90,9 @@ const getFieldText = (value: IAVCellValue) => {}};-const genFieldValue = (column: IAVColumn, input: HTMLElement): IAVCellValue => {- const content = (input as HTMLInputElement).value?.trim() || "";+const genFieldValue = (column: IAVColumn, input: HTMLElement, previousValue?: IAVCellValue): IAVCellValue => {+ const inputContent = (input as HTMLInputElement).value || "";+ const content = inputContent.trim();switch (column.type) {case "number":return {type: column.type, number: {content: Number(content), isNotEmpty: content !== ""}};@@ -131,6 +133,9 @@ const genFieldValue = (column: IAVColumn, input: HTMLElement): IAVCellValue => {return {type: column.type, relation: {blockIDs: getSelectedOptionNames(input)}};case "checkbox":return {type: column.type, checkbox: {checked: input.getAttribute("aria-pressed") === "true"}};+ case "text":+ return createAVPlainTextEditValue(previousValue?.type === "text" &&+ previousValue.text?.content === inputContent ? inputContent : content, previousValue);default:return {type: column.type, text: {content}};}@@ -208,6 +213,8 @@ const hasFieldValue = (column: IAVColumn, value: IAVCellValue) => {return value.relation?.blockIDs?.length > 0;case "checkbox":return value.checkbox?.checked;+ case "text":+ return !!value.text?.content || !!value.text?.rich;default:return !!value.text?.content;}@@ -496,7 +503,9 @@ const collectTemplate = (root: HTMLElement, itemTemplate: IAVNewItemTemplate, firoot.querySelectorAll<HTMLElement>("[data-field-id]").forEach(element => {const column = fields.find(item => item.id === element.dataset.fieldId);const mode = (element.querySelector('[data-role="field-mode"]') as HTMLSelectElement)?.value as TAVNewItemFieldValueMode || "static";- const value = mode === "static" ? genFieldValue(column, element.querySelector('[data-role="field-value"]')) : undefined;+ const previousValue = itemTemplate.fieldValues?.[column.id]?.value;+ const value = mode === "static" ?+ genFieldValue(column, element.querySelector('[data-role="field-value"]'), previousValue) : undefined;if (mode === "static" && !hasFieldValue(column, value)) {return;}diff --git a/app/src/protyle/render/av/relation.ts b/app/src/protyle/render/av/relation.tsindex 31eca1b7e1..fb68a25fbb 100644--- a/app/src/protyle/render/av/relation.ts+++ b/app/src/protyle/render/av/relation.ts@@ -21,6 +21,7 @@ import {getAVColumnTextMeasurer, getAVRelationColumnWidth, getAVTableFitWidths}import {getSearchAVFocus} from "./searchAVFocus";import {getAVTemplateHTML} from "./attributeValue";import {hasAVRenderTemplateResult} from "./cellValue";+import {renderAVRichTextElements} from "./richText";interface IAVItem {avID: string;@@ -438,9 +439,9 @@ style="${primaryCell.bgColor ? `background-color:${primaryCell.bgColor};` : ""}$data-position="north" aria-label="${window.siyuan.languages.openBy}"><svg><use xlink:href="#iconOpen"></use></svg></button>` : ""}</span>`;} else {- html += `<span class="av__relation-table-cell"+ html += `<div class="av__relation-table-cell"style="${cell?.bgColor ? `background-color:${cell.bgColor};` : ""}${cell?.color ? `color:${cell.color};` : ""}">${cell?.value ?- renderCell(cell.value, 0, false, "table", column.options, column.dateFormat, column.renderTemplate) : ""}</span>`;+ renderCell(cell.value, 0, false, "table", column.options, column.dateFormat, column.renderTemplate) : ""}</div>`;}});return html + "</div>";@@ -653,6 +654,7 @@ ${genRelationLoaderHTML(state.loading, state.loaderVisible)}`;listElement.querySelector('[data-relation-type="candidateRows"]').insertAdjacentHTML("beforeend", candidateHTML);}}+ renderAVRichTextElements(listElement);renderFooter(!!listElement.querySelector('[data-relation-type="candidate"]'));if (!listElement.querySelector(".b3-menu__item--current")) {listElement.querySelector('[data-type="setRelationCell"]')?.classList.add("b3-menu__item--current");diff --git a/app/src/protyle/render/av/render.ts b/app/src/protyle/render/av/render.tsindex b929baf9c7..f0aa76ba81 100644--- a/app/src/protyle/render/av/render.ts+++ b/app/src/protyle/render/av/render.ts@@ -47,6 +47,7 @@ import {setAVVisibleViewIDs} from "./viewVisibility";import {removeAVPasteSkeleton} from "./paste";+import {renderAVRichTextElements} from "./richText";import {getGroupTableRenderPlan,getUninitializedGroupRowCounts,@@ -403,12 +404,14 @@ export const initUnfoldedGroupTables = (blockElement: HTMLElement, protyle: IProblockElement.toggleAttribute(Constants.ATTRIBUTE_V_SCROLL,totalLoadedRows > GROUP_TABLE_INITIAL_ROW_BUDGET || bodies.some(bodyElement =>bodyElement.querySelector(".av__spacer")));+ renderAVRichTextElements(blockElement);initVirtualScroll({protyle, blockElement, data, selectedItemPoints});restoreAVCellSelection(blockElement);};const afterRenderTable = (options: ITableOptions) => {setAVData(options.blockElement, options.data);+ renderAVRichTextElements(options.blockElement);if (!refreshAVCellSelection(options.blockElement, options.data)) {options.resetData.selectCellId = undefined;options.resetData.dragFillId = undefined;diff --git a/app/src/protyle/render/av/richText.test.ts b/app/src/protyle/render/av/richText.test.tsnew file mode 100644index 0000000000..57e86c605a--- /dev/null+++ b/app/src/protyle/render/av/richText.test.ts@@ -0,0 +1,593 @@+import * as assert from "node:assert/strict";+import {describe, it} from "node:test";+import {cloneAVCellValueSnapshot} from "./cellValue";+import {getInlineFontFamilyStyle} from "../../toolbar/fontFamilyCore";+import {+ AV_RICH_TEXT_EDITOR_ALLOWED_ATTRIBUTES,+ AV_RICH_TEXT_EDITOR_ALLOWED_TAGS,+ AV_RICH_TEXT_PREVIEW_ALLOWED_ATTRIBUTES,+ AV_RICH_TEXT_PREVIEW_ALLOWED_TAGS,+ AV_RICH_TEXT_PREVIEW_TEXT_ONLY_TAGS,+ configureAVRichTextLute,+ createAVPlainTextEditValue,+ createAVPlainTextValue,+ createAVRichTextStyleBackslashEncoding,+ createAVRichTextValue,+ getAVTextCopyContent,+ getAVTextPlainContent,+ getAVTextSource,+ getAVRichTextSafeURL,+ isAVRichTextExecutableCodeLanguage,+ projectAVRichTextPlainBlocks,+ protectAVRichTextKramdownStyleEntities,+ restoreAVRichTextStyleEntities,+ sanitizeAVRichTextInlineMemoContent,+ sanitizeAVRichTextInlineStyle,+} from "./richTextValue";++const hasDOM = typeof globalThis.document?.createElement === "function";++describe("attribute view text source compatibility", () => {+ it("keeps legacy Markdown-looking content literal", () => {+ const literal = "**literal** ((20240101000000-abcdefg \"reference\")) $x$";+ const value: IAVCellValue = {type: "text", text: {content: literal}};++ assert.deepEqual(getAVTextSource(value), {kind: "plain", content: literal});+ assert.equal(getAVTextPlainContent(value), literal);+ });++ it("uses only a valid rich envelope as the rich source", () => {+ const value: IAVCellValue = {+ type: "text",+ text: {+ content: "Projected text",+ rich: {spec: 1, format: "kramdown", content: "**Rich** source"},+ },+ };++ assert.deepEqual(getAVTextSource(value), {kind: "rich", content: "**Rich** source"});+ assert.equal(getAVTextPlainContent(value), "Projected text");+ assert.deepEqual(getAVTextSource({+ type: "text",+ text: {content: "Explicitly plain", rich: null},+ }), {kind: "plain", content: "Explicitly plain"});+ assert.deepEqual(getAVTextSource({+ type: "text",+ text: {+ content: "Unsupported envelope",+ rich: {spec: 2, format: "kramdown", content: "**not active**"},+ },+ } as unknown as IAVCellValue), {kind: "plain", content: "Unsupported envelope"});+ });++ it("keeps the plain projection authoritative for copy and export consumers", () => {+ const value: IAVCellValue = {+ type: "text",+ text: {+ content: "first\nsecond",+ rich: {spec: 1, format: "kramdown", content: "first\n\nsecond"},+ },+ };++ assert.equal(getAVTextPlainContent(value), "first\nsecond");+ value.text.content = "\n first\nsecond \n";+ assert.equal(getAVTextCopyContent(value), "first\nsecond");+ });++ it("identifies only executable code fence languages", () => {+ for (const language of [+ "abc", "echarts", "flowchart", "graphviz", "infographic", "mermaid", "mindmap", "plantuml",+ ]) {+ assert.equal(isAVRichTextExecutableCodeLanguage(language), true);+ }+ assert.equal(isAVRichTextExecutableCodeLanguage("GraphViz options"), true);+ assert.equal(isAVRichTextExecutableCodeLanguage("javascript"), false);+ assert.equal(isAVRichTextExecutableCodeLanguage("go options"), false);+ });++ it("encodes only staged text style delimiters for Kramdown", () => {+ const code = String.raw`<span data-type="text" style="font-family: 'Code\Font';">literal</span>`;+ const style = String.raw`font-family: var(--b3-font-family-emoji-reset), 'Semi>` + "`" + String.raw`; \'Quoted\' \\ 字体', ` ++ "var(--b3-font-family-editor), var(--b3-font-family);";+ const firstSentinel = "\uE000av-rich-text-style-0\uF8FF";+ const encoding = createAVRichTextStyleBackslashEncoding(code + firstSentinel);+ const markdown = encoding.encodeMarkdown(`${encoding.protectStyle(style)}\n${code}`);++ assert.notEqual(encoding.sentinel, firstSentinel);+ assert.equal((code + firstSentinel).includes(encoding.sentinel), false);+ assert.equal(markdown, `${style.replaceAll("\\", "\").replaceAll("`", "`")}\n${code}`);+ assert.equal(markdown.includes(encoding.sentinel), false);+ });++ it("protects text span IAL style entities without treating arbitrary dollars as math", () => {+ const styled = '<span title="a>b" data-type="strong text">styled</span>' ++ '{: custom="a}>b" style="font-family: \'Semi>; \\'Quoted\\' & 字体\';" ' ++ 'other="\"}';+ const nested = '<span data-type="strong"><span data-type="text">nested</span>' ++ '{: style="font-family: \'A\B\';"}</span>';+ const plain = '<span data-type="strong">plain</span>{: style="font-family: \'A\B\';"}';+ const fake = '<span data-type="text">fake</span>{: style="font-family: \'A\B\';"}';+ const source = [+ styled,+ nested,+ plain,+ "```html",+ fake,+ "```",+ "~~~~",+ fake,+ "~~~~",+ `\`${fake}\``,+ `\`\`${fake}\`\``,+ `$${fake}$`,+ `$$${fake}$$`,+ "$$",+ fake,+ "$$",+ `\`cross\r\n${fake}\r\nline\``,+ "prose \",+ `\`unclosed ${styled}`,+ ].join("\r\n");+ const protectedStyle = protectAVRichTextKramdownStyleEntities(source);+ const restoredSource = protectedStyle.protections.reduce((content, protection) =>+ content.replaceAll(protection.token, protection.encoded), protectedStyle.content);+ const decoded = restoreAVRichTextStyleEntities(protectedStyle.content, protectedStyle.protections);++ assert.equal(restoredSource, source);+ assert.deepEqual(protectedStyle.protections.map((item) => item.encoded), [+ ">", "\", "\", "&", "\", "\", "\", ">", "\", "\", "&",+ ]);+ assert.match(decoded, /font-family: 'Semi>; \\'Quoted\\' & 字体';/);+ assert.equal(protectedStyle.content.includes(plain), true);+ assert.equal(protectedStyle.content.includes("```html\r\n" + fake + "\r\n```"), true);+ assert.equal(protectedStyle.content.includes("~~~~\r\n" + fake + "\r\n~~~~"), true);+ assert.equal(protectedStyle.content.includes(`\`${fake}\``), true);+ assert.equal(protectedStyle.content.includes(`\`\`${fake}\`\``), true);+ assert.equal(protectedStyle.content.includes(`$${fake}$`), false);+ assert.equal(protectedStyle.content.includes(`$$${fake}$$`), false);+ assert.equal(protectedStyle.content.includes("$$\r\n" + fake + "\r\n$$"), true);+ assert.equal(protectedStyle.content.includes(`\`cross\r\n${fake}\r\nline\``), true);+ assert.equal(protectedStyle.content.includes("prose \"), true);+ });++ it("handles long malformed delimiter input in a single scan", () => {+ const unmatchedRuns = Array.from({length: 512}, (_, index) => "`".repeat(index + 1) + "x").join("");+ const occupiedSentinels = Array.from({length: 4096}, (_, index) =>+ `\uE000av-rich-text-style-${index.toString(36)}\uF8FF`).join("");+ const styled = '<span data-type="text">styled</span>' ++ '{: style="font-family: \'A`B` \ 字体\';"}';+ const source = "\\".repeat(65536) + unmatchedRuns + occupiedSentinels + styled;+ const protectedStyle = protectAVRichTextKramdownStyleEntities(source);+ const encoding = createAVRichTextStyleBackslashEncoding(occupiedSentinels);++ assert.equal(protectedStyle.protections.length, 3);+ assert.deepEqual(protectedStyle.protections.map((item) => item.encoded), ["`", "`", "\"]);+ assert.equal(protectedStyle.content.includes(protectedStyle.protections[0].token), true);+ assert.equal(encoding.sentinel, "\uE000av-rich-text-style-35s\uF8FF");+ });++ it("round-trips complex styles through the bundled Lute parser", () => {+ if (typeof Lute === "undefined") {+ require("../../../../stage/protyle/js/lute/lute.min.js");+ }+ const lute = Lute.New();+ lute.SetTextMark(true);+ lute.SetHTMLTag2TextMark(true);+ lute.SetKramdownIAL(true);+ lute.SetSpin(true);+ lute.SetProtyleWYSIWYG(true);+ lute.SetSanitize(true);+ const fontFamily = getInlineFontFamilyStyle("A`B` Semi; 'Quoted' > \\ & {} 字体");+ const style = `font-family: ${fontFamily};`;+ const blockDOM = '<div data-type="NodeParagraph"><div contenteditable="true">' ++ `<span data-type="text" style="${style}">font</span>` ++ "</div></div>";+ const writeEncoding = createAVRichTextStyleBackslashEncoding(blockDOM);+ const protectedBlockDOM = blockDOM.replace(style, writeEncoding.protectStyle(style));+ const persisted = writeEncoding.encodeMarkdown(lute.BlockDOM2Md(protectedBlockDOM).trim());+ const source = `$5 ${persisted} $10`;+ const protectedStyle = protectAVRichTextKramdownStyleEntities(source);+ const parsed = lute.Md2BlockDOM(protectedStyle.content);+ const restored = restoreAVRichTextStyleEntities(parsed, protectedStyle.protections);++ assert.match(persisted, /\/);+ assert.match(persisted, /`/);+ assert.match(persisted, />/);+ assert.equal(protectedStyle.protections.length > 0, true);+ assert.match(restored, /\$5 /);+ assert.match(restored, / \$10/);+ assert.equal(restored.includes(`data-type="text" style="${style}"`), true);+ assert.doesNotMatch(restored, /\{:\s*style=/);+ });++ it("keeps canonical multiline code spans literal through the bundled Lute parser", () => {+ if (typeof Lute === "undefined") {+ require("../../../../stage/protyle/js/lute/lute.min.js");+ }+ const lute = Lute.New();+ lute.SetTextMark(true);+ lute.SetHTMLTag2TextMark(true);+ lute.SetKramdownIAL(true);+ lute.SetSpin(true);+ lute.SetProtyleWYSIWYG(true);+ lute.SetSanitize(true);+ const literal = "<span data-type="text">x</span>" ++ "{: style="font-family: A&#92;B;"}";+ const blockDOM = '<div data-type="NodeParagraph"><div contenteditable="true">' ++ `<span data-type="code">start\n${literal}\nend</span>` ++ "</div></div>";+ const markdown = lute.BlockDOM2Md(blockDOM).trim();+ const protectedStyle = protectAVRichTextKramdownStyleEntities(markdown);+ const parsed = lute.Md2BlockDOM(protectedStyle.content);++ assert.match(markdown, /start\n/);+ assert.deepEqual(protectedStyle.protections, []);+ assert.match(parsed, /data-type="code"/);+ assert.match(parsed, /&#92;/);+ });++ it("projects block content with the same newline rules as the kernel", () => {+ if (typeof Lute === "undefined") {+ require("../../../../stage/protyle/js/lute/lute.min.js");+ }+ const lute = Lute.New();+ lute.SetTextMark(true);+ lute.SetHTMLTag2TextMark(true);+ lute.SetKramdownIAL(true);+ lute.SetSpin(true);+ lute.SetProtyleWYSIWYG(true);+ lute.SetSanitize(true);+ const paragraph = lute.BlockDOM2Content(lute.Md2BlockDOM("first"));+ const code = lute.BlockDOM2Content(lute.Md2BlockDOM("```txt\ncode\n\n```"));+ const next = lute.BlockDOM2Content(lute.Md2BlockDOM("next"));++ assert.equal(code, "code\n\n");+ assert.equal(projectAVRichTextPlainBlocks([paragraph, code, next]), "first\ncode\nnext");+ assert.equal(projectAVRichTextPlainBlocks([paragraph, ""]), "first");+ assert.equal(projectAVRichTextPlainBlocks([], "fallback\n"), "fallback\n");+ });++ it("keeps image emoji aliases literal while preserving Unicode emoji", () => {+ if (typeof Lute === "undefined") {+ require("../../../../stage/protyle/js/lute/lute.min.js");+ }+ const lute = Lute.New();+ lute.SetTextMark(true);+ lute.SetHTMLTag2TextMark(true);+ lute.SetKramdownIAL(true);+ lute.SetSpin(true);+ lute.SetProtyleWYSIWYG(true);+ lute.SetSanitize(true);+ configureAVRichTextLute(lute);+ const markdown = ":siyuan: 😀";+ const blockDOM = lute.Md2BlockDOM(markdown);++ assert.equal(blockDOM.includes("<img"), false);+ assert.match(blockDOM, /:siyuan: 😀/);+ assert.equal(lute.BlockDOM2Content(blockDOM), markdown);+ });++ it("restores every fixed inline syntax switch on the isolated Lute", () => {+ const values = new Map<PropertyKey, boolean>();+ const lute = new Proxy({}, {+ get: (_target, property) => (enabled: boolean) => values.set(property, enabled),+ }) as Lute;++ assert.equal(configureAVRichTextLute(lute), lute);+ for (const property of [+ "SetCustomBlock", "SetGitConflict", "SetInlineAsterisk", "SetInlineUnderscore",+ "SetGFMStrikethrough", "SetSup", "SetSub", "SetTag", "SetInlineMath", "SetMark",+ "SetFullWidthStrikethrough",+ ]) {+ assert.equal(values.get(property), true, property);+ }+ for (const property of ["SetEmoji", "SetGFMStrikethrough1", "SetExportNormalizeTaskListMarker"]) {+ assert.equal(values.get(property), false, property);+ }+ });++ it("uses a strict active-content and interaction policy for previews", () => {+ for (const tag of ["audio", "embed", "iframe", "img", "object", "script", "style", "video"]) {+ assert.equal(AV_RICH_TEXT_PREVIEW_ALLOWED_TAGS.includes(tag), false);+ assert.equal(AV_RICH_TEXT_EDITOR_ALLOWED_TAGS.includes(tag), false);+ }+ for (const attribute of ["onerror", "onclick", "src", "srcdoc", "xlink:href"]) {+ assert.equal(AV_RICH_TEXT_PREVIEW_ALLOWED_ATTRIBUTES.includes(attribute), false);+ if (attribute !== "xlink:href") {+ assert.equal(AV_RICH_TEXT_EDITOR_ALLOWED_ATTRIBUTES.includes(attribute), false);+ }+ }+ assert.deepEqual(AV_RICH_TEXT_PREVIEW_TEXT_ONLY_TAGS, ["sup"]);+ assert.equal(sanitizeAVRichTextInlineMemoContent(+ "&lt;img src=x onerror=alert(1)&gt;memo</img>"+ ), "");+ assert.equal(sanitizeAVRichTextInlineMemoContent("2 < 3\tline\nnext\r\u200D\u200F"),+ "2 < 3\tline\nnext\r\u200D\u200F");+ assert.equal(sanitizeAVRichTextInlineMemoContent("heart <3"), "heart <3");+ assert.equal(sanitizeAVRichTextInlineMemoContent("2 < 3"), "2 < 3");+ assert.equal(sanitizeAVRichTextInlineMemoContent('<span title=">">memo</span>'), "");+ assert.equal(sanitizeAVRichTextInlineMemoContent("<script"), "");+ assert.equal(sanitizeAVRichTextInlineMemoContent("memo </span"), "");+ assert.equal(sanitizeAVRichTextInlineMemoContent("memo <!--"), "");+ assert.equal(sanitizeAVRichTextInlineMemoContent("memo <?xml"), "");+ assert.equal(sanitizeAVRichTextInlineMemoContent("<script>"), "");+ assert.equal(sanitizeAVRichTextInlineMemoContent("memo\u0000content"), "");+ assert.equal(sanitizeAVRichTextInlineMemoContent("memo\u007Fcontent"), "");++ let deeplyEncodedMemo = "&";+ for (let depth = 0; depth < 8; depth++) {+ deeplyEncodedMemo = deeplyEncodedMemo.replace(/&/g, "&");+ }+ assert.equal(sanitizeAVRichTextInlineMemoContent(deeplyEncodedMemo), "");++ for (const unsafe of [+ "javascript:alert(1)",+ "java\nscript:alert(1)",+ "java\u200Bscript:alert(1)",+ "javascript:alert(1)",+ "javascript&colon;alert(1)",+ "java%73cript:alert(1)",+ "vbscript:msgbox(1)",+ "data:text/html,<script>alert(1)</script>",+ "file:///tmp/payload.html",+ "blob:https://example.com/id",+ "ftp://example.com/file",+ "https:example.com",+ "http:///path",+ "siyuan:/blocks/20240101000000-abcdefg",+ "mailto://example.com",+ "mailto:/[email protected]",+ "tel://12025550123",+ "//",+ "///path",+ "/javascript:alert(1)",+ "folder:name",+ "assets/../payload.html",+ "%zz",+ "\\\\server\\payload.html",+ " https://example.com",+ ]) {+ assert.equal(getAVRichTextSafeURL(unsafe), "");+ }+ for (const safe of [+ "https://example.com/a?q=v#f", "mailto:[email protected]", "tel:+12025550123",+ "siyuan://blocks/20240101000000-abcdefg", "web+siyuan://blocks/20240101000000-abcdefg",+ "../relative/note.md", "/relative/note.md", "#section", "?q=v", "//example.com/path",+ "assets/file with space.pdf", "assets/percent%25.txt",+ ]) {+ assert.equal(getAVRichTextSafeURL(safe), safe);+ }+ });++ it("keeps only supported inline color declarations", () => {+ assert.equal(sanitizeAVRichTextInlineStyle(+ "background-color: var(--b3-font-background8); color:var(--b3-font-color2);"+ ), "color: var(--b3-font-color2); background-color: var(--b3-font-background8);");+ assert.equal(sanitizeAVRichTextInlineStyle(+ "color: var(--b3-inline-builtin-info-color, var(--b3-card-info-color)); " ++ "background-color: var(--b3-inline-builtin-info-background-color, " ++ "var(--b3-card-info-background));"+ ), "color: var(--b3-inline-builtin-info-color, var(--b3-card-info-color)); " ++ "background-color: var(--b3-inline-builtin-info-background-color, " ++ "var(--b3-card-info-background));");+ assert.equal(sanitizeAVRichTextInlineStyle(+ "color: var(--b3-inline-style-20260821120000-abcdefg-color, #AABBCC); " ++ "background-color: var(--b3-inline-style-20260821120000-abcdefg-background-color, #112233);"+ ), "color: var(--b3-inline-style-20260821120000-abcdefg-color, #aabbcc); " ++ "background-color: var(--b3-inline-style-20260821120000-abcdefg-background-color, #112233);");+ assert.equal(sanitizeAVRichTextInlineStyle(+ "color: red; background-image: url(https://example.com/pixel); " ++ "background-color: var(--b3-font-background13);"+ ), "background-color: var(--b3-font-background13);");+ assert.equal(sanitizeAVRichTextInlineStyle(+ "color: var(--b3-font-color14); background-color: var(--b3-font-color1);"+ ), "");+ assert.equal(sanitizeAVRichTextInlineStyle(+ "color: var(--b3-font-color8, url(https://example.com/pixel));"+ ), "");+ });++ it("normalizes the complete inline font style set", () => {+ const fontFamily = getInlineFontFamilyStyle("Semi; 'Quoted' > \\ 字体");+ const style = [+ "unicode-bidi: isolate",+ `font-family: ${fontFamily}`,+ "direction: rtl",+ "font-size: .56em",+ "-webkit-text-fill-color: transparent",+ "-webkit-text-stroke: 0.2px var(--b3-theme-on-background)",+ "text-shadow: 1px 1px var(--b3-theme-surface-lighter), " ++ "2px 2px var(--b3-theme-surface-lighter), 3px 3px var(--b3-theme-surface-lighter), " ++ "4px 4px var(--b3-theme-surface-lighter)",+ "--b3-parent-background: var(--b3-font-background2)",+ ].join("; ") + ";";++ assert.equal(sanitizeAVRichTextInlineStyle(style), [+ "font-size: 0.56em;",+ `font-family: ${fontFamily};`,+ "-webkit-text-stroke: 0.2px var(--b3-theme-on-background);",+ "-webkit-text-fill-color: transparent;",+ "text-shadow: 1px 1px var(--b3-theme-surface-lighter), " ++ "2px 2px var(--b3-theme-surface-lighter), 3px 3px var(--b3-theme-surface-lighter), " ++ "4px 4px var(--b3-theme-surface-lighter);",+ "direction: rtl;",+ "unicode-bidi: isolate;",+ ].join(" "));+ });++ it("drops incomplete or non-canonical inline style declarations", () => {+ const maximumFontFamily = getInlineFontFamilyStyle("字".repeat(256));+ assert.equal(sanitizeAVRichTextInlineStyle(+ `font-size: 72.00px; font-family: ${maximumFontFamily};`+ ), `font-size: 72px; font-family: ${maximumFontFamily};`);+ assert.equal(sanitizeAVRichTextInlineStyle(+ "color: var(--b3-font-color2); -webkit-text-stroke: 0.2px var(--b3-theme-on-background); " ++ "direction: ltr; font-size: 8px; font-family: url(https://example.com/font);"+ ), "color: var(--b3-font-color2);");+ assert.equal(sanitizeAVRichTextInlineStyle(+ "-webkit-text-fill-color: transparent; unicode-bidi: isolate; font-size: 4.51em; " ++ "text-shadow: 1px 1px red;"+ ), "");+ assert.equal(sanitizeAVRichTextInlineStyle(+ "font-family: var(--b3-font-family-emoji-reset), 'unterminated; color: var(--b3-font-color2);"+ ), "");+ assert.equal(sanitizeAVRichTextInlineStyle(+ `font-family: ${getInlineFontFamilyStyle("字".repeat(257))};`+ ), "");+ });+});++describe("attribute view text value creation", () => {+ it("creates a rich envelope without mutating the source snapshot", () => {+ const source: IAVCellValue = {+ id: "cell-id",+ type: "text",+ isDetached: true,+ text: {content: "old", rich: null},+ };+ const created = createAVRichTextValue("**new**", "new", source);++ assert.deepEqual(created, {+ id: "cell-id",+ type: "text",+ isDetached: true,+ text: {+ content: "new",+ rich: {spec: 1, format: "kramdown", content: "**new**"},+ },+ });+ assert.deepEqual(source.text, {content: "old", rich: null});+ });++ it("supports omitted and explicit-null rich state for plain writes", () => {+ assert.deepEqual(createAVPlainTextValue("plain"), {+ type: "text",+ text: {content: "plain"},+ });+ assert.deepEqual(createAVPlainTextValue("plain", undefined, true), {+ type: "text",+ text: {content: "plain", rich: null},+ });+ });++ it("preserves template rich text only while its plain projection is unchanged", () => {+ const source: IAVCellValue = {+ type: "text",+ text: {+ content: "projected",+ rich: {spec: 1, format: "kramdown", content: "**projected**"},+ },+ };++ assert.deepEqual(createAVPlainTextEditValue("projected", source).text, source.text);+ assert.deepEqual(createAVPlainTextEditValue("changed", source).text,+ {content: "changed", rich: null});+ assert.deepEqual(createAVPlainTextEditValue("legacy", {type: "text", text: {content: "old"}}).text,+ {content: "legacy"});+ assert.notEqual(createAVPlainTextEditValue("projected", source).text.rich, source.text.rich);+ });++ it("preserves rich data in independent undo snapshots and removes rendered HTML", () => {+ const value: IAVCellValue = {+ type: "text",+ renderedContent: "<strong>preview</strong>",+ text: {+ content: "preview",+ rich: {spec: 1, format: "kramdown", content: "**preview**"},+ },+ };+ const snapshot = cloneAVCellValueSnapshot(value);++ assert.equal(snapshot.renderedContent, undefined);+ assert.deepEqual(snapshot.text, value.text);+ snapshot.text!.rich!.content = "changed";+ assert.equal(value.text!.rich!.content, "**preview**");+ });+});++describe("attribute view rich text DOM policy", () => {+ it("drops unsupported blocks and preserves supported inline marks", {+ skip: hasDOM ? false : "The Node test environment does not provide a DOM implementation",+ }, async () => {+ Object.assign(globalThis, {NODE_ENV: "test", SIYUAN_VERSION: "test"});+ const richText = await import("./richText");+ const blockDOM = [+ '<div data-type="NodeHeading" data-subtype="h2"><div contenteditable="true">heading</div></div>',+ '<div data-type="NodeParagraph"><div contenteditable="true">',+ '<span data-type="tag">tag</span>',+ '<span data-type="file-annotation-ref">annotation</span>',+ '<span data-type="inline-memo" data-inline-memo-content="memo">memo</span>',+ '<span data-type="strong" style="color: var(--b3-font-color2);">unstyled strong</span>',+ '<span data-type="strong text" style="color: var(--b3-font-color2);">styled strong</span>',+ "</div></div>",+ '<div data-type="NodeImage"><span class="img">image</span></div>',+ '<div data-type="NodeTable">table</div>',+ '<div data-type="NodeHTMLBlock">html</div>',+ '<div data-type="NodeBlockQueryEmbed">embed</div>',+ '<div data-type="NodeCodeBlock" data-subtype="mermaid" class="render-node">diagram</div>',+ '<div data-type="NodeCodeBlock" data-subtype="GraphViz options" class="code-block">graph</div>',+ ].join("");+ const sanitized = richText.sanitizeAVRichTextBlockDOM(blockDOM);++ assert.match(sanitized, /data-type="NodeParagraph"[^>]*>.*heading/s);+ assert.match(sanitized, /data-type="tag"/);+ assert.match(sanitized, /data-type="file-annotation-ref"/);+ assert.match(sanitized, /data-type="inline-memo"/);+ assert.match(sanitized, /data-type="strong">unstyled strong/);+ assert.match(sanitized, /data-type="strong text" style="color: var\(--b3-font-color2\);">styled strong/);+ for (const type of ["NodeHeading", "NodeImage", "NodeTable", "NodeHTMLBlock", "NodeBlockQueryEmbed"]) {+ assert.doesNotMatch(sanitized, new RegExp(`data-type="${type}"`));+ }+ assert.doesNotMatch(sanitized, /data-subtype="mermaid"/);+ assert.doesNotMatch(sanitized, /data-subtype="GraphViz options"/);+ });++ it("does not expose generated structure IDs and keeps rendered links identifiable", {+ skip: hasDOM && typeof Lute !== "undefined" ? false :+ "The Node test environment does not provide DOM and Lute globals",+ }, async () => {+ Object.assign(globalThis, {NODE_ENV: "test", SIYUAN_VERSION: "test"});+ const richText = await import("./richText");+ const html = richText.getAVRichTextPreviewHTML("[SiYuan](https://b3log.org/siyuan)");++ assert.doesNotMatch(html, /\sid="[^"]+"/);+ assert.match(html, /data-type="[^"]*a[^"]*"/);+ assert.match(html, /data-href="https:\/\/b3log\.org\/siyuan"/);+ });++ it("flattens inline memo HTML and removes dangerous preview links", {+ skip: hasDOM && typeof Lute !== "undefined" ? false :+ "The Node test environment does not provide DOM and Lute globals",+ }, async () => {+ Object.assign(globalThis, {NODE_ENV: "test", SIYUAN_VERSION: "test"});+ const richText = await import("./richText");+ const markdown = '<span data-type="inline-memo" data-inline-memo-content="' ++ "<img src=x onerror=alert(1)><span data-type=file-annotation-ref " ++ 'data-id=javascript:alert(1)>spoof</span>">memo</span>\n\n' ++ "[unsafe](javascript:alert(1))";+ const html = richText.getAVRichTextPreviewHTML(markdown);++ assert.doesNotMatch(html, /<(?:img|script|iframe)\b/i);+ assert.doesNotMatch(html, /\son\w+=/i);+ assert.doesNotMatch(html, /javascript:/i);+ assert.doesNotMatch(html, /data-type="file-annotation-ref"/i);+ assert.match(html, /<sup>\([^<]*spoof[^<]*\)<\/sup>/i);+ });++ it("round-trips escaped font family names through Kramdown style IAL", {+ skip: hasDOM && typeof Lute !== "undefined" ? false :+ "The Node test environment does not provide DOM and Lute globals",+ }, async () => {+ Object.assign(globalThis, {NODE_ENV: "test", SIYUAN_VERSION: "test"});+ const richText = await import("./richText");+ const fontFamily = getInlineFontFamilyStyle("Semi; 'Quoted' 字体");+ const blockDOM = '<div data-type="NodeParagraph"><div contenteditable="true">' ++ `<span data-type="text" style="font-family: ${fontFamily};">font</span>` ++ "</div></div>";+ const serialized = richText.serializeAVRichTextBlockDOM(blockDOM);++ assert.doesNotMatch(serialized.markdown, /\\'/);+ assert.match(serialized.markdown, /\'Quoted\'/);+ assert.equal(richText.serializeAVRichTextBlockDOM(serialized.blockDOM).markdown, serialized.markdown);+ });+});diff --git a/app/src/protyle/render/av/richText.ts b/app/src/protyle/render/av/richText.tsnew file mode 100644index 0000000000..26ed5c1ed2--- /dev/null+++ b/app/src/protyle/render/av/richText.ts@@ -0,0 +1,406 @@+import {escapeHtml} from "../../../util/escape";+import {highlightRender} from "../highlightRender";+import {getAgentLute} from "../setLute";+import {mathRender} from "../mathRender";+import {+ createAVRichTextStyleBackslashEncoding,+ createAVRichTextStyleEntityReplacer,+ configureAVRichTextLute,+ getAVRichTextSafeURL,+ isAVRichTextExecutableCodeLanguage,+ projectAVRichTextPlainBlocks,+ protectAVRichTextKramdownStyleEntities,+ sanitizeAVRichTextInlineMemoContent,+ sanitizeAVRichTextInlineStyle,+ AV_RICH_TEXT_PREVIEW_SANITIZE_OPTIONS,+ AV_RICH_TEXT_PREVIEW_TEXT_ONLY_TAGS,+ AV_RICH_TEXT_EDITOR_ALLOWED_ATTRIBUTES,+ AV_RICH_TEXT_EDITOR_ALLOWED_TAGS,+} from "./richTextValue";+import type {AVRichTextStyleEntityProtection} from "./richTextValue";++export {+ AV_RICH_TEXT_FORMAT,+ AV_RICH_TEXT_EDITOR_ALLOWED_ATTRIBUTES,+ AV_RICH_TEXT_EDITOR_ALLOWED_TAGS,+ AV_RICH_TEXT_PREVIEW_ALLOWED_ATTRIBUTES,+ AV_RICH_TEXT_PREVIEW_ALLOWED_TAGS,+ AV_RICH_TEXT_PREVIEW_SANITIZE_OPTIONS,+ AV_RICH_TEXT_PREVIEW_TEXT_ONLY_TAGS,+ AV_RICH_TEXT_SPEC,+ configureAVRichTextLute,+ createAVPlainTextValue,+ createAVPlainTextEditValue,+ createAVRichTextStyleBackslashEncoding,+ createAVRichTextValue,+ getAVTextCopyContent,+ getAVTextPlainContent,+ getAVTextSource,+ getAVRichTextSafeURL,+ isAVRichTextExecutableCodeLanguage,+ projectAVRichTextPlainBlocks,+ protectAVRichTextKramdownStyleEntities,+ restoreAVRichTextStyleEntities,+ sanitizeAVRichTextInlineMemoContent,+ sanitizeAVRichTextInlineStyle,+} from "./richTextValue";+export type {AVTextSource} from "./richTextValue";+export const AV_RICH_TEXT_CLASS = "av__celltext--rich";++const ALLOWED_BLOCK_TYPES = new Set([+ "NodeParagraph",+ "NodeList",+ "NodeListItem",+ "NodeBlockquote",+ "NodeCodeBlock",+ "NodeMathBlock",+]);+const ALLOWED_INLINE_TYPES = new Set([+ "a",+ "block-ref",+ "code",+ "em",+ "file-annotation-ref",+ "inline-math",+ "inline-memo",+ "kbd",+ "mark",+ "s",+ "strong",+ "sub",+ "sup",+ "tag",+ "text",+ "u",+]);+const ALLOWED_EDITOR_TAGS = new Set(AV_RICH_TEXT_EDITOR_ALLOWED_TAGS.map((tag) => tag.toUpperCase()));+const previewCache = new Map<string, string>();+const PREVIEW_CACHE_LIMIT = 256;+let richTextLute: Lute | undefined;++// 数据库存储的是稳定的 Kramdown 片段,解析不能跟随用户的 Markdown 语法开关变化。+export const getAVRichTextLute = () => {+ if (!richTextLute) {+ richTextLute = getAgentLute({+ emojiSite: "/emojis",+ emojis: {},+ headingAnchor: false,+ listStyle: false,+ paragraphBeginningSpace: true,+ sanitize: true,+ });+ configureAVRichTextLute(richTextLute);+ }+ return richTextLute;+};++const replaceWithText = (element: Element) => {+ element.replaceWith(document.createTextNode(element.textContent || ""));+};++const removeUnsupportedBlockAttributes = (element: HTMLElement) => {+ Array.from(element.attributes).forEach((attribute) => {+ if (attribute.name.startsWith("custom-") || attribute.name === "bookmark" ||+ attribute.name === "memo" || attribute.name === "name" || attribute.name === "style") {+ element.removeAttribute(attribute.name);+ }+ });+};++export const sanitizeAVRichTextBlockDOM = (blockDOM: string) => {+ const template = document.createElement("template");+ template.innerHTML = blockDOM;+ template.content.querySelectorAll<HTMLElement>('[data-type^="Node"]').forEach((element) => {+ const type = element.dataset.type;+ if (type === "NodeCodeBlock" && (element.classList.contains("render-node") ||+ isAVRichTextExecutableCodeLanguage(element.dataset.subtype || ""))) {+ element.remove();+ return;+ }+ if (ALLOWED_BLOCK_TYPES.has(type)) {+ removeUnsupportedBlockAttributes(element);+ return;+ }+ if (type === "NodeHeading") {+ element.dataset.type = "NodeParagraph";+ element.className = "p";+ element.removeAttribute("data-subtype");+ removeUnsupportedBlockAttributes(element);+ return;+ }+ element.remove();+ });+ template.content.querySelectorAll(+ ".img, img, iframe, audio, video, object, embed, script, style, link, meta, form, input, button, textarea, select"+ ).forEach((element) => {+ element.remove();+ });+ template.content.querySelectorAll<HTMLElement>("*").forEach((element) => {+ if (!ALLOWED_EDITOR_TAGS.has(element.tagName)) {+ replaceWithText(element);+ }+ });+ template.content.querySelectorAll<HTMLElement>("span[data-type]").forEach((element) => {+ const types = (element.dataset.type || "").split(" ").filter(Boolean);+ if (types.some((type) => !ALLOWED_INLINE_TYPES.has(type))) {+ replaceWithText(element);+ return;+ }+ const style = types.includes("text") ? sanitizeAVRichTextInlineStyle(element.getAttribute("style")) : "";+ if (style) {+ element.setAttribute("style", style);+ } else {+ element.removeAttribute("style");+ }+ if (types.includes("inline-memo")) {+ element.dataset.inlineMemoContent = sanitizeAVRichTextInlineMemoContent(+ element.dataset.inlineMemoContent || "");+ }+ });+ template.content.querySelectorAll<HTMLElement>("*").forEach((element) => {+ Array.from(element.attributes).forEach((attribute) => {+ const name = attribute.name.toLowerCase();+ if (!AV_RICH_TEXT_EDITOR_ALLOWED_ATTRIBUTES.includes(name) ||+ name === "xlink:href" && !attribute.value.startsWith("#icon")) {+ element.removeAttribute(attribute.name);+ }+ });+ });+ template.content.querySelectorAll<HTMLElement>('[data-type~="a"][data-href]').forEach((element) => {+ const href = getAVRichTextSafeURL(element.dataset.href);+ if (href) {+ element.dataset.href = href;+ } else {+ element.removeAttribute("data-href");+ }+ });+ template.content.querySelectorAll<HTMLElement>('[data-type~="file-annotation-ref"][data-id]')+ .forEach((element) => {+ if (!getAVRichTextSafeURL(element.dataset.id)) {+ element.removeAttribute("data-id");+ }+ });+ template.content.querySelectorAll<HTMLElement>('[data-type~="block-ref"][data-id]').forEach((element) => {+ if (!/^\d{14}-[a-z0-9]{7}$/.test(element.dataset.id || "")) {+ element.removeAttribute("data-id");+ }+ });+ template.content.querySelectorAll<HTMLElement>("[style]:not(span[data-type])")+ .forEach((element) => element.removeAttribute("style"));+ return (template.innerHTML || "").trim();+};++const cleanAVRichTextBlockDOMStructure = (blockDOM: string) => {+ const template = document.createElement("template");+ template.innerHTML = blockDOM;+ template.content.querySelectorAll(".protyle-attr, .protyle-icons").forEach((element) => element.remove());+ template.content.querySelectorAll<HTMLElement>("*").forEach((element) => {+ ["data-node-id", "data-node-index", "updated"].forEach((attribute) => {+ element.removeAttribute(attribute);+ });+ });+ return (template.innerHTML || "").trim();+};++const protectAVRichTextStyleBackslashes = (+ blockDOM: string,+ encoding: ReturnType<typeof createAVRichTextStyleBackslashEncoding>,+) => {+ const template = document.createElement("template");+ template.innerHTML = blockDOM;+ template.content.querySelectorAll<HTMLElement>('span[data-type~="text"][style]').forEach((element) => {+ element.setAttribute("style", encoding.protectStyle(element.getAttribute("style") || ""));+ });+ return (template.innerHTML || "").trim();+};++const restoreAVRichTextBlockDOMStyleEntities = (+ blockDOM: string,+ protections: AVRichTextStyleEntityProtection[],+) => {+ if (protections.length === 0) {+ return blockDOM;+ }+ const template = document.createElement("template");+ template.innerHTML = blockDOM;+ const restored = new Set<string>();+ const replaceProtections = createAVRichTextStyleEntityReplacer(protections);+ template.content.querySelectorAll<HTMLElement>('span[data-type~="text"][style]').forEach((element) => {+ const style = element.getAttribute("style") || "";+ element.setAttribute("style", replaceProtections(style, true, restored));+ });+ const restoreLiteralText = (element: Element) => {+ const visit = (node: Node) => {+ if (node.nodeType === Node.TEXT_NODE) {+ node.nodeValue = replaceProtections(node.nodeValue || "", false, restored);+ return;+ }+ node.childNodes.forEach(visit);+ };+ visit(element);+ };+ template.content.querySelectorAll('[data-type="NodeCodeBlock"], span[data-type~="code"]')+ .forEach(restoreLiteralText);+ template.content.querySelectorAll<HTMLElement>(+ '[data-type="NodeMathBlock"][data-content], [data-type="NodeMathBlock"] [data-content], ' ++ 'span[data-type~="inline-math"][data-content]'+ ).forEach((element) => {+ element.setAttribute("data-content",+ replaceProtections(element.getAttribute("data-content") || "", false, restored));+ });+ if (protections.some((protection) => !restored.has(protection.token))) {+ throw new Error("Invalid attribute view rich text style entity");+ }+ return (template.innerHTML || "").trim();+};++const parseAVRichTextKramdown = (markdown: string, lute = getAVRichTextLute()) => {+ const protectedStyle = protectAVRichTextKramdownStyleEntities(markdown);+ return restoreAVRichTextBlockDOMStyleEntities(lute.Md2BlockDOM(protectedStyle.content),+ protectedStyle.protections);+};++const getAVRichTextPlainContent = (blockDOM: string, lute: Lute) => {+ const template = document.createElement("template");+ template.innerHTML = blockDOM;+ const blocks = Array.from(template.content.querySelectorAll<HTMLElement>(+ '[data-type="NodeParagraph"], [data-type="NodeCodeBlock"], [data-type="NodeMathBlock"]'+ )).map((element) => lute.BlockDOM2Content(element.outerHTML));+ return projectAVRichTextPlainBlocks(blocks, lute.BlockDOM2Content(blockDOM));+};++export const serializeAVRichTextBlockDOM = (blockDOM: string, lute = getAVRichTextLute()) => {+ const sanitizedBlockDOM = sanitizeAVRichTextBlockDOM(blockDOM);+ const cleanBlockDOM = cleanAVRichTextBlockDOMStructure(sanitizedBlockDOM);+ const styleBackslashEncoding = createAVRichTextStyleBackslashEncoding(cleanBlockDOM);+ const protectedBlockDOM = protectAVRichTextStyleBackslashes(cleanBlockDOM, styleBackslashEncoding);+ const markdown = protectedBlockDOM ?+ styleBackslashEncoding.encodeMarkdown(lute.BlockDOM2Md(protectedBlockDOM).trim()) : "";+ const normalizedBlockDOM = markdown ? sanitizeAVRichTextBlockDOM(parseAVRichTextKramdown(markdown, lute)) : "";+ return {+ blockDOM: normalizedBlockDOM,+ markdown,+ plainText: normalizedBlockDOM ? getAVRichTextPlainContent(normalizedBlockDOM, lute) : "",+ };+};++export const getAVRichTextBlockDOM = (markdown: string) => markdown ?+ sanitizeAVRichTextBlockDOM(parseAVRichTextKramdown(markdown)) : "";++const getAVRichTextPreviewBlockDOM = (blockDOM: string) => {+ const template = document.createElement("template");+ template.innerHTML = cleanAVRichTextBlockDOMStructure(blockDOM);+ template.content.querySelectorAll(".protyle-action").forEach((element) => element.remove());+ return (template.innerHTML || "").trim();+};++const prepareAVRichTextPreviewHTML = (html: string) => {+ const template = document.createElement("template");+ template.innerHTML = window.DOMPurify.sanitize(html, AV_RICH_TEXT_PREVIEW_SANITIZE_OPTIONS);+ template.content.querySelectorAll<HTMLElement>(AV_RICH_TEXT_PREVIEW_TEXT_ONLY_TAGS.join(","))+ .forEach((element) => {+ // BlockDOM2HTML 使用 sup 输出备注内容;这里只保留文本,避免备注伪造可交互标记。+ element.textContent = element.textContent || "";+ });+ template.content.querySelectorAll<HTMLElement>("div.language-math").forEach((element) => {+ const content = element.textContent || "";+ element.className = "render-node";+ element.dataset.subtype = "math";+ element.dataset.content = content;+ element.textContent = "";+ });+ template.content.querySelectorAll<HTMLElement>("pre > code").forEach((element) => {+ const languageClass = Array.from(element.classList).find((className) => className.startsWith("language-"));+ element.parentElement.className = "code-block";+ element.parentElement.dataset.language = languageClass?.slice("language-".length) || "plaintext";+ });+ template.content.querySelectorAll<HTMLElement>("*").forEach((element) => {+ ["id", "data-node-id", "data-node-index", "updated", "contenteditable", "spellcheck", "draggable"]+ .forEach((attribute) => element.removeAttribute(attribute));+ const types = (element.dataset.type || "").split(" ").filter(Boolean);+ const style = element.tagName === "SPAN" && types.includes("text") ?+ sanitizeAVRichTextInlineStyle(element.getAttribute("style")) : "";+ if (style) {+ element.setAttribute("style", style);+ } else {+ element.removeAttribute("style");+ }+ });+ template.content.querySelectorAll<HTMLInputElement>("input").forEach((element) => {+ if (element.type !== "checkbox") {+ element.remove();+ return;+ }+ element.disabled = true;+ });+ template.content.querySelectorAll<HTMLElement>("[data-href], a[href]").forEach((element) => {+ const href = getAVRichTextSafeURL(element.getAttribute("href") || element.dataset.href);+ if (!href) {+ element.removeAttribute("href");+ element.removeAttribute("data-href");+ return;+ }+ element.setAttribute("href", href);+ element.dataset.href = href;+ });+ template.content.querySelectorAll<HTMLElement>('[data-type~="file-annotation-ref"][data-id]')+ .forEach((element) => {+ if (!getAVRichTextSafeURL(element.dataset.id)) {+ element.removeAttribute("data-id");+ }+ });+ template.content.querySelectorAll<HTMLAnchorElement>("a[href]").forEach((element) => {+ const types = new Set((element.dataset.type || "").split(" ").filter(Boolean));+ types.add("a");+ element.dataset.type = Array.from(types).join(" ");+ });+ return template.innerHTML;+};++export const getAVRichTextPreviewHTML = (markdown: string) => {+ if (!markdown) {+ return "";+ }+ const cached = previewCache.get(markdown);+ if (typeof cached === "string") {+ previewCache.delete(markdown);+ previewCache.set(markdown, cached);+ return cached;+ }+ try {+ const lute = getAVRichTextLute();+ const blockDOM = getAVRichTextBlockDOM(markdown);+ const previewBlockDOM = getAVRichTextPreviewBlockDOM(blockDOM);+ const html = previewBlockDOM ? prepareAVRichTextPreviewHTML(lute.BlockDOM2HTML(previewBlockDOM)) : "";+ previewCache.set(markdown, html);+ if (previewCache.size > PREVIEW_CACHE_LIMIT) {+ const oldestKey = previewCache.keys().next().value;+ if (oldestKey) {+ previewCache.delete(oldestKey);+ }+ }+ return html;+ } catch (error) {+ console.error(error);+ return escapeHtml(markdown);+ }+};++export const renderAVRichTextElements = (root: Element) => {+ const selector = `.${AV_RICH_TEXT_CLASS}:not([data-rich-rendered="true"])`;+ const elements: HTMLElement[] = [];+ if (root.matches(selector)) {+ elements.push(root as HTMLElement);+ }+ elements.push(...root.querySelectorAll<HTMLElement>(selector));+ if (elements.length === 0) {+ return;+ }+ elements.forEach((element) => {+ element.dataset.richRendered = "true";+ });+ elements.forEach((element) => {+ mathRender(element);+ highlightRender(element);+ });+};diff --git a/app/src/protyle/render/av/richTextEditor.ts b/app/src/protyle/render/av/richTextEditor.tsnew file mode 100644index 0000000000..e9cc12024e--- /dev/null+++ b/app/src/protyle/render/av/richTextEditor.ts@@ -0,0 +1,218 @@+import {escapeHtml} from "../../../util/escape";+import {isMobile} from "../../../util/functions";+import {callMobileAppShowKeyboard} from "../../../mobile/util/mobileAppUtil";+import {hintRef, hintSlash} from "../../hint/extend";+import {mountProtyleLiteFragment} from "../../lite/fragmentEditor";+import {highlightRender} from "../highlightRender";+import {mathRender} from "../mathRender";+import {+ configureAVRichTextLute,+ createAVRichTextValue,+ getAVRichTextLute,+ getAVRichTextBlockDOM,+ getAVTextSource,+ sanitizeAVRichTextBlockDOM,+ serializeAVRichTextBlockDOM,+} from "./richText";++const SAFE_SLASH_IDS = new Set([+ "ref",+ "list",+ "orderedList",+ "check",+ "quote",+ "code",+ "math",+ "link",+ "bold",+ "italic",+ "underline",+ "strike",+ "mark",+ "sup",+ "sub",+ "inlineCode",+ "kbd",+ "tag",+ "inlineMath",+]);++interface AVRichTextEditorOptions {+ protyle: IProtyle;+ nodeElement: HTMLElement;+ anchorElement: HTMLElement;+ value: IAVCellValue;+ stableCells: import("./selectionState").IAVSelectedCell[];+ onSave: (value: IAVCellValue, nodeElement: HTMLElement,+ stableCells: import("./selectionState").IAVSelectedCell[]) => void | Promise<void>;+ onDestroy?: () => void;+}++interface ActiveEditor {+ finish: (save: boolean) => Promise<void>;+}++let activeEditor: ActiveEditor | undefined;++const prepareHint = (protyle: IProtyle) => {+ if (protyle.hint.element.classList.contains("fn__none")) {+ protyle.hint.element.style.zIndex = (++window.siyuan.zIndex).toString();+ }+};++const hintAVRef = (key: string, protyle: IProtyle, source: THintSource) => {+ prepareHint(protyle);+ return hintRef(key, protyle, source);+};++const hintAVSlash = (key: string, protyle: IProtyle, source: THintSource) => {+ prepareHint(protyle);+ return hintSlash(key, protyle, source).filter((item) => item.id && SAFE_SLASH_IDS.has(item.id));+};++const setPanelPosition = (panelElement: HTMLElement, anchorElement: HTMLElement) => {+ if (isMobile()) {+ panelElement.classList.add("av__richtext-editor--mobile");+ panelElement.removeAttribute("style");+ return;+ }+ const margin = 8;+ const anchorRect = anchorElement.getBoundingClientRect();+ const width = Math.min(Math.max(anchorRect.width, 420), window.innerWidth - margin * 2);+ const maxHeight = Math.max(240, Math.min(480, window.innerHeight - margin * 2));+ const left = Math.min(Math.max(anchorRect.left, margin), window.innerWidth - width - margin);+ const availableBelow = window.innerHeight - anchorRect.bottom - margin;+ const top = availableBelow >= Math.min(maxHeight, 320) ? anchorRect.bottom :+ Math.max(margin, anchorRect.top - maxHeight);+ panelElement.style.left = `${left}px`;+ panelElement.style.top = `${top}px`;+ panelElement.style.width = `${width}px`;+ panelElement.style.maxHeight = `${maxHeight}px`;+};++export const destroyAVRichTextEditor = (save = false) => {+ void activeEditor?.finish(save);+};++export const openAVRichTextEditor = (options: AVRichTextEditorOptions) => {+ void activeEditor?.finish(false);++ const maskElement = document.createElement("div");+ maskElement.className = "av__mask av__richtext-mask";+ maskElement.style.zIndex = (++window.siyuan.zIndex).toString();+ maskElement.innerHTML = `<div class="av__richtext-editor" role="dialog">+ <div class="av__richtext-host"></div>+ <div class="av__richtext-actions">+ <button type="button" class="b3-button b3-button--cancel" data-type="cancel">${escapeHtml(window.siyuan.languages.cancel)}</button>+ <button type="button" class="b3-button b3-button--text" data-type="save">${escapeHtml(window.siyuan.languages.save)}</button>+ </div>+</div>`;+ document.body.appendChild(maskElement);+ const panelElement = maskElement.firstElementChild as HTMLElement;+ const hostElement = panelElement.querySelector<HTMLElement>(".av__richtext-host");+ hostElement.dataset.protyleLiteRender = "safe";+ setPanelPosition(panelElement, options.anchorElement);++ const source = getAVTextSource(options.value);+ const toolbar: IProtyleOptions["toolbar"] = [+ "block-ref", "a", "|", "text", "strong", "em", "u", "s", "mark", "sup", "sub",+ "code", "kbd", "tag", "inline-math", "inline-memo", "clear",+ ];+ const hint: IProtyleOptions["hint"] = {+ extend: [{key: "((", hint: hintAVRef}, {key: "【【", hint: hintAVRef},+ {key: "((", hint: hintAVRef}, {key: "[[", hint: hintAVRef},+ {key: "/", hint: hintAVSlash}, {key: "、", hint: hintAVSlash}],+ };+ const fragment = mountProtyleLiteFragment(hostElement, {+ initialBlockHTML: source.kind === "rich" ? getAVRichTextBlockDOM(source.content) : undefined,+ initialPlainText: source.kind === "plain" ? source.content : undefined,+ placeholder: window.siyuan.languages.empty,+ protyleOptions: {+ notebookId: options.protyle.notebookId ||+ options.nodeElement.closest<HTMLElement>(".protyle")?.dataset.notebookId,+ toolbar,+ hint,+ },+ runtimeCapabilities: {+ upload: false,+ websocket: false,+ lute: getAVRichTextLute(),+ lockedOptions: {toolbar, hint},+ pluginExtensions: false,+ customBlockRender: false,+ sanitizeBlockDOM: sanitizeAVRichTextBlockDOM,+ restoreLuteMarkdownSyntax: configureAVRichTextLute,+ },+ afterSetContent: (protyle, element) => {+ mathRender(element);+ highlightRender(element);+ protyle.undo.clear();+ },+ });+ const initialMarkdown = serializeAVRichTextBlockDOM(fragment.getBlockHTML()).markdown;++ let finished = false;+ let cancelled = false;+ const isOwnerConnected = () => options.protyle.element.isConnected && options.nodeElement.isConnected &&+ options.anchorElement.isConnected;+ const resize = () => setPanelPosition(panelElement, options.anchorElement);+ window.addEventListener("resize", resize);+ const ownerObserver = new MutationObserver(() => {+ if (!isOwnerConnected()) {+ void finish(false);+ }+ });+ ownerObserver.observe(document.body, {childList: true, subtree: true});++ const finish = async (save: boolean) => {+ if (!save) {+ cancelled = true;+ }+ if (finished) {+ return;+ }+ finished = true;+ try {+ if (save) {+ await fragment.protyle.wysiwyg.flushPendingInput();+ if (cancelled || !isOwnerConnected()) {+ return;+ }+ const serialized = serializeAVRichTextBlockDOM(fragment.getBlockHTML());+ if (serialized.markdown !== initialMarkdown) {+ await options.onSave(createAVRichTextValue(serialized.markdown, serialized.plainText, options.value),+ options.nodeElement, options.stableCells);+ }+ }+ } finally {+ ownerObserver.disconnect();+ window.removeEventListener("resize", resize);+ fragment.destroy();+ maskElement.remove();+ if (activeEditor?.finish === finish) {+ activeEditor = undefined;+ }+ options.onDestroy?.();+ }+ };++ activeEditor = {finish};+ maskElement.addEventListener("mousedown", (event) => {+ if (event.target === maskElement) {+ void finish(true);+ }+ });+ panelElement.querySelector('[data-type="cancel"]').addEventListener("click", () => void finish(false));+ panelElement.querySelector('[data-type="save"]').addEventListener("click", () => void finish(true));+ panelElement.addEventListener("keydown", (event: KeyboardEvent) => {+ if (event.key === "Escape" && fragment.hintElement.classList.contains("fn__none") &&+ fragment.protyle.toolbar.element.classList.contains("fn__none") &&+ fragment.protyle.toolbar.subElement.classList.contains("fn__none")) {+ event.preventDefault();+ event.stopPropagation();+ void finish(false);+ }+ }, true);+ fragment.focus(true);+ callMobileAppShowKeyboard();+};diff --git a/app/src/protyle/render/av/richTextValue.ts b/app/src/protyle/render/av/richTextValue.tsnew file mode 100644index 0000000000..cd3b211fa4--- /dev/null+++ b/app/src/protyle/render/av/richTextValue.ts@@ -0,0 +1,921 @@+import {getInlineFontFamilyName, getInlineFontFamilyStyle} from "../../toolbar/fontFamilyCore";++export const AV_RICH_TEXT_SPEC = 1 as const;+export const AV_RICH_TEXT_FORMAT = "kramdown" as const;+export const AV_RICH_TEXT_PREVIEW_ALLOWED_TAGS = [+ "a", "blockquote", "br", "code", "div", "em", "input", "kbd", "li", "mark", "ol", "p", "pre",+ "s", "span", "strong", "sub", "sup", "u", "ul",+];+export const AV_RICH_TEXT_PREVIEW_ALLOWED_ATTRIBUTES = [+ "checked", "class", "data-content", "data-href", "data-id", "data-language", "data-subtype", "data-type",+ "disabled", "href", "style", "title", "type",+];+export const AV_RICH_TEXT_PREVIEW_TEXT_ONLY_TAGS = ["sup"];+export const AV_RICH_TEXT_EDITOR_ALLOWED_TAGS = ["br", "div", "span", "svg", "use", "wbr"];+export const AV_RICH_TEXT_EDITOR_ALLOWED_ATTRIBUTES = [+ "aria-label", "class", "contenteditable", "data-content", "data-href", "data-id", "data-inline-memo-content",+ "data-marker", "data-node-id", "data-node-index", "data-position", "data-subtype", "data-type", "draggable",+ "spellcheck", "spin", "style", "updated", "xlink:href",+];+export const AV_RICH_TEXT_PREVIEW_SANITIZE_OPTIONS = {+ ALLOWED_TAGS: AV_RICH_TEXT_PREVIEW_ALLOWED_TAGS,+ ALLOWED_ATTR: AV_RICH_TEXT_PREVIEW_ALLOWED_ATTRIBUTES,+ ALLOW_ARIA_ATTR: false,+ ALLOW_DATA_ATTR: false,+ ALLOWED_URI_REGEXP: /^(?:(?:https?|mailto|siyuan|tel|web\+siyuan):|[#/?]|\.\.?\/|[^a-z]|[a-z0-9._~-]+(?:[/?#]|$))/i,+};+const BUILTIN_INLINE_COLOR_COUNT = 13;+const MAX_INLINE_FONT_FAMILY_LENGTH = 256;+type AVRichTextStyleProperty = "color" | "background-color";++const HOLLOW_STROKE = "0.2px var(--b3-theme-on-background)";+const HOLLOW_FILL = "transparent";+const TEXT_SHADOW = "1px 1px var(--b3-theme-surface-lighter), " ++ "2px 2px var(--b3-theme-surface-lighter), 3px 3px var(--b3-theme-surface-lighter), " ++ "4px 4px var(--b3-theme-surface-lighter)";+const FONT_FAMILY_PATTERN = /^var\(--b3-font-family-emoji-reset\)\s*,\s*(?:'(?:\\[\s\S]|[^'\\])*'|"(?:\\[\s\S]|[^"\\])*")\s*,\s*var\(--b3-font-family-editor\)\s*,\s*var\(--b3-font-family\)$/;++const EXECUTABLE_CODE_LANGUAGES = new Set([+ "abc",+ "echarts",+ "flowchart",+ "graphviz",+ "infographic",+ "mermaid",+ "mindmap",+ "plantuml",+]);++export type AVTextSource = {+ kind: "plain" | "rich";+ content: string;+};++export interface AVRichTextStyleEntityProtection {+ token: string;+ encoded: string;+ decoded: string;+}++const AV_RICH_TEXT_FORMAT_CHARACTER = /\p{Cf}/u;++const isAVRichTextControlOrFormatCharacter = (character: string) => {+ const codePoint = character.codePointAt(0) || 0;+ return codePoint <= 0x1F || 0x7F <= codePoint && codePoint <= 0x9F ||+ AV_RICH_TEXT_FORMAT_CHARACTER.test(character);+};++const hasUnsafeAVRichTextURLCharacter = (value: string) => Array.from(value).some((character) =>+ character === "\\" || isAVRichTextControlOrFormatCharacter(character));++const hasValidAVRichTextUnicode = (value: string) => {+ for (let index = 0; index < value.length; index++) {+ const code = value.charCodeAt(index);+ if (0xD800 <= code && code <= 0xDBFF) {+ if (index + 1 >= value.length) {+ return false;+ }+ const next = value.charCodeAt(++index);+ if (next < 0xDC00 || 0xDFFF < next) {+ return false;+ }+ } else if (0xDC00 <= code && code <= 0xDFFF) {+ return false;+ }+ }+ return true;+};++const unescapeAVRichTextHTML = (value: string) => {+ if (typeof Lute !== "undefined") {+ return Lute.UnEscapeHTMLStr(value);+ }+ return value.replace(/&(?:amp|apos|colon|gt|lt|newline|quot|rlm|tab|zerowidthspace|zwj|zwnj|#(?:x[0-9a-f]+|\d+));/gi,+ (entity) => {+ const named: Record<string, string> = {+ "&": "&", ":": ":", ">": ">", "<": "<", """: '"', "'": "'",+ "&newline;": "\n", "‏": "\u200F", "&tab;": "\t", "&zerowidthspace;": "\u200B",+ "‍": "\u200D", "‌": "\u200C",+ };+ const normalized = entity.toLowerCase();+ if (named[normalized]) {+ return named[normalized];+ }+ const numeric = normalized.match(/^&#(x[0-9a-f]+|\d+);$/);+ const codePoint = numeric?.[1].startsWith("x") ? Number.parseInt(numeric[1].slice(1), 16) :+ Number.parseInt(numeric?.[1] || "", 10);+ return Number.isInteger(codePoint) && 0 < codePoint && codePoint <= 0x10FFFF ?+ String.fromCodePoint(codePoint) : entity;+ });+};++const decodeAVRichTextHTMLEntities = (value: string) => {+ let decoded = value;+ for (let depth = 0; depth < 8; depth++) {+ const next = unescapeAVRichTextHTML(decoded);+ if (next === decoded) {+ return decoded;+ }+ decoded = next;+ }+ return unescapeAVRichTextHTML(decoded) === decoded ? decoded : undefined;+};++export const sanitizeAVRichTextInlineMemoContent = (value: string) => {+ const hasDisallowedControl = (candidate: string) => Array.from(candidate).some((character) => {+ const codePoint = character.codePointAt(0) || 0;+ return (codePoint <= 0x1F || 0x7F <= codePoint && codePoint <= 0x9F) &&+ codePoint !== 0x09 && codePoint !== 0x0A && codePoint !== 0x0D;+ });+ if (!hasValidAVRichTextUnicode(value) || hasDisallowedControl(value)) {+ return "";+ }++ let decoded = value;+ let stable = false;+ for (let depth = 0; depth < 8; depth++) {+ const next = unescapeAVRichTextHTML(decoded);+ if (!hasValidAVRichTextUnicode(next) || hasDisallowedControl(next)) {+ return "";+ }+ if (next === decoded) {+ stable = true;+ break;+ }+ decoded = next;+ }+ if (!stable) {+ return "";+ }++ for (let start = decoded.indexOf("<"); start >= 0; start = decoded.indexOf("<", start + 1)) {+ let index = start + 1;+ if (decoded[index] === "/") {+ index++;+ if (/[A-Za-z]/.test(decoded[index] || "")) {+ return "";+ }+ continue;+ }+ if (/[A-Za-z!?]/.test(decoded[index] || "")) {+ return "";+ }+ }+ return value;+};++const isCleanAVRichTextAssetPath = (value: string) => {+ const path = value.split(/[?#]/, 1)[0];+ const relativePath = path.startsWith("/") ? path.slice(1) : path;+ if (!relativePath.startsWith("assets/")) {+ return true;+ }+ const segments = path.split("/");+ const cleanSegments: string[] = [];+ segments.forEach((segment) => {+ if (!segment || segment === ".") {+ return;+ }+ if (segment === "..") {+ cleanSegments.pop();+ } else {+ cleanSegments.push(segment);+ }+ });+ const cleanPath = `${path.startsWith("/") ? "/" : ""}${cleanSegments.join("/")}` || ".";+ return cleanPath === path;+};++export const getAVRichTextSafeURL = (value?: string | null) => {+ const original = value || "";+ if (!original) {+ return "";+ }+ if (original.trim() !== original || !hasValidAVRichTextUnicode(original)) {+ return "";+ }+ const url = decodeAVRichTextHTMLEntities(original);+ if (typeof url !== "string" || hasUnsafeAVRichTextURLCharacter(url)) {+ return "";+ }+ let percentDecoded: string;+ try {+ percentDecoded = decodeURIComponent(url);+ } catch {+ return "";+ }+ if (!hasValidAVRichTextUnicode(percentDecoded) || hasUnsafeAVRichTextURLCharacter(percentDecoded)) {+ return "";+ }+ const scheme = url.match(/^([a-z][a-z0-9+.-]*):/i)?.[1].toLowerCase();+ if (scheme) {+ if (scheme === "mailto" || scheme === "tel") {+ const opaque = url.slice(scheme.length + 1);+ return opaque && !opaque.startsWith("/") ? url : "";+ }+ if (scheme !== "http" && scheme !== "https" && scheme !== "siyuan" && scheme !== "web+siyuan") {+ return "";+ }+ if (!url.toLowerCase().startsWith(`${scheme}://`)) {+ return "";+ }+ const authority = url.slice(scheme.length + 3).split(/[/?#]/, 1)[0];+ if (!authority) {+ return "";+ }+ try {+ const parsed = new URL(url);+ return parsed.host && parsed.protocol === `${scheme}:` ? url : "";+ } catch {+ return "";+ }+ }+ if (url.startsWith("//")) {+ const authority = url.slice(2).split(/[/?#]/, 1)[0];+ if (!authority) {+ return "";+ }+ try {+ if (!new URL(`https:${url}`).host) {+ return "";+ }+ } catch {+ return "";+ }+ } else {+ const firstPathSegment = percentDecoded.replace(/^\/+/, "").split(/[/?#]/, 1)[0];+ if (firstPathSegment.includes(":")) {+ return "";+ }+ }+ return isCleanAVRichTextAssetPath(percentDecoded) ? url : "";+};++export const configureAVRichTextLute = (lute: Lute) => {+ const fixedLute = lute as Lute & {+ SetEmoji: (enabled: boolean) => void;+ SetGitConflict: (enabled: boolean) => void;+ };+ fixedLute.SetEmoji(false);+ fixedLute.SetCustomBlock(true);+ fixedLute.SetGitConflict(true);+ fixedLute.SetInlineAsterisk(true);+ fixedLute.SetInlineUnderscore(true);+ fixedLute.SetGFMStrikethrough1(false);+ fixedLute.SetGFMStrikethrough(true);+ fixedLute.SetSup(true);+ fixedLute.SetSub(true);+ fixedLute.SetTag(true);+ fixedLute.SetInlineMath(true);+ fixedLute.SetMark(true);+ fixedLute.SetFullWidthStrikethrough(true);+ fixedLute.SetExportNormalizeTaskListMarker(false);+ return lute;+};++const escapeAVRichTextRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");++const createAVRichTextStyleSentinel = (source: string) => {+ const used = new Set<string>();+ const sentinelPattern = /\uE000av-rich-text-style-([0-9a-z]+)\uF8FF/g;+ for (let match = sentinelPattern.exec(source); match; match = sentinelPattern.exec(source)) {+ used.add(match[1]);+ }+ let index = 0;+ while (used.has(index.toString(36))) {+ index++;+ }+ return `\uE000av-rich-text-style-${index.toString(36)}\uF8FF`;+};++export const createAVRichTextStyleBackslashEncoding = (source: string) => {+ const sentinel = createAVRichTextStyleSentinel(source);+ const backslashSentinel = `${sentinel}\uE003`;+ const backtickSentinel = `${sentinel}\uE004`;+ return {+ sentinel,+ protectStyle: (style: string) => style.replace(/[\\`]/g,+ (character) => character === "\\" ? backslashSentinel : backtickSentinel),+ encodeMarkdown: (markdown: string) => markdown+ .replaceAll(backslashSentinel, "\")+ .replaceAll(backtickSentinel, "`"),+ };+};++const findAVRichTextQuotedEnd = (content: string, start: number, end: number, terminator: string) => {+ let quote = "";+ let escaped = false;+ for (let index = start; index < end; index++) {+ const character = content[index];+ if (escaped) {+ escaped = false;+ } else if (character === "\\") {+ escaped = true;+ } else if (quote) {+ if (character === quote) {+ quote = "";+ }+ } else if (character === "'" || character === '"') {+ quote = character;+ } else if (character === terminator) {+ return index;+ }+ }+ return -1;+};++const getAVRichTextQuotedAttribute = (content: string, start: number, end: number, expected: string) => {+ let index = start;+ while (index < end) {+ while (index < end && /\s/.test(content[index])) {+ index++;+ }+ if (content[index] === "." || content[index] === "#") {+ while (index < end && !/\s/.test(content[index])) {+ index++;+ }+ continue;+ }+ const nameStart = index;+ while (index < end && /[-:\w]/.test(content[index])) {+ index++;+ }+ if (nameStart === index) {+ index++;+ continue;+ }+ const name = content.slice(nameStart, index);+ while (index < end && /\s/.test(content[index])) {+ index++;+ }+ if (content[index] !== "=") {+ continue;+ }+ index++;+ while (index < end && /\s/.test(content[index])) {+ index++;+ }+ const quote = content[index];+ if (quote !== "'" && quote !== '"') {+ while (index < end && !/\s/.test(content[index])) {+ index++;+ }+ continue;+ }+ const valueStart = ++index;+ let escaped = false;+ while (index < end) {+ const character = content[index];+ if (escaped) {+ escaped = false;+ } else if (character === "\\") {+ escaped = true;+ } else if (character === quote) {+ break;+ }+ index++;+ }+ if (index >= end) {+ return;+ }+ if (name === expected) {+ return {start: valueStart, end: index, value: content.slice(valueStart, index)};+ }+ index++;+ }+};++const getAVRichTextMarkdownContainerContent = (line: string) => {+ let index = 0;+ while (index < line.length) {+ while (index < line.length && (line[index] === " " || line[index] === "\t")) {+ index++;+ }+ if (line[index] === ">") {+ index++;+ if (line[index] === " " || line[index] === "\t") {+ index++;+ }+ continue;+ }+ const list = line.slice(index).match(/^(?:[-+*]|\d+[.)])[ \t]+/);+ if (list) {+ index += list[0].length;+ continue;+ }+ break;+ }+ return line.slice(index);+};++const getAVRichTextDelimiterRun = (content: string, index: number, character: string) => {+ let end = index;+ while (content[end] === character) {+ end++;+ }+ return end - index;+};++interface AVRichTextLiteralRange {+ start: number;+ end: number;+}++const getAVRichTextLiteralBlockRanges = (markdown: string) => {+ const ranges: AVRichTextLiteralRange[] = [];+ let open: {start: number, character: string, length: number, math: boolean} | undefined;+ for (let lineStart = 0; lineStart <= markdown.length;) {+ let lineEnd = markdown.indexOf("\n", lineStart);+ if (lineEnd < 0) {+ lineEnd = markdown.length;+ }+ const contentEnd = lineEnd > lineStart && markdown[lineEnd - 1] === "\r" ? lineEnd - 1 : lineEnd;+ const structuralContent = getAVRichTextMarkdownContainerContent(markdown.slice(lineStart, contentEnd));+ const nextLine = lineEnd < markdown.length ? lineEnd + 1 : markdown.length;+ if (open?.math) {+ if (structuralContent.trim() === "$$") {+ ranges.push({start: open.start, end: nextLine});+ open = undefined;+ }+ } else if (open) {+ const closingRun = getAVRichTextDelimiterRun(structuralContent, 0, open.character);+ if (closingRun >= open.length && structuralContent.slice(closingRun).trim() === "") {+ ranges.push({start: open.start, end: nextLine});+ open = undefined;+ }+ } else {+ const fence = structuralContent.match(/^(`{3,}|~{3,})/);+ if (fence && (fence[1][0] !== "`" || !structuralContent.slice(fence[1].length).includes("`"))) {+ open = {start: lineStart, character: fence[1][0], length: fence[1].length, math: false};+ } else if (structuralContent.trim() === "$$") {+ open = {start: lineStart, character: "$", length: 2, math: true};+ }+ }+ if (lineEnd === markdown.length) {+ break;+ }+ lineStart = nextLine;+ }+ if (open) {+ ranges.push({start: open.start, end: markdown.length});+ }+ return ranges;+};++const getAVRichTextLiteralRanges = (markdown: string) => {+ const blockRanges = getAVRichTextLiteralBlockRanges(markdown);+ const ranges = [...blockRanges];+ const escaped = new Uint8Array(markdown.length);+ let backslashes = 0;+ for (let index = 0; index < markdown.length; index++) {+ escaped[index] = backslashes % 2;+ backslashes = markdown[index] === "\\" ? backslashes + 1 : 0;+ }+ const paragraphBreaks: AVRichTextLiteralRange[] = [];+ const paragraphBreakPattern = /\r?\n[ \t]*(?:\r?\n|$)/g;+ for (let match = paragraphBreakPattern.exec(markdown); match; match = paragraphBreakPattern.exec(markdown)) {+ paragraphBreaks.push({start: match.index, end: match.index + match[0].length});+ }+ let runs: {start: number, end: number, length: number}[] = [];+ const flushRuns = () => {+ const nextByLength = new Map<number, number>();+ const nextSame = new Array<number>(runs.length).fill(-1);+ for (let index = runs.length - 1; index >= 0; index--) {+ nextSame[index] = nextByLength.get(runs[index].length) ?? -1;+ nextByLength.set(runs[index].length, index);+ }+ for (let index = 0; index < runs.length;) {+ const closing = nextSame[index];+ if (closing < 0) {+ index++;+ continue;+ }+ ranges.push({start: runs[index].start, end: runs[closing].end});+ index = closing + 1;+ }+ runs = [];+ };+ let blockIndex = 0;+ let breakIndex = 0;+ for (let index = 0; index < markdown.length;) {+ while (blockIndex < blockRanges.length && blockRanges[blockIndex].end <= index) {+ blockIndex++;+ }+ const block = blockRanges[blockIndex];+ if (block && block.start <= index) {+ flushRuns();+ index = block.end;+ continue;+ }+ while (breakIndex < paragraphBreaks.length && paragraphBreaks[breakIndex].end <= index) {+ breakIndex++;+ }+ const paragraphBreak = paragraphBreaks[breakIndex];+ if (paragraphBreak && paragraphBreak.start <= index) {+ flushRuns();+ index = paragraphBreak.end;+ continue;+ }+ if (markdown[index] === "<") {+ const tagEnd = findAVRichTextQuotedEnd(markdown, index + 1,+ Math.min(block?.start ?? markdown.length, paragraphBreak?.start ?? markdown.length), ">");+ if (tagEnd >= 0) {+ index = tagEnd + 1;+ continue;+ }+ } else if (markdown.startsWith("{:", index)) {+ const ialEnd = findAVRichTextQuotedEnd(markdown, index + 2,+ Math.min(block?.start ?? markdown.length, paragraphBreak?.start ?? markdown.length), "}");+ if (ialEnd >= 0) {+ index = ialEnd + 1;+ continue;+ }+ }+ if (markdown[index] !== "`" || escaped[index]) {+ index++;+ continue;+ }+ const run = getAVRichTextDelimiterRun(markdown, index, "`");+ runs.push({start: index, end: index + run, length: run});+ index += run;+ }+ flushRuns();+ return ranges.sort((left, right) => left.start - right.start);+};++const decodeAVRichTextStyleEntity = (entity: string) => {+ const named: Record<string, string> = {+ "&": "&",+ "'": "'",+ ">": ">",+ "<": "<",+ """: '"',+ };+ if (typeof named[entity] === "string") {+ return named[entity];+ }+ const numeric = entity.match(/^&#(x[0-9a-f]+|\d+);$/i);+ if (!numeric) {+ return;+ }+ const codePoint = numeric[1][0].toLowerCase() === "x" ?+ Number.parseInt(numeric[1].slice(1), 16) : Number.parseInt(numeric[1], 10);+ if (!Number.isInteger(codePoint) || codePoint <= 0 || codePoint > 0x10FFFF ||+ 0xD800 <= codePoint && codePoint <= 0xDFFF) {+ return;+ }+ return String.fromCodePoint(codePoint);+};++export const createAVRichTextStyleEntityReplacer = (protections: AVRichTextStyleEntityProtection[]) => {+ const entities = new Map(protections.map((protection) => [protection.token, protection]));+ const sentinelEnd = protections[0]?.token.indexOf("\uF8FF") ?? -1;+ const sentinel = sentinelEnd < 0 ? "" : protections[0].token.slice(0, sentinelEnd + 1);+ const tokenPattern = sentinel ? new RegExp(`${escapeAVRichTextRegExp(sentinel)}[0-9a-z]+\uE002`, "g") : undefined;+ return (+ value: string,+ useDecodedValue: boolean,+ restored?: Set<string>,+ ) => {+ if (!tokenPattern) {+ return value;+ }+ tokenPattern.lastIndex = 0;+ return value.replace(tokenPattern, (token) => {+ const entity = entities.get(token);+ if (!entity) {+ return token;+ }+ restored?.add(token);+ return useDecodedValue ? entity.decoded : entity.encoded;+ });+ };+};++export const restoreAVRichTextStyleEntities = (+ value: string,+ protections: AVRichTextStyleEntityProtection[],+) => createAVRichTextStyleEntityReplacer(protections)(value, true);++export const projectAVRichTextPlainBlocks = (blocks: string[], fallback = "") => blocks.length === 0 ? fallback :+ blocks.map((block) => block.replace(/\n+$/, "")).join("\n").replace(/\n+$/, "");++export const protectAVRichTextKramdownStyleEntities = (markdown: string) => {+ const sentinel = createAVRichTextStyleSentinel(markdown);+ const protections: AVRichTextStyleEntityProtection[] = [];+ const replacements: {start: number, end: number, value: string}[] = [];+ const spanStack: {text: boolean, literal: boolean}[] = [];+ const literalRanges = getAVRichTextLiteralRanges(markdown);+ let literalIndex = 0;+ for (let index = 0; index < markdown.length;) {+ while (literalIndex < literalRanges.length && literalRanges[literalIndex].end <= index) {+ literalIndex++;+ }+ const literalRange = literalRanges[literalIndex];+ if (literalRange && literalRange.start <= index) {+ index = literalRange.end;+ continue;+ }+ if (markdown[index] !== "<") {+ index++;+ continue;+ }+ if (markdown.startsWith("<span", index) && /[\s/>]/.test(markdown[index + 5] || "")) {+ const tagEnd = findAVRichTextQuotedEnd(markdown, index + 5, markdown.length, ">");+ if (tagEnd < 0) {+ index++;+ continue;+ }+ const dataType = getAVRichTextQuotedAttribute(markdown, index + 5, tagEnd, "data-type");+ if (markdown[tagEnd - 1] !== "/") {+ const types = dataType?.value.split(/\s+/) || [];+ spanStack.push({+ text: types.includes("text"),+ literal: types.includes("code") || spanStack.at(-1)?.literal === true,+ });+ }+ index = tagEnd + 1;+ continue;+ }+ if (!markdown.startsWith("</span", index) || !/[\s>]/.test(markdown[index + 6] || "")) {+ index++;+ continue;+ }+ const tagEnd = findAVRichTextQuotedEnd(markdown, index + 6, markdown.length, ">");+ if (tagEnd < 0) {+ index++;+ continue;+ }+ const span = spanStack.pop();+ const isText = span?.text === true && !span.literal;+ const ialStart = tagEnd + 1;+ if (!isText || !markdown.startsWith("{:", ialStart)) {+ index = tagEnd + 1;+ continue;+ }+ const ialEnd = findAVRichTextQuotedEnd(markdown, ialStart + 2, markdown.length, "}");+ if (ialEnd < 0) {+ index = tagEnd + 1;+ continue;+ }+ const style = getAVRichTextQuotedAttribute(markdown, ialStart + 2, ialEnd, "style");+ if (style) {+ for (let entityStart = style.start; entityStart < style.end;) {+ if (markdown[entityStart] === "`") {+ const token = `${sentinel}${protections.length.toString(36)}\uE002`;+ protections.push({token, encoded: "`", decoded: "`"});+ replacements.push({start: entityStart, end: entityStart + 1, value: token});+ entityStart++;+ continue;+ }+ if (markdown[entityStart] !== "&") {+ entityStart++;+ continue;+ }+ const semicolon = markdown.indexOf(";", entityStart + 1);+ if (semicolon < 0 || semicolon >= style.end) {+ entityStart++;+ continue;+ }+ const encoded = markdown.slice(entityStart, semicolon + 1);+ const decoded = decodeAVRichTextStyleEntity(encoded);+ if (typeof decoded !== "string") {+ entityStart++;+ continue;+ }+ const token = `${sentinel}${protections.length.toString(36)}\uE002`;+ protections.push({token, encoded, decoded});+ replacements.push({start: entityStart, end: semicolon + 1, value: token});+ entityStart = semicolon + 1;+ }+ }+ index = ialEnd + 1;+ }+ if (replacements.length === 0) {+ return {content: markdown, protections};+ }+ let content = "";+ let start = 0;+ replacements.forEach((replacement) => {+ content += markdown.slice(start, replacement.start) + replacement.value;+ start = replacement.end;+ });+ return {content: content + markdown.slice(start), protections};+};++export const isAVRichTextExecutableCodeLanguage = (info: string) =>+ EXECUTABLE_CODE_LANGUAGES.has(info.trim().split(/\s+/, 1)[0].toLowerCase());++const normalizeAVRichTextInlineStyleValue = (property: AVRichTextStyleProperty, value: string) => {+ const builtinColor = value.match(/^var\(--b3-font-(color|background)(\d+)\)$/);+ if (builtinColor) {+ const index = Number(builtinColor[2]);+ if (Number.isInteger(index) && 1 <= index && index <= BUILTIN_INLINE_COLOR_COUNT &&+ (property === "color" && builtinColor[1] === "color" ||+ property === "background-color" && builtinColor[1] === "background")) {+ return `var(--b3-font-${builtinColor[1]}${index})`;+ }+ return "";+ }++ const builtinStyle = value.match(+ /^var\(--b3-inline-builtin-(error|warning|info|success)-(color|background-color),\s*var\(--b3-card-(error|warning|info|success)-(color|background)\)\)$/+ );+ if (builtinStyle) {+ const expectedStyleProperty = property === "color" ? "color" : "background-color";+ const expectedLegacyProperty = property === "color" ? "color" : "background";+ if (builtinStyle[1] === builtinStyle[3] && builtinStyle[2] === expectedStyleProperty &&+ builtinStyle[4] === expectedLegacyProperty) {+ return `var(--b3-inline-builtin-${builtinStyle[1]}-${expectedStyleProperty}, ` ++ `var(--b3-card-${builtinStyle[1]}-${expectedLegacyProperty}))`;+ }+ return "";+ }++ const customStyle = value.match(+ /^var\(--b3-inline-style-([0-9]{14}-[a-z0-9]{7})-(color|background-color),\s*(#[0-9A-Fa-f]{6})\)$/+ );+ const expectedCustomProperty = property === "color" ? "color" : "background-color";+ if (customStyle && customStyle[2] === expectedCustomProperty) {+ return `var(--b3-inline-style-${customStyle[1]}-${expectedCustomProperty}, ${customStyle[3].toLowerCase()})`;+ }+ return "";+};++const splitAVRichTextStyleDeclarations = (style: string) => {+ const declarations: string[] = [];+ let start = 0;+ let quote = "";+ let escaped = false;+ let parentheses = 0;+ for (let index = 0; index < style.length; index++) {+ const character = style[index];+ if (escaped) {+ escaped = false;+ continue;+ }+ if (character === "\\") {+ escaped = true;+ continue;+ }+ if (quote) {+ if (character === quote) {+ quote = "";+ }+ continue;+ }+ if (character === "'" || character === '"') {+ quote = character;+ } else if (character === "(") {+ parentheses++;+ } else if (character === ")") {+ if (parentheses === 0) {+ return [];+ }+ parentheses--;+ } else if (character === ";" && parentheses === 0) {+ declarations.push(style.slice(start, index));+ start = index + 1;+ }+ }+ if (escaped || quote || parentheses !== 0) {+ return [];+ }+ declarations.push(style.slice(start));+ return declarations;+};++const normalizeAVRichTextFontSize = (value: string) => {+ const match = value.match(/^(\d+)(?:\.0{1,2})?px$/);+ if (match) {+ const size = Number(match[1]);+ return 9 <= size && size <= 72 ? `${size}px` : "";+ }+ const emMatch = value.match(/^(?:(\d+)(?:\.(\d{1,2}))?|\.(\d{1,2}))em$/);+ if (!emMatch) {+ return "";+ }+ const size = Number(value.slice(0, -2));+ return 0.56 <= size && size <= 4.5 ? `${size}em` : "";+};++const normalizeAVRichTextFontFamily = (value: string) => {+ if (value.length > 2048 || !FONT_FAMILY_PATTERN.test(value)) {+ return "";+ }+ const family = getInlineFontFamilyName(value);+ if (!family || Array.from(family).length > MAX_INLINE_FONT_FAMILY_LENGTH) {+ return "";+ }+ return getInlineFontFamilyStyle(family);+};++export const sanitizeAVRichTextInlineStyle = (style: unknown) => {+ if (typeof style !== "string") {+ return "";+ }+ const values = new Map<string, string>();+ splitAVRichTextStyleDeclarations(style).forEach((declaration) => {+ const match = declaration.match(/^\s*([-a-z]+)\s*:\s*([\s\S]*?)\s*$/);+ if (!match) {+ return;+ }+ const property = match[1];+ const value = match[2];+ if (property === "color" || property === "background-color") {+ const normalized = normalizeAVRichTextInlineStyleValue(property, value);+ if (normalized) {+ values.set(property, normalized);+ }+ } else if (property === "font-size") {+ const normalized = normalizeAVRichTextFontSize(value);+ if (normalized) {+ values.set(property, normalized);+ }+ } else if (property === "font-family") {+ const normalized = normalizeAVRichTextFontFamily(value);+ if (normalized) {+ values.set(property, normalized);+ }+ } else if (property === "-webkit-text-stroke" && value === HOLLOW_STROKE ||+ property === "-webkit-text-fill-color" && value === HOLLOW_FILL ||+ property === "text-shadow" && value === TEXT_SHADOW ||+ property === "direction" && (value === "ltr" || value === "rtl") ||+ property === "unicode-bidi" && value === "isolate") {+ values.set(property, value);+ }+ });+ if (!values.has("-webkit-text-stroke") || !values.has("-webkit-text-fill-color")) {+ values.delete("-webkit-text-stroke");+ values.delete("-webkit-text-fill-color");+ }+ if (!values.has("direction") || !values.has("unicode-bidi")) {+ values.delete("direction");+ values.delete("unicode-bidi");+ }+ return [+ "color",+ "background-color",+ "font-size",+ "font-family",+ "-webkit-text-stroke",+ "-webkit-text-fill-color",+ "text-shadow",+ "direction",+ "unicode-bidi",+ ].map((property) => values.has(property) ? `${property}: ${values.get(property)};` : "")+ .filter(Boolean).join(" ");+};++export const getAVTextSource = (value?: IAVCellValue): AVTextSource => {+ const rich = value?.type === "text" ? value.text?.rich : undefined;+ if (rich && rich.spec === AV_RICH_TEXT_SPEC && rich.format === AV_RICH_TEXT_FORMAT &&+ typeof rich.content === "string") {+ return {kind: "rich", content: rich.content};+ }+ return {kind: "plain", content: value?.type === "text" && typeof value.text?.content === "string" ?+ value.text.content : ""};+};++export const getAVTextPlainContent = (value?: IAVCellValue) =>+ value?.type === "text" && typeof value.text?.content === "string" ? value.text.content : "";++export const getAVTextCopyContent = (value?: IAVCellValue) => getAVTextPlainContent(value).trim();++export const createAVRichTextValue = (markdown: string, plainText: string,+ sourceValue?: IAVCellValue): IAVCellValue => ({+ ...sourceValue,+ type: "text",+ text: {+ content: plainText,+ rich: {+ spec: AV_RICH_TEXT_SPEC,+ format: AV_RICH_TEXT_FORMAT,+ content: markdown,+ },+ },+});++export const createAVPlainTextValue = (content: string, sourceValue?: IAVCellValue,+ clearRich = false): IAVCellValue => ({+ ...sourceValue,+ type: "text",+ text: clearRich ? {content, rich: null} : {content},+});++export const createAVPlainTextEditValue = (content: string, sourceValue?: IAVCellValue): IAVCellValue => {+ const sourceText = sourceValue?.type === "text" ? sourceValue.text : undefined;+ let rich: IAVCellValue["text"]["rich"] | undefined;+ if (sourceText && sourceText.content === content) {+ rich = sourceText.rich;+ } else if (sourceText?.rich !== undefined) {+ rich = null;+ }+ return {+ type: "text",+ text: typeof rich === "undefined" ? {content} : {+ content,+ rich: rich && {...rich},+ },+ };+};diff --git a/app/src/protyle/render/av/row.ts b/app/src/protyle/render/av/row.tsindex 18300c67c6..4bb97532ce 100644--- a/app/src/protyle/render/av/row.ts+++ b/app/src/protyle/render/av/row.ts@@ -30,6 +30,7 @@ import {getCardCoverHTML, getCardCoverSource} from "./cover";import {getCardFieldsClass} from "./gallery/cardLayout";import {getAVFilteredTipContext} from "./filteredTip";import {clearAVItemSelectionState} from "./selectionState";+import {renderAVRichTextElements} from "./richText";const getGalleryActionsHTML = (data: IAVGallery | IAVKanban, row: IAVGalleryItem, primaryHidden = false) => {const canPosition = Boolean(row.coverURL && !row.coverURL.startsWith("background") && getCardCoverSource(data));@@ -483,6 +484,7 @@ ${colType === "block" ? ' data-detached="true"' : ""}>${renderCell(genCellValue(cellItem.innerHTML = renderCell(cellValue, 0, true, "table", undefined,cellItem.dataset.dateFormat as TAVDateFormat);renderCellAttr(cellItem, cellValue);+ renderAVRichTextElements(cellItem);}});});diff --git a/app/src/protyle/render/av/virtualScroll.ts b/app/src/protyle/render/av/virtualScroll.tsindex d460ab2a96..11e9767473 100644--- a/app/src/protyle/render/av/virtualScroll.ts+++ b/app/src/protyle/render/av/virtualScroll.ts@@ -2,6 +2,7 @@ import {Constants} from "../../../constants";import {getRowHTML} from "./row";import {IAVSelectedCell, reconcileAVSelectedItemIDs, restoreAVCellSelection} from "./selectionState";import {getGroupTableViewportWindow} from "./groupTableVirtual";+import {renderAVRichTextElements} from "./richText";const BUFFER_RATIO = 1;@@ -436,6 +437,7 @@ const doTrim = (blockElement: HTMLElement, elementRect: DOMRect): void => {syncTableBottomSpacer(bodyEl, state, dataEnd);}bodyStates.set(bodyEl, state);+ renderAVRichTextElements(bodyEl);}});};@@ -552,6 +554,9 @@ export const ensureAVTableAdjacentRow = (rowElement: HTMLElement, direction: "pr}bodyStates.set(bodyElement, state);const newRowElement = bodyElement.querySelector<HTMLElement>(`.av__row[data-index="${targetIndex}"]`);+ if (newRowElement) {+ renderAVRichTextElements(newRowElement);+ }if (newRowElement && state.selectedRowIds?.has(row.id)) {newRowElement.classList.add("av__row--select");newRowElement.querySelector(".av__firstcol use")?.setAttribute("xlink:href", "#iconCheck");diff --git a/app/src/protyle/render/chartRender.ts b/app/src/protyle/render/chartRender.tsindex 856eefe9f3..d621d27d63 100644--- a/app/src/protyle/render/chartRender.ts+++ b/app/src/protyle/render/chartRender.ts@@ -48,6 +48,9 @@ const secureEChartsOption = (option: any) => {};export const chartRender = (element: Element, cdn = Constants.PROTYLE_CDN) => {+ if (element.closest('[data-protyle-lite-render="safe"]')) {+ return;+ }let echartsElements: Element[] | NodeListOf<Element> = [];if (element.getAttribute("data-subtype") === "echarts" && element.getAttribute("data-render") !== "true") {echartsElements = [element];@@ -65,6 +68,9 @@ export const chartRender = (element: Element, cdn = Constants.PROTYLE_CDN) => {width = wysiswgElement.firstElementChild.clientWidth;}echartsElements.forEach(async (e: HTMLDivElement) => {+ if (e.closest('[data-protyle-lite-render="safe"]')) {+ return;+ }e.setAttribute("data-render", "true");if (!e.firstElementChild.classList.contains("protyle-icons")) {e.insertAdjacentHTML("afterbegin", genIconHTML(wysiswgElement, ["refresh", "edit", "more"]));@@ -100,7 +106,7 @@ export const chartRender = (element: Element, cdn = Constants.PROTYLE_CDN) => {};export const refreshChartTheme = (element: Element) => {- if (typeof window.echarts === "undefined") {+ if (element.closest('[data-protyle-lite-render="safe"]') || typeof window.echarts === "undefined") {return;}let echartsElements: HTMLElement[] | NodeListOf<HTMLElement> = [];@@ -111,6 +117,9 @@ export const refreshChartTheme = (element: Element) => {}const refreshElements: HTMLElement[] = [];echartsElements.forEach((item) => {+ if (item.closest('[data-protyle-lite-render="safe"]')) {+ return;+ }const chartElement = item.querySelector<HTMLElement>("[_echarts_instance_]");if (!chartElement) {return;diff --git a/app/src/protyle/render/mathRender.ts b/app/src/protyle/render/mathRender.tsindex 338c9553a4..7eb0155148 100644--- a/app/src/protyle/render/mathRender.ts+++ b/app/src/protyle/render/mathRender.ts@@ -6,6 +6,7 @@ import {hasClosestBlock} from "../util/hasClosest";import {looseJsonParse} from "../../util/functions";import {genRenderFrame} from "./util";import {getHostCapabilities} from "../../util/hostCapabilities";+import {getMathRenderSecurity} from "./mathRenderSecurity";const fitMathWidth = (mathElement: HTMLElement, blockElement: HTMLElement | false, isBlock: boolean) => {return new Promise<void>((resolve) => {@@ -48,15 +49,17 @@ export const mathRender = (element: Element, cdn = Constants.PROTYLE_CDN, maxWid}const isBlock = mathElement.tagName === "DIV";const remoteKernel = getHostCapabilities().remoteKernel;+ const security = getMathRenderSecurity(remoteKernel,+ Boolean(mathElement.closest('[data-protyle-lite-render="safe"]')));try {let mathHTML = window.katex.renderToString(Lute.UnEscapeHTMLStr(mathElement.getAttribute("data-content")), {displayMode: isBlock,output: "html",macros,- trust: !remoteKernel, // REF: https://katex.org/docs/supported#html+ trust: security.trust, // REF: https://katex.org/docs/supported#htmlstrict: (errorCode) => errorCode === "unicodeTextInMathMode" ? "ignore" : "warn",});- if (remoteKernel) {+ if (security.sanitize) {mathHTML = window.DOMPurify.sanitize(mathHTML);}const blockElement = hasClosestBlock(mathElement);diff --git a/app/src/protyle/render/mathRenderSecurity.test.ts b/app/src/protyle/render/mathRenderSecurity.test.tsnew file mode 100644index 0000000000..d64cb4df9a--- /dev/null+++ b/app/src/protyle/render/mathRenderSecurity.test.ts@@ -0,0 +1,32 @@+import * as assert from "node:assert/strict";+import {describe, it} from "node:test";+import {getMathRenderSecurity} from "./mathRenderSecurity";++describe("math render security", () => {+ it("always disables trusted KaTeX commands for safe fragments", () => {+ assert.deepEqual(getMathRenderSecurity(false, true), {trust: false, sanitize: true});+ assert.deepEqual(getMathRenderSecurity(true, true), {trust: false, sanitize: true});+ assert.deepEqual(getMathRenderSecurity(false, false), {trust: true, sanitize: false});+ });++ it("does not render active markup from untrusted KaTeX commands", () => {+ const katex = require("../../../stage/protyle/js/katex/katex.min.js");+ const security = getMathRenderSecurity(false, true);+ const fixtures = [+ String.raw`\href{javascript:alert(1)}{link}`,+ String.raw`\includegraphics{https://example.com/image.png}`,+ String.raw`\htmlStyle{background:url(https://example.com/image.png)}{x}`,+ ];++ fixtures.forEach((fixture) => {+ const html = katex.renderToString(fixture, {+ output: "html",+ throwOnError: false,+ trust: security.trust,+ });+ assert.doesNotMatch(html, /href=["']javascript:/i);+ assert.doesNotMatch(html, /<img\b/i);+ assert.doesNotMatch(html, /background\s*:\s*url/i);+ });+ });+});diff --git a/app/src/protyle/render/mathRenderSecurity.ts b/app/src/protyle/render/mathRenderSecurity.tsnew file mode 100644index 0000000000..45e426d537--- /dev/null+++ b/app/src/protyle/render/mathRenderSecurity.ts@@ -0,0 +1,4 @@+export const getMathRenderSecurity = (remoteKernel: boolean, safeRender: boolean) => ({+ trust: !remoteKernel && !safeRender,+ sanitize: remoteKernel || safeRender,+});diff --git a/app/src/protyle/runtimeCapabilities.test.ts b/app/src/protyle/runtimeCapabilities.test.tsnew file mode 100644index 0000000000..ccabc51ab9--- /dev/null+++ b/app/src/protyle/runtimeCapabilities.test.ts@@ -0,0 +1,113 @@+import * as assert from "node:assert/strict";+import {describe, it} from "node:test";+import {+ applyProtyleLockedOptions,+ areProtylePluginExtensionsEnabled,+ areProtyleRuntimePluginExtensionsEnabled,+ disableProtyleUpload,+ isProtyleUploadDisabled,+ getProtyleBlockDOMSanitizer,+ getProtyleLockedToolbar,+ getProtyleRestrictedPlainTextHTML,+ isProtyleCustomBlockRenderEnabled,+ registerProtyleRuntimeCapabilities,+ resolveProtyleLute,+ restoreProtyleLuteMarkdownSyntax,+} from "./runtimeCapabilities";++describe("Protyle runtime capabilities", () => {+ it("applies toolbar and hint constraints after plugin options", () => {+ const pluginOptions = {+ toolbar: ["upload", "widget"],+ hint: {+ emojiPath: "/plugin-emojis",+ extend: [{key: ":"}, {key: "/"}],+ },+ } as unknown as IProtyleOptions;+ const lockedToolbar = ["strong", "em"];+ const lockedHint = {extend: [{key: "/"}]};+ const resolved = applyProtyleLockedOptions(pluginOptions, {+ toolbar: lockedToolbar,+ hint: lockedHint,+ });++ assert.deepEqual(resolved.toolbar, lockedToolbar);+ assert.deepEqual(resolved.hint.extend, lockedHint.extend);+ assert.equal(resolved.hint.emojiPath, "/plugin-emojis");+ assert.equal(areProtyleRuntimePluginExtensionsEnabled({}), true);+ assert.equal(areProtyleRuntimePluginExtensionsEnabled({pluginExtensions: false}), false);+ });++ it("injects an isolated Lute without obtaining or mutating the shared instance", () => {+ const isolatedLute = {} as Lute;+ let sharedCalls = 0;+ const resolved = resolveProtyleLute(() => {+ sharedCalls++;+ return {} as Lute;+ }, isolatedLute);++ assert.equal(resolved, isolatedLute);+ assert.equal(sharedCalls, 0);+ });++ it("restores an isolated Lute with its runtime policy and keeps the ordinary fallback", () => {+ const isolatedLute = {} as Lute;+ const isolated = {lute: isolatedLute} as IProtyle;+ let runtimeRestore: Lute | undefined;+ let defaultRestore: Lute | undefined;+ registerProtyleRuntimeCapabilities(isolated, {+ restoreLuteMarkdownSyntax: (lute) => {+ runtimeRestore = lute;+ },+ });++ restoreProtyleLuteMarkdownSyntax(isolated, (lute) => {+ defaultRestore = lute;+ });+ assert.equal(runtimeRestore, isolatedLute);+ assert.equal(defaultRestore, undefined);++ const ordinaryLute = {} as Lute;+ const ordinary = {lute: ordinaryLute} as IProtyle;+ restoreProtyleLuteMarkdownSyntax(ordinary, (lute) => {+ defaultRestore = lute;+ });+ assert.equal(defaultRestore, ordinaryLute);+ });++ it("keeps disabled upload state tied to the Protyle instance", () => {+ const disabled = {} as IProtyle;+ const enabled = {} as IProtyle;++ disableProtyleUpload(disabled);++ assert.equal(isProtyleUploadDisabled(disabled), true);+ assert.equal(isProtyleUploadDisabled(enabled), false);+ });++ it("keeps restricted plugin and BlockDOM capabilities tied to one instance", () => {+ const restricted = {} as IProtyle;+ const regular = {} as IProtyle;+ const toolbar = ["strong", "em"];+ const sanitizer = (blockDOM: string) => blockDOM.replace(/<img[^>]*>/g, "");+ registerProtyleRuntimeCapabilities(restricted, {+ pluginExtensions: false,+ customBlockRender: false,+ lockedOptions: {toolbar},+ sanitizeBlockDOM: sanitizer,+ });++ assert.equal(areProtylePluginExtensionsEnabled(restricted), false);+ assert.equal(isProtyleCustomBlockRenderEnabled(restricted), false);+ assert.deepEqual(getProtyleLockedToolbar(restricted), toolbar);+ assert.equal(getProtyleBlockDOMSanitizer(restricted), sanitizer);+ assert.equal(areProtylePluginExtensionsEnabled(regular), true);+ assert.equal(isProtyleCustomBlockRenderEnabled(regular), true);+ });++ it("turns restricted fallback paste into inert text only", () => {+ assert.equal(getProtyleRestrictedPlainTextHTML(+ '<table><img src=x onerror="alert(1)"></table>\nnext'+ ), "<table><img src=x onerror="alert(1)"></table><br>next");+ });+});diff --git a/app/src/protyle/runtimeCapabilities.ts b/app/src/protyle/runtimeCapabilities.tsnew file mode 100644index 0000000000..3f00eec46c--- /dev/null+++ b/app/src/protyle/runtimeCapabilities.ts@@ -0,0 +1,60 @@+import {merge} from "./util/merge";++export interface ProtyleRuntimeCapabilities {+ upload?: boolean;+ websocket?: boolean;+ lute?: Lute;+ lockedOptions?: Partial<Pick<IProtyleOptions, "hint" | "toolbar">>;+ pluginExtensions?: boolean;+ customBlockRender?: boolean;+ sanitizeBlockDOM?: (blockDOM: string) => string;+ restoreLuteMarkdownSyntax?: (lute: Lute) => void;+}++const uploadDisabledProtyles = new WeakSet<IProtyle>();+const protyleRuntimeCapabilities = new WeakMap<IProtyle, ProtyleRuntimeCapabilities>();++export const applyProtyleLockedOptions = (options: IProtyleOptions,+ lockedOptions?: ProtyleRuntimeCapabilities["lockedOptions"]) =>+ lockedOptions ? merge(options, lockedOptions) as IProtyleOptions : options;++export const resolveProtyleLute = (getSharedLute: () => Lute, runtimeLute?: Lute) =>+ runtimeLute || getSharedLute();++export const registerProtyleRuntimeCapabilities = (protyle: IProtyle,+ capabilities: ProtyleRuntimeCapabilities) => {+ protyleRuntimeCapabilities.set(protyle, capabilities);+};++export const areProtyleRuntimePluginExtensionsEnabled = (capabilities: ProtyleRuntimeCapabilities) =>+ capabilities.pluginExtensions !== false;++export const areProtylePluginExtensionsEnabled = (protyle: IProtyle) =>+ areProtyleRuntimePluginExtensionsEnabled(protyleRuntimeCapabilities.get(protyle) || {});++export const isProtyleCustomBlockRenderEnabled = (protyle: IProtyle) =>+ protyleRuntimeCapabilities.get(protyle)?.customBlockRender !== false;++export const getProtyleLockedToolbar = (protyle: IProtyle) =>+ protyleRuntimeCapabilities.get(protyle)?.lockedOptions?.toolbar;++export const getProtyleBlockDOMSanitizer = (protyle: IProtyle) =>+ protyleRuntimeCapabilities.get(protyle)?.sanitizeBlockDOM;++export const restoreProtyleLuteMarkdownSyntax = (protyle: IProtyle, restoreDefault: (lute: Lute) => void) => {+ const restore = protyleRuntimeCapabilities.get(protyle)?.restoreLuteMarkdownSyntax || restoreDefault;+ restore(protyle.lute);+};++export const getProtyleRestrictedPlainTextHTML = (value: string) => value.replace(/&/g, "&")+ .replace(/</g, "<")+ .replace(/>/g, ">")+ .replace(/"/g, """)+ .replace(/'/g, "'")+ .replace(/\r\n?|\n/g, "<br>");++export const disableProtyleUpload = (protyle: IProtyle) => {+ uploadDisabledProtyles.add(protyle);+};++export const isProtyleUploadDisabled = (protyle: IProtyle) => uploadDisabledProtyles.has(protyle);diff --git a/app/src/protyle/toolbar/index.ts b/app/src/protyle/toolbar/index.tsindex dab306ae2c..1c7c3396ef 100644--- a/app/src/protyle/toolbar/index.ts+++ b/app/src/protyle/toolbar/index.ts@@ -98,6 +98,10 @@ import {normalizeCalloutTitleRange} from "./inlineRangeBoundary";import {resolvePluginToolbar} from "../../plugin/toolbarItem";+import {+ areProtylePluginExtensionsEnabled,+ getProtyleLockedToolbar,+} from "../runtimeCapabilities";const filterPluginToolbar = (toolbar: Array<string | IMenuItem>, lite: boolean) => {if (!lite) {@@ -117,6 +121,9 @@ const filterPluginToolbar = (toolbar: Array<string | IMenuItem>, lite: boolean)};const applyPluginToolbar = (toolbar: Array<string | IMenuItem>, protyle: IProtyle) => {+ if (!areProtylePluginExtensionsEnabled(protyle)) {+ return toolbarKeyToMenu(toolbar) as IMenuItem[];+ }let result = toolbar;protyle.app.plugins.forEach((plugin) => {const previous = [...result];@@ -183,13 +190,15 @@ export class Toolbar {});applyToolbarEntryVisibility(this.element);/// #if MOBILE- updateMobilePluginToolbar(protyle);+ if (areProtylePluginExtensionsEnabled(protyle)) {+ updateMobilePluginToolbar(protyle);+ }/// #endif}public update(protyle: IProtyle) {this.element.innerHTML = "";- protyle.options.toolbar = toolbarKeyToMenu(getDefaultToolbar(isMobile()));+ protyle.options.toolbar = toolbarKeyToMenu(getProtyleLockedToolbar(protyle) || getDefaultToolbar(isMobile()));protyle.options.toolbar = applyPluginToolbar(protyle.options.toolbar, protyle);if (!isMobile() && !protyle.lite) {refreshToolbarCatalog(protyle.options.toolbar);@@ -200,7 +209,9 @@ export class Toolbar {});applyToolbarEntryVisibility(this.element);/// #if MOBILE- updateMobilePluginToolbar(protyle);+ if (areProtylePluginExtensionsEnabled(protyle)) {+ updateMobilePluginToolbar(protyle);+ }/// #endif}@@ -1845,14 +1856,16 @@ export class Toolbar {if (!protyle.disabled) {textElement.select();}- forEachPluginSubscriber("open-noneditableblock", eventBus => {- eventBus.emit("open-noneditableblock", {- protyle,- toolbar: this,- blockElement: nodeElement,- renderElement,+ if (areProtylePluginExtensionsEnabled(protyle)) {+ forEachPluginSubscriber("open-noneditableblock", eventBus => {+ eventBus.emit("open-noneditableblock", {+ protyle,+ toolbar: this,+ blockElement: nodeElement,+ renderElement,+ });});- });+ }}public showCodeLanguage(protyle: IProtyle, languageElements: HTMLElement[]) {@@ -1879,7 +1892,7 @@ export class Toolbar {let html = `<div data-id="clearLanguage" class="b3-list-item">${window.siyuan.languages.clear}</div>`;let hljsLanguages = Constants.ALIAS_CODE_LANGUAGES.concat(window.hljs?.listLanguages() ?? []).sort();- if (hasPluginSubscriber("code-language-update")) {+ if (areProtylePluginExtensionsEnabled(protyle) && hasPluginSubscriber("code-language-update")) {const eventDetail = {languages: hljsLanguages, type: "init", listElement};emitToPlugins("code-language-update", eventDetail);hljsLanguages = eventDetail.languages;@@ -1951,7 +1964,7 @@ export class Toolbar {}}- if (hasPluginSubscriber("code-language-update")) {+ if (areProtylePluginExtensionsEnabled(protyle) && hasPluginSubscriber("code-language-update")) {const eventDetail = {languages: value ? matchLanguages : hljsLanguages, type: "match", value, listElement};emitToPlugins("code-language-update", eventDetail);matchLanguages = eventDetail.languages;@@ -2532,13 +2545,15 @@ export class Toolbar {private updateLanguage(languageElements: HTMLElement[], protyle: IProtyle, selectedLang: string) {const currentLang = selectedLang === window.siyuan.languages.clear ? "" : selectedLang;- forEachPluginSubscriber("code-language-change", eventBus => {- eventBus.emit("code-language-change", {- language: currentLang,- languageElements,- protyle: protyle+ if (areProtylePluginExtensionsEnabled(protyle)) {+ forEachPluginSubscriber("code-language-change", eventBus => {+ eventBus.emit("code-language-change", {+ language: currentLang,+ languageElements,+ protyle: protyle+ });});- });+ }if (!Constants.SIYUAN_RENDER_CODE_LANGUAGES.includes(currentLang)) {window.siyuan.storage[Constants.LOCAL_CODELANG] = currentLang;diff --git a/app/src/protyle/upload/index.ts b/app/src/protyle/upload/index.tsindex 48c1933736..410858685c 100644--- a/app/src/protyle/upload/index.ts+++ b/app/src/protyle/upload/index.ts@@ -27,6 +27,7 @@ import {import {getAssetUploadResult, getAssetUploadSuccesses} from "./uploadResult";import {AssetUploadHandlerTimeoutError, waitForUploadHandler} from "./uploadHandler";import {getHostCapabilities} from "../../util/hostCapabilities";+import {isProtyleUploadDisabled} from "../runtimeCapabilities";interface FileWithPath extends File {path: string;@@ -767,6 +768,10 @@ export const uploadLocalFiles = (files: ILocalFiles[], protyle: IProtyle, isUplooptions?: IUploadInsertOptions, successCB?: (response: IWebSocketData,result: Omit<IAssetUploadResult, "requestId" | "input">) => void,completeCB?: (succeeded: boolean) => void) => {+ if (isProtyleUploadDisabled(protyle)) {+ completeCB?.(false);+ return;+ }const uploadOptions = captureUploadInsertPosition(protyle, options);const callbacks: IAssetUploadCallbacks = {success(responseText, response, _input, result) {@@ -805,6 +810,13 @@ export const uploadFiles = (protyle: IProtyle, files: FileList | DataTransferIteresult: Omit<IAssetUploadResult, "requestId" | "input">) => void,completeCB?: (succeeded: boolean) => void,options?: IUploadInsertOptions) => {+ if (isProtyleUploadDisabled(protyle)) {+ completeCB?.(false);+ if (element) {+ element.value = "";+ }+ return;+ }const uploadOptions = captureUploadInsertPosition(protyle, options);let fileList: File[] = [];for (let i = 0; i < files.length; i++) {diff --git a/app/src/protyle/upload/pluginEvent.ts b/app/src/protyle/upload/pluginEvent.tsindex 63910c4621..96d682ff70 100644--- a/app/src/protyle/upload/pluginEvent.ts+++ b/app/src/protyle/upload/pluginEvent.ts@@ -1,6 +1,7 @@import type {EventBus, IEventBusSafeEmitResult} from "../../plugin/EventBusCore";import {emitWithErrors, eventBusHas, hasPluginSubscriber} from "../../plugin/EventBusCore";import {genUUID} from "../../util/genID";+import {areProtylePluginExtensionsEnabled} from "../runtimeCapabilities";export interface IAssetUploadEventContext {source: TAssetUploadSource;@@ -338,7 +339,8 @@ export const prepareAssetUpload = (options: {if (initialValidationError) {return fail(initialValidationError);}- if (!hasPluginSubscriber("before-upload-assets")) {+ if ((options.protyle && !areProtylePluginExtensionsEnabled(options.protyle)) ||+ !hasPluginSubscriber("before-upload-assets")) {return {state: "ready", task};}const plugins = Array.from(options.plugins).filter(plugin => !unloadingPlugins.has(plugin) &&diff --git a/app/src/protyle/util/destroy.ts b/app/src/protyle/util/destroy.tsindex b60007aab5..7d267c721a 100644--- a/app/src/protyle/util/destroy.ts+++ b/app/src/protyle/util/destroy.ts@@ -6,6 +6,7 @@ import {unmountBreadcrumbButtons} from "../../plugin/breadcrumbButton";import {forEachPluginSubscriber} from "../../plugin/EventBusCore";import {unregisterCustomBlockRoot} from "../../plugin/customBlockRender";import {destroyTrackedRanges} from "./trackedRange";+import {areProtylePluginExtensionsEnabled} from "../runtimeCapabilities";export const destroy = (protyle: IProtyle) => {if (!protyle) {@@ -46,9 +47,11 @@ export const destroy = (protyle: IProtyle) => {}, 10240);}}- forEachPluginSubscriber("destroy-protyle", eventBus => {- eventBus.emit("destroy-protyle", {- protyle,+ if (areProtylePluginExtensionsEnabled(protyle)) {+ forEachPluginSubscriber("destroy-protyle", eventBus => {+ eventBus.emit("destroy-protyle", {+ protyle,+ });});- });+ }};diff --git a/app/src/protyle/util/onGet.ts b/app/src/protyle/util/onGet.tsindex 24076141b1..0384fba9a6 100644--- a/app/src/protyle/util/onGet.ts+++ b/app/src/protyle/util/onGet.ts@@ -36,6 +36,7 @@ import {isIPhone} from "./compatibility";import {forEachPluginSubscriber} from "../../plugin/EventBusCore";import {disposeCustomBlocksInElement, setCustomBlockRootReady} from "../../plugin/customBlockRender";import {invalidateTrackedRanges, invalidateTrackedRangesInElement} from "./trackedRange";+import {areProtylePluginExtensionsEnabled} from "../runtimeCapabilities";/// #if MOBILEimport {updateMobileTitleReadonly} from "./setEditMode";/// #endif@@ -408,12 +409,14 @@ const setHTML = (options: {});protyle.options.defIds = [];if (options.action.includes(Constants.CB_GET_APPEND) || options.action.includes(Constants.CB_GET_BEFORE)) {- forEachPluginSubscriber("loaded-protyle-dynamic", eventBus => {- eventBus.emit("loaded-protyle-dynamic", {- protyle,- position: options.action.includes(Constants.CB_GET_APPEND) ? "afterend" : "beforebegin"+ if (areProtylePluginExtensionsEnabled(protyle)) {+ forEachPluginSubscriber("loaded-protyle-dynamic", eventBus => {+ eventBus.emit("loaded-protyle-dynamic", {+ protyle,+ position: options.action.includes(Constants.CB_GET_APPEND) ? "afterend" : "beforebegin"+ });});- });+ }return;}@@ -462,9 +465,11 @@ const setHTML = (options: {}}- forEachPluginSubscriber("loaded-protyle-static", eventBus => {- eventBus.emit("loaded-protyle-static", {protyle});- });+ if (areProtylePluginExtensionsEnabled(protyle)) {+ forEachPluginSubscriber("loaded-protyle-static", eventBus => {+ eventBus.emit("loaded-protyle-static", {protyle});+ });+ }};export const disabledForeverProtyle = (protyle: IProtyle) => {diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.tsindex 0c7793349f..00b0fea946 100644--- a/app/src/protyle/util/paste.ts+++ b/app/src/protyle/util/paste.ts@@ -58,6 +58,12 @@ import {resetPastedQueryEmbedRenderState} from "../render/embedRenderState";import {getHostCapabilities, sanitizeKernelHTML} from "../../util/hostCapabilities";import {eventBusHas, hasPluginSubscriber} from "../../plugin/EventBusCore";import {normalizeSemanticInlineElements, stripSemanticMarkersFromRangeText} from "./inlineElementMarker";+import {+ areProtylePluginExtensionsEnabled,+ getProtyleBlockDOMSanitizer,+ getProtyleRestrictedPlainTextHTML,+ restoreProtyleLuteMarkdownSyntax,+} from "../runtimeCapabilities";/// #if !BROWSERimport {ipcRenderer} from "electron";/// #endif@@ -276,12 +282,15 @@ export const pasteAsPlainText = async (protyle: IProtyle) => {textPlain = textPlain.replace(/__@kbd@__/g, "<kbd>").replace(/__@\/kbd@__/g, "</kbd>");textPlain = textPlain.replace(/__@u@__/g, "<u>").replace(/__@\/u@__/g, "</u>");- // 临界区:Lute 已是所有编辑器共享的单例,此处临时把 inline-syntax 标志置 true 再恢复。- // enable/transform/restore 必须保持同步执行,中间不得插入 await,否则并发编辑器的- // 转换调用(如实时输入的 SpinBlockDOM)会读到被改写的标志而产生错误输出。+ // 转换期间临时启用行级语法,并在同步转换完成后按当前编辑器的运行时配置恢复。+ // enable/transform/restore 之间不得插入 await,避免其他同步转换读取到临时配置。enableLuteMarkdownSyntax(protyle);- const content = protyle.lute.BlockDOM2EscapeMarkerContent(protyle.lute.Md2BlockDOM(textPlain));- restoreLuteMarkdownSyntax(protyle);+ let content: string;+ try {+ content = protyle.lute.BlockDOM2EscapeMarkerContent(protyle.lute.Md2BlockDOM(textPlain));+ } finally {+ restoreLuteMarkdownSyntax(protyle);+ }// insertHTML 会进行内部反转义insertHTML(content, protyle, false, false, true);@@ -299,11 +308,13 @@ export const enableLuteMarkdownSyntax = (protyle: IProtyle) => {};export const restoreLuteMarkdownSyntax = (protyle: IProtyle) => {- applyLuteMarkdownSyntax(protyle.lute, window.siyuan.config.editor.markdown);+ restoreProtyleLuteMarkdownSyntax(protyle, (lute) => {+ applyLuteMarkdownSyntax(lute, window.siyuan.config.editor.markdown);+ });};const readLocalFile = async (protyle: IProtyle, localFiles: ILocalFiles[], options?: IUploadInsertOptions) => {- if (protyle && protyle.app && protyle.app.plugins && hasPluginSubscriber("paste")) {+ if (areProtylePluginExtensionsEnabled(protyle) && protyle.app?.plugins && hasPluginSubscriber("paste")) {const plugins = Array.from(protyle.app.plugins);for (let i = 0; i < plugins.length; i++) {const plugin = plugins[i];@@ -587,6 +598,7 @@ const insertConvertedBlockDOM = (protyle: IProtyle, dom: string, range: Range) =export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEvent | IClipboardData) & {target: HTMLElement}, uploadOptions?: IUploadInsertOptions) => {+ const blockDOMSanitizer = getProtyleBlockDOMSanitizer(protyle);if ("clipboardData" in event || "dataTransfer" in event) {event.stopPropagation();event.preventDefault();@@ -642,7 +654,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEvenfiles = event.dataTransfer.files;}} else {- if (event.localFiles?.length > 0) {+ if (!blockDOMSanitizer && event.localFiles?.length > 0) {readLocalFile(protyle, event.localFiles, assetUploadOptions);return;}@@ -651,6 +663,13 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEvensiyuanHTML = event.siyuanHTML;files = event.files;}+ if (blockDOMSanitizer) {+ // 受限片段不解析外部 HTML 或文件;内部 BlockDOM 会在进入 DOM 前由专用白名单清洗。+ textHTML = "";+ files = [];+ vscodeEditorData = "";+ wpsPresentation = undefined;+ }// Improve the pasting of selected text in PDF rectangular annotation https://github.com/siyuan-note/siyuan/issues/11629textPlain = textPlain.replace(/\r\n|\r|\u2028|\u2029/g, "\n");@@ -677,7 +696,8 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEvenreturn;}}- if (!siyuanHTML && !textHTML && !textPlain && !wpsPresentation && ("clipboardData" in event)) {+ if (!blockDOMSanitizer && !siyuanHTML && !textHTML && !textPlain && !wpsPresentation &&+ ("clipboardData" in event)) {const localFiles: ILocalFiles[] = await getLocalFiles();if (!isPasteInsertPositionAvailable()) {return;@@ -730,7 +750,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEventextHTML = Lute.Sanitize(textHTML);}- if (protyle && protyle.app && protyle.app.plugins && hasPluginSubscriber("paste")) {+ if (areProtylePluginExtensionsEnabled(protyle) && protyle.app?.plugins && hasPluginSubscriber("paste")) {const plugins = Array.from(protyle.app.plugins);for (let i = 0; i < plugins.length; i++) {const plugin = plugins[i];@@ -804,6 +824,10 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEvensiyuanHTML = Lute.Sanitize(siyuanHTML);}+ if (blockDOMSanitizer) {+ siyuanHTML = siyuanHTML ? blockDOMSanitizer(siyuanHTML) : "";+ }+if (!siyuanHTML && textHTML) {const officeList = convertOfficeLists(textHTML);textHTML = officeList.html;@@ -841,6 +865,13 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEvenprotyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--hl").forEach(item => {item.classList.remove("protyle-wysiwyg--hl");});+ if (blockDOMSanitizer && !siyuanHTML) {+ const plainHTML = getProtyleRestrictedPlainTextHTML(removeZWJ(textPlain));+ if (plainHTML) {+ insertAtPasteRange(plainHTML, range);+ }+ return;+ }const code = processPasteCode(textHTML, textPlain, originalTextHTML, protyle);if (nodeElement.getAttribute("data-type") === "NodeCodeBlock" ||protyle.toolbar.getCurrentType(range).includes("code")) {diff --git a/app/src/protyle/util/processCode.ts b/app/src/protyle/util/processCode.tsindex 27c6898862..8ff567e937 100644--- a/app/src/protyle/util/processCode.ts+++ b/app/src/protyle/util/processCode.ts@@ -60,6 +60,11 @@ const RENDER_MAP: Record<string, (previewPanel: Element) => void> = {};export const processRender = (previewPanel: Element) => {+ // 受限 Lite 编辑器只渲染公式,代码围栏始终作为源码编辑,不能执行图表或 HTML。+ if (previewPanel.closest('[data-protyle-lite-render="safe"]')) {+ mathRender(previewPanel);+ return;+ }customBlockRender(previewPanel);const language = previewPanel.getAttribute("data-subtype");if (RENDER_MAP[language]) {diff --git a/app/src/protyle/util/setEditMode.ts b/app/src/protyle/util/setEditMode.tsindex f11687ffc1..dd138ea6d6 100644--- a/app/src/protyle/util/setEditMode.ts+++ b/app/src/protyle/util/setEditMode.ts@@ -3,6 +3,7 @@ import {getAllModels} from "../../layout/getAll";import {updateOutline} from "../../editor/util";import {resize} from "./resize";import {forEachPluginSubscriber} from "../../plugin/EventBusCore";+import {areProtylePluginExtensionsEnabled} from "../runtimeCapabilities";/// #if MOBILEexport const updateMobileTitleReadonly = (protyle: IProtyle) => {@@ -58,7 +59,9 @@ export const setEditMode = (protyle: IProtyle, type: TEditorMode) => {updateMobileTitleReadonly(protyle);/// #endifhideElements(["gutterOnly", "toolbar", "select", "hint", "util"], protyle);- forEachPluginSubscriber("switch-protyle-mode", eventBus => {- eventBus.emit("switch-protyle-mode", {protyle});- });+ if (areProtylePluginExtensionsEnabled(protyle)) {+ forEachPluginSubscriber("switch-protyle-mode", eventBus => {+ eventBus.emit("switch-protyle-mode", {protyle});+ });+ }};diff --git a/app/src/protyle/wysiwyg/commonHotkey.ts b/app/src/protyle/wysiwyg/commonHotkey.tsindex d51b23e75c..625787ea3e 100644--- a/app/src/protyle/wysiwyg/commonHotkey.ts+++ b/app/src/protyle/wysiwyg/commonHotkey.ts@@ -19,6 +19,7 @@ import {isEncryptedBox} from "../../util/pathName";import {normalizeHTMLAssetIFrameBlockDOM} from "../../asset/html";import {captureCommandContext} from "../../command/context";import {resolvePluginCommandCallback, supportsPluginCommandSource} from "../../plugin/commandAdapter";+import {areProtylePluginExtensionsEnabled} from "../runtimeCapabilities";export const commonHotkey = (protyle: IProtyle, event: KeyboardEvent, nodeElement?: HTMLElement) => {if (matchHotKey(window.siyuan.config.keymap.editor.general.netImg2LocalAsset.custom, event)) {@@ -113,28 +114,30 @@ export const commonHotkey = (protyle: IProtyle, event: KeyboardEvent, nodeElemenreturn true;}/// #if !MOBILE- let matchedCommand: ICommand | undefined;- protyle.app.plugins.find(item => {- item.commands.find(command => {- if (supportsPluginCommandSource(command, "editorShortcut") &&- matchHotKey(command.customHotkey, event)) {- matchedCommand = command;+ if (areProtylePluginExtensionsEnabled(protyle)) {+ let matchedCommand: ICommand | undefined;+ protyle.app.plugins.find(item => {+ item.commands.find(command => {+ if (supportsPluginCommandSource(command, "editorShortcut") &&+ matchHotKey(command.customHotkey, event)) {+ matchedCommand = command;+ return true;+ }+ });+ return Boolean(matchedCommand);+ });+ if (matchedCommand) {+ const commandContext = captureCommandContext({+ app: protyle.app,+ source: "editorShortcut",+ protyle,+ range: protyle.toolbar.range,+ });+ const callback = resolvePluginCommandCallback(matchedCommand, commandContext);+ if (callback) {+ void callback();return true;}- });- return Boolean(matchedCommand);- });- if (matchedCommand) {- const commandContext = captureCommandContext({- app: protyle.app,- source: "editorShortcut",- protyle,- range: protyle.toolbar.range,- });- const callback = resolvePluginCommandCallback(matchedCommand, commandContext);- if (callback) {- void callback();- return true;}}/// #endifdiff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.tsindex 05a3623925..253da868e3 100644--- a/app/src/protyle/wysiwyg/index.ts+++ b/app/src/protyle/wysiwyg/index.ts@@ -208,6 +208,7 @@ import {shouldOpenListItemAttr} from "./listContext";import {getBlockEdgeCaretRange, isCaretRangeInsideElement} from "./blockEdgeCaret";import {LargeListVirtualizer} from "./listVirtualization";import {forEachPluginSubscriber} from "../../plugin/EventBusCore";+import {areProtylePluginExtensionsEnabled} from "../runtimeCapabilities";import {syncRootAttributes} from "../util/syncRootAttributes";import {isDirectCalloutStructureClick} from "./calloutClick";import {@@ -4406,12 +4407,14 @@ export class WYSIWYG {this.preventClick = false;return;}- forEachPluginSubscriber("click-editorcontent", eventBus => {- eventBus.emit("click-editorcontent", {- protyle,- event+ if (areProtylePluginExtensionsEnabled(protyle)) {+ forEachPluginSubscriber("click-editorcontent", eventBus => {+ eventBus.emit("click-editorcontent", {+ protyle,+ event+ });});- });+ }const templateInteractiveElement = getAVTemplateInteractiveElement(event.target);if (templateInteractiveElement && !isAVTemplateLink(templateInteractiveElement)) {event.stopPropagation();diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.tsindex 82a4408a96..6c3a7c8914 100644--- a/app/src/types/index.d.ts+++ b/app/src/types/index.d.ts@@ -1503,7 +1503,12 @@ interface IAVCellValue {renderedContent?: string,isDetached?: boolean,text?: {- content: string+ content: string,+ rich?: {+ spec: 1,+ format: "kramdown",+ content: string+ } | null},number?: {content?: number,diff --git a/docs/API.ja.md b/docs/API.ja.mdindex ae98495091..499c060c62 100644--- a/docs/API.ja.md+++ b/docs/API.ja.md@@ -2272,6 +2272,7 @@|------------|----------------------------------------------------------------------------------------------------------------------|| `block` | `{"block": {"content": "1行目", "id": "<紐づくブロックID>"}, "isDetached": false}` || `text` | `{"text": {"content": "テキスト"}}` |+| `text`(リッチテキスト) | `{"text": {"content": "テキスト", "rich": {"spec": 1, "format": "kramdown", "content": "**テキスト**"}}}` || `number` | `{"number": {"content": 42, "isNotEmpty": true}}`(クリアは `{"isNotEmpty": false}`) || `date` | `{"date": {"content": 1676042451000, "isNotEmpty": true}}`(ミリ秒タイムスタンプ) || `select` | `{"mSelect": [{"content": "完了", "color": "1"}]}`(最大1つ) |@@ -2283,6 +2284,8 @@> ⚠️ `itemID` は**アイテム ID**、つまり[レンダリング](#レンダリング)が返すアイテムの `id` です。表形式では `rows[].id`、ギャラリーとカンバンでは `cards[].id` であり、グループ化が有効な場合は `groups[]` 内の対応するビューインスタンスにあります。また、主キー値の `value.blockID` とも同じです。紐づくアイテムの場合、紐づくブロック ID は主キー値の `value.block.id` にあります。両者は異なる概念であり、同一であると仮定してはいけません。誤った ID を渡すと、値はレンダリングされたセルに現れない孤立データとして保存されます。+リッチテキストでは、`text.rich.content` が正規の Kramdown ソースです。カーネルはサポート対象の構造を検証して `text.content` のプレーンテキスト表現を生成するため、呼び出し側が指定したプレーンテキスト表現は無視されます。既存の API クライアントとの互換性を保つため、`text.rich` を省略した場合、`text.content` が変わっていなければ保存済みのリッチテキストを維持し、変わっていればプレーンテキストで置き換えます。プレーンテキスト表現が同じ場合でも、`"rich": null` を送信すると書式を明示的に削除できます。リッチテキストを含むデータベースはストレージ仕様 9 を使用するため、それより前のデータベース仕様だけをサポートするカーネルでは開けません。+* `/api/av/setAttributeViewBlockAttr`* パラメータdiff --git a/docs/API.md b/docs/API.mdindex cd077a8c1f..27808379f4 100644--- a/docs/API.md+++ b/docs/API.md@@ -2312,6 +2312,7 @@ Updates a single cell (one field of one row). This is the primary write endpoint|------------|----------------------------------------------------------------------------------------------------------------------|| `block` | `{"block": {"content": "First row", "id": "<boundBlockID>"}, "isDetached": false}` || `text` | `{"text": {"content": "Some text"}}` |+| `text` (rich) | `{"text": {"content": "Some text", "rich": {"spec": 1, "format": "kramdown", "content": "**Some** text"}}}` || `number` | `{"number": {"content": 42, "isNotEmpty": true}}` (clear with `{"isNotEmpty": false}`) || `date` | `{"date": {"content": 1676042451000, "isNotEmpty": true}}` (millisecond timestamp) || `select` | `{"mSelect": [{"content": "Done", "color": "1"}]}` (at most one option) |@@ -2326,6 +2327,8 @@ Updates a single cell (one field of one row). This is the primary write endpointFor `mAsset`, each item uses `type: "image"` to render an image or `type: "file"` to render a file link. Updating the value replaces the entire `mAsset` array, so append operations must include the existing items.+For rich text, `text.rich.content` is the authoritative Kramdown source. The kernel validates its supported structure and derives `text.content` as the plain-text projection; a caller-provided plain-text projection is ignored. For compatibility with existing API clients, omitting `text.rich` preserves the stored rich-text payload when `text.content` is unchanged, but replaces it with plain text when `text.content` changes. Send `"rich": null` to explicitly remove rich formatting even when the plain-text projection is unchanged. Attribute views containing rich text use storage spec 9 and cannot be opened by kernels that only support earlier attribute-view specs.+* `/api/av/setAttributeViewBlockAttr`* Parametersdiff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.mdindex 0cd0f65cfd..6d1bfd9eee 100644--- a/docs/API.zh-CN.md+++ b/docs/API.zh-CN.md@@ -2272,6 +2272,7 @@|------------|----------------------------------------------------------------------------------------------------------------------|| `block` | `{"block": {"content": "第一行", "id": "<绑定块ID>"}, "isDetached": false}` || `text` | `{"text": {"content": "文本"}}` |+| `text`(富文本) | `{"text": {"content": "文本", "rich": {"spec": 1, "format": "kramdown", "content": "**文本**"}}}` || `number` | `{"number": {"content": 42, "isNotEmpty": true}}`(清空用 `{"isNotEmpty": false}`) || `date` | `{"date": {"content": 1676042451000, "isNotEmpty": true}}`(毫秒时间戳) || `select` | `{"mSelect": [{"content": "已完成", "color": "1"}]}`(至多一个选项) |@@ -2283,6 +2284,8 @@> ⚠️ `itemID` 是**条目 ID**,即[渲染](#渲染)返回的条目 `id`:表格为 `rows[].id`,卡片和看板为 `cards[].id`,启用分组时位于 `groups[]` 的对应视图实例中。它也等于主键值的 `value.blockID`。对于绑定条目,绑定块 ID 位于主键值的 `value.block.id`;二者是不同概念,不能假设相等。传入错误的 ID 会把值存为孤儿数据,不会出现在渲染后的单元格中。+对于富文本,`text.rich.content` 是权威的 Kramdown 源。内核会校验其受支持的结构并派生 `text.content` 纯文本投影;调用方提供的纯文本投影会被忽略。为兼容现有 API 客户端,省略 `text.rich` 时,如果 `text.content` 未改变则保留已存储的富文本载荷,如果 `text.content` 改变则以纯文本替换。即使纯文本投影未改变,也可以发送 `"rich": null` 明确移除富文本格式。包含富文本的数据库使用存储规范 9,无法由仅支持更早数据库规范的内核打开。+* `/api/av/setAttributeViewBlockAttr`* 参数diff --git a/kernel/av/av.go b/kernel/av/av.goindex 0f60f60883..b8aea597f8 100644--- a/kernel/av/av.go+++ b/kernel/av/av.go@@ -513,7 +513,7 @@ type Viewable interface {func NewAttributeView(id string) (ret *AttributeView) {view, blockKey, selectKey := NewTableViewWithBlockKey(ast.NewNodeID())ret = &AttributeView{- Spec: CurrentSpec,+ Spec: PlainTextSpec,ID: id,KeyValues: []*KeyValues{{Key: blockKey}, {Key: selectKey}},Views: []*View{view},@@ -909,6 +909,9 @@ func parseAttributeViewByPathInBoxWithOptions(avJSONPath, boxID string, resolveCif nil == err {err = CheckSpec(ret)}+ if nil == err {+ err = ret.NormalizeRichText()+ }if nil == err {if resolveColors {ret.ResolveDirectColors()@@ -930,6 +933,11 @@ func SaveAttributeView(av *AttributeView) (err error) {}}()+ if err = av.NormalizeRichText(); nil != err {+ logging.LogErrorf("normalize attribute view [%s] rich text failed: %s", av.ID, err)+ return+ }+// 做一些数据兼容和订正处理UpgradeSpec(av)@@ -1037,6 +1045,9 @@ func SaveAttributeView(av *AttributeView) (err error) {}cacheAttributeViewData(av, avBoxID, data)+ if RichTextSpec <= av.Spec {+ NotifyAttributeViewSaved(av.ID, avBoxID)+ }if util.ExceedLargeFileWarningSize(len(data)) {msg := fmt.Sprintf(util.Langs[util.Lang][268], av.Name+" "+filepath.Base(avJSONPath), util.LargeFileWarningSize)@@ -1334,6 +1345,7 @@ var (ErrWrongLayoutType = errors.New("wrong layout type")ErrInvalidColumnAlign = errors.New("invalid column align")ErrSpecTooNew = errors.New("attribute view spec is too new")+ ErrRichTextSpecMismatch = errors.New("attribute view rich text requires storage spec 9")ErrFilterTooDeep = errors.New("filter nesting depth exceeds the maximum allowed"))diff --git a/kernel/av/av_fix.go b/kernel/av/av_fix.goindex 0f449fb510..5cccedf61b 100644--- a/kernel/av/av_fix.go+++ b/kernel/av/av_fix.go@@ -20,11 +20,16 @@ import ("time""github.com/88250/lute/ast"+ "github.com/88250/lute/parse""github.com/siyuan-note/logging""github.com/siyuan-note/siyuan/kernel/util")-const CurrentSpec = 8+const (+ CurrentSpec = 9+ PlainTextSpec = 8+ RichTextSpec = 9+)const MaxFilterNestingDepth = 3@@ -41,6 +46,7 @@ func UpgradeSpec(av *AttributeView) {upgradeSpec6(av)upgradeSpec7(av)upgradeSpec8(av)+ upgradeSpec9(av)}func CheckSpec(av *AttributeView) (err error) {@@ -49,6 +55,69 @@ func CheckSpec(av *AttributeView) (err error) {err = ErrSpecTooNewreturn}+ if av.Spec < RichTextSpec && av.HasRichText() {+ logging.LogErrorf("attribute view [%s] rich text requires spec [%d], current is [%d]", av.ID, RichTextSpec, av.Spec)+ err = ErrRichTextSpecMismatch+ return+ }+ return+}++// upgradeSpec9 仅在首次保存富文本值时升级,避免纯文本数据库因为在新版中打开而失去旧版兼容性。+func upgradeSpec9(av *AttributeView) {+ if RichTextSpec <= av.Spec || !av.HasRichText() {+ return+ }++ av.Spec = RichTextSpec+}++// HasRichText 返回属性视图是否包含富文本值。+func (av *AttributeView) HasRichText() bool {+ if nil == av {+ return false+ }+ found := false+ av.visitPersistedValues(func(value *Value) {+ if nil != value.Text && value.Text.IsRich() {+ found = true+ }+ })+ return found+}++// NormalizeRichText 校验所有富文本载荷,并刷新对应的纯文本投影。+func (av *AttributeView) NormalizeRichText() (err error) {+ if nil == av {+ return+ }+ type normalizedText struct {+ value *ValueText+ content string+ richContent string+ }+ var normalized []normalizedText+ av.visitPersistedValues(func(value *Value) {+ if nil != err || nil == value.Text || !value.Text.IsRich() {+ return+ }+ rich := *value.Text.Rich+ var tree *parse.Tree+ if tree, err = NormalizeValueTextRich(&rich); nil == err {+ normalized = append(normalized, normalizedText{+ value: value.Text,+ content: valueTextRichPlainContent(tree),+ richContent: rich.Content,+ })+ }+ })+ if nil != err {+ return+ }+ for _, text := range normalized {+ text.value.Content = text.content+ text.value.Rich.Content = text.richContent+ }return}diff --git a/kernel/av/av_fix_test.go b/kernel/av/av_fix_test.goindex f58d3e9631..3e2b0d2995 100644--- a/kernel/av/av_fix_test.go+++ b/kernel/av/av_fix_test.go@@ -39,8 +39,8 @@ func TestUpgradeSpec6CardConfiguration(t *testing.T) {UpgradeSpec(attrView)- if CurrentSpec != attrView.Spec {- t.Fatalf("expected spec %d, got %d", CurrentSpec, attrView.Spec)+ if PlainTextSpec != attrView.Spec {+ t.Fatalf("expected spec %d, got %d", PlainTextSpec, attrView.Spec)}if 180 != attrView.Views[0].Gallery.CardWidth {t.Fatalf("expected gallery width 180, got %d", attrView.Views[0].Gallery.CardWidth)@@ -62,8 +62,8 @@ func TestUpgradeSpec7RemovesPersistedCurrentView(t *testing.T) {t.Fatal(err)}UpgradeSpec(attrView)- if CurrentSpec != attrView.Spec {- t.Fatalf("expected spec %d, got %d", CurrentSpec, attrView.Spec)+ if PlainTextSpec != attrView.Spec {+ t.Fatalf("expected spec %d, got %d", PlainTextSpec, attrView.Spec)}data, err := json.Marshal(attrView)if nil != err {@@ -81,7 +81,67 @@ func TestUpgradeSpec7RemovesPersistedCurrentView(t *testing.T) {func TestUpgradeSpec8(t *testing.T) {attrView := &AttributeView{Spec: 7}UpgradeSpec(attrView)- if CurrentSpec != attrView.Spec {- t.Fatalf("expected spec %d, got %d", CurrentSpec, attrView.Spec)+ if PlainTextSpec != attrView.Spec {+ t.Fatalf("expected spec %d, got %d", PlainTextSpec, attrView.Spec)+ }+}++func TestUpgradeSpec9OnlyForRichText(t *testing.T) {+ plain := &AttributeView{Spec: PlainTextSpec, KeyValues: []*KeyValues{{Values: []*Value{{+ Type: KeyTypeText,+ Text: &ValueText{Content: "**literal**"},+ }}}}}+ UpgradeSpec(plain)+ if PlainTextSpec != plain.Spec {+ t.Fatalf("plain text unexpectedly upgraded to spec %d", plain.Spec)+ }++ rich := &AttributeView{Spec: PlainTextSpec, KeyValues: []*KeyValues{{Values: []*Value{{+ Type: KeyTypeText,+ Text: &ValueText{Rich: &ValueTextRich{+ Spec: ValueTextRichSpec,+ Format: ValueTextRichFormatKramdown,+ Content: "**rich**",+ }},+ }}}}}+ UpgradeSpec(rich)+ if RichTextSpec != rich.Spec {+ t.Fatalf("expected rich text spec %d, got %d", RichTextSpec, rich.Spec)+ }++ rich.KeyValues[0].Values[0].Text.Rich = nil+ UpgradeSpec(rich)+ if RichTextSpec != rich.Spec {+ t.Fatalf("rich text spec was downgraded to %d", rich.Spec)+ }++ templateRich := &AttributeView{+ Spec: PlainTextSpec,+ NewItemTemplates: []*NewItemTemplate{{+ FieldValues: map[string]*NewItemFieldValue{+ "text": {+ Value: &Value{+ Type: KeyTypeText,+ Text: &ValueText{Rich: &ValueTextRich{+ Spec: ValueTextRichSpec,+ Format: ValueTextRichFormatKramdown,+ Content: "**template**",+ }},+ },+ },+ },+ }},+ }+ UpgradeSpec(templateRich)+ if RichTextSpec != templateRich.Spec {+ t.Fatalf("persisted template rich text did not upgrade spec: %d", templateRich.Spec)+ }++ mismatched := &AttributeView{Spec: PlainTextSpec, KeyValues: rich.KeyValues}+ mismatched.KeyValues[0].Values[0].Text.Rich = &ValueTextRich{+ Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown, Content: "rich",+ }+ if err := CheckSpec(mismatched); ErrRichTextSpecMismatch != err {+ t.Fatalf("rich text in plain storage spec was accepted: %v", err)}}diff --git a/kernel/av/av_search_test.go b/kernel/av/av_search_test.goindex 77eb994834..90add9bc40 100644--- a/kernel/av/av_search_test.go+++ b/kernel/av/av_search_test.go@@ -48,7 +48,7 @@ func TestParseAttributeViewSearchInfo(t *testing.T) {t.Fatalf("unexpected second view: %+v", info.Views[1])}- if _, err = parseAttributeViewSearchInfo([]byte(`{"spec": 9}`)); err != ErrSpecTooNew {+ if _, err = parseAttributeViewSearchInfo([]byte(`{"spec": 10}`)); err != ErrSpecTooNew {t.Fatalf("expected newer spec error, got %v", err)}}diff --git a/kernel/av/filter_test.go b/kernel/av/filter_test.goindex 3df2a2209c..39ae123e16 100644--- a/kernel/av/filter_test.go+++ b/kernel/av/filter_test.go@@ -851,8 +851,8 @@ func TestUpgradeSpec5(t *testing.T) {// spec 4 + 扁平叶子 → 包装成根组av4 := &AttributeView{Spec: 4, Views: []*View{{Filters: []*ViewFilter{leaf("c1"), leaf("c2")}}}}UpgradeSpec(av4)- if av4.Spec != CurrentSpec {- t.Fatalf("spec should be upgraded to %d, got %d", CurrentSpec, av4.Spec)+ if av4.Spec != PlainTextSpec {+ t.Fatalf("spec should be upgraded to %d, got %d", PlainTextSpec, av4.Spec)}filters := av4.Views[0].Filtersif len(filters) != 1 || !filters[0].IsGroup() || FilterCombinationAnd != filters[0].Combination {diff --git a/kernel/av/ref_hook.go b/kernel/av/ref_hook.gonew file mode 100644index 0000000000..ee23d854bb--- /dev/null+++ b/kernel/av/ref_hook.go@@ -0,0 +1,35 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package av++import "github.com/siyuan-note/logging"++// AttributeViewSaved 由 model 层注入,在属性视图落盘后刷新载体文档的引用索引。+var AttributeViewSaved func(avID, boxID string)++// NotifyAttributeViewSaved 安全地通知上层属性视图已经落盘。+func NotifyAttributeViewSaved(avID, boxID string) {+ if nil == AttributeViewSaved {+ return+ }+ defer func() {+ if recovered := recover(); nil != recovered {+ logging.LogErrorf("notify saved attribute view [%s] failed: %v", avID, recovered)+ }+ }()+ AttributeViewSaved(avID, boxID)+}diff --git a/kernel/av/render_template.go b/kernel/av/render_template.goindex 6d54cb5919..c3165d0478 100644--- a/kernel/av/render_template.go+++ b/kernel/av/render_template.go@@ -72,6 +72,14 @@ func (av *AttributeView) suspendRenderedContents() (restore func()) {}}+// VisitPersistedValues 遍历属性视图中所有会持久化的值,每个值仅访问一次。+func (av *AttributeView) VisitPersistedValues(visit func(*Value)) {+ if nil == av || nil == visit {+ return+ }+ av.visitPersistedValues(visit)+}+func (av *AttributeView) visitPersistedValues(visit func(*Value)) {visited := map[*Value]struct{}{}var visitValue func(value *Value)diff --git a/kernel/av/value.go b/kernel/av/value.goindex 189ef02930..b268ac9a7e 100644--- a/kernel/av/value.go+++ b/kernel/av/value.go@@ -18,15 +18,23 @@ package avimport ("fmt"+ "html""math"+ "net/url"+ "path""reflect"+ "regexp""sort""strconv""strings""time"+ "unicode"+ "unicode/utf8""github.com/88250/gulu"+ "github.com/88250/lute""github.com/88250/lute/ast"+ "github.com/88250/lute/parse""github.com/siyuan-note/siyuan/kernel/util""golang.org/x/text/language""golang.org/x/text/message"@@ -517,7 +525,1641 @@ func (value *Value) NormalizeBlockRefSubtype(avID string, attrs map[string]strin}type ValueText struct {- Content string `json:"content"`+ Content string `json:"content"`+ Rich *ValueTextRich `json:"rich,omitempty"`+}++const ValueTextRichSpec = 1++type ValueTextRichFormat string++const ValueTextRichFormatKramdown ValueTextRichFormat = "kramdown"++// ValueTextRich 描述文本字段的富文本源,Content 是 SiYuan Kramdown 片段。+type ValueTextRich struct {+ Spec int `json:"spec"`+ Format ValueTextRichFormat `json:"format"`+ Content string `json:"content"`+}++// IsRich 返回文本值是否包含富文本源。+func (value *ValueText) IsRich() bool {+ return nil != value && nil != value.Rich+}++// ParseValueTextRich 校验并解析文本字段的富文本源。+func ParseValueTextRich(rich *ValueTextRich) (tree *parse.Tree, err error) {+ _, tree, err = parseValueTextRich(rich)+ return+}++func parseValueTextRich(rich *ValueTextRich) (blockDOM string, tree *parse.Tree, err error) {+ if nil == rich {+ return+ }+ if ValueTextRichSpec != rich.Spec {+ err = fmt.Errorf("unsupported attribute view rich text spec [%d]", rich.Spec)+ return+ }+ if ValueTextRichFormatKramdown != rich.Format {+ err = fmt.Errorf("unsupported attribute view rich text format [%s]", rich.Format)+ return+ }++ luteEngine := newValueTextRichLute()+ content, protectedStyleEntities, protectErr := protectValueTextRichKramdownStyleEntities(rich.Content)+ if nil != protectErr {+ err = protectErr+ return+ }+ blockDOM, tree = luteEngine.Md2BlockDOMTree(content, true)+ if nil == tree || nil == tree.Root {+ err = fmt.Errorf("parse attribute view rich text failed")+ return+ }+ if 0 < len(protectedStyleEntities) {+ if err = restoreValueTextRichTreeStyleEntities(tree, protectedStyleEntities); nil != err {+ return+ }+ blockDOM = luteEngine.Tree2BlockDOM(tree, luteEngine.RenderOptions, luteEngine.ParseOptions)+ }+ err = validateValueTextRichTree(tree)+ return+}++func validateValueTextRichTree(tree *parse.Tree) (err error) {+ if nil == tree || nil == tree.Root {+ return fmt.Errorf("attribute view rich text tree is missing")+ }+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if !entering {+ return ast.WalkContinue+ }+ if !isAllowedValueTextRichNode(node) {+ err = fmt.Errorf("unsupported attribute view rich text node [%s]", node.Type.String())+ return ast.WalkStop+ }+ return ast.WalkContinue+ })+ return+}++// newValueTextRichLute 固定启用存储格式支持的语法,避免编辑器开关变化后重解释既有数据。+func newValueTextRichLute() *lute.Lute {+ ret := lute.New()+ ret.SetTextMark(true)+ ret.SetEmoji(false)+ ret.SetProtyleWYSIWYG(true)+ ret.SetBlockRef(true)+ ret.SetFileAnnotationRef(true)+ ret.SetKramdownIAL(true)+ ret.SetHTMLTag2TextMark(true)+ ret.SetSuperBlock(true)+ ret.SetCustomBlock(true)+ ret.SetImgPathAllowSpace(true)+ ret.SetGitConflict(true)+ ret.SetInlineAsterisk(true)+ ret.SetInlineUnderscore(true)+ ret.SetSup(true)+ ret.SetSub(true)+ ret.SetTag(true)+ ret.SetInlineMath(true)+ ret.SetGFMStrikethrough(true)+ ret.SetFullWidthStrikethrough(true)+ ret.SetGFMStrikethrough1(false)+ ret.SetMark(true)+ ret.SetInlineMathAllowDigitAfterOpenMarker(true)+ ret.SetFootnotes(false)+ ret.SetToC(false)+ ret.SetIndentCodeBlock(false)+ ret.SetParagraphBeginningSpace(true)+ ret.SetAutoSpace(false)+ ret.SetHeadingID(false)+ ret.SetSetext(false)+ ret.SetYamlFrontMatter(false)+ ret.SetLinkRef(false)+ ret.SetCodeSyntaxHighlight(false)+ ret.SetSanitize(true)+ ret.SetUnorderedListMarker("-")+ ret.SetCallout(true)+ ret.SetDataTask(true)+ ret.SetArbitraryTaskListItemMarker(true)+ ret.SetExportNormalizeTaskListMarker(false)+ ret.SetEnsureListItemParagraph(true)+ return ret+}++func isAllowedValueTextRichNode(node *ast.Node) bool {+ if nil == node {+ return false+ }+ switch node.Type {+ case ast.NodeDocument, ast.NodeParagraph,+ ast.NodeBlockquote, ast.NodeBlockquoteMarker,+ ast.NodeList, ast.NodeListItem, ast.NodeTaskListItemMarker,+ ast.NodeCodeBlockFenceOpenMarker, ast.NodeCodeBlockFenceCloseMarker, ast.NodeCodeBlockCode,+ ast.NodeMathBlock, ast.NodeMathBlockOpenMarker, ast.NodeMathBlockContent, ast.NodeMathBlockCloseMarker,+ ast.NodeText,+ ast.NodeEmphasis, ast.NodeEmA6kOpenMarker, ast.NodeEmA6kCloseMarker, ast.NodeEmU8eOpenMarker,+ ast.NodeEmU8eCloseMarker,+ ast.NodeStrong, ast.NodeStrongA6kOpenMarker, ast.NodeStrongA6kCloseMarker, ast.NodeStrongU8eOpenMarker,+ ast.NodeStrongU8eCloseMarker,+ ast.NodeCodeSpan, ast.NodeCodeSpanOpenMarker, ast.NodeCodeSpanContent, ast.NodeCodeSpanCloseMarker,+ ast.NodeHardBreak, ast.NodeSoftBreak,+ ast.NodeLink, ast.NodeOpenBracket, ast.NodeCloseBracket, ast.NodeOpenParen,+ ast.NodeCloseParen, ast.NodeLinkText, ast.NodeLinkTitle, ast.NodeLinkSpace,+ ast.NodeHTMLEntity, ast.NodeLess, ast.NodeGreater,+ ast.NodeStrikethrough, ast.NodeStrikethrough1OpenMarker, ast.NodeStrikethrough1CloseMarker,+ ast.NodeStrikethrough2OpenMarker, ast.NodeStrikethrough2CloseMarker,+ ast.NodeEmoji, ast.NodeEmojiUnicode, ast.NodeEmojiAlias,+ ast.NodeInlineMath, ast.NodeInlineMathOpenMarker, ast.NodeInlineMathContent, ast.NodeInlineMathCloseMarker,+ ast.NodeBackslash, ast.NodeBackslashContent,+ ast.NodeBlockRef, ast.NodeBlockRefID, ast.NodeBlockRefSpace, ast.NodeBlockRefText,+ ast.NodeBlockRefDynamicText,+ ast.NodeMark, ast.NodeMark1OpenMarker, ast.NodeMark1CloseMarker, ast.NodeMark2OpenMarker,+ ast.NodeMark2CloseMarker,+ ast.NodeTag, ast.NodeTagOpenMarker, ast.NodeTagCloseMarker,+ ast.NodeSup, ast.NodeSupOpenMarker, ast.NodeSupCloseMarker,+ ast.NodeSub, ast.NodeSubOpenMarker, ast.NodeSubCloseMarker,+ ast.NodeKbd, ast.NodeKbdOpenMarker, ast.NodeKbdCloseMarker,+ ast.NodeUnderline, ast.NodeUnderlineOpenMarker, ast.NodeUnderlineCloseMarker,+ ast.NodeBr,+ ast.NodeFileAnnotationRef, ast.NodeFileAnnotationRefID, ast.NodeFileAnnotationRefSpace,+ ast.NodeFileAnnotationRefText:+ return true+ case ast.NodeLinkDest:+ return isAllowedValueTextRichLinkTarget(node.TokensStr())+ case ast.NodeCodeBlock, ast.NodeCodeBlockFenceInfoMarker:+ return !isValueTextRichExecutableCodeFence(node.CodeBlockInfo)+ case ast.NodeKramdownBlockIAL:+ return isAllowedValueTextRichBlockIAL(node)+ case ast.NodeKramdownSpanIAL:+ return isAllowedValueTextRichSpanIAL(node)+ case ast.NodeTextMark:+ return isAllowedValueTextMark(node)+ }+ return false+}++func isValueTextRichExecutableCodeFence(info []byte) bool {+ fields := strings.Fields(strings.ToLower(string(info)))+ if 1 > len(fields) {+ return false+ }+ switch fields[0] {+ case "abc", "echarts", "flowchart", "graphviz", "infographic", "mermaid", "mindmap", "plantuml":+ return true+ }+ return false+}++func isAllowedValueTextMark(node *ast.Node) bool {+ if !isAllowedValueTextMarkType(node) || !isAllowedValueTextMarkReferenceData(node) {+ return false+ }+ if 1 > len(node.KramdownIAL) {+ return nil == node.Next || ast.NodeKramdownSpanIAL != node.Next.Type+ }+ return nil != node.Next && ast.NodeKramdownSpanIAL == node.Next.Type &&+ isAllowedValueTextRichSpanIAL(node.Next)+}++func isAllowedValueTextMarkType(node *ast.Node) bool {+ if "" == node.TextMarkType || "" != node.TextMarkFlashcardOcclusionID {+ return false+ }+ for _, typ := range strings.Fields(node.TextMarkType) {+ switch typ {+ case "text", "block-ref", "kbd", "file-annotation-ref", "a", "strong", "em", "u", "s", "mark",+ "sup", "sub", "tag", "code", "inline-math", "inline-memo":+ default:+ return false+ }+ }+ return true+}++func isAllowedValueTextMarkReferenceData(node *ast.Node) bool {+ if node.IsTextMarkType("block-ref") {+ if !ast.IsNodeIDPattern(node.TextMarkBlockRefID) ||+ ("d" != node.TextMarkBlockRefSubtype && "s" != node.TextMarkBlockRefSubtype) ||+ node.IsTextMarkType("a") || node.IsTextMarkType("file-annotation-ref") ||+ node.IsTextMarkType("inline-math") || "" != node.TextMarkAHref || "" != node.TextMarkATitle ||+ "" != node.TextMarkFileAnnotationRefID || "" != node.TextMarkInlineMathContent {+ return false+ }+ } else if "" != node.TextMarkBlockRefID || "" != node.TextMarkBlockRefSubtype {+ return false+ }++ if node.IsTextMarkType("file-annotation-ref") {+ if !isAllowedValueTextMarkFileAnnotationRefID(node.TextMarkFileAnnotationRefID) ||+ node.IsTextMarkType("a") || node.IsTextMarkType("inline-math") || "" != node.TextMarkAHref ||+ "" != node.TextMarkATitle || "" != node.TextMarkInlineMathContent {+ return false+ }+ } else if "" != node.TextMarkFileAnnotationRefID {+ return false+ }++ if node.IsTextMarkType("a") {+ if !isAllowedValueTextRichLinkTarget(node.TextMarkAHref) {+ return false+ }+ } else if "" != node.TextMarkAHref || "" != node.TextMarkATitle {+ return false+ }++ if node.IsTextMarkType("inline-memo") {+ if !isAllowedValueTextRichInlineMemoContent(node.TextMarkInlineMemoContent) {+ return false+ }+ } else if "" != node.TextMarkInlineMemoContent {+ return false+ }+ return true+}++func isAllowedValueTextRichLinkTarget(target string) bool {+ if "" == target {+ return true+ }+ if target != strings.TrimSpace(target) || !utf8.ValidString(target) {+ return false+ }+ target, decodedTarget, ok := decodeValueTextRichLinkTarget(target)+ if !ok || !utf8.ValidString(decodedTarget) || target != strings.TrimSpace(target) ||+ containsValueTextRichUnsafeControl(target) ||+ containsValueTextRichUnsafeControl(decodedTarget) || strings.ContainsRune(target, '\\') ||+ strings.ContainsRune(decodedTarget, '\\') {+ return false+ }++ parsed, err := url.Parse(target)+ if nil != err {+ return false+ }+ scheme := strings.ToLower(parsed.Scheme)+ switch scheme {+ case "http", "https":+ return "" != parsed.Host && "" == parsed.Opaque &&+ strings.HasPrefix(strings.ToLower(target), scheme+"://")+ case "mailto", "tel":+ return "" != parsed.Opaque && strings.HasPrefix(strings.ToLower(target), scheme+":")+ case "siyuan", "web+siyuan":+ return "" != parsed.Host && "" == parsed.Opaque &&+ strings.HasPrefix(strings.ToLower(target), scheme+"://")+ case "":+ return isAllowedValueTextRichRelativeLinkTarget(target, decodedTarget, parsed)+ default:+ return false+ }+}++func decodeValueTextRichLinkTarget(target string) (ret, decoded string, ok bool) {+ ret = target+ for iteration := 0; iteration < 8; iteration++ {+ next := html.UnescapeString(ret)+ if next == ret {+ decoded, err := url.PathUnescape(ret)+ if nil != err {+ return "", "", false+ }+ return ret, decoded, true+ }+ ret = next+ }+ return "", "", false+}++func isAllowedValueTextRichRelativeLinkTarget(target, decodedTarget string, parsed *url.URL) bool {+ if strings.HasPrefix(target, "//") {+ return "" != parsed.Host+ }+ separator := strings.IndexAny(decodedTarget, "/?#")+ if colon := strings.IndexByte(decodedTarget, ':'); 0 <= colon && (0 > separator || colon < separator) {+ return false+ }+ if "" != parsed.Host {+ return false+ }+ assetPath := strings.TrimPrefix(parsed.Path, "/")+ if strings.HasPrefix(assetPath, "assets/") {+ return path.Clean(assetPath) == assetPath+ }+ return true+}++func isAllowedValueTextRichInlineMemoContent(content string) bool {+ if !utf8.ValidString(content) || containsValueTextRichMemoControl(content) {+ return false+ }+ decoded := content+ for iteration := 0; iteration < 8; iteration++ {+ next := html.UnescapeString(decoded)+ if next == decoded {+ return !containsValueTextRichHTMLTag(decoded)+ }+ decoded = next+ if containsValueTextRichMemoControl(decoded) {+ return false+ }+ }+ return false+}++func containsValueTextRichHTMLTag(content string) bool {+ for cursor := 0; cursor < len(content); cursor++ {+ if '<' != content[cursor] || cursor+1 >= len(content) {+ continue+ }+ next := content[cursor+1]+ if '!' == next || '?' == next || isValueTextRichASCIIAlpha(next) {+ return true+ }+ if '/' == next && cursor+2 < len(content) && isValueTextRichASCIIAlpha(content[cursor+2]) {+ return true+ }+ }+ return false+}++func isValueTextRichASCIIAlpha(char byte) bool {+ return 'a' <= char && char <= 'z' || 'A' <= char && char <= 'Z'+}++func containsValueTextRichMemoControl(value string) bool {+ for _, char := range value {+ if unicode.IsControl(char) && '\t' != char && '\n' != char && '\r' != char {+ return true+ }+ }+ return false+}++func containsValueTextRichUnsafeControl(value string) bool {+ for _, char := range value {+ if unicode.IsControl(char) || unicode.In(char, unicode.Cf) {+ return true+ }+ }+ return false+}++func isAllowedValueTextMarkFileAnnotationRefID(id string) bool {+ const prefix = "assets/"+ if !strings.HasPrefix(id, prefix) {+ return false+ }+ parts := strings.Split(strings.TrimPrefix(id, prefix), "/")+ if 2 != len(parts) {+ return false+ }+ fileName := parts[0]+ if !strings.Contains(fileName, "-") || !strings.HasSuffix(strings.ToLower(fileName), ".pdf") {+ return false+ }+ fileBase := fileName[:len(fileName)-len(".pdf")]+ if 23 > len(fileBase) || !ast.IsNodeIDPattern(fileBase[len(fileBase)-22:]) {+ return false+ }+ return ast.IsNodeIDPattern(parts[1])+}++func isAllowedValueTextRichSpanIAL(node *ast.Node) bool {+ if nil == node || nil == node.Previous || ast.NodeTextMark != node.Previous.Type ||+ !isAllowedValueTextMarkType(node.Previous) || !node.Previous.IsTextMarkType("text") {+ return false+ }+ markIAL := node.Previous.KramdownIAL+ spanIAL := parse.Tokens2IAL(node.Tokens)+ if 1 != len(markIAL) || 1 != len(spanIAL) || 2 != len(markIAL[0]) || 2 != len(spanIAL[0]) ||+ "style" != markIAL[0][0] || "style" != spanIAL[0][0] {+ return false+ }+ style := node.Previous.IALAttr("style")+ if "" == style || style != parse.IALVal(node, "style") {+ return false+ }+ return isAllowedValueTextRichStyle(style)+}++func isAllowedValueTextRichStyle(style string) bool {+ _, ok := normalizeValueTextRichStyle(style)+ return ok+}++func normalizeValueTextRichStyle(style string) (ret string, ok bool) {+ declarations, ok := parseValueTextRichStyleDeclarations(style)+ if !ok {+ return "", false+ }+ for property, value := range declarations {+ if declarations[property], ok = normalizeValueTextRichStyleValue(property, value); !ok {+ return "", false+ }+ }+ if !valueTextRichStylePairMatches(declarations, "direction", "unicode-bidi") ||+ !valueTextRichStylePairMatches(declarations, "-webkit-text-stroke", "-webkit-text-fill-color") {+ return "", false+ }++ var normalized []string+ for _, property := range valueTextRichStylePropertyOrder {+ if value, exists := declarations[property]; exists {+ normalized = append(normalized, property+": "+value+";")+ }+ }+ if len(normalized) != len(declarations) {+ return "", false+ }+ return strings.Join(normalized, " "), true+}++func parseValueTextRichStyleDeclarations(style string) (ret map[string]string, ok bool) {+ segments, ok := splitValueTextRichStyle(style, ';')+ if !ok || 1 > len(segments) {+ return nil, false+ }+ ret = make(map[string]string, len(segments))+ for _, segment := range segments {+ parts, valid := splitValueTextRichStyle(segment, ':')+ if !valid || 2 != len(parts) {+ return nil, false+ }+ property, value := strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1])+ if "" == property || "" == value {+ return nil, false+ }+ if _, exists := ret[property]; exists {+ return nil, false+ }+ ret[property] = value+ }+ return ret, true+}++func splitValueTextRichStyle(value string, separator byte) (ret []string, ok bool) {+ value = strings.TrimSpace(value)+ if "" == value {+ return nil, false+ }+ start, parentheses := 0, 0+ var quote byte+ escaped := false+ for i := 0; i < len(value); i++ {+ character := value[i]+ if escaped {+ escaped = false+ continue+ }+ if '\\' == character {+ escaped = true+ continue+ }+ if 0 != quote {+ if quote == character {+ quote = 0+ }+ continue+ }+ if '\'' == character || '"' == character {+ quote = character+ continue+ }+ switch character {+ case '(':+ parentheses+++ case ')':+ if 1 > parentheses {+ return nil, false+ }+ parentheses--+ default:+ if separator == character && 0 == parentheses {+ part := strings.TrimSpace(value[start:i])+ if "" == part {+ if ';' == separator && i == len(value)-1 {+ start = len(value)+ continue+ }+ return nil, false+ }+ ret = append(ret, part)+ start = i + 1+ if ':' == separator {+ part = strings.TrimSpace(value[start:])+ if "" == part {+ return nil, false+ }+ ret = append(ret, part)+ return ret, true+ }+ }+ }+ }+ if escaped || 0 != quote || 0 != parentheses {+ return nil, false+ }+ if start < len(value) {+ part := strings.TrimSpace(value[start:])+ if "" == part {+ return nil, false+ }+ ret = append(ret, part)+ }+ return ret, 0 < len(ret)+}++func valueTextRichStylePairMatches(declarations map[string]string, first, second string) bool {+ _, hasFirst := declarations[first]+ _, hasSecond := declarations[second]+ return hasFirst == hasSecond+}++func normalizeValueTextRichStyleValue(property, value string) (ret string, ok bool) {+ switch property {+ case "color":+ if ret, ok = normalizeValueTextRichBuiltinPaletteValue(property, value); ok {+ return ret, true+ }+ if ret, ok = normalizeValueTextRichCustomStyleValue(property, valueTextRichCustomColorPattern, value); ok {+ return ret, true+ }+ return normalizeValueTextRichBuiltinStyleValue(property, value)+ case "background-color":+ if ret, ok = normalizeValueTextRichBuiltinPaletteValue(property, value); ok {+ return ret, true+ }+ if ret, ok = normalizeValueTextRichCustomStyleValue(property, valueTextRichCustomBackgroundPattern, value); ok {+ return ret, true+ }+ return normalizeValueTextRichBuiltinStyleValue(property, value)+ case "font-size":+ return normalizeValueTextRichFontSize(value)+ case "font-family":+ return normalizeValueTextRichFontFamily(value)+ case "direction":+ return value, "ltr" == value || "rtl" == value+ case "unicode-bidi":+ return value, "isolate" == value+ case "-webkit-text-stroke":+ return value, valueTextRichHollowStroke == value+ case "-webkit-text-fill-color":+ return value, valueTextRichHollowFill == value+ case "text-shadow":+ return value, valueTextRichTextShadow == value+ }+ return "", false+}++func normalizeValueTextRichFontSize(value string) (ret string, ok bool) {+ if match := valueTextRichFontSizePXPattern.FindStringSubmatch(value); 2 == len(match) {+ size, err := strconv.Atoi(match[1])+ if nil == err && 9 <= size && size <= 72 {+ return strconv.Itoa(size) + "px", true+ }+ return "", false+ }+ if !valueTextRichFontSizeEMPattern.MatchString(value) {+ return "", false+ }+ number := strings.TrimSuffix(value, "em")+ size, err := strconv.ParseFloat(number, 64)+ if nil != err || size < 0.56 || 4.5 < size {+ return "", false+ }+ return strconv.FormatFloat(size, 'f', -1, 64) + "em", true+}++func normalizeValueTextRichFontFamily(value string) (ret string, ok bool) {+ if 2048 < len(value) {+ return "", false+ }+ parts, ok := splitValueTextRichStyle(value, ',')+ if !ok || 4 != len(parts) || "var(--b3-font-family-emoji-reset)" != parts[0] ||+ "var(--b3-font-family-editor)" != parts[2] || "var(--b3-font-family)" != parts[3] {+ return "", false+ }+ quoted := parts[1]+ if 2 > len(quoted) || quoted[0] != quoted[len(quoted)-1] || ('\'' != quoted[0] && '"' != quoted[0]) {+ return "", false+ }+ escaped := quoted[1 : len(quoted)-1]+ family, ok := unescapeValueTextRichCSSString(escaped)+ if !ok || "" == family || 256 < utf8.RuneCountInString(family) {+ return "", false+ }+ normalizedFamily := strings.ToLower(family)+ if "emojis additional" == normalizedFamily || "emojis reset" == normalizedFamily ||+ "inherit" == normalizedFamily || "initial" == normalizedFamily || "revert" == normalizedFamily ||+ "revert-layer" == normalizedFamily || "unset" == normalizedFamily || strings.HasPrefix(normalizedFamily, "var(") {+ return "", false+ }+ return "var(--b3-font-family-emoji-reset), '" + escapeValueTextRichCSSString(family) ++ "', var(--b3-font-family-editor), var(--b3-font-family)", true+}++func unescapeValueTextRichCSSString(value string) (ret string, ok bool) {+ var builder strings.Builder+ for i := 0; i < len(value); {+ if '\\' != value[i] {+ character, size := utf8.DecodeRuneInString(value[i:])+ if utf8.RuneError == character && 1 == size {+ return "", false+ }+ builder.WriteRune(character)+ i += size+ continue+ }+ i+++ if len(value) <= i {+ return "", false+ }+ start := i+ for i < len(value) && i-start < 6 && isValueTextRichCSSHex(value[i]) {+ i+++ }+ if start < i {+ codePoint, err := strconv.ParseInt(value[start:i], 16, 32)+ if nil != err || 0 == codePoint || 0x10ffff < codePoint {+ builder.WriteRune(utf8.RuneError)+ } else {+ builder.WriteRune(rune(codePoint))+ }+ if i < len(value) && isValueTextRichCSSWhitespace(value[i]) {+ i+++ }+ continue+ }+ character, size := utf8.DecodeRuneInString(value[i:])+ if utf8.RuneError == character && 1 == size {+ return "", false+ }+ builder.WriteRune(character)+ i += size+ }+ return builder.String(), true+}++func escapeValueTextRichCSSString(value string) string {+ var builder strings.Builder+ for _, character := range value {+ switch {+ case '"' == character:+ builder.WriteString(`\22 `)+ case '\'' == character || '\\' == character:+ builder.WriteByte('\\')+ builder.WriteRune(character)+ case character < 32 || 127 == character:+ builder.WriteByte('\\')+ builder.WriteString(strconv.FormatInt(int64(character), 16))+ builder.WriteByte(' ')+ default:+ builder.WriteRune(character)+ }+ }+ return builder.String()+}++func isValueTextRichCSSHex(character byte) bool {+ return '0' <= character && character <= '9' || 'a' <= character && character <= 'f' ||+ 'A' <= character && character <= 'F'+}++func isValueTextRichCSSWhitespace(character byte) bool {+ switch character {+ case ' ', '\t', '\n', '\r', '\f':+ return true+ }+ return false+}++func normalizeValueTextRichCustomStyleValue(property string, pattern *regexp.Regexp, value string) (ret string, ok bool) {+ match := pattern.FindStringSubmatch(value)+ if 3 != len(match) || !ast.IsNodeIDPattern(match[1]) {+ return "", false+ }+ return fmt.Sprintf("var(--b3-inline-style-%s-%s, %s)", match[1], property, strings.ToLower(match[2])), true+}++func normalizeValueTextRichBuiltinPaletteValue(property, value string) (ret string, ok bool) {+ match := valueTextRichBuiltinPalettePattern.FindStringSubmatch(value)+ if 3 != len(match) || "color" == property && "color" != match[1] ||+ "background-color" == property && "background" != match[1] {+ return "", false+ }+ index, err := strconv.Atoi(match[2])+ if nil != err || 1 > index || 13 < index {+ return "", false+ }+ return fmt.Sprintf("var(--b3-font-%s%d)", match[1], index), true+}++func normalizeValueTextRichBuiltinStyleValue(property, value string) (ret string, ok bool) {+ valueSuffix, legacySuffix := "color", "color"+ if "background-color" == property {+ valueSuffix, legacySuffix = "background-color", "background"+ }+ match := valueTextRichBuiltinStylePattern.FindStringSubmatch(value)+ if 5 != len(match) || match[1] != match[3] || match[2] != valueSuffix || match[4] != legacySuffix {+ return "", false+ }+ return fmt.Sprintf("var(--b3-inline-builtin-%s-%s, var(--b3-card-%s-%s))",+ match[1], valueSuffix, match[1], legacySuffix), true+}++func normalizeValueTextRichTreeStyles(tree *parse.Tree) (err error) {+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if !entering || ast.NodeTextMark != node.Type || 1 > len(node.KramdownIAL) {+ return ast.WalkContinue+ }+ style := node.IALAttr("style")+ var normalized string+ var ok bool+ if normalized, ok = normalizeValueTextRichStyle(style); !ok {+ err = fmt.Errorf("unsupported attribute view rich text style")+ return ast.WalkStop+ }+ node.SetIALAttr("style", normalized)+ node.Next.Tokens = parse.IAL2Tokens(node.KramdownIAL)+ return ast.WalkContinue+ })+ return+}++func isAllowedValueTextRichBlockIAL(node *ast.Node) bool {+ ial := parse.Tokens2IAL(node.Tokens)+ if 1 > len(ial) {+ return false+ }+ hasID := false+ for _, attr := range ial {+ if 2 != len(attr) {+ return false+ }+ switch attr[0] {+ case "id":+ if !ast.IsNodeIDPattern(attr[1]) {+ return false+ }+ hasID = true+ case "updated":+ if !isValueTextRichTimestamp(attr[1]) {+ return false+ }+ case "type":+ if "doc" != attr[1] {+ return false+ }+ default:+ return false+ }+ }+ return hasID+}++func isValueTextRichTimestamp(value string) bool {+ if 14 != len(value) {+ return false+ }+ for _, digit := range value {+ if digit < '0' || '9' < digit {+ return false+ }+ }+ return true+}++var valueTextRichBlockDOMStructuralAttrs = regexp.MustCompile(`\s(?:data-node-id|data-node-index|updated)="[^"]*"`)++const (+ valueTextRichHollowStroke = "0.2px var(--b3-theme-on-background)"+ valueTextRichHollowFill = "transparent"+ valueTextRichTextShadow = "1px 1px var(--b3-theme-surface-lighter), 2px 2px var(--b3-theme-surface-lighter), " ++ "3px 3px var(--b3-theme-surface-lighter), 4px 4px var(--b3-theme-surface-lighter)"+)++var valueTextRichStylePropertyOrder = []string{+ "color",+ "background-color",+ "font-size",+ "font-family",+ "-webkit-text-stroke",+ "-webkit-text-fill-color",+ "text-shadow",+ "direction",+ "unicode-bidi",+}++var (+ valueTextRichBuiltinPalettePattern = regexp.MustCompile(`^var\(--b3-font-(color|background)(\d+)\)$`)+ valueTextRichBuiltinStylePattern = regexp.MustCompile(+ `^var\(--b3-inline-builtin-(error|warning|info|success)-(color|background-color),\s*` ++ `var\(--b3-card-(error|warning|info|success)-(color|background)\)\)$`,+ )+ valueTextRichCustomColorPattern = regexp.MustCompile(+ `^var\(--b3-inline-style-([0-9]{14}-[a-z0-9]{7})-color,\s*(#[0-9A-Fa-f]{6})\)$`,+ )+ valueTextRichCustomBackgroundPattern = regexp.MustCompile(+ `^var\(--b3-inline-style-([0-9]{14}-[a-z0-9]{7})-background-color,\s*(#[0-9A-Fa-f]{6})\)$`,+ )+ valueTextRichFontSizePXPattern = regexp.MustCompile(`^(\d+)(?:\.0{1,2})?px$`)+ valueTextRichFontSizeEMPattern = regexp.MustCompile(`^(?:(\d+)(?:\.(\d{1,2}))?|\.(\d{1,2}))em$`)+)++// RenderValueTextRich 将经过校验的富文本语法树序列化为 SiYuan Kramdown。+func RenderValueTextRich(tree *parse.Tree) (content string, err error) {+ if err = validateValueTextRichTree(tree); nil != err {+ return+ }+ content, _, err = normalizeValueTextRichTreeSource(tree)+ return+}++func valueTextRichBlockDOM2Kramdown(luteEngine *lute.Lute, blockDOM string) string {+ blockDOM = valueTextRichBlockDOMStructuralAttrs.ReplaceAllString(blockDOM, "")+ blockDOM, backslashSentinel, backtickSentinel := protectValueTextRichBlockDOMStyleCharacters(blockDOM)+ markdown := strings.TrimSpace(luteEngine.BlockDOM2Md(blockDOM))+ if "" != backtickSentinel {+ markdown = strings.ReplaceAll(markdown, backtickSentinel, "`")+ markdown = strings.ReplaceAll(markdown, backslashSentinel, "\")+ }+ return markdown+}++func protectValueTextRichBlockDOMStyleCharacters(blockDOM string) (ret, backslashSentinel, backtickSentinel string) {+ if !strings.ContainsAny(blockDOM, "\\`") {+ return blockDOM, "", ""+ }+ backslashSentinel = newValueTextRichBackslashSentinel(blockDOM)+ backtickSentinel = newValueTextRichBackslashSentinel(blockDOM + backslashSentinel)++ var builder strings.Builder+ remaining := blockDOM+ for {+ start := strings.Index(remaining, "<span")+ if 0 > start {+ builder.WriteString(remaining)+ break+ }+ builder.WriteString(remaining[:start])+ remaining = remaining[start:]+ end := valueTextRichBlockDOMTagEnd(remaining)+ if 0 > end {+ builder.WriteString(remaining)+ break+ }+ tag := remaining[:end+1]+ dataType, hasDataType := valueTextRichBlockDOMAttribute(tag, "data-type")+ style, hasStyle := valueTextRichBlockDOMAttribute(tag, "style")+ if hasDataType && hasStyle && containsValueTextRichDataType(dataType, "text") &&+ strings.ContainsAny(style, "\\`") {+ protectedStyle := strings.ReplaceAll(style, `\`, backslashSentinel)+ protectedStyle = strings.ReplaceAll(protectedStyle, "`", backtickSentinel)+ tag = strings.Replace(tag, `style="`+style+`"`, `style="`+protectedStyle+`"`, 1)+ }+ builder.WriteString(tag)+ remaining = remaining[end+1:]+ }+ return builder.String(), backslashSentinel, backtickSentinel+}++func valueTextRichBlockDOMTagEnd(tag string) int {+ var quote byte+ for i := len("<span"); i < len(tag); i++ {+ character := tag[i]+ if 0 != quote {+ if quote == character {+ quote = 0+ }+ continue+ }+ if '\'' == character || '"' == character {+ quote = character+ continue+ }+ if '>' == character {+ return i+ }+ }+ return -1+}++func valueTextRichBlockDOMAttribute(tag, name string) (value string, ok bool) {+ marker := " " + name + `="`+ start := strings.Index(tag, marker)+ if 0 > start {+ return "", false+ }+ start += len(marker)+ end := strings.IndexByte(tag[start:], '"')+ if 0 > end {+ return "", false+ }+ return tag[start : start+end], true+}++func containsValueTextRichDataType(dataType, expected string) bool {+ for _, typ := range strings.Fields(dataType) {+ if expected == typ {+ return true+ }+ }+ return false+}++type valueTextRichStyleEntityProtection struct {+ sentinel string+ token string+ encoded string+ decoded string+}++type valueTextRichLiteralRange struct {+ start int+ end int+}++func protectValueTextRichKramdownStyleEntities(markdown string) (ret string,+ protections []valueTextRichStyleEntityProtection, err error) {+ const marker = `</span>{:`+ if !strings.Contains(markdown, marker) {+ return markdown, nil, nil+ }+ sentinel := newValueTextRichBackslashSentinel(markdown)+ literalRanges := valueTextRichLiteralMarkdownRanges(markdown)+ literalRangeIndex := 0+ var builder strings.Builder+ cursor := 0+ for {+ start := strings.Index(markdown[cursor:], marker)+ if 0 > start {+ builder.WriteString(markdown[cursor:])+ break+ }+ start += cursor+ builder.WriteString(markdown[cursor:start])+ for literalRangeIndex < len(literalRanges) && literalRanges[literalRangeIndex].end <= start {+ literalRangeIndex+++ }+ if literalRangeIndex < len(literalRanges) && literalRanges[literalRangeIndex].start <= start {+ builder.WriteString(marker)+ cursor = start + len(marker)+ continue+ }+ ialStart := start + len("</span>")+ valueStart, valueEnd, ialEnd, ok := valueTextRichSpanIALStyleBounds(markdown[ialStart:])+ if !ok {+ return "", nil, fmt.Errorf("invalid attribute view rich text span style IAL")+ }+ valueStart += ialStart+ valueEnd += ialStart+ ialEnd += ialStart+ builder.WriteString(markdown[start:valueStart])+ style, protected := protectValueTextRichStyleEntities(markdown[valueStart:valueEnd],+ sentinel, len(protections))+ builder.WriteString(style)+ protections = append(protections, protected...)+ builder.WriteString(markdown[valueEnd:ialEnd])+ cursor = ialEnd+ }+ return builder.String(), protections, nil+}++func valueTextRichSpanIALStyleBounds(ial string) (valueStart, valueEnd, end int, ok bool) {+ if !strings.HasPrefix(ial, "{: ") && !strings.HasPrefix(ial, "{:\t") &&+ !strings.HasPrefix(ial, "{:\n") && !strings.HasPrefix(ial, "{:\r") {+ return 0, 0, 0, false+ }+ position := 2+ for position < len(ial) && isValueTextRichCSSWhitespace(ial[position]) {+ position+++ }+ nameStart := position+ for position < len(ial) && ('a' <= ial[position] && ial[position] <= 'z' || '-' == ial[position]) {+ position+++ }+ if "style" != ial[nameStart:position] {+ return 0, 0, 0, false+ }+ for position < len(ial) && isValueTextRichCSSWhitespace(ial[position]) {+ position+++ }+ if len(ial) <= position || '=' != ial[position] {+ return 0, 0, 0, false+ }+ position+++ for position < len(ial) && isValueTextRichCSSWhitespace(ial[position]) {+ position+++ }+ if len(ial) <= position || ('\'' != ial[position] && '"' != ial[position]) {+ return 0, 0, 0, false+ }+ quote := ial[position]+ valueStart = position + 1+ valueEnd = strings.IndexByte(ial[valueStart:], quote)+ if 0 > valueEnd {+ return 0, 0, 0, false+ }+ valueEnd += valueStart+ position = valueEnd + 1+ for position < len(ial) && isValueTextRichCSSWhitespace(ial[position]) {+ position+++ }+ if len(ial) <= position || '}' != ial[position] {+ return 0, 0, 0, false+ }+ return valueStart, valueEnd, position + 1, true+}++func valueTextRichLiteralMarkdownRanges(markdown string) (ret []valueTextRichLiteralRange) {+ blockRanges := valueTextRichBlockLiteralMarkdownRanges(markdown)+ cursor := 0+ for _, blockRange := range blockRanges {+ if cursor < blockRange.start {+ ret = append(ret, valueTextRichCodeSpanRanges(markdown[cursor:blockRange.start], cursor)...)+ }+ ret = append(ret, blockRange)+ cursor = blockRange.end+ }+ if cursor < len(markdown) {+ ret = append(ret, valueTextRichCodeSpanRanges(markdown[cursor:], cursor)...)+ }+ return+}++func valueTextRichBlockLiteralMarkdownRanges(markdown string) (ret []valueTextRichLiteralRange) {+ var fence byte+ var fenceLength int+ inMathBlock := false+ literalStart := -1+ for offset := 0; offset <= len(markdown); {+ end := strings.IndexByte(markdown[offset:], '\n')+ if 0 > end {+ end = len(markdown)+ } else {+ end += offset+ }+ nextLine := end+ if end < len(markdown) {+ nextLine+++ }+ line := strings.TrimSpace(stripValueTextRichMarkdownContainer(markdown[offset:end]))+ inLiteral := 0 != fence || inMathBlock+ if 0 != fence {+ if isValueTextRichClosingFence(line, fence, fenceLength) {+ fence, fenceLength = 0, 0+ }+ } else if inMathBlock {+ if "$$" == line {+ inMathBlock = false+ }+ } else if marker, length := valueTextRichOpeningFence(line); 0 != marker {+ fence, fenceLength, inLiteral = marker, length, true+ } else if "$$" == line {+ inMathBlock, inLiteral = true, true+ }+ if inLiteral {+ if 0 > literalStart {+ literalStart = offset+ }+ if 0 == fence && !inMathBlock {+ ret = append(ret, valueTextRichLiteralRange{start: literalStart, end: nextLine})+ literalStart = -1+ }+ }+ if len(markdown) == end {+ break+ }+ offset = nextLine+ }+ if 0 <= literalStart {+ ret = append(ret, valueTextRichLiteralRange{start: literalStart, end: len(markdown)})+ }+ return+}++func stripValueTextRichMarkdownContainer(line string) string {+ for {+ line = strings.TrimLeft(line, " \t")+ if strings.HasPrefix(line, ">") {+ line = strings.TrimPrefix(line, ">")+ continue+ }+ if 2 <= len(line) && ('-' == line[0] || '+' == line[0] || '*' == line[0]) &&+ (' ' == line[1] || '\t' == line[1]) {+ line = line[2:]+ continue+ }+ orderedEnd := -1+ for i := 0; i < len(line); i++ {+ if '0' <= line[i] && line[i] <= '9' {+ continue+ }+ if 0 < i && ('.' == line[i] || ')' == line[i]) && i+1 < len(line) &&+ (' ' == line[i+1] || '\t' == line[i+1]) {+ orderedEnd = i + 2+ }+ break+ }+ if 0 <= orderedEnd {+ line = line[orderedEnd:]+ continue+ }+ return line+ }+}++func valueTextRichOpeningFence(line string) (marker byte, length int) {+ if "" == line {+ return 0, 0+ }+ marker = line[0]+ if '`' != marker && '~' != marker {+ return 0, 0+ }+ for length < len(line) && marker == line[length] {+ length+++ }+ if 3 > length || ('`' == marker && strings.ContainsRune(line[length:], '`')) {+ return 0, 0+ }+ return marker, length+}++func isValueTextRichClosingFence(line string, marker byte, openingLength int) bool {+ if "" == line || marker != line[0] {+ return false+ }+ length := 0+ for length < len(line) && marker == line[length] {+ length+++ }+ return openingLength <= length && "" == strings.TrimSpace(line[length:])+}++func valueTextRichCodeSpanRanges(content string, offset int) (ret []valueTextRichLiteralRange) {+ type markerRun struct {+ start int+ end int+ length int+ }+ var runs []markerRun+ flushRuns := func() {+ nextSame := make([]int, len(runs))+ nextByLength := map[int]int{}+ for i := len(runs) - 1; 0 <= i; i-- {+ nextSame[i] = -1+ if next, ok := nextByLength[runs[i].length]; ok {+ nextSame[i] = next+ }+ nextByLength[runs[i].length] = i+ }+ for i := 0; i < len(runs); {+ close := nextSame[i]+ if 0 > close {+ i+++ continue+ }+ ret = append(ret, valueTextRichLiteralRange{+ start: offset + runs[i].start,+ end: offset + runs[close].end,+ })+ i = close + 1+ }+ runs = nil+ }++ paragraphBreaks := valueTextRichParagraphBreakRanges(content)+ paragraphBreakIndex := 0+ backslashes := 0+ for index := 0; index < len(content); {+ for paragraphBreakIndex < len(paragraphBreaks) && paragraphBreaks[paragraphBreakIndex].end <= index {+ paragraphBreakIndex+++ }+ var paragraphBreak *valueTextRichLiteralRange+ if paragraphBreakIndex < len(paragraphBreaks) {+ paragraphBreak = ¶graphBreaks[paragraphBreakIndex]+ if paragraphBreak.start <= index {+ flushRuns()+ index = paragraphBreak.end+ backslashes = 0+ continue+ }+ }+ limit := len(content)+ if nil != paragraphBreak {+ limit = paragraphBreak.start+ }+ if '<' == content[index] {+ if end := valueTextRichQuotedDelimiterEnd(content, index+1, limit, '>'); 0 <= end {+ index = end + 1+ backslashes = 0+ continue+ }+ } else if strings.HasPrefix(content[index:], "{:") {+ if end := valueTextRichQuotedDelimiterEnd(content, index+2, limit, '}'); 0 <= end {+ index = end + 1+ backslashes = 0+ continue+ }+ }+ if '\\' == content[index] {+ backslashes+++ index+++ continue+ }+ if '`' != content[index] {+ backslashes = 0+ index+++ continue+ }+ length := valueTextRichMarkerRunLength(content, index, '`')+ start := index+ if 1 == backslashes%2 {+ start+++ length--+ }+ if 0 < length {+ runs = append(runs, markerRun{start: start, end: start + length, length: length})+ }+ index += valueTextRichMarkerRunLength(content, index, '`')+ backslashes = 0+ }+ flushRuns()+ return+}++func valueTextRichParagraphBreakRanges(content string) (ret []valueTextRichLiteralRange) {+ for cursor := 0; cursor < len(content); {+ lineEnd := strings.IndexByte(content[cursor:], '\n')+ if 0 > lineEnd {+ break+ }+ lineEnd += cursor+ start := lineEnd+ if 0 < start && '\r' == content[start-1] {+ start--+ }+ next := lineEnd + 1+ for next < len(content) && (' ' == content[next] || '\t' == content[next]) {+ next+++ }+ end := -1+ if len(content) == next {+ end = next+ } else if '\n' == content[next] {+ end = next + 1+ } else if '\r' == content[next] && next+1 < len(content) && '\n' == content[next+1] {+ end = next + 2+ }+ if 0 <= end {+ ret = append(ret, valueTextRichLiteralRange{start: start, end: end})+ cursor = end+ continue+ }+ cursor = lineEnd + 1+ }+ return+}++func valueTextRichQuotedDelimiterEnd(content string, start, limit int, delimiter byte) int {+ var quote byte+ escaped := false+ for i := start; i < limit; i++ {+ character := content[i]+ if escaped {+ escaped = false+ continue+ }+ if 0 != quote {+ if '\\' == character {+ escaped = true+ } else if quote == character {+ quote = 0+ }+ continue+ }+ if '\'' == character || '"' == character {+ quote = character+ continue+ }+ if delimiter == character {+ return i+ }+ }+ return -1+}++func valueTextRichMarkerRunLength(line string, start int, marker byte) int {+ length := 0+ for start+length < len(line) && marker == line[start+length] {+ length+++ }+ return length+}++func protectValueTextRichStyleEntities(style, sentinel string, offset int) (ret string,+ protections []valueTextRichStyleEntityProtection) {+ var builder strings.Builder+ remaining := style+ for {+ start := strings.IndexAny(remaining, "&`")+ if 0 > start {+ builder.WriteString(remaining)+ break+ }+ builder.WriteString(remaining[:start])+ remaining = remaining[start:]+ if '`' == remaining[0] {+ token := sentinel + strconv.Itoa(offset+len(protections)) + "\ue002"+ builder.WriteString(token)+ protections = append(protections, valueTextRichStyleEntityProtection{+ sentinel: sentinel, token: token, encoded: "`", decoded: "`",+ })+ remaining = remaining[1:]+ continue+ }+ end := strings.IndexByte(remaining, ';')+ if 0 > end {+ builder.WriteByte(remaining[0])+ remaining = remaining[1:]+ continue+ }+ encoded := remaining[:end+1]+ decoded := html.UnescapeString(encoded)+ if encoded == decoded {+ builder.WriteByte(remaining[0])+ remaining = remaining[1:]+ continue+ }+ token := sentinel + strconv.Itoa(offset+len(protections)) + "\ue002"+ builder.WriteString(token)+ protections = append(protections, valueTextRichStyleEntityProtection{+ sentinel: sentinel, token: token, encoded: encoded, decoded: decoded,+ })+ remaining = remaining[end+1:]+ }+ return builder.String(), protections+}++func restoreValueTextRichTreeStyleEntities(tree *parse.Tree,+ protections []valueTextRichStyleEntityProtection) (err error) {+ if 1 > len(protections) {+ return+ }+ sentinel := protections[0].sentinel+ stylePairs := make([]string, 0, len(protections)*2)+ literalPairs := make([]string, 0, len(protections)*2)+ textMarkCodePairs := make([]string, 0, len(protections)*2)+ textMarkInlineMathPairs := make([]string, 0, len(protections)*2)+ tokenIndexes := make(map[string]int, len(protections))+ restored := make([]bool, len(protections))+ for i, protection := range protections {+ if sentinel != protection.sentinel {+ return fmt.Errorf("inconsistent attribute view rich text style entity sentinel")+ }+ tokenIndexes[protection.token] = i+ stylePairs = append(stylePairs, protection.token, protection.decoded)+ literalPairs = append(literalPairs, protection.token, protection.encoded)+ encoded := strings.ReplaceAll(protection.encoded, "&", "&")+ textMarkCodePairs = append(textMarkCodePairs, protection.token, encoded)+ textMarkInlineMathPairs = append(textMarkInlineMathPairs, protection.token,+ strings.ReplaceAll(encoded, "&", "&"))+ }+ styleReplacer := strings.NewReplacer(stylePairs...)+ literalReplacer := strings.NewReplacer(literalPairs...)+ textMarkCodeReplacer := strings.NewReplacer(textMarkCodePairs...)+ textMarkInlineMathReplacer := strings.NewReplacer(textMarkInlineMathPairs...)++ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if !entering {+ return ast.WalkContinue+ }+ style := node.IALAttr("style")+ styleProtected := strings.Contains(style, sentinel)+ textProtected := ast.NodeTextMark == node.Type && strings.Contains(node.TextMarkTextContent, sentinel)+ inlineMathProtected := ast.NodeTextMark == node.Type &&+ strings.Contains(node.TextMarkInlineMathContent, sentinel)+ tokens := string(node.Tokens)+ tokensProtected := strings.Contains(tokens, sentinel)+ if styleProtected {+ if !node.IsTextMarkType("text") {+ err = fmt.Errorf("encoded style entity is not attached to an attribute view rich text span")+ return ast.WalkStop+ }+ if textProtected || inlineMathProtected || tokensProtected ||+ !markValueTextRichStyleProtections(style, sentinel, tokenIndexes, restored) {+ err = fmt.Errorf("invalid encoded style entity in attribute view rich text span")+ return ast.WalkStop+ }+ style = styleReplacer.Replace(style)+ node.SetIALAttr("style", style)+ if nil != node.Next && ast.NodeKramdownSpanIAL == node.Next.Type {+ node.Next.Tokens = parse.IAL2Tokens(node.KramdownIAL)+ }+ return ast.WalkContinue+ }+ if textProtected || inlineMathProtected {+ if !node.IsTextMarkType("code") && !node.IsTextMarkType("inline-math") {+ err = fmt.Errorf("invalid encoded style entity in attribute view rich text mark [%s]", node.TextMarkType)+ return ast.WalkStop+ }+ if tokensProtected || textProtected &&+ !markValueTextRichStyleProtections(node.TextMarkTextContent, sentinel, tokenIndexes, restored) ||+ inlineMathProtected &&+ !markValueTextRichStyleProtections(node.TextMarkInlineMathContent, sentinel, tokenIndexes, restored) {+ err = fmt.Errorf("invalid encoded style entity in attribute view rich text mark [%s]", node.TextMarkType)+ return ast.WalkStop+ }+ node.TextMarkTextContent = textMarkCodeReplacer.Replace(node.TextMarkTextContent)+ node.TextMarkInlineMathContent = textMarkInlineMathReplacer.Replace(node.TextMarkInlineMathContent)+ return ast.WalkContinue+ }+ if !tokensProtected {+ return ast.WalkContinue+ }+ switch node.Type {+ case ast.NodeCodeBlockCode, ast.NodeMathBlockContent, ast.NodeCodeSpanContent, ast.NodeInlineMathContent:+ if !markValueTextRichStyleProtections(tokens, sentinel, tokenIndexes, restored) {+ err = fmt.Errorf("invalid encoded style entity in attribute view rich text node [%s]", node.Type.String())+ return ast.WalkStop+ }+ node.Tokens = []byte(literalReplacer.Replace(tokens))+ default:+ err = fmt.Errorf("invalid encoded style entity in attribute view rich text node [%s]", node.Type.String())+ return ast.WalkStop+ }+ return ast.WalkContinue+ })+ if nil != err {+ return+ }+ for _, found := range restored {+ if !found {+ return fmt.Errorf("attribute view rich text style entity was not restored")+ }+ }+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if entering && valueTextRichNodeContainsSentinel(node, sentinel) {+ err = fmt.Errorf("attribute view rich text style entity sentinel was not removed from node [%s]",+ node.Type.String())+ return ast.WalkStop+ }+ return ast.WalkContinue+ })+ return+}++func valueTextRichNodeContainsSentinel(node *ast.Node, sentinel string) bool {+ values := []string{+ node.ID, node.Spec, node.Data, string(node.Tokens), string(node.CodeBlockOpenFence),+ string(node.CodeBlockInfo), string(node.CodeBlockCloseFence), string(node.LinkRefLabel),+ string(node.FootnotesRefLabel), node.FootnotesRefId, string(node.HtmlEntityTokens),+ node.TextMarkType, node.TextMarkAHref, node.TextMarkATitle, node.TextMarkInlineMathContent,+ node.TextMarkInlineMemoContent, node.TextMarkBlockRefID, node.TextMarkBlockRefSubtype,+ node.TextMarkFileAnnotationRefID, node.TextMarkFlashcardOcclusionID, node.TextMarkTextContent,+ }+ for _, value := range values {+ if strings.Contains(value, sentinel) {+ return true+ }+ }+ for _, attr := range node.KramdownIAL {+ for _, value := range attr {+ if strings.Contains(value, sentinel) {+ return true+ }+ }+ }+ for name, value := range node.Properties {+ if strings.Contains(name, sentinel) || strings.Contains(value, sentinel) {+ return true+ }+ }+ return false+}++func markValueTextRichStyleProtections(value, sentinel string, tokenIndexes map[string]int, restored []bool) bool {+ const suffix = "\ue002"+ for cursor := 0; cursor < len(value); {+ start := strings.Index(value[cursor:], sentinel)+ if 0 > start {+ return true+ }+ start += cursor+ end := strings.Index(value[start+len(sentinel):], suffix)+ if 0 > end {+ return false+ }+ end += start + len(sentinel) + len(suffix)+ index, ok := tokenIndexes[value[start:end]]+ if !ok {+ return false+ }+ restored[index] = true+ cursor = end+ }+ return true+}++func newValueTextRichBackslashSentinel(content string) string {+ const (+ prefix = "\ue000siyuan-av-rich-text-backslash"+ suffix = "\ue001"+ )+ maxSuffixes := 0+ for cursor := 0; cursor < len(content); {+ start := strings.Index(content[cursor:], prefix)+ if 0 > start {+ break+ }+ start += cursor + len(prefix)+ suffixes := 0+ for strings.HasPrefix(content[start:], suffix) {+ suffixes+++ start += len(suffix)+ }+ if maxSuffixes < suffixes {+ maxSuffixes = suffixes+ }+ cursor = start+ }+ return prefix + strings.Repeat(suffix, maxSuffixes+1)+}++// NormalizeValueTextRich 校验并将文本字段的富文本源规范化为 SiYuan Kramdown。+func NormalizeValueTextRich(rich *ValueTextRich) (tree *parse.Tree, err error) {+ _, tree, err = parseValueTextRich(rich)+ if nil != err || nil == rich {+ return tree, err+ }+ var normalized string+ if normalized, tree, err = normalizeValueTextRichTreeSource(tree); nil != err {+ return nil, err+ }+ rich.Content = normalized+ return tree, nil+}++func normalizeValueTextRichTreeSource(tree *parse.Tree) (content string, normalizedTree *parse.Tree, err error) {+ normalizedTree = tree+ previous := ""+ for iteration := 0; iteration < 4; iteration++ {+ if err = normalizeValueTextRichTreeStyles(normalizedTree); nil != err {+ return "", nil, err+ }+ luteEngine := newValueTextRichLute()+ blockDOM := luteEngine.Tree2BlockDOM(normalizedTree, luteEngine.RenderOptions, luteEngine.ParseOptions)+ content = valueTextRichBlockDOM2Kramdown(luteEngine, blockDOM)+ if 0 < iteration && previous == content {+ return content, normalizedTree, nil+ }+ previous = content+ candidate := &ValueTextRich{+ Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown, Content: content,+ }+ if _, normalizedTree, err = parseValueTextRich(candidate); nil != err {+ return "", nil, err+ }+ }+ return "", nil, fmt.Errorf("attribute view rich text normalization did not converge")+}++// NormalizeRichContent 校验富文本载荷,并根据富文本源刷新纯文本投影。+func (value *ValueText) NormalizeRichContent() (err error) {+ if !value.IsRich() {+ return+ }+ tree, err := NormalizeValueTextRich(value.Rich)+ if nil != err {+ return err+ }+ value.Content = valueTextRichPlainContent(tree)+ return+}++func valueTextRichPlainContent(tree *parse.Tree) string {+ if nil == tree || nil == tree.Root {+ return ""+ }+ var blocks []string+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if !entering {+ return ast.WalkContinue+ }+ switch node.Type {+ case ast.NodeParagraph, ast.NodeCodeBlock, ast.NodeMathBlock:+ blocks = append(blocks, strings.TrimRight(node.Content(), "\n"))+ return ast.WalkSkipChildren+ }+ return ast.WalkContinue+ })+ if 0 == len(blocks) {+ return tree.Root.Content()+ }+ return strings.TrimRight(strings.Join(blocks, "\n"), "\n")}type ValueNumber struct {diff --git a/kernel/av/value_text_test.go b/kernel/av/value_text_test.gonew file mode 100644index 0000000000..3340fcb452--- /dev/null+++ b/kernel/av/value_text_test.go@@ -0,0 +1,1052 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package av++import (+ "encoding/json"+ "strings"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/editor"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestValueTextPlainJSONCompatibility(t *testing.T) {+ const content = "**literal** <tag> ((20240101000000-abcdefg))\nnext"+ value := &ValueText{}+ if err := json.Unmarshal([]byte(`{"content":"**literal** <tag> ((20240101000000-abcdefg))\nnext"}`), value); nil != err {+ t.Fatal(err)+ }+ if value.IsRich() || content != value.Content {+ t.Fatalf("plain text changed during decode: %+v", value)+ }++ data, err := json.Marshal(value)+ if nil != err {+ t.Fatal(err)+ }+ if strings.Contains(string(data), `"rich"`) {+ t.Fatalf("plain text unexpectedly persisted rich payload: %s", data)+ }+}++func TestValueTextNormalizeRichContent(t *testing.T) {+ value := &ValueText{+ Content: "untrusted projection",+ Rich: &ValueTextRich{+ Spec: ValueTextRichSpec,+ Format: ValueTextRichFormatKramdown,+ Content: "**Bold** and [link](https://example.com)",+ },+ }+ if err := value.NormalizeRichContent(); nil != err {+ t.Fatal(err)+ }+ if "Bold and link" != value.Content {+ t.Fatalf("unexpected plain text projection: %q", value.Content)+ }++ data, err := json.Marshal(value)+ if nil != err {+ t.Fatal(err)+ }+ decoded := &ValueText{}+ if err = json.Unmarshal(data, decoded); nil != err {+ t.Fatal(err)+ }+ if nil == decoded.Rich || value.Content != decoded.Content || value.Rich.Content != decoded.Rich.Content {+ t.Fatalf("rich text did not survive JSON round trip: %+v", decoded)+ }+}++func TestValueTextRichMultiBlockPlainProjection(t *testing.T) {+ value := &Value{+ Type: KeyTypeText,+ Text: &ValueText{Rich: &ValueTextRich{+ Spec: ValueTextRichSpec,+ Format: ValueTextRichFormatKramdown,+ Content: "first\n\nsecond",+ }},+ }+ if err := value.Text.NormalizeRichContent(); nil != err {+ t.Fatal(err)+ }+ if "first\nsecond" != value.Text.Content {+ t.Fatalf("unexpected multi-block projection: %q", value.Text.Content)+ }+ if "first\nsecond" != value.String(false) {+ t.Fatalf("text consumers did not receive the plain projection: %q", value.String(false))+ }++ tests := []struct {+ name string+ source string+ expected string+ }{+ {"paragraphs", "first\n\nsecond", "first\nsecond"},+ {"list", "- first\n- second", "first\nsecond"},+ {"task list", "- [ ] todo\n- [x] done", "todo\ndone"},+ {"blockquote", "> first\n>\n> second", "first\nsecond"},+ {"code block", "```go\nfirst\nsecond\n```", "first\nsecond"},+ {"math block", "$$\nfirst\nsecond\n$$", "first\nsecond"},+ }+ for _, test := range tests {+ text := &ValueText{Rich: &ValueTextRich{+ Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown, Content: test.source,+ }}+ if err := text.NormalizeRichContent(); nil != err {+ t.Fatalf("normalize %s failed: %s", test.name, err)+ }+ if test.expected != text.Content {+ t.Fatalf("unexpected %s projection: want %q, got %q", test.name, test.expected, text.Content)+ }+ }+}++func TestValueTextRichASTWhitelist(t *testing.T) {+ allowed := []string{+ "",+ "plain **strong** *emphasis* ~~strike~~ ==mark== `code` $x$ [link](https://example.com) " ++ "((20240101000000-abcdefg \"reference\"))",+ "<u>underline</u>",+ "<kbd>Ctrl</kbd>",+ "^superscript^ ~subscript~ #tag#",+ "<span data-type=\"text\" style=\"color: var(--b3-font-color8); background-color: var(--b3-font-background8);\">styled</span>",+ "<span data-type=\"inline-memo\" data-inline-memo-content=\"memo\">annotated</span>",+ "<<assets/document-20240101000000-abcdefg.pdf/20240101000001-bcdefgh \"annotation\">>",+ "- first\n- [ ] task\n - nested",+ "> quote",+ "```go\nfmt.Println(1)\n```",+ "```javascript\nconsole.log(1)\n```",+ "$$\nx^2\n$$",+ }+ for _, content := range allowed {+ rich := &ValueTextRich{Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown, Content: content}+ if _, err := NormalizeValueTextRich(rich); nil != err {+ t.Fatalf("allowed rich text was rejected, content=%q: %s", content, err)+ }+ normalized := rich.Content+ if _, err := NormalizeValueTextRich(rich); nil != err {+ t.Fatalf("normalized rich text was rejected, content=%q: %s", normalized, err)+ }+ if normalized != rich.Content {+ t.Fatalf("rich text normalization is not idempotent: %q != %q", normalized, rich.Content)+ }+ if strings.Contains(rich.Content, "{: id=") {+ t.Fatalf("normalized rich text leaked generated block attributes: %q", rich.Content)+ }+ }++ rejected := []string{+ "# heading",+ "",+ "| a | b |\n| --- | --- |\n| 1 | 2 |",+ "<div>HTML</div>",+ "{{ SELECT * FROM blocks }}",+ "<div data-type=\"NodeAttributeView\" data-av-id=\"20240101000000-abcdefg\"></div>",+ "<iframe data-type=\"NodeWidget\" data-subtype=\"widget\"></iframe>",+ "<iframe src=\"https://example.com\"></iframe>",+ "<audio src=\"assets/audio.mp3\"></audio>",+ "<video src=\"assets/video.mp4\"></video>",+ "paragraph\n{: style=\"color: red\"}",+ `<span data-type="text">styled</span>{: style="font-family: 'A\B';`,+ `<span data-type="text">styled</span>{: style="color: var(--b3-font-color8);" title="x"}`,+ }+ for _, content := range rejected {+ rich := &ValueTextRich{Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown, Content: content}+ if _, err := NormalizeValueTextRich(rich); nil == err {+ t.Fatalf("unsupported rich text was accepted: %q", content)+ }+ }+}++func TestValueTextRichEmojiAliasRemainsLiteral(t *testing.T) {+ rich := &ValueTextRich{+ Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown, Content: ":siyuan: 😀",+ }+ tree, err := NormalizeValueTextRich(rich)+ if nil != err {+ t.Fatal(err)+ }+ if ":siyuan: 😀" != rich.Content || ":siyuan: 😀" != tree.Root.Content() {+ t.Fatalf("emoji alias was not kept as literal text: source=%q plain=%q", rich.Content, tree.Root.Content())+ }+ before := rich.Content+ if _, err = NormalizeValueTextRich(rich); nil != err || before != rich.Content {+ t.Fatalf("emoji alias normalization is not stable, before=%q, after=%q, err=%v", before, rich.Content, err)+ }+}++func TestValueTextRichRejectsExecutableCodeFences(t *testing.T) {+ languages := []string{"abc", "echarts", "flowchart", "graphviz", "infographic", "mermaid", "mindmap", "plantuml"}+ for _, language := range languages {+ rich := &ValueTextRich{+ Spec: ValueTextRichSpec,+ Format: ValueTextRichFormatKramdown,+ Content: "```" + language + "\ncontent\n```",+ }+ if _, err := NormalizeValueTextRich(rich); nil == err {+ t.Fatalf("executable code fence %q was accepted", language)+ }+ }++ for _, info := range []string{"MERMAID", "GraphViz options"} {+ rich := &ValueTextRich{+ Spec: ValueTextRichSpec,+ Format: ValueTextRichFormatKramdown,+ Content: "```" + info + "\ncontent\n```",+ }+ if _, err := NormalizeValueTextRich(rich); nil == err {+ t.Fatalf("executable code fence info %q was accepted", info)+ }+ }+}++func TestValueTextRichTextMarkReferenceValidation(t *testing.T) {+ const (+ blockID = "20240101000000-abcdefg"+ annotationID = "20240101000001-bcdefgh"+ annotation = "assets/document-20240101000000-abcdefg.pdf/" + annotationID+ )+ allowed := []string{+ `<span data-type="block-ref" data-id="` + blockID + `" data-subtype="d">dynamic</span>`,+ `<span data-type="block-ref" data-id="` + blockID + `" data-subtype="s">static</span>`,+ `<span data-type="block-ref" data-id="` + blockID + `">default static</span>`,+ `<span data-type="block-ref text" data-id="` + blockID + `" data-subtype="d" ` ++ `style="color: var(--b3-font-color8);">styled dynamic</span>`,+ `<span data-type="file-annotation-ref" data-id="` + annotation + `">annotation</span>`,+ }+ for _, content := range allowed {+ rich := &ValueTextRich{Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown, Content: content}+ if _, err := NormalizeValueTextRich(rich); nil != err {+ t.Fatalf("valid text mark reference was rejected, content=%q: %s", content, err)+ }+ }++ rejected := []string{+ `<span data-type="block-ref" data-subtype="d">missing ID</span>`,+ `<span data-type="block-ref" data-id="invalid" data-subtype="d">invalid ID</span>`,+ `<span data-type="block-ref" data-id="` + blockID + `" data-subtype="x">invalid subtype</span>`,+ `<span data-type="block-ref file-annotation-ref" data-id="` + blockID ++ `" data-subtype="d">mixed references</span>`,+ `<span data-type="file-annotation-ref" data-id="javascript:alert(1)">protocol</span>`,+ `<span data-type="file-annotation-ref" data-id="assets/document-` + blockID ++ `.png/` + annotationID + `">not PDF</span>`,+ `<span data-type="file-annotation-ref" data-id="assets/document-invalid.pdf/` ++ annotationID + `">invalid file ID</span>`,+ `<span data-type="file-annotation-ref" data-id="assets/document-` + blockID ++ `.pdf/invalid">invalid annotation ID</span>`,+ `<span data-type="file-annotation-ref" data-id="` + annotation + `?box=` + blockID ++ `">query</span>`,+ }+ for _, content := range rejected {+ rich := &ValueTextRich{Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown, Content: content}+ if _, err := NormalizeValueTextRich(rich); nil == err {+ t.Fatalf("invalid text mark reference was accepted: %q", content)+ }+ }+}++func TestValueTextRichTextMarkStyleIALWhitelist(t *testing.T) {+ const (+ fontFamily = "var(--b3-font-family-emoji-reset), 'KaiTi', var(--b3-font-family-editor), " ++ "var(--b3-font-family)"+ complexFontFamily = `var(--b3-font-family-emoji-reset), 'Semi; \'Quoted\' > \\ 字体', ` ++ `var(--b3-font-family-editor), var(--b3-font-family)`+ backtickFontFamily = "var(--b3-font-family-emoji-reset), 'A`B` Semi; \\'Quoted\\' > \\\\ 字体', " ++ "var(--b3-font-family-editor), var(--b3-font-family)"+ hollow = "-webkit-text-stroke: 0.2px var(--b3-theme-on-background); " ++ "-webkit-text-fill-color: transparent;"+ shadow = "1px 1px var(--b3-theme-surface-lighter), 2px 2px var(--b3-theme-surface-lighter), " ++ "3px 3px var(--b3-theme-surface-lighter), 4px 4px var(--b3-theme-surface-lighter)"+ )+ allowed := []struct {+ content string+ style string+ }{+ {`<span data-type="text" style="color: var(--b3-font-color1);">foreground</span>`,+ "color: var(--b3-font-color1);"},+ {`<span data-type="text" style="color: var(--b3-font-color01);">normalized foreground</span>`,+ "color: var(--b3-font-color1);"},+ {`<span data-type="text" style="background-color: var(--b3-font-background13);">background</span>`,+ "background-color: var(--b3-font-background13);"},+ {`<span data-type="text strong" style="color: var(--b3-inline-builtin-error-color,var(--b3-card-error-color)); ` ++ `background-color: var(--b3-inline-builtin-warning-background-color, var(--b3-card-warning-background));">builtin</span>`,+ "color: var(--b3-inline-builtin-error-color, var(--b3-card-error-color)); " ++ "background-color: var(--b3-inline-builtin-warning-background-color, var(--b3-card-warning-background));"},+ {`<span data-type="text" style="color: var(--b3-inline-style-20240101000000-abcdefg-color,#A1b2C3); ` ++ `background-color: var(--b3-inline-style-20240101000000-abcdefg-background-color, #d4E5f6);">custom</span>`,+ "color: var(--b3-inline-style-20240101000000-abcdefg-color, #a1b2c3); " ++ "background-color: var(--b3-inline-style-20240101000000-abcdefg-background-color, #d4e5f6);"},+ {`<span data-type="text" style="font-size: 9.00px;">minimum pixels</span>`, "font-size: 9px;"},+ {`<span data-type="text" style="font-size: 72px;">maximum pixels</span>`, "font-size: 72px;"},+ {`<span data-type="text" style="font-size: .56em;">minimum em</span>`, "font-size: 0.56em;"},+ {`<span data-type="text" style="font-size: 4.50em;">maximum em</span>`, "font-size: 4.5em;"},+ {`<span data-type="text">single quote IAL</span>{: style='font-size: 1.00em;'}`,+ "font-size: 1em;"},+ {`<span data-type="text" style="font-family: ` + fontFamily + `;">font</span>`,+ "font-family: " + fontFamily + ";"},+ {`<span data-type="text" style="font-family: var(--b3-font-family-emoji-reset), ` ++ `"Double Font", var(--b3-font-family-editor), var(--b3-font-family);">double quoted font</span>`,+ "font-family: var(--b3-font-family-emoji-reset), 'Double Font', " ++ "var(--b3-font-family-editor), var(--b3-font-family);"},+ {`<span data-type="text" style="font-family: ` + complexFontFamily + `; font-size: 1em;">complex font</span>`,+ "font-size: 1em; font-family: " + complexFontFamily + ";"},+ {`<span data-type="text" style="font-family: ` + backtickFontFamily + `;">backtick font</span>`,+ "font-family: " + backtickFontFamily + ";"},+ {`<span data-type="text" style="unicode-bidi: isolate; direction: rtl;">right to left</span>`,+ "direction: rtl; unicode-bidi: isolate;"},+ {`<span data-type="text" style="-webkit-text-fill-color: transparent; ` ++ `-webkit-text-stroke: 0.2px var(--b3-theme-on-background);">hollow</span>`, hollow},+ {`<span data-type="text" style="text-shadow: ` + shadow + `;">shadow</span>`,+ "text-shadow: " + shadow + ";"},+ {`<span data-type="text" style="unicode-bidi:isolate; font-size: 12.0px; ` ++ `color:var(--b3-font-color8); direction:ltr;">combined</span>`,+ "color: var(--b3-font-color8); font-size: 12px; direction: ltr; unicode-bidi: isolate;"},+ }+ maximumFontFamily := "var(--b3-font-family-emoji-reset), '" + strings.Repeat("字", 256) ++ "', var(--b3-font-family-editor), var(--b3-font-family)"+ allowed = append(allowed, struct {+ content string+ style string+ }{`<span data-type="text" style="font-family: ` + maximumFontFamily + `;">maximum font</span>`,+ "font-family: " + maximumFontFamily + ";"})+ for _, test := range allowed {+ rich := &ValueTextRich{Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown, Content: test.content}+ tree, err := NormalizeValueTextRich(rich)+ if nil != err {+ t.Fatalf("safe text mark style was rejected, content=%q: %s", test.content, err)+ }+ var style string+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if entering && ast.NodeTextMark == node.Type && 0 < len(node.KramdownIAL) {+ style = node.IALAttr("style")+ return ast.WalkStop+ }+ return ast.WalkContinue+ })+ if test.style != style {+ t.Fatalf("style was not canonicalized\nwant: %q\n got: %q\nrich: %q", test.style, style, rich.Content)+ }+ if strings.Contains(test.content, "complex font") && !strings.Contains(rich.Content, "\") {+ t.Fatalf("CSS backslashes were not encoded in the persisted span IAL: %q", rich.Content)+ }+ if strings.Contains(test.content, "backtick font") && !strings.Contains(rich.Content, "`") {+ t.Fatalf("CSS backticks were not encoded in the persisted span IAL: %q", rich.Content)+ }+ before := rich.Content+ if _, err = NormalizeValueTextRich(rich); nil != err || before != rich.Content {+ t.Fatalf("canonical style is not stable, before=%q, after=%q, err=%v", before, rich.Content, err)+ }+ }++ rejected := []string{+ `<span data-type="text" style="color: #112233;">raw color</span>`,+ `<span data-type="text" style="color: var(--theme-color);">arbitrary variable</span>`,+ `<span data-type="text" style="color: var(--b3-font-color0);">zero index</span>`,+ `<span data-type="text" style="color: var(--b3-font-color14);">out of range</span>`,+ `<span data-type="text" style="color: var(--b3-font-background8);">wrong variable family</span>`,+ `<span data-type="text" style="font-size: 8px;">small pixels</span>`,+ `<span data-type="text" style="font-size: 73px;">large pixels</span>`,+ `<span data-type="text" style="font-size: 12.5px;">fractional pixels</span>`,+ `<span data-type="text" style="font-size: 0.55em;">small em</span>`,+ `<span data-type="text" style="font-size: 4.51em;">large em</span>`,+ `<span data-type="text" style="font-size: 1.234em;">precise em</span>`,+ `<span data-type="text" style="font-family: Arial;">unwrapped font</span>`,+ `<span data-type="text" style="font-family: var(--b3-font-family-emoji-reset), 'KaiTi', ` ++ `var(--b3-font-family-editor);">incomplete font fallback</span>`,+ `<span data-type="text" style="font-family: var(--b3-font-family-emoji-reset), ` ++ `'unterminated, var(--b3-font-family-editor), var(--b3-font-family);">unterminated font</span>`,+ `<span data-type="text" style="font-family: var(--b3-font-family-emoji-reset), 'inherit', ` ++ `var(--b3-font-family-editor), var(--b3-font-family);">global font</span>`,+ `<span data-type="text" style="font-family: var(--b3-font-family-emoji-reset), 'var(--evil)', ` ++ `var(--b3-font-family-editor), var(--b3-font-family);">variable font</span>`,+ `<span data-type="text" style="font-family: var(--b3-font-family-emoji-reset), 'Emojis Reset', ` ++ `var(--b3-font-family-editor), var(--b3-font-family);">reserved font</span>`,+ `<span data-type="text" style="direction: rtl;">unpaired direction</span>`,+ `<span data-type="text" style="unicode-bidi: isolate;">unpaired bidi</span>`,+ `<span data-type="text" style="direction: auto; unicode-bidi: isolate;">automatic direction</span>`,+ `<span data-type="text" style="direction: rtl; unicode-bidi: embed;">unsafe bidi</span>`,+ `<span data-type="text" style="-webkit-text-stroke: 0.2px var(--b3-theme-on-background);">unpaired stroke</span>`,+ `<span data-type="text" style="-webkit-text-stroke: 0.3px var(--b3-theme-on-background); ` ++ `-webkit-text-fill-color: transparent;">wrong stroke</span>`,+ `<span data-type="text" style="text-shadow: 1px 1px var(--b3-theme-surface-lighter);">wrong shadow</span>`,+ `<span data-type="text" style="--b3-parent-background: #fff;">parent background</span>`,+ `<span data-type="text" style="font-weight: bold;">custom CSS</span>`,+ `<span data-type="strong" style="color: var(--b3-font-color8);">style without text type</span>`,+ `<span data-type="text" style="color: var(--b3-font-color8); background-image: url(javascript:alert(1));">URL</span>`,+ `<span data-type="text" style="color: var(--b3-font-color8); color: var(--b3-font-color9);">duplicate</span>`,+ `<span data-type="text" style="color: var(--b3-inline-builtin-danger-color, var(--b3-card-danger-color));">unknown builtin</span>`,+ `<span data-type="text" style="color: var(--b3-inline-style-invalid-color, #112233);">invalid ID</span>`,+ `<span data-type="text" style="color: var(--b3-inline-style-20240101000000-abcdefg-color, url(javascript:alert(1)));">custom URL</span>`,+ `<span data-type="text" custom-foo="bar" style="color: var(--b3-font-color8);">custom attribute</span>`,+ }+ longFamily := strings.Repeat("字", 257)+ rejected = append(rejected, `<span data-type="text" style="font-family: var(--b3-font-family-emoji-reset), '`++ longFamily+`', var(--b3-font-family-editor), var(--b3-font-family);">long font</span>`)+ for _, content := range rejected {+ rich := &ValueTextRich{Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown, Content: content}+ if _, err := NormalizeValueTextRich(rich); nil == err {+ t.Fatalf("unsafe text mark style was accepted: %q", content)+ }+ }++ tree, err := ParseValueTextRich(&ValueTextRich{+ Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown, Content: "**strong**",+ })+ if nil != err {+ t.Fatal(err)+ }+ var paragraph *ast.Node+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if entering && ast.NodeParagraph == node.Type {+ paragraph = node+ return ast.WalkStop+ }+ return ast.WalkContinue+ })+ if nil == paragraph {+ t.Fatal("paragraph node is missing")+ }+ style := "color: var(--b3-font-color8);"+ strong := &ast.Node{Type: ast.NodeStrong, KramdownIAL: [][]string{{"style", style}}}+ paragraph.AppendChild(strong)+ strong.InsertAfter(&ast.Node{Type: ast.NodeKramdownSpanIAL, Tokens: []byte(`{: style="` + style + `"}`)})+ if err = validateValueTextRichTree(tree); nil == err {+ t.Fatal("span IAL not attached to a text mark was accepted")+ }+}++func TestValueTextRichStyleBackslashEncodingIsScoped(t *testing.T) {+ literal := `</span>{: style="font-family: 'A\B';"}`+ tests := []struct {+ name string+ content string+ preserveEntity bool+ protections int+ }{+ {"fenced code", "```\n" + literal + "\n```", true, 0},+ {"nested container fenced code", "> - ```\n> " + literal + "\n> ```", true, 0},+ {"inline code", "`" + literal + "`", true, 0},+ {"multiline inline code", "`line one\n" + literal + "\nline three`", true, 0},+ {"multiline multi-backtick code", "``line one\n" + literal + "\nline three``", true, 0},+ {"math block", "$$\n" + literal + "\n$$", true, 0},+ {"inline math", "$" + literal + "$", false, 1},+ }+ for _, test := range tests {+ protected, protections, protectErr := protectValueTextRichKramdownStyleEntities(test.content)+ if nil != protectErr || test.protections != len(protections) {+ t.Fatalf("span IAL scanner entered %s", test.name)+ }+ if 0 == test.protections && test.content != protected {+ t.Fatalf("literal %s was rewritten: %q", test.name, protected)+ }+ rich := &ValueTextRich{+ Spec: ValueTextRichSpec,+ Format: ValueTextRichFormatKramdown,+ Content: test.content,+ }+ tree, err := NormalizeValueTextRich(rich)+ if nil != err {+ t.Fatalf("normalize %s failed: %s", test.name, err)+ }+ if strings.Contains(rich.Content, "\ue000") {+ t.Fatalf("span IAL scanner sentinel leaked from %s: %q", test.name, rich.Content)+ }+ if test.preserveEntity && !strings.Contains(rich.Content, "#92;") {+ t.Fatalf("span IAL entity inside %s was not preserved literally: %q", test.name, rich.Content)+ }+ if !test.preserveEntity && !strings.Contains(rich.Content, `A\B`) {+ t.Fatalf("span IAL entity inside %s lost its math meaning: %q", test.name, rich.Content)+ }+ if "fenced code" == test.name && !strings.Contains(rich.Content, literal) {+ t.Fatalf("fenced code source was changed: %q", rich.Content)+ }+ foundStyle := false+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if entering && ast.NodeTextMark == node.Type && "" != node.IALAttr("style") {+ foundStyle = true+ return ast.WalkStop+ }+ return ast.WalkContinue+ })+ if foundStyle {+ t.Fatalf("span IAL text inside %s was interpreted as a style", test.name)+ }+ normalized := rich.Content+ if _, err = NormalizeValueTextRich(rich); nil != err || normalized != rich.Content {+ t.Fatalf("%s entity normalization is not stable, before=%q, after=%q, err=%v",+ test.name, normalized, rich.Content, err)+ }+ }+}++func TestValueTextRichStyleEntityScannerBoundaries(t *testing.T) {+ styled := `<span data-type="text">styled</span>{: style="font-family: ` ++ `var(--b3-font-family-emoji-reset), 'A\B > C', ` ++ `var(--b3-font-family-editor), var(--b3-font-family);"}`+ backtickFont := `<span data-type="text">styled</span>{: style="font-family: ` ++ `var(--b3-font-family-emoji-reset), 'A` + "`B`" + ` Semi; \'Quoted\' > 字体', ` ++ `var(--b3-font-family-editor), var(--b3-font-family);"}`+ tests := []struct {+ name string+ content string+ protections int+ reject bool+ }{+ {"styled span", styled, 2, false},+ {"backticks inside font IAL", backtickFont, 5, false},+ {"unclosed code opener", "`unclosed " + styled, 2, false},+ {"escaped code opener", `\` + "` literal " + styled, 2, false},+ {"single quoted style IAL", `<span data-type="text">styled</span>{: style='font-family: ` ++ `var(--b3-font-family-emoji-reset), "A\B", ` ++ `var(--b3-font-family-editor), var(--b3-font-family);'}`, 3, false},+ {"inline code", "`" + styled + "`", 0, false},+ {"multi-backtick code", "``" + styled + "``", 0, false},+ {"multiline inline code", "`line one\n" + styled + "\nline three`", 0, false},+ {"multiline multi-backtick code", "``line one\n" + styled + "\nline three``", 0, false},+ {"fenced code", "```\n" + styled + "\n```", 0, false},+ {"tilde fenced code", "~~~\n" + styled + "\n~~~", 0, false},+ {"blockquote fenced code", "> ```\n> " + styled + "\n> ```", 0, false},+ {"list fenced code", "- ```\n " + styled + "\n ```", 0, false},+ {"nested list blockquote fenced code", "- > ```\n > " + styled + "\n > ```", 0, false},+ {"nested ordered list fenced code", "1. - ```\n " + styled + "\n ```", 0, false},+ {"inline math", "$" + styled + "$", 2, false},+ {"math block", "$$\n" + styled + "\n$$", 0, false},+ {"CRLF fenced code", "```\r\n" + styled + "\r\n```", 0, false},+ {"missing IAL close", `<span data-type="text">styled</span>{: style="color: var(--b3-font-color8);`, 0, true},+ {"extra attr before style", `<span data-type="text">styled</span>{: title="x" ` ++ `style="color: var(--b3-font-color8);"}`, 0, true},+ {"extra attr after style", `<span data-type="text">styled</span>{: ` ++ `style="color: var(--b3-font-color8);" title="x"}`, 0, true},+ {"missing IAL whitespace", `<span data-type="text">styled</span>{:style="color: var(--b3-font-color8);"}`, 0, true},+ {"malformed fenced literal", "```\n<span data-type=\"text\">styled</span>{: style=\"unterminated\n```", 0, false},+ {"nested malformed fenced literal",+ "> - ```\n> <span data-type=\"text\">styled</span>{: style=\"unterminated\n> ```", 0, false},+ }+ for _, test := range tests {+ protected, protections, err := protectValueTextRichKramdownStyleEntities(test.content)+ if test.reject != (nil != err) {+ t.Fatalf("unexpected %s error: %v", test.name, err)+ }+ if test.reject {+ continue+ }+ if test.protections != len(protections) {+ t.Fatalf("unexpected %s protection count: want %d, got %d in %q",+ test.name, test.protections, len(protections), protected)+ }+ if 0 == test.protections && test.content != protected {+ t.Fatalf("literal %s was rewritten: %q", test.name, protected)+ }+ }+}++func TestValueTextRichStyleEntitiesInsideDollarDelimitedText(t *testing.T) {+ const expectedStyle = `font-family: var(--b3-font-family-emoji-reset), 'Semi; \'Quoted\' > \\ ` ++ `字体', var(--b3-font-family-editor), var(--b3-font-family);`+ seed := &ValueTextRich{+ Spec: ValueTextRichSpec,+ Format: ValueTextRichFormatKramdown,+ Content: `<span data-type="text" style="` + expectedStyle ++ `">styled</span>`,+ }+ if _, err := NormalizeValueTextRich(seed); nil != err {+ t.Fatal(err)+ }+ if !strings.Contains(seed.Content, "\") {+ t.Fatalf("seed style does not exercise encoded CSS: %q", seed.Content)+ }++ for _, content := range []string{"$" + seed.Content + "$", "$5 " + seed.Content + " $10"} {+ rich := &ValueTextRich{Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown, Content: content}+ tree, err := NormalizeValueTextRich(rich)+ if nil != err {+ t.Fatalf("dollar-delimited styled text was rejected, content=%q: %s", content, err)+ }+ var style string+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if entering && ast.NodeTextMark == node.Type && node.IsTextMarkType("text") {+ style = node.IALAttr("style")+ return ast.WalkStop+ }+ return ast.WalkContinue+ })+ if expectedStyle != style {+ t.Fatalf("dollar-delimited text style changed\nwant: %q\n got: %q\nrich: %q", expectedStyle, style, rich.Content)+ }+ if strings.Contains(rich.Content, "\ue000") || !strings.Contains(rich.Content, "\") {+ t.Fatalf("dollar-delimited style entity was not safely persisted: %q", rich.Content)+ }+ before := rich.Content+ if _, err = NormalizeValueTextRich(rich); nil != err || before != rich.Content {+ t.Fatalf("dollar-delimited style normalization is not stable, before=%q, after=%q, err=%v",+ before, rich.Content, err)+ }+ }+}++func TestValueTextRichStyleEntityScannerManyMarkers(t *testing.T) {+ const (+ repetitions = 1024+ styled = `<span data-type="text">styled</span>{: style="font-family: ` ++ `var(--b3-font-family-emoji-reset), 'A\\B > C', ` ++ `var(--b3-font-family-editor), var(--b3-font-family);"}`+ )+ var markdown strings.Builder+ for i := 0; i < repetitions; i++ {+ markdown.WriteString(styled)+ markdown.WriteByte('\n')+ }+ markdown.WriteString("```\n")+ for i := 0; i < repetitions; i++ {+ markdown.WriteString(styled)+ markdown.WriteByte('\n')+ }+ markdown.WriteString("```\n")+ for i := 0; i < repetitions; i++ {+ markdown.WriteByte('`')+ markdown.WriteString(styled)+ markdown.WriteString("`\n")+ }++ content := markdown.String()+ protected, protections, err := protectValueTextRichKramdownStyleEntities(content)+ if nil != err {+ t.Fatal(err)+ }+ if repetitions*3 != len(protections) {+ t.Fatalf("unexpected protection count: want %d, got %d", repetitions*3, len(protections))+ }+ if !strings.Contains(protected, protections[0].sentinel) {+ t.Fatal("style entities were not protected")+ }+ if !strings.Contains(protected, "```\n"+styled+"\n") ||+ !strings.Contains(protected, "`"+styled+"`\n") {+ t.Fatal("literal marker content was rewritten")+ }+}++func TestValueTextRichStyleSentinelLongCollisionPrefix(t *testing.T) {+ const (+ prefix = "\ue000siyuan-av-rich-text-backslash"+ suffix = "\ue001"+ repetitions = 4096+ )+ content := prefix + strings.Repeat(suffix, repetitions)+ sentinel := newValueTextRichBackslashSentinel(content)+ want := prefix + strings.Repeat(suffix, repetitions+1)+ if want != sentinel || strings.Contains(content, sentinel) {+ t.Fatalf("unexpected collision-free sentinel length: want %d bytes, got %d bytes",+ len(want), len(sentinel))+ }+}++func TestValueTextRichRestoresManyStyleEntities(t *testing.T) {+ const (+ repetitions = 128+ styled = `<span data-type="text">styled</span>{: style="font-family: ` ++ `var(--b3-font-family-emoji-reset), 'A\\B > C', ` ++ `var(--b3-font-family-editor), var(--b3-font-family);"}`+ )+ content := strings.Repeat(styled+"\n\n", repetitions)+ rich := &ValueTextRich{Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown, Content: content}+ tree, err := NormalizeValueTextRich(rich)+ if nil != err {+ t.Fatal(err)+ }+ styledMarks := 0+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if entering && ast.NodeTextMark == node.Type && node.IsTextMarkType("text") &&+ "" != node.IALAttr("style") {+ styledMarks+++ }+ return ast.WalkContinue+ })+ if repetitions != styledMarks {+ t.Fatalf("unexpected styled mark count: want %d, got %d", repetitions, styledMarks)+ }+ if strings.Contains(rich.Content, "\ue000") || !strings.Contains(rich.Content, "\") {+ t.Fatalf("style entity restoration leaked or lost its encoding")+ }+ before := rich.Content+ if _, err = NormalizeValueTextRich(rich); nil != err || before != rich.Content {+ t.Fatalf("many style entities are not stable, err=%v", err)+ }+}++func TestValueTextRichNormalizationStripsStructuralIAL(t *testing.T) {+ rich := &ValueTextRich{+ Spec: ValueTextRichSpec,+ Format: ValueTextRichFormatKramdown,+ Content: "paragraph\n{: id=\"20240101000000-abcdefg\" updated=\"20240101000000\"}",+ }+ if _, err := NormalizeValueTextRich(rich); nil != err {+ t.Fatal(err)+ }+ for _, structuralAttr := range []string{"{:", "data-node-id", "data-node-index", "updated="} {+ if strings.Contains(rich.Content, structuralAttr) {+ t.Fatalf("normalized rich text leaked structural attribute %q: %q", structuralAttr, rich.Content)+ }+ }+}++func TestValueTextRichInlineRoundTrip(t *testing.T) {+ tests := []struct {+ content string+ typ string+ nodeType ast.NodeType+ }{+ {"**strong**", "strong", ast.NodeStrong},+ {"<u>underline</u>", "u", ast.NodeUnderline},+ {"<kbd>Ctrl</kbd>", "kbd", ast.NodeKbd},+ {"^superscript^", "sup", ast.NodeSup},+ {"~subscript~", "sub", ast.NodeSub},+ {"#tag#", "tag", ast.NodeTag},+ {"<span data-type=\"text\" style=\"color: var(--b3-font-color8);\">styled</span>", "text", ast.NodeTextMark},+ {"<span data-type=\"inline-memo\" data-inline-memo-content=\"memo\">annotated</span>", "inline-memo", ast.NodeTextMark},+ {"((20240101000000-abcdefg \"reference\"))", "block-ref", ast.NodeBlockRef},+ {"<<assets/document-20240101000000-abcdefg.pdf/20240101000001-bcdefgh \"annotation\">>", "file-annotation-ref", ast.NodeFileAnnotationRef},+ }+ for _, test := range tests {+ rich := &ValueTextRich{Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown, Content: test.content}+ for pass := 0; pass < 2; pass++ {+ tree, err := ParseValueTextRich(rich)+ if nil != err {+ t.Fatalf("parse inline type %q failed: %s", test.typ, err)+ }+ found := false+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if !entering {+ return ast.WalkContinue+ }+ if ast.NodeTextMark == node.Type && node.IsTextMarkType(test.typ) ||+ ast.NodeTextMark != test.nodeType && test.nodeType == node.Type {+ found = true+ return ast.WalkStop+ }+ return ast.WalkContinue+ })+ if !found {+ var nodeTypes []string+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if entering {+ nodeTypes = append(nodeTypes, node.Type.String()+":"+node.TextMarkType)+ }+ return ast.WalkContinue+ })+ t.Fatalf("inline type %q was not parsed from %q: %v", test.typ, rich.Content, nodeTypes)+ }+ if 0 == pass {+ if _, err = NormalizeValueTextRich(rich); nil != err {+ t.Fatalf("normalize inline type %q failed: %s", test.typ, err)+ }+ }+ }+ }++ combined := &ValueTextRich{Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown, Content: "***combined***"}+ for pass := 0; pass < 2; pass++ {+ tree, err := ParseValueTextRich(combined)+ if nil != err {+ t.Fatal(err)+ }+ found := false+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if entering && ast.NodeTextMark == node.Type && node.ContainTextMarkTypes("strong", "em") {+ found = true+ return ast.WalkStop+ }+ return ast.WalkContinue+ })+ if !found {+ t.Fatalf("combined text mark was not preserved: %q", combined.Content)+ }+ if 0 == pass {+ if _, err = NormalizeValueTextRich(combined); nil != err {+ t.Fatal(err)+ }+ }+ }+}++func TestValueTextRichParserIgnoresEditorMarkdownSettings(t *testing.T) {+ original := *util.MarkdownSettings+ defer func() {+ *util.MarkdownSettings = original+ }()++ rich := &ValueTextRich{+ Spec: ValueTextRichSpec,+ Format: ValueTextRichFormatKramdown,+ Content: "***em strong*** ==mark== ~~strike~~ ^sup^ ~sub~ #tag# $math$",+ }+ if _, err := NormalizeValueTextRich(rich); nil != err {+ t.Fatal(err)+ }++ util.MarkdownSettings.InlineAsterisk = false+ util.MarkdownSettings.InlineUnderscore = false+ util.MarkdownSettings.InlineSup = false+ util.MarkdownSettings.InlineSub = false+ util.MarkdownSettings.InlineTag = false+ util.MarkdownSettings.InlineMath = false+ util.MarkdownSettings.InlineStrikethrough = false+ util.MarkdownSettings.InlineFullWidthStrikethrough = false+ util.MarkdownSettings.InlineMark = false+ disabled := false+ util.MarkdownSettings.BlockFullWidthTaskList = &disabled+ util.MarkdownSettings.CodeBlockMiddleDot = &disabled++ disabledSettingsRich := &ValueTextRich{+ Spec: ValueTextRichSpec,+ Format: ValueTextRichFormatKramdown,+ Content: "***em strong*** ==mark== ~~strike~~ ^sup^ ~sub~ #tag# $math$",+ }+ if _, err := NormalizeValueTextRich(disabledSettingsRich); nil != err {+ t.Fatal(err)+ }++ for _, candidate := range []*ValueTextRich{rich, disabledSettingsRich} {+ tree, err := ParseValueTextRich(candidate)+ if nil != err {+ t.Fatal(err)+ }+ for _, typ := range []string{"em", "strong", "mark", "s", "sup", "sub", "tag", "inline-math"} {+ found := false+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if entering && ast.NodeTextMark == node.Type && node.IsTextMarkType(typ) {+ found = true+ return ast.WalkStop+ }+ return ast.WalkContinue+ })+ if !found {+ t.Fatalf("stored inline type %q depended on editor Markdown settings: %q", typ, candidate.Content)+ }+ }+ }+}++func TestValueTextRichSanitizesExecutableInlineMarkup(t *testing.T) {+ tests := []struct {+ content string+ forbidden []string+ allowReject bool+ }{+ {"[link](JaVaScRiPt:alert(1))", []string{"javascript:", "alert(1)"}, true},+ {"<span data-type=\"strong\" onclick=\"alert(1)\">bold</span>", []string{"onclick", "alert(1)"}, true},+ }+ for _, test := range tests {+ rich := &ValueTextRich{Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown, Content: test.content}+ if _, err := NormalizeValueTextRich(rich); nil != err {+ if test.allowReject {+ continue+ }+ t.Fatalf("safe link structure was rejected instead of sanitized: %s", err)+ }+ blockDOM, _, err := parseValueTextRich(rich)+ if nil != err {+ t.Fatal(err)+ }+ persisted := strings.ToLower(rich.Content)+ rendered := strings.ToLower(blockDOM)+ for _, forbidden := range test.forbidden {+ if strings.Contains(persisted, forbidden) || strings.Contains(rendered, forbidden) {+ t.Fatalf("executable inline markup survived normalization: source=%q rendered=%q", rich.Content, blockDOM)+ }+ }+ }+}++func TestValueTextRichLinkTargetPolicy(t *testing.T) {+ allowed := []string{+ "",+ "https://example.com/path?q=value#fragment",+ "HTTP://localhost:6806/path",+ "mailto:[email protected]",+ "tel:+8613800138000",+ "siyuan://blocks/20240101000000-abcdefg?focus=1",+ "web+siyuan://bazaar/plugins/example/readme",+ "../relative/note.md",+ "/absolute/path",+ "#heading",+ "?query=value",+ "//example.com/path",+ "assets/file with space-20240101000000-abcdefg.pdf?page=2",+ "assets/percent%25-20240101000000-abcdefg.txt",+ }+ blocked := []string{+ " javascript:alert(1)",+ "javascript:alert(1)",+ "JaVaScRiPt:alert(1)",+ "java\tscript:alert(1)",+ "java\x00script:alert(1)",+ "java\u200bscript:alert(1)",+ "javascript:alert(1)",+ "javascript&colon;alert(1)",+ "java%73cript:alert(1)",+ "vbscript:msgbox(1)",+ "data:text/html,<script>alert(1)</script>",+ "file:///tmp/document.txt",+ "blob:https://example.com/id",+ "ftp://example.com/file",+ "custom://action",+ "https:example.com",+ "http:///missing-host",+ "tel:",+ "siyuan:/blocks/20240101000000-abcdefg",+ "web+siyuan:/bazaar/plugins/example/readme",+ `https:\\example.com`,+ "assets/../outside.txt",+ "relative/%zz",+ "relative/%ff",+ "relative/%C3",+ "relative/%E4%B8",+ }+ for _, target := range allowed {+ linkDest := &ast.Node{Type: ast.NodeLinkDest, Tokens: []byte(target)}+ textMark := &ast.Node{Type: ast.NodeTextMark, TextMarkType: "a", TextMarkAHref: target}+ if !isAllowedValueTextRichNode(linkDest) {+ t.Fatalf("allowed classic link destination was rejected: %q", target)+ }+ if !isAllowedValueTextMark(textMark) {+ t.Fatalf("allowed text mark link destination was rejected: %q", target)+ }+ }+ for _, target := range blocked {+ linkDest := &ast.Node{Type: ast.NodeLinkDest, Tokens: []byte(target)}+ textMark := &ast.Node{Type: ast.NodeTextMark, TextMarkType: "a", TextMarkAHref: target}+ if isAllowedValueTextRichNode(linkDest) {+ t.Fatalf("unsafe classic link destination was accepted: %q", target)+ }+ if isAllowedValueTextMark(textMark) {+ t.Fatalf("unsafe text mark link destination was accepted: %q", target)+ }+ }+}++func TestValueTextRichRejectsObfuscatedLinkTargets(t *testing.T) {+ contents := []string{+ "[classic](<vbscript:msgbox(1)>)",+ "[classic](<java%73cript:alert(1)>)",+ "[classic](<data:text/html,active>)",+ `<span data-type="a" data-href=" javascript:alert(1)">leading whitespace</span>`,+ `<span data-type="a" data-href="java
script:alert(1)">control</span>`,+ `<span data-type="a" data-href="javascript&colon;alert(1)">entity</span>`,+ `<span data-type="a" data-href="file:///tmp/document.txt">file</span>`,+ }+ for _, content := range contents {+ rich := &ValueTextRich{Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown, Content: content}+ if _, err := NormalizeValueTextRich(rich); nil == err {+ t.Fatalf("obfuscated rich text link target was accepted: %q", content)+ }+ }+}++func TestValueTextRichInlineMemoIsPlainText(t *testing.T) {+ allowed := []string{+ "plain memo",+ "plain & safe",+ "copyright ©",+ "2 < 3 and 4 > 1",+ "heart <3",+ "tab\tline",+ "line one\nline two\rline three",+ "\U0001f469\u200d\U0001f4bb developer",+ "\u200fنص ثنائي الاتجاه",+ }+ blocked := []string{+ "<img src=x onerror=alert(1)>",+ "<span data-type=\"file-annotation-ref\" data-id=\"assets/document.pdf/id\">fake</span>",+ "<script>alert(1)</script>",+ "&lt;img src=x onerror=alert(1)&gt;",+ "memo\x00control",+ }+ for _, content := range allowed {+ node := &ast.Node{Type: ast.NodeTextMark, TextMarkType: "inline-memo", TextMarkInlineMemoContent: content}+ if !isAllowedValueTextMark(node) {+ t.Fatalf("plain inline memo was rejected: %q", content)+ }+ }+ for _, content := range blocked {+ node := &ast.Node{Type: ast.NodeTextMark, TextMarkType: "inline-memo", TextMarkInlineMemoContent: content}+ if isAllowedValueTextMark(node) {+ t.Fatalf("active or ambiguous inline memo was accepted: %q", content)+ }+ }++ allowedRich := &ValueTextRich{+ Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown,+ Content: `<span data-type="inline-memo" data-inline-memo-content="plain & safe">annotated</span>`,+ }+ if _, err := NormalizeValueTextRich(allowedRich); nil != err {+ t.Fatalf("plain inline memo failed normalization: %v", err)+ }+ malicious := []string{+ `<span data-type="inline-memo" data-inline-memo-content="<img src=x onerror=alert(1)>">image</span>`,+ `<span data-type="inline-memo" data-inline-memo-content="<span data-type='file-annotation-ref'>fake</span>">fake</span>`,+ `<span data-type="inline-memo" data-inline-memo-content="&lt;script&gt;alert(1)&lt;/script&gt;">entity</span>`,+ "<span data-type=\"inline-memo\" data-inline-memo-content=\"memocontrol\">control</span>",+ }+ for _, content := range malicious {+ rich := &ValueTextRich{Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown, Content: content}+ if _, err := NormalizeValueTextRich(rich); nil == err {+ t.Fatalf("active inline memo was accepted: %q", content)+ }+ }+}++func TestValueTextRichInlineMemoWhitespaceFromBlockDOM(t *testing.T) {+ blockDOM := `<div data-node-id="20240101000000-abcdefg" data-type="NodeParagraph" class="p">` ++ `<div contenteditable="true" spellcheck="false"><span data-type="inline-memo" ` ++ "data-inline-memo-content=\"tab\tline one\nline two\rline three\">annotated</span></div>" ++ `<div class="protyle-attr" contenteditable="false"></div></div>`+ markdown := newValueTextRichLute().BlockDOM2Md(blockDOM)+ rich := &ValueTextRich{Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown, Content: markdown}+ tree, err := NormalizeValueTextRich(rich)+ if nil != err {+ t.Fatalf("normalize inline memo textarea whitespace from BlockDOM: %v, markdown=%q", err, markdown)+ }++ want := "tab\tline one" + editor.IALValEscNewLine + "line two" + editor.IALValEscNewLine + "line three"+ got := ""+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if entering && node.IsTextMarkType("inline-memo") {+ got = node.TextMarkInlineMemoContent+ return ast.WalkStop+ }+ return ast.WalkContinue+ })+ if got != want {+ t.Fatalf("inline memo textarea whitespace = %q, want %q, markdown=%q", got, want, markdown)+ }+}++func TestValueTextRejectsUnsupportedRichPayload(t *testing.T) {+ tests := []*ValueTextRich{+ {Spec: ValueTextRichSpec + 1, Format: ValueTextRichFormatKramdown},+ {Spec: ValueTextRichSpec, Format: "block-dom"},+ }+ for _, rich := range tests {+ value := &ValueText{Rich: rich}+ if err := value.NormalizeRichContent(); nil == err {+ t.Fatalf("unsupported rich payload was accepted: %+v", rich)+ }+ }+}diff --git a/kernel/model/asset_reference.go b/kernel/model/asset_reference.goindex 77ffadca35..7bc8d9fcd2 100644--- a/kernel/model/asset_reference.go+++ b/kernel/model/asset_reference.go@@ -227,31 +227,83 @@ func rewriteAttributeViewValueAssetReferences(value *av.Value, options assetRefeupdated = true}}- if value.Relation != nil {- for _, content := range value.Relation.Contents {- updated = rewriteAttributeViewValueAssetReferences(content, options) || updated- }- }- if value.Rollup != nil {- for _, content := range value.Rollup.Contents {- updated = rewriteAttributeViewValueAssetReferences(content, options) || updated- }+ if rewriteAttributeViewRichAssetReferences(value, options) {+ updated = true}return}-func rewriteAttributeViewAssetReferences(attrView *av.AttributeView, options assetReferenceRewriteOptions) (updated bool) {- if attrView == nil {+func rewriteAttributeViewRichAssetReferences(value *av.Value, options assetReferenceRewriteOptions) (updated bool) {+ if nil == value || nil == value.Text || nil == value.Text.Rich {return}- for _, keyValues := range attrView.KeyValues {- if keyValues == nil {- continue+ tree, err := av.ParseValueTextRich(value.Text.Rich)+ if nil != err || nil == tree {+ return+ }+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if !entering {+ return ast.WalkContinue}- for _, value := range keyValues.Values {- updated = rewriteAttributeViewValueAssetReferences(value, options) || updated+ switch node.Type {+ case ast.NodeLinkDest:+ reference := node.TokensStr()+ if rewritten := rewriteAssetReference(reference, options); rewritten != reference {+ node.Tokens = []byte(rewritten)+ updated = true+ }+ case ast.NodeTextMark:+ if node.IsTextMarkType("a") {+ if rewritten := rewriteAssetReference(node.TextMarkAHref, options); rewritten != node.TextMarkAHref {+ node.TextMarkAHref = rewritten+ updated = true+ }+ }+ if node.IsTextMarkType("file-annotation-ref") {+ rewritten := rewriteAttributeViewFileAnnotationReference(node.TextMarkFileAnnotationRefID, options)+ if rewritten != node.TextMarkFileAnnotationRefID {+ node.TextMarkFileAnnotationRefID = rewritten+ updated = true+ }+ }+ case ast.NodeFileAnnotationRefID:+ reference := node.TokensStr()+ if rewritten := rewriteAttributeViewFileAnnotationReference(reference, options); rewritten != reference {+ node.Tokens = []byte(rewritten)+ updated = true+ }}+ return ast.WalkContinue+ })+ if !updated {+ return+ }++ oldRichContent, oldContent := value.Text.Rich.Content, value.Text.Content+ richContent, err := av.RenderValueTextRich(tree)+ if nil != err {+ return false+ }+ value.Text.Rich.Content = richContent+ if err = value.Text.NormalizeRichContent(); nil != err {+ value.Text.Rich.Content, value.Text.Content = oldRichContent, oldContent+ return false}+ return true+}++func rewriteAttributeViewFileAnnotationReference(reference string, options assetReferenceRewriteOptions) string {+ options.bindTargetBox = false+ return rewriteAssetReference(reference, options)+}++func rewriteAttributeViewAssetReferences(attrView *av.AttributeView, options assetReferenceRewriteOptions) (updated bool) {+ if attrView == nil {+ return+ }+ attrView.VisitPersistedValues(func(value *av.Value) {+ updated = rewriteAttributeViewValueAssetReferences(value, options) || updated+ })return}diff --git a/kernel/model/asset_reference_test.go b/kernel/model/asset_reference_test.goindex a8dd99fa13..9e8819881d 100644--- a/kernel/model/asset_reference_test.go+++ b/kernel/model/asset_reference_test.go@@ -18,6 +18,7 @@ package modelimport (stdhtml "html"+ "reflect""strings""testing"@@ -121,18 +122,61 @@ func TestRewriteAttributeViewAssetReferences(t *testing.T) {sourceBoxID = "20260812000000-source0"targetBoxID = "20260812000001-target0")+ richText := &av.ValueText{+ Content: "stale rich projection",+ Rich: &av.ValueTextRich{+ Spec: av.ValueTextRichSpec, Format: av.ValueTextRichFormatKramdown,+ Content: strings.Join([]string{+ "[Markdown](assets/rich.png)",+ `<span data-type="a" data-href="assets/rich-text-mark.png">Text mark</span>`,+ `<<assets/native-20200101000001-bcdefgh.pdf/20200101000002-cdefghi "PDF shorthand">>`,+ `<span data-type="file-annotation-ref" data-id="assets/span-20200101000003-defghij.pdf/20200101000004-efghijk">PDF text mark</span>`,+ "[Network](https://example.com/remote.png)",+ }, "\n\n"),+ },+ }+ relationRichText := &av.ValueText{Content: "stale relation projection", Rich: &av.ValueTextRich{+ Spec: av.ValueTextRichSpec, Format: av.ValueTextRichFormatKramdown,+ Content: "[Relation rich](assets/relation-rich.png)",+ }}+ rollupRichText := &av.ValueText{Content: "stale rollup projection", Rich: &av.ValueTextRich{+ Spec: av.ValueTextRichSpec, Format: av.ValueTextRichFormatKramdown,+ Content: "[Rollup rich](assets/rollup-rich.png)",+ }}+ templateRichText := &av.ValueText{Content: "stale template projection", Rich: &av.ValueTextRich{+ Spec: av.ValueTextRichSpec, Format: av.ValueTextRichFormatKramdown,+ Content: "[Template rich](assets/template-rich.png)",+ }}attrView := &av.AttributeView{KeyValues: []*av.KeyValues{{Values: []*av.Value{{URL: &av.ValueURL{Content: "assets/url.png?box=" + sourceBoxID}},{MAsset: []*av.ValueAsset{{Content: "assets/file.pdf?page=3&box=" + sourceBoxID}}},- {Relation: &av.ValueRelation{Contents: []*av.Value{{URL: &av.ValueURL{Content: "assets/relation.png?box=" + sourceBoxID}}}}},- {Rollup: &av.ValueRollup{Contents: []*av.Value{{MAsset: []*av.ValueAsset{{Content: "assets/rollup.png?box=" + sourceBoxID}}}}}},- }}}}+ {Text: richText},+ {Relation: &av.ValueRelation{Contents: []*av.Value{{+ URL: &av.ValueURL{Content: "assets/relation.png?box=" + sourceBoxID},+ Text: relationRichText,+ }}}},+ {Rollup: &av.ValueRollup{Contents: []*av.Value{{+ MAsset: []*av.ValueAsset{{Content: "assets/rollup.png?box=" + sourceBoxID}},+ Text: rollupRichText,+ }}}},+ }}}, NewItemTemplates: []*av.NewItemTemplate{{+ FieldValues: map[string]*av.NewItemFieldValue{+ "text": {Value: &av.Value{Text: templateRichText}},+ },+ }}}options := assetReferenceRewriteOptions{pathMap: map[string]string{- "assets/url.png": "assets/encrypted-url.png",- "assets/file.pdf": "assets/encrypted-file.pdf",- "assets/relation.png": "assets/encrypted-relation.png",- "assets/rollup.png": "assets/encrypted-rollup.png",+ "assets/url.png": "assets/encrypted-url.png",+ "assets/file.pdf": "assets/encrypted-file.pdf",+ "assets/rich.png": "assets/encrypted-rich.png",+ "assets/rich-text-mark.png": "assets/encrypted-rich-text-mark.png",+ "assets/native-20200101000001-bcdefgh.pdf": "assets/encrypted-native-20200101000011-lmnopqr.pdf",+ "assets/span-20200101000003-defghij.pdf": "assets/encrypted-span-20200101000013-nopqrst.pdf",+ "assets/relation.png": "assets/encrypted-relation.png",+ "assets/relation-rich.png": "assets/encrypted-relation-rich.png",+ "assets/rollup.png": "assets/encrypted-rollup.png",+ "assets/rollup-rich.png": "assets/encrypted-rollup-rich.png",+ "assets/template-rich.png": "assets/encrypted-template-rich.png",},targetBoxID: targetBoxID,bindTargetBox: true,@@ -144,10 +188,54 @@ func TestRewriteAttributeViewAssetReferences(t *testing.T) {values := attrView.KeyValues[0].ValuesassertEqualAssetReference(t, values[0].URL.Content, "assets/encrypted-url.png?box="+targetBoxID)assertEqualAssetReference(t, values[1].MAsset[0].Content, "assets/encrypted-file.pdf?box="+targetBoxID+"&page=3")- assertEqualAssetReference(t, values[2].Relation.Contents[0].URL.Content,+ assertEqualAssetReference(t, values[3].Relation.Contents[0].URL.Content,"assets/encrypted-relation.png?box="+targetBoxID)- assertEqualAssetReference(t, values[3].Rollup.Contents[0].MAsset[0].Content,+ assertEqualAssetReference(t, values[4].Rollup.Contents[0].MAsset[0].Content,"assets/encrypted-rollup.png?box="+targetBoxID)++ wantRichAssets := []string{+ "assets/encrypted-rich.png?box=" + targetBoxID,+ "assets/encrypted-rich-text-mark.png?box=" + targetBoxID,+ "assets/encrypted-native-20200101000011-lmnopqr.pdf",+ "assets/encrypted-span-20200101000013-nopqrst.pdf",+ }+ assertAttributeViewRichAssets(t, richText, wantRichAssets)+ if got, want := richText.Content, "Markdown\nText mark\nPDF shorthand\nPDF text mark\nNetwork"; got != want {+ t.Fatalf("rich plain projection = %q, want %q", got, want)+ }+ assertAttributeViewRichAssets(t, relationRichText,+ []string{"assets/encrypted-relation-rich.png?box=" + targetBoxID})+ assertAttributeViewRichAssets(t, rollupRichText,+ []string{"assets/encrypted-rollup-rich.png?box=" + targetBoxID})+ assertAttributeViewRichAssets(t, templateRichText,+ []string{"assets/encrypted-template-rich.png?box=" + targetBoxID})+ if got, want := relationRichText.Content, "Relation rich"; got != want {+ t.Fatalf("relation rich plain projection = %q, want %q", got, want)+ }+ if got, want := rollupRichText.Content, "Rollup rich"; got != want {+ t.Fatalf("rollup rich plain projection = %q, want %q", got, want)+ }+ if got, want := templateRichText.Content, "Template rich"; got != want {+ t.Fatalf("template rich plain projection = %q, want %q", got, want)+ }+}++func assertAttributeViewRichAssets(t *testing.T, text *av.ValueText, want []string) {+ t.Helper()+ tree, err := av.ParseValueTextRich(text.Rich)+ if nil != err {+ t.Fatalf("parse rewritten attribute view rich text: %v", err)+ }+ if got := getAssetsLinkDests(tree.Root, false); !reflect.DeepEqual(got, want) {+ t.Fatalf("rewritten attribute view rich assets: got %v, want %v", got, want)+ }+ normalized := text.Rich.Content+ if err = text.NormalizeRichContent(); nil != err {+ t.Fatalf("renormalize rewritten attribute view rich text: %v", err)+ }+ if text.Rich.Content != normalized {+ t.Fatalf("rewritten attribute view rich text is not normalized:\ngot %q\nwant %q", text.Rich.Content, normalized)+ }}func assertAssetReferenceContains(t *testing.T, got, want string) {diff --git a/kernel/model/assets.go b/kernel/model/assets.goindex 8a66c1fd47..cbffe351cf 100644--- a/kernel/model/assets.go+++ b/kernel/model/assets.go@@ -2215,7 +2215,8 @@ func assetLinkDestBlockID(node *ast.Node) string {func getAssetLinkDestsByNode(node *ast.Node, includeServePath bool) []string {if !node.IsBlock() && ast.NodeLinkDest != node.Type && ast.NodeHTMLBlock != node.Type && ast.NodeInlineHTML != node.Type &&ast.NodeIFrame != node.Type && ast.NodeWidget != node.Type && ast.NodeAudio != node.Type && ast.NodeVideo != node.Type &&- ast.NodeAttributeView != node.Type && !node.IsTextMarkType("a") && !node.IsTextMarkType("file-annotation-ref") {+ ast.NodeAttributeView != node.Type && ast.NodeFileAnnotationRefID != node.Type && !node.IsTextMarkType("a") &&+ !node.IsTextMarkType("file-annotation-ref") {return nil}@@ -2319,7 +2320,8 @@ func getAssetsLinkDestsWithAttributeViewItemFilter(// 修改以下代码时需要同时修改 database 构造行级元素实现,增加必要的类型if !entering || (ast.NodeLinkDest != n.Type && ast.NodeHTMLBlock != n.Type && ast.NodeInlineHTML != n.Type &&ast.NodeIFrame != n.Type && ast.NodeWidget != n.Type && ast.NodeAudio != n.Type && ast.NodeVideo != n.Type &&- ast.NodeAttributeView != n.Type && !n.IsTextMarkType("a") && !n.IsTextMarkType("file-annotation-ref")) {+ ast.NodeAttributeView != n.Type && ast.NodeFileAnnotationRefID != n.Type && !n.IsTextMarkType("a") &&+ !n.IsTextMarkType("file-annotation-ref")) {return ast.WalkContinue}@@ -2338,17 +2340,13 @@ func getAssetsLinkDestsWithAttributeViewItemFilter(dest := strings.TrimSpace(n.TextMarkAHref)ret = append(ret, dest)} else if n.IsTextMarkType("file-annotation-ref") {- if !util.IsAssetLinkDest(gulu.Str.ToBytes(n.TextMarkFileAnnotationRefID), includeServePath) {- return ast.WalkContinue+ if dest := fileAnnotationAssetLinkDest(n.TextMarkFileAnnotationRefID, includeServePath); "" != dest {+ ret = append(ret, dest)}-- if !strings.Contains(n.TextMarkFileAnnotationRefID, "/") {- return ast.WalkContinue+ } else if ast.NodeFileAnnotationRefID == n.Type {+ if dest := fileAnnotationAssetLinkDest(n.TokensStr(), includeServePath); "" != dest {+ ret = append(ret, dest)}-- dest := n.TextMarkFileAnnotationRefID[:strings.LastIndexByte(n.TextMarkFileAnnotationRefID, '/')]- dest = strings.TrimSpace(dest)- ret = append(ret, dest)} else if ast.NodeAttributeView == n.Type {attrView, _ := av.ParseAttributeView(n.AttributeViewID)if nil == attrView {@@ -2387,36 +2385,89 @@ func getAssetsLinkDestsWithAttributeViewItemFilter(return}+func fileAnnotationAssetLinkDest(reference string, includeServePath bool) string {+ if !util.IsAssetLinkDest(gulu.Str.ToBytes(reference), includeServePath) {+ return ""+ }+ separator := strings.LastIndexByte(reference, '/')+ if separator < len("assets/") {+ return ""+ }+ return strings.TrimSpace(reference[:separator])+}+func getAttributeViewAssetsLinkDests(attrView *av.AttributeView,includeServePath bool,itemFilter attributeViewItemFilter,) (ret []string) {- for _, keyValues := range attrView.KeyValues {- if av.KeyTypeMAsset != keyValues.Key.Type && av.KeyTypeURL != keyValues.Key.Type {- continue- }-- for _, value := range keyValues.Values {- if nil != itemFilter && !itemFilter(attrView, value.BlockID) {+ if nil == attrView {+ return+ }+ collectValue := func(value *av.Value) {+ ret = append(ret, getAttributeViewValueAssetsLinkDests(value, includeServePath)...)+ }+ if nil == itemFilter {+ attrView.VisitPersistedValues(collectValue)+ } else {+ for _, keyValues := range attrView.KeyValues {+ if nil == keyValues {continue}-- if av.KeyTypeMAsset == keyValues.Key.Type {- for _, asset := range value.MAsset {- dest := asset.Content- if util.IsAssetLinkDest([]byte(dest), includeServePath) {- ret = append(ret, strings.TrimSpace(dest))- }- }- } else if nil != value.URL {- dest := value.URL.Content- if util.IsAssetLinkDest([]byte(dest), includeServePath) {- ret = append(ret, strings.TrimSpace(dest))+ for _, value := range keyValues.Values {+ if nil == value || !itemFilter(attrView, value.BlockID) {+ continue}+ visitAttributeViewValue(value, collectValue)}}}+ ret = gulu.Str.RemoveDuplicatedElem(ret)+ return+}++func visitAttributeViewValue(value *av.Value, visit func(*av.Value)) {+ visitAttributeViewValue0(value, visit, map[*av.Value]struct{}{})+}++func visitAttributeViewValue0(value *av.Value, visit func(*av.Value), visited map[*av.Value]struct{}) {+ if nil == value {+ return+ }+ if _, ok := visited[value]; ok {+ return+ }+ visited[value] = struct{}{}+ visit(value)+ if nil != value.Relation {+ for _, content := range value.Relation.Contents {+ visitAttributeViewValue0(content, visit, visited)+ }+ }+ if nil != value.Rollup {+ for _, content := range value.Rollup.Contents {+ visitAttributeViewValue0(content, visit, visited)+ }+ }+}++func getAttributeViewValueAssetsLinkDests(value *av.Value, includeServePath bool) (ret []string) {+ if nil == value {+ return+ }+ if nil != value.URL && util.IsAssetLinkDest([]byte(value.URL.Content), includeServePath) {+ ret = append(ret, strings.TrimSpace(value.URL.Content))+ }+ for _, asset := range value.MAsset {+ if nil != asset && util.IsAssetLinkDest([]byte(asset.Content), includeServePath) {+ ret = append(ret, strings.TrimSpace(asset.Content))+ }+ }+ if nil != value.Text && nil != value.Text.Rich {+ if tree, err := av.ParseValueTextRich(value.Text.Rich); nil == err && nil != tree {+ ret = append(ret, getAssetsLinkDests(tree.Root, includeServePath)...)+ }+ }return}diff --git a/kernel/model/assets_test.go b/kernel/model/assets_test.goindex 6e6da645cb..2f442b9409 100644--- a/kernel/model/assets_test.go+++ b/kernel/model/assets_test.go@@ -661,10 +661,13 @@ func TestGetAssetLinkDestsByNode(t *testing.T) {paragraph := &ast.Node{Type: ast.NodeParagraph, ID: blockID}paragraph.SetIALAttr("custom-data-assets", "assets/custom.png")linkDest := &ast.Node{Type: ast.NodeLinkDest, Tokens: []byte("assets/image.png")}+ annotationID := &ast.Node{Type: ast.NodeFileAnnotationRefID,+ Tokens: []byte("assets/document-20200101000001-bcdefgh.pdf/20200101000002-cdefghi")}root.AppendChild(paragraph)paragraph.AppendChild(linkDest)+ paragraph.AppendChild(annotationID)- want := []string{"assets/custom.png", "assets/image.png"}+ want := []string{"assets/custom.png", "assets/image.png", "assets/document-20200101000001-bcdefgh.pdf"}if got := getAssetsLinkDests(root, false); !reflect.DeepEqual(got, want) {t.Fatalf("get asset link destinations: got %v, want %v", got, want)}@@ -674,6 +677,10 @@ func TestGetAssetLinkDestsByNode(t *testing.T) {if got := getAssetLinkDestsByNode(linkDest, false); !reflect.DeepEqual(got, []string{"assets/image.png"}) {t.Fatalf("get inline asset link destinations: got %v, want %v", got, []string{"assets/image.png"})}+ if got := getAssetLinkDestsByNode(annotationID, false); !reflect.DeepEqual(got,+ []string{"assets/document-20200101000001-bcdefgh.pdf"}) {+ t.Fatalf("get PDF annotation asset link destination: got %v", got)+ }if got := assetLinkDestBlockID(linkDest); got != blockID {t.Fatalf("get asset link destination block ID: got %q, want %q", got, blockID)}@@ -706,23 +713,89 @@ func TestGetAttributeViewAssetsLinkDestsFiltersItems(t *testing.T) {{BlockID: "private-item", URL: &av.ValueURL{Content: "assets/private-url.png"}},},},+ {+ Key: &av.Key{Type: av.KeyTypeText},+ Values: []*av.Value{+ {+ BlockID: "public-item",+ Text: newAttributeViewRichText(t, strings.Join([]string{+ "[Markdown](assets/public-rich.png)",+ `<span data-type="a" data-href="assets/public-text-mark.png">Text mark</span>`,+ `<<assets/public-document-20200101000001-bcdefgh.pdf/20200101000002-cdefghi "PDF shorthand">>`,+ `<span data-type="file-annotation-ref" data-id="assets/public-span-20200101000003-defghij.pdf/20200101000004-efghijk">PDF text mark</span>`,+ "[Network](https://example.com/remote.png)",+ }, "\n\n")),+ Relation: &av.ValueRelation{Contents: []*av.Value{{+ Text: newAttributeViewRichText(t, "[Relation](assets/public-relation.png)"),+ }}},+ Rollup: &av.ValueRollup{Contents: []*av.Value{{+ Text: newAttributeViewRichText(t, "[Rollup](assets/public-rollup.png)"),+ }}},+ },+ {+ BlockID: "private-item",+ Text: newAttributeViewRichText(t, "[Private](assets/private-rich.png)"),+ },+ },+ },},+ NewItemTemplates: []*av.NewItemTemplate{{+ FieldValues: map[string]*av.NewItemFieldValue{+ "text": {Value: &av.Value{Text: newAttributeViewRichText(t, "[Template](assets/template-rich.png)")}},+ },+ }},}filter := func(_ *av.AttributeView, itemID string) bool {return "public-item" == itemID}- want := []string{"assets/public.png", "assets/public-url.png"}+ want := []string{+ "assets/public.png",+ "assets/public-url.png",+ "assets/public-rich.png",+ "assets/public-text-mark.png",+ "assets/public-document-20200101000001-bcdefgh.pdf",+ "assets/public-span-20200101000003-defghij.pdf",+ "assets/public-relation.png",+ "assets/public-rollup.png",+ }if got := getAttributeViewAssetsLinkDests(attrView, false, filter); !reflect.DeepEqual(got, want) {t.Fatalf("get filtered attribute view asset links: got %v, want %v", got, want)}- want = []string{"assets/public.png", "assets/private.png", "assets/public-url.png", "assets/private-url.png"}+ want = []string{+ "assets/public.png",+ "assets/private.png",+ "assets/public-url.png",+ "assets/private-url.png",+ "assets/public-rich.png",+ "assets/public-text-mark.png",+ "assets/public-document-20200101000001-bcdefgh.pdf",+ "assets/public-span-20200101000003-defghij.pdf",+ "assets/public-relation.png",+ "assets/public-rollup.png",+ "assets/private-rich.png",+ "assets/template-rich.png",+ }if got := getAttributeViewAssetsLinkDests(attrView, false, nil); !reflect.DeepEqual(got, want) {t.Fatalf("get unfiltered attribute view asset links: got %v, want %v", got, want)}}+func newAttributeViewRichText(t *testing.T, content string) *av.ValueText {+ t.Helper()+ ret := &av.ValueText{+ Content: "stale projection",+ Rich: &av.ValueTextRich{+ Spec: av.ValueTextRichSpec, Format: av.ValueTextRichFormatKramdown, Content: content,+ },+ }+ if err := ret.NormalizeRichContent(); nil != err {+ t.Fatalf("normalize attribute view rich text: %v", err)+ }+ return ret+}+func TestRenameAssetClearsAttributeViewCache(t *testing.T) {const avID = "20200101000000-abcdefg"oldPath := "assets/old-20200101000000-abcdefg.png"diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.goindex e0682389e7..e925df9b0e 100644--- a/kernel/model/attribute_view.go+++ b/kernel/model/attribute_view.go@@ -8152,17 +8152,16 @@ func updateAttributeViewValue0(tx *Transaction, attrView *av.AttributeView, keyIval.Type = keyValues.Key.Type}+ created := falseif nil == val {val = &av.Value{ID: ast.NewNodeID(), KeyID: keyID, BlockID: itemID, Type: keyValues.Key.Type, CreatedAt: now, UpdatedAt: now}- keyValues.Values = append(keyValues.Values, val)- if nil != context {- context.values[keyID][itemID] = val- }+ created = true}valueID := val.IDvalueType := val.TypevalueCreatedAt := val.CreatedAt+ oldText := val.TextisUpdatingBlockKey := av.KeyTypeBlock == val.Typevar oldRelationBlockIDs []string@@ -8178,15 +8177,42 @@ func updateAttributeViewValue0(tx *Transaction, attrView *av.AttributeView, keyIlogging.LogErrorf("marshal value [%+v] failed: %s", valueData, err)return}- if err = gulu.JSON.UnmarshalJSON(data, val); err != nil {+ updatedVal := val+ // 文本值先在副本上合并和校验,避免富文本校验失败污染原值,并保留旧客户端的部分更新语义。+ if av.KeyTypeText == valueType {+ updatedVal = val.Clone()+ if nil == updatedVal {+ err = fmt.Errorf("clone attribute view text value [%s] failed", valueID)+ return+ }+ }+ if err = gulu.JSON.UnmarshalJSON(data, updatedVal); err != nil {logging.LogErrorf("unmarshal data [%s] failed: %s", data, err)return}- val.ID = valueID- val.KeyID = keyID- val.BlockID = itemID- val.Type = valueType- val.CreatedAt = valueCreatedAt+ updatedVal.ID = valueID+ updatedVal.KeyID = keyID+ updatedVal.BlockID = itemID+ updatedVal.Type = valueType+ updatedVal.CreatedAt = valueCreatedAt+ if av.KeyTypeText == updatedVal.Type && nil != updatedVal.Text {+ if nil != oldText && nil != oldText.Rich && !attributeViewTextRichFieldPresent(data) &&+ updatedVal.Text.Content != oldText.Content {+ updatedVal.Text.Rich = nil+ }+ if err = updatedVal.Text.NormalizeRichContent(); nil != err {+ return+ }+ }+ if updatedVal != val {+ *val = *updatedVal+ }+ if created {+ keyValues.Values = append(keyValues.Values, val)+ if nil != context {+ context.values[keyID][itemID] = val+ }+ }key, _ := attrView.GetKey(keyID)@@ -8364,6 +8390,23 @@ func updateAttributeViewValue0(tx *Transaction, attrView *av.AttributeView, keyIreturn}+func attributeViewTextRichFieldPresent(data []byte) bool {+ var valueFields map[string]json.RawMessage+ if err := json.Unmarshal(data, &valueFields); nil != err {+ return false+ }+ textData, ok := valueFields["text"]+ if !ok {+ return false+ }+ var textFields map[string]json.RawMessage+ if err := json.Unmarshal(textData, &textFields); nil != err {+ return false+ }+ _, ret := textFields["rich"]+ return ret+}+func refreshRelatedSrcAvs(destAvID string, tx *Transaction) {refreshRelatedSrcAvsInBlock(destAvID, "", tx)}diff --git a/kernel/model/attribute_view_ref_dynamic.go b/kernel/model/attribute_view_ref_dynamic.gonew file mode 100644index 0000000000..663d64944c--- /dev/null+++ b/kernel/model/attribute_view_ref_dynamic.go@@ -0,0 +1,105 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package model++import (+ "github.com/88250/lute/ast"+ "github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode"+)++type attributeViewRefSource struct {+ avID string+ boxID string+}++func refreshAttributeViewDynamicRefTexts(updatedDefNodes map[string]*ast.Node, refs []*sql.Ref) {+ for _, source := range attributeViewRefSources(refs) {+ attrView, err := av.ParseAttributeViewInBox(source.avID, source.boxID)+ if nil != err || nil == attrView || !updateAttributeViewDynamicRefTexts(attrView, updatedDefNodes) {+ continue+ }+ if err = av.SaveAttributeView(attrView); nil != err {+ logging.LogErrorf("save attribute view [%s] dynamic reference text failed: %s", source.avID, err)+ continue+ }+ ReloadAttrView(source.avID)+ refreshRelatedSrcAvs(source.avID, nil)+ }+}++func attributeViewRefSources(refs []*sql.Ref) (ret []attributeViewRefSource) {+ seen := map[string]bool{}+ for _, ref := range refs {+ if nil == ref || sql.AttributeViewRefType != ref.Type || "" == ref.BlockID {+ continue+ }+ boxID := ""+ if IsEncryptedBox(ref.Box) {+ boxID = ref.Box+ }+ tree, err := LoadTreeByBlockIDInExactBox(ref.BlockID, boxID)+ if nil != err || nil == tree || tree.Box != ref.Box || tree.Path != ref.Path {+ continue+ }+ databaseNode := treenode.GetNodeInTree(tree, ref.BlockID)+ if nil == databaseNode || ast.NodeAttributeView != databaseNode.Type || "" == databaseNode.AttributeViewID {+ continue+ }+ key := boxID + "\x00" + databaseNode.AttributeViewID+ if seen[key] {+ continue+ }+ seen[key] = true+ ret = append(ret, attributeViewRefSource{avID: databaseNode.AttributeViewID, boxID: boxID})+ }+ return+}++func updateAttributeViewDynamicRefTexts(attrView *av.AttributeView, updatedDefNodes map[string]*ast.Node) (changed bool) {+ if nil == attrView || 0 == len(updatedDefNodes) {+ return+ }+ for _, keyValues := range attrView.KeyValues {+ if nil == keyValues || nil == keyValues.Key || av.KeyTypeText != keyValues.Key.Type {+ continue+ }+ for _, value := range keyValues.Values {+ if nil == value || nil == value.Text || !value.Text.IsRich() {+ continue+ }+ fragmentTree, err := av.ParseValueTextRich(value.Text.Rich)+ if nil != err || nil == fragmentTree {+ continue+ }+ valueChanged, _ := updateRefText(fragmentTree.Root, updatedDefNodes)+ if !valueChanged {+ continue+ }+ richContent, renderErr := av.RenderValueTextRich(fragmentTree)+ if nil != renderErr {+ logging.LogWarnf("render attribute view [%s] dynamic reference text failed: %s", attrView.ID, renderErr)+ continue+ }+ value.Text.Rich.Content = richContent+ changed = true+ }+ }+ return+}diff --git a/kernel/model/attribute_view_ref_dynamic_test.go b/kernel/model/attribute_view_ref_dynamic_test.gonew file mode 100644index 0000000000..a556814bae--- /dev/null+++ b/kernel/model/attribute_view_ref_dynamic_test.go@@ -0,0 +1,158 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package model++import (+ "testing"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode"+)++func TestUpdateAttributeViewDynamicRefTextsKeepsStaticAnchors(t *testing.T) {+ originalConf := Conf+ Conf = &AppConf{Editor: conf.NewEditor()}+ t.Cleanup(func() { Conf = originalConf })++ const defID = "20260904040000-def0001"+ const refStyle = "color: var(--b3-font-color8);"+ attrView := &av.AttributeView{KeyValues: []*av.KeyValues{{+ Key: &av.Key{ID: "text", Type: av.KeyTypeText},+ Values: []*av.Value{{Type: av.KeyTypeText, Text: &av.ValueText{+ Rich: &av.ValueTextRich{+ Spec: av.ValueTextRichSpec, Format: av.ValueTextRichFormatKramdown,+ Content: `<span data-type="block-ref text" data-id="` + defID ++ `" data-subtype="d" style="` + refStyle + `">Old dynamic</span> and ((` + defID ++ ` "Static anchor")) #tag# ` ++ "<<assets/document-20240101000000-abcdefg.pdf/20240101000001-bcdefgh \"annotation\">> " ++ "<span data-type=\"inline-memo\" data-inline-memo-content=\"memo\">annotated</span>",+ },+ }}},+ }}}+ defRoot := &ast.Node{Type: ast.NodeDocument, ID: "20260904040001-root001"}+ defBlock := &ast.Node{Type: ast.NodeParagraph, ID: defID}+ defBlock.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("New dynamic")})+ defRoot.AppendChild(defBlock)++ if !updateAttributeViewDynamicRefTexts(attrView, map[string]*ast.Node{defID: defBlock}) {+ t.Fatal("expected the dynamic attribute view reference anchor to change")+ }+ fragmentTree, err := av.ParseValueTextRich(attrView.KeyValues[0].Values[0].Text.Rich)+ if nil != err {+ t.Fatal(err)+ }+ anchors := map[string]string{}+ marks := map[string]bool{}+ dynamicStyle := ""+ dynamicStyleIAL := false+ ast.Walk(fragmentTree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if !entering {+ return ast.WalkContinue+ }+ if treenode.IsBlockRef(node) {+ _, text, subtype := treenode.GetBlockRef(node)+ anchors[subtype] = text+ if "d" == subtype {+ marks["dynamic-block-ref"] = node.IsTextMarkType("block-ref") && node.IsTextMarkType("text")+ dynamicStyle = node.IALAttr("style")+ dynamicStyleIAL = nil != node.Next && ast.NodeKramdownSpanIAL == node.Next.Type+ }+ }+ for _, typ := range []string{"tag", "file-annotation-ref", "inline-memo"} {+ if node.IsTextMarkType(typ) || "tag" == typ && ast.NodeTag == node.Type ||+ "file-annotation-ref" == typ && ast.NodeFileAnnotationRef == node.Type {+ marks[typ] = true+ }+ }+ return ast.WalkContinue+ })+ if "New dynamic" != anchors["d"] {+ t.Fatalf("unexpected dynamic anchor: %q", anchors["d"])+ }+ if "Static anchor" != anchors["s"] {+ t.Fatalf("static anchor changed: %q", anchors["s"])+ }+ if !marks["dynamic-block-ref"] || refStyle != dynamicStyle || !dynamicStyleIAL {+ t.Fatalf("dynamic reference style was not preserved: types=%v, style=%q, IAL=%v",+ marks["dynamic-block-ref"], dynamicStyle, dynamicStyleIAL)+ }+ for _, typ := range []string{"tag", "file-annotation-ref", "inline-memo"} {+ if !marks[typ] {+ t.Fatalf("dynamic anchor refresh removed %s markup", typ)+ }+ }+ rich := attrView.KeyValues[0].Values[0].Text.Rich+ if _, err = av.NormalizeValueTextRich(rich); nil != err {+ t.Fatal(err)+ }+ normalized := rich.Content+ if _, err = av.NormalizeValueTextRich(rich); nil != err || normalized != rich.Content {+ t.Fatalf("updated styled dynamic reference is not stable, before=%q, after=%q, err=%v",+ normalized, rich.Content, err)+ }+}++func TestUpdateAttributeViewDynamicRefTextsIgnoresLegacyPlainText(t *testing.T) {+ const (+ defID = "20260904041000-def0001"+ literal = "((20260904041000-def0001 'Literal plain text'))"+ )+ attrView := &av.AttributeView{KeyValues: []*av.KeyValues{{+ Key: &av.Key{ID: "text", Type: av.KeyTypeText},+ Values: []*av.Value{{Type: av.KeyTypeText, Text: &av.ValueText{Content: literal}}},+ }}}+ defBlock := &ast.Node{Type: ast.NodeParagraph, ID: defID}+ defBlock.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("Updated")})++ if updateAttributeViewDynamicRefTexts(attrView, map[string]*ast.Node{defID: defBlock}) {+ t.Fatal("legacy plain text was treated as rich text")+ }+ if literal != attrView.KeyValues[0].Values[0].Text.Content {+ t.Fatalf("legacy plain text changed: %q", attrView.KeyValues[0].Values[0].Text.Content)+ }+}++func TestAttributeViewRefSourcesResolveCarrierAndDeduplicateMirrors(t *testing.T) {+ const (+ boxID = "20260904042000-box0001"+ rootID = "20260904042001-root001"+ attributeView = "20260904042002-av00001"+ firstBlockID = "20260904042003-db00001"+ secondBlockID = "20260904042004-db00002"+ )+ setupExportRelatedTest(t, boxID)+ setupAttributeViewRefI18n(t)+ if err := av.SaveAttributeView(av.NewAttributeView(attributeView)); nil != err {+ t.Fatal(err)+ }+ tree := newAttributeViewRefCarrierTestTree(boxID, rootID, attributeView, firstBlockID, secondBlockID)+ writeExportRelatedTestTree(t, tree)++ refs := []*sql.Ref{+ {Type: sql.AttributeViewRefType, BlockID: firstBlockID, RootID: rootID, Box: boxID, Path: tree.Path},+ {Type: sql.AttributeViewRefType, BlockID: secondBlockID, RootID: rootID, Box: boxID, Path: tree.Path},+ {Type: sql.AttributeViewRefType, BlockID: firstBlockID, RootID: rootID, Box: boxID, Path: "/stale.sy"},+ {Type: "textmark", BlockID: firstBlockID, RootID: rootID, Box: boxID, Path: tree.Path},+ }+ sources := attributeViewRefSources(refs)+ if 1 != len(sources) || attributeView != sources[0].avID || "" != sources[0].boxID {+ t.Fatalf("unexpected attribute view reference sources: %+v", sources)+ }+}diff --git a/kernel/model/attribute_view_ref_index.go b/kernel/model/attribute_view_ref_index.gonew file mode 100644index 0000000000..17bb45762b--- /dev/null+++ b/kernel/model/attribute_view_ref_index.go@@ -0,0 +1,127 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package model++import (+ "path"+ "strings"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode"+)++func queueAttributeViewRefIndex(avID, avBoxID string) {+ if "" == avID {+ return+ }+ attrView, err := av.ParseAttributeViewInBox(avID, avBoxID)+ if nil != err || nil == attrView || av.RichTextSpec > attrView.Spec {+ return+ }+ queueAttributeViewRefCarrierIndex(avID, avBoxID)+}++// queueExternalAttributeViewRefIndex 用于同步、历史和快照直接替换 AV 文件后的引用重建。+// 这里不能按当前规范版本跳过,因为旧的富文本文件可能被纯文本文件替换,需要删除既有引用。+func queueExternalAttributeViewRefIndex(avID, avBoxID string) {+ if "" == avID || ("" != avBoxID && !IsEncryptedBox(avBoxID)) {+ return+ }+ queueAttributeViewRefCarrierIndex(avID, avBoxID)+}++func queueAttributeViewRefCarrierIndex(avID, avBoxID string) {+ for _, tree := range attributeViewRefCarrierTrees(avID, avBoxID) {+ sql.UpdateRefsTreeQueue(tree)+ }+}++func queueExternalAttributeViewRefIndexByRepoPath(repoPath string) {+ avID, avBoxID, ok := parseAttributeViewRefRepoPath(repoPath)+ if !ok {+ return+ }+ queueExternalAttributeViewRefIndex(avID, avBoxID)+}++func parseAttributeViewRefRepoPath(repoPath string) (avID, avBoxID string, ok bool) {+ repoPath = "/" + strings.TrimPrefix(path.Clean(strings.ReplaceAll(repoPath, "\\", "/")), "/")+ parts := strings.Split(strings.TrimPrefix(repoPath, "/"), "/")+ switch {+ case 3 == len(parts) && "storage" == parts[0] && "av" == parts[1]:+ case 4 == len(parts) && ast.IsNodeIDPattern(parts[0]) && "storage" == parts[1] && "av" == parts[2]:+ avBoxID = parts[0]+ default:+ return "", "", false+ }+ filename := parts[len(parts)-1]+ if ".json" != path.Ext(filename) {+ return "", "", false+ }+ avID = strings.TrimSuffix(filename, ".json")+ if !ast.IsNodeIDPattern(avID) {+ return "", "", false+ }+ return avID, avBoxID, true+}++func attributeViewRefCarrierTrees(avID, avBoxID string) (ret []*parse.Tree) {+ queuedRootIDs := map[string]bool{}+ for _, blockID := range treenode.GetMirrorAttrViewBlockIDs(avID) {+ blockTree := attributeViewCarrierBlockTree(blockID, avBoxID)+ if nil == blockTree || !sameAttributeViewRefBoundary(avBoxID, blockTree.BoxID) || queuedRootIDs[blockTree.RootID] {+ continue+ }+ tree, err := LoadTreeByBlockIDInExactBox(blockID, attributeViewRefQueryBoxID(avBoxID))+ if nil != err || nil == tree {+ continue+ }+ databaseNode := treenode.GetNodeInTree(tree, blockID)+ if nil == databaseNode || ast.NodeAttributeView != databaseNode.Type || avID != databaseNode.AttributeViewID {+ continue+ }+ queuedRootIDs[tree.ID] = true+ ret = append(ret, tree)+ }+ return+}++func attributeViewCarrierBlockTree(blockID, avBoxID string) *treenode.BlockTree {+ if "" != avBoxID && IsEncryptedBox(avBoxID) {+ return treenode.GetBlockTreeInBox(blockID, avBoxID)+ }+ return treenode.GetBlockTreeInExactBox(blockID, "")+}++func attributeViewRefQueryBoxID(avBoxID string) string {+ if "" != avBoxID && IsEncryptedBox(avBoxID) {+ return avBoxID+ }+ return ""+}++func sameAttributeViewRefBoundary(avBoxID, carrierBoxID string) bool {+ avEncrypted := "" != avBoxID && IsEncryptedBox(avBoxID)+ carrierEncrypted := "" != carrierBoxID && IsEncryptedBox(carrierBoxID)+ if !avEncrypted && !carrierEncrypted {+ return true+ }+ return avEncrypted && carrierEncrypted && avBoxID == carrierBoxID+}diff --git a/kernel/model/attribute_view_ref_index_test.go b/kernel/model/attribute_view_ref_index_test.gonew file mode 100644index 0000000000..fcb6d7028b--- /dev/null+++ b/kernel/model/attribute_view_ref_index_test.go@@ -0,0 +1,170 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package model++import (+ "testing"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAttributeViewRefCarrierTreesUseEveryMirrorOnce(t *testing.T) {+ const (+ boxID = "20260904020000-box0001"+ attributeView = "20260904020001-av00001"+ firstRootID = "20260904020002-root001"+ secondRootID = "20260904020003-root002"+ firstBlockID = "20260904020004-db00001"+ secondBlockID = "20260904020005-db00002"+ thirdBlockID = "20260904020006-db00003"+ )+ setupExportRelatedTest(t, boxID)+ setupAttributeViewRefI18n(t)+ attrView := av.NewAttributeView(attributeView)+ if err := av.SaveAttributeView(attrView); nil != err {+ t.Fatal(err)+ }++ firstTree := newAttributeViewRefCarrierTestTree(boxID, firstRootID, attributeView, firstBlockID, secondBlockID)+ secondTree := newAttributeViewRefCarrierTestTree(boxID, secondRootID, attributeView, thirdBlockID)+ writeExportRelatedTestTree(t, firstTree)+ writeExportRelatedTestTree(t, secondTree)+ for _, blockID := range []string{firstBlockID, secondBlockID, thirdBlockID} {+ av.UpsertBlockRel(attributeView, blockID)+ }++ trees := attributeViewRefCarrierTrees(attributeView, "")+ if 2 != len(trees) {+ t.Fatalf("expected two unique carrier roots, got %d", len(trees))+ }+ roots := map[string]bool{}+ for _, tree := range trees {+ roots[tree.ID] = true+ }+ if !roots[firstRootID] || !roots[secondRootID] {+ t.Fatalf("unexpected carrier roots: %+v", roots)+ }+}++func TestAttributeViewRefCarrierTreesRequirePhysicalCarrier(t *testing.T) {+ const (+ boxID = "20260904021000-box0001"+ attributeView = "20260904021001-av00001"+ )+ setupExportRelatedTest(t, boxID)+ setupAttributeViewRefI18n(t)+ if err := av.SaveAttributeView(av.NewAttributeView(attributeView)); nil != err {+ t.Fatal(err)+ }++ if trees := attributeViewRefCarrierTrees(attributeView, ""); 0 != len(trees) {+ t.Fatalf("attribute view without a carrier produced index trees: %+v", trees)+ }+}++func TestSameAttributeViewRefBoundary(t *testing.T) {+ const (+ encryptedBox = "20260904022000-encbox1"+ otherEncryptedBox = "20260904022001-encbox2"+ normalBox = "20260904022002-box0001"+ )+ markRuntimeEncryptedBox(encryptedBox)+ markRuntimeEncryptedBox(otherEncryptedBox)+ t.Cleanup(func() {+ forgetRuntimeEncryptedBox(encryptedBox)+ forgetRuntimeEncryptedBox(otherEncryptedBox)+ })++ if !sameAttributeViewRefBoundary("", normalBox) {+ t.Fatal("global attribute views should allow normal notebook carriers")+ }+ if sameAttributeViewRefBoundary("", encryptedBox) {+ t.Fatal("global attribute views should reject encrypted notebook carriers")+ }+ if !sameAttributeViewRefBoundary(encryptedBox, encryptedBox) {+ t.Fatal("encrypted attribute views should allow carriers in the same notebook")+ }+ if sameAttributeViewRefBoundary(encryptedBox, otherEncryptedBox) {+ t.Fatal("encrypted attribute views should reject carriers in another encrypted notebook")+ }+ if sameAttributeViewRefBoundary(encryptedBox, normalBox) {+ t.Fatal("encrypted attribute views should reject normal notebook carriers")+ }+}++func TestParseAttributeViewRefRepoPath(t *testing.T) {+ const (+ avID = "20260904023000-av00001"+ boxID = "20260904023001-encbox1"+ )+ tests := []struct {+ name string+ path string+ wantAVID string+ wantBoxID string+ wantOK bool+ }{+ {name: "global", path: "/storage/av/" + avID + ".json", wantAVID: avID, wantOK: true},+ {name: "relative global", path: "storage/av/" + avID + ".json", wantAVID: avID, wantOK: true},+ {name: "encrypted", path: "/" + boxID + "/storage/av/" + avID + ".json", wantAVID: avID, wantBoxID: boxID, wantOK: true},+ {name: "windows separators", path: boxID + "\\storage\\av\\" + avID + ".json", wantAVID: avID, wantBoxID: boxID, wantOK: true},+ {name: "nested", path: "/backup/storage/av/" + avID + ".json"},+ {name: "invalid id", path: "/storage/av/not-an-id.json"},+ {name: "wrong extension", path: "/storage/av/" + avID + ".json.bak"},+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ gotAVID, gotBoxID, gotOK := parseAttributeViewRefRepoPath(test.path)+ if gotAVID != test.wantAVID || gotBoxID != test.wantBoxID || gotOK != test.wantOK {+ t.Fatalf("parse result = (%q, %q, %t), want (%q, %q, %t)", gotAVID, gotBoxID, gotOK,+ test.wantAVID, test.wantBoxID, test.wantOK)+ }+ })+ }+}++func setupAttributeViewRefI18n(t *testing.T) {+ t.Helper()+ originalLang, originalLangs := util.Lang, util.AttrViewLangs+ util.Lang = "en"+ util.AttrViewLangs = map[string]map[string]any{+ "en": {"key": "Key", "select": "Select", "table": "Table"},+ }+ t.Cleanup(func() {+ util.Lang, util.AttrViewLangs = originalLang, originalLangs+ })+}++func newAttributeViewRefCarrierTestTree(boxID, rootID, avID string, blockIDs ...string) *parse.Tree {+ tree := treenode.NewTree(boxID, "/"+rootID+".sy", "/Database", "Database")+ for nil != tree.Root.FirstChild {+ tree.Root.FirstChild.Unlink()+ }+ for _, blockID := range blockIDs {+ databaseNode := &ast.Node{+ Type: ast.NodeAttributeView, ID: blockID, AttributeViewID: avID,+ AttributeViewType: string(av.LayoutTypeTable),+ }+ databaseNode.SetIALAttr("id", blockID)+ tree.Root.AppendChild(databaseNode)+ }+ return tree+}diff --git a/kernel/model/attribute_view_render_test.go b/kernel/model/attribute_view_render_test.goindex 9f10f0c0e2..2a3c99d237 100644--- a/kernel/model/attribute_view_render_test.go+++ b/kernel/model/attribute_view_render_test.go@@ -83,7 +83,7 @@ func TestImmutableAttributeViewRenderDoesNotWrite(t *testing.T) {if nil != err {t.Fatal(err)}- if view.GetID() != attrView.Views[0].ID || attrView.Spec != av.CurrentSpec {+ if view.GetID() != attrView.Views[0].ID || attrView.Spec != av.PlainTextSpec {t.Fatalf("unexpected immutable render result: %s, spec %d", view.GetID(), attrView.Spec)}path := filepath.Join(util.DataDir, "storage", "av", attrView.ID+".json")diff --git a/kernel/model/attribute_view_rich_history_test.go b/kernel/model/attribute_view_rich_history_test.gonew file mode 100644index 0000000000..cf908c49d8--- /dev/null+++ b/kernel/model/attribute_view_rich_history_test.go@@ -0,0 +1,83 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package model++import "testing"++func TestDocDiffAttributeViewSignatureIncludesRichTextSource(t *testing.T) {+ left := []byte(`{+ "spec": 1,+ "id": "20260904010000-av00001",+ "keyValues": [{+ "key": {"id": "text", "type": "text"},+ "values": [{+ "type": "text",+ "text": {+ "content": "same projection",+ "rich": {"spec": 1, "format": "kramdown", "content": "**same projection**"}+ }+ }]+ }]+ }`)+ right := []byte(`{+ "spec": 1,+ "id": "20260904010000-av00001",+ "keyValues": [{+ "key": {"id": "text", "type": "text"},+ "values": [{+ "type": "text",+ "text": {+ "content": "same projection",+ "rich": {"spec": 1, "format": "kramdown", "content": "*same projection*"}+ }+ }]+ }]+ }`)++ if docDiffAttributeViewSignature(left) == docDiffAttributeViewSignature(right) {+ t.Fatal("expected rich text source changes to affect the attribute view history signature")+ }+}++func TestDocDiffAttributeViewSignatureKeepsLegacyAndRichTextDistinct(t *testing.T) {+ legacy := []byte(`{+ "spec": 1,+ "id": "20260904010000-av00001",+ "keyValues": [{+ "key": {"id": "text", "type": "text"},+ "values": [{"type": "text", "text": {"content": "**literal**"}}]+ }]+ }`)+ rich := []byte(`{+ "spec": 1,+ "id": "20260904010000-av00001",+ "keyValues": [{+ "key": {"id": "text", "type": "text"},+ "values": [{+ "type": "text",+ "text": {+ "content": "literal",+ "rich": {"spec": 1, "format": "kramdown", "content": "**literal**"}+ }+ }]+ }]+ }`)++ if docDiffAttributeViewSignature(legacy) == docDiffAttributeViewSignature(rich) {+ t.Fatal("expected legacy plain text and rich text payloads to remain distinct in attribute view history")+ }+}diff --git a/kernel/model/attribute_view_value_identity_test.go b/kernel/model/attribute_view_value_identity_test.goindex a4e49c483c..20d50b50fa 100644--- a/kernel/model/attribute_view_value_identity_test.go+++ b/kernel/model/attribute_view_value_identity_test.go@@ -217,3 +217,221 @@ func TestCheckAttrViewCorrectsValueKeyID(t *testing.T) {t.Fatalf("value key ID was not corrected: %s", value.KeyID)}}++func TestUpdateAttributeViewTextValuePreservesRichPayloadForUnchangedLegacyWrites(t *testing.T) {+ attrView, textValue, textKeyID, itemID := newAttributeViewRichTextUpdateTest()+ originalRichContent := textValue.Text.Rich.Content++ updated, err := updateAttributeViewValue(nil, attrView, textKeyID, itemID,+ &av.Value{Type: av.KeyTypeText, Text: &av.ValueText{Content: "old"}}, false)+ if nil != err {+ t.Fatal(err)+ }+ if updated != textValue || nil == updated.Text || "old" != updated.Text.Content || nil == updated.Text.Rich ||+ originalRichContent != updated.Text.Rich.Content {+ t.Fatalf("unchanged legacy write did not preserve rich text: value=%+v text=%+v rich=%+v", updated,+ updated.Text, updated.Text.Rich)+ }+}++func TestUpdateAttributeViewTextValueClearsRichPayloadForChangedLegacyWrites(t *testing.T) {+ attrView, textValue, textKeyID, itemID := newAttributeViewRichTextUpdateTest()++ updated, err := updateAttributeViewValue(nil, attrView, textKeyID, itemID,+ &av.Value{Type: av.KeyTypeText, Text: &av.ValueText{Content: "plain replacement"}}, false)+ if nil != err {+ t.Fatal(err)+ }+ if updated != textValue || nil == updated.Text || "plain replacement" != updated.Text.Content || nil != updated.Text.Rich {+ t.Fatalf("plain write did not replace rich text: %+v", updated)+ }+}++func TestUpdateAttributeViewTextValueExplicitlyClearsUnchangedRichPayload(t *testing.T) {+ attrView, textValue, textKeyID, itemID := newAttributeViewRichTextUpdateTest()++ updated, err := updateAttributeViewValue(nil, attrView, textKeyID, itemID, map[string]any{+ "text": map[string]any{+ "content": "old",+ "rich": nil,+ },+ }, false)+ if nil != err {+ t.Fatal(err)+ }+ if updated != textValue || nil == updated.Text || "old" != updated.Text.Content || nil != updated.Text.Rich {+ t.Fatalf("explicit rich null did not clear formatting: %+v", updated)+ }+}++func TestUpdateAttributeViewTextValueExplicitlyClearsRichWithoutContent(t *testing.T) {+ attrView, textValue, textKeyID, itemID := newAttributeViewRichTextUpdateTest()++ updated, err := updateAttributeViewValue(nil, attrView, textKeyID, itemID, map[string]any{+ "text": map[string]any{"rich": nil},+ }, false)+ if nil != err {+ t.Fatal(err)+ }+ if updated != textValue || nil == updated.Text || "old" != updated.Text.Content || nil != updated.Text.Rich {+ t.Fatalf("explicit rich null changed the plain text projection: %+v", updated)+ }+}++func TestUpdateAttributeViewTextValuePreservesOmittedFields(t *testing.T) {+ tests := []struct {+ name string+ data any+ }{+ {name: "value fields omitted", data: map[string]any{"type": av.KeyTypeText}},+ {name: "empty text object", data: map[string]any{"text": map[string]any{}}},+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ attrView, textValue, textKeyID, itemID := newAttributeViewRichTextUpdateTest()+ originalCreatedAt := textValue.CreatedAt++ updated, err := updateAttributeViewValue(nil, attrView, textKeyID, itemID, test.data, false)+ if nil != err {+ t.Fatal(err)+ }+ if updated != textValue || nil == updated.Text || "old" != updated.Text.Content || nil == updated.Text.Rich ||+ originalCreatedAt != updated.CreatedAt {+ t.Fatalf("partial text update discarded stored fields: %+v", updated)+ }+ })+ }+}++func TestUpdateAttributeViewTextValueNormalizesRichProjection(t *testing.T) {+ attrView, textValue, textKeyID, itemID := newAttributeViewRichTextUpdateTest()++ updated, err := updateAttributeViewValue(nil, attrView, textKeyID, itemID, &av.Value{+ Type: av.KeyTypeText,+ Text: &av.ValueText{+ Content: "untrusted projection",+ Rich: &av.ValueTextRich{+ Spec: av.ValueTextRichSpec,+ Format: av.ValueTextRichFormatKramdown,+ Content: "**updated** text",+ },+ },+ }, false)+ if nil != err {+ t.Fatal(err)+ }+ if updated != textValue || nil == updated.Text || "updated text" != updated.Text.Content || nil == updated.Text.Rich {+ t.Fatalf("rich write was not normalized: %+v", updated)+ }+}++func TestUpdateAttributeViewTextValueRejectsInvalidRichPayloadWithoutMutation(t *testing.T) {+ attrView, textValue, textKeyID, itemID := newAttributeViewRichTextUpdateTest()+ originalText := textValue.Text++ _, err := updateAttributeViewValue(nil, attrView, textKeyID, itemID, &av.Value{+ Type: av.KeyTypeText,+ Text: &av.ValueText{Rich: &av.ValueTextRich{+ Spec: av.ValueTextRichSpec + 1,+ Format: av.ValueTextRichFormatKramdown,+ Content: "invalid",+ }},+ }, false)+ if nil == err {+ t.Fatal("invalid rich payload was accepted")+ }+ if textValue.Text != originalText || "old" != textValue.Text.Content || nil == textValue.Text.Rich {+ t.Fatalf("invalid rich write mutated the stored value: %+v", textValue)+ }+}++func TestUpdateAttributeViewTextValueRejectsInvalidRichPayloadWithoutCreatingMissingCell(t *testing.T) {+ for _, useContext := range []bool{false, true} {+ name := "without context"+ if useContext {+ name = "with context"+ }+ t.Run(name, func(t *testing.T) {+ const (+ blockKeyID = "20260904130000-blockky"+ textKeyID = "20260904130001-textkey"+ itemID = "20260904130002-item001"+ )+ blockValue := &av.Value{+ BlockID: itemID,+ Type: av.KeyTypeBlock,+ Block: &av.ValueBlock{},+ }+ textKeyValues := &av.KeyValues{Key: &av.Key{ID: textKeyID, Type: av.KeyTypeText}}+ attrView := &av.AttributeView{KeyValues: []*av.KeyValues{+ {Key: &av.Key{ID: blockKeyID, Type: av.KeyTypeBlock}, Values: []*av.Value{blockValue}},+ textKeyValues,+ }}+ var context *attrViewValueUpdateContext+ if useContext {+ context = newAttrViewValueUpdateContext(attrView)+ }++ _, err := updateAttributeViewValue0(nil, attrView, textKeyID, itemID, &av.Value{+ Type: av.KeyTypeText,+ Text: &av.ValueText{Rich: &av.ValueTextRich{+ Spec: av.ValueTextRichSpec + 1,+ Format: av.ValueTextRichFormatKramdown,+ Content: "invalid",+ }},+ }, false, context)+ if nil == err {+ t.Fatal("invalid rich payload was accepted")+ }+ if 0 != len(textKeyValues.Values) {+ t.Fatalf("invalid rich write created a missing cell: %+v", textKeyValues.Values)+ }+ if nil != context {+ if 0 != len(context.values[textKeyID]) || nil != context.values[textKeyID][itemID] {+ t.Fatalf("invalid rich write registered a missing cell in the update context: %+v",+ context.values[textKeyID])+ }+ if context.keyValues[textKeyID] != textKeyValues || context.blockValues[itemID] != blockValue {+ t.Fatal("invalid rich write changed existing update context indexes")+ }+ }+ })+ }+}++func newAttributeViewRichTextUpdateTest() (attrView *av.AttributeView, textValue *av.Value, textKeyID, itemID string) {+ const (+ blockKeyID = "20260904120000-blockky"+ keyID = "20260904120001-textkey"+ rowID = "20260904120002-item001"+ )+ textValue = &av.Value{+ ID: "20260904120003-value01",+ KeyID: keyID,+ BlockID: rowID,+ Type: av.KeyTypeText,+ Text: &av.ValueText{+ Content: "old",+ Rich: &av.ValueTextRich{+ Spec: av.ValueTextRichSpec,+ Format: av.ValueTextRichFormatKramdown,+ Content: `<span data-type="strong">old</span>`,+ },+ },+ }+ attrView = &av.AttributeView{KeyValues: []*av.KeyValues{+ {+ Key: &av.Key{ID: blockKeyID, Type: av.KeyTypeBlock},+ Values: []*av.Value{{+ BlockID: rowID,+ Type: av.KeyTypeBlock,+ Block: &av.ValueBlock{},+ }},+ },+ {+ Key: &av.Key{ID: keyID, Type: av.KeyTypeText},+ Values: []*av.Value{textValue},+ },+ }}+ return attrView, textValue, keyID, rowID+}diff --git a/kernel/model/export.go b/kernel/model/export.goindex d25ba2c6d3..1b217da23d 100644--- a/kernel/model/export.go+++ b/kernel/model/export.go@@ -2934,7 +2934,7 @@ func exportAv(avID, boxID, exportStorageAvDir, exportFolder string, assetPathMap}func copyExportAttributeViewAssets(attrView *av.AttributeView, boxID, exportFolder string, assetPathMap map[string]string) {- // 导出资源文件列和指向本地资源的 URL 列 https://github.com/siyuan-note/siyuan/issues/9919+ // 导出资源文件列、指向本地资源的 URL 列和富文本中的本地资源 https://github.com/siyuan-note/siyuan/issues/9919for _, assetPath := range getAttributeViewAssetsLinkDests(attrView, false, nil) {destPath := filepath.Join(exportFolder, AssetPathWithoutQuery(assetPath))srcPath := ""diff --git a/kernel/model/filesys_init.go b/kernel/model/filesys_init.goindex 06adb7a398..8fc07f66fb 100644--- a/kernel/model/filesys_init.go+++ b/kernel/model/filesys_init.go@@ -44,6 +44,7 @@ func init() {}return bt.BoxID}+ av.AttributeViewSaved = queueAttributeViewRefIndexsql.IsEncryptedBoxFn = IsEncryptedBoxsql.IsBoxUnlockedFn = isBoxUnlockedForAccesstreenode.IsEncryptedBoxFn = IsEncryptedBoxdiff --git a/kernel/model/history.go b/kernel/model/history.goindex 83a00dc777..6bdd7d4ee1 100644--- a/kernel/model/history.go+++ b/kernel/model/history.go@@ -680,7 +680,13 @@ func RollbackAttributeViewHistory(historyPath string) (err error) {logging.LogErrorf("copy file [%s] to [%s] failed: %s", from, to, err)return}- cache.RemoveAVData(strings.TrimSuffix(filepath.Base(historyPath), ".json"))+ avID := strings.TrimSuffix(filepath.Base(historyPath), ".json")+ cache.RemoveAVData(avID)+ avBoxID := ""+ if len(pathParts) >= 2 && IsEncryptedBox(pathParts[1]) {+ avBoxID = pathParts[1]+ }+ queueExternalAttributeViewRefIndex(avID, avBoxID)IncSync()util.PushMsg(Conf.Language(102), 3000)return nildiff --git a/kernel/model/push_reload.go b/kernel/model/push_reload.goindex 3502fe0010..f3558029a7 100644--- a/kernel/model/push_reload.go+++ b/kernel/model/push_reload.go@@ -368,10 +368,15 @@ func refreshDynamicRefTexts0(updatedDefNodes map[string]*ast.Node, updatedTreestreeRefNodeIDs := map[string]*hashset.Set{}var changedNodes []*ast.Nodevar refs []*sql.Ref+ var attributeViewRefs []*sql.Reffor _, updateNode := range updatedDefNodes {boxID := updatedNodeBoxID(updateNode, updatedTrees)refs, changedNodes = getRefsCacheByDefNode(updateNode, boxID)for _, ref := range refs {+ if sql.AttributeViewRefType == ref.Type {+ attributeViewRefs = append(attributeViewRefs, ref)+ continue+ }if refIDs, ok := treeRefNodeIDs[ref.RootID]; !ok {refIDs = hashset.New()refIDs.Add(ref.BlockID)@@ -384,6 +389,7 @@ func refreshDynamicRefTexts0(updatedDefNodes map[string]*ast.Node, updatedTreesfor _, n := range changedNodes {updatedDefNodes[n.ID] = n}+ refreshAttributeViewDynamicRefTexts(updatedDefNodes, attributeViewRefs)changedRefTree := map[string]*parse.Tree{}diff --git a/kernel/model/repository.go b/kernel/model/repository.goindex 197d8d4bec..6572eccaba 100644--- a/kernel/model/repository.go+++ b/kernel/model/repository.go@@ -382,6 +382,7 @@ func RollbackRepoSnapshotFile(fileID string) (err error) {if strings.Contains(file.Path, "/storage/av/") && strings.HasSuffix(file.Path, ".json") {avID := strings.TrimSuffix(filepath.Base(file.Path), ".json")cache.RemoveAVData(avID)+ queueExternalAttributeViewRefIndexByRepoPath(file.Path)ReloadAttrView(avID)}@@ -2306,6 +2307,7 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,// 有数据变更,需要重建索引var upserts, removes []string+ changedAttributeViewPaths := map[string]bool{}var upsertTrees int// 可能需要重新加载部分功能var needReloadFlashcard, needReloadInlineStyles, needReloadOcrTexts, needReloadPlugin, needReloadSnippet bool@@ -2376,6 +2378,7 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,if strings.Contains(file.Path, "/storage/av/") && strings.HasSuffix(file.Path, ".json") {cache.RemoveAVData(strings.TrimSuffix(filepath.Base(file.Path), ".json"))+ changedAttributeViewPaths[file.Path] = true}}@@ -2457,6 +2460,7 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,if strings.Contains(file.Path, "/storage/av/") && strings.HasSuffix(file.Path, ".json") {cache.RemoveAVData(strings.TrimSuffix(filepath.Base(file.Path), ".json"))+ changedAttributeViewPaths[file.Path] = true}}@@ -2543,6 +2547,9 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,}upsertRootIDs, removeRootIDs := incReindex(upserts, removes)+ for changedPath := range changedAttributeViewPaths {+ queueExternalAttributeViewRefIndexByRepoPath(changedPath)+ }needReloadFiletree = !needReloadUI && (needReloadFiletree || 0 < len(upsertRootIDs) || 0 < len(removeRootIDs))if needReloadFiletree {ReloadFiletree()diff --git a/kernel/sql/attribute_view_ref.go b/kernel/sql/attribute_view_ref.gonew file mode 100644index 0000000000..6843a9bc8f--- /dev/null+++ b/kernel/sql/attribute_view_ref.go@@ -0,0 +1,108 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package sql++import (+ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/treenode"+)++const AttributeViewRefType = "av"++func attributeViewRefsFromNode(tree *parse.Tree, databaseNode *ast.Node) (ret []*Ref) {+ if nil == tree || nil == databaseNode || ast.NodeAttributeView != databaseNode.Type ||+ "" == databaseNode.ID || "" == databaseNode.AttributeViewID {+ return+ }++ avBoxID := attributeViewRefStorageBoxID(tree.Box)+ attrView, err := av.ParseAttributeViewInBox(databaseNode.AttributeViewID, avBoxID)+ if nil != err || nil == attrView {+ return+ }+ return attributeViewRefs(tree, databaseNode, attrView)+}++func attributeViewRefStorageBoxID(carrierBoxID string) string {+ if nil != IsEncryptedBoxFn && IsEncryptedBoxFn(carrierBoxID) {+ return carrierBoxID+ }+ return ""+}++func attributeViewRefs(tree *parse.Tree, databaseNode *ast.Node, attrView *av.AttributeView) (ret []*Ref) {+ if nil == tree || nil == databaseNode || nil == attrView {+ return+ }++ for _, keyValues := range attrView.KeyValues {+ if nil == keyValues || nil == keyValues.Key || av.KeyTypeText != keyValues.Key.Type {+ continue+ }+ for _, value := range keyValues.Values {+ if nil == value || nil == value.Text || !value.Text.IsRich() || "" == value.Text.Rich.Content {+ continue+ }+ fragmentTree, err := av.ParseValueTextRich(value.Text.Rich)+ if nil != err || nil == fragmentTree || nil == fragmentTree.Root {+ continue+ }+ ast.Walk(fragmentTree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if !entering || !treenode.IsBlockRef(node) {+ return ast.WalkContinue+ }+ ref := buildAttributeViewRef(tree, databaseNode, node)+ if "" != ref.DefBlockID && !isRepeatedRef(ret, ref) {+ ret = append(ret, ref)+ }+ return ast.WalkContinue+ })+ }+ }+ return+}++func buildAttributeViewRef(tree *parse.Tree, databaseNode, refNode *ast.Node) *Ref {+ tmpType := refNode.TextMarkType+ refNode.TextMarkType = "block-ref"+ markdown := treenode.ExportNodeStdMd(refNode, luteEngine)+ refNode.TextMarkType = tmpType++ defBlockID, text, _ := treenode.GetBlockRef(refNode)+ var defBlockParentID, defBlockRootID, defBlockPath string+ if defBlock := treenode.GetBlockTreeInBox(defBlockID, tree.Box); nil != defBlock {+ defBlockParentID = defBlock.ParentID+ defBlockRootID = defBlock.RootID+ defBlockPath = defBlock.Path+ }+ return &Ref{+ ID: ast.NewNodeID(),+ DefBlockID: defBlockID,+ DefBlockParentID: defBlockParentID,+ DefBlockRootID: defBlockRootID,+ DefBlockPath: defBlockPath,+ BlockID: databaseNode.ID,+ RootID: tree.ID,+ Box: tree.Box,+ Path: tree.Path,+ Content: text,+ Markdown: markdown,+ Type: AttributeViewRefType,+ }+}diff --git a/kernel/sql/attribute_view_ref_cache_test.go b/kernel/sql/attribute_view_ref_cache_test.gonew file mode 100644index 0000000000..06d0f8d8dc--- /dev/null+++ b/kernel/sql/attribute_view_ref_cache_test.go@@ -0,0 +1,367 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package sql++import (+ "testing"+ "time"++ "github.com/88250/lute/parse"+)++func TestRemoveRefCacheByPathEvictsWholeDefinition(t *testing.T) {+ originalIsEncryptedBoxFn, originalIsBoxUnlockedFn := IsEncryptedBoxFn, IsBoxUnlockedFn+ IsEncryptedBoxFn = func(string) bool { return false }+ IsBoxUnlockedFn = func(string) bool { return true }+ clearRefCache()+ t.Cleanup(func() {+ clearRefCache()+ IsEncryptedBoxFn, IsBoxUnlockedFn = originalIsEncryptedBoxFn, originalIsBoxUnlockedFn+ })++ const (+ definitionID = "20260904030000-def0001"+ boxID = "20260904030001-box0001"+ targetPath = "/20260904030002-root001.sy"+ otherPath = "/20260904030003-root002.sy"+ )+ putRefCache(boxID, &Ref{+ DefBlockID: definitionID, BlockID: "target", RootID: "target-root", Box: boxID, Path: targetPath,+ })+ putRefCache(boxID, &Ref{+ DefBlockID: definitionID, BlockID: "other", RootID: "other-root", Box: boxID, Path: otherPath,+ })++ removeRefCacheByPath(boxID, targetPath)+ if _, ok := defIDRefsCache.Get(refCacheKey(definitionID, boxID)); ok {+ t.Fatal("path invalidation left a partial definition cache entry")+ }+}++func TestRefCachePartialPutMergesCompleteDatabaseResult(t *testing.T) {+ const (+ boxID = "20260904030500-encbox1"+ definitionID = "20260904030501-def0001"+ )+ originalIsEncryptedBoxFn, originalIsBoxUnlockedFn := IsEncryptedBoxFn, IsBoxUnlockedFn+ IsEncryptedBoxFn = func(candidate string) bool { return boxID == candidate }+ IsBoxUnlockedFn = func(candidate string) bool { return boxID == candidate }+ clearRefCache()+ t.Cleanup(func() {+ clearRefCache()+ IsEncryptedBoxFn, IsBoxUnlockedFn = originalIsEncryptedBoxFn, originalIsBoxUnlockedFn+ })++ pending := &Ref{DefBlockID: definitionID, BlockID: "pending", Box: boxID, Path: "/a.sy"}+ stored := &Ref{DefBlockID: definitionID, BlockID: "stored", Box: boxID, Path: "/b.sy"}+ putRefCache(boxID, pending)+ queryCalls := 0+ refs := getRefsCacheByDefIDInBox(definitionID, boxID, func(string, bool, string) []*Ref {+ queryCalls+++ return []*Ref{stored}+ })+ if 2 != len(refs) || nil == refsByBlockID(refs)[pending.BlockID] || nil == refsByBlockID(refs)[stored.BlockID] {+ t.Fatalf("partial cache did not merge the complete database result: %+v", refs)+ }+ refs = getRefsCacheByDefIDInBox(definitionID, boxID, func(string, bool, string) []*Ref {+ queryCalls+++ return nil+ })+ if 1 != queryCalls || 2 != len(refs) {+ t.Fatalf("merged complete cache was not reused: calls=%d refs=%+v", queryCalls, refs)+ }+}++func TestRefCachePathReindexReloadsCompleteDefinition(t *testing.T) {+ const (+ boxID = "20260904030700-encbox1"+ definitionID = "20260904030701-def0001"+ pathA = "/a.sy"+ pathB = "/b.sy"+ )+ originalIsEncryptedBoxFn, originalIsBoxUnlockedFn := IsEncryptedBoxFn, IsBoxUnlockedFn+ IsEncryptedBoxFn = func(candidate string) bool { return boxID == candidate }+ IsBoxUnlockedFn = func(candidate string) bool { return boxID == candidate }+ clearRefCache()+ t.Cleanup(func() {+ clearRefCache()+ IsEncryptedBoxFn, IsBoxUnlockedFn = originalIsEncryptedBoxFn, originalIsBoxUnlockedFn+ })++ oldA := &Ref{DefBlockID: definitionID, BlockID: "a", Box: boxID, Path: pathA, Content: "old"}+ refB := &Ref{DefBlockID: definitionID, BlockID: "b", Box: boxID, Path: pathB}+ getRefsCacheByDefIDInBox(definitionID, boxID, func(string, bool, string) []*Ref {+ return []*Ref{oldA, refB}+ })+ removeRefCacheByPath(boxID, pathA)+ if _, ok := defIDRefsCache.Get(refCacheKey(definitionID, boxID)); ok {+ t.Fatal("path invalidation retained an incomplete definition cache")+ }++ newA := &Ref{DefBlockID: definitionID, BlockID: "a", Box: boxID, Path: pathA, Content: "new"}+ queryCalls := 0+ refs := getRefsCacheByDefIDInBox(definitionID, boxID, func(string, bool, string) []*Ref {+ queryCalls+++ return []*Ref{newA, refB}+ })+ byBlockID := refsByBlockID(refs)+ if 2 != len(refs) || "new" != byBlockID["a"].Content || nil == byBlockID["b"] {+ t.Fatalf("reindexed definition cache is incomplete: %+v", refs)+ }+ refs = getRefsCacheByDefIDInBox(definitionID, boxID, func(string, bool, string) []*Ref {+ queryCalls+++ return nil+ })+ if 1 != queryCalls || 2 != len(refs) {+ t.Fatalf("complete reindexed cache was not reused: calls=%d refs=%+v", queryCalls, refs)+ }+}++func TestFailedRefQueueOperationClearsPendingCache(t *testing.T) {+ const (+ boxID = "20260904030900-encbox1"+ definitionID = "20260904030901-def0001"+ pathA = "/a.sy"+ pathB = "/b.sy"+ )+ originalIsEncryptedBoxFn, originalIsBoxUnlockedFn := IsEncryptedBoxFn, IsBoxUnlockedFn+ IsEncryptedBoxFn = func(candidate string) bool { return boxID == candidate }+ IsBoxUnlockedFn = func(candidate string) bool { return boxID == candidate }+ clearRefCache()+ t.Cleanup(func() {+ clearRefCache()+ IsEncryptedBoxFn, IsBoxUnlockedFn = originalIsEncryptedBoxFn, originalIsBoxUnlockedFn+ })++ oldA := &Ref{DefBlockID: definitionID, BlockID: "a", Box: boxID, Path: pathA, Content: "old"}+ refB := &Ref{DefBlockID: definitionID, BlockID: "b", Box: boxID, Path: pathB}+ getRefsCacheByDefIDInBox(definitionID, boxID, func(string, bool, string) []*Ref {+ return []*Ref{oldA, refB}+ })+ removeRefCacheByPath(boxID, pathA)+ putRefCache(boxID, &Ref{+ DefBlockID: definitionID, BlockID: "a", Box: boxID, Path: pathA, Content: "uncommitted",+ })+ getRefsCacheByDefIDInBox(definitionID, boxID, func(string, bool, string) []*Ref {+ return []*Ref{oldA, refB}+ })+ invalidateRefsCacheForOperation(&dbQueueOperation{+ action: "update_refs", upsertTree: &parse.Tree{Box: boxID, Path: pathA},+ })++ queryCalls := 0+ refs := getRefsCacheByDefIDInBox(definitionID, boxID, func(string, bool, string) []*Ref {+ queryCalls+++ return []*Ref{oldA, refB}+ })+ byBlockID := refsByBlockID(refs)+ if 1 != queryCalls || 2 != len(refs) || "old" != byBlockID["a"].Content || nil == byBlockID["b"] {+ t.Fatalf("failed operation cache did not return to database state: calls=%d refs=%+v", queryCalls, refs)+ }+}++func refsByBlockID(refs []*Ref) map[string]*Ref {+ ret := make(map[string]*Ref, len(refs))+ for _, ref := range refs {+ if nil != ref {+ ret[ref.BlockID] = ref+ }+ }+ return ret+}++func TestRemoveRefCacheByPathUsesEncryptedScope(t *testing.T) {+ const encryptedBoxID = "20260904031000-encbox1"+ originalIsEncryptedBoxFn, originalIsBoxUnlockedFn := IsEncryptedBoxFn, IsBoxUnlockedFn+ IsEncryptedBoxFn = func(boxID string) bool { return encryptedBoxID == boxID }+ IsBoxUnlockedFn = func(boxID string) bool { return encryptedBoxID == boxID }+ clearRefCache()+ t.Cleanup(func() {+ clearRefCache()+ IsEncryptedBoxFn, IsBoxUnlockedFn = originalIsEncryptedBoxFn, originalIsBoxUnlockedFn+ })++ const definitionID = "20260904031001-def0001"+ putRefCache(encryptedBoxID, &Ref{+ DefBlockID: definitionID, BlockID: "carrier", RootID: "root", Box: encryptedBoxID, Path: "/root.sy",+ })+ removeRefCacheByPath(encryptedBoxID, "/root.sy")+ if _, ok := defIDRefsCache.Get(refCacheKey(definitionID, encryptedBoxID)); ok {+ t.Fatal("encrypted carrier reference remained cached after reindexing")+ }+}++func TestRefCacheLateQueryDoesNotRepopulateInvalidatedScope(t *testing.T) {+ const (+ boxID = "20260904032000-encbox1"+ definitionID = "20260904032001-def0001"+ path = "/20260904032002-root001.sy"+ )+ originalIsEncryptedBoxFn, originalIsBoxUnlockedFn := IsEncryptedBoxFn, IsBoxUnlockedFn+ IsEncryptedBoxFn = func(candidate string) bool { return boxID == candidate }+ IsBoxUnlockedFn = func(candidate string) bool { return boxID == candidate }+ clearRefCache()+ t.Cleanup(func() {+ clearRefCache()+ IsEncryptedBoxFn, IsBoxUnlockedFn = originalIsEncryptedBoxFn, originalIsBoxUnlockedFn+ })++ stale := &Ref{DefBlockID: definitionID, BlockID: "stale", Box: boxID, Path: path}+ queryStarted := make(chan struct{})+ allowQueryReturn := make(chan struct{})+ result := make(chan []*Ref, 1)+ go func() {+ result <- getRefsCacheByDefIDInBox(definitionID, boxID,+ func(string, bool, string) []*Ref {+ close(queryStarted)+ <-allowQueryReturn+ return []*Ref{stale}+ })+ }()++ select {+ case <-queryStarted:+ case <-time.After(3 * time.Second):+ t.Fatal("reference cache query did not start")+ }+ removeRefCacheByPath(boxID, path)+ close(allowQueryReturn)+ select {+ case refs := <-result:+ if 1 != len(refs) || "stale" != refs[0].BlockID {+ t.Fatalf("unexpected in-flight query result: %+v", refs)+ }+ case <-time.After(3 * time.Second):+ t.Fatal("reference cache query did not finish")+ }++ if _, ok := defIDRefsCache.Get(refCacheKey(definitionID, boxID)); ok {+ t.Fatal("late query repopulated an invalidated reference cache scope")+ }+ fresh := &Ref{DefBlockID: definitionID, BlockID: "fresh", Box: boxID, Path: path}+ queryCalls := 0+ refs := getRefsCacheByDefIDInBox(definitionID, boxID, func(string, bool, string) []*Ref {+ queryCalls+++ return []*Ref{fresh}+ })+ if 1 != len(refs) || "fresh" != refs[0].BlockID {+ t.Fatalf("fresh query result was not cached: %+v", refs)+ }+ refs = getRefsCacheByDefIDInBox(definitionID, boxID, func(string, bool, string) []*Ref {+ queryCalls+++ return nil+ })+ if 1 != queryCalls || 1 != len(refs) || "fresh" != refs[0].BlockID {+ t.Fatalf("fresh cache was not reused: calls=%d refs=%+v", queryCalls, refs)+ }+}++func TestRefCacheLateQueryDoesNotOverwriteAuthoritativePut(t *testing.T) {+ const (+ boxID = "20260904032500-encbox1"+ definitionID = "20260904032501-def0001"+ path = "/20260904032502-root001.sy"+ blockID = "20260904032503-block01"+ )+ originalIsEncryptedBoxFn, originalIsBoxUnlockedFn := IsEncryptedBoxFn, IsBoxUnlockedFn+ IsEncryptedBoxFn = func(candidate string) bool { return boxID == candidate }+ IsBoxUnlockedFn = func(candidate string) bool { return boxID == candidate }+ clearRefCache()+ t.Cleanup(func() {+ clearRefCache()+ IsEncryptedBoxFn, IsBoxUnlockedFn = originalIsEncryptedBoxFn, originalIsBoxUnlockedFn+ })++ queryStarted := make(chan struct{})+ allowQueryReturn := make(chan struct{})+ result := make(chan []*Ref, 1)+ go func() {+ result <- getRefsCacheByDefIDInBox(definitionID, boxID,+ func(string, bool, string) []*Ref {+ close(queryStarted)+ <-allowQueryReturn+ return []*Ref{{+ DefBlockID: definitionID, BlockID: blockID, Box: boxID, Path: path, Content: "stale",+ }}+ })+ }()++ select {+ case <-queryStarted:+ case <-time.After(3 * time.Second):+ t.Fatal("reference cache query did not start")+ }+ putRefCache(boxID, &Ref{+ DefBlockID: definitionID, BlockID: blockID, Box: boxID, Path: path, Content: "fresh",+ })+ close(allowQueryReturn)+ select {+ case <-result:+ case <-time.After(3 * time.Second):+ t.Fatal("reference cache query did not finish")+ }++ item, ok := defIDRefsCache.Get(refCacheKey(definitionID, boxID))+ if !ok {+ t.Fatal("authoritative reference cache entry is missing")+ }+ entry := item.(*refCacheEntry)+ if nil == entry.refs[blockID] || "fresh" != entry.refs[blockID].Content {+ t.Fatalf("late query overwrote pending cache entry: %+v", entry.refs)+ }+}++func TestRefCacheInvalidationGenerations(t *testing.T) {+ const (+ boxA = "20260904033000-encbox1"+ boxB = "20260904033001-encbox2"+ definitionID = "20260904033002-def0001"+ )+ originalIsEncryptedBoxFn, originalIsBoxUnlockedFn := IsEncryptedBoxFn, IsBoxUnlockedFn+ IsEncryptedBoxFn = func(candidate string) bool { return boxA == candidate || boxB == candidate }+ IsBoxUnlockedFn = func(candidate string) bool { return boxA == candidate || boxB == candidate }+ clearRefCache()+ t.Cleanup(func() {+ clearRefCache()+ IsEncryptedBoxFn, IsBoxUnlockedFn = originalIsEncryptedBoxFn, originalIsBoxUnlockedFn+ })++ beforeA, beforeB := getRefCacheGeneration(boxA), getRefCacheGeneration(boxB)+ removeRefCacheByPath(boxB, "/root.sy")+ afterA, afterB := getRefCacheGeneration(boxA), getRefCacheGeneration(boxB)+ if beforeA != afterA {+ t.Fatalf("invalidating another encrypted scope changed generation A: before=%+v after=%+v", beforeA, afterA)+ }+ if beforeB.global != afterB.global || beforeB.scope == afterB.scope {+ t.Fatalf("path invalidation did not advance only scope B: before=%+v after=%+v", beforeB, afterB)+ }++ beforeGlobal := getRefCacheGeneration(boxA)+ removeRefCacheByDefID(definitionID)+ afterGlobal := getRefCacheGeneration(boxA)+ if beforeGlobal.global == afterGlobal.global {+ t.Fatalf("definition invalidation did not advance global generation: before=%+v after=%+v",+ beforeGlobal, afterGlobal)+ }++ beforeGlobal = getRefCacheGeneration(boxA)+ clearRefCache()+ afterGlobal = getRefCacheGeneration(boxA)+ if beforeGlobal.global == afterGlobal.global {+ t.Fatalf("cache clear did not advance global generation: before=%+v after=%+v", beforeGlobal, afterGlobal)+ }+}diff --git a/kernel/sql/attribute_view_ref_test.go b/kernel/sql/attribute_view_ref_test.gonew file mode 100644index 0000000000..4d865ede32--- /dev/null+++ b/kernel/sql/attribute_view_ref_test.go@@ -0,0 +1,165 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package sql++import (+ "testing"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/cache"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestRefsFromTreeIncludesAttributeViewRichTextReferences(t *testing.T) {+ const (+ rootID = "20260904009000-root001"+ databaseID = "20260904009001-db00001"+ defID = "20260904009002-def0001"+ attributeView = "20260904009003-av00001"+ )+ originalDataDir, originalLang, originalLangs := util.DataDir, util.Lang, util.AttrViewLangs+ util.DataDir = t.TempDir()+ util.Lang = "en"+ util.AttrViewLangs = map[string]map[string]any{+ "en": {"key": "Key", "select": "Select", "table": "Table"},+ }+ t.Cleanup(func() {+ cache.RemoveAVData(attributeView)+ util.DataDir, util.Lang, util.AttrViewLangs = originalDataDir, originalLang, originalLangs+ })++ attrView := av.NewAttributeView(attributeView)+ textKey := &av.Key{ID: "text", Type: av.KeyTypeText}+ attrView.KeyValues = append(attrView.KeyValues, &av.KeyValues{+ Key: textKey,+ Values: []*av.Value{{Type: av.KeyTypeText, Text: &av.ValueText{+ Rich: &av.ValueTextRich{+ Spec: av.ValueTextRichSpec, Format: av.ValueTextRichFormatKramdown,+ Content: "((" + defID + " \"Reference\"))",+ },+ }}},+ })+ if err := av.SaveAttributeView(attrView); nil != err {+ t.Fatal(err)+ }++ root := &ast.Node{Type: ast.NodeDocument, ID: rootID}+ databaseNode := &ast.Node{Type: ast.NodeAttributeView, ID: databaseID, AttributeViewID: attributeView}+ root.AppendChild(databaseNode)+ tree := &parse.Tree{Root: root, ID: rootID, Box: "20260904009004-box0001", Path: "/" + rootID + ".sy"}+ refs, _ := refsFromTree(tree)+ if 1 != len(refs) || defID != refs[0].DefBlockID || databaseID != refs[0].BlockID || AttributeViewRefType != refs[0].Type {+ t.Fatalf("unexpected attribute view references: %+v", refs)+ }+}++func TestAttributeViewRefsUseCarrierDatabaseBlock(t *testing.T) {+ const (+ rootID = "20260904010000-root001"+ databaseID = "20260904010001-db00001"+ firstDefID = "20260904010002-def0001"+ secondDefID = "20260904010003-def0002"+ attributeView = "20260904010004-av00001"+ )+ tree := &parse.Tree{+ Root: &ast.Node{Type: ast.NodeDocument, ID: rootID},+ ID: rootID,+ Box: "20260904010005-box0001",+ Path: "/" + rootID + ".sy",+ HPath: "/Database",+ }+ databaseNode := &ast.Node{Type: ast.NodeAttributeView, ID: databaseID, AttributeViewID: attributeView}+ attrView := &av.AttributeView{KeyValues: []*av.KeyValues{+ {+ Key: &av.Key{ID: "text", Type: av.KeyTypeText},+ Values: []*av.Value{{Type: av.KeyTypeText, Text: &av.ValueText{+ Content: "First and second",+ Rich: &av.ValueTextRich{+ Spec: av.ValueTextRichSpec, Format: av.ValueTextRichFormatKramdown,+ Content: `<span data-type="block-ref text" data-id="` + firstDefID ++ `" data-subtype="d" style="color: var(--b3-font-color8);">First</span> and ((` ++ secondDefID + ` "Second")) and ((` + firstDefID + ` 'First again'))`,+ },+ }}},+ },+ }}++ refs := attributeViewRefs(tree, databaseNode, attrView)+ if 2 != len(refs) {+ t.Fatalf("expected references to be deduplicated by carrier and definition, got %d", len(refs))+ }+ byDefinition := map[string]*Ref{}+ for _, ref := range refs {+ byDefinition[ref.DefBlockID] = ref+ if databaseID != ref.BlockID || rootID != ref.RootID || tree.Box != ref.Box || tree.Path != ref.Path {+ t.Fatalf("reference source is not the carrier database block: %+v", ref)+ }+ if AttributeViewRefType != ref.Type {+ t.Fatalf("unexpected attribute view reference type: %q", ref.Type)+ }+ }+ if "First" != byDefinition[firstDefID].Content || "Second" != byDefinition[secondDefID].Content {+ t.Fatalf("unexpected reference anchors: %+v", byDefinition)+ }+}++func TestAttributeViewRefsIgnoreLegacyPlainTextAndDerivedValues(t *testing.T) {+ const defID = "20260904010002-def0001"+ tree := &parse.Tree{Root: &ast.Node{Type: ast.NodeDocument}, ID: "root", Box: "box", Path: "/root.sy"}+ databaseNode := &ast.Node{Type: ast.NodeAttributeView, ID: "database"}+ attrView := &av.AttributeView{KeyValues: []*av.KeyValues{+ {+ Key: &av.Key{ID: "legacy", Type: av.KeyTypeText},+ Values: []*av.Value{{Type: av.KeyTypeText, Text: &av.ValueText{+ Content: "((" + defID + " \"literal plain text\"))",+ }}},+ },+ {+ Key: &av.Key{ID: "rollup", Type: av.KeyTypeRollup},+ Values: []*av.Value{{Type: av.KeyTypeRollup, Rollup: &av.ValueRollup{Contents: []*av.Value{{+ Type: av.KeyTypeText,+ Text: &av.ValueText{Rich: &av.ValueTextRich{+ Spec: av.ValueTextRichSpec, Format: av.ValueTextRichFormatKramdown,+ Content: "((" + defID + " \"derived\"))",+ }},+ }}}}},+ },+ }}++ if refs := attributeViewRefs(tree, databaseNode, attrView); 0 != len(refs) {+ t.Fatalf("legacy or derived values produced attribute view references: %+v", refs)+ }+}++func TestAttributeViewRefStorageBoxIDKeepsCryptoBoundary(t *testing.T) {+ original := IsEncryptedBoxFn+ IsEncryptedBoxFn = func(boxID string) bool {+ return "20260904010000-encbox1" == boxID+ }+ t.Cleanup(func() {+ IsEncryptedBoxFn = original+ })++ if actual := attributeViewRefStorageBoxID("20260904010000-box0001"); "" != actual {+ t.Fatalf("normal carrier should use global attribute view storage, got %q", actual)+ }+ if actual := attributeViewRefStorageBoxID("20260904010000-encbox1"); "20260904010000-encbox1" != actual {+ t.Fatalf("encrypted carrier should use its exact storage boundary, got %q", actual)+ }+}diff --git a/kernel/sql/block_ref.go b/kernel/sql/block_ref.goindex 445101e319..8c3b7f87c2 100644--- a/kernel/sql/block_ref.go+++ b/kernel/sql/block_ref.go@@ -38,6 +38,7 @@ type Ref struct {}func upsertRefs(tx *sql.Tx, tree *parse.Tree) (err error) {+ removeRefCacheByPath(tree.Box, tree.Path)if err = deleteRefsByPath(tx, tree.Box, tree.Path); err != nil {return}@@ -49,6 +50,7 @@ func upsertRefs(tx *sql.Tx, tree *parse.Tree) (err error) {}func deleteRefs(tx *sql.Tx, tree *parse.Tree) (err error) {+ removeRefCacheByPath(tree.Box, tree.Path)if err = deleteRefsByPath(tx, tree.Box, tree.Path); err != nil {return}diff --git a/kernel/sql/cache.go b/kernel/sql/cache.goindex 4c7a98433c..68d97cd3f7 100644--- a/kernel/sql/cache.go+++ b/kernel/sql/cache.go@@ -150,7 +150,22 @@ func removeBlockCacheKey(id, key string) {}}-var defIDRefsCache = gcache.New(30*time.Minute, 5*time.Minute)+var (+ defIDRefsCache = gcache.New(30*time.Minute, 5*time.Minute)+ refCacheMu sync.RWMutex+ refCacheGlobalGeneration uint64+ refCacheGenerations = map[string]uint64{}+)++type refCacheGeneration struct {+ global uint64+ scope uint64+}++type refCacheEntry struct {+ refs map[string]*Ref+ complete bool+}// refCacheScopeBoxID 按加密边界规范化引用缓存范围:普通笔记本共享全局范围,加密笔记本保持独立范围。func refCacheScopeBoxID(boxID string) string {@@ -169,28 +184,50 @@ func GetRefsCacheByDefID(defID string) (ret []*Ref) {}func GetRefsCacheByDefIDInBox(defID, boxID string) (ret []*Ref) {+ return getRefsCacheByDefIDInBox(defID, boxID, QueryRefsByDefIDInBox)+}++func getRefsCacheByDefIDInBox(defID, boxID string,+ query func(defBlockID string, containChildren bool, boxID string) []*Ref) (ret []*Ref) {if encryptedBoxCacheUnavailable(boxID) {return}boxID = refCacheScopeBoxID(boxID)key := refCacheKey(defID, boxID)- for k, refs := range defIDRefsCache.Items() {- if k == key {- for _, ref := range refs.Object.(map[string]*Ref) {+ refCacheMu.RLock()+ generation := currentRefCacheGeneration(boxID)+ partial := map[string]*Ref{}+ if cached, ok := defIDRefsCache.Get(key); ok {+ if entry, valid := cached.(*refCacheEntry); valid {+ for blockID, ref := range entry.refs {ret = append(ret, ref)+ partial[blockID] = ref+ }+ if entry.complete {+ refCacheMu.RUnlock()+ return}}}- if 1 > len(ret) {- allRefs := QueryRefsByDefIDInBox(defID, false, boxID)- for _, ref := range allRefs {- // 按 box 过滤:boxID 非空时只选同 box 的 Ref,boxID 为空时全部保留- if boxID == "" || ref.Box == boxID {- ret = append(ret, ref)- putRefCache(boxID, ref)- }+ refCacheMu.RUnlock()+ allRefs := query(defID, false, boxID)+ merged := map[string]*Ref{}+ var cacheable []*Ref+ for _, ref := range allRefs {+ // 按 box 过滤:boxID 非空时只选同 box 的 Ref,boxID 为空时全部保留+ if boxID == "" || ref.Box == boxID {+ merged[ref.BlockID] = ref+ cacheable = append(cacheable, ref)}}+ for blockID, ref := range partial {+ merged[blockID] = ref+ }+ ret = ret[:0]+ for _, ref := range merged {+ ret = append(ret, ref)+ }+ putRefCacheIfGeneration(defID, boxID, generation, cacheable)return}@@ -203,19 +240,101 @@ func putRefCache(boxID string, ref *Ref) {if encryptedBoxCacheUnavailable(boxID) {return}+ refCacheMu.Lock()+ defer refCacheMu.Unlock()+ boxID = refCacheScopeBoxID(boxID)+ refCacheGenerations[boxID]+++ putRefCacheLocked(boxID, ref)+}++func putRefCacheIfGeneration(defID, boxID string, generation refCacheGeneration, refs []*Ref) {+ if encryptedBoxCacheUnavailable(boxID) {+ return+ }+ boxID = refCacheScopeBoxID(boxID)+ refCacheMu.Lock()+ defer refCacheMu.Unlock()+ if generation != currentRefCacheGeneration(boxID) {+ return+ }+ complete := make(map[string]*Ref, len(refs))+ for _, ref := range refs {+ if nil != ref {+ complete[ref.BlockID] = ref+ }+ }+ key := refCacheKey(defID, boxID)+ if cached, ok := defIDRefsCache.Get(key); ok {+ if entry, valid := cached.(*refCacheEntry); valid {+ for blockID, ref := range entry.refs {+ complete[blockID] = ref+ }+ }+ }+ defIDRefsCache.SetDefault(key, &refCacheEntry{refs: complete, complete: true})+}++func putRefCacheLocked(boxID string, ref *Ref) {+ if nil == ref {+ return+ }key := refCacheKey(ref.DefBlockID, boxID)- defBlockRefs, ok := defIDRefsCache.Get(key)- if !ok {- defBlockRefs = map[string]*Ref{}+ entry := &refCacheEntry{refs: map[string]*Ref{}}+ if cached, ok := defIDRefsCache.Get(key); ok {+ if existing, valid := cached.(*refCacheEntry); valid {+ entry = existing+ }}- defBlockRefs.(map[string]*Ref)[ref.BlockID] = ref- defIDRefsCache.SetDefault(key, defBlockRefs)+ entry.refs[ref.BlockID] = ref+ entry.complete = false+ defIDRefsCache.SetDefault(key, entry)}func removeRefCacheByDefID(defID string) {- defIDRefsCache.Delete(refCacheKey(defID, ""))+ refCacheMu.Lock()+ defer refCacheMu.Unlock()+ refCacheGlobalGeneration+++ suffix := "\x00" + defID+ for key := range defIDRefsCache.Items() {+ if strings.HasSuffix(key, suffix) {+ defIDRefsCache.Delete(key)+ }+ }+}++func removeRefCacheByPath(boxID, path string) {+ refCacheMu.Lock()+ defer refCacheMu.Unlock()+ refCacheGenerations[refCacheScopeBoxID(boxID)]+++ for key, item := range defIDRefsCache.Items() {+ entry, ok := item.Object.(*refCacheEntry)+ if !ok {+ continue+ }+ for _, ref := range entry.refs {+ if nil != ref && ref.Box == boxID && ref.Path == path {+ defIDRefsCache.Delete(key)+ break+ }+ }+ }}func clearRefCache() {+ refCacheMu.Lock()+ defer refCacheMu.Unlock()+ refCacheGlobalGeneration+++ refCacheGenerations = map[string]uint64{}defIDRefsCache.Flush()}++func getRefCacheGeneration(boxID string) refCacheGeneration {+ refCacheMu.RLock()+ defer refCacheMu.RUnlock()+ return currentRefCacheGeneration(refCacheScopeBoxID(boxID))+}++// currentRefCacheGeneration 返回当前引用缓存代数,调用方必须持有 refCacheMu。+func currentRefCacheGeneration(boxID string) refCacheGeneration {+ return refCacheGeneration{global: refCacheGlobalGeneration, scope: refCacheGenerations[boxID]}+}diff --git a/kernel/sql/database.go b/kernel/sql/database.goindex df17056ca3..d0f86e5a7e 100644--- a/kernel/sql/database.go+++ b/kernel/sql/database.go@@ -530,6 +530,13 @@ func refsFromTree(tree *parse.Tree) (refs []*Ref, fileAnnotationRefs []*FileAnnoif ast.NodeCustomBlock == n.Type {return ast.WalkSkipChildren}+ if ast.NodeAttributeView == n.Type {+ for _, ref := range attributeViewRefsFromNode(tree, n) {+ if !isRepeatedRef(refs, ref) {+ refs = append(refs, ref)+ }+ }+ }return ast.WalkContinue}diff --git a/kernel/sql/queue.go b/kernel/sql/queue.goindex dbda6526c9..47d03be67c 100644--- a/kernel/sql/queue.go+++ b/kernel/sql/queue.go@@ -284,14 +284,17 @@ func FlushQueue() {if err = execOp(op, tx, context); err != nil {tx.Rollback()closeTxPreparedStmts(tx)+ invalidateRefsCacheForOperation(op)logging.LogErrorf("queue operation [%s] failed: %s", op.action, err)continue}if err = commitTx(tx); err != nil {+ invalidateRefsCacheForOperation(op)logging.LogErrorf("commit tx failed: %s", err)continue}+ invalidateRefsCacheForOperation(op)backlinkChange.addOperation(op)switch op.action {@@ -328,6 +331,12 @@ func FlushQueue() {clearIndexQueue(indexSnapshot)}+func invalidateRefsCacheForOperation(op *dbQueueOperation) {+ if nil != op && ("update_refs" == op.action || "delete_refs" == op.action) && nil != op.upsertTree {+ removeRefCacheByPath(op.upsertTree.Box, op.upsertTree.Path)+ }+}+func execOp(op *dbQueueOperation, tx *sql.Tx, context map[string]any) (err error) {switch op.action {case "index":