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 lunar date editing and parsing https://github.com/siyuan-note/siyuan/issues/20322
Daniel729b4d788739
diff --git a/app/src/plugin/Menu.ts b/app/src/plugin/Menu.tsindex f38d13c16d..b0a6d0b524 100644--- a/app/src/plugin/Menu.ts+++ b/app/src/plugin/Menu.ts@@ -1,7 +1,11 @@import {Menu as SiyuanMenu} from "../menus/Menu";+const independentMenus = new WeakMap<HTMLElement, Menu>();+export class Menu {private menu: SiyuanMenu;+ private parentMenu?: Menu;+ private childMenus = new Set<Menu>();public isOpen: boolean;public element: HTMLElement;@@ -37,8 +41,9 @@ export class Menu {this.menu.element.setAttribute("data-name", id);}if (independent) {+ independentMenus.set(this.element, this);const closeEvent = (event: MouseEvent) => {- if (!this.element.contains(event.target as Node)) {+ if (!this.contains(event.target as Node)) {this.close();}};@@ -54,6 +59,11 @@ export class Menu {this.menu.removeCB = () => {window.removeEventListener("click", closeEvent, true);this.element.removeEventListener("keydown", keydownEvent);+ this.childMenus.forEach(menu => menu.close());+ this.childMenus.clear();+ this.parentMenu?.childMenus.delete(this);+ this.parentMenu = undefined;+ independentMenus.delete(this.element);closeCB?.();this.element.remove();};@@ -101,6 +111,17 @@ export class Menu {if (this.isOpen) {return;}+ // 按触发控件记录菜单归属,点击派生菜单时保留父表单,父菜单关闭时清理子菜单。+ if (independentMenus.has(this.element)) {+ this.parentMenu?.childMenus.delete(this);+ this.parentMenu = undefined;+ const parentElement = options.target?.closest<HTMLElement>(".b3-menu");+ const parentMenu = parentElement && independentMenus.get(parentElement);+ if (parentMenu && parentMenu !== this && !this.contains(parentMenu.element)) {+ this.parentMenu = parentMenu;+ parentMenu.childMenus.add(this);+ }+ }this.menu.popup(options);}@@ -114,4 +135,8 @@ export class Menu {close() {this.menu.remove();}++ private contains(target: Node): boolean {+ return this.element.contains(target) || Array.from(this.childMenus).some(menu => menu.contains(target));+ }}diff --git a/app/src/protyle/render/av/calendar/date.ts b/app/src/protyle/render/av/calendar/date.tsindex 85d24976c5..a5a3337050 100644--- a/app/src/protyle/render/av/calendar/date.ts+++ b/app/src/protyle/render/av/calendar/date.ts@@ -91,7 +91,7 @@ export const getCalendarDate = (value: IAVCellValue, format: TAVDateFormat = "")const time = /[ T](\d{2}):(\d{2})(?::(\d{2}))?$/.exec(content);const dateText = time ? content.slice(0, time.index) : content;for (const candidate of new Set<TAVDateFormat>(["", format, "full"])) {- const parsed = parseDateValue(dateText, candidate);+ const parsed = parseDateValue(dateText, candidate, format === "lunar");if (!parsed.isNotEmpty || parsed.hasEndDate || !parsed.isNotTime) {continue;}diff --git a/app/src/protyle/render/av/cell.ts b/app/src/protyle/render/av/cell.tsindex a363082c74..0e136ae0d1 100644--- a/app/src/protyle/render/av/cell.ts+++ b/app/src/protyle/render/av/cell.ts@@ -1185,6 +1185,10 @@ export const updateCellsValue = async (protyle: IProtyle, nodeElement: HTMLElemecellValue = transformCellValue(type, newValue);} else {cellValue = genCellValue(type, newValue, column?.dateFormat);+ // 非空文本解析失败时跳过该单元格,空文本和清空操作仍可删除日期。+ if (type === "date" && typeof newValue === "string" && newValue.trim() && !cellValue.date.isNotEmpty) {+ continue;+ }}if (type === "block" && typeof cellValue.block.icon === "undefined") {cellValue.block.icon = oldValue.block.icon || "";diff --git a/app/src/protyle/render/av/dateFormat.ts b/app/src/protyle/render/av/dateFormat.tsindex 4d32383b02..01666e38b1 100644--- a/app/src/protyle/render/av/dateFormat.ts+++ b/app/src/protyle/render/av/dateFormat.ts@@ -50,7 +50,11 @@ export const formatDateValue = (value: IAVCellDateValue, format: TAVDateFormat =const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");const parseFullDate = (value: string) => {- const tokens = window.siyuan.languages._attrView.dateFormatFullTemplate.split(/(\$\{year}|\$\{month}|\$\{day})/);+ const template = typeof window === "undefined" ? undefined : window.siyuan?.languages?._attrView?.dateFormatFullTemplate;+ if (!template) {+ return;+ }+ const tokens = template.split(/(\$\{year}|\$\{month}|\$\{day})/);const captures: string[] = [];const months = getMonths();const pattern = tokens.map((token: string) => {@@ -83,29 +87,24 @@ const parseFullDate = (value: string) => {};};-const parseDateEndpoint = (value: string, format: TAVDateFormat): {content: number, isNotTime: boolean} | undefined => {+const parseDateEndpoint = (value: string, format: TAVDateFormat, allowLunar: boolean): {content: number, isNotTime: boolean} | undefined => {const trimmed = value.trim();const timeMatch = trimmed.match(/\s+(\d{1,2}):(\d{2})$/);const hour = timeMatch ? Number(timeMatch[1]) : 0;const minute = timeMatch ? Number(timeMatch[2]) : 0;const dateText = timeMatch ? trimmed.substring(0, timeMatch.index).trim() : trimmed;+ const lunar = allowLunar && parseLunarDate(dateText);+ if (lunar) {+ const content = lunarToSolar(lunar, hour, minute);+ return content === undefined ? undefined : {content, isNotTime: !timeMatch};+ }let year: number;let month: number;let day: number;- if (format === "lunar") {- const lunar = parseLunarDate(dateText);- if (!lunar) {- const suffix = ` (${window.siyuan.languages._attrView.lunarRange})`;- const solarText = dateText.endsWith(suffix) ? dateText.slice(0, -suffix.length) : dateText;- return /^\d{4}-\d{1,2}-\d{1,2}$/.test(solarText) ?- parseDateEndpoint(solarText + (timeMatch ? timeMatch[0] : ""), "") : undefined;- }- const content = lunar && lunarToSolar(lunar, hour, minute);- return content === undefined ? undefined : {content, isNotTime: !timeMatch};- } else if (format === "full") {+ if (format === "lunar" || format === "full") {const parts = parseFullDate(dateText);if (!parts) {- return;+ return parseDateEndpoint(value, "", allowLunar);}({year, month, day} = parts);} else {@@ -140,7 +139,14 @@ const parseDateEndpoint = (value: string, format: TAVDateFormat): {content: numb}}if (!match) {- return;+ if (format !== "") {+ return parseDateEndpoint(value, "", allowLunar);+ }+ const parts = parseFullDate(dateText);+ if (!parts) {+ return;+ }+ ({year, month, day} = parts);}}if (hour > 23 || minute > 59 || month < 1 || month > 12 || day < 1 || day > 31) {@@ -156,14 +162,15 @@ const parseDateEndpoint = (value: string, format: TAVDateFormat): {content: numbreturn {content: parsed.valueOf(), isNotTime: !timeMatch};};-export const parseDateValue = (value: string, format: TAVDateFormat = ""): IAVCellDateValue => {- const normalized = format === "lunar" ? value.replaceAll(` (${window.siyuan.languages._attrView.lunarRange})`, "") : value;+export const parseDateValue = (value: string, format: TAVDateFormat = "", allowLunar = true): IAVCellDateValue => {+ const range = typeof window === "undefined" ? undefined : window.siyuan?.languages?._attrView?.lunarRange;+ const normalized = range && allowLunar ? value.replaceAll(` (${range})`, "") : value;const endpoints = normalized.split(/\s*→\s*|\s+[~-]\s+/);if (endpoints.length > 2) {return {content: null, isNotEmpty: false, content2: null, isNotEmpty2: false, hasEndDate: false, isNotTime: true};}- const start = parseDateEndpoint(endpoints[0], format);- const end = endpoints.length === 2 ? parseDateEndpoint(endpoints[1], format) : undefined;+ const start = parseDateEndpoint(endpoints[0], format, allowLunar);+ const end = endpoints.length === 2 ? parseDateEndpoint(endpoints[1], format, allowLunar) : undefined;if (!start || (endpoints.length === 2 && !end)) {return {content: null, isNotEmpty: false, content2: null, isNotEmpty2: false, hasEndDate: false, isNotTime: true};}diff --git a/app/src/protyle/render/av/datePaste.test.ts b/app/src/protyle/render/av/datePaste.test.tsnew file mode 100644index 0000000000..fcf5a73f5a--- /dev/null+++ b/app/src/protyle/render/av/datePaste.test.ts@@ -0,0 +1,64 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";+import {isAVDateType, isAVReadonlyType, isAVTextType} from "./capabilities";+import {cloneAVCellValueSnapshot, createAVCellUpdateOperation, genEmptyAVCellValue} from "./cellValue";+import {rebindAVCellValue} from "./dragFillValue";+import {formatDateValue, parseDateValue} from "./dateFormat";+import type {IAVSelectedCell} from "./selectionState";++const isCellUpdate = (operation: IOperation): operation is Extract<IOperation, {action: "updateAttrViewCell"}> =>+ operation.action === "updateAttrViewCell";++test("date paste preserves stored values on invalid text and supports explicit clearing and calendar conversion", async () => {+ Object.defineProperty(globalThis, "window", {configurable: true,+ value: {siyuan: {languages: JSON.parse(readFileSync("appearance/langs/en.json", "utf8"))}}});+ const source = readFileSync("src/protyle/render/av/cell.ts", "utf8");+ const fragment = source.slice(source.indexOf("export const genCellValue ="), source.indexOf("export const cellScrollIntoView =")) ++ source.slice(source.indexOf("export const updateCellsValue ="), source.indexOf("export const updateAttrViewCellInOtherElements ="));+ const exports = {} as Pick<typeof import("./cell"), "updateCellsValue">;+ runInNewContext(transpileModule(fragment, {compilerOptions: {+ module: ModuleKind.CommonJS, target: ScriptTarget.ES2021,+ }}).outputText, {exports, isAVDateType, isAVReadonlyType, isAVTextType, cloneAVCellValueSnapshot, createAVCellUpdateOperation,+ genEmptyAVCellValue, rebindAVCellValue, formatDateValue, parseDateValue,+ getAVBatchEditMode: () => "replace", getCellValueText: () => "stored date",+ objEquals: (first: unknown, second: unknown) => JSON.stringify(first) === JSON.stringify(second)});+ const stored: IAVCellValue = {id: "date-value", keyID: "birthday", blockID: "row", type: "date",+ date: {content: new Date(2024, 0, 2, 3, 4, 5, 123).valueOf(), isNotEmpty: true, isNotTime: false}};+ const snapshot = JSON.stringify(stored);+ const block = {dataset: {avId: "database", nodeId: "database-block"},+ getAttribute: () => "table"} as unknown as HTMLElement;+ const paste = (value: string | undefined, format: TAVDateFormat) => {+ const column: IAVColumn = {id: "birthday", name: "Birthday", type: "date", dateFormat: format,+ date: {autoFillNow: false, fillSpecificTime: true}};+ const selected: IAVSelectedCell = {groupID: "", rowID: "row", colID: column.id, rowIndex: 0, colIndex: 0, column,+ cell: {id: stored.id, value: stored, valueType: "date", bgColor: "", color: ""}};+ return exports.updateCellsValue({} as IProtyle, block, value, undefined, [column], undefined,+ true, false, false, [selected], false);+ };+ for (const format of ["full", "lunar"] as TAVDateFormat[]) {+ for (const text of ["not a date", "2025-02-30", "Chinese lunar 2026, Leap Month 6, day 1",+ "2025-07-25 → invalid end"]) {+ const operations = await paste(text, format);+ assert.equal(operations.doOperations.length, 0, `${format}: ${text}`);+ assert.equal(operations.undoOperations.length, 0);+ assert.equal(JSON.stringify(stored), snapshot);+ }+ for (const empty of [undefined, ""]) {+ const operations = await paste(empty, format);+ const operation = operations.doOperations.find(isCellUpdate);+ assert.ok(operation);+ assert.equal(operation.data.date.isNotEmpty, false, "explicit clearing remains available");+ }+ for (const text of ["July 25, 2025 14:07", "Chinese lunar 2025, Leap Month 6, day 1 14:07"]) {+ const operations = await paste(text, format);+ const operation = operations.doOperations.find(isCellUpdate);+ assert.ok(operation);+ assert.equal(operation.data.date.content, new Date(2025, 6, 25, 14, 7).valueOf());+ assert.equal(operations.undoOperations.find(isCellUpdate).data.date.content,+ stored.date.content);+ }+ }+});diff --git a/app/src/protyle/render/av/fieldValueEditor.ts b/app/src/protyle/render/av/fieldValueEditor.tsindex 63d3398123..d3131da629 100644--- a/app/src/protyle/render/av/fieldValueEditor.ts+++ b/app/src/protyle/render/av/fieldValueEditor.ts@@ -177,7 +177,7 @@ export const bindFieldLunarDates = (host: HTMLElement) => {},});const rect = target.getBoundingClientRect();- menu.open({x: rect.left, y: rect.bottom, h: rect.height});+ menu.open({x: rect.left, y: rect.bottom, h: rect.height, target});}));};diff --git a/app/src/protyle/render/av/lunarCalendar.test.ts b/app/src/protyle/render/av/lunarCalendar.test.tsindex 2e54046c88..fede06fdbc 100644--- a/app/src/protyle/render/av/lunarCalendar.test.ts+++ b/app/src/protyle/render/av/lunarCalendar.test.ts@@ -4,6 +4,7 @@ import {join} from "node:path";import {test} from "node:test";import {formatLunarDate, getLunarMonths, lunarToSolar, parseLunarDate, solarToLunar} from "./lunarCalendar";import {formatDateDisplay, parseDateValue} from "./dateFormat";+import {getCalendarDate} from "./calendar/date";const languagesPath = join(__dirname, "../../../../appearance/langs");const setLanguage = (name: string) => Object.defineProperty(globalThis, "window", {@@ -75,3 +76,75 @@ test("Gregorian clipboard dates remain accepted in lunar fields", () => {setLanguage("en.json");assert.equal(parseDateValue("2025-07-25 14:07", "lunar").content, new Date(2025, 6, 25, 14, 7).valueOf());});++test("unambiguous lunar, localized Gregorian, and ISO clipboard dates cross field calendars", () => {+ const formats: TAVDateFormat[] = ["", "full", "lunar", "month-day-year", "day-month-year", "year-month-day"];+ for (const language of readdirSync(languagesPath).filter(name => name.endsWith(".json"))) {+ setLanguage(language);+ const start = new Date(2025, 6, 25, 14, 7).valueOf();+ const end = new Date(2025, 6, 26, 15, 8).valueOf();+ for (const source of ["", "full", "lunar"] as TAVDateFormat[]) {+ const text = `${formatDateDisplay(start, source, false)} → ${formatDateDisplay(end, source, false)}`;+ for (const target of formats) {+ const parsed = parseDateValue(text, target);+ assert.equal(parsed.content, start, `${language}: ${source} to ${target}`);+ assert.equal(parsed.content2, end);+ assert.equal(parsed.hasEndDate, true);+ assert.equal(parsed.isNotTime, false);+ }+ }+ const legacy = new Date(1800, 0, 2, 14, 7).valueOf();+ assert.equal(parseDateValue(formatDateDisplay(legacy, "lunar", false), "full").content, legacy);+ }+ setLanguage("en.json");+ assert.equal(parseDateValue("07/08/2025", "month-day-year").content, new Date(2025, 6, 8).valueOf());+ assert.equal(parseDateValue("07/08/2025", "day-month-year").content, new Date(2025, 7, 7).valueOf());+ assert.equal(parseDateValue("07/08/2025", "lunar").isNotEmpty, false);+});++test("lunar text validates the entered time rather than a nonexistent local midnight", () => {+ const originalTimezone = process.env.TZ;+ try {+ process.env.TZ = "America/Sao_Paulo";+ setLanguage("en.json");+ const noon = new Date(2018, 10, 4, 12).valueOf();+ const lunar = solarToLunar(noon);+ assert.deepEqual(parseLunarDate(formatLunarDate(lunar)), lunar);+ for (const format of ["lunar", "full", ""] as TAVDateFormat[]) {+ assert.equal(parseDateValue(formatDateDisplay(noon, "lunar", false), format).content, noon);+ }+ assert.equal(parseDateValue(`${formatLunarDate(lunar)} 00:30`, "lunar").isNotEmpty, false);+ } finally {+ if (originalTimezone === undefined) {+ delete process.env.TZ;+ } else {+ process.env.TZ = originalTimezone;+ }+ }+});++test("ISO date parsing retains its standalone behavior without a localized UI", () => {+ const originalWindow = Object.getOwnPropertyDescriptor(globalThis, "window");+ Reflect.deleteProperty(globalThis, "window");+ try {+ assert.equal(parseDateValue("2026-09-01").content, new Date(2026, 8, 1).valueOf());+ assert.equal(parseDateValue("2026-09-01 14:07").content, new Date(2026, 8, 1, 14, 7).valueOf());+ assert.equal(parseDateValue("not a date").isNotEmpty, false);+ } finally {+ if (originalWindow) {+ Object.defineProperty(globalThis, "window", originalWindow);+ }+ }+});++test("calendar templates preserve the field calendar rules while clipboard parsing permits conversion", () => {+ setLanguage("en.json");+ const content = new Date(2025, 6, 25, 14, 7).valueOf();+ const value: IAVCellValue = {type: "date", date: {isNotEmpty: false}, hasRenderTemplate: true,+ renderedContent: formatDateDisplay(content, "lunar", false)};+ assert.equal(getCalendarDate(value, "lunar").content, content);+ assert.equal(getCalendarDate(value, "full"), undefined);+ assert.equal(parseDateValue(value.renderedContent, "full").content, content);+ value.renderedContent = formatDateDisplay(new Date(1800, 0, 2).valueOf(), "lunar");+ assert.equal(getCalendarDate(value, "full"), undefined);+});diff --git a/app/src/protyle/render/av/lunarCalendar.ts b/app/src/protyle/render/av/lunarCalendar.tsindex 1a8122d832..77dadc04fa 100644--- a/app/src/protyle/render/av/lunarCalendar.ts+++ b/app/src/protyle/render/av/lunarCalendar.ts@@ -35,13 +35,20 @@ export const solarToLunar = (content: number): ILunarDate | undefined => {export const getLunarMonths = (year: number) => months.filter(month => month[0] === year);-export const lunarToSolar = (lunar: ILunarDate, hours = 0, minutes = 0): number | undefined => {+const getLunarCivilDate = (lunar: ILunarDate): Date | undefined => {const month = months.find(month => month[0] === lunar.year && month[1] === lunar.month);- if (!month || !Number.isInteger(lunar.day) || lunar.day < 1 || lunar.day > month[3] ||- !Number.isInteger(hours) || hours < 0 || hours > 23 || !Number.isInteger(minutes) || minutes < 0 || minutes > 59) {+ if (!month || !Number.isInteger(lunar.day) || lunar.day < 1 || lunar.day > month[3]) {+ return undefined;+ }+ return new Date((month[2] + lunar.day - 1) * dayMilliseconds);+};++export const lunarToSolar = (lunar: ILunarDate, hours = 0, minutes = 0): number | undefined => {+ const civil = getLunarCivilDate(lunar);+ if (!civil || !Number.isInteger(hours) || hours < 0 || hours > 23 ||+ !Number.isInteger(minutes) || minutes < 0 || minutes > 59) {return undefined;}- const civil = new Date((month[2] + lunar.day - 1) * dayMilliseconds);const result = new Date(civil.getUTCFullYear(), civil.getUTCMonth(), civil.getUTCDate(), hours, minutes);// 夏令时造成不存在的本地时间时返回错误,不把输入静默调整为其它时间。if (result.getFullYear() !== civil.getUTCFullYear() || result.getMonth() !== civil.getUTCMonth() ||@@ -64,11 +71,15 @@ export const formatLunarDate = (lunar: ILunarDate) => window.siyuan.languages._a.replaceAll("${day}", getLunarDayLabel(lunar.day));export const parseLunarDate = (content: string): ILunarDate | undefined => {+ const template = typeof window === "undefined" ? undefined : window.siyuan?.languages?._attrView?.lunarDateTemplate;+ if (!template || !content.startsWith(template.split(/\$\{year}|\$\{month}|\$\{day}/)[0])) {+ return undefined;+ }const escape = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");const names = Array.from({length: 12}, (_, index) => [getLunarMonthLabel(index + 1), getLunarMonthLabel(-index - 1)]).flat();const days: string[] = window.siyuan.languages._attrView.lunarDays.split("|");const captures: string[] = [];- const pattern = window.siyuan.languages._attrView.lunarDateTemplate.split(/(\$\{year}|\$\{month}|\$\{day})/).map((token: string) => {+ const pattern = template.split(/(\$\{year}|\$\{month}|\$\{day})/).map((token: string) => {if (token === "${year}") {captures.push("year");return "(\\d{4})";@@ -87,5 +98,5 @@ export const parseLunarDate = (content: string): ILunarDate | undefined => {captures.forEach((key, index) => parts[key] = match[index + 1]);const index = names.indexOf(parts.month);const lunar = {year: Number(parts.year), month: (Math.floor(index / 2) + 1) * (index % 2 ? -1 : 1), day: days.indexOf(parts.day) + 1};- return lunarToSolar(lunar) === undefined ? undefined : lunar;+ return getLunarCivilDate(lunar) ? lunar : undefined;};diff --git a/app/src/protyle/render/av/lunarDate.test.ts b/app/src/protyle/render/av/lunarDate.test.tsindex 3720b3bd0c..7d63e57670 100644--- a/app/src/protyle/render/av/lunarDate.test.ts+++ b/app/src/protyle/render/av/lunarDate.test.ts@@ -10,6 +10,43 @@ import {compileString} from "sass";const browserCases = (sources: Record<string, string>, language: Record<string, unknown>, data: unknown, css: string) => {const check: typeof assert = require("node:assert/strict");+ // 只替代菜单外观和定位,保留独立菜单、移动端选择器及农历字段的真实事件处理。+ class MenuSurface {+ public removeCB?: () => void;+ constructor(public element: HTMLElement) {+ element.addEventListener("click", event => {+ if (typeof event.detail === "string" && event.detail === "back") {+ this.remove();+ }+ });+ }+ remove() {+ const callback = this.removeCB;+ this.removeCB = undefined;+ callback?.();+ this.element.lastElementChild.innerHTML = "";+ this.element.classList.add("fn__none");+ }+ popup() {+ this.element.classList.remove("fn__none");+ }+ addItem(options: IMenu) {+ const element = document.createElement(options.type === "empty" ? "div" : "button");+ element.innerHTML = options.label;+ this.element.lastElementChild.append(element);+ options.bind?.(element);+ if (options.click) {+ element.addEventListener("click", (event: MouseEvent) => {+ const keepOpen = options.click(element, event);+ event.preventDefault();+ event.stopImmediatePropagation();+ if (!keepOpen) {+ this.remove();+ }+ });+ }+ }+ }const modules: Record<string, unknown> = {"../../../../../kernel/av/lunar_calendar_data.json": data,"./capabilities": {},@@ -20,12 +57,18 @@ const browserCases = (sources: Record<string, string>, language: Record<string,escapeHtml: (value: string) => value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">"),},"../../../dialog/message": {showMessage: () => {}},+ "../menus/Menu": {Menu: MenuSurface},};+ modules["../../util/escape"] = modules["../../../util/escape"];Object.assign(window, {siyuan: {languages: language}});for (const [name, source] of Object.entries(sources)) {const exports = {};new Function("require", "exports", source)((name: string) => modules[name], exports);modules["./" + name] = exports;+ if (name === "pluginMenu") {+ modules["../../../plugin/Menu"] = exports;+ modules["../../plugin/Menu"] = exports;+ }}const editor = modules["./lunarDate"] as typeof import("./lunarDate");const style = document.createElement("style");@@ -111,6 +154,67 @@ const browserCases = (sources: Record<string, string>, language: Record<string,check.equal(closeCount, before, "Enter on a select confirms its option without closing the editor");}}+ mount({isNotEmpty: false, isNotTime: true}, true);+ const beforeConfirm = closeCount;+ menu.querySelector<HTMLButtonElement>("[data-lunar-confirm]").click();+ submit();+ check.equal(updates.length, 1, "confirm saves the prefilled date exactly once");+ check.equal(updates[0].isNotEmpty, true);+ check.equal(closeCount, beforeConfirm + 1);+ mount(original, true);+ select("year", "2026");+ const beforeInvalid = closeCount;+ menu.querySelector<HTMLButtonElement>("[data-lunar-confirm]").click();+ check.equal(updates.length, 0, "invalid confirmation preserves the stored value");+ check.equal(closeCount, beforeInvalid, "invalid confirmation keeps the editor open");++ const commonMenu = document.createElement("div");+ commonMenu.className = "b3-menu fn__none";+ commonMenu.innerHTML = '<div class="b3-menu__title"><span class="b3-menu__label"></span></div><div class="b3-menu__items"></div>';+ document.body.append(commonMenu);+ Object.assign(window.siyuan, {menus: {menu: new MenuSurface(commonMenu)}});+ const fieldEditor = modules["./fieldValueEditor"] as typeof import("./fieldValueEditor");+ const mobileSelect = modules["./nativeSelect"] as typeof import("../../../mobile/util/nativeSelect");+ const calendar = modules["./lunarCalendar"] as typeof import("./lunarCalendar");+ mobileSelect.initMobileSelect();+ const host = document.createElement("div");+ host.innerHTML = fieldEditor.getValueInputHTML({id: "birthday", name: "Birthday", type: "date", dateFormat: "lunar"},+ {mode: "static", value: {type: "date", date: {...original, isNotTime: true, hasEndDate: false}}});+ document.body.append(host);+ fieldEditor.bindFieldLunarDates(host);+ const trigger = host.querySelector<HTMLButtonElement>("button");+ trigger.click();+ const parent = document.querySelector<HTMLElement>('[data-menu="true"]');+ const choose = (part: string, label: string) => {+ const select = parent.querySelector<HTMLSelectElement>(`[data-lunar-part="${part}"]`);+ select.click();+ const picker = mobileSelect.getMobileSelectMenuElement();+ const choice = Array.from(picker.querySelectorAll<HTMLButtonElement>("button")).find(item => item.textContent === label);+ check.ok(choice, "mobile date option exists");+ choice.click();+ check.equal(select.isConnected, true, "selecting a child menu preserves the parent form");+ check.equal(parent.isConnected, true);+ check.equal(picker.isConnected, false, "the option menu closes after selection");+ };+ choose("year", "2026");+ choose("month", calendar.getLunarMonthLabel(8));+ choose("day", calendar.getLunarDayLabel(15));+ parent.querySelector<HTMLButtonElement>("[data-lunar-confirm]").click();+ check.equal(parent.isConnected, false);+ check.equal(JSON.parse(trigger.dataset.lunarValue).content, new Date(2026, 8, 25).valueOf());++ trigger.click();+ const reopened = document.querySelector<HTMLElement>('[data-menu="true"]');+ reopened.querySelector<HTMLSelectElement>('[data-lunar-part="year"]').click();+ const picker = mobileSelect.getMobileSelectMenuElement();+ reopened.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true}));+ check.equal(reopened.isConnected, false);+ check.equal(picker.isConnected, false, "closing the parent also removes its child menu");+ check.equal(mobileSelect.getMobileSelectMenuElement(), undefined);+ trigger.click();+ const outsideClosed = document.querySelector<HTMLElement>('[data-menu="true"]');+ document.body.click();+ check.equal(outsideClosed.isConnected, false, "outside clicks still dismiss independent menus");return "Lunar date editor cases passed";};@@ -122,6 +226,12 @@ test("lunar date controls preserve dates, validate selections, and fit narrow latranspileModule(readFileSync(path.join(__dirname, name + ".ts"), "utf8"), {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},}).outputText]));+ for (const [name, file] of Object.entries({pluginMenu: "src/plugin/Menu.ts",+ nativeSelect: "src/mobile/util/nativeSelect.ts", fieldValueEditor: "src/protyle/render/av/fieldValueEditor.ts"})) {+ sources[name] = transpileModule(readFileSync(file, "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText;+ }const language = JSON.parse(readFileSync("appearance/langs/zh-CN.json", "utf8"));const data = JSON.parse(readFileSync("../kernel/av/lunar_calendar_data.json", "utf8"));const css = compileString(readFileSync("src/assets/scss/business/_av.scss", "utf8")).css;diff --git a/app/src/protyle/render/av/lunarDate.ts b/app/src/protyle/render/av/lunarDate.tsindex cbd35ddc3b..599285f3ea 100644--- a/app/src/protyle/render/av/lunarDate.ts+++ b/app/src/protyle/render/av/lunarDate.ts@@ -37,6 +37,7 @@ ${getEndpointHTML(value.isNotEmpty2 ? value.content2 : now, value.isNotTime, !va<button class="b3-menu__separator"></button><label class="b3-menu__item"><span class="fn__flex-center">${lang.endDate}</span><span class="fn__space fn__flex-1"></span><input data-lunar-end type="checkbox" class="b3-switch b3-switch--menu"${value.hasEndDate ? " checked" : ""}></label><label class="b3-menu__item"><span class="fn__flex-center">${lang.includeTime}</span><span class="fn__space fn__flex-1"></span><input data-lunar-include-time type="checkbox" class="b3-switch b3-switch--menu"${value.isNotTime ? "" : " checked"}></label>+<div class="fn__flex"><span class="fn__flex-1"></span><button type="button" class="b3-button b3-button--text" data-lunar-confirm>${escapeHtml(lang.confirm)}</button></div><button class="b3-menu__separator"></button><button class="b3-menu__item" data-type="clearDate"><svg class="b3-menu__icon"><use xlink:href="#iconTrashcan"></use></svg><span class="b3-menu__label">${lang.clear}</span></button></div></div>`;@@ -133,6 +134,14 @@ export const bindLunarDateEditor = (options: {}}}));+ options.menuElement.querySelector("[data-lunar-confirm]").addEventListener("click", event => {+ event.preventDefault();+ event.stopPropagation();+ dirty = true;+ if (submit()) {+ options.close();+ }+ });options.menuElement.querySelector('[data-type="clearDate"]').addEventListener("click", event => {event.preventDefault();event.stopPropagation();diff --git a/kernel/av/layout_calendar.go b/kernel/av/layout_calendar.goindex 388a303536..0f7c1067a5 100644--- a/kernel/av/layout_calendar.go+++ b/kernel/av/layout_calendar.go@@ -76,7 +76,7 @@ var calendarTemplateTimePattern = regexp.MustCompile(`[ T](\d{2}):(\d{2})(?::(\d// newCalendarTemplateDateParser 复用字段日期格式和当前语言的月份、日期模板,每次日历渲染只编译一次。func newCalendarTemplateDateParser(format DateDisplayFormat) func(string, *time.Location) *ValueDate {- var lunarParser func(string, *time.Location) (time.Time, bool)+ var lunarParser func(string) (time.Time, bool)if format == DateDisplayFormatLunar {lunarParser = newLunarDateParser()}@@ -118,10 +118,10 @@ func newCalendarTemplateDateParser(format DateDisplayFormat) func(string, *time.var date time.Timefound := falseif lunarParser != nil {- date, found = lunarParser(content, location)+ date, found = lunarParser(content)}for _, layout := range layouts {- if parsed, err := time.ParseInLocation(layout, content, location); err == nil {+ if parsed, err := time.ParseInLocation(layout, content, time.UTC); err == nil {date = parsedfound = truebreak@@ -141,13 +141,14 @@ func newCalendarTemplateDateParser(format DateDisplayFormat) func(string, *time.break}}- date = time.Date(year, time.Month(month), day, 0, 0, 0, 0, location)+ date = time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC)if int(date.Month()) != month || date.Day() != day {return nil}}parsed := time.Date(date.Year(), date.Month(), date.Day(), hour, minute, second, 0, location)- if date.Year() < 1 || parsed.Day() != date.Day() || parsed.Hour() != hour || parsed.Minute() != minute || parsed.Second() != second {+ if date.Year() < 1 || parsed.Year() != date.Year() || parsed.Month() != date.Month() || parsed.Day() != date.Day() ||+ parsed.Hour() != hour || parsed.Minute() != minute || parsed.Second() != second {return nil}return &ValueDate{Content: parsed.UnixMilli(), IsNotEmpty: true, IsNotTime: timeParts == nil}diff --git a/kernel/av/lunar_calendar.go b/kernel/av/lunar_calendar.goindex 5af585e2ee..90a0beb92f 100644--- a/kernel/av/lunar_calendar.go+++ b/kernel/av/lunar_calendar.go@@ -51,11 +51,11 @@ func solarToLunar(solar time.Time) (lunar lunarDate, ok bool) {return lunarDate{month[0], month[1], day - month[2] + 1}, true}-func lunarToSolar(lunar lunarDate, location *time.Location) (time.Time, bool) {+// 只转换公历年月日,时区和具体时间由调用方校验,避免经过不存在的本地零点时改变日期。+func lunarToSolar(lunar lunarDate) (time.Time, bool) {for _, month := range lunarCalendar.Months {if month[0] == lunar.year && month[1] == lunar.month && lunar.day > 0 && lunar.day <= month[3] {- civil := time.Unix(int64(month[2]+lunar.day-1)*86400, 0).UTC()- return time.Date(civil.Year(), civil.Month(), civil.Day(), 0, 0, 0, 0, location), true+ return time.Unix(int64(month[2]+lunar.day-1)*86400, 0).UTC(), true}}return time.Time{}, false@@ -78,7 +78,7 @@ func formatLunarDate(lunar lunarDate) string {"${day}", strings.Split(GetAttributeViewI18n("lunarDays"), "|")[lunar.day-1]).Replace(GetAttributeViewI18n("lunarDateTemplate"))}-func newLunarDateParser() func(string, *time.Location) (time.Time, bool) {+func newLunarDateParser() func(string) (time.Time, bool) {names := make([]string, 0, 24)monthValues := map[string]int{}for month := 1; month <= 12; month++ {@@ -100,12 +100,12 @@ func newLunarDateParser() func(string, *time.Location) (time.Time, bool) {regexp.QuoteMeta("${month}"), "(?P<month>"+strings.Join(names, "|")+")",regexp.QuoteMeta("${day}"), "(?P<day>"+strings.Join(dayNames, "|")+")").Replace(pattern)parser := regexp.MustCompile("^" + pattern + "$")- return func(content string, location *time.Location) (time.Time, bool) {+ return func(content string) (time.Time, bool) {parts := parser.FindStringSubmatch(content)if parts == nil {return time.Time{}, false}year, _ := strconv.Atoi(parts[parser.SubexpIndex("year")])- return lunarToSolar(lunarDate{year, monthValues[parts[parser.SubexpIndex("month")]], dayValues[parts[parser.SubexpIndex("day")]]}, location)+ return lunarToSolar(lunarDate{year, monthValues[parts[parser.SubexpIndex("month")]], dayValues[parts[parser.SubexpIndex("day")]]})}}diff --git a/kernel/av/lunar_calendar_test.go b/kernel/av/lunar_calendar_test.goindex a10a516597..1a50fc5981 100644--- a/kernel/av/lunar_calendar_test.go+++ b/kernel/av/lunar_calendar_test.go@@ -39,7 +39,7 @@ func TestLunarCalendarCoverage(t *testing.T) {}for day := 1; day <= month[3]; day++ {want := lunarDate{month[0], month[1], day}- solar, ok := lunarToSolar(want, time.UTC)+ solar, ok := lunarToSolar(want)if !ok {t.Fatalf("cannot convert %v", want)}@@ -54,7 +54,7 @@ func TestLunarCalendarCoverage(t *testing.T) {}}for _, date := range []lunarDate{{2026, -6, 1}, {2025, -6, 30}, {2025, 1, 31}, {2100, 12, 2}, {1900, 1, 1}} {- if _, ok := lunarToSolar(date, time.UTC); ok {+ if _, ok := lunarToSolar(date); ok {t.Fatalf("invalid lunar date accepted: %v", date)}}@@ -97,11 +97,11 @@ func TestLunarDateLocalizedRoundTrips(t *testing.T) {setLunarTestLanguage(t, language)parser := newCalendarTemplateDateParser(DateDisplayFormatLunar)for _, lunar := range []lunarDate{{2025, 6, 1}, {2025, -6, 1}, {2026, 8, 15}} {- date, ok := lunarToSolar(lunar, time.Local)+ date, ok := lunarToSolar(lunar)if !ok {t.Fatal(lunar)}- date = date.Add(14*time.Hour + 7*time.Minute)+ date = time.Date(date.Year(), date.Month(), date.Day(), 14, 7, 0, 0, time.Local)text := formatDateDisplay(date.UnixMilli(), DateDisplayFormatLunar, false)got := parser(text, time.Local)if got == nil || got.Content != date.UnixMilli() {@@ -116,3 +116,40 @@ func TestLunarDateLocalizedRoundTrips(t *testing.T) {})}}++func TestLunarTemplateDateDaylightSaving(t *testing.T) {+ setLunarTestLanguage(t, "en")+ for _, test := range []struct {+ zone string+ year int+ month time.Month+ day, hour, minute, invalidHour int+ }{+ {"America/Sao_Paulo", 2018, time.November, 4, 12, 30, 0},+ {"America/New_York", 2024, time.March, 10, 3, 30, 2},+ } {+ t.Run(test.zone, func(t *testing.T) {+ location, err := time.LoadLocation(test.zone)+ if err != nil {+ t.Fatal(err)+ }+ original := time.Date(test.year, test.month, test.day, test.hour, test.minute, 17, 0, location)+ lunar, ok := solarToLunar(original)+ if !ok {+ t.Fatal("date outside lunar range")+ }+ clock := original.Format("15:04:05")+ parser := newCalendarTemplateDateParser(DateDisplayFormatLunar)+ for _, dateText := range []string{formatLunarDate(lunar), original.Format("2006-01-02")} {+ parsed := parser(dateText+" "+clock, location)+ if parsed == nil || parsed.Content != original.UnixMilli() {+ t.Fatalf("valid time did not round trip: %q, %+v", dateText+" "+clock, parsed)+ }+ invalidClock := time.Date(2000, 1, 1, test.invalidHour, 30, 0, 0, time.UTC).Format("15:04")+ if parsed := parser(dateText+" "+invalidClock, location); parsed != nil {+ t.Fatalf("nonexistent local time accepted: %q, %+v", dateText+" "+invalidClock, parsed)+ }+ }+ })+ }+}