Skip to content

Angular Example: Scopes

import {
  Component,
  computed,
  inject,
  input,
  output,
  signal,
} from '@angular/core'
import {
  injectFormatForDisplay,
  injectHotkey,
  injectHotkeyScopesState,
  provideHotkeys,
} from '@tanstack/angular-hotkeys'

// Every hotkey below is a plain `injectHotkey` call with no `scope` option. It
// registers in the scope of the nearest `provideHotkeys` in its component's
// injector tree that sets one, or in `global` when none does.

/** No provider above it sets a scope, so it's in `global`. */
@Component({
  selector: 'app-global-scope',
  standalone: true,
  template: `
    <section class="demo-section">
      <h2>Global scope</h2>
      <p>
        <kbd>{{ formatForDisplay('Alt+[KeyH]') }}</kbd> opens help. It's in
        <code>global</code>, which is always active. Only an exclusive scope
        suspends it.
      </p>
      <p role="status">
        Help opened {{ opened() }} {{ opened() === 1 ? 'time' : 'times' }}
      </p>
    </section>
  `,
})
export class GlobalScope {
  readonly formatForDisplay = injectFormatForDisplay()
  readonly opened = signal(0)

  constructor() {
    injectHotkey('Alt+[KeyH]', () => this.opened.update((n) => n + 1))
  }
}

/** In its own `palette` scope, so the dialog below can allow just this. */
@Component({
  selector: 'app-palette',
  standalone: true,
  providers: [provideHotkeys({ scope: 'palette' })],
  template: `
    <section class="demo-section">
      <h2>Command palette</h2>
      <p>
        <kbd>{{ formatForDisplay('Mod+K') }}</kbd> opens the palette. It's in
        the <code>palette</code> scope.
      </p>
      <p role="status">
        Palette opened {{ opened() }} {{ opened() === 1 ? 'time' : 'times' }}
      </p>
    </section>
  `,
})
export class Palette {
  readonly formatForDisplay = injectFormatForDisplay()
  readonly opened = signal(0)

  constructor() {
    // Mod+K would focus the browser's search bar on Windows and Linux. A
    // matched hotkey calls `preventDefault` by default.
    injectHotkey('Mod+K', () => this.opened.update((n) => n + 1))
  }
}

@Component({
  selector: 'app-comment-box',
  standalone: true,
  providers: [provideHotkeys({ scope: 'comments' })],
  template: `<div class="panel">Comment box</div>`,
})
export class CommentBox {
  readonly post = output()

  constructor() {
    // Only this one runs while both are active, because `comments` is nested.
    injectHotkey('Mod+S', () => this.post.emit())
  }
}

/** In the `document` scope. The comment box nests `comments` inside it. */
@Component({
  selector: 'app-nested-scopes',
  standalone: true,
  imports: [CommentBox],
  providers: [provideHotkeys({ scope: 'document' })],
  template: `
    <section class="demo-section">
      <h2>Nested scopes</h2>
      <p>
        The document and its comment box both register
        <kbd>{{ formatForDisplay('Mod+S') }}</kbd
        >. The <code>comments</code> scope is nested in <code>document</code>,
        so it wins while it's mounted. Hide the comment box and the document
        saves again.
      </p>
      <label>
        <input
          #checkbox
          type="checkbox"
          [checked]="showComments()"
          (change)="showComments.set(checkbox.checked)"
        />
        Show comment box
      </label>
      @if (showComments()) {
        <app-comment-box (post)="posts.set(posts() + 1)" />
      }
      <p role="status">
        Document saves: {{ saves() }}. Comments posted: {{ posts() }}.
      </p>
    </section>
  `,
})
export class NestedScopes {
  readonly formatForDisplay = injectFormatForDisplay()
  readonly saves = signal(0)
  readonly posts = signal(0)
  readonly showComments = signal(true)

  constructor() {
    // Mod+S would open the browser's Save dialog. A matched hotkey calls
    // `preventDefault` by default.
    injectHotkey('Mod+S', () => this.saves.update((n) => n + 1))
  }
}

@Component({
  selector: 'app-folder',
  standalone: true,
  // The getters run in this component's injector, so they read its inputs.
  // With `enabled` false, the scope stays in the page but inactive, so its
  // hotkeys don't fire. Destroying the folder would lose its state.
  providers: [
    provideHotkeys({
      scope: () => inject(Folder).scope(),
      enabled: () => inject(Folder).selected(),
    }),
  ],
  template: `
    <button
      class="panel folder"
      [attr.aria-pressed]="selected()"
      (click)="selectFolder.emit()"
    >
      {{ name() }}: {{ count() }} {{ count() === 1 ? 'item' : 'items' }}
    </button>
  `,
})
export class Folder {
  readonly scope = input.required<string>()
  readonly name = input.required<string>()
  readonly count = input.required<number>()
  readonly selected = input.required<boolean>()
  readonly selectFolder = output()
  readonly add = output()

