Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
770 lines (682 loc) · 27.9 KB
/
Copy pathapp.js
File metadata and controls
770 lines (682 loc) · 27.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
import { reactive, html, watch } from 'https://esm.sh/@arrow-js/core'
/*
app.js is intentionally verbose and heavily commented.
It is written for two audiences:
1. a beginner trying to understand the moving parts
2. a senior developer reopening the project in 6 months
High-level architecture:
- htmx fetches HTML fragments from the server
- htmx swaps them into #content
- this script looks at the new DOM and enhances any fragment it recognises
- each fragment gets its own Arrow-JS state and template rendering
*/
const requestStatus = document.getElementById('requestStatus')
// -----------------------------------------------------------------------------
// htmx lifecycle logging
// -----------------------------------------------------------------------------
// These event names match htmx 2.x. htmx 4 renamed several lifecycle events,
// so if you later upgrade you should revisit these handlers. The migration guide
// calls out the event-name changes. See the README for links. cite omitted in file
// -----------------------------------------------------------------------------
document.body.addEventListener('htmx:beforeRequest', (event) => {
const path = event.detail?.pathInfo?.requestPath || '(unknown path)'
requestStatus.textContent = `Request started: ${path}`
})
document.body.addEventListener('htmx:afterSwap', (event) => {
const target = event.detail?.target
requestStatus.textContent = `Swap complete in #${target?.id || 'unknown'}. Arrow is now enhancing the new fragment.`
try {
initArrowIslands(target || document)
} catch (err) {
console.error('Arrow enhancement failed after swap', err)
requestStatus.textContent = `Swap complete, but Arrow enhancement failed. Check the browser console.`
}
})
document.body.addEventListener('htmx:responseError', (event) => {
requestStatus.textContent = `Request failed: ${event.detail?.xhr?.status || 'unknown status'}`
})
// -----------------------------------------------------------------------------
// Helper: bind any buttons inside the swapped HTML that should trigger htmx
// fragment loads but are rendered by Arrow templates rather than static HTML.
// -----------------------------------------------------------------------------
function wireFragmentNav(root = document) {
root.querySelectorAll('[data-fragment-nav]').forEach((button) => {
if (button.dataset.boundNav === 'true') return
button.dataset.boundNav = 'true'
button.addEventListener('click', () => {
const fragment = button.dataset.fragmentNav
if (!fragment) return
htmx.ajax('GET', `/fragments/${fragment}.html`, '#content')
})
})
}
// -----------------------------------------------------------------------------
// 1. Search island
// -----------------------------------------------------------------------------
function initSearchIsland(root) {
const host = root.querySelector('[data-arrow-search]')
if (!host || host.dataset.arrowBound === 'true') return
host.dataset.arrowBound = 'true'
/*
Local state for the fragment.
Arrow tracks reads and writes through the reactive proxy.
*/
const state = reactive({
term: host.dataset.initialTerm || '',
role: host.dataset.initialRole || 'all',
serverResultCount: Number(host.dataset.serverCount || '0'),
items: JSON.parse(host.dataset.items || '[]'),
recentMessages: []
})
/*
Computed values in Arrow-JS are created by passing a function to reactive().
These re-run automatically when any tracked reactive reads change.
*/
const filteredItems = reactive(() => {
const term = state.term.trim().toLowerCase()
return state.items.filter((item) => {
const haystack = `${item.name} ${item.role} ${item.location}`.toLowerCase()
const matchesTerm = !term || haystack.includes(term)
const matchesRole = state.role === 'all' || item.role === state.role
return matchesTerm && matchesRole
})
})
const totalVisible = reactive(() => filteredItems.value.length)
const hasFilters = reactive(() => !!state.term.trim() || state.role !== 'all')
const summaryText = reactive(() => {
const noun = totalVisible.value === 1 ? 'person' : 'people'
const suffix = hasFilters.value ? 'after local Arrow filtering' : 'with no local filters applied'
return `${totalVisible.value} ${noun} visible, ${suffix}.`
})
/*
Watchers are useful for side effects that should happen when reactive data changes,
such as writing to a log, syncing to localStorage or updating analytics.
*/
const [, stopWatchingSearch] = watch(
() => `${state.term}|${state.role}|${totalVisible.value}`,
(signature) => {
const timestamp = new Date().toLocaleTimeString()
state.recentMessages = [`${timestamp}: filters changed -> ${signature}`, ...state.recentMessages].slice(0, 4)
}
)
const view = html`
<section class="stack">
<div>
<h2>Search fragment <span class="badge">Arrow computed + watch</span></h2>
<p class="muted">
The server returned some initial rows. Arrow-JS now adds local filtering,
computed summaries and a tiny watcher-driven activity log.
</p>
</div>
<div class="flash success small">
Server-side fragment load complete. The server says it returned ${() => state.serverResultCount} rows.
</div>
<div class="row">
<input
type="search"
placeholder="Type to filter by name, role or location"
.value="${() => state.term}"
@input="${(evt) => { state.term = evt.target.value }}"
/>
<select @change="${(evt) => { state.role = evt.target.value }}">
<option value="all" selected="${() => state.role === 'all'}">All roles</option>
<option value="Developer" selected="${() => state.role === 'Developer'}">Developer</option>
<option value="Tester" selected="${() => state.role === 'Tester'}">Tester</option>
<option value="Analyst" selected="${() => state.role === 'Analyst'}">Analyst</option>
<option value="Product Owner" selected="${() => state.role === 'Product Owner'}">Product Owner</option>
</select>
<span class="badge">${() => totalVisible.value} visible</span>
<span class="badge">${() => hasFilters.value ? 'Local filters on' : 'No local filters'}</span>
</div>
<div class="status">
<strong>Computed summary:</strong> ${() => summaryText.value}
</div>
<table class="results-table">
<thead>
<tr>
<th>Name</th>
<th>Role</th>
<th>Location</th>
</tr>
</thead>
<tbody>
${() => filteredItems.value.map(item => html`
<tr>
<td>${item.name}</td>
<td>${item.role}</td>
<td>${item.location}</td>
</tr>
`)}
</tbody>
</table>
<div>
<h4>Watcher log</h4>
<ul>
${() => state.recentMessages.map(message => html`<li>${message}</li>`)}
</ul>
</div>
<div class="row">
<button class="soft" data-fragment-nav="results">Load server results fragment</button>
<button class="soft" data-fragment-nav="picker">Load dual-list fragment</button>
</div>
</section>
`
view(host)
wireFragmentNav(host)
}
// -----------------------------------------------------------------------------
// 2. Results island
// -----------------------------------------------------------------------------
function initResultsIsland(root) {
const host = root.querySelector('[data-arrow-results]')
if (!host || host.dataset.arrowBound === 'true') return
host.dataset.arrowBound = 'true'
const state = reactive({
showNotes: false,
compactMode: true,
minimumScore: Number(host.dataset.minimumScore || '0'),
rows: JSON.parse(host.dataset.rows || '[]'),
auditTrail: []
})
const visibleRows = reactive(() => state.rows.filter(row => row.score >= state.minimumScore))
const averageScore = reactive(() => {
if (!visibleRows.value.length) return 0
const total = visibleRows.value.reduce((sum, row) => sum + row.score, 0)
return Math.round((total / visibleRows.value.length) * 10) / 10
})
const topPerformer = reactive(() => visibleRows.value.length
? [...visibleRows.value].sort((a, b) => b.score - a.score)[0].name
: 'No results')
const [, stopResultsWatcher] = watch(
() => `${state.showNotes}|${state.compactMode}|${state.minimumScore}|${visibleRows.value.length}`,
(signature) => {
state.auditTrail = [`UI state changed: ${signature}`, ...state.auditTrail].slice(0, 5)
}
)
const view = html`
<section class="stack">
<div>
<h2>Results fragment <span class="badge">Computed metrics</span></h2>
<p class="muted">
This fragment simulates server-returned search results. Arrow-JS adds local display rules,
computed metrics and a watcher-backed audit trail.
</p>
</div>
<div class="row">
<button class="soft" @click="${() => { state.showNotes = !state.showNotes }}">
${() => state.showNotes ? 'Hide notes' : 'Show notes'}
</button>
<button class="soft" @click="${() => { state.compactMode = !state.compactMode }}">
${() => state.compactMode ? 'Switch to expanded view' : 'Switch to compact view'}
</button>
<label class="row small">
Minimum score
<select @change="${(evt) => { state.minimumScore = Number(evt.target.value) }}">
<option value="0" selected="${() => state.minimumScore === 0}">0</option>
<option value="85" selected="${() => state.minimumScore === 85}">85</option>
<option value="90" selected="${() => state.minimumScore === 90}">90</option>
<option value="95" selected="${() => state.minimumScore === 95}">95</option>
</select>
</label>
</div>
<div class="row small">
<span class="badge">${() => visibleRows.value.length} visible rows</span>
<span class="badge">Average: ${() => averageScore.value}</span>
<span class="badge">Top performer: ${() => topPerformer.value}</span>
</div>
<table class="results-table">
<thead>
<tr>
<th>Name</th>
<th>Score</th>
<th>${() => state.compactMode ? 'Summary' : 'Full Notes'}</th>
</tr>
</thead>
<tbody>
${() => visibleRows.value.map(row => html`
<tr>
<td>${row.name}</td>
<td>${row.score}</td>
<td>
${() => state.showNotes
? (state.compactMode ? row.notesShort : row.notesLong)
: 'Hidden until notes are shown'}
</td>
</tr>
`)}
</tbody>
</table>
<div>
<h4>Watcher audit trail</h4>
<ul>
${() => state.auditTrail.map(message => html`<li>${message}</li>`)}
</ul>
</div>
<div class="row">
<button class="soft" data-fragment-nav="search">Back to search fragment</button>
<button class="soft" data-fragment-nav="picker">Load dual-list fragment</button>
</div>
</section>
`
view(host)
wireFragmentNav(host)
}
// -----------------------------------------------------------------------------
// 3. Dual-list picker island
// -----------------------------------------------------------------------------
function initPickerIsland(root) {
const host = root.querySelector('[data-arrow-picker]')
if (!host || host.dataset.arrowBound === 'true') return
host.dataset.arrowBound = 'true'
const payload = JSON.parse(host.dataset.payload || '{}')
const state = reactive({
available: payload.available || [],
selected: payload.selected || [],
filterAvailable: '',
filterSelected: '',
moveCount: 0,
history: []
})
const filteredAvailable = reactive(() => {
const term = state.filterAvailable.trim().toLowerCase()
return state.available.filter(item => !term || item.toLowerCase().includes(term))
})
const filteredSelected = reactive(() => {
const term = state.filterSelected.trim().toLowerCase()
return state.selected.filter(item => !term || item.toLowerCase().includes(term))
})
const totalAssigned = reactive(() => state.selected.length)
const canSave = reactive(() => state.selected.length >= 2)
const saveMessage = reactive(() => canSave.value
? `Ready to save ${state.selected.length} selections.`
: 'Select at least two items before saving.')
function moveToSelected(item) {
state.available = state.available.filter(x => x !== item)
state.selected = [...state.selected, item].sort()
state.moveCount += 1
}
function moveToAvailable(item) {
state.selected = state.selected.filter(x => x !== item)
state.available = [...state.available, item].sort()
state.moveCount += 1
}
/*
Batch reset: all properties are updated in one assignment so the
watcher only fires once for the combined change. Arrow-JS batches
synchronous writes into a single reactive cycle automatically, so
setting multiple properties in the same synchronous block avoids
intermediate re-renders without needing a special API.
*/
function resetToDefaults() {
state.available = [...(payload.available || [])]
state.selected = [...(payload.selected || [])]
state.filterAvailable = ''
state.filterSelected = ''
state.moveCount = 0
}
const [, stopPickerWatcher] = watch(
() => `${state.moveCount}|${state.selected.join(',')}`,
(snapshot) => {
state.history = [`Selection changed -> ${snapshot}`, ...state.history].slice(0, 5)
}
)
const view = html`
<section class="stack">
<div>
<h2>Dual-list picker <span class="badge">Template-heavy local UI</span></h2>
<p class="muted">
This is a classic interactive island: too rich for ad hoc jQuery, but not a good reason to turn the whole page into a SPA.
</p>
</div>
<div class="row small">
<span class="badge">Assigned: ${() => totalAssigned.value}</span>
<span class="badge">Moves: ${() => state.moveCount}</span>
<span class="badge">${() => canSave.value ? 'Can save' : 'Cannot save yet'}</span>
</div>
<div class="status"><strong>Computed save state:</strong> ${() => saveMessage.value}</div>
<div class="list-grid">
<div class="list-box">
<h3>Available</h3>
<input type="text"
placeholder="Filter available"
@input="${(evt) => { state.filterAvailable = evt.target.value }}" />
<ul>
${() => filteredAvailable.value.map(item => html`
<li>
<span>${item}</span>
<button class="soft" @click="${() => moveToSelected(item)}">Add →</button>
</li>
`)}
</ul>
</div>
<div class="move-buttons">
<button class="soft" data-fragment-nav="search">Search</button>
<button class="soft" data-fragment-nav="results">Results</button>
</div>
<div class="list-box">
<h3>Selected</h3>
<input type="text"
placeholder="Filter selected"
@input="${(evt) => { state.filterSelected = evt.target.value }}" />
<ul>
${() => filteredSelected.value.map(item => html`
<li>
<span>${item}</span>
<button class="soft" @click="${() => moveToAvailable(item)}">← Remove</button>
</li>
`)}
</ul>
</div>
</div>
<div>
<h4>Watcher history</h4>
<ul>
${() => state.history.map(entry => html`<li>${entry}</li>`)}
</ul>
</div>
<div class="row">
<button class="primary" @click="${() => resetToDefaults()}">Reset to defaults (batch update)</button>
<button class="soft" data-fragment-nav="search">Back to search fragment</button>
<button class="soft" data-fragment-nav="notifications">Load notifications fragment</button>
</div>
<div class="status small muted">
<strong>Tip:</strong> The Reset button updates all state properties in a single
synchronous block. Arrow-JS batches synchronous writes into one reactive cycle
automatically, preventing intermediate re-renders.
</div>
</section>
`
view(host)
wireFragmentNav(host)
}
// -----------------------------------------------------------------------------
// 4. Notifications island — timer-driven reactivity, dynamic CSS classes,
// and a local nextTick helper (setTimeout 0) for post-render DOM access.
// Uses only the proven reactive/html/watch imports.
// -----------------------------------------------------------------------------
/*
Local nextTick polyfill.
Defers a callback until the next microtask/macrotask, after Arrow has
finished updating the DOM. This avoids importing nextTick from arrow-js
which may not be available in the esm.sh bundle version being used.
*/
function nextTick(fn) {
setTimeout(fn, 0)
}
function initNotificationsIsland(root) {
const host = root.querySelector('[data-arrow-notifications]')
if (!host || host.dataset.arrowBound === 'true') return
host.dataset.arrowBound = 'true'
const categories = JSON.parse(host.dataset.categories || '["Info"]')
/*
Pre-built messages for each category so the user can trigger
notifications instantly without typing.
*/
const presetMessages = {
Info: [
'Database connection established',
'Background sync completed',
'New software update available',
'User session refreshed'
],
Warning: [
'Session expires in 15 minutes',
'Disk space running low (12% remaining)',
'API response time degrading',
'Password expires in 5 days'
],
Success: [
'Server started successfully',
'File upload complete — 3 files saved',
'Profile updated successfully',
'Deployment finished — all tests passed'
],
Error: [
'Failed to connect to payment gateway',
'Build pipeline failed — 2 errors found',
'Authentication token has expired',
'Unable to reach notification service'
]
}
/*
Track which preset index we're at per category so we cycle through them.
*/
const presetIndex = { Info: 0, Warning: 0, Success: 0, Error: 0 }
const state = reactive({
notifications: [],
dismissingIds: [],
nextId: 1,
message: '',
category: categories[0] || 'Info',
autoExpire: true,
ttlSeconds: 5,
paused: false,
nextTickLog: [],
triggerCount: 0
})
const totalCount = reactive(() => state.notifications.length)
const activeCount = reactive(() => state.notifications.filter(n => !n.dismissed && !state.dismissingIds.includes(n.id)).length)
function categoryClass(cat) {
const map = { Info: 'info', Warning: 'warning', Success: 'success', Error: 'danger' }
return map[cat] || 'info'
}
/*
Category icon — a small unicode symbol for visual flair.
*/
function categoryIcon(cat) {
const map = { Info: 'ℹ️', Warning: '⚠️', Success: '✅', Error: '❌' }
return map[cat] || '💬'
}
function addNotification(message, category) {
const msg = (message || state.message).trim()
if (!msg) return
const cat = category || state.category
const id = state.nextId
state.notifications = [
{
id,
message: msg,
category: cat,
createdAt: new Date().toLocaleTimeString(),
ttl: state.autoExpire ? state.ttlSeconds : null,
dismissed: false
},
...state.notifications
]
state.nextId += 1
state.message = ''
state.triggerCount += 1
// nextTick: runs after Arrow has updated the DOM
nextTick(() => {
const timestamp = new Date().toLocaleTimeString()
state.nextTickLog = [
`${timestamp}: nextTick fired after adding "${msg}" — DOM confirmed updated.`,
...state.nextTickLog
].slice(0, 4)
})
}
/*
Quick-trigger: picks the next preset message for the chosen category
and fires it immediately. This is the main "make something happen" button.
*/
function triggerNotification() {
const cat = state.category
const presets = presetMessages[cat] || ['Something happened']
const idx = presetIndex[cat] || 0
const msg = presets[idx % presets.length]
presetIndex[cat] = idx + 1
addNotification(msg, cat)
}
/*
Animated dismiss: adds a 'dismissing' class, waits for the CSS
animation to finish, then actually removes the notification.
*/
function dismissNotification(id) {
if (state.dismissingIds.includes(id)) return
state.dismissingIds = [...state.dismissingIds, id]
setTimeout(() => {
state.notifications = state.notifications.filter(n => n.id !== id)
state.dismissingIds = state.dismissingIds.filter(did => did !== id)
}, 350)
}
function clearAll() {
const ids = state.notifications.map(n => n.id)
state.dismissingIds = [...ids]
setTimeout(() => {
state.notifications = []
state.dismissingIds = []
}, 350)
}
// Timer-driven reactive updates: decrement TTL every second
setInterval(() => {
if (state.paused) return
const updated = state.notifications.map(n => {
if (n.dismissed || n.ttl === null || state.dismissingIds.includes(n.id)) return n
const newTtl = n.ttl - 1
if (newTtl <= 0) {
// Auto-dismiss with animation
dismissNotification(n.id)
return n
}
return { ...n, ttl: newTtl }
})
state.notifications = updated
}, 1000)
/*
Helper: build the full class string for a notification item.
Arrow-JS does not allow mixing static interpolations (${value}) with
reactive expressions (${() => ...}) inside the same attribute, so we
build the entire class in a single reactive callback.
*/
function notifClass(n) {
return `flash ${categoryClass(n.category)} notif-item${state.dismissingIds.includes(n.id) ? ' dismissing' : ''}${n.dismissed ? ' dismissed' : ''}`
}
const triggerLabel = reactive(() => `🚀 Trigger ${state.category} notification`)
const triggerHint = reactive(() => {
const plural = state.triggerCount === 1 ? '' : 's'
return `Each click cycles through preset ${state.category} messages. Triggered ${state.triggerCount} time${plural} so far.`
})
const timerLabel = reactive(() => state.paused ? '▶ Resume timer' : '⏸ Pause timer')
const timerBadge = reactive(() => state.paused ? '⏸ Timer paused' : '▶ Timer running')
const view = html`
<section class="stack">
<div>
<h2>Notifications <span class="badge">animated + timers</span></h2>
<p class="muted">
Choose a notification type and click <strong>Trigger</strong> to watch it animate in.
Each notification slides in, can be dismissed with an out-animation, and optionally
auto-expires after a countdown.
</p>
</div>
<div class="trigger-area">
<h3>🔔 Trigger a notification</h3>
<div class="row" style="margin-top:8px;">
<select @change="${(evt) => { state.category = evt.target.value }}"
style="min-width:160px;">
${categories.map(cat => html`
<option value="${cat}" selected="${() => state.category === cat}">${categoryIcon(cat)} ${cat}</option>
`)}
</select>
<button class="primary" @click="${() => triggerNotification()}"
style="font-size:15px; padding:12px 24px;">
${() => triggerLabel.value}
</button>
</div>
<p class="muted small" style="margin-top:8px;">${() => triggerHint.value}</p>
</div>
<div class="row small">
<span class="badge">${() => totalCount.value} total</span>
<span class="badge">${() => activeCount.value} active</span>
<span class="badge">${() => timerBadge.value}</span>
</div>
<details style="margin-top:4px;">
<summary>✏️ Type a custom notification message</summary>
<div class="row" style="margin-top:10px;">
<input
type="text"
class="notif-input"
placeholder="Type a custom notification message…"
.value="${() => state.message}"
@input="${(evt) => { state.message = evt.target.value }}"
@keydown="${(evt) => { if (evt.key === 'Enter') addNotification() }}"
/>
<button class="primary" @click="${() => addNotification()}">Add custom</button>
</div>
</details>
<div class="row small">
<label style="display:inline-flex;align-items:center;gap:6px;">
<input type="checkbox"
.checked="${() => state.autoExpire}"
@change="${(evt) => { state.autoExpire = evt.target.checked }}" />
Auto-expire
</label>
<label style="display:inline-flex;align-items:center;gap:6px;">
TTL
<select style="min-width:80px;" @change="${(evt) => { state.ttlSeconds = Number(evt.target.value) }}">
<option value="3" selected="${() => state.ttlSeconds === 3}">3s</option>
<option value="5" selected="${() => state.ttlSeconds === 5}">5s</option>
<option value="10" selected="${() => state.ttlSeconds === 10}">10s</option>
<option value="30" selected="${() => state.ttlSeconds === 30}">30s</option>
</select>
</label>
<button class="soft" @click="${() => { state.paused = !state.paused }}">
${() => timerLabel.value}
</button>
<button class="soft" @click="${() => clearAll()}">🗑 Clear all</button>
</div>
<div>
${() => state.notifications.length === 0
? html`<div class="status muted small">
No notifications yet. Use the trigger area above to create one!
</div>`
: state.notifications.map(n => html`
<div class="${() => notifClass(n)}" style="overflow:hidden;">
<div class="row" style="justify-content:space-between;">
<div>
${categoryIcon(n.category)} <strong>[${n.category}]</strong> ${n.message}
<span class="muted small" style="margin-left:8px;">${n.createdAt}</span>
</div>
<div>
<span class="small muted" style="margin-left:8px;">
${() => n.ttl !== null && !n.dismissed && !state.dismissingIds.includes(n.id) ? '⏱ ' + n.ttl + 's' : ''}
</span>
<button class="soft small"
style="${() => n.dismissed || state.dismissingIds.includes(n.id) ? 'display:none;' : ''}"
@click="${() => dismissNotification(n.id)}">✕ Dismiss</button>
</div>
</div>
</div>
`)
}
</div>
<div>
<h4>nextTick log</h4>
${() => state.nextTickLog.length === 0
? html`<p class="muted small">Log entries will appear after you trigger a notification.</p>`
: html`<ul>
${() => state.nextTickLog.map(entry => html`<li class="small">${entry}</li>`)}
</ul>`
}
</div>
<div class="row">
<button class="soft" data-fragment-nav="search">Back to search fragment</button>
<button class="soft" data-fragment-nav="picker">Load dual-list fragment</button>
</div>
</section>
`
view(host)
wireFragmentNav(host)
}
// -----------------------------------------------------------------------------
// Scan a newly swapped fragment and enhance any known islands.
// -----------------------------------------------------------------------------
function initArrowIslands(root = document) {
initSearchIsland(root)
initResultsIsland(root)
initPickerIsland(root)
initNotificationsIsland(root)
}
// Also wire any fragment-nav buttons that are already present in the shell.
wireFragmentNav(document)
// Helpful startup trace for debugging in the browser console.
console.log('app.js loaded; waiting for htmx swaps to enhance fragments.')