index.js 1.4 KB

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