Skip to content

About

Design System used by other projects

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

34 Commits

Folders and files

Repository files navigation

@FERCBusters/mosp-design-system

A small shared UI "shell" + helper library designed to be used across various FERCBusters Open Source projects.

It assumes you're serving mostly-static HTML pages (no SPA) and using:

  • Bootstrap 5 (CSS + JS bundle)
  • bootstrap-icons
  • D3 (page-specific; not bundled here)

What this provides

Standard UI shell

  • Fixed horizontal Bootstrap navbar (navbar-keen)
  • Consistent brand slot (icon + name)
  • Consistent buttons, cards, tables, muted text (via styles.css)
  • Nine theme palettes (Ink, the default, Sand, Ocean, Forest, Sunset, Rose, Slate, Teal and Purple), each with a dark variant. Text coloured by the theme tokens clears WCAG AA contrast, 4.5:1, on the surfaces the tokens paint; tests/theme-contrast.test.mjs checks every palette in both modes.
  • Optional:
    • Framework selector (adds ?framework=<slug> to nav links)
    • Global search box (optionally with datalist autocomplete)
    • Notification bell + badge (polling + optional websocket), or a bell menu of several notification kinds with a count beside each
    • Shortcuts dropdown: "Save this view…" + list + delete

Standard helpers (shared patterns)

  • CSRF header handling (see "CSRF cookie" below)
  • apiGet/apiPost/apiPatch/apiPut/apiDelete/apiPostForm
  • querystring helpers (qs/qbool/qint/setQuery)
  • timestamp helpers (fmtTs, filename-safe fmtTsFilename)
  • configurable visible date-format ↔ yyyy-mm-dd helpers
  • sortable tables
  • toast() helper for Bootstrap alerts
  • bindAutoApply() helper (debounced auto-apply for filters)
  • enhanceMultiSelect() / enhanceMultiSelects(): one picker for every place a page lets a person choose several entries (see "Multi-select picker" below)
  • relatedCard() / relatedCards() / updateRelatedCard(): one frame for every card that lists what a record is linked to (see "Related-item cards" below)

Multi-select picker

enhanceMultiSelect(select) turns a <select multiple> into a search-then-add picker: a search box, a short scrollable list of tick boxes for people who would rather browse than type, and the chosen entries as removable chips. Typing narrows the list; Enter adds the only match and clears the search. enhanceMultiSelects(root = document) does this for every <select multiple> under root, so a consuming application calls it once per page; mark a select data-picker="off" to keep its native control.

The native select stays in the page, hidden, and remains the value. Page code keeps filling its options, setting option.selected and reading selectedOptions, and a change made in the picker fires a bubbling change event on the select. The picker redraws by itself when the select's options are replaced, when the select or a fieldset around it is disabled, on the select's change event and when its form is reset. After setting option.selected from code on options that are already there, call refreshMultiSelect(select).

<label for="controls">Controls</label>
<select id="controls" multiple></select>
import { enhanceMultiSelects, refreshMultiSelect } from '/vendor/mosp-design-system/app.js';
enhanceMultiSelects();

Deselect all, after the chips, clears the choice in one action (options the page disabled stay chosen).

A choice can carry a value of its own, such as how relevant a chosen control is. Describe it on the select as JSON in data-picker-extra, for example {"label": "Relevance", "choices": [["high", "High"], ["low", "Low"]], "default": "low"}. Each row then has a small select beside its tick box, enabled while the row is ticked; the value is kept on the option as data-extra and shown in the chip. Ticking an option without a value gives it the default, or the first choice.

An option's text is what is listed and searched; its title is searched too and shown as a tooltip, and data-badge="…" adds a small label beside it. Everything is inserted as text, never as HTML. Lists longer than 400 entries draw the first 400 and ask for a search. Styling is .mosp-picker* in src/css/70-admin-and-forms.css, on top of the existing .keen-multiselect-wrap list.

Related-item cards

A record's page often lists what the record is linked to: the risks mapped to a control, the documents a legal requirement bears on, the stories that include it. relatedCard(options) builds one such card and relatedCards(cards, host) lays a set of them out, so their headings, text size, tables and spacing are the same on every page and in every application.

