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:
Aslam
2024-10-18 21:18:20 +07:00
committed by GitHub
parent c93c634a77
commit a440828f8c
158 changed files with 2808 additions and 1064 deletions

View File

@@ -0,0 +1,19 @@
/*
* Add block-node class to blockquote element
*/
import { mergeAttributes } from "@tiptap/core"
import { Blockquote as TiptapBlockquote } from "@tiptap/extension-blockquote"
export const Blockquote = TiptapBlockquote.extend({
renderHTML({ HTMLAttributes }) {
return [
"blockquote",
mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, {
class: "block-node",
}),
0,
]
},
})
export default Blockquote

View File

@@ -0,0 +1,14 @@
import { BulletList as TiptapBulletList } from "@tiptap/extension-bullet-list"
export const BulletList = TiptapBulletList.extend({
addOptions() {
return {
...this.parent?.(),
HTMLAttributes: {
class: "list-node",
},
}
},
})
export default BulletList

View File

@@ -0,0 +1 @@
export * from "./bullet-list"

View File

@@ -0,0 +1,17 @@
import { CodeBlockLowlight as TiptapCodeBlockLowlight } from "@tiptap/extension-code-block-lowlight"
import { common, createLowlight } from "lowlight"
export const CodeBlockLowlight = TiptapCodeBlockLowlight.extend({
addOptions() {
return {
...this.parent?.(),
lowlight: createLowlight(common),
defaultLanguage: null,
HTMLAttributes: {
class: "block-node",
},
}
},
})
export default CodeBlockLowlight

View File

@@ -0,0 +1 @@
export * from "./code-block-lowlight"

View File

@@ -0,0 +1,15 @@
import { Code as TiptapCode } from "@tiptap/extension-code"
export const Code = TiptapCode.extend({
addOptions() {
return {
...this.parent?.(),
HTMLAttributes: {
class: "inline",
spellCheck: "false",
},
}
},
})
export default Code

View File

@@ -0,0 +1 @@
export * from "./code"

View File

@@ -0,0 +1,13 @@
import { Dropcursor as TiptapDropcursor } from "@tiptap/extension-dropcursor"
export const Dropcursor = TiptapDropcursor.extend({
addOptions() {
return {
...this.parent?.(),
width: 2,
class: "ProseMirror-dropcursor border",
}
},
})
export default Dropcursor

View File

@@ -0,0 +1 @@
export * from "./dropcursor"

View 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,
}),
]
},
})

View File

@@ -0,0 +1,33 @@
/*
* Add heading level validation. decimal (0-9)
* Add heading class to heading element
*/
import { mergeAttributes } from "@tiptap/core"
import TiptapHeading from "@tiptap/extension-heading"
import type { Level } from "@tiptap/extension-heading"
export const Heading = TiptapHeading.extend({
addOptions() {
return {
...this.parent?.(),
levels: [1, 2, 3] as Level[],
HTMLAttributes: {
class: "heading-node",
},
}
},
renderHTML({ node, HTMLAttributes }) {
const nodeLevel = parseInt(node.attrs.level, 10) as Level
const hasLevel = this.options.levels.includes(nodeLevel)
const level = hasLevel ? nodeLevel : this.options.levels[0]
return [
`h${level}`,
mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),
0,
]
},
})
export default Heading

View File

@@ -0,0 +1 @@
export * from "./heading"

View File

@@ -0,0 +1,18 @@
/*
* Wrap the horizontal rule in a div element.
* Also add a keyboard shortcut to insert a horizontal rule.
*/
import { HorizontalRule as TiptapHorizontalRule } from "@tiptap/extension-horizontal-rule"
export const HorizontalRule = TiptapHorizontalRule.extend({
addKeyboardShortcuts() {
return {
"Mod-Alt--": () =>
this.editor.commands.insertContent({
type: this.name,
}),
}
},
})
export default HorizontalRule

View File

@@ -0,0 +1 @@
export * from "./horizontal-rule"

View 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"

View File

@@ -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>
)
})

View File

@@ -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>
)
}

View File

@@ -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"

View 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),
}
}

