textWysiwyg.tsx 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { KEYS } from "../index";
  2. type TextWysiwygParams = {
  3. initText: string;
  4. x: number;
  5. y: number;
  6. strokeColor: string;
  7. font: string;
  8. onSubmit: (text: string) => void;
  9. };
  10. export function textWysiwyg({
  11. initText,
  12. x,
  13. y,
  14. strokeColor,
  15. font,
  16. onSubmit
  17. }: TextWysiwygParams) {
  18. const input = document.createElement("input");
  19. input.value = initText;
  20. Object.assign(input.style, {
  21. color: strokeColor,
  22. position: "absolute",
  23. top: y + "px",
  24. left: x + "px",
  25. transform: "translate(-50%, -50%)",
  26. boxShadow: "none",
  27. textAlign: "center",
  28. width: (window.innerWidth - x) * 2 + "px",
  29. font: font,
  30. border: "none",
  31. background: "transparent"
  32. });
  33. input.onkeydown = ev => {
  34. if (ev.key === KEYS.ESCAPE) {
  35. ev.preventDefault();
  36. if (initText) {
  37. input.value = initText;
  38. handleSubmit();
  39. return;
  40. }
  41. cleanup();
  42. return;
  43. }
  44. if (ev.key === KEYS.ENTER) {
  45. ev.preventDefault();
  46. handleSubmit();
  47. }
  48. };
  49. input.onblur = handleSubmit;
  50. function stopEvent(ev: Event) {
  51. ev.stopPropagation();
  52. }
  53. function handleSubmit() {
  54. if (input.value) {
  55. onSubmit(input.value);
  56. }
  57. cleanup();
  58. }
  59. function cleanup() {
  60. input.onblur = null;
  61. input.onkeydown = null;
  62. window.removeEventListener("wheel", stopEvent, true);
  63. document.body.removeChild(input);
  64. }
  65. window.addEventListener("wheel", stopEvent, true);
  66. document.body.appendChild(input);
  67. input.focus();
  68. input.select();
  69. }