Move to TanStack Start from Next.js (#184)

This commit is contained in:
Aslam
2024-10-07 16:44:17 +07:00
committed by GitHub
parent 3a89a1c07f
commit 950ebc3dad
514 changed files with 20021 additions and 15508 deletions

46
web/shared/actions.ts Normal file
View File

@@ -0,0 +1,46 @@
import { getAuth } from "@clerk/tanstack-start/server"
import { createServerFn } from "@tanstack/start"
import { create } from "ronin"
import { z } from "zod"
const MAX_FILE_SIZE = 1 * 1024 * 1024
const ALLOWED_FILE_TYPES = [
"image/jpeg",
"image/png",
"image/gif",
"image/webp",
]
const ImageRuleSchema = z.object({
file: z
.instanceof(File)
.refine((file) => ALLOWED_FILE_TYPES.includes(file.type), {
message:
"Invalid file type. Only JPEG, PNG, GIF, and WebP images are allowed.",
})
.refine((file) => file.size <= MAX_FILE_SIZE, {
message: "File size exceeds the maximum limit of 1 MB.",
}),
})
export const storeImageFn = createServerFn(
"POST",
async (data: FormData, { request }) => {
const auth = await getAuth(request)
if (!auth.userId) {
throw new Error("Unauthorized")
}
const { file } = ImageRuleSchema.parse({ file: data.get("file") })
const fileModel = await create.image.with({
content: file,
name: file.name,
type: file.type,
size: file.size,
})
return { fileModel }
},
)

View File

@@ -0,0 +1,34 @@
import { useRef, useCallback } from "react"
export function useThrottle<T extends (...args: any[]) => void>(
callback: T,
delay: number,
): (...args: Parameters<T>) => void {
const lastRan = useRef(Date.now())
const timeoutRef = useRef<NodeJS.Timeout | null>(null)
return useCallback(
(...args: Parameters<T>) => {
const handler = () => {
if (Date.now() - lastRan.current >= delay) {
callback(...args)
lastRan.current = Date.now()
} else {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current)
}
timeoutRef.current = setTimeout(
() => {
callback(...args)
lastRan.current = Date.now()
},
delay - (Date.now() - lastRan.current),
)
}
}
handler()
},
[callback, delay],
)
}

View File

@@ -0,0 +1,115 @@
import { useTextmenuCommands } from "../../hooks/use-text-menu-commands"
import { PopoverWrapper } from "../ui/popover-wrapper"
import { useTextmenuStates } from "../../hooks/use-text-menu-states"
import { BubbleMenu as TiptapBubbleMenu, Editor } from "@tiptap/react"
import { ToolbarButton } from "../ui/toolbar-button"
import { Icon } from "../ui/icon"
import { Keybind } from "../ui/keybind"
export type BubbleMenuProps = {
editor: Editor
}
export const BubbleMenu = ({ editor }: BubbleMenuProps) => {
const commands = useTextmenuCommands(editor)
const states = useTextmenuStates(editor)
const toolbarButtonClassname =
"hover:opacity-100 transition-all dark:border-slate-500/10 border-gray-400 hover:border-b-2 active:translate-y-0 hover:translate-y-[-1.5px] hover:bg-zinc-300 dark:hover:bg-neutral-800 shadow-md rounded-[10px]"
return (
<TiptapBubbleMenu
tippyOptions={{
// duration: [0, 999999],
popperOptions: { placement: "top-start" },
}}
className="flex h-[40px] min-h-[40px] items-center rounded-[14px] shadow-md"
editor={editor}
pluginKey="textMenu"
shouldShow={states.shouldShow}
updateDelay={100}
>
<PopoverWrapper
className="flex items-center rounded-[14px] border border-slate-400/10 bg-gray-100 p-[4px] dark:bg-[#121212]"
style={{
boxShadow: "inset 0px 0px 5px 3px var(--boxShadow)",
}}
>
<div className="flex space-x-1">
<Keybind keys={["Ctrl", "I"]}>
<ToolbarButton
className={toolbarButtonClassname}
value="bold"
aria-label="Bold"
onPressedChange={commands.onBold}
isActive={states.isBold}
>
<Icon name="Bold" strokeWidth={2.5} />
</ToolbarButton>
</Keybind>
<Keybind keys={["Ctrl", "U"]}>
<ToolbarButton
className={toolbarButtonClassname}
value="italic"
aria-label="Italic"
onClick={commands.onItalic}
isActive={states.isItalic}
>
<Icon name="Italic" strokeWidth={2.5} />
</ToolbarButton>
</Keybind>
<Keybind keys={["Ctrl", "S"]}>
<ToolbarButton
className={toolbarButtonClassname}
value="strikethrough"
aria-label="Strikethrough"
onClick={commands.onStrike}
isActive={states.isStrike}
>
<Icon name="Strikethrough" strokeWidth={2.5} />
</ToolbarButton>
</Keybind>
{/* <ToolbarButton value="link" aria-label="Link">
<Icon name="Link" strokeWidth={2.5} />
</ToolbarButton> */}
<Keybind keys={["cmd", "K"]}>
<ToolbarButton
className={toolbarButtonClassname}
value="quote"
aria-label="Quote"
onClick={commands.onCode}
isActive={states.isCode}
>
<Icon name="Quote" strokeWidth={2.5} />
</ToolbarButton>
</Keybind>
<Keybind keys={["Ctrl", "O"]}>
<ToolbarButton
className={toolbarButtonClassname}
value="inline code"
aria-label="Inline code"
onClick={commands.onCode}
isActive={states.isCode}
>
<Icon name="Braces" strokeWidth={2.5} />
</ToolbarButton>
</Keybind>
<ToolbarButton
className={toolbarButtonClassname}
value="code block"
aria-label="Code block"
onClick={commands.onCodeBlock}
>
<Icon name="Code" strokeWidth={2.5} />
</ToolbarButton>
{/* <ToolbarButton value="list" aria-label="List">
<Icon name="List" strokeWidth={2.5} />
</ToolbarButton> */}
</div>
</PopoverWrapper>
</TiptapBubbleMenu>
)
}
export default BubbleMenu

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,52 @@
import { ReactNode, useState } from "react"
import { motion } from "framer-motion"
export function Keybind({
keys,
children,
}: {
keys: string[]
children: ReactNode
}) {
const [hovered, setHovered] = useState(false)
const variants = {
hidden: { opacity: 0, y: 6, x: "-50%" },
visible: { opacity: 1, y: 0, x: "-50%" },
}
return (
<div
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
className="group relative h-full"
>
<motion.div
initial="hidden"
animate={hovered ? "visible" : "hidden"}
variants={variants}
transition={{ duration: 0.2, delay: 0.4 }}
className="absolute left-[50%] top-[-30px] flex h-fit w-fit items-center rounded-[7px] border border-slate-400/30 bg-gray-100 p-[3px] px-2 text-[10px] drop-shadow-sm dark:border-slate-400/10 dark:bg-[#191919]"
style={{
boxShadow: "inset 0px 0px 6px 2px var(--boxShadow)",
}}
>
{keys.map((key, index) => (
<span key={key}>
{index > 0 && <span className="mx-1">+</span>}
{(() => {
switch (key.toLowerCase()) {
case "cmd":
return "⌘"
case "shift":
return "⇪"
default:
return key
}
})()}
</span>
))}
</motion.div>
{children}
</div>
)
}

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(
"bg-popover text-popover-foreground rounded-lg border 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 "@/lib/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,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,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,45 @@
import { StarterKit } from "./starter-kit"
import { TaskList } from "./task-list"
import { TaskItem } from "./task-item"
import { HorizontalRule } from "./horizontal-rule"
import { Blockquote } from "./blockquote/blockquote"
import { SlashCommand } from "./slash-command"
import { Heading } from "./heading"
import { Link } from "./link"
import { CodeBlockLowlight } from "./code-block-lowlight"
import { Selection } from "./selection"
import { Code } from "./code"
import { Paragraph } from "./paragraph"
import { BulletList } from "./bullet-list"
import { OrderedList } from "./ordered-list"
import { Dropcursor } from "./dropcursor"
export interface ExtensionOptions {
placeholder?: string
}
export const createExtensions = ({
placeholder = "Start typing...",
}: ExtensionOptions) => [
Heading,
Code,
Link,
TaskList,
TaskItem,
Selection,
Paragraph,
Dropcursor,
Blockquote,
BulletList,
OrderedList,
SlashCommand,
HorizontalRule,
CodeBlockLowlight,
StarterKit.configure({
placeholder: {
placeholder: () => placeholder,
},
}),
]
export default createExtensions

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,122 @@
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: "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 { getShortcutKeys } from "@/lib/utils"
import { Icon } from "../../components/ui/icon"
import { PopoverWrapper } from "../../components/ui/popover-wrapper"
import { Shortcut } from "../../components/ui/shortcut"
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,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 "./la-editor"

View File

@@ -0,0 +1,107 @@
import * as React from "react"
import { EditorContent, useEditor } from "@tiptap/react"
import { Editor, Content } from "@tiptap/core"
import { BubbleMenu } from "./components/bubble-menu"
import { createExtensions } from "./extensions"
import "./styles/index.css"
import { cn } from "@/lib/utils"
import { getOutput } from "./lib/utils"
import type { EditorView } from "@tiptap/pm/view"
import { useThrottle } from "@shared/hooks/use-throttle"
export interface LAEditorProps
extends Omit<React.HTMLProps<HTMLDivElement>, "value"> {
output?: "html" | "json" | "text"
placeholder?: string
editorClassName?: string
onUpdate?: (content: Content) => void
onBlur?: (content: Content) => void
handleKeyDown?: (view: EditorView, event: KeyboardEvent) => boolean
value?: any
throttleDelay?: number
}
export interface LAEditorRef {
editor: Editor | null
}
export const LAEditor = React.forwardRef<LAEditorRef, LAEditorProps>(
(
{
value,
placeholder,
output = "html",
editorClassName,
className,
onUpdate,
onBlur,
handleKeyDown,
throttleDelay = 1000,
...props
},
ref,
) => {
const throttledSetValue = useThrottle(
(value: Content) => onUpdate?.(value),
throttleDelay,
)
const handleUpdate = React.useCallback(
(editor: Editor) => {
throttledSetValue(getOutput(editor, output))
},
[output, throttledSetValue],
)
const editor = useEditor({
autofocus: false,
immediatelyRender: false,
extensions: createExtensions({ placeholder }),
editorProps: {
attributes: {
autocomplete: "off",
autocorrect: "off",
autocapitalize: "off",
class: editorClassName || "",
},
handleKeyDown,
},
onCreate: ({ editor }) => {
editor.commands.setContent(value)
},
onUpdate: ({ editor }) => handleUpdate(editor),
onBlur: ({ editor }) => {
onBlur?.(getOutput(editor, output))
},
})
React.useImperativeHandle(
ref,
() => ({
editor: editor,
}),
[editor],
)
if (!editor) {
return null
}
return (
<div
className={cn(
"la-editor relative flex h-full w-full grow flex-col",
className,
)}
{...props}
>
<EditorContent editor={editor} />
<BubbleMenu editor={editor} />
</div>
)
},
)
LAEditor.displayName = "LAEditor"
export default LAEditor

View File

@@ -0,0 +1,12 @@
import { Editor } from "@tiptap/core"
import { LAEditorProps } from "../../la-editor"
export function getOutput(editor: Editor, output: LAEditorProps["output"]) {
if (output === "html") return editor.getHTML()
if (output === "json") return editor.getJSON()
if (output === "text") return editor.getText()
return ""
}
export * from "./isCustomNodeSelected"
export * from "./isTextSelected"

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,6 @@
@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";

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,90 @@
.la-editor div.tiptap p {
@apply text-[var(--la-font-size-regular)];
}
.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-primary bg-primary border 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,22 @@
[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)];
}
.la-editor div.tiptap p {
@apply text-[var(--la-font-size-regular)];
}

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 bg-accent-foreground/15 absolute bottom-0 left-0 top-0 h-full w-1 rounded-sm 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 outline-muted-foreground rounded-full outline outline-2 outline-offset-1;
}
.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 text-primary cursor-pointer;
}
.la-editor .ProseMirror a.link:hover {
@apply underline;
}

