chaley logo

MENU

HomeDocsChangelog
Skip to documentation

Developer documentation

Chaley Walkthrough documentation

Chaley Walkthrough is an open-source JavaScript onboarding library for building audio-guided product tours and interactive walkthroughs. Supply a narration file and a timeline of element IDs; Chaley synchronizes highlights, captions, scrolling and optional interactions with the recording.

Visitors can listen, pause, resume, seek, replay and stop using the built-in floating player. Developers control the timeline, appearance and actions. There are no runtime dependencies, accounts, hosted services or telemetry.

Current version: 0.1.0. This guide documents the complete current API. Pin this version for reproducible installations. Subsequent changes are recorded in the changelog.

Package on npm | MIT license

Install

In your application directory:

npm install chaley-walkthrough

To pin the version documented here:

npm install [email protected]

Import both the class and its required stylesheet:

import { Walkthrough } from "chaley-walkthrough";
import "chaley-walkthrough/style.css";

Import CSS once in your application entry or global styles entry. The package includes TypeScript declarations, an ES module build and a browser script build. CommonJS require() is not provided. For plain HTML without a bundler, see Direct script tags.

Quick start

Build your first audio-guided tour in JavaScript. This example assumes your application uses a JavaScript bundler. Add uniquely identified elements to an existing page:

<button id="start-tour" type="button">Show me around</button>
<section id="overview">Your overview</section>
<button id="settings" type="button">Settings</button>

Serve your recording at /audio/welcome.mp3. In tools with a public directory this usually means placing it at public/audio/welcome.mp3. Run this code after those elements have mounted:

import { Walkthrough } from "chaley-walkthrough";
import "chaley-walkthrough/style.css";

const tour = new Walkthrough({
  audio: "/audio/welcome.mp3",
  trigger: "#start-tour",
  timeline: [
    { time: 0, target: null, caption: "Welcome. Let's look around." },
    { time: 3, target: "#overview", caption: "Here is your overview." },
    { time: 8, target: "#settings", caption: "Your settings are here." },
    { time: 12, target: null, caption: "You're ready to get started." },
  ],
});

tour.on("error", (issue) => {
  console.warn(`[${issue.code}] ${issue.message}`);
});

// When this page/component is removed, call:
// tour.destroy();

Click Show me around to start. The configured trigger handles playback; no extra click listener is needed. Use a recording longer than the final cue and replace sample timestamps with those from your own recording. A null target leaves the player and narration running without a highlight.

To manage starting yourself, omit trigger and call tour.start() from your own button handler, catching its promise as shown in Playback API and events. Start from a real user gesture so the browser can permit audio.

How a walkthrough works

Each instance owns one audio recording and one timeline. Construction validates and copies the configuration and binds the optional trigger; media and visuals are created lazily. The recording is the authoritative clock. Chaley selects the latest cue at or before its position and keeps it active until the next cue or completion. An empty timeline provides audio/player controls without highlights.

Only one session is active per document, including paused sessions. Starting another walkthrough stops the previous one, which remains reusable. Scrolling does not pause narration. Seeking selects a cue but does not execute actions or reconstruct earlier menu/dialog state.

import { Walkthrough } from "chaley-walkthrough";
import "chaley-walkthrough/style.css";

// Initialise after the trigger and initial targets have mounted.
const tour = new Walkthrough({
  audio: "/audio/tour.mp3",
  timeline: [
    { time: 0, target: null, caption: "Welcome." },
    { time: 3.5, target: "#wallet" },
  ],
});

Module imports are safe without window or document. Construct instances only in the browser. Each instance owns a deeply frozen copy of its configuration. The original object is not frozen or modified. Editing it after construction will not update the tour. Destroy and recreate the instance to change audio, timeline or configuration; CSS custom properties can change live. There is no public manager or configuration array.

Direct script tags

After installation, copy chaley-walkthrough.iife.js and style.css from node_modules/chaley-walkthrough/dist/ into your site's served assets, for example /vendor/chaley-walkthrough/. Use matching files from the same version. Load initialization after the relevant elements:

<link rel="stylesheet" href="/vendor/chaley-walkthrough/style.css" />
<button id="start-tour" type="button">Show me around</button>
<section id="overview">Your overview</section>
<script src="/vendor/chaley-walkthrough/chaley-walkthrough.iife.js"></script>
<script>
  const tour = new ChaleyWalkthrough.Walkthrough({
    audio: "/audio/tour.mp3",
    trigger: "#start-tour",
    timeline: [{ time: 0, target: "#overview", caption: "Welcome." }],
  });
  tour.on("error", (issue) => console.warn(issue.code, issue.message));
