@flare-engine/dialogue 0.4.6 → 0.4.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +10 -16
- package/dist/index.d.mts.map +1 -1
- package/dist/index.d.ts +10 -16
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -6
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +3 -6
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { Signal } from "@flare-engine/events";
|
|
2
|
-
//#region src/graph.d.ts
|
|
3
2
|
/**
|
|
4
3
|
* Dialogue graph data types.
|
|
5
4
|
*
|
|
@@ -74,12 +73,10 @@ interface DialogueGraph {
|
|
|
74
73
|
/** All nodes keyed by id. */
|
|
75
74
|
readonly nodes: Record<string, DialogueNode>;
|
|
76
75
|
}
|
|
77
|
-
declare function createDialogueGraph(id: string, start: string, nodes: Record<string, DialogueNode>): DialogueGraph;
|
|
78
|
-
declare function getNode(graph: DialogueGraph, nodeId: string): DialogueNode | undefined;
|
|
79
|
-
//#endregion
|
|
80
|
-
//#region src/runner.d.ts
|
|
76
|
+
export declare function createDialogueGraph(id: string, start: string, nodes: Record<string, DialogueNode>): DialogueGraph;
|
|
77
|
+
export declare function getNode(graph: DialogueGraph, nodeId: string): DialogueNode | undefined;
|
|
81
78
|
type DialogueErrorCode = 'missing-node' | 'cycle';
|
|
82
|
-
declare class DialogueError extends Error {
|
|
79
|
+
export declare class DialogueError extends Error {
|
|
83
80
|
readonly code: DialogueErrorCode;
|
|
84
81
|
/** Source node whose transition triggered the error (or the entry id when there is no source). */
|
|
85
82
|
readonly nodeId: string;
|
|
@@ -115,7 +112,7 @@ interface ActiveOption {
|
|
|
115
112
|
readonly next: string;
|
|
116
113
|
}
|
|
117
114
|
type DialogueRunnerState = 'idle' | 'running' | 'waiting-choice' | 'ended';
|
|
118
|
-
declare function interpolate(template: string, vars: VariableBag): string;
|
|
115
|
+
export declare function interpolate(template: string, vars: VariableBag): string;
|
|
119
116
|
interface DialogueRunner {
|
|
120
117
|
readonly onLine: Signal<DialogueLineEvent>;
|
|
121
118
|
readonly onChoice: Signal<DialogueChoiceEvent>;
|
|
@@ -138,9 +135,7 @@ interface DialogueRunnerOptions {
|
|
|
138
135
|
*/
|
|
139
136
|
onError?: (err: DialogueError) => void;
|
|
140
137
|
}
|
|
141
|
-
declare function createDialogueRunner(options?: DialogueRunnerOptions): DialogueRunner;
|
|
142
|
-
//#endregion
|
|
143
|
-
//#region src/text-reveal.d.ts
|
|
138
|
+
export declare function createDialogueRunner(options?: DialogueRunnerOptions): DialogueRunner;
|
|
144
139
|
/**
|
|
145
140
|
* Text-over-time reveal hook for dialogue lines.
|
|
146
141
|
*
|
|
@@ -164,10 +159,9 @@ interface TextRevealOptions {
|
|
|
164
159
|
/** Extra delay (in seconds) after punctuation (.!?). Default: 0.15. */
|
|
165
160
|
punctuationDelay?: number;
|
|
166
161
|
}
|
|
167
|
-
declare function createTextReveal(text: string): TextRevealState;
|
|
168
|
-
declare function updateTextReveal(state: TextRevealState, dt: number, options?: TextRevealOptions): void;
|
|
169
|
-
declare function completeTextReveal(state: TextRevealState): void;
|
|
170
|
-
declare function resetTextReveal(state: TextRevealState, newText?: string): void;
|
|
171
|
-
|
|
172
|
-
export { type ActionHandler, type ActionNode, type ActiveOption, type BranchArm, type BranchNode, type ChoiceNode, type ChoiceOption, type ConditionResolver, type DialogueChoiceEvent, DialogueError, type DialogueErrorCode, type DialogueGraph, type DialogueLineEvent, type DialogueNode, type DialogueRunner, type DialogueRunnerOptions, type DialogueRunnerState, type EndNode, type LineNode, type TextRevealOptions, type TextRevealState, type VariableBag, completeTextReveal, createDialogueGraph, createDialogueRunner, createTextReveal, getNode, interpolate, resetTextReveal, updateTextReveal };
|
|
162
|
+
export declare function createTextReveal(text: string): TextRevealState;
|
|
163
|
+
export declare function updateTextReveal(state: TextRevealState, dt: number, options?: TextRevealOptions): void;
|
|
164
|
+
export declare function completeTextReveal(state: TextRevealState): void;
|
|
165
|
+
export declare function resetTextReveal(state: TextRevealState, newText?: string): void;
|
|
166
|
+
export type { ActionHandler, ActionNode, ActiveOption, BranchArm, BranchNode, ChoiceNode, ChoiceOption, ConditionResolver, DialogueChoiceEvent, DialogueErrorCode, DialogueGraph, DialogueLineEvent, DialogueNode, DialogueRunner, DialogueRunnerOptions, DialogueRunnerState, EndNode, LineNode, TextRevealOptions, TextRevealState, VariableBag };
|
|
173
167
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/graph.ts","../src/runner.ts","../src/text-reveal.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/graph.ts","../src/runner.ts","../src/text-reveal.ts"],"mappings":";;;;;;;;;;;;;UAeiB;WACN;;WAEA;;;;;;WAMA;;WAEA;;WAEA;;UAGM;;WAEN;;WAEA;;WAEA;;UAGM;WACN;;WAEA;;WAEA;WACA,kBAAkB;;UAGZ;;WAEN;;WAEA;;UAGM;WACN;WACA,eAAe;;WAEf;;UAGM;WACN;;WAEA;;WAEA;;UAGM;WACN;;KAGC,eAAe,WAAW,aAAa,aAAa,aAAa;UAI5D;;WAEN;;WAEA;;WAEA,OAAO,eAAe;;wBAGjB,oBACd,YACA,eACA,OAAO,eAAe,gBACrB;wBAIa,QAAQ,OAAO,eAAe,iBAAiB;KCrFnD;qBAEC,sBAAsB;WACxB,MAAM;;WAEN;;WAEA;;WAEA;EAGP,YAAA,MAAM,mBACN,iBACA;IAAU;IAAgB;IAAoB;;;KAatC,qBAAqB;KACrB,iBAAiB,uBAAuB;KACxC,cAAc;UAET;WACN;;WAEA;WACA;WACA;;UAGM;WACN;WACA;WACA,kBAAkB;WAClB;;UAGM;WACN;WACA;WACA;;KAGC;wBAII,YAAY,kBAAkB,MAAM;UASnC;WACN,QAAQ,OAAO;WACf,UAAU,OAAO;WACjB,UAAU;WACV,OAAO;WAEP,OAAO;WACP;WACA;EAET,MAAM,OAAO,eAAe,YAAY;EACxC;EACA,aAAa;EACb;;UAGe;EACf,aAAa;EACb,UAAU;;;;;EAKV,WAAW,KAAK;;wBAKF,qBAAqB,UAAU,wBAAwB;;;;;;;;UC9FtD;;WAEN;;EAET;;EAEA;;EAEA;;UAGe;;EAEf;;EAEA;;wBAUc,iBAAiB,eAAe;wBAOhC,iBACd,OAAO,iBACP,YACA,UAAU;wBA8BI,mBAAmB,OAAO;wBAM1B,gBAAgB,OAAO,iBAAiB"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { Signal } from "@flare-engine/events";
|
|
2
|
-
//#region src/graph.d.ts
|
|
3
2
|
/**
|
|
4
3
|
* Dialogue graph data types.
|
|
5
4
|
*
|
|
@@ -74,12 +73,10 @@ interface DialogueGraph {
|
|
|
74
73
|
/** All nodes keyed by id. */
|
|
75
74
|
readonly nodes: Record<string, DialogueNode>;
|
|
76
75
|
}
|
|
77
|
-
declare function createDialogueGraph(id: string, start: string, nodes: Record<string, DialogueNode>): DialogueGraph;
|
|
78
|
-
declare function getNode(graph: DialogueGraph, nodeId: string): DialogueNode | undefined;
|
|
79
|
-
//#endregion
|
|
80
|
-
//#region src/runner.d.ts
|
|
76
|
+
export declare function createDialogueGraph(id: string, start: string, nodes: Record<string, DialogueNode>): DialogueGraph;
|
|
77
|
+
export declare function getNode(graph: DialogueGraph, nodeId: string): DialogueNode | undefined;
|
|
81
78
|
type DialogueErrorCode = 'missing-node' | 'cycle';
|
|
82
|
-
declare class DialogueError extends Error {
|
|
79
|
+
export declare class DialogueError extends Error {
|
|
83
80
|
readonly code: DialogueErrorCode;
|
|
84
81
|
/** Source node whose transition triggered the error (or the entry id when there is no source). */
|
|
85
82
|
readonly nodeId: string;
|
|
@@ -115,7 +112,7 @@ interface ActiveOption {
|
|
|
115
112
|
readonly next: string;
|
|
116
113
|
}
|
|
117
114
|
type DialogueRunnerState = 'idle' | 'running' | 'waiting-choice' | 'ended';
|
|
118
|
-
declare function interpolate(template: string, vars: VariableBag): string;
|
|
115
|
+
export declare function interpolate(template: string, vars: VariableBag): string;
|
|
119
116
|
interface DialogueRunner {
|
|
120
117
|
readonly onLine: Signal<DialogueLineEvent>;
|
|
121
118
|
readonly onChoice: Signal<DialogueChoiceEvent>;
|
|
@@ -138,9 +135,7 @@ interface DialogueRunnerOptions {
|
|
|
138
135
|
*/
|
|
139
136
|
onError?: (err: DialogueError) => void;
|
|
140
137
|
}
|
|
141
|
-
declare function createDialogueRunner(options?: DialogueRunnerOptions): DialogueRunner;
|
|
142
|
-
//#endregion
|
|
143
|
-
//#region src/text-reveal.d.ts
|
|
138
|
+
export declare function createDialogueRunner(options?: DialogueRunnerOptions): DialogueRunner;
|
|
144
139
|
/**
|
|
145
140
|
* Text-over-time reveal hook for dialogue lines.
|
|
146
141
|
*
|
|
@@ -164,10 +159,9 @@ interface TextRevealOptions {
|
|
|
164
159
|
/** Extra delay (in seconds) after punctuation (.!?). Default: 0.15. */
|
|
165
160
|
punctuationDelay?: number;
|
|
166
161
|
}
|
|
167
|
-
declare function createTextReveal(text: string): TextRevealState;
|
|
168
|
-
declare function updateTextReveal(state: TextRevealState, dt: number, options?: TextRevealOptions): void;
|
|
169
|
-
declare function completeTextReveal(state: TextRevealState): void;
|
|
170
|
-
declare function resetTextReveal(state: TextRevealState, newText?: string): void;
|
|
171
|
-
|
|
172
|
-
export { type ActionHandler, type ActionNode, type ActiveOption, type BranchArm, type BranchNode, type ChoiceNode, type ChoiceOption, type ConditionResolver, type DialogueChoiceEvent, DialogueError, type DialogueErrorCode, type DialogueGraph, type DialogueLineEvent, type DialogueNode, type DialogueRunner, type DialogueRunnerOptions, type DialogueRunnerState, type EndNode, type LineNode, type TextRevealOptions, type TextRevealState, type VariableBag, completeTextReveal, createDialogueGraph, createDialogueRunner, createTextReveal, getNode, interpolate, resetTextReveal, updateTextReveal };
|
|
162
|
+
export declare function createTextReveal(text: string): TextRevealState;
|
|
163
|
+
export declare function updateTextReveal(state: TextRevealState, dt: number, options?: TextRevealOptions): void;
|
|
164
|
+
export declare function completeTextReveal(state: TextRevealState): void;
|
|
165
|
+
export declare function resetTextReveal(state: TextRevealState, newText?: string): void;
|
|
166
|
+
export type { ActionHandler, ActionNode, ActiveOption, BranchArm, BranchNode, ChoiceNode, ChoiceOption, ConditionResolver, DialogueChoiceEvent, DialogueErrorCode, DialogueGraph, DialogueLineEvent, DialogueNode, DialogueRunner, DialogueRunnerOptions, DialogueRunnerState, EndNode, LineNode, TextRevealOptions, TextRevealState, VariableBag };
|
|
173
167
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/graph.ts","../src/runner.ts","../src/text-reveal.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/graph.ts","../src/runner.ts","../src/text-reveal.ts"],"mappings":";;;;;;;;;;;;;UAeiB;WACN;;WAEA;;;;;;WAMA;;WAEA;;WAEA;;UAGM;;WAEN;;WAEA;;WAEA;;UAGM;WACN;;WAEA;;WAEA;WACA,kBAAkB;;UAGZ;;WAEN;;WAEA;;UAGM;WACN;WACA,eAAe;;WAEf;;UAGM;WACN;;WAEA;;WAEA;;UAGM;WACN;;KAGC,eAAe,WAAW,aAAa,aAAa,aAAa;UAI5D;;WAEN;;WAEA;;WAEA,OAAO,eAAe;;wBAGjB,oBACd,YACA,eACA,OAAO,eAAe,gBACrB;wBAIa,QAAQ,OAAO,eAAe,iBAAiB;KCrFnD;qBAEC,sBAAsB;WACxB,MAAM;;WAEN;;WAEA;;WAEA;EAGP,YAAA,MAAM,mBACN,iBACA;IAAU;IAAgB;IAAoB;;;KAatC,qBAAqB;KACrB,iBAAiB,uBAAuB;KACxC,cAAc;UAET;WACN;;WAEA;WACA;WACA;;UAGM;WACN;WACA;WACA,kBAAkB;WAClB;;UAGM;WACN;WACA;WACA;;KAGC;wBAII,YAAY,kBAAkB,MAAM;UASnC;WACN,QAAQ,OAAO;WACf,UAAU,OAAO;WACjB,UAAU;WACV,OAAO;WAEP,OAAO;WACP;WACA;EAET,MAAM,OAAO,eAAe,YAAY;EACxC;EACA,aAAa;EACb;;UAGe;EACf,aAAa;EACb,UAAU;;;;;EAKV,WAAW,KAAK;;wBAKF,qBAAqB,UAAU,wBAAwB;;;;;;;;UC9FtD;;WAEN;;EAET;;EAEA;;EAEA;;UAGe;;EAEf;;EAEA;;wBAUc,iBAAiB,eAAe;wBAOhC,iBACd,OAAO,iBACP,YACA,UAAU;wBA8BI,mBAAmB,OAAO;wBAM1B,gBAAgB,OAAO,iBAAiB"}
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
let _flare_engine_events = require("@flare-engine/events");
|
|
3
|
-
|
|
3
|
+
// src/graph.ts
|
|
4
4
|
function createDialogueGraph(id, start, nodes) {
|
|
5
5
|
return {
|
|
6
6
|
id,
|
|
@@ -11,8 +11,7 @@ function createDialogueGraph(id, start, nodes) {
|
|
|
11
11
|
function getNode(graph, nodeId) {
|
|
12
12
|
return Object.hasOwn(graph.nodes, nodeId) ? graph.nodes[nodeId] : void 0;
|
|
13
13
|
}
|
|
14
|
-
|
|
15
|
-
//#region src/runner.ts
|
|
14
|
+
// src/runner.ts
|
|
16
15
|
/**
|
|
17
16
|
* Dialogue runner — walks a DialogueGraph, evaluating conditions,
|
|
18
17
|
* interpolating variables, and emitting signals for each step.
|
|
@@ -198,8 +197,7 @@ function createDialogueRunner(options) {
|
|
|
198
197
|
}
|
|
199
198
|
};
|
|
200
199
|
}
|
|
201
|
-
|
|
202
|
-
//#region src/text-reveal.ts
|
|
200
|
+
// src/text-reveal.ts
|
|
203
201
|
const DEFAULT_SPEED = 30;
|
|
204
202
|
const DEFAULT_PUNCT_DELAY = .15;
|
|
205
203
|
const PUNCTUATION = /* @__PURE__ */ new Set([
|
|
@@ -254,7 +252,6 @@ function resetTextReveal(state, newText) {
|
|
|
254
252
|
state._cursor = 0;
|
|
255
253
|
state.complete = text.length === 0;
|
|
256
254
|
}
|
|
257
|
-
//#endregion
|
|
258
255
|
exports.DialogueError = DialogueError;
|
|
259
256
|
exports.completeTextReveal = completeTextReveal;
|
|
260
257
|
exports.createDialogueGraph = createDialogueGraph;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["Signal"],"sources":["../src/graph.ts","../src/runner.ts","../src/text-reveal.ts"],"sourcesContent":["/**\n * Dialogue graph data types.\n *\n * A dialogue graph is a directed graph of nodes. Each node is one of:\n * - `line`: NPC/character speaks. Optional `next` pointer.\n * - `choice`: Player picks from options. Each option points to a node.\n * - `branch`: Condition-based routing. First truthy condition wins.\n * - `action`: Fires a callback, then advances to `next`.\n * - `end`: Terminal node. Conversation stops.\n *\n * Graphs are plain JSON — no classes, no runtime coupling.\n */\n\n// ─── Node types ──────────────────────────────────────────────────\n\nexport interface LineNode {\n readonly kind: 'line';\n /** Speaker name / id. */\n readonly speaker: string;\n /**\n * Optional portrait key resolved by the UI layer to an avatar image /\n * shape / atlas frame. The dialogue runtime is portrait-agnostic — it\n * forwards the key via `DialogueLineEvent.speakerPortraitKey`.\n */\n readonly speakerPortraitKey?: string;\n /** Text template. Supports `{var}` interpolation via the runner's variable bag. */\n readonly text: string;\n /** Next node id, or null to end. */\n readonly next: string | null;\n}\n\nexport interface ChoiceOption {\n /** Display text. Supports `{var}` interpolation. */\n readonly text: string;\n /** Node id to jump to when selected. */\n readonly next: string;\n /** Optional condition key — option is hidden when condition returns false. */\n readonly condition?: string;\n}\n\nexport interface ChoiceNode {\n readonly kind: 'choice';\n /** Optional prompt text before the choices. */\n readonly prompt?: string;\n /** Speaker for the prompt, if any. */\n readonly speaker?: string;\n readonly options: readonly ChoiceOption[];\n}\n\nexport interface BranchArm {\n /** Condition key evaluated by the runner's condition resolver. */\n readonly condition: string;\n /** Node id to jump to when condition is true. */\n readonly next: string;\n}\n\nexport interface BranchNode {\n readonly kind: 'branch';\n readonly arms: readonly BranchArm[];\n /** Fallback node id if no arm matches. Null → end. */\n readonly fallback: string | null;\n}\n\nexport interface ActionNode {\n readonly kind: 'action';\n /** Callback key. Runner looks this up in the action registry. */\n readonly action: string;\n /** Next node id after the action fires. */\n readonly next: string | null;\n}\n\nexport interface EndNode {\n readonly kind: 'end';\n}\n\nexport type DialogueNode = LineNode | ChoiceNode | BranchNode | ActionNode | EndNode;\n\n// ─── Graph ───────────────────────────────────────────────────────\n\nexport interface DialogueGraph {\n /** Unique graph identifier. */\n readonly id: string;\n /** Node id to start from. */\n readonly start: string;\n /** All nodes keyed by id. */\n readonly nodes: Record<string, DialogueNode>;\n}\n\nexport function createDialogueGraph(\n id: string,\n start: string,\n nodes: Record<string, DialogueNode>,\n): DialogueGraph {\n return { id, start, nodes };\n}\n\nexport function getNode(graph: DialogueGraph, nodeId: string): DialogueNode | undefined {\n return Object.hasOwn(graph.nodes, nodeId) ? graph.nodes[nodeId] : undefined;\n}\n","/**\n * Dialogue runner — walks a DialogueGraph, evaluating conditions,\n * interpolating variables, and emitting signals for each step.\n */\n\nimport { Signal } from '@flare-engine/events';\nimport type { ChoiceNode, DialogueGraph, LineNode } from './graph.js';\nimport { getNode } from './graph.js';\n\n// ─── Error ───────────────────────────────────────────────────────\n\nexport type DialogueErrorCode = 'missing-node' | 'cycle';\n\nexport class DialogueError extends Error {\n readonly code: DialogueErrorCode;\n /** Source node whose transition triggered the error (or the entry id when there is no source). */\n readonly nodeId: string;\n /** 'missing-node': the target id that could not be resolved. */\n readonly missingId?: string;\n /** 'cycle': the node-id chain walked before the step budget was exceeded. */\n readonly chain?: readonly string[];\n\n constructor(\n code: DialogueErrorCode,\n message: string,\n detail: { nodeId: string; missingId?: string; chain?: readonly string[] },\n ) {\n super(message);\n this.name = 'DialogueError';\n this.code = code;\n this.nodeId = detail.nodeId;\n this.missingId = detail.missingId;\n this.chain = detail.chain;\n }\n}\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport type ConditionResolver = (key: string) => boolean;\nexport type ActionHandler = (key: string) => void | Promise<void>;\nexport type VariableBag = Record<string, string | number>;\n\nexport interface DialogueLineEvent {\n readonly speaker: string;\n /** Optional portrait key forwarded verbatim from the source LineNode. */\n readonly speakerPortraitKey?: string;\n readonly text: string;\n readonly nodeId: string;\n}\n\nexport interface DialogueChoiceEvent {\n readonly prompt: string | undefined;\n readonly speaker: string | undefined;\n readonly options: readonly ActiveOption[];\n readonly nodeId: string;\n}\n\nexport interface ActiveOption {\n readonly index: number;\n readonly text: string;\n readonly next: string;\n}\n\nexport type DialogueRunnerState = 'idle' | 'running' | 'waiting-choice' | 'ended';\n\n// ─── Interpolation ───────────────────────────────────────────────\n\nexport function interpolate(template: string, vars: VariableBag): string {\n return template.replace(/\\{(\\w+)\\}/g, (_match, key: string) => {\n const val = Object.hasOwn(vars, key) ? vars[key] : undefined;\n return val !== undefined ? String(val) : `{${key}}`;\n });\n}\n\n// ─── Runner ──────────────────────────────────────────────────────\n\nexport interface DialogueRunner {\n readonly onLine: Signal<DialogueLineEvent>;\n readonly onChoice: Signal<DialogueChoiceEvent>;\n readonly onAction: Signal<string>;\n readonly onEnd: Signal<string>;\n\n readonly state: DialogueRunnerState;\n readonly currentNodeId: string | null;\n readonly graphId: string | null;\n\n start(graph: DialogueGraph, variables?: VariableBag): void;\n advance(): void;\n selectChoice(index: number): void;\n stop(): void;\n}\n\nexport interface DialogueRunnerOptions {\n conditions?: ConditionResolver;\n actions?: ActionHandler;\n /**\n * Invoked on a recoverable dialogue error — currently a transition to a\n * missing node. Default (no hook): logs a console.warn, then ends.\n */\n onError?: (err: DialogueError) => void;\n}\n\nconst STEP_BUDGET = 1000;\n\nexport function createDialogueRunner(options?: DialogueRunnerOptions): DialogueRunner {\n const onLine = new Signal<DialogueLineEvent>();\n const onChoice = new Signal<DialogueChoiceEvent>();\n const onAction = new Signal<string>();\n const onEnd = new Signal<string>();\n\n const conditions = options?.conditions ?? (() => true);\n const actions = options?.actions;\n const onError = options?.onError;\n\n let _state: DialogueRunnerState = 'idle';\n let _graph: DialogueGraph | null = null;\n let _currentNodeId: string | null = null;\n let _vars: VariableBag = {};\n let _activeOptions: ActiveOption[] = [];\n\n function setState(s: DialogueRunnerState): void {\n _state = s;\n }\n\n function end(): void {\n setState('ended');\n const graphId = _graph?.id ?? '';\n _currentNodeId = null;\n onEnd.emit(graphId);\n }\n\n function reportMissing(fromNodeId: string | null, missingId: string): void {\n const graphId = _graph?.id ?? '';\n const from = fromNodeId ? ` from node '${fromNodeId}'` : ' as its start node';\n const err = new DialogueError(\n 'missing-node',\n `Dialogue '${graphId}' references missing node '${missingId}'${from} — ending conversation.`,\n { nodeId: fromNodeId ?? missingId, missingId },\n );\n if (onError) onError(err);\n else console.warn(err.message);\n }\n\n function processLine(node: LineNode, nodeId: string): void {\n setState('running');\n const text = interpolate(node.text, _vars);\n onLine.emit({\n speaker: node.speaker,\n speakerPortraitKey: node.speakerPortraitKey,\n text,\n nodeId,\n });\n }\n\n function processChoice(node: ChoiceNode, nodeId: string): void {\n _activeOptions = [];\n for (let i = 0; i < node.options.length; i++) {\n const opt = node.options[i]!;\n if (opt.condition && !conditions(opt.condition)) continue;\n _activeOptions.push({\n index: _activeOptions.length,\n text: interpolate(opt.text, _vars),\n next: opt.next,\n });\n }\n\n if (_activeOptions.length === 0) {\n end();\n return;\n }\n\n setState('waiting-choice');\n onChoice.emit({\n prompt: node.prompt ? interpolate(node.prompt, _vars) : undefined,\n speaker: node.speaker,\n options: _activeOptions,\n nodeId,\n });\n }\n\n function run(entryId: string, fromNodeId: string | null): void {\n if (!_graph) return;\n\n let currentId: string | null = entryId;\n let from: string | null = fromNodeId;\n const chain: string[] = [];\n let steps = 0;\n\n while (currentId !== null) {\n const nodeId = currentId;\n const node = getNode(_graph, nodeId);\n\n if (!node) {\n reportMissing(from, nodeId);\n end();\n return;\n }\n\n chain.push(nodeId);\n if (++steps > STEP_BUDGET) {\n throw new DialogueError(\n 'cycle',\n `Dialogue '${_graph.id}' cycle detected — step budget exceeded (chain: …${chain.slice(-12).join('→')})`,\n { nodeId, chain: chain.slice() },\n );\n }\n\n _currentNodeId = nodeId;\n from = nodeId;\n\n switch (node.kind) {\n case 'line':\n processLine(node, nodeId);\n return;\n case 'choice':\n processChoice(node, nodeId);\n return;\n case 'branch': {\n let next: string | null = node.fallback;\n for (const arm of node.arms) {\n if (conditions(arm.condition)) {\n next = arm.next;\n break;\n }\n }\n currentId = next;\n break;\n }\n case 'action':\n onAction.emit(node.action);\n actions?.(node.action);\n currentId = node.next;\n break;\n case 'end':\n end();\n return;\n }\n }\n\n end();\n }\n\n const runner: DialogueRunner = {\n onLine,\n onChoice,\n onAction,\n onEnd,\n\n get state() {\n return _state;\n },\n get currentNodeId() {\n return _currentNodeId;\n },\n get graphId() {\n return _graph?.id ?? null;\n },\n\n start(graph: DialogueGraph, variables?: VariableBag): void {\n _graph = graph;\n _vars = variables ?? {};\n _activeOptions = [];\n setState('running');\n run(graph.start, null);\n },\n\n advance(): void {\n if (_state !== 'running' || !_graph || !_currentNodeId) return;\n const node = getNode(_graph, _currentNodeId);\n if (node?.kind !== 'line') return;\n if (node.next) {\n run(node.next, _currentNodeId);\n } else {\n end();\n }\n },\n\n selectChoice(index: number): void {\n if (_state !== 'waiting-choice') return;\n const opt = _activeOptions[index];\n if (!opt) return;\n _activeOptions = [];\n setState('running');\n run(opt.next, _currentNodeId);\n },\n\n stop(): void {\n setState('idle');\n _graph = null;\n _currentNodeId = null;\n _vars = {};\n _activeOptions = [];\n },\n };\n\n return runner;\n}\n","/**\n * Text-over-time reveal hook for dialogue lines.\n *\n * Drives a typewriter effect: call `updateTextReveal(state, dt)` each frame\n * and read `state.visibleText` for the currently revealed substring.\n * Supports per-character speed, instant-complete, and pause-on-punctuation.\n */\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport interface TextRevealState {\n /** Full text being revealed. */\n readonly fullText: string;\n /** Characters revealed so far. */\n visibleText: string;\n /** Whether the full text has been revealed. */\n complete: boolean;\n /** Internal fractional character cursor. */\n _cursor: number;\n}\n\nexport interface TextRevealOptions {\n /** Characters per second. Default: 30. */\n speed?: number;\n /** Extra delay (in seconds) after punctuation (.!?). Default: 0.15. */\n punctuationDelay?: number;\n}\n\nconst DEFAULT_SPEED = 30;\nconst DEFAULT_PUNCT_DELAY = 0.15;\n\nconst PUNCTUATION = new Set(['.', '!', '?', ':', ';']);\n\n// ─── API ─────────────────────────────────────────────────────────\n\nexport function createTextReveal(text: string): TextRevealState {\n if (text.length === 0) {\n return { fullText: text, visibleText: text, complete: true, _cursor: 0 };\n }\n return { fullText: text, visibleText: '', complete: false, _cursor: 0 };\n}\n\nexport function updateTextReveal(\n state: TextRevealState,\n dt: number,\n options?: TextRevealOptions,\n): void {\n if (state.complete) return;\n\n const speed = options?.speed ?? DEFAULT_SPEED;\n const punctDelay = options?.punctuationDelay ?? DEFAULT_PUNCT_DELAY;\n const len = state.fullText.length;\n\n // Determine effective speed — slow down after punctuation\n const prevCharIdx = Math.floor(state._cursor) - 1;\n let effectiveSpeed = speed;\n if (prevCharIdx >= 0 && prevCharIdx < len) {\n const prevChar = state.fullText[prevCharIdx]!;\n if (PUNCTUATION.has(prevChar)) {\n // Slow down: treat the punctuation gap as taking `punctDelay` seconds\n // Effective speed = 1 / punctDelay so cursor advances ~1 char in punctDelay time\n effectiveSpeed = punctDelay > 0 ? 1 / punctDelay : speed;\n }\n }\n\n state._cursor += effectiveSpeed * dt;\n const charCount = Math.min(Math.floor(state._cursor), len);\n state.visibleText = state.fullText.slice(0, charCount);\n\n if (charCount >= len) {\n state.visibleText = state.fullText;\n state.complete = true;\n }\n}\n\nexport function completeTextReveal(state: TextRevealState): void {\n state.visibleText = state.fullText;\n state._cursor = state.fullText.length;\n state.complete = true;\n}\n\nexport function resetTextReveal(state: TextRevealState, newText?: string): void {\n const text = newText ?? state.fullText;\n (state as { fullText: string }).fullText = text;\n state.visibleText = '';\n state._cursor = 0;\n state.complete = text.length === 0;\n}\n"],"mappings":";;;AAwFA,SAAgB,oBACd,IACA,OACA,OACe;CACf,OAAO;EAAE;EAAI;EAAO;CAAM;AAC5B;AAEA,SAAgB,QAAQ,OAAsB,QAA0C;CACtF,OAAO,OAAO,OAAO,MAAM,OAAO,MAAM,IAAI,MAAM,MAAM,UAAU,KAAA;AACpE;;;;;;;ACrFA,IAAa,gBAAb,cAAmC,MAAM;CACvC;;CAEA;;CAEA;;CAEA;CAEA,YACE,MACA,SACA,QACA;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,SAAS,OAAO;EACrB,KAAK,YAAY,OAAO;EACxB,KAAK,QAAQ,OAAO;CACtB;AACF;AAiCA,SAAgB,YAAY,UAAkB,MAA2B;CACvE,OAAO,SAAS,QAAQ,eAAe,QAAQ,QAAgB;EAC7D,MAAM,MAAM,OAAO,OAAO,MAAM,GAAG,IAAI,KAAK,OAAO,KAAA;EACnD,OAAO,QAAQ,KAAA,IAAY,OAAO,GAAG,IAAI,IAAI,IAAI;CACnD,CAAC;AACH;AA8BA,MAAM,cAAc;AAEpB,SAAgB,qBAAqB,SAAiD;CACpF,MAAM,SAAS,IAAIA,qBAAAA,OAA0B;CAC7C,MAAM,WAAW,IAAIA,qBAAAA,OAA4B;CACjD,MAAM,WAAW,IAAIA,qBAAAA,OAAe;CACpC,MAAM,QAAQ,IAAIA,qBAAAA,OAAe;CAEjC,MAAM,aAAa,SAAS,qBAAqB;CACjD,MAAM,UAAU,SAAS;CACzB,MAAM,UAAU,SAAS;CAEzB,IAAI,SAA8B;CAClC,IAAI,SAA+B;CACnC,IAAI,iBAAgC;CACpC,IAAI,QAAqB,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M,cAAc,MAAM;EAC1B,MAAM,WAAW;CACnB;AACF;AAEA,SAAgB,mBAAmB,OAA8B;CAC/D,MAAM,cAAc,MAAM;CAC1B,MAAM,UAAU,MAAM,SAAS;CAC/B,MAAM,WAAW;AACnB;AAEA,SAAgB,gBAAgB,OAAwB,SAAwB;CAC9E,MAAM,OAAO,WAAW,MAAM;CAC9B,MAAgC,WAAW;CAC3C,MAAM,cAAc;CACpB,MAAM,UAAU;CAChB,MAAM,WAAW,KAAK,WAAW;AACnC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["Signal"],"sources":["../src/graph.ts","../src/runner.ts","../src/text-reveal.ts"],"sourcesContent":["/**\n * Dialogue graph data types.\n *\n * A dialogue graph is a directed graph of nodes. Each node is one of:\n * - `line`: NPC/character speaks. Optional `next` pointer.\n * - `choice`: Player picks from options. Each option points to a node.\n * - `branch`: Condition-based routing. First truthy condition wins.\n * - `action`: Fires a callback, then advances to `next`.\n * - `end`: Terminal node. Conversation stops.\n *\n * Graphs are plain JSON — no classes, no runtime coupling.\n */\n\n// ─── Node types ──────────────────────────────────────────────────\n\nexport interface LineNode {\n readonly kind: 'line';\n /** Speaker name / id. */\n readonly speaker: string;\n /**\n * Optional portrait key resolved by the UI layer to an avatar image /\n * shape / atlas frame. The dialogue runtime is portrait-agnostic — it\n * forwards the key via `DialogueLineEvent.speakerPortraitKey`.\n */\n readonly speakerPortraitKey?: string;\n /** Text template. Supports `{var}` interpolation via the runner's variable bag. */\n readonly text: string;\n /** Next node id, or null to end. */\n readonly next: string | null;\n}\n\nexport interface ChoiceOption {\n /** Display text. Supports `{var}` interpolation. */\n readonly text: string;\n /** Node id to jump to when selected. */\n readonly next: string;\n /** Optional condition key — option is hidden when condition returns false. */\n readonly condition?: string;\n}\n\nexport interface ChoiceNode {\n readonly kind: 'choice';\n /** Optional prompt text before the choices. */\n readonly prompt?: string;\n /** Speaker for the prompt, if any. */\n readonly speaker?: string;\n readonly options: readonly ChoiceOption[];\n}\n\nexport interface BranchArm {\n /** Condition key evaluated by the runner's condition resolver. */\n readonly condition: string;\n /** Node id to jump to when condition is true. */\n readonly next: string;\n}\n\nexport interface BranchNode {\n readonly kind: 'branch';\n readonly arms: readonly BranchArm[];\n /** Fallback node id if no arm matches. Null → end. */\n readonly fallback: string | null;\n}\n\nexport interface ActionNode {\n readonly kind: 'action';\n /** Callback key. Runner looks this up in the action registry. */\n readonly action: string;\n /** Next node id after the action fires. */\n readonly next: string | null;\n}\n\nexport interface EndNode {\n readonly kind: 'end';\n}\n\nexport type DialogueNode = LineNode | ChoiceNode | BranchNode | ActionNode | EndNode;\n\n// ─── Graph ───────────────────────────────────────────────────────\n\nexport interface DialogueGraph {\n /** Unique graph identifier. */\n readonly id: string;\n /** Node id to start from. */\n readonly start: string;\n /** All nodes keyed by id. */\n readonly nodes: Record<string, DialogueNode>;\n}\n\nexport function createDialogueGraph(\n id: string,\n start: string,\n nodes: Record<string, DialogueNode>,\n): DialogueGraph {\n return { id, start, nodes };\n}\n\nexport function getNode(graph: DialogueGraph, nodeId: string): DialogueNode | undefined {\n return Object.hasOwn(graph.nodes, nodeId) ? graph.nodes[nodeId] : undefined;\n}\n","/**\n * Dialogue runner — walks a DialogueGraph, evaluating conditions,\n * interpolating variables, and emitting signals for each step.\n */\n\nimport { Signal } from '@flare-engine/events';\nimport type { ChoiceNode, DialogueGraph, LineNode } from './graph.js';\nimport { getNode } from './graph.js';\n\n// ─── Error ───────────────────────────────────────────────────────\n\nexport type DialogueErrorCode = 'missing-node' | 'cycle';\n\nexport class DialogueError extends Error {\n readonly code: DialogueErrorCode;\n /** Source node whose transition triggered the error (or the entry id when there is no source). */\n readonly nodeId: string;\n /** 'missing-node': the target id that could not be resolved. */\n readonly missingId?: string;\n /** 'cycle': the node-id chain walked before the step budget was exceeded. */\n readonly chain?: readonly string[];\n\n constructor(\n code: DialogueErrorCode,\n message: string,\n detail: { nodeId: string; missingId?: string; chain?: readonly string[] },\n ) {\n super(message);\n this.name = 'DialogueError';\n this.code = code;\n this.nodeId = detail.nodeId;\n this.missingId = detail.missingId;\n this.chain = detail.chain;\n }\n}\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport type ConditionResolver = (key: string) => boolean;\nexport type ActionHandler = (key: string) => void | Promise<void>;\nexport type VariableBag = Record<string, string | number>;\n\nexport interface DialogueLineEvent {\n readonly speaker: string;\n /** Optional portrait key forwarded verbatim from the source LineNode. */\n readonly speakerPortraitKey?: string;\n readonly text: string;\n readonly nodeId: string;\n}\n\nexport interface DialogueChoiceEvent {\n readonly prompt: string | undefined;\n readonly speaker: string | undefined;\n readonly options: readonly ActiveOption[];\n readonly nodeId: string;\n}\n\nexport interface ActiveOption {\n readonly index: number;\n readonly text: string;\n readonly next: string;\n}\n\nexport type DialogueRunnerState = 'idle' | 'running' | 'waiting-choice' | 'ended';\n\n// ─── Interpolation ───────────────────────────────────────────────\n\nexport function interpolate(template: string, vars: VariableBag): string {\n return template.replace(/\\{(\\w+)\\}/g, (_match, key: string) => {\n const val = Object.hasOwn(vars, key) ? vars[key] : undefined;\n return val !== undefined ? String(val) : `{${key}}`;\n });\n}\n\n// ─── Runner ──────────────────────────────────────────────────────\n\nexport interface DialogueRunner {\n readonly onLine: Signal<DialogueLineEvent>;\n readonly onChoice: Signal<DialogueChoiceEvent>;\n readonly onAction: Signal<string>;\n readonly onEnd: Signal<string>;\n\n readonly state: DialogueRunnerState;\n readonly currentNodeId: string | null;\n readonly graphId: string | null;\n\n start(graph: DialogueGraph, variables?: VariableBag): void;\n advance(): void;\n selectChoice(index: number): void;\n stop(): void;\n}\n\nexport interface DialogueRunnerOptions {\n conditions?: ConditionResolver;\n actions?: ActionHandler;\n /**\n * Invoked on a recoverable dialogue error — currently a transition to a\n * missing node. Default (no hook): logs a console.warn, then ends.\n */\n onError?: (err: DialogueError) => void;\n}\n\nconst STEP_BUDGET = 1000;\n\nexport function createDialogueRunner(options?: DialogueRunnerOptions): DialogueRunner {\n const onLine = new Signal<DialogueLineEvent>();\n const onChoice = new Signal<DialogueChoiceEvent>();\n const onAction = new Signal<string>();\n const onEnd = new Signal<string>();\n\n const conditions = options?.conditions ?? (() => true);\n const actions = options?.actions;\n const onError = options?.onError;\n\n let _state: DialogueRunnerState = 'idle';\n let _graph: DialogueGraph | null = null;\n let _currentNodeId: string | null = null;\n let _vars: VariableBag = {};\n let _activeOptions: ActiveOption[] = [];\n\n function setState(s: DialogueRunnerState): void {\n _state = s;\n }\n\n function end(): void {\n setState('ended');\n const graphId = _graph?.id ?? '';\n _currentNodeId = null;\n onEnd.emit(graphId);\n }\n\n function reportMissing(fromNodeId: string | null, missingId: string): void {\n const graphId = _graph?.id ?? '';\n const from = fromNodeId ? ` from node '${fromNodeId}'` : ' as its start node';\n const err = new DialogueError(\n 'missing-node',\n `Dialogue '${graphId}' references missing node '${missingId}'${from} — ending conversation.`,\n { nodeId: fromNodeId ?? missingId, missingId },\n );\n if (onError) onError(err);\n else console.warn(err.message);\n }\n\n function processLine(node: LineNode, nodeId: string): void {\n setState('running');\n const text = interpolate(node.text, _vars);\n onLine.emit({\n speaker: node.speaker,\n speakerPortraitKey: node.speakerPortraitKey,\n text,\n nodeId,\n });\n }\n\n function processChoice(node: ChoiceNode, nodeId: string): void {\n _activeOptions = [];\n for (let i = 0; i < node.options.length; i++) {\n const opt = node.options[i]!;\n if (opt.condition && !conditions(opt.condition)) continue;\n _activeOptions.push({\n index: _activeOptions.length,\n text: interpolate(opt.text, _vars),\n next: opt.next,\n });\n }\n\n if (_activeOptions.length === 0) {\n end();\n return;\n }\n\n setState('waiting-choice');\n onChoice.emit({\n prompt: node.prompt ? interpolate(node.prompt, _vars) : undefined,\n speaker: node.speaker,\n options: _activeOptions,\n nodeId,\n });\n }\n\n function run(entryId: string, fromNodeId: string | null): void {\n if (!_graph) return;\n\n let currentId: string | null = entryId;\n let from: string | null = fromNodeId;\n const chain: string[] = [];\n let steps = 0;\n\n while (currentId !== null) {\n const nodeId = currentId;\n const node = getNode(_graph, nodeId);\n\n if (!node) {\n reportMissing(from, nodeId);\n end();\n return;\n }\n\n chain.push(nodeId);\n if (++steps > STEP_BUDGET) {\n throw new DialogueError(\n 'cycle',\n `Dialogue '${_graph.id}' cycle detected — step budget exceeded (chain: …${chain.slice(-12).join('→')})`,\n { nodeId, chain: chain.slice() },\n );\n }\n\n _currentNodeId = nodeId;\n from = nodeId;\n\n switch (node.kind) {\n case 'line':\n processLine(node, nodeId);\n return;\n case 'choice':\n processChoice(node, nodeId);\n return;\n case 'branch': {\n let next: string | null = node.fallback;\n for (const arm of node.arms) {\n if (conditions(arm.condition)) {\n next = arm.next;\n break;\n }\n }\n currentId = next;\n break;\n }\n case 'action':\n onAction.emit(node.action);\n actions?.(node.action);\n currentId = node.next;\n break;\n case 'end':\n end();\n return;\n }\n }\n\n end();\n }\n\n const runner: DialogueRunner = {\n onLine,\n onChoice,\n onAction,\n onEnd,\n\n get state() {\n return _state;\n },\n get currentNodeId() {\n return _currentNodeId;\n },\n get graphId() {\n return _graph?.id ?? null;\n },\n\n start(graph: DialogueGraph, variables?: VariableBag): void {\n _graph = graph;\n _vars = variables ?? {};\n _activeOptions = [];\n setState('running');\n run(graph.start, null);\n },\n\n advance(): void {\n if (_state !== 'running' || !_graph || !_currentNodeId) return;\n const node = getNode(_graph, _currentNodeId);\n if (node?.kind !== 'line') return;\n if (node.next) {\n run(node.next, _currentNodeId);\n } else {\n end();\n }\n },\n\n selectChoice(index: number): void {\n if (_state !== 'waiting-choice') return;\n const opt = _activeOptions[index];\n if (!opt) return;\n _activeOptions = [];\n setState('running');\n run(opt.next, _currentNodeId);\n },\n\n stop(): void {\n setState('idle');\n _graph = null;\n _currentNodeId = null;\n _vars = {};\n _activeOptions = [];\n },\n };\n\n return runner;\n}\n","/**\n * Text-over-time reveal hook for dialogue lines.\n *\n * Drives a typewriter effect: call `updateTextReveal(state, dt)` each frame\n * and read `state.visibleText` for the currently revealed substring.\n * Supports per-character speed, instant-complete, and pause-on-punctuation.\n */\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport interface TextRevealState {\n /** Full text being revealed. */\n readonly fullText: string;\n /** Characters revealed so far. */\n visibleText: string;\n /** Whether the full text has been revealed. */\n complete: boolean;\n /** Internal fractional character cursor. */\n _cursor: number;\n}\n\nexport interface TextRevealOptions {\n /** Characters per second. Default: 30. */\n speed?: number;\n /** Extra delay (in seconds) after punctuation (.!?). Default: 0.15. */\n punctuationDelay?: number;\n}\n\nconst DEFAULT_SPEED = 30;\nconst DEFAULT_PUNCT_DELAY = 0.15;\n\nconst PUNCTUATION = new Set(['.', '!', '?', ':', ';']);\n\n// ─── API ─────────────────────────────────────────────────────────\n\nexport function createTextReveal(text: string): TextRevealState {\n if (text.length === 0) {\n return { fullText: text, visibleText: text, complete: true, _cursor: 0 };\n }\n return { fullText: text, visibleText: '', complete: false, _cursor: 0 };\n}\n\nexport function updateTextReveal(\n state: TextRevealState,\n dt: number,\n options?: TextRevealOptions,\n): void {\n if (state.complete) return;\n\n const speed = options?.speed ?? DEFAULT_SPEED;\n const punctDelay = options?.punctuationDelay ?? DEFAULT_PUNCT_DELAY;\n const len = state.fullText.length;\n\n // Determine effective speed — slow down after punctuation\n const prevCharIdx = Math.floor(state._cursor) - 1;\n let effectiveSpeed = speed;\n if (prevCharIdx >= 0 && prevCharIdx < len) {\n const prevChar = state.fullText[prevCharIdx]!;\n if (PUNCTUATION.has(prevChar)) {\n // Slow down: treat the punctuation gap as taking `punctDelay` seconds\n // Effective speed = 1 / punctDelay so cursor advances ~1 char in punctDelay time\n effectiveSpeed = punctDelay > 0 ? 1 / punctDelay : speed;\n }\n }\n\n state._cursor += effectiveSpeed * dt;\n const charCount = Math.min(Math.floor(state._cursor), len);\n state.visibleText = state.fullText.slice(0, charCount);\n\n if (charCount >= len) {\n state.visibleText = state.fullText;\n state.complete = true;\n }\n}\n\nexport function completeTextReveal(state: TextRevealState): void {\n state.visibleText = state.fullText;\n state._cursor = state.fullText.length;\n state.complete = true;\n}\n\nexport function resetTextReveal(state: TextRevealState, newText?: string): void {\n const text = newText ?? state.fullText;\n (state as { fullText: string }).fullText = text;\n state.visibleText = '';\n state._cursor = 0;\n state.complete = text.length === 0;\n}\n"],"mappings":";;;AAwFA,SAAgB,oBACd,IACA,OACA,OACe;CACf,OAAO;EAAE;EAAI;EAAO;CAAM;AAC5B;AAEA,SAAgB,QAAQ,OAAsB,QAA0C;CACtF,OAAO,OAAO,OAAO,MAAM,OAAO,MAAM,IAAI,MAAM,MAAM,UAAU,KAAA;AACpE;;;;;;ACrFA,IAAa,gBAAb,cAAmC,MAAM;CACvC;;CAEA;;CAEA;;CAEA;CAEA,YACE,MACA,SACA,QACA;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,SAAS,OAAO;EACrB,KAAK,YAAY,OAAO;EACxB,KAAK,QAAQ,OAAO;CACtB;AACF;AAiCA,SAAgB,YAAY,UAAkB,MAA2B;CACvE,OAAO,SAAS,QAAQ,eAAe,QAAQ,QAAgB;EAC7D,MAAM,MAAM,OAAO,OAAO,MAAM,GAAG,IAAI,KAAK,OAAO,KAAA;EACnD,OAAO,QAAQ,KAAA,IAAY,OAAO,GAAG,IAAI,IAAI,IAAI;CACnD,CAAC;AACH;AA8BA,MAAM,cAAc;AAEpB,SAAgB,qBAAqB,SAAiD;CACpF,MAAM,SAAS,IAAIA,qBAAAA,OAA0B;CAC7C,MAAM,WAAW,IAAIA,qBAAAA,OAA4B;CACjD,MAAM,WAAW,IAAIA,qBAAAA,OAAe;CACpC,MAAM,QAAQ,IAAIA,qBAAAA,OAAe;CAEjC,MAAM,aAAa,SAAS,qBAAqB;CACjD,MAAM,UAAU,SAAS;CACzB,MAAM,UAAU,SAAS;CAEzB,IAAI,SAA8B;CAClC,IAAI,SAA+B;CACnC,IAAI,iBAAgC;CACpC,IAAI,QAAqB,CAAC;CAC1B,IAAI,iBAAiC,CAAC;CAEtC,SAAS,SAAS,GAA8B;EAC9C,SAAS;CACX;CAEA,SAAS,MA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AAM;CAC1B,MAAM,UAAU,MAAM,SAAS;CAC/B,MAAM,WAAW;AACnB;AAEA,SAAgB,gBAAgB,OAAwB,SAAwB;CAC9E,MAAM,OAAO,WAAW,MAAM;CAC9B,MAAgC,WAAW;CAC3C,MAAM,cAAc;CACpB,MAAM,UAAU;CAChB,MAAM,WAAW,KAAK,WAAW;AACnC"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Signal } from "@flare-engine/events";
|
|
2
|
-
|
|
2
|
+
// src/graph.ts
|
|
3
3
|
function createDialogueGraph(id, start, nodes) {
|
|
4
4
|
return {
|
|
5
5
|
id,
|
|
@@ -10,8 +10,7 @@ function createDialogueGraph(id, start, nodes) {
|
|
|
10
10
|
function getNode(graph, nodeId) {
|
|
11
11
|
return Object.hasOwn(graph.nodes, nodeId) ? graph.nodes[nodeId] : void 0;
|
|
12
12
|
}
|
|
13
|
-
|
|
14
|
-
//#region src/runner.ts
|
|
13
|
+
// src/runner.ts
|
|
15
14
|
/**
|
|
16
15
|
* Dialogue runner — walks a DialogueGraph, evaluating conditions,
|
|
17
16
|
* interpolating variables, and emitting signals for each step.
|
|
@@ -197,8 +196,7 @@ function createDialogueRunner(options) {
|
|
|
197
196
|
}
|
|
198
197
|
};
|
|
199
198
|
}
|
|
200
|
-
|
|
201
|
-
//#region src/text-reveal.ts
|
|
199
|
+
// src/text-reveal.ts
|
|
202
200
|
const DEFAULT_SPEED = 30;
|
|
203
201
|
const DEFAULT_PUNCT_DELAY = .15;
|
|
204
202
|
const PUNCTUATION = /* @__PURE__ */ new Set([
|
|
@@ -253,7 +251,6 @@ function resetTextReveal(state, newText) {
|
|
|
253
251
|
state._cursor = 0;
|
|
254
252
|
state.complete = text.length === 0;
|
|
255
253
|
}
|
|
256
|
-
//#endregion
|
|
257
254
|
export { DialogueError, completeTextReveal, createDialogueGraph, createDialogueRunner, createTextReveal, getNode, interpolate, resetTextReveal, updateTextReveal };
|
|
258
255
|
|
|
259
256
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/graph.ts","../src/runner.ts","../src/text-reveal.ts"],"sourcesContent":["/**\n * Dialogue graph data types.\n *\n * A dialogue graph is a directed graph of nodes. Each node is one of:\n * - `line`: NPC/character speaks. Optional `next` pointer.\n * - `choice`: Player picks from options. Each option points to a node.\n * - `branch`: Condition-based routing. First truthy condition wins.\n * - `action`: Fires a callback, then advances to `next`.\n * - `end`: Terminal node. Conversation stops.\n *\n * Graphs are plain JSON — no classes, no runtime coupling.\n */\n\n// ─── Node types ──────────────────────────────────────────────────\n\nexport interface LineNode {\n readonly kind: 'line';\n /** Speaker name / id. */\n readonly speaker: string;\n /**\n * Optional portrait key resolved by the UI layer to an avatar image /\n * shape / atlas frame. The dialogue runtime is portrait-agnostic — it\n * forwards the key via `DialogueLineEvent.speakerPortraitKey`.\n */\n readonly speakerPortraitKey?: string;\n /** Text template. Supports `{var}` interpolation via the runner's variable bag. */\n readonly text: string;\n /** Next node id, or null to end. */\n readonly next: string | null;\n}\n\nexport interface ChoiceOption {\n /** Display text. Supports `{var}` interpolation. */\n readonly text: string;\n /** Node id to jump to when selected. */\n readonly next: string;\n /** Optional condition key — option is hidden when condition returns false. */\n readonly condition?: string;\n}\n\nexport interface ChoiceNode {\n readonly kind: 'choice';\n /** Optional prompt text before the choices. */\n readonly prompt?: string;\n /** Speaker for the prompt, if any. */\n readonly speaker?: string;\n readonly options: readonly ChoiceOption[];\n}\n\nexport interface BranchArm {\n /** Condition key evaluated by the runner's condition resolver. */\n readonly condition: string;\n /** Node id to jump to when condition is true. */\n readonly next: string;\n}\n\nexport interface BranchNode {\n readonly kind: 'branch';\n readonly arms: readonly BranchArm[];\n /** Fallback node id if no arm matches. Null → end. */\n readonly fallback: string | null;\n}\n\nexport interface ActionNode {\n readonly kind: 'action';\n /** Callback key. Runner looks this up in the action registry. */\n readonly action: string;\n /** Next node id after the action fires. */\n readonly next: string | null;\n}\n\nexport interface EndNode {\n readonly kind: 'end';\n}\n\nexport type DialogueNode = LineNode | ChoiceNode | BranchNode | ActionNode | EndNode;\n\n// ─── Graph ───────────────────────────────────────────────────────\n\nexport interface DialogueGraph {\n /** Unique graph identifier. */\n readonly id: string;\n /** Node id to start from. */\n readonly start: string;\n /** All nodes keyed by id. */\n readonly nodes: Record<string, DialogueNode>;\n}\n\nexport function createDialogueGraph(\n id: string,\n start: string,\n nodes: Record<string, DialogueNode>,\n): DialogueGraph {\n return { id, start, nodes };\n}\n\nexport function getNode(graph: DialogueGraph, nodeId: string): DialogueNode | undefined {\n return Object.hasOwn(graph.nodes, nodeId) ? graph.nodes[nodeId] : undefined;\n}\n","/**\n * Dialogue runner — walks a DialogueGraph, evaluating conditions,\n * interpolating variables, and emitting signals for each step.\n */\n\nimport { Signal } from '@flare-engine/events';\nimport type { ChoiceNode, DialogueGraph, LineNode } from './graph.js';\nimport { getNode } from './graph.js';\n\n// ─── Error ───────────────────────────────────────────────────────\n\nexport type DialogueErrorCode = 'missing-node' | 'cycle';\n\nexport class DialogueError extends Error {\n readonly code: DialogueErrorCode;\n /** Source node whose transition triggered the error (or the entry id when there is no source). */\n readonly nodeId: string;\n /** 'missing-node': the target id that could not be resolved. */\n readonly missingId?: string;\n /** 'cycle': the node-id chain walked before the step budget was exceeded. */\n readonly chain?: readonly string[];\n\n constructor(\n code: DialogueErrorCode,\n message: string,\n detail: { nodeId: string; missingId?: string; chain?: readonly string[] },\n ) {\n super(message);\n this.name = 'DialogueError';\n this.code = code;\n this.nodeId = detail.nodeId;\n this.missingId = detail.missingId;\n this.chain = detail.chain;\n }\n}\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport type ConditionResolver = (key: string) => boolean;\nexport type ActionHandler = (key: string) => void | Promise<void>;\nexport type VariableBag = Record<string, string | number>;\n\nexport interface DialogueLineEvent {\n readonly speaker: string;\n /** Optional portrait key forwarded verbatim from the source LineNode. */\n readonly speakerPortraitKey?: string;\n readonly text: string;\n readonly nodeId: string;\n}\n\nexport interface DialogueChoiceEvent {\n readonly prompt: string | undefined;\n readonly speaker: string | undefined;\n readonly options: readonly ActiveOption[];\n readonly nodeId: string;\n}\n\nexport interface ActiveOption {\n readonly index: number;\n readonly text: string;\n readonly next: string;\n}\n\nexport type DialogueRunnerState = 'idle' | 'running' | 'waiting-choice' | 'ended';\n\n// ─── Interpolation ───────────────────────────────────────────────\n\nexport function interpolate(template: string, vars: VariableBag): string {\n return template.replace(/\\{(\\w+)\\}/g, (_match, key: string) => {\n const val = Object.hasOwn(vars, key) ? vars[key] : undefined;\n return val !== undefined ? String(val) : `{${key}}`;\n });\n}\n\n// ─── Runner ──────────────────────────────────────────────────────\n\nexport interface DialogueRunner {\n readonly onLine: Signal<DialogueLineEvent>;\n readonly onChoice: Signal<DialogueChoiceEvent>;\n readonly onAction: Signal<string>;\n readonly onEnd: Signal<string>;\n\n readonly state: DialogueRunnerState;\n readonly currentNodeId: string | null;\n readonly graphId: string | null;\n\n start(graph: DialogueGraph, variables?: VariableBag): void;\n advance(): void;\n selectChoice(index: number): void;\n stop(): void;\n}\n\nexport interface DialogueRunnerOptions {\n conditions?: ConditionResolver;\n actions?: ActionHandler;\n /**\n * Invoked on a recoverable dialogue error — currently a transition to a\n * missing node. Default (no hook): logs a console.warn, then ends.\n */\n onError?: (err: DialogueError) => void;\n}\n\nconst STEP_BUDGET = 1000;\n\nexport function createDialogueRunner(options?: DialogueRunnerOptions): DialogueRunner {\n const onLine = new Signal<DialogueLineEvent>();\n const onChoice = new Signal<DialogueChoiceEvent>();\n const onAction = new Signal<string>();\n const onEnd = new Signal<string>();\n\n const conditions = options?.conditions ?? (() => true);\n const actions = options?.actions;\n const onError = options?.onError;\n\n let _state: DialogueRunnerState = 'idle';\n let _graph: DialogueGraph | null = null;\n let _currentNodeId: string | null = null;\n let _vars: VariableBag = {};\n let _activeOptions: ActiveOption[] = [];\n\n function setState(s: DialogueRunnerState): void {\n _state = s;\n }\n\n function end(): void {\n setState('ended');\n const graphId = _graph?.id ?? '';\n _currentNodeId = null;\n onEnd.emit(graphId);\n }\n\n function reportMissing(fromNodeId: string | null, missingId: string): void {\n const graphId = _graph?.id ?? '';\n const from = fromNodeId ? ` from node '${fromNodeId}'` : ' as its start node';\n const err = new DialogueError(\n 'missing-node',\n `Dialogue '${graphId}' references missing node '${missingId}'${from} — ending conversation.`,\n { nodeId: fromNodeId ?? missingId, missingId },\n );\n if (onError) onError(err);\n else console.warn(err.message);\n }\n\n function processLine(node: LineNode, nodeId: string): void {\n setState('running');\n const text = interpolate(node.text, _vars);\n onLine.emit({\n speaker: node.speaker,\n speakerPortraitKey: node.speakerPortraitKey,\n text,\n nodeId,\n });\n }\n\n function processChoice(node: ChoiceNode, nodeId: string): void {\n _activeOptions = [];\n for (let i = 0; i < node.options.length; i++) {\n const opt = node.options[i]!;\n if (opt.condition && !conditions(opt.condition)) continue;\n _activeOptions.push({\n index: _activeOptions.length,\n text: interpolate(opt.text, _vars),\n next: opt.next,\n });\n }\n\n if (_activeOptions.length === 0) {\n end();\n return;\n }\n\n setState('waiting-choice');\n onChoice.emit({\n prompt: node.prompt ? interpolate(node.prompt, _vars) : undefined,\n speaker: node.speaker,\n options: _activeOptions,\n nodeId,\n });\n }\n\n function run(entryId: string, fromNodeId: string | null): void {\n if (!_graph) return;\n\n let currentId: string | null = entryId;\n let from: string | null = fromNodeId;\n const chain: string[] = [];\n let steps = 0;\n\n while (currentId !== null) {\n const nodeId = currentId;\n const node = getNode(_graph, nodeId);\n\n if (!node) {\n reportMissing(from, nodeId);\n end();\n return;\n }\n\n chain.push(nodeId);\n if (++steps > STEP_BUDGET) {\n throw new DialogueError(\n 'cycle',\n `Dialogue '${_graph.id}' cycle detected — step budget exceeded (chain: …${chain.slice(-12).join('→')})`,\n { nodeId, chain: chain.slice() },\n );\n }\n\n _currentNodeId = nodeId;\n from = nodeId;\n\n switch (node.kind) {\n case 'line':\n processLine(node, nodeId);\n return;\n case 'choice':\n processChoice(node, nodeId);\n return;\n case 'branch': {\n let next: string | null = node.fallback;\n for (const arm of node.arms) {\n if (conditions(arm.condition)) {\n next = arm.next;\n break;\n }\n }\n currentId = next;\n break;\n }\n case 'action':\n onAction.emit(node.action);\n actions?.(node.action);\n currentId = node.next;\n break;\n case 'end':\n end();\n return;\n }\n }\n\n end();\n }\n\n const runner: DialogueRunner = {\n onLine,\n onChoice,\n onAction,\n onEnd,\n\n get state() {\n return _state;\n },\n get currentNodeId() {\n return _currentNodeId;\n },\n get graphId() {\n return _graph?.id ?? null;\n },\n\n start(graph: DialogueGraph, variables?: VariableBag): void {\n _graph = graph;\n _vars = variables ?? {};\n _activeOptions = [];\n setState('running');\n run(graph.start, null);\n },\n\n advance(): void {\n if (_state !== 'running' || !_graph || !_currentNodeId) return;\n const node = getNode(_graph, _currentNodeId);\n if (node?.kind !== 'line') return;\n if (node.next) {\n run(node.next, _currentNodeId);\n } else {\n end();\n }\n },\n\n selectChoice(index: number): void {\n if (_state !== 'waiting-choice') return;\n const opt = _activeOptions[index];\n if (!opt) return;\n _activeOptions = [];\n setState('running');\n run(opt.next, _currentNodeId);\n },\n\n stop(): void {\n setState('idle');\n _graph = null;\n _currentNodeId = null;\n _vars = {};\n _activeOptions = [];\n },\n };\n\n return runner;\n}\n","/**\n * Text-over-time reveal hook for dialogue lines.\n *\n * Drives a typewriter effect: call `updateTextReveal(state, dt)` each frame\n * and read `state.visibleText` for the currently revealed substring.\n * Supports per-character speed, instant-complete, and pause-on-punctuation.\n */\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport interface TextRevealState {\n /** Full text being revealed. */\n readonly fullText: string;\n /** Characters revealed so far. */\n visibleText: string;\n /** Whether the full text has been revealed. */\n complete: boolean;\n /** Internal fractional character cursor. */\n _cursor: number;\n}\n\nexport interface TextRevealOptions {\n /** Characters per second. Default: 30. */\n speed?: number;\n /** Extra delay (in seconds) after punctuation (.!?). Default: 0.15. */\n punctuationDelay?: number;\n}\n\nconst DEFAULT_SPEED = 30;\nconst DEFAULT_PUNCT_DELAY = 0.15;\n\nconst PUNCTUATION = new Set(['.', '!', '?', ':', ';']);\n\n// ─── API ─────────────────────────────────────────────────────────\n\nexport function createTextReveal(text: string): TextRevealState {\n if (text.length === 0) {\n return { fullText: text, visibleText: text, complete: true, _cursor: 0 };\n }\n return { fullText: text, visibleText: '', complete: false, _cursor: 0 };\n}\n\nexport function updateTextReveal(\n state: TextRevealState,\n dt: number,\n options?: TextRevealOptions,\n): void {\n if (state.complete) return;\n\n const speed = options?.speed ?? DEFAULT_SPEED;\n const punctDelay = options?.punctuationDelay ?? DEFAULT_PUNCT_DELAY;\n const len = state.fullText.length;\n\n // Determine effective speed — slow down after punctuation\n const prevCharIdx = Math.floor(state._cursor) - 1;\n let effectiveSpeed = speed;\n if (prevCharIdx >= 0 && prevCharIdx < len) {\n const prevChar = state.fullText[prevCharIdx]!;\n if (PUNCTUATION.has(prevChar)) {\n // Slow down: treat the punctuation gap as taking `punctDelay` seconds\n // Effective speed = 1 / punctDelay so cursor advances ~1 char in punctDelay time\n effectiveSpeed = punctDelay > 0 ? 1 / punctDelay : speed;\n }\n }\n\n state._cursor += effectiveSpeed * dt;\n const charCount = Math.min(Math.floor(state._cursor), len);\n state.visibleText = state.fullText.slice(0, charCount);\n\n if (charCount >= len) {\n state.visibleText = state.fullText;\n state.complete = true;\n }\n}\n\nexport function completeTextReveal(state: TextRevealState): void {\n state.visibleText = state.fullText;\n state._cursor = state.fullText.length;\n state.complete = true;\n}\n\nexport function resetTextReveal(state: TextRevealState, newText?: string): void {\n const text = newText ?? state.fullText;\n (state as { fullText: string }).fullText = text;\n state.visibleText = '';\n state._cursor = 0;\n state.complete = text.length === 0;\n}\n"],"mappings":";;AAwFA,SAAgB,oBACd,IACA,OACA,OACe;CACf,OAAO;EAAE;EAAI;EAAO;CAAM;AAC5B;AAEA,SAAgB,QAAQ,OAAsB,QAA0C;CACtF,OAAO,OA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ner.ts","../src/text-reveal.ts"],"sourcesContent":["/**\n * Dialogue graph data types.\n *\n * A dialogue graph is a directed graph of nodes. Each node is one of:\n * - `line`: NPC/character speaks. Optional `next` pointer.\n * - `choice`: Player picks from options. Each option points to a node.\n * - `branch`: Condition-based routing. First truthy condition wins.\n * - `action`: Fires a callback, then advances to `next`.\n * - `end`: Terminal node. Conversation stops.\n *\n * Graphs are plain JSON — no classes, no runtime coupling.\n */\n\n// ─── Node types ──────────────────────────────────────────────────\n\nexport interface LineNode {\n readonly kind: 'line';\n /** Speaker name / id. */\n readonly speaker: string;\n /**\n * Optional portrait key resolved by the UI layer to an avatar image /\n * shape / atlas frame. The dialogue runtime is portrait-agnostic — it\n * forwards the key via `DialogueLineEvent.speakerPortraitKey`.\n */\n readonly speakerPortraitKey?: string;\n /** Text template. Supports `{var}` interpolation via the runner's variable bag. */\n readonly text: string;\n /** Next node id, or null to end. */\n readonly next: string | null;\n}\n\nexport interface ChoiceOption {\n /** Display text. Supports `{var}` interpolation. */\n readonly text: string;\n /** Node id to jump to when selected. */\n readonly next: string;\n /** Optional condition key — option is hidden when condition returns false. */\n readonly condition?: string;\n}\n\nexport interface ChoiceNode {\n readonly kind: 'choice';\n /** Optional prompt text before the choices. */\n readonly prompt?: string;\n /** Speaker for the prompt, if any. */\n readonly speaker?: string;\n readonly options: readonly ChoiceOption[];\n}\n\nexport interface BranchArm {\n /** Condition key evaluated by the runner's condition resolver. */\n readonly condition: string;\n /** Node id to jump to when condition is true. */\n readonly next: string;\n}\n\nexport interface BranchNode {\n readonly kind: 'branch';\n readonly arms: readonly BranchArm[];\n /** Fallback node id if no arm matches. Null → end. */\n readonly fallback: string | null;\n}\n\nexport interface ActionNode {\n readonly kind: 'action';\n /** Callback key. Runner looks this up in the action registry. */\n readonly action: string;\n /** Next node id after the action fires. */\n readonly next: string | null;\n}\n\nexport interface EndNode {\n readonly kind: 'end';\n}\n\nexport type DialogueNode = LineNode | ChoiceNode | BranchNode | ActionNode | EndNode;\n\n// ─── Graph ───────────────────────────────────────────────────────\n\nexport interface DialogueGraph {\n /** Unique graph identifier. */\n readonly id: string;\n /** Node id to start from. */\n readonly start: string;\n /** All nodes keyed by id. */\n readonly nodes: Record<string, DialogueNode>;\n}\n\nexport function createDialogueGraph(\n id: string,\n start: string,\n nodes: Record<string, DialogueNode>,\n): DialogueGraph {\n return { id, start, nodes };\n}\n\nexport function getNode(graph: DialogueGraph, nodeId: string): DialogueNode | undefined {\n return Object.hasOwn(graph.nodes, nodeId) ? graph.nodes[nodeId] : undefined;\n}\n","/**\n * Dialogue runner — walks a DialogueGraph, evaluating conditions,\n * interpolating variables, and emitting signals for each step.\n */\n\nimport { Signal } from '@flare-engine/events';\nimport type { ChoiceNode, DialogueGraph, LineNode } from './graph.js';\nimport { getNode } from './graph.js';\n\n// ─── Error ───────────────────────────────────────────────────────\n\nexport type DialogueErrorCode = 'missing-node' | 'cycle';\n\nexport class DialogueError extends Error {\n readonly code: DialogueErrorCode;\n /** Source node whose transition triggered the error (or the entry id when there is no source). */\n readonly nodeId: string;\n /** 'missing-node': the target id that could not be resolved. */\n readonly missingId?: string;\n /** 'cycle': the node-id chain walked before the step budget was exceeded. */\n readonly chain?: readonly string[];\n\n constructor(\n code: DialogueErrorCode,\n message: string,\n detail: { nodeId: string; missingId?: string; chain?: readonly string[] },\n ) {\n super(message);\n this.name = 'DialogueError';\n this.code = code;\n this.nodeId = detail.nodeId;\n this.missingId = detail.missingId;\n this.chain = detail.chain;\n }\n}\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport type ConditionResolver = (key: string) => boolean;\nexport type ActionHandler = (key: string) => void | Promise<void>;\nexport type VariableBag = Record<string, string | number>;\n\nexport interface DialogueLineEvent {\n readonly speaker: string;\n /** Optional portrait key forwarded verbatim from the source LineNode. */\n readonly speakerPortraitKey?: string;\n readonly text: string;\n readonly nodeId: string;\n}\n\nexport interface DialogueChoiceEvent {\n readonly prompt: string | undefined;\n readonly speaker: string | undefined;\n readonly options: readonly ActiveOption[];\n readonly nodeId: string;\n}\n\nexport interface ActiveOption {\n readonly index: number;\n readonly text: string;\n readonly next: string;\n}\n\nexport type DialogueRunnerState = 'idle' | 'running' | 'waiting-choice' | 'ended';\n\n// ─── Interpolation ───────────────────────────────────────────────\n\nexport function interpolate(template: string, vars: VariableBag): string {\n return template.replace(/\\{(\\w+)\\}/g, (_match, key: string) => {\n const val = Object.hasOwn(vars, key) ? vars[key] : undefined;\n return val !== undefined ? String(val) : `{${key}}`;\n });\n}\n\n// ─── Runner ──────────────────────────────────────────────────────\n\nexport interface DialogueRunner {\n readonly onLine: Signal<DialogueLineEvent>;\n readonly onChoice: Signal<DialogueChoiceEvent>;\n readonly onAction: Signal<string>;\n readonly onEnd: Signal<string>;\n\n readonly state: DialogueRunnerState;\n readonly currentNodeId: string | null;\n readonly graphId: string | null;\n\n start(graph: DialogueGraph, variables?: VariableBag): void;\n advance(): void;\n selectChoice(index: number): void;\n stop(): void;\n}\n\nexport interface DialogueRunnerOptions {\n conditions?: ConditionResolver;\n actions?: ActionHandler;\n /**\n * Invoked on a recoverable dialogue error — currently a transition to a\n * missing node. Default (no hook): logs a console.warn, then ends.\n */\n onError?: (err: DialogueError) => void;\n}\n\nconst STEP_BUDGET = 1000;\n\nexport function createDialogueRunner(options?: DialogueRunnerOptions): DialogueRunner {\n const onLine = new Signal<DialogueLineEvent>();\n const onChoice = new Signal<DialogueChoiceEvent>();\n const onAction = new Signal<string>();\n const onEnd = new Signal<string>();\n\n const conditions = options?.conditions ?? (() => true);\n const actions = options?.actions;\n const onError = options?.onError;\n\n let _state: DialogueRunnerState = 'idle';\n let _graph: DialogueGraph | null = null;\n let _currentNodeId: string | null = null;\n let _vars: VariableBag = {};\n let _activeOptions: ActiveOption[] = [];\n\n function setState(s: DialogueRunnerState): void {\n _state = s;\n }\n\n function end(): void {\n setState('ended');\n const graphId = _graph?.id ?? '';\n _currentNodeId = null;\n onEnd.emit(graphId);\n }\n\n function reportMissing(fromNodeId: string | null, missingId: string): void {\n const graphId = _graph?.id ?? '';\n const from = fromNodeId ? ` from node '${fromNodeId}'` : ' as its start node';\n const err = new DialogueError(\n 'missing-node',\n `Dialogue '${graphId}' references missing node '${missingId}'${from} — ending conversation.`,\n { nodeId: fromNodeId ?? missingId, missingId },\n );\n if (onError) onError(err);\n else console.warn(err.message);\n }\n\n function processLine(node: LineNode, nodeId: string): void {\n setState('running');\n const text = interpolate(node.text, _vars);\n onLine.emit({\n speaker: node.speaker,\n speakerPortraitKey: node.speakerPortraitKey,\n text,\n nodeId,\n });\n }\n\n function processChoice(node: ChoiceNode, nodeId: string): void {\n _activeOptions = [];\n for (let i = 0; i < node.options.length; i++) {\n const opt = node.options[i]!;\n if (opt.condition && !conditions(opt.condition)) continue;\n _activeOptions.push({\n index: _activeOptions.length,\n text: interpolate(opt.text, _vars),\n next: opt.next,\n });\n }\n\n if (_activeOptions.length === 0) {\n end();\n return;\n }\n\n setState('waiting-choice');\n onChoice.emit({\n prompt: node.prompt ? interpolate(node.prompt, _vars) : undefined,\n speaker: node.speaker,\n options: _activeOptions,\n nodeId,\n });\n }\n\n function run(entryId: string, fromNodeId: string | null): void {\n if (!_graph) return;\n\n let currentId: string | null = entryId;\n let from: string | null = fromNodeId;\n const chain: string[] = [];\n let steps = 0;\n\n while (currentId !== null) {\n const nodeId = currentId;\n const node = getNode(_graph, nodeId);\n\n if (!node) {\n reportMissing(from, nodeId);\n end();\n return;\n }\n\n chain.push(nodeId);\n if (++steps > STEP_BUDGET) {\n throw new DialogueError(\n 'cycle',\n `Dialogue '${_graph.id}' cycle detected — step budget exceeded (chain: …${chain.slice(-12).join('→')})`,\n { nodeId, chain: chain.slice() },\n );\n }\n\n _currentNodeId = nodeId;\n from = nodeId;\n\n switch (node.kind) {\n case 'line':\n processLine(node, nodeId);\n return;\n case 'choice':\n processChoice(node, nodeId);\n return;\n case 'branch': {\n let next: string | null = node.fallback;\n for (const arm of node.arms) {\n if (conditions(arm.condition)) {\n next = arm.next;\n break;\n }\n }\n currentId = next;\n break;\n }\n case 'action':\n onAction.emit(node.action);\n actions?.(node.action);\n currentId = node.next;\n break;\n case 'end':\n end();\n return;\n }\n }\n\n end();\n }\n\n const runner: DialogueRunner = {\n onLine,\n onChoice,\n onAction,\n onEnd,\n\n get state() {\n return _state;\n },\n get currentNodeId() {\n return _currentNodeId;\n },\n get graphId() {\n return _graph?.id ?? null;\n },\n\n start(graph: DialogueGraph, variables?: VariableBag): void {\n _graph = graph;\n _vars = variables ?? {};\n _activeOptions = [];\n setState('running');\n run(graph.start, null);\n },\n\n advance(): void {\n if (_state !== 'running' || !_graph || !_currentNodeId) return;\n const node = getNode(_graph, _currentNodeId);\n if (node?.kind !== 'line') return;\n if (node.next) {\n run(node.next, _currentNodeId);\n } else {\n end();\n }\n },\n\n selectChoice(index: number): void {\n if (_state !== 'waiting-choice') return;\n const opt = _activeOptions[index];\n if (!opt) return;\n _activeOptions = [];\n setState('running');\n run(opt.next, _currentNodeId);\n },\n\n stop(): void {\n setState('idle');\n _graph = null;\n _currentNodeId = null;\n _vars = {};\n _activeOptions = [];\n },\n };\n\n return runner;\n}\n","/**\n * Text-over-time reveal hook for dialogue lines.\n *\n * Drives a typewriter effect: call `updateTextReveal(state, dt)` each frame\n * and read `state.visibleText` for the currently revealed substring.\n * Supports per-character speed, instant-complete, and pause-on-punctuation.\n */\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport interface TextRevealState {\n /** Full text being revealed. */\n readonly fullText: string;\n /** Characters revealed so far. */\n visibleText: string;\n /** Whether the full text has been revealed. */\n complete: boolean;\n /** Internal fractional character cursor. */\n _cursor: number;\n}\n\nexport interface TextRevealOptions {\n /** Characters per second. Default: 30. */\n speed?: number;\n /** Extra delay (in seconds) after punctuation (.!?). Default: 0.15. */\n punctuationDelay?: number;\n}\n\nconst DEFAULT_SPEED = 30;\nconst DEFAULT_PUNCT_DELAY = 0.15;\n\nconst PUNCTUATION = new Set(['.', '!', '?', ':', ';']);\n\n// ─── API ─────────────────────────────────────────────────────────\n\nexport function createTextReveal(text: string): TextRevealState {\n if (text.length === 0) {\n return { fullText: text, visibleText: text, complete: true, _cursor: 0 };\n }\n return { fullText: text, visibleText: '', complete: false, _cursor: 0 };\n}\n\nexport function updateTextReveal(\n state: TextRevealState,\n dt: number,\n options?: TextRevealOptions,\n): void {\n if (state.complete) return;\n\n const speed = options?.speed ?? DEFAULT_SPEED;\n const punctDelay = options?.punctuationDelay ?? DEFAULT_PUNCT_DELAY;\n const len = state.fullText.length;\n\n // Determine effective speed — slow down after punctuation\n const prevCharIdx = Math.floor(state._cursor) - 1;\n let effectiveSpeed = speed;\n if (prevCharIdx >= 0 && prevCharIdx < len) {\n const prevChar = state.fullText[prevCharIdx]!;\n if (PUNCTUATION.has(prevChar)) {\n // Slow down: treat the punctuation gap as taking `punctDelay` seconds\n // Effective speed = 1 / punctDelay so cursor advances ~1 char in punctDelay time\n effectiveSpeed = punctDelay > 0 ? 1 / punctDelay : speed;\n }\n }\n\n state._cursor += effectiveSpeed * dt;\n const charCount = Math.min(Math.floor(state._cursor), len);\n state.visibleText = state.fullText.slice(0, charCount);\n\n if (charCount >= len) {\n state.visibleText = state.fullText;\n state.complete = true;\n }\n}\n\nexport function completeTextReveal(state: TextRevealState): void {\n state.visibleText = state.fullText;\n state._cursor = state.fullText.length;\n state.complete = true;\n}\n\nexport function resetTextReveal(state: TextRevealState, newText?: string): void {\n const text = newText ?? state.fullText;\n (state as { fullText: string }).fullText = text;\n state.visibleText = '';\n state._cursor = 0;\n state.complete = text.length === 0;\n}\n"],"mappings":";;AAwFA,SAAgB,oBACd,IACA,OACA,OACe;CACf,OAAO;EAAE;EAAI;EAAO;CAAM;AAC5B;AAEA,SAAgB,QAAQ,OAAsB,QAA0C;CACtF,OAAO,OAAO,OAAO,MAAM,OAAO,MAAM,IAAI,MAAM,MAAM,UAAU,KAAA;AACpE;;;;;;ACrFA,IAAa,gBAAb,cAAmC,MAAM;CACvC;;CAEA;;CAEA;;CAEA;CA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BAAiB,MAA+B;CAC9D,IAAI,KAAK,WAAW,GAClB,OAAO;EAAE,UAAU;EAAM,aAAa;EAAM,UAAU;EAAM,SAAS;CAAE;CAEzE,OAAO;EAAE,UAAU;EAAM,aAAa;EAAI,UAAU;EAAO,SAAS;CAAE;AACxE;AAEA,SAAgB,iBACd,OACA,IACA,SACM;CACN,IAAI,MAAM,UAAU;CAEpB,MAAM,QAAQ,SAAS,SAAS;CAChC,MAAM,aAAa,SAAS,oBAAoB;CAChD,MAAM,MAAM,MAAM,SAAS;CAG3B,MAAM,cAAc,KAAK,MAAM,MAAM,OAAO,IAAI;CAChD,IAAI,iBAAiB;CACrB,IAAI,eAAe,KAAK,cAAc,KAAK;EACzC,MAAM,WAAW,MAAM,SAAS;EAChC,IAAI,YAAY,IAAI,QAAQ,GAG1B,iBAAiB,aAAa,IAAI,IAAI,aAAa;CAEvD;CAEA,MAAM,WAAW,iBAAiB;CAClC,MAAM,YAAY,KAAK,IAAI,KAAK,MAAM,MAAM,OAAO,GAAG,GAAG;CACzD,MAAM,cAAc,MAAM,SAAS,MAAM,GAAG,SAAS;CAErD,IAAI,aAAa,KAAK;EACpB,MAAM,cAAc,MAAM;EAC1B,MAAM,WAAW;CACnB;AACF;AAEA,SAAgB,mBAAmB,OAA8B;CAC/D,MAAM,cAAc,MAAM;CAC1B,MAAM,UAAU,MAAM,SAAS;CAC/B,MAAM,WAAW;AACnB;AAEA,SAAgB,gBAAgB,OAAwB,SAAwB;CAC9E,MAAM,OAAO,WAAW,MAAM;CAC9B,MAAgC,WAAW;CAC3C,MAAM,cAAc;CACpB,MAAM,UAAU;CAChB,MAAM,WAAW,KAAK,WAAW;AACnC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@flare-engine/dialogue",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.7",
|
|
4
4
|
"description": "Dialogue graph runtime — lines, choices, conditions, variables, text-over-time reveal",
|
|
5
5
|
"keywords": ["flare-engine", "dialogue", "narrative", "branching", "rpg"],
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
"typecheck": "tsc --noEmit"
|
|
38
38
|
},
|
|
39
39
|
"dependencies": {
|
|
40
|
-
"@flare-engine/events": "^0.4.
|
|
40
|
+
"@flare-engine/events": "^0.4.7"
|
|
41
41
|
},
|
|
42
42
|
"engines": {
|
|
43
43
|
"node": ">=20"
|