Add a chart view to databases
Bars, a line or a donut of the view's records, counted or with a number property summed or averaged, per choice, checkbox, person or month of a date. Drawn as SVG in the theme's colours; bars and slices take a choice's colour. The view's filters apply. The chart settings redraw themselves, so the number property appears for sums and averages and a change keeps the others. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d3c4d1f57a
commit
fa17016456
13 files changed
+512
-10
No files matched your search
@@ -11,6 +11,8 @@ What changed in each Docwell release. The release workflow copies a version's se
|
||||
these views as tables.
|
||||
- A **timeline** view: records as bars from a start date to an end date property, shown by days, weeks or months. Drag
|
||||
a bar to move it, or its right edge to change its end.
|
||||
- A **chart** view: bars, a line or a donut of the records, counted or with a number property summed or averaged, per
|
||||
choice, person or month.
|
||||
- Fixed: the view settings of a calendar showed only its properties, not the date property to place records by.
|
||||
|
||||
### Email
|
||||
|
||||
@@ -73,7 +73,9 @@ it together, and Ctrl+Z undoes database changes like any other.
|
||||
and a **gallery** of cards, covered with the first image of an attachment property you pick in the view's settings.
|
||||
Lists and galleries can be grouped like tables. A **timeline** draws each record as a bar from its date property to an
|
||||
end date property (both chosen in the view's settings; without an end, a bar lasts a day), by days, weeks or months:
|
||||
drag a bar to move both dates, or its right edge to change the end. Click the active tab to rename, duplicate, change or delete the view;
|
||||
drag a bar to move both dates, or its right edge to change the end. A **chart** shows the view's records as bars, a
|
||||
line or a donut, counted, or with a number property summed or averaged, per value of a select, checkbox or member
|
||||
property, or per month of a date; the view's filters apply. Click the active tab to rename, duplicate, change or delete the view;
|
||||
which view you look at is yours alone. Apps older than a layout show it as a table.
|
||||
- **Records as pages:** **Open** on a record, or a click on a card, opens it beside the page, with its properties on
|
||||
top and room to write below. **Open as full page** (the arrow button) shows the record on its own, in the page's
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import * as Y from "yjs";
|
||||
import { formatDelimited, fromCSV, parseDelimited, toCSV } from "./csv";
|
||||
import { addDays, convertValue, coverImage, daysBetween, defaultView, timelineSpan, timelineStart, groupRows, monthGrid, moveToGroup, normalize, viewRows, type Column, type DbData, type Row } from "./model";
|
||||
import { addDays, chartData, convertValue, coverImage, daysBetween, niceMax, defaultView, timelineSpan, timelineStart, 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" };
|
||||
@@ -187,3 +187,43 @@ describe("timeline view", () => {
|
||||
expect(from < "2026-11-19").toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("chart view", () => {
|
||||
const due: Column = { id: "d", name: "Due", type: "date" };
|
||||
|
||||
it("counts records per choice, leaving out an empty no-value group", () => {
|
||||
const db = sample();
|
||||
const pts = chartData(db, { type: "bar", x: "s", op: "count", y: null }, db.rows, "None", "Yes", "No")!;
|
||||
// In grouping order: no value first, like grouped tables.
|
||||
expect(pts.map((p) => [p.key, p.value])).toEqual([
|
||||
["", 1],
|
||||
["todo", 1],
|
||||
["done", 1],
|
||||
]);
|
||||
});
|
||||
|
||||
it("sums and averages a number property", () => {
|
||||
const db = sample();
|
||||
const sum = chartData(db, { type: "bar", x: "s", op: "sum", y: "p" }, db.rows, "None", "Yes", "No")!;
|
||||
expect(sum.map((p) => p.value)).toEqual([5, 3, 1]);
|
||||
const rows = [row("a", { s: "todo", p: 3 }), row("b", { s: "todo", p: 4 }), row("c", { s: "todo" })];
|
||||
const avg = chartData(db, { type: "bar", x: "s", op: "avg", y: "p" }, rows, "None", "Yes", "No")!;
|
||||
expect(avg.find((p) => p.key === "todo")).toMatchObject({ value: 3.5, count: 3 });
|
||||
});
|
||||
|
||||
it("buckets dates by month, in order, without undated records", () => {
|
||||
const db: DbData = { ...sample(), columns: [title, due] };
|
||||
const rows = [row("a", { d: "2026-12-03" }), row("b", { d: "2026-11-20" }), row("c", { d: "2026-11-02" }), row("e", {})];
|
||||
const pts = chartData(db, { type: "line", x: "d", op: "count", y: null }, rows, "None", "Yes", "No")!;
|
||||
expect(pts.map((p) => [p.key, p.value])).toEqual([
|
||||
["2026-11", 2],
|
||||
["2026-12", 1],
|
||||
]);
|
||||
});
|
||||
|
||||
it("has no data without an axis, and rounds the axis top", () => {
|
||||
expect(chartData(sample(), { type: "bar", x: "p", op: "count", y: null }, [], "", "", "")).toBeNull();
|
||||
expect([niceMax(0), niceMax(3), niceMax(7), niceMax(12), niceMax(100)]).toEqual([1, 5, 10, 20, 100]);
|
||||
expect(normalize({ columns: [title], views: [{ id: "c", type: "chart", chart: { type: "pie", op: "max" } }] }).views[0]!.chart).toEqual({ type: "bar", x: null, op: "count", y: null });
|
||||
});
|
||||
});
|
||||
@@ -28,6 +28,19 @@ export const englishDatabaseLabels = {
|
||||
viewList: "List",
|
||||
viewGallery: "Gallery",
|
||||
viewTimeline: "Timeline",
|
||||
viewChart: "Chart",
|
||||
chartType: "Chart type",
|
||||
chartBar: "Bars",
|
||||
chartLine: "Line",
|
||||
chartDonut: "Donut",
|
||||
chartX: "Show records by",
|
||||
chartMeasure: "Measure",
|
||||
chartCount: "Count of records",
|
||||
chartSum: "Sum of",
|
||||
chartAvg: "Average of",
|
||||
chartValue: "Number property",
|
||||
noChartAxis: "Add a select, checkbox, member or date property to chart records by.",
|
||||
noChartData: "Nothing to chart: no record has a value here.",
|
||||
endColumn: "End date property",
|
||||
sameDay: "Same day as the start",
|
||||
scaleDay: "Days",
|
||||
@@ -238,6 +251,7 @@ const viewKeys: Record<ViewType, keyof DatabaseLabels> = {
|
||||
list: "viewList",
|
||||
gallery: "viewGallery",
|
||||
timeline: "viewTimeline",
|
||||
chart: "viewChart",
|
||||
};
|
||||
|
||||
export const viewLabel = (l: DatabaseLabels, t: ViewType) => l[viewKeys[t]];
|
||||
|
||||
@@ -75,9 +75,24 @@ export interface Row {
|
||||
}
|
||||
|
||||
/** View layouts. Clients that do not know a layout show it as a table (normalize). */
|
||||
export const viewTypes = ["table", "kanban", "calendar", "list", "gallery", "timeline"] as const;
|
||||
export const viewTypes = ["table", "kanban", "calendar", "list", "gallery", "timeline", "chart"] as const;
|
||||
export type ViewType = (typeof viewTypes)[number];
|
||||
|
||||
export const chartTypes = ["bar", "line", "donut"] as const;
|
||||
export type ChartType = (typeof chartTypes)[number];
|
||||
export const chartOps = ["count", "sum", "avg"] as const;
|
||||
export type ChartOp = (typeof chartOps)[number];
|
||||
|
||||
/** What a chart view draws: records counted, or a number property summed or averaged, per value of x. */
|
||||
export interface ChartSpec {
|
||||
type: ChartType;
|
||||
/** The property along the axis: a groupable one, or a date (by month). */
|
||||
x: string | null;
|
||||
op: ChartOp;
|
||||
/** The number property summed or averaged; unused for counts. */
|
||||
y: string | null;
|
||||
}
|
||||
|
||||
export const timelineScales = ["day", "week", "month"] as const;
|
||||
export type TimelineScale = (typeof timelineScales)[number];
|
||||
|
||||
@@ -128,6 +143,8 @@ export interface View {
|
||||
endColumn: string | null;
|
||||
/** How much time a timeline shows: days, weeks or months. */
|
||||
scale: TimelineScale;
|
||||
/** What a chart view draws. */
|
||||
chart: ChartSpec;
|
||||
/** Column widths in pixels, by column id. */
|
||||
widths: Record<string, number>;
|
||||
}
|
||||
@@ -163,10 +180,27 @@ export function defaultView(type: ViewType, name: string, columns: Column[]): Vi
|
||||
cover: type === "gallery" ? (columns.find((c) => c.type === "attachment")?.id ?? null) : null,
|
||||
endColumn: type === "timeline" ? (dates.find((c) => c.id !== date?.id)?.id ?? null) : null,
|
||||
scale: "week",
|
||||
chart: { type: "bar", x: type === "chart" ? (columns.find((c) => chartAxisTypes.includes(c.type))?.id ?? null) : null, op: "count", y: null },
|
||||
widths: {},
|
||||
};
|
||||
}
|
||||
|
||||
/** Columns a chart can be drawn along: groupable ones, and dates (by month). */
|
||||
export const chartAxisTypes: ColumnType[] = ["select", "multiSelect", "checkbox", "member", "createdBy", "date", "createdTime"];
|
||||
|
||||
/** Columns a chart can sum or average. */
|
||||
export const chartMeasureTypes: ColumnType[] = ["number", "progress", "rollup"];
|
||||
|
||||
function readChart(raw: unknown, ids: Set<string>): ChartSpec {
|
||||
const o = isObject(raw) ? raw : {};
|
||||
return {
|
||||
type: (chartTypes as readonly string[]).includes(String(o.type)) ? (o.type as ChartType) : "bar",
|
||||
x: typeof o.x === "string" && ids.has(o.x) ? o.x : null,
|
||||
op: (chartOps as readonly string[]).includes(String(o.op)) ? (o.op as ChartOp) : "count",
|
||||
y: typeof o.y === "string" && ids.has(o.y) ? o.y : null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Columns rows can be grouped by, and kanban boards built on. */
|
||||
export const groupableTypes: ColumnType[] = ["select", "multiSelect", "checkbox", "member", "createdBy"];
|
||||
|
||||
@@ -221,6 +255,7 @@ export function normalize(raw: unknown): DbData {
|
||||
cover: typeof v.cover === "string" && ids.has(v.cover) ? v.cover : null,
|
||||
endColumn: typeof v.endColumn === "string" && ids.has(v.endColumn) ? v.endColumn : null,
|
||||
scale: (timelineScales as readonly string[]).includes(String(v.scale)) ? (v.scale as TimelineScale) : "week",
|
||||
chart: readChart(v.chart, ids),
|
||||
widths: isObject(v.widths)
|
||||
? Object.fromEntries(Object.entries(v.widths).filter((e): e is [string, number] => typeof e[1] === "number"))
|
||||
: {},
|
||||
@@ -694,3 +729,57 @@ export function timelineStart(today: string, scale: TimelineScale): string {
|
||||
return addDays(d, -dow);
|
||||
}
|
||||
|
||||
/** One bar, point or slice of a chart. key is a group key, or a month (YYYY-MM) for dates. */
|
||||
export interface ChartPoint {
|
||||
key: string;
|
||||
label: string;
|
||||
color?: PaletteColor;
|
||||
value: number;
|
||||
/** How many records it stands for. */
|
||||
count: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The points a chart view draws from rows (already filtered), or null when
|
||||
* it has no usable axis. Dates are counted by month, in order, leaving out
|
||||
* records without one; other axes follow groupRows, without an empty
|
||||
* "no value" group.
|
||||
*/
|
||||
export function chartData(db: DbData, chart: ChartSpec, rows: Row[], noValue: string, yes: string, no: string): ChartPoint[] | null {
|
||||
const x = db.columns.find((c) => c.id === chart.x && chartAxisTypes.includes(c.type));
|
||||
if (!x) return null;
|
||||
const y = chart.op === "count" ? undefined : db.columns.find((c) => c.id === chart.y && chartMeasureTypes.includes(c.type));
|
||||
const measure = (rs: Row[]): number => {
|
||||
if (!y) return rs.length;
|
||||
const nums = rs.flatMap((r) => {
|
||||
const n = asNumber(cellValue(r, y));
|
||||
return n === null ? [] : [n];
|
||||
});
|
||||
const sum = nums.reduce((a, b) => a + b, 0);
|
||||
const v = chart.op === "avg" ? (nums.length ? sum / nums.length : 0) : sum;
|
||||
return Math.round(v * 100) / 100;
|
||||
};
|
||||
if (x.type === "date" || x.type === "createdTime") {
|
||||
const months = new Map<string, Row[]>();
|
||||
for (const r of rows) {
|
||||
const d = dateOf(cellValue(r, x));
|
||||
if (d) months.set(d.slice(0, 7), [...(months.get(d.slice(0, 7)) ?? []), r]);
|
||||
}
|
||||
return [...months.keys()].sort().map((key) => {
|
||||
const rs = months.get(key)!;
|
||||
return { key, label: key, value: measure(rs), count: rs.length };
|
||||
});
|
||||
}
|
||||
return groupRows(rows, x, noValue, yes, no)
|
||||
.filter((g) => g.rows.length || (g.key !== "" && x.type !== "member" && x.type !== "createdBy"))
|
||||
.map((g) => ({ key: g.key, label: g.label, color: g.color, value: measure(g.rows), count: g.rows.length }));
|
||||
}
|
||||
|
||||
/** A round top for a chart's axis: 1, 2 or 5 times a power of ten, at least max. */
|
||||
export function niceMax(max: number): number {
|
||||
if (max <= 0) return 1;
|
||||
const p = 10 ** Math.floor(Math.log10(max));
|
||||
for (const m of [1, 2, 5, 10]) if (m * p >= max) return m * p;
|
||||
return 10 * p;
|
||||
}
|
||||
|
||||
@@ -7,9 +7,16 @@ import { typeIcons } from "./cells";
|
||||
import { h, icon } from "./dom";
|
||||
import { opLabel, typeLabel } from "./labels";
|
||||
import {
|
||||
chartAxisTypes,
|
||||
chartMeasureTypes,
|
||||
chartOps,
|
||||
chartTypes,
|
||||
filterOps,
|
||||
groupableTypes,
|
||||
opTakesValue,
|
||||
type ChartOp,
|
||||
type ChartSpec,
|
||||
type ChartType,
|
||||
type Column,
|
||||
type Filter,
|
||||
type FilterOp,
|
||||
@@ -200,6 +207,48 @@ export function datePanel(ctx: DbContext, box: HTMLElement, view: View) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* What a chart draws: its type, its axis, and what it measures. It keeps
|
||||
* the chart as last saved and redraws itself, since the panel stays open
|
||||
* across changes (the number property shows only for sums and averages).
|
||||
*/
|
||||
export function chartPanel(ctx: DbContext, outer: HTMLElement, view: View) {
|
||||
const store = ctx.store;
|
||||
const l = ctx.labels;
|
||||
let chart = { ...view.chart };
|
||||
const box = h("div", { class: "dw-db-pop__chart" });
|
||||
outer.append(box);
|
||||
const save = (patch: Partial<ChartSpec>) => {
|
||||
chart = { ...chart, ...patch };
|
||||
store?.updateView(view.id, { chart });
|
||||
draw();
|
||||
};
|
||||
const axes = ctx.db.columns.filter((c) => chartAxisTypes.includes(c.type));
|
||||
const numbers = ctx.db.columns.filter((c) => chartMeasureTypes.includes(c.type));
|
||||
const name = (c: Column) => c.name || typeLabel(l, c.type);
|
||||
const draw = () => {
|
||||
box.replaceChildren(
|
||||
h("label", { class: "dw-db-pop__label" }, l.chartType),
|
||||
select<ChartType>(chart.type, chartTypes.map((t) => ({ value: t, label: t === "bar" ? l.chartBar : t === "line" ? l.chartLine : l.chartDonut })), l.chartType, (type) => save({ type })),
|
||||
h("label", { class: "dw-db-pop__label" }, l.chartX),
|
||||
axes.length
|
||||
? select(chart.x ?? "", [{ value: "", label: "—" }, ...axes.map((c) => ({ value: c.id, label: name(c) }))], l.chartX, (x) => save({ x: x || null }))
|
||||
: h("p", { class: "dw-db-pop__empty" }, l.noChartAxis),
|
||||
h("label", { class: "dw-db-pop__label" }, l.chartMeasure),
|
||||
select<ChartOp>(
|
||||
chart.op,
|
||||
chartOps.filter((op) => op === "count" || numbers.length).map((op) => ({ value: op, label: op === "count" ? l.chartCount : op === "sum" ? l.chartSum : l.chartAvg })),
|
||||
l.chartMeasure,
|
||||
(op) => save({ op, y: op === "count" ? null : (chart.y ?? numbers[0]?.id ?? null) }),
|
||||
),
|
||||
);
|
||||
if (chart.op !== "count" && numbers.length) {
|
||||
box.append(select(chart.y ?? "", numbers.map((c) => ({ value: c.id, label: name(c) })), l.chartValue, (y) => save({ y: y || null })));
|
||||
}
|
||||
};
|
||||
draw();
|
||||
}
|
||||
|
||||
/** The property a timeline's bars end on; without one, bars last a day. */
|
||||
export function endPanel(ctx: DbContext, box: HTMLElement, view: View) {
|
||||
const store = ctx.store;
|
||||
|
||||
@@ -16,6 +16,8 @@ import {
|
||||
cellText,
|
||||
cellValue,
|
||||
addDays,
|
||||
chartAxisTypes,
|
||||
chartData,
|
||||
coverImage,
|
||||
dateOf,
|
||||
daysBetween,
|
||||
@@ -25,6 +27,7 @@ import {
|
||||
isoDay,
|
||||
monthGrid,
|
||||
moveToGroup,
|
||||
niceMax,
|
||||
timelineScale,
|
||||
timelineScales,
|
||||
timelineSpan,
|
||||
@@ -36,6 +39,7 @@ import {
|
||||
type Column,
|
||||
type DbData,
|
||||
type Group,
|
||||
type ChartPoint,
|
||||
type Row,
|
||||
type TimelineScale,
|
||||
type View,
|
||||
@@ -263,9 +267,9 @@ export class DatabaseView {
|
||||
};
|
||||
count(b.filter, v.filters.length);
|
||||
count(b.sort, v.sorts.length);
|
||||
b.sort.hidden = v.type === "calendar";
|
||||
b.sort.hidden = v.type === "calendar" || v.type === "chart";
|
||||
b.group.classList.toggle("is-on", !!v.groupBy && groupedLayouts.includes(v.type));
|
||||
b.group.hidden = v.type === "calendar" || v.type === "timeline";
|
||||
b.group.hidden = v.type === "calendar" || v.type === "timeline" || v.type === "chart";
|
||||
b.add.hidden = !this.editable;
|
||||
this.drawBulk();
|
||||
}
|
||||
@@ -304,6 +308,7 @@ export class DatabaseView {
|
||||
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 === "chart") p.chartPanel(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);
|
||||
@@ -365,6 +370,7 @@ export class DatabaseView {
|
||||
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 === "chart" && !v.chart.x) patch.chart = { ...v.chart, x: cols.find((c) => chartAxisTypes.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;
|
||||
@@ -490,6 +496,7 @@ export class DatabaseView {
|
||||
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 if (v.type === "chart") this.drawChart(v);
|
||||
else this.drawTable(v);
|
||||
}
|
||||
|
||||
@@ -1337,6 +1344,123 @@ export class DatabaseView {
|
||||
this.body.replaceChildren(...children);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- chart
|
||||
|
||||
/**
|
||||
* The view's records counted, or a number property summed or averaged,
|
||||
* per value of a property (dates by month): bars, a line or a donut, drawn
|
||||
* as SVG in the theme's colours. Each bar, point or slice's tooltip tells
|
||||
* its value and how many records it stands for.
|
||||
*/
|
||||
private drawChart(v: View) {
|
||||
const l = this.labels;
|
||||
const rows = viewRows(this.db, v, this.search);
|
||||
const points = chartData(this.db, v.chart, rows, l.noValue, l.checked, l.unchecked);
|
||||
if (!points) {
|
||||
this.body.replaceChildren(h("p", { class: "dw-db__empty" }, l.noChartAxis));
|
||||
return;
|
||||
}
|
||||
if (!points.length || points.every((pt) => pt.value === 0)) {
|
||||
this.body.replaceChildren(h("p", { class: "dw-db__empty" }, rows.length ? l.noChartData : this.db.rows.length ? l.noMatches : l.noRows));
|
||||
return;
|
||||
}
|
||||
const locale = this.host.locale;
|
||||
const num = new Intl.NumberFormat(locale, { maximumFractionDigits: 2 });
|
||||
const month = (key: string) => new Date(`${key}-15T12:00:00Z`).toLocaleDateString(locale, { month: "short", year: "numeric", timeZone: "UTC" });
|
||||
const labelOf = (pt: ChartPoint) => (/^\d{4}-\d{2}$/.test(pt.key) && pt.key === pt.label ? month(pt.key) : pt.label);
|
||||
const tip = (pt: ChartPoint) => `${labelOf(pt)}: ${num.format(pt.value)}${v.chart.op === "count" ? "" : ` (${pt.count})`}`;
|
||||
const chart = v.chart.type === "donut" ? this.donut(points, labelOf, tip, num) : this.axes(v.chart.type, points, labelOf, tip, num);
|
||||
this.body.replaceChildren(h("div", { class: "dw-db-ch" }, chart));
|
||||
}
|
||||
|
||||
/** Bars or a line over a value axis. */
|
||||
private axes(type: "bar" | "line", points: ChartPoint[], labelOf: (p: ChartPoint) => string, tip: (p: ChartPoint) => string, num: Intl.NumberFormat): Node {
|
||||
const slot = 56;
|
||||
const left = 44;
|
||||
const top = 16;
|
||||
const plot = 180;
|
||||
const width = Math.max(320, left + points.length * slot + 8);
|
||||
const height = top + plot + 44;
|
||||
const max = niceMax(Math.max(...points.map((pt) => pt.value)));
|
||||
const min = Math.min(0, ...points.map((pt) => pt.value));
|
||||
const span = max - min || 1;
|
||||
const yAt = (val: number) => top + plot - ((val - min) / span) * plot;
|
||||
const svg = svgEl("svg", { class: "dw-db-ch__svg", viewBox: `0 0 ${width} ${height}`, width: String(width), height: String(height), role: "img", "aria-label": this.db.title || this.labels.viewChart });
|
||||
for (let i = 0; i <= 4; i++) {
|
||||
const val = min + (span * i) / 4;
|
||||
const y = yAt(val);
|
||||
svg.append(
|
||||
svgEl("line", { class: "dw-db-ch__grid", x1: String(left), x2: String(width - 4), y1: String(y), y2: String(y) }),
|
||||
svgEl("text", { class: "dw-db-ch__tick", x: String(left - 6), y: String(y + 4), "text-anchor": "end" }, num.format(val)),
|
||||
);
|
||||
}
|
||||
const xAt = (i: number) => left + i * slot + slot / 2;
|
||||
if (type === "line") {
|
||||
svg.append(svgEl("polyline", { class: "dw-db-ch__line", points: points.map((pt, i) => `${xAt(i)},${yAt(pt.value)}`).join(" ") }));
|
||||
}
|
||||
points.forEach((pt, i) => {
|
||||
const x = xAt(i);
|
||||
const y = yAt(pt.value);
|
||||
const zero = yAt(0);
|
||||
const mark =
|
||||
type === "bar"
|
||||
? svgEl("rect", { class: "dw-db-ch__bar", x: String(x - slot * 0.32), y: String(Math.min(y, zero)), width: String(slot * 0.64), height: String(Math.max(Math.abs(zero - y), 1)), rx: "3", "data-color": pt.color ?? "" })
|
||||
: svgEl("circle", { class: "dw-db-ch__dot", cx: String(x), cy: String(y), r: "4" });
|
||||
mark.append(svgEl("title", {}, tip(pt)));
|
||||
const text = labelOf(pt);
|
||||
svg.append(
|
||||
mark,
|
||||
svgEl("text", { class: "dw-db-ch__value", x: String(x), y: String(Math.min(y, zero) - 5), "text-anchor": "middle" }, num.format(pt.value)),
|
||||
svgEl("text", { class: "dw-db-ch__label", x: String(x), y: String(top + plot + 18), "text-anchor": "middle" }, text.length > 9 ? `${text.slice(0, 8)}…` : text, svgEl("title", {}, text)),
|
||||
);
|
||||
});
|
||||
return h("div", { class: "dw-db-ch__scroll" }, svg);
|
||||
}
|
||||
|
||||
/** A donut of slices, with a legend beside it. */
|
||||
private donut(points: ChartPoint[], labelOf: (p: ChartPoint) => string, tip: (p: ChartPoint) => string, num: Intl.NumberFormat): Node {
|
||||
const shown = points.filter((pt) => pt.value > 0);
|
||||
const total = shown.reduce((a, pt) => a + pt.value, 0);
|
||||
const r = 70;
|
||||
const round = 2 * Math.PI * r;
|
||||
const svg = svgEl("svg", { class: "dw-db-ch__svg dw-db-ch__donut", viewBox: "0 0 200 200", width: "200", height: "200", role: "img", "aria-label": this.db.title || this.labels.viewChart });
|
||||
// Slices without a colour of their own take turns through the palette.
|
||||
const fallback = ["blue", "green", "orange", "purple", "teal", "pink", "yellow", "red", "gray"] as const;
|
||||
const colorOf = (pt: ChartPoint, i: number) => pt.color ?? fallback[i % fallback.length]!;
|
||||
let at = 0;
|
||||
shown.forEach((pt, i) => {
|
||||
const len = (pt.value / total) * round;
|
||||
const slice = svgEl("circle", {
|
||||
class: "dw-db-ch__slice",
|
||||
cx: "100",
|
||||
cy: "100",
|
||||
r: String(r),
|
||||
"stroke-dasharray": `${len} ${round - len}`,
|
||||
"stroke-dashoffset": String(-at),
|
||||
transform: "rotate(-90 100 100)",
|
||||
"data-color": colorOf(pt, i),
|
||||
});
|
||||
slice.append(svgEl("title", {}, tip(pt)));
|
||||
svg.append(slice);
|
||||
at += len;
|
||||
});
|
||||
svg.append(svgEl("text", { class: "dw-db-ch__total", x: "100", y: "108", "text-anchor": "middle" }, num.format(total)));
|
||||
const legend = h(
|
||||
"ul",
|
||||
{ class: "dw-db-ch__legend" },
|
||||
shown.map((pt, i) =>
|
||||
h(
|
||||
"li",
|
||||
{ title: tip(pt) },
|
||||
h("span", { class: "dw-db-ch__swatch", dataset: { color: colorOf(pt, i) }, "aria-hidden": "true" }),
|
||||
h("span", { class: "dw-db-ch__name" }, labelOf(pt)),
|
||||
h("span", { class: "dw-db-ch__num" }, `${num.format(pt.value)} · ${Math.round((pt.value / total) * 100)}%`),
|
||||
),
|
||||
),
|
||||
);
|
||||
return h("div", { class: "dw-db-ch__pie" }, svg, legend);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- timeline
|
||||
|
||||
/**
|
||||
@@ -1717,6 +1841,7 @@ const fallbackView: View = {
|
||||
cover: null,
|
||||
endColumn: null,
|
||||
scale: "week",
|
||||
chart: { type: "bar", x: null, op: "count", y: null },
|
||||
widths: {},
|
||||
};
|
||||
|
||||
@@ -1728,8 +1853,17 @@ const viewIcons: Record<ViewType, IconName> = {
|
||||
list: "list",
|
||||
gallery: "grid",
|
||||
timeline: "timeline",
|
||||
chart: "chart",
|
||||
};
|
||||
|
||||
/** An SVG element (h() makes HTML ones). */
|
||||
function svgEl(tag: string, attrs: Record<string, string>, ...children: (Node | string)[]): SVGElement {
|
||||
const el = document.createElementNS("http://www.w3.org/2000/svg", tag);
|
||||
for (const [k, v] of Object.entries(attrs)) if (v !== "") el.setAttribute(k, v);
|
||||
el.append(...children);
|
||||
return el;
|
||||
}
|
||||
|
||||
/** Layouts the Group button applies to (kanban always groups, in its settings). */
|
||||
const groupedLayouts: ViewType[] = ["table", "list", "gallery"];
|
||||
|
||||
|
||||
@@ -1902,6 +1902,106 @@
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- Chart view ---- */
|
||||
.dw-db-ch {
|
||||
padding: 12px 0 4px;
|
||||
}
|
||||
.dw-db-ch__scroll {
|
||||
overflow-x: auto;
|
||||
}
|
||||
.dw-db-ch__svg {
|
||||
display: block;
|
||||
max-width: none;
|
||||
overflow: visible;
|
||||
font-family: inherit;
|
||||
}
|
||||
.dw-db-ch__grid {
|
||||
stroke: var(--color-line);
|
||||
stroke-width: 1;
|
||||
}
|
||||
.dw-db-ch__tick,
|
||||
.dw-db-ch__label {
|
||||
fill: var(--color-ink-muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
.dw-db-ch__value {
|
||||
fill: var(--color-ink);
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.dw-db-ch__bar {
|
||||
fill: var(--dw-c, var(--color-accent));
|
||||
opacity: 0.85;
|
||||
}
|
||||
.dw-db-ch__bar:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
.dw-db-ch__line {
|
||||
fill: none;
|
||||
stroke: var(--color-accent);
|
||||
stroke-width: 2;
|
||||
stroke-linejoin: round;
|
||||
}
|
||||
.dw-db-ch__dot {
|
||||
fill: var(--color-surface);
|
||||
stroke: var(--color-accent);
|
||||
stroke-width: 2;
|
||||
}
|
||||
.dw-db-ch__pie {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 16px 32px;
|
||||
}
|
||||
.dw-db-ch__slice {
|
||||
fill: none;
|
||||
stroke: var(--dw-c, var(--color-accent));
|
||||
stroke-width: 28;
|
||||
}
|
||||
.dw-db-ch__slice:hover {
|
||||
stroke-width: 32;
|
||||
}
|
||||
.dw-db-ch__total {
|
||||
fill: var(--color-ink);
|
||||
font-size: 22px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.dw-db-ch__legend {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
font-size: 13px;
|
||||
}
|
||||
.dw-db-ch__legend li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
.dw-db-ch__swatch {
|
||||
flex: none;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 2px;
|
||||
background: var(--dw-c, var(--color-accent));
|
||||
}
|
||||
.dw-db-ch__name {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.dw-db-ch__num {
|
||||
margin-left: auto;
|
||||
padding-left: 12px;
|
||||
color: var(--color-ink-muted);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* ---- Timeline view ---- */
|
||||
.dw-db-tl {
|
||||
padding-top: 8px;
|
||||
@@ -2364,6 +2464,13 @@
|
||||
.dw-db-pop--panel {
|
||||
min-width: 20rem;
|
||||
}
|
||||
/* Parts of a panel that redraw themselves keep the panel's column layout. */
|
||||
.dw-db-pop__chart,
|
||||
.dw-db-pop__props {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
.dw-db-pop--choices {
|
||||
width: 18rem;
|
||||
}
|
||||
|
||||
@@ -916,7 +916,20 @@
|
||||
"earlier": "Früher",
|
||||
"later": "Später",
|
||||
"noStartColumn": "Füge eine Datumseigenschaft hinzu, um Einträge auf der Zeitleiste anzuordnen.",
|
||||
"dragEnd": "Ziehen, um das Enddatum zu ändern"
|
||||
"dragEnd": "Ziehen, um das Enddatum zu ändern",
|
||||
"viewChart": "Diagramm",
|
||||
"chartType": "Diagrammtyp",
|
||||
"chartBar": "Balken",
|
||||
"chartLine": "Linie",
|
||||
"chartDonut": "Ring",
|
||||
"chartX": "Einträge zeigen nach",
|
||||
"chartMeasure": "Messgröße",
|
||||
"chartCount": "Anzahl der Einträge",
|
||||
"chartSum": "Summe von",
|
||||
"chartAvg": "Durchschnitt von",
|
||||
"chartValue": "Zahleneigenschaft",
|
||||
"noChartAxis": "Füge eine Auswahl-, Kontrollkästchen-, Mitglieder- oder Datumseigenschaft hinzu, um Einträge danach darzustellen.",
|
||||
"noChartData": "Nichts darzustellen: Kein Eintrag hat hier einen Wert."
|
||||
},
|
||||
"edgeless": {
|
||||
"toolbar": "Werkzeuge der Tafel",
|
||||
|
||||
@@ -916,7 +916,20 @@
|
||||
"earlier": "Earlier",
|
||||
"later": "Later",
|
||||
"noStartColumn": "Add a date property to place records on the timeline.",
|
||||
"dragEnd": "Drag to change the end date"
|
||||
"dragEnd": "Drag to change the end date",
|
||||
"viewChart": "Chart",
|
||||
"chartType": "Chart type",
|
||||
"chartBar": "Bars",
|
||||
"chartLine": "Line",
|
||||
"chartDonut": "Donut",
|
||||
"chartX": "Show records by",
|
||||
"chartMeasure": "Measure",
|
||||
"chartCount": "Count of records",
|
||||
"chartSum": "Sum of",
|
||||
"chartAvg": "Average of",
|
||||
"chartValue": "Number property",
|
||||
"noChartAxis": "Add a select, checkbox, member or date property to chart records by.",
|
||||
"noChartData": "Nothing to chart: no record has a value here."
|
||||
},
|
||||
"edgeless": {
|
||||
"toolbar": "Canvas tools",
|
||||
|
||||
@@ -916,7 +916,20 @@
|
||||
"earlier": "Antes",
|
||||
"later": "Después",
|
||||
"noStartColumn": "Añade una propiedad de fecha para colocar los registros en el cronograma.",
|
||||
"dragEnd": "Arrastra para cambiar la fecha de fin"
|
||||
"dragEnd": "Arrastra para cambiar la fecha de fin",
|
||||
"viewChart": "Gráfico",
|
||||
"chartType": "Tipo de gráfico",
|
||||
"chartBar": "Barras",
|
||||
"chartLine": "Línea",
|
||||
"chartDonut": "Anillo",
|
||||
"chartX": "Mostrar registros por",
|
||||
"chartMeasure": "Medida",
|
||||
"chartCount": "Número de registros",
|
||||
"chartSum": "Suma de",
|
||||
"chartAvg": "Promedio de",
|
||||
"chartValue": "Propiedad numérica",
|
||||
"noChartAxis": "Añade una propiedad de selección, casilla, miembro o fecha para representar los registros.",
|
||||
"noChartData": "Nada que representar: ningún registro tiene un valor aquí."
|
||||
},
|
||||
"edgeless": {
|
||||
"toolbar": "Herramientas del lienzo",
|
||||
|
||||
@@ -916,7 +916,20 @@
|
||||
"earlier": "Plus tôt",
|
||||
"later": "Plus tard",
|
||||
"noStartColumn": "Ajoutez une propriété de date pour placer les enregistrements sur la chronologie.",
|
||||
"dragEnd": "Faites glisser pour changer la date de fin"
|
||||
"dragEnd": "Faites glisser pour changer la date de fin",
|
||||
"viewChart": "Graphique",
|
||||
"chartType": "Type de graphique",
|
||||
"chartBar": "Barres",
|
||||
"chartLine": "Courbe",
|
||||
"chartDonut": "Anneau",
|
||||
"chartX": "Afficher les enregistrements par",
|
||||
"chartMeasure": "Mesure",
|
||||
"chartCount": "Nombre d’enregistrements",
|
||||
"chartSum": "Somme de",
|
||||
"chartAvg": "Moyenne de",
|
||||
"chartValue": "Propriété numérique",
|
||||
"noChartAxis": "Ajoutez une propriété de sélection, case à cocher, membre ou date pour représenter les enregistrements.",
|
||||
"noChartData": "Rien à représenter : aucun enregistrement n’a de valeur ici."
|
||||
},
|
||||
"edgeless": {
|
||||
"toolbar": "Outils du tableau",
|
||||
|
||||
@@ -916,7 +916,20 @@
|
||||
"earlier": "Wcześniej",
|
||||
"later": "Później",
|
||||
"noStartColumn": "Dodaj właściwość daty, aby umieścić rekordy na osi czasu.",
|
||||
"dragEnd": "Przeciągnij, aby zmienić datę końca"
|
||||
"dragEnd": "Przeciągnij, aby zmienić datę końca",
|
||||
"viewChart": "Wykres",
|
||||
"chartType": "Typ wykresu",
|
||||
"chartBar": "Słupki",
|
||||
"chartLine": "Linia",
|
||||
"chartDonut": "Pierścień",
|
||||
"chartX": "Pokaż rekordy według",
|
||||
"chartMeasure": "Miara",
|
||||
"chartCount": "Liczba rekordów",
|
||||
"chartSum": "Suma",
|
||||
"chartAvg": "Średnia",
|
||||
"chartValue": "Właściwość liczbowa",
|
||||
"noChartAxis": "Dodaj właściwość wyboru, pola wyboru, członka lub daty, aby pokazać rekordy na wykresie.",
|
||||
"noChartData": "Nie ma czego pokazać: żaden rekord nie ma tu wartości."
|
||||
},
|
||||
"edgeless": {
|
||||
"toolbar": "Narzędzia tablicy",
|
||||
|
||||
Reference in new issue
Block a user