@bitcobblers/wod-wiki-lang 0.53.2204 → 0.55.2206

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/react.cjs CHANGED
@@ -42,8 +42,12 @@ var useRuntimeExecution = (runtime) => {
42
42
  clearInterval(intervalRef.current);
43
43
  intervalRef.current = null;
44
44
  }
45
+ if (startTimeRef.current !== null) {
46
+ const now = runtime?.nowProvider?.nowMs() ?? wallClockNow.nowMs();
47
+ setElapsedTime(now - startTimeRef.current);
48
+ }
45
49
  setStatus("idle");
46
- }, []);
50
+ }, [runtime]);
47
51
  const executeStep = react.useCallback(() => {
48
52
  if (!runtime) return;
49
53
  try {
@@ -63,6 +67,10 @@ var useRuntimeExecution = (runtime) => {
63
67
  clearInterval(intervalRef.current);
64
68
  intervalRef.current = null;
65
69
  }
70
+ if (startTimeRef.current !== null) {
71
+ const now = runtime?.nowProvider?.nowMs() ?? wallClockNow.nowMs();
72
+ setElapsedTime(now - startTimeRef.current);
73
+ }
66
74
  setStatus("completed");
67
75
  }
68
76
  });
@@ -105,10 +113,15 @@ var useRuntimeExecution = (runtime) => {
105
113
  clearInterval(intervalRef.current);
106
114
  intervalRef.current = null;
107
115
  }
116
+ if (startTimeRef.current !== null) {
117
+ const now = runtime?.nowProvider?.nowMs() ?? wallClockNow.nowMs();
118
+ setElapsedTime(now - startTimeRef.current);
119
+ }
108
120
  if (runtime) {
121
+ const pauseDate = runtime.nowProvider?.now() ?? wallClockNow.now();
109
122
  runtime.handle({
110
123
  name: "timer:pause",
111
- timestamp: /* @__PURE__ */ new Date(),
124
+ timestamp: pauseDate,
112
125
  data: {}
113
126
  });
114
127
  }
@@ -216,6 +229,29 @@ var calculateDuration = (spans, now) => {
216
229
  }, 0);
217
230
  };
218
231
 
232
+ // src/runtime/browserRuntimeNow.ts
233
+ function getRuntimeNowMs() {
234
+ if (typeof window !== "undefined") {
235
+ const senderClock = window.__chromecast_senderClockTimeMs;
236
+ if (typeof senderClock === "function") {
237
+ try {
238
+ const value = senderClock();
239
+ if (Number.isFinite(value)) {
240
+ return value;
241
+ }
242
+ } catch {
243
+ }
244
+ }
245
+ }
246
+ return Date.now();
247
+ }
248
+ function createBrowserRuntimeNow() {
249
+ return {
250
+ now: () => new Date(getRuntimeNowMs()),
251
+ nowMs: () => getRuntimeNowMs()
252
+ };
253
+ }
254
+
219
255
  // src/react/hooks/useBlockMemory.ts
