Add list and gallery views to databases

List shows one line per record with its visible properties; gallery
shows cards in a grid, covered with the first image of an attachment
property chosen in the view's settings. Both filter, sort and group
like tables, and a click opens the record. Older clients show the new
layouts as tables (normalize already falls back for unknown types).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-11-17 12:27:43 +01:00
1 parent 29465e4617
commit ab73a7d0d7
13 files changed
+601 -64

No files matched your search

+63 -4
View File
@@ -3,7 +3,19 @@
import { describe, expect, it } from "vitest";
import * as Y from "yjs";
import { formatDelimited, fromCSV, parseDelimited, toCSV } from "./csv";
import { convertValue, defaultView, groupRows, monthGrid, moveToGroup, normalize, viewRows, type Column, type DbData, type Row } from "./model";
import {
convertValue,
coverImage,
defaultView,
groupRows,
monthGrid,
moveToGroup,
normalize,
viewRows,
type Column,
type DbData,
type Row,
} from "./model";
import { blocksOf, DbStore, readDb, seedDb } from "./store";
const title: Column = { id: "t", name: "Name", type: "title" };
@@ -23,7 +35,11 @@ function sample(): DbData {
return {
title: "Tasks",
columns: [title, status, points],
rows: [row("a", { t: "Write", s: "todo", p: 3 }), row("b", { t: "Read", s: "done", p: 1 }), row("c", { t: "Ship", p: 5 })],
rows: [
row("a", { t: "Write", s: "todo", p: 3 }),
row("b", { t: "Read", s: "done", p: 1 }),
row("c", { t: "Ship", p: 5 }),
],
views: [defaultView("table", "Table", [title, status, points])],
};
}
@@ -81,13 +97,23 @@ describe("CSV", () => {
["a", "b,c", 'd "e"\nf'],
["1", "2", "3"],
]);
expect(formatDelimited([["a", "b,c"], ['x"y', ""]])).toBe('a,"b,c"\r\n"x""y",');
expect(
formatDelimited([
["a", "b,c"],
['x"y', ""],
]),
).toBe('a,"b,c"\r\n"x""y",');
});
it("guesses column types on import and writes them back", () => {
const { columns, rows } = fromCSV("Name,Points,Due,Done\nA,1,2026-11-01,yes\nB,2.5,2026-11-02,no\n");
expect(columns.map((c) => c.type)).toEqual(["title", "number", "date", "checkbox"]);
expect(rows[1]).toEqual({ [columns[0]!.id]: "B", [columns[1]!.id]: 2.5, [columns[2]!.id]: "2026-11-02", [columns[3]!.id]: false });
expect(rows[1]).toEqual({
[columns[0]!.id]: "B",
[columns[1]!.id]: 2.5,
[columns[2]!.id]: "2026-11-02",
[columns[3]!.id]: false,
});
const db = sample();
expect(toCSV(db, db.columns, db.rows).split("\r\n")[1]).toBe("Write,To do,3");
});
@@ -129,3 +155,36 @@ describe("database store", () => {
}
});
});
describe("list and gallery views", () => {
it("reads the new layouts and a gallery's cover, and shows unknown layouts as tables", () => {
const files: Column = { id: "f", name: "Photos", type: "attachment" };
const db = normalize({
columns: [title, files],
views: [
{ id: "g", name: "Pictures", type: "gallery", cover: "f" },
{ id: "l", name: "Lines", type: "list", cover: "gone" },
{ id: "x", name: "Future", type: "mindmap" },
],
});
expect(db.views.map((v) => [v.type, v.cover])).toEqual([
["gallery", "f"],
["list", null],
["table", null],
]);
expect(defaultView("gallery", "G", [title, files]).cover).toBe("f");
expect(defaultView("list", "L", [title, files]).cover).toBeNull();
});
it("covers a card with the first image of the cell", () => {
expect(
coverImage([
{ name: "notes.pdf", src: "/f/1", mime: "application/pdf" },
{ name: "a.png", src: "/f/2", mime: "image/png" },
]),
).toBe("/f/2");
expect(coverImage([{ name: "photo.JPG", src: "/f/3" }])).toBe("/f/3");
expect(coverImage([{ name: "notes.pdf", src: "/f/1" }])).toBe("");
expect(coverImage("nope")).toBe("");
});
});
+13 -2
View File
@@ -25,6 +25,10 @@ export const englishDatabaseLabels = {
viewTable: "Table",
viewKanban: "Kanban",
viewCalendar: "Calendar",
viewList: "List",
viewGallery: "Gallery",
cover: "Card cover",
noCover: "No cover",
noValue: "No value",
checked: "Checked",
unchecked: "Unchecked",
@@ -217,7 +221,14 @@ const opKeys: Record<FilterOp, keyof DatabaseLabels> = {
export const opLabel = (l: DatabaseLabels, op: FilterOp) => l[opKeys[op]];
export const viewLabel = (l: DatabaseLabels, t: ViewType) =>
t === "kanban" ? l.viewKanban : t === "calendar" ? l.viewCalendar : l.viewTable;
const viewKeys: Record<ViewType, keyof DatabaseLabels> = {
table: "viewTable",
kanban: "viewKanban",
calendar: "viewCalendar",
list: "viewList",
gallery: "viewGallery",
};
export const viewLabel = (l: DatabaseLabels, t: ViewType) => l[viewKeys[t]];
export const fill = (s: string, n: number | string) => s.replace("{n}", String(n));
+38 -6
View File
@@ -74,7 +74,8 @@ export interface Row {
computed?: Record<string, Computed>;
}
export const viewTypes = ["table", "kanban", "calendar"] as const;
/** View layouts. Clients that do not know a layout show it as a table (normalize). */
export const viewTypes = ["table", "kanban", "calendar", "list", "gallery"] as const;
export type ViewType = (typeof viewTypes)[number];
export type FilterOp =
@@ -118,6 +119,8 @@ export interface View {
groupBy: string | null;
/** The date column a calendar places rows by. */
dateColumn: string | null;
/** The attachment column whose first image is a gallery card's cover; null for none. */
cover: string | null;
/** Column widths in pixels, by column id. */
widths: Record<string, number>;
}
@@ -133,7 +136,10 @@ export interface DbData {
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);
return [...bytes]
.map((b) => b.toString(36).padStart(2, "0"))
.join("")
.slice(0, 10);
}
export function defaultView(type: ViewType, name: string, columns: Column[]): View {
@@ -149,6 +155,7 @@ export function defaultView(type: ViewType, name: string, columns: Column[]): Vi
sorts: [],
groupBy: type === "kanban" ? (groupable?.id ?? null) : null,
dateColumn: type === "calendar" ? (date?.id ?? null) : null,
cover: type === "gallery" ? (columns.find((c) => c.type === "attachment")?.id ?? null) : null,
widths: {},
};
}
@@ -196,14 +203,19 @@ export function normalize(raw: unknown): DbData {
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")
? 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 }] : []))
? 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,
cover: typeof v.cover === "string" && ids.has(v.cover) ? v.cover : null,
widths: isObject(v.widths)
? Object.fromEntries(Object.entries(v.widths).filter((e): e is [string, number] => typeof e[1] === "number"))
: {},
@@ -215,7 +227,9 @@ export function normalize(raw: unknown): DbData {
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" }];
return [
{ id: o.id, name: typeof o.name === "string" ? o.name : "", color: isPaletteColor(o.color) ? o.color : "gray" },
];
}
function person(p: unknown): Person | null {
@@ -354,7 +368,10 @@ export function matchesFilter(row: Row, col: Column, f: Filter): boolean {
// A filter without a value yet matches everything, as in a spreadsheet.
if (f.value === undefined || f.value === null || f.value === "") return true;
// A rollup that counts or sums compares as a number.
const numeric = col.type === "rollup" && (typeof v === "number" || v === null) && ["is", "isNot", "gt", "lt", "gte", "lte"].includes(f.op);
const numeric =
col.type === "rollup" &&
(typeof v === "number" || v === null) &&
["is", "isNot", "gt", "lt", "gte", "lte"].includes(f.op);
switch (numeric ? "number" : col.type) {
case "number":
case "progress": {
@@ -628,3 +645,18 @@ export function monthGrid(year: number, month: number, weekStart = 1): string[]
isoDay(new Date(start.getFullYear(), start.getMonth(), start.getDate() + i)),
);
}
/** The first image of an attachment cell, for a gallery cover; "" when it has none. */
export function coverImage(v: unknown): string {
if (!Array.isArray(v)) return "";
for (const f of v as Partial<Attachment>[]) {
if (!f || typeof f.src !== "string" || !f.src) continue;
if (
typeof f.mime === "string"
? f.mime.startsWith("image/")
: /\.(png|jpe?g|gif|webp|avif|svg)$/i.test(f.name ?? f.src)
)
return f.src;
}
return "";
}
+16
View File
@@ -200,6 +200,22 @@ export function datePanel(ctx: DbContext, box: HTMLElement, view: View) {
);
}
/** The attachment property whose first image covers a gallery's cards. */
export function coverPanel(ctx: DbContext, box: HTMLElement, view: View) {
const store = ctx.store;
const l = ctx.labels;
const files = ctx.db.columns.filter((c) => c.type === "attachment");
box.append(
h("label", { class: "dw-db-pop__label" }, l.cover),
select(
view.cover ?? "",
[{ value: "", label: l.noCover }, ...files.map((c) => ({ value: c.id, label: c.name || typeLabel(l, c.type) }))],
l.cover,
(v) => store?.updateView(view.id, { cover: v || null }),
),
);
}
/** Which properties the view shows. */
export function propertiesPanel(ctx: DbContext, box: HTMLElement, view: View) {
const store = ctx.store;
+311 -45
View File
@@ -4,6 +4,7 @@
// (table, kanban or calendar). The header stays put between redraws, so
// panels opened from the toolbar keep their anchor while the rows change.
import type { IconName } from "@docwell/ui/icons";
import { openBlockMenu, type BlockAction } from "../blockmenu";
import { editCell, inlineTypes, readOnlyTypes, renderCell, typeIcons, type DbContext } from "./cells";
import { formatDelimited, fromCSV, matchHeader, parseCell, parseDelimited, toCSV } from "./csv";
@@ -14,6 +15,7 @@ import { touchDraggable } from "./touchdrag";
import {
cellText,
cellValue,
coverImage,
dateOf,
editableTypes,
filterOps,
@@ -80,7 +82,12 @@ export class DatabaseView {
const now = new Date();
this.month = { y: now.getFullYear(), m: now.getMonth() };
const l = host.labels;
this.searchInput = h("input", { class: "dw-db-input dw-db__search", placeholder: l.search, "aria-label": l.search, hidden: true });
this.searchInput = h("input", {
class: "dw-db-input dw-db__search",
placeholder: l.search,
"aria-label": l.search,
hidden: true,
});
this.searchInput.addEventListener("input", () => {
this.search = this.searchInput.value;
this.limit = PAGE;
@@ -204,7 +211,7 @@ export class DatabaseView {
role: "tab",
"aria-selected": String(v.id === active.id),
},
icon(v.type === "kanban" ? "cards" : v.type === "calendar" ? "calendar" : "table", 14),
icon(viewIcons[v.type], 14),
h("span", {}, v.name || viewLabel(l, v.type)),
);
tab.addEventListener("click", () => {
@@ -229,7 +236,7 @@ export class DatabaseView {
viewTypes.map((t) => ({
id: t,
label: viewLabel(l, t),
icon: t === "kanban" ? "cards" : t === "calendar" ? "calendar" : "table",
icon: viewIcons[t],
run: () => {
this.showView(this.host.store!.addView(t, viewLabel(l, t)));
},
@@ -252,7 +259,7 @@ export class DatabaseView {
count(b.filter, v.filters.length);
count(b.sort, v.sorts.length);
b.sort.hidden = v.type === "calendar";
b.group.classList.toggle("is-on", !!v.groupBy && v.type === "table");
b.group.classList.toggle("is-on", !!v.groupBy && groupedLayouts.includes(v.type));
b.group.hidden = v.type === "calendar";
b.add.hidden = !this.editable;
this.drawBulk();
@@ -266,10 +273,15 @@ export class DatabaseView {
const l = this.labels;
this.bulk.replaceChildren(
h("span", {}, fill(l.selected, ids.length)),
iconButton("trash", l.deleteRows, () => {
this.host.store?.deleteRows(ids);
this.picked.clear();
}, l.deleteRows),
iconButton(
"trash",
l.deleteRows,
() => {
this.host.store?.deleteRows(ids);
this.picked.clear();
},
l.deleteRows,
),
iconButton("close", l.close, () => {
this.picked.clear();
this.draw();
@@ -292,6 +304,7 @@ export class DatabaseView {
else {
if (view.type === "calendar") p.datePanel(ctx, box, view);
if (view.type === "kanban") p.groupPanel(ctx, box, view);
if (view.type === "gallery") p.coverPanel(ctx, box, view);
p.propertiesPanel(ctx, box, view);
}
},
@@ -320,7 +333,7 @@ export class DatabaseView {
children: viewTypes.map((t: ViewType) => ({
id: t,
label: viewLabel(l, t),
icon: t === v.type ? "check" : t === "kanban" ? "cards" : t === "calendar" ? "calendar" : "table",
icon: t === v.type ? "check" : viewIcons[t],
run: () => this.setLayout(v, t),
})),
},
@@ -334,7 +347,13 @@ export class DatabaseView {
},
];
if (this.db.views.length > 1) {
actions.push({ id: "delete", label: l.deleteView, icon: "trash", danger: true, run: () => store.deleteView(v.id) });
actions.push({
id: "delete",
label: l.deleteView,
icon: "trash",
danger: true,
run: () => store.deleteView(v.id),
});
}
openBlockMenu(anchor, actions, l.layout);
}
@@ -350,7 +369,9 @@ export class DatabaseView {
private setLayout(v: View, type: ViewType) {
const patch: Partial<View> = { type };
const cols = this.db.columns;
if (type === "kanban" && !v.groupBy) patch.groupBy = cols.find((c) => ["select", "multiSelect", "checkbox", "member"].includes(c.type))?.id ?? null;
if (type === "kanban" && !v.groupBy)
patch.groupBy = cols.find((c) => ["select", "multiSelect", "checkbox", "member"].includes(c.type))?.id ?? null;
if (type === "gallery" && !v.cover) patch.cover = cols.find((c) => c.type === "attachment")?.id ?? null;
if (type === "calendar" && !v.dateColumn) patch.dateColumn = cols.find((c) => c.type === "date")?.id ?? null;
if (type === "calendar" && !patch.dateColumn && !v.dateColumn && this.host.store) {
patch.dateColumn = this.host.store.addColumn("date", this.labels.typeDate);
@@ -402,13 +423,19 @@ export class DatabaseView {
ids.set(first.id, title.id);
}
for (const c of rest) {
const existing = this.db.columns.find((x) => x.name.toLowerCase() === c.name.toLowerCase() && x.type !== "title");
const existing = this.db.columns.find(
(x) => x.name.toLowerCase() === c.name.toLowerCase() && x.type !== "title",
);
if (existing) store.deleteColumn(existing.id);
const id = store.addColumn(c.type, c.name);
if (c.options) store.setOptions(id, c.options);
ids.set(c.id, id);
}
store.addRows(parsed.rows.map((cells) => Object.fromEntries(Object.entries(cells).map(([k, val]) => [ids.get(k) ?? k, val]))));
store.addRows(
parsed.rows.map((cells) =>
Object.fromEntries(Object.entries(cells).map(([k, val]) => [ids.get(k) ?? k, val])),
),
);
this.host.notify?.(fill(this.labels.imported, parsed.rows.length));
return;
}
@@ -468,6 +495,7 @@ export class DatabaseView {
const v = this.view;
if (v.type === "kanban") this.drawKanban(v);
else if (v.type === "calendar") this.drawCalendar(v);
else if (v.type === "list" || v.type === "gallery") this.drawItems(v);
else this.drawTable(v);
}
@@ -547,7 +575,14 @@ export class DatabaseView {
const add = h("button", { type: "button", class: "dw-db-t__new" }, icon("plus", 14), h("span", {}, l.newRow));
add.addEventListener("click", () => {
const cells: Record<string, unknown> = {};
if (group && g.key) cells[group.id] = moveToGroup({ id: "", cells: {}, createdAt: 0, createdBy: null }, group, "", g.key, g.rows.flatMap((x) => asPeople(cellValue(x, group))));
if (group && g.key)
cells[group.id] = moveToGroup(
{ id: "", cells: {}, createdAt: 0, createdBy: null },
group,
"",
g.key,
g.rows.flatMap((x) => asPeople(cellValue(x, group))),
);
else if (group?.type === "checkbox") cells[group.id] = g.key === "true";
this.addRow(cells);
});
@@ -556,11 +591,19 @@ export class DatabaseView {
table.append(tbody);
}
const children: Node[] = [];
const wrap = h("div", { class: "dw-db-t__wrap", role: "grid", tabIndex: 0, "aria-label": this.db.title || l.database }, table);
const wrap = h(
"div",
{ class: "dw-db-t__wrap", role: "grid", tabIndex: 0, "aria-label": this.db.title || l.database },
table,
);
children.push(wrap);
if (!rows.length) children.push(h("p", { class: "dw-db__empty" }, this.db.rows.length ? l.noMatches : l.noRows));
if (rows.length > shown && shown >= this.limit) {
const more = h("button", { type: "button", class: "dw-db__btn dw-db__more" }, `${l.more} (${rows.length - shown})`);
const more = h(
"button",
{ type: "button", class: "dw-db__btn dw-db__more" },
`${l.more} (${rows.length - shown})`,
);
more.addEventListener("click", () => {
this.limit += PAGE;
this.drawBody();
@@ -607,7 +650,10 @@ export class DatabaseView {
const id = e.dataTransfer?.getData("application/x-docwell-column");
if (!id || id === c.id) return;
e.preventDefault();
this.host.store?.moveColumn(id, this.db.columns.findIndex((x) => x.id === c.id));
this.host.store?.moveColumn(
id,
this.db.columns.findIndex((x) => x.id === c.id),
);
});
// Drag the right edge to resize; the width is saved with the view.
const grip = h("span", { class: "dw-db-t__resize", title: l.resize, "aria-hidden": "true" });
@@ -652,9 +698,7 @@ export class DatabaseView {
}
const all = this.db.columns;
const at = all.findIndex((x) => x.id === c.id);
const actions: BlockAction[] = [
{ id: "rename", label: l.rename, icon: "pencil", run: () => this.renameColumn(c) },
];
const actions: BlockAction[] = [{ id: "rename", label: l.rename, icon: "pencil", run: () => this.renameColumn(c) }];
if (c.type !== "title") {
actions.push({
id: "type",
@@ -673,9 +717,19 @@ export class DatabaseView {
});
}
if (c.type === "relation")
actions.push({ id: "relationTo", label: l.relationTo, icon: "relation", run: () => this.linkSettings(anchor, c.id) });
actions.push({
id: "relationTo",
label: l.relationTo,
icon: "relation",
run: () => this.linkSettings(anchor, c.id),
});
if (c.type === "rollup")
actions.push({ id: "rollup", label: l.rollupSettings, icon: "rollup", run: () => this.linkSettings(anchor, c.id) });
actions.push({
id: "rollup",
label: l.rollupSettings,
icon: "rollup",
run: () => this.linkSettings(anchor, c.id),
});
actions.push(sortBy(false), sortBy(true), {
id: "filter",
label: l.filterBy,
@@ -685,13 +739,26 @@ export class DatabaseView {
this.buttons.filter.click();
},
});
if (c.type !== "title") actions.push({ id: "hide", label: l.hide, icon: "close", run: () => store.updateView(v.id, { hidden: [...v.hidden, c.id] }) });
if (c.type !== "title")
actions.push({
id: "hide",
label: l.hide,
icon: "close",
run: () => store.updateView(v.id, { hidden: [...v.hidden, c.id] }),
});
actions.push(
{ id: "left", label: l.insertLeft, icon: "plus", run: () => this.insertColumn(at) },
{ id: "right", label: l.insertRight, icon: "plus", run: () => this.insertColumn(at + 1) },
);
if (at > 0) actions.push({ id: "moveLeft", label: l.moveLeft, icon: "arrow-up", run: () => store.moveColumn(c.id, at - 1) });
if (at < all.length - 1) actions.push({ id: "moveRight", label: l.moveRight, icon: "arrow-down", run: () => store.moveColumn(c.id, at + 1) });
if (at > 0)
actions.push({ id: "moveLeft", label: l.moveLeft, icon: "arrow-up", run: () => store.moveColumn(c.id, at - 1) });
if (at < all.length - 1)
actions.push({
id: "moveRight",
label: l.moveRight,
icon: "arrow-down",
run: () => store.moveColumn(c.id, at + 1),
});
if (c.type !== "title") {
actions.push(
{ id: "duplicate", label: l.duplicate, icon: "copy", run: () => store.duplicateColumn(c.id, `${c.name} 2`) },
@@ -775,7 +842,12 @@ export class DatabaseView {
const tr = h("tr", { dataset: { row: r.id }, class: this.picked.has(r.id) ? "is-picked" : "" });
const gutter = h("td", { class: "dw-db-t__gutter" });
if (this.editable) {
const check = h("input", { type: "checkbox", class: "dw-db-t__pick", "aria-label": l.selectRow, checked: this.picked.has(r.id) });
const check = h("input", {
type: "checkbox",
class: "dw-db-t__pick",
"aria-label": l.selectRow,
checked: this.picked.has(r.id),
});
check.addEventListener("change", () => {
if (check.checked) this.picked.add(r.id);
else this.picked.delete(r.id);
@@ -784,7 +856,11 @@ export class DatabaseView {
});
gutter.append(check);
if (movable) {
const grip = h("span", { class: "dw-db-t__grip", draggable: true, title: l.dragRow, "aria-hidden": "true" }, icon("grip", 14));
const grip = h(
"span",
{ class: "dw-db-t__grip", draggable: true, title: l.dragRow, "aria-hidden": "true" },
icon("grip", 14),
);
grip.addEventListener("dragstart", (e) => {
e.dataTransfer?.setData("application/x-docwell-row", r.id);
if (e.dataTransfer) e.dataTransfer.effectAllowed = "move";
@@ -834,9 +910,18 @@ export class DatabaseView {
}
tr.append(gutter);
for (const c of cols) {
const td = h("td", { dataset: { col: c.id }, class: `dw-db-t__cell dw-db-t__cell--${c.type}`, role: "gridcell" }, renderCell(this.ctx(), r, c));
const td = h(
"td",
{ dataset: { col: c.id }, class: `dw-db-t__cell dw-db-t__cell--${c.type}`, role: "gridcell" },
renderCell(this.ctx(), r, c),
);
if (c.type === "title") {
const open = h("button", { type: "button", class: "dw-db-t__open", title: l.openRow }, icon("open", 13), h("span", {}, l.openRow));
const open = h(
"button",
{ type: "button", class: "dw-db-t__open", title: l.openRow },
icon("open", 13),
h("span", {}, l.openRow),
);
open.addEventListener("click", (e) => {
e.stopPropagation();
this.openRow(r.id);
@@ -916,7 +1001,8 @@ export class DatabaseView {
private markSelection() {
if (!this.grid) return;
for (const el of this.grid.querySelectorAll(".is-selected, .is-in-range")) el.classList.remove("is-selected", "is-in-range");
for (const el of this.grid.querySelectorAll(".is-selected, .is-in-range"))
el.classList.remove("is-selected", "is-in-range");
const rg = this.range();
if (!rg || !this.sel) return;
for (let r = rg.r0; r <= rg.r1; r++) {
@@ -930,7 +1016,10 @@ export class DatabaseView {
}
private cellEl(row: string, col: string): HTMLElement | null {
return this.grid?.querySelector<HTMLElement>(`tr[data-row="${CSS.escape(row)}"] td[data-col="${CSS.escape(col)}"]`) ?? null;
return (
this.grid?.querySelector<HTMLElement>(`tr[data-row="${CSS.escape(row)}"] td[data-col="${CSS.escape(col)}"]`) ??
null
);
}
private startEdit(initial?: string) {
@@ -977,7 +1066,12 @@ export class DatabaseView {
return this.host.redo();
}
if (mod) return;
const arrows: Record<string, [number, number]> = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] };
const arrows: Record<string, [number, number]> = {
ArrowUp: [-1, 0],
ArrowDown: [1, 0],
ArrowLeft: [0, -1],
ArrowRight: [0, 1],
};
const step = arrows[e.key];
if (step) {
e.preventDefault();
@@ -1012,7 +1106,8 @@ export class DatabaseView {
for (let r = rg.r0; r <= rg.r1; r++) {
for (let c = rg.c0; c <= rg.c1; c++) {
const col = this.tableCols[c]!;
if (!readOnlyTypes.includes(col.type) && !isBackRelation(col)) changes.push({ row: this.tableRows[r]!.id, col: col.id, value: null });
if (!readOnlyTypes.includes(col.type) && !isBackRelation(col))
changes.push({ row: this.tableRows[r]!.id, col: col.id, value: null });
}
}
this.host.store.setCells(changes);
@@ -1123,7 +1218,13 @@ export class DatabaseView {
for (const r of g.rows.slice(0, this.limit)) {
const card = h(
"div",
{ class: "dw-db-k__card", tabIndex: 0, role: "button", draggable: this.editable && !readOnlyTypes.includes(col.type), dataset: { row: r.id } },
{
class: "dw-db-k__card",
tabIndex: 0,
role: "button",
draggable: this.editable && !readOnlyTypes.includes(col.type),
dataset: { row: r.id },
},
h("div", { class: "dw-db-k__title" }, renderCell(this.ctx(), r, title)),
shown.flatMap((c) => {
if (cellText(r, c) === "" || (c.type === "checkbox" && cellValue(r, c) !== true)) return [];
@@ -1162,7 +1263,8 @@ export class DatabaseView {
},
drop: (t) => {
const at = listAt(t);
if (at) dropCard(r.id, g.key, at.dataset.group ?? "", t?.closest<HTMLElement>(".dw-db-k__card")?.dataset.row);
if (at)
dropCard(r.id, g.key, at.dataset.group ?? "", t?.closest<HTMLElement>(".dw-db-k__card")?.dataset.row);
},
end: () => mark?.classList.remove("is-drop"),
});
@@ -1173,7 +1275,10 @@ export class DatabaseView {
const add = h("button", { type: "button", class: "dw-db-t__new" }, icon("plus", 14), h("span", {}, l.newRow));
add.addEventListener("click", () => {
const blank: Row = { id: "", cells: {}, createdAt: 0, createdBy: null };
this.addRow(g.key || col.type === "checkbox" ? { [col.id]: moveToGroup(blank, col, "", g.key, people) } : {}, true);
this.addRow(
g.key || col.type === "checkbox" ? { [col.id]: moveToGroup(blank, col, "", g.key, people) } : {},
true,
);
});
list.append(add);
list.addEventListener("dragover", (e) => {
@@ -1200,6 +1305,138 @@ export class DatabaseView {
this.body.replaceChildren(board);
}
// ---------------------------------------------------------------- list and gallery
/**
* Rows as lines (list) or cards (gallery), in the view's order, grouped
* when the view groups. A click opens the record; properties are read-only
* here, like on kanban cards.
*/
private drawItems(v: View) {
const l = this.labels;
const gallery = v.type === "gallery";
const rows = viewRows(this.db, v, this.search);
const group = v.groupBy ? this.db.columns.find((c) => c.id === v.groupBy) : undefined;
const groups: Group[] = group
? groupRows(rows, group, l.noValue, l.checked, l.unchecked).filter((g) => g.rows.length || g.key !== "")
: [{ key: "", label: "", rows }];
const title = titleColumn(this.db);
const shown = visibleColumns(this.db, v).filter((c) => c.type !== "title" && c.id !== v.cover);
const cover = gallery ? this.db.columns.find((c) => c.id === v.cover && c.type === "attachment") : undefined;
const ctx = this.ctx();
const props = (r: Row) =>
shown.flatMap((c) => {
if (cellText(r, c) === "" || (c.type === "checkbox" && cellValue(r, c) !== true)) return [];
return [h("span", { class: "dw-db-i__prop", title: c.name }, renderCell(ctx, r, c))];
});
const item = (r: Row) => {
const children: Node[] = [];
if (gallery) {
const src = cover ? coverImage(cellValue(r, cover)) : "";
children.push(
h(
"div",
{ class: src ? "dw-db-i__cover" : "dw-db-i__cover is-empty", "aria-hidden": "true" },
src
? h("img", { src: ctx.files ? ctx.files.resolve(src) : src, alt: "", loading: "lazy", draggable: false })
: null,
),
);
}
children.push(
h("div", { class: "dw-db-i__title" }, renderCell(ctx, r, title)),
h("div", { class: "dw-db-i__props" }, props(r)),
);
const el = h("div", { class: "dw-db-i__item", tabIndex: 0, role: "button", dataset: { row: r.id } }, children);
el.addEventListener("click", (e) => {
// Links and files inside a card open themselves.
if ((e.target as HTMLElement).closest("a")) return;
this.openRow(r.id);
});
el.addEventListener("keydown", (e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
this.openRow(r.id);
}
});
return el;
};
const wrap = h("div", { class: gallery ? "dw-db-i dw-db-i--gallery" : "dw-db-i dw-db-i--list" });
let count = 0;
for (const g of groups) {
const key = `${v.id}:${g.key}`;
const section = h("section", { class: "dw-db-i__group", "aria-label": g.label || undefined });
if (group) {
const open = !this.collapsed.has(key);
const toggle = h(
"button",
{ type: "button", class: "dw-db-t__group", "aria-expanded": String(open) },
icon(open ? "chevron-down" : "chevron-right", 14),
g.key && group.type !== "checkbox" && group.type !== "member" && group.type !== "createdBy"
? h("span", { class: "dw-db-tag", dataset: { color: g.color ?? "gray" } }, g.label)
: h("span", {}, g.label),
h("span", { class: "dw-db-t__count" }, String(g.rows.length)),
);
toggle.addEventListener("click", () => {
if (open) this.collapsed.add(key);
else this.collapsed.delete(key);
this.drawBody();
});
section.append(toggle);
if (!open) {
wrap.append(section);
continue;
}
}
const items = h("div", { class: "dw-db-i__items" });
for (const r of g.rows) {
if (count >= this.limit) break;
count++;
items.append(item(r));
}
if (this.editable && count < this.limit) {
const add = h(
"button",
{ type: "button", class: "dw-db-t__new dw-db-i__new" },
icon("plus", 14),
h("span", {}, l.newRow),
);
add.addEventListener("click", () => {
const cells: Record<string, unknown> = {};
if (group && (g.key || group.type === "checkbox")) {
const blank: Row = { id: "", cells: {}, createdAt: 0, createdBy: null };
cells[group.id] = moveToGroup(
blank,
group,
"",
g.key,
g.rows.flatMap((x) => asPeople(cellValue(x, group))),
);
}
this.addRow(cells, true);
});
items.append(add);
}
section.append(items);
wrap.append(section);
}
const children: Node[] = [wrap];
if (!rows.length) children.push(h("p", { class: "dw-db__empty" }, this.db.rows.length ? l.noMatches : l.noRows));
if (rows.length > count && count >= this.limit) {
const more = h(
"button",
{ type: "button", class: "dw-db__btn dw-db__more" },
`${l.more} (${rows.length - count})`,
);
more.addEventListener("click", () => {
this.limit += PAGE;
this.drawBody();
});
children.push(more);
}
this.body.replaceChildren(...children);
}
// ---------------------------------------------------------------- calendar
private drawCalendar(v: View) {
@@ -1234,15 +1471,24 @@ export class DatabaseView {
h("strong", { class: "dw-db-c__month" }, monthName),
iconButton("chevron-left", l.previousMonth, () => go(-1)),
iconButton("chevron-right", l.nextMonth, () => go(1)),
iconButton("calendar", l.today, () => {
const d = new Date();
this.month = { y: d.getFullYear(), m: d.getMonth() };
this.drawBody();
}, l.today),
iconButton(
"calendar",
l.today,
() => {
const d = new Date();
this.month = { y: d.getFullYear(), m: d.getMonth() };
this.drawBody();
},
l.today,
),
);
const week = days.slice(0, 7).map((d) => {
const [yy, mm, dd] = d.split("-").map(Number);
return h("div", { class: "dw-db-c__wd" }, new Date(yy!, mm! - 1, dd!).toLocaleDateString(this.host.locale, { weekday: "short" }));
return h(
"div",
{ class: "dw-db-c__wd" },
new Date(yy!, mm! - 1, dd!).toLocaleDateString(this.host.locale, { weekday: "short" }),
);
});
const chip = (r: Row) => {
const el = h(
@@ -1283,12 +1529,20 @@ export class DatabaseView {
const inMonth = Number(d.slice(5, 7)) === m + 1;
const cell = h(
"div",
{ class: `dw-db-c__day${inMonth ? "" : " is-out"}${d === today ? " is-today" : ""}`, role: "gridcell", dataset: { day: d } },
{
class: `dw-db-c__day${inMonth ? "" : " is-out"}${d === today ? " is-today" : ""}`,
role: "gridcell",
dataset: { day: d },
},
h("span", { class: "dw-db-c__num" }, String(Number(d.slice(8)))),
(byDay.get(d) ?? []).map(chip),
);
if (this.editable && col.type === "date") {
const add = h("button", { type: "button", class: "dw-db-c__add", "aria-label": `${l.newRow} ${d}`, title: l.newRow }, icon("plus", 12));
const add = h(
"button",
{ type: "button", class: "dw-db-c__add", "aria-label": `${l.newRow} ${d}`, title: l.newRow },
icon("plus", 12),
);
add.addEventListener("click", () => this.addRow({ [col.id]: d }, true));
cell.append(add);
}
@@ -1334,10 +1588,22 @@ const fallbackView: View = {
sorts: [],
groupBy: null,
dateColumn: null,
cover: null,
widths: {},
};
/** The icon of each layout, on tabs and in menus. */
const viewIcons: Record<ViewType, IconName> = {
table: "table",
kanban: "cards",
calendar: "calendar",
list: "list",
gallery: "grid",
};
/** Layouts the Group button applies to (kanban always groups, in its settings). */
const groupedLayouts: ViewType[] = ["table", "list", "gallery"];
function asPeople(v: unknown) {
return Array.isArray(v) ? (v as { id: string; name: string }[]).filter((p) => p && typeof p.id === "string") : [];
}
+125
View File
@@ -1777,6 +1777,131 @@
border-bottom-color: transparent;
}
/* ---- List and gallery views ---- */
.dw-db-i {
display: flex;
flex-direction: column;
gap: 12px;
padding: 8px 0 4px;
}
.dw-db-i__group {
display: flex;
flex-direction: column;
gap: 6px;
}
.dw-db-i__item {
cursor: pointer;
min-width: 0;
}
.dw-db-i__item:focus-visible {
outline: 2px solid var(--color-accent);
outline-offset: 1px;
}
.dw-db-i__title {
font-weight: 600;
min-width: 0;
overflow-wrap: anywhere;
}
.dw-db-i__props {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px 10px;
min-width: 0;
font-size: 13px;
color: var(--color-ink-muted);
}
.dw-db-i__prop {
min-width: 0;
max-width: 100%;
}
.dw-db-i__new {
justify-self: start;
}
/* List: one line per record, its properties on the right. */
.dw-db-i--list .dw-db-i__items {
display: flex;
flex-direction: column;
}
.dw-db-i--list .dw-db-i__item {
display: flex;
align-items: center;
gap: 12px;
padding: 6px 8px;
border-bottom: 1px solid var(--color-line);
border-radius: var(--radius-sm);
}
.dw-db-i--list .dw-db-i__item:hover {
background: var(--color-surface-sunken);
}
.dw-db-i--list .dw-db-i__title {
flex: 1 1 auto;
}
.dw-db-i--list .dw-db-i__props {
flex: 0 1 auto;
justify-content: flex-end;
}
/* Gallery: cards in a grid, with a cover image when the view has one. */
.dw-db-i--gallery .dw-db-i__items {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 12px;
}
.dw-db-i--gallery .dw-db-i__item {
display: flex;
flex-direction: column;
gap: 4px;
overflow: hidden;
padding-bottom: 10px;
border: 1px solid var(--color-line);
border-radius: var(--radius-md);
background: var(--color-surface-raised);
box-shadow: 0 1px 2px rgb(0 0 0 / 0.04);
}
.dw-db-i--gallery .dw-db-i__item:hover {
border-color: var(--color-line-strong);
}
.dw-db-i--gallery .dw-db-i__title,
.dw-db-i--gallery .dw-db-i__props {
padding: 0 10px;
}
.dw-db-i__cover {
aspect-ratio: 16 / 9;
margin-bottom: 6px;
background: var(--color-surface-sunken);
}
.dw-db-i__cover.is-empty {
aspect-ratio: auto;
height: 6px;
}
.dw-db-i__cover img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 0;
}
.dw-db-i--gallery .dw-db-i__new {
min-height: 80px;
justify-content: center;
border: 1px dashed var(--color-line);
border-radius: var(--radius-md);
}
@media (max-width: 640px) {
.dw-db-i--gallery .dw-db-i__items {
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
}
.dw-db-i--list .dw-db-i__item {
flex-wrap: wrap;
gap: 4px 12px;
}
.dw-db-i--list .dw-db-i__props {
justify-content: flex-start;
}
}
/* ---- Kanban view ---- */
.dw-db-k {
display: flex;