npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@proumeus/redhood-dialogue-sdk

v1.6.0

Published

A lightweight browser SDK for REDHOOD-style branching visual novel dialogue with pixel UI support.

Readme

@proumeus/redhood-dialogue-sdk

A lightweight browser SDK for REDHOOD-style branching visual novel dialogue.

Built with plain JavaScript and native DOM — no React, no Vue, no build step required.

Current version: 1.6.0 — character expressions, portrait transitions, and name colors. See CHANGELOG.md.

About REDHOOD

REDHOOD is an independent dark fairy-tale 2D game inspired by Little Red Riding Hood. This SDK extends the game into a small creator kit for modders and web developers.

Play REDHOOD

https://proumeus.itch.io/redhood

Install

npm install @proumeus/redhood-dialogue-sdk

Features

  • Typewriter effect — characters appear one by one; click to skip
  • Character portraits — optional left/center/right portraits per speaker or node
  • Character expressions — define expressions once, reference by name in dialogue nodes
  • Portrait transitions — optional none or fade transitions between expressions
  • Portrait preloading — preload character images to reduce first-display flicker
  • Dialogue history — review past lines without changing game state
  • Auto play — automatically advance linear dialogue after a delay
  • Skip mode — rapidly advance dialogue but pause at choices
  • Branching choices — multiple paths with choices and nextId
  • Dialogue variables — store boolean, number, and string state during play
  • Conditional choices — show or hide options based on variables
  • Built-in actions — setVariable, changeVariable, and emit
  • Save / load — export and import dialogue runtime state
  • Node-based API — createDialogue() with start(), restart(), destroy()
  • Legacy array API — createDialogueScene() still supported
  • REDHOOD themes — dark, blood, forest
  • Pixel font mode — set font: "pixel" for retro UI
  • Input validation — invalid dialogue data logs clear [RedHoodSDK] console errors
  • TypeScript definitions — full autocomplete in VS Code and Cursor
  • Zero runtime dependencies — plain ES modules, works in any modern browser

Quick start

<div id="game"></div>

<script type="module">
  import { createDialogue } from "@proumeus/redhood-dialogue-sdk";

  const nodes = {
    "intro-1": {
      speaker: "Jack",
      text: "A new adventurer?",
      nextId: "intro-2",
    },
    "intro-2": {
      speaker: "Jack",
      text: "It's been a long time",
      nextId: "end-1",
    },
    "end-1": {
      speaker: "Jack",
      text: "(nodded)",
    },
  };

  const dialogue = createDialogue({
    container: "#game",
    startId: "intro-1",
    nodes,
    typeSpeed: 35,
    font: "pixel",
    onEnd() {
      console.log("Dialogue ended");
    },
  });

  dialogue.start();
</script>

Load Press Start 2P for pixel font mode:

<link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap" rel="stylesheet">

Branching dialogue example

Use choices instead of nextId when the player should pick a path:

const nodes = {
  "choice-1": {
    speaker: "Jack",
    text: "What will you do?",
    choices: [
      { label: "Accept", nextId: "accept-1" },
      { label: "Cancel", nextId: "cancel-1" },
    ],
  },
  "accept-1": {
    speaker: "RedHood",
    text: "thanks",
    nextId: "end-1",
  },
  "cancel-1": {
    speaker: "RedHood",
    text: "I want to look around first",
    nextId: "end-1",
  },
  "end-1": {
    speaker: "Jack",
    text: "(nodded)",
  },
};

const dialogue = createDialogue({
  container: "#game",
  startId: "choice-1",
  nodes,
});

dialogue.start();

Each choice needs label (or text) and nextId. A node with no nextId and no choices ends the dialogue.

Character Portraits

Portraits are optional. Existing dialogue scripts without portraits continue to work unchanged.

Define a character registry in createDialogue():

const dialogue = createDialogue({
  container: "#game",
  startId: "intro-1",
  nodes,
  characters: {
    Jack: {
      portrait: "assets/jack-default.png",
      defaultPosition: "left",
    },
    RedHood: "assets/redhood-default.png",
  },
});

You can also override a portrait on a specific node:

{
  speaker: "RedHood",
  text: "Thanks.",
  portrait: {
    src: "assets/redhood-happy.png",
    position: "right",
    expression: "happy",
  },
}

Resolution order:

  1. node.portrait (explicit src always wins)
  2. node.expression → characters[speaker].expressions
  3. characters[speaker].defaultExpression
  4. characters[speaker].portrait
  5. no portrait

Positions: left, center, or right. Node-level position overrides character defaults.

