diff --git a/apps/desktop/src/components/grid/DataGrid.vue b/apps/desktop/src/components/grid/DataGrid.vue index 415681e889..931cc01e5c 100644 --- a/apps/desktop/src/components/grid/DataGrid.vue +++ b/apps/desktop/src/components/grid/DataGrid.vue @@ -6512,11 +6512,11 @@ function primitiveCellFormatKey(value: CellValue, columnIndex?: number): string } function formatCell(value: CellValue, columnIndex?: number, originalBytes?: number, limitDisplay = true): string { + const formatter = columnIndex === undefined ? undefined : resolvedColumnFormatters.value[columnIndex]; if (props.mongoCollectionGrid) { - const documentGridText = mongoDocumentGridDisplayText(value); + const documentGridText = mongoDocumentGridDisplayText(value, formatter); if (documentGridText !== undefined) return documentGridText; } - const formatter = columnIndex === undefined ? undefined : resolvedColumnFormatters.value[columnIndex]; if (formatter?.kind === "foreign-key-display" && columnIndex !== undefined) { const display = formatForeignKeyCellDisplay(value, columnIndex); return limitDisplay ? limitDataGridCellDisplay(display, resolvedDatabaseType.value === "sqlserver" ? SQLSERVER_DATA_GRID_CELL_DISPLAY_MAX_LENGTH : undefined) : display; diff --git a/apps/desktop/src/lib/mongo/__tests__/mongoDocumentValues.spec.ts b/apps/desktop/src/lib/mongo/__tests__/mongoDocumentValues.spec.ts new file mode 100644 index 0000000000..3ae3a46edb --- /dev/null +++ b/apps/desktop/src/lib/mongo/__tests__/mongoDocumentValues.spec.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from "vitest"; +import type { ColumnFormatterConfig } from "@/lib/dataGrid/columnFormatter"; +import { mongoDocumentGridClipboardText, mongoDocumentGridColumnTypes, mongoDocumentGridDisplayText, mongoDocumentGridEditorText, mongoDocumentGridExternalValue, mongoDocumentGridValue } from "@/lib/mongo/mongoDocumentValues"; + +function dateFormatter(timezone: string | undefined): ColumnFormatterConfig { + return { kind: "datetime", unit: "auto", pattern: "YYYY-MM-DD HH:mm:ss", timezone }; +} + +describe("MongoDB document date display", () => { + it("infers top-level Extended JSON dates as temporal columns", () => { + expect(mongoDocumentGridColumnTypes([{ createdAt: { $date: "2026-09-24T02:00:00.000Z" } }], ["createdAt"])).toEqual(["datetime"]); + expect(mongoDocumentGridColumnTypes([{ createdAt: { $date: { $numberLong: "1790215200000" } } }], ["createdAt"])).toEqual(["datetime"]); + }); + + it("preserves mixed numeric column inference", () => { + expect(mongoDocumentGridColumnTypes([{ value: { $numberInt: "1" } }, { value: { $numberLong: "2" } }], ["value"])).toEqual(["number"]); + }); + + it("formats top-level dates in UTC and IANA time zones", () => { + const value = mongoDocumentGridValue({ $date: "2026-09-24T02:00:00.000Z" }); + expect(mongoDocumentGridDisplayText(value, dateFormatter("UTC"))).toBe("2026-09-24 02:00:00"); + expect(mongoDocumentGridDisplayText(value, dateFormatter("Asia/Shanghai"))).toBe("2026-09-24 10:00:00"); + }); + + it("formats nested dates without changing non-date BSON values", () => { + const value = mongoDocumentGridValue({ event: { at: { $date: "2026-09-24T02:00:00.000Z" }, sequence: { $numberLong: "9007199254740993" } }, tags: ["a"] }); + expect(mongoDocumentGridDisplayText(value, dateFormatter("Asia/Shanghai"))).toBe('{"event":{"at":"2026-09-24 10:00:00","sequence":{"$numberLong":"9007199254740993"}},"tags":["a"]}'); + }); + + it("uses local time when no timezone override is configured", () => { + const value = mongoDocumentGridValue({ $date: "2026-09-24T02:00:00.000Z" }); + expect(mongoDocumentGridDisplayText(value, dateFormatter(undefined))).toMatch(/^2026-09-2[34] \d{2}:00:00$/); + }); + + it("falls back to the original Extended JSON for an invalid timezone", () => { + const value = mongoDocumentGridValue({ nested: { $date: "2026-09-24T02:00:00.000Z" } }); + expect(mongoDocumentGridDisplayText(value, dateFormatter("Invalid/Timezone"))).toBe('{"nested":{"$date":"2026-09-24T02:00:00.000Z"}}'); + }); + + it("keeps edit, copy, and external values independent from display formatting", () => { + const original = { createdAt: { $date: "2026-09-24T02:00:00.000Z" }, nested: [{ $date: "2026-09-24T03:00:00.000Z" }] }; + const value = mongoDocumentGridValue(original) as string; + const rawJson = JSON.stringify(original); + expect(mongoDocumentGridDisplayText(value, dateFormatter("Asia/Shanghai"))).not.toBe(rawJson); + expect(mongoDocumentGridEditorText(value)).toBe(rawJson); + expect(mongoDocumentGridClipboardText(value)).toBe(rawJson); + expect(mongoDocumentGridExternalValue(value)).toBe(rawJson); + }); + + it("does not reinterpret a BSON string that merely looks like Extended JSON", () => { + const value = mongoDocumentGridValue('{"$date":"2026-09-24T02:00:00.000Z"}') as string; + expect(mongoDocumentGridDisplayText(value, dateFormatter("Asia/Shanghai"))).toBeUndefined(); + }); +}); diff --git a/apps/desktop/src/lib/mongo/mongoDocumentValues.ts b/apps/desktop/src/lib/mongo/mongoDocumentValues.ts index 0e57aeb665..63a9efd43c 100644 --- a/apps/desktop/src/lib/mongo/mongoDocumentValues.ts +++ b/apps/desktop/src/lib/mongo/mongoDocumentValues.ts @@ -1,4 +1,5 @@ import type { CellValue } from "@/lib/dataGrid/cellValue"; +import { applyColumnFormatter, type ColumnFormatterConfig } from "@/lib/dataGrid/columnFormatter"; export type MongoInputValue = string | number | boolean | null; @@ -11,6 +12,7 @@ const MONGO_INTEGER_PATTERN = /^-?\d+$/; // before entering the grid and restored before being saved. const MONGO_DOCUMENT_GRID_PREFIX = "\u0000dbx:mongo-document-grid:"; const MONGO_DOCUMENT_GRID_ESCAPED_STRING_PREFIX = `${MONGO_DOCUMENT_GRID_PREFIX}string:`; +const MONGO_DOCUMENT_GRID_JSON_PREFIX = `${MONGO_DOCUMENT_GRID_PREFIX}json:`; export const MONGO_DOCUMENT_GRID_NULL = `${MONGO_DOCUMENT_GRID_PREFIX}null`; const MAX_SAFE_BIGINT = BigInt(Number.MAX_SAFE_INTEGER); const MIN_BSON_INT64 = -9223372036854775808n; @@ -65,14 +67,32 @@ function mongoDocumentNumericValueType(value: unknown): string | undefined { return typeof object[key] === "string" ? MONGO_EXTENDED_JSON_NUMERIC_TYPES.get(key) : undefined; } +type MongoDateTimeFormatter = Extract; + +function mongoExtendedJsonDateValue(value: unknown): string | number | undefined { + if (!value || typeof value !== "object" || Array.isArray(value)) return undefined; + const object = value as Record; + if (Object.keys(object).length !== 1 || !("$date" in object)) return undefined; + const date = object.$date; + if (typeof date === "string" || typeof date === "number") return date; + if (!date || typeof date !== "object" || Array.isArray(date)) return undefined; + const canonical = date as Record; + return Object.keys(canonical).length === 1 && typeof canonical.$numberLong === "string" ? canonical.$numberLong : undefined; +} + export function mongoDocumentGridColumnTypes(documents: readonly Record[], columns: readonly string[]): string[] { return columns.map((column) => { let inferredType: string | undefined; for (const document of documents) { const value = document[column]; if (value === undefined || value === null) continue; + if (mongoExtendedJsonDateValue(value) !== undefined) { + if (inferredType && inferredType !== "datetime") return ""; + inferredType = "datetime"; + continue; + } const numericType = mongoDocumentNumericValueType(value); - if (!numericType) return ""; + if (!numericType || inferredType === "datetime") return ""; inferredType = inferredType && inferredType !== numericType ? "number" : numericType; } return inferredType ?? ""; @@ -136,18 +156,25 @@ export function mongoDocumentDisplayValue(value: unknown): unknown { export function mongoDocumentGridValue(value: unknown): unknown { if (value === null) return MONGO_DOCUMENT_GRID_NULL; if (typeof value === "string" && value.startsWith(MONGO_DOCUMENT_GRID_PREFIX)) return `${MONGO_DOCUMENT_GRID_ESCAPED_STRING_PREFIX}${value}`; - return mongoDocumentDisplayValue(value); + const displayValue = mongoDocumentDisplayValue(value); + return displayValue && typeof displayValue === "object" ? `${MONGO_DOCUMENT_GRID_JSON_PREFIX}${JSON.stringify(displayValue)}` : displayValue; } function mongoDocumentGridEscapedString(value: unknown): string | undefined { return typeof value === "string" && value.startsWith(MONGO_DOCUMENT_GRID_ESCAPED_STRING_PREFIX) ? value.slice(MONGO_DOCUMENT_GRID_ESCAPED_STRING_PREFIX.length) : undefined; } +function mongoDocumentGridJson(value: unknown): string | undefined { + return typeof value === "string" && value.startsWith(MONGO_DOCUMENT_GRID_JSON_PREFIX) ? value.slice(MONGO_DOCUMENT_GRID_JSON_PREFIX.length) : undefined; +} + /** Returns the text presented in a collection-grid editor, when customized. */ export function mongoDocumentGridEditorText(value: unknown): string | undefined { // An existing BSON null is represented as NULL in the grid, but editing it // starts with an empty input. The private marker must never be user-facing. if (value === MONGO_DOCUMENT_GRID_NULL) return ""; + const json = mongoDocumentGridJson(value); + if (json !== undefined) return json; return mongoDocumentGridEscapedString(value); } @@ -158,16 +185,65 @@ export function mongoDocumentGridClipboardText(value: unknown): string | undefin } /** Returns the custom display text required by collection-grid BSON values. */ -export function mongoDocumentGridDisplayText(value: unknown): string | undefined { +export function mongoDocumentGridDisplayText(value: unknown, formatter?: ColumnFormatterConfig): string | undefined { if (value === MONGO_DOCUMENT_GRID_NULL) return "NULL"; const escapedString = mongoDocumentGridEscapedString(value); if (escapedString !== undefined) return JSON.stringify(escapedString); + const json = mongoDocumentGridJson(value); + if (json !== undefined) return formatMongoDocumentGridJson(json, formatter); return value === "NULL" ? JSON.stringify(value) : undefined; } +function formatMongoDocumentGridJson(json: string, formatter: ColumnFormatterConfig | undefined): string { + if (formatter?.kind !== "datetime" || !validMongoDisplayTimeZone(formatter.timezone)) return json; + try { + const transformed = formatMongoDocumentDates(JSON.parse(json), formatter); + if (!transformed.changed) return json; + return typeof transformed.value === "string" ? transformed.value : JSON.stringify(transformed.value); + } catch { + return json; + } +} + +function validMongoDisplayTimeZone(timeZone: string | undefined): boolean { + if (!timeZone) return true; + try { + new Intl.DateTimeFormat("en", { timeZone }).format(0); + return true; + } catch { + return false; + } +} + +function formatMongoDocumentDates(value: unknown, formatter: MongoDateTimeFormatter): { value: unknown; changed: boolean } { + const date = mongoExtendedJsonDateValue(value); + if (date !== undefined) return { value: applyColumnFormatter(date, formatter), changed: true }; + if (Array.isArray(value)) { + let changed = false; + const items = value.map((item) => { + const transformed = formatMongoDocumentDates(item, formatter); + changed ||= transformed.changed; + return transformed.value; + }); + return { value: changed ? items : value, changed }; + } + if (!value || typeof value !== "object") return { value, changed: false }; + let changed = false; + const object = Object.fromEntries( + Object.entries(value as Record).map(([key, item]) => { + const transformed = formatMongoDocumentDates(item, formatter); + changed ||= transformed.changed; + return [key, transformed.value]; + }), + ); + return { value: changed ? object : value, changed }; +} + /** Restores a collection-grid value before it leaves the grid externally. */ export function mongoDocumentGridExternalValue(value: CellValue): CellValue { if (value === MONGO_DOCUMENT_GRID_NULL) return null; + const json = mongoDocumentGridJson(value); + if (json !== undefined) return json; const escapedString = mongoDocumentGridEscapedString(value); return escapedString === undefined ? value : escapedString; }