Skip to content

Commit 2b04b9f

Browse files
committed
Clean up layer state logic
1 parent eaf1424 commit 2b04b9f

File tree

1 file changed

+35
-19
lines changed

1 file changed

+35
-19
lines changed

src/state.ts

+35-19
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { atom } from "jotai";
1+
import { atom, type Atom } from "jotai";
22
import { atomFamily, splitAtom, waitForAll } from "jotai/utils";
33
import { RedirectError, rethrowUnless } from "./utils";
44

@@ -157,24 +157,40 @@ const LayerConstructors = {
157157
grid: GridLayer,
158158
} as const;
159159

160-
export const layerAtoms = atom((get) => {
161-
const atoms = get(sourceInfoAtomAtoms);
162-
if (atoms.length === 0) {
163-
return [];
164-
}
165-
const layersState = get(waitForAll(atoms.map((a) => layerFamilyAtom(get(a)))));
166-
return layersState.flatMap((layer) => {
167-
if (!layer.on) return [];
168-
const Layer = LayerConstructors[layer.kind];
160+
const layerInstanceFamily = atomFamily((a: Atom<LayerState>) =>
161+
atom((get) => {
162+
const { on, layerProps, kind } = get(a);
163+
if (!on) {
164+
return null;
165+
}
166+
const Layer = LayerConstructors[kind];
169167
// @ts-expect-error - TS can't resolve that Layer & layerProps bound together
170-
const layers: Array<VizarrLayer> = [new Layer(layer.layerProps)];
171-
if (layer.kind === "multiscale" && layer.labels?.length) {
172-
const imageLabelLayers = layer.labels.map(
173-
({ layerProps, transformSourceSelection }) =>
174-
new LabelLayer({ ...layerProps, selection: transformSourceSelection(layer.layerProps.selections[0]) }),
175-
);
176-
layers.push(...imageLabelLayers);
168+
return new Layer(layerProps) as VizarrLayer;
169+
}),
170+
);
171+
172+
const imageLabelsIstanceFamily = atomFamily((a: Atom<LayerState>) =>
173+
atom((get) => {
174+
const { on, labels, layerProps } = get(a);
175+
if (!on || !labels) {
176+
return [];
177177
}
178-
return layers;
179-
});
178+
return labels.map(
179+
(label) =>
180+
new LabelLayer({
181+
...label.layerProps,
182+
selection: label.transformSourceSelection(layerProps.selections[0]),
183+
}),
184+
);
185+
}),
186+
);
187+
188+
export const layerAtoms = atom((get) => {
189+
const layerAtoms = [];
190+
for (const sourceAtom of get(sourceInfoAtomAtoms)) {
191+
const layerStateAtom = layerFamilyAtom(get(sourceAtom));
192+
layerAtoms.push(layerInstanceFamily(layerStateAtom));
193+
layerAtoms.push(imageLabelsIstanceFamily(layerStateAtom));
194+
}
195+
return get(waitForAll(layerAtoms)).flat();
180196
});

0 commit comments

Comments
 (0)