-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsettings.ts
More file actions
1953 lines (1722 loc) · 80.4 KB
/
settings.ts
File metadata and controls
1953 lines (1722 loc) · 80.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
// Copyright © 2025-2026 OpenVCS Contributors
// SPDX-License-Identifier: GPL-3.0-or-later
import { TAURI } from '../lib/tauri';
import { openModal, closeModal } from '../ui/modals';
import { toKebab } from '../lib/dom';
import { confirmBool } from '../lib/confirm';
import { notify } from '../lib/notify';
import { setTheme } from '../ui/layout';
import { DEFAULT_DARK_THEME_ID, DEFAULT_LIGHT_THEME_ID, DEFAULT_THEME_ID, getActiveThemeId, getAvailableThemes, refreshAvailableThemes, selectThemePack } from '../themes';
import { reloadPlugins } from '../plugins';
import type { PluginSummary } from '../plugins';
import { applyPluginSettingsSections } from '../plugins';
import type { GlobalSettings, ThemeSummary } from '../types';
const THEME_PACK_HINT = 'Install a theme ZIP into the themes folder, or install a plugin that provides themes.';
const SYSTEM_DARK_MQ = matchMedia('(prefers-color-scheme: dark)');
interface PluginMenuPayload {
plugin_id: string;
id: string;
label: string;
elements: Array<{
type: 'text' | 'button' | string;
id?: string;
content?: string;
label?: string;
}>;
}
interface PluginSettingOptionPayload {
value: string;
label: string;
}
interface PluginSettingFieldPayload {
id: string;
kind: 'bool' | 's32' | 'u32' | 'f64' | 'text' | string;
label: string;
description?: string | null;
default_value: unknown;
value: unknown;
options?: PluginSettingOptionPayload[];
}
function pluginSectionId(pluginId: string, menuId: string): string {
return `plugin-${toKebab(`${pluginId}-${menuId}`)}`;
}
function flashSavedState(button: HTMLButtonElement, originalText = 'Save') {
button.classList.add('saved-state');
button.textContent = 'Saved!';
setTimeout(() => {
button.textContent = originalText;
button.classList.remove('saved-state');
}, 2000);
}
function renderPluginSettingFields(
fields: PluginSettingFieldPayload[],
): HTMLDivElement {
const settingsWrap = document.createElement('div');
settingsWrap.className = 'group';
const heading = document.createElement('h4');
heading.className = 'settings-section-title';
heading.textContent = 'Settings';
settingsWrap.appendChild(heading);
const controls = new Map<string, HTMLInputElement | HTMLSelectElement>();
for (const field of fields) {
const settingId = String(field?.id || '').trim();
if (!settingId) continue;
const kind = String(field?.kind || '').trim().toLowerCase();
const row = document.createElement('div');
row.className = 'group';
const hasOptions = Array.isArray(field.options) && field.options.length > 0;
let control: HTMLInputElement | HTMLSelectElement;
if (kind === 'bool') {
const labelEl = document.createElement('label');
labelEl.className = 'checkbox';
const input = document.createElement('input');
input.type = 'checkbox';
input.checked = Boolean(field.value);
labelEl.appendChild(input);
labelEl.append(` ${String(field?.label || settingId).trim() || settingId}`);
control = input;
row.appendChild(labelEl);
} else if (kind === 'text' && hasOptions) {
const labelEl = document.createElement('label');
labelEl.textContent = String(field?.label || settingId).trim() || settingId;
row.appendChild(labelEl);
const select = document.createElement('select');
for (const option of field.options || []) {
const opt = document.createElement('option');
opt.value = String(option?.value || '');
opt.textContent = String(option?.label || option?.value || '').trim() || opt.value;
select.appendChild(opt);
}
const value = String(field?.value ?? '');
if (value && Array.from(select.options).some((opt) => opt.value === value)) {
select.value = value;
}
control = select;
row.appendChild(control);
} else {
const labelEl = document.createElement('label');
labelEl.textContent = String(field?.label || settingId).trim() || settingId;
row.appendChild(labelEl);
const input = document.createElement('input');
if (kind === 's32' || kind === 'u32' || kind === 'f64') {
input.type = 'number';
input.step = kind === 'f64' ? 'any' : '1';
if (kind === 'u32') input.min = '0';
const n = Number(field?.value ?? field?.default_value ?? 0);
input.value = Number.isFinite(n) ? String(n) : '0';
} else {
input.type = 'text';
input.value = String(field?.value ?? field?.default_value ?? '');
}
control = input;
row.appendChild(control);
}
control.setAttribute('data-setting-id', settingId);
control.setAttribute('data-setting-kind', kind);
controls.set(settingId, control);
const description = String(field?.description || '').trim();
if (description) {
const hint = document.createElement('small');
hint.textContent = description;
row.appendChild(hint);
}
settingsWrap.appendChild(row);
}
return settingsWrap;
}
const loadedPluginSettings = new Map<string, PluginSettingFieldPayload[]>();
export function clearPluginSettingsCache(): void {
loadedPluginSettings.clear();
}
async function ensurePluginSettingsLoaded(modal: HTMLElement, pluginId: string, section: string): Promise<boolean> {
const panelsScroll = modal.querySelector('#settings-panels-scroll');
if (!panelsScroll) return false;
const panel = panelsScroll.querySelector<HTMLElement>(`.panel-form[data-panel="${CSS.escape(section)}"]`);
if (!panel) return false;
const cacheKey = pluginId.toLowerCase();
if (loadedPluginSettings.has(cacheKey)) {
const existing = panel.querySelector('.group');
if (existing) return true;
const fields = loadedPluginSettings.get(cacheKey)!;
const settingsWrap = renderPluginSettingFields(fields);
panel.appendChild(settingsWrap);
return true;
}
const loading = panel.querySelector('.plugin-settings-loading');
if (loading) {
(loading as HTMLElement).dataset.loading = 'true';
}
try {
const fields = await TAURI.invoke<PluginSettingFieldPayload[]>('get_plugin_settings', { pluginId });
loadedPluginSettings.set(cacheKey, Array.isArray(fields) ? fields : []);
const loadingEl = panel.querySelector('.plugin-settings-loading');
if (loadingEl) loadingEl.remove();
if (!Array.isArray(fields) || fields.length === 0) {
const empty = document.createElement('div');
empty.className = 'group';
empty.textContent = 'No settings available';
panel.appendChild(empty);
return true;
}
const settingsWrap = renderPluginSettingFields(fields);
panel.appendChild(settingsWrap);
return true;
} catch {
const loadingEl = panel.querySelector('.plugin-settings-loading');
if (loadingEl) {
(loadingEl as HTMLElement).dataset.loading = 'false';
const error = document.createElement('div');
error.className = 'group';
error.textContent = 'Failed to load settings';
loadingEl.appendChild(error);
}
return false;
}
}
export function applyAnimationPreference(enabled: boolean | undefined | null) {
document.documentElement.dataset.animations = enabled === false ? 'off' : 'on';
}
function normalizeAppearance(value: unknown): 'light' | 'dark' | 'both' | null {
const raw = String(value ?? '').trim().toLowerCase();
if (raw === 'light' || raw === 'dark' || raw === 'both') return raw;
return null;
}
function modeForTheme(themeId: string): 'light' | 'dark' {
const desired = (themeId || DEFAULT_LIGHT_THEME_ID).trim().toLowerCase() || DEFAULT_LIGHT_THEME_ID;
const summary = getAvailableThemes().find((t) => (t.id || '').toLowerCase() === desired);
const appearance = normalizeAppearance(summary?.appearance);
if (appearance === 'light') return 'light';
if (appearance === 'dark') return 'dark';
return SYSTEM_DARK_MQ.matches ? 'dark' : 'light';
}
function themeOptionLabel(theme: ThemeSummary): string {
const version = theme.version?.trim();
return version ? `${theme.name} (${version})` : theme.name;
}
function themeTooltip(id: string): string {
const theme = getAvailableThemes().find((t) => t.id.toLowerCase() === id.toLowerCase());
if (!theme) return THEME_PACK_HINT;
const details: string[] = [];
if (theme.description) details.push(theme.description);
const meta = [theme.author, theme.version].filter(Boolean).join(' • ');
if (meta) details.push(meta);
return details.join('\n') || THEME_PACK_HINT;
}
async function renderPluginMenus(modal: HTMLElement): Promise<void> {
const nav = modal.querySelector('#settings-nav');
const panelsScroll = modal.querySelector('#settings-panels-scroll');
if (!nav || !panelsScroll) return;
nav.querySelectorAll<HTMLElement>('[data-plugin-menu="true"]').forEach((node) => node.remove());
nav.querySelectorAll<HTMLElement>('[data-plugin-menus-wrap="true"]').forEach((node) => node.remove());
panelsScroll
.querySelectorAll<HTMLElement>('.panel-form[data-plugin-menu="true"]')
.forEach((node) => node.remove());
if (!TAURI.has) return;
let menus: PluginMenuPayload[] = [];
let pluginSummaries: PluginSummary[] = [];
try {
menus = await TAURI.invoke<PluginMenuPayload[]>('list_plugin_menus');
} catch {
return;
}
try {
pluginSummaries = await TAURI.invoke<PluginSummary[]>('list_plugins');
} catch {
pluginSummaries = [];
}
const pluginSources = new Map<string, string>();
const pluginNames = new Map<string, string>();
for (const summary of Array.isArray(pluginSummaries) ? pluginSummaries : []) {
const id = String(summary?.id || '').trim().toLowerCase();
if (!id) continue;
pluginSources.set(id, String(summary?.source || '').trim().toLowerCase());
pluginNames.set(id, String(summary?.name || summary?.id || '').trim() || id);
}
const pluginsNavBtn = nav.querySelector<HTMLElement>('[data-section="plugins"]');
const pluginsNavLi = pluginsNavBtn?.closest('li') || null;
let thirdPartySublist: HTMLElement | null = null;
const ensureThirdPartySublist = (): HTMLElement => {
if (thirdPartySublist) return thirdPartySublist;
const wrap = document.createElement('div');
wrap.setAttribute('data-plugin-menus-wrap', 'true');
const heading = document.createElement('div');
heading.className = 'settings-plugin-subhead';
heading.textContent = 'Plugin Settings';
wrap.appendChild(heading);
const list = document.createElement('ul');
list.className = 'settings-plugin-sublist';
list.setAttribute('data-plugin-menus', 'true');
wrap.appendChild(list);
if (pluginsNavLi) {
pluginsNavLi.appendChild(wrap);
} else {
nav.appendChild(wrap);
}
thirdPartySublist = list;
return list;
};
for (const menu of menus) {
const section = pluginSectionId(menu.plugin_id, menu.id);
const navLi = document.createElement('li');
navLi.dataset.pluginMenu = 'true';
const navBtn = document.createElement('button');
const source = pluginSources.get(String(menu.plugin_id || '').trim().toLowerCase()) || '';
const isBuiltIn = source === 'built-in';
navBtn.className = 'seg-btn';
navBtn.setAttribute('data-section', section);
navBtn.textContent = menu.label || menu.id;
navLi.appendChild(navBtn);
if (isBuiltIn) {
if (pluginsNavLi?.parentElement) {
pluginsNavLi.parentElement.insertBefore(navLi, pluginsNavLi);
} else {
nav.appendChild(navLi);
}
} else {
ensureThirdPartySublist().appendChild(navLi);
}
const panel = document.createElement('form');
panel.className = 'panel-form hidden';
panel.setAttribute('data-panel', section);
panel.setAttribute('data-plugin-menu', 'true');
panel.dataset.pluginId = menu.plugin_id;
panel.dataset.menuId = menu.id;
for (const element of menu.elements || []) {
const group = document.createElement('div');
group.className = 'group';
if (element.type === 'text') {
const text = document.createElement('div');
text.textContent = String(element.content || '');
group.appendChild(text);
} else if (element.type === 'button') {
const button = document.createElement('button');
button.type = 'button';
button.className = 'tbtn';
button.textContent = String(element.label || 'Action');
button.dataset.pluginAction = String(element.id || '');
button.dataset.pluginId = menu.plugin_id;
group.appendChild(button);
}
panel.appendChild(group);
}
panelsScroll.appendChild(panel);
}
for (const summary of Array.isArray(pluginSummaries) ? pluginSummaries : []) {
const pluginId = String(summary?.id || '').trim();
const pluginKey = pluginId.toLowerCase();
if (!pluginId) continue;
const section = `plugin-settings-${toKebab(pluginId)}`;
const navLi = document.createElement('li');
navLi.dataset.pluginMenu = 'true';
const navBtn = document.createElement('button');
navBtn.className = 'seg-btn';
navBtn.setAttribute('data-section', section);
navBtn.textContent = pluginNames.get(pluginKey) || pluginId;
navLi.appendChild(navBtn);
ensureThirdPartySublist().appendChild(navLi);
const panel = document.createElement('form');
panel.className = 'panel-form hidden';
panel.setAttribute('data-panel', section);
panel.setAttribute('data-plugin-menu', 'true');
panel.dataset.pluginId = pluginId;
panel.dataset.pluginSettings = 'true';
const loading = document.createElement('div');
loading.className = 'plugin-settings-loading group';
loading.dataset.loading = 'true';
loading.textContent = 'Loading settings...';
panel.appendChild(loading);
panelsScroll.appendChild(panel);
}
}
async function rebuildThemePackOptions(
selectEl: HTMLSelectElement,
opts: { desiredId?: string | null; forceReload?: boolean } = {},
) {
const { desiredId, forceReload } = opts;
if (forceReload) {
try {
await refreshAvailableThemes();
} catch {
// ignore refresh errors; fallback to whatever themes are cached
}
}
const themes = getAvailableThemes();
const desiredLower = String(desiredId ?? selectEl.value ?? DEFAULT_LIGHT_THEME_ID).trim().toLowerCase() || DEFAULT_LIGHT_THEME_ID;
selectEl.innerHTML = '';
for (const theme of themes) {
const opt = document.createElement('option');
opt.value = theme.id;
opt.textContent = themeOptionLabel(theme);
opt.title = themeTooltip(theme.id);
selectEl.appendChild(opt);
}
const match = themes.find((t) => t.id.toLowerCase() === desiredLower);
selectEl.value = match ? match.id : DEFAULT_LIGHT_THEME_ID;
selectEl.title = themeTooltip(selectEl.value || DEFAULT_LIGHT_THEME_ID);
}
export function openSettings(section?: string){
openModal('settings-modal');
const modal = document.getElementById('settings-modal') as HTMLElement | null;
if (!modal) return;
applyPluginSettingsSections(modal);
renderPluginMenus(modal)
.catch(() => {})
.finally(() => {
if (section) activateSection(modal, section);
});
// Prevent a "double-click to refresh" feel where the user opens the Theme dropdown
// before the async settings/theme list has finished loading.
if (TAURI.has) {
modal.setAttribute('aria-busy', 'true');
const setThemeAuto = modal.querySelector<HTMLInputElement>('#set-theme-auto');
const setThemeSel = modal.querySelector<HTMLSelectElement>('#set-theme');
if (setThemeAuto) setThemeAuto.disabled = true;
if (setThemeSel) {
setThemeSel.disabled = true;
setThemeSel.innerHTML = '';
const opt = document.createElement('option');
opt.value = DEFAULT_LIGHT_THEME_ID;
opt.textContent = 'Loading…';
setThemeSel.appendChild(opt);
}
}
loadSettingsIntoForm(modal)
.catch(console.error)
.finally(() => {
modal.removeAttribute('aria-busy');
const setThemeAuto = modal.querySelector<HTMLInputElement>('#set-theme-auto');
if (setThemeAuto) setThemeAuto.disabled = false;
});
}
function activateSection(modal: HTMLElement, section: string) {
const nav = modal.querySelector('#settings-nav');
const panels = modal.querySelector('#settings-panels');
if (!nav || !panels) return;
const safeSection = (() => {
const requested = String(section || '').trim();
if (requested && nav.querySelector<HTMLElement>(`[data-section="${requested}"]`)) return requested;
return 'general';
})();
const btn = nav.querySelector<HTMLElement>(`[data-section="${safeSection}"]`);
nav.querySelectorAll<HTMLElement>('.seg-btn').forEach(b => {
b.classList.toggle('active', b === btn);
});
panels.querySelectorAll<HTMLElement>('.panel-form').forEach(p => {
p.classList.toggle('hidden', p.getAttribute('data-panel') !== safeSection);
});
// Keep footer actions hidden for action-only plugin menu panels.
const actions = modal.querySelector<HTMLElement>('.sheet-actions');
const activePanel = panels.querySelector<HTMLElement>(
`.panel-form[data-panel="${CSS.escape(safeSection)}"]`,
);
const isPluginMenuPanel = activePanel?.getAttribute('data-plugin-menu') === 'true';
const isPluginSettingsPanel = activePanel?.getAttribute('data-plugin-settings') === 'true';
const hideActions = safeSection === 'plugins' || (isPluginMenuPanel && !isPluginSettingsPanel);
if (actions) actions.classList.toggle('hidden', hideActions);
if (isPluginSettingsPanel && activePanel) {
const pluginId = String(activePanel.dataset.pluginId || '').trim();
if (pluginId) {
ensurePluginSettingsLoaded(modal, pluginId, safeSection).catch(() => {});
}
}
}
/** Collects typed plugin setting values from a plugin-settings panel. */
function collectPluginSettingsFromPanel(
panel: HTMLElement,
): Array<{ id: string; value: unknown }> {
const entries: Array<{ id: string; value: unknown }> = [];
const controls = panel.querySelectorAll<HTMLInputElement | HTMLSelectElement>(
'[data-setting-id][data-setting-kind]',
);
for (const control of controls) {
const settingId = String(control.getAttribute('data-setting-id') || '').trim();
const kind = String(control.getAttribute('data-setting-kind') || '')
.trim()
.toLowerCase();
if (!settingId || !kind) continue;
let value: unknown;
if (kind === 'bool' && control instanceof HTMLInputElement) {
value = control.checked;
} else if (kind === 's32' || kind === 'u32' || kind === 'f64') {
const n = Number(control.value);
if (!Number.isFinite(n)) {
value = 0;
} else if (kind === 's32') {
value = Math.trunc(n);
} else if (kind === 'u32') {
value = Math.max(0, Math.trunc(n));
} else {
value = n;
}
} else {
value = control.value ?? '';
}
entries.push({ id: settingId, value });
}
return entries;
}
export function wireSettings() {
const modal = document.getElementById('settings-modal') as HTMLElement | null;
if (!modal || (modal as any).__wired) return;
(modal as any).__wired = true;
applyPluginSettingsSections(modal);
// Close on backdrop / [data-close]
modal.addEventListener('click', (e) => {
const backdrop = modal.querySelector('.backdrop');
if ((e.target as Element).matches?.('[data-close]') || e.target === backdrop) {
closeModal('settings-modal');
}
});
// Sidebar switching
const nav = modal.querySelector('#settings-nav') as HTMLElement | null;
const panels = modal.querySelector('#settings-panels') as HTMLElement | null;
if (nav && panels) {
nav.addEventListener('click', (e) => {
const btn = (e.target as HTMLElement).closest('[data-section]') as HTMLElement | null;
if (!btn) return;
const target = btn.getAttribute('data-section') || undefined;
if (!target) return;
activateSection(modal, target);
});
panels.addEventListener('click', async (e) => {
const btn = (e.target as HTMLElement).closest<HTMLButtonElement>('button[data-plugin-action][data-plugin-id]');
if (!btn || !TAURI.has) return;
const pluginId = btn.dataset.pluginId || '';
const actionId = btn.dataset.pluginAction || '';
if (!pluginId || !actionId) return;
try {
await TAURI.invoke('invoke_plugin_action', { pluginId, actionId });
} catch (err) {
console.error('Failed to invoke plugin action', err);
notify('Plugin action failed');
}
});
}
const lfsToggle = modal.querySelector<HTMLInputElement>('#set-lfs-enabled');
const lfsDependents = ['#set-lfs-concurrency', '#set-lfs-require-lock', '#set-lfs-bg-fetch']
.map(sel => modal.querySelector<HTMLInputElement>(sel))
.filter((el): el is HTMLInputElement => !!el);
const updateLfsDependentState = () => {
const enabled = !!lfsToggle?.checked;
lfsDependents.forEach(input => input.disabled = !enabled);
};
updateLfsDependentState();
lfsToggle?.addEventListener('change', updateLfsDependentState);
const mergeModeSel = modal.querySelector('#set-merge-mode') as HTMLSelectElement | null;
const mergeCustomGroups = Array.from(modal.querySelectorAll<HTMLElement>('[data-merge-custom]'));
const updateMergeCustomState = () => {
const custom = (mergeModeSel?.value || 'builtin') === 'custom';
mergeCustomGroups.forEach((group) => {
group.classList.toggle('disabled', !custom);
group.querySelectorAll('input, textarea, select').forEach((field) => {
(field as HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement).disabled = !custom;
});
});
};
updateMergeCustomState();
mergeModeSel?.addEventListener('change', updateMergeCustomState);
const sshBinSel = modal.querySelector('#set-git-ssh-binary') as HTMLSelectElement | null;
const sshPathInput = modal.querySelector('#set-git-ssh-path') as HTMLInputElement | null;
const updateSshPathState = () => {
if (!sshPathInput) return;
const mode = (sshBinSel?.value || 'auto').toLowerCase();
const enabled = mode === 'custom';
sshPathInput.disabled = !enabled;
if (!enabled) sshPathInput.value = '';
};
updateSshPathState();
sshBinSel?.addEventListener('change', updateSshPathState);
const setThemeAuto = modal.querySelector<HTMLInputElement>('#set-theme-auto');
const setThemeSel = modal.querySelector<HTMLSelectElement>('#set-theme');
const syncThemeTitle = () => {
if (!setThemeSel) return;
setThemeSel.title = themeTooltip(setThemeSel.value || DEFAULT_LIGHT_THEME_ID);
};
const applyThemeFromControls = async (opts: { silent?: boolean } = {}) => {
if (!setThemeSel) return;
const auto = !!setThemeAuto?.checked;
setThemeSel.disabled = auto;
const themeId = setThemeSel.value || DEFAULT_LIGHT_THEME_ID;
const mode: 'system' | 'light' | 'dark' = auto ? 'system' : modeForTheme(themeId);
setTheme(mode);
await selectThemePack(themeId, { silent: opts.silent, mode });
if (auto) {
setThemeSel.value = getActiveThemeId() || DEFAULT_LIGHT_THEME_ID;
}
syncThemeTitle();
};
setThemeSel?.addEventListener('pointerdown', () => {
if (setThemeAuto?.checked) return;
// Keep the options list in sync with the already-cached theme list without
// kicking off an async refresh during the same user gesture (which makes the
// native picker look stale until it's opened again).
rebuildThemePackOptions(setThemeSel, {
desiredId: setThemeSel.value,
forceReload: false,
}).catch(() => {});
});
setThemeSel?.addEventListener('change', () => {
applyThemeFromControls({ silent: true }).catch(() => {});
});
setThemeAuto?.addEventListener('change', () => {
applyThemeFromControls({ silent: true }).catch(() => {});
});
window.addEventListener('openvcs:theme-pack-changed', () => {
if (!setThemeAuto?.checked || !setThemeSel) return;
setThemeSel.value = getActiveThemeId() || DEFAULT_LIGHT_THEME_ID;
setThemeSel.disabled = true;
syncThemeTitle();
});
const settingsSave = modal.querySelector('#settings-save') as HTMLButtonElement | null;
const settingsReset = modal.querySelector('#settings-reset') as HTMLButtonElement | null;
if (settingsSave) {
settingsSave.style.width = '5rem';
settingsSave.style.textAlign = 'center';
}
settingsSave?.addEventListener('click', async () => {
if (!settingsSave) return;
if (settingsSave.classList.contains('saved-state') || settingsSave.classList.contains('saving-state')) return;
settingsSave.classList.add('saving-state');
settingsSave.disabled = true;
try {
const activePanel = modal.querySelector<HTMLElement>('#settings-panels .panel-form:not(.hidden)');
if (activePanel?.getAttribute('data-plugin-settings') === 'true') {
if (!TAURI.has) return;
const pluginId = String(activePanel.dataset.pluginId || '').trim();
if (!pluginId) {
notify('Failed to save plugin settings');
return;
}
await TAURI.invoke('save_plugin_settings', {
pluginId,
values: collectPluginSettingsFromPanel(activePanel),
});
notify('Plugin settings saved');
flashSavedState(settingsSave);
return;
}
const next = collectSettingsFromForm(modal);
if (TAURI.has) {
await TAURI.invoke('set_global_settings', { cfg: next });
}
modal.dataset.currentCfg = JSON.stringify(next);
const theme = (next.general?.theme || 'system') as 'system' | 'light' | 'dark';
const pack = String(next.general?.theme_pack || DEFAULT_LIGHT_THEME_ID);
setTheme(theme);
try { await selectThemePack(pack, { silent: true, mode: theme }); } catch {}
try {
const root = document.documentElement;
const tabw = Number(next?.diff?.tab_width ?? 4);
if (tabw && isFinite(tabw)) root.style.setProperty('--tab-size', String(tabw));
const uiScale = Number(next?.ux?.ui_scale ?? 1);
if (uiScale && isFinite(uiScale)) root.style.setProperty('--ui-scale', String(uiScale));
const mono = String(next?.ux?.font_mono || '').trim();
if (mono) root.style.setProperty('--mono', mono);
else root.style.removeProperty('--mono');
applyAnimationPreference(next?.performance?.animations);
} catch {}
notify('Settings saved');
flashSavedState(settingsSave);
} catch (e) {
console.error('Failed to save settings:', e);
notify('Failed to save settings');
} finally {
settingsSave.classList.remove('saving-state');
settingsSave.disabled = false;
}
});
settingsReset?.addEventListener('click', async () => {
try {
const activePanel = modal.querySelector<HTMLElement>('#settings-panels .panel-form:not(.hidden)');
if (activePanel?.getAttribute('data-plugin-settings') === 'true') {
if (!TAURI.has) return;
const pluginId = String(activePanel.dataset.pluginId || '').trim();
const section = String(activePanel.getAttribute('data-panel') || '').trim();
if (!pluginId) {
notify('Failed to reset plugin settings');
return;
}
await TAURI.invoke('reset_plugin_settings', { pluginId });
notify('Plugin settings reset');
clearPluginSettingsCache();
await renderPluginMenus(modal);
if (section) activateSection(modal, section);
return;
}
if (!TAURI.has) return;
const cur = await TAURI.invoke<GlobalSettings>('get_global_settings');
cur.general = {
theme: 'system',
theme_pack: DEFAULT_LIGHT_THEME_ID,
language: 'system',
default_backend: 'git',
update_channel: 'stable',
reopen_last_repos: true,
checks_on_launch: true,
telemetry: false,
crash_reports: false,
};
cur.diff = { tab_width: 4, ignore_whitespace: 'none', max_file_size_mb: 10, intraline: true, show_binary_placeholders: true, external_diff: {enabled:false,path:'',args:''}, external_merge: {enabled:false,path:'',args:''}, binary_exts: ['png','jpg','dds','uasset'] };
cur.lfs = { enabled: true, concurrency: 4, require_lock_before_edit: false, background_fetch_on_checkout: true };
cur.performance = { progressive_render: true, gpu_accel: true, animations: true };
cur.ux = { ui_scale: 1.0, font_mono: 'monospace', vim_nav: false, color_blind_mode: 'none', recents_limit: 10 };
cur.logging = { level: 'info', live_viewer: false, retain_archives: 10 };
cur.plugins = { disabled: [], enabled: [] };
await TAURI.invoke('set_global_settings', { cfg: cur });
applyAnimationPreference(cur.performance?.animations);
await loadSettingsIntoForm(modal);
setTheme('system');
try { await selectThemePack(DEFAULT_LIGHT_THEME_ID, { silent: true, mode: 'system' }); } catch {}
notify('Defaults restored');
} catch (e) { console.error('Failed to restore defaults:', e); notify('Failed to restore defaults'); }
});
// Settings are loaded by `openSettings()` on open.
}
function collectSettingsFromForm(root: HTMLElement): GlobalSettings {
const get = <T extends HTMLElement = HTMLElement>(sel: string) => root.querySelector<T>(sel);
const base = JSON.parse(root?.dataset.currentCfg || '{}');
const o: GlobalSettings = { ...base };
const autoTheme = !!get<HTMLInputElement>('#set-theme-auto')?.checked;
const themePack = get<HTMLSelectElement>('#set-theme')?.value || DEFAULT_LIGHT_THEME_ID;
const theme = autoTheme ? 'system' : modeForTheme(themePack);
o.general = {
...o.general,
theme,
theme_pack: themePack || DEFAULT_LIGHT_THEME_ID,
language: get<HTMLSelectElement>('#set-language')?.value,
default_backend: (get<HTMLSelectElement>('#set-default-backend')?.value || 'git') as any,
update_channel: get<HTMLSelectElement>('#set-update-channel')?.value || 'stable',
reopen_last_repos: !!get<HTMLInputElement>('#set-reopen-last')?.checked,
checks_on_launch: !!get<HTMLInputElement>('#set-checks-on-launch')?.checked,
};
o.diff = {
...o.diff,
tab_width: Number(get<HTMLInputElement>('#set-tab-width')?.value ?? 0),
ignore_whitespace: get<HTMLSelectElement>('#set-ignore-whitespace')?.value,
max_file_size_mb: Number(get<HTMLInputElement>('#set-max-file-size-mb')?.value ?? 0),
intraline: !!get<HTMLInputElement>('#set-intraline')?.checked,
show_binary_placeholders: !!get<HTMLInputElement>('#set-binary-placeholders')?.checked,
external_merge: (() => {
const mode = get<HTMLSelectElement>('#set-merge-mode')?.value || 'builtin';
const path = (get<HTMLInputElement>('#set-merge-path')?.value || '').trim();
const args = get<HTMLInputElement>('#set-merge-args')?.value || '';
return {
enabled: mode === 'custom' && path.length > 0,
path,
args,
};
})(),
};
if (get('#set-lfs-enabled') || get('#set-lfs-concurrency') || get('#set-lfs-require-lock')) {
const rawConc = Number(get<HTMLInputElement>('#set-lfs-concurrency')?.value ?? 0);
const conc = rawConc && isFinite(rawConc) ? Math.max(1, Math.min(16, rawConc)) : 4;
o.lfs = {
...o.lfs,
enabled: !!get<HTMLInputElement>('#set-lfs-enabled')?.checked,
concurrency: conc,
require_lock_before_edit: !!get<HTMLInputElement>('#set-lfs-require-lock')?.checked,
background_fetch_on_checkout: !!get<HTMLInputElement>('#set-lfs-bg-fetch')?.checked,
};
}
o.performance = {
...o.performance,
animations: !!get<HTMLInputElement>('#set-animations')?.checked,
progressive_render: !!get<HTMLInputElement>('#set-progressive-render')?.checked,
gpu_accel: !!get<HTMLInputElement>('#set-gpu-accel')?.checked,
};
const rlRaw = get<HTMLInputElement>('#set-recents-limit')?.value ?? '';
const recentsLimit = rlRaw.trim() === '' ? 10 : Math.max(1, Math.min(100, Number(rlRaw)));
o.ux = {
...o.ux,
ui_scale: Number(get<HTMLInputElement>('#set-ui-scale')?.value ?? 1),
font_mono: get<HTMLInputElement>('#set-font-mono')?.value,
vim_nav: !!get<HTMLInputElement>('#set-vim-nav')?.checked,
color_blind_mode: get<HTMLSelectElement>('#set-cb-mode')?.value,
recents_limit: recentsLimit,
};
// Logging
const keepRaw = get<HTMLInputElement>('#set-log-keep')?.value ?? '';
const keep = keepRaw.trim() === '' ? 10 : Math.max(1, Math.min(100, Number(keepRaw)));
o.logging = {
...o.logging,
level: (get<HTMLSelectElement>('#set-log-level')?.value || 'info') as any,
retain_archives: keep,
};
const pluginsStateKey = '__pluginsPanelState';
const pluginsState = (root as any)[pluginsStateKey] as { disabled?: Set<string>; enabled?: Set<string>; list?: PluginSummary[] } | undefined;
if (pluginsState?.disabled instanceof Set && pluginsState?.enabled instanceof Set) {
const byLower = new Map<string, string>();
for (const plugin of Array.isArray(pluginsState.list) ? pluginsState.list : []) {
const id = String(plugin?.id || '').trim();
if (!id) continue;
byLower.set(id.toLowerCase(), id);
}
const disabled = Array.from(pluginsState.disabled.values())
.map((id) => String(id || '').trim().toLowerCase())
.filter(Boolean)
.map((id) => byLower.get(id) || id);
const enabled = Array.from(pluginsState.enabled.values())
.map((id) => String(id || '').trim().toLowerCase())
.filter(Boolean)
.map((id) => byLower.get(id) || id);
o.plugins = { ...(o.plugins || {}), disabled, enabled };
} else {
const pluginToggles = Array.from(root.querySelectorAll<HTMLInputElement>('[data-plugin-id]'));
if (pluginToggles.length) {
const disabled: string[] = [];
const enabled: string[] = [];
for (const toggle of pluginToggles) {
const id = String(toggle.dataset.pluginId || '').trim();
if (!id) continue;
if (toggle.checked) enabled.push(id);
else disabled.push(id);
}
o.plugins = { ...(o.plugins || {}), disabled, enabled };
}
}
return o;
}
export async function loadSettingsIntoForm(root?: HTMLElement) {
const m = root || (document.getElementById('settings-modal') as HTMLElement | null);
if (!m) return;
const get = <T extends HTMLElement = HTMLElement>(sel: string) => m.querySelector<T>(sel);
const cfg = TAURI.has ? await TAURI.invoke<GlobalSettings>('get_global_settings') : null;
if (!cfg) return;
m.dataset.currentCfg = JSON.stringify(cfg);
await loadPluginsIntoForm(m, cfg);
const themeSel = get<HTMLSelectElement>('#set-theme');
const elAuto = get<HTMLInputElement>('#set-theme-auto');
const themePref = (cfg.general?.theme || 'system') as 'system'|'light'|'dark';
if (elAuto) elAuto.checked = themePref === 'system';
if (themeSel) {
let desiredId = String(cfg.general?.theme_pack || DEFAULT_LIGHT_THEME_ID);
if (desiredId.trim().toLowerCase() === DEFAULT_THEME_ID) {
desiredId = themePref === 'dark' ? DEFAULT_DARK_THEME_ID : DEFAULT_LIGHT_THEME_ID;
}
await rebuildThemePackOptions(themeSel, {
desiredId,
forceReload: true,
});
themeSel.disabled = themePref === 'system';
if (themePref === 'system') {
themeSel.value = getActiveThemeId() || themeSel.value;
}
}
const elLang = get<HTMLSelectElement>('#set-language'); if (elLang) elLang.value = toKebab(cfg.general?.language);
await refreshDefaultBackendOptions(m, cfg);
const elChan = get<HTMLSelectElement>('#set-update-channel'); if (elChan) {
elChan.value = toKebab(cfg.general?.update_channel);
}
const elReo = get<HTMLInputElement>('#set-reopen-last'); if (elReo) elReo.checked = !!cfg.general?.reopen_last_repos;
const elChk = get<HTMLInputElement>('#set-checks-on-launch'); if (elChk) elChk.checked = !!cfg.general?.checks_on_launch;
const elRl = get<HTMLInputElement>('#set-recents-limit'); if (elRl) elRl.value = String(cfg.ux?.recents_limit ?? 10);
const elTw = get<HTMLInputElement>('#set-tab-width'); if (elTw) elTw.value = String(cfg.diff?.tab_width ?? 0);
const elIw = get<HTMLSelectElement>('#set-ignore-whitespace'); if (elIw) elIw.value = toKebab(cfg.diff?.ignore_whitespace);
const elMx = get<HTMLInputElement>('#set-max-file-size-mb'); if (elMx) elMx.value = String(cfg.diff?.max_file_size_mb ?? 0);
const elIn = get<HTMLInputElement>('#set-intraline'); if (elIn) elIn.checked = !!cfg.diff?.intraline;
const elBp = get<HTMLInputElement>('#set-binary-placeholders'); if (elBp) elBp.checked = !!cfg.diff?.show_binary_placeholders;
const elMm = get<HTMLSelectElement>('#set-merge-mode');
const elMp = get<HTMLInputElement>('#set-merge-path');
const elMa = get<HTMLInputElement>('#set-merge-args');
if (elMp) elMp.value = cfg.diff?.external_merge?.path ?? '';
if (elMa) elMa.value = cfg.diff?.external_merge?.args ?? '';
if (elMm) {
const ext = cfg.diff?.external_merge;
elMm.value = ext && ext.enabled && (ext.path || '').trim().length > 0 ? 'custom' : 'builtin';
elMm.dispatchEvent(new Event('change'));
}
const elLe = get<HTMLInputElement>('#set-lfs-enabled'); if (elLe) elLe.checked = !!cfg.lfs?.enabled;
const elLc = get<HTMLInputElement>('#set-lfs-concurrency'); if (elLc) elLc.value = String(cfg.lfs?.concurrency ?? 0);
const elLl = get<HTMLInputElement>('#set-lfs-require-lock'); if (elLl) elLl.checked = !!cfg.lfs?.require_lock_before_edit;
const elBg = get<HTMLInputElement>('#set-lfs-bg-fetch'); if (elBg) elBg.checked = !!cfg.lfs?.background_fetch_on_checkout;
elLe?.dispatchEvent(new Event('change'));
const elAni= get<HTMLInputElement>('#set-animations'); if (elAni) elAni.checked = cfg.performance?.animations !== false;
const elPrg= get<HTMLInputElement>('#set-progressive-render'); if (elPrg) elPrg.checked = !!cfg.performance?.progressive_render;
const elGpu= get<HTMLInputElement>('#set-gpu-accel'); if (elGpu) elGpu.checked = !!cfg.performance?.gpu_accel;
const elUi = get<HTMLInputElement>('#set-ui-scale'); if (elUi) elUi.value = String(cfg.ux?.ui_scale ?? 1.0);
const elFm = get<HTMLInputElement>('#set-font-mono'); if (elFm) elFm.value = cfg.ux?.font_mono ?? 'monospace';
const elVn = get<HTMLInputElement>('#set-vim-nav'); if (elVn) elVn.checked = !!cfg.ux?.vim_nav;
const elCb = get<HTMLSelectElement>('#set-cb-mode'); if (elCb) elCb.value = toKebab(cfg.ux?.color_blind_mode);
// Logging
const elLvl = get<HTMLSelectElement>('#set-log-level'); if (elLvl) elLvl.value = toKebab(cfg.logging?.level || 'info');
const elKeep= get<HTMLInputElement>('#set-log-keep'); if (elKeep) elKeep.value = String(cfg.logging?.retain_archives ?? 10);
}
async function refreshDefaultBackendOptions(modal: HTMLElement, cfg: GlobalSettings) {
const el = modal.querySelector<HTMLSelectElement>('#set-default-backend');
if (!el) return;
const desired = String(cfg.general?.default_backend || '').trim();
let available: Array<[string, string]> = [];
if (TAURI.has) {
try {
available = await TAURI.invoke<Array<[string, string]>>('list_vcs_backends_cmd');
} catch {}
}
const backends = (Array.isArray(available) ? available : [])
.map(([id, name]) => [String(id || '').trim(), String(name || '').trim()] as const)
.filter(([id]) => id.length > 0);
el.innerHTML = '';
for (const [id, name] of backends) {
const opt = document.createElement('option');
opt.value = id;
opt.textContent = name || id;
el.appendChild(opt);
}
el.disabled = backends.length === 0;
if (!backends.length) return;
if (desired && backends.some(([id]) => id === desired)) {