TanStack
import {
  FormatForDisplayController,
  HotkeyController,
  hotkey,
} from '@tanstack/lit-hotkeys'
import { LitElement, css, html, nothing, unsafeCSS } from 'lit'
import { customElement, state } from 'lit/decorators.js'
import { createRef, ref } from 'lit/directives/ref.js'
import appStyles from './index.css?raw'
import type { HotkeyChordCallbackContext } from '@tanstack/lit-hotkeys'

// Lit has no provider. Each `@hotkey` and `HotkeyController` takes its own
// options.
@customElement('my-app')
export class MyApp extends LitElement {
  static styles = [
    css`
      :host {
        display: block;
        margin: 0;
        font-family: system-ui, -apple-system, sans-serif;
        background: #f5f5f5;
        color: #333;
        box-sizing: border-box;
      }
      :host *,
      :host *::before,
      :host *::after {
        box-sizing: border-box;
      }
    `,
    unsafeCSS(appStyles),
  ]

  private formatForDisplay = new FormatForDisplayController(this)

  // Chords as strings and objects
  @state() private lastBasic = 'none'

  // Each `@hotkey` registers one hotkey for the method below it, so this
  // method handles five hotkeys. `hotkey` is the chord as registered, with
  // `Mod` kept. `parsedChord` has `Mod` resolved for this platform: Meta on
  // macOS, Control elsewhere.
  // Mod+S would open the browser's Save dialog. A matched hotkey calls
  // `preventDefault` by default, so the dialog stays closed. `meta` doesn't
  // change matching. The devtools and cheat sheets read it.
  // F2, Alt+ArrowUp, and Escape use their `event.key` names. To match a key
  // by position instead, write its code: 'Mod+[KeyS]'.
  // The object form is the same chord as 'Mod+Shift+S', for chords built
  // from data such as modifier checkboxes. `hotkey` reports it as the string
  // 'Mod+Shift+S'.
  @hotkey('Mod+S', { meta: { name: 'Save', description: 'Save the document' } })
  @hotkey('F2')
  @hotkey('Alt+ArrowUp')
  @hotkey('Escape')
  @hotkey({ key: 'S', mod: true, shift: true })
  showChord(
    _event: KeyboardEvent,
    { hotkey, parsedChord }: HotkeyChordCallbackContext,
  ) {
    this.lastBasic = `${hotkey} (modifiers: ${parsedChord.modifiers.join('+') || 'none'})`
  }

  // Fire once while held
  @state() private resetCount = 0

  // Chords only. Without `requireReset`, holding Mod+K fires again on every
  // key repeat. With it, Mod+K fires once until you release a key.
  @hotkey('Mod+K', { requireReset: true })
  countReset() {
    this.resetCount++
  }

  // Fire on key release
  @state() private previewShown = false

  // Hold Mod+P to show the preview. The keydown hotkey shows it, and the
  // keyup hotkey hides it when you release P or Mod. The two don't conflict
  // because their `eventType` differs. A keyup hotkey still calls
  // `preventDefault` on the keydown, so the print dialog doesn't open.
  @hotkey('Mod+P')
  showPreview() {
    this.previewShown = true
  }

  @hotkey('Mod+P', { eventType: 'keyup' })
  hidePreview() {
    this.previewShown = false
  }

  // Turn hotkeys on and off
  @state() private stateEnabled = true
  @state() private modECount = 0
  @state() private modGCount = 0
  private getterCheckboxRef = createRef<HTMLInputElement>()

  // Decorator options are fixed when the class is defined. For options that
  // read element state, use `HotkeyController` with an options function. The
  // controller calls it again after each update. A disabled hotkey stays
  // registered and visible in the devtools. It doesn't call
  // `preventDefault`, so the browser handles Mod+E.
  private modE = new HotkeyController(
    this,
    'Mod+E',
    () => this.modECount++,
    () => ({ enabled: this.stateEnabled }),
  )

  // An `enabled` function is read on each key press, for state that lives
  // outside Lit. This one reads an unbound checkbox, so toggling it doesn't
  // update the element. Keep the function cheap: it runs on every key press.
  private modG = new HotkeyController(this, 'Mod+G', () => this.modGCount++, {
    enabled: () => this.getterCheckboxRef.value?.checked ?? false,
  })

  // Listen on one element
  @state() private panelCount = 0
  @state() private drawerCount = 0
  @state() private drawerOpen = false
  private panelRef = createRef<HTMLDivElement>()
  private drawerRef = createRef<HTMLDivElement>()

