@blueshed/joined 0.2.2 → 0.3.1

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.
Files changed (237) hide show
  1. package/.claude/skills/joined/SKILL.md +9 -1
  2. package/.claude/skills/joined/reference.md +316 -63
  3. package/.claude/skills/joined-door/SKILL.md +57 -0
  4. package/README.md +19 -50
  5. package/docs/design.md +158 -37
  6. package/docs/introduction.md +27 -27
  7. package/docs/light-and-shadow.svg +2 -1
  8. package/docs/links-and-trust.svg +1 -0
  9. package/docs/stories-to-code.svg +2 -1
  10. package/docs/wire-op.svg +1 -0
  11. package/examples/README.md +20 -0
  12. package/examples/account/account.json +1 -0
  13. package/examples/account/derive.ts +41 -0
  14. package/examples/account/generated/elements.ts +52 -0
  15. package/examples/account/generated/rows.ts +22 -0
  16. package/examples/account/generated/rules.ts +32 -0
  17. package/examples/account/routes.ts +5 -0
  18. package/examples/app.css +11 -1
  19. package/examples/cafe/books.html +2 -2
  20. package/examples/cafe/cafe.css +96 -85
  21. package/examples/cafe/generated/books.rows.ts +22 -0
  22. package/examples/cafe/generated/books.rules.ts +3 -2
  23. package/examples/cafe/generated/kitchen.rows.ts +27 -0
  24. package/examples/cafe/generated/kitchen.rules.ts +11 -1
  25. package/examples/cafe/generated/menu.rows.ts +22 -0
  26. package/examples/cafe/generated/menu.rules.ts +3 -2
  27. package/examples/cafe/generated/order.rows.ts +27 -0
  28. package/examples/cafe/generated/order.rules.ts +11 -1
  29. package/examples/cafe/generated/staff.elements.ts +7 -2
  30. package/examples/cafe/generated/staff.rows.ts +22 -0
  31. package/examples/cafe/generated/staff.rules.ts +9 -1
  32. package/examples/cafe/generated/supplies.queries.ts +4 -2
  33. package/examples/cafe/generated/supplies.rows.ts +22 -0
  34. package/examples/cafe/generated/supplies.rules.ts +17 -1
  35. package/examples/cafe/generated/till.queries.ts +2 -0
  36. package/examples/cafe/generated/till.rows.ts +27 -0
  37. package/examples/cafe/generated/till.rules.ts +11 -1
  38. package/examples/cafe/index.html +14 -15
  39. package/examples/cafe/kitchen.css +11 -19
  40. package/examples/cafe/kitchen.ts +7 -3
  41. package/examples/cafe/look.ts +30 -0
  42. package/examples/cafe/menu.html +10 -26
  43. package/examples/cafe/menu.ts +8 -80
  44. package/examples/cafe/migrations/002-guard-supplies.ts +15 -0
  45. package/examples/cafe/order.html +8 -7
  46. package/examples/cafe/order.ts +6 -2
  47. package/examples/cafe/routes.ts +0 -1
  48. package/examples/cafe/staff.json +5 -0
  49. package/examples/cafe/stories.jsonl +6 -2
  50. package/examples/cafe/supplies.html +35 -34
  51. package/examples/cafe/supplies.ts +59 -39
  52. package/examples/cafe/till.ts +19 -11
  53. package/examples/cafe/views.ts +7 -5
  54. package/examples/chart/arches.ts +150 -0
  55. package/examples/chart/chart.css +11 -0
  56. package/examples/chart/chart.json +87 -0
  57. package/examples/chart/generated/elements.ts +105 -0
  58. package/examples/chart/generated/queries.ts +36 -0
  59. package/examples/chart/generated/rows.ts +27 -0
  60. package/examples/chart/generated/rules.ts +111 -0
  61. package/examples/chart/grid.ts +118 -0
  62. package/examples/chart/index.html +78 -0
  63. package/examples/chart/migrations/001-chart.ts +6 -0
  64. package/examples/chart/migrations/002-create-conditions.ts +6 -0
  65. package/examples/chart/page.ts +20 -0
  66. package/examples/chart/routes.ts +7 -0
  67. package/examples/chart/stories.jsonl +14 -0
  68. package/examples/chart/teeth.ts +57 -0
  69. package/examples/desk/desk.css +6 -10
  70. package/examples/desk/generated/elements.ts +1 -1
  71. package/examples/desk/generated/rows.ts +22 -0
  72. package/examples/desk/generated/rules.ts +34 -1
  73. package/examples/desk/index.html +10 -3
  74. package/examples/desk/lanes.css +21 -19
  75. package/examples/desk/routes.ts +0 -2
  76. package/examples/desk/stories.jsonl +4 -3
  77. package/examples/desk/tally.css +1 -1
  78. package/examples/desk/thumbs.ts +2 -2
  79. package/examples/docs.ts +7 -4
  80. package/examples/hello/generated/elements.ts +2 -2
  81. package/examples/hello/generated/rules.ts +3 -2
  82. package/examples/hello/hello.css +2 -4
  83. package/examples/hello/index.html +10 -3
  84. package/examples/hello/page.ts +4 -4
  85. package/examples/index.html +20 -12
  86. package/examples/notes/generated/elements.ts +112 -0
  87. package/examples/notes/generated/queries.ts +42 -0
  88. package/examples/notes/generated/rows.ts +27 -0
  89. package/examples/notes/generated/rules.ts +133 -0
  90. package/examples/notes/index.html +32 -0
  91. package/examples/notes/look.ts +41 -0
  92. package/examples/notes/migrations/001-notes.ts +7 -0
  93. package/examples/notes/notes.json +78 -0
  94. package/examples/notes/page.ts +21 -0
  95. package/examples/notes/routes.ts +6 -0
  96. package/examples/notes/stories.jsonl +24 -0
  97. package/examples/page.ts +9 -2
  98. package/examples/people/generated/rows.ts +22 -0
  99. package/examples/people/generated/rules.ts +11 -1
  100. package/examples/people/links.ts +8 -9
  101. package/examples/people/people.css +1 -1
  102. package/examples/people/routes.ts +1 -3
  103. package/examples/people/stories.jsonl +1 -0
  104. package/examples/people/view.ts +5 -2
  105. package/examples/trip/generated/elements.ts +5 -3
  106. package/examples/trip/generated/queries.ts +12 -1
  107. package/examples/trip/generated/rows.ts +27 -0
  108. package/examples/trip/generated/rules.ts +56 -2
  109. package/examples/trip/index.html +58 -12
  110. package/examples/trip/line.css +186 -0
  111. package/examples/trip/line.ts +51 -40
  112. package/examples/trip/page.ts +65 -71
  113. package/examples/trip/routes.ts +9 -5
  114. package/examples/trip/stays.css +13 -13
  115. package/examples/trip/stays.ts +15 -10
  116. package/examples/trip/stories.jsonl +2 -0
  117. package/examples/trip/told.ts +3 -26
  118. package/examples/trip/trip.css +16 -0
  119. package/examples/trips/generated/elements.ts +1 -1
  120. package/examples/trips/generated/rows.ts +22 -0
  121. package/examples/trips/generated/rules.ts +9 -1
  122. package/examples/trips/index.html +10 -10
  123. package/examples/trips/map.ts +3 -14
  124. package/examples/trips/new-trip.ts +14 -16
  125. package/examples/trips/trips.css +24 -23
  126. package/examples/weeks/generated/elements.ts +1 -1
  127. package/examples/weeks/generated/queries.ts +11 -0
  128. package/examples/weeks/generated/rows.ts +22 -0
  129. package/examples/weeks/generated/rules.ts +11 -5
  130. package/examples/weeks/routes.ts +3 -2
  131. package/examples/weeks/stories.jsonl +1 -0
  132. package/examples/welcome.css +43 -33
  133. package/package.json +8 -2
  134. package/src/attachment.ts +17 -2
  135. package/src/awesome.ts +103 -0
  136. package/src/board.css +76 -0
  137. package/src/board.ts +173 -0
  138. package/src/cli.ts +28 -3
  139. package/src/compile.ts +821 -109
  140. package/src/definitions.ts +113 -27
  141. package/src/demo.css +2 -5
  142. package/src/draft.ts +48 -27
  143. package/src/drawer.ts +248 -0
  144. package/src/engine.ts +253 -170
  145. package/src/fields.ts +341 -0
  146. package/src/file-value.ts +12 -2
  147. package/src/files.ts +113 -33
  148. package/src/ground.ts +110 -0
  149. package/src/icon-names.ts +19 -2
  150. package/src/keep.ts +16 -3
  151. package/src/kit.ts +51 -0
  152. package/src/link.ts +3 -3
  153. package/src/map.css +140 -0
  154. package/src/map.ts +200 -0
  155. package/src/mcp.ts +129 -24
  156. package/src/members/demo.ts +13 -12
  157. package/src/members/generated/rows.ts +22 -0
  158. package/src/members/generated/rules.ts +3 -2
  159. package/src/members/group.ts +105 -55
  160. package/src/members/keys.ts +95 -79
  161. package/src/members/panel.css +40 -35
  162. package/src/members/panel.ts +58 -37
  163. package/src/migrate.ts +178 -125
  164. package/src/migrations/005-change-kept.ts +7 -0
  165. package/src/month.css +129 -0
  166. package/src/month.ts +179 -0
  167. package/src/ops.ts +40 -1
  168. package/src/page.css +11 -2
  169. package/src/page.ts +68 -17
  170. package/src/parts.css +614 -230
  171. package/src/parts.ts +259 -36
  172. package/src/plane.css +61 -0
  173. package/src/plane.ts +153 -0
  174. package/src/postgres-server.ts +60 -0
  175. package/src/reading.css +73 -0
  176. package/src/reading.ts +238 -0
  177. package/src/rows.css +289 -0
  178. package/src/rows.ts +864 -0
  179. package/src/search.css +80 -0
  180. package/src/search.ts +130 -0
  181. package/src/server.ts +355 -137
  182. package/src/settings.ts +9 -4
  183. package/src/sheet.ts +116 -0
  184. package/src/skill.ts +40 -0
  185. package/src/slots.css +90 -0
  186. package/src/slots.ts +213 -0
  187. package/src/specs.ts +38 -0
  188. package/src/starter.ts +19 -2
  189. package/src/store.ts +224 -161
  190. package/src/stories.ts +43 -11
  191. package/src/surface.ts +164 -0
  192. package/src/time.ts +2 -0
  193. package/src/timeline.css +111 -0
  194. package/src/timeline.ts +235 -0
  195. package/src/toast.ts +21 -48
  196. package/src/together.ts +15 -24
  197. package/src/tokens.css +89 -3
  198. package/src/tokens.json +287 -7
  199. package/src/tool.ts +210 -0
  200. package/src/upkeep.ts +47 -22
  201. package/src/views.css +43 -0
  202. package/src/views.ts +111 -0
  203. package/src/week.css +150 -0
  204. package/src/week.ts +254 -0
  205. package/src/write.ts +326 -78
  206. package/starter/CHANGELOG.md +8 -0
  207. package/starter/CLAUDE.md +9 -3
  208. package/starter/bunfig +5 -0
  209. package/starter/githooks/pre-commit +13 -0
  210. package/starter/prettierignore +5 -0
  211. package/starter/tests/hello.test.ts +2 -0
  212. package/starter/tests/records.test.ts +40 -0
  213. package/starter/todo.jsonl +0 -0
  214. package/docs/learning.md +0 -76
  215. package/examples/cafe/trust.ts +0 -20
  216. package/examples/desk/trust.ts +0 -24
  217. package/examples/people/trust.ts +0 -14
  218. package/examples/trip/answer-rows.ts +0 -70
  219. package/examples/trip/bar.ts +0 -89
  220. package/examples/trip/calendar-map.css +0 -711
  221. package/examples/trip/calendar-map.ts +0 -249
  222. package/examples/trip/drags.ts +0 -143
  223. package/examples/trip/drawer.ts +0 -250
  224. package/examples/trip/event-form.ts +0 -200
  225. package/examples/trip/holding.ts +0 -61
  226. package/examples/trip/map.ts +0 -234
  227. package/examples/trip/month.ts +0 -87
  228. package/examples/trip/other-weeks.ts +0 -67
  229. package/examples/trip/peek.ts +0 -71
  230. package/examples/trip/people-chips.ts +0 -74
  231. package/examples/trip/shell.ts +0 -39
  232. package/examples/trip/trust.ts +0 -51
  233. package/examples/trip/week.ts +0 -237
  234. package/examples/trip/writes.ts +0 -91
  235. package/examples/trip/zones.ts +0 -16
  236. package/examples/weeks/derive.ts +0 -23
  237. package/src/scrim.ts +0 -81
