util.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import { useStage } from "@/core/hook/use-global-vars";
  2. import { Text } from "konva/lib/shapes/Text";
  3. export const useGetPointerTextNdx = () => {
  4. const stage = useStage();
  5. return (shape: Text) => {
  6. let pointerPos = stage.value?.getNode().pointerPos;
  7. const str = shape.text();
  8. if (!pointerPos || str.length === 0) {
  9. return str.length;
  10. }
  11. const transform = shape.getAbsoluteTransform().copy().invert()
  12. const textPos = {x: 0, y: 0}
  13. const finalPos = transform.point({
  14. x: pointerPos.x - textPos.x,
  15. y: pointerPos.y - textPos.y,
  16. });
  17. const width = shape.width();
  18. const textHeight = shape.textHeight;
  19. const lineNdx = Math.floor(finalPos.y / textHeight);
  20. const textArr = shape.textArr;
  21. let ndx = str.length;
  22. if (lineNdx >= textArr.length || lineNdx < 0) return ndx;
  23. const line = textArr[lineNdx];
  24. const hanlfSize = shape.fontSize() / 2
  25. let i = 0;
  26. let x = 0;
  27. if (shape.align() === 'center') {
  28. x = (width - line.width) / 2;
  29. } else if (shape.align() === 'right') {
  30. x = width - line.width;
  31. }
  32. let after = false;
  33. for (; i < line.text.length; i++) {
  34. const size = shape.measureSize(line.text[i]);
  35. x += size.width;
  36. if (x > finalPos.x) {
  37. const diff = x - finalPos.x
  38. if (diff < hanlfSize && line.text.length >= i + 1) {
  39. after = true;
  40. }
  41. break;
  42. }
  43. }
  44. if (i === line.text.length) {
  45. ndx = line.text.length - 1;
  46. after = true;
  47. } else {
  48. ndx = i;
  49. }
  50. let strNdx = 0;
  51. let emptyCount = 0;
  52. for (let i = 0; i < lineNdx; i++) {
  53. const cStr = textArr[i].text;
  54. if (!cStr) {
  55. // emptyCount++;
  56. } else if (i !== lineNdx) {
  57. strNdx = strNdx + str.substring(strNdx).indexOf(cStr) + cStr.length;
  58. emptyCount = 0;
  59. } else {
  60. strNdx = strNdx + str.substring(strNdx).indexOf(cStr);
  61. emptyCount = 0;
  62. }
  63. if (i !== lineNdx) {
  64. if (textArr[i].lastInParagraph) {
  65. strNdx += 1;
  66. }
  67. }
  68. }
  69. const char = line.text[ndx];
  70. const yStr = str.substring(strNdx + emptyCount);
  71. i = ndx;
  72. for (; i < yStr.length; i++) {
  73. if (yStr[i] === char) {
  74. break;
  75. }
  76. }
  77. ndx = strNdx + emptyCount + i + (after ? 1 : 0);
  78. return ndx;
  79. };
  80. };