aboutsummaryrefslogtreecommitdiff
path: root/build/js/ui/palette.js
blob: ae2c9e947fc04aa8a6d96d1f6ce807f72af8d3f8 (plain)
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
// Command palette (Ctrl+K): fuzzy search over every menu command and tool.
import { el, prettyShortcut } from '../core/util.js';
import { openDialog } from './dialogs.js';
import { icon } from './icons.js';

/** Map action id -> menu path ("Image ▸ Adjustments") from the menu definition. */
export function menuPaths(menus) {
  const paths = new Map();
  const walk = (items, path) => {
    for (const it of items) {
      if (it === '-' || !it) continue;
      if (it.submenu) walk(typeof it.submenu === 'function' ? it.submenu() : it.submenu, [...path, it.label]);
      else if (it.action && !paths.has(it.action)) paths.set(it.action, path.join(' ▸ '));
    }
  };
  for (const m of menus) walk(m.items, [m.label]);
  return paths;
}

/**
 * Score how well `query` matches `text` as a subsequence (higher is better), or -1.
 * Rewards matches at word starts and runs of consecutive characters.
 */
export function fuzzyScore(query, text) {
  const q = query.toLowerCase(), t = text.toLowerCase();
  if (!q) return 0;
  const direct = t.indexOf(q);
  if (direct >= 0) return 1000 - direct * 2 - (t.length - q.length) * 0.1 + (direct === 0 || /\W/.test(t[direct - 1]) ? 200 : 0);
  let score = 0, ti = 0, run = 0;
  for (const ch of q) {
    if (ch === ' ') continue;
    const found = t.indexOf(ch, ti);
    if (found < 0) return -1;
    const wordStart = found === 0 || /[\s/▸&(-]/.test(t[found - 1]);
    run = found === ti ? run + 1 : 0;
    score += 10 + (wordStart ? 25 : 0) + run * 8 - Math.min(20, found - ti);
    ti = found + 1;
  }
  return score;
}

/** True if every word of the query starts some word of text. */
export function wordPrefixMatch(query, text) {
  const words = text.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);
  const tokens = query.toLowerCase().split(/\s+/).filter(Boolean);
  return tokens.length > 0 && tokens.every((t) => words.some((w) => w.startsWith(t)));
}

export function commandPalette(app) {
  const paths = menuPaths(app.ui.menu.definition);
  const entries = [];
  for (const a of app.actions.values()) {
    if (a.id === 'help.commands') continue;
    const label = a.label.replace(/…$/, '');
    const path = paths.get(a.id) || (a.id.startsWith('color.') ? 'Color' : '');
    entries.push({ id: a.id, label, path, shortcut: a.shortcut, enabled: () => !a.enabled || a.enabled(app), run: () => app.run(a.id), dialog: a.label.endsWith('…') });
  }
  for (const [id, T] of app.toolClasses) {
    entries.push({ id: `tool:${id}`, label: `${T.label} Tool`, path: 'Tools', shortcut: T.shortcut, icon: T.icon, enabled: () => true, run: () => app.setTool(id) });
  }
  const recent = app.prefs.get('recentCommands', []);

  const input = el('input', { type: 'text', class: 'palette-input', placeholder: 'Type a command, tool or menu item…', spellcheck: false, autocomplete: 'off' });
  const list = el('div', { class: 'palette-list', role: 'listbox' });
  let shown = [];
  let index = 0;
  let close = null;

  const render = () => {
    const q = input.value.trim();
    if (!q) {
      const rec = recent.map((id) => entries.find((e) => e.id === id)).filter(Boolean);
      const rest = entries.filter((e) => !recent.includes(e.id)).sort((a, b) => a.label.localeCompare(b.label));
      shown = [...rec, ...rest];
    } else {
      // Disabled commands still show (so you learn they exist) but sort last.
      // Fuzzy on the label; the menu path only counts as whole-word prefixes ("adj lev").
      shown = entries
        .map((e) => ({ e, s: Math.max(fuzzyScore(q, e.label), wordPrefixMatch(q, `${e.path} ${e.label}`) ? 1 : -1) }))
        .filter((r) => r.s >= 0)
        .map((r) => ({ e: r.e, s: r.s - (r.e.enabled() ? 0 : 10000) }))
        .sort((a, b) => b.s - a.s)
        .map((r) => r.e);
    }
    index = Math.max(0, shown.findIndex((e) => e.enabled()));
    list.innerHTML = '';
    if (!shown.length) list.appendChild(el('div', { class: 'palette-empty' }, 'No matching commands'));
    shown.slice(0, 200).forEach((e, i) => {
      const on = e.enabled();
      const row = el('div', { class: `palette-row${on ? '' : ' disabled'}${!q && recent.includes(e.id) ? ' recent' : ''}`, role: 'option', 'data-i': i },
        el('span', { class: 'palette-icon', html: e.icon ? icon(e.icon, 15) : '' }),
        el('span', { class: 'palette-label' }, e.label, e.dialog ? '…' : ''),
        el('span', { class: 'palette-path' }, e.path),
        el('span', { class: 'palette-key' }, e.shortcut ? el('kbd', {}, prettyShortcut(e.shortcut)) : ''));
      row.addEventListener('pointermove', () => { if (on && index !== i) { index = i; highlight(); } });
      row.addEventListener('click', () => { if (on) choose(i); });
      list.appendChild(row);
    });
    highlight();
  };

  const highlight = () => {
    list.querySelectorAll('.palette-row').forEach((r) => r.classList.toggle('active', Number(r.dataset.i) === index));
    const cur = list.querySelector('.palette-row.active');
    if (cur) {
      if (cur.offsetTop < list.scrollTop) list.scrollTop = cur.offsetTop;
      else if (cur.offsetTop + cur.offsetHeight > list.scrollTop + list.clientHeight) list.scrollTop = cur.offsetTop + cur.offsetHeight - list.clientHeight;
    }
  };

  const step = (dir) => {
    if (!shown.length) return;
    for (let k = 1; k <= shown.length; k++) {
      const i = (index + dir * k + shown.length) % shown.length;
      if (shown[i].enabled()) { index = i; break; }
    }
    highlight();
  };

  const choose = (i) => {
    const e = shown[i];
    if (!e || !e.enabled()) return;
    app.prefs.set('recentCommands', [e.id, ...recent.filter((id) => id !== e.id)].slice(0, 8));
    close?.(e);
  };

  input.addEventListener('input', render);
  render();
  const done = openDialog({
    title: 'Commands',
    body: el('div', { class: 'palette' }, input, list),
    buttons: [],
    width: 560,
    className: 'palette-dialog',
    onOpen: (c) => { close = c; },
    onKey: (e) => {
      if (e.key === 'ArrowDown') { e.preventDefault(); step(1); return true; }
      if (e.key === 'ArrowUp') { e.preventDefault(); step(-1); return true; }
      if (e.key === 'PageDown') { e.preventDefault(); for (let k = 0; k < 8; k++) step(1); return true; }
      if (e.key === 'PageUp') { e.preventDefault(); for (let k = 0; k < 8; k++) step(-1); return true; }
      if (e.key === 'Enter') { e.preventDefault(); e.stopPropagation(); choose(index); return true; }
      return false;
    },
  });
  done.then((e) => {
    // Run after the palette is gone so commands that open dialogs work normally.
    if (e && e.run) setTimeout(() => e.run(), 0);
  });
  return done;
}