package/src/fields.ts ADDED
@@ -0,0 +1,341 @@
1
+ // A field as a sheet asks for it (joined/kit, <j-field>): one control for each kind of value the stories hold, so a
2
+ // page names a field and is given the right one. What's in the document is shown in the control, and what's typed or
3
+ // picked is read back as the document holds it: a price in pence typed in pounds, a length typed "2h 30m" kept as
4
+ // PT2H30M, a time to the minute kept to the second. Each is a form control by the field's name (a hidden one where the
5
+ // control is more than a box: people's chips, a place), so a Draft (./draft.ts) holds it until Save like any other.
6
+ // Its label is the field's words; what it can't read is said as the box's own complaint, and Save waits for it.
7
+
8
+ import { choose, chosen } from "./draft.ts";
9
+ import { iconButton } from "./icons.ts";
10
+ import { hueOf } from "./hues.ts";
11
+ import { face, typeahead } from "./parts.ts";
12
+ import { attachment } from "./attachment.ts";
13
+ import { PlaceSearch } from "./place-search.ts";
14
+ import type { Field } from "./rows.ts";
15
+ import { lasts, lengthOf } from "./time.ts";
16
+
17
+ /** What a page may say of a field, beyond what the stories do: its words, and how it's read (money in its minor
18
+ * units, words long enough for a box of lines), and whether, once an item has it, it's only said there (readonly):
19
+ * asked as it's added, never changed after; a line said under its label (hint); and, of a link, who isn't offered:
20
+ * none the open item's field `not` holds (an owner never offered as their own accountant, not="owners"). */
21
+ export type Kind = {
22
+ label?: string;
23
+ as?: "money" | "long";
24
+ currency?: string;
25
+ readonly?: boolean;
26
+ hint?: string;
27
+ not?: string;
28
+ };
29
+ export type Asked = Field & Kind;
30
+
31
+ /** What a control needs of the page: what a link may be to, that what it holds has changed, and the document its
32
+ * item is of (a file is kept for it). */
33
+ export type Context = { choices(f: Field): [key: number, words: string][]; changed(): void; doc(): string };
34
+
35
+ /** A field's control: its element (a label holding it), the document's value as the form shows it, the form's as the
36
+ * document keeps it, and what it offers drawn again as what may be chosen changes. */
37
+ export type Control = {
38
+ el: HTMLElement;
39
+ shown(v: unknown): string | boolean;
40
+ kept(s: string | boolean): unknown;
41
+ refresh(): void;
42
+ };
43
+
44
+ export const el = <K extends keyof HTMLElementTagNameMap>(tag: K, props: object = {}, ...inside: (Node | string)[]) => {
45
+ const e = Object.assign(document.createElement(tag), props);
46
+ e.append(...inside);
47
+ return e;
48
+ };
49
+ /** A field's words, where its control is joined's: a part of their own (label), as Web Awesome's label is. */
50
+ const named = (words: string) => {
51
+ const s = el("span", {}, words);
52
+ s.setAttribute("part", "label");
53
+ return s;
54
+ };
55
+ /** Told each time a control is filled from the document (a Draft's fill, which says what it holds in data-saved):
56
+ * after it, its value is what was filled. */
57
+ const filled = (control: HTMLElement, then: () => void) =>
58
+ new MutationObserver(then).observe(control, { attributes: true, attributeFilter: ["data-saved"] });
59
+ /** How many may be chosen from as themselves (design.md, Choosing). */
60
+ const FEW = 6;
61
+ const ZONES = Intl.supportedValuesOf("timeZone");
62
+
63
+ /** A currency's minor units and its symbol, as the reader's locale writes it. */
64
+ export function currencyOf(code = "GBP") {
65
+ const f = new Intl.NumberFormat(undefined, { style: "currency", currency: code });
66
+ return {
67
+ digits: f.resolvedOptions().maximumFractionDigits ?? 2,
68
+ symbol: f.formatToParts(0).find((p) => p.type === "currency")!.value,
69
+ format: (n: number) => f.format(n),
70
+ };
71
+ }
72
+
73
+ /** How a value of a field reads where it's said, not asked (a row's facts): money as money, a length as a length. */
74
+ export function reads(f: Asked, v: unknown): string | null {
75
+ if (f.as === "money" && typeof v === "number") {
76
+ const c = currencyOf(f.currency);
77
+ return c.format(v / 10 ** c.digits);
78
+ }
79
+ return null;
80
+ }
81
+
82
+ /** A field's control, as its kind and type say (made()), its parts named so a page can reach it in its sheet's shadow
83
+ * (j-sheet::part(field-accountants)): each field `field` and `field-<name>`, its words `label`, its box `control`, its
84
+ * hint `hint`; a list of people's chips `chips`, each `chip` and `chosen` or `offered`. */
85
+ export function control(f: Asked, words: string, page: Context): Control {
86
+ const c = made(f, words, page),
87
+ it = c.el;
88
+ it.setAttribute("part", `field field-${f.name}`);
89
+ // Web Awesome's own: its label, its box and its hint, passed out under joined's names, and its hint its own
90
+ if (it.localName.startsWith("wa-")) {
91
+ it.setAttribute("exportparts", "form-control-label:label, base:control, input:control, hint");
92
+ if (f.hint) it.setAttribute("hint", f.hint);
93
+ } else if (f.hint) {
94
+ // a choice of a few is Web Awesome's select, a hint of its own; the rest joined's, said under their words
95
+ it.querySelector(":scope > wa-select")?.setAttribute("hint", f.hint);
96
+ const hint = el("small", { className: "j-hint" }, f.hint);
97
+ hint.setAttribute("part", "hint");
98
+ it.querySelector("[part~=label]")?.after(hint);
99
+ }
100
+ return c;
101
+ }
102
+
103
+ /** The control, as its kind and type say: Web Awesome's for what it has (a box, a number, a tick, words of several
104
+ * lines, a choice of a few), each its label its own; joined's for what's its own (a length, a zone, a place, people, a
105
+ * typeahead), its words in a span of their own. */
106
+ function made(f: Asked, words: string, page: Context): Control {
107
+ const name = f.name,
108
+ plain = (v: unknown) => (v === undefined || v === null ? "" : String(v)),
109
+ // its name an attribute at once (Web Awesome reflects a property only as it next draws): a form finds it by it
110
+ wa = (tag: string, props: object = {}) => {
111
+ const it = Object.assign(document.createElement(tag), { label: words, autocomplete: "off", ...props });
112
+ return (it.setAttribute("name", name), it) as HTMLElement;
113
+ },
114
+ same = { kept: (s: string | boolean) => s, refresh() {} };
115
+ if (f.type === "boolean") {
116
+ const box = wa("wa-checkbox");
117
+ box.append(words);
118
+ return { ...same, el: box, shown: (v) => v === true };
119
+ }
120
+ if (f.to && f.how === "one") return one(f, words, page);
121
+ if (f.to && f.how === "ids") return people(f, words, page);
122
+ if (f.as === "money") {
123
+ const c = currencyOf(f.currency);
124
+ return {
125
+ el: wa("wa-number-input", {
126
+ label: `${words}, ${c.symbol}`,
127
+ step: 1 / 10 ** c.digits,
128
+ min: 0,
129
+ inputmode: "decimal",
130
+ withoutSteppers: true,
131
+ }),
132
+ shown: (v) => (typeof v === "number" ? (v / 10 ** c.digits).toFixed(c.digits) : ""),
133
+ kept: (s) => Math.round(Number(s) * 10 ** c.digits),
134
+ refresh() {},
135
+ };
136
+ }
137
+ if (f.type === "integer" || f.type === "decimal")
138
+ return {
139
+ el: wa(
140
+ "wa-number-input",
141
+ f.type === "integer" ? { inputmode: "numeric" } : { step: "any", inputmode: "decimal", withoutSteppers: true },
142
+ ),
143
+ shown: plain,
144
+ kept: (s) => Number(s),
145
+ refresh() {},
146
+ };
147
+ if (f.type === "date-time")
148
+ return {
149
+ el: wa("wa-input", { type: "datetime-local" }),
150
+ shown: (v) => plain(v).slice(0, 16),
151
+ kept: (s) => (String(s).length === 16 ? `${s}:00` : s),
152
+ refresh() {},
153
+ };
154
+ if (f.type === "duration") {
155
+ const input = wa("wa-input", { placeholder: "2h 30m" }) as HTMLInputElement,
156
+ check = () =>
157
+ input.setCustomValidity(!input.value.trim() || lengthOf(input.value) ? "" : "A length, such as 45m or 2h 30m");
158
+ input.addEventListener("input", check);
159
+ // filled from the document (or put back by Never mind), it's read again
160
+ filled(input, check);
161
+ return {
162
+ el: input,
163
+ shown: (v) => lasts(plain(v) || undefined),
164
+ kept: (s) => lengthOf(String(s)),
165
+ refresh() {},
166
+ };
167
+ }
168
+ if (f.type === "zone") return zone(f, words, page);
169
+ if (f.type === "file") return file(f, words, page);
170
+ if (f.type === "place") return place(f, words, page);
171
+ if (f.as === "long") return { ...same, el: wa("wa-textarea", { rows: 4, resize: "auto" }), shown: plain };
172
+ return { ...same, el: wa("wa-input"), shown: plain };
173
+ }
174
+
175
+ /** A link to one item: chosen from a few as a select; from more, found by typing, the one chosen said in its box. */
176
+ function one(f: Field, words: string, page: Context): Control {
177
+ const select = Object.assign(document.createElement("wa-select"), { label: words }) as HTMLElement & {
178
+ value: string | null;
179
+ required: boolean;
180
+ },
181
+ find = el("input", { className: "find", autocomplete: "off", ariaLabel: words }),
182
+ list = el("div", { className: "j-choices", role: "listbox", ariaLabel: words, hidden: true }),
183
+ many = el("label", {}, named(words), find, list);
184
+ select.setAttribute("name", f.name);
185
+ const offer = typeahead(
186
+ find,
187
+ list,
188
+ () => page.choices(f),
189
+ (key) => (choose(select, String(key)), refresh(), page.changed()),
190
+ );
191
+ function refresh() {
192
+ const all = page.choices(f),
193
+ few = all.length <= FEW,
194
+ was = chosen(select) || null;
195
+ select.setAttribute("placeholder", f.needed ? "Choose one" : "None");
196
+ select.toggleAttribute("with-clear", !f.needed);
197
+ // drawn again only where they've changed: Web Awesome's select keeps a value only as one of its options chosen
198
+ const now = JSON.stringify(all);
199
+ if (select.dataset.offered !== now) {
200
+ select.dataset.offered = now;
201
+ select.replaceChildren(
202
+ ...all.map(([key, words]) => {
203
+ const o = el("wa-option" as "option", {}, words);
204
+ o.setAttribute("value", String(key));
205
+ return o;
206
+ }),
207
+ );
208
+ }
209
+ choose(select, was);
210
+ select.hidden = !few;
211
+ many.hidden = few;
212
+ find.placeholder = all.find(([key]) => String(key) === was)?.[1] ?? "Type to find one";
213
+ offer();
214
+ }
215
+ return {
216
+ el: el("div", { className: "j-one" }, select, many),
217
+ shown: (v) => (v === undefined || v === null ? "" : String(v)),
218
+ kept: (s) => (s === "" ? undefined : Number(s)),
219
+ refresh,
220
+ };
221
+ }
222
+
223
+ /** A list of people: each a chip to press, those in it pressed. Picks within a Save surface: kept with the rest. */
224
+ function people(f: Field, words: string, page: Context): Control {
225
+ const held = el("input", { type: "hidden", name: f.name }),
226
+ chips = el("div", { className: "j-chips", role: "group", ariaLabel: words });
227
+ chips.setAttribute("part", "chips");
228
+ const ids = (): number[] => JSON.parse(held.value || "[]");
229
+ function refresh() {
230
+ chips.replaceChildren(
231
+ ...page.choices(f).map(([key, who]) => {
232
+ const on = ids().includes(key),
233
+ b = el("button", { type: "button", ariaPressed: String(on) }, face(key, who), who);
234
+ b.style.setProperty("--hue", hueOf(key));
235
+ // findable by whose it is, and styled by whether it's chosen or only offered
236
+ b.dataset.key = String(key);
237
+ b.setAttribute("part", `chip ${on ? "chosen" : "offered"}`);
238
+ b.addEventListener("click", () => {
239
+ const now = ids().includes(key) ? ids().filter((k) => k !== key) : [...ids(), key].sort((a, b) => a - b);
240
+ held.value = JSON.stringify(now);
241
+ refresh();
242
+ page.changed();
243
+ });
244
+ return b;
245
+ }),
246
+ );
247
+ }
248
+ // filled by the draft without an input event: the chips follow it as it's filled
249
+ filled(held, refresh);
250
+ return {
251
+ el: el("div", { className: "label" }, named(words), held, chips),
252
+ shown: (v) => JSON.stringify([...((v as number[]) ?? [])].sort((a, b) => a - b)),
253
+ kept: (s) => JSON.parse(String(s) || "[]"),
254
+ refresh,
255
+ };
256
+ }
257
+
258
+ /** A file: joined's attachment (its picture, or a PDF's link; a way to choose one, and to take it off), the file kept
259
+ * for the item's document as it's chosen, its value held in the form until Save, or Add in a modal, as any field's. */
260
+ function file(f: Field, words: string, page: Context): Control {
261
+ const held = el("input", { type: "hidden", name: f.name }),
262
+ draw = () => part.draw(held.value || undefined, { put: true, take: !f.needed }),
263
+ set = (v: string) => ((held.value = v), draw(), page.changed(), Promise.resolve(undefined)),
264
+ part = attachment(page.doc, set, () => set(""));
265
+ filled(held, draw);
266
+ return {
267
+ el: el("div", { className: "label" }, named(words), held, part.el),
268
+ shown: (v) => (v ? String(v) : ""),
269
+ kept: (s) => s || undefined,
270
+ refresh: draw,
271
+ };
272
+ }
273
+
274
+ /** A time zone, found by typing a city ("tokyo", "new york"); what's typed is kept only where it's one. */
275
+ function zone(f: Field, words: string, page: Context): Control {
276
+ // named apart from its label, which holds the list too: its words would be the box's name while it's shown
277
+ const input = el("input", {
278
+ name: f.name,
279
+ autocomplete: "off",
280
+ placeholder: "A city: Tokyo, London",
281
+ ariaLabel: words,
282
+ }),
283
+ list = el("div", { className: "j-choices", role: "listbox", ariaLabel: words, hidden: true });
284
+ typeahead(
285
+ input,
286
+ list,
287
+ () => ZONES.map((z, i) => [i, z]),
288
+ (i) => ((input.value = ZONES[i]!), input.setCustomValidity(""), page.changed()),
289
+ );
290
+ // typeahead empties the box as it chooses: the zone is written back after it
291
+ const check = () =>
292
+ input.setCustomValidity(!input.value || ZONES.includes(input.value) ? "" : "Choose a zone from those offered");
293
+ input.addEventListener("input", check);
294
+ filled(input, check);
295
+ return {
296
+ el: el("label", {}, named(words), input, list),
297
+ shown: (v) => (v ? String(v) : ""),
298
+ kept: (s) => s,
299
+ refresh() {},
300
+ };
301
+ }
302
+
303
+ /** A place: found by its name (Photon, ./places.ts), and kept as where it is (geo:lat,lng); said by the name it was
304
+ * found by, or where it is. Taken away by its ×. */
305
+ function place(f: Field, words: string, page: Context): Control {
306
+ const held = el("input", { type: "hidden", name: f.name }),
307
+ find = el("input", { type: "search", autocomplete: "off", placeholder: "Find a place", ariaLabel: words }),
308
+ at = el("span", { className: "at" }),
309
+ clear = iconButton("close", "No place"),
310
+ list = el("div", { className: "j-choices", role: "listbox", hidden: true }),
311
+ search = new PlaceSearch(list, (p) => {
312
+ held.value = p.coordinates;
313
+ at.textContent = p.name;
314
+ find.value = "";
315
+ page.changed();
316
+ said();
317
+ });
318
+ const said = () => {
319
+ if (!held.value) at.textContent = "";
320
+ else if (!at.textContent) at.textContent = held.value.replace(/^geo:/, "");
321
+ clear.hidden = !held.value;
322
+ };
323
+ clear.addEventListener("click", () => ((held.value = ""), said(), page.changed()));
324
+ find.addEventListener("input", () => search.search(find.value.trim(), () => undefined));
325
+ find.addEventListener("keydown", (e) => e.key === "Enter" && e.preventDefault());
326
+ filled(held, () => ((at.textContent = ""), said()));
327
+ return {
328
+ el: el(
329
+ "label",
330
+ { className: "place" },
331
+ named(words),
332
+ held,
333
+ el("span", { className: "where" }, at, clear),
334
+ find,
335
+ list,
336
+ ),
337
+ shown: (v) => (v ? String(v) : ""),
338
+ kept: (s) => s || undefined,
339
+ refresh: said,
340
+ };
341
+ }
package/src/file-value.ts CHANGED
@@ -9,5 +9,15 @@ export const TOO_BIG = `That file is too big: under ${MOST / 1024 / 1024} MB, pl
9
9
 
10
10
  /** A file field's value's name: `file:<name>`'s. */
11
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)}`;
12
+ /** A kind's instance's folder: `book:1`'s is `book-1` (its files' folder, where its kind keeps them apart). */
13
+ export const folderOf = (doc: string) => {
14
+ const [, name, key] = /^([a-z][a-z0-9-]*):(\d+)(?:\?|$)/.exec(doc) ?? [];
15
+ return name ? `${name}-${key}` : "";
16
+ };
17
+ /** Where a file field's value is served: `file:<name>` at /files/<name>; or, given the item's document and that's a
18
+ * kind's instance, at /files/<its folder>/<name>, to whoever may hold it (a guest by its `code`). */
19
+ export const fileUrl = (value: string, doc = "") => {
20
+ const folder = folderOf(doc),
21
+ code = /[?&]code=([^&]*)/.exec(doc)?.[1];
22
+ return folder ? `/files/${folder}/${fileName(value)}${code ? `?code=${code}` : ""}` : `/files/${fileName(value)}`;
23
+ };
package/src/files.ts CHANGED
@@ -12,9 +12,13 @@
12
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
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
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.
15
+ // joined's, so neither is letting its files go. A kind that keeps its files apart (`kind: { files: "apart" }`) keeps
16
+ // each instance's in a folder of its own, `book-1/<name>`: served at /files/book-1/<name> only to whoever may hold
17
+ // `book:1` and see an item naming it (as is any instance's file, from its folder or the shared one), and handed back
18
+ // with it (/export/book-1).
16
19
 
