feat(editor): drop image to upload

This commit is contained in:
EGOIST
2022-05-08 12:47:33 +08:00
parent fea7bbf09c
commit d022ef19cf
7 changed files with 164 additions and 54 deletions
+25 -4
View File
@@ -21,6 +21,7 @@ import {
indentOnInput,
syntaxHighlighting,
} from "@codemirror/language"
import { IS_PROD } from "~/lib/constants"
const theme = EditorView.theme({
".cm-scroller": {
@@ -36,11 +37,17 @@ const theme = EditorView.theme({
},
})
export const Editor: React.FC<{
export const useEditor = ({
value,
onChange,
placeholder,
onDropFile,
}: {
value: string
onChange: (value: string) => void
placeholder?: string
}> = ({ value, onChange, placeholder }) => {
onDropFile?: (file: File, view: EditorView) => void
}) => {
const editorRef = useRef<HTMLDivElement | null>(null)
const [view, setView] = useState<EditorView | null>(null)
@@ -70,6 +77,14 @@ export const Editor: React.FC<{
placeholderExtension(placeholder || ""),
syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
theme,
EditorView.domEventHandlers({
drop(e) {
const file = e.dataTransfer?.items[0]?.getAsFile()
if (!file) return
onDropFile?.(file, view)
},
}),
],
}),
parent: editorRef.current!,
@@ -81,17 +96,23 @@ export const Editor: React.FC<{
view.destroy()
setView(null)
}
}, [onChange, placeholder])
}, [onChange, placeholder, onDropFile])
// Update view state when `value` changed
useEffect(() => {
const currentValue = view ? view.state.doc.toString() : ""
if (view && value !== currentValue) {
if (!IS_PROD) {
console.log("updating editor value", value)
}
view.dispatch({
changes: { from: 0, to: currentValue.length, insert: value || "" },
})
}
}, [value, view])
return <div ref={editorRef}></div>
return {
view,
editorRef,
}
}
+22
View File
@@ -1,10 +1,32 @@
import Markdown from "markdown-it"
import { getUserContentsUrl } from "./user-contents"
const isExternLink = (url: string) => /^https?:\/\//.test(url)
const handleImages = (md: Markdown) => {
const imageRule = md.renderer.rules.image!
md.renderer.rules.image = (tokens, idx, options, env, self) => {
const token = tokens[idx]
const url = token.attrGet("src")
// Don't allow images from other domains.
if (!url || isExternLink(url)) {
return ""
}
token.attrSet("src", getUserContentsUrl(url))
return imageRule(tokens, idx, options, env, self)
}
}
export const renderPageContent = async (content: string) => {
const md = new Markdown({
html: false,
linkify: true,
})
md.use(handleImages)
const html = md.render(content)
return { html }
}
+26
View File
@@ -0,0 +1,26 @@
import {
unstable_parseMultipartFormData,
type UploadHandler,
} from "@remix-run/node"
import { nanoid } from "nanoid"
import { s3uploadFile } from "./s3.server"
export const uploadImage = async (
request: Request,
{ userId }: { userId: string }
) => {
const uploadHandler: UploadHandler = async ({ stream, mimetype }) => {
const chunks = []
for await (let chunk of stream) {
chunks.push(chunk)
}
const buffer = Buffer.concat(chunks)
const filename = `${userId}/${nanoid()}.jpg`
await s3uploadFile(filename, buffer, mimetype)
return filename
}
const formData = await unstable_parseMultipartFormData(request, uploadHandler)
return Object.fromEntries(formData)
}
+5 -23
View File
@@ -1,40 +1,22 @@
import {
type ActionFunction,
unstable_parseMultipartFormData,
type UploadHandler,
} from "@remix-run/node"
import { nanoid } from "nanoid"
import { type ActionFunction } from "@remix-run/node"
import { z } from "zod"
import { siteController } from "~/controllers/site.controller"
import { getAuthUser } from "~/lib/auth.server"
import { s3uploadFile } from "~/lib/s3.server"
import { uploadImage } from "~/lib/upload.server"
import { userModel } from "~/models/user.model"
export const action: ActionFunction = async ({ request }) => {
try {
const user = await getAuthUser(request, true)
const uploadHandler: UploadHandler = async ({ stream }) => {
const chunks = []
for await (let chunk of stream) {
chunks.push(chunk)
}
const buffer = Buffer.concat(chunks)
const filename = `${user.id}/${nanoid()}.jpg`
await s3uploadFile(filename, buffer, "image/jpeg")
return filename
}
const formData = await unstable_parseMultipartFormData(
request,
uploadHandler
)
const data = await uploadImage(request, { userId: user.id })
const values = z
.object({
file: z.string(),
site: z.string().optional(),
})
.parse(Object.fromEntries(formData))
.parse(data)
if (values.site) {
await siteController.updateSite(user, {
+24
View File
@@ -0,0 +1,24 @@
import { type ActionFunction } from "@remix-run/node"
import { z } from "zod"
import { getAuthUser } from "~/lib/auth.server"
import { uploadImage } from "~/lib/upload.server"
export const action: ActionFunction = async ({ request }) => {
try {
const user = await getAuthUser(request, true)
const data = await uploadImage(request, { userId: user.id })
const values = z
.object({
file: z.string(),
})
.parse(data)
return { file: values.file }
} catch (error: any) {
console.error(error)
return {
error: error.message,
}
}
}
+53 -24
View File
@@ -21,7 +21,8 @@ import { z } from "zod"
import toast from "react-hot-toast"
import { Input } from "~/components/ui/Input"
import { getSiteLink } from "~/lib/helpers"
import { Editor } from "~/components/ui/Editor"
import { useEditor } from "~/components/ui/Editor"
import { type EditorView } from "@codemirror/view"
export const loader: LoaderFunction = async ({ request, params }) => {
const user = await getAuthUser(request)
@@ -44,7 +45,6 @@ export const loader: LoaderFunction = async ({ request, params }) => {
export const action: ActionFunction = async ({ request, params }) => {
const isDelete = request.method === "delete"
const user = await getAuthUser(request)
const url = new URL(request.url)
if (!user) return redirect("/")
@@ -103,11 +103,11 @@ export default function SubdomainEditor() {
publishedAt: page?.publishedAt || null,
})
const [values, setValues] = useState({
title: "",
content: "",
publishedAt: new Date(),
published: false,
slug: "",
title: page.title,
content: page.content,
publishedAt: page.publishedAt,
published: page.published,
slug: page.slug,
})
const updateValue = (field: string, value: any) => {
setValues((values) => {
@@ -118,18 +118,6 @@ export default function SubdomainEditor() {
})
}
useEffect(() => {
if (page) {
setValues({
title: page.title,
content: page.content,
publishedAt: page.publishedAt,
published: page.published,
slug: page.slug,
})
}
}, [page])
const fetcher = useFetcher()
useEffect(() => {
@@ -144,6 +132,51 @@ export default function SubdomainEditor() {
[]
)
const handleDropFile = useCallback(async (file: File, view: EditorView) => {
if (!file.type.startsWith("image/")) {
toast.error("You can only upload images")
return
}
const position = view.state.selection.main.head
const toastId = toast.loading("Uploading...")
const form = new FormData()
form.append("file", file)
const res = await fetch("/api/upload-image", {
body: form,
headers: {},
credentials: "same-origin",
method: "POST",
})
if (!res.ok) {
toast.error("Upload failed", {
id: toastId,
})
} else {
const data = await res.json()
if (data.error) {
toast.error(data.error, { id: toastId })
} else {
toast.success("Uploaded!", {
id: toastId,
})
view.dispatch(
view.state.replaceSelection(
`\n\n![${file.name.replace(/\.\w+$/, "")}](${data.file})\n\n`
)
)
}
}
}, [])
const { editorRef } = useEditor({
value: values.content,
onChange: handleEditorContentChange,
onDropFile: handleDropFile,
placeholder: "Start writing here..",
})
return (
<DashboardMain fullWidth>
<header className="flex justify-between absolute top-0 left-0 right-0 z-10 px-5 h-14 border-b items-center text-sm">
@@ -240,11 +273,7 @@ export default function SubdomainEditor() {
</div>
<div className="mt-5">
<div className="">
<Editor
value={values.content}
onChange={handleEditorContentChange}
placeholder="Start writing here.."
/>
<div ref={editorRef}></div>
</div>
</div>
</div>
+9 -3
View File
@@ -5,6 +5,7 @@ import compression from "compression"
import morgan from "morgan"
import { createRequestHandler } from "@remix-run/express"
import { getReplayResponse, setFlyRegionHeader } from "./fly"
import { IS_PROD } from "~/lib/constants"
const BUILD_DIR = path.join(process.cwd(), "build")
@@ -14,7 +15,9 @@ app.all("*", getReplayResponse)
app.use(setFlyRegionHeader)
app.use(compression())
if (IS_PROD) {
app.use(compression())
}
// http://expressjs.com/en/advanced/best-practice-security.html#at-a-minimum-disable-x-powered-by-header
app.disable("x-powered-by")
@@ -22,12 +25,15 @@ app.disable("x-powered-by")
// Remix fingerprints its assets so we can cache forever.
app.use(
"/build",
express.static("public/build", { immutable: true, maxAge: "1y" })
express.static(
"public/build",
IS_PROD ? { immutable: true, maxAge: "1y" } : {}
)
)
// Everything else (like favicon.ico) is cached for an hour. You may want to be
// more aggressive with this caching.
app.use(express.static("public", { maxAge: "1h" }))
app.use(express.static("public", IS_PROD ? { maxAge: "1h" } : {}))
app.use(morgan("tiny"))