</script>

The browser bundle exposes ChaleyWalkthrough.Walkthrough with the same API as ESM. Call tour.start() from a user gesture and handle its promise. CSS is separate; CommonJS is not provided. Serve the page and audio through your web server. The vendor paths above are URLs you create, not automatically exposed npm import paths. If your Content Security Policy blocks inline scripts, use an allowed external initialization script.

Configuration reference

All timestamps are seconds; transition and hold durations are milliseconds; theme padding and radius are pixels. Per-cue scroll, effect, transition and transitionDuration override defaults. Theme and player configuration apply to the whole instance.

This example shows every top-level group. Provide matching elements and application handlers for the IDs:

const tour = new Walkthrough({
  audio: "/audio/product-tour.mp3",
  trigger: "#start-product-tour",
  allowActions: true,
  theme: {
    overlayOpacity: 0.15,
    highlightColor: "#7c3aed",
    padding: 8,
    borderRadius: 12,
  },
  defaults: {
    scroll: true,
    effect: "ripple",
    transition: "move",
    transitionDuration: 400,
  },
  player: { position: "bottom-left", captions: true },
  timeline: [
    { time: 0, target: null, caption: "Welcome." },
    { time: 3, target: "#overview", effect: "spotlight" },
    { time: 7, target: "#open-menu", action: { type: "click" } },
    { time: 10, target: "#menu-content", transition: "instant" },
    { time: 15, target: null, caption: "That concludes the tour." },
  ],
});

Unknown fields and invalid values throw TypeError with a field path. Configuration is data, not executable callbacks.

FieldRequirement/default
audioRequired non-empty URL string. Media failures are reported during playback.
timelineRequired array; empty is allowed for audio-only playback.
triggerOptional literal HTML ID prefixed with #; binds at construction.
allowActionsOptional developer override. Authored actions run unless explicitly false.
player.positionOne of bottom-right (default), bottom-left, top-right, top-left.
player.captionsBoolean; initially shows captions by default.
defaults.scrollBoolean; defaults to true.
defaults.effectripple, spotlight, none; defaults to ripple.
defaults.transitionmove, instant; defaults to move.
defaults.transitionDurationFinite non-negative number; defaults to 400.
theme.overlayOpacityNumber between 0 and 1 inclusive; defaults to 0.1.
theme.highlightColorNon-empty CSS color string; defaults to #0039a3. Use valid browser CSS color syntax.
theme.paddingFinite non-negative number; defaults to 6 pixels.
theme.borderRadiusFinite non-negative number; defaults to 8 pixels.

Timeline cue fields

FieldRequired?Meaning
timeYesFinite non-negative start time in seconds; fractions supported.
targetYesLiteral "#id" or null to clear highlight and backdrop.
captionNoPlain text for this cue. A cue without caption clears previous text.
scrollNoBoolean overriding automatic scrolling.
effectNo"ripple", "spotlight" or "none".
transitionNo"move" or "instant".
transitionDurationNoFinite non-negative movement milliseconds.
actionNoClick or long-press object; requires a non-null target.

Each cue requires a finite, non-negative time and a target that is either null or a #-prefixed ID. Times must be strictly increasing; duplicates are rejected rather than sorted. IDs must be unique in the host document and contain no ASCII whitespace. References are literal IDs, not CSS selectors, so punctuation does not require CSS escaping.

Cues may override scroll, effect, transition and transitionDuration using the same validation rules as defaults. Optional caption must be a string and is rendered as text, never HTML. target: null clears both highlight and backdrop. Automatic scrolling respects cue overrides.

Optional action is either { type: 'click' } or { type: 'longpress', holdDuration: 800 }. Long-press duration must be finite and positive. Actions require a non-null target and are validated even when allowActions is false. holdDuration is invalid on click actions.

If construction reports config.timeline[10].action, check the eleventh cue (indices start at zero). Use action: { type: 'click' }, not action: 'click'. For a cue without an action, omit the property rather than supplying null, false or an empty string. This validates the descriptor format; it does not judge whether the developer's chosen interaction is appropriate.

The timeline selects the latest cue at or before the audio clock, returning no cue before the first timestamp or for an empty timeline. Completion clears the cue. Cues beyond finite known duration emit recoverable warnings once per cue per instance.

