Debian Codegraph @

progress-plugin/src/index.ts

raw
1 import Plugin from '@swup/plugin';
2 import ProgressBar from './ProgressBar.js';
3
4 type Options = {
5 className: string;
6 delay: number;
7 transition: number;
8 minValue: number;
9 initialValue: number;
10 finishAnimation: boolean;
11 };
12
13 export default class SwupProgressPlugin extends Plugin {
14 name = 'SwupProgressPlugin';
15
16 defaults: Options = {
17 className: 'swup-progress-bar',
18 delay: 300,
19 transition: 300,
20 minValue: 0.1,
21 initialValue: 0.25,
22 finishAnimation: true
23 };
24 options: Options;
25
26 progressBar: ProgressBar;
27 showProgressBarTimeout?: number;
28 hideProgressBarTimeout?: number;
29
30 constructor(options: Partial<Options> = {}) {
31 super();
32 this.options = { ...this.defaults, ...options };
33 const { className, minValue, initialValue, transition: animationDuration } = this.options;
34 this.progressBar = new ProgressBar({
35 className,
36 minValue,
37 initialValue,
38 animationDuration
39 });
40 }
41
42 mount() {
43 this.on('visit:start', this.startShowingProgress);
44 this.on('page:view', this.stopShowingProgress);
45 }
46
47 startShowingProgress() {
48 this.progressBar.setValue(0);
49 this.showProgressBarAfterDelay();
50 }
51
52 stopShowingProgress() {
53 this.progressBar.setValue(1);
54 if (this.options.finishAnimation) {
55 this.finishAnimationAndHideProgressBar();
56 } else {
57 this.hideProgressBar();
58 }
59 }
60
61 showProgressBar() {
62 this.cancelHideProgressBarTimeout();
63 this.progressBar.show();
64 }
65
66 showProgressBarAfterDelay() {
67 this.cancelShowProgressBarTimeout();
68 this.cancelHideProgressBarTimeout();
69 this.showProgressBarTimeout = window.setTimeout(
70 this.showProgressBar.bind(this),
71 this.options.delay
72 );
73 }
74
75 hideProgressBar() {
76 this.cancelShowProgressBarTimeout();
77 this.progressBar.hide();
78 }
79
80 finishAnimationAndHideProgressBar() {
81 this.cancelShowProgressBarTimeout();
82 this.hideProgressBarTimeout = window.setTimeout(
83 this.hideProgressBar.bind(this),
84 this.options.transition
85 );
86 }
87
88 cancelShowProgressBarTimeout() {
89 window.clearTimeout(this.showProgressBarTimeout);
90 delete this.showProgressBarTimeout;
91 }
92
93 cancelHideProgressBarTimeout() {
94 window.clearTimeout(this.hideProgressBarTimeout);
95 delete this.hideProgressBarTimeout;
96 }
97 }