@joknoll/svelte-attach 0.0.0-stage → 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/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,78 @@
1
- # Temporary Holding Version
1
+ # @joknoll/svelte-attach
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Svelte attachments to add keyboard shortcuts, sound effects, vibration, and gamepad controls to Svelte 5 components.
4
+
5
+ ## Usage
6
+
7
+ Requires Svelte `5.55.0` or later.
8
+
9
+ ### Keyboard
10
+
11
+ ```svelte
12
+ <script lang="ts">
13
+ import { hotkey } from "@joknoll/svelte-attach/key";
14
+ </script>
15
+
16
+ <button popovertarget="shortcuts" {@attach hotkey("mod+k")}>
17
+ Show shortcuts
18
+ </button>
19
+
20
+ <div id="shortcuts" popover>Press Escape to close.</div>
21
+ ```
22
+
23
+ Press `⌘K` on Apple devices or `Ctrl+K` elsewhere to open the popover. The button doesn’t need focus.
24
+
25
+ [Keyboard API](docs/keyboard.md)
26
+
27
+ ### Sound
28
+
29
+ ```svelte
30
+ <script lang="ts">
31
+ import { sound } from "@joknoll/svelte-attach/sound";
32
+ import click from "./click.opus";
33
+ </script>
34
+
35
+ <button {@attach sound(click)}>Play sound</button>
36
+ ```
37
+
38
+ Sound plays on `click` by default. Set `on` to use a different event.
39
+
40
+ Use sound sparingly for meaningful moments, like completing a task. Avoid playing it on every click or keystroke, and let users mute it.
41
+
42
+ [Sound API](docs/sound.md)
43
+
44
+ ### Vibration
45
+
46
+ ```svelte
47
+ <script lang="ts">
48
+ import { haptic } from "@joknoll/svelte-attach/haptic";
49
+ </script>
50
+
51
+ <button {@attach haptic("light")}>Try vibration</button>
52
+ ```
53
+
54
+ The button vibrates the device on click if the browser and device support vibration.
55
+
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.
57
+
58
+ [Vibration API](docs/vibration.md)
59
+
60
+ ### Gamepad
61
+
62
+ ```svelte
63
+ <script lang="ts">
64
+ import { gamepadButton } from "@joknoll/svelte-attach/gamepad";
65
+ </script>
66
+
67
+ <button popovertarget="gamepad-help" {@attach gamepadButton("A")}>
68
+ Show controls
69
+ </button>
70
+
71
+ <div id="gamepad-help" popover>Press Escape to close.</div>
72
+ ```
73
+
74
+ Focus the button, then press `A` on a standard-mapped gamepad to open the popover.
75
+
76
+ [Gamepad API](docs/gamepad.md)
77
+
78
+ [Full documentation](docs/)
@@ -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
@@ -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 };
@@ -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,150 @@
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
+ /**
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
+ */
122
+ ignoreInputs?: boolean;
123
+ /** Defaults to true. */
124
+ ignoreRepeat?: boolean;
125
+ }
126
+ export interface PressedOptions {
127
+ /** Defaults to `"is-pressed"`. */
128
+ className?: string;
129
+ /** Defaults to true. */
130
+ ignoreInputs?: boolean;
131
+ }
132
+ /**
133
+ * Clicks the element, or calls `onTrigger`, when a shortcut is pressed anywhere on the page.
134
+ * When several attached elements share a shortcut, the most recently attached eligible one runs.
135
+ * Sets `aria-keyshortcuts` and restores the previous value on detach.
136
+ *
137
+ * @example
138
+ * ```svelte
139
+ * <button {@attach hotkey("mod+s", { pressedClass: "active" })} onclick={save}>Save</button>
140
+ * ```
141
+ */
142
+ export declare function hotkey<const S extends string, E extends HTMLElement = HTMLElement>(keys: Shortcut<S> | readonly Shortcut<S>[], options?: HotkeyOptions<E>): Attachment<E>;
143
+ /**
144
+ * Adds a class while a shortcut is held, without triggering anything. A lone modifier such as
145
+ * `"mod"` or `"shift"` is a valid shortcut here. Use `hotkey`'s `pressedClass` for elements
146
+ * that also activate.
147
+ */
148
+ export declare function pressed<const S extends string>(keys: Shortcut<S> | readonly Shortcut<S>[], options?: PressedOptions): Attachment<HTMLElement>;
149
+ //#endregion
150
+ export type { Shortcut };
package/dist/key.js ADDED
@@ -0,0 +1,373 @@
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
+ 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
+ }
209
+ function matches(event, spec) {
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;
220
+ }
221
+ /** True when releasing this key ends the shortcut: its key or any of its modifiers. */
222
+ function releases(event, spec) {
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;
226
+ }
227
+ //#endregion
228
+ //#region src/key/dispatcher.ts
229
+ const NON_TEXT_INPUTS = /* @__PURE__ */ new Set([
230
+ "checkbox",
231
+ "button",
232
+ "submit",
233
+ "reset",
234
+ "image",
235
+ "color",
236
+ "file"
237
+ ]);
238
+ const registrations = /* @__PURE__ */ new Set();
239
+ let stopListener = null;
240
+ function isTyping(event) {
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;
246
+ }
247
+ function inIgnoreZone(event) {
248
+ const target = event.target;
249
+ if (!(target instanceof Element)) return false;
250
+ let ancestor = target.parentElement;
251
+ while (ancestor) {
252
+ if (ancestor.hasAttribute("data-keyshortcuts-ignore")) return document.activeElement !== ancestor;
253
+ ancestor = ancestor.parentElement;
254
+ }
255
+ return false;
256
+ }
257
+ function handleKeydown(event) {
258
+ if (event.isComposing || event.key === "Dead" && !event.altKey) return;
259
+ const ignoreZone = inIgnoreZone(event);
260
+ const eligible = (reg) => {
261
+ if (reg.ignoreRepeat && event.repeat) return false;
262
+ if (reg.ignoreInputs && isTyping(event)) return false;
263
+ if (ignoreZone) return false;
264
+ const { element } = reg;
265
+ if (!element.isConnected || element.matches(":disabled") || element.closest("[inert]")) return false;
266
+ return reg.shortcuts.some((shortcut) => matches(event, shortcut));
267
+ };
268
+ for (const reg of registrations) if (!reg.consume && eligible(reg)) reg.handler(event);
269
+ for (const reg of [...registrations].reverse()) if (reg.consume && eligible(reg)) {
270
+ reg.handler(event);
271
+ return;
272
+ }
273
+ }
274
+ function register(reg) {
275
+ if (registrations.size === 0) stopListener = on(window, "keydown", handleKeydown);
276
+ registrations.add(reg);
277
+ return () => {
278
+ registrations.delete(reg);
279
+ if (registrations.size === 0 && stopListener) {
280
+ stopListener();
281
+ stopListener = null;
282
+ }
283
+ };
284
+ }
285
+ //#endregion
286
+ //#region src/key/index.ts
287
+ function trackHeld(element, className) {
288
+ const active = /* @__PURE__ */ new Map();
289
+ const release = (event) => {
290
+ if (active.size === 0) return;
291
+ for (const [shortcut, code] of active) if (!event || code !== "" && event.code === code || releases(event, shortcut)) active.delete(shortcut);
292
+ if (active.size === 0) element.classList.remove(className);
293
+ };
294
+ const offUp = on(window, "keyup", release);
295
+ const offBlur = on(window, "blur", () => release());
296
+ return {
297
+ press(event, shortcuts) {
298
+ for (const shortcut of shortcuts) if (matches(event, shortcut)) active.set(shortcut, event.code);
299
+ element.classList.add(className);
300
+ },
301
+ stop() {
302
+ offUp();
303
+ offBlur();
304
+ release();
305
+ }
306
+ };
307
+ }
308
+ /**
309
+ * Clicks the element, or calls `onTrigger`, when a shortcut is pressed anywhere on the page.
310
+ * When several attached elements share a shortcut, the most recently attached eligible one runs.
311
+ * Sets `aria-keyshortcuts` and restores the previous value on detach.
312
+ *
313
+ * @example
314
+ * ```svelte
315
+ * <button {@attach hotkey("mod+s", { pressedClass: "active" })} onclick={save}>Save</button>
316
+ * ```
317
+ */
318
+ function hotkey(keys, options = {}) {
319
+ const { onTrigger, pressedClass, preventDefault = true, stopPropagation = false, ignoreInputs = true, ignoreRepeat = true } = options;
320
+ const shortcuts = parseShortcuts(keys);
321
+ const aria = formatAria(shortcuts);
322
+ return (element) => {
323
+ const held = pressedClass ? trackHeld(element, pressedClass) : void 0;
324
+ const previousAria = element.getAttribute("aria-keyshortcuts");
325
+ element.setAttribute("aria-keyshortcuts", aria);
326
+ const unregister = register({
327
+ element,
328
+ shortcuts,
329
+ consume: true,
330
+ ignoreInputs,
331
+ ignoreRepeat,
332
+ handler: (event) => {
333
+ if (preventDefault) event.preventDefault();
334
+ if (stopPropagation) event.stopPropagation();
335
+ held?.press(event, shortcuts);
336
+ if (onTrigger) onTrigger(element, event);
337
+ else element.click();
338
+ }
339
+ });
340
+ return () => {
341
+ unregister();
342
+ held?.stop();
343
+ if (previousAria === null) element.removeAttribute("aria-keyshortcuts");
344
+ else element.setAttribute("aria-keyshortcuts", previousAria);
345
+ };
346
+ };
347
+ }
348
+ /**
349
+ * Adds a class while a shortcut is held, without triggering anything. A lone modifier such as
350
+ * `"mod"` or `"shift"` is a valid shortcut here. Use `hotkey`'s `pressedClass` for elements
351
+ * that also activate.
352
+ */
353
+ function pressed(keys, options = {}) {
354
+ const { className = "is-pressed", ignoreInputs = true } = options;
355
+ const shortcuts = parseShortcuts(keys);
356
+ return (element) => {
357
+ const held = trackHeld(element, className);
358
+ const unregister = register({
359
+ element,
360
+ shortcuts,
361
+ consume: false,
362
+ ignoreInputs,
363
+ ignoreRepeat: true,
364
+ handler: (event) => held.press(event, shortcuts)
365
+ });
366
+ return () => {
367
+ unregister();
368
+ held.stop();
369
+ };
370
+ };
371
+ }
372
+ //#endregion
373
+ export { formatHint, hotkey, pressed };
@@ -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.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.1",
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 example#check && vp run example#build",
79
+ "dev": "vp run example#dev"
80
+ }
6
81
  }