npm package: @series-inc/slinky-phaser
Description: Phaser visual novel framework built on slinky-core
Author: Series Inc
Latest version: 1.0.0

# @series-inc/slinky-phaser

Phaser visual novel framework built on [@series-inc/slinky-core](../slinky-core).

## Overview

This package provides Phaser-specific UI components, modules, and scenes for building visual novels. It depends on `@series-inc/slinky-core` for the framework-agnostic narrative engine.

## Architecture

```
┌─────────────────────────────────────────────────────────────┐
│ GAME LAYER (apps/basic-game, apps/rundot-template)        │
│ - Owns directive handlers for THIS game                     │
│ - Defines game-specific TContext                            │
│ - Processes SlinkyFrame directives                          │
└─────────────────────────────────────────────────────────────┘
                           ↓ imports
┌─────────────────────────────────────────────────────────────┐
│ PHASER LAYER (slinky-phaser) ← YOU ARE HERE                 │
│ - Reusable Phaser modules (VideoModule, ModalModule, etc.)  │
│ - BaseNarrativeScene (frame rendering)                      │
│ - SlinkyPlugin (coordinates Phaser integration)             │
│ - StoryAssetLoader (Phaser asset loading)                   │
└─────────────────────────────────────────────────────────────┘
                           ↓ imports
┌─────────────────────────────────────────────────────────────┐
│ CORE LAYER (slinky-core)                                    │
│ - StoryEngine (implements IStoryEngine, composes services)  │
│ - buildFrame() (static utility function)                    │
│ - DirectiveRegistry<TContext> (generic, game-owned)         │
│ - SaveModule (state management via IStoryEngine)            │
│ - Services: StoryStateManager, InkVariableManager, etc.     │
└─────────────────────────────────────────────────────────────┘
```

## What's Included

### Modules

Reusable Phaser components for building visual novels:

- **AnimationModule** - Animation management and coordination
  - Sprite animation sequences
  - Tween-based animations
  - Animation callbacks and events

- **AspectRatioModule** - Responsive aspect ratio handling
  - Automatic camera resizing
  - Maintains aspect ratio across devices
  - Supports multiple aspect ratio configurations

- **ChatWidgetModule** - Chat/messaging UI components
  - Message bubbles with sender/receiver styling
  - Typing indicators
  - Timestamps and metadata
  - Scrollable message history

- **ChoiceModule** - Choice rendering and selection
  - Button-based choice UI
  - Premium choice support (currency costs)
  - Grid layout for visual choices
  - Action sheets for native-style pickers

- **DialogModule** - Dialog box UI
  - Character name tags
  - Typewriter text effect
  - Portrait display
  - Shake effect for emphasis

- **InventoryModule** - Inventory system interface
  - Item tracking (key → quantity)
  - Currency/wallet management
  - Character closet/wardrobe system
  - Interface definition (game implements actual storage)

- **LayerModule** - Scene layer management
  - Z-index management for scene elements
  - Layer creation and cleanup
  - Depth sorting utilities

- **ModalModule** - Modal dialogs
  - Alert dialogs (single button)
  - Confirm dialogs (yes/no)
  - Action sheets (multiple options)
  - Text input dialogs
  - Number input dialogs
  - Grid select dialogs

- **ResponsiveThemeHelper** - Theme responsiveness utilities
  - Breakpoint-based styling
  - Dynamic theme switching
  - Device-specific adjustments

- **SceneTransitionModule** - Scene transition effects
  - Fade transitions
  - Crossfade between scenes
  - Slide transitions
  - Configurable duration and easing

- **ThemeModule** - Theme management
  - JSON-based theme definitions
  - Dynamic theme switching
  - Color scheme management
  - Font family configuration

- **VideoModule** - Video playback
  - Fullscreen video playback
  - Video sequences with pre-roll/post-roll
  - Looping support
  - Crossfade between videos
  - Layer-based video rendering

### Scenes

Base classes for building different narrative experiences:

- **BaseNarrativeScene** - Abstract base class for all narrative scenes
  - Frame processing and rendering
  - Module container management
  - Event handling
  - Lifecycle hooks
  - Input management

- **AvatarNarrativeScene** - Visual novel with character sprites
  - Full-screen character avatars
  - Character positioning (left/center/right)
  - Character animations and emotions
  - Background rendering
  - Dialog box with portraits

- **ChatNarrativeScene** - Messaging app style
  - Message bubble layout
  - Sender/receiver styling
  - Typing indicators
  - Scrollable conversation view

- **ProseNarrativeScene** - Book/text style
  - Page-based text display
  - Paragraph formatting
  - Typewriter effects
  - Scrollable text container

- **BootScene** - Initial loading scene
  - Asset loading progress
  - Loading bar UI
  - Error handling
  - Transition to main scene

### Asset Loading

- **StoryAssetLoader** - Asset loading for Ink stories
  - Automatic asset extraction from Ink content
  - CDN-based asset URLs
  - Critical asset identification
  - Background asset loading
  - Phaser loader integration

- **AssetExtractor** - Parse story content for asset references
  - Background images
  - Character avatars
  - Music tracks
  - Video files
  - SFX

