@mostra/react 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/form.js CHANGED
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import { g as fieldKey, o as useStore } from "./hooks-DsfXVbTO.js";
2
+ import { g as fieldKey, o as useStore } from "./hooks-BfV824_7.js";
3
3
  import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
4
4
  import { get, set, useForm as useForm$1 } from "react-hook-form";
5
5
  //#region src/form.ts
@@ -332,6 +332,12 @@ var HttpTransport = class {
332
332
  live(request) {
333
333
  return this.#post("/live", request);
334
334
  }
335
+ respondents(request) {
336
+ return this.#post("/respondents", request);
337
+ }
338
+ presence(request, options) {
339
+ return this.#post("/presence", request, options?.keepalive === true);
340
+ }
335
341
  subscribe(cursor, handlers) {
336
342
  let closed = false;
337
343
  let last = cursor;
@@ -425,6 +431,20 @@ var HttpTransport = class {
425
431
  live
426
432
  });
427
433
  });
434
+ source.addEventListener("respondents", (event) => {
435
+ const respondents = JSON.parse(event.data);
436
+ handlers.onEphemeral?.({
437
+ kind: "respondents",
438
+ respondents
439
+ });
440
+ });
441
+ source.addEventListener("presence", (event) => {
442
+ const presence = JSON.parse(event.data);
443
+ handlers.onEphemeral?.({
444
+ kind: "presence",
445
+ presence
446
+ });
447
+ });
428
448
  source.addEventListener("error", () => {
429
449
  if (closed) return;
430
450
  failures += 1;
@@ -996,7 +1016,7 @@ var ServerClient = class {
996
1016
  return;
997
1017
  }
998
1018
  if (!this.#merge(tracked, message.run)) this.attach({ runIds: [message.run.runId] }).catch(() => {});
999
- } else this.#applyLiveUpdate(message.live);
1019
+ } else if (message.kind === "live") this.#applyLiveUpdate(message.live);
1000
1020
  }
1001
1021
  /** Keeps an update for a run the page will track once its start is answered. */
1002
1022
  #keepEarly(delta) {
