npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

nwl-components

v3.9.0

Published

This project is a library of components to be used on the frontend of the Neuroweblab projects. They are similar in style and behaviour to existing projects.

Readme

About

This project is a library of components to be used on the frontend of the Neuroweblab projects. They are similar in style and behaviour to existing projects.

Scope

nwl-components holds only generic components, which any NAAT app can use and customise through props, slots and the config object: the project-management pages, the project-page shell, and generic building blocks. Nothing tied to one app (BrainBox or microdraw) and none of a viewer's own logic belongs here; that stays in each app.

Exports by group:

| Group | Exports | |---|---| | Pages | UserPage, NewProjectPage, SettingsPage, ProjectPage (the project-page shell: header, resizable left/right split, fullscreen; the app fills the slots) | | Layout | Wrapper, Header, Nav, Footer | | Settings | Settings, ProjectInfo, Files, Collaborators, Annotations, Access, ImportFilesDialog, PureFiles, PureCollaborators, PureAnnotations | | Common widgets | Button, Checkbox, Select, TextInput, TextArea, Autocomplete, Table, SortableTh and useSortable (sortable table columns), Tabs, Tab | | Settings page files loader | useBatchedFiles (3.5.0, see "Settings page files loader") | | Admin page | DamagedProjects and useDamagedProjects (the "Damaged projects" section: props show-time, undo-url; 3.7.0, see the CHANGELOG) | | Page helpers | fetchJSON, postJSON, defaultFetchLabelSets (the label sets of /api/getLabelsets, PureAnnotations' default), formatDate, pad, localDate, shownName (3.5.0, see "Settings page files loader") | | Building blocks | Editor (floating/dockable tool window with content and tools slots), Row, Col, ButtonsGroup, RangeSlider, AdjustSettings, Chat and ScriptConsole (replaced by nwl-components/chat), TextAnnotations, VolumeAnnotations, AnnotationCell, OntologySelector (label-set selector) |

To clean up

App-specific content that should become neutral later (no component is deprecated):

  • the BrainBox stories src/components/pages/BrainboxProjectPage.stories.js and src/components/project/BrainboxProject.stories.js;
  • the story data TextAnnotations.brainbox.fixtures.json and TextAnnotations.microdraw.fixtures.json;
  • the BrainBox settings (site name, logo, URLs, label sets) in .storybook/preview.js;
  • Chat and ScriptConsole are replaced by nwl-components/chat (3.8.0, see "Chat and script area"), which the viewers use: Chat renders messages as raw HTML (v-html), and ScriptConsole loads codeflask and consolita from CDN URLs and targets the global id #logScript. Whether they leave is decided for 4.0.0.

Settings page files loader

The server sends a project's settings page without its files: useBatchedFiles fetches them in batches from /project/json/<shortname>/files and shows them as they arrive (3.5.0).

import { SettingsPage, useBatchedFiles } from 'nwl-components';

const { files, filesLoaded, loadFiles } = useBatchedFiles({ shortname: project.shortname, filesTotal });
project.filesLoaded = filesLoaded; // { count }: sent when saving

createApp({
  template: '<SettingsPage :project="project" :files="files" />',
  setup: () => ({ project, files }),
  mounted () { loadFiles(); }
});

Options: batchLength (100) and retryDelays ([500, 1000] ms). While loading, the "Files" heading shows (loading… r / t) and the files' section has .filesLoading (not editable); after the retries, the error and a Retry button. Its CSS is in dist/style.css.

The page helpers: fetchJSON(url, options) and postJSON(url, data) throw body.error, body.msg or '<status> <statusText>' when the answer isn't ok or has success: false; formatDate(date, { time = false }) (YYYY-MM-DD, or YYYY-MM-DD HH:MM as stored); localDate(iso, dateTime = false) (local time) and pad(n); shownName(row, { nameKey = 'name', shortnameKey = 'shortname' }) (the name, or the shortname when it is blank).

Sortable tables

useSortable(rows, columns) keeps a table's sort state; SortableTh is a header cell that sorts by its column when clicked (or with Enter/Space). Every sortable header always shows an icon (a grey up/down "sort" icon when the column is not the sort column, one up or down arrow when it is; inline SVG from Tabler Icons, MIT) in a box of fixed size, so nothing moves when you click; aria-sort is set on the <th>. First click sorts ascending, a second click reverses, another column sorts ascending; missing values (null, undefined, '', not a number/date) are always last. The rows array is never mutated. Headers written as plain <th> look as before.

import { SortableTh, Table, useSortable } from 'nwl-components';

const PageContents = {
  template: '#template',
  setup () {
    const projects = ref([]);
    const sort = useSortable(projects, {
      // column name: { key: row property (or row => value), type: 'string' (default) | 'number' | 'date' }
      Name: { key: 'project' },
      Files: { key: 'numFiles', type: 'number' },
      'Last modified': { key: 'modified', type: 'date' }
    });

    return { projects, sort, sortedProjects: sort.sortedRows };
  }
};
const app = createApp(PageContents);
app.component('Table', Table);
app.component('SortableTh', SortableTh);
<script type="text/html" id="template">
  <Table>
    <thead><tr>
      <sortable-th :sort="sort" column="Name">Name</sortable-th>
      <sortable-th :sort="sort" column="Files">Files</sortable-th>
      <sortable-th :sort="sort" column="Last modified">Last modified</sortable-th>
    </tr></thead>
    <tbody>
      <tr v-for="project in sortedProjects">...</tr>
    </tbody>
  </Table>
</script>

In a template parsed by the browser (written directly in the page, not in a <script type="text/html">), write <th is="vue:sortable-th" ...> instead, so the browser keeps it inside the table. useSortable also returns sortBy(column), direction(column) ('ascending', 'descending' or 'none'), and the refs sortColumn and sortAscending; a third argument { column, ascending } sets an initial sort. Story: Common/Table (npm run storybook). Since 1.5.0.

Table cells wrap at spaces only, so a long word such as an owner's user name is never broken. A cell that may break inside a word, so that the table is never wider than its panel (for example a long project name with no spaces), opts in with the class nwl-break-anywhere (overflow-wrap: anywhere). It works on cells written in the Table slot. Since 1.5.3.

<tr v-for="project in sortedProjects">
  <td class="nwl-break-anywhere">{{ project.name }}</td>
  <td>{{ project.owner }}</td>
</tr>

Tables without Vue

Pages that build their tables with template strings and the DOM sort them the same way with nwl-components/sort, which has no Vue (about 3 kB). Importing these names from nwl-components itself also works, but bundles Vue and the whole library. useSortable and SortableTh use the same code, so the order and the header markup never differ.

import { nextSort, sortRows, sortableHeader } from 'nwl-components/sort';

const columns = { Name: { key: 'project' }, Files: { key: 'numFiles', type: 'number' } };
let state = { column: null, ascending: true };
const headers = {};
const render = () => {
  const rows = state.column ? sortRows(projects, columns[state.column], state.ascending) : projects;
  tbody.innerHTML = rows.map((p) => `<tr><td>${p.project}</td><td>${p.numFiles}</td></tr>`).join('');
  for (const [name, header] of Object.entries(headers)) {
    header.setDirection(name !== state.column ? 'none' : state.ascending ? 'ascending' : 'descending');
  }
};
for (const th of table.querySelectorAll('th')) {
  const name = th.textContent;
  headers[name] = sortableHeader(th, { onSort: () => { state = nextSort(state, name); render(); } });
}
render();
  • sortRows(rows, { key, type }, ascending = true): a new, sorted array (stable; missing values last in both directions; strings in natural order, localeCompare with numeric: true, so "E90" comes before "E120"; since 1.6.1). sortValue(row, column) is the value it compares.
  • sortableHeader(th, { direction, onSort }) turns a <th> into SortableTh's markup (class="nwl-sortable", aria-sort, a <button type="button"> with the th's content and the icon; Enter and Space work as on any button) and returns { th, button, setDirection(direction) }.
  • nextSort(state, column): the sort after a click, as in useSortable.
  • For template strings: renderSortIcon(direction) (the SVG) and ariaSort(direction).

