Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/composer-attachments-gate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@intentface/ui": minor
---

- [Composer] [Breaking] The composer now takes files, whether dropped, pasted or passed to `attachments.add`, only while `Composer.Attachments` is mounted. To keep receiving files, mount `<Composer.Attachments />`.
- [Composer] Fix attachments staying on after `Composer.Attachments` unmounts. Unmounting it inside a mounted composer now also clears the files it held.
4 changes: 3 additions & 1 deletion content/docs/primitives/composer.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,9 @@ skipping the last one fires `onSubmit` with `{ kind: "answers" }`. Pass a new
input — it renders no strip of its own. The visible list is yours: read
`useComposer(c => c.attachments)` and lay the items out with the
`@intentface/ui/attachments` parts. `Composer.AttachmentTrigger` opens the
file dialog, and files can also be dropped onto the composer.
file dialog. While `Composer.Attachments` is mounted, files can also be
dropped onto the composer or pasted into it. Without it, the composer ignores
both and leaves drops to the browser.

<Demo component={<AttachmentsDemo />} file="primitives/composer/demos/attachments.tsx" />

Expand Down
23 changes: 19 additions & 4 deletions packages/ui/src/composer/attachments-machine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ export type AttachmentStoreAction =
| { type: "hand-off" };

export type AttachmentStoreConfig = {
// Whether this composer takes files at all. Composer.Attachments turns it on
// while mounted.
enabled: boolean;
accept: string;
maxFiles: number;
maxFileSize: number;
Expand All @@ -40,6 +43,8 @@ export const attachmentReducer = (
): AttachmentStoreState => {
switch (action.type) {
case "add": {
if (!config.enabled) return state;

const incoming = [...action.files];
if (!incoming.length) return state;

Expand Down Expand Up @@ -88,6 +93,9 @@ export const attachmentReducer = (
// Drag-and-drop handlers. A depth counter tracks enter/leave so nested
// elements don't flicker the dragging state.
export type DragHandlerCallbacks = {
// Whether files are taken at all. While off, every event is ignored and the
// depth resets, so a drag that ended unseen leaves no count behind.
isEnabled?: () => boolean;
isInScope: (event: DragEvent) => boolean;
onFiles: (files: FileList) => void;
setDragging: (active: boolean) => void;
Expand All @@ -96,30 +104,37 @@ export type DragHandlerCallbacks = {
export const createDragHandlers = (callbacks: DragHandlerCallbacks) => {
const counter = { current: 0 };
const carriesFiles = (event: DragEvent) => event.dataTransfer?.types?.includes("Files") ?? false;
const isInScope = (event: DragEvent) => {
if (callbacks.isEnabled && !callbacks.isEnabled()) {
counter.current = 0;
return false;
}
return callbacks.isInScope(event);
};

return {
onDragOver: (event: Event) => {
const dragEvent = event as DragEvent;
if (!callbacks.isInScope(dragEvent)) return;
if (!isInScope(dragEvent)) return;
if (carriesFiles(dragEvent)) dragEvent.preventDefault();
},
onDragEnter: (event: Event) => {
const dragEvent = event as DragEvent;
if (!callbacks.isInScope(dragEvent)) return;
if (!isInScope(dragEvent)) return;
if (carriesFiles(dragEvent)) {
counter.current++;
callbacks.setDragging(true);
}
},
onDragLeave: (event: Event) => {
const dragEvent = event as DragEvent;
if (!callbacks.isInScope(dragEvent)) return;
if (!isInScope(dragEvent)) return;
counter.current--;
if (counter.current === 0) callbacks.setDragging(false);
},
onDrop: (event: Event) => {
const dragEvent = event as DragEvent;
if (!callbacks.isInScope(dragEvent)) return;
if (!isInScope(dragEvent)) return;
if (carriesFiles(dragEvent)) dragEvent.preventDefault();
counter.current = 0;
callbacks.setDragging(false);
Expand Down
24 changes: 20 additions & 4 deletions packages/ui/src/composer/attachments.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
// dropzone, error) is presentation: the styled layer composes it from
// useComposer((c) => c.attachments) and the Attachments primitives.

import type { ChangeEvent, ReactNode } from "react";
import { type ChangeEvent, type ReactNode, useEffect } from "react";
import { type AttachmentItem, revokeAttachmentUrl, toAttachmentItem } from "../attachments";
import type { PrimitiveProps } from "../internal/primitive-props";
import { useRenderElement } from "../internal/render/useRenderElement";
import { useIsomorphicLayoutEffect } from "./internals";
import { useComposer, useComposerContextStore } from "./store";

export type ComposerAttachmentsProps = {
Expand All @@ -19,7 +20,7 @@ export type ComposerAttachmentsProps = {
// Cleanup for a removed item, or a sent one once onSubmit has settled.
// Defaults to revoking blob URLs.
destroy?: (item: AttachmentItem) => void;
// Policy — the package imposes none: accept everything, no caps.
// Policy — once mounted, accepts every file with no caps unless set.
accept?: string;
maxFiles?: number;
maxFileSize?: number;
Expand All @@ -41,8 +42,23 @@ export const ComposerAttachments = ({
const store = useComposerContextStore();
const attachments = useComposer((composer) => composer.attachments);

store.attachmentConfigRef.current = { accept, maxFiles, maxFileSize, convert, destroy };
attachments.globalDropRef.current = globalDrop;
const { fileInputRef } = attachments;

// Every mounted instance holds intake on; the newest sets the policy, and
// files are taken until the last one leaves.
useIsomorphicLayoutEffect(
() => store.claimAttachments({ accept, maxFiles, maxFileSize, convert, destroy, globalDrop }),
[store, accept, maxFiles, maxFileSize, convert, destroy, globalDrop],
);

// Removed while the composer stays: the strip usually goes with it, so the
// files it held must not be sent unseen. The store keeps them while another
// instance shows them, or while this input stays in the document (StrictMode,
// a hidden <Activity>) and could come back.
useEffect(() => {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resolved in e085ec9. The cleanup now calls store.settleAttachments(input) and no longer reads rootRef.current itself. The store checks the root at cleanup time on purpose: once the root is gone, the files are the root's to reset. npm run doctor now reports no issues.


Generated by Claude Code

const input = fileInputRef.current;
return () => store.settleAttachments(input);
}, [store, fileInputRef]);

const handleFileChange = (event: ChangeEvent<HTMLInputElement>) => {
if (event.currentTarget.files) {
Expand Down
11 changes: 6 additions & 5 deletions packages/ui/src/composer/internals.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,22 +72,23 @@ export const useCommandRegistry = (commands: ComposerCommandsMap) => {
export const useDragDropFiles = ({
rootRef,
globalDropRef,
configRef,
onFiles,
setDragging,
}: {
rootRef: RefObject<HTMLElement | null>;
globalDropRef: RefObject<boolean>;
configRef: RefObject<{ enabled: boolean }>;
onFiles: (files: FileList) => void;
setDragging: (active: boolean) => void;
}) => {
const onFilesRef = useAsRef(onFiles);

useEffect(() => {
const isInScope = (event: DragEvent) =>
globalDropRef.current || (rootRef.current?.contains(event.target as Node) ?? false);

const handlers = createDragHandlers({
isInScope,
isEnabled: () => configRef.current.enabled,
isInScope: (event) =>
globalDropRef.current || (rootRef.current?.contains(event.target as Node) ?? false),
onFiles: (files) => onFilesRef.current(files),
setDragging,
});
Expand All @@ -102,7 +103,7 @@ export const useDragDropFiles = ({
document.removeEventListener("dragleave", handlers.onDragLeave);
document.removeEventListener("drop", handlers.onDrop);
};
}, [rootRef, globalDropRef, setDragging]);
}, [rootRef, globalDropRef, configRef, setDragging]);
};

export const useComposerSnapshot = ({
Expand Down
1 change: 1 addition & 0 deletions packages/ui/src/composer/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ export const ComposerRoot = ({
useDragDropFiles({
rootRef,
globalDropRef,
configRef: store.attachmentConfigRef,
onFiles: addAttachments,
setDragging: store.setDragging,
});
Expand Down
104 changes: 91 additions & 13 deletions packages/ui/src/composer/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,19 @@ export type ComposerStore = {
setHighlight: (index: number) => void;
setQuestions: (questions: AskUserQuestion[] | null) => void;
setDragging: (active: boolean) => void;
resetAttachments: () => void;
/**
* Composer.Attachments' hold on file intake, taken in a layout effect. The
* latest holder sets the policy, and intake stays on until the last one lets
* go. Returns the release.
*/
claimAttachments: (policy: AttachmentPolicy) => () => void;
/**
* A departing Composer.Attachments' passive cleanup, given the file input it
* rendered. Once no holder is left and the root stays, it clears the files,
* unless the input is still in the document (StrictMode, a hidden
* <Activity>): those are kept for the holder's return.
*/
settleAttachments: (input: HTMLInputElement | null) => void;
/** Composer.Root's keydown: the question's and generation's keys for anything in its tree. True when it used the key; the caller marks it used. */
handleKeyDown: (event: KeyboardEvent) => boolean;
/** The question's keys when focus fell onto the page itself or a container around the composer. Mounted by Composer.Root; returns the cleanup. */
Expand Down Expand Up @@ -219,6 +231,8 @@ export type ComposerStore = {
commandSelectRef: RefObject<(() => void) | null>;
};

export type AttachmentPolicy = Omit<AttachmentStoreConfig, "enabled"> & { globalDrop: boolean };

// Enter and Composer.Submit send through the store, not a native submit, so a
// <form> root runs its validation here: a required, empty Composer.Textarea
// blocks an attachment-only send as it would a native submit.
Expand Down Expand Up @@ -267,11 +281,11 @@ export const createComposerStore = (): ComposerStore => {
const optionsRef: RefObject<AskUserOptionsHandle | null> = { current: null };
const fileInputRef: RefObject<HTMLInputElement | null> = { current: null };
const globalDropRef: RefObject<boolean> = { current: false };
// Permissive defaults: accept everything, no caps, platform-default blob
// ingestion. Composer.Attachments overwrites this with the consumer's
// policy and any custom convert/destroy.
// Attachments are off until Composer.Attachments mounts and writes its
// policy over this one.
const attachmentConfigRef: RefObject<AttachmentStoreConfig> = {
current: {
enabled: false,
accept: "",
maxFiles: Number.POSITIVE_INFINITY,
maxFileSize: Number.POSITIVE_INFINITY,
Expand Down Expand Up @@ -373,9 +387,21 @@ export const createComposerStore = (): ComposerStore => {
};

// --- Attachments
// Each item is released by the destroy of the policy that accepted it, even
// after another Composer.Attachments has taken over.
const destroyers = new WeakMap<AttachmentItem, (item: AttachmentItem) => void>();
const destroyItem = (item: AttachmentItem) =>
(destroyers.get(item) ?? attachmentConfigRef.current.destroy)(item);

const dispatchAttachments = (action: AttachmentStoreAction) => {
const next = attachmentReducer(attachmentState, action, attachmentConfigRef.current);
const config = attachmentConfigRef.current;
const next = attachmentReducer(attachmentState, action, { ...config, destroy: destroyItem });
if (next === attachmentState) return;
if (action.type === "add") {
for (const item of next.items) {
if (!destroyers.has(item)) destroyers.set(item, config.destroy);
}
}
attachmentState = next;
snapshot = {
...snapshot,
Expand All @@ -390,6 +416,55 @@ export const createComposerStore = (): ComposerStore => {
notify();
};

// Mounted Composer.Attachments, oldest first; the newest sets the policy.
const holders: AttachmentPolicy[] = [];
// The input of a holder that left while its input stayed in the document (a
// hidden <Activity>). Its files wait for it; once the input is gone for good,
// nothing will show them again, so they are cleared.
let waitingInput: HTMLInputElement | null = null;

const clearAbandonedFiles = () => {
if (!waitingInput || waitingInput.isConnected) return;
waitingInput = null;
dispatchAttachments({ type: "reset" });
};

const applyHolders = () => {
const top = holders.at(-1);
if (top) {
const { globalDrop, ...policy } = top;
attachmentConfigRef.current = { ...policy, enabled: true };
globalDropRef.current = globalDrop;
} else {
attachmentConfigRef.current = { ...attachmentConfigRef.current, enabled: false };
globalDropRef.current = false;
setDragging(false);
}
};

const claimAttachments = (policy: AttachmentPolicy) => {
clearAbandonedFiles();
waitingInput = null;
holders.push(policy);
applyHolders();
return () => {
const index = holders.indexOf(policy);
if (index !== -1) holders.splice(index, 1);
applyHolders();
};
};

const settleAttachments = (input: HTMLInputElement | null) => {
// Another holder took over (a keyed replacement) and shows the files; or
// the whole composer went, and the root decides.
if (holders.length || !rootRef.current?.isConnected) return;
if (input?.isConnected) {
waitingInput = input;
return;
}
dispatchAttachments({ type: "reset" });
};

// --- Ask-user
// The execute half of the ask-user flow: replay a transition's effects
// against the editor controller, the options handle, and the submit
Expand Down Expand Up @@ -562,33 +637,34 @@ export const createComposerStore = (): ComposerStore => {
return;
}

const { attachments, isSubmitting } = snapshot;
if (snapshot.isSubmitting || !isRootValid(rootRef.current)) return;

if (isSubmitting || !isRootValid(rootRef.current)) return;
clearAbandonedFiles();
// Files go out only while a Composer.Attachments shows them. Ones waiting
// for a hidden holder stay behind for its return.
const files = holders.length ? attachmentState.items : [];

const serialized = controller.serialize();
const trimmedText = serialized.text.trim();
if (!trimmedText && !attachments.items.length) return;
if (!trimmedText && !files.length) return;

// Emit the generic attachment descriptors; the consumer's onSubmit adapts
// them to its wire format (e.g. FilePart via prepareAttachmentsForSend).
// Text may be empty on an attachments-only submit — any placeholder copy
// is the consumer's.
const files = attachments.items;
const { destroy } = attachmentConfigRef.current;

// From the hand-off on the store no longer holds the files, so everything
// after it runs inside the try and the finally is their only release.
try {
dispatchAttachments({ type: "hand-off" });
if (files.length) dispatchAttachments({ type: "hand-off" });
controller.clear();
await onSubmitRef.current?.({
kind: "message",
text: trimmedText,
files,
});
} finally {
for (const item of files) destroy(item);
for (const item of files) destroyItem(item);
}
};

Expand Down Expand Up @@ -617,6 +693,7 @@ export const createComposerStore = (): ComposerStore => {
// revoke attachment object URLs, then restore the pristine snapshot.
const reset = () => {
dispatchAttachments({ type: "reset" });
waitingInput = null;
flow = IDLE_FLOW;
commandSelectRef.current = null;
snapshot = initialSnapshot;
Expand Down Expand Up @@ -649,7 +726,8 @@ export const createComposerStore = (): ComposerStore => {
setHighlight,
setQuestions,
setDragging,
resetAttachments: () => dispatchAttachments({ type: "reset" }),
claimAttachments,
settleAttachments,
handleKeyDown,
listenForStrayKeys,
finalizePanelClose,
Expand Down
2 changes: 1 addition & 1 deletion packages/ui/src/composer/use-composer-editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -522,7 +522,7 @@ const createEditorEngine = (getDependencies: () => EngineDependencies) => {

const handlePaste = (event: ClipboardEvent) => {
const items = event.clipboardData?.items;
if (items) {
if (items && getDependencies().store.attachmentConfigRef.current.enabled) {
const files = [...items]
.filter((item) => item.kind === "file")
.map((item) => item.getAsFile())
Expand Down
Loading
Loading