An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support display formats for database date fields https://github.com/siyuan-note/siyuan/issues/10610
Danielfc9b0d28cd15
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex a991c04606..b123e0d7d9 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1928,6 +1928,10 @@"quit": "خروج من التطبيق"},"_attrView": {+ "dateFormat": "تنسيق التاريخ",+ "fullDate": "التاريخ الكامل",+ "dateMonths": "يناير|فبراير|مارس|أبريل|مايو|يونيو|يوليو|أغسطس|سبتمبر|أكتوبر|نوفمبر|ديسمبر",+ "dateFormatFullTemplate": "${day} ${month} ${year}","empty": "فارغ","table": "جدول","gallery": "بطاقة",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 85d772c6da..3dd05a3ee0 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1928,6 +1928,10 @@"quit": "Anwendung beenden"},"_attrView": {+ "dateFormat": "Datumsformat",+ "fullDate": "Vollständiges Datum",+ "dateMonths": "Januar|Februar|März|April|Mai|Juni|Juli|August|September|Oktober|November|Dezember",+ "dateFormatFullTemplate": "${day}. ${month} ${year}","empty": "Leer","table": "Tabelle","gallery": "Karte",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 3f04cfc8d3..883b98a670 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1928,6 +1928,10 @@"quit": "Quit application"},"_attrView": {+ "dateFormat": "Date format",+ "fullDate": "Full date",+ "dateMonths": "January|February|March|April|May|June|July|August|September|October|November|December",+ "dateFormatFullTemplate": "${month} ${day}, ${year}","empty": "Empty","table": "Table","gallery": "Card",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 86f21fa0d1..c88ac9c594 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1928,6 +1928,10 @@"quit": "Salir de la aplicación"},"_attrView": {+ "dateFormat": "Formato de fecha",+ "fullDate": "Fecha completa",+ "dateMonths": "enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre",+ "dateFormatFullTemplate": "${day} de ${month} de ${year}","empty": "Vacío","table": "Tabla","gallery": "Tarjeta",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex 09f6fc092c..5b9827e870 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1928,6 +1928,10 @@"quit": "Quitter le programme"},"_attrView": {+ "dateFormat": "Format de date",+ "fullDate": "Date complète",+ "dateMonths": "janvier|février|mars|avril|mai|juin|juillet|août|septembre|octobre|novembre|décembre",+ "dateFormatFullTemplate": "${day} ${month} ${year}","empty": "Vide","table": "Tableau","gallery": "Carte",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex 266f09e3e9..60ccbe833a 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1928,6 +1928,10 @@"quit": "צא מהאפליקציה"},"_attrView": {+ "dateFormat": "תבנית תאריך",+ "fullDate": "תאריך מלא",+ "dateMonths": "ינואר|פברואר|מרץ|אפריל|מאי|יוני|יולי|אוגוסט|ספטמבר|אוקטובר|נובמבר|דצמבר",+ "dateFormatFullTemplate": "${day} ${month} ${year}","empty": "ריק","table": "טבלה","gallery": "כרטיס",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex f7385650ee..7c20789241 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1928,6 +1928,10 @@"quit": "एप्लिकेशन से बाहर निकलें"},"_attrView": {+ "dateFormat": "दिनांक प्रारूप",+ "fullDate": "पूर्ण दिनांक",+ "dateMonths": "जनवरी|फ़रवरी|मार्च|अप्रैल|मई|जून|जुलाई|अगस्त|सितंबर|अक्टूबर|नवंबर|दिसंबर",+ "dateFormatFullTemplate": "${day} ${month} ${year}","empty": "खाली","table": "तालिका","gallery": "कार्ड",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 23a3e455c8..623420a40d 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1928,6 +1928,10 @@"quit": "Keluar aplikasi"},"_attrView": {+ "dateFormat": "Format tanggal",+ "fullDate": "Tanggal lengkap",+ "dateMonths": "Januari|Februari|Maret|April|Mei|Juni|Juli|Agustus|September|Oktober|November|Desember",+ "dateFormatFullTemplate": "${day} ${month} ${year}","empty": "Kosong","table": "Tabel","gallery": "Kartu",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex 157749d230..62bf58636b 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1928,6 +1928,10 @@"quit": "Esci dall'applicazione"},"_attrView": {+ "dateFormat": "Formato data",+ "fullDate": "Data completa",+ "dateMonths": "gennaio|febbraio|marzo|aprile|maggio|giugno|luglio|agosto|settembre|ottobre|novembre|dicembre",+ "dateFormatFullTemplate": "${day} ${month} ${year}","empty": "Vuoto","table": "Tabella","gallery": "Scheda",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex f733b0b4dc..54c66c9826 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1928,6 +1928,10 @@"quit": "アプリケーションを終了"},"_attrView": {+ "dateFormat": "日付形式",+ "fullDate": "完全な日付",+ "dateMonths": "1月|2月|3月|4月|5月|6月|7月|8月|9月|10月|11月|12月",+ "dateFormatFullTemplate": "${year}年${month}${day}日","empty": "空白","table": "テーブル","gallery": "カード",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex a8d4d42e65..7b576f50c6 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1928,6 +1928,10 @@"quit": "애플리케이션 종료"},"_attrView": {+ "dateFormat": "날짜 형식",+ "fullDate": "전체 날짜",+ "dateMonths": "1월|2월|3월|4월|5월|6월|7월|8월|9월|10월|11월|12월",+ "dateFormatFullTemplate": "${year}년 ${month} ${day}일","empty": "비어 있음","table": "표","gallery": "카드",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 92bd849419..08d16f1b6c 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1928,6 +1928,10 @@"quit": "Applicatie afsluiten"},"_attrView": {+ "dateFormat": "Datumnotatie",+ "fullDate": "Volledige datum",+ "dateMonths": "januari|februari|maart|april|mei|juni|juli|augustus|september|oktober|november|december",+ "dateFormatFullTemplate": "${day} ${month} ${year}","empty": "Leeg","table": "Tabel","gallery": "Kaart",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 246472d219..d689e31e59 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1928,6 +1928,10 @@"quit": "Zamknij aplikację"},"_attrView": {+ "dateFormat": "Format daty",+ "fullDate": "Pełna data",+ "dateMonths": "stycznia|lutego|marca|kwietnia|maja|czerwca|lipca|sierpnia|września|października|listopada|grudnia",+ "dateFormatFullTemplate": "${day} ${month} ${year}","empty": "Pusty","table": "Tabela","gallery": "Karta",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 9245615a81..e32c1cd7b4 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1928,6 +1928,10 @@"quit": "Sair do aplicativo"},"_attrView": {+ "dateFormat": "Formato de data",+ "fullDate": "Data completa",+ "dateMonths": "janeiro|fevereiro|março|abril|maio|junho|julho|agosto|setembro|outubro|novembro|dezembro",+ "dateFormatFullTemplate": "${day} de ${month} de ${year}","empty": "Vazio","table": "Tabela","gallery": "Cartão",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 6426771425..f804f30fed 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1928,6 +1928,10 @@"quit": "Выйти из приложения"},"_attrView": {+ "dateFormat": "Формат даты",+ "fullDate": "Полная дата",+ "dateMonths": "января|февраля|марта|апреля|мая|июня|июля|августа|сентября|октября|ноября|декабря",+ "dateFormatFullTemplate": "${day} ${month} ${year} г.","empty": "Пусто","table": "Таблица","gallery": "Карточка",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex 1f6031be21..45ccbc8ca3 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1928,6 +1928,10 @@"quit": "Ukončiť aplikáciu"},"_attrView": {+ "dateFormat": "Formát dátumu",+ "fullDate": "Úplný dátum",+ "dateMonths": "januára|februára|marca|apríla|mája|júna|júla|augusta|septembra|októbra|novembra|decembra",+ "dateFormatFullTemplate": "${day}. ${month} ${year}","empty": "Prázdne","table": "Tabuľka","gallery": "Karta",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex ccdbc8941b..6578c71d96 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1928,6 +1928,10 @@"quit": "ออก"},"_attrView": {+ "dateFormat": "รูปแบบวันที่",+ "fullDate": "วันที่แบบเต็ม",+ "dateMonths": "มกราคม|กุมภาพันธ์|มีนาคม|เมษายน|พฤษภาคม|มิถุนายน|กรกฎาคม|สิงหาคม|กันยายน|ตุลาคม|พฤศจิกายน|ธันวาคม",+ "dateFormatFullTemplate": "${day} ${month} ${year}","empty": "ว่างเปล่า","table": "ตาราง","gallery": "การ์ด",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex a98029f128..168e2d3d0c 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1928,6 +1928,10 @@"quit": "Uygulamadan çık"},"_attrView": {+ "dateFormat": "Tarih biçimi",+ "fullDate": "Tam tarih",+ "dateMonths": "Ocak|Şubat|Mart|Nisan|Mayıs|Haziran|Temmuz|Ağustos|Eylül|Ekim|Kasım|Aralık",+ "dateFormatFullTemplate": "${day} ${month} ${year}","empty": "Boş","table": "Tablo","gallery": "Kart görünümü",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 7f89f54209..dec28e075c 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1928,6 +1928,10 @@"quit": "Вийти із застосунку"},"_attrView": {+ "dateFormat": "Формат дати",+ "fullDate": "Повна дата",+ "dateMonths": "січня|лютого|березня|квітня|травня|червня|липня|серпня|вересня|жовтня|листопада|грудня",+ "dateFormatFullTemplate": "${day} ${month} ${year} р.","empty": "Порожньо","table": "Таблиця","gallery": "Картка",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex db4b28a7bb..6f1311e35e 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1928,6 +1928,10 @@"quit": "退出程序"},"_attrView": {+ "dateFormat": "日期格式",+ "fullDate": "完整日期",+ "dateMonths": "一月|二月|三月|四月|五月|六月|七月|八月|九月|十月|十一月|十二月",+ "dateFormatFullTemplate": "${year}年${month}${day}日","empty": "空白","table": "表格","gallery": "卡片",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex 0218808c8b..4218c2632e 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1928,6 +1928,10 @@"quit": "退出程序"},"_attrView": {+ "dateFormat": "日期格式",+ "fullDate": "完整日期",+ "dateMonths": "一月|二月|三月|四月|五月|六月|七月|八月|九月|十月|十一月|十二月",+ "dateFormatFullTemplate": "${year}年${month}${day}日","empty": "空白","table": "表格","gallery": "卡片",diff --git a/app/src/constants.ts b/app/src/constants.tsindex ed78327a1a..e5e0b326dd 100644--- a/app/src/constants.ts+++ b/app/src/constants.ts@@ -278,6 +278,7 @@ export abstract class Constants {public static readonly MENU_AV_ADD_SORT = "av-add-sort"; // 数据库添加排序条件菜单public static readonly MENU_AV_COL_OPTION = "av-col-option"; // 数据库单选多选字段的选项编辑菜单public static readonly MENU_AV_COL_FORMAT_NUMBER = "av-col-format-number"; // 数据库数字字段格式化菜单+ public static readonly MENU_AV_COL_FORMAT_DATE = "av-col-format-date"; // 数据库日期字段格式化菜单public static readonly MENU_AV_GROUP_DATE = "avGroupDate"; // 数据库日期字段分组菜单的日期菜单public static readonly MENU_AV_GROUP_SORT = "avGroupSort"; // 数据库日期字段分组菜单的排序菜单public static readonly MENU_AV_KANBAN_GROUP = "av-kanban-group"; // 数据库看板分组菜单diff --git a/app/src/protyle/render/av/action.ts b/app/src/protyle/render/av/action.tsindex 302610c999..5acab973e5 100644--- a/app/src/protyle/render/av/action.ts+++ b/app/src/protyle/render/av/action.ts@@ -1152,10 +1152,12 @@ export const updateAttrViewCellAnimation = (cellElement: HTMLElement, value: IAVcontent: cellElement.getAttribute("aria-label").split('<div class="ft__on-surface">')[0],};}- cellElement.innerHTML = renderCell(value, 0, iconElement ? !iconElement.classList.contains("fn__none") : false, viewType);+ cellElement.innerHTML = renderCell(value, 0, iconElement ? !iconElement.classList.contains("fn__none") : false,+ viewType, undefined, cellElement.dataset.dateFormat as TAVDateFormat);cellElement.parentElement.setAttribute("data-empty", cellValueIsEmpty(value).toString());} else {- cellElement.innerHTML = renderCell(value, 0, iconElement ? !iconElement.classList.contains("fn__none") : false);+ cellElement.innerHTML = renderCell(value, 0, iconElement ? !iconElement.classList.contains("fn__none") : false,+ undefined, undefined, cellElement.dataset.dateFormat as TAVDateFormat);}if (hasDragFill) {addDragFill(cellElement);diff --git a/app/src/protyle/render/av/attributePanel.ts b/app/src/protyle/render/av/attributePanel.tsindex 266fe972c1..22c1d05c1d 100644--- a/app/src/protyle/render/av/attributePanel.ts+++ b/app/src/protyle/render/av/attributePanel.ts@@ -14,6 +14,7 @@ const refreshActions = new Set<TOperation>(["setAttrViewColDesc","setAttrViewName","updateAttrViewColNumberFormat",+ "setAttrViewColDateFormat",]);export class AVAttributePanel {diff --git a/app/src/protyle/render/av/attributeValue.ts b/app/src/protyle/render/av/attributeValue.tsindex 04bd828c50..0ae745995d 100644--- a/app/src/protyle/render/av/attributeValue.ts+++ b/app/src/protyle/render/av/attributeValue.ts@@ -1,8 +1,8 @@import {escapeAriaLabel, escapeAttr, escapeHtml} from "../../../util/escape";-import * as dayjs from "dayjs";import {unicode2Emoji} from "../../../emoji";import {Constants} from "../../../constants";import {getCompressURL} from "../../../util/image";+import {formatDateDisplay, formatDateValue} from "./dateFormat";export const createEmptyAVValue = (keyID: string, type: TAVCol, blockID?: string) => ({type,@@ -95,10 +95,10 @@ const genAVRollupHTML = (value: IAVCellValue) => {html = dataValue.formattedContent;} else {if (dataValue && dataValue.isNotEmpty) {- html = dayjs(dataValue.content).format(dataValue.isNotTime ? "YYYY-MM-DD" : "YYYY-MM-DD HH:mm");+ html = formatDateDisplay(dataValue.content, "", dataValue.isNotTime);}if (dataValue && dataValue.hasEndDate && dataValue.isNotEmpty && dataValue.isNotEmpty2) {- html = `<svg class="av__cellicon"><use xlink:href="#iconForward"></use></svg>${dayjs(dataValue.content2).format(dataValue.isNotTime ? "YYYY-MM-DD" : "YYYY-MM-DD HH:mm")}`;+ html = `<svg class="av__cellicon"><use xlink:href="#iconForward"></use></svg>${formatDateDisplay(dataValue.content2, "", dataValue.isNotTime)}`;}}if (html) {@@ -118,7 +118,7 @@ const genAVRollupHTML = (value: IAVCellValue) => {return html;};-export const genAVValueHTML = (value: IAVCellValue) => {+export const genAVValueHTML = (value: IAVCellValue, dateFormat: TAVDateFormat = "") => {let html = "";switch (value.type) {case "block":@@ -151,17 +151,18 @@ export const genAVValueHTML = (value: IAVCellValue) => {case "date":html = `<span class="av__celltext" data-value='${JSON.stringify(value[value.type])}' placeholder="${window.siyuan.languages.empty}">`;if (value[value.type] && value[value.type].isNotEmpty) {- html += dayjs(value[value.type].content).format(value[value.type].isNotTime ? "YYYY-MM-DD" : "YYYY-MM-DD HH:mm");+ html += escapeHtml(formatDateDisplay(value[value.type].content, dateFormat, value[value.type].isNotTime));}if (value[value.type] && value[value.type].hasEndDate && value[value.type].isNotEmpty && value[value.type].isNotEmpty2) {- html += `<svg class="av__cellicon"><use xlink:href="#iconForward"></use></svg>${dayjs(value[value.type].content2).format(value[value.type].isNotTime ? "YYYY-MM-DD" : "YYYY-MM-DD HH:mm")}`;+ html += `<svg class="av__cellicon"><use xlink:href="#iconForward"></use></svg>${escapeHtml(formatDateDisplay(value[value.type].content2, dateFormat, value[value.type].isNotTime))}`;}html += "</span>";break;case "created":case "updated":if (value[value.type].isNotEmpty) {- html = `<span data-content="${value[value.type].content}">${dayjs(value[value.type].content).format("YYYY-MM-DD HH:mm")}</span>`;+ html = `<span data-content="${value[value.type].content}">${escapeHtml(value[value.type].formattedContent ||+ formatDateValue(value[value.type], dateFormat))}</span>`;}break;case "url":@@ -229,6 +230,7 @@ export const genAVAttributeRowHTML = (options: {name: string,color: string}[],+ dateFormat?: TAVDateFormat,value: IAVCellValue,empty: boolean,}) => {@@ -243,7 +245,8 @@ export const genAVAttributeRowHTML = (options: {</div><div data-av-id="${options.avID}" data-col-id="${value.keyID}" data-row-id="${value.blockID}"${value.id ? ` data-id="${value.id}"` : ""} data-cell-value="${encodeURIComponent(JSON.stringify(value))}" data-type="${value.type}"${value.isDetached ? ' data-detached="true"' : ""}data-options="${options.selectOptions ? escapeAttr(JSON.stringify(options.selectOptions)) : "[]"}"+data-date-format="${options.dateFormat || ""}"${hasOwnPlaceholder ? "" : `placeholder="${window.siyuan.languages.empty}"`}-class="fn__flex-1 fn__flex${textInputType ? "" : " custom-attr__avvalue"}${["created", "updated"].includes(value.type) ? " custom-attr__avvalue--readonly" : ""}">${genAVValueHTML(value)}</div>+class="fn__flex-1 fn__flex${textInputType ? "" : " custom-attr__avvalue"}${["created", "updated"].includes(value.type) ? " custom-attr__avvalue--readonly" : ""}">${genAVValueHTML(value, options.dateFormat)}</div></div>`;};diff --git a/app/src/protyle/render/av/batchEdit.ts b/app/src/protyle/render/av/batchEdit.tsindex de2878ef49..32b75d7767 100644--- a/app/src/protyle/render/av/batchEdit.ts+++ b/app/src/protyle/render/av/batchEdit.ts@@ -81,8 +81,10 @@ const createEditProxy = (options: {if (value.isDetached) {cellElement.dataset.detached = "true";}+ cellElement.dataset.dateFormat = options.field.dateFormat || "";cellElement.style.cssText = "position:absolute;inset:0;";- cellElement.innerHTML = renderCell(value, 0, options.data.view.showIcon, "table", options.field.options);+ cellElement.innerHTML = renderCell(value, 0, options.data.view.showIcon, "table", options.field.options,+ options.field.dateFormat);return cellElement;};diff --git a/app/src/protyle/render/av/blockAttr.ts b/app/src/protyle/render/av/blockAttr.tsindex 1e260916e8..fd8d60fb1a 100644--- a/app/src/protyle/render/av/blockAttr.ts+++ b/app/src/protyle/render/av/blockAttr.ts@@ -85,6 +85,7 @@ export const renderAVAttribute = (element: HTMLElement, id: string, protyle: IPrdesc: string,icon: string,id: string,+ dateFormat?: TAVDateFormat,options?: {name: string,color: string@@ -123,6 +124,7 @@ export const renderAVAttribute = (element: HTMLElement, id: string, protyle: IPricon: item.key.icon,typeIcon: getColIconByType(item.key.type),selectOptions: item.key.options,+ dateFormat: item.key.dateFormat,value,empty: cellValueIsEmpty(value),});diff --git a/app/src/protyle/render/av/cell.ts b/app/src/protyle/render/av/cell.tsindex 40854d2f8a..c954ee4931 100644--- a/app/src/protyle/render/av/cell.ts+++ b/app/src/protyle/render/av/cell.ts@@ -16,6 +16,7 @@ import {getAssetName, pathPosix} from "../../../util/pathName";import {mergeAddOption} from "./select";import {escapeAriaLabel, escapeAttr, escapeHtml} from "../../../util/escape";import {electronUndo} from "../../undo";+import {formatDateDisplay, formatDateValue, parseDateValue} from "./dateFormat";import {getFieldIdByCellElement} from "./row";import {getFieldsByData} from "./view";import {getCompressURL, removeCompressURL} from "../../../util/image";@@ -260,7 +261,7 @@ const transformCellValue = (colType: TAVCol, value: IAVCellValue): IAVCellValuereturn newValue;};-export const genCellValue = (colType: TAVCol, value: string | any) => {+export const genCellValue = (colType: TAVCol, value: string | any, dateFormat: TAVDateFormat = "") => {let cellValue: IAVCellValue = {type: colType,[colType === "select" ? "mSelect" : colType]: value as IAVCellDateValue@@ -297,42 +298,10 @@ export const genCellValue = (colType: TAVCol, value: string | any) => {}};} else if (["date", "created", "updated"].includes(colType)) {- let values = value.split("→");- if (values.length !== 2) {- values = value.split("-");- if (values.length !== 2) {- values = value.split("~");- }- }- const dateObj1 = dayjs(values[0]);- const dateObj2 = dayjs(values[1] || "");- if (isNaN(dateObj1.valueOf())) {- cellValue = {- type: colType,- [colType]: {- content: null,- isNotEmpty: false,- content2: null,- isNotEmpty2: false,- formattedContent: "",- hasEndDate: false,- isNotTime: true,- }- };- } else {- cellValue = {- type: colType,- [colType]: {- content: dateObj1.valueOf(),- isNotEmpty: true,- content2: dateObj2.valueOf() || 0,- isNotEmpty2: !isNaN(dateObj2.valueOf()),- hasEndDate: !isNaN(dateObj2.valueOf()),- isNotTime: dateObj1.hour() === 0 && values[0].split(":").length === 1,- formattedContent: "",- }- };- }+ cellValue = {+ type: colType,+ [colType]: parseDateValue(value, dateFormat)+ };} else if (colType === "relation") {cellValue = {type: colType,@@ -920,11 +889,16 @@ export const updateCellsValue = async (protyle: IProtyle, nodeElement: HTMLElemenewValue.icon = oldValue.block.icon;}}+ let column = columns?.find(columnItem => columnItem.id === colId);+ if (type === "date" && !column) {+ const response = await fetchSyncPost("/api/av/getAttributeViewKeysByID", {avID, keyIDs: [colId]});+ column = response.data?.[0];+ }let cellValue: IAVCellValue;if (typeof newValue === "object" && newValue.type) {cellValue = transformCellValue(type, newValue);} else {- cellValue = genCellValue(type, newValue);+ cellValue = genCellValue(type, newValue, column?.dateFormat);}cellValue.id = cellId;if ((cellValue.type === "date" && typeof cellValue.date === "string") ||@@ -936,20 +910,13 @@ export const updateCellsValue = async (protyle: IProtyle, nodeElement: HTMLElemedoOperations.push(...operations.doOperations);undoOperations.push(...operations.undoOperations);}- // formattedContent 在单元格渲染时没有用到,需对比保持一致if (type === "date") {if (!(value && typeof value === "object" && typeof value.isNotTime === "boolean")) {- const column = columns?.find(item => item.id === colId);if (column?.date) {cellValue.date.isNotTime = !column.date.fillSpecificTime;- } else {- const response = await fetchSyncPost("/api/av/getAttributeViewKeysByID", {avID: avID, keyIDs: [colId]});- if (response.data[0].date) {- cellValue.date.isNotTime = !response.data[0].date.fillSpecificTime;- }}}- cellValue.date.formattedContent = oldValue.date.formattedContent;+ cellValue.date.formattedContent = formatDateValue(cellValue.date, column?.dateFormat);}if (forceOperation || !objEquals(cellValue, oldValue)) {doOperations.push({@@ -970,7 +937,7 @@ export const updateCellsValue = async (protyle: IProtyle, nodeElement: HTMLElemedata: oldValue});if (isCustomAttr) {- item.innerHTML = genAVValueHTML(cellValue);+ item.innerHTML = genAVValueHTML(cellValue, column?.dateFormat);item.parentElement.dataset.empty = cellValueIsEmpty(cellValue).toString();} else {updateAttrViewCellAnimation(item, cellValue);@@ -1045,7 +1012,7 @@ export const updateAttrViewCellInOtherElements = (protyle: IProtyle, avID: strinreturn;}updateCustomAttr(cellElement);- cellElement.innerHTML = genAVValueHTML(value);+ cellElement.innerHTML = genAVValueHTML(value, cellElement.dataset.dateFormat as TAVDateFormat);});};@@ -1069,7 +1036,7 @@ export const renderCellAttr = (cellElement: Element, value: IAVCellValue) => {};export const renderCell = (cellValue: IAVCellValue, rowIndex = 0, showIcon = true, type: TAVView = "table",- selectOptions?: IAVColumn["options"]) => {+ selectOptions?: IAVColumn["options"], dateFormat: TAVDateFormat = "") => {let text = "";if ("template" === cellValue.type) {text = `<span class="av__celltext av__celltext--template">${cellValue ? getAVTemplateHTML(cellValue.template.content || "") : ""}</span>`;@@ -1106,17 +1073,17 @@ export const renderCell = (cellValue: IAVCellValue, rowIndex = 0, showIcon = truconst dataValue = cellValue ? cellValue.date : null;text = `<span class="av__celltext" data-value='${JSON.stringify(dataValue)}'>`;if (dataValue && dataValue.isNotEmpty) {- text += dayjs(dataValue.content).format(dataValue.isNotTime ? "YYYY-MM-DD" : "YYYY-MM-DD HH:mm");+ text += escapeHtml(formatDateDisplay(dataValue.content, dateFormat, dataValue.isNotTime));}if (dataValue && dataValue.hasEndDate && dataValue.isNotEmpty && dataValue.isNotEmpty2) {- text += `<svg class="av__cellicon"><use xlink:href="#iconForward"></use></svg>${dayjs(dataValue.content2).format(dataValue.isNotTime ? "YYYY-MM-DD" : "YYYY-MM-DD HH:mm")}`;+ text += `<svg class="av__cellicon"><use xlink:href="#iconForward"></use></svg>${escapeHtml(formatDateDisplay(dataValue.content2, dateFormat, dataValue.isNotTime))}`;}text += "</span>";} else if (["created", "updated"].includes(cellValue.type)) {const dataValue = cellValue ? cellValue[cellValue.type as "date"] : null;text = `<span class="av__celltext" data-value='${JSON.stringify(dataValue)}'>`;if (dataValue && dataValue.isNotEmpty) {- text += dataValue.formattedContent;+ text += escapeHtml(dataValue.formattedContent || formatDateValue(dataValue, dateFormat));}text += "</span>";} else if (["lineNumber"].includes(cellValue.type)) {@@ -1208,10 +1175,10 @@ const renderRollup = (cellValue: IAVCellValue, showIcon: boolean) => {text = dataValue.formattedContent;} else {if (dataValue && dataValue.isNotEmpty) {- text = dayjs(dataValue.content).format(dataValue.isNotTime ? "YYYY-MM-DD" : "YYYY-MM-DD HH:mm");+ text = formatDateDisplay(dataValue.content, "", dataValue.isNotTime);}if (dataValue && dataValue.hasEndDate && dataValue.isNotEmpty && dataValue.isNotEmpty2) {- text = `<svg class="av__cellicon"><use xlink:href="#iconForward"></use></svg>${dayjs(dataValue.content2).format(dataValue.isNotTime ? "YYYY-MM-DD" : "YYYY-MM-DD HH:mm")}`;+ text = `<svg class="av__cellicon"><use xlink:href="#iconForward"></use></svg>${formatDateDisplay(dataValue.content2, "", dataValue.isNotTime)}`;}}if (text) {@@ -1314,7 +1281,8 @@ export const dragFillCellsValue = (protyle: IProtyle, nodeElement: HTMLElement,rowID,data});- item.element.innerHTML = renderCell(data, 0, showIcon);+ item.element.innerHTML = renderCell(data, 0, showIcon, "table", undefined,+ item.element.dataset.dateFormat as TAVDateFormat);renderCellAttr(item.element, data);delete item.colId;delete item.element;diff --git a/app/src/protyle/render/av/col.ts b/app/src/protyle/render/av/col.tsindex 3cbfcb406c..5f8904c91e 100644--- a/app/src/protyle/render/av/col.ts+++ b/app/src/protyle/render/av/col.ts@@ -5,6 +5,7 @@ import {getDefaultOperatorByType, getEditableFilters, hasFilterForColumn} from "import {genCellValue, renderCell} from "./cell";import {getPropertiesHTML, openMenuPanel} from "./openMenuPanel";import {getLabelByNumberFormat} from "./number";+import {getLabelByDateFormat} from "./dateFormat";import {removeAttrViewColAnimation, updateAttrViewCellAnimation, updateAttrViewColAnimation} from "./action";import {openEmojiPanel, unicode2Emoji} from "../../../emoji";import {focusBlock} from "../../util/selection";@@ -180,6 +181,11 @@ export const getEditHTML = (options: {html += '<button class="b3-menu__separator" data-id="separator_2"></button>' + getRollupHTML({colData});} else if (colData.type === "date") {html += `<button class="b3-menu__separator" data-id="separator_2"></button>+<button class="b3-menu__item" data-type="dateFormat" data-format="${colData.dateFormat || ""}">+ <svg class="b3-menu__icon"><use xlink:href="#iconFormat"></use></svg>+ <span class="b3-menu__label">${window.siyuan.languages._attrView.dateFormat}</span>+ <span class="b3-menu__accelerator">${getLabelByDateFormat(colData.dateFormat)}</span>+</button><label class="b3-menu__item"><span class="fn__flex-center">${window.siyuan.languages.fillCreated}</span><span class="fn__space fn__flex-1"></span>@@ -192,6 +198,11 @@ export const getEditHTML = (options: {</label>`;} else if (["updated", "created"].includes(colData.type)) {html += `<button class="b3-menu__separator" data-id="separator_2"></button>+<button class="b3-menu__item" data-type="dateFormat" data-format="${colData.dateFormat || ""}">+ <svg class="b3-menu__icon"><use xlink:href="#iconFormat"></use></svg>+ <span class="b3-menu__label">${window.siyuan.languages._attrView.dateFormat}</span>+ <span class="b3-menu__accelerator">${getLabelByDateFormat(colData.dateFormat)}</span>+</button><label class="b3-menu__item"><span class="fn__flex-center">${window.siyuan.languages.includeTime}</span><span class="fn__space fn__flex-1"></span>@@ -677,6 +688,7 @@ data-wrap="false" data-dtype="${options.type}" data-align="" style="width: 200pxicon: options.icon,typeIcon: getColIconByType(options.type),selectOptions: colData?.options,+ dateFormat: colData?.dateFormat,value: createEmptyAVValue(options.id, options.type, rowID),empty: true,}));@@ -2025,6 +2037,7 @@ const genColDataByType = (type: TAVCol, id: string, name: string) => {name,desc: "",numberFormat: "",+ dateFormat: "",pin: false,template: "",type,diff --git a/app/src/protyle/render/av/dateFormat.ts b/app/src/protyle/render/av/dateFormat.tsnew file mode 100644index 0000000000..b668e1e303--- /dev/null+++ b/app/src/protyle/render/av/dateFormat.ts@@ -0,0 +1,176 @@+const pad = (value: number) => value.toString().padStart(2, "0");++const getMonths = (): string[] => window.siyuan.languages._attrView.dateMonths.split("|");++export const formatDateDisplay = (content: number, format: TAVDateFormat = "", isNotTime = true) => {+ const date = new Date(content);+ const year = date.getFullYear();+ const month = date.getMonth() + 1;+ const day = date.getDate();+ let formatted: string;+ if (format === "full") {+ formatted = window.siyuan.languages._attrView.dateFormatFullTemplate+ .replaceAll("${year}", year.toString())+ .replaceAll("${month}", getMonths()[month - 1] || date.toLocaleString(undefined, {month: "long"}))+ .replaceAll("${day}", day.toString());+ } else if (format === "month-day-year") {+ formatted = `${pad(month)}/${pad(day)}/${year}`;+ } else if (format === "day-month-year") {+ formatted = `${pad(day)}/${pad(month)}/${year}`;+ } else if (format === "year-month-day") {+ formatted = `${year}/${pad(month)}/${pad(day)}`;+ } else {+ formatted = `${year}-${pad(month)}-${pad(day)}`;+ }+ if (!isNotTime) {+ formatted += ` ${pad(date.getHours())}:${pad(date.getMinutes())}`;+ }+ return formatted;+};++export const formatDateValue = (value: IAVCellDateValue, format: TAVDateFormat = "") => {+ if (!value?.isNotEmpty || !value.content) {+ return "";+ }+ let formatted = formatDateDisplay(value.content, format, value.isNotTime);+ if (value.hasEndDate && value.isNotEmpty2 && value.content2) {+ formatted += ` → ${formatDateDisplay(value.content2, format, value.isNotTime)}`;+ }+ return formatted;+};++const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");++const parseFullDate = (value: string) => {+ const tokens = window.siyuan.languages._attrView.dateFormatFullTemplate.split(/(\$\{year}|\$\{month}|\$\{day})/);+ const captures: string[] = [];+ const months = getMonths();+ const pattern = tokens.map((token: string) => {+ if (token === "${year}") {+ captures.push("year");+ return "(\\d{4})";+ }+ if (token === "${month}") {+ captures.push("month");+ return `(${months.map(escapeRegExp).sort((a, b) => b.length - a.length).join("|")})`;+ }+ if (token === "${day}") {+ captures.push("day");+ return "(\\d{1,2})";+ }+ return escapeRegExp(token);+ }).join("");+ const match = value.match(new RegExp(`^${pattern}$`, "i"));+ if (!match) {+ return;+ }+ const parts: Record<string, string> = {};+ captures.forEach((capture, index) => {+ parts[capture] = match[index + 1];+ });+ return {+ year: Number(parts.year),+ month: months.findIndex((month) => month.toLocaleLowerCase() === parts.month.toLocaleLowerCase()) + 1,+ day: Number(parts.day),+ };+};++const parseDateEndpoint = (value: string, format: TAVDateFormat) => {+ 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;+ let year: number;+ let month: number;+ let day: number;+ if (format === "full") {+ const parts = parseFullDate(dateText);+ if (!parts) {+ return;+ }+ ({year, month, day} = parts);+ } else {+ let match: RegExpMatchArray;+ if (format === "month-day-year") {+ match = dateText.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);+ if (match) {+ month = Number(match[1]);+ day = Number(match[2]);+ year = Number(match[3]);+ }+ } else if (format === "day-month-year") {+ match = dateText.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);+ if (match) {+ day = Number(match[1]);+ month = Number(match[2]);+ year = Number(match[3]);+ }+ } else if (format === "year-month-day") {+ match = dateText.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})$/);+ if (match) {+ year = Number(match[1]);+ month = Number(match[2]);+ day = Number(match[3]);+ }+ } else {+ match = dateText.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/);+ if (match) {+ year = Number(match[1]);+ month = Number(match[2]);+ day = Number(match[3]);+ }+ }+ if (!match) {+ return;+ }+ }+ if (hour > 23 || minute > 59 || month < 1 || month > 12 || day < 1 || day > 31) {+ return;+ }+ const parsed = new Date(0);+ parsed.setFullYear(year, month - 1, day);+ parsed.setHours(hour, minute, 0, 0);+ if (parsed.getFullYear() !== year || parsed.getMonth() !== month - 1 || parsed.getDate() !== day ||+ parsed.getHours() !== hour || parsed.getMinutes() !== minute) {+ return;+ }+ return {content: parsed.valueOf(), isNotTime: !timeMatch};+};++export const parseDateValue = (value: string, format: TAVDateFormat = ""): IAVCellDateValue => {+ const endpoints = value.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;+ if (!start || (endpoints.length === 2 && !end)) {+ return {content: null, isNotEmpty: false, content2: null, isNotEmpty2: false, hasEndDate: false, isNotTime: true};+ }+ return {+ content: start.content,+ isNotEmpty: true,+ content2: end?.content || 0,+ isNotEmpty2: !!end,+ hasEndDate: !!end,+ isNotTime: start.isNotTime && (!end || end.isNotTime),+ formattedContent: "",+ };+};++export const getLabelByDateFormat = (format: TAVDateFormat = "") => {+ if (format === "full") {+ return window.siyuan.languages._attrView.fullDate;+ }+ if (format === "month-day-year") {+ return "MM/DD/YYYY";+ }+ if (format === "day-month-year") {+ return "DD/MM/YYYY";+ }+ if (format === "year-month-day") {+ return "YYYY/MM/DD";+ }+ return "YYYY-MM-DD";+};diff --git a/app/src/protyle/render/av/dateFormatMenu.ts b/app/src/protyle/render/av/dateFormatMenu.tsnew file mode 100644index 0000000000..cd3f36a74b--- /dev/null+++ b/app/src/protyle/render/av/dateFormatMenu.ts@@ -0,0 +1,59 @@+import {Menu} from "../../../plugin/Menu";+import {transaction} from "../../wysiwyg/transaction";+import {Constants} from "../../../constants";+import {getAllEditor, getAllModels} from "../../../layout/getAll";+import {getLabelByDateFormat} from "./dateFormat";++const refreshDatabaseAttributePanels = (protyle: IProtyle, avID: string) => {+ protyle.databaseAttributePanel?.refresh();+ getAllEditor().forEach((editor) => {+ if (editor.protyle !== protyle && editor.protyle.databaseAttributePanel?.hasDatabase(avID)) {+ editor.protyle.databaseAttributePanel.refresh();+ }+ });+ /// #if !MOBILE+ getAllModels().custom.forEach((model) => {+ if (model.type === "siyuan-database-row" && model.data.avID === avID) {+ model.update?.();+ }+ });+ /// #endif+};++export const formatDate = (options: {+ avPanelElement: Element,+ element: HTMLElement,+ protyle: IProtyle,+ colId: string,+ avID: string,+ type: "date" | "created" | "updated",+ oldFormat: TAVDateFormat+}) => {+ const menu = new Menu(Constants.MENU_AV_COL_FORMAT_DATE);+ (["", "full", "month-day-year", "day-month-year", "year-month-day"] as TAVDateFormat[]).forEach((format) => {+ menu.addItem({+ iconHTML: format === options.oldFormat ? '<svg><use xlink:href="#iconSelect"></use></svg>' : "",+ label: getLabelByDateFormat(format),+ click() {+ transaction(options.protyle, [{+ action: "setAttrViewColDateFormat",+ id: options.colId,+ avID: options.avID,+ format,+ type: options.type,+ }], [{+ action: "setAttrViewColDateFormat",+ id: options.colId,+ avID: options.avID,+ format: options.oldFormat,+ type: options.type,+ }], {+ callback: () => refreshDatabaseAttributePanels(options.protyle, options.avID),+ });+ options.avPanelElement.remove();+ }+ });+ });+ const rect = options.element.getBoundingClientRect();+ menu.open({x: rect.left, y: rect.bottom, h: rect.height, w: rect.width, isLeft: true});+};diff --git a/app/src/protyle/render/av/gallery/item.ts b/app/src/protyle/render/av/gallery/item.tsindex 8e7f83d66c..56fb3a9762 100644--- a/app/src/protyle/render/av/gallery/item.ts+++ b/app/src/protyle/render/av/gallery/item.ts@@ -42,7 +42,9 @@ export const insertGalleryItemAnimation = (options: {data-field-id="${item.dataset.fieldId}"data-wrap="${item.dataset.wrap}"data-dtype="${item.dataset.dtype}"-${fieldType === "block" ? ' data-detached="true"' : ""}>${renderCell(genCellValue(fieldType, null), lineNumber, false, type)}</div>`;+data-date-format="${item.dataset.dateFormat || ""}"+${fieldType === "block" ? ' data-detached="true"' : ""}>${renderCell(genCellValue(fieldType, null), lineNumber,+ false, type, undefined, item.dataset.dateFormat as TAVDateFormat)}</div>`;if (item.previousElementSibling.classList.contains("av__gallery-name")) {cellsHTML += `<div class="av__gallery-field av__gallery-field--name" data-empty="${item.parentElement.dataset.empty}">${item.previousElementSibling.outerHTML}@@ -91,7 +93,8 @@ ${fieldType === "block" ? ' data-detached="true"' : ""}>${renderCell(genCellValuif (cellValue.type === "checkbox" && cellItem.parentElement.querySelector(".av__gallery-tip")) {cellValue.checkbox.content = cellItem.getAttribute("aria-label").split('<div class="ft__on-surface">')[0];}- cellItem.innerHTML = renderCell(cellValue, undefined, false, type);+ cellItem.innerHTML = renderCell(cellValue, undefined, false, type, undefined,+ cellItem.dataset.dateFormat as TAVDateFormat);renderCellAttr(cellItem, cellValue);}});diff --git a/app/src/protyle/render/av/openMenuPanel.ts b/app/src/protyle/render/av/openMenuPanel.tsindex b7bc6080cb..875fe3acbc 100644--- a/app/src/protyle/render/av/openMenuPanel.ts+++ b/app/src/protyle/render/av/openMenuPanel.ts@@ -33,6 +33,7 @@ import {genCellValue, updateCellsValue} from "./cell";import {addSort, bindSortsEvent, getSortsHTML} from "./sort";import {bindDateEvent, getDateHTML} from "./date";import {formatNumber} from "./number";+import {formatDate} from "./dateFormatMenu";import {updateAttrViewCellAnimation} from "./action";import {addAssetLink, bindAssetEvent, editAssetItem, getAssetHTML, updateAssetCell} from "./asset";import {Constants} from "../../../constants";@@ -1117,6 +1118,21 @@ export const openMenuPanel = (options: {event.preventDefault();event.stopPropagation();break;+ } else if (type === "dateFormat") {+ const colId = menuElement.querySelector(".b3-menu__item").getAttribute("data-col-id");+ const colData = fields.find((item) => item.id === colId);+ formatDate({+ avPanelElement,+ element: target,+ protyle: options.protyle,+ oldFormat: target.dataset.format as TAVDateFormat,+ colId,+ avID,+ type: colData.type as "date" | "created" | "updated",+ });+ event.preventDefault();+ event.stopPropagation();+ break;} else if (type === "newCol") {avPanelElement.remove();const addMenu = addCol(options.protyle, options.blockElement);diff --git a/app/src/protyle/render/av/relation.ts b/app/src/protyle/render/av/relation.tsindex afd5406532..46c3717835 100644--- a/app/src/protyle/render/av/relation.ts+++ b/app/src/protyle/render/av/relation.ts@@ -321,7 +321,7 @@ style="${primaryCell.bgColor ? `background-color:${primaryCell.bgColor};` : ""}$} else {html += `<span class="av__relation-table-cell"style="${cell?.bgColor ? `background-color:${cell.bgColor};` : ""}${cell?.color ? `color:${cell.color};` : ""}">${cell?.value ?- renderCell(cell.value, 0, false, "table", column.options) : ""}</span>`;+ renderCell(cell.value, 0, false, "table", column.options, column.dateFormat) : ""}</span>`;}});return html + "</div>";diff --git a/app/src/protyle/render/av/render.ts b/app/src/protyle/render/av/render.tsindex b468d8cdfe..9117e8c68e 100644--- a/app/src/protyle/render/av/render.ts+++ b/app/src/protyle/render/av/render.ts@@ -171,6 +171,7 @@ const getTableHTMLs = (data: IAVTable, e: HTMLElement, virtualData: IAVVirtualDa}contentHTML += `<div class="av__cell av__cell--header" data-col-id="${column.id}" draggable="true"data-icon="${column.icon}" data-dtype="${column.type}" data-wrap="${column.wrap}" data-pin="${column.pin}"+data-date-format="${column.dateFormat || ""}"data-freeze="${freezeIndex === index}"data-desc="${escapeAttr(column.desc)}" data-align="${column.align || ""}" data-position="north"style="width: ${column.width || "200px"};">diff --git a/app/src/protyle/render/av/row.ts b/app/src/protyle/render/av/row.tsindex 0f358aa962..28e0270b00 100644--- a/app/src/protyle/render/av/row.ts+++ b/app/src/protyle/render/av/row.ts@@ -96,9 +96,10 @@ data-position="5west"data-id="${cell.id}"data-field-id="${galleryData.fields[fieldsIndex].id}"data-dtype="${cell.valueType}"+data-date-format="${galleryData.fields[fieldsIndex].dateFormat || ""}"${cell.value?.isDetached ? ' data-detached="true"' : ""}style="${cell.bgColor ? `background-color:${cell.bgColor};` : ""}-${cell.color ? `color:${cell.color};` : ""}">${renderCell(cell.value, options.rowIndex, galleryData.showIcon, "gallery", galleryData.fields[fieldsIndex].options)}</div>`;+${cell.color ? `color:${cell.color};` : ""}">${renderCell(cell.value, options.rowIndex, galleryData.showIcon, "gallery", galleryData.fields[fieldsIndex].options, galleryData.fields[fieldsIndex].dateFormat)}</div>`;if (galleryData.displayFieldName) {html += `<div class="av__gallery-field av__gallery-field--name" data-empty="${isEmpty}"><div class="av__gallery-name">@@ -160,9 +161,10 @@ data-position="5west"data-id="${cell.id}"data-field-id="${kanbanData.fields[fieldsIndex].id}"data-dtype="${cell.valueType}"+data-date-format="${kanbanData.fields[fieldsIndex].dateFormat || ""}"${cell.value?.isDetached ? ' data-detached="true"' : ""}style="${cell.bgColor ? `background-color:${cell.bgColor};` : ""}-${cell.color ? `color:${cell.color};` : ""}">${renderCell(cell.value, options.rowIndex, kanbanData.showIcon, "kanban", kanbanData.fields[fieldsIndex].options)}</div>`;+${cell.color ? `color:${cell.color};` : ""}">${renderCell(cell.value, options.rowIndex, kanbanData.showIcon, "kanban", kanbanData.fields[fieldsIndex].options, kanbanData.fields[fieldsIndex].dateFormat)}</div>`;if (kanbanData.displayFieldName) {html += `<div class="av__gallery-field av__gallery-field--name" data-empty="${isEmpty}"><div class="av__gallery-name">@@ -208,11 +210,12 @@ ${cell.color ? `color:${cell.color};` : ""}">${renderCell(cell.value, options.rohtml += `<div class="av__cell${checkClass}" data-id="${cell.id}" data-col-id="${column.id}"data-wrap="${column.wrap}"data-dtype="${column.type}"+data-date-format="${column.dateFormat || ""}"data-align="${column.align || ""}"${cell.value?.isDetached ? ' data-detached="true"' : ""}style="width: ${column.width || "200px"};${cell.bgColor ? `background-color:${cell.bgColor};` : ""}-${cell.color ? `color:${cell.color};` : ""}">${renderCell(cell.value, options.rowIndex, tableData.showIcon, "table", column.options)}</div>`;+${cell.color ? `color:${cell.color};` : ""}">${renderCell(cell.value, options.rowIndex, tableData.showIcon, "table", column.options, column.dateFormat)}</div>`;if (options.pinIndex === index) {html += "</div>";@@ -395,9 +398,11 @@ export const insertAttrViewBlockAnimation = (options: {cellsHTML += `<div class="av__cell${colType === "checkbox" ? " av__cell-uncheck" : ""}" data-col-id="${item.dataset.colId}"data-wrap="${item.dataset.wrap}"data-dtype="${item.dataset.dtype}"+data-date-format="${item.dataset.dateFormat || ""}"data-align="${item.dataset.align || ""}"style="width: ${item.style.width};"-${colType === "block" ? ' data-detached="true"' : ""}>${renderCell(genCellValue(colType, null), lineNumber)}</div>`;+${colType === "block" ? ' data-detached="true"' : ""}>${renderCell(genCellValue(colType, null), lineNumber,+ true, "table", undefined, item.dataset.dateFormat as TAVDateFormat)}</div>`;if (pinIndex === index) {cellsHTML += "</div>";}@@ -426,7 +431,8 @@ ${colType === "block" ? ' data-detached="true"' : ""}>${renderCell(genCellValue(}if (updateIds.includes(cellItem.dataset.colId)) {const cellValue = response.data.values[cellItem.dataset.colId];- cellItem.innerHTML = renderCell(cellValue);+ cellItem.innerHTML = renderCell(cellValue, 0, true, "table", undefined,+ cellItem.dataset.dateFormat as TAVDateFormat);renderCellAttr(cellItem, cellValue);}});diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.tsindex 7b155eeb11..bc42554b30 100644--- a/app/src/protyle/wysiwyg/transaction.ts+++ b/app/src/protyle/wysiwyg/transaction.ts@@ -1170,7 +1170,7 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUndif (["addAttrViewCol", "updateAttrViewCol", "updateAttrViewColOptions","updateAttrViewColOption", "updateAttrViewCell", "sortAttrViewRow", "sortAttrViewCol", "setAttrViewColHidden","setAttrViewColWrap", "setAttrViewColWidth", "setAttrViewColAlign", "removeAttrViewColOption", "setAttrViewName", "setAttrViewFilters",- "setAttrViewSorts", "setAttrViewNewItemTemplates", "setAttrViewColCalc", "removeAttrViewCol", "updateAttrViewColNumberFormat", "removeAttrViewBlock",+ "setAttrViewSorts", "setAttrViewNewItemTemplates", "setAttrViewColCalc", "removeAttrViewCol", "updateAttrViewColNumberFormat", "setAttrViewColDateFormat", "removeAttrViewBlock","replaceAttrViewBlock", "updateAttrViewColTemplate", "setAttrViewColPin", "addAttrViewView", "setAttrViewColIcon","removeAttrViewView", "setAttrViewViewName", "setAttrViewViewIcon", "duplicateAttrViewView", "duplicateAttrViewRow", "sortAttrViewView","updateAttrViewColRelation", "setAttrViewPageSize", "updateAttrViewColRollup", "sortAttrViewKey", "setAttrViewColDesc",diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.tsindex 667b9c0e7a..174d6a5cd1 100644--- a/app/src/types/index.d.ts+++ b/app/src/types/index.d.ts@@ -44,6 +44,7 @@ type TOperation =| "setAttrViewSorts"| "setAttrViewColCalc"| "updateAttrViewColNumberFormat"+ | "setAttrViewColDateFormat"| "replaceAttrViewBlock"| "addAttrViewView"| "setAttrViewViewName"@@ -105,6 +106,7 @@ type TEventBus = "ws-main" | "sync-start" | "sync-end" | "sync-fail" |"kernel-plugin-state-change"type TAVView = "table" | "gallery" | "kanban"type TAVAlign = "" | "left" | "center" | "right"+type TAVDateFormat = "" | "full" | "month-day-year" | "day-month-year" | "year-month-day"type TAVCol ="text"| "date"@@ -663,7 +665,7 @@ interface IOperation {isTwoWay?: boolean, // 是否双向关联backRelationKeyID?: string, // 双向关联的目标关联列 IDavID?: string, // av- format?: string // updateAttrViewColNumberFormat 专享+ format?: string // 属性视图字段格式化keyID?: string // updateAttrViewCell 专享rowID?: string // updateAttrViewCell 专享data?: any, // updateAttr 时为 { old: IObject, new: IObject }, updateAttrViewCell 时为 {TAVCol: {content: string}}@@ -1161,6 +1163,7 @@ interface IAVColumn {hidden: boolean,type: TAVCol,numberFormat: string,+ dateFormat?: TAVDateFormat,template: string,calc: IAVCalc,updated?: {diff --git a/app/tests/dateFormat.test.ts b/app/tests/dateFormat.test.tsnew file mode 100644index 0000000000..0ecdef7aaa--- /dev/null+++ b/app/tests/dateFormat.test.ts@@ -0,0 +1,41 @@+import assert from "node:assert/strict";+import test from "node:test";++(globalThis as typeof globalThis & { window: unknown }).window = {+ siyuan: {+ languages: {+ _attrView: {+ dateMonths: "January|February|March|April|May|June|July|August|September|October|November|December",+ dateFormatFullTemplate: "${month} ${day}, ${year}",+ }+ }+ }+};++const loadDateFormat = () => import("../src/protyle/render/av/dateFormat");++test("formats dates with the same fixed patterns as the kernel", async () => {+ const {formatDateDisplay} = await loadDateFormat();+ const content = new Date(2024, 2, 5, 14, 7).valueOf();+ assert.equal(formatDateDisplay(content, "", true), "2024-03-05");+ assert.equal(formatDateDisplay(content, "full", true), "March 5, 2024");+ assert.equal(formatDateDisplay(content, "month-day-year", false), "03/05/2024 14:07");+ assert.equal(formatDateDisplay(content, "day-month-year", true), "05/03/2024");+ assert.equal(formatDateDisplay(content, "year-month-day", true), "2024/03/05");+});++test("parses displayed dates strictly according to the field format", async () => {+ const {parseDateValue} = await loadDateFormat();+ const parsed = parseDateValue("05/03/2024 14:07 → 06/04/2024 15:08", "day-month-year");+ assert.equal(parsed.content, new Date(2024, 2, 5, 14, 7).valueOf());+ assert.equal(parsed.content2, new Date(2024, 3, 6, 15, 8).valueOf());+ assert.equal(parsed.hasEndDate, true);+ assert.equal(parsed.isNotTime, false);++ const full = parseDateValue("March 5, 2024", "full");+ assert.equal(full.content, new Date(2024, 2, 5).valueOf());+ assert.equal(full.isNotTime, true);++ assert.equal(parseDateValue("03/05/2024", "").isNotEmpty, false);+ assert.equal(parseDateValue("2024-02-30", "").isNotEmpty, false);+});diff --git a/kernel/av/av.go b/kernel/av/av.goindex 86a905257b..f10192c9c7 100644--- a/kernel/av/av.go+++ b/kernel/av/av.go@@ -181,6 +181,9 @@ type Key struct {// 数字NumberFormat NumberFormat `json:"numberFormat"` // 列数字格式化+ // 日期、创建时间、更新时间+ DateFormat DateDisplayFormat `json:"dateFormat,omitempty"` // 日期显示格式+// 模板Template string `json:"template"` // 模板内容diff --git a/kernel/av/calc.go b/kernel/av/calc.goindex cf4c149731..897f8067b0 100644--- a/kernel/av/calc.go+++ b/kernel/av/calc.go@@ -672,7 +672,9 @@ func calcFieldDate(collection Collection, field Field, fieldIndex int) {}}if 0 != earliest {- calc.Result = &Value{Date: NewFormattedValueDate(earliest, 0, DateFormatNone, isNotTime, hasEndDate)}+ date := NewFormattedValueDate(earliest, 0, DateFormatNone, isNotTime, hasEndDate)+ date.FormatDate(field.GetDateFormat())+ calc.Result = &Value{Date: date}}case CalcOperatorLatest:latest := int64(0)@@ -688,7 +690,9 @@ func calcFieldDate(collection Collection, field Field, fieldIndex int) {}}if 0 != latest {- calc.Result = &Value{Date: NewFormattedValueDate(latest, 0, DateFormatNone, isNotTime, hasEndDate)}+ date := NewFormattedValueDate(latest, 0, DateFormatNone, isNotTime, hasEndDate)+ date.FormatDate(field.GetDateFormat())+ calc.Result = &Value{Date: date}}case CalcOperatorRange:earliest := int64(0)@@ -1419,7 +1423,9 @@ func calcFieldCreated(collection Collection, field Field, fieldIndex int, attrViisNotTime = !key.Created.IncludeTime}- calc.Result = &Value{Created: NewFormattedValueCreated(earliest, 0, CreatedFormatNone, isNotTime)}+ created := NewFormattedValueCreated(earliest, 0, CreatedFormatNone, isNotTime)+ created.FormatDate(field.GetDateFormat(), isNotTime)+ calc.Result = &Value{Created: created}}case CalcOperatorLatest:latest := int64(0)@@ -1438,7 +1444,9 @@ func calcFieldCreated(collection Collection, field Field, fieldIndex int, attrViisNotTime = !key.Created.IncludeTime}- calc.Result = &Value{Created: NewFormattedValueCreated(latest, 0, CreatedFormatNone, isNotTime)}+ created := NewFormattedValueCreated(latest, 0, CreatedFormatNone, isNotTime)+ created.FormatDate(field.GetDateFormat(), isNotTime)+ calc.Result = &Value{Created: created}}case CalcOperatorRange:earliest := int64(0)@@ -1567,7 +1575,9 @@ func calcFieldUpdated(collection Collection, field Field, fieldIndex int, attrViisNotTime = !key.Updated.IncludeTime}- calc.Result = &Value{Updated: NewFormattedValueUpdated(earliest, 0, UpdatedFormatNone, isNotTime)}+ updated := NewFormattedValueUpdated(earliest, 0, UpdatedFormatNone, isNotTime)+ updated.FormatDate(field.GetDateFormat(), isNotTime)+ calc.Result = &Value{Updated: updated}}case CalcOperatorLatest:latest := int64(0)@@ -1586,7 +1596,9 @@ func calcFieldUpdated(collection Collection, field Field, fieldIndex int, attrViisNotTime = !key.Updated.IncludeTime}- calc.Result = &Value{Updated: NewFormattedValueUpdated(latest, 0, UpdatedFormatNone, isNotTime)}+ updated := NewFormattedValueUpdated(latest, 0, UpdatedFormatNone, isNotTime)+ updated.FormatDate(field.GetDateFormat(), isNotTime)+ calc.Result = &Value{Updated: updated}}case CalcOperatorRange:earliest := int64(0)diff --git a/kernel/av/date_format_test.go b/kernel/av/date_format_test.gonew file mode 100644index 0000000000..084c239371--- /dev/null+++ b/kernel/av/date_format_test.go@@ -0,0 +1,88 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package av++import (+ "testing"+ "time"++ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestDateDisplayFormat(t *testing.T) {+ oldLang := util.Lang+ oldAttrViewLangs := util.AttrViewLangs+ util.Lang = "en_US"+ util.AttrViewLangs = map[string]map[string]any{+ "en_US": {+ "dateMonths": "January|February|March|April|May|June|July|August|September|October|November|December",+ "dateFormatFullTemplate": "${month} ${day}, ${year}",+ },+ }+ t.Cleanup(func() {+ util.Lang = oldLang+ util.AttrViewLangs = oldAttrViewLangs+ })++ start := time.Date(2024, time.March, 5, 14, 7, 0, 0, time.Local).UnixMilli()+ end := time.Date(2024, time.April, 6, 14, 7, 0, 0, time.Local).UnixMilli()+ tests := []struct {+ format DateDisplayFormat+ expected string+ }{+ {DateDisplayFormatDefault, "2024-03-05"},+ {DateDisplayFormatFull, "March 5, 2024"},+ {DateDisplayFormatMonthDayYear, "03/05/2024"},+ {DateDisplayFormatDayMonthYear, "05/03/2024"},+ {DateDisplayFormatYearMonthDay, "2024/03/05"},+ }+ for _, test := range tests {+ date := NewFormattedValueDate(start, 0, DateFormatNone, true, false)+ date.FormatDate(test.format)+ if test.expected != date.FormattedContent {+ t.Fatalf("format %q: expected %q, got %q", test.format, test.expected, date.FormattedContent)+ }+ }++ date := NewFormattedValueDate(start, end, DateFormatNone, false, true)+ date.FormatDate(DateDisplayFormatDayMonthYear)+ if "05/03/2024 14:07 → 06/04/2024 14:07" != date.FormattedContent {+ t.Fatalf("unexpected range: %q", date.FormattedContent)+ }+ value := &Value{Type: KeyTypeDate, Date: date}+ if date.FormattedContent != value.String(true) {+ t.Fatalf("formatted string not used: %q", value.String(true))+ }+ if DateDisplayFormat("invalid").IsValid() {+ t.Fatal("invalid date display format accepted")+ }+}++func TestCreatedAndUpdatedDateDisplayFormat(t *testing.T) {+ content := time.Date(2024, time.March, 5, 14, 7, 0, 0, time.Local).UnixMilli()+ created := NewFormattedValueCreated(content, 0, CreatedFormatNone, false)+ created.FormatDate(DateDisplayFormatMonthDayYear, false)+ if "03/05/2024 14:07" != created.FormattedContent {+ t.Fatalf("unexpected created date: %q", created.FormattedContent)+ }++ updated := NewFormattedValueUpdated(content, 0, UpdatedFormatNone, true)+ updated.FormatDate(DateDisplayFormatYearMonthDay, true)+ if "2024/03/05" != updated.FormattedContent {+ t.Fatalf("unexpected updated date: %q", updated.FormattedContent)+ }+}diff --git a/kernel/av/layout.go b/kernel/av/layout.goindex 74b4b2bf70..8d05b57f2d 100644--- a/kernel/av/layout.go+++ b/kernel/av/layout.go@@ -154,14 +154,15 @@ type BaseInstanceField struct {// 以下是某些字段类型的特有属性- Options []*SelectOption `json:"options,omitempty"` // 选项列表- NumberFormat NumberFormat `json:"numberFormat"` // 数字字段格式化- Template string `json:"template"` // 模板字段内容- Relation *Relation `json:"relation,omitempty"` // 关联字段- Rollup *Rollup `json:"rollup,omitempty"` // 汇总字段- Date *Date `json:"date,omitempty"` // 日期设置- Created *Created `json:"created,omitempty"` // 创建时间设置- Updated *Updated `json:"updated,omitempty"` // 更新时间设置+ Options []*SelectOption `json:"options,omitempty"` // 选项列表+ NumberFormat NumberFormat `json:"numberFormat"` // 数字字段格式化+ DateFormat DateDisplayFormat `json:"dateFormat,omitempty"` // 日期显示格式+ Template string `json:"template"` // 模板字段内容+ Relation *Relation `json:"relation,omitempty"` // 关联字段+ Rollup *Rollup `json:"rollup,omitempty"` // 汇总字段+ Date *Date `json:"date,omitempty"` // 日期设置+ Created *Created `json:"created,omitempty"` // 创建时间设置+ Updated *Updated `json:"updated,omitempty"` // 更新时间设置}func (baseInstanceField *BaseInstanceField) GetID() string {@@ -184,6 +185,10 @@ func (baseInstanceField *BaseInstanceField) GetNumberFormat() NumberFormat {return baseInstanceField.NumberFormat}+func (baseInstanceField *BaseInstanceField) GetDateFormat() DateDisplayFormat {+ return baseInstanceField.DateFormat+}+// Collection 描述了一个集合的接口。// 集合可以是表格、卡片等,包含多个项目。type Collection interface {@@ -230,6 +235,9 @@ type Field interface {// GetNumberFormat 返回数字字段的格式化设置。GetNumberFormat() NumberFormat++ // GetDateFormat 返回日期字段的显示格式。+ GetDateFormat() DateDisplayFormat}// Item 描述了一个项目的接口。diff --git a/kernel/av/value.go b/kernel/av/value.goindex 01fae61afc..e2711895e9 100644--- a/kernel/av/value.go+++ b/kernel/av/value.go@@ -98,6 +98,9 @@ func (value *Value) String(format bool) string {if nil == value.Date {return ""}+ if format && "" != value.Date.FormattedContent {+ return value.Date.FormattedContent+ }formatted := NewFormattedValueDate(value.Date.Content, value.Date.Content2, DateFormatNone, value.Date.IsNotTime, value.Date.HasEndDate)return formatted.FormattedContentcase KeyTypeSelect:@@ -624,6 +627,67 @@ type ValueDate struct {FormattedContent string `json:"formattedContent"`}+type DateDisplayFormat string++const (+ DateDisplayFormatDefault DateDisplayFormat = ""+ DateDisplayFormatFull DateDisplayFormat = "full"+ DateDisplayFormatMonthDayYear DateDisplayFormat = "month-day-year"+ DateDisplayFormatDayMonthYear DateDisplayFormat = "day-month-year"+ DateDisplayFormatYearMonthDay DateDisplayFormat = "year-month-day"+)++func (format DateDisplayFormat) IsValid() bool {+ switch format {+ case DateDisplayFormatDefault, DateDisplayFormatFull, DateDisplayFormatMonthDayYear,+ DateDisplayFormatDayMonthYear, DateDisplayFormatYearMonthDay:+ return true+ }+ return false+}++func formatDateDisplay(content int64, format DateDisplayFormat, isNotTime bool) string {+ contentTime := time.UnixMilli(content)+ var formatted string+ switch format {+ case DateDisplayFormatFull:+ months := strings.Split(GetAttributeViewI18n("dateMonths"), "|")+ month := contentTime.Month().String()+ if monthIndex := int(contentTime.Month()) - 1; 0 <= monthIndex && monthIndex < len(months) {+ month = months[monthIndex]+ }+ formatted = GetAttributeViewI18n("dateFormatFullTemplate")+ formatted = strings.ReplaceAll(formatted, "${year}", strconv.Itoa(contentTime.Year()))+ formatted = strings.ReplaceAll(formatted, "${month}", month)+ formatted = strings.ReplaceAll(formatted, "${day}", strconv.Itoa(contentTime.Day()))+ case DateDisplayFormatMonthDayYear:+ formatted = contentTime.Format("01/02/2006")+ case DateDisplayFormatDayMonthYear:+ formatted = contentTime.Format("02/01/2006")+ case DateDisplayFormatYearMonthDay:+ formatted = contentTime.Format("2006/01/02")+ default:+ formatted = contentTime.Format("2006-01-02")+ }+ if !isNotTime {+ formatted += " " + contentTime.Format("15:04")+ }+ return formatted+}++func (date *ValueDate) FormatDate(format DateDisplayFormat) {+ if nil == date || !date.IsNotEmpty || 0 == date.Content {+ if nil != date {+ date.FormattedContent = ""+ }+ return+ }+ date.FormattedContent = formatDateDisplay(date.Content, format, date.IsNotTime)+ if date.HasEndDate && date.IsNotEmpty2 && 0 != date.Content2 {+ date.FormattedContent += " → " + formatDateDisplay(date.Content2, format, date.IsNotTime)+ }+}+// DateEndpoint 描述日期筛选或排序使用的时间端点。type DateEndpoint string@@ -803,12 +867,27 @@ func NewFormattedValueCreated(content, content2 int64, format CreatedFormat, isN}ret = &ValueCreated{Content: content,+ IsNotEmpty: 0 != content,Content2: content2,+ IsNotEmpty2: 0 != content2,FormattedContent: formatted,}return}+func (created *ValueCreated) FormatDate(format DateDisplayFormat, isNotTime bool) {+ if nil == created || !created.IsNotEmpty || 0 == created.Content {+ if nil != created {+ created.FormattedContent = ""+ }+ return+ }+ created.FormattedContent = formatDateDisplay(created.Content, format, isNotTime)+ if created.IsNotEmpty2 && 0 != created.Content2 {+ created.FormattedContent += " → " + formatDateDisplay(created.Content2, format, isNotTime)+ }+}+type ValueUpdated struct {Content int64 `json:"content"`IsNotEmpty bool `json:"isNotEmpty"`@@ -844,12 +923,27 @@ func NewFormattedValueUpdated(content, content2 int64, format UpdatedFormat, isN}ret = &ValueUpdated{Content: content,+ IsNotEmpty: 0 != content,Content2: content2,+ IsNotEmpty2: 0 != content2,FormattedContent: formatted,}return}+func (updated *ValueUpdated) FormatDate(format DateDisplayFormat, isNotTime bool) {+ if nil == updated || !updated.IsNotEmpty || 0 == updated.Content {+ if nil != updated {+ updated.FormattedContent = ""+ }+ return+ }+ updated.FormattedContent = formatDateDisplay(updated.Content, format, isNotTime)+ if updated.IsNotEmpty2 && 0 != updated.Content2 {+ updated.FormattedContent += " → " + formatDateDisplay(updated.Content2, format, isNotTime)+ }+}+type ValueCheckbox struct {Checked bool `json:"checked"`}@@ -888,6 +982,14 @@ func (r *ValueRollup) BuildContents(keyValues []*KeyValues, destKey *Key, relatiif KeyTypeNumber == destKey.Type {destVal.Number.Format = destKey.NumberFormatdestVal.Number.FormatNumber()+ } else if KeyTypeDate == destKey.Type {+ destVal.Date.FormatDate(destKey.DateFormat)+ } else if KeyTypeCreated == destKey.Type {+ isNotTime := nil != destKey.Created && !destKey.Created.IncludeTime+ destVal.Created.FormatDate(destKey.DateFormat, isNotTime)+ } else if KeyTypeUpdated == destKey.Type {+ isNotTime := nil != destKey.Updated && !destKey.Updated.IncludeTime+ destVal.Updated.FormatDate(destKey.DateFormat, isNotTime)}r.Contents = append(r.Contents, destVal.Clone())@@ -1238,7 +1340,9 @@ func (r *ValueRollup) calcContents(calc *RollupCalc, destKey *Key) {switch typ {case KeyTypeDate:if 0 != earliest {- r.Contents = []*Value{{Type: KeyTypeDate, Date: NewFormattedValueDate(earliest, 0, DateFormatNone, isNotTime, hasEndDate)}}+ date := NewFormattedValueDate(earliest, 0, DateFormatNone, isNotTime, hasEndDate)+ date.FormatDate(destKey.DateFormat)+ r.Contents = []*Value{{Type: KeyTypeDate, Date: date}}}case KeyTypeUpdated:if 0 != earliest {@@ -1247,7 +1351,9 @@ func (r *ValueRollup) calcContents(calc *RollupCalc, destKey *Key) {isNotTime = !destKey.Updated.IncludeTime}- r.Contents = []*Value{{Type: KeyTypeUpdated, Updated: NewFormattedValueUpdated(earliest, 0, UpdatedFormatNone, isNotTime)}}+ updated := NewFormattedValueUpdated(earliest, 0, UpdatedFormatNone, isNotTime)+ updated.FormatDate(destKey.DateFormat, isNotTime)+ r.Contents = []*Value{{Type: KeyTypeUpdated, Updated: updated}}}case KeyTypeCreated:if 0 != earliest {@@ -1256,7 +1362,9 @@ func (r *ValueRollup) calcContents(calc *RollupCalc, destKey *Key) {isNotTime = !destKey.Created.IncludeTime}- r.Contents = []*Value{{Type: KeyTypeCreated, Created: NewFormattedValueCreated(earliest, 0, CreatedFormatNone, isNotTime)}}+ created := NewFormattedValueCreated(earliest, 0, CreatedFormatNone, isNotTime)+ created.FormatDate(destKey.DateFormat, isNotTime)+ r.Contents = []*Value{{Type: KeyTypeCreated, Created: created}}}}case CalcOperatorLatest:@@ -1292,7 +1400,9 @@ func (r *ValueRollup) calcContents(calc *RollupCalc, destKey *Key) {switch typ {case KeyTypeDate:if 0 != latest {- r.Contents = []*Value{{Type: KeyTypeDate, Date: NewFormattedValueDate(latest, 0, DateFormatNone, isNotTime, hasEndDate)}}+ date := NewFormattedValueDate(latest, 0, DateFormatNone, isNotTime, hasEndDate)+ date.FormatDate(destKey.DateFormat)+ r.Contents = []*Value{{Type: KeyTypeDate, Date: date}}}case KeyTypeUpdated:if 0 != latest {@@ -1300,7 +1410,9 @@ func (r *ValueRollup) calcContents(calc *RollupCalc, destKey *Key) {if nil != destKey.Updated {isNotTime = !destKey.Updated.IncludeTime}- r.Contents = []*Value{{Type: KeyTypeUpdated, Updated: NewFormattedValueUpdated(latest, 0, UpdatedFormatNone, isNotTime)}}+ updated := NewFormattedValueUpdated(latest, 0, UpdatedFormatNone, isNotTime)+ updated.FormatDate(destKey.DateFormat, isNotTime)+ r.Contents = []*Value{{Type: KeyTypeUpdated, Updated: updated}}}case KeyTypeCreated:if 0 != latest {@@ -1309,7 +1421,9 @@ func (r *ValueRollup) calcContents(calc *RollupCalc, destKey *Key) {isNotTime = !destKey.Created.IncludeTime}- r.Contents = []*Value{{Type: KeyTypeCreated, Created: NewFormattedValueCreated(latest, 0, CreatedFormatNone, isNotTime)}}+ created := NewFormattedValueCreated(latest, 0, CreatedFormatNone, isNotTime)+ created.FormatDate(destKey.DateFormat, isNotTime)+ r.Contents = []*Value{{Type: KeyTypeCreated, Created: created}}}}case CalcOperatorChecked:diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.goindex eb87dc1295..b06c42df1e 100644--- a/kernel/model/attribute_view.go+++ b/kernel/model/attribute_view.go@@ -6142,6 +6142,40 @@ func updateAttributeViewColNumberFormat(operation *Operation) (err error) {return}+func (tx *Transaction) doSetAttrViewColDateFormat(operation *Operation) (ret *TxErr) {+ err := setAttributeViewColDateFormat(operation)+ if err != nil {+ return &TxErr{code: TxErrHandleAttributeView, id: operation.AvID, msg: err.Error()}+ }+ return+}++func setAttributeViewColDateFormat(operation *Operation) (err error) {+ format := av.DateDisplayFormat(operation.Format)+ if !format.IsValid() {+ return errors.New("invalid date display format")+ }++ attrView, err := av.ParseAttributeView(operation.AvID)+ if err != nil {+ return+ }++ colType := av.KeyType(operation.Typ)+ if av.KeyTypeDate != colType && av.KeyTypeCreated != colType && av.KeyTypeUpdated != colType {+ return errors.New("date display format is only available for date fields")+ }+ for _, keyValues := range attrView.KeyValues {+ if keyValues.Key.ID == operation.ID && keyValues.Key.Type == colType {+ keyValues.Key.DateFormat = format+ break+ }+ }++ err = av.SaveAttributeView(attrView)+ return+}+func (tx *Transaction) doUpdateAttrViewColumn(operation *Operation) (ret *TxErr) {err := updateAttributeViewColumn(operation)if err != nil {@@ -6636,9 +6670,13 @@ func updateAttributeViewValue(tx *Transaction, attrView *av.AttributeView, keyID}}} else if av.KeyTypeDate == val.Type {- if nil != val.Date && !val.Date.IsNotEmpty {- val.Date.Content = 0- val.Date.FormattedContent = ""+ if nil != val.Date {+ if !val.Date.IsNotEmpty {+ val.Date.Content = 0+ val.Date.FormattedContent = ""+ } else if nil != key {+ val.Date.FormatDate(key.DateFormat)+ }}} else if av.KeyTypeSelect == val.Type || av.KeyTypeMSelect == val.Type {if nil != key && 0 < len(val.MSelect) {diff --git a/kernel/model/export.go b/kernel/model/export.goindex 4cff2559dc..81266f7a0e 100644--- a/kernel/model/export.go+++ b/kernel/model/export.go@@ -198,7 +198,10 @@ func ExportAv2CSV(avID, blockID string) (zipPath string, err error) {if nil != cell.Value {if av.KeyTypeDate == cell.Value.Type {if nil != cell.Value.Date {- cell.Value.Date = av.NewFormattedValueDate(cell.Value.Date.Content, cell.Value.Date.Content2, av.DateFormatNone, cell.Value.Date.IsNotTime, cell.Value.Date.HasEndDate)+ key, _ := attrView.GetKey(cell.Value.KeyID)+ if nil != key {+ cell.Value.Date.FormatDate(key.DateFormat)+ }}} else if av.KeyTypeCreated == cell.Value.Type {if nil != cell.Value.Created {@@ -208,7 +211,9 @@ func ExportAv2CSV(avID, blockID string) (zipPath string, err error) {isNotTime = !key.Created.IncludeTime}- cell.Value.Created = av.NewFormattedValueCreated(cell.Value.Created.Content, 0, av.CreatedFormatNone, isNotTime)+ if nil != key {+ cell.Value.Created.FormatDate(key.DateFormat, isNotTime)+ }}} else if av.KeyTypeUpdated == cell.Value.Type {if nil != cell.Value.Updated {@@ -218,7 +223,9 @@ func ExportAv2CSV(avID, blockID string) (zipPath string, err error) {isNotTime = !key.Updated.IncludeTime}- cell.Value.Updated = av.NewFormattedValueUpdated(cell.Value.Updated.Content, 0, av.UpdatedFormatNone, isNotTime)+ if nil != key {+ cell.Value.Updated.FormatDate(key.DateFormat, isNotTime)+ }}} else if av.KeyTypeMAsset == cell.Value.Type {if nil != cell.Value.MAsset {@@ -3482,7 +3489,10 @@ func exportTree(tree *parse.Tree, wysiwyg, keepFold, avHiddenCol bool,}} else if av.KeyTypeDate == cell.Value.Type {if nil != cell.Value.Date {- cell.Value.Date = av.NewFormattedValueDate(cell.Value.Date.Content, cell.Value.Date.Content2, av.DateFormatNone, cell.Value.Date.IsNotTime, cell.Value.Date.HasEndDate)+ key, _ := attrView.GetKey(cell.Value.KeyID)+ if nil != key {+ cell.Value.Date.FormatDate(key.DateFormat)+ }}} else if av.KeyTypeCreated == cell.Value.Type {if nil != cell.Value.Created {@@ -3492,7 +3502,9 @@ func exportTree(tree *parse.Tree, wysiwyg, keepFold, avHiddenCol bool,isNotTime = !key.Created.IncludeTime}- cell.Value.Created = av.NewFormattedValueCreated(cell.Value.Created.Content, 0, av.CreatedFormatNone, isNotTime)+ if nil != key {+ cell.Value.Created.FormatDate(key.DateFormat, isNotTime)+ }}} else if av.KeyTypeUpdated == cell.Value.Type {if nil != cell.Value.Updated {@@ -3502,7 +3514,9 @@ func exportTree(tree *parse.Tree, wysiwyg, keepFold, avHiddenCol bool,isNotTime = !key.Updated.IncludeTime}- cell.Value.Updated = av.NewFormattedValueUpdated(cell.Value.Updated.Content, 0, av.UpdatedFormatNone, isNotTime)+ if nil != key {+ cell.Value.Updated.FormatDate(key.DateFormat, isNotTime)+ }}} else if av.KeyTypeURL == cell.Value.Type {if nil != cell.Value.URL {diff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex a899c3f00a..247b4f6ab4 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -334,6 +334,8 @@ func performTx(tx *Transaction) (ret *TxErr) {ret = tx.doSetAttrViewColCalc(op)case "updateAttrViewColNumberFormat":ret = tx.doUpdateAttrViewColNumberFormat(op)+ case "setAttrViewColDateFormat":+ ret = tx.doSetAttrViewColDateFormat(op)case "replaceAttrViewBlock":ret = tx.doReplaceAttrViewBlock(op)case "updateAttrViewColTemplate":diff --git a/kernel/sql/av.go b/kernel/sql/av.goindex f02d4ce8df..8b545312d5 100644--- a/kernel/sql/av.go+++ b/kernel/sql/av.go@@ -347,13 +347,18 @@ func filterNotFoundAttrViewItems(keyValuesMap map[string][]*av.KeyValues) {}}-func fillAttributeViewBaseValue(baseValue *av.BaseValue, fieldID, itemID string, fieldNumberFormat av.NumberFormat, fieldTemplate string, fieldDateIsTime bool) {+func fillAttributeViewBaseValue(baseValue *av.BaseValue, fieldID, itemID string, fieldNumberFormat av.NumberFormat,+ fieldDateFormat av.DateDisplayFormat, fieldTemplate string, fieldDateIsTime bool) {switch baseValue.ValueType {case av.KeyTypeNumber: // 格式化数字if nil != baseValue.Value && nil != baseValue.Value.Number && baseValue.Value.Number.IsNotEmpty {baseValue.Value.Number.Format = fieldNumberFormatbaseValue.Value.Number.FormatNumber()}+ case av.KeyTypeDate: // 格式化日期+ if nil != baseValue.Value && nil != baseValue.Value.Date {+ baseValue.Value.Date.FormatDate(fieldDateFormat)+ }case av.KeyTypeTemplate: // 渲染模板字段baseValue.Value = &av.Value{ID: baseValue.ID, KeyID: fieldID, BlockID: itemID, Type: av.KeyTypeTemplate, Template: &av.ValueTemplate{Content: fieldTemplate}}case av.KeyTypeCreated: // 填充创建时间字段值,后面再渲染@@ -389,8 +394,12 @@ func fillAttributeViewAutoGeneratedValues(attrView *av.AttributeView, collectioncase av.KeyTypeCreated: // 渲染创建时间key, _ := attrView.GetKey(value.KeyID)isNotTime := false- if nil != key && nil != key.Created {- isNotTime = !key.Created.IncludeTime+ dateFormat := av.DateDisplayFormatDefault+ if nil != key {+ dateFormat = key.DateFormat+ if nil != key.Created {+ isNotTime = !key.Created.IncludeTime+ }}ial := map[string]string{}@@ -409,15 +418,19 @@ func fillAttributeViewAutoGeneratedValues(attrView *av.AttributeView, collectioncreated, parseErr := time.ParseInLocation("20060102150405", createdStr, time.Local)if nil == parseErr {value.Created = av.NewFormattedValueCreated(created.UnixMilli(), 0, av.CreatedFormatNone, isNotTime)- value.Created.IsNotEmpty = true} else {value.Created = av.NewFormattedValueCreated(time.Now().UnixMilli(), 0, av.CreatedFormatNone, isNotTime)}+ value.Created.FormatDate(dateFormat, isNotTime)case av.KeyTypeUpdated: // 渲染更新时间key, _ := attrView.GetKey(value.KeyID)isNotTime := false- if nil != key && nil != key.Updated {- isNotTime = !key.Updated.IncludeTime+ dateFormat := av.DateDisplayFormatDefault+ if nil != key {+ dateFormat = key.DateFormat+ if nil != key.Updated {+ isNotTime = !key.Updated.IncludeTime+ }}ial := map[string]string{}@@ -431,16 +444,15 @@ func fillAttributeViewAutoGeneratedValues(attrView *av.AttributeView, collectionupdatedStr := ial["updated"]if "" == updatedStr && nil != block {value.Updated = av.NewFormattedValueUpdated(block.Block.Updated, 0, av.UpdatedFormatNone, isNotTime)- value.Updated.IsNotEmpty = true} else {updated, parseErr := time.ParseInLocation("20060102150405", updatedStr, time.Local)if nil == parseErr {value.Updated = av.NewFormattedValueUpdated(updated.UnixMilli(), 0, av.UpdatedFormatNone, isNotTime)- value.Updated.IsNotEmpty = true} else {value.Updated = av.NewFormattedValueUpdated(time.Now().UnixMilli(), 0, av.UpdatedFormatNone, isNotTime)}}+ value.Updated.FormatDate(dateFormat, isNotTime)}}}diff --git a/kernel/sql/av_gallery.go b/kernel/sql/av_gallery.goindex 15b09c7f23..66d6286d8c 100644--- a/kernel/sql/av_gallery.go+++ b/kernel/sql/av_gallery.go@@ -63,6 +63,7 @@ func RenderAttributeViewGallery(attrView *av.AttributeView, view *av.View, queryCalc: field.Calc,Options: key.Options,NumberFormat: key.NumberFormat,+ DateFormat: key.DateFormat,Template: key.Template,Relation: key.Relation,Rollup: key.Rollup,@@ -129,7 +130,8 @@ func RenderAttributeViewGallery(attrView *av.AttributeView, view *av.View, queryif nil != field.Date {filedDateIsTime = field.Date.FillSpecificTime}- fillAttributeViewBaseValue(fieldValue.BaseValue, field.ID, cardID, field.NumberFormat, field.Template, filedDateIsTime)+ fillAttributeViewBaseValue(fieldValue.BaseValue, field.ID, cardID, field.NumberFormat, field.DateFormat,+ field.Template, filedDateIsTime)galleryCard.Values = append(galleryCard.Values, fieldValue)}diff --git a/kernel/sql/av_kanban.go b/kernel/sql/av_kanban.goindex a69eb6e612..3451f9ccab 100644--- a/kernel/sql/av_kanban.go+++ b/kernel/sql/av_kanban.go@@ -58,6 +58,7 @@ func RenderAttributeViewKanban(attrView *av.AttributeView, view *av.View, queryCalc: field.Calc,Options: key.Options,NumberFormat: key.NumberFormat,+ DateFormat: key.DateFormat,Template: key.Template,Relation: key.Relation,Rollup: key.Rollup,@@ -124,7 +125,8 @@ func RenderAttributeViewKanban(attrView *av.AttributeView, view *av.View, queryif nil != field.Date {filedDateIsTime = field.Date.FillSpecificTime}- fillAttributeViewBaseValue(fieldValue.BaseValue, field.ID, cardID, field.NumberFormat, field.Template, filedDateIsTime)+ fillAttributeViewBaseValue(fieldValue.BaseValue, field.ID, cardID, field.NumberFormat, field.DateFormat,+ field.Template, filedDateIsTime)kanbanCard.Values = append(kanbanCard.Values, fieldValue)}diff --git a/kernel/sql/av_table.go b/kernel/sql/av_table.goindex f79caa4b2b..a8c425e17e 100644--- a/kernel/sql/av_table.go+++ b/kernel/sql/av_table.go@@ -58,6 +58,7 @@ func RenderAttributeViewTable(attrView *av.AttributeView, view *av.View, query sCalc: col.Calc,Options: key.Options,NumberFormat: key.NumberFormat,+ DateFormat: key.DateFormat,Template: key.Template,Relation: key.Relation,Rollup: key.Rollup,@@ -115,7 +116,8 @@ func RenderAttributeViewTable(attrView *av.AttributeView, view *av.View, query sif nil != col.Date {filedDateIsTime = col.Date.FillSpecificTime}- fillAttributeViewBaseValue(tableCell.BaseValue, col.ID, rowID, col.NumberFormat, col.Template, filedDateIsTime)+ fillAttributeViewBaseValue(tableCell.BaseValue, col.ID, rowID, col.NumberFormat, col.DateFormat, col.Template,+ filedDateIsTime)tableRow.Cells = append(tableRow.Cells, tableCell)}ret.Rows = append(ret.Rows, &tableRow)