The headers' look is in nwl-components/sort/style.css, which has only the th.nwl-sortable and .nwl-sort-* rules, after the design tokens they read (:root custom properties, see "Design tokens"; 6 kB in all). Load that file, not dist/style.css, on a page not built with nwl-components: dist/style.css has global rules (* sets the font size and colour of every element). With a bundler, import 'nwl-components/sort/style.css' (webpack 4 included); otherwise link node_modules/nwl-components/dist/sort/style.css. dist/style.css keeps the same rules for SortableTh. Story: Common/PlainSort. Since 1.6.0.

Resizable columns

Every Table has resizable columns (since 3.1.0): a handle at the right edge of each column header, the last one's included. Drag it with a mouse, pen or finger, or focus it (Tab: each sort button, then its handle) and press ArrowLeft/ArrowRight (10px; 50px with Shift). A double-click on a handle, or Enter on a focused one, goes back to the automatic layout. Widths are not remembered: a reload gives the automatic layout again.

  • Nothing moves before a resize. The handle is absolutely positioned inside its th (position: relative), about 8px wide and the header's full height; invisible at rest, a 1px line in --nwl-border-strong on hover, during a drag and on keyboard focus (plus base.css's focus outline). It is outside the sort button: grabbing or clicking it never sorts.
  • The first resize freezes every column's rendered width, in whole px, on its header cell (width, box-sizing: border-box) and switches the table to table-layout: fixed, its width the sum of its columns. From then on only the resized column changes, and the table gets wider or narrower. Rows added or removed later keep the widths. A column added or removed after a resize goes back to the automatic layout. The minimum width is 3em, or the header's padding and sort icon if larger.
  • Too wide: the table scrolls horizontally inside its wrapper (overflow-x: auto); the page never scrolls sideways. The wrapper is a scroll container only while the table is wider than it (class nwl-resize-overflow, checked after each resize and when the wrapper's size changes), so popups in cells (Autocomplete) are not clipped otherwise. Resized cells wrap, even inside a word (overflow-wrap: anywhere), so nothing is cut.
  • Screen readers: the handle is <span class="nwl-col-resize" role="separator" aria-orientation="vertical" tabindex="0" aria-label="Resize column <header text>">, with aria-valuenow the column's width in px.

Table renders <div class="nwl-resize-wrap"><table>…</table></div>: the div has no box (display: contents) until a column is resized. The attributes given to Table (class, style, …) go to the <table>, as before. <Table :resizable="false"> has no handles. ImportFilesDialog uses the same helper. Stories: Common/Table ResizableColumns and ResizableSameLayout.

Tables without Vue

Pages that build their tables with template strings and the DOM use nwl-components/resize (no Vue, about 5 kB) and its CSS, nwl-components/resize/style.css (only the .nwl-resize-*, .nwl-col-resize, th.nwl-resizable and .nwl-resized rules, after the design tokens), loaded as nwl-components/sort/style.css is (see "Sortable tables"; webpack 4 included, or link node_modules/nwl-components/dist/resize/style.css).

import { resizableColumns } from 'nwl-components/resize';

// after the table's header row exists; sortableHeader() before or after, either way
const columns = resizableColumns(table);
columns.reset();   // back to the automatic layout
columns.destroy(); // handles and wrapper removed, the table as it was
  • resizableColumns(table, { wrapper }) adds the handles and returns { reset(), destroy() }. Calling it again on the same table returns the same object and does nothing else.
  • Only tables whose first row holds column headers: the first row of the thead, or, without a thead, a first row of th only. Key/value tables (a th per row) and layout tables get nothing.
  • Headers added later, or whose text the page rewrites, get their handle on their own (a MutationObserver on the table): there is no need to call it again when columns change.
  • Without wrapper, the helper wraps the table in <div class="nwl-resize-wrap">. With it, it uses the given element as it is (give it overflow-x: auto, or the class nwl-resize-wrap). Either way the wrapper has the class nwl-resize-active while the columns are resized, and nwl-resize-overflow while the table is wider than it.
  • Also exported: columnHeaders(table), minColumnWidth(th).

Story: Common/PlainResize (the helper's unit tests, in a shadow root with only resize/style.css).

Chat and script area

The viewers' chat and script area (BrainBox's MRI viewer, microdraw's histology viewer), without Vue (3.8.0): import { chatLog, chatInput, textArea } from 'nwl-components/chat' (webpack 4 too), or, on a page with no bundle, /lib/nwl-components/chat/nwl-components-chat.umd.js, which gives window.nwlComponentsChat. Each helper takes elements, not selectors (microdraw's viewer is in a shadow root). The WebSocket code (sending, receiving, names) stays in each app.

const log = chatLog(dom.querySelector('#logChat .text'));
log.append({ name, text, own, href });
chatInput(dom.querySelector('#msg'), (text) => { /* send it */ });
const area = textArea({
  block: dom.querySelector('#textInputBlock'),
  chat: dom.querySelector('#logChat'),
  script: dom.querySelector('#logScript'),
  handle: dom.querySelector('#textInputResize') // minHeight: 100 by default
});
area.show('Chat'); // 'Script', or anything else to hide
  • chatLog(el).append({ name, text, own, href }): a line name: text, the name in bold, inside a link to href when given; an own line reads name (me): text, with (me) in italics. Either part may be left out (a notice). Text only (textContent, createElement), never HTML. The log scrolls to the bottom after each line.
  • chatInput(input, onSend): Enter calls onSend with the trimmed text and clears the input; empty text sends nothing.
  • textArea({ block, chat, script, handle, minHeight }): show('Chat') and show('Script') show the area (display: flex), switch the chat and the console with the class hidden, and focus the chat's input or the console's textarea; anything else hides the area (display: none). handle resizes the area with the mouse and with a finger (touch listeners with {passive: false}): its flex becomes 0 0 <height>px, at least minHeight.
  • No script loading: the console stays Consolita.init(el, root) in each app, with its vendored codeflask and consolita. A library must not load code from a CDN into the apps' pages.

Storybook's Common/PlainChat tests each helper.

Toolbar frame

The frame of the viewers' full toolbar (3.9.0), as an HTML string: toolsFrame from nwl-components/chat. It works where each viewer builds its toolbar: BrainBox inserts it in the page (insertAdjacentHTML, webpack 4), and microdraw renders it on the server, with require('nwl-components/chat') in Node, into a mustache page with triple braces. It holds only the library's markup and the app's own templates, never user data.

const { toolsFrame } = require('nwl-components/chat');
const html = toolsFrame({
  iconUrl: (name) => '/lib/nwl-components/icons/' + name + '.svg',
  slider: sliderHtml,   // the app's #sliderBlock content: its - and + buttons and its slider
  buttons: buttonsHtml, // the app's #buttonsBlock content: its tools
  extra: penSizeHtml,   // optional, after the buttons (BrainBox's #penSizeBlock)
  sliceNumber: true     // optional: #slice-number in the drag handle (microdraw)
});
  • The outline, with the ids both apps use: #tools-side holds #tools-minimized (the menu icon, #bars-icon) and #tools-maximized, which holds #headerBlock (#display-minimize, #toolsDragHandle, #display-left, #display-right), #sliderBlock, #buttonsBlock, extra, #notificationsBlock and #textInputBlock (#logChat with .text and #msg, #logScript, #textInputResize), for chatLog, chatInput and textArea.
  • iconUrl(name) gives the four icons' URLs: bars, times-circle, caret-square-o-left, caret-square-o-right. The slots go in as they are, as HTML.
  • The header buttons have the classes nwl-tool-button mui push noBorder; each app's widget code makes them work (microdraw's MUI.push, BrainBox's AtlasMakerUI.push). The slider, its classes, the buttons and the dragging stay in each app.
  • widgets.css styles the frame's own parts: #bars-icon centred in its button, the drag handle's grab cursor (grabbing with the class dragging), #logChat as a column, and the script console in #logScript (white text on black, wrapping, the panel's font size). codeflask adds its own <style>s outside any layer when it starts, so the properties it also sets are !important: .codeflask's position: relative and background, and .codeflask__flatten's white-space: pre-wrap, font-size: inherit and caret-color.
  • The text area grows to fill the toolbar's height when there is room, and is 270px tall when the toolbar's height is set by its content (flex: 1 1 270px).

Storybook's Common/PlainChat tests the frame (ToolsFrame, ToolsFrameWithSliceNumber, ScriptConsole).

Embeddable viewer

nwl-components/embed (no Vue, since 3.6.0) holds what BrainBox's /mri/embed and microdraw's /data/embed share: the embed page's sizing, and the /embed.js loader a host page includes to get the viewer in an iframe kept at the height it asks for.

// server: the text of /embed.js, built once at start-up
import { embedScript } from 'nwl-components/embed';

const embedJs = embedScript({
  prefix: 'microdraw', // microdraw:embed-resize, window.__microdrawEmbeds, data-microdraw-embedded
  appName: 'MicroDraw', // console messages, iframe title
  endpoint: '/data/embed',
  required: 'source', // data-source
  params: { source: 'source', project: 'project', slice: 'slice', maxHeight: 'maxHeight', microdrawLink: 'microdrawLink' },
  optionsDoc: [['data-source', 'source URL of the dataset (required)'], ['data-project', 'project whose regions are shown']]
});

// embed page: the height to ask the host page for
import { desiredEmbedHeight, positiveIntParam } from 'nwl-components/embed';
const height = desiredEmbedHeight({ width, aspect, toolbarHeight, maxHeight: positiveIntParam(params.maxHeight) || Infinity });

The served text is src/embed/loader.js, unminified and with its comments, with the app's names as a JSON literal at its top. A page with no bundle loads dist/embed/nwl-components-embed.umd.js and finds the same names on nwlComponentsEmbed. Story: Library/Embed.

Design tokens

The library's colours, fonts, font sizes and corner radii are CSS custom properties, defined in src/styles/tokens.css (:root rules only) in two tiers:

  • the raw palette (--nwl-grey-44, --nwl-white, --nwl-cyan, …): the only place with hex values;
  • the semantic tokens, to use in components and app CSS: backgrounds (--nwl-bg, --nwl-bg-surface, --nwl-bg-elevated, …), borders (--nwl-border, …), text (--nwl-text, --nwl-text-2, --nwl-text-3, …), accent, links and status colours (--nwl-danger, --nwl-success, --nwl-warning), font families (--nwl-font-body, --nwl-font-display, --nwl-font-mono), sizes (--nwl-text-xs … --nwl-text-hero; body text is --nwl-text-md), weights, line heights, spacing (--nwl-space-1 … --nwl-space-16), radii (--nwl-radius-sm, --nwl-radius-md) and shadows.

Their values are the kit's look (see "Look"); since 3.0.0 there is one set, with no theme attribute. Storybook's Library/Tokens page lists every token with a sample.

dist/style.css and nwl-components/sort/style.css each include the tokens, so a page that loads either needs nothing else. To use the tokens in an app's own CSS without those files:

import 'nwl-components/tokens.css'; // with a bundler (webpack 4 included)
<!-- a page with no bundle: serve or copy node_modules/nwl-components/dist/tokens.css -->
<link rel="stylesheet" href="/lib/nwl-components/tokens.css">
.my-panel {
  background: var(--nwl-bg-surface);
  border: 1px solid var(--nwl-border);
  border-radius: var(--nwl-radius-sm);
}

Loading the tokens twice on a page (e.g. tokens.css and dist/style.css) is harmless. npm run lint fails on a hex colour in src/**/*.{vue,css} outside tokens.css, and on a var(--nwl-…) that tokens.css doesn't define. Since 1.8.0.

Base styles and cascade layers

Since 2.0.0 all the library's CSS is in three cascade layers, declared in this order at the top of each stylesheet it ships (dist/style.css, nwl-components/base.css, nwl-components/sort/style.css):

@layer nwl.base, nwl.widgets, nwl.components;
  • nwl.base: src/styles/base.css (below);
  • nwl.widgets: src/styles/widgets.css, the widget classes (see "Widgets");
  • nwl.components: the components' styles (scoped or not), sortable.css, and the CSS of bundled dependencies (splitpanes).

The tokens (tokens.css) stay outside the layers: they only define custom properties. An app's own CSS, which is not in a layer, always wins over the library's, whatever the load order or the selectors' specificity: button { … } in an app overrides Button's scoped rules. No !important and no html … prefix are needed. (An app that puts its own CSS in layers must declare them after nwl.components to keep this.)

base.css replaces 1.x's global * { box-sizing: border-box; font-size: 14px; color: white } rule, which is gone. Its selectors are wrapped in :where() (no specificity), and they apply inside the wrapper (.app, the root of Wrapper) only, except two:

  • html: font-size: var(--nwl-text-md) (1rem = 14px, as in 1.x), and body: margin: 0;
  • .app: font (--nwl-font-body, --nwl-text-md) and colour (--nwl-text), inherited by everything inside; box-sizing: border-box, inherited by every element and pseudo-element;
  • headings, small, sub, sup, code, pre and form controls take their parent's font size; form controls and <dialog> their parent's colour, and form controls their parent's font family (since 3.0.0; before, they kept the browser's); links --nwl-link;
  • h1 and h2 are semibold (600), h3 medium (500), since 3.0.0; their size and alignment stay as they are (as above, or the app's);
  • keyboard focus: :focus-visible gets a 2px solid --nwl-focus outline, 2px away (--nwl-focus is --nwl-text, #e8e8e8). Mouse focus shows nothing on buttons; browsers show it on text fields and Chromium on <select>, as they decide what is :focus-visible.

dist/style.css includes base.css. A page without the Vue components (e.g. a Mustache page that wants the same font, colour and focus style) can load it alone, after the tokens:

import 'nwl-components/tokens.css';
import 'nwl-components/base.css'; // webpack 4 too (a copy at the package root)
<link rel="stylesheet" href="/lib/nwl-components/tokens.css">
<link rel="stylesheet" href="/lib/nwl-components/base.css">
<div class="app">…</div>

Outside .app, nothing sets font, colour or box-sizing any more: an app's own markup on a page that loads dist/style.css gets them from the app's CSS (or from being inside .app).

Widgets

Since 2.1.0, src/styles/widgets.css holds class-based widgets for markup that isn't Vue (Mustache pages, the viewers' tool panels); the library's Button uses them too. They are in @layer nwl.widgets and every selector is wrapped in :where(), so an app rule with one class wins over them. Colours, borders and radii come from the semantic tokens.

State is an ARIA attribute, not a class, so screen readers get it too: aria-pressed="true" on a tool button that is on, aria-selected="true" on a selected table row, disabled (or aria-disabled="true" on a link) on a button. The apps' classes (.pressed, .mui-pressed, .selected) don't style the widgets.

Push button (Save, Cancel): 1px --nwl-border-strong outline, --nwl-radius-md, bold, on a <button>, <a>, <select> or <input type="button|submit">. Hover: --nwl-bg-pressed; disabled: opacity .4.

<button class="nwl-push-button">Save</button>

Tool button (a viewer's tool panel): 24px high, 1px --nwl-border, --nwl-radius-sm; it fills its container's width, less its 1px margins, as the apps' div tools did. On a native <button> it is in the tab order with no script. Pressed: aria-pressed="true" gives --nwl-bg-pressed. Hover: --nwl-bg-pressed on a text button, opacity .5 on a button whose only element is an icon (img, svg or .nwl-icon; CSS can't see text, so a button with an icon and text counts as an icon button). .nwl-tool-button--sub: a tool inside a group (no border, 22px).

<div style="flex: 1"><button class="nwl-tool-button" aria-pressed="true">Sag</button></div>
<div style="flex: 1">
  <button class="nwl-tool-button" aria-pressed="false" aria-label="Full screen">
    <img class="nwl-icon" src="/img/fullscreen.svg" alt="">
  </button>
</div>

Icon button: an icon with no border; opacity .5 on hover. It shows no text, so give it an accessible name with aria-label, and an empty alt to its image.

<button class="nwl-icon-button" aria-label="Zoom in"><img class="nwl-icon" src="/img/zoomIn.svg" alt=""></button>

Icon: 16px, aligned with the text (vertical-align: middle), not selectable.

<img class="nwl-icon" src="/img/home.svg" alt="Home">

Text field (<input>, <textarea>): its parent's font size and colour, --nwl-bg-input, 1px --nwl-border, --nwl-radius-sm, no padding (as the apps' .text), placeholder in --nwl-text-placeholder.

