-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
amp-accordion.js
254 lines (230 loc) · 8.26 KB
/
amp-accordion.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
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
/**
* Copyright 2016 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {KeyCodes} from '../../../src/utils/key-codes';
import {Layout} from '../../../src/layout';
import {closest} from '../../../src/dom';
import {dev, user} from '../../../src/log';
import {removeFragment} from '../../../src/url';
import {dict} from '../../../src/utils/object';
import {tryFocus} from '../../../src/dom';
import {parseJson} from '../../../src/json';
class AmpAccordion extends AMP.BaseElement {
/** @param {!AmpElement} element */
constructor(element) {
super(element);
/** @private {!Array<!Node>} */
this.headers_ = [];
/** @private {?string} */
this.sessionId_ = null;
/** @private {?JsonObject} */
this.currentState_ = null;
/** @private {boolean} */
this.sessionOptOut_ = false;
}
/** @override */
isLayoutSupported(layout) {
return layout == Layout.CONTAINER;
}
/** @override */
buildCallback() {
this.sessionOptOut_ = this.element.hasAttribute('disable-session-states');
// sessionStorage key: special created id for this element, this.sessionId_.
// sessionStorage value: string that can convert to this.currentState_ obj.
this.sessionId_ = this.getSessionStorageKey_();
this.currentState_ = this.getSessionState_();
const sections = this.getRealChildren();
sections.forEach((section, index) => {
user().assert(
section.tagName.toLowerCase() == 'section',
'Sections should be enclosed in a <section> tag, ' +
'See https://github.com/ampproject/amphtml/blob/master/extensions/' +
'amp-accordion/amp-accordion.md. Found in: %s', this.element);
const sectionComponents = section.children;
user().assert(
sectionComponents.length == 2,
'Each section must have exactly two children. ' +
'See https://github.com/ampproject/amphtml/blob/master/extensions/' +
'amp-accordion/amp-accordion.md. Found in: %s', this.element);
const content = sectionComponents[1];
content.classList.add('i-amphtml-accordion-content');
let contentId = content.getAttribute('id');
if (!contentId) {
contentId = this.element.id + '_AMP_content_' + index;
content.setAttribute('id', contentId);
}
if (this.currentState_[contentId]) {
section.setAttribute('expanded', '');
} else if (this.currentState_[contentId] === false) {
section.removeAttribute('expanded');
}
this.mutateElement(() => {
// Just mark this element as dirty since we changed the state
// based on runtime state. This triggers checking again
// whether children need layout.
// See https://github.com/ampproject/amphtml/issues/3586
// for details.
});
const header = sectionComponents[0];
header.classList.add('i-amphtml-accordion-header');
header.setAttribute('role', 'heading');
header.setAttribute('aria-controls', contentId);
header.setAttribute('aria-expanded',
section.hasAttribute('expanded').toString());
if (!header.hasAttribute('tabindex')) {
header.setAttribute('tabindex', 0);
}
this.headers_.push(header);
header.addEventListener('click', this.clickHandler_.bind(this));
header.addEventListener('keydown', this.keyDownHandler_.bind(this));
});
}
/**
* Generate a sessionStorage Key based on amp-accordion element id.
* @return {?string}
* @private
*/
getSessionStorageKey_() {
const id_ = this.element.id || this.element.getResourceId();
const url = removeFragment(this.win.location.href);
return `amp-${id_}-${url}`;
}
/**
* Get previous state from sessionStorage.
* @return {!JsonObject}
* @private
*/
getSessionState_() {
if (this.sessionOptOut_) {
return dict();
}
try {
const sessionStr =
this.win./*OK*/sessionStorage.getItem(
dev().assertString(this.sessionId_));
return sessionStr
? /** @type {!JsonObject} */ (
dev().assert(parseJson(dev().assertString(sessionStr))))
: dict();
} catch (e) {
dev().fine('AMP-ACCORDION', e.message, e.stack);
return dict();
}
}
/**
* Set current state to sessionStorage.
* @private
*/
setSessionState_() {
if (this.sessionOptOut_) {
return;
}
const sessionStr = JSON.stringify(this.currentState_);
try {
this.win./*OK*/sessionStorage.setItem(
dev().assertString(this.sessionId_), sessionStr);
} catch (e) {
dev().fine('AMP-ACCORDION', e.message, e.stack);
}
}
/**
* Handles accordion header activation, through clicks or enter/space presses.
* @param {!Event} event 'click' or 'keydown' event.
* @private
*/
onHeaderPicked_(event) {
event.preventDefault();
const header = dev().assertElement(event.currentTarget);
const section = header.parentElement;
const sectionComponents = section.children;
const content = sectionComponents[1];
const contentId = content.getAttribute('id');
const isSectionClosedAfterClick = section.hasAttribute('expanded');
this.mutateElement(() => {
if (section.hasAttribute('expanded')) {
section.removeAttribute('expanded');
header.setAttribute('aria-expanded', 'false');
} else {
section.setAttribute('expanded', '');
header.setAttribute('aria-expanded', 'true');
}
}, section);
this.currentState_[contentId] = !isSectionClosedAfterClick;
this.setSessionState_();
}
/**
* Handles clicks on an accordion header to expand/collapse its content.
*/
clickHandler_(event) {
// Need to support clicks on any children of the header except
// for on links, which should not have their default behavior
// overidden.
const target = dev().assertElement(event.target);
const header = dev().assertElement(event.currentTarget);
const anchor = closest(target, e => e.tagName == 'A', header);
if (anchor === null) {
// Don't use clicks on links in header to expand/collapse.
this.onHeaderPicked_(event);
}
}
/**
* Handles key presses on an accordion header to expand/collapse its content
* or move focus to previous/next header.
* @param {!Event} event keydown event.
*/
keyDownHandler_(event) {
if (event.defaultPrevented) {
return;
}
const keyCode = event.keyCode;
switch (keyCode) {
case KeyCodes.UP_ARROW: /* fallthrough */
case KeyCodes.DOWN_ARROW:
this.navigationKeyDownHandler_(event);
return;
case KeyCodes.ENTER: /* fallthrough */
case KeyCodes.SPACE:
if (event.target == event.currentTarget) {
// Only activate if header element was activated directly.
// Do not respond to key presses on its children.
this.onHeaderPicked_(event);
}
return;
}
}
/**
* Handles keyboard navigation events. Only respond to keyboard navigation
* if a section header already has focus.
* @param {!Event} event
* @private
*/
navigationKeyDownHandler_(event) {
const header = dev().assertElement(event.currentTarget);
const index = this.headers_.indexOf(header);
if (index !== -1) {
event.preventDefault();
// Up and down are the same regardless of locale direction.
const diff = event.keyCode == KeyCodes.UP_ARROW ? -1 : 1;
// If user navigates one past the beginning or end, wrap around.
let newFocusIndex = (index + diff) % this.headers_.length;
if (newFocusIndex < 0) {
newFocusIndex = newFocusIndex + this.headers_.length;
}
const newFocusHeader = this.headers_[newFocusIndex];
tryFocus(newFocusHeader);
}
}
}
AMP.registerElement('amp-accordion', AmpAccordion);