Skip to content

Knowledge Reading and Lists Developer Guide

Ed Mozley edited this page Dec 1, 2026 · 1 revision

Knowledge - reading and lists: developer guide

5.15.0. Four issues raised by @Dr4inder: #464 (folding tree), #478 (article path, owner, review, audience, table of contents), #481 (card badges, folder path, owner) and #493 (branded PDFs). The user's view: Knowledge - Β§ Folding the tree, Β§ Reading an article, Β§ Badges, folder paths and owners in the list, Β§ The Branding header and footer.

Almost all of this is in the browser: the lists and the article are drawn by assets/js/knowledge.js from data the page already has. The server adds three things - the owner's name and a review state on each list row, and two values printed into the page.

πŸ“ Files

File What
includes/knowledge/review_state.php New. KB_REVIEW_SOON_DAYS and knowledgeReviewStateSql() - one rule for "overdue" and "due soon"
api/knowledge/knowledge_articles.php The list now returns owner_name and review_state
api/knowledge/knowledge_article.php One article now returns review_state (it already had owner_name)
knowledge/index.php Prints window.KB_SHOW_TOC and window.KB_LIST_PERSON
knowledge/settings/manifest.php New tab display (KNOWLEDGE_MANAGE, setting key knowledge_list_person)
knowledge/settings/index.php The Display tab; the Table of contents choice on the personal Left panel tab; the personal-tab load fix
assets/js/knowledge.js (v88) Tree folding, breadcrumb, meta line, table of contents, badges, folder path, owner, the PDF bands
assets/css/knowledge.css (v36) Tree toggles, crumbs, badges, the table of contents and its container query
assets/css/mobile.css Owner and audience fold behind the meta tap on a phone; an overdue review stays visible
assets/js/network-mapper.js (v25) {{page}} / {{pages}} print 1 on a diagram
system/branding/index.php, lang/en/system.php The two new tokens listed under the header / footer boxes

No schema change: knowledge_list_person is a system_settings row and knowledge_article_toc a user_preferences row, both read with a default when absent.

πŸ“… Review state - decided on the server

const KB_REVIEW_SOON_DAYS = 30;

function knowledgeReviewStateSql(string $alias = 'a'): string
{
    $col = $alias . '.next_review_date';
    return "CASE WHEN $col IS NULL THEN NULL"
         . " WHEN $col < DATE(UTC_TIMESTAMP()) THEN 'overdue'"
         . " WHEN $col <= DATE_ADD(DATE(UTC_TIMESTAMP()), INTERVAL " . KB_REVIEW_SOON_DAYS . " DAY) THEN 'soon'"
         . " ELSE NULL END";
}

Both article endpoints select it as review_state:

" . knowledgeReviewStateSql('a') . " AS review_state
  • 30 days because Knowledge β†’ Review (api/knowledge/get_review_list.php) calls the same window "upcoming". A badge on a card and the Review page must never disagree.
  • TRAP: never in the browser. The browser's clock is in the reader's time zone; the Review page and the reminders (includes/knowledge/review_reminders.php) use the server's UTC date. Worked out in JavaScript, an article would turn overdue a day early or late for some readers.
  • The date itself has no time of day, so the article view shows it with fmtNaiveDate() - never fmtDate(), which would shift it through the reader's zone.