<input class="nwl-text-field" placeholder="Project name">

Table (3.4.0): .nwl-table on a plain <table> spaces its columns as Table and SortableTh do: padding-right: 1em on every cell but the last of its row (14px at 14px). ImportFilesDialog's table has it.

<table class="nwl-table"><tr><th>Name</th><th>Size</th></tr></table>

Resized table (3.4.0, resize.css, also in nwl-components/resize/style.css): once a column is resized (.nwl-resized), its cells wrap, even inside a word, and clip what still overflows (text-overflow: clip), with no ellipsis. An app rule outside the layers wins over it whatever the specificity, so an app that puts text-overflow: ellipsis or white-space: nowrap on cells limits that rule to tables that weren't resized:

#projectFiles table:not(.nwl-resized) :is(th, td) { text-overflow: ellipsis; white-space: nowrap; }

Selected row: aria-selected="true" on a <tr> gives --nwl-bg-elevated.

<tr aria-selected="true"><td>axolotl</td></tr>

Floating panel (3.2.0): a box whose header stays while its body scrolls (a viewer's label set or layers panel, a dialog). A flex column: the header (.nwl-panel-header, at least 36px, --nwl-bg-pressed) never shrinks; the body (.nwl-panel-body, 10px padding) takes the rest and scrolls (overflow: auto; min-height: 0). Flex rather than position: sticky: the header is outside the scrolling box, so it needs no offset matching the panel's padding, and the scrollbar runs beside the body only. The panel (--nwl-bg-surface, 1px --nwl-border, --nwl-shadow-2, overflow: hidden) keeps the position and size the app gives it, may be resizable (by the handle below), is dragged by its header with the app's own script, and is never larger than the viewport. It is a flex box: a script that shows it sets style.display = "flex", not "block" (or uses the hidden attribute).

<div class="nwl-panel nwl-panel-resizable" style="position: fixed; width: 400px; height: 300px">
  <div class="nwl-panel-header">
    <button class="nwl-icon-button" aria-label="Close" style="float: right"><img class="nwl-icon" src="/img/close.svg" alt=""></button>
    <b>Layers</b>
  </div>
  <div class="nwl-panel-body">…</div>
</div>

A panel centred with top: 50%; left: 50%; transform: translate(-50%, -50%) keeps its centre when resized, so it grows in every direction. floatingPanel(panel) (from nwl-components, or nwl-components/panel without Vue; on a page with no bundle, /lib/nwl-components/panel/nwl-components-panel.umd.js gives window.nwlComponentsPanel) leaves it centred at rest and pins it by its top-left corner at the first pointerdown on it (pinPanel: transform: none, left / top in px, at the same place). A resize then grows it towards the corner pulled only; the app's drag places its top-left corner (left = pointerX - (pressX - rect.left)).

Resize handle (3.3.0): iOS and iPadOS Safari draw no resize: both corner, so a finger could not resize a panel. floatingPanel(panel) gives a resizable panel (the class nwl-panel-resizable, or a computed resize other than none) a handle of its own, resizablePanel(panel): a <span class="nwl-panel-resize-handle" role="button" tabindex="0" aria-label="Resize"> in its bottom-right corner, a 24 × 24 px hit area above the body and its scrollbar, drawn as an 8px corner mark (--nwl-text-3, --nwl-text on hover). It is dragged with pointer events (mouse, pen, finger: pointer capture, touch-action: none), pins the panel first, and sets its width and height in px (sizePanel): at least 160 × 100, never larger than the viewport nor past its right and bottom edges. Arrow keys resize it by 10px, 50px with Shift. The panel's native resize is turned off (inline resize: none), so there is one corner everywhere. A panel that isn't positioned becomes position: relative; fixed and absolute panels keep theirs. A second call does nothing.

Keyboard focus on the widgets shows base.css's outline (2px --nwl-focus), also outside .app. Links take --nwl-link (hover --nwl-link-hover), both the text colour: keep their underline (the browser's) where they sit in text, so they don't depend on colour alone.

