@uiwwsw/virtual-keyboard 0.6.0 → 0.7.1

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
@@ -581,6 +581,14 @@ function VirtualInput({
581
581
  const caretIndexRef = useRef(caretIndex);
582
582
  const [selection, setSelection] = useState2({ start: null, end: null });
583
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);
584
592
  const charPositionsRef = useRef([]);
585
593
  const scrollXRef = useRef(0);
586
594
  useEffect2(() => {
@@ -664,10 +672,13 @@ function VirtualInput({
664
672
  const caretColor = (computedStyle.caretColor !== "auto" ? computedStyle.caretColor : color) || "black";
665
673
  const y = height / 2;
666
674
  const x = borderLeft + paddingLeft;
667
- if (!internalValue && placeholder) {
675
+ const text = internalValueRef.current;
676
+ const cIndex = caretIndexRef.current;
677
+ const isCursorVisible = showCursorRef.current;
678
+ if (!text && placeholder) {
668
679
  ctx.fillStyle = "#aaa";
669
680
  ctx.fillText(placeholder, x, y);
670
- if (isFocused && showCursor) {
681
+ if (isFocused && isCursorVisible) {
671
682
  ctx.beginPath();
672
683
  ctx.moveTo(x, y - fontSize / 2);
673
684
  ctx.lineTo(x, y + fontSize / 2);
@@ -678,16 +689,16 @@ function VirtualInput({
678
689
  return;
679
690
  }
680
691
  ctx.fillStyle = color;
681
- if (charPositionsRef.current.length !== internalValue.length + 1) {
692
+ if (charPositionsRef.current.length !== text.length + 1) {
682
693
  const positions = [x];
683
- for (let i = 0;i < internalValue.length; i++) {
684
- const w = ctx.measureText(internalValue.slice(0, i + 1)).width;
694
+ for (let i = 0;i < text.length; i++) {
695
+ const w = ctx.measureText(text.slice(0, i + 1)).width;
685
696
  positions.push(x + w);
686
697
  }
687
698
  charPositionsRef.current = positions;
688
699
  }
689
700
  const charX = charPositionsRef.current;
690
- const caretPos = charX[caretIndex] ?? x;
701
+ const caretPos = charX[cIndex] ?? x;
691
702
  const viewLeft = paddingLeft;
692
703
  const viewRight = width - paddingRight - borderLeft - borderRight;
693
704
  const safety = 2;
@@ -718,9 +729,9 @@ function VirtualInput({
718
729
  ctx.fillRect(startX, 0, endX - startX, height);
719
730
  ctx.fillStyle = color;
720
731
  }
721
- ctx.fillText(internalValue, x, y);
722
- if (isFocused && showCursor && !hasSelection) {
723
- const caretX = charX[caretIndex] ?? x;
732
+ ctx.fillText(text, x, y);
733
+ if (isFocused && isCursorVisible && !hasSelection) {
734
+ const caretX = charX[cIndex] ?? x;
724
735
  ctx.beginPath();
725
736
  ctx.moveTo(caretX, y - fontSize / 2);
726
737
  ctx.lineTo(caretX, y + fontSize / 2);
@@ -728,8 +739,33 @@ function VirtualInput({
728
739
  ctx.lineWidth = 1.5;
729
740
  ctx.stroke();
730
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
+ }
731
767
  ctx.restore();
732
- }, [internalValue, caretIndex, isFocused, showCursor, placeholder, hasSelection, selection]);
768
+ }, [isFocused, placeholder, hasSelection, selection, showCopyFeedback]);
733
769
  useEffect2(() => {
734
770
  let animationFrameId;
735
771
  const loop = () => {
@@ -776,20 +812,103 @@ function VirtualInput({
776
812
  let currentX = 0;
777
813
  for (let i = 0;i < internalValue.length; i++) {
778
814
  const w = ctx.measureText(internalValue[i]).width;
779
- if (x < currentX + w / 2) {
815
+ if (x < currentX + w / 2)
780
816
  return i;
781
- }
782
817
  currentX += w;
783
818
  }
784
819
  return internalValue.length;
785
820
  }, [internalValue]);
786
821
  const handleCanvasClick = useCallback((e) => {
822
+ if (showCopyFeedback)
823
+ return;
787
824
  const index = getCharIndexFromX(e.clientX);
788
825
  caretIndexRef.current = index;
789
826
  setCaretIndex(index);
790
827
  clearSelection();
791
828
  onFocus(id);
792
- }, [getCharIndexFromX, clearSelection, 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]);
793
912
  const handleKeyDown = useCallback((e) => {
794
913
  const currentVal = internalValueRef.current;
795
914
  const currentCaret = caretIndexRef.current;
@@ -797,6 +916,49 @@ function VirtualInput({
797
916
  setHangulMode(!hangulMode);
798
917
  return;
799
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
+ }
800
962
  if (e.shiftKey && (e.key === "ArrowLeft" || e.key === "ArrowRight")) {
801
963
  const newIndex = e.key === "ArrowLeft" ? Math.max(0, currentCaret - 1) : Math.min(currentVal.length, currentCaret + 1);
802
964
  setSelection((prev) => ({
@@ -896,7 +1058,16 @@ function VirtualInput({
896
1058
  onFocus: () => onFocus(id, containerRef.current),
897
1059
  onBlur: (e) => onBlur(e),
898
1060
  onKeyDown: handleKeyDown,
1061
+ onContextMenu: (e) => e.preventDefault(),
1062
+ onCopy: handleCopy,
1063
+ onCut: handleCut,
1064
+ onPaste: handlePaste,
899
1065
  onClick: handleCanvasClick,
1066
+ onPointerDown: handlePointerDown,
1067
+ onPointerMove: handlePointerMove,
1068
+ onPointerUp: handlePointerUp,
1069
+ onPointerLeave: handlePointerUp,
1070
+ onPointerCancel: handlePointerUp,
900
1071
  "data-virtual-input": "true",
901
1072
  css: `
902
1073
  :host {
@@ -1014,7 +1185,8 @@ function useKeypadInteraction({
1014
1185
  toggleKorean,
1015
1186
  shift,
1016
1187
  getTransformedValue,
1017
- keyBoundsRef
1188
+ keyBoundsRef,
1189
+ calculateLayout
1018
1190
  }) {
1019
1191
  const activePresses = useRef3(new Map);
1020
1192
  const repeatableKeys = useMemo2(() => new Set(["char", "Backspace", "Delete", "Space", "ArrowLeft", "ArrowRight"]), []);
@@ -1040,7 +1212,6 @@ function useKeypadInteraction({
1040
1212
  shiftKey: shift
1041
1213
  });
1042
1214
  inputRef.current?.handleKeyDown(event);
1043
- inputRef.current?.scrollIntoView();
1044
1215
  }, [getTransformedValue, inputRef, shift, toggleKorean, toggleShift]);
1045
1216
  const clearRepeat = useCallback3((press) => {
1046
1217
  if (!press?.repeatTimeout)
@@ -1069,7 +1240,9 @@ function useKeypadInteraction({
1069
1240
  const canvas = e.currentTarget;
1070
1241
  if (!canvas)
1071
1242
  return;
1072
- canvas.setPointerCapture(e.pointerId);
1243
+ if (!keyBoundsRef.current.length) {
1244
+ keyBoundsRef.current = calculateLayout();
1245
+ }
1073
1246
  activePresses.current.forEach((press) => {
1074
1247
  clearRepeat(press);
1075
1248
  });
@@ -1095,7 +1268,7 @@ function useKeypadInteraction({
1095
1268
  keyIndex: -1
1096
1269
  });
1097
1270
  }
1098
- }, [dispatchKeyEvent, startRepeat, keyBoundsRef]);
1271
+ }, [calculateLayout, clearRepeat, dispatchKeyEvent, startRepeat, keyBoundsRef]);
1099
1272
  const handlePointerMove = useCallback3((e) => {
1100
1273
  e.preventDefault();
1101
1274
  const press = activePresses.current.get(e.pointerId);
@@ -1204,9 +1377,23 @@ function VirtualKeypad({
1204
1377
  toggleKorean,
1205
1378
  shift,
1206
1379
  getTransformedValue,
1207
- keyBoundsRef
1380
+ keyBoundsRef,
1381
+ calculateLayout
1208
1382
  });
1209
- const drawKey = (ctx, key, isPressed, isActiveModifier, scale, currentTheme) => {
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) => {
1210
1397
  const r = 10 / scale;
1211
1398
  const { x, y, w, h } = key;
1212
1399
  const colors = currentTheme === "dark" ? {
@@ -1250,20 +1437,7 @@ function VirtualKeypad({
1250
1437
  ctx.font = `500 ${fontSize}px "${fontFamily}"`;
1251
1438
  ctx.fillStyle = textColor;
1252
1439
  ctx.fillText(key.label, x + w / 2, y + h / 2 + pressOffset);
1253
- };
1254
- const roundRect = (ctx, x, y, w, h, r) => {
1255
- if (w < 2 * r)
1256
- r = w / 2;
1257
- if (h < 2 * r)
1258
- r = h / 2;
1259
- ctx.beginPath();
1260
- ctx.moveTo(x + r, y);
1261
- ctx.arcTo(x + w, y, x + w, y + h, r);
1262
- ctx.arcTo(x + w, y + h, x, y + h, r);
1263
- ctx.arcTo(x, y + h, x, y, r);
1264
- ctx.arcTo(x, y, x + w, y, r);
1265
- ctx.closePath();
1266
- };
1440
+ }, [roundRect]);
1267
1441
  const draw = useCallback4(() => {
1268
1442
  const canvas = canvasRef.current;
1269
1443
  if (!canvas)
@@ -1303,28 +1477,51 @@ function VirtualKeypad({
1303
1477
  const isActiveModifier = key.value === "Shift" && shift || key.value === "HangulMode" && hangulMode;
1304
1478
  drawKey(ctx, key, isPressed, isActiveModifier, scale, theme);
1305
1479
  });
1306
- }, [calculateLayout, hangulMode, shift, viewport.scale, activePresses, keyBoundsRef, theme]);
1480
+ }, [calculateLayout, drawKey, hangulMode, shift, viewport.scale, activePresses, keyBoundsRef, theme]);
1307
1481
  useEffect4(() => {
1308
1482
  keyBoundsRef.current = [];
1309
1483
  }, [hangulMode, shift, keyBoundsRef]);
1484
+ const outsideTapRef = useRef4(null);
1310
1485
  useEffect4(() => {
1311
- const handleGlobalPointerDown = (e) => {
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) => {
1312
1492
  if (!containerRef.current || !focusId)
1313
1493
  return;
1314
1494
  const path = e.composedPath();
1315
- if (path.includes(containerRef.current)) {
1495
+ if (isInsideVirtual(path, containerRef.current)) {
1496
+ outsideTapRef.current = null;
1316
1497
  return;
1317
1498
  }
1318
- const isInput = path.some((node) => {
1319
- return node instanceof Element && node.getAttribute("data-virtual-input") === "true";
1320
- });
1321
- if (isInput)
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))
1322
1515
  return;
1323
1516
  onBlur(true);
1324
1517
  };
1325
- window.addEventListener("pointerdown", handleGlobalPointerDown, { capture: true });
1518
+ window.addEventListener("pointerdown", handlePointerDown2, { capture: true });
1519
+ window.addEventListener("pointerup", handlePointerUp2, { capture: true });
1520
+ window.addEventListener("pointercancel", handlePointerUp2, { capture: true });
1326
1521
  return () => {
1327
- window.removeEventListener("pointerdown", handleGlobalPointerDown, { capture: true });
1522
+ window.removeEventListener("pointerdown", handlePointerDown2, { capture: true });
1523
+ window.removeEventListener("pointerup", handlePointerUp2, { capture: true });
1524
+ window.removeEventListener("pointercancel", handlePointerUp2, { capture: true });
1328
1525
  };
1329
1526
  }, [focusId, onBlur]);
1330
1527
  useEffect4(() => {
@@ -13,13 +13,14 @@ type VirtualInputContextType = {
13
13
  toggleKorean: () => void;
14
14
  shift: boolean;
15
15
  };
16
- export declare function useKeypadInteraction({ inputRef, toggleShift, toggleKorean, shift, getTransformedValue, keyBoundsRef }: VirtualInputContextType & {
16
+ export declare function useKeypadInteraction({ inputRef, toggleShift, toggleKorean, shift, getTransformedValue, keyBoundsRef, calculateLayout, }: VirtualInputContextType & {
17
17
  getTransformedValue: (cell: {
18
18
  label?: string;
19
19
  value: string;
20
20
  type?: string;
21
21
  }) => string;
22
22
  keyBoundsRef: React.MutableRefObject<KeyBounds[]>;
23
+ calculateLayout: () => KeyBounds[];
23
24
  }): {
24
25
  activePresses: import("react").RefObject<Map<number, ActivePress>>;
25
26
  handlePointerDown: (e: React.PointerEvent<HTMLCanvasElement>) => void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uiwwsw/virtual-keyboard",
3
- "version": "0.6.0",
3
+ "version": "0.7.1",
4
4
  "type": "module",
5
5
  "types": "dist/types/index.d.ts",
6
6
  "main": "dist/index.js",