Playback API and events

The package exports WalkthroughConfig, TimelineCue, CueOptions, CueAction, WalkthroughTheme, PlayerOptions, WalkthroughState, WalkthroughStatus, IdReference, Effect, Transition, CueChangeReason, CueChangeEvent, WalkthroughIssue and WalkthroughEventMap as TypeScript types.

MemberBehaviour
start(): Promise<void>Starts idle/ended/error at zero; resumes paused; no-op while playing. Repeated pending starts share a promise.
pause(): voidPauses playing/loading at the current position. Cancels pending play with AbortError. Other live states are unchanged.
resume(): Promise<void>Resumes paused playback; otherwise no-op or shares a pending play request.
seek(seconds): voidImmediately reconciles time/cue; finite non-negative seconds required. Clamps to known duration, queues media seek before metadata. Executes no actions.
restart(): Promise<void>Cancels the old run and starts at zero.
stop(): voidReleases audio, resets time to zero and cue to null, returns to idle.
destroy(): voidTerminal, idempotent cleanup of media, frames and listeners; resets time/cue.
stateFrozen snapshot: status, currentTime, duration, activeCue. Unknown duration is null; known duration is retained after stop/destroy.
on(event, listener)Subscribes to future events and returns an idempotent unsubscribe function. Read state for initial state.

A playback promise resolves when its play request succeeds, not when narration finishes. Listen for complete to detect the end.

state.status is idle, loading, playing, paused, ended, error or destroyed. loading includes initial loading and buffering. Time and duration are in seconds; activeCue is the selected cue or null.

After destruction, asynchronous methods reject; other mutators and new subscriptions throw. Reading state and existing unsubscribe functions remain safe. Catch playback promises: interruptions reject with AbortError, while playback failures reject with the underlying cause. Stale promises cannot revive a cancelled session. Resume after cancellation of a pending play uses a fresh media element at the preserved position.

Seeking while idle/ended/error updates the snapshot without changing status or starting audio. A subsequent start() begins at zero. To start at another position, call start from a gesture then seek; when paused, seek then resume.

EventPayload
statechangeFrozen state whenever any field changes, including clock updates.
cuechange{ cue, previousCue, reason, state }, only when cue identity changes, including clearing.
completeFinal ended snapshot, emitted on media completion, not stop.
error{ code, message, recoverable, cause?, cue? }, including nonfatal warnings.

Cue reasons: start, resume, playback, seek, recovery, stop, ended, error, destroy. Seeking and recovery select only the current cue, without a backlog. Media events supplement animation-frame polling; no independent timeline timer is used. loading covers initial start and buffering. Hidden-tab recovery reconciles with the media clock. Subscriber exceptions are logged and isolated; keep listeners lightweight.

Errors and warnings

CodeMeaning / first check
PLAYBACK_REJECTEDPlayback failed to start. Use a real gesture and inspect the cause.
MEDIA_ERRORLoading/decoding failed. Check audio URL, response and codec.
SEEK_FAILEDMedia could not seek. Check duration and server seek support.
CUE_BEYOND_DURATIONCue exceeds known duration. Correct timestamp or recording.
TARGET_NOT_FOUNDMissing/detached ID. Check spelling and mount timing.
TARGET_NOT_RENDERABLENo usable visible layout box. Check hidden content and dimensions.
RENDER_UNAVAILABLEBody unavailable. Initialize after DOM readiness.
SCROLL_INCOMPLETETarget did not become fully visible in time. Check clipping and size.
ACTION_SKIPPEDTarget missing or not visible/ready. Not an element-type safety rejection.
TRIGGER_NOT_FOUNDTrigger missing at construction. Initialize after mount.
TRIGGER_CONFLICTAnother instance owns the trigger; first binding wins. Use unique IDs.

Direct seek failure emits a recoverable error and throws; deferred seek failure terminates the attempt. recoverable: false means the playback attempt failed, not that the instance is destroyed: fix the cause and call start() to retry. Playback failures also reject the relevant promise; browser autoplay restrictions still apply.

The following assumes a tour without a configured trigger. Do not bind this extra start handler when using the automatic trigger option:

