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,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

View File

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

View File

@@ -0,0 +1,30 @@
import * as React from "react"
import { cn } from "@/lib/utils"
import { icons } from "lucide-react"
export type IconProps = {
name: keyof typeof icons
className?: string
strokeWidth?: number
[key: string]: any
}
export const Icon = React.memo(
({ name, className, size, strokeWidth, ...props }: IconProps) => {
const IconComponent = icons[name]
if (!IconComponent) {
return null
}
return (
<IconComponent
className={cn(!size ? "size-4" : size, className)}
strokeWidth={strokeWidth || 2}
{...props}
/>
)
},
)
Icon.displayName = "Icon"

View File

@@ -0,0 +1,24 @@
import * as React from "react"
import { cn } from "@/lib/utils"
export type PopoverWrapperProps = React.HTMLProps<HTMLDivElement>
export const PopoverWrapper = React.forwardRef<
HTMLDivElement,
PopoverWrapperProps
>(({ children, className, ...props }, ref) => {
return (
<div
className={cn(
"rounded-lg border bg-popover text-popover-foreground shadow-sm",
className,
)}
{...props}
ref={ref}
>
{children}
</div>
)
})
PopoverWrapper.displayName = "PopoverWrapper"

View File

@@ -0,0 +1,55 @@
import * as React from "react"
import { cn } from "@/lib/utils"
import { getShortcutKey } from "@shared/utils"
export interface ShortcutKeyWrapperProps
extends React.HTMLAttributes<HTMLSpanElement> {
ariaLabel: string
}
const ShortcutKeyWrapper = React.forwardRef<
HTMLSpanElement,
ShortcutKeyWrapperProps
>(({ className, ariaLabel, children, ...props }, ref) => {
return (
<span
aria-label={ariaLabel}
className={cn("inline-flex items-center gap-0.5", className)}
{...props}
ref={ref}
>
{children}
</span>
)
})
ShortcutKeyWrapper.displayName = "ShortcutKeyWrapper"
export interface ShortcutKeyProps
extends React.HTMLAttributes<HTMLSpanElement> {
shortcut: string
}
const ShortcutKey = React.forwardRef<HTMLSpanElement, ShortcutKeyProps>(
({ className, shortcut, ...props }, ref) => {
return (
<kbd
className={cn(
"inline-block min-w-2.5 text-center align-baseline font-sans text-xs font-medium capitalize text-[rgb(156,157,160)]",
className,
)}
{...props}
ref={ref}
>
{getShortcutKey(shortcut).symbol}
</kbd>
)
},
)
ShortcutKey.displayName = "ShortcutKey"
export const Shortcut = {
Wrapper: ShortcutKeyWrapper,
Key: ShortcutKey,
}

View File

@@ -0,0 +1,57 @@
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip"
import { Toggle } from "@/components/ui/toggle"
import * as React from "react"
import { cn } from "@/lib/utils"
import type { TooltipContentProps } from "@radix-ui/react-tooltip"
interface ToolbarButtonProps
extends React.ComponentPropsWithoutRef<typeof Toggle> {
isActive?: boolean
tooltip?: string
tooltipOptions?: TooltipContentProps
}
const ToolbarButton = React.forwardRef<HTMLButtonElement, ToolbarButtonProps>(
function ToolbarButton(
{ isActive, children, tooltip, className, tooltipOptions, ...props },
ref,
) {
return (
<Tooltip>
<TooltipTrigger asChild>
<Toggle
size="sm"
ref={ref}
className={cn(
"size-7 rounded-md p-0",
{
"bg-primary/10 text-primary hover:bg-primary/10 hover:text-primary":
isActive,
},
className,
)}
{...props}
>
{children}
</Toggle>
</TooltipTrigger>
{tooltip && (
<TooltipContent {...tooltipOptions}>
<div className="flex flex-col items-center text-center">
{tooltip}
</div>
</TooltipContent>
)}
</Tooltip>
)
},
)
ToolbarButton.displayName = "ToolbarButton"
export { ToolbarButton }

View 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

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

View 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

View File

