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:
37
web/shared/components/spinner.tsx
Normal file
37
web/shared/components/spinner.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
interface SpinnerProps extends React.SVGProps<SVGSVGElement> {}
|
||||
|
||||
const SpinnerComponent = React.forwardRef<SVGSVGElement, SpinnerProps>(
|
||||
function Spinner({ className, ...props }, ref) {
|
||||
return (
|
||||
<svg
|
||||
ref={ref}
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
className={cn("animate-spin", className)}
|
||||
{...props}
|
||||
>
|
||||
<circle
|
||||
className="opacity-25"
|
||||
cx="12"
|
||||
cy="12"
|
||||
r="10"
|
||||
stroke="currentColor"
|
||||
strokeWidth="4"
|
||||
></circle>
|
||||
<path
|
||||
className="opacity-75"
|
||||
fill="currentColor"
|
||||
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
|
||||
></path>
|
||||
</svg>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
SpinnerComponent.displayName = "Spinner"
|
||||
|
||||
export const Spinner = React.memo(SpinnerComponent)
|
||||
90
web/shared/editor/components/bubble-menu/bubble-menu.tsx
Normal file
90
web/shared/editor/components/bubble-menu/bubble-menu.tsx
Normal file
@@ -0,0 +1,90 @@
|
||||
import { useTextmenuCommands } from "../../hooks/use-text-menu-commands"
|
||||
import { PopoverWrapper } from "../ui/popover-wrapper"
|
||||
import { useTextmenuStates } from "../../hooks/use-text-menu-states"
|
||||
import { BubbleMenu as TiptapBubbleMenu, Editor } from "@tiptap/react"
|
||||
import { ToolbarButton } from "../ui/toolbar-button"
|
||||
import { Icon } from "../ui/icon"
|
||||
|
||||
export type BubbleMenuProps = {
|
||||
editor: Editor
|
||||
}
|
||||
|
||||
export const BubbleMenu = ({ editor }: BubbleMenuProps) => {
|
||||
const commands = useTextmenuCommands(editor)
|
||||
const states = useTextmenuStates(editor)
|
||||
|
||||
return (
|
||||
<TiptapBubbleMenu
|
||||
tippyOptions={{
|
||||
// duration: [0, 999999],
|
||||
popperOptions: { placement: "top-start" },
|
||||
}}
|
||||
editor={editor}
|
||||
pluginKey="textMenu"
|
||||
shouldShow={states.shouldShow}
|
||||
updateDelay={100}
|
||||
>
|
||||
<PopoverWrapper>
|
||||
<div className="flex space-x-1">
|
||||
<ToolbarButton
|
||||
value="bold"
|
||||
aria-label="Bold"
|
||||
onPressedChange={commands.onBold}
|
||||
isActive={states.isBold}
|
||||
>
|
||||
<Icon name="Bold" strokeWidth={2.5} />
|
||||
</ToolbarButton>
|
||||
|
||||
<ToolbarButton
|
||||
value="italic"
|
||||
aria-label="Italic"
|
||||
onClick={commands.onItalic}
|
||||
isActive={states.isItalic}
|
||||
>
|
||||
<Icon name="Italic" strokeWidth={2.5} />
|
||||
</ToolbarButton>
|
||||
|
||||
<ToolbarButton
|
||||
value="strikethrough"
|
||||
aria-label="Strikethrough"
|
||||
onClick={commands.onStrike}
|
||||
isActive={states.isStrike}
|
||||
>
|
||||
<Icon name="Strikethrough" strokeWidth={2.5} />
|
||||
</ToolbarButton>
|
||||
|
||||
<ToolbarButton
|
||||
value="quote"
|
||||
aria-label="Quote"
|
||||
onClick={commands.onCode}
|
||||
isActive={states.isCode}
|
||||
>
|
||||
<Icon name="Quote" strokeWidth={2.5} />
|
||||
</ToolbarButton>
|
||||
|
||||
<ToolbarButton
|
||||
value="inline code"
|
||||
aria-label="Inline code"
|
||||
onClick={commands.onCode}
|
||||
isActive={states.isCode}
|
||||
>
|
||||
<Icon name="Braces" strokeWidth={2.5} />
|
||||
</ToolbarButton>
|
||||
|
||||
<ToolbarButton
|
||||
value="code block"
|
||||
aria-label="Code block"
|
||||
onClick={commands.onCodeBlock}
|
||||
>
|
||||
<Icon name="Code" strokeWidth={2.5} />
|
||||
</ToolbarButton>
|
||||
{/* <ToolbarButton value="list" aria-label="List">
|
||||
<Icon name="List" strokeWidth={2.5} />
|
||||
</ToolbarButton> */}
|
||||
</div>
|
||||
</PopoverWrapper>
|
||||
</TiptapBubbleMenu>
|
||||
)
|
||||
}
|
||||
|
||||
export default BubbleMenu
|
||||
@@ -10,7 +10,7 @@ export const PopoverWrapper = React.forwardRef<
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground rounded-lg border shadow-sm",
|
||||
"rounded-lg border bg-popover text-popover-foreground shadow-sm",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { getShortcutKey } from "@/lib/utils"
|
||||
import { getShortcutKey } from "@shared/utils"
|
||||
|
||||
export interface ShortcutKeyWrapperProps
|
||||
extends React.HTMLAttributes<HTMLSpanElement> {
|
||||
43
web/shared/editor/editor.tsx
Normal file
43
web/shared/editor/editor.tsx
Normal file
@@ -0,0 +1,43 @@
|
||||
import * as React from "react"
|
||||
import "./styles/index.css"
|
||||
|
||||
import { EditorContent } from "@tiptap/react"
|
||||
import { Content } from "@tiptap/core"
|
||||
import { BubbleMenu } from "./components/bubble-menu"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { useLaEditor, UseLaEditorProps } from "./hooks/use-la-editor"
|
||||
|
||||
export interface LaEditorProps extends UseLaEditorProps {
|
||||
value?: Content
|
||||
className?: string
|
||||
editorContentClassName?: string
|
||||
}
|
||||
|
||||
export const LaEditor = React.memo(
|
||||
React.forwardRef<HTMLDivElement, LaEditorProps>(
|
||||
({ className, editorContentClassName, ...props }, ref) => {
|
||||
const editor = useLaEditor(props)
|
||||
|
||||
if (!editor) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn("relative flex h-full w-full grow flex-col", className)}
|
||||
ref={ref}
|
||||
>
|
||||
<EditorContent
|
||||
editor={editor}
|
||||
className={cn("la-editor", editorContentClassName)}
|
||||
/>
|
||||
<BubbleMenu editor={editor} />
|
||||
</div>
|
||||
)
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
LaEditor.displayName = "LaEditor"
|
||||
|
||||
export default LaEditor
|
||||
116
web/shared/editor/extensions/file-handler/index.ts
Normal file
116
web/shared/editor/extensions/file-handler/index.ts
Normal file
@@ -0,0 +1,116 @@
|
||||
import { type Editor, Extension } from "@tiptap/core"
|
||||
import { Plugin, PluginKey } from "@tiptap/pm/state"
|
||||
import type { FileError, FileValidationOptions } from "@shared/editor/lib/utils"
|
||||
import { filterFiles } from "@shared/editor/lib/utils"
|
||||
|
||||
type FileHandlePluginOptions = {
|
||||
key?: PluginKey
|
||||
editor: Editor
|
||||
onPaste?: (editor: Editor, files: File[], pasteContent?: string) => void
|
||||
onDrop?: (editor: Editor, files: File[], pos: number) => void
|
||||
onValidationError?: (errors: FileError[]) => void
|
||||
} & FileValidationOptions
|
||||
|
||||
const FileHandlePlugin = (options: FileHandlePluginOptions) => {
|
||||
const {
|
||||
key,
|
||||
editor,
|
||||
onPaste,
|
||||
onDrop,
|
||||
onValidationError,
|
||||
allowedMimeTypes,
|
||||
maxFileSize,
|
||||
} = options
|
||||
|
||||
return new Plugin({
|
||||
key: key || new PluginKey("fileHandler"),
|
||||
|
||||
props: {
|
||||
handleDrop(view, event) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
|
||||
const { dataTransfer } = event
|
||||
|
||||
if (!dataTransfer?.files.length) {
|
||||
return
|
||||
}
|
||||
|
||||
const pos = view.posAtCoords({
|
||||
left: event.clientX,
|
||||
top: event.clientY,
|
||||
})
|
||||
|
||||
const [validFiles, errors] = filterFiles(
|
||||
Array.from(dataTransfer.files),
|
||||
{
|
||||
allowedMimeTypes,
|
||||
maxFileSize,
|
||||
allowBase64: options.allowBase64,
|
||||
},
|
||||
)
|
||||
|
||||
if (errors.length > 0 && onValidationError) {
|
||||
onValidationError(errors)
|
||||
}
|
||||
|
||||
if (validFiles.length > 0 && onDrop) {
|
||||
onDrop(editor, validFiles, pos?.pos ?? 0)
|
||||
}
|
||||
},
|
||||
|
||||
handlePaste(_, event) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
|
||||
const { clipboardData } = event
|
||||
|
||||
if (!clipboardData?.files.length) {
|
||||
return
|
||||
}
|
||||
|
||||
const [validFiles, errors] = filterFiles(
|
||||
Array.from(clipboardData.files),
|
||||
{
|
||||
allowedMimeTypes,
|
||||
maxFileSize,
|
||||
allowBase64: options.allowBase64,
|
||||
},
|
||||
)
|
||||
const html = clipboardData.getData("text/html")
|
||||
|
||||
if (errors.length > 0 && onValidationError) {
|
||||
onValidationError(errors)
|
||||
}
|
||||
|
||||
if (validFiles.length > 0 && onPaste) {
|
||||
onPaste(editor, validFiles, html)
|
||||
}
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export const FileHandler = Extension.create<
|
||||
Omit<FileHandlePluginOptions, "key" | "editor">
|
||||
>({
|
||||
name: "fileHandler",
|
||||
|
||||
addOptions() {
|
||||
return {
|
||||
allowBase64: false,
|
||||
allowedMimeTypes: [],
|
||||
maxFileSize: 0,
|
||||
}
|
||||
},
|
||||
|
||||
addProseMirrorPlugins() {
|
||||
return [
|
||||
FileHandlePlugin({
|
||||
key: new PluginKey(this.name),
|
||||
editor: this.editor,
|
||||
...this.options,
|
||||
}),
|
||||
]
|
||||
},
|
||||
})
|
||||
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"
|
||||
@@ -83,6 +83,17 @@ export const GROUPS: Group[] = [
|
||||
name: "insert",
|
||||
title: "Insert",
|
||||
commands: [
|
||||
{
|
||||
name: "image",
|
||||
label: "Image",
|
||||
iconName: "Image",
|
||||
description: "Insert an image",
|
||||
shortcuts: ["mod", "shift", "i"],
|
||||
aliases: ["img"],
|
||||
action: (editor) => {
|
||||
editor.chain().focus().toggleImage().run()
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "codeBlock",
|
||||
label: "Code Block",
|
||||
@@ -6,10 +6,10 @@ import { Button } from "@/components/ui/button"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
|
||||
import { Command, MenuListProps } from "./types"
|
||||
import { getShortcutKeys } from "@/lib/utils"
|
||||
import { Icon } from "../../components/ui/icon"
|
||||
import { PopoverWrapper } from "../../components/ui/popover-wrapper"
|
||||
import { Shortcut } from "../../components/ui/shortcut"
|
||||
import { getShortcutKeys } from "@shared/utils"
|
||||
|
||||
export const MenuList = React.forwardRef((props: MenuListProps, ref) => {
|
||||
const scrollContainer = React.useRef<HTMLDivElement>(null)
|
||||
254
web/shared/editor/hooks/use-la-editor.ts
Normal file
254
web/shared/editor/hooks/use-la-editor.ts
Normal file
@@ -0,0 +1,254 @@
|
||||
import * as React from "react"
|
||||
import type { Editor } from "@tiptap/core"
|
||||
import type { Content, EditorOptions, UseEditorOptions } from "@tiptap/react"
|
||||
import { useEditor } from "@tiptap/react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { useThrottleCallback } from "@shared/hooks/use-throttle-callback"
|
||||
import { getOutput } from "@shared/editor/lib/utils"
|
||||
import { StarterKit } from "@shared/editor/extensions/starter-kit"
|
||||
import { TaskList } from "@shared/editor/extensions/task-list"
|
||||
import { TaskItem } from "@shared/editor/extensions/task-item"
|
||||
import { HorizontalRule } from "@shared/editor/extensions/horizontal-rule"
|
||||
import { Blockquote } from "@shared/editor/extensions/blockquote/blockquote"
|
||||
import { SlashCommand } from "@shared/editor/extensions/slash-command"
|
||||
import { Heading } from "@shared/editor/extensions/heading"
|
||||
import { Link } from "@shared/editor/extensions/link"
|
||||
import { CodeBlockLowlight } from "@shared/editor/extensions/code-block-lowlight"
|
||||
import { Selection } from "@shared/editor/extensions/selection"
|
||||
import { Code } from "@shared/editor/extensions/code"
|
||||
import { Paragraph } from "@shared/editor/extensions/paragraph"
|
||||
import { BulletList } from "@shared/editor/extensions/bullet-list"
|
||||
import { OrderedList } from "@shared/editor/extensions/ordered-list"
|
||||
import { Dropcursor } from "@shared/editor/extensions/dropcursor"
|
||||
import { Image } from "../extensions/image"
|
||||
import { FileHandler } from "../extensions/file-handler"
|
||||
import { toast } from "sonner"
|
||||
import { useAccount } from "~/lib/providers/jazz-provider"
|
||||
import { ImageLists } from "~/lib/schema/folder"
|
||||
import { LaAccount, Image as LaImage } from "~/lib/schema"
|
||||
import { storeImageFn } from "@shared/actions"
|
||||
|
||||
export interface UseLaEditorProps
|
||||
extends Omit<UseEditorOptions, "editorProps"> {
|
||||
value?: Content
|
||||
output?: "html" | "json" | "text"
|
||||
placeholder?: string
|
||||
editorClassName?: string
|
||||
throttleDelay?: number
|
||||
onUpdate?: (content: Content) => void
|
||||
onBlur?: (content: Content) => void
|
||||
editorProps?: EditorOptions["editorProps"]
|
||||
}
|
||||
|
||||
const createExtensions = ({
|
||||
me,
|
||||
placeholder,
|
||||
}: {
|
||||
me?: LaAccount
|
||||
placeholder: string
|
||||
}) => [
|
||||
Heading,
|
||||
Code,
|
||||
Link,
|
||||
TaskList,
|
||||
TaskItem,
|
||||
Selection,
|
||||
Paragraph,
|
||||
Image.configure({
|
||||
allowedMimeTypes: ["image/*"],
|
||||
maxFileSize: 5 * 1024 * 1024,
|
||||
allowBase64: true,
|
||||
uploadFn: async (blobUrl) => {
|
||||
const uniqueId = Math.random().toString(36).substring(7)
|
||||
const response = await fetch(blobUrl)
|
||||
const blob = await response.blob()
|
||||
|
||||
const file = new File([blob], `${uniqueId}`, { type: blob.type })
|
||||
|
||||
const formData = new FormData()
|
||||
formData.append("file", file)
|
||||
|
||||
const store = await storeImageFn(formData)
|
||||
|
||||
if (me) {
|
||||
if (!me.root?.images) {
|
||||
me.root!.images = ImageLists.create([], { owner: me })
|
||||
}
|
||||
|
||||
const img = LaImage.create(
|
||||
{
|
||||
url: store.fileModel.content.src,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
{ owner: me },
|
||||
)
|
||||
|
||||
me.root!.images.push(img)
|
||||
}
|
||||
|
||||
return store.fileModel.content.src
|
||||
},
|
||||
onToggle(editor, files, pos) {
|
||||
files.forEach((file) =>
|
||||
editor.commands.insertContentAt(pos, {
|
||||
type: "image",
|
||||
attrs: { src: URL.createObjectURL(file) },
|
||||
}),
|
||||
)
|
||||
},
|
||||
onValidationError(errors) {
|
||||
errors.forEach((error) => {
|
||||
toast.error("Image validation error", {
|
||||
position: "bottom-right",
|
||||
description: error.reason,
|
||||
})
|
||||
})
|
||||
},
|
||||
onActionSuccess({ action }) {
|
||||
const mapping = {
|
||||
copyImage: "Copy Image",
|
||||
copyLink: "Copy Link",
|
||||
download: "Download",
|
||||
}
|
||||
toast.success(mapping[action], {
|
||||
position: "bottom-right",
|
||||
description: "Image action success",
|
||||
})
|
||||
},
|
||||
onActionError(error, { action }) {
|
||||
const mapping = {
|
||||
copyImage: "Copy Image",
|
||||
copyLink: "Copy Link",
|
||||
download: "Download",
|
||||
}
|
||||
toast.error(`Failed to ${mapping[action]}`, {
|
||||
position: "bottom-right",
|
||||
description: error.message,
|
||||
})
|
||||
},
|
||||
}),
|
||||
FileHandler.configure({
|
||||
allowBase64: true,
|
||||
allowedMimeTypes: ["image/*"],
|
||||
maxFileSize: 5 * 1024 * 1024,
|
||||
onDrop: (editor, files, pos) => {
|
||||
files.forEach((file) =>
|
||||
editor.commands.insertContentAt(pos, {
|
||||
type: "image",
|
||||
attrs: { src: URL.createObjectURL(file) },
|
||||
}),
|
||||
)
|
||||
},
|
||||
onPaste: (editor, files) => {
|
||||
files.forEach((file) =>
|
||||
editor.commands.insertContent({
|
||||
type: "image",
|
||||
attrs: { src: URL.createObjectURL(file) },
|
||||
}),
|
||||
)
|
||||
},
|
||||
onValidationError: (errors) => {
|
||||
errors.forEach((error) => {
|
||||
console.log("File validation error", error)
|
||||
})
|
||||
},
|
||||
}),
|
||||
Dropcursor,
|
||||
Blockquote,
|
||||
BulletList,
|
||||
OrderedList,
|
||||
SlashCommand,
|
||||
HorizontalRule,
|
||||
CodeBlockLowlight,
|
||||
StarterKit.configure({
|
||||
placeholder: {
|
||||
placeholder: () => placeholder,
|
||||
},
|
||||
}),
|
||||
]
|
||||
|
||||
export const useLaEditor = ({
|
||||
value,
|
||||
output = "html",
|
||||
placeholder = "",
|
||||
editorClassName,
|
||||
throttleDelay = 0,
|
||||
onUpdate,
|
||||
onBlur,
|
||||
editorProps,
|
||||
...props
|
||||
}: UseLaEditorProps) => {
|
||||
const { me } = useAccount({ root: { images: [] } })
|
||||
|
||||
const throttledSetValue = useThrottleCallback(
|
||||
(editor: Editor) => {
|
||||
const content = getOutput(editor, output)
|
||||
onUpdate?.(content)
|
||||
},
|
||||
[output, onUpdate],
|
||||
throttleDelay,
|
||||
)
|
||||
|
||||
const handleCreate = React.useCallback(
|
||||
(editor: Editor) => {
|
||||
if (value) {
|
||||
editor.commands.setContent(value)
|
||||
}
|
||||
},
|
||||
[value],
|
||||
)
|
||||
|
||||
const handleBlur = React.useCallback(
|
||||
(editor: Editor) => {
|
||||
const content = getOutput(editor, output)
|
||||
onBlur?.(content)
|
||||
},
|
||||
[output, onBlur],
|
||||
)
|
||||
|
||||
const mergedEditorProps = React.useMemo(() => {
|
||||
const defaultEditorProps: EditorOptions["editorProps"] = {
|
||||
attributes: {
|
||||
autocomplete: "off",
|
||||
autocorrect: "off",
|
||||
autocapitalize: "off",
|
||||
class: cn("focus:outline-none", editorClassName),
|
||||
},
|
||||
}
|
||||
|
||||
if (!editorProps) return defaultEditorProps
|
||||
|
||||
return {
|
||||
...defaultEditorProps,
|
||||
...editorProps,
|
||||
attributes: {
|
||||
...defaultEditorProps.attributes,
|
||||
...editorProps.attributes,
|
||||
},
|
||||
}
|
||||
}, [editorProps, editorClassName])
|
||||
|
||||
const editorOptions: UseEditorOptions = React.useMemo(
|
||||
() => ({
|
||||
extensions: createExtensions({ me, placeholder }),
|
||||
editorProps: mergedEditorProps,
|
||||
onUpdate: ({ editor }) => throttledSetValue(editor),
|
||||
onCreate: ({ editor }) => handleCreate(editor),
|
||||
onBlur: ({ editor }) => handleBlur(editor),
|
||||
...props,
|
||||
}),
|
||||
[
|
||||
placeholder,
|
||||
mergedEditorProps,
|
||||
throttledSetValue,
|
||||
handleCreate,
|
||||
handleBlur,
|
||||
props,
|
||||
],
|
||||
)
|
||||
|
||||
return useEditor(editorOptions)
|
||||
}
|
||||
|
||||
export default useLaEditor
|
||||
1
web/shared/editor/index.ts
Normal file
1
web/shared/editor/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from "./editor"
|
||||
187
web/shared/editor/lib/utils/index.ts
Normal file
187
web/shared/editor/lib/utils/index.ts
Normal file
@@ -0,0 +1,187 @@
|
||||
import { LaEditorProps } from "@shared/editor"
|
||||
import { Editor } from "@tiptap/core"
|
||||
|
||||
export function getOutput(editor: Editor, format: LaEditorProps["output"]) {
|
||||
if (format === "json") {
|
||||
return editor.getJSON()
|
||||
}
|
||||
|
||||
if (format === "html") {
|
||||
return editor.getText() ? editor.getHTML() : ""
|
||||
}
|
||||
|
||||
return editor.getText()
|
||||
}
|
||||
|
||||
export type FileError = {
|
||||
file: File | string
|
||||
reason: "type" | "size" | "invalidBase64" | "base64NotAllowed"
|
||||
}
|
||||
|
||||
export type FileValidationOptions = {
|
||||
allowedMimeTypes: string[]
|
||||
maxFileSize?: number
|
||||
allowBase64: boolean
|
||||
}
|
||||
|
||||
type FileInput = File | { src: string | File; alt?: string; title?: string }
|
||||
|
||||
// URL validation and sanitization
|
||||
export const isUrl = (
|
||||
text: string,
|
||||
options?: { requireHostname: boolean; allowBase64?: boolean },
|
||||
): boolean => {
|
||||
if (text.match(/\n/)) return false
|
||||
|
||||
try {
|
||||
const url = new URL(text)
|
||||
const blockedProtocols = [
|
||||
"javascript:",
|
||||
"file:",
|
||||
"vbscript:",
|
||||
...(options?.allowBase64 ? [] : ["data:"]),
|
||||
]
|
||||
|
||||
if (blockedProtocols.includes(url.protocol)) return false
|
||||
if (options?.allowBase64 && url.protocol === "data:")
|
||||
return /^data:image\/[a-z]+;base64,/.test(text)
|
||||
if (url.hostname) return true
|
||||
|
||||
return (
|
||||
url.protocol !== "" &&
|
||||
(url.pathname.startsWith("//") || url.pathname.startsWith("http")) &&
|
||||
!options?.requireHostname
|
||||
)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export const sanitizeUrl = (
|
||||
url: string | null | undefined,
|
||||
options?: { allowBase64?: boolean },
|
||||
): string | undefined => {
|
||||
if (!url) return undefined
|
||||
|
||||
if (options?.allowBase64 && url.startsWith("data:image")) {
|
||||
return isUrl(url, { requireHostname: false, allowBase64: true })
|
||||
? url
|
||||
: undefined
|
||||
}
|
||||
|
||||
const isValidUrl = isUrl(url, {
|
||||
requireHostname: false,
|
||||
allowBase64: options?.allowBase64,
|
||||
})
|
||||
const isSpecialProtocol = /^(\/|#|mailto:|sms:|fax:|tel:)/.test(url)
|
||||
|
||||
return isValidUrl || isSpecialProtocol ? url : `https://${url}`
|
||||
}
|
||||
|
||||
// File handling
|
||||
export async function blobUrlToBase64(blobUrl: string): Promise<string> {
|
||||
const response = await fetch(blobUrl)
|
||||
const blob = await response.blob()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader()
|
||||
reader.onloadend = () => {
|
||||
if (typeof reader.result === "string") {
|
||||
resolve(reader.result)
|
||||
} else {
|
||||
reject(new Error("Failed to convert Blob to base64"))
|
||||
}
|
||||
}
|
||||
reader.onerror = reject
|
||||
reader.readAsDataURL(blob)
|
||||
})
|
||||
}
|
||||
|
||||
const validateFileOrBase64 = <T extends FileInput>(
|
||||
input: File | string,
|
||||
options: FileValidationOptions,
|
||||
originalFile: T,
|
||||
validFiles: T[],
|
||||
errors: FileError[],
|
||||
) => {
|
||||
const { isValidType, isValidSize } = checkTypeAndSize(input, options)
|
||||
|
||||
if (isValidType && isValidSize) {
|
||||
validFiles.push(originalFile)
|
||||
} else {
|
||||
if (!isValidType) errors.push({ file: input, reason: "type" })
|
||||
if (!isValidSize) errors.push({ file: input, reason: "size" })
|
||||
}
|
||||
}
|
||||
|
||||
const checkTypeAndSize = (
|
||||
input: File | string,
|
||||
{ allowedMimeTypes, maxFileSize }: FileValidationOptions,
|
||||
) => {
|
||||
const mimeType = input instanceof File ? input.type : base64MimeType(input)
|
||||
const size =
|
||||
input instanceof File ? input.size : atob(input.split(",")[1]).length
|
||||
|
||||
const isValidType =
|
||||
allowedMimeTypes.length === 0 ||
|
||||
allowedMimeTypes.includes(mimeType) ||
|
||||
allowedMimeTypes.includes(`${mimeType.split("/")[0]}/*`)
|
||||
|
||||
const isValidSize = !maxFileSize || size <= maxFileSize
|
||||
|
||||
return { isValidType, isValidSize }
|
||||
}
|
||||
|
||||
const base64MimeType = (encoded: string): string => {
|
||||
const result = encoded.match(/data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,.*/)
|
||||
return result && result.length ? result[1] : "unknown"
|
||||
}
|
||||
|
||||
const isBase64 = (str: string): boolean => {
|
||||
if (str.startsWith("data:")) {
|
||||
const matches = str.match(/^data:[^;]+;base64,(.+)$/)
|
||||
if (matches && matches[1]) {
|
||||
str = matches[1]
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
atob(str)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export const filterFiles = <T extends FileInput>(
|
||||
files: T[],
|
||||
options: FileValidationOptions,
|
||||
): [T[], FileError[]] => {
|
||||
const validFiles: T[] = []
|
||||
const errors: FileError[] = []
|
||||
|
||||
files.forEach((file) => {
|
||||
const actualFile = "src" in file ? file.src : file
|
||||
|
||||
if (actualFile instanceof File) {
|
||||
validateFileOrBase64(actualFile, options, file, validFiles, errors)
|
||||
} else if (typeof actualFile === "string") {
|
||||
if (isBase64(actualFile)) {
|
||||
if (options.allowBase64) {
|
||||
validateFileOrBase64(actualFile, options, file, validFiles, errors)
|
||||
} else {
|
||||
errors.push({ file: actualFile, reason: "base64NotAllowed" })
|
||||
}
|
||||
} else {
|
||||
validFiles.push(file)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return [validFiles, errors]
|
||||
}
|
||||
|
||||
export * from "./isCustomNodeSelected"
|
||||
export * from "./isTextSelected"
|
||||
@@ -4,3 +4,4 @@
|
||||
@import "partials/lists.css";
|
||||
@import "partials/typography.css";
|
||||
@import "partials/misc.css";
|
||||
@import "partials/zoom.css";
|
||||
@@ -1,7 +1,3 @@
|
||||
.la-editor div.tiptap p {
|
||||
@apply text-[var(--la-font-size-regular)];
|
||||
}
|
||||
|
||||
.la-editor .ProseMirror ol {
|
||||
@apply list-decimal;
|
||||
}
|
||||
@@ -68,7 +64,7 @@
|
||||
}
|
||||
|
||||
.la-editor .ProseMirror .taskItem-checkbox:checked {
|
||||
@apply border-primary bg-primary border bg-no-repeat;
|
||||
@apply border border-primary bg-primary bg-no-repeat;
|
||||
background-image: var(--checkbox-bg-image);
|
||||
}
|
||||
|
||||
@@ -16,7 +16,3 @@
|
||||
content: attr(data-placeholder);
|
||||
@apply pointer-events-none float-left h-0 text-[var(--la-secondary)];
|
||||
}
|
||||
|
||||
.la-editor div.tiptap p {
|
||||
@apply text-[var(--la-font-size-regular)];
|
||||
}
|
||||
@@ -43,7 +43,7 @@
|
||||
|
||||
.la-editor .ProseMirror blockquote::before,
|
||||
.la-editor .ProseMirror blockquote.is-empty::before {
|
||||
@apply bg-accent-foreground/15 absolute bottom-0 left-0 top-0 h-full w-1 rounded-sm content-[''];
|
||||
@apply absolute bottom-0 left-0 top-0 h-full w-1 rounded-sm bg-accent-foreground/15 content-[''];
|
||||
}
|
||||
|
||||
.la-editor .ProseMirror hr {
|
||||
@@ -51,7 +51,7 @@
|
||||
}
|
||||
|
||||
.la-editor .ProseMirror-focused hr.ProseMirror-selectednode {
|
||||
@apply outline-muted-foreground rounded-full outline outline-2 outline-offset-1;
|
||||
@apply rounded-full outline outline-2 outline-offset-1 outline-muted-foreground;
|
||||
}
|
||||
|
||||
.la-editor .ProseMirror .ProseMirror-gapcursor {
|
||||
@@ -19,7 +19,7 @@
|
||||
}
|
||||
|
||||
.la-editor .ProseMirror a.link {
|
||||
@apply text-primary cursor-pointer;
|
||||
@apply cursor-pointer text-primary;
|
||||
}
|
||||
|
||||
.la-editor .ProseMirror a.link:hover {
|
||||
@@ -1,5 +1,7 @@
|
||||
:root {
|
||||
--la-font-size-regular: 0.9375rem;
|
||||
--mt-overlay: rgba(251, 251, 251, 0.75);
|
||||
--mt-transparent-foreground: rgba(0, 0, 0, 0.4);
|
||||
--mt-bg-secondary: rgba(251, 251, 251, 0.8);
|
||||
--checkbox-bg-image: url("data:image/svg+xml;utf8,%3Csvg%20width=%2210%22%20height=%229%22%20viewBox=%220%200%2010%208%22%20xmlns=%22http://www.w3.org/2000/svg%22%20fill=%22%23fbfbfb%22%3E%3Cpath%20d=%22M3.46975%205.70757L1.88358%204.1225C1.65832%203.8974%201.29423%203.8974%201.06897%204.1225C0.843675%204.34765%200.843675%204.7116%201.06897%204.93674L3.0648%206.93117C3.29006%207.15628%203.65414%207.15628%203.8794%206.93117L8.93103%201.88306C9.15633%201.65792%209.15633%201.29397%208.93103%201.06883C8.70578%200.843736%208.34172%200.843724%208.11646%201.06879C8.11645%201.0688%208.11643%201.06882%208.11642%201.06883L3.46975%205.70757Z%22%20stroke-width=%220.2%22%20/%3E%3C/svg%3E");
|
||||
|
||||
--la-code-background: rgba(8, 43, 120, 0.047);
|
||||
@@ -23,7 +25,9 @@
|
||||
}
|
||||
|
||||
.dark .ProseMirror {
|
||||
--la-font-size-regular: 0.9375rem;
|
||||
--mt-overlay: rgba(31, 32, 35, 0.75);
|
||||
--mt-transparent-foreground: rgba(255, 255, 255, 0.4);
|
||||
--mt-bg-secondary: rgba(31, 32, 35, 0.8);
|
||||
--checkbox-bg-image: url("data:image/svg+xml;utf8,%3Csvg%20width=%2210%22%20height=%229%22%20viewBox=%220%200%2010%208%22%20xmlns=%22http://www.w3.org/2000/svg%22%20fill=%22lch%284.8%25%200.7%20272%29%22%3E%3Cpath%20d=%22M3.46975%205.70757L1.88358%204.1225C1.65832%203.8974%201.29423%203.8974%201.06897%204.1225C0.843675%204.34765%200.843675%204.7116%201.06897%204.93674L3.0648%206.93117C3.29006%207.15628%203.65414%207.15628%203.8794%206.93117L8.93103%201.88306C9.15633%201.65792%209.15633%201.29397%208.93103%201.06883C8.70578%200.843736%208.34172%200.843724%208.11646%201.06879C8.11645%201.0688%208.11643%201.06882%208.11642%201.06883L3.46975%205.70757Z%22%20stroke-width=%220.2%22%20/%3E%3C/svg%3E");
|
||||
|
||||
--la-code-background: rgba(255, 255, 255, 0.075);
|
||||
94
web/shared/editor/styles/partials/zoom.css
Normal file
94
web/shared/editor/styles/partials/zoom.css
Normal file
@@ -0,0 +1,94 @@
|
||||
[data-rmiz-ghost] {
|
||||
position: absolute;
|
||||
pointer-events: none;
|
||||
}
|
||||
[data-rmiz-btn-zoom],
|
||||
[data-rmiz-btn-unzoom] {
|
||||
background-color: rgba(0, 0, 0, 0.7);
|
||||
border-radius: 50%;
|
||||
border: none;
|
||||
box-shadow: 0 0 1px rgba(255, 255, 255, 0.5);
|
||||
color: #fff;
|
||||
height: 40px;
|
||||
margin: 0;
|
||||
outline-offset: 2px;
|
||||
padding: 9px;
|
||||
touch-action: manipulation;
|
||||
width: 40px;
|
||||
-webkit-appearance: none;
|
||||
-moz-appearance: none;
|
||||
appearance: none;
|
||||
}
|
||||
[data-rmiz-btn-zoom]:not(:focus):not(:active) {
|
||||
position: absolute;
|
||||
clip: rect(0 0 0 0);
|
||||
clip-path: inset(50%);
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
pointer-events: none;
|
||||
white-space: nowrap;
|
||||
width: 1px;
|
||||
}
|
||||
[data-rmiz-btn-zoom] {
|
||||
position: absolute;
|
||||
inset: 10px 10px auto auto;
|
||||
cursor: zoom-in;
|
||||
}
|
||||
[data-rmiz-btn-unzoom] {
|
||||
position: absolute;
|
||||
inset: 20px 20px auto auto;
|
||||
cursor: zoom-out;
|
||||
z-index: 1;
|
||||
}
|
||||
[data-rmiz-content="found"] img,
|
||||
[data-rmiz-content="found"] svg,
|
||||
[data-rmiz-content="found"] [role="img"],
|
||||
[data-rmiz-content="found"] [data-zoom] {
|
||||
cursor: inherit;
|
||||
}
|
||||
[data-rmiz-modal]::backdrop {
|
||||
display: none;
|
||||
}
|
||||
[data-rmiz-modal][open] {
|
||||
position: fixed;
|
||||
width: 100vw;
|
||||
width: 100dvw;
|
||||
height: 100vh;
|
||||
height: 100dvh;
|
||||
max-width: none;
|
||||
max-height: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
overflow: hidden;
|
||||
}
|
||||
[data-rmiz-modal-overlay] {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
transition: background-color 0.3s;
|
||||
}
|
||||
[data-rmiz-modal-overlay="hidden"] {
|
||||
background-color: rgba(255, 255, 255, 0);
|
||||
}
|
||||
[data-rmiz-modal-overlay="visible"] {
|
||||
background-color: rgba(255, 255, 255, 1);
|
||||
}
|
||||
[data-rmiz-modal-content] {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
[data-rmiz-modal-img] {
|
||||
position: absolute;
|
||||
cursor: zoom-out;
|
||||
image-rendering: high-quality;
|
||||
transform-origin: top left;
|
||||
transition: transform 0.3s;
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
[data-rmiz-modal-overlay],
|
||||
[data-rmiz-modal-img] {
|
||||
transition-duration: 0.01ms !important;
|
||||
}
|
||||
}
|
||||
53
web/shared/hooks/use-throttle-callback.ts
Normal file
53
web/shared/hooks/use-throttle-callback.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { useCallback, useRef, useEffect } from "react"
|
||||
|
||||
type AnyFunction = (...args: any[]) => any
|
||||
|
||||
export function useThrottleCallback<T extends AnyFunction>(
|
||||
callback: T,
|
||||
deps: React.DependencyList,
|
||||
delay: number,
|
||||
): T {
|
||||
const timeoutRef = useRef<NodeJS.Timeout | null>(null)
|
||||
const lastCalledRef = useRef<number>(0)
|
||||
const callbackRef = useRef<T>(callback)
|
||||
|
||||
// Update the callback ref whenever the callback changes
|
||||
useEffect(() => {
|
||||
callbackRef.current = callback
|
||||
}, [callback])
|
||||
|
||||
useEffect(() => {
|
||||
// Cleanup function to clear the timeout
|
||||
return () => {
|
||||
if (timeoutRef.current) {
|
||||
clearTimeout(timeoutRef.current)
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
return useCallback(
|
||||
(...args: Parameters<T>) => {
|
||||
const now = Date.now()
|
||||
|
||||
if (now - lastCalledRef.current >= delay) {
|
||||
// If enough time has passed, call the function immediately
|
||||
lastCalledRef.current = now
|
||||
callbackRef.current(...args)
|
||||
} else {
|
||||
// Otherwise, set a timeout to call the function later
|
||||
if (timeoutRef.current) {
|
||||
clearTimeout(timeoutRef.current)
|
||||
}
|
||||
|
||||
timeoutRef.current = setTimeout(
|
||||
() => {
|
||||
lastCalledRef.current = Date.now()
|
||||
callbackRef.current(...args)
|
||||
},
|
||||
delay - (now - lastCalledRef.current),
|
||||
)
|
||||
}
|
||||
},
|
||||
[delay, ...deps],
|
||||
) as T
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
import { useTextmenuCommands } from "../../hooks/use-text-menu-commands"
|
||||
import { PopoverWrapper } from "../ui/popover-wrapper"
|
||||
import { useTextmenuStates } from "../../hooks/use-text-menu-states"
|
||||
import { BubbleMenu as TiptapBubbleMenu, Editor } from "@tiptap/react"
|
||||
import { ToolbarButton } from "../ui/toolbar-button"
|
||||
import { Icon } from "../ui/icon"
|
||||
import { Keybind } from "../ui/keybind"
|
||||
|
||||
export type BubbleMenuProps = {
|
||||
editor: Editor
|
||||
}
|
||||
|
||||
export const BubbleMenu = ({ editor }: BubbleMenuProps) => {
|
||||
const commands = useTextmenuCommands(editor)
|
||||
const states = useTextmenuStates(editor)
|
||||
|
||||
const toolbarButtonClassname =
|
||||
"hover:opacity-100 transition-all dark:border-slate-500/10 border-gray-400 hover:border-b-2 active:translate-y-0 hover:translate-y-[-1.5px] hover:bg-zinc-300 dark:hover:bg-neutral-800 shadow-md rounded-[10px]"
|
||||
|
||||
return (
|
||||
<TiptapBubbleMenu
|
||||
tippyOptions={{
|
||||
// duration: [0, 999999],
|
||||
popperOptions: { placement: "top-start" },
|
||||
}}
|
||||
className="flex h-[40px] min-h-[40px] items-center rounded-[14px] shadow-md"
|
||||
editor={editor}
|
||||
pluginKey="textMenu"
|
||||
shouldShow={states.shouldShow}
|
||||
updateDelay={100}
|
||||
>
|
||||
<PopoverWrapper
|
||||
className="flex items-center rounded-[14px] border border-slate-400/10 bg-gray-100 p-[4px] dark:bg-[#121212]"
|
||||
style={{
|
||||
boxShadow: "inset 0px 0px 5px 3px var(--boxShadow)",
|
||||
}}
|
||||
>
|
||||
<div className="flex space-x-1">
|
||||
<Keybind keys={["Ctrl", "I"]}>
|
||||
<ToolbarButton
|
||||
className={toolbarButtonClassname}
|
||||
value="bold"
|
||||
aria-label="Bold"
|
||||
onPressedChange={commands.onBold}
|
||||
isActive={states.isBold}
|
||||
>
|
||||
<Icon name="Bold" strokeWidth={2.5} />
|
||||
</ToolbarButton>
|
||||
</Keybind>
|
||||
|
||||
<Keybind keys={["Ctrl", "U"]}>
|
||||
<ToolbarButton
|
||||
className={toolbarButtonClassname}
|
||||
value="italic"
|
||||
aria-label="Italic"
|
||||
onClick={commands.onItalic}
|
||||
isActive={states.isItalic}
|
||||
>
|
||||
<Icon name="Italic" strokeWidth={2.5} />
|
||||
</ToolbarButton>
|
||||
</Keybind>
|
||||
<Keybind keys={["Ctrl", "S"]}>
|
||||
<ToolbarButton
|
||||
className={toolbarButtonClassname}
|
||||
value="strikethrough"
|
||||
aria-label="Strikethrough"
|
||||
onClick={commands.onStrike}
|
||||
isActive={states.isStrike}
|
||||
>
|
||||
<Icon name="Strikethrough" strokeWidth={2.5} />
|
||||
</ToolbarButton>
|
||||
</Keybind>
|
||||
{/* <ToolbarButton value="link" aria-label="Link">
|
||||
<Icon name="Link" strokeWidth={2.5} />
|
||||
</ToolbarButton> */}
|
||||
<Keybind keys={["cmd", "K"]}>
|
||||
<ToolbarButton
|
||||
className={toolbarButtonClassname}
|
||||
value="quote"
|
||||
aria-label="Quote"
|
||||
onClick={commands.onCode}
|
||||
isActive={states.isCode}
|
||||
>
|
||||
<Icon name="Quote" strokeWidth={2.5} />
|
||||
</ToolbarButton>
|
||||
</Keybind>
|
||||
<Keybind keys={["Ctrl", "O"]}>
|
||||
<ToolbarButton
|
||||
className={toolbarButtonClassname}
|
||||
value="inline code"
|
||||
aria-label="Inline code"
|
||||
onClick={commands.onCode}
|
||||
isActive={states.isCode}
|
||||
>
|
||||
<Icon name="Braces" strokeWidth={2.5} />
|
||||
</ToolbarButton>
|
||||
</Keybind>
|
||||
<ToolbarButton
|
||||
className={toolbarButtonClassname}
|
||||
value="code block"
|
||||
aria-label="Code block"
|
||||
onClick={commands.onCodeBlock}
|
||||
>
|
||||
<Icon name="Code" strokeWidth={2.5} />
|
||||
</ToolbarButton>
|
||||
{/* <ToolbarButton value="list" aria-label="List">
|
||||
<Icon name="List" strokeWidth={2.5} />
|
||||
</ToolbarButton> */}
|
||||
</div>
|
||||
</PopoverWrapper>
|
||||
</TiptapBubbleMenu>
|
||||
)
|
||||
}
|
||||
|
||||
export default BubbleMenu
|
||||
@@ -1,52 +0,0 @@
|
||||
import { ReactNode, useState } from "react"
|
||||
import { motion } from "framer-motion"
|
||||
|
||||
export function Keybind({
|
||||
keys,
|
||||
children,
|
||||
}: {
|
||||
keys: string[]
|
||||
children: ReactNode
|
||||
}) {
|
||||
const [hovered, setHovered] = useState(false)
|
||||
const variants = {
|
||||
hidden: { opacity: 0, y: 6, x: "-50%" },
|
||||
visible: { opacity: 1, y: 0, x: "-50%" },
|
||||
}
|
||||
return (
|
||||
<div
|
||||
onMouseEnter={() => setHovered(true)}
|
||||
onMouseLeave={() => setHovered(false)}
|
||||
className="group relative h-full"
|
||||
>
|
||||
<motion.div
|
||||
initial="hidden"
|
||||
animate={hovered ? "visible" : "hidden"}
|
||||
variants={variants}
|
||||
transition={{ duration: 0.2, delay: 0.4 }}
|
||||
className="absolute left-[50%] top-[-30px] flex h-fit w-fit items-center rounded-[7px] border border-slate-400/30 bg-gray-100 p-[3px] px-2 text-[10px] drop-shadow-sm dark:border-slate-400/10 dark:bg-[#191919]"
|
||||
style={{
|
||||
boxShadow: "inset 0px 0px 6px 2px var(--boxShadow)",
|
||||
}}
|
||||
>
|
||||
{keys.map((key, index) => (
|
||||
<span key={key}>
|
||||
{index > 0 && <span className="mx-1">+</span>}
|
||||
{(() => {
|
||||
switch (key.toLowerCase()) {
|
||||
case "cmd":
|
||||
return "⌘"
|
||||
case "shift":
|
||||
return "⇪"
|
||||
|
||||
default:
|
||||
return key
|
||||
}
|
||||
})()}
|
||||
</span>
|
||||
))}
|
||||
</motion.div>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
import { StarterKit } from "./starter-kit"
|
||||
import { TaskList } from "./task-list"
|
||||
import { TaskItem } from "./task-item"
|
||||
import { HorizontalRule } from "./horizontal-rule"
|
||||
import { Blockquote } from "./blockquote/blockquote"
|
||||
import { SlashCommand } from "./slash-command"
|
||||
import { Heading } from "./heading"
|
||||
import { Link } from "./link"
|
||||
import { CodeBlockLowlight } from "./code-block-lowlight"
|
||||
import { Selection } from "./selection"
|
||||
import { Code } from "./code"
|
||||
import { Paragraph } from "./paragraph"
|
||||
import { BulletList } from "./bullet-list"
|
||||
import { OrderedList } from "./ordered-list"
|
||||
import { Dropcursor } from "./dropcursor"
|
||||
|
||||
export interface ExtensionOptions {
|
||||
placeholder?: string
|
||||
}
|
||||
|
||||
export const createExtensions = ({
|
||||
placeholder = "Start typing...",
|
||||
}: ExtensionOptions) => [
|
||||
Heading,
|
||||
Code,
|
||||
Link,
|
||||
TaskList,
|
||||
TaskItem,
|
||||
Selection,
|
||||
Paragraph,
|
||||
Dropcursor,
|
||||
Blockquote,
|
||||
BulletList,
|
||||
OrderedList,
|
||||
SlashCommand,
|
||||
HorizontalRule,
|
||||
CodeBlockLowlight,
|
||||
StarterKit.configure({
|
||||
placeholder: {
|
||||
placeholder: () => placeholder,
|
||||
},
|
||||
}),
|
||||
]
|
||||
|
||||
export default createExtensions
|
||||
@@ -1 +0,0 @@
|
||||
export * from "./la-editor"
|
||||
@@ -1,107 +0,0 @@
|
||||
import * as React from "react"
|
||||
import { EditorContent, useEditor } from "@tiptap/react"
|
||||
import { Editor, Content } from "@tiptap/core"
|
||||
import { BubbleMenu } from "./components/bubble-menu"
|
||||
import { createExtensions } from "./extensions"
|
||||
import "./styles/index.css"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { getOutput } from "./lib/utils"
|
||||
import type { EditorView } from "@tiptap/pm/view"
|
||||
import { useThrottle } from "@shared/hooks/use-throttle"
|
||||
|
||||
export interface LAEditorProps
|
||||
extends Omit<React.HTMLProps<HTMLDivElement>, "value"> {
|
||||
output?: "html" | "json" | "text"
|
||||
placeholder?: string
|
||||
editorClassName?: string
|
||||
onUpdate?: (content: Content) => void
|
||||
onBlur?: (content: Content) => void
|
||||
handleKeyDown?: (view: EditorView, event: KeyboardEvent) => boolean
|
||||
value?: any
|
||||
throttleDelay?: number
|
||||
}
|
||||
|
||||
export interface LAEditorRef {
|
||||
editor: Editor | null
|
||||
}
|
||||
|
||||
export const LAEditor = React.forwardRef<LAEditorRef, LAEditorProps>(
|
||||
(
|
||||
{
|
||||
value,
|
||||
placeholder,
|
||||
output = "html",
|
||||
editorClassName,
|
||||
className,
|
||||
onUpdate,
|
||||
onBlur,
|
||||
handleKeyDown,
|
||||
throttleDelay = 1000,
|
||||
...props
|
||||
},
|
||||
ref,
|
||||
) => {
|
||||
const throttledSetValue = useThrottle(
|
||||
(value: Content) => onUpdate?.(value),
|
||||
throttleDelay,
|
||||
)
|
||||
|
||||
const handleUpdate = React.useCallback(
|
||||
(editor: Editor) => {
|
||||
throttledSetValue(getOutput(editor, output))
|
||||
},
|
||||
[output, throttledSetValue],
|
||||
)
|
||||
|
||||
const editor = useEditor({
|
||||
autofocus: false,
|
||||
immediatelyRender: false,
|
||||
extensions: createExtensions({ placeholder }),
|
||||
editorProps: {
|
||||
attributes: {
|
||||
autocomplete: "off",
|
||||
autocorrect: "off",
|
||||
autocapitalize: "off",
|
||||
class: editorClassName || "",
|
||||
},
|
||||
handleKeyDown,
|
||||
},
|
||||
onCreate: ({ editor }) => {
|
||||
editor.commands.setContent(value)
|
||||
},
|
||||
onUpdate: ({ editor }) => handleUpdate(editor),
|
||||
onBlur: ({ editor }) => {
|
||||
onBlur?.(getOutput(editor, output))
|
||||
},
|
||||
})
|
||||
|
||||
React.useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
editor: editor,
|
||||
}),
|
||||
[editor],
|
||||
)
|
||||
|
||||
if (!editor) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"la-editor relative flex h-full w-full grow flex-col",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<EditorContent editor={editor} />
|
||||
<BubbleMenu editor={editor} />
|
||||
</div>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
LAEditor.displayName = "LAEditor"
|
||||
|
||||
export default LAEditor
|
||||
@@ -1,12 +0,0 @@
|
||||
import { Editor } from "@tiptap/core"
|
||||
import { LAEditorProps } from "../../la-editor"
|
||||
|
||||
export function getOutput(editor: Editor, output: LAEditorProps["output"]) {
|
||||
if (output === "html") return editor.getHTML()
|
||||
if (output === "json") return editor.getJSON()
|
||||
if (output === "text") return editor.getText()
|
||||
return ""
|
||||
}
|
||||
|
||||
export * from "./isCustomNodeSelected"
|
||||
export * from "./isTextSelected"
|
||||
@@ -113,7 +113,7 @@ const ImageEditBlock = ({
|
||||
onChange={handleFile}
|
||||
/>
|
||||
{error && (
|
||||
<div className="text-destructive text-sm bg-destructive/10 p-2 rounded">
|
||||
<div className="rounded bg-destructive/10 p-2 text-sm text-destructive">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
5
web/shared/utils/index.ts
Normal file
5
web/shared/utils/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export const isClient = () => typeof window !== "undefined"
|
||||
|
||||
export const isServer = () => !isClient()
|
||||
|
||||
export * from "./keyboard"
|
||||
67
web/shared/utils/keyboard.ts
Normal file
67
web/shared/utils/keyboard.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
import { isServer } from "@shared/utils"
|
||||
|
||||
interface ShortcutKeyResult {
|
||||
symbol: string
|
||||
readable: string
|
||||
}
|
||||
|
||||
export function getShortcutKey(key: string): ShortcutKeyResult {
|
||||
const lowercaseKey = key.toLowerCase()
|
||||
if (lowercaseKey === "mod") {
|
||||
return isMac()
|
||||
? { symbol: "⌘", readable: "Command" }
|
||||
: { symbol: "Ctrl", readable: "Control" }
|
||||
} else if (lowercaseKey === "alt") {
|
||||
return isMac()
|
||||
? { symbol: "⌥", readable: "Option" }
|
||||
: { symbol: "Alt", readable: "Alt" }
|
||||
} else if (lowercaseKey === "shift") {
|
||||
return isMac()
|
||||
? { symbol: "⇧", readable: "Shift" }
|
||||
: { symbol: "Shift", readable: "Shift" }
|
||||
} else {
|
||||
return { symbol: key.toUpperCase(), readable: key }
|
||||
}
|
||||
}
|
||||
|
||||
export function getShortcutKeys(keys: string[]): ShortcutKeyResult[] {
|
||||
return keys.map((key) => getShortcutKey(key))
|
||||
}
|
||||
|
||||
export function isModKey(
|
||||
event: KeyboardEvent | MouseEvent | React.KeyboardEvent,
|
||||
) {
|
||||
return isMac() ? event.metaKey : event.ctrlKey
|
||||
}
|
||||
|
||||
export function isMac(): boolean {
|
||||
if (isServer()) {
|
||||
return false
|
||||
}
|
||||
return window.navigator.platform === "MacIntel"
|
||||
}
|
||||
|
||||
export function isWindows(): boolean {
|
||||
if (isServer()) {
|
||||
return false
|
||||
}
|
||||
return window.navigator.platform === "Win32"
|
||||
}
|
||||
|
||||
let supportsPassive = false
|
||||
|
||||
try {
|
||||
const opts = Object.defineProperty({}, "passive", {
|
||||
get() {
|
||||
supportsPassive = true
|
||||
},
|
||||
})
|
||||
// @ts-expect-error ts-migrate(2769) testPassive is not a real event
|
||||
window.addEventListener("testPassive", null, opts)
|
||||
// @ts-expect-error ts-migrate(2769) testPassive is not a real event
|
||||
window.removeEventListener("testPassive", null, opts)
|
||||
} catch (e) {
|
||||
// No-op
|
||||
}
|
||||
|
||||
export const supportsPassiveListener = supportsPassive
|
||||
Reference in New Issue
Block a user