Files
wekan/models/lib/boardViewSettings.js
T
Lauri Ojansivu b7589737f5 File docs/Features the way the WeKan menus are.
A feature's guide now sits under the menu it is used from, read from the
templates rather than from where somebody once put it: Header-Bar,
All-Boards, Pages, Board-Header (search and every Board View), Board-Sidebar
(Board Settings, Filter, Members, Labels, Archive), Rules, Swimlanes, Lists,
Cards, Member-Settings, Admin-Panel and Login-Page. Topics used from several
menus (editor, history, theme, translations, email, troubleshooting) are in
General.

- Each area has a README mapping its menu entries to their guides and to the
  template or server module that implements them. Board-Header/README.md
  lists all 40 Board View entries with the template boardBody.jade renders;
  five views (Table, Calendar Mode, Time, Timeline, Map) have no guide of
  their own yet and say so.
- Board-View.md listed 25 views while BOARD_VIEWS has 40; it now lists all
  of them with their English labels.
- Pages keep their file names. Where a released changelog links an old path,
  a "# Moved" page stays there and points to the new one; test-menu.sh skips
  folders holding only those.
- Undo was filed under Login; it is General/Undo now.
- Every link in docs, code comments, scripts and tests follows the move;
  docsLinksResolve checks them all.

Tests that read a doc follow it to its new place. boardViewSettings now fails
when Board-View.md or Board-Header/README.md differs from BOARD_VIEWS, or
names a template boardBody.jade does not render.

Thanks to xet7 !
2026-10-16 23:45:35 +03:00

495 lines
23 KiB
JavaScript

