feat: editor toolbar clear

This commit is contained in:
DIYgod
2023-08-25 00:38:11 +01:00
parent e7b697b243
commit b3bf66f972
27 changed files with 46 additions and 59 deletions
+1 -1
View File
@@ -8,9 +8,9 @@ import { EditorView } from "@codemirror/view"
import { useAccountState } from "@crossbell/connect-kit"
import { Popover } from "@headlessui/react"
import { editorUpload } from "~/components/dashboard/toolbars/Multimedia"
import { Avatar } from "~/components/ui/Avatar"
import { Button } from "~/components/ui/Button"
import { editorUpload } from "~/editor/Multimedia"
import { useUploadFile } from "~/hooks/useUploadFile"
import { useTranslation } from "~/lib/i18n/client"
import {
@@ -5,8 +5,8 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { EditorView } from "@codemirror/view"
import { toolbarShortcuts } from "~/editor"
import { editorUpload } from "~/editor/Multimedia"
import { toolbarShortcuts } from "~/components/dashboard/toolbars"
import { editorUpload } from "~/components/dashboard/toolbars/Multimedia"
import { useIsMobileLayout } from "~/hooks/useMobileLayout"
import { useUploadFile } from "~/hooks/useUploadFile"
import { useTranslation } from "~/lib/i18n/client"
@@ -5,21 +5,11 @@ import { usePopper } from "react-popper"
import { EditorView } from "@codemirror/view"
import { Popover } from "@headlessui/react"
import type { ICommand } from "~/editor"
import { Tooltip } from "~/components/ui/Tooltip"
import { useTranslation } from "~/lib/i18n/client"
import { isMacOS } from "~/lib/utils"
import { Tooltip } from "./Tooltip"
export interface EditorToolbarProps {
view?: EditorView
toolbars: ICommand[]
}
enum ToolbarMode {
Normal,
Preview,
}
import { type ICommand, toolbars } from "./toolbars"
type IToolbarItemProps = ICommand<any> & { view?: EditorView }
@@ -91,56 +81,54 @@ const ToolbarItemWithPopover = ({
)
}
export const EditorToolbar = memo(({ view, toolbars }: EditorToolbarProps) => {
export const EditorToolbar = memo(({ view }: { view?: EditorView }) => {
const { t } = useTranslation("dashboard")
const renderToolbar = useCallback(
(mode: ToolbarMode) =>
// eslint-disable-next-line react/display-name
({ name, icon, label, execute, ui, shortcut }: ICommand) => {
return ui ? (
<ToolbarItemWithPopover
({ name, icon, label, execute, ui, shortcut }: ICommand) => {
return ui ? (
<ToolbarItemWithPopover
key={name}
name={name}
icon={icon}
label={label}
execute={execute}
ui={ui}
view={view}
shortcut={shortcut}
/>
) : (
<Tooltip
key={name}
label={`${t(label)}${keyDisplay(shortcut)}`}
placement="bottom"
>
<button
key={name}
name={name}
icon={icon}
label={label}
execute={execute}
ui={ui}
view={view}
shortcut={shortcut}
/>
) : (
<Tooltip
key={name}
label={`${t(label)}${keyDisplay(shortcut)}`}
placement="bottom"
title={name}
type="button"
className={
"w-9 h-9 transition-colors text-lg border border-transparent rounded flex items-center justify-center text-zinc-500 group-hover:text-zinc-600 hover:text-zinc-500 hover:border-zinc-300 hover:bg-zinc-100"
}
onClick={() => {
view &&
execute({
view,
options: { container: view.dom },
})
}}
>
<button
key={name}
title={name}
type="button"
className={
"w-9 h-9 transition-colors text-lg border border-transparent rounded flex items-center justify-center text-zinc-500 group-hover:text-zinc-600 hover:text-zinc-500 hover:border-zinc-300 hover:bg-zinc-100"
}
onClick={() => {
view &&
execute({
view,
options: { container: view.dom },
})
}}
>
<span className={icon}></span>
</button>
</Tooltip>
)
},
<span className={icon}></span>
</button>
</Tooltip>
)
},
[view, t],
)
return (
<div className="flex group">
<div className="flex-1 flex space-x-1">
{toolbars?.map(renderToolbar(ToolbarMode.Normal))}
{toolbars?.map(renderToolbar)}
</div>
</div>
)
@@ -0,0 +1,10 @@
import { ICommand, wrapExecute } from "."
export const AlignCenter: ICommand = {
name: "align center",
label: "Align Center",
icon: "icon-[mingcute--align-center-line]",
execute: ({ view }) => {
wrapExecute({ view, prepend: ":p[", append: "]{.center}" })
},
}
@@ -0,0 +1,10 @@
import { ICommand, wrapExecute } from "."
export const AlignRight: ICommand = {
name: "align right",
label: "Align Right",
icon: "icon-[mingcute--align-right-line]",
execute: ({ view }) => {
wrapExecute({ view, prepend: ":p[", append: "]{.right}" })
},
}
@@ -0,0 +1,23 @@
import { type EditorView } from "@codemirror/view"
import { type ICommand, wrapExecute } from "."
const action = (view: EditorView) => {
wrapExecute({ view, prepend: "**", append: "**" })
}
export const Bold: ICommand = {
name: "bold",
label: "Bold",
icon: "icon-[mingcute--bold-line]",
execute({ view }) {
action(view)
},
shortcut: {
key: "Mod-b",
run(view) {
action(view)
return true
},
},
}
@@ -0,0 +1,72 @@
import toast from "react-hot-toast"
import { UploadFile } from "~/lib/upload-file"
import { ICommand } from "."
const uploadResources = async (text: string) => {
const markdownHttpImagesRegex = /\!\[([^\]]*)\]\((?=(https:\/\/))([^)]+)\)/g
const markdownHttpImageRegex = /\!\[([^\]]*)\]\((?=(https:\/\/))([^)]+)\)/
const markdownHttpImages = text.match(markdownHttpImagesRegex)
if (markdownHttpImages) {
const markdownReplacementsArray = await Promise.all(
markdownHttpImages.map(async (markdownHttpImage) => {
const match = markdownHttpImage.match(markdownHttpImageRegex)!
const altText = match[1]
const url = match[3]
const toastId = toast.loading(`Uploading ${altText || url}`)
try {
const response = await fetch(url)
if (!response.ok) {
throw new Error(response.statusText)
}
const blob = await response.blob()
const key = (await UploadFile(blob)).key
toast.success(`Uploaded ${altText || url}!`, {
id: toastId,
})
return {
originalMarkdown: markdownHttpImage,
newMarkdown: `![${altText}](${key})`,
}
} catch (error) {
if (error instanceof Error) {
toast.error(`Failed upload ${altText || url}, ${error.message}`, {
id: toastId,
})
}
console.error(error)
return undefined
}
}),
)
return markdownReplacementsArray.reduce(
(prev, cur) =>
cur ? prev.replace(cur.originalMarkdown, cur.newMarkdown) : prev,
text,
)
} else {
return text
}
}
export const Cloud: ICommand = {
name: "cloud",
label: "Upload All Images to IPFS",
icon: "icon-[mingcute--upload-3-line]",
execute: async ({ view }) => {
const docJson = view.state.doc.toJSON()
const newDocJson = await Promise.all(
docJson.map((line: string) => uploadResources(line)),
)
view.dispatch({
changes: [
{
from: 0,
to: view.state.doc.toString().length,
insert: newDocJson.join("\n"),
},
],
})
},
}
@@ -0,0 +1,10 @@
import { ICommand, wrapExecute } from "."
export const Code: ICommand = {
name: "code",
label: "Inline Code",
icon: "icon-[mingcute--code-line]",
execute: ({ view }) => {
wrapExecute({ view, prepend: "`", append: "`" })
},
}
@@ -0,0 +1,10 @@
import { ICommand, wrapExecute } from "."
export const CodeBlock: ICommand = {
name: "codeblock",
label: "Code Block",
icon: "icon-[mingcute--web-line]",
execute: ({ view }) => {
wrapExecute({ view, prepend: "```\n", append: "\n```" })
},
}
@@ -0,0 +1,15 @@
import { EmojiPicker } from "~/components/common/EmojiPicker"
import { ICommand, wrapExecute } from "."
export const Emoji: ICommand<string> = {
name: "emoji",
label: "Emoji",
icon: "icon-[mingcute--emoji-2-line]",
execute: ({ view, payload }) => {
wrapExecute({ view, prepend: payload || "", append: "" })
},
ui: ({ transferPayload }) => (
<EmojiPicker onEmojiSelect={(e: any) => transferPayload(e.native)} />
),
}
@@ -0,0 +1,10 @@
import { ICommand, wrapExecute } from "."
export const Formula: ICommand = {
name: "formula",
label: "Formula",
icon: "icon-[mingcute--formula-line]",
execute: ({ view }) => {
wrapExecute({ view, prepend: "$$ ", append: " $$" })
},
}
@@ -0,0 +1,10 @@
import { ICommand, prependExecute } from "."
export const Heading: ICommand = {
name: "heading",
label: "Heading",
icon: "icon-[mingcute--heading-2-line]",
execute: ({ view }) => {
prependExecute({ view, prepend: "## " })
},
}
@@ -0,0 +1,16 @@
import { getSiteLink } from "~/lib/helpers"
import { ICommand } from "."
export const Help: ICommand = {
name: "help",
label: "Help: Markdown syntax and components used by xLog",
icon: "icon-[mingcute--question-line]",
execute: ({ view }) => {
window.open(
`${getSiteLink({
subdomain: "xlog",
})}/xfm`,
)
},
}
@@ -0,0 +1,23 @@
import { type EditorView } from "@codemirror/view"
import { type ICommand, wrapExecute } from "."
const action = (view: EditorView) => {
wrapExecute({ view, prepend: "_", append: "_" })
}
export const Italic: ICommand = {
name: "italic",
label: "Italic",
icon: "icon-[mingcute--italic-line]",
execute({ view }) {
action(view)
},
shortcut: {
key: "Mod-i",
run(view) {
action(view)
return true
},
},
}
@@ -0,0 +1,23 @@
import { type EditorView } from "@codemirror/view"
import { type ICommand, wrapExecute } from "."
const action = (view: EditorView) => {
wrapExecute({ view, prepend: "[", append: "]()" })
}
export const Link: ICommand = {
name: "link",
label: "Link",
icon: "icon-[mingcute--link-2-line]",
execute({ view }) {
action(view)
},
shortcut: {
key: "Mod-k",
run(view) {
action(view)
return true
},
},
}
@@ -0,0 +1,10 @@
import { ICommand, wrapExecute } from "."
export const ListOrdered: ICommand = {
name: "list-ordered",
label: "Ordered List",
icon: "icon-[mingcute--list-ordered-line]",
execute: ({ view }) => {
wrapExecute({ view, prepend: "1. ", append: "\n" })
},
}
@@ -0,0 +1,10 @@
import { ICommand, wrapExecute } from "."
export const ListUnordered: ICommand = {
name: "list-unordered",
label: "Unordered List",
icon: "icon-[mingcute--list-check-line]",
execute: ({ view }) => {
wrapExecute({ view, prepend: "- ", append: "\n" })
},
}
@@ -0,0 +1,10 @@
import { ICommand, wrapExecute } from "."
export const Mention: ICommand = {
name: "mention",
label: "Mention",
icon: "icon-[mingcute--at-line]",
execute: ({ view }) => {
wrapExecute({ view, prepend: "@", append: "" })
},
}
@@ -0,0 +1,115 @@
import NodeID3 from "node-id3"
import toast from "react-hot-toast"
import { type EditorView } from "@codemirror/view"
import { MAXIMUM_FILE_SIZE } from "~/lib/constants"
import { UploadFile } from "~/lib/upload-file"
import type { ICommand } from "."
import { wrapExecute } from "./helper"
export async function editorUpload(file: File, view: EditorView) {
const toastId = toast.loading("Uploading...")
try {
if (
!file.type.startsWith("image/") &&
!file.type.startsWith("audio/") &&
!file.type.startsWith("video/")
) {
throw new Error("You can only upload images, audios and videos")
}
const uploadFilesizeInMB = file.size / 1024 / 1024
if (uploadFilesizeInMB > MAXIMUM_FILE_SIZE) {
toast.error(
`File Size is too big. It should be less than ${MAXIMUM_FILE_SIZE} MB`,
{
id: toastId,
},
)
return
}
const { key } = await UploadFile(file)
toast.success("Uploaded!", {
id: toastId,
})
if (file.type.startsWith("image/")) {
wrapExecute({
view,
prepend: "",
append: `
![${file.name.replace(/\.\w+$/, "")}](${key})
`,
})
} else if (file.type.startsWith("audio/")) {
const fileArrayBuffer = await file.arrayBuffer()
const fileBuffer = Buffer.from(fileArrayBuffer)
const tags = NodeID3.read(fileBuffer)
const name = tags.title ?? file.name
const artist = tags.artist
const cover = await (async () => {
const image = tags.image
if (!image || typeof image === "string") return image
const toastId = toast.loading("Uploading cover...")
const { key } = await UploadFile(
new Blob([image.imageBuffer], { type: image.type.name }),
)
toast.success("Uploaded cover!", {
id: toastId,
})
return key
})()
wrapExecute({
view,
prepend: "",
append: `
<audio src="${key}" name="${name}" ${artist ? `artist="${artist}"` : ""} ${
cover ? `cover="${cover}"` : ""
}></audio>
`,
})
} else if (file.type.startsWith("video/")) {
wrapExecute({
view,
prepend: "",
append: `
<video>
<source src="${key}" type="${file.type}" />
</video>
`,
})
} else if (file.type === "text/plain") {
wrapExecute({
view,
prepend: "",
append: key,
})
} else {
throw new Error("Unknown upload file type")
}
} catch (error) {
if (error instanceof Error) {
toast.error(error.message, { id: toastId })
}
}
}
export const Multimedia: ICommand = {
name: "upload-multimedia",
label: "Upload Image, Audio or Video",
icon: "icon-[mingcute--photo-album-line]",
execute: ({ view }) => {
const input = document.createElement("input")
input.type = "file"
input.addEventListener("change", async (e: any) => {
const file = e.target?.files?.[0]
await editorUpload(file, view)
input.remove()
})
input.click()
},
}
@@ -0,0 +1,10 @@
import { ICommand, wrapExecute } from "."
export const Quote: ICommand = {
name: "quote",
label: "Quote",
icon: "icon-[mingcute--quote-left-fill]",
execute: ({ view }) => {
wrapExecute({ view, prepend: "> ", append: "\n" })
},
}
@@ -0,0 +1,10 @@
import { ICommand, wrapExecute } from "."
export const Strikethrough: ICommand = {
name: "strikethrough",
label: "Strikethrough",
icon: "icon-[mingcute--strikethrough-line]",
execute: ({ view }) => {
wrapExecute({ view, prepend: "~~", append: "~~" })
},
}
@@ -0,0 +1,23 @@
import { type EditorView } from "@codemirror/view"
import { type ICommand, wrapExecute } from "."
const action = (view: EditorView) => {
wrapExecute({ view, prepend: "<u>", append: "</u>" })
}
export const Underline: ICommand = {
name: "underline",
label: "Underline",
icon: "icon-[mingcute--underline-line]",
execute: ({ view }) => {
action(view)
},
shortcut: {
key: "Mod-u",
run(view) {
action(view)
return true
},
},
}
@@ -0,0 +1,47 @@
import { EditorSelection } from "@codemirror/state"
import { EditorView } from "@codemirror/view"
export type IWrapExecute = {
view: EditorView
prepend: string
append: string
}
export const wrapExecute = ({ view, prepend, append }: IWrapExecute) => {
const range = view.state.selection.ranges[0]
const selection = view.state.sliceDoc(
range.from - prepend.length,
range.to + append.length,
)
if (selection.startsWith(prepend) && selection.endsWith(append)) {
view.dispatch(
view.state.changeByRange((range) => ({
changes: [
{
from: range.from - prepend.length,
to: range.to + append.length,
insert: view.state.sliceDoc(range.from, range.to),
},
],
range: EditorSelection.range(
range.from - prepend.length,
range.to - prepend.length,
),
})),
)
view.focus()
return
}
view.dispatch(
view.state.changeByRange((range) => ({
changes: [
{ from: range.from, insert: prepend },
{ from: range.to, insert: append },
],
range: EditorSelection.range(
range.from + prepend.length,
range.to + prepend.length,
),
})),
)
view.focus()
}
+116
View File
@@ -0,0 +1,116 @@
import { Dispatch, SetStateAction } from "react"
import { EditorSelection } from "@codemirror/state"
import { type EditorView, type KeyBinding } from "@codemirror/view"
import { AlignCenter } from "./AlignCenter"
import { AlignRight } from "./AlignRight"
import { Bold } from "./Bold"
import { Cloud } from "./Cloud"
import { Code } from "./Code"
import { CodeBlock } from "./CodeBlock"
import { Emoji } from "./Emoji"
import { Formula } from "./Formula"
import { Heading } from "./Heading"
import { Help } from "./Help"
import { Italic } from "./Italic"
import { Link } from "./Link"
import { ListOrdered } from "./ListOrdered"
import { ListUnordered } from "./ListUnordered"
import { Mention } from "./Mention"
import { Multimedia } from "./Multimedia"
import { Quote } from "./Quote"
import { Strikethrough } from "./Strikethrough"
import { Underline } from "./Underline"
export type ICommand<P = any> = {
icon: string
name: string
label: string
execute: (_: {
view: EditorView
options?: {
setPreviewVisible?: Dispatch<SetStateAction<boolean>>
container?: HTMLElement | null
}
payload?: P
}) => void
// While the `ui` field exists, the ui component will be rendered in a popover first,
// then you can call `transferPayload` to transfer the payload to the `execute` function.
// You can find a sample usage in `./Emoji.tsx`.
ui?: (props: {
transferPayload: (payload: P) => void
view: EditorView
}) => JSX.Element
shortcut?: KeyBinding
}
export type IPrependExecute = {
view: EditorView
prepend: string
}
export const prependExecute = ({ view, prepend }: IPrependExecute) => {
const range = view.state.selection.ranges[0]
const selection = view.state.sliceDoc(range.from - prepend.length, range.to)
if (selection.startsWith(prepend)) {
view.dispatch(
view.state.changeByRange((range) => ({
changes: [
{
from: range.from - prepend.length,
to: range.to,
insert: view.state.sliceDoc(range.from, range.to),
},
],
range: EditorSelection.range(
range.from - prepend.length,
range.to - prepend.length,
),
})),
)
view.focus()
return
}
view.dispatch(
view.state.changeByRange((range) => {
return {
changes: [{ from: range.from, insert: prepend }],
range: EditorSelection.range(
range.from + prepend.length,
range.to + prepend.length,
),
}
}),
)
view.focus()
}
export const toolbars: ICommand[] = [
Heading,
Bold,
Italic,
Strikethrough,
Underline,
Quote,
AlignCenter,
AlignRight,
Code,
CodeBlock,
ListUnordered,
ListOrdered,
Link,
Multimedia,
Mention,
Formula,
Emoji,
Cloud,
Help,
]
export const toolbarShortcuts = toolbars
.map((t) => t.shortcut)
.filter(<T,>(v: T): v is NonNullable<T> => !!v)
export { wrapExecute } from "./helper"
export type { IWrapExecute } from "./helper"
@@ -0,0 +1,70 @@
import { type CharacterEntity } from "crossbell"
import { type Completion, autocompletion } from "@codemirror/autocomplete"
import { indexer } from "@crossbell/indexer"
import { getDefaultAvatarIpfsUrl } from "@crossbell/ui"
import {
extractCharacterAvatar,
extractCharacterName,
} from "@crossbell/util-metadata"
import { toGateway } from "~/lib/ipfs-parser"
async function fetchCharacters(query: string) {
return (await indexer.search.characters(query, { limit: 10 })).list
}
type CompletionWithCharacter = Completion & { character?: CharacterEntity }
export function mentionAutocompletion() {
return autocompletion({
icons: false,
addToOptions: [
{
render({ character }: CompletionWithCharacter) {
if (!character) return null
const container = document.createElement("div")
const img = document.createElement("img")
container.className =
"inline-flex items-center justify-center pr-1 py-1 align-middle"
img.className = "w-5 h-5 object-cover rounded-md"
img.src = toGateway(
extractCharacterAvatar(character) ??
getDefaultAvatarIpfsUrl(character.handle),
)
container.appendChild(img)
return container
},
position: 20,
},
],
override: [
async (context) => {
let word = context.matchBefore(/@\w+/)
if (!word) return null
const characters = await fetchCharacters(word.text.slice(1))
const completions: Completion[] = characters.map((character) => {
const handle = `@${character.handle}`
const characterName = extractCharacterName(character, {
fallbackToHandle: false,
})
return {
label: handle,
detail: characterName,
apply: `${handle} `,
character,
}
})
return { from: word.from, options: completions }
},
],
})
}
+1 -1
View File
@@ -39,7 +39,7 @@ import {
import { tags } from "@lezer/highlight"
import { scroll } from "@uiw/codemirror-extensions-events"
import { mentionAutocompletion } from "~/editor/mention-autocompletion"
import { mentionAutocompletion } from "~/components/dashboard/toolbars/mention-autocompletion"
import {
codemirrorReconfigureExtension,
monospaceFonts,