refactor: fix reactivity
This commit is contained in:
+25
-1
@@ -2,7 +2,7 @@ import {createModel, Signal, signal} from '@preact/signals-core';
|
||||
import {createEntityCollection} from "../utils/entity";
|
||||
import {Part} from "./part";
|
||||
import {Region} from "./region";
|
||||
import {RuleRegistry, RuleContext, dispatchCommand as dispatchRuleCommand} from "./rule";
|
||||
import {RuleDef, RuleRegistry, RuleContext, dispatchCommand as dispatchRuleCommand} from "./rule";
|
||||
|
||||
export type Context = {
|
||||
type: string;
|
||||
@@ -37,11 +37,33 @@ export const GameContext = createModel((root: Context) => {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function registerRule(name: string, rule: RuleDef<unknown>) {
|
||||
const newRules = new Map(rules.value);
|
||||
newRules.set(name, rule);
|
||||
rules.value = newRules;
|
||||
}
|
||||
|
||||
function unregisterRule(name: string) {
|
||||
const newRules = new Map(rules.value);
|
||||
newRules.delete(name);
|
||||
rules.value = newRules;
|
||||
}
|
||||
|
||||
function addRuleContext(ctx: RuleContext<unknown>) {
|
||||
ruleContexts.value = [...ruleContexts.value, ctx];
|
||||
}
|
||||
|
||||
function removeRuleContext(ctx: RuleContext<unknown>) {
|
||||
ruleContexts.value = ruleContexts.value.filter(c => c !== ctx);
|
||||
}
|
||||
|
||||
function dispatchCommand(input: string) {
|
||||
return dispatchRuleCommand({
|
||||
rules: rules.value,
|
||||
ruleContexts: ruleContexts.value,
|
||||
contexts,
|
||||
addRuleContext,
|
||||
removeRuleContext,
|
||||
}, input);
|
||||
}
|
||||
|
||||
@@ -54,6 +76,8 @@ export const GameContext = createModel((root: Context) => {
|
||||
pushContext,
|
||||
popContext,
|
||||
latestContext,
|
||||
registerRule,
|
||||
unregisterRule,
|
||||
dispatchCommand,
|
||||
}
|
||||
})
|
||||
|
||||
+4
-3
@@ -38,13 +38,12 @@ function parseYieldedSchema(value: string | CommandSchema): CommandSchema {
|
||||
|
||||
function pushContextToGame(game: GameContextLike, ctx: RuleContext<unknown>) {
|
||||
game.contexts.value = [...game.contexts.value, { value: ctx } as any];
|
||||
game.ruleContexts.push(ctx);
|
||||
game.addRuleContext(ctx);
|
||||
}
|
||||
|
||||
function discardChildren(game: GameContextLike, parent: RuleContext<unknown>) {
|
||||
for (const child of parent.children) {
|
||||
const idx = game.ruleContexts.indexOf(child);
|
||||
if (idx !== -1) game.ruleContexts.splice(idx, 1);
|
||||
game.removeRuleContext(child);
|
||||
|
||||
const ctxIdx = game.contexts.value.findIndex((c: any) => c.value === child);
|
||||
if (ctxIdx !== -1) {
|
||||
@@ -161,4 +160,6 @@ type GameContextLike = {
|
||||
rules: RuleRegistry;
|
||||
ruleContexts: RuleContext<unknown>[];
|
||||
contexts: { value: any[] };
|
||||
addRuleContext: (ctx: RuleContext<unknown>) => void;
|
||||
removeRuleContext: (ctx: RuleContext<unknown>) => void;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user