### Complete Gallery Example Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/elements/built-in/gallery.en-US.mdx A comprehensive example demonstrating adding items (statically and dynamically), checking for items, removing items, and clearing the gallery within a single action sequence. ```typescript const gallery = new Gallery<{timestamp: number, description: string}>(); scene.action([ gallery.add("item1", { timestamp: Date.now(), description: "First item" }), gallery.add("item2", (ctx) => ({ timestamp: Date.now(), description: "Dynamically created item" })), Condition.If(gallery.has("item1"), [ "Item 1 is unlocked!", ]), gallery.remove("item1"), gallery.clear() ]); ``` -------------------------------- ### start Method Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/types/ITransition.en-US.mdx Starts the transition effect. An optional callback function can be provided to be executed upon completion of the transition. ```APIDOC ## start Method Start the transition effect. - `onComplete?: () => void` - Callback function that will be called when the transition is completed. > You can request animation by calling `Base.prototype.requestAnimation` if you extend the `Base` class. > > ```ts > super.requestAnimation({ > start: 0, > end: 1, > duration: this.duration > }, { > onComplete, > onUpdate: (value) => { > this.state.opacity = value; > } > }); > ``` ``` -------------------------------- ### Example Usage Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/player/hooks/useVoiceState.en-US.mdx An example demonstrating how to use the useVoiceState hook to control and display voice playback status. ```APIDOC ## Usage Example ```typescript import {useVoiceState} from "narraleaf-react"; function VoiceControls() { const {done, voice, playVoice, getVoiceSrc} = useVoiceState(); return (
{voice &&

Source: {getVoiceSrc() ?? "unknown"}

}
); } ``` ``` -------------------------------- ### Usage Example Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/player/hooks/usePreference.en-US.mdx Demonstrates how to use the usePreference hook to get and set the 'autoForward' preference. ```APIDOC ## Usage Example This hook is similar to the [useState](https://react.dev/reference/react/useState) hook. It returns a tuple containing the current value and a function to update the value. ### Import ```typescript import {usePreference} from "narraleaf-react"; ``` ### Component Example ```typescript function myComponent() { const [autoForward, setAutoForward] = usePreference("autoForward"); function triggerAutoForward() { setAutoForward(current => !current); } return (
Auto Forward: {autoForward ? "Enabled" : "Disabled"}
); } ``` ``` -------------------------------- ### start Method Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/types/ITransition.zh-CN.mdx Initiates the transition animation. An optional callback can be provided to execute code once the animation finishes. ```APIDOC ## Method: start(onComplete?: () => void): void ### Description Starts the transition effect. The `onComplete` callback is invoked when the transition finishes. ### Parameters * `onComplete` (function, optional) - A callback function to execute after the transition is completed. ### Example Usage (Extending Base Class) ```ts // When extending the Base class: super.requestAnimation({ start: 0, end: 1, duration: this.duration }, { onComplete, onUpdate: (value) => { this.state.opacity = value; } }); ``` ``` -------------------------------- ### Using color Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/types/WordConfig.en-US.mdx Example of how to set the color property for a word. ```APIDOC ## Setting color ### Description Sets the color of the word. ### Usage ```typescript new Word({ color: 'red', }); ``` ``` -------------------------------- ### Custom Gallery Service Example Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/elements/service.en-US.mdx An example of a custom service implementing a gallery with an 'add' action. It demonstrates state management (unlocked items) and serialization/deserialization. ```typescript type GalleryActions = { "add": [name: string] }; class Gallery extends Service { // custom data unlocked: string[] = []; constructor() { super(); // register the action handler this.on("add", (ctx: ServiceHandlerCtx, name: string) => { console.log("Adding", name); this.unlocked.push(name); }) } /* Implement the serialize and deserialize methods */ serialize(): Record | null { return { unlocked: this.unlocked }; } deserialize(data: Record): void { this.unlocked = data.unlocked; } /* Custom service logic */ add(name: string) { // trigger the action return this.trigger("add", name); } } ``` -------------------------------- ### Install NarraLeaf-React with npm, yarn, or pnpm Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/installation.en-US.mdx Use this command to install NarraLeaf-React and the required Motion library version in your project. ```bash npm install narraleaf-react motion@11 ``` ```bash yarn add narraleaf-react motion@11 ``` ```bash pnpm add narraleaf-react motion@11 ``` -------------------------------- ### Integrate AutoForwardButton in App Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/basic/manage-preferences.en-US.mdx This example shows how to integrate the `AutoForwardButton` component within your application's game player setup. Ensure `GameProviders` and `Player` components are correctly configured. ```tsx import { usePreference, Stage } from "narraleaf-react"; const story = /* your story here */; function App() { return (
{ liveGame.newGame(); }}> {/* Add the AutoForwardButton component here */}
); } ``` -------------------------------- ### Create a Scene with Actions in TypeScript Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/index.en-US.mdx Define a scene with a sequence of actions including background changes, character introductions, dialogue, and interactive menus. This example demonstrates scene setup and basic narrative flow. ```typescript scene.action([ scene.background.char("/bg_park.png", new Dissolve(500)), "The sun is shining gently through the trees.", "It's already 9 AM, and I somehow woke up feeling more refreshed than usual.", Emma.show({ duration: 500 }) .darken(0.3, 500, "easeIn") .char("emma_happy.png"), E`Good morning, Alex!`, "A girl stands beside me, cheerful as ever.", "I'm not sure how she does it, but Emma always seems to be in a good mood.", A`Emma, how many times have I ${c("TOLD", "#Ff0000")} you not to sneak into my morning walks unannounced?`, E`You left the door open—how could I resist?`, Menu.prompt("What should I do?") .choose("Want to go grab some breakfast?", [ E`Really? You're finally inviting me out? Let's go then!`, ]) .choose("Too early. Let's chill here a bit.", [ E`Ugh, you're always so boring in the morning.`, E`But fine, let's sit. I actually brought something to show you.`, ]), ]); ``` -------------------------------- ### Example: Position with Alignments Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/types/RawPosition.en-US.mdx Demonstrates creating a RawPosition using xalign and yalign, which represent percentages. ```typescript const position: RawPosition = { xalign: 0.5, // x: 50% yalign: 0.3, // y: 30% }; ``` -------------------------------- ### Page with Layout Example Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/player/page-router/page.en-US.mdx Demonstrates nesting Page components within a Layout to define routes like '/user' and '/user/profile'. ```tsx import { Layout, Page } from "narraleaf-react"; {/* /user */} {/* /user/profile */} ``` -------------------------------- ### Full Custom Dialog Example with Styling and State Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/solutions/custom-dialog.en-US.mdx A comprehensive example demonstrating a custom dialog with background images, conditional nametag visibility using isNarrator, and a typing-complete indicator using the 'done' state from useDialog. It also includes a sub-component for sentence context. ```tsx import { Dialog, Nametag, Texts, useDialog } from "narraleaf-react"; import clsx from "clsx"; // Sub-component: show triangle/underline when typing is done function SentenceContext() { const { done } = useDialog(); return ( <>
); } export function GameDialog() { const { isNarrator } = useDialog(); return (
); } ``` -------------------------------- ### Using className Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/types/WordConfig.en-US.mdx Example of how to set the className property when creating a new Word instance. ```APIDOC ## Setting className ### Description Applies a CSS class to the word for styling purposes. ### Usage ```typescript new Word({ className: 'bold', }); ``` ``` -------------------------------- ### Access Gallery Service and Items Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/player/hooks/useLiveGame.en-US.mdx Demonstrates how to get the 'gallery' service from the live game object and retrieve all items using the $getAll method. ```typescript function GalleryComponent() { const liveGame = useLiveGame(); const gallery = liveGame.story?.getService>("gallery"); if (gallery) { const allItems = gallery.$getAll(); return (
{Object.keys(allItems).map(name => (
{name}
))}
); } return null; } ``` -------------------------------- ### Basic Player Component Setup Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/player.en-US.mdx This snippet shows how to set up and render the Player component within GameProviders. It initializes a new game upon player readiness and sets the player's dimensions. ```tsx "use client"; import { GameProviders, Player } from "narraleaf-react"; import { useState } from "react"; import { story } from "./my-story"; export default function Page() { return ( { liveGame.newGame(); }} width="100vw" height="100vh" /> ); } ``` -------------------------------- ### Key Binding Example Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/types/KeyBindingType.en-US.mdx Demonstrates how to use KeyBindingType to set, modify, or remove key bindings for actions within the game's key map. ```APIDOC ## Example ```typescript // Change the skip action key to F3 game.keyMap.setKeyBinding(KeyBindingType.skipAction, "F3"); // Bind both Control and F3 to skipAction game.keyMap.setKeyBinding(KeyBindingType.skipAction, ["Control", "F3"]); // Remove the binding game.keyMap.setKeyBinding(KeyBindingType.skipAction, null); ``` ``` -------------------------------- ### Example: Position with Coordinates Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/types/RawPosition.en-US.mdx Shows how to define a RawPosition using absolute x and y coordinates. ```typescript const position = { x: 100, // x: 100px y: "50%", // y: 50% }; ``` -------------------------------- ### Example Component Usage Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/types/Components.en-US.mdx Illustrates how to use the `Components` type to create a functional component named `component` that accepts a `text` prop. ```typescript const component: Components<{ text: string }> = ({ text }) =>
{text}
; ``` -------------------------------- ### Accessing Services with useLiveGame Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/player/hooks/useLiveGame.en-US.mdx Example of using useLiveGame to access and interact with a 'gallery' service within the live game object. ```APIDOC ## Accessing Services ```typescript function GalleryComponent() { const liveGame = useLiveGame(); const gallery = liveGame.story?.getService>("gallery"); if (gallery) { const allItems = gallery.$getAll(); return (
{Object.keys(allItems).map(name => (
{name}
))}
); } return null; } ``` ``` -------------------------------- ### Accessing Game State with useLiveGame Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/player/hooks/useLiveGame.en-US.mdx Example of using useLiveGame to display the current scene name and game state. ```APIDOC ## Accessing Game State ```typescript function GameStatusComponent() { const liveGame = useLiveGame(); return (

