@uyghurcommunity/ui 0.0.0-stage → 0.4.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.
Files changed (215) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +223 -2
  3. package/THIRD_PARTY_NOTICES.md +28 -0
  4. package/assets/flags/east-turkistan.svg +1 -0
  5. package/assets/icon-catalog.json +1514 -0
  6. package/assets/icons/almond.svg +1 -0
  7. package/assets/icons/ancient-ruins.svg +1 -0
  8. package/assets/icons/apricot.svg +1 -0
  9. package/assets/icons/archway.svg +1 -0
  10. package/assets/icons/arrow-down.svg +1 -0
  11. package/assets/icons/arrow-left.svg +1 -0
  12. package/assets/icons/arrow-right.svg +1 -0
  13. package/assets/icons/arrow-up.svg +1 -0
  14. package/assets/icons/atlas.svg +1 -0
  15. package/assets/icons/aywan.svg +1 -0
  16. package/assets/icons/book.svg +1 -0
  17. package/assets/icons/boots.svg +1 -0
  18. package/assets/icons/calendar.svg +1 -0
  19. package/assets/icons/calligraphy.svg +1 -0
  20. package/assets/icons/camel.svg +1 -0
  21. package/assets/icons/carpet.svg +1 -0
  22. package/assets/icons/carved-door.svg +1 -0
  23. package/assets/icons/ceramic-vase.svg +1 -0
  24. package/assets/icons/chapan.svg +1 -0
  25. package/assets/icons/check-circle.svg +1 -0
  26. package/assets/icons/check.svg +1 -0
  27. package/assets/icons/chevron-down.svg +1 -0
  28. package/assets/icons/chevron-left.svg +1 -0
  29. package/assets/icons/chevron-right.svg +1 -0
  30. package/assets/icons/chevron-up.svg +1 -0
  31. package/assets/icons/city-gate.svg +1 -0
  32. package/assets/icons/close.svg +1 -0
  33. package/assets/icons/code.svg +1 -0
  34. package/assets/icons/color/almond.svg +1 -0
  35. package/assets/icons/color/ancient-ruins.svg +1 -0
  36. package/assets/icons/color/apricot.svg +1 -0
  37. package/assets/icons/color/archway.svg +1 -0
  38. package/assets/icons/color/atlas.svg +1 -0
  39. package/assets/icons/color/aywan.svg +1 -0
  40. package/assets/icons/color/boots.svg +1 -0
  41. package/assets/icons/color/calligraphy.svg +1 -0
  42. package/assets/icons/color/camel.svg +1 -0
  43. package/assets/icons/color/carpet.svg +1 -0
  44. package/assets/icons/color/carved-door.svg +1 -0
  45. package/assets/icons/color/ceramic-vase.svg +1 -0
  46. package/assets/icons/color/chapan.svg +1 -0
  47. package/assets/icons/color/city-gate.svg +1 -0
  48. package/assets/icons/color/cotton.svg +1 -0
  49. package/assets/icons/color/crescent.svg +1 -0
  50. package/assets/icons/color/dap.svg +1 -0
  51. package/assets/icons/color/doppa-top.svg +1 -0
  52. package/assets/icons/color/doppa.svg +1 -0
  53. package/assets/icons/color/dove.svg +1 -0
  54. package/assets/icons/color/dutar.svg +1 -0
  55. package/assets/icons/color/embroidery.svg +1 -0
  56. package/assets/icons/color/floral-rosette.svg +1 -0
  57. package/assets/icons/color/flower.svg +1 -0
  58. package/assets/icons/color/fur-hat.svg +1 -0
  59. package/assets/icons/color/ghijek.svg +1 -0
  60. package/assets/icons/color/grapes.svg +1 -0
  61. package/assets/icons/color/horse.svg +1 -0
  62. package/assets/icons/color/jewelry.svg +1 -0
  63. package/assets/icons/color/laghman.svg +1 -0
  64. package/assets/icons/color/landscape.svg +1 -0
  65. package/assets/icons/color/lattice-window.svg +1 -0
  66. package/assets/icons/color/loom.svg +1 -0
  67. package/assets/icons/color/madrasa.svg +1 -0
  68. package/assets/icons/color/mausoleum.svg +1 -0
  69. package/assets/icons/color/melon.svg +1 -0
  70. package/assets/icons/color/mens-coat.svg +1 -0
  71. package/assets/icons/color/minaret.svg +1 -0
  72. package/assets/icons/color/mosque.svg +1 -0
  73. package/assets/icons/color/nan-stack.svg +1 -0
  74. package/assets/icons/color/nan.svg +1 -0
  75. package/assets/icons/color/ornamental-border.svg +1 -0
  76. package/assets/icons/color/polo.svg +1 -0
  77. package/assets/icons/color/pomegranate.svg +1 -0
  78. package/assets/icons/color/rawap.svg +1 -0
  79. package/assets/icons/color/samsa.svg +1 -0
  80. package/assets/icons/color/sash.svg +1 -0
  81. package/assets/icons/color/satar.svg +1 -0
  82. package/assets/icons/color/spindle.svg +1 -0
  83. package/assets/icons/color/star-eight.svg +1 -0
  84. package/assets/icons/color/surnai.svg +1 -0
  85. package/assets/icons/color/tambur.svg +1 -0
  86. package/assets/icons/color/tea-bowl.svg +1 -0
  87. package/assets/icons/color/tea-set.svg +1 -0
  88. package/assets/icons/color/teapot.svg +1 -0
  89. package/assets/icons/color/traditional-house.svg +1 -0
  90. package/assets/icons/color/traditional-shoes.svg +1 -0
  91. package/assets/icons/color/tree-of-life.svg +1 -0
  92. package/assets/icons/color/unity.svg +1 -0
  93. package/assets/icons/color/uyghur-medallion.svg +1 -0
  94. package/assets/icons/color/womens-dress.svg +1 -0
  95. package/assets/icons/color/womens-headdress.svg +1 -0
  96. package/assets/icons/color/yurt.svg +1 -0
  97. package/assets/icons/copy.svg +1 -0
  98. package/assets/icons/cotton.svg +1 -0
  99. package/assets/icons/crescent.svg +1 -0
  100. package/assets/icons/dap.svg +1 -0
  101. package/assets/icons/direction-ltr.svg +1 -0
  102. package/assets/icons/direction-rtl.svg +1 -0
  103. package/assets/icons/doppa-top.svg +1 -0
  104. package/assets/icons/doppa.svg +1 -0
  105. package/assets/icons/dove.svg +1 -0
  106. package/assets/icons/download.svg +1 -0
  107. package/assets/icons/dutar.svg +1 -0
  108. package/assets/icons/edit.svg +1 -0
  109. package/assets/icons/embroidery.svg +1 -0
  110. package/assets/icons/external-link.svg +1 -0
  111. package/assets/icons/floral-rosette.svg +1 -0
  112. package/assets/icons/flower.svg +1 -0
  113. package/assets/icons/fur-hat.svg +1 -0
  114. package/assets/icons/ghijek.svg +1 -0
  115. package/assets/icons/globe.svg +1 -0
  116. package/assets/icons/grapes.svg +1 -0
  117. package/assets/icons/heart.svg +1 -0
  118. package/assets/icons/home.svg +1 -0
  119. package/assets/icons/horse.svg +1 -0
  120. package/assets/icons/image.svg +1 -0
  121. package/assets/icons/info.svg +1 -0
  122. package/assets/icons/jewelry.svg +1 -0
  123. package/assets/icons/keyboard.svg +1 -0
  124. package/assets/icons/laghman.svg +1 -0
  125. package/assets/icons/landscape.svg +1 -0
  126. package/assets/icons/language.svg +1 -0
  127. package/assets/icons/lattice-window.svg +1 -0
  128. package/assets/icons/link.svg +1 -0
  129. package/assets/icons/loom.svg +1 -0
  130. package/assets/icons/madrasa.svg +1 -0
  131. package/assets/icons/mail.svg +1 -0
  132. package/assets/icons/mausoleum.svg +1 -0
  133. package/assets/icons/melon.svg +1 -0
  134. package/assets/icons/mens-coat.svg +1 -0
  135. package/assets/icons/menu.svg +1 -0
  136. package/assets/icons/minaret.svg +1 -0
  137. package/assets/icons/minus.svg +1 -0
  138. package/assets/icons/moon.svg +1 -0
  139. package/assets/icons/mosque.svg +1 -0
  140. package/assets/icons/nan-stack.svg +1 -0
  141. package/assets/icons/nan.svg +1 -0
  142. package/assets/icons/ornamental-border.svg +1 -0
  143. package/assets/icons/palette.svg +1 -0
  144. package/assets/icons/pause.svg +1 -0
  145. package/assets/icons/play.svg +1 -0
  146. package/assets/icons/plus.svg +1 -0
  147. package/assets/icons/polo.svg +1 -0
  148. package/assets/icons/pomegranate.svg +1 -0
  149. package/assets/icons/rawap.svg +1 -0
  150. package/assets/icons/redo.svg +1 -0
  151. package/assets/icons/samsa.svg +1 -0
  152. package/assets/icons/sash.svg +1 -0
  153. package/assets/icons/satar.svg +1 -0
  154. package/assets/icons/search.svg +1 -0
  155. package/assets/icons/settings.svg +1 -0
  156. package/assets/icons/spindle.svg +1 -0
  157. package/assets/icons/star-eight.svg +1 -0
  158. package/assets/icons/star.svg +1 -0
  159. package/assets/icons/sun.svg +1 -0
  160. package/assets/icons/surnai.svg +1 -0
  161. package/assets/icons/tambur.svg +1 -0
  162. package/assets/icons/tea-bowl.svg +1 -0
  163. package/assets/icons/tea-set.svg +1 -0
  164. package/assets/icons/teapot.svg +1 -0
  165. package/assets/icons/traditional-house.svg +1 -0
  166. package/assets/icons/traditional-shoes.svg +1 -0
  167. package/assets/icons/trash.svg +1 -0
  168. package/assets/icons/tree-of-life.svg +1 -0
  169. package/assets/icons/undo.svg +1 -0
  170. package/assets/icons/unity.svg +1 -0
  171. package/assets/icons/upload.svg +1 -0
  172. package/assets/icons/user.svg +1 -0
  173. package/assets/icons/users.svg +1 -0
  174. package/assets/icons/uyghur-medallion.svg +1 -0
  175. package/assets/icons/warning.svg +1 -0
  176. package/assets/icons/womens-dress.svg +1 -0
  177. package/assets/icons/womens-headdress.svg +1 -0
  178. package/assets/icons/yurt.svg +1 -0
  179. package/assets/maps/README.md +27 -0
  180. package/assets/maps/east-turkistan-filled.svg +1 -0
  181. package/assets/maps/east-turkistan-outline.svg +1 -0
  182. package/assets/maps/east-turkistan.metadata.json +64 -0
  183. package/assets/maps/east-turkistan.source.geojson +1 -0
  184. package/package.json +93 -4
  185. package/src/application.css +4 -0
  186. package/src/application.d.ts +7 -0
  187. package/src/application.js +120 -0
  188. package/src/blocks.css +1 -0
  189. package/src/font.css +8 -0
  190. package/src/heritage-color.js +30 -0
  191. package/src/icon-labels.js +98 -0
  192. package/src/icons.d.ts +13 -0
  193. package/src/icons.js +102 -0
  194. package/src/index.d.ts +17 -0
  195. package/src/index.js +201 -0
  196. package/src/interactions.css +15 -0
  197. package/src/interactions.d.ts +10 -0
  198. package/src/interactions.js +183 -0
  199. package/src/map-data.js +68 -0
  200. package/src/maps.d.ts +11 -0
  201. package/src/maps.js +17 -0
  202. package/src/reference-clothing.js +51 -0
  203. package/src/reference-places.js +43 -0
  204. package/src/styles.css +20 -0
  205. package/src/themes.d.ts +7 -0
  206. package/src/themes.js +36 -0
  207. package/src/traditional-drawings.js +42 -0
  208. package/src/vendor/README.md +17 -0
  209. package/src/vendor/keyboard/LICENSE +21 -0
  210. package/src/vendor/keyboard/index.js +248 -0
  211. package/src/vendor/keyboard/style.js +22 -0
  212. package/src/vendor/text/LICENSE +21 -0
  213. package/src/vendor/text/index.js +275 -0
  214. package/src/writing.d.ts +17 -0
  215. package/src/writing.js +111 -0
