@blueshed/joined 0.3.0 → 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 (109) hide show
  1. package/.claude/skills/joined/reference.md +57 -18
  2. package/docs/design.md +93 -38
  3. package/docs/introduction.md +9 -9
  4. package/docs/light-and-shadow.svg +1 -0
  5. package/docs/links-and-trust.svg +1 -0
  6. package/docs/stories-to-code.svg +2 -1
  7. package/docs/wire-op.svg +1 -0
  8. package/examples/app.css +9 -0
  9. package/examples/cafe/cafe.css +87 -69
  10. package/examples/cafe/generated/staff.elements.ts +7 -2
  11. package/examples/cafe/generated/staff.rules.ts +3 -0
  12. package/examples/cafe/generated/supplies.rules.ts +5 -0
  13. package/examples/cafe/kitchen.css +11 -19
  14. package/examples/cafe/kitchen.ts +6 -2
  15. package/examples/cafe/migrations/002-guard-supplies.ts +15 -0
  16. package/examples/cafe/order.html +2 -1
  17. package/examples/cafe/order.ts +1 -1
  18. package/examples/cafe/staff.json +5 -0
  19. package/examples/cafe/stories.jsonl +4 -2
  20. package/examples/cafe/supplies.html +1 -0
  21. package/examples/cafe/supplies.ts +45 -28
  22. package/examples/cafe/till.ts +14 -10
  23. package/examples/cafe/views.ts +7 -5
  24. package/examples/chart/arches.ts +5 -3
  25. package/examples/chart/chart.css +7 -2
  26. package/examples/desk/desk.css +6 -10
  27. package/examples/desk/generated/elements.ts +1 -1
  28. package/examples/desk/index.html +1 -1
  29. package/examples/desk/lanes.css +21 -19
  30. package/examples/desk/stories.jsonl +1 -1
  31. package/examples/desk/tally.css +1 -1
  32. package/examples/docs.ts +7 -4
  33. package/examples/index.html +16 -7
  34. package/examples/notes/generated/queries.ts +8 -2
  35. package/examples/notes/index.html +1 -1
  36. package/examples/notes/stories.jsonl +3 -0
  37. package/examples/page.ts +9 -2
  38. package/examples/people/links.ts +7 -9
  39. package/examples/people/people.css +1 -1
  40. package/examples/people/view.ts +1 -1
  41. package/examples/trip/generated/elements.ts +1 -1
  42. package/examples/trip/stays.css +1 -1
  43. package/examples/trip/stays.ts +1 -1
  44. package/examples/trips/generated/elements.ts +1 -1
  45. package/examples/trips/trips.css +24 -23
  46. package/examples/welcome.css +41 -33
  47. package/package.json +1 -1
  48. package/src/attachment.ts +17 -2
  49. package/src/board.css +2 -1
  50. package/src/board.ts +4 -4
  51. package/src/cli.ts +14 -2
  52. package/src/compile.ts +255 -77
  53. package/src/definitions.ts +62 -14
  54. package/src/demo.css +2 -5
  55. package/src/draft.ts +10 -4
  56. package/src/drawer.ts +30 -4
  57. package/src/engine.ts +14 -5
  58. package/src/fields.ts +88 -15
  59. package/src/file-value.ts +12 -2
  60. package/src/files.ts +113 -35
  61. package/src/icon-names.ts +4 -0
  62. package/src/keep.ts +16 -3
  63. package/src/map.css +23 -16
  64. package/src/map.ts +3 -3
  65. package/src/mcp.ts +24 -3
  66. package/src/members/group.ts +41 -17
  67. package/src/members/keys.ts +3 -3
  68. package/src/members/panel.css +17 -18
  69. package/src/members/panel.ts +9 -2
  70. package/src/migrate.ts +58 -21
  71. package/src/migrations/005-change-kept.ts +7 -0
  72. package/src/month.css +6 -2
  73. package/src/month.ts +5 -5
  74. package/src/ops.ts +40 -1
  75. package/src/page.css +3 -2
  76. package/src/page.ts +64 -16
  77. package/src/parts.css +178 -86
  78. package/src/parts.ts +60 -20
  79. package/src/plane.css +9 -4
  80. package/src/plane.ts +4 -2
  81. package/src/reading.css +1 -5
  82. package/src/rows.css +2 -21
  83. package/src/rows.ts +123 -39
  84. package/src/server.ts +157 -30
  85. package/src/sheet.ts +4 -2
  86. package/src/slots.css +0 -4
  87. package/src/specs.ts +1 -1
  88. package/src/starter.ts +15 -1
  89. package/src/store.ts +40 -18
  90. package/src/surface.ts +7 -2
  91. package/src/time.ts +2 -0
  92. package/src/timeline.ts +14 -5
  93. package/src/together.ts +15 -17
  94. package/src/tokens.css +12 -3
  95. package/src/tokens.json +38 -7
  96. package/src/tool.ts +6 -7
  97. package/src/upkeep.ts +31 -4
  98. package/src/views.css +8 -9
  99. package/src/views.ts +23 -6
  100. package/src/week.css +1 -2
  101. package/src/week.ts +11 -7
  102. package/src/write.ts +130 -15
  103. package/starter/CHANGELOG.md +8 -0
  104. package/starter/CLAUDE.md +7 -1
  105. package/starter/bunfig +2 -1
  106. package/starter/githooks/pre-commit +13 -0
  107. package/starter/prettierignore +1 -0
  108. package/starter/tests/records.test.ts +40 -0
  109. package/starter/todo.jsonl +0 -0