const unsubscribe = tour.on("cuechange", ({ cue, reason }) => {
  console.log(cue, reason);
});
tour.on("error", (issue) => console.warn(issue.code, issue.message));
const startButton = document.getElementById("start-tour");
const startTour = () => {
  void tour.start().catch((error) => {
    if (error?.name !== "AbortError") console.error(error);
  });
};
startButton.addEventListener("click", startTour);
// On application cleanup:
// startButton.removeEventListener("click", startTour);
// unsubscribe();
// tour.destroy();

Highlighting, motion and tracking

Import chaley-walkthrough/style.css (or link the generated stylesheet for script-tag usage). CSS is required for positioning, dimming and pointer pass-through. Targets are literal document IDs resolved using getElementById() after removing the first #; punctuation needs no CSS escaping. IDs must be unique. Initialise after the host DOM exists.

One fixed, decorative root is appended to the document body on the first drawable cue (or the active modal host described below). It contains a persistent outline with a transparent interior and a large outer shadow for the backdrop. The default dimming opacity is 0.1; padding is 6px, radius 8px and outline color #0039a3. The decorative renderer does not modify or focus the host target; separately configured actions may click it. The root is hidden from assistive technology and both layers pass pointer events through to application controls.

SettingCurrent rendering
effect: 'spotlight'Outline and backdrop without ripple rings.
effect: 'ripple' (default)Outline/backdrop plus two expanding, fading rings.
effect: 'none'Clears outline and backdrop for that cue. Overrides the instance default.
target: nullClears all visual decoration.
theme.overlayOpacity: 0Transparent backdrop; outline remains.
theme.highlightColor, padding, borderRadiusSet outline color, outside padding and cutout/outline radius.
transition: 'move' (default)Animate natural cue changes between visible highlight positions.
transition: 'instant'Position immediately.
transitionDurationMovement milliseconds, default 400; zero makes positioning instant.

Natural playback cue changes animate position, width, height and radius from the current rendered box to the destination using the configured duration. A new cue interrupts earlier movement and starts from the current rendered position. First appearance, seeking (including same-time seeks), recovery and changes while paused position immediately. Pause retains the highlight, settles any in-progress movement at the target and pauses ripple; resume restarts ripple. Stop, completion and fatal audio errors hide it and release tracking; destroy removes the owned nodes. Seeking while idle/ended/error does not create visible decoration. Stop/start reuse the same nodes until destruction.

A missing/detached target or one with no positive layout box or hidden/collapsed CSS visibility clears stale decoration and emits a recoverable warning; audio continues and the active timeline cue remains selected. Warnings are deduplicated per issue code and target ID per instance. A body-less document emits RENDER_UNAVAILABLE. No warning is emitted for a null target or an effect-none cue.

IDs and geometry are checked once per animation frame while a non-null, non-none cue is active in a visible document, including while playback is paused or buffering. ResizeObserver watches the current target; captured scroll and window resize events share the same pending frame. This also detects transform-only changes, sibling layout shifts and target removal/replacement without a seek. Missing targets stay eligible for automatic recovery while their cue remains active. Dialog host changes are monitored separately while the player or highlighter is visible.

Tracking writes geometry only when it changes. If the target moves during a transition, movement is cancelled and the highlight follows its current box immediately rather than repeatedly restarting the transition. This keeps user scrolling aligned. Hidden documents suspend geometry frames and pause ripple; visibility recovery refreshes geometry immediately. Stop, null/none cues, end, fatal errors and destroy release highlight geometry tracking and cancel queued frames and movement. The visible player retains its own dialog and keyboard handling until hidden or destroyed.

Automatic scrolling brings off-screen targets into view using viewport and ancestor clipping checks. With scrolling disabled, an off-screen cutout can still leave a backdrop over the viewport. Visibility checks do not detect overlapping elements or all transformed clipping geometry. Highlight tracking and player placement read the active target during playback; verify performance on complex host pages.

Theme configuration supplies inline custom properties on the overlay root: --chaley-walkthrough-overlay-opacity, --chaley-walkthrough-highlight-color and --chaley-walkthrough-border-radius. Prefer configuration for these values. The stylesheet also exposes --chaley-walkthrough-z-index (default 2147483000), which can be set on .chaley-walkthrough-root. No global element selectors are installed.

prefers-reduced-motion: reduce disables ripple and forces instant positioning. Preference changes are handled live: enabling it cancels current movement and settles the highlight at its target. Ripple has two 1600ms cycles staggered by 800ms; these decorative timings are fixed; there are no configuration fields for ripple speed. The layers remain pointer-transparent and do not move keyboard focus.

Native dialogs