dist/style.css includes the widgets. A page with no bundle links the three files, in this order (microdraw serves node_modules/nwl-components/dist/ as /lib/nwl-components/):

<link rel="stylesheet" href="/lib/nwl-components/tokens.css">
<link rel="stylesheet" href="/lib/nwl-components/base.css">
<link rel="stylesheet" href="/lib/nwl-components/widgets.css">

With a bundler: import 'nwl-components/widgets.css' after the tokens and base (webpack 4 too: a copy at the package root). Storybook's Library/Widgets shows each widget in plain HTML, with its states.

Icons

Every UI icon of nwl-components, BrainBox and microdraw, one SVG file per meaning (73), in dist/icons/<name>.svg. The map in src/icons/README.md lists each name, its meaning, the file it came from and the app copies it replaces.

  • In a page or app CSS: /lib/nwl-components/icons/<name>.svg where the app serves node_modules/nwl-components/dist/ at /lib/nwl-components/ (microdraw does).
  • With a bundler: nwl-components/dist/icons/<name>.svg (webpack 4, which ignores exports; html-loader takes ~nwl-components/dist/icons/<name>.svg), or nwl-components/icons/<name>.svg through exports.
<img class="nwl-icon" alt="undo" src="/lib/nwl-components/icons/undo.svg">

