@uyghurcommunity/keyboard 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,738 @@
1
+ // Generated by npm run build. Source available in src/.
2
+ const alkatipFontFace = `@font-face {
3
+ font-family: "ALKATIP Basma";
4
+ src: url("https://db.onlinewebfonts.com/t/3c16518f40da2fc2901f37666c0556a7.woff2") format("woff2"),
5
+ url("https://db.onlinewebfonts.com/t/3c16518f40da2fc2901f37666c0556a7.woff") format("woff"),
6
+ url("https://db.onlinewebfonts.com/t/3c16518f40da2fc2901f37666c0556a7.ttf") format("truetype");
7
+ font-weight: normal;
8
+ font-style: normal;
9
+ font-display: swap;
10
+ }`;
11
+ const alkatipHelperStyles = `.alkatip-basma {
12
+ font-family: "ALKATIP Basma", serif;
13
+ direction: rtl;
14
+ unicode-bidi: embed;
15
+ line-height: 2.2;
16
+ }`;
17
+ const keyboardStyles = `
18
+ ${alkatipHelperStyles}
19
+ .ug-keyboard {
20
+ --_bg:#f1f3ef; --_key:#fff; --_ink:#17362f; --_line:#ccd7cf; --_hover:#e3ede5; --_focus:#087866;
21
+ box-sizing:border-box;
22
+ width:100%;
23
+ padding:12px;
24
+ border:1px solid var(--ug-line,var(--_line));
25
+ border-radius:16px;
26
+ background:var(--ug-bg,var(--_bg));
27
+ color:var(--ug-ink,var(--_ink));
28
+ color-scheme:light;
29
+ font-family:"ALKATIP Basma",Tahoma,Arial,sans-serif;
30
+ line-height:1.5;
31
+ }
32
+ .ug-keyboard[dir="ltr"] { direction:ltr; }
33
+ .ug-keyboard[data-theme="dark"] {
34
+ --_bg:#182722; --_key:#263c33; --_ink:#eef7f2; --_line:#527367; --_hover:#37564a; --_focus:#89e6ca;
35
+ color-scheme:dark;
36
+ }
37
+ .ug-keyboard * { box-sizing:border-box; }
38
+ .ug-keyboard__row {
39
+ display:flex;
40
+ flex-wrap:wrap;
41
+ justify-content:center;
42
+ gap:6px;
43
+ margin-block:6px;
44
+ }
45
+ .ug-keyboard__layout, .ug-keyboard__key {
46
+ min-width:44px;
47
+ min-height:44px;
48
+ border:1px solid var(--ug-line,var(--_line));
49
+ border-radius:8px;
50
+ background:var(--ug-key,var(--_key));
51
+ color:inherit;
52
+ cursor:pointer;
53
+ touch-action:manipulation;
54
+ }
55
+ .ug-keyboard__layout {
56
+ max-width:100%;
57
+ padding:4px 8px;
58
+ font:16px/1.5 "ALKATIP Basma",Tahoma,Arial,sans-serif;
59
+ }
60
+ .ug-keyboard__key {
61
+ display:inline-flex;
62
+ align-items:center;
63
+ justify-content:center;
64
+ flex:1 0 44px;
65
+ padding:4px 2px;
66
+ font:22px/1.5 "ALKATIP Basma",Tahoma,Arial,sans-serif;
67
+ }
68
+ .ug-keyboard__key:hover, .ug-keyboard__key[aria-pressed="true"] { background:var(--ug-hover,var(--_hover)); }
69
+ .ug-keyboard__key:focus-visible, .ug-keyboard__layout:focus-visible {
70
+ outline:2px solid var(--ug-focus,var(--_focus));
71
+ outline-offset:1px;
72
+ z-index:1;
73
+ }
74
+ .ug-keyboard__key[data-action] { font-size:16px; gap:8px; }
75
+ .ug-keyboard__key { position:relative; }
76
+ /* Shift letter (top) and Latin key cap (bottom), as printed on a Uyghur keyboard. */
77
+ .ug-keyboard__shift-legend { position:absolute; top:1px; left:6px; font-size:13px; line-height:1.3; opacity:.72; pointer-events:none; }
78
+ .ug-keyboard__cap { position:absolute; bottom:2px; right:6px; font:10px/1 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; opacity:.45; pointer-events:none; }
79
+ /* A real key press lights up its virtual key. */
80
+ .ug-keyboard__key[data-pressed="true"] { background:var(--ug-focus,var(--_focus)); color:var(--ug-key,var(--_key)); border-color:var(--ug-focus,var(--_focus)); transform:translateY(1px); }
81
+ /* Shift and Delete icons are Uyghur UI drawings (arrow-up, arrow-left), drawn as masks so they follow the text colour. */
82
+ .ug-keyboard__icon { display:inline-block; width:18px; height:18px; flex:none; background-color:currentColor; -webkit-mask:center/contain no-repeat; mask:center/contain no-repeat; }
83
+ .ug-keyboard__icon--shift { -webkit-mask-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M12 19V5m-6 6 6-6 6 6'/%3E%3C/svg%3E"); mask-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M12 19V5m-6 6 6-6 6 6'/%3E%3C/svg%3E"); }
84
+ .ug-keyboard__icon--backspace { -webkit-mask-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M19 12H5m6-6-6 6 6 6'/%3E%3C/svg%3E"); mask-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M19 12H5m6-6-6 6 6 6'/%3E%3C/svg%3E"); }
85
+ .ug-keyboard[data-compact="true"] .ug-keyboard__cap { display:none; }
86
+ .ug-keyboard__key[data-action="space"] { flex-grow:4; }
87
+ .ug-keyboard[data-compact="true"] { padding:6px; }
88
+ .ug-keyboard[data-compact="true"] .ug-keyboard__row { gap:3px; margin-block:3px; }
89
+ .ug-keyboard[data-compact="true"] .ug-keyboard__key { padding:2px; font-size:18px; }
90
+ .ug-keyboard[hidden] { display:none; }
91
+ @media (max-width:420px) {
92
+ .ug-keyboard { padding:6px; }
93
+ .ug-keyboard__row { gap:4px; }
94
+ .ug-keyboard__cap { display:none; }
95
+ .ug-keyboard__shift-legend { left:3px; font-size:11px; }
96
+ .ug-keyboard__key[data-action="backspace"] { font-size:13px; gap:4px; }
97
+ }
98
+ `;
99
+
100
+ /** The complete 32-letter alphabet is represented across these virtual rows. */
101
+ export const KEY_LAYOUT = Object.freeze([
102
+ Object.freeze(['چ', 'ۋ', 'ې', 'ر', 'ت', 'ي', 'ۇ', 'ڭ', 'و', 'پ']),
103
+ Object.freeze(['ھ', 'س', 'د', 'ا', 'ە', 'ى', 'ق', 'ك', 'ل', 'ژ']),
104
+ Object.freeze(['ز', 'ش', 'غ', 'ۈ', 'ب', 'ن', 'م', 'ۆ', 'گ', 'خ', 'ف', 'ج']),
105
+ Object.freeze(['ئ', 'ئا', 'ئە', 'ئې', 'ئى', 'ئو', 'ئۇ', 'ئۆ', 'ئۈ']),
106
+ ]);
107
+
108
+ /** An explicit, optional phonetic map. This is not an operating-system layout. */
109
+ export const PHONETIC_MAP = Object.freeze({
110
+ a: 'ا', b: 'ب', c: 'چ', d: 'د', e: 'ە', f: 'ف', g: 'گ', h: 'ھ', i: 'ى', j: 'ج',
111
+ k: 'ك', l: 'ل', m: 'م', n: 'ن', o: 'و', p: 'پ', q: 'ق', r: 'ر', s: 'س', t: 'ت',
112
+ u: 'ۇ', v: 'ۆ', w: 'ۋ', x: 'خ', y: 'ي', z: 'ز',
113
+ Z: 'ژ', A: 'ئا', E: 'ئە', I: 'ئى', O: 'ئو', U: 'ئۇ', G: 'غ', N: 'ڭ', S: 'ش', V: 'ئۆ', W: 'ئۈ', C: 'ج', Y: 'ې',
114
+ });
115
+
116
+ const arabicExtras = ['ژ', 'ف', 'گ', 'خ', 'ج', 'ۆ', '،', '؛', '؟', '«', '»'];
117
+
118
+ // Functional key positions verified against Microsoft Learn's Uyghur layout
119
+ // (KLID 00010480) and cross-checked against XKB cn(ug). The web keyboard
120
+ // displays key positions from left to right and edits text right to left.
121
+ // The Uyghur character inventory and behavior still need native-speaker review.
122
+ const desktopRows = [
123
+ ['`', ...'1234567890', '-', '='],
124
+ [...'چۋېرتيۇڭوپ', ']', '[', '\\'],
125
+ [...'ھسداەىقكل', '؛', "'"],
126
+ [...'زشغۈبنم', '،', '.', 'ئ'],
127
+ ];
128
+ const desktopShiftedRows = [
129
+ ['~', ...'!@#$%^&*)(', '_', '+'],
130
+ [...'چۋېرتيۇڭوپ', '»', '«', '|'],
131
+ ['ھ', 'س', 'ژ', 'ف', 'گ', 'خ', 'ج', 'ۆ', 'لا', ':', '"'],
132
+ [...'زشغۈبنم', '>', '<', '؟'],
133
+ ];
134
+ const desktopKeys = [..."`1234567890-=qwertyuiop[]\\asdfghjkl;'zxcvbnm,./"];
135
+ const desktopShiftKeys = [...'~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:"ZXCVBNM<>?'];
136
+ // Physical key positions, row by row, as KeyboardEvent.code values, so a real key
137
+ // press can light up the matching virtual key whatever the operating-system layout.
138
+ const desktopCodes = [
139
+ ['Backquote', 'Digit1', 'Digit2', 'Digit3', 'Digit4', 'Digit5', 'Digit6', 'Digit7', 'Digit8', 'Digit9', 'Digit0', 'Minus', 'Equal'],
140
+ [...'QWERTYUIOP'].map((k) => 'Key' + k).concat(['BracketLeft', 'BracketRight', 'Backslash']),
141
+ [...'ASDFGHJKL'].map((k) => 'Key' + k).concat(['Semicolon', 'Quote']),
142
+ [...'ZXCVBNM'].map((k) => 'Key' + k).concat(['Comma', 'Period', 'Slash']),
143
+ ];
144
+ // The Latin key cap printed on each key, as on a Uyghur keyboard sticker.
145
+ const desktopCaps = desktopCodes.map((row) => row.map((code) => (code.startsWith('Key') ? code.slice(3) : '')));
146
+ const desktopMap = {};
147
+ for (const [keys, values] of [[desktopKeys, desktopRows.flat()], [desktopShiftKeys, desktopShiftedRows.flat()]]) {
148
+ keys.forEach((key, index) => { desktopMap[key] = values[index]; });
149
+ }
150
+
151
+ const latinRows = [
152
+ [...'qwertyuiop'],
153
+ [...'asdfghjkl'],
154
+ [...'zxcvbnm', 'ë', 'ö', 'ü', "'"],
155
+ ];
156
+ const cyrillicRows = [
157
+ [...'йцукенгшщзхъ'],
158
+ [...'фывапролджэ'],
159
+ [...'ячсмитьбюё'],
160
+ [...'әғҗқңөүһ'],
161
+ ];
162
+
163
+ function shiftRows(rows) {
164
+ return rows.map((row) => row.map((key) => key.toUpperCase()));
165
+ }
166
+
167
+ function freezeLayout(layout) {
168
+ for (const rows of [layout.rows, layout.shiftedRows, layout.keyCodes, layout.keyCaps]) {
169
+ if (!rows) continue;
170
+ rows.forEach(Object.freeze);
171
+ Object.freeze(rows);
172
+ }
173
+ Object.freeze(layout.labels);
174
+ Object.freeze(layout.physicalMap);
175
+ Object.freeze(layout.secondary);
176
+ return Object.freeze(layout);
177
+ }
178
+
179
+ /**
180
+ * The standard Uyghur computer layout is the default: the one built into Windows
181
+ * (KLID 00010480), Linux (XKB cn(ug)) and macOS, and taught by typing trainers
182
+ * such as Konupka. Its letters are checked key by key in the tests.
183
+ */
184
+ export const DEFAULT_LAYOUT = 'uey-desktop';
185
+
186
+ export const KEYBOARD_LAYOUTS = Object.freeze({
187
+ 'uey-desktop': freezeLayout({
188
+ id: 'uey-desktop', labels: { en: 'Standard Uyghur (UEY)', ug: 'ئۆلچەملىك ئۇيغۇرچە (UEY)' }, lang: 'ug-Arab',
189
+ direction: 'rtl', keyDirection: 'ltr', rows: desktopRows, shiftedRows: desktopShiftedRows,
190
+ physicalMap: desktopMap, secondary: arabicExtras, reviewStatus: 'draft',
191
+ keyCodes: desktopCodes, keyCaps: desktopCaps,
192
+ }),
193
+ phonetic: freezeLayout({
194
+ id: 'phonetic', labels: { en: 'Phonetic', ug: 'ئاھاڭداش' }, lang: 'ug-Arab',
195
+ direction: 'rtl', rows: KEY_LAYOUT, physicalMap: PHONETIC_MAP, secondary: arabicExtras,
196
+ }),
197
+ uly: freezeLayout({
198
+ id: 'uly', labels: { en: 'Latin (ULY)', ug: 'لاتىن يېزىقى (ULY)' }, lang: 'ug-Latn',
199
+ direction: 'ltr', rows: latinRows, shiftedRows: shiftRows(latinRows),
200
+ secondary: ['ch', 'gh', 'ng', 'sh', 'zh', '،', '؛', '؟', '«', '»'], reviewStatus: 'draft',
201
+ }),
202
+ usy: freezeLayout({
203
+ id: 'usy', labels: { en: 'Cyrillic (USY)', ug: 'كىرىل يېزىقى (USY)' }, lang: 'ug-Cyrl',
204
+ direction: 'ltr', rows: cyrillicRows, shiftedRows: shiftRows(cyrillicRows),
205
+ secondary: ['،', '؛', '؟', '«', '»'], reviewStatus: 'draft',
206
+ }),
207
+ });
208
+
209
+ // New Uyghur translations and control labels need native-speaker review.
210
+ const keyboardLabels = {
211
+ en: {
212
+ keyboard: 'Uyghur keyboard', layout: 'Keyboard layout', space: 'Space', backspace: 'Backspace', shift: 'Shift',
213
+ punctuation: { '،': 'Comma', '؛': 'Semicolon', '؟': 'Question mark', '«': 'Left guillemet', '»': 'Right guillemet' },
214
+ },
215
+ ug: {
216
+ keyboard: 'ئۇيغۇرچە كۇنۇپكا تاختىسى', layout: 'كۇنۇپكا تاختىسىنىڭ ئورۇنلاشتۇرۇلۇشى',
217
+ space: 'بوشلۇق', backspace: 'ئالدىنقى ھەرپنى ئۆچۈرۈش', shift: 'چوڭ ھەرپ كۇنۇپكىسى',
218
+ punctuation: { '،': 'پەش', '؛': 'چېكىتلىك پەش', '؟': 'سوئال بەلگىسى', '«': 'سول تىرناق', '»': 'ئوڭ تىرناق' },
219
+ },
220
+ };
221
+
222
+ const directions = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End']);
223
+
224
+ /** Locate the next key using the visual rows, including rows wrapped on phones. */
225
+ function nextKey(buttonRows, current, key, rtl) {
226
+ if (!directions.has(key)) return undefined;
227
+ const buttons = buttonRows.flat();
228
+ const currentRect = current.getBoundingClientRect?.();
229
+ const rows = [];
230
+ if (currentRect?.width) {
231
+ let top;
232
+ for (const button of buttons) {
233
+ const rect = button.getBoundingClientRect();
234
+ if (top !== rect.top) {
235
+ rows.push([]);
236
+ top = rect.top;
237
+ }
238
+ rows.at(-1).push(button);
239
+ }
240
+ } else {
241
+ rows.push(...buttonRows);
242
+ }
243
+ const rowIndex = rows.findIndex((row) => row.includes(current));
244
+ if (rowIndex < 0) return undefined;
245
+ const row = rows[rowIndex];
246
+ const index = row.indexOf(current);
247
+ if (key === 'Home') return row[0];
248
+ if (key === 'End') return row.at(-1);
249
+ if (key === 'ArrowLeft') return row[index + (rtl ? 1 : -1)] || current;
250
+ if (key === 'ArrowRight') return row[index + (rtl ? -1 : 1)] || current;
251
+ const nextRow = rows[rowIndex + (key === 'ArrowUp' ? -1 : 1)];
252
+ if (!nextRow) return current;
253
+ if (!currentRect?.width) return nextRow[Math.min(index, nextRow.length - 1)];
254
+ const center = currentRect.left + currentRect.width / 2;
255
+ let nearest = current;
256
+ let distance = Infinity;
257
+ for (const button of nextRow) {
258
+ const rect = button.getBoundingClientRect();
259
+ const difference = Math.abs(center - rect.left - rect.width / 2);
260
+ if (difference < distance) {
261
+ nearest = button;
262
+ distance = difference;
263
+ }
264
+ }
265
+ return nearest;
266
+ }
267
+
268
+
269
+ const fontStyleId = 'uyghur-keyboard-alkatip-font';
270
+ const fontRegistrations = new WeakMap();
271
+ function acquireFont(document) {
272
+ let registration = fontRegistrations.get(document);
273
+ if (!registration) {
274
+ const parent = document.head || document.documentElement;
275
+ if (!parent) return () => {};
276
+ let element = document.getElementById(fontStyleId);
277
+ const owned = !element;
278
+ if (!element) {
279
+ element = document.createElement('style');
280
+ element.id = fontStyleId;
281
+ element.textContent = alkatipFontFace + '\n' + alkatipHelperStyles;
282
+ parent.appendChild(element);
283
+ }
284
+ registration = { element, owned, count: 0 };
285
+ fontRegistrations.set(document, registration);
286
+ }
287
+ registration.count++;
288
+ let released = false;
289
+ return () => {
290
+ if (released) return;
291
+ released = true;
292
+ if (--registration.count === 0) {
293
+ if (registration.owned) registration.element.remove();
294
+ fontRegistrations.delete(document);
295
+ }
296
+ };
297
+ }
298
+
299
+ function selection(value, start, end) {
300
+ const length = value.length;
301
+ const first = Number.isFinite(start) ? Math.max(0, Math.min(length, Math.trunc(start))) : length;
302
+ const last = Number.isFinite(end) ? Math.max(0, Math.min(length, Math.trunc(end))) : first;
303
+ return [Math.min(first, last), Math.max(first, last)];
304
+ }
305
+
306
+ /** Pure UTF-16 selection replacement, using the same offsets as HTML inputs. */
307
+ export function replaceSelection(value, start, end, text) {
308
+ if (typeof value !== 'string' || typeof text !== 'string') throw new TypeError('value and text must be strings');
309
+ const [a, b] = selection(value, start, end);
310
+ return { value: value.slice(0, a) + text + value.slice(b), start: a + text.length, end: a + text.length };
311
+ }
312
+
313
+ /** Remove a selected range or the preceding complete grapheme. */
314
+ export function deleteSelectionBackward(value, start, end) {
315
+ if (typeof value !== 'string') throw new TypeError('value must be a string');
316
+ const [a, b] = selection(value, start, end);
317
+ if (a !== b) return replaceSelection(value, a, b, '');
318
+ if (!a) return { value, start: 0, end: 0 };
319
+ let previous = 0;
320
+ if (typeof Intl.Segmenter === 'function') {
321
+ for (const part of new Intl.Segmenter('ug', { granularity: 'grapheme' }).segment(value)) {
322
+ if (part.index >= a) break;
323
+ previous = part.index;
324
+ }
325
+ } else {
326
+ previous = a - 1;
327
+ const code = value.charCodeAt(previous);
328
+ if (previous && code >= 0xdc00 && code <= 0xdfff) previous--;
329
+ }
330
+ return replaceSelection(value, previous, a, '');
331
+ }
332
+
333
+ function makeEvent(target, name, type, text, cancelable) {
334
+ const view = target.ownerDocument?.defaultView || globalThis;
335
+ if (typeof view.InputEvent === 'function') {
336
+ return new view.InputEvent(name, { bubbles: true, composed: true, cancelable, inputType: type, data: text });
337
+ }
338
+ const event = new view.Event(name, { bubbles: true, composed: true, cancelable });
339
+ Object.defineProperties(event, { inputType: { value: type }, data: { value: text } });
340
+ return event;
341
+ }
342
+
343
+ /** Mount a virtual keyboard next to a text input/textarea, or in options.container. */
344
+ export function createKeyboard(target, options = {}) {
345
+ if (!target || typeof target.value !== 'string' || typeof target.setSelectionRange !== 'function' || !target.ownerDocument) {
346
+ throw new TypeError('createKeyboard needs a text input or textarea');
347
+ }
348
+ if (target.tagName === 'INPUT' && !['text', 'search', 'tel', 'url', 'password'].includes(target.type || 'text')) {
349
+ throw new TypeError('The input type must support text selection');
350
+ }
351
+ const layouts = new Map(Object.entries(KEYBOARD_LAYOUTS));
352
+ for (const custom of options.layouts || []) {
353
+ if (!custom.id || layouts.has(custom.id) || !custom.rows?.some((row) => row.length) ||
354
+ !['rtl', 'ltr'].includes(custom.direction)) {
355
+ throw new TypeError('Custom layouts need a unique id, at least one key, and a valid direction');
356
+ }
357
+ layouts.set(custom.id, custom);
358
+ }
359
+ let layout = layouts.get(options.layout ?? DEFAULT_LAYOUT);
360
+ if (!layout) throw new TypeError('Unknown keyboard layout: ' + options.layout);
361
+ const direction = options.direction;
362
+ if (direction && !['rtl', 'ltr', 'auto', 'preserve'].includes(direction)) {
363
+ throw new TypeError('direction must be rtl, ltr, auto, or preserve');
364
+ }
365
+ const originalDirection = target.getAttribute('dir');
366
+ let appliedDirection;
367
+ const doc = target.ownerDocument;
368
+ const locale = options.locale === 'en' ? 'en' : 'ug';
369
+ const labels = keyboardLabels[locale];
370
+ const root = doc.createElement('div');
371
+ root.className = 'ug-keyboard alkatip-basma';
372
+ root.lang = locale;
373
+ root.dir = locale === 'ug' ? 'rtl' : 'ltr';
374
+ root.setAttribute('role', 'group');
375
+ root.setAttribute('aria-label', options.label || labels.keyboard);
376
+ const style = doc.createElement('style');
377
+ style.textContent = keyboardStyles;
378
+ root.appendChild(style);
379
+ let physical = options.physical === true;
380
+ let autoHamza = options.autoHamza === true;
381
+ let secondary = options.secondaryKeys === true;
382
+ // Shift letters and Latin key caps on each key, where the layout has them.
383
+ let legends = options.legends !== false;
384
+ const pressTimers = new Map();
385
+ let destroyed = false;
386
+ let composing = false;
387
+ let shifted = false;
388
+ let buttonRows = [];
389
+ let activeButton;
390
+
391
+ const layoutSelect = doc.createElement('select');
392
+ layoutSelect.className = 'ug-keyboard__layout';
393
+ layoutSelect.setAttribute('aria-label', labels.layout);
394
+ for (const [id, item] of layouts) {
395
+ const option = doc.createElement('option');
396
+ option.value = id;
397
+ option.textContent = item.labels[locale] || item.labels.en;
398
+ layoutSelect.appendChild(option);
399
+ }
400
+ layoutSelect.value = layout.id;
401
+ root.appendChild(layoutSelect);
402
+ const keys = doc.createElement('div');
403
+ keys.className = 'ug-keyboard__keys';
404
+ root.appendChild(keys);
405
+
406
+ function setTargetDirection() {
407
+ const nextDirection = direction || layout.direction;
408
+ if (nextDirection === 'preserve') return;
409
+ if (appliedDirection !== undefined && target.getAttribute('dir') !== appliedDirection) return;
410
+ target.setAttribute('dir', nextDirection);
411
+ appliedDirection = nextDirection;
412
+ }
413
+
414
+ function legend(className, text) {
415
+ const span = doc.createElement('span');
416
+ span.className = className;
417
+ span.textContent = text;
418
+ span.setAttribute('aria-hidden', 'true');
419
+ return span;
420
+ }
421
+
422
+ function keyButton(text, action, { shiftText, cap, code } = {}) {
423
+ const button = doc.createElement('button');
424
+ button.type = 'button';
425
+ button.className = 'ug-keyboard__key';
426
+ button.textContent = text;
427
+ button.tabIndex = -1;
428
+ if (action) button.dataset.action = action;
429
+ else button.dataset.text = text;
430
+ if (code) button.dataset.code = code;
431
+ if (legends && shiftText) button.appendChild(legend('ug-keyboard__shift-legend', shiftText));
432
+ if (legends && cap) button.appendChild(legend('ug-keyboard__cap', cap));
433
+ if (action === 'shift' || action === 'backspace') button.insertBefore(legend(`ug-keyboard__icon ug-keyboard__icon--${action}`, ''), button.firstChild ?? null);
434
+ const localized = labels[action] || labels.punctuation[text];
435
+ button.lang = localized ? locale : layout.lang;
436
+ button.setAttribute('aria-label', localized || text);
437
+ if (action === 'shift') button.setAttribute('aria-pressed', String(shifted));
438
+ return button;
439
+ }
440
+
441
+ function focusedElement() {
442
+ return root.getRootNode?.().activeElement || doc.activeElement;
443
+ }
444
+
445
+ function setActiveButton(button) {
446
+ if (activeButton) activeButton.tabIndex = -1;
447
+ activeButton = button;
448
+ activeButton.tabIndex = 0;
449
+ }
450
+
451
+ function renderKeys() {
452
+ const index = buttonRows.flat().indexOf(activeButton);
453
+ const restoreFocus = keys.contains(focusedElement());
454
+ keys.dir = layout.keyDirection || layout.direction;
455
+ const current = shifted ? layout.shiftedRows : layout.rows;
456
+ const other = shifted ? layout.rows : layout.shiftedRows;
457
+ const rows = current.map((row, r) => row.map((text, k) => keyButton(text, undefined, {
458
+ // Show the Shift letter only where Shift gives a different letter (D: د and ژ).
459
+ shiftText: !shifted && other?.[r]?.[k] && other[r][k] !== text ? other[r][k] : undefined,
460
+ cap: layout.keyCaps?.[r]?.[k],
461
+ code: layout.keyCodes?.[r]?.[k],
462
+ })));
463
+ if (secondary && layout.secondary?.length) rows.push(layout.secondary.map((text) => keyButton(text)));
464
+ const actions = [keyButton(labels.space, 'space'), keyButton(locale === 'ug' ? 'ئۆچۈرۈش' : 'Delete', 'backspace')];
465
+ if (layout.shiftedRows) actions.unshift(keyButton('', 'shift'));
466
+ rows.push(actions);
467
+ buttonRows = rows;
468
+ keys.replaceChildren();
469
+ for (const buttons of rows) {
470
+ const row = doc.createElement('div');
471
+ row.className = 'ug-keyboard__row';
472
+ for (const button of buttons) row.appendChild(button);
473
+ keys.appendChild(row);
474
+ }
475
+ const buttons = rows.flat();
476
+ setActiveButton(buttons[Math.min(Math.max(index, 0), buttons.length - 1)]);
477
+ if (restoreFocus) activeButton.focus();
478
+ }
479
+
480
+ function setLayout(id) {
481
+ const next = layouts.get(id);
482
+ if (!next) throw new TypeError('Unknown keyboard layout: ' + id);
483
+ if (destroyed || next === layout) return;
484
+ layout = next;
485
+ shifted = false;
486
+ layoutSelect.value = id;
487
+ setTargetDirection();
488
+ renderKeys();
489
+ }
490
+
491
+ function setTheme(theme) {
492
+ if (!['light', 'dark'].includes(theme)) throw new TypeError('theme must be light or dark');
493
+ root.dataset.theme = theme;
494
+ }
495
+
496
+ function setCompact(enabled) {
497
+ root.dataset.compact = String(Boolean(enabled));
498
+ }
499
+
500
+ setTheme(options.theme ?? 'light');
501
+ setCompact(options.compact);
502
+ renderKeys();
503
+
504
+ if (options.container) options.container.appendChild(root);
505
+ else if (target.parentNode) target.parentNode.insertBefore(root, target.nextSibling);
506
+ else throw new Error('Attach the target to a document or provide a container');
507
+ // Font faces must be registered in the owner document, including when keys
508
+ // themselves live in a Web Component's shadow root.
509
+ const releaseFont = acquireFont(doc);
510
+ setTargetDirection();
511
+
512
+ function commit(result, inputType, text, focusTarget = true) {
513
+ if (destroyed || target.disabled || target.readOnly || composing) return false;
514
+ if (!target.dispatchEvent(makeEvent(target, 'beforeinput', inputType, text, true))) return false;
515
+ target.value = result.value;
516
+ if (focusTarget) target.focus({ preventScroll: true });
517
+ target.setSelectionRange(result.start, result.end);
518
+ target.dispatchEvent(makeEvent(target, 'input', inputType, text, false));
519
+ const view = doc.defaultView || globalThis;
520
+ if (typeof view.CustomEvent === 'function') {
521
+ root.dispatchEvent(new view.CustomEvent('uyghur-input', { bubbles: true, composed: true, detail: { value: target.value, inputType, text } }));
522
+ }
523
+ return true;
524
+ }
525
+ function insert(text) {
526
+ if (typeof text !== 'string') throw new TypeError('insert expects a string');
527
+ return insertText(text, true);
528
+ }
529
+ function insertText(text, focusTarget) {
530
+ const result = replaceSelection(target.value, target.selectionStart, target.selectionEnd, text);
531
+ return commit(result, 'insertText', text, focusTarget);
532
+ }
533
+ function deleteBackward(focusTarget) {
534
+ const result = deleteSelectionBackward(target.value, target.selectionStart, target.selectionEnd);
535
+ return commit(result, 'deleteContentBackward', null, focusTarget);
536
+ }
537
+ function withHamza(text) {
538
+ if (!autoHamza || layout.lang !== 'ug-Arab' || !/^[اەېىوۇۆۈ]$/u.test(text)) return text;
539
+ const [start] = selection(target.value, target.selectionStart, target.selectionEnd);
540
+ const insideWord = /[\p{L}\p{M}\p{N}\p{Pc}\u200c\u200d]$/u.test(target.value.slice(0, start));
541
+ return insideWord ? text : 'ئ' + text;
542
+ }
543
+ function onClick(event) {
544
+ const button = event.target.closest?.('button.ug-keyboard__key');
545
+ if (!button || !keys.contains(button)) return;
546
+ setActiveButton(button);
547
+ const action = button.dataset.action;
548
+ const focusTarget = event.detail !== 0 || focusedElement() !== button;
549
+ if (action === 'shift') {
550
+ shifted = !shifted;
551
+ renderKeys();
552
+ } else if (action === 'backspace') {
553
+ deleteBackward(focusTarget);
554
+ } else {
555
+ insertText(withHamza(action === 'space' ? ' ' : button.dataset.text), focusTarget);
556
+ }
557
+ }
558
+ function onPointerDown(event) {
559
+ // Keep the selection in the target while clicking the virtual keys.
560
+ if (event.target.closest?.('button.ug-keyboard__key')) event.preventDefault();
561
+ }
562
+ function onVirtualKeyDown(event) {
563
+ if (event.altKey || event.ctrlKey || event.metaKey || event.defaultPrevented) return;
564
+ const button = nextKey(buttonRows, event.target, event.key, keys.dir === 'rtl');
565
+ if (!button) return;
566
+ event.preventDefault();
567
+ setActiveButton(button);
568
+ button.focus();
569
+ }
570
+ /** The virtual key a physical key press corresponds to: by position first, then by character. */
571
+ function buttonFor(event) {
572
+ const all = buttonRows.flat();
573
+ if (event.code) {
574
+ const byCode = all.find((button) => button.dataset.code === event.code);
575
+ if (byCode) return byCode;
576
+ }
577
+ if (event.key === ' ') return all.find((button) => button.dataset.action === 'space');
578
+ if (event.key === 'Backspace') return all.find((button) => button.dataset.action === 'backspace');
579
+ if (event.key === 'Shift') return all.find((button) => button.dataset.action === 'shift');
580
+ const map = layout.physicalMap;
581
+ const char = map && Object.hasOwn(map, event.key) ? map[event.key] : event.key;
582
+ return all.find((button) => button.dataset.text === char || button.dataset.text === event.key);
583
+ }
584
+ function release(button) {
585
+ clearTimeout(pressTimers.get(button));
586
+ pressTimers.delete(button);
587
+ if (button.dataset) delete button.dataset.pressed;
588
+ }
589
+ function press(event) {
590
+ const button = buttonFor(event);
591
+ if (!button) return;
592
+ release(button);
593
+ button.dataset.pressed = 'true';
594
+ // Keyboards that never send keyup (some mobile IMEs) still clear the highlight.
595
+ pressTimers.set(button, setTimeout(() => release(button), 600));
596
+ }
597
+ function onKeyUp(event) {
598
+ const button = buttonFor(event);
599
+ if (button) release(button);
600
+ }
601
+ function onKeyDown(event) {
602
+ if (composing || event.isComposing || event.defaultPrevented || event.ctrlKey || event.metaKey || event.altKey) return;
603
+ press(event);
604
+ const map = layout.physicalMap;
605
+ const mapped = physical && map && Object.hasOwn(map, event.key) ? map[event.key] : undefined;
606
+ const text = withHamza(mapped ?? event.key);
607
+ if (mapped !== undefined || text !== event.key) {
608
+ event.preventDefault();
609
+ insertText(text, true);
610
+ }
611
+ }
612
+ const onLayoutChange = () => setLayout(layoutSelect.value);
613
+ const beginComposition = () => { composing = true; };
614
+ const endComposition = () => { composing = false; };
615
+ root.addEventListener('click', onClick);
616
+ root.addEventListener('pointerdown', onPointerDown);
617
+ keys.addEventListener('keydown', onVirtualKeyDown);
618
+ layoutSelect.addEventListener('change', onLayoutChange);
619
+ target.addEventListener('keydown', onKeyDown);
620
+ target.addEventListener('keyup', onKeyUp);
621
+ target.addEventListener('compositionstart', beginComposition);
622
+ target.addEventListener('compositionend', endComposition);
623
+
624
+ return {
625
+ element: root,
626
+ get layout() { return layout.id; },
627
+ insert,
628
+ backspace() { return deleteBackward(true); },
629
+ setLayout,
630
+ setTheme,
631
+ setCompact,
632
+ setAutoHamza(enabled) { autoHamza = Boolean(enabled); },
633
+ setSecondaryKeys(enabled) {
634
+ if (destroyed) return;
635
+ secondary = Boolean(enabled);
636
+ renderKeys();
637
+ },
638
+ setPhysicalMapping(enabled) { physical = Boolean(enabled); },
639
+ setLegends(enabled) {
640
+ if (destroyed) return;
641
+ legends = Boolean(enabled);
642
+ renderKeys();
643
+ },
644
+ setVisible(visible) { root.hidden = !visible; },
645
+ destroy() {
646
+ if (destroyed) return;
647
+ destroyed = true;
648
+ root.removeEventListener('click', onClick);
649
+ root.removeEventListener('pointerdown', onPointerDown);
650
+ keys.removeEventListener('keydown', onVirtualKeyDown);
651
+ layoutSelect.removeEventListener('change', onLayoutChange);
652
+ target.removeEventListener('keydown', onKeyDown);
653
+ target.removeEventListener('keyup', onKeyUp);
654
+ for (const button of [...pressTimers.keys()]) release(button);
655
+ target.removeEventListener('compositionstart', beginComposition);
656
+ target.removeEventListener('compositionend', endComposition);
657
+ root.remove();
658
+ releaseFont();
659
+ if (appliedDirection !== undefined && target.getAttribute('dir') === appliedDirection) {
660
+ if (originalDirection === null) target.removeAttribute('dir');
661
+ else target.setAttribute('dir', originalDirection);
662
+ }
663
+ },
664
+ };
665
+ }
666
+
667
+ /** Define the optional Web Component. Safe to import the package in Node/SSR. */
668
+ export function defineUyghurKeyboard(name = 'uyghur-keyboard', registry = globalThis.customElements) {
669
+ if (!registry || typeof globalThis.HTMLElement !== 'function') return null;
670
+ if (registry.get(name)) return registry.get(name);
671
+ class UyghurKeyboardElement extends HTMLElement {
672
+ static get observedAttributes() {
673
+ return ['for', 'physical', 'layout', 'auto-hamza', 'secondary-keys', 'compact', 'theme', 'lang'];
674
+ }
675
+ connectedCallback() {
676
+ if (!this.shadowRoot) this.attachShadow({ mode: 'open' });
677
+ this.mountKeyboard();
678
+ this.readyListener = () => this.mountKeyboard();
679
+ if (this.ownerDocument.readyState === 'loading') this.ownerDocument.addEventListener('DOMContentLoaded', this.readyListener, { once: true });
680
+ }
681
+ attributeChangedCallback(name) {
682
+ if (!this.isConnected) return;
683
+ if (!this.controller || name === 'for' || name === 'lang') {
684
+ this.mountKeyboard();
685
+ } else if (name === 'layout') {
686
+ this.controller.setLayout(this.requestedLayout);
687
+ } else if (name === 'theme') {
688
+ this.controller.setTheme(this.getAttribute('theme') === 'dark' ? 'dark' : 'light');
689
+ } else {
690
+ const setters = {
691
+ physical: 'setPhysicalMapping', 'auto-hamza': 'setAutoHamza',
692
+ 'secondary-keys': 'setSecondaryKeys', compact: 'setCompact',
693
+ };
694
+ this.controller[setters[name]](this.hasAttribute(name));
695
+ }
696
+ }
697
+ disconnectedCallback() {
698
+ this.controller?.destroy();
699
+ this.controller = null;
700
+ if (this.readyListener) this.ownerDocument.removeEventListener('DOMContentLoaded', this.readyListener);
701
+ }
702
+ mountKeyboard() {
703
+ this.controller?.destroy();
704
+ this.controller = null;
705
+ this.shadowRoot?.replaceChildren();
706
+ const hostStyle = this.ownerDocument.createElement('style');
707
+ hostStyle.textContent = ':host { display: block; }';
708
+ this.shadowRoot?.appendChild(hostStyle);
709
+ const target = this.ownerDocument.getElementById(this.getAttribute('for') || '');
710
+ if (!target) return;
711
+ this.controller = createKeyboard(target, {
712
+ container: this.shadowRoot,
713
+ layout: this.requestedLayout,
714
+ physical: this.hasAttribute('physical'),
715
+ autoHamza: this.hasAttribute('auto-hamza'),
716
+ secondaryKeys: this.hasAttribute('secondary-keys'),
717
+ compact: this.hasAttribute('compact'),
718
+ theme: this.getAttribute('theme') === 'dark' ? 'dark' : 'light',
719
+ locale: this.getAttribute('lang')?.split('-')[0] === 'en' ? 'en' : 'ug',
720
+ });
721
+ }
722
+ get requestedLayout() {
723
+ const id = this.getAttribute('layout');
724
+ return Object.hasOwn(KEYBOARD_LAYOUTS, id) ? id : DEFAULT_LAYOUT;
725
+ }
726
+ get layout() { return this.controller?.layout ?? this.requestedLayout; }
727
+ set layout(id) {
728
+ if (!Object.hasOwn(KEYBOARD_LAYOUTS, id)) throw new TypeError('Unknown keyboard layout: ' + id);
729
+ this.setAttribute('layout', id);
730
+ }
731
+ insert(text) { return this.controller?.insert(text) || false; }
732
+ backspace() { return this.controller?.backspace() || false; }
733
+ }
734
+ registry.define(name, UyghurKeyboardElement);
735
+ return UyghurKeyboardElement;
736
+ }
737
+
738
+ defineUyghurKeyboard();