@uiwwsw/virtual-keyboard 0.7.1 → 0.7.2

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/dist/index.js CHANGED
@@ -1,1873 +1,2 @@
1
- // src/components/Input.tsx
2
- import {
3
- useCallback,
4
- useEffect as useEffect2,
5
- useMemo,
6
- useRef,
7
- useState as useState2,
8
- useImperativeHandle,
9
- useId
10
- } from "react";
11
-
12
- // src/components/ShadowWrapper.tsx
13
- import { useEffect, useState, memo } from "react";
14
- import ReactDOM from "react-dom";
15
- import { jsxDEV, Fragment } from "react/jsx-dev-runtime";
16
- var ShadowWrapper = memo((props) => {
17
- const [host, setHost] = useState(null);
18
- const [shadowRoot, setShadowRoot] = useState(null);
19
- const { tagName, css, children, hostRef, ...rest } = props;
20
- const Component = tagName;
21
- useEffect(() => {
22
- if (host && !shadowRoot) {
23
- const shadow = host.attachShadow({ mode: "open" });
24
- setShadowRoot(shadow);
25
- }
26
- if (hostRef) {
27
- hostRef.current = host;
28
- }
29
- }, [host, shadowRoot, hostRef]);
30
- return /* @__PURE__ */ jsxDEV(Component, {
31
- ref: setHost,
32
- ...rest,
33
- children: shadowRoot && ReactDOM.createPortal(/* @__PURE__ */ jsxDEV(Fragment, {
34
- children: [
35
- css && /* @__PURE__ */ jsxDEV("style", {
36
- children: css
37
- }, undefined, false, undefined, this),
38
- children
39
- ]
40
- }, undefined, true, undefined, this), shadowRoot)
41
- }, undefined, false, undefined, this);
42
- });
43
- ShadowWrapper.displayName = "ShadowWrapper";
44
-
45
- // src/components/Context.tsx
46
- import {
47
- createContext,
48
- useContext
49
- } from "react";
50
- var VirtualInputContext = createContext(null);
51
- function useVirtualInputContext() {
52
- const context = useContext(VirtualInputContext);
53
- if (!context) {
54
- throw new Error("Input must be used within an <VirtualInputProvider>. Wrap your app with <VirtualInputProvider>.");
55
- }
56
- return context;
57
- }
58
-
59
- // node_modules/es-hangul/dist/index.mjs
60
- function excludeLastElement(array) {
61
- const lastElement = array[array.length - 1];
62
- return [array.slice(0, -1), lastElement != null ? lastElement : ""];
63
- }
64
- function joinString(...args) {
65
- return args.join("");
66
- }
67
- function isBlank(character) {
68
- return /^\s$/.test(character);
69
- }
70
- function assert(condition, errorMessage) {
71
- if (condition === false) {
72
- throw new Error(errorMessage != null ? errorMessage : "Invalid condition");
73
- }
74
- }
75
- function hasValueInReadOnlyStringList(list, value) {
76
- return list.some((item) => item === value);
77
- }
78
- function hasProperty(obj, key) {
79
- return Object.prototype.hasOwnProperty.call(obj, key);
80
- }
81
- var _JASO_HANGUL_NFD = [..."각힣".normalize("NFD")].map((char) => char.charCodeAt(0));
82
- var COMPLETE_HANGUL_START_CHARCODE = "가".charCodeAt(0);
83
- var COMPLETE_HANGUL_END_CHARCODE = "힣".charCodeAt(0);
84
- var NUMBER_OF_JONGSEONG = 28;
85
- var NUMBER_OF_JUNGSEONG = 21;
86
- var DISASSEMBLED_CONSONANTS_BY_CONSONANT = {
87
- "": "",
88
- ㄱ: "ㄱ",
89
- ㄲ: "ㄲ",
90
- ㄳ: "ㄱㅅ",
91
- ㄴ: "ㄴ",
92
- ㄵ: "ㄴㅈ",
93
- ㄶ: "ㄴㅎ",
94
- ㄷ: "ㄷ",
95
- ㄸ: "ㄸ",
96
- ㄹ: "ㄹ",
97
- ㄺ: "ㄹㄱ",
98
- ㄻ: "ㄹㅁ",
99
- ㄼ: "ㄹㅂ",
100
- ㄽ: "ㄹㅅ",
101
- ㄾ: "ㄹㅌ",
102
- ㄿ: "ㄹㅍ",
103
- ㅀ: "ㄹㅎ",
104
- ㅁ: "ㅁ",
105
- ㅂ: "ㅂ",
106
- ㅃ: "ㅃ",
107
- ㅄ: "ㅂㅅ",
108
- ㅅ: "ㅅ",
109
- ㅆ: "ㅆ",
110
- ㅇ: "ㅇ",
111
- ㅈ: "ㅈ",
112
- ㅉ: "ㅉ",
113
- ㅊ: "ㅊ",
114
- ㅋ: "ㅋ",
115
- ㅌ: "ㅌ",
116
- ㅍ: "ㅍ",
117
- ㅎ: "ㅎ"
118
- };
119
- var DISASSEMBLED_VOWELS_BY_VOWEL = {
120
- ㅏ: "ㅏ",
121
- ㅐ: "ㅐ",
122
- ㅑ: "ㅑ",
123
- ㅒ: "ㅒ",
124
- ㅓ: "ㅓ",
125
- ㅔ: "ㅔ",
126
- ㅕ: "ㅕ",
127
- ㅖ: "ㅖ",
128
- ㅗ: "ㅗ",
129
- ㅘ: "ㅗㅏ",
130
- ㅙ: "ㅗㅐ",
131
- ㅚ: "ㅗㅣ",
132
- ㅛ: "ㅛ",
133
- ㅜ: "ㅜ",
134
- ㅝ: "ㅜㅓ",
135
- ㅞ: "ㅜㅔ",
136
- ㅟ: "ㅜㅣ",
137
- ㅠ: "ㅠ",
138
- ㅡ: "ㅡ",
139
- ㅢ: "ㅡㅣ",
140
- ㅣ: "ㅣ"
141
- };
142
- var CHOSEONGS = [
143
- "ㄱ",
144
- "ㄲ",
145
- "ㄴ",
146
- "ㄷ",
147
- "ㄸ",
148
- "ㄹ",
149
- "ㅁ",
150
- "ㅂ",
151
- "ㅃ",
152
- "ㅅ",
153
- "ㅆ",
154
- "ㅇ",
155
- "ㅈ",
156
- "ㅉ",
157
- "ㅊ",
158
- "ㅋ",
159
- "ㅌ",
160
- "ㅍ",
161
- "ㅎ"
162
- ];
163
- var JUNSEONGS = Object.values(DISASSEMBLED_VOWELS_BY_VOWEL);
164
- var JONGSEONGS = [
165
- "",
166
- "ㄱ",
167
- "ㄲ",
168
- "ㄳ",
169
- "ㄴ",
170
- "ㄵ",
171
- "ㄶ",
172
- "ㄷ",
173
- "ㄹ",
174
- "ㄺ",
175
- "ㄻ",
176
- "ㄼ",
177
- "ㄽ",
178
- "ㄾ",
179
- "ㄿ",
180
- "ㅀ",
181
- "ㅁ",
182
- "ㅂ",
183
- "ㅄ",
184
- "ㅅ",
185
- "ㅆ",
186
- "ㅇ",
187
- "ㅈ",
188
- "ㅊ",
189
- "ㅋ",
190
- "ㅌ",
191
- "ㅍ",
192
- "ㅎ"
193
- ].map((consonant) => DISASSEMBLED_CONSONANTS_BY_CONSONANT[consonant]);
194
- var HANGUL_DIGITS = [
195
- "",
196
- "만",
197
- "억",
198
- "조",
199
- "경",
200
- "해",
201
- "자",
202
- "양",
203
- "구",
204
- "간",
205
- "정",
206
- "재",
207
- "극",
208
- "항하사",
209
- "아승기",
210
- "나유타",
211
- "불가사의",
212
- "무량대수",
213
- "겁",
214
- "업"
215
- ];
216
- var HANGUL_DIGITS_MAX = HANGUL_DIGITS.length * 4;
217
- function disassembleCompleteCharacter(letter) {
218
- const charCode = letter.charCodeAt(0);
219
- const isCompleteHangul = COMPLETE_HANGUL_START_CHARCODE <= charCode && charCode <= COMPLETE_HANGUL_END_CHARCODE;
220
- if (!isCompleteHangul) {
221
- return;
222
- }
223
- const hangulCode = charCode - COMPLETE_HANGUL_START_CHARCODE;
224
- const jongseongIndex = hangulCode % NUMBER_OF_JONGSEONG;
225
- const jungseongIndex = (hangulCode - jongseongIndex) / NUMBER_OF_JONGSEONG % NUMBER_OF_JUNGSEONG;
226
- const choseongIndex = Math.floor((hangulCode - jongseongIndex) / NUMBER_OF_JONGSEONG / NUMBER_OF_JUNGSEONG);
227
- return {
228
- choseong: CHOSEONGS[choseongIndex],
229
- jungseong: JUNSEONGS[jungseongIndex],
230
- jongseong: JONGSEONGS[jongseongIndex]
231
- };
232
- }
233
- function disassembleToGroups(str) {
234
- const result = [];
235
- for (const letter of str) {
236
- const disassembledComplete = disassembleCompleteCharacter(letter);
237
- if (disassembledComplete != null) {
238
- result.push([
239
- ...disassembledComplete.choseong,
240
- ...disassembledComplete.jungseong,
241
- ...disassembledComplete.jongseong
242
- ]);
243
- continue;
244
- }
245
- if (hasProperty(DISASSEMBLED_CONSONANTS_BY_CONSONANT, letter)) {
246
- const disassembledConsonant = DISASSEMBLED_CONSONANTS_BY_CONSONANT[letter];
247
- result.push([...disassembledConsonant]);
248
- continue;
249
- }
250
- if (hasProperty(DISASSEMBLED_VOWELS_BY_VOWEL, letter)) {
251
- const disassembledVowel = DISASSEMBLED_VOWELS_BY_VOWEL[letter];
252
- result.push([...disassembledVowel]);
253
- continue;
254
- }
255
- result.push([letter]);
256
- }
257
- return result;
258
- }
259
- function disassemble(str) {
260
- return disassembleToGroups(str).reduce((hanguls, disassembleds) => `${hanguls}${disassembleds.join("")}`, "");
261
- }
262
- function canBeChoseong(character) {
263
- return hasValueInReadOnlyStringList(CHOSEONGS, character);
264
- }
265
- function canBeJongseong(character) {
266
- return hasValueInReadOnlyStringList(JONGSEONGS, character);
267
- }
268
- function canBeJungseong(character) {
269
- if (!character) {
270
- return false;
271
- }
272
- if (character in DISASSEMBLED_VOWELS_BY_VOWEL) {
273
- return true;
274
- }
275
- return hasValueInReadOnlyStringList(JUNSEONGS, character);
276
- }
277
- function combineVowels(vowel1, vowel2) {
278
- var _a, _b;
279
- return (_b = (_a = Object.entries(DISASSEMBLED_VOWELS_BY_VOWEL).find(([, value]) => value === `${vowel1}${vowel2}`)) == null ? undefined : _a[0]) != null ? _b : `${vowel1}${vowel2}`;
280
- }
281
- function combineCharacter(choseong, jungseong, jongseong = "") {
282
- if (canBeChoseong(choseong) === false || canBeJungseong(jungseong) === false || canBeJongseong(jongseong) === false) {
283
- throw new Error(`Invalid hangul Characters: ${choseong}, ${jungseong}, ${jongseong}`);
284
- }
285
- const numOfJungseongs = JUNSEONGS.length;
286
- const numOfJongseongs = JONGSEONGS.length;
287
- const choseongIndex = CHOSEONGS.indexOf(choseong);
288
- const jungseongIndex = JUNSEONGS.indexOf(jungseong);
289
- const jongseongIndex = JONGSEONGS.indexOf(jongseong);
290
- const choseongOfTargetConsonant = choseongIndex * numOfJungseongs * numOfJongseongs;
291
- const choseongOfTargetVowel = jungseongIndex * numOfJongseongs;
292
- const unicode = COMPLETE_HANGUL_START_CHARCODE + choseongOfTargetConsonant + choseongOfTargetVowel + jongseongIndex;
293
- return String.fromCharCode(unicode);
294
- }
295
- function hasBatchim(str, options) {
296
- const lastChar = str[str.length - 1];
297
- if (lastChar == null) {
298
- return false;
299
- }
300
- const charCode = lastChar.charCodeAt(0);
301
- const isNotCompleteHangul = charCode < COMPLETE_HANGUL_START_CHARCODE || charCode > COMPLETE_HANGUL_END_CHARCODE;
302
- if (isNotCompleteHangul) {
303
- return false;
304
- }
305
- const batchimCode = (charCode - COMPLETE_HANGUL_START_CHARCODE) % NUMBER_OF_JONGSEONG;
306
- const batchimLength = JONGSEONGS[batchimCode].length;
307
- switch (options == null ? undefined : options.only) {
308
- case "single": {
309
- return batchimLength === 1;
310
- }
311
- case "double": {
312
- return batchimLength === 2;
313
- }
314
- default: {
315
- return batchimCode > 0;
316
- }
317
- }
318
- }
319
- function removeLastCharacter(words) {
320
- const lastCharacter = words[words.length - 1];
321
- if (lastCharacter == null) {
322
- return "";
323
- }
324
- const result = (() => {
325
- const disassembleLastCharacter = disassembleToGroups(lastCharacter);
326
- const [lastCharacterWithoutLastAlphabet] = excludeLastElement(disassembleLastCharacter[0]);
327
- if (lastCharacterWithoutLastAlphabet.length <= 3) {
328
- const [first, middle, last] = lastCharacterWithoutLastAlphabet;
329
- if (middle != null) {
330
- return canBeJungseong(last) ? combineCharacter(first, `${middle}${last}`) : combineCharacter(first, middle, last);
331
- }
332
- return first;
333
- } else {
334
- const [first, firstJungseong, secondJungseong, firstJongseong] = lastCharacterWithoutLastAlphabet;
335
- return combineCharacter(first, `${firstJungseong}${secondJungseong}`, firstJongseong);
336
- }
337
- })();
338
- return [words.substring(0, words.length - 1), result].join("");
339
- }
340
- function isHangulCharacter(character) {
341
- return /^[가-힣]$/.test(character);
342
- }
343
- function isHangulAlphabet(character) {
344
- return /^[ㄱ-ㅣ]$/.test(character);
345
- }
346
- function binaryAssembleAlphabets(source, nextCharacter) {
347
- if (canBeJungseong(`${source}${nextCharacter}`)) {
348
- return combineVowels(source, nextCharacter);
349
- }
350
- const isConsonantSource = canBeJungseong(source) === false;
351
- if (isConsonantSource && canBeJungseong(nextCharacter)) {
352
- return combineCharacter(source, nextCharacter);
353
- }
354
- return joinString(source, nextCharacter);
355
- }
356
- function linkHangulCharacters(source, nextCharacter) {
357
- const sourceJamo = disassembleToGroups(source)[0];
358
- const [, lastJamo] = excludeLastElement(sourceJamo);
359
- return joinString(removeLastCharacter(source), combineCharacter(lastJamo, nextCharacter));
360
- }
361
- function binaryAssembleCharacters(source, nextCharacter) {
362
- assert(isHangulCharacter(source) || isHangulAlphabet(source), `Invalid source character: ${source}. Source must be one character.`);
363
- assert(isHangulAlphabet(nextCharacter), `Invalid next character: ${nextCharacter}. Next character must be one of the choseong, jungseong, or jongseong.`);
364
- const sourceJamos = disassembleToGroups(source)[0];
365
- const isSingleCharacter = sourceJamos.length === 1;
366
- if (isSingleCharacter) {
367
- const sourceCharacter = sourceJamos[0];
368
- return binaryAssembleAlphabets(sourceCharacter, nextCharacter);
369
- }
370
- const [restJamos, lastJamo] = excludeLastElement(sourceJamos);
371
- const secondaryLastJamo = excludeLastElement(restJamos)[1];
372
- const needLinking = canBeChoseong(lastJamo) && canBeJungseong(nextCharacter);
373
- if (needLinking) {
374
- return linkHangulCharacters(source, nextCharacter);
375
- }
376
- const fixConsonant = curriedCombineCharacter;
377
- const combineJungseong = fixConsonant(restJamos[0]);
378
- if (canBeJungseong(`${lastJamo}${nextCharacter}`)) {
379
- return combineJungseong(`${lastJamo}${nextCharacter}`)();
380
- }
381
- if (canBeJungseong(`${secondaryLastJamo}${lastJamo}`) && canBeJongseong(nextCharacter)) {
382
- return combineJungseong(`${secondaryLastJamo}${lastJamo}`)(nextCharacter);
383
- }
384
- if (canBeJungseong(lastJamo) && canBeJongseong(nextCharacter)) {
385
- return combineJungseong(lastJamo)(nextCharacter);
386
- }
387
- const fixVowel = combineJungseong;
388
- const combineJongseong = fixVowel(canBeJungseong(`${restJamos[1]}${restJamos[2]}`) ? `${restJamos[1]}${restJamos[2]}` : restJamos[1]);
389
- const lastConsonant = lastJamo;
390
- if (hasBatchim(source, {
391
- only: "single"
392
- }) && canBeJongseong(`${lastConsonant}${nextCharacter}`)) {
393
- return combineJongseong(`${lastConsonant}${nextCharacter}`);
394
- }
395
- return joinString(source, nextCharacter);
396
- }
397
- function binaryAssemble(source, nextCharacter) {
398
- const [rest, lastCharacter] = excludeLastElement(source.split(""));
399
- const needJoinString = isBlank(lastCharacter) || isBlank(nextCharacter);
400
- return joinString(...rest, needJoinString ? joinString(lastCharacter, nextCharacter) : binaryAssembleCharacters(lastCharacter, nextCharacter));
401
- }
402
- var curriedCombineCharacter = (choseong) => (jungseong) => (jongseong = "") => combineCharacter(choseong, jungseong, jongseong);
403
- function assemble(fragments) {
404
- const disassembled = disassemble(fragments.join("")).split("");
405
- return disassembled.reduce(binaryAssemble);
406
- }
407
- var JASO_HANGUL_NFD = {
408
- START_CHOSEONG: _JASO_HANGUL_NFD[0],
409
- START_JUNGSEONG: _JASO_HANGUL_NFD[1],
410
- START_JONGSEONG: _JASO_HANGUL_NFD[2],
411
- END_CHOSEONG: _JASO_HANGUL_NFD[3],
412
- END_JUNGSEONG: _JASO_HANGUL_NFD[4],
413
- END_JONGSEONG: _JASO_HANGUL_NFD[5]
414
- };
415
- var EXTRACT_CHOSEONG_REGEX = new RegExp(`[^\\u${JASO_HANGUL_NFD.START_CHOSEONG.toString(16)}-\\u${JASO_HANGUL_NFD.END_CHOSEONG.toString(16)}ㄱ-ㅎ\\s]+`, "ug");
416
- var CHOOSE_NFD_CHOSEONG_REGEX = new RegExp(`[\\u${JASO_HANGUL_NFD.START_CHOSEONG.toString(16)}-\\u${JASO_HANGUL_NFD.END_CHOSEONG.toString(16)}]`, "g");
417
- var 로__ = ["으로/로", "으로서/로서", "으로써/로써", "으로부터/로부터"];
418
- function josa(word, josa2) {
419
- if (word.length === 0) {
420
- return word;
421
- }
422
- return word + josaPicker(word, josa2);
423
- }
424
- josa.pick = josaPicker;
425
- function josaPicker(word, josa2) {
426
- var _a;
427
- if (word.length === 0) {
428
- return josa2.split("/")[0];
429
- }
430
- const has_ = hasBatchim(word);
431
- let index = has_ ? 0 : 1;
432
- const is_ = has_ && ((_a = disassembleCompleteCharacter(word[word.length - 1])) == null ? undefined : _a.jongseong) === "ㄹ";
433
- const isCaseOf_ = has_ && is_ && 로__.includes(josa2);
434
- if (josa2 === "와/과" || isCaseOf_) {
435
- index = index === 0 ? 1 : 0;
436
- }
437
- const isEndsWith_ = word[word.length - 1] === "이";
438
- if (josa2 === "이에요/예요" && isEndsWith_) {
439
- index = 1;
440
- }
441
- return josa2.split("/")[index];
442
- }
443
- var QWERTY_KEYBOARD_MAP = {
444
- q: "ㅂ",
445
- Q: "ㅃ",
446
- w: "ㅈ",
447
- W: "ㅉ",
448
- e: "ㄷ",
449
- E: "ㄸ",
450
- r: "ㄱ",
451
- R: "ㄲ",
452
- t: "ㅅ",
453
- T: "ㅆ",
454
- y: "ㅛ",
455
- Y: "ㅛ",
456
- u: "ㅕ",
457
- U: "ㅕ",
458
- i: "ㅑ",
459
- I: "ㅑ",
460
- o: "ㅐ",
461
- O: "ㅒ",
462
- p: "ㅔ",
463
- P: "ㅖ",
464
- a: "ㅁ",
465
- A: "ㅁ",
466
- s: "ㄴ",
467
- S: "ㄴ",
468
- d: "ㅇ",
469
- D: "ㅇ",
470
- f: "ㄹ",
471
- F: "ㄹ",
472
- g: "ㅎ",
473
- G: "ㅎ",
474
- h: "ㅗ",
475
- H: "ㅗ",
476
- j: "ㅓ",
477
- J: "ㅓ",
478
- k: "ㅏ",
479
- K: "ㅏ",
480
- l: "ㅣ",
481
- L: "ㅣ",
482
- z: "ㅋ",
483
- Z: "ㅋ",
484
- x: "ㅌ",
485
- X: "ㅌ",
486
- c: "ㅊ",
487
- C: "ㅊ",
488
- v: "ㅍ",
489
- V: "ㅍ",
490
- b: "ㅠ",
491
- B: "ㅠ",
492
- n: "ㅜ",
493
- N: "ㅜ",
494
- m: "ㅡ",
495
- M: "ㅡ"
496
- };
497
- function convertQwertyToAlphabet(word) {
498
- return word.split("").map((inputText) => hasProperty(QWERTY_KEYBOARD_MAP, inputText) ? QWERTY_KEYBOARD_MAP[inputText] : inputText).join("");
499
- }
500
- function convertQwertyToHangul(word) {
501
- if (!word) {
502
- return "";
503
- }
504
- return assemble([...convertQwertyToAlphabet(word)]);
505
- }
506
-
507
- // src/utils/isHangul.ts
508
- function isHangul(char) {
509
- return /^[\u1100-\u11FF\u3130-\u318F\uAC00-\uD7AF]$/.test(char);
510
- }
511
-
512
- // src/utils/parseKeyInput.ts
513
- function parseKeyInput(e, hangulMode) {
514
- const isMac = navigator.userAgent.includes("Mac");
515
- if (!isMac && e.key === "HangulMode") {
516
- return { handled: true, toggleHangulMode: true };
517
- }
518
- const ignoredKeys = new Set([
519
- "Shift",
520
- "Control",
521
- "Alt",
522
- "Meta",
523
- "CapsLock",
524
- "Enter",
525
- "Tab",
526
- "ArrowUp",
527
- "ArrowDown",
528
- "ArrowLeft",
529
- "ArrowRight",
530
- "Backspace",
531
- "Delete",
532
- "Unidentified"
533
- ]);
534
- if (ignoredKeys.has(e.key)) {
535
- return { handled: false };
536
- }
537
- if (isMac) {
538
- if (isHangul(e.key)) {
539
- return {
540
- handled: true,
541
- text: e.key,
542
- composing: true
543
- };
544
- } else {
545
- return {
546
- handled: true,
547
- text: e.key,
548
- composing: false
549
- };
550
- }
551
- }
552
- if (hangulMode && e.key.length === 1) {
553
- return {
554
- handled: true,
555
- text: isHangul(e.key) ? e.key : convertQwertyToHangul(e.key),
556
- composing: true
557
- };
558
- }
559
- return {
560
- handled: true,
561
- text: e.key,
562
- composing: false
563
- };
564
- }
565
-
566
- // src/components/Input.tsx
567
- import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
568
- function VirtualInput({
569
- value: controlledValue,
570
- defaultValue,
571
- placeholder,
572
- onChange,
573
- ...props
574
- }) {
575
- const id = useId();
576
- const canvasRef = useRef(null);
577
- const containerRef = useRef(null);
578
- const [internalValue, setInternalValue] = useState2(controlledValue ?? defaultValue ?? "");
579
- const [caretIndex, setCaretIndex] = useState2(() => (controlledValue ?? defaultValue ?? "").length);
580
- const internalValueRef = useRef(internalValue);
581
- const caretIndexRef = useRef(caretIndex);
582
- const [selection, setSelection] = useState2({ start: null, end: null });
583
- const [showCursor, setShowCursor] = useState2(true);
584
- const showCursorRef = useRef(showCursor);
585
- useEffect2(() => {
586
- showCursorRef.current = showCursor;
587
- }, [showCursor]);
588
- const longPressTimerRef = useRef(null);
589
- const [showCopyFeedback, setShowCopyFeedback] = useState2(false);
590
- const pointerStartedRef = useRef(false);
591
- const pointerStartPositionRef = useRef(null);
592
- const charPositionsRef = useRef([]);
593
- const scrollXRef = useRef(0);
594
- useEffect2(() => {
595
- charPositionsRef.current = [];
596
- }, [internalValue]);
597
- const {
598
- focusId,
599
- onFocus,
600
- onBlur,
601
- hangulMode,
602
- setHangulMode,
603
- isCompositionRef,
604
- inputRef,
605
- shift
606
- } = useVirtualInputContext();
607
- const isFocused = focusId === id;
608
- useEffect2(() => {
609
- if (controlledValue !== undefined && controlledValue !== internalValue) {
610
- setInternalValue(controlledValue);
611
- internalValueRef.current = controlledValue;
612
- }
613
- }, [controlledValue, internalValue]);
614
- useEffect2(() => {
615
- if (!isFocused)
616
- return;
617
- const interval = setInterval(() => {
618
- setShowCursor((prev) => !prev);
619
- }, 530);
620
- return () => clearInterval(interval);
621
- }, [isFocused]);
622
- useEffect2(() => {
623
- setShowCursor(true);
624
- }, [caretIndex, internalValue]);
625
- const hasSelection = useMemo(() => selection.start !== null && selection.end !== null && selection.start !== selection.end, [selection]);
626
- const clearSelection = useCallback(() => {
627
- setSelection({ start: null, end: null });
628
- }, []);
629
- const deleteSelectedText = useCallback(() => {
630
- const currentVal = internalValueRef.current;
631
- if (!hasSelection || selection.start === null || selection.end === null) {
632
- return { newString: currentVal, finalCaretIndex: caretIndexRef.current };
633
- }
634
- const [start, end] = [selection.start, selection.end].sort((a, b) => a - b);
635
- const newString = currentVal.slice(0, start) + currentVal.slice(end);
636
- clearSelection();
637
- return { newString, finalCaretIndex: start };
638
- }, [
639
- hasSelection,
640
- selection,
641
- clearSelection
642
- ]);
643
- const draw = useCallback(() => {
644
- const canvas = canvasRef.current;
645
- const container = containerRef.current;
646
- if (!canvas || !container)
647
- return;
648
- const ctx = canvas.getContext("2d");
649
- if (!ctx)
650
- return;
651
- const dpr = window.devicePixelRatio || 1;
652
- const rect = container.getBoundingClientRect();
653
- if (canvas.width !== rect.width * dpr || canvas.height !== rect.height * dpr) {
654
- canvas.width = rect.width * dpr;
655
- canvas.height = rect.height * dpr;
656
- ctx.scale(dpr, dpr);
657
- charPositionsRef.current = [];
658
- }
659
- const width = rect.width;
660
- const height = rect.height;
661
- ctx.clearRect(0, 0, width, height);
662
- const computedStyle = window.getComputedStyle(container);
663
- const font = `${computedStyle.fontStyle} ${computedStyle.fontVariant} ${computedStyle.fontWeight} ${computedStyle.fontSize} ${computedStyle.fontFamily}`;
664
- ctx.font = font;
665
- ctx.textBaseline = "middle";
666
- const fontSize = parseFloat(computedStyle.fontSize);
667
- const paddingLeft = parseFloat(computedStyle.paddingLeft) || 0;
668
- const paddingRight = parseFloat(computedStyle.paddingRight) || 0;
669
- const borderLeft = parseFloat(computedStyle.borderLeftWidth) || 0;
670
- const borderRight = parseFloat(computedStyle.borderRightWidth) || 0;
671
- const color = computedStyle.color || "black";
672
- const caretColor = (computedStyle.caretColor !== "auto" ? computedStyle.caretColor : color) || "black";
673
- const y = height / 2;
674
- const x = borderLeft + paddingLeft;
675
- const text = internalValueRef.current;
676
- const cIndex = caretIndexRef.current;
677
- const isCursorVisible = showCursorRef.current;
678
- if (!text && placeholder) {
679
- ctx.fillStyle = "#aaa";
680
- ctx.fillText(placeholder, x, y);
681
- if (isFocused && isCursorVisible) {
682
- ctx.beginPath();
683
- ctx.moveTo(x, y - fontSize / 2);
684
- ctx.lineTo(x, y + fontSize / 2);
685
- ctx.strokeStyle = caretColor;
686
- ctx.lineWidth = 1.5;
687
- ctx.stroke();
688
- }
689
- return;
690
- }
691
- ctx.fillStyle = color;
692
- if (charPositionsRef.current.length !== text.length + 1) {
693
- const positions = [x];
694
- for (let i = 0;i < text.length; i++) {
695
- const w = ctx.measureText(text.slice(0, i + 1)).width;
696
- positions.push(x + w);
697
- }
698
- charPositionsRef.current = positions;
699
- }
700
- const charX = charPositionsRef.current;
701
- const caretPos = charX[cIndex] ?? x;
702
- const viewLeft = paddingLeft;
703
- const viewRight = width - paddingRight - borderLeft - borderRight;
704
- const safety = 2;
705
- const totalTextWidth = (charX[charX.length - 1] ?? x) - x;
706
- const availableWidth = viewRight - viewLeft;
707
- if (totalTextWidth < availableWidth) {
708
- scrollXRef.current = 0;
709
- } else {
710
- let s = scrollXRef.current;
711
- if (caretPos - s > viewRight - safety) {
712
- s = caretPos - viewRight + safety;
713
- }
714
- if (caretPos - s < viewLeft + safety) {
715
- s = caretPos - viewLeft - safety;
716
- }
717
- const contentEnd = charX[charX.length - 1] ?? x;
718
- const maxScroll = Math.max(0, contentEnd - viewRight + safety);
719
- s = Math.max(0, Math.min(s, maxScroll));
720
- scrollXRef.current = s;
721
- }
722
- ctx.save();
723
- ctx.translate(-scrollXRef.current, 0);
724
- if (hasSelection && selection.start !== null && selection.end !== null) {
725
- const [start, end] = [selection.start, selection.end].sort((a, b) => a - b);
726
- const startX = charX[start] ?? x;
727
- const endX = charX[end] ?? charX[charX.length - 1];
728
- ctx.fillStyle = "#b4d5fe";
729
- ctx.fillRect(startX, 0, endX - startX, height);
730
- ctx.fillStyle = color;
731
- }
732
- ctx.fillText(text, x, y);
733
- if (isFocused && isCursorVisible && !hasSelection) {
734
- const caretX = charX[cIndex] ?? x;
735
- ctx.beginPath();
736
- ctx.moveTo(caretX, y - fontSize / 2);
737
- ctx.lineTo(caretX, y + fontSize / 2);
738
- ctx.strokeStyle = caretColor;
739
- ctx.lineWidth = 1.5;
740
- ctx.stroke();
741
- }
742
- if (showCopyFeedback) {
743
- ctx.save();
744
- ctx.translate(scrollXRef.current, 0);
745
- ctx.fillStyle = "rgba(0, 0, 0, 0.7)";
746
- const msg = "Copied!";
747
- const msgWidth = ctx.measureText(msg).width + 20;
748
- const msgHeight = fontSize + 10;
749
- const cx = width / 2;
750
- const cy = height / 2;
751
- const r = 6;
752
- const rw = msgWidth;
753
- const rh = msgHeight;
754
- const rx = cx - rw / 2;
755
- const ry = cy - rh / 2;
756
- ctx.beginPath();
757
- ctx.fillStyle = "rgba(30, 41, 59, 0.9)";
758
- ctx.roundRect(rx, ry, rw, rh, r);
759
- ctx.fill();
760
- ctx.fillStyle = "#ffffff";
761
- ctx.font = `bold ${fontSize * 0.8}px system-ui`;
762
- ctx.textAlign = "center";
763
- ctx.textBaseline = "middle";
764
- ctx.fillText(msg, cx, cy);
765
- ctx.restore();
766
- }
767
- ctx.restore();
768
- }, [isFocused, placeholder, hasSelection, selection, showCopyFeedback]);
769
- useEffect2(() => {
770
- let animationFrameId;
771
- const loop = () => {
772
- draw();
773
- animationFrameId = requestAnimationFrame(loop);
774
- };
775
- loop();
776
- return () => cancelAnimationFrame(animationFrameId);
777
- }, [draw]);
778
- const updateValue = useCallback((newValue, newCaretIndex) => {
779
- internalValueRef.current = newValue;
780
- caretIndexRef.current = newCaretIndex;
781
- if (controlledValue === undefined) {
782
- setInternalValue(newValue);
783
- }
784
- const fakeInput = { value: newValue };
785
- const changeEvent = {
786
- target: fakeInput,
787
- currentTarget: fakeInput
788
- };
789
- onChange?.(changeEvent);
790
- setCaretIndex(newCaretIndex);
791
- }, [controlledValue, onChange]);
792
- const getCharIndexFromX = useCallback((clientX) => {
793
- const canvas = canvasRef.current;
794
- if (!canvas)
795
- return 0;
796
- const rect = canvas.getBoundingClientRect();
797
- const x = clientX - rect.left + scrollXRef.current;
798
- if (charPositionsRef.current.length === internalValue.length + 1) {
799
- const charX = charPositionsRef.current;
800
- for (let i = 0;i < charX.length - 1; i++) {
801
- const center = (charX[i] + charX[i + 1]) / 2;
802
- if (x < center)
803
- return i;
804
- }
805
- return internalValue.length;
806
- }
807
- const ctx = canvas.getContext("2d");
808
- if (!ctx)
809
- return 0;
810
- const computedStyle = window.getComputedStyle(containerRef.current);
811
- ctx.font = `${computedStyle.fontSize} ${computedStyle.fontFamily}`;
812
- let currentX = 0;
813
- for (let i = 0;i < internalValue.length; i++) {
814
- const w = ctx.measureText(internalValue[i]).width;
815
- if (x < currentX + w / 2)
816
- return i;
817
- currentX += w;
818
- }
819
- return internalValue.length;
820
- }, [internalValue]);
821
- const handleCanvasClick = useCallback((e) => {
822
- if (showCopyFeedback)
823
- return;
824
- const index = getCharIndexFromX(e.clientX);
825
- caretIndexRef.current = index;
826
- setCaretIndex(index);
827
- clearSelection();
828
- onFocus(id);
829
- }, [getCharIndexFromX, clearSelection, onFocus, id, showCopyFeedback]);
830
- const handleCopy = useCallback((e) => {
831
- e.preventDefault();
832
- const currentVal = internalValueRef.current;
833
- const sel = selection;
834
- if (sel.start !== null && sel.end !== null && sel.start !== sel.end) {
835
- const [start, end] = [sel.start, sel.end].sort((a, b) => a - b);
836
- const textToCopy = currentVal.slice(start, end);
837
- e.clipboardData.setData("text/plain", textToCopy);
838
- if (navigator.vibrate)
839
- navigator.vibrate(50);
840
- setShowCopyFeedback(true);
841
- setTimeout(() => setShowCopyFeedback(false), 1500);
842
- }
843
- }, [selection]);
844
- const handleCut = useCallback((e) => {
845
- e.preventDefault();
846
- const currentVal = internalValueRef.current;
847
- if (hasSelection && selection.start !== null && selection.end !== null) {
848
- const [start, end] = [selection.start, selection.end].sort((a, b) => a - b);
849
- const textToCopy = currentVal.slice(start, end);
850
- e.clipboardData.setData("text/plain", textToCopy);
851
- if (navigator.vibrate)
852
- navigator.vibrate(50);
853
- setShowCopyFeedback(true);
854
- setTimeout(() => setShowCopyFeedback(false), 1500);
855
- const { newString, finalCaretIndex } = deleteSelectedText();
856
- updateValue(newString, finalCaretIndex);
857
- }
858
- }, [hasSelection, selection, deleteSelectedText, updateValue]);
859
- const handlePaste = useCallback((e) => {
860
- e.preventDefault();
861
- const text = e.clipboardData.getData("text/plain");
862
- if (!text)
863
- return;
864
- const currentVal = internalValueRef.current;
865
- const currentCaret = caretIndexRef.current;
866
- const { newString, finalCaretIndex } = hasSelection ? deleteSelectedText() : { newString: currentVal, finalCaretIndex: currentCaret };
867
- const finalString = newString.slice(0, finalCaretIndex) + text + newString.slice(finalCaretIndex);
868
- updateValue(finalString, finalCaretIndex + text.length);
869
- }, [hasSelection, deleteSelectedText, updateValue]);
870
- const cancelLongPress = useCallback(() => {
871
- if (longPressTimerRef.current) {
872
- clearTimeout(longPressTimerRef.current);
873
- longPressTimerRef.current = null;
874
- }
875
- pointerStartedRef.current = false;
876
- pointerStartPositionRef.current = null;
877
- }, []);
878
- const handlePointerDown = useCallback((e) => {
879
- if (e.button !== 0)
880
- return;
881
- cancelLongPress();
882
- pointerStartedRef.current = true;
883
- pointerStartPositionRef.current = { x: e.clientX, y: e.clientY };
884
- longPressTimerRef.current = window.setTimeout(async () => {
885
- if (!pointerStartedRef.current)
886
- return;
887
- pointerStartedRef.current = false;
888
- try {
889
- if (internalValueRef.current) {
890
- await navigator.clipboard.writeText(internalValueRef.current);
891
- if (navigator.vibrate)
892
- navigator.vibrate(50);
893
- setShowCopyFeedback(true);
894
- setTimeout(() => setShowCopyFeedback(false), 1500);
895
- }
896
- } catch (err) {
897
- console.error("Failed to copy", err);
898
- }
899
- }, 600);
900
- }, [cancelLongPress]);
901
- const handlePointerMove = useCallback((e) => {
902
- if (!pointerStartedRef.current || !pointerStartPositionRef.current)
903
- return;
904
- const dx = Math.abs(e.clientX - pointerStartPositionRef.current.x);
905
- const dy = Math.abs(e.clientY - pointerStartPositionRef.current.y);
906
- if (dx > 10 || dy > 10)
907
- cancelLongPress();
908
- }, [cancelLongPress]);
909
- const handlePointerUp = useCallback(() => {
910
- cancelLongPress();
911
- }, [cancelLongPress]);
912
- const handleKeyDown = useCallback((e) => {
913
- const currentVal = internalValueRef.current;
914
- const currentCaret = caretIndexRef.current;
915
- if (e.key === "HangulMode") {
916
- setHangulMode(!hangulMode);
917
- return;
918
- }
919
- const isCmd = e.ctrlKey || e.metaKey;
920
- const isHome = e.key === "ArrowUp" || isCmd && e.key === "ArrowLeft" || e.key === "Home";
921
- const isEnd = e.key === "ArrowDown" || isCmd && e.key === "ArrowRight" || e.key === "End";
922
- if (isHome) {
923
- e.preventDefault();
924
- const newIndex = 0;
925
- if (e.shiftKey) {
926
- setSelection((prev) => ({
927
- start: prev.start ?? currentCaret,
928
- end: newIndex
929
- }));
930
- } else {
931
- clearSelection();
932
- }
933
- caretIndexRef.current = newIndex;
934
- setCaretIndex(newIndex);
935
- return;
936
- }
937
- if (isEnd) {
938
- e.preventDefault();
939
- const newIndex = currentVal.length;
940
- if (e.shiftKey) {
941
- setSelection((prev) => ({
942
- start: prev.start ?? currentCaret,
943
- end: newIndex
944
- }));
945
- } else {
946
- clearSelection();
947
- }
948
- caretIndexRef.current = newIndex;
949
- setCaretIndex(newIndex);
950
- return;
951
- }
952
- if (e.ctrlKey || e.metaKey) {
953
- const key = e.key.toLowerCase();
954
- if (key === "a") {
955
- e.preventDefault();
956
- setSelection({ start: 0, end: currentVal.length });
957
- caretIndexRef.current = currentVal.length;
958
- setCaretIndex(currentVal.length);
959
- return;
960
- }
961
- }
962
- if (e.shiftKey && (e.key === "ArrowLeft" || e.key === "ArrowRight")) {
963
- const newIndex = e.key === "ArrowLeft" ? Math.max(0, currentCaret - 1) : Math.min(currentVal.length, currentCaret + 1);
964
- setSelection((prev) => ({
965
- start: prev.start ?? currentCaret,
966
- end: newIndex
967
- }));
968
- caretIndexRef.current = newIndex;
969
- setCaretIndex(newIndex);
970
- return;
971
- }
972
- switch (e.key) {
973
- case "ArrowLeft": {
974
- const newIndex = Math.max(0, currentCaret - 1);
975
- caretIndexRef.current = newIndex;
976
- setCaretIndex(newIndex);
977
- clearSelection();
978
- return;
979
- }
980
- case "ArrowRight": {
981
- const newIndex = Math.min(currentVal.length, currentCaret + 1);
982
- caretIndexRef.current = newIndex;
983
- setCaretIndex(newIndex);
984
- clearSelection();
985
- return;
986
- }
987
- case "Backspace": {
988
- isCompositionRef.current = false;
989
- if (hasSelection) {
990
- const { newString: newString2, finalCaretIndex: finalCaretIndex2 } = deleteSelectedText();
991
- updateValue(newString2, finalCaretIndex2);
992
- } else if (currentCaret > 0) {
993
- const newString2 = currentVal.slice(0, currentCaret - 1) + currentVal.slice(currentCaret);
994
- updateValue(newString2, currentCaret - 1);
995
- }
996
- return;
997
- }
998
- }
999
- const result = parseKeyInput(e, hangulMode);
1000
- if (result.toggleHangulMode) {
1001
- setHangulMode(!hangulMode);
1002
- return;
1003
- }
1004
- if (!result.handled || !result.text)
1005
- return;
1006
- if (e.ctrlKey || e.metaKey || e.altKey)
1007
- return;
1008
- const { composing } = result;
1009
- let { text } = result;
1010
- if (shift && text.length === 1 && text.match(/[a-z]/i)) {
1011
- text = text.toUpperCase();
1012
- }
1013
- const { newString, finalCaretIndex } = hasSelection ? deleteSelectedText() : { newString: currentVal, finalCaretIndex: currentCaret };
1014
- const prevChar = newString[finalCaretIndex - 1];
1015
- if (composing && isHangul(prevChar) && isCompositionRef.current) {
1016
- const combined = assemble([prevChar, text]);
1017
- const finalString = newString.slice(0, finalCaretIndex - 1) + combined + newString.slice(finalCaretIndex);
1018
- updateValue(finalString, finalCaretIndex - 1 + combined.length);
1019
- } else {
1020
- const finalString = newString.slice(0, finalCaretIndex) + text + newString.slice(finalCaretIndex);
1021
- updateValue(finalString, finalCaretIndex + text.length);
1022
- }
1023
- isCompositionRef.current = composing;
1024
- }, [hangulMode, setHangulMode, isCompositionRef, shift, updateValue, hasSelection, deleteSelectedText, clearSelection]);
1025
- useImperativeHandle(inputRef, () => {
1026
- if (isFocused) {
1027
- return {
1028
- handleKeyDown,
1029
- scrollIntoView: () => {
1030
- containerRef.current?.scrollIntoView({
1031
- behavior: "smooth",
1032
- block: "nearest"
1033
- });
1034
- }
1035
- };
1036
- }
1037
- return inputRef.current;
1038
- }, [isFocused, handleKeyDown, inputRef]);
1039
- return /* @__PURE__ */ jsxDEV2(ShadowWrapper, {
1040
- tagName: "virtual-input-canvas",
1041
- hostRef: containerRef,
1042
- id,
1043
- className: props.className,
1044
- role: "textbox",
1045
- tabIndex: 0,
1046
- ...props,
1047
- style: {
1048
- display: "inline-block",
1049
- minHeight: "1.5em",
1050
- height: "1.5em",
1051
- outline: "none",
1052
- font: "inherit",
1053
- width: "100%",
1054
- position: "relative",
1055
- cursor: "text",
1056
- ...props.style
1057
- },
1058
- onFocus: () => onFocus(id, containerRef.current),
1059
- onBlur: (e) => onBlur(e),
1060
- onKeyDown: handleKeyDown,
1061
- onContextMenu: (e) => e.preventDefault(),
1062
- onCopy: handleCopy,
1063
- onCut: handleCut,
1064
- onPaste: handlePaste,
1065
- onClick: handleCanvasClick,
1066
- onPointerDown: handlePointerDown,
1067
- onPointerMove: handlePointerMove,
1068
- onPointerUp: handlePointerUp,
1069
- onPointerLeave: handlePointerUp,
1070
- onPointerCancel: handlePointerUp,
1071
- "data-virtual-input": "true",
1072
- css: `
1073
- :host {
1074
- display: inline-block;
1075
- position: relative;
1076
- }
1077
- canvas {
1078
- width: 100%;
1079
- height: 100%;
1080
- display: block;
1081
- }
1082
- `,
1083
- children: /* @__PURE__ */ jsxDEV2("canvas", {
1084
- ref: canvasRef,
1085
- style: { width: "100%", height: "100%", display: "block" }
1086
- }, undefined, false, undefined, this)
1087
- }, undefined, false, undefined, this);
1088
- }
1089
- // src/components/Provider.tsx
1090
- import {
1091
- useState as useState6,
1092
- useRef as useRef5,
1093
- useCallback as useCallback6,
1094
- useEffect as useEffect8
1095
- } from "react";
1096
-
1097
- // src/components/Keypad.tsx
1098
- import { useRef as useRef4, useEffect as useEffect4, useCallback as useCallback4 } from "react";
1099
- import { createPortal } from "react-dom";
1100
-
1101
- // src/utils/isMobileAgent.ts
1102
- function isMobileAgent(userAgent = navigator.userAgent) {
1103
- const mobileRegex = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i;
1104
- return mobileRegex.test(userAgent);
1105
- }
1106
-
1107
- // src/hooks/useKeypadLayout.ts
1108
- import { useCallback as useCallback2, useRef as useRef2 } from "react";
1109
- function useKeypadLayout({
1110
- layout,
1111
- viewport,
1112
- hangulMode,
1113
- shift
1114
- }) {
1115
- const keyBoundsRef = useRef2([]);
1116
- const getTransformedValue = useCallback2((cell) => {
1117
- if (cell.type === "char") {
1118
- const isConvertibleHangulSource = hangulMode && /[a-zA-Z]/.test(cell.value) && cell.value.length === 1;
1119
- if (isConvertibleHangulSource) {
1120
- return convertQwertyToHangul(cell.value);
1121
- }
1122
- if (shift) {
1123
- return cell.value.toUpperCase();
1124
- }
1125
- return cell.value;
1126
- }
1127
- return cell.label ?? cell.value;
1128
- }, [hangulMode, shift]);
1129
- const calculateLayout = useCallback2(() => {
1130
- if (!layout)
1131
- return [];
1132
- const scale = viewport.scale;
1133
- const compactRatio = Math.max(0, Math.min(1, (viewport.width - 260) / 140));
1134
- const padding = (2 + (10 - 2) * compactRatio) / scale;
1135
- const gap = (2 + (8 - 2) * compactRatio) / scale;
1136
- const totalHeight = 200 / scale;
1137
- const width = viewport.width;
1138
- const height = totalHeight;
1139
- const contentW = width - padding * 2;
1140
- const contentH = height - padding * 2;
1141
- const bounds = [];
1142
- const rowCount = layout.length;
1143
- const rowHeight = (contentH - (rowCount - 1) * gap) / rowCount;
1144
- let currentY = padding;
1145
- layout.forEach((row, rowIndex) => {
1146
- const rowWidth = contentW;
1147
- const totalFlexGrow = row.reduce((acc, cell) => acc + (cell.width || 1), 0);
1148
- const totalGapW = (row.length - 1) * gap;
1149
- const availableW = rowWidth - totalGapW;
1150
- const unitW = availableW / totalFlexGrow;
1151
- let currentX = padding;
1152
- row.forEach((cell, colIndex) => {
1153
- const flex = cell.width || 1;
1154
- const cellW = flex * unitW;
1155
- bounds.push({
1156
- x: currentX,
1157
- y: currentY,
1158
- w: cellW,
1159
- h: rowHeight,
1160
- value: cell.value,
1161
- type: cell.type,
1162
- label: getTransformedValue(cell),
1163
- rowIndex,
1164
- colIndex,
1165
- isAction: cell.type === "action"
1166
- });
1167
- currentX += cellW + gap;
1168
- });
1169
- currentY += rowHeight + gap;
1170
- });
1171
- return bounds;
1172
- }, [layout, viewport, getTransformedValue]);
1173
- return {
1174
- keyBoundsRef,
1175
- calculateLayout,
1176
- getTransformedValue
1177
- };
1178
- }
1179
-
1180
- // src/hooks/useKeypadInteraction.ts
1181
- import { useCallback as useCallback3, useRef as useRef3, useMemo as useMemo2, useEffect as useEffect3 } from "react";
1182
- function useKeypadInteraction({
1183
- inputRef,
1184
- toggleShift,
1185
- toggleKorean,
1186
- shift,
1187
- getTransformedValue,
1188
- keyBoundsRef,
1189
- calculateLayout
1190
- }) {
1191
- const activePresses = useRef3(new Map);
1192
- const repeatableKeys = useMemo2(() => new Set(["char", "Backspace", "Delete", "Space", "ArrowLeft", "ArrowRight"]), []);
1193
- const dispatchKeyEvent = useCallback3((value, type) => {
1194
- if (typeof navigator !== "undefined" && "vibrate" in navigator) {
1195
- navigator.vibrate?.(10);
1196
- }
1197
- if (type === "action") {
1198
- if (value === "Shift") {
1199
- toggleShift();
1200
- return;
1201
- }
1202
- if (value === "HangulMode") {
1203
- toggleKorean();
1204
- return;
1205
- }
1206
- }
1207
- const event = new KeyboardEvent("keydown", {
1208
- key: getTransformedValue({ value, type }),
1209
- code: `Key${value.toUpperCase()}`,
1210
- bubbles: true,
1211
- cancelable: true,
1212
- shiftKey: shift
1213
- });
1214
- inputRef.current?.handleKeyDown(event);
1215
- }, [getTransformedValue, inputRef, shift, toggleKorean, toggleShift]);
1216
- const clearRepeat = useCallback3((press) => {
1217
- if (!press?.repeatTimeout)
1218
- return;
1219
- window.clearTimeout(press.repeatTimeout);
1220
- }, []);
1221
- const startRepeat = useCallback3((press) => {
1222
- const canRepeat = press.type && repeatableKeys.has(press.type) || repeatableKeys.has(press.value);
1223
- if (!canRepeat)
1224
- return;
1225
- const firstDelay = 500;
1226
- const repeatInterval = 60;
1227
- const tick = () => {
1228
- const storedPress = activePresses.current.get(press.pointerId);
1229
- if (!storedPress)
1230
- return;
1231
- dispatchKeyEvent(storedPress.value, storedPress.type);
1232
- storedPress.repeatTimeout = window.setTimeout(tick, repeatInterval);
1233
- activePresses.current.set(press.pointerId, storedPress);
1234
- };
1235
- press.repeatTimeout = window.setTimeout(tick, firstDelay);
1236
- activePresses.current.set(press.pointerId, press);
1237
- }, [dispatchKeyEvent, repeatableKeys]);
1238
- const handlePointerDown = useCallback3((e) => {
1239
- e.preventDefault();
1240
- const canvas = e.currentTarget;
1241
- if (!canvas)
1242
- return;
1243
- if (!keyBoundsRef.current.length) {
1244
- keyBoundsRef.current = calculateLayout();
1245
- }
1246
- activePresses.current.forEach((press) => {
1247
- clearRepeat(press);
1248
- });
1249
- const rect = canvas.getBoundingClientRect();
1250
- const x = e.clientX - rect.left;
1251
- const y = e.clientY - rect.top;
1252
- const hitKey = keyBoundsRef.current.find((k) => x >= k.x && x <= k.x + k.w && y >= k.y && y <= k.y + k.h);
1253
- if (hitKey) {
1254
- const keyIndex = hitKey.rowIndex * 100 + hitKey.colIndex;
1255
- dispatchKeyEvent(hitKey.value, hitKey.type);
1256
- const press = {
1257
- pointerId: e.pointerId,
1258
- value: hitKey.value,
1259
- type: hitKey.type,
1260
- keyIndex
1261
- };
1262
- activePresses.current.set(e.pointerId, press);
1263
- startRepeat(press);
1264
- } else {
1265
- activePresses.current.set(e.pointerId, {
1266
- pointerId: e.pointerId,
1267
- value: "",
1268
- keyIndex: -1
1269
- });
1270
- }
1271
- }, [calculateLayout, clearRepeat, dispatchKeyEvent, startRepeat, keyBoundsRef]);
1272
- const handlePointerMove = useCallback3((e) => {
1273
- e.preventDefault();
1274
- const press = activePresses.current.get(e.pointerId);
1275
- if (!press)
1276
- return;
1277
- const canvas = e.currentTarget;
1278
- if (!canvas)
1279
- return;
1280
- const rect = canvas.getBoundingClientRect();
1281
- const x = e.clientX - rect.left;
1282
- const y = e.clientY - rect.top;
1283
- const hitKey = keyBoundsRef.current.find((k) => x >= k.x && x <= k.x + k.w && y >= k.y && y <= k.y + k.h);
1284
- if (hitKey) {
1285
- const newKeyIndex = hitKey.rowIndex * 100 + hitKey.colIndex;
1286
- if (newKeyIndex !== press.keyIndex) {
1287
- clearRepeat(press);
1288
- dispatchKeyEvent(hitKey.value, hitKey.type);
1289
- const newPress = {
1290
- pointerId: e.pointerId,
1291
- value: hitKey.value,
1292
- type: hitKey.type,
1293
- keyIndex: newKeyIndex
1294
- };
1295
- activePresses.current.set(e.pointerId, newPress);
1296
- startRepeat(newPress);
1297
- }
1298
- } else {
1299
- if (press.keyIndex !== -1) {
1300
- clearRepeat(press);
1301
- activePresses.current.set(e.pointerId, {
1302
- pointerId: e.pointerId,
1303
- value: "",
1304
- keyIndex: -1
1305
- });
1306
- }
1307
- }
1308
- }, [clearRepeat, dispatchKeyEvent, startRepeat, keyBoundsRef]);
1309
- const handlePointerUp = useCallback3((e) => {
1310
- e.preventDefault();
1311
- const press = activePresses.current.get(e.pointerId);
1312
- if (press) {
1313
- clearRepeat(press);
1314
- activePresses.current.delete(e.pointerId);
1315
- }
1316
- }, [clearRepeat]);
1317
- useEffect3(() => {
1318
- return () => {
1319
- activePresses.current.forEach((press) => {
1320
- if (press.repeatTimeout) {
1321
- window.clearTimeout(press.repeatTimeout);
1322
- }
1323
- });
1324
- activePresses.current.clear();
1325
- };
1326
- }, []);
1327
- const handlePointerCancel = useCallback3((e) => {
1328
- handlePointerUp(e);
1329
- }, [handlePointerUp]);
1330
- return {
1331
- activePresses,
1332
- handlePointerDown,
1333
- handlePointerMove,
1334
- handlePointerUp,
1335
- handlePointerCancel
1336
- };
1337
- }
1338
-
1339
- // src/components/Keypad.tsx
1340
- import { jsxDEV as jsxDEV3 } from "react/jsx-dev-runtime";
1341
- function VirtualKeypad({
1342
- layout,
1343
- viewport
1344
- }) {
1345
- const {
1346
- focusId,
1347
- onBlur,
1348
- onFocus,
1349
- inputRef,
1350
- shift,
1351
- hangulMode,
1352
- toggleShift,
1353
- toggleKorean,
1354
- theme
1355
- } = useVirtualInputContext();
1356
- const canvasRef = useRef4(null);
1357
- const containerRef = useRef4(null);
1358
- const {
1359
- keyBoundsRef,
1360
- calculateLayout,
1361
- getTransformedValue
1362
- } = useKeypadLayout({
1363
- layout,
1364
- viewport,
1365
- hangulMode,
1366
- shift
1367
- });
1368
- const {
1369
- activePresses,
1370
- handlePointerDown,
1371
- handlePointerMove,
1372
- handlePointerUp,
1373
- handlePointerCancel
1374
- } = useKeypadInteraction({
1375
- inputRef,
1376
- toggleShift,
1377
- toggleKorean,
1378
- shift,
1379
- getTransformedValue,
1380
- keyBoundsRef,
1381
- calculateLayout
1382
- });
1383
- const roundRect = useCallback4((ctx, x, y, w, h, r) => {
1384
- if (w < 2 * r)
1385
- r = w / 2;
1386
- if (h < 2 * r)
1387
- r = h / 2;
1388
- ctx.beginPath();
1389
- ctx.moveTo(x + r, y);
1390
- ctx.arcTo(x + w, y, x + w, y + h, r);
1391
- ctx.arcTo(x + w, y + h, x, y + h, r);
1392
- ctx.arcTo(x, y + h, x, y, r);
1393
- ctx.arcTo(x, y, x + w, y, r);
1394
- ctx.closePath();
1395
- }, []);
1396
- const drawKey = useCallback4((ctx, key, isPressed, isActiveModifier, scale, currentTheme) => {
1397
- const r = 10 / scale;
1398
- const { x, y, w, h } = key;
1399
- const colors = currentTheme === "dark" ? {
1400
- shadow: "#0f172a",
1401
- keyFace: isPressed ? "#334155" : "#1e293b",
1402
- text: "#f8fafc",
1403
- actionFace: isPressed ? "#475569" : "#334155",
1404
- activeModFace: isPressed ? "#f8fafc" : "#e2e8f0",
1405
- activeModText: "#0f172a"
1406
- } : {
1407
- shadow: "#cbd5e1",
1408
- keyFace: isPressed ? "#f1f5f9" : "#ffffff",
1409
- text: "#1e293b",
1410
- actionFace: isPressed ? "#e2e8f0" : "#f1f5f9",
1411
- activeModFace: isPressed ? "#bfdbfe" : "#dbeafe",
1412
- activeModText: "#1d4ed8"
1413
- };
1414
- let faceColor = colors.keyFace;
1415
- let textColor = colors.text;
1416
- if (key.isAction) {
1417
- faceColor = colors.actionFace;
1418
- }
1419
- if (isActiveModifier) {
1420
- faceColor = colors.activeModFace;
1421
- textColor = colors.activeModText;
1422
- }
1423
- const depth = 4 / scale;
1424
- const pressOffset = isPressed ? depth * 0.6 : 0;
1425
- ctx.fillStyle = colors.shadow;
1426
- roundRect(ctx, x, y + depth, w, h, r);
1427
- ctx.fill();
1428
- ctx.fillStyle = faceColor;
1429
- roundRect(ctx, x, y + pressOffset, w, h, r);
1430
- ctx.fill();
1431
- ctx.textAlign = "center";
1432
- ctx.textBaseline = "middle";
1433
- let fontSize = 20 / scale;
1434
- if (key.label.length > 1)
1435
- fontSize = 16 / scale;
1436
- const fontFamily = currentTheme === "dark" ? "Inter, system-ui, sans-serif" : "Inter, system-ui, sans-serif";
1437
- ctx.font = `500 ${fontSize}px "${fontFamily}"`;
1438
- ctx.fillStyle = textColor;
1439
- ctx.fillText(key.label, x + w / 2, y + h / 2 + pressOffset);
1440
- }, [roundRect]);
1441
- const draw = useCallback4(() => {
1442
- const canvas = canvasRef.current;
1443
- if (!canvas)
1444
- return;
1445
- const ctx = canvas.getContext("2d", { alpha: false });
1446
- if (!ctx)
1447
- return;
1448
- const dpr = window.devicePixelRatio || 1;
1449
- const rect = canvas.getBoundingClientRect();
1450
- if (Math.abs(canvas.width - rect.width * dpr) > 1 || Math.abs(canvas.height - rect.height * dpr) > 1) {
1451
- canvas.width = rect.width * dpr;
1452
- canvas.height = rect.height * dpr;
1453
- ctx.scale(dpr, dpr);
1454
- keyBoundsRef.current = calculateLayout();
1455
- }
1456
- if (keyBoundsRef.current.length === 0) {
1457
- keyBoundsRef.current = calculateLayout();
1458
- }
1459
- const width = rect.width;
1460
- const height = rect.height;
1461
- const bgColors = {
1462
- dark: "#0f172a",
1463
- light: "#e2e8f0"
1464
- };
1465
- ctx.fillStyle = bgColors[theme] || bgColors.light;
1466
- ctx.fillRect(0, 0, width, height);
1467
- const scale = viewport.scale;
1468
- keyBoundsRef.current.forEach((key) => {
1469
- let isPressed = false;
1470
- for (const press of activePresses.current.values()) {
1471
- const keyIndex = key.rowIndex * 100 + key.colIndex;
1472
- if (press.keyIndex === keyIndex) {
1473
- isPressed = true;
1474
- break;
1475
- }
1476
- }
1477
- const isActiveModifier = key.value === "Shift" && shift || key.value === "HangulMode" && hangulMode;
1478
- drawKey(ctx, key, isPressed, isActiveModifier, scale, theme);
1479
- });
1480
- }, [calculateLayout, drawKey, hangulMode, shift, viewport.scale, activePresses, keyBoundsRef, theme]);
1481
- useEffect4(() => {
1482
- keyBoundsRef.current = [];
1483
- }, [hangulMode, shift, keyBoundsRef]);
1484
- const outsideTapRef = useRef4(null);
1485
- useEffect4(() => {
1486
- const isInsideVirtual = (path, keypadEl) => {
1487
- const inKeypad = path.includes(keypadEl);
1488
- const inInput = path.some((node) => node instanceof Element && node.getAttribute("data-virtual-input") === "true");
1489
- return inKeypad || inInput;
1490
- };
1491
- const handlePointerDown2 = (e) => {
1492
- if (!containerRef.current || !focusId)
1493
- return;
1494
- const path = e.composedPath();
1495
- if (isInsideVirtual(path, containerRef.current)) {
1496
- outsideTapRef.current = null;
1497
- return;
1498
- }
1499
- outsideTapRef.current = { pointerId: e.pointerId, x: e.clientX, y: e.clientY };
1500
- };
1501
- const handlePointerUp2 = (e) => {
1502
- if (!containerRef.current || !focusId)
1503
- return;
1504
- const tap = outsideTapRef.current;
1505
- outsideTapRef.current = null;
1506
- if (!tap || tap.pointerId !== e.pointerId)
1507
- return;
1508
- const dx = Math.abs(e.clientX - tap.x);
1509
- const dy = Math.abs(e.clientY - tap.y);
1510
- const moved = Math.hypot(dx, dy) > 10;
1511
- if (moved)
1512
- return;
1513
- const path = e.composedPath();
1514
- if (isInsideVirtual(path, containerRef.current))
1515
- return;
1516
- onBlur(true);
1517
- };
1518
- window.addEventListener("pointerdown", handlePointerDown2, { capture: true });
1519
- window.addEventListener("pointerup", handlePointerUp2, { capture: true });
1520
- window.addEventListener("pointercancel", handlePointerUp2, { capture: true });
1521
- return () => {
1522
- window.removeEventListener("pointerdown", handlePointerDown2, { capture: true });
1523
- window.removeEventListener("pointerup", handlePointerUp2, { capture: true });
1524
- window.removeEventListener("pointercancel", handlePointerUp2, { capture: true });
1525
- };
1526
- }, [focusId, onBlur]);
1527
- useEffect4(() => {
1528
- let handle;
1529
- const loop = () => {
1530
- draw();
1531
- handle = requestAnimationFrame(loop);
1532
- };
1533
- loop();
1534
- return () => cancelAnimationFrame(handle);
1535
- }, [draw]);
1536
- if (!focusId || !isMobileAgent())
1537
- return null;
1538
- return createPortal(/* @__PURE__ */ jsxDEV3(ShadowWrapper, {
1539
- tagName: "virtual-keypad-canvas",
1540
- hostRef: containerRef,
1541
- style: {
1542
- position: "fixed",
1543
- bottom: 0,
1544
- left: 0,
1545
- right: 0,
1546
- margin: "0 auto",
1547
- width: viewport.width,
1548
- height: Math.round(200 / viewport.scale),
1549
- backgroundColor: theme === "dark" ? "#0f172a" : "#e2e8f0",
1550
- borderRadius: `calc(18px / ${viewport.scale}) calc(18px / ${viewport.scale}) 0 0`,
1551
- boxShadow: `0 calc(-6px / ${viewport.scale}) calc(30px / ${viewport.scale}) rgba(15, 23, 42, 0.2)`,
1552
- zIndex: 9999,
1553
- overflow: "hidden",
1554
- userSelect: "none",
1555
- touchAction: "none",
1556
- "--scale-factor": viewport.scale,
1557
- "--keypad-bg": theme === "dark" ? "#0f172a" : "#e2e8f0"
1558
- },
1559
- onFocus: () => {
1560
- if (focusId)
1561
- onFocus(focusId);
1562
- },
1563
- onBlur,
1564
- onContextMenu: (e) => e.preventDefault(),
1565
- onPointerDown: (e) => e.preventDefault(),
1566
- onClickCapture: (e) => {
1567
- e.preventDefault();
1568
- e.stopPropagation();
1569
- },
1570
- css: `
1571
- :host {
1572
- display: block;
1573
- }
1574
- canvas {
1575
- display: block;
1576
- width: 100%;
1577
- height: 100%;
1578
- touch-action: none;
1579
- }
1580
- `,
1581
- children: /* @__PURE__ */ jsxDEV3("canvas", {
1582
- ref: canvasRef,
1583
- onPointerDown: handlePointerDown,
1584
- onPointerMove: handlePointerMove,
1585
- onPointerUp: handlePointerUp,
1586
- onPointerLeave: handlePointerUp,
1587
- onPointerCancel: handlePointerCancel,
1588
- style: { width: "100%", height: "100%", display: "block" }
1589
- }, undefined, false, undefined, this)
1590
- }, undefined, false, undefined, this), document.body);
1591
- }
1592
-
1593
- // src/hooks/useStorage.ts
1594
- import { useState as useState3, useCallback as useCallback5, useEffect as useEffect5 } from "react";
1595
- var isBrowser = typeof window !== "undefined";
1596
- function useStorage(key, initialValue) {
1597
- const [storedValue, setStoredValue] = useState3(() => {
1598
- if (!isBrowser) {
1599
- return initialValue instanceof Function ? initialValue() : initialValue;
1600
- }
1601
- try {
1602
- const item = window.localStorage.getItem(key);
1603
- if (item) {
1604
- return JSON.parse(item);
1605
- } else {
1606
- const valueToStore = initialValue instanceof Function ? initialValue() : initialValue;
1607
- window.localStorage.setItem(key, JSON.stringify(valueToStore));
1608
- return valueToStore;
1609
- }
1610
- } catch (error) {
1611
- console.error(`Error reading localStorage key "${key}":`, error);
1612
- return initialValue instanceof Function ? initialValue() : initialValue;
1613
- }
1614
- });
1615
- const setValue = useCallback5((value) => {
1616
- if (!isBrowser) {
1617
- console.warn(`Tried to set localStorage key "${key}" in a non-browser environment.`);
1618
- return;
1619
- }
1620
- try {
1621
- const valueToStore = value instanceof Function ? value(storedValue) : value;
1622
- setStoredValue(valueToStore);
1623
- window.localStorage.setItem(key, JSON.stringify(valueToStore));
1624
- } catch (error) {
1625
- console.error(`Error setting localStorage key "${key}":`, error);
1626
- }
1627
- }, [key, storedValue]);
1628
- useEffect5(() => {
1629
- if (!isBrowser)
1630
- return;
1631
- const handleStorageChange = (event) => {
1632
- if (event.storageArea !== window.localStorage || event.key !== key) {
1633
- return;
1634
- }
1635
- try {
1636
- if (event.newValue) {
1637
- if (JSON.stringify(storedValue) !== event.newValue) {
1638
- setStoredValue(JSON.parse(event.newValue));
1639
- }
1640
- }
1641
- } catch (error) {
1642
- console.error(`Error handling storage change for key "${key}":`, error);
1643
- }
1644
- };
1645
- window.addEventListener("storage", handleStorageChange);
1646
- return () => window.removeEventListener("storage", handleStorageChange);
1647
- }, [key, storedValue]);
1648
- return [storedValue, setValue];
1649
- }
1650
-
1651
- // src/assets/qwerty.json
1652
- var qwerty_default = [
1653
- [
1654
- { label: "q", value: "q", type: "char" },
1655
- { label: "w", value: "w", type: "char" },
1656
- { label: "e", value: "e", type: "char" },
1657
- { label: "r", value: "r", type: "char" },
1658
- { label: "t", value: "t", type: "char" },
1659
- { label: "y", value: "y", type: "char" },
1660
- { label: "u", value: "u", type: "char" },
1661
- { label: "i", value: "i", type: "char" },
1662
- { label: "o", value: "o", type: "char" },
1663
- { label: "p", value: "p", type: "char" }
1664
- ],
1665
- [
1666
- { label: "a", value: "a", type: "char" },
1667
- { label: "s", value: "s", type: "char" },
1668
- { label: "d", value: "d", type: "char" },
1669
- { label: "f", value: "f", type: "char" },
1670
- { label: "g", value: "g", type: "char" },
1671
- { label: "h", value: "h", type: "char" },
1672
- { label: "j", value: "j", type: "char" },
1673
- { label: "k", value: "k", type: "char" },
1674
- { label: "l", value: "l", type: "char" }
1675
- ],
1676
- [
1677
- { label: "⇧", value: "Shift", type: "action" },
1678
- { label: "z", value: "z", type: "char" },
1679
- { label: "x", value: "x", type: "char" },
1680
- { label: "c", value: "c", type: "char" },
1681
- { label: "v", value: "v", type: "char" },
1682
- { label: "b", value: "b", type: "char" },
1683
- { label: "n", value: "n", type: "char" },
1684
- { label: "m", value: "m", type: "char" },
1685
- { label: "⌫", value: "Backspace", type: "action" }
1686
- ],
1687
- [
1688
- { label: "␣", value: " ", width: 5, type: "action" },
1689
- { label: "⏎", value: `
1690
- `, type: "action" },
1691
- { label: "🌐", value: "HangulMode", type: "action" }
1692
- ]
1693
- ];
1694
-
1695
- // src/hooks/useVisualViewport.ts
1696
- import { useEffect as useEffect6, useState as useState4 } from "react";
1697
- var getVisualViewport = () => {
1698
- if (typeof window !== "undefined" && window.visualViewport) {
1699
- return {
1700
- width: window.visualViewport.width,
1701
- height: window.visualViewport.height,
1702
- scale: window.visualViewport.scale,
1703
- offsetLeft: window.visualViewport.offsetLeft,
1704
- offsetTop: window.visualViewport.offsetTop
1705
- };
1706
- }
1707
- return {
1708
- width: window.innerWidth,
1709
- height: window.innerHeight,
1710
- scale: 1,
1711
- offsetLeft: 0,
1712
- offsetTop: 0
1713
- };
1714
- };
1715
- var isSameViewport = (prev, next) => prev.width === next.width && prev.height === next.height && prev.scale === next.scale && prev.offsetLeft === next.offsetLeft && prev.offsetTop === next.offsetTop;
1716
- var useVisualViewport = () => {
1717
- const [viewport, setViewport] = useState4(getVisualViewport);
1718
- useEffect6(() => {
1719
- if (typeof window === "undefined")
1720
- return;
1721
- let rafId = null;
1722
- const applyViewportUpdate = () => {
1723
- const nextViewport = getVisualViewport();
1724
- setViewport((prev) => isSameViewport(prev, nextViewport) ? prev : nextViewport);
1725
- };
1726
- const handleResize = () => {
1727
- if (rafId !== null) {
1728
- cancelAnimationFrame(rafId);
1729
- }
1730
- rafId = requestAnimationFrame(applyViewportUpdate);
1731
- };
1732
- if (window.visualViewport) {
1733
- window.visualViewport.addEventListener("resize", handleResize, { passive: true });
1734
- window.visualViewport.addEventListener("scroll", handleResize, { passive: true });
1735
- } else {
1736
- window.addEventListener("resize", handleResize, { passive: true });
1737
- }
1738
- return () => {
1739
- if (rafId !== null) {
1740
- cancelAnimationFrame(rafId);
1741
- }
1742
- if (window.visualViewport) {
1743
- window.visualViewport.removeEventListener("resize", handleResize);
1744
- window.visualViewport.removeEventListener("scroll", handleResize);
1745
- } else {
1746
- window.removeEventListener("resize", handleResize);
1747
- }
1748
- };
1749
- }, []);
1750
- return viewport;
1751
- };
1752
-
1753
- // src/hooks/useSystemTheme.ts
1754
- import { useState as useState5, useEffect as useEffect7 } from "react";
1755
- function useSystemTheme() {
1756
- const [theme, setTheme] = useState5(() => {
1757
- if (typeof window !== "undefined" && window.matchMedia) {
1758
- return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
1759
- }
1760
- return "light";
1761
- });
1762
- useEffect7(() => {
1763
- if (typeof window === "undefined" || !window.matchMedia)
1764
- return;
1765
- const mq = window.matchMedia("(prefers-color-scheme: dark)");
1766
- const handler = (e) => {
1767
- setTheme(e.matches ? "dark" : "light");
1768
- };
1769
- mq.addEventListener("change", handler);
1770
- return () => mq.removeEventListener("change", handler);
1771
- }, []);
1772
- return theme;
1773
- }
1774
-
1775
- // src/components/Provider.tsx
1776
- import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
1777
- function VirtualInputProvider({
1778
- children,
1779
- layout = qwerty_default,
1780
- defaultHangulMode = true,
1781
- theme
1782
- }) {
1783
- const inputRef = useRef5(null);
1784
- const sti = useRef5(setTimeout(() => null, 0));
1785
- const isCompositionRef = useRef5(undefined);
1786
- const [focusId, setFocusId] = useState6();
1787
- const [shift, setShift] = useState6(false);
1788
- const [hangulMode, setHangulMode] = useStorage("virtual-keyboard-hangul-mode", defaultHangulMode);
1789
- const viewport = useVisualViewport();
1790
- const systemTheme = useSystemTheme();
1791
- const effectiveTheme = theme ?? systemTheme;
1792
- const focusedElementRef = useRef5(null);
1793
- useEffect8(() => {
1794
- if (focusId && focusedElementRef.current) {
1795
- const paddingBottom = Math.round(200 / viewport.scale);
1796
- document.body.style.paddingBottom = `${paddingBottom}px`;
1797
- setTimeout(() => {
1798
- const el = focusedElementRef.current;
1799
- if (el) {
1800
- const rect = el.getBoundingClientRect();
1801
- const scrollTop = window.scrollY || document.documentElement.scrollTop;
1802
- const elementTop = rect.top + scrollTop;
1803
- const availableHeight = viewport.height - paddingBottom;
1804
- const targetScroll = elementTop - availableHeight / 2 + rect.height / 2;
1805
- window.scrollTo({
1806
- top: targetScroll,
1807
- behavior: "smooth"
1808
- });
1809
- }
1810
- }, 100);
1811
- } else {
1812
- document.body.style.paddingBottom = "0px";
1813
- }
1814
- return () => {
1815
- document.body.style.paddingBottom = "0px";
1816
- };
1817
- }, [focusId, viewport.scale, viewport.height, viewport.offsetTop]);
1818
- const onFocus = (id, target) => {
1819
- clearTimeout(sti.current);
1820
- if (target)
1821
- focusedElementRef.current = target;
1822
- setFocusId(id);
1823
- };
1824
- const onBlur = useCallback6((e) => {
1825
- if (e === true) {
1826
- setFocusId(undefined);
1827
- isCompositionRef.current = false;
1828
- return;
1829
- }
1830
- if (e && typeof e === "object" && "relatedTarget" in e && e.relatedTarget) {
1831
- if (e.relatedTarget.getAttribute("data-virtual-input")) {
1832
- return;
1833
- }
1834
- sti.current = setTimeout(() => {
1835
- setFocusId(undefined);
1836
- isCompositionRef.current = false;
1837
- }, 0);
1838
- return;
1839
- }
1840
- }, [setFocusId, isCompositionRef]);
1841
- const toggleShift = useCallback6(() => {
1842
- setShift((prev) => !prev);
1843
- }, []);
1844
- const toggleKorean = useCallback6(() => {
1845
- setHangulMode((prev) => !prev);
1846
- }, [setHangulMode]);
1847
- return /* @__PURE__ */ jsxDEV4(VirtualInputContext.Provider, {
1848
- value: {
1849
- focusId,
1850
- hangulMode,
1851
- shift,
1852
- theme: effectiveTheme,
1853
- onFocus,
1854
- onBlur,
1855
- setHangulMode,
1856
- toggleShift,
1857
- toggleKorean,
1858
- isCompositionRef,
1859
- inputRef
1860
- },
1861
- children: [
1862
- children,
1863
- /* @__PURE__ */ jsxDEV4(VirtualKeypad, {
1864
- layout,
1865
- viewport
1866
- }, undefined, false, undefined, this)
1867
- ]
1868
- }, undefined, true, undefined, this);
1869
- }
1870
- export {
1871
- VirtualInputProvider,
1872
- VirtualInput
1873
- };
1
+ export * from "./components/Input";
2
+ export * from "./components/Provider";