From 97c780fd044c56c2e6b8a7015749945049f80bb1 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 20 Nov 2026 14:58:35 -0500 Subject: [PATCH] feat: Consistent resize handles for images, videos, PDFs and embeds All media get side, bottom and corner handles driven by one lock rule. Images and videos stay locked. PDFs and embeds can be unlocked to resize each axis independently. --- .../components/AspectRatioLockButton.tsx | 40 ++++ app/editor/components/MediaDimension.tsx | 35 +-- app/editor/components/MediaLinkEditor.tsx | 16 ++ .../commands/toggleAspectRatioLock.test.ts | 58 +++++ .../editor/commands/toggleAspectRatioLock.ts | 30 +++ shared/editor/components/Embed.tsx | 54 +++-- shared/editor/components/Image.tsx | 43 +--- shared/editor/components/PDF.tsx | 83 ++----- shared/editor/components/ResizeHandle.tsx | 123 ++++++++--- shared/editor/components/Video.tsx | 20 +- .../editor/components/hooks/useDragResize.ts | 204 +++++++++--------- shared/editor/lib/pdf.test.ts | 16 +- shared/editor/lib/pdf.ts | 17 -- shared/editor/nodes/Attachment.tsx | 32 +-- shared/editor/nodes/Embed.tsx | 7 + shared/i18n/locales/en_US/translation.json | 2 +- 16 files changed, 437 insertions(+), 343 deletions(-) create mode 100644 app/editor/components/AspectRatioLockButton.tsx create mode 100644 shared/editor/commands/toggleAspectRatioLock.test.ts create mode 100644 shared/editor/commands/toggleAspectRatioLock.ts diff --git a/app/editor/components/AspectRatioLockButton.tsx b/app/editor/components/AspectRatioLockButton.tsx new file mode 100644 index 0000000000..b8319e0631 --- /dev/null +++ b/app/editor/components/AspectRatioLockButton.tsx @@ -0,0 +1,40 @@ +import { PadlockIcon } from "outline-icons"; +import type * as React from "react"; +import { useTranslation } from "react-i18next"; +import styled, { useTheme } from "styled-components"; +import { UnlockedPadlockIcon } from "~/components/Icons/UnlockedPadlockIcon"; +import ToolbarButton from "./ToolbarButton"; + +interface Props extends React.ComponentProps { + /** Whether the aspect ratio is locked. */ + isLocked: boolean; +} + +/** + * A toolbar button that shows and toggles whether media keeps its aspect ratio. + * + * @param props - the component props. + * @returns the button. + */ +export function AspectRatioLockButton({ isLocked, ...rest }: Props) { + const { t } = useTranslation(); + const theme = useTheme(); + + return ( + + {isLocked ? ( + + ) : ( + + )} + + ); +} + +const LockButton = styled(ToolbarButton)` + justify-content: center; +`; diff --git a/app/editor/components/MediaDimension.tsx b/app/editor/components/MediaDimension.tsx index 7361aa7c4d..a2d63407ec 100644 --- a/app/editor/components/MediaDimension.tsx +++ b/app/editor/components/MediaDimension.tsx @@ -1,8 +1,7 @@ import type { NodeSelection } from "prosemirror-state"; import * as Toolbar from "@radix-ui/react-toolbar"; -import { PadlockIcon } from "outline-icons"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; -import styled, { useTheme } from "styled-components"; +import styled from "styled-components"; import Flex from "@shared/components/Flex"; import Text from "@shared/components/Text"; import { contentWidth } from "@shared/editor/lib/contentWidth"; @@ -10,13 +9,11 @@ import { pdfNaturalHeight, pdfNaturalWidth, resolvePDFDimensions, - scalePDFDimensions, } from "@shared/editor/lib/pdf"; import { extraArea } from "@shared/styles"; -import { UnlockedPadlockIcon } from "~/components/Icons/UnlockedPadlockIcon"; import Input, { NativeInput, Outline } from "~/components/Input"; import { useEditor } from "./EditorContext"; -import ToolbarButton from "./ToolbarButton"; +import { AspectRatioLockButton } from "./AspectRatioLockButton"; import Tooltip from "./Tooltip"; import { useTranslation } from "react-i18next"; @@ -40,7 +37,6 @@ interface Props { export function MediaDimension({ tooltip }: Props) { const isDraggingRef = useRef(false); const { t } = useTranslation(); - const theme = useTheme(); const { view, commands } = useEditor(); const { state } = view; const { selection } = state; @@ -261,9 +257,7 @@ export function MediaDimension({ tooltip }: Props) { const dimensions = nodeType === "attachment" - ? isLocked - ? scalePDFDimensions({ width, height }, newWidth) - : { width: newWidth, height: newHeight ?? height } + ? resolvePDFDimensions(newWidth, newHeight) : { width: newWidth, height: newHeight }; setLocalDimension({ @@ -277,7 +271,7 @@ export function MediaDimension({ tooltip }: Props) { return () => { window.removeEventListener("media-drag-resize", handleDragResize); }; - }, [nodeType, width, height, isLocked]); + }, [nodeType]); // Debounce validation so errors are not shown while typing. useEffect(() => { @@ -302,8 +296,6 @@ export function MediaDimension({ tooltip }: Props) { return () => clearTimeout(timeout); }, [width, height, localDimension, isOutsideBounds]); - const lockLabel = t("Lock aspect ratio"); - return ( @@ -334,19 +326,12 @@ export function MediaDimension({ tooltip }: Props) { {canUnlock && ( - + - - {isLocked ? ( - - ) : ( - - )} - + /> )} @@ -379,7 +364,3 @@ const StyledInput = styled(Input)<{ $error?: boolean }>` ${(props) => props.$error && `color: ${props.theme.danger}`}; } `; - -const LockButton = styled(ToolbarButton)` - justify-content: center; -`; diff --git a/app/editor/components/MediaLinkEditor.tsx b/app/editor/components/MediaLinkEditor.tsx index 76ae8c1965..57bd5df2a2 100644 --- a/app/editor/components/MediaLinkEditor.tsx +++ b/app/editor/components/MediaLinkEditor.tsx @@ -7,7 +7,9 @@ import { useTranslation } from "react-i18next"; import styled from "styled-components"; import Flex from "~/components/Flex"; import Tooltip from "~/components/Tooltip"; +import { toggleAspectRatioLock } from "@shared/editor/commands/toggleAspectRatioLock"; import Input from "~/editor/components/Input"; +import { AspectRatioLockButton } from "./AspectRatioLockButton"; import ToolbarButton from "./ToolbarButton"; import useOnClickOutside from "~/hooks/useOnClickOutside"; @@ -52,6 +54,12 @@ export function MediaLinkEditor({ view.focus(); }, [view]); + const handleToggleLock = useCallback(() => { + if (node) { + toggleAspectRatioLock(node.type)(view.state, view.dispatch); + } + }, [node, view]); + const openLink = useCallback(() => { window.open(url, "_blank"); }, [url]); @@ -115,6 +123,14 @@ export function MediaLinkEditor({ onKeyDown={handleKeyDown} readOnly={!view.editable} /> + {view.editable && node.type.name === "embed" && ( + + + + )} diff --git a/shared/editor/commands/toggleAspectRatioLock.test.ts b/shared/editor/commands/toggleAspectRatioLock.test.ts new file mode 100644 index 0000000000..1206dff5df --- /dev/null +++ b/shared/editor/commands/toggleAspectRatioLock.test.ts @@ -0,0 +1,58 @@ +import { NodeSelection } from "prosemirror-state"; +import type { EditorState } from "prosemirror-state"; +import { createEditorState, p, schema } from "@shared/test/editor"; +import { toggleAspectRatioLock } from "./toggleAspectRatioLock"; + +const { embed } = schema.nodes; + +/** + * Creates a state with an embed node selected. + * + * @param attrs - the embed attributes. + * @returns the editor state. + */ +function selectedEmbed(attrs: Record = {}) { + const state = createEditorState( + schema.nodes.doc.create(null, [ + embed.create({ href: "https://example.com", ...attrs }), + p(""), + ]) + ); + return state.apply(state.tr.setSelection(NodeSelection.create(state.doc, 0))); +} + +/** + * Runs the command and returns the resulting state. + * + * @param state - the editor state. + * @returns the state after the command, or undefined if it did not apply. + */ +function toggle(state: EditorState) { + let next: EditorState | undefined; + toggleAspectRatioLock(embed)(state, (tr) => { + next = state.apply(tr); + }); + return next; +} + +describe("toggleAspectRatioLock", () => { + it("defaults to locked", () => { + expect(selectedEmbed().doc.firstChild?.attrs.lockAspectRatio).toBeNull(); + }); + + it("unlocks a locked node and keeps it selected", () => { + const next = toggle(selectedEmbed()); + expect(next?.doc.firstChild?.attrs.lockAspectRatio).toBe(false); + expect(next?.selection).toBeInstanceOf(NodeSelection); + }); + + it("clears the attribute when locking again", () => { + const next = toggle(selectedEmbed({ lockAspectRatio: false })); + expect(next?.doc.firstChild?.attrs.lockAspectRatio).toBeNull(); + }); + + it("does not apply to other node types", () => { + const state = createEditorState(schema.nodes.doc.create(null, [p("text")])); + expect(toggleAspectRatioLock(embed)(state)).toBe(false); + }); +}); diff --git a/shared/editor/commands/toggleAspectRatioLock.ts b/shared/editor/commands/toggleAspectRatioLock.ts new file mode 100644 index 0000000000..5c08142134 --- /dev/null +++ b/shared/editor/commands/toggleAspectRatioLock.ts @@ -0,0 +1,30 @@ +import type { NodeType } from "prosemirror-model"; +import type { Command } from "prosemirror-state"; +import { NodeSelection } from "prosemirror-state"; + +/** + * Toggles whether a selected node of the given type keeps its aspect ratio when + * resized. An unset value means locked, so locking clears the attribute. + * + * @param type - the node type that stores the lock. + * @returns the command. + */ +export function toggleAspectRatioLock(type: NodeType): Command { + return (state, dispatch) => { + const { selection } = state; + if (!(selection instanceof NodeSelection) || selection.node.type !== type) { + return false; + } + + const { attrs } = selection.node; + const transaction = state.tr + .setNodeMarkup(selection.from, undefined, { + ...attrs, + lockAspectRatio: attrs.lockAspectRatio === false ? null : false, + }) + .setMeta("addToHistory", true); + const $pos = transaction.doc.resolve(selection.from); + dispatch?.(transaction.setSelection(new NodeSelection($pos))); + return true; + }; +} diff --git a/shared/editor/components/Embed.tsx b/shared/editor/components/Embed.tsx index 7d42a2eea6..297e153939 100644 --- a/shared/editor/components/Embed.tsx +++ b/shared/editor/components/Embed.tsx @@ -5,7 +5,8 @@ import { getMatchingEmbed } from "../lib/embeds"; import type { ComponentProps } from "../types"; import DisabledEmbed from "./DisabledEmbed"; import Frame from "./Frame"; -import { ResizeBottom, ResizeLeft, ResizeRight } from "./ResizeHandle"; +import { contentWidth } from "../lib/contentWidth"; +import { ResizeHandles, ResizeLeft, ResizeRight } from "./ResizeHandle"; import useDragResize from "./hooks/useDragResize"; type Props = ComponentProps & { @@ -22,32 +23,49 @@ const Embed = (props: Props) => { const naturalHeight = 400; const isResizable = !!onChangeSize && !embedsDisabled; - const { width, height, handlePointerDown, dragging } = useDragResize({ - width: node.attrs.width ?? naturalWidth, - height: node.attrs.height ?? naturalHeight, - naturalWidth, - naturalHeight, - onChangeSize, - ref, - }); + // A width at the editor edge is stored as unset, so the embed stays full width. + const handleChangeSize = React.useCallback( + (size: { width: number; height?: number }) => { + const max = ref.current ? contentWidth(ref.current) : Infinity; + onChangeSize?.({ + ...size, + width: size.width >= max ? naturalWidth : size.width, + }); + }, + [onChangeSize] + ); + + const { width, height, handlePointerDown, handleDoubleClick, dragging } = + useDragResize({ + width: node.attrs.width ?? naturalWidth, + height: node.attrs.height ?? naturalHeight, + naturalWidth, + naturalHeight, + isLocked: node.attrs.lockAspectRatio !== false, + onChangeSize: onChangeSize ? handleChangeSize : undefined, + ref, + }); const style: React.CSSProperties = { - width: width || "100%", + width: "100%", height: height || 400, - maxWidth: "100%", pointerEvents: dragging ? "none" : "all", }; + // The wrapper takes the width so the resize handles sit on the frame edges. return ( - + {isEditable && isResizable && ( - <> - - + )} ); diff --git a/shared/editor/components/Image.tsx b/shared/editor/components/Image.tsx index 7fb6b2e849..d08be35324 100644 --- a/shared/editor/components/Image.tsx +++ b/shared/editor/components/Image.tsx @@ -10,14 +10,7 @@ import { isExternalUrl, sanitizeImageSrc, sanitizeUrl } from "../../utils/urls"; import { getDisplayUrl } from "../lib/uploadPlaceholder"; import { EditorStyleHelper } from "../styles/EditorStyleHelper"; import type { ComponentProps } from "../types"; -import { - ResizeLeft, - ResizeRight, - ResizeTopLeft, - ResizeTopRight, - ResizeBottomLeft, - ResizeBottomRight, -} from "./ResizeHandle"; +import { ResizeHandles, ResizeLeft, ResizeRight } from "./ResizeHandle"; import useDragResize from "./hooks/useDragResize"; type Props = ComponentProps & { @@ -290,35 +283,10 @@ const Image = (props: Props) => { )} {isEditable && !isFullWidth && isResizable && ( <> - - - - - - )} @@ -432,8 +400,7 @@ const ImageWrapper = styled.div<{ isFullWidth: boolean; $dragging: boolean }>` opacity: 0.9; } - ${ResizeLeft}, ${ResizeRight}, - ${ResizeTopLeft}, ${ResizeTopRight}, ${ResizeBottomLeft}, ${ResizeBottomRight} { + ${ResizeLeft}, ${ResizeRight} { opacity: 1; } } diff --git a/shared/editor/components/PDF.tsx b/shared/editor/components/PDF.tsx index 38c3a52feb..d020998962 100644 --- a/shared/editor/components/PDF.tsx +++ b/shared/editor/components/PDF.tsx @@ -2,14 +2,7 @@ import React, { useCallback, useRef } from "react"; import { useMergeRefs } from "react-merge-refs"; import styled from "styled-components"; import useDragResize from "./hooks/useDragResize"; -import { - ResizeBottomLeft, - ResizeBottomRight, - ResizeLeft, - ResizeRight, - ResizeTopLeft, - ResizeTopRight, -} from "./ResizeHandle"; +import { ResizeHandles, ResizeLeft, ResizeRight } from "./ResizeHandle"; import type { ComponentProps } from "../types"; import { isFirefox } from "../../utils/browser"; import { sanitizeUrl } from "../../utils/urls"; @@ -42,15 +35,17 @@ export default function PdfViewer(props: Props) { const debounceTimerRef = useRef(null); const dimensions = resolvePDFDimensions(node.attrs.width, node.attrs.height); - const { width, height, handlePointerDown, dragging } = useDragResize({ - width: node.attrs.width, - height: dimensions.height, - naturalWidth: pdfNaturalWidth, - naturalHeight: pdfNaturalHeight, - aspectRatio: dimensions.height / dimensions.width, - onChangeSize, - ref, - }); + const { width, height, handlePointerDown, handleDoubleClick, dragging } = + useDragResize({ + width: node.attrs.width, + height: dimensions.height, + naturalWidth: pdfNaturalWidth, + naturalHeight: pdfNaturalHeight, + aspectRatio: dimensions.height / dimensions.width, + isLocked: node.attrs.lockAspectRatio !== false, + onChangeSize, + ref, + }); // force embed to reload, so the content fits the new size. const observeRef = useCallback( @@ -122,42 +117,19 @@ export default function PdfViewer(props: Props) { style={{ width: "100%", height: "auto", - aspectRatio: - node.attrs.lockAspectRatio !== false - ? `${dimensions.width} / ${dimensions.height}` - : `${width ?? dimensions.width} / ${height ?? dimensions.height}`, + aspectRatio: `${width ?? dimensions.width} / ${height ?? dimensions.height}`, pointerEvents: !isEditable || (isSelected && !dragging) ? "initial" : "none", marginTop: 6, }} /> {isEditable && !!props.onChangeSize && ( - <> - - - - - - - + )} ); @@ -187,23 +159,6 @@ const PDFWrapper = styled.div<{ $dragging: boolean }>` will-change: ${(props) => (props.$dragging ? "width, height" : "auto")}; } - /* The wrapper clips overflow, so corners sit inside it rather than on the edge. */ - ${ResizeTopLeft}, ${ResizeTopRight} { - top: 0; - } - - ${ResizeBottomLeft}, ${ResizeBottomRight} { - bottom: 0; - } - - ${ResizeTopLeft}, ${ResizeBottomLeft} { - left: 0; - } - - ${ResizeTopRight}, ${ResizeBottomRight} { - right: 0; - } - &:hover { ${ResizeLeft}, ${ResizeRight} { opacity: 1; diff --git a/shared/editor/components/ResizeHandle.tsx b/shared/editor/components/ResizeHandle.tsx index f819e1925a..fdab55360f 100644 --- a/shared/editor/components/ResizeHandle.tsx +++ b/shared/editor/components/ResizeHandle.tsx @@ -1,5 +1,74 @@ +import type * as React from "react"; import styled from "styled-components"; import { s } from "../../styles"; +import type { DragDirection } from "./hooks/useDragResize"; + +interface ResizeHandlesProps { + /** Returns the pointer down handler for a resize direction. */ + onPointerDown: ( + direction: DragDirection + ) => (event: React.PointerEvent) => void; + /** Callback triggered when a handle is double-clicked. */ + onDoubleClick?: () => void; + /** Whether the side handles are visible without hover. */ + isVisible: boolean; + /** Whether the handles sit inside the edges, for wrappers that clip overflow. */ + isInset?: boolean; +} + +/** + * The full set of resize handles for a media node: visible side handles, and + * invisible bottom and corner handles. + * + * @param props - the component props. + * @returns the resize handles. + */ +export function ResizeHandles({ + onPointerDown, + onDoubleClick, + isVisible, + isInset = false, +}: ResizeHandlesProps) { + return ( + <> + + + + + + + + + ); +} export const ResizeLeft = styled.div<{ $dragging: boolean }>` cursor: ew-resize; @@ -42,35 +111,35 @@ export const ResizeRight = styled(ResizeLeft)` } `; -export const ResizeBottom = styled(ResizeLeft)` - cursor: ns-resize; - left: 30%; - right: 30%; - top: initial; - bottom: 8px; - width: auto; - height: 8px; +interface EdgeProps { + $inset: boolean; +} - &:after { - left: 50%; - bottom: 8px; - transform: translateX(-50%); - width: 25%; - height: 6px; - min-width: 20px; - min-height: 0; +/** Offsets an invisible handle by half its size, or keeps it inside the edge. */ +const edgeOffset = (props: EdgeProps) => (props.$inset ? "0" : "-4px"); + +export const ResizeBottom = styled.div` + cursor: ns-resize; + position: absolute; + left: 8px; + right: 8px; + bottom: ${edgeOffset}; + height: 8px; + z-index: 9; + user-select: none; + + @media print { + display: none; } `; -export const ResizeCorner = styled.div<{ $dragging: boolean }>` +export const ResizeCorner = styled.div` position: absolute; width: 8px; height: 8px; border-radius: 50%; z-index: 10; user-select: none; - opacity: ${(props) => (props.$dragging ? 1 : 0)}; - transition: opacity 150ms ease-in-out; @media print { display: none; @@ -79,24 +148,24 @@ export const ResizeCorner = styled.div<{ $dragging: boolean }>` export const ResizeTopLeft = styled(ResizeCorner)` cursor: nwse-resize; - top: -4px; - left: -4px; + top: ${edgeOffset}; + left: ${edgeOffset}; `; export const ResizeTopRight = styled(ResizeCorner)` cursor: nesw-resize; - top: -4px; - right: -4px; + top: ${edgeOffset}; + right: ${edgeOffset}; `; export const ResizeBottomLeft = styled(ResizeCorner)` cursor: nesw-resize; - bottom: -4px; - left: -4px; + bottom: ${edgeOffset}; + left: ${edgeOffset}; `; export const ResizeBottomRight = styled(ResizeCorner)` cursor: nwse-resize; - bottom: -4px; - right: -4px; + bottom: ${edgeOffset}; + right: ${edgeOffset}; `; diff --git a/shared/editor/components/Video.tsx b/shared/editor/components/Video.tsx index fc8a37a450..1f1a7a9a3d 100644 --- a/shared/editor/components/Video.tsx +++ b/shared/editor/components/Video.tsx @@ -5,7 +5,7 @@ import { sanitizeUrl } from "../../utils/urls"; import { getDisplayUrl } from "../lib/uploadPlaceholder"; import { EditorStyleHelper } from "../styles/EditorStyleHelper"; import type { ComponentProps } from "../types"; -import { ResizeLeft, ResizeRight } from "./ResizeHandle"; +import { ResizeHandles, ResizeLeft, ResizeRight } from "./ResizeHandle"; import useDragResize from "./hooks/useDragResize"; type Props = ComponentProps & { @@ -80,18 +80,12 @@ export default function Video(props: Props) { controls={!dragging} /> {isEditable && isResizable && ( - <> - - - + )} {children} diff --git a/shared/editor/components/hooks/useDragResize.ts b/shared/editor/components/hooks/useDragResize.ts index dc9b2fe260..46b0671b55 100644 --- a/shared/editor/components/hooks/useDragResize.ts +++ b/shared/editor/components/hooks/useDragResize.ts @@ -2,7 +2,8 @@ import * as React from "react"; import { contentWidth } from "../../lib/contentWidth"; import { EditorStyleHelper } from "../../styles/EditorStyleHelper"; -type DragDirection = +/** A side or corner of an element that can be dragged to resize it. */ +export type DragDirection = | "left" | "right" | "bottom" @@ -74,10 +75,19 @@ type Params = { ref: React.RefObject; /** Whether the element should scale symmetrically from the center. Defaults to true. */ isCentered?: boolean; - /** The height to width ratio kept when resizing from a corner. Defaults to the natural ratio. */ + /** Whether resizing keeps the aspect ratio. Defaults to true. */ + isLocked?: boolean; + /** The height to width ratio kept while locked. Defaults to the natural ratio, then the ratio at drag start. */ aspectRatio?: number; }; +const cornerDirections: DragDirection[] = [ + "topLeft", + "topRight", + "bottomLeft", + "bottomRight", +]; + export default function useDragResize(props: Params): ReturnValue { const { onChangeSize, @@ -87,10 +97,11 @@ export default function useDragResize(props: Params): ReturnValue { minHeight, ref, isCentered = true, + isLocked = true, } = props; const aspectRatio = props.aspectRatio ?? - (naturalWidth ? naturalHeight / naturalWidth : undefined); + (naturalWidth && naturalHeight ? naturalHeight / naturalWidth : undefined); // The committed size passed in through props is the source of truth. `draft` // holds the size being previewed while resizing and is released once the @@ -107,6 +118,7 @@ export default function useDragResize(props: Params): ReturnValue { width: props.width, height: props.height, }); + const [ratioAtDragStart, setRatioAtDragStart] = React.useState(); const [dragging, setDragging] = React.useState(); const isResizable = !!onChangeSize; @@ -141,114 +153,107 @@ export default function useDragResize(props: Params): ReturnValue { const handlePointerMove = React.useCallback( (event: PointerEvent) => { event.preventDefault(); - - let diffX = 0; - let diffY = 0; - if (dragging === "left") { - diffX = offset.x - event.pageX; - } else if (dragging === "right") { - diffX = event.pageX - offset.x; - } else if (dragging === "bottom") { - diffY = event.pageY - offset.y; - } else if (dragging === "topLeft") { - diffX = offset.x - event.pageX; - diffY = offset.y - event.pageY; - } else if (dragging === "topRight") { - diffX = event.pageX - offset.x; - diffY = offset.y - event.pageY; - } else if (dragging === "bottomLeft") { - diffX = offset.x - event.pageX; - diffY = event.pageY - offset.y; - } else if (dragging === "bottomRight") { - diffX = event.pageX - offset.x; - diffY = event.pageY - offset.y; + if (!dragging) { + return; } - const isCorner = [ - "topLeft", - "topRight", - "bottomLeft", - "bottomRight", - ].includes(dragging || ""); + const isCorner = cornerDirections.includes(dragging); + const isLeft = + dragging === "left" || + dragging === "topLeft" || + dragging === "bottomLeft"; + const isTop = dragging === "topLeft" || dragging === "topRight"; + const movesX = dragging !== "bottom"; + const movesY = dragging === "bottom" || isCorner; + const diffX = movesX + ? isLeft + ? offset.x - event.pageX + : event.pageX - offset.x + : 0; + const diffY = movesY + ? isTop + ? offset.y - event.pageY + : event.pageY - offset.y + : 0; + const factor = isCentered ? 2 : 1; + const startWidth = sizeAtDragStart.width; - if (isCorner && aspectRatio) { - const hFactor = isCentered ? 0.5 : 1; - const factor = isCentered ? 2 : 1; - const dW = - (diffX * hFactor + diffY * aspectRatio) / - (hFactor * hFactor + aspectRatio * aspectRatio); - diffX = dW / factor; - } + // When dragged to or beyond the editor edge, store the natural width as a + // sentinel for "full width" so the element stays responsive. Only do this + // when the natural width actually exceeds the editor — otherwise constrain + // to the editor edge rather than snapping a smaller image back down to its + // natural size. + const toWidth = (newWidth: number) => { + const constrained = constrainWidth(newWidth, maxWidth); + return { + stored: + newWidth >= maxWidth && naturalWidth >= maxWidth + ? naturalWidth + : constrained, + }; + }; - if (diffX && sizeAtDragStart.width) { - const factor = isCentered ? 2 : 1; - const newWidth = sizeAtDragStart.width + diffX * factor; - const constrainedWidth = constrainWidth(newWidth, maxWidth); + let nextState: SizeState; - // When dragged to or beyond the editor edge, store the natural width as a - // sentinel for "full width" so the element stays responsive. Only do this - // when the natural width actually exceeds the editor — otherwise constrain - // to the editor edge rather than snapping a smaller image back down to its - // natural size. - const nextWidth = - newWidth >= maxWidth && naturalWidth >= maxWidth - ? naturalWidth - : constrainedWidth; - const nextHeight = isCorner - ? aspectRatio - ? Math.round(constrainedWidth * aspectRatio) - : undefined - : sizeAtDragStart.height; + if (isLocked && ratioAtDragStart) { + const ratio = ratioAtDragStart; + let newWidth = startWidth + diffX * factor; - setDraft({ - width: nextWidth, - height: nextHeight, - }); + if (dragging === "bottom") { + newWidth = startWidth + diffY / ratio; + } else if (isCorner) { + // Project the pointer movement onto the diagonal of the aspect ratio. + const hFactor = 1 / factor; + newWidth = + startWidth + + (diffX * hFactor + diffY * ratio) / + (hFactor * hFactor + ratio * ratio); + } - window.dispatchEvent( - new CustomEvent("media-drag-resize", { - detail: { - width: nextWidth, - height: nextHeight, - isDragging: true, - }, - }) - ); - } + const { stored } = toWidth(newWidth); + nextState = { + width: stored, + height: Math.round(stored * ratio), + }; + } else { + let nextHeight = sizeAtDragStart.height; + if (movesY && sizeAtDragStart.height) { + const gridHeight = gridHeightSnap ?? 10; + const newHeight = sizeAtDragStart.height + diffY; + const heightOnGrid = Math.round(newHeight / gridHeight) * gridHeight; + nextHeight = Math.max(heightOnGrid, minHeight ?? 50); + } - if (diffY && sizeAtDragStart.height && !isCorner) { - const gridHeight = gridHeightSnap ?? 10; - const newHeight = sizeAtDragStart.height + diffY; - const heightOnGrid = Math.round(newHeight / gridHeight) * gridHeight; - const nextHeight = Math.max(heightOnGrid, minHeight ?? 50); - - // Vertical-only drags never adjust the width, so it is carried over - // from the current size rather than recomputed. - const nextState = { - width: sizeRef.current.width, + nextState = { + // Vertical-only drags never adjust the width, so it is carried over + // from the current size rather than recomputed. + width: movesX + ? toWidth(startWidth + diffX * factor).stored + : sizeRef.current.width, height: nextHeight, }; - - setDraft(nextState); - - window.dispatchEvent( - new CustomEvent("media-drag-resize", { - detail: { - ...nextState, - isDragging: true, - }, - }) - ); } + + setDraft(nextState); + + window.dispatchEvent( + new CustomEvent("media-drag-resize", { + detail: { + ...nextState, + isDragging: true, + }, + }) + ); }, [ dragging, offset, sizeAtDragStart, + ratioAtDragStart, maxWidth, gridHeightSnap, naturalWidth, - aspectRatio, + isLocked, minHeight, constrainWidth, isCentered, @@ -321,12 +326,15 @@ export default function useDragResize(props: Params): ReturnValue { // Calculate constraints once at the start of dragging as it's relatively expensive operation const max = ref.current ? contentWidth(ref.current) : Infinity; setMaxWidth(max); - setSizeAtDragStart({ - // When no width has been set yet the element is displayed at full width, - // so begin resizing from the maximum width rather than the minimum. - width: constrainWidth(size.width || max, max), - height: size.height, - }); + + // When no width has been set yet the element is displayed at full width, + // so begin resizing from the maximum width rather than the minimum. + const startWidth = constrainWidth(size.width || max, max); + setSizeAtDragStart({ width: startWidth, height: size.height }); + setRatioAtDragStart( + aspectRatio ?? + (size.height && startWidth ? size.height / startWidth : undefined) + ); setOffset({ x: event.pageX, y: event.pageY, diff --git a/shared/editor/lib/pdf.test.ts b/shared/editor/lib/pdf.test.ts index 22edc2f4a1..2ddf5baeca 100644 --- a/shared/editor/lib/pdf.test.ts +++ b/shared/editor/lib/pdf.test.ts @@ -1,9 +1,4 @@ -import { - pdfNaturalHeight, - pdfNaturalWidth, - resolvePDFDimensions, - scalePDFDimensions, -} from "./pdf"; +import { pdfNaturalHeight, pdfNaturalWidth, resolvePDFDimensions } from "./pdf"; describe("resolvePDFDimensions", () => { it("returns the natural dimensions when none are stored", () => { @@ -27,12 +22,3 @@ describe("resolvePDFDimensions", () => { }); }); }); - -describe("scalePDFDimensions", () => { - it("keeps the aspect ratio of the given dimensions", () => { - expect(scalePDFDimensions({ width: 700, height: 400 }, 350)).toEqual({ - width: 350, - height: 200, - }); - }); -}); diff --git a/shared/editor/lib/pdf.ts b/shared/editor/lib/pdf.ts index 179b5f6fab..02fe1d3262 100644 --- a/shared/editor/lib/pdf.ts +++ b/shared/editor/lib/pdf.ts @@ -43,20 +43,3 @@ export function resolvePDFDimensions( height: pdfNaturalHeight, }; } - -/** - * Scales PDF preview dimensions to a new width and keeps their aspect ratio. - * - * @param dimensions - the current preview dimensions. - * @param width - the new preview width. - * @returns the scaled PDF preview dimensions. - */ -export function scalePDFDimensions( - dimensions: PDFDimensions, - width: number -): PDFDimensions { - return { - width, - height: Math.round((width * dimensions.height) / dimensions.width), - }; -} diff --git a/shared/editor/nodes/Attachment.tsx b/shared/editor/nodes/Attachment.tsx index ea0359aff7..33934430bb 100644 --- a/shared/editor/nodes/Attachment.tsx +++ b/shared/editor/nodes/Attachment.tsx @@ -12,11 +12,12 @@ import type { Primitive } from "utility-types"; import { bytesToHumanReadable, getEventFiles } from "../../utils/files"; import { sanitizeUrl } from "../../utils/urls"; import insertFiles from "../commands/insertFiles"; +import { toggleAspectRatioLock } from "../commands/toggleAspectRatioLock"; import toggleWrap from "../commands/toggleWrap"; import FileExtension from "../components/FileExtension"; import Widget from "../components/Widget"; import type { MarkdownSerializerState } from "../lib/markdown/serializer"; -import { resolvePDFDimensions, scalePDFDimensions } from "../lib/pdf"; +import { resolvePDFDimensions } from "../lib/pdf"; import { isPDFAttachment } from "../queries/isPDFAttachment"; import attachmentsRule from "../rules/links"; import type { ComponentProps } from "../types"; @@ -130,11 +131,7 @@ export default class Attachment extends Node { } const $pos = doc.resolve(pos); - const current = resolvePDFDimensions(node.attrs.width, node.attrs.height); - const dimensions = - node.attrs.lockAspectRatio !== false - ? scalePDFDimensions(current, width) - : { width, height: height ?? current.height }; + const dimensions = resolvePDFDimensions(width, height); view.dispatch(tr.setSelection(new NodeSelection($pos))); commands["resizeAttachment"](dimensions); @@ -277,25 +274,10 @@ export default class Attachment extends Node { dispatch?.(transaction.setSelection(new NodeSelection($pos))); return true; }, - toggleAttachmentAspectRatioLock: (): Command => (state, dispatch) => { - if ( - !(state.selection instanceof NodeSelection) || - !state.selection.node.attrs.preview - ) { - return false; - } - - const { attrs } = state.selection.node; - const transaction = state.tr - .setNodeMarkup(state.selection.from, undefined, { - ...attrs, - lockAspectRatio: attrs.lockAspectRatio === false ? null : false, - }) - .setMeta("addToHistory", true); - const $pos = transaction.doc.resolve(state.selection.from); - dispatch?.(transaction.setSelection(new NodeSelection($pos))); - return true; - }, + toggleAttachmentAspectRatioLock: (): Command => (state, dispatch) => + state.selection instanceof NodeSelection && + !!state.selection.node.attrs.preview && + toggleAspectRatioLock(type)(state, dispatch), resizeAttachment: ({ width, height }: { width: number; height?: number }): Command => (state, dispatch) => { diff --git a/shared/editor/nodes/Embed.tsx b/shared/editor/nodes/Embed.tsx index b2145b9610..ee03e75289 100644 --- a/shared/editor/nodes/Embed.tsx +++ b/shared/editor/nodes/Embed.tsx @@ -11,6 +11,7 @@ import { NodeSelection, TextSelection } from "prosemirror-state"; import * as React from "react"; import type { Primitive } from "utility-types"; import { sanitizeUrl } from "../../utils/urls"; +import { toggleAspectRatioLock } from "../commands/toggleAspectRatioLock"; import EmbedComponent from "../components/Embed"; import defaultEmbeds from "../embeds"; import { getMatchingEmbed, transformListToEmbeds } from "../lib/embeds"; @@ -41,6 +42,11 @@ export default class Embed extends Node { height: { default: null, }, + // Unset means locked, so only unlocked nodes store a value. + lockAspectRatio: { + default: null, + validate: "boolean|null", + }, }, parseDOM: [ { @@ -143,6 +149,7 @@ export default class Embed extends Node { commands({ type }: { type: NodeType }) { return { + toggleEmbedAspectRatioLock: (): Command => toggleAspectRatioLock(type), embed: (attrs: Record): Command => (state, dispatch) => { diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index 04729bbe44..c3cd3164cb 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -778,6 +778,7 @@ "Last seen": "Last seen", "{{ time }} local time": "{{ time }} local time", "Your import completed": "Your import completed", + "Lock aspect ratio": "Lock aspect ratio", "Templates": "Templates", "View comment thread": "View comment thread", "Previous match": "Previous match", @@ -794,7 +795,6 @@ "Remove link": "Remove link", "Formatting controls": "Formatting controls", "Search or paste a link": "Search or paste a link", - "Lock aspect ratio": "Lock aspect ratio", "Image width": "Image width", "Width": "Width", "Image height": "Image height",