Character Expressions

Define expressions once in the character registry, then reference them from dialogue nodes:

const characters = {
  redhood: {
    name: "Red Hood",
    nameColor: "#d94b4b",
    portrait: "assets/redhood.png",
    defaultExpression: "neutral",
    defaultPosition: "left",
    expressions: {
      neutral: "assets/redhood-neutral.png",
      angry: "assets/redhood-angry.png",
      happy: "assets/redhood-happy.png",
      sad: "assets/redhood-sad.png",
    },
  },
};

Reference expressions in dialogue nodes:

{
  character: "redhood",
  expression: "angry",
  text: "Don't come any closer.",
}

Portrait resolution priority:

  1. node.portrait.src — explicit node portrait always wins
  2. node.expression — lookup in characters[id].expressions
  3. characters[id].defaultExpression
  4. characters[id].portrait
  5. no portrait

Fallback behavior for unknown expressions:

  • Falls back to defaultExpression, then portrait, then no portrait
  • Logs a single [RedHoodSDK] warning per missing expression (no crash)

Backward-compatible portrait syntax remains valid:

portrait: "assets/redhood.png"
portrait: { src: "assets/redhood.png", position: "left" }
portrait: { src: "assets/redhood.png", position: "left", expression: "neutral" }

Name colors

Apply optional per-character name colors (speaker label only):

guide: {
  name: "Guide",
  nameColor: "#62aaff",
}

CSS overrides continue to work normally.

Portrait transitions and preloading

createDialogue({
  container: "#game",
  startId: "intro-1",
  nodes,
  characters,
  portraitTransition: "fade",       // "none" (default) | "fade"
  portraitTransitionDuration: 200,  // milliseconds
  preloadPortraits: true,           // default: true
});

Legacy createDialogueScene() also accepts portraitTransition, portraitTransitionDuration, and preloadPortraits.

Preloading scans character portrait, expressions, and node-level portrait sources. Failures never crash the engine.

Dialogue History

The SDK records lines that have already been displayed:

dialogue.openHistory();
dialogue.closeHistory();
dialogue.toggleHistory();

const entries = dialogue.getHistory();
// [{ speaker: "Jack", text: "Hello.", nodeId: "intro-1" }, ...]

Behavior:

  • History stores at least speaker and text
  • Opening or closing history does not change the current node or runtime state
  • Choices are not replayed from history
  • clearHistory() removes recorded entries; restart() also clears history

Auto Play and Skip

Auto play advances linear dialogue after typing finishes:

const dialogue = createDialogue({
  container: "#game",
  startId: "intro-1",
  nodes,
  autoPlayDelay: 2000,
});

dialogue.setAutoPlay(true);
dialogue.setAutoPlayDelay(1500);
dialogue.isAutoPlayEnabled();
dialogue.getAutoPlayDelay();

Skip mode rapidly advances dialogue:

dialogue.setSkipMode(true);
dialogue.isSkipModeEnabled();

Rules:

  • Auto play and skip both pause at choice nodes
  • Skip never automatically selects a choice
  • Manual click-to-advance continues to work normally
  • Skip skips typing instantly but still uses the normal runtime navigation path

Events:

dialogue.on("autoPlayChange", ({ enabled }) => {});
dialogue.on("skipModeChange", ({ enabled }) => {});
dialogue.on("historyOpen", () => {});
dialogue.on("historyClose", () => {});
dialogue.on("portraitChange", ({ active, left, right, speaker }) => {});

Variables

Dialogue variables let you store lightweight game state while a conversation runs.

Supported types:

  • boolean
  • number
  • string
dialogue.setVariable("hasKey", true);
dialogue.setVariable("trust", 10);

const hasKey = dialogue.getVariable("hasKey");
const trust = dialogue.getVariable("trust");

Behavior:

  • Reading a variable that was never set returns undefined
  • Pass a second argument to provide a default: dialogue.getVariable("trust", 0)
  • Variables are stored internally and are not exposed as mutable references
  • You can seed initial values with defaultVariables in createDialogue()

Common errors:

  • Setting a non-primitive value throws a RedHoodError
  • Empty variable names throw a RedHoodError

Conditional Choices

Add an optional condition to a choice to control whether it appears.

{
  id: "open-door",
  text: "Open the door",
  nextNodeId: "door-opened",
  condition: {
    variable: "hasKey",
    operator: "equals",
    value: true
  }
}

Supported operators:

  • equals
  • notEquals
  • greaterThan
  • greaterThanOrEqual
  • lessThan
  • lessThanOrEqual