Native modal dialogs opened with showModal() are supported in browsers with :modal and the Popover API. No configuration change is needed. The player and highlighter move into a shared manual popover inside the active modal, escaping its clipping and transforms while remaining part of its interactive subtree. They return to the body on close/removal, including while paused or showing a caption-only cue. Ordinary non-modal dialogs (show() or open) use the regular body overlay.

Chaley does not open or close your dialogs automatically: author a click action on an application button to invoke its handler, then target dialog content in later cues. Close the dialog through your own handler before targeting outside controls; outside content retains native modal inertness. Seeking does not reconstruct dialog state. Escape stops an active tour and leaves the dialog open; a subsequent Escape follows normal dialog behavior. A previously prevented Escape is respected. No focus trap or automatic target focus is added.

The host uses a manual popover because top-layer elements escape ancestor clipping and positioning (Popover documentation). Older browsers without the Popover API fall back to dialog-descendant mounting, which cannot guarantee positioning through transformed/clipped dialogs. Arbitrary popovers opened above the tour, fullscreen, iframes, shadow DOM and transformed body/root stacking contexts remain outside supported coverage. A high z-index cannot solve every stacking context. Reduced-motion and input tests are not a claim of accessibility compliance.

For a timeline-controlled dialog, your application owns the open/close handlers:

<button id="open-help" type="button">Open help</button>
<dialog id="help-dialog">
  <p id="help-content">Information about this page.</p>
  <button id="close-help" type="button">Close help</button>
</dialog>
const dialog = document.getElementById("help-dialog");
document.getElementById("open-help").onclick = () => dialog.showModal();
document.getElementById("close-help").onclick = () => dialog.close();

const tour = new Walkthrough({
  audio: "/audio/help-tour.mp3",
  timeline: [
    { time: 0, target: "#open-help", action: { type: "click" } },
    { time: 4, target: "#help-content" },
    { time: 9, target: "#close-help", action: { type: "click" } },
  ],
});
// Start from a user gesture as shown in the quick start.

Stopping or destroying the tour does not close your application's dialog.

Automatic scrolling

Visible targets are left in place. Other targets use native scrollIntoView({ behavior: "smooth", block: "center", inline: "nearest" }), including nested scroll containers and CSS scroll margins. Reduced motion uses instant. Full target containment is required, with one pixel tolerance; oversized targets may never satisfy it.

Audio continues while scrolling. The old spotlight is hidden and the new one appears after three stable, visible frames. Waiting stops after two seconds with a recoverable SCROLL_INCOMPLETE warning if the target is still inaccessible. Cue change, seek, stop, end and destroy cancel the wait and freeze the native scroll chain at its current position. A seek may initiate a new scroll to its destination. Pause cancels actions but lets scrolling finish. Leave enough narration time for scrolling and transitions.

Developer-controlled actions

const tour = new Walkthrough({
  audio: "/audio/tour.mp3",
  // Adding action descriptors opts in; allowActions: false disables them.
  timeline: [
    { time: 0, target: null },
    { time: 2, target: "#open-menu", action: { type: "click" } },
    { time: 5, target: "#menu-content" },
    {
      time: 9,
      target: "#hold-options",
      action: { type: "longpress", holdDuration: 800 },
    },
  ],
});

The developer chooses the target and action. Click uses HTMLElement.click() after target resolution, visibility, scrolling and highlight movement completion. effect: "none" deliberately skips decoration but still requires visibility. Action readiness waits at most two seconds plus the configured transition duration after scrolling.

Adding an action descriptor enables it; no visitor approval is requested. Set allowActions: false only when you want to disable all actions for that instance. Each eligible cue has at most one attempt per run. A cancelled/unready attempt is not retried on resume or revisiting the cue; restart or a fresh start after stop/end resets attempts. Pause, buffering, hidden tabs, seek, cue change, stop and destroy cancel pending actions. Seeking to or across an action never executes it; later natural entry into an as-yet unattempted cue can execute it. Recovery selects the current cue without running missed actions. Seeking cannot reconstruct a dropdown or other UI state created by earlier actions.

Long press dispatches bubbling, cancelable, composed pointerdown, waits holdDuration, then dispatches pointerup. Events use pointerId: 1, pointerType: "touch", isPrimary: true, button: 0, centre coordinates and buttons: 1 on down / 0 on release. Cancellation dispatches pointercancel to the original element, including a detached element; host handlers must release press state on cancel. Removal, replacement or loss of visibility also cancels a held press. No mouse events, automatic click, context menu or trusted gesture are synthesized. There is no universal long-press DOM contract: host code must explicitly support this sequence. Test your host component's pointer handlers explicitly.

