@joknoll/svelte-attach 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,155 +1,78 @@
1
1
  # @joknoll/svelte-attach
2
2
 
3
- Svelte 5 attachments for keyboard shortcuts, sound effects, vibration, and gamepad buttons. Each feature has its own import path, so you only load what you use.
3
+ Svelte attachments to add keyboard shortcuts, sound effects, vibration, and gamepad controls to Svelte 5 components.
4
4
 
5
- ```bash
6
- vp add @joknoll/svelte-attach
7
- ```
8
-
9
- | Import | Purpose |
10
- | -------------------------------- | ----------------------------------------------- |
11
- | `@joknoll/svelte-attach/key` | Keyboard shortcuts and held state |
12
- | `@joknoll/svelte-attach/sound` | Web Audio playback bound to DOM events |
13
- | `@joknoll/svelte-attach/haptic` | Web Vibration feedback bound to DOM events |
14
- | `@joknoll/svelte-attach/gamepad` | Standard gamepad buttons that activate elements |
5
+ ## Usage
15
6
 
16
- Every attachment has the same shape: `name(primary, options?)`. The first argument is the one thing you always need, and everything optional, including callbacks, goes in the options object. Callbacks receive the element first. Invalid arguments throw when the attachment is created, not when an event fires. Attachments that need a browser API do nothing during server rendering, and `isSupported()` reports whether that API exists.
7
+ Requires Svelte `5.55.0` or later.
17
8
 
18
- ## Keyboard shortcuts
9
+ ### Keyboard
19
10
 
20
11
  ```svelte
21
12
  <script lang="ts">
22
- import { hotkey, pressed, formatHint } from "@joknoll/svelte-attach/key";
13
+ import { hotkey } from "@joknoll/svelte-attach/key";
23
14
  </script>
24
15
 
25
- <button title={formatHint("mod+k")} {@attach hotkey("mod+k", { pressedClass: "is-pressed" })}>
26
- Open command menu
16
+ <button popovertarget="shortcuts" {@attach hotkey("mod+k")}>
17
+ Show shortcuts
27
18
  </button>
28
19
 
29
- <kbd {@attach pressed("shift")}>Shift</kbd>
20
+ <div id="shortcuts" popover>Press Escape to close.</div>
30
21
  ```
31
22
 
32
- `hotkey(keys, options?)` clicks the attached element when a shortcut is pressed anywhere on the page. Options:
33
-
34
- - **`onTrigger(element, event)`:** called instead of the click.
35
- - **`pressedClass`:** a class kept on the element from activation until the shortcut is released.
36
- - **`preventDefault`, `stopPropagation`, `ignoreInputs`, `ignoreRepeat`:** control dispatch. `preventDefault`, `ignoreInputs` and `ignoreRepeat` default to `true`.
37
-
38
- `hotkey` also sets `aria-keyshortcuts` and restores the previous value on cleanup. When two attached elements claim the same shortcut, the most recently attached one wins, and removing it restores the previous one.
39
-
40
- A shortcut is zero or more modifiers followed by one key, joined with `+`, such as `"ctrl+shift+k"`. Pass an array for alternatives, such as `["j", "arrowdown"]`.
23
+ Press `⌘K` on Apple devices or `Ctrl+K` elsewhere to open the popover. The button doesn’t need focus.
41
24
 
42
- - **Modifiers:** `ctrl`, `shift`, `alt`, `meta`, and `mod`, which means Meta on Apple devices and Control elsewhere. `control`, `option`, `cmd`, `command`, and `win` are accepted as aliases.
43
- - **Keys:**
44
- - any single character
45
- - `f1` to `f12`
46
- - `escape`, `enter`, `tab`, `space`, `plus`, `backspace`, `delete`, `insert`, `home`, `end`, `pageup`, `pagedown`
47
- - the arrows `arrowup` / `up`, `arrowdown` / `down`, `arrowleft` / `left`, `arrowright` / `right`
48
- - `esc`, `return` and `del` as aliases
49
- - **Errors:** shortcut literals are checked by TypeScript, so `hotkey("ctrl+esacpe")` fails to compile with `Unknown key "esacpe"`. Shortcuts held in a `string` variable are checked at runtime and throw a `TypeError`.
25
+ [Keyboard API](docs/keyboard.md)
50
26
 