- **UARAssetExtractor** - Universal Avatar Renderer asset extraction
  - Character sprite components
  - Outfit variations
  - Emotion states
  - Skin tones

### Plugin

- **SlinkyPlugin** - Phaser plugin for story integration
  - Story engine initialization
  - Scene coordination
  - Asset management
  - UAR character rendering
  - Settings and state management
  - Directive registry integration

### Video Components

- **VideoPlayer** - Video playback components
  - Sequence player (pre-roll + main + post-roll)
  - Crossfade support
  - Loop support
  - Event callbacks

## Installation

```bash
npm install @series-inc/slinky-phaser @series-inc/slinky-core phaser
```

## Usage

### Basic Setup

```typescript
import Phaser from 'phaser';
import { SlinkyPlugin, BootScene, AvatarNarrativeScene } from '@series-inc/slinky-phaser';

const config: Phaser.Types.Core.GameConfig = {
  type: Phaser.AUTO,
  width: 1920,
  height: 1080,
  scene: [BootScene, AvatarNarrativeScene],
  plugins: {
    global: [{
      key: 'SlinkyPlugin',
      plugin: SlinkyPlugin,
      start: true
    }]
  }
};

const game = new Phaser.Game(config);
```

### Scene Configuration

```typescript
class MyNarrativeScene extends AvatarNarrativeScene {
  constructor() {
    super({
      key: 'MyNarrativeScene',
      storyPath: '/stories/my-story.ink',
      themeConfig: myTheme,
      assetBaseUrl: '/cdn'
    });
  }
}
```

### Using Modules

```typescript
import { DialogModule, ChoiceModule, VideoModule } from '@series-inc/slinky-phaser';

class MyScene extends BaseNarrativeScene {
  create() {
    super.create();

    // Initialize modules
    this.dialogModule = new DialogModule(this, this.themeConfig);
    this.choiceModule = new ChoiceModule(this, this.themeConfig);
    this.videoModule = new VideoModule(this);

    // Use modules
    this.dialogModule.showDialog('Hello, world!', 'Character');
    this.choiceModule.showChoices(choices);
    this.videoModule.playVideo('/videos/intro.mp4');
  }
}
```

For a complete working example, see [basic-game](../../apps/basic-game).

## Architecture Notes

### Directive Handlers Belong in Game Layer

**Directive handlers belong in the game layer**, not in this package. Each game defines its own directive handlers using `DirectiveRegistry<TContext>` from `@series-inc/slinky-core`.

This allows games to:
- Define game-specific directives
- Customize directive execution
- Control the context type passed to handlers
- Keep game logic separate from the framework

Example from basic-game:

```typescript
import { DirectiveRegistry } from '@series-inc/slinky-core';
import { SceneUpdateDirectiveHandler } from './directives/SceneUpdateDirectiveHandler';

const registry = new DirectiveRegistry<GameContext>();
registry.register('SCENE_UPDATE', new SceneUpdateDirectiveHandler());
```

### Module vs Service Pattern

`slinky-phaser` uses a **module pattern** where each module is instantiated and owned by the scene. This differs from the service locator pattern used in earlier versions.

**Module Pattern** (current):
```typescript
class MyScene extends BaseNarrativeScene {
  dialogModule: DialogModule;

  create() {
    this.dialogModule = new DialogModule(this, config);
    this.dialogModule.showDialog(...);
  }
}
```

**Benefits**:
- Clear ownership and lifecycle
- Explicit dependencies
- No global state
- Easier to test

### Theme Configuration

Themes are JSON files that define colors, fonts, and layout for different screen sizes (breakpoints). Each module reads theme configuration relevant to its functionality.

Example theme structure:
```json
{
  "colors": {
    "primary": "#9B5DE5",
    "secondary": "#00BBF9"
  },
  "fonts": {
    "primary": "Arial, sans-serif"
  },
  "responsive": {
    "mobile": { "choices": { ... } },
    "tablet": { "choices": { ... } },
    "desktop": { "choices": { ... } }
  }
}
```

## Documentation

### For Developers & Contributors

- **[AGENTS.md](./AGENTS.md)** - Detailed guide for AI agents and developers working on slinky-phaser
  - Service testing patterns with Phaser mocks
  - Module architecture and best practices
  - Common workflows and pitfalls
- **[CONTRIBUTING.md](../../CONTRIBUTING.md)** - Contribution guidelines for the Slinky monorepo

### Related Documentation

- **[slinky-core](../slinky-core/README.md)** - Core narrative engine documentation
- **[basic-game](../../apps/basic-game/README.md)** - Reference implementation

---

## Build & Development

```bash
# Build the package
npm run build

# Watch mode for development
npm run dev

# Type checking
npm run typecheck

# Run tests
npm run test
```

## Dependencies

| Dependency | Purpose |
|---|---|
| `@series-inc/slinky-core` | Core narrative engine |
| `phaser` | Game framework (peer dependency) |
| `@series-inc/uar` | Universal Avatar Renderer |
| `bbcode-parser` | Rich text parsing |