  constructor() {
    // The same call in every folder. Only the enabled folder's scope fires it.
    injectHotkey('Alt+[KeyN]', () => this.add.emit())
  }
}

/** In the `mail` scope. Each folder nests its own scope inside it. */
@Component({
  selector: 'app-enabled-scopes',
  standalone: true,
  imports: [Folder],
  providers: [provideHotkeys({ scope: 'mail' })],
  template: `
    <section class="demo-section">
      <h2>Enabled scopes</h2>
      <p>
        All three folders stay mounted and register
        <kbd>{{ formatForDisplay('Alt+[KeyN]') }}</kbd
        >. Only the selected folder's provider is <code>enabled</code>, so the
        key adds to that one. Select with
        <kbd>{{ formatForDisplay('Alt+[KeyI]') }}</kbd
        >, <kbd>{{ formatForDisplay('Alt+[KeyA]') }}</kbd
        >, and <kbd>{{ formatForDisplay('Alt+[KeyS]') }}</kbd
        >.
      </p>
      <div class="folders">
        <app-folder
          scope="inbox"
          name="Inbox"
          [count]="items().Inbox"
          [selected]="current() === 'Inbox'"
          (selectFolder)="current.set('Inbox')"
          (add)="items.set({ ...items(), Inbox: items().Inbox + 1 })"
        />
        <app-folder
          scope="archive"
          name="Archive"
          [count]="items().Archive"
          [selected]="current() === 'Archive'"
          (selectFolder)="current.set('Archive')"
          (add)="items.set({ ...items(), Archive: items().Archive + 1 })"
        />
        <app-folder
          scope="spam"
          name="Spam"
          [count]="items().Spam"
          [selected]="current() === 'Spam'"
          (selectFolder)="current.set('Spam')"
          (add)="items.set({ ...items(), Spam: items().Spam + 1 })"
        />
      </div>
      <p role="status">
        Selected: {{ current() }}. Items: Inbox {{ items().Inbox }}, Archive
        {{ items().Archive }}, Spam {{ items().Spam }}
      </p>
    </section>
  `,
})
export class EnabledScopes {
  readonly formatForDisplay = injectFormatForDisplay()
  readonly current = signal('Inbox')
  readonly items = signal({ Inbox: 0, Archive: 0, Spam: 0 })

  constructor() {
    injectHotkey('Alt+[KeyI]', () => this.current.set('Inbox'))
    injectHotkey('Alt+[KeyA]', () => this.current.set('Archive'))
    injectHotkey('Alt+[KeyS]', () => this.current.set('Spam'))
  }
}

/** Nested in the exclusive `dialog` scope, so it stays active. */
@Component({
  selector: 'app-steps',
  standalone: true,
  providers: [provideHotkeys({ scope: 'dialog-steps' })],
  template: `
    <p class="panel">
      Step {{ step() }} of 3. <kbd>{{ formatForDisplay('Alt+[KeyN]') }}</kbd>
      moves to the next step.
    </p>
  `,
})
export class Steps {
  readonly formatForDisplay = injectFormatForDisplay()
  readonly step = signal(1)

  constructor() {
    // The folders register Alt+N too, but their scopes are suspended.
    injectHotkey('Alt+[KeyN]', () => this.step.update((n) => (n % 3) + 1))
  }
}

@Component({
  selector: 'app-settings-dialog',
  standalone: true,
  imports: [Steps],
  // `exclusive` without `allow` suspends every other scope. The `allow`
  // array is compared by value, so a new array doesn't reactivate the scope.
  providers: [
    provideHotkeys({
      scope: 'dialog',
      exclusive: () => ({ allow: inject(SettingsDialog).allow() }),
    }),
  ],
  // Renders in place, inside the settings section. The scope comes from the
  // injector tree, not from where the DOM renders, so moving the element to
  // the body would change nothing.
  template: `
    <div class="backdrop">
      <div
        class="dialog"
        role="dialog"
        aria-modal="true"
        aria-labelledby="dialog-title"
      >
        <h2 id="dialog-title">Edit settings</h2>
        <p>
          <kbd>{{ formatForDisplay('Mod+S') }}</kbd> saves this dialog instead
          of the document. <kbd>{{ formatForDisplay('Escape') }}</kbd> closes
          it.
        </p>
        <app-steps />
        <div class="actions">
          <button class="secondary" (click)="close.emit()">Cancel</button>
          <button (click)="save.emit()">Save</button>
        </div>
      </div>
    </div>
  `,
})
export class SettingsDialog {
  readonly formatForDisplay = injectFormatForDisplay()
  readonly allow = input.required<Array<string>>()
  readonly close = output()
  readonly save = output()