@@ -0,0 +1,48 @@
import * as React from "react"
import { Editor } from "@tiptap/react"
export const useTextmenuCommands = (editor: Editor) => {
const onBold = React.useCallback(
() => editor.chain().focus().toggleBold().run(),
[editor],
)
const onItalic = React.useCallback(
() => editor.chain().focus().toggleItalic().run(),
[editor],
)
const onStrike = React.useCallback(
() => editor.chain().focus().toggleStrike().run(),
[editor],
)
const onCode = React.useCallback(
() => editor.chain().focus().toggleCode().run(),
[editor],
)
const onCodeBlock = React.useCallback(
() => editor.chain().focus().toggleCodeBlock().run(),
[editor],
)
const onQuote = React.useCallback(
() => editor.chain().focus().toggleBlockquote().run(),
[editor],
)
const onLink = React.useCallback(
(url: string, inNewTab?: boolean) =>
editor
.chain()
.focus()
.setLink({ href: url, target: inNewTab ? "_blank" : "" })
.run(),
[editor],
)
return {
onBold,
onItalic,
onStrike,
onCode,
onCodeBlock,
onQuote,
onLink,
}
}

View File

@@ -0,0 +1,34 @@
import * as React from "react"
import { Editor } from "@tiptap/react"
import { ShouldShowProps } from "../types"
import { isCustomNodeSelected, isTextSelected } from "../lib/utils"
export const useTextmenuStates = (editor: Editor) => {
const shouldShow = React.useCallback(
({ view, from }: ShouldShowProps) => {
if (!view) {
return false
}
const domAtPos = view.domAtPos(from || 0).node as HTMLElement
const nodeDOM = view.nodeDOM(from || 0) as HTMLElement
const node = nodeDOM || domAtPos
if (isCustomNodeSelected(editor, node)) {
return false
}
return isTextSelected({ editor })
},
[editor],
)
return {
isBold: editor.isActive("bold"),
isItalic: editor.isActive("italic"),
isStrike: editor.isActive("strike"),
isUnderline: editor.isActive("underline"),
isCode: editor.isActive("code"),
shouldShow,
}
}

View File

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

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

View File

@@ -0,0 +1,37 @@
import { HorizontalRule } from "../../extensions/horizontal-rule"
import { Link } from "../../extensions/link"
import { Editor } from "@tiptap/react"
export const isTableGripSelected = (node: HTMLElement) => {
let container = node
while (container && !["TD", "TH"].includes(container.tagName)) {
container = container.parentElement!
}
const gripColumn =
container &&
container.querySelector &&
container.querySelector("a.grip-column.selected")
const gripRow =
container &&
container.querySelector &&
container.querySelector("a.grip-row.selected")
if (gripColumn || gripRow) {
return true
}
return false
}
export const isCustomNodeSelected = (editor: Editor, node: HTMLElement) => {
const customNodes = [HorizontalRule.name, Link.name]
return (
customNodes.some((type) => editor.isActive(type)) ||
isTableGripSelected(node)
)
}
export default isCustomNodeSelected

View File

@@ -0,0 +1,26 @@
import { isTextSelection } from "@tiptap/core"
import { Editor } from "@tiptap/react"
export const isTextSelected = ({ editor }: { editor: Editor }) => {
const {
state: {
doc,
selection,
selection: { empty, from, to },
},
} = editor
// Sometime check for `empty` is not enough.
// Doubleclick an empty paragraph returns a node size of 2.
// So we check also for an empty text size.
const isEmptyTextBlock =
!doc.textBetween(from, to).length && isTextSelection(selection)
if (empty || isEmptyTextBlock || !editor.isEditable) {
return false
}
return true
}
export default isTextSelected

View File

@@ -0,0 +1,7 @@
@import "partials/vars.css";
@import "partials/prosemirror-base.css";
@import "partials/code-highlight.css";
@import "partials/lists.css";
@import "partials/typography.css";
@import "partials/misc.css";
@import "partials/zoom.css";

View File

