@flare-engine/dialogue 0.4.10 → 0.4.11

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 CHANGED
@@ -91,6 +91,13 @@ export declare class DialogueError extends Error {
91
91
  });
92
92
  }
93
93
  type ConditionResolver = (key: string) => boolean;
94
+ /**
95
+ * Called synchronously when the runner reaches an `ActionNode`, after
96
+ * `onAction` has emitted. The return value is ignored: a returned promise is
97
+ * not awaited, so the runner moves on to the node's `next` before it settles,
98
+ * and nothing handles its rejection — an async handler must catch its own
99
+ * errors.
100
+ */
94
101
  type ActionHandler = (key: string) => void | Promise<void>;
95
102
  type VariableBag = Record<string, string | number>;
96
103
  interface DialogueLineEvent {
@@ -152,11 +159,13 @@ interface TextRevealState {
152
159
  complete: boolean;
153
160
  /** Internal fractional character cursor. */
154
161
  _cursor: number;
162
+ /** Internal punctuation pause still to wait, in seconds. Absent reads as 0. */
163
+ _pause?: number;
155
164
  }
156
165
  interface TextRevealOptions {
157
166
  /** Characters per second. Default: 30. */
158
167
  speed?: number;
159
- /** Extra delay (in seconds) after punctuation (.!?). Default: 0.15. */
168
+ /** Extra delay (in seconds) after punctuation (.!?:;). Default: 0.15. */
160
169
  punctuationDelay?: number;
161
170
  }
162
171
  export declare function createTextReveal(text: string): TextRevealState;
@@ -1 +1 @@
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"}
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;;;;;;;;KAQrB,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;;;;;;;;UCrGtD;;WAEN;;EAET;;EAEA;;EAEA;;EAEA;;UAGe;;EAEf;;EAEA;;wBAUc,iBAAiB,eAAe;wBAOhC,iBACd,OAAO,iBACP,YACA,UAAU;wBAyDI,mBAAmB,OAAO;wBAO1B,gBAAgB,OAAO,iBAAiB"}
package/dist/index.d.ts CHANGED
@@ -91,6 +91,13 @@ export declare class DialogueError extends Error {
91
91
  });
92
92
  }
93
93
  type ConditionResolver = (key: string) => boolean;
94
+ /**
95
+ * Called synchronously when the runner reaches an `ActionNode`, after
96
+ * `onAction` has emitted. The return value is ignored: a returned promise is
97
+ * not awaited, so the runner moves on to the node's `next` before it settles,
98
+ * and nothing handles its rejection — an async handler must catch its own
99
+ * errors.
100
+ */
94
101
  type ActionHandler = (key: string) => void | Promise<void>;
95
102
  type VariableBag = Record<string, string | number>;
96
103
  interface DialogueLineEvent {
@@ -152,11 +159,13 @@ interface TextRevealState {
152
159
  complete: boolean;
153
160
  /** Internal fractional character cursor. */
154
161
  _cursor: number;
162
+ /** Internal punctuation pause still to wait, in seconds. Absent reads as 0. */
163
+ _pause?: number;
155
164
  }
156
165
  interface TextRevealOptions {
157
166
  /** Characters per second. Default: 30. */
158
167
  speed?: number;
159
- /** Extra delay (in seconds) after punctuation (.!?). Default: 0.15. */
168
+ /** Extra delay (in seconds) after punctuation (.!?:;). Default: 0.15. */
160
169
  punctuationDelay?: number;
161
170
  }
162
171
  export declare function createTextReveal(text: string): TextRevealState;
@@ -1 +1 @@
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"}
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;;;;;;;;KAQrB,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;;;;;;;;UCrGtD;;WAEN;;EAET;;EAEA;;EAEA;;EAEA;;UAGe;;EAEf;;EAEA;;wBAUc,iBAAiB,eAAe;wBAOhC,iBACd,OAAO,iBACP,YACA,UAAU;wBAyDI,mBAAmB,OAAO;wBAO1B,gBAAgB,OAAO,iBAAiB"}
package/dist/index.js CHANGED
@@ -212,13 +212,15 @@ function createTextReveal(text) {
212
212
  fullText: text,
213
213
  visibleText: text,
214
214
  complete: true,
215
- _cursor: 0
215
+ _cursor: 0,
216
+ _pause: 0
216
217
  };
217
218
  return {
218
219
  fullText: text,
219
220
  visibleText: "",
220
221
  complete: false,
221
- _cursor: 0
222
+ _cursor: 0,
223
+ _pause: 0
222
224
  };
223
225
  }
