UNPKG

tldraw

Version:

A tiny little drawing editor.

357 lines (356 loc) • 12.3 kB
import { Fragment, jsx, jsxs } from "react/jsx-runtime"; import { BaseBoxShapeUtil, FileHelpers, HTMLContainer, Image, MediaHelpers, Vec, fetch, imageShapeMigrations, imageShapeProps, lerp, 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 { useImageOrVideoAsset } from "../shared/useImageOrVideoAsset.mjs"; import { usePrefersReducedMotion } from "../shared/usePrefersReducedMotion.mjs"; async function getDataURIFromURL(url) { const response = await fetch(url); const blob = await response.blob(); return FileHelpers.blobToDataUrl(blob); } class ImageShapeUtil extends BaseBoxShapeUtil { static type = "image"; static props = imageShapeProps; static migrations = imageShapeMigrations; isAspectRatioLocked() { return true; } canCrop() { return true; } getDefaultProps() { return { w: 100, h: 100, assetId: null, playing: true, url: "", crop: null, flipX: false, flipY: false }; } 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 } }; return resized; } component(shape) { return /* @__PURE__ */ jsx(ImageShape, { shape }); } indicator(shape) { const isCropping = this.editor.getCroppingShapeId() === shape.id; if (isCropping) return null; return /* @__PURE__ */ jsx("rect", { width: toDomPrecision(shape.props.w), height: toDomPrecision(shape.props.h) }); } async toSvg(shape) { if (!shape.props.assetId) return null; const asset = this.editor.getAsset(shape.props.assetId); if (!asset) return null; let src = await this.editor.resolveAssetUrl(shape.props.assetId, { shouldResolveToOriginal: true }); if (!src) return null; if (src.startsWith("blob:") || src.startsWith("http") || src.startsWith("/") || src.startsWith("./")) { src = (await getDataURIFromURL(src)) || ""; } 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 = 1 / (crop.bottomRight.x - crop.topLeft.x) * shape.props.w; const h = 1 / (crop.bottomRight.y - crop.topLeft.y) * shape.props.h; 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 { asset, url } = useImageOrVideoAsset({ shapeId: shape.id, assetId: shape.props.assetId }); const prefersReducedMotion = usePrefersReducedMotion(); const [staticFrameSrc, setStaticFrameSrc] = useState(""); const [loadedUrl, setLoadedUrl] = useState(null); const isAnimated = getIsAnimated(editor, shape); useEffect(() => { if (url && isAnimated) { let cancelled = false; 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); setStaticFrameSrc(canvas.toDataURL()); setLoadedUrl(url); }; image.crossOrigin = "anonymous"; image.src = url; return () => { cancelled = true; }; } }, [editor, isAnimated, prefersReducedMotion, url]); 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(--color-text-3)", backgroundColor: "var(--color-low)", border: "1px solid var(--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 } ) }), /* @__PURE__ */ jsxs( HTMLContainer, { id: shape.id, style: { overflow: "hidden", width: shape.props.w, height: shape.props.h }, 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 }, loadedSrc ), nextSrc && /* @__PURE__ */ jsx( "img", { className: "tl-image", style: getFlipStyle(shape), crossOrigin, src: nextSrc, referrerPolicy: "strict-origin-when-cross-origin", draggable: false, onLoad: () => setLoadedUrl(nextSrc) }, nextSrc ) ] }), shape.props.url && /* @__PURE__ */ jsx(HyperlinkButton, { url: shape.props.url }) ] } ) ] }); }); function getIsAnimated(editor, shape) { const asset = shape.props.assetId ? editor.getAsset(shape.props.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 = 1 / (crop.bottomRight.x - crop.topLeft.x) * shape.props.w; const h = 1 / (crop.bottomRight.y - crop.topLeft.y) * shape.props.h; 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 } = shape.props; if (!flipX && !flipY) return void 0; const scale = `scale(${flipX ? -1 : 1}, ${flipY ? -1 : 1})`; const translate = size ? `translate(${flipX ? size.width : 0}px, ${flipY ? size.height : 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: /* @__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, style: flip ? { ...flip, transform: `${cropTransform} ${flip.transform}` } : { transform: cropTransform } } ) }) ] }); } else { return /* @__PURE__ */ jsx( "image", { href: src, width: shape.props.w, height: shape.props.h, style: getFlipStyle(shape, { width: shape.props.w, height: shape.props.h }) } ); } } export { ImageShapeUtil }; //# sourceMappingURL=ImageShapeUtil.mjs.map