feat: implement scoped stat system with player/global support
Introduces a scoping mechanism for statistics, allowing properties to be defined as either "player" (prefixed with player name) or "global". - Adds `scope` property to StatDef - Implements key resolution to handle bare keys vs full keys - Updates `canModifyStat` to enforce player-specific permissions - Enhances `makeStatLookup` to resolve scoped references in formulas - Adds documentation for the new stat system
This commit is contained in:
@@ -15,7 +15,7 @@ import { actionPrefill, setActionPrefill } from "../stores/reveal";
|
||||
import { useJournalCompletions, ensureCompletions } from "./completions";
|
||||
import { resolveRollPayload } from "./types/roll";
|
||||
import { resolveSparkPayload } from "./types/spark";
|
||||
import { resolveStatRoll, canModifyStat } from "./stat-helpers";
|
||||
import { resolveStatRoll, canModifyStat, fullKey } from "./stat-helpers";
|
||||
import { parseInput } from "./command-parser";
|
||||
import type { CompletionItem } from "./command-parser";
|
||||
import { buildCompletions } from "./command-completions";
|
||||
@@ -147,13 +147,18 @@ export const JournalInput: Component = () => {
|
||||
const p = payload as { action?: string; key?: string; value?: string };
|
||||
|
||||
if (p.action === "roll" && p.key) {
|
||||
const resolved = resolveStatRoll(p.key, comp.data.stats, stream.stats);
|
||||
const resolved = resolveStatRoll(
|
||||
p.key,
|
||||
comp.data.stats,
|
||||
stream.stats,
|
||||
stream.myName,
|
||||
);
|
||||
if (resolved.error) {
|
||||
setError(resolved.error);
|
||||
} else {
|
||||
const result = sendMessage("stat", {
|
||||
action: "set",
|
||||
key: p.key,
|
||||
key: resolved.fullKey,
|
||||
value: resolved.value,
|
||||
});
|
||||
const r = unwrap(result);
|
||||
@@ -167,16 +172,38 @@ export const JournalInput: Component = () => {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!canModifyStat(stream.myRole, stream.myName, p.key)) {
|
||||
// Resolve bare key to full key for set/del
|
||||
const fk = resolveKey(p.key, comp.data.stats, stream.myName);
|
||||
|
||||
if (!canModifyStat(stream.myRole, stream.myName, fk, comp.data.stats)) {
|
||||
setError(`无权修改属性: ${p.key}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const result = sendMessage("stat", payload);
|
||||
const result = sendMessage("stat", {
|
||||
action: p.action,
|
||||
key: fk,
|
||||
value: p.value,
|
||||
});
|
||||
const r = unwrap(result);
|
||||
finish(r.ok, r.err);
|
||||
}
|
||||
|
||||
/** Resolve a bare or full key to the actual runtime key. */
|
||||
function resolveKey(
|
||||
inputKey: string,
|
||||
statDefs: typeof comp.data.stats,
|
||||
playerName: string,
|
||||
): string {
|
||||
// Exact match
|
||||
if (statDefs.some((d) => fullKey(d, playerName) === inputKey))
|
||||
return inputKey;
|
||||
// Bare key → full key
|
||||
const def = statDefs.find((d) => d.key === inputKey);
|
||||
if (def) return fullKey(def, playerName);
|
||||
return inputKey;
|
||||
}
|
||||
|
||||
/** Clear text + error on success, or set error on failure. */
|
||||
function finish(success: boolean, err?: string) {
|
||||
if (success) {
|
||||
|
||||
@@ -1,30 +1,29 @@
|
||||
/**
|
||||
* StatsView — table view of all stat key-value pairs
|
||||
*
|
||||
* Groups stats by owner (global, then per-player). Shows computed values
|
||||
* Groups stats by scope (global, then per-player). Shows computed values
|
||||
* (base + modifiers) and inline roll buttons for stats with roll/table/formula.
|
||||
*/
|
||||
|
||||
import { Component, For, createMemo, Show } from "solid-js";
|
||||
import { useJournalStream } from "../stores/journalStream";
|
||||
import { useJournalCompletions } from "./completions";
|
||||
import { fullKey } from "./stat-helpers";
|
||||
import type { StatDef } from "./completions";
|
||||
|
||||
export const StatsView: Component = () => {
|
||||
const stream = useJournalStream();
|
||||
const comp = useJournalCompletions();
|
||||
|
||||
/** All stat definitions from YAML */
|
||||
const statDefs = createMemo(() => comp.data.stats);
|
||||
|
||||
/** Current runtime values */
|
||||
const values = createMemo(() => stream.stats);
|
||||
|
||||
/** Build a lookup: key -> StatDef */
|
||||
/** Build a lookup: fullKey -> StatDef */
|
||||
const defMap = createMemo(() => {
|
||||
const map = new Map<string, StatDef>();
|
||||
for (const def of statDefs()) {
|
||||
map.set(def.key, def);
|
||||
const fk = fullKey(def, stream.myName);
|
||||
map.set(fk, def);
|
||||
}
|
||||
return map;
|
||||
});
|
||||
@@ -38,10 +37,17 @@ export const StatsView: Component = () => {
|
||||
const baseNum = parseFloat(base);
|
||||
|
||||
if (def.type === "number" || def.type === "derived") {
|
||||
// Sum modifiers that target this key
|
||||
const modKeys = statDefs()
|
||||
.filter((d) => d.type === "modifier" && d.target === key)
|
||||
.map((d) => d.key);
|
||||
// Sum modifiers that target this key (fullKey matching)
|
||||
const modKeys: string[] = [];
|
||||
for (const [fk, d] of defMap()) {
|
||||
if (
|
||||
d.type === "modifier" &&
|
||||
d.target &&
|
||||
fullKeyTarget(d.target, d, def)
|
||||
) {
|
||||
modKeys.push(fk);
|
||||
}
|
||||
}
|
||||
let total = isNaN(baseNum) ? 0 : baseNum;
|
||||
for (const mk of modKeys) {
|
||||
const mv = parseFloat(values()[mk] ?? defMap().get(mk)?.default ?? "0");
|
||||
@@ -53,29 +59,50 @@ export const StatsView: Component = () => {
|
||||
return base || "—";
|
||||
}
|
||||
|
||||
/** Group stats by owner */
|
||||
/** Check if a modifier's target matches a given def (scoped correctly). */
|
||||
function fullKeyTarget(
|
||||
target: string,
|
||||
modDef: StatDef,
|
||||
targetDef: StatDef,
|
||||
): boolean {
|
||||
if (modDef.scope === targetDef.scope) {
|
||||
return (
|
||||
fullKey({ ...modDef, key: target }, stream.myName) ===
|
||||
fullKey(targetDef, stream.myName)
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Group stats by scope */
|
||||
const groups = createMemo(() => {
|
||||
const result: { owner: string; label: string; keys: string[] }[] = [];
|
||||
const globalKeys: string[] = [];
|
||||
const playerMap = new Map<string, string[]>();
|
||||
const result: {
|
||||
scope: string;
|
||||
label: string;
|
||||
entries: { fullKey: string; def: StatDef }[];
|
||||
}[] = [];
|
||||
const globalEntries: { fullKey: string; def: StatDef }[] = [];
|
||||
const playerEntries: { fullKey: string; def: StatDef }[] = [];
|
||||
|
||||
for (const def of statDefs()) {
|
||||
const colonIdx = def.key.indexOf(":");
|
||||
if (colonIdx === -1) {
|
||||
globalKeys.push(def.key);
|
||||
const fk = fullKey(def, stream.myName);
|
||||
if (def.scope === "global") {
|
||||
globalEntries.push({ fullKey: fk, def });
|
||||
} else {
|
||||
const owner = def.key.slice(0, colonIdx);
|
||||
if (!playerMap.has(owner)) playerMap.set(owner, []);
|
||||
playerMap.get(owner)!.push(def.key);
|
||||
playerEntries.push({ fullKey: fk, def });
|
||||
}
|
||||
}
|
||||
|
||||
if (globalKeys.length > 0) {
|
||||
result.push({ owner: "", label: "全局", keys: globalKeys });
|
||||
if (globalEntries.length > 0) {
|
||||
result.push({ scope: "global", label: "全局", entries: globalEntries });
|
||||
}
|
||||
|
||||
for (const [owner, keys] of playerMap) {
|
||||
result.push({ owner, label: owner, keys });
|
||||
if (playerEntries.length > 0) {
|
||||
result.push({
|
||||
scope: "player",
|
||||
label: `玩家 (${stream.myName})`,
|
||||
entries: playerEntries,
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
@@ -100,42 +127,47 @@ export const StatsView: Component = () => {
|
||||
</span>
|
||||
</div>
|
||||
<div class="divide-y divide-gray-100">
|
||||
<For each={group.keys}>
|
||||
{(key) => {
|
||||
const def = () => defMap().get(key);
|
||||
const val = () => values()[key];
|
||||
const comp = () => computedValue(key);
|
||||
const hasModifiers = () =>
|
||||
statDefs().some(
|
||||
(d) => d.type === "modifier" && d.target === key,
|
||||
);
|
||||
<For each={group.entries}>
|
||||
{({ fullKey: fk, def }) => {
|
||||
const val = () => values()[fk];
|
||||
const comp = () => computedValue(fk);
|
||||
const hasModifiers = () => {
|
||||
for (const [mfk, md] of defMap()) {
|
||||
if (
|
||||
md.type === "modifier" &&
|
||||
md.target &&
|
||||
fullKeyTarget(md.target, md, def)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
const canRoll = () =>
|
||||
def()?.roll || def()?.formula || def()?.type === "enum";
|
||||
def.roll || def.formula || def.type === "enum";
|
||||
|
||||
return (
|
||||
<div class="flex items-center px-3 py-1.5 hover:bg-white/50 transition-colors">
|
||||
{/* Label + type badge */}
|
||||
<div class="flex-1 min-w-0 flex items-center gap-1.5">
|
||||
<span class="text-sm text-gray-800 truncate">
|
||||
{def()?.label ?? key}
|
||||
{def.label}
|
||||
</span>
|
||||
<span class="text-[10px] text-gray-400 bg-gray-100 px-1 rounded shrink-0">
|
||||
{key}
|
||||
{def.key}
|
||||
</span>
|
||||
<Show when={def()?.type === "modifier"}>
|
||||
<Show when={def.type === "modifier"}>
|
||||
<span class="text-[10px] text-blue-400 bg-blue-50 px-1 rounded shrink-0">
|
||||
→{def()?.target}
|
||||
→{def.target}
|
||||
</span>
|
||||
</Show>
|
||||
</div>
|
||||
|
||||
{/* Value */}
|
||||
<div class="flex items-center gap-2 shrink-0">
|
||||
<Show
|
||||
when={val() !== undefined}
|
||||
fallback={
|
||||
<span class="text-sm text-gray-300">
|
||||
{def()?.default ?? "—"}
|
||||
{def.default ?? "—"}
|
||||
</span>
|
||||
}
|
||||
>
|
||||
@@ -144,11 +176,10 @@ export const StatsView: Component = () => {
|
||||
</span>
|
||||
</Show>
|
||||
|
||||
{/* Computed value (shown when different from base) */}
|
||||
<Show
|
||||
when={
|
||||
hasModifiers() &&
|
||||
comp() !== (val() ?? def()?.default ?? "")
|
||||
comp() !== (val() ?? def.default ?? "")
|
||||
}
|
||||
>
|
||||
<span class="text-xs text-gray-400">
|
||||
@@ -156,13 +187,11 @@ export const StatsView: Component = () => {
|
||||
</span>
|
||||
</Show>
|
||||
|
||||
{/* Roll button */}
|
||||
<Show when={canRoll()}>
|
||||
<button
|
||||
class="text-[10px] bg-green-100 text-green-700 hover:bg-green-200 px-1.5 py-0.5 rounded transition-colors"
|
||||
title="掷骰"
|
||||
onClick={() => {
|
||||
// Prefill the input with /stat roll key
|
||||
const textarea =
|
||||
document.querySelector<HTMLTextAreaElement>(
|
||||
"#journal-input-textarea",
|
||||
@@ -175,7 +204,7 @@ export const StatsView: Component = () => {
|
||||
)?.set;
|
||||
nativeInputValueSetter?.call(
|
||||
textarea,
|
||||
`/stat roll ${key}`,
|
||||
`/stat roll ${def.key}`,
|
||||
);
|
||||
textarea.dispatchEvent(
|
||||
new Event("input", { bubbles: true }),
|
||||
|
||||
@@ -43,6 +43,7 @@ export interface StatDef {
|
||||
key: string;
|
||||
label: string;
|
||||
type: "number" | "string" | "enum" | "modifier" | "derived";
|
||||
scope: "player" | "global";
|
||||
default?: string;
|
||||
target?: string;
|
||||
options?: string[];
|
||||
@@ -204,10 +205,12 @@ function parseStatYaml(yaml: string, source: string): StatDef[] {
|
||||
function flushCurrent() {
|
||||
if (!current || !current.key) return;
|
||||
const type = (current.type || "number") as StatDef["type"];
|
||||
const scope = (current.scope || "global") as StatDef["scope"];
|
||||
defs.push({
|
||||
key: current.key,
|
||||
label: current.label || current.key,
|
||||
type,
|
||||
scope,
|
||||
default: current.default,
|
||||
target: current.target,
|
||||
options:
|
||||
|
||||
@@ -10,19 +10,39 @@ import { evaluateFormula } from "./stat-formula";
|
||||
import type { StatDef } from "./completions";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// Key resolution
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Get the full runtime key for a stat def, given a player name. */
|
||||
export function fullKey(def: StatDef, playerName: string): string {
|
||||
return def.scope === "player" ? `${playerName}:${def.key}` : def.key;
|
||||
}
|
||||
|
||||
/** Find a stat def by its full runtime key. */
|
||||
export function findStatDef(
|
||||
fk: string,
|
||||
statDefs: StatDef[],
|
||||
playerName: string,
|
||||
): StatDef | undefined {
|
||||
return statDefs.find((d) => fullKey(d, playerName) === fk);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Formula stat reference resolution
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Replace stat key references in a dice formula (e.g. "1d20 + attack")
|
||||
* with their numeric values, so the result can be passed to rollFormula.
|
||||
*
|
||||
* Bare keys in formulas resolve relative to the caller's scope: if the
|
||||
* caller def is `scope: player`, then `attack` resolves to `alice:attack`.
|
||||
*/
|
||||
export function resolveStatRefs(
|
||||
formula: string,
|
||||
lookup: (key: string) => number,
|
||||
): string {
|
||||
return formula.replace(/[a-zA-Z_]\w*/g, (match) => {
|
||||
// Don't replace dice notation tokens like "d20", "kh1", etc.
|
||||
if (/^d\d/i.test(match)) return match;
|
||||
if (/^[kdh]\d/i.test(match)) return match;
|
||||
const val = lookup(match);
|
||||
@@ -30,21 +50,35 @@ export function resolveStatRefs(
|
||||
});
|
||||
}
|
||||
|
||||
/** Build a stat lookup function that resolves keys to numbers. */
|
||||
/**
|
||||
* Build a stat lookup function that resolves bare keys to numbers.
|
||||
* Bare keys are scoped by `playerName` if the originating def is player-scoped.
|
||||
*/
|
||||
export function makeStatLookup(
|
||||
runtimeStats: Record<string, string>,
|
||||
statDefs: StatDef[],
|
||||
): (key: string) => number {
|
||||
return (k: string): number => {
|
||||
const val = runtimeStats[k];
|
||||
if (val !== undefined) {
|
||||
const n = parseFloat(val);
|
||||
return isNaN(n) ? 0 : n;
|
||||
playerName: string,
|
||||
/** The def that references are being resolved for (for scoping bare keys). */
|
||||
callerDef?: StatDef,
|
||||
): (bareKey: string) => number {
|
||||
return (bareKey: string): number => {
|
||||
// Try as a full key first, then try scoped
|
||||
const candidates = [bareKey];
|
||||
if (callerDef && callerDef.scope === "player") {
|
||||
candidates.push(`${playerName}:${bareKey}`);
|
||||
}
|
||||
const sdef = statDefs.find((s) => s.key === k);
|
||||
if (sdef?.default !== undefined) {
|
||||
const n = parseFloat(sdef.default);
|
||||
return isNaN(n) ? 0 : n;
|
||||
|
||||
for (const k of candidates) {
|
||||
const val = runtimeStats[k];
|
||||
if (val !== undefined) {
|
||||
const n = parseFloat(val);
|
||||
if (!isNaN(n)) return n;
|
||||
}
|
||||
const sdef = statDefs.find((d) => fullKey(d, playerName) === k);
|
||||
if (sdef?.default !== undefined) {
|
||||
const n = parseFloat(sdef.default);
|
||||
if (!isNaN(n)) return n;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
@@ -58,11 +92,19 @@ export function makeStatLookup(
|
||||
export function canModifyStat(
|
||||
role: string,
|
||||
myName: string,
|
||||
key: string,
|
||||
fullKey: string,
|
||||
statDefs: StatDef[],
|
||||
): boolean {
|
||||
if (role === "gm") return true;
|
||||
if (role === "observer") return false;
|
||||
return key.startsWith(myName + ":");
|
||||
|
||||
const def = findStatDef(fullKey, statDefs, myName);
|
||||
if (!def) return false;
|
||||
if (def.scope === "player") {
|
||||
return fullKey.startsWith(myName + ":");
|
||||
}
|
||||
// Global stats: player can't modify
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -70,38 +112,54 @@ export function canModifyStat(
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface StatRollResult {
|
||||
fullKey: string;
|
||||
value: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a /stat roll command: look up the stat definition, evaluate the
|
||||
* appropriate resolution strategy (enum random, derived formula, dice roll),
|
||||
* and return the string value to publish.
|
||||
* Resolve a /stat roll command: look up the stat definition (by bare or full
|
||||
* key), evaluate the appropriate resolution strategy, and return the string
|
||||
* value to publish.
|
||||
*/
|
||||
export function resolveStatRoll(
|
||||
key: string,
|
||||
inputKey: string,
|
||||
statDefs: StatDef[],
|
||||
runtimeStats: Record<string, string>,
|
||||
playerName: string,
|
||||
): StatRollResult {
|
||||
const def = statDefs.find((s) => s.key === key);
|
||||
// Try exact match first, then resolve bare key → full key
|
||||
let def = statDefs.find((d) => fullKey(d, playerName) === inputKey);
|
||||
if (!def) {
|
||||
return { value: "", error: `未知属性: ${key}` };
|
||||
// Try bare key: find a player-scoped def whose fullKey would match
|
||||
def = statDefs.find(
|
||||
(d) => d.scope === "player" && fullKey(d, playerName) === inputKey,
|
||||
);
|
||||
}
|
||||
if (!def) {
|
||||
// Try finding a bare key match (for global or player)
|
||||
def = statDefs.find((d) => d.key === inputKey);
|
||||
}
|
||||
|
||||
const lookup = makeStatLookup(runtimeStats, statDefs);
|
||||
if (!def) {
|
||||
return { fullKey: inputKey, value: "", error: `未知属性: ${inputKey}` };
|
||||
}
|
||||
|
||||
const fk = fullKey(def, playerName);
|
||||
const lookup = makeStatLookup(runtimeStats, statDefs, playerName, def);
|
||||
|
||||
if (def.type === "enum" && def.options && def.options.length > 0) {
|
||||
const idx = Math.floor(Math.random() * def.options.length);
|
||||
return { value: def.options[idx] };
|
||||
return { fullKey: fk, value: def.options[idx] };
|
||||
}
|
||||
|
||||
if (def.type === "derived" && def.formula) {
|
||||
try {
|
||||
const result = evaluateFormula(def.formula, lookup);
|
||||
return { value: String(result) };
|
||||
return { fullKey: fk, value: String(result) };
|
||||
} catch (e) {
|
||||
return {
|
||||
fullKey: fk,
|
||||
value: "",
|
||||
error: e instanceof Error ? e.message : "公式计算失败",
|
||||
};
|
||||
@@ -111,8 +169,8 @@ export function resolveStatRoll(
|
||||
if (def.roll) {
|
||||
const resolvedFormula = resolveStatRefs(def.roll, lookup);
|
||||
const roll = rollFormula(resolvedFormula);
|
||||
return { value: String(roll.result.total) };
|
||||
return { fullKey: fk, value: String(roll.result.total) };
|
||||
}
|
||||
|
||||
return { value: "", error: `属性 "${key}" 不支持掷骰` };
|
||||
return { fullKey: fk, value: "", error: `属性 "${inputKey}" 不支持掷骰` };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user