Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
38648fc083 | ||
|
|
6414d4e675 | ||
|
|
ae64ef195d | ||
|
|
06a4b7bb36 | ||
|
|
2c8023ee4b | ||
|
|
c0e79ee39c |
@@ -95,11 +95,11 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). While a reply is due (read with the live face, never the page's) the page polls `session-messages` (`use-reply-catch-up`, also at once when the page comes back into view or online) in case a push was missed, replaying the messages and the bot's face and task as their pushes.
|
||||
- **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 `/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/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. 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.
|
||||
- **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. 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`.
|
||||
- **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`. A reply's history shows the user's own reactions on each bot message in its app record (`botMessagesToHarness`, so `run-bot-reply` loads history with `user_id`), and the chat reply note tells the bot to save lasting preferences they show in its memory of that user; 👎 is in the set for that.
|
||||
- **Attachments:** uploaded on pick (`upload-attachment.ts`, private `media`, no text kept: a reply reads a document's text from the file), linked via `bot_message_media`. Replies read files of the last `BotReplyAttachmentMessages` messages. Tasks don't get files yet.
|
||||
- **Thinking row / stop:** `bot-busy-state.ts` decides the row's line and whether Stop shows. Stop (`api/admin/bots/stop.ts`, `stop-bot-jobs`) fails every open job of that bot for the user, aborts the running handler (`job-abort-registry`) and drops late face updates.
|
||||
- **Voice:** mic -> `api/admin/bots/transcribe.ts`; play -> `GET speak-message` streamed into `<audio>`. Nothing recorded is stored. Both disabled with a note when the harness has no model.
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.15.0",
|
||||
"version": "0.15.3",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -212,3 +212,64 @@ describe("botMessagesToHarness with mentions", () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("botMessagesToHarness with reactions", () => {
|
||||
test("adds the user's reactions to the record of the message's tools", () => {
|
||||
expect(
|
||||
botMessagesToHarness({
|
||||
messages: [
|
||||
message("user", "summarise it"),
|
||||
{
|
||||
...message("bot", "Here it is."),
|
||||
tool_log: JSON.stringify([{ name: "read_file", ok: true }]),
|
||||
reactions: [
|
||||
{ emoji: "👍" as const, count: 1, mine: true },
|
||||
{ emoji: "👎" as const, count: 1, mine: true },
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toEqual([
|
||||
{ role: "user", content: "summarise it" },
|
||||
{
|
||||
role: "assistant",
|
||||
content:
|
||||
"Here it is.\n\n[App record: this message's run called read_file. The user reacted to it with 👍 (like), 👎 (dislike).]",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("records reactions on a message whose run wasn't recorded", () => {
|
||||
expect(
|
||||
botMessagesToHarness({
|
||||
messages: [
|
||||
message("user", "hi"),
|
||||
{
|
||||
...message("bot", "hello"),
|
||||
reactions: [{ emoji: "❤️" as const, count: 1, mine: true }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toEqual([
|
||||
{ role: "user", content: "hi" },
|
||||
{ role: "assistant", content: "hello\n\n[App record: The user reacted to it with ❤️ (love).]" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("leaves out reactions that aren't the user's", () => {
|
||||
expect(
|
||||
botMessagesToHarness({
|
||||
messages: [
|
||||
message("user", "hi"),
|
||||
{
|
||||
...message("bot", "hello"),
|
||||
reactions: [{ emoji: "🎉" as const, count: 1, mine: false }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toEqual([
|
||||
{ role: "user", content: "hi" },
|
||||
{ role: "assistant", content: "hello" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import isCrewMessage from "@/src/utils/is-crew-message";
|
||||
import { BotMessageReactions } from "@/src/dict/bot-dict";
|
||||
import describeToolUses from "@/src/harness/text/describe-tool-uses";
|
||||
import type { HarnessContentPart, HarnessMessage, HarnessToolUse } from "@/src/harness/types";
|
||||
import type { BotMessageWithAttachments } from "@/src/types";
|
||||
import type { BotMessageReaction, BotMessageWithAttachments } from "@/src/types";
|
||||
import describeMessageRefs, { type MessageRefNames } from "@/src/utils/describe-message-refs";
|
||||
import { AppRecordPrefix } from "@/src/utils/strip-app-records";
|
||||
import describeAttachment from "./describe-attachment";
|
||||
@@ -10,7 +11,15 @@ import crewMessageBlock from "@/src/utils/crew-message-block";
|
||||
type Params = {
|
||||
messages: Pick<
|
||||
BotMessageWithAttachments,
|
||||
"id" | "author" | "text" | "attachments" | "reply_to" | "tool_log" | "from_chatroom_id" | "from_install_request_id"
|
||||
| "id"
|
||||
| "author"
|
||||
| "text"
|
||||
| "attachments"
|
||||
| "reply_to"
|
||||
| "tool_log"
|
||||
| "reactions"
|
||||
| "from_chatroom_id"
|
||||
| "from_install_request_id"
|
||||
>[];
|
||||
/**
|
||||
* Loaded files by message id (`loadAttachmentParts`). Files of other
|
||||
@@ -34,7 +43,8 @@ type Turn = { role: "user" | "assistant"; parts: HarnessContentPart[] };
|
||||
* starts with the user. A turn that is only text stays a string. A bot
|
||||
* message whose run was recorded (`tool_log`) is followed by the app's
|
||||
* record of the tools it called, so the bot can tell what its past
|
||||
* messages actually did from what they say. A chatroom's outcome brought
|
||||
* messages actually did from what they say, and of how the user reacted
|
||||
* to it, their feedback on it. A chatroom's outcome brought
|
||||
* back to the bot, or the coordinator's answer to its install request
|
||||
* (`isCrewMessage`), is a user turn fenced as what the
|
||||
* coordinator passed on (`crewMessageBlock`), never the user's words.
|
||||
@@ -95,7 +105,9 @@ function messageParts({
|
||||
const content: HarnessContentPart[] = text ? [{ type: "text", text }] : [];
|
||||
|
||||
if (role == "assistant") {
|
||||
const record = text ? appRecord({ tool_log: message.tool_log }) : "";
|
||||
const record = text
|
||||
? appRecord({ tool_log: message.tool_log, reactions: message.reactions })
|
||||
: "";
|
||||
|
||||
return record ? [...content, { type: "text", text: record }] : content;
|
||||
}
|
||||
@@ -116,10 +128,25 @@ function messageParts({
|
||||
}
|
||||
|
||||
/**
|
||||
* The app's line after a bot message naming the tools its run called, or
|
||||
* nothing when the run wasn't recorded.
|
||||
* The app's line after a bot message naming the tools its run called and
|
||||
* the user's own reactions to it, or nothing when there's neither.
|
||||
*/
|
||||
function appRecord({ tool_log }: { tool_log?: string | null }) {
|
||||
function appRecord({
|
||||
tool_log,
|
||||
reactions,
|
||||
}: {
|
||||
tool_log?: string | null;
|
||||
reactions?: BotMessageReaction[];
|
||||
}) {
|
||||
const facts = [toolsRecord({ tool_log }), reactionsRecord({ reactions })].filter(Boolean);
|
||||
|
||||
return facts.length ? `${AppRecordPrefix} ${facts.join(" ")}]` : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* The tools a recorded run called, or nothing when it wasn't recorded.
|
||||
*/
|
||||
function toolsRecord({ tool_log }: { tool_log?: string | null }) {
|
||||
if (!tool_log) return "";
|
||||
|
||||
let uses: HarnessToolUse[];
|
||||
@@ -134,7 +161,23 @@ function appRecord({ tool_log }: { tool_log?: string | null }) {
|
||||
|
||||
const called = uses.length ? describeToolUses({ uses }) : "no tools";
|
||||
|
||||
return `${AppRecordPrefix} this message's run called ${called}.]`;
|
||||
return `this message's run called ${called}.`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The reactions the user gave a message, named, or nothing. A bot's own
|
||||
* reactions aren't the user's feedback.
|
||||
*/
|
||||
function reactionsRecord({ reactions }: { reactions?: BotMessageReaction[] }) {
|
||||
const named = (reactions || [])
|
||||
.filter((reaction) => reaction.mine)
|
||||
.map((reaction) => {
|
||||
const title = BotMessageReactions.find((known) => known.value == reaction.emoji)?.title;
|
||||
|
||||
return title ? `${reaction.emoji} (${title.toLowerCase()})` : reaction.emoji;
|
||||
});
|
||||
|
||||
return named.length ? `The user reacted to it with ${named.join(", ")}.` : "";
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -108,6 +108,7 @@ export default async function runBotReply({
|
||||
const history = await grabBotMessages({
|
||||
session_id,
|
||||
limit: AppData.BotReplyHistoryMessages,
|
||||
user_id,
|
||||
});
|
||||
|
||||
const answered_id = await grabAnsweredMessageId({ session_id });
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import Img from "@moduletrace/twui/layout/Img";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import type { FilePreviewKind } from "@/src/utils/file-preview-kind";
|
||||
import FilePreviewNotice from "./file-preview-notice";
|
||||
import ImageViewer from "./image-viewer";
|
||||
import FilePreviewText from "./file-preview-text";
|
||||
|
||||
type Props = {
|
||||
@@ -13,7 +13,8 @@ type Props = {
|
||||
|
||||
/**
|
||||
* The preview itself, by kind. Media the browser draws itself (images,
|
||||
* PDFs, audio, video) load from the file's URL; text kinds are read into
|
||||
* PDFs, audio, video) load from the file's URL, an image in a viewer with
|
||||
* zoom and fits (`ImageViewer`); text kinds are read into
|
||||
* the page (`FilePreviewText`). Nothing here runs the file: an SVG shows
|
||||
* through `<img>`, which runs no script, and an HTML page in a frame
|
||||
* sandboxed twice (the attribute here and the `sandbox` CSP the media
|
||||
@@ -22,11 +23,7 @@ type Props = {
|
||||
*/
|
||||
export default function FilePreviewBody({ kind, name, url, size }: Props) {
|
||||
if (kind == "image") {
|
||||
return (
|
||||
<Stack className="grow min-h-0 w-full items-center justify-center p-4 overflow-auto bg-sunken">
|
||||
<Img src={url} alt={name} className="max-w-full max-h-full object-contain" />
|
||||
</Stack>
|
||||
);
|
||||
return <ImageViewer url={url} name={name} />;
|
||||
}
|
||||
|
||||
if (kind == "pdf") {
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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,15 +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;
|
||||
};
|
||||
|
||||
@@ -24,16 +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
|
||||
@@ -57,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}
|
||||
@@ -78,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,8 @@ 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", () => {
|
||||
const html = renderToString(
|
||||
@@ -51,3 +53,36 @@ test("a file link stays a real link to the bytes until clicked", () => {
|
||||
expect(html).toContain('href="/media/9"');
|
||||
expect(html).toContain("Preview report.md");
|
||||
});
|
||||
|
||||
test("an image opens in the viewer, with its zoom and fit controls", () => {
|
||||
const html = renderToString(<FilePreviewBody kind="image" name="page.png" url="/media/5" />);
|
||||
|
||||
expect(html).toContain('src="/media/5"');
|
||||
expect(html).toContain("Zoom in (+)");
|
||||
expect(html).toContain("Zoom out (-)");
|
||||
expect(html).toContain("Fit width");
|
||||
expect(html).toContain("Actual size");
|
||||
});
|
||||
|
||||
test("a folder link stays a real link to the files browser until clicked", () => {
|
||||
const html = renderToString(
|
||||
<FolderPreviewLink spec={{ volume: "bots", owner_id: 3 }} path="reports" href="/admin/files?volume=bots&owner=3&path=reports" title="Open reports">
|
||||
reports
|
||||
</FolderPreviewLink>,
|
||||
);
|
||||
|
||||
expect(html).toContain('href="/admin/files?volume=bots&owner=3&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);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { useState, type ReactNode } from "react";
|
||||
import Link from "@moduletrace/twui/layout/Link";
|
||||
import isPlainClick from "@/src/utils/is-plain-click";
|
||||
import type { StorageSpec } from "@/src/utils/storage-volumes";
|
||||
import FolderPreviewModal from "./folder-preview-modal";
|
||||
|
||||
type Props = {
|
||||
spec: StorageSpec;
|
||||
path: string;
|
||||
/**
|
||||
* The folder in the files browser, where a modified click goes.
|
||||
*/
|
||||
href: string;
|
||||
title?: string;
|
||||
className?: string;
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
/**
|
||||
* A link to a folder that opens it over the page (`FolderPreviewModal`) on
|
||||
* a plain click. It stays a real link to the files browser, so a middle
|
||||
* click or Ctrl/Cmd click still opens the folder there in a new tab.
|
||||
*/
|
||||
export default function FolderPreviewLink({ spec, path, href, title, className, children }: Props) {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Link
|
||||
href={href}
|
||||
title={title}
|
||||
onClick={(event) => {
|
||||
if (!isPlainClick({ event })) return;
|
||||
|
||||
event.preventDefault();
|
||||
setOpen(true);
|
||||
}}
|
||||
className={className}
|
||||
>
|
||||
{children}
|
||||
</Link>
|
||||
{open ? <FolderPreviewModal spec={spec} path={path} onClose={() => setOpen(false)} /> : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
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";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { SquareArrowOutUpRight } from "lucide-react";
|
||||
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";
|
||||
import StorageEntryRow from "./storage-entry-row";
|
||||
|
||||
type Props = {
|
||||
spec: StorageSpec;
|
||||
/**
|
||||
* The folder it opens on, inside the volume (empty at the top).
|
||||
*/
|
||||
path: string;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* 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 (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.
|
||||
*/
|
||||
export default function FolderPreviewModal({ spec, path: start_path, onClose }: Props) {
|
||||
const [path, set_path] = useState(start_path);
|
||||
const [search, set_search] = useState("");
|
||||
const query = useDebouncedValue({ value: search.trim() });
|
||||
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) => {
|
||||
set_path(next_path);
|
||||
set_search("");
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open
|
||||
setOpen={(next_open) => {
|
||||
if (!next_open) onClose();
|
||||
}}
|
||||
className="max-w-3xl! w-[95vw] h-[85vh] p-0 bg-paper flex flex-col overflow-hidden"
|
||||
>
|
||||
<Row className="w-full gap-3! flex-nowrap items-center pl-5 pr-14 py-3 border-0 border-b border-solid border-hairline">
|
||||
<Stack className="min-w-0 grow gap-0! items-start">
|
||||
<H2
|
||||
title={path || name}
|
||||
className="text-base! leading-6! tracking-normal! font-bold text-ink truncate w-full"
|
||||
>
|
||||
{name}
|
||||
</H2>
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{folderSummary({ folder })}
|
||||
</Span>
|
||||
</Stack>
|
||||
<Link
|
||||
href={storageSpecHref({ spec, path })}
|
||||
title="Open this folder in Files"
|
||||
className="shrink-0 inline-flex items-center gap-1.5 px-2 py-1.5 text-[13px] leading-[18px] text-ink-secondary hover:text-ink rounded-default hover:bg-sunken no-underline"
|
||||
>
|
||||
<SquareArrowOutUpRight size={16} aria-hidden />
|
||||
<Span className="hidden sm:inline">Open in Files</Span>
|
||||
</Link>
|
||||
</Row>
|
||||
<Stack className="w-full gap-0! items-stretch px-5">
|
||||
<FilesBreadcrumbRow crumbs={folder?.breadcrumbs || []} onOpenFolder={openFolder} />
|
||||
<FilesSearchInput value={search} onChange={set_search} />
|
||||
</Stack>
|
||||
<Stack className="grow min-h-0 w-full mt-2 gap-0! items-stretch overflow-y-auto px-5 pb-4">
|
||||
{folder?.entries.length ? (
|
||||
folder.entries.map((entry) => (
|
||||
<StorageEntryRow
|
||||
key={entry.path}
|
||||
entry={entry}
|
||||
selected={entry.kind == "folder" && entry.path == path}
|
||||
gallery={gallery}
|
||||
onOpenFolder={openFolder}
|
||||
/>
|
||||
))
|
||||
) : (
|
||||
<Span className="py-8 text-[13px] leading-[18px] text-ink-secondary">
|
||||
{emptyFolderText({ folder, search, loading, error })}
|
||||
</Span>
|
||||
)}
|
||||
</Stack>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
export type ImageViewerTool = {
|
||||
id: string;
|
||||
icon: LucideIcon;
|
||||
/**
|
||||
* What it does, with its key, for the tooltip and screen readers.
|
||||
*/
|
||||
title: string;
|
||||
/**
|
||||
* Shown beside the icon on wider screens; icon only without one.
|
||||
*/
|
||||
label?: string;
|
||||
pressed?: boolean;
|
||||
disabled?: boolean;
|
||||
onClick: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* One control on the image preview's toolbar: a zoom, or a preset that
|
||||
* shows as pressed while it is the one in use.
|
||||
*/
|
||||
export default function ImageViewerToolButton({ icon: Icon, title, label, pressed, disabled, onClick }: ImageViewerTool) {
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
title={title}
|
||||
aria-label={title}
|
||||
aria-pressed={pressed}
|
||||
disabled={disabled}
|
||||
onClick={onClick}
|
||||
className={twMerge("gap-1.5! text-ink-secondary hover:text-ink", pressed && "bg-ink/5 text-ink")}
|
||||
>
|
||||
<Icon size={16} aria-hidden />
|
||||
{label ? <Span className="hidden sm:inline text-[13px] leading-[18px]">{label}</Span> : null}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import { MoveHorizontal, Scan, Shrink, ZoomIn, ZoomOut } from "lucide-react";
|
||||
import {
|
||||
ImageViewerMaxScale,
|
||||
ImageViewerMinScale,
|
||||
type ImageViewerMode,
|
||||
} from "@/src/dict/image-viewer-dict";
|
||||
import ImageViewerToolButton, { type ImageViewerTool } from "./image-viewer-tool-button";
|
||||
|
||||
type Props = {
|
||||
mode: ImageViewerMode;
|
||||
scale: number;
|
||||
natural: { width: number; height: number } | null;
|
||||
onZoom: (direction: "in" | "out") => void;
|
||||
onChoose: (mode: Exclude<ImageViewerMode, "custom">) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* The image preview's controls: zoom out and in around the zoom level,
|
||||
* the presets (whole, the frame's width, actual size), and the picture's
|
||||
* own size in pixels.
|
||||
*/
|
||||
export default function ImageViewerToolbar({ mode, scale, natural, onZoom, onChoose }: Props) {
|
||||
const loaded = Boolean(natural);
|
||||
const zoom_out: ImageViewerTool = {
|
||||
id: "out",
|
||||
icon: ZoomOut,
|
||||
title: "Zoom out (-)",
|
||||
disabled: !loaded || scale <= ImageViewerMinScale,
|
||||
onClick: () => onZoom("out"),
|
||||
};
|
||||
const zoom_in: ImageViewerTool = {
|
||||
id: "in",
|
||||
icon: ZoomIn,
|
||||
title: "Zoom in (+)",
|
||||
disabled: !loaded || scale >= ImageViewerMaxScale,
|
||||
onClick: () => onZoom("in"),
|
||||
};
|
||||
const preset_tools: ImageViewerTool[] = [
|
||||
{
|
||||
id: "fit",
|
||||
icon: Shrink,
|
||||
title: "Show the whole image (0)",
|
||||
label: "Fit",
|
||||
pressed: mode == "fit",
|
||||
disabled: !loaded,
|
||||
onClick: () => onChoose("fit"),
|
||||
},
|
||||
{
|
||||
id: "width",
|
||||
icon: MoveHorizontal,
|
||||
title: "Fit the width and scroll down (W)",
|
||||
label: "Fit width",
|
||||
pressed: mode == "width",
|
||||
disabled: !loaded,
|
||||
onClick: () => onChoose("width"),
|
||||
},
|
||||
{
|
||||
id: "actual",
|
||||
icon: Scan,
|
||||
title: "Actual size, one image pixel per screen pixel (1)",
|
||||
label: "Actual size",
|
||||
pressed: mode == "actual",
|
||||
disabled: !loaded,
|
||||
onClick: () => onChoose("actual"),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<Row className="w-full gap-1! flex-wrap items-center px-3 py-1.5 border-0 border-b border-solid border-hairline bg-paper">
|
||||
<ImageViewerToolButton {...zoom_out} />
|
||||
<Span className="min-w-12 text-center text-[13px] leading-[18px] font-bold tabular-nums text-ink">
|
||||
{loaded ? `${Math.round(scale * 100)}%` : "..."}
|
||||
</Span>
|
||||
<ImageViewerToolButton {...zoom_in} />
|
||||
<Span className="inline-block mx-1 h-5 w-px bg-hairline" aria-hidden />
|
||||
{preset_tools.map((tool) => (
|
||||
<ImageViewerToolButton key={tool.id} {...tool} />
|
||||
))}
|
||||
{natural ? (
|
||||
<Span className="ml-auto pl-2 text-[12px] leading-4 tabular-nums text-ink-secondary">
|
||||
{`${natural.width} x ${natural.height} px`}
|
||||
<Span className="hidden md:inline">{" · Ctrl + scroll to zoom, drag to move"}</Span>
|
||||
</Span>
|
||||
) : null}
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import Img from "@moduletrace/twui/layout/Img";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import type { RefObject } from "react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import useImageViewer from "@/src/hooks/use-image-viewer";
|
||||
import useImageViewerGestures from "@/src/hooks/use-image-viewer-gestures";
|
||||
import FilePreviewNotice from "./file-preview-notice";
|
||||
import ImageViewerToolbar from "./image-viewer-toolbar";
|
||||
|
||||
type Props = {
|
||||
url: string;
|
||||
name: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* An image in the file preview, to inspect rather than glance at: zoom
|
||||
* (buttons, keys, Ctrl/Cmd + wheel or a pinch at the pointer), fit whole,
|
||||
* fit the width (a full-page screenshot opens that way and scrolls down),
|
||||
* actual size, double click to zoom into a spot, drag to move around.
|
||||
* The picture is sized with its `width` attribute, so no style is set,
|
||||
* and centred with auto margins, which (unlike flex centring) never push
|
||||
* the top of a picture taller than the frame out of reach.
|
||||
*/
|
||||
export default function ImageViewer({ url, name }: Props) {
|
||||
const viewer = useImageViewer();
|
||||
const { dragging, pointerHandlers } = useImageViewerGestures(viewer);
|
||||
const width = viewer.natural ? Math.max(1, Math.floor(viewer.natural.width * viewer.scale)) : undefined;
|
||||
|
||||
return (
|
||||
<Stack className="grow min-h-0 w-full gap-0! items-stretch">
|
||||
<ImageViewerToolbar
|
||||
mode={viewer.mode}
|
||||
scale={viewer.scale}
|
||||
natural={viewer.natural}
|
||||
onZoom={(direction) => viewer.zoom({ direction })}
|
||||
onChoose={(mode) => viewer.choose({ mode })}
|
||||
/>
|
||||
<Stack
|
||||
componentRef={viewer.container_ref as RefObject<HTMLDivElement>}
|
||||
{...pointerHandlers}
|
||||
onDoubleClick={(event) => viewer.toggle({ point: { x: event.clientX, y: event.clientY } })}
|
||||
className={twMerge(
|
||||
"relative grow min-h-0 w-full gap-0! items-stretch overflow-auto overscroll-contain bg-sunken select-none",
|
||||
viewer.scale < 1 && "cursor-zoom-in",
|
||||
dragging && "cursor-grabbing",
|
||||
)}
|
||||
>
|
||||
<Stack className="shrink-0 w-max min-w-full min-h-full gap-0! items-start p-4">
|
||||
<Img
|
||||
ref={viewer.image_ref}
|
||||
src={url}
|
||||
alt={name}
|
||||
loading="eager"
|
||||
draggable={false}
|
||||
width={width}
|
||||
onLoad={viewer.onImageLoad}
|
||||
imgErrComp={<FilePreviewNotice message="This image couldn't be loaded. Download it to open it." />}
|
||||
className={twMerge(
|
||||
"block shrink-0 m-auto h-auto object-contain",
|
||||
width ? "max-w-none max-h-none" : "max-w-full max-h-full",
|
||||
)}
|
||||
/>
|
||||
</Stack>
|
||||
</Stack>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
+7
-2
@@ -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}
|
||||
@@ -55,6 +55,7 @@ You are chatting with the user. Answer their latest messages directly and briefl
|
||||
- When a message mixes both, answer the quick parts in this reply and start a task for the rest.
|
||||
- When only the user can do something on a computer (log in, solve a captcha, enter a code), ask them to take over with ask_user_to_take_over and say exactly what to do. They'll tell you when they hand it back; then carry on.
|
||||
- When the user tells you something worth keeping, save it with update_memory: about them in your memory of this user, never in your core memory, which every user you work for shares. When they correct how you work for everyone, update your instructions with update_instructions; a correction that's only their preference goes in your memory of them.
|
||||
- An app record saying the user reacted to one of your messages is their feedback on it: 👍, ❤️ and 🎉 mean they liked it, 👎 that they didn't; 😂, 😮 and 😢 are how it made them feel, not a verdict. When reactions show a preference that lasts (length, format, tone, what to include or leave out), save it in your memory of this user with update_memory (scope "user", in a workspace too). One reaction to one answer isn't a preference yet, so don't save it, and don't save what your memory already says. Bring a reaction up only when it helps: after a 👎 on your last answer with no word about why, you can ask in one short question what to change.
|
||||
- To add a worker to the crew, use create_bot once the user has asked for it or agreed, and add_bot_to_workspace to place it. A bot exists only when create_bot made it: never describe one as if it did, and never write it into a workspace's context.
|
||||
- Never claim you did something you didn't do.
|
||||
- Nothing wakes you when a run ends: its result is posted here, and that's all. So never promise to do something once a run finishes. Do it in this reply (renaming a task or logging a note with update_task needs no computer), or queue it now with start_task (with separate when another run of yours is open on that computer) and say it's queued.
|
||||
|
||||
@@ -173,6 +173,10 @@ export const BotMessageReactions = [
|
||||
title: "Like",
|
||||
value: "👍",
|
||||
},
|
||||
{
|
||||
title: "Dislike",
|
||||
value: "👎",
|
||||
},
|
||||
{
|
||||
title: "Love",
|
||||
value: "❤️",
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* How the image preview sizes a picture: `fit` shows it whole, `width`
|
||||
* fills the frame's width and scrolls down (a full-page screenshot),
|
||||
* `actual` is one image pixel per screen pixel, `custom` is wherever the
|
||||
* user zoomed to. The fits never blow a small picture up past its own size.
|
||||
*/
|
||||
export const ImageViewerModes = ["fit", "width", "actual", "custom"] as const;
|
||||
|
||||
export type ImageViewerMode = (typeof ImageViewerModes)[number];
|
||||
|
||||
/**
|
||||
* The stops the zoom buttons (and `+`/`-`) step through, from
|
||||
* `ImageViewerMinScale` to `ImageViewerMaxScale`.
|
||||
*/
|
||||
export const ImageViewerZoomSteps = [
|
||||
0.05, 0.1, 0.25, 0.33, 0.5, 0.67, 0.75, 0.9, 1, 1.25, 1.5, 2, 3, 4, 6, 8, 12, 16,
|
||||
] as const;
|
||||
|
||||
export const ImageViewerMinScale = 0.05;
|
||||
|
||||
export const ImageViewerMaxScale = 16;
|
||||
|
||||
/**
|
||||
* A picture this much taller (relative to its width) than the frame opens
|
||||
* at the frame's width rather than whole: shrunk to fit, a page screenshot
|
||||
* is a thin unreadable strip.
|
||||
*/
|
||||
export const ImageViewerTallRatio = 2;
|
||||
@@ -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]);
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { useEffect, useRef, useState, type PointerEvent, type RefObject } from "react";
|
||||
import type { ImageViewerMode } from "@/src/dict/image-viewer-dict";
|
||||
import type { ImageViewerPoint } from "./use-image-viewer";
|
||||
|
||||
type Params = {
|
||||
container_ref: RefObject<HTMLDivElement | null>;
|
||||
scale_ref: RefObject<number>;
|
||||
zoom: (params: { direction: "in" | "out"; point?: ImageViewerPoint }) => void;
|
||||
zoomTo: (params: { scale: number; point?: ImageViewerPoint }) => void;
|
||||
choose: (params: { mode: Exclude<ImageViewerMode, "custom">; point?: ImageViewerPoint }) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* How much one wheel pixel zooms (a trackpad pinch arrives as small
|
||||
* Ctrl+wheel steps, a mouse wheel as large ones).
|
||||
*/
|
||||
const WheelZoomRate = 0.0025;
|
||||
|
||||
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 image preview's hands: Ctrl/Cmd + wheel (and a trackpad pinch) zooms
|
||||
* at the pointer, a plain wheel scrolls, dragging with the mouse moves a
|
||||
* picture bigger than the frame, and the keys `+` `-` zoom, `0` fits, `w`
|
||||
* fits the width and `1` shows actual size.
|
||||
*/
|
||||
export default function useImageViewerGestures({ container_ref, scale_ref, zoom, zoomTo, choose }: Params) {
|
||||
const drag_ref = useRef<{ x: number; y: number; left: number; top: number } | null>(null);
|
||||
const [dragging, set_dragging] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const container = container_ref.current;
|
||||
|
||||
if (!container) return;
|
||||
|
||||
const onWheel = (event: WheelEvent) => {
|
||||
if (!event.ctrlKey && !event.metaKey) return;
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
const pixels = event.deltaMode == 1 ? event.deltaY * 16 : event.deltaY;
|
||||
const factor = Math.exp(-pixels * WheelZoomRate);
|
||||
|
||||
zoomTo({ scale: scale_ref.current * factor, point: { x: event.clientX, y: event.clientY } });
|
||||
};
|
||||
|
||||
container.addEventListener("wheel", onWheel, { passive: false });
|
||||
|
||||
return () => container.removeEventListener("wheel", onWheel);
|
||||
}, [container_ref, scale_ref, zoomTo]);
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.ctrlKey || event.metaKey || event.altKey) return;
|
||||
|
||||
if (typingInField({ target: event.target })) return;
|
||||
|
||||
if (event.key == "+" || event.key == "=") zoom({ direction: "in" });
|
||||
else if (event.key == "-" || event.key == "_") zoom({ direction: "out" });
|
||||
else if (event.key == "0") choose({ mode: "fit" });
|
||||
else if (event.key == "w" || event.key == "W") choose({ mode: "width" });
|
||||
else if (event.key == "1") choose({ mode: "actual" });
|
||||
else return;
|
||||
|
||||
event.preventDefault();
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onKey);
|
||||
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [zoom, choose]);
|
||||
|
||||
const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {
|
||||
const container = container_ref.current;
|
||||
|
||||
if (!container || event.pointerType != "mouse" || event.button != 0) return;
|
||||
|
||||
const overflows =
|
||||
container.scrollWidth > container.clientWidth || container.scrollHeight > container.clientHeight;
|
||||
|
||||
if (!overflows) return;
|
||||
|
||||
event.preventDefault();
|
||||
container.setPointerCapture(event.pointerId);
|
||||
drag_ref.current = {
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
left: container.scrollLeft,
|
||||
top: container.scrollTop,
|
||||
};
|
||||
set_dragging(true);
|
||||
};
|
||||
|
||||
const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
|
||||
const container = container_ref.current;
|
||||
const drag = drag_ref.current;
|
||||
|
||||
if (!container || !drag) return;
|
||||
|
||||
container.scrollLeft = drag.left - (event.clientX - drag.x);
|
||||
container.scrollTop = drag.top - (event.clientY - drag.y);
|
||||
};
|
||||
|
||||
const onPointerUp = (event: PointerEvent<HTMLDivElement>) => {
|
||||
if (!drag_ref.current) return;
|
||||
|
||||
drag_ref.current = null;
|
||||
set_dragging(false);
|
||||
container_ref.current?.releasePointerCapture(event.pointerId);
|
||||
};
|
||||
|
||||
return {
|
||||
dragging,
|
||||
pointerHandlers: {
|
||||
onPointerDown,
|
||||
onPointerMove,
|
||||
onPointerUp,
|
||||
onPointerCancel: onPointerUp,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
import type { ImageViewerMode } from "@/src/dict/image-viewer-dict";
|
||||
import imageViewerClampScale from "@/src/utils/image-viewer-clamp-scale";
|
||||
import imageViewerDefaultMode from "@/src/utils/image-viewer-default-mode";
|
||||
import imageViewerFitScale from "@/src/utils/image-viewer-fit-scale";
|
||||
import imageViewerZoomStep from "@/src/utils/image-viewer-zoom-step";
|
||||
|
||||
type Size = { width: number; height: number };
|
||||
|
||||
/**
|
||||
* A point on the screen (client coordinates) a zoom keeps still.
|
||||
*/
|
||||
export type ImageViewerPoint = { x: number; y: number };
|
||||
|
||||
/**
|
||||
* Where a zoom lands: the part of the picture under a point stays under it,
|
||||
* or the view goes back to the top left.
|
||||
*/
|
||||
type Anchor = { fx: number; fy: number; ax: number; ay: number } | "top";
|
||||
|
||||
/**
|
||||
* The frame's padding on each side (the frame's `p-4`), left out of the
|
||||
* room a fit has.
|
||||
*/
|
||||
const FramePadding = 16;
|
||||
|
||||
function clampUnit({ value }: { value: number }) {
|
||||
if (!Number.isFinite(value)) return 0.5;
|
||||
|
||||
return Math.min(1, Math.max(0, value));
|
||||
}
|
||||
|
||||
/**
|
||||
* The image preview's state: how big the picture is drawn and where the
|
||||
* frame is scrolled. A preset (`fit`, `width`, `actual`) follows the frame
|
||||
* as it resizes; a zoom keeps the part of the picture under the pointer
|
||||
* (or the frame's middle) where it was, so the user can walk into a detail.
|
||||
*/
|
||||
export default function useImageViewer() {
|
||||
const container_ref = useRef<HTMLDivElement>(null);
|
||||
const image_ref = useRef<HTMLImageElement>(null);
|
||||
const anchor_ref = useRef<Anchor | null>(null);
|
||||
const [natural, set_natural] = useState<Size | null>(null);
|
||||
const [frame, set_frame] = useState<Size>({ width: 0, height: 0 });
|
||||
const [mode, set_mode] = useState<ImageViewerMode | null>(null);
|
||||
const [custom_scale, set_custom_scale] = useState(1);
|
||||
const [tick, set_tick] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
const container = container_ref.current;
|
||||
|
||||
if (!container || typeof ResizeObserver == "undefined") return;
|
||||
|
||||
const measure = () =>
|
||||
set_frame({
|
||||
width: Math.max(0, container.clientWidth - FramePadding * 2),
|
||||
height: Math.max(0, container.clientHeight - FramePadding * 2),
|
||||
});
|
||||
|
||||
measure();
|
||||
|
||||
const observer = new ResizeObserver(measure);
|
||||
|
||||
observer.observe(container);
|
||||
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (mode || !natural || !frame.width) return;
|
||||
|
||||
set_mode(imageViewerDefaultMode({ natural, frame }));
|
||||
}, [mode, natural, frame]);
|
||||
|
||||
const shown_mode: ImageViewerMode = mode || "fit";
|
||||
const scale = !natural
|
||||
? 1
|
||||
: shown_mode == "custom"
|
||||
? custom_scale
|
||||
: imageViewerFitScale({ mode: shown_mode, natural, frame });
|
||||
const scale_ref = useRef(scale);
|
||||
|
||||
scale_ref.current = scale;
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const anchor = anchor_ref.current;
|
||||
const container = container_ref.current;
|
||||
const image = image_ref.current;
|
||||
|
||||
anchor_ref.current = null;
|
||||
|
||||
if (!anchor || !container || !image) return;
|
||||
|
||||
if (anchor == "top") {
|
||||
container.scrollTo({ left: 0, top: 0 });
|
||||
return;
|
||||
}
|
||||
|
||||
container.scrollLeft = image.offsetLeft + anchor.fx * image.offsetWidth - anchor.ax;
|
||||
container.scrollTop = image.offsetTop + anchor.fy * image.offsetHeight - anchor.ay;
|
||||
}, [scale, tick]);
|
||||
|
||||
/**
|
||||
* Which part of the picture is under a point (the frame's middle when
|
||||
* none is given), to keep it there after the zoom.
|
||||
*/
|
||||
const captureAnchor = useCallback(({ point }: { point?: ImageViewerPoint }): Anchor | null => {
|
||||
const container = container_ref.current;
|
||||
const image = image_ref.current;
|
||||
|
||||
if (!container || !image) return null;
|
||||
|
||||
const box = container.getBoundingClientRect();
|
||||
const at = point || {
|
||||
x: box.left + container.clientLeft + container.clientWidth / 2,
|
||||
y: box.top + container.clientTop + container.clientHeight / 2,
|
||||
};
|
||||
const rect = image.getBoundingClientRect();
|
||||
|
||||
return {
|
||||
fx: clampUnit({ value: (at.x - rect.left) / (rect.width || 1) }),
|
||||
fy: clampUnit({ value: (at.y - rect.top) / (rect.height || 1) }),
|
||||
ax: at.x - box.left - container.clientLeft,
|
||||
ay: at.y - box.top - container.clientTop,
|
||||
};
|
||||
}, []);
|
||||
|
||||
const zoomTo = useCallback(
|
||||
({ scale: next, point }: { scale: number; point?: ImageViewerPoint }) => {
|
||||
anchor_ref.current = captureAnchor({ point });
|
||||
set_custom_scale(imageViewerClampScale({ scale: next }));
|
||||
set_mode("custom");
|
||||
set_tick((value) => value + 1);
|
||||
},
|
||||
[captureAnchor],
|
||||
);
|
||||
|
||||
const zoom = useCallback(
|
||||
({ direction, point }: { direction: "in" | "out"; point?: ImageViewerPoint }) =>
|
||||
zoomTo({ scale: imageViewerZoomStep({ scale: scale_ref.current, direction }), point }),
|
||||
[zoomTo],
|
||||
);
|
||||
|
||||
/**
|
||||
* A preset. Fitting starts from the top left (a page screenshot reads
|
||||
* from its top); actual size keeps the point (or the middle) in view.
|
||||
*/
|
||||
const choose = useCallback(
|
||||
({ mode: next, point }: { mode: Exclude<ImageViewerMode, "custom">; point?: ImageViewerPoint }) => {
|
||||
anchor_ref.current = next == "actual" ? captureAnchor({ point }) : "top";
|
||||
set_mode(next);
|
||||
set_tick((value) => value + 1);
|
||||
},
|
||||
[captureAnchor],
|
||||
);
|
||||
|
||||
/**
|
||||
* A double click: into actual size at that point from anything
|
||||
* smaller, else back to the picture's own fit.
|
||||
*/
|
||||
const toggle = useCallback(
|
||||
({ point }: { point: ImageViewerPoint }) => {
|
||||
if (scale_ref.current < 1) return choose({ mode: "actual", point });
|
||||
|
||||
if (!natural) return;
|
||||
|
||||
choose({ mode: imageViewerDefaultMode({ natural, frame }) });
|
||||
},
|
||||
[choose, natural, frame],
|
||||
);
|
||||
|
||||
const onImageLoad = useCallback(() => {
|
||||
const image = image_ref.current;
|
||||
|
||||
if (!image?.naturalWidth || !image.naturalHeight) return;
|
||||
|
||||
set_natural({ width: image.naturalWidth, height: image.naturalHeight });
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (image_ref.current?.complete) onImageLoad();
|
||||
}, [onImageLoad]);
|
||||
|
||||
return {
|
||||
container_ref,
|
||||
image_ref,
|
||||
natural,
|
||||
mode: shown_mode,
|
||||
scale,
|
||||
scale_ref,
|
||||
zoom,
|
||||
zoomTo,
|
||||
choose,
|
||||
toggle,
|
||||
onImageLoad,
|
||||
};
|
||||
}
|
||||
@@ -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]);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { useEffect, useId, useRef } from "react";
|
||||
|
||||
/**
|
||||
* The open modals that close on Escape one at a time, oldest first.
|
||||
*/
|
||||
const OpenModals: string[] = [];
|
||||
|
||||
/**
|
||||
* Escape closes only the modal on top. twui's modal closes every open one
|
||||
* on the same key press, so a file opened from a folder (or a folder from
|
||||
* a file) would take both away. Listening first, on the window's capture
|
||||
* phase, the modal on top closes itself and the press goes no further.
|
||||
*/
|
||||
export default function useTopModalEscape({ onClose }: { onClose: () => void }) {
|
||||
const id = useId();
|
||||
const close_ref = useRef(onClose);
|
||||
|
||||
close_ref.current = onClose;
|
||||
|
||||
useEffect(() => {
|
||||
OpenModals.push(id);
|
||||
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.key != "Escape" || OpenModals.at(-1) != id) return;
|
||||
|
||||
event.stopPropagation();
|
||||
close_ref.current();
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onKey, true);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onKey, true);
|
||||
|
||||
const index = OpenModals.lastIndexOf(id);
|
||||
|
||||
if (index >= 0) OpenModals.splice(index, 1);
|
||||
};
|
||||
}, [id]);
|
||||
}
|
||||
@@ -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,6 +1,6 @@
|
||||
import Link from "@moduletrace/twui/layout/Link";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import { FolderOpen } from "lucide-react";
|
||||
import FolderPreviewLink from "@/src/components/general/folder-preview-link";
|
||||
import { folderRefUrl } from "@/src/utils/folder-ref";
|
||||
import { storagePathName, type StorageSpec } from "@/src/utils/storage-volumes";
|
||||
|
||||
@@ -11,11 +11,13 @@ type Props = {
|
||||
|
||||
/**
|
||||
* A folder a bot named in a message (`folderRef`): the name it ends with,
|
||||
* linked into the files browser, where the user can look at everything in
|
||||
* it. Nothing is downloaded: a folder ref never serves bytes, and this chip
|
||||
* never guesses from the name whether it is a file or a folder, because the
|
||||
* ref itself already says it is a folder. A file the bot saved is a file
|
||||
* ref (`fileRef`) and opens the file instead.
|
||||
* opening the folder over the chat (`FolderPreviewModal`), where each file
|
||||
* opens in its own preview. It stays a link to the same folder in the
|
||||
* files browser, for a middle or Ctrl/Cmd click and the modal's "Open in
|
||||
* Files". Nothing is downloaded: a folder ref never serves bytes, and this
|
||||
* chip never guesses from the name whether it is a file or a folder,
|
||||
* because the ref itself already says it is a folder. A file the bot saved
|
||||
* is a file ref (`fileRef`) and opens the file instead.
|
||||
*
|
||||
* Written without a literal ref in this comment on purpose: Tailwind scans
|
||||
* every page and partial, reads a bracketed `name:value` as an
|
||||
@@ -26,13 +28,15 @@ export default function FolderRefChip({ spec, path }: Props) {
|
||||
const name = storagePathName({ volume: spec.volume, path });
|
||||
|
||||
return (
|
||||
<Link
|
||||
<FolderPreviewLink
|
||||
spec={spec}
|
||||
path={path}
|
||||
href={folderRefUrl({ volume: spec.volume, owner_id: spec.owner_id, path })}
|
||||
title={`Open ${path || name} in Files`}
|
||||
title={`Open ${path || name}`}
|
||||
className="inline-flex h-6 max-w-full gap-1.5 items-center px-1.5 align-middle rounded-default-xs border-0 bg-sunken text-[13px] font-bold leading-4 text-ink hover:opacity-80"
|
||||
>
|
||||
<FolderOpen size={14} aria-hidden className="shrink-0" />
|
||||
<Span className="truncate">{name}</Span>
|
||||
</Link>
|
||||
</FolderPreviewLink>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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,14 +1,16 @@
|
||||
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";
|
||||
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 "../(functions)/folder-text";
|
||||
import FilesBreadcrumbRow from "../(partials)/files-breadcrumb-row";
|
||||
import FilesSearchInput from "../(partials)/files-search-input";
|
||||
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";
|
||||
import StorageEntryRow from "../(partials)/storage-entry-row";
|
||||
import StorageEntryRow from "@/src/components/general/storage-entry-row";
|
||||
import Divider from "@moduletrace/twui/layout/Divider";
|
||||
import Paper from "@moduletrace/twui/elements/Paper";
|
||||
|
||||
@@ -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}
|
||||
/>
|
||||
))
|
||||
|
||||
@@ -3,7 +3,7 @@ import useDebouncedValue from "@/src/hooks/use-debounced-value";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import type { StorageSpecOption } from "@/src/types";
|
||||
import { parseStorageSpec, type StorageSpec } from "@/src/utils/storage-volumes";
|
||||
import useStorageFolder from "../(hooks)/use-storage-folder";
|
||||
import useStorageFolder from "@/src/hooks/use-storage-folder";
|
||||
import FilesBrowser from "./files-browser";
|
||||
|
||||
/**
|
||||
|
||||
@@ -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;
|
||||
/**
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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",
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { ImageViewerMaxScale, ImageViewerMinScale } from "@/src/dict/image-viewer-dict";
|
||||
|
||||
/**
|
||||
* A scale kept inside the viewer's range (a wheel or pinch can ask for
|
||||
* anything).
|
||||
*/
|
||||
export default function imageViewerClampScale({ scale }: { scale: number }) {
|
||||
if (!Number.isFinite(scale)) return 1;
|
||||
|
||||
return Math.min(ImageViewerMaxScale, Math.max(ImageViewerMinScale, scale));
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { ImageViewerTallRatio, type ImageViewerMode } from "@/src/dict/image-viewer-dict";
|
||||
|
||||
type Size = { width: number; height: number };
|
||||
|
||||
/**
|
||||
* How a picture first opens: whole, unless it is far taller than the frame
|
||||
* (a full-page screenshot), which opens at the frame's width so it reads
|
||||
* from the top and scrolls down.
|
||||
*/
|
||||
export default function imageViewerDefaultMode({
|
||||
natural,
|
||||
frame,
|
||||
}: {
|
||||
natural: Size;
|
||||
frame: Size;
|
||||
}): Extract<ImageViewerMode, "fit" | "width"> {
|
||||
if (natural.width <= 0 || natural.height <= 0) return "fit";
|
||||
|
||||
if (frame.width <= 0 || frame.height <= 0) return "fit";
|
||||
|
||||
const picture = natural.height / natural.width;
|
||||
const window = frame.height / frame.width;
|
||||
|
||||
return picture > window * ImageViewerTallRatio ? "width" : "fit";
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { ImageViewerMode } from "@/src/dict/image-viewer-dict";
|
||||
|
||||
type Size = { width: number; height: number };
|
||||
|
||||
type Params = {
|
||||
mode: Exclude<ImageViewerMode, "custom">;
|
||||
natural: Size;
|
||||
frame: Size;
|
||||
};
|
||||
|
||||
/**
|
||||
* The scale a preset shows a picture at: whole (`fit`), filling the
|
||||
* frame's width (`width`) or at its own size (`actual`). Neither fit
|
||||
* enlarges a picture smaller than the frame: zooming in does that.
|
||||
*/
|
||||
export default function imageViewerFitScale({ mode, natural, frame }: Params) {
|
||||
if (mode == "actual") return 1;
|
||||
|
||||
if (natural.width <= 0 || natural.height <= 0) return 1;
|
||||
|
||||
const frame_width = Math.max(1, frame.width);
|
||||
const frame_height = Math.max(1, frame.height);
|
||||
const by_width = frame_width / natural.width;
|
||||
|
||||
if (mode == "width") return Math.min(1, by_width);
|
||||
|
||||
return Math.min(1, by_width, frame_height / natural.height);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import {
|
||||
ImageViewerMaxScale,
|
||||
ImageViewerMinScale,
|
||||
ImageViewerZoomSteps,
|
||||
} from "@/src/dict/image-viewer-dict";
|
||||
|
||||
/**
|
||||
* The next zoom stop in or out from a scale, so a fit at 37% zooms in to
|
||||
* 50%, not 47%. Stays inside the viewer's range.
|
||||
*/
|
||||
export default function imageViewerZoomStep({
|
||||
scale,
|
||||
direction,
|
||||
}: {
|
||||
scale: number;
|
||||
direction: "in" | "out";
|
||||
}) {
|
||||
const margin = 0.001;
|
||||
|
||||
if (direction == "in") {
|
||||
return ImageViewerZoomSteps.find((step) => step > scale + margin) || ImageViewerMaxScale;
|
||||
}
|
||||
|
||||
return [...ImageViewerZoomSteps].reverse().find((step) => step < scale - margin) || ImageViewerMinScale;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { ImageViewerMaxScale, ImageViewerMinScale } from "@/src/dict/image-viewer-dict";
|
||||
import imageViewerClampScale from "./image-viewer-clamp-scale";
|
||||
import imageViewerDefaultMode from "./image-viewer-default-mode";
|
||||
import imageViewerFitScale from "./image-viewer-fit-scale";
|
||||
import imageViewerZoomStep from "./image-viewer-zoom-step";
|
||||
|
||||
const frame = { width: 1000, height: 800 };
|
||||
|
||||
test("fit shows a big picture whole and never enlarges a small one", () => {
|
||||
expect(imageViewerFitScale({ mode: "fit", natural: { width: 2000, height: 1000 }, frame })).toBe(0.5);
|
||||
expect(imageViewerFitScale({ mode: "fit", natural: { width: 1000, height: 1600 }, frame })).toBe(0.5);
|
||||
expect(imageViewerFitScale({ mode: "fit", natural: { width: 200, height: 100 }, frame })).toBe(1);
|
||||
});
|
||||
|
||||
test("fit width fills the frame's width whatever the height", () => {
|
||||
expect(imageViewerFitScale({ mode: "width", natural: { width: 2880, height: 20000 }, frame })).toBeCloseTo(1000 / 2880);
|
||||
expect(imageViewerFitScale({ mode: "width", natural: { width: 400, height: 20000 }, frame })).toBe(1);
|
||||
expect(imageViewerFitScale({ mode: "actual", natural: { width: 2880, height: 20000 }, frame })).toBe(1);
|
||||
});
|
||||
|
||||
test("a full-page screenshot opens at the frame's width, a photo whole", () => {
|
||||
expect(imageViewerDefaultMode({ natural: { width: 1440, height: 9000 }, frame })).toBe("width");
|
||||
expect(imageViewerDefaultMode({ natural: { width: 4000, height: 3000 }, frame })).toBe("fit");
|
||||
expect(imageViewerDefaultMode({ natural: { width: 0, height: 0 }, frame })).toBe("fit");
|
||||
});
|
||||
|
||||
test("zoom steps move to the next stop and stay in range", () => {
|
||||
expect(imageViewerZoomStep({ scale: 0.37, direction: "in" })).toBe(0.5);
|
||||
expect(imageViewerZoomStep({ scale: 0.37, direction: "out" })).toBe(0.33);
|
||||
expect(imageViewerZoomStep({ scale: 1, direction: "in" })).toBe(1.25);
|
||||
expect(imageViewerZoomStep({ scale: ImageViewerMaxScale, direction: "in" })).toBe(ImageViewerMaxScale);
|
||||
expect(imageViewerZoomStep({ scale: ImageViewerMinScale, direction: "out" })).toBe(ImageViewerMinScale);
|
||||
expect(imageViewerClampScale({ scale: 100 })).toBe(ImageViewerMaxScale);
|
||||
expect(imageViewerClampScale({ scale: Number.NaN })).toBe(1);
|
||||
});
|
||||
@@ -4,7 +4,8 @@ type Params = {
|
||||
|
||||
/**
|
||||
* The opening of the line the app adds after a bot's past message, naming
|
||||
* the tools its run called (`botMessagesToHarness`).
|
||||
* the tools its run called and the user's reactions to it
|
||||
* (`botMessagesToHarness`).
|
||||
*/
|
||||
export const AppRecordPrefix = "[App record:";
|
||||
|
||||
|
||||
Reference in New Issue
Block a user