The drawings are the apps' files as they were: fixed white (some with black cut-outs or grey accents), for dark backgrounds. They don't follow the text colour, and many have no viewBox. The library's own components (Nav, Access, PureFiles, the editor components) inline the same files. Storybook's Icons/All shows them all.

To find one to reuse, search by name, meaning or old file name and copy its path: Storybook's Icons/Finder, online at https://neuroanatomy.github.io/nwl-components/?path=/story/icons--finder (or locally with npm run storybook).

Look

The look of the kit (decisions U11–U17 of the UI kit plan): dark greys, off-white text, Source Sans 3 for text and IBM Plex Mono for data, no accent colour (focus and links are the text colour, links underlined in running text), heavier headings, shadows on menus and floating panels. First shipped in 2.4 as the opt-in "2027 theme"; since 3.0.0 it is the only look, with no attribute to set.

Every page that uses the kit links the fonts, after its tokens:

<head>
  <!-- after the page's tokens (dist/style.css, tokens.css or sort/style.css) -->
  <link rel="stylesheet" href="/lib/nwl-components/fonts.css">

fonts.css is a separate stylesheet (nwl-components/fonts.css, dist/fonts.css), not part of dist/style.css. Link it from where it is served (here node_modules/nwl-components/dist/ at /lib/nwl-components/): its font URLs (fonts/<file>.woff2) are relative to it. Don't import it through a bundler that leaves url() alone (webpack 4's css-loader with url: false): the browser would then look for the fonts next to the page. A page that forgets it still renders, in the stack after Source Sans 3 (Lucida Grande, Helvetica, Arial…).

