Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

preparingComposerImages.ts

75 lines2.5 KB

1import { create } from "zustand";
2​
3export interface PreparingComposerImage {
4 readonly id: string;
5 readonly name: string;
6 /** The uncompressed source, thumbnailed so the placeholder shows the image itself. */
7 readonly file: File;
8}
9​
10const NO_PREPARING_IMAGES: ReadonlyArray<PreparingComposerImage> = [];
11​
12/**
13 * Images accepted into a draft but still being compressed, keyed by attachment target. Large
14 * screenshots take a noticeable moment to re-encode, so the strip shows these right away and
15 * they hold their attachment slots until the real image joins the draft.
16 */
17const usePreparingComposerImageStore = create<{
18 readonly byTargetKey: Readonly<Record<string, ReadonlyArray<PreparingComposerImage>>>;
19}>(() => ({ byTargetKey: {} }));
20​
21export function usePreparingComposerImages(targetKey: string) {
22 return usePreparingComposerImageStore(
23 (state) => state.byTargetKey[targetKey] ?? NO_PREPARING_IMAGES,
24 );
26​
27export function countPreparingComposerImages(targetKey: string): number {
28 return usePreparingComposerImageStore.getState().byTargetKey[targetKey]?.length ?? 0;
30​
31export function addPreparingComposerImages(
32 targetKey: string,
33 images: ReadonlyArray<PreparingComposerImage>,
34): void {
35 usePreparingComposerImageStore.setState((state) => ({
36 byTargetKey: {
37 ...state.byTargetKey,
38 [targetKey]: [...(state.byTargetKey[targetKey] ?? NO_PREPARING_IMAGES), ...images],
39 },
40 }));
42​
43export function isPreparingComposerImage(targetKey: string, imageId: string): boolean {
44 return (
45 usePreparingComposerImageStore
46 .getState()
47 .byTargetKey[targetKey]?.some((image) => image.id === imageId) ?? false
48 );
50​
51/** Returns the ids that were still preparing; any other id was cancelled from the strip. */
52export function removePreparingComposerImages(
53 targetKey: string,
54 imageIds: ReadonlySet<string>,
55): ReadonlySet<string> {
56 const current =
57 usePreparingComposerImageStore.getState().byTargetKey[targetKey] ?? NO_PREPARING_IMAGES;
58 const removed = new Set(
59 current.filter((image) => imageIds.has(image.id)).map((image) => image.id),
60 );
61 if (removed.size === 0) return removed;
62 usePreparingComposerImageStore.setState((state) => {
63 const remaining = (state.byTargetKey[targetKey] ?? NO_PREPARING_IMAGES).filter(
64 (image) => !removed.has(image.id),
65 );
66 const byTargetKey = { ...state.byTargetKey };
67 if (remaining.length > 0) {
68 byTargetKey[targetKey] = remaining;
69 } else {
70 delete byTargetKey[targetKey];
71 }
72 return { byTargetKey };
73 });
74 return removed;