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
+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>