Current Scene: {liveGame.scene?.name}

Game State: {liveGame.state}

); } ``` ``` -------------------------------- ### Create a Horizontal Menu Layout Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/solutions/custom-menu.en-US.mdx This example demonstrates how to create a custom menu with a horizontal layout using flexbox properties on the `GameMenu` container. ```tsx function HorizontalMenu({ items }: { items: number[] }) { return ( {items.map((index) => ( ))} ); } ``` -------------------------------- ### Define Layouts and Pages with RouterProvider Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/player/page-router/router.en-US.mdx Set up the routing structure for your application using RouterProvider, RootLayout, Layout, and Page components. This example demonstrates how to define nested routes for home and about sections. ```tsx import { RouterProvider, RootLayout, Layout, Page, useRouter } from "narraleaf-react"; function MyPages() { return ( {/* /home */} {/* default page: /home */} {/* /home/detail */} {/* /about */} ); } ``` -------------------------------- ### Example Usage of ChainedActions Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/types/ChainedActions.en-US.mdx Illustrates how to construct an array of ChainedActions, including sequential 'say' actions for a character and a 'jumpTo' action for a scene. ```typescript [ character1 .say("Hello") .say("World"), scene1 .jumpTo(scene2), character2 .say("World") ] satisfies ChainedActions; ``` -------------------------------- ### Complete Story Example: React Page Integration Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core.en-US.mdx Demonstrates how to integrate the previously defined story into a React application. This includes setting up `GameProviders` and the `Player` component, and initiating a new game. ```tsx "use client"; import { Game, GameProviders, Player } from "narraleaf-react"; import { useState } from "react"; import { story } from "./story"; export default function App() { return ( { // start the game when the Player is ready game.getLiveGame().newGame(); }} height={"100vh"} /> ); } ``` -------------------------------- ### Video Initialization and Usage Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/elements/video.en-US.mdx Demonstrates how to create a new Video instance, configure its source and playback, and integrate it into a scene's actions. ```APIDOC ## Video Initialization ### Description Initializes a new Video element with specified configuration. ### Constructor `new Video(config: Partial)` - **config** (`Partial`) - Optional configuration object for the video. - **src** (`string`) - Required - The URL of the video file. - **muted** (`boolean`) - Optional - Whether the video should start muted. Defaults to `false`. ### Example ```typescript const video = new Video({ src: "https://example.com/video.mp4", muted: true, }); ``` ## Video Chainable Methods ### show #### Description Displays the video element. #### Method `video.show()` ### hide #### Description Hides the video element. #### Method `video.hide()` ### play #### Description Plays the video and waits for it to finish. #### Method `video.play()` ### Example Usage in Scene ```typescript scene.action([ video .show() .play() .hide(), ]); ``` ``` -------------------------------- ### Create Auto Forward Toggle Button Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/basic/manage-preferences.en-US.mdx Use the `usePreference` hook to get and set the 'autoForward' preference. This example demonstrates creating a button that toggles the auto-forward setting. ```tsx function AutoForwardButton() { const [autoForward, setAutoForward] = usePreference("autoForward"); function triggerAutoForward() { setAutoForward(current => !current); } return (
Auto Forward: {autoForward ? "Enabled" : "Disabled"}
); } ``` -------------------------------- ### Create a Bouncing Animation Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/animation/transform.en-US.mdx This example demonstrates creating a bouncing animation by chaining position changes and committing each step with specific durations and easing. ```typescript import { Transform } from "narraleaf-react"; const bounce = Transform.create() .position({ yoffset: -10 }) .commit({ duration: 120, ease: "easeOut" }) .position({ yoffset: 0 }) .commit({ duration: 100, ease: "easeOut" }) .repeat(2); scene.action([ characterImage.transform(bounce), ]); ``` -------------------------------- ### Requesting Animation in Base Class Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/types/ITransition.en-US.mdx Example of how to request an animation using `requestAnimation` when extending the `Base` class. This is typically done within the `start` method of a custom transition. ```typescript super.requestAnimation({ start: 0, end: 1, duration: this.duration }, { onComplete, onUpdate: (value) => { this.state.opacity = value; } }); ``` -------------------------------- ### Advanced Custom Menu with Styling and Pointer Events Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/solutions/custom-menu.en-US.mdx This example demonstrates an advanced custom menu with complex styling, including clip-path for shapes and drop-shadow effects. It also manages pointer events to ensure only the menu area is interactive. ```tsx import { GameMenu, Item } from "narraleaf-react"; function CustomMenu({ items }: { items: number[] }) { return (
{/* pointer-events-auto: only the menu box is interactive */}
{items.map((index) => ( ))}
); } ``` -------------------------------- ### Initialize a Sound Instance Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/basic/sound.en-US.mdx Create a new Sound instance with specified source, volume, loop, and sync properties. Ensure the src points to a valid sound file URL. ```typescript const sound = new Sound({ src: "https://YOUR_SOUND_URL.mp3", volume: 0.5, // 0.0 to 1.0 loop: true, // loop the sound sync: false, // do not wait for the sound to finish }); ``` -------------------------------- ### Initialize and Play Video Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/elements/video.en-US.mdx Demonstrates how to create a new Video instance with a source and play it within a scene action. Ensure the video source is valid. ```typescript const video = new Video({ src: "https://example.com/video.mp4", muted: true, }); scene.action([ video .show() .play() .hide(), ]); ``` -------------------------------- ### $get Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/elements/built-in/gallery.en-US.mdx Get the metadata of a specific item from the gallery by its name. ```APIDOC ## $get ### Description Get the metadata of an item. ### Method ```typescript gallery.$get(name: string): Metadata | undefined ``` ### Parameters #### Arguments - **name** (string) - Required - The name of the item to get the metadata of ### Returns - `Metadata | undefined` - The metadata of the item ``` -------------------------------- ### Gallery Service Initialization and Registration Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/elements/built-in/gallery.en-US.mdx Demonstrates how to create a new Gallery instance with custom metadata and register it with the story service. ```APIDOC ## Gallery Service Initialization and Registration ### Description Initialize a new Gallery instance and register it with the story service to make it accessible throughout the game. ### Code ```typescript import { Gallery } from "narraleaf-react"; // Define metadata type for gallery items interface CgMetadata { timestamp: number; description: string; } // Create a new Gallery instance const gallery = new Gallery(); // Register the gallery service with the story story.registerService("gallery", gallery); ``` ``` -------------------------------- ### Create and Register a Game Plugin Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/plugin.en-US.mdx Example of a plugin that logs a message on game initialization and cleans up on unregistration. The register method is invoked during game initialization, and unregister is called when the game is destroyed. ```typescript import { Game, IGamePluginRegistry, LiveGameEventToken } from "narraleaf-react"; let listenerToken: LiveGameEventToken; const plugin: IGamePluginRegistry = { name: "test_plugin", register: (game: Game) => { // This logic executes once the game is initialized // and before the player component is rendered listenerToken = game.hooks.hook("init", () => { console.log("Game initialized"); }); }, unregister: (game: Game) => { // This logic executes when the game is disposed // and before the player component is unmounted listenerToken.cancel(); } }; ``` -------------------------------- ### Registering a Service Action Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/elements/service.en-US.mdx Shows how to register a custom action handler for a service using the `on` method, typically within the constructor. This example registers an action named 'myAction'. ```typescript class MyCustomService extends Service { constructor() { super(); this.on("myAction", (ctx: ServiceHandlerCtx, ...args: any[]) => { // custom logic }); } } ``` -------------------------------- ### Image Initialization with Wearables Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/types/ImageConfig.en-US.mdx Demonstrates three methods for initializing an Image with child wearables. Method 1 uses the constructor with a wearables array. Method 2 uses the addWearable method. Method 3 uses the bindWearable method. ```typescript // method 1 const child = new Image({ isWearable: true, /* ... */ }); const parent = new Image({ src: "parent/image/src", wearables: [child] }); ``` ```typescript // method 2 const child = new Image(/* ... */); const parent = new Image(/* ... */).addWearable(child); ``` ```typescript // method 3 const parent = new Image(/* ... */); const child = new Image(/* ... */).bindWearable(parent); ``` -------------------------------- ### Complete Story Example: Story Definition Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core.en-US.mdx Provides a comprehensive example of defining a story, including scenes, characters, and actions. This serves as a template for creating your own interactive narratives. ```ts import { Story, Scene, Character, } from "narraleaf-react"; // Create a story const story = new Story("My Story"); const scene1 = new Scene("Scene 1", { background: { url: "https://via.placeholder.com/1920x1080" }, }); // define your characters const character1 = new Character("Character 1"); const character2 = new Character("Character 2"); // add actions to the scene scene1.action([ character1 .say("Hello World!") .say("Welcome to NarraLeaf!") .say("This is a Visual Novel framework for React.") .say("I hope you enjoy it!"), character2 .say("Start your story by editing this file.") .say("We have a lot of features for you."), ]); // add the scene to the story story.entry(scene1); export { story }; ``` -------------------------------- ### Menu Constructor with String Prompt and Actions Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/elements/menu.en-US.mdx Demonstrates creating a Menu and adding a choice where the prompt is a simple string and actions are provided as an array. ```typescript new Menu("what should I do?") .choose("go left", [ character1.say("I went left"), ]) ``` -------------------------------- ### configure(config) Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/game/game.en-US.mdx Configures the game with specified settings. Best used before game initialization. ```APIDOC ## configure(config) ### Description Assigns a new configuration to the game. This method is intended for use before the game is initialized. Settings applied after initialization may not take effect immediately, except for preferences. ### Method ```javascript configure(config: GameConfig): void ``` ### Parameters - `config` (GameConfig) - An object containing game configuration options. ### Request Example ```typescript const { game } = useGame(); useEffect(() => { game.configure({ ratioUpdateInterval: 0, // update the player size immediately cursor: "cursor.jpeg", cursorHeight: 60, cursorWidth: 60, }); }, []); ``` ``` -------------------------------- ### get Method Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/game/storable/namespace.en-US.mdx Retrieves the value associated with a specific key from the namespace. ```APIDOC ## get ### Description Retrieves the value associated with a specific key from the namespace. ### Parameters - **key** (Key) - Required - The key of the value to get ### Returns - `T[Key]` - The value associated with the key. ``` -------------------------------- ### entry Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/elements/story.en-US.mdx Sets the initial scene for the story to begin execution. ```APIDOC ## entry ### Description Sets the entry point scene for the story. ### Parameters #### Path Parameters - **scene** (Scene) - Required - The first scene to be executed. ### Returns - `this` ``` -------------------------------- ### Scene Constructor Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/elements/scene.en-US.mdx Initializes a new Scene instance with a given name and optional configuration. ```APIDOC ## constructor ### Description Initializes a new Scene instance. ### Parameters - **name** (string) - Required - Name of the scene - **config** (Partial) - Optional - Configuration object for the scene ``` -------------------------------- ### $getAll Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/elements/built-in/gallery.en-US.mdx Get all items currently in the gallery, returned as a record of item names to their metadata. ```APIDOC ## $getAll ### Description Get all items in the gallery. ### Method ```typescript gallery.$getAll(): Record ``` ### Returns - `Record` - All items in the gallery ``` -------------------------------- ### Registering and Accessing Services Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/elements/service.en-US.mdx Demonstrates how to register a service with the story and access it later via the game context. ```APIDOC ## Registering and Accessing Services ### Description Register a service with the story instance and access it later through the game context. ### Usage **Registering a service:** ```typescript const story = new Story(/* ... */); story.registerService("gallery", gallery); ``` **Accessing a service in a component:** ```tsx // ex. in a component const {game} = useGame(); const liveGame = game.getLiveGame(); const gallery = liveGame.story?.getService("gallery"); return ( {gallery && gallery.unlocked.map((name) => (
{name}
))} ); ``` ``` -------------------------------- ### Import Layer Class Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/elements/layer.en-US.mdx Import the Layer class from the narraleaf-react library to start using it. ```typescript import {Layer} from "narraleaf-react"; ``` -------------------------------- ### Open Settings Overlay from Quick Menu Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/solutions/page-overlay-settings.en-US.mdx Use the `useRouter` hook in a component like the Quick Menu to navigate to the settings overlay path using `router.navigate('/settings')`. ```tsx import { useRouter } from "narraleaf-react"; function QuickMenu() { const router = useRouter(); const openSettings = () => router.navigate("/settings"); // Navigate to settings overlay return (
); } ``` -------------------------------- ### Get All Items from Gallery Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/elements/built-in/gallery.en-US.mdx Retrieves all items currently in the gallery as a record of item names to their metadata. ```typescript const allItems = gallery.$getAll(); console.log("All items:", allItems); ``` -------------------------------- ### Create Menu Choices with Actions Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/types/MenuChoice.en-US.mdx Demonstrates how to create menu choices using the Menu.prompt and .choose methods. Each choice has a text prompt and an array of actions to execute when selected. Supports plain text and styled text prompts. ```typescript Menu.prompt("What should I do?") /** * option: "Go left" * action: say "I went left" and jump to scene2 */ .choose("Go left", [ character1.say("I went left"), scene1.jumpTo(scene2) ]) /** * option: "Go right" with red color * action: say "I went right" */ .choose(Sentence([ "Go", new Word("right", {color: "#ff0000"}) ]), [ character1.say("I went right") ]) ``` -------------------------------- ### get Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/elements/persistent.en-US.mdx An alias for `toWord`, retrieves a state value as a dynamic word for use in text outputs. ```APIDOC ## get>() ### Description Alias of `toWord` ### Parameters - **key** (K) - the key of the state ### Returns - `Word` ### Request Example ```typescript character.say`You have ${persis.get("coin")} coins`; ``` ``` -------------------------------- ### Menu Constructor with Sentence and Action Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/elements/menu.en-US.mdx Shows how to instantiate a Menu and add a choice using a Sentence object for the prompt and an array of actions. ```typescript new Menu("what should I do?") .choose(new Sentence("go left"), [ character1.say("I went left"), ]) ``` -------------------------------- ### CommonPosition Example Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/types/IPosition.en-US.mdx Instantiate CommonPosition with predefined position types. Ensure the CommonPosition type is imported. ```typescript import {CommonPosition} from "narraleaf-react"; // x: 66.67%, y: 50% new CommonPosition(CommonPosition.Positions.Right) ``` -------------------------------- ### Create NarraLeaf-React Project Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/quick-start.en-US.mdx Use this command to generate a new React app with the NarraLeaf-React template. This sets up the basic project structure. ```bash npx nlr-skeleton@latest my-project ``` -------------------------------- ### ruby Property Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/types/WordConfig.zh-CN.mdx The `ruby` property is used to display ruby text, useful for phonetic guides. ```APIDOC ## ruby The `ruby` property is used to display ruby text. This is useful for displaying phonetic guides for Chinese characters. ``` -------------------------------- ### Example: Position with Alignments and Offsets Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/types/RawPosition.en-US.mdx Defines a RawPosition using alignments and additional x/y offsets for fine-tuning. ```typescript const position = { xalign: 0.5, // x: 50% + 10px yalign: 0.3, // y: 30% + 20px xoffset: 10, yoffset: 20, }; ``` -------------------------------- ### Story Creation: Entry Point Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core.en-US.mdx Demonstrates how to create a new Story instance with a name and set an entry point scene for it. This is the initial step in defining a narrative flow. ```typescript import {Story,Scene} from "narraleaf-react"; const story = new Story("My First NarraLeaf Story"); // a human-readable name ``` ```typescript const scene1 = new Scene("scene1", {}); story.entry(scene1); ``` -------------------------------- ### FadeIn Constructor Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/animation/transition/fade-in.en-US.mdx Initializes a FadeIn transition with specified duration, starting position, and optional easing function. ```APIDOC ## constructor ### Description Initializes a FadeIn transition. ### Parameters #### Parameters - **duration** (number) - Required - The duration of the transition in milliseconds. - **startPos** ([xOffset: number, yOffset: number]) - Required - The starting position of the image, default is `[0, 0]`. For example, `[50, 50]` will start the image 50 pixels to the right and 50 pixels up. - **easing** (TransformDefinitions.EasingDefinition) - Optional - The easing function to use for the transition. ``` -------------------------------- ### Initialize game hook Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/game/hooks.en-US.mdx This hook is called when the game is initialized, before the player has rendered. Use it for setup tasks. ```typescript game.hooks.hook("init", () => { console.log("let's do something cool here"); }); ``` -------------------------------- ### Create a Gallery Instance Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/elements/built-in/gallery.en-US.mdx Instantiate a new Gallery service. Metadata can be defined with a specific type, like a timestamp. ```typescript const gallery = new Gallery<{timestamp: number}>(); ``` -------------------------------- ### Query Parameter Helpers Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/player/page-router/router.en-US.mdx Manage query parameters using helper methods for setting, getting, removing, and clearing them. ```tsx router.setQueryParam("lang", "en"); router.getQueryParam("lang"); // "en" router.removeQueryParam("lang"); router.setQueryParams({ tab: "general", theme: "dark" }); router.clearQueryParams(); ``` -------------------------------- ### Namespace Constructor Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/game/storable/namespace.en-US.mdx Initializes a new Namespace instance. The key defaults to the name if not provided. ```APIDOC ## constructor ### Description Initializes a new Namespace instance. ### Parameters - **name** (string) - Required - Human-readable name of the namespace - **initContent** (T) - Required - Initial content of the namespace - **key** (string) - Optional - The namespace key, default is the name ``` -------------------------------- ### Get Game Preference Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/game/preference/preference.en-US.mdx Retrieve the current value of a specific game preference. This is useful for checking the state of a setting. ```typescript const autoForward = game.preference.getPreference("autoForward"); ``` -------------------------------- ### Using Custom Gallery Service in a Scene Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/elements/service.en-US.mdx Demonstrates how to instantiate and use a custom service within a scene, chaining actions for sequential execution. ```typescript const gallery = new Gallery(); myScene.action([ gallery .add("image1") .add("image2") .add("image3"), ]); ``` -------------------------------- ### Story Constructor Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/elements/story.en-US.mdx Initializes a new Story instance with a given name and optional configuration. ```APIDOC ## constructor Story ### Description Initializes a new Story instance. ### Parameters #### Path Parameters - **name** (string) - Required - Name of the story - **config** (IStoryConfig) - Optional - Configuration object for the story. See [IStoryConfig](../types/IStoryConfig). ### Returns - `this` ``` -------------------------------- ### Get All Key Bindings - Core Game API Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/game/key-map.en-US.mdx Retrieves all currently defined key bindings within the KeyMap. ```typescript game.keyMap.getKeyBindings(); ``` -------------------------------- ### Get Key Binding - Core Game API Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/game/key-map.en-US.mdx Retrieve the current key binding for a given action type. ```typescript const current = game.keyMap.getKeyBinding(KeyBindingType.skipAction); ``` -------------------------------- ### Public Method: constructor Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/elements/sound.en-US.mdx Constructor for the Sound class, with two overloads. ```APIDOC ## Public Method ### constructor #### Overload 1 of 2 - `config?: Partial` - See [ISoundUserConfig](../types/ISoundUserConfig) #### Overload 2 of 2 - `src?: string` - The source of the sound ``` -------------------------------- ### Unlock CG in Story Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/solutions/gallery-service-localstorage.en-US.mdx Example of adding a new item to the gallery service, typically triggered by an in-game event. ```typescript scene.action([ narrator.say("You discovered a beautiful sunset."), gallery.add("cg_sunset", { url: "/images/cg/sunset.png", title: "Sunset", unlockedAt: Date.now(), }), narrator.say("Added to gallery."), ]); ``` -------------------------------- ### Menu Constructor Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/elements/menu.en-US.mdx Initializes a new Menu instance with various overloads for prompts and configurations. ```APIDOC ## Menu Constructor ### Description Initializes a new Menu instance. ### Parameters #### Path Parameters - **prompt** (SentencePrompt) - Required - See [SentencePrompt](../types/SentencePrompt) - **config?** (MenuConfig) - Optional - [MenuConfig](../types/MenuConfig) #### Overload 2 of 5 - **prompt** (Sentence) - Required - The prompt of the menu, See [Sentence](./character/sentence) - **config?** (MenuConfig) - Optional - [MenuConfig](../types/MenuConfig) #### Overload 3 of 5 - **prompt** (SentencePrompt | Sentence) - Required - The prompt of the menu - **config** (MenuConfig) - Required - [MenuConfig](../types/MenuConfig) #### Overload 4 of 5 - **prompt** (null) - Required - No prompt for the menu - **config?** (MenuConfig) - Optional - [MenuConfig](../types/MenuConfig) #### Overload 5 of 5 - **prompt** (SentencePrompt | Sentence | null) - Required - The prompt of the menu - **config** (MenuConfig) - Required - [MenuConfig](../types/MenuConfig) ``` -------------------------------- ### Create and Use a Namespace with Storable Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/game/storable.en-US.mdx Demonstrates initializing a new namespace, adding it to the Storable, and then setting and retrieving data within that namespace. Ensure the `Namespace` class is imported and a `storable` instance is obtained from the live game. ```typescript type Player1Content = { name: string; }; const storable = game.getLiveGame().getStorable(); // initialize a new namespace const player1namespace = new Namespace("player1", { name: "default name" }); storable.addNamespace(player1namespace); // set data from the namespace const namespace = storable.getNamespace('player1'); namespace.set('name', 'John Doe'); // get data from the namespace const name = namespace.get('name'); console.log(name); // John Doe ``` -------------------------------- ### Define Layout and Page Structure for Overlays Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/solutions/page-overlay-settings.en-US.mdx Set up the `RootLayout` with nested `Layout` and `Page` components to define routes for the main game stage and overlay pages like settings. ```tsx import { RootLayout, Layout, Page, Player } from "narraleaf-react"; function AppLayout() { return ( {/* Default page (game stage) - path: / */} {/* Settings overlay - path: /settings, /settings/general, etc. */} {/* /settings - settings entry or default tab */} {/* /settings/general - general settings */} {/* /settings/audio - audio settings */} ); } ``` -------------------------------- ### Example: Using Common Position Enum Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/types/RawPosition.en-US.mdx Illustrates using a predefined common position from an enum or similar structure. ```typescript const position = CommonPosition.Positions.Left; // x: 33.3%, y: 50% ``` -------------------------------- ### Get Game History Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/game/live-game.en-US.mdx Retrieve the game history to create a backlog. The history items can be used to undo specific actions. ```typescript import { useGame, GameHistory } from "narraleaf-react"; ``` ```typescript const game = useGame(); const history = game.getHistory(); function handleUndo(history: GameHistory) { game.undo(history.token); } return (

