herdr-gentle-shell 1.7.0 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,24 +1,39 @@
1
1
  'use strict';
2
2
 
3
- // The `/herdr-gentle:customize` floating panel, recovered from commit 0e92869
4
- // (odd/tasks/restore-customize-panel.md T1, S1/S2) and shaped like Gentle
5
- // Shell's own customize card (odd/tasks/customize-parity-done-idle.md T1, S1).
3
+ // The `/herdr-gentle:customize` floating panel, rebuilt after Gentle Shell's own
4
+ // customize card (odd/tasks/theme-sync-fix.md T4; S1/S2/S5/S6/S7).
6
5
  //
7
- // One left `CATEGORIES` list, one right pane headed `<Category> · n/m` holding
8
- // the setting rows, one line describing what the focused setting does, and the
9
- // Shell's footer keys. Each switch is ONE row that paints the stored value with
10
- // `●` and the other with `○`, so Enter (or a click on the row) is still the
11
- // whole toggle. The removed worktree / ODD / Issues / Reset sections are gone,
12
- // and the panel reads the current state handed in by the extension instead of a
13
- // cross-extension provider slot.
6
+ // One left `CATEGORIES` list and one right pane headed `<Category> · n/m`. Each
7
+ // setting is ONE line with its options inline — `●` marks the stored option, `›`
8
+ // the cursor option while it is elsewhere, `○` the rest — so moving the cursor
9
+ // never applies anything and only Enter confirms (upstream's `applyOnMove:
10
+ // false` for every setting here). When a line's options do not fit, the panel
11
+ // scrolls sideways: a window that always contains the cursor option, muted `‹`
12
+ // and `›` markers where options hide, and an `n/m` counter; if not even one
13
+ // option fits, upstream's compact `‹ value ›` form takes over.
14
+ //
15
+ // Below the panes sits the Shell's Preview block: a headline naming the
16
+ // highlighted option and its preview title, then the sample lines, all painted
17
+ // with the host theme (the theme swatch keeps its own raw SGR, because it must
18
+ // show THAT theme's colours, not the active one).
14
19
  //
15
20
  // The host component contract (pi-coding-agent `custom`): the factory receives
16
21
  // (hostTui, theme, keybindings, done) and returns
17
22
  // { render(width), handleInput(data), handleMouse(event), invalidate() }.
18
23
  // Selection keys and pointer hits only move local state and ask the host to
19
- // repaint; Esc finishes with done(null) and Enter (or a row click) with
20
- // done({categoryId, switchId, valueId}). This module never writes, notifies, or
21
- // reloads: the extension's single apply path runs after the overlay resolves.
24
+ // repaint; Esc finishes with done(null), and Enter (or an option click) awaits
25
+ // the injected `apply({ categoryId, settingId, optionId })`. The panel then
26
+ // swaps in the model that apply re-read, keeping the cursor by ids, and stays
27
+ // open unless apply answered `close: true` (the Moshi reload must not happen
28
+ // behind a mounted card). This module never writes, notifies, or reloads.
29
+ //
30
+ // The model is categories -> settings -> options. Option ids are structural
31
+ // (`on`, `none`, `theme:<name>`) and never derived from a label, so an installed
32
+ // theme literally named `None` or `Off` stays selectable and pinnable.
33
+
34
+ // The stored theme value is normalised by lib/theme-projection.js, so the panel
35
+ // and the store can never disagree about what "no theme" means.
36
+ const { normalizeThemeName } = require('./theme-projection.js');
22
37
 
