index.js 1.3 KB

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