  constructor() {
    injectHotkey('Escape', () => this.close.emit())
    // Saves the dialog. The document's Mod+S is suspended while it's open.
    injectHotkey('Mod+S', () => this.save.emit())
  }
}

/** In the `settings` scope. The dialog nests an exclusive scope inside it. */
@Component({
  selector: 'app-exclusive-scopes',
  standalone: true,
  imports: [SettingsDialog],
  providers: [provideHotkeys({ scope: 'settings' })],
  template: `
    <section class="demo-section">
      <h2>Exclusive scopes</h2>
      <p>
        While the dialog is open, its exclusive scope suspends every other
        scope, including <code>global</code>. Scopes nested in it keep working,
        and so do the scopes it allows.
      </p>
      <fieldset>
        <legend>Allow while the dialog is open</legend>
        <label>
          <input
            #global
            type="checkbox"
            [checked]="allowGlobal()"
            (change)="allowGlobal.set(global.checked)"
          />
          global
        </label>
        <label>
          <input
            #palette
            type="checkbox"
            [checked]="allowPalette()"
            (change)="allowPalette.set(palette.checked)"
          />
          palette
        </label>
      </fieldset>
      <button (click)="open.set(true)">
        Open dialog <kbd>{{ formatForDisplay('Alt+[KeyO]') }}</kbd>
      </button>
      @if (open()) {
        <app-settings-dialog
          [allow]="allow()"
          (close)="open.set(false)"
          (save)="saves.set(saves() + 1); open.set(false)"
        />
      }
      <p role="status">
        Dialog is {{ open() ? 'open' : 'closed' }}. Saved {{ saves() }}
        {{ saves() === 1 ? 'time' : 'times' }}.
      </p>
    </section>
  `,
})
export class ExclusiveScopes {
  readonly formatForDisplay = injectFormatForDisplay()
  readonly open = signal(false)
  readonly saves = signal(0)
  readonly allowGlobal = signal(false)
  readonly allowPalette = signal(true)
  readonly allow = computed(() => [
    ...(this.allowGlobal() ? ['global'] : []),
    ...(this.allowPalette() ? ['palette'] : []),
  ])

  constructor() {
    injectHotkey('Alt+[KeyO]', () => this.open.set(true))
  }
}

/** Reads the hotkey manager's scope state, which updates as scopes change. */
@Component({
  selector: 'app-scope-state',
  standalone: true,
  template: `
    <section class="demo-section">
      <h2>Scope state</h2>
      <div role="status">
        <p>Active: {{ list(scopes().active) }}</p>
        <p>Exclusive: {{ scopes().exclusive ?? 'none' }}</p>
        <p>Allowed: {{ list(scopes().allowed) }}</p>
        <p>Suspended: {{ list(scopes().suspended) }}</p>
      </div>
    </section>
  `,
})
export class ScopeState {
  readonly scopes = injectHotkeyScopesState()

  // Sorted, because the order scopes activate in depends on the order the
  // framework creates components. `global` is always active and isn't listed.
  list(names: ReadonlyArray<string>) {
    return names.length > 0 ? [...names].sort().join(', ') : 'none'
  }
}

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [
    EnabledScopes,
    ExclusiveScopes,
    GlobalScope,
    NestedScopes,
    Palette,
    ScopeState,
  ],
  template: `
    <div class="app">
      <header>
        <h1>Hotkey scopes</h1>
        <p>
          Each <code>provideHotkeys</code> with a <code>scope</code> groups the
          hotkeys of the component that provides it and its children. They fire
          while that component exists and the provider is enabled, and no
          exclusive scope suspends them.
        </p>
      </header>
      <main>
        <app-global-scope />
        <app-palette />
        <app-nested-scopes />
        <app-enabled-scopes />
        <app-exclusive-scopes />
        <app-scope-state />
      </main>
    </div>
  `,
})
export class AppComponent {}