@@ -0,0 +1,86 @@
.la-editor .ProseMirror code.inline {
@apply rounded border border-[var(--la-code-color)] bg-[var(--la-code-background)] px-1 py-0.5 text-sm;
}
.la-editor .ProseMirror pre {
@apply relative overflow-auto rounded border font-mono text-sm;
@apply border-[var(--la-pre-border)] bg-[var(--la-pre-background)] text-[var(--la-pre-color)];
@apply hyphens-none whitespace-pre text-left;
}
.la-editor .ProseMirror code {
@apply break-words leading-[1.7em];
}
.la-editor .ProseMirror pre code {
@apply block overflow-x-auto p-3.5;
}
.la-editor .ProseMirror pre {
.hljs-keyword,
.hljs-operator,
.hljs-function,
.hljs-built_in,
.hljs-builtin-name {
color: var(--hljs-keyword);
}
.hljs-attr,
.hljs-symbol,
.hljs-property,
.hljs-attribute,
.hljs-variable,
.hljs-template-variable,
.hljs-params {
color: var(--hljs-attr);
}
.hljs-name,
.hljs-regexp,
.hljs-link,
.hljs-type,
.hljs-addition {
color: var(--hljs-name);
}
.hljs-string,
.hljs-bullet {
color: var(--hljs-string);
}
.hljs-title,
.hljs-subst,
.hljs-section {
color: var(--hljs-title);
}
.hljs-literal,
.hljs-type,
.hljs-deletion {
color: var(--hljs-literal);
}
.hljs-selector-tag,
.hljs-selector-id,
.hljs-selector-class {
color: var(--hljs-selector-tag);
}
.hljs-number {
color: var(--hljs-number);
}
.hljs-comment,
.hljs-meta,
.hljs-quote {
color: var(--hljs-comment);
}
.hljs-emphasis {
@apply italic;
}
.hljs-strong {
@apply font-bold;
}
}

View File

@@ -0,0 +1,86 @@
.la-editor .ProseMirror code.inline {
@apply rounded border border-[var(--la-code-color)] bg-[var(--la-code-background)] px-1 py-0.5 text-sm;
}
.la-editor .ProseMirror pre {
@apply relative overflow-auto rounded border font-mono text-sm;
@apply border-[var(--la-pre-border)] bg-[var(--la-pre-background)] text-[var(--la-pre-color)];
@apply hyphens-none whitespace-pre text-left;
}
.la-editor .ProseMirror code {
@apply break-words leading-[1.7em];
}
.la-editor .ProseMirror pre code {
@apply block overflow-x-auto p-3.5;
}
.la-editor .ProseMirror pre {
.hljs-keyword,
.hljs-operator,
.hljs-function,
.hljs-built_in,
.hljs-builtin-name {
color: var(--hljs-keyword);
}
.hljs-attr,
.hljs-symbol,
.hljs-property,
.hljs-attribute,
.hljs-variable,
.hljs-template-variable,
.hljs-params {
color: var(--hljs-attr);
}
.hljs-name,
.hljs-regexp,
.hljs-link,
.hljs-type,
.hljs-addition {
color: var(--hljs-name);
}
.hljs-string,
.hljs-bullet {
color: var(--hljs-string);
}
.hljs-title,
.hljs-subst,
.hljs-section {
color: var(--hljs-title);
}
.hljs-literal,
.hljs-type,
.hljs-deletion {
color: var(--hljs-literal);
}
.hljs-selector-tag,
.hljs-selector-id,
.hljs-selector-class {
color: var(--hljs-selector-tag);
}
.hljs-number {
color: var(--hljs-number);
}
.hljs-comment,
.hljs-meta,
.hljs-quote {
color: var(--hljs-comment);
}
.hljs-emphasis {
@apply italic;
}
.hljs-strong {
@apply font-bold;
}
}

View File

