Compare commits

..
2 Commits
Author SHA1 Message Date
tbenandClaude Opus 5.5 ae64ef195d Release v0.15.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 11:37:53 +01:00
tbenandClaude Opus 5.5 06a4b7bb36 Step through a folder's images in the preview
An image opened from a list (a folder, the Files page, the chat's files
modal, a message's images) gets that list's images as a gallery:
Previous and Next in the header and the arrow keys step through them in
the same modal, each opening at its own fit, neighbours preloaded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 11:37:53 +01:00
19 changed files with 289 additions and 23 deletions
+1 -1
View File
@@ -96,7 +96,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
- **Sending:** `api/admin/bots/send-message.ts` -> `enqueueBotReply` -> `wakeBotsQueue`. **Never import `src/bots-queue/index.ts` from a page or API route** (pulls the bunext runtime into page bundles). Optimistic bubble in `pending_messages` until the saved message replaces it.
- **Composer:** Tiptap editor reading/writing markdown, drafts in `localStorage`, `@` bots / `#` workspaces written as `[bot:ID]`/`[workspace:ID]`. Enter sends (Mod+Enter in lists/code). `@tiptap/react` needs `use-sync-external-store`; the app ships an ESM stand-in in `packages/use-sync-external-store-esm` (file dependency + override; the Dockerfile copies `packages/` before `bun install`).
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `FolderPreviewModal`, the files browser's listing over the chat, files opening their own preview; a modified click or its Open in Files goes to `/admin/files`), `[take-over:ID:mode]`, `[proposal:ID]`, `[hook-proposal:ID]`, `[secret:ID]` (masked env, Reveal/Copy), `[secret-request:ID]` (masked input card), `[question:ID]` (a bot's questions), `[graphic:ID]` (a bot graphic, framed inline), `[room:ID]` (a chatroom), `[task:ID]` (a tracker task, opening `TaskDetailModal`). Parsers in `src/utils/*-ref.ts`. Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers passed on from chatrooms keep working.
- **File preview:** every file link (chips, attachments, files modal, task files, `/admin/files`) is a `FilePreviewLink`: a plain click opens `FilePreviewModal` (markdown rendered with the message elements, CSV/TSV as a table via `parseCsv`, images in `ImageViewer` (zoom buttons and keys, Ctrl/Cmd+wheel or pinch at the pointer, Fit, Fit width (a full-page screenshot opens that way and scrolls down), Actual size, double click, drag to pan; sized by the `width` attribute and centred with auto margins, never flex centring, which cuts off a tall picture's top), PDF/audio/video in place, HTML in a frame with `sandbox=""` (plus the media server's `sandbox` CSP), other text as code, the kind from `filePreviewKind`; Download and Open in a new tab), a modified click still opens a tab. Text is read up to `AppData.FilePreviewMaxTextBytes`. Never render a file's HTML on the app's origin or with scripts. Escape closes only the top modal of a stack (`useTopModalEscape`; twui closes every open one). The message elements and the preview import each other (through the file chips), so the preview merges `MessageMarkdownComponents` when it renders, never at module load.
- **File preview:** every file link (chips, attachments, files modal, task files, `/admin/files`) is a `FilePreviewLink`: a plain click opens `FilePreviewModal` (markdown rendered with the message elements, CSV/TSV as a table via `parseCsv`, images in `ImageViewer` (zoom buttons and keys, Ctrl/Cmd+wheel or pinch at the pointer, Fit, Fit width (a full-page screenshot opens that way and scrolls down), Actual size, double click, drag to pan; sized by the `width` attribute and centred with auto margins, never flex centring, which cuts off a tall picture's top), PDF/audio/video in place, HTML in a frame with `sandbox=""` (plus the media server's `sandbox` CSP), other text as code, the kind from `filePreviewKind`; Download and Open in a new tab), a modified click still opens a tab. Text is read up to `AppData.FilePreviewMaxTextBytes`. Never render a file's HTML on the app's origin or with scripts. Opened from a list (a folder, the files modal, a message's images), an image gets that list's images as its `gallery` (`imagePreviewGallery`): Previous/Next and the arrow keys step through them in the same modal, neighbours preloaded. Escape closes only the top modal of a stack (`useTopModalEscape`; twui closes every open one). The message elements and the preview import each other (through the file chips), so the preview merges `MessageMarkdownComponents` when it renders, never at module load.
- **Copy chat** (header menu): the active session (the one on screen) as one markdown document (`api/admin/bots/conversation-export` -> `conversationMarkdown`, refs as names, message headings demoted). The clipboard write starts on the click with a pending `ClipboardItem` (`copyPendingText`), since Safari drops the gesture after a fetch.
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. Replies and user-started tasks only: never routines, hook calls or chatroom sessions (no one sees those).
- **Replies/reactions:** `reply_to_message_id` (not an FK); reactions from the fixed `BotMessageReactions`, toggled by `react-message.ts` and the `react_to_message` tool, pushed as `server:bot-reaction`.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.15.1",
"version": "0.15.2",
"module": "index.ts",
"type": "module",
"private": true,
+8 -1
View File
@@ -1,5 +1,6 @@
import { useState, type ReactNode } from "react";
import Link from "@moduletrace/twui/layout/Link";
import type { FilePreviewItem } from "@/src/types";
import isPlainClick from "@/src/utils/is-plain-click";
import FilePreviewModal from "./file-preview-modal";
@@ -8,6 +9,11 @@ type Props = {
url: string;
media_type?: string | null;
size?: number;
/**
* The images it sits among (`imagePreviewGallery`), for Previous and
* Next in the preview.
*/
gallery?: FilePreviewItem[];
title?: string;
className?: string;
children: ReactNode;
@@ -18,7 +24,7 @@ type Props = {
* plain click. It stays a real link to the bytes, so a middle click or
* Ctrl/Cmd click still opens the file in a new tab.
*/
export default function FilePreviewLink({ name, url, media_type, size, title, className, children }: Props) {
export default function FilePreviewLink({ name, url, media_type, size, gallery, title, className, children }: Props) {
const [open, setOpen] = useState(false);
return (
@@ -44,6 +50,7 @@ export default function FilePreviewLink({ name, url, media_type, size, title, cl
url={url}
media_type={media_type}
size={size}
gallery={gallery}
onClose={() => setOpen(false)}
/>
) : null}
+39 -7
View File
@@ -1,3 +1,4 @@
import { useState } from "react";
import Modal from "@moduletrace/twui/elements/Modal";
import H2 from "@moduletrace/twui/layout/H2";
import Link from "@moduletrace/twui/layout/Link";
@@ -5,16 +6,27 @@ import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { Download, SquareArrowOutUpRight } from "lucide-react";
import useGalleryKeys from "@/src/hooks/use-gallery-keys";
import usePreloadImages from "@/src/hooks/use-preload-images";
import useTopModalEscape from "@/src/hooks/use-top-modal-escape";
import type { FilePreviewItem } from "@/src/types";
import filePreviewKind from "@/src/utils/file-preview-kind";
import formatBytes from "@/src/utils/format-bytes";
import galleryIndex from "@/src/utils/gallery-index";
import FilePreviewBody from "./file-preview-body";
import FilePreviewStepper from "./file-preview-stepper";
type Props = {
name: string;
url: string;
media_type?: string | null;
size?: number;
/**
* The images it was opened among (a folder's, a message's). When the
* file is one of them, Previous and Next (and the arrow keys) step
* through them without closing the preview.
*/
gallery?: FilePreviewItem[];
onClose: () => void;
};
@@ -25,18 +37,29 @@ const ActionClassName =
* A file over the page: markdown rendered, a CSV as a table, an image,
* PDF, audio or video in place, other text as code, with ways to download
* it or open it in a new tab. A file it can't show offers those only.
* Opened from a gallery, it steps through its images; each one opens fresh
* (fitted, scrolled to the top), and its neighbours load ahead.
*/
export default function FilePreviewModal({
name,
url,
media_type,
size,
onClose,
}: Props) {
export default function FilePreviewModal({ gallery, onClose, ...opened }: Props) {
const [index, set_index] = useState(() => galleryIndex({ gallery, url: opened.url }));
const stepping = Boolean(gallery && index >= 0 && gallery.length > 1);
const shown: FilePreviewItem = (stepping && gallery?.[index]) || opened;
const { name, url, media_type, size } = shown;
const kind = filePreviewKind({ name, media_type });
const base_name = name.split("/").pop() || name;
const count = gallery?.length || 0;
const step = ({ by }: { by: number }) =>
set_index((current) => Math.min(count - 1, Math.max(0, current + by)));
useTopModalEscape({ onClose });
useGalleryKeys({
enabled: stepping,
onPrevious: () => step({ by: -1 }),
onNext: () => step({ by: 1 }),
});
usePreloadImages({
urls: stepping ? [gallery?.[index + 1]?.url || "", gallery?.[index - 1]?.url || ""] : [],
});
return (
<Modal
@@ -60,6 +83,14 @@ export default function FilePreviewModal({
</Span>
) : null}
</Stack>
{stepping ? (
<FilePreviewStepper
index={index}
count={count}
onPrevious={() => step({ by: -1 })}
onNext={() => step({ by: 1 })}
/>
) : null}
<Link
href={url}
download={base_name}
@@ -81,6 +112,7 @@ export default function FilePreviewModal({
</Link>
</Row>
<FilePreviewBody
key={url}
kind={kind}
name={base_name}
url={url}
@@ -0,0 +1,41 @@
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import { ChevronLeft, ChevronRight } from "lucide-react";
import RowIconButton from "./row-icon-button";
type Props = {
/**
* The shown file's place in the gallery, from 0.
*/
index: number;
count: number;
onPrevious: () => void;
onNext: () => void;
};
/**
* Previous and Next through a preview's gallery (the images of a folder or
* a message), with where the shown one stands: "3 of 12". The arrow keys
* do the same.
*/
export default function FilePreviewStepper({ index, count, onPrevious, onNext }: Props) {
return (
<Row className="shrink-0 gap-0! flex-nowrap items-center">
<RowIconButton
icon={ChevronLeft}
title="Previous image (Left arrow)"
disabled={index <= 0}
onClick={onPrevious}
/>
<Span className="min-w-16 text-center text-[13px] leading-[18px] tabular-nums text-ink-secondary">
{`${index + 1} of ${count}`}
</Span>
<RowIconButton
icon={ChevronRight}
title="Next image (Right arrow)"
disabled={index >= count - 1}
onClick={onNext}
/>
</Row>
);
}
@@ -5,6 +5,7 @@ import FilePreviewBody from "./file-preview-body";
import FilePreviewLink from "./file-preview-link";
import FilePreviewMarkdown from "./file-preview-markdown";
import FilePreviewTable from "./file-preview-table";
import FilePreviewStepper from "./file-preview-stepper";
import FolderPreviewLink from "./folder-preview-link";
test("a markdown file renders as a document, raw HTML left out", () => {
@@ -73,3 +74,15 @@ test("a folder link stays a real link to the files browser until clicked", () =>
expect(html).toContain('href="/admin/files?volume=bots&amp;owner=3&amp;path=reports"');
expect(html).toContain("Open reports");
});
test("a gallery's stepper says where the image stands and stops at the ends", () => {
const first = renderToString(<FilePreviewStepper index={0} count={3} onPrevious={() => {}} onNext={() => {}} />);
const last = renderToString(<FilePreviewStepper index={2} count={3} onPrevious={() => {}} onNext={() => {}} />);
expect(first).toContain("1 of 3");
expect(first).toContain("Previous image");
expect(first).toContain("Next image");
expect(last).toContain("3 of 3");
expect((first.match(/disabled=""/g) || []).length).toBe(1);
expect((last.match(/disabled=""/g) || []).length).toBe(1);
});
@@ -1,4 +1,4 @@
import { useState } from "react";
import { useMemo, useState } from "react";
import Modal from "@moduletrace/twui/elements/Modal";
import H2 from "@moduletrace/twui/layout/H2";
import Link from "@moduletrace/twui/layout/Link";
@@ -10,6 +10,7 @@ import useDebouncedValue from "@/src/hooks/use-debounced-value";
import useStorageFolder from "@/src/hooks/use-storage-folder";
import useTopModalEscape from "@/src/hooks/use-top-modal-escape";
import { emptyFolderText, folderSummary } from "@/src/utils/folder-text";
import imagePreviewGallery from "@/src/utils/image-preview-gallery";
import { storagePathName, storageSpecHref, type StorageSpec } from "@/src/utils/storage-volumes";
import FilesBreadcrumbRow from "./files-breadcrumb-row";
import FilesSearchInput from "./files-search-input";
@@ -27,7 +28,8 @@ type Props = {
/**
* A folder over the page, as the files browser shows it: its entries,
* the trail back up and a search by name. A folder inside opens in place,
* a file opens in its own preview over this one, and "Open in Files" goes
* a file opens in its own preview over this one (an image stepping
* through the folder's other images), and "Open in Files" goes
* to the same folder in the files browser. The listing loads through the
* files browser's API, so the same access rules hold.
*/
@@ -38,6 +40,11 @@ export default function FolderPreviewModal({ spec, path: start_path, onClose }:
const { folder, loading, error } = useStorageFolder({ spec, path, search: query });
const name = folder?.breadcrumbs.at(-1)?.name || folder?.label || storagePathName({ volume: spec.volume, path });
const gallery = useMemo(
() => imagePreviewGallery({ items: (folder?.entries || []).map((entry) => ({ ...entry, url: entry.url || "" })) }),
[folder],
);
useTopModalEscape({ onClose });
const openFolder = (next_path: string) => {
@@ -85,6 +92,7 @@ export default function FolderPreviewModal({ spec, path: start_path, onClose }:
key={entry.path}
entry={entry}
selected={entry.kind == "folder" && entry.path == path}
gallery={gallery}
onOpenFolder={openFolder}
/>
))
+7 -2
View File
@@ -4,7 +4,7 @@ import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { twMerge } from "tailwind-merge";
import { FolderOpen } from "lucide-react";
import type { MediaType, StorageEntry } from "@/src/types";
import type { FilePreviewItem, MediaType, StorageEntry } from "@/src/types";
import formatBytes from "@/src/utils/format-bytes";
import relativeTime from "@/src/utils/relative-time";
import AttachmentIcon from "@/src/pages/admin/bots/[bot_id]/(partials)/attachment-icon";
@@ -13,6 +13,10 @@ import FilePreviewLink from "@/src/components/general/file-preview-link";
type Props = {
entry: StorageEntry;
selected?: boolean;
/**
* The folder's images, so an image's preview steps through the rest.
*/
gallery?: FilePreviewItem[];
onOpenFolder: (path: string) => void;
};
@@ -21,7 +25,7 @@ type Props = {
* file preview (its own media record when it is one of the bot's files, else
* the browser's streaming route).
*/
export default function StorageEntryRow({ entry, selected, onOpenFolder }: Props) {
export default function StorageEntryRow({ entry, selected, gallery, onOpenFolder }: Props) {
const is_folder = entry.kind == "folder";
return (
@@ -57,6 +61,7 @@ export default function StorageEntryRow({ entry, selected, onOpenFolder }: Props
url={entry.url || ""}
media_type={entry.media_type}
size={entry.size}
gallery={gallery}
className="text-[13px] font-bold leading-5 text-ink break-words hover:opacity-80"
>
{entry.name}
+47
View File
@@ -0,0 +1,47 @@
import { useEffect, useRef } from "react";
function typingInField({ target }: { target: EventTarget | null }) {
if (!(target instanceof HTMLElement)) return false;
if (target.isContentEditable) return true;
return ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName);
}
/**
* The left and right arrow keys step a preview's gallery back and forth,
* except while typing in a field or with a modifier held.
*/
export default function useGalleryKeys({
enabled,
onPrevious,
onNext,
}: {
enabled: boolean;
onPrevious: () => void;
onNext: () => void;
}) {
const handlers_ref = useRef({ onPrevious, onNext });
handlers_ref.current = { onPrevious, onNext };
useEffect(() => {
if (!enabled) return;
const onKey = (event: KeyboardEvent) => {
if (event.ctrlKey || event.metaKey || event.altKey || event.shiftKey) return;
if (typingInField({ target: event.target })) return;
if (event.key == "ArrowLeft") handlers_ref.current.onPrevious();
else if (event.key == "ArrowRight") handlers_ref.current.onNext();
else return;
event.preventDefault();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [enabled]);
}
+26
View File
@@ -0,0 +1,26 @@
import { useEffect } from "react";
/**
* Starts loading images the user is likely to open next (a gallery's
* neighbours), so stepping to one shows it at once.
*/
export default function usePreloadImages({ urls }: { urls: string[] }) {
const key = urls.join("\n");
useEffect(() => {
if (typeof Image == "undefined") return;
const images = urls.filter(Boolean).map((url) => {
const image = new Image();
image.decoding = "async";
image.src = url;
return image;
});
return () => {
for (const image of images) image.src = "";
};
}, [key]);
}
@@ -1,4 +1,4 @@
import { useContext, useEffect, useState } from "react";
import { useContext, useEffect, useMemo, useState } from "react";
import Modal from "@moduletrace/twui/elements/Modal";
import H2 from "@moduletrace/twui/layout/H2";
import Span from "@moduletrace/twui/layout/Span";
@@ -14,6 +14,7 @@ import HeaderIconButton from "@/src/components/general/header-icon-button";
import { AppContext } from "@/src/pages/__root";
import useDebouncedValue from "@/src/hooks/use-debounced-value";
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
import imagePreviewGallery from "@/src/utils/image-preview-gallery";
import useBotFiles from "../(hooks)/use-bot-files";
import FileRow from "./file-row";
import HeaderMenuItem from "./header-menu-item";
@@ -83,6 +84,10 @@ export default function BotFilesModal({ bot, workspace, menu, on_open }: Props)
};
const files = data?.files || [];
const gallery = useMemo(
() => imagePreviewGallery({ items: files.map((file) => ({ ...file, name: file.path || file.name })) }),
[data],
);
const usage = data?.usage;
return (
@@ -146,6 +151,7 @@ export default function BotFilesModal({ bot, workspace, menu, on_open }: Props)
file={file}
can_manage={can_manage}
busy={busy_id == file.id}
gallery={gallery}
onDelete={() =>
run({
url: `/api/admin/bots/delete-file`,
@@ -3,7 +3,7 @@ import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import Button from "@moduletrace/twui/layout/Button";
import { Trash2 } from "lucide-react";
import type { MediaType, PublicBotFile } from "@/src/types";
import type { FilePreviewItem, MediaType, PublicBotFile } from "@/src/types";
import relativeTime from "@/src/utils/relative-time";
import FilePreviewLink from "@/src/components/general/file-preview-link";
import AttachmentIcon from "./attachment-icon";
@@ -15,6 +15,10 @@ type Props = {
*/
can_manage: boolean;
busy?: boolean;
/**
* The listed images, so an image's preview steps through the rest.
*/
gallery?: FilePreviewItem[];
onDelete: () => void;
};
@@ -22,7 +26,7 @@ type Props = {
* One file in the files modal: its type, path, size and age, and what can
* be done with it.
*/
export default function FileRow({ file, can_manage, busy, onDelete }: Props) {
export default function FileRow({ file, can_manage, busy, gallery, onDelete }: Props) {
return (
<Row className="w-full gap-3! flex-nowrap items-start py-2 border-0 border-b border-solid border-hairline last:border-b-0">
<Row className="mt-0.5 text-ink-secondary">
@@ -34,6 +38,7 @@ export default function FileRow({ file, can_manage, busy, onDelete }: Props) {
url={file.url}
media_type={file.media_type}
size={file.size}
gallery={gallery}
className="text-[13px] font-bold leading-5 text-ink break-words hover:opacity-80"
>
{file.path || file.name}
@@ -1,22 +1,24 @@
import Img from "@moduletrace/twui/layout/Img";
import Span from "@moduletrace/twui/layout/Span";
import type { BotMessageAttachment } from "@/src/types";
import type { BotMessageAttachment, FilePreviewItem } from "@/src/types";
import FilePreviewLink from "@/src/components/general/file-preview-link";
import AttachmentIcon from "./attachment-icon";
/**
* One file on a message: an image as a thumbnail, anything else as a
* named chip. Both open the file in the preview.
* named chip. Both open the file in the preview; an image steps through
* the message's other images (`gallery`).
*/
export default function MessageAttachment({
name,
media_type,
url,
thumbnail_url,
}: BotMessageAttachment) {
gallery,
}: BotMessageAttachment & { gallery?: FilePreviewItem[] }) {
if (media_type == "image") {
return (
<FilePreviewLink name={name} url={url} media_type={media_type} title={name} className="block">
<FilePreviewLink name={name} url={url} media_type={media_type} gallery={gallery} title={name} className="block">
<Img
src={thumbnail_url || url}
alt={name}
@@ -1,5 +1,6 @@
import Row from "@moduletrace/twui/layout/Row";
import type { BotMessageAttachment } from "@/src/types";
import imagePreviewGallery from "@/src/utils/image-preview-gallery";
import MessageAttachment from "./message-attachment";
type Props = {
@@ -7,15 +8,18 @@ type Props = {
};
/**
* A message's files, right-aligned above its bubble.
* A message's files, right-aligned above its bubble. Its images make one
* gallery, so opening one steps through the others.
*/
export default function MessageAttachments({ attachments }: Props) {
if (!attachments?.length) return null;
const gallery = imagePreviewGallery({ items: attachments });
return (
<Row className="max-w-[80%] gap-2! justify-end">
{attachments.map((attachment) => (
<MessageAttachment key={attachment.id} {...attachment} />
<MessageAttachment key={attachment.id} {...attachment} gallery={gallery} />
))}
</Row>
);
@@ -1,3 +1,4 @@
import { useMemo } from "react";
import H2 from "@moduletrace/twui/layout/H2";
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
@@ -5,6 +6,7 @@ import Stack from "@moduletrace/twui/layout/Stack";
import type { StorageFolderPayload, StorageSpecOption } from "@/src/types";
import type { StorageSpec } from "@/src/utils/storage-volumes";
import { emptyFolderText, folderSummary } from "@/src/utils/folder-text";
import imagePreviewGallery from "@/src/utils/image-preview-gallery";
import FilesBreadcrumbRow from "@/src/components/general/files-breadcrumb-row";
import FilesSearchInput from "@/src/components/general/files-search-input";
import FilesVolumeRow from "../(partials)/files-volume-row";
@@ -42,6 +44,11 @@ export default function FilesBrowser({
onOpenFolder,
onOpenVolume,
}: Props) {
const gallery = useMemo(
() => imagePreviewGallery({ items: (folder?.entries || []).map((entry) => ({ ...entry, url: entry.url || "" })) }),
[folder],
);
return (
<Row className="w-full mt-6 gap-6! flex-wrap items-start lg:flex-nowrap">
<Stack className="w-full lg:w-[180px] shrink-0 items-stretch">
@@ -98,6 +105,7 @@ export default function FilesBrowser({
entry.kind == "folder" &&
entry.path == path
}
gallery={gallery}
onOpenFolder={onOpenFolder}
/>
))
+12
View File
@@ -1427,6 +1427,18 @@ export type BotFileScopesPayload = {
/**
* One entry in a folder the files browser shows: a file or a subfolder.
*/
/**
* One file the preview can show: its name, where its bytes are, and what
* kind of media it is. A list of them is a preview's gallery (the images
* of a folder or a message), stepped through with Previous and Next.
*/
export type FilePreviewItem = {
name: string;
url: string;
media_type?: string | null;
size?: number;
};
export type StorageEntry = {
name: string;
/**
+11
View File
@@ -0,0 +1,11 @@
import type { FilePreviewItem } from "@/src/types";
/**
* Where a file stands in a gallery, by its URL, or -1 when it isn't in it
* (the preview then shows it alone, without Previous and Next).
*/
export default function galleryIndex({ gallery, url }: { gallery?: FilePreviewItem[]; url: string }) {
if (!gallery?.length || !url) return -1;
return gallery.findIndex((item) => item.url == url);
}
+24
View File
@@ -0,0 +1,24 @@
import { expect, test } from "bun:test";
import galleryIndex from "./gallery-index";
import imagePreviewGallery from "./image-preview-gallery";
const items = [
{ name: "notes.md", url: "/media/1" },
{ name: "shot-1.png", url: "/media/2" },
{ name: "raw", url: "" },
{ name: "photo", url: "/media/3", media_type: "image" },
{ name: "clip.mp4", url: "/media/4" },
{ name: "logo.svg", url: "/media/5" },
];
test("a gallery keeps only the images, in the folder's order", () => {
expect(imagePreviewGallery({ items }).map((item) => item.url)).toEqual(["/media/2", "/media/3", "/media/5"]);
});
test("a file is found in its gallery by its URL", () => {
const gallery = imagePreviewGallery({ items });
expect(galleryIndex({ gallery, url: "/media/3" })).toBe(1);
expect(galleryIndex({ gallery, url: "/media/1" })).toBe(-1);
expect(galleryIndex({ gallery: undefined, url: "/media/3" })).toBe(-1);
});
+15
View File
@@ -0,0 +1,15 @@
import type { FilePreviewItem } from "@/src/types";
import filePreviewKind from "./file-preview-kind";
/**
* The images in a list of files, in the list's order: what the preview
* steps through with Previous and Next. Files without a URL are left out,
* and so is every other kind (a gallery is for looking at pictures).
*/
export default function imagePreviewGallery({ items }: { items: FilePreviewItem[] }): FilePreviewItem[] {
return items.filter(
(item) =>
Boolean(item.url) &&
filePreviewKind({ name: item.name, media_type: item.media_type }) == "image",
);
}