forked from unbug/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
318 lines (262 loc) · 10.3 KB
/
app.js
File metadata and controls
318 lines (262 loc) · 10.3 KB
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
(function(exports) {
// Control whether the site is ajax or static.
var AJAXIFY_SITE = true;//!navigator.userAgent.match('Mobile|Android');
var wasRelativeAnchorClick = false;
var siteBanner = null;
var docsMenu = null;
var dropdownPanel = null;
var appBar = null;
var sidebar = null;
function hideSidebar() {
sidebar.close();
}
function addPermalink(el) {
el.classList.add('has-permalink');
el.insertAdjacentHTML('beforeend',
'<a class="permalink" title="Permalink" href="#' + el.id + '">#</a>');
}
// Add permalinks to heading elements.
function addPermalinkHeadings(opt_inDoc) {
var doc = opt_inDoc || document;
var permalinkEl = doc.querySelector('.show-permalinks');
if (permalinkEl) {
['h2','h3','h4'].forEach(function(h, i) {
Array.prototype.forEach.call(
permalinkEl.querySelectorAll(h), addPermalink);
});
}
}
function prettyPrintPage(opt_inDoc) {
var doc = opt_inDoc || document;
// TODO: Use kramdown to add the class - {:.prettyprint .lang-js}.
Array.prototype.forEach.call(doc.querySelectorAll('pre'), function(pre, i) {
pre.classList.add('prettyprint');
});
exports.prettyPrint && prettyPrint();
}
/**
* Replaces in-page <script> tag in xhr'd body content with runnable script.
*
* @param {Node} node Container element to replace script content.
*/
function replaceScriptTagWithRunnableScript(node) {
var script = document.createElement('script');
script.text = node.innerHTML;
node.parentNode.replaceChild(script, node);
}
/**
* Replaces the main content of the page by loading the URL via XHR.
*
* @param {string} url The URL of the page to load.
* @param {boolean} opt_addToHistory If true, the URL is added to the browser's
* history.
*/
function injectPage(url, opt_addToHistory) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'document';
xhr.onloadend = function(e) {
if (e.target.status != 200) {
// TODO: use window.error and report this to server.
console.error('Page fetch error', e.target.status, e.target.statusText);
return;
}
var doc = e.target.response;
document.title = doc.title; // Update document title to fetched one.
var meta = doc.head.querySelector('meta[itemprop="name"]');
if (meta) {
var metaContentName = doc.head.querySelector('meta[itemprop="name"]').content;
document.head.querySelector('meta[itemprop="name"]').content = metaContentName;
}
// Update URL history now that title and URL are set.
var addToHistory = opt_addToHistory == undefined ? true : opt_addToHistory;
if (addToHistory) {
history.pushState({url: url}, doc.title, url);
}
// Record GA page view early; once metadata is set up and URL is updated.
exports.recordPageview();
// Update app-bar links.
var docAppBar = doc.querySelector('app-bar');
if (docAppBar) {
appBar.innerHTML = docAppBar.innerHTML;
} else {
// We're not on a doc page (e.g. demo page or something else). Just redirect.
location.href = url;
return;
}
// Inject article body.
var CONTAINER_SELECTOR = '#content-container scroll-area article';
var container = document.querySelector(CONTAINER_SELECTOR);
var newDocContainer = doc.querySelector(CONTAINER_SELECTOR);
container.innerHTML = newDocContainer.innerHTML;
// .innerHTML doesn't eval script. Replace <script> in-page with runnable version.
var scripts = container.querySelectorAll('script');
Array.prototype.forEach.call(scripts, function(node, i) {
replaceScriptTagWithRunnableScript(node);
});
// Set left-nav menu and highlight correct item.
docsMenu.setAttribute(
'menu', doc.querySelector('docs-menu').getAttribute('menu'));
docsMenu.highlightItemWithCurrentURL();
// Replace site-banner > header content.
var HEADER_SELECTOR = 'site-banner header';
var siteBannerHeader = document.querySelector(HEADER_SELECTOR);
siteBannerHeader.innerHTML = doc.querySelector(HEADER_SELECTOR).innerHTML;
// Update site-banner attributes. Elements in xhr'd document are not upgraded.
// We can't set properties directly. Instead, do old school attr replacement.
// This runs last to help color transition be buttery smooth.
var newDocSiteBanner = doc.querySelector('site-banner');
Array.prototype.forEach.call(newDocSiteBanner.attributes, function(attr, i) {
if (attr.name != 'unresolved') {
siteBanner.setAttribute(attr.name, attr.value);
}
});
// TODO: can't pass `doc` to prettyPrint() needs markup in DOM.
initPage();
// Scroll to hash, otherwise goto top of the loaded page.
if (location.hash) {
var scrollTargetEl = document.querySelector(location.hash);
scrollTargetEl && scrollTargetEl.scrollIntoView(true, {behavior: 'smooth'});
} else {
exports.scrollTo(0, 0);
}
// Hide mobile sidebar when injected page is finished loading. Prevents jank
// to do this as late as possible.
if (sidebar.mobile) {
hideSidebar();
}
};
xhr.send();
}
function initPage(opt_inDoc) {
var doc = opt_inDoc || document;
// TODO: do this at build time.
addPermalinkHeadings(doc);
// Only syntax highlight on desktop. Saves ~200ms.
if (!window.matchMedia('(max-width: 580px)').matches) {
prettyPrintPage(doc);
}
}
// Hijacks page to preventDefault() on links and make site ajax.
function ajaxifySite() {
document.addEventListener('polymer-ready', function(e) {
docsMenu.ajaxify = true;
dropdownPanel.ajaxify = true;
});
document.addEventListener('click', function(e) {
// Allow users to open new tabs.
if (e.metaKey || e.ctrlKey) {
return;
}
// Inject page if <a> was in the event path and matches ajax criteria:
// - was relative link and not javascript:
// - not a #hash link within the same page
// - is not going to a non-ajaxable page (index.html, apps, components, etc.)
// - was not targeted at a new window
for (var i = 0; i < e.path.length; ++i) {
var el = e.path[i];
if (el.localName == 'a') {
wasRelativeAnchorClick = !!el.hash;
if (!el.getAttribute('href').match(/^(https?:|javascript:|\/\/)/) &&
(location.origin == el.origin) &&
!(el.hash && (el.pathname == location.pathname)) &&
(el.pathname != '/') &&
(el.pathname != '/index.html') &&
(el.pathname.indexOf('/apps') != 0) &&
(el.pathname.indexOf('/components') != 0) &&
el.target == '') {
injectPage(el.href);
e.preventDefault();
e.stopPropagation();
}
return;
}
}
});
// TODO(ericbidelman): gave up on making this work on Safari + polyfill.
// Because this event fires on page in Safari/webkit, it means there's a
// wasteful call to injectPage().
// Note: Chromium no longer suffers from the popstate event firing on
// page load (crbug.com/63040). WebKit still does.
exports.addEventListener('popstate', function(e) {
Polymer.whenReady(function() {
if (e.state && e.state.url) {
// TODO(ericbidelman): Don't run this for relative anchors on the same page.
injectPage(e.state.url, false);
} else if (!wasRelativeAnchorClick && history.state) {
history.back();
}
});
});
}
document.addEventListener('polymer-ready', function(e) {
// TODO(ericbidelman): Hacky solution to get anchors scrolled to correct location
// in page. Layout of page happens later than the browser wants to scroll.
if (location.hash) {
window.setTimeout(function() {
var scrollTargetEl = document.querySelector(location.hash);
scrollTargetEl && scrollTargetEl.scrollIntoView(true, {behavior: 'smooth'});
}, 200);
}
// The dropdown panel in the sidebar for mobile
var dropdownToggle = document.querySelector('#dropdown-toggle');
var dropdownPanel = document.querySelector('dropdown-panel');
siteBanner.addEventListener('hamburger-time', function(e) {
sidebar.toggle();
});
dropdownToggle.addEventListener('click', function(e) {
dropdownPanel.openPanel();
// dropdownPanel listens to clicks on the document and autocloses
// so no need to add any more handlers
});
});
document.addEventListener('DOMContentLoaded', function(e) {
siteBanner = document.querySelector('site-banner');
docsMenu = document.querySelector('docs-menu');
dropdownPanel = document.querySelector('dropdown-panel');
sidebar = document.querySelector('#sidebar');
appBar = document.querySelector('app-bar');
if (AJAXIFY_SITE && docsMenu) { // Ajaxify on pages other than the home.
ajaxifySite();
// Insure add current page to history so back button has an URL for popstate.
history.pushState({url: document.location.href}, document.title,
document.location.href);
}
initPage();
});
document.addEventListener('click', function(e) {
// Search box close.
if (appBar.showingSearch) {
appBar.toggleSearch(e);
}
});
document.querySelector('[data-twitter-follow]').addEventListener('click', function(e) {
e.preventDefault();
var target = e.target.localName != 'a' ? e.target.parentElement : e.target;
exports.open(target.href, '', 'width=550,height=520');
});
// TODO: Create ga-logger component to avoid polluting the global scope.
exports.downloadStarter = function() {
ga('send', 'event', 'button', 'download');
};
exports.recordSearch = function(term) {
ga('send', 'event', 'search', term);
}
exports.recordPageview = function(opt_url) {
var url = opt_url || location.pathname + location.hash;
ga('send', 'pageview', url);
ga('devrelTracker.send', 'pageview', url);
};
// -------------------------------------------------------------------------- //
// Analytics -----
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-39334307-1', 'auto', {'siteSpeedSampleRate': 50});
ga('create', 'UA-49880327-9', 'auto', {'name': 'devrelTracker'});
exports.recordPageview();
// ---------------
console && console.log("%cWelcome to Polymer!\n%cweb components are the <bees-knees>",
"font-size:1.5em;color:#4558c9;", "color:#d61a7f;font-size:1em;");
})(window);