View File

@@ -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 }
}

View 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",
})
},
})

View File

@@ -0,0 +1 @@
export * from "./image"

View File

@@ -0,0 +1 @@
export * from "./link"

View File

@@ -0,0 +1,97 @@
import { mergeAttributes } from "@tiptap/core"
import TiptapLink from "@tiptap/extension-link"
import { EditorView } from "@tiptap/pm/view"
import { getMarkRange } from "@tiptap/core"
import { Plugin, TextSelection } from "@tiptap/pm/state"
export const Link = TiptapLink.extend({
/*
* Determines whether typing next to a link automatically becomes part of the link.
* In this case, we dont want any characters to be included as part of the link.
*/
inclusive: false,
/*
* Match all <a> elements that have an href attribute, except for:
* - <a> elements with a data-type attribute set to button
* - <a> elements with an href attribute that contains 'javascript:'
*/
parseHTML() {
return [
{
tag: 'a[href]:not([data-type="button"]):not([href *= "javascript:" i])',
},
]
},
renderHTML({ HTMLAttributes }) {
return [
"a",
mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),
0,
]
},
addOptions() {
return {
...this.parent?.(),
openOnClick: false,
HTMLAttributes: {
class: "link",
},
}
},
addProseMirrorPlugins() {
const { editor } = this
return [
...(this.parent?.() || []),
new Plugin({
props: {
handleKeyDown: (view: EditorView, event: KeyboardEvent) => {
const { selection } = editor.state
/*
* Handles the 'Escape' key press when there's a selection within the link.
* This will move the cursor to the end of the link.
*/
if (event.key === "Escape" && selection.empty !== true) {
editor.commands.focus(selection.to, { scrollIntoView: false })
}
return false
},
handleClick(view, pos) {
/*
* Marks the entire link when the user clicks on it.
*/
const { schema, doc, tr } = view.state
const range = getMarkRange(doc.resolve(pos), schema.marks.link)
if (!range) {
return
}
const { from, to } = range
const start = Math.min(from, to)
const end = Math.max(from, to)
if (pos < start || pos > end) {
return
}
const $start = doc.resolve(start)
const $end = doc.resolve(end)
const transaction = tr.setSelection(new TextSelection($start, $end))
view.dispatch(transaction)
},
},
}),
]
},
})
export default Link

View File

@@ -0,0 +1 @@
export * from "./ordered-list"

View File

@@ -0,0 +1,14 @@
import { OrderedList as TiptapOrderedList } from "@tiptap/extension-ordered-list"
export const OrderedList = TiptapOrderedList.extend({
addOptions() {
return {
...this.parent?.(),
HTMLAttributes: {
class: "list-node",
},
}
},
})
export default OrderedList

View File

@@ -0,0 +1 @@
export * from "./paragraph"

View File

@@ -0,0 +1,14 @@
import { Paragraph as TiptapParagraph } from "@tiptap/extension-paragraph"
export const Paragraph = TiptapParagraph.extend({
addOptions() {
return {
...this.parent?.(),
HTMLAttributes: {
class: "text-node",
},
}
},
})
export default Paragraph

View File

@@ -0,0 +1 @@
export * from "./selection"

View File

@@ -0,0 +1,36 @@
import { Extension } from "@tiptap/core"
import { Plugin, PluginKey } from "@tiptap/pm/state"
import { Decoration, DecorationSet } from "@tiptap/pm/view"
export const Selection = Extension.create({
name: "selection",
addProseMirrorPlugins() {
const { editor } = this
return [
new Plugin({
key: new PluginKey("selection"),
props: {
decorations(state) {
if (state.selection.empty) {
return null
}
if (editor.isFocused === true) {
return null
}
return DecorationSet.create(state.doc, [
Decoration.inline(state.selection.from, state.selection.to, {
class: "selection",
}),
])
},
},
}),
]
},
})
export default Selection

View File

