index.js 1.5 KB

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