A page that still sets data-nwl-theme="2027" on <html> (the opt-in of 2.4) is fine: nothing in the library reads the attribute any more, so it changes nothing.

| Token | 3.0.0 | |---|---| | --nwl-bg-canvas | #000 | | --nwl-bg-nav | #111 | | --nwl-bg | #1a1a1a | | --nwl-bg-surface | #252525 | | --nwl-bg-elevated | #2e2e2e (menus, selected and hovered rows) | | --nwl-bg-pressed | #404040 (pressed tool buttons, hovered text buttons) | | --nwl-border-subtle | #383838 (dividers only) | | --nwl-border | #777 (3.9 / 3.4 / 3.0:1 on bg / surface / elevated) | | --nwl-border-strong | #999 | | --nwl-text | #e8e8e8 | | --nwl-text-2 | #c0c0c0 | | --nwl-text-3 | #999 | | --nwl-text-placeholder | #999 | | --nwl-text-button | #ddd | | --nwl-focus, --nwl-link, --nwl-link-hover | --nwl-text (#e8e8e8) | | --nwl-font-body | "Source Sans 3", "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, Verdana, sans-serif | | --nwl-font-mono | "IBM Plex Mono", ui-monospace, Menlo, Consolas, monospace | | --nwl-font-display | Roboto, sans-serif (Roboto 100, the wordmark) | | --nwl-shadow-1 | 0 2px 8px rgba(0,0,0,.4): the Autocomplete results | | --nwl-shadow-2 | 0 8px 24px rgba(0,0,0,.5): the editor's floating tool palette, the OntologySelector panel, the ImportFilesDialog box | | --nwl-shadow-sm | 2px 2px 5px #808080 (the 2.x shadow, kept for app CSS) | | --nwl-content-max, --nwl-container-max | 800px, 1020px: TwoCols (user and settings pages) on screens of 1023px and up |

