@joknoll/svelte-attach 0.0.0-stage → 0.3.0
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/LICENSE +21 -0
- package/README.md +154 -2
- package/dist/gamepad.d.ts +44 -0
- package/dist/gamepad.js +83 -0
- package/dist/haptic.d.ts +41 -0
- package/dist/haptic.js +70 -0
- package/dist/key.d.ts +147 -0
- package/dist/key.js +347 -0
- package/dist/sound.d.ts +52 -0
- package/dist/sound.js +147 -0
- package/package.json +78 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Johannes Knoll
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,155 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @joknoll/svelte-attach
|
|
2
2
|
|
|
3
|
-
|
|
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.
|
|
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 |
|
|
15
|
+
|
|
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.
|
|
17
|
+
|
|
18
|
+
## Keyboard shortcuts
|
|
19
|
+
|
|
20
|
+
```svelte
|
|
21
|
+
<script lang="ts">
|
|
22
|
+
import { hotkey, pressed, formatHint } from "@joknoll/svelte-attach/key";
|
|
23
|
+
</script>
|
|
24
|
+
|
|
25
|
+
<button title={formatHint("mod+k")} {@attach hotkey("mod+k", { pressedClass: "is-pressed" })}>
|
|
26
|
+
Open command menu
|
|
27
|
+
</button>
|
|
28
|
+
|
|
29
|
+
<kbd {@attach pressed("shift")}>Shift</kbd>
|
|
30
|
+
```
|
|
31
|
+
|
|
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"]`.
|
|
41
|
+
|
|
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`.
|
|
50
|
+
|
|
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
|
|
58
|
+
|
|
59
|
+
```svelte
|
|
60
|
+
<script lang="ts">
|
|
61
|
+
import { sound, Sound } from "@joknoll/svelte-attach/sound";
|
|
62
|
+
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
|
+
</script>
|
|
69
|
+
|
|
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
|
+
/>
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`sound(src, options?)` plays a sound when the element receives the `on` event, which defaults to `"click"`.
|
|
84
|
+
|
|
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.
|
|
91
|
+
|
|
92
|
+
`new Sound(src, options?)` is for imperative playback.
|
|
93
|
+
|
|
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
|
|
99
|
+
|
|
100
|
+
```svelte
|
|
101
|
+
<script lang="ts">
|
|
102
|
+
import { haptic, triggerHaptic } from "@joknoll/svelte-attach/haptic";
|
|
103
|
+
</script>
|
|
104
|
+
|
|
105
|
+
<button {@attach haptic("selection", { on: "pointerdown" })}>Select</button>
|
|
106
|
+
<button onclick={() => triggerHaptic("success")}>Saved</button>
|
|
107
|
+
```
|
|
108
|
+
|
|
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.
|
|
114
|
+
|
|
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.
|
|
116
|
+
|
|
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.
|
|
118
|
+
|
|
119
|
+
## Gamepad
|
|
120
|
+
|
|
121
|
+
```svelte
|
|
122
|
+
<script lang="ts">
|
|
123
|
+
import { gamepadButton } from "@joknoll/svelte-attach/gamepad";
|
|
124
|
+
</script>
|
|
125
|
+
|
|
126
|
+
<button {@attach gamepadButton("A")} onclick={() => console.log("activated")}>
|
|
127
|
+
Focus me, then press A
|
|
128
|
+
</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
|
+
|
|
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
|
|
146
|
+
|
|
147
|
+
The example site lives in [`examples/website`](examples/website).
|
|
148
|
+
|
|
149
|
+
```bash
|
|
150
|
+
vp install
|
|
151
|
+
vp run ready
|
|
152
|
+
vp run dev
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
`vp run ready` formats, lints, and type-checks, builds the package, runs the tests, and checks and builds the example site.
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { Attachment } from "svelte/attachments";
|
|
2
|
+
//#region src/gamepad.d.ts
|
|
3
|
+
/** CONTRACT: Standard Gamepad API indices denote physical button positions. */
|
|
4
|
+
export declare const GamepadButtonMap: {
|
|
5
|
+
readonly A: 0;
|
|
6
|
+
readonly B: 1;
|
|
7
|
+
readonly X: 2;
|
|
8
|
+
readonly Y: 3;
|
|
9
|
+
readonly LB: 4;
|
|
10
|
+
readonly RB: 5;
|
|
11
|
+
readonly LT: 6;
|
|
12
|
+
readonly RT: 7;
|
|
13
|
+
readonly SELECT: 8;
|
|
14
|
+
readonly START: 9;
|
|
15
|
+
readonly L3: 10;
|
|
16
|
+
readonly R3: 11;
|
|
17
|
+
readonly UP: 12;
|
|
18
|
+
readonly DOWN: 13;
|
|
19
|
+
readonly LEFT: 14;
|
|
20
|
+
readonly RIGHT: 15;
|
|
21
|
+
readonly HOME: 16;
|
|
22
|
+
};
|
|
23
|
+
export type ButtonName = keyof typeof GamepadButtonMap;
|
|
24
|
+
export interface GamepadButtonOptions<E extends HTMLElement = HTMLElement> {
|
|
25
|
+
/** Replaces the default `element.click()`. */
|
|
26
|
+
onTrigger?: (element: E, pad: Gamepad) => void;
|
|
27
|
+
/** Gamepad slot to read. Defaults to the first occupied slot. */
|
|
28
|
+
padIndex?: number;
|
|
29
|
+
}
|
|
30
|
+
/** API availability only. Permissions Policy can still block access. */
|
|
31
|
+
export declare function isSupported(): boolean;
|
|
32
|
+
/** Uses the first occupied slot by default and returns false for a nonstandard mapping. */
|
|
33
|
+
export declare function isButtonPressed(button: ButtonName, padIndex?: number): boolean;
|
|
34
|
+
/**
|
|
35
|
+
* Clicks the element, or calls `onTrigger`, when a standard gamepad button is newly pressed
|
|
36
|
+
* while the element itself has focus.
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```svelte
|
|
40
|
+
* <button {@attach gamepadButton("A")} onclick={confirm}>Confirm</button>
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
export declare function gamepadButton<E extends HTMLElement = HTMLElement>(button: ButtonName, options?: GamepadButtonOptions<E>): Attachment<E>;
|
|
44
|
+
//#endregion
|
package/dist/gamepad.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
//#region src/gamepad.ts
|
|
2
|
+
/** CONTRACT: Standard Gamepad API indices denote physical button positions. */
|
|
3
|
+
const GamepadButtonMap = {
|
|
4
|
+
A: 0,
|
|
5
|
+
B: 1,
|
|
6
|
+
X: 2,
|
|
7
|
+
Y: 3,
|
|
8
|
+
LB: 4,
|
|
9
|
+
RB: 5,
|
|
10
|
+
LT: 6,
|
|
11
|
+
RT: 7,
|
|
12
|
+
SELECT: 8,
|
|
13
|
+
START: 9,
|
|
14
|
+
L3: 10,
|
|
15
|
+
R3: 11,
|
|
16
|
+
UP: 12,
|
|
17
|
+
DOWN: 13,
|
|
18
|
+
LEFT: 14,
|
|
19
|
+
RIGHT: 15,
|
|
20
|
+
HOME: 16
|
|
21
|
+
};
|
|
22
|
+
const registrations = /* @__PURE__ */ new Set();
|
|
23
|
+
let frame = 0;
|
|
24
|
+
/** API availability only. Permissions Policy can still block access. */
|
|
25
|
+
function isSupported() {
|
|
26
|
+
return typeof navigator !== "undefined" && typeof navigator.getGamepads === "function";
|
|
27
|
+
}
|
|
28
|
+
function connectedPad(pads, index) {
|
|
29
|
+
const pad = index === void 0 ? pads.find((entry) => entry !== null) : pads[index];
|
|
30
|
+
return pad?.mapping === "standard" ? pad : null;
|
|
31
|
+
}
|
|
32
|
+
/** Uses the first occupied slot by default and returns false for a nonstandard mapping. */
|
|
33
|
+
function isButtonPressed(button, padIndex) {
|
|
34
|
+
if (!isSupported()) return false;
|
|
35
|
+
return connectedPad(navigator.getGamepads(), padIndex)?.buttons[GamepadButtonMap[button]]?.pressed ?? false;
|
|
36
|
+
}
|
|
37
|
+
function poll() {
|
|
38
|
+
try {
|
|
39
|
+
const pads = navigator.getGamepads();
|
|
40
|
+
for (const registration of registrations) {
|
|
41
|
+
const { element, button, trigger, padIndex } = registration;
|
|
42
|
+
const pad = connectedPad(pads, padIndex);
|
|
43
|
+
const pressed = pad?.buttons[GamepadButtonMap[button]]?.pressed ?? false;
|
|
44
|
+
const newlyPressed = pressed && !registration.pressed;
|
|
45
|
+
registration.pressed = pressed;
|
|
46
|
+
if (newlyPressed && pad && document.visibilityState !== "hidden" && element.isConnected && element === document.activeElement && !element.matches(":disabled") && !element.closest("[inert]")) trigger(pad);
|
|
47
|
+
}
|
|
48
|
+
} finally {
|
|
49
|
+
frame = registrations.size > 0 ? requestAnimationFrame(poll) : 0;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Clicks the element, or calls `onTrigger`, when a standard gamepad button is newly pressed
|
|
54
|
+
* while the element itself has focus.
|
|
55
|
+
*
|
|
56
|
+
* @example
|
|
57
|
+
* ```svelte
|
|
58
|
+
* <button {@attach gamepadButton("A")} onclick={confirm}>Confirm</button>
|
|
59
|
+
* ```
|
|
60
|
+
*/
|
|
61
|
+
function gamepadButton(button, options = {}) {
|
|
62
|
+
if (!Object.hasOwn(GamepadButtonMap, button)) throw new RangeError(`Unknown gamepad button: ${String(button)}`);
|
|
63
|
+
const { onTrigger, padIndex } = options;
|
|
64
|
+
if (padIndex !== void 0 && (!Number.isInteger(padIndex) || padIndex < 0)) throw new RangeError("Gamepad padIndex must be a non-negative integer.");
|
|
65
|
+
return (element) => {
|
|
66
|
+
if (!isSupported() || typeof requestAnimationFrame !== "function") return;
|
|
67
|
+
const registration = {
|
|
68
|
+
element,
|
|
69
|
+
button,
|
|
70
|
+
trigger: (pad) => onTrigger ? onTrigger(element, pad) : element.click(),
|
|
71
|
+
padIndex,
|
|
72
|
+
pressed: false
|
|
73
|
+
};
|
|
74
|
+
registrations.add(registration);
|
|
75
|
+
if (registrations.size === 1) frame = requestAnimationFrame(poll);
|
|
76
|
+
return () => {
|
|
77
|
+
registrations.delete(registration);
|
|
78
|
+
if (registrations.size === 0) cancelAnimationFrame(frame);
|
|
79
|
+
};
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
//#endregion
|
|
83
|
+
export { GamepadButtonMap, gamepadButton, isButtonPressed, isSupported };
|
package/dist/haptic.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { Attachment } from "svelte/attachments";
|
|
2
|
+
//#region src/haptic.d.ts
|
|
3
|
+
/** CONTRACT: Entries alternate vibration and pause durations in milliseconds, starting with vibration. */
|
|
4
|
+
export declare const patterns: {
|
|
5
|
+
readonly light: readonly [10];
|
|
6
|
+
readonly medium: readonly [25];
|
|
7
|
+
readonly heavy: readonly [45];
|
|
8
|
+
readonly soft: readonly [35];
|
|
9
|
+
readonly rigid: readonly [12];
|
|
10
|
+
readonly selection: readonly [8];
|
|
11
|
+
readonly success: readonly [25, 60, 40];
|
|
12
|
+
readonly warning: readonly [35, 70, 35];
|
|
13
|
+
readonly error: readonly [35, 35, 35, 35, 35];
|
|
14
|
+
readonly nudge: readonly [50, 60, 30];
|
|
15
|
+
readonly buzz: readonly [300];
|
|
16
|
+
};
|
|
17
|
+
export type HapticPreset = keyof typeof patterns;
|
|
18
|
+
export type HapticPattern = HapticPreset | number | readonly number[];
|
|
19
|
+
export interface HapticOptions {
|
|
20
|
+
/** Event that triggers the vibration. Defaults to `"click"`. */
|
|
21
|
+
on?: keyof HTMLElementEventMap;
|
|
22
|
+
}
|
|
23
|
+
/** Whether `navigator.vibrate` exists. The browser can still decline a request. */
|
|
24
|
+
export declare function isSupported(): boolean;
|
|
25
|
+
/** Returns a mutable copy. Empty patterns and negative or non-finite durations throw a RangeError. */
|
|
26
|
+
export declare function createPattern(input?: HapticPattern): number[];
|
|
27
|
+
/** For valid patterns, false means the API is unavailable or the browser declined the request. */
|
|
28
|
+
export declare function triggerHaptic(input?: HapticPattern): boolean;
|
|
29
|
+
/** Requests cancellation of the current browser vibration, including requests made outside this package. */
|
|
30
|
+
export declare function cancelHaptic(): boolean;
|
|
31
|
+
/**
|
|
32
|
+
* Vibrates when the element receives `on` (default `"click"`). Detaching lets an ongoing
|
|
33
|
+
* vibration finish because cancellation would affect other callers.
|
|
34
|
+
*
|
|
35
|
+
* @example
|
|
36
|
+
* ```svelte
|
|
37
|
+
* <button {@attach haptic("selection", { on: "pointerdown" })}>Select</button>
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
export declare function haptic(pattern?: HapticPattern, options?: HapticOptions): Attachment<HTMLElement>;
|
|
41
|
+
//#endregion
|
package/dist/haptic.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { on } from "svelte/events";
|
|
2
|
+
//#region src/haptic.ts
|
|
3
|
+
/** CONTRACT: Entries alternate vibration and pause durations in milliseconds, starting with vibration. */
|
|
4
|
+
const patterns = {
|
|
5
|
+
light: [10],
|
|
6
|
+
medium: [25],
|
|
7
|
+
heavy: [45],
|
|
8
|
+
soft: [35],
|
|
9
|
+
rigid: [12],
|
|
10
|
+
selection: [8],
|
|
11
|
+
success: [
|
|
12
|
+
25,
|
|
13
|
+
60,
|
|
14
|
+
40
|
|
15
|
+
],
|
|
16
|
+
warning: [
|
|
17
|
+
35,
|
|
18
|
+
70,
|
|
19
|
+
35
|
|
20
|
+
],
|
|
21
|
+
error: [
|
|
22
|
+
35,
|
|
23
|
+
35,
|
|
24
|
+
35,
|
|
25
|
+
35,
|
|
26
|
+
35
|
|
27
|
+
],
|
|
28
|
+
nudge: [
|
|
29
|
+
50,
|
|
30
|
+
60,
|
|
31
|
+
30
|
|
32
|
+
],
|
|
33
|
+
buzz: [300]
|
|
34
|
+
};
|
|
35
|
+
/** Whether `navigator.vibrate` exists. The browser can still decline a request. */
|
|
36
|
+
function isSupported() {
|
|
37
|
+
return typeof navigator !== "undefined" && typeof navigator.vibrate === "function";
|
|
38
|
+
}
|
|
39
|
+
/** Returns a mutable copy. Empty patterns and negative or non-finite durations throw a RangeError. */
|
|
40
|
+
function createPattern(input = "medium") {
|
|
41
|
+
const values = typeof input === "string" ? patterns[input] : typeof input === "number" ? [input] : input;
|
|
42
|
+
if (!values || values.length === 0) throw new RangeError("A haptic pattern must contain at least one duration.");
|
|
43
|
+
for (const duration of values) if (!Number.isFinite(duration) || duration < 0) throw new RangeError("Haptic durations must be finite, non-negative numbers.");
|
|
44
|
+
return [...values];
|
|
45
|
+
}
|
|
46
|
+
/** For valid patterns, false means the API is unavailable or the browser declined the request. */
|
|
47
|
+
function triggerHaptic(input = "medium") {
|
|
48
|
+
const pattern = createPattern(input);
|
|
49
|
+
return isSupported() ? navigator.vibrate(pattern) : false;
|
|
50
|
+
}
|
|
51
|
+
/** Requests cancellation of the current browser vibration, including requests made outside this package. */
|
|
52
|
+
function cancelHaptic() {
|
|
53
|
+
return isSupported() ? navigator.vibrate(0) : false;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Vibrates when the element receives `on` (default `"click"`). Detaching lets an ongoing
|
|
57
|
+
* vibration finish because cancellation would affect other callers.
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* ```svelte
|
|
61
|
+
* <button {@attach haptic("selection", { on: "pointerdown" })}>Select</button>
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
function haptic(pattern = "medium", options = {}) {
|
|
65
|
+
const durations = createPattern(pattern);
|
|
66
|
+
const event = options.on ?? "click";
|
|
67
|
+
return (element) => on(element, event, () => triggerHaptic(durations));
|
|
68
|
+
}
|
|
69
|
+
//#endregion
|
|
70
|
+
export { cancelHaptic, createPattern, haptic, isSupported, patterns, triggerHaptic };
|
package/dist/key.d.ts
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { Attachment } from "svelte/attachments";
|
|
2
|
+
//#region src/key/shortcut.d.ts
|
|
3
|
+
declare const MODIFIERS: {
|
|
4
|
+
readonly ctrl: "ctrl";
|
|
5
|
+
readonly control: "ctrl";
|
|
6
|
+
readonly shift: "shift";
|
|
7
|
+
readonly alt: "alt";
|
|
8
|
+
readonly option: "alt";
|
|
9
|
+
readonly meta: "meta";
|
|
10
|
+
readonly cmd: "meta";
|
|
11
|
+
readonly command: "meta";
|
|
12
|
+
readonly win: "meta";
|
|
13
|
+
readonly mod: "mod";
|
|
14
|
+
};
|
|
15
|
+
declare const NAMED_KEYS: {
|
|
16
|
+
readonly escape: {
|
|
17
|
+
readonly aria: "Escape";
|
|
18
|
+
readonly label: "Esc";
|
|
19
|
+
};
|
|
20
|
+
readonly enter: {
|
|
21
|
+
readonly aria: "Enter";
|
|
22
|
+
readonly label: "Enter";
|
|
23
|
+
};
|
|
24
|
+
readonly tab: {
|
|
25
|
+
readonly aria: "Tab";
|
|
26
|
+
readonly label: "Tab";
|
|
27
|
+
};
|
|
28
|
+
readonly " ": {
|
|
29
|
+
readonly aria: "Space";
|
|
30
|
+
readonly label: "Space";
|
|
31
|
+
};
|
|
32
|
+
readonly "+": {
|
|
33
|
+
readonly aria: "Plus";
|
|
34
|
+
readonly label: "+";
|
|
35
|
+
};
|
|
36
|
+
readonly backspace: {
|
|
37
|
+
readonly aria: "Backspace";
|
|
38
|
+
readonly label: "Backspace";
|
|
39
|
+
};
|
|
40
|
+
readonly delete: {
|
|
41
|
+
readonly aria: "Delete";
|
|
42
|
+
readonly label: "Delete";
|
|
43
|
+
};
|
|
44
|
+
readonly insert: {
|
|
45
|
+
readonly aria: "Insert";
|
|
46
|
+
readonly label: "Insert";
|
|
47
|
+
};
|
|
48
|
+
readonly home: {
|
|
49
|
+
readonly aria: "Home";
|
|
50
|
+
readonly label: "Home";
|
|
51
|
+
};
|
|
52
|
+
readonly end: {
|
|
53
|
+
readonly aria: "End";
|
|
54
|
+
readonly label: "End";
|
|
55
|
+
};
|
|
56
|
+
readonly pageup: {
|
|
57
|
+
readonly aria: "PageUp";
|
|
58
|
+
readonly label: "PageUp";
|
|
59
|
+
};
|
|
60
|
+
readonly pagedown: {
|
|
61
|
+
readonly aria: "PageDown";
|
|
62
|
+
readonly label: "PageDown";
|
|
63
|
+
};
|
|
64
|
+
readonly arrowup: {
|
|
65
|
+
readonly aria: "ArrowUp";
|
|
66
|
+
readonly label: "Up";
|
|
67
|
+
};
|
|
68
|
+
readonly arrowdown: {
|
|
69
|
+
readonly aria: "ArrowDown";
|
|
70
|
+
readonly label: "Down";
|
|
71
|
+
};
|
|
72
|
+
readonly arrowleft: {
|
|
73
|
+
readonly aria: "ArrowLeft";
|
|
74
|
+
readonly label: "Left";
|
|
75
|
+
};
|
|
76
|
+
readonly arrowright: {
|
|
77
|
+
readonly aria: "ArrowRight";
|
|
78
|
+
readonly label: "Right";
|
|
79
|
+
};
|
|
80
|
+
};
|
|
81
|
+
declare const KEY_ALIASES: {
|
|
82
|
+
readonly space: " ";
|
|
83
|
+
readonly plus: "+";
|
|
84
|
+
readonly esc: "escape";
|
|
85
|
+
readonly return: "enter";
|
|
86
|
+
readonly del: "delete";
|
|
87
|
+
readonly up: "arrowup";
|
|
88
|
+
readonly down: "arrowdown";
|
|
89
|
+
readonly left: "arrowleft";
|
|
90
|
+
readonly right: "arrowright";
|
|
91
|
+
};
|
|
92
|
+
type NamedKey = Exclude<keyof typeof NAMED_KEYS, " " | "+"> | keyof typeof KEY_ALIASES;
|
|
93
|
+
type FunctionKey = `f${1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12}`;
|
|
94
|
+
type IsCharacter<S extends string> = S extends `${infer First}${infer Rest}` ? Rest extends "" ? First extends " " | "+" ? false : true : false : false;
|
|
95
|
+
type IsModifier<S extends string> = Lowercase<S> extends keyof typeof MODIFIERS ? true : false;
|
|
96
|
+
type IsKey<S extends string> = Lowercase<S> extends NamedKey | FunctionKey ? true : IsCharacter<S>;
|
|
97
|
+
type CheckParts<Whole extends string, Rest extends string> = Rest extends `${infer Part}+${infer Tail}` ? IsModifier<Part> extends true ? CheckParts<Whole, Tail> : Part extends "" ? `Empty part in "${Whole}"; write + as "plus"` : `"${Part}" in "${Whole}" is not a modifier; the key goes last` : IsKey<Rest> extends true ? Whole : IsModifier<Rest> extends true ? Whole : Rest extends "" ? `Shortcut "${Whole}" is missing a key` : `Unknown key "${Rest}" in "${Whole}"`;
|
|
98
|
+
/**
|
|
99
|
+
* Resolves to `S` for a valid shortcut literal and to an error message otherwise.
|
|
100
|
+
* A plain `string` passes and is validated at runtime instead.
|
|
101
|
+
*/
|
|
102
|
+
type Shortcut<S extends string> = S extends unknown ? string extends S ? S : CheckParts<S, S> : never;
|
|
103
|
+
/**
|
|
104
|
+
* Displays `mod+s` as `⌘ S` on Apple devices and `Ctrl + S` elsewhere, and joins alternatives
|
|
105
|
+
* with ` / `. Throws a `TypeError` for a malformed shortcut.
|
|
106
|
+
*/
|
|
107
|
+
export declare function formatHint<const S extends string>(keys: Shortcut<S> | readonly Shortcut<S>[]): string;
|
|
108
|
+
//#endregion
|
|
109
|
+
//#region src/key/index.d.ts
|
|
110
|
+
export interface HotkeyOptions<E extends HTMLElement = HTMLElement> {
|
|
111
|
+
/** Replaces the default `element.click()`. */
|
|
112
|
+
onTrigger?: (element: E, event: KeyboardEvent) => void;
|
|
113
|
+
/** Added when this hotkey fires and removed when the shortcut is released. */
|
|
114
|
+
pressedClass?: string;
|
|
115
|
+
/** Defaults to true. */
|
|
116
|
+
preventDefault?: boolean;
|
|
117
|
+
stopPropagation?: boolean;
|
|
118
|
+
/** Defaults to true: shortcuts are ignored while an input, select, textarea or editable element has focus. */
|
|
119
|
+
ignoreInputs?: boolean;
|
|
120
|
+
/** Defaults to true. */
|
|
121
|
+
ignoreRepeat?: boolean;
|
|
122
|
+
}
|
|
123
|
+
export interface PressedOptions {
|
|
124
|
+
/** Defaults to `"is-pressed"`. */
|
|
125
|
+
className?: string;
|
|
126
|
+
/** Defaults to true. */
|
|
127
|
+
ignoreInputs?: boolean;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Clicks the element, or calls `onTrigger`, when a shortcut is pressed anywhere on the page.
|
|
131
|
+
* When several attached elements share a shortcut, the most recently attached eligible one runs.
|
|
132
|
+
* Sets `aria-keyshortcuts` and restores the previous value on detach.
|
|
133
|
+
*
|
|
134
|
+
* @example
|
|
135
|
+
* ```svelte
|
|
136
|
+
* <button {@attach hotkey("mod+s", { pressedClass: "active" })} onclick={save}>Save</button>
|
|
137
|
+
* ```
|
|
138
|
+
*/
|
|
139
|
+
export declare function hotkey<const S extends string, E extends HTMLElement = HTMLElement>(keys: Shortcut<S> | readonly Shortcut<S>[], options?: HotkeyOptions<E>): Attachment<E>;
|
|
140
|
+
/**
|
|
141
|
+
* Adds a class while a shortcut is held, without triggering anything. A lone modifier such as
|
|
142
|
+
* `"mod"` or `"shift"` is a valid shortcut here. Use `hotkey`'s `pressedClass` for elements
|
|
143
|
+
* that also activate.
|
|
144
|
+
*/
|
|
145
|
+
export declare function pressed<const S extends string>(keys: Shortcut<S> | readonly Shortcut<S>[], options?: PressedOptions): Attachment<HTMLElement>;
|
|
146
|
+
//#endregion
|
|
147
|
+
export type { Shortcut };
|
package/dist/key.js
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
import { on } from "svelte/events";
|
|
2
|
+
//#region src/key/shortcut.ts
|
|
3
|
+
const MODIFIERS = {
|
|
4
|
+
ctrl: "ctrl",
|
|
5
|
+
control: "ctrl",
|
|
6
|
+
shift: "shift",
|
|
7
|
+
alt: "alt",
|
|
8
|
+
option: "alt",
|
|
9
|
+
meta: "meta",
|
|
10
|
+
cmd: "meta",
|
|
11
|
+
command: "meta",
|
|
12
|
+
win: "meta",
|
|
13
|
+
mod: "mod"
|
|
14
|
+
};
|
|
15
|
+
const NAMED_KEYS = {
|
|
16
|
+
escape: {
|
|
17
|
+
aria: "Escape",
|
|
18
|
+
label: "Esc"
|
|
19
|
+
},
|
|
20
|
+
enter: {
|
|
21
|
+
aria: "Enter",
|
|
22
|
+
label: "Enter"
|
|
23
|
+
},
|
|
24
|
+
tab: {
|
|
25
|
+
aria: "Tab",
|
|
26
|
+
label: "Tab"
|
|
27
|
+
},
|
|
28
|
+
" ": {
|
|
29
|
+
aria: "Space",
|
|
30
|
+
label: "Space"
|
|
31
|
+
},
|
|
32
|
+
"+": {
|
|
33
|
+
aria: "Plus",
|
|
34
|
+
label: "+"
|
|
35
|
+
},
|
|
36
|
+
backspace: {
|
|
37
|
+
aria: "Backspace",
|
|
38
|
+
label: "Backspace"
|
|
39
|
+
},
|
|
40
|
+
delete: {
|
|
41
|
+
aria: "Delete",
|
|
42
|
+
label: "Delete"
|
|
43
|
+
},
|
|
44
|
+
insert: {
|
|
45
|
+
aria: "Insert",
|
|
46
|
+
label: "Insert"
|
|
47
|
+
},
|
|
48
|
+
home: {
|
|
49
|
+
aria: "Home",
|
|
50
|
+
label: "Home"
|
|
51
|
+
},
|
|
52
|
+
end: {
|
|
53
|
+
aria: "End",
|
|
54
|
+
label: "End"
|
|
55
|
+
},
|
|
56
|
+
pageup: {
|
|
57
|
+
aria: "PageUp",
|
|
58
|
+
label: "PageUp"
|
|
59
|
+
},
|
|
60
|
+
pagedown: {
|
|
61
|
+
aria: "PageDown",
|
|
62
|
+
label: "PageDown"
|
|
63
|
+
},
|
|
64
|
+
arrowup: {
|
|
65
|
+
aria: "ArrowUp",
|
|
66
|
+
label: "Up"
|
|
67
|
+
},
|
|
68
|
+
arrowdown: {
|
|
69
|
+
aria: "ArrowDown",
|
|
70
|
+
label: "Down"
|
|
71
|
+
},
|
|
72
|
+
arrowleft: {
|
|
73
|
+
aria: "ArrowLeft",
|
|
74
|
+
label: "Left"
|
|
75
|
+
},
|
|
76
|
+
arrowright: {
|
|
77
|
+
aria: "ArrowRight",
|
|
78
|
+
label: "Right"
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
const KEY_ALIASES = {
|
|
82
|
+
space: " ",
|
|
83
|
+
plus: "+",
|
|
84
|
+
esc: "escape",
|
|
85
|
+
return: "enter",
|
|
86
|
+
del: "delete",
|
|
87
|
+
up: "arrowup",
|
|
88
|
+
down: "arrowdown",
|
|
89
|
+
left: "arrowleft",
|
|
90
|
+
right: "arrowright"
|
|
91
|
+
};
|
|
92
|
+
const MODIFIER_LABELS = {
|
|
93
|
+
ctrl: {
|
|
94
|
+
aria: "Control",
|
|
95
|
+
mac: "⌃",
|
|
96
|
+
other: "Ctrl"
|
|
97
|
+
},
|
|
98
|
+
shift: {
|
|
99
|
+
aria: "Shift",
|
|
100
|
+
mac: "⇧",
|
|
101
|
+
other: "Shift"
|
|
102
|
+
},
|
|
103
|
+
alt: {
|
|
104
|
+
aria: "Alt",
|
|
105
|
+
mac: "⌥",
|
|
106
|
+
other: "Alt"
|
|
107
|
+
},
|
|
108
|
+
meta: {
|
|
109
|
+
aria: "Meta",
|
|
110
|
+
mac: "⌘",
|
|
111
|
+
other: "Win"
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
const MODIFIER_ORDER = [
|
|
115
|
+
"ctrl",
|
|
116
|
+
"shift",
|
|
117
|
+
"alt",
|
|
118
|
+
"meta"
|
|
119
|
+
];
|
|
120
|
+
const FUNCTION_KEY = /^f([1-9]|1[0-2])$/;
|
|
121
|
+
function isMac() {
|
|
122
|
+
return typeof navigator !== "undefined" && /Mac|iPod|iPhone|iPad/.test(navigator.userAgent);
|
|
123
|
+
}
|
|
124
|
+
function own(table, key) {
|
|
125
|
+
return Object.hasOwn(table, key);
|
|
126
|
+
}
|
|
127
|
+
function resolveModifier(name) {
|
|
128
|
+
if (!own(MODIFIERS, name)) return void 0;
|
|
129
|
+
const modifier = MODIFIERS[name];
|
|
130
|
+
if (modifier !== "mod") return modifier;
|
|
131
|
+
return isMac() ? "meta" : "ctrl";
|
|
132
|
+
}
|
|
133
|
+
/** Maps `KeyboardEvent.key` to the stored form, so `Control` and `ctrl` compare equal. */
|
|
134
|
+
function eventKey(key) {
|
|
135
|
+
const lower = key.toLowerCase();
|
|
136
|
+
return own(MODIFIERS, lower) ? resolveModifier(lower) ?? lower : lower;
|
|
137
|
+
}
|
|
138
|
+
function resolveKey(name) {
|
|
139
|
+
if (own(KEY_ALIASES, name)) return KEY_ALIASES[name];
|
|
140
|
+
if (own(NAMED_KEYS, name)) return name;
|
|
141
|
+
if (FUNCTION_KEY.test(name)) return name;
|
|
142
|
+
if (name.length === 1) return name;
|
|
143
|
+
}
|
|
144
|
+
function parseShortcut(input) {
|
|
145
|
+
const parts = input.split("+").map((part) => part.trim().toLowerCase());
|
|
146
|
+
if (parts.some((part) => !part)) throw new TypeError(`Empty part in "${input}"; write + as "plus"`);
|
|
147
|
+
const spec = {
|
|
148
|
+
key: "",
|
|
149
|
+
ctrl: false,
|
|
150
|
+
shift: false,
|
|
151
|
+
alt: false,
|
|
152
|
+
meta: false
|
|
153
|
+
};
|
|
154
|
+
const last = parts.length - 1;
|
|
155
|
+
for (const [index, part] of parts.entries()) {
|
|
156
|
+
const modifier = resolveModifier(part);
|
|
157
|
+
if (modifier) {
|
|
158
|
+
spec[modifier] = true;
|
|
159
|
+
if (index === last) spec.key = modifier;
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
if (index !== last) throw new TypeError(`"${part}" in "${input}" is not a modifier; the key goes last`);
|
|
163
|
+
const key = resolveKey(part);
|
|
164
|
+
if (!key) throw new TypeError(`Unknown key "${part}" in "${input}"`);
|
|
165
|
+
spec.key = key;
|
|
166
|
+
}
|
|
167
|
+
return spec;
|
|
168
|
+
}
|
|
169
|
+
function parseShortcuts(keys) {
|
|
170
|
+
const list = typeof keys === "string" ? [keys] : keys;
|
|
171
|
+
if (list.length === 0) throw new TypeError("At least one shortcut is required.");
|
|
172
|
+
return list.map(parseShortcut);
|
|
173
|
+
}
|
|
174
|
+
function isModifierKey(key) {
|
|
175
|
+
return MODIFIER_ORDER.includes(key);
|
|
176
|
+
}
|
|
177
|
+
function keyName(key, field) {
|
|
178
|
+
if (own(NAMED_KEYS, key)) return NAMED_KEYS[key][field];
|
|
179
|
+
return key.toUpperCase();
|
|
180
|
+
}
|
|
181
|
+
function formatAria(shortcuts) {
|
|
182
|
+
return shortcuts.map((shortcut) => {
|
|
183
|
+
const names = MODIFIER_ORDER.filter((mod) => shortcut[mod]).map((mod) => MODIFIER_LABELS[mod].aria);
|
|
184
|
+
if (!isModifierKey(shortcut.key)) names.push(keyName(shortcut.key, "aria"));
|
|
185
|
+
return names.join("+");
|
|
186
|
+
}).join(" ");
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Displays `mod+s` as `⌘ S` on Apple devices and `Ctrl + S` elsewhere, and joins alternatives
|
|
190
|
+
* with ` / `. Throws a `TypeError` for a malformed shortcut.
|
|
191
|
+
*/
|
|
192
|
+
function formatHint(keys) {
|
|
193
|
+
const mac = isMac();
|
|
194
|
+
return parseShortcuts(keys).map((shortcut) => {
|
|
195
|
+
const parts = MODIFIER_ORDER.filter((mod) => shortcut[mod]).map((mod) => MODIFIER_LABELS[mod][mac ? "mac" : "other"]);
|
|
196
|
+
if (!isModifierKey(shortcut.key)) parts.push(keyName(shortcut.key, "label"));
|
|
197
|
+
return parts.join(mac ? " " : " + ");
|
|
198
|
+
}).join(" / ");
|
|
199
|
+
}
|
|
200
|
+
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;
|
|
202
|
+
}
|
|
203
|
+
/** True when releasing this key ends the shortcut: its key or any of its modifiers. */
|
|
204
|
+
function releases(event, spec) {
|
|
205
|
+
const key = eventKey(event.key);
|
|
206
|
+
return key === spec.key || isModifierKey(key) && spec[key];
|
|
207
|
+
}
|
|
208
|
+
//#endregion
|
|
209
|
+
//#region src/key/dispatcher.ts
|
|
210
|
+
const IGNORED_TAGS = /* @__PURE__ */ new Set([
|
|
211
|
+
"INPUT",
|
|
212
|
+
"TEXTAREA",
|
|
213
|
+
"SELECT"
|
|
214
|
+
]);
|
|
215
|
+
const registrations = /* @__PURE__ */ new Set();
|
|
216
|
+
let stopListener = null;
|
|
217
|
+
function isTyping(event) {
|
|
218
|
+
const target = event.target;
|
|
219
|
+
return target instanceof HTMLElement && (IGNORED_TAGS.has(target.tagName) || target.isContentEditable);
|
|
220
|
+
}
|
|
221
|
+
function inIgnoreZone(event) {
|
|
222
|
+
const target = event.target;
|
|
223
|
+
if (!(target instanceof Element)) return false;
|
|
224
|
+
let ancestor = target.parentElement;
|
|
225
|
+
while (ancestor) {
|
|
226
|
+
if (ancestor.hasAttribute("data-keyshortcuts-ignore")) return document.activeElement !== ancestor;
|
|
227
|
+
ancestor = ancestor.parentElement;
|
|
228
|
+
}
|
|
229
|
+
return false;
|
|
230
|
+
}
|
|
231
|
+
function handleKeydown(event) {
|
|
232
|
+
if (event.isComposing || event.key === "Dead") return;
|
|
233
|
+
const ignoreZone = inIgnoreZone(event);
|
|
234
|
+
const eligible = (reg) => {
|
|
235
|
+
if (reg.ignoreRepeat && event.repeat) return false;
|
|
236
|
+
if (reg.ignoreInputs && isTyping(event)) return false;
|
|
237
|
+
if (ignoreZone) return false;
|
|
238
|
+
const { element } = reg;
|
|
239
|
+
if (!element.isConnected || element.matches(":disabled") || element.closest("[inert]")) return false;
|
|
240
|
+
return reg.shortcuts.some((shortcut) => matches(event, shortcut));
|
|
241
|
+
};
|
|
242
|
+
for (const reg of registrations) if (!reg.consume && eligible(reg)) reg.handler(event);
|
|
243
|
+
for (const reg of [...registrations].reverse()) if (reg.consume && eligible(reg)) {
|
|
244
|
+
reg.handler(event);
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
function register(reg) {
|
|
249
|
+
if (registrations.size === 0) stopListener = on(window, "keydown", handleKeydown);
|
|
250
|
+
registrations.add(reg);
|
|
251
|
+
return () => {
|
|
252
|
+
registrations.delete(reg);
|
|
253
|
+
if (registrations.size === 0 && stopListener) {
|
|
254
|
+
stopListener();
|
|
255
|
+
stopListener = null;
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
//#endregion
|
|
260
|
+
//#region src/key/index.ts
|
|
261
|
+
function trackHeld(element, className) {
|
|
262
|
+
const active = /* @__PURE__ */ new Set();
|
|
263
|
+
const release = (event) => {
|
|
264
|
+
if (active.size === 0) return;
|
|
265
|
+
for (const shortcut of active) if (!event || releases(event, shortcut)) active.delete(shortcut);
|
|
266
|
+
if (active.size === 0) element.classList.remove(className);
|
|
267
|
+
};
|
|
268
|
+
const offUp = on(window, "keyup", release);
|
|
269
|
+
const offBlur = on(window, "blur", () => release());
|
|
270
|
+
return {
|
|
271
|
+
press(event, shortcuts) {
|
|
272
|
+
for (const shortcut of shortcuts) if (matches(event, shortcut)) active.add(shortcut);
|
|
273
|
+
element.classList.add(className);
|
|
274
|
+
},
|
|
275
|
+
stop() {
|
|
276
|
+
offUp();
|
|
277
|
+
offBlur();
|
|
278
|
+
release();
|
|
279
|
+
}
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Clicks the element, or calls `onTrigger`, when a shortcut is pressed anywhere on the page.
|
|
284
|
+
* When several attached elements share a shortcut, the most recently attached eligible one runs.
|
|
285
|
+
* Sets `aria-keyshortcuts` and restores the previous value on detach.
|
|
286
|
+
*
|
|
287
|
+
* @example
|
|
288
|
+
* ```svelte
|
|
289
|
+
* <button {@attach hotkey("mod+s", { pressedClass: "active" })} onclick={save}>Save</button>
|
|
290
|
+
* ```
|
|
291
|
+
*/
|
|
292
|
+
function hotkey(keys, options = {}) {
|
|
293
|
+
const { onTrigger, pressedClass, preventDefault = true, stopPropagation = false, ignoreInputs = true, ignoreRepeat = true } = options;
|
|
294
|
+
const shortcuts = parseShortcuts(keys);
|
|
295
|
+
const aria = formatAria(shortcuts);
|
|
296
|
+
return (element) => {
|
|
297
|
+
const held = pressedClass ? trackHeld(element, pressedClass) : void 0;
|
|
298
|
+
const previousAria = element.getAttribute("aria-keyshortcuts");
|
|
299
|
+
element.setAttribute("aria-keyshortcuts", aria);
|
|
300
|
+
const unregister = register({
|
|
301
|
+
element,
|
|
302
|
+
shortcuts,
|
|
303
|
+
consume: true,
|
|
304
|
+
ignoreInputs,
|
|
305
|
+
ignoreRepeat,
|
|
306
|
+
handler: (event) => {
|
|
307
|
+
if (preventDefault) event.preventDefault();
|
|
308
|
+
if (stopPropagation) event.stopPropagation();
|
|
309
|
+
held?.press(event, shortcuts);
|
|
310
|
+
if (onTrigger) onTrigger(element, event);
|
|
311
|
+
else element.click();
|
|
312
|
+
}
|
|
313
|
+
});
|
|
314
|
+
return () => {
|
|
315
|
+
unregister();
|
|
316
|
+
held?.stop();
|
|
317
|
+
if (previousAria === null) element.removeAttribute("aria-keyshortcuts");
|
|
318
|
+
else element.setAttribute("aria-keyshortcuts", previousAria);
|
|
319
|
+
};
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Adds a class while a shortcut is held, without triggering anything. A lone modifier such as
|
|
324
|
+
* `"mod"` or `"shift"` is a valid shortcut here. Use `hotkey`'s `pressedClass` for elements
|
|
325
|
+
* that also activate.
|
|
326
|
+
*/
|
|
327
|
+
function pressed(keys, options = {}) {
|
|
328
|
+
const { className = "is-pressed", ignoreInputs = true } = options;
|
|
329
|
+
const shortcuts = parseShortcuts(keys);
|
|
330
|
+
return (element) => {
|
|
331
|
+
const held = trackHeld(element, className);
|
|
332
|
+
const unregister = register({
|
|
333
|
+
element,
|
|
334
|
+
shortcuts,
|
|
335
|
+
consume: false,
|
|
336
|
+
ignoreInputs,
|
|
337
|
+
ignoreRepeat: true,
|
|
338
|
+
handler: (event) => held.press(event, shortcuts)
|
|
339
|
+
});
|
|
340
|
+
return () => {
|
|
341
|
+
unregister();
|
|
342
|
+
held.stop();
|
|
343
|
+
};
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
//#endregion
|
|
347
|
+
export { formatHint, hotkey, pressed };
|
package/dist/sound.d.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { Attachment } from "svelte/attachments";
|
|
2
|
+
//#region src/sound.d.ts
|
|
3
|
+
type EventName = keyof HTMLElementEventMap;
|
|
4
|
+
export interface SoundOptions {
|
|
5
|
+
/** Between 0 and 1. Defaults to 1. */
|
|
6
|
+
volume?: number;
|
|
7
|
+
loop?: boolean;
|
|
8
|
+
/** Playback speed, greater than 0. Defaults to 1. */
|
|
9
|
+
rate?: number;
|
|
10
|
+
}
|
|
11
|
+
/** A URL, or a function that picks one when the event fires. Returning null skips playback. */
|
|
12
|
+
export type SoundSource<E extends HTMLElement = HTMLElement> = string | ((element: E, event: Event) => string | null | undefined);
|
|
13
|
+
export interface SoundAttachmentOptions extends SoundOptions {
|
|
14
|
+
/** Event that starts playback. Defaults to `"click"`. */
|
|
15
|
+
on?: EventName;
|
|
16
|
+
/** Event that stops every playback this attachment started. */
|
|
17
|
+
stopOn?: EventName;
|
|
18
|
+
/** Receives selection, load and playback errors. Without it they are logged. */
|
|
19
|
+
onError?: (error: unknown) => void;
|
|
20
|
+
}
|
|
21
|
+
export interface Playback {
|
|
22
|
+
stop(): void;
|
|
23
|
+
}
|
|
24
|
+
export declare function isSupported(): boolean;
|
|
25
|
+
export declare class Sound {
|
|
26
|
+
private readonly src;
|
|
27
|
+
private readonly options;
|
|
28
|
+
private readonly playbacks;
|
|
29
|
+
private generation;
|
|
30
|
+
constructor(src: string, options?: SoundOptions);
|
|
31
|
+
/** Primes the shared URL cache. Resolves to false without Web Audio and rejects on load failure. */
|
|
32
|
+
preload(): Promise<boolean>;
|
|
33
|
+
/**
|
|
34
|
+
* The handle stops only this playback. Resolves to null without Web Audio, or when `stop()`
|
|
35
|
+
* ran before playback started. Load and resume failures reject.
|
|
36
|
+
*/
|
|
37
|
+
play(): Promise<Playback | null>;
|
|
38
|
+
/** Stops active playbacks and prevents pending ones from starting after load or resume. */
|
|
39
|
+
stop(): void;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Plays a sound when the element receives `on` (default `"click"`). `stopOn` and detaching stop
|
|
43
|
+
* active sounds and prevent pending ones from starting.
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* ```svelte
|
|
47
|
+
* <button {@attach sound(click, { volume: 0.5 })}>Click</button>
|
|
48
|
+
* ```
|
|
49
|
+
*/
|
|
50
|
+
export declare function sound<E extends HTMLElement = HTMLElement>(src: SoundSource<E>, options?: SoundAttachmentOptions): Attachment<E>;
|
|
51
|
+
//#endregion
|
|
52
|
+
export {};
|
package/dist/sound.js
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { on } from "svelte/events";
|
|
2
|
+
//#region src/sound.ts
|
|
3
|
+
const buffers = /* @__PURE__ */ new Map();
|
|
4
|
+
let sharedContext;
|
|
5
|
+
function isSupported() {
|
|
6
|
+
return typeof AudioContext !== "undefined";
|
|
7
|
+
}
|
|
8
|
+
function audioContext() {
|
|
9
|
+
if (!isSupported()) return void 0;
|
|
10
|
+
return sharedContext ??= new AudioContext();
|
|
11
|
+
}
|
|
12
|
+
function loadBuffer(src, context) {
|
|
13
|
+
const cached = buffers.get(src);
|
|
14
|
+
if (cached) return cached;
|
|
15
|
+
const pending = (async () => {
|
|
16
|
+
const response = await fetch(src);
|
|
17
|
+
if (!response.ok) throw new Error(`Failed to load sound ${src}: HTTP ${response.status}`);
|
|
18
|
+
return context.decodeAudioData(await response.arrayBuffer());
|
|
19
|
+
})();
|
|
20
|
+
buffers.set(src, pending);
|
|
21
|
+
pending.catch(() => {
|
|
22
|
+
if (buffers.get(src) === pending) buffers.delete(src);
|
|
23
|
+
});
|
|
24
|
+
return pending;
|
|
25
|
+
}
|
|
26
|
+
function validate({ volume = 1, rate = 1 }) {
|
|
27
|
+
if (!Number.isFinite(volume) || volume < 0 || volume > 1) throw new RangeError("Sound volume must be between 0 and 1.");
|
|
28
|
+
if (!Number.isFinite(rate) || rate <= 0) throw new RangeError("Sound rate must be greater than 0.");
|
|
29
|
+
}
|
|
30
|
+
var Sound = class {
|
|
31
|
+
src;
|
|
32
|
+
options;
|
|
33
|
+
playbacks = /* @__PURE__ */ new Set();
|
|
34
|
+
generation = 0;
|
|
35
|
+
constructor(src, options = {}) {
|
|
36
|
+
this.src = src;
|
|
37
|
+
this.options = options;
|
|
38
|
+
validate(options);
|
|
39
|
+
}
|
|
40
|
+
/** Primes the shared URL cache. Resolves to false without Web Audio and rejects on load failure. */
|
|
41
|
+
async preload() {
|
|
42
|
+
const context = audioContext();
|
|
43
|
+
if (!context) return false;
|
|
44
|
+
await loadBuffer(this.src, context);
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The handle stops only this playback. Resolves to null without Web Audio, or when `stop()`
|
|
49
|
+
* ran before playback started. Load and resume failures reject.
|
|
50
|
+
*/
|
|
51
|
+
async play() {
|
|
52
|
+
const context = audioContext();
|
|
53
|
+
if (!context) return null;
|
|
54
|
+
const generation = this.generation;
|
|
55
|
+
const [buffer] = await Promise.all([loadBuffer(this.src, context), context.resume()]);
|
|
56
|
+
if (generation !== this.generation) return null;
|
|
57
|
+
const source = context.createBufferSource();
|
|
58
|
+
const gain = context.createGain();
|
|
59
|
+
source.buffer = buffer;
|
|
60
|
+
source.loop = this.options.loop ?? false;
|
|
61
|
+
source.playbackRate.value = this.options.rate ?? 1;
|
|
62
|
+
gain.gain.value = this.options.volume ?? 1;
|
|
63
|
+
source.connect(gain).connect(context.destination);
|
|
64
|
+
let active = true;
|
|
65
|
+
const playback = { stop: () => {
|
|
66
|
+
if (!active) return;
|
|
67
|
+
active = false;
|
|
68
|
+
this.playbacks.delete(playback);
|
|
69
|
+
try {
|
|
70
|
+
source.stop();
|
|
71
|
+
} catch (error) {
|
|
72
|
+
if (!(error instanceof DOMException && error.name === "InvalidStateError")) throw error;
|
|
73
|
+
} finally {
|
|
74
|
+
source.disconnect();
|
|
75
|
+
gain.disconnect();
|
|
76
|
+
}
|
|
77
|
+
} };
|
|
78
|
+
source.onended = () => {
|
|
79
|
+
if (!active) return;
|
|
80
|
+
active = false;
|
|
81
|
+
this.playbacks.delete(playback);
|
|
82
|
+
source.disconnect();
|
|
83
|
+
gain.disconnect();
|
|
84
|
+
};
|
|
85
|
+
try {
|
|
86
|
+
source.start();
|
|
87
|
+
} catch (error) {
|
|
88
|
+
source.disconnect();
|
|
89
|
+
gain.disconnect();
|
|
90
|
+
throw error;
|
|
91
|
+
}
|
|
92
|
+
this.playbacks.add(playback);
|
|
93
|
+
return playback;
|
|
94
|
+
}
|
|
95
|
+
/** Stops active playbacks and prevents pending ones from starting after load or resume. */
|
|
96
|
+
stop() {
|
|
97
|
+
this.generation += 1;
|
|
98
|
+
for (const playback of this.playbacks) playback.stop();
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
/**
|
|
102
|
+
* Plays a sound when the element receives `on` (default `"click"`). `stopOn` and detaching stop
|
|
103
|
+
* active sounds and prevent pending ones from starting.
|
|
104
|
+
*
|
|
105
|
+
* @example
|
|
106
|
+
* ```svelte
|
|
107
|
+
* <button {@attach sound(click, { volume: 0.5 })}>Click</button>
|
|
108
|
+
* ```
|
|
109
|
+
*/
|
|
110
|
+
function sound(src, options = {}) {
|
|
111
|
+
const { on: playEvent = "click", stopOn, onError, ...soundOptions } = options;
|
|
112
|
+
validate(soundOptions);
|
|
113
|
+
return (element) => {
|
|
114
|
+
const instances = /* @__PURE__ */ new Map();
|
|
115
|
+
const getSound = (url) => {
|
|
116
|
+
let instance = instances.get(url);
|
|
117
|
+
if (!instance) {
|
|
118
|
+
instance = new Sound(url, soundOptions);
|
|
119
|
+
instances.set(url, instance);
|
|
120
|
+
}
|
|
121
|
+
return instance;
|
|
122
|
+
};
|
|
123
|
+
const reportError = (error) => {
|
|
124
|
+
if (onError) onError(error);
|
|
125
|
+
else console.warn("[svelte-attach/sound] Playback failed:", error);
|
|
126
|
+
};
|
|
127
|
+
const stop = () => {
|
|
128
|
+
for (const instance of instances.values()) instance.stop();
|
|
129
|
+
};
|
|
130
|
+
const offPlay = on(element, playEvent, (event) => {
|
|
131
|
+
try {
|
|
132
|
+
const url = typeof src === "string" ? src : src(element, event);
|
|
133
|
+
if (url != null) getSound(url).play().catch(reportError);
|
|
134
|
+
} catch (error) {
|
|
135
|
+
reportError(error);
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
const offStop = stopOn ? on(element, stopOn, stop) : void 0;
|
|
139
|
+
return () => {
|
|
140
|
+
offPlay();
|
|
141
|
+
offStop?.();
|
|
142
|
+
stop();
|
|
143
|
+
};
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
//#endregion
|
|
147
|
+
export { Sound, isSupported, sound };
|
package/package.json
CHANGED
|
@@ -1,6 +1,81 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@joknoll/svelte-attach",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Svelte 5 attachments for keyboard shortcuts, sound effects, vibration, and gamepad buttons.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"attachment",
|
|
7
|
+
"gamepad",
|
|
8
|
+
"haptic",
|
|
9
|
+
"hotkey",
|
|
10
|
+
"keyboard",
|
|
11
|
+
"sound",
|
|
12
|
+
"svelte",
|
|
13
|
+
"svelte5",
|
|
14
|
+
"vibration",
|
|
15
|
+
"web-audio"
|
|
16
|
+
],
|
|
17
|
+
"homepage": "https://github.com/joknoll/svelte-attach#readme",
|
|
18
|
+
"bugs": {
|
|
19
|
+
"url": "https://github.com/joknoll/svelte-attach/issues"
|
|
20
|
+
},
|
|
21
|
+
"license": "MIT",
|
|
22
|
+
"author": "joknoll",
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "git+https://github.com/joknoll/svelte-attach.git"
|
|
26
|
+
},
|
|
27
|
+
"files": [
|
|
28
|
+
"dist"
|
|
29
|
+
],
|
|
30
|
+
"type": "module",
|
|
31
|
+
"sideEffects": false,
|
|
32
|
+
"exports": {
|
|
33
|
+
"./key": {
|
|
34
|
+
"types": "./dist/key.d.ts",
|
|
35
|
+
"default": "./dist/key.js"
|
|
36
|
+
},
|
|
37
|
+
"./sound": {
|
|
38
|
+
"types": "./dist/sound.d.ts",
|
|
39
|
+
"default": "./dist/sound.js"
|
|
40
|
+
},
|
|
41
|
+
"./haptic": {
|
|
42
|
+
"types": "./dist/haptic.d.ts",
|
|
43
|
+
"default": "./dist/haptic.js"
|
|
44
|
+
},
|
|
45
|
+
"./gamepad": {
|
|
46
|
+
"types": "./dist/gamepad.d.ts",
|
|
47
|
+
"default": "./dist/gamepad.js"
|
|
48
|
+
},
|
|
49
|
+
"./package.json": "./package.json"
|
|
50
|
+
},
|
|
51
|
+
"publishConfig": {
|
|
52
|
+
"access": "public"
|
|
53
|
+
},
|
|
54
|
+
"devDependencies": {
|
|
55
|
+
"@types/node": "^24",
|
|
56
|
+
"jsdom": "^29.0.1",
|
|
57
|
+
"svelte": "^5.55.0",
|
|
58
|
+
"typescript": "^7.0.2",
|
|
59
|
+
"vite-plus": "1.2.0"
|
|
60
|
+
},
|
|
61
|
+
"peerDependencies": {
|
|
62
|
+
"svelte": ">=5.55.0"
|
|
63
|
+
},
|
|
64
|
+
"devEngines": {
|
|
65
|
+
"packageManager": {
|
|
66
|
+
"name": "pnpm",
|
|
67
|
+
"version": "12.11.2",
|
|
68
|
+
"onFail": "download"
|
|
69
|
+
},
|
|
70
|
+
"runtime": {
|
|
71
|
+
"name": "node",
|
|
72
|
+
"version": ">=22.18.0"
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
"scripts": {
|
|
76
|
+
"build": "vp pack",
|
|
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"
|
|
80
|
+
}
|
|
6
81
|
}
|