View File

@@ -0,0 +1,47 @@
:root {
--la-font-size-regular: 0.9375rem;
--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 {
--la-font-size-regular: 0.9375rem;
--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,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
}

View File

@@ -0,0 +1,39 @@
import type { Editor } from "@tiptap/react"
import { BubbleMenu } from "@tiptap/react"
import { ImagePopoverBlock } from "../image/image-popover-block"
import { ShouldShowProps } from "../../types"
const ImageBubbleMenu = ({ editor }: { editor: Editor }) => {
const shouldShow = ({ editor, from, to }: ShouldShowProps) => {
if (from === to) {
return false
}
const img = editor.getAttributes("image")
if (img.src) {
return true
}
return false
}
const unSetImage = () => {
editor.commands.deleteSelection()
}
return (
<BubbleMenu
editor={editor}
shouldShow={shouldShow}
tippyOptions={{
placement: "bottom",
offset: [0, 8],
}}
>
<ImagePopoverBlock onRemove={unSetImage} />
</BubbleMenu>
)
}
export { ImageBubbleMenu }

View File

@@ -0,0 +1,113 @@
import * as React from "react"
import { Editor } from "@tiptap/react"
import { BubbleMenu } from "@tiptap/react"
import { LinkEditBlock } from "../link/link-edit-block"
import { LinkPopoverBlock } from "../link/link-popover-block"
import { ShouldShowProps } from "../../types"
interface LinkBubbleMenuProps {
editor: Editor
}
interface LinkAttributes {
href: string
target: string
}
export const LinkBubbleMenu: React.FC<LinkBubbleMenuProps> = ({ editor }) => {
const [showEdit, setShowEdit] = React.useState(false)
const [linkAttrs, setLinkAttrs] = React.useState<LinkAttributes>({
href: "",
target: "",
})
const [selectedText, setSelectedText] = React.useState("")
const updateLinkState = React.useCallback(() => {
const { from, to } = editor.state.selection
const { href, target } = editor.getAttributes("link")
const text = editor.state.doc.textBetween(from, to, " ")
setLinkAttrs({ href, target })
setSelectedText(text)
}, [editor])
const shouldShow = React.useCallback(
({ editor, from, to }: ShouldShowProps) => {
if (from === to) {
return false
}
const { href } = editor.getAttributes("link")
if (href) {
updateLinkState()
return true
}
return false
},
[updateLinkState],
)
const handleEdit = React.useCallback(() => {
setShowEdit(true)
}, [])
const onSetLink = React.useCallback(
(url: string, text?: string, openInNewTab?: boolean) => {
editor
.chain()
.focus()
.extendMarkRange("link")
.insertContent({
type: "text",
text: text || url,
marks: [
{
type: "link",
attrs: {
href: url,
target: openInNewTab ? "_blank" : "",
},
},
],
})
.setLink({ href: url, target: openInNewTab ? "_blank" : "" })
.run()
setShowEdit(false)
updateLinkState()
},
[editor, updateLinkState],
)
const onUnsetLink = React.useCallback(() => {
editor.chain().focus().extendMarkRange("link").unsetLink().run()
setShowEdit(false)
updateLinkState()
}, [editor, updateLinkState])
return (
<BubbleMenu
editor={editor}
shouldShow={shouldShow}
tippyOptions={{
placement: "bottom-start",
onHidden: () => setShowEdit(false),
}}
>
{showEdit ? (
<LinkEditBlock
defaultUrl={linkAttrs.href}
defaultText={selectedText}
defaultIsNewTab={linkAttrs.target === "_blank"}
onSave={onSetLink}
className="w-full min-w-80 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none"
/>
) : (
<LinkPopoverBlock
onClear={onUnsetLink}
url={linkAttrs.href}
onEdit={handleEdit}
/>
)}
</BubbleMenu>
)
}

View File

@@ -0,0 +1,125 @@
import * as React from "react"
import type { Editor } from "@tiptap/react"
import { Button } from "@/components/ui/button"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import { cn } from "@/lib/utils"
import { storeImageFn } from "@shared/actions"
import { ZodError } from "zod"
interface ImageEditBlockProps extends React.HTMLAttributes<HTMLDivElement> {
editor: Editor
close: () => void
}
const ImageEditBlock = ({
editor,
className,
close,
...props
}: ImageEditBlockProps) => {
const fileInputRef = React.useRef<HTMLInputElement>(null)
const [link, setLink] = React.useState<string>("")
const [isUploading, setIsUploading] = React.useState<boolean>(false)
const [error, setError] = React.useState<string | null>(null)
const handleClick = (e: React.MouseEvent) => {
e.preventDefault()
e.stopPropagation()
fileInputRef.current?.click()
}
const handleLink = () => {
editor.chain().focus().setImage({ src: link }).run()
close()
}
const handleFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files
if (!files || files.length === 0) return
setIsUploading(true)
setError(null)
const formData = new FormData()
formData.append("file", files[0])
try {
const response = await storeImageFn(formData)
editor
.chain()
.setImage({ src: response.fileModel.content.src })
.focus()
.run()
close()
} catch (error) {
if (error instanceof Error) {
try {
const errors = JSON.parse(error.message)
if (errors.body.name === "ZodError") {
setError(
(errors.body as ZodError).issues
.map((issue) => issue.message)
.join(", "),
)
} else {
setError(error.message)
}
} catch (parseError) {
setError(error.message)
}
} else {
setError("An unknown error occurred")
}
} finally {
setIsUploading(false)
}
}
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
e.stopPropagation()
handleLink()
}
return (
<form onSubmit={handleSubmit}>
<div className={cn("space-y-6", className)} {...props}>
<div className="space-y-1">
<Label>Attach an image link</Label>
<div className="flex">
<Input
type="url"
required
placeholder="https://example.com"
value={link}
className="grow"
onChange={(e) => setLink(e.target.value)}
/>
<Button type="submit" className="ml-2 inline-block">
Submit
</Button>
</div>
</div>
<Button className="w-full" onClick={handleClick} disabled={isUploading}>
{isUploading ? "Uploading..." : "Upload from your computer"}
</Button>
<input
type="file"
accept="image/jpeg,image/png,image/gif,image/webp"
ref={fileInputRef}
className="hidden"
onChange={handleFile}
/>
{error && (
<div className="text-destructive text-sm bg-destructive/10 p-2 rounded">
{error}
</div>
)}
</div>
</form>
)
}
export { ImageEditBlock }