@@ -6,15 +6,22 @@
6
6
  // { post: { to: "posts", one: true, gone: "with" } }: removing the post removes what links to it, as ops
7
7
  // { order: { to: "orders", one: true, part: true } }: structure, not a reference (is a, has a, composition):
8
8
  // what the item is part of, one id. A page places it by that and never pops it (docs/design.md, "A peek");
9
- // a link that goes with what it points at is part of it too. Any other link is a reference, and pops
9
+ // a link that goes with what it points at is part of it too. Any other link is a reference, and pops.
10
+ // { supplier: { to: "members", one: true, holds: "staff/posts[role=supplier]@members" } }: whoever it
11
+ // names is one a who-path of collections finds (no role, no @field: it's asked of them, not the writer),
12
+ // refused "supplier names someone who isn't among staff's posts with role supplier", checked by a cannot
10
13
  // roles who someone is to the document, beyond a member, each a who-path to them.
14
+ // title the field that names a collection's items, where it isn't the first field of words: { accounts: "name" }
11
15
  // owns who sees what: a who-path for the whole document, or one per collection (a collection not named
12
16
  // is everyone's). A page is sent, and told of, only the items its person sees.
13
17
  // kind { root: "shelves" }: a document for each item of another document's collection (shelf:1,
14
18
  // shelf:2), its collections each instance's own; a role's @field is that root item's, or the item's a write
15
- // is to where it has that field (a post's author).
19
+ // is to where it has that field (a post's author). `files: "apart"` keeps each instance's files in a folder of
20
+ // its own (book-1/), served only to who may hold it, and handed back with it (/export/book-1).
16
21
  // fills a field the server fills on every add, and only the server writes (a route's write, a reaction):
17
- // { cards: { added: "now" }, boards: { count: 0 } }; "now" is the instant it's added, "me" its writer.
22
+ // { cards: { added: "now" }, boards: { count: 0 } }; "now" is the instant it's added, "me" its writer. Where
23
+ // the seed gives the field wall clocks (2026-07-01T12:41:07, no Z), "now" is one: on the clock of the item's
24
+ // own zone (its field named zone, a time zone), else its kind's root's, else the document's own (/zone).
18
25
  // unique fields no two items of a collection share: { people: ["name"] }, or several together
19
26
  // ({ rooms: [["hotel", "name"]] }); an item without one is held to nothing.
20
27
  // noOverlap a collection's items that may not hold one time: { stays: { range: ["from", "until"], same:
@@ -50,6 +57,8 @@
50
57
  // refused: "…" }] }, held as the write leaves it (SQLite's by code, Postgres's by a trigger at its end).
51
58
  // apart lists of an item no id is in two of: { events: [{ lists: ["keen", "asked", "declined"], refused: "…" }] },
52
59
  // held as within is.
60
+ // notEmpty fields of words that are never none, nor only spaces: { notes: ["text"] }, refused "text cannot be empty"
61
+ // (a trigger). One a store holds already, from before it was said, is left until it's changed.
53
62
  // waits { by: "moderated", posts: "waiting", refused: "…" }: in a kind, while the root item's field is true, an
54
63
  // add to posts gives its field that moves (moves) as that first step, or it's refused in those words.
55
64
  //
@@ -65,10 +74,13 @@ import type { Op } from "./ops.ts";
65
74
 
66
75
  /** An app's definitions, as its stories' header lines say them, one a key. */
