tldraw
Version:
A tiny little drawing editor.
495 lines (494 loc) • 16.8 kB
JavaScript
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import {
BaseBoxShapeUtil,
Ellipse2d,
FileHelpers,
HTMLContainer,
Image,
MediaHelpers,
Rectangle2d,
Vec,
WeakCache,
fetch,
imageShapeMigrations,
imageShapeProps,
lerp,
modulate,
resizeBox,
structuredClone,
toDomPrecision,
useEditor,
useUniqueSafeId,
useValue
} from "@tldraw/editor";
import classNames from "classnames";
import { memo, useEffect, useState } from "react";
import { BrokenAssetIcon } from "../shared/BrokenAssetIcon.mjs";
import { HyperlinkButton } from "../shared/HyperlinkButton.mjs";
import { getUncroppedSize } from "../shared/crop.mjs";
import { useImageOrVideoAsset } from "../shared/useImageOrVideoAsset.mjs";
import { usePrefersReducedMotion } from "../shared/usePrefersReducedMotion.mjs";
import { TRANSPARENT_IMAGE_MIMETYPES, getAlphaData, preloadAlphaData } from "./ImageAlphaCache.mjs";
import { ImageEllipse2d, ImageRectangle2d } from "./ImageAlphaGeometry.mjs";
async function getDataURIFromURL(url) {
const response = await fetch(url);
const blob = await response.blob();
return FileHelpers.blobToDataUrl(blob);
}
const imageSvgExportCache = new WeakCache();
class ImageShapeUtil extends BaseBoxShapeUtil {
static type = "image";
static props = imageShapeProps;
static migrations = imageShapeMigrations;
isAspectRatioLocked() {
return true;
}
canCrop() {
return true;
}
isExportBoundsContainer() {
return true;
}
getDefaultProps() {
return {
w: 100,
h: 100,
assetId: null,
playing: true,
url: "",
crop: null,
flipX: false,
flipY: false,
altText: ""
};
}
getGeometry(shape) {
const asset = shape.props.assetId ? this.editor.getAsset(shape.props.assetId) : null;
const mimeType = asset && "mimeType" in asset.props ? asset.props.mimeType : null;
const supportsTransparency = mimeType != null && TRANSPARENT_IMAGE_MIMETYPES.includes(mimeType);
const assetSrc = asset && "src" in asset.props ? asset.props.src : null;
if (shape.props.crop?.isCircle) {
if (supportsTransparency && assetSrc) {
const src = assetSrc;
return new ImageEllipse2d({
width: shape.props.w,
height: shape.props.h,
isFilled: true,
alphaDataGetter: () => getAlphaData(src),
crop: shape.props.crop,
flipX: shape.props.flipX,
flipY: shape.props.flipY
});
}
return new Ellipse2d({
width: shape.props.w,
height: shape.props.h,
isFilled: true
});
}
if (supportsTransparency && assetSrc) {
const src = assetSrc;
return new ImageRectangle2d({
width: shape.props.w,
height: shape.props.h,
isFilled: true,
alphaDataGetter: () => getAlphaData(src),
crop: shape.props.crop,
flipX: shape.props.flipX,
flipY: shape.props.flipY
});
}
return new Rectangle2d({
width: shape.props.w,
height: shape.props.h,
isFilled: true
});
}
getAriaDescriptor(shape) {
return shape.props.altText;
}
onResize(shape, info) {
let resized = resizeBox(shape, info);
const { flipX, flipY } = info.initialShape.props;
const { scaleX, scaleY, mode } = info;
resized = {
...resized,
props: {
...resized.props,
flipX: scaleX < 0 !== flipX,
flipY: scaleY < 0 !== flipY
}
};
if (!shape.props.crop) return resized;
const flipCropHorizontally = (
// We used the flip horizontally feature
(// We resized the shape past it's bounds, so it flipped
mode === "scale_shape" && scaleX === -1 || mode === "resize_bounds" && flipX !== resized.props.flipX)
);
const flipCropVertically = (
// We used the flip vertically feature
(// We resized the shape past it's bounds, so it flipped
mode === "scale_shape" && scaleY === -1 || mode === "resize_bounds" && flipY !== resized.props.flipY)
);
const { topLeft, bottomRight } = shape.props.crop;
resized.props.crop = {
topLeft: {
x: flipCropHorizontally ? 1 - bottomRight.x : topLeft.x,
y: flipCropVertically ? 1 - bottomRight.y : topLeft.y
},
bottomRight: {
x: flipCropHorizontally ? 1 - topLeft.x : bottomRight.x,
y: flipCropVertically ? 1 - topLeft.y : bottomRight.y
},
isCircle: shape.props.crop.isCircle
};
return resized;
}
component(shape) {
return /* @__PURE__ */ jsx(ImageShape, { shape });
}
indicator(shape) {
const isCropping = this.editor.getCroppingShapeId() === shape.id;
if (isCropping) return null;
if (shape.props.crop?.isCircle) {
return /* @__PURE__ */ jsx(
"ellipse",
{
cx: toDomPrecision(shape.props.w / 2),
cy: toDomPrecision(shape.props.h / 2),
rx: toDomPrecision(shape.props.w / 2),
ry: toDomPrecision(shape.props.h / 2)
}
);
}
return /* @__PURE__ */ jsx("rect", { width: toDomPrecision(shape.props.w), height: toDomPrecision(shape.props.h) });
}
useLegacyIndicator() {
return false;
}
getIndicatorPath(shape) {
if (this.editor.getCroppingShapeId() === shape.id) return void 0;
const path = new Path2D();
if (shape.props.crop?.isCircle) {
const cx = shape.props.w / 2;
const cy = shape.props.h / 2;
path.ellipse(cx, cy, cx, cy, 0, 0, Math.PI * 2);
} else {
path.rect(0, 0, shape.props.w, shape.props.h);
}
return path;
}
async toSvg(shape, ctx) {
const props = shape.props;
if (!props.assetId) return null;
const asset = this.editor.getAsset(props.assetId);
if (!asset) return null;
const { w } = getUncroppedSize(shape.props, props.crop);
const src = await imageSvgExportCache.get(asset, async () => {
let src2 = await ctx.resolveAssetUrl(asset.id, w);
if (!src2) return null;
if (src2.startsWith("blob:") || src2.startsWith("http") || src2.startsWith("/") || src2.startsWith("./")) {
src2 = (await getDataURIFromURL(src2)) || "";
}
if (getIsAnimated(this.editor, asset.id)) {
const { promise } = getFirstFrameOfAnimatedImage(src2);
src2 = await promise;
}
return src2;
});
if (!src) return null;
return /* @__PURE__ */ jsx(SvgImage, { shape, src });
}
onDoubleClickEdge(shape) {
const props = shape.props;
if (!props) return;
if (this.editor.getCroppingShapeId() !== shape.id) {
return;
}
const crop = structuredClone(props.crop) || {
topLeft: { x: 0, y: 0 },
bottomRight: { x: 1, y: 1 }
};
const { w, h } = getUncroppedSize(shape.props, crop);
const pointDelta = new Vec(crop.topLeft.x * w, crop.topLeft.y * h).rot(shape.rotation);
const partial = {
id: shape.id,
type: shape.type,
x: shape.x - pointDelta.x,
y: shape.y - pointDelta.y,
props: {
crop: {
topLeft: { x: 0, y: 0 },
bottomRight: { x: 1, y: 1 }
},
w,
h
}
};
this.editor.updateShapes([partial]);
}
getInterpolatedProps(startShape, endShape, t) {
function interpolateCrop(startShape2, endShape2) {
if (startShape2.props.crop === null && endShape2.props.crop === null) return null;
const startTL = startShape2.props.crop?.topLeft || { x: 0, y: 0 };
const startBR = startShape2.props.crop?.bottomRight || { x: 1, y: 1 };
const endTL = endShape2.props.crop?.topLeft || { x: 0, y: 0 };
const endBR = endShape2.props.crop?.bottomRight || { x: 1, y: 1 };
return {
topLeft: { x: lerp(startTL.x, endTL.x, t), y: lerp(startTL.y, endTL.y, t) },
bottomRight: { x: lerp(startBR.x, endBR.x, t), y: lerp(startBR.y, endBR.y, t) }
};
}
return {
...(t > 0.5 ? endShape.props : startShape.props),
w: lerp(startShape.props.w, endShape.props.w, t),
h: lerp(startShape.props.h, endShape.props.h, t),
crop: interpolateCrop(startShape, endShape)
};
}
}
const ImageShape = memo(function ImageShape2({ shape }) {
const editor = useEditor();
const { w } = getUncroppedSize(shape.props, shape.props.crop);
const { asset, url } = useImageOrVideoAsset({
shapeId: shape.id,
assetId: shape.props.assetId,
width: w
});
const prefersReducedMotion = usePrefersReducedMotion();
const [staticFrameSrc, setStaticFrameSrc] = useState("");
const [loadedUrl, setLoadedUrl] = useState(null);
const isAnimated = asset && getIsAnimated(editor, asset.id);
useEffect(() => {
if (url && isAnimated) {
const { promise, cancel } = getFirstFrameOfAnimatedImage(url);
promise.then((dataUrl) => {
setStaticFrameSrc(dataUrl);
setLoadedUrl(url);
});
return () => {
cancel();
};
}
return void 0;
}, [editor, isAnimated, prefersReducedMotion, url]);
const mimeType = asset && "mimeType" in asset.props ? asset.props.mimeType : null;
const supportsTransparency = mimeType != null && TRANSPARENT_IMAGE_MIMETYPES.includes(mimeType);
const assetSrc = asset && "src" in asset.props ? asset.props.src : null;
useEffect(() => {
if (url && supportsTransparency) {
preloadAlphaData(url, assetSrc ?? void 0);
}
}, [url, supportsTransparency, assetSrc]);
const showCropPreview = useValue(
"show crop preview",
() => shape.id === editor.getOnlySelectedShapeId() && editor.getCroppingShapeId() === shape.id && editor.isIn("select.crop"),
[editor, shape.id]
);
const reduceMotion = prefersReducedMotion && (asset?.props.mimeType?.includes("video") || isAnimated);
const containerStyle = getCroppedContainerStyle(shape);
const nextSrc = url === loadedUrl ? null : url;
const loadedSrc = reduceMotion ? staticFrameSrc : loadedUrl;
if (!url && !asset?.props.src) {
return /* @__PURE__ */ jsxs(
HTMLContainer,
{
id: shape.id,
style: {
overflow: "hidden",
width: shape.props.w,
height: shape.props.h,
color: "var(--tl-color-text-3)",
backgroundColor: "var(--tl-color-low)",
border: "1px solid var(--tl-color-low-border)"
},
children: [
/* @__PURE__ */ jsx(
"div",
{
className: classNames("tl-image-container", asset && "tl-image-container-loading"),
style: containerStyle,
children: asset ? null : /* @__PURE__ */ jsx(BrokenAssetIcon, {})
}
),
"url" in shape.props && shape.props.url && /* @__PURE__ */ jsx(HyperlinkButton, { url: shape.props.url })
]
}
);
}
const crossOrigin = isAnimated ? "anonymous" : void 0;
return /* @__PURE__ */ jsxs(Fragment, { children: [
showCropPreview && loadedSrc && /* @__PURE__ */ jsx("div", { style: containerStyle, children: /* @__PURE__ */ jsx(
"img",
{
className: "tl-image",
style: { ...getFlipStyle(shape), opacity: 0.1 },
crossOrigin,
src: loadedSrc,
referrerPolicy: "strict-origin-when-cross-origin",
draggable: false,
alt: ""
}
) }),
/* @__PURE__ */ jsxs(
HTMLContainer,
{
id: shape.id,
style: {
overflow: "hidden",
width: shape.props.w,
height: shape.props.h,
borderRadius: shape.props.crop?.isCircle ? "50%" : void 0
},
children: [
/* @__PURE__ */ jsxs("div", { className: classNames("tl-image-container"), style: containerStyle, children: [
loadedSrc && /* @__PURE__ */ jsx(
"img",
{
className: "tl-image",
style: getFlipStyle(shape),
crossOrigin,
src: loadedSrc,
referrerPolicy: "strict-origin-when-cross-origin",
draggable: false,
alt: shape.props.altText
},
loadedSrc
),
nextSrc && /* @__PURE__ */ jsx(
"img",
{
className: "tl-image",
style: getFlipStyle(shape),
crossOrigin,
src: nextSrc,
referrerPolicy: "strict-origin-when-cross-origin",
draggable: false,
alt: shape.props.altText,
onLoad: () => setLoadedUrl(nextSrc)
},
nextSrc
)
] }),
shape.props.url && /* @__PURE__ */ jsx(HyperlinkButton, { url: shape.props.url })
]
}
)
] });
});
function getIsAnimated(editor, assetId) {
const asset = assetId ? editor.getAsset(assetId) : void 0;
if (!asset) return false;
return "mimeType" in asset.props && MediaHelpers.isAnimatedImageType(asset?.props.mimeType) || "isAnimated" in asset.props && asset.props.isAnimated;
}
function getCroppedContainerStyle(shape) {
const crop = shape.props.crop;
const topLeft = crop?.topLeft;
if (!topLeft) {
return {
width: shape.props.w,
height: shape.props.h
};
}
const { w, h } = getUncroppedSize(shape.props, crop);
const offsetX = -topLeft.x * w;
const offsetY = -topLeft.y * h;
return {
transform: `translate(${offsetX}px, ${offsetY}px)`,
width: w,
height: h
};
}
function getFlipStyle(shape, size) {
const { flipX, flipY, crop } = shape.props;
if (!flipX && !flipY) return void 0;
let cropOffsetX;
let cropOffsetY;
if (crop) {
const { w, h } = getUncroppedSize(shape.props, crop);
const cropWidth = crop.bottomRight.x - crop.topLeft.x;
const cropHeight = crop.bottomRight.y - crop.topLeft.y;
cropOffsetX = modulate(crop.topLeft.x, [0, 1 - cropWidth], [0, w - shape.props.w]);
cropOffsetY = modulate(crop.topLeft.y, [0, 1 - cropHeight], [0, h - shape.props.h]);
}
const scale = `scale(${flipX ? -1 : 1}, ${flipY ? -1 : 1})`;
const translate = size ? `translate(${(flipX ? size.width : 0) - (cropOffsetX ? cropOffsetX : 0)}px,
${(flipY ? size.height : 0) - (cropOffsetY ? cropOffsetY : 0)}px)` : "";
return {
transform: `${translate} ${scale}`,
// in SVG, flipping around the center doesn't work so we use explicit width/height
transformOrigin: size ? "0 0" : "center center"
};
}
function SvgImage({ shape, src }) {
const cropClipId = useUniqueSafeId();
const containerStyle = getCroppedContainerStyle(shape);
const crop = shape.props.crop;
if (containerStyle.transform && crop) {
const { transform: cropTransform, width, height } = containerStyle;
const croppedWidth = (crop.bottomRight.x - crop.topLeft.x) * width;
const croppedHeight = (crop.bottomRight.y - crop.topLeft.y) * height;
const points = [
new Vec(0, 0),
new Vec(croppedWidth, 0),
new Vec(croppedWidth, croppedHeight),
new Vec(0, croppedHeight)
];
const flip = getFlipStyle(shape, { width, height });
return /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsx("defs", { children: /* @__PURE__ */ jsx("clipPath", { id: cropClipId, children: crop.isCircle ? /* @__PURE__ */ jsx(
"ellipse",
{
cx: croppedWidth / 2,
cy: croppedHeight / 2,
rx: croppedWidth / 2,
ry: croppedHeight / 2
}
) : /* @__PURE__ */ jsx("polygon", { points: points.map((p) => `${p.x},${p.y}`).join(" ") }) }) }),
/* @__PURE__ */ jsx("g", { clipPath: `url(#${cropClipId})`, children: /* @__PURE__ */ jsx(
"image",
{
href: src,
width,
height,
"aria-label": shape.props.altText,
style: flip ? { ...flip } : { transform: cropTransform }
}
) })
] });
} else {
return /* @__PURE__ */ jsx(
"image",
{
href: src,
width: shape.props.w,
height: shape.props.h,
"aria-label": shape.props.altText,
style: getFlipStyle(shape, { width: shape.props.w, height: shape.props.h })
}
);
}
}
function getFirstFrameOfAnimatedImage(url) {
let cancelled = false;
const promise = new Promise((resolve) => {
const image = Image();
image.onload = () => {
if (cancelled) return;
const canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
const ctx = canvas.getContext("2d");
if (!ctx) return;
ctx.drawImage(image, 0, 0);
resolve(canvas.toDataURL());
};
image.crossOrigin = "anonymous";
image.src = url;
});
return { promise, cancel: () => cancelled = true };
}
export {
ImageShapeUtil
};
//# sourceMappingURL=ImageShapeUtil.mjs.map