import {Signal, signal, SignalOptions} from "@preact/signals-core"; import {create} from 'mutative'; export class Entity extends Signal { public constructor(public readonly id: string, t?: T, options?: SignalOptions) { super(t, options); } produce(fn: (draft: T) => void) { this.value = create(this.value, fn); } } export function entity(id: string, t?: T, options?: SignalOptions) { return new Entity(id, t, options); } export type EntityCollection = { collection: Signal>>; remove(...ids: string[]): void; add(...entities: (T & {id: string})[]): void; get(id: string): Entity; } export function createEntityCollection(): EntityCollection { const collection = signal({} as Record>); const remove = (...ids: string[]) => { collection.value = Object.fromEntries( Object.entries(collection.value).filter(([id]) => !ids.includes(id)), ); }; const add = (...entities: (T & {id: string})[]) => { collection.value = { ...collection.value, ...Object.fromEntries(entities.map((e) => [e.id, entity(e.id, e)])), }; }; const get = (id: string) => collection.value[id]; return { collection, remove, add, get } }