Files
NodeBB/public/src/ajaxify.js

584 lines
17 KiB
JavaScript
Raw Normal View History

2017-02-18 01:56:23 -07:00
'use strict';
2022-02-28 15:43:43 -05:00
const hooks = require('./modules/hooks');
2022-02-19 18:07:08 -05:00
const { render } = require('./widgets');
2015-07-21 11:23:16 -04:00
2022-02-14 21:35:33 -05:00
window.ajaxify = window.ajaxify || {};
ajaxify.widgets = { render: render };
(function () {
let apiXHR = null;
let ajaxifyTimer;
2015-07-21 11:23:16 -04:00
let retry = true;
let previousBodyClass = '';
2015-07-21 11:23:16 -04:00
ajaxify.count = 0;
2015-07-21 11:23:16 -04:00
ajaxify.currentPage = null;
2015-08-10 17:57:51 -04:00
ajaxify.go = function (url, callback, quiet) {
// Automatically reconnect to socket and re-ajaxify on success
2015-07-21 11:23:16 -04:00
if (!socket.connected) {
app.reconnect();
2015-07-21 11:23:16 -04:00
if (ajaxify.reconnectAction) {
$(window).off('action:reconnected', ajaxify.reconnectAction);
}
ajaxify.reconnectAction = function (e) {
2015-08-10 17:57:51 -04:00
ajaxify.go(url, callback, quiet);
2015-07-21 11:23:16 -04:00
$(window).off(e);
2015-08-10 17:57:51 -04:00
};
2015-07-21 11:23:16 -04:00
$(window).on('action:reconnected', ajaxify.reconnectAction);
}
// Abort subsequent requests if clicked multiple times within a short window of time
if (ajaxifyTimer && (Date.now() - ajaxifyTimer) < 500) {
return true;
}
ajaxifyTimer = Date.now();
2015-07-21 11:23:16 -04:00
if (ajaxify.handleRedirects(url)) {
return true;
}
if (!quiet && url === ajaxify.currentPage + window.location.search + window.location.hash) {
quiet = true;
}
2015-10-20 17:53:44 -04:00
app.leaveCurrentRoom();
2015-07-21 11:23:16 -04:00
$(window).off('scroll');
if ($('#content').hasClass('ajaxifying') && apiXHR) {
apiXHR.abort();
}
app.previousUrl = !['reset'].includes(ajaxify.currentPage) ?
window.location.pathname.slice(config.relative_path.length) + window.location.search :
app.previousUrl;
2016-05-03 19:13:10 +03:00
2016-06-20 13:39:08 +03:00
url = ajaxify.start(url);
// If any listeners alter url and set it to an empty string, abort the ajaxification
if (url === null) {
2021-04-08 12:28:34 -04:00
hooks.fire('action:ajaxify.end', { url: url, tpl_url: ajaxify.data.template.name, title: ajaxify.data.title });
return false;
}
2016-08-05 16:32:44 +03:00
previousBodyClass = ajaxify.data.bodyClass;
2015-07-21 11:23:16 -04:00
$('#footer, #content').removeClass('hide').addClass('ajaxifying');
ajaxify.loadData(url, function (err, data) {
2021-02-04 02:07:29 -07:00
if (!err || (
err &&
err.data &&
(parseInt(err.data.status, 10) !== 302 && parseInt(err.data.status, 10) !== 308)
)) {
2016-06-20 14:55:50 +03:00
ajaxify.updateHistory(url, quiet);
}
2015-07-21 11:23:16 -04:00
if (err) {
return onAjaxError(err, url, callback, quiet);
}
2016-04-13 11:58:14 -04:00
2016-03-10 19:07:42 +02:00
retry = true;
2015-07-21 11:23:16 -04:00
renderTemplate(url, data.templateToRender || data.template.name, data, callback);
2015-07-21 11:23:16 -04:00
});
return true;
};
// this function is called just once from footer on page load
ajaxify.coldLoad = function () {
const url = ajaxify.start(window.location.pathname.slice(1) + window.location.search + window.location.hash);
ajaxify.updateHistory(url, true);
2020-09-06 22:07:39 -04:00
ajaxify.end(url, ajaxify.data.template.name);
hooks.fire('action:ajaxify.coldLoad');
};
ajaxify.isCold = function () {
return ajaxify.count <= 1;
};
ajaxify.handleRedirects = function (url) {
2017-03-07 16:13:09 +03:00
url = ajaxify.removeRelativePath(url.replace(/^\/|\/$/g, '')).toLowerCase();
const isClientToAdmin = url.startsWith('admin') && window.location.pathname.indexOf(config.relative_path + '/admin') !== 0;
const isAdminToClient = !url.startsWith('admin') && window.location.pathname.indexOf(config.relative_path + '/admin') === 0;
2017-03-07 13:38:31 +03:00
2018-04-19 14:24:01 -04:00
if (isClientToAdmin || isAdminToClient) {
2018-06-02 15:56:23 -04:00
window.open(config.relative_path + '/' + url, '_top');
2015-07-21 11:23:16 -04:00
return true;
}
return false;
};
ajaxify.start = function (url) {
2015-07-21 11:23:16 -04:00
url = ajaxify.removeRelativePath(url.replace(/^\/|\/$/g, ''));
const payload = {
2017-02-17 19:31:21 -07:00
url: url,
};
hooks.logs.collect();
2021-04-08 12:28:34 -04:00
hooks.fire('action:ajaxify.start', payload);
2015-07-21 11:23:16 -04:00
ajaxify.count += 1;
return payload.url;
2016-06-20 13:39:08 +03:00
};
ajaxify.updateHistory = function (url, quiet) {
2016-03-24 13:21:05 +02:00
ajaxify.currentPage = url.split(/[?#]/)[0];
2016-04-21 22:59:42 +03:00
if (window.history && window.history.pushState) {
window.history[!quiet ? 'pushState' : 'replaceState']({
2017-02-17 19:31:21 -07:00
url: url,
2018-06-02 15:56:23 -04:00
}, url, config.relative_path + '/' + url);
2016-04-21 22:59:42 +03:00
}
2015-07-21 11:23:16 -04:00
};
function onAjaxError(err, url, callback, quiet) {
const data = err.data;
const textStatus = err.textStatus;
2015-07-21 11:23:16 -04:00
if (data) {
let status = parseInt(data.status, 10);
2022-01-10 16:44:16 -05:00
if ([400, 403, 404, 500, 502, 504].includes(status)) {
2016-03-10 19:07:42 +02:00
if (status === 502 && retry) {
retry = false;
ajaxifyTimer = undefined;
2016-03-10 19:07:42 +02:00
return ajaxify.go(url, callback, quiet);
}
2015-07-21 11:23:16 -04:00
if (status === 502) {
status = 500;
}
if (data.responseJSON) {
data.responseJSON.config = config;
}
2016-03-10 19:07:42 +02:00
2015-07-21 11:23:16 -04:00
$('#footer, #content').removeClass('hide').addClass('ajaxifying');
2016-03-06 00:45:32 +02:00
return renderTemplate(url, status.toString(), data.responseJSON || {}, callback);
2015-07-21 11:23:16 -04:00
} else if (status === 401) {
2021-12-06 14:31:35 -05:00
require(['alerts'], function (alerts) {
alerts.error('[[global:please_log_in]]');
});
2015-07-21 11:23:16 -04:00
app.previousUrl = url;
2016-05-03 19:13:10 +03:00
window.location.href = config.relative_path + '/login';
} else if (status === 302 || status === 308) {
if (data.responseJSON && data.responseJSON.external) {
// this is used by sso plugins to redirect to the auth route
// cant use ajaxify.go for /auth/sso routes
window.location.href = data.responseJSON.external;
} else if (typeof data.responseJSON === 'string') {
ajaxifyTimer = undefined;
if (data.responseJSON.startsWith('http://') || data.responseJSON.startsWith('https://')) {
window.location.href = data.responseJSON;
} else {
ajaxify.go(data.responseJSON.slice(1), callback, quiet);
}
2015-07-21 11:23:16 -04:00
}
}
} else if (textStatus !== 'abort') {
2021-12-06 14:31:35 -05:00
require(['alerts'], function (alerts) {
alerts.error(data.responseJSON.error);
});
2015-07-21 11:23:16 -04:00
}
}
function renderTemplate(url, tpl_url, data, callback) {
hooks.fire('action:ajaxify.loadingTemplates', {});
2020-12-02 14:14:56 -05:00
require(['translator', 'benchpress'], function (translator, Benchpress) {
Benchpress.render(tpl_url, data)
.then(rendered => translator.translate(rendered))
.then(function (translated) {
translated = translator.unescape(translated);
$('body').removeClass(previousBodyClass).addClass(data.bodyClass);
$('#content').html(translated);
ajaxify.end(url, tpl_url);
if (typeof callback === 'function') {
callback();
}
$('#content, #footer').removeClass('ajaxifying');
// Only executed on ajaxify. Otherwise these'd be in ajaxify.end()
updateTitle(data.title);
updateTags();
});
});
2015-07-21 11:23:16 -04:00
}
2020-09-06 22:36:09 -04:00
function updateTitle(title) {
if (!title) {
return;
}
require(['translator'], function (translator) {
title = config.titleLayout.replace(/&#123;/g, '{').replace(/&#125;/g, '}')
.replace('{pageTitle}', function () { return title; })
.replace('{browserTitle}', function () { return config.browserTitle; });
// Allow translation strings in title on ajaxify (#5927)
title = translator.unescape(title);
const data = { title: title };
hooks.fire('action:ajaxify.updateTitle', data);
translator.translate(data.title, function (translated) {
2020-09-06 22:36:09 -04:00
window.document.title = $('<div></div>').html(translated).text();
});
});
}
function updateTags() {
const metaWhitelist = ['title', 'description', /og:.+/, /article:.+/, 'robots'].map(function (val) {
2020-09-06 22:36:09 -04:00
return new RegExp(val);
});
const linkWhitelist = ['canonical', 'alternate', 'up'];
2020-09-06 22:36:09 -04:00
// Delete the old meta tags
Array.prototype.slice
.call(document.querySelectorAll('head meta'))
.filter(function (el) {
const name = el.getAttribute('property') || el.getAttribute('name');
2020-09-06 22:36:09 -04:00
return metaWhitelist.some(function (exp) {
return !!exp.test(name);
});
})
.forEach(function (el) {
document.head.removeChild(el);
});
require(['translator'], function (translator) {
// Add new meta tags
ajaxify.data._header.tags.meta
.filter(function (tagObj) {
const name = tagObj.name || tagObj.property;
return metaWhitelist.some(function (exp) {
return !!exp.test(name);
});
}).forEach(async function (tagObj) {
if (tagObj.content) {
tagObj.content = await translator.translate(tagObj.content);
}
const metaEl = document.createElement('meta');
Object.keys(tagObj).forEach(function (prop) {
metaEl.setAttribute(prop, tagObj[prop]);
});
document.head.appendChild(metaEl);
2020-09-06 22:36:09 -04:00
});
});
2020-09-06 22:36:09 -04:00
// Delete the old link tags
Array.prototype.slice
.call(document.querySelectorAll('head link'))
.filter(function (el) {
const name = el.getAttribute('rel');
2020-09-06 22:36:09 -04:00
return linkWhitelist.some(function (item) {
return item === name;
});
})
.forEach(function (el) {
document.head.removeChild(el);
});
// Add new link tags
ajaxify.data._header.tags.link
.filter(function (tagObj) {
return linkWhitelist.some(function (item) {
return item === tagObj.rel;
});
})
.forEach(function (tagObj) {
const linkEl = document.createElement('link');
2020-09-06 22:36:09 -04:00
Object.keys(tagObj).forEach(function (prop) {
linkEl.setAttribute(prop, tagObj[prop]);
});
document.head.appendChild(linkEl);
});
}
ajaxify.end = function (url, tpl_url) {
2020-10-18 01:33:03 -04:00
// Scroll back to top of page
if (!ajaxify.isCold()) {
window.scrollTo(0, 0);
}
ajaxify.loadScript(tpl_url, function done() {
2021-04-08 12:28:34 -04:00
hooks.fire('action:ajaxify.end', { url: url, tpl_url: tpl_url, title: ajaxify.data.title });
hooks.logs.flush();
});
ajaxify.widgets.render(tpl_url);
2015-07-21 11:23:16 -04:00
hooks.fire('action:ajaxify.contentLoaded', { url: url, tpl: tpl_url });
2015-07-21 11:23:16 -04:00
app.processPage();
};
ajaxify.parseData = function () {
const dataEl = $('#ajaxify-data');
2016-08-26 16:39:03 +03:00
if (dataEl.length) {
ajaxify.data = JSON.parse(dataEl.text());
dataEl.remove();
}
};
ajaxify.removeRelativePath = function (url) {
2018-06-02 15:56:23 -04:00
if (url.startsWith(config.relative_path.slice(1))) {
url = url.slice(config.relative_path.length);
2015-07-21 11:23:16 -04:00
}
return url;
};
ajaxify.refresh = function (callback) {
2016-03-24 13:21:05 +02:00
ajaxify.go(ajaxify.currentPage + window.location.search + window.location.hash, callback, true);
2015-07-21 11:23:16 -04:00
};
ajaxify.loadScript = function (tpl_url, callback) {
let location = !app.inAdmin ? 'forum/' : '';
if (tpl_url.startsWith('admin')) {
location = '';
}
2021-04-08 12:28:34 -04:00
const data = {
tpl_url: tpl_url,
scripts: [location + tpl_url],
2021-04-08 12:28:34 -04:00
};
2017-02-09 15:50:05 -07:00
2021-04-08 12:28:34 -04:00
// Hint: useful if you want to load a module on a specific page (append module name to `scripts`)
hooks.fire('action:script.load', data);
hooks.fire('filter:script.load', data).then((data) => {
// Require and parse modules
let outstanding = data.scripts.length;
2021-04-08 12:28:34 -04:00
const scripts = data.scripts.map(function (script) {
2021-04-08 12:28:34 -04:00
if (typeof script === 'function') {
return function (next) {
script();
next();
};
}
if (typeof script === 'string') {
2022-02-14 21:35:33 -05:00
return async function (next) {
const module = await app.require(script);
2022-02-14 21:35:33 -05:00
// Hint: useful if you want to override a loaded library (e.g. replace core client-side logic),
// or call a method other than .init()
hooks.fire('static:script.init', { tpl_url, name: script, module }).then(() => {
if (module && module.init) {
module.init();
}
2021-04-08 12:28:34 -04:00
next();
});
};
}
return null;
}).filter(Boolean);
if (scripts.length) {
scripts.forEach(function (fn) {
fn(function () {
outstanding -= 1;
if (outstanding === 0) {
callback();
}
});
});
} else {
callback();
}
2015-07-21 11:23:16 -04:00
});
};
ajaxify.loadData = function (url, callback) {
2015-07-21 11:23:16 -04:00
url = ajaxify.removeRelativePath(url);
hooks.fire('action:ajaxify.loadingData', { url: url });
2015-07-21 11:23:16 -04:00
apiXHR = $.ajax({
2018-06-02 15:56:23 -04:00
url: config.relative_path + '/api/' + url,
2015-07-21 11:23:16 -04:00
cache: false,
2016-10-25 16:52:03 -04:00
headers: {
2017-02-17 19:31:21 -07:00
'X-Return-To': app.previousUrl,
2016-10-25 16:52:03 -04:00
},
2017-06-30 23:38:31 -06:00
success: function (data, textStatus, xhr) {
2015-07-21 11:23:16 -04:00
if (!data) {
return;
}
2015-08-27 19:22:51 -04:00
2017-06-30 23:38:31 -06:00
if (xhr.getResponseHeader('X-Redirect')) {
return callback({
data: {
status: 302,
responseJSON: data,
},
textStatus: 'error',
});
}
2015-07-21 11:23:16 -04:00
ajaxify.data = data;
2015-08-27 19:22:51 -04:00
data.config = config;
hooks.fire('action:ajaxify.dataLoaded', { url: url, data: data });
2015-07-21 11:23:16 -04:00
2015-10-15 13:00:32 -04:00
callback(null, data);
2015-07-21 11:23:16 -04:00
},
error: function (data, textStatus) {
2015-07-21 11:23:16 -04:00
if (data.status === 0 && textStatus === 'error') {
data.status = 500;
2018-05-29 10:27:56 -04:00
data.responseJSON = data.responseJSON || {};
data.responseJSON.error = '[[error:no-connection]]';
2015-07-21 11:23:16 -04:00
}
callback({
data: data,
2017-02-17 19:31:21 -07:00
textStatus: textStatus,
2015-07-21 11:23:16 -04:00
});
2017-02-17 19:31:21 -07:00
},
2015-07-21 11:23:16 -04:00
});
};
ajaxify.loadTemplate = function (template, callback) {
2022-02-14 21:35:33 -05:00
$.ajax({
2022-02-15 20:54:08 -05:00
url: `${config.asset_base_url}/templates/${template}.js`,
cache: false,
2022-02-14 21:35:33 -05:00
dataType: 'text',
success: function (script) {
// eslint-disable-next-line no-new-func
const renderFunction = new Function('module', script);
const moduleObj = { exports: {} };
renderFunction(moduleObj);
callback(moduleObj.exports);
2022-02-14 21:35:33 -05:00
},
}).fail(function () {
console.error('Unable to load template: ' + template);
2022-02-14 21:35:33 -05:00
callback(new Error('[[error:unable-to-load-template]]'));
});
2015-07-21 11:23:16 -04:00
};
require(['translator', 'benchpress'], function (translator, Benchpress) {
translator.translate('[[error:no-connection]]');
translator.translate('[[error:socket-reconnect-failed]]');
translator.translate(`[[global:reconnecting-message, ${config.siteTitle}]]`);
Benchpress.registerLoader(ajaxify.loadTemplate);
2020-09-06 21:55:31 -04:00
Benchpress.setGlobal('config', config);
Benchpress.render('500', {}); // loads and caches the 500.tpl
});
}());
$(document).ready(function () {
$(window).on('popstate', function (ev) {
ev = ev.originalEvent;
if (ev !== null && ev.state) {
if (ev.state.url === null && ev.state.returnPath !== undefined) {
window.history.replaceState({
url: ev.state.returnPath,
}, ev.state.returnPath, config.relative_path + '/' + ev.state.returnPath);
} else if (ev.state.url !== undefined) {
ajaxify.go(ev.state.url, function () {
hooks.fire('action:popstate', { url: ev.state.url });
}, true);
}
}
});
2015-07-21 11:23:16 -04:00
function ajaxifyAnchors() {
function hrefEmpty(href) {
2021-02-03 23:52:14 -07:00
// eslint-disable-next-line no-script-url
2015-07-21 11:23:16 -04:00
return href === undefined || href === '' || href === 'javascript:;';
}
const location = document.location || window.location;
const rootUrl = location.protocol + '//' + (location.hostname || location.host) + (location.port ? ':' + location.port : '');
const contentEl = document.getElementById('content');
2016-09-02 14:16:46 -04:00
2015-07-21 11:23:16 -04:00
// Enhancing all anchors to ajaxify...
$(document.body).on('click', 'a', function (e) {
const _self = this;
2017-02-18 18:55:33 -07:00
if (this.target !== '' || (this.protocol !== 'http:' && this.protocol !== 'https:')) {
return;
}
const $this = $(this);
const href = $this.attr('href');
const internalLink = utils.isInternalURI(this, window.location, config.relative_path);
2017-02-18 18:55:33 -07:00
const rootAndPath = new RegExp(`^${rootUrl}${config.relative_path}/?`);
const process = function () {
2016-07-28 11:51:06 -04:00
if (!e.ctrlKey && !e.shiftKey && !e.metaKey && e.which === 1) {
if (internalLink) {
const pathname = this.href.replace(rootAndPath, '');
2016-07-28 11:51:06 -04:00
// Special handling for urls with hashes
if (window.location.pathname === this.pathname && this.hash.length) {
window.location.hash = this.hash;
2017-02-18 14:32:35 -07:00
} else if (ajaxify.go(pathname)) {
e.preventDefault();
2016-07-28 11:51:06 -04:00
}
2018-06-02 15:56:23 -04:00
} else if (window.location.pathname !== config.relative_path + '/outgoing') {
2016-09-02 14:16:46 -04:00
if (config.openOutgoingLinksInNewTab && $.contains(contentEl, this)) {
const externalTab = window.open();
externalTab.opener = null;
externalTab.location = this.href;
2016-07-28 11:51:06 -04:00
e.preventDefault();
} else if (config.useOutgoingLinksPage) {
const safeUrls = config.outgoingLinksWhitelist.trim().split(/[\s,]+/g).filter(Boolean);
const href = this.href;
2017-11-02 13:35:49 -04:00
if (!safeUrls.length || !safeUrls.some(function (url) { return href.indexOf(url) !== -1; })) {
2017-03-10 14:03:07 -05:00
ajaxify.go('outgoing?url=' + encodeURIComponent(href));
e.preventDefault();
}
2016-07-28 11:51:06 -04:00
}
}
}
};
2020-09-17 23:11:04 -04:00
if ($this.attr('data-ajaxify') === 'false') {
if (!internalLink) {
return;
}
return e.preventDefault();
}
2016-07-28 11:51:06 -04:00
// Default behaviour for rss feeds
2020-09-17 23:11:04 -04:00
if (internalLink && href && href.endsWith('.rss')) {
return;
}
2019-07-12 14:48:30 -04:00
// Default behaviour for sitemap
2020-09-17 23:11:04 -04:00
if (internalLink && href && String(_self.pathname).startsWith(config.relative_path + '/sitemap') && href.endsWith('.xml')) {
2019-07-12 14:48:30 -04:00
return;
}
2018-04-19 14:24:01 -04:00
// Default behaviour for uploads and direct links to API urls
if (internalLink && ['/uploads', '/assets/uploads/', '/api/'].some(function (prefix) {
2018-04-19 14:24:01 -04:00
return String(_self.pathname).startsWith(config.relative_path + prefix);
})) {
return;
}
2021-02-03 23:52:14 -07:00
// eslint-disable-next-line no-script-url
2021-11-18 16:42:18 -05:00
if (hrefEmpty(this.href) || this.protocol === 'javascript:' || href === '#' || href === '') {
2015-07-21 11:23:16 -04:00
return e.preventDefault();
}
2016-07-28 11:51:06 -04:00
if (app.flags && app.flags.hasOwnProperty('_unsaved') && app.flags._unsaved === true) {
if (e.ctrlKey) {
return;
}
require(['bootbox'], function (bootbox) {
bootbox.confirm('[[global:unsaved-changes]]', function (navigate) {
if (navigate) {
app.flags._unsaved = false;
process.call(_self);
}
});
2016-07-28 11:51:06 -04:00
});
return e.preventDefault();
2015-07-21 11:23:16 -04:00
}
2016-07-28 11:51:06 -04:00
process.call(_self);
2015-07-21 11:23:16 -04:00
});
}
if (window.history && window.history.pushState) {
// Progressive Enhancement, ajaxify available only to modern browsers
ajaxifyAnchors();
}
2017-02-18 02:30:48 -07:00
});