@blueshed/joined 0.1.20 → 0.2.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 (84) hide show
  1. package/.claude/skills/joined/SKILL.md +1 -1
  2. package/.claude/skills/joined/reference.md +99 -18
  3. package/README.md +6 -4
  4. package/docs/design.md +31 -8
  5. package/docs/introduction.md +1 -1
  6. package/docs/learning.md +1 -1
  7. package/docs/light-and-shadow.svg +119 -0
  8. package/docs/links-and-trust.svg +93 -0
  9. package/docs/logo.svg +47 -0
  10. package/docs/stories-to-code.svg +86 -0
  11. package/docs/wire-op.svg +99 -0
  12. package/examples/cafe/kitchen.ts +2 -2
  13. package/examples/desk/card.ts +43 -0
  14. package/examples/desk/desk.css +17 -0
  15. package/examples/desk/desk.json +41 -0
  16. package/examples/desk/generated/elements.ts +69 -0
  17. package/examples/desk/generated/queries.ts +33 -0
  18. package/examples/desk/generated/rules.ts +94 -0
  19. package/examples/desk/index.html +34 -0
  20. package/examples/desk/lanes.css +126 -0
  21. package/examples/desk/lanes.ts +133 -0
  22. package/examples/desk/migrations/001-desk.ts +8 -0
  23. package/examples/desk/page.ts +29 -0
  24. package/examples/desk/pulse.ts +20 -0
  25. package/examples/desk/routes.ts +9 -0
  26. package/examples/desk/steps.ts +32 -0
  27. package/examples/desk/stories.jsonl +18 -0
  28. package/examples/desk/tally.css +62 -0
  29. package/examples/desk/tally.ts +76 -0
  30. package/examples/desk/thumbs.ts +45 -0
  31. package/examples/desk/trust.ts +24 -0
  32. package/examples/desk/words.ts +17 -0
  33. package/examples/trip/bar.ts +1 -1
  34. package/examples/trip/calendar-map.css +2 -0
  35. package/examples/trip/drags.ts +3 -3
  36. package/examples/trip/drawer.ts +5 -5
  37. package/examples/trip/event-form.ts +8 -7
  38. package/examples/trip/holding.ts +1 -1
  39. package/examples/trip/ics.ts +22 -112
  40. package/examples/trip/line-stops.ts +1 -1
  41. package/examples/trip/line-words.ts +1 -1
  42. package/examples/trip/line.ts +1 -1
  43. package/examples/trip/map.ts +1 -1
  44. package/examples/trip/month.ts +1 -1
  45. package/examples/trip/other-weeks.ts +1 -1
  46. package/examples/trip/page.ts +2 -2
  47. package/examples/trip/peek.ts +1 -1
  48. package/examples/trip/routes.ts +3 -3
  49. package/examples/trip/shell.ts +3 -3
  50. package/examples/trip/stays.ts +1 -1
  51. package/examples/trip/week.ts +1 -1
  52. package/examples/trip/writes.ts +1 -1
  53. package/examples/trips/card.ts +1 -1
  54. package/examples/trips/map.ts +1 -1
  55. package/examples/weeks/derive.ts +1 -1
  56. package/package.json +9 -2
  57. package/src/attachment.ts +18 -11
  58. package/src/client.ts +7 -0
  59. package/src/demo.css +29 -26
  60. package/src/demo.ts +2 -2
  61. package/src/draft.ts +23 -8
  62. package/src/files.ts +25 -9
  63. package/{examples/trip/mercator.ts → src/geo.ts} +13 -3
  64. package/src/icon-names.ts +4 -0
  65. package/src/ics.ts +130 -0
  66. package/src/members/group.ts +3 -1
  67. package/src/members/panel.css +208 -201
  68. package/src/members/panel.ts +17 -8
  69. package/src/ops.ts +5 -0
  70. package/src/outbox.ts +70 -0
  71. package/src/page.css +76 -70
  72. package/src/page.ts +86 -15
  73. package/src/parts.css +575 -428
  74. package/src/parts.ts +18 -5
  75. package/{examples/trip → src}/place-search.ts +5 -5
  76. package/{examples/trip → src}/places.ts +9 -7
  77. package/src/rank.ts +20 -0
  78. package/src/scrim.ts +81 -0
  79. package/src/server.ts +59 -13
  80. package/{examples/trip → src}/time.ts +37 -5
  81. package/src/together.ts +2 -6
  82. package/src/tokens.css +5 -0
  83. package/src/tokens.json +35 -0
  84. package/src/write.ts +29 -14
