index.mjs 1.3 KB

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