View File

@@ -0,0 +1,50 @@
import * as React from "react"
import type { Editor } from "@tiptap/react"
import type { VariantProps } from "class-variance-authority"
import type { toggleVariants } from "@/components/ui/toggle"
import { ImageIcon } from "@radix-ui/react-icons"
import { ToolbarButton } from "../toolbar-button"
import {
Dialog,
DialogContent,
DialogHeader,
DialogDescription,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import { ImageEditBlock } from "./image-edit-block"
interface ImageEditDialogProps extends VariantProps<typeof toggleVariants> {
editor: Editor
}
const ImageEditDialog = ({ editor, size, variant }: ImageEditDialogProps) => {
const [open, setOpen] = React.useState(false)
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<ToolbarButton
isActive={editor.isActive("image")}
tooltip="Image"
aria-label="Image"
size={size}
variant={variant}
>
<ImageIcon className="size-5" />
</ToolbarButton>
</DialogTrigger>
<DialogContent className="sm:max-w-lg">
<DialogHeader>
<DialogTitle>Select image</DialogTitle>
<DialogDescription className="sr-only">
Upload an image from your computer
</DialogDescription>
</DialogHeader>
<ImageEditBlock editor={editor} close={() => setOpen(false)} />
</DialogContent>
</Dialog>
)
}
export { ImageEditDialog }

View File

@@ -0,0 +1,25 @@
import { ToolbarButton } from "../toolbar-button"
import { TrashIcon } from "@radix-ui/react-icons"
const ImagePopoverBlock = ({
onRemove,
}: {
onRemove: (e: React.MouseEvent<HTMLButtonElement>) => void
}) => {
const handleRemove = (e: React.MouseEvent<HTMLButtonElement>) => {
e.preventDefault()
onRemove(e)
}
return (
<div className="flex h-10 overflow-hidden rounded bg-background p-2 shadow-lg">
<div className="inline-flex items-center gap-1">
<ToolbarButton tooltip="Remove" onClick={handleRemove}>
<TrashIcon className="size-4" />
</ToolbarButton>
</div>
</div>
)
}
export { ImagePopoverBlock }

View File

@@ -0,0 +1,88 @@
import * as React from "react"
import { Button } from "@/components/ui/button"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { Input } from "@/components/ui/input"
import { cn } from "@/lib/utils"
export interface LinkEditorProps extends React.HTMLAttributes<HTMLDivElement> {
defaultUrl?: string
defaultText?: string
defaultIsNewTab?: boolean
onSave: (url: string, text?: string, isNewTab?: boolean) => void
}
export const LinkEditBlock = React.forwardRef<HTMLDivElement, LinkEditorProps>(
({ onSave, defaultIsNewTab, defaultUrl, defaultText, className }, ref) => {
const formRef = React.useRef<HTMLDivElement>(null)
const [url, setUrl] = React.useState(defaultUrl || "")
const [text, setText] = React.useState(defaultText || "")
const [isNewTab, setIsNewTab] = React.useState(defaultIsNewTab || false)
const handleSave = React.useCallback(
(e: React.FormEvent) => {
e.preventDefault()
if (formRef.current) {
const isValid = Array.from(
formRef.current.querySelectorAll("input"),
).every((input) => input.checkValidity())
if (isValid) {
onSave(url, text, isNewTab)
} else {
formRef.current.querySelectorAll("input").forEach((input) => {
if (!input.checkValidity()) {
input.reportValidity()
}
})
}
}
},
[onSave, url, text, isNewTab],
)
React.useImperativeHandle(ref, () => formRef.current as HTMLDivElement)
return (
<div ref={formRef}>
<div className={cn("space-y-4", className)}>
<div className="space-y-1">
<Label>URL</Label>
<Input
type="url"
required
placeholder="Enter URL"
value={url}
onChange={(e) => setUrl(e.target.value)}
/>
</div>
<div className="space-y-1">
<Label>Display Text (optional)</Label>
<Input
type="text"
placeholder="Enter display text"
value={text}
onChange={(e) => setText(e.target.value)}
/>
</div>
<div className="flex items-center space-x-2">
<Label>Open in New Tab</Label>
<Switch checked={isNewTab} onCheckedChange={setIsNewTab} />
</div>
<div className="flex justify-end space-x-2">
<Button type="button" onClick={handleSave}>
Save
</Button>
</div>
</div>
</div>
)
},
)
LinkEditBlock.displayName = "LinkEditBlock"
export default LinkEditBlock

View File

@@ -0,0 +1,72 @@
import * as React from "react"
import type { Editor } from "@tiptap/react"
import type { VariantProps } from "class-variance-authority"
import type { toggleVariants } from "@/components/ui/toggle"
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover"
import { Link2Icon } from "@radix-ui/react-icons"
import { ToolbarButton } from "../toolbar-button"
import { LinkEditBlock } from "./link-edit-block"
interface LinkEditPopoverProps extends VariantProps<typeof toggleVariants> {
editor: Editor
}
const LinkEditPopover = ({ editor, size, variant }: LinkEditPopoverProps) => {
const [open, setOpen] = React.useState(false)
const { from, to } = editor.state.selection
const text = editor.state.doc.textBetween(from, to, " ")
const onSetLink = React.useCallback(
(url: string, text?: string, openInNewTab?: boolean) => {
editor
.chain()
.focus()
.extendMarkRange("link")
.insertContent({
type: "text",
text: text || url,
marks: [
{
type: "link",
attrs: {
href: url,
target: openInNewTab ? "_blank" : "",
},
},
],
})
.setLink({ href: url })
.run()
editor.commands.enter()
},
[editor],
)
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<ToolbarButton
isActive={editor.isActive("link")}
tooltip="Link"
aria-label="Insert link"
disabled={editor.isActive("codeBlock")}
size={size}
variant={variant}
>
<Link2Icon className="size-5" />
</ToolbarButton>
</PopoverTrigger>
<PopoverContent className="w-full min-w-80" align="start" side="bottom">
<LinkEditBlock onSave={onSetLink} defaultText={text} />
</PopoverContent>
</Popover>
)
}
export { LinkEditPopover }

View File