Default behavior:

  • If a condition is not met, the option is hidden
  • Options without a condition always appear normally
  • Set hiddenConditionBehavior: "disable" in createDialogue() to show failed options as disabled buttons instead

Type rules:

  • equals / notEquals work with boolean, number, and string values
  • Ordering operators expect comparable types; missing numeric variables are treated as 0

Common errors:

  • Unsupported operators are reported during validation
  • Invalid condition shapes are logged when dialogue data is loaded

Actions and Events

Attach optional actions to a choice. Actions run after the choice is accepted and before the dialogue moves to the next node.

Execution order:

  1. Validate the selected choice is available
  2. Record the selected option id
  3. Run each action in array order
  4. Navigate to nextId / nextNodeId

Supported action types:

{
  id: "accept-quest",
  text: "Accept the quest",
  nextNodeId: "quest-accepted",
  actions: [
    { type: "setVariable", variable: "questAccepted", value: true },
    { type: "changeVariable", variable: "trust", amount: 5 },
    { type: "emit", event: "startQuest", payload: { questId: "red-forest" } }
  ]
}

setVariable

Sets a variable directly.

changeVariable

Adds a numeric amount to an existing number variable.

  • If the variable does not exist yet, it starts from 0
  • If the variable exists but is not a number, the action throws a clear error

emit

Dispatches an external event to listeners registered on the dialogue instance:

dialogue.on("startQuest", (payload) => {
  console.log(payload);
});

dialogue.off("startQuest", handler);

Notes:

  • The SDK never executes string code or uses eval
  • Selecting an unavailable or unknown choice does not run actions
  • Keep payload JSON-serializable; do not store functions, DOM nodes, or other non-serializable values

Saving and Loading Dialogue State

Export the current runtime state for save games:

const saveData = dialogue.exportState();
localStorage.setItem("dialogue-save", JSON.stringify(saveData));

Example shape:

{
  version: 1,
  currentNodeId: "forest-entry",
  variables: {
    hasKey: true,
    trust: 10
  },
  selectedOptionIds: ["accept-quest"],
  visitedNodeIds: ["start", "forest-entry"]
}

Restore it later:

const saveData = JSON.parse(localStorage.getItem("dialogue-save"));
await dialogue.importState(saveData);

Behavior:

  • exportState() returns a plain object safe for JSON.stringify
  • importState() validates the full payload first, then applies it atomically
  • Invalid node ids, unsupported versions, or malformed fields throw RedHoodError
  • If import fails, the previous runtime state is left unchanged

Data Validation

Dialogue data is validated when you call createDialogue() or createDialogueScene().

The validator checks:

  • Duplicate or missing node ids
  • Missing startId
  • Invalid or missing nextId / nextNodeId targets
  • Duplicate option ids
  • Invalid conditions and operators
  • Unsupported or incomplete actions

Example error:

[RedHoodSDK] Invalid nextNodeId "missing-node" in option "open-door". The target node does not exist. Suggestion: add node "missing-node" or fix the reference.

Fix the reported field and try again. Runtime errors also log clearly and end the scene safely.

TypeScript Types

Type definitions ship with the package at src/index.d.ts.

Key exports:

DialogueVariableValue
DialogueVariables
DialogueCondition
DialogueConditionOperator
DialogueAction
DialoguePortrait
DialogueCharacter
DialogueHistoryEntry
SetVariableAction
ChangeVariableAction
EmitAction
DialogueOption
DialogueNode
DialogueData
DialogueState
DialogueStateV1

Action types use a discriminated union:

type DialogueAction =
  | SetVariableAction
  | ChangeVariableAction
  | EmitAction;

This gives you autocomplete, invalid operator errors, and typed save-state exports in Cursor and VS Code.

Migration from v1.5.x / v1.4.x

v1.6.0 is backward compatible with existing dialogue files.

What stays the same:

  • All v1.4/v1.5 portrait formats, history, auto play, skip, save/load, and branching
  • speaker on nodes (also accepts character alias)
  • Existing themes, typewriter behavior, and click-to-advance UX

What is new and optional:

  • characters[].expressions, defaultExpression, and nameColor
  • node.expression and node.position
  • portraitTransition, portraitTransitionDuration, and preloadPortraits
  • Center portrait positioning

No migration is required unless you want expressions.

Migration from v1.3.x

v1.4.0+ is backward compatible with existing dialogue files.

What stays the same:

  • createDialogue(), start(), restart(), and destroy()
  • Variables, conditions, actions, events, and save/load
  • Legacy createDialogueScene() array-based scenes

