@composable-os/pack-programs 0.0.0-stage → 0.1.0-beta.8

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 (39) hide show
  1. package/LICENSE +109 -0
  2. package/dist/authoring.d.ts +47 -0
  3. package/dist/authoring.js +493 -0
  4. package/dist/blocks/programs-bank/exercise-bank.d.ts +4 -0
  5. package/dist/blocks/programs-bank/exercise-bank.js +68 -0
  6. package/dist/blocks/programs-builder/program-builder.d.ts +26 -0
  7. package/dist/blocks/programs-builder/program-builder.js +295 -0
  8. package/dist/blocks/programs-class-today/class-today.d.ts +6 -0
  9. package/dist/blocks/programs-class-today/class-today.js +15 -0
  10. package/dist/blocks/programs-coach-client/coach-client.d.ts +5 -0
  11. package/dist/blocks/programs-coach-client/coach-client.js +10 -0
  12. package/dist/blocks/programs-native-class-today/class-today-screen.d.ts +6 -0
  13. package/dist/blocks/programs-native-class-today/class-today-screen.js +14 -0
  14. package/dist/blocks/programs-native-coach-client/coach-client-screen.d.ts +7 -0
  15. package/dist/blocks/programs-native-coach-client/coach-client-screen.js +9 -0
  16. package/dist/blocks/programs-native-progress/progress-screen.d.ts +5 -0
  17. package/dist/blocks/programs-native-progress/progress-screen.js +31 -0
  18. package/dist/blocks/programs-native-session/session-screen.d.ts +7 -0
  19. package/dist/blocks/programs-native-session/session-screen.js +130 -0
  20. package/dist/blocks/programs-native-today/today-screen.d.ts +7 -0
  21. package/dist/blocks/programs-native-today/today-screen.js +11 -0
  22. package/dist/blocks/programs-progress/progress.d.ts +10 -0
  23. package/dist/blocks/programs-progress/progress.js +40 -0
  24. package/dist/blocks/programs-session/session-view.d.ts +9 -0
  25. package/dist/blocks/programs-session/session-view.js +116 -0
  26. package/dist/blocks/programs-today/today.d.ts +7 -0
  27. package/dist/blocks/programs-today/today.js +16 -0
  28. package/dist/client/index.d.ts +1723 -0
  29. package/dist/client/index.js +779 -0
  30. package/dist/dashboards.d.ts +5 -0
  31. package/dist/dashboards.js +145 -0
  32. package/dist/index.d.ts +1181 -0
  33. package/dist/index.js +608 -0
  34. package/dist/layout.d.ts +88 -0
  35. package/dist/layout.js +268 -0
  36. package/dist/tools.d.ts +344 -0
  37. package/dist/tools.js +930 -0
  38. package/package.json +36 -4
  39. package/README.md +0 -3
