-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patheditor.cljs
More file actions
898 lines (818 loc) · 41.9 KB
/
Copy patheditor.cljs
File metadata and controls
898 lines (818 loc) · 41.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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
(ns shell.editor
"Blocks UI composition layer.
Responsibilities:
- boot explicit startup surfaces (plugins, keymaps, storage, render)
- compose components and route intents through the shared executor
- keep DOM-global listeners and browser wiring at the shell edge"
(:require [clojure.string :as str]
[replicant.dom :as d]
[kernel.db :as db]
[kernel.query :as q]
[kernel.transaction :as tx]
[kernel.api :as api]
[shell.log :as slog]
[components.block :as block]
[components.sidebar :as sidebar]
[components.backlinks :as backlinks]
[dataspex.core :as dataspex]
[components.image :as image]
[shell.dispatch-bridge :as dispatch-bridge]
[shell.executor :as executor]
[shell.global-keyboard :as global-keyboard]
[shell.storage :as storage]
[shell.e2e-scenarios]
[shell.view-state :as vs]
[shell.url-sync :as url-sync]
[utils.text-selection :as text-sel]
[debug-api]
[plugins.manifest :as plugins]
#_{:clj-kondo/ignore [:unused-namespace]} ; load-time registration
[shell.render-manifest :as render-manifest]
[keymap.bindings :as bindings]
[kernel.state-machine :as sm]
[kernel.intent :as intent]
[components.quick-switcher :as quick-switcher]
[components.notification :as notification]
[components.lightbox :as lightbox]
[components.journals :as journals]
[components.all-pages :as all-pages]
[utils.journal :as journal]
[utils.cursor-boundaries :as cursor-bounds]))
;; ── State atom ────────────────────────────────────────────────────────────────
(defn- query-param?
"Check if URL contains a query param substring."
[param]
(let [search (.-search js/location)]
(boolean (and search (>= (.indexOf search param) 0)))))
(defn- test-mode? [] (query-param? "test=true"))
(defn- embed-mode? [] (query-param? "embed"))
(defn- fixture-mode? [] (query-param? "fixture"))
;; Initial DB - starts with demo content, replaced when folder is loaded
(defonce !db
(atom
;; Always start with empty DB - demo data loaded only if no folder configured.
;; Undo/redo lives in shell.log/!log (the canonical event-sourced state).
(db/empty-db)))
;; Storage status atom for UI feedback
(defonce !storage-status
(atom {:folder-name nil
:loading? false
;; Start in checking state - true until we know if folder exists
:checking? true}))
(defn- navigate-to-startup-page!
"Navigate to initial surface based on URL param or default to the journals view.
Priority:
1. If ?page=PageName in URL, navigate to that page
2. Otherwise, open the stacked journals view (Logseq-style homepage).
The JournalsView component auto-materializes today's journal when
missing via :ensure-page-exists, so no page creation is needed here."
[]
(if-let [url-page-name (url-sync/get-page-from-url)]
;; URL specifies a page - navigate there
(do
(js/console.log "🔗 Opening page from URL:" url-page-name)
(executor/apply-intent! !db
{:type :navigate-to-page
:page-name url-page-name}
"URL"))
;; No URL page - default to journals view (stacked, newest first)
(do
(js/console.log "📖 Opening journals view")
(executor/apply-intent! !db
{:type :open-journals-view}
"STARTUP"))))
(defn load-from-folder!
"Load pages from the currently selected folder into DB.
If folder is empty, starts with empty DB.
Navigates to page from URL or today's journal."
[]
(lightbox/hide!)
(swap! !storage-status assoc :loading? true)
(-> (storage/load-all-pages)
(.then (fn [ops]
(if (seq ops)
;; Folder has pages - load them. Loaded state is the new
;; baseline (:root-db of the log), not an undoable action.
(do
(js/console.log "📂 Loading" (count ops) "ops from folder...")
(let [loaded (:db (tx/interpret (db/empty-db) ops))]
(reset! !db loaded)
(slog/reset-with-db! loaded)
;; Managed files = exactly what the loaded db projects.
;; Files that failed to load stay unmanaged → undeletable.
(storage/sync-managed-from-db! loaded)))
;; Empty folder - start with empty DB
(do
(js/console.log "📂 Empty folder, starting fresh")
(reset! !db (db/empty-db))
(slog/reset-with-db! (db/empty-db))
(storage/sync-managed-from-db! (db/empty-db))))
;; Navigate to startup page (URL param or today's journal)
(navigate-to-startup-page!)
(swap! !storage-status assoc
:loading? false
:checking? false
:folder-name (storage/get-folder-name))))
(.catch (fn [err]
(js/console.error "Failed to load from folder:" err)
(swap! !storage-status assoc :loading? false :checking? false)))))
(defn pick-folder!
"Show folder picker dialog and load pages from selected folder."
[]
(-> (storage/pick-folder!)
(.then (fn [handle]
(when handle
(load-from-folder!))))))
(defn clear-folder!
"Disconnect from the current folder and reset to empty state."
[]
(lightbox/hide!)
(storage/clear-folder!)
(image/clear-url-cache!)
(swap! !storage-status assoc :folder-name nil)
;; Reset to empty DB (no demo data - user must pick folder or start fresh)
(reset! !db (db/empty-db))
(slog/reset-with-db! (db/empty-db))
(storage/sync-managed-from-db! (db/empty-db))
(vs/put! [:ui :current-page] nil))
;; Try to restore previously selected folder on startup
(defonce _restore-folder
(when-not (or (test-mode?) (fixture-mode?))
(-> (storage/restore-folder!)
(.then (fn [restored?]
(if restored?
;; Folder found - load-from-folder! will clear :checking? when done
(load-from-folder!)
;; No folder configured - clear checking state, stay empty
(swap! !storage-status assoc :checking? false))))
(.catch (fn [_err]
;; Error checking - clear state, stay empty
(swap! !storage-status assoc :checking? false))))))
;; Auto-save to folder on DB changes (debounced, page-scoped)
(defonce ^:private save-timeout (atom nil))
(defonce ^:private dirty-pages (atom #{}))
(defn- page-for
"Return the enclosing page id for node-id in db, or node-id itself if it is
a page. Returns nil for keyword roots and nodes with no page ancestor."
[db node-id]
(when (string? node-id)
(if (= :page (get-in db [:nodes node-id :type]))
node-id
(q/page-of db node-id))))
(defn- dirty-page-ids
"Compute the set of page ids whose on-disk representation may have changed
between old-db and new-db. Looks at node-level and children-order diffs
only; resolves each changed id to its enclosing page in BOTH dbs so moves,
deletions, and page renames are covered."
[old-db new-db]
(let [old-nodes (:nodes old-db)
new-nodes (:nodes new-db)
old-children (:children-by-parent old-db)
new-children (:children-by-parent new-db)
diff-keys (fn [a b]
(into #{}
(concat
(keep (fn [[k v]] (when (not= v (get b k)) k)) a)
(keep (fn [[k v]] (when (not= v (get a k)) k)) b))))
changed-ids (into (diff-keys old-nodes new-nodes)
(diff-keys old-children new-children))]
(into #{}
(comp (mapcat (fn [id] [(page-for old-db id) (page-for new-db id)]))
(filter some?))
changed-ids)))
(defn- schedule-save!
"Accumulate dirty pages and schedule a debounced write (500ms)."
[old-val new-val]
(swap! dirty-pages into (dirty-page-ids old-val new-val))
(when-let [t @save-timeout]
(js/clearTimeout t))
(reset! save-timeout
(js/setTimeout
(fn []
(let [pages @dirty-pages]
(reset! dirty-pages #{})
(when (and (not (test-mode?)) (storage/has-folder?))
(storage/save-pages! new-val pages)
;; Folder converges to the db: drop managed files whose
;; page is gone (rename, undo of a rename, deletion).
(storage/reconcile-files! new-val))))
500)))
(defonce _db-watcher
(add-watch !db :auto-save
(fn [_ _ old-val new-val]
(schedule-save! old-val new-val))))
;; ── URL Sync (popstate handler for browser back/forward) ────────────────────
(defn- handle-url-navigation
"Handle browser back/forward navigation (popstate).
Navigates to page specified in URL, or to journals view if none."
[page-name]
(if page-name
;; Navigate to page from URL
(executor/apply-intent! !db
{:type :navigate-to-page
:page-name page-name}
"POPSTATE")
;; No page in URL - go to journals view
(executor/apply-intent! !db
{:type :go-to-journal
:journal-title (journal/today-title)}
"POPSTATE")))
(defonce _url-sync-init
(when-not (test-mode?)
(url-sync/init! handle-url-navigation)))
;; ── Intent dispatcher ─────────────────────────────────────────────────────────
(def ^:private structural-intents
"Intent types that may cause DOM re-render and blur.
These intents need keep-edit-on-blur! to prevent the blur handler from
exiting edit mode when focus shifts during re-render."
#{:indent-selected :outdent-selected :move-selected-up :move-selected-down :delete-selected
;; Enter creates new block and moves focus - blur would exit edit mode
:context-aware-enter
;; Paste with blank lines creates new blocks and moves focus to last block
:paste-text
;; Arrow navigation changes editing-block-id - old block unmounts, blur fires
:navigate-with-cursor-memory :navigate-to-adjacent
;; Delete/merge ops change editing-block-id to prev/next/merged block
:delete :merge-with-prev :split-at-cursor})
(defn handle-intent
"Single intent dispatcher - accepts {:type ...} intent maps only.
This is the ONLY place intents are dispatched.
Components call (on-intent {:type ...}) for all intents."
[intent]
(let [intent-map (if (keyword? intent) {:type intent} intent)]
;; Suppress blur-exit during structural ops to prevent focus loss during re-render
(when (contains? structural-intents (:type intent-map))
(vs/keep-edit-on-blur!))
;; Use shared runtime for the actual dispatch
(executor/apply-intent! !db intent-map "DIRECT")))
;; ── Rendering ─────────────────────────────────────────────────────────────────
(defn MockText
"Hidden element for cursor position detection (Logseq technique).
CRITICAL: Must match contenteditable styling for accurate row detection:
- word-wrap and overflow-wrap must match to ensure same wrapping behavior
- width, font-size, font-family, line-height copied dynamically by update-mock-text!"
[]
[:div#mock-text
{:style {:width "100%"
:height "100%"
:position "absolute"
:visibility "hidden"
:top 0
:left 0
:pointer-events "none"
:z-index -1000
:word-wrap "break-word" ;; Match contenteditable
:overflow-wrap "break-word"}}]) ;; Match contenteditable
(defn Outline
"Render outline tree by composing Block components.
Also handles drag & drop at the container level for drops to first position."
[{:keys [db root-id on-intent]}]
(let [children (get-in db [:children-by-parent root-id] [])
editing-block-id (vs/lookup [:ui :editing-block-id])
focus-block-id (vs/lookup [:selection :focus])
selection-set (vs/lookup [:selection :nodes])
folded-set (vs/lookup [:ui :folded])
first-child-id (first children)
;; Check if dropping at top of outline
drop-target (vs/lookup [:ui :drag :drop-target])
dropping-at-top? (and (= (:id drop-target) ::outline-top)
(= (:zone drop-target) :first))
;; Check if actively dragging
dragging? (seq (vs/lookup [:ui :drag :dragging-ids]))]
(if (empty? children)
;; Empty page: auto-seed a first block and put the cursor in it on
;; mount (no click-to-edit placeholder). The keyed mount hook fires
;; exactly once per empty page; once the block exists the branch
;; flips to the populated form below. Mirrors the journals fix in
;; `components.journals/JournalPage` (commit 06cc7605).
[:div.outline.outline--empty
{:replicant/key (str root-id "-empty")
:replicant/on-mount
(fn [_]
(when on-intent
(on-intent {:type :create-block-in-page
:page-id root-id
:block-id (str "block-" (random-uuid))})))}]
;; Normal state: render block tree with dedicated top drop zone
[:div.outline
;; Top drop zone - only shown during drag, intercepts drops above first block
(when dragging?
[:div.top-drop-zone
{:style {:height (if dropping-at-top? "20px" "12px")
:margin-bottom "4px"
:border-radius "4px"
:transition "all 0.15s ease"
:background (if dropping-at-top?
"rgba(59, 130, 246, 0.15)"
"transparent")}
:on {:dragover (fn [e]
(.preventDefault e)
(.stopPropagation e)
(set! (.-dropEffect (.-dataTransfer e)) "move")
(let [dragging (vs/lookup [:ui :drag :dragging-ids])]
(when-not (contains? dragging first-child-id)
(vs/drag-over! ::outline-top :first))))
:dragleave (fn [_e]
(when (= (:id (vs/lookup [:ui :drag :drop-target])) ::outline-top)
(vs/drag-over! nil nil)))
:drop (fn [e]
(.preventDefault e)
(.stopPropagation e)
(let [dragging (vs/lookup [:ui :drag :dragging-ids])]
(vs/put! [:ui :drag] nil)
(when (seq dragging)
(on-intent {:type :move
:selection (vec dragging)
:parent root-id
:anchor :first}))))}}
;; Visual indicator line
(when dropping-at-top?
[:div {:style {:height "2px"
:background "#3b82f6"
:border-radius "1px"}}])])
;; Render blocks
(map (fn [child-id]
(block/Block {:db db
:block-id child-id
:depth 0
:is-focused (= focus-block-id child-id)
:is-selected (contains? selection-set child-id)
:is-editing (= editing-block-id child-id)
:is-folded (contains? folded-set child-id)
:on-intent on-intent}))
children)])))
(defn PageTitle
"Editable page title component.
Matches journal-title styling. Click to edit, blur/Enter to save.
Uses uncontrolled input pattern (browser owns value during edit)."
[{:keys [page-id page-title on-intent]}]
(let [editing? (vs/editing-page-title?)]
(if editing?
;; Edit mode - uncontrolled input (browser owns value)
[:div.page-title-header
[:input.page-title-input
{:type "text"
:replicant/key (str page-id "-edit")
:default-value page-title
:replicant/on-mount (fn [{:replicant/keys [node]}]
(.focus node)
(.select node))
:on {:blur (fn [e]
(let [new-title (str/trim (.-value (.-target e)))]
;; Update DB first, THEN update view state
;; This ensures re-render sees the new title
(when (and (not (str/blank? new-title))
(not= new-title page-title))
(on-intent {:type :rename-page
:page-id page-id
:new-title new-title}))
(vs/put! [:ui :editing-page-title?] false)))
:keydown (fn [e]
(case (.-key e)
"Enter" (do (.preventDefault e)
(.blur (.-target e)))
"Escape" (do (.preventDefault e)
;; Reset value and exit without saving
(set! (.-value (.-target e)) page-title)
(vs/put! [:ui :editing-page-title?] false))
nil))}}]]
;; View mode - clickable h1
[:div.page-title-header
[:h1.page-title-display
{:replicant/key (str page-id "-view")
:on {:click (fn [_e]
(vs/put! [:ui :editing-page-title?] true))}}
page-title]])))
(defn HotkeysReference []
(let [kbd (fn [& key-names]
(into [:span.hotkeys-keys]
(interpose [:span.hotkeys-plus "+"]
(map (fn [k] [:kbd k]) key-names))))
row (fn [combo desc]
[:div.hotkeys-row [:span.hotkeys-desc desc] combo])
group (fn [title & items]
(into [:section.hotkeys-group [:h5 title]] items))]
[:aside.hotkeys-panel
[:header.hotkeys-head "Shortcuts"]
(group "Navigation"
(row (kbd "↑") "Previous block")
(row (kbd "↓") "Next block")
(row (kbd "Shift" "↑") "Extend up")
(row (kbd "Shift" "↓") "Extend down")
(row (kbd "Esc") "Exit edit")
(row (kbd "Enter") "Edit selected"))
(group "Editing"
(row (kbd "Enter") "Split / new")
(row (kbd "Shift" "Enter") "New line")
(row (kbd "⌫") "Delete / merge")
(row (kbd "Tab") "Indent")
(row (kbd "Shift" "Tab") "Outdent")
(row (kbd "⌘" "Enter") "Toggle checkbox"))
(group "Structure"
(row (kbd "⌘" "⇧" "↑") "Move up")
(row (kbd "⌘" "⇧" "↓") "Move down")
(row (kbd "⌘" ";") "Toggle fold")
(row (kbd "⌘" "↑") "Collapse")
(row (kbd "⌘" "↓") "Expand all"))
(group "History"
(row (kbd "⌘" "Z") "Undo")
(row (kbd "⌘" "⇧" "Z") "Redo"))
(group "View"
(row (kbd "⌘" "\\") "Toggle sidebar")
(row (kbd "⌘" "/") "This panel")
(row (kbd "⌘" "⇧" "E") "Reading mode"))]))
(defn- FloatingControls
"Bottom-right floating buttons: reading mode + hotkey panel toggle."
[{:keys [on-intent reading-mode? hotkeys-visible?]}]
[:div.floating-controls
[:button.floating-btn
{:type "button"
:title "Reading mode (⌘⇧E)"
:aria-label "Toggle reading mode"
:aria-pressed (boolean reading-mode?)
:class (when reading-mode? "is-active")
:on {:click (fn [_] (on-intent {:type :toggle-reading-mode}))}}
"Aa"]
[:button.floating-btn
{:type "button"
:title "Keyboard shortcuts (⌘/)"
:aria-label "Toggle keyboard shortcuts"
:aria-pressed (boolean hotkeys-visible?)
:class (when hotkeys-visible? "is-active")
:on {:click (fn [_] (on-intent {:type :toggle-hotkeys}))}}
"?"]])
(defn App
"Main app - pure composition, no business logic."
[]
(let [db @!db
storage-status @!storage-status
checking? (:checking? storage-status)
embed? (embed-mode?)
current-page-id (vs/lookup [:ui :current-page])
page-title (when current-page-id (q/page-title db current-page-id))
sidebar-visible? (vs/sidebar-visible?)
hotkeys-visible? (vs/hotkeys-visible?)
reading-mode? (vs/reading-mode?)
journals-view? (vs/journals-view?)
quick-switcher-visible? (vs/quick-switcher-visible?)]
[:div {:class (cond-> ["app"]
embed? (conj "app--embed")
reading-mode? (conj "reading-mode"))}
;; Sidebar for page navigation (toggleable via Cmd+\)
;; Always show sidebar - it has the folder picker
(when (and sidebar-visible? (not embed?) (not reading-mode?))
(sidebar/Sidebar {:db db
:on-intent handle-intent
:on-pick-folder pick-folder!
:on-clear-folder clear-folder!
:storage-status storage-status}))
;; Main wrapper - flexbox centering for content
[:div {:class (str "main-wrapper" (when embed? " main-wrapper--embed"))}
;; Main content area - only render after storage check completes
(when-not checking?
[:main {:class (str "main-content" (when embed? " main-content--embed"))
:on {:click (fn [_e]
;; Background click to clear selection (Logseq parity)
(when-not (vs/lookup [:ui :editing-block-id])
(handle-intent {:type :selection :mode :clear})))}}
;; Mock-text for cursor detection
(MockText)
;; Header with navigation
;; Main content area - journals view, current page, or empty state
(cond
;; Journals view - all journals stacked
journals-view?
(journals/JournalsView {:db db :on-intent handle-intent})
;; Single page view
current-page-id
[:div {:class (when embed? "embed-shell")}
;; Editable page title (click to rename)
(when-not embed?
(PageTitle {:page-id current-page-id
:page-title page-title
:on-intent handle-intent}))
;; Main outline for current page only
(Outline {:db db
:root-id current-page-id
:on-intent handle-intent})
;; Backlinks panel - shows "Linked References" from other pages
(when-not embed?
(backlinks/BacklinksPanel {:db db
:page-title page-title
:on-intent handle-intent}))]
;; All Pages view (no page selected)
:else
(all-pages/AllPagesView {:db db :on-intent handle-intent}))
;; Hotkeys reference (toggleable via Cmd+?)
(when hotkeys-visible?
(HotkeysReference))])]
;; Quick Switcher overlay (Cmd+K) - rendered outside main content for proper modal behavior
(when (and quick-switcher-visible? (not embed?))
(quick-switcher/QuickSwitcher {:db db :on-intent handle-intent}))
;; Toast notification (uses Popover API for top-layer rendering)
(when-not embed?
(notification/Notification))
;; Lightbox overlay for fullscreen image viewing
(when-not embed?
(lightbox/Lightbox))
;; Floating controls (bottom-right): reading-mode + hotkeys toggles
(when-not embed?
(FloatingControls {:on-intent handle-intent
:reading-mode? reading-mode?
:hotkeys-visible? hotkeys-visible?}))]))
;; ── Main ──────────────────────────────────────────────────────────────────────
(defn render! []
(d/render (js/document.getElementById "root")
(App)))
;; Batched render using requestAnimationFrame to prevent nested render warnings.
;; When multiple state changes (DB + session) happen in the same frame,
;; this coalesces them into a single render call.
(defonce ^:private render-scheduled? (atom false))
(defn- process-auto-trash-queue!
"Process queued pages for auto-trash check.
Called after render to avoid nested dispatch.
Skipped under `?test=true` — the 100 ms queue otherwise silently
trashes empty fixture pages created by `:create-page` in tests and
takes focus with it through `handle-delete-page`'s session update,
making any multi-page e2e scenario flake. In tests, fixtures are
ephemeral by definition; auto-trash is a prod-side UX feature."
[]
(when-not (test-mode?)
(doseq [page-id (vs/take-auto-trash-queue!)]
(executor/apply-intent! !db
{:type :auto-trash-empty-page
:page-id page-id}
"AUTO-TRASH"))))
(defn request-render!
"Request a render on the next animation frame.
Multiple calls in the same frame are coalesced into one render.
Also processes auto-trash queue after render completes.
Uses a setTimeout safety net: if rAF is throttled (backgrounded tab,
suspended frame loop), the flag would otherwise stay stuck at true
and wedge all future state changes. Whichever fires first wins; the
ran? latch prevents a double-render."
[]
(when-not @render-scheduled?
(reset! render-scheduled? true)
(let [ran? (atom false)
run-once (fn []
(when (compare-and-set! ran? false true)
(reset! render-scheduled? false)
(render!)
(js/setTimeout process-auto-trash-queue! 100)))]
(js/requestAnimationFrame run-once)
(js/setTimeout run-once 250))))
;; ── Test Helpers ──────────────────────────────────────────────────────────────
(defn reset-to-empty-db!
"Reset database to empty state for E2E tests with one empty block.
Exposed on window.TEST_HELPERS for Playwright."
[]
;; Reset DB (document only, no session data). The fixture is the new
;; baseline, so it becomes the log's :root-db (not an undoable action).
(let [initial (:db (tx/interpret
(db/empty-db)
[{:op :create-node :id "test-page" :type :page :props {:title "Test Page"}}
{:op :place :id "test-page" :under :doc :at :last}
{:op :create-node :id "test-block-1" :type :block :props {:text ""}}
{:op :place :id "test-block-1" :under "test-page" :at :last}]))]
(reset! !db initial)
(slog/reset-with-db! initial))
;; Reset session and set current page
(vs/reset-view-state!)
(vs/put! [:ui :journals-view?] false) ; Disable journals view so test-page is visible
(vs/put! [:ui :current-page] "test-page")
;; Clear storage checking state (no folder check needed in test mode)
(swap! !storage-status assoc :checking? false))
(defn- normalize-view-state-updates
"Convert JS/EDN fixture payload into view-state updates with proper sets."
[session]
(cond-> session
(sequential? (get-in session [:selection :nodes]))
(update-in [:selection :nodes] set)
(sequential? (get-in session [:ui :folded]))
(update-in [:ui :folded] set)))
(defn load-fixture!
"Load a fixture payload into the editor for embedded demos/tests.
Payload shape:
{:ops [...]
:session {:selection {:nodes [...] :focus ... :anchor ...}
:ui {:current-page ... :editing-block-id ... :cursor-position ...
:folded [...] :zoom-root ...}}}"
[payload-js]
(let [payload (js->clj payload-js :keywordize-keys true)
ops (mapv (fn [op]
(cond-> op
(:op op) (update :op keyword)
(:type op) (update :type keyword)
(:at op) (update :at keyword)
(and (:under op) (string? (:under op))
(#{"doc" ":doc" "trash" ":trash"} (:under op)))
(update :under #(keyword (str/replace % #"^:" "")))))
(:ops payload))
session (normalize-view-state-updates (or (:session payload) {}))
result (tx/interpret (db/empty-db) ops)
loaded (:db result)]
(reset! !db loaded)
(slog/reset-with-db! loaded)
(vs/reset-view-state!)
(vs/merge-view-state-updates! session)
(swap! !storage-status assoc :checking? false)))
(defn main []
(when ^boolean goog.DEBUG
(js/console.log "Blocks UI starting...")
;; Log uncited intents once (grouped) instead of on each registration
(intent/log-uncited-intents!))
;; Reset to empty DB for E2E tests (handles hot-reload where defonce doesn't re-run)
(when (test-mode?)
(reset-to-empty-db!))
;; Expose test helpers for E2E tests
(set! (.-TEST_HELPERS js/window)
#js {:resetToEmptyDb reset-to-empty-db!
;; First-class affordance so journals.spec doesn't need to
;; click the sidebar nav (flaky under Replicant re-render
;; timing). `reset-to-empty-db!` sets journals-view? false;
;; tests that need journals view must explicitly enter it.
:openJournalsView (fn []
(handle-intent {:type :open-journals-view}))
:dispatchIntent (fn [intent-js]
;; Convert JS object to Clojure map, ensuring keyword fields are keywords
(let [raw (js->clj intent-js :keywordize-keys true)
;; Fields that need keyword values (not just keys)
intent (cond-> raw
(:type raw) (update :type keyword)
(:mode raw) (update :mode keyword)
(:at raw) (update :at keyword)
(:cursor-at raw) (update :cursor-at keyword))]
(handle-intent intent)))
;; Direct DB manipulation for test fixture setup
;; Bypasses state machine (appropriate for setting initial state)
:setBlockText (fn [block-id text]
(swap! !db assoc-in [:nodes block-id :props :text] text))
:getBlockText (fn [block-id]
(get-in @!db [:nodes block-id :props :text] ""))
:getDb (fn [] (clj->js @!db))
:getSession (fn [] (clj->js (vs/get-view-state)))
:showLightbox (fn [src alt]
(lightbox/show! {:src src :alt alt}))
:hideLightbox (fn []
(lightbox/hide!))
:clearFolder (fn []
(clear-folder!))
;; Transact raw ops (for test setup - creates blocks, places them, etc.)
:transact (fn [ops-js]
(let [ops (js->clj ops-js :keywordize-keys true)
;; Convert special string values to keywords
ops (mapv (fn [op]
(cond-> op
(:op op) (update :op keyword)
(:type op) (update :type keyword)
(:at op) (update :at keyword)
;; Handle :under as keyword for special roots
(and (:under op) (string? (:under op))
(#{"doc" ":doc" "trash" ":trash"} (:under op)))
(update :under #(keyword (str/replace % #"^:" "")))))
ops)
result (tx/interpret @!db ops)]
(reset! !db (:db result))))
:loadFixture load-fixture!
;; ── Debug Helpers (for E2E test diagnostics) ────────────────────────
;; Debug an intent - check if it would be allowed and why
:debugIntent (fn [intent-js]
(let [raw (js->clj intent-js :keywordize-keys true)
intent (cond-> raw
(:type raw) (update :type keyword)
(:mode raw) (update :mode keyword))
current-session (vs/get-view-state)
state (sm/current-state current-session)
allowed? (sm/intent-allowed? current-session intent)
requirements (sm/get-intent-requirements (:type intent))]
#js {:allowed allowed?
:currentState (name state)
:intentType (name (:type intent))
:requiredStates (when requirements
(clj->js (mapv name requirements)))
:reason (when-not allowed?
(str "Intent :" (:type intent)
" requires states " (pr-str requirements)
" but current state is :" state))}))
;; Get a snapshot of current app state for debugging
:snapshot (fn []
(let [current-session (vs/get-view-state)]
#js {:state (name (sm/current-state current-session))
:editingBlockId (get-in current-session [:ui :editing-block-id])
:selectedIds (clj->js (vec (get-in current-session [:selection :nodes] #{})))
:focusId (get-in current-session [:selection :focus])
:bufferBlockId (get-in current-session [:buffer :block-id])
:bufferDirty (get-in current-session [:buffer :dirty?])}))
;; Copy full debug state to clipboard for bug reports
:copyDebugState (fn []
(let [current-session (vs/get-view-state)
db-snapshot @!db
debug-data {:timestamp (.toISOString (js/Date.))
:state (sm/current-state current-session)
:session current-session
:db {:nodes (get db-snapshot :nodes)
:children-by-parent (get db-snapshot :children-by-parent)
:roots (get db-snapshot :roots)}
:dom {:activeElement (when-let [el (.-activeElement js/document)]
{:tagName (.-tagName el)
:id (.-id el)
:className (.-className el)
:contentEditable (.-contentEditable el)})
:selection (when-let [sel (.getSelection js/window)]
{:type (.-type sel)
:anchorOffset (.-anchorOffset sel)
:focusOffset (.-focusOffset sel)
:isCollapsed (.-isCollapsed sel)})}}
json-str (js/JSON.stringify (clj->js debug-data) nil 2)]
(-> (js/navigator.clipboard.writeText json-str)
(.then #(js/console.log "✅ Debug state copied to clipboard"))
(.catch #(js/console.error "❌ Failed to copy:" %)))
(js/console.log "Debug state:" debug-data)
json-str))})
(when (and (or (embed-mode?) (fixture-mode?)) (seq (.-name js/window)))
(try
(load-fixture! (.parse js/JSON (.-name js/window)))
(catch :default err
(js/console.error "Failed to load embed fixture from window.name" err))))
;; Phase 2: Expose session for debugging
(set! (.-SESSION js/window) vs/!view-state)
;; Initialize plugin/bootstrap surfaces explicitly.
(plugins/init!)
;; Initialize keyboard bindings (explicit, not side-effect driven)
(bindings/reload!)
;; Initialize IME composition tracking for CJK/emoji input safety
;; Tracks compositionstart/compositionend at document level
(cursor-bounds/setup-composition-tracking!)
;; Fixture demos should be deterministic; persisted recents/favorites from
;; the hosting origin would otherwise erase the seeded sidebar state.
(when-not (fixture-mode?)
(vs/load-persisted-state!))
;; Cleanup old trash (30+ days) and scan for empty pages on startup
;; Deferred to allow DB to load first
(js/setTimeout
(fn []
(when-not (test-mode?)
;; First, mark pages in trash > 30 days as tombstones
(executor/apply-intent! !db {:type :cleanup-old-trash} "STARTUP")
;; Then, garbage collect tombstoned nodes. gc-tombstones bypasses the
;; transaction pipeline (it's housekeeping, not a user action), so we
;; must re-anchor the log to match or undo would resurrect the GC'd
;; nodes. Accepting: GC drops prior undo history.
(swap! !db api/gc-tombstones)
(slog/reset-with-db! @!db)
;; GC purged pages from the db — reconcile their files away too.
(storage/reconcile-files! @!db)
;; Finally, auto-trash any empty pages (except today's journal)
(executor/apply-intent! !db {:type :scan-empty-pages} "STARTUP")))
2000)
;; Note: Current page is set by load-from-folder! after storage check completes
;; Enable lifecycle hooks and function-based DOM handlers.
;; CRITICAL: Lifecycle hooks must still fire for cursor placement
(d/set-dispatch!
(fn [event-data handler-data]
(dispatch-bridge/dispatch-handler-data! event-data handler-data)))
;; Set up global keyboard listener (Cmd+Z, etc)
(.addEventListener js/document "keydown"
(fn [e]
(global-keyboard/handle-keydown !db handle-intent e)))
;; Set up auto-render on state changes (DB, session, and storage status)
;; Uses request-render! to batch multiple changes into single render (prevents nested render warnings)
(add-watch !db :render (fn [_ _ _ _] (request-render!)))
(add-watch vs/!view-state :render (fn [_ _ _ _] (request-render!)))
(add-watch !storage-status :render (fn [_ _ _ _] (request-render!)))
;; Initialize Dataspex for state inspection
;; NOTE: track-changes disabled to prevent memory accumulation during heavy use
;; Only inspect DB and view-state (primary debugging targets)
;; Logs are available via tooling/get-log and tooling/get-clipboard-log from REPL
;; but not in Dataspex to avoid per-intent overhead
(dataspex/inspect "App DB" !db)
(dataspex/inspect "View State" vs/!view-state)
;; Install queryable DEBUG API for AI tools and E2E tests
(debug-api/install! !db)
;; Apply text selection effects from formatting operations
;; Watch session for pending-selection instead of DB
(add-watch vs/!view-state :text-selection-effects
(fn [_ _ _ new-session]
(when-let [{:keys [block-id start end]}
(get-in new-session [:ui :pending-selection])]
(js/requestAnimationFrame
(fn []
(when-let [editable-el (.querySelector js/document
(str "[data-block-id='" block-id "'] .block-content"))]
(try
;; CRITICAL: Update DOM text from DB BEFORE setting selection
;; This ensures formatting changes (e.g., **bold**) are visible in contenteditable
;; Without this, blur handler would commit stale DOM text back to DB
(let [db @!db
db-text (get-in db [:nodes block-id :props :text] "")]
(when (not= (.-textContent editable-el) db-text)
(set! (.-textContent editable-el) db-text)))
;; Use make-range for correct multi-node DOM handling
(let [range (text-sel/make-range editable-el start end)]
(text-sel/set-current-range! range))
(catch js/Error e
(js/console.error "Text selection failed:" e))))
;; Clear pending selection after applying
(vs/put! [:ui :pending-selection] nil))))))
(render!))