Backlog

{history.map((item) => (
handleUndo(item)} > {/* show the action text */} {/* text is available when the action is "say" or "menu" */} {item.element.text}
))}
); ``` -------------------------------- ### Get Item Metadata from Gallery Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/elements/built-in/gallery.en-US.mdx Retrieves the metadata of a specific item from the gallery by its name. Returns undefined if the item does not exist. ```typescript const metadata = gallery.$get("item"); console.log(metadata?.timestamp); ``` -------------------------------- ### Implement Settings Page Component Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/solutions/page-overlay-settings.en-US.mdx Create a settings page component that functions as an overlay. Use `useRouter` to handle closing the overlay by navigating back when the backdrop or close button is clicked. Prevent the overlay from closing when the panel content is clicked. ```tsx import { useRouter } from "narraleaf-react"; function SettingsGeneral() { const router = useRouter(); return (
router.back()} // Click overlay to close >
e.stopPropagation()} // Prevent closing when clicking panel >

General Settings

{/* Settings form content */}
); } ``` -------------------------------- ### Basic Custom Service Implementation Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/elements/service.en-US.mdx Illustrates the fundamental structure for creating a custom service by extending the base `Service` class and implementing `serialize` and `deserialize` methods. ```typescript class MyCustomService extends Service { /** * Serialize the service to data * * **Note**: data must be JSON serializable, return null if nothing needs to be saved */ serialize(): Record | null { return null; } /** * Load data to the service * @param data data exported from toData */ deserialize(data: Record): void { } } ``` -------------------------------- ### Preference Constructor Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/game/preference/preference.en-US.mdx Initializes the Preference manager with default settings. ```APIDOC ## constructor ### Description Initializes the Preference manager with default settings. ### Parameters #### Path Parameters - **settings** (T) - Required - The default preference settings ``` -------------------------------- ### Using cps Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/core/types/WordConfig.en-US.mdx Example of how to set the cps (characters per second) property to control typing speed for a specific word. ```APIDOC ## Setting cps ### Description Controls the typing speed for a specific word by setting characters per second. ### Usage ```typescript new Word({ cps: 10, // 10 characters per second }); ``` ``` -------------------------------- ### Query Parameter Helpers Source: https://github.com/narraleaf/react.narraleaf.com/blob/master/pages/documentation/player/page-router/router.en-US.mdx Includes methods for setting, getting, removing, and clearing query parameters, as well as checking for their existence and counting them. ```APIDOC ## Query Helpers ### Description Provides utilities for manipulating and querying URL parameters. ### Methods - `setQueryParam(key: string, value: string)`: Sets a single query parameter. - `getQueryParam(key: string)`: Retrieves the value of a specific query parameter. - `removeQueryParam(key: string)`: Removes a query parameter. - `setQueryParams(params: Record)`: Merges multiple query parameters. - `clearQueryParams()`: Removes all query parameters. - `hasQueryParam(key: string)`: Checks if a query parameter exists. - `getQueryParamKeys()`: Returns an array of all query parameter keys. - `getQueryParamCount()`: Returns the total number of query parameters. ### Examples ```typescript router.setQueryParam("lang", "en"); router.getQueryParam("lang"); // "en" router.removeQueryParam("lang"); router.setQueryParams({ tab: "general", theme: "dark" }); router.clearQueryParams(); ``` ```