  // An element only gets key events while it or something inside it has
  // focus, so the panel has `tabindex="0"`. Enter does nothing elsewhere.
  // The ref is empty until the first render, and an unset target registers
  // nothing, so the options function reads the ref after each update.
  private panelEnter = new HotkeyController(
    this,
    'Enter',
    () => this.panelCount++,
    () => ({ target: this.panelRef.value }),
  )

  // The drawer renders only while it is open. The controller reads the ref
  // after each update, so the hotkey attaches when the drawer renders and
  // detaches when it goes away. Each target gets its own Enter, so these two
  // don't conflict.
  private drawerEnter = new HotkeyController(
    this,
    'Enter',
    () => this.drawerCount++,
    () => ({ target: this.drawerRef.value }),
  )

  // Typing in text fields
  @state() private lastInputs = 'none'

  // The default `ignoreInputs: 'auto'` decides from the hotkey. A key that
  // types or edits text, such as N, Shift+N, Alt+N, or an arrow key, is
  // skipped while a text field has focus, so N types into the field.
  // With 'auto', Control and Meta chords such as Mod+Enter, Escape, and
  // function keys fire in text fields too, because they type nothing.
  // `true` skips text fields for every hotkey. Mod+A then selects the field's
  // text, and selects nothing on the rest of the page.
  // `false` fires in text fields too. 'auto' would skip Shift+Enter there.
  @hotkey('N')
  @hotkey('Mod+Enter')
  @hotkey('Mod+A', { ignoreInputs: true })
  @hotkey('Shift+Enter', { ignoreInputs: false })
  showInputHotkey(
    _event: KeyboardEvent,
    { hotkey }: HotkeyChordCallbackContext,
  ) {
    this.lastInputs = hotkey
  }

  // The browser's default action
  @state() private lastPrevent = 'none'
  private digitsRef = createRef<HTMLInputElement>()

  // These hotkeys listen on the text field. A hotkey targeted at a field
  // always gets its keys, whatever `ignoreInputs` says. By default a matched
  // hotkey calls `preventDefault`, so 1 doesn't type.
  private digitOne = new HotkeyController(
    this,
    '1',
    (_event, { hotkey }) => (this.lastPrevent = hotkey),
    () => ({ target: this.digitsRef.value }),
  )

  // `false` lets the browser act too, so 2 fires the hotkey and types.
  private digitTwo = new HotkeyController(
    this,
    '2',
    (_event, { hotkey }) => (this.lastPrevent = hotkey),
    () => ({ target: this.digitsRef.value, preventDefault: false }),
  )

  // A disabled hotkey normally leaves the key to the browser. `'always'`
  // keeps calling `preventDefault` while the hotkey is disabled, so 3 doesn't
  // type and the callback doesn't run.
  private digitThree = new HotkeyController(
    this,
    '3',
    (_event, { hotkey }) => (this.lastPrevent = hotkey),
    () => ({
      target: this.digitsRef.value,
      enabled: false,
      preventDefault: 'always',
    }),
  )

  // Stop outer hotkeys
  @state() private stopPanel = true
  @state() private stopPanelCount = 0
  @state() private stopPageCount = 0
  private stopPanelRef = createRef<HTMLDivElement>()

  // With focus inside the panel, its hotkey runs before the page's hotkey
  // for the same key. `stopPropagation: true`, the default, stops the event
  // there, so the page's Mod+D doesn't fire. With `false`, both fire.
  private panelModD = new HotkeyController(
    this,
    'Mod+D',
    () => this.stopPanelCount++,
    () => ({
      target: this.stopPanelRef.value,
      stopPropagation: this.stopPanel,
    }),
  )

  @hotkey('Mod+D')
  countPageModD() {
    this.stopPageCount++
  }

  // Run before a widget's own handler
  @state() private bubbleCount = 0
  @state() private captureCount = 0

  // Hotkeys listen in the bubble phase, after the focused element's own
  // handlers. The widget below calls `stopPropagation` on every key, so
  // Mod+ArrowUp never reaches the page while the widget has focus.
  @hotkey('Mod+ArrowUp')
  countBubble() {
    this.bubbleCount++
  }

  // `capture: true` runs the hotkey on the way down, before the widget's
  // handler. With the default `stopPropagation: true`, the widget then
  // doesn't see Mod+ArrowDown at all.
  @hotkey('Mod+ArrowDown', { capture: true })
  countCapture() {
    this.captureCount++
  }

