// SPDX-License-Identifier: AGPL-3.0-or-later // The shape of a database block (ADR-13) and the pure rules over it: how a // cell reads as text, filtering, sorting, grouping and changing a column's // type. The live data is a Y.Map (store.ts); views render a plain snapshot. import type { JSONContent } from "@tiptap/core"; import { isPaletteColor, palette, type PaletteColor } from "../colors"; export const columnTypes = [ "title", "text", "number", "checkbox", "select", "multiSelect", "date", "progress", "link", "attachment", "member", "createdTime", "createdBy", ] as const; export type ColumnType = (typeof columnTypes)[number]; /** Types a column can be changed to (the title column stays the title). */ export const editableTypes = columnTypes.filter((t) => t !== "title"); export interface SelectOption { id: string; name: string; color: PaletteColor; } export interface Column { id: string; name: string; type: ColumnType; /** The choices of a select or multi-select column. */ options?: SelectOption[]; } export interface Person { id: string; name: string; } export interface Attachment { name: string; src: string; size?: number; mime?: string; } export interface Row { id: string; cells: Record; /** Milliseconds since the epoch. */ createdAt: number; createdBy: Person | null; /** Whether the row was opened as a page and has a body. */ hasBody?: boolean; /** The body as ProseMirror nodes, in snapshots read from JSON (see ADR-13). */ body?: JSONContent[]; } export const viewTypes = ["table", "kanban", "calendar"] as const; export type ViewType = (typeof viewTypes)[number]; export type FilterOp = | "contains" | "notContains" | "is" | "isNot" | "isEmpty" | "isNotEmpty" | "gt" | "lt" | "gte" | "lte" | "before" | "after" | "checked" | "unchecked"; export interface Filter { column: string; op: FilterOp; value?: unknown; } export interface Sort { column: string; desc: boolean; } export interface View { id: string; name: string; type: ViewType; /** Column ids the view leaves out. */ hidden: string[]; filters: Filter[]; /** Whether a row must match every filter or any. */ filterMode: "and" | "or"; sorts: Sort[]; /** The column rows are grouped by (kanban always groups). */ groupBy: string | null; /** The date column a calendar places rows by. */ dateColumn: string | null; /** Column widths in pixels, by column id. */ widths: Record; } export interface DbData { title: string; columns: Column[]; rows: Row[]; views: View[]; } /** A short random id, unique enough within one document. */ export function newId(): string { const bytes = new Uint8Array(6); crypto.getRandomValues(bytes); return [...bytes].map((b) => b.toString(36).padStart(2, "0")).join("").slice(0, 10); } export function defaultView(type: ViewType, name: string, columns: Column[]): View { const groupable = columns.find((c) => groupableTypes.includes(c.type)); const date = columns.find((c) => c.type === "date" || c.type === "createdTime"); return { id: newId(), name, type, hidden: [], filters: [], filterMode: "and", sorts: [], groupBy: type === "kanban" ? (groupable?.id ?? null) : null, dateColumn: type === "calendar" ? (date?.id ?? null) : null, widths: {}, }; } /** Columns rows can be grouped by, and kanban boards built on. */ export const groupableTypes: ColumnType[] = ["select", "multiSelect", "checkbox", "member", "createdBy"]; /** Reads a database from untrusted JSON (a node's data attribute, a paste), dropping what does not fit. */ export function normalize(raw: unknown): DbData { const o = isObject(raw) ? raw : {}; const columns = (Array.isArray(o.columns) ? o.columns : []).flatMap((c): Column[] => { if (!isObject(c) || typeof c.id !== "string" || !c.id) return []; const type = (columnTypes as readonly string[]).includes(String(c.type)) ? (c.type as ColumnType) : "text"; const col: Column = { id: c.id, name: typeof c.name === "string" ? c.name : "", type }; if (Array.isArray(c.options)) col.options = c.options.flatMap(option); return [col]; }); if (!columns.some((c) => c.type === "title")) columns.unshift({ id: newId(), name: "", type: "title" }); const rows = (Array.isArray(o.rows) ? o.rows : []).flatMap((r): Row[] => { if (!isObject(r) || typeof r.id !== "string" || !r.id) return []; const row: Row = { id: r.id, cells: isObject(r.cells) ? { ...r.cells } : {}, createdAt: typeof r.createdAt === "number" ? r.createdAt : 0, createdBy: person(r.createdBy), }; if (Array.isArray(r.body) && r.body.length) { row.body = r.body as JSONContent[]; row.hasBody = true; } return [row]; }); const ids = new Set(columns.map((c) => c.id)); const views = (Array.isArray(o.views) ? o.views : []).flatMap((v): View[] => { if (!isObject(v) || typeof v.id !== "string" || !v.id) return []; const type = (viewTypes as readonly string[]).includes(String(v.type)) ? (v.type as ViewType) : "table"; return [ { id: v.id, name: typeof v.name === "string" ? v.name : "", type, hidden: Array.isArray(v.hidden) ? v.hidden.filter((h): h is string => typeof h === "string") : [], filters: Array.isArray(v.filters) ? v.filters.filter((f): f is Filter => isObject(f) && typeof f.column === "string" && typeof f.op === "string") : [], filterMode: v.filterMode === "or" ? "or" : "and", sorts: Array.isArray(v.sorts) ? v.sorts.flatMap((s) => (isObject(s) && typeof s.column === "string" ? [{ column: s.column, desc: !!s.desc }] : [])) : [], groupBy: typeof v.groupBy === "string" && ids.has(v.groupBy) ? v.groupBy : null, dateColumn: typeof v.dateColumn === "string" && ids.has(v.dateColumn) ? v.dateColumn : null, widths: isObject(v.widths) ? Object.fromEntries(Object.entries(v.widths).filter((e): e is [string, number] => typeof e[1] === "number")) : {}, }, ]; }); return { title: typeof o.title === "string" ? o.title : "", columns, rows, views }; } function option(o: unknown): SelectOption[] { if (!isObject(o) || typeof o.id !== "string") return []; return [{ id: o.id, name: typeof o.name === "string" ? o.name : "", color: isPaletteColor(o.color) ? o.color : "gray" }]; } function person(p: unknown): Person | null { return isObject(p) && typeof p.id === "string" ? { id: p.id, name: typeof p.name === "string" ? p.name : "" } : null; } export function isObject(v: unknown): v is Record { return typeof v === "object" && v !== null && !Array.isArray(v); } /** The title column (normalize makes sure there is one). */ export function titleColumn(db: DbData): Column { return db.columns.find((c) => c.type === "title") ?? db.columns[0]!; } /** The value a row has in a column; created time and creator come from the row itself. */ export function cellValue(row: Row, col: Column): unknown { if (col.type === "createdTime") return row.createdAt || null; if (col.type === "createdBy") return row.createdBy ? [row.createdBy] : []; return row.cells[col.id]; } export function isEmptyValue(v: unknown): boolean { return v === undefined || v === null || v === "" || v === false || (Array.isArray(v) && v.length === 0); } /** "YYYY-MM-DD" of a date cell, or "" when it holds none. */ export function dateOf(v: unknown): string { if (typeof v === "number" && v > 0) return isoDay(new Date(v)); if (typeof v === "string" && /^\d{4}-\d{2}-\d{2}/.test(v)) return v.slice(0, 10); return ""; } export function isoDay(d: Date): string { const p = (n: number) => String(n).padStart(2, "0"); return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`; } export function asNumber(v: unknown): number | null { if (typeof v === "number" && Number.isFinite(v)) return v; if (typeof v === "string" && v.trim() !== "") { const n = Number(v.trim().replace(",", ".")); return Number.isFinite(n) ? n : null; } return null; } export function asList(v: unknown): T[] { return Array.isArray(v) ? (v as T[]) : []; } /** A cell as plain text: for CSV, search, sorting text and copying. */ export function cellText(row: Row, col: Column): string { const v = cellValue(row, col); switch (col.type) { case "title": case "text": case "link": return typeof v === "string" ? v : ""; case "number": case "progress": { const n = asNumber(v); return n === null ? "" : String(n); } case "checkbox": return v === true ? "true" : "false"; case "select": return col.options?.find((o) => o.id === v)?.name ?? ""; case "multiSelect": { const names = asList(v).map((id) => col.options?.find((o) => o.id === id)?.name); return names.filter((n): n is string => !!n).join(", "); } case "date": case "createdTime": return dateOf(v); case "attachment": return asList(v) .map((a) => a?.name ?? "") .join(", "); case "member": case "createdBy": return asList(v) .map((p) => p?.name ?? "") .join(", "); } } /** The filter operators a column type offers, the first being the default. */ export function filterOps(type: ColumnType): FilterOp[] { switch (type) { case "number": case "progress": return ["is", "isNot", "gt", "lt", "gte", "lte", "isEmpty", "isNotEmpty"]; case "checkbox": return ["checked", "unchecked"]; case "select": return ["is", "isNot", "isEmpty", "isNotEmpty"]; case "multiSelect": case "member": case "createdBy": return ["contains", "notContains", "isEmpty", "isNotEmpty"]; case "date": case "createdTime": return ["is", "before", "after", "isEmpty", "isNotEmpty"]; case "attachment": return ["isEmpty", "isNotEmpty"]; default: return ["contains", "notContains", "is", "isNot", "isEmpty", "isNotEmpty"]; } } /** Whether a filter operator compares against a value the user types or picks. */ export const opTakesValue = (op: FilterOp) => !["isEmpty", "isNotEmpty", "checked", "unchecked"].includes(op); export function matchesFilter(row: Row, col: Column, f: Filter): boolean { const v = cellValue(row, col); if (f.op === "isEmpty") return isEmptyValue(v) || cellText(row, col) === ""; if (f.op === "isNotEmpty") return !(isEmptyValue(v) || cellText(row, col) === ""); if (f.op === "checked") return v === true; if (f.op === "unchecked") return v !== true; // A filter without a value yet matches everything, as in a spreadsheet. if (f.value === undefined || f.value === null || f.value === "") return true; switch (col.type) { case "number": case "progress": { const n = asNumber(v); const want = asNumber(f.value); if (want === null) return true; if (n === null) return f.op === "isNot"; return { is: n === want, isNot: n !== want, gt: n > want, lt: n < want, gte: n >= want, lte: n <= want }[ f.op as "is" ]; } case "select": return f.op === "is" ? v === f.value : v !== f.value; case "multiSelect": { const has = asList(v).includes(String(f.value)); return f.op === "notContains" ? !has : has; } case "member": case "createdBy": { const want = String(f.value).toLowerCase(); const has = asList(v).some((p) => p?.id === f.value || p?.name?.toLowerCase().includes(want)); return f.op === "notContains" ? !has : has; } case "date": case "createdTime": { const d = dateOf(v); const want = dateOf(f.value); if (!d) return false; return f.op === "before" ? d < want : f.op === "after" ? d > want : d === want; } default: { const text = cellText(row, col).toLowerCase(); const want = String(f.value).toLowerCase(); switch (f.op) { case "contains": return text.includes(want); case "notContains": return !text.includes(want); case "is": return text === want; case "isNot": return text !== want; default: return true; } } } } /** Compares two rows by one column, empty cells last. */ export function compareRows(a: Row, b: Row, col: Column): number { const ea = cellText(a, col) === "" && col.type !== "checkbox"; const eb = cellText(b, col) === "" && col.type !== "checkbox"; if (ea || eb) return ea === eb ? 0 : ea ? 1 : -1; switch (col.type) { case "number": case "progress": return (asNumber(cellValue(a, col)) ?? 0) - (asNumber(cellValue(b, col)) ?? 0); case "checkbox": return Number(cellValue(a, col) === true) - Number(cellValue(b, col) === true); case "createdTime": return a.createdAt - b.createdAt; case "select": { // Choices sort in their own order, like a status column. const order = (r: Row) => col.options?.findIndex((o) => o.id === cellValue(r, col)) ?? -1; return order(a) - order(b); } default: return cellText(a, col).localeCompare(cellText(b, col), undefined, { numeric: true, sensitivity: "base" }); } } /** The rows a view shows, filtered, searched and sorted (stable: ties keep the manual order). */ export function viewRows(db: DbData, view: View, search = ""): Row[] { const byId = new Map(db.columns.map((c) => [c.id, c])); const filters = view.filters.flatMap((f) => { const col = byId.get(f.column); return col ? [{ f, col }] : []; }); const q = search.trim().toLowerCase(); let rows = db.rows.filter((r) => { if (filters.length) { const test = ({ f, col }: (typeof filters)[number]) => matchesFilter(r, col, f); if (view.filterMode === "or" ? !filters.some(test) : !filters.every(test)) return false; } return !q || db.columns.some((c) => cellText(r, c).toLowerCase().includes(q)); }); const sorts = view.sorts.flatMap((s) => { const col = byId.get(s.column); return col ? [{ col, desc: s.desc }] : []; }); if (sorts.length) { rows = rows .map((r, i) => ({ r, i })) .sort((x, y) => { for (const s of sorts) { const c = compareRows(x.r, y.r, s.col); // Empty cells stay last in both directions. if (c !== 0) { const empty = cellText(x.r, s.col) === "" || cellText(y.r, s.col) === ""; return s.desc && !(empty && s.col.type !== "checkbox") ? -c : c; } } return x.i - y.i; }) .map((x) => x.r); } return rows; } /** The columns a view shows, in order. The title column always shows. */ export function visibleColumns(db: DbData, view: View): Column[] { return db.columns.filter((c) => c.type === "title" || !view.hidden.includes(c.id)); } export interface Group { /** The value rows in this group have: an option id, "true"/"false", a person id; "" = none. */ key: string; label: string; color?: PaletteColor; rows: Row[]; } /** Splits rows into groups by a column: one per choice (in order) plus "No value". */ export function groupRows(rows: Row[], col: Column, noValue: string, yes: string, no: string): Group[] { const groups = new Map(); const add = (key: string, label: string, color?: PaletteColor) => { if (!groups.has(key)) groups.set(key, { key, label, color, rows: [] }); return groups.get(key)!; }; if (col.type === "checkbox") { add("false", no); add("true", yes); } else { add("", noValue); for (const o of col.options ?? []) add(o.id, o.name, o.color); } for (const r of rows) { for (const key of groupKeys(r, col)) { const g = groups.get(key) ?? add(key, personName(r, col, key) || key); g.rows.push(r); } } return [...groups.values()]; } function personName(r: Row, col: Column, id: string): string { return asList(cellValue(r, col)).find((p) => p?.id === id)?.name ?? ""; } /** The groups a row belongs to in a column (several for multi-select and members). */ export function groupKeys(r: Row, col: Column): string[] { const v = cellValue(r, col); switch (col.type) { case "checkbox": return [v === true ? "true" : "false"]; case "select": return [typeof v === "string" && col.options?.some((o) => o.id === v) ? v : ""]; case "multiSelect": { const ids = asList(v).filter((id) => col.options?.some((o) => o.id === id)); return ids.length ? ids : [""]; } case "member": case "createdBy": { const ids = asList(v).flatMap((p) => (p?.id ? [p.id] : [])); return ids.length ? ids : [""]; } default: return [""]; } } /** * The cell value after moving a row from one group to another (kanban drag): * select takes the new choice, multi-select swaps the old one for the new. */ export function moveToGroup(r: Row, col: Column, from: string, to: string, people: Person[] = []): unknown { const v = cellValue(r, col); switch (col.type) { case "checkbox": return to === "true"; case "select": return to || null; case "multiSelect": { const ids = asList(v).filter((id) => id !== from && id !== to); return to ? [...ids, to] : ids; } case "member": { const list = asList(v).filter((p) => p?.id !== from && p?.id !== to); const p = people.find((x) => x.id === to) ?? asList(v).find((x) => x?.id === to); return to && p ? [...list, p] : list; } default: return v; } } /** The next palette colour for a new choice, so neighbours differ. */ export function nextColor(options: SelectOption[]): PaletteColor { const choices = palette.filter((c) => c !== "gray"); return choices[options.length % choices.length]!; } /** * A cell's value after its column changed type. Text becomes choices (new * options are returned to add), numbers parse, choices become their names. */ export function convertValue( v: unknown, from: Column, to: ColumnType, options: SelectOption[], ): { value: unknown; options: SelectOption[] } { if (from.type === to) return { value: v, options }; const text = cellText({ id: "", cells: { [from.id]: v }, createdAt: 0, createdBy: null }, from); const choice = (name: string) => { const n = name.trim(); if (!n) return null; let o = options.find((x) => x.name.toLowerCase() === n.toLowerCase()); if (!o) { o = { id: newId(), name: n, color: nextColor(options) }; options = [...options, o]; } return o.id; }; switch (to) { case "title": case "text": case "link": return { value: text || null, options }; case "number": return { value: asNumber(text), options }; case "progress": { const n = asNumber(text); return { value: n === null ? null : Math.max(0, Math.min(100, Math.round(n))), options }; } case "checkbox": return { value: ["true", "yes", "1", "x", "✓", "done"].includes(text.trim().toLowerCase()), options }; case "select": return { value: choice(text.split(",")[0] ?? ""), options }; case "multiSelect": { const ids = text.split(",").flatMap((t) => { const id = choice(t); return id ? [id] : []; }); return { value: [...new Set(ids)], options }; } case "date": return { value: dateOf(text) || null, options }; case "member": return { value: from.type === "member" || from.type === "createdBy" ? v : [], options }; default: return { value: null, options }; } } /** Days of the month grid around a month (Monday first): 5 or 6 weeks of "YYYY-MM-DD". */ export function monthGrid(year: number, month: number, weekStart = 1): string[] { const first = new Date(year, month, 1); const lead = (first.getDay() - weekStart + 7) % 7; const start = new Date(year, month, 1 - lead); const days = new Date(year, month + 1, 0).getDate(); const weeks = Math.ceil((lead + days) / 7); return Array.from({ length: weeks * 7 }, (_, i) => isoDay(new Date(start.getFullYear(), start.getMonth(), start.getDate() + i)), ); }