'use strict';
// Board Settings / Board View: which entries of the Board View menu a board
// offers, and which one it opens in, separately for a PUBLIC and a PRIVATE
// board (design: docs/Features/Board-Sidebar/Board-Settings/Board-View.md).
//
// Pure CommonJS, no Meteor: the client (the popup, the view menu and
// Utils.boardView), the server (the Board instance setters) and the
// tests/*.test.cjs guards all load this ONE table and these decisions, so
// the menu, the popup and the fallback can not drift apart.
//
// Stored on the board as
// boardViewSettings: { '<view>': { showOnPublic, showOnPrivate } }
// defaultPublicBoardView: '<view>'
// defaultPrivateBoardView: '<view>'
// A missing entry or a missing side means SHOWN, and a missing default is
// Swimlanes - a board that never opened the popup behaves as it always did.
// The Board View menu, top to bottom - the same order and the same label
// keys as client/components/boards/boardHeader.jade (boardChangeViewPopup).
// tests/boardViewSettings.test.cjs fails when the two differ.
const BOARD_VIEWS = [
{ view: 'board-view-swimlanes', labelKey: 'swimlanes', icon: 'fa-th-large' },
{ view: 'board-view-lists', labelKey: 'board-view-lists', icon: 'fa-trello' },
{ view: 'board-view-table', labelKey: 'board-view-table', icon: 'fa-table' },
{ view: 'board-view-cal', labelKey: 'board-view-cal', icon: 'fa-calendar' },
// #3194: Trello's calendar - a card on its due day, with its labels.
{ view: 'board-view-calendar-mode', labelKey: 'board-view-calendar-mode', icon: 'fa-calendar-check-o' },
{ view: 'board-view-multiboard-cal', labelKey: 'board-view-multiboard-cal', icon: 'fa-calendar-plus-o' },
{ view: 'board-view-time', labelKey: 'board-view-time', icon: 'fa-clock-o' },
{ view: 'board-view-timeline', labelKey: 'board-view-timeline', icon: 'fa-history' },
{ view: 'board-view-stats', labelKey: 'board-view-stats', icon: 'fa-pie-chart' },
{ view: 'board-view-group-by-assignee', labelKey: 'board-view-group-by-assignee', icon: 'fa-users' },
{ view: 'board-view-gantt', labelKey: 'board-view-gantt', icon: 'fa-bar-chart' },
{ view: 'board-view-gantt-frappe', labelKey: 'board-view-gantt-frappe', icon: 'fa-tasks' },
{ view: 'board-view-gantt-dhtmlx', labelKey: 'board-view-gantt-dhtmlx', icon: 'fa-list-alt' },
{ view: 'board-view-product-backlog', labelKey: 'board-view-product-backlog', icon: 'fa-list-ol' },
{ view: 'board-view-sprints', labelKey: 'board-view-sprints', icon: 'fa-repeat' },
{ view: 'board-view-sprint-report', labelKey: 'board-view-sprint-report', icon: 'fa-bar-chart' },
{ view: 'board-view-velocity', labelKey: 'board-view-velocity', icon: 'fa-line-chart' },
{ view: 'board-view-roadmap', labelKey: 'board-view-roadmap', icon: 'fa-road' },
{ view: 'board-view-dashboard', labelKey: 'board-view-dashboard', icon: 'fa-tachometer' },
{ view: 'board-view-bigboard', labelKey: 'board-view-bigboard', icon: 'fa-th' },
{ view: 'board-view-burndown', labelKey: 'board-view-burndown', icon: 'fa-line-chart' },
{ view: 'board-view-burnup', labelKey: 'board-view-burnup', icon: 'fa-area-chart' },
{ view: 'board-view-cumulative-flow', labelKey: 'board-view-cumulative-flow', icon: 'fa-signal' },
{ view: 'board-view-control-chart', labelKey: 'board-view-control-chart', icon: 'fa-crosshairs' },
{ view: 'board-view-cycle-time', labelKey: 'board-view-cycle-time', icon: 'fa-refresh' },
{ view: 'board-view-flow-efficiency', labelKey: 'board-view-flow-efficiency', icon: 'fa-percent' },
{ view: 'board-view-lead-time', labelKey: 'board-view-lead-time', icon: 'fa-hourglass-half' },
{ view: 'board-view-throughput-histogram', labelKey: 'board-view-throughput-histogram', icon: 'fa-columns' },
{ view: 'board-view-wip-run', labelKey: 'board-view-wip-run', icon: 'fa-flag-checkered' },
{ view: 'board-view-pulse', labelKey: 'board-view-pulse', icon: 'fa-heartbeat' },
{ view: 'board-view-aging-wip', labelKey: 'board-view-aging-wip', icon: 'fa-hourglass-half' },
{ view: 'board-view-blocker-analysis', labelKey: 'board-view-blocker-analysis', icon: 'fa-ban' },
{ view: 'board-view-monte-carlo', labelKey: 'board-view-monte-carlo', icon: 'fa-random' },
{ view: 'board-view-process-behavior', labelKey: 'board-view-process-behavior', icon: 'fa-line-chart' },
{ view: 'board-view-size-cycle-time', labelKey: 'board-view-size-cycle-time', icon: 'fa-braille' },
// #3256: cards as markers on an uploaded image (client/components/boards/mapView.*).
{ view: 'board-view-map', labelKey: 'board-view-map', icon: 'fa-map-marker' },
// #794: the board as a Gmail-like mailbox - the email-to-card list is the
// Inbox, lists and labels are folders and labels (client/components/boards/emailView.*).
{ view: 'board-view-email', labelKey: 'board-view-email', icon: 'fa-envelope' },
// The board as a Slack / Rocket.Chat workspace: channels in a tree, the card,
// its comments as chat (client/components/boards/chatView.*).
{ view: 'board-view-chat', labelKey: 'board-view-chat', icon: 'fa-comments' },
// The board as a GitHub / Gitea issue tracker: issues, milestones, labels,
// files and the history with its undo (client/components/boards/versionControlView.*).
{ view: 'board-view-version-control', labelKey: 'board-view-version-control', icon: 'fa-code-fork' },
// #211: the same cards in several named column sets (client/components/boards/columnSetsView.*).
{ view: 'board-view-column-sets', labelKey: 'board-view-column-sets', icon: 'fa-columns' },
];
const DEFAULT_BOARD_VIEW = 'board-view-swimlanes';
const VIEW_KEYS = BOARD_VIEWS.map(v => v.view);
// The menu's DEFAULT order - what a board with no stored boardViewOrder
// renders, the popup's default row order, and where a view missing from a
// stored order is slotted in. It is the order the Board View menu had BEFORE
// views became orderable: the 25 static `li` entries of boardChangeViewPopup
// in client/components/boards/boardHeader.jade at commit 525bcab1b (the
// parent of the Board Settings / Board View feature), transcribed top to
// bottom. Written out rather than derived from BOARD_VIEWS so that
// re-sorting that table can not silently change what every board shows;
// tests/boardViewSettings.test.cjs pins this list literally.
const DEFAULT_BOARD_VIEW_ORDER = [
'board-view-swimlanes',
'board-view-lists',
'board-view-table',
'board-view-cal',
'board-view-calendar-mode',
'board-view-multiboard-cal',
'board-view-time',
'board-view-timeline',
'board-view-stats',
'board-view-group-by-assignee',
'board-view-gantt',
'board-view-gantt-frappe',
'board-view-gantt-dhtmlx',
'board-view-product-backlog',
'board-view-sprints',
'board-view-sprint-report',
'board-view-velocity',
'board-view-roadmap',
'board-view-dashboard',
'board-view-bigboard',
'board-view-burndown',
'board-view-burnup',
'board-view-cumulative-flow',
'board-view-control-chart',
'board-view-cycle-time',
'board-view-flow-efficiency',
'board-view-lead-time',
'board-view-throughput-histogram',
'board-view-wip-run',
'board-view-pulse',
'board-view-aging-wip',
'board-view-blocker-analysis',
'board-view-monte-carlo',
'board-view-process-behavior',
'board-view-size-cycle-time',
'board-view-map',
'board-view-email',
'board-view-chat',
'board-view-version-control',
'board-view-column-sets',
];
// Views added to the default order after a board could save an order of its
// own (Board Settings / Board View). A saved order that lacks only these is
// the default order of its time, not a custom one (normalizeBoardViewOrder).
const VIEWS_ADDED_LATER = ['board-view-calendar-mode', 'board-view-email', 'board-view-chat', 'board-view-version-control',
'board-view-column-sets'];
// After which entries the menu draws a separator - the same six `hr`s the
// pre-feature template had, at the same places - only in the DEFAULT order,
// where the groups (board views / calendars and time / statistics /
// grouping / the Gantts / roadmap, dashboard, bigboard / the charts) still
// mean something. A custom order has no groups and no separators.
const SEPARATOR_AFTER = [
'board-view-table',
'board-view-timeline',
'board-view-stats',
'board-view-group-by-assignee',
'board-view-gantt-dhtmlx',
'board-view-bigboard',
];
// #6736: `allowView` is the instance's own decision (Admin Panel / Settings /
// Visibility / Features, models/lib/instanceFeatures.js) - a view the instance
// disabled is not offered on any board, whatever the board says. Without it
// every view is allowed, as before.
const allowAll = () => true;
// The class the per-view click handlers in boardHeader.js listen for:
// 'board-view-gantt-frappe' -> 'js-open-gantt-frappe-view'.
function boardViewJsClass(view) {
return `js-open-${view.replace(/^board-view-/, '')}-view`;
}
function isKnownBoardView(view) {
return VIEW_KEYS.includes(view);
}
// A stored order made whole (same shape as models/lib/cardFieldOrder.js):
// unknown keys and duplicates are dropped, and every known view that is
// missing is appended in its default position, so the menu always lists
// every view exactly once, whatever an old or hand-edited document holds.
function normalizeBoardViewOrder(storedOrder) {
const seen = new Set();
const result = [];
if (Array.isArray(storedOrder)) {
storedOrder.forEach(view => {
if (typeof view === 'string' && isKnownBoardView(view) && !seen.has(view)) {
seen.add(view);
result.push(view);
}
});
}
// The default list first, then - belt and braces - any view BOARD_VIEWS
// knows that the default list does not, so a view added to the table but
// not yet to the list above still reaches the menu (at the end) instead
// of vanishing. tests/boardViewSettings.test.cjs fails when the two differ.
// A saved order that IS the default order of its time - every default view,
// in default order, missing only views added after it was saved
// (VIEWS_ADDED_LATER) - is the default order: it gets every view in its
// default place - Calendar Mode below Calendar (#3194) - and keeps the
// menu's separators. Any other order is the user's own, and a view it lacks
// goes at the end.
const olderDefault = DEFAULT_BOARD_VIEW_ORDER.filter(view => seen.has(view) || !VIEWS_ADDED_LATER.includes(view));
if (result.length && olderDefault.length === result.length && olderDefault.every((view, i) => view === result[i])) {
result.length = 0;
}
DEFAULT_BOARD_VIEW_ORDER.concat(VIEW_KEYS).forEach(view => {
if (result.includes(view)) return;
result.push(view);
});
return result;
}
// Drag and drop in Board Settings / Board View: `visibleOrder` is the rows as
// dropped - the views the popup shows, in their new order. Each takes the next
// slot that held a shown view, so a view the instance disabled (not a row)
// keeps its place. Unknown and missing views change nothing.
function reorderVisibleBoardViews(order, visibleOrder, allowView = allowAll) {
const list = normalizeBoardViewOrder(order);
const shown = list.filter(view => allowView(view));
const dropped = Array.isArray(visibleOrder) ? visibleOrder.filter(view => shown.includes(view)) : [];
if (dropped.length !== shown.length || new Set(dropped).size !== dropped.length) return list;
let next = 0;
return list.map(view => (allowView(view) ? dropped[next++] : view));
}
function isDefaultBoardViewOrder(order) {
const list = normalizeBoardViewOrder(order);
return list.every((view, i) => view === DEFAULT_BOARD_VIEW_ORDER[i]);
}
// BOARD_VIEWS in the board's order.
function orderedBoardViews(board) {
const byKey = new Map(BOARD_VIEWS.map(v => [v.view, v]));
return normalizeBoardViewOrder(board && board.boardViewOrder).map(view => byKey.get(view));
}
// Move `view` one step up or down. Returns a new, normalized array; a no-op
// (unknown view, first item up, last item down) returns the normalized
// order unchanged, so the first row's up arrow and the last row's down
// arrow do nothing.
//
// #6736: with `allowView`, the move steps over views the instance disabled
// (they are not rows of the popup), so one click passes exactly one row the
// admin can see; with no visible row to pass, nothing moves.
function moveBoardView(order, view, direction, allowView = allowAll) {
const list = normalizeBoardViewOrder(order);
const from = list.indexOf(view);
if (from === -1) return list;
const step = direction === 'up' ? -1 : 1;
let to = from + step;
while (to >= 0 && to < list.length && !allowView(list[to])) to += step;
if (to < 0 || to >= list.length) return list;
const result = list.slice();
const [moved] = result.splice(from, 1);
result.splice(to, 0, moved);
return result;
}
// 'public' or 'private'; anything else (undefined on a board doc that
// predates the field, a typo) is treated as private, the safer side.
function normalizeVisibility(visibility) {
return visibility === 'public' ? 'public' : 'private';
}
function showField(visibility) {
return normalizeVisibility(visibility) === 'public' ? 'showOnPublic' : 'showOnPrivate';
}
function defaultField(visibility) {
return normalizeVisibility(visibility) === 'public'
? 'defaultPublicBoardView'
: 'defaultPrivateBoardView';
}
// Which side's settings apply to the person looking. A PUBLIC board shows its
// public settings - Show on / Default on Public Board - to the public: a
// visitor who is not logged in, or is logged in and not a member. Its own
// members work on it, so they get the private side, the same as on a private
// board. So a public board can open read-only in, say, Version Control or
// Email for the world, and offer the world only those views, while its
// members keep every view. Without a userId (old callers) a public board is
// public to everybody, as it was before.
function boardViewAudience(board, userId) {
if (normalizeVisibility(board && board.permission) !== 'public') return 'private';
const member = !!userId && Array.isArray(board.members)
&& board.members.some(m => m && m.userId === userId && m.isActive !== false);
return member ? 'private' : 'public';
}
function isBoardViewShown(board, view, visibility) {
const settings = (board && board.boardViewSettings) || {};
const entry = settings[view];
if (!entry || typeof entry !== 'object') return true;
const value = entry[showField(visibility)];
return value !== false;
}
function defaultBoardView(board, visibility) {
const value = board && board[defaultField(visibility)];
return isKnownBoardView(value) ? value : DEFAULT_BOARD_VIEW;
}
// The views the board offers, in the board's order.
function visibleBoardViews(board, visibility, allowView = allowAll) {
return orderedBoardViews(board).filter(v => allowView(v.view) && isBoardViewShown(board, v.view, visibility));
}
// What the Board View menu renders: the visible views in the board's order,
// each with the class its click handler listens for, whether it is the one
// currently rendered, and whether a separator follows it (default order
// only). `currentView` is what Utils.boardView() returns.
function boardViewMenuEntries(board, currentView, allowView = allowAll, userId) {
const visibility = boardViewAudience(board, userId);
const defaultOrder = isDefaultBoardViewOrder(board && board.boardViewOrder);
const visible = visibleBoardViews(board, visibility, allowView);
return visible.map((v, i) => ({
view: v.view,
labelKey: v.labelKey,
icon: v.icon,
jsClass: boardViewJsClass(v.view),
isCurrent: v.view === currentView,
separatorAfter: defaultOrder && i < visible.length - 1 && SEPARATOR_AFTER.includes(v.view),
}));
}
// The view to RENDER for this board: what the user asked for when the board
// offers it, otherwise the board's default for its visibility. The default
// is always shown (the setters keep that invariant), but a document edited
// by hand could break it, so the last resort is Swimlanes regardless - a
// user is never left on a view that renders nothing.
function resolveBoardView(board, requestedView, allowView = allowAll, userId) {
if (!board) return requestedView;
const visibility = boardViewAudience(board, userId);
if (isKnownBoardView(requestedView) && allowView(requestedView) &&
isBoardViewShown(board, requestedView, visibility)) {
return requestedView;
}
const fallback = defaultBoardView(board, visibility);
if (allowView(fallback) && isBoardViewShown(board, fallback, visibility)) return fallback;
// Swimlanes is core: no instance feature can disable it.
return DEFAULT_BOARD_VIEW;
}
// $set for a "Show on Public/Private Board" click. null when the click would
// hide that side's default view: a default must stay reachable, so the
// popup ignores the click and the admin picks another default first.
function showBoardViewModifier(board, view, visibility, shown) {
if (!isKnownBoardView(view)) return null;
const on = shown !== false;
if (!on && defaultBoardView(board, visibility) === view) return null;
return { [`boardViewSettings.${view}.${showField(visibility)}`]: on };
}
// $set for a "Default on Public/Private Board" click: radio semantics - the
// one field holds the one default, so setting it un-sets the previous one -
// and the new default is shown on that side, whatever its box said before.
function defaultBoardViewModifier(board, view, visibility) {
if (!isKnownBoardView(view)) return null;
return {
[defaultField(visibility)]: view,
[`boardViewSettings.${view}.${showField(visibility)}`]: true,
};
}
// What GET /api/boards/:boardId/boardViewSettings answers, and what the PUT
// answers after it wrote: every view exactly once with both sides made
// explicit (a missing entry/side means SHOWN), the two defaults resolved
// through defaultBoardView() so an unknown or missing default reads as
// Swimlanes, and the order made whole - the same decisions the UI renders
// with, so the API never reports a state the menu would not show.
function boardViewSettingsSnapshot(board) {
const boardViewSettings = {};
VIEW_KEYS.forEach(view => {
boardViewSettings[view] = {
showOnPublic: isBoardViewShown(board, view, 'public'),
showOnPrivate: isBoardViewShown(board, view, 'private'),
};
});
return {
boardViewSettings,
defaultPublicBoardView: defaultBoardView(board, 'public'),
defaultPrivateBoardView: defaultBoardView(board, 'private'),
boardViewOrder: normalizeBoardViewOrder(board && board.boardViewOrder),
keys: VIEW_KEYS.slice(),
};
}
// Apply a dotted-key $set ({ 'boardViewSettings.x.showOnPublic': true }) to a
// plain copy of a board document, so a request that changes the default AND
// hides views is checked against the state its earlier parts produced.
function applyDotSet(doc, $set) {
Object.keys($set).forEach(key => {
const parts = key.split('.');
let node = doc;
parts.slice(0, -1).forEach(part => {
if (!node[part] || typeof node[part] !== 'object') node[part] = {};
node = node[part];
});
node[parts[parts.length - 1]] = $set[key];
});
return doc;
}
// PUT /api/boards/:boardId/boardViewSettings: the request body, any subset
// of { boardViewSettings, defaultPublicBoardView, defaultPrivateBoardView,
// boardViewOrder }, turned into ONE $set through the same pure modifiers the
// popup's clicks use, or refused with a reason. Defaults are applied before
// the show flags (a default is always shown, and the new default is the one
// that must stay shown), an unknown view key anywhere is a 400, hiding a
// side's default is a 400 (the popup silently ignores that click; an API
// caller is told), and an order is normalised after every key in it was
// checked. Returns { $set } - empty when nothing recognised was sent - or
// { error }.
function boardViewSettingsRequest(board, input) {
if (!input || typeof input !== 'object' || Array.isArray(input)) {
return { error: 'body must be a JSON object' };
}
const working = JSON.parse(JSON.stringify({
boardViewSettings: (board && board.boardViewSettings) || {},
defaultPublicBoardView: board && board.defaultPublicBoardView,
defaultPrivateBoardView: board && board.defaultPrivateBoardView,
boardViewOrder: board && board.boardViewOrder,
}));
const $set = {};
const merge = mod => {
Object.assign($set, mod);
applyDotSet(working, mod);
};
for (const side of ['public', 'private']) {
const field = defaultField(side);
if (!Object.prototype.hasOwnProperty.call(input, field)) continue;
const view = input[field];
if (typeof view !== 'string' || !isKnownBoardView(view)) {
return { error: `${field}: unknown board view "${String(view)}"` };
}
merge(defaultBoardViewModifier(working, view, side));
}
if (Object.prototype.hasOwnProperty.call(input, 'boardViewSettings')) {
const table = input.boardViewSettings;
if (!table || typeof table !== 'object' || Array.isArray(table)) {
return { error: 'boardViewSettings must be an object of { "<view>": { showOnPublic, showOnPrivate } }' };
}
for (const view of Object.keys(table)) {
if (!isKnownBoardView(view)) {
return { error: `boardViewSettings: unknown board view "${view}"` };
}
const entry = table[view];
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
return { error: `boardViewSettings.${view} must be an object with showOnPublic and/or showOnPrivate` };
}
for (const side of ['public', 'private']) {
const flag = showField(side);
if (!Object.prototype.hasOwnProperty.call(entry, flag)) continue;
const raw = entry[flag];
const shown = raw === true || String(raw).toLowerCase() === 'true';
const mod = showBoardViewModifier(working, view, side, shown);
if (!mod) {
return { error: `boardViewSettings.${view}.${flag}: cannot hide the ${side} default view; set ${defaultField(side)} to another view first` };
}
merge(mod);
}
}
}
if (Object.prototype.hasOwnProperty.call(input, 'boardViewOrder')) {
const order = input.boardViewOrder;
if (!Array.isArray(order)) {
return { error: 'boardViewOrder must be an array of board view keys' };
}
const unknown = order.find(view => typeof view !== 'string' || !isKnownBoardView(view));
if (unknown !== undefined) {
return { error: `boardViewOrder: unknown board view "${String(unknown)}"` };
}
merge({ boardViewOrder: normalizeBoardViewOrder(order) });
}
return { $set };
}
module.exports = {
BOARD_VIEWS,
boardViewSettingsSnapshot,
boardViewSettingsRequest,
DEFAULT_BOARD_VIEW,
DEFAULT_BOARD_VIEW_ORDER,
SEPARATOR_AFTER,
boardViewJsClass,
normalizeBoardViewOrder,
isDefaultBoardViewOrder,
orderedBoardViews,
moveBoardView,
reorderVisibleBoardViews,
boardViewMenuEntries,
boardViewAudience,
isKnownBoardView,
normalizeVisibility,
isBoardViewShown,
defaultBoardView,
visibleBoardViews,
resolveBoardView,
showBoardViewModifier,
defaultBoardViewModifier,
};