@@ -0,0 +1,86 @@
.la-editor .ProseMirror ol {
@apply list-decimal;
}
.la-editor .ProseMirror ol ol {
list-style: lower-alpha;
}
.la-editor .ProseMirror ol ol ol {
list-style: lower-roman;
}
.la-editor .ProseMirror ul {
list-style: disc;
}
.la-editor .ProseMirror ul ul {
list-style: circle;
}
.la-editor .ProseMirror ul ul ul {
list-style: square;
}
.la-editor .ProseMirror ul[data-type="taskList"] {
@apply list-none pl-1;
}
.la-editor .ProseMirror ul[data-type="taskList"] p {
@apply m-0;
}
.la-editor .ProseMirror ul[data-type="taskList"] li > label {
@apply mr-2 mt-0.5 flex-none select-none;
}
.la-editor .ProseMirror li[data-type="taskItem"] {
@apply flex flex-row items-start;
}
.la-editor .ProseMirror li[data-type="taskItem"] .taskItem-checkbox-container {
@apply relative pr-2;
}
.la-editor .ProseMirror .taskItem-drag-handle {
@apply absolute -left-5 top-1.5 h-[18px] w-[18px] cursor-move pl-0.5 text-[var(--la-secondary)] opacity-0;
}
.la-editor
.ProseMirror
li[data-type="taskItem"]:hover:not(:has(li:hover))
> .taskItem-checkbox-container
> .taskItem-drag-handle {
@apply opacity-100;
}
.la-editor .ProseMirror .taskItem-drag-handle:hover {
@apply text-[var(--la-drag-handle-hover)];
}
.la-editor .ProseMirror .taskItem-checkbox {
fill-opacity: 0;
@apply h-3.5 w-3.5 flex-shrink-0 cursor-pointer select-none appearance-none rounded border border-solid border-[var(--la-secondary)] bg-transparent bg-[1px_2px] p-0.5 align-middle transition-colors duration-75 ease-out;
}
.la-editor .ProseMirror .taskItem-checkbox:checked {
@apply border border-primary bg-primary bg-no-repeat;
background-image: var(--checkbox-bg-image);
}
.la-editor .ProseMirror .taskItem-content {
@apply min-w-0 flex-1;
}
.la-editor
.ProseMirror
li[data-checked="true"]
.taskItem-content
> :not([data-type="taskList"]),
.la-editor
.ProseMirror
li[data-checked="true"]
.taskItem-content
.taskItem-checkbox {
@apply opacity-75;
}

View File

@@ -0,0 +1,18 @@
[data-theme="slash-command"] {
width: 1000vw;
}
.la-editor .ProseMirror .is-empty::before {
@apply pointer-events-none float-left h-0 w-full text-[var(--la-secondary)];
}
.la-editor:not(.no-command)
.ProseMirror.ProseMirror-focused
> p.has-focus.is-empty::before {
content: "Type / for commands...";
}
.la-editor .ProseMirror > p.is-editor-empty::before {
content: attr(data-placeholder);
@apply pointer-events-none float-left h-0 text-[var(--la-secondary)];
}

View File

@@ -0,0 +1,86 @@
.la-editor .ProseMirror {
@apply block flex-1 whitespace-pre-wrap outline-0 focus:outline-none;
}
.la-editor .ProseMirror .block-node:not(:last-child),
.la-editor .ProseMirror .list-node:not(:last-child),
.la-editor .ProseMirror .text-node:not(:last-child) {
@apply mb-2.5;
}
.la-editor .ProseMirror ol,
.la-editor .ProseMirror ul {
@apply pl-6;
}
.la-editor .ProseMirror blockquote,
.la-editor .ProseMirror dl,
.la-editor .ProseMirror ol,
.la-editor .ProseMirror p,
.la-editor .ProseMirror pre,
.la-editor .ProseMirror ul {
@apply m-0;
}
.la-editor .ProseMirror li {
@apply leading-7;
}
.la-editor .ProseMirror p {
@apply break-words;
}
.la-editor .ProseMirror li .text-node:has(+ .list-node),
.la-editor .ProseMirror li > .list-node,
.la-editor .ProseMirror li > .text-node,
.la-editor .ProseMirror li p {
@apply mb-0;
}
.la-editor .ProseMirror blockquote {
@apply relative pl-3.5;
}
.la-editor .ProseMirror blockquote::before,
.la-editor .ProseMirror blockquote.is-empty::before {
@apply absolute bottom-0 left-0 top-0 h-full w-1 rounded-sm bg-accent-foreground/15 content-[''];
}
.la-editor .ProseMirror hr {
@apply my-3 h-0.5 w-full border-none bg-[var(--la-hr)];
}
.la-editor .ProseMirror-focused hr.ProseMirror-selectednode {
@apply rounded-full outline outline-2 outline-offset-1 outline-muted-foreground;
}
.la-editor .ProseMirror .ProseMirror-gapcursor {
@apply pointer-events-none absolute hidden;
}
.la-editor .ProseMirror .ProseMirror-hideselection {
@apply caret-transparent;
}
.la-editor .ProseMirror.resize-cursor {
@apply cursor-col-resize;
}
.la-editor .ProseMirror .selection {
@apply inline-block;
}
.la-editor .ProseMirror .selection,
.la-editor .ProseMirror *::selection,
::selection {
@apply bg-primary/40;
}
/* Override native selection when custom selection is present */
.la-editor .ProseMirror .selection::selection {
background: transparent;
}
[data-theme="slash-command"] {
width: 1000vw;
}