@@ -0,0 +1,133 @@
import { Group } from "./types"
export const GROUPS: Group[] = [
{
name: "format",
title: "Format",
commands: [
{
name: "heading1",
label: "Heading 1",
iconName: "Heading1",
description: "High priority section title",
aliases: ["h1"],
shortcuts: ["mod", "alt", "1"],
action: (editor) => {
editor.chain().focus().setHeading({ level: 1 }).run()
},
},
{
name: "heading2",
label: "Heading 2",
iconName: "Heading2",
description: "Medium priority section title",
aliases: ["h2"],
shortcuts: ["mod", "alt", "2"],
action: (editor) => {
editor.chain().focus().setHeading({ level: 2 }).run()
},
},
{
name: "heading3",
label: "Heading 3",
iconName: "Heading3",
description: "Low priority section title",
aliases: ["h3"],
shortcuts: ["mod", "alt", "3"],
action: (editor) => {
editor.chain().focus().setHeading({ level: 3 }).run()
},
},
],
},
{
name: "list",
title: "List",
commands: [
{
name: "bulletList",
label: "Bullet List",
iconName: "List",
description: "Unordered list of items",
aliases: ["ul"],
shortcuts: ["mod", "shift", "8"],
action: (editor) => {
editor.chain().focus().toggleBulletList().run()
},
},
{
name: "numberedList",
label: "Numbered List",
iconName: "ListOrdered",
description: "Ordered list of items",
aliases: ["ol"],
shortcuts: ["mod", "shift", "7"],
action: (editor) => {
editor.chain().focus().toggleOrderedList().run()
},
},
{
name: "taskList",
label: "Task List",
iconName: "ListTodo",
description: "Task list with todo items",
aliases: ["todo"],
shortcuts: ["mod", "shift", "8"],
action: (editor) => {
editor.chain().focus().toggleTaskList().run()
},
},
],
},
{
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",
iconName: "SquareCode",
description: "Code block with syntax highlighting",
shortcuts: ["mod", "alt", "c"],
shouldBeHidden: (editor) => editor.isActive("columns"),
action: (editor) => {
editor.chain().focus().setCodeBlock().run()
},
},
{
name: "horizontalRule",
label: "Divider",
iconName: "Divide",
description: "Insert a horizontal divider",
aliases: ["hr"],
shortcuts: ["mod", "shift", "-"],
action: (editor) => {
editor.chain().focus().setHorizontalRule().run()
},
},
{
name: "blockquote",
label: "Blockquote",
iconName: "Quote",
description: "Element for quoting",
shortcuts: ["mod", "shift", "b"],
action: (editor) => {
editor.chain().focus().setBlockquote().run()
},
},
],
},
]
export default GROUPS

View File

@@ -0,0 +1 @@
export * from "./slash-command"

View File

