### Install @gravity-ui/onboarding
Source: https://github.com/gravity-ui/onboarding/blob/main/README.md
Command to install the @gravity-ui/onboarding package using npm.
```shell
npm i @gravity-ui/onboarding
```
--------------------------------
### Basic React Onboarding Setup
Source: https://github.com/gravity-ui/onboarding/blob/main/README.md
Demonstrates how to set up and use the createOnboarding hook in a React application. It includes creating presets, defining steps, and integrating with UI components.
```typescript jsx
// onboarding/lib.ts
import {createOnboarding, createPreset} from '@gravity-ui/onboarding';
export const {
useOnboardingStep,
useOnboardingPreset,
useOnboardingHint,
useOnboarding,
controller,
} = createOnboarding({
config: {
presets: {
// createPreset - wrapper for better type inference
todoListFirstUsage: createPreset({
name: '',
steps: [
createStep({
slug: 'createTodoList',
name: 'create-todo-list',
description: 'Click button to create todo list',
}),
/* other scanario steps */
],
}),
},
},
// onboarding state from backend
baseState: () => {/* ... */},
getProgressState: () => {/* ... */},
// save new onboarding state to backend
onSave: {
state: (state) => {/* ... */},
progress: (progress) => {/* ... */},
},
});
```
```typescript jsx
// Hint.tsx
import { useCallback } from 'react';
import { Popup } from '@gravity-ui/uikit';
import { useOnboardingHint } from './lib.ts';
export const OnboardingHint = () => {
const { anchorRef, hint, open, onClose } = useOnboardingHint();
const handleClose = useCallback(() => {
onClose();
}, [onClose]);
return (
<>
{hint?.step.name}
{hint?.step.description}
>
);
};
```
```typescript jsx
// todo-list.tsx
import { useOnboardingStep } from './onboarding/lib';
export const SomeFeature = () => {
const { pass, ref } = useOnboardingStep('createTodoList');
return (
);
};
```
--------------------------------
### Integrating Onboarding Plugins
Source: https://github.com/gravity-ui/onboarding/blob/main/README.md
Illustrates how to integrate various plugins with the createOnboarding function. It includes examples for MultiTabSyncPlugin, PromoPresetsPlugin, and WizardPlugin, showing their respective configuration options.
```typescript jsx
import {createOnboarding} from '@gravity-ui/onboarding';
import {
MultiTabSyncPlugin,
PromoPresetsPlugin,
WizardPlugin,
} from '@gravity-ui/onboarding/dist/plugins';
const {controller} = createOnboarding({
/* ... */
plugins: [
new MultiTabSyncPlugin({
enableStateSync: false, // Experimantal. Default - false(recommended). Sync all onboarding state.
enableCloseHintSync: true, // closes hont in all browser tabs,
changeStateLSKey: 'onboarding.plugin-sync.changeState', // localStorage key for state sync
closeHintLSKey: 'onboarding.plugin-sync.closeHint', // localStorage key for close hint in all tabs
}),
new PromoPresetsPlugin({
turnOnWhenShowHint: true, // Default - true. Force to turn on onboarding, when promo hint should be shown
turnOnWhenSuggestPromoPreset: true, // Default - true. Force to turn on onboarding, when promo preset suggested
}),
new WizardPlugin(),
],
});
```
--------------------------------
### Preset Configuration Example
Source: https://github.com/gravity-ui/onboarding/blob/main/README.md
Demonstrates how to configure a specific onboarding preset, including its name, type, visibility, steps, and event hooks. It shows how to use helper functions like `goPrevStep` and `goNextStep` within step actions.
```typescript jsx
const onboardingOptions = {
config: {
presets: {
// you can use goPrevStep and goNextStep in steps
createProject: createPreset(({goPrevStep, goNextStep}) => ({
// preset name should be unique
name: 'Creating project', // text for user
type: 'default', // optional. 'default'(default value) | 'interlal' | 'combined'
visibility: 'visible', // optional. 'visible'(defaule value) | 'initialHidden' | 'alwaysHidden';
description: '', // optional, text for user
steps: [
{
slug: 'openBoard', // step slug must be unique across all presets
name: '', // text to show in popup
description: '', // text to show in popup
placement: 'top', // optional. Hint placement for step
passMode: 'onAction', // optional. 'onAction'(default value) | 'onShowHint' - trigger step pass on hint show
hintParams: {
// you can use theese actions in Hint component to display buttons
actions: [
{
children: 'Go back',
view: 'action' as const,
onClick: () => {
goNextStep()
},
},
{
children: 'Go next',
view: 'action' as const,
onClick: () => {
goNextStep()
},
},
],
}, // optional. any custom properties for hint
closeOnElementUnmount: false, // optional. default valeue - false. Will close hint when element umnounts. 'True' not reccomended in general^ but may me helpful for some corners
passRestriction: 'afterPrevious', // optional. afterPrevious will block pass step is previous not passed
hooks: {
// optional
onStepPass: () => {/**/},
onCloseHint: () => {/**/},
onCloseHintByUser: () => {/**/},
},
},
],
hooks: {
// optional
onBeforeStart: () => {/**/},
onStart: () => {/**/},
onEnd: () => {/**/},
},
})),
},
},
};
```
--------------------------------
### Using useOnboardingStepBySelector
Source: https://github.com/gravity-ui/onboarding/blob/main/README.md
Example demonstrating how to use `useOnboardingStepBySelector` when direct element access is not available, using a CSS selector to target the element for the onboarding step.
```typescript jsx
// todo-list.tsx
import {useOnboardingStepBySelector} from '../todo-list-onboarding.ts';
const ref = useRef()
useOnboardingStepBySelector({
element: ref.current,
selector: '.deep_nested_element',
step: 'createFirstIssue'
});
return (
);
```
--------------------------------
### Custom Promo Conditions
Source: https://github.com/gravity-ui/onboarding/blob/main/README.md
Demonstrates how to create and use custom conditions for promos. This example shows a condition that checks the user's language preference.
```typescript
const user = {/**/} // get user from state
const usersWithLanguage = (language) => user.language = language;
const promo = {slug: 'somePoll', conditions: [usersWithLanguage('english')]};
```
--------------------------------
### Subscribing to Onboarding Events
Source: https://github.com/gravity-ui/onboarding/blob/main/README.md
Shows how to subscribe to events emitted by the onboarding controller. It provides an example of subscribing to the 'beforeShowHint' event and demonstrates how a callback can return `false` to prevent an action, such as showing a hint.
```typescript jsx
controller.events.subscribe('beforeShowHint', callback);
```
```typescript jsx
controller.events.subscribe('stepElementReached', async () => {
/* ... */
if(someCondition) {
// forbid show hint
return false
}
});
```
--------------------------------
### Trigger Promo in Component
Source: https://github.com/gravity-ui/onboarding/blob/main/README.md
Demonstrates how to use the `usePromoManager` hook within a React component to request starting a promo and skip it on unmount. It checks the promo status to determine if it's active.
```typescript
import { usePromoManager } from './promo-manager';
const { status, requestStart, skipPromo } = usePromoManager('issuePoll');
useMount(() => {
requestStart();
});
useUnmount(() => {
skipPromo();
});
if(status === 'active') {
// allowed to run. Do something
}
```
--------------------------------
### Onboarding Integration with Promo Manager
Source: https://github.com/gravity-ui/onboarding/blob/main/README.md
Shows how to integrate the Gravity UI onboarding system with the promo manager using `PromoPresetsPlugin`. This allows for displaying advertising and educational hints, with the ability to limit frequency and set constraints.
```typescript
import {
createOnboarding
} from "./index";
const {controller: onboardingController} = createOnboarding({
config: {
presets: {
coolNewFeature: {
name: 'Cool feature',
visibility: 'alwaysHidden',
steps: [/**/] // Placeholder for onboarding steps
},
coolNewFeature2: {
name: 'Cool feature2',
visibility: 'alwaysHidden',
steps: [/**/], // Placeholder for onboarding steps
}
}
},
plugins: [new PromoPresetsPlugin(),] // Assuming PromoPresetsPlugin is available
/**/
});
const {controller} = createPromoManager({
...testOptions, // Assuming testOptions is defined elsewhere
config: {
promoGroups: [
{
slug: 'hintPromos',
conditions: [ShowOnceForSession()], // only 1 promo hint for session (assuming ShowOnceForSession is a defined helper)
promos: [
{
slug: 'coolNewFeature', // slug = onboarding preset name
conditions: [/**/], // you can add additional conditions
},
],
},
],
},
onboarding: {
getInstance: () => onboardingController,
groupSlug: 'hintPromos',
},
});
```
--------------------------------
### Promo Conditions and Constraints
Source: https://github.com/gravity-ui/onboarding/blob/main/README.md
Illustrates the use of various built-in conditions like `ShowOnceForSession`, `ShowOnceForPeriod`, and `MatchUrl` for promos and promo groups. It also shows how to define constraints, such as `LimitFrequency`, to manage the interplay between different promos.
```typescript
import {
ShowOnceForSession,
ShowOnceForPeriod,
MatchUrl,
LimitFrequency
} from '@gravity-ui/onboarding/dist/promo-manager/helpers';
const groupOfPolls = {
slug: 'groupOfPolls',
promos: [
{slug: 'somePoll', conditions: [ShowOnceForPeriod({month: 1}))},
{slug: 'pollForPageWithparam', conditions: [
MatchUrl('param=value'),
ShowOnceForPeriod({month: 5})
]},
],
}
const groupOfHints = {
slug: 'groupOfHints',
conditions: [ShowOnceForSession()],
promos: [
{slug: 'someHint'},
{slug: 'hintForSpecificPage', conditions: [
MatchUrl('/folder/\w{5}/page$'),
]},
],
}
const {controller} = createPromoManager({
config: {
constraints: [
LimitFrequency({
slugs: ['somePoll', 'groupOfHints'], // can use promos slugs and group slugs
interval: {days: 1},
})
],
promoGroups: [groupOfHints, groupOfPolls]
},
});
```
--------------------------------
### JSON Configuration for Promo Manager
Source: https://github.com/gravity-ui/onboarding/blob/main/README.md
Demonstrates how to define conditions and constraints using JSON serializable objects within the Gravity UI promo manager. This allows for dynamic configuration loading and management.
```typescript
const usersWithLanguage = (language) => user.language = language;
const {controller} = createPromoManager({
config: { // config section now can be parsed from json
constraints: [
{
helper: 'LimitFrequency',
args: [{
slugs: ['somePoll', 'groupOfHints'], // can use promos slugs and group slugs
interval: {days: 1},
}],
},
],
promoGroups: [{
slug: 'groupOfPolls',
promos: [
{
slug: 'somePoll',
conditions: [{
helper: 'ShowOnceForPeriod',
args: [{month: 1}]
}]
},
{
slug: 'pollForPageWithparam',
conditions: [
{
helper: 'MatchUrl',
args: ['param=value']
},
{
helper: 'usersWithLanguage',
args: ['English']
},
]
}
],
}]
},
conditionHelpers: {
usersWithLanguage,
},
});
```
--------------------------------
### Initialize Promo Manager
Source: https://github.com/gravity-ui/onboarding/blob/main/README.md
Initializes the promo manager with configuration for promo groups, conditions, and progress state handling. It exports controller, usePromoManager, and useActivePromo hooks.
```typescript
import { createPromoManager } from '@gravity-ui/onboarding/dist/promo-manager';
import { ShowOnceForPeriod } from '@gravity-ui/onboarding/dist/promo-manager/helpers';
export const { controller, usePromoManager, useActivePromo } = createPromoManager({
config: {
promoGroups: [{
slug: 'poll',
conditions: [ShowOnceForPeriod({month: 1})],
promos: [
{
slug: 'issuePoll',
conditions: [ShowOncePerMonths(6)],
meta: {...}
},
],
}],
},
progressState: () => {/* ... */},
getProgressState: () => {/* ... */},
onSave: {
progress: (state) => () => {/* ... */},
},
});
```
--------------------------------
### Creating a Custom Onboarding Plugin
Source: https://github.com/gravity-ui/onboarding/blob/main/README.md
Provides a template for creating a custom plugin for Gravity UI Onboarding. It shows the structure of a plugin object with an `apply` method that receives the onboarding controller, allowing for custom event subscriptions or other logic.
```typescript jsx
import {createOnboarding} from '@gravity-ui/onboarding';
import {WizardPlugin} from '@gravity-ui/onboarding/dist/plugins';
const myPlugin = {
apply: (onboarding) => {
/**
* Do something with onboarding controller
* For exampe subscribe on event
* onboarding.events.subscribe('init', () => {});
*/
},
};
const {controller} = createOnboarding({
/**/
plugins: [new WizardPlugin(), myPlugin],
});
```
--------------------------------
### Trigger Promo on Page Open Event
Source: https://github.com/gravity-ui/onboarding/blob/main/README.md
Demonstrates using the `UrlEventPlugin` to trigger promos when a user opens a specific URL. The promo is configured with `MatchUrl` and a `pageOpened` trigger event.
```typescript
const {controller} = createPromoManager({
config: {
promoGroups: [
{
slug: '1',
promos: [
{
slug: 'promo1',
conditions: [MatchUrl('/folder/\w{5}/page$'),],
trigger: {on: 'pageOpened', timeout: 2000},
},
],
},
],
},
plugins: [new UrlEventsPlugin({eventName: 'pageOpened'})],
})
```
--------------------------------
### Onboarding Options Configuration
Source: https://github.com/gravity-ui/onboarding/blob/main/README.md
Defines the overall configuration for the onboarding system, including global switches, state management functions, event hooks, and logging.
```typescript jsx
const onboardingOptions = {
config: {
presets: {/**/},
},
globalSwitch: 'off', // optional. turn off onboarding globally. For example in some entire env
ignoreUnknownPresets: true, // optional. will not thorow error for unknown presets
baseState: {/**/}, // initial state for current user
getProgressState: () => {/**/}, // function to load user progress
customDefaultState: {/**/}, // optional. will apply this value for user with no base state
onSave: {
// functions to save user state
state: (state) => {/**/},
progress: (progress) => {/**/},
},
showHint: (state) => {}, // optional. function to show hint. Only for vanilla js usage
logger: { // optional. you can specify custom logger
level: 'error' as const,
logger: {
debug: () => {/**/},
error: () => {/**/},
},
},
debugMode: true, // optional. true will show a lot of debug messages. Recommended for dev environment
plugins: [/**/], // optional. you can use existing plugins or write your own
// optional. you can subscribe to onboarding events
hooks: {
showHint: ({preset, step}) => {/**/},
stepPass: ({preset, step}) => {/**/},
addPreset: ({preset}) => {/**/},
beforeRunPreset: ({preset}) => {/**/},
runPreset: ({preset}) => {/**/},
finishPreset: ({preset}) => {/**/},
beforeSuggestPreset: ({preset}) => {/**/},
beforeShowHint: ({stepData}) => {/**/},
stateChange: ({state}) => {/**/},
hintDataChanged: ({state}) => {/**/},
closeHint: ({hint, eventSource}) => {/**/},
closeHintByUser: ({hint, eventSource}) => {/**/},
init: () => {/**/},
wizardStateChanged: ({wizardState}) => {/**/},
applyDefaultState: ({wizardState}) => {/**/},
},
};
```
--------------------------------
### Creating Combined Presets
Source: https://github.com/gravity-ui/onboarding/blob/main/README.md
Demonstrates how to create combined presets in Gravity UI Onboarding by defining internal presets and a combined preset that picks one of the internal presets based on a condition. It involves importing necessary functions from '@gravity-ui/onboarding'.
```typescript jsx
import {createInternalPreset, createCombinedPreset, createOnboarding} from '@gravity-ui/onboarding';
createOnboarding({
config: {
presets: {
// you need to add internal presets. Here it is internal1 and internal2
internal1: createInternalPreset({
name: 'Internal2',
type: 'internal' as const,
steps: [/* ... */]
}),
internal2: createInternalPreset({
name: 'Internal2',
type: 'internal' as const,
steps: [/* ... */],
}),
// combined preset has no steps
combined: createCombinedPreset({
name: 'combined',
type: 'combined' as const,
// pickPreset calls on preset start and resolve combined preset to specific internal preset
pickPreset: () => {
if(someCondition) {
return 'internal1'
}
return 'internal2'
},
internalPresets: ['internal1', 'internal2'],
}),
},
},
});
```
--------------------------------
### Trigger Promo on Custom Event
Source: https://github.com/gravity-ui/onboarding/blob/main/README.md
Shows how to configure a promo to be triggered by a custom event sent via the promo manager's controller. The `trigger.on` property specifies the event name, and `timeout` sets a delay.
```typescript
const promo = {
slug: 'promo1',
conditions: [],
trigger: {on: 'someCustomEvent', timeout: 1000}
}
const {controller} = createPromoManager({
config: {
promoGroups: [{
slug: 'group',
conditions: [],
promos: [promo],
}]
},
});
controller.sendEvent('someCustomEvent')
```
--------------------------------
### CLA Adoption Confirmation
Source: https://github.com/gravity-ui/onboarding/blob/main/CONTRIBUTING.md
This snippet shows the required text to include in a pull request to confirm adoption of the Yandex Contributor License Agreement (CLA). It specifies the format for linking to the CLA.
```text
I hereby agree to the terms of the CLA available at: [link].
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.