From d022ef19cff20b9308c0dab067e6da3a6b6e441a Mon Sep 17 00:00:00 2001 From: EGOIST Date: Sun, 8 May 2022 12:47:33 +0800 Subject: [PATCH] feat(editor): drop image to upload --- app/components/ui/Editor.tsx | 29 ++++++-- app/lib/markdown.server.ts | 22 +++++++ app/lib/upload.server.ts | 26 ++++++++ app/routes/api/save-avatar.ts | 28 ++------ app/routes/api/upload-image.ts | 24 +++++++ app/routes/dashboard/$subdomain/editor.tsx | 77 +++++++++++++++------- server/index.ts | 12 +++- 7 files changed, 164 insertions(+), 54 deletions(-) create mode 100644 app/lib/upload.server.ts create mode 100644 app/routes/api/upload-image.ts diff --git a/app/components/ui/Editor.tsx b/app/components/ui/Editor.tsx index 9ff498b2..9fb16d70 100644 --- a/app/components/ui/Editor.tsx +++ b/app/components/ui/Editor.tsx @@ -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(null) const [view, setView] = useState(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
+ return { + view, + editorRef, + } } diff --git a/app/lib/markdown.server.ts b/app/lib/markdown.server.ts index 79570831..0588e067 100644 --- a/app/lib/markdown.server.ts +++ b/app/lib/markdown.server.ts @@ -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 } } diff --git a/app/lib/upload.server.ts b/app/lib/upload.server.ts new file mode 100644 index 00000000..2b88bf05 --- /dev/null +++ b/app/lib/upload.server.ts @@ -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) +} diff --git a/app/routes/api/save-avatar.ts b/app/routes/api/save-avatar.ts index 7f4f4cee..4d2c6b5d 100644 --- a/app/routes/api/save-avatar.ts +++ b/app/routes/api/save-avatar.ts @@ -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, { diff --git a/app/routes/api/upload-image.ts b/app/routes/api/upload-image.ts new file mode 100644 index 00000000..609a97ca --- /dev/null +++ b/app/routes/api/upload-image.ts @@ -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, + } + } +} diff --git a/app/routes/dashboard/$subdomain/editor.tsx b/app/routes/dashboard/$subdomain/editor.tsx index a0338204..43cadeef 100644 --- a/app/routes/dashboard/$subdomain/editor.tsx +++ b/app/routes/dashboard/$subdomain/editor.tsx @@ -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 (
@@ -240,11 +273,7 @@ export default function SubdomainEditor() {
- +
diff --git a/server/index.ts b/server/index.ts index 2ae82dd7..6932a664 100644 --- a/server/index.ts +++ b/server/index.ts @@ -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"))