aboutsummaryrefslogtreecommitdiff
path: root/build/js/ui/menu.js
blob: cd6499d58686ba86d519aa2f9890ae726ddc2e49 (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
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
// Menu bar with dropdowns, submenus, and context menus. Items reference app actions.
// Keyboard: F10 opens the menu bar; arrows move, Enter activates, Esc closes,
// and a letter jumps to the next item starting with it.
import { el, prettyShortcut } from '../core/util.js';

export class MenuBar {
  constructor(app, container, definition) {
    this.app = app;
    this.definition = definition;
    this.bar = el('nav', { class: 'menubar', role: 'menubar' });
    container.appendChild(this.bar);
    this.openMenu = null;
    this.titles = [];
    for (const menu of definition) {
      const btn = el('button', { type: 'button', class: 'menu-title', role: 'menuitem', 'aria-haspopup': 'true', tabindex: '-1' }, menu.label);
      btn.addEventListener('pointerdown', (e) => {
        e.preventDefault();
        if (this.openMenu?.btn === btn) this.close();
        else this.open(menu, btn);
      });
      btn.addEventListener('pointerenter', () => {
        if (this.openMenu && this.openMenu.btn !== btn) this.open(menu, btn);
      });
      this.titles.push({ menu, btn });
      this.bar.appendChild(btn);
    }
    document.addEventListener('pointerdown', (e) => {
      if (!e.target.closest('.menu-popup, .menu-title')) this.close();
    });
    document.addEventListener('keydown', (e) => this.onKey(e), true);
    window.addEventListener('blur', () => this.close());
  }

  get isOpen() { return !!(this.openMenu || this.context); }

  open(menu, btn, { focusFirst = false } = {}) {
    this.close();
    const r = btn.getBoundingClientRect();
    const popup = this.buildPopup(typeof menu.items === 'function' ? menu.items() : menu.items);
    popup.style.left = `${r.left}px`;
    popup.style.top = `${r.bottom}px`;
    document.body.appendChild(popup);
    this.fitOnScreen(popup);
    btn.classList.add('open');
    btn.setAttribute('aria-expanded', 'true');
    this.openMenu = { btn, popup, menu };
    if (focusFirst) this.moveFocus(popup, 1);
  }

  /** Open the first menu from the keyboard. */
  openFromKeyboard(index = 0) {
    const t = this.titles[index];
    if (t) this.open(t.menu, t.btn, { focusFirst: true });
  }

  close() {
    if (!this.openMenu && !this.context) return;
    this.openMenu?.btn.classList.remove('open');
    this.openMenu?.btn.removeAttribute('aria-expanded');
    document.querySelectorAll('.menu-popup').forEach((p) => p.remove());
    this.openMenu = null;
    this.context = null;
  }

  showContext(x, y, items) {
    this.close();
    const popup = this.buildPopup(items);
    popup.style.left = `${x}px`;
    popup.style.top = `${y}px`;
    document.body.appendChild(popup);
    this.fitOnScreen(popup);
    this.context = popup;
  }

  fitOnScreen(popup) {
    const r = popup.getBoundingClientRect();
    if (r.right > window.innerWidth) popup.style.left = `${Math.max(0, window.innerWidth - r.width - 4)}px`;
    if (r.bottom > window.innerHeight) popup.style.top = `${Math.max(0, window.innerHeight - r.height - 4)}px`;
  }

  buildPopup(items) {
    const popup = el('div', { class: 'menu-popup', role: 'menu' });
    popup.rows = [];
    for (const item of items) {
      if (item === '-') { popup.appendChild(el('div', { class: 'menu-sep', role: 'separator' })); continue; }
      if (item.heading) { popup.appendChild(el('div', { class: 'menu-heading' }, item.heading)); continue; }
      const action = item.action ? this.app.actions.get(item.action) : null;
      const label = item.label || action?.label || item.action;
      const shortcut = item.shortcut ?? action?.shortcut;
      const enabled = item.enabled ? item.enabled() : action?.enabled ? action.enabled(this.app) : true;
      const checked = item.checked ? item.checked() : action?.checked ? action.checked(this.app) : null;
      const row = el('div', {
        class: `menu-item${enabled ? '' : ' disabled'}${item.submenu ? ' has-sub' : ''}`, role: 'menuitem',
        'aria-disabled': enabled ? null : 'true', 'aria-haspopup': item.submenu ? 'true' : null,
      },
      el('span', { class: 'menu-check' }, checked ? '✓' : ''),
      el('span', { class: 'menu-label' }, label),
      el('span', { class: 'menu-shortcut' }, item.submenu ? '▸' : prettyShortcut(shortcut || '')));
      row.enabled = enabled;
      row.label = label;
      if (item.submenu) {
        row.openSub = () => this.openSub(popup, row, item);
        row.addEventListener('pointerenter', () => { this.setFocus(popup, row); row.openSub(); });
      } else {
        row.activate = () => {
          if (!enabled) return;
          this.close();
          if (item.run) item.run();
          else this.app.run(item.action, ...(item.args || []));
        };
        row.addEventListener('pointerenter', () => {
          this.setFocus(popup, row);
          this.closeSubsBelow(popup);
        });
        row.addEventListener('click', () => row.activate());
      }
      popup.rows.push(row);
      popup.appendChild(row);
    }
    return popup;
  }

  /** Remove submenus opened from rows of `popup` (or deeper). */
  closeSubsBelow(popup) {
    let sub = popup.child;
    while (sub) { const next = sub.child; sub.remove(); sub = next; }
    popup.child = null;
    popup.querySelectorAll(':scope > .menu-item.sub-open').forEach((n) => n.classList.remove('sub-open'));
  }

  openSub(popup, row, item) {
    if (popup.child?.parentRow === row) return popup.child;
    this.closeSubsBelow(popup);
    const sub = this.buildPopup(typeof item.submenu === 'function' ? item.submenu() : item.submenu);
    sub.classList.add('sub');
    sub.parentRow = row;
    sub.parentPopup = popup;
    const rr = row.getBoundingClientRect();
    sub.style.left = `${rr.right - 2}px`;
    sub.style.top = `${rr.top - 4}px`;
    document.body.appendChild(sub);
    const sr = sub.getBoundingClientRect();
    if (sr.right > window.innerWidth) sub.style.left = `${rr.left - sr.width + 2}px`;
    if (sr.bottom > window.innerHeight) sub.style.top = `${Math.max(0, window.innerHeight - sr.height - 4)}px`;
    row.classList.add('sub-open');
    popup.child = sub;
    return sub;
  }

  // ------------------------------------------------------------ keyboard
  setFocus(popup, row) {
    popup.rows.forEach((r) => r.classList.toggle('focused', r === row));
    popup.focused = row;
  }

  moveFocus(popup, dir) {
    const rows = popup.rows.filter((r) => r.enabled);
    if (!rows.length) return;
    const i = rows.indexOf(popup.focused);
    const next = i < 0 ? (dir > 0 ? rows[0] : rows[rows.length - 1]) : rows[(i + dir + rows.length) % rows.length];
    this.setFocus(popup, next);
    next.scrollIntoView({ block: 'nearest' });
  }

  /** The innermost open popup. */
  deepest() {
    let p = this.openMenu?.popup || this.context;
    while (p?.child) p = p.child;
    return p;
  }

  onKey(e) {
    if (!this.isOpen) {
      if (e.key === 'F10' && !e.ctrlKey && !e.altKey && !e.metaKey && !document.querySelector('.dialog-backdrop')) {
        e.preventDefault();
        e.stopPropagation();
        this.openFromKeyboard(0);
      }
      return;
    }
    if (e.ctrlKey || e.metaKey) { this.close(); return; } // let shortcuts through
    const popup = this.deepest();
    const handled = () => { e.preventDefault(); e.stopPropagation(); };
    const stepMenu = (dir) => {
      if (!this.openMenu) return;
      const i = this.titles.findIndex((t) => t.btn === this.openMenu.btn);
      const t = this.titles[(i + dir + this.titles.length) % this.titles.length];
      this.open(t.menu, t.btn, { focusFirst: true });
    };
    switch (e.key) {
      case 'ArrowDown': handled(); this.moveFocus(popup, 1); return;
      case 'ArrowUp': handled(); this.moveFocus(popup, -1); return;
      case 'Home': handled(); popup.focused = null; this.moveFocus(popup, 1); return;
      case 'End': handled(); popup.focused = null; this.moveFocus(popup, -1); return;
      case 'ArrowRight': {
        handled();
        const row = popup.focused;
        if (row?.openSub && row.enabled) this.moveFocus(row.openSub(), 1);
        else stepMenu(1);
        return;
      }
      case 'ArrowLeft':
        handled();
        if (popup.parentPopup) this.closeSubsBelow(popup.parentPopup);
        else stepMenu(-1);
        return;
      case 'Enter':
      case ' ': {
        handled();
        const row = popup.focused;
        if (!row?.enabled) return;
        if (row.openSub) this.moveFocus(row.openSub(), 1);
        else row.activate();
        return;
      }
      case 'Escape':
        handled();
        if (popup.parentPopup) this.closeSubsBelow(popup.parentPopup);
        else this.close();
        return;
      case 'Tab':
        handled();
        stepMenu(e.shiftKey ? -1 : 1);
        return;
      default:
        if (e.key.length === 1 && !e.altKey) {
          handled();
          const ch = e.key.toLowerCase();
          const rows = popup.rows.filter((r) => r.enabled);
          const start = rows.indexOf(popup.focused);
          for (let k = 1; k <= rows.length; k++) {
            const r = rows[(start + k) % rows.length];
            if (r.label.toLowerCase().startsWith(ch)) { this.setFocus(popup, r); r.scrollIntoView({ block: 'nearest' }); break; }
          }
        }
    }
  }
}