There is no element-type safety filter: links, default buttons, labels and form controls are not rejected by the library. Developers decide whether an action is appropriate and whether navigation would interrupt their tour. Native behavior still applies: HTMLElement.click() does not activate a disabled native control, and synthetic events remain untrusted. ACTION_SKIPPED now indicates a missing/unready target, not a safety-policy rejection. Normal lifecycle cancellation emits no error. Browser restrictions on privileged APIs remain in force.

Player customization

The player appears during loading/playback, stays visible while paused, and offers replay after completion or retry after a media error. Stop hides it; destroy removes it. It uses native buttons and a labelled range input with visible focus outlines. Tab navigates controls, Space/Enter activates buttons, and arrow keys seek when the slider has focus. Escape stops the current session unless an earlier handler prevented the event. No focus trap or automatic target focus is used. Unknown or zero duration disables seeking.

Captions come from the active cue and display literally in a polite live region. The caption button is available only if the timeline has captions. player: { position: "bottom-left", captions: false } selects a preferred corner and initially hides captions. Placement tries another corner when it overlaps the target; this is best effort during state/clock updates, not a guarantee for targets covering the viewport. Screen-reader combinations require further testing.

Set these CSS custom properties on :root or directly on .chaley-walkthrough-player, after the library stylesheet:

.chaley-walkthrough-player {
  --chaley-walkthrough-player-background: #111827;
  --chaley-walkthrough-player-color: #f9fafb;
  --chaley-walkthrough-player-accent: #a78bfa;
  --chaley-walkthrough-player-border: #4b5563;
  --chaley-walkthrough-player-hover: #374151;
  --chaley-walkthrough-player-opacity: 1;
  --chaley-walkthrough-player-radius: 12px;
  --chaley-walkthrough-player-spacing: 18px;
  --chaley-walkthrough-player-offset: 24px;
  --chaley-walkthrough-player-z-index: 2147483001;
}
CSS custom propertyDefaultControls
--chaley-walkthrough-player-background#ffffffPanel background.
--chaley-walkthrough-player-color#172033Text and button text.
--chaley-walkthrough-player-accentInstance theme.highlightColorSlider accent and keyboard focus outlines.
--chaley-walkthrough-player-border#cbd5e1Panel/button borders.
--chaley-walkthrough-player-hover#f1f5f9Button hover background.
--chaley-walkthrough-player-opacity1Entire player opacity, including text.
--chaley-walkthrough-player-radius16pxPanel corner radius.
--chaley-walkthrough-player-spacing16pxPanel padding.
--chaley-walkthrough-player-offset16pxDistance from viewport edges.
--chaley-walkthrough-player-z-index2147483001Player's ordinary document stacking order.
--chaley-walkthrough-z-index2147483000Overlay stacking; set on :root or .chaley-walkthrough-root.

CSS length values need units such as px or rem. Choose colors and opacity that preserve contrast. For font or panel width, ordinary CSS can target .chaley-walkthrough-player; preserve usable controls, viewport fit and pointer behavior. There are no configuration fields for font, width, label translation, ripple speed, custom rendering or a headless player.

Use theme for highlight color, padding, radius and opacity: the renderer writes its theme properties onto its root, overriding inherited values. Raising a z-index does not override browser top-layer rules.

Player controls receive pointer events; the decorative highlight does not. The player remains usable with reduced motion and has no entrance animation. Colors and opacity remain the developer's responsibility when customizing contrast.

Triggers and independent instances

const firstTour = new Walkthrough({
  audio: "/audio/first.mp3",
  trigger: "#start-first",
  timeline: [],
});
const secondTour = new Walkthrough({
  audio: "/audio/second.mp3",
  trigger: "#start-second",
  timeline: [],
});
firstTour.on("error", (issue) => console.warn(issue.code, issue.message));
secondTour.on("error", (issue) => console.warn(issue.code, issue.message));

Each constructor binds its own trigger and never starts audio. Trigger clicks prevent their default browser navigation/submission and call start; rejected playback promises are handled and reported through error events. Use accessible host buttons for keyboard activation. Starting another instance stops the previous session, including a paused or loading one, and cancels its scroll, action and media work before new playback. The old instance remains reusable at time zero. Completed/error players are also cleared when another tour starts. Destroying an inactive instance never stops the active tour.