@@ -0,0 +1,77 @@
import * as React from "react"
import { Separator } from "@/components/ui/separator"
import { ToolbarButton } from "../toolbar-button"
import {
CopyIcon,
ExternalLinkIcon,
LinkBreak2Icon,
} from "@radix-ui/react-icons"
interface LinkPopoverBlockProps {
url: string
onClear: () => void
onEdit: (e: React.MouseEvent<HTMLButtonElement>) => void
}
export const LinkPopoverBlock: React.FC<LinkPopoverBlockProps> = ({
url,
onClear,
onEdit,
}) => {
const [copyTitle, setCopyTitle] = React.useState<string>("Copy")
const handleCopy = React.useCallback(
(e: React.MouseEvent<HTMLButtonElement>) => {
e.preventDefault()
navigator.clipboard
.writeText(url)
.then(() => {
setCopyTitle("Copied!")
setTimeout(() => setCopyTitle("Copy"), 1000)
})
.catch(console.error)
},
[url],
)
const handleOpenLink = React.useCallback(() => {
window.open(url, "_blank", "noopener,noreferrer")
}, [url])
return (
<div className="flex h-10 overflow-hidden rounded bg-background p-2 shadow-lg">
<div className="inline-flex items-center gap-1">
<ToolbarButton
tooltip="Edit link"
onClick={onEdit}
className="w-auto px-2"
>
Edit link
</ToolbarButton>
<Separator orientation="vertical" />
<ToolbarButton
tooltip="Open link in a new tab"
onClick={handleOpenLink}
>
<ExternalLinkIcon className="size-4" />
</ToolbarButton>
<Separator orientation="vertical" />
<ToolbarButton tooltip="Clear link" onClick={onClear}>
<LinkBreak2Icon className="size-4" />
</ToolbarButton>
<Separator orientation="vertical" />
<ToolbarButton
tooltip={copyTitle}
onClick={handleCopy}
tooltipOptions={{
onPointerDownOutside: (e) => {
if (e.target === e.currentTarget) e.preventDefault()
},
}}
>
<CopyIcon className="size-4" />
</ToolbarButton>
</div>
</div>
)
}

View File

@@ -0,0 +1,93 @@
import * as React from "react"
import type { Editor } from "@tiptap/react"
import type { FormatAction } from "../../types"
import type { toggleVariants } from "@/components/ui/toggle"
import type { VariantProps } from "class-variance-authority"
import {
CaretDownIcon,
CodeIcon,
DividerHorizontalIcon,
PlusIcon,
QuoteIcon,
} from "@radix-ui/react-icons"
import { LinkEditPopover } from "../link/link-edit-popover"
import { ImageEditDialog } from "../image/image-edit-dialog"
import { ToolbarSection } from "../toolbar-section"
type InsertElementAction = "codeBlock" | "blockquote" | "horizontalRule"
interface InsertElement extends FormatAction {
value: InsertElementAction
}
const formatActions: InsertElement[] = [
{
value: "codeBlock",
label: "Code block",
icon: <CodeIcon className="size-5" />,
action: (editor) => editor.chain().focus().toggleCodeBlock().run(),
isActive: (editor) => editor.isActive("codeBlock"),
canExecute: (editor) =>
editor.can().chain().focus().toggleCodeBlock().run(),
shortcuts: ["mod", "alt", "C"],
},
{
value: "blockquote",
label: "Blockquote",
icon: <QuoteIcon className="size-5" />,
action: (editor) => editor.chain().focus().toggleBlockquote().run(),
isActive: (editor) => editor.isActive("blockquote"),
canExecute: (editor) =>
editor.can().chain().focus().toggleBlockquote().run(),
shortcuts: ["mod", "shift", "B"],
},
{
value: "horizontalRule",
label: "Divider",
icon: <DividerHorizontalIcon className="size-5" />,
action: (editor) => editor.chain().focus().setHorizontalRule().run(),
isActive: () => false,
canExecute: (editor) =>
editor.can().chain().focus().setHorizontalRule().run(),
shortcuts: ["mod", "alt", "-"],
},
]
interface SectionFiveProps extends VariantProps<typeof toggleVariants> {
editor: Editor
activeActions?: InsertElementAction[]
mainActionCount?: number
}
export const SectionFive: React.FC<SectionFiveProps> = ({
editor,
activeActions = formatActions.map((action) => action.value),
mainActionCount = 0,
size,
variant,
}) => {
return (
<>
<LinkEditPopover editor={editor} size={size} variant={variant} />
<ImageEditDialog editor={editor} size={size} variant={variant} />
<ToolbarSection
editor={editor}
actions={formatActions}
activeActions={activeActions}
mainActionCount={mainActionCount}
dropdownIcon={
<>
<PlusIcon className="size-5" />
<CaretDownIcon className="size-5" />
</>
}
dropdownTooltip="Insert elements"
size={size}
variant={variant}
/>
</>
)
}
SectionFive.displayName = "SectionFive"
export default SectionFive

View File

@@ -0,0 +1,81 @@
import * as React from "react"
import type { Editor } from "@tiptap/react"
import type { FormatAction } from "../../types"
import type { toggleVariants } from "@/components/ui/toggle"
import type { VariantProps } from "class-variance-authority"
import { CaretDownIcon, ListBulletIcon } from "@radix-ui/react-icons"
import { ToolbarSection } from "../toolbar-section"
type ListItemAction = "orderedList" | "bulletList"
interface ListItem extends FormatAction {
value: ListItemAction
}
const formatActions: ListItem[] = [
{
value: "orderedList",
label: "Numbered list",
icon: (
<svg
xmlns="http://www.w3.org/2000/svg"
height="20px"
viewBox="0 -960 960 960"
width="20px"
fill="currentColor"
>
<path d="M144-144v-48h96v-24h-48v-48h48v-24h-96v-48h120q10.2 0 17.1 6.9 6.9 6.9 6.9 17.1v48q0 10.2-6.9 17.1-6.9 6.9-17.1 6.9 10.2 0 17.1 6.9 6.9 6.9 6.9 17.1v48q0 10.2-6.9 17.1-6.9 6.9-17.1 6.9H144Zm0-240v-96q0-10.2 6.9-17.1 6.9-6.9 17.1-6.9h72v-24h-96v-48h120q10.2 0 17.1 6.9 6.9 6.9 6.9 17.1v72q0 10.2-6.9 17.1-6.9 6.9-17.1 6.9h-72v24h96v48H144Zm48-240v-144h-48v-48h96v192h-48Zm168 384v-72h456v72H360Zm0-204v-72h456v72H360Zm0-204v-72h456v72H360Z" />
</svg>
),
isActive: (editor) => editor.isActive("orderedList"),
action: (editor) => editor.chain().focus().toggleOrderedList().run(),
canExecute: (editor) =>
editor.can().chain().focus().toggleOrderedList().run(),
shortcuts: ["mod", "shift", "7"],
},
{
value: "bulletList",
label: "Bullet list",
icon: <ListBulletIcon className="size-5" />,
isActive: (editor) => editor.isActive("bulletList"),
action: (editor) => editor.chain().focus().toggleBulletList().run(),
canExecute: (editor) =>
editor.can().chain().focus().toggleBulletList().run(),
shortcuts: ["mod", "shift", "8"],
},
]
interface SectionFourProps extends VariantProps<typeof toggleVariants> {
editor: Editor
activeActions?: ListItemAction[]
mainActionCount?: number
}
export const SectionFour: React.FC<SectionFourProps> = ({
editor,
activeActions = formatActions.map((action) => action.value),
mainActionCount = 0,
size,
variant,
}) => {
return (
<ToolbarSection
editor={editor}
actions={formatActions}
activeActions={activeActions}
mainActionCount={mainActionCount}
dropdownIcon={
<>
<ListBulletIcon className="size-5" />
<CaretDownIcon className="size-5" />
</>
}
dropdownTooltip="Lists"
size={size}
variant={variant}
/>
)
}
SectionFour.displayName = "SectionFour"
export default SectionFour

View File

