-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathsupertag-view-table.el
More file actions
2024 lines (1840 loc) · 93.9 KB
/
Copy pathsupertag-view-table.el
File metadata and controls
2024 lines (1840 loc) · 93.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
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; supertag-view-table.el --- Table view for supertag -*- lexical-binding: t; -*-
;;; Commentary:
;; This module provides a generic, responsive grid UI component that can display
;; any query results with real-time updates from the automation system.
;;
;; Key features:
;; - Data source separation: UI is stateless, data provided by query objects
;; - Reactive updates: Automatically updates when underlying data changes
;; - Generic component: Can display any query results, not just specific tags
;; - Named views: Support for predefined view configurations
;;; Code:
(require 'cl-lib)
(require 'subr-x)
(require 'supertag-core-store)
(require 'supertag-core-notify)
(require 'supertag-ops-node)
(require 'supertag-ops-tag)
(require 'supertag-ops-field)
(require 'supertag-ops-relation)
(require 'supertag-services-formula)
(require 'supertag-services-ui)
(require 'supertag-services-query)
(require 'supertag-view-helper)
(require 'supertag-view-api)
(require 'supertag-view-framework)
(require 'supertag-virtual-column)
(require 'org)
;;; Faces
(defface supertag-view-table-parent-title-face
'((t :inherit shadow))
"Face used for the parent-title line in the Title column."
:group 'supertag-view)
;;; --- Core State Management ---
(defvar-local supertag-view-table--query-objs nil
"List of query objects that provide data for this grid view.")
(defvar-local supertag-view-table--entity-ids nil
"List of entity IDs currently displayed in the grid.")
(defvar-local supertag-view-table--columns nil
"Column configuration for the grid.")
(defvar-local supertag-view-table--current-table-index 0
"Index of currently active table in multi-table view.")
(defun supertag-view-table--normalize-query (query)
"Normalize QUERY while keeping string callers exact for compatibility."
(if (stringp query)
(list :type :tag :value query)
query))
(defun supertag-view-table--query-for-tag (tag)
"Return a query for TAG, aggregating when it has explicit descendants."
(append (list :type :tag :value tag)
(when (supertag-view-api-tag-descendants tag)
'(:include-descendants t))))
(defun supertag-view-table--read-tag-query (&optional prompt choices)
"Read a canonical Tag query."
(let ((tag (supertag-ui-read-tag
(or prompt "View table for tag: ")
(or choices (supertag-view-api-list-tag-ids))
nil nil)))
(supertag-view-table--query-for-tag tag)))
(defun supertag-view-table--aggregate-p (&optional query)
"Return non-nil when QUERY or the current query includes descendants."
(plist-get (or query (supertag-view-table--get-current-query-obj))
:include-descendants))
(defun supertag-view-table--ensure-exact-table ()
"Reject schema and field writes from a descendant aggregate table."
(when (supertag-view-table--aggregate-p)
(user-error "Descendant aggregate tables are read-only")))
(defvar-local supertag-view-table--view-config nil
"View configuration for filtering, sorting, and column selection.")
(defvar-local supertag-view-table--named-views nil
"Alist of named views for the current table. ((\"View Name\" . <view-config-plist>) ...)")
(defvar-local supertag-view-table--current-view-name nil
"Name of the currently active view.")
;;; --- Layout Registry and Render Dispatcher ---
(defvar supertag-view-table--layout-registry (make-hash-table :test 'equal)
"Registry of layout renderers for view-table. Keys are symbols, values are functions.")
(defun supertag-view-table-register-layout (layout fn)
"Register a renderer FN for LAYOUT symbol."
(puthash layout fn supertag-view-table--layout-registry))
(defcustom supertag-view-table-default-layout 'table
"Default layout used by view-table renderer dispatcher."
:type '(choice (const table) (symbol))
:group 'supertag-view)
(defconst supertag-view-table--refs-field-name "Refs"
"Display name for the default reference field.")
(defconst supertag-view-table--refs-field-id "refs"
"Canonical field id for the default reference field.")
(defun supertag-view-table-render (layout state)
"Render STATE using LAYOUT. STATE is a plist produced by `supertag-view-table--build-state'."
(let* ((lo (or layout supertag-view-table-default-layout 'table))
(fn (gethash lo supertag-view-table--layout-registry)))
(unless (functionp fn)
(error "No renderer registered for layout: %s" lo))
(funcall fn state)))
;;; --- State Builder (data layer) ---
(defun supertag-view-table--build-state ()
"Build a render-agnostic state plist for the current table buffer.
Returns a plist with keys:
:columns - column definitions (list of plists)
:rows - rows as list of plists (:id and :values alist)
:meta - additional info (view config, options)"
(let* ((columns supertag-view-table--columns)
(entity-ids supertag-view-table--entity-ids)
(rows (cl-loop for eid in entity-ids
for data = (supertag-view-table--get-entity-data eid)
when data
collect (list :id eid
:values (cl-loop for col in columns
for key = (plist-get col :key)
collect (cons key (supertag-view-table--get-cell-value data key col))))))
(meta (list :view-config supertag-view-table--view-config
:current-view-name supertag-view-table--current-view-name
:query-obj (supertag-view-table--get-current-query-obj))))
(list :columns columns :rows rows :meta meta)))
;;; --- Expanded Rows (Inline Details) ---
(defvar-local supertag-view-table--expanded-rows (make-hash-table :test 'equal)
"Set of expanded row entity-ids for inline details.")
(defun supertag-view-table--row-expanded-p (entity-id)
(and entity-id (gethash entity-id supertag-view-table--expanded-rows)))
(defun supertag-view-table--expand-row (entity-id)
(when entity-id (puthash entity-id t supertag-view-table--expanded-rows)))
(defun supertag-view-table--collapse-row (entity-id)
(when entity-id (remhash entity-id supertag-view-table--expanded-rows)))
(defun supertag-view-table-toggle-row-details ()
"Toggle inline details under the current row."
(interactive)
(let* ((coords (supertag-view-table--get-cell-coords))
(entity-id (and coords (plist-get coords :entity-id))))
(if (not entity-id)
(message "No row selected")
(if (supertag-view-table--row-expanded-p entity-id)
(supertag-view-table--collapse-row entity-id)
(supertag-view-table--expand-row entity-id))
(supertag-view-table-refresh))))
(defun supertag-view-table-expand-all-rows ()
"Expand inline details for all rows."
(interactive)
(clrhash supertag-view-table--expanded-rows)
(dolist (eid supertag-view-table--entity-ids)
(puthash eid t supertag-view-table--expanded-rows))
(supertag-view-table-refresh))
(defun supertag-view-table-collapse-all-rows ()
"Collapse inline details for all rows."
(interactive)
(clrhash supertag-view-table--expanded-rows)
(supertag-view-table-refresh))
(defcustom supertag-view-table-image-target-char-height 5
"Image target display height in table cells (in character lines)."
:type 'integer
:group 'supertag-view)
(defcustom supertag-view-table-image-max-width-ratio 0.8
"Maximum ratio of image width to cell content space."
:type 'float
:group 'supertag-view)
(defcustom supertag-view-table-image-column-width 14
"Default display width of image column (in characters)."
:type 'integer
:group 'supertag-view)
(defcustom supertag-view-table-per-tag-image-widths nil
"Image column width settings for each tag, format: ((tag1 . width1) (tag2 . width2) ...)"
:type '(alist :key-type string :value-type integer)
:group 'supertag-view)
;;; --- TODO State Handling ---
(defcustom supertag-view-table-strip-todo-keywords t
"Whether to strip TODO keywords from node titles in table view.
If non-nil, TODO keywords will be removed from titles.
If nil, titles will be displayed as-is with TODO keywords."
:type 'boolean
:group 'supertag-view)
(defcustom supertag-view-table-todo-keywords
'("TODO" "DONE" "NEXT" "WAITING" "HOLD" "CANCELLED" "CANCELED"
"STARTED" "DELEGATED" "DEFERRED" "SOMEDAY")
"List of TODO keywords to strip from node titles in table view.
Only used when `supertag-view-table-strip-todo-keywords' is non-nil.
You can customize this list to match your org-mode TODO keywords."
:type '(repeat string)
:group 'supertag-view)
(defun supertag-view-table--strip-todo-keyword (title)
"Remove TODO keywords from TITLE if configured to do so.
Removes org-mode TODO keywords based on `supertag-view-table-todo-keywords'.
Only strips keywords if `supertag-view-table-strip-todo-keywords' is non-nil."
(if (not supertag-view-table-strip-todo-keywords)
title
(let ((keywords-regexp (concat "^\\("
(mapconcat #'regexp-quote
supertag-view-table-todo-keywords
"\\|")
"\\)\\s-+")))
(if (string-match keywords-regexp title)
(string-trim (substring title (match-end 0)))
title))))
;;; --- Grid Rendering Engine ---
(defun supertag-view-table--view-input (data-source columns view-config named-views)
"Normalize Table view arguments into one Runtime input plist."
(let ((query-objs
(cond
((and (listp data-source) (keywordp (car data-source)))
(list (supertag-view-table--normalize-query data-source)))
((and (listp data-source)
(listp (car data-source))
(keywordp (caar data-source)))
(mapcar #'supertag-view-table--normalize-query data-source))
(t
(list (supertag-view-table--normalize-query data-source))))))
(list :query-objs query-objs
:columns columns
:view-config view-config
:named-views named-views)))
(defun supertag-view-table--view-buffer-name (input)
"Return the Table buffer name for Runtime INPUT."
(let ((query-objs (plist-get input :query-objs)))
(if (> (length query-objs) 1)
"*Supertag Multi-Table*"
(format "*Supertag Table: %s*"
(plist-get (car query-objs) :value)))))
(defun supertag-view-table--initialize-view (input)
"Initialize and render the current Table buffer from Runtime INPUT."
(let* ((query-objs (plist-get input :query-objs))
(query (car query-objs))
(entity-ids (supertag-view-table--get-entities query))
(columns (or (plist-get input :columns)
(supertag-view-table--get-columns query)))
(view-config (plist-get input :view-config))
(named-views (plist-get input :named-views)))
(setq-local truncate-lines t)
(setq-local supertag-view-table--query-objs query-objs)
(setq-local supertag-view-table--entity-ids entity-ids)
(setq-local supertag-view-table--columns columns)
(setq-local supertag-view-table--current-table-index 0)
(setq-local supertag-view-table--view-config view-config)
(setq-local supertag-view-table--named-views named-views)
(setq-local supertag-view-table--current-view-name
(and named-views (stringp (caar named-views))
(caar named-views)))
(when-let* ((active-config
(or view-config
(and supertag-view-table--current-view-name
(cdr (assoc supertag-view-table--current-view-name
named-views))))))
(supertag-view-table--apply-view-config active-config))
(supertag-view-table-render
supertag-view-table-default-layout
(supertag-view-table--build-state))
(supertag-view-table--goto-first-cell)
(message "Rendered table with %d entities" (length entity-ids))))
(defun supertag-view-table--render-view (input)
"Render Runtime INPUT, preserving live Table configuration on refresh."
(if supertag-view-table--query-objs
(supertag-view-table--refresh-current)
(supertag-view-table--initialize-view input)))
(defun supertag-view-table--capture-selection ()
"Return the current Table cell selection."
(supertag-view-table--get-cell-coords-robust))
(defun supertag-view-table--restore-selection (selection)
"Restore opaque Table cell SELECTION when it still exists."
(when-let* ((entity-id (plist-get selection :entity-id)))
(let ((col-key (plist-get selection :col-key))
match
position)
(goto-char (point-min))
(while (and (not position)
(setq match (text-property-search-forward
'entity-id entity-id t)))
(when (eq (get-text-property (prop-match-beginning match) 'col-key)
col-key)
(setq position (prop-match-beginning match))))
(when position
(goto-char position)))))
(defun supertag-view-table--subscribe-view (_input _state refresh)
"Subscribe the Table Adapter and call REFRESH for relevant Store changes."
(supertag-view-api-subscribe
:store-changed
(lambda (path _old-value _new-value)
(when (and (listp path)
(memq (car path)
'(:nodes :databases :automations :behaviors
:field-values :tags :field-definitions
:tag-field-associations)))
(funcall refresh)))))
(defun supertag-view-table--display-buffer (buffer _alist)
"Display Table BUFFER using the existing main-window policy."
(let* ((current-window (selected-window))
(target-window
(if (window-parameter current-window 'window-side)
(or (when (fboundp 'window-main-window)
(window-main-window (selected-frame)))
(frame-root-window))
current-window)))
(when (window-live-p target-window)
(select-window target-window)
(set-window-buffer target-window buffer)
(set-window-scroll-bars target-window nil t nil t)
target-window)))
(defun supertag-view-table--register-view ()
"Register the Table Adapter when needed."
(unless (supertag-view-get 'table)
(supertag-view-register
:id 'table
:name "Table"
:selectable nil
:buffer-name-fn #'supertag-view-table--view-buffer-name
:mode-fn #'supertag-view-table-mode
:state-fn #'identity
:render-fn #'supertag-view-table--render-view
:subscribe-fn #'supertag-view-table--subscribe-view
:capture-selection-fn #'supertag-view-table--capture-selection
:restore-selection-fn #'supertag-view-table--restore-selection
:display-action '(supertag-view-table--display-buffer))))
(defun supertag-view-table (data-source &optional columns view-config named-views)
"Interactive table view for various data sources.
DATA-SOURCE can be:
- A tag name (string) for nodes with that tag
- A plist with :type and :value for specific data types
- A list of query objects for multi-table view
- A function that returns a list of entity IDs
COLUMNS is an optional list of column configurations.
VIEW-CONFIG is an optional view configuration plist with:
- :fields - List of visible field names
- :sort - Sort configuration (:field and :order)
- :filter - Filter conditions
- :group-by - Grouping field
NAMED-VIEWS is an alist of pre-defined views.
If called interactively without DATA-SOURCE, prompts for data source selection."
(interactive
(list (supertag-view-table--read-tag-query)))
(supertag-view-table--register-view)
(supertag-view-open
'table
(supertag-view-table--view-input
data-source columns view-config named-views)))
(defun supertag-view-table--apply-view-config (view-config)
"Apply VIEW-CONFIG to current table state."
(when view-config
(let ((visible-fields (plist-get view-config :visible-fields))
(sort-config (plist-get view-config :sort))
(filter-config (plist-get view-config :filter)))
;; Filter columns based on visible fields
(when visible-fields
(setq-local supertag-view-table--columns
(cl-remove-if-not
(lambda (col)
(or (memq (plist-get col :key) '(:title :refs))
(member (symbol-name (plist-get col :key)) visible-fields)))
supertag-view-table--columns)))
;; Apply sorting
(when sort-config
(setq-local supertag-view-table--entity-ids
(supertag-view-table--apply-sorting supertag-view-table--entity-ids sort-config)))
;; Apply filtering
(when filter-config
(setq-local supertag-view-table--entity-ids
(supertag-view-table--apply-filtering supertag-view-table--entity-ids filter-config))))))
(defun supertag-view-table--apply-sorting (entity-ids sort-config)
"Apply sorting to ENTITY-IDS based on SORT-CONFIG."
(let ((sort-field (plist-get sort-config :field))
(sort-order (or (plist-get sort-config :order) :asc)))
(sort entity-ids
(lambda (a b)
(let* ((entity-a (supertag-view-table--get-entity-data a))
(entity-b (supertag-view-table--get-entity-data b))
(value-a (supertag-view-table--get-sort-value entity-a sort-field))
(value-b (supertag-view-table--get-sort-value entity-b sort-field)))
(if (eq sort-order :desc)
(supertag-view-table--compare-sort-values value-b value-a)
(supertag-view-table--compare-sort-values value-a value-b)))))))
(defun supertag-view-table--get-sort-value (entity-data field)
"Get sort value from ENTITY-DATA for FIELD."
(pcase field
('title (plist-get entity-data :title))
('created-at (plist-get entity-data :created-at))
('modified-at (plist-get entity-data :modified-at))
('todo (plist-get entity-data :todo))
('priority (plist-get entity-data :priority))
(_
;; Check properties
(let ((props (plist-get entity-data :properties)))
(plist-get props (intern (format ":%s" field)))))))
(defun supertag-view-table--compare-sort-values (a b)
"Compare two sort values A and B."
(cond
((and (null a) (null b)) nil)
((null a) t)
((null b) nil)
((and (numberp a) (numberp b)) (< a b))
((and (stringp a) (stringp b)) (string< a b))
((and (listp a) (listp b)) ; timestamps
(time-less-p a b))
(t (string< (format "%s" a) (format "%s" b)))))
(defun supertag-view-table--apply-filtering (entity-ids filter-config)
"Apply filtering to ENTITY-IDS based on FILTER-CONFIG."
(cl-remove-if-not
(lambda (entity-id)
(let ((entity-data (supertag-view-table--get-entity-data entity-id)))
(supertag-view-table--evaluate-filter-condition entity-data filter-config)))
entity-ids))
(defun supertag-view-table--evaluate-filter-condition (entity-data condition)
"Evaluate a filter CONDITION against ENTITY-DATA."
(pcase (car condition)
('and
(cl-every (lambda (sub-condition)
(supertag-view-table--evaluate-filter-condition entity-data sub-condition))
(cdr condition)))
('or
(cl-some (lambda (sub-condition)
(supertag-view-table--evaluate-filter-condition entity-data sub-condition))
(cdr condition)))
('not
(not (supertag-view-table--evaluate-filter-condition entity-data (cadr condition))))
('field
(let* ((field-name (cadr condition))
(operator (caddr condition))
(expected-value (cadddr condition))
(query-obj (supertag-view-table--get-current-query-obj))
(actual-value
(pcase (plist-get query-obj :type)
(:tag
;; For tag queries, get field value using default-aware accessor
(let* ((node-id (plist-get entity-data :id))
(tag-id (supertag-view-table--get-current-tag-id))
;; Remove leading colon from field-name if present
(clean-field-name (if (string-prefix-p ":" field-name)
(substring field-name 1)
field-name)))
(when (and node-id tag-id)
(supertag-query-field-value node-id tag-id clean-field-name))))
(_
;; For other query types, try properties first
(let ((props (plist-get entity-data :properties)))
(plist-get props (intern field-name)))))))
(supertag-view-table--compare-values actual-value operator expected-value)))
('title
(let* ((operator (cadr condition))
(expected-value (caddr condition))
(actual-value (plist-get entity-data :title)))
(supertag-view-table--compare-values actual-value operator expected-value)))
('tag
(let* ((operator (cadr condition))
(expected-tag (caddr condition))
(tags (plist-get entity-data :tags)))
(pcase operator
('has (member expected-tag tags))
('not-has (not (member expected-tag tags)))
(_ nil))))
(_ nil)))
(defun supertag-view-table--compare-values (actual operator expected)
"Compare ACTUAL value with EXPECTED using OPERATOR."
(pcase operator
('= (equal actual expected))
('!= (not (equal actual expected)))
('> (and (numberp actual) (numberp expected) (> actual expected)))
('< (and (numberp actual) (numberp expected) (< actual expected)))
('>= (and (numberp actual) (numberp expected) (>= actual expected)))
('<= (and (numberp actual) (numberp expected) (<= actual expected)))
('contains (and (stringp actual) (stringp expected) (string-match-p expected actual)))
('starts-with (and (stringp actual) (stringp expected) (string-prefix-p expected actual)))
('ends-with (and (stringp actual) (stringp expected) (string-suffix-p expected actual)))
('empty (or (null actual) (and (stringp actual) (string-empty-p actual))))
('not-empty (not (or (null actual) (and (stringp actual) (string-empty-p actual)))))
(_ nil)))
(defun supertag-view-table--select-multiple-tags ()
"Select multiple tags for multi-table view."
(let* ((available-tags (supertag-view-api-list-tag-ids))
(selected-tags '()))
(while (let ((tag (supertag-ui-read-tag
"Select tag (empty finishes): "
available-tags nil t)))
(when (and tag (not (string-empty-p tag)))
(push (supertag-view-table--query-for-tag tag) selected-tags)
(setq available-tags (delete tag available-tags))
t)))
(nreverse selected-tags)))
(defun supertag-view-table--get-entities (query-obj)
"Get entity IDs based on QUERY-OBJ configuration."
(supertag-view-api-list-entity-ids query-obj))
(defun supertag-view-table--get-columns (query-obj)
"Get column configuration based on QUERY-OBJ."
(pcase (plist-get query-obj :type)
(:tag
(if (supertag-view-table--aggregate-p query-obj)
'((:name "Title" :key :title :width 40)
(:name "Tags" :key :tags :width 28)
(:name "File" :key :file :width 36))
(supertag-view-table--get-columns-for-tag
(plist-get query-obj :value))))
(:behavior
'((:name "Name" :key :name :width 30)
(:name "Trigger" :key :trigger :width 15)
(:name "Action" :key :action :width 15)
(:name "Enabled" :key :enabled :width 10 :type :boolean)))
(:automation
'((:name "Name" :key :name :width 30)
(:name "Description" :key :description :width 40)
(:name "Trigger" :key :trigger :width 15)
(:name "Enabled" :key :enabled :width 10 :type :boolean)))
(_
(supertag-view-table--default-columns))))
(defun supertag-view-table-select-tag ()
"Interactive table view with tag selection from list.
Prompts user to select a tag from available tags."
(interactive)
(supertag-view-table
(supertag-view-table--read-tag-query "Select tag: ")))
(defun supertag-view-table--get-available-tags ()
"Return canonical Tag IDs."
(sort (delete-dups (supertag-view-api-list-tag-ids)) #'string<))
(defun supertag-tag-get-id-by-name (tag-name)
"Get tag ID by TAG-NAME."
(supertag-view-api-tag-id tag-name))
(defun supertag-view-table--ensure-refs-field (tag-id)
"Ensure the Refs node-reference field exists and is associated with TAG-ID."
(when (and tag-id (stringp tag-id))
(unless (supertag-global-field-get supertag-view-table--refs-field-id)
(supertag-global-field-create
(list :id supertag-view-table--refs-field-id
:name supertag-view-table--refs-field-name
:type :node-reference)))
(unless (supertag-tag-get-field tag-id supertag-view-table--refs-field-name)
(supertag-tag-associate-field tag-id supertag-view-table--refs-field-id))))
(defun supertag-view-table--get-columns-for-tag (tag-name)
"Get column configuration for TAG-NAME, including custom fields with type information.
Automatically detects virtual databases and uses their database fields."
(let ((tag-id (supertag-tag-get-id-by-name tag-name)))
(if (not tag-id)
(supertag-view-table--default-columns)
(let* ((fields (supertag-query-resolved-fields tag-id)) ; Includes inherited fields.
(base-columns '((:name "Title" :key :title :width 40)))
(refs-field (cl-find supertag-view-table--refs-field-id fields
:key (lambda (f)
(or (plist-get f :id)
(supertag-sanitize-field-id (plist-get f :name))))
:test #'equal))
(refs-name (or (plist-get refs-field :name) supertag-view-table--refs-field-name))
(refs-column (list (append `(:name ,refs-name
:key :refs
:field-id ,supertag-view-table--refs-field-id
:type :node-reference
:width 20)
refs-field)))
(seen (make-hash-table :test 'equal))
(field-columns
(cl-loop for field-def in fields
for raw-name = (plist-get field-def :name)
for fid = (or (plist-get field-def :id) raw-name)
for slug = (and fid (supertag-sanitize-field-id fid))
for dedupe-key = slug
unless (or (null dedupe-key)
(and slug (equal slug supertag-view-table--refs-field-id))
(gethash dedupe-key seen))
do (puthash dedupe-key t seen)
and collect (let ((col `(:name ,raw-name
:key ,(intern (or slug raw-name))
:field-id ,slug
:width 20)))
;; Keep the full field definition (type/options etc.)
(append col field-def)))))
(append base-columns field-columns refs-column
;; Add virtual columns
(supertag-view-table--get-virtual-columns))))))
(defun supertag-view-table--get-virtual-columns ()
"Get virtual columns as table column definitions."
(when (fboundp 'supertag-virtual-column-list)
(let ((vcols (supertag-virtual-column-list)))
(cl-loop for vcol in vcols
for id = (plist-get vcol :id)
for name = (plist-get vcol :name)
for type = (plist-get vcol :type)
collect (list :name name
:key (intern (concat ":" id))
:virtual-column id
:type :virtual-column
:width 15)))))
(defun supertag-view-table--default-columns ()
"Return default column configuration."
`((:name "Title" :key :title :width 40)
(:name ,supertag-view-table--refs-field-name
:key :refs
:field-id ,supertag-view-table--refs-field-id
:type :node-reference
:width 20)))
(defun supertag-view-table--render-table (state)
"Renderer for layout 'table'. Consumes STATE built by `supertag-view-table--build-state'."
(let* ((inhibit-read-only t)
(columns (plist-get state :columns))
(rows (plist-get state :rows))
(query-obj (supertag-view-table--get-current-query-obj)))
(erase-buffer)
;; Calculate dynamic column widths from data
(let* ((headers (mapcar (lambda (col) (plist-get col :name)) columns))
(data-rows (mapcar (lambda (row)
(mapcar (lambda (col)
(let* ((key (plist-get col :key))
(pair (assoc key (plist-get row :values))))
(cdr pair)))
columns))
rows))
(calculated-widths (supertag-view-table--calculate-column-widths headers data-rows))
(table-info (when query-obj
(format "Table: %s%s (%d/%d)"
(plist-get query-obj :value)
(if (supertag-view-table--aggregate-p query-obj)
" + descendants"
"")
(1+ supertag-view-table--current-table-index)
(length supertag-view-table--query-objs))))
(view-info (if supertag-view-table--current-view-name
(format "View: %s" supertag-view-table--current-view-name)
"View: Default"))
(full-header (string-join (list table-info view-info) " | "))
;; Update live columns with widths
(updated-columns (cl-loop for col in columns
for width in calculated-widths
collect (plist-put (copy-sequence col) :width width))))
(setq supertag-view-table--columns updated-columns)
;; Table info above the table
(when full-header
(insert (propertize full-header 'face '(:weight bold :foreground "blue")) "\n\n"))
;; Top border
(insert (supertag-view-table--draw-separator "┌" "┬" "┐") "\n")
;; Header row
(let ((header-parts (cl-loop for col in updated-columns
for width in (mapcar (lambda (c) (plist-get c :width)) updated-columns)
collect (propertize (format " %s " (supertag-view-table--pad-string (plist-get col :name) width))
'face 'bold))))
(insert (format "│%s│" (string-join header-parts "│")) "\n"))
;; Header separator
(insert (supertag-view-table--draw-separator "├" "┼" "┤") "\n")
;; Body rows
(let ((processed-rows
(mapcar (lambda (row)
(let* ((eid (plist-get row :id))
(widths (mapcar (lambda (c) (plist-get c :width)) updated-columns)))
(cl-loop for col in updated-columns
for width in widths
for col-idx from 0
for key = (plist-get col :key)
for val = (cdr (assoc key (plist-get row :values)))
collect (let ((lines (supertag-view-table--format-cell val width)))
(list :entity-id eid :col-index col-idx :col-key key :lines lines)))))
rows)))
(dolist (prow processed-rows)
(when prow
(let* ((row-height (apply #'max (cons 1 (mapcar (lambda (cell) (length (plist-get cell :lines))) prow))))
(output-lines '()))
(dotimes (line-idx row-height)
(let ((line-parts
(cl-loop for p-cell in prow
collect (let* ((lines (plist-get p-cell :lines))
(content-part (or (nth line-idx lines) ""))
(width (plist-get (nth (plist-get p-cell :col-index) updated-columns) :width))
(padded (supertag-view-table--pad-string content-part width)))
(propertize (format " %s " padded)
'entity-id (plist-get p-cell :entity-id)
'supertag-entity-id (plist-get p-cell :entity-id)
'col-index (plist-get p-cell :col-index)
'col-key (plist-get p-cell :col-key))))))
(push (format "│%s│" (string-join line-parts "│")) output-lines)))
(insert (string-join (nreverse output-lines) "\n"))
;; Expanded inline details (read-only, no cell props)
(let ((eid (plist-get (car prow) :entity-id)))
(when (supertag-view-table--row-expanded-p eid)
(insert "\n")
(supertag-view-table--insert-expanded-details eid)))
(unless (eq prow (car (last processed-rows)))
(insert "\n" (supertag-view-table--draw-separator "├" "┼" "┤") "\n"))))))
;; Bottom border
(insert "\n" (supertag-view-table--draw-separator "└" "┴" "┘"))
;; Footer
(insert "\n\n")
(supertag-view-helper-insert-simple-footer
"⌨️ Edit: [RET] Edit Cell | [C-c C-i] Insert Image | [w] Adjust Image Width"
"📊 Columns: [C-c C-a] Add | [C-c C-d] Delete | [C-c C-r] Rename | [C-c C-t] Set Type"
"🔍 Filter: [/] Apply Filter | [C-c /] Clear Filter | [C-c v s] Switch View"
"📍 Navigation: [n/p] Line | [f/b] Cell | [TAB] Next Cell | [t] Switch Table | [o] Goto Node | [C-o] Goto Ref"
"🔧 Actions: [g] Refresh | [?] Help | [q] Quit")
;; Move to first cell
(supertag-view-table--goto-first-cell)
(setq buffer-read-only t))))
(defun supertag-view-table--pad-string (text width)
"Pad TEXT with spaces to fit WIDTH while respecting maximum cell width."
(let* ((text-str (truncate-string-to-width (if (stringp text) text (format "%s" text)) width 0 nil))
(padding (- width (string-width text-str))))
(if (> padding 0)
(concat text-str (make-string padding ?\s))
text-str)))
;;; --- Additional Layouts: Node Detail ---
(defun supertag-view-table--build-node-detail-state (node-id)
"Build a minimal state plist for rendering NODE-ID via the node-detail layout.
This uses `supertag-view-build-node-state' to obtain the data-only node view."
(let ((node-state (supertag-view-build-node-state node-id)))
(when node-state
(list :layout 'node-detail
:node-state node-state))))
(defun supertag-view-table--render-node-detail (state)
"Render a single node detail card from STATE in the current buffer.
STATE is expected to contain a :node-state plist built by
`supertag-view-build-node-state'."
(let* ((node-state (plist-get state :node-state))
(node (plist-get node-state :node))
(node-id (plist-get node-state :id)))
(let ((inhibit-read-only t))
(erase-buffer)
(cond
;; 优先复用现有的 Node View 渲染函数(如果已加载)。
((and node-state (fboundp 'supertag-view-node--render-from-state))
(supertag-view-node--render-from-state node-state))
;; 简单回退:只显示标题和 ID。
(node
(let* ((title (or (plist-get node :title) "Untitled Node")))
(insert (format "📄 %s\n\n" title))
(insert (format "ID: %s\n" node-id))))
(t
(insert "Node not found."))))))
;; Register default table layout renderer + node-detail layout at load time.
(ignore-errors
(supertag-view-table-register-layout 'table #'supertag-view-table--render-table)
(supertag-view-table-register-layout 'node-detail #'supertag-view-table--render-node-detail))
(defun supertag-view-table--calculate-column-widths (headers data-rows)
"Calculate the optimal column widths based on headers and data.
HEADERS is a list of strings for the column titles.
DATA-ROWS is a list of lists, where each inner list represents a row.
Returns a list of integers representing the calculated width for each column."
(when (or headers data-rows)
(let* ((num-columns (length headers))
(min-width 8) ; Minimum width for any column
(max-width 50) ; Maximum width for any column
(widths (make-list num-columns 0))
(current-tag (supertag-view-table--get-current-tag-id))
(image-width (if current-tag
(supertag-view-table--get-image-column-width-for-tag current-tag)
supertag-view-table-image-column-width)))
;; 1. Calculate initial widths from headers
(dotimes (i num-columns)
(setf (nth i widths) (max min-width (string-width (nth i headers)))))
;; 2. Expand widths based on data rows
(dolist (row data-rows)
(dotimes (i num-columns)
(when (< i (length row))
(let* ((cell-content (format "%s" (or (nth i row) "")))
(content-width
(if (supertag-view-table--is-image-path-p cell-content)
image-width
(string-width cell-content))))
(setf (nth i widths) (max (nth i widths) content-width))))))
;; 3. Apply max width constraint
(dotimes (i num-columns)
(setf (nth i widths) (min max-width (nth i widths))))
;; 4. (Future) Adjust total width to fit window size.
;; For now, we just return the calculated widths.
widths)))
(defun supertag-view-table--render-header ()
"Render the grid header with column names only.
Table information is now displayed separately above the table."
(let ((header-parts (cl-loop for col in supertag-view-table--columns
for width in (mapcar (lambda (c) (plist-get c :width)) supertag-view-table--columns)
collect (propertize
(format " %s " (supertag-view-table--pad-string (plist-get col :name) width))
'face 'bold))))
(insert (format "│%s│" (string-join header-parts "│")))))
(defun supertag-view-table--draw-separator (&optional left mid right)
"Draw a horizontal separator line with configurable characters.
LEFT, MID, RIGHT are the characters for left-end, middle, and right-end.
Uses improved styling from old version."
(let* ((left (or left "├"))
(mid (or mid "┼"))
(right (or right "┤"))
(widths (mapcar (lambda (c) (plist-get c :width)) supertag-view-table--columns))
(segments (mapcar (lambda (w) (make-string (+ w 2) ?─)) widths)))
(format "%s%s%s" left (string-join segments mid) right)))
(defun supertag-view-table--get-entity-data (entity-id)
"Get entity data based on current query type."
(let ((query-obj (supertag-view-table--get-current-query-obj)))
(pcase (plist-get query-obj :type)
(:tag
(supertag-view-api-get-entity :nodes entity-id))
(:behavior
(supertag-view-api-get-entity :behaviors entity-id))
(:automation
(supertag-view-api-get-entity :automations entity-id))
(:database
(supertag-view-api-get-entity :databases entity-id))
(_
(supertag-view-api-get-entity (plist-get query-obj :type) entity-id)))))
(defun supertag-view-table--get-referenced-by (node-id)
"Return node IDs that reference NODE-ID."
(when node-id
(let ((relations (supertag-query-relations-to node-id :reference)))
(cl-remove-if-not #'stringp
(mapcar (lambda (rel) (plist-get rel :from)) relations)))))
(defun supertag-view-table--get-references (node-id)
"Return node IDs referenced by NODE-ID."
(when node-id
(let ((relations (supertag-query-relations-from node-id :reference)))
(cl-remove-if-not #'stringp
(mapcar (lambda (rel) (plist-get rel :to)) relations)))))
(defun supertag-view-table--merge-reference-values (field-value relation-ids)
"Merge FIELD-VALUE with RELATION-IDS, preserving FIELD-VALUE order."
(let* ((field-ids (supertag-field-normalize-node-reference-list field-value))
(rel-ids (cl-remove-duplicates
(cl-remove-if-not #'stringp relation-ids)
:test #'string=))
(extras (cl-remove-if (lambda (id) (member id field-ids)) rel-ids)))
(append field-ids extras)))
(defun supertag-view-table--format-reference-sources (node-id)
"Format backlinks for NODE-ID as a multi-line string with jump metadata."
(let ((refs (supertag-view-table--get-referenced-by node-id)))
(if (null refs)
""
(mapconcat
(lambda (ref-id)
(let* ((node (supertag-view-api-get-entity :nodes ref-id))
(raw-title (or (plist-get node :raw-value)
(plist-get node :title)
"[Untitled]"))
(display-title (if (fboundp 'org-link-display-format)
(org-link-display-format raw-title)
raw-title))
(clean-title (supertag-view-table--strip-todo-keyword display-title))
(rendered (supertag-view-helper-render-org-links (string-trim clean-title))))
(when (and rendered (> (length rendered) 0))
(add-text-properties 0 (length rendered)
`(supertag-ref-id ,ref-id)
rendered))
rendered))
refs
"\n"))))
(defun supertag-view-table--format-node-reference-values (value)
"Format node-reference VALUE as a multi-line string with jump metadata."
(let ((refs (supertag-field-normalize-node-reference-list value)))
(if (null refs)
""
(mapconcat
(lambda (ref-id)
(let* ((node (supertag-view-api-get-entity :nodes ref-id))
(raw-title (or (plist-get node :raw-value)
(plist-get node :title)
"[Untitled]"))
(display-title (if (fboundp 'org-link-display-format)
(org-link-display-format raw-title)
raw-title))
(clean-title (supertag-view-table--strip-todo-keyword display-title))
(rendered (supertag-view-helper-render-org-links (string-trim clean-title))))
(when (and rendered (> (length rendered) 0))
(add-text-properties 0 (length rendered)
`(supertag-ref-id ,ref-id)
rendered))
rendered))
refs
"\n"))))
(defun supertag-view-table--field-name-for-column (column key)
"Return the field name string for COLUMN/KEY."
(or (plist-get column :field-id)
(plist-get column :name)
(symbol-name key)))
(defun supertag-view-table--get-cell-value (entity-data key column)
"Get cell value from ENTITY-DATA for KEY, formatted according to COLUMN type."
(let ((query-obj (supertag-view-table--get-current-query-obj)))
(let* ((col-type (plist-get column :type))
(raw-value
(pcase (plist-get query-obj :type)
(:tag
(pcase key
(:title
(let* ((raw-title (or (plist-get entity-data :title) "No Title"))
(base-title (supertag-view-table--strip-todo-keyword raw-title))
;; Render org-style links inside the title so [[id:...][desc]]
;; shows as clickable `desc` within the cell.
(rendered-title (supertag-view-helper-render-org-links base-title))
(olp (plist-get entity-data :olp))
(parent-title (and (listp olp)
(> (length olp) 1)
;; OLP is [root ... parent current]
(nth (- (length olp) 2) olp))))
(if (and parent-title (not (string-empty-p parent-title)))
;; First line: current title (with org links rendered);
;; second line: parent title (subdued).
(concat rendered-title "\n"
(propertize parent-title 'face 'supertag-view-table-parent-title-face))
rendered-title)))
(:refs
(let* ((node-id (plist-get entity-data :id))
(tag-id (supertag-view-table--get-current-tag-id))
(field-name (supertag-view-table--field-name-for-column column key))
(field-value (when (and node-id tag-id)
(supertag-view-api-node-field-in-tag node-id tag-id field-name)))
(rel-ids (supertag-view-table--get-references node-id)))
(supertag-view-table--merge-reference-values field-value rel-ids)))
(:file (or (plist-get entity-data :file) "No File"))
(:tags (string-join (plist-get entity-data :tags) ", "))
(_
(let* ((node-id (plist-get entity-data :id))
(tag-id (supertag-view-table--get-current-tag-id))
(field-name (supertag-view-table--field-name-for-column column key))
(vc-id (plist-get column :virtual-column)))
(cond
;; Virtual columns
((and vc-id (fboundp 'supertag-virtual-column-get))
(supertag-virtual-column-get node-id vc-id))