mirror of
https://github.com/NodeBB/NodeBB.git
synced 2025-11-07 06:25:50 +01:00
Webpack5 (#10311)
* feat: webpack 5 part 1 * fix: gruntfile fixes * fix: fix taskbar warning add app.importScript copy public/src/modules to build folder * refactor: remove commented old code * feat: reenable admin * fix: acp settings pages, fix sortable on manage categories embedded require in html not allowed * fix: bundle serialize/deserizeli so plugins dont break * test: fixe util tests * test: fix require path * test: more test fixes * test: require correct utils module * test: require correct utils * test: log stack * test: fix db require blowing up tests * test: move and disable bundle test * refactor: add aliases * test: disable testing route * fix: move webpack modules necessary for build, into `dependencies` * test: fix one more test remove 500-embed.tpl * fix: restore use of assets/nodebb.min.js, at least for now * fix: remove unnecessary line break * fix: point to proper ACP bundle * test: maybe fix build test * test: composer * refactor: dont need dist * refactor: more cleanup use everything from build/public folder * get rid of conditional import in app.js * fix: ace * refactor: cropper alias * test: lint and test fixes * lint: fix * refactor: rename function to app.require * refactor: go back to using app.require * chore: use github branch * chore: use webpack branch * feat: webpack webinstaller * feat: add chunkFile name with contenthash * refactor: move hooks to top * refactor: get rid of template500Function * fix(deps): use webpack5 branch of 2factor plugin * chore: tagging v2.0.0-beta.0 pre-release version 💥 :shipit: 🎉 🚀 * refactor: disable cache on templates loadTemplate is called once by benchpress and the result is cache internally * refactor: add server side helpers.js * feat: deprecate /plugins shorthand route, closes #10343 * refactor: use build/public for webpack * test: fix filename * fix: more specific selector * lint: ignore * refactor: fix comments * test: add debug for random failing test * refactor: cleanup remove test page, remove dupe functions in utils.common * lint: use relative path for now * chore: bump prerelease version * feat: add translateKeys * fix: optional params * fix: get rid of extra timeago files * refactor: cleanup, require timeago locale earlier remove translator.prepareDOM, it is in header.tpl html tag * refactor: privileges system to use a Map in the backend instead of separate objects for keys and labels (#10378) * refactor: privileges system to use a Map in the backend instead of separate objects for keys and labels - Existing hooks are preserved (to be deprecated at a later date, possibly) - New init hooks are called on NodeBB start, and provide a one-stop shop to add new privileges, instead of having to add to four different hooks * docs: fix typo in comment * test: spec changes * refactor: privileges system to use a Map in the backend instead of separate objects for keys and labels (#10378) * refactor: privileges system to use a Map in the backend instead of separate objects for keys and labels - Existing hooks are preserved (to be deprecated at a later date, possibly) - New init hooks are called on NodeBB start, and provide a one-stop shop to add new privileges, instead of having to add to four different hooks * docs: fix typo in comment * test: spec changes * feat: allow app.require('bootbox'/'benchpressjs') * refactor: require server side utils * test: jquery ready * change istaller to use build/public * test: use document.addEventListener * refactor: closes #10301 * refactor: generateTopicClass * fix: column counts for other privileges * fix: #10443, regression where sorted-list items did not render into the DOM in the predicted order [breaking] * fix: typo in hook name * refactor: introduce a generic autocomplete.init() method that can be called to add nodebb-style autocompletion but using different data sources (e.g. not user/groups/tags) * fix: crash if `delay` not passed in (as it cannot be destructured) * refactor: replace substr * feat: set --panel-offset style in html element based on stored value in localStorage * refactor: addDropupHandler() logic to be less naive - Take into account height of the menu - Don't apply dropUp logic if there's nothing in the dropdown - Remove 'hidden' class (added by default in Persona for post tools) when menu items are added closes #10423 * refactor: simplify utils.params [breaking] Retrospective analysis of the usage of this method suggests that the options passed in are superfluous, and that only `url` is required. Using a browser built-in makes more sense to accomplish what this method sets out to do. * feat: add support for returning full URLSearchParams for utils.params * fix: utils.params() fallback handling * fix: default empty obj for params() * fix: remove \'loggedin\' and \'register\' qs parameters once they have been used, delay invocation of messages until ajaxify.end * fix: utils.params() not allowing relative paths to be passed in * refactor(DRY): new assertPasswordValidity utils method * fix: incorrect error message returned on insufficient privilege on flag edit * fix: read/update/delete access to flags API should be limited for moderators to only post flags in categories they moderate - added failing tests and patched up middleware.assert.flags to fix * refactor: flag api v3 tests to create new post and flags on every round * fix: missing error:no-flag language key * refactor: flags.canView to check flag existence, simplify middleware.assert.flag * feat: flag deletion API endpoint, #10426 * feat: UI for flag deletion, closes #10426 * chore: update plugin versions * chore: up emoji * chore: update markdown * chore: up emoji-android * fix: regression caused by utils.params() refactor, supports arrays and pipes all values through utils.toType, adjusts tests to type check Co-authored-by: Julian Lam <julian@nodebb.org>
This commit is contained in:
committed by
GitHub
parent
d6843294fc
commit
d20b07cfea
347
public/src/modules/helpers.common.js
Normal file
347
public/src/modules/helpers.common.js
Normal file
@@ -0,0 +1,347 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = function (utils, Benchpress, relative_path) {
|
||||
Benchpress.setGlobal('true', true);
|
||||
Benchpress.setGlobal('false', false);
|
||||
|
||||
const helpers = {
|
||||
displayMenuItem,
|
||||
buildMetaTag,
|
||||
buildLinkTag,
|
||||
stringify,
|
||||
escape,
|
||||
stripTags,
|
||||
generateCategoryBackground,
|
||||
generateChildrenCategories,
|
||||
generateTopicClass,
|
||||
membershipBtn,
|
||||
spawnPrivilegeStates,
|
||||
localeToHTML,
|
||||
renderTopicImage,
|
||||
renderTopicEvents,
|
||||
renderEvents,
|
||||
renderDigestAvatar,
|
||||
userAgentIcons,
|
||||
buildAvatar,
|
||||
register,
|
||||
__escape: identity,
|
||||
};
|
||||
|
||||
function identity(str) {
|
||||
return str;
|
||||
}
|
||||
|
||||
function displayMenuItem(data, index) {
|
||||
const item = data.navigation[index];
|
||||
if (!item) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (item.route.match('/users') && data.user && !data.user.privileges['view:users']) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (item.route.match('/tags') && data.user && !data.user.privileges['view:tags']) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (item.route.match('/groups') && data.user && !data.user.privileges['view:groups']) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function buildMetaTag(tag) {
|
||||
const name = tag.name ? 'name="' + tag.name + '" ' : '';
|
||||
const property = tag.property ? 'property="' + tag.property + '" ' : '';
|
||||
const content = tag.content ? 'content="' + tag.content.replace(/\n/g, ' ') + '" ' : '';
|
||||
|
||||
return '<meta ' + name + property + content + '/>\n\t';
|
||||
}
|
||||
|
||||
function buildLinkTag(tag) {
|
||||
const attributes = ['link', 'rel', 'as', 'type', 'href', 'sizes', 'title', 'crossorigin'];
|
||||
const [link, rel, as, type, href, sizes, title, crossorigin] = attributes.map(attr => (tag[attr] ? `${attr}="${tag[attr]}" ` : ''));
|
||||
|
||||
return '<link ' + link + rel + as + type + sizes + title + href + crossorigin + '/>\n\t';
|
||||
}
|
||||
|
||||
function stringify(obj) {
|
||||
// Turns the incoming object into a JSON string
|
||||
return JSON.stringify(obj).replace(/&/gm, '&').replace(/</gm, '<').replace(/>/gm, '>')
|
||||
.replace(/"/g, '"');
|
||||
}
|
||||
|
||||
function escape(str) {
|
||||
return utils.escapeHTML(str);
|
||||
}
|
||||
|
||||
function stripTags(str) {
|
||||
return utils.stripHTMLTags(str);
|
||||
}
|
||||
|
||||
function generateCategoryBackground(category) {
|
||||
if (!category) {
|
||||
return '';
|
||||
}
|
||||
const style = [];
|
||||
|
||||
if (category.bgColor) {
|
||||
style.push('background-color: ' + category.bgColor);
|
||||
}
|
||||
|
||||
if (category.color) {
|
||||
style.push('color: ' + category.color);
|
||||
}
|
||||
|
||||
if (category.backgroundImage) {
|
||||
style.push('background-image: url(' + category.backgroundImage + ')');
|
||||
if (category.imageClass) {
|
||||
style.push('background-size: ' + category.imageClass);
|
||||
}
|
||||
}
|
||||
|
||||
return style.join('; ') + ';';
|
||||
}
|
||||
|
||||
function generateChildrenCategories(category) {
|
||||
let html = '';
|
||||
if (!category || !category.children || !category.children.length) {
|
||||
return html;
|
||||
}
|
||||
category.children.forEach(function (child) {
|
||||
if (child && !child.isSection) {
|
||||
const link = child.link ? child.link : (relative_path + '/category/' + child.slug);
|
||||
html += '<span class="category-children-item pull-left">' +
|
||||
'<div role="presentation" class="icon pull-left" style="' + generateCategoryBackground(child) + '">' +
|
||||
'<i class="fa fa-fw ' + child.icon + '"></i>' +
|
||||
'</div>' +
|
||||
'<a href="' + link + '"><small>' + child.name + '</small></a></span>';
|
||||
}
|
||||
});
|
||||
html = html ? ('<span class="category-children">' + html + '</span>') : html;
|
||||
return html;
|
||||
}
|
||||
|
||||
function generateTopicClass(topic) {
|
||||
const fields = ['locked', 'pinned', 'deleted', 'unread', 'scheduled'];
|
||||
return fields.filter(field => !!topic[field]).join(' ');
|
||||
}
|
||||
|
||||
// Groups helpers
|
||||
function membershipBtn(groupObj) {
|
||||
if (groupObj.isMember && groupObj.name !== 'administrators') {
|
||||
return '<button class="btn btn-danger" data-action="leave" data-group="' + groupObj.displayName + '"' + (groupObj.disableLeave ? ' disabled' : '') + '><i class="fa fa-times"></i> [[groups:membership.leave-group]]</button>';
|
||||
}
|
||||
|
||||
if (groupObj.isPending && groupObj.name !== 'administrators') {
|
||||
return '<button class="btn btn-warning disabled"><i class="fa fa-clock-o"></i> [[groups:membership.invitation-pending]]</button>';
|
||||
} else if (groupObj.isInvited) {
|
||||
return '<button class="btn btn-link" data-action="rejectInvite" data-group="' + groupObj.displayName + '">[[groups:membership.reject]]</button><button class="btn btn-success" data-action="acceptInvite" data-group="' + groupObj.name + '"><i class="fa fa-plus"></i> [[groups:membership.accept-invitation]]</button>';
|
||||
} else if (!groupObj.disableJoinRequests && groupObj.name !== 'administrators') {
|
||||
return '<button class="btn btn-success" data-action="join" data-group="' + groupObj.displayName + '"><i class="fa fa-plus"></i> [[groups:membership.join-group]]</button>';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function spawnPrivilegeStates(member, privileges) {
|
||||
const states = [];
|
||||
for (const priv in privileges) {
|
||||
if (privileges.hasOwnProperty(priv)) {
|
||||
states.push({
|
||||
name: priv,
|
||||
state: privileges[priv],
|
||||
});
|
||||
}
|
||||
}
|
||||
return states.map(function (priv) {
|
||||
const guestDisabled = ['groups:moderate', 'groups:posts:upvote', 'groups:posts:downvote', 'groups:local:login', 'groups:group:create'];
|
||||
const spidersEnabled = ['groups:find', 'groups:read', 'groups:topics:read', 'groups:view:users', 'groups:view:tags', 'groups:view:groups'];
|
||||
const globalModDisabled = ['groups:moderate'];
|
||||
const disabled =
|
||||
(member === 'guests' && (guestDisabled.includes(priv.name) || priv.name.startsWith('groups:admin:'))) ||
|
||||
(member === 'spiders' && !spidersEnabled.includes(priv.name)) ||
|
||||
(member === 'Global Moderators' && globalModDisabled.includes(priv.name));
|
||||
|
||||
return '<td class="text-center" data-privilege="' + priv.name + '" data-value="' + priv.state + '"><input autocomplete="off" type="checkbox"' + (priv.state ? ' checked' : '') + (disabled ? ' disabled="disabled"' : '') + ' /></td>';
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function localeToHTML(locale, fallback) {
|
||||
locale = locale || fallback || 'en-GB';
|
||||
return locale.replace('_', '-');
|
||||
}
|
||||
|
||||
function renderTopicImage(topicObj) {
|
||||
if (topicObj.thumb) {
|
||||
return '<img src="' + topicObj.thumb + '" class="img-circle user-img" title="' + topicObj.user.username + '" />';
|
||||
}
|
||||
return '<img component="user/picture" data-uid="' + topicObj.user.uid + '" src="' + topicObj.user.picture + '" class="user-img" title="' + topicObj.user.username + '" />';
|
||||
}
|
||||
|
||||
function renderTopicEvents(index, sort) {
|
||||
if (sort === 'most_votes') {
|
||||
return '';
|
||||
}
|
||||
const start = this.posts[index].eventStart;
|
||||
const end = this.posts[index].eventEnd;
|
||||
const events = this.events.filter(event => event.timestamp >= start && event.timestamp < end);
|
||||
if (!events.length) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return renderEvents.call(this, events);
|
||||
}
|
||||
|
||||
function renderEvents(events) {
|
||||
return events.reduce((html, event) => {
|
||||
html += `<li component="topic/event" class="timeline-event" data-topic-event-id="${event.id}">
|
||||
<div class="timeline-badge">
|
||||
<i class="fa ${event.icon || 'fa-circle'}"></i>
|
||||
</div>
|
||||
<span class="timeline-text">
|
||||
${event.href ? `<a href="${relative_path}${event.href}">${event.text}</a>` : event.text}
|
||||
</span>
|
||||
`;
|
||||
|
||||
if (event.user) {
|
||||
if (!event.user.system) {
|
||||
html += `<span><a href="${relative_path}/user/${event.user.userslug}">${buildAvatar(event.user, 'xs', true)} ${event.user.username}</a></span> `;
|
||||
} else {
|
||||
html += `<span class="timeline-text">[[global:system-user]]</span> `;
|
||||
}
|
||||
}
|
||||
|
||||
html += `<span class="timeago timeline-text" title="${event.timestampISO}"></span>`;
|
||||
|
||||
if (this.privileges.isAdminOrMod) {
|
||||
html += ` <span component="topic/event/delete" data-topic-event-id="${event.id}" class="timeline-text pointer" title="[[topic:delete-event]]"><i class="fa fa-trash"></i></span>`;
|
||||
}
|
||||
|
||||
return html;
|
||||
}, '');
|
||||
}
|
||||
|
||||
function renderDigestAvatar(block) {
|
||||
if (block.teaser) {
|
||||
if (block.teaser.user.picture) {
|
||||
return '<img style="vertical-align: middle; width: 32px; height: 32px; border-radius: 50%;" src="' + block.teaser.user.picture + '" title="' + block.teaser.user.username + '" />';
|
||||
}
|
||||
return '<div style="vertical-align: middle; width: 32px; height: 32px; line-height: 32px; font-size: 16px; background-color: ' + block.teaser.user['icon:bgColor'] + '; color: white; text-align: center; display: inline-block; border-radius: 50%;">' + block.teaser.user['icon:text'] + '</div>';
|
||||
}
|
||||
if (block.user.picture) {
|
||||
return '<img style="vertical-align: middle; width: 32px; height: 32px; border-radius: 50%;" src="' + block.user.picture + '" title="' + block.user.username + '" />';
|
||||
}
|
||||
return '<div style="vertical-align: middle; width: 32px; height: 32px; line-height: 32px; font-size: 16px; background-color: ' + block.user['icon:bgColor'] + '; color: white; text-align: center; display: inline-block; border-radius: 50%;">' + block.user['icon:text'] + '</div>';
|
||||
}
|
||||
|
||||
function userAgentIcons(data) {
|
||||
let icons = '';
|
||||
|
||||
switch (data.platform) {
|
||||
case 'Linux':
|
||||
icons += '<i class="fa fa-fw fa-linux"></i>';
|
||||
break;
|
||||
case 'Microsoft Windows':
|
||||
icons += '<i class="fa fa-fw fa-windows"></i>';
|
||||
break;
|
||||
case 'Apple Mac':
|
||||
icons += '<i class="fa fa-fw fa-apple"></i>';
|
||||
break;
|
||||
case 'Android':
|
||||
icons += '<i class="fa fa-fw fa-android"></i>';
|
||||
break;
|
||||
case 'iPad':
|
||||
icons += '<i class="fa fa-fw fa-tablet"></i>';
|
||||
break;
|
||||
case 'iPod': // intentional fall-through
|
||||
case 'iPhone':
|
||||
icons += '<i class="fa fa-fw fa-mobile"></i>';
|
||||
break;
|
||||
default:
|
||||
icons += '<i class="fa fa-fw fa-question-circle"></i>';
|
||||
break;
|
||||
}
|
||||
|
||||
switch (data.browser) {
|
||||
case 'Chrome':
|
||||
icons += '<i class="fa fa-fw fa-chrome"></i>';
|
||||
break;
|
||||
case 'Firefox':
|
||||
icons += '<i class="fa fa-fw fa-firefox"></i>';
|
||||
break;
|
||||
case 'Safari':
|
||||
icons += '<i class="fa fa-fw fa-safari"></i>';
|
||||
break;
|
||||
case 'IE':
|
||||
icons += '<i class="fa fa-fw fa-internet-explorer"></i>';
|
||||
break;
|
||||
case 'Edge':
|
||||
icons += '<i class="fa fa-fw fa-edge"></i>';
|
||||
break;
|
||||
default:
|
||||
icons += '<i class="fa fa-fw fa-question-circle"></i>';
|
||||
break;
|
||||
}
|
||||
|
||||
return icons;
|
||||
}
|
||||
|
||||
function buildAvatar(userObj, size, rounded, classNames, component) {
|
||||
/**
|
||||
* userObj requires:
|
||||
* - uid, picture, icon:bgColor, icon:text (getUserField w/ "picture" should return all 4), username
|
||||
* size: one of "xs", "sm", "md", "lg", or "xl" (required), or an integer
|
||||
* rounded: true or false (optional, default false)
|
||||
* classNames: additional class names to prepend (optional, default none)
|
||||
* component: overrides the default component (optional, default none)
|
||||
*/
|
||||
|
||||
// Try to use root context if passed-in userObj is undefined
|
||||
if (!userObj) {
|
||||
userObj = this;
|
||||
}
|
||||
|
||||
const attributes = [
|
||||
'alt="' + userObj.username + '"',
|
||||
'title="' + userObj.username + '"',
|
||||
'data-uid="' + userObj.uid + '"',
|
||||
'loading="lazy"',
|
||||
];
|
||||
const styles = [];
|
||||
classNames = classNames || '';
|
||||
|
||||
// Validate sizes, handle integers, otherwise fall back to `avatar-sm`
|
||||
if (['xs', 'sm', 'sm2x', 'md', 'lg', 'xl'].includes(size)) {
|
||||
classNames += ' avatar-' + size;
|
||||
} else if (!isNaN(parseInt(size, 10))) {
|
||||
styles.push('width: ' + size + 'px;', 'height: ' + size + 'px;', 'line-height: ' + size + 'px;', 'font-size: ' + (parseInt(size, 10) / 16) + 'rem;');
|
||||
} else {
|
||||
classNames += ' avatar-sm';
|
||||
}
|
||||
attributes.unshift('class="avatar ' + classNames + (rounded ? ' avatar-rounded' : '') + '"');
|
||||
|
||||
// Component override
|
||||
if (component) {
|
||||
attributes.push('component="' + component + '"');
|
||||
} else {
|
||||
attributes.push('component="avatar/' + (userObj.picture ? 'picture' : 'icon') + '"');
|
||||
}
|
||||
|
||||
if (userObj.picture) {
|
||||
return '<img ' + attributes.join(' ') + ' src="' + userObj.picture + '" style="' + styles.join(' ') + '" />';
|
||||
}
|
||||
|
||||
styles.push('background-color: ' + userObj['icon:bgColor'] + ';');
|
||||
return '<span ' + attributes.join(' ') + ' style="' + styles.join(' ') + '">' + userObj['icon:text'] + '</span>';
|
||||
}
|
||||
|
||||
function register() {
|
||||
Object.keys(helpers).forEach(function (helperName) {
|
||||
Benchpress.registerHelper(helperName, helpers[helperName]);
|
||||
});
|
||||
}
|
||||
|
||||
return helpers;
|
||||
};
|
||||
Reference in New Issue
Block a user