@@ -0,0 +1,151 @@
import * as React from "react"
import type { Editor } from "@tiptap/react"
import type { Level } from "@tiptap/extension-heading"
import type { FormatAction } from "../../types"
import type { VariantProps } from "class-variance-authority"
import type { toggleVariants } from "@/components/ui/toggle"
import { cn } from "@/lib/utils"
import { CaretDownIcon, LetterCaseCapitalizeIcon } from "@radix-ui/react-icons"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { ToolbarButton } from "../toolbar-button"
import { ShortcutKey } from "../shortcut-key"
interface TextStyle
extends Omit<
FormatAction,
"value" | "icon" | "action" | "isActive" | "canExecute"
> {
element: keyof JSX.IntrinsicElements
level?: Level
className: string
}
const formatActions: TextStyle[] = [
{
label: "Normal Text",
element: "span",
className: "grow",
shortcuts: ["mod", "alt", "0"],
},
{
label: "Heading 1",
element: "h1",
level: 1,
className: "m-0 grow text-3xl font-extrabold",
shortcuts: ["mod", "alt", "1"],
},
{
label: "Heading 2",
element: "h2",
level: 2,
className: "m-0 grow text-xl font-bold",
shortcuts: ["mod", "alt", "2"],
},
{
label: "Heading 3",
element: "h3",
level: 3,
className: "m-0 grow text-lg font-semibold",
shortcuts: ["mod", "alt", "3"],
},
{
label: "Heading 4",
element: "h4",
level: 4,
className: "m-0 grow text-base font-semibold",
shortcuts: ["mod", "alt", "4"],
},
{
label: "Heading 5",
element: "h5",
level: 5,
className: "m-0 grow text-sm font-normal",
shortcuts: ["mod", "alt", "5"],
},
{
label: "Heading 6",
element: "h6",
level: 6,
className: "m-0 grow text-sm font-normal",
shortcuts: ["mod", "alt", "6"],
},
]
interface SectionOneProps extends VariantProps<typeof toggleVariants> {
editor: Editor
activeLevels?: Level[]
}
export const SectionOne: React.FC<SectionOneProps> = React.memo(
({ editor, activeLevels = [1, 2, 3, 4, 5, 6], size, variant }) => {
const filteredActions = React.useMemo(
() =>
formatActions.filter(
(action) => !action.level || activeLevels.includes(action.level),
),
[activeLevels],
)
const handleStyleChange = React.useCallback(
(level?: Level) => {
if (level) {
editor.chain().focus().toggleHeading({ level }).run()
} else {
editor.chain().focus().setParagraph().run()
}
},
[editor],
)
const renderMenuItem = React.useCallback(
({ label, element: Element, level, className, shortcuts }: TextStyle) => (
<DropdownMenuItem
key={label}
onClick={() => handleStyleChange(level)}
className={cn("flex flex-row items-center justify-between gap-4", {
"bg-accent": level
? editor.isActive("heading", { level })
: editor.isActive("paragraph"),
})}
aria-label={label}
>
<Element className={className}>{label}</Element>
<ShortcutKey keys={shortcuts} />
</DropdownMenuItem>
),
[editor, handleStyleChange],
)
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<ToolbarButton
isActive={editor.isActive("heading")}
tooltip="Text styles"
aria-label="Text styles"
pressed={editor.isActive("heading")}
className="w-12"
disabled={editor.isActive("codeBlock")}
size={size}
variant={variant}
>
<LetterCaseCapitalizeIcon className="size-5" />
<CaretDownIcon className="size-5" />
</ToolbarButton>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-full">
{filteredActions.map(renderMenuItem)}
</DropdownMenuContent>
</DropdownMenu>
)
},
)
SectionOne.displayName = "SectionOne"
export default SectionOne

View File

@@ -0,0 +1,215 @@
import * as React from "react"
import type { Editor } from "@tiptap/react"
import type { toggleVariants } from "@/components/ui/toggle"
import type { VariantProps } from "class-variance-authority"
import { CaretDownIcon, CheckIcon } from "@radix-ui/react-icons"
import { ToolbarButton } from "../toolbar-button"
import {
Popover,
PopoverTrigger,
PopoverContent,
} from "@/components/ui/popover"
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip"
import { useTheme } from "../../hooks/use-theme"
interface ColorItem {
cssVar: string
label: string
darkLabel?: string
}
interface ColorPalette {
label: string
colors: ColorItem[]
inverse: string
}
const COLORS: ColorPalette[] = [
{
label: "Palette 1",
inverse: "hsl(var(--background))",
colors: [
{ cssVar: "hsl(var(--foreground))", label: "Default" },
{ cssVar: "var(--mt-accent-bold-blue)", label: "Bold blue" },
{ cssVar: "var(--mt-accent-bold-teal)", label: "Bold teal" },
{ cssVar: "var(--mt-accent-bold-green)", label: "Bold green" },
{ cssVar: "var(--mt-accent-bold-orange)", label: "Bold orange" },
{ cssVar: "var(--mt-accent-bold-red)", label: "Bold red" },
{ cssVar: "var(--mt-accent-bold-purple)", label: "Bold purple" },
],
},
{
label: "Palette 2",
inverse: "hsl(var(--background))",
colors: [
{ cssVar: "var(--mt-accent-gray)", label: "Gray" },
{ cssVar: "var(--mt-accent-blue)", label: "Blue" },
{ cssVar: "var(--mt-accent-teal)", label: "Teal" },
{ cssVar: "var(--mt-accent-green)", label: "Green" },
{ cssVar: "var(--mt-accent-orange)", label: "Orange" },
{ cssVar: "var(--mt-accent-red)", label: "Red" },
{ cssVar: "var(--mt-accent-purple)", label: "Purple" },
],
},
{
label: "Palette 3",
inverse: "hsl(var(--foreground))",
colors: [
{ cssVar: "hsl(var(--background))", label: "White", darkLabel: "Black" },
{ cssVar: "var(--mt-accent-blue-subtler)", label: "Blue subtle" },
{ cssVar: "var(--mt-accent-teal-subtler)", label: "Teal subtle" },
{ cssVar: "var(--mt-accent-green-subtler)", label: "Green subtle" },
{ cssVar: "var(--mt-accent-yellow-subtler)", label: "Yellow subtle" },
{ cssVar: "var(--mt-accent-red-subtler)", label: "Red subtle" },
{ cssVar: "var(--mt-accent-purple-subtler)", label: "Purple subtle" },
],
},
]
const MemoizedColorButton = React.memo<{
color: ColorItem
isSelected: boolean
inverse: string
onClick: (value: string) => void
}>(({ color, isSelected, inverse, onClick }) => {
const isDarkMode = useTheme()
const label = isDarkMode && color.darkLabel ? color.darkLabel : color.label
return (
<Tooltip>
<TooltipTrigger asChild>
<ToggleGroupItem
className="relative size-7 rounded-md p-0"
value={color.cssVar}
aria-label={label}
style={{ backgroundColor: color.cssVar }}
onClick={(e: React.MouseEvent<HTMLButtonElement>) => {
e.preventDefault()
onClick(color.cssVar)
}}
>
{isSelected && (
<CheckIcon
className="absolute inset-0 m-auto size-6"
style={{ color: inverse }}
/>
)}
</ToggleGroupItem>
</TooltipTrigger>
<TooltipContent side="bottom">
<p>{label}</p>
</TooltipContent>
</Tooltip>
)
})
MemoizedColorButton.displayName = "MemoizedColorButton"
const MemoizedColorPicker = React.memo<{
palette: ColorPalette
selectedColor: string
inverse: string
onColorChange: (value: string) => void
}>(({ palette, selectedColor, inverse, onColorChange }) => (
<ToggleGroup
type="single"
value={selectedColor}
onValueChange={(value: string) => {
if (value) onColorChange(value)
}}
className="gap-1.5"
>
{palette.colors.map((color, index) => (
<MemoizedColorButton
key={index}
inverse={inverse}
color={color}
isSelected={selectedColor === color.cssVar}
onClick={onColorChange}
/>
))}
</ToggleGroup>
))
MemoizedColorPicker.displayName = "MemoizedColorPicker"
interface SectionThreeProps extends VariantProps<typeof toggleVariants> {
editor: Editor
}
export const SectionThree: React.FC<SectionThreeProps> = ({
editor,
size,
variant,
}) => {
const color =
editor.getAttributes("textStyle")?.color || "hsl(var(--foreground))"
const [selectedColor, setSelectedColor] = React.useState(color)
const handleColorChange = React.useCallback(
(value: string) => {
setSelectedColor(value)
editor.chain().setColor(value).run()
},
[editor],
)
React.useEffect(() => {
setSelectedColor(color)
}, [color])
return (
<Popover>
<PopoverTrigger asChild>
<ToolbarButton
tooltip="Text color"
aria-label="Text color"
className="w-12"
size={size}
variant={variant}
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="size-5"
style={{ color: selectedColor }}
>
<path d="M4 20h16" />
<path d="m6 16 6-12 6 12" />
<path d="M8 12h8" />
</svg>
<CaretDownIcon className="size-5" />
</ToolbarButton>
</PopoverTrigger>
<PopoverContent align="start" className="w-full">
<div className="space-y-1.5">
{COLORS.map((palette, index) => (
<MemoizedColorPicker
key={index}
palette={palette}
inverse={palette.inverse}
selectedColor={selectedColor}
onColorChange={handleColorChange}
/>
))}
</div>
</PopoverContent>
</Popover>
)
}
SectionThree.displayName = "SectionThree"
export default SectionThree