package/src/parts.ts CHANGED
@@ -1,16 +1,29 @@
1
- // joined's parts (src/parts.css), one sheet: the page adopts it as this is first imported, and a
2
- // display adopts it in its shadow, before its own. A display or the group imports this; a page holding the group
3
- // needn't, unless it wants a part's behaviour (the page's line said, a modal that asks first, a button showing it's
4
- // open), and a page without one (anonymous: hello) imports it for the look.
1
+ // joined's parts (src/parts.css), one sheet, a layer (joined) beneath anything of an app's own, so any rule of an
2
+ // app's wins, whatever its specificity: the page adopts it as this is first imported, and a display adopts it in its
3
+ // shadow by adopt(), before its own. A display or the group imports this; a page holding the group needn't, unless
4
+ // it wants a part's behaviour (the page's line said, a modal that asks first, a button showing it's open), and a page
5
+ // without one (anonymous: hello) imports it for the look. The page's surfaces, and each adopted shadow's, dim the
6
+ // page by its one scrim (./scrim.ts).
5
7
 
6
8
  import STYLE from "./parts.css" with { type: "text" };
7
9
  import { hueOf } from "./hues.ts";
8
10
  import { keep } from "./keep.ts";
9
11
  import type { Answer } from "./page.ts";
12
+ import { watch } from "./scrim.ts";
10
13
 
11
14
  export const PARTS = new CSSStyleSheet();
12
15
  PARTS.replaceSync(STYLE);
13
- document.adoptedStyleSheets = [...document.adoptedStyleSheets, PARTS];
16
+ /** Where the scrim watches, a modal's and a sheet's own ::backdrop let go: the scrim dims for them. */
17
+ const WATCHED = new CSSStyleSheet();
18
+ WATCHED.replaceSync(`@layer joined { :is(dialog, .sheet)::backdrop { background: transparent; } }`);
19
+ document.adoptedStyleSheets = [...document.adoptedStyleSheets, PARTS, WATCHED];
20
+
21
+ /** A display's shadow given joined's parts, then its own sheets (which win, joined's being a layer beneath), its
22
+ * modals, sheets and drawers dimming the page by its one scrim as the page's do. */
23
+ export function adopt(root: ShadowRoot, ...sheets: CSSStyleSheet[]) {
24
+ root.adoptedStyleSheets = [PARTS, WATCHED, ...sheets];
25
+ watch(root);
26
+ }
14
27
 
15
28
  /** A person's face (Identity): their initial in their hue, their name its title; or, where there's no room (an
16
29
  * event's block), their dot. */
@@ -1,8 +1,8 @@
1
- // The place search in an event's form: what's typed as its place, asked of Photon (./places.ts) near the map's
2
- // middle a moment after the typing stops, and the places found offered beneath it to pick from. An answer to a
3
- // search typed past since is let go, so what's offered is always what's typed.
1
+ // A place search in a form (joined/place-search): what's typed as its place, asked of Photon (./places.ts) near a
2
+ // point (the map's middle, a board's pins) a moment after the typing stops, and the places found offered beneath it
3
+ // to pick from. An answer to a search typed past since is let go, so what's offered is always what's typed.
4
4
 
5
- import { keep } from "joined/keep";
5
+ import { keep } from "./keep.ts";
6
6
  import { find, type Place } from "./places.ts";
7
7
 
