mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-04-19 15:21:23 +02:00
Lint stuff
This commit is contained in:
@@ -1,22 +1,34 @@
|
||||
import { atom } from "jotai";
|
||||
import { selectAtom } from "jotai/utils";
|
||||
|
||||
/** Any model must at least have an id. */
|
||||
type BaseModel = { id: string };
|
||||
/** Model map: each key is a model type name, each value is the model shape (must have id). */
|
||||
type ModelMap = Record<string, { id: string }>;
|
||||
|
||||
/** The raw store shape: model type string → id → model instance. */
|
||||
type StoreData<M extends BaseModel> = Record<string, Record<string, M>>;
|
||||
/** The store data shape derived from the model map. */
|
||||
type StoreData<M extends ModelMap> = {
|
||||
[K in keyof M]: Record<string, M[K]>;
|
||||
};
|
||||
|
||||
export type ModelChange = { type: "upsert" } | { type: "delete" };
|
||||
|
||||
export function createModelStore<M extends BaseModel>() {
|
||||
const dataAtom = atom<StoreData<M>>({});
|
||||
function emptyStore<M extends ModelMap>(keys: (keyof M)[]): StoreData<M> {
|
||||
const data = {} as StoreData<M>;
|
||||
for (const k of keys) {
|
||||
data[k] = {} as Record<string, M[typeof k]>;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
export function createModelStore<M extends ModelMap>(
|
||||
modelTypes: (keyof M & string)[],
|
||||
) {
|
||||
const dataAtom = atom<StoreData<M>>(emptyStore<M>(modelTypes));
|
||||
|
||||
/** Apply a single upsert or delete to the store. */
|
||||
function applyChange(
|
||||
function applyChange<K extends keyof M & string>(
|
||||
prev: StoreData<M>,
|
||||
modelType: string,
|
||||
model: M,
|
||||
modelType: K,
|
||||
model: M[K],
|
||||
change: ModelChange,
|
||||
): StoreData<M> {
|
||||
if (change.type === "upsert") {
|
||||
@@ -32,24 +44,24 @@ export function createModelStore<M extends BaseModel>() {
|
||||
}
|
||||
|
||||
/** Atom that selects all models of a given type as an array. */
|
||||
function listAtom(modelType: string) {
|
||||
function listAtom<K extends keyof M & string>(modelType: K) {
|
||||
return selectAtom(
|
||||
dataAtom,
|
||||
(data) => Object.values(data[modelType] ?? {}),
|
||||
(data) => Object.values(data[modelType] ?? {}) as M[K][],
|
||||
shallowEqual,
|
||||
);
|
||||
}
|
||||
|
||||
/** Atom that selects all models of a given type, sorted by a field. */
|
||||
function orderedListAtom<K extends keyof M>(
|
||||
modelType: string,
|
||||
field: K,
|
||||
function orderedListAtom<K extends keyof M & string>(
|
||||
modelType: K,
|
||||
field: keyof M[K],
|
||||
order: "asc" | "desc",
|
||||
) {
|
||||
return selectAtom(
|
||||
dataAtom,
|
||||
(data) => {
|
||||
const vals = Object.values(data[modelType] ?? {});
|
||||
const vals = Object.values(data[modelType] ?? {}) as M[K][];
|
||||
return vals.sort((a, b) => {
|
||||
const n = a[field] > b[field] ? 1 : -1;
|
||||
return order === "desc" ? -n : n;
|
||||
|
||||
Reference in New Issue
Block a user