### Initialize Tour Guide Client Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/tourguideclient.md Initializes the Tour Guide Client with custom options like backdrop color and keyboard controls. Call `start()` to begin the tour. ```javascript import { TourGuideClient } from "@sjmc11/tourguidejs"; const tg = new TourGuideClient({ backdropColor: 'rgba(0, 0, 0, 0.7)', keyboardControls: true }); await tg.start(); ``` -------------------------------- ### Create and Start a Tour Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/00-START-HERE.md Initialize a TourGuideClient with tour steps and then start the tour. Ensure the necessary SCSS is imported for styling. ```javascript import { TourGuideClient } from "@sjmc11/tourguidejs"; import "@sjmc11/tourguidejs/src/scss/tour.scss"; // Create tour const tg = new TourGuideClient({ steps: [ { target: '#step1', title: 'Welcome', content: 'This is step 1' }, { target: '#step2', title: 'Features', content: 'Try this feature' } ] }); // Start it await tg.start(); ``` -------------------------------- ### Initialize and Start a Tour Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/tourguideclient.md Instantiate the TourGuideClient with steps and then start the tour, optionally filtering by a group identifier. Ensure steps are defined before calling start. ```javascript const tg = new TourGuideClient({ steps: [ { target: '#feature-1', content: 'Click here to start' }, { target: '#feature-2', content: 'Now try this' } ] }); await tg.start('onboarding'); ``` -------------------------------- ### Complete Tour with Callbacks and Validation Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/callbacks-and-lifecycle.md Example demonstrating a full tour setup with step-specific validation (beforeLeave), UI interaction (afterEnter), global step change tracking (onBeforeStepChange, onAfterStepChange), and finalization logic (onFinish). ```javascript const tg = new TourGuideClient({ steps: [ { target: '#form-email', content: 'Enter your email', beforeLeave: async (current, next) => { const email = document.querySelector('#form-email').value; if (!email.includes('@')) throw new Error('Valid email required'); } }, { target: '#form-password', content: 'Create a password', afterEnter: () => { document.querySelector('#form-password').focus(); } } ] }); // Global callbacks tg.onBeforeStepChange((current, next) => { console.log(`Moving from ${current} to ${next}`); }); tg.onAfterStepChange((prev, current) => { analytics.trackEvent('step_completed', { step: current }); }); tg.onFinish(async () => { await api.post('/register', getFormData()); showSuccessMessage(); }); // Start tour await tg.start(); ``` -------------------------------- ### Start TourGuide JS Tour Source: https://github.com/sjmc11/tourguide-js/blob/main/readme.md Initiate the tour by calling the start method on the TourGuideClient instance. This will display the first step to the user. ```javascript tg.start() ``` -------------------------------- ### Basic Tour Usage Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/README.md Initialize and start a guided tour using TourGuideClient. Define tour steps programmatically with targets, titles, and content. Ensure SCSS styles are imported for proper rendering. ```javascript import { TourGuideClient } from "@sjmc11/tourguidejs"; import "@sjmc11/tourguidejs/src/scss/tour.scss"; const tg = new TourGuideClient({ steps: [ { target: '#welcome', title: 'Welcome', content: 'Thanks for joining us!' }, { target: '#feature', title: 'Feature', content: 'Check out this cool feature' } ] }); await tg.start(); ``` -------------------------------- ### Install TourGuide JS Source: https://github.com/sjmc11/tourguide-js/blob/main/readme.md Install the TourGuide JS library using npm. This command adds the package to your project's dependencies. ```bash npm i @sjmc11/tourguidejs ``` -------------------------------- ### Minimal Tour Setup Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/configuration.md Initialize a basic tour with essential steps. Ensure the TourGuideClient is imported before use. ```javascript const tg = new TourGuideClient({ steps: [ { target: '#step1', content: 'First step' }, { target: '#step2', content: 'Second step' } ] }); await tg.start(); ``` -------------------------------- ### Start or Resume Tour with `start` Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/step-management.md Initiate the tour using the `start` method. It can begin from the first step, a specific group, or resume from the last step if `rememberStep` is enabled. ```javascript // Start from beginning await tg.start(); // Start specific group await tg.start('feature-intro'); // Resume from last step (if rememberStep enabled) const tg = new TourGuideClient({ rememberStep: true }); await tg.start(); // Resumes at last step ``` -------------------------------- ### Start Tour with HTML Data Attributes Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/README.md Initialize TourGuideClient and start a tour when steps are defined using HTML data attributes. The client automatically discovers and uses these steps. ```javascript const tg = new TourGuideClient(); await tg.start(); ``` -------------------------------- ### Initialize TourGuide with Multi-Group Steps Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/README.md Instantiate TourGuideClient and define steps belonging to different groups. Start a specific group's tour using its identifier. ```javascript const tg = new TourGuideClient({ steps: [ { group: 'onboarding', target: '#step1', content: '...' }, { group: 'features', target: '#step2', content: '...' } ] }); await tg.start('onboarding'); ``` -------------------------------- ### afterEnter Example: Highlighting, Logging, and Focusing Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/callbacks-and-lifecycle.md An example demonstrating the afterEnter callback for highlighting form fields, logging step views, and focusing the first input element. ```javascript { target: '#checkout-form', content: 'Complete your purchase', afterEnter: async (current, next) => { // Highlight form fields document.querySelectorAll('#checkout-form input').forEach(input => { input.classList.add('tour-highlight'); }); // Log view analytics.trackEvent('tour_step_view', { step: 'checkout' }); // Focus first field document.querySelector('#checkout-form input').focus(); } } ``` -------------------------------- ### Integration Test TourGuide.js Initialization Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/architecture-internals.md Shows how to integration test the TourGuide.js client by initializing it with steps, starting the tour, and asserting DOM changes. ```javascript const tg = new TourGuideClient({ steps: [...] }) await tg.start() // Assert DOM changes assert(document.querySelector('.tg-dialog')) ``` -------------------------------- ### beforeEnter Example: Admin Validation and Data Loading Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/callbacks-and-lifecycle.md An example demonstrating the use of the beforeEnter callback to validate admin access and load dynamic data before a step is displayed. ```javascript { target: '#admin-panel', content: 'Admin settings', beforeEnter: async (current, next) => { // Only admins can see this step const isAdmin = await checkIsAdmin(); if (!isAdmin) { throw new Error('Admin access required'); } // Load admin data const adminData = await api.get('/admin/stats'); next.adminData = adminData; } } ``` -------------------------------- ### Progressive Disclosure Tour Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/usage-examples.md Define and start tours progressively based on user activity or feature completion. This example shows how to manage multiple tours for onboarding, intermediate, and advanced features. ```javascript const tours = { onboarding: { name: 'onboarding', steps: [/* basic features */] }, intermediate: { name: 'intermediate', steps: [/* intermediate features */] }, advanced: { name: 'advanced', steps: [/* advanced features */] } }; async function startAppropriateTour(user) { const tg = new TourGuideClient(); // Onboarded users need to see new features if (!tg.isFinished('new-features')) { tg.addSteps(tours.intermediate.steps); await tg.start('intermediate'); } // After some time, show advanced features if (user.daysActive > 30 && !tg.isFinished('advanced')) { tg.addSteps(tours.advanced.steps); await tg.start('advanced'); } } ``` -------------------------------- ### afterLeave Example: Removing Highlights and Logging Completion Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/callbacks-and-lifecycle.md An example demonstrating the afterLeave callback for removing tour-specific highlighting from elements and logging the completion of a step. ```javascript { target: '#feature', content: 'Try this feature', afterLeave: async (current, next) => { // Remove highlighting document.querySelectorAll('.tour-highlight').forEach(el => { el.classList.remove('tour-highlight'); }); // Log completion await api.post('/tour/steps/completed', { step: 'feature-intro', time: Date.now() }); } } ``` -------------------------------- ### Initialize a Simple Tour Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/api-quick-reference.md Use this snippet to create and start a basic tour with predefined steps. Ensure the target elements exist in the DOM. ```javascript const tg = new TourGuideClient({ steps: [ { target: '#step1', content: 'Content 1' }, { target: '#step2', content: 'Content 2' } ] }); await tg.start(); ``` -------------------------------- ### start Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/tourguideclient.md Begins the tour at the current or remembered step. It can optionally filter steps by a group identifier. ```APIDOC ## start ### Description Begins the tour at the current or remembered step. It can optionally filter steps by a group identifier. ### Method start ### Signature start(group?: string): Promise ### Parameters #### Query Parameters - **group** (string) - Optional - Tour group identifier to filter and organize steps ### Returns Promise - Resolves to true when tour starts successfully ### Throws Rejects if tour is already active, no steps found, or step initialization fails ### Example ```javascript const tg = new TourGuideClient({ steps: [ { target: '#feature-1', content: 'Click here to start' }, { target: '#feature-2', content: 'Now try this' } ] }); await tg.start('onboarding'); ``` ``` -------------------------------- ### Handle Promise Rejection on Tour Start Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/event-system-and-errors.md Use a try-catch block to gracefully handle errors when starting a tour, such as network issues or configuration problems. ```javascript try { await tg.start(); } catch (error) { console.error('Tour failed to start:', error); // Handle error } ``` -------------------------------- ### Guided Tutorial with Validations using TourGuideClient Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/usage-examples.md Create a step-by-step tutorial with validations before proceeding to the next step. Use the `beforeLeave` hook to perform checks and throw an error if validation fails. ```javascript const tg = new TourGuideClient({ steps: [ { target: '#step1-button', title: 'Step 1: Create', content: 'Click the Create button to start', beforeLeave: async () => { // Verify user clicked the button const created = await api.get('/check/created'); if (!created) { throw new Error('Please complete Step 1 first'); } } }, { target: '#step2-input', title: 'Step 2: Configure', content: 'Fill in the configuration', beforeLeave: async () => { const configured = await api.get('/check/configured'); if (!configured) { throw new Error('Please complete Step 2 first'); } } }, { target: '#step3-submit', title: 'Step 3: Submit', content: 'Submit your work', beforeLeave: async () => { const submitted = await api.get('/check/submitted'); if (!submitted) { throw new Error('Please complete Step 3 first'); } } } ] }); tg.onFinish(async () => { await api.post('/tutorial/completed'); showSuccessMessage('Tutorial complete!'); }); await tg.start(); ``` -------------------------------- ### Include TourGuide JS Scripts and Styles Source: https://github.com/sjmc11/tourguide-js/blob/main/readme.md Import the necessary SCSS for styling and the TourGuideClient class for JavaScript functionality. This setup is required before initializing a tour. ```javascript // Style import "@sjmc11/tourguidejs/src/scss/tour.scss" // JS import {TourGuideClient} from "@sjmc11/tourguidejs/src/Tour" ``` -------------------------------- ### Group and Start Tour by Group Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/step-management.md Organize steps into named groups using the `group` property. You can then start the tour by specifying a group name to show only steps belonging to that group. ```javascript const tg = new TourGuideClient({ steps: [ { target: '#feature-1', content: 'Feature one', group: 'features' }, { target: '#settings-1', content: 'Setting one', group: 'settings' }, { target: '#admin-1', content: 'Admin feature', group: 'admin' } ] }); // Show only features group await tg.start('features'); // Later, show settings await tg.exit(); await tg.start('settings'); ``` -------------------------------- ### Console Output Examples Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/event-system-and-errors.md Examples of messages logged to the console when debug mode is enabled, including tour start/exit events, step navigation, and error conditions. ```javascript // Start "Start tour" ``` ```javascript // Step change "Moving from step 0 to step 1" ``` ```javascript // Errors (with debug) "Tour already active" "No tour steps detected" "Promise waiting" ``` ```javascript // Info "Tour exited" ``` -------------------------------- ### Fallback Tour on Primary Tour Failure Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/event-system-and-errors.md Use a try-catch block to attempt starting a primary tour and fall back to a basic tour if the primary tour fails to initialize or start. ```javascript const tg = new TourGuideClient(); try { await tg.start('primary-tour'); } catch (error) { console.warn('Primary tour failed:', error); // Fall back to basic tour const basicTg = new TourGuideClient({ steps: [{ target: 'body', content: 'Welcome!' }] }); await basicTg.start(); } ``` -------------------------------- ### Multi-Group Tours Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/usage-examples.md Organize tour steps into distinct groups to cater to different user paths or feature sets. Start specific groups by passing their name to the start method. ```javascript const tg = new TourGuideClient({ steps: [ // Onboarding tour { group: 'onboarding', target: '#signup-form', content: 'Create your account here', order: 1 }, { group: 'onboarding', target: '#profile-setup', content: 'Complete your profile', order: 2 }, // Feature discovery tour { group: 'features', target: '#advanced-search', content: 'Use advanced search to find anything', order: 1 }, { group: 'features', target: '#saved-items', content: 'Save items for later', order: 2 } ] }); // Start onboarding for new users if (!user.isOnboarded) { await tg.start('onboarding'); } // Show features later if (user.completedOnboarding && !user.seenFeatures) { await tg.start('features'); } ``` -------------------------------- ### Listener Management Methods Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/api-quick-reference.md Methods for initializing and destroying event listeners for the tour guide. ```APIDOC ## initListeners() ### Description Initialize event listeners for the tour guide. ### Method `initListeners()` ### Returns Promise - A promise that resolves to a boolean indicating success. ``` ```APIDOC ## destroyListeners() ### Description Remove event listeners associated with the tour guide. ### Method `destroyListeners()` ### Returns Promise - A promise that resolves to a boolean indicating success. ``` -------------------------------- ### Create Tour Step with HTML Content Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/types.md Example of creating a TourGuideStep using an HTML string for the dialog content. This allows for rich text formatting within the step's dialog. ```typescript const step: TourGuideStep = { target: '#form', content: '

