-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
amp-social-share.js
181 lines (159 loc) · 6.2 KB
/
amp-social-share.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
/**
* 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 {addParamsToUrl, parseUrl, parseQueryString} from '../../../src/url';
import {setStyle} from '../../../src/style';
import {getDataParamsFromAttributes} from '../../../src/dom';
import {getSocialConfig} from './amp-social-share-config';
import {isLayoutSizeDefined} from '../../../src/layout';
import {dev, user} from '../../../src/log';
import {dict} from '../../../src/utils/object';
import {openWindowDialog} from '../../../src/dom';
import {Services} from '../../../src/services';
import {CSS} from '../../../build/amp-social-share-0.1.css';
class AmpSocialShare extends AMP.BaseElement {
/** @param {!AmpElement} element */
constructor(element) {
super(element);
/** @private {?string} */
this.shareEndpoint_ = null;
/** @private @const {!JsonObject} */
this.params_ = dict();
/** @private {?../../../src/service/platform-impl.Platform} */
this.platform_ = null;
/** @private {?../../../src/service/viewer-impl.Viewer} */
this.viewer_ = null;
/** @private {?string} */
this.href_ = null;
/** @private {?string} */
this.target_ = null;
}
/** @override */
isLayoutSupported() {
return true;
}
/** @override */
buildCallback() {
const typeAttr = user().assert(this.element.getAttribute('type'),
'The type attribute is required. %s', this.element);
user().assert(!/\s/.test(typeAttr),
'Space characters are not allowed in type attribute value. %s',
this.element);
this.platform_ = Services.platformFor(this.win);
this.viewer_ = Services.viewerForDoc(this.element);
if (typeAttr === 'system') {
// Hide/ignore system component if navigator.share unavailable
if (!this.systemShareSupported_()) {
setStyle(this.element, 'display', 'none');
return;
}
} else {
// Hide/ignore non-system component if system share wants to be unique
const systemOnly = this.systemShareSupported_() &&
!!this.win.document.querySelectorAll(
'amp-social-share[type=system][data-mode=replace]').length;
if (systemOnly) {
setStyle(this.element, 'display', 'none');
return;
}
}
const typeConfig = getSocialConfig(typeAttr) || dict();
this.shareEndpoint_ = user().assert(
this.element.getAttribute('data-share-endpoint') ||
typeConfig['shareEndpoint'],
'The data-share-endpoint attribute is required. %s', this.element);
Object.assign(this.params_, typeConfig['defaultParams'],
getDataParamsFromAttributes(this.element));
const hrefWithVars = addParamsToUrl(this.shareEndpoint_, this.params_);
const urlReplacements = Services.urlReplacementsForDoc(this.getAmpDoc());
const bindingVars = typeConfig['bindings'];
const bindings = {};
if (bindingVars) {
bindingVars.forEach(name => {
const bindingName = name.toUpperCase();
bindings[bindingName] = this.params_[name];
});
}
urlReplacements.expandUrlAsync(hrefWithVars, bindings).then(href => {
this.href_ = href;
// mailto:, whatsapp: protocols breaks when opened in _blank on iOS Safari
const protocol = parseUrl(href).protocol;
const isMailTo = protocol === 'mailto:';
const isWhatsApp = protocol === 'whatsapp:';
const isSms = protocol === 'sms:';
const isIosSafari = this.platform_.isIos() && this.platform_.isSafari();
this.target_ = (isIosSafari && (isMailTo || isWhatsApp || isSms))
? '_top' : '_blank';
if (isSms) {
// http://stackoverflow.com/a/19126326
// This code path seems to be stable for both iOS and Android.
this.href_ = this.href_.replace('?', '?&');
}
});
this.element.setAttribute('role', 'button');
if (!this.element.hasAttribute('tabindex')) {
this.element.setAttribute('tabindex', '0');
}
this.element.addEventListener('click', () => this.handleClick_());
this.element.addEventListener('keydown', this.handleKeyPress_.bind(this));
this.element.classList.add(`amp-social-share-${typeAttr}`);
}
/**
* Handle key presses on the element.
* @param {!Event} event
* @private
*/
handleKeyPress_(event) {
const keyCode = event.keyCode;
if (keyCode == KeyCodes.SPACE || keyCode == KeyCodes.ENTER) {
event.preventDefault();
this.handleActivation_();
}
}
/**
* Handle clicks on the element.
* @private
*/
handleClick_() {
this.handleActivation_();
}
/** @private */
handleActivation_() {
user().assert(this.href_ && this.target_, 'Clicked before href is set.');
const href = dev().assertString(this.href_);
const target = dev().assertString(this.target_);
if (this.shareEndpoint_ === 'navigator-share:') {
dev().assert(navigator.share !== undefined,
'navigator.share disappeared.');
// navigator.share() fails 'gulp check-types' validation on Travis
navigator['share'](parseQueryString(href.substr(href.indexOf('?'))));
} else {
const windowFeatures = 'resizable,scrollbars,width=640,height=480';
openWindowDialog(this.win, href, target, windowFeatures);
}
}
/** @private */
systemShareSupported_() {
// Chrome exports navigator.share in WebView but does not implement it.
// See https://bugs.chromium.org/p/chromium/issues/detail?id=765923
const isChromeWebview = this.viewer_.isWebviewEmbedded() &&
this.platform_.isChrome();
return ('share' in navigator) && !isChromeWebview;
}
}
AMP.extension('amp-social-share', '0.1', AMP => {
AMP.registerElement('amp-social-share', AmpSocialShare, CSS);
});