@@ -0,0 +1,172 @@
import * as React from "react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Separator } from "@/components/ui/separator"
import { Command, MenuListProps } from "./types"
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)
const activeItem = React.useRef<HTMLButtonElement>(null)
const [selectedGroupIndex, setSelectedGroupIndex] = React.useState(0)
const [selectedCommandIndex, setSelectedCommandIndex] = React.useState(0)
// Anytime the groups change, i.e. the user types to narrow it down, we want to
// reset the current selection to the first menu item
React.useEffect(() => {
setSelectedGroupIndex(0)
setSelectedCommandIndex(0)
}, [props.items])
const selectItem = React.useCallback(
(groupIndex: number, commandIndex: number) => {
const command = props.items[groupIndex].commands[commandIndex]
props.command(command)
},
[props],
)
React.useImperativeHandle(ref, () => ({
onKeyDown: ({ event }: { event: React.KeyboardEvent }) => {
if (event.key === "ArrowDown") {
if (!props.items.length) {
return false
}
const commands = props.items[selectedGroupIndex].commands
let newCommandIndex = selectedCommandIndex + 1
let newGroupIndex = selectedGroupIndex
if (commands.length - 1 < newCommandIndex) {
newCommandIndex = 0
newGroupIndex = selectedGroupIndex + 1
}
if (props.items.length - 1 < newGroupIndex) {
newGroupIndex = 0
}
setSelectedCommandIndex(newCommandIndex)
setSelectedGroupIndex(newGroupIndex)
return true
}
if (event.key === "ArrowUp") {
if (!props.items.length) {
return false
}
let newCommandIndex = selectedCommandIndex - 1
let newGroupIndex = selectedGroupIndex
if (newCommandIndex < 0) {
newGroupIndex = selectedGroupIndex - 1
newCommandIndex = props.items[newGroupIndex]?.commands.length - 1 || 0
}
if (newGroupIndex < 0) {
newGroupIndex = props.items.length - 1
newCommandIndex = props.items[newGroupIndex].commands.length - 1
}
setSelectedCommandIndex(newCommandIndex)
setSelectedGroupIndex(newGroupIndex)
return true
}
if (event.key === "Enter") {
if (
!props.items.length ||
selectedGroupIndex === -1 ||
selectedCommandIndex === -1
) {
return false
}
selectItem(selectedGroupIndex, selectedCommandIndex)
return true
}
return false
},
}))
React.useEffect(() => {
if (activeItem.current && scrollContainer.current) {
const offsetTop = activeItem.current.offsetTop
const offsetHeight = activeItem.current.offsetHeight
scrollContainer.current.scrollTop = offsetTop - offsetHeight
}
}, [selectedCommandIndex, selectedGroupIndex])
const createCommandClickHandler = React.useCallback(
(groupIndex: number, commandIndex: number) => {
return () => {
selectItem(groupIndex, commandIndex)
}
},
[selectItem],
)
if (!props.items.length) {
return null
}
return (
<PopoverWrapper
ref={scrollContainer}
className="flex max-h-[min(80vh,24rem)] flex-col overflow-auto p-1"
>
{props.items.map((group, groupIndex: number) => (
<React.Fragment key={group.title}>
{group.commands.map((command: Command, commandIndex: number) => (
<Button
key={command.label}
variant="ghost"
onClick={createCommandClickHandler(groupIndex, commandIndex)}
className={cn(
"relative w-full justify-between gap-2 px-3.5 py-1.5 font-normal",
{
"bg-accent text-accent-foreground":
selectedGroupIndex === groupIndex &&
selectedCommandIndex === commandIndex,
},
)}
>
<Icon name={command.iconName} />
<span className="truncate text-sm">{command.label}</span>
<div className="flex flex-auto flex-row"></div>
<Shortcut.Wrapper
ariaLabel={getShortcutKeys(command.shortcuts)
.map((shortcut) => shortcut.readable)
.join(" + ")}
>
{command.shortcuts.map((shortcut) => (
<Shortcut.Key shortcut={shortcut} key={shortcut} />
))}
</Shortcut.Wrapper>
</Button>
))}
{groupIndex !== props.items.length - 1 && (
<Separator className="my-1.5" />
)}
</React.Fragment>
))}
</PopoverWrapper>
)
})
MenuList.displayName = "MenuList"
export default MenuList

View File