51
- `pressed(keys, { className = "is-pressed", ignoreInputs = true })` adds a class while a shortcut is held, without triggering anything. A lone modifier such as `"mod"` or `"shift"` is a valid shortcut here, which suits key caps in a hint.
52
-
53
- `formatHint(keys)` formats shortcuts for display: `mod+s` becomes `⌘ S` on Apple devices and `Ctrl + S` elsewhere. On the server it renders the non-Apple form.
54
-
55
- Hotkeys ignore repeated keys, IME composition, focused form fields and editable elements, disabled elements, and elements inside an inert subtree. `data-keyshortcuts-ignore` on a container suppresses hotkeys while focus is inside it.
56
-
57
- ## Sound
27
+ ### Sound
58
28
 
59
29
  ```svelte
60
30
  <script lang="ts">
61
- import { sound, Sound } from "@joknoll/svelte-attach/sound";
31
+ import { sound } from "@joknoll/svelte-attach/sound";
62
32
  import click from "./click.opus";
63
- import switchOn from "./switch-on.opus";
64
- import switchOff from "./switch-off.opus";
65
-
66
- const quietClick = sound(click, { volume: 0.4 });
67
- const notification = new Sound(click);
68
33
  </script>
69
34
 
70
- <button {@attach sound(click)}>Click</button>
71
- <button {@attach quietClick}>Quiet click</button>
72
- <button onclick={() => notification.play()}>Play manually</button>
73
- <input
74
- type="checkbox"
75
- role="switch"
76
- aria-label="Sound switch"
77
- {@attach sound((input: HTMLInputElement) => (input.checked ? switchOn : switchOff), {
78
- on: "change",
79
- })}
80
- />
35
+ <button {@attach sound(click)}>Play sound</button>
81
36
  ```
82
37
 
83
- `sound(src, options?)` plays a sound when the element receives the `on` event, which defaults to `"click"`.
38
+ Sound plays on `click` by default. Set `on` to use a different event.
84
39
 
85
- - **`src`:** a URL, or `(element, event) => URL` to choose a sound when the event fires. Return `null` or `undefined` to skip playback.
86
- - **Stopping:** the `stopOn` event and attachment cleanup stop every playback the attachment started and cancel pending ones.
87
- - **Errors:** selection, load, and playback errors reach `onError`; without it they are logged.
88
- - **Other options:** `volume` (0 to 1), `loop`, and `rate` (greater than 0).
89
- - **Reuse:** one `sound(...)` result can be attached to many elements.
90
- - **Caching:** decoded audio is cached by URL across all attachments and `Sound` instances, and a failed load leaves the cache so a later play can retry.
40
+ Use sound sparingly for meaningful moments, like completing a task. Avoid playing it on every click or keystroke, and let users mute it.
91
41
 
92
- `new Sound(src, options?)` is for imperative playback.
42
+ [Sound API](docs/sound.md)
93
43
 
94
- - **`await play()`:** returns a handle that stops just that playback. It returns `null` when Web Audio is unavailable or `stop()` ran before playback started, and rejects on load errors. Calls can overlap.
95
- - **`stop()`:** stops all current playbacks and cancels pending ones.
96
- - **`preload()`:** resolves to `true` when decoding succeeds and to `false` when Web Audio is unavailable.
97
-
98
- ## Vibration
44
+ ### Vibration
99
45
 
100
46
  ```svelte
101
47
  <script lang="ts">
102
- import { haptic, triggerHaptic } from "@joknoll/svelte-attach/haptic";
48
+ import { haptic } from "@joknoll/svelte-attach/haptic";
103
49
  </script>
104
50
 
105
- <button {@attach haptic("selection", { on: "pointerdown" })}>Select</button>
106
- <button onclick={() => triggerHaptic("success")}>Saved</button>
51
+ <button {@attach haptic("light")}>Try vibration</button>
107
52
  ```
108
53
 
109
- `haptic(pattern = "medium", { on = "click" })` vibrates when the element receives the event and removes its listener on cleanup. A pattern can take three forms:
110
-
111
- - **Preset name:** `light`, `medium`, `heavy`, `soft`, `rigid`, `selection`, `success`, `warning`, `error`, `nudge`, or `buzz`.
112
- - **Single duration:** one number, in milliseconds.
113
- - **Sequence:** an array of alternating vibration and pause durations.
54
+ The button vibrates the device on click if the browser and device support vibration.
114
55
 
115
- `createPattern(input)` returns a validated copy of the duration sequence, and rejects empty, negative, or non-finite durations. `triggerHaptic(input)` and `cancelHaptic()` return the browser's success boolean, or `false` when vibration is unavailable. `cancelHaptic()` stops the device's current vibration, including one started outside this package.
56
+ Use a brief pulse to confirm a deliberate action, like snapping an item into place. Avoid buzzing during repeated actions like scrolling or typing. Keep visible feedback so the interaction works without vibration.
116
57
 
