forked from ampproject/amphtml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
amp-state.js
176 lines (161 loc) · 5.1 KB
/
amp-state.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
/**
* 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 {Services} from '../../../src/services';
import {map} from '../../../src/utils/object';
import {fetchBatchedJsonFor} from '../../../src/batched-json';
import {isJsonScriptTag} from '../../../src/dom';
import {toggle} from '../../../src/style';
import {tryParseJson} from '../../../src/json';
import {dev, user} from '../../../src/log';
export class AmpState extends AMP.BaseElement {
/** @override */
getPriority() {
// Loads after other content.
return 1;
}
/** @override */
isAlwaysFixed() {
return true;
}
/** @override */
isLayoutSupported(unusedLayout) {
return true;
}
/** @override */
activate(unusedInvocation) {
// TODO(choumx): Remove this after a few weeks in production.
const TAG = this.getName_();
this.user().error(TAG,
'Please use AMP.setState() action explicitly, e.g. ' +
'on="submit-success:AMP.setState({myAmpState: event.response})"');
}
/** @override */
buildCallback() {
toggle(this.element, /* opt_display */ false);
this.element.setAttribute('aria-hidden', 'true');
// Don't parse or fetch in prerender mode.
const viewer = Services.viewerForDoc(this.getAmpDoc());
viewer.whenFirstVisible().then(() => this.initialize_());
}
/** @override */
mutatedAttributesCallback(mutations) {
const viewer = Services.viewerForDoc(this.getAmpDoc());
if (!viewer.isVisible()) {
const TAG = this.getName_();
dev().error(TAG, 'Viewer must be visible before mutation.');
return;
}
const src = mutations['src'];
if (src !== undefined) {
this.fetchSrcAndUpdateState_(/* isInit */ false);
}
}
/** @override */
renderOutsideViewport() {
// We want the state data to be available wherever it is in the document.
return true;
}
/** @private */
initialize_() {
if (this.element.hasAttribute('overridable')) {
Services.bindForDocOrNull(this.element).then(bind => {
dev().assert(bind, 'Bind service can not be found.');
bind.makeStateKeyOverridable(this.element.getAttribute('id'));
});
}
// Parse child script tag and/or fetch JSON from endpoint at `src`
// attribute, with the latter taking priority.
const children = this.element.children;
if (children.length > 0) {
this.parseChildAndUpdateState_();
}
if (this.element.hasAttribute('src')) {
this.fetchSrcAndUpdateState_(/* isInit */ true);
}
}
/**
* Parses JSON in child script element and updates state.
* @private
*/
parseChildAndUpdateState_() {
const TAG = this.getName_();
const children = this.element.children;
if (children.length != 1) {
this.user().error(
TAG, 'Should contain exactly one <script> child.');
return;
}
const firstChild = children[0];
if (!isJsonScriptTag(firstChild)) {
this.user().error(TAG,
'State should be in a <script> tag with type="application/json".');
return;
}
const json = tryParseJson(firstChild.textContent, e => {
this.user().error(
TAG, 'Failed to parse state. Is it valid JSON?', e);
});
this.updateState_(json, /* isInit */ true);
}
/**
* Wrapper to stub during testing.
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
* @param {!Element} element
* @return {!Promise}
* @visibleForTesting
*/
fetchBatchedJsonFor_(ampdoc, element) {
return fetchBatchedJsonFor(ampdoc, element);
}
/**
* @param {boolean} isInit
* @returm {!Promise}
* @private
*/
fetchSrcAndUpdateState_(isInit) {
const ampdoc = this.getAmpDoc();
return this.fetchBatchedJsonFor_(ampdoc, this.element).then(json => {
this.updateState_(json, isInit);
});
}
/**
* @param {*} json
* @param {boolean} isInit
* @private
*/
updateState_(json, isInit) {
if (json === undefined || json === null) {
return;
}
const id = user().assert(this.element.id, '<amp-state> must have an id.');
const state = /** @type {!JsonObject} */ (map());
state[id] = json;
Services.bindForDocOrNull(this.element).then(bind => {
dev().assert(bind, 'Bind service can not be found.');
bind.setState(state,
/* opt_skipEval */ isInit, /* opt_isAmpStateMutation */ !isInit);
});
}
/**
* @return {string} Returns a string to identify this tag. May not be unique
* if the element id is not unique.
* @private
*/
getName_() {
return '<amp-state> ' +
(this.element.getAttribute('id') || '<unknown id>');
}
}