@@ -0,0 +1,275 @@
1
+ /** Unicode labels here describe code points, not resolved Unicode bidi levels. */
2
+ export const DIRECTIONAL_CONTROLS = Object.freeze({
3
+ '\u061c': 'ALM', '\u200e': 'LRM', '\u200f': 'RLM', '\u202a': 'LRE', '\u202b': 'RLE',
4
+ '\u202c': 'PDF', '\u202d': 'LRO', '\u202e': 'RLO', '\u2066': 'LRI', '\u2067': 'RLI',
5
+ '\u2068': 'FSI', '\u2069': 'PDI',
6
+ });
7
+
8
+ export const INVISIBLE_CHARACTERS = Object.freeze({
9
+ '\u0000': 'NUL', '\t': 'TAB', '\n': 'LF', '\r': 'CR', ' ': 'SPACE', '\u00a0': 'NBSP',
10
+ '\u00ad': 'SOFT HYPHEN', '\u034f': 'CGJ', '\u180e': 'MVS', '\u200b': 'ZWSP',
11
+ '\u200c': 'ZWNJ', '\u200d': 'ZWJ', '\u2028': 'LINE SEPARATOR', '\u2029': 'PARAGRAPH SEPARATOR',
12
+ '\u202f': 'NARROW NBSP', '\u2060': 'WORD JOINER', '\ufeff': 'BOM / ZWNBSP',
13
+ ...DIRECTIONAL_CONTROLS,
14
+ });
15
+
16
+ const CLEANUP_DEFAULTS = Object.freeze({
17
+ normalization: 'none', removeDirectionalControls: false, removeZeroWidthSpace: false,
18
+ removeByteOrderMark: false, removeSoftHyphen: false, removeJoiningControls: false,
19
+ trim: false, lineEndings: 'preserve',
20
+ });
21
+
22
+ function requireText(text, name = 'text') {
23
+ if (typeof text !== 'string') throw new TypeError(`${name} must be a string`);
24
+ }
25
+ function readOptions(value, keys) {
26
+ if (value === undefined) return {};
27
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('options must be an object');
28
+ for (const key of Object.keys(value)) if (!keys.includes(key)) throw new TypeError(`Unknown option: ${key}`);
29
+ return value;
30
+ }
31
+ function readLimit(limit = 400) {
32
+ if (!Number.isInteger(limit) || limit < 1 || limit > 10000) throw new RangeError('limit must be an integer from 1 to 10000');
33
+ return limit;
34
+ }
35
+ function readDirection(direction = 'auto') {
36
+ if (!['auto', 'rtl', 'ltr'].includes(direction)) throw new TypeError('direction must be auto, rtl, or ltr');
37
+ return direction;
38
+ }
39
+ function readLocale(locale = 'ug') {
40
+ if (typeof locale !== 'string' || !locale) throw new TypeError('locale must be a nonempty BCP 47 language tag');
41
+ // Canonicalization also validates the tag even when Segmenter is unavailable.
42
+ return Intl.getCanonicalLocales(locale)[0];
43
+ }
44
+ function codePointLabel(character) {
45
+ return 'U+' + character.codePointAt(0).toString(16).toUpperCase().padStart(4, '0');
46
+ }
47
+ function isUnpairedSurrogate(character) {
48
+ const value = character.codePointAt(0);
49
+ return value >= 0xd800 && value <= 0xdfff;
50
+ }
51
+
52
+ /** UTF-16 indices match textarea selection offsets. Fallback is explicitly not grapheme segmentation. */
53
+ export function segmentGraphemes(text, options) {
54
+ requireText(text);
55
+ const { locale } = readOptions(options, ['locale']);
56
+ const language = readLocale(locale);
57
+ if (typeof Intl.Segmenter === 'function') {
58
+ const segments = Array.from(new Intl.Segmenter(language, { granularity: 'grapheme' }).segment(text), (part) => ({
59
+ segment: part.segment, index: part.index, end: part.index + part.segment.length,
60
+ }));
61
+ return { mode: 'grapheme', segments };
62
+ }
63
+ let index = 0;
64
+ const segments = Array.from(text, (segment) => {
65
+ const entry = { segment, index, end: index + segment.length };
66
+ index = entry.end;
67
+ return entry;
68
+ });
69
+ return { mode: 'code-point-fallback', segments };
70
+ }
71
+
72
+ function describeCharacter(character, index, offset) {
73
+ const directionalControl = DIRECTIONAL_CONTROLS[character] || null;
74
+ const joiningControl = character === '\u200c' || character === '\u200d';
75
+ const defaultIgnorable = /\p{Default_Ignorable_Code_Point}/u.test(character);
76
+ const whitespace = /\p{White_Space}/u.test(character);
77
+ const control = /\p{Cc}/u.test(character);
78
+ const combiningMark = /\p{Mark}/u.test(character);
79
+ const unpairedSurrogate = isUnpairedSurrogate(character);
80
+ const invisible = defaultIgnorable || whitespace || control;
81
+ const category = unpairedSurrogate ? 'Unpaired surrogate' : directionalControl ? 'Directional control'
82
+ : joiningControl ? 'Joining control' : control ? 'Control character' : whitespace ? 'Whitespace'
83
+ : defaultIgnorable ? 'Default ignorable' : combiningMark ? 'Combining mark'
84
+ : /\p{Script=Arabic}/u.test(character) ? 'Arabic script' : /\p{Script=Latin}/u.test(character) ? 'Latin script'
85
+ : /\p{Number}/u.test(character) ? 'Number' : /\p{Punctuation}/u.test(character) ? 'Punctuation' : 'Symbol / other';
86
+ const label = INVISIBLE_CHARACTERS[character] || (unpairedSurrogate ? 'UNPAIRED SURROGATE' : invisible ? codePointLabel(character) : null);
87
+ return {
88
+ index, offset, end: offset + character.length, character,
89
+ codePoint: codePointLabel(character), escape: character.length === 2
90
+ ? `\\u{${character.codePointAt(0).toString(16).toUpperCase()}}`
91
+ : `\\u${character.charCodeAt(0).toString(16).toUpperCase().padStart(4, '0')}`,
92
+ category, label, display: label ? `[${label}]` : character,
93
+ invisible, directionalControl, joiningControl, defaultIgnorable, combiningMark, unpairedSurrogate,
94
+ };
95
+ }
96
+
97
+ export function inspectUnicode(text, options) {
98
+ requireText(text);
99
+ const { limit: requestedLimit, locale } = readOptions(options, ['limit', 'locale']);
100
+ const limit = readLimit(requestedLimit);
101
+ const segmentation = segmentGraphemes(text, { locale });
102
+ const counts = { utf16Units: text.length, codePoints: 0, graphemes: segmentation.mode === 'grapheme' ? segmentation.segments.length : null,
103
+ invisible: 0, directionalControls: 0, joiningControls: 0, defaultIgnorables: 0, combiningMarks: 0, unpairedSurrogates: 0 };
104
+ const rows = [];
105
+ let offset = 0;
106
+ for (const character of text) {
107
+ const row = describeCharacter(character, counts.codePoints, offset);
108
+ if (rows.length < limit) rows.push(row);
109
+ counts.codePoints++;
110
+ counts.invisible += Number(row.invisible);
111
+ counts.directionalControls += Number(Boolean(row.directionalControl));
112
+ counts.joiningControls += Number(row.joiningControl);
113
+ counts.defaultIgnorables += Number(row.defaultIgnorable);
114
+ counts.combiningMarks += Number(row.combiningMark);
115
+ counts.unpairedSurrogates += Number(row.unpairedSurrogate);
116
+ offset = row.end;
117
+ }
118
+ return {
119
+ counts, rows, truncated: counts.codePoints > limit, limit,
120
+ segmentation: segmentation.mode,
121
+ graphemes: segmentation.segments.slice(0, limit),
122
+ graphemesTruncated: segmentation.segments.length > limit,
123
+ normalized: { NFC: text === text.normalize('NFC'), NFKC: text === text.normalize('NFKC') },
124
+ };
125
+ }
126
+
127
+ /** Make invisible code points explicit; this output is a display aid, not a round-trip encoding. */
128
+ export function visibleText(text, options) {
129
+ requireText(text);
130
+ const { showSpaces = true } = readOptions(options, ['showSpaces']);
131
+ if (typeof showSpaces !== 'boolean') throw new TypeError('showSpaces must be a boolean');
132
+ return Array.from(text, (character) => {
133
+ if (character === ' ' && !showSpaces) return ' ';
134
+ const row = describeCharacter(character, 0, 0);
135
+ if (!row.invisible && !row.unpairedSurrogate) return character;
136
+ return row.display + (character === '\n' || character === '\r' || character === '\u2028' || character === '\u2029' ? '\n' : '');
137
+ }).join('');
138
+ }
139
+
140
+ /** A compact contiguous replacement with boundaries at graphemes (code points on fallback). */
141
+ export function diffText(before, after) {
142
+ requireText(before, 'before'); requireText(after, 'after');
143
+ const a = segmentGraphemes(before).segments.map((part) => part.segment);
144
+ const b = segmentGraphemes(after).segments.map((part) => part.segment);
145
+ let prefixLength = 0;
146
+ while (prefixLength < a.length && prefixLength < b.length && a[prefixLength] === b[prefixLength]) prefixLength++;
147
+ let suffixLength = 0;
148
+ while (suffixLength < a.length - prefixLength && suffixLength < b.length - prefixLength
149
+ && a[a.length - 1 - suffixLength] === b[b.length - 1 - suffixLength]) suffixLength++;
150
+ return { changed: before !== after, prefix: a.slice(0, prefixLength).join(''),
151
+ removed: a.slice(prefixLength, a.length - suffixLength).join(''),
152
+ added: b.slice(prefixLength, b.length - suffixLength).join(''),
153
+ suffix: suffixLength ? a.slice(a.length - suffixLength).join('') : '' };
154
+ }
155
+
156
+ function cleanupOptions(value) {
157
+ const requested = readOptions(value, Object.keys(CLEANUP_DEFAULTS));
158
+ const options = { ...CLEANUP_DEFAULTS, ...requested };
159
+ if (!['none', 'NFC', 'NFKC'].includes(options.normalization)) throw new TypeError('normalization must be none, NFC, or NFKC');
160
+ if (!['preserve', 'lf'].includes(options.lineEndings)) throw new TypeError('lineEndings must be preserve or lf');
161
+ for (const key of Object.keys(CLEANUP_DEFAULTS).filter((key) => !['normalization', 'lineEndings'].includes(key))) {
162
+ if (typeof options[key] !== 'boolean') throw new TypeError(`${key} must be a boolean`);
163
+ }
164
+ return options;
165
+ }
166
+
167
+ /** No-op by default. Does not strip Arabic marks or letters, or guess a spelling/transliteration. */
168
+ export function previewCleanup(text, requestedOptions) {
169
+ requireText(text);
170
+ const options = cleanupOptions(requestedOptions);
171
+ const changes = [];
172
+ let result = text;
173
+ const removals = [
174
+ ['removeDirectionalControls', (char) => Boolean(DIRECTIONAL_CONTROLS[char])],
175
+ ['removeZeroWidthSpace', (char) => char === '\u200b'],
176
+ ['removeByteOrderMark', (char) => char === '\ufeff'],
177
+ ['removeSoftHyphen', (char) => char === '\u00ad'],
178
+ ['removeJoiningControls', (char) => char === '\u200c' || char === '\u200d'],
179
+ ];
180
+ for (const [operation, matches] of removals) {
181
+ if (!options[operation]) continue;
182
+ let count = 0;
183
+ result = Array.from(result, (char) => { if (matches(char)) { count++; return ''; } return char; }).join('');
184
+ if (count) changes.push({ operation, count });
185
+ }
186
+ if (options.lineEndings === 'lf') {
187
+ const matches = result.match(/\r\n|\r/g);
188
+ if (matches) { result = result.replace(/\r\n|\r/g, '\n'); changes.push({ operation: 'lineEndings', count: matches.length }); }
189
+ }
190
+ if (options.trim) {
191
+ // String.trim also removes BOM and NBSP at the edges; this is explicit and documented.
192
+ const trimmed = result.trim();
193
+ if (trimmed !== result) {
194
+ changes.push({ operation: 'trim', count: Array.from(result).length - Array.from(trimmed).length });
195
+ result = trimmed;
196
+ }
197
+ }
198
+ if (options.normalization !== 'none') {
199
+ const normalized = result.normalize(options.normalization);
200
+ if (normalized !== result) changes.push({ operation: options.normalization, count: null });
201
+ result = normalized;
202
+ }
203
+ return { original: text, text: result, changed: text !== result, options, changes, diff: diffText(text, result) };
204
+ }
205
+
206
+ export function escapeHTML(text) {
207
+ requireText(text);
208
+ return text.replace(/[&<>"'\r]/g, (character) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;', '\r': '&#13;' })[character]);
209
+ }
210
+
211
+ export const FONT_FACE_CSS = `@font-face {
212
+ font-family: "ALKATIP Basma";
213
+ src: url("https://db.onlinewebfonts.com/t/3c16518f40da2fc2901f37666c0556a7.woff2") format("woff2"),
214
+ url("https://db.onlinewebfonts.com/t/3c16518f40da2fc2901f37666c0556a7.woff") format("woff"),
215
+ url("https://db.onlinewebfonts.com/t/3c16518f40da2fc2901f37666c0556a7.ttf") format("truetype");
216
+ font-weight: normal;
217
+ font-style: normal;
218
+ font-display: swap;
219
+ }`;
220
+
221
+ export function createRTLFixture(text, options) {
222
+ requireText(text);
223
+ const { direction: requestedDirection, lang = 'ug', title = 'Uyghur text fixture', includeFontFace = false } = readOptions(options, ['direction', 'lang', 'title', 'includeFontFace']);
224
+ const direction = readDirection(requestedDirection);
225
+ if (typeof lang !== 'string' || !/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(lang)) throw new TypeError('lang must be a BCP 47 language tag');
226
+ requireText(title, 'title');
227
+ if (typeof includeFontFace !== 'boolean') throw new TypeError('includeFontFace must be a boolean');
228
+ const warnings = [];
229
+ let renderedText = '';
230
+ for (const character of text) {
231
+ if (character === '\0' || isUnpairedSurrogate(character)) renderedText += '\ufffd';
232
+ else renderedText += character;
233
+ }
234
+ if (renderedText !== text) warnings.push('HTML cannot round-trip NUL or unpaired surrogates. Those values render as U+FFFD; use the JSON report to preserve the original JavaScript string.');
235
+ const css = (includeFontFace ? FONT_FACE_CSS + '\n' : '') + `.text-fixture {
236
+ max-inline-size: 52rem;
237
+ margin-inline: auto;
238
+ padding: 1.5rem;
239
+ border: 1px solid #b9d5e8;
240
+ border-radius: 1rem;
241
+ color: #132a3c;
242
+ background: #fff;
243
+ font-family: "ALKATIP Basma", Tahoma, Arial, sans-serif;
244
+ line-height: 2.2;
245
+ }
246
+ .text-fixture__input {
247
+ margin: 0 0 1rem;
248
+ white-space: pre-wrap;
249
+ overflow-wrap: anywhere;
250
+ unicode-bidi: isolate;
251
+ text-align: start;
252
+ font: inherit;
253
+ }
254
+ .text-fixture bdi { unicode-bidi: isolate; }
255
+ .text-fixture code { font-family: ui-monospace, "ALKATIP Basma", monospace; }
256
+ `;
257
+ // A div with pre-wrap preserves an initial LF; HTML's <pre> start-tag newline rule would discard it.
258
+ const html = `<section class="text-fixture" lang="${escapeHTML(lang)}" dir="${direction}">\n <div class="text-fixture__input" dir="${direction}">${escapeHTML(renderedText)}</div>\n <p>ئۇلىنىش: <bdi dir="ltr"><code>https://example.com/ug?q=123</code></bdi> · سان: <bdi dir="ltr">2026 / 123.45</bdi></p>\n</section>`;
259
+ const document = `<!doctype html>\n<html lang="${escapeHTML(lang)}" dir="${direction}">\n<head>\n <meta charset="utf-8">\n <meta name="viewport" content="width=device-width,initial-scale=1">\n <title>${escapeHTML(title)}</title>\n <style>\n${css} </style>\n</head>\n<body>\n${html}\n</body>\n</html>\n`;
260
+ return { direction, lang, html, css, document, warnings };
261
+ }
262
+
263
+ /** A deterministic report; exported JSON intentionally includes the user's original text. */
264
+ export function createTextReport(text, options) {
265
+ requireText(text);
266
+ const { direction: requestedDirection, cleanup, limit } = readOptions(options, ['direction', 'cleanup', 'limit']);
267
+ return {
268
+ schemaVersion: 1,
269
+ generator: { name: '@uyghurcommunity/text', version: '0.1.0' },
270
+ direction: readDirection(requestedDirection),
271
+ text,
272
+ inspection: inspectUnicode(text, { limit }),
273
+ cleanupPreview: previewCleanup(text, cleanup),
274
+ };
275
+ }
@@ -0,0 +1,17 @@
1
+ export interface CleanupOptions {
2
+ normalization?: 'none' | 'NFC' | 'NFKC'; lineEndings?: 'preserve' | 'lf'; trim?: boolean;
3
+ removeDirectionalControls?: boolean; removeZeroWidthSpace?: boolean; removeByteOrderMark?: boolean;
4
+ removeSoftHyphen?: boolean; removeJoiningControls?: boolean;
5
+ }
6
+ export interface CleanupPreview {
7
+ readonly original: string; readonly text: string; readonly changed: boolean;
8
+ readonly options: Readonly<Required<CleanupOptions>>;
9
+ readonly changes: readonly { readonly operation: string; readonly count: number | null }[];
10
+ readonly diff: { readonly changed: boolean; readonly prefix: string; readonly removed: string; readonly added: string; readonly suffix: string };
11
+ }
12
+ export interface WritingValidation { valid: boolean; message: string; length: number; maxLength: number }
13
+ export interface UyghurInputController {
14
+ getValue(): string; setValue(value: string): boolean; previewCleanup(options?: CleanupOptions): CleanupPreview | null;
15
+ applyCleanup(): boolean; undoCleanup(): boolean; validate(): WritingValidation; destroy(): void;
16
+ }
17
+ export declare function bindUyghurInput(root: HTMLElement, options?: { onChange?: (value: string) => void; maxLength?: number }): UyghurInputController;
package/src/writing.js ADDED
@@ -0,0 +1,111 @@
1
+ import { createKeyboard } from './vendor/keyboard/index.js';
2
+ import { previewCleanup as createCleanupPreview, visibleText } from './vendor/text/index.js';
3
+
4
+ /** Bind real Uyghur keyboard input and an explicit, reversible Unicode cleanup workflow. */
5
+ export function bindUyghurInput(root, { onChange, maxLength = 10000 } = {}) {
6
+ if (!root?.querySelector || !root.ownerDocument) throw new TypeError('A writing container is required');
7
+ if (onChange !== undefined && typeof onChange !== 'function') throw new TypeError('onChange must be a function');
8
+ if (!Number.isInteger(maxLength) || maxLength < 1 || maxLength > 100000) throw new RangeError('maxLength must be an integer from 1 to 100000');
9
+ const input = root.querySelector('[data-ug-writing-input]'), toggle = root.querySelector('[data-ug-keyboard-toggle]'), host = root.querySelector('[data-ug-keyboard]');
10
+ const preview = root.querySelector('[data-ug-writing-preview]'), status = root.querySelector('[data-ug-writing-status]'), cleanup = root.querySelector('[data-ug-cleanup-preview]');
11
+ const previewButton = root.querySelector('[data-ug-cleanup-preview-button]'), applyButton = root.querySelector('[data-ug-cleanup-apply]'), undoButton = root.querySelector('[data-ug-cleanup-undo]');
12
+ if (input?.tagName !== 'TEXTAREA' || !toggle || !host || !preview || !status || !cleanup || !previewButton || !applyButton || !undoButton) throw new TypeError('Writing controls are incomplete');
13
+ const doc = root.ownerDocument, win = doc.defaultView;
14
+ const old = { maxLength: input.getAttribute('maxlength'), inputDir: input.getAttribute('dir'), invalid: input.getAttribute('aria-invalid'), previewDir: preview.getAttribute('dir'), expanded: toggle.getAttribute('aria-expanded'), hostHidden: host.hidden, applyDisabled: applyButton.disabled, undoDisabled: undoButton.disabled };
15
+ const nativeLimit = old.maxLength !== null && /^\d+$/.test(old.maxLength) ? Number(old.maxLength) : Infinity;
16
+ const limit = Math.min(maxLength, nativeLimit);
17
+ input.setAttribute('maxlength', String(limit)); input.setAttribute('dir', 'auto'); preview.setAttribute('dir', 'auto'); toggle.setAttribute('aria-expanded', String(!host.hidden));
18
+ const keyboard = createKeyboard(input, { container: host, direction: 'preserve', physical: false });
19
+ let destroyed = false, composing = false, replacing = false, pending = null, undo = null, reported = input.value;
20
+ const alive = () => { if (destroyed) throw new Error('Writing controller has been destroyed'); };
21
+ const say = (message) => { status.textContent = message; };
22
+ function validate() {
23
+ alive();
24
+ const length = input.value.length;
25
+ const message = input.required && !input.value ? 'مەزمۇن كىرگۈزۈڭ.' : length > limit ? `مەزمۇن ئۇزۇنلۇقى ${limit} چەكتىن ئېشىپ كەتتى.` : '';
26
+ input.setAttribute('aria-invalid', String(Boolean(message)));
27
+ if (message) say(message);
28
+ return { valid: !message, message, length, maxLength: limit };
29
+ }
30
+ function updateButtons() { applyButton.disabled = composing || !pending?.changed || pending.original !== input.value || input.disabled || input.readOnly; undoButton.disabled = composing || !undo || undo.after !== input.value || input.disabled || input.readOnly; }
31
+ function refresh(notify = false) {
32
+ preview.textContent = input.value;
33
+ const result = validate(); if (result.valid) say(`${result.length} / ${limit}`);
34
+ updateButtons();
35
+ if (notify && reported !== input.value) { reported = input.value; onChange?.(input.value); }
36
+ }
37
+ function invalidate() { pending = null; cleanup.textContent = ''; if (undo?.after !== input.value) undo = null; }
38
+ function changed(event) { if (destroyed || composing || event?.isComposing) return; invalidate(); refresh(true); }
39
+ function beforeInput(event) {
40
+ if (destroyed || replacing || composing || event.isComposing || event.defaultPrevented || !event.inputType?.startsWith('insert')) return;
41
+ const text = typeof event.data === 'string' ? event.data : event.dataTransfer?.getData?.('text/plain');
42
+ if (typeof text !== 'string') return; // The native textarea enforces its own maxLength for paste/IME.
43
+ const start = input.selectionStart ?? input.value.length, end = input.selectionEnd ?? start;
44
+ if (input.value.length - (end - start) + text.length > limit) { event.preventDefault(); say(`مەزمۇن ئۇزۇنلۇقى ${limit} چەكتىن ئېشىپ كەتتى.`); }
45
+ }
46
+ function makeInputEvent(name, text, cancelable) {
47
+ if (typeof win.InputEvent === 'function') return new win.InputEvent(name, { bubbles: true, composed: true, cancelable, inputType: 'insertReplacementText', data: text });
48
+ const event = new win.Event(name, { bubbles: true, composed: true, cancelable });
49
+ Object.defineProperties(event, { inputType: { value: 'insertReplacementText' }, data: { value: text } }); return event;
50
+ }
51
+ function caret() { return { start: input.selectionStart ?? 0, end: input.selectionEnd ?? 0, direction: input.selectionDirection || 'none' }; }
52
+ function commit(text, selection, { editable = true, restoreOriginal = false } = {}) {
53
+ if (composing || editable && (input.disabled || input.readOnly)) return false;
54
+ if (!restoreOriginal && text.length > limit) { say(`مەزمۇن ئۇزۇنلۇقى ${limit} چەكتىن ئېشىپ كەتتى.`); return false; }
55
+ replacing = true;
56
+ let accepted;
57
+ try { accepted = input.dispatchEvent(makeInputEvent('beforeinput', text, true)); } finally { replacing = false; }
58
+ if (!accepted) { say('ئۆزگەرتىش قوللىنىلمىدى.'); return false; }
59
+ input.value = text;
60
+ input.setSelectionRange(Math.min(selection.start, text.length), Math.min(selection.end, text.length), selection.direction);
61
+ input.dispatchEvent(makeInputEvent('input', text, false)); return true;
62
+ }
63
+ function setValue(value) {
64
+ alive(); if (typeof value !== 'string') throw new TypeError('Writing value must be a string');
65
+ if (value.length > limit) throw new RangeError(`Writing value exceeds maxLength ${limit}`);
66
+ if (value === input.value) return false;
67
+ return commit(value, caret(), { editable: false });
68
+ }
69
+ function previewCleanup(options = {}) {
70
+ alive(); if (composing) { say('يېزىش تاماملانغاندىن كېيىن ئالدىن كۆرۈڭ.'); return null; }
71
+ const result = createCleanupPreview(input.value, options);
72
+ pending = Object.freeze({ ...result, options: Object.freeze({ ...result.options }), changes: Object.freeze(result.changes.map((change) => Object.freeze({ ...change }))), diff: Object.freeze({ ...result.diff }) });
73
+ cleanup.textContent = visibleText(result.text, { showSpaces: false }); updateButtons();
74
+ say(result.changed ? 'ئالدىن كۆرۈنۈش تەييار. قوللىنىشتىن بۇرۇن ئۆزگىرىشنى تەكشۈرۈڭ.' : 'بۇ تاللاشلاردا ئۆزگىرىش يوق.'); return pending;
75
+ }
76
+ function applyCleanup() {
77
+ alive();
78
+ if (!pending?.changed || pending.original !== input.value || composing) { invalidate(); updateButtons(); say('ئاۋۋال يېڭى ئالدىن كۆرۈنۈش ھاسىل قىلىڭ.'); return false; }
79
+ const candidate = pending, previous = caret(), before = input.value;
80
+ const a = candidate.diff.prefix.length, b = a + candidate.diff.removed.length, inserted = candidate.diff.added.length;
81
+ const mapped = (offset) => offset <= a ? offset : offset >= b ? offset + inserted - (b - a) : a + inserted;
82
+ if (!commit(candidate.text, { start: mapped(previous.start), end: mapped(previous.end), direction: previous.direction })) return false;
83
+ if (input.value === candidate.text) undo = { before, after: candidate.text, selection: previous };
84
+ pending = null; updateButtons(); say('ئۆزگىرىش قوللىنىلدى؛ بىر قېتىم كەينىگە قايتۇرالايسىز.'); return true;
85
+ }
86
+ function undoCleanup() {
87
+ alive(); if (!undo || undo.after !== input.value || composing) { updateButtons(); return false; }
88
+ const record = undo;
89
+ if (!commit(record.before, record.selection, { restoreOriginal: true })) return false;
90
+ undo = null; pending = null; cleanup.textContent = ''; updateButtons(); say('ئەسلى مەزمۇن قايتۇرۇلدى.'); return true;
91
+ }
92
+ function toggleKeyboard() { if (destroyed) return; host.hidden = !host.hidden; toggle.setAttribute('aria-expanded', String(!host.hidden)); if (host.hidden && host.contains(doc.activeElement)) toggle.focus(); }
93
+ function keyboardEscape(event) { if (event.key === 'Escape' && !host.hidden) { event.preventDefault(); host.hidden = true; toggle.setAttribute('aria-expanded', 'false'); toggle.focus(); } }
94
+ function compositionStart() { composing = true; pending = null; cleanup.textContent = ''; updateButtons(); }
95
+ function compositionEnd() { composing = false; invalidate(); refresh(true); }
96
+ const previewClick = () => previewCleanup({ normalization: 'NFC', lineEndings: 'lf' });
97
+ input.addEventListener('beforeinput', beforeInput); input.addEventListener('input', changed); input.addEventListener('compositionstart', compositionStart); input.addEventListener('compositionend', compositionEnd);
98
+ toggle.addEventListener('click', toggleKeyboard); host.addEventListener('keydown', keyboardEscape); previewButton.addEventListener('click', previewClick); applyButton.addEventListener('click', applyCleanup); undoButton.addEventListener('click', undoCleanup);
99
+ refresh();
100
+ return {
101
+ getValue() { alive(); return input.value; }, setValue, previewCleanup, applyCleanup, undoCleanup, validate,
102
+ destroy() {
103
+ if (destroyed) return; destroyed = true;
104
+ input.removeEventListener('beforeinput', beforeInput); input.removeEventListener('input', changed); input.removeEventListener('compositionstart', compositionStart); input.removeEventListener('compositionend', compositionEnd);
105
+ toggle.removeEventListener('click', toggleKeyboard); host.removeEventListener('keydown', keyboardEscape); previewButton.removeEventListener('click', previewClick); applyButton.removeEventListener('click', applyCleanup); undoButton.removeEventListener('click', undoCleanup);
106
+ keyboard.destroy(); host.hidden = old.hostHidden; applyButton.disabled = old.applyDisabled; undoButton.disabled = old.undoDisabled;
107
+ for (const [node, attribute, value] of [[input, 'maxlength', old.maxLength], [input, 'dir', old.inputDir], [input, 'aria-invalid', old.invalid], [preview, 'dir', old.previewDir], [toggle, 'aria-expanded', old.expanded]]) { if (value === null) node.removeAttribute(attribute); else node.setAttribute(attribute, value); }
108
+ pending = null; undo = null;
109
+ },
110
+ };
111
+ }