mirror of
https://github.com/excalidraw/excalidraw.git
synced 2026-12-05 18:55:28 +03:00
feat(editor): offer the display's pixel scale and show output size in image export (#12852)
* feat(editor): offer the display's pixel scale and show output size in image export - add the display's pixel ratio (e.g. 1.5×) as an export scale, sorted among 1×/2×/3×, and default to it - mark it with a monitor icon and a "your display" caption with an explanatory tooltip - show the exported image's pixel dimensions under the preview - Tooltip: delay can be a number of ms (export dialog uses 150 ms) * fix(editor): default export scale from the editor's window, measure export size once - default exportScale follows the editor's own window (pop-out on another display), not the global one - dialog measures the export content once and only multiplies on scale change (getExportContentSize + getExportSize) * perf(editor): don't re-render the export preview on scale, embed or name changes The preview always renders at scale 1 without an embedded scene or name, so those settings only re-ran a full-scene export.
This commit is contained in:
1 parent
6515c7d22a
commit
4372494df0
12 files changed
+616
-62
No files matched your search
@@ -100,7 +100,7 @@ export const actionClearCanvas = register({
|
||||
newElementWith(element, { isDeleted: true }),
|
||||
),
|
||||
appState: {
|
||||
...getDefaultAppState(),
|
||||
...getDefaultAppState(app.ownerWindow),
|
||||
files: {},
|
||||
theme: appState.theme,
|
||||
penMode: appState.penMode,
|
||||
|
||||
@@ -24,20 +24,66 @@ import type {
|
||||
ToolType,
|
||||
} from "./types";
|
||||
|
||||
const MIN_DYNAMIC_EXPORT_SCALE = EXPORT_SCALES[0];
|
||||
const MAX_DYNAMIC_EXPORT_SCALE = EXPORT_SCALES[EXPORT_SCALES.length - 1];
|
||||
|
||||
/**
|
||||
* Returns the window's device pixel ratio normalized to 2 decimal places when
|
||||
* it falls within the supported export scale range (`[1, 3]`), else `null`.
|
||||
*/
|
||||
export const getDeviceExportScale = (
|
||||
ownerWindow?: Window | null,
|
||||
): number | null => {
|
||||
const win =
|
||||
ownerWindow ?? (typeof window !== "undefined" ? window : undefined);
|
||||
const rawDpr = win?.devicePixelRatio;
|
||||
if (!rawDpr || !Number.isFinite(rawDpr)) {
|
||||
return null;
|
||||
}
|
||||
const dpr = Math.round(rawDpr * 100) / 100;
|
||||
if (dpr < MIN_DYNAMIC_EXPORT_SCALE || dpr > MAX_DYNAMIC_EXPORT_SCALE) {
|
||||
return null;
|
||||
}
|
||||
return dpr;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns sorted export scale choices, inserting the user's dPR scale (and any
|
||||
* persisted non-default scale) where it fits among the default picks.
|
||||
*/
|
||||
export const getExportScales = (
|
||||
deviceExportScale: number | null,
|
||||
currentScale?: number,
|
||||
): number[] => {
|
||||
const scales = new Set<number>(EXPORT_SCALES);
|
||||
if (deviceExportScale != null) {
|
||||
scales.add(deviceExportScale);
|
||||
}
|
||||
if (
|
||||
currentScale != null &&
|
||||
Number.isFinite(currentScale) &&
|
||||
currentScale > 0
|
||||
) {
|
||||
scales.add(currentScale);
|
||||
}
|
||||
return Array.from(scales).sort((a, b) => a - b);
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolved lazily rather than at module scope: this module is pulled in by the
|
||||
* export pipeline, which must be importable outside a browser realm.
|
||||
*/
|
||||
const getDefaultExportScale = () => {
|
||||
const devicePixelRatio =
|
||||
typeof window === "undefined" ? 1 : window.devicePixelRatio || 1;
|
||||
return EXPORT_SCALES.includes(devicePixelRatio) ? devicePixelRatio : 1;
|
||||
export const getDefaultExportScale = (ownerWindow?: Window | null) => {
|
||||
return getDeviceExportScale(ownerWindow) ?? 1;
|
||||
};
|
||||
|
||||
export const getDefaultAppState = (): Omit<
|
||||
AppState,
|
||||
"offsetTop" | "offsetLeft" | "width" | "height"
|
||||
> => {
|
||||
/**
|
||||
* @param ownerWindow the editor's window (defaults to the global one), which
|
||||
* the default export scale follows
|
||||
*/
|
||||
export const getDefaultAppState = (
|
||||
ownerWindow?: Window | null,
|
||||
): Omit<AppState, "offsetTop" | "offsetLeft" | "width" | "height"> => {
|
||||
return {
|
||||
showWelcomeScreen: false,
|
||||
theme: THEME.LIGHT,
|
||||
@@ -80,7 +126,7 @@ export const getDefaultAppState = (): Omit<
|
||||
penDetected: false,
|
||||
errorMessage: null,
|
||||
exportBackground: true,
|
||||
exportScale: getDefaultExportScale(),
|
||||
exportScale: getDefaultExportScale(ownerWindow),
|
||||
exportEmbedScene: false,
|
||||
exportWithDarkMode: false,
|
||||
fileHandle: null,
|
||||
|
||||
@@ -302,7 +302,11 @@ import { ActionManager } from "../actions/manager";
|
||||
import { actions } from "../actions/register";
|
||||
import { getShortcutFromShortcutName } from "../actions/shortcuts";
|
||||
import { trackEvent } from "../analytics";
|
||||
import { getDefaultAppState, isEraserActive } from "../appState";
|
||||
import {
|
||||
getDefaultAppState,
|
||||
getDefaultExportScale,
|
||||
isEraserActive,
|
||||
} from "../appState";
|
||||
import {
|
||||
copyTextToSystemClipboard,
|
||||
parseDataTransferEvent,
|
||||
@@ -780,7 +784,7 @@ class App extends React.Component<AppProps, AppState> {
|
||||
|
||||
constructor(props: AppProps) {
|
||||
super(props);
|
||||
const defaultAppState = getDefaultAppState();
|
||||
const defaultAppState = getDefaultAppState(this.ownerWindow);
|
||||
const {
|
||||
viewModeEnabled = false,
|
||||
zenModeEnabled = false,
|
||||
@@ -3523,7 +3527,7 @@ class App extends React.Component<AppProps, AppState> {
|
||||
this.elementRenderOffsets = new Map();
|
||||
this.scene.replaceAllElements([]);
|
||||
this.setState((state) => ({
|
||||
...getDefaultAppState(),
|
||||
...getDefaultAppState(this.ownerWindow),
|
||||
isLoading: opts?.resetLoadingState ? false : state.isLoading,
|
||||
theme: this.state.theme,
|
||||
}));
|
||||
@@ -3590,6 +3594,11 @@ class App extends React.Component<AppProps, AppState> {
|
||||
deleteInvisibleElements: true,
|
||||
});
|
||||
let restoredAppState = restoreAppState(initialData?.appState, null);
|
||||
if (initialData?.appState?.exportScale == null) {
|
||||
// the default follows the editor's window (e.g. a pop-out on another
|
||||
// display), which `restoreAppState` doesn't know about
|
||||
restoredAppState.exportScale = getDefaultExportScale(this.ownerWindow);
|
||||
}
|
||||
const activeTool = restoredAppState.activeTool;
|
||||
|
||||
if (!restoredAppState.preferredSelectionTool.initialized) {
|
||||
|
||||
@@ -2,9 +2,61 @@
|
||||
|
||||
.excalidraw {
|
||||
--ImageExportModal-preview-border: #d6d6d6;
|
||||
--ImageExportModal-dimensions-color: var(--color-gray-70);
|
||||
|
||||
.ImageExportModal__scale {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
|
||||
&__display {
|
||||
gap: 3px;
|
||||
|
||||
& svg {
|
||||
width: 13px;
|
||||
height: 13px;
|
||||
flex: none;
|
||||
}
|
||||
}
|
||||
|
||||
// absolutely positioned so the caption doesn't change the row height
|
||||
// (and the picker stays aligned with the setting's label)
|
||||
&__caption {
|
||||
position: absolute;
|
||||
top: calc(100% + 3px);
|
||||
right: 4px;
|
||||
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 3px;
|
||||
|
||||
font-family: "Assistant";
|
||||
font-size: 0.75rem;
|
||||
line-height: 1;
|
||||
white-space: nowrap;
|
||||
color: var(--ImageExportModal-dimensions-color);
|
||||
cursor: help;
|
||||
|
||||
& svg {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
}
|
||||
|
||||
@include isMobile {
|
||||
right: unset;
|
||||
left: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
@include isMobile {
|
||||
align-items: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
&.theme--dark {
|
||||
--ImageExportModal-preview-border: #5c5c5c;
|
||||
--ImageExportModal-dimensions-color: var(--color-gray-30);
|
||||
}
|
||||
|
||||
.ImageExportModal {
|
||||
@@ -67,6 +119,7 @@
|
||||
}
|
||||
|
||||
&__canvas {
|
||||
position: relative;
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
@@ -82,16 +135,28 @@
|
||||
border-radius: 12px;
|
||||
|
||||
overflow: hidden;
|
||||
padding: 1rem;
|
||||
padding: 1rem 1rem 2.25rem;
|
||||
|
||||
& > canvas {
|
||||
max-width: calc(100% - 2rem);
|
||||
max-height: calc(100% - 2rem);
|
||||
&__content {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
|
||||
filter: none !important;
|
||||
&[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@include isMobile {
|
||||
max-height: 100%;
|
||||
& > canvas {
|
||||
max-width: calc(100% - 2rem);
|
||||
max-height: calc(100% - 1rem);
|
||||
|
||||
filter: none !important;
|
||||
|
||||
@include isMobile {
|
||||
max-height: 100%;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,6 +165,27 @@
|
||||
max-width: unset;
|
||||
}
|
||||
}
|
||||
|
||||
&__dimensions {
|
||||
position: absolute;
|
||||
bottom: 0.5rem;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
|
||||
padding: 2px 8px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--ImageExportModal-preview-border);
|
||||
background: var(--island-bg-color);
|
||||
|
||||
font-family: "Assistant";
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.3;
|
||||
color: var(--ImageExportModal-dimensions-color);
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
|
||||
&__settings {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import React, { useEffect, useRef, useState } from "react";
|
||||
import React, { useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import {
|
||||
DEFAULT_EXPORT_PADDING,
|
||||
EXPORT_IMAGE_TYPES,
|
||||
THEME,
|
||||
isFirefox,
|
||||
EXPORT_SCALES,
|
||||
cloneJSON,
|
||||
} from "@excalidraw/common";
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
actionChangeExportScale,
|
||||
actionChangeProjectName,
|
||||
} from "../actions/actionExport";
|
||||
import { getDeviceExportScale, getExportScales } from "../appState";
|
||||
import { probablySupportsClipboardBlob } from "../clipboard";
|
||||
import { prepareElementsForExport } from "../data";
|
||||
import { canvasToBlob } from "../data/blob";
|
||||
@@ -25,9 +26,15 @@ import { useCopyStatus } from "../hooks/useCopiedIndicator";
|
||||
|
||||
import { t } from "../i18n";
|
||||
import { isSomeElementSelected } from "../scene";
|
||||
import { exportScene, getExportConfigFromAppState } from "../scene/export";
|
||||
import {
|
||||
exportScene,
|
||||
getExportConfigFromAppState,
|
||||
getExportContentSize,
|
||||
getExportSize,
|
||||
} from "../scene/export";
|
||||
|
||||
import { copyIcon, downloadIcon, helpIcon } from "./icons";
|
||||
import { useApp } from "./App.context";
|
||||
import { copyIcon, DeviceDesktopIcon, downloadIcon, helpIcon } from "./icons";
|
||||
import { Dialog } from "./Dialog";
|
||||
import { RadioGroup } from "./RadioGroup";
|
||||
import { Switch } from "./Switch";
|
||||
@@ -41,6 +48,30 @@ import type { ActionManager } from "../actions/manager";
|
||||
import type { FontResolvers } from "../fonts";
|
||||
import type { AppClassProperties, BinaryFiles, UIAppState } from "../types";
|
||||
|
||||
/** ms before the dialog's tooltips show */
|
||||
const EXPORT_DIALOG_TOOLTIP_DELAY = 200;
|
||||
|
||||
const useDeviceExportScale = (ownerWindow: Window | null | undefined) => {
|
||||
const [rawDpr, setRawDpr] = useState(() => ownerWindow?.devicePixelRatio);
|
||||
|
||||
useEffect(() => {
|
||||
const update = () => setRawDpr(ownerWindow?.devicePixelRatio);
|
||||
update();
|
||||
if (!ownerWindow?.matchMedia) {
|
||||
return;
|
||||
}
|
||||
const mq = ownerWindow.matchMedia(
|
||||
`(resolution: ${ownerWindow.devicePixelRatio}dppx)`,
|
||||
);
|
||||
mq.addEventListener?.("change", update);
|
||||
return () => {
|
||||
mq.removeEventListener?.("change", update);
|
||||
};
|
||||
}, [ownerWindow, rawDpr]);
|
||||
|
||||
return getDeviceExportScale(ownerWindow);
|
||||
};
|
||||
|
||||
export const ErrorCanvasPreview = () => {
|
||||
return (
|
||||
<div>
|
||||
@@ -79,6 +110,9 @@ const ImageExportModal = ({
|
||||
appStateSnapshot,
|
||||
);
|
||||
|
||||
const app = useApp();
|
||||
const deviceExportScale = useDeviceExportScale(app?.ownerWindow);
|
||||
|
||||
const [projectName, setProjectName] = useState(name);
|
||||
const [exportSelectionOnly, setExportSelectionOnly] = useState(hasSelection);
|
||||
const [exportWithBackground, setExportWithBackground] = useState(
|
||||
@@ -89,6 +123,7 @@ const ImageExportModal = ({
|
||||
);
|
||||
const [exportScale, setExportScale] = useState(appStateSnapshot.exportScale);
|
||||
|
||||
const previewContainerRef = useRef<HTMLDivElement>(null);
|
||||
const previewRef = useRef<HTMLDivElement>(null);
|
||||
const previewRenderRequestIdRef = useRef(0);
|
||||
const [renderError, setRenderError] = useState<Error | null>(null);
|
||||
@@ -108,19 +143,54 @@ const ImageExportModal = ({
|
||||
resetCopyStatus,
|
||||
]);
|
||||
|
||||
const { exportedElements, exportingFrame } = prepareElementsForExport(
|
||||
elementsSnapshot,
|
||||
appStateSnapshot,
|
||||
exportSelectionOnly,
|
||||
const { exportedElements, exportingFrame } = useMemo(
|
||||
() =>
|
||||
prepareElementsForExport(
|
||||
elementsSnapshot,
|
||||
appStateSnapshot,
|
||||
exportSelectionOnly,
|
||||
),
|
||||
[elementsSnapshot, appStateSnapshot, exportSelectionOnly],
|
||||
);
|
||||
|
||||
// measured once per content change; scale changes only multiply
|
||||
const exportContentSize = useMemo(() => {
|
||||
if (exportedElements.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return getExportContentSize({
|
||||
elements: exportedElements,
|
||||
exportingFrame,
|
||||
padding: DEFAULT_EXPORT_PADDING,
|
||||
frames: appStateSnapshot.frameRendering.enabled
|
||||
? appStateSnapshot.frameRendering
|
||||
: { name: false, outline: false, clip: false },
|
||||
theme: exportWithDarkMode ? THEME.DARK : THEME.LIGHT,
|
||||
renderEnvironment: app?.renderEnvironment,
|
||||
});
|
||||
}, [
|
||||
exportedElements,
|
||||
exportingFrame,
|
||||
appStateSnapshot.frameRendering,
|
||||
exportWithDarkMode,
|
||||
app?.renderEnvironment,
|
||||
]);
|
||||
const exportDimensions =
|
||||
exportContentSize && getExportSize(exportContentSize, exportScale);
|
||||
|
||||
const exportScaleChoices = useMemo(
|
||||
() => getExportScales(deviceExportScale, exportScale),
|
||||
[deviceExportScale, exportScale],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const previewContainer = previewContainerRef.current;
|
||||
const previewNode = previewRef.current;
|
||||
if (!previewNode) {
|
||||
if (!previewContainer || !previewNode) {
|
||||
return;
|
||||
}
|
||||
const maxWidth = previewNode.offsetWidth;
|
||||
const maxHeight = previewNode.offsetHeight;
|
||||
const maxWidth = previewContainer.offsetWidth;
|
||||
const maxHeight = previewContainer.offsetHeight;
|
||||
if (!maxWidth) {
|
||||
return;
|
||||
}
|
||||
@@ -149,6 +219,7 @@ const ImageExportModal = ({
|
||||
maxWidthOrHeight: Math.max(maxWidth, maxHeight),
|
||||
exportingFrame,
|
||||
fontResolvers,
|
||||
environment: app?.renderEnvironment,
|
||||
},
|
||||
})
|
||||
.then(async (canvas) => {
|
||||
@@ -180,31 +251,48 @@ const ImageExportModal = ({
|
||||
}
|
||||
|
||||
console.error(error);
|
||||
previewNode.replaceChildren();
|
||||
setRenderError(error);
|
||||
});
|
||||
|
||||
return () => {
|
||||
previewRenderRequestIdRef.current += 1;
|
||||
};
|
||||
// only what the preview renders: it is always at scale 1 (fit to the
|
||||
// container) with no embedded scene, so scale/embed changes don't redraw it
|
||||
}, [
|
||||
appStateSnapshot,
|
||||
files,
|
||||
exportedElements,
|
||||
exportingFrame,
|
||||
projectName,
|
||||
exportWithBackground,
|
||||
exportWithDarkMode,
|
||||
exportScale,
|
||||
embedScene,
|
||||
fontResolvers,
|
||||
app?.renderEnvironment,
|
||||
]);
|
||||
|
||||
return (
|
||||
<div className="ImageExportModal">
|
||||
<h3>{t("imageExportDialog.header")}</h3>
|
||||
<div className="ImageExportModal__preview">
|
||||
<div className="ImageExportModal__preview__canvas" ref={previewRef}>
|
||||
<div
|
||||
className="ImageExportModal__preview__canvas"
|
||||
ref={previewContainerRef}
|
||||
>
|
||||
<div
|
||||
className="ImageExportModal__preview__canvas__content"
|
||||
ref={previewRef}
|
||||
hidden={!!renderError}
|
||||
/>
|
||||
{renderError && <ErrorCanvasPreview />}
|
||||
{!renderError && exportDimensions && (
|
||||
<div
|
||||
className="ImageExportModal__preview__dimensions"
|
||||
data-testid="image-export-dimensions"
|
||||
>
|
||||
{`${exportDimensions.width} \u00d7 ${exportDimensions.height} px`}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="ImageExportModal__preview__filename">
|
||||
{!nativeFileSystemSupported && (
|
||||
@@ -296,18 +384,51 @@ const ImageExportModal = ({
|
||||
label={t("imageExportDialog.label.scale")}
|
||||
name="exportScale"
|
||||
>
|
||||
<RadioGroup
|
||||
name="exportScale"
|
||||
value={exportScale}
|
||||
onChange={(scale) => {
|
||||
setExportScale(scale);
|
||||
actionManager.executeAction(actionChangeExportScale, "ui", scale);
|
||||
}}
|
||||
choices={EXPORT_SCALES.map((scale) => ({
|
||||
value: scale,
|
||||
label: `${scale}\u00d7`,
|
||||
}))}
|
||||
/>
|
||||
<div className="ImageExportModal__scale">
|
||||
<RadioGroup
|
||||
name="exportScale"
|
||||
value={exportScale}
|
||||
onChange={(scale) => {
|
||||
setExportScale(scale);
|
||||
actionManager.executeAction(
|
||||
actionChangeExportScale,
|
||||
"ui",
|
||||
scale,
|
||||
);
|
||||
}}
|
||||
choices={exportScaleChoices.map((scale) => {
|
||||
const matchesDisplay = scale === deviceExportScale;
|
||||
return {
|
||||
value: scale,
|
||||
label: matchesDisplay ? (
|
||||
<>
|
||||
{DeviceDesktopIcon}
|
||||
{`${scale}\u00d7`}
|
||||
</>
|
||||
) : (
|
||||
`${scale}\u00d7`
|
||||
),
|
||||
className: matchesDisplay
|
||||
? "ImageExportModal__scale__display"
|
||||
: undefined,
|
||||
};
|
||||
})}
|
||||
/>
|
||||
{deviceExportScale !== null && (
|
||||
<Tooltip
|
||||
className="ImageExportModal__scale__caption"
|
||||
label={t("imageExportDialog.tooltip.scaleMatchesDisplay", {
|
||||
percent: Math.round(deviceExportScale * 100),
|
||||
})}
|
||||
long
|
||||
delay={EXPORT_DIALOG_TOOLTIP_DELAY}
|
||||
>
|
||||
{DeviceDesktopIcon}
|
||||
{t("imageExportDialog.label.yourDisplay")}
|
||||
{helpIcon}
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
</ExportSetting>
|
||||
|
||||
<div className="ImageExportModal__settings__buttons">
|
||||
@@ -375,14 +496,14 @@ const ExportSetting = ({
|
||||
name,
|
||||
}: ExportSettingProps) => {
|
||||
return (
|
||||
<div className="ImageExportModal__settings__setting" title={label}>
|
||||
<div className="ImageExportModal__settings__setting">
|
||||
<label
|
||||
htmlFor={name}
|
||||
className="ImageExportModal__settings__setting__label"
|
||||
>
|
||||
{label}
|
||||
{tooltip && (
|
||||
<Tooltip label={tooltip} long={true}>
|
||||
<Tooltip label={tooltip} long delay={EXPORT_DIALOG_TOOLTIP_DELAY}>
|
||||
{helpIcon}
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
@@ -6,6 +6,7 @@ export type RadioGroupChoice<T> = {
|
||||
value: T;
|
||||
label: React.ReactNode;
|
||||
ariaLabel?: string;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
export type RadioGroupProps<T> = {
|
||||
@@ -25,7 +26,7 @@ export const RadioGroup = function <T>({
|
||||
<div className="RadioGroup">
|
||||
{choices.map((choice) => (
|
||||
<div
|
||||
className={clsx("RadioGroup__choice", {
|
||||
className={clsx("RadioGroup__choice", choice.className, {
|
||||
active: choice.value === value,
|
||||
})}
|
||||
key={String(choice.value)}
|
||||
|
||||
@@ -169,8 +169,11 @@ export const showTooltip = (
|
||||
position = "bottom",
|
||||
}: {
|
||||
long?: boolean;
|
||||
/** show after a short delay (unless a tooltip was visible just now) */
|
||||
delay?: boolean;
|
||||
/**
|
||||
* show after a delay (unless a tooltip was visible just now):
|
||||
* `true` for the default delay, or a number of ms
|
||||
*/
|
||||
delay?: boolean | number;
|
||||
position?: "bottom" | "top";
|
||||
} = {},
|
||||
) => {
|
||||
@@ -195,7 +198,10 @@ export const showTooltip = (
|
||||
Date.now() - tooltipHiddenAt > TOOLTIP_WARM_WINDOW
|
||||
) {
|
||||
showTooltipTimer = {
|
||||
id: ownerWindow.setTimeout(show, TOOLTIP_DELAY),
|
||||
id: ownerWindow.setTimeout(
|
||||
show,
|
||||
typeof delay === "number" ? delay : TOOLTIP_DELAY,
|
||||
),
|
||||
ownerWindow,
|
||||
};
|
||||
} else {
|
||||
@@ -210,8 +216,11 @@ type TooltipProps = {
|
||||
style?: React.CSSProperties;
|
||||
className?: string;
|
||||
disabled?: boolean;
|
||||
/** show after a short delay (unless a tooltip was visible just now) */
|
||||
delay?: boolean;
|
||||
/**
|
||||
* show after a delay (unless a tooltip was visible just now):
|
||||
* `true` for the default delay, or a number of ms
|
||||
*/
|
||||
delay?: boolean | number;
|
||||
};
|
||||
|
||||
export const Tooltip = ({
|
||||
|
||||
@@ -539,6 +539,7 @@
|
||||
"header": "Export image",
|
||||
"label": {
|
||||
"withBackground": "Background",
|
||||
"yourDisplay": "your display",
|
||||
"onlySelected": "Only selected",
|
||||
"darkMode": "Dark mode",
|
||||
"embedScene": "Embed scene",
|
||||
@@ -546,7 +547,8 @@
|
||||
"padding": "Padding"
|
||||
},
|
||||
"tooltip": {
|
||||
"embedScene": "Scene data will be saved into the exported PNG/SVG file so that the scene can be restored from it.\nWill increase exported file size."
|
||||
"embedScene": "Scene data will be saved into the exported PNG/SVG file so that the scene can be restored from it.\nWill increase exported file size.",
|
||||
"scaleMatchesDisplay": "Matches your display scaling ({{percent}}%), so it looks like your canvas at 100% zoom."
|
||||
},
|
||||
"title": {
|
||||
"exportToPng": "Export to PNG",
|
||||
|
||||
@@ -1275,7 +1275,7 @@ export const encodeSvgBase64Payload = ({
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// getCanvasSize
|
||||
// getCanvasSize / getExportSize
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// calculate smallest area to fit the contents in
|
||||
@@ -1289,6 +1289,64 @@ const getCanvasSize = (
|
||||
return [minX, minY, width, height];
|
||||
};
|
||||
|
||||
export type ExportContentSize = {
|
||||
width: number;
|
||||
height: number;
|
||||
padding: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Measures the unscaled content size (and effective padding) of an
|
||||
* unconstrained export of `elements`. Expensive (restores the elements and
|
||||
* computes their bounds), so measure once and size with `getExportSize()`.
|
||||
*/
|
||||
export const getExportContentSize = ({
|
||||
elements,
|
||||
exportingFrame = null,
|
||||
padding = DEFAULT_EXPORT_PADDING,
|
||||
frames,
|
||||
theme = THEME.LIGHT,
|
||||
renderEnvironment,
|
||||
}: {
|
||||
elements: readonly NonDeletedExcalidrawElement[];
|
||||
exportingFrame?: NonDeleted<ExcalidrawFrameLikeElement> | null;
|
||||
padding?: number;
|
||||
frames?: ExportSceneBaseConfig["frames"];
|
||||
theme?: Theme;
|
||||
renderEnvironment?: RenderEnvironment;
|
||||
}): ExportContentSize => {
|
||||
const restoredElements = getNonDeletedElements(
|
||||
restoreElements(elements, null, { deleteInvisibleElements: true }),
|
||||
);
|
||||
const resolvedRenderEnvironment =
|
||||
getExportRenderEnvironment(renderEnvironment);
|
||||
const frameRendering = getFrameRenderingConfig(exportingFrame, frames);
|
||||
const elementsForRender = prepareElementsForRender({
|
||||
elements: restoredElements,
|
||||
exportingFrame,
|
||||
theme,
|
||||
frameRendering,
|
||||
renderEnvironment: resolvedRenderEnvironment,
|
||||
});
|
||||
const [, , width, height] = getCanvasSize(
|
||||
exportingFrame ? [exportingFrame] : getRootElements(elementsForRender),
|
||||
);
|
||||
return { width, height, padding: exportingFrame ? 0 : padding };
|
||||
};
|
||||
|
||||
/**
|
||||
* The exact pixel dimensions `exportToCanvas` produces at `scale` for content
|
||||
* measured by `getExportContentSize()`.
|
||||
*/
|
||||
export const getExportSize = (
|
||||
{ width, height, padding }: ExportContentSize,
|
||||
scale: number,
|
||||
): { width: number; height: number } => ({
|
||||
// same arithmetic as `exportToCanvas` so the rounding matches
|
||||
width: Math.max(1, Math.round(width * scale + padding * 2 * scale)),
|
||||
height: Math.max(1, Math.round(height * scale + padding * 2 * scale)),
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// exportToBlob
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -16,7 +16,10 @@ import { useColorTopPicksDnD } from "../components/ColorPicker/colorTopPicksDnD"
|
||||
|
||||
import type { ExcalidrawImperativeAPI } from "../types";
|
||||
|
||||
const mountEditorInOwnDocument = (currentItemFontFamily?: FontFamily) => {
|
||||
const mountEditorInOwnDocument = (
|
||||
currentItemFontFamily?: FontFamily,
|
||||
devicePixelRatio?: number,
|
||||
) => {
|
||||
const iframe = document.createElement("iframe");
|
||||
document.body.append(iframe);
|
||||
|
||||
@@ -43,6 +46,7 @@ const mountEditorInOwnDocument = (currentItemFontFamily?: FontFamily) => {
|
||||
value: window.requestAnimationFrame.bind(window),
|
||||
},
|
||||
ResizeObserver: { value: window.ResizeObserver },
|
||||
...(devicePixelRatio && { devicePixelRatio: { value: devicePixelRatio } }),
|
||||
});
|
||||
Object.defineProperty(ownerDocument, "defaultView", { value: ownerWindow });
|
||||
Object.defineProperty(ownerWindow.HTMLCanvasElement.prototype, "getContext", {
|
||||
@@ -378,4 +382,19 @@ describe("cross-document rendering", () => {
|
||||
defaultFontEditor.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("defaults the export scale to its own window's pixel ratio", async () => {
|
||||
// e.g. a pop-out on a 150% display, opened from a 100% one
|
||||
expect(window.devicePixelRatio).toBe(1);
|
||||
const editor = mountEditorInOwnDocument(undefined, 1.5);
|
||||
|
||||
try {
|
||||
await waitFor(() =>
|
||||
expect(editor.getAPI()?.getAppState().isLoading).toBe(false),
|
||||
);
|
||||
expect(editor.getAPI()!.getAppState().exportScale).toBe(1.5);
|
||||
} finally {
|
||||
editor.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -4,18 +4,28 @@ import { MIME_TYPES, SVG_NS } from "@excalidraw/common";
|
||||
|
||||
import type { FileId, FractionalIndex } from "@excalidraw/element/types";
|
||||
|
||||
import { getDefaultAppState } from "../appState";
|
||||
import {
|
||||
getDefaultAppState,
|
||||
getDeviceExportScale,
|
||||
getExportScales,
|
||||
} from "../appState";
|
||||
import * as clipboardModule from "../clipboard";
|
||||
import { exportCanvas, prepareElementsForExport } from "../data";
|
||||
import { getDataURL } from "../data/blob";
|
||||
import { encodePngMetadata } from "../data/image";
|
||||
import { serializeAsJSON } from "../data/json";
|
||||
import { TOOLTIP_CLASS, TOOLTIP_VISIBLE_CLASS } from "../components/Tooltip";
|
||||
import { Excalidraw } from "../index";
|
||||
import { encodeSvgBase64Payload, exportScene } from "../scene/export";
|
||||
import {
|
||||
encodeSvgBase64Payload,
|
||||
exportScene,
|
||||
getExportContentSize,
|
||||
getExportSize,
|
||||
} from "../scene/export";
|
||||
import { decodeSvgBase64Payload } from "../data/encode";
|
||||
|
||||
import { API } from "./helpers/api";
|
||||
import { render, waitFor } from "./test-utils";
|
||||
import { fireEvent, render, screen, waitFor } from "./test-utils";
|
||||
|
||||
const { h } = window;
|
||||
|
||||
@@ -291,3 +301,173 @@ describe("export", () => {
|
||||
expect(svgText).toMatchSnapshot(`svg export output`);
|
||||
});
|
||||
});
|
||||
|
||||
describe("export scale & image export dialog", () => {
|
||||
const originalDpr = Object.getOwnPropertyDescriptor(
|
||||
window,
|
||||
"devicePixelRatio",
|
||||
);
|
||||
|
||||
const setDevicePixelRatio = (dpr: number) => {
|
||||
Object.defineProperty(window, "devicePixelRatio", {
|
||||
configurable: true,
|
||||
value: dpr,
|
||||
});
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
if (originalDpr) {
|
||||
Object.defineProperty(window, "devicePixelRatio", originalDpr);
|
||||
}
|
||||
});
|
||||
|
||||
it("normalizes devicePixelRatio and inserts dynamic scale in sorted order", () => {
|
||||
setDevicePixelRatio(1.5);
|
||||
expect(getDeviceExportScale(window)).toBe(1.5);
|
||||
expect(getDefaultAppState().exportScale).toBe(1.5);
|
||||
expect(getExportScales(1.5, 1.5)).toEqual([1, 1.5, 2, 3]);
|
||||
|
||||
setDevicePixelRatio(1.100000023841858);
|
||||
expect(getDeviceExportScale(window)).toBe(1.1);
|
||||
expect(getExportScales(1.1, 1)).toEqual([1, 1.1, 2, 3]);
|
||||
|
||||
setDevicePixelRatio(2);
|
||||
expect(getDeviceExportScale(window)).toBe(2);
|
||||
expect(getExportScales(2, 2)).toEqual([1, 2, 3]);
|
||||
|
||||
// out of [1, 3] range -> no dynamic scale added, default falls back to 1
|
||||
setDevicePixelRatio(0.75);
|
||||
expect(getDeviceExportScale(window)).toBeNull();
|
||||
expect(getDefaultAppState().exportScale).toBe(1);
|
||||
expect(getExportScales(null, 1)).toEqual([1, 2, 3]);
|
||||
|
||||
setDevicePixelRatio(4);
|
||||
expect(getDeviceExportScale(window)).toBeNull();
|
||||
expect(getDefaultAppState().exportScale).toBe(1);
|
||||
|
||||
// preserves a persisted non-default scale even on a different monitor
|
||||
expect(getExportScales(1, 1.5)).toEqual([1, 1.5, 2, 3]);
|
||||
});
|
||||
|
||||
it("getExportSize matches exportScene canvas dimensions", async () => {
|
||||
const rect = API.createElement({
|
||||
type: "rectangle",
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 100,
|
||||
height: 200,
|
||||
});
|
||||
const elements = [rect];
|
||||
|
||||
const contentSize = getExportContentSize({ elements });
|
||||
for (const scale of [1, 1.5, 2, 3]) {
|
||||
const expected = getExportSize(contentSize, scale);
|
||||
const canvas = await exportScene({
|
||||
type: "canvas",
|
||||
data: { elements },
|
||||
config: { scale },
|
||||
});
|
||||
expect(expected).toEqual({ width: canvas.width, height: canvas.height });
|
||||
}
|
||||
|
||||
const frame = API.createElement({
|
||||
type: "frame",
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 1000,
|
||||
height: 1000,
|
||||
});
|
||||
expect(
|
||||
getExportSize(
|
||||
getExportContentSize({ elements: [frame], exportingFrame: frame }),
|
||||
1.5,
|
||||
),
|
||||
).toEqual({ width: 1500, height: 1500 });
|
||||
});
|
||||
|
||||
it("shows dynamic dPR scale with a display marker and live export dimensions in dialog", async () => {
|
||||
setDevicePixelRatio(1.5);
|
||||
await render(<Excalidraw />);
|
||||
|
||||
const rect = API.createElement({
|
||||
type: "rectangle",
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 100,
|
||||
height: 200,
|
||||
});
|
||||
const smallRect = API.createElement({
|
||||
type: "rectangle",
|
||||
x: 200,
|
||||
y: 0,
|
||||
width: 40,
|
||||
height: 60,
|
||||
});
|
||||
API.setElements([rect, smallRect]);
|
||||
API.setSelectedElements([smallRect]);
|
||||
API.setAppState({ openDialog: { name: "imageExport" } });
|
||||
|
||||
const scaleInputs = await waitFor(() => {
|
||||
const inputs = Array.from(
|
||||
document.querySelectorAll<HTMLInputElement>(
|
||||
'input[type="radio"][name="exportScale"]',
|
||||
),
|
||||
);
|
||||
expect(inputs).toHaveLength(4);
|
||||
return inputs;
|
||||
});
|
||||
|
||||
const choices = scaleInputs.map((input) => input.parentElement!);
|
||||
expect(choices.map((el) => el.textContent)).toEqual([
|
||||
"1×",
|
||||
"1.5×",
|
||||
"2×",
|
||||
"3×",
|
||||
]);
|
||||
|
||||
// 1.5× matches dPR, is highlighted, and is active by default
|
||||
expect(
|
||||
choices[1].classList.contains("ImageExportModal__scale__display"),
|
||||
).toBe(true);
|
||||
expect(choices[1].classList.contains("active")).toBe(true);
|
||||
expect(
|
||||
choices[0].classList.contains("ImageExportModal__scale__display"),
|
||||
).toBe(false);
|
||||
const caption = document.querySelector<HTMLElement>(
|
||||
".ImageExportModal__scale__caption",
|
||||
)!;
|
||||
expect(caption.textContent).toBe("your display");
|
||||
|
||||
// hovering the caption explains the display scale
|
||||
fireEvent.pointerEnter(caption);
|
||||
const tooltip = await waitFor(() => {
|
||||
const el = document.querySelector<HTMLDivElement>(`.${TOOLTIP_CLASS}`);
|
||||
expect(el?.classList.contains(TOOLTIP_VISIBLE_CLASS)).toBe(true);
|
||||
return el;
|
||||
});
|
||||
expect(tooltip?.textContent).toBe(
|
||||
"Matches your display scaling (150%), so it looks like your canvas at 100% zoom.",
|
||||
);
|
||||
fireEvent.pointerLeave(caption);
|
||||
|
||||
// initial dimensions: onlySelected is true (smallRect 40x60 + 20px padding = 60x80) at 1.5× -> 90 × 120 px
|
||||
const dimensions = screen.getByTestId("image-export-dimensions");
|
||||
expect(dimensions.textContent).toBe("90 × 120 px");
|
||||
|
||||
// switching scale to 2× updates dimensions immediately -> 120 × 160 px
|
||||
fireEvent.click(scaleInputs[2]);
|
||||
expect(dimensions.textContent).toBe("120 × 160 px");
|
||||
// 1.5× stays highlighted even when inactive
|
||||
expect(
|
||||
choices[1].classList.contains("ImageExportModal__scale__display"),
|
||||
).toBe(true);
|
||||
expect(choices[1].classList.contains("active")).toBe(false);
|
||||
|
||||
// toggling "Only selected" off expands bounds to both rects (240x200 + 20px padding = 260x220) at 2× -> 520 × 440 px
|
||||
const onlySelectedSwitch = document.querySelector<HTMLInputElement>(
|
||||
'input[name="exportOnlySelected"]',
|
||||
)!;
|
||||
fireEvent.click(onlySelectedSwitch);
|
||||
expect(dimensions.textContent).toBe("520 × 440 px");
|
||||
});
|
||||
});
|
||||
@@ -35,7 +35,13 @@ const wrapperOf = (container: HTMLElement, label: string) =>
|
||||
container.querySelector<HTMLDivElement>(`[data-testid="${label}"]`)!
|
||||
.parentElement!;
|
||||
|
||||
const Harness = ({ labels, delay }: { labels: string[]; delay?: boolean }) => (
|
||||
const Harness = ({
|
||||
labels,
|
||||
delay,
|
||||
}: {
|
||||
labels: string[];
|
||||
delay?: boolean | number;
|
||||
}) => (
|
||||
<>
|
||||
{labels.map((label) => (
|
||||
<Tooltip key={label} label={label} delay={delay}>
|
||||
@@ -71,6 +77,23 @@ describe("Tooltip", () => {
|
||||
expect(isTooltipVisible()).toBe(false);
|
||||
});
|
||||
|
||||
it("waits a custom delay given in ms", () => {
|
||||
const { container } = renderComponent(
|
||||
<Harness labels={["a"]} delay={150} />,
|
||||
);
|
||||
|
||||
fireEvent.pointerEnter(wrapperOf(container, "a"));
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(149);
|
||||
});
|
||||
expect(isTooltipVisible()).toBe(false);
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(1);
|
||||
});
|
||||
expect(isTooltipVisible()).toBe(true);
|
||||
});
|
||||
|
||||
it("skips the delay while still warm from a tooltip that just hid", () => {
|
||||
const { container } = renderComponent(
|
||||
<Harness labels={["a", "b"]} delay />,
|
||||
|
||||
Reference in new issue
Block a user