prism-react-editor
Version:
Lightweight, extensible code editor component for React apps
41 lines (40 loc) • 1.61 kB
JavaScript
"use client";
import { useLayoutEffect } from "react";
import { k as createTemplate, a as addTextareaListener, l as getPosition, m as scrollToEl, u as updateNode, h as getLineBefore, f as getLineEnd } from "../local-Cq-4Fajb.js";
const cursorTemplate = /* @__PURE__ */ createTemplate(
"<div style=position:absolute;top:0;opacity:0;padding-right:inherit> <span><span></span> "
);
const useCursorPosition = (editor) => {
useLayoutEffect(() => {
const cursorContainer = cursorTemplate();
const [before, span] = cursorContainer.childNodes;
const [cursor, after] = span.childNodes;
const selectionChange = (selection) => {
const value = editor.value;
const activeLine = editor.lines[editor.activeLine];
const position = selection[selection[2] < "f" ? 0 : 1];
updateNode(before, getLineBefore(value, position));
updateNode(after, value.slice(position, getLineEnd(value, position)) + "\n");
if (cursorContainer.parentNode != activeLine) activeLine.prepend(cursorContainer);
};
const scrollIntoView = () => scrollToEl(editor, cursor);
const cleanup1 = editor.on("selectionChange", selectionChange);
const cleanup2 = addTextareaListener(editor, "input", (e) => {
if (/history/.test(e.inputType)) scrollIntoView();
});
editor.extensions.cursor = {
scrollIntoView,
getPosition: () => getPosition(editor, cursor)
};
return () => {
delete editor.extensions.cursor;
cleanup1();
cleanup2();
cursor.remove();
};
}, []);
};
export {
useCursorPosition
};
//# sourceMappingURL=cursor.js.map