diff --git a/src/components/ExtendedTextarea.svelte b/src/components/ExtendedTextarea.svelte index 7e943be67..4446d23f1 100644 --- a/src/components/ExtendedTextarea.svelte +++ b/src/components/ExtendedTextarea.svelte @@ -9,6 +9,7 @@ import { onDestroy, onMount } from "svelte"; import { SvelteMap } from "svelte/reactivity"; + import { basename } from "@app/lib/embeds"; import { hints } from "@app/lib/hints"; import { invoke } from "@app/lib/invoke"; import { matchesShortcut } from "@app/lib/shortcuts.svelte"; @@ -125,17 +126,44 @@ embedUploadError = undefined; }, 5000); - function updateBodyAndSelection(input: string[], pre: string, after: string) { - const allEmbeds = input.join(""); - body = pre.concat(allEmbeds, after); - selectionStart = pre.length + allEmbeds.length; - selectionEnd = pre.length + allEmbeds.length; - } - function splitBody() { return [body.substring(0, selectionStart), body.substring(selectionStart)]; } + async function uploadEmbeds( + items: T[], + nameOf: (item: T) => string, + save: (item: T) => Promise, + ) { + const [preBody, afterBody] = splitBody(); + body = + preBody + + items.map(item => `[Uploading ${nameOf(item)}...]()\n`).join("") + + afterBody; + const links = await Promise.all( + items.map(async item => { + const name = nameOf(item); + try { + const oid = await save(item); + embeds.set(oid, { name, content: `git:${oid}` }); + return `[${name}](${oid})\n`; + } catch { + embedUploadError = "Upload failed, embed exceeded 10Mb."; + restoreDragDropText(); + return ""; + } + }), + ); + const inserted = links.join(""); + body = preBody + inserted + afterBody; + selectionStart = preBody.length + inserted.length; + selectionEnd = selectionStart; + } + + function saveByPath(path: string) { + return invoke("save_embed_by_path", { rid, path }); + } + onMount(async () => { if (window.__TAURI_INTERNALS__) { if (attachEnabled) { @@ -152,29 +180,7 @@ position: { x: number; y: number }; }>("tauri://drag-drop", async event => { draggingOver = false; - const [preBody, afterBody] = splitBody(); - - return Promise.all( - event.payload.paths.map(async path => { - const pathSegments = path.split("/"); - const name = pathSegments[pathSegments.length - 1]; - const uploadLabel = `[Uploading ${name}...]()\n`; - - body = preBody.concat(uploadLabel, afterBody); - try { - const oid = await invoke("save_embed_by_path", { - rid, - path, - }); - embeds.set(oid, { name, content: `git:${oid}` }); - return `[${name}](${oid})\n`; - } catch { - embedUploadError = "Upload failed, embed exceeded 10Mb."; - restoreDragDropText(); - return ""; - } - }), - ).then(texts => updateBodyAndSelection(texts, preBody, afterBody)); + await uploadEmbeds(event.payload.paths, basename, saveByPath); }); } } @@ -187,28 +193,7 @@ }); async function attachEmbedsByPaths(paths: string[]) { - const [preBody, afterBody] = splitBody(); - - return Promise.all( - paths.map(async path => { - const pathSegments = path.split("/"); - const name = pathSegments[pathSegments.length - 1]; - const uploadLabel = `[Uploading ${name}...]()\n`; - body = preBody.concat(uploadLabel, afterBody); - try { - const oid = await invoke("save_embed_by_path", { - rid, - path, - }); - embeds.set(oid, { name: name ?? path, content: `git:${oid}` }); - return `[${name}](${oid})\n`; - } catch { - embedUploadError = "Upload failed, embed exceeded 10Mb."; - restoreDragDropText(); - return ""; - } - }), - ).then(texts => updateBodyAndSelection(texts, preBody, afterBody)); + await uploadEmbeds(paths, basename, saveByPath); } async function handlePaste(e: ClipboardEvent) { @@ -218,51 +203,28 @@ if (e.clipboardData?.files && e.clipboardData.files.length > 0) { e.preventDefault(); - const [preBody, afterBody] = splitBody(); - // We read the buffer on the backend, if it's a image buffer. + const files = Array.from(e.clipboardData.files); + // A single item may be an image the webview can't hand over, so the + // backend reads it from the clipboard itself. if (e.clipboardData.items.length === 1) { - const file = e.clipboardData.files[0]; - const uploadLabel = `[Uploading...]()\n`; - body = preBody.concat(uploadLabel, afterBody); - try { - const oid = await invoke("save_embed_by_clipboard", { - name: file.name, - rid, - }); - - embeds.set(oid, { name: file.name, content: `git:${oid}` }); - body = preBody.concat(`[${file.name}](${oid})\n`, afterBody); - } catch { - body = preBody.concat(``, afterBody); - embedUploadError = "Upload failed, embed exceeded 10Mb."; - restoreDragDropText(); - } + await uploadEmbeds( + files.slice(0, 1), + file => file.name, + file => + invoke("save_embed_by_clipboard", { name: file.name, rid }), + ); } else { - return Promise.all( - Array.from(e.clipboardData.files).map(async file => { - const arrayBuffer = await file.arrayBuffer(); - const bytes = new Uint8Array(arrayBuffer); - const uploadLabel = `[Uploading ${file.name}...]()\n`; - body = preBody.concat(uploadLabel, afterBody); - try { - const oid = await invoke("save_embed_by_bytes", { - rid, - name: file.name, - bytes, - }); - embeds.set(oid, { name: file.name, content: `git:${oid}` }); - return `[${file.name}](${oid})\n`; - } catch { - embedUploadError = "Upload failed, embed exceeded 10Mb."; - restoreDragDropText(); - return ""; - } - }), - ).then(texts => updateBodyAndSelection(texts, preBody, afterBody)); + await uploadEmbeds( + files, + file => file.name, + async file => + invoke("save_embed_by_bytes", { + rid, + name: file.name, + bytes: new Uint8Array(await file.arrayBuffer()), + }), + ); } - } else { - // In case that the clipboard data isn't an array of files, - // we want to make use of the default behavior and insert the clipboard content. } } diff --git a/src/components/Markdown.svelte b/src/components/Markdown.svelte index e9df8e545..070d4ec8a 100644 --- a/src/components/Markdown.svelte +++ b/src/components/Markdown.svelte @@ -5,6 +5,7 @@ import { toDom } from "hast-util-to-dom"; import { mount, tick, unmount } from "svelte"; + import { embedPreviewKind } from "@app/lib/embeds"; import { parseFrontmatter } from "@app/lib/frontmatter"; import { invoke } from "@app/lib/invoke"; import { markdownWithExtensions, Renderer } from "@app/lib/markdown"; @@ -111,34 +112,33 @@ const buffer = Buffer.from(content); const blob = new Blob([buffer]); const url = URL.createObjectURL(blob); - // Embed an img element below the link - if (mimeType?.startsWith("image")) { + const kind = embedPreviewKind(mimeType); + if (kind === "image") { const element = document.createElement("img"); element.setAttribute("src", url); element.style.display = "block"; e.style.display = "block"; e.insertAdjacentElement("afterend", element); - // Embed an iframe to display pdf correctly element below the link - } else if (mimeType?.startsWith("application")) { + } else if (kind === "document") { const element = document.createElement("embed"); element.setAttribute("src", url); - element.type = mimeType; + element.type = mimeType ?? ""; element.style.overflow = "scroll"; element.style.height = "40rem"; element.style.overscrollBehavior = "contain"; e.style.display = "block"; e.insertAdjacentElement("afterend", element); - } else if (mimeType?.startsWith("video")) { + } else if (kind === "video") { const element = document.createElement("video"); const node = document.createElement("source"); node.src = url; element.controls = true; - node.type = mimeType; + node.type = mimeType ?? ""; element.style.width = "100%"; e.style.display = "block"; element.appendChild(node); e.insertAdjacentElement("afterend", element); - } else if (mimeType?.startsWith("audio")) { + } else if (kind === "audio") { const element = document.createElement("audio"); element.style.display = "block"; element.src = url; diff --git a/src/lib/embeds.ts b/src/lib/embeds.ts new file mode 100644 index 000000000..be60ce6e1 --- /dev/null +++ b/src/lib/embeds.ts @@ -0,0 +1,13 @@ +export function basename(path: string): string { + return path.split("/").pop() ?? path; +} + +export function embedPreviewKind( + mimeType: string | null, +): "image" | "document" | "video" | "audio" | undefined { + if (mimeType?.startsWith("image")) return "image"; + if (mimeType?.startsWith("application")) return "document"; + if (mimeType?.startsWith("video")) return "video"; + if (mimeType?.startsWith("audio")) return "audio"; + return undefined; +} diff --git a/tests/unit/embeds.test.ts b/tests/unit/embeds.test.ts new file mode 100644 index 000000000..4a82a3a8b --- /dev/null +++ b/tests/unit/embeds.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, test } from "vitest"; + +import { basename, embedPreviewKind } from "@app/lib/embeds"; + +describe("basename", () => { + test.each([ + ["/home/alice/cat.png", "cat.png"], + ["cat.png", "cat.png"], + ])("of %j is %j", (path, expected) => { + expect(basename(path)).toBe(expected); + }); +}); + +test.each([ + ["image/png", "image"], + ["application/pdf", "document"], + ["video/mp4", "video"], + ["audio/ogg", "audio"], + ["text/plain", undefined], + [null, undefined], +])("a %j embed previews as %j", (mimeType, expected) => { + expect(embedPreviewKind(mimeType)).toBe(expected); +});