Skip to content

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

:bug: Respect editing locks across attribute panel tabs https://github.com/siyuan-note/siyuan/issues/20334

Daniel066fc51ffa0c
diff --git a/app/src/assets/scss/business/_custom.scss b/app/src/assets/scss/business/_custom.scss
index 347cb76bf6..8270412254 100644
--- a/app/src/assets/scss/business/_custom.scss
+++ b/app/src/assets/scss/business/_custom.scss
@@ -359,6 +359,9 @@
.custom-attr[data-readonly="true"] {
[data-type="remove"],
[data-type="addColumn"],
+ [data-action="bookmark"],
+ [data-action="addCustom"],
+ [data-action="remove"],
.av__row > .block__icon[draggable] {
display: none;
}
diff --git a/app/src/menus/aliasInput.test.ts b/app/src/menus/aliasInput.test.ts
index b47d82457b..cd926d4428 100644
--- a/app/src/menus/aliasInput.test.ts
+++ b/app/src/menus/aliasInput.test.ts
@@ -1,6 +1,6 @@
import {describe, it} from "node:test";
import * as assert from "node:assert/strict";
-import {parseAliases, updateAliases} from "./aliasInput";
+import {bindAliasInput, parseAliases, updateAliases} from "./aliasInput";
describe("alias input", () => {
it("splits ASCII commas, trims whitespace and keeps distinct aliases in order", () => {
@@ -31,3 +31,53 @@ describe("alias input", () => {
assert.deepEqual(updateAliases([], value), [value]);
});
});
+
+it("readonly aliases preserve text without editing, deletion, focus or drag handlers taking action", async () => {
+ const calls: string[] = [];
+ interface IFakeAliasElement {
+ children: IFakeAliasElement[];
+ textContent: string;
+ className: string;
+ events: Record<string, (event: unknown) => void>;
+ classList: {toggle: () => void, contains: () => boolean};
+ append: (child: IFakeAliasElement) => void;
+ replaceChildren: () => void;
+ setAttribute: () => void;
+ addEventListener: (type: string, callback: (event: unknown) => void) => void;
+ focus: () => void;
+ }
+ const makeElement = (): IFakeAliasElement => ({
+ children: [],
+ textContent: "",
+ className: "",
+ events: {} as Record<string, (event: unknown) => void>,
+ classList: {toggle() {}, contains: () => true},
+ append(child: IFakeAliasElement) { this.children.push(child); },
+ replaceChildren() { this.children = []; },
+ setAttribute() {},
+ addEventListener(type: string, callback: (event: unknown) => void) { this.events[type] = callback; },
+ focus: () => calls.push("focus"),
+ });
+ const list = makeElement();
+ const input = makeElement();
+ const add = {...makeElement(), querySelector: () => ({textContent: ""})};
+ const element = {innerHTML: "", querySelector: (selector: string) => selector === ".b3-chips" ? list :
+ selector === "button" ? add : input};
+ const previousDocument = globalThis.document;
+ globalThis.document = {createElement: makeElement} as unknown as Document;
+ try {
+ const aliases = bindAliasInput(element as unknown as HTMLElement, "first,<literal>", {
+ readonly: true, addLabel: "add", removeLabel: "remove", placeholder: "alias", spellcheck: false,
+ save: async () => { calls.push("save"); return true; },
+ });
+ assert.deepEqual(list.children.map(chip => chip.children.map(text => text.textContent)), [["first"], ["<literal>"]]);
+ assert.ok(list.children.every(chip => Object.keys(chip.events).length === 0));
+ list.events.pointerdown({});
+ add.events.click({});
+ aliases.focus();
+ assert.equal(await aliases.commit(), true);
+ assert.deepEqual(calls, []);
+ } finally {
+ globalThis.document = previousDocument;
+ }
+});
diff --git a/app/src/menus/aliasInput.ts b/app/src/menus/aliasInput.ts
index 6633deeaf8..d5f5ed565a 100644
--- a/app/src/menus/aliasInput.ts
+++ b/app/src/menus/aliasInput.ts
@@ -12,6 +12,7 @@ export const bindAliasInput = (element: HTMLElement, initialValue: string, optio
removeLabel: string,
placeholder: string,
spellcheck: boolean,
+ readonly?: boolean,
dragThreshold?: number,
save: (value: string) => Promise<boolean>,
}) => {
@@ -32,6 +33,8 @@ export const bindAliasInput = (element: HTMLElement, initialValue: string, optio
input.placeholder = options.placeholder;
input.setAttribute("aria-label", options.placeholder);
input.spellcheck = options.spellcheck;
+ input.readOnly = Boolean(options.readonly);
+ add.classList.toggle("fn__none", Boolean(options.readonly));
list.addEventListener("click", event => {
if (suppressClick && event.detail !== 0) {
event.preventDefault();
@@ -45,6 +48,9 @@ export const bindAliasInput = (element: HTMLElement, initialValue: string, optio
}
}, {passive: true});
list.addEventListener("pointerdown", event => {
+ if (options.readonly) {
+ return;
+ }
suppressClick = false;
// 点击标签时由点击处理器先提交草稿,避免失焦重绘移除正在点击的元素。
if (document.activeElement === input) {
@@ -164,6 +170,13 @@ export const bindAliasInput = (element: HTMLElement, initialValue: string, optio
aliases.forEach(alias => {
const chip = document.createElement("div");
chip.className = "b3-chip b3-chip--middle";
+ if (options.readonly) {
+ const text = document.createElement("span");
+ text.textContent = alias;
+ chip.append(text);
+ list.append(chip);
+ return;
+ }
chip.innerHTML = "<span class=\"b3-chip--pointer\" role=\"button\" tabindex=\"0\"></span><svg class=\"b3-chip__close\" role=\"button\" tabindex=\"0\"><use xlink:href=\"#iconClose\"></use></svg>";
const text = chip.querySelector("span");
const remove = chip.querySelector("svg");
@@ -236,12 +249,18 @@ export const bindAliasInput = (element: HTMLElement, initialValue: string, optio
return persist(next, restoreFocus);
};
const open = () => {
+ if (options.readonly) {
+ return;
+ }
add.classList.add("fn__none");
input.classList.remove("fn__none");
input.focus();
input.select();
};
const activate = (action: () => Promise<void>) => {
+ if (options.readonly) {
+ return;
+ }
// 标签操作依次提交,避免失焦保存和连续删除互相覆盖。
activeActions++;
actions = actions.then(async () => {
diff --git a/app/src/menus/attributeSheet.test.ts b/app/src/menus/attributeSheet.test.ts
index 8c68ddd6d4..c080646a28 100644
--- a/app/src/menus/attributeSheet.test.ts
+++ b/app/src/menus/attributeSheet.test.ts
@@ -65,3 +65,59 @@ for (const mobile of [true, false]) {
});
}
}
+
+for (const mobile of [true, false]) {
+ for (const kernelReadonly of [true, false]) {
+ test(`${mobile ? "mobile" : "desktop"} readonly attributes block writes and initial focus (${kernelReadonly})`, () => {
+ const calls: string[] = [];
+ const containers = ["attr", "custom", "NodeAttributeView"].map(type => ({dataset: {type, readonly: ""}}));
+ const fields = ["bookmark", "name", "memo", "custom-test"].map(name => ({
+ value: "", readOnly: false, dataset: {name},
+ getAttribute: () => name,
+ focus: () => calls.push("focus"),
+ change: (): void => undefined,
+ addEventListener(_type: string, callback: () => void) { this.change = callback; },
+ }));
+ let click: (event: object) => void;
+ const element = {
+ contains: () => false, setAttribute() {},
+ addEventListener: (_type: string, callback: typeof click) => { click = callback; },
+ querySelector: (selector: string) => fields.find(field => selector.includes(`"${field.dataset.name}"`)),
+ querySelectorAll: (selector: string) => selector === ".custom-attr" ? containers :
+ selector.includes("custom-attr") ? [fields[3]] : fields,
+ };
+ const dependencies: Record<string, unknown> = {
+ "../util/functions": {isMobile: () => mobile},
+ "../constants": {Constants: {}},
+ "../dialog": {Dialog: class {element = element; destroy() {}}},
+ "./aliasInput": {bindAliasInput: (_element: unknown, _value: string, options: {readonly: boolean}) => {
+ assert.equal(options.readonly, true);
+ return {focus: () => calls.push("alias-focus")};
+ }},
+ "../util/fetch": {fetchPost: () => calls.push("write")},
+ "../mobile/util/keyboardToolbar": {activeBlur() {}},
+ "../mobile/util/bindBottomSheetDialog": {bindBottomSheetDialog: () => () => {}},
+ };
+ const source = parse(readFileSync("src/menus/commonMenuItem.ts", "utf8"),
+ {MOBILE: mobile, BROWSER: true}, false, true, "commonMenuItem.ts");
+ const code = transpileModule(source, {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText;
+ const exports: {openFileAttr?: (attrs: object, focusName: string, protyle: object) => void} = {};
+ runInNewContext(code, {
+ exports, require: (name: string) => dependencies[name] || {},
+ document: {activeElement: {blur() {}}},
+ getSelection: () => ({rangeCount: 0}),
+ window: {siyuan: {languages: {}, config: {readonly: kernelReadonly, editor: {spellcheck: false}}}},
+ });
+ exports.openFileAttr({id: "doc", "custom-test": "value"}, "alias", {disabled: !kernelReadonly});
+ assert.ok(containers.every(container => container.dataset.readonly === "true"));
+ assert.ok(fields.every(field => field.readOnly));
+ fields.forEach(field => field.change());
+ for (const action of ["remove", "bookmark", "addCustom"]) {
+ click({target: {dataset: {action}}, preventDefault() {}, stopPropagation() {}});
+ }
+ assert.deepEqual(calls, []);
+ });
+ }
+}
diff --git a/app/src/menus/commonMenuItem.ts b/app/src/menus/commonMenuItem.ts
index edcad82aa7..11381b4efd 100644
--- a/app/src/menus/commonMenuItem.ts
+++ b/app/src/menus/commonMenuItem.ts
@@ -53,6 +53,9 @@ import {activeBlur} from "../mobile/util/keyboardToolbar";
const bindAttrInput = (inputElement: HTMLInputElement, id: string) => {
inputElement.addEventListener("change", () => {
+ if (inputElement.readOnly) {
+ return;
+ }
fetchPost("/api/attr/setBlockAttrs", {
id,
attrs: {[inputElement.dataset.name]: inputElement.value}
@@ -209,6 +212,8 @@ export const openFileAttr = (attrs: Record<string, string>, focusName = "bookmar
});
}
}
+ const readonly = Boolean(window.siyuan.config.readonly || protyle?.disabled || (!protyle &&
+ (attrs[Constants.CUSTOM_SY_READONLY] === "true" || window.siyuan.config.editor.readOnly)));
Object.keys(attrs).forEach(item => {
if (Constants.CUSTOM_RIFF_DECKS === item || item.startsWith("custom-sy-")) {
return;
@@ -318,6 +323,9 @@ export const openFileAttr = (attrs: Record<string, string>, focusName = "bookmar
const disposeSheet = bindBottomSheetDialog(dialog, async () => dialog.destroy());
/// #endif
dialog.element.setAttribute("data-key", Constants.DIALOG_ATTR);
+ dialog.element.querySelectorAll<HTMLElement>(".custom-attr").forEach(item => {
+ item.dataset.readonly = String(readonly);
+ });
(dialog.element.querySelector('.b3-text-field[data-name="bookmark"]') as HTMLInputElement).value = attrs.bookmark || "";
(dialog.element.querySelector('.b3-text-field[data-name="name"]') as HTMLInputElement).value = attrs.name || "";
const aliasInput = bindAliasInput(dialog.element.querySelector("[data-alias-input]"), attrs.alias || "", {
@@ -326,6 +334,7 @@ export const openFileAttr = (attrs: Record<string, string>, focusName = "bookmar
removeLabel: window.siyuan.languages.remove,
placeholder: window.siyuan.languages.attrAliasTip,
spellcheck: window.siyuan.config.editor.spellcheck,
+ readonly,
save: async (alias) => {
try {
const response = await fetchSyncPost("/api/attr/setBlockAttrs", {id: attrs.id, attrs: {alias}});
@@ -356,6 +365,11 @@ export const openFileAttr = (attrs: Record<string, string>, focusName = "bookmar
}
while (target !== dialog.element) {
const type = target.dataset.action;
+ if (readonly && ["remove", "bookmark", "addCustom"].includes(type)) {
+ event.preventDefault();
+ event.stopPropagation();
+ return;
+ }
if (target.classList.contains("item--full")) {
target.parentElement.querySelector(".item--focus").classList.remove("item--focus");
target.classList.add("item--focus");
@@ -451,13 +465,14 @@ export const openFileAttr = (attrs: Record<string, string>, focusName = "bookmar
}
});
dialog.element.querySelectorAll(".b3-text-field[data-name]").forEach((item: HTMLInputElement) => {
- if (!isMobile() && focusName !== "av" && focusName !== "custom" && focusName === item.getAttribute("data-name")) {
+ item.readOnly = item.readOnly || readonly;
+ if (!readonly && !isMobile() && focusName !== "av" && focusName !== "custom" && focusName === item.getAttribute("data-name")) {
item.focus();
}
bindAttrInput(item, attrs.id);
});
if (focusName === "alias") {
- if (!isMobile()) {
+ if (!readonly && !isMobile()) {
aliasInput.focus();
}
} else if (focusName === "av") {