@@ -1045,6 +1065,308 @@ var ServerClient = class {
1045
1065
  function decode(value) {
1046
1066
  return deserializeAll(value);
1047
1067
  }
1068
+ //#endregion
1069
+ //#region src/runtime/team.ts
1070
+ /** How often the roster is read again while a hook shows it (the gateway follows it a minute). */
1071
+ const RESPONDENTS_RENEW_MS = 2e4;
1072
+ /** How often a present page posts though nothing changed (the gateway keeps it 30 s). */
1073
+ const PRESENCE_HEARTBEAT_MS = 1e4;
1074
+ /** The page's team state: its roster and its presence. */
1075
+ var TeamClient = class {
1076
+ #transport;
1077
+ #viewId;
1078
+ #timers;
1079
+ #listeners = /* @__PURE__ */ new Set();
1080
+ #version = 0;
1081
+ #roster;
1082
+ #rosterError;
1083
+ #rosterWatchers = 0;
1084
+ #rosterTimer;
1085
+ #presence;
1086
+ #sharing = /* @__PURE__ */ new Map();
1087
+ #cursor = null;
1088
+ #selection = null;
1089
+ /** What the gateway was last told, so an unchanged state is sent only as a heartbeat. */
1090
+ #sent = {
1091
+ cursor: "null",
1092
+ selection: "null"
1093
+ };
1094
+ #sendTimer;
1095
+ #heartbeat;
1096
+ #lastSend = 0;
1097
+ #inFlight = false;
1098
+ #again = false;
1099
+ #blockedUntil = 0;
1100
+ /** This page's count of its presence posts (`seq`), a leave included. */
1101
+ #seq = 0;
1102
+ /** The count of the page's last leave: an answer to an earlier post is no longer its own. */
1103
+ #leftAt = -1;
1104
+ #stopTracking;
1105
+ constructor(options) {
1106
+ this.#transport = options.transport;
1107
+ this.#viewId = options.viewId;
1108
+ this.#timers = options.timers ?? {
1109
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
1110
+ clearTimeout: (handle) => clearTimeout(handle)
1111
+ };
1112
+ }
1113
+ /** Whether this page can reach the gateway's team routes (a live page; not a static export). */
1114
+ get available() {
1115
+ return this.#transport?.respondents !== void 0 && this.#viewId !== void 0;
1116
+ }
1117
+ subscribe = (listener) => {
1118
+ this.#listeners.add(listener);
1119
+ return () => this.#listeners.delete(listener);
1120
+ };
1121
+ version = () => this.#version;
1122
+ #changed() {
1123
+ this.#version += 1;
1124
+ for (const listener of [...this.#listeners]) listener();
1125
+ }
1126
+ roster() {
1127
+ return this.#roster;
1128
+ }
1129
+ rosterError() {
1130
+ return this.#rosterError;
1131
+ }
1132
+ /** A `useRespondents` mounted: reads the roster now and keeps it followed; returns the stop. */
1133
+ watchRespondents() {
1134
+ this.#rosterWatchers += 1;
1135
+ if (this.#rosterWatchers === 1) this.#readRoster();
1136
+ let stopped = false;
1137
+ return () => {
1138
+ if (stopped) return;
1139
+ stopped = true;
1140
+ this.#rosterWatchers -= 1;
1141
+ if (this.#rosterWatchers === 0 && this.#rosterTimer !== void 0) {
1142
+ this.#timers.clearTimeout(this.#rosterTimer);
1143
+ this.#rosterTimer = void 0;
1144
+ }
1145
+ };
1146
+ }
1147
+ async #readRoster() {
1148
+ if (this.#rosterTimer !== void 0) this.#timers.clearTimeout(this.#rosterTimer);
1149
+ this.#rosterTimer = void 0;
1150
+ const transport = this.#transport;
1151
+ if (!transport?.respondents || this.#viewId === void 0 || this.#rosterWatchers === 0) return;
1152
+ try {
1153
+ this.#roster = await transport.respondents({ viewId: this.#viewId });
1154
+ this.#rosterError = void 0;
1155
+ } catch (error) {
1156
+ if (error instanceof MostraError) this.#rosterError = error;
1157
+ }
1158
+ this.#changed();
1159
+ if (this.#rosterWatchers > 0) this.#rosterTimer = this.#timers.setTimeout(() => void this.#readRoster(), RESPONDENTS_RENEW_MS);
1160
+ }
1161
+ presence() {
1162
+ return this.#presence;
1163
+ }
1164
+ /** A `usePresence` mounted with what it shares: joins presence; returns the leave. */
1165
+ joinPresence(sharing) {
1166
+ const id = Symbol("presence");
1167
+ this.#sharing.set(id, sharing);
1168
+ this.#retrack();
1169
+ this.#schedule(0);
1170
+ return () => {
1171
+ if (!this.#sharing.delete(id)) return;
1172
+ this.#retrack();
1173
+ if (this.#sharing.size === 0) this.#leave(false);
1174
+ else this.#schedule(0);
1175
+ };
1176
+ }
1177
+ #shares() {
1178
+ let cursor = false;
1179
+ let selection = false;
1180
+ for (const entry of this.#sharing.values()) {
1181
+ cursor ||= entry.cursor;
1182
+ selection ||= entry.selection;
1183
+ }
1184
+ return {
1185
+ cursor,
1186
+ selection
1187
+ };
1188
+ }
1189
+ /** Follows the pointer and the selection as far as a mounted hook shares them. */
1190
+ #retrack() {
1191
+ this.#stopTracking?.();
1192
+ this.#stopTracking = void 0;
1193
+ const { cursor, selection } = this.#shares();
1194
+ if (!cursor) this.#cursor = null;
1195
+ if (!selection) this.#selection = null;
1196
+ if (typeof document === "undefined" || this.#sharing.size === 0) return;
1197
+ const stops = [];
1198
+ if (cursor) {
1199
+ const move = (event) => {
1200
+ this.#cursor = {
1201
+ x: Math.round(event.pageX),
1202
+ y: Math.round(event.pageY)
1203
+ };
1204
+ this.#schedule();
1205
+ };
1206
+ const away = () => {
1207
+ this.#cursor = null;
1208
+ this.#schedule();
1209
+ };
1210
+ document.addEventListener("pointermove", move, { passive: true });
1211
+ document.documentElement.addEventListener("pointerleave", away);
1212
+ stops.push(() => {
1213
+ document.removeEventListener("pointermove", move);
1214
+ document.documentElement.removeEventListener("pointerleave", away);
1215
+ });
1216
+ }
1217
+ if (selection) {
1218
+ const read = () => {
1219
+ this.#selection = selectionNow();
1220
+ this.#schedule();
1221
+ };
1222
+ document.addEventListener("focusin", read);
1223
+ document.addEventListener("focusout", read);
1224
+ document.addEventListener("selectionchange", read);
1225
+ stops.push(() => {
1226
+ document.removeEventListener("focusin", read);
1227
+ document.removeEventListener("focusout", read);
1228
+ document.removeEventListener("selectionchange", read);
1229
+ });
1230
+ }
1231
+ const gone = () => this.#leave(true);
1232
+ const back = (event) => {
1233
+ if (!event.persisted || this.#sharing.size === 0) return;
1234
+ this.#presence = void 0;
1235
+ this.#changed();
1236
+ this.#schedule(0);
1237
+ };
1238
+ window.addEventListener("pagehide", gone);
1239
+ window.addEventListener("pageshow", back);
1240
+ stops.push(() => {
1241
+ window.removeEventListener("pagehide", gone);
1242
+ window.removeEventListener("pageshow", back);
1243
+ });
1244
+ this.#stopTracking = () => {
1245
+ for (const stop of stops) stop();
1246
+ };
1247
+ }
1248
+ /** Posts soon: at once when the throttle allows, else when it does; the latest state wins. */
1249
+ #schedule(delay) {
1250
+ if (!this.#transport?.presence || this.#viewId === void 0 || this.#sharing.size === 0) return;
1251
+ if (this.#sendTimer !== void 0) return;
1252
+ const now = Date.now();
1253
+ const wait = Math.max(delay ?? 0, this.#lastSend + 100 - now, this.#blockedUntil - now, 0);
1254
+ this.#sendTimer = this.#timers.setTimeout(() => {
1255
+ this.#sendTimer = void 0;
1256
+ this.#send();
1257
+ }, wait);
1258
+ }
1259
+ async #send() {
1260
+ const transport = this.#transport;
1261
+ if (!transport?.presence || this.#viewId === void 0 || this.#sharing.size === 0) return;
1262
+ if (this.#inFlight) {
1263
+ this.#again = true;
1264
+ return;
1265
+ }
1266
+ this.#inFlight = true;
1267
+ this.#lastSend = Date.now();
1268
+ const cursor = JSON.stringify(this.#cursor);
1269
+ const selection = JSON.stringify(this.#selection);
1270
+ this.#seq += 1;
1271
+ const seq = this.#seq;
1272
+ const request = {
1273
+ viewId: this.#viewId,
1274
+ ...cursor !== this.#sent.cursor ? { cursor: this.#cursor } : {},
1275
+ ...selection !== this.#sent.selection ? { selection: this.#selection } : {},
1276
+ seq
1277
+ };
1278
+ try {
1279
+ const answer = await transport.presence(request);
1280
+ if (this.#leftAt > seq) return;
1281
+ this.#presence = answer;
1282
+ this.#sent = {
1283
+ cursor,
1284
+ selection
1285
+ };
1286
+ this.#changed();
1287
+ } catch (error) {
1288
+ if (error instanceof MostraError && error.code === "MOSTRA_TEAM_PRESENCE_RATE_LIMITED") {
1289
+ this.#blockedUntil = Date.now() + 1e3;
1290
+ this.#again = true;
1291
+ }
1292
+ } finally {
1293
+ this.#inFlight = false;
1294
+ }
1295
+ if (this.#leftAt > seq) return;
1296
+ if (this.#heartbeat !== void 0) this.#timers.clearTimeout(this.#heartbeat);
1297
+ this.#heartbeat = this.#sharing.size > 0 ? this.#timers.setTimeout(() => this.#schedule(0), PRESENCE_HEARTBEAT_MS) : void 0;
1298
+ if (this.#again || JSON.stringify(this.#cursor) !== this.#sent.cursor || JSON.stringify(this.#selection) !== this.#sent.selection) {
1299
+ this.#again = false;
1300
+ this.#schedule();
1301
+ }
1302
+ }
1303
+ #leave(closing) {
1304
+ for (const timer of [this.#sendTimer, this.#heartbeat]) if (timer !== void 0) this.#timers.clearTimeout(timer);
1305
+ this.#sendTimer = void 0;
1306
+ this.#heartbeat = void 0;
1307
+ this.#sent = {
1308
+ cursor: "null",
1309
+ selection: "null"
1310
+ };
1311
+ this.#again = false;
1312
+ const transport = this.#transport;
1313
+ if (!transport?.presence || this.#viewId === void 0) return;
1314
+ this.#seq += 1;
1315
+ this.#leftAt = this.#seq;
1316
+ transport.presence({
1317
+ viewId: this.#viewId,
1318
+ leave: true,
1319
+ seq: this.#seq
1320
+ }, { keepalive: closing }).catch(() => void 0);
1321
+ if (!closing) {
1322
+ this.#presence = void 0;
1323
+ this.#changed();
1324
+ }
1325
+ }
1326
+ /** The stream reconnected: read the roster again and post presence, since messages were lost. */
1327
+ resync() {
1328
+ if (this.#rosterWatchers > 0) this.#readRoster();
1329
+ if (this.#sharing.size > 0) this.#schedule(0);
1330
+ }
1331
+ /** One ephemeral message of the page's stream. */
1332
+ receive(message) {
1333
+ if (message.kind === "respondents") {
1334
+ if (this.#rosterWatchers === 0) return;
1335
+ this.#roster = message.respondents;
1336
+ } else {
1337
+ if (this.#sharing.size === 0) return;
1338
+ this.#presence = message.presence;
1339
+ }
1340
+ this.#changed();
1341
+ }
1342
+ stop() {
1343
+ this.#stopTracking?.();
1344
+ for (const timer of [
1345
+ this.#sendTimer,
1346
+ this.#heartbeat,
1347
+ this.#rosterTimer
1348
+ ]) if (timer !== void 0) this.#timers.clearTimeout(timer);
1349
+ }
1350
+ };
1351
+ /**
1352
+ * The viewer's selection as presence shares it: the focused element's `data-presence-id`, `id` or
1353
+ * `name` (the nearest one that has one), and in a text input its selected range.
1354
+ */
1355
+ function selectionNow() {
1356
+ const active = document.activeElement;
1357
+ if (!active || active === document.body) return null;
1358
+ const element = active.closest("[data-presence-id]")?.getAttribute("data-presence-id") ?? (active.id !== "" ? active.id : void 0) ?? active.getAttribute("name") ?? void 0;
1359
+ if (element === void 0 || element === "") return null;
1360
+ const input = active;
1361
+ const range = typeof input.selectionStart === "number" && typeof input.selectionEnd === "number" ? {
1362
+ start: input.selectionStart,
1363
+ end: input.selectionEnd
1364
+ } : {};
1365
+ return {
1366
+ element: element.slice(0, 256),
1367
+ ...range
1368
+ };
1369
+ }
1048
1370
  /** How long a submit waits for the event stream to reach the page's own last save. */
1049
1371
  const CATCH_UP_MS = 5e3;
1050
1372
  /** How soon waiting saves try again once the event stream shows the gateway answers. */
@@ -1159,6 +1481,8 @@ var Store = class {
1159
1481
  #stopStream;
1160
1482
  /** Plain calls, action runs and live sources (WP-08), over the same transport and view. */
1161
1483
  server;
1484
+ /** The roster and presence (WP-31, D168), over the same transport and view. */
1485
+ team;
1162
1486
  constructor(options) {
1163
1487
  this.#options = options;
1164
1488
  this.server = new ServerClient({
@@ -1166,6 +1490,11 @@ var Store = class {
1166
1490
  ...options.mode === "live" && options.view ? { viewId: options.view.viewId } : {},
1167
1491
  ...options.timers ? { timers: options.timers } : {}
1168
1492
  });
1493
+ this.team = new TeamClient({
1494
+ ...options.mode === "live" && options.transport ? { transport: options.transport } : {},
1495
+ ...options.mode === "live" && options.view ? { viewId: options.view.viewId } : {},
1496
+ ...options.timers ? { timers: options.timers } : {}
1497
+ });
1169
1498
  this.mode = options.mode;
1170
1499
  this.view = options.view;
1171
1500
  this.#viewer = options.viewer;
@@ -1230,11 +1559,15 @@ var Store = class {
1230
1559
  if (online) {
1231
1560
  this.#kickQueue();
1232
1561
  this.server.resync();
1562
+ this.team.resync();
1233
1563
  }
1234
1564
  this.#changed(this.#allKeys());
1235
1565
  }
1236
1566
  },
1237
- onEphemeral: (message) => this.server.receive(message)
1567
+ onEphemeral: (message) => {
1568
+ if (message.kind === "respondents" || message.kind === "presence") this.team.receive(message);
1569
+ else this.server.receive(message);
1570
+ }
1238
1571
  });
1239
1572
  if (typeof window !== "undefined") window.addEventListener("online", () => this.#kickQueue());
1240
1573
  }
@@ -1242,6 +1575,7 @@ var Store = class {
1242
1575
  stop() {
1243
1576
  this.#stopStream?.();
1244
1577
  this.server.stop();
1578
+ this.team.stop();
1245
1579
  this.#broadcast?.close();
1246
1580
  if (this.#debounce !== void 0) this.#timers.clearTimeout(this.#debounce);
1247
1581
  if (this.#retry !== void 0) this.#timers.clearTimeout(this.#retry);
@@ -1275,7 +1609,8 @@ var Store = class {
1275
1609
  value: field.value,
1276
1610
  revision: Number(field.revision),
1277
1611
  deleted: false,
1278
- ...field.updatedBy ? { updatedBy: field.updatedBy } : {}
1612
+ ...field.updatedBy ? { updatedBy: field.updatedBy } : {},
1613
+ updatedAt: field.updatedAt
1279
1614
  });
1280
1615
  }
1281
1616
  return replace;
@@ -1315,7 +1650,8 @@ var Store = class {
1315
1650
  value: mine.value,
1316
1651
  revision,
1317
1652
  deleted: false,
1318
- updatedBy: event.actor
1653
+ updatedBy: event.actor,
1654
+ updatedAt: event.at
1319
1655
  });
1320
1656
  else {
1321
1657
  this.#unknown.add(key);
@@ -1328,7 +1664,8 @@ var Store = class {
1328
1664
  value: change.deleted ? void 0 : change.value,
1329
1665
  revision,
1330
1666
  deleted: change.deleted === true,
1331
- updatedBy: event.actor
1667
+ updatedBy: event.actor,
1668
+ updatedAt: event.at
1332
1669
  });
1333
1670
  }
1334
1671
  this.#seen[scope] = Math.max(this.#seen[scope], revision);
@@ -1390,6 +1727,10 @@ var Store = class {
1390
1727
  updatedBy(key) {
1391
1728
  return this.#server.get(key)?.updatedBy;
1392
1729
  }
1730
+ /** When the field was written last, as the gateway or this page knows it. */
1731
+ updatedAt(key) {
1732
+ return this.#server.get(key)?.updatedAt;
1733
+ }
1393
1734
  /** Why the gateway refused the field's edit for good, if it did: its code and message. */
1394
1735
  refusal(key) {
1395
1736
  return this.#refused.get(key);
@@ -1803,7 +2144,8 @@ var Store = class {
1803
2144
  updatedBy: {
1804
2145
  kind: "viewer",
1805
2146
  ...this.#viewer ? { id: this.#viewer.id } : {}
1806
- }
2147
+ },
2148
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1807
2149
  });
1808
2150
  applied.push({
1809
2151
  id: op.id,
@@ -2037,7 +2379,8 @@ var Store = class {
2037
2379
  value: change.value,
2038
2380
  revision: data.revision,
2039
2381
  deleted: change.value === void 0,
2040
- ...current?.updatedBy ? { updatedBy: current.updatedBy } : {}
2382
+ ...current?.updatedBy ? { updatedBy: current.updatedBy } : {},
2383
+ ...current?.updatedAt !== void 0 ? { updatedAt: current.updatedAt } : {}
2041
2384
  });
2042
2385
  touched.push(key);
2043
2386
  }
@@ -2501,11 +2844,14 @@ function validationOf(validate, value) {
2501
2844
  error: messageOf(result)
2502
2845
  };
2503
2846
  }
2504
- function updatedByOf(actor) {
2847
+ function updatedByOf(actor, at, viewerId) {
2505
2848
  if (!actor || actor.kind === "mostra") return void 0;
2506
2849
  return {
2507
2850
  kind: actor.kind,
2508
- ...actor.name !== void 0 ? { name: actor.name } : {}
2851
+ ...actor.name !== void 0 ? { name: actor.name } : {},
2852
+ ...actor.key !== void 0 ? { key: actor.key } : {},
2853
+ ...actor.kind === "viewer" && viewerId !== void 0 ? { self: actor.id === viewerId } : {},
2854
+ ...at !== void 0 ? { at } : {}
2509
2855
  };
2510
2856
  }
2511
2857
  const warned = /* @__PURE__ */ new Set();
@@ -2620,18 +2966,14 @@ function useField(id, initial, options = {}) {
2620
2966
  const conflict = store.conflict(key);
2621
2967
  const refusal = store.refusal(key);
2622
2968
  const save = store.save(key);
2623
- const writer = updatedByOf(store.updatedBy(key));
2624
- const writerKind = writer?.kind;
2625
- const writerName = writer?.name;
2969
+ const writer = updatedByOf(store.updatedBy(key), store.updatedAt(key), store.viewer()?.id);
2970
+ const writerText = writer === void 0 ? void 0 : JSON.stringify(writer);
2626
2971
  return [
2627
2972
  value,
2628
2973
  set,
2629
2974
  useMemo(() => {
2630
2975
  const message = error ?? refusal?.message;
2631
- const updatedBy = writerKind === void 0 ? void 0 : {
2632
- kind: writerKind,
2633
- ...writerName !== void 0 ? { name: writerName } : {}
2634
- };
2976
+ const updatedBy = writerText === void 0 ? void 0 : JSON.parse(writerText);
2635
2977
  return {
2636
2978
  save,
2637
2979
  ...message !== void 0 ? { error: message } : {},
@@ -2647,8 +2989,7 @@ function useField(id, initial, options = {}) {
2647
2989
  error,
2648
2990
  refusal,
2649
2991
  conflict,
2650
- writerKind,
2651
- writerName,
2992
+ writerText,
2652
2993
  store,
2653
2994
  key,
2654
2995
  scope,
@@ -2800,4 +3141,4 @@ function useArtifact() {
2800
3141
  //#endregion
2801
3142
  export { serverFunctionId as _, useSignal as a, MemoryJournal as b, useSubmitControl as c, connectShell as d, listenShell as f, fieldKey as g, Store as h, useField as i, useViewer as l, reportReady as m, useArtifact as n, useStore as o, openLink as p, useChoice as r, useSubmit as s, RuntimeProvider as t, builtVersion as u, HttpTransport as v, MostraError as x, IndexedDbJournal as y };
2802
3143
 
2803
- //# sourceMappingURL=hooks-DsfXVbTO.js.map
3144
+ //# sourceMappingURL=hooks-BfV824_7.js.map