Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/alpine-hotkey-directive.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/alpine-hotkeys': minor
---

Add the `x-hotkey` directive, installed with `Alpine.plugin(hotkeyDirective)`. Name the hotkey with modifiers and give the callback as the expression: `x-hotkey.mod.s="save()"`, `x-hotkey.escape="close()"`, or `x-hotkey.g.h="goHome()"` for a sequence. The hotkey lives as long as the attribute, so a morph that changes or removes it, as Livewire does on every update, replaces or removes the hotkey. A changed `x-init="$hotkeys.createHotkey(...)"` stays registered until its element is removed. With Alpine's CSP build, name a component method: `x-hotkey.mod.s="save"`. A page that only uses `x-hotkey` doesn't ship the `$hotkeys` owners and readers.
5 changes: 5 additions & 0 deletions .changeset/ember-4-12-floor.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/ember-hotkeys': minor
---

Support Ember 4.12 and newer, including the 4.12 and 5.12 LTS lines and ember-source 6.8.0 to 6.8.2, 6.9.0 and 6.10.0. The adapter tracked its state with `@ember/reactive/collections`, which only newer ember-source versions ship. It now uses `@glimmer/tracking`, which every supported version has.
5 changes: 5 additions & 0 deletions .changeset/ember-scope-defaults-order.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/ember-hotkeys': minor
---

`createHotkeysScope` defaults no longer override an app hotkey's declared options. The helpers and modifiers from a scope put its defaults below the declaration, as the App Hotkeys guide says: scope defaults, then declared options, then call-site options. Before, a scope default such as `preventDefault: true` replaced `preventDefault: false` from `defineAppHotkeys`.
46 changes: 46 additions & 0 deletions .github/workflows/ember-compat.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
name: Ember Compatibility

