mirror of
https://github.com/linsa-io/linsa.git
synced 2026-01-12 12:20:23 +01:00
chore: Enhancement + New Feature (#185)
* wip * wip page * chore: style * wip pages * wip pages * chore: toggle * chore: link * feat: topic search * chore: page section * refactor: apply tailwind class ordering * fix: handle loggedIn user for guest route * feat: folder & image schema * chore: move utils to shared * refactor: tailwind class ordering * feat: img ext for editor * refactor: remove qa * fix: tanstack start * fix: wrong import * chore: use toast * chore: schema
This commit is contained in:
173
web/shared/editor/extensions/image/components/image-actions.tsx
Normal file
173
web/shared/editor/extensions/image/components/image-actions.tsx
Normal file
@@ -0,0 +1,173 @@
|
||||
import * as React from "react"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import {
|
||||
ClipboardCopyIcon,
|
||||
DotsHorizontalIcon,
|
||||
DownloadIcon,
|
||||
Link2Icon,
|
||||
SizeIcon,
|
||||
} from "@radix-ui/react-icons"
|
||||
|
||||
interface ImageActionsProps {
|
||||
shouldMerge?: boolean
|
||||
isLink?: boolean
|
||||
onView?: () => void
|
||||
onDownload?: () => void
|
||||
onCopy?: () => void
|
||||
onCopyLink?: () => void
|
||||
}
|
||||
|
||||
interface ActionButtonProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
icon: React.ReactNode
|
||||
tooltip: string
|
||||
}
|
||||
|
||||
export const ActionWrapper = React.memo(
|
||||
React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ children, className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"absolute right-3 top-3 flex flex-row rounded px-0.5 opacity-0 group-hover/node-image:opacity-100",
|
||||
"border-[0.5px] bg-[var(--mt-bg-secondary)] [backdrop-filter:saturate(1.8)_blur(20px)]",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
ActionWrapper.displayName = "ActionWrapper"
|
||||
|
||||
export const ActionButton = React.memo(
|
||||
React.forwardRef<HTMLButtonElement, ActionButtonProps>(
|
||||
({ icon, tooltip, className, ...props }, ref) => (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
ref={ref}
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
"relative flex h-7 w-7 flex-row rounded-none p-0 text-muted-foreground hover:text-foreground",
|
||||
"bg-transparent hover:bg-transparent",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{icon}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">{tooltip}</TooltipContent>
|
||||
</Tooltip>
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
ActionButton.displayName = "ActionButton"
|
||||
|
||||
type ActionKey = "onView" | "onDownload" | "onCopy" | "onCopyLink"
|
||||
|
||||
const ActionItems: Array<{
|
||||
key: ActionKey
|
||||
icon: React.ReactNode
|
||||
tooltip: string
|
||||
isLink?: boolean
|
||||
}> = [
|
||||
{
|
||||
key: "onView",
|
||||
icon: <SizeIcon className="size-4" />,
|
||||
tooltip: "View image",
|
||||
},
|
||||
{
|
||||
key: "onDownload",
|
||||
icon: <DownloadIcon className="size-4" />,
|
||||
tooltip: "Download image",
|
||||
},
|
||||
{
|
||||
key: "onCopy",
|
||||
icon: <ClipboardCopyIcon className="size-4" />,
|
||||
tooltip: "Copy image to clipboard",
|
||||
},
|
||||
{
|
||||
key: "onCopyLink",
|
||||
icon: <Link2Icon className="size-4" />,
|
||||
tooltip: "Copy image link",
|
||||
isLink: true,
|
||||
},
|
||||
]
|
||||
|
||||
export const ImageActions: React.FC<ImageActionsProps> = React.memo(
|
||||
({ shouldMerge = false, isLink = false, ...actions }) => {
|
||||
const [isOpen, setIsOpen] = React.useState(false)
|
||||
|
||||
const handleAction = React.useCallback(
|
||||
(e: React.MouseEvent, action: (() => void) | undefined) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
action?.()
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
const filteredActions = React.useMemo(
|
||||
() => ActionItems.filter((item) => isLink || !item.isLink),
|
||||
[isLink],
|
||||
)
|
||||
|
||||
return (
|
||||
<ActionWrapper className={cn({ "opacity-100": isOpen })}>
|
||||
{shouldMerge ? (
|
||||
<DropdownMenu open={isOpen} onOpenChange={setIsOpen}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<ActionButton
|
||||
icon={<DotsHorizontalIcon className="size-4" />}
|
||||
tooltip="Open menu"
|
||||
onClick={(e) => e.preventDefault()}
|
||||
/>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-56" align="end">
|
||||
{filteredActions.map(({ key, icon, tooltip }) => (
|
||||
<DropdownMenuItem
|
||||
key={key}
|
||||
onClick={(e) => handleAction(e, actions[key])}
|
||||
>
|
||||
<div className="flex flex-row items-center gap-2">
|
||||
{icon}
|
||||
<span>{tooltip}</span>
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
) : (
|
||||
filteredActions.map(({ key, icon, tooltip }) => (
|
||||
<ActionButton
|
||||
key={key}
|
||||
icon={icon}
|
||||
tooltip={tooltip}
|
||||
onClick={(e) => handleAction(e, actions[key])}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</ActionWrapper>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
ImageActions.displayName = "ImageActions"
|
||||
@@ -0,0 +1,16 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Spinner } from "@shared/components/spinner"
|
||||
|
||||
export const ImageOverlay = React.memo(() => {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-row items-center justify-center",
|
||||
"absolute inset-0 rounded bg-[var(--mt-overlay)] opacity-100 transition-opacity",
|
||||
)}
|
||||
>
|
||||
<Spinner className="size-7" />
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,311 @@
|
||||
import * as React from "react"
|
||||
import { NodeViewWrapper, type NodeViewProps } from "@tiptap/react"
|
||||
import type { ElementDimensions } from "../hooks/use-drag-resize"
|
||||
import { useDragResize } from "../hooks/use-drag-resize"
|
||||
import { ResizeHandle } from "./resize-handle"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { NodeSelection } from "@tiptap/pm/state"
|
||||
import { Controlled as ControlledZoom } from "react-medium-image-zoom"
|
||||
import { ActionButton, ActionWrapper, ImageActions } from "./image-actions"
|
||||
import { useImageActions } from "../hooks/use-image-actions"
|
||||
import { blobUrlToBase64 } from "@shared/editor/lib/utils"
|
||||
import { InfoCircledIcon, TrashIcon } from "@radix-ui/react-icons"
|
||||
import { ImageOverlay } from "./image-overlay"
|
||||
import { Spinner } from "@shared/components/spinner"
|
||||
|
||||
const MAX_HEIGHT = 600
|
||||
const MIN_HEIGHT = 120
|
||||
const MIN_WIDTH = 120
|
||||
|
||||
interface ImageState {
|
||||
src: string
|
||||
isServerUploading: boolean
|
||||
imageLoaded: boolean
|
||||
isZoomed: boolean
|
||||
error: boolean
|
||||
naturalSize: ElementDimensions
|
||||
}
|
||||
|
||||
export const ImageViewBlock: React.FC<NodeViewProps> = ({
|
||||
editor,
|
||||
node,
|
||||
getPos,
|
||||
selected,
|
||||
updateAttributes,
|
||||
}) => {
|
||||
const {
|
||||
src: initialSrc,
|
||||
width: initialWidth,
|
||||
height: initialHeight,
|
||||
} = node.attrs
|
||||
const [imageState, setImageState] = React.useState<ImageState>({
|
||||
src: initialSrc,
|
||||
isServerUploading: false,
|
||||
imageLoaded: false,
|
||||
isZoomed: false,
|
||||
error: false,
|
||||
naturalSize: { width: initialWidth, height: initialHeight },
|
||||
})
|
||||
|
||||
const containerRef = React.useRef<HTMLDivElement>(null)
|
||||
const [activeResizeHandle, setActiveResizeHandle] = React.useState<
|
||||
"left" | "right" | null
|
||||
>(null)
|
||||
|
||||
const focus = React.useCallback(() => {
|
||||
const { view } = editor
|
||||
const $pos = view.state.doc.resolve(getPos())
|
||||
view.dispatch(view.state.tr.setSelection(new NodeSelection($pos)))
|
||||
}, [editor, getPos])
|
||||
|
||||
const onDimensionsChange = React.useCallback(
|
||||
({ width, height }: ElementDimensions) => {
|
||||
focus()
|
||||
updateAttributes({ width, height })
|
||||
},
|
||||
[focus, updateAttributes],
|
||||
)
|
||||
|
||||
const aspectRatio =
|
||||
imageState.naturalSize.width / imageState.naturalSize.height
|
||||
const maxWidth = MAX_HEIGHT * aspectRatio
|
||||
|
||||
const { isLink, onView, onDownload, onCopy, onCopyLink, onRemoveImg } =
|
||||
useImageActions({
|
||||
editor,
|
||||
node,
|
||||
src: imageState.src,
|
||||
onViewClick: (isZoomed) =>
|
||||
setImageState((prev) => ({ ...prev, isZoomed })),
|
||||
})
|
||||
|
||||
const {
|
||||
currentWidth,
|
||||
currentHeight,
|
||||
updateDimensions,
|
||||
initiateResize,
|
||||
isResizing,
|
||||
} = useDragResize({
|
||||
initialWidth: initialWidth ?? imageState.naturalSize.width,
|
||||
initialHeight: initialHeight ?? imageState.naturalSize.height,
|
||||
contentWidth: imageState.naturalSize.width,
|
||||
contentHeight: imageState.naturalSize.height,
|
||||
gridInterval: 0.1,
|
||||
onDimensionsChange,
|
||||
minWidth: MIN_WIDTH,
|
||||
minHeight: MIN_HEIGHT,
|
||||
maxWidth,
|
||||
})
|
||||
|
||||
const shouldMerge = React.useMemo(() => currentWidth <= 180, [currentWidth])
|
||||
|
||||
const handleImageLoad = React.useCallback(
|
||||
(ev: React.SyntheticEvent<HTMLImageElement>) => {
|
||||
const img = ev.target as HTMLImageElement
|
||||
const newNaturalSize = {
|
||||
width: img.naturalWidth,
|
||||
height: img.naturalHeight,
|
||||
}
|
||||
setImageState((prev) => ({
|
||||
...prev,
|
||||
naturalSize: newNaturalSize,
|
||||
imageLoaded: true,
|
||||
}))
|
||||
updateAttributes({
|
||||
width: img.width || newNaturalSize.width,
|
||||
height: img.height || newNaturalSize.height,
|
||||
alt: img.alt,
|
||||
title: img.title,
|
||||
})
|
||||
|
||||
if (!initialWidth) {
|
||||
updateDimensions((state) => ({ ...state, width: newNaturalSize.width }))
|
||||
}
|
||||
},
|
||||
[initialWidth, updateAttributes, updateDimensions],
|
||||
)
|
||||
|
||||
const handleImageError = React.useCallback(() => {
|
||||
setImageState((prev) => ({ ...prev, error: true, imageLoaded: true }))
|
||||
}, [])
|
||||
|
||||
const handleResizeStart = React.useCallback(
|
||||
(direction: "left" | "right") =>
|
||||
(event: React.PointerEvent<HTMLDivElement>) => {
|
||||
setActiveResizeHandle(direction)
|
||||
initiateResize(direction)(event)
|
||||
},
|
||||
[initiateResize],
|
||||
)
|
||||
|
||||
const handleResizeEnd = React.useCallback(() => {
|
||||
setActiveResizeHandle(null)
|
||||
}, [])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!isResizing) {
|
||||
handleResizeEnd()
|
||||
}
|
||||
}, [isResizing, handleResizeEnd])
|
||||
|
||||
React.useEffect(() => {
|
||||
const handleImage = async () => {
|
||||
const imageExtension = editor.options.extensions.find(
|
||||
(ext) => ext.name === "image",
|
||||
)
|
||||
const { uploadFn } = imageExtension?.options ?? {}
|
||||
|
||||
if (initialSrc.startsWith("blob:")) {
|
||||
if (!uploadFn) {
|
||||
try {
|
||||
const base64 = await blobUrlToBase64(initialSrc)
|
||||
setImageState((prev) => ({ ...prev, src: base64 }))
|
||||
updateAttributes({ src: base64 })
|
||||
} catch {
|
||||
setImageState((prev) => ({ ...prev, error: true }))
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
setImageState((prev) => ({ ...prev, isServerUploading: true }))
|
||||
const url = await uploadFn(initialSrc, editor)
|
||||
setImageState((prev) => ({
|
||||
...prev,
|
||||
src: url,
|
||||
isServerUploading: false,
|
||||
}))
|
||||
updateAttributes({ src: url })
|
||||
} catch {
|
||||
setImageState((prev) => ({
|
||||
...prev,
|
||||
error: true,
|
||||
isServerUploading: false,
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
handleImage()
|
||||
}, [editor, initialSrc, updateAttributes])
|
||||
|
||||
return (
|
||||
<NodeViewWrapper
|
||||
ref={containerRef}
|
||||
data-drag-handle
|
||||
className="relative text-center leading-none"
|
||||
>
|
||||
<div
|
||||
className="group/node-image relative mx-auto rounded-md object-contain"
|
||||
style={{
|
||||
maxWidth: `min(${maxWidth}px, 100%)`,
|
||||
width: currentWidth,
|
||||
maxHeight: MAX_HEIGHT,
|
||||
aspectRatio: `${imageState.naturalSize.width} / ${imageState.naturalSize.height}`,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"relative flex h-full cursor-default flex-col items-center gap-2 rounded",
|
||||
{
|
||||
"outline outline-2 outline-offset-1 outline-primary":
|
||||
selected || isResizing,
|
||||
},
|
||||
)}
|
||||
>
|
||||
<div className="h-full contain-paint">
|
||||
<div className="relative h-full">
|
||||
{!imageState.imageLoaded && !imageState.error && (
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<Spinner className="size-7" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{imageState.error && (
|
||||
<div className="absolute inset-0 flex flex-col items-center justify-center">
|
||||
<InfoCircledIcon className="size-8 text-destructive" />
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
Failed to load image
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ControlledZoom
|
||||
isZoomed={imageState.isZoomed}
|
||||
onZoomChange={() =>
|
||||
setImageState((prev) => ({ ...prev, isZoomed: false }))
|
||||
}
|
||||
>
|
||||
<img
|
||||
className={cn(
|
||||
"h-auto rounded object-contain transition-shadow",
|
||||
{
|
||||
"opacity-0": !imageState.imageLoaded || imageState.error,
|
||||
},
|
||||
)}
|
||||
style={{
|
||||
maxWidth: `min(100%, ${maxWidth}px)`,
|
||||
minWidth: `${MIN_WIDTH}px`,
|
||||
maxHeight: MAX_HEIGHT,
|
||||
}}
|
||||
width={currentWidth}
|
||||
height={currentHeight}
|
||||
src={imageState.src}
|
||||
onError={handleImageError}
|
||||
onLoad={handleImageLoad}
|
||||
alt={node.attrs.alt || ""}
|
||||
/>
|
||||
</ControlledZoom>
|
||||
</div>
|
||||
|
||||
{imageState.isServerUploading && <ImageOverlay />}
|
||||
|
||||
{editor.isEditable &&
|
||||
imageState.imageLoaded &&
|
||||
!imageState.error &&
|
||||
!imageState.isServerUploading && (
|
||||
<>
|
||||
<ResizeHandle
|
||||
onPointerDown={handleResizeStart("left")}
|
||||
className={cn("left-1", {
|
||||
hidden: isResizing && activeResizeHandle === "right",
|
||||
})}
|
||||
isResizing={isResizing && activeResizeHandle === "left"}
|
||||
/>
|
||||
<ResizeHandle
|
||||
onPointerDown={handleResizeStart("right")}
|
||||
className={cn("right-1", {
|
||||
hidden: isResizing && activeResizeHandle === "left",
|
||||
})}
|
||||
isResizing={isResizing && activeResizeHandle === "right"}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{imageState.error && (
|
||||
<ActionWrapper>
|
||||
<ActionButton
|
||||
icon={<TrashIcon className="size-4" />}
|
||||
tooltip="Remove image"
|
||||
onClick={onRemoveImg}
|
||||
/>
|
||||
</ActionWrapper>
|
||||
)}
|
||||
|
||||
{!isResizing &&
|
||||
!imageState.error &&
|
||||
!imageState.isServerUploading && (
|
||||
<ImageActions
|
||||
shouldMerge={shouldMerge}
|
||||
isLink={isLink}
|
||||
onView={onView}
|
||||
onDownload={onDownload}
|
||||
onCopy={onCopy}
|
||||
onCopyLink={onCopyLink}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</NodeViewWrapper>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
interface ResizeProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
isResizing?: boolean
|
||||
}
|
||||
|
||||
export const ResizeHandle = React.forwardRef<HTMLDivElement, ResizeProps>(
|
||||
({ className, isResizing = false, ...props }, ref) => {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"absolute top-1/2 h-10 max-h-full w-1.5 -translate-y-1/2 transform cursor-col-resize rounded border border-solid border-[var(--mt-transparent-foreground)] bg-[var(--mt-bg-secondary)] p-px transition-all",
|
||||
"opacity-0 [backdrop-filter:saturate(1.8)_blur(20px)]",
|
||||
{
|
||||
"opacity-80": isResizing,
|
||||
"group-hover/node-image:opacity-80": !isResizing,
|
||||
},
|
||||
"before:absolute before:inset-y-0 before:-left-1 before:-right-1",
|
||||
className,
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
></div>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
ResizeHandle.displayName = "ResizeHandle"
|
||||
171
web/shared/editor/extensions/image/hooks/use-drag-resize.ts
Normal file
171
web/shared/editor/extensions/image/hooks/use-drag-resize.ts
Normal file
@@ -0,0 +1,171 @@
|
||||
import { useState, useCallback, useEffect } from "react"
|
||||
|
||||
type ResizeDirection = "left" | "right"
|
||||
export type ElementDimensions = { width: number; height: number }
|
||||
|
||||
type HookParams = {
|
||||
initialWidth?: number
|
||||
initialHeight?: number
|
||||
contentWidth?: number
|
||||
contentHeight?: number
|
||||
gridInterval: number
|
||||
minWidth: number
|
||||
minHeight: number
|
||||
maxWidth: number
|
||||
onDimensionsChange?: (dimensions: ElementDimensions) => void
|
||||
}
|
||||
|
||||
export function useDragResize({
|
||||
initialWidth,
|
||||
initialHeight,
|
||||
contentWidth,
|
||||
contentHeight,
|
||||
gridInterval,
|
||||
minWidth,
|
||||
minHeight,
|
||||
maxWidth,
|
||||
onDimensionsChange,
|
||||
}: HookParams) {
|
||||
const [dimensions, updateDimensions] = useState<ElementDimensions>({
|
||||
width: Math.max(initialWidth ?? minWidth, minWidth),
|
||||
height: Math.max(initialHeight ?? minHeight, minHeight),
|
||||
})
|
||||
const [boundaryWidth, setBoundaryWidth] = useState(Infinity)
|
||||
const [resizeOrigin, setResizeOrigin] = useState(0)
|
||||
const [initialDimensions, setInitialDimensions] = useState(dimensions)
|
||||
const [resizeDirection, setResizeDirection] = useState<
|
||||
ResizeDirection | undefined
|
||||
>()
|
||||
|
||||
const widthConstraint = useCallback(
|
||||
(proposedWidth: number, maxAllowedWidth: number) => {
|
||||
const effectiveMinWidth = Math.max(
|
||||
minWidth,
|
||||
Math.min(
|
||||
contentWidth ?? minWidth,
|
||||
(gridInterval / 100) * maxAllowedWidth,
|
||||
),
|
||||
)
|
||||
return Math.min(
|
||||
maxAllowedWidth,
|
||||
Math.max(proposedWidth, effectiveMinWidth),
|
||||
)
|
||||
},
|
||||
[gridInterval, contentWidth, minWidth],
|
||||
)
|
||||
|
||||
const handlePointerMove = useCallback(
|
||||
(event: PointerEvent) => {
|
||||
event.preventDefault()
|
||||
const movementDelta =
|
||||
(resizeDirection === "left"
|
||||
? resizeOrigin - event.pageX
|
||||
: event.pageX - resizeOrigin) * 2
|
||||
const gridUnitWidth = (gridInterval / 100) * boundaryWidth
|
||||
const proposedWidth = initialDimensions.width + movementDelta
|
||||
const alignedWidth =
|
||||
Math.round(proposedWidth / gridUnitWidth) * gridUnitWidth
|
||||
const finalWidth = widthConstraint(alignedWidth, boundaryWidth)
|
||||
const aspectRatio =
|
||||
contentHeight && contentWidth ? contentHeight / contentWidth : 1
|
||||
|
||||
updateDimensions({
|
||||
width: Math.max(finalWidth, minWidth),
|
||||
height: Math.max(
|
||||
contentWidth
|
||||
? finalWidth * aspectRatio
|
||||
: (contentHeight ?? minHeight),
|
||||
minHeight,
|
||||
),
|
||||
})
|
||||
},
|
||||
[
|
||||
widthConstraint,
|
||||
resizeDirection,
|
||||
boundaryWidth,
|
||||
resizeOrigin,
|
||||
gridInterval,
|
||||
contentHeight,
|
||||
contentWidth,
|
||||
initialDimensions.width,
|
||||
minWidth,
|
||||
minHeight,
|
||||
],
|
||||
)
|
||||
|
||||
const handlePointerUp = useCallback(
|
||||
(event: PointerEvent) => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
|
||||
setResizeOrigin(0)
|
||||
setResizeDirection(undefined)
|
||||
onDimensionsChange?.(dimensions)
|
||||
},
|
||||
[onDimensionsChange, dimensions],
|
||||
)
|
||||
|
||||
const handleKeydown = useCallback(
|
||||
(event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
updateDimensions({
|
||||
width: Math.max(initialDimensions.width, minWidth),
|
||||
height: Math.max(initialDimensions.height, minHeight),
|
||||
})
|
||||
setResizeDirection(undefined)
|
||||
}
|
||||
},
|
||||
[initialDimensions, minWidth, minHeight],
|
||||
)
|
||||
|
||||
const initiateResize = useCallback(
|
||||
(direction: ResizeDirection) =>
|
||||
(event: React.PointerEvent<HTMLDivElement>) => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
|
||||
setBoundaryWidth(maxWidth)
|
||||
setInitialDimensions({
|
||||
width: Math.max(
|
||||
widthConstraint(dimensions.width, maxWidth),
|
||||
minWidth,
|
||||
),
|
||||
height: Math.max(dimensions.height, minHeight),
|
||||
})
|
||||
setResizeOrigin(event.pageX)
|
||||
setResizeDirection(direction)
|
||||
},
|
||||
[
|
||||
maxWidth,
|
||||
widthConstraint,
|
||||
dimensions.width,
|
||||
dimensions.height,
|
||||
minWidth,
|
||||
minHeight,
|
||||
],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (resizeDirection) {
|
||||
document.addEventListener("keydown", handleKeydown)
|
||||
document.addEventListener("pointermove", handlePointerMove)
|
||||
document.addEventListener("pointerup", handlePointerUp)
|
||||
|
||||
return () => {
|
||||
document.removeEventListener("keydown", handleKeydown)
|
||||
document.removeEventListener("pointermove", handlePointerMove)
|
||||
document.removeEventListener("pointerup", handlePointerUp)
|
||||
}
|
||||
}
|
||||
}, [resizeDirection, handleKeydown, handlePointerMove, handlePointerUp])
|
||||
|
||||
return {
|
||||
initiateResize,
|
||||
isResizing: !!resizeDirection,
|
||||
updateDimensions,
|
||||
currentWidth: Math.max(dimensions.width, minWidth),
|
||||
currentHeight: Math.max(dimensions.height, minHeight),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import * as React from "react"
|
||||
import type { Editor } from "@tiptap/core"
|
||||
import type { Node } from "@tiptap/pm/model"
|
||||
import { isUrl } from "@shared/editor/lib/utils"
|
||||
|
||||
interface UseImageActionsProps {
|
||||
editor: Editor
|
||||
node: Node
|
||||
src: string
|
||||
onViewClick: (value: boolean) => void
|
||||
}
|
||||
|
||||
export type ImageActionHandlers = {
|
||||
onView?: () => void
|
||||
onDownload?: () => void
|
||||
onCopy?: () => void
|
||||
onCopyLink?: () => void
|
||||
onRemoveImg?: () => void
|
||||
}
|
||||
|
||||
export const useImageActions = ({
|
||||
editor,
|
||||
node,
|
||||
src,
|
||||
onViewClick,
|
||||
}: UseImageActionsProps) => {
|
||||
const isLink = React.useMemo(() => isUrl(src), [src])
|
||||
|
||||
const onView = React.useCallback(() => {
|
||||
onViewClick(true)
|
||||
}, [onViewClick])
|
||||
|
||||
const onDownload = React.useCallback(() => {
|
||||
editor.commands.downloadImage({ src: node.attrs.src, alt: node.attrs.alt })
|
||||
}, [editor.commands, node.attrs.alt, node.attrs.src])
|
||||
|
||||
const onCopy = React.useCallback(() => {
|
||||
editor.commands.copyImage({ src: node.attrs.src })
|
||||
}, [editor.commands, node.attrs.src])
|
||||
|
||||
const onCopyLink = React.useCallback(() => {
|
||||
editor.commands.copyLink({ src: node.attrs.src })
|
||||
}, [editor.commands, node.attrs.src])
|
||||
|
||||
const onRemoveImg = React.useCallback(() => {
|
||||
editor.commands.command(({ tr, dispatch }) => {
|
||||
const { selection } = tr
|
||||
const nodeAtSelection = tr.doc.nodeAt(selection.from)
|
||||
|
||||
if (nodeAtSelection && nodeAtSelection.type.name === "image") {
|
||||
if (dispatch) {
|
||||
tr.deleteSelection()
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})
|
||||
}, [editor.commands])
|
||||
|
||||
return { isLink, onView, onDownload, onCopy, onCopyLink, onRemoveImg }
|
||||
}
|
||||
288
web/shared/editor/extensions/image/image.ts
Normal file
288
web/shared/editor/extensions/image/image.ts
Normal file
@@ -0,0 +1,288 @@
|
||||
import type { ImageOptions } from "@tiptap/extension-image"
|
||||
import { Image as TiptapImage } from "@tiptap/extension-image"
|
||||
import type { Editor } from "@tiptap/react"
|
||||
import { ReactNodeViewRenderer } from "@tiptap/react"
|
||||
import { ImageViewBlock } from "./components/image-view-block"
|
||||
import {
|
||||
filterFiles,
|
||||
sanitizeUrl,
|
||||
type FileError,
|
||||
type FileValidationOptions,
|
||||
} from "@shared/editor/lib/utils"
|
||||
|
||||
interface DownloadImageCommandProps {
|
||||
src: string
|
||||
alt?: string
|
||||
}
|
||||
|
||||
interface ImageActionProps {
|
||||
src: string
|
||||
alt?: string
|
||||
action: "download" | "copyImage" | "copyLink"
|
||||
}
|
||||
|
||||
interface CustomImageOptions
|
||||
extends ImageOptions,
|
||||
Omit<FileValidationOptions, "allowBase64"> {
|
||||
uploadFn?: (blobUrl: string, editor: Editor) => Promise<string>
|
||||
onToggle?: (editor: Editor, files: File[], pos: number) => void
|
||||
onActionSuccess?: (props: ImageActionProps) => void
|
||||
onActionError?: (error: Error, props: ImageActionProps) => void
|
||||
customDownloadImage?: (
|
||||
props: ImageActionProps,
|
||||
options: CustomImageOptions,
|
||||
) => void
|
||||
customCopyImage?: (
|
||||
props: ImageActionProps,
|
||||
options: CustomImageOptions,
|
||||
) => void
|
||||
customCopyLink?: (
|
||||
props: ImageActionProps,
|
||||
options: CustomImageOptions,
|
||||
) => void
|
||||
onValidationError?: (errors: FileError[]) => void
|
||||
}
|
||||
|
||||
declare module "@tiptap/core" {
|
||||
interface Commands<ReturnType> {
|
||||
toggleImage: {
|
||||
toggleImage: () => ReturnType
|
||||
}
|
||||
setImages: {
|
||||
setImages: (
|
||||
attrs: { src: string | File; alt?: string; title?: string }[],
|
||||
) => ReturnType
|
||||
}
|
||||
downloadImage: {
|
||||
downloadImage: (attrs: DownloadImageCommandProps) => ReturnType
|
||||
}
|
||||
copyImage: {
|
||||
copyImage: (attrs: DownloadImageCommandProps) => ReturnType
|
||||
}
|
||||
copyLink: {
|
||||
copyLink: (attrs: DownloadImageCommandProps) => ReturnType
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleError = (
|
||||
error: unknown,
|
||||
props: ImageActionProps,
|
||||
errorHandler?: (error: Error, props: ImageActionProps) => void,
|
||||
) => {
|
||||
const typedError = error instanceof Error ? error : new Error("Unknown error")
|
||||
errorHandler?.(typedError, props)
|
||||
}
|
||||
|
||||
const handleDataUrl = (src: string): { blob: Blob; extension: string } => {
|
||||
const [header, base64Data] = src.split(",")
|
||||
const mimeType = header.split(":")[1].split(";")[0]
|
||||
const extension = mimeType.split("/")[1]
|
||||
const byteCharacters = atob(base64Data)
|
||||
const byteArray = new Uint8Array(byteCharacters.length)
|
||||
for (let i = 0; i < byteCharacters.length; i++) {
|
||||
byteArray[i] = byteCharacters.charCodeAt(i)
|
||||
}
|
||||
const blob = new Blob([byteArray], { type: mimeType })
|
||||
return { blob, extension }
|
||||
}
|
||||
|
||||
const handleImageUrl = async (
|
||||
src: string,
|
||||
): Promise<{ blob: Blob; extension: string }> => {
|
||||
const response = await fetch(src)
|
||||
if (!response.ok) throw new Error("Failed to fetch image")
|
||||
const blob = await response.blob()
|
||||
const extension = blob.type.split(/\/|\+/)[1]
|
||||
return { blob, extension }
|
||||
}
|
||||
|
||||
const fetchImageBlob = async (
|
||||
src: string,
|
||||
): Promise<{ blob: Blob; extension: string }> => {
|
||||
if (src.startsWith("data:")) {
|
||||
return handleDataUrl(src)
|
||||
} else {
|
||||
return handleImageUrl(src)
|
||||
}
|
||||
}
|
||||
|
||||
const saveImage = async (
|
||||
blob: Blob,
|
||||
name: string,
|
||||
extension: string,
|
||||
): Promise<void> => {
|
||||
const imageURL = URL.createObjectURL(blob)
|
||||
const link = document.createElement("a")
|
||||
link.href = imageURL
|
||||
link.download = `${name}.${extension}`
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
URL.revokeObjectURL(imageURL)
|
||||
}
|
||||
|
||||
const defaultDownloadImage = async (
|
||||
props: ImageActionProps,
|
||||
options: CustomImageOptions,
|
||||
): Promise<void> => {
|
||||
const { src, alt } = props
|
||||
const potentialName = alt || "image"
|
||||
|
||||
try {
|
||||
const { blob, extension } = await fetchImageBlob(src)
|
||||
await saveImage(blob, potentialName, extension)
|
||||
options.onActionSuccess?.({ ...props, action: "download" })
|
||||
} catch (error) {
|
||||
handleError(error, { ...props, action: "download" }, options.onActionError)
|
||||
}
|
||||
}
|
||||
|
||||
const defaultCopyImage = async (
|
||||
props: ImageActionProps,
|
||||
options: CustomImageOptions,
|
||||
) => {
|
||||
const { src } = props
|
||||
try {
|
||||
const res = await fetch(src)
|
||||
const blob = await res.blob()
|
||||
await navigator.clipboard.write([new ClipboardItem({ [blob.type]: blob })])
|
||||
options.onActionSuccess?.({ ...props, action: "copyImage" })
|
||||
} catch (error) {
|
||||
handleError(error, { ...props, action: "copyImage" }, options.onActionError)
|
||||
}
|
||||
}
|
||||
|
||||
const defaultCopyLink = async (
|
||||
props: ImageActionProps,
|
||||
options: CustomImageOptions,
|
||||
) => {
|
||||
const { src } = props
|
||||
try {
|
||||
await navigator.clipboard.writeText(src)
|
||||
options.onActionSuccess?.({ ...props, action: "copyLink" })
|
||||
} catch (error) {
|
||||
handleError(error, { ...props, action: "copyLink" }, options.onActionError)
|
||||
}
|
||||
}
|
||||
|
||||
export const Image = TiptapImage.extend<CustomImageOptions>({
|
||||
atom: true,
|
||||
|
||||
addOptions() {
|
||||
return {
|
||||
...this.parent?.(),
|
||||
allowedMimeTypes: [],
|
||||
maxFileSize: 0,
|
||||
uploadFn: undefined,
|
||||
onToggle: undefined,
|
||||
}
|
||||
},
|
||||
|
||||
addAttributes() {
|
||||
return {
|
||||
...this.parent?.(),
|
||||
width: {
|
||||
default: undefined,
|
||||
},
|
||||
height: {
|
||||
default: undefined,
|
||||
},
|
||||
}
|
||||
},
|
||||
|
||||
addCommands() {
|
||||
return {
|
||||
toggleImage: () => (props) => {
|
||||
const input = document.createElement("input")
|
||||
input.type = "file"
|
||||
input.accept = this.options.allowedMimeTypes.join(",")
|
||||
input.onchange = () => {
|
||||
const files = input.files
|
||||
if (!files) return
|
||||
|
||||
const [validImages, errors] = filterFiles(Array.from(files), {
|
||||
allowedMimeTypes: this.options.allowedMimeTypes,
|
||||
maxFileSize: this.options.maxFileSize,
|
||||
allowBase64: this.options.allowBase64,
|
||||
})
|
||||
|
||||
if (errors.length > 0 && this.options.onValidationError) {
|
||||
this.options.onValidationError(errors)
|
||||
return false
|
||||
}
|
||||
|
||||
if (validImages.length === 0) return false
|
||||
|
||||
if (this.options.onToggle) {
|
||||
this.options.onToggle(
|
||||
props.editor,
|
||||
validImages,
|
||||
props.editor.state.selection.from,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
input.click()
|
||||
return true
|
||||
},
|
||||
setImages:
|
||||
(attrs) =>
|
||||
({ commands }) => {
|
||||
const [validImages, errors] = filterFiles(attrs, {
|
||||
allowedMimeTypes: this.options.allowedMimeTypes,
|
||||
maxFileSize: this.options.maxFileSize,
|
||||
allowBase64: this.options.allowBase64,
|
||||
})
|
||||
|
||||
if (errors.length > 0 && this.options.onValidationError) {
|
||||
this.options.onValidationError(errors)
|
||||
}
|
||||
|
||||
if (validImages.length > 0) {
|
||||
return commands.insertContent(
|
||||
validImages.map((image) => {
|
||||
return {
|
||||
type: this.name,
|
||||
attrs: {
|
||||
src:
|
||||
image.src instanceof File
|
||||
? sanitizeUrl(URL.createObjectURL(image.src), {
|
||||
allowBase64: this.options.allowBase64,
|
||||
})
|
||||
: image.src,
|
||||
alt: image.alt,
|
||||
title: image.title,
|
||||
},
|
||||
}
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
return false
|
||||
},
|
||||
downloadImage: (attrs) => () => {
|
||||
const downloadFunc =
|
||||
this.options.customDownloadImage || defaultDownloadImage
|
||||
void downloadFunc({ ...attrs, action: "download" }, this.options)
|
||||
return true
|
||||
},
|
||||
copyImage: (attrs) => () => {
|
||||
const copyImageFunc = this.options.customCopyImage || defaultCopyImage
|
||||
void copyImageFunc({ ...attrs, action: "copyImage" }, this.options)
|
||||
return true
|
||||
},
|
||||
copyLink: (attrs) => () => {
|
||||
const copyLinkFunc = this.options.customCopyLink || defaultCopyLink
|
||||
void copyLinkFunc({ ...attrs, action: "copyLink" }, this.options)
|
||||
return true
|
||||
},
|
||||
}
|
||||
},
|
||||
|
||||
addNodeView() {
|
||||
return ReactNodeViewRenderer(ImageViewBlock, {
|
||||
className: "block-node",
|
||||
})
|
||||
},
|
||||
})
|
||||
1
web/shared/editor/extensions/image/index.ts
Normal file
1
web/shared/editor/extensions/image/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from "./image"
|
||||
Reference in New Issue
Block a user