The accent tokens (cyan, defined, unused), status colours, sizes (body 14px), weights, spacing and radii are unchanged from 2.x. No text is darker than #999 (≥ 4.7:1 on every background up to --nwl-bg-elevated). In base.css, form controls inherit the font family and headings are heavier (see "Base styles and cascade layers").

Storybook: Styles/Theme shows every tier 2 token with the contrast of each text/background pair, and the type scale in the three fonts. Its play tests check the contrasts (text 4.5:1, borders and focus 3:1, links 4.5:1; focus and links equal to the text colour), every token's 3.0.0 value (Defaults, also with the old attribute set), that form controls take the body font, and that the fonts load from fonts/. The preview links fonts.css (.storybook/preview-head.html), as an app's page does.

Upgrading from 2.x

  • Link fonts.css on every page (see above). Without it the text falls back to Lucida Grande or Helvetica.
  • The data-nwl-theme="2027" attribute is no longer needed; leaving it does no harm.
  • The 2.x values are gone: the old greys (#222 page, #333 panels, #444 menus, #555 pressed), white text, the browser's font in form controls, 684px content column. An app rule that depended on them must set its own values.
  • Removed tokens: --nwl-grey-22, --nwl-grey-55, --nwl-white-40, --nwl-shadow-md.
  • An app whose pages all opted in to the 2027 theme on 2.4.x sees no change.

Fonts

dist/fonts/ holds the kit's fonts as woff2, Latin subset, only the weights used: Source Sans 3 400, 400 italic and 600; IBM Plex Mono 400; Roboto 100 (the wordmark). They are copied at build from the @fontsource/source-sans-3, @fontsource/ibm-plex-mono and @fontsource/roboto packages (devDependencies). The pages make no request to Google Fonts or any other third party.

All three are under the SIL Open Font License 1.1; the licences ship next to the files (dist/fonts/LICENSE-source-sans-3.txt, LICENSE-ibm-plex-mono.txt, LICENSE-roboto.txt, each the LICENSE of its @fontsource package).

Single File Components

This project makes use of Vue SFCs: Single File Components, that have the .vue extension. They encapsulate the template, logic, and styling of a component in a single file, which makes sense for a library of components. Read more about SFC in the Vue documentation.

Scoped styles

When a tag has the scoped attribute, its CSS will apply to elements of the current component only. This is similar to the style encapsulation found in Shadow DOM.

Read more on https://vuejs.org/api/sfc-css-features.html#scoped-css

The idea here is to encapsulate the appearance of components in the file they are defined, and not let in leak elsewhere.

Composition API

The components make use of the Vue 3 Composition API which make code more reusable and to make it code more compact.

See below how we use composables to define access to the store methods and properties.

Store

In the project, the store is comprised of the modules in src/store.

Said modules are composables that consist of a main function, usually prefixed with use, designed to expose stateful logic to other components.

They contain reactive objects and actions to update them that you can "inject" inside of other components.

The idea is to have a centralized way of performing CRUD updates on the stateful slices of data on which rely other components.

useProject

useProject (src/store/project.js) holds the current project. Since 2.2.0 it is exported from the library entry, import { useProject } from 'nwl-components', and it shares its state with the library's components: the project an app sets is the one Nav (in Header) and the settings pages read. setProject(project) replaces the current project (null clears it); a project without files gets an empty files.list.

To show the settings link (/project/<shortname>/settings) in the Header, provide config and displaySettings, then set the project:

app.provide('config', config);
app.provide('displaySettings', true);
app.runWithContext(() => useProject().setProject(project));

useProject injects config, so call it inside a component's setup or inside the app's runWithContext (after config is provided), not at module level.

Pure components

Pure components, also sometimes called dumb components, doesn't have any logic tied to them: they're just taking care of how the component look and behave according to props. They can emit events, but the listeners should be plugged in the parent components.

The parent components are said to be container components (or sometimes smart components) : this is where you actually define the logic and actions of updating the store or retrieving data from it. They're the one actually connected to the store, defined above.

This concept makes it possible to separate view and business logic. In the project, pure components are prefixed with Pure.

Configuration

The apps give the components their settings through a config object, provided to the whole Vue app (app.provide('config', config)); see .storybook/preview.js for the usual keys (baseURL, usernameField, fetchLabelSets, ...). Optional settings, all off by default:

| Key | Default | Effect | |---|---|---| | showEmbedButton | true | Set to false to hide the "Embed Project" button (and its dialog) in the project settings, for apps that have no /project/:p/embed page. | | beforeSaveProject(project) | none | Called when "Save Changes" is clicked in the project settings, before the project is sent to the server, with the project as edited. Return (or resolve to) false to cancel the save; any other value saves as before. If it throws or rejects, the project is not saved and the page shows "Changes not saved". |

app.provide('config', {
  baseURL: '',
  // ...
  showEmbedButton: false,
  beforeSaveProject: async (project) => {
    // e.g. check the project, ask the user to confirm
    return confirm(`Save ${project.shortname}?`);
  }
});

Since 1.4.0.

Storybook

The components are documented through storybook, where you can see their props and see example use cases (for now we just have 'default' ones). Storybook stories are defined in files with the .stories.js extension. It's a quite handy tool to develop a component in isolation of other components.

Run npm run storybook to launch storybook.

CI builds it on every push to main (after the tests pass) and publishes it on GitHub Pages: https://neuroanatomy.github.io/nwl-components/ (job storybook-pages in .github/workflows/main.yml).

Recommended IDE Setup