This commit is contained in:
Tom Moor committed 2024-12-09 20:33:21 -05:00
1 parent 908f053920
commit 7830ccb501
5 files changed
+202 -50

No files matched your search

+90 -11
View File
@@ -1,21 +1,73 @@
import * as React from "react";
import styled from "styled-components";
import { EmbedDescriptor } from "../embeds";
import { getMatchingEmbed } from "../lib/embeds";
import { ComponentProps } from "../types";
import DisabledEmbed from "./DisabledEmbed";
import Frame from "./Frame";
import { ResizeBottom, ResizeLeft, ResizeRight } from "./ResizeHandle";
import useDragResize from "./hooks/useDragResize";
const EmbedComponent = ({
isEditable,
isSelected,
theme,
node,
embeds,
embedsDisabled,
}: ComponentProps & {
type Props = ComponentProps & {
embeds: EmbedDescriptor[];
embedsDisabled?: boolean;
}) => {
style?: React.CSSProperties;
onChangeSize?: (props: { width: number; height?: number }) => void;
};
const Embed = (props: Props) => {
const ref = React.useRef<HTMLIFrameElement>(null);
const { node, isEditable, onChangeSize } = props;
const naturalWidth = "100%";
const naturalHeight = 400;
const isResizable = !!onChangeSize;
const { width, height, setSize, handlePointerDown, dragging } = useDragResize(
{
width: node.attrs.width ?? naturalWidth,
height: node.attrs.height ?? naturalHeight,
naturalWidth,
naturalHeight,
gridSnap: 5,
onChangeSize,
ref,
}
);
React.useEffect(() => {
if (node.attrs.width && node.attrs.width !== width) {
setSize({
width: node.attrs.width,
height: node.attrs.height,
});
}
}, [node.attrs.width]);
const style: React.CSSProperties = {
width: width || "100%",
height: height || 400,
pointerEvents: dragging ? "none" : "all",
};
return (
<FrameWrapper ref={ref}>
<InnerEmbed ref={ref} style={style} {...props} />
{isEditable && isResizable && (
<>
<ResizeBottom
onPointerDown={handlePointerDown("bottom")}
$dragging={!!dragging}
/>
</>
)}
</FrameWrapper>
);
};
const InnerEmbed = React.forwardRef(function InnerEmbed_(
{ isEditable, isSelected, theme, node, embeds, embedsDisabled, style }: Props,
ref
) {
const cache = React.useMemo(
() => getMatchingEmbed(embeds, node.attrs.href),
[embeds, node.attrs.href]
@@ -43,7 +95,9 @@ const EmbedComponent = ({
const src = embed.transformMatch(matches);
return (
<Frame
ref={ref}
src={src}
style={style}
isSelected={isSelected}
canonicalUrl={embed.hideToolbar ? undefined : node.attrs.href}
title={embed.title}
@@ -57,7 +111,9 @@ const EmbedComponent = ({
return (
// @ts-expect-error Component type
<embed.component
ref={ref}
attrs={node.attrs}
style={style}
matches={matches}
isEditable={isEditable}
isSelected={isSelected}
@@ -68,6 +124,29 @@ const EmbedComponent = ({
}
return null;
};
});
export default EmbedComponent;
const FrameWrapper = styled.div`
line-height: 0;
position: relative;
margin-left: auto;
margin-right: auto;
white-space: nowrap;
cursor: default;
border-radius: 8px;
user-select: none;
max-width: 100%;
overflow: hidden;
transition-property: width, max-height;
transition-duration: 150ms;
transition-timing-function: ease-in-out;
&:hover {
${ResizeLeft}, ${ResizeRight} {
opacity: 1;
}
}
`;
export default Embed;
+6 -15
View File
@@ -20,10 +20,8 @@ type Props = Omit<Optional<HTMLIFrameElement>, "children"> & {
canonicalUrl?: string;
/** Whether the node is currently selected */
isSelected?: boolean;
/** The width of the frame */
width?: string;
/** The height of the frame */
height?: string;
/** Additional styling */
style?: React.CSSProperties;
/** The allow policy of the frame */
allow?: string;
};
@@ -58,8 +56,7 @@ class Frame extends React.Component<PropsWithRef> {
render() {
const {
border,
width = "100%",
height = "400px",
style,
forwardedRef,
icon,
title,
@@ -69,12 +66,11 @@ class Frame extends React.Component<PropsWithRef> {
className = "",
src,
} = this.props;
const withBar = !!(icon || canonicalUrl);
const withBar = false;
return (
<Rounded
width={width}
height={height}
style={style}
$withBar={withBar}
$border={border}
className={
@@ -86,8 +82,7 @@ class Frame extends React.Component<PropsWithRef> {
ref={forwardedRef}
$withBar={withBar}
sandbox="allow-same-origin allow-scripts allow-popups allow-forms allow-downloads allow-storage-access-by-user-activation"
width={width}
height={height}
style={style}
frameBorder="0"
title="embed"
loading="lazy"
@@ -121,8 +116,6 @@ const Iframe = styled.iframe<{ $withBar: boolean }>`
`;
const Rounded = styled.div<{
width: string;
height: string;
$withBar: boolean;
$border?: boolean;
}>`
@@ -130,8 +123,6 @@ const Rounded = styled.div<{
${(props) => (props.$border ? props.theme.embedBorder : "transparent")};
border-radius: 6px;
overflow: hidden;
width: ${(props) => props.width};
height: ${(props) => (props.$withBar ? props.height + 28 : props.height)};
`;
const Open = styled.a`
+20
View File
@@ -41,3 +41,23 @@ export const ResizeRight = styled(ResizeLeft)`
right: 8px;
}
`;
export const ResizeBottom = styled(ResizeLeft)`
cursor: ns-resize;
left: 0;
right: 0;
top: initial;
bottom: 8px;
width: auto;
height: 8px;
&:after {
left: 50%;
bottom: 8px;
transform: translateX(-50%);
width: 15%;
height: 6px;
min-width: 20px;
min-height: 0;
}
`;
+50 -22
View File
@@ -1,7 +1,7 @@
import * as React from "react";
import { EditorStyleHelper } from "../../styles/EditorStyleHelper";
type DragDirection = "left" | "right";
type DragDirection = "left" | "right" | "bottom";
type SizeState = { width: number; height?: number };
@@ -59,30 +59,53 @@ export default function useDragResize(props: Params): ReturnValue {
const handlePointerMove = (event: PointerEvent) => {
event.preventDefault();
let diff;
let diffX, diffY;
if (dragging === "left") {
diff = offset - event.pageX;
diffX = offset - event.pageX;
} else if (dragging === "right") {
diffX = event.pageX - offset;
} else {
diff = event.pageX - offset;
diffY = event.pageY - offset;
}
const gridWidth = (props.gridSnap / 100) * maxWidth;
const newWidth = sizeAtDragStart.width + diff * 2;
const widthOnGrid = Math.round(newWidth / gridWidth) * gridWidth;
const constrainedWidth = constrainWidth(widthOnGrid, maxWidth);
const aspectRatio = props.naturalHeight / props.naturalWidth;
if (diffX) {
const gridWidth = (props.gridSnap / 100) * maxWidth;
const newWidth = sizeAtDragStart.width + diffX * 2;
const widthOnGrid = Math.round(newWidth / gridWidth) * gridWidth;
const constrainedWidth = constrainWidth(widthOnGrid, maxWidth);
const aspectRatio = props.naturalHeight / props.naturalWidth;
setSize({
width:
// If the natural width is the same as the constrained width, use the natural width -
// special case for images resized to the full width of the editor.
constrainedWidth === Math.min(newWidth, maxWidth)
? props.naturalWidth
: constrainedWidth,
height: props.naturalWidth
? Math.round(constrainedWidth * aspectRatio)
: undefined,
});
setSize({
width:
// If the natural width is the same as the constrained width, use the natural width -
// special case for images resized to the full width of the editor.
constrainedWidth === Math.min(newWidth, maxWidth)
? props.naturalWidth
: constrainedWidth,
height: props.naturalWidth
? Math.round(constrainedWidth * aspectRatio)
: undefined,
});
}
if (diffY) {
const gridHeight = (props.gridSnap / 100) * maxWidth;
const newHeight = sizeAtDragStart.height + diffY;
const heightOnGrid = Math.round(newHeight / gridHeight) * gridHeight;
console.log({
newHeight,
heightOnGrid,
gridHeight,
diffY,
sizeAtDragStart,
});
setSize((state) => ({
...state,
height: heightOnGrid,
}));
}
};
const handlePointerUp = (event: PointerEvent) => {
@@ -127,7 +150,11 @@ export default function useDragResize(props: Params): ReturnValue {
width: constrainWidth(size.width, max),
height: size.height,
});
setOffset(event.pageX);
setOffset(
dragDirection === "left" || dragDirection === "right"
? event.pageX
: event.pageY
);
setDragging(dragDirection);
};
@@ -137,7 +164,8 @@ export default function useDragResize(props: Params): ReturnValue {
}
if (dragging) {
document.body.style.cursor = "ew-resize";
document.body.style.cursor =
dragging === "left" || dragging === "right" ? "ew-resize" : "ns-resize";
document.addEventListener("keydown", handleKeyDown);
document.addEventListener("pointermove", handlePointerMove);
document.addEventListener("pointerup", handlePointerUp);
+36 -2
View File
@@ -1,6 +1,6 @@
import { Token } from "markdown-it";
import { NodeSpec, NodeType, Node as ProsemirrorNode } from "prosemirror-model";
import { Command } from "prosemirror-state";
import { Command, NodeSelection } from "prosemirror-state";
import * as React from "react";
import { Primitive } from "utility-types";
import { sanitizeUrl } from "../../utils/urls";
@@ -23,7 +23,15 @@ export default class Embed extends Node {
group: "block",
atom: true,
attrs: {
href: {},
href: {
validate: "string",
},
width: {
default: null,
},
height: {
default: null,
},
},
parseDOM: [
{
@@ -87,14 +95,40 @@ export default class Embed extends Node {
return [embedsRule(this.options.embeds)];
}
handleChangeSize =
({ node, getPos }: { node: ProsemirrorNode; getPos: () => number }) =>
({ width, height }: { width: number; height?: number }) => {
const { view } = this.editor;
const { tr } = view.state;
console.log({
width,
height,
});
const pos = getPos();
const transaction = tr
.setNodeMarkup(pos, undefined, {
...node.attrs,
width,
height,
})
.setMeta("addToHistory", true);
const $pos = transaction.doc.resolve(getPos());
view.dispatch(transaction.setSelection(new NodeSelection($pos)));
};
component = (props: ComponentProps) => {
const { embeds, embedsDisabled } = this.editor.props;
console.log(props.node);
return (
<EmbedComponent
{...props}
embeds={embeds}
embedsDisabled={embedsDisabled}
onChangeSize={this.handleChangeSize(props)}
/>
);
};