@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.
- package/CHANGELOG.md +19 -0
- package/LICENSE +21 -0
- package/README.md +213 -2
- package/dist/uyghur-keyboard.js +738 -0
- package/docs/layouts.md +43 -0
- package/package.json +26 -4
- package/src/element.d.ts +1 -0
- package/src/element.js +3 -0
- package/src/index.d.ts +65 -0
- package/src/index.js +473 -0
- package/src/layouts.js +121 -0
- package/src/navigation.js +45 -0
- package/src/style.js +97 -0
package/docs/layouts.md
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# Keyboard layouts
|
|
2
|
+
|
|
3
|
+
| ID | Virtual keyboard | Optional physical mapping |
|
|
4
|
+
| --- | --- | --- |
|
|
5
|
+
| `uey-desktop` (default) | **The standard Uyghur computer layout**, in ANSI desktop key order, with a Shift layer | QWERTY key values mapped to Arabic-script characters |
|
|
6
|
+
| `phonetic` | The original Arabic-script rows and explicit hamza-vowel keys; not an operating-system layout | The original `PHONETIC_MAP` |
|
|
7
|
+
| `uly` | Latin letters, including `ë`, `ö`, and `ü`, and an apostrophe | The browser or operating system provides the physical input |
|
|
8
|
+
| `usy` | Cyrillic letters, including the Uyghur-specific keys, with space for letters used in loanwords | The browser or operating system provides the physical input |
|
|
9
|
+
|
|
10
|
+
The `uey-desktop` implementation uses the base and Shift positions of the printable ANSI rows, including the number and punctuation rows. It leaves operating-system modifiers, Caps Lock, AltGr, the numeric keypad and shortcuts to the host browser. The physical mapping reads `KeyboardEvent.key` from a US QWERTY input source. The virtual Shift button stays active until pressed again or the user switches layouts. Sources for the key positions are [Microsoft Learn's Uyghur keyboard, KLID 00010480](https://learn.microsoft.com/en-us/globalization/keyboards/kbdughr1) and [the XKB `cn(ug)` layout](https://github.com/GalliumOS/xkeyboard-config/blob/master/symbols/cn). Where the sources differ in shifted punctuation, the desktop layout follows the Microsoft reference. Its letters also match the reference sheet used by the Konupka typing trainer key for key, and a test pins every letter position. Since 0.3.0 it is the default layout, so text typed on the virtual keyboard uses the same key positions as a Uyghur keyboard on a computer.
|
|
11
|
+
|
|
12
|
+
The Latin and Cyrillic layouts are original virtual arrangements. Their letter inventories and key placement, the desktop character assignments, the optional secondary keys and their order, the automatic hamza behavior, the new Uyghur accessibility and layout labels, and the new test examples need native-speaker review. The three new built-in layouts carry `reviewStatus: 'draft'`.
|
|
13
|
+
|
|
14
|
+
## Adding a layout
|
|
15
|
+
|
|
16
|
+
Pass a plain data object through `layouts` and set its ID through `layout` or `keyboard.setLayout(id)`. Custom layouts appear alongside built-in layouts in the selector.
|
|
17
|
+
|
|
18
|
+
```js
|
|
19
|
+
const keyboard = createKeyboard(document.querySelector('textarea'), {
|
|
20
|
+
locale: 'en',
|
|
21
|
+
layout: 'symbols',
|
|
22
|
+
layouts: [{
|
|
23
|
+
id: 'symbols',
|
|
24
|
+
labels: { en: 'Symbols' },
|
|
25
|
+
lang: 'en',
|
|
26
|
+
direction: 'ltr',
|
|
27
|
+
rows: [['+', '-', '×', '÷']],
|
|
28
|
+
physicalMap: { '*': '×', '/': '÷' },
|
|
29
|
+
}],
|
|
30
|
+
});
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
- Give each layout a unique `id` and a label in English. An Uyghur label can be supplied as `labels.ug`.
|
|
34
|
+
- `lang` is the BCP 47 language or language-script tag for the keys. The text direction follows `direction`, unless the embedder supplies a `direction` option. `keyDirection` optionally overrides the visual key order.
|
|
35
|
+
- `rows` and optional `shiftedRows` contain button text. A button inserts the full string. A `shiftedRows` table adds a virtual Shift control.
|
|
36
|
+
- `physicalMap` maps exact key values to output strings when `physical` is enabled. The optional `secondary` row is displayed when `secondaryKeys` is enabled.
|
|
37
|
+
- Set `reviewStatus: 'draft'` on new Uyghur layouts that still need native-speaker review and document the source of the data.
|
|
38
|
+
|
|
39
|
+
## Keyboard and touch behavior
|
|
40
|
+
|
|
41
|
+
Tab moves to the layout selector and then the active key. The arrow keys move within and between visible rows. Home and End go to the first and last keys in the current row. Enter and Space activate a key and retain focus on it. Tab and Shift+Tab can leave the key group. Pointer activation returns focus to the editing target so typing can continue there.
|
|
42
|
+
|
|
43
|
+
Keys wrap in narrow containers and have a minimum width and height of 44 CSS pixels in both standard and compact mode. Controls use a minimum text size of 16 CSS pixels. For iOS Safari, set your own input or textarea font size to at least 16 CSS pixels too, as in the [README examples](../README.md#embed-with-one-script). Use a normal responsive viewport and leave pinch zoom available.
|
package/package.json
CHANGED
|
@@ -1,6 +1,28 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@uyghurcommunity/keyboard",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.3.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
|
+
}
|
package/src/element.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { defineUyghurKeyboard } from './index.js';
|
package/src/element.js
ADDED
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
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
|
+
/** KeyboardEvent.code for each key, parallel to rows; lets real key presses light up virtual keys. */
|
|
17
|
+
readonly keyCodes?: readonly (readonly string[])[];
|
|
18
|
+
/** Latin key cap printed on each key, parallel to rows. */
|
|
19
|
+
readonly keyCaps?: readonly (readonly string[])[];
|
|
20
|
+
}
|
|
21
|
+
export interface KeyboardOptions {
|
|
22
|
+
container?: HTMLElement | ShadowRoot;
|
|
23
|
+
physical?: boolean;
|
|
24
|
+
direction?: 'rtl' | 'ltr' | 'auto' | 'preserve';
|
|
25
|
+
layout?: string;
|
|
26
|
+
layouts?: readonly KeyboardLayout[];
|
|
27
|
+
locale?: KeyboardLocale;
|
|
28
|
+
theme?: KeyboardTheme;
|
|
29
|
+
autoHamza?: boolean;
|
|
30
|
+
secondaryKeys?: boolean;
|
|
31
|
+
/** Show each key's Shift letter and Latin key cap where the layout has them (default true). */
|
|
32
|
+
legends?: boolean;
|
|
33
|
+
compact?: boolean;
|
|
34
|
+
label?: string;
|
|
35
|
+
}
|
|
36
|
+
export interface KeyboardController {
|
|
37
|
+
readonly element: HTMLDivElement;
|
|
38
|
+
readonly layout: string;
|
|
39
|
+
setLayout(id: string): void;
|
|
40
|
+
setTheme(theme: KeyboardTheme): void;
|
|
41
|
+
setCompact(enabled: boolean): void;
|
|
42
|
+
setAutoHamza(enabled: boolean): void;
|
|
43
|
+
setSecondaryKeys(enabled: boolean): void;
|
|
44
|
+
setLegends(enabled: boolean): void;
|
|
45
|
+
insert(text: string): boolean;
|
|
46
|
+
backspace(): boolean;
|
|
47
|
+
setPhysicalMapping(enabled: boolean): void;
|
|
48
|
+
setVisible(visible: boolean): void;
|
|
49
|
+
destroy(): void;
|
|
50
|
+
}
|
|
51
|
+
export interface UyghurKeyboardElement extends HTMLElement {
|
|
52
|
+
layout: KeyboardLayoutId;
|
|
53
|
+
insert(text: string): boolean;
|
|
54
|
+
backspace(): boolean;
|
|
55
|
+
}
|
|
56
|
+
/** The standard Uyghur computer layout, used when no layout is given. */
|
|
57
|
+
export const DEFAULT_LAYOUT: 'uey-desktop';
|
|
58
|
+
export const KEYBOARD_LAYOUTS: Readonly<Record<KeyboardLayoutId, KeyboardLayout>>;
|
|
59
|
+
export const KEY_LAYOUT: readonly (readonly string[])[];
|
|
60
|
+
export const PHONETIC_MAP: Readonly<Record<string, string>>;
|
|
61
|
+
export function replaceSelection(value: string, start: number | null, end: number | null, text: string): SelectionResult;
|
|
62
|
+
export function deleteSelectionBackward(value: string, start: number | null, end: number | null): SelectionResult;
|
|
63
|
+
export function createKeyboard(target: HTMLInputElement | HTMLTextAreaElement, options?: KeyboardOptions): KeyboardController;
|
|
64
|
+
export function defineUyghurKeyboard(name?: string, registry?: CustomElementRegistry): CustomElementConstructor | null;
|
|
65
|
+
declare global { interface HTMLElementTagNameMap { 'uyghur-keyboard': UyghurKeyboardElement } }
|
package/src/index.js
ADDED
|
@@ -0,0 +1,473 @@
|
|
|
1
|
+
import { alkatipFontFace, alkatipHelperStyles, keyboardStyles } from './style.js';
|
|
2
|
+
import { DEFAULT_LAYOUT, KEYBOARD_LAYOUTS, keyboardLabels } from './layouts.js';
|
|
3
|
+
import { nextKey } from './navigation.js';
|
|
4
|
+
export { KEY_LAYOUT, PHONETIC_MAP, KEYBOARD_LAYOUTS, DEFAULT_LAYOUT } 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 ?? DEFAULT_LAYOUT);
|
|
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
|
+
// Shift letters and Latin key caps on each key, where the layout has them.
|
|
120
|
+
let legends = options.legends !== false;
|
|
121
|
+
const pressTimers = new Map();
|
|
122
|
+
let destroyed = false;
|
|
123
|
+
let composing = false;
|
|
124
|
+
let shifted = false;
|
|
125
|
+
let buttonRows = [];
|
|
126
|
+
let activeButton;
|
|
127
|
+
|
|
128
|
+
const layoutSelect = doc.createElement('select');
|
|
129
|
+
layoutSelect.className = 'ug-keyboard__layout';
|
|
130
|
+
layoutSelect.setAttribute('aria-label', labels.layout);
|
|
131
|
+
for (const [id, item] of layouts) {
|
|
132
|
+
const option = doc.createElement('option');
|
|
133
|
+
option.value = id;
|
|
134
|
+
option.textContent = item.labels[locale] || item.labels.en;
|
|
135
|
+
layoutSelect.appendChild(option);
|
|
136
|
+
}
|
|
137
|
+
layoutSelect.value = layout.id;
|
|
138
|
+
root.appendChild(layoutSelect);
|
|
139
|
+
const keys = doc.createElement('div');
|
|
140
|
+
keys.className = 'ug-keyboard__keys';
|
|
141
|
+
root.appendChild(keys);
|
|
142
|
+
|
|
143
|
+
function setTargetDirection() {
|
|
144
|
+
const nextDirection = direction || layout.direction;
|
|
145
|
+
if (nextDirection === 'preserve') return;
|
|
146
|
+
if (appliedDirection !== undefined && target.getAttribute('dir') !== appliedDirection) return;
|
|
147
|
+
target.setAttribute('dir', nextDirection);
|
|
148
|
+
appliedDirection = nextDirection;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function legend(className, text) {
|
|
152
|
+
const span = doc.createElement('span');
|
|
153
|
+
span.className = className;
|
|
154
|
+
span.textContent = text;
|
|
155
|
+
span.setAttribute('aria-hidden', 'true');
|
|
156
|
+
return span;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function keyButton(text, action, { shiftText, cap, code } = {}) {
|
|
160
|
+
const button = doc.createElement('button');
|
|
161
|
+
button.type = 'button';
|
|
162
|
+
button.className = 'ug-keyboard__key';
|
|
163
|
+
button.textContent = text;
|
|
164
|
+
button.tabIndex = -1;
|
|
165
|
+
if (action) button.dataset.action = action;
|
|
166
|
+
else button.dataset.text = text;
|
|
167
|
+
if (code) button.dataset.code = code;
|
|
168
|
+
if (legends && shiftText) button.appendChild(legend('ug-keyboard__shift-legend', shiftText));
|
|
169
|
+
if (legends && cap) button.appendChild(legend('ug-keyboard__cap', cap));
|
|
170
|
+
if (action === 'shift' || action === 'backspace') button.insertBefore(legend(`ug-keyboard__icon ug-keyboard__icon--${action}`, ''), button.firstChild ?? null);
|
|
171
|
+
const localized = labels[action] || labels.punctuation[text];
|
|
172
|
+
button.lang = localized ? locale : layout.lang;
|
|
173
|
+
button.setAttribute('aria-label', localized || text);
|
|
174
|
+
if (action === 'shift') button.setAttribute('aria-pressed', String(shifted));
|
|
175
|
+
return button;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function focusedElement() {
|
|
179
|
+
return root.getRootNode?.().activeElement || doc.activeElement;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function setActiveButton(button) {
|
|
183
|
+
if (activeButton) activeButton.tabIndex = -1;
|
|
184
|
+
activeButton = button;
|
|
185
|
+
activeButton.tabIndex = 0;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function renderKeys() {
|
|
189
|
+
const index = buttonRows.flat().indexOf(activeButton);
|
|
190
|
+
const restoreFocus = keys.contains(focusedElement());
|
|
191
|
+
keys.dir = layout.keyDirection || layout.direction;
|
|
192
|
+
const current = shifted ? layout.shiftedRows : layout.rows;
|
|
193
|
+
const other = shifted ? layout.rows : layout.shiftedRows;
|
|
194
|
+
const rows = current.map((row, r) => row.map((text, k) => keyButton(text, undefined, {
|
|
195
|
+
// Show the Shift letter only where Shift gives a different letter (D: د and ژ).
|
|
196
|
+
shiftText: !shifted && other?.[r]?.[k] && other[r][k] !== text ? other[r][k] : undefined,
|
|
197
|
+
cap: layout.keyCaps?.[r]?.[k],
|
|
198
|
+
code: layout.keyCodes?.[r]?.[k],
|
|
199
|
+
})));
|
|
200
|
+
if (secondary && layout.secondary?.length) rows.push(layout.secondary.map((text) => keyButton(text)));
|
|
201
|
+
const actions = [keyButton(labels.space, 'space'), keyButton(locale === 'ug' ? 'ئۆچۈرۈش' : 'Delete', 'backspace')];
|
|
202
|
+
if (layout.shiftedRows) actions.unshift(keyButton('', 'shift'));
|
|
203
|
+
rows.push(actions);
|
|
204
|
+
buttonRows = rows;
|
|
205
|
+
keys.replaceChildren();
|
|
206
|
+
for (const buttons of rows) {
|
|
207
|
+
const row = doc.createElement('div');
|
|
208
|
+
row.className = 'ug-keyboard__row';
|
|
209
|
+
for (const button of buttons) row.appendChild(button);
|
|
210
|
+
keys.appendChild(row);
|
|
211
|
+
}
|
|
212
|
+
const buttons = rows.flat();
|
|
213
|
+
setActiveButton(buttons[Math.min(Math.max(index, 0), buttons.length - 1)]);
|
|
214
|
+
if (restoreFocus) activeButton.focus();
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function setLayout(id) {
|
|
218
|
+
const next = layouts.get(id);
|
|
219
|
+
if (!next) throw new TypeError('Unknown keyboard layout: ' + id);
|
|
220
|
+
if (destroyed || next === layout) return;
|
|
221
|
+
layout = next;
|
|
222
|
+
shifted = false;
|
|
223
|
+
layoutSelect.value = id;
|
|
224
|
+
setTargetDirection();
|
|
225
|
+
renderKeys();
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function setTheme(theme) {
|
|
229
|
+
if (!['light', 'dark'].includes(theme)) throw new TypeError('theme must be light or dark');
|
|
230
|
+
root.dataset.theme = theme;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function setCompact(enabled) {
|
|
234
|
+
root.dataset.compact = String(Boolean(enabled));
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
setTheme(options.theme ?? 'light');
|
|
238
|
+
setCompact(options.compact);
|
|
239
|
+
renderKeys();
|
|
240
|
+
|
|
241
|
+
if (options.container) options.container.appendChild(root);
|
|
242
|
+
else if (target.parentNode) target.parentNode.insertBefore(root, target.nextSibling);
|
|
243
|
+
else throw new Error('Attach the target to a document or provide a container');
|
|
244
|
+
// Font faces must be registered in the owner document, including when keys
|
|
245
|
+
// themselves live in a Web Component's shadow root.
|
|
246
|
+
const releaseFont = acquireFont(doc);
|
|
247
|
+
setTargetDirection();
|
|
248
|
+
|
|
249
|
+
function commit(result, inputType, text, focusTarget = true) {
|
|
250
|
+
if (destroyed || target.disabled || target.readOnly || composing) return false;
|
|
251
|
+
if (!target.dispatchEvent(makeEvent(target, 'beforeinput', inputType, text, true))) return false;
|
|
252
|
+
target.value = result.value;
|
|
253
|
+
if (focusTarget) target.focus({ preventScroll: true });
|
|
254
|
+
target.setSelectionRange(result.start, result.end);
|
|
255
|
+
target.dispatchEvent(makeEvent(target, 'input', inputType, text, false));
|
|
256
|
+
const view = doc.defaultView || globalThis;
|
|
257
|
+
if (typeof view.CustomEvent === 'function') {
|
|
258
|
+
root.dispatchEvent(new view.CustomEvent('uyghur-input', { bubbles: true, composed: true, detail: { value: target.value, inputType, text } }));
|
|
259
|
+
}
|
|
260
|
+
return true;
|
|
261
|
+
}
|
|
262
|
+
function insert(text) {
|
|
263
|
+
if (typeof text !== 'string') throw new TypeError('insert expects a string');
|
|
264
|
+
return insertText(text, true);
|
|
265
|
+
}
|
|
266
|
+
function insertText(text, focusTarget) {
|
|
267
|
+
const result = replaceSelection(target.value, target.selectionStart, target.selectionEnd, text);
|
|
268
|
+
return commit(result, 'insertText', text, focusTarget);
|
|
269
|
+
}
|
|
270
|
+
function deleteBackward(focusTarget) {
|
|
271
|
+
const result = deleteSelectionBackward(target.value, target.selectionStart, target.selectionEnd);
|
|
272
|
+
return commit(result, 'deleteContentBackward', null, focusTarget);
|
|
273
|
+
}
|
|
274
|
+
function withHamza(text) {
|
|
275
|
+
if (!autoHamza || layout.lang !== 'ug-Arab' || !/^[اەېىوۇۆۈ]$/u.test(text)) return text;
|
|
276
|
+
const [start] = selection(target.value, target.selectionStart, target.selectionEnd);
|
|
277
|
+
const insideWord = /[\p{L}\p{M}\p{N}\p{Pc}\u200c\u200d]$/u.test(target.value.slice(0, start));
|
|
278
|
+
return insideWord ? text : 'ئ' + text;
|
|
279
|
+
}
|
|
280
|
+
function onClick(event) {
|
|
281
|
+
const button = event.target.closest?.('button.ug-keyboard__key');
|
|
282
|
+
if (!button || !keys.contains(button)) return;
|
|
283
|
+
setActiveButton(button);
|
|
284
|
+
const action = button.dataset.action;
|
|
285
|
+
const focusTarget = event.detail !== 0 || focusedElement() !== button;
|
|
286
|
+
if (action === 'shift') {
|
|
287
|
+
shifted = !shifted;
|
|
288
|
+
renderKeys();
|
|
289
|
+
} else if (action === 'backspace') {
|
|
290
|
+
deleteBackward(focusTarget);
|
|
291
|
+
} else {
|
|
292
|
+
insertText(withHamza(action === 'space' ? ' ' : button.dataset.text), focusTarget);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
function onPointerDown(event) {
|
|
296
|
+
// Keep the selection in the target while clicking the virtual keys.
|
|
297
|
+
if (event.target.closest?.('button.ug-keyboard__key')) event.preventDefault();
|
|
298
|
+
}
|
|
299
|
+
function onVirtualKeyDown(event) {
|
|
300
|
+
if (event.altKey || event.ctrlKey || event.metaKey || event.defaultPrevented) return;
|
|
301
|
+
const button = nextKey(buttonRows, event.target, event.key, keys.dir === 'rtl');
|
|
302
|
+
if (!button) return;
|
|
303
|
+
event.preventDefault();
|
|
304
|
+
setActiveButton(button);
|
|
305
|
+
button.focus();
|
|
306
|
+
}
|
|
307
|
+
/** The virtual key a physical key press corresponds to: by position first, then by character. */
|
|
308
|
+
function buttonFor(event) {
|
|
309
|
+
const all = buttonRows.flat();
|
|
310
|
+
if (event.code) {
|
|
311
|
+
const byCode = all.find((button) => button.dataset.code === event.code);
|
|
312
|
+
if (byCode) return byCode;
|
|
313
|
+
}
|
|
314
|
+
if (event.key === ' ') return all.find((button) => button.dataset.action === 'space');
|
|
315
|
+
if (event.key === 'Backspace') return all.find((button) => button.dataset.action === 'backspace');
|
|
316
|
+
if (event.key === 'Shift') return all.find((button) => button.dataset.action === 'shift');
|
|
317
|
+
const map = layout.physicalMap;
|
|
318
|
+
const char = map && Object.hasOwn(map, event.key) ? map[event.key] : event.key;
|
|
319
|
+
return all.find((button) => button.dataset.text === char || button.dataset.text === event.key);
|
|
320
|
+
}
|
|
321
|
+
function release(button) {
|
|
322
|
+
clearTimeout(pressTimers.get(button));
|
|
323
|
+
pressTimers.delete(button);
|
|
324
|
+
if (button.dataset) delete button.dataset.pressed;
|
|
325
|
+
}
|
|
326
|
+
function press(event) {
|
|
327
|
+
const button = buttonFor(event);
|
|
328
|
+
if (!button) return;
|
|
329
|
+
release(button);
|
|
330
|
+
button.dataset.pressed = 'true';
|
|
331
|
+
// Keyboards that never send keyup (some mobile IMEs) still clear the highlight.
|
|
332
|
+
pressTimers.set(button, setTimeout(() => release(button), 600));
|
|
333
|
+
}
|
|
334
|
+
function onKeyUp(event) {
|
|
335
|
+
const button = buttonFor(event);
|
|
336
|
+
if (button) release(button);
|
|
337
|
+
}
|
|
338
|
+
function onKeyDown(event) {
|
|
339
|
+
if (composing || event.isComposing || event.defaultPrevented || event.ctrlKey || event.metaKey || event.altKey) return;
|
|
340
|
+
press(event);
|
|
341
|
+
const map = layout.physicalMap;
|
|
342
|
+
const mapped = physical && map && Object.hasOwn(map, event.key) ? map[event.key] : undefined;
|
|
343
|
+
const text = withHamza(mapped ?? event.key);
|
|
344
|
+
if (mapped !== undefined || text !== event.key) {
|
|
345
|
+
event.preventDefault();
|
|
346
|
+
insertText(text, true);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
const onLayoutChange = () => setLayout(layoutSelect.value);
|
|
350
|
+
const beginComposition = () => { composing = true; };
|
|
351
|
+
const endComposition = () => { composing = false; };
|
|
352
|
+
root.addEventListener('click', onClick);
|
|
353
|
+
root.addEventListener('pointerdown', onPointerDown);
|
|
354
|
+
keys.addEventListener('keydown', onVirtualKeyDown);
|
|
355
|
+
layoutSelect.addEventListener('change', onLayoutChange);
|
|
356
|
+
target.addEventListener('keydown', onKeyDown);
|
|
357
|
+
target.addEventListener('keyup', onKeyUp);
|
|
358
|
+
target.addEventListener('compositionstart', beginComposition);
|
|
359
|
+
target.addEventListener('compositionend', endComposition);
|
|
360
|
+
|
|
361
|
+
return {
|
|
362
|
+
element: root,
|
|
363
|
+
get layout() { return layout.id; },
|
|
364
|
+
insert,
|
|
365
|
+
backspace() { return deleteBackward(true); },
|
|
366
|
+
setLayout,
|
|
367
|
+
setTheme,
|
|
368
|
+
setCompact,
|
|
369
|
+
setAutoHamza(enabled) { autoHamza = Boolean(enabled); },
|
|
370
|
+
setSecondaryKeys(enabled) {
|
|
371
|
+
if (destroyed) return;
|
|
372
|
+
secondary = Boolean(enabled);
|
|
373
|
+
renderKeys();
|
|
374
|
+
},
|
|
375
|
+
setPhysicalMapping(enabled) { physical = Boolean(enabled); },
|
|
376
|
+
setLegends(enabled) {
|
|
377
|
+
if (destroyed) return;
|
|
378
|
+
legends = Boolean(enabled);
|
|
379
|
+
renderKeys();
|
|
380
|
+
},
|
|
381
|
+
setVisible(visible) { root.hidden = !visible; },
|
|
382
|
+
destroy() {
|
|
383
|
+
if (destroyed) return;
|
|
384
|
+
destroyed = true;
|
|
385
|
+
root.removeEventListener('click', onClick);
|
|
386
|
+
root.removeEventListener('pointerdown', onPointerDown);
|
|
387
|
+
keys.removeEventListener('keydown', onVirtualKeyDown);
|
|
388
|
+
layoutSelect.removeEventListener('change', onLayoutChange);
|
|
389
|
+
target.removeEventListener('keydown', onKeyDown);
|
|
390
|
+
target.removeEventListener('keyup', onKeyUp);
|
|
391
|
+
for (const button of [...pressTimers.keys()]) release(button);
|
|
392
|
+
target.removeEventListener('compositionstart', beginComposition);
|
|
393
|
+
target.removeEventListener('compositionend', endComposition);
|
|
394
|
+
root.remove();
|
|
395
|
+
releaseFont();
|
|
396
|
+
if (appliedDirection !== undefined && target.getAttribute('dir') === appliedDirection) {
|
|
397
|
+
if (originalDirection === null) target.removeAttribute('dir');
|
|
398
|
+
else target.setAttribute('dir', originalDirection);
|
|
399
|
+
}
|
|
400
|
+
},
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** Define the optional Web Component. Safe to import the package in Node/SSR. */
|
|
405
|
+
export function defineUyghurKeyboard(name = 'uyghur-keyboard', registry = globalThis.customElements) {
|
|
406
|
+
if (!registry || typeof globalThis.HTMLElement !== 'function') return null;
|
|
407
|
+
if (registry.get(name)) return registry.get(name);
|
|
408
|
+
class UyghurKeyboardElement extends HTMLElement {
|
|
409
|
+
static get observedAttributes() {
|
|
410
|
+
return ['for', 'physical', 'layout', 'auto-hamza', 'secondary-keys', 'compact', 'theme', 'lang'];
|
|
411
|
+
}
|
|
412
|
+
connectedCallback() {
|
|
413
|
+
if (!this.shadowRoot) this.attachShadow({ mode: 'open' });
|
|
414
|
+
this.mountKeyboard();
|
|
415
|
+
this.readyListener = () => this.mountKeyboard();
|
|
416
|
+
if (this.ownerDocument.readyState === 'loading') this.ownerDocument.addEventListener('DOMContentLoaded', this.readyListener, { once: true });
|
|
417
|
+
}
|
|
418
|
+
attributeChangedCallback(name) {
|
|
419
|
+
if (!this.isConnected) return;
|
|
420
|
+
if (!this.controller || name === 'for' || name === 'lang') {
|
|
421
|
+
this.mountKeyboard();
|
|
422
|
+
} else if (name === 'layout') {
|
|
423
|
+
this.controller.setLayout(this.requestedLayout);
|
|
424
|
+
} else if (name === 'theme') {
|
|
425
|
+
this.controller.setTheme(this.getAttribute('theme') === 'dark' ? 'dark' : 'light');
|
|
426
|
+
} else {
|
|
427
|
+
const setters = {
|
|
428
|
+
physical: 'setPhysicalMapping', 'auto-hamza': 'setAutoHamza',
|
|
429
|
+
'secondary-keys': 'setSecondaryKeys', compact: 'setCompact',
|
|
430
|
+
};
|
|
431
|
+
this.controller[setters[name]](this.hasAttribute(name));
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
disconnectedCallback() {
|
|
435
|
+
this.controller?.destroy();
|
|
436
|
+
this.controller = null;
|
|
437
|
+
if (this.readyListener) this.ownerDocument.removeEventListener('DOMContentLoaded', this.readyListener);
|
|
438
|
+
}
|
|
439
|
+
mountKeyboard() {
|
|
440
|
+
this.controller?.destroy();
|
|
441
|
+
this.controller = null;
|
|
442
|
+
this.shadowRoot?.replaceChildren();
|
|
443
|
+
const hostStyle = this.ownerDocument.createElement('style');
|
|
444
|
+
hostStyle.textContent = ':host { display: block; }';
|
|
445
|
+
this.shadowRoot?.appendChild(hostStyle);
|
|
446
|
+
const target = this.ownerDocument.getElementById(this.getAttribute('for') || '');
|
|
447
|
+
if (!target) return;
|
|
448
|
+
this.controller = createKeyboard(target, {
|
|
449
|
+
container: this.shadowRoot,
|
|
450
|
+
layout: this.requestedLayout,
|
|
451
|
+
physical: this.hasAttribute('physical'),
|
|
452
|
+
autoHamza: this.hasAttribute('auto-hamza'),
|
|
453
|
+
secondaryKeys: this.hasAttribute('secondary-keys'),
|
|
454
|
+
compact: this.hasAttribute('compact'),
|
|
455
|
+
theme: this.getAttribute('theme') === 'dark' ? 'dark' : 'light',
|
|
456
|
+
locale: this.getAttribute('lang')?.split('-')[0] === 'en' ? 'en' : 'ug',
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
get requestedLayout() {
|
|
460
|
+
const id = this.getAttribute('layout');
|
|
461
|
+
return Object.hasOwn(KEYBOARD_LAYOUTS, id) ? id : DEFAULT_LAYOUT;
|
|
462
|
+
}
|
|
463
|
+
get layout() { return this.controller?.layout ?? this.requestedLayout; }
|
|
464
|
+
set layout(id) {
|
|
465
|
+
if (!Object.hasOwn(KEYBOARD_LAYOUTS, id)) throw new TypeError('Unknown keyboard layout: ' + id);
|
|
466
|
+
this.setAttribute('layout', id);
|
|
467
|
+
}
|
|
468
|
+
insert(text) { return this.controller?.insert(text) || false; }
|
|
469
|
+
backspace() { return this.controller?.backspace() || false; }
|
|
470
|
+
}
|
|
471
|
+
registry.define(name, UyghurKeyboardElement);
|
|
472
|
+
return UyghurKeyboardElement;
|
|
473
|
+
}
|