@@ -0,0 +1,262 @@
import { Editor, Extension } from "@tiptap/core"
import { ReactRenderer } from "@tiptap/react"
import Suggestion, {
SuggestionProps,
SuggestionKeyDownProps,
} from "@tiptap/suggestion"
import { PluginKey } from "@tiptap/pm/state"
import tippy from "tippy.js"
import { GROUPS } from "./groups"
import { MenuList } from "./menu-list"
const EXTENSION_NAME = "slashCommand"
let popup: any
export const SlashCommand = Extension.create({
name: EXTENSION_NAME,
priority: 200,
onCreate() {
popup = tippy("body", {
interactive: true,
trigger: "manual",
placement: "bottom-start",
theme: "slash-command",
maxWidth: "16rem",
offset: [16, 8],
popperOptions: {
strategy: "fixed",
modifiers: [{ name: "flip", enabled: false }],
},
})
},
addProseMirrorPlugins() {
return [
Suggestion({
editor: this.editor,
char: "/",
allowSpaces: true,
startOfLine: true,
pluginKey: new PluginKey(EXTENSION_NAME),
allow: ({ state, range }) => {
const $from = state.doc.resolve(range.from)
const isRootDepth = $from.depth === 1
const isParagraph = $from.parent.type.name === "paragraph"
const isStartOfNode = $from.parent.textContent?.charAt(0) === "/"
const isInColumn = this.editor.isActive("column")
const afterContent = $from.parent.textContent?.substring(
$from.parent.textContent?.indexOf("/"),
)
const isValidAfterContent = !afterContent?.endsWith(" ")
return (
((isRootDepth && isParagraph && isStartOfNode) ||
(isInColumn && isParagraph && isStartOfNode)) &&
isValidAfterContent
)
},
command: ({ editor, props }: { editor: Editor; props: any }) => {
const { view, state } = editor
const { $head, $from } = view.state.selection
const end = $from.pos
const from = $head?.nodeBefore
? end -
($head.nodeBefore.text?.substring(
$head.nodeBefore.text?.indexOf("/"),
).length ?? 0)
: $from.start()
const tr = state.tr.deleteRange(from, end)
view.dispatch(tr)
props.action(editor)
view.focus()
},
items: ({ query }: { query: string }) => {
return GROUPS.map((group) => ({
...group,
commands: group.commands
.filter((item) => {
const labelNormalized = item.label.toLowerCase().trim()
const queryNormalized = query.toLowerCase().trim()
if (item.aliases) {
const aliases = item.aliases.map((alias) =>
alias.toLowerCase().trim(),
)
return (
labelNormalized.includes(queryNormalized) ||
aliases.includes(queryNormalized)
)
}
return labelNormalized.includes(queryNormalized)
})
.filter((command) =>
command.shouldBeHidden
? !command.shouldBeHidden(this.editor)
: true,
)
.map((command) => ({
...command,
isEnabled: true,
})),
})).filter((group) => group.commands.length > 0)
},
render: () => {
let component: any
let scrollHandler: (() => void) | null = null
return {
onStart: (props: SuggestionProps) => {
component = new ReactRenderer(MenuList, {
props,
editor: props.editor,
})
const { view } = props.editor
// const editorNode = view.dom as HTMLElement
const getReferenceClientRect = () => {
if (!props.clientRect) {
return props.editor.storage[EXTENSION_NAME].rect
}
const rect = props.clientRect()
if (!rect) {
return props.editor.storage[EXTENSION_NAME].rect
}
let yPos = rect.y
if (
rect.top + component.element.offsetHeight + 40 >
window.innerHeight
) {
const diff =
rect.top +
component.element.offsetHeight -
window.innerHeight +
40
yPos = rect.y - diff
}
// const editorXOffset = editorNode.getBoundingClientRect().x
return new DOMRect(rect.x, yPos, rect.width, rect.height)
}
scrollHandler = () => {
popup?.[0].setProps({
getReferenceClientRect,
})
}
view.dom.parentElement?.addEventListener("scroll", scrollHandler)
popup?.[0].setProps({
getReferenceClientRect,
appendTo: () => document.body,
content: component.element,
})
popup?.[0].show()
},
onUpdate(props: SuggestionProps) {
component.updateProps(props)
const { view } = props.editor
// const editorNode = view.dom as HTMLElement
const getReferenceClientRect = () => {
if (!props.clientRect) {
return props.editor.storage[EXTENSION_NAME].rect
}
const rect = props.clientRect()
if (!rect) {
return props.editor.storage[EXTENSION_NAME].rect
}
return new DOMRect(rect.x, rect.y, rect.width, rect.height)
}
const scrollHandler = () => {
popup?.[0].setProps({
getReferenceClientRect,
})
}
view.dom.parentElement?.addEventListener("scroll", scrollHandler)
props.editor.storage[EXTENSION_NAME].rect = props.clientRect
? getReferenceClientRect()
: {
width: 0,
height: 0,
left: 0,
top: 0,
right: 0,
bottom: 0,
}
popup?.[0].setProps({
getReferenceClientRect,
})
},
onKeyDown(props: SuggestionKeyDownProps) {
if (props.event.key === "Escape") {
popup?.[0].hide()
return true
}
if (!popup?.[0].state.isShown) {
popup?.[0].show()
}
return component.ref?.onKeyDown(props)
},
onExit(props) {
popup?.[0].hide()
if (scrollHandler) {
const { view } = props.editor
view.dom.parentElement?.removeEventListener(
"scroll",
scrollHandler,
)
}
component.destroy()
},
}
},
}),
]
},
addStorage() {
return {
rect: {
width: 0,
height: 0,
left: 0,
top: 0,
right: 0,
bottom: 0,
},
}
},
})
export default SlashCommand

