38 lines
1.1 KiB
TypeScript
38 lines
1.1 KiB
TypeScript
|
|
import {createModel, Signal, signal} from '@preact/signals-core';
|
||
|
|
import {createEntityCollection} from "../utils/entity";
|
||
|
|
import {Part} from "./part";
|
||
|
|
import {Region} from "./region";
|
||
|
|
|
||
|
|
export type Context = {
|
||
|
|
type: string;
|
||
|
|
}
|
||
|
|
|
||
|
|
export const GameContext = createModel((root: Context) => {
|
||
|
|
const parts = createEntityCollection<Part>();
|
||
|
|
const regions = createEntityCollection<Region>();
|
||
|
|
const contexts = signal([signal(root)]);
|
||
|
|
function pushContext(context: Context) {
|
||
|
|
const ctxSignal = signal(context);
|
||
|
|
contexts.value = [...contexts.value, ctxSignal];
|
||
|
|
return context;
|
||
|
|
}
|
||
|
|
function popContext() {
|
||
|
|
contexts.value = contexts.value.slice(0, -1);
|
||
|
|
}
|
||
|
|
function latestContext<T extends Context>(type: T['type']){
|
||
|
|
for(let i = contexts.value.length - 1; i >= 0; i--){
|
||
|
|
if(contexts.value[i].value.type === type){
|
||
|
|
return contexts.value[i] as Signal<T>;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
return {
|
||
|
|
parts,
|
||
|
|
regions,
|
||
|
|
contexts,
|
||
|
|
pushContext,
|
||
|
|
popContext,
|
||
|
|
latestContext,
|
||
|
|
}
|
||
|
|
})
|