  // Keys another listener already handled
  @state() private modBCount = 0
  @state() private modICount = 0

  // The editor below calls `preventDefault` on its Control and Meta chords,
  // as rich text editors do for Mod+B. With `ignoreDefaultPrevented: true`,
  // the hotkey skips a key press that another listener already prevented.
  @hotkey('Mod+B', { ignoreDefaultPrevented: true })
  countModB() {
    this.modBCount++
  }

  // By default a hotkey fires even when the key was already prevented.
  @hotkey('Mod+I')
  countModI() {
    this.modICount++
  }

  // Duplicate hotkeys
  @state() private modYCount = 0
  @state() private modUCount = 0

  // Two registrations of the same hotkey on the same target both run.
  // `conflictBehavior` is checked when the second one registers, so set it
  // on each registration that may register second. 'allow' registers both
  // silently.
  @hotkey('Mod+Y', { conflictBehavior: 'allow' })
  @hotkey('Mod+Y', { conflictBehavior: 'allow' })
  countModY() {
    this.modYCount++
  }

  // The default, 'warn', also registers both, and logs
  // "[hotkeys] 'Mod+U' is already registered" in development. This example
  // triggers that warning on purpose. 'error' throws when the second one
  // registers instead.
  @hotkey('Mod+U')
  @hotkey('Mod+U')
  countModU() {
    this.modUCount++
  }