🌳 Folding the tree (#464)

renderTreeLayout() skips a folded folder's children; the folded set is a Set of folder ids kept in localStorage:

const KB_TREE_COLLAPSED_KEY = 'knowledge_tree_collapsed';
const kbTreeCollapsed = new Set((() => {
    try { const v = JSON.parse(localStorage.getItem(KB_TREE_COLLAPSED_KEY) || '[]'); return Array.isArray(v) ? v.map(String) : []; }
    catch (e) { return []; }
})());
Function Does
kbToggleTreeFolder(id) folds or unfolds one folder
kbTreeCollapseAll() / kbTreeExpandAll() the two buttons above the tree
kbTreeExpandTo(id) unfolds the folders above a folder; returns true when anything changed
kbRedrawTree(focusSelector) redraws in place - same filters, selection and scroll - and puts the focus back on the control used, which the redraw replaced

The toggle is a <button> of its own with aria-expanded and event.stopPropagation(), so folding never selects the folder (the row's own click). The arrow is drawn with CSS borders and rotated by [aria-expanded="true"] - a β–Έ glyph was a faint speck in the app's fonts.

selectFolder() calls kbTreeExpandTo() first, so a folder chosen from the left panel inside a folded branch gets a row to highlight:

const unfolded = kbLayout === 'tree' && kbTreeExpandTo(activeFolder);
...
if (unfolded) kbRedrawTree();

TRAP: a folded folder's articles are left OUT of the page, not hidden. The selection - Shift-click ranges, Ctrl+A - reads the rows on screen through kbVisibleArticleIds() (#articleList [data-article]). Rows hidden with CSS would still be in that list, and a range could sweep an article nobody could see into a bulk move.

πŸ“– The article view (#478)

renderArticleDetail() adds three helpers:

Function Draws
kbArticleBreadcrumb(article) Home β€Ί A β€Ί B from folderPath(article.folder_id); each part calls selectFolder(id, true). A folder not in kbFolders (not visible to this analyst) is not named - the crumb is the start alone
kbArticleStewardMeta(article) .kb-meta-owner, .kb-meta-review (is-overdue / is-soon) and .kb-meta-audience on the meta line
kbHighlightSidebarFolder(folderId) moves the sidebar's active class to the article's folder without changing activeFolder, so Back still returns to the list you left. showView('list') calls it with activeFolder to put it back

A deep link (?article=N) can draw the article before loadFolders() returns. loadFolders() therefore redraws the crumbs and the highlight when the article view is open.

The table of contents

kbBuildToc(container) runs after the body is drawn. It does nothing when window.KB_SHOW_TOC === false or the body has fewer than three non-empty H2 / H3 headings. Otherwise it inserts the list twice - a <details class="kb-toc-top"> above the text and a <nav class="kb-toc-side"> beside it - and CSS shows one:

.kb-toc-host { container-type: inline-size; container-name: kbtoc; }
.kb-toc-side { display: none; }
@container kbtoc (min-width: 860px) {
    .has-toc > .kb-toc-top { display: none; }
    .has-toc > .kb-article-grid { display: grid; grid-template-columns: minmax(0, 1fr) 220px; gap: 32px; align-items: start; }
    .has-toc .kb-toc-side { display: block; position: sticky; top: var(--kb-head-h, 0px); ... }
}

A container query, not a media query: what matters is how wide the article is, which depends on the sidebar as much as the window - so a narrow desktop window gets the folded block too, and no breakpoint is duplicated in mobile.css. The container is a wrapper of its own (.kb-toc-host) round the body only, because container-type brings layout containment and nothing else in the article (documents panel, diagrams) should be inside it.

Clicking an entry scrolls the heading into view and gives it the focus (tabindex="-1"), so a keyboard or screen-reader user is where the eye is.

TRAP: the header above the article is sticky, so a heading scrolled "to the top" would sit under it, and so would a sticky column with top: 0. --kb-head-h carries the header's height into the column's top and the headings' scroll-margin-top. And the header measures 0 when the list is built - renderArticleDetail() runs while the view is still display: none. The first cut set the height once and the column stuck behind the header. It is watched instead:

if (header && window.ResizeObserver) {
    container._kbTocObserver = new ResizeObserver(setHead);
    container._kbTocObserver.observe(header);
}

The observer reports the real height once the view is shown, and again whenever the header wraps differently. It is disconnected at the start of every kbBuildToc(), so an article with no contents list never leaves one watching a detached header.

πŸƒ Cards and rows (#481)

Function Does
kbListIsMixed() true when articles come from more than one folder (unfiled counts as one) - computed once per renderArticleList()
kbFolderLabel(article, mixed) the folder path; more than three parts lose the middle ([first, '…', last two]), the whole path in title; a folder this analyst cannot see shows nothing rather than a guess
kbStateBadges(article) Review overdue / Review due soon from review_state; Customers / Public from audience
kbCardPerson(article) author, owner or both, by window.KB_LIST_PERSON
function kbCardPerson(article) {
    const by = `<span>${escapeHtml(window.t('knowledge.list.by', { name: article.author_name }))}</span>`;
    const owner = article.owner_name
        ? `<span>${escapeHtml(window.t('knowledge.list.owner', { name: article.owner_name }))}</span>` : '';
    const mode = window.KB_LIST_PERSON || 'author';
    if (mode === 'owner') return owner || by;
    if (mode === 'both') return by + (owner && article.owner_name !== article.author_name ? owner : '');
    return by;
}

kbFolderLabel() used to show only the last folder's name, and only at the top level while searching. "Mixed" covers that case and any other list that spans folders, including a folder with shortcuts in it.

In the Cards layout the info line used to be one unwrapped line; with an owner and a path everything was cut to By ... Own.... It now wraps (.kb-layout-cards .article-card-info { flex-wrap: wrap; }), the path takes a line of its own, and the date has a class (kb-card-date) so no rule depends on its position. Cards in a row stay the same height because the grid stretches them.

Two values printed into the page

$kbTocStmt = $kbPrefConn->prepare("SELECT preference_value FROM user_preferences WHERE analyst_id = ? AND preference_key = 'knowledge_article_toc' LIMIT 1");
$kbShowToc = $kbTocStmt->fetchColumn() !== 'hide';
...
if (in_array($kbPersonVal, ['author', 'owner', 'both'], true)) $kbListPerson = $kbPersonVal;
<script>window.KB_SHOW_TOC = true; window.KB_LIST_PERSON = "author";</script>

Server-side rather than fetched, for the same reason as the sidebar mode: an article opened from a link would otherwise draw before the answer came back, and the contents list or the names would change under the reader.

The personal-tab fix

knowledge/settings/index.php loaded the Left panel tab's choices only in switchTab(). An analyst with no Knowledge settings rights sees only that tab, so it opens first and switchTab() never runs - every choice showed nothing ticked. DOMContentLoaded now loads them when that tab is the active one.

πŸ–¨οΈ The branded PDF (#493)

buildArticlePdf() fetches the Branding slots once per page (kbPdfBranding(), ../api/system/get_branding.php; a failure is not cached and the PDF prints without the branded text) and lays out two bands.

  • Tokens: resolveSlot(raw, page, pages) removes {{logo}} (it is drawn, not printed), fills {{title}} {{author}} {{version}} {{modified}} {{page}} {{pages}}, and leaves an unknown token as typed.
  • The page counter: when no slot names {{page}} / {{pages}}, the first empty footer slot - right, centre, left - gets an internal {{pagelabel}} (Page X of Y, knowledge.share.pdf_page_of); when all three are full it is a second line under the right one.
  • The fonts: the header and footer text is passed to FitsmPdf.create() with the article, so the writer fetches every script they need.
// Measured with three-digit page numbers, so a long PDF never outgrows its band.
const headerH = Math.max(0, ...header.map(s => layoutSlot(s, 'header', 999, 999).h));
const footerH = Math.max(0, ...footer.map(s => layoutSlot(s, 'footer', 999, 999).h));
const headerRule = headerH ? TOP + headerH + 2 : 0;
const footerRule = footerH ? pageH - BOTTOM - footerH - 2 : 0;
const topLimit = headerH ? headerRule + 5 : margin;
const bottomLimit = footerH ? footerRule - 4 : pageH - margin;

layoutSlot() sizes a slot (logo at most 12mm high in the header, 6mm in the footer, never wider than a third of the page; up to three lines of text), and drawBand() draws one. Every page break uses topLimit and bottomLimit - ensureSpace(), drawPicture() and the autoTable() margins - so nothing enters a band. y is a baseline, so the first line on a new page starts at topLimit + 4, leaving its capitals clear of the header rule. The title starts 7mm below the header's limit: before 5.15.0 its capitals sat on the logo's bottom edge.

The bands are drawn LAST. Only once the article is laid out is the number of pages known, so Page 2 of 3 is right whatever the tables and pictures did. The writer buffers its pages (bufferPages: true), so it can go back:

const pages = doc.getNumberOfPages();
for (let p = 1; p <= pages; p++) {
    doc.setPage(p);
    if (headerH) { drawBand(header, 'header', TOP, p, pages); doc.line(margin, headerRule, pageW - margin, headerRule); }
    if (footerH) { doc.line(margin, footerRule, pageW - margin, footerRule); drawBand(footer, 'footer', footerRule + 2, p, pages); }
}

The download (shareArticlePdf()) and the email attachment (sendShareEmail()) both call buildArticlePdf(), so they are the same PDF.

Network Mapper resolves its slots with its own renderSlotHtml(). It now knows {{page}} and {{pages}} and prints 1 - otherwise a box set up for PDFs would have shown the token on every diagram.

🧭 Decided

1 December 2026, with Ed:

  • The table of contents is a per-analyst preference, on by default (knowledge_article_toc, Settings β†’ Left panel).
  • Who cards and rows name is an install setting, knowledge_list_person, defaulting to the author - nothing changes until someone chooses.
  • "Due soon" is 30 days, to match the Review page.
  • The page counter is placed automatically in the first empty footer slot (right first) unless a slot uses {{page}}.

πŸ§ͺ Tests

Test Checks
tests/knowledge-tree-collapse.php 17 - the shipped tree code in Chrome with real CSS: folding hides children and never selects; aria and focus; remembered; Collapse all / Expand all; a folder in a folded branch unfolds and highlights; folded articles are out of kbVisibleArticleIds(); Expand all keeps a search
tests/knowledge-article-reading.php 5 against the database (the review-state SQL from a derived table: yesterday, today, +30, +31, none - nothing written) + 33 in Chrome: breadcrumb, meta line, sidebar highlight, table of contents beside / folded / absent / off, a click lands on the heading; folder path, badges and all three person modes
tests/knowledge-pdf-branding.php 13 - the shipped buildArticlePdf() against a recording stand-in for the writer: bands on every page with tokens filled, Page X of Y with the final total, no text within 2mm of either rule, table margins inside the bands, at least 6mm between logo and title, {{page}} / {{pages}} placement, no logo and empty boxes, Branding unreadable; plus the German string

Seven existing Knowledge tests build sandboxes from knowledge.js and needed the new helpers stubbed (kbHighlightSidebarFolder, kbListIsMixed, kbStateBadges, kbCardPerson, kbTreeCollapsed). TRAP, as before: a test that extracts functions by name fails with "X is not defined" when a function it runs starts calling a new helper.

Related pages

FreeITSM

Getting Started

Modules

Multi-tenancy (planned)

Responses to feedback

Blue sky thinking

Bugs resolved

Pull requests

Links

Clone this wiki locally