boardgame-core/src/core/context.ts

43 lines
1.2 KiB
TypeScript
Raw Normal View History

2026-04-01 13:36:16 +08:00
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>;
}
}
}
2026-04-01 17:34:21 +08:00
2026-04-01 13:36:16 +08:00
return {
parts,
regions,
contexts,
pushContext,
popContext,
latestContext,
}
2026-04-01 17:34:21 +08:00
})
/** 创建游戏上下文实例 */
export function createGameContext(root: Context = { type: 'game' }) {
return new GameContext(root);
}