Back to Faultline
SOURCE / PINNED RELEASE

Made of little things.

Faultline

Release
da1ffaa5624c…
Author-recorded commit
60f5f03189db…
License
LICENSE
Author’s source reference
nostr://npub182jczunncwe0jn6frpqwq3e0qjws7yqqnc3auccqv9nte2dnd63scjm4rf/wss%3A%2F%2Fgit.napplet.soy%2F/n-6932b12c78c

Archive hash verified: 5a2e0492417ec4e7…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

src/controller-menu.ts
// Use the same buttons and change handlers for every input device.
const choices = (root: HTMLElement) =>
  [...root.querySelectorAll<HTMLElement>('button:enabled, select:enabled, input:enabled')].filter(
    (node) => node.getClientRects().length && getComputedStyle(node).visibility !== 'hidden',
  );

function focus(node?: HTMLElement) {
  if (!node) return;
  node.focus({ preventScroll: true });
  node.scrollIntoView({ block: 'nearest', inline: 'nearest' });
}

export class ControllerMenu {
  private key = '';
  private remembered = '';
  private editor?: HTMLDialogElement;

  constructor(private dialog: HTMLDialogElement) {}

  private root() {
    return this.editor ?? (this.dialog.open ? this.dialog : document.getElementById('shell')!);
  }

  reset(screen: string) {
    if (screen === this.key) return;
    this.closeEditor();
    this.key = screen;
    this.remembered = '';
  }

  private id(node: HTMLElement) {
    return (
      node.dataset.room ??
      (node.id || node.getAttribute('aria-label') || node.textContent?.trim() || '')
    );
  }

  select(direction = 0, horizontal = false) {
    const root = this.root();
    const active = document.activeElement;
    if (
      !direction &&
      active instanceof HTMLElement &&
      root.contains(active) &&
      active.matches('button:enabled, select:enabled, input:enabled') &&
      active.getClientRects().length
    ) {
      this.remembered = this.id(active);
      return;
    }
    const nodes = choices(root);
    if (!nodes.length) return;
    const current = document.activeElement as HTMLElement;
    let i = nodes.indexOf(current);
    if (i < 0) {
      i = nodes.findIndex((node) => this.remembered && this.id(node) === this.remembered);
      if (i < 0) i = nodes.findIndex((node) => node.matches('#host, .primary, [data-key]'));
      focus(nodes[Math.max(0, i)]);
    } else if (direction) {
      if (horizontal && current instanceof HTMLSelectElement) {
        this.changeOption(current, direction);
        return;
      }
      // Vertical navigation reaches every control in a responsive, multi-column UI.
      // In the on-screen keyboard it instead moves one row at a time.
      const step = this.editor && !horizontal ? Number(this.editor.dataset.columns) : 1;
      focus(nodes[(i + direction * step + nodes.length) % nodes.length]);
    }
    this.remembered = this.id(document.activeElement as HTMLElement);
  }

  private changeOption(select: HTMLSelectElement, by: number) {
    const opts = [...select.options].filter((opt) => !opt.disabled);
    if (!opts.length) return;
    const i = opts.findIndex((opt) => opt.selected);
    select.value = opts[(i + by + opts.length) % opts.length].value;
    select.dispatchEvent(new Event('change', { bubbles: true }));
  }

  activate() {
    const node = document.activeElement;
    if (!(node instanceof HTMLElement) || !this.root().contains(node)) return this.select();
    if (node instanceof HTMLSelectElement) this.changeOption(node, 1);
    else if (node instanceof HTMLInputElement && node.type === 'text') this.edit(node);
    else node.click();
  }

  closeEditor() {
    if (!this.editor) return false;
    this.editor.close();
    this.editor.remove();
    this.editor = undefined;
    return true;
  }

  private edit(field: HTMLInputElement) {
    const isCode = field.getAttribute('aria-label') === 'Room code';
    const editor = document.createElement('dialog');
    editor.className = 'pad-editor';
    editor.setAttribute('aria-label', isCode ? 'Enter room code' : 'Edit name');
    const heading = document.createElement('h2');
    heading.textContent = editor.getAttribute('aria-label');
    const output = document.createElement('output');
    let draft = field.value;
    const display = () => {
      output.textContent = draft || '–';
    };
    const grid = document.createElement('div');
    grid.className = 'pad-keys';
    const columns = isCode ? 4 : 6;
    editor.dataset.columns = String(columns);
    grid.style.gridTemplateColumns = 'repeat(' + columns + ',1fr)';
    const button = (name: string, action: () => void) => {
      const b = document.createElement('button');
      b.type = 'button';
      b.textContent = name;
      b.onclick = action;
      grid.append(b);
      return b;
    };
    const characters = isCode ? '0123456789abcdef' : 'abcdefghijklmnopqrstuvwxyz0123456789';
    let upper = false;
    const formatCode = (s: string) =>
      s
        .replace(/-/g, '')
        .slice(0, 32)
        .replace(/^(.{8})(.+)$/, '$1-$2')
        .replace(/^(.{13})(.+)$/, '$1-$2')
        .replace(/^(.{18})(.+)$/, '$1-$2')
        .replace(/^(.{23})(.+)$/, '$1-$2');
    const append = (char: string) => {
      draft = isCode ? formatCode(draft + char) : (draft + char).slice(0, field.maxLength);
      display();
    };
    for (const ch of characters)
      button(ch, () => append(upper ? ch.toUpperCase() : ch)).dataset.key = ch;
    if (!isCode) {
      button('Shift', () => {
        upper = !upper;
        for (const key of grid.querySelectorAll<HTMLElement>('[data-key]'))
          key.textContent = upper ? key.dataset.key!.toUpperCase() : key.dataset.key!;
      });
      button('Space', () => append(' '));
      button('-', () => append('-'));
    }
    button('Delete', () => {
      draft = isCode ? formatCode(draft.replace(/-/g, '').slice(0, -1)) : draft.slice(0, -1);
      display();
    });
    button('Clear', () => {
      draft = '';
      display();
    });
    button('Done', () => {
      field.value = draft;
      field.dispatchEvent(new Event('input', { bubbles: true }));
      this.closeEditor();
      focus(field);
    });
    const help = document.createElement('small');
    help.textContent = 'D-pad to move · A to select · B to cancel';
    editor.append(heading, output, grid, help);
    editor.oncancel = (event) => {
      event.preventDefault();
      this.closeEditor();
    };
    document.body.append(editor);
    this.editor = editor;
    display();
    editor.showModal();
    focus(grid.firstElementChild as HTMLElement);
  }
}