Repository: jakemmarsh/react-tour-guide Branch: master Commit: 3945ab381e48 Files: 12 Total size: 20.8 KB Directory structure: gitextract_n_o7kowr/ ├── .gitignore ├── .jshintrc ├── .npmignore ├── LICENSE ├── README.md ├── gulpfile.js ├── index.js ├── lib/ │ ├── js/ │ │ ├── Indicator.js │ │ ├── Mixin.js │ │ └── Tooltip.js │ └── styles/ │ └── tour-guide.css └── package.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # Logs logs *.log # Runtime data pids *.pid *.seed # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) .grunt # Compiled binary addons (http://nodejs.org/api/addons.html) build/Release # Dependency directory # Commenting this out is preferred by some people, see # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git- node_modules # Users Environment Variables .lock-wscript # Distro files dist ================================================ FILE: .jshintrc ================================================ { "node": true, "browser": true, "esnext": true, "bitwise": true, "curly": true, "eqeqeq": true, "immed": true, "indent": 2, "latedef": true, "noarg": true, "regexp": true, "undef": true, "unused": true, "strict": true, "trailing": true, "smarttabs": true, "newcap": false } ================================================ FILE: .npmignore ================================================ lib gulpfile.js .jshintrc ================================================ FILE: LICENSE ================================================ The MIT License (MIT) Copyright (c) 2015 Jake Marsh Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ react-tour-guide [![npm version](https://badge.fury.io/js/react-tour-guide.svg)](http://badge.fury.io/js/react-tour-guide) ========================================================================================================================== A ReactJS mixin to give new users a popup-based tour of your application. An example can be seen [here](http://jakemmarsh.com/react-tour-guide/). --- ### Getting Started 1. `npm install --save react-tour-guide` 2. `var TourGuideMixin = require('react-tour-guide').Mixin` ```javascript var TourGuideMixin = require('react-tour-guide').Mixin; var tour = { startIndex: 0, scrollToSteps: true, steps: [ { text: 'This is the first step in the tour.', element: 'header', position: 'bottom', closeButtonText: 'Next' }, { text: 'This is the second step in the tour.', element: '.navigation', position: 'right' } ] }; var cb = function() { console.log('User has completed tour!'); }; var App = React.createClass({ mixins: [TourGuideMixin(tour, cb)], ... }); ``` If you're going to initialize the mixin without steps and add them later asynchronously, set your `startIndex` to a negative value ```javascript ... startIndex: -1, steps: [] ... ``` --- ### Options A Javascript object is passed to the `TourGuideMixin` to specify options, as well as the steps of your tour as an array (there is also a method to define these asynchronously, discussed below). The options are: - `startIndex` (int): the index from which to begin the steps of the tour. This can be retrieved and saved via `getUserTourProgress` (discussed below), in order to be specified when a user returns. Defaults to `0`. - `scrollToSteps` (bool): if true, the page will be automatically scrolled to the next indicator (if one exists) after a tooltip is dismissed. Defaults to `true`. - `steps` (array): the array of steps to be included in your tour. Defaults to an empty array. Each "step" in the array represents one indicator and tooltip that a user must click through in the guided tour. A step has the following structure: ```json { "text": "The helpful tip or information the user should read at this step.", "element": "A jQuery selector for the element which the step relates to.", "position": "Where to position the indicator in relation to the element.", "closeButtonText": "An optional string to be used as the text for the tooltip close button." } ``` Positions can be chosen from: `top-left`, `top-right`, `right`, `bottom-right`, `bottom`, `bottom-left`, `left`, and `center`. This defaults to `center`. --- ### Completion Callback An optional callback may be passed as the second parameter to `TourGuideMixin`, which will be called once the current user has completed all the steps of your tour. --- ### Methods ##### `setTourSteps(steps, cb)` This function is intended to provide you with a method to asynchronously define your steps (if they need to be fetched from a database, etc.) It takes a list of steps (of the form discussed earlier), along with an optional callback function as parameters. **This will completely overwrite any existing steps or progress**. Once the state is updated, the callback function will be invoked. ##### `getUserTourProgress()` Upon including the mixin, this will be available to your component. At any point, this method can be called to retrieve information about the current user's progress through the guided tour. The object returned looks like this: ```json { "index": 2, "percentageComplete": 50, "step": { "text": "...", "element": "...", "position": "..." } } ``` This information can be used to save a user's progress upon navigation from the page or application, allowing you to return them back to their correct spot when they visit next using the `startIndex` option (discussed above). --- ### Styling Some basic styling is provided in `/dist/css/tour-guide.css`. This can either be included directly in your project, or used as a base for your own custom styles. Below, the HTML structure of the tour is also outlined for custom styling. The guided tour consists of two main elements for each step: an `indicator` and a `tooltip`. An indicator is a flashing element positioned on a specific element on the page, cueing the user to click. Upon click, the associated tooltip is triggered which the user must then read and dismiss. **Note:** Elements are dynamically positioned by initially setting their `top` and `left` CSS properties to `-1000px`. Once they have been initially rendered and measured, they are then positioned correctly. Animations on these CSS properties should be avoided. ##### Indicator ```html
``` ##### Tooltip ```html

