1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 | 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 1x 3x 1x 2x 3x 3x 2x 2x 3x 2x 2x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 2x 1x 1x 1x 1x 7x 1x 1x 1x 1x 1x 7x 27x 27x 27x 27x 27x 27x 27x 2x 25x 2x 27x 27x 2x 2x 2x 27x 4x 4x 1x 1x 27x 7x 5x 2x 27x 1x 27x 27x 27x 27x 27x 27x 10x 27x 27x 3x 3x 2x 3x 3x 12x 12x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 3x 3x 3x 3x 6x 6x 177x 5x 5x 172x 172x 172x 172x 172x 172x 3x 156x 156x 5x 151x 151x 4x 4x 147x 66x 66x 66x 66x 66x 66x 57x 57x 57x 66x 27x 27x 27x 27x 27x 3x 24x 24x 24x 24x 24x 20x 24x 27x 27x 27x 27x 4x 4x 4x 4x 4x 4x 4x 2x 2x 4x 4x 4x 4x 4x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 2x 5x 5x 7x 8x 8x 8x 17x 17x 17x 17x 17x 17x 17x 1x 16x 16x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 10x 4x 4x 14x 14x 14x 14x 52x 52x 52x 52x 52x 52x 52x 6x 46x 52x 57x 57x 25x 32x 12x 20x 28x 28x 28x 28x 28x 28x 14x 14x 28x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 14x 14x 10x 8x 8x 6x 6x 8x 6x 10x 14x 8x 22x 30x 30x 30x 30x 18x 12x 4x 30x 4x 26x 18x 30x | import React from 'react'; import scroll from 'scroll'; import autobind from 'react-autobind'; import nested from 'nested-property'; import { getRootEl, logger, sanitizeSelector } from './utils'; import Beacon from './Beacon'; import Tooltip from './Tooltip'; const defaultState = { action: '', index: 0, isRunning: false, isTourSkipped: false, shouldRedraw: true, shouldRenderTooltip: false, shouldRun: false, standaloneData: false, // The standalone tooltip data xPos: -1000, yPos: -1000 }; const callbackTypes = { STEP_BEFORE: 'step:before', BEACON_BEFORE: 'beacon:before', BEACON_TRIGGER: 'beacon:trigger', TOOLTIP_BEFORE: 'tooltip:before', STEP_AFTER: 'step:after', STANDALONE_BEFORE: 'standalone:before', STANDALONE_AFTER: 'standalone:after', OVERLAY: 'overlay:click', HOLE: 'hole:click', FINISHED: 'finished', TARGET_NOT_FOUND: 'error:target_not_found' }; const DEFAULTS = { position: 'top', minWidth: 290 }; let hasTouch = false; class Joyride extends React.Component { constructor(props) { super(props); autobind(this); this.state = { ...defaultState }; this.listeners = { tooltips: {} }; } static propTypes = { allowClicksThruHole: React.PropTypes.bool, autoStart: React.PropTypes.bool, callback: React.PropTypes.func, debug: React.PropTypes.bool, disableOverlay: React.PropTypes.bool, holePadding: React.PropTypes.number, keyboardNavigation: React.PropTypes.bool, locale: React.PropTypes.object, resizeDebounce: React.PropTypes.bool, resizeDebounceDelay: React.PropTypes.number, run: React.PropTypes.bool, scrollOffset: React.PropTypes.number, scrollToFirstStep: React.PropTypes.bool, scrollToSteps: React.PropTypes.bool, showBackButton: React.PropTypes.bool, showOverlay: React.PropTypes.bool, showSkipButton: React.PropTypes.bool, showStepsProgress: React.PropTypes.bool, stepIndex: React.PropTypes.number, steps: React.PropTypes.array, tooltipOffset: React.PropTypes.number, type: React.PropTypes.string }; static defaultProps = { allowClicksThruHole: false, autoStart: false, debug: false, holePadding: 5, keyboardNavigation: true, locale: { back: 'Back', close: 'Close', last: 'Last', next: 'Next', skip: 'Skip' }, resizeDebounce: false, resizeDebounceDelay: 200, run: false, scrollToSteps: true, scrollOffset: 20, scrollToFirstStep: false, showBackButton: true, showOverlay: true, showSkipButton: false, showStepsProgress: false, steps: [], tooltipOffset: 15, type: 'single' }; componentDidMount() { const { autoStart, keyboardNavigation, resizeDebounce, resizeDebounceDelay, run, steps, type } = this.props; logger({ type: 'joyride:initialized', msg: [this.props], debug: this.props.debug, }); const stepsAreValid = this.checkStepsValidity(steps); if (steps && stepsAreValid && run) { this.start(autoStart); } if (resizeDebounce) { let timeoutId; this.listeners.resize = () => { clearTimeout(timeoutId); timeoutId = setTimeout(() => { timeoutId = null; this.calcPlacement(); }, resizeDebounceDelay); }; } else { this.listeners.resize = () => { this.calcPlacement(); }; } window.addEventListener('resize', this.listeners.resize); /* istanbul ignore else */ if (keyboardNavigation && type === 'continuous') { this.listeners.keyboard = this.onKeyboardNavigation; document.body.addEventListener('keydown', this.listeners.keyboard); } window.addEventListener('touchstart', function setHasTouch() { hasTouch = true; // Remove event listener once fired, otherwise it'll kill scrolling // performance window.removeEventListener('touchstart', setHasTouch); }, false); } componentWillReceiveProps(nextProps) { logger({ type: 'joyride:willReceiveProps', msg: [nextProps], debug: nextProps.debug, }); const { isRunning, shouldRun, standaloneData } = this.state; const { keyboardNavigation, run, steps, stepIndex } = this.props; const stepsChanged = (nextProps.steps !== steps); const stepIndexChanged = (nextProps.stepIndex !== stepIndex && nextProps.stepIndex !== this.state.index); const runChanged = (nextProps.run !== run); let shouldStart = false; let didStop = false; Iif (stepsChanged && this.checkStepsValidity(nextProps.steps)) { // Removed all steps, so reset if (!nextProps.steps || !nextProps.steps.length) { this.reset(); } // Start the joyride if steps were added for the first time, and run prop is true else if (!steps.length && nextProps.run) { shouldStart = true; } } /* istanbul ignore else */ if (runChanged) { // run prop was changed to off, so stop the joyride if (run && nextProps.run === false) { this.stop(); didStop = true; } // run prop was changed to on, so start the joyride else Eif (!run && nextProps.run) { shouldStart = true; } // Was not playing, but should, and isn't a standaloneData else if (!isRunning && (shouldRun && !standaloneData)) { shouldStart = true; } } /* istanbul ignore else */ if (stepIndexChanged) { const hasStep = nextProps.steps[nextProps.stepIndex]; const shouldDisplay = hasStep && nextProps.autoStart; Iif (runChanged && shouldStart) { this.start(nextProps.autoStart, nextProps.steps, nextProps.stepIndex); } // Next prop is set to run, and the index has changed, but for some reason joyride is not running // (maybe this is because of a target not mounted, and the app wants to skip to another step) else Eif (nextProps.run && !isRunning) { this.start(nextProps.autoStart, nextProps.steps, nextProps.stepIndex); } else if (!didStop) { this.toggleTooltip({ show: shouldDisplay, index: nextProps.stepIndex, steps: nextProps.steps, action: 'jump' }); } } // Did not change the index, but need to start up the joyride else if (shouldStart) { this.start(nextProps.autoStart, nextProps.steps); } // Update keyboard listeners if necessary /* istanbul ignore else */ Iif ( !this.listeners.keyboard && ((!keyboardNavigation && nextProps.keyboardNavigation) || keyboardNavigation) && nextProps.type === 'continuous' ) { this.listeners.keyboard = this.onKeyboardNavigation; document.body.addEventListener('keydown', this.listeners.keyboard); } else if ( this.listeners.keyboard && keyboardNavigation && (!nextProps.keyboardNavigation || nextProps.type !== 'continuous') ) { document.body.removeEventListener('keydown', this.listeners.keyboard); delete this.listeners.keyboard; } } componentWillUpdate(nextProps, nextState) { const { index, isRunning, shouldRenderTooltip, standaloneData } = this.state; const { steps } = this.props; const { steps: nextSteps } = nextProps; const step = steps[index]; const nextStep = nextSteps[nextState.index]; const hasRenderedTarget = Boolean(this.getStepTargetElement(nextStep)); // Standalone tooltip is being turned on if (!standaloneData && nextState.standaloneData) { this.triggerCallback({ type: callbackTypes.STANDALONE_BEFORE, step: nextState.standaloneData }); } // Standalone tooltip is being turned off else if (standaloneData && !nextState.standaloneData) { this.triggerCallback({ type: callbackTypes.STANDALONE_AFTER, step: standaloneData }); } // Tried to start, but something went wrong and we're not actually running Iif (nextState.action === 'start' && !nextState.isRunning) { // There's a step to use, but there's no target in the DOM if (nextStep && !hasRenderedTarget) { console.warn('Target not mounted', nextStep, nextState.action); //eslint-disable-line no-console this.triggerCallback({ action: 'start', index: nextState.index, type: callbackTypes.TARGET_NOT_FOUND, step: nextStep, }); } } // Started running from the beginning (the current index is 0) if ((!isRunning && nextState.isRunning) && nextState.index === 0) { this.triggerCallback({ action: 'start', index: nextState.index, type: callbackTypes.STEP_BEFORE, step: nextStep }); // Not showing a tooltip yet, so we're going to show a beacon instead /* istanbul ignore else */ if (!nextState.shouldRenderTooltip) { this.triggerCallback({ action: 'start', index: nextState.index, type: callbackTypes.BEACON_BEFORE, step: nextStep }); } } // Joyride was running (it might still be), and the index has been changed if (isRunning && nextState.index !== index) { this.triggerCallback({ action: nextState.action, index, type: callbackTypes.STEP_AFTER, step }); // Attempted to advance to a step with a target that cannot be found /* istanbul ignore else */ if (nextStep && !hasRenderedTarget) { console.warn('Target not mounted', nextStep, nextState.action); //eslint-disable-line no-console this.triggerCallback({ action: nextState.action, index: nextState.index, type: callbackTypes.TARGET_NOT_FOUND, step: nextStep, }); } // There's a next step and the index is > 0 // (which means STEP_BEFORE wasn't sent as part of the start handler above) else if (nextStep && nextState.index) { this.triggerCallback({ action: nextState.action, index: nextState.index, type: callbackTypes.STEP_BEFORE, step: nextStep }); } } // Running, and a tooltip is being turned on/off or the index is changing if (nextState.isRunning && (shouldRenderTooltip !== nextState.shouldRenderTooltip || nextState.index !== index)) { // Going to show a tooltip if (nextState.shouldRenderTooltip) { this.triggerCallback({ action: nextState.action || (nextState.index === 0 ? 'autostart' : ''), index: nextState.index, type: callbackTypes.TOOLTIP_BEFORE, step: nextStep }); } // Going to show a beacon else { this.triggerCallback({ action: nextState.action, index: nextState.index, type: callbackTypes.BEACON_BEFORE, step: nextStep }); } } // Joyride was changed to a step index which doesn't exist (hit the end) if (nextProps.run && nextSteps.length && index !== nextState.index && !nextStep) { this.triggerCallback({ action: nextState.action, type: callbackTypes.FINISHED, steps: nextSteps, isTourSkipped: nextState.isTourSkipped }); } } componentDidUpdate(prevProps, prevState) { const { index, shouldRedraw, isRunning, shouldRun, standaloneData } = this.state; const { scrollToFirstStep, scrollToSteps, steps } = this.props; const step = steps[index]; const scrollTop = this.getScrollTop(); const shouldScroll = ( scrollToFirstStep || (index > 0 || prevState.index > index)) && (step && !step.isFixed); // fixed steps don't need to scroll if (shouldRedraw && step) { this.calcPlacement(); } Iif (isRunning && scrollToSteps && shouldScroll && scrollTop >= 0) { scroll.top(getRootEl(), this.getScrollTop()); } Iif (steps.length && (!isRunning && shouldRun && !standaloneData)) { this.start(); } } componentWillUnmount() { window.removeEventListener('resize', this.listeners.resize); /* istanbul ignore else */ if (this.listeners.keyboard) { document.body.removeEventListener('keydown', this.listeners.keyboard); } /* istanbul ignore else */ if (Object.keys(this.listeners.tooltips).length) { Object.keys(this.listeners.tooltips) .map(key => ({ el: document.querySelector(key), event: this.listeners.tooltips[key].event, cb: this.listeners.tooltips[key].cb, key })) .filter(({ el }) => !!el) .forEach(({ el, event, cb, key }) => { el.removeEventListener(event, cb); delete this.listeners.tooltips[key]; }); } } /** * Starts the tour * * @param {boolean} [autorun] - Starts with the first tooltip opened * @param {Array} [steps] - Array of steps, defaults to this.props.steps * @param {number} [startIndex] - Optional step index to start joyride at */ start(autorun, steps = this.props.steps, startIndex = this.state.index) { const hasMountedTarget = Boolean(this.getStepTargetElement(steps[startIndex])); const shouldRenderTooltip = (autorun === true) && hasMountedTarget; logger({ type: 'joyride:start', msg: ['autorun:', autorun === true], debug: this.props.debug, }); this.setState({ action: 'start', index: startIndex, isRunning: Boolean(steps.length) && hasMountedTarget, shouldRenderTooltip, shouldRun: !steps.length, }); } /** * Stop the tour */ stop() { logger({ type: 'joyride:stop', debug: this.props.debug, }); this.setState({ isRunning: false, shouldRenderTooltip: false }); } /** * Move to the next step, if there is one. If there is no next step, hide the tooltip. */ next() { const { index, shouldRenderTooltip } = this.state; const { steps } = this.props; const nextIndex = index + 1; const shouldDisplay = Boolean(steps[nextIndex]) && shouldRenderTooltip; logger({ type: 'joyride:next', msg: ['new index:', nextIndex], debug: this.props.debug, }); this.toggleTooltip({ show: shouldDisplay, index: nextIndex, action: 'next' }); } /** * Move to the previous step, if there is one. If there is no previous step, hide the tooltip. */ back() { const { index, shouldRenderTooltip } = this.state; const { steps } = this.props; const previousIndex = index - 1; const shouldDisplay = Boolean(steps[previousIndex]) && shouldRenderTooltip; logger({ type: 'joyride:back', msg: ['new index:', previousIndex], debug: this.props.debug, }); this.toggleTooltip({ show: shouldDisplay, index: previousIndex, action: 'next' }); } /** * Reset Tour * * @param {boolean} [restart] - Starts the new tour right away */ reset(restart) { const { index, isRunning } = this.state; const shouldRestart = restart === true; const newState = { ...defaultState, isRunning: shouldRestart, shouldRenderTooltip: this.props.autoStart, }; logger({ type: 'joyride:reset', msg: ['restart:', shouldRestart], debug: this.props.debug, }); // Force a re-render if necessary if (shouldRestart && isRunning === shouldRestart && index === 0) { this.forceUpdate(); } this.setState(newState); } /** * Retrieve the current progress of your tour * * @returns {{index: number, percentageComplete: number, step: (object|null)}} */ getProgress() { const { index } = this.state; const { steps } = this.props; logger({ type: 'joyride:getProgress', msg: ['steps:', steps], debug: this.props.debug, }); return { index, percentageComplete: parseFloat(((index / steps.length) * 100).toFixed(2).replace('.00', '')), step: steps[index] }; } /** * Add standalone tooltip events * * @param {Object} data - Similar shape to a 'step', but for a single tooltip */ addTooltip(data) { Iif (!this.checkStepValidity(data)) { logger({ type: 'joyride:addTooltip:FAIL', msg: ['data:', data], debug: this.props.debug, }); return; } logger({ type: 'joyride:addTooltip', msg: ['data:', data], debug: this.props.debug, }); const key = data.trigger || sanitizeSelector(data.selector); const el = document.querySelector(key); Iif (!el) { return; } el.setAttribute('data-tooltip', JSON.stringify(data)); const eventType = data.event || 'click'; /* istanbul ignore else */ if (eventType === 'hover') { this.listeners.tooltips[`${key}mouseenter`] = { event: 'mouseenter', cb: this.onClickStandaloneTrigger }; this.listeners.tooltips[`${key}mouseleave`] = { event: 'mouseleave', cb: this.onClickStandaloneTrigger }; el.addEventListener('mouseenter', this.listeners.tooltips[`${key}mouseenter`].cb); el.addEventListener('mouseleave', this.listeners.tooltips[`${key}mouseleave`].cb); } this.listeners.tooltips[`${key}click`] = { event: 'click', cb: this.onClickStandaloneTrigger }; el.addEventListener('click', this.listeners.tooltips[`${key}click`].cb); } /** * Parse the incoming steps * * @deprecated * * @param {Array|Object} steps * @returns {Array} */ parseSteps(steps) { logger({ type: 'joyride:parseSteps', msg: 'joyride.parseSteps() is deprecated. It is no longer necessary to parse steps before providing them to Joyride.', warn: true, debug: this.props.debug, }); return steps; } /** * Verify that a step is valid * * @param {Object} step - A step object * @returns {boolean} - True if the step is valid, false otherwise */ checkStepValidity(step) { // Check that the step is the proper type if (!step || typeof step !== 'object' || Array.isArray(step)) { logger({ type: 'joyride:checkStepValidity', msg: 'Did not provide a step object.', warn: true, debug: this.props.debug, }); return false; } // Check that all required step fields are present const requiredFields = ['selector']; const hasRequiredField = (requiredField) => { const hasField = Boolean(step[requiredField]); Iif (!hasField) { logger({ type: 'joyride:checkStepValidity', msg: [`Provided a step without the required ${requiredField} property.`, 'Step:', step], warn: true, debug: this.props.debug, }); } return hasField; }; return requiredFields.every(hasRequiredField); } /** * Check one or more steps are valid * * @param {Object|Array} steps - A step object or array of step objects * @returns {boolean} - True if one or more stpes, and all steps are valid, false otherwise */ checkStepsValidity(steps) { /* istanbul ignore else */ Iif (!Array.isArray(steps) && typeof steps === 'object') { return this.checkStepValidity(steps); } else if (steps.length > 0) { return steps.every(this.checkStepValidity); } return false; } /** * Find and return the targeted DOM element based on a step's 'selector'. * * @private * @param {Object} step - A step object * @returns {Element} - A DOM element (if found) */ getStepTargetElement(step) { const isValidStep = this.checkStepValidity(step); if (!isValidStep) { return null; } const el = document.querySelector(sanitizeSelector(step.selector)); if (!el) { logger({ type: 'joyride:getStepTargetElement', msg: 'Target not rendered. For best results only add steps after they are mounted.', warn: true, debug: this.props.debug, }); return null; } return el; } /** * Get an element actual dimensions with margin * * @private * @returns {{height: number, width: number}} */ getElementDimensions() { const { shouldRenderTooltip, standaloneData } = this.state; const displayTooltip = standaloneData ? true : shouldRenderTooltip; const el = document.querySelector(displayTooltip ? '.joyride-tooltip' : '.joyride-beacon'); let height = 0; let width = 0; if (el) { const styles = window.getComputedStyle(el); height = el.clientHeight + parseInt(styles.marginTop || 0, 10) + parseInt(styles.marginBottom || 0, 10); width = el.clientWidth + parseInt(styles.marginLeft || 0, 10) + parseInt(styles.marginRight || 0, 10); } return { height, width }; } /** * Get the scrollTop position * * @private * @returns {number} */ getScrollTop() { const { index, yPos } = this.state; const { scrollOffset, steps } = this.props; const step = steps[index]; const target = this.getStepTargetElement(step); if (!target) { return 0; } const rect = target.getBoundingClientRect(); const targetTop = rect.top + (window.pageYOffset || document.documentElement.scrollTop); const position = this.calcPosition(step); let scrollTo = 0; /* istanbul ignore else */ if (/^top/.test(position)) { scrollTo = Math.floor(yPos - scrollOffset); } else if (/^bottom|^left|^right/.test(position)) { scrollTo = Math.floor(targetTop - scrollOffset); } return scrollTo; } /** * Trigger the callback. * * @private * @param {Object} options */ triggerCallback(options) { const { callback } = this.props; /* istanbul ignore else */ if (typeof callback === 'function') { logger({ type: 'joyride:triggerCallback', msg: [options], debug: this.props.debug, }); callback(options); } } /** * Keydown event listener * * @private * @param {Event} e - Keyboard event */ onKeyboardNavigation(e) { const { index, shouldRenderTooltip } = this.state; const { steps } = this.props; const intKey = (window.Event) ? e.which : e.keyCode; let hasSteps; if (shouldRenderTooltip) { if ([32, 38, 40].indexOf(intKey) > -1) { e.preventDefault(); } if (intKey === 27) { this.toggleTooltip({ show: false, index: index + 1, action: 'esc' }); } else if ([13, 32].indexOf(intKey) > -1) { hasSteps = Boolean(steps[index + 1]); this.toggleTooltip({ show: hasSteps, index: index + 1, action: 'next' }); } } } /** * Tooltip event listener * * @private * @param {Event} e - Click event */ onClickStandaloneTrigger(e) { e.preventDefault(); const { isRunning, standaloneData } = this.state; let tooltipData = e.currentTarget.dataset.tooltip; Iif (['mouseenter', 'mouseleave'].includes(e.type) && hasTouch) { return; } /* istanbul ignore else */ if (tooltipData) { tooltipData = JSON.parse(tooltipData); if (!standaloneData || (standaloneData.selector !== tooltipData.selector)) { this.setState({ isRunning: false, shouldRenderTooltip: false, shouldRun: isRunning, standaloneData: tooltipData, xPos: -1000, yPos: -1000 }); } else { document.querySelector('.joyride-tooltip__close').click(); } } } /** * Beacon click event listener * * @private * @param {Event} e - Click event */ onClickBeacon(e) { e.preventDefault(); const { index } = this.state; const { steps } = this.props; this.triggerCallback({ action: e.type, index, type: callbackTypes.BEACON_TRIGGER, step: steps[index] }); this.toggleTooltip({ show: true, index, action: `beacon:${e.type}` }); } /** * Tooltip click event listener * * @private * @param {Event} e - Click event */ onClickTooltip(e) { const { index, shouldRun } = this.state; const { steps, type } = this.props; const el = e.currentTarget.className.includes('joyride-') && ['A', 'BUTTON'].includes(e.currentTarget.tagName) ? e.currentTarget : e.target; const dataType = el.dataset.type; /* istanbul ignore else */ if (el.className.indexOf('joyride-') === 0) { e.preventDefault(); e.stopPropagation(); const tooltip = document.querySelector('.joyride-tooltip'); let newIndex = index + (dataType === 'back' ? -1 : 1); Iif (dataType === 'skip') { this.setState({ isTourSkipped: true }); newIndex = steps.length + 1; } /* istanbul ignore else */ if (tooltip.classList.contains('joyride-tooltip--standalone')) { this.setState({ isRunning: shouldRun, shouldRedraw: true, shouldRun: false, standaloneData: false }); } else if (dataType) { const shouldDisplay = ['continuous', 'guided'].indexOf(type) > -1 && ['close', 'skip'].indexOf(dataType) === -1 && Boolean(steps[newIndex]); this.toggleTooltip({ show: shouldDisplay, index: newIndex, action: dataType }); } Iif (e.target.className === 'joyride-overlay') { this.triggerCallback({ action: 'click', type: callbackTypes.OVERLAY, step: steps[index] }); } Iif (e.target.classList.contains('joyride-hole')) { this.triggerCallback({ action: 'click', type: callbackTypes.HOLE, step: steps[index] }); } } } onRenderTooltip() { this.calcPlacement(); } /** * Toggle Tooltip's visibility * * @private * @param {Object} options - Immediately destructured argument object * @param {Boolean} options.show - Render the tooltip or the beacon * @param {Number} options.index - The tour's new index * @param {string} [options.action] - The action being undertaken. * @param {Array} [options.steps] - The array of step objects that is going to be rendered */ toggleTooltip({ show, index = this.state.index, action, steps = this.props.steps }) { const nextStep = steps[index]; const hasMountedTarget = Boolean(this.getStepTargetElement(nextStep)); this.setState({ action, index, // Stop playing if there is no next step or can't find the target isRunning: (nextStep && hasMountedTarget) ? this.state.isRunning : false, // If we are not showing now, or there is no target, we'll need to redraw eventually shouldRedraw: !show || !hasMountedTarget, shouldRenderTooltip: show && hasMountedTarget, xPos: -1000, yPos: -1000 }); } /** * Position absolute elements next to its target * * @private */ calcPlacement() { const { index, isRunning, standaloneData, shouldRenderTooltip } = this.state; const { steps, tooltipOffset } = this.props; const step = standaloneData || (steps[index] || {}); const displayTooltip = standaloneData ? true : shouldRenderTooltip; const target = this.getStepTargetElement(step); logger({ type: `joyride:calcPlacement${this.getRenderStage()}`, msg: ['step:', step], debug: this.props.debug, }); /* istanbul ignore else */ if (!target) { return; } const placement = { x: -1000, y: -1000 }; /* istanbul ignore else */ if (step && (standaloneData || (isRunning && steps[index]))) { const offsetX = nested.get(step, 'style.beacon.offsetX') || 0; const offsetY = nested.get(step, 'style.beacon.offsetY') || 0; const position = this.calcPosition(step); const body = document.body.getBoundingClientRect(); const scrollTop = step.isFixed === true ? 0 : body.top; const component = this.getElementDimensions(); const rect = target.getBoundingClientRect(); // Calculate x position Iif (/^left/.test(position)) { placement.x = rect.left - (displayTooltip ? component.width + tooltipOffset : (component.width / 2) + offsetX); } else Iif (/^right/.test(position)) { placement.x = (rect.left + rect.width) - (displayTooltip ? -tooltipOffset : (component.width / 2) - offsetX); } else { placement.x = rect.left + ((rect.width / 2) - (component.width / 2)); } // Calculate y position if (/^top/.test(position)) { placement.y = (rect.top - scrollTop) - (displayTooltip ? component.height + tooltipOffset : (component.height / 2) + offsetY); } else Eif (/^bottom/.test(position)) { placement.y = (rect.top - scrollTop) + (rect.height - (displayTooltip ? -tooltipOffset : (component.height / 2) - offsetY)); } else { placement.y = (rect.top - scrollTop); } /* istanbul ignore else */ if (/^bottom|^top/.test(position)) { Iif (/left/.test(position)) { placement.x = rect.left - (displayTooltip ? tooltipOffset : component.width / 2); } else Iif (/right/.test(position)) { placement.x = rect.left + (rect.width - (displayTooltip ? component.width - tooltipOffset : component.width / 2)); } } this.setState({ shouldRedraw: false, xPos: this.preventWindowOverflow(Math.ceil(placement.x), 'x', component.width, component.height), yPos: this.preventWindowOverflow(Math.ceil(placement.y), 'y', component.width, component.height) }); } } /** * Update position for small screens. * * @private * @param {Object} step * * @returns {string} */ calcPosition(step) { const { tooltipOffset } = this.props; const body = document.body.getBoundingClientRect(); const target = this.getStepTargetElement(step); const width = this.getElementDimensions().width || DEFAULTS.minWidth; const rect = target.getBoundingClientRect(); let position = step.position || DEFAULTS.position; if (/^left/.test(position) && rect.left - (width + tooltipOffset) < 0) { position = 'top'; } else Iif (/^right/.test(position) && (rect.left + rect.width + (width + tooltipOffset)) > body.width) { position = 'bottom'; } return position; } /** * Get the render stage. * * @private * @returns {string} */ getRenderStage() { const { shouldRedraw, xPos } = this.state; if (shouldRedraw) { return ':redraw'; } else if (xPos < 0) { return ':pre-render'; } return ''; } /** * Prevent tooltip to render outside the window * * @private * @param {Number} value - The axis position * @param {String} axis - The Axis X or Y * @param {Number} elWidth - The target element width * @param {Number} elHeight - The target element height * @returns {Number} */ preventWindowOverflow(value, axis, elWidth, elHeight) { const winWidth = window.innerWidth; const body = document.body; const html = document.documentElement; const docHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight); let newValue = value; /* istanbul ignore else */ if (axis === 'x') { Iif (value + elWidth >= winWidth) { newValue = winWidth - elWidth - 15; } else Iif (value < 15) { newValue = 15; } } else if (axis === 'y') { if (value + elHeight >= docHeight) { newValue = docHeight - elHeight - 15; } else if (value < 15) { newValue = 15; } } return newValue; } /** * Create a React Element * * @private * @returns {boolean|ReactComponent} */ createComponent() { const { index, shouldRedraw, shouldRenderTooltip, standaloneData, xPos, yPos } = this.state; const { disableOverlay, holePadding, locale, showBackButton, showOverlay, showSkipButton, showStepsProgress, steps, type } = this.props; const currentStep = standaloneData || steps[index]; const step = { ...currentStep }; const target = this.getStepTargetElement(step); let component; const allowClicksThruHole = (step && step.allowClicksThruHole) || this.props.allowClicksThruHole; const shouldShowOverlay = standaloneData ? false : showOverlay; const buttons = { primary: locale.close }; logger({ type: `joyride:createComponent${this.getRenderStage()}`, msg: [ 'component:', shouldRenderTooltip || standaloneData ? 'Tooltip' : 'Beacon', 'animate:', xPos > -1 && !shouldRedraw, 'step:', step ], debug: this.props.debug, warn: !target, }); Iif (!target) { return false; } if (shouldRenderTooltip || standaloneData) { const position = this.calcPosition(step); /* istanbul ignore else */ if (!standaloneData) { /* istanbul ignore else */ if (['continuous', 'guided'].indexOf(type) > -1) { buttons.primary = locale.last; /* istanbul ignore else */ if (steps[index + 1]) { Iif (showStepsProgress) { let next = locale.next; if (typeof locale.next === 'string') { next = (<span>{locale.next}</span>); } buttons.primary = (<span>{next} <span>{`${(index + 1)}/${steps.length}`}</span></span>); } else { buttons.primary = locale.next; } } if (showBackButton && index > 0) { buttons.secondary = locale.back; } } Iif (showSkipButton) { buttons.skip = locale.skip; } } component = React.createElement(Tooltip, { allowClicksThruHole, animate: xPos > -1 && !shouldRedraw, buttons, disableOverlay, holePadding, position, selector: sanitizeSelector(step.selector), showOverlay: shouldShowOverlay, step, standalone: Boolean(standaloneData), target, type, xPos, yPos, onClick: this.onClickTooltip, onRender: this.onRenderTooltip }); } else { component = React.createElement(Beacon, { step, xPos, yPos, onTrigger: this.onClickBeacon, eventType: step.type || 'click' }); } return component; } render() { const { index, isRunning, standaloneData } = this.state; const { steps } = this.props; const hasStep = Boolean(steps[index]); let component; let standaloneComponent; if (isRunning && hasStep) { logger({ type: `joyride:render${this.getRenderStage()}`, msg: ['step:', steps[index]], debug: this.props.debug, }); } else if (!isRunning && standaloneData) { logger({ type: 'joyride:render', msg: ['tooltip:', standaloneData], debug: this.props.debug, }); } if (standaloneData) { standaloneComponent = this.createComponent(); } else if (isRunning && hasStep) { component = this.createComponent(); } return ( <div className="joyride"> {component} {standaloneComponent} </div> ); } } export default Joyride; |