-
Notifications
You must be signed in to change notification settings - Fork 51
/
index.js
83 lines (75 loc) · 2.42 KB
/
index.js
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
// @flow
import * as Behaviors from 'hyperview/src/services/behaviors';
import type {
DOMString,
Document,
Element,
HvComponentOnUpdate,
HvGetRoot,
HvUpdateRoot,
} from 'hyperview/src/types';
import { later, shallowCloneToRoot } from 'hyperview/src/services';
export default {
action: 'toggle',
callback: (
element: Element,
onUpdate: HvComponentOnUpdate,
getRoot: HvGetRoot,
updateRoot: HvUpdateRoot,
) => {
const targetId: ?DOMString = element.getAttribute('target');
if (!targetId) {
return;
}
const delayAttr: string = element.getAttribute('delay') || '0';
const parsedDelay: number = parseInt(delayAttr, 10);
const delay: number = isNaN(parsedDelay) ? 0 : parsedDelay;
const showIndicatorIds: Array<string> = (
element.getAttribute('show-during-load') || ''
).split(' ');
const hideIndicatorIds: Array<string> = (
element.getAttribute('hide-during-load') || ''
).split(' ');
const toggleElement = () => {
const doc: Document = getRoot();
const targetElement: ?Element = doc.getElementById(targetId);
if (!targetElement) {
return;
}
// Toggle the hide attribute of the target
const isCurrentlyHidden: boolean =
targetElement.getAttribute('hide') === 'true';
const newToggleState: string = isCurrentlyHidden ? 'false' : 'true';
targetElement.setAttribute('hide', newToggleState);
let newRoot: Document = shallowCloneToRoot(targetElement);
// If using the delay, we need to undo the indicators shown earlier.
if (delay > 0) {
newRoot = Behaviors.setIndicatorsAfterLoad(
showIndicatorIds,
hideIndicatorIds,
newRoot,
);
}
// Update the DOM with the new toggle state and finished indicators.
updateRoot(newRoot);
};
if (delay === 0) {
// If there's no delay, toggle immediately without showing/hiding
// any indicators.
toggleElement();
} else {
// If there's a delay, first trigger the indicators before the toggle.
const newRoot = Behaviors.setIndicatorsBeforeLoad(
showIndicatorIds,
hideIndicatorIds,
getRoot(),
);
// Update the DOM to reflect the new state of the indicators.
updateRoot(newRoot);
// Wait for the delay then toggle the target.
later(delay)
.then(toggleElement)
.catch(toggleElement);
}
},
};