import { relatedCard, relatedCards, updateRelatedCard } from '/vendor/mosp-design-system/app.js';

const risks = relatedCard({
  id: 'risksCard',
  title: 'Cross-referenced risks',
  description: 'Risks mapped to this control.',
  empty: 'Loading risks',
});
relatedCards([clauses, stories, risks], document.getElementById('relatedItems'));

updateRelatedCard(risks, {
  count: rows.length,
  table: {
    columns: ['Asset', { label: 'Risk', width: '80px', align: 'end' }],
    rows: rows.map((risk) => [{ text: risk.asset, href: risk.url, detail: risk.threat }, risk.score]),
  },
  empty: 'No risks mapped to this control.',
});

A card's body is one of: table ({ columns, rows }), links (a list of { text, href, detail, newTab, action }), or body (an element, for content with its own controls such as a form). empty is the message shown when the table or list has nothing in it. count adds a badge and action a button in the heading: { label, href } or an element. A cell is text, an element, a link { text, href, detail, newTab }, or a list of those.

Short cards sit side by side; a card with rows in a table takes the full width of the group, unless wide says otherwise. A hidden card leaves no gap. Cards do not scroll sideways, because a table header sticks beneath the navbar as the page scrolls and would otherwise stick to the card instead.

Security. Every string is written as text and never parsed as HTML, so a record's name cannot become markup. Where a page needs markup of its own it passes a DOM element it built; a string given in an element's place throws rather than being parsed. A link keeps its href only when it is one of the site's own paths or an http(s) URL (safeExternalHref); otherwise the text is shown without a link. A column width is applied only when it is a plain length, and a card id only when it is a plain identifier. Styling is .mosp-related-* in src/css/80-tabs-tags-graphs.css.