23
38
  const ROLE = Object.freeze({
24
39
  key: "accent",
@@ -31,8 +46,7 @@ const ROLE = Object.freeze({
31
46
  error: "error",
32
47
  });
33
48
 
34
- // The palette the former card shared with the other readers (then a separate
35
- // module): theme ROLE NAMES only, so a missing, partial or throwing theme
49
+ // The palette: theme ROLE NAMES only, so a missing, partial or throwing theme
36
50
  // degrades to plain text instead of breaking a render. Keys and titles are
37
51
  // emphasized through the theme's own `bold`, which keeps them distinguishable
38
52
  // in a monochrome terminal.
@@ -150,97 +164,110 @@ const CUSTOMIZE_TITLE = "Customize · Herdr Gentle Shell";
150
164
  const CUSTOMIZE_CARD_PADDING = 4;
151
165
  const CUSTOMIZE_NARROW_WIDTH = 60;
152
166
  const CUSTOMIZE_MAX_HEIGHT = 24;
153
- // The Shell's row vocabulary: `●` is the stored value, `○` the other one.
154
- const CUSTOMIZE_PILL_CURRENT = "●";
155
- const CUSTOMIZE_PILL_OTHER = "○";
156
-
157
- // The switches this package owns. `id` is the apply target the extension knows
158
- // (the sidebar rows go through the Herdr plugin's own configure step,
159
- // notifications through the `gentle-moshi.json` flag and its Pi settings
160
- // exclusion) and `setting` is the row name the panel paints. `description` is
161
- // the one line the card shows for the focused setting: it says what the switch
162
- // changes, and the notification switch is the Moshi channel, never the agent
163
- // notifications the host owns.
164
- const CUSTOMIZE_SWITCHES = [
165
- {
167
+ // The Shell's option vocabulary: `●` is the stored option, `›` the cursor while
168
+ // it is not the stored one, `○` everything else.
169
+ const CUSTOMIZE_MARK_CURRENT = "●";
170
+ const CUSTOMIZE_MARK_CURSOR = "›";
171
+ const CUSTOMIZE_MARK_OTHER = "○";
172
+ const CUSTOMIZE_OPTION_GAP = " ";
173
+ // The pointer hint lives in the footer exactly like upstream's `Click · …`.
174
+ const CUSTOMIZE_CLICK_PREFIX = "Click · ";
175
+
176
+ // The three settings this package owns, with the upstream order of their two
177
+ // options and the static preview each option carries. `id` is the apply target
178
+ // the extension knows; it is structural, never the label.
179
+ const CUSTOMIZE_SIDEBAR_SAMPLE_ON = "● project gentle worker";
180
+ const CUSTOMIZE_SIDEBAR_SAMPLE_OFF = "native Herdr rows; no managed block";
181
+ const CUSTOMIZE_MOSHI_SAMPLE_ON = "ask finished";
182
+ const CUSTOMIZE_MOSHI_SAMPLE_OFF = "silent; no Moshi notification";
183
+ const CUSTOMIZE_SYNC_SAMPLE_ON = "Herdr follows the theme active in Pi";
184
+ const CUSTOMIZE_SYNC_SAMPLE_OFF = "Herdr keeps its last palette";
185
+ const CUSTOMIZE_THEME_NONE_SAMPLE = "no theme pinned; Herdr keeps its last palette";
186
+
187
+ const CUSTOMIZE_TOGGLES = Object.freeze({
188
+ sidebar: {
166
189
  id: "sidebar",
167
190
  setting: "Sidebar agent rows",
168
- description: "Hands the Herdr sidebar to this plugin's managed agent rows.",
191
+ order: ["on", "off"],
192
+ // S5: the sample shows what the managed rows add, from the README's own
193
+ // description of the heading cell and the role words.
194
+ preview: (which) => ({
195
+ title: "static sidebar sample",
196
+ sample: which === "on" ? CUSTOMIZE_SIDEBAR_SAMPLE_ON : CUSTOMIZE_SIDEBAR_SAMPLE_OFF,
197
+ }),
198
+ unknownNote: "state unknown; Enter turns the rows on",
169
199
  },
170
- {
200
+ moshi: {
171
201
  id: "moshi",
172
202
  setting: "Notifications",
173
- description: "Replaces the Moshi hook with this plugin's own notification channel.",
174
- },
175
- ];
176
-
177
- // Two categories, one row each. `Herdr Sidebar` owns the managed agent rows the
178
- // plugin publishes and nothing else: the Moshi notification channel lives only
179
- // under `Moshi notifications`, so the sidebar switch can never toggle it.
180
- const CUSTOMIZE_CATEGORIES = [
181
- {
182
- id: "sidebar",
183
- title: "Herdr Sidebar",
184
- description: "The managed agent rows this plugin hands to the Herdr sidebar.",
185
- switches: ["sidebar"],
203
+ order: ["on", "off"],
204
+ preview: (which) => ({
205
+ title: "static notification sample",
206
+ sample: which === "on" ? CUSTOMIZE_MOSHI_SAMPLE_ON : CUSTOMIZE_MOSHI_SAMPLE_OFF,
207
+ }),
186
208
  },
187
- {
188
- id: "moshi",
189
- title: "Moshi notifications",
190
- description: "The Moshi notification channel this plugin owns.",
191
- switches: ["moshi"],
209
+ "theme-sync": {
210
+ id: "theme-sync",
211
+ setting: "Theme sync",
212
+ order: ["off", "on"],
213
+ preview: (which) => ({
214
+ title: "static sync sample",
215
+ sample: which === "on" ? CUSTOMIZE_SYNC_SAMPLE_ON : CUSTOMIZE_SYNC_SAMPLE_OFF,
216
+ }),
217
+ // An unreadable store is repairable with one key press instead of blocking
218
+ // the setting, so the note says what the action does.
219
+ unknownNote: "state unknown; Enter turns the sync on",
192
220
  },
193
- ];
194
-
195
- // One row per switch: it paints the stored value and carries the value Enter
196
- // applies, so a single key press is the whole toggle. `Unknown` keeps the row
197
- // actionable instead of blocking the repair, so an inconclusive check can
198
- // always be re-run from here.
199
- function toggleRow(definition, active) {
200
- const current = active === "on" || active === "off" ? active : null;
201
- return {
202
- id: current === "on" ? "off" : "on",
203
- switchId: definition.id,
204
- setting: definition.setting,
205
- description: definition.description,
206
- current,
207
- currentLabel: current === "on" ? "On" : current === "off" ? "Off" : "Unknown",
208
- otherLabel: current === "on" ? "Off" : "On",
209
- note: current === null ? "state unknown; Enter re-runs the managed rows" : undefined,
210
- };
211
- }
221
+ });
212
222
 
213
- // The current stored values as the extension read them. A sidebar state of
214
- // `unknown` (unresolvable plugin root or inconclusive `--check`) is never a
215
- // guessed value and never blocks the repair: the row stays selectable and a
216
- // note explains that On re-runs the managed rows. Notifications are always a
217
- // readable local flag.
218
- function customizePanelModel({ sidebar, moshi } = {}) {
219
- const stored = (value) => (value === "on" || value === "off" ? value : null);
220
- const current = { sidebar: stored(sidebar), moshi: stored(moshi) === "on" ? "on" : "off" };
221
- return CUSTOMIZE_CATEGORIES.map((category) => ({
222
- id: category.id,
223
- title: category.title,
224
- description: category.description,
225
- rows: category.switches.map((switchId) => toggleRow(
226
- CUSTOMIZE_SWITCHES.find((entry) => entry.id === switchId),
227
- current[switchId],
228
- )),
229
- }));
230
- }
223
+ // The theme list's inert option. `none` is its ID and `None` its label: an
224
+ // installed theme called `None` keeps the ID `theme:None`, so the two can never
225
+ // collide and both stay selectable.
226
+ const CUSTOMIZE_THEME_SETTING_ID = "theme";
227
+ const CUSTOMIZE_THEME_NONE_ID = "none";
228
+ const CUSTOMIZE_THEME_NONE_LABEL = "None";
229
+ const CUSTOMIZE_THEME_OPTION_PREFIX = "theme:";
230
+ const CUSTOMIZE_THEME_UNAVAILABLE_NOTE = "Themes unavailable; use Pi /settings";
231
+ const CUSTOMIZE_THEME_DISABLED_NOTE = "Turn Theme sync off to pick a specific theme.";
232
+ const CUSTOMIZE_THEME_UNKNOWN_NOTE = "state unknown; Enter pins a theme";
231
233
 
232
234
  // The key legend is ONE terminal row: the `key` spelling paints as the key
233
235
  // role and the rest as its description. `short` is the compact form, and
234
236
  // `priority` is the drop order, so the close key outlives every other hint.
235
237
  // There is no `p profiles` entry: this plugin owns no profiles concept, and a
236
- // dead key in the footer would be a lie. The pointer needs no entry either:
237
- // every legend token names a key the panel answers to.
238
- const CUSTOMIZE_FOOTER_KEYS = [
239
- { key: "←/→", text: "←/→ or Tab panes", short: "←/→ panes", priority: 60 },
240
- { key: "↑/↓", text: "↑/↓ move", short: "↑/↓ move", priority: 70 },
241
- { key: "Enter", text: "Enter apply", short: "Enter apply", priority: 80 },
242
- { key: "Esc", text: "Esc close", short: "Esc close", priority: 100 },
243
- ];
238
+ // dead key in the footer would be a lie.
239
+ //
240
+ // Three variants, chosen like upstream's `footerHint` (lib/visual-customize-view.ts
241
+ // in gentle-shell): the legend names what the keys do RIGHT NOW. A narrow card
242
+ // that only lists categories opens them with `→`; a focused option row reads
243
+ // `←/→ choose` (the arrows move the cursor and only Enter applies); the
244
+ // categories pane keeps the pane-switching legend.
245
+ const CUSTOMIZE_FOOTER_VARIANTS = {
246
+ categories: [
247
+ { key: "↑/↓", text: "↑/↓ categories", short: "↑/↓ move", priority: 70 },
248
+ { key: "→", text: "→ open", short: "→ open", priority: 80 },
249
+ { key: "Esc", text: "Esc close", short: "Esc close", priority: 100 },
250
+ ],
251
+ choose: [
252
+ { key: "←/→", text: "←/→ choose", short: "←/→ choose", priority: 70 },
253
+ { key: "Enter", text: "Enter apply", short: "Enter apply", priority: 90 },
254
+ { key: "↑/↓", text: "↑/↓ settings", short: "↑/↓ move", priority: 60 },
255
+ { key: "Tab", text: "Tab panes", short: "Tab panes", priority: 50 },
256
+ { key: "Esc", text: "Esc close", short: "Esc close", priority: 100 },
257
+ ],
258
+ panes: [
259
+ { key: "←/→", text: "←/→ or Tab panes", short: "←/→ panes", priority: 60 },
260
+ { key: "↑/↓", text: "↑/↓ move", short: "↑/↓ move", priority: 70 },
261
+ { key: "Enter", text: "Enter apply", short: "Enter apply", priority: 80 },
262
+ { key: "Esc", text: "Esc close", short: "Esc close", priority: 100 },
263
+ ],
264
+ };
265
+
266
+ function customizeFooterVariant(navOnly, pane, focusedSetting) {
267
+ if (navOnly) return CUSTOMIZE_FOOTER_VARIANTS.categories;
268
+ const onOptions = pane === "controls" && focusedSetting && Array.isArray(focusedSetting.options) && focusedSetting.options.length > 0;
269
+ return onOptions ? CUSTOMIZE_FOOTER_VARIANTS.choose : CUSTOMIZE_FOOTER_VARIANTS.panes;
270
+ }
244
271
 
245
272
  function customizeStripAnsi(value) {
246
273
  return String(value).replace(/\x1b\[[0-9;]*m/g, "").replace(/\x1b\]8;;.*?\x07/g, "");
@@ -302,28 +329,32 @@ function customizeCompose(helpers, theme, segments, size) {
302
329
  return painted + " ".repeat(Math.max(0, size - customizeMeasure(helpers, clipped)));
303
330
  }
304
331
 
305
- // An ALREADY painted row (the palette legend paints itself): pad it to `size`
306
- // without repainting, measuring visible columns.
332
+ // An ALREADY painted row: pad it to `size` without repainting, measuring
333
+ // visible columns.
307
334
  function customizePad(helpers, text, size) {
308
335
  return text + " ".repeat(Math.max(0, size - customizeMeasure(helpers, text)));
309
336
  }
310
337
 
311
338
  // The legend stays on ONE row: the compaction (full tokens, then short tokens,
312
339
  // then dropping the lowest-priority entries; display order never changes) and
313
- // the key/description painting live in the palette above. A legend still wider
314
- // than the card is truncated UNPAINTED so a cut never lands inside an escape.
340
+ // the key/description painting live in the palette above. The `Click · ` prefix
341
+ // is part of the row, exactly like upstream's footer, and costs width before
342
+ // any entry is dropped. A legend still wider than the card is truncated
343
+ // UNPAINTED so a cut never lands inside an escape.
315
344
  function customizeFooter(helpers, theme, entries, size) {
316
345
  const measure = (text) => customizeMeasure(helpers, text);
317
- const plain = palette.legendRow(null, entries, size, measure);
346
+ const prefixWidth = measure(CUSTOMIZE_CLICK_PREFIX);
347
+ const legendWidth = Math.max(0, size - prefixWidth);
348
+ const plain = `${CUSTOMIZE_CLICK_PREFIX}${palette.legendRow(null, entries, legendWidth, measure)}`;
318
349
  if (measure(plain) > size) return customizeFit(helpers, plain, Math.max(0, size));
319
- return palette.legendRow(theme, entries, size, measure);
350
+ return `${palette.description(theme, CUSTOMIZE_CLICK_PREFIX)}${palette.legendRow(theme, entries, legendWidth, measure)}`;
320
351
  }
321
352
 
322
353
  // Focused-row selection: a full-width band when the injected theme paints
323
354
  // backgrounds, else an accent ▸ marker — never a hardcoded escape, so focus
324
355
  // stays readable on a theme that answers neither.
325
- function customizeSelect(helpers, theme, label, size, focused) {
326
- const safe = String(label).split("\n")[0] ?? "";
356
+ function customizeSelect(helpers, theme, text, size, focused) {
357
+ const safe = String(text).split("\n")[0] ?? "";
327
358
  if (focused && theme && typeof theme.bg === "function") {
328
359
  try {
329
360
  const row = customizeFit(helpers, ` ${safe}`, Math.max(0, size));
@@ -378,47 +409,320 @@ function customizeIsKeyRelease(helpers, data) {
378
409
  return false;
379
410
  }
380
411
 
381
- // One setting line: the name column, then the Shell's pill pair — `●` on the
382
- // stored value and `○` on the other. A pair wider than the pane falls back to
383
- // the stored pill alone, so the narrow width keeps showing the real state.
384
- // `focused` marks the row Enter would apply (visible in either pane, so the
385
- // keyboard always shows its target) and `active` adds the band, which only the
386
- // pane that owns the focus paints.
387
- function customizeSettingLine(helpers, theme, row, nameWidth, size, focused, active) {
388
- const name = String(row.setting);
412
+ /* ------------------------------------------------------------------- model */
413
+
414
+ // A preview is either the upstream `{ title, sample }` pair or nothing at all:
415
+ // an unreadable source says so instead of falling back to the active theme.
416
+ function customizePreviewValue(themePreview, name) {
417
+ if (typeof themePreview !== "function") return null;
418
+ let preview;
419
+ try {
420
+ preview = themePreview(name);
421
+ } catch {
422
+ return null;
423
+ }
424
+ if (!preview || typeof preview !== "object") return null;
425
+ if (typeof preview.title !== "string" || typeof preview.sample !== "string") return null;
426
+ return { title: preview.title, sample: preview.sample };
427
+ }
428
+
429
+ function customizeOption(id, optionLabel, current, preview) {
430
+ return { id, label: optionLabel, current: current === true, preview: preview ?? null };
431
+ }
432
+
433
+ // One boolean setting. `value` is the stored option ("on"/"off") or null when
434
+ // the state could not be read: an unreadable state marks NO option current and
435
+ // carries a note instead of guessing.
436
+ function customizeToggleSetting(definition, stored) {
437
+ const current = stored === "on" || stored === "off" ? stored : null;
438
+ return {
439
+ id: definition.id,
440
+ setting: definition.setting,
441
+ ...(current === null ? { note: definition.unknownNote ?? "state unknown" } : {}),
442
+ options: definition.order.map((which) => customizeOption(
443
+ which,
444
+ which === "on" ? "On" : "Off",
445
+ current === which,
446
+ definition.preview(which),
447
+ )),
448
+ };
449
+ }
450
+
451
+ // The one setting that is not a boolean: `None` plus one option per installed
452
+ // theme, in Pi's own order. Its options are disabled (still selectable) only
453
+ // while the stored sync is on, and an unavailable theme list shows one note
454
+ // with no options at all instead of an empty list that looks pickable.
455
+ function customizeThemeSetting(themeState, themeNames, themePreview) {
456
+ const readable = themeState.ok !== false;
457
+ const syncOn = readable && themeState.sync === true;
458
+ const assigned = readable ? normalizeThemeName(themeState.theme) : null;
459
+ const listed = Array.isArray(themeNames);
460
+ const options = listed
461
+ ? [
462
+ customizeOption(
463
+ CUSTOMIZE_THEME_NONE_ID,
464
+ CUSTOMIZE_THEME_NONE_LABEL,
465
+ readable && assigned === null,
466
+ { title: "static unassigned sample", sample: CUSTOMIZE_THEME_NONE_SAMPLE },
467
+ ),
468
+ ...themeNames.map((name) => customizeOption(
469
+ `${CUSTOMIZE_THEME_OPTION_PREFIX}${name}`,
470
+ name,
471
+ readable && assigned === name,
472
+ customizePreviewValue(themePreview, name),
473
+ )),
474
+ ]
475
+ : [];
476
+ const notes = [];
477
+ if (!readable) notes.push(CUSTOMIZE_THEME_UNKNOWN_NOTE);
478
+ else if (syncOn) notes.push(CUSTOMIZE_THEME_DISABLED_NOTE);
479
+ if (!listed) notes.push(CUSTOMIZE_THEME_UNAVAILABLE_NOTE);
480
+ return {
481
+ id: CUSTOMIZE_THEME_SETTING_ID,
482
+ setting: "Gentle Shell theme",
483
+ ...(syncOn ? { disabled: true } : {}),
484
+ ...(notes.length ? { note: notes.join(" ") } : {}),
485
+ options,
486
+ };
487
+ }
488
+
489
+ // The current stored values as the extension read them. A sidebar state of
490
+ // `unknown` (unresolvable plugin root or inconclusive `--check`) and an
491
+ // unreadable theme store are never guessed values. `themeNames` is the host's
492
+ // theme list (`null` when the host exposes none) and `themePreview(name)` the
493
+ // per-theme swatch.
494
+ function customizePanelModel({ sidebar, moshi, theme, themeNames, themePreview } = {}) {
495
+ const stored = (value) => (value === "on" || value === "off" ? value : null);
496
+ const themeState = theme && typeof theme === "object"
497
+ ? theme
498
+ : { ok: false, sync: false, theme: null };
499
+ const themeSync = themeState.ok === false ? null : stored(themeState.sync === true ? "on" : "off");
500
+ const current = {
501
+ sidebar: stored(sidebar),
502
+ moshi: stored(moshi) === "on" ? "on" : "off",
503
+ };
504
+ return [
505
+ {
506
+ id: "sidebar",
507
+ title: "Herdr Sidebar",
508
+ settings: [customizeToggleSetting(CUSTOMIZE_TOGGLES.sidebar, current.sidebar)],
509
+ },
510
+ {
511
+ id: "moshi",
512
+ title: "Moshi notifications",
513
+ settings: [customizeToggleSetting(CUSTOMIZE_TOGGLES.moshi, current.moshi)],
514
+ },
515
+ {
516
+ id: "theme",
517
+ title: "Herdr Theme",
518
+ settings: [
519
+ customizeToggleSetting(CUSTOMIZE_TOGGLES["theme-sync"], themeSync),
520
+ customizeThemeSetting(themeState, themeNames, themePreview),
521
+ ],
522
+ },
523
+ ];
524
+ }
525
+
526
+ /* ---------------------------------------------------------- setting line */
527
+
528
+ // One setting line: the name column, then every option inline. `●` is the
529
+ // stored option, `›` the cursor while it is not the stored one, `○` the rest.
530
+ //
531
+ // A body wider than the pane becomes a sideways window that always contains the
532
+ // cursor option: muted `‹`/`›` mark hidden options on either side and an `n/m`
533
+ // counter names the cursor. Not even one option fitting falls back to upstream's
534
+ // compact `‹ value ›` form. The line is then fitted with an ellipsis, so a
535
+ // still-too-wide value is visibly cut instead of reading like a complete one.
536
+ //
537
+ // `focused` marks the line the keys act on (visible in either pane, so the
538
+ // keyboard always shows its target); `active` adds the band, which only the
539
+ // controls pane paints. A DISABLED setting is painted in the dim role and is
540
+ // never offered the band, because the band is this card's promise that Enter
541
+ // applies it.
542
+ function customizeSettingLine(helpers, theme, setting, cursorAt, nameWidth, size, focused, active) {
543
+ const name = String(setting.setting);
389
544
  const namePad = " ".repeat(Math.max(0, nameWidth - customizeMeasure(helpers, name)));
390
545
  const prefix = focused ? "▸ " : " ";
391
- const lead = `${prefix}${name}${namePad} `;
392
- const stored = `${CUSTOMIZE_PILL_CURRENT} ${row.currentLabel}`;
393
- const other = `${CUSTOMIZE_PILL_OTHER} ${row.otherLabel}`;
394
- const pair = `${stored} ${other}`;
395
- const showPair = customizeMeasure(helpers, `${lead}${pair}`) <= size;
396
- const body = showPair ? pair : stored;
397
- if (active && theme && typeof theme.bg === "function") {
546
+ const lead = `${name}${namePad}${CUSTOMIZE_OPTION_GAP}`;
547
+ const bodyStart = 2 + customizeMeasure(helpers, lead);
548
+ const budget = Math.max(0, size - bodyStart);
549
+ const disabled = setting.disabled === true;
550
+ const options = Array.isArray(setting.options) ? setting.options : [];
551
+ const cursor = Math.min(Math.max(0, cursorAt), Math.max(0, options.length - 1));
552
+ const kinds = (option, index) => {
553
+ if (disabled) return "label";
554
+ const current = option.current === true;
555
+ const atCursor = focused && index === cursor;
556
+ return current || (atCursor && !current) ? "accent" : "description";
557
+ };
558
+ const marks = options.map((option, index) => ({
559
+ index,
560
+ text: `${option.current === true
561
+ ? CUSTOMIZE_MARK_CURRENT
562
+ : (focused && index === cursor ? CUSTOMIZE_MARK_CURSOR : CUSTOMIZE_MARK_OTHER)} ${option.label}`,
563
+ kind: kinds(option, index),
564
+ }));
565
+ // Every option joined: the plain form when it fits, the window or the compact
566
+ // form otherwise.
567
+ const body = [];
568
+ const joined = marks.map((mark) => mark.text).join(CUSTOMIZE_OPTION_GAP);
569
+ if (customizeMeasure(helpers, joined) <= budget) {
570
+ marks.forEach((mark, index) => {
571
+ if (index > 0) body.push({ text: CUSTOMIZE_OPTION_GAP });
572
+ body.push({ text: mark.text, kind: mark.kind, option: mark.index });
573
+ });
574
+ } else if (marks.length) {
575
+ const counter = `${cursor + 1}/${options.length}`;
576
+ const windowAt = (first, last) => {
577
+ const segments = [];
578
+ if (first > 0) segments.push({ kind: "description", text: "‹ " });
579
+ for (let index = first; index <= last; index += 1) {
580
+ if (index > first) segments.push({ text: CUSTOMIZE_OPTION_GAP });
581
+ segments.push({ text: marks[index].text, kind: marks[index].kind, option: index });
582
+ }
583
+ if (last < marks.length - 1) segments.push({ kind: "description", text: " ›" });
584
+ segments.push({ kind: "description", text: ` ${counter}` });
585
+ return segments;
586
+ };
587
+ const widthOf = (segments) => customizeMeasure(helpers, segments.map((segment) => segment.text).join(""));
588
+ let first = cursor;
589
+ let last = cursor;
590
+ if (widthOf(windowAt(first, last)) <= budget) {
591
+ // Grow to the right first (what comes next), then to the left, so the
592
+ // window is stable and the cursor stays on screen in every frame.
593
+ for (;;) {
594
+ if (last + 1 < marks.length && widthOf(windowAt(first, last + 1)) <= budget) {
595
+ last += 1;
596
+ continue;
597
+ }
598
+ if (first - 1 >= 0 && widthOf(windowAt(first - 1, last)) <= budget) {
599
+ first -= 1;
600
+ continue;
601
+ }
602
+ break;
603
+ }
604
+ body.push(...windowAt(first, last));
605
+ } else {
606
+ // Upstream's compact fallback: one value between arrows plus the counter.
607
+ // The value keeps the ellipsis INSIDE the arrows (upstream truncates the
608
+ // whole line), so the card still names exactly the cursored option instead
609
+ // of showing a neighbouring value cut in half. A card too narrow for both
610
+ // keeps the value and drops the counter: naming the cursor wins.
611
+ let counterText = ` ${counter}`;
612
+ const arrows = 4;
613
+ let labelRoom = budget - arrows - customizeMeasure(helpers, counterText);
614
+ if (labelRoom < 2 && budget - arrows > labelRoom) {
615
+ counterText = "";
616
+ labelRoom = budget - arrows;
617
+ }
618
+ const shownLabel = labelRoom >= 1
619
+ ? customizeFit(helpers, options[cursor].label, labelRoom)
620
+ : options[cursor].label;
621
+ body.push({ kind: disabled ? "label" : "accent", text: `‹ ${shownLabel} ›`, option: cursor });
622
+ if (counterText) body.push({ kind: "description", text: counterText });
623
+ }
624
+ }
625
+ const spans = [];
626
+ let column = bodyStart;
627
+ for (const segment of body) {
628
+ const width = customizeMeasure(helpers, segment.text);
629
+ if (typeof segment.option === "number") spans.push({ index: segment.option, start: column, end: column + width });
630
+ column += width;
631
+ }
632
+ const plain = `${prefix}${lead}${body.map((segment) => segment.text).join("")}`;
633
+ const nameEnd = Math.min(size, 2 + customizeMeasure(helpers, name));
634
+ if (active && !disabled && theme && typeof theme.bg === "function") {
398
635
  try {
399
- const plain = customizeFit(helpers, `${lead}${body}`, Math.max(0, size));
400
- const band = theme.bg("selectedBg", plain + " ".repeat(Math.max(0, size - customizeMeasure(helpers, plain))));
401
- if (typeof band === "string") return band;
636
+ // The band is a full-width background, so it is only painted when nothing
637
+ // had to be cut: a band around a truncated line would hide the cut.
638
+ if (customizeFit(helpers, plain, Math.max(0, size)) === plain) {
639
+ const band = theme.bg("selectedBg", plain + " ".repeat(Math.max(0, size - customizeMeasure(helpers, plain))));
640
+ if (typeof band === "string") return { text: band, nameEnd, spans };
641
+ }
402
642
  } catch {
403
643
  // Fall through to the composed form below.
404
644
  }
405
645
  }
406
646
  const segments = [
407
- { kind: focused ? "key" : "label", text: prefix },
408
- { kind: focused ? "value" : "description", text: `${name}${namePad} ` },
409
- { kind: row.current === null ? "error" : "accent", text: stored },
647
+ { kind: disabled ? "label" : (focused ? "key" : "label"), text: prefix },
648
+ { kind: disabled ? "label" : (focused ? "value" : "description"), text: lead },
649
+ ...body,
410
650
  ];
411
- if (showPair) segments.push({ kind: "description", text: ` ${other}` });
412
- return customizeCompose(helpers, theme, segments, size);
651
+ return { text: customizeCompose(helpers, theme, segments, size), nameEnd, spans };
413
652
  }
414
653
 
415
- function createCustomizePanel({ helpers, hostTui, theme, rowsAvailable, model, done }) {
654
+ /* -------------------------------------------------------------- component */
655
+
656
+ function createCustomizePanel({ helpers, hostTui, theme, rowsAvailable, model: initialModel, apply, done }) {
416
657
  const state = {
417
658
  pane: "categories",
659
+ model: Array.isArray(initialModel) ? initialModel : [],
418
660
  cat: 0,
419
- row: model.map(() => 0),
661
+ settingId: initialModel && initialModel[0] && initialModel[0].settings[0] ? initialModel[0].settings[0].id : null,
662
+ cursors: new Map(),
420
663
  frame: null,
664
+ busy: false,
421
665
  };
666
+ function settings() {
667
+ const category = state.model[state.cat];
668
+ return category && Array.isArray(category.settings) ? category.settings : [];
669
+ }
670
+ function settingIndex() {
671
+ const at = settings().findIndex((entry) => entry.id === state.settingId);
672
+ return at < 0 ? 0 : at;
673
+ }
674
+ function focusedSetting() {
675
+ return settings()[settingIndex()] || null;
676
+ }
677
+ // A setting is entered on its stored option (upstream `landOn`); an unknown
678
+ // state has no stored option, so it enters on the first one.
679
+ function landOn(setting) {
680
+ const at = setting && Array.isArray(setting.options) ? setting.options.findIndex((option) => option.current === true) : -1;
681
+ return at < 0 ? 0 : at;
682
+ }
683
+ function cursorIndex(setting) {
684
+ if (!setting || !Array.isArray(setting.options)) return 0;
685
+ const stored = state.cursors.get(setting.id);
686
+ const at = setting.options.findIndex((option) => option.id === stored);
687
+ return at < 0 ? landOn(setting) : at;
688
+ }
689
+ function setCursor(setting, index) {
690
+ const option = setting && Array.isArray(setting.options) ? setting.options[index] : null;
691
+ if (option) state.cursors.set(setting.id, option.id);
692
+ }
693
+ // Every setting starts on its stored option, so a fresh frame never shows a
694
+ // cursor on a value nobody chose.
695
+ for (const category of state.model) {
696
+ for (const setting of category.settings || []) setCursor(setting, landOn(setting));
697
+ }
698
+ // The cursor survives a model swap by ID, which is why option ids are
699
+ // structural: after applying `off` the cursor stays on `off`, and only an
700
+ // option that no longer exists re-lands on the stored one.
701
+ function replaceModel(next) {
702
+ if (!Array.isArray(next) || next.length === 0) return;
703
+ const previousId = state.model[state.cat] ? state.model[state.cat].id : null;
704
+ const at = next.findIndex((category) => category.id === previousId);
705
+ state.model = next;
706
+ state.cat = at < 0 ? Math.min(state.cat, next.length - 1) : at;
707
+ const seen = new Set();
708
+ for (const category of next) {
709
+ for (const setting of category.settings || []) {
710
+ seen.add(setting.id);
711
+ const stored = state.cursors.get(setting.id);
712
+ const keep = stored !== undefined && Array.isArray(setting.options)
713
+ && setting.options.some((option) => option.id === stored);
714
+ if (!keep) {
715
+ const landed = setting.options ? setting.options[landOn(setting)] : null;
716
+ if (landed) state.cursors.set(setting.id, landed.id);
717
+ else state.cursors.delete(setting.id);
718
+ }
719
+ }
720
+ }
721
+ for (const id of [...state.cursors.keys()]) if (!seen.has(id)) state.cursors.delete(id);
722
+ if (!settings().some((setting) => setting.id === state.settingId)) {
723
+ state.settingId = settings()[0] ? settings()[0].id : null;
724
+ }
725
+ }
422
726
  function availableRows() {
423
727
  try {
424
728
  if (typeof rowsAvailable === "function") {
@@ -430,77 +734,68 @@ function createCustomizePanel({ helpers, hostTui, theme, rowsAvailable, model, d
430
734
  }
431
735
  return CUSTOMIZE_MAX_HEIGHT;
432
736
  }
433
- function focused() {
434
- const category = model[state.cat];
435
- return { category, row: category.rows[state.row[state.cat]] || null };
436
- }
437
- // What the card describes on its own row: the setting the values pane holds
438
- // the focus on, or the category while the left list owns it.
439
- function focusedDescription() {
440
- const category = model[state.cat];
441
- const row = state.pane === "values" ? focused().row : null;
442
- return row
443
- ? { title: row.setting, description: row.description }
444
- : { title: category.title, description: category.description };
445
- }
446
737
  function render(width) {
447
738
  const w = typeof width === "number" && Number.isFinite(width) ? Math.floor(width) : 0;
448
739
  state.frame = null;
449
740
  if (w <= 0) return [];
450
741
  const height = availableRows();
451
742
  if (!height) return [];
452
- const title = CUSTOMIZE_TITLE;
453
743
  // A card needs two border rows. At extreme dimensions keep a read-only
454
744
  // heading rather than activatable invisible controls.
455
745
  if (w < CUSTOMIZE_CARD_PADDING + 1 || height < 4) {
456
- return [title, "Enlarge terminal"].slice(0, Math.min(height, 2))
746
+ return [CUSTOMIZE_TITLE, "Enlarge terminal"].slice(0, Math.min(height, 2))
457
747
  .map((line) => customizeFit(helpers, line, w, ""));
458
748
  }
459
749
  const inner = w - CUSTOMIZE_CARD_PADDING;
460
750
  const narrow = w < CUSTOMIZE_NARROW_WIDTH;
461
- const navOnly = narrow && state.pane === "categories" && model.length > 1;
751
+ const navOnly = narrow && state.pane === "categories" && state.model.length > 1;
462
752
  // The left column fits every category title plus the focus prefix:
463
753
  // truncating a category name is never acceptable, the right pane may clip.
464
- const leftNeed = model.reduce(
754
+ const leftNeed = state.model.reduce(
465
755
  (need, entry) => Math.max(need, 2 + customizeMeasure(helpers, entry.title)),
466
756
  0,
467
757
  );
468
- const leftWidth = narrow ? 0 : Math.min(24, Math.max(leftNeed, Math.floor(inner * 0.28)));
758
+ const leftWidth = narrow ? 0 : Math.min(24, Math.max(leftNeed, Math.max(14, Math.floor(inner * 0.28))));
469
759
  const rightWidth = inner - leftWidth - (leftWidth ? 3 : 0);
470
- const category = model[state.cat];
471
- const rows = category.rows;
760
+ // Upstream's preview height rule: 6 / 3 / 1 / 0 lines by overlay height,
761
+ // deducted from the content height inside the same card.
762
+ const previewLines = height >= 18 ? 6 : height >= 11 ? 3 : height >= 8 ? 1 : 0;
472
763
  const showHeading = height >= 6;
473
- // The description rides directly above the legend, so it needs one more row
474
- // than the heading and the legend alone; a 6-row card keeps the keys and
475
- // drops the prose instead of the other way round.
476
- const showDescription = height >= 7;
477
- // Right pane: one line per setting (name column plus the pill pair) and,
478
- // when the stored state is unreadable, one muted note under it.
479
- const rightLines = rows.map((row, index) => ({ kind: "row", index, row }));
480
- for (const row of rows) if (row.note) rightLines.push({ kind: "note", text: row.note });
481
- // Title, then heading + description + legend when they fit, above two borders.
482
- const chrome = 1 + (showHeading ? 2 : 0) + (showDescription ? 1 : 0);
483
- const contentHeight = Math.max(1, height - 2 - chrome);
484
- const position = navOnly ? state.cat : state.row[state.cat];
485
- const listLength = navOnly ? model.length : rightLines.length;
764
+ const showTopGap = height >= 12;
765
+ const showBottomGap = height >= 9;
766
+ const chrome = 1 + (showHeading ? 2 : 0) + (showTopGap ? 1 : 0) + (showBottomGap ? 1 : 0);
767
+ const contentHeight = Math.max(1, height - 2 - chrome - previewLines);
768
+ const category = state.model[state.cat] || { id: null, title: "Settings", settings: [] };
769
+ const entries = category.settings || [];
770
+ const focusedAt = settingIndex();
771
+ // Right pane rows: one line per setting plus, when the state cannot name a
772
+ // value, one muted note under it.
773
+ const rightLines = [];
774
+ entries.forEach((setting, index) => {
775
+ rightLines.push({ kind: "setting", index, setting });
776
+ if (setting.note) rightLines.push({ kind: "note", text: setting.note });
777
+ });
778
+ const focusedLine = rightLines.findIndex((line) => line.kind === "setting" && line.index === focusedAt);
779
+ const position = navOnly ? state.cat : Math.max(0, focusedLine);
780
+ const listLength = navOnly ? state.model.length : rightLines.length;
486
781
  const start = Math.min(Math.max(0, position - contentHeight + 1), Math.max(0, listLength - contentHeight));
487
- const navStart = Math.min(Math.max(0, state.cat - contentHeight + 1), Math.max(0, model.length - contentHeight));
488
- const nameWidth = rows.reduce(
489
- (need, row) => Math.max(need, customizeMeasure(helpers, row.setting)),
490
- 0,
782
+ const navStart = Math.min(Math.max(0, state.cat - contentHeight + 1), Math.max(0, state.model.length - contentHeight));
783
+ const nameWidth = Math.min(
784
+ 20,
785
+ entries.reduce((need, setting) => Math.max(need, customizeMeasure(helpers, setting.setting)), 0),
491
786
  );
492
- const paint = (text, size, kind) => customizePaint(helpers, theme, kind, text, size);
787
+ const paintCell = (text, size, kind) => customizePaint(helpers, theme, kind, text, size);
493
788
  const compose = (segments, size) => customizeCompose(helpers, theme, segments, size);
494
789
  const divider = palette.paint(theme, "border", "│");
495
- const join = (left, right) => leftWidth
790
+ const join = (left, right) => (leftWidth
496
791
  ? `${left}${" ".repeat(Math.max(0, leftWidth - customizeMeasure(helpers, left)))} ${divider} ${right}`
497
- : right;
792
+ : right);
498
793
  const lines = [];
499
794
  const hits = [];
500
- // Title row doubles as the esc hint: same row, right-aligned.
501
- const escGap = Math.max(1, inner - customizeMeasure(helpers, title) - 3);
795
+ const titleRow = CUSTOMIZE_TITLE;
796
+ const escGap = Math.max(1, inner - customizeMeasure(helpers, titleRow) - 3);
502
797
  lines.push(compose([
503
- { kind: "title", text: title },
798
+ { kind: "title", text: titleRow },
504
799
  { text: " ".repeat(escGap) },
505
800
  { kind: "key", text: "esc" },
506
801
  ], inner));
@@ -510,59 +805,88 @@ function createCustomizePanel({ helpers, hostTui, theme, rowsAvailable, model, d
510
805
  : [
511
806
  { kind: "title", text: category.title },
512
807
  { kind: "label", text: " · " },
513
- { kind: "count", text: rows.length ? `${state.row[state.cat] + 1}/${rows.length}` : "empty" },
808
+ { kind: "count", text: entries.length ? `${focusedAt + 1}/${entries.length}` : "empty" },
514
809
  ];
515
810
  lines.push(join(
516
- leftWidth ? paint("CATEGORIES", leftWidth, "key") : "",
811
+ leftWidth ? paintCell("CATEGORIES", leftWidth, "key") : "",
517
812
  compose(heading, rightWidth),
518
813
  ));
519
814
  }
815
+ if (showTopGap) lines.push("");
520
816
  for (let i = 0; i < contentHeight; i += 1) {
521
817
  const navIndex = navStart + i;
522
- const nav = model[navIndex];
818
+ const nav = state.model[navIndex];
523
819
  const at = start + i;
524
- const item = navOnly ? (model[at] || null) : (rightLines[at] || null);
820
+ const item = navOnly ? (state.model[at] || null) : (rightLines[at] || null);
525
821
  // The card paints the top border above content line 0, so a content row's
526
822
  // rendered row is its index + 1.
527
823
  const y = lines.length + 1;
824
+ const rightStart = 2 + (leftWidth ? leftWidth + 3 : 0);
528
825
  const left = nav
529
826
  ? customizeSelect(helpers, theme, nav.title, leftWidth, navOnly ? at === state.cat : navIndex === state.cat && state.pane === "categories")
530
827
  : "";
531
828
  let right = "";
532
829
  if (navOnly) {
533
830
  right = item ? customizeSelect(helpers, theme, item.title, rightWidth, at === state.cat) : "";
534
- } else if (item && item.kind === "row") {
535
- right = customizeSettingLine(
831
+ if (item) hits.push({ kind: "category", index: at, y, x: rightStart + 2, end: rightStart + rightWidth });
832
+ } else if (item && item.kind === "setting") {
833
+ const rendered = customizeSettingLine(
536
834
  helpers,
537
835
  theme,
538
- item.row,
836
+ item.setting,
837
+ cursorIndex(item.setting),
539
838
  nameWidth,
540
839
  rightWidth,
541
- at === state.row[state.cat],
542
- at === state.row[state.cat] && state.pane === "values",
840
+ at === position,
841
+ at === position && state.pane === "controls",
543
842
  );
843
+ right = rendered.text;
844
+ // A click on the name only moves the focus; a click on an option applies
845
+ // exactly that option.
846
+ if (rendered.nameEnd > 2) {
847
+ hits.push({ kind: "setting", index: item.index, y, x: rightStart + 2, end: rightStart + rendered.nameEnd });
848
+ }
849
+ for (const span of rendered.spans) {
850
+ hits.push({ kind: "option", index: item.index, option: span.index, y, x: rightStart + span.start, end: rightStart + span.end });
851
+ }
544
852
  } else if (item && item.kind === "note") {
545
- right = paint(item.text, rightWidth, "description");
853
+ right = paintCell(item.text, rightWidth, "description");
546
854
  } else if (rightLines.length === 0) {
547
- right = paint("No settings available", rightWidth, "description");
855
+ right = paintCell("No settings available", rightWidth, "description");
548
856
  }
549
857
  lines.push(join(left, right));
550
858
  // Pointer hits cover the pane text only: a click on a border, the title,
551
859
  // the heading or the footer hits nothing and is ignored.
552
- const rightStart = 2 + (leftWidth ? leftWidth + 3 : 0);
553
860
  if (leftWidth && nav) hits.push({ kind: "category", index: navIndex, y, x: 2, end: 2 + leftWidth });
554
- if (navOnly && item) hits.push({ kind: "category", index: at, y, x: rightStart + 2, end: rightStart + rightWidth });
555
- else if (item && item.kind === "row") hits.push({ kind: "row", index: item.index, y, x: rightStart + 2, end: rightStart + rightWidth });
556
861
  }
557
- if (showDescription) {
558
- const described = focusedDescription();
559
- lines.push(compose([
560
- { kind: "value", text: `${described.title} — ` },
561
- { kind: "description", text: described.description },
562
- ], inner));
862
+ // The Preview block: a spacer, the accent headline naming the highlighted
863
+ // option and its preview title, then the muted sample lines — the upstream
864
+ // placement, height and roles. No separate `<Category> — <description>` row
865
+ // exists any more: the preview title IS the description.
866
+ if (previewLines >= 3) {
867
+ const setting = entries[focusedAt] || null;
868
+ const option = !navOnly && setting && Array.isArray(setting.options) ? setting.options[cursorIndex(setting)] : null;
869
+ const preview = option ? option.preview : null;
870
+ lines.push("");
871
+ const headline = navOnly
872
+ ? "→ controls · Esc close"
873
+ : preview && option
874
+ ? `Preview · ${option.label} · ${preview.title}`
875
+ : "Preview unavailable";
876
+ lines.push(paintCell(headline, inner, "accent"));
877
+ const sample = navOnly
878
+ ? [""]
879
+ : preview
880
+ ? preview.sample.split("\n")
881
+ : ["No read-only sample for this choice"];
882
+ for (let i = 0; i < previewLines - 2; i += 1) lines.push(paintCell(sample[i] ?? "", inner, "description"));
883
+ } else if (previewLines === 1) {
884
+ lines.push(paintCell(navOnly ? "→ controls · Esc close" : "Preview omitted · enlarge terminal", inner, "description"));
563
885
  }
886
+ if (showBottomGap) lines.push("");
564
887
  if (showHeading) {
565
- lines.push(customizePad(helpers, customizeFooter(helpers, theme, CUSTOMIZE_FOOTER_KEYS, inner), inner));
888
+ const footerEntries = customizeFooterVariant(navOnly, state.pane, entries[focusedAt] || null);
889
+ lines.push(customizePad(helpers, customizeFooter(helpers, theme, footerEntries, inner), inner));
566
890
  }
567
891
  const shown = lines.slice(0, Math.max(0, height - 2));
568
892
  state.frame = { width: w, height: shown.length + 2, hits: hits.filter((hit) => hit.y <= shown.length) };
@@ -575,68 +899,109 @@ function createCustomizePanel({ helpers, hostTui, theme, rowsAvailable, model, d
575
899
  // A repaint failure never breaks navigation.
576
900
  }
577
901
  }
902
+ // The one action that can write: it runs behind a busy guard (a second Enter
903
+ // while the first apply is in flight does nothing), swaps in the model apply
904
+ // read back, and closes only when the extension asked for it — the Moshi
905
+ // reload must never run behind a mounted card.
906
+ function runApply(setting, option) {
907
+ if (state.busy || !setting || !option) return;
908
+ state.busy = true;
909
+ let pending;
910
+ try {
911
+ pending = typeof apply === "function"
912
+ ? apply({ categoryId: state.model[state.cat] ? state.model[state.cat].id : null, settingId: setting.id, optionId: option.id })
913
+ : Promise.resolve(null);
914
+ } catch {
915
+ state.busy = false;
916
+ requestPaint();
917
+ return;
918
+ }
919
+ Promise.resolve(pending).then((result) => {
920
+ state.busy = false;
921
+ if (result && result.model) replaceModel(result.model);
922
+ if (result && result.close === true) {
923
+ done(null);
924
+ return;
925
+ }
926
+ requestPaint();
927
+ }, () => {
928
+ state.busy = false;
929
+ requestPaint();
930
+ });
931
+ }
932
+ function enterControls() {
933
+ state.pane = "controls";
934
+ const setting = focusedSetting();
935
+ if (setting) setCursor(setting, landOn(setting));
936
+ }
578
937
  function handleInput(data) {
579
938
  if (customizeIsKeyRelease(helpers, data)) return;
580
939
  if (customizeKeyMatches(helpers, data, ["escape", "ctrl+c"])) {
581
940
  done(null);
582
941
  return;
583
942
  }
584
- if (customizeKeyMatches(helpers, data, ["left", "right", "tab"])) {
585
- state.pane = state.pane === "categories" ? "values" : "categories";
586
- requestPaint();
587
- return;
588
- }
589
- if (customizeKeyMatches(helpers, data, ["up", "k"])) {
590
- if (state.pane === "categories") state.cat = (state.cat + model.length - 1) % model.length;
943
+ if (state.busy) return;
944
+ const length = state.pane === "categories" ? state.model.length : settings().length;
945
+ if (!length) return;
946
+ const setting = focusedSetting();
947
+ const step = state.pane === "controls" && setting && Array.isArray(setting.options) && setting.options.length
948
+ ? (customizeKeyMatches(helpers, data, ["left"]) ? -1 : customizeKeyMatches(helpers, data, ["right"]) ? 1 : 0)
949
+ : 0;
950
+ if (step === -1 && cursorIndex(setting) === 0) {
951
+ // Left past the first option leaves the controls, exactly like upstream.
952
+ state.pane = "categories";
953
+ } else if (step) {
954
+ const next = cursorIndex(setting) + step;
955
+ // Every setting defers to Enter (`applyOnMove: false`): a step that would
956
+ // leave the option range changes nothing and writes nothing.
957
+ if (next >= 0 && next < setting.options.length) setCursor(setting, next);
958
+ } else if (customizeKeyMatches(helpers, data, ["left"]) || (customizeKeyMatches(helpers, data, ["tab"]) && state.pane === "controls")) {
959
+ state.pane = "categories";
960
+ } else if (customizeKeyMatches(helpers, data, ["right"]) || (customizeKeyMatches(helpers, data, ["tab"]) && state.pane === "categories")) {
961
+ enterControls();
962
+ } else if (customizeKeyMatches(helpers, data, ["up", "k"])) {
963
+ if (state.pane === "categories") state.cat = (state.cat + state.model.length - 1) % state.model.length;
591
964
  else {
592
- const count = model[state.cat].rows.length;
593
- state.row[state.cat] = (state.row[state.cat] + count - 1) % count;
965
+ const list = settings();
966
+ const at = (settingIndex() + list.length - 1) % list.length;
967
+ state.settingId = list[at].id;
968
+ setCursor(list[at], landOn(list[at]));
594
969
  }
595
- requestPaint();
596
- return;
597
- }
598
- if (customizeKeyMatches(helpers, data, ["down", "j"])) {
599
- if (state.pane === "categories") state.cat = (state.cat + 1) % model.length;
970
+ } else if (customizeKeyMatches(helpers, data, ["down", "j"])) {
971
+ if (state.pane === "categories") state.cat = (state.cat + 1) % state.model.length;
600
972
  else {
601
- const count = model[state.cat].rows.length;
602
- state.row[state.cat] = (state.row[state.cat] + 1) % count;
973
+ const list = settings();
974
+ const at = (settingIndex() + 1) % list.length;
975
+ state.settingId = list[at].id;
976
+ setCursor(list[at], landOn(list[at]));
603
977
  }
604
- requestPaint();
605
- return;
606
- }
607
- if (customizeKeyMatches(helpers, data, ["enter", "return"])) {
608
- const current = focused();
609
- done({
610
- categoryId: current.category.id,
611
- switchId: current.row ? current.row.switchId : current.category.id,
612
- valueId: current.row ? current.row.id : null,
613
- });
978
+ } else if (customizeKeyMatches(helpers, data, ["enter", "return", "space"]) && state.pane === "categories") {
979
+ enterControls();
980
+ } else if (customizeKeyMatches(helpers, data, ["enter", "return", "space"])) {
981
+ runApply(setting, setting && Array.isArray(setting.options) ? setting.options[cursorIndex(setting)] : null);
614
982
  }
983
+ requestPaint();
615
984
  }
616
- // Pointer contract: x/y are local to this component's rendered frame, the
617
- // card border included. A press only captures the gesture; the click that
618
- // follows activates the hit, so a drag never applies a row by accident, and
619
- // a move only carries the focus. Anything outside a pane's text is ignored,
620
- // which is also the answer for a click on a border, the title, the heading
621
- // or the footer.
622
- //
623
- // The reported `width`/`height` are the box the host rendered, which the
624
- // overlay may have clipped shorter than the rows this panel budgeted. The hit
625
- // test therefore reads the frame it rendered and only clamps the row into it:
626
- // a geometry comparison the user cannot see must never swallow a real click.
985
+ // Pointer contract: x/y are local to this component's rendered frame, the card
986
+ // border included. A press only captures the gesture; the click that follows
987
+ // activates the hit, so a drag never applies an option by accident, and a move
988
+ // only carries the focus. Anything outside a pane's text is ignored.
627
989
  function focusHit(hit) {
628
990
  if (hit.kind === "category") {
629
991
  if (state.pane === "categories" && state.cat === hit.index) return false;
630
992
  state.cat = hit.index;
631
993
  state.pane = "categories";
994
+ state.settingId = settings()[0] ? settings()[0].id : null;
632
995
  return true;
633
996
  }
634
- const target = model[state.cat];
635
- if (!target || !target.rows[hit.index]) return false;
636
- if (state.pane === "values" && state.row[state.cat] === hit.index) return false;
637
- state.pane = "values";
638
- state.row[state.cat] = hit.index;
639
- return true;
997
+ const list = settings();
998
+ const setting = list[hit.index];
999
+ if (!setting) return false;
1000
+ const changed = state.pane !== "controls" || state.settingId !== setting.id || hit.kind === "option";
1001
+ state.pane = "controls";
1002
+ state.settingId = setting.id;
1003
+ if (hit.kind === "option") setCursor(setting, hit.option);
1004
+ return changed;
640
1005
  }
641
1006
  function handleMouse(event) {
642
1007
  if (!event) return undefined;
@@ -650,17 +1015,21 @@ function createCustomizePanel({ helpers, hostTui, theme, rowsAvailable, model, d
650
1015
  if (!hit) return undefined;
651
1016
  if (moving) return { handled: true, render: focusHit(hit) };
652
1017
  if (event.type === "press") return { handled: true, capture: true, render: false };
653
- const target = model[state.cat];
1018
+ if (state.busy) return { handled: true, render: false };
654
1019
  if (hit.kind === "category") {
655
1020
  state.cat = hit.index;
656
1021
  state.pane = "categories";
1022
+ state.settingId = settings()[0] ? settings()[0].id : null;
1023
+ // A narrow card has no category column: selecting one opens its settings.
1024
+ if (frame.width < CUSTOMIZE_NARROW_WIDTH) enterControls();
657
1025
  return { handled: true, render: true, focus: true };
658
1026
  }
659
- const row = target ? target.rows[hit.index] : null;
660
- if (!row) return undefined;
661
- state.pane = "values";
662
- state.row[state.cat] = hit.index;
663
- done({ categoryId: target.id, switchId: row.switchId, valueId: row.id });
1027
+ const setting = settings()[hit.index];
1028
+ if (!setting) return undefined;
1029
+ focusHit(hit);
1030
+ if (hit.kind === "option") {
1031
+ runApply(setting, setting.options ? setting.options[hit.option] : null);
1032
+ }
664
1033
  return { handled: true, render: true, focus: true };
665
1034
  }
666
1035
  function invalidate() {}