View File

@@ -0,0 +1,25 @@
import { Editor } from "@tiptap/core"
import { icons } from "lucide-react"
export interface Group {
name: string
title: string
commands: Command[]
}
export interface Command {
name: string
label: string
description: string
aliases?: string[]
shortcuts: string[]
iconName: keyof typeof icons
action: (editor: Editor) => void
shouldBeHidden?: (editor: Editor) => boolean
}
export interface MenuListProps {
editor: Editor
items: Group[]
command: (command: Command) => void
}

View File

@@ -0,0 +1,153 @@
import { Extension } from "@tiptap/core"
import { Bold, BoldOptions } from "@tiptap/extension-bold"
import { Document } from "@tiptap/extension-document"
import { Gapcursor } from "@tiptap/extension-gapcursor"
import { HardBreak, HardBreakOptions } from "@tiptap/extension-hard-break"
import { Italic, ItalicOptions } from "@tiptap/extension-italic"
import { ListItem, ListItemOptions } from "@tiptap/extension-list-item"
import { Strike, StrikeOptions } from "@tiptap/extension-strike"
import { Text } from "@tiptap/extension-text"
import { FocusClasses, FocusOptions } from "@tiptap/extension-focus"
import { Typography, TypographyOptions } from "@tiptap/extension-typography"
import { Placeholder, PlaceholderOptions } from "@tiptap/extension-placeholder"
import { History, HistoryOptions } from "@tiptap/extension-history"
export interface StarterKitOptions {
/**
* If set to false, the bold extension will not be registered
* @example bold: false
*/
bold: Partial<BoldOptions> | false
/**
* If set to false, the document extension will not be registered
* @example document: false
*/
document: false
/**
* If set to false, the gapcursor extension will not be registered
* @example gapcursor: false
*/
gapcursor: false
/**
* If set to false, the hardBreak extension will not be registered
* @example hardBreak: false
*/
hardBreak: Partial<HardBreakOptions> | false
/**
* If set to false, the history extension will not be registered
* @example history: false
*/
history: Partial<HistoryOptions> | false
/**
* If set to false, the italic extension will not be registered
* @example italic: false
*/
italic: Partial<ItalicOptions> | false
/**
* If set to false, the listItem extension will not be registered
* @example listItem: false
*/
listItem: Partial<ListItemOptions> | false
/**
* If set to false, the strike extension will not be registered
* @example strike: false
*/
strike: Partial<StrikeOptions> | false
/**
* If set to false, the text extension will not be registered
* @example text: false
*/
text: false
/**
* If set to false, the typography extension will not be registered
* @example typography: false
*/
typography: Partial<TypographyOptions> | false
/**
* If set to false, the placeholder extension will not be registered
* @example placeholder: false
*/
placeholder: Partial<PlaceholderOptions> | false
/**
* If set to false, the focus extension will not be registered
* @example focus: false
*/
focus: Partial<FocusOptions> | false
}
/**
* The starter kit is a collection of essential editor extensions.
*
* Its a good starting point for building your own editor.
*/
export const StarterKit = Extension.create<StarterKitOptions>({
name: "starterKit",
addExtensions() {
const extensions = []
if (this.options.bold !== false) {
extensions.push(Bold.configure(this.options?.bold))
}
if (this.options.document !== false) {
extensions.push(Document.configure(this.options?.document))
}
if (this.options.gapcursor !== false) {
extensions.push(Gapcursor.configure(this.options?.gapcursor))
}
if (this.options.hardBreak !== false) {
extensions.push(HardBreak.configure(this.options?.hardBreak))
}
if (this.options.history !== false) {
extensions.push(History.configure(this.options?.history))
}
if (this.options.italic !== false) {
extensions.push(Italic.configure(this.options?.italic))
}
if (this.options.listItem !== false) {
extensions.push(ListItem.configure(this.options?.listItem))
}
if (this.options.strike !== false) {
extensions.push(Strike.configure(this.options?.strike))
}
if (this.options.text !== false) {
extensions.push(Text.configure(this.options?.text))
}
if (this.options.typography !== false) {
extensions.push(Typography.configure(this.options?.typography))
}
if (this.options.placeholder !== false) {
extensions.push(Placeholder.configure(this.options?.placeholder))
}
if (this.options.focus !== false) {
extensions.push(FocusClasses.configure(this.options?.focus))
}
return extensions
},
})
export default StarterKit