View File

@@ -0,0 +1,115 @@
import * as React from "react"
import type { Editor } from "@tiptap/react"
import type { FormatAction } from "../../types"
import type { toggleVariants } from "@/components/ui/toggle"
import type { VariantProps } from "class-variance-authority"
import {
CodeIcon,
DotsHorizontalIcon,
FontBoldIcon,
FontItalicIcon,
StrikethroughIcon,
TextNoneIcon,
} from "@radix-ui/react-icons"
import { ToolbarSection } from "../toolbar-section"
type TextStyleAction =
| "bold"
| "italic"
| "strikethrough"
| "code"
| "clearFormatting"
interface TextStyle extends FormatAction {
value: TextStyleAction
}
const formatActions: TextStyle[] = [
{
value: "bold",
label: "Bold",
icon: <FontBoldIcon className="size-5" />,
action: (editor) => editor.chain().focus().toggleBold().run(),
isActive: (editor) => editor.isActive("bold"),
canExecute: (editor) =>
editor.can().chain().focus().toggleBold().run() &&
!editor.isActive("codeBlock"),
shortcuts: ["mod", "B"],
},
{
value: "italic",
label: "Italic",
icon: <FontItalicIcon className="size-5" />,
action: (editor) => editor.chain().focus().toggleItalic().run(),
isActive: (editor) => editor.isActive("italic"),
canExecute: (editor) =>
editor.can().chain().focus().toggleItalic().run() &&
!editor.isActive("codeBlock"),
shortcuts: ["mod", "I"],
},
{
value: "strikethrough",
label: "Strikethrough",
icon: <StrikethroughIcon className="size-5" />,
action: (editor) => editor.chain().focus().toggleStrike().run(),
isActive: (editor) => editor.isActive("strike"),
canExecute: (editor) =>
editor.can().chain().focus().toggleStrike().run() &&
!editor.isActive("codeBlock"),
shortcuts: ["mod", "shift", "S"],
},
{
value: "code",
label: "Code",
icon: <CodeIcon className="size-5" />,
action: (editor) => editor.chain().focus().toggleCode().run(),
isActive: (editor) => editor.isActive("code"),
canExecute: (editor) =>
editor.can().chain().focus().toggleCode().run() &&
!editor.isActive("codeBlock"),
shortcuts: ["mod", "E"],
},
{
value: "clearFormatting",
label: "Clear formatting",
icon: <TextNoneIcon className="size-5" />,
action: (editor) => editor.chain().focus().unsetAllMarks().run(),
isActive: () => false,
canExecute: (editor) =>
editor.can().chain().focus().unsetAllMarks().run() &&
!editor.isActive("codeBlock"),
shortcuts: ["mod", "\\"],
},
]
interface SectionTwoProps extends VariantProps<typeof toggleVariants> {
editor: Editor
activeActions?: TextStyleAction[]
mainActionCount?: number
}
export const SectionTwo: React.FC<SectionTwoProps> = ({
editor,
activeActions = formatActions.map((action) => action.value),
mainActionCount = 2,
size,
variant,
}) => {
return (
<ToolbarSection
editor={editor}
actions={formatActions}
activeActions={activeActions}
mainActionCount={mainActionCount}
dropdownIcon={<DotsHorizontalIcon className="size-5" />}
dropdownTooltip="More formatting"
dropdownClassName="w-8"
size={size}
variant={variant}
/>
)
}
SectionTwo.displayName = "SectionTwo"
export default SectionTwo

View File

@@ -0,0 +1,43 @@
import * as React from "react"
import { cn } from "@/lib/utils"
import { getShortcutKey } from "../utils"
export interface ShortcutKeyProps
extends React.HTMLAttributes<HTMLSpanElement> {
keys: string[]
}
export const ShortcutKey = React.forwardRef<HTMLSpanElement, ShortcutKeyProps>(
({ className, keys, ...props }, ref) => {
const modifiedKeys = keys.map((key) => getShortcutKey(key))
const ariaLabel = modifiedKeys
.map((shortcut) => shortcut.readable)
.join(" + ")
return (
<span
aria-label={ariaLabel}
className={cn("inline-flex items-center gap-0.5", className)}
{...props}
ref={ref}
>
{modifiedKeys.map((shortcut) => (
<kbd
key={shortcut.symbol}
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}
>
{shortcut.symbol}
</kbd>
))}
</span>
)
},
)
ShortcutKey.displayName = "ShortcutKey"

View File

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

View File

@@ -0,0 +1,120 @@
import * as React from "react"
import type { Editor } from "@tiptap/react"
import type { FormatAction } from "../types"
import type { VariantProps } from "class-variance-authority"
import type { toggleVariants } from "@/components/ui/toggle"
import { cn } from "@/lib/utils"
import { CaretDownIcon } from "@radix-ui/react-icons"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { ToolbarButton } from "./toolbar-button"
import { ShortcutKey } from "./shortcut-key"
import { getShortcutKey } from "../utils"
interface ToolbarSectionProps extends VariantProps<typeof toggleVariants> {
editor: Editor
actions: FormatAction[]
activeActions?: string[]
mainActionCount?: number
dropdownIcon?: React.ReactNode
dropdownTooltip?: string
dropdownClassName?: string
}
export const ToolbarSection: React.FC<ToolbarSectionProps> = ({
editor,
actions,
activeActions = actions.map((action) => action.value),
mainActionCount = 0,
dropdownIcon,
dropdownTooltip = "More options",
dropdownClassName = "w-12",
size,
variant,
}) => {
const { mainActions, dropdownActions } = React.useMemo(() => {
const sortedActions = actions
.filter((action) => activeActions.includes(action.value))
.sort(
(a, b) =>
activeActions.indexOf(a.value) - activeActions.indexOf(b.value),
)
return {
mainActions: sortedActions.slice(0, mainActionCount),
dropdownActions: sortedActions.slice(mainActionCount),
}
}, [actions, activeActions, mainActionCount])
const renderToolbarButton = React.useCallback(
(action: FormatAction) => (
<ToolbarButton
key={action.label}
onClick={() => action.action(editor)}
disabled={!action.canExecute(editor)}
isActive={action.isActive(editor)}
tooltip={`${action.label} ${action.shortcuts.map((s) => getShortcutKey(s).symbol).join(" ")}`}
aria-label={action.label}
size={size}
variant={variant}
>
{action.icon}
</ToolbarButton>
),
[editor, size, variant],
)
const renderDropdownMenuItem = React.useCallback(
(action: FormatAction) => (
<DropdownMenuItem
key={action.label}
onClick={() => action.action(editor)}
disabled={!action.canExecute(editor)}
className={cn("flex flex-row items-center justify-between gap-4", {
"bg-accent": action.isActive(editor),
})}
aria-label={action.label}
>
<span className="grow">{action.label}</span>
<ShortcutKey keys={action.shortcuts} />
</DropdownMenuItem>
),
[editor],
)
const isDropdownActive = React.useMemo(
() => dropdownActions.some((action) => action.isActive(editor)),
[dropdownActions, editor],
)
return (
<>
{mainActions.map(renderToolbarButton)}
{dropdownActions.length > 0 && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<ToolbarButton
isActive={isDropdownActive}
tooltip={dropdownTooltip}
aria-label={dropdownTooltip}
className={cn(dropdownClassName)}
size={size}
variant={variant}
>
{dropdownIcon || <CaretDownIcon className="size-5" />}
</ToolbarButton>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-full">
{dropdownActions.map(renderDropdownMenuItem)}
</DropdownMenuContent>
</DropdownMenu>
)}
</>
)
}
export default ToolbarSection

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,20 @@
import { Color as TiptapColor } from "@tiptap/extension-color"
import { Plugin } from "@tiptap/pm/state"
export const Color = TiptapColor.extend({
addProseMirrorPlugins() {
return [
...(this.parent?.() || []),
new Plugin({
props: {
handleKeyDown: (_, event) => {
if (event.key === "Enter") {
this.editor.commands.unsetColor()
}
return false
},
},
}),
]
},
})

