Records are bars from the view's date property to an end date property (chosen in the view's settings; without one a bar lasts a day), by days, weeks or months. Dragging a bar moves both dates; its right edge changes the end. Records without a start are listed below, like on the calendar. Bars stop the browser's own drag of the surrounding block. Also fixes the view settings panel: the properties list cleared the whole panel when it drew, so a calendar never showed its date property. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1931 lines
71 KiB
TypeScript
1931 lines
71 KiB
TypeScript
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||
|
||
// Draws a database block: its title, view tabs, toolbar and the active view
|
||
// (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";
|
||
import { closePopover, download, h, icon, iconButton, pickFile, popover, textInput } from "./dom";
|
||
import { fill, typeLabel, viewLabel, type DatabaseLabels } from "./labels";
|
||
import * as p from "./panels";
|
||
import { touchDraggable } from "./touchdrag";
|
||
import {
|
||
cellText,
|
||
cellValue,
|
||
addDays,
|
||
coverImage,
|
||
dateOf,
|
||
daysBetween,
|
||
editableTypes,
|
||
filterOps,
|
||
groupRows,
|
||
isoDay,
|
||
monthGrid,
|
||
moveToGroup,
|
||
timelineScale,
|
||
timelineScales,
|
||
timelineSpan,
|
||
timelineStart,
|
||
titleColumn,
|
||
viewRows,
|
||
viewTypes,
|
||
visibleColumns,
|
||
type Column,
|
||
type DbData,
|
||
type Group,
|
||
type Row,
|
||
type TimelineScale,
|
||
type View,
|
||
type ViewType,
|
||
} from "./model";
|
||
import { relationTargetPanel, rollupPanel } from "./relationui";
|
||
import { isBackRelation } from "./linked";
|
||
|
||
export interface ViewHost extends Omit<DbContext, "db" | "openRow" | "setEditing"> {
|
||
/** Opens a row as a page (peek.ts). */
|
||
openRow: (id: string, rows: string[]) => void;
|
||
undo: () => void;
|
||
redo: () => void;
|
||
/** Shows a short message (copied, imported). */
|
||
notify?: (text: string) => void;
|
||
/** Copies a link to a record; without it the row menu has no "Copy link". */
|
||
copyLink?: (row: string) => void;
|
||
}
|
||
|
||
const PAGE = 200;
|
||
|
||
/** The block's DOM and state; call update() with a new snapshot after every change. */
|
||
export class DatabaseView {
|
||
readonly dom = h("div", { class: "dw-db", dataset: { type: "database" }, contentEditable: "false" });
|
||
private db: DbData;
|
||
private viewId: string | null = null;
|
||
private search = "";
|
||
private editing = 0;
|
||
private pending = false;
|
||
private limit = PAGE;
|
||
private collapsed = new Set<string>();
|
||
/** The selected cell (row id, column id) and the corner of a range, in the table. */
|
||
private sel: { row: string; col: string } | null = null;
|
||
private anchor: { row: string; col: string } | null = null;
|
||
private picked = new Set<string>();
|
||
private month: { y: number; m: number };
|
||
/** The first day the timeline shows ("" = around today), and a zoom kept by people who cannot edit. */
|
||
private tlFrom = "";
|
||
private tlScale: TimelineScale | null = null;
|
||
|
||
private titleEl = h("div", { class: "dw-db__title" });
|
||
private tabs = h("div", { class: "dw-db__tabs", role: "tablist" });
|
||
private tools = h("div", { class: "dw-db__tools" });
|
||
private body = h("div", { class: "dw-db__body" });
|
||
private bulk = h("div", { class: "dw-db__bulk" });
|
||
private searchInput: HTMLInputElement;
|
||
private buttons: Record<"filter" | "sort" | "group" | "props" | "more" | "add" | "search", HTMLButtonElement>;
|
||
|
||
constructor(
|
||
private host: ViewHost,
|
||
db: DbData,
|
||
) {
|
||
this.db = db;
|
||
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.addEventListener("input", () => {
|
||
this.search = this.searchInput.value;
|
||
this.limit = PAGE;
|
||
this.drawBody();
|
||
});
|
||
this.searchInput.addEventListener("keydown", (e) => {
|
||
e.stopPropagation();
|
||
if (e.key === "Escape") {
|
||
this.searchInput.value = "";
|
||
this.search = "";
|
||
this.searchInput.hidden = true;
|
||
this.drawBody();
|
||
}
|
||
});
|
||
this.buttons = {
|
||
search: iconButton("search", l.search, () => {
|
||
this.searchInput.hidden = !this.searchInput.hidden;
|
||
if (!this.searchInput.hidden) this.searchInput.focus();
|
||
}),
|
||
filter: iconButton("filter", l.filter, (e) => this.panel(e, "filter"), l.filter),
|
||
sort: iconButton("sort", l.sort, (e) => this.panel(e, "sort"), l.sort),
|
||
group: iconButton("layers", l.group, (e) => this.panel(e, "group"), l.group),
|
||
props: iconButton("sliders", l.properties, (e) => this.panel(e, "props")),
|
||
more: iconButton("more", l.more, () => this.moreMenu()),
|
||
add: iconButton("plus", l.newRow, () => this.addRow(), l.newRow),
|
||
};
|
||
this.buttons.add.classList.add("dw-db__btn--primary");
|
||
const head = h("div", { class: "dw-db__head" }, this.titleEl);
|
||
const bar = h("div", { class: "dw-db__bar" }, this.tabs, this.tools);
|
||
this.tools.append(
|
||
this.searchInput,
|
||
this.buttons.search,
|
||
this.buttons.filter,
|
||
this.buttons.sort,
|
||
this.buttons.group,
|
||
this.buttons.props,
|
||
this.buttons.more,
|
||
this.buttons.add,
|
||
);
|
||
this.dom.append(head, bar, this.bulk, this.body);
|
||
this.draw();
|
||
}
|
||
|
||
private get labels(): DatabaseLabels {
|
||
return this.host.labels;
|
||
}
|
||
|
||
private get editable() {
|
||
return !!this.host.store;
|
||
}
|
||
|
||
private get view(): View {
|
||
return this.db.views.find((v) => v.id === this.viewId) ?? this.db.views[0] ?? fallbackView;
|
||
}
|
||
|
||
private ctx(): DbContext {
|
||
return {
|
||
...this.host,
|
||
db: this.db,
|
||
openRow: (id) => this.openRow(id),
|
||
setEditing: (on) => {
|
||
this.editing = Math.max(0, this.editing + (on ? 1 : -1));
|
||
if (!this.editing && this.pending) {
|
||
this.pending = false;
|
||
this.draw();
|
||
}
|
||
},
|
||
};
|
||
}
|
||
|
||
/** A new snapshot (a local or remote change) or new rights. */
|
||
update(db: DbData, host?: Partial<ViewHost>) {
|
||
this.db = db;
|
||
if (host) this.host = { ...this.host, ...host };
|
||
if (this.editing) {
|
||
this.pending = true;
|
||
return;
|
||
}
|
||
this.draw();
|
||
}
|
||
|
||
destroy() {
|
||
closePopover();
|
||
}
|
||
|
||
private draw() {
|
||
this.drawTitle();
|
||
this.drawTabs();
|
||
this.drawTools();
|
||
this.drawBody();
|
||
}
|
||
|
||
private drawTitle() {
|
||
const l = this.labels;
|
||
const title = this.db.title;
|
||
if (this.titleEl.querySelector("input") === document.activeElement) return;
|
||
if (!this.editable) {
|
||
this.titleEl.replaceChildren(h("span", { class: title ? "" : "is-empty" }, title || l.untitled));
|
||
return;
|
||
}
|
||
const input = h("input", { class: "dw-db__title-input", placeholder: l.untitled, "aria-label": l.untitled });
|
||
input.value = title;
|
||
input.addEventListener("keydown", (e) => {
|
||
e.stopPropagation();
|
||
if (e.key === "Enter" || e.key === "Escape") input.blur();
|
||
});
|
||
input.addEventListener("change", () => this.host.store?.setTitle(input.value));
|
||
this.titleEl.replaceChildren(input);
|
||
}
|
||
|
||
private drawTabs() {
|
||
const l = this.labels;
|
||
const active = this.view;
|
||
this.tabs.replaceChildren(
|
||
...this.db.views.map((v) => {
|
||
const tab = h(
|
||
"button",
|
||
{
|
||
type: "button",
|
||
class: v.id === active.id ? "dw-db__tab is-active" : "dw-db__tab",
|
||
role: "tab",
|
||
"aria-selected": String(v.id === active.id),
|
||
},
|
||
icon(viewIcons[v.type], 14),
|
||
h("span", {}, v.name || viewLabel(l, v.type)),
|
||
);
|
||
tab.addEventListener("click", () => {
|
||
if (v.id === active.id && this.editable) return this.viewMenu(tab, v);
|
||
this.viewId = v.id;
|
||
this.sel = null;
|
||
this.limit = PAGE;
|
||
this.draw();
|
||
});
|
||
tab.addEventListener("contextmenu", (e) => {
|
||
if (!this.editable) return;
|
||
e.preventDefault();
|
||
this.viewMenu(tab, v);
|
||
});
|
||
return tab;
|
||
}),
|
||
);
|
||
if (this.editable) {
|
||
const add = iconButton("plus", l.addView, () =>
|
||
openBlockMenu(
|
||
add,
|
||
viewTypes.map((t) => ({
|
||
id: t,
|
||
label: viewLabel(l, t),
|
||
icon: viewIcons[t],
|
||
run: () => {
|
||
this.showView(this.host.store!.addView(t, viewLabel(l, t)));
|
||
},
|
||
})),
|
||
l.addView,
|
||
),
|
||
);
|
||
this.tabs.append(add);
|
||
}
|
||
}
|
||
|
||
private drawTools() {
|
||
const v = this.view;
|
||
const b = this.buttons;
|
||
const count = (btn: HTMLButtonElement, n: number) => {
|
||
btn.classList.toggle("is-on", n > 0);
|
||
const span = btn.querySelector("span");
|
||
if (span) span.textContent = n ? `${btn.title} ${n}` : btn.title;
|
||
};
|
||
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 && groupedLayouts.includes(v.type));
|
||
b.group.hidden = v.type === "calendar" || v.type === "timeline";
|
||
b.add.hidden = !this.editable;
|
||
this.drawBulk();
|
||
}
|
||
|
||
private drawBulk() {
|
||
const ids = [...this.picked].filter((id) => this.db.rows.some((r) => r.id === id));
|
||
this.picked = new Set(ids);
|
||
this.bulk.hidden = !ids.length || !this.editable;
|
||
if (this.bulk.hidden) return this.bulk.replaceChildren();
|
||
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("close", l.close, () => {
|
||
this.picked.clear();
|
||
this.draw();
|
||
}),
|
||
);
|
||
}
|
||
|
||
private panel(e: MouseEvent, kind: "filter" | "sort" | "group" | "props") {
|
||
const anchor = e.currentTarget as HTMLElement;
|
||
{
|
||
popover(
|
||
anchor,
|
||
(box) => {
|
||
const ctx = this.ctx();
|
||
// Panels read the current view each time they redraw themselves.
|
||
const view = this.view;
|
||
if (kind === "filter") p.filterPanel(ctx, box, view);
|
||
else if (kind === "sort") p.sortPanel(ctx, box, view);
|
||
else if (kind === "group") p.groupPanel(ctx, box, view);
|
||
else {
|
||
if (view.type === "calendar" || view.type === "timeline") p.datePanel(ctx, box, view);
|
||
if (view.type === "timeline") p.endPanel(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);
|
||
}
|
||
},
|
||
{ class: "dw-db-pop--panel", label: anchor.title, placement: "bottom-end" },
|
||
);
|
||
}
|
||
}
|
||
|
||
private viewMenu(anchor: HTMLElement, v: View) {
|
||
const l = this.labels;
|
||
const store = this.host.store!;
|
||
const actions: BlockAction[] = [
|
||
{
|
||
id: "rename",
|
||
label: l.renameView,
|
||
icon: "pencil",
|
||
run: () => {
|
||
const name = window.prompt(l.viewName, v.name)?.trim();
|
||
if (name) store.updateView(v.id, { name });
|
||
},
|
||
},
|
||
{
|
||
id: "layout",
|
||
label: l.layout,
|
||
icon: "grid",
|
||
children: viewTypes.map((t: ViewType) => ({
|
||
id: t,
|
||
label: viewLabel(l, t),
|
||
icon: t === v.type ? "check" : viewIcons[t],
|
||
run: () => this.setLayout(v, t),
|
||
})),
|
||
},
|
||
{
|
||
id: "duplicate",
|
||
label: l.duplicateView,
|
||
icon: "copy",
|
||
run: () => {
|
||
this.showView(store.duplicateView(v.id, `${v.name || viewLabel(l, v.type)} 2`));
|
||
},
|
||
},
|
||
];
|
||
if (this.db.views.length > 1) {
|
||
actions.push({
|
||
id: "delete",
|
||
label: l.deleteView,
|
||
icon: "trash",
|
||
danger: true,
|
||
run: () => store.deleteView(v.id),
|
||
});
|
||
}
|
||
openBlockMenu(anchor, actions, l.layout);
|
||
}
|
||
|
||
private showView(id: string | null) {
|
||
if (!id) return;
|
||
this.viewId = id;
|
||
this.sel = null;
|
||
this.limit = PAGE;
|
||
this.draw();
|
||
}
|
||
|
||
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 === "gallery" && !v.cover) patch.cover = cols.find((c) => c.type === "attachment")?.id ?? null;
|
||
const dated = type === "calendar" || type === "timeline";
|
||
if (dated && !v.dateColumn) patch.dateColumn = cols.find((c) => c.type === "date")?.id ?? null;
|
||
if (type === "timeline" && !v.endColumn) {
|
||
const start = patch.dateColumn ?? v.dateColumn;
|
||
patch.endColumn = cols.find((c) => c.type === "date" && c.id !== start)?.id ?? null;
|
||
}
|
||
if (dated && !patch.dateColumn && !v.dateColumn && this.host.store) {
|
||
patch.dateColumn = this.host.store.addColumn("date", this.labels.typeDate);
|
||
}
|
||
this.host.store?.updateView(v.id, patch);
|
||
}
|
||
|
||
private moreMenu() {
|
||
const l = this.labels;
|
||
const v = this.view;
|
||
const actions: BlockAction[] = [
|
||
{
|
||
id: "csv",
|
||
label: l.exportCsv,
|
||
icon: "download",
|
||
run: () => {
|
||
const cols = visibleColumns(this.db, v);
|
||
const name = (this.db.title || l.untitled).replace(/[\\/:*?"<>|]+/g, " ").trim();
|
||
download(`${name}.csv`, `\uFEFF${toCSV(this.db, cols, viewRows(this.db, v, this.search))}`, "text/csv");
|
||
},
|
||
},
|
||
];
|
||
if (this.editable) {
|
||
actions.push({ id: "import", label: l.importCsv, icon: "upload", run: () => void this.importCsv() });
|
||
actions.push({ id: "view", label: l.layout, icon: "grid", run: () => this.viewMenu(this.buttons.more, v) });
|
||
}
|
||
openBlockMenu(this.buttons.more, actions, l.more);
|
||
}
|
||
|
||
/** Adds a CSV file's rows; columns are matched by name and missing ones added. */
|
||
private async importCsv() {
|
||
const store = this.host.store;
|
||
const file = await pickFile(".csv,text/csv,.tsv,text/tab-separated-values");
|
||
if (!store || !file) return;
|
||
const text = await file.text();
|
||
const sep = file.name.endsWith(".tsv") ? "\t" : ",";
|
||
const lines = parseDelimited(text, sep).filter((r) => r.some((f) => f.trim()));
|
||
if (lines.length < 2) return;
|
||
store.tx(() => {
|
||
if (this.db.rows.every((r) => !cellText(r, titleColumn(this.db)))) {
|
||
// An empty database takes the file's columns and guessed types.
|
||
const parsed = fromCSV(text, sep);
|
||
store.deleteRows(this.db.rows.map((r) => r.id));
|
||
const title = titleColumn(this.db);
|
||
const [first, ...rest] = parsed.columns;
|
||
const ids = new Map<string, string>();
|
||
if (first) {
|
||
store.renameColumn(title.id, first.name);
|
||
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",
|
||
);
|
||
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])),
|
||
),
|
||
);
|
||
this.host.notify?.(fill(this.labels.imported, parsed.rows.length));
|
||
return;
|
||
}
|
||
const { index, missing } = matchHeader(lines[0]!, this.db.columns);
|
||
const added = new Map(missing.map((name) => [name, store.addColumn("text", name)]));
|
||
const cols = lines[0]!.map((name, i): Column | null => {
|
||
const c = index[i];
|
||
if (c) return c;
|
||
const id = added.get(name.trim());
|
||
return id ? { id, name, type: "text" } : null;
|
||
});
|
||
const options = new Map(this.db.columns.map((c) => [c.id, [...(c.options ?? [])]]));
|
||
const rows = lines.slice(1).map((r) => {
|
||
const cells: Record<string, unknown> = {};
|
||
cols.forEach((c, i) => {
|
||
if (!c) return;
|
||
const val = parseCell(r[i] ?? "", c, options.get(c.id) ?? []);
|
||
if (val !== null) cells[c.id] = val;
|
||
});
|
||
return cells;
|
||
});
|
||
for (const c of this.db.columns) {
|
||
const o = options.get(c.id);
|
||
if (o && o.length !== (c.options?.length ?? 0)) store.setOptions(c.id, o);
|
||
}
|
||
store.addRows(rows);
|
||
this.host.notify?.(fill(this.labels.imported, rows.length));
|
||
});
|
||
}
|
||
|
||
private addRow(cells: Record<string, unknown> = {}, open = false) {
|
||
const store = this.host.store;
|
||
if (!store) return;
|
||
const v = this.view;
|
||
// A new row matches the view's simple filters, so it does not vanish.
|
||
for (const f of v.filters) {
|
||
const col = this.db.columns.find((c) => c.id === f.column);
|
||
if (!col || f.column in cells) continue;
|
||
if (f.op === "is" && (col.type === "select" || col.type === "text") && f.value) cells[col.id] = f.value;
|
||
if (f.op === "contains" && col.type === "multiSelect" && f.value) cells[col.id] = [f.value];
|
||
if (f.op === "checked") cells[col.id] = true;
|
||
}
|
||
const id = store.addRow(cells);
|
||
if (open || v.type !== "table") this.openRow(id);
|
||
else {
|
||
this.sel = { row: id, col: titleColumn(this.db).id };
|
||
queueMicrotask(() => this.startEdit());
|
||
}
|
||
}
|
||
|
||
private openRow(id: string) {
|
||
const rows = viewRows(this.db, this.view, this.search).map((r) => r.id);
|
||
this.host.openRow(id, rows);
|
||
}
|
||
|
||
private drawBody() {
|
||
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 if (v.type === "timeline") this.drawTimeline(v);
|
||
else this.drawTable(v);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- table
|
||
|
||
private tableRows: Row[] = [];
|
||
private tableCols: Column[] = [];
|
||
private grid: HTMLElement | null = null;
|
||
|
||
private drawTable(v: View) {
|
||
const l = this.labels;
|
||
const cols = visibleColumns(this.db, v);
|
||
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 }];
|
||
this.tableCols = cols;
|
||
this.tableRows = [];
|
||
const editable = this.editable;
|
||
const sorted = v.sorts.length > 0;
|
||
|
||
const colgroup = h(
|
||
"colgroup",
|
||
{},
|
||
h("col", { class: "dw-db-t__gutter-col" }),
|
||
cols.map((c) => h("col", { style: { width: `${v.widths[c.id] ?? (c.type === "title" ? 240 : 160)}px` } })),
|
||
editable ? h("col", { class: "dw-db-t__add-col" }) : null,
|
||
);
|
||
const head = h(
|
||
"tr",
|
||
{},
|
||
h("th", { class: "dw-db-t__gutter", "aria-hidden": "true" }),
|
||
cols.map((c, i) => this.headerCell(c, i, colgroup.children[i + 1] as HTMLElement)),
|
||
editable
|
||
? h(
|
||
"th",
|
||
{ class: "dw-db-t__add" },
|
||
iconButton("plus", l.addColumn, (e) => this.addColumnMenu(e.currentTarget as HTMLElement)),
|
||
)
|
||
: null,
|
||
);
|
||
const table = h("table", { class: "dw-db-t" }, colgroup, h("thead", {}, head));
|
||
let shown = 0;
|
||
for (const g of groups) {
|
||
const tbody = h("tbody", {});
|
||
const key = `${v.id}:${g.key}`;
|
||
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();
|
||
});
|
||
tbody.append(h("tr", { class: "dw-db-t__group-row" }, h("td", { colSpan: cols.length + 2 }, toggle)));
|
||
if (!open) {
|
||
table.append(tbody);
|
||
continue;
|
||
}
|
||
}
|
||
for (const r of g.rows) {
|
||
if (shown >= this.limit) break;
|
||
shown++;
|
||
this.tableRows.push(r);
|
||
tbody.append(this.tableRow(r, cols, editable && !sorted));
|
||
}
|
||
if (editable && shown < this.limit) {
|
||
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))),
|
||
);
|
||
else if (group?.type === "checkbox") cells[group.id] = g.key === "true";
|
||
this.addRow(cells);
|
||
});
|
||
tbody.append(h("tr", { class: "dw-db-t__new-row" }, h("td", { colSpan: cols.length + 2 }, add)));
|
||
}
|
||
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,
|
||
);
|
||
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})`,
|
||
);
|
||
more.addEventListener("click", () => {
|
||
this.limit += PAGE;
|
||
this.drawBody();
|
||
});
|
||
children.push(more);
|
||
}
|
||
this.grid = wrap;
|
||
wrap.addEventListener("keydown", (e) => this.onGridKey(e));
|
||
wrap.addEventListener("copy", (e) => this.onCopy(e));
|
||
wrap.addEventListener("paste", (e) => this.onPaste(e));
|
||
const scroll = this.body.querySelector(".dw-db-t__wrap")?.scrollLeft ?? 0;
|
||
const hadFocus = this.body.contains(document.activeElement);
|
||
this.body.replaceChildren(...children);
|
||
wrap.scrollLeft = scroll;
|
||
this.markSelection();
|
||
if (hadFocus && this.sel) wrap.focus({ preventScroll: true });
|
||
}
|
||
|
||
private headerCell(c: Column, index: number, colEl: HTMLElement): HTMLElement {
|
||
const l = this.labels;
|
||
const name = h("span", { class: "dw-db-t__name" }, c.name || typeLabel(l, c.type));
|
||
const btn = h(
|
||
"button",
|
||
{ type: "button", class: "dw-db-t__head", "aria-haspopup": "menu", draggable: this.editable },
|
||
icon(typeIcons[c.type], 14),
|
||
name,
|
||
);
|
||
const th = h("th", { dataset: { col: c.id } }, btn);
|
||
btn.addEventListener("click", () => this.columnMenu(btn, c, index));
|
||
if (this.editable) {
|
||
btn.addEventListener("dragstart", (e) => {
|
||
e.dataTransfer?.setData("application/x-docwell-column", c.id);
|
||
if (e.dataTransfer) e.dataTransfer.effectAllowed = "move";
|
||
});
|
||
th.addEventListener("dragover", (e) => {
|
||
if (e.dataTransfer?.types.includes("application/x-docwell-column")) {
|
||
e.preventDefault();
|
||
th.classList.add("is-drop");
|
||
}
|
||
});
|
||
th.addEventListener("dragleave", () => th.classList.remove("is-drop"));
|
||
th.addEventListener("drop", (e) => {
|
||
th.classList.remove("is-drop");
|
||
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),
|
||
);
|
||
});
|
||
// 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" });
|
||
grip.addEventListener("pointerdown", (e) => {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
const start = e.clientX;
|
||
const from = colEl.getBoundingClientRect().width || 160;
|
||
let width = from;
|
||
grip.setPointerCapture(e.pointerId);
|
||
const move = (ev: PointerEvent) => {
|
||
width = Math.max(72, Math.round(from + ev.clientX - start));
|
||
colEl.style.width = `${width}px`;
|
||
};
|
||
const up = () => {
|
||
grip.removeEventListener("pointermove", move);
|
||
grip.removeEventListener("pointerup", up);
|
||
const v = this.view;
|
||
if (width !== from) this.host.store?.updateView(v.id, { widths: { ...v.widths, [c.id]: width } });
|
||
};
|
||
grip.addEventListener("pointermove", move);
|
||
grip.addEventListener("pointerup", up);
|
||
});
|
||
th.append(grip);
|
||
}
|
||
return th;
|
||
}
|
||
|
||
private columnMenu(anchor: HTMLElement, c: Column, index: number) {
|
||
const l = this.labels;
|
||
const store = this.host.store;
|
||
const v = this.view;
|
||
const sortBy = (desc: boolean): BlockAction => ({
|
||
id: desc ? "desc" : "asc",
|
||
label: desc ? l.sortDescending : l.sortAscending,
|
||
icon: desc ? "arrow-down" : "arrow-up",
|
||
run: () => store?.updateView(v.id, { sorts: [{ column: c.id, desc }] }),
|
||
});
|
||
if (!store) {
|
||
openBlockMenu(anchor, [sortBy(false), sortBy(true)], c.name);
|
||
return;
|
||
}
|
||
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) }];
|
||
if (c.type !== "title") {
|
||
actions.push({
|
||
id: "type",
|
||
label: l.type,
|
||
icon: typeIcons[c.type],
|
||
children: editableTypes.map((t) => ({
|
||
id: t,
|
||
label: typeLabel(l, t),
|
||
icon: t === c.type ? "check" : typeIcons[t],
|
||
run: () => {
|
||
store.changeType(c.id, t);
|
||
// A relation needs its database, a rollup what to calculate.
|
||
if (t === "relation" || t === "rollup") queueMicrotask(() => this.linkSettings(anchor, c.id));
|
||
},
|
||
})),
|
||
});
|
||
}
|
||
if (c.type === "relation")
|
||
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(sortBy(false), sortBy(true), {
|
||
id: "filter",
|
||
label: l.filterBy,
|
||
icon: "filter",
|
||
run: () => {
|
||
store.updateView(v.id, { filters: [...v.filters, { column: c.id, op: filterOps(c.type)[0]! }] });
|
||
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] }),
|
||
});
|
||
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 (c.type !== "title") {
|
||
actions.push(
|
||
{ id: "duplicate", label: l.duplicate, icon: "copy", run: () => store.duplicateColumn(c.id, `${c.name} 2`) },
|
||
{ id: "delete", label: l.deleteColumn, icon: "trash", danger: true, run: () => store.deleteColumn(c.id) },
|
||
);
|
||
}
|
||
void index;
|
||
openBlockMenu(anchor, actions, c.name || typeLabel(l, c.type));
|
||
}
|
||
|
||
/** Opens the settings of a relation or rollup column. */
|
||
private linkSettings(anchor: HTMLElement, id: string) {
|
||
const col = this.db.columns.find((x) => x.id === id);
|
||
const target = anchor.isConnected ? anchor : (this.dom.querySelector(`[data-col="${id}"]`) ?? this.dom);
|
||
if (col?.type === "relation") relationTargetPanel(this.ctx(), target, col);
|
||
else if (col?.type === "rollup") rollupPanel(this.ctx(), target, col);
|
||
}
|
||
|
||
private insertColumn(at: number) {
|
||
const store = this.host.store;
|
||
if (!store) return;
|
||
const id = store.addColumn("text", this.labels.typeText, at);
|
||
queueMicrotask(() => {
|
||
const col = this.db.columns.find((c) => c.id === id);
|
||
if (col) this.renameColumn(col);
|
||
});
|
||
}
|
||
|
||
private addColumnMenu(anchor: HTMLElement) {
|
||
const l = this.labels;
|
||
openBlockMenu(
|
||
anchor,
|
||
editableTypes.map((t) => ({
|
||
id: t,
|
||
label: typeLabel(l, t),
|
||
icon: typeIcons[t],
|
||
run: () => {
|
||
const id = this.host.store?.addColumn(t, typeLabel(l, t));
|
||
queueMicrotask(() => {
|
||
const col = this.db.columns.find((c) => c.id === id);
|
||
if (col) this.renameColumn(col);
|
||
});
|
||
},
|
||
})),
|
||
l.addColumn,
|
||
);
|
||
}
|
||
|
||
/** Turns a column's header into a name field. */
|
||
private renameColumn(c: Column) {
|
||
const th = this.body.querySelector<HTMLElement>(`th[data-col="${CSS.escape(c.id)}"]`);
|
||
const store = this.host.store;
|
||
if (!store) return;
|
||
if (!th) {
|
||
const name = window.prompt(this.labels.columnName, c.name)?.trim();
|
||
if (name) store.renameColumn(c.id, name);
|
||
return;
|
||
}
|
||
const ctx = this.ctx();
|
||
ctx.setEditing(true);
|
||
const input = textInput(c.name, {
|
||
class: "dw-db-t__name-input",
|
||
label: this.labels.columnName,
|
||
onCommit: (name) => {
|
||
if (name.trim() && name.trim() !== c.name) store.renameColumn(c.id, name.trim());
|
||
ctx.setEditing(false);
|
||
this.drawBody();
|
||
},
|
||
onCancel: () => {
|
||
ctx.setEditing(false);
|
||
this.drawBody();
|
||
},
|
||
});
|
||
th.replaceChildren(input);
|
||
input.focus();
|
||
input.select();
|
||
}
|
||
|
||
private tableRow(r: Row, cols: Column[], movable: boolean): HTMLElement {
|
||
const l = this.labels;
|
||
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),
|
||
});
|
||
check.addEventListener("change", () => {
|
||
if (check.checked) this.picked.add(r.id);
|
||
else this.picked.delete(r.id);
|
||
tr.classList.toggle("is-picked", check.checked);
|
||
this.drawBulk();
|
||
});
|
||
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),
|
||
);
|
||
grip.addEventListener("dragstart", (e) => {
|
||
e.dataTransfer?.setData("application/x-docwell-row", r.id);
|
||
if (e.dataTransfer) e.dataTransfer.effectAllowed = "move";
|
||
e.dataTransfer?.setDragImage(tr, 0, 0);
|
||
});
|
||
gutter.append(grip);
|
||
tr.addEventListener("dragover", (e) => {
|
||
if (!e.dataTransfer?.types.includes("application/x-docwell-row")) return;
|
||
e.preventDefault();
|
||
const below = e.clientY > tr.getBoundingClientRect().top + tr.offsetHeight / 2;
|
||
tr.classList.toggle("is-drop-below", below);
|
||
tr.classList.toggle("is-drop-above", !below);
|
||
});
|
||
tr.addEventListener("dragleave", () => tr.classList.remove("is-drop-below", "is-drop-above"));
|
||
tr.addEventListener("drop", (e) => {
|
||
const below = tr.classList.contains("is-drop-below");
|
||
tr.classList.remove("is-drop-below", "is-drop-above");
|
||
const id = e.dataTransfer?.getData("application/x-docwell-row");
|
||
if (!id || id === r.id || !this.host.store) return;
|
||
e.preventDefault();
|
||
this.moveRowBeside(id, r.id, below);
|
||
});
|
||
// A finger drags the row by its grip (touchdrag.ts).
|
||
let mark: HTMLElement | null = null;
|
||
const unmark = () => mark?.classList.remove("is-drop-below", "is-drop-above");
|
||
const rowAt = (t: Element | null) => {
|
||
const at = t?.closest<HTMLElement>("tr[data-row]");
|
||
return at && at.parentElement === tr.parentElement && at !== tr ? at : null;
|
||
};
|
||
const below = (at: HTMLElement, y: number) => y > at.getBoundingClientRect().top + at.offsetHeight / 2;
|
||
touchDraggable(grip, {
|
||
source: tr,
|
||
ghost: () => h("div", { class: "dw-db-ghost--row" }, cellText(r, titleColumn(this.db)) || l.untitledRow),
|
||
over: (t, _x, y) => {
|
||
unmark();
|
||
mark = rowAt(t);
|
||
if (mark) mark.classList.add(below(mark, y) ? "is-drop-below" : "is-drop-above");
|
||
},
|
||
drop: (t, _x, y) => {
|
||
const at = rowAt(t);
|
||
if (at?.dataset.row) this.moveRowBeside(r.id, at.dataset.row, below(at, y));
|
||
},
|
||
end: unmark,
|
||
hold: () => this.rowMenu(tr, r),
|
||
});
|
||
}
|
||
}
|
||
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),
|
||
);
|
||
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),
|
||
);
|
||
open.addEventListener("click", (e) => {
|
||
e.stopPropagation();
|
||
this.openRow(r.id);
|
||
});
|
||
td.append(open);
|
||
}
|
||
td.addEventListener("mousedown", (e) => {
|
||
if ((e.target as HTMLElement).closest("input, button, a")) return;
|
||
if (e.shiftKey && this.sel) this.anchor = this.anchor ?? this.sel;
|
||
else this.anchor = null;
|
||
this.sel = { row: r.id, col: c.id };
|
||
if (!e.shiftKey) this.anchor = null;
|
||
this.markSelection();
|
||
// Inside the page's contenteditable the browser would leave focus where it was.
|
||
e.preventDefault();
|
||
this.grid?.focus({ preventScroll: true });
|
||
});
|
||
let touch = false;
|
||
td.addEventListener("pointerdown", (e) => (touch = e.pointerType === "touch"));
|
||
td.addEventListener("click", (e) => {
|
||
if ((e.target as HTMLElement).closest("input, button, a") || e.shiftKey) return;
|
||
// A phone has no keyboard to type into a selected cell: a tap edits it.
|
||
if (c.type === "checkbox" || touch) this.startEdit();
|
||
});
|
||
td.addEventListener("dblclick", () => this.startEdit());
|
||
tr.append(td);
|
||
}
|
||
if (this.editable) tr.append(h("td", { class: "dw-db-t__add" }));
|
||
tr.addEventListener("contextmenu", (e) => {
|
||
if (!this.editable && !this.host.copyLink) return;
|
||
e.preventDefault();
|
||
this.rowMenu(tr, r);
|
||
});
|
||
return tr;
|
||
}
|
||
|
||
/** Moves record id next to record beside in the database's own order. */
|
||
private moveRowBeside(id: string, beside: string, below: boolean) {
|
||
const store = this.host.store;
|
||
if (!store || id === beside) return;
|
||
const from = store.rowIndex(id);
|
||
let to = store.rowIndex(beside) + (below ? 1 : 0);
|
||
if (from < to) to--;
|
||
store.moveRow(id, to);
|
||
}
|
||
|
||
private rowMenu(anchor: HTMLElement, r: Row) {
|
||
const l = this.labels;
|
||
const store = this.host.store;
|
||
const copy = this.host.copyLink;
|
||
const actions: BlockAction[] = [{ id: "open", label: l.openRow, icon: "open", run: () => this.openRow(r.id) }];
|
||
if (copy) actions.push({ id: "link", label: l.copyLink, icon: "link", run: () => copy(r.id) });
|
||
if (store) {
|
||
const i = store.rowIndex(r.id);
|
||
actions.push(
|
||
{ id: "above", label: l.insertAbove, icon: "arrow-up", run: () => store.addRow({}, i) },
|
||
{ id: "below", label: l.insertBelow, icon: "arrow-down", run: () => store.addRow({}, i + 1) },
|
||
{ id: "duplicate", label: l.duplicateRow, icon: "copy", run: () => store.duplicateRow(r.id) },
|
||
{ id: "delete", label: l.deleteRow, icon: "trash", danger: true, run: () => store.deleteRows([r.id]) },
|
||
);
|
||
}
|
||
openBlockMenu(anchor, actions, l.openRow);
|
||
}
|
||
|
||
/** The (row, column) indexes of the selection's rectangle in the drawn table. */
|
||
private range(): { r0: number; r1: number; c0: number; c1: number } | null {
|
||
if (!this.sel) return null;
|
||
const ri = (id: string) => this.tableRows.findIndex((r) => r.id === id);
|
||
const ci = (id: string) => this.tableCols.findIndex((c) => c.id === id);
|
||
const a = this.anchor ?? this.sel;
|
||
const [ra, rb, ca, cb] = [ri(a.row), ri(this.sel.row), ci(a.col), ci(this.sel.col)];
|
||
if (rb < 0 || cb < 0) return null;
|
||
const r0 = ra < 0 ? rb : ra;
|
||
const c0 = ca < 0 ? cb : ca;
|
||
return { r0: Math.min(r0, rb), r1: Math.max(r0, rb), c0: Math.min(c0, cb), c1: Math.max(c0, cb) };
|
||
}
|
||
|
||
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");
|
||
const rg = this.range();
|
||
if (!rg || !this.sel) return;
|
||
for (let r = rg.r0; r <= rg.r1; r++) {
|
||
for (let c = rg.c0; c <= rg.c1; c++) {
|
||
this.cellEl(this.tableRows[r]!.id, this.tableCols[c]!.id)?.classList.add("is-in-range");
|
||
}
|
||
}
|
||
const el = this.cellEl(this.sel.row, this.sel.col);
|
||
el?.classList.add("is-selected");
|
||
el?.scrollIntoView({ block: "nearest", inline: "nearest" });
|
||
}
|
||
|
||
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
|
||
);
|
||
}
|
||
|
||
private startEdit(initial?: string) {
|
||
if (!this.sel || !this.host.store) return;
|
||
const r = this.db.rows.find((x) => x.id === this.sel!.row);
|
||
const c = this.db.columns.find((x) => x.id === this.sel!.col);
|
||
const el = this.cellEl(this.sel.row, this.sel.col);
|
||
if (!r || !c || !el) return;
|
||
editCell(this.ctx(), el, r, c, {
|
||
initial,
|
||
onDone: (move) => {
|
||
if (move) this.moveSel(move === "down" ? 1 : 0, move === "right" ? 1 : move === "left" ? -1 : 0, false);
|
||
this.drawBody();
|
||
this.grid?.focus({ preventScroll: true });
|
||
},
|
||
});
|
||
}
|
||
|
||
private moveSel(dr: number, dc: number, extend: boolean) {
|
||
const rows = this.tableRows;
|
||
const cols = this.tableCols;
|
||
if (!rows.length || !cols.length) return;
|
||
if (!this.sel) {
|
||
this.sel = { row: rows[0]!.id, col: cols[0]!.id };
|
||
return this.markSelection();
|
||
}
|
||
if (extend) this.anchor = this.anchor ?? { ...this.sel };
|
||
else this.anchor = null;
|
||
const r = Math.max(0, Math.min(rows.length - 1, rows.findIndex((x) => x.id === this.sel!.row) + dr));
|
||
const c = Math.max(0, Math.min(cols.length - 1, cols.findIndex((x) => x.id === this.sel!.col) + dc));
|
||
this.sel = { row: rows[r]!.id, col: cols[c]!.id };
|
||
this.markSelection();
|
||
}
|
||
|
||
private onGridKey(e: KeyboardEvent) {
|
||
if ((e.target as HTMLElement).closest("input, select, textarea")) return;
|
||
const mod = e.ctrlKey || e.metaKey;
|
||
if (mod && e.key.toLowerCase() === "z") {
|
||
e.preventDefault();
|
||
return e.shiftKey ? this.host.redo() : this.host.undo();
|
||
}
|
||
if (mod && e.key.toLowerCase() === "y") {
|
||
e.preventDefault();
|
||
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 step = arrows[e.key];
|
||
if (step) {
|
||
e.preventDefault();
|
||
return this.moveSel(step[0], step[1], e.shiftKey);
|
||
}
|
||
if (!this.sel) return;
|
||
if (e.key === "Tab") {
|
||
e.preventDefault();
|
||
return this.moveSel(0, e.shiftKey ? -1 : 1, false);
|
||
}
|
||
if (e.key === "Escape") {
|
||
this.sel = null;
|
||
this.anchor = null;
|
||
this.markSelection();
|
||
return;
|
||
}
|
||
if (e.key === "Enter" || e.key === "F2") {
|
||
e.preventDefault();
|
||
return this.startEdit();
|
||
}
|
||
if (e.key === " ") {
|
||
e.preventDefault();
|
||
const c = this.db.columns.find((x) => x.id === this.sel!.col);
|
||
if (c?.type === "title") return this.openRow(this.sel.row);
|
||
return this.startEdit();
|
||
}
|
||
if ((e.key === "Delete" || e.key === "Backspace") && this.host.store) {
|
||
e.preventDefault();
|
||
const rg = this.range();
|
||
if (!rg) return;
|
||
const changes = [];
|
||
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 });
|
||
}
|
||
}
|
||
this.host.store.setCells(changes);
|
||
return;
|
||
}
|
||
if (e.key.length === 1 && this.host.store) {
|
||
const c = this.db.columns.find((x) => x.id === this.sel!.col);
|
||
if (c && (inlineTypes.includes(c.type) || c.type === "select" || c.type === "multiSelect")) {
|
||
e.preventDefault();
|
||
this.startEdit(e.key);
|
||
}
|
||
}
|
||
}
|
||
|
||
/** Copies the selected cells as tab-separated text, which spreadsheets paste as cells. */
|
||
private onCopy(e: ClipboardEvent) {
|
||
if ((e.target as HTMLElement).closest("input, textarea")) return;
|
||
const rg = this.range();
|
||
if (!rg || !e.clipboardData) return;
|
||
e.preventDefault();
|
||
const lines: string[][] = [];
|
||
for (let r = rg.r0; r <= rg.r1; r++) {
|
||
const line: string[] = [];
|
||
for (let c = rg.c0; c <= rg.c1; c++) line.push(cellText(this.tableRows[r]!, this.tableCols[c]!));
|
||
lines.push(line);
|
||
}
|
||
e.clipboardData.setData("text/plain", formatDelimited(lines, "\t"));
|
||
this.host.notify?.(fill(this.labels.copyNotice, (rg.r1 - rg.r0 + 1) * (rg.c1 - rg.c0 + 1)));
|
||
}
|
||
|
||
/** Pastes tab-separated text from a spreadsheet at the selected cell, adding rows as needed. */
|
||
private onPaste(e: ClipboardEvent) {
|
||
if ((e.target as HTMLElement).closest("input, textarea")) return;
|
||
const store = this.host.store;
|
||
const text = e.clipboardData?.getData("text/plain");
|
||
if (!store || !text || !this.sel) return;
|
||
e.preventDefault();
|
||
const lines = parseDelimited(text.replace(/\r?\n$/, ""), text.includes("\t") ? "\t" : "\t");
|
||
const r0 = this.tableRows.findIndex((r) => r.id === this.sel!.row);
|
||
const c0 = this.tableCols.findIndex((c) => c.id === this.sel!.col);
|
||
if (r0 < 0 || c0 < 0) return;
|
||
const options = new Map(this.db.columns.map((c) => [c.id, [...(c.options ?? [])]]));
|
||
const changes: { row: string; col: string; value: unknown }[] = [];
|
||
const extra: Record<string, unknown>[] = [];
|
||
lines.forEach((line, i) => {
|
||
const row = this.tableRows[r0 + i];
|
||
const cells: Record<string, unknown> = {};
|
||
line.forEach((field, j) => {
|
||
const col = this.tableCols[c0 + j];
|
||
if (!col || readOnlyTypes.includes(col.type) || isBackRelation(col)) return;
|
||
const value = parseCell(field, col, options.get(col.id) ?? []);
|
||
if (row) changes.push({ row: row.id, col: col.id, value });
|
||
else if (value !== null) cells[col.id] = value;
|
||
});
|
||
if (!row) extra.push(cells);
|
||
});
|
||
store.tx(() => {
|
||
for (const c of this.db.columns) {
|
||
const o = options.get(c.id);
|
||
if (o && o.length !== (c.options?.length ?? 0)) store.setOptions(c.id, o);
|
||
}
|
||
store.setCells(changes);
|
||
if (extra.length) store.addRows(extra);
|
||
});
|
||
}
|
||
|
||
// ---------------------------------------------------------------- kanban
|
||
|
||
private drawKanban(v: View) {
|
||
const l = this.labels;
|
||
const col = this.db.columns.find((c) => c.id === v.groupBy);
|
||
if (!col) {
|
||
this.body.replaceChildren(h("p", { class: "dw-db__empty" }, l.noGroupColumn));
|
||
return;
|
||
}
|
||
const rows = viewRows(this.db, v, this.search);
|
||
const groups = groupRows(rows, col, l.noValue, l.checked, l.unchecked);
|
||
const shown = visibleColumns(this.db, v).filter((c) => c.type !== "title" && c.id !== col.id);
|
||
const title = titleColumn(this.db);
|
||
const people = rows.flatMap((r) => asPeople(cellValue(r, col)));
|
||
const board = h("div", { class: "dw-db-k" });
|
||
// A card dropped into the column of group "to", before card "before" if any.
|
||
const dropCard = (row: string, from: string, to: string, before?: string) => {
|
||
const store = this.host.store;
|
||
const r = this.db.rows.find((x) => x.id === row);
|
||
if (!store || !r) return;
|
||
store.tx(() => {
|
||
if (from !== to) store.setCell(row, col.id, moveToGroup(r, col, from, to, people));
|
||
if (before && before !== row && !v.sorts.length) {
|
||
const fromIndex = store.rowIndex(row);
|
||
let at = store.rowIndex(before);
|
||
if (fromIndex < at) at--;
|
||
store.moveRow(row, at);
|
||
}
|
||
});
|
||
};
|
||
for (const g of groups) {
|
||
if (!g.key && !g.rows.length && col.type !== "checkbox" && (col.options?.length ?? 0) > 0) continue;
|
||
const list = h("div", { class: "dw-db-k__cards", dataset: { group: g.key } });
|
||
const head = h(
|
||
"div",
|
||
{ class: "dw-db-k__head" },
|
||
g.key && col.type !== "checkbox" && col.type !== "member" && col.type !== "createdBy"
|
||
? h("span", { class: "dw-db-tag", dataset: { color: g.color ?? "gray" } }, g.label)
|
||
: h("span", { class: "dw-db-k__label" }, g.label),
|
||
h("span", { class: "dw-db-t__count" }, String(g.rows.length)),
|
||
);
|
||
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 },
|
||
},
|
||
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 [];
|
||
return [h("div", { class: "dw-db-k__prop", title: c.name }, renderCell(this.ctx(), r, c))];
|
||
}),
|
||
);
|
||
card.addEventListener("click", () => this.openRow(r.id));
|
||
card.addEventListener("keydown", (e) => {
|
||
if (e.key === "Enter" || e.key === " ") {
|
||
e.preventDefault();
|
||
this.openRow(r.id);
|
||
}
|
||
});
|
||
card.addEventListener("dragstart", (e) => {
|
||
e.dataTransfer?.setData("application/x-docwell-card", JSON.stringify({ row: r.id, from: g.key }));
|
||
if (e.dataTransfer) e.dataTransfer.effectAllowed = "move";
|
||
card.classList.add("is-dragging");
|
||
});
|
||
card.addEventListener("dragend", () => card.classList.remove("is-dragging"));
|
||
if (card.draggable) {
|
||
// A finger drags the card by a grip, shown on touch screens only.
|
||
const grip = h("span", { class: "dw-db-k__grip", "aria-hidden": "true" }, icon("grip", 14));
|
||
card.append(grip);
|
||
let mark: HTMLElement | null = null;
|
||
const listAt = (t: Element | null) => {
|
||
const at = t?.closest<HTMLElement>(".dw-db-k__cards");
|
||
return at && board.contains(at) ? at : null;
|
||
};
|
||
touchDraggable(grip, {
|
||
source: card,
|
||
ghost: () => card.cloneNode(true) as HTMLElement,
|
||
over: (t) => {
|
||
mark?.classList.remove("is-drop");
|
||
mark = listAt(t);
|
||
mark?.classList.add("is-drop");
|
||
},
|
||
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);
|
||
},
|
||
end: () => mark?.classList.remove("is-drop"),
|
||
});
|
||
}
|
||
list.append(card);
|
||
}
|
||
if (this.editable) {
|
||
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,
|
||
);
|
||
});
|
||
list.append(add);
|
||
list.addEventListener("dragover", (e) => {
|
||
if (!e.dataTransfer?.types.includes("application/x-docwell-card")) return;
|
||
e.preventDefault();
|
||
list.classList.add("is-drop");
|
||
});
|
||
list.addEventListener("dragleave", (e) => {
|
||
if (!list.contains(e.relatedTarget as Node)) list.classList.remove("is-drop");
|
||
});
|
||
list.addEventListener("drop", (e) => {
|
||
list.classList.remove("is-drop");
|
||
const raw = e.dataTransfer?.getData("application/x-docwell-card");
|
||
const store = this.host.store;
|
||
if (!raw || !store) return;
|
||
e.preventDefault();
|
||
const { row, from } = JSON.parse(raw) as { row: string; from: string };
|
||
// Dropped onto a card: the row goes before it.
|
||
dropCard(row, from, g.key, (e.target as HTMLElement).closest<HTMLElement>(".dw-db-k__card")?.dataset.row);
|
||
});
|
||
}
|
||
board.append(h("section", { class: "dw-db-k__col", "aria-label": g.label }, head, list));
|
||
}
|
||
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);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- timeline
|
||
|
||
/**
|
||
* Records as bars from their start date to their end date, one row each,
|
||
* in the view's order. Bars are dragged to move a record (both dates move)
|
||
* and by their right edge to change its end. Records without a start are
|
||
* listed below, like on the calendar.
|
||
*/
|
||
private drawTimeline(v: View) {
|
||
const l = this.labels;
|
||
const start = this.db.columns.find((c) => c.id === v.dateColumn);
|
||
if (!start) {
|
||
this.body.replaceChildren(h("p", { class: "dw-db__empty" }, l.noStartColumn));
|
||
return;
|
||
}
|
||
const end = this.db.columns.find((c) => c.id === v.endColumn && c.type === "date");
|
||
const scale = this.tlScale ?? v.scale;
|
||
const { px, days, step } = timelineScale[scale];
|
||
const today = isoDay(new Date());
|
||
const from = this.tlFrom || timelineStart(today, scale);
|
||
const last = addDays(from, days - 1);
|
||
const movable = this.editable && start.type === "date";
|
||
const title = titleColumn(this.db);
|
||
const rows = viewRows(this.db, v, this.search);
|
||
const placed: { r: Row; span: { from: string; to: string } }[] = [];
|
||
const undated: Row[] = [];
|
||
for (const r of rows) {
|
||
const span = timelineSpan(r, start, end);
|
||
if (span) placed.push({ r, span });
|
||
else undated.push(r);
|
||
}
|
||
const locale = this.host.locale;
|
||
const fmt = (day: string, o: Intl.DateTimeFormatOptions) =>
|
||
new Date(`${day}T12:00:00Z`).toLocaleDateString(locale, { ...o, timeZone: "UTC" });
|
||
|
||
// Navigation and zoom.
|
||
const go = (n: number) => {
|
||
this.tlFrom = addDays(from, n);
|
||
this.drawBody();
|
||
};
|
||
const zoom = h("div", { class: "dw-db-tl__zoom", role: "group" });
|
||
for (const sc of timelineScales) {
|
||
const label = sc === "day" ? l.scaleDay : sc === "week" ? l.scaleWeek : l.scaleMonth;
|
||
const b = h(
|
||
"button",
|
||
{
|
||
type: "button",
|
||
class: sc === scale ? "dw-db__btn is-on" : "dw-db__btn",
|
||
"aria-pressed": String(sc === scale),
|
||
},
|
||
label,
|
||
);
|
||
b.addEventListener("click", () => {
|
||
this.tlFrom = "";
|
||
if (this.editable && this.host.store) {
|
||
this.tlScale = null;
|
||
this.host.store.updateView(v.id, { scale: sc });
|
||
} else {
|
||
this.tlScale = sc;
|
||
this.drawBody();
|
||
}
|
||
});
|
||
zoom.append(b);
|
||
}
|
||
const nav = h(
|
||
"div",
|
||
{ class: "dw-db-c__nav" },
|
||
h(
|
||
"strong",
|
||
{ class: "dw-db-c__month" },
|
||
`${fmt(from, { day: "numeric", month: "short" })} – ${fmt(last, { day: "numeric", month: "short", year: "numeric" })}`,
|
||
),
|
||
iconButton("chevron-left", l.earlier, () => go(-step)),
|
||
iconButton("chevron-right", l.later, () => go(step)),
|
||
iconButton(
|
||
"calendar",
|
||
l.today,
|
||
() => {
|
||
this.tlFrom = "";
|
||
this.drawBody();
|
||
},
|
||
l.today,
|
||
),
|
||
zoom,
|
||
);
|
||
|
||
// The scale along the top: every day, every Monday, or every first of the month.
|
||
const width = days * px;
|
||
const ticks = h("div", { class: "dw-db-tl__ticks", style: { width: `${width}px` } });
|
||
for (let i = 0; i < days; i++) {
|
||
const day = addDays(from, i);
|
||
const dow = (new Date(`${day}T12:00:00Z`).getUTCDay() + 6) % 7;
|
||
let label = "";
|
||
if (scale === "day") label = fmt(day, { weekday: "narrow", day: "numeric" });
|
||
else if (scale === "week" && dow === 0) label = fmt(day, { day: "numeric", month: "short" });
|
||
else if (scale === "month" && day.endsWith("-01"))
|
||
label = fmt(day, { month: "short", year: day.slice(5, 7) === "01" ? "numeric" : undefined });
|
||
const weekend = dow >= 5 && scale !== "month";
|
||
if (!label && !weekend) continue;
|
||
const tick = h(
|
||
"span",
|
||
{
|
||
class: `dw-db-tl__tick${label ? "" : " is-blank"}${weekend ? " is-weekend" : ""}`,
|
||
style: { left: `${i * px}px`, width: `${px}px` },
|
||
},
|
||
label,
|
||
);
|
||
ticks.append(tick);
|
||
}
|
||
const todayAt = daysBetween(from, today);
|
||
const marks = (): Node[] => {
|
||
const out: Node[] = [];
|
||
if (todayAt >= 0 && todayAt < days)
|
||
out.push(
|
||
h("span", { class: "dw-db-tl__today", style: { left: `${todayAt * px + px / 2}px` }, "aria-hidden": "true" }),
|
||
);
|
||
return out;
|
||
};
|
||
|
||
const grid = h("div", { class: "dw-db-tl__grid" });
|
||
grid.style.setProperty("--dw-tl-width", `${width}px`);
|
||
grid.style.setProperty("--dw-tl-day", `${px}px`);
|
||
grid.append(
|
||
h(
|
||
"div",
|
||
{ class: "dw-db-tl__row dw-db-tl__row--head" },
|
||
h("div", { class: "dw-db-tl__label" }),
|
||
h("div", { class: "dw-db-tl__track" }, ticks, ...marks()),
|
||
),
|
||
);
|
||
|
||
for (const { r, span } of placed.slice(0, this.limit)) {
|
||
const name = cellText(r, title) || l.untitledRow;
|
||
const label = h("button", { type: "button", class: "dw-db-tl__label", title: name }, name);
|
||
label.addEventListener("click", () => this.openRow(r.id));
|
||
const track = h("div", { class: "dw-db-tl__track" }, ...marks());
|
||
const a = daysBetween(from, span.from);
|
||
const b = daysBetween(from, span.to) + 1;
|
||
if (b > 0 && a < days) {
|
||
const left = Math.max(a, 0);
|
||
const right = Math.min(b, days);
|
||
const bar = h(
|
||
"div",
|
||
{
|
||
class: `dw-db-tl__bar${a < 0 ? " is-cut-start" : ""}${b > days ? " is-cut-end" : ""}${movable ? " is-movable" : ""}`,
|
||
style: { left: `${left * px}px`, width: `${Math.max((right - left) * px, 4)}px` },
|
||
role: "button",
|
||
tabIndex: 0,
|
||
title: `${name}: ${span.from === span.to ? span.from : `${span.from} – ${span.to}`}`,
|
||
dataset: { row: r.id },
|
||
},
|
||
h("span", { class: "dw-db-tl__bar-text" }, name),
|
||
);
|
||
bar.addEventListener("keydown", (e) => {
|
||
if (e.key === "Enter" || e.key === " ") {
|
||
e.preventDefault();
|
||
this.openRow(r.id);
|
||
}
|
||
});
|
||
const handle =
|
||
movable && end && b <= days
|
||
? h("span", { class: "dw-db-tl__handle", title: l.dragEnd, "aria-hidden": "true" })
|
||
: null;
|
||
if (handle) bar.append(handle);
|
||
this.dragBar(
|
||
bar,
|
||
handle,
|
||
px,
|
||
(moved, resized) => {
|
||
const store = this.host.store;
|
||
if (!store) return;
|
||
if (!moved && !resized) return this.openRow(r.id);
|
||
store.tx(() => {
|
||
if (resized) {
|
||
const to = addDays(span.to, resized);
|
||
if (end) store.setCell(r.id, end.id, to < span.from ? span.from : to);
|
||
return;
|
||
}
|
||
store.setCell(r.id, start.id, addDays(span.from, moved));
|
||
// A record with an end keeps its length.
|
||
if (end && dateOf(cellValue(r, end))) store.setCell(r.id, end.id, addDays(span.to, moved));
|
||
});
|
||
},
|
||
movable,
|
||
);
|
||
track.append(bar);
|
||
}
|
||
grid.append(h("div", { class: "dw-db-tl__row" }, label, track));
|
||
}
|
||
if (this.editable) {
|
||
const add = h("button", { type: "button", class: "dw-db-t__new" }, icon("plus", 14), h("span", {}, l.newRow));
|
||
add.addEventListener("click", () => this.addRow(start.type === "date" ? { [start.id]: today } : {}, true));
|
||
grid.append(h("div", { class: "dw-db-tl__row dw-db-tl__row--new" }, add));
|
||
}
|
||
const scroller = h("div", { class: "dw-db-tl__scroll" }, grid);
|
||
const children: Node[] = [nav, scroller];
|
||
if (!rows.length) children.push(h("p", { class: "dw-db__empty" }, this.db.rows.length ? l.noMatches : l.noRows));
|
||
if (placed.length > this.limit) {
|
||
const more = h(
|
||
"button",
|
||
{ type: "button", class: "dw-db__btn dw-db__more" },
|
||
`${l.more} (${placed.length - this.limit})`,
|
||
);
|
||
more.addEventListener("click", () => {
|
||
this.limit += PAGE;
|
||
this.drawBody();
|
||
});
|
||
children.push(more);
|
||
}
|
||
if (undated.length) {
|
||
const chips = undated.slice(0, this.limit).map((r) => {
|
||
const chip = h("button", { type: "button", class: "dw-db-c__chip" }, cellText(r, title) || l.untitledRow);
|
||
chip.addEventListener("click", () => this.openRow(r.id));
|
||
return chip;
|
||
});
|
||
children.push(
|
||
h(
|
||
"details",
|
||
{ class: "dw-db-c__undated" },
|
||
h("summary", {}, fill(l.noDate, undated.length)),
|
||
h("div", { class: "dw-db-c__chips" }, chips),
|
||
),
|
||
);
|
||
}
|
||
this.body.replaceChildren(h("div", { class: "dw-db-tl" }, children));
|
||
}
|
||
|
||
/**
|
||
* Drags a timeline bar by whole days: the bar moves, or with the handle its
|
||
* end. done gets the days moved and the days the end moved (both 0 for a
|
||
* plain click or tap). Touch drags go sideways only, so the page still
|
||
* scrolls up and down.
|
||
*/
|
||
private dragBar(
|
||
bar: HTMLElement,
|
||
handle: HTMLElement | null,
|
||
px: number,
|
||
done: (moved: number, resized: number) => void,
|
||
movable: boolean,
|
||
) {
|
||
// The block around it is draggable; a bar must not start the browser's own drag.
|
||
bar.addEventListener("dragstart", (e) => {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
});
|
||
bar.addEventListener("pointerdown", (e) => {
|
||
if (e.button !== 0) return;
|
||
// No text selection or native drag from the mouse events that follow.
|
||
if (e.pointerType === "mouse") e.preventDefault();
|
||
e.stopPropagation();
|
||
const resizing = !!handle && (e.target as Node) === handle;
|
||
const x0 = e.clientX;
|
||
const y0 = e.clientY;
|
||
const w0 = bar.offsetWidth;
|
||
let days = 0;
|
||
let dragging = false;
|
||
try {
|
||
bar.setPointerCapture(e.pointerId);
|
||
} catch {
|
||
// A pointer the browser no longer tracks; moves still reach the bar.
|
||
}
|
||
const move = (ev: PointerEvent) => {
|
||
const dx = ev.clientX - x0;
|
||
if (!dragging && Math.abs(dx) < 4) {
|
||
// A finger moving up or down scrolls the page instead.
|
||
if (Math.abs(ev.clientY - y0) > 8) cleanup();
|
||
return;
|
||
}
|
||
if (!movable) return;
|
||
dragging = true;
|
||
days = Math.round(dx / px);
|
||
bar.classList.add("is-dragging");
|
||
if (resizing) bar.style.width = `${Math.max(w0 + days * px, px)}px`;
|
||
else bar.style.transform = `translateX(${days * px}px)`;
|
||
};
|
||
const cleanup = () => {
|
||
bar.removeEventListener("pointermove", move);
|
||
bar.removeEventListener("pointerup", up);
|
||
bar.removeEventListener("pointercancel", cancel);
|
||
if (bar.hasPointerCapture(e.pointerId)) bar.releasePointerCapture(e.pointerId);
|
||
};
|
||
const up = () => {
|
||
cleanup();
|
||
bar.classList.remove("is-dragging");
|
||
bar.style.transform = "";
|
||
if (resizing) bar.style.width = `${w0}px`;
|
||
if (!dragging) done(0, 0);
|
||
else if (days) done(resizing ? 0 : days, resizing ? days : 0);
|
||
};
|
||
const cancel = () => {
|
||
cleanup();
|
||
bar.classList.remove("is-dragging");
|
||
bar.style.transform = "";
|
||
bar.style.width = `${w0}px`;
|
||
};
|
||
bar.addEventListener("pointermove", move);
|
||
bar.addEventListener("pointerup", up);
|
||
bar.addEventListener("pointercancel", cancel);
|
||
});
|
||
}
|
||
|
||
// ---------------------------------------------------------------- calendar
|
||
|
||
private drawCalendar(v: View) {
|
||
const l = this.labels;
|
||
const col = this.db.columns.find((c) => c.id === v.dateColumn);
|
||
if (!col) {
|
||
this.body.replaceChildren(h("p", { class: "dw-db__empty" }, l.noDateColumn));
|
||
return;
|
||
}
|
||
const movable = this.editable && col.type === "date";
|
||
const { y, m } = this.month;
|
||
const days = monthGrid(y, m);
|
||
const rows = viewRows(this.db, v, this.search);
|
||
const byDay = new Map<string, Row[]>();
|
||
const undated: Row[] = [];
|
||
for (const r of rows) {
|
||
const d = dateOf(cellValue(r, col));
|
||
if (!d) undated.push(r);
|
||
else byDay.set(d, [...(byDay.get(d) ?? []), r]);
|
||
}
|
||
const title = titleColumn(this.db);
|
||
const today = isoDay(new Date());
|
||
const monthName = new Date(y, m, 1).toLocaleDateString(this.host.locale, { month: "long", year: "numeric" });
|
||
const go = (dm: number) => {
|
||
const d = new Date(y, m + dm, 1);
|
||
this.month = { y: d.getFullYear(), m: d.getMonth() };
|
||
this.drawBody();
|
||
};
|
||
const nav = h(
|
||
"div",
|
||
{ class: "dw-db-c__nav" },
|
||
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,
|
||
),
|
||
);
|
||
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" }),
|
||
);
|
||
});
|
||
const chip = (r: Row) => {
|
||
const el = h(
|
||
"button",
|
||
{ type: "button", class: "dw-db-c__chip", draggable: movable, dataset: { row: r.id } },
|
||
cellText(r, title) || l.untitledRow,
|
||
);
|
||
el.addEventListener("click", () => this.openRow(r.id));
|
||
el.addEventListener("dragstart", (e) => {
|
||
e.dataTransfer?.setData("application/x-docwell-row-date", r.id);
|
||
if (e.dataTransfer) e.dataTransfer.effectAllowed = "move";
|
||
});
|
||
if (movable) {
|
||
let mark: HTMLElement | null = null;
|
||
const dayAt = (t: Element | null) => {
|
||
const at = t?.closest<HTMLElement>(".dw-db-c__day");
|
||
return at && this.body.contains(at) ? at : null;
|
||
};
|
||
touchDraggable(el, {
|
||
source: el,
|
||
ghost: () => el.cloneNode(true) as HTMLElement,
|
||
over: (t) => {
|
||
mark?.classList.remove("is-drop");
|
||
mark = dayAt(t);
|
||
mark?.classList.add("is-drop");
|
||
},
|
||
drop: (t) => {
|
||
const day = dayAt(t)?.dataset.day;
|
||
if (day) this.host.store?.setCell(r.id, col.id, day);
|
||
},
|
||
end: () => mark?.classList.remove("is-drop"),
|
||
});
|
||
}
|
||
return el;
|
||
};
|
||
const grid = h("div", { class: "dw-db-c__grid", role: "grid" }, week);
|
||
for (const d of days) {
|
||
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 },
|
||
},
|
||
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),
|
||
);
|
||
add.addEventListener("click", () => this.addRow({ [col.id]: d }, true));
|
||
cell.append(add);
|
||
}
|
||
if (movable) {
|
||
cell.addEventListener("dragover", (e) => {
|
||
if (!e.dataTransfer?.types.includes("application/x-docwell-row-date")) return;
|
||
e.preventDefault();
|
||
cell.classList.add("is-drop");
|
||
});
|
||
cell.addEventListener("dragleave", () => cell.classList.remove("is-drop"));
|
||
cell.addEventListener("drop", (e) => {
|
||
cell.classList.remove("is-drop");
|
||
const id = e.dataTransfer?.getData("application/x-docwell-row-date");
|
||
if (!id) return;
|
||
e.preventDefault();
|
||
this.host.store?.setCell(id, col.id, d);
|
||
});
|
||
}
|
||
grid.append(cell);
|
||
}
|
||
const children: Node[] = [nav, grid];
|
||
if (undated.length) {
|
||
children.push(
|
||
h(
|
||
"details",
|
||
{ class: "dw-db-c__undated" },
|
||
h("summary", {}, fill(l.noDate, undated.length)),
|
||
h("div", { class: "dw-db-c__chips" }, undated.slice(0, this.limit).map(chip)),
|
||
),
|
||
);
|
||
}
|
||
this.body.replaceChildren(h("div", { class: "dw-db-c" }, children));
|
||
}
|
||
}
|
||
|
||
const fallbackView: View = {
|
||
id: "",
|
||
name: "",
|
||
type: "table",
|
||
hidden: [],
|
||
filters: [],
|
||
filterMode: "and",
|
||
sorts: [],
|
||
groupBy: null,
|
||
dateColumn: null,
|
||
cover: null,
|
||
endColumn: null,
|
||
scale: "week",
|
||
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",
|
||
timeline: "timeline",
|
||
};
|
||
|
||
/** 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") : [];
|
||
}
|