@@ -0,0 +1,779 @@
1
+ // The Programs pack's headless entry (stage 41, step 5; ADR 0418): functions and hooks over the
2
+ // typed client, no markup. A client app imports it as `@composable-os/pack-programs/client` and
3
+ // hands it its generated client; the Programs blocks render what it returns.
4
+ //
5
+ // As every pack's entry: the operations are typed from the pack's own tool schemas and the host's
6
+ // record operations, it takes the client and the app's `useQuery`, `useMutation`, `useState` and
7
+ // `useEffect` as arguments (no React or TanStack import), and it holds no rules. What a layout may
8
+ // hold is the host's document schema (a fault comes back with its path, which `faultsOf` maps to
9
+ // where the builder shows it); who may publish is the host's (`usePublish` is offered from what
10
+ // `user.me` says the account holds, and the host still decides); the dates, targets and last
11
+ // numbers are the tools'. The editing functions below only move parts of a layout around.
12
+ import { packHooks } from "@composable-os/client";
13
+ export const PROGRAM = "programs.program";
14
+ export const EXERCISE = "programs.exercise";
15
+ export const SESSION = "programs.session";
16
+ export const LOG = "programs.log";
17
+ // --- Reading a session ---------------------------------------------------------------------------
18
+ /** "3 × 8–12 @ 20 kg, 32X1, rest 90 s": a set target as a person reads it. */
19
+ export function describeSet(set) {
20
+ const parts = [];
21
+ if (set.kind === "reps")
22
+ parts.push(set.repsMax ? `${set.reps}–${set.repsMax} reps` : `${set.reps} reps`);
23
+ else if (set.kind === "time")
24
+ parts.push(`${set.seconds} s`);
25
+ else
26
+ parts.push(set.holds ? `${set.holds} × ${set.seconds} s hold` : `${set.seconds} s hold`);
27
+ if (set.load)
28
+ parts[0] = `${parts[0]} @ ${set.load} kg`;
29
+ if (set.kind === "reps" && set.tempo)
30
+ parts.push(set.tempo);
31
+ if (set.rest)
32
+ parts.push(`rest ${set.rest} s`);
33
+ return parts.join(", ");
34
+ }
35
+ /** A prescription's sets, grouped when they repeat: "3 × 8 reps @ 20 kg". */
36
+ export function describeSets(sets) {
37
+ const groups = [];
38
+ for (const set of sets) {
39
+ const text = describeSet(set);
40
+ const last = groups.at(-1);
41
+ if (last?.text === text)
42
+ last.count += 1;
43
+ else
44
+ groups.push({ text, count: 1 });
45
+ }
46
+ return groups.map((g) => (g.count > 1 ? `${g.count} × ${g.text}` : g.text)).join(", then ");
47
+ }
48
+ /** The exercises of a level, whatever its mode. */
49
+ export function levelExercises(level) {
50
+ return level.mode === "one" ? [level.exercise] : level.exercises;
51
+ }
52
+ /** What a level is, in words: "Level 3: one of these". */
53
+ export function levelLabel(level) {
54
+ return level.mode === "alternatives"
55
+ ? `Level ${level.level}: one of these`
56
+ : level.mode === "together"
57
+ ? `Level ${level.level}: together`
58
+ : `Level ${level.level}`;
59
+ }
60
+ /** The sets already logged of one prescription's set number in a session. */
61
+ export function loggedFor(logged, item, exercise, setNumber) {
62
+ return logged.find((l) => l.item === item && l.exercise === exercise && l.setNumber === setNumber);
63
+ }
64
+ /** A number typed in a field, or undefined when it is empty or not one. */
65
+ export function numberFrom(text) {
66
+ if (text.trim() === "")
67
+ return undefined;
68
+ const value = Number(text.replace(",", "."));
69
+ return Number.isFinite(value) ? value : undefined;
70
+ }
71
+ // --- Faults from the host, where they are ---------------------------------------------------------
72
+ /**
73
+ * The faults the host reported for a layout, by path: `weeks.0.sessions.1.day` → "At most 7". The
74
+ * builder shows each beside the part it names, and a part's own faults and those inside it
75
+ * (`faultsUnder`). The host's document check reports every fault with its path (ADR 0445); a ref
76
+ * to a missing exercise reports its path in `details.path`.
77
+ */
78
+ export function faultsOf(error, field = "layout") {
79
+ const out = new Map();
80
+ const details = error?.details;
81
+ if (!details || (details.field && details.field !== field))
82
+ return out;
83
+ for (const issue of details.issues ?? []) {
84
+ out.set((issue.path ?? []).join("."), issue.message ?? "Not allowed here");
85
+ }
86
+ if (details.path) {
87
+ const message = error.message ?? "Not found";
88
+ out.set(details.path.join("."), message.replace(/^[^:]*:\s*/, ""));
89
+ }
90
+ return out;
91
+ }
92
+ /** The faults at `path` and inside it. */
93
+ export function faultsUnder(faults, path) {
94
+ return [...faults].filter(([p]) => p === path || p.startsWith(`${path}.`)).map(([, m]) => m);
95
+ }
96
+ const clone = (value) => JSON.parse(JSON.stringify(value));
97
+ /** The path the host names a part with (`weeks.0.sessions.1.blocks.0.items.2`). */
98
+ export function pathOf(at) {
99
+ const parts = [`weeks.${at.week}`];
100
+ if (at.session !== undefined)
101
+ parts.push(`sessions.${at.session}`);
102
+ if (at.block !== undefined)
103
+ parts.push(`blocks.${at.block}`);
104
+ if (at.item !== undefined)
105
+ parts.push(`items.${at.item}`);
106
+ return parts.join(".");
107
+ }
108
+ export function emptyLayout() {
109
+ return { weeks: [{ sessions: [] }] };
110
+ }
111
+ /** A set as a new one starts: 8 reps, or 30 seconds for time, 20 for a hold. */
112
+ export function newSet(measure) {
113
+ if (measure === "time")
114
+ return { kind: "time", seconds: 30 };
115
+ if (measure === "hold")
116
+ return { kind: "hold", seconds: 20 };
117
+ return { kind: "reps", reps: 8 };
118
+ }
119
+ export function newPrescription(exercise, measure, sets = 3) {
120
+ return { exercise, sets: Array.from({ length: sets }, () => newSet(measure)) };
121
+ }
122
+ /** The next free label in a list: A, B, C… for blocks; A1, A2… for a block's items. */
123
+ export function nextLabel(taken, prefix = "") {
124
+ if (!prefix) {
125
+ for (let c = 65; c < 91; c += 1) {
126
+ const label = String.fromCharCode(c);
127
+ if (!taken.includes(label))
128
+ return label;
129
+ }
130
+ return `Z${taken.length}`;
131
+ }
132
+ for (let n = 1; n < 100; n += 1) {
133
+ if (!taken.includes(`${prefix}${n}`))
134
+ return `${prefix}${n}`;
135
+ }
136
+ return `${prefix}${taken.length + 1}`;
137
+ }
138
+ function sessionAt(layout, at) {
139
+ const session = layout.weeks[at.week]?.sessions[at.session ?? -1];
140
+ if (!session)
141
+ throw new Error("No session there");
142
+ return session;
143
+ }
144
+ function blockAt(layout, at) {
145
+ const block = sessionAt(layout, at).blocks[at.block ?? -1];
146
+ if (!block)
147
+ throw new Error("No block there");
148
+ return block;
149
+ }
150
+ function itemAt(layout, at) {
151
+ const item = blockAt(layout, at).items[at.item ?? -1];
152
+ if (!item)
153
+ throw new Error("No item there");
154
+ return item;
155
+ }
156
+ /** The prescription at `at`: an "all" item's `exercise`, or a level's. */
157
+ export function prescriptionAt(layout, at) {
158
+ const item = itemAt(layout, at);
159
+ if (item.kind === "all") {
160
+ const p = item.exercises[at.exercise ?? 0];
161
+ if (!p)
162
+ throw new Error("No exercise there");
163
+ return p;
164
+ }
165
+ const level = item.levels[at.level ?? 0];
166
+ if (!level)
167
+ throw new Error("No level there");
168
+ const p = levelExercises(level)[at.exercise ?? 0];
169
+ if (!p)
170
+ throw new Error("No exercise there");
171
+ return p;
172
+ }
173
+ const edit = (layout, change) => {
174
+ const copy = clone(layout);
175
+ change(copy);
176
+ return copy;
177
+ };
178
+ /** Moves an entry of a list from one place to another (drag and drop, or a key). */
179
+ export function move(list, from, to) {
180
+ const out = [...list];
181
+ if (from < 0 || from >= out.length)
182
+ return out;
183
+ const [entry] = out.splice(from, 1);
184
+ out.splice(Math.max(0, Math.min(to, out.length)), 0, entry);
185
+ return out;
186
+ }
187
+ export const layoutEdits = {
188
+ addWeek: (layout) => edit(layout, (l) => {
189
+ l.weeks.push({ sessions: [] });
190
+ }),
191
+ /** A copy of week `week`, right after it. */
192
+ copyWeek: (layout, week) => edit(layout, (l) => {
193
+ const copy = clone(l.weeks[week]);
194
+ if (copy) {
195
+ delete copy.label;
196
+ l.weeks.splice(week + 1, 0, copy);
197
+ }
198
+ }),
199
+ removeWeek: (layout, week) => edit(layout, (l) => {
200
+ l.weeks.splice(week, 1);
201
+ if (!l.weeks.length)
202
+ l.weeks.push({ sessions: [] });
203
+ }),
204
+ setWeekLabel: (layout, week, label) => edit(layout, (l) => {
205
+ const w = l.weeks[week];
206
+ if (!w)
207
+ return;
208
+ if (label.trim())
209
+ w.label = label;
210
+ else
211
+ delete w.label;
212
+ }),
213
+ addSession: (layout, week) => edit(layout, (l) => {
214
+ const w = l.weeks[week];
215
+ if (!w)
216
+ return;
217
+ const used = new Set(w.sessions.map((s) => s.day));
218
+ const day = [1, 3, 5, 2, 4, 6, 7].find((d) => !used.has(d)) ?? 1;
219
+ w.sessions.push({
220
+ name: `Session ${String.fromCharCode(65 + w.sessions.length)}`,
221
+ day,
222
+ blocks: [],
223
+ });
224
+ w.sessions.sort((a, b) => a.day - b.day);
225
+ }),
226
+ /** A copy of a session: in its own week, or into every later week (`toEveryWeek`). */
227
+ copySession: (layout, at, toWeek) => edit(layout, (l) => {
228
+ const session = clone(sessionAt(l, at));
229
+ const week = l.weeks[toWeek ?? at.week];
230
+ if (!week)
231
+ return;
232
+ if (toWeek === undefined)
233
+ session.name = `${session.name} (copy)`;
234
+ week.sessions.push(session);
235
+ week.sessions.sort((a, b) => a.day - b.day);
236
+ }),
237
+ removeSession: (layout, at) => edit(layout, (l) => {
238
+ l.weeks[at.week]?.sessions.splice(at.session ?? -1, 1);
239
+ }),
240
+ moveSession: (layout, week, from, to) => edit(layout, (l) => {
241
+ const w = l.weeks[week];
242
+ if (w)
243
+ w.sessions = move(w.sessions, from, to);
244
+ }),
245
+ setSession: (layout, at, values) => edit(layout, (l) => {
246
+ const s = sessionAt(l, at);
247
+ if (values.name !== undefined)
248
+ s.name = values.name;
249
+ if (values.day !== undefined)
250
+ s.day = values.day;
251
+ if (values.focus !== undefined) {
252
+ if (values.focus.trim())
253
+ s.focus = values.focus;
254
+ else
255
+ delete s.focus;
256
+ }
257
+ }),
258
+ setWarmup: (layout, at, text) => edit(layout, (l) => {
259
+ const s = sessionAt(l, at);
260
+ const warmup = { ...(s.warmup ?? {}) };
261
+ if (text.trim())
262
+ warmup.text = text;
263
+ else
264
+ delete warmup.text;
265
+ if (warmup.text || warmup.exercises?.length)
266
+ s.warmup = warmup;
267
+ else
268
+ delete s.warmup;
269
+ }),
270
+ addBlock: (layout, at) => edit(layout, (l) => {
271
+ const s = sessionAt(l, at);
272
+ s.blocks.push({ label: nextLabel(s.blocks.map((b) => b.label)), items: [] });
273
+ }),
274
+ removeBlock: (layout, at) => edit(layout, (l) => {
275
+ sessionAt(l, at).blocks.splice(at.block ?? -1, 1);
276
+ }),
277
+ moveBlock: (layout, at, from, to) => edit(layout, (l) => {
278
+ const s = sessionAt(l, at);
279
+ s.blocks = move(s.blocks, from, to);
280
+ }),
281
+ setBlock: (layout, at, values) => edit(layout, (l) => {
282
+ const b = blockAt(l, at);
283
+ if (values.label !== undefined)
284
+ b.label = values.label;
285
+ if (values.rounds !== undefined) {
286
+ if (values.rounds === null)
287
+ delete b.rounds;
288
+ else
289
+ b.rounds = values.rounds;
290
+ }
291
+ }),
292
+ /** An item for everyone with one exercise, or with levels (level 1 of the exercise). */
293
+ addItem: (layout, at, exercise, measure, kind = "all") => edit(layout, (l) => {
294
+ const b = blockAt(l, at);
295
+ const label = nextLabel(b.items.map((i) => i.label), b.label);
296
+ const p = newPrescription(exercise, measure);
297
+ b.items.push(kind === "all"
298
+ ? { kind: "all", label, exercises: [p] }
299
+ : { kind: "levels", label, levels: [{ mode: "one", level: 1, exercise: p }] });
300
+ }),
301
+ removeItem: (layout, at) => edit(layout, (l) => {
302
+ blockAt(l, at).items.splice(at.item ?? -1, 1);
303
+ }),
304
+ /** Moves an item within its block, or into another block of the same session. */
305
+ moveItem: (layout, at, to) => edit(layout, (l) => {
306
+ const s = sessionAt(l, at);
307
+ const [item] = s.blocks[at.block ?? -1]?.items.splice(at.item ?? -1, 1) ?? [];
308
+ const target = s.blocks[to.block];
309
+ if (!item || !target)
310
+ return;
311
+ target.items.splice(Math.max(0, Math.min(to.item, target.items.length)), 0, item);
312
+ }),
313
+ setItemLabel: (layout, at, label) => edit(layout, (l) => {
314
+ itemAt(l, at).label = label;
315
+ }),
316
+ /** Everyone, or levels: an item's exercises become level 1, or level 1 becomes everyone's. */
317
+ setItemKind: (layout, at, kind) => edit(layout, (l) => {
318
+ const b = blockAt(l, at);
319
+ const index = at.item ?? -1;
320
+ const item = b.items[index];
321
+ if (!item || item.kind === kind)
322
+ return;
323
+ if (kind === "levels" && item.kind === "all") {
324
+ const [first, ...rest] = item.exercises;
325
+ const level = rest.length && first
326
+ ? { mode: "together", level: 1, exercises: item.exercises }
327
+ : { mode: "one", level: 1, exercise: first };
328
+ b.items[index] = {
329
+ kind: "levels",
330
+ label: item.label,
331
+ levels: [level],
332
+ ...(item.notes ? { notes: item.notes } : {}),
333
+ };
334
+ }
335
+ else if (kind === "all" && item.kind === "levels") {
336
+ const first = item.levels[0];
337
+ b.items[index] = {
338
+ kind: "all",
339
+ label: item.label,
340
+ exercises: first ? levelExercises(first) : [],
341
+ ...(item.notes ? { notes: item.notes } : {}),
342
+ };
343
+ }
344
+ }),
345
+ /** A new level (the lowest free number) with one exercise. */
346
+ addLevel: (layout, at, exercise, measure, level) => edit(layout, (l) => {
347
+ const item = itemAt(l, at);
348
+ if (item.kind !== "levels")
349
+ return;
350
+ const used = new Set(item.levels.map((x) => x.level));
351
+ const number = level ?? [1, 2, 3, 4, 5].find((n) => !used.has(n)) ?? 5;
352
+ item.levels.push({
353
+ mode: "one",
354
+ level: number,
355
+ exercise: newPrescription(exercise, measure),
356
+ });
357
+ item.levels.sort((a, b) => a.level - b.level);
358
+ }),
359
+ removeLevel: (layout, at) => edit(layout, (l) => {
360
+ const item = itemAt(l, at);
361
+ if (item.kind === "levels")
362
+ item.levels.splice(at.level ?? -1, 1);
363
+ }),
364
+ setLevelNumber: (layout, at, number) => edit(layout, (l) => {
365
+ const item = itemAt(l, at);
366
+ if (item.kind !== "levels")
367
+ return;
368
+ const level = item.levels[at.level ?? -1];
369
+ if (level)
370
+ level.level = number;
371
+ item.levels.sort((a, b) => a.level - b.level);
372
+ }),
373
+ /** One, together or alternatives: a level's exercises kept, its shape changed. */
374
+ setLevelMode: (layout, at, mode) => edit(layout, (l) => {
375
+ const item = itemAt(l, at);
376
+ if (item.kind !== "levels")
377
+ return;
378
+ const index = at.level ?? -1;
379
+ const level = item.levels[index];
380
+ if (!level || level.mode === mode)
381
+ return;
382
+ const exercises = levelExercises(level);
383
+ item.levels[index] =
384
+ mode === "one"
385
+ ? { mode, level: level.level, exercise: exercises[0] }
386
+ : { mode, level: level.level, exercises };
387
+ }),
388
+ /** Another exercise beside the ones at `at` (an "all" item's, or a level's). */
389
+ addExercise: (layout, at, exercise, measure) => edit(layout, (l) => {
390
+ const item = itemAt(l, at);
391
+ const p = newPrescription(exercise, measure);
392
+ if (item.kind === "all") {
393
+ item.exercises.push(p);
394
+ return;
395
+ }
396
+ const index = at.level ?? -1;
397
+ const level = item.levels[index];
398
+ if (!level)
399
+ return;
400
+ item.levels[index] =
401
+ level.mode === "one"
402
+ ? { mode: "together", level: level.level, exercises: [level.exercise, p] }
403
+ : { ...level, exercises: [...level.exercises, p] };
404
+ }),
405
+ removeExercise: (layout, at) => edit(layout, (l) => {
406
+ const item = itemAt(l, at);
407
+ const index = at.exercise ?? -1;
408
+ if (item.kind === "all") {
409
+ item.exercises.splice(index, 1);
410
+ return;
411
+ }
412
+ const li = at.level ?? -1;
413
+ const level = item.levels[li];
414
+ if (!level || level.mode === "one")
415
+ return;
416
+ const rest = level.exercises.filter((_, i) => i !== index);
417
+ item.levels[li] =
418
+ rest.length === 1
419
+ ? { mode: "one", level: level.level, exercise: rest[0] }
420
+ : { ...level, exercises: rest };
421
+ }),
422
+ /** The exercise at `at` replaced by another of the bank, keeping its sets and note. */
423
+ swapExercise: (layout, at, exercise) => edit(layout, (l) => {
424
+ prescriptionAt(l, at).exercise = exercise;
425
+ }),
426
+ setSets: (layout, at, sets) => edit(layout, (l) => {
427
+ prescriptionAt(l, at).sets = sets;
428
+ }),
429
+ /** One more set, like the last. */
430
+ addSet: (layout, at) => edit(layout, (l) => {
431
+ const p = prescriptionAt(l, at);
432
+ const last = p.sets.at(-1);
433
+ p.sets.push(last ? clone(last) : newSet());
434
+ }),
435
+ removeSet: (layout, at) => edit(layout, (l) => {
436
+ prescriptionAt(l, at).sets.splice(at.set ?? -1, 1);
437
+ }),
438
+ /** One set's values: switching its kind keeps what the new kind has (load, rest). */
439
+ setSet: (layout, at, values) => edit(layout, (l) => {
440
+ const p = prescriptionAt(l, at);
441
+ const index = at.set ?? -1;
442
+ const old = p.sets[index];
443
+ if (!old)
444
+ return;
445
+ const kind = values.kind ?? old.kind;
446
+ const merged = { ...old, ...values, kind };
447
+ const keep = {
448
+ reps: ["kind", "reps", "repsMax", "load", "tempo", "rest"],
449
+ time: ["kind", "seconds", "load", "rest"],
450
+ hold: ["kind", "seconds", "holds", "load", "rest"],
451
+ };
452
+ const next = {};
453
+ for (const key of keep[kind]) {
454
+ if (merged[key] !== undefined && merged[key] !== null && merged[key] !== "")
455
+ next[key] = merged[key];
456
+ }
457
+ if (kind === "reps" && next.reps === undefined)
458
+ next.reps = 8;
459
+ if (kind !== "reps" && next.seconds === undefined)
460
+ next.seconds = 30;
461
+ p.sets[index] = next;
462
+ }),
463
+ setPrescriptionNote: (layout, at, note) => edit(layout, (l) => {
464
+ const p = prescriptionAt(l, at);
465
+ if (note.trim())
466
+ p.note = note;
467
+ else
468
+ delete p.note;
469
+ }),
470
+ /** A note on a session, a block or an item (whichever `at` reaches deepest). */
471
+ addNote: (layout, at, text, members = false) => edit(layout, (l) => {
472
+ const target = at.item !== undefined
473
+ ? itemAt(l, at)
474
+ : at.block !== undefined
475
+ ? blockAt(l, at)
476
+ : sessionAt(l, at);
477
+ target.notes = [...(target.notes ?? []), { text, ...(members ? { members: true } : {}) }];
478
+ }),
479
+ setNote: (layout, at, index, note) => edit(layout, (l) => {
480
+ const target = at.item !== undefined
481
+ ? itemAt(l, at)
482
+ : at.block !== undefined
483
+ ? blockAt(l, at)
484
+ : sessionAt(l, at);
485
+ const notes = [...(target.notes ?? [])];
486
+ if (note)
487
+ notes[index] = { text: note.text, ...(note.members ? { members: true } : {}) };
488
+ else
489
+ notes.splice(index, 1);
490
+ if (notes.length)
491
+ target.notes = notes;
492
+ else
493
+ delete target.notes;
494
+ }),
495
+ };
496
+ /** How many sessions, items and exercises a layout has, for the builder's summary. */
497
+ export function layoutSummary(layout) {
498
+ let sessions = 0;
499
+ let items = 0;
500
+ for (const w of layout.weeks) {
501
+ sessions += w.sessions.length;
502
+ for (const s of w.sessions)
503
+ for (const b of s.blocks)
504
+ items += b.items.length;
505
+ }
506
+ return { weeks: layout.weeks.length, sessions, items };
507
+ }
508
+ /** The ids of every exercise a layout names. */
509
+ export function exercisesIn(layout) {
510
+ const ids = new Set();
511
+ for (const w of layout.weeks) {
512
+ for (const s of w.sessions) {
513
+ for (const p of s.warmup?.exercises ?? [])
514
+ ids.add(p.exercise);
515
+ for (const b of s.blocks) {
516
+ for (const i of b.items) {
517
+ const all = i.kind === "all" ? i.exercises : i.levels.flatMap(levelExercises);
518
+ for (const p of all)
519
+ ids.add(p.exercise);
520
+ }
521
+ }
522
+ }
523
+ }
524
+ return [...ids];
525
+ }
526
+ /** How long the builder waits after the last edit before it saves the working copy. */
527
+ export const SAVE_AFTER_MS = 800;
528
+ /**
529
+ * The operations each hook calls (ADR 0453). A member's customer client gets the training hooks
530
+ * (today, a session, logging, history, progress, the class view), the staff client all of them.
531
+ * Who may do what is still the host's: a coach whose grants (ADR 0449) do not cover an operation
532
+ * is refused it there; `usePublishOffered` asks the host what the account holds.
533
+ */
534
+ export const PROGRAMS_HOOKS_CALL = {
535
+ useToday: ["x.programs.today"],
536
+ useSession: ["x.programs.sessionGet"],
537
+ useClassToday: ["x.programs.classToday"],
538
+ useLogSet: ["x.programs.logAdd"],
539
+ useUpdateSet: ["x.programs.logUpdate"],
540
+ useMarkSession: ["x.programs.sessionComplete"],
541
+ useHistory: ["x.programs.history"],
542
+ useProgress: ["x.programs.progress"],
543
+ useClientSessions: ["record.list"],
544
+ usePeople: ["person.list"],
545
+ useClassTypes: ["record.list"],
546
+ useBank: ["record.list"],
547
+ useExercises: ["record.list"],
548
+ useCreateExercise: ["record.create"],
549
+ useUpdateExercise: ["record.update"],
550
+ usePrograms: ["record.list"],
551
+ useCreateProgram: ["record.create"],
552
+ useDraft: ["x.programs.draft"],
553
+ useImportText: ["x.programs.importText"],
554
+ useAssign: ["x.programs.assign"],
555
+ useVersions: ["record.versions"],
556
+ usePublishOffered: ["user.me"],
557
+ usePublish: ["record.publish"],
558
+ useRestoreVersion: ["record.restoreVersion"],
559
+ useWorkingCopy: ["record.get", "record.update"],
560
+ };
561
+ /**
562
+ * Hooks for a React or React Native app:
563
+ * `const programs = createProgramsHooks({ useQuery, useMutation, useState, useEffect }, api)`.
564
+ * `api` is any generated client; the hooks it cannot back are not there, and calling one does
565
+ * not compile.
566
+ */
567
+ export function createProgramsHooks(react, client) {
568
+ return packHooks(client, PROGRAMS_HOOKS_CALL, (api) => allProgramsHooks(react, api));
569
+ }
570
+ function allProgramsHooks(react, api) {
571
+ const { useQuery, useMutation, useState } = react;
572
+ const useEffect = react.useEffect ?? (() => undefined);
573
+ return {
574
+ // A member's (or, for staff, a named client's) training.
575
+ useToday(input = {}) {
576
+ return useQuery(api.query("x.programs.today", input));
577
+ },
578
+ useSession(input) {
579
+ return useQuery(api.query("x.programs.sessionGet", input));
580
+ },
581
+ useClassToday(input) {
582
+ return useQuery(api.query("x.programs.classToday", input));
583
+ },
584
+ useLogSet() {
585
+ return useMutation(api.mutation("x.programs.logAdd"));
586
+ },
587
+ useUpdateSet() {
588
+ return useMutation(api.mutation("x.programs.logUpdate"));
589
+ },
590
+ useMarkSession() {
591
+ return useMutation(api.mutation("x.programs.sessionComplete"));
592
+ },
593
+ useHistory(input) {
594
+ return useQuery(api.query("x.programs.history", input));
595
+ },
596
+ useProgress(input = {}) {
597
+ return useQuery(api.query("x.programs.progress", input));
598
+ },
599
+ /** A client's sessions, newest first (staff): the coach's client view. */
600
+ useClientSessions(personId) {
601
+ return useQuery(api.query("record.list", {
602
+ object: SESSION,
603
+ filter: { field: "person", op: "eq", value: personId },
604
+ sort: { field: "date", direction: "desc" },
605
+ limit: 100,
606
+ }));
607
+ },
608
+ /** People whose name contains `search` (staff): whom to assign a program to. */
609
+ usePeople(search) {
610
+ return useQuery({
611
+ ...api.query("person.list", {
612
+ filter: { field: "displayName", op: "contains", value: search.trim() },
613
+ limit: 20,
614
+ }),
615
+ enabled: search.trim().length > 1,
616
+ });
617
+ },
618
+ /** The class types, for a member choosing their class. */
619
+ useClassTypes() {
620
+ return useQuery(api.query("record.list", {
621
+ object: "programs.classtype",
622
+ sort: { field: "order", direction: "asc" },
623
+ }));
624
+ },
625
+ // The bank.
626
+ useBank(search) {
627
+ return useQuery(api.query("record.list", {
628
+ object: EXERCISE,
629
+ ...(search?.trim()
630
+ ? { filter: { field: "name", op: "contains", value: search.trim() } }
631
+ : {}),
632
+ sort: { field: "name", direction: "asc" },
633
+ limit: 200,
634
+ }));
635
+ },
636
+ /** The bank's exercises with these ids (a program's own, whatever the size of the bank). */
637
+ useExercises(ids) {
638
+ const sorted = [...new Set(ids)].sort();
639
+ return useQuery({
640
+ ...api.query("record.list", {
641
+ object: EXERCISE,
642
+ filter: { field: "id", op: "in", value: sorted },
643
+ limit: 200,
644
+ }),
645
+ enabled: sorted.length > 0,
646
+ });
647
+ },
648
+ useCreateExercise() {
649
+ return useMutation(api.mutation("record.create"));
650
+ },
651
+ useUpdateExercise() {
652
+ return useMutation(api.mutation("record.update"));
653
+ },
654
+ // Programs.
655
+ usePrograms() {
656
+ return useQuery(api.query("record.list", {
657
+ object: PROGRAM,
658
+ sort: { field: "updatedAt", direction: "desc" },
659
+ limit: 100,
660
+ }));
661
+ },
662
+ useCreateProgram() {
663
+ return useMutation(api.mutation("record.create"));
664
+ },
665
+ useDraft() {
666
+ return useMutation(api.mutation("x.programs.draft"));
667
+ },
668
+ useImportText() {
669
+ return useMutation(api.mutation("x.programs.importText"));
670
+ },
671
+ useAssign() {
672
+ return useMutation(api.mutation("x.programs.assign"));
673
+ },
674
+ useVersions(programId) {
675
+ return useQuery(api.query("record.versions", { object: PROGRAM, id: programId }));
676
+ },
677
+ /**
678
+ * Whether to offer publishing: what `user.me` says the account holds. Only an offer: the host
679
+ * decides when it is asked (`records:publish`; an AI actor's request waits for a person who
680
+ * holds it, ADR 0480).
681
+ */
682
+ usePublishOffered() {
683
+ const me = useQuery(api.query("user.me", {}));
684
+ return Boolean(me.data?.permissions.some((p) => p === "records:publish"));
685
+ },
686
+ usePublish() {
687
+ return useMutation(api.mutation("record.publish"));
688
+ },
689
+ useRestoreVersion() {
690
+ return useMutation(api.mutation("record.restoreVersion"));
691
+ },
692
+ /**
693
+ * The builder's working copy of one program: the layout as the coach edits it, saved to the
694
+ * host `SAVE_AFTER_MS` after the last edit (and on `saveNow`). Faults the host reports come
695
+ * back by path (`faults`); the edit stays on screen so the coach fixes it where it is.
696
+ */
697
+ useWorkingCopy(programId) {
698
+ const program = useQuery(api.query("record.get", { object: PROGRAM, id: programId }));
699
+ const save = useMutation(api.mutation("record.update"));
700
+ const [draft, setDraft] = useState(null);
701
+ const [state, setState] = useState("saved");
702
+ const [faults, setFaults] = useState(new Map());
703
+ const [message, setMessage] = useState(null);
704
+ const [pending, setPending] = useState(0);
705
+ const loaded = program.data
706
+ ? {
707
+ layout: program.data.values.layout ?? emptyLayout(),
708
+ title: String(program.data.values.title ?? ""),
709
+ guidance: String(program.data.values.guidance ?? ""),
710
+ }
711
+ : null;
712
+ const current = draft ?? loaded;
713
+ const store = async (value) => {
714
+ setState("saving");
715
+ try {
716
+ await save.mutateAsync({
717
+ object: PROGRAM,
718
+ id: programId,
719
+ values: { layout: value.layout, title: value.title, guidance: value.guidance || null },
720
+ });
721
+ setFaults(new Map());
722
+ setMessage(null);
723
+ setState("saved");
724
+ }
725
+ catch (error) {
726
+ setFaults(faultsOf(error));
727
+ setMessage(error.message ?? "The host refused this change");
728
+ setState("refused");
729
+ }
730
+ };
731
+ useEffect(() => {
732
+ if (!draft || pending === 0)
733
+ return undefined;
734
+ const timer = setTimeout(() => void store(draft), SAVE_AFTER_MS);
735
+ return () => clearTimeout(timer);
736
+ }, [pending]);
737
+ return {
738
+ program: program.data,
739
+ isPending: program.isPending,
740
+ error: program.error,
741
+ layout: current?.layout ?? null,
742
+ title: current?.title ?? "",
743
+ guidance: current?.guidance ?? "",
744
+ state,
745
+ faults,
746
+ message,
747
+ /** Applies an edit (one of `layoutEdits`) and saves it shortly after. */
748
+ change(next) {
749
+ if (!current)
750
+ return;
751
+ setDraft({ ...current, layout: next });
752
+ setState("unsaved");
753
+ setPending((n) => n + 1);
754
+ },
755
+ rename(title, guidance) {
756
+ if (!current)
757
+ return;
758
+ setDraft({ ...current, title, guidance: guidance ?? current.guidance });
759
+ setState("unsaved");
760
+ setPending((n) => n + 1);
761
+ },
762
+ async saveNow() {
763
+ if (current)
764
+ await store(current);
765
+ },
766
+ /** The working copy as a version had it (after restoring one). */
767
+ reset(layout, title) {
768
+ setDraft({
769
+ layout,
770
+ title: title ?? current?.title ?? "",
771
+ guidance: current?.guidance ?? "",
772
+ });
773
+ setState("saved");
774
+ setFaults(new Map());
775
+ },
776
+ };
777
+ },
778
+ };
779
+ }