View File

@@ -0,0 +1,27 @@
.la-editor .ProseMirror .heading-node {
@apply relative font-semibold;
}
.la-editor .ProseMirror .heading-node:first-child {
@apply mt-0;
}
.la-editor .ProseMirror h1 {
@apply mb-4 mt-[46px] text-[1.375rem] leading-7 tracking-[-0.004375rem];
}
.la-editor .ProseMirror h2 {
@apply mb-3.5 mt-8 text-[1.1875rem] leading-7 tracking-[0.003125rem];
}
.la-editor .ProseMirror h3 {
@apply mb-3 mt-6 text-[1.0625rem] leading-6 tracking-[0.00625rem];
}
.la-editor .ProseMirror a.link {
@apply cursor-pointer text-primary;
}
.la-editor .ProseMirror a.link:hover {
@apply underline;
}

View File

@@ -0,0 +1,51 @@
:root {
--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);
--la-code-color: rgb(212, 212, 212);
--la-secondary: rgb(157, 157, 159);
--la-pre-background: rgb(236, 236, 236);
--la-pre-border: rgb(224, 224, 224);
--la-pre-color: rgb(47, 47, 49);
--la-hr: rgb(220, 220, 220);
--la-drag-handle-hover: rgb(92, 92, 94);
--hljs-string: rgb(170, 67, 15);
--hljs-title: rgb(176, 136, 54);
--hljs-comment: rgb(153, 153, 153);
--hljs-keyword: rgb(12, 94, 177);
--hljs-attr: rgb(58, 146, 188);
--hljs-literal: rgb(200, 43, 15);
--hljs-name: rgb(37, 151, 146);
--hljs-selector-tag: rgb(200, 80, 15);
--hljs-number: rgb(61, 160, 103);
}
.dark .ProseMirror {
--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);
--la-code-color: rgb(44, 46, 51);
--la-secondary: rgb(89, 90, 92);
--la-pre-background: rgb(8, 8, 8);
--la-pre-border: rgb(35, 37, 42);
--la-pre-color: rgb(227, 228, 230);
--la-hr: rgb(38, 40, 45);
--la-drag-handle-hover: rgb(150, 151, 153);
--hljs-string: rgb(218, 147, 107);
--hljs-title: rgb(241, 213, 157);
--hljs-comment: rgb(170, 170, 170);
--hljs-keyword: rgb(102, 153, 204);
--hljs-attr: rgb(144, 202, 232);
--hljs-literal: rgb(242, 119, 122);
--hljs-name: rgb(95, 192, 160);
--hljs-selector-tag: rgb(232, 199, 133);
--hljs-number: rgb(182, 231, 182);
}

View 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;
}
}

View File

@@ -0,0 +1,20 @@
import * as React from "react"
import { Editor as CoreEditor } from "@tiptap/core"
import { Editor } from "@tiptap/react"
import { EditorState } from "@tiptap/pm/state"
import { EditorView } from "@tiptap/pm/view"
export interface MenuProps {
editor: Editor
appendTo?: React.RefObject<any>
shouldHide?: boolean
}
export interface ShouldShowProps {
editor?: CoreEditor
view: EditorView
state?: EditorState
oldState?: EditorState
from?: number
to?: number
}