{The step's text goes here.}

Close
``` ================================================ FILE: gulpfile.js ================================================ 'use strict'; var gulp = require('gulp'); var del = require('del'); var react = require('gulp-react'); var runSequence = require('run-sequence'); var stripDebug = require('gulp-strip-debug'); var gulpif = require('gulp-if'); gulp.task('clean', function(cb) { return del(['./dist/css/*', './dist/js/*'], cb); }); gulp.task('styles', function() { return gulp.src('./lib/styles/**/*.css') .pipe(gulp.dest('./dist/css/')); }); gulp.task('scripts', function() { return gulp.src('./lib/js/**/*.js') .pipe(react()) .pipe(gulpif(global.isProd, stripDebug())) .pipe(gulp.dest('./dist/js/')); }); gulp.task('dev', function() { global.isProd = false; runSequence(['styles', 'scripts']); gulp.watch('./lib/js/**/*.js', ['scripts']); gulp.watch('./lib/styles/**/*.css', ['styles']); }); gulp.task('prod', ['clean'], function() { global.isProd = true; return runSequence(['styles', 'scripts']); }); ================================================ FILE: index.js ================================================ 'use strict'; module.exports = { Mixin: require('./dist/js/Mixin'), Indicator: require('./dist/js/Indicator'), Tooltip: require('./dist/js/Tooltip') }; ================================================ FILE: lib/js/Indicator.js ================================================ 'use strict'; var React = require('react/addons'); var Indicator = React.createClass({ propTypes: { cssPosition: React.PropTypes.string.isRequired, xPos: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string ]).isRequired, yPos: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string ]).isRequired, handleIndicatorClick: React.PropTypes.func.isRequired }, getDefaultProps: function() { return { cssPosition: 'absolute', xPos: -1000, yPos: -1000 }; }, render: function() { var styles = { 'position': this.props.cssPosition === 'fixed' ? 'fixed' : 'absolute', 'top': this.props.yPos, 'left': this.props.xPos }; return (
); } }); module.exports = Indicator; ================================================ FILE: lib/js/Mixin.js ================================================ 'use strict'; var React = require('react/addons'); var $ = require('jquery'); var Indicator = require('./Indicator'); var Tooltip = require('./Tooltip'); module.exports = function(settings, done) { var mixin = { settings: $.extend({ startIndex: 0, scrollToSteps: true, steps: [] }, settings), completionCallback: done || function() {}, getInitialState: function() { return { currentIndex: this.settings.startIndex, showTooltip: false, xPos: -1000, yPos: -1000 }; }, _renderLayer: function() { // By calling this method in componentDidMount() and componentDidUpdate(), you're effectively // creating a "wormhole" that funnels React's hierarchical updates through to a DOM node on an // entirely different part of the page. this.setState({ xPos: -1000, yPos: -1000 }); React.render(this.renderCurrentStep(), this._target); this.calculatePlacement(); }, _unrenderLayer: function() { React.unmountComponentAtNode(this._target); }, componentDidUpdate: function(prevProps, prevState) { var hasNewIndex = this.state.currentIndex !== prevState.currentIndex; var hasNewStep = !!this.settings.steps[this.state.currentIndex]; var hasSteps = this.settings.steps.length > 0; var hasNewX = this.state.xPos !== prevState.xPos; var hasNewY = this.state.yPos !== prevState.yPos; var didToggleTooltip = this.state.showTooltip && this.state.showTooltip !== prevState.showTooltip; if ( (hasNewIndex && hasNewStep) || didToggleTooltip || hasNewX || hasNewY ) { this._renderLayer(); } else if ( hasSteps && hasNewIndex && !hasNewStep ) { this.completionCallback(); this._unrenderLayer(); } }, componentDidMount: function() { // Appending to the body is easier than managing the z-index of everything on the page. // It's also better for accessibility and makes stacking a snap (since components will stack // in mount order). this._target = document.createElement('div'); document.body.appendChild(this._target); if ( this.settings.steps[this.state.currentIndex] ) { this._renderLayer(); } $(window).on('resize', this.calculatePlacement); }, componentWillUnmount: function() { this._unrenderLayer(); document.body.removeChild(this._target); $(window).off('resize', this.calculatePlacement); }, setTourSteps: function(steps, cb) { if (!(steps instanceof Array)) { return false; } cb = cb || function() {}; this.settings.steps = steps; this.setState({ currentIndex: this.state.currentIndex < 0 ? 0 : this.state.currentIndex, setTourSteps: steps.length }, cb); }, getUserTourProgress: function() { return { index: this.state.currentIndex, percentageComplete: (this.state.currentIndex/this.settings.steps.length)*100, step: this.settings.steps[this.state.currentIndex] }; }, preventWindowOverflow: function(value, axis, elWidth, elHeight) { var winWidth = parseInt($(window).width()); var docHeight = parseInt($(document).height()); if ( axis.toLowerCase() === 'x' ) { if ( value + elWidth > winWidth ) { console.log('right overflow. value:', value, 'elWidth:', elWidth); value = winWidth - elWidth; } else if ( value < 0 ) { console.log('left overflow. value:', value, 'elWidth:', elWidth); value = 0; } } else if ( axis.toLowerCase() === 'y' ) { if ( value + elHeight > docHeight ) { console.log('bottom overflow. value:', value, 'elHeight:', elHeight); value = docHeight - elHeight; } else if ( value < 0 ) { console.log('top overflow. value:', value, 'elHeight:', elHeight); value = 0; } } return value; }, calculatePlacement: function() { var step = this.settings.steps[this.state.currentIndex]; var $target = $(step.element); var offset = $target.offset(); var targetWidth = $target.outerWidth(); var targetHeight = $target.outerHeight(); var position = step.position.toLowerCase(); var topRegex = new RegExp('top', 'gi'); var bottomRegex = new RegExp('bottom', 'gi'); var leftRegex = new RegExp('left', 'gi'); var rightRegex = new RegExp('right', 'gi'); var $element = this.state.showTooltip ? $('.tour-tooltip') : $('.tour-indicator'); var elWidth = $element.outerWidth(); var elHeight = $element.outerHeight(); var placement = { x: -1000, y: -1000 }; // Calculate x position if ( leftRegex.test(position) ) { placement.x = offset.left - elWidth/2; } else if ( rightRegex.test(position) ) { placement.x = offset.left + targetWidth - elWidth/2; } else { placement.x = offset.left + targetWidth/2 - elWidth/2; } // Calculate y position if ( topRegex.test(position) ) { placement.y = offset.top - elHeight/2; } else if ( bottomRegex.test(position) ) { placement.y = offset.top + targetHeight - elHeight/2; } else { placement.y = offset.top + targetHeight/2 - elHeight/2; } this.setState({ xPos: this.preventWindowOverflow(placement.x, 'x', elWidth, elHeight), yPos: this.preventWindowOverflow(placement.y, 'y', elWidth, elHeight) }); }, handleIndicatorClick: function(evt) { evt.preventDefault(); this.setState({ showTooltip: true }); }, closeTooltip: function(evt) { evt.preventDefault(); this.setState({ showTooltip: false, currentIndex: this.state.currentIndex + 1 }, this.scrollToNextStep); }, scrollToNextStep: function() { var $nextIndicator = $('.tour-indicator'); if ( $nextIndicator && $nextIndicator.length && this.settings.scrollToSteps ) { $('html, body').animate({ 'scrollTop': $nextIndicator.offset().top - $(window).height()/2 }, 500); } }, renderCurrentStep: function() { var element = null; var currentStep = this.settings.steps[this.state.currentIndex]; var $target = currentStep && currentStep.element ? $(currentStep.element) : null; var cssPosition = $target ? $target.css('position') : null; if ( $target && $target.length ) { if ( this.state.showTooltip ) { element = ( ); } else { element = ( ); } } return element; } }; return mixin; }; ================================================ FILE: lib/js/Tooltip.js ================================================ 'use strict'; var React = require('react/addons'); var Tooltip = React.createClass({ propTypes: { cssPosition: React.PropTypes.string.isRequired, xPos: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string ]).isRequired, yPos: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string ]).isRequired, text: React.PropTypes.string.isRequired, closeButtonText: React.PropTypes.string, closeTooltip: React.PropTypes.func.isRequired }, getDefaultProps: function() { return { cssPosition: 'absolute', xPos: -1000, yPos: -1000, text: '' }; }, render: function() { var styles = { 'position': this.props.cssPosition === 'fixed' ? 'fixed' : 'absolute', 'top': this.props.yPos, 'left': this.props.xPos }; return (

{this.props.text || ''}

{this.props.closeButtonText || 'Close'}
); } }); module.exports = Tooltip; ================================================ FILE: lib/styles/tour-guide.css ================================================ .tour-indicator { height: 30px; width: 30px; -webkit-border-radius: 100%; -moz-border-radius: 100%; border-radius: 100%; background-color: #3f94d0; cursor: pointer; /* Animate */ -webkit-animation-name: pulse; -webkit-animation-duration: 1.5s; -webkit-animation-iteration-count: infinite; -webkit-animation-timing-function: ease-out; -moz-animation-name: pulse; -moz-animation-duration: 1.5s; -moz-animation-iteration-count: infinite; -moz-animation-timing-function: ease-out; -o-animation-name: pulse; -o-animation-duration: 1.5s; -o-animation-iteration-count: infinite; -o-animation-timing-function: ease-out; animation-name: pulse; animation-duration: 1.5s; animation-iteration-count: infinite; animation-timing-function: ease-out; } /* WebKit/Safari and Chrome */ @-webkit-keyframes pulse { 0% { -webkit-transform: scale(1); transform: scale(1); } 80% { -webkit-transform: scale(1.5); transform: scale(1.5); } 100% { -webkit-transform: scale(2.5); transform: scale(2.5); opacity: 0; } } /* Gecko/Firefox */ @-moz-keyframes pulse { 0% { -moz-transform: scale(0.3); transform: scale(0.3); opacity: 0.5; } 80% { -moz-transform: scale(1.5); transform: scale(1.5); opacity: 0; } 100% { -moz-transform: scale(2.5); transform: scale(2.5); opacity: 0; } } /* Presto/Opera */ @-o-keyframes pulse { 0% { -o-transform: scale(0.3); transform: scale(0.3); opacity: 0.5; } 80% { -o-transform: scale(1.5); transform: scale(1.5); opacity: 0; } 100% { -o-transform: scale(2.5); transform: scale(2.5); opacity: 0; } } /* Standard */ @keyframes pulse { 0% { transform: scale(0.3); opacity: 0.5; } 80% { transform: scale(1.5); opacity: 0; } 100% { transform: scale(2.5); opacity: 0; } } .tour-backdrop { z-index: 998; /* one below z-index of tour-toolip (999) */ position: fixed; top: 0; right: 0; bottom: 0; left: 0; text-align: center; background: rgba(0, 0, 0, 0.45); } .tour-tooltip { z-index: 999; width: 250px; background-color: #ffffff; color: #545454; border: 1px solid #dddddd; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; padding: 5px; -webkit-box-shadow: 0 8px 6px -6px rgba(0,0,0,0.4); -moz-box-shadow: 0 8px 6px -6px rgba(0,0,0,0.4); box-shadow: 0 8px 6px -6px rgba(0,0,0,0.4); } .tour-tooltip p { margin: 5px 3px; } .tour-tooltip .tour-btn.close { cursor: pointer; display: block; width: auto; margin: 0 auto; background-color: #ffffff; border: 1px solid #dddddd; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; padding: 3px; text-align: center; } .tour-tooltip .tour-btn.close:hover { border-color: #3f94d0; color: #3f94d0; } ================================================ FILE: package.json ================================================ { "name": "react-tour-guide", "version": "0.0.8", "author": "Jake Marsh ", "description": "A ReactJS mixin to give new users a popup-based tour of your application.", "repository": { "type": "git", "url": "https://github.com/jakemmarsh/react-tour-guide.git" }, "private": false, "license": "MIT", "keywords": [ "ReactJS", "react", "tour", "walkthrough", "guide" ], "engines": { "node": ">=0.12.x" }, "dependencies": { "jquery": "^2.1.3", "react": "^0.13.1" }, "devDependencies": { "del": "^1.1.1", "gulp": "^3.8.11", "gulp-if": "^1.2.5", "gulp-react": "^3.0.0", "gulp-strip-debug": "^1.0.2", "run-sequence": "^1.0.2" }, "scripts": { "prepublish": "gulp prod" } }