index.mjs 1.4 KB

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