View File

@@ -0,0 +1,68 @@
import * as React from "react"
import { NodeViewContent, Editor, NodeViewWrapper } from "@tiptap/react"
import { Icon } from "../../../components/ui/icon"
import { Node as ProseMirrorNode } from "@tiptap/pm/model"
import { Node } from "@tiptap/core"
interface TaskItemProps {
editor: Editor
node: ProseMirrorNode
updateAttributes: (attrs: Record<string, any>) => void
extension: Node
}
export const TaskItemView: React.FC<TaskItemProps> = ({
node,
updateAttributes,
editor,
extension,
}) => {
const handleChange = React.useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
const checked = event.target.checked
if (!editor.isEditable && !extension.options.onReadOnlyChecked) {
return
}
if (editor.isEditable) {
updateAttributes({ checked })
} else if (extension.options.onReadOnlyChecked) {
if (!extension.options.onReadOnlyChecked(node, checked)) {
event.target.checked = !checked
}
}
},
[editor.isEditable, extension.options, node, updateAttributes],
)
return (
<NodeViewWrapper
as="li"
data-type="taskItem"
data-checked={node.attrs.checked}
>
<div className="taskItem-checkbox-container">
<Icon
name="GripVertical"
data-drag-handle
className="taskItem-drag-handle"
/>
<label>
<input
type="checkbox"
checked={node.attrs.checked}
onChange={handleChange}
className="taskItem-checkbox"
/>
</label>
</div>
<div className="taskItem-content">
<NodeViewContent />
</div>
</NodeViewWrapper>
)
}
export default TaskItemView

View File

@@ -0,0 +1 @@
export * from "./task-item"

View File

@@ -0,0 +1,64 @@
import { ReactNodeViewRenderer } from "@tiptap/react"
import { mergeAttributes } from "@tiptap/core"
import { TaskItemView } from "./components/task-item-view"
import { TaskItem as TiptapTaskItem } from "@tiptap/extension-task-item"
export const TaskItem = TiptapTaskItem.extend({
name: "taskItem",
draggable: true,
addOptions() {
return {
...this.parent?.(),
nested: true,
}
},
addAttributes() {
return {
checked: {
default: false,
keepOnSplit: false,
parseHTML: (element) => {
const dataChecked = element.getAttribute("data-checked")
return dataChecked === "" || dataChecked === "true"
},
renderHTML: (attributes) => ({
"data-checked": attributes.checked,
}),
},
}
},
renderHTML({ node, HTMLAttributes }) {
return [
"li",
mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, {
"data-type": this.name,
}),
[
"div",
{ class: "taskItem-checkbox-container" },
[
"label",
[
"input",
{
type: "checkbox",
checked: node.attrs.checked ? "checked" : null,
class: "taskItem-checkbox",
},
],
],
],
["div", { class: "taskItem-content" }, 0],
]
},
addNodeView() {
return ReactNodeViewRenderer(TaskItemView, {
as: "span",
})
},
})

View File

@@ -0,0 +1 @@
export * from "./task-list"

View File

@@ -0,0 +1,12 @@
import { TaskList as TiptapTaskList } from "@tiptap/extension-task-list"
export const TaskList = TiptapTaskList.extend({
addOptions() {
return {
...this.parent?.(),
HTMLAttributes: {
class: "list-node",
},
}
},
})