@blueshed/joined 0.0.0-stage → 0.1.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/skills/joined/SKILL.md +17 -0
- package/.claude/skills/joined/reference.md +768 -0
- package/LICENSE +19 -0
- package/README.md +115 -2
- package/docs/design.md +148 -0
- package/docs/introduction.md +193 -0
- package/docs/learning.md +76 -0
- package/docs/stories.md +82 -0
- package/examples/app.css +27 -0
- package/examples/cafe/books.html +38 -0
- package/examples/cafe/books.json +13 -0
- package/examples/cafe/books.ts +64 -0
- package/examples/cafe/cafe.css +512 -0
- package/examples/cafe/front.html +115 -0
- package/examples/cafe/front.ts +7 -0
- package/examples/cafe/generated/books.elements.ts +52 -0
- package/examples/cafe/generated/books.queries.ts +11 -0
- package/examples/cafe/generated/books.rules.ts +42 -0
- package/examples/cafe/generated/kitchen.elements.ts +87 -0
- package/examples/cafe/generated/kitchen.queries.ts +47 -0
- package/examples/cafe/generated/kitchen.rules.ts +98 -0
- package/examples/cafe/generated/menu.elements.ts +61 -0
- package/examples/cafe/generated/menu.queries.ts +28 -0
- package/examples/cafe/generated/menu.rules.ts +65 -0
- package/examples/cafe/generated/order.elements.ts +87 -0
- package/examples/cafe/generated/order.queries.ts +47 -0
- package/examples/cafe/generated/order.rules.ts +95 -0
- package/examples/cafe/generated/staff.elements.ts +55 -0
- package/examples/cafe/generated/staff.queries.ts +27 -0
- package/examples/cafe/generated/staff.rules.ts +59 -0
- package/examples/cafe/generated/supplies.elements.ts +62 -0
- package/examples/cafe/generated/supplies.queries.ts +43 -0
- package/examples/cafe/generated/supplies.rules.ts +84 -0
- package/examples/cafe/generated/till.elements.ts +93 -0
- package/examples/cafe/generated/till.queries.ts +57 -0
- package/examples/cafe/generated/till.rules.ts +113 -0
- package/examples/cafe/index.html +70 -0
- package/examples/cafe/kitchen.css +107 -0
- package/examples/cafe/kitchen.html +39 -0
- package/examples/cafe/kitchen.ts +125 -0
- package/examples/cafe/menu.html +55 -0
- package/examples/cafe/menu.json +41 -0
- package/examples/cafe/menu.ts +84 -0
- package/examples/cafe/migrations/001-cafe.ts +11 -0
- package/examples/cafe/order.html +37 -0
- package/examples/cafe/order.ts +45 -0
- package/examples/cafe/rail-drag.ts +30 -0
- package/examples/cafe/routes.ts +32 -0
- package/examples/cafe/staff.json +20 -0
- package/examples/cafe/stories.jsonl +43 -0
- package/examples/cafe/supplies.html +77 -0
- package/examples/cafe/supplies.json +33 -0
- package/examples/cafe/supplies.ts +170 -0
- package/examples/cafe/till.json +95 -0
- package/examples/cafe/till.ts +122 -0
- package/examples/cafe/trust.ts +20 -0
- package/examples/cafe/views.ts +171 -0
- package/examples/docs.ts +28 -0
- package/examples/film.jpg +0 -0
- package/examples/hello/generated/elements.ts +45 -0
- package/examples/hello/generated/queries.ts +24 -0
- package/examples/hello/generated/rules.ts +45 -0
- package/examples/hello/hello.css +27 -0
- package/examples/hello/hello.json +1 -0
- package/examples/hello/index.html +32 -0
- package/examples/hello/migrations/001-hello.ts +6 -0
- package/examples/hello/page.ts +49 -0
- package/examples/hello/routes.ts +6 -0
- package/examples/hello/stories.jsonl +3 -0
- package/examples/index.html +146 -0
- package/examples/page.ts +11 -0
- package/examples/people/adding.ts +20 -0
- package/examples/people/generated/elements.ts +68 -0
- package/examples/people/generated/queries.ts +28 -0
- package/examples/people/generated/rules.ts +85 -0
- package/examples/people/links.ts +124 -0
- package/examples/people/migrations/001-people.ts +6 -0
- package/examples/people/migrations/002-add-people-member-and-guard-people.ts +7 -0
- package/examples/people/migrations/003-add-people-rank-and-guard-people.ts +7 -0
- package/examples/people/order.ts +61 -0
- package/examples/people/people.css +65 -0
- package/examples/people/people.json +26 -0
- package/examples/people/routes.ts +12 -0
- package/examples/people/stories.jsonl +20 -0
- package/examples/people/trust.ts +14 -0
- package/examples/people/view.ts +115 -0
- package/examples/routes.ts +11 -0
- package/examples/trip/answer-rows.ts +70 -0
- package/examples/trip/answers.ts +11 -0
- package/examples/trip/bar.ts +89 -0
- package/examples/trip/calendar-map.css +709 -0
- package/examples/trip/calendar-map.ts +249 -0
- package/examples/trip/drags.ts +143 -0
- package/examples/trip/drawer.ts +250 -0
- package/examples/trip/event-form.ts +199 -0
- package/examples/trip/generated/elements.ts +144 -0
- package/examples/trip/generated/queries.ts +46 -0
- package/examples/trip/generated/rules.ts +239 -0
- package/examples/trip/holding.ts +61 -0
- package/examples/trip/ics.ts +117 -0
- package/examples/trip/index.html +82 -0
- package/examples/trip/line-stops.ts +92 -0
- package/examples/trip/line-words.ts +79 -0
- package/examples/trip/line.ts +121 -0
- package/examples/trip/map.ts +234 -0
- package/examples/trip/mercator.ts +28 -0
- package/examples/trip/migrations/001-trip.ts +7 -0
- package/examples/trip/migrations/002-add-events-zone-and-guard-events.ts +7 -0
- package/examples/trip/migrations/003-guard-events-and-create-events_asked-and-more.ts +9 -0
- package/examples/trip/migrations/004-create-stays.ts +6 -0
- package/examples/trip/migrations/005-guard-events-and-create-events_arrives-and-more.ts +8 -0
- package/examples/trip/month.ts +87 -0
- package/examples/trip/other-weeks.ts +67 -0
- package/examples/trip/page.ts +121 -0
- package/examples/trip/peek.ts +71 -0
- package/examples/trip/people-chips.ts +74 -0
- package/examples/trip/place-search.ts +51 -0
- package/examples/trip/places.ts +34 -0
- package/examples/trip/routes.ts +27 -0
- package/examples/trip/shell.ts +39 -0
- package/examples/trip/stays.css +51 -0
- package/examples/trip/stays.ts +68 -0
- package/examples/trip/stories.jsonl +72 -0
- package/examples/trip/time.ts +46 -0
- package/examples/trip/told.ts +48 -0
- package/examples/trip/trip.json +69 -0
- package/examples/trip/trust.ts +51 -0
- package/examples/trip/week.ts +237 -0
- package/examples/trip/words.ts +4 -0
- package/examples/trip/writes.ts +91 -0
- package/examples/trip/zones.ts +16 -0
- package/examples/trips/card.ts +149 -0
- package/examples/trips/generated/elements.ts +60 -0
- package/examples/trips/generated/queries.ts +28 -0
- package/examples/trips/generated/rules.ts +62 -0
- package/examples/trips/index.html +47 -0
- package/examples/trips/map.ts +52 -0
- package/examples/trips/migrations/001-trips.ts +8 -0
- package/examples/trips/new-trip.ts +46 -0
- package/examples/trips/page.ts +9 -0
- package/examples/trips/routes.ts +7 -0
- package/examples/trips/stories.jsonl +12 -0
- package/examples/trips/trips.css +183 -0
- package/examples/trips/trips.json +7 -0
- package/examples/weeks/derive.ts +23 -0
- package/examples/weeks/generated/elements.ts +52 -0
- package/examples/weeks/generated/rules.ts +33 -0
- package/examples/weeks/routes.ts +4 -0
- package/examples/weeks/weeks.json +1 -0
- package/examples/welcome.css +299 -0
- package/package.json +55 -4
- package/src/attachment.ts +70 -0
- package/src/cli.ts +52 -0
- package/src/client.ts +98 -0
- package/src/compile.ts +2034 -0
- package/src/css.d.ts +5 -0
- package/src/definitions.ts +268 -0
- package/src/demo.css +29 -0
- package/src/demo.ts +42 -0
- package/src/draft.ts +69 -0
- package/src/engine.ts +288 -0
- package/src/file-value.ts +13 -0
- package/src/files.ts +187 -0
- package/src/follow.ts +56 -0
- package/src/hues.ts +3 -0
- package/src/icon-names.ts +77 -0
- package/src/icon.png +0 -0
- package/src/icons.ts +32 -0
- package/src/keep.ts +33 -0
- package/src/link.ts +31 -0
- package/src/mcp.ts +252 -0
- package/src/members/demo.ts +53 -0
- package/src/members/generated/elements.ts +68 -0
- package/src/members/generated/queries.ts +29 -0
- package/src/members/generated/rules.ts +65 -0
- package/src/members/group.ts +294 -0
- package/src/members/keys.ts +221 -0
- package/src/members/members.json +9 -0
- package/src/members/migrations/001-members.ts +6 -0
- package/src/members/migrations/002-guard-members.ts +11 -0
- package/src/members/migrations/003-add-members-act-and-guard-members.ts +7 -0
- package/src/members/panel.css +208 -0
- package/src/members/panel.ts +398 -0
- package/src/members/routes.ts +4 -0
- package/src/members/stories.jsonl +27 -0
- package/src/members/trust.ts +116 -0
- package/src/migrate.ts +597 -0
- package/src/migrations/001-joined.ts +13 -0
- package/src/migrations/002-group-keys.ts +16 -0
- package/src/migrations/003-change-inverse.ts +10 -0
- package/src/migrations/004-change-followed.ts +6 -0
- package/src/ops.ts +61 -0
- package/src/page.css +79 -0
- package/src/page.ts +413 -0
- package/src/parts.css +471 -0
- package/src/parts.ts +152 -0
- package/src/server.ts +862 -0
- package/src/settings.ts +94 -0
- package/src/starter.ts +89 -0
- package/src/store.ts +815 -0
- package/src/stories.ts +387 -0
- package/src/toast.ts +52 -0
- package/src/together.ts +167 -0
- package/src/tokens.css +85 -0
- package/src/tokens.json +457 -0
- package/src/upkeep.ts +86 -0
- package/src/visitors.ts +43 -0
- package/src/write.ts +567 -0
- package/starter/CLAUDE.md +37 -0
- package/starter/gitignore +3 -0
- package/starter/tests/hello-page.test.ts +14 -0
- package/starter/tests/hello.test.ts +8 -0
- package/starter/tsconfig.json +17 -0
package/src/engine.ts
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
// The engine beneath the store: SQLite (bun:sqlite, in a file), or Postgres (PGlite, in a folder). Each answers the
|
|
2
|
+
// same calls, as bun:sqlite's own: a statement run, its rows got, a transaction (a savepoint, within one), and each
|
|
3
|
+
// synchronous, so a write is one transaction and nothing comes between its parts. PGlite answers at once by its
|
|
4
|
+
// wire protocol (a query sent whole, its values written into it as literals). What each refuses, in a constraint's
|
|
5
|
+
// name or a trigger's words, it throws as Refused; the rest as it was. Where the two say a thing differently, the
|
|
6
|
+
// dialect says which.
|
|
7
|
+
|
|
8
|
+
import { Database } from "bun:sqlite";
|
|
9
|
+
|
|
10
|
+
export type Dialect = "sqlite" | "postgres";
|
|
11
|
+
type Args = unknown[] | Record<string, unknown>;
|
|
12
|
+
/** A statement, as both engines prepare one: its first row, or all of them. */
|
|
13
|
+
export type Statement = { get(...args: unknown[]): any; all(...args: unknown[]): any[] };
|
|
14
|
+
export type Engine = {
|
|
15
|
+
dialect: Dialect;
|
|
16
|
+
run(sql: string, args?: Args): { changes: number };
|
|
17
|
+
query(sql: string): Statement;
|
|
18
|
+
/** fn in a transaction (a savepoint, inside one): its value, or what it threw, all of it undone. */
|
|
19
|
+
transaction<T>(fn: () => T): (() => T) & { immediate(): T };
|
|
20
|
+
/** The transaction's foreign keys held to at its commit, not each statement: rows that link to each other, put in
|
|
21
|
+
* together. */
|
|
22
|
+
defer(): void;
|
|
23
|
+
/** A table's columns, by name (none: no table). */
|
|
24
|
+
columns(table: string): string[];
|
|
25
|
+
/** The schema a connection's own tables are in (the rows a write changed). */
|
|
26
|
+
temp: string;
|
|
27
|
+
/** Let go: Postgres's once its folder is written (awaited, to open it again). */
|
|
28
|
+
close(): void | Promise<void>;
|
|
29
|
+
};
|
|
30
|
+
/** A refusal of the database's, in the words it was given: a constraint's name, or a trigger's message. */
|
|
31
|
+
export class Refused extends Error {}
|
|
32
|
+
|
|
33
|
+
/** SQLite: bun:sqlite's Database, as it is, its constraint failures thrown as Refused. */
|
|
34
|
+
export function sqlite(file: string, { readonly = false } = {}): Engine {
|
|
35
|
+
const db = new Database(file, readonly ? { readonly, strict: true } : { create: true, strict: true });
|
|
36
|
+
if (!readonly) db.run("PRAGMA journal_mode = WAL");
|
|
37
|
+
db.run("PRAGMA busy_timeout = 5000");
|
|
38
|
+
// a link is a foreign key: what it points at is there, and isn't removed from under it
|
|
39
|
+
db.run("PRAGMA foreign_keys = ON");
|
|
40
|
+
// a value's form, as a guard asks it: a regular expression, matched (SQLite has no REGEXP of its own)
|
|
41
|
+
db.function("regexp", { deterministic: true }, (form: string, v: unknown) =>
|
|
42
|
+
typeof v === "string" && new RegExp(form).test(v) ? 1 : 0,
|
|
43
|
+
);
|
|
44
|
+
// a time and a length on (an ISO 8601 duration, in days, hours, minutes and seconds), as a wall clock: where
|
|
45
|
+
// something ends, as a window that holds what overlaps it asks (Postgres adds its interval)
|
|
46
|
+
db.function("ends", { deterministic: true }, (start: unknown, length: unknown) => {
|
|
47
|
+
const [d = 0, h = 0, m = 0, s = 0] =
|
|
48
|
+
/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/
|
|
49
|
+
.exec(String(length))
|
|
50
|
+
?.slice(1)
|
|
51
|
+
.map((n) => Number(n ?? 0)) ?? [];
|
|
52
|
+
const at = Date.parse(`${start}Z`);
|
|
53
|
+
return Number.isFinite(at)
|
|
54
|
+
? new Date(at + (((d * 24 + h) * 60 + m) * 60 + s) * 1000).toISOString().slice(0, 19)
|
|
55
|
+
: null;
|
|
56
|
+
});
|
|
57
|
+
const said = <T>(f: () => T): T => {
|
|
58
|
+
try {
|
|
59
|
+
return f();
|
|
60
|
+
} catch (e) {
|
|
61
|
+
if (e instanceof Error && String((e as { code?: string }).code).startsWith("SQLITE_CONSTRAINT"))
|
|
62
|
+
throw new Refused(e.message.replace(/^CHECK constraint failed: /, ""));
|
|
63
|
+
throw e;
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
return {
|
|
67
|
+
dialect: "sqlite",
|
|
68
|
+
run: (sql, args) => said(() => (args === undefined ? db.run(sql) : db.run(sql, args as never))),
|
|
69
|
+
query(sql) {
|
|
70
|
+
const s = db.query(sql);
|
|
71
|
+
return {
|
|
72
|
+
get: (...args) => said(() => s.get(...(args as never[]))),
|
|
73
|
+
all: (...args) => said(() => s.all(...(args as never[]))),
|
|
74
|
+
};
|
|
75
|
+
},
|
|
76
|
+
transaction: (fn) => db.transaction(fn) as never,
|
|
77
|
+
defer: () => db.run("PRAGMA defer_foreign_keys = ON"),
|
|
78
|
+
columns: (table) =>
|
|
79
|
+
(db.query("SELECT name FROM pragma_table_info(?)").all(table) as { name: string }[]).map((c) => c.name),
|
|
80
|
+
temp: "temp",
|
|
81
|
+
close: () => db.close(),
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** An empty database, as PGlite's files: each one in memory begun from it, not made anew (a fifth of the time). */
|
|
86
|
+
let blank: Promise<Blob> | undefined;
|
|
87
|
+
/** Postgres: PGlite in a folder (none: in memory), answered at once by its wire protocol. */
|
|
88
|
+
export async function postgres(dir?: string): Promise<Engine> {
|
|
89
|
+
const { PGlite } = await import("@electric-sql/pglite");
|
|
90
|
+
const pg = dir
|
|
91
|
+
? await PGlite.create(dir)
|
|
92
|
+
: await PGlite.create({
|
|
93
|
+
loadDataDir: await (blank ??= PGlite.create().then(async (empty) => {
|
|
94
|
+
const files = await empty.dumpDataDir("none");
|
|
95
|
+
await empty.close();
|
|
96
|
+
return files;
|
|
97
|
+
})),
|
|
98
|
+
});
|
|
99
|
+
let depth = 0;
|
|
100
|
+
const exec = (sql: string) => {
|
|
101
|
+
const out = parse(pg.execProtocolRawSync(message(sql)));
|
|
102
|
+
if (out.error) {
|
|
103
|
+
const { C: code = "", M: words = "", n: constraint } = out.error;
|
|
104
|
+
// a CHECK named for its words, a unique set's, or a trigger's RAISE: refused, in those words
|
|
105
|
+
if (code === "P0001") throw new Refused(words);
|
|
106
|
+
if (code.startsWith("23")) throw new Refused(code === "23514" && constraint ? constraint : words);
|
|
107
|
+
throw new Error(`${words} (${code}): ${sql.slice(0, 200)}`);
|
|
108
|
+
}
|
|
109
|
+
return out;
|
|
110
|
+
};
|
|
111
|
+
const rows = (sql: string, args: unknown[]) => {
|
|
112
|
+
const { fields, types, rows } = exec(bind(sql, args));
|
|
113
|
+
return rows.map((r) => Object.fromEntries(r.map((v, i) => [fields[i]!, typed(types[i]!, v)])));
|
|
114
|
+
};
|
|
115
|
+
return {
|
|
116
|
+
dialect: "postgres",
|
|
117
|
+
run: (sql, args) => ({ changes: exec(bind(sql, args === undefined ? [] : [args].flat())).changes }),
|
|
118
|
+
query: (sql) => ({
|
|
119
|
+
get: (...args) => rows(sql, args)[0] ?? null,
|
|
120
|
+
all: (...args) => rows(sql, args),
|
|
121
|
+
}),
|
|
122
|
+
transaction(fn) {
|
|
123
|
+
const run = () => {
|
|
124
|
+
const at = depth++;
|
|
125
|
+
exec(at ? `SAVEPOINT joined_${at}` : "BEGIN");
|
|
126
|
+
try {
|
|
127
|
+
const done = fn();
|
|
128
|
+
exec(at ? `RELEASE SAVEPOINT joined_${at}` : "COMMIT");
|
|
129
|
+
return done;
|
|
130
|
+
} catch (e) {
|
|
131
|
+
exec(at ? `ROLLBACK TO SAVEPOINT joined_${at}` : "ROLLBACK");
|
|
132
|
+
throw e;
|
|
133
|
+
} finally {
|
|
134
|
+
depth--;
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
return Object.assign(run, { immediate: run });
|
|
138
|
+
},
|
|
139
|
+
defer: () => void exec("SET CONSTRAINTS ALL DEFERRED"),
|
|
140
|
+
columns: (table) =>
|
|
141
|
+
rows(
|
|
142
|
+
"SELECT column_name AS name FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = ? ORDER BY ordinal_position",
|
|
143
|
+
[table],
|
|
144
|
+
).map((c) => c.name as string),
|
|
145
|
+
temp: "pg_temp",
|
|
146
|
+
close: () => pg.close(),
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The store's engine: Postgres (PGlite) in a folder, or SQLite in a file; either in memory (":memory:"). */
|
|
151
|
+
export const open = (db: string, kind: Dialect) =>
|
|
152
|
+
kind === "postgres" ? postgres(db === ":memory:" ? undefined : db) : Promise.resolve(sqlite(db));
|
|
153
|
+
|
|
154
|
+
/** A trigger: before or after an event on a table, its body run where `when` holds; SQLite's a connection's own
|
|
155
|
+
* (`temp`: made again as it opens). */
|
|
156
|
+
export type Trigger = {
|
|
157
|
+
name: string;
|
|
158
|
+
at: "BEFORE" | "AFTER";
|
|
159
|
+
event: string;
|
|
160
|
+
table: string;
|
|
161
|
+
when?: string;
|
|
162
|
+
body: string;
|
|
163
|
+
temp?: boolean;
|
|
164
|
+
};
|
|
165
|
+
/** A trigger, as each says it: SQLite's a statement, Postgres's a function, made again in place. */
|
|
166
|
+
export function triggerSql(dialect: Dialect, t: Trigger) {
|
|
167
|
+
const q = (n: string) => `"${n.replaceAll('"', '""')}"`;
|
|
168
|
+
if (dialect === "sqlite")
|
|
169
|
+
return `CREATE ${t.temp ? "TEMP " : ""}TRIGGER IF NOT EXISTS ${q(t.name)} ${t.at} ${t.event} ON ${t.temp ? "main." : ""}${q(t.table)}${t.when ? ` WHEN ${t.when}` : ""} BEGIN ${t.body} END`;
|
|
170
|
+
const body = t.when ? `IF ${t.when} THEN ${t.body} END IF;` : t.body;
|
|
171
|
+
return `CREATE OR REPLACE FUNCTION ${q(`${t.name}_fn`)}() RETURNS trigger LANGUAGE plpgsql AS $joined$ BEGIN ${body} IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; RETURN NEW; END $joined$; CREATE OR REPLACE TRIGGER ${q(t.name)} ${t.at} ${t.event} ON ${q(t.table)} FOR EACH ROW EXECUTE FUNCTION ${q(`${t.name}_fn`)}()`;
|
|
172
|
+
}
|
|
173
|
+
/** A trigger's statement refusing a change where `cond` holds, in its words (SQL of a string). */
|
|
174
|
+
export const refuseSql = (dialect: Dialect, cond: string, words: string) =>
|
|
175
|
+
dialect === "sqlite"
|
|
176
|
+
? `SELECT RAISE(ABORT, ${words}) WHERE ${cond};`
|
|
177
|
+
: `IF ${cond} THEN RAISE EXCEPTION '%', ${words}; END IF;`;
|
|
178
|
+
/** A trigger made by triggerSql, dropped: its name, and on Postgres its table. */
|
|
179
|
+
export function dropTriggerSql(dialect: Dialect, sql: string) {
|
|
180
|
+
const [, name, table] = /TRIGGER (?:IF NOT EXISTS )?("(?:[^"]|"")+") .*? ON (?:main\.)?("(?:[^"]|"")+")/.exec(sql)!;
|
|
181
|
+
return dialect === "sqlite" ? `DROP TRIGGER IF EXISTS ${name}` : `DROP TRIGGER IF EXISTS ${name} ON ${table}`;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** A simple query, as Postgres's wire protocol says it: Q, its length, the SQL, a nul. */
|
|
185
|
+
function message(sql: string) {
|
|
186
|
+
const body = new TextEncoder().encode(`${sql}\0`);
|
|
187
|
+
const m = new Uint8Array(5 + body.length);
|
|
188
|
+
m[0] = 81;
|
|
189
|
+
new DataView(m.buffer).setInt32(1, 4 + body.length);
|
|
190
|
+
m.set(body, 5);
|
|
191
|
+
return m;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** What Postgres answered: the last statement's fields, their types and rows (text, or null), how many it changed, and
|
|
195
|
+
* an error's fields (C its code, M its message, n its constraint). */
|
|
196
|
+
function parse(b: Uint8Array) {
|
|
197
|
+
const v = new DataView(b.buffer, b.byteOffset, b.byteLength),
|
|
198
|
+
text = new TextDecoder();
|
|
199
|
+
const out = { fields: [] as string[], types: [] as number[], rows: [] as (string | null)[][], changes: 0 } as {
|
|
200
|
+
fields: string[];
|
|
201
|
+
types: number[];
|
|
202
|
+
rows: (string | null)[][];
|
|
203
|
+
changes: number;
|
|
204
|
+
error?: Record<string, string>;
|
|
205
|
+
};
|
|
206
|
+
for (let i = 0; i < b.length;) {
|
|
207
|
+
const kind = String.fromCharCode(b[i]!),
|
|
208
|
+
at = i + 5;
|
|
209
|
+
i += 1 + v.getInt32(i + 1);
|
|
210
|
+
if (kind === "T") {
|
|
211
|
+
((out.fields = []), (out.types = []), (out.rows = []));
|
|
212
|
+
for (let n = v.getInt16(at), p = at + 2; n > 0; n--) {
|
|
213
|
+
const z = b.indexOf(0, p);
|
|
214
|
+
out.fields.push(text.decode(b.subarray(p, z)));
|
|
215
|
+
out.types.push(v.getInt32(z + 7));
|
|
216
|
+
p = z + 19;
|
|
217
|
+
}
|
|
218
|
+
} else if (kind === "D") {
|
|
219
|
+
const row: (string | null)[] = [];
|
|
220
|
+
for (let n = v.getInt16(at), p = at + 2; n > 0; n--) {
|
|
221
|
+
const len = v.getInt32(p);
|
|
222
|
+
p += 4;
|
|
223
|
+
row.push(len < 0 ? null : text.decode(b.subarray(p, (p += len))));
|
|
224
|
+
}
|
|
225
|
+
out.rows.push(row);
|
|
226
|
+
} else if (kind === "C") out.changes = Number(/ (\d+)$/.exec(text.decode(b.subarray(at, i - 1)))?.[1] ?? 0);
|
|
227
|
+
else if (kind === "E") {
|
|
228
|
+
const error: Record<string, string> = {};
|
|
229
|
+
for (let p = at; b[p] !== 0;) {
|
|
230
|
+
const z = b.indexOf(0, p + 1);
|
|
231
|
+
error[String.fromCharCode(b[p]!)] = text.decode(b.subarray(p + 1, z));
|
|
232
|
+
p = z + 1;
|
|
233
|
+
}
|
|
234
|
+
out.error ??= error;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return out;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** A value as its type says: a whole number or any number as a number, a boolean as one; anything else its text. */
|
|
241
|
+
function typed(type: number, v: string | null) {
|
|
242
|
+
if (v === null) return null;
|
|
243
|
+
if ([20, 21, 23, 700, 701, 1700].includes(type)) return Number(v);
|
|
244
|
+
if (type === 16) return v === "t";
|
|
245
|
+
return v;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** SQL with its values written into it as literals: each ? the next of a list, each $name an object's, outside
|
|
249
|
+
* quotes, quoted names and dollar-quoted bodies. */
|
|
250
|
+
export function bind(sql: string, args: unknown[]): string {
|
|
251
|
+
const named = args.length === 1 && args[0] && typeof args[0] === "object" && !Array.isArray(args[0]);
|
|
252
|
+
const values = named ? (args[0] as Record<string, unknown>) : null;
|
|
253
|
+
let n = 0,
|
|
254
|
+
out = "";
|
|
255
|
+
for (let i = 0; i < sql.length;) {
|
|
256
|
+
const c = sql[i]!;
|
|
257
|
+
if (c === "'" || c === '"') {
|
|
258
|
+
// a quote doubled is one, inside
|
|
259
|
+
let j = sql.indexOf(c, i + 1);
|
|
260
|
+
while (sql[j + 1] === c) j = sql.indexOf(c, j + 2);
|
|
261
|
+
out += sql.slice(i, j + 1);
|
|
262
|
+
i = j + 1;
|
|
263
|
+
} else if (c === "$") {
|
|
264
|
+
const tag = /^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(sql.slice(i));
|
|
265
|
+
if (tag) {
|
|
266
|
+
const end = sql.indexOf(tag[0], i + tag[0].length) + tag[0].length;
|
|
267
|
+
out += sql.slice(i, end);
|
|
268
|
+
i = end;
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
const name = /^\$([A-Za-z_][A-Za-z0-9_]*)/.exec(sql.slice(i));
|
|
272
|
+
if (name && values) {
|
|
273
|
+
out += literal(values[name[1]!] ?? null);
|
|
274
|
+
i += name[0].length;
|
|
275
|
+
} else ((out += c), i++);
|
|
276
|
+
} else if (c === "?" && !values) ((out += literal(args[n++] ?? null)), i++);
|
|
277
|
+
else ((out += c), i++);
|
|
278
|
+
}
|
|
279
|
+
return out;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** A value as a literal: a number as it is, a boolean as 1 or 0 (as SQLite keeps one), a string quoted. */
|
|
283
|
+
function literal(v: unknown): string {
|
|
284
|
+
if (v === null || v === undefined) return "NULL";
|
|
285
|
+
if (typeof v === "number") return Number.isFinite(v) ? String(v) : "NULL";
|
|
286
|
+
if (typeof v === "boolean") return v ? "1" : "0";
|
|
287
|
+
return `'${String(v).replaceAll("'", "''")}'`;
|
|
288
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// A file field's value, as the page and the server both read it: `file:<its name>` (the compiler's file form), served
|
|
2
|
+
// at /files/<its name>; and the most a file may be as it's sent, which the page asks before it sends one and the server
|
|
3
|
+
// again as it comes (src/files.ts).
|
|
4
|
+
|
|
5
|
+
/** The most a file may be as it's sent, in bytes: a phone's photo, or a long PDF. */
|
|
6
|
+
export const MOST = 20 * 1024 * 1024;
|
|
7
|
+
/** The most, in words a refusal says. */
|
|
8
|
+
export const TOO_BIG = `That file is too big: under ${MOST / 1024 / 1024} MB, please.`;
|
|
9
|
+
|
|
10
|
+
/** A file field's value's name: `file:<name>`'s. */
|
|
11
|
+
export const fileName = (value: string) => value.slice("file:".length);
|
|
12
|
+
/** Where a file field's value is served: `file:<name>` at /files/<name>. */
|
|
13
|
+
export const fileUrl = (value: string) => `/files/${fileName(value)}`;
|
package/src/files.ts
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
// A file a document names: a photo, an SVG or a PDF, its field's value `file:<its SHA-256>.<ext>` (the compiler's file form),
|
|
2
|
+
// kept in a folder, files/ beside the store, or a bucket (JOINED_FILES: `s3://<bucket>/<prefix>`), and served at
|
|
3
|
+
// /files/<its name>. Its name is its content's hash, so
|
|
4
|
+
// it never changes and is cached for good; the same file sent twice is kept once. A photo is kept as a WebP at most
|
|
5
|
+
// 1600px on its longer side (Bun.Image, nothing to install), which carries no EXIF, so no one's home is in it (the
|
|
6
|
+
// lineage's way: idea-cards' photos); a PDF as it came; an SVG too, as it came (Bun.Image can't read one, and drawn
|
|
7
|
+
// it would lose being sharp at every size), served sandboxed, since one opened by its path is a page of the site's and
|
|
8
|
+
// may hold a script (an <img> never runs it). A picture is refused by the size its header claims before it's
|
|
9
|
+
// decoded, and decoded one at a time, so a few small files claiming huge pictures can't take the server's memory. A
|
|
10
|
+
// JPEG, PNG, WebP or GIF is read everywhere; a HEIC or an AVIF only where the system can (a Mac, not Linux). Anyone
|
|
11
|
+
// may be sent one by its name, as a page's picture is: only who sees the item naming it is given that. Only someone
|
|
12
|
+
// who may put a file in a document may send one for it (the server asks that: `may`). A file no item names, nor any
|
|
13
|
+
// change kept (an undo puts it back), is let go by the store's upkeep once it's older than the history (and the week of
|
|
14
|
+
// backups, which may name it), so a file chosen and never saved goes too (`letGo`). A Postgres store's upkeep isn't
|
|
15
|
+
// joined's, so neither is letting its files go.
|
|
16
|
+
|
|
17
|
+
import { existsSync, readdirSync, statSync, unlinkSync } from "node:fs";
|
|
18
|
+
import type { BunFile, S3File, S3Options } from "bun";
|
|
19
|
+
import type { Engine } from "./engine.ts";
|
|
20
|
+
import { fileName, MOST, TOO_BIG } from "./file-value.ts";
|
|
21
|
+
import type { Type } from "./ops.ts";
|
|
22
|
+
|
|
23
|
+
/** A photo's longer side as it's kept, in px: a post at its widest on a wide screen. */
|
|
24
|
+
const WIDE = 1600;
|
|
25
|
+
/** The most pixels a picture may have: a 48-megapixel phone's photo (8064 × 6048) is under it. Decoded, a picture
|
|
26
|
+
* takes four bytes a pixel, 200 MB at most, and only one is decoded at a time. */
|
|
27
|
+
const PIXELS = 50_000_000;
|
|
28
|
+
/** The photos being made WebPs: one at a time, each after the last, whatever became of it. */
|
|
29
|
+
let making: Promise<unknown> = Promise.resolve();
|
|
30
|
+
/** An SVG, by how it opens: its XML line, comments and doctype, if any, then its <svg>. A page holding one isn't. */
|
|
31
|
+
const SVG = /^\s*(?:<\?xml[^>]*\?>\s*|<!--[\s\S]*?-->\s*|<!DOCTYPE[^>[]*(?:\[[\s\S]*?\])?>\s*)*<svg[\s>]/i;
|
|
32
|
+
/** What each kind kept is served as. */
|
|
33
|
+
const TYPES: Record<string, string> = { pdf: "application/pdf", svg: "image/svg+xml", webp: "image/webp" };
|
|
34
|
+
/** An SVG opened by its path is a page of the site's own: sandboxed, nothing in it runs or loads anything. */
|
|
35
|
+
const SANDBOX = "sandbox; default-src 'none'; style-src 'unsafe-inline'";
|
|
36
|
+
/** A kept file's name: its content's SHA-256, and its type's extension (the compiler's file form, after `file:`). */
|
|
37
|
+
const NAME = /^[0-9a-f]{64}\.[a-z0-9]{1,8}$/;
|
|
38
|
+
/** Each file a value names, in any text: a change's ops. */
|
|
39
|
+
const NAMED = new RegExp(`file:(${NAME.source.slice(1, -1)})`, "g");
|
|
40
|
+
|
|
41
|
+
/** Where the files are kept, a folder or a bucket, each asked the same three things: a file by its name (to write,
|
|
42
|
+
* to ask whether it's there, to send), each file kept with when it was, and one let go. */
|
|
43
|
+
export type Files = {
|
|
44
|
+
file(name: string): BunFile | S3File;
|
|
45
|
+
each(): AsyncIterable<{ name: string; at: number }>;
|
|
46
|
+
drop(name: string): Promise<unknown>;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
/** The files at `where`: a folder, or a bucket, `s3://<bucket>/<prefix>`, by Bun's S3 client (its keys, endpoint
|
|
50
|
+
* and region from S3_* or AWS_* in the environment, or `s3`). */
|
|
51
|
+
export function filesAt(where: string, s3?: S3Options): Files {
|
|
52
|
+
const bucket = /^s3:\/\/([^/]+)\/?(.*)$/.exec(where);
|
|
53
|
+
if (!bucket)
|
|
54
|
+
return {
|
|
55
|
+
file: (name) => Bun.file(`${where}/${name}`),
|
|
56
|
+
// (none sent yet: no folder)
|
|
57
|
+
async *each() {
|
|
58
|
+
for (const name of existsSync(where) ? readdirSync(where) : [])
|
|
59
|
+
yield { name, at: statSync(`${where}/${name}`).mtimeMs };
|
|
60
|
+
},
|
|
61
|
+
drop: async (name) => unlinkSync(`${where}/${name}`),
|
|
62
|
+
};
|
|
63
|
+
const client = new Bun.S3Client({ ...s3, bucket: bucket[1] }),
|
|
64
|
+
prefix = bucket[2] && !bucket[2].endsWith("/") ? `${bucket[2]}/` : bucket[2]!;
|
|
65
|
+
return {
|
|
66
|
+
file: (name) => client.file(prefix + name),
|
|
67
|
+
async *each() {
|
|
68
|
+
let continuationToken: string | undefined;
|
|
69
|
+
do {
|
|
70
|
+
const page = await client.list({ prefix, continuationToken });
|
|
71
|
+
for (const { key, lastModified } of page.contents ?? [])
|
|
72
|
+
yield { name: key.slice(prefix.length), at: Date.parse(lastModified ?? "") };
|
|
73
|
+
continuationToken = page.isTruncated ? page.nextContinuationToken : undefined;
|
|
74
|
+
} while (continuationToken);
|
|
75
|
+
},
|
|
76
|
+
drop: (name) => client.delete(prefix + name),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** A file kept: its value for a field; or refused, why, in a word for the page. */
|
|
81
|
+
export type Kept = { file: string } | { refused: string };
|
|
82
|
+
|
|
83
|
+
/** A file sent, kept by its content's hash in `files`: a photo made a WebP, an SVG and a PDF as they are; anything
|
|
84
|
+
* else refused. */
|
|
85
|
+
export async function keep(files: Files, bytes: Uint8Array): Promise<Kept> {
|
|
86
|
+
if (!bytes.length) return { refused: "That file is empty." };
|
|
87
|
+
if (bytes.length > MOST) return { refused: TOO_BIG };
|
|
88
|
+
const head = new TextDecoder().decode(bytes.subarray(0, 1024));
|
|
89
|
+
let out = bytes,
|
|
90
|
+
ext = head.startsWith("%PDF-") ? "pdf" : SVG.test(head) ? "svg" : "";
|
|
91
|
+
if (!ext)
|
|
92
|
+
try {
|
|
93
|
+
const made = making.then(() =>
|
|
94
|
+
new Bun.Image(bytes, { maxPixels: PIXELS })
|
|
95
|
+
.resize(WIDE, WIDE, { fit: "inside", withoutEnlargement: true })
|
|
96
|
+
.webp({ quality: 80 })
|
|
97
|
+
.bytes(),
|
|
98
|
+
);
|
|
99
|
+
making = made.catch(() => {});
|
|
100
|
+
[out, ext] = [await made, "webp"];
|
|
101
|
+
} catch (e) {
|
|
102
|
+
// (more pixels than PIXELS is said by the picture's header, before anything is decoded)
|
|
103
|
+
return {
|
|
104
|
+
refused:
|
|
105
|
+
(e as { code?: string }).code === "ERR_IMAGE_TOO_MANY_PIXELS"
|
|
106
|
+
? `That picture is too big: under ${PIXELS / 1_000_000} megapixels, please.`
|
|
107
|
+
: "joined keeps a photo (JPEG, PNG, WebP or GIF), an SVG or a PDF: that's none of them.",
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
const name = `${new Bun.CryptoHasher("sha256").update(out).digest("hex")}.${ext}`;
|
|
111
|
+
// written, kept already or not: the same bytes, its age started again, so upkeep doesn't let it go before it's saved
|
|
112
|
+
await files.file(name).write(out);
|
|
113
|
+
return { file: `file:${name}` };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Whether what someone may do in a document (its `may`, by collection and key) puts a file in it: an add to a
|
|
117
|
+
* collection with a file field, or a replace of one. */
|
|
118
|
+
export const putsFile = (
|
|
119
|
+
collections: Record<string, { fields: Record<string, Type> }>,
|
|
120
|
+
may: Record<string, Record<string, string>>,
|
|
121
|
+
) =>
|
|
122
|
+
Object.entries(collections).some(([coll, c]) => {
|
|
123
|
+
const files = Object.keys(c.fields).filter((f) => c.fields[f] === "file");
|
|
124
|
+
return (
|
|
125
|
+
!!files.length &&
|
|
126
|
+
Object.values(may[coll] ?? {}).some((tokens) =>
|
|
127
|
+
tokens.split(" ").some((t) => t === "add" || files.some((f) => t === `replace:${f}`)),
|
|
128
|
+
)
|
|
129
|
+
);
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
/** The routes: a file sent for a document (`POST /files?doc=board:1`, its bytes the body), by whoever `may` lets (why
|
|
133
|
+
* not, or null), one that says it's too big refused before it's read; and a file kept, by its name, with its type,
|
|
134
|
+
* cached for good. */
|
|
135
|
+
export function routes(files: Files, may: (req: Request, doc: string) => Promise<string | null>) {
|
|
136
|
+
return {
|
|
137
|
+
"/files": {
|
|
138
|
+
POST: async (req: Request) => {
|
|
139
|
+
const why = await may(req, new URL(req.url).searchParams.get("doc") ?? "");
|
|
140
|
+
if (why) return Response.json({ refused: why }, { status: 403 });
|
|
141
|
+
if (Number(req.headers.get("content-length")) > MOST)
|
|
142
|
+
return Response.json({ refused: TOO_BIG }, { status: 413 });
|
|
143
|
+
const kept = await keep(files, new Uint8Array(await req.arrayBuffer()));
|
|
144
|
+
return Response.json(kept, { status: "refused" in kept ? 422 : 200 });
|
|
145
|
+
},
|
|
146
|
+
},
|
|
147
|
+
"/files/:name": async (req: Request & { params: { name: string } }) => {
|
|
148
|
+
const { name } = req.params,
|
|
149
|
+
file = files.file(name);
|
|
150
|
+
return NAME.test(name) && (await file.exists())
|
|
151
|
+
? new Response(file.stream(), {
|
|
152
|
+
headers: {
|
|
153
|
+
"content-type": TYPES[name.split(".").at(-1)!] ?? "application/octet-stream",
|
|
154
|
+
"cache-control": "public, max-age=31536000, immutable",
|
|
155
|
+
"x-content-type-options": "nosniff",
|
|
156
|
+
...(name.endsWith(".svg") ? { "content-security-policy": SANDBOX } : {}),
|
|
157
|
+
},
|
|
158
|
+
})
|
|
159
|
+
: new Response("Not found", { status: 404 });
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Each file the store names: in an item's file field now, or in a change it keeps, which an undo may put back. */
|
|
165
|
+
export function named(db: Engine, rules: { collections: Record<string, { fields: Record<string, Type> }> }[]) {
|
|
166
|
+
const names = new Set<string>();
|
|
167
|
+
for (const { collections } of rules)
|
|
168
|
+
for (const [coll, c] of Object.entries(collections))
|
|
169
|
+
for (const f of Object.keys(c.fields).filter((f) => c.fields[f] === "file"))
|
|
170
|
+
for (const { v } of db.query(`SELECT "${f}" AS v FROM "${coll}" WHERE "${f}" IS NOT NULL`).all())
|
|
171
|
+
names.add(fileName(String(v)));
|
|
172
|
+
for (const { ops } of db
|
|
173
|
+
.query(
|
|
174
|
+
"SELECT CAST(ops AS TEXT) || ' ' || COALESCE(CAST(inverse AS TEXT), '') AS ops FROM changes WHERE CAST(ops AS TEXT) LIKE '%file:%' OR CAST(inverse AS TEXT) LIKE '%file:%'",
|
|
175
|
+
)
|
|
176
|
+
.all())
|
|
177
|
+
for (const [, name] of String(ops).matchAll(NAMED)) names.add(name!);
|
|
178
|
+
return names;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** The files nothing names, kept before a time (ms), let go; how many. */
|
|
182
|
+
export async function letGo(files: Files, names: Set<string>, before: number) {
|
|
183
|
+
let gone = 0;
|
|
184
|
+
for await (const { name, at } of files.each())
|
|
185
|
+
if (NAME.test(name) && !names.has(name) && at < before) (await files.drop(name), gone++);
|
|
186
|
+
return gone;
|
|
187
|
+
}
|
package/src/follow.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// A drag, as a finger or a mouse gives it: pointer events, never HTML drag and drop (joined/follow: the trip's blocks
|
|
2
|
+
// and pins, the people's order).
|
|
3
|
+
|
|
4
|
+
/** Follow a press to its release: each move, then its end; a cancelled press only ends. */
|
|
5
|
+
export function follow(down: PointerEvent, move: (e: PointerEvent) => void, end: (e: PointerEvent | null) => void) {
|
|
6
|
+
down.preventDefault();
|
|
7
|
+
down.stopPropagation();
|
|
8
|
+
const stop = (e: PointerEvent | null) => {
|
|
9
|
+
removeEventListener("pointermove", move);
|
|
10
|
+
removeEventListener("pointerup", up);
|
|
11
|
+
removeEventListener("pointercancel", cancel);
|
|
12
|
+
end(e);
|
|
13
|
+
};
|
|
14
|
+
const up = (e: PointerEvent) => stop(e),
|
|
15
|
+
cancel = () => stop(null);
|
|
16
|
+
addEventListener("pointermove", move);
|
|
17
|
+
addEventListener("pointerup", up);
|
|
18
|
+
addEventListener("pointercancel", cancel);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const HOLD = 400; // ms a finger is held still to pick a thing up
|
|
22
|
+
const STILL = 8; // px a held finger may wander
|
|
23
|
+
|
|
24
|
+
/** A press that picks a thing up (docs/design.md, "What a drag does"): a mouse's at once; a finger's once it's been
|
|
25
|
+
* held still a moment, so a swipe still scrolls the page (or, given, does what a swipe does there instead), and a
|
|
26
|
+
* tap is a tap (given what one does). Picked up, the page stays put under the finger until it's let go. */
|
|
27
|
+
export function held(down: PointerEvent, pick: () => void, swipe?: () => void, tap?: () => void) {
|
|
28
|
+
if (down.pointerType !== "touch") return pick();
|
|
29
|
+
const stop = () => {
|
|
30
|
+
clearTimeout(timer);
|
|
31
|
+
removeEventListener("pointermove", wander);
|
|
32
|
+
removeEventListener("pointerup", up);
|
|
33
|
+
removeEventListener("pointercancel", stop);
|
|
34
|
+
};
|
|
35
|
+
const up = () => (stop(), tap?.());
|
|
36
|
+
const wander = (e: PointerEvent) => {
|
|
37
|
+
if (Math.hypot(e.clientX - down.clientX, e.clientY - down.clientY) > STILL) (stop(), swipe?.());
|
|
38
|
+
};
|
|
39
|
+
const timer = setTimeout(() => {
|
|
40
|
+
stop();
|
|
41
|
+
// the page doesn't scroll under a thing picked up
|
|
42
|
+
const still = (e: TouchEvent) => e.preventDefault();
|
|
43
|
+
addEventListener("touchmove", still, { passive: false });
|
|
44
|
+
const done = () => (
|
|
45
|
+
removeEventListener("touchmove", still),
|
|
46
|
+
removeEventListener("pointerup", done),
|
|
47
|
+
removeEventListener("pointercancel", done)
|
|
48
|
+
);
|
|
49
|
+
addEventListener("pointerup", done);
|
|
50
|
+
addEventListener("pointercancel", done);
|
|
51
|
+
pick();
|
|
52
|
+
}, HOLD);
|
|
53
|
+
addEventListener("pointermove", wander);
|
|
54
|
+
addEventListener("pointerup", up);
|
|
55
|
+
addEventListener("pointercancel", stop);
|
|
56
|
+
}
|
package/src/hues.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// joined's icons by its own names, and lucide's outlines behind each: the data alone, so the page's
|
|
2
|
+
// helpers (src/icons.ts) and the design system's build (scripts/design.ts) draw from one list.
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
BedDouble,
|
|
6
|
+
Bot,
|
|
7
|
+
CalendarDays,
|
|
8
|
+
CalendarPlus,
|
|
9
|
+
CalendarRange,
|
|
10
|
+
Check,
|
|
11
|
+
CloudOff,
|
|
12
|
+
ChevronLeft,
|
|
13
|
+
ChevronRight,
|
|
14
|
+
Contact,
|
|
15
|
+
Copy,
|
|
16
|
+
Download,
|
|
17
|
+
Ellipsis,
|
|
18
|
+
GripVertical,
|
|
19
|
+
GitCommitVertical,
|
|
20
|
+
KeyRound,
|
|
21
|
+
Lock,
|
|
22
|
+
LockOpen,
|
|
23
|
+
Pencil,
|
|
24
|
+
Play,
|
|
25
|
+
LogIn,
|
|
26
|
+
LogOut,
|
|
27
|
+
Maximize2,
|
|
28
|
+
Plus,
|
|
29
|
+
Trash2,
|
|
30
|
+
Upload,
|
|
31
|
+
User,
|
|
32
|
+
UserMinus,
|
|
33
|
+
UserPlus,
|
|
34
|
+
Users,
|
|
35
|
+
X,
|
|
36
|
+
ZoomIn,
|
|
37
|
+
ZoomOut,
|
|
38
|
+
type IconNode,
|
|
39
|
+
} from "lucide";
|
|
40
|
+
|
|
41
|
+
export const ICONS = {
|
|
42
|
+
add: Plus,
|
|
43
|
+
agent: Bot,
|
|
44
|
+
away: CloudOff,
|
|
45
|
+
back: ChevronLeft,
|
|
46
|
+
calendar: CalendarDays,
|
|
47
|
+
"calendar-add": CalendarPlus,
|
|
48
|
+
check: Check,
|
|
49
|
+
close: X,
|
|
50
|
+
copy: Copy,
|
|
51
|
+
download: Download,
|
|
52
|
+
edit: Pencil,
|
|
53
|
+
grip: GripVertical,
|
|
54
|
+
group: Users,
|
|
55
|
+
grow: Maximize2,
|
|
56
|
+
month: CalendarRange,
|
|
57
|
+
more: Ellipsis,
|
|
58
|
+
line: GitCommitVertical,
|
|
59
|
+
"new-link": KeyRound,
|
|
60
|
+
on: ChevronRight,
|
|
61
|
+
out: LogOut,
|
|
62
|
+
people: Contact,
|
|
63
|
+
play: Play,
|
|
64
|
+
"person-add": UserPlus,
|
|
65
|
+
"person-remove": UserMinus,
|
|
66
|
+
"read-only": Lock,
|
|
67
|
+
"give-back": LockOpen,
|
|
68
|
+
remove: Trash2,
|
|
69
|
+
stay: BedDouble,
|
|
70
|
+
"sign-in": LogIn,
|
|
71
|
+
upload: Upload,
|
|
72
|
+
you: User,
|
|
73
|
+
"zoom-in": ZoomIn,
|
|
74
|
+
"zoom-out": ZoomOut,
|
|
75
|
+
} satisfies Record<string, IconNode>;
|
|
76
|
+
|
|
77
|
+
export type IconName = keyof typeof ICONS;
|
package/src/icon.png
ADDED
|
Binary file
|
package/src/icons.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// The marks joined draws, by its own names for them, and lucide's outlines behind each: lucide
|
|
2
|
+
// alone, never another set or an inline SVG (as dzql's cafe has it). A row's harmless action is its
|
|
3
|
+
// icon alone, with its words as its label and title; a bigger button has its icon before its words.
|
|
4
|
+
// In a page's markup, data-icon="name" on an element puts the icon at its start (iconify()).
|
|
5
|
+
|
|
6
|
+
import { createElement } from "lucide";
|
|
7
|
+
import { ICONS, type IconName } from "./icon-names.ts";
|
|
8
|
+
|
|
9
|
+
/** An icon, as an SVG element, hidden from a screen reader: its words go on what holds it. */
|
|
10
|
+
export const icon = (name: IconName) =>
|
|
11
|
+
createElement(ICONS[name], { width: 16, height: 16, "aria-hidden": "true", class: `icon icon-${name}` });
|
|
12
|
+
|
|
13
|
+
/** A button that is its icon alone: its words are its label and its title. */
|
|
14
|
+
export function iconButton(name: IconName, words: string, act?: () => void) {
|
|
15
|
+
const b = Object.assign(document.createElement("button"), {
|
|
16
|
+
type: "button",
|
|
17
|
+
className: "icon-only",
|
|
18
|
+
title: words,
|
|
19
|
+
ariaLabel: words,
|
|
20
|
+
});
|
|
21
|
+
b.append(icon(name));
|
|
22
|
+
if (act) b.addEventListener("click", act);
|
|
23
|
+
return b;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Each element with data-icon in a page's markup gets its icon at its start. */
|
|
27
|
+
export function iconify(root: ParentNode = document) {
|
|
28
|
+
for (const el of root.querySelectorAll<HTMLElement>("[data-icon]")) {
|
|
29
|
+
if (el.querySelector(":scope > svg.icon")) continue;
|
|
30
|
+
el.prepend(icon(el.dataset.icon as IconName));
|
|
31
|
+
}
|
|
32
|
+
}
|