Trigger IDs must exist at construction. Missing IDs emit TRIGGER_NOT_FOUND; duplicate assignments emit TRIGGER_CONFLICT, and the first binding wins. Warnings are queued to the next microtask so subscriptions added immediately after construction receive them. Conflicted/missing-trigger instances still support programmatic start. Trigger binding does not observe later mounts: if a trigger is mounted or replaced later, destroy and recreate that instance after mount. Destruction releases its trigger reservation and listener; stopping keeps the binding for reuse.

Use one loaded package copy/build per page so instances share the internal document coordinator. No public manager, tour identifier or configuration array is required. Latest start request wins even when lifecycle callbacks request a new start; superseded pending starts reject with AbortError. Destroy tours on route change/unmount; cross-page continuation remains out of scope.

React and other frameworks

Build a React product tour with Chaley’s framework-independent JavaScript API. There is no React-specific wrapper: initialize the walkthrough after the DOM mounts and destroy it during cleanup.

import { useEffect, useRef } from "react";
import { Walkthrough } from "chaley-walkthrough";
import "chaley-walkthrough/style.css";

export function Overview() {
  const tourRef = useRef(null);

  useEffect(() => {
    const tour = new Walkthrough({
      audio: "/audio/overview.mp3",
      timeline: [
        { time: 0, target: "#overview-title", caption: "Your overview." },
        {
          time: 5,
          target: "#overview-settings",
          caption: "Adjust preferences here.",
        },
      ],
    });
    tour.on("error", (issue) => console.warn(issue.code, issue.message));
    tourRef.current = tour;
    return () => {
      tourRef.current = null;
      tour.destroy();
    };
  }, []);

  function startTour() {
    const tour = tourRef.current;
    if (!tour) return;
    void tour.start().catch((error) => {
      if (error?.name !== "AbortError") console.error(error);
    });
  }

  return (
    <section>
      <button type="button" onClick={startTour}>
        Show me around
      </button>
      <h1 id="overview-title">Overview</h1>
      <button id="overview-settings" type="button">
        Settings
      </button>
    </section>
  );
}

For TypeScript React use useRef<Walkthrough | null>(null). Keep IDs unique when multiple component instances mount. Manage effect dependencies deliberately for prop-based configuration; avoid recreating a tour on every render. Cleanup is necessary for StrictMode's development setup/cleanup cycle and actual unmounts.

Use equivalent mount/teardown hooks in Vue, Svelte, Angular or other frameworks. Imports are SSR-safe; construction requires a browser document. Put initialization in client code and global CSS where your framework permits it. Test your own handlers, routes and dynamic mounts; synthetic long-press compatibility depends on host components.

TypeScript

Declarations ship with the package; no separate @types package is needed:

import { Walkthrough } from "chaley-walkthrough";
import type { WalkthroughConfig } from "chaley-walkthrough";
import "chaley-walkthrough/style.css";

const config = {
  audio: "/audio/tour.mp3",
  player: { position: "top-right" },
  timeline: [{ time: 0, target: "#overview", effect: "spotlight" }],
} satisfies WalkthroughConfig;

const tour = new Walkthrough(config);

Public types are listed in the API reference. Runtime validation still applies to JSON/untyped inputs.

If TypeScript reports that it cannot find declarations for the stylesheet import, include your bundler's CSS typings (for example, Vite's client types), or add this ambient declaration to a .d.ts file included by your application, such as src/styles.d.ts:

declare module "chaley-walkthrough/style.css";

This declaration describes the CSS import to TypeScript; your bundler must still load the actual stylesheet.

Browser behavior and boundaries

Developers are responsible for choosing appropriate actions. Navigation, form submission and destructive operations can interrupt a tour or change application data; prefer interactions that preserve the guided flow. Synthetic events cannot provide trusted user gestures. Seeking will not reconstruct UI state from earlier actions. Long-press handler compatibility requires explicit testing.

Cross-page continuation, automatic playlists, React Native, a visual timeline editor and a configuration-update method are not provided. Native modal dialog support is documented above; iframes and shadow DOM remain unsupported. Chrome and Edge have automated coverage. Validate Firefox, Safari, mobile and assistive-technology combinations relevant to your application rather than treating them as certified. There is no telemetry. Playback fetches the configured audio URL; remote hosts may receive requests. Serve audio with correct content type and byte-range support for seeking. Use original or licensed narration and leave time for scrolling and animations when authoring timestamps.