View File

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

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,55 @@
import * as React from "react"
import { isNumber, NodeViewProps, NodeViewWrapper } from "@tiptap/react"
import { useImageLoad } from "../../../hooks/use-image-load"
import { cn } from "@/lib/utils"
const ImageViewBlock = ({ editor, node, getPos }: NodeViewProps) => {
const imgSize = useImageLoad(node.attrs.src)
const paddingBottom = React.useMemo(() => {
if (!imgSize.width || !imgSize.height) {
return 0
}
return (imgSize.height / imgSize.width) * 100
}, [imgSize.width, imgSize.height])
return (
<NodeViewWrapper>
<div draggable data-drag-handle>
<figure>
<div
className="relative w-full"
style={{
paddingBottom: `${isNumber(paddingBottom) ? paddingBottom : 0}%`,
}}
>
<div className="absolute h-full w-full">
<div
className={cn(
"relative h-full max-h-full w-full max-w-full rounded transition-all",
)}
style={{
boxShadow:
editor.state.selection.from === getPos()
? "0 0 0 1px hsl(var(--primary))"
: "none",
}}
>
<div className="relative flex h-full max-h-full w-full max-w-full overflow-hidden">
<img
alt={node.attrs.alt}
src={node.attrs.src}
className="absolute left-2/4 top-2/4 m-0 h-full max-w-full -translate-x-2/4 -translate-y-2/4 transform object-contain"
/>
</div>
</div>
</div>
</div>
</figure>
</div>
</NodeViewWrapper>
)
}
export { ImageViewBlock }

View File

@@ -0,0 +1,9 @@
import { Image as TiptapImage } from "@tiptap/extension-image"
import { ReactNodeViewRenderer } from "@tiptap/react"
import { ImageViewBlock } from "./components/image-view-block"
export const Image = TiptapImage.extend({
addNodeView() {
return ReactNodeViewRenderer(ImageViewBlock)
},
})

View File

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

View File

@@ -0,0 +1,8 @@
export * from "./code-block-lowlight"
export * from "./color"
export * from "./horizontal-rule"
export * from "./image"
export * from "./link"
export * from "./selection"
export * from "./unset-all-marks"
export * from "./reset-marks-on-enter"

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: (_: 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 "./reset-marks-on-enter"

View File

@@ -0,0 +1,25 @@
import { Extension } from "@tiptap/core"
export const ResetMarksOnEnter = Extension.create({
name: "resetMarksOnEnter",
addKeyboardShortcuts() {
return {
Enter: ({ editor }) => {
if (
editor.isActive("bold") ||
editor.isActive("italic") ||
editor.isActive("strike") ||
editor.isActive("underline") ||
editor.isActive("code")
) {
editor.commands.splitBlock({ keepMarks: false })
return true
}
return false
},
}
},
})

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 @@
export * from "./unset-all-marks"

View File

@@ -0,0 +1,9 @@
import { Extension } from "@tiptap/core"
export const UnsetAllMarks = Extension.create({
addKeyboardShortcuts() {
return {
"Mod-\\": () => this.editor.commands.unsetAllMarks(),
}
},
})

View File

@@ -0,0 +1,15 @@
import * as React from "react"
export const useImageLoad = (src: string) => {
const [imgSize, setImgSize] = React.useState({ width: 0, height: 0 })
React.useEffect(() => {
const img = new Image()
img.src = src
img.onload = () => {
setImgSize({ width: img.width, height: img.height })
}
}, [src])
return imgSize
}

View File

@@ -0,0 +1,111 @@
import * as React from "react"
import type { Editor } from "@tiptap/core"
import type { Content, UseEditorOptions } from "@tiptap/react"
import { StarterKit } from "@tiptap/starter-kit"
import { useEditor } from "@tiptap/react"
import { Typography } from "@tiptap/extension-typography"
import { Placeholder } from "@tiptap/extension-placeholder"
import { TextStyle } from "@tiptap/extension-text-style"
import {
Link,
Image,
HorizontalRule,
CodeBlockLowlight,
Selection,
Color,
UnsetAllMarks,
ResetMarksOnEnter,
} from "../extensions"
import { cn } from "@/lib/utils"
import { getOutput } from "../utils"
import { useThrottle } from "./use-throttle"
export interface UseMinimalTiptapEditorProps extends UseEditorOptions {
value?: Content
output?: "html" | "json" | "text"
placeholder?: string
editorClassName?: string
throttleDelay?: number
onUpdate?: (content: Content) => void
onBlur?: (content: Content) => void
}
const createExtensions = (placeholder: string) => [
StarterKit.configure({
horizontalRule: false,
codeBlock: false,
paragraph: { HTMLAttributes: { class: "text-node" } },
heading: { HTMLAttributes: { class: "heading-node" } },
blockquote: { HTMLAttributes: { class: "block-node" } },
bulletList: { HTMLAttributes: { class: "list-node" } },
orderedList: { HTMLAttributes: { class: "list-node" } },
code: { HTMLAttributes: { class: "inline", spellcheck: "false" } },
dropcursor: { width: 2, class: "ProseMirror-dropcursor border" },
}),
Link,
Image,
Color,
TextStyle,
Selection,
Typography,
UnsetAllMarks,
HorizontalRule,
ResetMarksOnEnter,
CodeBlockLowlight,
Placeholder.configure({ placeholder: () => placeholder }),
]
export const useMinimalTiptapEditor = ({
value,
output = "html",
placeholder = "",
editorClassName,
throttleDelay = 0,
onUpdate,
onBlur,
...props
}: UseMinimalTiptapEditorProps) => {
const throttledSetValue = useThrottle(
(value: Content) => onUpdate?.(value),
throttleDelay,
)
const handleUpdate = React.useCallback(
(editor: Editor) => throttledSetValue(getOutput(editor, output)),
[output, throttledSetValue],
)
const handleCreate = React.useCallback(
(editor: Editor) => {
if (value && editor.isEmpty) {
editor.commands.setContent(value)
}
},
[value],
)
const handleBlur = React.useCallback(
(editor: Editor) => onBlur?.(getOutput(editor, output)),
[output, onBlur],
)
const editor = useEditor({
extensions: createExtensions(placeholder!),
editorProps: {
attributes: {
autocomplete: "off",
autocorrect: "off",
autocapitalize: "off",
class: cn("focus:outline-none", editorClassName),
},
},
onUpdate: ({ editor }) => handleUpdate(editor),
onCreate: ({ editor }) => handleCreate(editor),
onBlur: ({ editor }) => handleBlur(editor),
...props,
})
return editor
}
export default useMinimalTiptapEditor

View File

@@ -0,0 +1,25 @@
import * as React from "react"
export const useTheme = () => {
const [isDarkMode, setIsDarkMode] = React.useState(false)
React.useEffect(() => {
const darkModeMediaQuery = window.matchMedia("(prefers-color-scheme: dark)")
setIsDarkMode(darkModeMediaQuery.matches)
const handleChange = (e: MediaQueryListEvent) => {
const newDarkMode = e.matches
setIsDarkMode(newDarkMode)
}
darkModeMediaQuery.addEventListener("change", handleChange)
return () => {
darkModeMediaQuery.removeEventListener("change", handleChange)
}
}, [])
return isDarkMode
}
export default useTheme

View File

@@ -0,0 +1,34 @@
import * as React from "react"
export function useThrottle<T extends (...args: any[]) => void>(
callback: T,
delay: number,
): (...args: Parameters<T>) => void {
const lastRan = React.useRef(Date.now())
const timeoutRef = React.useRef<NodeJS.Timeout | null>(null)
return React.useCallback(
(...args: Parameters<T>) => {
const handler = () => {
if (Date.now() - lastRan.current >= delay) {
callback(...args)
lastRan.current = Date.now()
} else {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current)
}
timeoutRef.current = setTimeout(
() => {
callback(...args)
lastRan.current = Date.now()
},
delay - (Date.now() - lastRan.current),
)
}
}
handler()
},
[callback, delay],
)
}

View File

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

View File

