@colixsystems/widget-sdk 0.295.0 → 0.296.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/README.md CHANGED
@@ -90,7 +90,16 @@ See the design reference for the full architecture: [`docs/architecture/widget-m
90
90
 
91
91
  ## Status
92
92
 
93
- `v0.295.0` — pre-publish. The package surface (types, function names, export paths) is the v1 contract; runtime behaviour for some hooks is stubbed (each hook documents what's wired and what isn't). It is **not yet published to npm**.
93
+ `v0.296.0` — pre-publish. The package surface (types, function names, export paths) is the v1 contract; runtime behaviour for some hooks is stubbed (each hook documents what's wired and what isn't). It is **not yet published to npm**.
94
+
95
+ ### What's new in 0.296.0 (contract 1.243.0)
96
+
97
+ **New `useKeyboard()` hook: hardware keyboard input on both hosts.** A game or an editor no longer needs `onKeyDown` on a focused `View`, which stopped hearing keys the moment focus moved. `useKeyboard({ keys, onKeyDown, onKeyUp, active })` returns `{ supported, pressed }`. Key names are `KeyboardEvent.code` values on every host (`ArrowLeft`, `KeyW`, `Space`), so they do not change with the keyboard layout, and `pressed` is the set held right now. Name the keys the widget handles in `keys`: only those are delivered, and the host stops their browser default, so arrows and Space no longer scroll the page. On the web, keys keep arriving after a click elsewhere on the page; a focused button or link keeps Enter and Space, and a slider, list or tab set keeps its keys. On iOS and Android, keys pause while a text field is open. Keys typed into a text field are never delivered. Held keys are released, each with an `onKeyUp`, when the window or app loses focus or a text field opens, so a character never keeps running. `onKeyDown` repeats while a key is held on the web and Android; iOS sends one per press. `supported` is true where a keyboard is present (a mouse or trackpad on the web, or once any key is pressed); false means none has been seen yet, so show touch controls. In the Builder canvas and widget previews keys arrive only while the preview has focus. The web Player listens on the window; the Expo export reads iPad and phone hardware keyboards through `expo-key-event`. Additive.
98
+
99
+ ```js
100
+ const { supported, pressed } = useKeyboard({ keys: ["ArrowLeft", "ArrowRight", "Space"] });
101
+ const dx = (pressed.has("ArrowRight") ? 1 : 0) - (pressed.has("ArrowLeft") ? 1 : 0);
102
+ ```
94
103
 
95
104
  ### What's new in 0.295.0 (contract 1.242.0)
96
105
 
package/dist/contract.cjs CHANGED
@@ -3327,6 +3327,36 @@ const HOOKS = [
3327
3327
  requiredContextSlice: [],
3328
3328
  scopes: null,
3329
3329
  },
3330
+ // sc-15908 — host-brokered hardware keyboard. Optional slice; the hook
3331
+ // reports supported:false rather than throwing at render.
3332
+ {
3333
+ name: "useKeyboard",
3334
+ signature: "useKeyboard({ keys, onKeyDown, onKeyUp, active })",
3335
+ description:
3336
+ "Read hardware keyboard input — arrow keys in a game, shortcuts in an editor. Returns { supported, pressed }. " +
3337
+ "Key names are KeyboardEvent.code values on every host ('ArrowLeft', 'KeyW', 'Space', 'Enter', 'Escape', " +
3338
+ "'Digit1', 'ShiftLeft'), so they do not change with the keyboard layout. `pressed` is the Set of keys held now. " +
3339
+ "`keys` lists the keys the widget handles: only those are delivered, and the host stops their browser default so " +
3340
+ "arrows and Space do not scroll the page. Omit `keys` to hear every key with no default stopped. " +
3341
+ "onKeyDown(event) / onKeyUp(event) receive { key, character, repeat, shiftKey, ctrlKey, altKey, metaKey }; " +
3342
+ "onKeyDown repeats while a key is held (repeat: true) on the web and Android; iOS sends one onKeyDown per press and " +
3343
+ "may drop one key of two pressed at the same instant. `active: false` stops listening. On the web keys keep " +
3344
+ "arriving after a click elsewhere on the page, except Enter/Space on a focused button or link and keys inside a " +
3345
+ "slider, list or tab set, which stay with that control; on iOS and Android keys pause while a text field is open " +
3346
+ "and resume when its keyboard closes. Keys typed into a text field are never delivered. Held keys are released, " +
3347
+ "each with an onKeyUp, when the window or app loses focus, a text field opens or the hook turns inactive, so " +
3348
+ "nothing sticks; unmounting calls no handler. `supported` is true when a keyboard is present: on the web where the " +
3349
+ "device has a mouse or trackpad, and on any host once a key is pressed. False means no keyboard has been seen, so " +
3350
+ "ALWAYS render touch controls when supported is false (an iPad with a keyboard turns true at its first key press). " +
3351
+ "In the Builder canvas and widget previews keys arrive only while the preview has focus (click it first). " +
3352
+ "Identical on web (window key listeners) and the Expo export (expo-key-event, iOS and Android hardware keyboards).",
3353
+ returnShape: {
3354
+ supported: "boolean // a keyboard is present (fine pointer on web, or a key was pressed)",
3355
+ pressed: "ReadonlySet<string> // KeyboardEvent.code names held now",
3356
+ },
3357
+ requiredContextSlice: [],
3358
+ scopes: null,
3359
+ },
3330
3360
  // sc-6448 — host-brokered camera capture / photo picking. Optional slice;
3331
3361
  // the hook reports supported:false rather than throwing at render.
3332
3362
  {
@@ -4629,13 +4659,18 @@ const WIDGET_CONTEXT_SHAPE = {
4629
4659
  "start() -> Promise<{ getStatus() -> { durationMs, levelDb, ended }, stop() -> Promise<{ file, uri, durationMs, mime, release? }>, cancel() }> }, " +
4630
4660
  "audioPlayer: { isSupported() -> boolean, load(uri, onStatus({ loaded, playing, positionMs, durationMs, error? })) -> " +
4631
4661
  "{ play() -> Promise<void>, pause(), seek(ms) -> Promise<void>, release() } }, " +
4662
+ "keyboard: { hasKeyboard() -> boolean, subscribe({ keys: string[] | null, onKey({ type: 'down' | 'up', key, character, " +
4663
+ "repeat, shiftKey, ctrlKey, altKey, metaKey }), onRelease(), onDetected() }) -> unsubscribe }, " +
4632
4664
  "purchases: { isSupported() -> boolean, getOffering() -> Promise<offering | null>, getEntitlements() -> Promise<string[]>, " +
4633
4665
  "purchase(packageId) -> Promise<string[]>, restore() -> Promise<string[]> } }. " +
4634
4666
  "purchases backs usePurchases() and is NATIVE-ONLY: the Expo export brokers it through react-native-purchases when the " +
4635
4667
  "workspace connected RevenueCat; the web Player never does, because a browser has no store billing. " +
4636
- "Backs useGeolocation(), useSpeechToText(), useCamera(), useImageEditor(), useBarcodeScanner(), usePdfExport().openPdf, useAudioRecorder() and useAudioPlayer(). The web Player brokers them via " +
4637
- "navigator.geolocation, window.SpeechRecognition, a getUserMedia camera preview, a host-side canvas, BarcodeDetector, a new browser tab, MediaRecorder and an <audio> element; the Expo export via " +
4638
- "expo-location, expo-speech-recognition, expo-image-picker, expo-image-manipulator, expo-camera, expo-print and expo-audio. " +
4668
+ "Backs useGeolocation(), useSpeechToText(), useCamera(), useImageEditor(), useBarcodeScanner(), usePdfExport().openPdf, useAudioRecorder(), useAudioPlayer() and useKeyboard(). The web Player brokers them via " +
4669
+ "navigator.geolocation, window.SpeechRecognition, a getUserMedia camera preview, a host-side canvas, BarcodeDetector, a new browser tab, MediaRecorder, an <audio> element and window key listeners; the Expo export via " +
4670
+ "expo-location, expo-speech-recognition, expo-image-picker, expo-image-manipulator, expo-camera, expo-print, expo-audio and expo-key-event. " +
4671
+ "keyboard.subscribe delivers only the `keys` named (all when null), stops the browser default of a delivered key " +
4672
+ "pressed without Ctrl/Cmd/Alt, calls onRelease when the window or app loses focus or a text field opens and onDetected the first time any key " +
4673
+ "arrives; a Builder preview's broker accepts keys only while focus is inside the preview. " +
4639
4674
  "audioRecorder.start rejects with .code PERMISSION_DENIED | UNSUPPORTED | INTERNAL; getStatus().levelDb is the input level in dBFS " +
4640
4675
  "(null when unknown); `ended` is true once the host stopped the recording itself (a lost headset, a call), and stop() then " +
4641
4676
  "still resolves that clip. audioPlayer reports the end of a clip as playing:false at positionMs 0. " +
@@ -4672,6 +4707,7 @@ const WIDGET_CONTEXT_SHAPE = {
4672
4707
  pdfViewer: "object",
4673
4708
  audioRecorder: "object",
4674
4709
  audioPlayer: "object",
4710
+ keyboard: "object",
4675
4711
  purchases: "object",
4676
4712
  },
4677
4713
  },
@@ -6831,7 +6867,10 @@ const CONTRACT = deepFreeze({
6831
6867
  // `requestGuestPayment` / `getGuestPayment` (a visitor with no account
6832
6868
  // pays for an order they created), the payments slice gains both, the
6833
6869
  // `payments.charge:guest` scope, and four new PaymentError codes.
6834
- version: "1.242.0",
6870
+ // 1.243.0: additive (sc-15908) — `useKeyboard({ keys, onKeyDown, onKeyUp,
6871
+ // active })` + the optional `device.keyboard` slice (window key listeners
6872
+ // on web, expo-key-event on native).
6873
+ version: "1.243.0",
6835
6874
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
6836
6875
  hooks: HOOKS,
6837
6876
  primitives: PRIMITIVES,
package/dist/contract.js CHANGED
@@ -3323,6 +3323,36 @@ const HOOKS = [
3323
3323
  requiredContextSlice: [],
3324
3324
  scopes: null,
3325
3325
  },
3326
+ // sc-15908 — host-brokered hardware keyboard. Optional slice; the hook
3327
+ // reports supported:false rather than throwing at render.
3328
+ {
3329
+ name: "useKeyboard",
3330
+ signature: "useKeyboard({ keys, onKeyDown, onKeyUp, active })",
3331
+ description:
3332
+ "Read hardware keyboard input — arrow keys in a game, shortcuts in an editor. Returns { supported, pressed }. " +
3333
+ "Key names are KeyboardEvent.code values on every host ('ArrowLeft', 'KeyW', 'Space', 'Enter', 'Escape', " +
3334
+ "'Digit1', 'ShiftLeft'), so they do not change with the keyboard layout. `pressed` is the Set of keys held now. " +
3335
+ "`keys` lists the keys the widget handles: only those are delivered, and the host stops their browser default so " +
3336
+ "arrows and Space do not scroll the page. Omit `keys` to hear every key with no default stopped. " +
3337
+ "onKeyDown(event) / onKeyUp(event) receive { key, character, repeat, shiftKey, ctrlKey, altKey, metaKey }; " +
3338
+ "onKeyDown repeats while a key is held (repeat: true) on the web and Android; iOS sends one onKeyDown per press and " +
3339
+ "may drop one key of two pressed at the same instant. `active: false` stops listening. On the web keys keep " +
3340
+ "arriving after a click elsewhere on the page, except Enter/Space on a focused button or link and keys inside a " +
3341
+ "slider, list or tab set, which stay with that control; on iOS and Android keys pause while a text field is open " +
3342
+ "and resume when its keyboard closes. Keys typed into a text field are never delivered. Held keys are released, " +
3343
+ "each with an onKeyUp, when the window or app loses focus, a text field opens or the hook turns inactive, so " +
3344
+ "nothing sticks; unmounting calls no handler. `supported` is true when a keyboard is present: on the web where the " +
3345
+ "device has a mouse or trackpad, and on any host once a key is pressed. False means no keyboard has been seen, so " +
3346
+ "ALWAYS render touch controls when supported is false (an iPad with a keyboard turns true at its first key press). " +
3347
+ "In the Builder canvas and widget previews keys arrive only while the preview has focus (click it first). " +
3348
+ "Identical on web (window key listeners) and the Expo export (expo-key-event, iOS and Android hardware keyboards).",
3349
+ returnShape: {
3350
+ supported: "boolean // a keyboard is present (fine pointer on web, or a key was pressed)",
3351
+ pressed: "ReadonlySet<string> // KeyboardEvent.code names held now",
3352
+ },
3353
+ requiredContextSlice: [],
3354
+ scopes: null,
3355
+ },
3326
3356
  // sc-6448 — host-brokered camera capture / photo picking. Optional slice;
3327
3357
  // the hook reports supported:false rather than throwing at render.
3328
3358
  {
@@ -4625,13 +4655,18 @@ const WIDGET_CONTEXT_SHAPE = {
4625
4655
  "start() -> Promise<{ getStatus() -> { durationMs, levelDb, ended }, stop() -> Promise<{ file, uri, durationMs, mime, release? }>, cancel() }> }, " +
4626
4656
  "audioPlayer: { isSupported() -> boolean, load(uri, onStatus({ loaded, playing, positionMs, durationMs, error? })) -> " +
4627
4657
  "{ play() -> Promise<void>, pause(), seek(ms) -> Promise<void>, release() } }, " +
4658
+ "keyboard: { hasKeyboard() -> boolean, subscribe({ keys: string[] | null, onKey({ type: 'down' | 'up', key, character, " +
4659
+ "repeat, shiftKey, ctrlKey, altKey, metaKey }), onRelease(), onDetected() }) -> unsubscribe }, " +
4628
4660
  "purchases: { isSupported() -> boolean, getOffering() -> Promise<offering | null>, getEntitlements() -> Promise<string[]>, " +
4629
4661
  "purchase(packageId) -> Promise<string[]>, restore() -> Promise<string[]> } }. " +
4630
4662
  "purchases backs usePurchases() and is NATIVE-ONLY: the Expo export brokers it through react-native-purchases when the " +
4631
4663
  "workspace connected RevenueCat; the web Player never does, because a browser has no store billing. " +
4632
- "Backs useGeolocation(), useSpeechToText(), useCamera(), useImageEditor(), useBarcodeScanner(), usePdfExport().openPdf, useAudioRecorder() and useAudioPlayer(). The web Player brokers them via " +
4633
- "navigator.geolocation, window.SpeechRecognition, a getUserMedia camera preview, a host-side canvas, BarcodeDetector, a new browser tab, MediaRecorder and an <audio> element; the Expo export via " +
4634
- "expo-location, expo-speech-recognition, expo-image-picker, expo-image-manipulator, expo-camera, expo-print and expo-audio. " +
4664
+ "Backs useGeolocation(), useSpeechToText(), useCamera(), useImageEditor(), useBarcodeScanner(), usePdfExport().openPdf, useAudioRecorder(), useAudioPlayer() and useKeyboard(). The web Player brokers them via " +
4665
+ "navigator.geolocation, window.SpeechRecognition, a getUserMedia camera preview, a host-side canvas, BarcodeDetector, a new browser tab, MediaRecorder, an <audio> element and window key listeners; the Expo export via " +
4666
+ "expo-location, expo-speech-recognition, expo-image-picker, expo-image-manipulator, expo-camera, expo-print, expo-audio and expo-key-event. " +
4667
+ "keyboard.subscribe delivers only the `keys` named (all when null), stops the browser default of a delivered key " +
4668
+ "pressed without Ctrl/Cmd/Alt, calls onRelease when the window or app loses focus or a text field opens and onDetected the first time any key " +
4669
+ "arrives; a Builder preview's broker accepts keys only while focus is inside the preview. " +
4635
4670
  "audioRecorder.start rejects with .code PERMISSION_DENIED | UNSUPPORTED | INTERNAL; getStatus().levelDb is the input level in dBFS " +
4636
4671
  "(null when unknown); `ended` is true once the host stopped the recording itself (a lost headset, a call), and stop() then " +
4637
4672
  "still resolves that clip. audioPlayer reports the end of a clip as playing:false at positionMs 0. " +
@@ -4668,6 +4703,7 @@ const WIDGET_CONTEXT_SHAPE = {
4668
4703
  pdfViewer: "object",
4669
4704
  audioRecorder: "object",
4670
4705
  audioPlayer: "object",
4706
+ keyboard: "object",
4671
4707
  purchases: "object",
4672
4708
  },
4673
4709
  },
@@ -6827,7 +6863,10 @@ const CONTRACT = deepFreeze({
6827
6863
  // `requestGuestPayment` / `getGuestPayment` (a visitor with no account
6828
6864
  // pays for an order they created), the payments slice gains both, the
6829
6865
  // `payments.charge:guest` scope, and four new PaymentError codes.
6830
- version: "1.242.0",
6866
+ // 1.243.0: additive (sc-15908) — `useKeyboard({ keys, onKeyDown, onKeyUp,
6867
+ // active })` + the optional `device.keyboard` slice (window key listeners
6868
+ // on web, expo-key-event on native).
6869
+ version: "1.243.0",
6831
6870
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
6832
6871
  hooks: HOOKS,
6833
6872
  primitives: PRIMITIVES,
package/dist/index.d.ts CHANGED
@@ -968,6 +968,16 @@ export interface WidgetContext<TProps = unknown> {
968
968
  release(): void;
969
969
  };
970
970
  };
971
+ /** sc-15908 — backs useKeyboard. */
972
+ keyboard?: {
973
+ hasKeyboard(): boolean;
974
+ subscribe(subscriber: {
975
+ keys: string[] | null;
976
+ onKey(event: KeyboardKeyEvent & { type: "down" | "up" }): void;
977
+ onRelease(): void;
978
+ onDetected(): void;
979
+ }): () => void;
980
+ };
971
981
  /** sc-15163 — backs usePurchases. Brokered by the Expo export only. */
972
982
  purchases?: {
973
983
  isSupported?(): boolean;
@@ -3135,6 +3145,42 @@ export interface AudioPlayerResult {
3135
3145
  */
3136
3146
  export function useAudioPlayer(uri: string | null | undefined): AudioPlayerResult;
3137
3147
 
3148
+ /** A key event as `useKeyboard()` delivers it. */
3149
+ export interface KeyboardKeyEvent {
3150
+ /** KeyboardEvent.code name: "ArrowLeft", "KeyW", "Space", "Enter". */
3151
+ key: string;
3152
+ /** The printed character, or "" for keys that print none. */
3153
+ character: string;
3154
+ repeat: boolean;
3155
+ shiftKey: boolean;
3156
+ ctrlKey: boolean;
3157
+ altKey: boolean;
3158
+ metaKey: boolean;
3159
+ }
3160
+
3161
+ export interface UseKeyboardOptions {
3162
+ /** Keys the widget handles; only these arrive, with their browser default stopped. Omit for every key. */
3163
+ keys?: string[];
3164
+ onKeyDown?(event: KeyboardKeyEvent): void;
3165
+ onKeyUp?(event: KeyboardKeyEvent): void;
3166
+ /** False stops listening and releases held keys. Default true. */
3167
+ active?: boolean;
3168
+ }
3169
+
3170
+ export interface KeyboardResult {
3171
+ /** A keyboard is present: a fine pointer on web, or a key was pressed. */
3172
+ supported: boolean;
3173
+ /** Keys held right now. */
3174
+ pressed: ReadonlySet<string>;
3175
+ }
3176
+
3177
+ /**
3178
+ * Hardware keyboard input on both hosts: window key listeners in the web
3179
+ * Player, `expo-key-event` in the Expo export. Held keys are released when
3180
+ * the window or app loses focus.
3181
+ */
3182
+ export function useKeyboard(options?: UseKeyboardOptions): KeyboardResult;
3183
+
3138
3184
  /** One package of the current offering, as the store prices it. */
3139
3185
  export interface PurchasePackage {
3140
3186
  id: string;
package/dist/index.js CHANGED
@@ -136,6 +136,8 @@ export {
136
136
  useAudioPlayer,
137
137
  AudioPlayerError,
138
138
  } from "./audio.js";
139
+ // sc-15908 — one host-brokered source for both entries (ctx.device.keyboard).
140
+ export { useKeyboard } from "./keyboard.js";
139
141
  // sc-15163 — native-only in-app purchase; the web Player brokers none.
140
142
  export { usePurchases, PurchasesError } from "./purchases.js";
141
143
  export { useDatastoreFigure } from "./datastore-figure.js";
@@ -134,6 +134,8 @@ export {
134
134
  useAudioPlayer,
135
135
  AudioPlayerError,
136
136
  } from "./audio.js";
137
+ // sc-15908 — one host-brokered source for both entries (ctx.device.keyboard).
138
+ export { useKeyboard } from "./keyboard.js";
137
139
  // sc-15163 — native-only in-app purchase; the web Player brokers none.
138
140
  export { usePurchases, PurchasesError } from "./purchases.js";
139
141
  export { useDatastoreFigure } from "./datastore-figure.js";
@@ -0,0 +1,138 @@
1
+ // sc-15908 — host-brokered hardware keyboard input: `useKeyboard()`.
2
+ //
3
+ // One source for both hosts. The web Player brokers ctx.device.keyboard with
4
+ // window key listeners; the Expo export brokers it with expo-key-event. Key
5
+ // names are KeyboardEvent.code values ("ArrowLeft", "KeyW", "Space") on both,
6
+ // so they do not change with the keyboard layout.
7
+ //
8
+ // This file avoids JSX so it can ship as a plain .js without a transform.
9
+
10
+ import { useEffect, useRef, useState } from "react";
11
+ import { useWidgetContextOrThrow } from "./hooks.js";
12
+
13
+ const NO_KEYS = new Set();
14
+
15
+ function isUsable(client) {
16
+ return Boolean(
17
+ client &&
18
+ typeof client.subscribe === "function" &&
19
+ typeof client.hasKeyboard === "function",
20
+ );
21
+ }
22
+
23
+ function callQuietly(fn, event) {
24
+ if (typeof fn !== "function") return;
25
+ try {
26
+ fn(event);
27
+ } catch {
28
+ /* a widget handler's throw must not break the host's listener */
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Read hardware keyboard input. Returns `{ supported, pressed }`.
34
+ *
35
+ * - `supported` is true when a keyboard is present: on the web where the
36
+ * device has a fine pointer, and on any host once a key has been pressed.
37
+ * A phone without a keyboard reports false, so a widget shows its touch
38
+ * controls instead of a "press the arrow keys" hint.
39
+ * - `pressed` is the set of keys held right now (KeyboardEvent.code names).
40
+ *
41
+ * Options:
42
+ * - `keys` — the key names the widget handles. Only these are delivered, and
43
+ * the host stops their browser default (arrows and Space scroll no page).
44
+ * Omit it to receive every key with no default stopped.
45
+ * - `onKeyDown(event)` / `onKeyUp(event)` — `event` is `{ key, character,
46
+ * repeat, shiftKey, ctrlKey, altKey, metaKey }`.
47
+ * - `active` (default true) — false stops listening and releases held keys.
48
+ *
49
+ * Held keys are released, with an `onKeyUp` for each, when the window loses
50
+ * focus or the hook turns inactive, so a game never sticks "running". Keys
51
+ * typed into a text field are never delivered.
52
+ */
53
+ export function useKeyboard(options) {
54
+ const opts = options || {};
55
+ const ctx = useWidgetContextOrThrow("useKeyboard");
56
+ const client = ctx.device && ctx.device.keyboard;
57
+ const usable = isUsable(client);
58
+ const active = opts.active !== false;
59
+
60
+ const [detected, setDetected] = useState(false);
61
+ const [pressed, setPressed] = useState(NO_KEYS);
62
+
63
+ const handlersRef = useRef(opts);
64
+ handlersRef.current = opts;
65
+
66
+ // Declared first so its cleanup runs before the subscription's on unmount.
67
+ const unmountedRef = useRef(false);
68
+ useEffect(() => {
69
+ unmountedRef.current = false;
70
+ return () => {
71
+ unmountedRef.current = true;
72
+ };
73
+ }, []);
74
+
75
+ const keysId = Array.isArray(opts.keys) ? opts.keys.join("\u0000") : null;
76
+
77
+ useEffect(() => {
78
+ if (!usable || !active) return undefined;
79
+ const held = new Set();
80
+ const publish = () => setPressed(held.size ? new Set(held) : NO_KEYS);
81
+
82
+ const onKey = (event) => {
83
+ if (event.type === "down") {
84
+ if (!held.has(event.key)) {
85
+ held.add(event.key);
86
+ publish();
87
+ }
88
+ callQuietly(handlersRef.current.onKeyDown, toWidgetEvent(event));
89
+ } else if (held.delete(event.key)) {
90
+ publish();
91
+ callQuietly(handlersRef.current.onKeyUp, toWidgetEvent(event));
92
+ }
93
+ };
94
+
95
+ const releaseAll = () => {
96
+ if (held.size === 0) return;
97
+ const keys = [...held];
98
+ held.clear();
99
+ publish();
100
+ if (unmountedRef.current) return;
101
+ for (const key of keys) callQuietly(handlersRef.current.onKeyUp, releasedEvent(key));
102
+ };
103
+
104
+ const unsubscribe = client.subscribe({
105
+ keys: keysId === null ? null : keysId.split("\u0000"),
106
+ onKey,
107
+ onRelease: releaseAll,
108
+ onDetected: () => setDetected(true),
109
+ });
110
+
111
+ return () => {
112
+ if (typeof unsubscribe === "function") unsubscribe();
113
+ // Deactivated while mounted, the widget still hears its keys go up.
114
+ releaseAll();
115
+ };
116
+ }, [client, usable, active, keysId]);
117
+
118
+ return {
119
+ supported: usable && (detected || client.hasKeyboard()),
120
+ pressed: usable && active ? pressed : NO_KEYS,
121
+ };
122
+ }
123
+
124
+ function toWidgetEvent(event) {
125
+ return {
126
+ key: event.key,
127
+ character: event.character || "",
128
+ repeat: Boolean(event.repeat),
129
+ shiftKey: Boolean(event.shiftKey),
130
+ ctrlKey: Boolean(event.ctrlKey),
131
+ altKey: Boolean(event.altKey),
132
+ metaKey: Boolean(event.metaKey),
133
+ };
134
+ }
135
+
136
+ function releasedEvent(key) {
137
+ return toWidgetEvent({ key });
138
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@colixsystems/widget-sdk",
3
- "version": "0.295.0",
3
+ "version": "0.296.0",
4
4
  "description": "Common widget interface for AppStudio. Implements WidgetManifest, WidgetContext, property schema, and helper hooks.",
5
5
  "homepage": "https://github.com/Colix-AB/AppStudio",
6
6
  "type": "module",
package/src/contract.js CHANGED
@@ -3323,6 +3323,36 @@ const HOOKS = [
3323
3323
  requiredContextSlice: [],
3324
3324
  scopes: null,
3325
3325
  },
3326
+ // sc-15908 — host-brokered hardware keyboard. Optional slice; the hook
3327
+ // reports supported:false rather than throwing at render.
3328
+ {
3329
+ name: "useKeyboard",
3330
+ signature: "useKeyboard({ keys, onKeyDown, onKeyUp, active })",
3331
+ description:
3332
+ "Read hardware keyboard input — arrow keys in a game, shortcuts in an editor. Returns { supported, pressed }. " +
3333
+ "Key names are KeyboardEvent.code values on every host ('ArrowLeft', 'KeyW', 'Space', 'Enter', 'Escape', " +
3334
+ "'Digit1', 'ShiftLeft'), so they do not change with the keyboard layout. `pressed` is the Set of keys held now. " +
3335
+ "`keys` lists the keys the widget handles: only those are delivered, and the host stops their browser default so " +
3336
+ "arrows and Space do not scroll the page. Omit `keys` to hear every key with no default stopped. " +
3337
+ "onKeyDown(event) / onKeyUp(event) receive { key, character, repeat, shiftKey, ctrlKey, altKey, metaKey }; " +
3338
+ "onKeyDown repeats while a key is held (repeat: true) on the web and Android; iOS sends one onKeyDown per press and " +
3339
+ "may drop one key of two pressed at the same instant. `active: false` stops listening. On the web keys keep " +
3340
+ "arriving after a click elsewhere on the page, except Enter/Space on a focused button or link and keys inside a " +
3341
+ "slider, list or tab set, which stay with that control; on iOS and Android keys pause while a text field is open " +
3342
+ "and resume when its keyboard closes. Keys typed into a text field are never delivered. Held keys are released, " +
3343
+ "each with an onKeyUp, when the window or app loses focus, a text field opens or the hook turns inactive, so " +
3344
+ "nothing sticks; unmounting calls no handler. `supported` is true when a keyboard is present: on the web where the " +
3345
+ "device has a mouse or trackpad, and on any host once a key is pressed. False means no keyboard has been seen, so " +
3346
+ "ALWAYS render touch controls when supported is false (an iPad with a keyboard turns true at its first key press). " +
3347
+ "In the Builder canvas and widget previews keys arrive only while the preview has focus (click it first). " +
3348
+ "Identical on web (window key listeners) and the Expo export (expo-key-event, iOS and Android hardware keyboards).",
3349
+ returnShape: {
3350
+ supported: "boolean // a keyboard is present (fine pointer on web, or a key was pressed)",
3351
+ pressed: "ReadonlySet<string> // KeyboardEvent.code names held now",
3352
+ },
3353
+ requiredContextSlice: [],
3354
+ scopes: null,
3355
+ },
3326
3356
  // sc-6448 — host-brokered camera capture / photo picking. Optional slice;
3327
3357
  // the hook reports supported:false rather than throwing at render.
3328
3358
  {
@@ -4625,13 +4655,18 @@ const WIDGET_CONTEXT_SHAPE = {
4625
4655
  "start() -> Promise<{ getStatus() -> { durationMs, levelDb, ended }, stop() -> Promise<{ file, uri, durationMs, mime, release? }>, cancel() }> }, " +
4626
4656
  "audioPlayer: { isSupported() -> boolean, load(uri, onStatus({ loaded, playing, positionMs, durationMs, error? })) -> " +
4627
4657
  "{ play() -> Promise<void>, pause(), seek(ms) -> Promise<void>, release() } }, " +
4658
+ "keyboard: { hasKeyboard() -> boolean, subscribe({ keys: string[] | null, onKey({ type: 'down' | 'up', key, character, " +
4659
+ "repeat, shiftKey, ctrlKey, altKey, metaKey }), onRelease(), onDetected() }) -> unsubscribe }, " +
4628
4660
  "purchases: { isSupported() -> boolean, getOffering() -> Promise<offering | null>, getEntitlements() -> Promise<string[]>, " +
4629
4661
  "purchase(packageId) -> Promise<string[]>, restore() -> Promise<string[]> } }. " +
4630
4662
  "purchases backs usePurchases() and is NATIVE-ONLY: the Expo export brokers it through react-native-purchases when the " +
4631
4663
  "workspace connected RevenueCat; the web Player never does, because a browser has no store billing. " +
4632
- "Backs useGeolocation(), useSpeechToText(), useCamera(), useImageEditor(), useBarcodeScanner(), usePdfExport().openPdf, useAudioRecorder() and useAudioPlayer(). The web Player brokers them via " +
4633
- "navigator.geolocation, window.SpeechRecognition, a getUserMedia camera preview, a host-side canvas, BarcodeDetector, a new browser tab, MediaRecorder and an <audio> element; the Expo export via " +
4634
- "expo-location, expo-speech-recognition, expo-image-picker, expo-image-manipulator, expo-camera, expo-print and expo-audio. " +
4664
+ "Backs useGeolocation(), useSpeechToText(), useCamera(), useImageEditor(), useBarcodeScanner(), usePdfExport().openPdf, useAudioRecorder(), useAudioPlayer() and useKeyboard(). The web Player brokers them via " +
4665
+ "navigator.geolocation, window.SpeechRecognition, a getUserMedia camera preview, a host-side canvas, BarcodeDetector, a new browser tab, MediaRecorder, an <audio> element and window key listeners; the Expo export via " +
4666
+ "expo-location, expo-speech-recognition, expo-image-picker, expo-image-manipulator, expo-camera, expo-print, expo-audio and expo-key-event. " +
4667
+ "keyboard.subscribe delivers only the `keys` named (all when null), stops the browser default of a delivered key " +
4668
+ "pressed without Ctrl/Cmd/Alt, calls onRelease when the window or app loses focus or a text field opens and onDetected the first time any key " +
4669
+ "arrives; a Builder preview's broker accepts keys only while focus is inside the preview. " +
4635
4670
  "audioRecorder.start rejects with .code PERMISSION_DENIED | UNSUPPORTED | INTERNAL; getStatus().levelDb is the input level in dBFS " +
4636
4671
  "(null when unknown); `ended` is true once the host stopped the recording itself (a lost headset, a call), and stop() then " +
4637
4672
  "still resolves that clip. audioPlayer reports the end of a clip as playing:false at positionMs 0. " +
@@ -4668,6 +4703,7 @@ const WIDGET_CONTEXT_SHAPE = {
4668
4703
  pdfViewer: "object",
4669
4704
  audioRecorder: "object",
4670
4705
  audioPlayer: "object",
4706
+ keyboard: "object",
4671
4707
  purchases: "object",
4672
4708
  },
4673
4709
  },
@@ -6827,7 +6863,10 @@ const CONTRACT = deepFreeze({
6827
6863
  // `requestGuestPayment` / `getGuestPayment` (a visitor with no account
6828
6864
  // pays for an order they created), the payments slice gains both, the
6829
6865
  // `payments.charge:guest` scope, and four new PaymentError codes.
6830
- version: "1.242.0",
6866
+ // 1.243.0: additive (sc-15908) — `useKeyboard({ keys, onKeyDown, onKeyUp,
6867
+ // active })` + the optional `device.keyboard` slice (window key listeners
6868
+ // on web, expo-key-event on native).
6869
+ version: "1.243.0",
6831
6870
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
6832
6871
  hooks: HOOKS,
6833
6872
  primitives: PRIMITIVES,