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: Improve inline formatting toggles for mixed-format selections https://github.com/siyuan-note/siyuan/issues/19222
Danield489aad7ecf9
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.tsindex 5230b12977..371f3bc440 100644--- a/app/src/mobile/util/keyboardToolbar.ts+++ b/app/src/mobile/util/keyboardToolbar.ts@@ -886,7 +886,7 @@ const renderKeyboardToolbar = () => {dynamicElements[1].querySelectorAll(".protyle-toolbar__item--current").forEach(item => {item.classList.remove("protyle-toolbar__item--current");});- const types = protyle.toolbar.getCurrentType(range);+ const types = protyle.toolbar.getCurrentToolbarType(protyle, range);types.forEach(item => {if (["search-mark", "a", "block-ref", "virtual-block-ref", "text", "file-annotation-ref", "inline-math","inline-memo", "", "backslash"].includes(item)) {diff --git a/app/src/protyle/toolbar/index.ts b/app/src/protyle/toolbar/index.tsindex 39ce976b8b..cd8088e6c8 100644--- a/app/src/protyle/toolbar/index.ts+++ b/app/src/protyle/toolbar/index.ts@@ -68,6 +68,7 @@ import {resizeSide} from "../../history/resizeSide";import {activeBlur, updateMobilePluginToolbar} from "../../mobile/util/keyboardToolbar";import {FormatPainter} from "./FormatPainter";import {IFormatPainterSnapshot} from "./formatPainterCore";+import {getRangeInlineFormats, getRangesInlineFormats, INLINE_FORMAT_TYPES} from "./inlineFormat";import {clearDisallowedTextInputHotkey} from "../../util/hotKeyPolicy";import {getHostCapabilities} from "../../util/hostCapabilities";import {closeSubElement, SELECTION_TOOLBAR_SUB_ELEMENT_SOURCE} from "./subElementLifecycle";@@ -316,7 +317,7 @@ export class Toolbar {});this.element.querySelector('[data-type="a"]')?.toggleAttribute("disabled", isCrossBlock || isCrossCell);this.element.querySelector('[data-type="block-ref"]')?.toggleAttribute("disabled", isCrossBlock || isCrossCell);- const types = this.getCurrentType();+ const types = this.getCurrentToolbarType(protyle);types.forEach(item => {if (["search-mark", "a", "block-ref", "virtual-block-ref", "text", "file-annotation-ref", "inline-math","inline-memo", "", "backslash"].includes(item)) {@@ -373,6 +374,26 @@ export class Toolbar {return types;}+ public getCurrentToolbarType(protyle: IProtyle, range = this.range) {+ const types = this.getCurrentType(range);+ if (range.collapsed) {+ return types;+ }+ const nodeElement = hasClosestBlock(range.startContainer);+ if (!nodeElement) {+ return types;+ }+ const selectedRange = range.cloneRange();+ const editableElement = normalizeCalloutTitleRange(selectedRange, nodeElement,+ getContenteditableElement(nodeElement, selectedRange.startContainer));+ const formats = editableElement?.contains(selectedRange.endContainer) &&+ nodeElement.getAttribute("data-type") !== "NodeTable" ?+ getRangeInlineFormats(editableElement, selectedRange) || [] :+ getRangesInlineFormats(getBlockRanges(protyle.wysiwyg.element, selectedRange,+ ["NodeCodeBlock", "NodeAttributeView"]));+ return types.filter(type => !INLINE_FORMAT_TYPES.includes(type)).concat(formats);+ }+private hasInlineMark(editableElement: Element, range: Range, type: string) {const walker = document.createTreeWalker(editableElement, NodeFilter.SHOW_TEXT);let textNode = walker.nextNode() as Text;@@ -549,6 +570,9 @@ export class Toolbar {public hasTableCellsInlineMark(cellElements: HTMLTableCellElement[], type: string) {const ranges = this.getTableCellRanges(cellElements);+ if (INLINE_FORMAT_TYPES.includes(type)) {+ return getRangesInlineFormats(ranges).includes(type);+ }return ranges.length > 0 && ranges.every(item => this.hasInlineMark(item.editableElement, item.range, type));}@@ -685,7 +709,9 @@ export class Toolbar {const toolbarElement = isMobile() ? document.querySelector("#keyboardToolbar .keyboard__dynamic").nextElementSibling : this.element;const actionBtn = action === "toolbar" ? toolbarElement.querySelector(`[data-type="${type}"]`) : undefined;- const remove = type === "clear" || actionBtn?.classList.contains("protyle-toolbar__item--current") ||+ const remove = INLINE_FORMAT_TYPES.includes(type) && !textObj ?+ getRangesInlineFormats(ranges).includes(type) :+ type === "clear" || actionBtn?.classList.contains("protyle-toolbar__item--current") ||(!textObj && ranges.every(item => this.hasInlineMark(item.editableElement, item.range, type)));const visibleOffsets = new Map(ranges.map(item =>[item, getSelectionOffset(item.editableElement, undefined, item.range, true)]));@@ -785,6 +811,9 @@ export class Toolbar {const editableElement = normalizeCalloutTitleRange(this.range, nodeElement,getContenteditableElement(nodeElement, this.range.startContainer));const isBatch = remove !== undefined;+ // 在提取选区内容之前确定格式操作,空选区继续使用光标处的输入格式。+ const removeFormat = !isBatch && !this.range.collapsed && INLINE_FORMAT_TYPES.includes(type) && !textObj ?+ getRangeInlineFormats(editableElement, this.range)?.includes(type) : undefined;let rangeTypes: string[] = [];this.range.cloneContents().childNodes.forEach((item: HTMLElement) => {if (item.nodeType !== 3) {@@ -955,7 +984,7 @@ export class Toolbar {let endContainer: Node;let startOffset: number;let endOffset: number;- const shouldRemove = remove ?? (type === "clear" ||+ const shouldRemove = remove ?? removeFormat ?? (type === "clear" ||actionBtn?.classList.contains("protyle-toolbar__item--current") || (action === "range" && rangeTypes.length > 0 && rangeTypes.includes(type) && !textObj));diff --git a/app/src/protyle/toolbar/inlineFormat.test.ts b/app/src/protyle/toolbar/inlineFormat.test.tsnew file mode 100644index 0000000000..01538f0ef6--- /dev/null+++ b/app/src/protyle/toolbar/inlineFormat.test.ts@@ -0,0 +1,133 @@+import {before, describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {getRangeInlineFormats, getRangesInlineFormats, INLINE_FORMAT_TYPES} from "./inlineFormat";++before(() => {+ Object.assign(globalThis, {Node: {TEXT_NODE: 3}, NodeFilter: {SHOW_TEXT: 4}});+});++const selection = (segments: {text: string, types?: string, outerTypes?: string}[],+ startOffset = 0, endOffset?: number) => {+ const editableElement = {getAttribute: (): string | null => null} as unknown as Element;+ const nodes = segments.map(segment => {+ const parent = {+ tagName: "SPAN",+ getAttribute: () => segment.types || null,+ parentElement: segment.outerTypes ? {+ getAttribute: () => segment.outerTypes,+ parentElement: editableElement,+ } : editableElement,+ closest() {+ return this;+ },+ } as unknown as Element;+ const node = {+ nodeType: 3,+ data: segment.text,+ textContent: segment.text,+ parentElement: parent,+ } as unknown as Text;+ Object.assign(parent, {childNodes: [node]});+ return node;+ });+ Object.assign(editableElement, {+ ownerDocument: {+ createTreeWalker() {+ let index = 0;+ return {nextNode: () => nodes[index++]};+ },+ },+ });+ const range = {+ startContainer: nodes[0],+ startOffset,+ endContainer: nodes[nodes.length - 1],+ endOffset: endOffset ?? nodes[nodes.length - 1]?.data.length ?? 0,+ intersectsNode: () => true,+ } as unknown as Range;+ return {editableElement, range};+};++const formats = (selected: ReturnType<typeof selection>) =>+ getRangeInlineFormats(selected.editableElement, selected.range);++describe("inline format selection coverage", () => {+ INLINE_FORMAT_TYPES.forEach(type => {+ it(`adds ${type} when extending formatted text on either side`, () => {+ const marked = {text: "marked", types: type};+ const plain = {text: "plain"};+ assert.deepEqual(formats(selection([plain, marked, plain])), []);+ assert.deepEqual(formats(selection([marked, plain])), []);+ assert.deepEqual(formats(selection([plain, marked])), []);+ });++ it(`removes ${type} only when every selected segment has it`, () => {+ assert.deepEqual(formats(selection([+ {text: "first", types: type},+ {text: "second", types: `${type} text a`},+ ], 2, 3)), [type]);+ });+ });++ it("checks common formats independently and includes inherited marks", () => {+ assert.deepEqual(formats(selection([+ {text: "first", types: "em", outerTypes: "strong"},+ {text: "second", types: "strong u"},+ ])), ["strong"]);+ });++ it("does not count unselected text at either boundary", () => {+ assert.deepEqual(formats(selection([+ {text: "before"}, {text: "selected", types: "strong"}, {text: "after"},+ ], 6, 0)), ["strong"]);+ });++ it("ignores text nodes outside the range and formatting on the editable root", () => {+ const selected = selection([{text: "outside"}, {text: "bold", types: "strong"}]);+ selected.range.intersectsNode = node => node === selected.range.endContainer;+ assert.deepEqual(formats(selected), ["strong"]);+ const plain = selection([{text: "plain"}]);+ plain.editableElement.getAttribute = () => "strong";+ assert.deepEqual(formats(plain), []);+ });++ it("ignores zero-width boundaries and supported internal placeholders", () => {+ assert.deepEqual(formats(selection([+ {text: "\u200b"},+ {text: "\u2060value", types: "strong code"},+ {text: "\u200b\ufeff", types: "kbd"},+ {text: "\u200b"},+ ])), ["strong", "code"]);+ });++ it("keeps ordinary selected whitespace in the coverage check", () => {+ assert.deepEqual(formats(selection([{text: "bold", types: "strong"}, {text: " "}])), []);+ });++ it("ignores image helper text but checks text in semantic elements", () => {+ assert.deepEqual(formats(selection([+ {text: "bold", types: "strong"}, {text: "caption", outerTypes: "img"},+ ])), ["strong"]);+ ["a", "block-ref", "tag", "inline-memo", "inline-math"].forEach(type => {+ assert.deepEqual(formats(selection([+ {text: "bold", types: "strong"}, {text: "value", types: type},+ ])), []);+ });+ });++ it("does not infer formats from empty or collapsed text selections", () => {+ assert.equal(formats(selection([{text: "bold", types: "strong"}], 2, 2)), undefined);+ assert.equal(formats(selection([{text: "\u200b", types: "strong"}])), undefined);+ assert.deepEqual(getRangesInlineFormats([]), []);+ });++ it("requires coverage across every nonempty block or table cell", () => {+ const first = selection([{text: "first", types: "strong em"}]);+ const second = selection([{text: "second", types: "strong"}]);+ const empty = selection([{text: "\u200b"}]);+ assert.deepEqual(getRangesInlineFormats([first, empty, second]), ["strong"]);+ const mixed = selection([{text: "bold", types: "strong"}, {text: "plain"}]);+ assert.deepEqual(getRangesInlineFormats([first, mixed]), []);+ assert.deepEqual(getRangesInlineFormats([mixed, first]), []);+ });+});diff --git a/app/src/protyle/toolbar/inlineFormat.ts b/app/src/protyle/toolbar/inlineFormat.tsnew file mode 100644index 0000000000..b33c685faa--- /dev/null+++ b/app/src/protyle/toolbar/inlineFormat.ts@@ -0,0 +1,47 @@+import {getSemanticMarkerPrefixLengthForNode} from "../util/inlineElementMarker";++export const INLINE_FORMAT_TYPES = ["strong", "em", "u", "s", "mark", "sup", "sub", "code", "kbd"];++export const getRangeInlineFormats = (editableElement: Element, range: Range): string[] | undefined => {+ const walker = editableElement.ownerDocument.createTreeWalker(editableElement, NodeFilter.SHOW_TEXT);+ let formats: string[] | undefined;+ let textNode = walker.nextNode() as Text;+ while (textNode) {+ if (range.intersectsNode(textNode)) {+ const start = range.startContainer === textNode ? range.startOffset : 0;+ const end = range.endContainer === textNode ? range.endOffset : textNode.data.length;+ const visibleStart = Math.max(start, getSemanticMarkerPrefixLengthForNode(textNode));+ if (visibleStart < end && textNode.data.substring(visibleStart, end).split("\u200b").join("")) {+ const types: string[] = [];+ let element = textNode.parentElement;+ let image = false;+ while (element && element !== editableElement) {+ const elementTypes = (element.getAttribute("data-type") || "").split(" ");+ image = image || elementTypes.includes("img");+ types.push(...elementTypes);+ element = element.parentElement;+ }+ // 图片内部的辅助文本不参与行级格式判断。+ if (!image) {+ formats = (formats || INLINE_FORMAT_TYPES).filter(type => types.includes(type));+ if (formats.length === 0) {+ return formats;+ }+ }+ }+ }+ textNode = walker.nextNode() as Text;+ }+ return formats;+};++export const getRangesInlineFormats = (ranges: {editableElement: Element, range: Range}[]) => {+ let formats: string[] | undefined;+ ranges.forEach(item => {+ const current = getRangeInlineFormats(item.editableElement, item.range);+ if (current) {+ formats = (formats || INLINE_FORMAT_TYPES).filter(type => current.includes(type));+ }+ });+ return formats || [];+};