@@ -0,0 +1,103 @@
import * as React from "react"
import "./styles/index.css"
import type { Content, Editor } from "@tiptap/react"
import type { UseMinimalTiptapEditorProps } from "./hooks/use-minimal-tiptap"
import { EditorContent } from "@tiptap/react"
import { Separator } from "@/components/ui/separator"
import { cn } from "@/lib/utils"
import { SectionOne } from "./components/section/one"
import { SectionTwo } from "./components/section/two"
import { SectionThree } from "./components/section/three"
import { SectionFour } from "./components/section/four"
import { SectionFive } from "./components/section/five"
import { LinkBubbleMenu } from "./components/bubble-menu/link-bubble-menu"
import { ImageBubbleMenu } from "./components/bubble-menu/image-bubble-menu"
import { useMinimalTiptapEditor } from "./hooks/use-minimal-tiptap"
export interface MinimalTiptapProps
extends Omit<UseMinimalTiptapEditorProps, "onUpdate"> {
value?: Content
onChange?: (value: Content) => void
className?: string
editorContentClassName?: string
}
const Toolbar = ({ editor }: { editor: Editor }) => (
<div className="shrink-0 overflow-x-auto border-b border-border p-2">
<div className="flex w-max items-center gap-px">
<SectionOne editor={editor} activeLevels={[1, 2, 3, 4, 5, 6]} />
<Separator orientation="vertical" className="mx-2 h-7" />
<SectionTwo
editor={editor}
activeActions={[
"bold",
"italic",
"strikethrough",
"code",
"clearFormatting",
]}
mainActionCount={2}
/>
<Separator orientation="vertical" className="mx-2 h-7" />
<SectionThree editor={editor} />
<Separator orientation="vertical" className="mx-2 h-7" />
<SectionFour
editor={editor}
activeActions={["orderedList", "bulletList"]}
mainActionCount={0}
/>
<Separator orientation="vertical" className="mx-2 h-7" />
<SectionFive
editor={editor}
activeActions={["codeBlock", "blockquote", "horizontalRule"]}
mainActionCount={0}
/>
</div>
</div>
)
export const MinimalTiptapEditor = React.forwardRef<
HTMLDivElement,
MinimalTiptapProps
>(({ value, onChange, className, editorContentClassName, ...props }, ref) => {
const editor = useMinimalTiptapEditor({
value,
onUpdate: onChange,
...props,
})
if (!editor) {
return null
}
return (
<div
ref={ref}
className={cn(
"flex h-auto min-h-72 w-full flex-col rounded-md border border-input shadow-sm focus-within:border-primary",
className,
)}
>
<Toolbar editor={editor} />
<EditorContent
editor={editor}
className={cn("minimal-tiptap-editor", editorContentClassName)}
/>
<LinkBubbleMenu editor={editor} />
<ImageBubbleMenu editor={editor} />
</div>
)
})
MinimalTiptapEditor.displayName = "MinimalTiptapEditor"
export default MinimalTiptapEditor

View File

@@ -0,0 +1,182 @@
@import "./partials/code.css";
@import "./partials/placeholder.css";
@import "./partials/lists.css";
@import "./partials/typography.css";
:root {
--mt-font-size-regular: 0.9375rem;
--mt-code-background: #082b781f;
--mt-code-color: #d4d4d4;
--mt-secondary: #9d9d9f;
--mt-pre-background: #ececec;
--mt-pre-border: #e0e0e0;
--mt-pre-color: #2f2f31;
--mt-hr: #dcdcdc;
--mt-drag-handle-hover: #5c5c5e;
--mt-accent-bold-blue: #05c;
--mt-accent-bold-teal: #206a83;
--mt-accent-bold-green: #216e4e;
--mt-accent-bold-orange: #a54800;
--mt-accent-bold-red: #ae2e24;
--mt-accent-bold-purple: #5e4db2;
--mt-accent-gray: #758195;
--mt-accent-blue: #1d7afc;
--mt-accent-teal: #2898bd;
--mt-accent-green: #22a06b;
--mt-accent-orange: #fea362;
--mt-accent-red: #c9372c;
--mt-accent-purple: #8270db;
--mt-accent-blue-subtler: #cce0ff;
--mt-accent-teal-subtler: #c6edfb;
--mt-accent-green-subtler: #baf3db;
--mt-accent-yellow-subtler: #f8e6a0;
--mt-accent-red-subtler: #ffd5d2;
--mt-accent-purple-subtler: #dfd8fd;
--hljs-string: #aa430f;
--hljs-title: #b08836;
--hljs-comment: #999999;
--hljs-keyword: #0c5eb1;
--hljs-attr: #3a92bc;
--hljs-literal: #c82b0f;
--hljs-name: #259792;
--hljs-selector-tag: #c8500f;
--hljs-number: #3da067;
}
.dark {
--mt-font-size-regular: 0.9375rem;
--mt-code-background: #ffffff13;
--mt-code-color: #2c2e33;
--mt-secondary: #595a5c;
--mt-pre-background: #080808;
--mt-pre-border: #23252a;
--mt-pre-color: #e3e4e6;
--mt-hr: #26282d;
--mt-drag-handle-hover: #969799;
--mt-accent-bold-blue: #85b8ff;
--mt-accent-bold-teal: #9dd9ee;
--mt-accent-bold-green: #7ee2b8;
--mt-accent-bold-orange: #fec195;
--mt-accent-bold-red: #fd9891;
--mt-accent-bold-purple: #b8acf6;
--mt-accent-gray: #738496;
--mt-accent-blue: #388bff;
--mt-accent-teal: #42b2d7;
--mt-accent-green: #2abb7f;
--mt-accent-orange: #a54800;
--mt-accent-red: #e2483d;
--mt-accent-purple: #8f7ee7;
--mt-accent-blue-subtler: #09326c;
--mt-accent-teal-subtler: #164555;
--mt-accent-green-subtler: #164b35;
--mt-accent-yellow-subtler: #533f04;
--mt-accent-red-subtler: #5d1f1a;
--mt-accent-purple-subtler: #352c63;
--hljs-string: #da936b;
--hljs-title: #f1d59d;
--hljs-comment: #aaaaaa;
--hljs-keyword: #6699cc;
--hljs-attr: #90cae8;
--hljs-literal: #f2777a;
--hljs-name: #5fc0a0;
--hljs-selector-tag: #e8c785;
--hljs-number: #b6e7b6;
}
.minimal-tiptap-editor .ProseMirror {
@apply flex max-w-full flex-1 cursor-text flex-col;
@apply z-0 outline-0;
}
.minimal-tiptap-editor .ProseMirror > div.editor {
@apply block flex-1 whitespace-pre-wrap;
}
.minimal-tiptap-editor .ProseMirror .block-node:not(:last-child),
.minimal-tiptap-editor .ProseMirror .list-node:not(:last-child),
.minimal-tiptap-editor .ProseMirror .text-node:not(:last-child) {
@apply mb-2.5;
}
.minimal-tiptap-editor .ProseMirror ol,
.minimal-tiptap-editor .ProseMirror ul {
@apply pl-6;
}
.minimal-tiptap-editor .ProseMirror blockquote,
.minimal-tiptap-editor .ProseMirror dl,
.minimal-tiptap-editor .ProseMirror ol,
.minimal-tiptap-editor .ProseMirror p,
.minimal-tiptap-editor .ProseMirror pre,
.minimal-tiptap-editor .ProseMirror ul {
@apply m-0;
}
.minimal-tiptap-editor .ProseMirror li {
@apply leading-7;
}
.minimal-tiptap-editor .ProseMirror p {
@apply break-words;
}
.minimal-tiptap-editor .ProseMirror li .text-node:has(+ .list-node),
.minimal-tiptap-editor .ProseMirror li > .list-node,
.minimal-tiptap-editor .ProseMirror li > .text-node,
.minimal-tiptap-editor .ProseMirror li p {
@apply mb-0;
}
.minimal-tiptap-editor .ProseMirror blockquote {
@apply relative pl-3.5;
}
.minimal-tiptap-editor .ProseMirror blockquote::before,
.minimal-tiptap-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-[''];
}
.minimal-tiptap-editor .ProseMirror hr {
@apply my-3 h-0.5 w-full border-none bg-[var(--mt-hr)];
}
.minimal-tiptap-editor .ProseMirror-focused hr.ProseMirror-selectednode {
@apply rounded-full outline outline-2 outline-offset-1 outline-muted-foreground;
}
.minimal-tiptap-editor .ProseMirror .ProseMirror-gapcursor {
@apply pointer-events-none absolute hidden;
}
.minimal-tiptap-editor .ProseMirror .ProseMirror-hideselection {
@apply caret-transparent;
}
.minimal-tiptap-editor .ProseMirror.resize-cursor {
@apply cursor-col-resize;
}
.minimal-tiptap-editor .ProseMirror .selection {
@apply inline-block;
}
.minimal-tiptap-editor .ProseMirror .selection,
.minimal-tiptap-editor .ProseMirror *::selection,
::selection {
@apply bg-primary/25;
}
/* Override native selection when custom selection is present */
.minimal-tiptap-editor .ProseMirror .selection::selection {
background: transparent;
}

Some files were not shown because too many files have changed in this diff Show More