Add embeds to the Textarea

This commit is contained in:
Sebastian Martinez
2024-12-13 12:26:51 +01:00
parent 9fd2d489ae
commit ca4d9d13fd
20 changed files with 1156 additions and 278 deletions
+3
View File
@@ -6,6 +6,7 @@
variant: "primary" | "secondary" | "ghost" | "float" | "danger";
hoverable?: boolean;
onclick?: () => void;
stylePosition?: string;
stylePadding?: string;
styleHeight?: string;
styleMinHeight?: string;
@@ -27,6 +28,7 @@
stylePadding,
styleHeight,
styleMinHeight,
stylePosition,
styleWidth,
styleCursor = "default",
styleGap = "0.5rem",
@@ -222,6 +224,7 @@
<div class="p3-2"></div>
<div
class="p3-3"
style:position={stylePosition}
style:padding={stylePadding}
style:gap={styleGap}
style:overflow={styleOverflow}
+164 -23
View File
@@ -1,9 +1,15 @@
<script lang="ts">
import type { UnlistenFn } from "@tauri-apps/api/event";
import type { ComponentProps } from "svelte";
import type { Embed } from "@bindings/cob/thread/Embed";
import * as utils from "@app/lib/utils";
import type { Embed } from "@bindings/cob/thread/Embed";
import { invoke } from "@app/lib/invoke";
import { listen } from "@tauri-apps/api/event";
import { onDestroy, onMount } from "svelte";
import { open } from "@tauri-apps/plugin-dialog";
import Button from "./Button.svelte";
import Icon from "./Icon.svelte";
import Markdown from "./Markdown.svelte";
@@ -11,6 +17,7 @@
import OutlineButton from "./OutlineButton.svelte";
interface Props {
styleMinHeight?: string;
rid: string;
placeholder?: string;
submitCaption?: string;
@@ -21,6 +28,7 @@
submitInProgress?: boolean;
disallowEmptyBody?: boolean;
isValid?: () => boolean;
preview?: boolean;
stylePadding?: string;
borderVariant?: ComponentProps<typeof Textarea>["borderVariant"];
submit: (opts: {
@@ -32,6 +40,8 @@
/* eslint-disable prefer-const */
let {
preview = $bindable(false),
styleMinHeight,
rid,
placeholder = "Leave your comment",
submitCaption = "Comment",
@@ -49,12 +59,124 @@
}: Props = $props();
/* eslint-enable prefer-const */
let preview: boolean = $state(false);
let selectionStart = $state(0);
let selectionEnd = $state(0);
let inputFiles: FileList | undefined = $state(undefined);
let selectionStart = $state(body.length);
let selectionEnd = $state(body.length);
let draggingOver = $state(false);
let dragEnterUnlistenFn: UnlistenFn | undefined = undefined;
let dragLeaveUnlistenFn: UnlistenFn | undefined = undefined;
let dragDropUnlistenFn: UnlistenFn | undefined = undefined;
const inputId = `input-label-${crypto.randomUUID()}`;
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)];
}
onMount(async () => {
if (window.__TAURI_INTERNALS__) {
dragEnterUnlistenFn = await listen("tauri://drag-enter", () => {
draggingOver = true;
});
dragLeaveUnlistenFn = await listen("tauri://drag-leave", () => {
draggingOver = false;
});
dragDropUnlistenFn = await listen<{
paths: string[];
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 name = path.split("/").at(-1);
const uploadLabel = `[Uploading ${name}...]()\n`;
body = preBody.concat(uploadLabel, afterBody);
const oid = await invoke<string>("save_embed_by_path", {
rid,
path,
}).catch(console.error);
return `[${name}](${oid})\n`;
}),
).then(texts => updateBodyAndSelection(texts, preBody, afterBody));
});
}
});
onDestroy(() => {
if (dragEnterUnlistenFn) dragEnterUnlistenFn();
if (dragLeaveUnlistenFn) dragLeaveUnlistenFn();
if (dragDropUnlistenFn) dragDropUnlistenFn();
});
async function attachEmbedsByPaths(paths: string[]) {
const [preBody, afterBody] = splitBody();
return Promise.all(
paths.map(async path => {
const name = path.split("/").at(-1);
const uploadLabel = `[Uploading ${name}...]()\n`;
body = preBody.concat(uploadLabel, afterBody);
const oid = await invoke<string>("save_embed_by_path", {
rid,
path,
}).catch(console.error);
return `[${name}](${oid})\n`;
}),
).then(texts => updateBodyAndSelection(texts, preBody, afterBody));
}
async function handlePaste(e: ClipboardEvent) {
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.
if (e.clipboardData.items.length === 1) {
const file = e.clipboardData.files[0];
const uploadLabel = `[Uploading...]()\n`;
body = preBody.concat(uploadLabel, afterBody);
const oid = await invoke<string>("save_embed_by_clipboard", {
name: file.name,
rid,
}).catch(console.error);
body = preBody.concat(`[${file.name}](${oid})\n`, afterBody);
} 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);
const oid = await invoke<string>("save_embed_by_bytes", {
rid,
name: file.name,
bytes,
}).catch(console.error);
return `[${file.name}](${oid})\n`;
}),
).then(texts => updateBodyAndSelection(texts, preBody, afterBody));
}
} 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.
}
}
function selectFiles() {
void open({ multiple: true }).then(paths => {
if (paths) {
void attachEmbedsByPaths(paths);
}
});
}
function submitFn() {
void submit({ comment: body, embeds })
@@ -87,16 +209,19 @@
.buttons {
display: flex;
margin-left: auto;
gap: 1rem;
gap: 0.5rem;
}
.caption {
font-size: var(--font-size-small);
color: var(--color-fill-gray);
display: flex;
align-items: center;
flex-wrap: wrap;
align-items: flex-start;
gap: 0.25rem;
}
.preview {
width: 100%;
font-size: var(--font-size-small);
min-height: 109px;
padding: 0.75rem;
@@ -111,17 +236,14 @@
<Markdown {rid} breaks content={body} />
</div>
{:else}
<input
multiple
bind:files={inputFiles}
style:display="none"
type="file"
id={inputId} />
<Textarea
{draggingOver}
{borderVariant}
{stylePadding}
{styleMinHeight}
bind:selectionEnd
bind:selectionStart
onpaste={handlePaste}
{focus}
submit={() => submit({ comment: body, embeds })}
bind:value={body}
@@ -135,20 +257,37 @@
preview = false;
close();
}}>
<Icon name="cross" />Discard
<Icon name="cross" />
<span class="global-hide-on-small-desktop-down">Discard</span>
</OutlineButton>
{#if !preview}
<div class="caption">
<Icon name="markdown" />
Markdown is supported. Press {utils.modifierKey()}↵ to submit.
Drag and drop files to add them.
<div style="display: flex; align-items: center; gap: 0.25rem;">
<Icon name="markdown" />
Markdown is supported.
</div>
<span class="global-hide-on-small-desktop-down">
<br />
</span>
<span class="global-hide-on-small-desktop-down">
Press {utils.modifierKey()}↵ to submit.
</span>
</div>
{/if}
<div class="buttons">
<OutlineButton variant="ghost" onclick={selectFiles}>
<Icon name="attachment" />
<span class="global-hide-on-small-desktop-down">Attach</span>
</OutlineButton>
<OutlineButton
variant="ghost"
disabled={body.trim() === ""}
onclick={() => (preview = !preview)}>
<Icon name={preview ? "pen" : "eye"} />{preview ? "Edit" : "Preview"}
<Icon name={preview ? "pen" : "eye"} />
<span class="global-hide-on-small-desktop-down">
{preview ? "Edit" : "Preview"}
</span>
</OutlineButton>
<Button
variant="ghost"
@@ -157,11 +296,13 @@
(disallowEmptyBody && body.trim() === "")}
onclick={submitFn}>
<Icon name="checkmark" />
{#if submitInProgress}
Saving…
{:else}
{submitCaption}
{/if}
<span class="global-hide-on-small-desktop-down">
{#if submitInProgress}
Saving…
{:else}
{submitCaption}
{/if}
</span>
</Button>
</div>
</div>
+14
View File
@@ -6,6 +6,7 @@
onclick?: () => void;
disabled?: boolean;
name:
| "attachment"
| "arrow-left"
| "arrow-right"
| "checkmark"
@@ -108,6 +109,19 @@
<path d="M10 3H9.00003V13H10V3Z" />
<path d="M13 6H12V7H13V6Z" />
<path d="M14 7H13V8H14V7Z" />
{:else if name === "attachment"}
<path d="M4 4H12V5H4V4Z" />
<path d="M4 11H11V12H4V11Z" />
<path d="M13 6H14V8H13V6Z" />
<path d="M2 6H3V10H2V6Z" />
<path d="M12 5L13 5V6H12V5Z" />
<path d="M3 5L4 5V6L3 6L3 5Z" />
<path d="M12 8H13V9H12V8Z" />
<path d="M3 10H4L4 11H3L3 10Z" />
<path d="M5 9L12 9V10H5V9Z" />
<path d="M4 8H5V9L4 9V8Z" />
<path d="M5 6H11V7H5V6Z" />
<path d="M4 7H5L5 8H4L4 7Z" />
{:else if name === "checkmark"}
<path d="M7 11V12H6V11H7Z" />
<path d="M8 10V11L7 11L7 10H8Z" />
+63 -16
View File
@@ -41,6 +41,9 @@
}
$effect(() => {
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
content;
void tick().then(() => {
for (const e of container.querySelectorAll("a")) {
try {
@@ -59,6 +62,66 @@
) {
e.classList.add("no-underline");
}
// Iterate over all links, and try to add a base64 preview beneath it.
const href = e.getAttribute("href");
// If the markdown link is an oid embed
if (href && isCommit(href)) {
e.style.display = "block";
e.onclick = event => {
event.preventDefault();
invoke("save_embed_to_disk", {
rid,
oid: href,
name: e.innerText,
}).catch(console.error);
};
void invoke<Uint8Array>("get_embed", {
rid,
oid: href,
})
.then(byteArray => {
const buffer = Buffer.from(byteArray);
const blob = new Blob([buffer]);
const url = URL.createObjectURL(blob);
const ext = e.innerHTML.split(".").at(-1);
// Embed an img element below the link
if (ext?.match(/(gif|jpe?g|tiff?|png|webp|bmp)/)) {
const element = document.createElement("img");
element.setAttribute("src", url);
e.insertAdjacentElement("afterend", element);
// Embed an iframe to display pdf correctly element below the link
} else if (ext?.match(/(pdf)/)) {
const element = document.createElement("embed");
element.setAttribute("src", url);
element.type = "application/pdf";
element.style.overflow = "scroll";
element.style.height = "40rem";
element.style.overscrollBehavior = "contain";
e.insertAdjacentElement("afterend", element);
} else if (ext?.match(/(mp4|mov)/)) {
const element = document.createElement("video");
const node = document.createElement("source");
node.src = url;
element.controls = true;
node.type = `video/mp4`;
element.style.width = "100%";
element.appendChild(node);
e.insertAdjacentElement("afterend", element);
} else if (ext?.match(/(mp3)/)) {
const element = document.createElement("audio");
element.src = url;
element.controls = true;
e.insertAdjacentElement("afterend", element);
} else {
console.warn(
`Not able to provide a preview for ${e.innerHTML}`,
);
}
})
.catch(console.error);
}
}
// Replace standard HTML checkboxes with our custom radicle-icon-small element
@@ -75,22 +138,6 @@
i.remove();
}
// Iterate over all images, and replace the source with a canonicalized URL
// pointing at the repos /raw endpoint.
for (const i of container.querySelectorAll("img")) {
const imagePath = i.getAttribute("src");
// If the image is an oid embed
if (imagePath && isCommit(imagePath)) {
void invoke<string>("get_file_by_oid", {
rid,
oid: imagePath,
}).then(base64Content =>
i.setAttribute("src", `data:image/jpeg;base64,${base64Content}`),
);
}
}
// Replaces code blocks in the background with highlighted code.
const prefix = "language-";
const nodes = Array.from(document.body.querySelectorAll("pre code"));
+47 -10
View File
@@ -1,15 +1,18 @@
<script lang="ts">
import type { FormEventHandler } from "svelte/elements";
import type {
ClipboardEventHandler,
FormEventHandler,
} from "svelte/elements";
import type { ComponentProps } from "svelte";
import { tick } from "svelte";
import { onMount, tick } from "svelte";
import * as utils from "@app/lib/utils";
import Border from "./Border.svelte";
interface Props {
draggingOver?: boolean;
borderVariant?: ComponentProps<typeof Border>["variant"];
onpaste?: ClipboardEventHandler<HTMLTextAreaElement>;
focus?: boolean;
oninput?: FormEventHandler<HTMLTextAreaElement>;
onkeypress?: FormEventHandler<HTMLTextAreaElement>;
@@ -25,8 +28,10 @@
/* eslint-disable prefer-const */
let {
draggingOver,
borderVariant = "float",
focus = false,
onpaste,
oninput,
onkeypress,
placeholder = undefined,
@@ -44,6 +49,28 @@
let textareaElement: HTMLTextAreaElement | undefined = $state(undefined);
let focussed = $state(false);
onMount(() => {
if (textareaElement) {
// The selectionchange event listener doesn't modify the selection on Enter.
textareaElement.addEventListener("keydown", (event: KeyboardEvent) => {
if (event.key === "Enter") {
selectionStart += 1;
selectionEnd += 1;
}
});
textareaElement.addEventListener("selectionchange", (event: Event) => {
if (
event.target &&
"selectionStart" in event.target &&
"selectionEnd" in event.target
) {
selectionStart = event.target.selectionStart as number;
selectionEnd = event.target.selectionEnd as number;
}
});
}
});
// We either auto-grow the textarea, or allow the user to resize it. These
// options are mutually exclusive because a user resized textarea would
// automatically shrink upon text input otherwise.
@@ -67,12 +94,6 @@
}
});
$effect.pre(() => {
if (textareaElement) {
({ selectionStart, selectionEnd } = textareaElement);
}
});
$effect(() => {
void tick().then(() => {
if (textareaElement && focus) {
@@ -123,10 +144,22 @@
textarea::placeholder {
color: var(--color-foreground-dim);
}
.dragover {
position: absolute;
opacity: 0.5;
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
background-color: var(--color-background-float);
}
</style>
<Border
variant={focussed ? "secondary" : borderVariant}
stylePosition="relative"
styleWidth="100%"
{styleMinHeight}>
<textarea
@@ -142,10 +175,14 @@
? "scroll"
: undefined}
{placeholder}
{onpaste}
{oninput}
{onkeypress}
onfocus={() => (focussed = true)}
onblur={() => (focussed = false)}
onkeydown={handleKeydown}>
</textarea>
{#if draggingOver}
<div class="txt-small dragover">Drop files to add them as embeds.</div>
{/if}
</Border>