224
226
  function updateTextReveal(state, dt, options) {
@@ -226,23 +228,45 @@ function updateTextReveal(state, dt, options) {
226
228
  const speed = options?.speed ?? DEFAULT_SPEED;
227
229
  const punctDelay = options?.punctuationDelay ?? DEFAULT_PUNCT_DELAY;
228
230
  const len = state.fullText.length;
229
- const prevCharIdx = Math.floor(state._cursor) - 1;
230
- let effectiveSpeed = speed;
231
- if (prevCharIdx >= 0 && prevCharIdx < len) {
232
- const prevChar = state.fullText[prevCharIdx];
233
- if (PUNCTUATION.has(prevChar)) effectiveSpeed = punctDelay > 0 ? 1 / punctDelay : speed;
231
+ let cursor = state._cursor;
232
+ let pause = state._pause ?? 0;
233
+ let progress = speed * dt;
234
+ while (progress > 0 && cursor < len) {
235
+ if (pause > 0) {
236
+ const heldTime = progress / speed;
237
+ if (pause >= heldTime) {
238
+ pause -= heldTime;
239
+ progress = 0;
240
+ } else {
241
+ progress -= pause * speed;
242
+ pause = 0;
243
+ }
244
+ continue;
245
+ }
246
+ const nextBoundary = Math.floor(cursor) + 1;
247
+ const distance = nextBoundary - cursor;
248
+ if (progress < distance) {
249
+ cursor += progress;
250
+ break;
251
+ }
252
+ cursor = nextBoundary;
253
+ progress -= distance;
254
+ if (nextBoundary < len && punctDelay > 0 && PUNCTUATION.has(state.fullText[nextBoundary - 1])) pause = punctDelay;
234
255
  }
235
- state._cursor += effectiveSpeed * dt;
236
- const charCount = Math.min(Math.floor(state._cursor), len);
237
- state.visibleText = state.fullText.slice(0, charCount);
256
+ state._cursor = cursor;
257
+ state._pause = pause;
258
+ const charCount = Math.min(Math.floor(cursor), len);
238
259
  if (charCount >= len) {
239
260
  state.visibleText = state.fullText;
240
261
  state.complete = true;
262
+ return;
241
263
  }
264
+ if (charCount !== state.visibleText.length) state.visibleText = state.fullText.slice(0, charCount);
242
265
  }
243
266
  function completeTextReveal(state) {
244
267
  state.visibleText = state.fullText;
245
268
  state._cursor = state.fullText.length;
269
+ state._pause = 0;
246
270
  state.complete = true;
247
271
  }
248
272
  function resetTextReveal(state, newText) {
@@ -250,6 +274,7 @@ function resetTextReveal(state, newText) {
250
274
  state.fullText = text;
251
275
  state.visibleText = "";
252
276
  state._cursor = 0;
277
+ state._pause = 0;
253
278
  state.complete = text.length === 0;
254
279
  }
255
280
  exports.DialogueError = DialogueError;
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;C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AAS,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"}
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;\n/**\n * Called synchronously when the runner reaches an `ActionNode`, after\n * `onAction` has emitted. The return value is ignored: a returned promise is\n * not awaited, so the runner moves on to the node's `next` before it settles,\n * and nothing handles its rejection — an async handler must catch its own\n * errors.\n */\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 /** Internal punctuation pause still to wait, in seconds. Absent reads as 0. */\n _pause?: 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, _pause: 0 };\n }\n return { fullText: text, visibleText: '', complete: false, _cursor: 0, _pause: 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 // The pause is additive time: the cursor stops for `punctDelay` seconds each\n // time it crosses a punctuation character, then resumes at `speed`. The\n // budget is kept in cursor units (speed * dt) and spent boundary by boundary\n // so one large `dt` still honours every pause inside it.\n let cursor = state._cursor;\n let pause = state._pause ?? 0;\n let progress = speed * dt;\n while (progress > 0 && cursor < len) {\n if (pause > 0) {\n const heldTime = progress / speed;\n if (pause >= heldTime) {\n pause -= heldTime;\n progress = 0;\n } else {\n progress -= pause * speed;\n pause = 0;\n }\n continue;\n }\n const nextBoundary = Math.floor(cursor) + 1;\n const distance = nextBoundary - cursor;\n if (progress < distance) {\n cursor += progress;\n break;\n }\n cursor = nextBoundary;\n progress -= distance;\n if (\n nextBoundary < len &&\n punctDelay > 0 &&\n PUNCTUATION.has(state.fullText[nextBoundary - 1]!)\n ) {\n pause = punctDelay;\n }\n }\n state._cursor = cursor;\n state._pause = pause;\n\n const charCount = Math.min(Math.floor(cursor), len);\n if (charCount >= len) {\n state.visibleText = state.fullText;\n state.complete = true;\n return;\n }\n if (charCount !== state.visibleText.length) {\n state.visibleText = state.fullText.slice(0, charCount);\n }\n}\n\nexport function completeTextReveal(state: TextRevealState): void {\n state.visibleText = state.fullText;\n state._cursor = state.fullText.length;\n state._pause = 0;\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._pause = 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;AAwCA,SAAgB,YAAY,UAAkB,MAA2B;CACvE,OAAO,SAAS,QAAQ,eAAe,QAAQ,QAAgB;EAC7D,MAAM,MAAM,OAAO,OAAO,MAAM,GAAG,IAAI,KAAK,OAAO,KAAA;EACnD,O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QAAQ,SAAS,SAAS;CAChC,MAAM,aAAa,SAAS,oBAAoB;CAChD,MAAM,MAAM,MAAM,SAAS;CAM3B,IAAI,SAAS,MAAM;CACnB,IAAI,QAAQ,MAAM,UAAU;CAC5B,IAAI,WAAW,QAAQ;CACvB,OAAO,WAAW,KAAK,SAAS,KAAK;EACnC,IAAI,QAAQ,GAAG;GACb,MAAM,WAAW,WAAW;GAC5B,IAAI,SAAS,UAAU;IACrB,SAAS;IACT,WAAW;GACb,OAAO;IACL,YAAY,QAAQ;IACpB,QAAQ;GACV;GACA;EACF;EACA,MAAM,eAAe,KAAK,MAAM,MAAM,IAAI;EAC1C,MAAM,WAAW,eAAe;EAChC,IAAI,WAAW,UAAU;GACvB,UAAU;GACV;EACF;EACA,SAAS;EACT,YAAY;EACZ,IACE,eAAe,OACf,aAAa,KACb,YAAY,IAAI,MAAM,SAAS,eAAe,EAAG,GAEjD,QAAQ;CAEZ;CACA,MAAM,UAAU;CAChB,MAAM,SAAS;CAEf,MAAM,YAAY,KAAK,IAAI,KAAK,MAAM,MAAM,GAAG,GAAG;CAClD,IAAI,aAAa,KAAK;EACpB,MAAM,cAAc,MAAM;EAC1B,MAAM,WAAW;EACjB;CACF;CACA,IAAI,cAAc,MAAM,YAAY,QAClC,MAAM,cAAc,MAAM,SAAS,MAAM,GAAG,SAAS;AAEzD;AAEA,SAAgB,mBAAmB,OAA8B;CAC/D,MAAM,cAAc,MAAM;CAC1B,MAAM,UAAU,MAAM,SAAS;CAC/B,MAAM,SAAS;CACf,MAAM,WAAW;AACnB;AAEA,SAAgB,gBAAgB,OAAwB,SAAwB;CAC9E,MAAM,OAAO,WAAW,MAAM;CAC9B,MAAgC,WAAW;CAC3C,MAAM,cAAc;CACpB,MAAM,UAAU;CAChB,MAAM,SAAS;CACf,MAAM,WAAW,KAAK,WAAW;AACnC"}
package/dist/index.mjs CHANGED
@@ -211,13 +211,15 @@ function createTextReveal(text) {
211
211
  fullText: text,
212
212
  visibleText: text,
213
213
  complete: true,
214
- _cursor: 0
214
+ _cursor: 0,
215
+ _pause: 0
215
216
  };
216
217
  return {
217
218
  fullText: text,
218
219
  visibleText: "",
219
220
  complete: false,
220
- _cursor: 0
221
+ _cursor: 0,
222
+ _pause: 0
221
223
  };
222
224
  }
223
225
  function updateTextReveal(state, dt, options) {
@@ -225,23 +227,45 @@ function updateTextReveal(state, dt, options) {
225
227
  const speed = options?.speed ?? DEFAULT_SPEED;
226
228
  const punctDelay = options?.punctuationDelay ?? DEFAULT_PUNCT_DELAY;
227
229
  const len = state.fullText.length;
228
- const prevCharIdx = Math.floor(state._cursor) - 1;
229
- let effectiveSpeed = speed;
230
- if (prevCharIdx >= 0 && prevCharIdx < len) {
231
- const prevChar = state.fullText[prevCharIdx];
232
- if (PUNCTUATION.has(prevChar)) effectiveSpeed = punctDelay > 0 ? 1 / punctDelay : speed;
230
+ let cursor = state._cursor;
231
+ let pause = state._pause ?? 0;
232
+ let progress = speed * dt;
233
+ while (progress > 0 && cursor < len) {
234
+ if (pause > 0) {
235
+ const heldTime = progress / speed;
236
+ if (pause >= heldTime) {
237
+ pause -= heldTime;
238
+ progress = 0;
239
+ } else {
240
+ progress -= pause * speed;
241
+ pause = 0;
242
+ }
243
+ continue;
244
+ }
245
+ const nextBoundary = Math.floor(cursor) + 1;
246
+ const distance = nextBoundary - cursor;
247
+ if (progress < distance) {
248
+ cursor += progress;
249
+ break;
250
+ }
251
+ cursor = nextBoundary;
252
+ progress -= distance;
253
+ if (nextBoundary < len && punctDelay > 0 && PUNCTUATION.has(state.fullText[nextBoundary - 1])) pause = punctDelay;
233
254
  }
234
- state._cursor += effectiveSpeed * dt;
235
- const charCount = Math.min(Math.floor(state._cursor), len);
236
- state.visibleText = state.fullText.slice(0, charCount);
255
+ state._cursor = cursor;
256
+ state._pause = pause;
257
+ const charCount = Math.min(Math.floor(cursor), len);
237
258
  if (charCount >= len) {
238
259
  state.visibleText = state.fullText;
239
260
  state.complete = true;
261
+ return;
240
262
  }
263
+ if (charCount !== state.visibleText.length) state.visibleText = state.fullText.slice(0, charCount);
241
264
  }
242
265
  function completeTextReveal(state) {
243
266
  state.visibleText = state.fullText;
244
267
  state._cursor = state.fullText.length;
268
+ state._pause = 0;
245
269
  state.complete = true;
246
270
  }
247
271
  function resetTextReveal(state, newText) {
@@ -249,6 +273,7 @@ function resetTextReveal(state, newText) {
249
273
  state.fullText = text;
250
274
  state.visibleText = "";
251
275
  state._cursor = 0;
276
+ state._pause = 0;
252
277
  state.complete = text.length === 0;
253
278
  }
254
279
  export { DialogueError, completeTextReveal, createDialogueGraph, createDialogueRunner, createTextReveal, getNode, interpolate, resetTextReveal, updateTextReveal };
@@ -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,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,IAAI,OAA0B;CAC7C,MAAM,WAAW,IAAI,OAA4B;CACjD,MAAM,WAAW,IAAI,OAAe;CACpC,MAAM,QAAQ,IAAI,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;C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nB;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.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;\n/**\n * Called synchronously when the runner reaches an `ActionNode`, after\n * `onAction` has emitted. The return value is ignored: a returned promise is\n * not awaited, so the runner moves on to the node's `next` before it settles,\n * and nothing handles its rejection — an async handler must catch its own\n * errors.\n */\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 /** Internal punctuation pause still to wait, in seconds. Absent reads as 0. */\n _pause?: 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, _pause: 0 };\n }\n return { fullText: text, visibleText: '', complete: false, _cursor: 0, _pause: 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 // The pause is additive time: the cursor stops for `punctDelay` seconds each\n // time it crosses a punctuation character, then resumes at `speed`. The\n // budget is kept in cursor units (speed * dt) and spent boundary by boundary\n // so one large `dt` still honours every pause inside it.\n let cursor = state._cursor;\n let pause = state._pause ?? 0;\n let progress = speed * dt;\n while (progress > 0 && cursor < len) {\n if (pause > 0) {\n const heldTime = progress / speed;\n if (pause >= heldTime) {\n pause -= heldTime;\n progress = 0;\n } else {\n progress -= pause * speed;\n pause = 0;\n }\n continue;\n }\n const nextBoundary = Math.floor(cursor) + 1;\n const distance = nextBoundary - cursor;\n if (progress < distance) {\n cursor += progress;\n break;\n }\n cursor = nextBoundary;\n progress -= distance;\n if (\n nextBoundary < len &&\n punctDelay > 0 &&\n PUNCTUATION.has(state.fullText[nextBoundary - 1]!)\n ) {\n pause = punctDelay;\n }\n }\n state._cursor = cursor;\n state._pause = pause;\n\n const charCount = Math.min(Math.floor(cursor), len);\n if (charCount >= len) {\n state.visibleText = state.fullText;\n state.complete = true;\n return;\n }\n if (charCount !== state.visibleText.length) {\n state.visibleText = state.fullText.slice(0, charCount);\n }\n}\n\nexport function completeTextReveal(state: TextRevealState): void {\n state.visibleText = state.fullText;\n state._cursor = state.fullText.length;\n state._pause = 0;\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._pause = 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;AAwCA,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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AU;CAC5B,IAAI,WAAW,QAAQ;CACvB,OAAO,WAAW,KAAK,SAAS,KAAK;EACnC,IAAI,QAAQ,GAAG;GACb,MAAM,WAAW,WAAW;GAC5B,IAAI,SAAS,UAAU;IACrB,SAAS;IACT,WAAW;GACb,OAAO;IACL,YAAY,QAAQ;IACpB,QAAQ;GACV;GACA;EACF;EACA,MAAM,eAAe,KAAK,MAAM,MAAM,IAAI;EAC1C,MAAM,WAAW,eAAe;EAChC,IAAI,WAAW,UAAU;GACvB,UAAU;GACV;EACF;EACA,SAAS;EACT,YAAY;EACZ,IACE,eAAe,OACf,aAAa,KACb,YAAY,IAAI,MAAM,SAAS,eAAe,EAAG,GAEjD,QAAQ;CAEZ;CACA,MAAM,UAAU;CAChB,MAAM,SAAS;CAEf,MAAM,YAAY,KAAK,IAAI,KAAK,MAAM,MAAM,GAAG,GAAG;CAClD,IAAI,aAAa,KAAK;EACpB,MAAM,cAAc,MAAM;EAC1B,MAAM,WAAW;EACjB;CACF;CACA,IAAI,cAAc,MAAM,YAAY,QAClC,MAAM,cAAc,MAAM,SAAS,MAAM,GAAG,SAAS;AAEzD;AAEA,SAAgB,mBAAmB,OAA8B;CAC/D,MAAM,cAAc,MAAM;CAC1B,MAAM,UAAU,MAAM,SAAS;CAC/B,MAAM,SAAS;CACf,MAAM,WAAW;AACnB;AAEA,SAAgB,gBAAgB,OAAwB,SAAwB;CAC9E,MAAM,OAAO,WAAW,MAAM;CAC9B,MAAgC,WAAW;CAC3C,MAAM,cAAc;CACpB,MAAM,UAAU;CAChB,MAAM,SAAS;CACf,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.10",
3
+ "version": "0.4.11",
4
4
  "description": "Dialogue graph runtime — lines, choices, conditions, variables, text-over-time reveal",
5
5
  "keywords": [
6
6
  "flare-engine",
@@ -45,7 +45,7 @@
45
45
  "typecheck": "tsc --noEmit"
46
46
  },
47
47
  "dependencies": {
48
- "@flare-engine/events": "^0.4.10"
48
+ "@flare-engine/events": "^0.4.11"
49
49
  },
50
50
  "engines": {
51
51
  "node": ">=20"