67
76
  export type Definitions = {
68
- links?: Record<string, string | { to: string; one?: true; gone?: "with"; part?: true }>;
77
+ links?: Record<string, string | { to: string; one?: true; gone?: "with"; part?: true; holds?: string }>;
69
78
  roles?: Record<string, string>;
79
+ /** Each collection's field that names an item (in a row, a chooser, a peek), where it isn't the first field of words
80
+ * the stories give: { accounts: "name" }, not its code. */
81
+ title?: Record<string, string>;
70
82
  owns?: string | Record<string, string>;
71
- kind?: { root: string };
83
+ kind?: { root: string; files?: "apart" };
72
84
  fills?: Record<string, Record<string, unknown>>;
73
85
  timed?: Record<string, string>;
74
86
  unique?: Record<string, (string | string[])[]>;
@@ -101,6 +113,8 @@ export type Definitions = {
101
113
  within?: Record<string, { lists: string[]; of: string; refused: string }[]>;
102
114
  /** Lists of an item no id is in two of (one answer each): by collection. */
103
115
  apart?: Record<string, { lists: string[]; refused: string }[]>;
116
+ /** Fields of words that are never none, nor only spaces: by collection. */
117
+ notEmpty?: Record<string, string[]>;
104
118
  /** In a kind, a yes-or-no field of the root item: while it's true, an add to each collection named gives its field
105
119
  * that moves as this first step, or it's refused in these words (a board held for approval, a post waiting).
106
120
  * src/settings.ts. */
@@ -144,21 +158,47 @@ export type Takes = { while: string; refused: string } & Record<string, string>;
144
158
  * each of its lines' qty times its price. */
145
159
  export type Total = { of: string; by: string; sum: string; times?: string };
146
160
 
147
- const TERM =
161
+ /** A who-path of collections in words (links' holds): "staff's posts with role supplier". */
162
+ export const pathSaid = (path: string) =>
163
+ path
164
+ .split("|")
165
+ .map((t) => {
166
+ const [, of, coll, not, field, value] = t.trim().match(TERM) ?? [];
167
+ return `${of ? `${of}'s ` : ""}${coll}${field ? (not ? ` with no ${field}` : ` with ${field} ${value}`) : ""}`;
168
+ })
169
+ .join(" or ");
170
+ export const TERM =
148
171
  /^(?:([a-z][a-z0-9-]*)\/)?([a-z][a-z0-9-]*)(?:\[(!?)([a-z][a-z0-9-]*)(?:=([^\]]+))?\])?(?:@([a-z][a-z0-9-]*))?$/;
149
172
 
150
- /** A who-path as a JavaScript expression of m (the member), roles, item, read and doc (this document), true when m
151
- * is one of them: `item` the item a role's @field is of. In a kind (`kind`), `item` is the root's `item` the item a role's @field is of. In a kind (`kind`), `item` is the root's
173
+ /** The roles named on the way to a role named in a who-path, it last (`seen`, those before it); refused where it's
174
+ * one of them, as a role can't be itself. */
175
+ const onTo = (role: string, seen: string[], where: string) => {
176
+ if (seen.includes(role))
177
+ throw new Error(
178
+ `${where}: the role ${role} names itself (${[...seen.slice(seen.indexOf(role)), role].join(" → ")})`,
179
+ );
180
+ return [...seen, role];
181
+ };
182
+
183
+ /** A who-path as a JavaScript expression of m (the member), item, read and doc (this document), true when m
184
+ * is one of them: a role in it, that role's who-path (`roles`, each by name; `seen`, those named on the way to it);
185
+ * `item` the item a role's @field is of. In a kind (`kind`), `item` is the root's `item` the item a role's @field is of. In a kind (`kind`), `item` is the root's
152
186
  * and `at` the item a write is to: an @field is the item's where it has that field (a post's author), else the root's
153
187
  * (the board's owners). */
154
- export function whoCode(path: string, roles: string[], where: string, kind = false): string {
188
+ export function whoCode(
189
+ path: string,
190
+ roles: Record<string, string>,
191
+ where: string,
192
+ kind = false,
193
+ seen: string[] = [],
194
+ ): string {
155
195
  const names = (v: string) => `(${v} === m || (Array.isArray(${v}) && ${v}.includes(m)))`;
156
196
  return path
157
197
  .split("|")
158
198
  .map((t) => t.trim())
159
199
  .map((t) => {
160
200
  if (t === "member") return "true";
161
- if (roles.includes(t)) return `roles.includes(${JSON.stringify(t)})`;
201
+ if (roles[t] !== undefined) return `(${whoCode(roles[t], roles, where, kind, onTo(t, seen, where))})`;
162
202
  if (/^@[a-z][a-z0-9-]*$/.test(t)) {
163
203
  const f = JSON.stringify(t.slice(1));
164
204
  return kind
@@ -189,7 +229,15 @@ export type WhoOf = {
189
229
  };
190
230
  /** A who-path as SQL of a row (`at`, of collection `coll`): true when $member is one of them. The same path its code
191
231
  * is written from (whoCode), so the query holds what's asked of an item. A role's @field is its kind's root item's. */
192
- export function whoSql(path: string, coll: string, at: string, who: WhoOf, where: string, root = false): string {
232
+ export function whoSql(
233
+ path: string,
234
+ coll: string,
235
+ at: string,
236
+ who: WhoOf,
237
+ where: string,
238
+ root = false,
239
+ seen: string[] = [],
240
+ ): string {
193
241
  const q = (n: string) => `"${n.replaceAll('"', '""')}"`;
194
242
  const names = (c: string, a: string, f: string) =>
195
243
  who.list(c, f)
@@ -200,7 +248,7 @@ export function whoSql(path: string, coll: string, at: string, who: WhoOf, where
200
248
  .map((t) => t.trim())
201
249
  .map((t) => {
202
250
  if (t === "member") return "TRUE";
203
- if (who.roles[t]) return `(${whoSql(who.roles[t]!, coll, at, who, where, true)})`;
251
+ if (who.roles[t]) return `(${whoSql(who.roles[t]!, coll, at, who, where, true, onTo(t, seen, where))})`;
204
252
  if (/^@[a-z][a-z0-9-]*$/.test(t)) {
205
253
  const f = t.slice(1);
206
254
  // in a role of a kind, the root item's field
@@ -248,7 +296,7 @@ export function whoRules(
248
296
  const where = `${doc}'s definitions`;
249
297
  const k = defs.kind;
250
298
  let out = k
251
- ? `\n/** ${doc} is one of many: a document for each of ${root}'s ${k.root} (${doc}:1), its items each kept with it. */\nexport const kind = ${JSON.stringify({ root: k.root, doc: root, column: doc })};\n`
299
+ ? `\n/** ${doc} is one of many: a document for each of ${root}'s ${k.root} (${doc}:1), its items each kept with it. */\nexport const kind = ${JSON.stringify({ root: k.root, doc: root, column: doc, ...(k.files ? { files: k.files } : {}) })};\n`
252
300
  : `\n/** ${doc} is one document. */\nexport const kind = null;\n`;
253
301
  out += `\n/** Each grant, read off the stories: the roles whose stories do it (a member: anyone). An op no story
254
302
  * does isn't one. */\nexport const grants: Record<string, string[]> = ${JSON.stringify(grants, null, 2)};\n`;
@@ -264,7 +312,7 @@ export function whoRules(
264
312
  ? `(read(${JSON.stringify(root)})[${JSON.stringify(k.root)}] ?? []).find((i: any) => i.id === Number(doc.split(/[:?]/)[1]))`
265
313
  : "at";
266
314
  out += `\n/** Who someone is to ${doc} (and to an item of it, \`at\`), beyond a member: each role whose who-path finds them. */\n`;
267
- out += `export function rolesOf(m: number, read: (doc: string) => any, doc: string, at?: any): string[] {\n const item: any = ${item};\n return [${roles.map((r) => `\n ${whoCode(defs.roles![r]!, [], where, !!k)} ? ${JSON.stringify(r)} : ""`).join(",")},\n ].filter(Boolean);\n}\n`;
315
+ out += `export function rolesOf(m: number, read: (doc: string) => any, doc: string, at?: any): string[] {\n const item: any = ${item};\n return [${roles.map((r) => `\n ${whoCode(defs.roles![r]!, defs.roles!, where, !!k, [r])} ? ${JSON.stringify(r)} : ""`).join(",")},\n ].filter(Boolean);\n}\n`;
268
316
  return out + sight(doc, collections, defs, roles, where);
269
317
  }
270
318
 
package/src/demo.css CHANGED
@@ -5,23 +5,20 @@
5
5
  :host {
6
6
  display: block;
7
7
  }
8
- :host([hidden]) {
9
- display: none;
10
- }
11
8
  nav {
12
9
  display: flex;
13
10
  flex-wrap: wrap;
14
11
  align-items: baseline;
15
12
  gap: var(--space-4) var(--space-12);
16
13
  padding: var(--space-8) var(--space-12);
17
- border-radius: 4px;
14
+ border-radius: var(--radius);
18
15
  background: var(--well);
19
16
  color: var(--ink);
20
17
  font: var(--font-row);
21
18
  }
22
19
  a {
23
20
  padding: 0 var(--space-8);
24
- border-radius: 99px;
21
+ border-radius: var(--radius-pill);
25
22
  color: inherit;
26
23
  }
27
24
  a[aria-current] {
package/src/draft.ts CHANGED
@@ -10,13 +10,17 @@
10
10
  type Value = string | boolean;
11
11
  type Control = HTMLInputElement;
12
12
 
13
- /** Every draft on the page. */
14
- const drafts = new Set<Draft>();
13
+ /** Every draft on the page, held weakly: one its page lets go of is let go here too. */
14
+ const drafts = new Set<WeakRef<Draft>>();
15
15
  /** Whether a draft holds changes in a form that's shown: what's typed and not kept, or what its form says isn't (a
16
16
  * choice that's no control: the people chosen for an event), which a reload would lose (a page told another build
17
17
  * waits for none, src/page.ts). */
18
18
  export const unsaved = () =>
19
- [...drafts].some((d) => d.form.checkVisibility() && (d.changed || Object.keys(d.edits()).length > 0));
19
+ [...drafts].some((ref) => {
20
+ const d = ref.deref();
21
+ if (!d) return (drafts.delete(ref), false);
22
+ return d.form.checkVisibility() && (d.changed || Object.keys(d.edits()).length > 0);
23
+ });
20
24
 
21
25
  export class Draft {
22
26
  /** Whether its form last said it holds changes not kept. */
@@ -25,7 +29,7 @@ export class Draft {
25
29
  readonly form: HTMLFormElement,
26
30
  readonly note: HTMLElement,
27
31
  ) {
28
- drafts.add(this);
32
+ drafts.add(new WeakRef(this));
29
33
  }
30
34
  /** The form as the document has it: afresh, every control set; as it changes elsewhere, only those
31
35
  * not being changed here. */
@@ -67,7 +71,9 @@ export class Draft {
67
71
  }
68
72
  /** Why a write was refused, said in the note; nothing takes it back. */
69
73
  refuse(why: string) {
74
+ // (refused, an app's own word for it; j-refused, joined's parts': danger)
70
75
  this.note.classList.toggle("refused", !!why);
76
+ this.note.classList.toggle("j-refused", !!why);
71
77
  this.#say(why);
72
78
  }
73
79
  /** Never mind (`never`) puts back what it holds. (Its surface closes itself: src/surface.ts.) */
package/src/drawer.ts CHANGED
@@ -24,6 +24,8 @@ export type Host = {
24
24
  title(it: Element): string;
25
25
  /** The items a link may be to, as they're on the page: each its key and its title. */
26
26
  choices(f: Field): [key: number, words: string][];
27
+ /** The document its items are of, as the page holds it (a guest's, with its code): a file is kept for it. */
28
+ doc(): string;
27
29
  add(spec: Spec, value: object): Promise<Answer>;
28
30
  /** What's said of a write refused once the drawer has closed (a removal). */
29
31
  said(request: Promise<Answer>): void;
@@ -61,7 +63,7 @@ export class Drawer {
61
63
  const form = this.#form.id,
62
64
  foot = el(
63
65
  "footer",
64
- {},
66
+ { part: "foot" },
65
67
  this.#gone,
66
68
  el("button", { type: "button", className: "act", name: "never" }, "Never mind"),
67
69
  this.#go,
@@ -85,7 +87,7 @@ export class Drawer {
85
87
  this.#form.addEventListener("submit", (e) => (e.preventDefault(), void this.#save()));
86
88
  this.#gone.addEventListener("click", () => {
87
89
  const it = this.open as Item;
88
- ask(`Remove ${host.title(it)}?`, () => (this.show(null), host.said(it.removeItem!())));
90
+ ask(`${host.title(it)} will be removed.`, () => (this.show(null), host.said(it.removeItem!())));
89
91
  });
90
92
  this.#hash = inHash(
91
93
  spec.one,
@@ -98,10 +100,31 @@ export class Drawer {
98
100
  #control = (name: string) => this.#form.elements.namedItem(name) as HTMLInputElement | HTMLSelectElement;
99
101
  /** A field as the drawer asks for it, in its label, as its kind says (./fields.ts). */
100
102
  #asked(f: Asked) {
101
- const c = control(f, this.host.label(f), { choices: (f) => this.host.choices(f), changed: () => this.#shown() });
103
+ const c = control(f, this.host.label(f), {
104
+ choices: () => this.#offered(f),
105
+ // what's offered may follow what's chosen (a field's `not`)
106
+ changed: () => (this.#shown(), this.asks.some((a) => a.not) && this.#choices()),
107
+ doc: () => this.host.doc(),
108
+ });
102
109
  this.#controls.set(f.name, c);
103
110
  return c;
104
111
  }
112
+ /** What a link may be to: the page's items, but none its field `not` holds now (an owner never offered as their own
113
+ * accountant), unless it's linked to them already. */
114
+ #offered(f: Asked) {
115
+ const all = this.host.choices(f);
116
+ if (!f.not) return all;
117
+ const out = new Set(this.#holds(f.not)),
118
+ mine = new Set(this.#holds(f.name));
119
+ return all.filter(([key]) => !out.has(key) || mine.has(key));
120
+ }
121
+ /** The ids a field holds now: as it's chosen in the form where it's asked, else as the open item has it. */
122
+ #holds(name: string): number[] {
123
+ const c = this.#controls.get(name),
124
+ box = this.#control(name);
125
+ const v = c && box ? c.kept(box.value) : this.open && this.open !== "new" ? this.open.data[name] : undefined;
126
+ return [v ?? []].flat() as number[];
127
+ }
105
128
  /** What each control offers, as the page has it now (the items a link may be to, the people to choose). */
106
129
  #choices() {
107
130
  for (const f of this.asks) {
@@ -210,13 +233,16 @@ export class Drawer {
210
233
  .filter(([name, v]) => v !== "" || (!adding && words(name)))
211
234
  .map(([name, v]) => [name, this.#controls.get(name)!.kept(v)]),
212
235
  );
236
+ const was = this.open;
213
237
  const why = adding
214
238
  ? await this.host.add(this.spec, { ...this.#given, ...this.#filled, ...edits })
215
239
  : stays
216
240
  ? `${stays} can't be left empty`
217
241
  : ((Object.keys(edits).length ? await item.replace!(edits) : undefined) ??
218
242
  (cleared.length ? await item.removeField!(...cleared) : undefined));
243
+ // what was saved, if it's open still: one opened meanwhile (a new one asked) is left as it is
244
+ if (this.open !== was) return;
219
245
  this.#draft.refuse(why ?? "");
220
- if (!why) this.show(adding ? null : this.open);
246
+ if (!why) this.show(adding ? null : was);
221
247
  }
222
248
  }
package/src/engine.ts CHANGED
@@ -110,8 +110,9 @@ const WRITING = 0x6a6f696e; // "join"
110
110
  /** SQLite: bun:sqlite's Database, as it is, its constraint failures thrown as Refused. */
111
111
  export function sqlite(file: string, { readonly = false } = {}): Engine {
112
112
  const db = new Database(file, readonly ? { readonly, strict: true } : { create: true, strict: true });
113
- if (!readonly) db.run("PRAGMA journal_mode = WAL");
113
+ // another's write waited for from the first: a store opened by two processes at once (its log recovered by one)
114
114
  db.run("PRAGMA busy_timeout = 5000");
115
+ if (!readonly) db.run("PRAGMA journal_mode = WAL");
115
116
  // a link is a foreign key: what it points at is there, and isn't removed from under it
116
117
  db.run("PRAGMA foreign_keys = ON");
117
118
  // a value's form, as a guard asks it: a regular expression, matched (SQLite has no REGEXP of its own)
@@ -282,13 +283,20 @@ export type Trigger = {
282
283
  body: string;
283
284
  temp?: boolean;
284
285
  };
286
+ /** A function's body as Postgres quotes it: between dollar tags its words don't hold ($joined$, else $joined1$…), so
287
+ * no word of a refusal ends it. */
288
+ const dollared = (body: string) => {
289
+ let tag = "$joined$";
290
+ for (let n = 1; body.includes(tag); n++) tag = `$joined${n}$`;
291
+ return `${tag} ${body} ${tag}`;
292
+ };
285
293
  /** A trigger, as each says it: SQLite's a statement, Postgres's a function, made again in place. */
286
294
  export function triggerSql(dialect: Dialect, t: Trigger) {
287
295
  const q = (n: string) => `"${n.replaceAll('"', '""')}"`;
288
296
  if (dialect === "sqlite")
289
297
  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`;
290
298
  const body = t.when ? `IF ${t.when} THEN ${t.body} END IF;` : t.body;
291
- 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`)}()`;
299
+ return `CREATE OR REPLACE FUNCTION ${q(`${t.name}_fn`)}() RETURNS trigger LANGUAGE plpgsql AS ${dollared(`BEGIN ${body} IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; RETURN NEW; END`)}; CREATE OR REPLACE TRIGGER ${q(t.name)} ${t.at} ${t.event} ON ${q(t.table)} FOR EACH ROW EXECUTE FUNCTION ${q(`${t.name}_fn`)}()`;
292
300
  }
293
301
  /** Postgres's trigger that waits for the end of a write (a constraint trigger, deferred): its body run for each row
294
302
  * changed on any of its tables, `item` the row's column naming the item it's of; held at the write's end, as the store
@@ -299,7 +307,7 @@ export function constraintSql(t: { name: string; on: { table: string; event: str
299
307
  // each table's a statement of its own (its function made again with each), as the store makes and drops them
300
308
  return t.on.map(
301
309
  ({ table, event }, n) =>
302
- `CREATE OR REPLACE FUNCTION ${fn}() RETURNS trigger LANGUAGE plpgsql AS $joined$ DECLARE item INTEGER; BEGIN IF TG_OP = 'DELETE' THEN item := OLD.${t.item}; ELSE item := NEW.${t.item}; END IF; ${t.body} RETURN NULL; END $joined$; CREATE CONSTRAINT TRIGGER ${q(`${t.name}_${n}`)} AFTER ${event} ON ${q(table)} DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION ${fn}()`,
310
+ `CREATE OR REPLACE FUNCTION ${fn}() RETURNS trigger LANGUAGE plpgsql AS ${dollared(`DECLARE item INTEGER; BEGIN IF TG_OP = 'DELETE' THEN item := OLD.${t.item}; ELSE item := NEW.${t.item}; END IF; ${t.body} RETURN NULL; END`)}; CREATE CONSTRAINT TRIGGER ${q(`${t.name}_${n}`)} AFTER ${event} ON ${q(table)} DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION ${fn}()`,
303
311
  );
304
312
  }
305
313
  /** A trigger's statement refusing a change where `cond` holds, in its words (SQL of a string). */
@@ -327,9 +335,10 @@ export function numbered(sql: string, args: unknown[]): [string, unknown[]] {
327
335
  for (let i = 0; i < sql.length;) {
328
336
  const c = sql[i]!;
329
337
  if (c === "'" || c === '"') {
330
- // a quote doubled is one, inside
338
+ // a quote doubled is one, inside; one never closed, the rest (for the database to refuse)
331
339
  let j = sql.indexOf(c, i + 1);
332
- while (sql[j + 1] === c) j = sql.indexOf(c, j + 2);
340
+ while (j >= 0 && sql[j + 1] === c) j = sql.indexOf(c, j + 2);
341
+ if (j < 0) j = sql.length;
333
342
  out += sql.slice(i, j + 1);
334
343
  i = j < 0 ? sql.length : j + 1;
335
344
  } else if (c === "$") {
package/src/fields.ts CHANGED
@@ -9,18 +9,28 @@ import { choose, chosen } from "./draft.ts";
9
9
  import { iconButton } from "./icons.ts";
10
10
  import { hueOf } from "./hues.ts";
11
11
  import { face, typeahead } from "./parts.ts";
12
+ import { attachment } from "./attachment.ts";
12
13
  import { PlaceSearch } from "./place-search.ts";
13
14
  import type { Field } from "./rows.ts";
14
15
  import { lasts, lengthOf } from "./time.ts";
15
16
 
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
17
18
  * units, words long enough for a box of lines), and whether, once an item has it, it's only said there (readonly):
18
- * asked as it's added, never changed after. */
19
- export type Kind = { label?: string; as?: "money" | "long"; currency?: string; readonly?: boolean };
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
+ };
20
29
  export type Asked = Field & Kind;
21
30
 
22
- /** What a control needs of the page: what a link may be to, and that what it holds has changed. */
23
- export type Context = { choices(f: Field): [key: number, words: string][]; changed(): void };
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 };
24
34
 
25
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
26
36
  * document keeps it, and what it offers drawn again as what may be chosen changes. */
@@ -36,6 +46,12 @@ export const el = <K extends keyof HTMLElementTagNameMap>(tag: K, props: object
36
46
  e.append(...inside);
37
47
  return e;
38
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
+ };
39
55
  /** Told each time a control is filled from the document (a Draft's fill, which says what it holds in data-saved):
40
56
  * after it, its value is what was filled. */
41
57
  const filled = (control: HTMLElement, then: () => void) =>
@@ -63,10 +79,31 @@ export function reads(f: Asked, v: unknown): string | null {
63
79
  return null;
64
80
  }
65
81
 
66
- /** A field's control, as its kind and type say: Web Awesome's for what it has (a box, a number, a tick, words of
67
- * several lines, a choice of a few), each its label its own; joined's for what's its own (a length, a zone, a place,
68
- * people, a typeahead). */
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`. */
69
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 {
70
107
  const name = f.name,
71
108
  plain = (v: unknown) => (v === undefined || v === null ? "" : String(v)),
72
109
  // its name an attribute at once (Web Awesome reflects a property only as it next draws): a form finds it by it
@@ -129,6 +166,7 @@ export function control(f: Asked, words: string, page: Context): Control {
129
166
  };
130
167
  }
131
168
  if (f.type === "zone") return zone(f, words, page);
169
+ if (f.type === "file") return file(f, words, page);
132
170
  if (f.type === "place") return place(f, words, page);
133
171
  if (f.as === "long") return { ...same, el: wa("wa-textarea", { rows: 4, resize: "auto" }), shown: plain };
134
172
  return { ...same, el: wa("wa-input"), shown: plain };
@@ -141,8 +179,8 @@ function one(f: Field, words: string, page: Context): Control {
141
179
  required: boolean;
142
180
  },
143
181
  find = el("input", { className: "find", autocomplete: "off", ariaLabel: words }),
144
- list = el("div", { className: "j-choices", role: "listbox", hidden: true }),
145
- many = el("label", {}, words, find, list);
182
+ list = el("div", { className: "j-choices", role: "listbox", ariaLabel: words, hidden: true }),
183
+ many = el("label", {}, named(words), find, list);
146
184
  select.setAttribute("name", f.name);
147
185
  const offer = typeahead(
148
186
  find,
@@ -186,12 +224,17 @@ function one(f: Field, words: string, page: Context): Control {
186
224
  function people(f: Field, words: string, page: Context): Control {
187
225
  const held = el("input", { type: "hidden", name: f.name }),
188
226
  chips = el("div", { className: "j-chips", role: "group", ariaLabel: words });
227
+ chips.setAttribute("part", "chips");
189
228
  const ids = (): number[] => JSON.parse(held.value || "[]");
190
229
  function refresh() {
191
230
  chips.replaceChildren(
192
231
  ...page.choices(f).map(([key, who]) => {
193
- const b = el("button", { type: "button", ariaPressed: String(ids().includes(key)) }, face(key, who), who);
232
+ const on = ids().includes(key),
233
+ b = el("button", { type: "button", ariaPressed: String(on) }, face(key, who), who);
194
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"}`);
195
238
  b.addEventListener("click", () => {
196
239
  const now = ids().includes(key) ? ids().filter((k) => k !== key) : [...ids(), key].sort((a, b) => a - b);
197
240
  held.value = JSON.stringify(now);
@@ -205,17 +248,39 @@ function people(f: Field, words: string, page: Context): Control {
205
248
  // filled by the draft without an input event: the chips follow it as it's filled
206
249
  filled(held, refresh);
207
250
  return {
208
- el: el("div", { className: "label" }, el("span", {}, words), held, chips),
251
+ el: el("div", { className: "label" }, named(words), held, chips),
209
252
  shown: (v) => JSON.stringify([...((v as number[]) ?? [])].sort((a, b) => a - b)),
210
253
  kept: (s) => JSON.parse(String(s) || "[]"),
211
254
  refresh,
212
255
  };
213
256
  }
214
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
+
215
274
  /** A time zone, found by typing a city ("tokyo", "new york"); what's typed is kept only where it's one. */
216
275
  function zone(f: Field, words: string, page: Context): Control {
217
- const input = el("input", { name: f.name, autocomplete: "off", placeholder: "A city: Tokyo, London" }),
218
- list = el("div", { className: "j-choices", role: "listbox", hidden: true });
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 });
219
284
  typeahead(
220
285
  input,
221
286
  list,
@@ -228,7 +293,7 @@ function zone(f: Field, words: string, page: Context): Control {
228
293
  input.addEventListener("input", check);
229
294
  filled(input, check);
230
295
  return {
231
- el: el("label", {}, words, input, list),
296
+ el: el("label", {}, named(words), input, list),
232
297
  shown: (v) => (v ? String(v) : ""),
233
298
  kept: (s) => s,
234
299
  refresh() {},
@@ -260,7 +325,15 @@ function place(f: Field, words: string, page: Context): Control {
260
325
  find.addEventListener("keydown", (e) => e.key === "Enter" && e.preventDefault());
261
326
  filled(held, () => ((at.textContent = ""), said()));
262
327
  return {
263
- el: el("label", { className: "place" }, words, held, el("span", { className: "where" }, at, clear), find, list),
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
+ ),
264
337
  shown: (v) => (v ? String(v) : ""),
265
338
  kept: (s) => s || undefined,
266
339
  refresh: said,
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
+ };