117
- The Web Vibration API controls timing, not physical intensity. Support varies by browser and device, so use vibration as an optional complement to visible feedback.
58
+ [Vibration API](docs/vibration.md)
118
59
 
119
- ## Gamepad
60
+ ### Gamepad
120
61
 
121
62
  ```svelte
122
63
  <script lang="ts">
123
64
  import { gamepadButton } from "@joknoll/svelte-attach/gamepad";
124
65
  </script>
125
66
 
126
- <button {@attach gamepadButton("A")} onclick={() => console.log("activated")}>
127
- Focus me, then press A
67
+ <button popovertarget="gamepad-help" {@attach gamepadButton("A")}>
68
+ Show controls
128
69
  </button>
129
- ```
130
-
131
- `gamepadButton(button, options?)` clicks the attached element on a new press, **only while it has focus**.
132
-
133
- - **`onTrigger(element, pad)`:** replaces the click.
134
- - **`padIndex`:** selects a gamepad slot. By default the first connected pad is used.
135
- - **Polling:** disabled elements are ignored, all attachments share one animation-frame poller, and polling stops when the last attachment is removed.
136
70
 
137
- `isButtonPressed(button, padIndex?)` reads the current state once. It returns `false` on the server, when no gamepad is connected, or when the pad does not report the standard mapping. `GamepadButtonMap` and `ButtonName` name the standard button positions:
138
-
139
- - the face buttons `A`, `B`, `X`, `Y`
140
- - the shoulders and triggers `LB`, `RB`, `LT`, `RT`
141
- - the stick presses `L3` and `R3`
142
- - the directional buttons `UP`, `DOWN`, `LEFT`, `RIGHT`
143
- - `SELECT`, `START`, and `HOME`
144
-
145
- ## Development
71
+ <div id="gamepad-help" popover>Press Escape to close.</div>
72
+ ```
146
73
 
147
- The example site lives in [`examples/website`](examples/website).
74
+ Focus the button, then press `A` on a standard-mapped gamepad to open the popover.
148
75
 
149
- ```bash
150
- vp install
151
- vp run ready
152
- vp run dev
153
- ```
76
+ [Gamepad API](docs/gamepad.md)
154
77
 
155
- `vp run ready` formats, lints, and type-checks, builds the package, runs the tests, and checks and builds the example site.
78
+ [Full documentation](docs/)
package/dist/key.d.ts CHANGED
@@ -115,7 +115,10 @@ export interface HotkeyOptions<E extends HTMLElement = HTMLElement> {
115
115
  /** Defaults to true. */
116
116
  preventDefault?: boolean;
117
117
  stopPropagation?: boolean;
118
- /** Defaults to true: shortcuts are ignored while an input, select, textarea or editable element has focus. */
118
+ /**
119
+ * Defaults to true: shortcuts are ignored while a text field, select, radio, range or editable
120
+ * element has focus. Checkboxes and buttons do not block them.
121
+ */
119
122
  ignoreInputs?: boolean;
120
123
  /** Defaults to true. */
121
124
  ignoreRepeat?: boolean;
package/dist/key.js CHANGED
@@ -197,26 +197,52 @@ function formatHint(keys) {
197
197
  return parts.join(mac ? " " : " + ");
198
198
  }).join(" / ");
199
199
  }
200
+ const PHYSICAL_KEY = /^(?:Key([A-Z])|Digit([0-9]))$/;
201
+ /** The letter or digit at this key's position on a US layout, read from `KeyboardEvent.code`. */
202
+ function physicalKey(code) {
203
+ const match = PHYSICAL_KEY.exec(code);
204
+ return (match?.[1] ?? match?.[2])?.toLowerCase();
205
+ }
206
+ function isSymbol(key) {
207
+ return key.length === 1 && key !== " " && key.toLowerCase() === key.toUpperCase();
208
+ }
200
209
  function matches(event, spec) {
201
- return eventKey(event.key) === spec.key && event.ctrlKey === spec.ctrl && event.shiftKey === spec.shift && event.altKey === spec.alt && event.metaKey === spec.meta;
210
+ if (event.metaKey !== spec.meta) return false;
211
+ const typed = eventKey(event.key);
212
+ if (typed === spec.key && isSymbol(typed)) {
213
+ const altGraph = event.getModifierState("AltGraph");
214
+ const altTypes = altGraph || isMac();
215
+ return (event.ctrlKey && !altGraph) === spec.ctrl && (!spec.shift || event.shiftKey) && (spec.alt ? event.altKey : altTypes || !event.altKey);
216
+ }
217
+ if (event.ctrlKey !== spec.ctrl || event.shiftKey !== spec.shift || event.altKey !== spec.alt) return false;
218
+ if (typed === spec.key) return true;
219
+ return !/^[a-z0-9]$/.test(typed) && physicalKey(event.code) === spec.key;
202
220
  }
203
221
  /** True when releasing this key ends the shortcut: its key or any of its modifiers. */
204
222
  function releases(event, spec) {
205
- const key = eventKey(event.key);
206
- return key === spec.key || isModifierKey(key) && spec[key];
223
+ const typed = eventKey(event.key);
224
+ if (isModifierKey(typed)) return typed === spec.key || spec[typed];
225
+ return typed === spec.key || physicalKey(event.code) === spec.key;
207
226
  }
208
227
  //#endregion
209
228
  //#region src/key/dispatcher.ts
210
- const IGNORED_TAGS = /* @__PURE__ */ new Set([
211
- "INPUT",
212
- "TEXTAREA",
213
- "SELECT"
229
+ const NON_TEXT_INPUTS = /* @__PURE__ */ new Set([
230
+ "checkbox",
231
+ "button",
232
+ "submit",
233
+ "reset",
234
+ "image",
235
+ "color",
236
+ "file"
214
237
  ]);
215
238
  const registrations = /* @__PURE__ */ new Set();
216
239
  let stopListener = null;
217
240
  function isTyping(event) {
218
- const target = event.target;
219
- return target instanceof HTMLElement && (IGNORED_TAGS.has(target.tagName) || target.isContentEditable);
241
+ const target = event.composedPath()[0];
242
+ if (!(target instanceof HTMLElement)) return false;
243
+ if (target.isContentEditable) return true;
244
+ if (target instanceof HTMLInputElement) return !NON_TEXT_INPUTS.has(target.type);
245
+ return target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement;
220
246
  }
221
247
  function inIgnoreZone(event) {
222
248
  const target = event.target;
@@ -229,7 +255,7 @@ function inIgnoreZone(event) {
229
255
  return false;
230
256
  }
231
257
  function handleKeydown(event) {
232
- if (event.isComposing || event.key === "Dead") return;
258
+ if (event.isComposing || event.key === "Dead" && !event.altKey) return;
233
259
  const ignoreZone = inIgnoreZone(event);
234
260
  const eligible = (reg) => {
235
261
  if (reg.ignoreRepeat && event.repeat) return false;
@@ -259,17 +285,17 @@ function register(reg) {
259
285
  //#endregion
260
286
  //#region src/key/index.ts
261
287
  function trackHeld(element, className) {
262
- const active = /* @__PURE__ */ new Set();
288
+ const active = /* @__PURE__ */ new Map();
263
289
  const release = (event) => {
264
290
  if (active.size === 0) return;
265
- for (const shortcut of active) if (!event || releases(event, shortcut)) active.delete(shortcut);
291
+ for (const [shortcut, code] of active) if (!event || code !== "" && event.code === code || releases(event, shortcut)) active.delete(shortcut);
266
292
  if (active.size === 0) element.classList.remove(className);
267
293
  };
268
294
  const offUp = on(window, "keyup", release);
269
295
  const offBlur = on(window, "blur", () => release());
270
296
  return {
271
297
  press(event, shortcuts) {
272
- for (const shortcut of shortcuts) if (matches(event, shortcut)) active.add(shortcut);
298
+ for (const shortcut of shortcuts) if (matches(event, shortcut)) active.set(shortcut, event.code);
273
299
  element.classList.add(className);
274
300
  },
275
301
  stop() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joknoll/svelte-attach",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Svelte 5 attachments for keyboard shortcuts, sound effects, vibration, and gamepad buttons.",
5
5
  "keywords": [
6
6
  "attachment",
@@ -75,7 +75,7 @@
75
75
  "scripts": {
76
76
  "build": "vp pack",
77
77
  "test": "vp test",
78
- "ready": "vp check && vp run build && vp test && vp run website#check && vp run website#build",
79
- "dev": "vp run website#dev"
78
+ "ready": "vp check && vp run build && vp test && vp run example#check && vp run example#build",
79
+ "dev": "vp run example#dev"
80
80
  }
81
81
  }