tldraw
Version:
A tiny little drawing editor.
83 lines (82 loc) • 2.88 kB
JavaScript
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { preventDefault, useEditor } from "@tldraw/editor";
import { useCallback, useEffect, useRef, useState } from "react";
import { useUiEvents } from "../../context/events.mjs";
import { useTranslation } from "../../hooks/useTranslation/useTranslation.mjs";
import { TldrawUiButton } from "../primitives/Button/TldrawUiButton.mjs";
import { TldrawUiButtonIcon } from "../primitives/Button/TldrawUiButtonIcon.mjs";
import { TldrawUiInput } from "../primitives/TldrawUiInput.mjs";
function AltTextEditor({ shapeId, onClose, source }) {
const editor = useEditor();
const [altText, setAltText] = useState(() => {
const shape = editor.getShape(shapeId);
if (!shape) return "";
if (!("altText" in shape.props)) throw Error("Shape does not have altText property");
return shape.props.altText || "";
});
const msg = useTranslation();
const ref = useRef(null);
const trackEvent = useUiEvents();
const isReadonly = editor.getIsReadonly();
const handleValueChange = (value) => setAltText(value);
const handleComplete = () => {
trackEvent("set-alt-text", { source });
const shape = editor.getShape(shapeId);
if (!shape) return;
editor.updateShapes([
{
id: shape.id,
type: shape.type,
props: { altText }
}
]);
onClose();
};
const handleConfirm = () => handleComplete();
const handleAltTextCancel = useCallback(() => onClose(), [onClose]);
useEffect(() => {
ref.current?.select();
function handleKeyDown(event) {
if (event.key === "Escape") {
event.stopPropagation();
handleAltTextCancel();
}
}
document.addEventListener("keydown", handleKeyDown, { capture: true });
return () => {
document.removeEventListener("keydown", handleKeyDown, { capture: true });
};
}, [handleAltTextCancel]);
return /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsx(
TldrawUiInput,
{
ref,
className: "tlui-media__toolbar-alt-text-input",
"data-testid": "media-toolbar.alt-text-input",
value: altText,
placeholder: msg("tool.media-alt-text-desc"),
"aria-label": msg("tool.media-alt-text-desc"),
onValueChange: handleValueChange,
onComplete: handleComplete,
onCancel: handleAltTextCancel,
disabled: isReadonly
}
),
!isReadonly && /* @__PURE__ */ jsx(
TldrawUiButton,
{
title: msg("tool.media-alt-text-confirm"),
"data-testid": "tool.media-alt-text-confirm",
type: "icon",
onPointerDown: preventDefault,
onClick: handleConfirm,
children: /* @__PURE__ */ jsx(TldrawUiButtonIcon, { small: true, icon: "check" })
}
)
] });
}
export {
AltTextEditor
};
//# sourceMappingURL=AltTextEditor.mjs.map