### Create and Start a Shepherd Tour Source: https://github.com/shipshapecode/shepherd/blob/main/shepherd.js/test/cypress/dummy/index.html Initialize a new Shepherd tour with default options and add a step. The tour is then started to guide the user. ```javascript const tour = new Shepherd.Tour({ defaultStepOptions: { classes: 'shadow-md bg-purple-dark', scrollTo: true } }); tour.addStep({ title: 'Example Shepherd', text: 'Creating a Shepherd is easy too! Just create ...', attachTo: { element: '.hero-example', on: 'bottom' }, advanceOn: { selector: '.docs-link', event: 'click' }, id: 'example' }); tour.start(); ``` ```javascript import Shepherd from '../../../dist/js/shepherd.mjs'; window.Shepherd = Shepherd; ``` -------------------------------- ### Create and Start a Basic Tour Source: https://github.com/shipshapecode/shepherd/blob/main/shepherd.js/dummy/index.html Initialize a new Shepherd tour with default options and add a single step. This example demonstrates basic tour creation and starting the tour. ```javascript const tour = new Shepherd.Tour({ defaultStepOptions: { classes: 'shadow-md bg-purple-dark', scrollTo: true } }); tour.addStep({ title: 'Example Shepherd', text: 'Creating a Shepherd is easy too! Just create ...', attachTo: { element: '.hero-example', on: 'bottom' }, advanceOn: { selector: '.docs-link', event: 'click' }, id: 'example' }); tour.start(); ``` -------------------------------- ### Start the Tour Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/src/content/docs/guides/usage.md Initiate the tour by calling the `start` method on the Tour instance. This will display the first step according to the tour's configuration. ```javascript tour.start(); ``` -------------------------------- ### Basic Tour Initialization and Step Addition Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/src/content/docs/guides/usage.md Demonstrates how to import Shepherd, create a new Tour instance with default options, add a step, and start the tour. ```APIDOC ## Basic Tour Initialization and Step Addition ### Description This example shows the fundamental steps to get started with Shepherd.js: importing the library, creating a tour instance with custom options, defining a step, and initiating the tour. ### Method N/A (JavaScript execution) ### Endpoint N/A (Client-side JavaScript) ### Parameters N/A ### Request Example ```javascript import Shepherd from 'shepherd.js'; const tour = new Shepherd.Tour({ useModalOverlay: true, defaultStepOptions: { classes: 'shadow-md bg-purple-dark', scrollTo: true } }); tour.addStep({ id: 'example-step', text: 'This step is attached to the bottom of the .example-css-selector element.', attachTo: { element: '.example-css-selector', on: 'bottom' }, classes: 'example-step-extra-class', buttons: [ { text: 'Next', action: tour.next } ] }); tour.start(); ``` ### Response N/A (Tour is initiated and displayed on the page) ``` -------------------------------- ### Install Shepherd.js with pnpm Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/src/content/docs/guides/install.mdx Use pnpm to install Shepherd.js, a fast, disk-space-efficient package manager. ```bash pnpm add shepherd.js ``` -------------------------------- ### Install react-shepherd Source: https://github.com/shipshapecode/shepherd/blob/main/packages/react/README.md Install the react-shepherd package using npm. ```bash npm install --save react-shepherd ``` -------------------------------- ### Install Shepherd.js with bun Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/src/content/docs/guides/install.mdx Use bun, a fast all-in-one JavaScript runtime, to add Shepherd.js to your project. ```bash bun add shepherd.js ``` -------------------------------- ### Tour Instance Methods Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/src/content/docs/guides/usage.md Details methods available on a Tour instance, such as adding, removing, starting, and controlling steps. ```APIDOC ## Tour Instance Methods ### Description This section outlines the key methods available on a `Tour` instance for managing the tour's lifecycle and steps. ### Methods - `tour.addStep(stepOptions)`: Adds a new step to the tour. - `tour.removeStep(stepId)`: Removes a step from the tour by its ID. - `tour.start()`: Starts the tour. - `tour.next()`: Advances to the next step. - `tour.back()`: Goes back to the previous step. - `tour.cancel()`: Cancels the tour. - `tour.complete()`: Marks the tour as complete. - `tour.show(stepId)`: Shows a specific step by its ID. - `tour.hide()`: Hides the current step. - `tour.destroy()`: Destroys the tour instance and cleans up. ### Request Example ```javascript // Assuming 'tour' is an initialized Shepherd.Tour instance // Add a step tour.addStep({ id: 'step-2', text: 'This is the second step.', attachTo: { element: '#element-id', on: 'right' }, buttons: [ { text: 'Back', action: tour.back }, { text: 'Finish', action: tour.complete } ] }); // Remove a step tour.removeStep('example-step'); // Start the tour tour.start(); // Navigate to the next step tour.next(); // Cancel the tour tour.cancel(); ``` ### Response N/A (Methods control tour behavior and state) ``` -------------------------------- ### Install Shepherd.js with npm Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/src/content/docs/guides/install.mdx Use npm to install Shepherd.js as a dependency for your project. ```bash npm install shepherd.js --save ``` -------------------------------- ### Install Shepherd.js with yarn Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/src/content/docs/guides/install.mdx Use yarn to add Shepherd.js to your project's dependencies. ```bash yarn add shepherd.js ``` -------------------------------- ### Starlight Project Commands Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/README.md Common npm commands for managing your Starlight project. Use `npm run dev` to start a local development server and `npm run build` to create a production build. ```bash npm install ``` ```bash npm run dev ``` ```bash npm run build ``` ```bash npm run preview ``` ```bash npm run astro ... ``` ```bash npm run astro -- --help ``` -------------------------------- ### Get Step and Tour Information Source: https://context7.com/shipshapecode/shepherd/llms.txt Access tour and step state information for conditional logic and debugging. This includes getting steps by ID, the current step, and checking the tour's active status. ```javascript // Get step by ID const welcomeStep = tour.getById('welcome'); console.log('Welcome step:', welcomeStep); // Get current step const current = tour.getCurrentStep(); if (current) { console.log('Current step ID:', current.id); console.log('Step is open:', current.isOpen()); console.log('Step element:', current.getElement()); console.log('Target element:', current.getTarget()); console.log('Step tour:', current.getTour()); } // Check tour status console.log('Tour is active:', tour.isActive()); console.log('Total steps:', tour.steps.length); // Access active tour globally if (Shepherd.activeTour) { console.log('Active tour ID:', Shepherd.activeTour.id); console.log('Active tour current step:', Shepherd.activeTour.getCurrentStep()?.id); } ``` -------------------------------- ### Control Tour Navigation and State Source: https://context7.com/shipshapecode/shepherd/llms.txt Use these methods to start, navigate, show specific steps, cancel, complete, and check the status of a tour. Ensure the tour instance is available before calling these methods. ```javascript // Start the tour tour.start(); ``` ```javascript // Navigate programmatically document.getElementById('next-btn').addEventListener('click', () => { tour.next(); }); ``` ```javascript document.getElementById('back-btn').addEventListener('click', () => { tour.back(); }); ``` ```javascript // Show a specific step by ID document.getElementById('jump-to-feature').addEventListener('click', () => { tour.show('feature-highlight'); }); ``` ```javascript // Show a specific step by index tour.show(2); // Shows the third step (0-indexed) ``` ```javascript // Cancel the tour document.getElementById('exit-tour').addEventListener('click', () => { tour.cancel(); }); ``` ```javascript // Complete the tour manually document.getElementById('finish-tour').addEventListener('click', () => { tour.complete(); }); ``` ```javascript // Check if tour is active if (tour.isActive()) { console.log('Tour is currently running'); } ``` ```javascript // Get current step const currentStep = tour.getCurrentStep(); console.log('Current step ID:', currentStep?.id); ``` ```javascript // Hide current step without ending tour tour.hide(); ``` -------------------------------- ### Usage via Provider/Context in React Source: https://github.com/shipshapecode/shepherd/blob/main/packages/react/README.md Demonstrates how to use react-shepherd with the ShepherdJourneyProvider and useShepherd hook to create and start a tour dynamically. Ensure newSteps is imported from its respective file. ```tsx import { Component, useContext } from 'react'; import { ShepherdJourneyProvider, useShepherd } from 'react-shepherd'; import newSteps from './steps'; const tourOptions = { defaultStepOptions: { cancelIcon: { enabled: true } }, useModalOverlay: true }; function Button() { const Shepherd = useShepherd(); const tour = new Shepherd.Tour({ ...tourOptions, steps: newSteps }); return ( ); } export default function App() { return (
); } ``` -------------------------------- ### Add Custom Progress Indicator Source: https://context7.com/shipshapecode/shepherd/llms.txt Add a custom progress indicator showing current step position using the `when` show event. This example demonstrates creating and inserting a progress indicator into the tour footer. ```javascript tour.addStep({ id: 'step-with-progress', title: 'Feature Tour', text: 'Learn about our features.', when: { show() { const currentStep = Shepherd.activeTour?.getCurrentStep(); const currentStepElement = currentStep?.getElement(); const footer = currentStepElement?.querySelector('.shepherd-footer'); // Create progress indicator const progress = document.createElement('span'); progress.className = 'shepherd-progress'; const currentIndex = Shepherd.activeTour?.steps.indexOf(currentStep) + 1; const totalSteps = Shepherd.activeTour?.steps.length; progress.innerText = `${currentIndex} of ${totalSteps}`; // Insert before the last button const lastButton = currentStepElement?.querySelector('.shepherd-button:last-child'); footer?.insertBefore(progress, lastButton); } }, buttons: [ { text: 'Back', secondary: true, action: function() { this.back(); } }, { text: 'Next', action: function() { this.next(); } } ] }); ``` -------------------------------- ### Add a Step to the Tour Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/src/content/docs/guides/usage.md Add a step to the tour using the `addStep` method. This example defines a step with an ID, text content, attachment details (element selector and position), custom CSS classes, and buttons with actions. ```javascript tour.addStep({ id: 'example-step', text: 'This step is attached to the bottom of the .example-css-selector element.', attachTo: { element: '.example-css-selector', on: 'bottom' }, classes: 'example-step-extra-class', buttons: [ { text: 'Next', action: tour.next } ] }); ``` -------------------------------- ### Handle Modal Shown Event Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/src/content/docs/guides/usage.md Use `beforeShowPromise` to delay the step display until an asynchronous operation completes. This example waits for a Bootstrap modal's `shown.bs.modal` event before resolving the promise. ```javascript beforeShowPromise: function() { return new Promise(function(resolve) { $('#my-bootstrap-modal').on('shown.bs.modal', function () { resolve(); }); }); }, ``` -------------------------------- ### Initialize Astro Blog Project Source: https://github.com/shipshapecode/shepherd/blob/main/landing/README.md Use this command to scaffold a new Astro project using the blog template. ```sh npm create astro@latest -- --template blog ``` -------------------------------- ### Tour Instance API Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/src/content/docs/guides/usage.md Explains how to create Tour instances and lists the available configuration options for the Tour constructor. ```APIDOC ## Tour Instance API ### Description This section details the creation of `Tour` instances and the various options that can be passed to the constructor to customize tour behavior. ### Method `new Shepherd.Tour(options)` ### Endpoint N/A (Client-side JavaScript constructor) ### Parameters #### Request Body (Tour Options) - **classPrefix** (string) - Optional - Prefix for generated class names. - **confirmCancel** (boolean | function) - Optional - If true, prompts confirmation before cancelling. If a function, it's called and its return value determines cancellation. - **confirmCancelMessage** (string) - Optional - Message displayed in the confirmation dialog. - **defaultStepOptions** (object) - Optional - Default options applied to all steps. - **exitOnEsc** (boolean) - Optional - Enables/disables exiting the tour with the Escape key (defaults to true). - **keyboardNavigation** (boolean) - Optional - Enables/disables navigation using arrow keys (defaults to true). - **stepsContainer** (HTMLElement) - Optional - A container element for steps; defaults to `document.body`. - **modalContainer** (HTMLElement) - Optional - A container element for the modal overlay; defaults to `document.body`. - **steps** (array) - Optional - An array of step options objects or Step instances to initialize the tour with. - **tourName** (string) - Optional - An optional name for the tour, appended to its ID. - **useModalOverlay** (boolean) - Optional - Determines if a modal overlay is used (defaults to true). ### Request Example ```javascript const myTour = new Shepherd.Tour({ classPrefix: 'my-tour-prefix', confirmCancel: true, confirmCancelMessage: 'Are you sure you want to exit this tour?', defaultStepOptions: { classes: 'custom-step-class', scrollTo: false }, exitOnEsc: false, keyboardNavigation: true, steps: [ // Array of step options objects or Step instances ], tourName: 'Welcome Tour', useModalOverlay: false }); ``` ### Response N/A (Returns a `Tour` instance ``` -------------------------------- ### Initialize a Basic Shepherd Tour Source: https://github.com/shipshapecode/shepherd/blob/main/shepherd.js/dev/index.html Create a simple tour instance with default step options and a single step. ```javascript const tour = new Shepherd.Tour({ defaultStepOptions: { classes: 'shadow-md bg-purple-dark', scrollTo: true } }); tour.addStep({ title: 'Example Shepherd', text: 'Creating a Shepherd is easy too! Just create ...', attachTo: { element: '.hero-example', on: 'bottom' }, advanceOn: { selector: '.docs-link', event: 'click' }, id: 'example' }); tour.start(); ``` -------------------------------- ### Initialize a Full Shepherd Tour Source: https://github.com/shipshapecode/shepherd/blob/main/shepherd.js/dev/index.html Configure a comprehensive tour with multiple steps, modal overlays, and custom button actions. ```javascript import Shepherd from '/js/shepherd.mjs'; const tour = new Shepherd.Tour({ defaultStepOptions: { cancelIcon: { enabled: true } }, useModalOverlay: true, steps: [ { text: `

Shepherd is a JavaScript library for guiding users through your app. It uses Floating UI, another open source library, to render dialogs for each tour "step".

Among many things, Floating UI makes sure your steps never end up off screen or cropped by an overflow. (Try resizing your browser to see what we mean.)

`, attachTo: { element: '.hero-welcome', on: 'bottom' }, classes: 'shepherd-step-element shepherd-transparent-text first-step', buttons: [ { action() { return this.cancel(); }, classes: 'shepherd-button-secondary', text: 'Exit' }, { action() { return this.next(); }, classes: 'shepherd-button-example-primary', text: 'Next' } ], id: 'welcome' }, { title: 'Including', text: 'Including Shepherd is easy! Just include shepherd.js. The styles are bundled with the JS.', attachTo: { element: '.hero-including', on: 'bottom' }, buttons: [ { action() { return this.back(); }, classes: 'shepherd-button-secondary', text: 'Back' }, { action() { return this.next(); }, classes: 'shepherd-button-example-primary', text: 'Next' } ], id: 'including', classes: 'shepherd-step-element second-step' }, { title: 'Example Shepherd', text: 'Creating a Shepherd is easy too! Just create Shepherd and add as many steps as you want. Check out the documentation to learn more.', attachTo: { element: '.hero-example', on: 'bottom' }, buttons: [ { action() { return this.back(); }, classes: 'shepherd-button-secondary', text: 'Back' }, { action() { return this.next(); }, classes: 'shepherd-button-example-primary', text: 'Next' } ], id: 'example', classes: 'shepherd-step-element third-step' }, { title: 'Learn more', text: 'Star Shepherd on Github so you remember it for your next project', attachTo: { element: '.hero-followup', on: 'left' }, buttons: [ { action() { return this.back(); }, classes: 'shepherd-button-secondary', text: 'Back' }, { action() { return this.next(); }, classes: 'shepherd-button-example-primary', text: 'Done' } ], id: 'followup', classes: 'shepherd-step-element fourth-step' } ] }); tour.start(); ``` -------------------------------- ### Create a Tour Instance with Options Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/src/content/docs/guides/usage.md Instantiate a new Shepherd Tour object by passing a configuration object to the `Shepherd.Tour` constructor. This allows for customization of tour behavior and appearance. ```javascript const myTour = new Shepherd.Tour(options); ``` -------------------------------- ### Add the final step to complete the tour Source: https://context7.com/shipshapecode/shepherd/llms.txt Define the last step of the tour, which provides a 'Finish' button to conclude the guided experience. ```javascript tour.addStep({ id: 'final-step', title: 'You\'re All Set!', text: 'You now know the basics. Click \'Finish\' to complete the tour.', buttons: [ { text: 'Finish', action: function() { this.complete(); } } ] }); ``` -------------------------------- ### Create a New Tour Instance Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/src/content/docs/guides/usage.md Initialize a new Shepherd Tour instance. The `useModalOverlay` option enables a modal overlay, and `defaultStepOptions` allows setting common configurations for all steps, such as styling and scroll behavior. ```javascript const tour = new Shepherd.Tour({ useModalOverlay: true, defaultStepOptions: { classes: 'shadow-md bg-purple-dark', scrollTo: true } }); ``` -------------------------------- ### Create a new Shepherd.js Tour instance Source: https://context7.com/shipshapecode/shepherd/llms.txt Initialize a new Shepherd.js tour with various configuration options such as modal overlay, keyboard navigation, and confirmation messages. ```javascript import Shepherd from 'shepherd.js'; const tour = new Shepherd.Tour({ useModalOverlay: true, exitOnEsc: true, keyboardNavigation: true, confirmCancel: true, confirmCancelMessage: 'Are you sure you want to exit the tour?', defaultStepOptions: { classes: 'shadow-md bg-purple-dark', scrollTo: { behavior: 'smooth', block: 'center' }, cancelIcon: { enabled: true, label: 'Close Tour' } } }); // Tour is ready to have steps added console.log('Tour created with ID:', tour.id); ``` -------------------------------- ### Initialize Shepherd Tour with Steps Source: https://github.com/shipshapecode/shepherd/blob/main/shepherd.js/dummy/index.html This code initializes a Shepherd tour with multiple steps, each configured with text, attachment points, buttons, and unique IDs. It demonstrates advanced step configuration and tour initialization. ```javascript import Shepherd from '../dist/js/shepherd.mjs'; window.Shepherd = Shepherd; const shepherd = new Shepherd.Tour({ defaultStepOptions: { cancelIcon: { enabled: true } }, useModalOverlay: true }); const steps = [ { text: `

Shepherd is a JavaScript library for guiding users through your app. It uses Floating UI, another open source library, to render dialogs for each tour "step".

Among many things, Floating UI makes sure your steps never end up off screen or cropped by an overflow. (Try resizing your browser to see what we mean.)

`, attachTo: { element: '.hero-welcome', on: 'bottom' }, classes: 'shepherd-step-element shepherd-transparent-text first-step', buttons: [ { action: shepherd.cancel, classes: 'shepherd-button-secondary', text: 'Exit' }, { action: shepherd.next, classes: 'shepherd-button-example-primary', text: 'Next' } ], id: 'welcome' }, { title: 'Including', text: 'Including Shepherd is easy! Just include shepherd.js. The styles are bundled with the JS.', attachTo: { element: '.hero-including', on: 'bottom' }, buttons: [ { action: shepherd.back, classes: 'shepherd-button-secondary', text: 'Back' }, { action: shepherd.next, classes: 'shepherd-button-example-primary', text: 'Next' } ], id: 'including', classes: 'shepherd-step-element second-step' }, { title: 'Example Shepherd', text: 'Creating a Shepherd is easy too! Just create Shepherd and add as many steps as you want. Check out the documentation to learn more.', attachTo: { element: '.hero-example', on: 'bottom' }, buttons: [ { action: shepherd.back, classes: 'shepherd-button-secondary', text: 'Back' }, { action: shepherd.next, classes: 'shepherd-button-example-primary', text: 'Next' } ], id: 'example', classes: 'shepherd-step-element third-step' }, { title: 'Learn more', text: 'Star Shepherd on Github so you remember it for your next project', attachTo: { element: '.hero-followup', on: 'left' }, buttons: [ { action: shepherd.back, classes: 'shepherd-button-secondary', text: 'Back' }, { action: shepherd.next, classes: 'shepherd-button-example-primary', text: 'Done' } ], id: 'followup', classes: 'shepherd-step-element fourth-step' } ]; shepherd.addSteps(steps); shepherd.start(); ``` -------------------------------- ### Create a New Starlight Project Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/README.md Use this command to create a new Astro project with the Starlight template. This sets up the basic structure for your documentation site. ```bash npm create astro@latest -- --template starlight ``` -------------------------------- ### Starlight Project Structure Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/README.md Understand the default directory layout for a Starlight project. Key directories include `src/content/docs/` for Markdown files and `public/` for static assets. ```bash .\n├── public/\n├── src/\n│ ├── assets/\n│ ├── content/\n│ │ ├── docs/\n│ │ └── config.ts\n│ └── env.d.ts\n├── astro.config.mjs\n├── package.json\n└── tsconfig.json ``` -------------------------------- ### View Project Directory Structure Source: https://github.com/shipshapecode/shepherd/blob/main/landing/README.md Visual representation of the standard Astro project file layout. ```text ├── public/ ├── src/ │ ├── components/ │ ├── content/ │ ├── layouts/ │ └── pages/ ├── astro.config.mjs ├── README.md ├── package.json └── tsconfig.json ``` -------------------------------- ### Add multiple steps using addSteps() Source: https://context7.com/shipshapecode/shepherd/llms.txt Define an array of step configurations and add them all to the tour at once using the `addSteps()` method. ```javascript const tourSteps = [ { id: 'step-1', title: 'Navigation Menu', text: 'Use this menu to navigate between different sections.', attachTo: { element: '.nav-menu', on: 'bottom' }, buttons: [ { text: 'Next', action: function() { this.next(); } } ] }, { id: 'step-2', title: 'Search Feature', text: 'Search for anything using this search bar.', attachTo: { element: '#search-input', on: 'bottom' }, buttons: [ { text: 'Back', secondary: true, action: function() { this.back(); } }, { text: 'Next', action: function() { this.next(); } } ] }, { id: 'step-3', title: 'User Profile', text: 'Access your profile settings here.', attachTo: { element: '.user-profile', on: 'left' }, buttons: [ { text: 'Back', secondary: true, action: function() { this.back(); } }, { text: 'Complete', action: function() { this.complete(); } } ] } ]; tour.addSteps(tourSteps); tour.start(); ``` -------------------------------- ### Initialize Shepherd Library Source: https://github.com/shipshapecode/shepherd/blob/main/shepherd.js/test/cypress/examples/destroying-elements.html Imports the Shepherd module and attaches it to the global window object for access. ```javascript import Shepherd from '../../../dist/js/shepherd.mjs'; window.Shepherd = Shepherd; ``` -------------------------------- ### React Context Pattern for Shepherd Tours Source: https://context7.com/shipshapecode/shepherd/llms.txt Set up Shepherd tour as a React context for app-wide access to the same tour instance. Ensure the hook is used within the provider. ```javascript import React, { createContext, useContext } from 'react'; import Shepherd from 'shepherd.js'; const ShepherdTourContext = createContext(null); const tourInstance = new Shepherd.Tour({ useModalOverlay: true, defaultStepOptions: { cancelIcon: { enabled: true }, scrollTo: true } }); export function ShepherdTourProvider({ children }) { return ( {children} ); } export function useTour() { const tour = useContext(ShepherdTourContext); if (!tour) { throw new Error('useTour must be used within ShepherdTourProvider'); } return tour; } // Usage function HomePage() { const tour = useTour(); const setupAndStartTour = () => { // Clear existing steps while (tour.steps.length) { tour.removeStep(tour.steps[0].id); } // Add page-specific steps tour.addSteps([ { id: 'home-intro', title: 'Home Page', text: 'This is your dashboard.', attachTo: { element: '.dashboard', on: 'bottom' }, buttons: [{ text: 'Got it!', action: function() { this.complete(); } }] } ]); tour.start(); }; return (
); } ``` -------------------------------- ### Add another step with specific options Source: https://context7.com/shipshapecode/shepherd/llms.txt Add a step to the tour that highlights a specific feature, allowing users to navigate back and forth. ```javascript tour.addStep({ id: 'feature-highlight', title: 'Dashboard Overview', text: 'Here you can see all your important metrics at a glance.', attachTo: { element: '#dashboard-container', on: 'right' }, arrow: true, canClickTarget: true, scrollTo: true, buttons: [ { text: 'Back', secondary: true, action: function() { this.back(); } }, { text: 'Next', action: function() { this.next(); } } ] }); ``` -------------------------------- ### Step Configuration Options Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/src/content/docs/guides/usage.md Configuration properties available when defining a Shepherd step. ```APIDOC ## Step Configuration Options ### Parameters - **modalOverlayOpeningRadius** (number|object) - Optional - Border radius for the modal overlay opening. Can be a number or object with { topLeft, bottomLeft, bottomRight, topRight }. - **floatingUIOptions** (object) - Optional - Extra options passed to Floating UI. - **showOn** (function) - Optional - Function returning boolean to determine if the step should be shown. - **scrollTo** (boolean|object) - Optional - Configuration for scrolling to the element. If object, passed as params to scrollIntoView. - **scrollToHandler** (function) - Optional - Custom function to override default scroll behavior. - **when** (object) - Optional - Event hooks for step lifecycle (e.g., show, hide). - **arrow** (boolean|object) - Optional - Enables or configures the arrow element pointing to the target. ``` -------------------------------- ### Handle Tour and Step Events Source: https://context7.com/shipshapecode/shepherd/llms.txt Implement event listeners for tour lifecycle stages, step transitions, and global Shepherd events to integrate analytics or custom logic. ```javascript // Tour-level events tour.on('start', () => { console.log('Tour started'); analytics.track('tour_started', { tourId: tour.id }); }); tour.on('complete', () => { console.log('Tour completed'); analytics.track('tour_completed', { tourId: tour.id }); }); tour.on('cancel', () => { console.log('Tour cancelled'); analytics.track('tour_cancelled', { tourId: tour.id }); }); tour.on('show', ({ step, previous }) => { console.log(`Showing step: ${step.id}, previous: ${previous?.id}`); analytics.track('step_shown', { stepId: step.id }); }); tour.on('hide', () => { console.log('Step hidden'); }); // Step-level events using 'when' option tour.addStep({ id: 'tracked-step', title: 'Tracked Step', text: 'This step has event handlers.', when: { 'before-show': function() { console.log('About to show step'); }, show: function() { console.log('Step is now visible'); this.getElement().querySelector('.custom-element')?.focus(); }, 'before-hide': function() { console.log('About to hide step'); }, hide: function() { console.log('Step is now hidden'); }, destroy: function() { console.log('Step destroyed'); } } }); // Global Shepherd events (all tours) Shepherd.on('show', ({ tour, step }) => { console.log(`Global: ${tour.id} showing ${step.id}`); }); // One-time event binding tour.once('complete', () => { showCelebration(); }); ``` -------------------------------- ### Configure Step Attachment Options Source: https://context7.com/shipshapecode/shepherd/llms.txt Define where a step's tooltip attaches to an element and its positioning using Floating UI placement options. Supports direct element selectors, query selectors, or functions for dynamic elements. ```javascript // Attach to bottom of element tour.addStep({ id: 'attach-bottom', text: 'This tooltip appears below the target element.', attachTo: { element: '#target-element', on: 'bottom' } }); ``` ```javascript // Attach with specific alignment tour.addStep({ id: 'attach-aligned', text: 'This tooltip is aligned to the start of the right side.', attachTo: { element: '.sidebar', on: 'right-start' } }); ``` ```javascript // Lazy evaluation for dynamic elements tour.addStep({ id: 'dynamic-element', text: 'This step attaches to a dynamically loaded element.', attachTo: { element: () => document.querySelector('.dynamic-content'), on: 'top' } }); ``` ```javascript // Centered modal (no element attachment) tour.addStep({ id: 'centered-step', title: 'Important Announcement', text: 'This step appears in the center of the screen without attaching to any element.' }); ``` -------------------------------- ### Configure Event-Based Step Progression Source: https://context7.com/shipshapecode/shepherd/llms.txt Use advanceOn to automatically transition to the next step when a specific event occurs on a target element. Manual advancement can be implemented for complex interactions by checking step state. ```javascript tour.addStep({ id: 'click-to-advance', title: 'Click the Button', text: 'Click the "Add Item" button to continue the tour.', attachTo: { element: '#add-item-btn', on: 'bottom' }, advanceOn: { selector: '#add-item-btn', event: 'click' } }); tour.addStep({ id: 'input-to-advance', title: 'Enter Your Name', text: 'Type something in the input field and press Enter.', attachTo: { element: '#name-input', on: 'bottom' }, advanceOn: { selector: '#name-input', event: 'keypress' } }); // Manual advancement for complex user actions const complexStep = tour.addStep({ id: 'complex-action', title: 'Complete the Form', text: 'Fill out the entire form to proceed.', attachTo: { element: '#complex-form', on: 'right' } }); document.getElementById('complex-form').addEventListener('submit', (e) => { if (complexStep.isOpen()) { Shepherd.activeTour.next(); } }); ``` -------------------------------- ### Define Step Events with 'when' Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/src/content/docs/guides/usage.md Use the 'when' property to define lifecycle event handlers such as 'show' or 'hide'. ```javascript when: { show: function() { window.scrollTo(0, 0); } } ``` -------------------------------- ### Apply Custom Styling with CSS Classes Source: https://context7.com/shipshapecode/shepherd/llms.txt Apply custom CSS classes and prefixes to style tours independently or avoid conflicts with existing styles. Classes can be added at the tour level or per step. ```javascript // Add custom classes at tour level const styledTour = new Shepherd.Tour({ defaultStepOptions: { classes: 'shepherd-theme-custom my-custom-tour' } }); // Add custom classes per step styledTour.addStep({ id: 'styled-step', classes: 'highlighted-step important', highlightClass: 'my-highlight-class', title: 'Custom Styled Step', text: 'This step has custom styling applied.' }); // Use class prefix for multiple independent tours const tour1 = new Shepherd.Tour({ classPrefix: 'tour1-' }); const tour2 = new Shepherd.Tour({ classPrefix: 'tour2-' }); // CSS can then target each independently: // .tour1-shepherd-enabled { ... } // .tour2-shepherd-enabled { ... } ``` -------------------------------- ### Configure Tour Cancel Confirmation Source: https://context7.com/shipshapecode/shepherd/llms.txt Set up confirmation dialogs before allowing users to cancel a tour. Supports simple `window.confirm` or custom asynchronous confirmation functions. ```javascript // Simple window.confirm const tour1 = new Shepherd.Tour({ confirmCancel: true, confirmCancelMessage: 'Are you sure? You can restart the tour later.' }); ``` ```javascript // Custom async confirmation function const tour2 = new Shepherd.Tour({ confirmCancel: async () => { // Show custom modal and wait for user response const userConfirmed = await showCustomConfirmModal({ title: 'Exit Tour?', message: 'You can restart the tour from the help menu.', confirmText: 'Yes, exit', cancelText: 'Continue tour' }); return userConfirmed; } }); ``` ```javascript // Sync custom function const tour3 = new Shepherd.Tour({ confirmCancel: () => { // Only confirm if user hasn't completed more than half const currentIndex = Shepherd.activeTour?.steps.indexOf( Shepherd.activeTour?.getCurrentStep() ); const totalSteps = Shepherd.activeTour?.steps.length || 0; if (currentIndex < totalSteps / 2) { return window.confirm('You\'re almost done! Are you sure you want to exit?'); } return true; // Allow cancel without confirmation if past halfway } }); ``` -------------------------------- ### Tour Methods Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/src/content/docs/guides/usage.md Methods for managing steps and controlling the execution flow of a Shepherd tour. ```APIDOC ## Tour Methods ### addStep(options) Creates a new Step object with options and returns the Step instance. If no id is provided, one is generated. ### addSteps([Steps]) Adds multiple steps to the tour. ### getById(id) Returns a step with a specific id. ### isActive() Checks if the tour is currently active. ### next() Advances to the next step in the order they were added. ### back() Shows the previous step in the order they were added. ### cancel() Triggers cancel on the current step, hiding it without advancing. ### complete() Calls _done() triggering the complete event. ### hide() Hides the current step. ### show([id]) Shows the step specified by id (string) or index (number). Defaults to the first step. ### start() Shows the first step and begins the tour. ### getCurrentStep() Returns the currently shown step. ### removeStep(id) Removes the step from the tour. ``` -------------------------------- ### Apply offsets to tour steps Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/src/content/docs/recipes/cookbook.md Configure FloatingUI middleware within the floatingUIOptions to adjust the positioning of the tour step relative to its target. ```javascript import { offset } from '@floating-ui/dom'; const tour = new Shepherd.Tour({ steps: [ { ... floatingUIOptions: { middleware: [offset({ mainAxis: 0, crossAxis: 12 })] } ... } ] }); ``` -------------------------------- ### Conditionally Show or Skip Steps Source: https://context7.com/shipshapecode/shepherd/llms.txt The showOn function allows for runtime logic to determine if a step should be displayed, such as checking user roles, device types, or feature flags. ```javascript tour.addStep({ id: 'admin-only', title: 'Admin Features', text: 'These features are only available to administrators.', attachTo: { element: '.admin-panel', on: 'right' }, showOn: function() { // Only show this step for admin users return window.currentUser?.role === 'admin'; } }); tour.addStep({ id: 'mobile-step', title: 'Mobile Navigation', text: 'Swipe to navigate on mobile devices.', showOn: function() { // Only show on mobile devices return window.innerWidth < 768; } }); tour.addStep({ id: 'feature-flag-step', title: 'New Feature', text: 'Try our new beta feature!', attachTo: { element: '#new-feature', on: 'bottom' }, showOn: function() { // Only show if element exists and feature flag is enabled return document.querySelector('#new-feature') !== null && window.featureFlags?.newFeature === true; } }); ``` -------------------------------- ### Configure Floating UI Positioning Source: https://context7.com/shipshapecode/shepherd/llms.txt Use Floating UI middleware to control tooltip positioning and viewport constraints. Requires importing middleware from @floating-ui/dom. ```javascript import { offset, flip, shift } from '@floating-ui/dom'; tour.addStep({ id: 'custom-positioning', title: 'Custom Offset', text: 'This tooltip has a custom offset from the target element.', attachTo: { element: '#positioned-element', on: 'bottom' }, floatingUIOptions: { middleware: [ offset({ mainAxis: 20, crossAxis: 10 }), flip(), shift({ padding: 5 }) ] } }); tour.addStep({ id: 'constrained-positioning', title: 'Constrained Tooltip', text: 'This tooltip stays within the viewport boundaries.', attachTo: { element: '.edge-element', on: 'right' }, floatingUIOptions: { middleware: [ offset(10), flip({ fallbackPlacements: ['left', 'top', 'bottom'] }), shift({ padding: 10 }) ] } }); ``` -------------------------------- ### Apply custom classes to tour steps Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/src/content/docs/guides/styling.md Pass custom class names to the defaultStepOptions to hook into your own CSS rules. ```javascript let tour = new Shepherd.Tour({ defaultStepOptions: { classes: 'shepherd-theme-custom' } }); ``` -------------------------------- ### Create a custom Shepherd tour hook Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/src/content/docs/recipes/react.md Encapsulates the creation and memoization of a Shepherd tour instance based on provided options and steps. ```javascript export const useShepherdTour = ({ tourOptions, steps }) => { const tourObject = useMemo(() => { const tourInstance = new Shepherd.Tour(tourOptions); tourInstance.addSteps(steps); return tourInstance; }, [tourOptions, steps]); return tourObject; }; ``` -------------------------------- ### Specify Custom Containers for Tour Elements Source: https://context7.com/shipshapecode/shepherd/llms.txt Specify custom container elements for tour steps and modal overlay instead of using document.body. This allows for better control over where tour elements are rendered. ```javascript const tour = new Shepherd.Tour({ stepsContainer: document.getElementById('tour-container'), modalContainer: document.getElementById('modal-container'), useModalOverlay: true }); ``` -------------------------------- ### Manage Tooltip Arrow Configuration Source: https://context7.com/shipshapecode/shepherd/llms.txt Control the visibility and padding of the tooltip arrow for precise alignment. ```javascript // Arrow enabled (default) tour.addStep({ id: 'with-arrow', title: 'Step with Arrow', text: 'The arrow points to the target element.', attachTo: { element: '#target', on: 'bottom' }, arrow: true }); // Arrow disabled tour.addStep({ id: 'no-arrow', title: 'Step without Arrow', text: 'No arrow is displayed for this tooltip.', attachTo: { element: '#target', on: 'bottom' }, arrow: false }); // Arrow with custom padding tour.addStep({ id: 'arrow-padding', title: 'Padded Arrow', text: 'The arrow stays at least 10px from the tooltip edge.', attachTo: { element: '#target', on: 'bottom-start' }, arrow: { padding: 10 } }); ``` -------------------------------- ### Step Methods Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/src/content/docs/guides/usage.md Methods available on a Shepherd step instance to control its lifecycle and state. ```APIDOC ## Step Methods ### Methods - **show()** - Shows the step. - **hide()** - Hides the step. - **cancel()** - Hides the step and triggers the 'cancel' event. - **complete()** - Hides the step and triggers the 'complete' event. - **scrollTo()** - Scrolls to the step's element. - **isOpen()** - Returns true if the step is currently shown. - **destroy()** - Removes the element. - **on(eventName, handler, [context])** - Binds an event. - **off(eventName, [handler])** - Unbinds an event. - **once(eventName, handler, [context])** - Binds just the next instance of an event. ``` -------------------------------- ### Define Tour Element Styles Source: https://github.com/shipshapecode/shepherd/blob/main/shepherd.js/test/cypress/examples/destroying-elements.html Sets font families and positioning for tour step elements. ```css h1, h2 { font-family: Lato; } .first, .second { position: absolute; display: inline-block; padding: 50px; background: red; } .second { right: 0; background: blue; } ``` -------------------------------- ### Include Shepherd.js via jsDelivr CDN Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/src/content/docs/guides/install.mdx Include Shepherd.js and its CSS directly from the jsDelivr CDN. This method is useful for quick testing or projects that do not use a package manager. ```html ``` -------------------------------- ### Configure Step Buttons with Custom Actions Source: https://context7.com/shipshapecode/shepherd/llms.txt Customize step buttons with dynamic text, actions, classes, disabled states, ARIA labels, and HTML attributes for advanced control and testing. ```javascript tour.addStep({ id: 'button-examples', title: 'Advanced Button Options', text: 'Buttons can be fully customized.', buttons: [ { text: 'Skip', classes: 'shepherd-button-secondary custom-skip-btn', secondary: true, label: 'Skip this step', attrs: { 'data-test': 'skip-button', 'data-analytics-id': 'tour-skip' }, action: function() { this.next(); } }, { text: 'Learn More', classes: 'learn-more-btn', disabled: function() { // Dynamically disable based on condition return !document.querySelector('.required-field')?.value; }, action: function() { window.open('/docs', '_blank'); } }, { text: function() { // Dynamic text (useful for i18n) return window.translations?.next || 'Next'; }, label: function() { return window.translations?.nextLabel || 'Go to next step'; }, action: function() { this.next(); } } ] }); ``` -------------------------------- ### Import Shepherd.js Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/src/content/docs/guides/usage.md Import the Shepherd library using standard ES6 import syntax. This is typically the first step when setting up a tour in a project using module bundlers like Rollup or Webpack. ```javascript import Shepherd from 'shepherd.js'; ``` -------------------------------- ### Include Shepherd via Script Tag Source: https://github.com/shipshapecode/shepherd/blob/main/shepherd.js/dev/index.html Add the Shepherd library to your project using a module script tag. ```html ``` -------------------------------- ### Define Step Buttons with Actions Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/src/content/docs/guides/usage.md Add custom buttons to the step's footer using the `buttons` array. Each button can have custom text, classes, attributes, and an `action` function that executes on click. The `action` is bound to the tour instance. ```javascript buttons: [ { text: 'Next', action: function() { return this.next(); } }, { text: 'Skip', secondary: true, action: function() { return this.cancel(); } } ] ``` ```javascript action() { return this.show('some_step_name'); } ``` -------------------------------- ### Implement Shepherd with Context Provider Source: https://github.com/shipshapecode/shepherd/blob/main/docs-src/src/content/docs/recipes/react.md Shares a Shepherd tour instance across the component tree using React Context, enabling components to trigger tour methods. ```javascript // App imports above, this is either in a root App.js/ts file or somewhere in your app const ShepherdTourContext = React.createContext(); const ShepherdTourContextConsumer = ShepherdTourContext.Consumer; const shepherdTourInstance = new Shepherd.Tour(); return ( { ... } ); // elsewhere in your app within a component const tour = useContext(ShepherdTourContext); return (
); ```