8
8
  export class PlaceSearch {
@@ -16,7 +16,7 @@ export class PlaceSearch {
16
16
  ) {}
17
17
 
18
18
  /** Places called `q`, near the point `near` gives, offered to pick from; under three letters, none. */
19
- search(q: string, near: () => { lat: number; lng: number }) {
19
+ search(q: string, near: () => { lat: number; lng: number } | undefined) {
20
20
  const asked = ++this.#asked;
21
21
  if (q.length < 3) return this.found([]);
22
22
  const at = near();
@@ -1,6 +1,8 @@
1
- // Places by name, and the name of a point: Photon, komoot's search over OpenStreetMap, open to all and
2
- // asked from the page, as the map's tiles are. Nothing found, or Photon away, is no place: the form
3
- // keeps what it had.
1
+ // Places by name, and the name of a point (joined/places): Photon, komoot's search over OpenStreetMap, open to all
2
+ // and asked from the page, as the map's tiles are. Only what's typed, or the point, is sent. Nothing found, or
3
+ // Photon away, is no place: the form keeps what it had.
4
+
5
+ import { geoOf } from "./geo.ts";
4
6
 
5
7
  const PHOTON = "https://photon.komoot.io";
6
8
  export type Place = { name: string; coordinates: string };
@@ -13,7 +15,7 @@ type Feature = {
13
15
  const placeOf = ({ geometry, properties: p }: Feature): Place => {
14
16
  const [lng, lat] = geometry.coordinates;
15
17
  const name = [...new Set([p.name ?? p.street, p.district, p.city ?? p.county ?? p.state])].filter(Boolean).join(", ");
16
- return { name, coordinates: `geo:${lat.toFixed(4)},${lng.toFixed(4)}` };
18
+ return { name, coordinates: geoOf({ lat, lng }) };
17
19
  };
18
20
  const ask = async (path: string): Promise<Place[]> => {
19
21
  try {
@@ -26,9 +28,9 @@ const ask = async (path: string): Promise<Place[]> => {
26
28
  }
27
29
  };
28
30
 
29
- /** Places called this, those near a point first. */
30
- export const find = (q: string, near: { lat: number; lng: number }) =>
31
- ask(`/api/?q=${encodeURIComponent(q)}&limit=5&lang=en&lat=${near.lat}&lon=${near.lng}`);
31
+ /** Places called this, those near a point first (none: anywhere). */
32
+ export const find = (q: string, near?: { lat: number; lng: number }) =>
33
+ ask(`/api/?q=${encodeURIComponent(q)}&limit=5&lang=en${near ? `&lat=${near.lat}&lon=${near.lng}` : ""}`);
32
34
  /** The name of the place at a point, or none. */
33
35
  export const nameOf = async ({ lat, lng }: { lat: number; lng: number }) =>
34
36
  (await ask(`/reverse?lat=${lat}&lon=${lng}&lang=en`))[0]?.name ?? null;
package/src/rank.ts ADDED
@@ -0,0 +1,20 @@
1
+ // Where an item let go lands among others (joined/rank), as a rank between theirs: halfway between the one above and
2
+ // the one below, one less than the first, one more than the last. One write moves it, and none of the others: a list
3
+ // held in a number's order (`{"order":{"tasks":"rank"}}`) puts it in its place on every page. The desk's lanes,
4
+ // cardlet's columns and idea-cards' stacks are this.
5
+
6
+ /** The rank between `before` and `after` (either none, at an end); none at all: 1. */
7
+ export const between = (before?: number, after?: number) =>
8
+ before === undefined ? (after ?? 2) - 1 : after === undefined ? before + 1 : (before + after) / 2;
9
+
10
+ /** Where among `rows` (the others in the list, in their order, each with its rank in `ranks`) a thing let go at `y`
11
+ * lands: its place among them, and its rank there. */
12
+ export function landing(
13
+ rows: Pick<HTMLElement, "getBoundingClientRect" | "offsetHeight">[],
14
+ ranks: number[],
15
+ y: number,
16
+ ) {
17
+ const i = rows.findIndex((r) => y < r.getBoundingClientRect().top + r.offsetHeight / 2),
18
+ at = i < 0 ? rows.length : i;
19
+ return { at, rank: between(ranks[at - 1], ranks[at]) };
20
+ }
package/src/scrim.ts ADDED
@@ -0,0 +1,81 @@
1
+ // The scrim: one, on the page (.j-scrim, src/parts.css), behind what's open: a modal, anywhere; on a phone, a drawer
2
+ // or a sheet too, which there are a phone's sheets risen from the foot. It fades in and out with them in every browser,
3
+ // where a ::backdrop doesn't in Safari; a modal's own ::backdrop and a sheet's are let go wherever this watches. While a
4
+ // modal asks over a drawer, the scrim is over the drawer too. A tap on it closes the drawer on top, as its × does
5
+ // (its control named close); so does Escape, wherever you are, but where a modal or a sheet is open (Escape is theirs)
6
+ // or something before it took Escape for its own (preventDefault: a list of places found, closing).
7
+ //
8
+ // It watches the page, and each shadow a display gives joined's parts by adopt() (src/parts.ts): which of its
9
+ // surfaces are open, as they open and close (a drawer's hidden, a modal's open, a sheet's toggle), never searching
10
+ // the page for them again.
11
+
12
+ const phone = matchMedia("(max-width: 40rem)");
13
+ /** The surfaces open, in the order they opened: the last is on top. */
14
+ const open = new Set<HTMLElement>();
15
+ const watched = new WeakSet<Document | ShadowRoot>();
16
+ let scrim: HTMLElement | undefined;
17
+
18
+ /** Whether a surface is open: a drawer shown, a modal shown modal, a sheet's popover open. */
19
+ const isOpen = (el: HTMLElement) =>
20
+ el.isConnected &&
21
+ (el instanceof HTMLDialogElement
22
+ ? el.open && el.matches(":modal")
23
+ : el.classList.contains("drawer")
24
+ ? !el.hidden
25
+ : el.matches(":popover-open"));
26
+
27
+ /** A surface, as it is now: open (on top), or not. */
28
+ function note(el: Element) {
29
+ if (!(el instanceof HTMLElement) || !el.matches("dialog, .drawer, .sheet")) return;
30
+ open.delete(el);
31
+ if (isOpen(el)) open.add(el);
32
+ }
33
+
34
+ const drawers = () => [...open].filter((el) => el.isConnected && el.classList.contains("drawer") && !el.hidden);
35
+ const asking = () => [...open].some((el) => el instanceof HTMLDialogElement && isOpen(el));
36
+ const sheet = () => [...open].some((el) => el.classList.contains("sheet") && isOpen(el));
37
+
38
+ /** The scrim as what's open says: on behind a modal, and on a phone behind a drawer or a sheet. */
39
+ function dim() {
40
+ for (const el of open) if (!isOpen(el)) open.delete(el);
41
+ const on = asking() || (phone.matches && (drawers().length > 0 || sheet()));
42
+ if (!scrim && !on) return;
43
+ scrim ??= made();
44
+ scrim.classList.toggle("j-on", on);
45
+ scrim.classList.toggle("j-asking", asking());
46
+ }
47
+
48
+ /** The drawer on top closed, by its own ×, so it closes as it would. */
49
+ const closeTop = () => drawers().at(-1)?.querySelector<HTMLButtonElement>("[name=close]")?.click();
50
+
51
+ function made() {
52
+ const el = Object.assign(document.createElement("div"), { className: "j-scrim" });
53
+ el.ariaHidden = "true";
54
+ // a tap on it closes the drawer on top; unless it was the tap that took a sheet away (the popover closes itself)
55
+ let wasSheet = false;
56
+ el.addEventListener("pointerdown", () => (wasSheet = sheet()));
57
+ el.addEventListener("click", () => !wasSheet && closeTop());
58
+ document.body.append(el);
59
+ return el;
60
+ }
61
+
62
+ /** Watch a root's surfaces: the page, or a display's shadow. */
63
+ export function watch(root: Document | ShadowRoot) {
64
+ if (watched.has(root)) return;
65
+ watched.add(root);
66
+ for (const el of root.querySelectorAll("dialog, .drawer, .sheet")) note(el);
67
+ new MutationObserver((changes) => {
68
+ for (const c of changes) note(c.target as Element);
69
+ dim();
70
+ }).observe(root, { subtree: true, attributes: true, attributeFilter: ["hidden", "open"] });
71
+ // a popover says it's opened or closed by toggle, which doesn't bubble: heard as it passes, on its way down
72
+ root.addEventListener("toggle", (e) => (note(e.target as Element), dim()), true);
73
+ dim();
74
+ }
75
+
76
+ phone.addEventListener("change", dim);
77
+ document.addEventListener("keydown", (e) => {
78
+ if (e.key !== "Escape" || e.defaultPrevented || asking() || sheet()) return;
79
+ closeTop();
80
+ });
81
+ watch(document);
package/src/server.ts CHANGED
@@ -52,6 +52,8 @@ type Message = {
52
52
  ops?: Op[];
53
53
  why?: string;
54
54
  writes?: Part[];
55
+ /** A change of the document to undo, by its version: the page's own. */
56
+ undo?: number;
55
57
  } & Asked;
56
58
 
57
59
  /** A page's message, read; or why it isn't one joined reads. */
@@ -63,7 +65,7 @@ export function messageOf(text: string): Message | string {
63
65
  return "that isn't JSON";
64
66
  }
65
67
  if (typeof m !== "object" || m === null || Array.isArray(m)) return "a message is a JSON object";
66
- const { id, subscribe, since, unsubscribe, doc, ops, why, writes } = m as Record<string, unknown>;
68
+ const { id, subscribe, since, unsubscribe, doc, ops, why, writes, undo } = m as Record<string, unknown>;
67
69
  const op = (o: any) =>
68
70
  typeof o === "object" && o !== null && ["add", "replace", "remove"].includes(o.op) && typeof o.path === "string";
69
71
  const part = (w: any) =>
@@ -82,6 +84,8 @@ export function messageOf(text: string): Message | string {
82
84
  if ([subscribe, unsubscribe, doc, why].some((s) => s !== undefined && typeof s !== "string"))
83
85
  return "subscribe, unsubscribe, doc and why are strings";
84
86
  if (since !== undefined && !Number.isInteger(since)) return "since is a version";
87
+ if (undo !== undefined && !(Number.isInteger(undo) && typeof doc === "string"))
88
+ return "an undo is a document's version";
85
89
  if (ops !== undefined && !(Array.isArray(ops) && ops.every(op)))
86
90
  return "ops are each an add, a replace or a remove, at a path";
87
91
  return m as Message;
@@ -402,7 +406,7 @@ export async function start({
402
406
  if (docParts(doc).name === GROUP) throw new Refused("the group's changes aren't undone");
403
407
  const ops = store.undoing(doc, version);
404
408
  // held to the stories as any write is
405
- const why = ungranted(doc, ops, null);
409
+ const why = ungranted(doc, ops, null, true, true);
406
410
  if (why) throw new Refused(why);
407
411
  const landed = land([{ doc, ops }], by, null, { undoes: version, held: pagesHold() });
408
412
  tell(landed);
@@ -659,6 +663,37 @@ export async function start({
659
663
  if (ws.data.docs.delete(m.unsubscribe) && !derives.has(m.unsubscribe)) ws.unsubscribe(topicOf(ws, m.unsubscribe));
660
664
  return void forget(ws, m.unsubscribe);
661
665
  }
666
+ // a page undoes a change of a document it holds, its own (who made it, or nobody where there are no members): its
667
+ // inverse, guarded, as the server's undo is; answered done with the version the undo made, which the page may undo
668
+ // in turn (a redo)
669
+ if (m.undo !== undefined) {
670
+ const doc = m.doc!,
671
+ base = docParts(doc).base,
672
+ by = who?.member ?? null;
673
+ const made = store.change(base, m.undo);
674
+ // nobody's change (a stranger's, the server's own, a rule's, a reaction's) is undone only by the page that made it
675
+ const no = !ws.data.docs.has(doc)
676
+ ? `this page isn't subscribed to ${base}`
677
+ : made && (made.by !== by || (by === null && !ws.data.made?.has(`${base} ${m.undo}`)))
678
+ ? "a change is undone by whoever made it"
679
+ : docParts(base).name === GROUP
680
+ ? "the group's changes aren't undone"
681
+ : null;
682
+ // held as the page's own write is: who they are now (read-only, a role gone, a guest's level), the app's
683
+ // rules, and its settings (frozen); then guarded as the server's undo is
684
+ let w: Written;
685
+ try {
686
+ if (no) throw new Refused(no);
687
+ w = await written([{ doc, ops: store.undoing(base, m.undo) }], who, m.undo);
688
+ } catch (e) {
689
+ if (!(e instanceof Refused)) throw e;
690
+ log?.(`undo ${base} ${m.undo} by ${byOf(who)}: refused, ${e.message}`);
691
+ return say(ws, { refused: m.id, why: e.message });
692
+ }
693
+ if ("why" in w) return say(ws, { refused: m.id, why: w.why });
694
+ if (by === null) (ws.data.made ??= new Set()).add(`${base} ${w.version}`);
695
+ return say(ws, { done: m.id, version: w.version });
696
+ }
662
697
  if (!m.ops && !m.writes) {
663
698
  return say(ws, await group.asked(ws, m as Message & { id: number }));
664
699
  }
@@ -676,6 +711,9 @@ export async function start({
676
711
  writes.map((w) => ({ ...w, why: w.why?.trim() || undefined })),
677
712
  who,
678
713
  );
714
+ // a stranger's change, which only this page undoes
715
+ if (!("why" in w) && who === null)
716
+ (ws.data.made ??= new Set()).add(`${docParts(writes[0]!.doc).base} ${w.version}`);
679
717
  say(
680
718
  ws,
681
719
  "why" in w
@@ -690,10 +728,11 @@ export async function start({
690
728
  /** A write, a page's or an agent's at the MCP door: of one document or several (src/together.ts), each as it names
691
729
  * it (a window's write is its document's), by who, landed whole or not at all, told, and answered: done, with the
692
730
  * version its first part made and the id each item added was given, in order, so the writer needn't match them; or
693
- * refused, why. Each logs one line. */
694
- async function written(writes: Part[], who: Who | null): Promise<Written> {
731
+ * refused, why. Each logs one line. `undoes`: a page's undo, of the version it puts back (src/write.ts, ask). */
732
+ async function written(writes: Part[], who: Who | null, undoes?: number): Promise<Written> {
695
733
  const doc = writes.map((w) => docParts(w.doc).base).join(" and "),
696
- by = byOf(who);
734
+ by = byOf(who),
735
+ act = undoes === undefined ? "write" : `undo ${undoes}`;
697
736
  // In the write's transaction, in order, refused at the first that says no: the app's own rules, the grants, and
698
737
  // the group's rules (src/write.ts), and, as its rows are written, the tables' constraints; each part's.
699
738
  const afters: ((applied: Op[]) => Promise<void>)[] = [];
@@ -703,23 +742,30 @@ export async function start({
703
742
  const no = mayHold(name, who?.member ?? null, !(members && rootToken));
704
743
  if (no) throw new Refused(no);
705
744
  let after: (applied: Op[]) => Promise<void> = async () => {};
706
- const asking = ask(name, ops, why, who, (doc, ops) => {
707
- const write = group.write(doc, ops, who, why);
708
- if (!("refused" in write)) after = write.after;
709
- return write;
710
- });
745
+ const asking = ask(
746
+ name,
747
+ ops,
748
+ why,
749
+ who,
750
+ (doc, ops) => {
751
+ const write = group.write(doc, ops, who, why);
752
+ if (!("refused" in write)) after = write.after;
753
+ return write;
754
+ },
755
+ undoes !== undefined,
756
+ );
711
757
  afters.push(after);
712
758
  return asking;
713
759
  };
714
760
  // a write lands whole or not at all, with what follows from it, in the store's one transaction; then it's told
715
761
  let landed: ReturnType<typeof land>;
716
762
  try {
717
- landed = land(writes, who?.member ?? null, who?.agent?.label ?? null, { asked, held: pagesHold() });
763
+ landed = land(writes, who?.member ?? null, who?.agent?.label ?? null, { undoes, asked, held: pagesHold() });
718
764
  } catch (e) {
719
765
  // refused in words; anything else is the server's, logged, and the writer told it wasn't saved
720
766
  if (!(e instanceof Refused)) console.error(`a write to ${doc} failed:`, e);
721
767
  const why = e instanceof Refused ? e.message : "That wasn't saved: the server had a problem with it.";
722
- log?.(`write ${doc} by ${by}: refused, ${why}`);
768
+ log?.(`${act} ${doc} by ${by}: refused, ${why}`);
723
769
  return { why };
724
770
  }
725
771
  tell(landed);
@@ -728,7 +774,7 @@ export async function start({
728
774
  // what follows each part (the group's pages told, a new member's link made), and then the writer's answer:
729
775
  // done is all of it done
730
776
  for (const [i, after] of afters.entries()) await after(landed.parts[i]!.ops);
731
- log?.(`write ${doc} by ${by}: done, version ${change.version}`);
777
+ log?.(`${act} ${doc} by ${by}: done, version ${change.version}`);
732
778
  const ids = landed.applied
733
779
  .filter((o) => o.op === "add" && parts(o.path).key === "-" && parts(o.path).field === undefined)
734
780
  .map((o) => o.value.id as number);
@@ -1,5 +1,6 @@
1
- // The trip's time: a start is a wall clock (floating time, kept as if UTC), a length an ISO 8601 duration
2
- // (PT1H30M), a day a count from 1 January 1970.
1
+ // Time on the page (joined/time): a start is a wall clock (floating time, kept as if UTC), a length an ISO 8601
2
+ // duration (PT1H30M), a day a count from 1 January 1970. Pure: the trip's calendar is drawn by it, and an app's
3
+ // timeline, a stay's nights or a day's heading take it as they are, rather than a copy each.
3
4
 
4
5
  export const DAY = 86_400_000,
5
6
  MIN = 60_000,
@@ -25,11 +26,41 @@ export const stayed = (s: { from: string; until: string }) => {
25
26
  /** An event's hours, from its start for its length: 09:00–10:30. */
26
27
  export const hours = (start: string, duration: string) =>
27
28
  `${hhmm(wall(start))}–${hhmm(wall(start) + seconds(duration) * 1000)}`;
29
+ /** A length's seconds: days, hours, minutes and seconds (P1DT2H, PT90M, PT30S); one that can't be read, none. */
28
30
  export const seconds = (d: string) => {
29
- const [days = 0, h = 0, m = 0] = (/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?)?$/.exec(d) ?? [])
31
+ const [days = 0, h = 0, m = 0, s = 0] = (/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/.exec(d) ?? [])
30
32
  .slice(1)
31
33
  .map((n) => Number(n ?? 0));
32
- return ((days * 24 + h) * 60 + m) * 60;
34
+ return ((days * 24 + h) * 60 + m) * 60 + s;
35
+ };
36
+ /** The wall clock a start's length ends at. */
37
+ export const ends = (start: string, duration: string) => local(wall(start) + seconds(duration) * 1000);
38
+ /** A length as people say it: PT2H30M is 2h 30m, P1DT3H 1d 3h; none, or one that can't be read, nothing. */
39
+ export const lasts = (d: string | undefined) => {
40
+ const n = Math.round(seconds(d ?? "") / 60);
41
+ return [
42
+ Math.floor(n / 1440) && `${Math.floor(n / 1440)}d`,
43
+ Math.floor(n / 60) % 24 && `${Math.floor(n / 60) % 24}h`,
44
+ n % 60 && `${n % 60}m`,
45
+ ]
46
+ .filter(Boolean)
47
+ .join(" ");
48
+ };
49
+ /** What people say a length is, as a duration: 2h 30m, 90m, 1.5h, 1d 3h, 2 (hours), or a duration as it is (pt2h is
50
+ * PT2H); what can't be read, or no length at all, none. */
51
+ export const lengthOf = (words: string) => {
52
+ const w = words.trim().toLowerCase();
53
+ if (/^p/.test(w)) return seconds(w.toUpperCase()) ? w.toUpperCase() : null;
54
+ const hours = /^(\d+(?:\.\d+)?)\s*h?$/.exec(w),
55
+ parts = /^(?:(\d+)\s*d)?\s*(?:(\d+)\s*h)?\s*(?:(\d+)\s*m)?$/.exec(w);
56
+ const mins = hours
57
+ ? Math.round(Number(hours[1]) * 60)
58
+ : parts?.slice(1).some(Boolean)
59
+ ? (Number(parts[1] ?? 0) * 24 + Number(parts[2] ?? 0)) * 60 + Number(parts[3] ?? 0)
60
+ : null;
61
+ if (!mins) return null;
62
+ const d = Math.floor(mins / 1440);
63
+ return `P${d ? `${d}D` : ""}${mins % 1440 ? iso(mins % 1440).slice(1) : ""}`;
33
64
  };
34
65
  /** The first of a day's month, and the Monday a month's grid starts on (its six weeks hold the whole month). */
35
66
  export const firstOf = (day: number) => {
@@ -42,5 +73,6 @@ export const on = (e: { start: string; duration: string }, day: number) => {
42
73
  const from = wall(e.start);
43
74
  return Math.floor(from / DAY) <= day && day * DAY < from + Math.max(1, seconds(e.duration)) * 1000;
44
75
  };
76
+ /** Minutes as a length: PT1H30M; none at all, PT0M (a moment, which a calendar reads). */
45
77
  export const iso = (mins: number) =>
46
- `PT${Math.floor(mins / 60) ? `${Math.floor(mins / 60)}H` : ""}${mins % 60 ? `${mins % 60}M` : ""}`;
78
+ `PT${Math.floor(mins / 60) ? `${Math.floor(mins / 60)}H` : ""}${mins % 60 || !mins ? `${mins % 60}M` : ""}`;
package/src/together.ts CHANGED
@@ -11,7 +11,7 @@
11
11
 
12
12
  import type { Story } from "./compile.ts";
13
13
  import { Refused } from "./engine.ts";
14
- import { docParts, parts, type Op } from "./ops.ts";
14
+ import { docParts, madeBy, NTH, parts, type Op } from "./ops.ts";
15
15
 
16
16
  /** One document's part of a write: its ops, and why, as a write of one document is. */
17
17
  export type Part = { doc: string; ops: Op[]; why?: string };
@@ -22,14 +22,10 @@ export type Told = Omit<Story, "does" | "cannot"> & { does?: Part | Part[]; cann
22
22
  /** The documents as the compiler holds a story's state: each by its name (a kind's, every instance's rows). */
23
23
  type State = Record<string, Record<string, unknown>>;
24
24
 
25
- /** "$n": the write's nth add. */
26
- const NTH = /^\$([1-9]\d*)$/;
27
-
28
25
  /** A story's does or cannot, as its parts: one write, or several. */
29
26
  export const partsOf = (w: Part | Part[]) => (Array.isArray(w) ? w : [w]);
30
27
 
31
- /** Whether a part's document is named by an add before it in its write (`board:$1`): no page holds it yet. */
32
- export const madeBy = (doc: string) => NTH.test(docParts(doc).key ?? "");
28
+ export { madeBy };
33
29
 
34
30
  /** Each add of an item, in order: what a later "$n" counts. */
35
31
  const addsOf = (ops: Op[]) =>
package/src/tokens.css CHANGED
@@ -60,6 +60,11 @@
60
60
  --space-48: 48px;
61
61
  --space-64: 64px;
62
62
  --gutter: clamp(1rem, 4vw, 1.5rem);
63
+ --rise: 420ms cubic-bezier(0.32, 0.72, 0, 1);
64
+ --fall: 280ms cubic-bezier(0.4, 0, 1, 1);
65
+ --ask: 220ms cubic-bezier(0.32, 0.72, 0, 1);
66
+ --ask-out: 160ms ease-out;
67
+ --drop: 160ms ease-out;
63
68
  }
64
69
  @media (prefers-color-scheme: dark) {
65
70
  :root {
package/src/tokens.json CHANGED
@@ -375,6 +375,11 @@
375
375
  "value": "4px",
376
376
  "usage": "Everything that has a corner: a button, a field, a block, the calendar, the map, a drawer, a modal, a sheet, the toast."
377
377
  },
378
+ {
379
+ "name": "radius-sheet",
380
+ "value": "14px",
381
+ "usage": "A drawer's and a sheet's top corners on a phone, where it rises from the foot: rounder, as an iPhone's sheet."
382
+ },
378
383
  {
379
384
  "name": "radius-inner",
380
385
  "value": "3px",
@@ -453,5 +458,35 @@
453
458
  "dark": "40%"
454
459
  }
455
460
  ]
461
+ },
462
+ "motion": {
463
+ "note": "How a surface comes and goes, as an iPhone's do: a drawer or a sheet rises, a modal settles, a menu drops; the scrim fades with them. Under prefers-reduced-motion, nothing moves.",
464
+ "tokens": [
465
+ {
466
+ "name": "rise",
467
+ "value": "420ms cubic-bezier(0.32, 0.72, 0, 1)",
468
+ "usage": "A drawer or a sheet coming into place (from the foot on a phone, from the right where it docks), and the scrim fading in behind it: quick, then a long soft settle."
469
+ },
470
+ {
471
+ "name": "fall",
472
+ "value": "280ms cubic-bezier(0.4, 0, 1, 1)",
473
+ "usage": "A drawer or a sheet going back the way it came, and the scrim fading out: quicker than it came, gathering speed."
474
+ },
475
+ {
476
+ "name": "ask",
477
+ "value": "220ms cubic-bezier(0.32, 0.72, 0, 1)",
478
+ "usage": "A modal fading in and settling from a little larger, as an iPhone's alert."
479
+ },
480
+ {
481
+ "name": "ask-out",
482
+ "value": "160ms ease-out",
483
+ "usage": "A modal fading as it shrinks a little, gone."
484
+ },
485
+ {
486
+ "name": "drop",
487
+ "value": "160ms ease-out",
488
+ "usage": "A menu dropping a few pixels from its button as it fades in."
489
+ }
490
+ ]
456
491
  }
457
492
  }
package/src/write.ts CHANGED
@@ -140,8 +140,9 @@ export function writes({
140
140
  /** Why a write does what no story does (an op of a form no path has, or one no story grants), or what the
141
141
  * writer's roles may not; null if neither. `roles` null: the server's own write, or nobody's on an open group,
142
142
  * asked only whether a story does it; `anyone`, whether what's granted anyone is the writer's. Asked in the write's
143
- * transaction: the values are the tables' to refuse. */
144
- function ungranted(doc: string, ops: Op[], roles: ((o: Op) => string[]) | null, anyone = true) {
143
+ * transaction: the values are the tables' to refuse. `undoing`: an undo's inverse, where an item removed is put back
144
+ * as it was, at whatever step it had come to, by anyone a story lets add one at any step. */
145
+ function ungranted(doc: string, ops: Op[], roles: ((o: Op) => string[]) | null, anyone = true, undoing = false) {
145
146
  const { grants, collections, moves } = rulesOf(doc);
146
147
  for (const o of ops) {
147
148
  const { coll, key, field, link, more } = parts(o.path);
@@ -169,15 +170,23 @@ export function writes({
169
170
  // an add giving a field that moves: its first step, from nothing
170
171
  const first =
171
172
  formed && o.op === "add" && field === undefined && moves?.[coll] ? (o.value as any)?.[moves[coll]] : undefined;
172
- const to = formed
173
- ? (grants[
174
- moved
175
- ? `${grantOf(o)}:${itemAt(doc, o)?.[field!]}>${o.value}`
176
- : first !== undefined
177
- ? `${grantOf(o)}.${moves![coll]}:>${first}`
178
- : grantOf(o)
179
- ] ?? (filled && !moved ? [] : undefined))
180
- : undefined;
173
+ const back =
174
+ undoing && first !== undefined
175
+ ? Object.entries(grants)
176
+ .filter(([g]) => g === grantOf(o) || g.startsWith(`${grantOf(o)}.${moves![coll]}:>`))
177
+ .flatMap(([, to]) => to)
178
+ : [];
179
+ const to = back.length
180
+ ? back
181
+ : formed
182
+ ? (grants[
183
+ moved
184
+ ? `${grantOf(o)}:${itemAt(doc, o)?.[field!]}>${o.value}`
185
+ : first !== undefined
186
+ ? `${grantOf(o)}.${moves![coll]}:>${first}`
187
+ : grantOf(o)
188
+ ] ?? (filled && !moved ? [] : undefined))
189
+ : undefined;
181
190
  if (!to) return moved || first !== undefined ? "that isn't a move you can make" : `no ${o.op} at ${o.path}`;
182
191
  if (roles && !grantsTo(to, () => roles(o), anyone)) return `you may not ${o.op} at ${o.path}`;
183
192
  }
@@ -412,6 +421,7 @@ export function writes({
412
421
  why: string | undefined,
413
422
  who: { member: number } | null,
414
423
  group: (doc: string, ops: Op[]) => { ops: Op[]; within?: (applied: Op[]) => void } | { refused: string },
424
+ undoing = false,
415
425
  ) {
416
426
  const r = rulesOf(doc);
417
427
  if (r.derived) throw new Refused(`${doc} is derived from ${r.derived.join(" and ")}: write that`);
@@ -420,7 +430,8 @@ export function writes({
420
430
  // an anonymous document's writes are anyone's; any other's, each op's by who the writer is to its item
421
431
  const ruled =
422
432
  trusts[r.doc]?.({ doc: docParts(doc).base, ops, why }, { member: who?.member ?? 0, roles }, read) ??
423
- serversIn(doc, ops) ??
433
+ // (an undo puts back what the server filled, as it was)
434
+ (undoing ? null : serversIn(doc, ops)) ??
424
435
  // who the writer is to the item each op is to: a member's roles, and a guest's (a page holding the document by
425
436
  // the item's own code: definitions' guests)
426
437
  ungranted(
@@ -428,11 +439,13 @@ export function writes({
428
439
  ops,
429
440
  !who && r.anonymous ? null : (o) => rolesTo(doc, who?.member ?? null, parts(o.path).coll, itemAt(doc, o)),
430
441
  anyoneIs(doc, who?.member ?? null),
442
+ undoing,
431
443
  ) ??
432
444
  // of a kind, what its root item's settings say of a write the grants allow (a frozen board, one held for approval)
433
445
  settled(
434
446
  r,
435
- settingsNow(r, () => rootItem(r, doc, read)),
447
+ // (an undo puts an item back at the step it had come to: frozen alone refuses it)
448
+ ((now) => (undoing ? { ...now, first: {} } : now))(settingsNow(r, () => rootItem(r, doc, read))),
436
449
  ops,
437
450
  );
438
451
  if (ruled) throw new Refused(ruled);
@@ -472,7 +485,9 @@ export function writes({
472
485
  applied: Op[] = [],
473
486
  own: Change[] = [];
474
487
  const one = (d: string, o: Op[], b: number | null, v: string | null, w?: (applied: Op[]) => void, u?: number) => {
475
- const made = store.write(d, fill(d, withGone(d, o), b), b, v, w, { undoes: u });
488
+ // (an undo puts back what was, filled as it was then: a field cleared since stays clear)
489
+ const gone = withGone(d, o);
490
+ const made = store.write(d, u === undefined ? fill(d, gone, b) : gone, b, v, w, { undoes: u });
476
491
  // what the definitions hold of it (unique, noOverlap), once the write is done: refused whole if not
477
492
  const held = rulesOf(d).holds?.(read(d), touchedBy(made.applied));
478
493
  if (held) throw new Refused(held);