index.mjs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. //#region ../../packages/hooks/use-cursor/index.ts
  2. function useCursor(input) {
  3. let selectionInfo;
  4. function recordCursor() {
  5. if (input.value == void 0) return;
  6. const { selectionStart, selectionEnd, value } = input.value;
  7. if (selectionStart == null || selectionEnd == null) return;
  8. selectionInfo = {
  9. selectionStart,
  10. selectionEnd,
  11. value,
  12. beforeTxt: value.slice(0, Math.max(0, selectionStart)),
  13. afterTxt: value.slice(Math.max(0, selectionEnd))
  14. };
  15. }
  16. function setCursor() {
  17. if (input.value == void 0 || selectionInfo == void 0) return;
  18. const { value } = input.value;
  19. const { beforeTxt, afterTxt, selectionStart } = selectionInfo;
  20. if (beforeTxt == void 0 || afterTxt == void 0 || selectionStart == void 0) return;
  21. let startPos = value.length;
  22. if (value.endsWith(afterTxt)) startPos = value.length - afterTxt.length;
  23. else if (value.startsWith(beforeTxt)) startPos = beforeTxt.length;
  24. else {
  25. const beforeLastChar = beforeTxt[selectionStart - 1];
  26. const newIndex = value.indexOf(beforeLastChar, selectionStart - 1);
  27. if (newIndex !== -1) startPos = newIndex + 1;
  28. }
  29. input.value.setSelectionRange(startPos, startPos);
  30. }
  31. return [recordCursor, setCursor];
  32. }
  33. //#endregion
  34. export { useCursor };
  35. //# sourceMappingURL=index.mjs.map