# The Ember adapter in classic ember-cli apps on the oldest Ember lines its peer
# range allows. The package's own tests run on a recent Ember only.
on:
pull_request:
paths:
- packages/hotkeys/src/**
- packages/hotkeys/package.json
- packages/ember-hotkeys/**
- e2e/ember-compat/**
- e2e/scripts/ember-compat.ts
- e2e/package.json
- .github/workflows/ember-compat.yml
push:
branches: [main]
workflow_dispatch:

concurrency:
group: ${{ github.workflow }}-${{ github.event.number || github.ref }}
cancel-in-progress: true

permissions:
contents: read

jobs:
ember:
name: Ember ${{ matrix.ember }}
runs-on: ubuntu-latest
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
ember: ['4.12', '5.12']
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Setup Tools
uses: TanStack/config/.github/setup@c1ef98305f122da0257951e5e2896e143bdf8173 # main
# Chrome comes with the runner image.
- name: Run Probe App
run: pnpm test:e2e:ember-compat "~${EMBER_VERSION}.0"
env:
EMBER_VERSION: ${{ matrix.ember }}
450 changes: 288 additions & 162 deletions .intent/review-state.json

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions docs/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -1623,6 +1623,10 @@
"label": "createHotkeysScope",
"to": "framework/alpine/reference/functions/createHotkeysScope"
},
{
"label": "hotkeyDirective",
"to": "framework/alpine/reference/functions/hotkeyDirective"
},
{
"label": "hotkeyRecorderPlugin",
"to": "framework/alpine/reference/functions/hotkeyRecorderPlugin"
Expand Down
2 changes: 1 addition & 1 deletion docs/framework/alpine/guides/hotkeys.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ To register hotkeys from markup, install `hotkeysPlugin` and call the same funct
</div>
```

The plugin destroys `$hotkeys` with its element. The rest of this guide uses an owner from `createHotkeysScope`.
The plugin destroys `$hotkeys` with its element. For a fixed hotkey with the default options, the `x-hotkey` directive is shorter and follows morphs: `x-hotkey.mod.s="count++"`. See [Use the `x-hotkey` directive](../quick-start#use-the-x-hotkey-directive). The rest of this guide uses an owner from `createHotkeysScope`.

### Optional hotkeys

Expand Down
46 changes: 45 additions & 1 deletion docs/framework/alpine/quick-start.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,33 @@ Destroying the owner unregisters every hotkey it created. The adapter runs in th

That's all a hotkey needs. Shared defaults, scopes, and the other features later in this guide are optional, so add them as your app grows.

### Use the `x-hotkey` directive

To register a hotkey in markup, install `hotkeyDirective` and name the hotkey with modifiers. The expression runs when the hotkey fires, with `$event` set to the keyboard event:

```ts
import Alpine from 'alpinejs'
import { hotkeyDirective } from '@tanstack/alpine-hotkeys'

Alpine.plugin(hotkeyDirective)
Alpine.start()
```

```html
<div x-data="{ count: 0 }" x-hotkey.mod.s="count++">
Saved <span x-text="count"></span> times
</div>
```

HTML lowercases attribute names, so write each part in lowercase and multi-word keys with dashes: `x-hotkey.mod.shift.k`, `x-hotkey.escape`, `x-hotkey.arrow-up`, `x-hotkey.f2`. Write modifiers before their key. Each key ends a step, so `x-hotkey.g.h` is the sequence `['G', 'H']`, and `x-hotkey.s.mod`, with no key after `mod`, registers nothing.

The hotkey uses the built-in defaults and lives as long as the attribute. Alpine removes it with its element, and when a morph changes or removes the attribute, as Livewire does on every update. For options, a hotkey that changes with state, or a key that can't be written in an attribute name, such as `?` or `[KeyW]`, use `$hotkeys` or an owner from `createHotkeysScope`.

`hotkeyDirective` is a separate plugin from `hotkeysPlugin`. A page that only uses `x-hotkey` doesn't ship the owners and readers that `$hotkeys` holds.

### Use the `$hotkeys` magic

The plugin also adds the `$hotkeys` magic, which registers hotkeys from markup:
`hotkeysPlugin` also adds the `$hotkeys` magic, which takes the same arguments as an owner from `createHotkeysScope`:

```html
<div x-data="{ count: 0 }" x-init="$hotkeys.createHotkey('Mod+S', () => count++)">
Expand All @@ -57,6 +81,26 @@ The plugin also adds the `$hotkeys` magic, which registers hotkeys from markup:

Call `$hotkeys.create*` in `x-init` or `init()`, and read `.value` anywhere. In a reactive expression such as `x-text`, each evaluation calls `create*` again and adds a new subscription.

Alpine runs `x-init` again when a morph changes it, but `$hotkeys` keeps its registrations until its element is removed. On pages that Livewire or `Alpine.morph` updates, a changed `x-init` hotkey stays registered next to the new one. Use `x-hotkey`, or an `Alpine.data` component that destroys its owner in `destroy()`, on those pages.

### Alpine's CSP build

The CSP build of Alpine, `@alpinejs/csp`, can't parse arrow functions, so `x-init="$hotkeys.createHotkey('Mod+S', () => save())"` registers nothing. Move the callback into an `Alpine.data` component, and name the method in `x-hotkey`:

```ts
Alpine.data('editor', () => ({
save() {
// ...
},
}))
```

```html
<div x-data="editor" x-hotkey.mod.s="save"></div>
```

A call such as `x-hotkey.mod.s="save()"` needs `@alpinejs/csp` 3.15 or newer, because older CSP builds only run a method by name. The `init()` pattern from [Register a hotkey](#register-a-hotkey) also works, because the callback lives in JavaScript, not in markup.

## Register several hotkeys

When a component has more than one hotkey, register them together with `createHotkeys`:
Expand Down
27 changes: 27 additions & 0 deletions docs/framework/alpine/reference/functions/hotkeyDirective.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
---
id: hotkeyDirective
title: hotkeyDirective
---

<!-- DO NOT EDIT: this page is autogenerated from the type comments -->

```ts
function hotkeyDirective(alpine): void;
```

Defined in: [hotkeyDirective.ts:46](https://github.com/TanStack/hotkeys/blob/main/packages/alpine-hotkeys/src/hotkeyDirective.ts#L46)

Installs `x-hotkey`, which registers the hotkey named by its modifiers while
its element exists: `x-hotkey.mod.s="save()"`, `x-hotkey.escape="close()"`,
`x-hotkey.g.h="goHome()"`. The expression gets `$event`. Alpine removes the
hotkey with its element, and when a morph changes or removes the attribute.

## Parameters

### alpine

`Alpine`

## Returns

`void`
1 change: 1 addition & 0 deletions docs/framework/alpine/reference/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,6 @@ title: "@tanstack/alpine-hotkeys"

- [createHotkeyRecorder](functions/createHotkeyRecorder.md)
- [createHotkeysScope](functions/createHotkeysScope.md)
- [hotkeyDirective](functions/hotkeyDirective.md)
- [hotkeyRecorderPlugin](functions/hotkeyRecorderPlugin.md)
- [hotkeysPlugin](functions/hotkeysPlugin.md)
6 changes: 3 additions & 3 deletions docs/framework/ember/reference/classes/useHotkey.md
Original file line number Diff line number Diff line change
Expand Up @@ -1650,8 +1650,11 @@ coalesced manner.
\| ((`properties`) => `void`)
\| (() => `void`)
\| `DirtyableTag`
\| ((...`args`) => `any`)
\| ((...`args`) => `this`)
\| (() => `this`)
\| (() => `void`)
\| (() => `string`)
\| (\{
\<`K`\> (`key`): `UseHotkey`\[`K`\];
(`key`): `unknown`;
Expand Down Expand Up @@ -1683,9 +1686,6 @@ coalesced manner.
\| ((`keyName`, `decrement?`) => `number`)
\| ((`keyName`) => `boolean`)
\| (\<`K`\>(`key`) => `unknown`)
\| ((...`args`) => `any`)
\| (() => `void`)
\| (() => `string`)
\| `undefined`

##### Parameters
Expand Down
6 changes: 3 additions & 3 deletions docs/framework/ember/reference/classes/useHotkeys.md
Original file line number Diff line number Diff line change
Expand Up @@ -1633,6 +1633,9 @@ coalesced manner.
\| ((`positional`, `options`) => `void`)
\| `Owner`
\| `DirtyableTag`
\| ((...`args`) => `any`)
\| (() => `void`)
\| (() => `string`)
\| ((`properties`) => `void`)
\| (() => `void`)
\| ((...`args`) => `this`)
Expand Down Expand Up @@ -1668,9 +1671,6 @@ coalesced manner.
\| ((`keyName`, `decrement?`) => `number`)
\| ((`keyName`) => `boolean`)
\| (\<`K`\>(`key`) => `unknown`)
\| ((...`args`) => `any`)
\| (() => `void`)
\| (() => `string`)
\| `undefined`

##### Parameters
Expand Down
2 changes: 1 addition & 1 deletion docs/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ Start with the [Alpine Quick Start](./framework/alpine/quick-start) and [Alpine

# Ember

Requires Ember 6.8.3 or newer (excluding 6.9.0 and 6.10.0), and works with Vite (Embroider) or classic `ember-cli` with `ember-auto-import`. Register hotkeys in strict-mode `.gts` components and pass the component as owner to state readers and recorders.
Requires Ember 4.12 or newer, and works with Vite (Embroider) or classic `ember-cli` with `ember-auto-import` 2. Register hotkeys in strict-mode `.gts` components and pass the component as owner to state readers and recorders.

Start with the [Ember Quick Start](./framework/ember/quick-start) and [Ember guides](./framework/ember/guides/hotkeys). Ember ships the hotkeys adapter only and has no dedicated devtools package.

Expand Down
23 changes: 16 additions & 7 deletions e2e/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@

Browser tests for `@tanstack/hotkeys`, run with Playwright against the library source.

| Suite | Command | Browsers | Keys |
| ------------------------------- | ------------------------------ | ------------------------------- | ----------------------------------------------- |
| Browser behavior (`browser/`) | `pnpm test:e2e` | Chromium, Firefox, WebKit | Playwright's simulated keyboard |
| Adapters (`adapters/`) | `pnpm test:e2e:adapters` | Chromium, Firefox, WebKit | Playwright's simulated keyboard |
| Keyboard layouts (`layouts/`) | `pnpm test:e2e:layouts:docker` | Chromium, Firefox | Real key presses through Linux keyboard layouts |
| Server rendering (`ssr/`) | `pnpm test:e2e:ssr` | Chromium | Playwright's simulated keyboard |
| Real input, nightly (`native/`) | `pnpm test:e2e:native` | Chromium, Edge, Chrome, Firefox | Real key presses on Windows, Wayland, and ibus |
| Suite | Command | Browsers | Keys |
| ------------------------------------- | -------------------------------------- | ------------------------------- | ----------------------------------------------- |
| Browser behavior (`browser/`) | `pnpm test:e2e` | Chromium, Firefox, WebKit | Playwright's simulated keyboard |
| Adapters (`adapters/`) | `pnpm test:e2e:adapters` | Chromium, Firefox, WebKit | Playwright's simulated keyboard |
| Keyboard layouts (`layouts/`) | `pnpm test:e2e:layouts:docker` | Chromium, Firefox | Real key presses through Linux keyboard layouts |
| Server rendering (`ssr/`) | `pnpm test:e2e:ssr` | Chromium | Playwright's simulated keyboard |
| Ember compatibility (`ember-compat/`) | `pnpm test:e2e:ember-compat <version>` | Chrome | Synthetic events in Ember's test runner |
| Real input, nightly (`native/`) | `pnpm test:e2e:native` | Chromium, Edge, Chrome, Firefox | Real key presses on Windows, Wayland, and ibus |

Run the commands from the repository root or from `e2e/`. Install browsers once with `pnpm --filter @tanstack/hotkeys-e2e exec playwright install`.

Expand Down Expand Up @@ -53,6 +54,14 @@ For each example and for a Mac and a Windows user agent, the tests check that:

To add an example, add it to `ssr/examples.ts` with an unused port and the command that starts its production server.

## Ember compatibility

The Ember adapter supports `ember-source` 4.12 and newer, but its own tests run on a recent Ember only. This check runs it in a classic ember-cli app on an older Ember. `scripts/ember-compat.ts` generates the app with the given ember-cli version, copies in the probe component and test from `ember-compat/`, installs the packed core and adapter, and runs `ember test`. The test registers a hotkey with the `useHotkey` helper and one with the `onHotkey` modifier, fires both, reads held keys, a key hold and a hint, and checks that teardown unregisters everything.

Run `pnpm test:e2e:ember-compat "~4.12.0"` from the repository root: it builds the core and the adapter, then runs the check. Run `pnpm --filter @tanstack/hotkeys-e2e test:e2e:ember-compat "~4.12.0"` to skip the build. A second argument sets the `ember-source` version. The app is generated in a temporary folder and needs network access. The script runs on macOS and Linux. The check uses Chrome; set `TESTEM_BROWSER="Headless Edge"` where only Edge is installed.

CI runs it on 4.12 and 5.12 for pull requests that change the core source or the Ember adapter, and after each merge to `main`.

## Keyboard layouts

These tests switch the X11 keyboard layout with `setxkbmap` and press physical keys with `xdotool`. The browser receives the same events a user's keyboard would produce on that layout. Cases cover AltGr, AZERTY, QWERTZ, Dvorak, Russian (alone and with a US group), dead keys, Turkish dotless i, the Czech digit row, the ISO and JIS extra keys (UK, Brazilian ABNT2, Japanese), and the numpad with NumLock on and off.
Expand Down
7 changes: 7 additions & 0 deletions e2e/ember-compat/app/components/probe.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{{use-hotkey 'Control+S' this.save}}
<span id='count'>{{this.count}}</span>
<span id='held'>{{this.heldText}}</span>
<span id='hold'>{{if this.hold.value 'held' 'up'}}</span>
<span id='hint'>{{if this.hint.value 'on' 'off'}}</span>
<span id='label'>{{this.formatForDisplay 'Control+S'}}</span>
<div id='el' tabindex='0' {{on-hotkey 'K' this.save}}></div>
25 changes: 25 additions & 0 deletions e2e/ember-compat/app/components/probe.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { action } from '@ember/object'
import Component from '@glimmer/component'
import { tracked } from '@glimmer/tracking'
import {
useFormatForDisplay,
useHeldKeys,
useHotkeyHint,
useKeyHold,
} from '@tanstack/ember-hotkeys'

export default class Probe extends Component {
@tracked count = 0
held = useHeldKeys(this)
hold = useKeyHold(this, 'Control')
hint = useHotkeyHint(this, 'Control+S')
formatForDisplay = useFormatForDisplay()

get heldText() {
return this.held.value.join(',')
}

@action save() {
this.count++
}
}
1 change: 1 addition & 0 deletions e2e/ember-compat/app/helpers/use-hotkey.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { useHotkey as default } from '@tanstack/ember-hotkeys'
1 change: 1 addition & 0 deletions e2e/ember-compat/app/modifiers/on-hotkey.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { onHotkey as default } from '@tanstack/ember-hotkeys'
60 changes: 60 additions & 0 deletions e2e/ember-compat/tests/integration/probe-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { render, settled, clearRender, focus } from '@ember/test-helpers'
import { VERSION } from '@ember/version'
import { getHotkeyManager } from '@tanstack/ember-hotkeys'
import { hbs } from 'ember-cli-htmlbars'
import { setupRenderingTest } from 'ember-qunit'
import { module, test } from 'qunit'

function key(target, type, init) {
target.dispatchEvent(
new KeyboardEvent(type, { bubbles: true, cancelable: true, ...init }),
)
}

module('tanstack ember-hotkeys probe', function (hooks) {
setupRenderingTest(hooks)

test('helper, modifier, readers and teardown', async function (assert) {
assert.ok(true, `ember-source ${VERSION}`)
await render(hbs`<Probe />`)
await settled()
assert.strictEqual(
getHotkeyManager().registrations.state.size,
2,
'helper and modifier registered',
)
assert.dom('#hint').hasText('off')
assert.dom('#label').hasAnyText()

key(document.body, 'keydown', {
key: 'Control',
code: 'ControlLeft',
ctrlKey: true,
})
await settled()
assert.dom('#held').hasText('Control', 'held keys tracked')
assert.dom('#hold').hasText('held', 'key hold tracked')
assert.dom('#hint').hasText('on', 'hint tracked')

key(document.body, 'keydown', { key: 's', code: 'KeyS', ctrlKey: true })
await settled()
assert.dom('#count').hasText('1', 'helper hotkey fired')
key(document.body, 'keyup', { key: 's', code: 'KeyS', ctrlKey: true })
key(document.body, 'keyup', { key: 'Control', code: 'ControlLeft' })
await settled()
assert.dom('#held').hasText('', 'released')
assert.dom('#hint').hasText('off')

await focus('#el')
key(document.querySelector('#el'), 'keydown', { key: 'k', code: 'KeyK' })
await settled()
assert.dom('#count').hasText('2', 'modifier hotkey fired')

await clearRender()
assert.strictEqual(
getHotkeyManager().registrations.state.size,
0,
'teardown',
)
})
})
1 change: 1 addition & 0 deletions e2e/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"scripts": {
"test:e2e": "playwright test",
"test:e2e:adapters": "playwright test --config playwright.adapters.config.ts",
"test:e2e:ember-compat": "node scripts/ember-compat.ts",
"test:e2e:layouts": "playwright test --config playwright.layouts.config.ts",
"test:e2e:layouts:docker": "node scripts/layouts-docker.ts",
"test:e2e:native": "playwright test --config playwright.native.config.ts",
Expand Down
Loading
Loading