diff --git a/packages/excalidraw/actions/actionCanvas.tsx b/packages/excalidraw/actions/actionCanvas.tsx index 5aae8cb92c..c5358df3c2 100644 --- a/packages/excalidraw/actions/actionCanvas.tsx +++ b/packages/excalidraw/actions/actionCanvas.tsx @@ -100,7 +100,7 @@ export const actionClearCanvas = register({ newElementWith(element, { isDeleted: true }), ), appState: { - ...getDefaultAppState(), + ...getDefaultAppState(app.ownerWindow), files: {}, theme: appState.theme, penMode: appState.penMode, diff --git a/packages/excalidraw/appState.ts b/packages/excalidraw/appState.ts index 190d83c398..0ccbb3a215 100644 --- a/packages/excalidraw/appState.ts +++ b/packages/excalidraw/appState.ts @@ -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(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 => { 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, diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsx index 5beb21ab89..9fb078a19d 100644 --- a/packages/excalidraw/components/App.tsx +++ b/packages/excalidraw/components/App.tsx @@ -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 { 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 { 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 { 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) { diff --git a/packages/excalidraw/components/ImageExportDialog.scss b/packages/excalidraw/components/ImageExportDialog.scss index f20220e943..66218408c2 100644 --- a/packages/excalidraw/components/ImageExportDialog.scss +++ b/packages/excalidraw/components/ImageExportDialog.scss @@ -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 { diff --git a/packages/excalidraw/components/ImageExportDialog.tsx b/packages/excalidraw/components/ImageExportDialog.tsx index 2d4743ff7a..efaf5e48ef 100644 --- a/packages/excalidraw/components/ImageExportDialog.tsx +++ b/packages/excalidraw/components/ImageExportDialog.tsx @@ -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 (
@@ -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(null); const previewRef = useRef(null); const previewRenderRequestIdRef = useRef(0); const [renderError, setRenderError] = useState(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 (

{t("imageExportDialog.header")}

-
+
+
{!nativeFileSystemSupported && ( @@ -296,18 +384,51 @@ const ImageExportModal = ({ label={t("imageExportDialog.label.scale")} name="exportScale" > - { - setExportScale(scale); - actionManager.executeAction(actionChangeExportScale, "ui", scale); - }} - choices={EXPORT_SCALES.map((scale) => ({ - value: scale, - label: `${scale}\u00d7`, - }))} - /> +
+ { + 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 && ( + + {DeviceDesktopIcon} + {t("imageExportDialog.label.yourDisplay")} + {helpIcon} + + )} +
@@ -375,14 +496,14 @@ const ExportSetting = ({ name, }: ExportSettingProps) => { return ( -
+