Files
outline/shared/editor/nodes/Attachment.tsx
T
Tom Moor ee3c88bc14 fix: Standardize media resizing, add aspect ratio lock control (#14677)
* fix: Allow PDF embed width and height to change independently

Adds an aspect ratio lock toggle to the media dimension toolbar for PDF
embeds, renders PDFs at their stored aspect ratio, and keeps that ratio
when drag resizing.

* feat: Add corner resize handles to PDF embeds and persist aspect ratio lock

Stores the lock as an optional attachment attribute, where unset means
locked, so side handles change only the width of unlocked PDFs.

* 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.

* feat: Show width, height and lock in the embed toolbar

* feat: Start embeds unlocked and step media dimensions with arrow keys

Embeds start with an unlocked aspect ratio so full-width embeds can still
be made taller, while PDFs start locked. Up and down arrows step the
dimension inputs by 1, or 10 with shift.

* fix: Align the aspect ratio padlock with the dimension digits

* fix: Move the aspect ratio lock closer to the dimension inputs

* fix: Show the aspect ratio lock state in its tooltip
2026-11-21 11:33:02 -05:00

328 lines
9.2 KiB
TypeScript

import type Token from "markdown-it/lib/token.mjs";
import { DownloadIcon } from "outline-icons";
import type {
NodeSpec,
NodeType,
Node as ProsemirrorNode,
} from "prosemirror-model";
import type { Command } from "prosemirror-state";
import { NodeSelection } from "prosemirror-state";
import { Trans } from "react-i18next";
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 } from "../lib/pdf";
import { isPDFAttachment } from "../queries/isPDFAttachment";
import attachmentsRule from "../rules/links";
import type { ComponentProps } from "../types";
import Node from "./Node";
import PdfViewer from "../components/PDF";
export default class Attachment extends Node {
get name() {
return "attachment";
}
get rulePlugins() {
return [attachmentsRule];
}
get schema(): NodeSpec {
return {
attrs: {
id: {
default: null,
},
href: {
default: null,
},
title: {},
size: {
default: 0,
},
preview: {
default: false,
},
width: {
default: null,
},
height: {
default: null,
},
// Unset means the default for the node type, see isAspectRatioLocked.
lockAspectRatio: {
default: null,
validate: "boolean|null",
},
contentType: {
default: null,
validate: "string|null",
},
},
group: "block",
defining: true,
atom: true,
parseDOM: [
{
priority: 100,
tag: "a.attachment",
getAttrs: (dom: HTMLAnchorElement) => ({
id: dom.id,
title: dom.innerText,
href: dom.getAttribute("href"),
size: parseInt(dom.dataset.size || "0", 10),
}),
},
],
toDOM: (node) => [
"a",
{
class: `attachment`,
id: node.attrs.id,
href: sanitizeUrl(node.attrs.href),
download: node.attrs.title,
"data-size": node.attrs.size,
},
String(node.attrs.title),
],
leafText: (node) => node.attrs.title,
};
}
handleSelect =
({ getPos }: ComponentProps) =>
() => {
const { view } = this.editor;
const pos = getPos();
if (pos === undefined) {
return;
}
const $pos = view.state.doc.resolve(pos);
const transaction = view.state.tr.setSelection(new NodeSelection($pos));
view.dispatch(transaction);
};
handleChangeSize =
({
node,
getPos,
}: {
node: ProsemirrorNode;
getPos: () => number | undefined;
}) =>
({ width, height }: { width: number; height?: number }) => {
if (!node.attrs.preview) {
return;
}
const { view, commands } = this.editor;
const { doc, tr } = view.state;
const pos = getPos();
if (pos === undefined) {
return;
}
const $pos = doc.resolve(pos);
const dimensions = resolvePDFDimensions(width, height);
view.dispatch(tr.setSelection(new NodeSelection($pos)));
commands["resizeAttachment"](dimensions);
};
component = (props: ComponentProps) => {
const { embedsDisabled } = this.editor.props;
const { isSelected, isEditable, node } = props;
const context =
node.attrs.href || node.attrs.size ? (
bytesToHumanReadable(node.attrs.size || "0")
) : (
<>
<Trans>Uploading</Trans>…
</>
);
return node.attrs.preview && !embedsDisabled && isPDFAttachment(node) ? (
<PdfViewer
icon={<FileExtension title={node.attrs.title} />}
title={node.attrs.title}
context={context}
onChangeSize={this.handleChangeSize(props)}
{...props}
/>
) : (
<Widget
icon={<FileExtension title={node.attrs.title} />}
href={node.attrs.href}
title={node.attrs.title}
onMouseDown={this.handleSelect(props)}
onDoubleClick={() => {
this.editor.commands.downloadAttachment();
}}
onClick={(event) => {
if (isEditable) {
event.preventDefault();
event.stopPropagation();
}
}}
context={context}
isSelected={isSelected}
>
{node.attrs.href && !isEditable && <DownloadIcon size={20} />}
</Widget>
);
};
commands({ type }: { type: NodeType }) {
return {
createAttachment: (attrs: Record<string, Primitive>) =>
toggleWrap(type, attrs),
deleteAttachment: (): Command => (state, dispatch) => {
dispatch?.(state.tr.deleteSelection());
return true;
},
replaceAttachment: (): Command => (state) => {
if (!(state.selection instanceof NodeSelection)) {
return false;
}
const { view } = this.editor;
const { node } = state.selection;
const { uploadFile, onFileUploadStart, onFileUploadStop, onNotice } =
this.editor.props;
if (!uploadFile) {
throw new Error("uploadFile prop is required to replace attachments");
}
const accept = isPDFAttachment(node)
? ".pdf"
: node.type.name === "attachment"
? "*"
: null;
if (accept === null) {
return false;
}
// create an input element and click to trigger picker
const inputElement = document.createElement("input");
inputElement.type = "file";
inputElement.accept = accept;
inputElement.onchange = (event) => {
const files = getEventFiles(event);
void insertFiles(view, event, state.selection.from, files, {
uploadFile,
onFileUploadStart,
onFileUploadStop,
onNotice,
replaceExisting: true,
attrs: {
preview: node.attrs.preview,
},
});
};
inputElement.click();
return true;
},
downloadAttachment: (): Command => (state) => {
if (!(state.selection instanceof NodeSelection)) {
return false;
}
const { node } = state.selection;
const href = sanitizeUrl(node.attrs.href);
if (!href) {
return false;
}
// create a temporary link node and click it
const link = document.createElement("a");
link.href = href;
link.target = "_blank";
link.rel = "noopener noreferrer";
document.body.appendChild(link);
link.click();
// cleanup
document.body.removeChild(link);
return true;
},
toggleAttachmentPreview: (): Command => (state, dispatch) => {
if (!(state.selection instanceof NodeSelection)) {
return false;
}
const { node } = state.selection;
if (!isPDFAttachment(node)) {
return false;
}
const { attrs } = state.selection.node;
const transaction = state.tr
.setNodeMarkup(state.selection.from, undefined, {
...attrs,
preview: !attrs.preview,
})
.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) => {
if (
!(state.selection instanceof NodeSelection) ||
!state.selection.node.attrs.preview
) {
return false;
}
const { view } = this.editor;
const { tr } = view.state;
const { attrs } = state.selection.node;
const transaction = tr
.setNodeMarkup(state.selection.from, undefined, {
...attrs,
width,
height,
})
.setMeta("addToHistory", true);
const $pos = transaction.doc.resolve(state.selection.from);
dispatch?.(transaction.setSelection(new NodeSelection($pos)));
return true;
},
};
}
toMarkdown(state: MarkdownSerializerState, node: ProsemirrorNode) {
state.ensureNewLine();
state.write(
`[${node.attrs.title} ${node.attrs.size}](${node.attrs.href})\n\n`
);
state.ensureNewLine();
}
parseMarkdown() {
return {
node: "attachment",
getAttrs: (tok: Token) => ({
href: tok.attrGet("href"),
title: tok.attrGet("title"),
size: tok.attrGet("size"),
}),
};
}
}