Enter your email here

', title: 'Email Form' }; ``` -------------------------------- ### DOM Element Initialization Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/architecture-internals.md This constructor initializes the dialog and backdrop elements for the tour guide. These elements are created once and appended to the body, persisting throughout the tour's lifecycle. ```javascript constructor() { this.dialog = document.createElement('div') this.backdrop = document.createElement('div') // Appended to body in createTourGuideDialog/createTourGuideBackdrop } ``` -------------------------------- ### Announce New Features with TourGuide.js Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/usage-examples.md Use this snippet to announce new features to users. It defines tour steps with targets, titles, and content, then initializes and starts the TourGuideClient. The tour is only shown if the features haven't been marked as seen in local storage. ```javascript const newFeatures = [ { target: '#new-search', title: '🆕 Advanced Search', content: 'We\'ve upgraded search with AI-powered results' }, { target: '#new-sharing', title: '🆕 Smart Sharing', content: 'Share collections with one click' }, { target: '#new-analytics', title: '🆕 Analytics Dashboard', content: 'Track usage and insights' } ]; const tg = new TourGuideClient({ dialogClass: 'feature-announcement', backdropColor: 'rgba(100, 200, 255, 0.3)', steps: newFeatures, keyboardControls: true, exitOnEscape: true }); tg.onFinish(() => { // Mark features as seen localStorage.setItem('features-v2-seen', JSON.stringify(newFeatures)); }); // Only show if not seen if (!localStorage.getItem('features-v2-seen')) { await tg.start(); } ``` -------------------------------- ### Create Tour Step with Text Content Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/types.md Example of creating a TourGuideStep with simple text content for the dialog body. The target element is specified using a CSS selector. ```typescript const step: TourGuideStep = { target: '#button', title: 'Click Me', content: 'This button triggers an important action' }; ``` -------------------------------- ### Troubleshoot Callbacks Not Firing Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/event-system-and-errors.md Helps diagnose why callbacks like `onFinish` or `onBeforeExit` might not be invoked. Emphasizes registering callbacks before starting the tour and checking for errors within the callbacks themselves. ```javascript // Issue: onFinish/onBeforeExit not called // Solution 1: Register before starting tg.onFinish(() => { /* ... */ }); await tg.start(); // Fires callbacks // Solution 2: Check for errors in callbacks tg.onAfterStepChange((prev, current) => { console.log('Step changed to', current); }); ``` -------------------------------- ### TourGuideClient Class Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/README.md The main class for controlling and managing tours. It provides methods for starting, navigating, managing steps, configuring options, and handling tour completion. ```APIDOC ## Class: TourGuideClient ### Description The `TourGuideClient` class is the primary interface for interacting with the TourGuide.js library. It allows you to programmatically control the tour flow, manage tour steps, configure tour behavior, and listen for various tour events. ### Methods #### Navigation - **start(group?: string): Promise** - Starts a tour, optionally for a specific group. - **visitStep(index: "next" | "prev" | number): Promise** - Navigates to a specific step by index, or to the next/previous step. - **nextStep(): Promise** - Advances the tour to the next step. - **prevStep(): Promise** - Navigates the tour to the previous step. - **exit(): Promise** - Exits the current tour. #### Step Management - **addSteps(steps: TourGuideStep[]): Promise** - Adds an array of `TourGuideStep` objects to the current tour. - **refresh(): Promise** - Refreshes the current tour, re-calculating element positions. - **refreshDialog(): Promise** - Refreshes the tour dialog, updating its position and content. - **updatePositions(): Promise** - Updates the positions of all tour elements, useful after DOM changes. #### Configuration - **setOptions(options: TourGuideOptions): Promise** - Updates the tour's options with a new set of configurations. #### Completion - **finishTour(exit?: boolean, group?: string): Promise** - Marks the current tour as finished, optionally exiting it. - **deleteFinishedTour(group?: string): void** - Removes the finished status for a given tour group. - **isFinished(group?: string): boolean** - Checks if a tour for a given group has been marked as finished. #### Callbacks - **onFinish(callback: Function): void** - Registers a callback function to be executed when a tour finishes. - **onBeforeExit(callback: Function): void** - Registers a callback function to be executed before exiting a tour. - **onAfterExit(callback: Function): void** - Registers a callback function to be executed after exiting a tour. - **onBeforeStepChange(callback: Function): void** - Registers a callback function to be executed before a step changes. - **onAfterStepChange(callback: Function): void** - Registers a callback function to be executed after a step changes. #### Listeners - **initListeners(): Promise** - Initializes event listeners for the tour. - **destroyListeners(): Promise** - Removes all event listeners associated with the tour. ### Properties - **activeStep: number** - The index of the currently active step. - **isVisible: boolean** - Indicates whether the tour dialog is currently visible. - **tourSteps: TourGuideStep[]** - An array containing all the `TourGuideStep` objects in the tour. - **options: TourGuideOptions** - The current configuration options for the tour. - **group: string** - The identifier for the current tour group. - **dialog: HTMLElement** - A reference to the tour dialog's DOM element. - **backdrop: HTMLElement** - A reference to the tour backdrop's DOM element. ``` -------------------------------- ### Create Tour Step with Lifecycle Callbacks Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/types.md Example of a TourGuideStep that includes lifecycle callbacks (beforeEnter, afterEnter, beforeLeave, afterLeave). These functions execute at specific points during the step's lifecycle and can be asynchronous. ```typescript const step: TourGuideStep = { target: '#feature', content: 'Advanced feature guide', beforeEnter: async (current, next) => { // Validate user has permission const hasAccess = await checkUserAccess('advanced-feature'); if (!hasAccess) throw new Error('Access denied'); }, afterEnter: async (current, next) => { // Track analytics analytics.trackStepView('feature-guide'); }, beforeLeave: (current, next) => { // Save progress console.log(`Moving from step to feature guide`); }, afterLeave: (current, next) => { // Cleanup document.querySelector('#tooltip')?.remove(); } }; ``` -------------------------------- ### Graceful Degradation for Tour Initialization Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/event-system-and-errors.md Wrap tour initialization and starting logic in an async IIFE with a try-catch block to prevent tour errors from breaking the entire page. ```javascript // Try to start tour, but don't break page (async () => { try { const tg = new TourGuideClient({ steps: loadTourSteps() }); if (!tg.isFinished('main-tour')) { await tg.start('main-tour'); } } catch (error) { // Log but don't throw - page still works console.warn('Tour initialization failed:', error); } })(); ``` -------------------------------- ### Implement Conditional Steps in TourGuide.js Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/usage-examples.md This example demonstrates how to create conditional steps in a tour. The `beforeEnter` hook allows you to programmatically skip steps based on user state, such as subscription type, by throwing an error. ```javascript const tg = new TourGuideClient({ steps: [ { target: '#features', content: 'Explore features', order: 1 }, { target: '#premium-feature', content: 'Premium feature (requires subscription)', order: 2, beforeEnter: async (current, next) => { // Skip if user doesn't have premium const subscription = await api.get('/user/subscription'); if (subscription.type === 'free') { throw new Error('Premium only - showing upgrade option'); } } }, { target: '#basic-features', content: 'Basic features', order: 3 } ] }); await tg.start(); ``` -------------------------------- ### Define Multi-Group Tour Steps Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/step-management.md Define tour steps organized into distinct groups like 'onboarding' and 'features'. Each step has an order, target element, content, and an optional title. After defining steps, you can start a specific group using `tg.start('groupName')`. ```javascript const tg = new TourGuideClient({ steps: [ // Onboarding group { group: 'onboarding', order: 1, target: '#welcome', content: 'Welcome to the app!', title: 'Getting Started' }, { group: 'onboarding', order: 2, target: '#signup', content: 'Create an account' }, // Feature tour group { group: 'features', order: 1, target: '#dashboard', content: 'View your data', title: 'Dashboard' }, { group: 'features', order: 2, target: '#charts', content: 'Analyze with charts' } ] }); // Start onboarding await tg.start('onboarding'); // Later, show features await tg.exit(); await tg.start('features'); ``` -------------------------------- ### Initialize TourGuide JS Client Source: https://github.com/sjmc11/tourguide-js/blob/main/readme.md Create a new instance of the TourGuideClient. Pass an options object to configure the tour, or an empty object for default settings. ```javascript const tg = new TourGuideClient({} : TourGuideOptions) ``` -------------------------------- ### Initialization Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/api-quick-reference.md Initializes a new instance of the TourGuideClient. Options can be provided to configure the tour's behavior. ```APIDOC ## Initialization Initializes a new instance of the TourGuideClient. ### Method ```javascript new TourGuideClient(options?: TourGuideOptions) ``` ### Parameters #### Options - **options** (TourGuideOptions) - Optional - Configuration options for the tour. ``` -------------------------------- ### Initialize TourGuideClient Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/tourguideclient.md Instantiate the TourGuideClient with optional configuration. The options object allows customization of tour behavior and appearance. ```typescript constructor(options?: TourGuideOptions) ``` -------------------------------- ### beforeLeave Example: Email Validation and Saving Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/callbacks-and-lifecycle.md An example using the beforeLeave callback to validate an email input and save the data before navigating away from the step. ```javascript { target: '#email-field', content: 'Enter your email', beforeLeave: async (current, next) => { // Validate email const email = document.querySelector('#email-field').value; if (!isValidEmail(email)) { throw new Error('Please enter a valid email'); } // Save email await api.post('/user/email', { email }); } } ``` -------------------------------- ### Initialize TourGuideClient with Steps Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/step-management.md Pass an array of step objects to the TourGuideClient constructor to define the tour sequence upon initialization. ```javascript const tg = new TourGuideClient({ steps: [ { target: '#intro-button', title: 'Welcome', content: 'This is your starting point' }, { target: '#main-feature', title: 'Main Feature', content: 'Learn how to use this feature' } ] }); await tg.start(); ``` -------------------------------- ### Import TourGuide.js Client and Types Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/README.md Demonstrates the main client import path and alternative direct import. Also shows how to import type definitions for options and steps. ```javascript // Main client import { TourGuideClient } from "@sjmc11/tourguidejs"; // Alternative direct import import { TourGuideClient } from "@sjmc11/tourguidejs/src/Tour"; // Types import type { TourGuideOptions } from "@sjmc11/tourguidejs/src/core/options"; import type { TourGuideStep } from "@sjmc11/tourguidejs/src/types/TourGuideStep"; // Styles import "@sjmc11/tourguidejs/src/scss/tour.scss"; ``` -------------------------------- ### Import TourGuide.js Components Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/api-quick-reference.md Import the main `TourGuideClient` class, relevant types for options and steps, and the SCSS styles for the tour. ```javascript // Main class import { TourGuideClient } from "@sjmc11/tourguidejs/src/Tour" // Types import type { TourGuideOptions } from "@sjmc11/tourguidejs/src/core/options" import type { TourGuideStep } from "@sjmc11/tourguidejs/src/types/TourGuideStep" // Styles import "@sjmc11/tourguidejs/src/scss/tour.scss" ``` -------------------------------- ### TourGuide JS Configuration and Steps Source: https://github.com/sjmc11/tourguide-js/blob/main/demo.html Defines the steps for a TourGuide JS tour and initializes the TourGuideClient. This snippet is used to set up the tour's content, targets, and behavior, including custom logic for step transitions. ```javascript const steps = [{"content": "This is the title element", "title": "Welcome aboard 👋", "target": "#title", "order": "", "group": "groupA"}, {"content": "Grid wrapper", "title": "Test positioning of a large element occupying the entire screen", "target": "#grid-wrapper", "dialogTarget": "#card1", "order": "", "group": "groupA"}, {"content": "Card One", "title": "This is the first card", "target": "#card1", "order": "", "group": "groupA", "beforeEnter": "() => { console.log('wait 6 seconds') return new Promise((resolve, reject) => { setTimeout(function () { resolve(); }, 1000); }) }"}, {"content": "Card Deux", "title": "This is the second card", "target": "#card2", "order": "", "group": "groupA", "beforeEnter": "() => { return new Promise((resolve, reject) => { // Reject entering the step reject('skip step') // Prevent loading state from stopping step navigation tg._promiseWaiting = false // Get the desired step index based on direction let skipToIndex = 4 if (tg.activeStep === 4) skipToIndex = 2 // Visit the desired step tg.visitStep(skipToIndex) }) }"}, {"content": "Card Three", "title": "This is the last card", "target": "#card3", "order": "", "group": "groupA"}] const tg = new tourguide.TourGuideClient({ steps: steps, group: "groupA", completeOnFinish: true, allowDialogOverlap: true, exitOnClickOutside: true, activeStepInteraction: true, }) // const triggerBtn = document.getElementById('tourTrigger') // tg.onBeforeStepChange(()=>{ // return new Promise((resolve, reject) => { // setTimeout(function () { resolve(); }, 6000); // }) // }) function openTour() { tg.start() } ``` -------------------------------- ### State Properties Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/api-quick-reference.md Properties that represent the current state of the tour guide. ```APIDOC ## State Properties ### `activeStep` - **Type**: `number` - **Read-Only**: No - **Description**: Current step index of the tour. ``` ```APIDOC ### `isVisible` - **Type**: `boolean` - **Read-Only**: No - **Description**: Indicates whether the tour is currently active. ``` ```APIDOC ### `tourSteps` - **Type**: `TourGuideStep[]` - **Read-Only**: No - **Description**: Computed array of tour steps. ``` ```APIDOC ### `options` - **Type**: `TourGuideOptions` - **Read-Only**: No - **Description**: Current configuration options for the tour. ``` ```APIDOC ### `group` - **Type**: `string` - **Read-Only**: No - **Description**: The current tour group identifier. ``` ```APIDOC ### `dialog` - **Type**: `HTMLElement` - **Read-Only**: No - **Description**: The DOM element for the tour dialog. ``` ```APIDOC ### `backdrop` - **Type**: `HTMLElement` - **Read-Only**: No - **Description**: The DOM element for the tour backdrop. ``` ```APIDOC ### `isFinished(group?)` - **Type**: `Function` - **Read-Only**: No - **Description**: Checks the completion status of a tour group. Accepts an optional group name. ``` -------------------------------- ### Strict Steps Tutorial Configuration Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/configuration.md Configure a tutorial tour to enforce strict step behavior, disabling step remembering, and focusing on dialog interaction with instant transitions. ```javascript const tg = new TourGuideClient({ rememberStep: false, // Always start fresh completeOnFinish: false, // Don't lock tour activeStepInteraction: false, // Focus on dialog dialogAnimate: false, // Instant transitions autoScroll: true }); ``` -------------------------------- ### TourGuideOptions Properties Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/api-quick-reference.md Configuration options for customizing the tour guide's behavior and appearance. ```APIDOC ## TourGuideOptions Properties ### Display Options - **`backdropColor`** (string) - Default: `"rgba(20,20,21,0.84)"` - Overlay color. - **`backdropClass`** (string) - Default: `""` - Custom backdrop CSS class. - **`backdropAnimate`** (boolean) - Default: `true` - Whether to animate the backdrop. - **`dialogClass`** (string) - Default: `""` - Custom dialog CSS class. - **`dialogZ`** (number) - Default: `999` - Z-index value for the dialog. - **`dialogWidth`** (number) - Default: `0` - Fixed width for the dialog. - **`dialogMaxWidth`** (number) - Default: `340` - Maximum width for the dialog. - **`dialogAnimate`** (boolean) - Default: `true` - Whether to animate the dialog. - **`dialogPlacement`** (Placement) - Default: `undefined` - Preferred position for the dialog. ``` ```APIDOC ### Interaction Options - **`keyboardControls`** (boolean) - Default: `true` - Enable keyboard navigation controls. - **`exitOnEscape`** (boolean) - Default: `true` - Allow closing the tour by pressing the Escape key. - **`exitOnClickOutside`** (boolean) - Default: `true` - Allow closing the tour by clicking outside the dialog. - **`activeStepInteraction`** (boolean) - Default: `true` - Allow interaction with the target element of the active step. ``` ```APIDOC ### Progress Options - **`showStepDots`** (boolean) - Default: `true` - Show progress dots for steps. - **`stepDotsPlacement`** ( "footer" | "body" ) - Default: `"footer"` - Placement of the step dots. - **`showStepProgress`** (boolean) - Default: `true` - Show the step counter. - **`progressBar`** (string) - Default: `""` - Color of the progress bar. - **`showButtons`** (boolean) - Default: `true` - Show navigation buttons. - **`hideNext`** (boolean) - Default: `false` - Hide the 'Next' button. - **`hidePrev`** (boolean) - Default: `false` - Hide the 'Previous' button. - **`closeButton`** (boolean) - Default: `true` - Show the close button. ``` ```APIDOC ### Button Labels - **`nextLabel`** (string) - Default: `"Next"` - Text for the 'Next' button. - **`prevLabel`** (string) - Default: `"Back"` - Text for the 'Previous' button. - **`finishLabel`** (string) - Default: `"Finish"` - Text for the 'Finish' button. ``` ```APIDOC ### Scroll & Positioning - **`autoScroll`** (boolean) - Default: `true` - Enable automatic scrolling to the target element. - **`autoScrollSmooth`** (boolean) - Default: `true` - Enable smooth scrolling animation. - **`autoScrollOffset`** (number) - Default: `20` - Offset from the edge when scrolling to the target. - **`targetPadding`** (number) - Default: `30` - Padding around the target element. - **`allowDialogOverlap`** (boolean) - Default: `false` - Allow the dialog to overlap the target element. ``` ```APIDOC ### State Options - **`completeOnFinish`** (boolean) - Default: `true` - Save tour completion status. - **`rememberStep`** (boolean) - Default: `false` - Resume the tour from the last step. - **`debug`** (boolean) - Default: `true` - Enable debug logging. - **`steps`** (TourGuideStep[]) - Default: `[]` - Initial array of tour steps. ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/event-system-and-errors.md Initialize TourGuideClient with the debug option set to true to log warnings and informational messages to the browser console. ```javascript const tg = new TourGuideClient({ debug: true // Log warnings and info }); ``` -------------------------------- ### Local Storage for Completed Tours Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/architecture-internals.md Example of how completed tours are stored in localStorage. This format allows tracking which tours have been finished by a user. ```javascript localStorage.tg_tours_complete = "onboarding,features,admin" ``` -------------------------------- ### Track Memory Usage Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/event-system-and-errors.md Monitor JavaScript heap size before and after starting a tour. This helps identify potential memory leaks introduced by the tour. ```javascript if (performance.memory) { console.log('Memory before:', performance.memory.usedJSHeapSize); await tg.start(); console.log('Memory after:', performance.memory.usedJSHeapSize); } ``` -------------------------------- ### Handle 'Tour Already Active' Error Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/event-system-and-errors.md Prevent errors by ensuring that `exit()` is called before starting a new tour if a tour is already in progress. ```javascript const tg = new TourGuideClient(); await tg.start(); await tg.start(); // Error: Tour already active ``` -------------------------------- ### Update Configuration at Runtime Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/configuration.md Use the `setOptions()` method to dynamically update configuration settings after the `TourGuideClient` has been initialized. The tour will automatically refresh to reflect these changes. ```javascript const tg = new TourGuideClient(); // Later, update options await tg.setOptions({ backdropColor: 'rgba(255, 0, 0, 0.5)', keyboardControls: false }); ``` -------------------------------- ### initListeners Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/tourguideclient.md Initializes all event listeners for the tour, including navigation buttons, window events, and keyboard controls. This method is called automatically when a tour starts. ```APIDOC ## initListeners ### Description Initializes all event listeners for the tour, including navigation buttons, window events, and keyboard controls. This method is called automatically when a tour starts. ### Method ```typescript initListeners(): Promise ``` ### Parameters None ### Response #### Success Response (200) - **boolean**: Indicates if listeners were successfully initialized. ``` -------------------------------- ### Custom Dialog and Backdrop Classes Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/styling-and-dom.md Initialize TourGuideClient with custom CSS classes for the dialog and backdrop. This allows for extensive theming and styling of the tour interface. ```javascript const tg = new TourGuideClient({ dialogClass: 'onboarding-dialog', backdropClass: 'onboarding-backdrop' }); ``` -------------------------------- ### Component-Generated Content (Vue Example) Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/step-management.md Generate step content using framework components, such as Vue. The content is typically the DOM element rendered by the component. ```javascript // Vue example const vueComponent = new Vue({ template: '
Step content
' }); const step = { target: '#feature', content: vueComponent.$el }; // Or create from template const template = document.querySelector('#step-template'); const content = template.cloneNode(true); const step = { target: '#feature', content: content }; ``` -------------------------------- ### Unit Test TourGuide.js Handlers Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/architecture-internals.md Demonstrates how to unit test handlers by mocking the TourGuideClient and asserting state changes after calling a handler. ```javascript const mockClient = { tourSteps: [step1, step2], activeStep: 0, options: defaultOptions, dialog: document.createElement('div') } // Call handler await handleVisitStep.call(mockClient, 1) // Assert state changes assert.equal(mockClient.activeStep, 1) ``` -------------------------------- ### Basic Tour with Hardcoded Steps Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/usage-examples.md Define tour steps programmatically using an array of step objects. Ensure the tourguide-js CSS is imported. ```javascript import { TourGuideClient } from "@sjmc11/tourguidejs"; import "@sjmc11/tourguidejs/src/scss/tour.scss"; const tg = new TourGuideClient({ steps: [ { target: '#welcome-banner', title: 'Welcome', content: 'Thanks for joining us! Let\'s get started.', order: 1 }, { target: '#main-nav', title: 'Navigation', content: 'Use this menu to navigate the app.', order: 2 }, { target: '#dashboard', title: 'Your Dashboard', content: 'All your stats appear here.', order: 3 } ] }); // Start on button click document.querySelector('#start-tour').addEventListener('click', () => { tg.start(); }); ``` -------------------------------- ### Tourguide.js Project Structure Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/architecture-internals.md Overview of the tourguide-js project directory layout, including source files, compiled output, and configuration. ```tree tourguide-js/ ├── src/ │ ├── Tour.ts # Main TourGuideClient class │ ├── Tour.d.ts # TypeScript definitions │ ├── core/ │ │ ├── backdrop.ts # Backdrop overlay creation & positioning │ │ ├── callbacks.ts # Global callback registration │ │ ├── dialog.ts # Dialog HTML & positioning │ │ ├── dots.ts # Progress dots rendering │ │ ├── listeners.ts # Event listener management │ │ ├── options.ts # Configuration types │ │ ├── positioning.ts # Position computation orchestration │ │ ├── scrollTo.ts # Auto-scroll implementation │ │ └── steps.ts # Step computation & filtering │ ├── handlers/ │ │ ├── handleAddStep.ts # Dynamic step addition │ │ ├── handleClose.ts # Tour exit logic │ │ ├── handleFinishTour.ts # Completion & localStorage │ │ ├── handleRefresh.ts # Recomputation logic │ │ ├── handleSetOptions.ts # Options update │ │ ├── handleTourStart.ts # Tour initialization │ │ └── handleVisitStep.ts # Navigation & step lifecycle │ ├── types/ │ │ └── TourGuideStep.ts # Step type definition │ ├── util/ │ │ ├── util_default_options.ts # Default config │ │ ├── util_promise.ts # Promise utilities │ │ └── util_wait_for_element.ts # DOM wait utility │ └── scss/ │ └── tour.scss # Styling ├── dist/ │ ├── tour.js # Compiled output │ └── tour.d.ts # Type definitions └── package.json ``` -------------------------------- ### Measure Navigation Time Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/event-system-and-errors.md Track the time it takes for a step to render after navigation. Use `onBeforeStepChange` to record the start time and `onAfterStepChange` to calculate and log the duration. ```javascript let navigationStart; tg.onBeforeStepChange((current, next) => { navigationStart = performance.now(); }); tg.onAfterStepChange((prev, current) => { const duration = performance.now() - navigationStart; console.log(`Step ${current} rendered in ${duration.toFixed(2)}ms`); }); ``` -------------------------------- ### Custom Theming with TourGuide.js Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/README.md Shows how to customize the dialog and backdrop classes and colors for TourGuide.js. This allows for unique branding and appearance. ```javascript const tg = new TourGuideClient({ dialogClass: 'custom-theme', backdropClass: 'custom-backdrop', backdropColor: 'rgba(100, 100, 100, 0.8)' }); ``` ```css .custom-theme { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 12px; color: white; } .custom-theme .tg-dialog-btn { background: white; color: #667eea; } ``` -------------------------------- ### Override Arrow Styles with CSS Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/styling-and-dom.md Customize the appearance of the arrow element used in the tour guide, controlling its size, color, and positioning. This applies to the `.tg-arrow` class. ```css .tg-arrow { width: 10px; height: 10px; background: white; position: absolute; pointer-events: none; } ``` -------------------------------- ### Configure State & Persistence Options Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/configuration.md Enable saving tour completion status and resuming from the last step. Define pre-defined tour steps. ```javascript const tg = new TourGuideClient({ completeOnFinish: true, rememberStep: true, // Remembers last step steps: [ // step definitions ] }); ``` -------------------------------- ### HTML Attribute-Based Tour Source: https://github.com/sjmc11/tourguide-js/blob/main/_autodocs/usage-examples.md Define tour steps directly within HTML elements using data attributes. This approach simplifies setup for static content. ```html
``` ```javascript const tg = new TourGuideClient(); await tg.start(); ```