What is new and optional (v1.4+):

  • characters registry and node.portrait
  • openHistory(), closeHistory(), getHistory()
  • setAutoPlay(), setSkipMode(), and related helpers

No changes are required unless you want the new features.

Migration from v1.2.x

v1.3.0 is backward compatible with existing dialogue files.

What stays the same:

  • createDialogue(), start(), restart(), and destroy()
  • Legacy choices with label / text and nextId
  • createDialogueScene() array-based scenes
  • Existing themes, typewriter behavior, and click-to-advance UX

What is new and optional:

  • condition
  • actions
  • id on choices
  • nextNodeId alias for nextId
  • setVariable(), getVariable(), on(), off(), exportState(), importState()

No changes are required unless you want the new features.

Console prefix update:

  • Validation and runtime errors now use [RedHoodSDK] instead of [redhood-dialogue-sdk]

API

createDialogue(options)

| Option | Default | Description | | --- | --- | --- | | container | — | CSS selector or DOM element | | startId | — | First node id to display | | nodes | — | Object map of dialogue nodes | | characters | — | Optional speaker portrait registry | | typeSpeed | 35 | Typewriter speed (ms per character) | | allowSkipTyping | true | Click to instantly finish typing | | showSpeaker | true | Show or hide speaker name | | showPortraits | true | Show or hide portrait stage | | autoPlayDelay | 2000 | Default auto-play delay in ms | | portraitTransition | "none" | Portrait transition: none or fade | | portraitTransitionDuration | 200 | Fade duration in ms | | preloadPortraits | true | Preload character portrait images | | theme | "dark" | Visual theme: dark, blood, forest | | font | "serif" | Set to "pixel" for pixel font | | onEnd | — | Called when dialogue ends | | defaultVariables | — | Initial dialogue variables | | hiddenConditionBehavior | "hide" | "hide" or "disable" for failed conditions |

Node format:

{
  speaker: "Jack",
  text: "Hello.",
  portrait: "assets/jack-default.png",
  nextId: "next-node",
  choices: [
    {
      id: "accept-quest",
      label: "Accept",
      nextNodeId: "accepted",
      condition: { variable: "trust", operator: "greaterThanOrEqual", value: 5 },
      actions: [{ type: "emit", event: "questAccepted" }],
    },
  ],
}

Returns:

const dialogue = createDialogue({ ... });

dialogue.start();
dialogue.restart();
dialogue.destroy();

dialogue.setVariable("hasKey", true);
dialogue.getVariable("hasKey");

dialogue.on("doorOpened", (payload) => {});
dialogue.off("doorOpened", handler);

const saveData = dialogue.exportState();
await dialogue.importState(saveData);

dialogue.openHistory();
dialogue.closeHistory();
dialogue.getHistory();

dialogue.setAutoPlay(true);
dialogue.setSkipMode(false);

dialogue.getCurrentNodeId();
dialogue.getAvailableChoices();
dialogue.selectChoice("open-door");

Legacy API

createDialogueScene(containerId, sceneData, options?) is still available for array-based scenes.

Utilities

  • typeText(element, text, speed?) — typewriter effect with .skip()
  • applyRedhoodStyles(sceneElement, options?) — apply REDHOOD styles
  • DialogueRuntime — headless runtime for custom integrations and tests
  • DialogueHistory — lightweight history/backlog tracker
  • PlaybackController — headless auto-play and skip controller
  • PortraitRenderer — portrait slot rendering with fade transitions
  • resolvePortrait() / resolvePortraitSlots() — portrait and expression resolution helpers
  • collectPortraitSources() / preloadPortraitImages() — portrait preloading helpers
  • validateDialogueNodes(nodes, startId, characters?) — validate node maps manually

Interaction

  • While typing — click the dialogue box to finish the current line instantly
  • After typing — click again to go to the next node, or enable auto play / skip
  • Choices — appear only after typing finishes; click a choice button to branch
  • History — open the backlog overlay to review past lines without changing state
  • End — when a node has no nextId and no choices, dialogue ends and onEnd runs

Demo

npm install
npm run dev

Open:

  • http://localhost:3456/demo/expressions-demo.html — v1.6.0 expressions, transitions, save/load
  • http://localhost:3456/demo/vn-demo.html — portraits, history, auto play, and skip
  • http://localhost:3456/demo/ — basic branching demo with portraits
  • http://localhost:3456/demo/variables-demo.html — variables, conditions, actions, and save/load

Run tests:

npm test

Changelog

See CHANGELOG.md for full version history.

License

MIT © Proumeus