17
- import { existsSync, readdirSync, statSync, unlinkSync } from "node:fs";
20
+ import { existsSync, readdirSync, renameSync, statSync, unlinkSync } from "node:fs";
21
+ import { folderOf } from "./file-value.ts";
18
22
  import type { BunFile, S3File, S3Options } from "bun";
19
23
  import type { Engine } from "./engine.ts";
20
24
  import { fileName, MOST, TOO_BIG } from "./file-value.ts";
@@ -50,13 +54,18 @@ function markdown(named: string, bytes: Uint8Array) {
50
54
  const SANDBOX = "sandbox; default-src 'none'; style-src 'unsafe-inline'";
51
55
  /** A kept file's name: its content's SHA-256, and its type's extension (the compiler's file form, after `file:`). */
52
56
  const NAME = /^[0-9a-f]{64}\.[a-z0-9]{1,8}$/;
57
+ /** A kept file's place: its name, in its instance's folder where its kind keeps them apart (`book-1/<name>`). */
58
+ const KEPT = /^(?:[a-z][a-z0-9-]*-\d+\/)?[0-9a-f]{64}\.[a-z0-9]{1,8}$/;
53
59
  /** Each file a value names, in any text: a change's ops. */
54
60
  const NAMED = new RegExp(`file:(${NAME.source.slice(1, -1)})`, "g");
55
61
 
56
- /** Where the files are kept, a folder or a bucket, each asked the same three things: a file by its name (to write,
57
- * to ask whether it's there, to send), each file kept with when it was, and one let go. */
62
+ /** Where the files are kept, a folder or a bucket, each asked the same four things: a file by its name (to ask
63
+ * whether it's there, to send), one put whole (never seen half written, nor written over while it's being sent: a
64
+ * folder's is written beside it and renamed over it, a bucket's object is put whole), each file kept with when it
65
+ * was, and one let go. */
58
66
  export type Files = {
59
67
  file(name: string): BunFile | S3File;
68
+ put(name: string, bytes: Uint8Array): Promise<unknown>;
60
69
  each(): AsyncIterable<{ name: string; at: number }>;
61
70
  drop(name: string): Promise<unknown>;
62
71
  };
@@ -68,10 +77,16 @@ export function filesAt(where: string, s3?: S3Options): Files {
68
77
  if (!bucket)
69
78
  return {
70
79
  file: (name) => Bun.file(`${where}/${name}`),
71
- // (none sent yet: no folder)
80
+ put: async (name, bytes) => {
81
+ const part = `${where}/${name}.${crypto.randomUUID()}.part`;
82
+ await Bun.write(part, bytes);
83
+ renameSync(part, `${where}/${name}`);
84
+ },
85
+ // (none sent yet: no folder); an instance's folder's files by their place in it
72
86
  async *each() {
73
- for (const name of existsSync(where) ? readdirSync(where) : [])
74
- yield { name, at: statSync(`${where}/${name}`).mtimeMs };
87
+ for (const name of existsSync(where) ? readdirSync(where, { recursive: true }) : [])
88
+ if (statSync(`${where}/${name}`).isFile())
89
+ yield { name: String(name), at: statSync(`${where}/${name}`).mtimeMs };
75
90
  },
76
91
  drop: async (name) => unlinkSync(`${where}/${name}`),
77
92
  };
@@ -79,6 +94,7 @@ export function filesAt(where: string, s3?: S3Options): Files {
79
94
  prefix = bucket[2] && !bucket[2].endsWith("/") ? `${bucket[2]}/` : bucket[2]!;
80
95
  return {
81
96
  file: (name) => client.file(prefix + name),
97
+ put: (name, bytes) => client.file(prefix + name).write(bytes),
82
98
  async *each() {
83
99
  let continuationToken: string | undefined;
84
100
  do {
@@ -97,7 +113,7 @@ export type Kept = { file: string } | { refused: string };
97
113
 
98
114
  /** A file sent, kept by its content's hash in `files`: a photo made a WebP, an SVG and a PDF as they are, and a
99
115
  * Markdown file as it is where it's `named` so; anything else refused. */
100
- export async function keep(files: Files, bytes: Uint8Array, named = ""): Promise<Kept> {
116
+ export async function keep(files: Files, bytes: Uint8Array, named = "", folder = ""): Promise<Kept> {
101
117
  if (!bytes.length) return { refused: "That file is empty." };
102
118
  if (bytes.length > MOST) return { refused: TOO_BIG };
103
119
  const head = new TextDecoder().decode(bytes.subarray(0, 1024));
@@ -124,7 +140,7 @@ export async function keep(files: Files, bytes: Uint8Array, named = ""): Promise
124
140
  }
125
141
  const name = `${new Bun.CryptoHasher("sha256").update(out).digest("hex")}.${ext}`;
126
142
  // written, kept already or not: the same bytes, its age started again, so upkeep doesn't let it go before it's saved
127
- await files.file(name).write(out);
143
+ await files.put(folder ? `${folder}/${name}` : name, out);
128
144
  return { file: `file:${name}` };
129
145
  }
130
146
 
@@ -144,10 +160,39 @@ export const putsFile = (
144
160
  );
145
161
  });
146
162
 
163
+ /** A file kept, served with its type: for good where anyone may be sent it, else kept by the browser alone. */
164
+ const serve = (name: string, file: BunFile | S3File, shared: boolean) =>
165
+ new Response(file.stream(), {
166
+ headers: {
167
+ "content-type": TYPES[name.split(".").at(-1)!] ?? "application/octet-stream",
168
+ "cache-control": shared ? "public, max-age=31536000, immutable" : "private, max-age=31536000, immutable",
169
+ "x-content-type-options": "nosniff",
170
+ ...(name.endsWith(".svg") ? { "content-security-policy": SANDBOX } : {}),
171
+ },
172
+ });
173
+
174
+ /** A request's body, read as it comes, or null once it's more than `most` bytes: the rest is never read, so one sent
175
+ * in parts, its size unsaid, can't take the server's memory. */
176
+ export async function upTo(req: Request, most: number) {
177
+ const parts: Uint8Array[] = [];
178
+ let size = 0;
179
+ for await (const part of req.body ?? []) {
180
+ if ((size += part.length) > most) return null;
181
+ parts.push(part);
182
+ }
183
+ return new Uint8Array(Buffer.concat(parts));
184
+ }
185
+
147
186
  /** The routes: a file sent for a document (`POST /files?doc=board:1`, its bytes the body, `&name=` its file's name), by whoever `may` lets (why
148
- * 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,
149
- * cached for good. */
150
- export function routes(files: Files, may: (req: Request, doc: string) => Promise<string | null>) {
187
+ * not, or null), one that says it's too big refused before it's read, kept in its instance's folder where `apart`
188
+ * says its kind keeps them so; a file kept, by its name, with its type, cached for good; and an instance's file, by its
189
+ * folder and name (`/files/book-1/<name>`), to whoever `holds` lets hold it, from its folder or the shared one. */
190
+ export function routes(
191
+ files: Files,
192
+ may: (req: Request, doc: string) => Promise<string | null>,
193
+ holds: (req: Request, doc: string, name: string) => Promise<string | null>,
194
+ apart: (doc: string) => Promise<boolean>,
195
+ ) {
151
196
  return {
152
197
  "/files": {
153
198
  POST: async (req: Request) => {
@@ -155,8 +200,16 @@ export function routes(files: Files, may: (req: Request, doc: string) => Promise
155
200
  if (why) return Response.json({ refused: why }, { status: 403 });
156
201
  if (Number(req.headers.get("content-length")) > MOST)
157
202
  return Response.json({ refused: TOO_BIG }, { status: 413 });
158
- const url = new URL(req.url);
159
- const kept = await keep(files, new Uint8Array(await req.arrayBuffer()), url.searchParams.get("name") ?? "");
203
+ const url = new URL(req.url),
204
+ doc = url.searchParams.get("doc")!,
205
+ bytes = await upTo(req, MOST);
206
+ if (!bytes) return Response.json({ refused: TOO_BIG }, { status: 413 });
207
+ const kept = await keep(
208
+ files,
209
+ bytes,
210
+ url.searchParams.get("name") ?? "",
211
+ (await apart(doc)) ? folderOf(doc) : "",
212
+ );
160
213
  return Response.json(kept, { status: "refused" in kept ? 422 : 200 });
161
214
  },
162
215
  },
@@ -164,33 +217,60 @@ export function routes(files: Files, may: (req: Request, doc: string) => Promise
164
217
  const { name } = req.params,
165
218
  file = files.file(name);
166
219
  return NAME.test(name) && (await file.exists())
167
- ? new Response(file.stream(), {
168
- headers: {
169
- "content-type": TYPES[name.split(".").at(-1)!] ?? "application/octet-stream",
170
- "cache-control": "public, max-age=31536000, immutable",
171
- "x-content-type-options": "nosniff",
172
- ...(name.endsWith(".svg") ? { "content-security-policy": SANDBOX } : {}),
173
- },
174
- })
220
+ ? serve(name, file, true)
175
221
  : new Response("Not found", { status: 404 });
176
222
  },
223
+ "/files/:folder/:name": async (req: Request & { params: { folder: string; name: string } }) => {
224
+ const { folder, name } = req.params,
225
+ at = /^([a-z][a-z0-9-]*)-(\d+)$/.exec(folder),
226
+ code = new URL(req.url).searchParams.get("code");
227
+ if (!at || !NAME.test(name)) return new Response("Not found", { status: 404 });
228
+ const why = await holds(
229
+ req,
230
+ `${at[1]}:${at[2]}${code === null ? "" : `?code=${encodeURIComponent(code)}`}`,
231
+ name,
232
+ );
233
+ if (why) return Response.json({ refused: why }, { status: 403 });
234
+ const own = files.file(`${folder}/${name}`),
235
+ shared = files.file(name);
236
+ return (await own.exists())
237
+ ? serve(name, own, false)
238
+ : (await shared.exists())
239
+ ? serve(name, shared, false)
240
+ : new Response("Not found", { status: 404 });
241
+ },
177
242
  };
178
243
  }
179
244
 
180
- /** Each file the store names: in an item's file field now, or in a change it keeps, which an undo may put back. */
181
- export function named(db: Engine, rules: { collections: Record<string, { fields: Record<string, Type> }> }[]) {
182
- const names = new Set<string>();
183
- for (const { collections } of rules)
245
+ /** Each file the store names, by its place: in an item's file field now, or in a change it keeps, which an undo may
246
+ * put back; an instance's of a kind that keeps its files apart, in its folder (`book-1/<name>`). */
247
+ export async function named(
248
+ db: Engine,
249
+ rules: {
250
+ doc?: string;
251
+ collections: Record<string, { fields: Record<string, Type> }>;
252
+ kind?: { column: string; files?: "apart" } | null;
253
+ }[],
254
+ ) {
255
+ const names = new Set<string>(),
256
+ apart = new Set(rules.flatMap((r) => (r.kind?.files === "apart" && r.doc ? [r.doc] : [])));
257
+ for (const { collections, kind } of rules) {
258
+ const column = kind?.files === "apart" ? kind.column : null;
184
259
  for (const [coll, c] of Object.entries(collections))
185
260
  for (const f of Object.keys(c.fields).filter((f) => c.fields[f] === "file"))
186
- for (const { v } of db.query(`SELECT "${f}" AS v FROM "${coll}" WHERE "${f}" IS NOT NULL`).all())
187
- names.add(fileName(String(v)));
188
- for (const { ops } of db
261
+ for (const { v, k } of (await db
262
+ .query(`SELECT "${f}" AS v, ${column ? `"${column}"` : "NULL"} AS k FROM "${coll}" WHERE "${f}" IS NOT NULL`)
263
+ .all()) as { v: unknown; k: unknown }[])
264
+ names.add(column ? `${column}-${k}/${fileName(String(v))}` : fileName(String(v)));
265
+ }
266
+ for (const { doc, ops } of (await db
189
267
  .query(
190
- "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:%'",
268
+ "SELECT doc, 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:%'",
191
269
  )
192
- .all())
193
- for (const [, name] of String(ops).matchAll(NAMED)) names.add(name!);
270
+ .all()) as { doc: string; ops: unknown }[]) {
271
+ const folder = apart.has(doc.split(":")[0]!) ? folderOf(doc) : "";
272
+ for (const [, name] of String(ops).matchAll(NAMED)) names.add(folder ? `${folder}/${name}` : name!);
273
+ }
194
274
  return names;
195
275
  }
196
276
 
@@ -198,6 +278,6 @@ export function named(db: Engine, rules: { collections: Record<string, { fields:
198
278
  export async function letGo(files: Files, names: Set<string>, before: number) {
199
279
  let gone = 0;
200
280
  for await (const { name, at } of files.each())
201
- if (NAME.test(name) && !names.has(name) && at < before) (await files.drop(name), gone++);
281
+ if (KEPT.test(name) && !names.has(name) && at < before) (await files.drop(name), gone++);
202
282
  return gone;
203
283
  }