@uyghurcommunity/keyboard 0.0.0-stage → 0.2.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/package.json CHANGED
@@ -1,6 +1,28 @@
1
1
  {
2
2
  "name": "@uyghurcommunity/keyboard",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Accessible, dependency-free Uyghur virtual keyboard with multiple layouts and optional physical mapping.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "UyghurCommunity",
8
+ "repository": { "type": "git", "url": "https://github.com/UyghurCommunity/uyghur-keyboard.git" },
9
+ "homepage": "https://uyghurcommunity.github.io/uyghur-keyboard/",
10
+ "bugs": "https://github.com/UyghurCommunity/uyghur-keyboard/issues",
11
+ "keywords": ["uyghur", "keyboard", "rtl", "web-component", "unicode", "accessibility"],
12
+ "exports": {
13
+ ".": { "types": "./src/index.d.ts", "import": "./src/index.js" },
14
+ "./element": { "types": "./src/element.d.ts", "import": "./src/element.js" },
15
+ "./bundle": { "types": "./src/index.d.ts", "import": "./dist/uyghur-keyboard.js" }
16
+ },
17
+ "types": "./src/index.d.ts",
18
+ "files": ["src", "dist", "docs", "README.md", "CHANGELOG.md", "LICENSE"],
19
+ "sideEffects": ["./src/element.js", "./dist/uyghur-keyboard.js"],
20
+ "engines": { "node": ">=18" },
21
+ "scripts": {
22
+ "test": "node --test",
23
+ "build": "node scripts/build-bundle.js",
24
+ "check": "node --check src/index.js && node --check src/element.js && node --check demo/demo.js && node --check demo/motion.js && node --check dist/uyghur-keyboard.js && node scripts/build-bundle.js --check",
25
+ "prepack": "npm run check && npm test"
26
+ },
27
+ "publishConfig": { "access": "public" }
28
+ }
@@ -0,0 +1 @@
1
+ export { defineUyghurKeyboard } from './index.js';
package/src/element.js ADDED
@@ -0,0 +1,3 @@
1
+ import { defineUyghurKeyboard } from './index.js';
2
+ export { defineUyghurKeyboard } from './index.js';
3
+ defineUyghurKeyboard();
package/src/index.d.ts ADDED
@@ -0,0 +1,56 @@
1
+ export interface SelectionResult { value: string; start: number; end: number }
2
+ export type KeyboardLayoutId = 'phonetic' | 'uey-desktop' | 'uly' | 'usy';
3
+ export type KeyboardLocale = 'ug' | 'en';
4
+ export type KeyboardTheme = 'light' | 'dark';
5
+ export interface KeyboardLayout {
6
+ readonly id: string;
7
+ readonly labels: Readonly<{ en: string; ug?: string }>;
8
+ readonly lang: string;
9
+ readonly direction: 'rtl' | 'ltr';
10
+ readonly keyDirection?: 'rtl' | 'ltr';
11
+ readonly rows: readonly (readonly string[])[];
12
+ readonly shiftedRows?: readonly (readonly string[])[];
13
+ readonly physicalMap?: Readonly<Record<string, string>>;
14
+ readonly secondary?: readonly string[];
15
+ readonly reviewStatus?: 'draft';
16
+ }
17
+ export interface KeyboardOptions {
18
+ container?: HTMLElement | ShadowRoot;
19
+ physical?: boolean;
20
+ direction?: 'rtl' | 'ltr' | 'auto' | 'preserve';
21
+ layout?: string;
22
+ layouts?: readonly KeyboardLayout[];
23
+ locale?: KeyboardLocale;
24
+ theme?: KeyboardTheme;
25
+ autoHamza?: boolean;
26
+ secondaryKeys?: boolean;
27
+ compact?: boolean;
28
+ label?: string;
29
+ }
30
+ export interface KeyboardController {
31
+ readonly element: HTMLDivElement;
32
+ readonly layout: string;
33
+ setLayout(id: string): void;
34
+ setTheme(theme: KeyboardTheme): void;
35
+ setCompact(enabled: boolean): void;
36
+ setAutoHamza(enabled: boolean): void;
37
+ setSecondaryKeys(enabled: boolean): void;
38
+ insert(text: string): boolean;
39
+ backspace(): boolean;
40
+ setPhysicalMapping(enabled: boolean): void;
41
+ setVisible(visible: boolean): void;
42
+ destroy(): void;
43
+ }
44
+ export interface UyghurKeyboardElement extends HTMLElement {
45
+ layout: KeyboardLayoutId;
46
+ insert(text: string): boolean;
47
+ backspace(): boolean;
48
+ }
49
+ export const KEYBOARD_LAYOUTS: Readonly<Record<KeyboardLayoutId, KeyboardLayout>>;
50
+ export const KEY_LAYOUT: readonly (readonly string[])[];
51
+ export const PHONETIC_MAP: Readonly<Record<string, string>>;
52
+ export function replaceSelection(value: string, start: number | null, end: number | null, text: string): SelectionResult;
53
+ export function deleteSelectionBackward(value: string, start: number | null, end: number | null): SelectionResult;
54
+ export function createKeyboard(target: HTMLInputElement | HTMLTextAreaElement, options?: KeyboardOptions): KeyboardController;
55
+ export function defineUyghurKeyboard(name?: string, registry?: CustomElementRegistry): CustomElementConstructor | null;
56
+ declare global { interface HTMLElementTagNameMap { 'uyghur-keyboard': UyghurKeyboardElement } }
package/src/index.js ADDED
@@ -0,0 +1,411 @@
1
+ import { alkatipFontFace, alkatipHelperStyles, keyboardStyles } from './style.js';
2
+ import { KEYBOARD_LAYOUTS, keyboardLabels } from './layouts.js';
3
+ import { nextKey } from './navigation.js';
4
+ export { KEY_LAYOUT, PHONETIC_MAP, KEYBOARD_LAYOUTS } from './layouts.js';
5
+
6
+ const fontStyleId = 'uyghur-keyboard-alkatip-font';
7
+ const fontRegistrations = new WeakMap();
8
+ function acquireFont(document) {
9
+ let registration = fontRegistrations.get(document);
10
+ if (!registration) {
11
+ const parent = document.head || document.documentElement;
12
+ if (!parent) return () => {};
13
+ let element = document.getElementById(fontStyleId);
14
+ const owned = !element;
15
+ if (!element) {
16
+ element = document.createElement('style');
17
+ element.id = fontStyleId;
18
+ element.textContent = alkatipFontFace + '\n' + alkatipHelperStyles;
19
+ parent.appendChild(element);
20
+ }
21
+ registration = { element, owned, count: 0 };
22
+ fontRegistrations.set(document, registration);
23
+ }
24
+ registration.count++;
25
+ let released = false;
26
+ return () => {
27
+ if (released) return;
28
+ released = true;
29
+ if (--registration.count === 0) {
30
+ if (registration.owned) registration.element.remove();
31
+ fontRegistrations.delete(document);
32
+ }
33
+ };
34
+ }
35
+
36
+ function selection(value, start, end) {
37
+ const length = value.length;
38
+ const first = Number.isFinite(start) ? Math.max(0, Math.min(length, Math.trunc(start))) : length;
39
+ const last = Number.isFinite(end) ? Math.max(0, Math.min(length, Math.trunc(end))) : first;
40
+ return [Math.min(first, last), Math.max(first, last)];
41
+ }
42
+
43
+ /** Pure UTF-16 selection replacement, using the same offsets as HTML inputs. */
44
+ export function replaceSelection(value, start, end, text) {
45
+ if (typeof value !== 'string' || typeof text !== 'string') throw new TypeError('value and text must be strings');
46
+ const [a, b] = selection(value, start, end);
47
+ return { value: value.slice(0, a) + text + value.slice(b), start: a + text.length, end: a + text.length };
48
+ }
49
+
50
+ /** Remove a selected range or the preceding complete grapheme. */
51
+ export function deleteSelectionBackward(value, start, end) {
52
+ if (typeof value !== 'string') throw new TypeError('value must be a string');
53
+ const [a, b] = selection(value, start, end);
54
+ if (a !== b) return replaceSelection(value, a, b, '');
55
+ if (!a) return { value, start: 0, end: 0 };
56
+ let previous = 0;
57
+ if (typeof Intl.Segmenter === 'function') {
58
+ for (const part of new Intl.Segmenter('ug', { granularity: 'grapheme' }).segment(value)) {
59
+ if (part.index >= a) break;
60
+ previous = part.index;
61
+ }
62
+ } else {
63
+ previous = a - 1;
64
+ const code = value.charCodeAt(previous);
65
+ if (previous && code >= 0xdc00 && code <= 0xdfff) previous--;
66
+ }
67
+ return replaceSelection(value, previous, a, '');
68
+ }
69
+
70
+ function makeEvent(target, name, type, text, cancelable) {
71
+ const view = target.ownerDocument?.defaultView || globalThis;
72
+ if (typeof view.InputEvent === 'function') {
73
+ return new view.InputEvent(name, { bubbles: true, composed: true, cancelable, inputType: type, data: text });
74
+ }
75
+ const event = new view.Event(name, { bubbles: true, composed: true, cancelable });
76
+ Object.defineProperties(event, { inputType: { value: type }, data: { value: text } });
77
+ return event;
78
+ }
79
+
80
+ /** Mount a virtual keyboard next to a text input/textarea, or in options.container. */
81
+ export function createKeyboard(target, options = {}) {
82
+ if (!target || typeof target.value !== 'string' || typeof target.setSelectionRange !== 'function' || !target.ownerDocument) {
83
+ throw new TypeError('createKeyboard needs a text input or textarea');
84
+ }
85
+ if (target.tagName === 'INPUT' && !['text', 'search', 'tel', 'url', 'password'].includes(target.type || 'text')) {
86
+ throw new TypeError('The input type must support text selection');
87
+ }
88
+ const layouts = new Map(Object.entries(KEYBOARD_LAYOUTS));
89
+ for (const custom of options.layouts || []) {
90
+ if (!custom.id || layouts.has(custom.id) || !custom.rows?.some((row) => row.length) ||
91
+ !['rtl', 'ltr'].includes(custom.direction)) {
92
+ throw new TypeError('Custom layouts need a unique id, at least one key, and a valid direction');
93
+ }
94
+ layouts.set(custom.id, custom);
95
+ }
96
+ let layout = layouts.get(options.layout ?? 'phonetic');
97
+ if (!layout) throw new TypeError('Unknown keyboard layout: ' + options.layout);
98
+ const direction = options.direction;
99
+ if (direction && !['rtl', 'ltr', 'auto', 'preserve'].includes(direction)) {
100
+ throw new TypeError('direction must be rtl, ltr, auto, or preserve');
101
+ }
102
+ const originalDirection = target.getAttribute('dir');
103
+ let appliedDirection;
104
+ const doc = target.ownerDocument;
105
+ const locale = options.locale === 'en' ? 'en' : 'ug';
106
+ const labels = keyboardLabels[locale];
107
+ const root = doc.createElement('div');
108
+ root.className = 'ug-keyboard alkatip-basma';
109
+ root.lang = locale;
110
+ root.dir = locale === 'ug' ? 'rtl' : 'ltr';
111
+ root.setAttribute('role', 'group');
112
+ root.setAttribute('aria-label', options.label || labels.keyboard);
113
+ const style = doc.createElement('style');
114
+ style.textContent = keyboardStyles;
115
+ root.appendChild(style);
116
+ let physical = options.physical === true;
117
+ let autoHamza = options.autoHamza === true;
118
+ let secondary = options.secondaryKeys === true;
119
+ let destroyed = false;
120
+ let composing = false;
121
+ let shifted = false;
122
+ let buttonRows = [];
123
+ let activeButton;
124
+
125
+ const layoutSelect = doc.createElement('select');
126
+ layoutSelect.className = 'ug-keyboard__layout';
127
+ layoutSelect.setAttribute('aria-label', labels.layout);
128
+ for (const [id, item] of layouts) {
129
+ const option = doc.createElement('option');
130
+ option.value = id;
131
+ option.textContent = item.labels[locale] || item.labels.en;
132
+ layoutSelect.appendChild(option);
133
+ }
134
+ layoutSelect.value = layout.id;
135
+ root.appendChild(layoutSelect);
136
+ const keys = doc.createElement('div');
137
+ keys.className = 'ug-keyboard__keys';
138
+ root.appendChild(keys);
139
+
140
+ function setTargetDirection() {
141
+ const nextDirection = direction || layout.direction;
142
+ if (nextDirection === 'preserve') return;
143
+ if (appliedDirection !== undefined && target.getAttribute('dir') !== appliedDirection) return;
144
+ target.setAttribute('dir', nextDirection);
145
+ appliedDirection = nextDirection;
146
+ }
147
+
148
+ function keyButton(text, action) {
149
+ const button = doc.createElement('button');
150
+ button.type = 'button';
151
+ button.className = 'ug-keyboard__key';
152
+ button.textContent = text;
153
+ button.tabIndex = -1;
154
+ if (action) button.dataset.action = action;
155
+ else button.dataset.text = text;
156
+ const localized = labels[action] || labels.punctuation[text];
157
+ button.lang = localized ? locale : layout.lang;
158
+ button.setAttribute('aria-label', localized || text);
159
+ if (action === 'shift') button.setAttribute('aria-pressed', String(shifted));
160
+ return button;
161
+ }
162
+
163
+ function focusedElement() {
164
+ return root.getRootNode?.().activeElement || doc.activeElement;
165
+ }
166
+
167
+ function setActiveButton(button) {
168
+ if (activeButton) activeButton.tabIndex = -1;
169
+ activeButton = button;
170
+ activeButton.tabIndex = 0;
171
+ }
172
+
173
+ function renderKeys() {
174
+ const index = buttonRows.flat().indexOf(activeButton);
175
+ const restoreFocus = keys.contains(focusedElement());
176
+ keys.dir = layout.keyDirection || layout.direction;
177
+ const rows = (shifted ? layout.shiftedRows : layout.rows).map((row) => row.map((text) => keyButton(text)));
178
+ if (secondary && layout.secondary?.length) rows.push(layout.secondary.map((text) => keyButton(text)));
179
+ const actions = [keyButton(labels.space, 'space'), keyButton('⌫ ' + (locale === 'ug' ? 'ئۆچۈرۈش' : 'Delete'), 'backspace')];
180
+ if (layout.shiftedRows) actions.unshift(keyButton('⇧', 'shift'));
181
+ rows.push(actions);
182
+ buttonRows = rows;
183
+ keys.replaceChildren();
184
+ for (const buttons of rows) {
185
+ const row = doc.createElement('div');
186
+ row.className = 'ug-keyboard__row';
187
+ for (const button of buttons) row.appendChild(button);
188
+ keys.appendChild(row);
189
+ }
190
+ const buttons = rows.flat();
191
+ setActiveButton(buttons[Math.min(Math.max(index, 0), buttons.length - 1)]);
192
+ if (restoreFocus) activeButton.focus();
193
+ }
194
+
195
+ function setLayout(id) {
196
+ const next = layouts.get(id);
197
+ if (!next) throw new TypeError('Unknown keyboard layout: ' + id);
198
+ if (destroyed || next === layout) return;
199
+ layout = next;
200
+ shifted = false;
201
+ layoutSelect.value = id;
202
+ setTargetDirection();
203
+ renderKeys();
204
+ }
205
+
206
+ function setTheme(theme) {
207
+ if (!['light', 'dark'].includes(theme)) throw new TypeError('theme must be light or dark');
208
+ root.dataset.theme = theme;
209
+ }
210
+
211
+ function setCompact(enabled) {
212
+ root.dataset.compact = String(Boolean(enabled));
213
+ }
214
+
215
+ setTheme(options.theme ?? 'light');
216
+ setCompact(options.compact);
217
+ renderKeys();
218
+
219
+ if (options.container) options.container.appendChild(root);
220
+ else if (target.parentNode) target.parentNode.insertBefore(root, target.nextSibling);
221
+ else throw new Error('Attach the target to a document or provide a container');
222
+ // Font faces must be registered in the owner document, including when keys
223
+ // themselves live in a Web Component's shadow root.
224
+ const releaseFont = acquireFont(doc);
225
+ setTargetDirection();
226
+
227
+ function commit(result, inputType, text, focusTarget = true) {
228
+ if (destroyed || target.disabled || target.readOnly || composing) return false;
229
+ if (!target.dispatchEvent(makeEvent(target, 'beforeinput', inputType, text, true))) return false;
230
+ target.value = result.value;
231
+ if (focusTarget) target.focus({ preventScroll: true });
232
+ target.setSelectionRange(result.start, result.end);
233
+ target.dispatchEvent(makeEvent(target, 'input', inputType, text, false));
234
+ const view = doc.defaultView || globalThis;
235
+ if (typeof view.CustomEvent === 'function') {
236
+ root.dispatchEvent(new view.CustomEvent('uyghur-input', { bubbles: true, composed: true, detail: { value: target.value, inputType, text } }));
237
+ }
238
+ return true;
239
+ }
240
+ function insert(text) {
241
+ if (typeof text !== 'string') throw new TypeError('insert expects a string');
242
+ return insertText(text, true);
243
+ }
244
+ function insertText(text, focusTarget) {
245
+ const result = replaceSelection(target.value, target.selectionStart, target.selectionEnd, text);
246
+ return commit(result, 'insertText', text, focusTarget);
247
+ }
248
+ function deleteBackward(focusTarget) {
249
+ const result = deleteSelectionBackward(target.value, target.selectionStart, target.selectionEnd);
250
+ return commit(result, 'deleteContentBackward', null, focusTarget);
251
+ }
252
+ function withHamza(text) {
253
+ if (!autoHamza || layout.lang !== 'ug-Arab' || !/^[اەېىوۇۆۈ]$/u.test(text)) return text;
254
+ const [start] = selection(target.value, target.selectionStart, target.selectionEnd);
255
+ const insideWord = /[\p{L}\p{M}\p{N}\p{Pc}\u200c\u200d]$/u.test(target.value.slice(0, start));
256
+ return insideWord ? text : 'ئ' + text;
257
+ }
258
+ function onClick(event) {
259
+ const button = event.target.closest?.('button.ug-keyboard__key');
260
+ if (!button || !keys.contains(button)) return;
261
+ setActiveButton(button);
262
+ const action = button.dataset.action;
263
+ const focusTarget = event.detail !== 0 || focusedElement() !== button;
264
+ if (action === 'shift') {
265
+ shifted = !shifted;
266
+ renderKeys();
267
+ } else if (action === 'backspace') {
268
+ deleteBackward(focusTarget);
269
+ } else {
270
+ insertText(withHamza(action === 'space' ? ' ' : button.dataset.text), focusTarget);
271
+ }
272
+ }
273
+ function onPointerDown(event) {
274
+ // Keep the selection in the target while clicking the virtual keys.
275
+ if (event.target.closest?.('button.ug-keyboard__key')) event.preventDefault();
276
+ }
277
+ function onVirtualKeyDown(event) {
278
+ if (event.altKey || event.ctrlKey || event.metaKey || event.defaultPrevented) return;
279
+ const button = nextKey(buttonRows, event.target, event.key, keys.dir === 'rtl');
280
+ if (!button) return;
281
+ event.preventDefault();
282
+ setActiveButton(button);
283
+ button.focus();
284
+ }
285
+ function onKeyDown(event) {
286
+ if (composing || event.isComposing || event.defaultPrevented || event.ctrlKey || event.metaKey || event.altKey) return;
287
+ const map = layout.physicalMap;
288
+ const mapped = physical && map && Object.hasOwn(map, event.key) ? map[event.key] : undefined;
289
+ const text = withHamza(mapped ?? event.key);
290
+ if (mapped !== undefined || text !== event.key) {
291
+ event.preventDefault();
292
+ insertText(text, true);
293
+ }
294
+ }
295
+ const onLayoutChange = () => setLayout(layoutSelect.value);
296
+ const beginComposition = () => { composing = true; };
297
+ const endComposition = () => { composing = false; };
298
+ root.addEventListener('click', onClick);
299
+ root.addEventListener('pointerdown', onPointerDown);
300
+ keys.addEventListener('keydown', onVirtualKeyDown);
301
+ layoutSelect.addEventListener('change', onLayoutChange);
302
+ target.addEventListener('keydown', onKeyDown);
303
+ target.addEventListener('compositionstart', beginComposition);
304
+ target.addEventListener('compositionend', endComposition);
305
+
306
+ return {
307
+ element: root,
308
+ get layout() { return layout.id; },
309
+ insert,
310
+ backspace() { return deleteBackward(true); },
311
+ setLayout,
312
+ setTheme,
313
+ setCompact,
314
+ setAutoHamza(enabled) { autoHamza = Boolean(enabled); },
315
+ setSecondaryKeys(enabled) {
316
+ if (destroyed) return;
317
+ secondary = Boolean(enabled);
318
+ renderKeys();
319
+ },
320
+ setPhysicalMapping(enabled) { physical = Boolean(enabled); },
321
+ setVisible(visible) { root.hidden = !visible; },
322
+ destroy() {
323
+ if (destroyed) return;
324
+ destroyed = true;
325
+ root.removeEventListener('click', onClick);
326
+ root.removeEventListener('pointerdown', onPointerDown);
327
+ keys.removeEventListener('keydown', onVirtualKeyDown);
328
+ layoutSelect.removeEventListener('change', onLayoutChange);
329
+ target.removeEventListener('keydown', onKeyDown);
330
+ target.removeEventListener('compositionstart', beginComposition);
331
+ target.removeEventListener('compositionend', endComposition);
332
+ root.remove();
333
+ releaseFont();
334
+ if (appliedDirection !== undefined && target.getAttribute('dir') === appliedDirection) {
335
+ if (originalDirection === null) target.removeAttribute('dir');
336
+ else target.setAttribute('dir', originalDirection);
337
+ }
338
+ },
339
+ };
340
+ }
341
+
342
+ /** Define the optional Web Component. Safe to import the package in Node/SSR. */
343
+ export function defineUyghurKeyboard(name = 'uyghur-keyboard', registry = globalThis.customElements) {
344
+ if (!registry || typeof globalThis.HTMLElement !== 'function') return null;
345
+ if (registry.get(name)) return registry.get(name);
346
+ class UyghurKeyboardElement extends HTMLElement {
347
+ static get observedAttributes() {
348
+ return ['for', 'physical', 'layout', 'auto-hamza', 'secondary-keys', 'compact', 'theme', 'lang'];
349
+ }
350
+ connectedCallback() {
351
+ if (!this.shadowRoot) this.attachShadow({ mode: 'open' });
352
+ this.mountKeyboard();
353
+ this.readyListener = () => this.mountKeyboard();
354
+ if (this.ownerDocument.readyState === 'loading') this.ownerDocument.addEventListener('DOMContentLoaded', this.readyListener, { once: true });
355
+ }
356
+ attributeChangedCallback(name) {
357
+ if (!this.isConnected) return;
358
+ if (!this.controller || name === 'for' || name === 'lang') {
359
+ this.mountKeyboard();
360
+ } else if (name === 'layout') {
361
+ this.controller.setLayout(this.requestedLayout);
362
+ } else if (name === 'theme') {
363
+ this.controller.setTheme(this.getAttribute('theme') === 'dark' ? 'dark' : 'light');
364
+ } else {
365
+ const setters = {
366
+ physical: 'setPhysicalMapping', 'auto-hamza': 'setAutoHamza',
367
+ 'secondary-keys': 'setSecondaryKeys', compact: 'setCompact',
368
+ };
369
+ this.controller[setters[name]](this.hasAttribute(name));
370
+ }
371
+ }
372
+ disconnectedCallback() {
373
+ this.controller?.destroy();
374
+ this.controller = null;
375
+ if (this.readyListener) this.ownerDocument.removeEventListener('DOMContentLoaded', this.readyListener);
376
+ }
377
+ mountKeyboard() {
378
+ this.controller?.destroy();
379
+ this.controller = null;
380
+ this.shadowRoot?.replaceChildren();
381
+ const hostStyle = this.ownerDocument.createElement('style');
382
+ hostStyle.textContent = ':host { display: block; }';
383
+ this.shadowRoot?.appendChild(hostStyle);
384
+ const target = this.ownerDocument.getElementById(this.getAttribute('for') || '');
385
+ if (!target) return;
386
+ this.controller = createKeyboard(target, {
387
+ container: this.shadowRoot,
388
+ layout: this.requestedLayout,
389
+ physical: this.hasAttribute('physical'),
390
+ autoHamza: this.hasAttribute('auto-hamza'),
391
+ secondaryKeys: this.hasAttribute('secondary-keys'),
392
+ compact: this.hasAttribute('compact'),
393
+ theme: this.getAttribute('theme') === 'dark' ? 'dark' : 'light',
394
+ locale: this.getAttribute('lang')?.split('-')[0] === 'en' ? 'en' : 'ug',
395
+ });
396
+ }
397
+ get requestedLayout() {
398
+ const id = this.getAttribute('layout');
399
+ return Object.hasOwn(KEYBOARD_LAYOUTS, id) ? id : 'phonetic';
400
+ }
401
+ get layout() { return this.controller?.layout ?? this.requestedLayout; }
402
+ set layout(id) {
403
+ if (!Object.hasOwn(KEYBOARD_LAYOUTS, id)) throw new TypeError('Unknown keyboard layout: ' + id);
404
+ this.setAttribute('layout', id);
405
+ }
406
+ insert(text) { return this.controller?.insert(text) || false; }
407
+ backspace() { return this.controller?.backspace() || false; }
408
+ }
409
+ registry.define(name, UyghurKeyboardElement);
410
+ return UyghurKeyboardElement;
411
+ }
package/src/layouts.js ADDED
@@ -0,0 +1,103 @@
1
+ /** The complete 32-letter alphabet is represented across these virtual rows. */
2
+ export const KEY_LAYOUT = Object.freeze([
3
+ Object.freeze(['چ', 'ۋ', 'ې', 'ر', 'ت', 'ي', 'ۇ', 'ڭ', 'و', 'پ']),
4
+ Object.freeze(['ھ', 'س', 'د', 'ا', 'ە', 'ى', 'ق', 'ك', 'ل', 'ژ']),
5
+ Object.freeze(['ز', 'ش', 'غ', 'ۈ', 'ب', 'ن', 'م', 'ۆ', 'گ', 'خ', 'ف', 'ج']),
6
+ Object.freeze(['ئ', 'ئا', 'ئە', 'ئې', 'ئى', 'ئو', 'ئۇ', 'ئۆ', 'ئۈ']),
7
+ ]);
8
+
9
+ /** An explicit, optional phonetic map. This is not an operating-system layout. */
10
+ export const PHONETIC_MAP = Object.freeze({
11
+ a: 'ا', b: 'ب', c: 'چ', d: 'د', e: 'ە', f: 'ف', g: 'گ', h: 'ھ', i: 'ى', j: 'ج',
12
+ k: 'ك', l: 'ل', m: 'م', n: 'ن', o: 'و', p: 'پ', q: 'ق', r: 'ر', s: 'س', t: 'ت',
13
+ u: 'ۇ', v: 'ۆ', w: 'ۋ', x: 'خ', y: 'ي', z: 'ز',
14
+ Z: 'ژ', A: 'ئا', E: 'ئە', I: 'ئى', O: 'ئو', U: 'ئۇ', G: 'غ', N: 'ڭ', S: 'ش', V: 'ئۆ', W: 'ئۈ', C: 'ج', Y: 'ې',
15
+ });
16
+
17
+ const arabicExtras = ['ژ', 'ف', 'گ', 'خ', 'ج', 'ۆ', '،', '؛', '؟', '«', '»'];
18
+
19
+ // Functional key positions verified against Microsoft Learn's Uyghur layout
20
+ // (KLID 00010480) and cross-checked against XKB cn(ug). The web keyboard
21
+ // displays key positions from left to right and edits text right to left.
22
+ // The Uyghur character inventory and behavior still need native-speaker review.
23
+ const desktopRows = [
24
+ ['`', ...'1234567890', '-', '='],
25
+ [...'چۋېرتيۇڭوپ', ']', '[', '\\'],
26
+ [...'ھسداەىقكل', '؛', "'"],
27
+ [...'زشغۈبنم', '،', '.', 'ئ'],
28
+ ];
29
+ const desktopShiftedRows = [
30
+ ['~', ...'!@#$%^&*)(', '_', '+'],
31
+ [...'چۋېرتيۇڭوپ', '»', '«', '|'],
32
+ ['ھ', 'س', 'ژ', 'ف', 'گ', 'خ', 'ج', 'ۆ', 'لا', ':', '"'],
33
+ [...'زشغۈبنم', '>', '<', '؟'],
34
+ ];
35
+ const desktopKeys = [..."`1234567890-=qwertyuiop[]\\asdfghjkl;'zxcvbnm,./"];
36
+ const desktopShiftKeys = [...'~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:"ZXCVBNM<>?'];
37
+ const desktopMap = {};
38
+ for (const [keys, values] of [[desktopKeys, desktopRows.flat()], [desktopShiftKeys, desktopShiftedRows.flat()]]) {
39
+ keys.forEach((key, index) => { desktopMap[key] = values[index]; });
40
+ }
41
+
42
+ const latinRows = [
43
+ [...'qwertyuiop'],
44
+ [...'asdfghjkl'],
45
+ [...'zxcvbnm', 'ë', 'ö', 'ü', "'"],
46
+ ];
47
+ const cyrillicRows = [
48
+ [...'йцукенгшщзхъ'],
49
+ [...'фывапролджэ'],
50
+ [...'ячсмитьбюё'],
51
+ [...'әғҗқңөүһ'],
52
+ ];
53
+
54
+ function shiftRows(rows) {
55
+ return rows.map((row) => row.map((key) => key.toUpperCase()));
56
+ }
57
+
58
+ function freezeLayout(layout) {
59
+ for (const rows of [layout.rows, layout.shiftedRows]) {
60
+ if (!rows) continue;
61
+ rows.forEach(Object.freeze);
62
+ Object.freeze(rows);
63
+ }
64
+ Object.freeze(layout.labels);
65
+ Object.freeze(layout.physicalMap);
66
+ Object.freeze(layout.secondary);
67
+ return Object.freeze(layout);
68
+ }
69
+
70
+ export const KEYBOARD_LAYOUTS = Object.freeze({
71
+ phonetic: freezeLayout({
72
+ id: 'phonetic', labels: { en: 'Phonetic', ug: 'ئاھاڭداش' }, lang: 'ug-Arab',
73
+ direction: 'rtl', rows: KEY_LAYOUT, physicalMap: PHONETIC_MAP, secondary: arabicExtras,
74
+ }),
75
+ 'uey-desktop': freezeLayout({
76
+ id: 'uey-desktop', labels: { en: 'Arabic desktop (UEY)', ug: 'ئەرەب يېزىقى (UEY)' }, lang: 'ug-Arab',
77
+ direction: 'rtl', keyDirection: 'ltr', rows: desktopRows, shiftedRows: desktopShiftedRows,
78
+ physicalMap: desktopMap, secondary: arabicExtras, reviewStatus: 'draft',
79
+ }),
80
+ uly: freezeLayout({
81
+ id: 'uly', labels: { en: 'Latin (ULY)', ug: 'لاتىن يېزىقى (ULY)' }, lang: 'ug-Latn',
82
+ direction: 'ltr', rows: latinRows, shiftedRows: shiftRows(latinRows),
83
+ secondary: ['ch', 'gh', 'ng', 'sh', 'zh', '،', '؛', '؟', '«', '»'], reviewStatus: 'draft',
84
+ }),
85
+ usy: freezeLayout({
86
+ id: 'usy', labels: { en: 'Cyrillic (USY)', ug: 'كىرىل يېزىقى (USY)' }, lang: 'ug-Cyrl',
87
+ direction: 'ltr', rows: cyrillicRows, shiftedRows: shiftRows(cyrillicRows),
88
+ secondary: ['،', '؛', '؟', '«', '»'], reviewStatus: 'draft',
89
+ }),
90
+ });
91
+
92
+ // New Uyghur translations and control labels need native-speaker review.
93
+ export const keyboardLabels = {
94
+ en: {
95
+ keyboard: 'Uyghur keyboard', layout: 'Keyboard layout', space: 'Space', backspace: 'Backspace', shift: 'Shift',
96
+ punctuation: { '،': 'Comma', '؛': 'Semicolon', '؟': 'Question mark', '«': 'Left guillemet', '»': 'Right guillemet' },
97
+ },
98
+ ug: {
99
+ keyboard: 'ئۇيغۇرچە كۇنۇپكا تاختىسى', layout: 'كۇنۇپكا تاختىسىنىڭ ئورۇنلاشتۇرۇلۇشى',
100
+ space: 'بوشلۇق', backspace: 'ئالدىنقى ھەرپنى ئۆچۈرۈش', shift: 'چوڭ ھەرپ كۇنۇپكىسى',
101
+ punctuation: { '،': 'پەش', '؛': 'چېكىتلىك پەش', '؟': 'سوئال بەلگىسى', '«': 'سول تىرناق', '»': 'ئوڭ تىرناق' },
102
+ },
103
+ };
@@ -0,0 +1,45 @@
1
+ const directions = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End']);
2
+
3
+ /** Locate the next key using the visual rows, including rows wrapped on phones. */
4
+ export function nextKey(buttonRows, current, key, rtl) {
5
+ if (!directions.has(key)) return undefined;
6
+ const buttons = buttonRows.flat();
7
+ const currentRect = current.getBoundingClientRect?.();
8
+ const rows = [];
9
+ if (currentRect?.width) {
10
+ let top;
11
+ for (const button of buttons) {
12
+ const rect = button.getBoundingClientRect();
13
+ if (top !== rect.top) {
14
+ rows.push([]);
15
+ top = rect.top;
16
+ }
17
+ rows.at(-1).push(button);
18
+ }
19
+ } else {
20
+ rows.push(...buttonRows);
21
+ }
22
+ const rowIndex = rows.findIndex((row) => row.includes(current));
23
+ if (rowIndex < 0) return undefined;
24
+ const row = rows[rowIndex];
25
+ const index = row.indexOf(current);
26
+ if (key === 'Home') return row[0];
27
+ if (key === 'End') return row.at(-1);
28
+ if (key === 'ArrowLeft') return row[index + (rtl ? 1 : -1)] || current;
29
+ if (key === 'ArrowRight') return row[index + (rtl ? -1 : 1)] || current;
30
+ const nextRow = rows[rowIndex + (key === 'ArrowUp' ? -1 : 1)];
31
+ if (!nextRow) return current;
32
+ if (!currentRect?.width) return nextRow[Math.min(index, nextRow.length - 1)];
33
+ const center = currentRect.left + currentRect.width / 2;
34
+ let nearest = current;
35
+ let distance = Infinity;
36
+ for (const button of nextRow) {
37
+ const rect = button.getBoundingClientRect();
38
+ const difference = Math.abs(center - rect.left - rect.width / 2);
39
+ if (difference < distance) {
40
+ nearest = button;
41
+ distance = difference;
42
+ }
43
+ }
44
+ return nearest;
45
+ }