An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Correct font toolbar selection and custom profile defaults https://github.com/siyuan-note/siyuan/issues/19226
Danielc5aef36dba73
diff --git a/app/scripts/fontSizeSelection.test.js b/app/scripts/fontSizeSelection.test.jsnew file mode 100644index 0000000000..c99dd42b5f--- /dev/null+++ b/app/scripts/fontSizeSelection.test.js@@ -0,0 +1,120 @@+const assert = require("node:assert/strict");+const {readFileSync, mkdtempSync, rmSync} = require("node:fs");+const path = require("node:path");+const os = require("node:os");++const runCases = () => {+ const assert = require("node:assert/strict");+ document.body.innerHTML = '<div id="editor" style="font-size:16px"><div data-node-id="quote" data-type="NodeBlockquote">' ++ '<div data-node-id="one" data-type="NodeParagraph"><div contenteditable="true">111<span contenteditable="false" style="font-size:12px">badge</span></div><div class="protyle-attr" style="font-size:12px">attribute</div></div>' ++ '<div data-node-id="two" data-type="NodeParagraph"><div contenteditable="true">222</div></div></div></div>';+ const editor = document.getElementById("editor");+ const first = editor.querySelector('[data-node-id="one"] > div');+ const second = editor.querySelector('[data-node-id="two"] > div');+ const range = document.createRange();+ range.setStart(first.firstChild, 1);+ range.setEnd(second.firstChild, 2);+ const sample = () => window.fontSize.getSelectedFontSize(window.selection.getBlockRanges(editor, range));+ assert.equal(sample().fontSize, "16px");+ assert.equal(sample().mixed, false);+ second.style.fontSize = "20px";+ assert.equal(sample().mixed, true);+ second.style.fontSize = "1em";+ assert.equal(sample().mixed, false);+ assert.equal(sample().fontSize, "16px");+ first.style.fontSize = "1em";+ assert.equal(sample().fontSize, "1em");+ assert.equal(sample().baseFontSize, 16);+ second.innerHTML = '222<span style="font-size:30px">outside</span>';+ range.setEnd(second.firstChild, 2);+ assert.equal(sample().mixed, false);+ range.setEnd(second.lastChild.firstChild, 1);+ assert.equal(sample().mixed, true);+ range.setStart(second.firstChild, 3);+ assert.equal(sample().fontSize, "30px");+ assert.equal(sample().mixed, false);+};++const runElectron = async () => {+ const {app, BrowserWindow} = require("electron");+ app.setPath("userData", process.argv[2]);+ app.commandLine.appendSwitch("disable-gpu");+ await app.whenReady();+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false}});+ let exitCode = 0;+ try {+ const ts = require("typescript");+ const root = path.join(__dirname, "../src/protyle");+ const read = name => readFileSync(path.join(root, name + ".ts"), "utf8");+ const extract = (name, names) => {+ const source = ts.createSourceFile(name, read(name), ts.ScriptTarget.Latest, true);+ const statements = source.statements.filter(statement => ts.isVariableStatement(statement) &&+ statement.declarationList.declarations.some(declaration => names.includes(declaration.name.getText(source))));+ assert.equal(statements.length, names.length);+ return statements.map(statement => statement.getText(source)).join("\n");+ };+ // 使用实际块选区解析;位置偏移与隐藏页签不参与本组字号场景。+ const modules = {+ "toolbar/fontSizeCore": read("toolbar/fontSizeCore"),+ "toolbar/fontSizeSelection": read("toolbar/fontSizeSelection"),+ "util/hasClosest": read("util/hasClosest"),+ "wysiwyg/getBlock": 'import {hasClosestBlock, hasClosestByClassName} from "../util/hasClosest";\n' ++ extract("wysiwyg/getBlock", ["getContenteditableElement"]),+ "util/selection": 'import {hasClosestBlock, isInEmbedBlock} from "./hasClosest";\n' ++ 'import {getContenteditableElement} from "../wysiwyg/getBlock";\n' ++ "const isHiddenTabContent = () => false; const getSelectionOffset = () => ({start:0,end:0});\n" ++ extract("util/selection", ["getBlockRanges"]),+ };+ const sources = Object.fromEntries(Object.entries(modules).map(([name, source]) => [name,+ ts.transpileModule(source, {compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020}}).outputText]));+ await win.loadURL("data:text/html,<html><body></body></html>");+ await win.webContents.executeJavaScript(`(() => {+ const sources = ${JSON.stringify(sources)}, cache = {};+ const load = name => {+ if (!cache[name]) {+ if (!sources[name]) { throw new Error(name); }+ cache[name] = {};+ const resolve = dependency => load(require("node:path").posix.normalize(+ require("node:path").posix.dirname(name) + "/" + dependency));+ new Function("require", "exports", sources[name])(resolve, cache[name]);+ }+ return cache[name];+ };+ window.fontSize = load("toolbar/fontSizeSelection");+ window.selection = load("util/selection");+ })()`);+ await win.webContents.executeJavaScript(`(${runCases.toString()})()`);+ console.log("Font size selection cases passed");+ } catch (error) {+ console.error(error);+ exitCode = 1;+ } finally {+ win.destroy();+ app.exit(exitCode);+ }+};++if (process.versions.electron && process.type === "browser") {+ runElectron().catch(error => {+ console.error(error);+ require("electron").app.exit(1);+ });+} else {+ require("node:test").it("samples editable cross-block font sizes with native DOM ranges", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 45000,+ }, async () => {+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ const profile = mkdtempSync(path.join(os.tmpdir(), "siyuan-font-size-"));+ try {+ const {stdout} = await require("node:util").promisify(require("node:child_process").execFile)(+ require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 40000});+ assert.match(stdout, /Font size selection cases passed/);+ } finally {+ assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir()));+ assert.ok(path.basename(profile).startsWith("siyuan-font-size-"));+ rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});+ }+ });+}diff --git a/app/src/assets/scss/protyle/_toolbar.scss b/app/src/assets/scss/protyle/_toolbar.scssindex b5c9a5bc3e..72c4ff9d75 100644--- a/app/src/assets/scss/protyle/_toolbar.scss+++ b/app/src/assets/scss/protyle/_toolbar.scss@@ -9,6 +9,9 @@display: flex;&__item {+ display: inline-flex;+ align-items: center;+ justify-content: center;color: var(--b3-theme-on-background);border: 0;background-color: transparent;diff --git a/app/src/config/entryVisibility/catalog.ts b/app/src/config/entryVisibility/catalog.tsindex 7950ff06fd..7a24f809ae 100644--- a/app/src/config/entryVisibility/catalog.ts+++ b/app/src/config/entryVisibility/catalog.ts@@ -25,6 +25,7 @@ export interface IEntryCatalogNode {sortable?: boolean;fixed?: boolean;defaultVisible?: () => boolean;+ customDefaultVisible?: boolean;children?: IEntryCatalogNode[];}@@ -39,7 +40,7 @@ const lang = (key: string) => () => window.siyuan.languages[key] || key;const literal = (value: string) => () => value;const location = (...labels: Array<() => string>) => () => labels.map((label) => label()).join(" - ");const node = (key: string, label: () => string, simple = true, children?: IEntryCatalogNode[],- sortable?: boolean, options?: Pick<IEntryCatalogNode, "defaultVisible" | "fixed">): IEntryCatalogNode => ({+ sortable?: boolean, options?: Pick<IEntryCatalogNode, "defaultVisible" | "customDefaultVisible" | "fixed">): IEntryCatalogNode => ({key,label,simple,@@ -468,9 +469,14 @@ const gutterSingle = () => [export const SLASH_MENU_ROOT_PATH = "editor.slash.menu";-const toolbarBuiltinChildren = DESKTOP_TOOLBAR_ENTRIES.map((item) => item.separator- ? separator(item.key)- : node(item.key, lang(item.lang), !["font-family", "font-size"].includes(item.key)));+const toolbarBuiltinChildren = DESKTOP_TOOLBAR_ENTRIES.map((item) => {+ if (item.separator) {+ return separator(item.key);+ }+ const fontControl = ["font-family", "font-size"].includes(item.key);+ return node(item.key, lang(item.lang), !fontControl, undefined, undefined,+ fontControl ? {customDefaultVisible: false} : undefined);+});const toolbarBuiltinNodeMap = new Map(toolbarBuiltinChildren.map((item) => [item.key, item]));const slashMenuBuiltinChildren = [@@ -1031,6 +1037,8 @@ export const getEntryParentPath = (path: string) => parentMap.get(path);export const isEntryCatalogNodeConfigurable = (item: IEntryCatalogNode) => item.fixed !== true;export const getEntryCatalogDefaultVisibility = (path: string) =>getEntryCatalogNode(path)?.defaultVisible?.() ?? true;+export const getEntryCatalogCustomDefaultVisibility = (path: string) =>+ getEntryCatalogNode(path)?.customDefaultVisible ?? getEntryCatalogDefaultVisibility(path);export const getEntryPaths = () => Array.from(entryMap.entries()).filter(([, item]) => isEntryCatalogNodeConfigurable(item)).map(([path]) => path);diff --git a/app/src/config/entryVisibility/profile.test.ts b/app/src/config/entryVisibility/profile.test.tsindex ab61241048..b96ac2d676 100644--- a/app/src/config/entryVisibility/profile.test.ts+++ b/app/src/config/entryVisibility/profile.test.ts@@ -1,6 +1,6 @@import * as assert from "node:assert/strict";import test from "node:test";-import {getEntryCatalogDefaultVisibility, getEntryCatalogNode} from "./catalog";+import {getEntryCatalogCustomDefaultVisibility, getEntryCatalogDefaultVisibility, getEntryCatalogNode} from "./catalog";import {TOOLBAR_ENTRY_ROOT_PATH} from "../../protyle/toolbar/defaults";import {getBuiltinProfileEntryVisibility,@@ -17,11 +17,14 @@ test("font toolbar entries are visible in Full, hidden in Simple and preserve exassert.equal(defaultVisible, true);assert.equal(getBuiltinProfileEntryVisibility("full", entry.simple, defaultVisible), true);assert.equal(getBuiltinProfileEntryVisibility("simple", entry.simple, defaultVisible), false);- assert.equal(getProfileEntryVisibility({entries: {}}, path, defaultVisible), true);- assert.equal(getProfileEntryVisibility({entries: {[path]: true}}, path, defaultVisible), true);- assert.equal(getProfileEntryVisibility({entries: {[path]: false}}, path, defaultVisible), false);+ const customDefaultVisible = getEntryCatalogCustomDefaultVisibility(path);+ assert.equal(customDefaultVisible, false);+ assert.equal(getProfileEntryVisibility({entries: {}}, path, customDefaultVisible), false);+ assert.equal(getProfileEntryVisibility({entries: {[path]: true}}, path, customDefaultVisible), true);+ assert.equal(getProfileEntryVisibility({entries: {[path]: false}}, path, customDefaultVisible), false);}assert.equal(getEntryCatalogDefaultVisibility(`${TOOLBAR_ENTRY_ROOT_PATH}.text`), true);+ assert.equal(getEntryCatalogCustomDefaultVisibility(`${TOOLBAR_ENTRY_ROOT_PATH}.text`), true);});test("built-in profiles honor entry defaults", () => {diff --git a/app/src/config/entryVisibility/runtime.ts b/app/src/config/entryVisibility/runtime.tsindex a3ab0b2302..7c109eadc7 100644--- a/app/src/config/entryVisibility/runtime.ts+++ b/app/src/config/entryVisibility/runtime.ts@@ -2,6 +2,7 @@ import {fetchPost} from "../../util/fetch";import {Constants} from "../../constants";import {getEntryCatalogDefaultVisibility,+ getEntryCatalogCustomDefaultVisibility,getEntryCatalogChildren,getEntryCatalogNode,getDockEntryKey,@@ -72,7 +73,7 @@ export const getConfiguredEntryVisibility = (path: string): boolean => {} else if (active === ENTRY_PROFILE_SIMPLE) {visible = getTemplateVisibility(path, ENTRY_PROFILE_SIMPLE);} else {- visible = getProfileEntryVisibility(getActiveEntryProfile(), path, getEntryCatalogDefaultVisibility(path));+ visible = getProfileEntryVisibility(getActiveEntryProfile(), path, getEntryCatalogCustomDefaultVisibility(path));}if (!visible) {return false;diff --git a/app/src/config/entryVisibility/ui.ts b/app/src/config/entryVisibility/ui.tsindex d2fe0b90c8..64ee432096 100644--- a/app/src/config/entryVisibility/ui.ts+++ b/app/src/config/entryVisibility/ui.ts@@ -5,7 +5,7 @@ import {genUUID} from "../../util/genID";import {entryCatalog,getEntryCatalogChildren,- getEntryCatalogDefaultVisibility,+ getEntryCatalogCustomDefaultVisibility,getEntryCatalogPathChain,getEntryPaths,IEntryCatalogNode,@@ -247,7 +247,7 @@ const renderEntrySwitch = (profile: Config.IEntryVisibilityProfile, path: stringreturn `<input class="b3-switch" type="checkbox"aria-label="${escapeAttr(label)}" data-entry-path="${escapeAttr(path)}"${readOnly ? ' data-entry-readonly aria-disabled="true"' : ""}${!parentEnabled && !readOnly ? " disabled" : ""}${getProfileEntryVisibility(profile, path,- getEntryCatalogDefaultVisibility(path)) ? " checked" : ""}>`;+ getEntryCatalogCustomDefaultVisibility(path)) ? " checked" : ""}>`;};const renderEntryRows = (profile: Config.IEntryVisibilityProfile, prefix: string,@@ -451,7 +451,7 @@ const renderEntryColumns = (profile: Config.IEntryVisibilityProfile, sectionKey:let title = directDisplayRoot?.label() || section.label();let parentEnabled = directDisplayRoot? getProfileEntryVisibility(profile, directDisplayRootPath,- getEntryCatalogDefaultVisibility(directDisplayRootPath))+ getEntryCatalogCustomDefaultVisibility(directDisplayRootPath)): true;let depth = 0;while (nodes.length > 0) {@@ -470,7 +470,7 @@ const renderEntryColumns = (profile: Config.IEntryVisibilityProfile, sectionKey:break;}parentEnabled = parentEnabled && getProfileEntryVisibility(profile, selectedPath,- getEntryCatalogDefaultVisibility(selectedPath));+ getEntryCatalogCustomDefaultVisibility(selectedPath));nodes = selectedNode.children;prefix = selectedPath;title = selectedNode.label();diff --git a/app/src/protyle/toolbar/fontControls.ts b/app/src/protyle/toolbar/fontControls.tsindex 2bd71b8baa..3e6d3ff50a 100644--- a/app/src/protyle/toolbar/fontControls.ts+++ b/app/src/protyle/toolbar/fontControls.ts@@ -2,36 +2,23 @@ import {Menu} from "../../plugin/Menu";import {ToolbarItem} from "./ToolbarItem";import {convertFontSize, fontEvent, getFontNodeElements, getFontSizeInfo} from "./Font";import {getInlineFontFamilyLabel, getInlineFontFamilyState, getInlineFontFamilyValue, openFontFamilyMenu} from "./fontFamilyMenu";-import {focusByRange} from "../util/selection";+import {focusByRange, getBlockRanges} from "../util/selection";import {escapeAttr} from "../../util/escape";import {isMixedFontSize, normalizeFontSizeInput} from "./fontSizeCore";import {closeSubElement} from "./subElementLifecycle";+import {getSelectedFontSize} from "./fontSizeSelection";export const getFontSizeState = (protyle: IProtyle) => {const nodes = getFontNodeElements(protyle);const info = getFontSizeInfo(protyle, nodes);const sizes: string[] = [];const range = protyle.toolbar.range;- const root = range.commonAncestorContainer;- const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);- const collect = (node: Node) => {- const start = node === range.startContainer ? range.startOffset : 0;- const end = node === range.endContainer ? range.endOffset : node.textContent?.length;- if (start === end) {- return;- }- if (node.textContent?.trim() && range.intersectsNode(node) && node.parentElement) {- sizes.push(getComputedStyle(node.parentElement).fontSize);- }- };if (nodes?.length) {nodes.forEach(node => sizes.push(getComputedStyle(node).fontSize));} else if (!range.collapsed) {- if (root.nodeType === Node.TEXT_NODE) {- collect(root);- }- while (walker.nextNode()) {- collect(walker.currentNode);+ const selected = getSelectedFontSize(getBlockRanges(protyle.wysiwyg.element, range));+ if (selected) {+ return {...selected, disabled: false};}}return {...info, mixed: isMixedFontSize(sizes), disabled: nodes?.some(node => node.classList.contains("li")) || false};diff --git a/app/src/protyle/toolbar/fontSizeSelection.ts b/app/src/protyle/toolbar/fontSizeSelection.tsnew file mode 100644index 0000000000..5c4a37a94d--- /dev/null+++ b/app/src/protyle/toolbar/fontSizeSelection.ts@@ -0,0 +1,47 @@+import {isMixedFontSize} from "./fontSizeCore";++interface IFontSizeSample {+ fontSize: string;+ computedSize: string;+ baseFontSize: number;+}++export const getSelectedFontSize = (ranges: {editableElement: Element; range: Range}[]) => {+ const samples: IFontSizeSample[] = [];+ // 仅统计选中的可编辑正文,排除块属性和不可编辑的辅助文字。+ ranges.forEach(({editableElement, range}) => {+ const walker = document.createTreeWalker(editableElement, NodeFilter.SHOW_TEXT);+ let text = walker.nextNode() as Text;+ while (text) {+ const start = text === range.startContainer ? range.startOffset : 0;+ const end = text === range.endContainer ? range.endOffset : text.length;+ const decoration = text.parentElement?.closest('[contenteditable="false"]');+ if (range.intersectsNode(text) && text.data.slice(start, end).replace(/\u200b/g, "") &&+ !(decoration && editableElement.contains(decoration))) {+ const computedSize = getComputedStyle(text.parentElement).fontSize;+ let styled = text.parentElement;+ while (styled && editableElement.contains(styled) && !styled.style.fontSize) {+ styled = styled.parentElement;+ }+ const declaredSize = styled && editableElement.contains(styled) ? styled.style.fontSize : "";+ const inlineSize = /^(?:\d*\.)?\d+(?:px|em)$/.test(declaredSize) ? declaredSize : "";+ samples.push({+ fontSize: inlineSize || computedSize,+ computedSize,+ baseFontSize: parseFloat(inlineSize && styled.parentElement ?+ getComputedStyle(styled.parentElement).fontSize : computedSize),+ });+ }+ text = walker.nextNode() as Text;+ }+ });+ if (samples.length === 0) {+ return;+ }+ const first = samples[0];+ return {+ fontSize: isMixedFontSize(samples.map(sample => sample.fontSize)) ? first.computedSize : first.fontSize,+ baseFontSize: first.baseFontSize,+ mixed: isMixedFontSize(samples.map(sample => sample.computedSize)),+ };+};