Skip to content

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

:bug: Correct mobile database calendar controls and text editor back navigation https://github.com/siyuan-note/siyuan/issues/19949

Danieldab7a9a4d14c
diff --git a/app/src/mobile/util/MobileBackFoward.test.ts b/app/src/mobile/util/MobileBackFoward.test.ts
new file mode 100644
index 0000000000..0cf5bfe9ee
--- /dev/null
+++ b/app/src/mobile/util/MobileBackFoward.test.ts
@@ -0,0 +1,48 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {join} from "node:path";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {transpileModule, ModuleKind, ScriptTarget} from "typescript";
+import {isAbove} from "../../util/zIndex";
+
+test("mobile back saves the database text editor before leaving its owner", () => {
+ const source = transpileModule(readFileSync(join(__dirname, "MobileBackFoward.ts"), "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2020},
+ }).outputText;
+ for (const overlay of ["document", "row", "dialog", "menu"]) {
+ let saved = 0;
+ let closedDialog = 0;
+ let closedMenu = 0;
+ let navigated = 0;
+ const richText = {style: {zIndex: "2"}};
+ const menu = {classList: {contains: (name: string) =>
+ name === "fn__none" ? overlay !== "menu" : true},
+ dispatchEvent: () => closedMenu++};
+ const dialogs = overlay === "document" || overlay === "menu" ? [] : [{
+ element: {querySelector: () => ({style: {zIndex: overlay === "dialog" ? "3" : "1"}})},
+ destroy: () => closedDialog++,
+ }];
+ const modules: Record<string, unknown> = {
+ "../editor": {getCurrentEditor: (): undefined => undefined},
+ "../../protyle/render/av/richTextEditor": {destroyAVRichTextEditor: (save: boolean) => {
+ assert.equal(save, true);
+ saved++;
+ }},
+ "../../util/zIndex": {isAbove},
+ };
+ const api = {} as typeof import("./MobileBackFoward");
+ runInNewContext(source, {
+ exports: api, require: (name: string) => modules[name] || {}, CustomEvent: class {},
+ document: {getElementById: () => ({style: {}}), querySelector: () => richText},
+ window: {siyuan: {dialogs, menus: {menu: {element: menu}}, mobile: {
+ tabs: {goBack: () => { navigated++; return Promise.resolve(true); }},
+ }}},
+ });
+ api.goBack();
+ assert.equal(saved, overlay === "document" || overlay === "row" ? 1 : 0);
+ assert.equal(closedDialog, overlay === "dialog" ? 1 : 0);
+ assert.equal(closedMenu, overlay === "menu" ? 1 : 0);
+ assert.equal(navigated, 0);
+ }
+});
diff --git a/app/src/mobile/util/MobileBackFoward.ts b/app/src/mobile/util/MobileBackFoward.ts
index 1dfbeaecec..7c1dec1dad 100644
--- a/app/src/mobile/util/MobileBackFoward.ts
+++ b/app/src/mobile/util/MobileBackFoward.ts
@@ -3,6 +3,8 @@ import {hideElements} from "../../protyle/ui/hideElements";
import {getCurrentEditor} from "../editor";
import {closePanel} from "./closePanel";
import {backModel, destroyModel} from "../menu/model";
+import {destroyAVRichTextEditor} from "../../protyle/render/av/richTextEditor";
+import {isAbove} from "../../util/zIndex";
export const clearMobileBackForward = (notebookId?: string) => {
if (notebookId) {
@@ -23,6 +25,8 @@ export const goForward = () => {
export const goBack = () => {
const editor = getCurrentEditor();
const menuElement = document.getElementById("menu");
+ const richTextElement = document.querySelector<HTMLElement>(".av__richtext-mask");
+ const topDialog = window.siyuan.dialogs[window.siyuan.dialogs.length - 1];
if (window.siyuan.menus.menu.element.classList.contains("b3-menu--fullscreen") &&
!window.siyuan.menus.menu.element.classList.contains("fn__none")) {
window.siyuan.menus.menu.element.dispatchEvent(new CustomEvent("click", {detail: "back"}));
@@ -30,6 +34,10 @@ export const goBack = () => {
} else if (window.siyuan.viewer && !window.siyuan.viewer.destroyed) {
window.siyuan.viewer.destroy();
return;
+ } else if (richTextElement && (!topDialog ||
+ isAbove(richTextElement, topDialog.element.querySelector(".b3-dialog")))) {
+ destroyAVRichTextEditor(true);
+ return;
} else if (window.siyuan.dialogs.length !== 0) {
window.siyuan.dialogs[window.siyuan.dialogs.length - 1].destroy();
return;
diff --git a/app/src/protyle/render/av/calendar/render.test.ts b/app/src/protyle/render/av/calendar/render.test.ts
index c6e9ea5a12..d3a213767c 100644
--- a/app/src/protyle/render/av/calendar/render.test.ts
+++ b/app/src/protyle/render/av/calendar/render.test.ts
@@ -165,7 +165,11 @@ test("calendar checkbox clicks and keyboard activation update only the chosen fi
const updates: unknown[] = [];
let opens = 0;
let html = "";
+ let startDrag: () => void;
+ let menusClosed = 0;
const root = {
+ isConnected: true,
+ classList: {add() {}},
querySelectorAll: (): unknown[] => [],
querySelector: () => ({addEventListener() {}}),
addEventListener(type: string, listener: (event: unknown) => void, capture?: boolean) {
@@ -179,6 +183,8 @@ test("calendar checkbox clicks and keyboard activation update only the chosen fi
"./state": {getCalendarState: () => ({anchor: start, mode: "week", rowLimit: 3}), getCalendarRequestRange: () => range},
"./settings": {isCalendarDateColumn: () => true, bindCalendarSettings() {}},
"./undated": {getCalendarUndatedHTML: () => "", bindCalendarUndated() {}},
+ "./hitTest": {getCalendarDropDay: () => start},
+ "./preview": {createCalendarPreviewLayout: () => ({})},
"../render": {genTabHeaderHTML: () => ""},
"../cellValue": {cellValueIsEmpty},
"../conditionalColor": {getConditionalBackground},
@@ -198,7 +204,10 @@ test("calendar checkbox clicks and keyboard activation update only the chosen fi
compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2020},
}).outputText, {
exports, require: (name: string) => modules[name] || {},
- window: {siyuan: {isPublish: mode === "publish", config: {lang: "en"}, languages: {}, menus: {menu: {remove() {}}}}},
+ window: {siyuan: {isPublish: mode === "publish", config: {lang: "en"}, languages: {},
+ menus: {menu: {remove() { menusClosed++; }}}},
+ setTimeout: (callback: () => void) => { startDrag = callback; return 1; }, addEventListener() {}},
+ AbortController,
document: {activeElement: null},
});
const block = {dataset: {avId: "database", nodeId: "carrier"},
@@ -228,5 +237,97 @@ test("calendar checkbox clicks and keyboard activation update only the chosen fi
assert.equal(args[9][0].rowID, "row");
assert.equal(args[9][0].colID, "second");
}
+ if (mode === "mobile") {
+ const closedBeforeDrag = menusClosed;
+ handlers.touchstart({
+ target: {closest: (selector: string) => selector === "[data-calendar-item]" ? item : null},
+ touches: [{identifier: 1, clientX: 10, clientY: 20}],
+ });
+ assert.equal(menusClosed, closedBeforeDrag, "touching an event does not dismiss its menu before dragging");
+ startDrag();
+ assert.equal(menusClosed, closedBeforeDrag + 1, "long-press dragging dismisses the item menu");
+ }
+ }
+});
+
+test("calendar edit-mode changes refresh controls and stale actions cannot create rows", async () => {
+ for (const mobile of [false, true]) {
+ const start = new Date(2026, 8, 1).getTime();
+ const range = {start, end: dates.addCalendarDays(start, 7), timeZone: "UTC"};
+ const state = {anchor: start, mode: "week", rowLimit: 3, expandedWeeks: new Set()};
+ const handlers: Record<string, (event: unknown) => void> = {};
+ let html = "";
+ let created = 0;
+ const root = {
+ querySelectorAll: (): unknown[] => [],
+ querySelector: () => ({addEventListener() {}}),
+ addEventListener(type: string, listener: (event: unknown) => void, capture?: boolean) {
+ if (capture !== true) {
+ handlers[type] = listener;
+ }
+ },
+ };
+ const block = {dataset: {avId: "database", nodeId: "carrier"},
+ querySelector: (selector: string) => selector === ".av__calendar" ? root : null, removeAttribute() {}};
+ const data = {viewID: "calendar", viewType: "calendar", view: {
+ calendar: {dateKeyID: "date"}, calendarRange: range,
+ columns: [{id: "date", type: "date"}], rows: [],
+ }} as unknown as IAV;
+ const protyle = {disabled: true, options: {}, element: {getAttribute: (): null => null},
+ wysiwyg: {element: {style: {}, setAttribute() {},
+ querySelectorAll: (selector: string) => selector === '.av[data-av-type="calendar"]' ? [block] : []}},
+ } as unknown as IProtyle;
+ const calendar = {} as typeof import("./render");
+ const modules: Record<string, unknown> = {
+ "./date": dates,
+ "./state": {getCalendarState: () => state, getCalendarRequestRange: () => range},
+ "./settings": {isCalendarDateColumn: () => true},
+ "./undated": {getCalendarUndatedHTML: () => "", bindCalendarUndated() {}},
+ "../render": {genTabHeaderHTML: () => ""},
+ "../newItemTemplate": {createAttributeViewItem: () => created++},
+ "../../../../util/escape": {escapeAttr: String, escapeHtml: String},
+ "../../../../constants": {Constants: {ZWSP: ""}},
+ "../container": {replaceAVContainer: (_block: unknown, value: string) => { html = value; }},
+ "../virtualScroll": {getAVData: () => data, getAVSelectedItemIDs: (): string[] => [], setAVData() {}},
+ "../search": {bindAvSearch() {}},
+ "../richText": {renderAVRichTextElements() {}},
+ "../locate": {finishAVLocate() {}},
+ "../render/av/calendar/render": calendar,
+ "../../util/functions": {isMobile: () => mobile},
+ "../ui/hideElements": {hideElements() {}},
+ "./disabledWYSIWYG": {disabledWYSIWYG() {}},
+ "./setEditMode": {updateMobileTitleReadonly() {}},
+ "../../dialog/tooltip": {hideTooltip() {}},
+ "./compatibility": {isAndroid: () => mobile, isIPhone: () => false},
+ };
+ const context = {
+ require: (name: string) => modules[name] || {},
+ window: {siyuan: {config: {lang: "en"}, languages: {}, menus: {menu: {remove() {}}}}},
+ document: {activeElement: null as Element | null},
+ };
+ const compile = (file: string) => transpileModule(readFileSync(file, "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2020},
+ }).outputText;
+ runInNewContext(compile(join(__dirname, "render.ts")), {...context, exports: calendar});
+ const modes = {} as typeof import("../../../util/onGet");
+ runInNewContext(compile(join(__dirname, "../../../util/onGet.ts")), {...context, exports: modes});
+ await calendar.renderCalendar(block as unknown as HTMLElement, protyle, data);
+ assert.doesNotMatch(html, /data-calendar-add=/);
+ modes.enableProtyle(protyle);
+ assert.match(html, /data-calendar-add=/);
+ const editableClick = handlers.click;
+ const clickAdd = () => editableClick({stopPropagation() {}, target: {
+ closest: (selector: string) => selector === "[data-calendar-add]" ? {dataset: {calendarAdd: start}} : null,
+ }});
+ clickAdd();
+ assert.equal(created, 1);
+ modes.disabledProtyle(protyle);
+ assert.doesNotMatch(html, /data-calendar-add=/);
+ clickAdd();
+ assert.equal(created, 1, "a handler retained before locking must check the current mode");
+ modes.enableProtyle(protyle);
+ assert.match(html, /data-calendar-add=/);
+ clickAdd();
+ assert.equal(created, 2);
}
});
diff --git a/app/src/protyle/render/av/calendar/render.ts b/app/src/protyle/render/av/calendar/render.ts
index 6d705ee015..795b4ace23 100644
--- a/app/src/protyle/render/av/calendar/render.ts
+++ b/app/src/protyle/render/av/calendar/render.ts
@@ -17,7 +17,7 @@ import {replaceAVContainer} from "../container";
import {renderAVRichTextElements} from "../richText";
import {avContextmenu} from "../action";
import {bindAvSearch} from "../search";
-import {getAVSelectedItemIDs, setAVData} from "../virtualScroll";
+import {getAVData, getAVSelectedItemIDs, setAVData} from "../virtualScroll";
import {addCalendarDays, calendarDay, calendarDayDistance, getCalendarInterval, getISOWeekForCalendarRow, ICalendarEvent, ICalendarSegment,
moveCalendarDate, packCalendarWeek, resizeCalendarDate} from "./date";
import {openCalendarJump} from "./jump";
@@ -32,6 +32,15 @@ const iconButton = (action: string, icon: string, label: string) => `<button typ
const canEditCalendar = (protyle: IProtyle) => !protyle.disabled && !window.siyuan.isPublish &&
!protyle.options.history?.created && !protyle.options.history?.snapshot;
+export const refreshCalendarReadonly = (protyle: IProtyle) => {
+ protyle.wysiwyg.element.querySelectorAll<HTMLElement>('.av[data-av-type="calendar"]').forEach(blockElement => {
+ const data = getAVData(blockElement);
+ if (data?.viewType === "calendar") {
+ void renderCalendar(blockElement, protyle, data);
+ }
+ });
+};
+
const openCalendarItem = (protyle: IProtyle, blockElement: HTMLElement, row: IAVRow) => {
const primary = row.cells.find(cell => cell.valueType === "block" || cell.value?.type === "block");
if (!primary?.value) {
@@ -175,6 +184,7 @@ const bindCalendarDrag = (root: HTMLElement, protyle: IProtyle, blockElement: HT
return;
}
dragging = true;
+ window.siyuan.menus.menu.remove();
root.classList.add("av__calendar--dragging");
sourceItems.forEach(element => element.classList.add("av__calendar-item--dragging"));
};
@@ -451,6 +461,9 @@ export const renderCalendar = async (blockElement: HTMLElement, protyle: IProtyl
void avRender(blockElement, protyle);
};
const create = (date: number) => {
+ if (!canEditCalendar(protyle)) {
+ return;
+ }
state.anchor = date;
createAttributeViewItem({protyle, blockElement, templateID: data.defaultTemplateID,
position: {calendarDate: date}});
@@ -528,7 +541,7 @@ export const renderCalendar = async (blockElement: HTMLElement, protyle: IProtyl
void renderCalendar(blockElement, protyle, data);
}
const field = target.closest<HTMLElement>("[data-calendar-create-field]");
- if (field && editable) {
+ if (field && canEditCalendar(protyle)) {
addCalendarDateField(protyle, blockElement, data, field.dataset.calendarCreateField as "date" | "created" | "updated");
}
});
@@ -554,7 +567,7 @@ export const renderCalendar = async (blockElement: HTMLElement, protyle: IProtyl
menu.addSeparator();
menu.addItem({icon: "iconOpen", label: window.siyuan.languages.openBy,
click: () => { void openCalendarItem(protyle, blockElement, entry.row); }});
- if (editable && dateColumn?.type === "date") {
+ if (canEditCalendar(protyle) && dateColumn?.type === "date") {
const week = item.closest<HTMLElement>("[data-calendar-week]");
const rect = week.getBoundingClientRect();
const day = addCalendarDays(Number(week.dataset.calendarWeek),
diff --git a/app/src/protyle/util/onGet.ts b/app/src/protyle/util/onGet.ts
index 556df89043..11123e2172 100644
--- a/app/src/protyle/util/onGet.ts
+++ b/app/src/protyle/util/onGet.ts
@@ -20,6 +20,7 @@ import {isMobile} from "../../util/functions";
import {foldPassiveType} from "../wysiwyg/renderBacklink";
import {showMessage} from "../../dialog/message";
import {avRender} from "../render/av/render";
+import {refreshCalendarReadonly} from "../render/av/calendar/render";
import {hideTooltip} from "../../dialog/tooltip";
import {stickyRow} from "../render/av/row";
import {getContenteditableElement} from "../wysiwyg/getBlock";
@@ -516,6 +517,7 @@ export const disabledForeverProtyle = (protyle: IProtyle) => {
/** 禁用编辑器 */
export const disabledProtyle = (protyle: IProtyle) => {
+ const wasDisabled = protyle.disabled;
window.siyuan.menus.menu.remove();
hideElements(["gutter", "toolbar", "select", "hint", "util"], protyle);
protyle.disabled = true;
@@ -531,6 +533,9 @@ export const disabledProtyle = (protyle: IProtyle) => {
protyle.background.element.classList.remove("protyle-background--enable");
}
disabledWYSIWYG(protyle.wysiwyg.element);
+ if (!wasDisabled) {
+ refreshCalendarReadonly(protyle);
+ }
if (protyle.breadcrumb) {
const readonlyButton = protyle.breadcrumb.element.parentElement.querySelector('[data-type="readonly"]');
readonlyButton.querySelector("use").setAttribute("xlink:href", "#iconLock");
@@ -552,6 +557,7 @@ export const enableProtyle = (protyle: IProtyle) => {
if (protyle.element.getAttribute("disabled-forever") === "true") {
return;
}
+ const wasDisabled = protyle.disabled;
protyle.disabled = false;
protyle.databaseAttributePanel?.updateReadonly();
if (isMobile()) {
@@ -587,6 +593,9 @@ export const enableProtyle = (protyle: IProtyle) => {
protyle.wysiwyg.element.querySelectorAll(".av").forEach((item: HTMLElement) => {
stickyRow(item, protyle.contentElement, "all");
});
+ if (wasDisabled) {
+ refreshCalendarReadonly(protyle);
+ }
if (protyle.breadcrumb) {
const readonlyButton = protyle.breadcrumb.element.parentElement.querySelector('[data-type="readonly"]');
readonlyButton.querySelector("use").setAttribute("xlink:href", "#iconUnlock");
diff --git a/app/tests/avAttributeCarrier.test.js b/app/tests/avAttributeCarrier.test.js
index 99b4fcf1f7..d100ac95d1 100644
--- a/app/tests/avAttributeCarrier.test.js
+++ b/app/tests/avAttributeCarrier.test.js
@@ -21,6 +21,7 @@ const runCases = async () => {
}
},
renderAVRichTextElements: () => {},
+ preserveAVBindingRange: () => () => {},
getColIconByType: () => "iconDatabase",
genAVAttributeRowHTML: ({value}) => `<div data-row-id="${value.blockID}" data-col-id="${value.keyID}"></div>`,
getPageSize: () => ({unGroupPageSize: 20, groupPageSize: {}}),
@@ -126,6 +127,7 @@ const runCases = async () => {
constructor(_app, _element, options) {
initialize = () => options.after({protyle: {
id: "row-editor", highlight: {styleElement: document.createElement("style")},
+ hint: {element: document.createElement("div")},
}});
}
destroy() {}
diff --git a/app/tests/avRichTextEditor.test.js b/app/tests/avRichTextEditor.test.js
index 9814477ecc..355bbcdb99 100644
--- a/app/tests/avRichTextEditor.test.js
+++ b/app/tests/avRichTextEditor.test.js
@@ -126,6 +126,24 @@ const runCases = async (sources) => {
assert.equal(hasAVEditorSession(state.owner), false);
assert.equal(document.querySelector(".av__richtext-mask"), null);
+ if (mobile) {
+ const cancelled = createOwner(true);
+ fragment.input.append(document.createTextNode("discarded"));
+ document.querySelector('[data-type="cancel"]').click();
+ await settle();
+ assert.equal(cancelled.saves.length, 0);
+ assert.equal(cancelled.closed(), 1);
+ assert.equal(document.querySelector(".av__richtext-mask"), null);
+
+ const returned = createOwner(true);
+ fragment.pendingInput = "pending";
+ editor.destroyAVRichTextEditor(true);
+ await settle();
+ assert.equal(returned.saves[0][0].text.content, "Initialpending");
+ assert.equal(returned.closed(), 1);
+ assert.equal(document.querySelector(".av__richtext-mask"), null);
+ }
+
const removed = createOwner(mode !== "document");
fragment.input.append(document.createTextNode("unsaved"));
await settle();