foldkit 0.32.0 → 0.33.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.
@@ -0,0 +1,678 @@
1
+ import { clsx } from 'clsx';
2
+ import { Array as Array_, Effect, HashSet, Match as M, Number as Number_, Option, Predicate, Record, Schema as S, Stream, String as String_, SubscriptionRef, pipe, } from 'effect';
3
+ import { OptionExt } from '../effectExtensions';
4
+ import { html } from '../html';
5
+ import { m } from '../message';
6
+ import { makeElement } from '../runtime/runtime';
7
+ import { makeSubscriptions } from '../runtime/subscription';
8
+ import { evo } from '../struct';
9
+ import { lockScroll, unlockScroll } from '../task/scrollLock';
10
+ import * as Tabs from '../ui/tabs';
11
+ import { overlayStyles } from './overlay-styles';
12
+ import { INIT_INDEX } from './store';
13
+ // MODEL
14
+ const DisplayEntry = S.Struct({
15
+ tag: S.String,
16
+ commandCount: S.Number,
17
+ timestamp: S.Number,
18
+ isModelChanged: S.Boolean,
19
+ });
20
+ const INSPECTOR_TABS_ID = 'dt-inspector';
21
+ const InspectorTabsModel = S.Struct({
22
+ id: S.String,
23
+ activeIndex: S.Number,
24
+ focusedIndex: S.Number,
25
+ activationMode: S.Literal('Automatic', 'Manual'),
26
+ });
27
+ const Model = S.Struct({
28
+ isOpen: S.Boolean,
29
+ isMobile: S.Boolean,
30
+ entries: S.Array(DisplayEntry),
31
+ startIndex: S.Number,
32
+ isPaused: S.Boolean,
33
+ pausedAtIndex: S.Number,
34
+ maybeSelectedIndex: S.OptionFromSelf(S.Number),
35
+ maybeInspectedModel: S.OptionFromSelf(S.Unknown),
36
+ maybeInspectedMessage: S.OptionFromSelf(S.Unknown),
37
+ expandedPaths: S.HashSetFromSelf(S.String),
38
+ changedPaths: S.HashSetFromSelf(S.String),
39
+ affectedPaths: S.HashSetFromSelf(S.String),
40
+ inspectorTabs: InspectorTabsModel,
41
+ });
42
+ const Flags = S.Struct({
43
+ isMobile: S.Boolean,
44
+ entries: S.Array(DisplayEntry),
45
+ startIndex: S.Number,
46
+ isPaused: S.Boolean,
47
+ pausedAtIndex: S.Number,
48
+ });
49
+ // MESSAGE
50
+ const ClickedToggle = m('ClickedToggle');
51
+ const ClickedRow = m('ClickedRow', { index: S.Number });
52
+ const ClickedResume = m('ClickedResume');
53
+ const ClickedClear = m('ClickedClear');
54
+ const CompletedJump = m('CompletedJump');
55
+ const CompletedResume = m('CompletedResume');
56
+ const ClickedFollowLatest = m('ClickedFollowLatest');
57
+ const CompletedClear = m('CompletedClear');
58
+ const LockedScroll = m('LockedScroll');
59
+ const UnlockedScroll = m('UnlockedScroll');
60
+ const ScrolledToTop = m('ScrolledToTop');
61
+ const CrossedMobileBreakpoint = m('CrossedMobileBreakpoint', {
62
+ isMobile: S.Boolean,
63
+ });
64
+ const ReceivedInspectedState = m('ReceivedInspectedState', {
65
+ model: S.Unknown,
66
+ maybeMessage: S.OptionFromSelf(S.Unknown),
67
+ changedPaths: S.HashSetFromSelf(S.String),
68
+ affectedPaths: S.HashSetFromSelf(S.String),
69
+ });
70
+ const ToggledTreeNode = m('ToggledTreeNode', { path: S.String });
71
+ const GotInspectorTabsMessage = m('GotInspectorTabsMessage', {
72
+ message: S.Unknown,
73
+ });
74
+ const ReceivedStoreUpdate = m('ReceivedStoreUpdate', {
75
+ entries: S.Array(DisplayEntry),
76
+ startIndex: S.Number,
77
+ isPaused: S.Boolean,
78
+ pausedAtIndex: S.Number,
79
+ });
80
+ const Message = S.Union(ClickedToggle, ClickedRow, ClickedResume, ClickedClear, ClickedFollowLatest, CompletedJump, CompletedResume, CompletedClear, LockedScroll, UnlockedScroll, ScrolledToTop, CrossedMobileBreakpoint, ReceivedInspectedState, ToggledTreeNode, GotInspectorTabsMessage, ReceivedStoreUpdate);
81
+ // HELPERS
82
+ const MILLIS_PER_SECOND = 1000;
83
+ const MOBILE_BREAKPOINT = 767;
84
+ const MOBILE_BREAKPOINT_QUERY = `(max-width: ${MOBILE_BREAKPOINT}px)`;
85
+ const TREE_INDENT_PX = 12;
86
+ const MAX_PREVIEW_KEYS = 3;
87
+ const formatTimeDelta = (deltaMs) => M.value(deltaMs).pipe(M.when(0, () => '0ms'), M.when(Number_.lessThan(MILLIS_PER_SECOND), ms => `+${Math.round(ms)}ms`), M.orElse(ms => `+${(ms / MILLIS_PER_SECOND).toFixed(1)}s`));
88
+ const MESSAGE_LIST_SELECTOR = '.message-list';
89
+ const toDisplayEntries = ({ entries }) => Array_.map(entries, ({ tag, commandCount, timestamp, isModelChanged }) => ({
90
+ tag,
91
+ commandCount,
92
+ timestamp,
93
+ isModelChanged,
94
+ }));
95
+ const toDisplayState = (state) => ({
96
+ entries: toDisplayEntries(state),
97
+ startIndex: state.startIndex,
98
+ isPaused: state.isPaused,
99
+ pausedAtIndex: state.pausedAtIndex,
100
+ });
101
+ const isExpandable = (value) => Predicate.isNotNull(value) && typeof value === 'object';
102
+ const Tagged = S.Struct({ _tag: S.String });
103
+ const isTagged = S.is(Tagged);
104
+ const objectPreview = (value) => pipe(value, Record.keys, Array_.filter(key => key !== '_tag'), Array_.match({
105
+ onEmpty: () => '{}',
106
+ onNonEmpty: keys => {
107
+ const preview = pipe(keys, Array_.take(MAX_PREVIEW_KEYS), Array_.join(', '));
108
+ return Array_.length(keys) > MAX_PREVIEW_KEYS
109
+ ? `{ ${preview}, … }`
110
+ : `{ ${preview} }`;
111
+ },
112
+ }));
113
+ const collapsedPreview = (value) => M.value(value).pipe(M.when(Array.isArray, array => `(${array.length})`), M.when(Predicate.isReadonlyRecord, objectPreview), M.orElse(() => ''));
114
+ const emptyDiff = {
115
+ changedPaths: HashSet.empty(),
116
+ affectedPaths: HashSet.empty(),
117
+ };
118
+ const computeDiff = (previous, current) => {
119
+ const changed = new Set();
120
+ const walk = (prev, curr, path) => {
121
+ if (prev === curr) {
122
+ return;
123
+ }
124
+ if (!isExpandable(curr) || !isExpandable(prev)) {
125
+ changed.add(path);
126
+ return;
127
+ }
128
+ if (Array.isArray(curr) && Array.isArray(prev)) {
129
+ walkArray(prev, curr, path);
130
+ }
131
+ else if (Predicate.isReadonlyRecord(curr) &&
132
+ Predicate.isReadonlyRecord(prev)) {
133
+ walkObject(prev, curr, path);
134
+ }
135
+ else {
136
+ changed.add(path);
137
+ }
138
+ };
139
+ const walkObject = (prev, curr, path) => {
140
+ pipe(curr, Record.keys, Array_.forEach(key => {
141
+ const childPath = `${path}.${key}`;
142
+ if (Record.has(prev, key)) {
143
+ walk(prev[key], curr[key], childPath);
144
+ }
145
+ else {
146
+ changed.add(childPath);
147
+ }
148
+ }));
149
+ };
150
+ const walkArray = (prev, curr, path) => {
151
+ const prevRefToIndex = new Map(prev.map((item, index) => [item, index]));
152
+ curr.forEach((item, index) => {
153
+ const childPath = `${path}.${index}`;
154
+ const prevIndex = prevRefToIndex.get(item);
155
+ if (Predicate.isUndefined(prevIndex) || prevIndex !== index) {
156
+ changed.add(childPath);
157
+ }
158
+ });
159
+ };
160
+ walk(previous, current, 'root');
161
+ const affected = new Set(changed);
162
+ const addAncestors = (path) => {
163
+ pipe(path, String_.lastIndexOf('.'), Option.map(lastDot => path.substring(0, lastDot)), Option.filter(parent => !affected.has(parent)), Option.map(parent => {
164
+ affected.add(parent);
165
+ addAncestors(parent);
166
+ }));
167
+ };
168
+ changed.forEach(addAncestors);
169
+ return {
170
+ changedPaths: HashSet.fromIterable(changed),
171
+ affectedPaths: HashSet.fromIterable(affected),
172
+ };
173
+ };
174
+ // UPDATE
175
+ const makeUpdate = (store, shadow, mode) => {
176
+ const jumpTo = (index) => Effect.gen(function* () {
177
+ yield* store.jumpTo(index);
178
+ return CompletedJump();
179
+ });
180
+ const inspectState = (index) => Effect.gen(function* () {
181
+ const model = yield* store.getModelAtIndex(index);
182
+ const maybeMessage = yield* store.getMessageAtIndex(index);
183
+ const diff = index === INIT_INDEX
184
+ ? emptyDiff
185
+ : yield* pipe(store.getModelAtIndex(index - 1), Effect.map(previousModel => computeDiff(previousModel, model)), Effect.catchAll(() => Effect.succeed(emptyDiff)));
186
+ return ReceivedInspectedState({ model, maybeMessage, ...diff });
187
+ });
188
+ const inspectLatest = Effect.gen(function* () {
189
+ const state = yield* SubscriptionRef.get(store.stateRef);
190
+ const latestIndex = Array_.isEmptyReadonlyArray(state.entries)
191
+ ? INIT_INDEX
192
+ : state.startIndex + state.entries.length - 1;
193
+ return yield* inspectState(latestIndex);
194
+ });
195
+ const resume = Effect.gen(function* () {
196
+ yield* store.resume;
197
+ return CompletedResume();
198
+ });
199
+ const clear = Effect.gen(function* () {
200
+ yield* store.clear;
201
+ return CompletedClear();
202
+ });
203
+ const toggleScrollLock = (shouldLock) => shouldLock
204
+ ? lockScroll.pipe(Effect.as(LockedScroll()))
205
+ : unlockScroll.pipe(Effect.as(UnlockedScroll()));
206
+ const scrollToTop = Effect.sync(() => {
207
+ const messageList = shadow.querySelector(MESSAGE_LIST_SELECTOR);
208
+ if (messageList instanceof HTMLElement) {
209
+ messageList.scrollTop = 0;
210
+ }
211
+ return ScrolledToTop();
212
+ });
213
+ return (model, message) => M.value(message).pipe(M.withReturnType(), M.tags({
214
+ ClickedToggle: () => {
215
+ const nextIsOpen = !model.isOpen;
216
+ return [
217
+ evo(model, { isOpen: () => nextIsOpen }),
218
+ OptionExt.when(model.isMobile, toggleScrollLock(nextIsOpen)).pipe(Option.toArray),
219
+ ];
220
+ },
221
+ CrossedMobileBreakpoint: ({ isMobile }) => [
222
+ evo(model, { isMobile: () => isMobile }),
223
+ OptionExt.when(model.isOpen, toggleScrollLock(isMobile)).pipe(Option.toArray),
224
+ ],
225
+ ClickedRow: ({ index }) => M.value(mode).pipe(M.withReturnType(), M.when('TimeTravel', () => [
226
+ model,
227
+ [jumpTo(index), inspectState(index)],
228
+ ]), M.when('Inspect', () => [
229
+ evo(model, {
230
+ maybeSelectedIndex: () => Option.some(index),
231
+ }),
232
+ [inspectState(index)],
233
+ ]), M.exhaustive),
234
+ ClickedResume: () => [
235
+ evo(model, {
236
+ expandedPaths: () => HashSet.empty(),
237
+ changedPaths: () => HashSet.empty(),
238
+ affectedPaths: () => HashSet.empty(),
239
+ }),
240
+ [resume, inspectLatest],
241
+ ],
242
+ ClickedClear: () => [
243
+ evo(model, {
244
+ maybeSelectedIndex: () => Option.none(),
245
+ expandedPaths: () => HashSet.empty(),
246
+ changedPaths: () => HashSet.empty(),
247
+ affectedPaths: () => HashSet.empty(),
248
+ }),
249
+ [clear, inspectLatest],
250
+ ],
251
+ ClickedFollowLatest: () => [
252
+ evo(model, {
253
+ maybeSelectedIndex: () => Option.none(),
254
+ expandedPaths: () => HashSet.empty(),
255
+ changedPaths: () => HashSet.empty(),
256
+ affectedPaths: () => HashSet.empty(),
257
+ }),
258
+ [inspectLatest, scrollToTop],
259
+ ],
260
+ ReceivedInspectedState: ({ model: inspectedModel, maybeMessage, changedPaths, affectedPaths, }) => [
261
+ evo(model, {
262
+ maybeInspectedModel: () => Option.some(inspectedModel),
263
+ maybeInspectedMessage: () => maybeMessage,
264
+ changedPaths: () => changedPaths,
265
+ affectedPaths: () => affectedPaths,
266
+ }),
267
+ [],
268
+ ],
269
+ GotInspectorTabsMessage: ({ message: tabsMessage }) => {
270
+ const [nextTabsModel, tabsCommands] = Tabs.update(model.inspectorTabs,
271
+ /* eslint-disable-next-line @typescript-eslint/consistent-type-assertions */
272
+ tabsMessage);
273
+ return [
274
+ evo(model, {
275
+ inspectorTabs: () => nextTabsModel,
276
+ }),
277
+ tabsCommands.map(Effect.map(innerMessage => GotInspectorTabsMessage({ message: innerMessage }))),
278
+ ];
279
+ },
280
+ ToggledTreeNode: ({ path }) => [
281
+ evo(model, {
282
+ expandedPaths: paths => HashSet.toggle(paths, path),
283
+ }),
284
+ [],
285
+ ],
286
+ ReceivedStoreUpdate: ({ entries, startIndex, isPaused, pausedAtIndex, }) => {
287
+ const shouldFollowLatest = M.value(mode).pipe(M.when('TimeTravel', () => !isPaused), M.when('Inspect', () => Option.isNone(model.maybeSelectedIndex)), M.exhaustive);
288
+ return [
289
+ evo(model, {
290
+ entries: () => entries,
291
+ startIndex: () => startIndex,
292
+ isPaused: () => isPaused,
293
+ pausedAtIndex: () => pausedAtIndex,
294
+ }),
295
+ shouldFollowLatest ? [scrollToTop, inspectLatest] : [],
296
+ ];
297
+ },
298
+ }), M.tag('CompletedJump', 'CompletedResume', 'CompletedClear', 'LockedScroll', 'UnlockedScroll', 'ScrolledToTop', () => [model, []]), M.exhaustive);
299
+ };
300
+ // SUBSCRIPTION
301
+ const SubscriptionDeps = S.Struct({
302
+ storeUpdates: S.Null,
303
+ mobileBreakpoint: S.Null,
304
+ });
305
+ const makeOverlaySubscriptions = (store) => makeSubscriptions(SubscriptionDeps)({
306
+ storeUpdates: {
307
+ modelToDependencies: () => null,
308
+ depsToStream: () => Stream.concat(Stream.make(pipe(SubscriptionRef.get(store.stateRef), Effect.map(state => ReceivedStoreUpdate(toDisplayState(state))))), pipe(store.stateRef.changes, Stream.map(state => Effect.succeed(ReceivedStoreUpdate(toDisplayState(state)))))),
309
+ },
310
+ mobileBreakpoint: {
311
+ modelToDependencies: () => null,
312
+ depsToStream: () => Stream.async(emit => {
313
+ const mediaQuery = window.matchMedia(MOBILE_BREAKPOINT_QUERY);
314
+ const handler = (event) => {
315
+ emit.single(Effect.succeed(CrossedMobileBreakpoint({ isMobile: event.matches })));
316
+ };
317
+ mediaQuery.addEventListener('change', handler);
318
+ return Effect.sync(() => mediaQuery.removeEventListener('change', handler));
319
+ }),
320
+ },
321
+ });
322
+ // VIEW
323
+ const indexClass = 'text-2xs text-dt-muted font-mono min-w-5';
324
+ const headerButtonClass = 'dt-header-button bg-transparent border-none text-dt-muted cursor-pointer text-base font-mono transition-colors';
325
+ const ROW_BASE = 'dt-row flex items-center py-1 px-1 cursor-pointer gap-1.5 transition-colors border-l-3 border-b';
326
+ const BADGE_POSITION_CLASS = {
327
+ BottomRight: 'dt-pos-br',
328
+ BottomLeft: 'dt-pos-bl',
329
+ TopRight: 'dt-pos-tr',
330
+ TopLeft: 'dt-pos-tl',
331
+ };
332
+ const PANEL_POSITION_CLASS = {
333
+ BottomRight: 'dt-panel-br',
334
+ BottomLeft: 'dt-panel-bl',
335
+ TopRight: 'dt-panel-tr',
336
+ TopLeft: 'dt-panel-tl',
337
+ };
338
+ const makeView = (position, mode, maybeBanner) => {
339
+ const { div, header, span, ul, button, svg, path, keyed, Class, Style, OnClick, AriaHidden, Xmlns, Fill, ViewBox, StrokeWidth, Stroke, StrokeLinecap, StrokeLinejoin, D, empty, } = html();
340
+ // JSON TREE
341
+ const leafValueView = (value) => M.value(value).pipe(M.when(Predicate.isNull, () => span([Class('json-null italic')], ['null'])), M.when(Predicate.isUndefined, () => span([Class('json-null italic')], ['undefined'])), M.when(Predicate.isString, stringValue => span([Class('json-string')], [`"${stringValue}"`])), M.when(Predicate.isNumber, numberValue => span([Class('json-number')], [String(numberValue)])), M.when(Predicate.isBoolean, booleanValue => span([Class('json-boolean')], [String(booleanValue)])), M.orElse(unknownValue => span([Class('json-null')], [String(unknownValue)])));
342
+ const keyView = (key) => span([Class('json-key')], [`${key}:\u00a0`]);
343
+ const CHEVRON_RIGHT = 'M8.25 4.5l7.5 7.5-7.5 7.5';
344
+ const CHEVRON_DOWN = 'M19.5 8.25l-7.5 7.5-7.5-7.5';
345
+ const arrowView = (isExpanded) => svg([
346
+ AriaHidden(true),
347
+ Class('json-arrow shrink-0'),
348
+ Xmlns('http://www.w3.org/2000/svg'),
349
+ Fill('none'),
350
+ ViewBox('0 0 24 24'),
351
+ StrokeWidth('2'),
352
+ Stroke('currentColor'),
353
+ ], [
354
+ path([
355
+ StrokeLinecap('round'),
356
+ StrokeLinejoin('round'),
357
+ D(isExpanded ? CHEVRON_DOWN : CHEVRON_RIGHT),
358
+ ], []),
359
+ ]);
360
+ const tagLabelView = (tag) => span([Class('json-tag')], [tag]);
361
+ const diffDotView = span([Class('diff-dot')], []);
362
+ const inlineDiffDotView = span([Class('diff-dot-inline')], []);
363
+ const flattenTree = (value, treePath, expandedPaths, changedPaths, affectedPaths, depth, maybeKey, accumulator, indentRootChildren) => {
364
+ const isRoot = treePath === 'root';
365
+ const nodeIsExpandable = isExpandable(value);
366
+ const isExpanded = nodeIsExpandable && (isRoot || HashSet.has(expandedPaths, treePath));
367
+ const maybeTag = pipe(value, Option.liftPredicate(isTagged), Option.map(({ _tag }) => _tag));
368
+ accumulator.push({
369
+ value,
370
+ treePath,
371
+ depth,
372
+ maybeKey,
373
+ isExpandable: nodeIsExpandable,
374
+ isExpanded,
375
+ isChanged: HashSet.has(changedPaths, treePath),
376
+ isAffected: HashSet.has(affectedPaths, treePath),
377
+ maybeTag,
378
+ });
379
+ if (!isExpanded) {
380
+ return;
381
+ }
382
+ const childDepth = isRoot && !indentRootChildren ? depth : depth + 1;
383
+ if (Array.isArray(value)) {
384
+ value.forEach((item, arrayIndex) => flattenTree(item, `${treePath}.${arrayIndex}`, expandedPaths, changedPaths, affectedPaths, childDepth, Option.some(String(arrayIndex)), accumulator, indentRootChildren));
385
+ }
386
+ else if (Predicate.isReadonlyRecord(value)) {
387
+ pipe(value, Record.toEntries, Array_.filter(([key]) => key !== '_tag'), Array_.forEach(([key, childValue]) => flattenTree(childValue, `${treePath}.${key}`, expandedPaths, changedPaths, affectedPaths, childDepth, Option.some(key), accumulator, indentRootChildren)));
388
+ }
389
+ };
390
+ const flatNodeView = (node) => {
391
+ const indent = Style({ paddingLeft: `${node.depth * TREE_INDENT_PX}px` });
392
+ const hasDiffDot = node.isChanged || node.isAffected;
393
+ if (!node.isExpandable) {
394
+ return div([
395
+ Class(clsx('tree-row flex items-center gap-px font-mono text-2xs', node.isChanged && 'diff-changed')),
396
+ indent,
397
+ ], [
398
+ ...(hasDiffDot ? [diffDotView] : []),
399
+ ...Array_.getSomes([Option.map(node.maybeKey, keyView)]),
400
+ leafValueView(node.value),
401
+ ]);
402
+ }
403
+ const isRoot = node.treePath === 'root';
404
+ const preview = node.isExpanded
405
+ ? Array.isArray(node.value)
406
+ ? `(${node.value.length})`
407
+ : ''
408
+ : collapsedPreview(node.value);
409
+ return div([
410
+ Class(clsx('tree-row flex items-center gap-px font-mono text-2xs', !isRoot && 'tree-row-expandable cursor-pointer', node.isChanged && 'diff-changed')),
411
+ indent,
412
+ ...(isRoot ? [] : [OnClick(ToggledTreeNode({ path: node.treePath }))]),
413
+ ], [
414
+ ...(isRoot ? [] : [arrowView(node.isExpanded)]),
415
+ ...(!isRoot && hasDiffDot ? [diffDotView] : []),
416
+ ...Array_.getSomes([
417
+ Option.map(node.maybeKey, keyView),
418
+ Option.map(node.maybeTag, tagLabelView),
419
+ ]),
420
+ span([Class('json-preview')], [preview]),
421
+ ]);
422
+ };
423
+ const treeView = (value, rootPath, expandedPaths, changedPaths, affectedPaths, maybeRootLabel, indentRootChildren) => {
424
+ const nodes = [];
425
+ flattenTree(value, rootPath, expandedPaths, changedPaths, affectedPaths, 0, maybeRootLabel, nodes, indentRootChildren);
426
+ return div([
427
+ Class('inspector-tree flex-1 overflow-auto overscroll-contain min-h-0 min-w-0'),
428
+ ], nodes.map(flatNodeView));
429
+ };
430
+ const inspectedTimestamp = (model) => {
431
+ const lastIndex = Array_.isEmptyReadonlyArray(model.entries)
432
+ ? INIT_INDEX
433
+ : model.startIndex + model.entries.length - 1;
434
+ const selectedIndex = M.value(mode).pipe(M.when('TimeTravel', () => model.isPaused ? model.pausedAtIndex : lastIndex), M.when('Inspect', () => Option.getOrElse(model.maybeSelectedIndex, () => lastIndex)), M.exhaustive);
435
+ if (selectedIndex === INIT_INDEX) {
436
+ return '0ms';
437
+ }
438
+ const baseTimestamp = pipe(model.entries, Array_.head, Option.match({
439
+ onNone: () => 0,
440
+ onSome: ({ timestamp }) => timestamp,
441
+ }));
442
+ return pipe(Array_.get(model.entries, selectedIndex - model.startIndex), Option.map(entry => {
443
+ const delta = entry.timestamp - baseTimestamp;
444
+ const seconds = Math.floor(delta / MILLIS_PER_SECOND);
445
+ const remainingMs = delta % MILLIS_PER_SECOND;
446
+ return seconds > 0
447
+ ? `+${seconds}s ${remainingMs.toFixed(1)}ms`
448
+ : `+${remainingMs.toFixed(1)}ms`;
449
+ }), Option.getOrElse(() => ''));
450
+ };
451
+ const emptyInspectorView = div([
452
+ Class('flex-1 flex items-center justify-center text-dt-muted text-2xs font-mono min-w-0'),
453
+ ], ['Click a message to inspect']);
454
+ const INSPECTOR_TABS = ['Model', 'Message'];
455
+ const noMessageView = div([
456
+ Class('flex-1 flex items-center justify-center text-dt-muted text-2xs font-mono min-w-0'),
457
+ ], ['Init — no Message']);
458
+ const modelTabContent = (model, inspectedModel) => treeView(inspectedModel, 'root', model.expandedPaths, model.changedPaths, model.affectedPaths, Option.none(), true);
459
+ const messageTabContent = (model) => Option.match(model.maybeInspectedMessage, {
460
+ onNone: () => noMessageView,
461
+ onSome: message => div([Class('flex flex-col flex-1 min-h-0 min-w-0')], [
462
+ div([
463
+ Class('px-2 py-1 border-b text-2xs text-dt-muted font-mono shrink-0'),
464
+ ], [inspectedTimestamp(model)]),
465
+ div([Class('flex flex-col flex-1 min-h-0 min-w-0 pt-1 pl-1')], [
466
+ treeView(message, 'root', model.expandedPaths, HashSet.empty(), HashSet.empty(), Option.none(), false),
467
+ ]),
468
+ ]),
469
+ });
470
+ const inspectorTabContent = (model, tab, inspectedModel) => M.value(tab).pipe(M.when('Model', () => modelTabContent(model, inspectedModel)), M.when('Message', () => messageTabContent(model)), M.exhaustive);
471
+ const inspectorPaneView = (model) => div([Class('flex flex-col border-l min-w-0 flex-1 dt-inspector-pane')], [
472
+ Tabs.view({
473
+ model: model.inspectorTabs,
474
+ toMessage: tabsMessage => GotInspectorTabsMessage({ message: tabsMessage }),
475
+ tabs: INSPECTOR_TABS,
476
+ className: 'flex flex-col flex-1 min-h-0',
477
+ tabListClassName: 'flex border-b shrink-0',
478
+ tabToConfig: (tab, { isActive }) => ({
479
+ buttonClassName: clsx('dt-tab-button cursor-pointer text-base font-mono px-3 py-1', isActive ? 'text-dt dt-tab-active' : 'text-dt-muted'),
480
+ buttonContent: span([], [tab]),
481
+ panelClassName: 'flex flex-col flex-1 min-h-0 min-w-0',
482
+ panelContent: Option.match(model.maybeInspectedModel, {
483
+ onNone: () => emptyInspectorView,
484
+ onSome: inspectedModel => inspectorTabContent(model, tab, inspectedModel),
485
+ }),
486
+ }),
487
+ }),
488
+ ]);
489
+ // MESSAGE LIST
490
+ const badgeView = (model) => button([
491
+ Class(clsx('fixed bg-dt-bg text-dt cursor-pointer flex flex-col items-center justify-center font-mono outline-none dt-badge', BADGE_POSITION_CLASS[position], model.isPaused ? 'dt-badge-paused' : 'dt-badge-accent')),
492
+ Style({ width: '22px', height: '56px', fontSize: '10px' }),
493
+ OnClick(ClickedToggle()),
494
+ ], [
495
+ model.isOpen
496
+ ? svg([
497
+ AriaHidden(true),
498
+ Xmlns('http://www.w3.org/2000/svg'),
499
+ Fill('none'),
500
+ ViewBox('0 0 24 24'),
501
+ StrokeWidth('1.5'),
502
+ Stroke('currentColor'),
503
+ Style({ width: '12px', height: '12px' }),
504
+ ], [
505
+ path([
506
+ StrokeLinecap('round'),
507
+ StrokeLinejoin('round'),
508
+ D('M6 18L18 6M6 6l12 12'),
509
+ ], []),
510
+ ])
511
+ : div([
512
+ Class('flex flex-col items-center gap-0.5 text-dt-muted font-semibold tracking-wider leading-none'),
513
+ ], [span([], ['D']), span([], ['E']), span([], ['V'])]),
514
+ ]);
515
+ const headerClass = 'flex items-center justify-between px-3 py-1.5 border-b shrink-0';
516
+ const actionButtonClass = 'dt-resume-button bg-transparent border-none text-dt-live cursor-pointer text-base font-mono font-medium';
517
+ const statusClass = 'text-base font-mono';
518
+ const clearHistoryButton = button([Class(headerButtonClass), OnClick(ClickedClear())], ['Clear history']);
519
+ const headerView = (model) => {
520
+ const { status, action } = M.value(mode).pipe(M.withReturnType(), M.when('TimeTravel', () => model.isPaused
521
+ ? {
522
+ status: span([Class(`${statusClass} text-dt-paused`)], [
523
+ model.pausedAtIndex === INIT_INDEX
524
+ ? 'Paused (init)'
525
+ : `Paused (${model.pausedAtIndex + 1})`,
526
+ ]),
527
+ action: button([Class(actionButtonClass), OnClick(ClickedResume())], ['Resume →']),
528
+ }
529
+ : {
530
+ status: span([Class(`${statusClass} text-dt-live font-medium`)], ['Live']),
531
+ action: empty,
532
+ }), M.when('Inspect', () => Option.match(model.maybeSelectedIndex, {
533
+ onNone: () => ({
534
+ status: empty,
535
+ action: empty,
536
+ }),
537
+ onSome: selectedIndex => ({
538
+ status: span([Class(`${statusClass} text-dt-accent`)], [
539
+ selectedIndex === INIT_INDEX
540
+ ? 'Inspecting (init)'
541
+ : `Inspecting (${selectedIndex + 1})`,
542
+ ]),
543
+ action: button([Class(actionButtonClass), OnClick(ClickedFollowLatest())], ['Follow Latest →']),
544
+ }),
545
+ })), M.exhaustive);
546
+ return header([Class(headerClass)], [status, action, clearHistoryButton]);
547
+ };
548
+ const initRowView = (isSelected, isPausedHere) => keyed('li')('init', [
549
+ Class(clsx(ROW_BASE, isSelected && 'selected')),
550
+ OnClick(ClickedRow({ index: INIT_INDEX })),
551
+ ], [
552
+ ...OptionExt.when(mode === 'TimeTravel', span([Class('pause-column')], isPausedHere ? [pauseIconView] : [])).pipe(Option.toArray),
553
+ span([Class('dot-column')], []),
554
+ span([Class(indexClass)], []),
555
+ span([Class('text-base text-dt-muted font-mono')], ['Init']),
556
+ ]);
557
+ const pauseIconView = svg([
558
+ AriaHidden(true),
559
+ Class('dt-pause-icon'),
560
+ Xmlns('http://www.w3.org/2000/svg'),
561
+ Fill('none'),
562
+ ViewBox('0 0 24 24'),
563
+ StrokeWidth('2.5'),
564
+ Stroke('currentColor'),
565
+ ], [
566
+ path([
567
+ StrokeLinecap('round'),
568
+ StrokeLinejoin('round'),
569
+ D('M5.75 3v18M18.25 3v18'),
570
+ ], []),
571
+ ]);
572
+ const messageRowView = (tag, absoluteIndex, isSelected, isPausedHere, timeDelta, isModelChanged) => keyed('li')(String(absoluteIndex), [
573
+ Class(clsx(ROW_BASE, isSelected && 'selected')),
574
+ OnClick(ClickedRow({ index: absoluteIndex })),
575
+ ], [
576
+ ...OptionExt.when(mode === 'TimeTravel', span([Class('pause-column')], isPausedHere ? [pauseIconView] : [])).pipe(Option.toArray),
577
+ span([Class('dot-column')], isModelChanged ? [inlineDiffDotView] : []),
578
+ span([Class(indexClass)], [String(absoluteIndex + 1)]),
579
+ span([Class('text-base text-dt font-mono flex-1 truncate')], [tag]),
580
+ span([
581
+ Class('text-2xs text-dt-muted font-mono shrink-0 text-right min-w-5'),
582
+ ], [formatTimeDelta(timeDelta)]),
583
+ ]);
584
+ const messageListView = (model) => {
585
+ const baseTimestamp = pipe(model.entries, Array_.head, Option.match({
586
+ onNone: () => 0,
587
+ onSome: ({ timestamp }) => timestamp,
588
+ }));
589
+ const lastIndex = Array_.isEmptyReadonlyArray(model.entries)
590
+ ? INIT_INDEX
591
+ : model.startIndex + model.entries.length - 1;
592
+ const selectedIndex = M.value(mode).pipe(M.when('TimeTravel', () => model.isPaused ? model.pausedAtIndex : lastIndex), M.when('Inspect', () => Option.getOrElse(model.maybeSelectedIndex, () => lastIndex)), M.exhaustive);
593
+ const isInitSelected = selectedIndex === INIT_INDEX;
594
+ const messageRows = pipe(model.entries, Array_.map((entry, arrayIndex) => {
595
+ const absoluteIndex = model.startIndex + arrayIndex;
596
+ const isSelected = selectedIndex === absoluteIndex;
597
+ const isPausedHere = model.isPaused && model.pausedAtIndex === absoluteIndex;
598
+ return messageRowView(entry.tag, absoluteIndex, isSelected, isPausedHere, entry.timestamp - baseTimestamp, entry.isModelChanged);
599
+ }), Array_.reverse);
600
+ return ul([Class('message-list flex-1 overflow-y-auto overscroll-contain min-h-0')], [
601
+ ...messageRows,
602
+ initRowView(isInitSelected, model.isPaused && model.pausedAtIndex === INIT_INDEX),
603
+ ]);
604
+ };
605
+ // PANEL
606
+ const panelView = (model) => keyed('div')('dt-panel', [
607
+ Class(clsx('fixed dt-panel dt-panel-wide bg-dt-bg border rounded-lg flex flex-col overflow-hidden font-mono text-dt', PANEL_POSITION_CLASS[position])),
608
+ ], [
609
+ ...Option.map(maybeBanner, banner => div([
610
+ Class('px-3 py-2 border-b text-sm text-dt-muted font-mono shrink-0 leading-snug'),
611
+ ], [banner])).pipe(Option.toArray),
612
+ headerView(model),
613
+ div([Class('flex flex-1 min-h-0 dt-content')], [
614
+ div([Class('flex flex-col min-h-0 dt-message-pane')], [messageListView(model)]),
615
+ inspectorPaneView(model),
616
+ ]),
617
+ ]);
618
+ const interactionBlocker = div([Class('dt-interaction-blocker')], []);
619
+ return (model) => div([], [
620
+ ...OptionExt.when(model.isPaused && mode === 'TimeTravel', interactionBlocker).pipe(Option.toArray),
621
+ ...OptionExt.when(model.isOpen, panelView(model)).pipe(Option.toArray),
622
+ badgeView(model),
623
+ ]);
624
+ };
625
+ // CREATE
626
+ const DEVTOOLS_HOST_ID = 'foldkit-devtools';
627
+ const createShadowContainer = () => {
628
+ const existingHost = document.getElementById(DEVTOOLS_HOST_ID);
629
+ if (existingHost) {
630
+ existingHost.remove();
631
+ }
632
+ const host = document.createElement('div');
633
+ host.id = DEVTOOLS_HOST_ID;
634
+ document.body.appendChild(host);
635
+ const shadow = host.attachShadow({ mode: 'open' });
636
+ const styleElement = document.createElement('style');
637
+ styleElement.textContent = overlayStyles;
638
+ shadow.appendChild(styleElement);
639
+ const container = document.createElement('div');
640
+ shadow.appendChild(container);
641
+ return { container, shadow };
642
+ };
643
+ export const createOverlay = (store, position, mode, maybeBanner) => Effect.gen(function* () {
644
+ const { container, shadow } = createShadowContainer();
645
+ const flags = Effect.gen(function* () {
646
+ const storeState = yield* SubscriptionRef.get(store.stateRef);
647
+ return {
648
+ isMobile: window.matchMedia(MOBILE_BREAKPOINT_QUERY).matches,
649
+ ...toDisplayState(storeState),
650
+ };
651
+ });
652
+ const init = (flags) => [
653
+ {
654
+ isOpen: false,
655
+ ...flags,
656
+ maybeSelectedIndex: Option.none(),
657
+ maybeInspectedModel: Option.none(),
658
+ maybeInspectedMessage: Option.none(),
659
+ expandedPaths: HashSet.empty(),
660
+ changedPaths: HashSet.empty(),
661
+ affectedPaths: HashSet.empty(),
662
+ inspectorTabs: Tabs.init({ id: INSPECTOR_TABS_ID }),
663
+ },
664
+ [],
665
+ ];
666
+ const overlayRuntime = makeElement({
667
+ Model,
668
+ Flags,
669
+ flags,
670
+ init,
671
+ update: makeUpdate(store, shadow, mode),
672
+ view: makeView(position, mode, maybeBanner),
673
+ container,
674
+ subscriptions: makeOverlaySubscriptions(store),
675
+ devtools: { show: 'Never' },
676
+ });
677
+ yield* Effect.forkDaemon(overlayRuntime());
678
+ });