-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMenuModel.js
More file actions
1049 lines (914 loc) · 35.4 KB
/
Copy pathMenuModel.js
File metadata and controls
1049 lines (914 loc) · 35.4 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
function stripJsonc(raw) {
return String(raw || "")
.replace(/^\s*\/\/[^\n]*(\n|$)/gm, "")
.replace(/,(\s*[}\]])/g, "$1")
}
function normalizeAliases(value) {
if (Array.isArray(value)) return value.filter(function(v) { return v })
if (typeof value === "string" && value) return [value]
return []
}
function normalizeItem(id, raw) {
var value = raw || {}
var aliases = normalizeAliases(value.aliases)
var parent = value.parent
if (parent === undefined)
parent = id.indexOf(".") >= 0 ? id.split(".").slice(0, -1).join(".") : "root"
if (id === "root") parent = ""
var kind = value.action ? "action" : (value.target ? "link" : "menu")
return {
id: id,
parent: parent,
kind: kind,
icon: value.icon || "",
iconFont: value.iconFont || "",
label: value.label || id,
title: value.title || "",
target: value.target || "",
description: value.description || "",
action: value.action || "",
provider: value.provider || "",
aliases: aliases,
when: value.when || "",
checked: value.checked || ""
}
}
function parseMenuJsonc(raw) {
var stripped = stripJsonc(raw)
if (!stripped.trim()) return []
var parsed
try {
parsed = JSON.parse(stripped)
} catch (e) {
return []
}
if (typeof parsed !== "object" || parsed === null) return []
var source = (parsed.items && typeof parsed.items === "object" && !Array.isArray(parsed.items))
? parsed.items
: parsed
var out = []
for (var id in source) {
var entry = source[id]
if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue
out.push(normalizeItem(id, entry))
}
return out
}
function mergeMenuSources(defaultItems, userItems) {
var nextItems = ({})
var nextOrder = []
var sources = [defaultItems || [], userItems || []]
for (var s = 0; s < sources.length; s++) {
var src = sources[s]
for (var i = 0; i < src.length; i++) {
var entry = src[i]
if (!entry || !entry.id) continue
if (!nextItems[entry.id]) nextOrder.push(entry.id)
var prior = nextItems[entry.id] || {}
var merged = {}
for (var k in prior) merged[k] = prior[k]
for (var k2 in entry) merged[k2] = entry[k2]
merged.id = entry.id
nextItems[entry.id] = merged
}
}
if (!nextItems.root) {
nextItems.root = { id: "root", parent: "", kind: "menu", icon: "", iconFont: "", label: "Go", title: "", target: "", description: "", aliases: [], when: "", checked: "", action: "", provider: "" }
nextOrder.unshift("root")
}
for (var k3 = 0; k3 < nextOrder.length; k3++) nextItems[nextOrder[k3]].order = k3
return {
items: nextItems,
itemOrder: nextOrder
}
}
// Both merges below return fresh items/itemOrder objects for the caller to
// assign in one go. They must never write into the maps they are handed: those
// live in QML `var` properties, and an in-place write into such an object is
// occasionally dropped by the engine — the key lands with an undefined value.
// A lost write used to leave an id in itemOrder with no item behind it, and
// the next merge then kept that orphan and appended a second row for the same
// app, so the launcher listed it twice (and again on every later rescan).
// Swaps every app row for the current set. Rows keep the order they arrive in;
// ids already claimed (including duplicate desktop ids) are listed once.
function mergeAppRows(items, itemOrder, appRows) {
var source = items || ({})
var order = Array.isArray(itemOrder) ? itemOrder : []
var rows = Array.isArray(appRows) ? appRows : []
var nextItems = ({})
var nextOrder = []
for (var i = 0; i < order.length; i++) {
var id = order[i]
var existing = source[id]
// Orphans (an id with no item) are dropped rather than carried forward,
// so a single lost write cannot compound into a duplicate row.
if (!existing || existing.kind === "app") continue
nextItems[id] = existing
nextOrder.push(id)
}
for (var j = 0; j < rows.length; j++) {
var row = rows[j]
if (!row || !row.id || nextItems[row.id]) continue
row.order = nextOrder.length
nextItems[row.id] = row
nextOrder.push(row.id)
}
return { items: nextItems, itemOrder: nextOrder }
}
// Swaps the rows one provider contributed, leaving every other item untouched.
// Rows carry the id of the submenu that produced them, so a provider that runs
// again drops its previous batch — a plugin that was just enabled disappears
// from the Enable list — without disturbing static children declared in JSONC.
function swapProviderRows(items, itemOrder, menuId, rows) {
var source = items || ({})
var order = Array.isArray(itemOrder) ? itemOrder : []
var incoming = Array.isArray(rows) ? rows : []
var nextItems = ({})
var nextOrder = []
for (var i = 0; i < order.length; i++) {
var id = order[i]
var existing = source[id]
if (!existing || existing.providerMenu === menuId) continue
nextItems[id] = existing
nextOrder.push(id)
}
for (var j = 0; j < incoming.length; j++) {
var row = incoming[j]
if (!row || !row.id || nextItems[row.id]) continue
row.providerMenu = menuId
row.order = nextOrder.length
nextItems[row.id] = row
nextOrder.push(row.id)
}
return { items: nextItems, itemOrder: nextOrder }
}
function item(items, id) {
return items && items[id] ? items[id] : null
}
// Routes may name a real id (`system`, `setup.power`) or an alias declared in
// JSONC (`power-menu`, `settings`). An exact id beats any alias, and app rows
// are never routable: their aliases carry .desktop Keywords and GenericName
// for search, so an installed application could otherwise shadow a menu route
// (htop ships `Keywords=system;...`). Unknown strings fall through as the
// literal input so misspellings still attempt to open that id.
function resolveRoute(items, itemOrder, input) {
var raw = String(input || "").toLowerCase().replace(/_/g, "-")
if (!raw || raw === "go" || raw === "menu") return "root"
if (item(items, raw)) return raw
var order = Array.isArray(itemOrder) ? itemOrder : []
for (var i = 0; i < order.length; i++) {
var entry = item(items, order[i])
if (!entry || entry.kind === "app" || !entry.aliases) continue
for (var j = 0; j < entry.aliases.length; j++) {
var alias = String(entry.aliases[j] || "").toLowerCase().replace(/_/g, "-")
if (alias === raw) return entry.id
}
}
return raw
}
function slugify(value) {
return String(value || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "item"
}
function depthFor(items, id) {
var depth = 0
var current = item(items, id)
var guard = 0
while (current && current.parent && current.parent !== "root" && guard < 32) {
depth += 1
current = item(items, current.parent)
guard += 1
}
return depth
}
function pathFor(items, id) {
var labels = []
var current = item(items, id)
var guard = 0
while (current && current.id !== "root" && guard < 32) {
labels.unshift(current.label)
current = item(items, current.parent)
guard += 1
}
return labels.join(" › ")
}
function parentPathFor(items, id) {
var entry = item(items, id)
if (!entry || !entry.parent || entry.parent === "root") return ""
return pathFor(items, entry.parent)
}
function isDescendantOf(items, id, ancestorId) {
if (ancestorId === "root") return id !== "root"
var current = item(items, id)
var guard = 0
while (current && current.parent && guard < 32) {
if (current.parent === ancestorId) return true
current = item(items, current.parent)
guard += 1
}
return false
}
function childCount(items, itemOrder, id) {
var count = 0
var order = Array.isArray(itemOrder) ? itemOrder : []
for (var i = 0; i < order.length; i++) {
var entry = item(items, order[i])
if (entry && entry.parent === id) count += 1
}
return count
}
function isVisible(items, itemOrder, whenResults, entry, depth) {
if (!entry) return false
if (entry.when && whenResults && whenResults[entry.id] === false) return false
if (entry.kind !== "menu" && entry.kind !== "link") return true
if (entry.provider) return true
var guard = depth || 0
if (guard >= 32) return false
var target = entry.kind === "link" ? entry.target : entry.id
var order = Array.isArray(itemOrder) ? itemOrder : []
for (var i = 0; i < order.length; i++) {
var child = item(items, order[i])
if (child && child.parent === target && isVisible(items, itemOrder, whenResults, child, guard + 1)) return true
}
return false
}
function labelFor(entry, checkedResults) {
if (!entry) return ""
if (entry.checked && checkedResults && checkedResults[entry.id]) return entry.label + " ✓"
return entry.label
}
function searchableToken(value) {
return String(value || "").replace(/[._-]+/g, " ")
}
function leafIdFor(id) {
var parts = String(id || "").split(".")
return parts.length > 0 ? parts[parts.length - 1] : id
}
function nameSearchText(entry) {
if (!entry) return ""
var aliases = []
var values = Array.isArray(entry.aliases) ? entry.aliases : []
for (var i = 0; i < values.length; i++) aliases.push(searchableToken(values[i]))
return [entry.label, searchableToken(leafIdFor(entry.id)), aliases.join(" ")].join(" ").toLowerCase()
}
function termInSearchWords(term, text) {
var words = String(text || "").toLowerCase().split(/\s+/)
for (var i = 0; i < words.length; i++) {
if (words[i] === term) return true
}
return false
}
function descriptionTextMatches(query, text) {
var terms = String(query || "").toLowerCase().trim().split(/\s+/)
for (var i = 0; i < terms.length; i++) {
if (terms[i] && !termInSearchWords(terms[i], text)) return false
}
return true
}
// Search scores use fixed-width tiers. Lower is better, and the detail portion
// never crosses a tier boundary, so an excellent fuzzy match cannot outrank a
// literal substring. Keep this pure JavaScript: the menu rebuilds on every
// keystroke and Node can exercise these functions without starting Quickshell.
var SEARCH_TIER_EXACT = 0
var SEARCH_TIER_PREFIX = 1
var SEARCH_TIER_WORD_PREFIX = 2
var SEARCH_TIER_SUBSTRING = 3
var SEARCH_TIER_SUBSEQUENCE = 6
var SEARCH_TIER_TYPO = 9
var SEARCH_TIER_SIZE = 10000
var SEARCH_NO_MATCH = 2147483647
function normalizeSearchText(value) {
return String(value || "")
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
.replace(/[._:/\\-]+/g, " ")
.replace(/\s+/g, " ")
.trim()
.toLowerCase()
}
function searchWords(value) {
var normalized = normalizeSearchText(value)
return normalized ? normalized.split(/\s+/) : []
}
function searchTierName(tier) {
if (tier === SEARCH_TIER_EXACT) return "exact"
if (tier === SEARCH_TIER_PREFIX) return "prefix"
if (tier === SEARCH_TIER_WORD_PREFIX) return "word-prefix"
if (tier === SEARCH_TIER_SUBSTRING) return "substring"
if (tier === SEARCH_TIER_SUBSEQUENCE) return "subsequence"
if (tier === SEARCH_TIER_TYPO) return "typo"
return "none"
}
function packedSearchScore(tier, detail) {
var bounded = Math.max(0, Math.min(SEARCH_TIER_SIZE - 1, Math.round(detail || 0)))
return tier * SEARCH_TIER_SIZE + bounded
}
function isSearchBoundary(candidate, index) {
return index === 0 || candidate.charAt(index - 1) === " "
}
// Dynamic-programming subsequence score. Every query character must appear in
// order. Consecutive runs and word starts are cheap; gaps and late starts cost
// more. A rolling prefix minimum keeps this O(query * candidate), including
// repeated characters, rather than trying every preceding match.
function normalizedSubsequenceScore(needle, haystack) {
if (!needle || !haystack || needle.length > haystack.length) return -1
// Most launcher candidates do not contain the query at all. This cheap scan
// avoids allocating DP rows for those overwhelmingly common misses.
var scan = 0
for (var n = 0; n < needle.length; n++) {
scan = haystack.indexOf(needle.charAt(n), scan)
if (scan < 0) return -1
scan += 1
}
var previous = []
var current = []
var i
var j
for (j = 0; j < haystack.length; j++) {
if (haystack.charAt(j) !== needle.charAt(0)) previous[j] = SEARCH_NO_MATCH
else previous[j] = j * 6 + (isSearchBoundary(haystack, j) ? 0 : 8)
}
for (i = 1; i < needle.length; i++) {
current = []
var prefixMinimum = SEARCH_NO_MATCH
for (j = 0; j < haystack.length; j++) {
current[j] = SEARCH_NO_MATCH
// Once j advances, k <= j - 2 are the non-consecutive predecessors.
// Their transition is prev[k] - 3k + 3j + 9, so only the minimum
// prev[k] - 3k must be carried forward.
if (j >= 2 && previous[j - 2] !== SEARCH_NO_MATCH)
prefixMinimum = Math.min(prefixMinimum, previous[j - 2] - 3 * (j - 2))
if (haystack.charAt(j) !== needle.charAt(i)) continue
if (j > 0 && previous[j - 1] !== SEARCH_NO_MATCH)
current[j] = previous[j - 1]
if (prefixMinimum !== SEARCH_NO_MATCH) {
var boundaryBonus = isSearchBoundary(haystack, j) ? 8 : 0
current[j] = Math.min(current[j], prefixMinimum + 3 * j + 9 - boundaryBonus)
}
}
previous = current
}
var best = SEARCH_NO_MATCH
for (j = 0; j < previous.length; j++) best = Math.min(best, previous[j])
if (best === SEARCH_NO_MATCH) return -1
// Prefer compact candidates after the positional score has tied.
return Math.min(SEARCH_TIER_SIZE - 1, best + Math.max(0, haystack.length - needle.length))
}
function subsequenceScore(query, candidate) {
return normalizedSubsequenceScore(
normalizeSearchText(query).replace(/\s+/g, ""),
normalizeSearchText(candidate)
)
}
// Optimal-string-alignment Damerau-Levenshtein distance with a strict bound.
// Adjacent transposition is one edit. Candidate words are short, but the
// length check and final bound keep typo matching predictable and inexpensive.
function normalizedBoundedDamerauLevenshtein(a, b, maxDistance) {
var limit = Math.max(0, Number(maxDistance) || 0)
if (Math.abs(a.length - b.length) > limit) return limit + 1
if (a === b) return 0
if (!a.length) return b.length <= limit ? b.length : limit + 1
if (!b.length) return a.length <= limit ? a.length : limit + 1
var previousPrevious = null
var previous = []
var current = []
var i
var j
for (j = 0; j <= b.length; j++) previous[j] = j
for (i = 1; i <= a.length; i++) {
current = [i]
for (j = 1; j <= b.length; j++) {
var substitutionCost = a.charAt(i - 1) === b.charAt(j - 1) ? 0 : 1
var value = Math.min(
previous[j] + 1,
current[j - 1] + 1,
previous[j - 1] + substitutionCost
)
if (i > 1 && j > 1
&& a.charAt(i - 1) === b.charAt(j - 2)
&& a.charAt(i - 2) === b.charAt(j - 1)) {
value = Math.min(value, previousPrevious[j - 2] + 1)
}
current[j] = value
}
previousPrevious = previous
previous = current
}
return previous[b.length] <= limit ? previous[b.length] : limit + 1
}
function boundedDamerauLevenshtein(left, right, maxDistance) {
return normalizedBoundedDamerauLevenshtein(
normalizeSearchText(left),
normalizeSearchText(right),
maxDistance
)
}
function typoDistanceLimit(term) {
if (term.length < 4) return 0
return term.length >= 8 ? 2 : 1
}
function acceptableTypoDistance(term, word, limit) {
if (!limit || Math.abs(term.length - word.length) > limit) return -1
// Avoid spending edit distance on a vastly different candidate and prevent
// two changes from accepting a short word merely because it crossed length 8.
var longest = Math.max(term.length, word.length)
var distance = normalizedBoundedDamerauLevenshtein(term, word, limit)
if (distance <= 0 || distance > limit) return -1
if (distance / longest > 0.25) return -1
return distance
}
function compactSubsequenceIndexes(term, value) {
var needle = String(term || "").toLowerCase()
var candidate = String(value || "").toLowerCase()
if (!needle || !candidate || needle.length > candidate.length) return []
var best = []
var bestSpan = SEARCH_NO_MATCH
for (var start = candidate.indexOf(needle.charAt(0)); start >= 0; start = candidate.indexOf(needle.charAt(0), start + 1)) {
var indexes = [start]
var at = start + 1
var complete = true
for (var i = 1; i < needle.length; i++) {
at = candidate.indexOf(needle.charAt(i), at)
if (at < 0) {
complete = false
break
}
indexes.push(at)
at += 1
}
if (!complete) continue
var span = indexes[indexes.length - 1] - indexes[0]
if (span < bestSpan) {
best = indexes
bestSpan = span
}
}
return best
}
function labelHighlightIndexes(label, query) {
var value = String(label || "")
var lower = value.toLowerCase()
var terms = searchWords(query)
var marked = ({})
for (var t = 0; t < terms.length; t++) {
var term = terms[t]
var indexes = []
var literal = lower.indexOf(term)
var i
if (literal >= 0) {
for (i = 0; i < term.length; i++) indexes.push(literal + i)
} else {
indexes = compactSubsequenceIndexes(term, lower)
}
// A real typo has no complete subsequence. In that case, emphasizing the
// accepted word is clearer than pretending only a few letters matched.
if (indexes.length === 0) {
var typoLimit = typoDistanceLimit(term)
var wordPattern = /[A-Za-z0-9]+/g
var wordMatch
var bestWord = null
var bestDistance = SEARCH_NO_MATCH
while ((wordMatch = wordPattern.exec(value)) !== null) {
var distance = acceptableTypoDistance(term, wordMatch[0].toLowerCase(), typoLimit)
if (distance >= 0 && distance < bestDistance) {
bestDistance = distance
bestWord = { index: wordMatch.index, length: wordMatch[0].length }
}
}
if (bestWord) {
for (i = 0; i < bestWord.length; i++) indexes.push(bestWord.index + i)
}
}
for (i = 0; i < indexes.length; i++) marked[indexes[i]] = true
}
return marked
}
function escapeStyledCharacter(character) {
if (character === "&") return "&"
if (character === "<") return "<"
if (character === ">") return ">"
if (character === '"') return """
return character
}
// StyledText inherits the row's theme-aware foreground/selection color. Bold
// is the only visual treatment, keeping highlighting legible and restrained.
function styledLabel(label, query) {
var value = String(label || "")
var marked = labelHighlightIndexes(value, query)
var output = ""
var bold = false
for (var i = 0; i < value.length; i++) {
var shouldBold = marked[i] === true
if (shouldBold && !bold) {
output += "<b>"
bold = true
} else if (!shouldBold && bold) {
output += "</b>"
bold = false
}
output += escapeStyledCharacter(value.charAt(i))
}
if (bold) output += "</b>"
return output
}
function normalizedTermMatchScore(term, candidate, words, fieldWeight) {
if (!term || !candidate) return null
var weight = Math.max(0, Number(fieldWeight) || 0)
var i
var index
if (candidate === term)
return { score: packedSearchScore(SEARCH_TIER_EXACT, weight), tier: SEARCH_TIER_EXACT }
for (i = 0; i < words.length; i++) {
if (words[i] === term)
return { score: packedSearchScore(SEARCH_TIER_EXACT, weight + i * 25), tier: SEARCH_TIER_EXACT }
}
if (candidate.indexOf(term) === 0)
return { score: packedSearchScore(SEARCH_TIER_PREFIX, weight + candidate.length - term.length), tier: SEARCH_TIER_PREFIX }
for (i = 0; i < words.length; i++) {
if (words[i].indexOf(term) === 0)
return { score: packedSearchScore(SEARCH_TIER_WORD_PREFIX, weight + i * 25 + words[i].length - term.length), tier: SEARCH_TIER_WORD_PREFIX }
}
index = candidate.indexOf(term)
if (index >= 0)
return { score: packedSearchScore(SEARCH_TIER_SUBSTRING, weight + index * 8 + candidate.length - term.length), tier: SEARCH_TIER_SUBSTRING }
var fuzzy = normalizedSubsequenceScore(term, candidate)
if (fuzzy >= 0)
return { score: packedSearchScore(SEARCH_TIER_SUBSEQUENCE, weight + fuzzy), tier: SEARCH_TIER_SUBSEQUENCE }
var typoLimit = typoDistanceLimit(term)
var bestDistance = SEARCH_NO_MATCH
var bestLengthDelta = SEARCH_NO_MATCH
for (i = 0; i < words.length; i++) {
var distance = acceptableTypoDistance(term, words[i], typoLimit)
if (distance < 0) continue
var lengthDelta = Math.abs(term.length - words[i].length)
if (distance < bestDistance || (distance === bestDistance && lengthDelta < bestLengthDelta)) {
bestDistance = distance
bestLengthDelta = lengthDelta
}
}
if (bestDistance !== SEARCH_NO_MATCH) {
return {
score: packedSearchScore(SEARCH_TIER_TYPO, weight + bestDistance * 1200 + bestLengthDelta * 80),
tier: SEARCH_TIER_TYPO
}
}
return null
}
function termMatchScore(term, rawCandidate, fieldWeight) {
var candidate = normalizeSearchText(rawCandidate)
return normalizedTermMatchScore(normalizeSearchText(term), candidate, searchWords(candidate), fieldWeight)
}
var SEARCH_FIELD_CACHE = ({})
var SEARCH_FIELD_CACHE_SIZE = 0
var SEARCH_FIELD_CACHE_LIMIT = 8192
function searchFieldSignature(entry) {
var aliases = Array.isArray(entry.aliases) ? entry.aliases : []
return [entry.label, entry.id, aliases.join("\u001f"), entry.description].join("\u001e")
}
function normalizedSearchField(text, weight) {
var normalized = normalizeSearchText(text)
return { text: normalized, words: normalized ? normalized.split(/\s+/) : [], weight: weight }
}
function entrySearchFields(entry) {
if (!entry) return []
// Prefix the key so special object properties such as "__proto__" can never
// collide with the cache object's prototype.
var key = "$" + String(entry.id || "")
var signature = searchFieldSignature(entry)
var cached = SEARCH_FIELD_CACHE[key]
if (cached && cached.signature === signature) return cached.fields
// Provider rows can churn over a long shell session. A coarse reset keeps
// this module-level cache bounded without complicating the hot search path.
if (SEARCH_FIELD_CACHE_SIZE >= SEARCH_FIELD_CACHE_LIMIT) {
SEARCH_FIELD_CACHE = ({})
SEARCH_FIELD_CACHE_SIZE = 0
}
var fields = []
fields.push(normalizedSearchField(entry.label, 0))
fields.push(normalizedSearchField(leafIdFor(entry.id), 1800))
var aliases = Array.isArray(entry.aliases) ? entry.aliases : []
for (var i = 0; i < aliases.length; i++) fields.push(normalizedSearchField(aliases[i], 3500))
fields.push(normalizedSearchField(entry.description, 6500))
if (!cached) SEARCH_FIELD_CACHE_SIZE += 1
SEARCH_FIELD_CACHE[key] = { signature: signature, fields: fields }
return fields
}
function entryMatch(entry, query) {
var normalizedQuery = normalizeSearchText(query)
if (!normalizedQuery) return { matched: true, score: 0, tier: "exact" }
if (!entry) return { matched: false, score: SEARCH_NO_MATCH, tier: "none" }
var fields = entrySearchFields(entry)
var normalizedLabel = fields.length ? fields[0].text : ""
if (normalizedLabel === normalizedQuery)
return { matched: true, score: 0, tier: "exact" }
var terms = normalizedQuery.split(/\s+/)
var worstTier = SEARCH_TIER_EXACT
var detailTotal = 0
var tierTotal = 0
for (var i = 0; i < terms.length; i++) {
var best = null
for (var j = 0; j < fields.length; j++) {
var candidate = normalizedTermMatchScore(terms[i], fields[j].text, fields[j].words, fields[j].weight)
if (candidate && (!best || candidate.score < best.score)) best = candidate
}
if (!best) return { matched: false, score: SEARCH_NO_MATCH, tier: "none" }
worstTier = Math.max(worstTier, best.tier)
tierTotal += best.tier
detailTotal += best.score % SEARCH_TIER_SIZE
}
// The weakest term defines the tier. Average field/position penalties and a
// small tier-mix penalty distinguish all-prefix matches from exact+prefix
// without allowing those details to leak into the next tier.
var detail = Math.round(detailTotal / terms.length + (tierTotal / terms.length) * 100)
return {
matched: true,
score: packedSearchScore(worstTier, detail),
tier: searchTierName(worstTier)
}
}
function parseUsageEntries(raw) {
var parsed
try {
parsed = JSON.parse(String(raw || ""))
} catch (e) {
return []
}
var source = Array.isArray(parsed) ? parsed : (parsed && Array.isArray(parsed.entries) ? parsed.entries : [])
var rows = []
var seen = ({})
for (var i = 0; i < source.length; i++) {
var row = source[i] || {}
var id = String(row.id || "")
var key = "$" + id
if (!id || seen[key]) continue
seen[key] = true
rows.push({
id: id,
count: Math.max(0, Math.floor(Number(row.count) || 0)),
lastUsed: Math.max(0, Math.floor(Number(row.lastUsed) || 0))
})
}
return rows
}
function usageCountMap(entries) {
var counts = ({})
var rows = Array.isArray(entries) ? entries : []
for (var i = 0; i < rows.length; i++) {
if (!rows[i] || !rows[i].id) continue
counts["$" + rows[i].id] = Math.max(0, Math.floor(Number(rows[i].count) || 0))
}
return counts
}
function usageCount(counts, id) {
return Math.max(0, Math.floor(Number((counts || ({}))["$" + String(id || "")]) || 0))
}
function usageRankBonus(count) {
var value = Math.max(0, Number(count) || 0)
if (!value) return 0
return Math.min(900, Math.round(Math.log(value + 1) / Math.log(2) * 150))
}
function recordUsage(entries, id, timestamp, limit) {
var target = String(id || "")
if (!target) return Array.isArray(entries) ? entries.slice(0) : []
var source = Array.isArray(entries) ? entries : []
var next = []
var found = false
for (var i = 0; i < source.length; i++) {
var row = source[i]
if (!row || !row.id) continue
if (row.id === target) {
next.push({
id: target,
count: Math.min(1000000, Math.max(0, Math.floor(Number(row.count) || 0)) + 1),
lastUsed: Math.max(0, Math.floor(Number(timestamp) || 0))
})
found = true
} else {
next.push({ id: String(row.id), count: Math.max(0, Math.floor(Number(row.count) || 0)), lastUsed: Math.max(0, Math.floor(Number(row.lastUsed) || 0)) })
}
}
if (!found) next.push({ id: target, count: 1, lastUsed: Math.max(0, Math.floor(Number(timestamp) || 0)) })
next.sort(function(a, b) {
if (a.lastUsed !== b.lastUsed) return b.lastUsed - a.lastUsed
if (a.count !== b.count) return b.count - a.count
return a.id < b.id ? -1 : (a.id > b.id ? 1 : 0)
})
return next.slice(0, Math.max(1, Math.floor(Number(limit) || 512)))
}
function matchesQuery(entry, query, visible) {
if (!entry || entry.id === "root") return false
if (!visible) return false
return entryMatch(entry, query).matched
}
function searchScore(items, entry, query, knownMatch, knownUsageCount) {
var match = knownMatch || entryMatch(entry, query)
if (!match.matched) return SEARCH_NO_MATCH
var kindAdjustment = 0
if (entry.kind === "menu" || entry.kind === "link") kindAdjustment = -2000
// Preserve the built-in launcher's preference for an installed application
// when it ties an identically named menu action (for example, Zen).
if (entry.kind === "app") kindAdjustment = -5000
return match.score * 10000
+ kindAdjustment
- usageRankBonus(knownUsageCount) * 1000
+ depthFor(items, entry.id) * 25
+ (Number(entry.order) || 0)
}
function searchResult(items, entry, query, visible, knownUsageCount) {
if (!entry || entry.id === "root" || !visible)
return { matched: false, score: SEARCH_NO_MATCH, tier: "none" }
var match = entryMatch(entry, query)
if (!match.matched) return match
return {
matched: true,
score: searchScore(items, entry, query, match, knownUsageCount),
tier: match.tier,
usageCount: Math.max(0, Math.floor(Number(knownUsageCount) || 0))
}
}
function entryTypeLabel(entry) {
if (!entry) return ""
if (entry.kind === "app") return "APP"
if (entry.kind === "menu" || entry.kind === "link") return "MENU"
if (entry.kind === "action") return "ACTION"
return ""
}
function displayRow(items, itemOrder, checkedResults, entry, detail, score, section) {
var target = entry.kind === "link" ? entry.target : entry.id
var renderedLabel = labelFor(entry, checkedResults)
return {
itemId: entry.id,
kind: entry.kind,
icon: entry.icon,
iconFont: entry.iconFont || "",
appIcon: entry.appIcon || "",
appId: entry.appId || "",
label: renderedLabel,
labelMarkup: styledLabel(renderedLabel, ""),
matchTier: "",
typeLabel: entryTypeLabel(entry),
usageCount: 0,
target: target,
detail: detail || "",
path: pathFor(items, entry.id),
childCount: (entry.kind === "menu" || entry.kind === "link") ? childCount(items, itemOrder, target) : 0,
action: entry.action || "",
provider: entry.provider || "",
copyText: "",
score: score || 0,
section: section || ""
}
}
// Commands a `checked:` expression reads a value out of. Every sibling row
// asks the same one -- Defaults > Browser has seven rows all comparing
// against `omarchy-default-browser` -- so the batch runs it once and the rows
// read the captured answer.
//
// The capture has to be eager. These are read inside `$(...)`, and a value
// cached while one expression runs lives in that subshell only, so a lazy
// memo never survives to the expression after it.
var GUARD_READERS = [
"omarchy-channel-current",
"omarchy-default-agent",
"omarchy-default-browser",
"omarchy-default-editor",
"omarchy-default-terminal",
"omarchy-dns"
]
// Package and command presence account for most of what the guards ask, and
// asked one at a time they are almost all fork: the shipped menu spends over
// a second on them. Answer them inside the guard process instead. These
// shadow the real commands for the batch only, so they have to agree with
// them everywhere, including for no arguments at all (present is true of
// nothing, missing is not).
//
// `pacman -Q` resolves a name through what installed packages provide, not
// just what they are called -- with gvim installed it reports `vim` as
// present -- so the set has to carry provides too, or `install.editor.vim`
// comes back and offers to install what is already there. A version
// constraint (`bash>=1`) is not a name any set can answer, so it goes to
// pacman itself; no shipped guard writes one.
//
// `pacman -Qi` wraps a long list across continuation lines whenever COLUMNS
// is set in the environment, which a login shell may well have done, so the
// parser follows the indented lines rather than reading the first one and
// dropping half of what is installed.
function guardHelpers() {
return 'declare -A __omarchy_pkgs=()\n'
+ 'mapfile -t __omarchy_pkg_names < <({ pacman -Qq; LC_ALL=C pacman -Qi'
+ " | awk '/^[A-Za-z]/ { provides = ($0 ~ /^Provides/); sub(/^[^:]*: /, \"\") }"
+ ' provides && $0 != "None" { n = split($0, p, " ");'
+ ' for (i = 1; i <= n; i++) { sub(/[<>=].*/, "", p[i]); print p[i] } }\'; } 2>/dev/null)\n'
+ 'for __omarchy_pkg in "${__omarchy_pkg_names[@]}"; do __omarchy_pkgs[$__omarchy_pkg]=1; done\n'
+ '__omarchy_pkg_has() { [[ -n ${__omarchy_pkgs[$1]-} ]] && return 0; '
+ '[[ $1 == *[\\<\\>=]* ]] && { pacman -Q "$1" &>/dev/null; return; }; return 1; }\n'
+ 'omarchy-pkg-present() { local p; for p in "$@"; do __omarchy_pkg_has "$p" || return 1; done; return 0; }\n'
+ 'omarchy-pkg-missing() { local p; for p in "$@"; do __omarchy_pkg_has "$p" || return 0; done; return 1; }\n'
+ 'omarchy-cmd-present() { local c; for c in "$@"; do command -v "$c" &>/dev/null || return 1; done; return 0; }\n'
+ 'omarchy-cmd-missing() { local c; for c in "$@"; do command -v "$c" &>/dev/null || return 0; done; return 1; }\n'
}
// Substitute the captured answer into the expression rather than shadowing
// the reader with a function. `$(reader)` and the variable holding what it
// printed are interchangeable -- both strip trailing newlines, both split the
// same way unquoted -- while a function would also catch `command -v reader`,
// `VAR=x reader`, and every other form, and answer those wrong. Anything but
// the plain substitution is left alone to run the real command.
function guardPrelude(guards) {
var prelude = guardHelpers()
for (var i = 0; i < GUARD_READERS.length; i++) {
// The guards arrive already substituted, so what marks a reader as wanted
// is the slot standing in for it, not the call it replaced.
if (guards.indexOf(guardReaderSlot(i)) < 0) continue
// `|| :` so a reader that exits nonzero cannot take the batch down with
// it under a login shell that turned on errexit.
prelude += "__omarchy_read_" + i + "=$(" + GUARD_READERS[i] + " 2>/dev/null) || :\n"
}
return prelude
}
function guardReaderSlot(index) {
return "${__omarchy_read_" + index + "}"
}
function substituteGuardReaders(expression) {
for (var i = 0; i < GUARD_READERS.length; i++)
expression = expression.split("$(" + GUARD_READERS[i] + ")").join(guardReaderSlot(i))
return expression
}
function guardLine(id, tag, expression) {
return "if { " + substituteGuardReaders(expression) + "; } >/dev/null 2>&1; then echo "
+ id + ":" + tag + ":1; else echo " + id + ":" + tag + ":0; fi\n"
}
// One bash script for every `when:` and `checked:` in the menu, reporting
// `<id>:<w|c>:<0|1>` per line. Speed is the whole point: the menu opens on
// the last evaluation's answers, so however long this takes is how long a row
// can contradict the state it describes.
function guardScript(items) {
var guards = ""
var ids = Object.keys(items || {})
for (var i = 0; i < ids.length; i++) {
var entry = items[ids[i]]
if (!entry) continue
if (entry.when) guards += guardLine(ids[i], "w", entry.when)
if (entry.checked) guards += guardLine(ids[i], "c", entry.checked)
}
return guards ? guardPrelude(guards) + guards : ""
}
function primaryActionLabel(mode, kind) {
if (mode === "input") return "Submit"
if (mode === "select") return "Select"
if (kind === "instant") return "Copy"
return kind === "action" ? "Run" : "Open"
}
function primaryActionAvailable(mode, hasSelection) {
return mode === "input" || !!hasSelection
}
function deleteActionAvailable(mode, kind) {
return mode === "menu" && kind === "app"
}
if (typeof module !== "undefined") {