Audio authoring and timestamps

Use original or appropriately licensed narration. Produce a browser-playable file, listen to the final exported recording, and record cue start times in seconds from that exact file. Re-exporting or trimming audio can invalidate timestamps. Start with a target-null introduction, add targets at the relevant narration timestamps, and optionally finish with a target-null closing cue. Cues remain active until the next timestamp; this library does not generate timestamps or captions.

Allow enough narration time for scroll settlement (up to two seconds), highlight movement (400ms by default), and any configured hold. Leave time after a menu-opening click before its content cue; the host application owns rendering delays. Audio continues while scrolling, so short cues may cancel actions before they can run. Large/inaccessible targets may never become fully visible. Check actual browser playback rather than assuming a file extension guarantees codec support.

Serve audio from the consumer's public asset URL, not a local filesystem path. Use the correct media content type and byte-range support for reliable seeking. Confirm the response is audio rather than an SPA HTML fallback, and check site CSP/media-src, mixed-content and authentication restrictions if loading fails. Remote audio hosts receive the configured requests; the library sends no telemetry or analytics. Verify synchronization with your actual recording.

Troubleshooting

SymptomCheck or correction
Constructor throws config.timeline[N].actionN is zero-based. Use an object: { type: "click" } or { type: "longpress", holdDuration: 800 }; omit action for no interaction. Strings/null/functions are invalid.
Unknown config field or enumCheck the configuration table. Validation intentionally rejects misspelled fields rather than silently ignoring them.
Trigger has no effectInitialise after mount, use a unique literal ID, subscribe immediately to error events and inspect TRIGGER_NOT_FOUND/TRIGGER_CONFLICT. Recreate after trigger replacement.
Audio rejected or fails to loadStart from a user gesture; catch start/resume promises. Inspect PLAYBACK_REJECTED/MEDIA_ERROR and the Network response for the configured URL.
No highlight or unstyled playerImport the separate stylesheet. Confirm positive visible target geometry and no unsupported iframe/shadow-root lookup.
ACTION_SKIPPED or SCROLL_INCOMPLETECheck current target visibility/attachment, clipping, target size and cue spacing. These are readiness checks, not element-type safety filtering.
Action never runs after seekingExpected: seeks do not execute actions. Replay naturally to reproduce earlier UI actions. Also check explicit allowActions=false.
Long press remains stuck in host UIHandle pointercancel and component unmount cleanup. Synthetic events do not create a universal native longpress.
Two players or conflicting sessionsUse one package copy/build; do not mix separately loaded ESM and IIFE copies. Destroy instances on unmount.
npm link changes do not appearKeep npm run dev running in the library; restart the consumer dev server and clear its dependency cache. Test the archive to remove symlink ambiguity.
Node import succeeds but constructor failsExpected SSR behavior: import on the server is safe; construct only after browser mount.
A dialog or header covers the highlightUse the rebuilt JS and CSS together. Native modal support requires :modal and the Popover API; check custom CSS and other top-layer popovers. Iframes and shadow DOM remain unsupported.

For reproducible defects, include package version, browser/OS, installation method, smallest cue/host handler and error-event output.

Checklist for developers and AI agents

  1. Install the package and import its separate CSS. Use one package copy per page.

  2. Supply your own served audio URL, final-recording timestamps, captions and existing unique IDs. Do not invent targets absent from the host interface.

  3. Construct after mount. Use either trigger or your own user-gesture handler; catch programmatic playback promises and subscribe to errors.

  4. Use strictly increasing seconds for cues and milliseconds for transition/hold durations. Shared behavior goes in defaults; appearance goes in theme and player.

  5. Add action objects only where the developer intends application handlers to run. Account for navigation, dialog/menu state, rendering delays and cancellation. Seeking will not recreate earlier actions.

  6. Use documented configuration and CSS variables. Do not invent methods such as next(), addStep() or setConfig().

  7. Destroy on unmount/route changes. Recreate after configuration or trigger replacement. Never instantiate during server rendering.

  8. Verify playback, pause/resume, seek, replay, errors, keyboard controls, reduced motion, dialogs and cleanup in your application.

Changes, contributions and license

See CHANGELOG.md for release changes. Contributor setup and internal implementation records belong in CONTRIBUTING.md. This README is the consumer API and integration guide.

Chaley Walkthrough is licensed under the MIT license.