Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

0.8.0: drag and drop files into chats (whole chat is the target, works in the apps) (#478)

Oleksandr Ivanchenko5f98555f83ed
diff --git a/apps/mac/src/main.rs b/apps/mac/src/main.rs
index d33d274f..2b396406 100644
--- a/apps/mac/src/main.rs
+++ b/apps/mac/src/main.rs
@@ -711,6 +711,11 @@ fn make_window<R: Runtime>(app: &AppHandle<R>, place: &Place, goto: Goto, visibl
.inner_size(1280.0, 820.0)
.min_inner_size(900.0, 600.0)
.initialization_script(APP_MARK)
+ // Files dropped from Finder or Explorer go to the page, which attaches them to the open
+ // chat. Tauri's own drop handler is on by default and takes every drop (wry never hands
+ // it to WKWebView or WebView2), so the page would see no drag events at all. Nothing in
+ // the app listens for Tauri's drag-drop events. The connect and nudge windows keep it.
+ .disable_drag_drop_handler()
// The window only shows its place; another place opens in its own window, every other
// page in the default browser
.on_navigation(move |url| route(&nav_app, &nav_place, url, false))
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index ad9d4de9..04a9085d 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -12,6 +12,7 @@ import { dismiss as dismissGetStarted, isDismissed as getStartedDismissed, showC
import { useStartVersion } from './gettingStartedInstall';
import { SpaceTile } from './components/Spaces';
import { ChatView, ChatMessage, DiscussionState, RoutingState, QueuedState, SendOptions } from './components/ChatView';
+import { DropPillHost } from './components/DropLayer';
import { ReactResult, Reaction, optimisticReplyRef, reactionOf, saveReaction, senderLabel } from './reactReply';
import { PhoneTabBar, type PhoneTabItem } from './components/PhoneTabBar';
import { ThreadBar, ThreadHeader, ThreadPicker, type ThreadBarProps } from './components/ThreadBar';
@@ -3995,7 +3996,10 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
)}
</div>
) : (
- <div className={`flex-1 min-h-0 flex ${devOn ? 'kw-blueprint' : ''}`} data-main-pane>{mainPane}</div>
+ <div className={`relative flex-1 min-h-0 flex ${devOn ? 'kw-blueprint' : ''}`} data-main-pane>
+ {mainPane}
+ <DropPillHost />
+ </div>
)}
{(showPhoneList || needsSetup) && (
<PhoneTabBar
@@ -4026,8 +4030,9 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
) : (
<>
{sidebar('all')}
- <div className={`flex-1 min-w-0 min-h-0 flex ${devOn ? 'kw-blueprint' : ''}`} data-main-pane>
+ <div className={`relative flex-1 min-w-0 min-h-0 flex ${devOn ? 'kw-blueprint' : ''}`} data-main-pane>
{mainPane}
+ <DropPillHost />
</div>
</>
)}
diff --git a/frontend/src/attachments.ts b/frontend/src/attachments.ts
index c2d0a674..63808e1a 100644
--- a/frontend/src/attachments.ts
+++ b/frontend/src/attachments.ts
@@ -138,6 +138,33 @@ export function attachKind(f: { name: string; type?: string }): AttachKind | nul
return 'text';
}
+/** MIMEs refused before the drop on top of `BINARY_MIMES` and the prefixes below (0.8.0 drag preview). */
+const PREVIEW_REFUSED_EXACT = new Set(
+ (
+ 'image/heic image/heif image/avif image/tiff image/bmp image/vnd.adobe.photoshop ' +
+ 'video/x-matroska video/x-msvideo video/x-ms-wmv video/x-flv video/mpeg video/3gpp'
+ ).split(' '),
+);
+const PREVIEW_REFUSED_PREFIXES = ['audio/', 'font/', 'application/vnd.ms-', 'application/vnd.openxmlformats-officedocument.', 'application/vnd.oasis.opendocument.'];
+
+/**
+ * True when a file dragged over a chat surely can't go, from its MIME alone (no name yet). Narrower
+ * than `attachKind`, which checks the extension first: the preview must never refuse a file the drop
+ * would take, so `video/mp2t` (a `.ts` file), `image/svg+xml`, an empty or octet-stream type and any
+ * MIME not listed here are never refused.
+ */
+export function previewRefusesMime(type: string): boolean {
+ const mime = (type || '').toLowerCase().split(';')[0].trim();
+ if (!mime) return false;
+ return BINARY_MIMES.has(mime) || PREVIEW_REFUSED_EXACT.has(mime) || PREVIEW_REFUSED_PREFIXES.some((p) => mime.startsWith(p));
+}
+
+/** True for archive MIMEs (zip, tar, 7z and the like): the refusal adds "Unzip it". */
+export function isArchiveMime(type: string): boolean {
+ const mime = (type || '').toLowerCase().split(';')[0].trim();
+ return /zip|x-tar|x-7z|rar|bzip2|x-xz|gzip/.test(mime);
+}
+
/** The one line shown when a file's type can't be attached. */
export const SUPPORTED_TYPES_TEXT = 'Images, videos (MP4, MOV, WebM), PDFs and text or code files work.';
diff --git a/frontend/src/components/Attachments.tsx b/frontend/src/components/Attachments.tsx
index 5013e082..24f90e04 100644
--- a/frontend/src/components/Attachments.tsx
+++ b/frontend/src/components/Attachments.tsx
@@ -311,7 +311,11 @@ export const FileTiles: React.FC<{ files: AttachmentRef[]; align?: 'start' | 'en
);
/** A file in the composer: uploading (with progress), ready, or failed (with the reason and Retry). */
-export const UploadChip: React.FC<{ item: PendingUpload; onRemove: () => void; onRetry?: () => void }> = ({ item, onRemove, onRetry }) => {
+/**
+ * `fresh` is the chip's place in a drop that just landed (0, 1, 2…): it drops into the tray with a
+ * short stagger and a tint that fades (0.8.0 drag and drop). Everything else about the chip is as before.
+ */
+export const UploadChip: React.FC<{ item: PendingUpload; onRemove: () => void; onRetry?: () => void; fresh?: number }> = ({ item, onRemove, onRetry, fresh }) => {
const pct = Math.round(item.progress * 100);
const failed = item.state === 'error';
const video = isVideo(item.mime || item.attachment?.mime) || attachKind({ name: item.name, type: item.mime }) === 'video';
@@ -319,7 +323,9 @@ export const UploadChip: React.FC<{ item: PendingUpload; onRemove: () => void; o
<li
className={`relative flex items-center gap-2 max-w-full sm:max-w-[16rem] pl-2 pr-1 py-1 rounded-lg border text-[11px] overflow-hidden ${
failed ? 'border-rose-500/40 bg-rose-500/10' : 'border-zinc-700/70 bg-zinc-800/70'
- }`}
+ }${fresh !== undefined ? ' kw-chip-new' : ''}`}
+ data-fresh={fresh !== undefined ? 'true' : undefined}
+ style={fresh !== undefined ? ({ '--kw-chip-delay': `${40 + (fresh === 0 ? 0 : fresh === 1 ? 30 : 60)}ms` } as React.CSSProperties) : undefined}
>
{item.state === 'uploading' ? (
<Loader2 size={12} className="shrink-0 text-sky-300 animate-spin motion-reduce:animate-none" aria-hidden="true" />
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 05820776..003c0ce5 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -1,4 +1,5 @@
-import React, { Fragment, useState, useRef, useEffect, useLayoutEffect, useMemo } from 'react';
+import React, { Fragment, useState, useRef, useEffect, useLayoutEffect, useMemo, useSyncExternalStore } from 'react';
+import { flushSync } from 'react-dom';
import { queuedText } from '../claudeVm';
import { QueuedBeside } from './QueuedBeside';
import type { SwitchEntry } from '../watchLive';
@@ -52,6 +53,8 @@ import {
uploadRetryable,
uploadSlotsLeft,
} from '../attachments';
+import { DropRecipient, FOLDER_NOTE, dragHasFiles, dropAnnouncement, dropCard, modalOpen, previewDrag, splitDrop, windowDragWatch } from '../dragPreview';
+import { DropBot, DropLayer, DropPhase } from './DropLayer';
import { EarlierCopies, FileTiles, UploadChip } from './Attachments';
import { arrangeSharedFiles, botDisplayName, botOf, shareInfo } from '../sharedFiles';
import { ranOnLabel } from '../engines';
@@ -530,10 +533,38 @@ export const ChatView: React.FC<ChatViewProps> = ({
const [uploads, setUploads] = useState<PendingUpload[]>([]);
const stacked = composerStacked({ phone, focused: composerFocused, hasContent: inputVal.length > 0 || uploads.length > 0 });
const [uploadNote, setUploadNote] = useState<string | null>(null);
- const [dragOver, setDragOver] = useState(false);
const uploadFiles = useRef(new Map<string, { file: File; abort: AbortController }>());
const fileInputRef = useRef<HTMLInputElement>(null);
- const dragDepth = useRef(0);
+ // 0.8.0 drag and drop (Mira's design): the window knows a file drag is in it; this chat knows the
+ // pointer is over its column (header, list and composer, not a side pane).
+ const dragWatch = windowDragWatch();
+ const winDrag = useSyncExternalStore(dragWatch.subscribe, dragWatch.get, dragWatch.get);
+ useEffect(() => dragWatch.registerChat(), [dragWatch]);
+ const overDepth = useRef(0);
+ const [overChat, setOverChat] = useState(false);
+ // The window watch renders the armed card at sync priority; the pane's own over/refused change has to
+ // land in that same task, or the browser can paint one frame of "Drop here…" before the real card
+ // (drag events are continuous priority, so a plain setState renders a scheduler task later).
+ const overNow = useRef(false);
+ const markOver = (v: boolean) => {
+ if (overNow.current === v) return;
+ overNow.current = v;
+ flushSync(() => setOverChat(v));
+ };
+ const headerRef = useRef<HTMLDivElement>(null);
+ const columnRef = useRef<HTMLDivElement>(null);
+ const composerWrapRef = useRef<HTMLDivElement>(null);
+ const rootRef = useRef<HTMLDivElement>(null);
+ // Chips that came with the drop that just landed, by key, with their place in it (for the stagger).
+ const [freshChips, setFreshChips] = useState<Record<string, number>>({});
+ // The drop card's words for screen readers, and "3 files added for Frontend. Uploading." after a drop;
+ // cleared shortly after so the same line can be read again.
+ const [dropAnnounce, setDropAnnounce] = useState('');
+ useEffect(() => {
+ if (!dropAnnounce) return;
+ const t = setTimeout(() => setDropAnnounce(''), 4000);
+ return () => clearTimeout(t);
+ }, [dropAnnounce]);
const [openThoughts, setOpenThoughts] = useState<Record<string, boolean>>({});
const [copiedId, setCopiedId] = useState<string | null>(null);
const scrollRef = useRef<HTMLDivElement>(null);
@@ -905,10 +936,13 @@ export const ChatView: React.FC<ChatViewProps> = ({
};
/** Files from the picker, a drop or a paste: checked here, then uploaded right away. */
- const addFiles = (files: File[]) => {
- if (!files.length) return;
+ const addFiles = (files: File[], extraNotes: string[] = []): string[] => {
+ if (!files.length) {
+ if (extraNotes.length) setUploadNote(extraNotes.join(' '));
+ return [];
+ }
const room = uploadSlotsLeft(uploads);
- const notes: string[] = [];
+ const notes: string[] = [...extraNotes];
if (files.length > room) notes.push(`Up to ${MAX_ATTACHMENTS} files per message; ${files.length - room === 1 ? 'one was' : `${files.length - room} were`} left out.`);
const added: PendingUpload[] = [];
for (const file of files.slice(0, room)) {
@@ -923,6 +957,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
}
setUploadNote(notes.length ? notes.join(' ') : null);
if (added.length) setUploads((list) => [...list, ...added]);
+ return added.map((u) => u.key);
};
const removeUpload = (key: string) => {
@@ -938,34 +973,6 @@ export const ChatView: React.FC<ChatViewProps> = ({
startUpload(key, f);
};
- const hasFiles = (e: React.DragEvent) => Array.from(e.dataTransfer.types).includes('Files');
- const dropHandlers = {
- onDragEnter: (e: React.DragEvent) => {
- if (!hasFiles(e)) return;
- e.preventDefault();
- dragDepth.current += 1;
- setDragOver(true);
- },
- onDragOver: (e: React.DragEvent) => {
- if (!hasFiles(e)) return;
- e.preventDefault();
- e.dataTransfer.dropEffect = 'copy';
- },
- onDragLeave: (e: React.DragEvent) => {
- if (!hasFiles(e)) return;
- dragDepth.current = Math.max(0, dragDepth.current - 1);
- if (dragDepth.current === 0) setDragOver(false);
- },
- onDrop: (e: React.DragEvent) => {
- if (!hasFiles(e)) return;
- e.preventDefault();
- dragDepth.current = 0;
- setDragOver(false);
- addFiles(filesFrom(e.dataTransfer.files));
- textareaRef.current?.focus();
- },
- };
-
// `/idea …` goes in the idea jar, not to a bot (spec §2.3): the field dresses violet and blocks a send it can't take.
const ideaMode = isIdeaCommand(inputVal);
const ideaBlocked = ideaMode ? ideaBlockedLine(inputVal, IDEA_MAX, uploads.length > 0) : null;
@@ -1535,6 +1542,140 @@ export const ChatView: React.FC<ChatViewProps> = ({
teamName,
names: activeKwants.map((k) => k.name).concat(activeTeams.map((t) => t.name)),
});
+
+ // ---------- 0.8.0 drop files into the chat (design.md §2–§6) ----------
+ // Who gets the files: the same answer as the "Answers:" hint, so the two never disagree.
+ const mentioned = target.kind === 'mention' ? target.label.replace(/^@/, '') : '';
+ const mentionedBot = mentioned ? activeKwants.find((k) => k.name.toLowerCase() === mentioned.toLowerCase()) : undefined;
+ const asDropBot = (k: { id: string; name: string; avatar_sprite?: string }): DropBot => ({ id: k.id, name: k.name, avatar: k.avatar_sprite });
+ const roomBots: DropBot[] = (teamMembers?.length ? teamMembers : activeKwants).map(asDropBot);
+ // A team @mention shows that team's bots, like a room (#478 M4); never a made-up face for the team.
+ const mentionedTeamName = mentioned.replace(/ team$/i, '');
+ const mentionedTeam =
+ mentioned && !mentionedBot
+ ? activeTeams.find((t) => t.name.toLowerCase() === mentioned.toLowerCase() || t.name.toLowerCase() === mentionedTeamName.toLowerCase())
+ : undefined;
+ const mentionedTeamBots: DropBot[] = (mentionedTeam?.member_kwants ?? [])
+ .map((id) => activeKwants.find((k) => k.id === id))
+ .filter((k): k is (typeof activeKwants)[number] => !!k)
+ .map(asDropBot);
+ const dropTo: { recipient: DropRecipient; single: boolean; bots: DropBot[]; botId?: string } =
+ target.kind === 'mention'
+ ? mentionedBot
+ ? { recipient: { kind: 'bot', name: mentionedBot.name }, single: true, bots: [asDropBot(mentionedBot)], botId: mentionedBot.id }
+ : { recipient: { kind: 'team', name: mentionedTeam?.name ?? mentionedTeamName }, single: false, bots: mentionedTeamBots }
+ : home?.kind === 'bot'
+ ? {
+ recipient: { kind: 'bot', name: home.bot?.name ?? title },
+ single: true,
+ bots: [{ id: home.bot?.id, name: home.bot?.name ?? title, avatar: home.bot?.avatar_sprite }],
+ botId: home.bot?.id,
+ }
+ : home?.kind === 'general'
+ ? { recipient: { kind: 'general', name: 'General' }, single: false, bots: roomBots }
+ : home?.kind === 'team' || (target.kind === 'team' && teamName)
+ ? { recipient: { kind: 'team', name: teamName ?? title }, single: false, bots: roomBots }
+ : { recipient: { kind: 'channel', name: title }, single: false, bots: roomBots };
+ // A modal open when the drag came in keeps the layer away (the Import dialog has its own drop zone).
+ const modalUp = useMemo(() => winDrag.active && typeof document !== 'undefined' && modalOpen(document), [winDrag.active]);
+ const dragOn = winDrag.active && !modalUp;
+ const dropPreview = previewDrag(winDrag.items, uploads.length);
+ const card = dropCard({ preview: dropPreview, recipient: dropTo.recipient, ideaMode });
+ const livePhase: DropPhase | null = !dragOn ? null : overChat ? (card.state === 'refused' ? 'refused' : 'over') : 'armed';
+ useEffect(() => {
+ if (!winDrag.active) {
+ overDepth.current = 0;
+ overNow.current = false;
+ setOverChat(false);
+ }
+ }, [winDrag.active]);
+ // The layer runs its exit after the drag ends: the landing (160 ms) after a drop, else a fade (100 ms).
+ const lastCard = useRef(card);
+ if (livePhase) lastCard.current = card;
+ const landed = useRef(false);
+ const [exiting, setExiting] = useState<'landing' | 'leaving' | null>(null);
+ const wasLive = useRef(false);
+ useEffect(() => {
+ if (livePhase) {
+ // A new drag: a drop that landed after the last one ended must not play this one's exit as a landing.
+ if (!wasLive.current) landed.current = false;
+ wasLive.current = true;
+ setExiting(null);
+ return;
+ }
+ if (!wasLive.current) return;
+ wasLive.current = false;
+ const how = landed.current ? 'landing' : 'leaving';
+ landed.current = false;
+ setExiting(how);
+ const t = setTimeout(() => setExiting(null), how === 'landing' ? 160 : 100);
+ return () => clearTimeout(t);
+ }, [livePhase]);
+ // Spoken on state changes only, never on every dragover.
+ const announceLine = livePhase === 'over' || livePhase === 'refused' ? card.announce : '';
+ useEffect(() => {
+ if (announceLine) setDropAnnounce(announceLine);
+ }, [announceLine]);
+ // Card height room: the composer's height + 24 px; a side pane's width stays out of the layer.
+ const [layerBox, setLayerBox] = useState({ bottomPad: 120, rightGap: 0 });
+ useLayoutEffect(() => {
+ if (!dragOn) return;
+ const root = rootRef.current?.getBoundingClientRect();
+ const col = columnRef.current?.getBoundingClientRect();
+ const bottomPad = (composerWrapRef.current?.offsetHeight ?? 96) + 24;
+ const rightGap = root && col && col.width ? Math.max(0, Math.round(root.right - col.right)) : 0;
+ setLayerBox((b) => (b.bottomPad === bottomPad && b.rightGap === rightGap ? b : { bottomPad, rightGap }));
+ }, [dragOn, uploads.length, vmOpen]);
+ const inColumn = (t: EventTarget | null) => {
+ if (!(t instanceof Node)) return false;
+ if (t instanceof Element && t.closest('[data-drop-layer]')) return true;
+ return !!(headerRef.current?.contains(t) || columnRef.current?.contains(t));
+ };
+ const dropHandlers = {
+ onDragEnter: (e: React.DragEvent) => {
+ if (!dragHasFiles(e.dataTransfer)) return;
+ overDepth.current += 1;
+ markOver(inColumn(e.target));
+ },
+ onDragOver: (e: React.DragEvent) => {
+ if (!dragHasFiles(e.dataTransfer)) return;
+ e.preventDefault();
+ const inside = inColumn(e.target);
+ markOver(inside);
+ e.dataTransfer.dropEffect = inside && dragOn && card.state === 'over' ? 'copy' : 'none';
+ },
+ onDragLeave: (e: React.DragEvent) => {
+ if (!dragHasFiles(e.dataTransfer)) return;
+ overDepth.current = Math.max(0, overDepth.current - 1);
+ if (overDepth.current === 0) markOver(false);
+ },
+ onDrop: (e: React.DragEvent) => {
+ if (!dragHasFiles(e.dataTransfer)) return;
+ e.preventDefault();
+ overDepth.current = 0;
+ // Not flushed: the drop ends the drag anyway, and the exit must see `landed` first.
+ overNow.current = false;
+ setOverChat(false);
+ if (!inColumn(e.target) || modalUp) return;
+ // What the drop itself holds decides, the same way the card did (an ignored drop does nothing).
+ const items = e.dataTransfer.items as unknown as ArrayLike<DataTransferItem>;
+ const now = dropCard({ preview: previewDrag(items?.length ? items : winDrag.items, uploads.length), recipient: dropTo.recipient, ideaMode });
+ if (now.state === 'refused') return;
+ const dropped = splitDrop(items, e.dataTransfer.files);
+ const keys = addFiles(dropped.files, dropped.folders.length ? [FOLDER_NOTE] : []);
+ landed.current = true;
+ textareaRef.current?.focus();
+ playSfx('blip');
+ if (dropTo.single && dropTo.botId) moodNoticed(dropTo.botId);
+ setDropAnnounce(dropAnnouncement(keys.length, dropTo.recipient));
+ if (keys.length) {
+ setFreshChips((m) => ({ ...m, ...Object.fromEntries(keys.map((k, i) => [k, i])) }));
+ setTimeout(() => setFreshChips((m) => Object.fromEntries(Object.entries(m).filter(([k]) => !keys.includes(k)))), 800);
+ }
+ },
+ };
+ const layerPhase: DropPhase | null = livePhase ?? exiting;
+ const composerLit = livePhase === 'over';
const toolPhone = 'w-11 h-11 text-[#a39dcc] hover:text-zinc-100 hover:bg-white/[0.06] active:bg-white/[0.06] focus-visible:outline-[#b8adff]';
// Phone hint row (spec A2): no "@ mention · attach files" on touch, and "Answers:" only where it isn't
// obvious (channels and team chats, or a direct chat with an @mention typed).
@@ -1555,9 +1696,18 @@ export const ChatView: React.FC<ChatViewProps> = ({
};
return (
- <div className="flex-1 flex flex-col h-full bg-surface-main overflow-hidden" data-keyboard-mode={kbd ? 'on' : undefined}>
+ <div
+ ref={rootRef}
+ className="relative flex-1 flex flex-col h-full bg-surface-main overflow-hidden"
+ data-keyboard-mode={kbd ? 'on' : undefined}
+ data-drop-target="chat"
+ data-drop-active={livePhase && livePhase !== 'armed' ? 'true' : undefined}
+ data-drop-phase={layerPhase ?? undefined}
+ {...dropHandlers}
+ >
{/* Channel / bot header: 56 px on a phone, 48 px in keyboard mode (instant, no animation) */}
<div
+ ref={headerRef}
data-chat-header
className={`${kbd ? 'h-12' : 'h-14'} shrink-0 border-b border-hairline px-2 sm:px-6 gap-2 flex items-center justify-between bg-surface-main/80 backdrop-blur-md select-none`}
>
@@ -1741,7 +1891,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
{/* Main Split Layout: Messages/Input on Left + Virtual Machine Side Drawer on Right */}
<div className="flex-1 flex overflow-hidden min-h-0">
- <div className="flex-1 flex flex-col h-full overflow-hidden min-w-0">
+ <div ref={columnRef} className="flex-1 flex flex-col h-full overflow-hidden min-w-0">
{/* Messages Stream */}
<div
ref={scrollRef}
@@ -1945,6 +2095,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
{/* Modern Composer Input Bar */}
<div
+ ref={composerWrapRef}
className={`px-3 ${phone ? 'pt-2 pb-[max(0.5rem,env(safe-area-inset-bottom))]' : 'pt-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]'} sm:p-4 border-t border-hairline bg-surface-side/60`}
>
{teamMembers && teamMembers.length > 0 && (
@@ -2034,25 +2185,16 @@ export const ChatView: React.FC<ChatViewProps> = ({
<form
onSubmit={handleSubmit}
- {...dropHandlers}
aria-label={`Message ${title}`}
data-composer-form
data-stacked={phone ? String(stacked) : undefined}
className={`relative max-w-4xl mx-auto flex flex-wrap items-end ${stacked ? 'gap-x-1.5 gap-y-1' : 'gap-1.5'} border rounded-2xl p-2 transition-colors ${
phone ? 'bg-[#1a1538]' : 'bg-surface-raised shadow-raised'
- } ${
- dragOver
- ? 'border-sky-500/70 bg-sky-950/30'
- : phone
- ? 'border-white/10 focus-within:border-[#6c58e0]/70'
- : 'border-hairline-strong focus-within:border-sky-400/50'
- }`}
+ } ${phone ? 'border-white/10 focus-within:border-[#6c58e0]/70' : 'border-hairline-strong focus-within:border-sky-400/50'}${
+ layerPhase ? ' kw-dd-raised' : ''
+ }${composerLit ? ' kw-dd-lit' : ''}`}
+ data-drop-lit={composerLit ? 'true' : undefined}
>
- {dragOver && (
- <div className="absolute inset-0 z-10 rounded-2xl border-2 border-dashed border-sky-400/70 bg-zinc-950/80 flex items-center justify-center gap-2 text-sm font-medium text-sky-200 pointer-events-none">
- <Paperclip size={15} aria-hidden="true" /> Drop files to attach
- </div>
- )}
{replyTo && (
<ReplyChip
key={replyTo.id}
@@ -2067,7 +2209,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
{uploads.length > 0 && (
<ul className="flex flex-wrap gap-1.5 min-w-0" aria-label="Files to send">
{uploads.map((u) => (
- <UploadChip key={u.key} item={u} onRemove={() => removeUpload(u.key)} onRetry={() => retryUpload(u.key)} />
+ <UploadChip key={u.key} item={u} onRemove={() => removeUpload(u.key)} onRetry={() => retryUpload(u.key)} fresh={freshChips[u.key]} />
))}
</ul>
)}
@@ -2209,7 +2351,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
<AtSign size={phone ? 18 : 17} aria-hidden="true" />
{/* Phone (spec A5): "New" anchors to the @ button's own box, never on the field's border or an Ask chip */}
{phone && !isStreaming && (
- <NewTag id="mention" className={`absolute -top-1.5 -right-1 ${isMentionOpen ? 'hidden' : ''}`} />
+ <NewTag id="mention" className={`absolute -top-1.5 -right-1 ${isMentionOpen ? 'hidden' : ''} ${layerPhase ? 'hidden' : ''}`} />
)}
</button>
{stacked && <span className="flex-1" aria-hidden="true" />}
@@ -2217,11 +2359,12 @@ export const ChatView: React.FC<ChatViewProps> = ({
Only the send button follows "@" when it shows: 44px on phones / 36px from sm, plus a 6px gap;
11px is the form's border + padding. Hidden (not marked as seen) while a reply streams, so it
never sits on the working strip's edge and comes back after the turn; hidden while the mention
- picker is open, so it never peeks under it. */}
+ picker is open, so it never peeks under it; hidden (not marked as seen) while the drop layer is up,
+ so it never outshines the drop card (#478 Mira M3). */}
{!phone && !isStreaming && (
<NewTag
id="mention"
- className={`absolute bottom-full mb-1.5 [--kw-cbtn-step:50px] sm:[--kw-cbtn-step:42px] ${isMentionOpen ? 'hidden' : ''}`}
+ className={`absolute bottom-full mb-1.5 [--kw-cbtn-step:50px] sm:[--kw-cbtn-step:42px] ${isMentionOpen ? 'hidden' : ''} ${layerPhase ? 'hidden' : ''}`}
style={{ right: 'calc(11px + var(--kw-cbtn-step))' }}
/>
)}
@@ -2347,6 +2490,20 @@ export const ChatView: React.FC<ChatViewProps> = ({
showOnceBot={vmShowOnceBot}
/>
</div>
+ {layerPhase && (
+ <DropLayer
+ phase={layerPhase}
+ card={livePhase ? card : lastCard.current}
+ single={dropTo.single}
+ bots={dropTo.bots}
+ bottomPad={layerBox.bottomPad}
+ rightGap={layerBox.rightGap}
+ />
+ )}
+ {/* The drop card's words, and "3 files added for Frontend. Uploading." after a drop. */}
+ <div role="status" aria-live="polite" className="sr-only" data-drop-announce>
+ {dropAnnounce}
+ </div>
</div>
);
};
diff --git a/frontend/src/components/DropLayer.tsx b/frontend/src/components/DropLayer.tsx
new file mode 100644
index 00000000..a876c9c3
--- /dev/null
+++ b/frontend/src/components/DropLayer.tsx
@@ -0,0 +1,188 @@
+// 0.8.0 drop files into a chat (Mira's design, release-080/drag-drop/design.md §2). One layer over the
+// ChatView column: veil, a frame with pixel corners, and a card saying who gets the files and what
+// they are. DropPill is the one line shown over a page that isn't a chat. Both are aria-hidden: the
+// chat's own live region speaks for them.
+import React, { useEffect, useRef, useState, useSyncExternalStore } from 'react';
+import { AlertTriangle, Ban, File as FileIcon, FileText, Film, Image as ImageIcon, MessageSquare, Users } from 'lucide-react';
+import { ModernAvatar } from './ModernAvatar';
+import type { DropCardModel, Heading, KindPart } from '../dragPreview';
+import { PILL_TEXT, modalOpen, windowDragWatch } from '../dragPreview';
+
+export type DropPhase = 'armed' | 'over' | 'refused' | 'landing' | 'leaving';
+
+export interface DropBot {
+ id?: string;
+ name: string;
+ avatar?: string;
+}
+
+const Corner: React.FC<{ pos: 'tl' | 'tr' | 'bl' | 'br' }> = ({ pos }) => (
+ <svg className={`kw-dd-corner ${pos}`} width="18" height="18" viewBox="0 0 6 6" shapeRendering="crispEdges" aria-hidden="true">
+ <rect x="0" y="0" width="6" height="1" />
+ <rect x="0" y="0" width="1" height="6" />
+ <rect x="1" y="1" width="1" height="1" />
+ </svg>
+);
+
+const KindIcon: React.FC<{ kind: KindPart['kind'] }> = ({ kind }) => {
+ const Icon = kind === 'image' ? ImageIcon : kind === 'video' ? Film : kind === 'pdf' || kind === 'text' ? FileText : FileIcon;
+ return <Icon size={12} className="text-zinc-400" aria-hidden="true" />;
+};
+
+const HeadingLine: React.FC<{ h: Heading; refused: boolean }> = ({ h, refused }) => (
+ <h3 className="kw-dd-heading" data-drop-heading>
+ {h.pre}
+ {h.name && <em className={refused ? 'not-italic text-zinc-100' : 'not-italic text-sky-200'}>{h.name}</em>}
+ {h.post}
+ </h3>
+);
+
+export interface DropLayerProps {
+ phase: DropPhase;
+ card: DropCardModel;
+ /** One bot (a bot chat or an @mention) or a room's bots. */
+ single: boolean;
+ bots: DropBot[];
+ /** Room left under the card for the composer: its height + 24 px. */
+ bottomPad: number;
+ /** Space taken on the right by a side pane, which is not a target. */
+ rightGap?: number;
+ /** In B, C and D the layer takes the drop, so links and code below never get it. */
+ onDragOver?: React.DragEventHandler;
+ onDrop?: React.DragEventHandler;
+}
+
+export const DropLayer: React.FC<DropLayerProps> = ({ phase, card, single, bots, bottomPad, rightGap = 0, onDragOver, onDrop }) => {
+ const refused = phase === 'refused' || (card.state === 'refused' && phase !== 'armed');
+ const heading = phase === 'armed' ? card.armedHeading : card.heading;
+ const shown = bots.slice(0, 4);
+ const more = bots.length - shown.length;
+ const takesDrop = phase === 'over' || phase === 'refused';
+ return (
+ <div
+ className="kw-dd"
+ data-drop-layer
+ data-phase={phase}
+ data-refused={refused ? 'true' : undefined}
+ aria-hidden="true"
+ style={{ right: rightGap, pointerEvents: takesDrop ? 'auto' : 'none' }}
+ onDragOver={onDragOver}
+ onDrop={onDrop}
+ >
+ <div className="kw-dd-veil" />
+ <div className="kw-dd-frame">
+ <Corner pos="tl" />
+ <Corner pos="tr" />
+ <Corner pos="bl" />
+ <Corner pos="br" />
+ </div>
+ <div className="kw-dd-place" style={{ paddingBottom: bottomPad }}>
+ <div className="kw-dd-card" data-drop-card>
+ <div className="kw-dd-who">
+ {single ? (
+ <span className="kw-dd-one">
+ <ModernAvatar role={bots[0]?.avatar || bots[0]?.name || ''} name={bots[0]?.name || ''} size={64} kwantId={bots[0]?.id} className="rounded-2xl" />
+ </span>
+ ) : (
+ <span className="kw-dd-many">
+ {shown.map((b) => (
+ <ModernAvatar key={b.id ?? b.name} role={b.avatar || b.name} name={b.name} size={44} kwantId={b.id} className="rounded-full" />
+ ))}
+ {more > 0 && <span className="kw-dd-more">+{more}</span>}
+ {/* A team whose bots aren't loaded: a plain group circle, never a made-up bot face (#478 M4). */}
+ {!bots.length && (
+ <span className="kw-dd-more" data-drop-team-icon>
+ <Users size={18} className="text-zinc-300" aria-hidden="true" />
+ </span>
+ )}
+ </span>
+ )}
+ {card.count !== null && !refused && (
+ <span key={card.count} className="kw-dd-count" data-drop-count>
+ {card.count}
+ </span>
+ )}
+ </div>
+ <HeadingLine h={heading} refused={refused} />
+ {card.refusal ? (
+ <>
+ <p className="kw-dd-refuse" data-drop-refusal>
+ <Ban size={13} aria-hidden="true" className="shrink-0 mt-[2px]" />
+ <span>{card.refusal.line1}</span>
+ </p>
+ {card.refusal.line2 && <p className="kw-dd-refuse2">{card.refusal.line2}</p>}
+ </>
+ ) : (
+ <>
+ {card.what && (
+ <p className="kw-dd-what" data-drop-summary>
+ {card.count} {card.count === 1 ? 'file' : 'files'} ·{' '}
+ {card.kinds.map((k, i) => (
+ <React.Fragment key={k.kind}>
+ {i > 0 && ', '}
+ <span className="kw-dd-kind">
+ <KindIcon kind={k.kind} />
+ {k.label}
+ </span>
+ </React.Fragment>
+ ))}
+ </p>
+ )}
+ <p className="kw-dd-lim">Up to 20 MB each · videos 100 MB</p>
+ {card.wont.length > 0 && (
+ <div className="kw-dd-wont" data-drop-warning>
+ {card.wont.map((w) => (
+ <div key={w}>
+ <AlertTriangle size={13} aria-hidden="true" className="shrink-0 mt-[2px] text-amber-300" />
+ <span>{w}</span>
+ </div>
+ ))}
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+};
+
+/** State F: over a page with no chat. Bottom-centre of the main pane, 28 px up. */
+export const DropPill: React.FC<{ leaving?: boolean }> = ({ leaving }) => (
+ <div className="kw-dd-pill" data-drop-pill data-phase={leaving ? 'leaving' : 'shown'} aria-hidden="true">
+ <MessageSquare size={15} className="text-zinc-400" aria-hidden="true" />
+ {PILL_TEXT}
+ </div>
+);
+
+/**
+ * Shows DropPill while a file drag is over the window and no chat is open to take it (design §2 F),
+ * and says it once for screen readers. The window guard already makes such a drop do nothing.
+ */
+export const DropPillHost: React.FC = () => {
+ const watch = windowDragWatch();
+ const drag = useSyncExternalStore(watch.subscribe, watch.get, watch.get);
+ const want = drag.active && drag.chats === 0 && !(typeof document !== 'undefined' && modalOpen(document));
+ const [leaving, setLeaving] = useState(false);
+ const was = useRef(false);
+ useEffect(() => {
+ if (want) {
+ was.current = true;
+ setLeaving(false);
+ return;
+ }
+ if (!was.current) return;
+ was.current = false;
+ setLeaving(true);
+ const t = setTimeout(() => setLeaving(false), 100);
+ return () => clearTimeout(t);
+ }, [want]);
+ return (
+ <>
+ {(want || leaving) && <DropPill leaving={!want} />}
+ <span role="status" aria-live="polite" className="sr-only" data-drop-pill-announce>
+ {want ? PILL_TEXT + '.' : ''}
+ </span>
+ </>
+ );
+};
diff --git a/frontend/src/dragPreview.ts b/frontend/src/dragPreview.ts
new file mode 100644
index 00000000..a7564112
--- /dev/null
+++ b/frontend/src/dragPreview.ts
@@ -0,0 +1,476 @@
+// 0.8.0 drag and drop into chats (Mira's design, release-080/drag-drop/design.md). What a file drag
+// carries, read while it is still in the air; the words the drop card shows; what a drop brought; and
+// the window-level watch that knows a file drag is over the window at all.
+import { MAX_ATTACHMENTS, isArchiveMime, previewRefusesMime } from './attachments';
+
+/** One dragged item as the browser shows it before the drop: its kind and MIME type, never its name. */
+export interface DragItemLike {
+ kind: string;
+ type: string;
+}
+
+export type DragKind = 'image' | 'video' | 'pdf' | 'text' | 'file' | 'refused';
+
+const IMAGE = new Set(['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/webp']);
+const VIDEO = new Set(['video/mp4', 'video/quicktime', 'video/webm']);
+
+const mimeOf = (type: string) => (type || '').toLowerCase().split(';')[0].trim();
+
+/**
+ * The kind of a dragged file from its MIME alone (design §4). Anything that isn't surely refused and
+ * isn't a known image, video, PDF or text type is a plain "file": an empty type, a folder, a `.ts`
+ * file the browser calls `video/mp2t`, an SVG. The drop decides those by name.
+ */
+export function dragKind(type: string): DragKind {
+ const mime = mimeOf(type);
+ if (previewRefusesMime(mime)) return 'refused';
+ if (IMAGE.has(mime)) return 'image';
+ if (VIDEO.has(mime)) return 'video';
+ if (mime === 'application/pdf') return 'pdf';
+ if (mime.startsWith('text/') || mime === 'application/json') return 'text';
+ return 'file';
+}
+
+/** True when a drag carries files (as opposed to text or a link), from `dataTransfer.types`. */
+export function dragHasFiles(dt: { types?: ArrayLike<string> | readonly string[] | null } | null | undefined): boolean {
+ if (!dt?.types) return false;
+ return Array.from(dt.types as ArrayLike<string>).includes('Files');
+}
+
+export interface DragPreview {
+ /** Files in the drag; null when the browser shows none yet (some WebKit builds during dragover). */
+ count: number | null;
+ /** Files that will land, by kind (never 'refused'). */
+ kinds: Record<Exclude<DragKind, 'refused'>, number>;
+ /** Files that will land: what `addFiles` keeps (the first `slotsLeft`, less the refused among them). */
+ go: number;
+ /** Files that won't fit in the tray (and aren't refused anyway). */
+ overBy: number;
+ /** MIME types of the files that surely can't go. */
+ refused: string[];
+ /** Files already in the tray. */
+ inTray: number;
+ slotsLeft: number;
+}
+
+/** Copies what a drag shows into plain objects; `DataTransferItemList` can't be read later. */
+export const dragItemsOf = (items: ArrayLike<DragItemLike> | null | undefined): DragItemLike[] =>
+ Array.from(items ?? [])
+ .filter((i) => i?.kind === 'file')
+ .map((i) => ({ kind: 'file', type: i.type || '' }));
+
+/**
+ * What a file drag holds, during dragenter or dragover. Mirrors `addFiles`: it keeps the first
+ * `slotsLeft` files, and the refused ones among those still take a slot.
+ */
+export function previewDrag(items: ArrayLike<DragItemLike> | null | undefined, inTray = 0): DragPreview {
+ const list = dragItemsOf(items);
+ const slotsLeft = Math.max(0, MAX_ATTACHMENTS - inTray);
+ const kinds = { image: 0, video: 0, pdf: 0, text: 0, file: 0 };
+ const refused: string[] = [];
+ let go = 0;
+ let overBy = 0;
+ list.forEach((item, i) => {
+ const k = dragKind(item.type);
+ if (k === 'refused') refused.push(mimeOf(item.type));
+ else if (i >= slotsLeft) overBy += 1;
+ else {
+ go += 1;
+ kinds[k] += 1;
+ }
+ });
+ return { count: list.length || null, kinds, go, overBy, refused, inTray, slotsLeft };
+}
+
+const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
+const KIND_WORDS: Record<Exclude<DragKind, 'refused'>, [string, string]> = {
+ image: ['image', 'images'],
+ video: ['video', 'videos'],
+ pdf: ['PDF', 'PDFs'],
+ text: ['text file', 'text files'],
+ file: ['file', 'files'],
+};
+
+export interface KindPart {
+ kind: Exclude<DragKind, 'refused'> | 'other';
+ label: string;
+}
+
+/** The kinds for the what line: at most 3, biggest first; the rest fold into "{n} other". */
+export function kindParts(p: DragPreview): KindPart[] {
+ const order: Array<Exclude<DragKind, 'refused'>> = ['image', 'video', 'pdf', 'text', 'file'];
+ const groups = order.filter((k) => p.kinds[k] > 0).sort((a, b) => p.kinds[b] - p.kinds[a]);
+ const shown = groups.slice(0, 3).map((k) => ({ kind: k, label: plural(p.kinds[k], ...KIND_WORDS[k]) }));
+ const rest = groups.slice(3).reduce((n, k) => n + p.kinds[k], 0);
+ return rest ? [...shown, { kind: 'other', label: `${rest} other` }] : shown;
+}
+
+/** "3 files · 2 images, 1 PDF" (the what line as plain text). */
+export function whatLine(p: DragPreview): string | null {
+ if (p.count === null || !p.go) return null;
+ return `${plural(p.go, 'file')} · ${kindParts(p)
+ .map((k) => k.label)
+ .join(', ')}`;
+}
+
+/** Who the files go to: from `answerTarget()`, so the card and the "Answers:" hint never disagree. */
+export interface DropRecipient {
+ /** bot: a bot's own chat or an @mention. general/team/channel: a room. */
+ kind: 'bot' | 'general' | 'team' | 'channel';
+ /** "Frontend", "General", "Kitchen" (team name without "team"), "#launch". */
+ name: string;
+}
+
+/** The heading in three parts, so the name can be drawn in the accent. */
+export interface Heading {
+ pre: string;
+ name: string;
+ post: string;
+}
+
+export const headingText = (h: Heading) => `${h.pre}${h.name}${h.post}`;
+
+/** "Drop to give Frontend these files" (B, C) or "Drop here to give…" (A). */
+export function dropHeading(r: DropRecipient, count: number | null, armed = false): Heading {
+ const here = armed ? 'Drop here to ' : 'Drop to ';
+ if (r.kind === 'bot') return { pre: `${here}give `, name: r.name, post: count === null ? ' your files' : count === 1 ? ' this file' : ' these files' };
+ if (r.kind === 'general') return { pre: `${here}share in `, name: r.name, post: '' };
+ if (r.kind === 'team') return { pre: `${here}share with the `, name: r.name, post: ' team' };
+ return { pre: `${here}share with `, name: r.name, post: '' };
+}
+
+/** The recipient inside a sentence: "Frontend", "General", "the Kitchen team". */
+const nameIn = (r: DropRecipient) => (r.kind === 'team' ? `the ${r.name} team` : r.name);
+
+const WORKS = 'Images, videos, PDFs and text or code files work.';
+
+/** How a refused MIME is named when all refused files share it. */
+function refusedWords(mime: string): { one: string; many: string; group: string } | null {
+ if (mime === 'application/zip' || mime === 'application/x-zip-compressed') return { one: 'ZIP', many: 'ZIPs', group: 'ZIP files' };
+ if (isArchiveMime(mime)) return { one: 'archive', many: 'archives', group: 'Archives' };
+ if (mime.startsWith('audio/')) return { one: 'audio file', many: 'audio files', group: 'Audio files' };
+ if (mime.startsWith('font/')) return { one: 'font', many: 'fonts', group: 'Fonts' };
+ if (mime === 'application/msword' || /^application\/vnd\.(ms-|openxmlformats-officedocument\.|oasis\.opendocument\.)/.test(mime))
+ return { one: 'Office file', many: 'Office files', group: 'Office files' };
+ return null;
+}
+
+/** The kind's words when every refused file has the same one, else null. */
+function sameRefused(mimes: string[]) {
+ const words = mimes.map(refusedWords);
+ const first = words[0];
+ return first && words.every((w) => w?.one === first.one) ? first : null;
+}
+
+export interface Refusal {
+ heading: Heading;
+ line1: string;
+ line2?: string;
+}
+
+export interface DropCardModel {
+ /** over: at least one file will go (B, C). refused: nothing will (D). */
+ state: 'over' | 'refused';
+ heading: Heading;
+ armedHeading: Heading;
+ /** Files that will go, for the badge; null hides it. */
+ count: number | null;
+ kinds: KindPart[];
+ what: string | null;
+ /** The won't-go rows (C), at most 2. */
+ wont: string[];
+ refusal: Refusal | null;
+ /** What a screen reader hears when this state starts. */
+ announce: string;
+}
+
+export interface DropCardInput {
+ preview: DragPreview;
+ recipient: DropRecipient;
+ /** The field holds `/idea …`: files can't go in the jar. */
+ ideaMode?: boolean;
+ /** The composer can't take files right now; its own reason. */
+ disabledReason?: string | null;
+}
+
+/** Everything the drop card says, for one drag over one chat (design §2 B–D, §5). */
+export function dropCard({ preview: p, recipient: r, ideaMode, disabledReason }: DropCardInput): DropCardModel {
+ const refusal = refusalOf(p, r, ideaMode, disabledReason);
+ if (refusal) {
+ return {
+ state: 'refused',
+ heading: refusal.heading,
+ armedHeading: refusal.heading,
+ count: null,
+ kinds: [],
+ what: null,
+ wont: [],
+ refusal,
+ announce: `${headingText(refusal.heading)}. ${refusal.line1}`,
+ };
+ }
+ const count = p.count === null ? null : p.go;
+ const wont: string[] = [];
+ if (p.overBy) {
+ const already = p.inTray ? `, ${p.inTray} ${p.inTray === 1 ? 'is' : 'are'} already in` : '';
+ wont.push(`${p.overBy} more won't fit: ${MAX_ATTACHMENTS} files per message${already}.`);
+ }
+ if (p.refused.length) {
+ const same = sameRefused(p.refused);
+ const what = same ? (p.refused.length === 1 ? same.one : same.many) : p.refused.length === 1 ? 'file' : 'files';
+ wont.push(`${p.refused.length} ${what} can't go. ${WORKS}`);
+ }
+ const kinds = count === null ? [] : kindParts(p);
+ const what = whatLine(p);
+ const heading = dropHeading(r, count);
+ let announce: string;
+ if (count === null) announce = `${headingText(heading)}.`;
+ else {
+ const files = plural(count, 'file');
+ const lead = r.kind === 'bot' ? `Drop to give ${r.name} ${files}` : `Drop to share ${files} ${r.kind === 'general' ? 'in' : 'with'} ${nameIn(r)}`;
+ announce = `${lead}: ${kinds.map((k) => k.label).join(', ')}.`;
+ }
+ const short: string[] = [];
+ if (p.overBy) short.push(`${p.overBy} more won't fit.`);
+ if (p.refused.length) {
+ const same = sameRefused(p.refused);
+ short.push(`${p.refused.length} ${same ? (p.refused.length === 1 ? same.one : same.many) : p.refused.length === 1 ? 'file' : 'files'} can't go.`);
+ }
+ if (short.length) announce += ` ${short.join(' ')}`;
+ return { state: 'over', heading, armedHeading: dropHeading(r, count, true), count, kinds, what, wont: wont.slice(0, 2), refusal: null, announce };
+}
+
+/** Why nothing in this drag can go, in the design's order (§2 D), or null when something will. */
+function refusalOf(p: DragPreview, r: DropRecipient, ideaMode?: boolean, disabledReason?: string | null): Refusal | null {
+ const who = nameIn(r);
+ if (ideaMode)
+ return { heading: { pre: "Files can't go in the idea jar", name: '', post: '' }, line1: 'Ideas are text only.', line2: `Clear /idea from the field to send them to ${who}.` };
+ if (disabledReason) return { heading: { pre: "Can't drop files here right now", name: '', post: '' }, line1: disabledReason };
+ if (p.slotsLeft === 0) return { heading: { pre: 'The tray is full', name: '', post: '' }, line1: `${MAX_ATTACHMENTS} files per message.`, line2: 'Send these first, then drop the rest.' };
+ if (p.count !== null && p.go === 0 && p.overBy === 0 && p.refused.length) {
+ const n = p.refused.length;
+ const same = sameRefused(p.refused);
+ const archives = p.refused.every(isArchiveMime);
+ return {
+ heading: { pre: n === 1 ? "This can't go to " : "These can't go to ", name: who, post: '' },
+ line1: same ? `${same.group} can't be attached.` : n === 1 ? "This file can't be attached." : "These files can't be attached.",
+ line2: archives ? `${WORKS} ${n === 1 ? 'Unzip it' : 'Unzip them'} and drop the files inside.` : WORKS,
+ };
+ }
+ return null;
+}
+
+/** One dropped item: a `DataTransferItem` whose entry tells a folder from a file. */
+interface DropItemLike extends DragItemLike {
+ getAsFile(): File | null;
+ webkitGetAsEntry?: () => { isDirectory: boolean; name: string } | null;
+}
+
+export interface DroppedFiles {
+ files: File[];
+ /** Names of folders in the drop; kwant takes files only. */
+ folders: string[];
+}
+
+/**
+ * Splits a drop into files and folders. Call it inside the drop event: the items are empty after.
+ * Without items (or without `webkitGetAsEntry`) every entry of `files` counts as a file.
+ */
+export function splitDrop(items: ArrayLike<DropItemLike> | null | undefined, files?: ArrayLike<File> | null): DroppedFiles {
+ const list = Array.from(items ?? []).filter((i) => i?.kind === 'file');
+ if (!list.length) return { files: Array.from(files ?? []), folders: [] };
+ const out: DroppedFiles = { files: [], folders: [] };
+ for (const item of list) {
+ const entry = item.webkitGetAsEntry?.() ?? null;
+ if (entry?.isDirectory) {
+ out.folders.push(entry.name);
+ continue;
+ }
+ const f = item.getAsFile();
+ if (f) out.files.push(f);
+ }
+ return out;
+}
+
+/** The note shown (and read out) when a drop held folders (design §2 E5). */
+export const FOLDER_NOTE = "Folders can't go: drop the files inside.";
+
+/** What a screen reader hears after a drop: "3 files added for Frontend. Uploading." */
+export function dropAnnouncement(added: number, r?: DropRecipient): string {
+ if (!added) return 'No files added.';
+ return `${plural(added, 'file')} added${r ? ` for ${nameIn(r)}` : ''}. Uploading.`;
+}
+
+export const PILL_TEXT = 'Open a chat to drop files there';
+
+/** A drag or drop event as the window guard sees it. */
+interface GuardEvent {
+ type: string;
+ defaultPrevented: boolean;
+ preventDefault(): void;
+ dataTransfer: { types?: ArrayLike<string> | null; dropEffect?: string } | null;
+}
+
+/**
+ * The window-level guard: a file drag that no drop target took (nobody called preventDefault) must
+ * not open the file in place of kwant. Shows the "no drop" cursor and swallows the drop. Text, links
+ * and drags a target already handled pass untouched. Returns true when it stepped in.
+ */
+export function guardFileDrag(e: GuardEvent): boolean {
+ if (e.defaultPrevented || !dragHasFiles(e.dataTransfer)) return false;
+ e.preventDefault();
+ if (e.type === 'dragover' && e.dataTransfer) e.dataTransfer.dropEffect = 'none';
+ return true;
+}
+
+/** Puts the guard on a window (bubble phase, so drop targets act first). Returns the cleanup. */
+export function installFileDropGuard(win: Pick<Window, 'addEventListener' | 'removeEventListener'>): () => void {
+ const on = (e: Event) => void guardFileDrag(e as unknown as GuardEvent);
+ win.addEventListener('dragover', on);
+ win.addEventListener('drop', on);
+ return () => {
+ win.removeEventListener('dragover', on);
+ win.removeEventListener('drop', on);
+ };
+}
+
+// ---------- the window watch: is a file drag over the window? ----------
+
+export interface WindowDrag {
+ /** A file drag is over the window. */
+ active: boolean;
+ /** What it carries, as last seen (empty when the browser showed nothing). */
+ items: DragItemLike[];
+ /** How many open chats can take a drop right now (ChatView registers); 0 shows the pill. */
+ chats: number;
+}
+
+type Win = Pick<Window, 'addEventListener' | 'removeEventListener' | 'setTimeout' | 'clearTimeout'>;
+
+/**
+ * Watches a window for file drags (design §6.1–6.2, Ada's #478 M2). It ends the drag when:
+ * - the enter/leave depth counter falls to 0;
+ * - a dragleave has no relatedTarget (the pointer left the window), unless a dragenter came in the
+ * same task (WebKit gives no relatedTarget when crossing from one element to the next, and fires
+ * the new element's dragenter just before the old one's dragleave);
+ * - the first mousemove or pointermove arrives: mouse events don't fire during an OS drag, so one
+ * arriving means the drag is over (this catches a dragleave WebKit missed on a fast exit);
+ * - Esc, dragend or drop;
+ * - and, as a last fallback, no dragover for `watchdogMs` (1500 ms). WebKit, the Mac app's
+ * WKWebView included, sends dragover mostly when the pointer moves, so a hand held still must
+ * not end it; a shorter watchdog made the layer vanish and blink back.
+ * A dragover after the drag ended starts it again.
+ */
+export function createDragWatch(win: Win, watchdogMs = 1500) {
+ let state: WindowDrag = { active: false, items: [], chats: 0 };
+ let depth = 0;
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ // A dragenter came in this task: a null-relatedTarget dragleave right after it is a crossing, not an exit.
+ let justEntered = false;
+ const subs = new Set<() => void>();
+ const set = (next: Partial<WindowDrag>) => {
+ state = { ...state, ...next };
+ subs.forEach((f) => f());
+ };
+ const arm = () => {
+ if (timer) win.clearTimeout(timer);
+ timer = win.setTimeout(end, watchdogMs);
+ };
+ function end() {
+ depth = 0;
+ if (timer) win.clearTimeout(timer);
+ timer = null;
+ if (state.active) set({ active: false, items: [] });
+ }
+ const take = (e: DragEvent) => {
+ const items = dragItemsOf(e.dataTransfer?.items as unknown as ArrayLike<DragItemLike>);
+ if (!state.active) set({ active: true, items });
+ else if (items.length && items.length !== state.items.length) set({ items });
+ };
+ const onEnter = (e: Event) => {
+ const d = e as DragEvent;
+ if (!dragHasFiles(d.dataTransfer)) return;
+ depth += 1;
+ justEntered = true;
+ win.setTimeout(() => {
+ justEntered = false;
+ }, 0);
+ take(d);
+ arm();
+ };
+ const onOver = (e: Event) => {
+ const d = e as DragEvent;
+ if (!dragHasFiles(d.dataTransfer)) return;
+ if (!state.active) depth = Math.max(depth, 1);
+ take(d);
+ arm();
+ };
+ const onLeave = (e: Event) => {
+ const d = e as DragEvent;
+ if (!dragHasFiles(d.dataTransfer)) return;
+ depth = Math.max(0, depth - 1);
+ if (depth === 0 || (d.relatedTarget == null && !justEntered)) end();
+ };
+ // No mouse events during an OS drag: one arriving means the drag is over.
+ const onMove = () => {
+ if (state.active) end();
+ };
+ const onKey = (e: Event) => {
+ if ((e as KeyboardEvent).key === 'Escape' && state.active) end();
+ };
+ const listen: Array<[string, (e: Event) => void]> = [
+ ['dragenter', onEnter],
+ ['dragover', onOver],
+ ['dragleave', onLeave],
+ ['drop', end],
+ ['dragend', end],
+ ['keydown', onKey],
+ ['mousemove', onMove],
+ ['pointermove', onMove],
+ ];
+ let installed = false;
+ const install = () => {
+ if (installed) return;
+ installed = true;
+ listen.forEach(([t, f]) => win.addEventListener(t, f, true));
+ };
+ const uninstall = () => {
+ if (!installed) return;
+ installed = false;
+ listen.forEach(([t, f]) => win.removeEventListener(t, f, true));
+ end();
+ };
+ return {
+ get: () => state,
+ /** Subscribes; the first subscriber puts the listeners on the window, the last takes them off. */
+ subscribe(f: () => void) {
+ subs.add(f);
+ install();
+ return () => {
+ subs.delete(f);
+ if (!subs.size) uninstall();
+ };
+ },
+ /** An open chat that takes drops; returns the cleanup. */
+ registerChat() {
+ set({ chats: state.chats + 1 });
+ return () => set({ chats: Math.max(0, state.chats - 1) });
+ },
+ end,
+ };
+}
+
+export type DragWatch = ReturnType<typeof createDragWatch>;
+
+let shared: DragWatch | null = null;
+/** The one watch on this window, made on first use. */
+export const windowDragWatch = (): DragWatch =>
+ (shared ??= createDragWatch(
+ typeof window !== 'undefined'
+ ? window
+ : // Rendered to a string (tests, no window): nothing to watch.
+ { addEventListener() {}, removeEventListener() {}, setTimeout: (f: () => void, ms?: number) => setTimeout(f, ms) as unknown as number, clearTimeout: (t?: number) => clearTimeout(t) },
+ ));
+
+/** True when a modal dialog is open: the chat's drop layer never shows over one (design §1). */
+export const modalOpen = (doc: Document = document) => !!doc.querySelector('[aria-modal="true"], [role="alertdialog"], dialog[open]');
diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx
index 3db6cfdb..15986622 100644
--- a/frontend/src/main.tsx
+++ b/frontend/src/main.tsx
@@ -3,6 +3,7 @@ import ReactDOM from 'react-dom/client';
import { App } from './Shell';
import { SandboxViewer } from './components/SandboxViewer';
import { AuthGate } from './components/AuthGate';
+import { installFileDropGuard } from './dragPreview';
import { captureInstallPrompt, registerServiceWorker, trackAppHeight } from './pwa';
import './styles/fonts.css';
import './styles/modern.css';
@@ -15,10 +16,13 @@ import './styles/tickets.css';
import './styles/telegram.css';
import './styles/showOnce.css';
import './styles/gettingStarted.css';
+import './styles/dropLayer.css';
registerServiceWorker();
captureInstallPrompt();
trackAppHeight();
+// A file dropped outside a chat never opens in place of kwant (browser, Mac and Windows apps).
+installFileDropGuard(window);
const sandboxMatch = window.location.pathname.match(/^\/sandbox\/([^/]+)\/?$/);
diff --git a/frontend/src/styles/dropLayer.css b/frontend/src/styles/dropLayer.css
new file mode 100644
index 00000000..f218645b
--- /dev/null
+++ b/frontend/src/styles/dropLayer.css
@@ -0,0 +1,131 @@
+/* 0.8.0 drop files into a chat (Mira, release-080/drag-drop/design.md). Transform and opacity only;
+ reduced motion keeps every state's look and changes only opacity, in 120 ms. */
+.kw-dd {
+ position: absolute;
+ top: 0;
+ left: 0;
+ bottom: 0;
+ z-index: 30;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ animation: kw-dd-in 120ms var(--kw-ease) both;
+}
+.kw-dd-veil { position: absolute; inset: 0; background: rgb(18 14 38 / 0.8); transition: background-color 160ms var(--kw-ease), opacity 140ms cubic-bezier(0.4, 0, 1, 1); }
+.kw-dd-frame {
+ position: absolute;
+ inset: 10px;
+ border-radius: 18px;
+ box-shadow: inset 0 0 0 1.5px rgb(157 143 255 / 0.55), inset 0 0 56px rgb(130 112 245 / 0.16);
+ transition: box-shadow 160ms var(--kw-ease), opacity 140ms cubic-bezier(0.4, 0, 1, 1);
+}
+.kw-dd-corner { position: absolute; fill: #b8adff; transition: fill 160ms var(--kw-ease); }
+.kw-dd-corner.tl { top: 4px; left: 4px; }
+.kw-dd-corner.tr { top: 4px; right: 4px; transform: scaleX(-1); }
+.kw-dd-corner.bl { bottom: 4px; left: 4px; transform: scaleY(-1); }
+.kw-dd-corner.br { bottom: 4px; right: 4px; transform: scale(-1, -1); }
+.kw-dd-place { position: relative; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; box-sizing: border-box; }
+.kw-dd-card {
+ position: relative;
+ width: min(380px, calc(100% - 48px));
+ padding: 24px 28px 20px;
+ border-radius: 20px;
+ background: #231b4d;
+ border: 1px solid rgb(157 143 255 / 0.35);
+ box-shadow: 0 24px 64px rgb(0 0 0 / 0.55), 0 0 0 6px rgb(130 112 245 / 0.08);
+ text-align: center;
+ transition: transform 160ms var(--kw-ease), opacity 160ms var(--kw-ease), border-color 160ms var(--kw-ease);
+}
+@media (max-width: 767px) { .kw-dd-card { width: calc(100% - 32px); } }
+.kw-dd-who { position: relative; display: inline-flex; justify-content: center; margin-bottom: 14px; }
+.kw-dd-one { display: inline-flex; border-radius: 16px; box-shadow: 0 0 0 2px #231b4d, 0 0 0 4px rgb(157 143 255 / 0.8), 0 0 22px 4px rgb(130 112 245 / 0.35); transition: box-shadow 160ms var(--kw-ease), opacity 160ms; }
+.kw-dd-many { display: flex; }
+.kw-dd-many > * { margin-left: -10px; border-radius: 999px; box-shadow: 0 0 0 3px #231b4d; }
+.kw-dd-many > *:first-child { margin-left: 0; }
+.kw-dd-more { width: 44px; height: 44px; border-radius: 999px; background: #2c2552; color: #e2dff5; font-size: 12px; font-weight: 600; display: inline-flex; align-items: center; justify-content: center; }
+.kw-dd-count {
+ position: absolute; right: -10px; bottom: -6px; min-width: 26px; height: 26px; padding: 0 7px; border-radius: 999px;
+ background: #6c58e0; color: #fff; font-size: 12px; font-weight: 700; display: inline-flex; align-items: center; justify-content: center;
+ box-shadow: 0 0 0 3px #231b4d; font-variant-numeric: tabular-nums; animation: kw-dd-badge 120ms var(--kw-ease) both;
+}
+.kw-dd-heading { font-size: 18px; line-height: 24px; font-weight: 600; color: #f5f4fb; letter-spacing: -0.01em; text-wrap: balance; }
+.kw-dd-what { margin-top: 6px; font-size: 13px; line-height: 18px; color: #c9c5e6; font-variant-numeric: tabular-nums; }
+.kw-dd-kind { display: inline-flex; align-items: center; gap: 4px; color: #e2dff5; }
+.kw-dd-lim { margin-top: 4px; font-size: 11px; line-height: 16px; color: #8d87b8; }
+.kw-dd-wont { margin-top: 14px; text-align: left; border-radius: 10px; border: 1px solid rgb(252 211 77 / 0.28); background: rgb(252 211 77 / 0.08); padding: 8px 10px; display: flex; flex-direction: column; gap: 4px; }
+.kw-dd-wont > div { display: flex; gap: 8px; font-size: 12px; line-height: 17px; color: #fde68a; }
+.kw-dd-refuse { margin-top: 8px; display: inline-flex; gap: 6px; font-size: 13px; line-height: 18px; color: #fda4af; text-align: left; }
+.kw-dd-refuse2 { margin-top: 4px; font-size: 12px; line-height: 17px; color: #a39dcc; }
+
+/* A. armed: files are in the window, the pointer isn't over the chat */
+.kw-dd[data-phase='armed'] .kw-dd-veil { background: rgb(18 14 38 / 0.55); }
+.kw-dd[data-phase='armed'] .kw-dd-frame { box-shadow: inset 0 0 0 1.5px rgb(157 143 255 / 0.3); transition-duration: 120ms; }
+.kw-dd[data-phase='armed'] .kw-dd-corner { fill: #6c58e0; }
+.kw-dd[data-phase='armed'] .kw-dd-card { transform: scale(0.96); opacity: 0.82; border-color: rgb(157 143 255 / 0.2); box-shadow: 0 24px 64px rgb(0 0 0 / 0.45); transition-duration: 120ms; }
+.kw-dd[data-phase='armed'] .kw-dd-one { box-shadow: 0 0 0 2px #231b4d, 0 0 0 4px rgb(157 143 255 / 0.35); }
+.kw-dd[data-phase='armed'] .kw-dd-count { animation: none; }
+/* A -> B: the avatar hops and the badge pops */
+.kw-dd[data-phase='over'] .kw-dd-who { animation: kw-dd-hop 160ms var(--kw-ease); }
+.kw-dd[data-phase='over'] .kw-dd-count { animation: kw-dd-pop 160ms var(--kw-ease) both; }
+
+/* D. nothing will go: neutral, never violet */
+.kw-dd[data-refused='true'] .kw-dd-frame { box-shadow: inset 0 0 0 1.5px rgb(141 135 184 / 0.35); }
+.kw-dd[data-refused='true'] .kw-dd-corner { fill: #5a5383; }
+.kw-dd[data-refused='true'] .kw-dd-card { border-color: #3f3868; box-shadow: 0 24px 64px rgb(0 0 0 / 0.55); }
+.kw-dd[data-refused='true'] .kw-dd-one { box-shadow: 0 0 0 2px #231b4d, 0 0 0 4px #3f3868; opacity: 0.6; }
+.kw-dd[data-refused='true'] .kw-dd-heading { color: #ecebf7; }
+
+/* E. landing: the layer fades and the card drops toward the tray */
+.kw-dd[data-phase='landing'] { pointer-events: none; }
+.kw-dd[data-phase='landing'] .kw-dd-veil,
+.kw-dd[data-phase='landing'] .kw-dd-frame { opacity: 0; }
+.kw-dd[data-phase='landing'] .kw-dd-card { transform: translateY(64px) scale(0.6); opacity: 0; transition: transform 160ms cubic-bezier(0.4, 0, 1, 1), opacity 160ms cubic-bezier(0.4, 0, 1, 1); }
+/* leaves the window, Esc or watchdog */
+.kw-dd[data-phase='leaving'] { opacity: 0; pointer-events: none; transition: opacity 100ms cubic-bezier(0.4, 0, 1, 1); }
+
+/* the composer is the landing spot: above the veil, lit while a drop will go */
+.kw-dd-raised { z-index: 40; }
+.kw-dd-lit { border-color: #9d8fff !important; box-shadow: 0 0 0 4px rgb(130 112 245 / 0.22), 0 0 24px 2px rgb(130 112 245 / 0.25) !important; transition: box-shadow 160ms var(--kw-ease), border-color 160ms var(--kw-ease); }
+
+/* new tray chips: drop in, staggered, with a tint that fades from 600 to 800 ms */
+.kw-chip-new { animation: kw-chip-in 160ms var(--kw-ease) both; animation-delay: var(--kw-chip-delay, 40ms); }
+.kw-chip-new::after {
+ content: '';
+ position: absolute;
+ inset: 0;
+ border-radius: inherit;
+ box-shadow: inset 0 0 0 1px rgb(157 143 255 / 0.55);
+ background: rgb(130 112 245 / 0.14);
+ pointer-events: none;
+ animation: kw-chip-tint 800ms linear both;
+}
+
+/* F. over a page that isn't a chat */
+.kw-dd-pill {
+ position: absolute; left: 50%; bottom: 28px; transform: translateX(-50%); z-index: 50;
+ display: inline-flex; align-items: center; gap: 8px; padding: 10px 16px; border-radius: 999px;
+ background: #231b4d; border: 1px solid rgb(255 255 255 / 0.14); box-shadow: 0 12px 32px rgb(0 0 0 / 0.5);
+ font-size: 13px; line-height: 18px; color: #f5f4fb; white-space: nowrap; pointer-events: none;
+ animation: kw-dd-in 120ms var(--kw-ease) both;
+}
+.kw-dd-pill[data-phase='leaving'] { opacity: 0; transition: opacity 100ms linear; }
+
+@keyframes kw-dd-in { from { opacity: 0; } to { opacity: 1; } }
+@keyframes kw-dd-hop { 0% { transform: translateY(0); } 50% { transform: translateY(-3px); } 100% { transform: translateY(0); } }
+@keyframes kw-dd-pop { from { transform: scale(0.6); } to { transform: scale(1); } }
+@keyframes kw-dd-badge { from { transform: scale(0.85); } to { transform: scale(1); } }
+@keyframes kw-chip-in { from { opacity: 0; transform: translateY(-10px) scale(0.92); } to { opacity: 1; transform: none; } }
+@keyframes kw-chip-tint { 0%, 75% { opacity: 1; } 100% { opacity: 0; } }
+@keyframes kw-chip-tint-flat { 0%, 99.9% { opacity: 1; } 100% { opacity: 0; } }
+@keyframes kw-chip-fade { from { opacity: 0; } to { opacity: 1; } }
+
+@media (prefers-reduced-motion: reduce) {
+ .kw-dd, .kw-dd-pill { animation: kw-dd-in 120ms linear both; }
+ .kw-dd *, .kw-dd-pill { transition-property: opacity, background-color, border-color, box-shadow, fill !important; transition-duration: 120ms !important; transition-timing-function: linear !important; }
+ .kw-dd[data-phase] .kw-dd-who, .kw-dd[data-phase] .kw-dd-count { animation: none; }
+ .kw-dd[data-phase='landing'] .kw-dd-card { transform: none; }
+ .kw-dd[data-phase='leaving'], .kw-dd[data-phase='landing'] { transition: opacity 120ms linear; }
+ .kw-dd[data-phase='landing'] { opacity: 0; }
+ .kw-chip-new { animation: kw-chip-fade 120ms linear both; animation-delay: 0ms; }
+ .kw-chip-new::after { animation: kw-chip-tint-flat 600ms linear both; }
+}
diff --git a/frontend/tests/dragDropPane.test.mjs b/frontend/tests/dragDropPane.test.mjs
new file mode 100644
index 00000000..02cfcd22
--- /dev/null
+++ b/frontend/tests/dragDropPane.test.mjs
@@ -0,0 +1,497 @@
+// 0.8.0 drag and drop into chats (Pixel, Mira's design release-080/drag-drop/design.md): the whole open
+// chat takes a file drop (header, message list and composer), with a card saying who gets the files
+// and what is coming; after the drop the files sit in the same tray and the cursor is in the field.
+// Paste, the paperclip and the 10-file limit are unchanged. The pane cases fail on main fd3dfafa,
+// where only the <form> listens and there is no drop layer.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLButtonElement', 'HTMLInputElement', 'HTMLTextAreaElement', 'Element', 'Node', 'Event', 'KeyboardEvent', 'FocusEvent', 'MutationObserver', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'CSS', 'DOMException']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(globalThis, k, { value: dom.window[k], configurable: true, writable: true });
+}
+const store = new Map();
+const ls = { getItem: (k) => (store.has(k) ? store.get(k) : null), setItem: (k, v) => void store.set(k, String(v)), removeItem: (k) => void store.delete(k) };
+Object.defineProperty(globalThis, 'localStorage', { value: ls, configurable: true, writable: true });
+Object.defineProperty(dom.window, 'localStorage', { value: ls, configurable: true });
+dom.window.matchMedia = (q) => ({ matches: false, media: q, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} });
+globalThis.matchMedia = dom.window.matchMedia;
+globalThis.ResizeObserver ??= class { observe() {} unobserve() {} disconnect() {} };
+globalThis.IntersectionObserver ??= class { observe() {} unobserve() {} disconnect() {} };
+dom.window.HTMLElement.prototype.scrollIntoView ??= function () {};
+dom.window.HTMLElement.prototype.scrollTo ??= function () {};
+// Uploads start right away; these never finish, so the chips stay "uploading".
+const sent = [];
+globalThis.XMLHttpRequest = class {
+ upload = {};
+ open(_m, url) { this.url = url; }
+ send(body) { sent.push({ url: this.url, body }); }
+ abort() {}
+};
+
+const ui = await loadBundled(`
+ import React from 'react';
+ import { flushSync } from 'react-dom';
+ import { createRoot } from 'react-dom/client';
+ import { ChatView } from './src/components/ChatView';
+ import { DropPillHost } from './src/components/DropLayer';
+ export const mount = (p) => {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = createRoot(host);
+ flushSync(() => root.render(React.createElement(ChatView, p)));
+ return { host, unmount: () => { root.unmount(); host.remove(); } };
+ };
+ export const mountPill = () => {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = createRoot(host);
+ flushSync(() => root.render(React.createElement(DropPillHost)));
+ return { host, unmount: () => { root.unmount(); host.remove(); } };
+ };
+ export const act = (fn) => flushSync(fn);
+`);
+
+const props = (extra = {}) => ({
+ title: 'Frontend', subtitle: 'Pixel', messages: [], streamingText: '', streamingThinking: '', isStreaming: false,
+ pendingApprovals: [], onSendMessage: () => {}, onResolveApproval: () => {}, onCancelDiscussion: () => {}, kwants: [], teams: [],
+ home: { kind: 'bot', bot: { id: 'k-front', name: 'Frontend', title: 'Frontend engineer', avatar_sprite: 'Frontend' } }, ...extra,
+});
+
+const mkFile = (name, type = 'image/png', size = 2048) => {
+ const f = new dom.window.File(['x'.repeat(Math.min(size, 16))], name, { type });
+ Object.defineProperty(f, 'size', { value: size });
+ return f;
+};
+// jsdom has no DataTransfer: a stand-in with types, items and files, as Chrome gives them.
+const dataTransfer = (files, extraTypes = []) => ({
+ types: files.length ? ['Files', ...extraTypes] : extraTypes,
+ files,
+ items: files.map((f) => ({ kind: 'file', type: f.type, getAsFile: () => f, webkitGetAsEntry: () => ({ isDirectory: false, name: f.name }) })),
+ dropEffect: 'none',
+ effectAllowed: 'all',
+});
+// The card itself lands in the event's own task (ChatView flushes it). What effects set afterwards (the
+// live region, the exit phase) runs in React's scheduler, which Node drives with setImmediate; whether
+// that or a setTimeout(0) comes first isn't fixed in Node (it flipped on CI's Node 20), so wait for both.
+const tick = async () => {
+ for (let i = 0; i < 3; i += 1) {
+ await new Promise((r) => setImmediate(r));
+ await new Promise((r) => setTimeout(r, 0));
+ }
+};
+// A dragleave inside the page has a relatedTarget (where the pointer went); pass `out` for one that
+// leaves the window, which has none (#478 M2 ends the drag on it).
+const OUT = Symbol('out of the window');
+const fire = async (el, type, dt, to) => {
+ const e = new dom.window.Event(type, { bubbles: true, cancelable: true });
+ Object.defineProperty(e, 'dataTransfer', { value: dt });
+ if (type === 'dragleave') Object.defineProperty(e, 'relatedTarget', { value: to === OUT ? null : (to ?? document.body) });
+ ui.act(() => el.dispatchEvent(e));
+ await tick();
+ return e;
+};
+const parts = (host) => ({
+ pane: host.firstElementChild,
+ header: host.querySelector('[data-chat-header]'),
+ list: host.querySelector('[role="log"]'),
+ form: host.querySelector('form[data-composer-form]'),
+ field: host.querySelector('textarea'),
+});
+const chips = (host) => host.querySelectorAll('ul[aria-label="Files to send"] > li').length;
+const layer = (host) => host.querySelector('[data-drop-layer]');
+const phase = (host) => layer(host)?.getAttribute('data-phase') ?? null;
+const heading = (host) => host.querySelector('[data-drop-heading]')?.textContent ?? null;
+const said = (host) => host.querySelector('[data-drop-announce]')?.textContent ?? '';
+const wait = (ms) => new Promise((r) => setTimeout(r, ms));
+// Somewhere in the window that isn't the chat (the sidebar).
+const elsewhere = () => {
+ const el = document.createElement('nav');
+ document.body.appendChild(el);
+ return el;
+};
+// Ends any drag a test left in the air, so the next one starts clean.
+const endDrag = async () => {
+ ui.act(() => window.dispatchEvent(new dom.window.Event('dragend')));
+ await wait(200);
+};
+const typeIn = (field, text) => {
+ const set = Object.getOwnPropertyDescriptor(dom.window.HTMLTextAreaElement.prototype, 'value').set;
+ ui.act(() => {
+ set.call(field, text);
+ field.dispatchEvent(new dom.window.Event('input', { bubbles: true }));
+ });
+};
+
+test('a file drag over the header or the message list lights up the chat; off the chat it stays armed', async () => {
+ const v = ui.mount(props());
+ const side = elsewhere();
+ try {
+ const { header, list, form } = parts(v.host);
+ assert.ok(header && list, 'the chat has a header and a message list');
+ const two = () => dataTransfer([mkFile('a.png'), mkFile('b.pdf', 'application/pdf')]);
+ // Into the window over the sidebar first: armed, quieter, the composer not lit.
+ await fire(side, 'dragenter', two());
+ assert.equal(phase(v.host), 'armed');
+ assert.equal(heading(v.host), 'Drop here to give Frontend these files');
+ assert.ok(!form.className.includes('kw-dd-lit'));
+ assert.equal(layer(v.host).style.pointerEvents, 'none', 'armed never takes the drop');
+ // Onto the header: over, lit, the layer is the drop surface.
+ const enter = await fire(header, 'dragenter', two());
+ await fire(side, 'dragleave', two());
+ assert.equal(phase(v.host), 'over');
+ assert.equal(heading(v.host), 'Drop to give Frontend these files');
+ assert.equal(v.host.querySelector('[data-drop-count]')?.textContent, '2');
+ assert.ok(form.className.includes('kw-dd-lit') && form.className.includes('kw-dd-raised'), 'the composer is lit above the veil');
+ assert.equal(layer(v.host).style.pointerEvents, 'auto');
+ assert.equal(layer(v.host).getAttribute('aria-hidden'), 'true');
+ assert.equal(said(v.host), 'Drop to give Frontend 2 files: 1 image, 1 PDF.');
+ void enter;
+ // Moving onto a child element: enter the list, then leave the header. No flicker.
+ await fire(list, 'dragenter', two());
+ await fire(header, 'dragleave', two());
+ assert.equal(phase(v.host), 'over', 'still on while the drag is anywhere in the chat');
+ const over = await fire(list, 'dragover', two());
+ assert.equal(over.defaultPrevented, true);
+ assert.equal(over.dataTransfer.dropEffect, 'copy');
+ // Back to the sidebar: armed again, not gone.
+ await fire(side, 'dragenter', two());
+ await fire(list, 'dragleave', two());
+ assert.equal(phase(v.host), 'armed');
+ // Out of the window: the layer fades and goes.
+ await fire(side, 'dragleave', two(), OUT);
+ assert.equal(phase(v.host), 'leaving');
+ await wait(150);
+ assert.equal(layer(v.host), null);
+ } finally {
+ side.remove();
+ v.unmount();
+ await endDrag();
+ }
+});
+
+test('a drop on the message list lands in the tray, the cursor goes to the field and it is read out', async () => {
+ sent.length = 0;
+ const v = ui.mount(props());
+ try {
+ const { list, field } = parts(v.host);
+ const files = [mkFile('one.png'), mkFile('two.pdf', 'application/pdf'), mkFile('three.md', 'text/markdown')];
+ await fire(list, 'dragenter', dataTransfer(files));
+ assert.equal(v.host.querySelector('[data-drop-summary]')?.textContent, '3 files · 1 image, 1 PDF, 1 text file');
+ const drop = await fire(layer(v.host), 'drop', dataTransfer(files));
+ assert.equal(drop.defaultPrevented, true, 'the browser does not open the file');
+ assert.equal(chips(v.host), 3, 'three files in the tray');
+ assert.equal(sent.length, 3, 'all three upload as with the paperclip');
+ assert.equal(document.activeElement, field, 'the cursor is in the field');
+ assert.equal(said(v.host), '3 files added for Frontend. Uploading.');
+ assert.equal(phase(v.host), 'landing', 'the card hands the files down');
+ assert.equal(v.host.querySelectorAll('li[data-fresh]').length, 3, 'the new chips come in tinted');
+ const delays = [...v.host.querySelectorAll('li[data-fresh]')].map((li) => li.style.getPropertyValue('--kw-chip-delay'));
+ assert.deepEqual(delays, ['40ms', '70ms', '100ms']);
+ await wait(200);
+ assert.equal(layer(v.host), null, 'gone by 160 ms');
+ await wait(700);
+ assert.equal(v.host.querySelectorAll('li[data-fresh]').length, 0, 'the tint is gone by 800 ms');
+ } finally {
+ v.unmount();
+ await endDrag();
+ }
+});
+
+test('text and links dragged over the chat are left alone', async () => {
+ const v = ui.mount(props());
+ try {
+ const { list } = parts(v.host);
+ const e = await fire(list, 'dragenter', dataTransfer([], ['text/plain', 'text/uri-list']));
+ const o = await fire(list, 'dragover', dataTransfer([], ['text/plain', 'text/uri-list']));
+ assert.equal(e.defaultPrevented, false);
+ assert.equal(o.defaultPrevented, false);
+ assert.equal(layer(v.host), null);
+ } finally {
+ v.unmount();
+ await endDrag();
+ }
+});
+
+test('unchanged: the box itself still takes a drop, and eleven files keep ten with the note', async () => {
+ sent.length = 0;
+ const v = ui.mount(props());
+ try {
+ const { form } = parts(v.host);
+ const eleven = Array.from({ length: 11 }, (_, i) => mkFile(`p${i}.png`));
+ await fire(form, 'dragenter', dataTransfer(eleven));
+ assert.match(v.host.querySelector('[data-drop-warning]')?.textContent ?? '', /1 more won't fit: 10 files per message\./);
+ assert.equal(v.host.querySelector('[data-drop-count]')?.textContent, '10', 'the badge counts only what will go');
+ await fire(form, 'drop', dataTransfer(eleven));
+ assert.equal(chips(v.host), 10);
+ assert.match(v.host.textContent, /Up to 10 files per message; one was left out\./);
+ } finally {
+ v.unmount();
+ await endDrag();
+ }
+});
+
+test('unchanged: paste and the paperclip add files to the same tray, with the same checks', async () => {
+ const v = ui.mount(props());
+ try {
+ const { field } = parts(v.host);
+ const paste = new dom.window.Event('paste', { bubbles: true, cancelable: true });
+ const shot = mkFile('shot.png');
+ Object.defineProperty(paste, 'clipboardData', { value: { items: [{ kind: 'file', type: 'image/png', getAsFile: () => shot }], types: ['Files'] } });
+ ui.act(() => field.dispatchEvent(paste));
+ await tick();
+ assert.equal(chips(v.host), 1);
+
+ const input = v.host.querySelector('input[type="file"]');
+ Object.defineProperty(input, 'files', { value: [mkFile('big.pdf', 'application/pdf', 21 * 1024 * 1024), mkFile('ok.txt', 'text/plain')], configurable: true });
+ ui.act(() => input.dispatchEvent(new dom.window.Event('change', { bubbles: true })));
+ await tick();
+ assert.equal(chips(v.host), 2, 'the 20 MB file is caught before upload');
+ assert.match(v.host.textContent, /big\.pdf is too big/);
+ assert.equal(v.host.querySelectorAll('li[data-fresh]').length, 0, 'only a drop gets the landing tint');
+ } finally {
+ v.unmount();
+ }
+});
+
+test('/idea mode: the card says files can\'t go in the jar, the cursor says no, and the drop is ignored', async () => {
+ sent.length = 0;
+ const v = ui.mount(props());
+ try {
+ const { list, field, form } = parts(v.host);
+ typeIn(field, '/idea a faster search');
+ await fire(list, 'dragenter', dataTransfer([mkFile('a.png')]));
+ assert.equal(phase(v.host), 'refused');
+ assert.equal(heading(v.host), "Files can't go in the idea jar");
+ assert.match(v.host.querySelector('[data-drop-refusal]').textContent, /Ideas are text only\./);
+ assert.match(v.host.textContent, /Clear \/idea from the field to send them to Frontend\./);
+ assert.ok(!form.className.includes('kw-dd-lit'), 'not lit');
+ assert.equal(v.host.querySelector('[data-drop-count]'), null, 'no badge');
+ assert.equal(said(v.host), "Files can't go in the idea jar. Ideas are text only.");
+ const over = await fire(list, 'dragover', dataTransfer([mkFile('a.png')]));
+ assert.equal(over.dataTransfer.dropEffect, 'none');
+ const drop = await fire(layer(v.host), 'drop', dataTransfer([mkFile('a.png')]));
+ assert.equal(drop.defaultPrevented, true, 'never opens the file either');
+ assert.equal(chips(v.host), 0);
+ assert.equal(sent.length, 0);
+ } finally {
+ v.unmount();
+ await endDrag();
+ }
+});
+
+test('all refused: a ZIP gets the neutral card and is not added', async () => {
+ sent.length = 0;
+ const v = ui.mount(props());
+ try {
+ const { list } = parts(v.host);
+ const zip = () => dataTransfer([mkFile('site.zip', 'application/zip')]);
+ await fire(list, 'dragenter', zip());
+ assert.equal(phase(v.host), 'refused');
+ assert.equal(layer(v.host).getAttribute('data-refused'), 'true');
+ assert.equal(heading(v.host), "This can't go to Frontend");
+ assert.match(v.host.textContent, /ZIP files can't be attached\./);
+ assert.match(v.host.textContent, /Unzip it and drop the files inside\./);
+ await fire(layer(v.host), 'drop', zip());
+ assert.equal(chips(v.host), 0);
+ assert.equal(sent.length, 0);
+ } finally {
+ v.unmount();
+ await endDrag();
+ }
+});
+
+test('some won\'t go: the won\'t-go rows, and a dropped folder is left out with the folder line', async () => {
+ const v = ui.mount(props());
+ try {
+ const { list } = parts(v.host);
+ const twelve = [...Array.from({ length: 11 }, (_, i) => mkFile(`p${i}.png`)), mkFile('a.zip', 'application/zip')];
+ await fire(list, 'dragenter', dataTransfer(twelve));
+ const rows = [...v.host.querySelectorAll('[data-drop-warning] > div')].map((d) => d.textContent);
+ assert.deepEqual(rows, ["1 more won't fit: 10 files per message.", "1 ZIP can't go. Images, videos, PDFs and text or code files work."]);
+ assert.equal(v.host.querySelector('[data-drop-summary]')?.textContent, '10 files · 10 images');
+ await endDrag();
+
+ const png = mkFile('cat.png');
+ const dt = dataTransfer([png]);
+ dt.items.unshift({ kind: 'file', type: '', getAsFile: () => mkFile('Photos', '', 0), webkitGetAsEntry: () => ({ isDirectory: true, name: 'Photos' }) });
+ await fire(list, 'dragenter', dt);
+ assert.equal(v.host.querySelector('[data-drop-summary]')?.textContent, '2 files · 1 image, 1 file', 'a folder looks like a file before the drop');
+ await fire(list, 'drop', dt);
+ assert.equal(chips(v.host), 1, 'only the file');
+ assert.match(v.host.querySelector('p[role="alert"]').textContent, /Folders can't go: drop the files inside\./);
+ } finally {
+ v.unmount();
+ await endDrag();
+ }
+});
+
+test('a room shows its bots and shares with the room; an @mention gives one bot the files', async () => {
+ const bots = ['Marketer', 'Scout', 'Quill', 'Echo', 'Orbit'].map((n, i) => ({ id: `k${i}`, name: n, title: n, avatar_sprite: n }));
+ const v = ui.mount(props({ title: 'Booktuning Marketing', home: undefined, teamName: 'Booktuning Marketing', teamMembers: bots, kwants: bots }));
+ try {
+ const { list, field } = parts(v.host);
+ await fire(list, 'dragenter', dataTransfer([mkFile('a.png')]));
+ assert.equal(heading(v.host), 'Drop to share with the Booktuning Marketing team');
+ assert.equal(v.host.querySelector('.kw-dd-more')?.textContent, '+1', 'four avatars, then +1');
+ assert.equal(said(v.host), 'Drop to share 1 file with the Booktuning Marketing team: 1 image.');
+ await endDrag();
+ typeIn(field, '@Scout look at this');
+ await fire(list, 'dragenter', dataTransfer([mkFile('a.png')]));
+ assert.equal(heading(v.host), 'Drop to give Scout this file');
+ assert.equal(v.host.querySelector('.kw-dd-more'), null);
+ } finally {
+ v.unmount();
+ await endDrag();
+ }
+});
+
+test('the side pane is not a target, a modal keeps the layer away; Esc, a mouse move or leaving the window hide it, a still hand does not', async () => {
+ const v = ui.mount(props());
+ try {
+ const { list } = parts(v.host);
+ // A side pane next to the chat: inside the chat's root, outside its column.
+ const pane = document.createElement('aside');
+ list.parentElement.parentElement.appendChild(pane);
+ await fire(pane, 'dragenter', dataTransfer([mkFile('a.png')]));
+ assert.equal(phase(v.host), 'armed');
+ const o = await fire(pane, 'dragover', dataTransfer([mkFile('a.png')]));
+ assert.equal(o.defaultPrevented, true);
+ assert.equal(o.dataTransfer.dropEffect, 'none');
+ await fire(pane, 'drop', dataTransfer([mkFile('a.png')]));
+ assert.equal(chips(v.host), 0, 'a drop on the side pane does nothing');
+ pane.remove();
+ await endDrag();
+
+ await fire(list, 'dragenter', dataTransfer([mkFile('a.png')]));
+ assert.equal(phase(v.host), 'over');
+ ui.act(() => window.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'Escape' })));
+ await tick();
+ assert.equal(phase(v.host), 'leaving', 'Esc hides it');
+ await endDrag();
+
+ // #478 M2: a hand held still (WebKit sends no dragover then) keeps the layer; the first mouse
+ // move means the OS drag is over; a dragleave out of the window ends it too.
+ await fire(list, 'dragenter', dataTransfer([mkFile('a.png')]));
+ assert.equal(phase(v.host), 'over');
+ await wait(1000);
+ assert.equal(phase(v.host), 'over', 'no dragover for 1 s: still over');
+ ui.act(() => window.dispatchEvent(new dom.window.Event('mousemove')));
+ await tick();
+ assert.equal(phase(v.host), 'leaving', 'a mousemove ends it');
+ await endDrag();
+ await fire(list, 'dragenter', dataTransfer([mkFile('a.png')]));
+ await fire(list, 'dragenter', dataTransfer([mkFile('a.png')]));
+ await fire(list, 'dragleave', dataTransfer([mkFile('a.png')]), OUT);
+ assert.equal(phase(v.host), 'leaving', 'a dragleave with no relatedTarget ends it, depth or not');
+ await endDrag();
+
+ const modal = document.createElement('div');
+ modal.setAttribute('aria-modal', 'true');
+ document.body.appendChild(modal);
+ await fire(list, 'dragenter', dataTransfer([mkFile('a.png')]));
+ assert.equal(layer(v.host), null, 'never over a modal');
+ modal.remove();
+ } finally {
+ v.unmount();
+ await endDrag();
+ }
+});
+
+test('a team @mention shows that team\'s bots, not a made-up face, and gives the files to the team (#478 M4)', async () => {
+ const bots = ['Chef', 'Sous', 'Baker'].map((n, i) => ({ id: `kk${i}`, name: n, title: n, avatar_sprite: n }));
+ const teams = [{ id: 't-kitchen', name: 'Kitchen', member_kwants: ['kk0', 'kk2'] }, { id: 't-empty', name: 'Garden', member_kwants: ['gone'] }];
+ const v = ui.mount(props({ kwants: [{ id: 'k-front', name: 'Frontend', title: 'Frontend', avatar_sprite: 'Frontend' }, ...bots], teams }));
+ try {
+ const { list, field } = parts(v.host);
+ typeIn(field, '@Kitchen look at these');
+ await fire(list, 'dragenter', dataTransfer([mkFile('a.png')]));
+ assert.equal(heading(v.host), 'Drop to share with the Kitchen team');
+ const many = v.host.querySelector('.kw-dd-many');
+ assert.ok(many, 'the room stack, not one big avatar');
+ assert.ok(!v.host.querySelector('.kw-dd-one'), 'no single big avatar');
+ assert.deepEqual([...many.children].map((c) => c.getAttribute('aria-label') ?? c.textContent).length, 2, "Kitchen's two members");
+ assert.ok(!v.host.querySelector('[data-drop-team-icon]'), 'members found: no group circle');
+ await fire(list, 'drop', dataTransfer([mkFile('a.png')]));
+ assert.equal(said(v.host), '1 file added for the Kitchen team. Uploading.');
+ await endDrag();
+ // A team whose bots aren't loaded: a plain group circle.
+ typeIn(field, '@Garden here');
+ await fire(list, 'dragenter', dataTransfer([mkFile('b.png')]));
+ assert.equal(heading(v.host), 'Drop to share with the Garden team');
+ assert.ok(v.host.querySelector('.kw-dd-many [data-drop-team-icon]'), 'the Users circle');
+ assert.equal(v.host.querySelector('.kw-dd-many')?.children.length, 1, 'no bot faces');
+ } finally {
+ v.unmount();
+ await endDrag();
+ }
+});
+
+test('the composer\'s "New" hint hides while the drop layer is up and comes back after, unseen (#478 M3)', async () => {
+ const v = ui.mount(props());
+ try {
+ const { list } = parts(v.host);
+ const shown = () => {
+ const el = v.host.querySelector('[data-new-tag="mention"]');
+ return !!el && !el.classList.contains('hidden');
+ };
+ assert.equal(shown(), true, 'the hint shows before the drag');
+ await fire(list, 'dragenter', dataTransfer([mkFile('a.png')]));
+ assert.equal(phase(v.host), 'over');
+ assert.equal(shown(), false, 'hidden during the drag');
+ await endDrag();
+ assert.equal(layer(v.host), null);
+ assert.equal(shown(), true, 'back after: not marked as seen');
+ } finally {
+ v.unmount();
+ await endDrag();
+ }
+});
+
+test('the over or refused card shows in the dragenter\'s own task, with no armed frame first (#478 round 2)', async () => {
+ const v = ui.mount(props());
+ try {
+ const { list, field } = parts(v.host);
+ // No wait between the event and the read: the window watch's armed render and the pane's own change
+ // land together, so the browser never paints "Drop here to…" first.
+ const enter = (dt) => {
+ const e = new dom.window.Event('dragenter', { bubbles: true, cancelable: true });
+ Object.defineProperty(e, 'dataTransfer', { value: dt });
+ ui.act(() => list.dispatchEvent(e));
+ };
+ enter(dataTransfer([mkFile('a.png')]));
+ assert.equal(phase(v.host), 'over');
+ assert.equal(heading(v.host), 'Drop to give Frontend this file');
+ await endDrag();
+ typeIn(field, '/idea later');
+ enter(dataTransfer([mkFile('a.png')]));
+ assert.equal(phase(v.host), 'refused');
+ } finally {
+ v.unmount();
+ await endDrag();
+ }
+});
+
+test('no chat open: the "Open a chat" pill shows and is read out; with a chat open it does not', async () => {
+ const p = ui.mountPill();
+ const side = elsewhere();
+ try {
+ await fire(side, 'dragenter', dataTransfer([mkFile('a.png')]));
+ assert.equal(p.host.querySelector('[data-drop-pill]')?.textContent, 'Open a chat to drop files there');
+ assert.equal(p.host.querySelector('[data-drop-pill-announce]').textContent, 'Open a chat to drop files there.');
+ await endDrag();
+ assert.equal(p.host.querySelector('[data-drop-pill]'), null);
+ const v = ui.mount(props());
+ await fire(side, 'dragenter', dataTransfer([mkFile('a.png')]));
+ assert.equal(p.host.querySelector('[data-drop-pill]'), null, 'the chat shows its own layer instead');
+ assert.equal(phase(v.host), 'armed');
+ v.unmount();
+ } finally {
+ side.remove();
+ p.unmount();
+ await endDrag();
+ }
+});
diff --git a/frontend/tests/dragPreview.test.mjs b/frontend/tests/dragPreview.test.mjs
new file mode 100644
index 00000000..310dc316
--- /dev/null
+++ b/frontend/tests/dragPreview.test.mjs
@@ -0,0 +1,306 @@
+// 0.8.0 drag and drop into chats (Pixel): the drag-preview helper (what a drag holds before the drop),
+// the drop split (files vs folders), the announcement and the window guard that keeps a stray file
+// drop from opening in place of kwant.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { readFileSync } from 'node:fs';
+import { loadBundled } from './bundle.mjs';
+
+const d = await loadBundled(`export * from './src/dragPreview'; export { MAX_ATTACHMENTS, attachKind, previewRefusesMime } from './src/attachments';`);
+
+const file = (type) => ({ kind: 'file', type });
+const str = (type) => ({ kind: 'string', type });
+
+const bot = { kind: 'bot', name: 'Frontend' };
+const team = { kind: 'team', name: 'Kitchen' };
+const card = (items, inTray = 0, extra = {}) => d.dropCard({ preview: d.previewDrag(items, inTray), recipient: bot, ...extra });
+
+test('one image: one file goes, the card gives it to the bot', () => {
+ const p = d.previewDrag([file('image/png')]);
+ assert.deepEqual({ count: p.count, go: p.go, overBy: p.overBy, slotsLeft: p.slotsLeft, refused: p.refused }, { count: 1, go: 1, overBy: 0, slotsLeft: 10, refused: [] });
+ assert.equal(d.whatLine(p), '1 file · 1 image');
+ const c = card([file('image/png')]);
+ assert.equal(c.state, 'over');
+ assert.equal(d.headingText(c.heading), 'Drop to give Frontend this file');
+ assert.equal(d.headingText(c.armedHeading), 'Drop here to give Frontend this file');
+ assert.deepEqual(c.wont, []);
+ assert.equal(c.announce, 'Drop to give Frontend 1 file: 1 image.');
+});
+
+test('three mixed files: counted by kind; a dragged link alongside is not a file; no items hides the count', () => {
+ const p = d.previewDrag([file('image/jpeg'), file('image/webp'), file('application/pdf'), str('text/uri-list')]);
+ assert.equal(p.count, 3);
+ assert.deepEqual(p.kinds, { image: 2, video: 0, pdf: 1, text: 0, file: 0 });
+ assert.equal(d.whatLine(p), '3 files · 2 images, 1 PDF');
+ const q = d.previewDrag([file('video/mp4'), file('text/markdown'), file('application/json'), file('')]);
+ assert.deepEqual([q.kinds.video, q.kinds.text, q.kinds.file], [1, 2, 1]);
+ // Five kinds: three shown, the rest fold into "other".
+ const r = d.previewDrag([file('image/png'), file('image/png'), file('video/mp4'), file('video/mp4'), file('application/pdf'), file('text/plain'), file('')]);
+ assert.deepEqual(d.kindParts(r).map((k) => k.label), ['2 images', '2 videos', '1 PDF', '2 other']);
+ // A browser that shows no items before the drop: no count, no badge, the heading still says who.
+ const none = d.previewDrag([]);
+ assert.equal(none.count, null);
+ const c = d.dropCard({ preview: none, recipient: bot });
+ assert.equal(c.count, null);
+ assert.equal(d.headingText(c.heading), 'Drop to give Frontend your files');
+ assert.equal(c.announce, 'Drop to give Frontend your files.');
+});
+
+test('headings for every recipient', () => {
+ const h = (r, n = 2, armed = false) => d.headingText(d.dropHeading(r, n, armed));
+ assert.equal(h(bot), 'Drop to give Frontend these files');
+ assert.equal(h({ kind: 'general', name: 'General' }), 'Drop to share in General');
+ assert.equal(h(team), 'Drop to share with the Kitchen team');
+ assert.equal(h({ kind: 'channel', name: '#launch' }, 2, true), 'Drop here to share with #launch');
+ const parts = d.dropHeading(team, 1);
+ assert.deepEqual(parts, { pre: 'Drop to share with the ', name: 'Kitchen', post: ' team' }, 'the name is drawn apart');
+ const c = d.dropCard({ preview: d.previewDrag([file('image/png')]), recipient: team });
+ assert.equal(c.announce, 'Drop to share 1 file with the Kitchen team: 1 image.');
+});
+
+test('some won\'t go: over the limit, with the tray already holding files, and refused files beside good ones', () => {
+ assert.equal(d.MAX_ATTACHMENTS, 10, 'the limit is unchanged');
+ const eleven = Array.from({ length: 11 }, () => file('image/png'));
+ const p = d.previewDrag(eleven);
+ assert.deepEqual({ go: p.go, overBy: p.overBy }, { go: 10, overBy: 1 });
+ assert.deepEqual(card(eleven).wont, ["1 more won't fit: 10 files per message."]);
+ const c = card([file('image/png'), file('image/png'), file('image/png')], 8);
+ assert.deepEqual({ go: c.count, wont: c.wont }, { go: 2, wont: ["1 more won't fit: 10 files per message, 8 are already in."] });
+ assert.equal(c.announce, "Drop to give Frontend 2 files: 2 images. 1 more won't fit.");
+ const one = card(Array.from({ length: 10 }, () => file('image/png')), 1);
+ assert.match(one.wont[0], /1 is already in\.$/);
+ const mixed = card([file('image/png'), file('application/zip'), file('application/zip')]);
+ assert.equal(mixed.state, 'over');
+ assert.deepEqual(mixed.wont, ["2 ZIPs can't go. Images, videos, PDFs and text or code files work."]);
+ const odd = card([file('image/png'), file('application/zip'), file('audio/mpeg')]);
+ assert.equal(odd.wont[0], "2 files can't go. Images, videos, PDFs and text or code files work.");
+ // A refused file still takes a slot, as addFiles does.
+ const slot = d.previewDrag([file('application/zip'), file('image/png')], 9);
+ assert.deepEqual({ go: slot.go, overBy: slot.overBy, refused: slot.refused.length }, { go: 0, overBy: 1, refused: 1 });
+});
+
+test('all refused: the neutral card, in the design\'s order', () => {
+ const zip = card([file('application/zip')]);
+ assert.equal(zip.state, 'refused');
+ assert.equal(zip.count, null);
+ assert.equal(d.headingText(zip.heading), "This can't go to Frontend");
+ assert.equal(zip.refusal.line1, "ZIP files can't be attached.");
+ assert.equal(zip.refusal.line2, 'Images, videos, PDFs and text or code files work. Unzip it and drop the files inside.');
+ assert.equal(zip.announce, "This can't go to Frontend. ZIP files can't be attached.");
+ const two = d.dropCard({ preview: d.previewDrag([file('audio/mpeg'), file('application/msword')]), recipient: team });
+ assert.equal(d.headingText(two.heading), "These can't go to the Kitchen team");
+ assert.equal(two.refusal.line1, "These files can't be attached.");
+ assert.equal(two.refusal.line2, 'Images, videos, PDFs and text or code files work.');
+ const office = card([file('application/vnd.openxmlformats-officedocument.wordprocessingml.document')]);
+ assert.equal(office.refusal.line1, "Office files can't be attached.");
+ // Idea mode first, then a disabled composer, then a full tray.
+ const idea = card([file('application/zip')], 10, { ideaMode: true, disabledReason: 'Sign in first.' });
+ assert.equal(d.headingText(idea.heading), "Files can't go in the idea jar");
+ assert.equal(idea.refusal.line2, 'Clear /idea from the field to send them to Frontend.');
+ const off = card([file('image/png')], 10, { disabledReason: 'Sign in first.' });
+ assert.deepEqual([d.headingText(off.heading), off.refusal.line1], ["Can't drop files here right now", 'Sign in first.']);
+ const full = card([file('image/png')], 10);
+ assert.deepEqual([d.headingText(full.heading), full.refusal.line1, full.refusal.line2], ['The tray is full', '10 files per message.', 'Send these first, then drop the rest.']);
+});
+
+test('the refusal list before the drop matches what the tray refuses after it, and never refuses .ts or SVG', () => {
+ const refused = ['application/zip', 'application/x-zip-compressed', 'application/x-7z-compressed', 'audio/mpeg', 'audio/wav', 'font/woff2', 'image/heic', 'image/heif', 'image/avif', 'image/tiff', 'image/bmp',
+ 'image/vnd.adobe.photoshop', 'video/x-matroska', 'video/x-msvideo', 'video/mpeg', 'application/msword', 'application/vnd.ms-excel',
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.oasis.opendocument.text'];
+ for (const t of refused) {
+ assert.equal(d.previewRefusesMime(t), true, t);
+ assert.equal(d.dragKind(t), 'refused', t);
+ assert.equal(d.attachKind({ name: '', type: t }), null, `${t}: refused by the tray with no name`);
+ assert.equal(d.attachKind({ name: 'x.xyz', type: t }), null, `${t}: refused by the tray with an unknown extension`);
+ }
+ for (const t of ['video/mp2t', 'image/svg+xml', '', 'application/octet-stream', 'application/x-made-up'])
+ assert.equal(d.previewRefusesMime(t), false, `${t || '(empty)'} is never refused before the drop`);
+ assert.equal(d.dragKind('video/mp2t'), 'file', '.ts files are often code, not video');
+});
+
+test('a folder: a plain file while dragging, split out on drop with the folder line', () => {
+ const png = { name: 'cat.png', size: 10, type: 'image/png' };
+ const items = [
+ { kind: 'file', type: '', getAsFile: () => ({ name: 'Photos', size: 0, type: '' }), webkitGetAsEntry: () => ({ isDirectory: true, name: 'Photos' }) },
+ { kind: 'file', type: 'image/png', getAsFile: () => png, webkitGetAsEntry: () => ({ isDirectory: false, name: 'cat.png' }) },
+ { kind: 'string', type: 'text/plain', getAsFile: () => null },
+ ];
+ const out = d.splitDrop(items, [png]);
+ assert.deepEqual(out.folders, ['Photos']);
+ assert.deepEqual(out.files, [png]);
+ assert.equal(d.FOLDER_NOTE, "Folders can't go: drop the files inside.");
+ assert.deepEqual(d.splitDrop(null, [png]).files, [png], 'no items (an old engine): the file list as it is');
+});
+
+test('the announcement after a drop, and the pill', () => {
+ assert.equal(d.dropAnnouncement(3, bot), '3 files added for Frontend. Uploading.');
+ assert.equal(d.dropAnnouncement(1, team), '1 file added for the Kitchen team. Uploading.');
+ assert.equal(d.dropAnnouncement(0, bot), 'No files added.');
+ assert.equal(d.PILL_TEXT, 'Open a chat to drop files there');
+});
+
+// A fake window: listeners by type, timers run by hand.
+const fakeWin = () => {
+ const on = {};
+ const timers = new Map();
+ let id = 0;
+ return {
+ on,
+ timers,
+ addEventListener: (t, f, capture) => ((on[t] ??= []).push(f), assert.equal(capture, true, 'capture phase')),
+ removeEventListener: (t, f) => (on[t] = (on[t] ?? []).filter((g) => g !== f)),
+ setTimeout: (f, ms) => (timers.set(++id, { f, ms }), id),
+ clearTimeout: (t) => timers.delete(t),
+ fire: (t, e) => (on[t] ?? []).forEach((f) => f(e)),
+ runTimers: () => [...timers.entries()].forEach(([k, { f }]) => (timers.delete(k), f())),
+ // Ends the current task: runs the 0 ms timers only (the "a dragenter came in this task" flag).
+ nextTask: () => [...timers.entries()].filter(([, t]) => t.ms === 0).forEach(([k, { f }]) => (timers.delete(k), f())),
+ waitingMs: () => [...timers.values()].map((t) => t.ms).filter((ms) => ms > 0),
+ };
+};
+const dragE = (types = ['Files'], items = [file('image/png')], relatedTarget = {}) => ({ dataTransfer: { types, items }, relatedTarget });
+// A dragleave out of the window: no relatedTarget.
+const leaveWindow = () => ({ dataTransfer: { types: ['Files'], items: [file('image/png')] }, relatedTarget: null });
+
+test('the window watch: depth for enter and leave, the 1500 ms fallback, Esc, a late dragover, open chats', () => {
+ const w = fakeWin();
+ const watch = d.createDragWatch(w);
+ assert.equal(Object.keys(w.on).length, 0, 'nothing on the window until someone listens');
+ let seen = 0;
+ const off = watch.subscribe(() => seen++);
+ assert.deepEqual(Object.keys(w.on).sort(), ['dragend', 'dragenter', 'dragleave', 'dragover', 'drop', 'keydown', 'mousemove', 'pointermove']);
+ w.fire('dragenter', dragE(['text/plain'], []));
+ assert.equal(watch.get().active, false, 'text drags are not watched');
+ w.fire('dragenter', dragE());
+ assert.equal(watch.get().active, true);
+ assert.equal(watch.get().items.length, 1);
+ w.fire('dragenter', dragE());
+ w.fire('dragleave', dragE());
+ assert.equal(watch.get().active, true, 'moving onto a child keeps it on');
+ w.fire('dragleave', dragE());
+ assert.equal(watch.get().active, false, 'depth 0: left the window');
+ // The fallback: armed at 1500 ms on every dragover; firing it ends the drag.
+ w.fire('dragenter', dragE());
+ w.nextTask();
+ w.fire('dragover', dragE());
+ assert.deepEqual(w.waitingMs(), [1500], 'one fallback timer, re-armed');
+ w.runTimers();
+ assert.equal(watch.get().active, false, 'no dragover for 1500 ms: over');
+ w.fire('dragover', dragE());
+ assert.equal(watch.get().active, true, 'a later dragover starts it again');
+ w.fire('keydown', { key: 'a' });
+ assert.equal(watch.get().active, true);
+ w.fire('keydown', { key: 'Escape' });
+ assert.equal(watch.get().active, false, 'Esc');
+ w.fire('dragenter', dragE());
+ w.fire('drop', dragE());
+ assert.equal(watch.get().active, false, 'drop');
+ const a = watch.registerChat();
+ const b = watch.registerChat();
+ assert.equal(watch.get().chats, 2);
+ a();
+ b();
+ assert.equal(watch.get().chats, 0);
+ assert.ok(seen > 0);
+ off();
+ assert.equal(Object.values(w.on).flat().length, 0, 'the last one out takes the listeners off');
+});
+
+// #478 M2: WebKit (and the Mac app's WKWebView) sends dragover mostly when the pointer moves.
+test('a hand held still keeps the drag: no dragover for 1 s with depth > 0 stays active', () => {
+ const w = fakeWin();
+ const watch = d.createDragWatch(w);
+ const off = watch.subscribe(() => {});
+ w.fire('dragenter', dragE());
+ w.nextTask();
+ w.fire('dragover', dragE());
+ // 1 s of nothing: only timers shorter than 1 s may fire.
+ [...w.timers.entries()].filter(([, t]) => t.ms <= 1000).forEach(([k, { f }]) => (w.timers.delete(k), f()));
+ assert.equal(watch.get().active, true, 'still over the chat after 1 s with no dragover');
+ assert.deepEqual(w.waitingMs(), [1500], 'only the 1500 ms fallback is waiting');
+ off();
+});
+
+test('the first mousemove or pointermove ends the drag', () => {
+ for (const type of ['mousemove', 'pointermove']) {
+ const w = fakeWin();
+ const watch = d.createDragWatch(w);
+ const off = watch.subscribe(() => {});
+ w.fire(type, {});
+ assert.equal(watch.get().active, false, 'nothing to end');
+ w.fire('dragenter', dragE());
+ w.fire('dragenter', dragE());
+ assert.equal(watch.get().active, true);
+ w.fire(type, {});
+ assert.equal(watch.get().active, false, `${type}: the OS drag is over`);
+ w.fire('dragover', dragE());
+ w.fire('dragleave', dragE());
+ assert.equal(watch.get().active, false, 'the depth started again from 0, not from the old 2');
+ off();
+ }
+});
+
+test('a dragleave with no relatedTarget ends the drag; a crossing in the same task does not', () => {
+ const w = fakeWin();
+ const watch = d.createDragWatch(w);
+ const off = watch.subscribe(() => {});
+ w.fire('dragenter', dragE());
+ w.fire('dragenter', dragE());
+ w.fire('dragenter', dragE());
+ w.nextTask();
+ // WebKit crossing from one element to the next: the new dragenter, then the old dragleave with no relatedTarget.
+ w.fire('dragenter', dragE());
+ w.fire('dragleave', leaveWindow());
+ assert.equal(watch.get().active, true, 'a crossing, not an exit');
+ w.nextTask();
+ w.fire('dragleave', leaveWindow());
+ assert.equal(watch.get().active, false, 'left the window with depth still 2');
+ off();
+});
+
+const ev = (type, types, prevented = false) => {
+ const e = { type, defaultPrevented: prevented, dataTransfer: { types, dropEffect: 'copy' }, prevented: 0 };
+ e.preventDefault = () => { e.prevented += 1; e.defaultPrevented = true; };
+ return e;
+};
+
+test('a file drop outside a chat is prevented and shows the no-drop cursor', () => {
+ const over = ev('dragover', ['Files']);
+ assert.equal(d.guardFileDrag(over), true);
+ assert.equal(over.prevented, 1);
+ assert.equal(over.dataTransfer.dropEffect, 'none');
+ const drop = ev('drop', ['Files']);
+ assert.equal(d.guardFileDrag(drop), true);
+ assert.equal(drop.prevented, 1);
+});
+
+test('the guard leaves text, links and drops a target already took alone', () => {
+ for (const types of [['text/plain'], ['text/uri-list', 'text/html'], []]) {
+ const e = ev('drop', types);
+ assert.equal(d.guardFileDrag(e), false, types.join());
+ assert.equal(e.prevented, 0);
+ }
+ // The chat pane or the Import dialog called preventDefault: copy cursor stays, nothing more.
+ const taken = ev('dragover', ['Files'], true);
+ assert.equal(d.guardFileDrag(taken), false);
+ assert.equal(taken.dataTransfer.dropEffect, 'copy');
+});
+
+test('the guard goes on the window in bubble phase and comes off', () => {
+ const calls = [];
+ const win = { addEventListener: (t, f, o) => calls.push(['add', t, o]), removeEventListener: (t) => calls.push(['remove', t]) };
+ const off = d.installFileDropGuard(win);
+ assert.deepEqual(calls, [['add', 'dragover', undefined], ['add', 'drop', undefined]]);
+ off();
+ assert.deepEqual(calls.slice(2), [['remove', 'dragover'], ['remove', 'drop']]);
+ const main = readFileSync(new URL('../src/main.tsx', import.meta.url), 'utf8');
+ assert.match(main, /installFileDropGuard\(window\)/, 'the app installs it at start');
+});
+
+test('the Mac and Windows place window hands drops to the page', () => {
+ const rs = readFileSync(new URL('../../apps/mac/src/main.rs', import.meta.url), 'utf8');
+ const start = rs.indexOf('fn make_window<');
+ const body = rs.slice(start, rs.indexOf('\n}\n', start));
+ assert.match(body, /\.disable_drag_drop_handler\(\)/);
+ assert.equal(rs.match(/disable_drag_drop_handler/g).length, 1, 'only the place window; connect and nudge keep Tauri\'s');
+});