Open History to see the last commit
1import { useEffect, useRef } from "react";
2import { create } from "zustand";
3
4import { useStableCallback } from "../../hooks/useStableCallback";
5
6export interface PreparingComposerImage {
7 readonly id: string;
8 readonly name: string;
9 /** The uncompressed source, thumbnailed so the placeholder shows the image itself. */
10 readonly file: File;
11 /** Looks like an image the draft already has: it holds its slot but shows no tile. */
12 readonly hidden: boolean;
13}
14
15const NO_PREPARING_IMAGES: ReadonlyArray<PreparingComposerImage> = [];
16
17/**
18 * Images accepted into a draft but still being compressed, keyed by attachment target. Large
19 * screenshots take a noticeable moment to re-encode, so the strip shows these right away and
20 * they hold their attachment slots until the real image joins the draft.
21 */
22const usePreparingComposerImageStore = create<{
23 readonly byTargetKey: Readonly<Record<string, ReadonlyArray<PreparingComposerImage>>>;
24}>(() => ({ byTargetKey: {} }));
25
26export function usePreparingComposerImages(targetKey: string) {
27 return usePreparingComposerImageStore(
28 (state) => state.byTargetKey[targetKey] ?? NO_PREPARING_IMAGES,
29 );
30}
31
32export function getPreparingComposerImages(
33 targetKey: string,
34): ReadonlyArray<PreparingComposerImage> {
35 return usePreparingComposerImageStore.getState().byTargetKey[targetKey] ?? NO_PREPARING_IMAGES;
36}
37
38export function countPreparingComposerImages(targetKey: string): number {
39 return getPreparingComposerImages(targetKey).length;
40}
41
42export function addPreparingComposerImages(
43 targetKey: string,
44 images: ReadonlyArray<PreparingComposerImage>,
45): void {
46 usePreparingComposerImageStore.setState((state) => ({
47 byTargetKey: {
48 ...state.byTargetKey,
49 [targetKey]: [...(state.byTargetKey[targetKey] ?? NO_PREPARING_IMAGES), ...images],
50 },
51 }));
52}
53
54export function isPreparingComposerImage(targetKey: string, imageId: string): boolean {
55 return (
56 usePreparingComposerImageStore
57 .getState()
58 .byTargetKey[targetKey]?.some((image) => image.id === imageId) ?? false
59 );
60}
61
62/** Returns the ids that were still preparing; any other id was cancelled from the strip. */
63export function removePreparingComposerImages(
64 targetKey: string,
65 imageIds: ReadonlySet<string>,
66 options?: { readonly cancelSubmission?: boolean },
67): ReadonlySet<string> {
68 const current =
69 usePreparingComposerImageStore.getState().byTargetKey[targetKey] ?? NO_PREPARING_IMAGES;
70 const removed = new Set(
71 current.filter((image) => imageIds.has(image.id)).map((image) => image.id),
72 );
73 if (removed.size === 0) return removed;
74 if (options?.cancelSubmission) invalidatePendingSubmit(targetKey);
75 usePreparingComposerImageStore.setState((state) => {
76 const remaining = (state.byTargetKey[targetKey] ?? NO_PREPARING_IMAGES).filter(
77 (image) => !removed.has(image.id),
78 );
79 const byTargetKey = { ...state.byTargetKey };
80 if (remaining.length > 0) {
81 byTargetKey[targetKey] = remaining;
82 } else {
83 delete byTargetKey[targetKey];
84 }
85 return { byTargetKey };
86 });
87 return removed;
88}
89
90// Bumped on cancel so a send held for the cancelled images is dropped rather than released.
91const cancelGenerations = new Map<string, number>();
92
93function invalidatePendingSubmit(targetKey: string) {
94 cancelGenerations.set(targetKey, (cancelGenerations.get(targetKey) ?? 0) + 1);
95}
96
97/** Drops every image still preparing for the target, so its compression result is discarded. */
98export function cancelPreparingComposerImages(targetKey: string): void {
99 invalidatePendingSubmit(targetKey);
100 if (!usePreparingComposerImageStore.getState().byTargetKey[targetKey]) return;
101 usePreparingComposerImageStore.setState((state) => {
102 const byTargetKey = { ...state.byTargetKey };
103 delete byTargetKey[targetKey];
104 return { byTargetKey };
105 });
106}
107
108/**
109 * Holds a send made while the target still has images compressing, and runs it once they finish,
110 * so the turn includes them. Returns false when nothing is compressing and the caller should send.
111 */
112export function useSubmitAfterPreparingImages(targetKey: string, blocked = false) {
113 const preparing = usePreparingComposerImages(targetKey);
114 const pendingRef = useRef<{
115 readonly targetKey: string;
116 readonly cancelGeneration: number;
117 readonly submit: () => void;
118 } | null>(null);
119 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- sends only after the render where the compressed images joined the draft
120 useEffect(() => {
121 const pending = pendingRef.current;
122 if (!pending) return;
123 if (
124 pending.targetKey !== targetKey ||
125 pending.cancelGeneration !== (cancelGenerations.get(targetKey) ?? 0)
126 ) {
127 pendingRef.current = null;
128 return;
129 }
130 if (preparing.length > 0 || blocked) return;
131 pendingRef.current = null;
132 // After the composer's later effects have synced its draft refs to this render.
133 queueMicrotask(pending.submit);
134 }, [preparing, targetKey, blocked]);
135 return useStableCallback((submit: () => void) => {
136 if (countPreparingComposerImages(targetKey) === 0) return false;
137 pendingRef.current = {
138 targetKey,
139 cancelGeneration: cancelGenerations.get(targetKey) ?? 0,
140 submit,
141 };
142 return true;
143 });
144}