220
256
  function useBlockMemory(block, type) {
221
257
  const tag = type;
@@ -258,14 +294,7 @@ function useDisplayState(block) {
258
294
  }
259
295
  function useTimerDisplay(block) {
260
296
  const timer = useTimerState(block);
261
- const getNow = () => {
262
- if (typeof window !== "undefined") {
263
- const receiverClock = window.__chromecast_senderClockTimeMs;
264
- if (typeof receiverClock === "function") return receiverClock();
265
- }
266
- return Date.now();
267
- };
268
- const [now, setNow] = react.useState(getNow());
297
+ const [now, setNow] = react.useState(() => getRuntimeNowMs());
269
298
  const isRunning = react.useMemo(() => {
270
299
  if (!timer || timer.spans.length === 0) return false;
271
300
  const lastSpan = timer.spans[timer.spans.length - 1];
@@ -277,7 +306,7 @@ function useTimerDisplay(block) {
277
306
  let running = true;
278
307
  const tick = () => {
279
308
  if (!running || typeof requestAnimationFrame !== "function") return;
280
- setNow(getNow());
309
+ setNow(getRuntimeNowMs());
281
310
  animationFrameId = requestAnimationFrame(tick);
282
311
  };
283
312
  animationFrameId = requestAnimationFrame(tick);
@@ -348,6 +377,9 @@ function useScriptRuntime() {
348
377
  }
349
378
  return runtime;
350
379
  }
380
+ function useOptionalScriptRuntime() {
381
+ return react.useContext(ScriptRuntimeContext) ?? null;
382
+ }
351
383
 
352
384
  // src/react/hooks/useOutputStatements.ts
353
385
  function useOutputStatements(runtime) {
@@ -539,7 +571,7 @@ function usePrimaryTimer() {
539
571
  return react.useMemo(() => {
540
572
  if (timers.length === 0) return void 0;
541
573
  const leaf = timers[0];
542
- if (leaf.block.blockType === "Rest") return leaf;
574
+ if (leaf.block.blockType === "Rest" || leaf.timer.polarity === "rest") return leaf;
543
575
  const pinned = [...timers].reverse().find((t) => t.isPinned);
544
576
  if (pinned) return pinned;
545
577
  return leaf;
@@ -693,31 +725,6 @@ function useStackDisplayRows() {
693
725
  return entries.length > 0 ? entries : void 0;
694
726
  }, [blocks, version]);
695
727
  }
696
-
697
- // src/runtime/browserRuntimeNow.ts
698
- function getRuntimeNowMs() {
699
- if (typeof window !== "undefined") {
700
- const senderClock = window.__chromecast_senderClockTimeMs;
701
- if (typeof senderClock === "function") {
702
- try {
703
- const value = senderClock();
704
- if (Number.isFinite(value)) {
705
- return value;
706
- }
707
- } catch {
708
- }
709
- }
710
- }
711
- return Date.now();
712
- }
713
- function createBrowserRuntimeNow() {
714
- return {
715
- now: () => new Date(getRuntimeNowMs()),
716
- nowMs: () => getRuntimeNowMs()
717
- };
718
- }
719
-
720
- // src/react/hooks/useTimerElapsed.ts
721
728
  function useTimerElapsed(blockKey) {
722
729
  const runtime = useScriptRuntime();
723
730
  const block = react.useMemo(() => {
@@ -775,6 +782,766 @@ function useTimerElapsed(blockKey) {
775
782
  timeSpans
776
783
  };
777
784
  }
785
+ var TIME_LIKE_TYPES = /* @__PURE__ */ new Set([
786
+ wodWikiCore.MetricType.Duration,
787
+ wodWikiCore.MetricType.Time,
788
+ wodWikiCore.MetricType.Elapsed,
789
+ wodWikiCore.MetricType.Total
790
+ ]);
791
+ function isTimeLikeMetric(type) {
792
+ return TIME_LIKE_TYPES.has(type);
793
+ }
794
+ function baseText(metric) {
795
+ if (metric.image) return metric.image;
796
+ if (metric.value === void 0 || metric.value === null) return metric.type;
797
+ if (typeof metric.value === "object") {
798
+ const v = metric.value;
799
+ if ("text" in v) return String(v.text);
800
+ if ("current" in v) return `Round ${v.current}`;
801
+ return JSON.stringify(metric.value);
802
+ }
803
+ return String(metric.value);
804
+ }
805
+ function computeLabel(metric, _surface) {
806
+ if (isTimeLikeMetric(metric.type) && typeof metric.value === "number") {
807
+ return formatDurationSmart(metric.value);
808
+ }
809
+ const base = baseText(metric);
810
+ if (metric.type === wodWikiCore.MetricType.Rounds || metric.type === "rounds") {
811
+ const trimmed = base.trim();
812
+ if (/^\d+$/.test(trimmed)) {
813
+ const n = Number(trimmed);
814
+ return `${base} ${n === 1 ? "Round" : "Rounds"}`;
815
+ }
816
+ }
817
+ return base;
818
+ }
819
+ function buildTooltip(metric) {
820
+ const parts = [];
821
+ parts.push(`Type: ${metric.type}`);
822
+ if (metric.value !== void 0) parts.push(`Value: ${metric.value}`);
823
+ if (metric.origin) parts.push(`Origin: ${metric.origin}`);
824
+ if (metric.sourceBlockKey) parts.push(`Block: ${metric.sourceBlockKey}`);
825
+ if (metric.timestamp) parts.push(`Time: ${metric.timestamp.toISOString()}`);
826
+ return parts.join("\n");
827
+ }
828
+ var COLUMN_LABEL_MAP = {
829
+ duration: "Duration",
830
+ rep: "Reps",
831
+ effort: "Effort",
832
+ distance: "Distance",
833
+ rounds: "Rounds",
834
+ resistance: "Resistance",
835
+ action: "Action",
836
+ increment: "Increment",
837
+ metric: "Metric",
838
+ label: "Label",
839
+ text: "Text",
840
+ custom: "Custom",
841
+ calculated: "Calculated",
842
+ "current-round": "Current Round",
843
+ volume: "Volume",
844
+ intensity: "Intensity",
845
+ load: "Load",
846
+ work: "Work",
847
+ lap: "Lap",
848
+ group: "Group",
849
+ time: "Time",
850
+ elapsed: "Elapsed",
851
+ total: "Total",
852
+ "system-time": "System Time",
853
+ spans: "Spans",
854
+ system: "System",
855
+ rir: "RIR",
856
+ "session-rpe": "Session RPE",
857
+ "session-load": "Session Load",
858
+ "met-score": "MET Score",
859
+ tis: "TIS",
860
+ sound: "Sound"
861
+ };
862
+ function humanizeMetricKey(value) {
863
+ const spaced = value.replace(/[_-]+/g, " ").replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").trim();
864
+ if (spaced.length === 0) return "";
865
+ return spaced.split(/\s+/).map((word) => {
866
+ if (word === word.toUpperCase()) return word;
867
+ if (/^[A-Z]{2,}$/.test(word)) return word;
868
+ return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
869
+ }).join(" ");
870
+ }
871
+ function computeColumnLabel(type) {
872
+ const key = String(type).trim();
873
+ const normalized = key.toLowerCase();
874
+ return COLUMN_LABEL_MAP[normalized] ?? humanizeMetricKey(key);
875
+ }
876
+ var TAG_MARKER_PREFIX = "tag.";
877
+
878
+ // src/metrics/presentation/MetricPresentationPolicy.ts
879
+ function isRestMetric(metric) {
880
+ const t = metric.type.toLowerCase();
881
+ if (t !== "effort") return false;
882
+ const v = metric.value ?? metric.image ?? "";
883
+ return v.trim().toLowerCase() === "rest";
884
+ }
885
+ function computeTone(metric, rest) {
886
+ if (rest) return "rest";
887
+ const t = metric.type.toLowerCase();
888
+ const toneMap = {
889
+ time: "time",
890
+ duration: "time",
891
+ elapsed: "time",
892
+ total: "time",
893
+ spans: "time",
894
+ rep: "rep",
895
+ effort: "effort",
896
+ distance: "distance",
897
+ rounds: "rounds",
898
+ increment: "rounds",
899
+ "current-round": "rounds",
900
+ action: "action",
901
+ resistance: "resistance",
902
+ text: "muted",
903
+ label: "muted",
904
+ group: "muted",
905
+ lap: "muted",
906
+ system: "system",
907
+ "system-time": "system",
908
+ volume: "rep",
909
+ intensity: "effort",
910
+ load: "resistance",
911
+ work: "effort",
912
+ rir: "effort",
913
+ "session-rpe": "effort",
914
+ "session-load": "resistance",
915
+ "met-score": "distance",
916
+ tis: "action",
917
+ sound: "system",
918
+ metric: "effort",
919
+ custom: "muted",
920
+ calculated: "effort"
921
+ };
922
+ return toneMap[t] ?? "unknown";
923
+ }
924
+ function createPolicy() {
925
+ const policy = {
926
+ isStructural(metric) {
927
+ const t = metric.type;
928
+ if (t === wodWikiCore.MetricType.Group || t === "group") {
929
+ const img = metric.image ?? "";
930
+ return img === "+" || img === "-";
931
+ }
932
+ return t === wodWikiCore.MetricType.Lap || t === "lap";
933
+ },
934
+ isHidden(metric, surface) {
935
+ if (this.isStructural(metric)) {
936
+ return surface !== "debug";
937
+ }
938
+ const t = metric.type;
939
+ if ((t === wodWikiCore.MetricType.Sound || t === "sound") && surface !== "debug") return true;
940
+ if (t.startsWith(TAG_MARKER_PREFIX) && surface !== "debug") return true;
941
+ if (surface === "review-grid-column") {
942
+ if (t === wodWikiCore.MetricType.Elapsed || t === "elapsed" || t === wodWikiCore.MetricType.Total || t === "total") return true;
943
+ if (t === wodWikiCore.MetricType.System || t === "system") return true;
944
+ }
945
+ return false;
946
+ },
947
+ present(metric, surface) {
948
+ const structural = this.isStructural(metric);
949
+ const hidden = this.isHidden(metric, surface);
950
+ const rest = isRestMetric(metric);
951
+ const comment = (metric.type === wodWikiCore.MetricType.Text || metric.type === "text") && metric.origin === "parser";
952
+ const userEntered = metric.origin === "user";
953
+ let renderKind;
954
+ if (hidden) {
955
+ renderKind = "hidden";
956
+ } else if (comment) {
957
+ renderKind = "comment";
958
+ } else if (surface === "timer-subtitle" || surface === "history-label" || surface === "label-composer") {
959
+ renderKind = "plain-text";
960
+ } else if (surface === "review-grid-column") {
961
+ renderKind = "column-heading";
962
+ } else {
963
+ renderKind = "badge";
964
+ }
965
+ return {
966
+ metric,
967
+ label: computeLabel(metric),
968
+ tooltip: buildTooltip(metric),
969
+ renderKind,
970
+ tone: computeTone(metric, rest),
971
+ iconKey: rest ? "rest" : metric.type,
972
+ visible: !hidden,
973
+ structural,
974
+ rest,
975
+ comment,
976
+ userEntered,
977
+ columnLabel: computeColumnLabel(metric.type)
978
+ };
979
+ },
980
+ presentGroup(metrics, surface) {
981
+ return metrics.map((m) => this.present(m, surface));
982
+ },
983
+ columnLabel(type) {
984
+ return computeColumnLabel(type);
985
+ }
986
+ };
987
+ return policy;
988
+ }
989
+ var metricPresentation = createPolicy();
990
+
991
+ // src/runtime/projection/SessionClockProjection.ts
992
+ var EXCLUDED_REP_BLOCK_TYPES = {
993
+ Rounds: true,
994
+ Group: true,
995
+ AMRAP: true,
996
+ EMOM: true,
997
+ SessionRoot: true,
998
+ Root: true,
999
+ Timer: true,
1000
+ Rest: true
1001
+ };
1002
+ function serializeSpans(spans) {
1003
+ return spans.map(
1004
+ (s) => s.ended !== void 0 ? { started: s.started, ended: s.ended } : { started: s.started }
1005
+ );
1006
+ }
1007
+ function resolveVisualPolarity(params) {
1008
+ if (params.isPaused) return "paused";
1009
+ if (params.direction === "down" && params.durationMs !== void 0 && params.durationMs > 0) {
1010
+ if (params.displayMs <= 0) return "overrun";
1011
+ if (params.displayMs <= 5e3) return "final5";
1012
+ }
1013
+ return params.basePolarity === "rest" ? "rest" : "work";
1014
+ }
1015
+ function isRequiredCountdownLocked(params) {
1016
+ return !params.isPaused && params.required && params.direction === "down" && params.durationMs !== void 0 && params.displayMs > 0;
1017
+ }
1018
+ var WATCHED_CLOCK_MEMORY_TAGS = [
1019
+ "time",
1020
+ "round",
1021
+ "display",
1022
+ "metric:display",
1023
+ "metric:result",
1024
+ "metric:next"
1025
+ ];
1026
+ function observeSessionClockInputs(runtime, onChange) {
1027
+ let skipFlash = false;
1028
+ let skipFlashKey = 0;
1029
+ let skipTimer;
1030
+ let memoryUnsubs = [];
1031
+ const emit = () => onChange({ skipFlash, skipFlashKey });
1032
+ const rebindBlockMemory = () => {
1033
+ memoryUnsubs.forEach((fn) => fn());
1034
+ memoryUnsubs = [];
1035
+ for (const block of runtime.stack.blocks) {
1036
+ for (const tag of WATCHED_CLOCK_MEMORY_TAGS) {
1037
+ for (const loc of block.getMemoryByTag(tag)) {
1038
+ memoryUnsubs.push(loc.subscribe(emit));
1039
+ }
1040
+ }
1041
+ }
1042
+ };
1043
+ rebindBlockMemory();
1044
+ const unsubStack = runtime.subscribeToStack(() => {
1045
+ rebindBlockMemory();
1046
+ emit();
1047
+ });
1048
+ const unsubSkip = runtime.eventBus.on(
1049
+ "timer:skip-attempt",
1050
+ () => {
1051
+ skipFlashKey += 1;
1052
+ skipFlash = true;
1053
+ clearTimeout(skipTimer);
1054
+ emit();
1055
+ skipTimer = setTimeout(() => {
1056
+ skipFlash = false;
1057
+ emit();
1058
+ }, 3e3);
1059
+ },
1060
+ "session-clock-inputs-flash"
1061
+ );
1062
+ return () => {
1063
+ clearTimeout(skipTimer);
1064
+ unsubStack();
1065
+ unsubSkip();
1066
+ memoryUnsubs.forEach((fn) => fn());
1067
+ memoryUnsubs = [];
1068
+ };
1069
+ }
1070
+ function readBlockRound(block) {
1071
+ if (!block) return void 0;
1072
+ const round = block.getMemoryByTag("round")[0]?.metrics[0];
1073
+ if (!round || typeof round.current !== "number") return void 0;
1074
+ const display = block.getMemoryByTag("display")[0]?.metrics[0]?.value;
1075
+ const label = display?.roundDisplay ?? (round.total !== void 0 ? `Round ${round.current} of ${round.total}` : `Round ${round.current}`);
1076
+ return { current: round.current, total: round.total, label };
1077
+ }
1078
+ function readNextPreviewText(blocks) {
1079
+ for (const block of blocks) {
1080
+ const nextLocs = block.getMemoryByTag("metric:next");
1081
+ if (nextLocs.length === 0) continue;
1082
+ const merged = wodWikiCore.MetricContainer.empty(block.key.toString());
1083
+ for (const loc of nextLocs) merged.merge(loc.metrics);
1084
+ if (merged.length > 0) {
1085
+ return metricPresentation.presentGroup([...merged], "timer-subtitle").filter((t) => t.visible).map((t) => t.label).filter(Boolean).join(" ").trim() || null;
1086
+ }
1087
+ }
1088
+ return null;
1089
+ }
1090
+ function extractRepTargets(blocks) {
1091
+ const targets = [];
1092
+ for (const block of blocks) {
1093
+ const blockType = block.blockType ?? "";
1094
+ if (EXCLUDED_REP_BLOCK_TYPES[blockType]) {
1095
+ continue;
1096
+ }
1097
+ if (block.getMemoryByTag("children:status").length > 0) continue;
1098
+ const displayLocs = block.getMemoryByTag("metric:display");
1099
+ const resultLocs = block.getMemoryByTag("metric:result");
1100
+ const blockKey = block.key.toString();
1101
+ const grouped = displayLocs.length > 1;
1102
+ for (let idx = 0; idx < displayLocs.length; idx++) {
1103
+ const loc = displayLocs[idx];
1104
+ let plannedTarget = null;
1105
+ let movementText;
1106
+ for (const m of loc.metrics) {
1107
+ if (m.type === wodWikiCore.MetricType.Rep && m.origin !== "user" && typeof m.value === "number") {
1108
+ plannedTarget = m.value;
1109
+ }
1110
+ if ((m.type === wodWikiCore.MetricType.Effort || m.type === wodWikiCore.MetricType.Action) && typeof m.value === "string" && m.value) {
1111
+ movementText ??= m.value;
1112
+ }
1113
+ }
1114
+ const hasMovementIdentity = plannedTarget !== null || loc.metrics.some(
1115
+ (m) => (m.type === wodWikiCore.MetricType.Effort || m.type === wodWikiCore.MetricType.Action) && (typeof m.value === "string" || typeof m.image === "string")
1116
+ );
1117
+ if (!hasMovementIdentity) continue;
1118
+ let actual = null;
1119
+ if (resultLocs.length > 0) {
1120
+ const resLoc = resultLocs[Math.min(idx, resultLocs.length - 1)];
1121
+ if (resLoc) {
1122
+ const userHits = [];
1123
+ for (const m of resLoc.metrics) {
1124
+ if (m.origin === "user" && m.type === wodWikiCore.MetricType.Rep && typeof m.value === "number") {
1125
+ userHits.push(m);
1126
+ }
1127
+ }
1128
+ const last = userHits[userHits.length - 1];
1129
+ if (last) actual = last.value;
1130
+ }
1131
+ }
1132
+ const sourceId = block.sourceIds[idx] ?? idx;
1133
+ targets.push({
1134
+ occurrenceId: grouped ? `${blockKey}:${sourceId}` : blockKey,
1135
+ blockKey,
1136
+ ...grouped ? { sourceId } : {},
1137
+ label: grouped && movementText ? movementText : block.label,
1138
+ target: plannedTarget,
1139
+ actual
1140
+ });
1141
+ }
1142
+ }
1143
+ return targets;
1144
+ }
1145
+ function projectSessionClock(runtime, options = {}) {
1146
+ const status = options.executionStatus ?? "idle";
1147
+ const isPaused = status === "paused";
1148
+ const skipFlash = options.skipFlash ?? false;
1149
+ const skipFlashKey = options.skipFlashKey ?? 0;
1150
+ if (!runtime) {
1151
+ return {
1152
+ mainLabel: "Timer",
1153
+ displayMs: 0,
1154
+ direction: "up",
1155
+ activeSpans: [],
1156
+ basePolarity: "work",
1157
+ required: false,
1158
+ sessionElapsedMs: 0,
1159
+ sessionSpans: [],
1160
+ polarity: isPaused ? "paused" : "work",
1161
+ isRequiredLockActive: false,
1162
+ secondaryTimers: [],
1163
+ upNext: null,
1164
+ repTargets: [],
1165
+ isRunning: status === "running",
1166
+ isPaused,
1167
+ isNextDisabled: isPaused || options.canNextOverride === false,
1168
+ skipFlash,
1169
+ skipFlashKey
1170
+ };
1171
+ }
1172
+ const nowMs = options.nowMs ?? runtime.nowProvider.nowMs();
1173
+ const blocks = runtime.stack.blocks;
1174
+ const orderedRootToLeaf = [...blocks].reverse();
1175
+ const displayEntries = [];
1176
+ orderedRootToLeaf.forEach((block, index) => {
1177
+ if (block.blockType === "Root" && !block.label) return;
1178
+ const displayRows = block.getMemoryByTag("metric:display").map((loc) => loc.metrics);
1179
+ if (displayRows.length === 0 && !block.label) return;
1180
+ displayEntries.push({
1181
+ block,
1182
+ displayRows,
1183
+ label: block.label,
1184
+ isLeaf: index === orderedRootToLeaf.length - 1
1185
+ });
1186
+ });
1187
+ const leafEntry = displayEntries.find((e) => e.isLeaf);
1188
+ const roundsEntry = displayEntries.find((e) => e.block.blockType === "Rounds") ?? displayEntries.find((e) => e.block.getMemoryByTag("round").length > 0 && e.block.blockType !== "SessionRoot");
1189
+ const roundInfo = readBlockRound(roundsEntry?.block);
1190
+ const roundsLabel = roundInfo?.label ?? roundsEntry?.label;
1191
+ const allTimers = [];
1192
+ for (const block of blocks) {
1193
+ const timer = block.getMemoryByTag("time")[0]?.metrics[0]?.value;
1194
+ if (!timer) continue;
1195
+ allTimers.push({
1196
+ block,
1197
+ timer,
1198
+ isPinned: timer.role === "primary"
1199
+ });
1200
+ }
1201
+ const isAnyTimerRunning = allTimers.some(
1202
+ (t) => t.timer.spans.some((s) => s.ended === void 0)
1203
+ );
1204
+ const topTimer = allTimers[0];
1205
+ const primaryTimer = topTimer && (topTimer.block.blockType === "Rest" || topTimer.timer.polarity === "rest") ? topTimer : [...allTimers].reverse().find((t) => t.isPinned) ?? topTimer;
1206
+ const leafTimer = leafEntry ? allTimers.find((t) => t.block.key.toString() === leafEntry.block.key.toString()) : void 0;
1207
+ const isRestHero = primaryTimer?.block.blockType === "Rest" || primaryTimer?.timer.polarity === "rest";
1208
+ const active = isRestHero || primaryTimer?.isPinned ? primaryTimer : leafTimer ?? primaryTimer;
1209
+ const leafLabel = leafEntry?.label;
1210
+ const mainLabel = (isRestHero ? primaryTimer?.block.label || primaryTimer?.timer.label : primaryTimer?.isPinned ? roundsLabel || primaryTimer.timer.label : roundsLabel && roundsLabel !== leafLabel ? roundsLabel : leafLabel || primaryTimer?.timer.label) || "Timer";
1211
+ const subLabel = isRestHero && roundsLabel && roundsLabel !== mainLabel ? roundsLabel : mainLabel === leafLabel ? void 0 : leafLabel;
1212
+ let subLabels;
1213
+ if (!isRestHero && leafEntry && leafEntry.displayRows.length > 1) {
1214
+ const lines = leafEntry.displayRows.map(
1215
+ (row) => metricPresentation.presentGroup([...row], "timer-subtitle").filter((t) => t.visible).map((t) => t.label).filter(Boolean).join(" ").trim()
1216
+ ).filter(Boolean);
1217
+ if (lines.length > 0) subLabels = lines;
1218
+ }
1219
+ if (!subLabels) subLabels = subLabel ? [subLabel] : void 0;
1220
+ const activeDirection = active?.timer.direction ?? "up";
1221
+ const activeDurationMs = active?.timer.durationMs;
1222
+ const activeSpans = active ? serializeSpans(active.timer.spans) : [];
1223
+ let displayMs = 0;
1224
+ if (active) {
1225
+ const elapsed = calculateDuration(active.timer.spans, nowMs);
1226
+ displayMs = activeDirection === "down" && activeDurationMs !== void 0 ? Math.max(0, activeDurationMs - elapsed) : elapsed;
1227
+ }
1228
+ const withElapsed = allTimers.map((entry) => ({
1229
+ entry,
1230
+ elapsed: calculateDuration(entry.timer.spans, nowMs)
1231
+ }));
1232
+ const sessionHolder = withElapsed.find((e) => e.entry.block.blockType === "SessionRoot") ?? withElapsed.reduce(
1233
+ (best, cur) => cur.elapsed > (best?.elapsed ?? -1) ? cur : best,
1234
+ withElapsed[withElapsed.length - 1]
1235
+ );
1236
+ const sessionElapsedMs = sessionHolder?.elapsed ?? 0;
1237
+ const sessionSpans = sessionHolder ? serializeSpans(sessionHolder.entry.timer.spans) : [];
1238
+ const activeKey = active?.block.key.toString();
1239
+ const sessionKey = sessionHolder?.entry.block.key.toString();
1240
+ const secondaryTimers = allTimers.filter((t) => {
1241
+ if (t.timer.role === "hidden") return false;
1242
+ const key = t.block.key.toString();
1243
+ return key !== activeKey && key !== sessionKey;
1244
+ }).map((t) => {
1245
+ const elapsed = calculateDuration(t.timer.spans, nowMs);
1246
+ return {
1247
+ id: t.block.key.toString(),
1248
+ label: t.timer.label || t.block.label || "Timer",
1249
+ displayMs: t.timer.direction === "down" && t.timer.durationMs !== void 0 ? Math.max(0, t.timer.durationMs - elapsed) : elapsed,
1250
+ direction: t.timer.direction,
1251
+ durationMs: t.timer.durationMs,
1252
+ spans: serializeSpans(t.timer.spans)
1253
+ };
1254
+ });
1255
+ const basePolarity = active?.block.blockType === "Rest" || active?.timer.polarity === "rest" ? "rest" : "work";
1256
+ const required = Boolean(active?.timer.required);
1257
+ const polarity = resolveVisualPolarity({
1258
+ isPaused,
1259
+ basePolarity,
1260
+ direction: activeDirection,
1261
+ durationMs: activeDurationMs,
1262
+ displayMs
1263
+ });
1264
+ const isRequiredLockActive = isRequiredCountdownLocked({
1265
+ isPaused,
1266
+ required,
1267
+ direction: activeDirection,
1268
+ durationMs: activeDurationMs,
1269
+ displayMs
1270
+ });
1271
+ return {
1272
+ mainLabel,
1273
+ subLabels,
1274
+ displayMs,
1275
+ direction: activeDirection,
1276
+ durationMs: activeDurationMs,
1277
+ activeSpans,
1278
+ basePolarity,
1279
+ required,
1280
+ sessionElapsedMs,
1281
+ sessionSpans,
1282
+ polarity,
1283
+ isRequiredLockActive,
1284
+ roundCurrent: roundInfo?.current,
1285
+ roundTotal: roundInfo?.total,
1286
+ roundLabel: roundInfo?.label,
1287
+ secondaryTimers,
1288
+ upNext: readNextPreviewText(blocks),
1289
+ repTargets: extractRepTargets(blocks),
1290
+ isRunning: isAnyTimerRunning || status === "running",
1291
+ isPaused,
1292
+ isNextDisabled: isPaused || options.canNextOverride === false,
1293
+ skipFlash,
1294
+ skipFlashKey
1295
+ };
1296
+ }
1297
+
1298
+ // src/react/hooks/useSessionClockProjection.ts
1299
+ function useSessionClockProjection(options = {}) {
1300
+ const contextRuntime = useOptionalScriptRuntime();
1301
+ const runtime = options.runtime !== void 0 ? options.runtime : contextRuntime;
1302
+ const enabled = options.active ?? true;
1303
+ const [signalState, setSignalState] = react.useState({
1304
+ revision: 0,
1305
+ skipFlash: false,
1306
+ skipFlashKey: 0
1307
+ });
1308
+ react.useEffect(() => {
1309
+ if (!runtime || !enabled) return void 0;
1310
+ return observeSessionClockInputs(runtime, ({ skipFlash, skipFlashKey }) => {
1311
+ setSignalState((prev) => ({
1312
+ revision: prev.revision + 1,
1313
+ skipFlash,
1314
+ skipFlashKey
1315
+ }));
1316
+ });
1317
+ }, [runtime, enabled]);
1318
+ const [nowMs, setNowMs] = react.useState(() => getRuntimeNowMs());
1319
+ const structuralFrame = react.useMemo(() => {
1320
+ void signalState.revision;
1321
+ return projectSessionClock(runtime, {
1322
+ nowMs,
1323
+ executionStatus: options.executionStatus,
1324
+ canNextOverride: options.canNextOverride,
1325
+ skipFlash: signalState.skipFlash,
1326
+ skipFlashKey: signalState.skipFlashKey
1327
+ });
1328
+ }, [
1329
+ runtime,
1330
+ signalState.revision,
1331
+ signalState.skipFlash,
1332
+ signalState.skipFlashKey,
1333
+ nowMs,
1334
+ options.executionStatus,
1335
+ options.canNextOverride
1336
+ ]);
1337
+ react.useEffect(() => {
1338
+ if (!enabled || !structuralFrame.isRunning || structuralFrame.isPaused) return void 0;
1339
+ if (typeof requestAnimationFrame !== "function") return void 0;
1340
+ let frameId = 0;
1341
+ let mounted = true;
1342
+ const tick = () => {
1343
+ if (!mounted) return;
1344
+ setNowMs(getRuntimeNowMs());
1345
+ frameId = requestAnimationFrame(tick);
1346
+ };
1347
+ frameId = requestAnimationFrame(tick);
1348
+ return () => {
1349
+ mounted = false;
1350
+ cancelAnimationFrame(frameId);
1351
+ };
1352
+ }, [enabled, structuralFrame.isRunning, structuralFrame.isPaused]);
1353
+ return structuralFrame;
1354
+ }
1355
+ var NON_LABEL_SEGMENT_METRIC_TYPES = {
1356
+ [wodWikiCore.MetricType.Elapsed]: true,
1357
+ [wodWikiCore.MetricType.Total]: true,
1358
+ [wodWikiCore.MetricType.Spans]: true,
1359
+ [wodWikiCore.MetricType.SystemTime]: true,
1360
+ [wodWikiCore.MetricType.CurrentRound]: true,
1361
+ [wodWikiCore.MetricType.System]: true
1362
+ };
1363
+ function projectionsToUniqueSummaries(projections) {
1364
+ const byName = /* @__PURE__ */ new Map();
1365
+ for (const proj of projections) {
1366
+ byName.set(proj.name, {
1367
+ key: proj.name,
1368
+ label: computeColumnLabel(proj.name),
1369
+ value: proj.value,
1370
+ unit: proj.unit,
1371
+ metricType: proj.metricType ?? wodWikiCore.MetricType.Metric,
1372
+ origin: proj.origin
1373
+ });
1374
+ }
1375
+ return [...byName.values()];
1376
+ }
1377
+ function fallbackSummariesFromOutputs(outputs) {
1378
+ const byName = /* @__PURE__ */ new Map();
1379
+ for (const output of outputs) {
1380
+ const metrics = output.metrics;
1381
+ for (let j = 0; j + 1 < metrics.length; j += 2) {
1382
+ const labelMetric = metrics[j];
1383
+ const valueMetric = metrics[j + 1];
1384
+ if (!labelMetric || !valueMetric || typeof valueMetric.value !== "number") continue;
1385
+ const name = labelMetric.image ?? String(labelMetric.value);
1386
+ byName.set(name, {
1387
+ key: name,
1388
+ label: computeColumnLabel(name),
1389
+ value: valueMetric.value,
1390
+ unit: valueMetric.unit ?? "",
1391
+ metricType: valueMetric.type || wodWikiCore.MetricType.Metric,
1392
+ origin: valueMetric.origin
1393
+ });
1394
+ }
1395
+ }
1396
+ return [...byName.values()];
1397
+ }
1398
+ function formatSplitDeltaLabel(deltaMs) {
1399
+ const deltaSec = Math.round(deltaMs / 1e3);
1400
+ if (deltaSec === 0) return "even";
1401
+ return deltaSec > 0 ? `+${deltaSec}s` : `${deltaSec}s`;
1402
+ }
1403
+ function readRoundFromOutput(output) {
1404
+ const metric = output.getMetric(wodWikiCore.MetricType.CurrentRound);
1405
+ if (!metric) return {};
1406
+ const round = typeof metric.value === "number" ? metric.value : void 0;
1407
+ let totalRounds;
1408
+ if ("total" in metric && typeof metric.total === "number") {
1409
+ totalRounds = metric.total;
1410
+ }
1411
+ return { round, totalRounds };
1412
+ }
1413
+ function deriveRoundSplits(outputs) {
1414
+ const previousElapsedByKey = /* @__PURE__ */ new Map();
1415
+ const rows = [];
1416
+ for (let idx = 0; idx < outputs.length; idx++) {
1417
+ const out = outputs[idx];
1418
+ if (out.outputType !== "segment") continue;
1419
+ if (out.sourceBlockKey.startsWith("session-root")) continue;
1420
+ if (out.completionReason === "rounds-complete") continue;
1421
+ if (out.sourceStatementId === void 0 && !out.sourceBlockKey.startsWith("rest")) continue;
1422
+ const elapsedVal = out.getMetric(wodWikiCore.MetricType.Elapsed)?.value;
1423
+ const fallbackSpanElapsed = out.timeSpan.ended !== void 0 ? Math.max(0, out.timeSpan.ended - out.timeSpan.started) : 0;
1424
+ const elapsedMs = typeof elapsedVal === "number" ? elapsedVal : fallbackSpanElapsed;
1425
+ if (!Number.isFinite(elapsedMs)) continue;
1426
+ const displayTokens = metricPresentation.presentGroup(
1427
+ out.metrics.filter((m) => !NON_LABEL_SEGMENT_METRIC_TYPES[m.type]),
1428
+ "timer-subtitle"
1429
+ ).filter((t) => t.visible).map((t) => t.label).filter(Boolean).join(" ").trim();
1430
+ const label = displayTokens || out.text?.trim() || (out.sourceBlockKey.startsWith("rest") ? "Rest" : "Segment");
1431
+ const comparisonKey = out.sourceStatementId !== void 0 ? `stmt:${out.sourceStatementId}` : `key:${label.toLowerCase()}`;
1432
+ const prevElapsed = previousElapsedByKey.get(comparisonKey);
1433
+ const deltaMs = prevElapsed !== void 0 ? elapsedMs - prevElapsed : void 0;
1434
+ previousElapsedByKey.set(comparisonKey, elapsedMs);
1435
+ const { round, totalRounds } = readRoundFromOutput(out);
1436
+ rows.push({
1437
+ id: `${out.sourceBlockKey}:${idx}`,
1438
+ comparisonKey,
1439
+ label,
1440
+ elapsedMs,
1441
+ ...round !== void 0 ? { round } : {},
1442
+ ...totalRounds !== void 0 ? { totalRounds } : {},
1443
+ ...deltaMs !== void 0 ? { deltaMs, deltaLabel: formatSplitDeltaLabel(deltaMs) } : {}
1444
+ });
1445
+ }
1446
+ return rows;
1447
+ }
1448
+ function projectLiveSessionTelemetry(runtime) {
1449
+ if (!runtime) {
1450
+ return { summaries: [], splits: [] };
1451
+ }
1452
+ const typedProjections = runtime.getLiveProjections?.();
1453
+ const summaries = typedProjections && typedProjections.length > 0 ? projectionsToUniqueSummaries(typedProjections) : fallbackSummariesFromOutputs(runtime.getLiveAnalytics?.() ?? []);
1454
+ const splits = deriveRoundSplits(runtime.getOutputStatements());
1455
+ return { summaries, splits };
1456
+ }
1457
+
1458
+ // src/react/hooks/useLiveSessionTelemetry.ts
1459
+ function useLiveSessionTelemetry(runtimeOverride) {
1460
+ const contextRuntime = useOptionalScriptRuntime();
1461
+ const runtime = runtimeOverride !== void 0 ? runtimeOverride : contextRuntime;
1462
+ const [version, setVersion] = react.useState(0);
1463
+ react.useEffect(() => {
1464
+ if (!runtime) {
1465
+ setVersion(0);
1466
+ return void 0;
1467
+ }
1468
+ return runtime.subscribeToOutput?.(() => {
1469
+ setVersion((v) => v + 1);
1470
+ });
1471
+ }, [runtime]);
1472
+ return react.useMemo(() => {
1473
+ return projectLiveSessionTelemetry(runtime);
1474
+ }, [runtime, version]);
1475
+ }
1476
+ function formatStatementLabel(statement) {
1477
+ const presented = metricPresentation.presentGroup(
1478
+ [...statement.metrics].filter((m) => m.type !== wodWikiCore.MetricType.Hint),
1479
+ "timer-subtitle"
1480
+ ).filter((t) => t.visible).map((t) => t.label).filter(Boolean).join(" ").trim();
1481
+ return presented || statement.text?.trim() || "Step";
1482
+ }
1483
+ function projectScriptOutline(runtime) {
1484
+ const statements = runtime?.script?.statements;
1485
+ if (!runtime || !statements || statements.length === 0) return [];
1486
+ const activeIds = /* @__PURE__ */ new Set();
1487
+ for (const block of runtime.stack.blocks) {
1488
+ if (block.blockType === "SessionRoot" || block.blockType === "WaitingToStart") continue;
1489
+ for (const id of block.sourceIds) {
1490
+ if (typeof id === "number") activeIds.add(id);
1491
+ }
1492
+ }
1493
+ const completedIds = /* @__PURE__ */ new Set();
1494
+ for (const out of runtime.getOutputStatements()) {
1495
+ if (out.outputType === "segment" && typeof out.sourceStatementId === "number") {
1496
+ completedIds.add(out.sourceStatementId);
1497
+ }
1498
+ }
1499
+ const depthOf = (stmt) => {
1500
+ let depth = 0;
1501
+ let cur = stmt.parent;
1502
+ const seen = /* @__PURE__ */ new Set();
1503
+ while (cur !== void 0 && !seen.has(cur)) {
1504
+ seen.add(cur);
1505
+ const parentStmt = runtime.script.getId(cur);
1506
+ if (!parentStmt) break;
1507
+ depth += 1;
1508
+ cur = parentStmt.parent;
1509
+ }
1510
+ return depth;
1511
+ };
1512
+ const nodes = [];
1513
+ for (const stmt of statements) {
1514
+ if (typeof stmt.id !== "number") continue;
1515
+ const label = formatStatementLabel(stmt);
1516
+ const status = activeIds.has(stmt.id) ? "active" : completedIds.has(stmt.id) ? "completed" : "upcoming";
1517
+ nodes.push({
1518
+ statementId: stmt.id,
1519
+ depth: depthOf(stmt),
1520
+ label,
1521
+ status
1522
+ });
1523
+ }
1524
+ return nodes;
1525
+ }
1526
+
1527
+ // src/react/hooks/useScriptOutline.ts
1528
+ function useScriptOutline(runtimeOverride) {
1529
+ const contextRuntime = useOptionalScriptRuntime();
1530
+ const runtime = runtimeOverride !== void 0 ? runtimeOverride : contextRuntime;
1531
+ const [tick, setTick] = react.useState(0);
1532
+ react.useEffect(() => {
1533
+ if (!runtime) return void 0;
1534
+ const unsubStack = runtime.subscribeToStack(() => setTick((t) => t + 1));
1535
+ const unsubOut = runtime.subscribeToOutput?.(() => setTick((t) => t + 1));
1536
+ return () => {
1537
+ unsubStack();
1538
+ unsubOut?.();
1539
+ };
1540
+ }, [runtime]);
1541
+ return react.useMemo(() => {
1542
+ return projectScriptOutline(runtime);
1543
+ }, [runtime, tick]);
1544
+ }
778
1545
  function cn(...classes) {
779
1546
  return classes.filter(Boolean).join(" ");
780
1547
  }
@@ -821,8 +1588,10 @@ exports.useBlockOutputs = useBlockOutputs;
821
1588
  exports.useDisplayState = useDisplayState;
822
1589
  exports.useFragmentSource = useFragmentSource;
823
1590
  exports.useLiveAnalytics = useLiveAnalytics;
1591
+ exports.useLiveSessionTelemetry = useLiveSessionTelemetry;
824
1592
  exports.useMemorySubscription = useMemorySubscription;
825
1593
  exports.useNextPreview = useNextPreview;
1594
+ exports.useOptionalScriptRuntime = useOptionalScriptRuntime;
826
1595
  exports.useOutputHierarchy = useOutputHierarchy;
827
1596
  exports.useOutputStatement = useOutputStatement;
828
1597
  exports.useOutputStatements = useOutputStatements;
@@ -830,8 +1599,10 @@ exports.usePrimaryTimer = usePrimaryTimer;
830
1599
  exports.useRoundDisplay = useRoundDisplay;
831
1600
  exports.useRoundState = useRoundState;
832
1601
  exports.useRuntimeExecution = useRuntimeExecution;
1602
+ exports.useScriptOutline = useScriptOutline;
833
1603
  exports.useScriptRuntime = useScriptRuntime;
834
1604
  exports.useSecondaryTimers = useSecondaryTimers;
1605
+ exports.useSessionClockProjection = useSessionClockProjection;
835
1606
  exports.useSnapshotBlocks = useSnapshotBlocks;
836
1607
  exports.useSnapshotCurrentBlock = useSnapshotCurrentBlock;
837
1608
  exports.useStackDisplayRows = useStackDisplayRows;