  render() {
    const formatForDisplay = this.formatForDisplay.format

    return html`
      <div class="app">
        <header>
          <h1>@hotkey</h1>
          <p>
            @hotkey registers one hotkey while its element is connected, and
            HotkeyController does the same for options that change. Each section
            below shows one way to write a hotkey or one of its options.
          </p>
        </header>

        <main>
          <section class="demo-section">
            <h2>Chords as strings and objects</h2>
            <p>
              Press <kbd>${formatForDisplay('Mod+S')}</kbd>,
              <kbd>${formatForDisplay('F2')}</kbd>,
              <kbd>${formatForDisplay('Alt+ArrowUp')}</kbd>,
              <kbd>${formatForDisplay('Escape')}</kbd>, or
              <kbd>${formatForDisplay('Mod+Shift+S')}</kbd>. The last one is
              written as an object.
            </p>
            <p role="status" class="info-box">Last fired: ${this.lastBasic}</p>
            <p class="hint">
              For a hotkey per platform or more than one hotkey per action, see
              the hotkey-alternates example. For sequences such as G then H, see
              hotkey-sequences.
            </p>
          </section>

          <section class="demo-section">
            <h2>Fire once while held</h2>
            <p>
              Hold <kbd>${formatForDisplay('Mod+K')}</kbd>. The count goes up
              once per press, not on every key repeat.
            </p>
            <p role="status" class="info-box">Mod+K: ${this.resetCount}</p>
          </section>

          <section class="demo-section">
            <h2>Fire on key release</h2>
            <p>
              Hold <kbd>${formatForDisplay('Mod+P')}</kbd> to show the preview.
              Release it to hide the preview.
            </p>
            <p role="status" class="info-box">
              ${this.previewShown ? 'Preview shown' : 'Preview hidden'}
            </p>
          </section>

          <section class="demo-section">
            <h2>Turn hotkeys on and off</h2>
            <p>
              <kbd>${formatForDisplay('Mod+E')}</kbd> reads
              <code>enabled</code> from element state.
              <kbd>${formatForDisplay('Mod+G')}</kbd> reads it from a function
              on each key press.
            </p>
            <label class="control">
              <input
                type="checkbox"
                .checked=${this.stateEnabled}
                @change=${(event: Event) =>
                  (this.stateEnabled = (
                    event.target as HTMLInputElement
                  ).checked)}
              />
              Enable Mod+E
            </label>
            <label class="control">
              <input type="checkbox" checked ${ref(this.getterCheckboxRef)} />
              Enable Mod+G
            </label>
            <p role="status" class="info-box">
              Mod+E: ${this.modECount}, Mod+G: ${this.modGCount}
            </p>
          </section>

          <section class="demo-section">
            <h2>Listen on one element</h2>
            <p>
              Click the panel or the drawer, then press
              <kbd>${formatForDisplay('Enter')}</kbd>. Each has its own hotkey.
            </p>
            <div class="target-grid">
              <div ${ref(this.panelRef)} tabindex="0" class="target-area">
                Panel
              </div>
              <div>
                <button
                  aria-expanded=${this.drawerOpen ? 'true' : 'false'}
                  @click=${() => (this.drawerOpen = !this.drawerOpen)}
                >
                  Toggle drawer
                </button>
                ${
                  this.drawerOpen
                    ? html`<div
                        ${ref(this.drawerRef)}
                        tabindex="0"
                        class="target-area"
                      >
                        Drawer
                      </div>`
                    : nothing
                }
              </div>
            </div>
            <p role="status" class="info-box">
              Panel: ${this.panelCount}, drawer: ${this.drawerCount}
            </p>
          </section>

          <section class="demo-section">
            <h2>Typing in text fields</h2>
            <p>
              Press <kbd>${formatForDisplay('N')}</kbd>,
              <kbd>${formatForDisplay('Mod+Enter')}</kbd>,
              <kbd>${formatForDisplay('Mod+A')}</kbd>, and
              <kbd>${formatForDisplay('Shift+Enter')}</kbd> on the page, then in
              the text field. In the field, N types and Mod+A selects the text.
            </p>
            <label class="control"> Text field <input type="text" /> </label>
            <p role="status" class="info-box">Last fired: ${this.lastInputs}</p>
          </section>

          <section class="demo-section">
            <h2>The browser's default action</h2>
            <p>
              Type 1, 2, and 3 in the field. Only 2 types, because the hotkeys
              for 1 and 3 call <code>preventDefault</code>. The hotkey for 3 is
              disabled, so it doesn't fire.
            </p>
            <label class="control">
              Digits <input type="text" ${ref(this.digitsRef)} />
            </label>
            <p role="status" class="info-box">
              Last fired: ${this.lastPrevent}
            </p>
          </section>

          <section class="demo-section">
            <h2>Stop outer hotkeys</h2>
            <p>
              The panel and the page each have a
              <kbd>${formatForDisplay('Mod+D')}</kbd> hotkey. Click the panel
              and press it, then turn off stopping and press it again.
            </p>
            <label class="control">
              <input
                type="checkbox"
                .checked=${this.stopPanel}
                @change=${(event: Event) =>
                  (this.stopPanel = (event.target as HTMLInputElement).checked)}
              />
              Stop propagation in the panel
            </label>
            <div ${ref(this.stopPanelRef)} tabindex="0" class="target-area">
              Panel
            </div>
            <p role="status" class="info-box">
              Panel: ${this.stopPanelCount}, page: ${this.stopPageCount}
            </p>
          </section>

          <section class="demo-section">
            <h2>Run before a widget's own handler</h2>
            <p>
              Click the widget, which stops every key from reaching the page.
              Then press <kbd>${formatForDisplay('Mod+ArrowUp')}</kbd> and
              <kbd>${formatForDisplay('Mod+ArrowDown')}</kbd>. Only the capture
              hotkey fires.
            </p>
            <!-- Stands in for a component that handles keys itself. -->
            <div
              tabindex="0"
              class="target-area"
              @keydown=${(event: KeyboardEvent) => event.stopPropagation()}
            >
              Widget
            </div>
            <p role="status" class="info-box">
              Bubble: ${this.bubbleCount}, capture: ${this.captureCount}
            </p>
          </section>

          <section class="demo-section">
            <h2>Keys another listener already handled</h2>
            <p>
              Click the editor and press
              <kbd>${formatForDisplay('Mod+B')}</kbd> and
              <kbd>${formatForDisplay('Mod+I')}</kbd>. The editor prevents both,
              so only Mod+I fires. Outside the editor, both fire.
            </p>
            <!-- Stands in for a rich text editor that handles its own chords. -->
            <div
              tabindex="0"
              class="target-area"
              @keydown=${(event: KeyboardEvent) => {
                if (event.ctrlKey || event.metaKey) event.preventDefault()
              }}
            >
              Editor
            </div>
            <p role="status" class="info-box">
              Mod+B: ${this.modBCount}, Mod+I: ${this.modICount}
            </p>
          </section>

          <section class="demo-section">
            <h2>Duplicate hotkeys</h2>
            <p>
              <kbd>${formatForDisplay('Mod+Y')}</kbd> and
              <kbd>${formatForDisplay('Mod+U')}</kbd> are each registered twice,
              so one press runs two callbacks. Mod+U uses the default
              <code>conflictBehavior</code>, so the console shows a warning for
              it in development.
            </p>
            <p role="status" class="info-box">
              Mod+Y: ${this.modYCount}, Mod+U: ${this.modUCount}
            </p>
          </section>
        </main>
      </div>
    `
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'my-app': MyApp
  }
}