Files

  • dist/app.js – bundled ESM module for consuming applications.
  • dist/styles.css – bundled themeable CSS for consuming applications.
  • dist/theme-boot.js – a classic script that applies the theme this browser last applied before the page first paints.
  • src/js/*.js – maintainable JavaScript source fragments, split by feature area.
  • src/css/*.css – maintainable CSS source fragments, split by feature area.
  • src/boot/theme-boot.js – the part of dist/theme-boot.js that reads the saved theme.
  • scripts/build.mjs – concatenates the ordered source fragments into dist/app.js and dist/styles.css, and writes dist/theme-boot.js from src/js/05-theme-attributes.js and src/boot/theme-boot.js.

The source fragments intentionally share one bundle scope and are concatenated in the explicit order listed in scripts/build.mjs. Edit the relevant file under src/js/ or src/css/, then run npm run build; do not edit generated files under dist/ directly.

Basic integration pattern (static HTML)

  1. Copy the kit into each app's public/ (recommended path):
services/ui/public/vendor/mosp-design-system/
  app.js
  styles.css
  theme-boot.js
  1. Include the theme boot script and Bootstrap + icons. The boot script goes first in <head>, without defer or async: module scripts can run after the first paint, so without it a page can show the base palette briefly before the saved theme. With no saved theme the scripts apply Ink, the default. It only reads the saved theme; applyTheme() saves it.
<script src="/vendor/mosp-design-system/theme-boot.js"></script>
<link href="/vendor/bootstrap/bootstrap.min.css" rel="stylesheet">
<link href="/vendor/bootstrap-icons/bootstrap-icons.min.css" rel="stylesheet">
<link rel="stylesheet" href="/vendor/mosp-design-system/styles.css">
  1. Add a navbar mount element:
<body data-page="controls">
  <div id="navbar"></div>
  ...
</body>
  1. Configure BEFORE importing (inline <script> above any module imports):

Example for KEEN:

<script>
  window.mospUiConfig = {
    appId: "keen",
    appName: "Keen",
    brandIcon: "/keen.svg",
    brandHref: "/",
    csrf: { cookieName: "keen_csrf" },
    auth: {
      meEndpoint: "/api/v1/me",
      logoutEndpoint: "/api/v1/auth/logout",
      logoutRedirect: "/login.html",
      accountHref: "/account.html"
    },
    links: [
      { label: "Controls", href: "/?stay=1", key: "controls" },
      { label: "Events", href: "/events.html", key: "events" },
      { label: "Sources", href: "/sources.html", key: "sources" },
      { label: "Admin", href: "/admin.html", key: "admin", requireAny: ["is_admin", "can_audit_trail"] }
    ],
    framework: {
      enabled: true,
      // Optional, as for links: leave the picker out unless the (mapped)
      // user has these flags, e.g. an installation feature that is on.
      requireAll: ["feature_frameworks"],
      endpoint: "/api/v1/frameworks",
      queryParam: "framework",
      default: "ISO27001:2022"
    },
    search: {
      enabled: true,
      placeholder: "Search events",
      targetPath: "/events.html",
      queryParam: "q",
      datalistId: "mospSavedSearches",
      datalistEndpoint: "/api/v1/me/saved-searches"
    },
    shortcuts: {
      enabled: true,
      endpoint: "/api/v1/me/shortcuts"
    },
    bell: {
      enabled: true,
      href: "/admin.html#questions",
      title: "Open questions",
      summaryEndpoint: "/api/v1/admin/questions/summary",
      countKey: "open_count",
      wsUrl: (location.protocol === "https:" ? "wss://" : "ws://") + location.host + "/api/ws/notifications",
      wsType: "questions.open_count"
    }
  };
</script>

To list several kinds of notification, give the bell items instead of href, summaryEndpoint and countKey. The bell then opens a menu with each kind's count beside it, and its badge shows their total. items may be a function of the signed-in user; with one item the bell is a link to it, and with none it is hidden. ws: true marks the item the websocket's count messages update:

bell: {
  enabled: true,
  title: "Notifications",
  items: (me) => [
    {label: "Questions", href: "/questions.html", icon: "bi-chat-left-text",
     summaryEndpoint: {admin: "/api/v1/admin/questions/summary", user: "/api/v1/me/questions/summary"},
     countKey: {admin: "open_count", user: "unread_count"}, ws: true},
    ...(me?.is_admin ? [{label: "Suggested rules", href: "/admin.html#rule-suggestions",
      summaryEndpoint: "/api/v1/admin/rule-suggestions/summary", countKey: "open_count"}] : []),
  ],
}
  1. In your page modules, call initNavbar():
import { initNavbar, apiGet } from "/vendor/mosp-design-system/app.js";

const me = await initNavbar();
// ... page-specific logic ...

Sharing the code across repos

Option A — npm dependency via git

In each app's UI build directory:

  • add dependency:

    • "@FERCBusters/mosp-design-system": "git+ssh://[email protected]/FERCBusters/mosp-design-system.git#dev"
  • add a build/copy step to place dist/ into services/ui/public/vendor/mosp-design-system/.

Option B — git submodule

  • Add the UI kit as a submodule into each repo (e.g. vendor/mosp-design-system/)
  • Copy dist/* into public/vendor/mosp-design-system/ during build/deploy.

CSRF cookie

The API helpers that change data (apiPost, apiPatch, apiPut, apiDelete, apiPostForm, and apiRequest when it sends a change) repeat the CSRF cookie's value in the csrf.headerName header. csrf.cookieName is the cookie's name without a prefix.

A server that sets Secure cookies without a Domain attribute can name the cookie __Host-<cookieName>. A browser accepts that name only from the page's own host over HTTPS, so a site under the same parent domain can neither set nor shadow it. The helpers read __Host-<cookieName> first and <cookieName> otherwise, so one bundle serves an installation behind HTTPS and one reached over plain HTTP. A cookieName that already begins with __Host- or __Secure- is read as it is.

Navbar startup data

Navbar autocomplete and shortcuts share their initial saved-search result when configured with the same endpoint. Saving or deleting a shortcut still refreshes the list from the API. A failed autocomplete request allows shortcuts to retry.

getLoadedFrameworkCatalog() returns the original successful framework-picker response, including application-specific metadata, or null before it is loaded. Applications can reuse it after initNavbar() to render additional navigation without requesting the catalogue again. Explicit refreshes remain the caller's responsibility. The response stays in memory for the current document.

Run npm test for the navbar data regression checks and npm run build to build the distributed assets.

About

Design System used by other projects

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages