mithril-materialized
v4.0.0
Published
Material Design components for Mithril.js with no external JavaScript dependencies.
Maintainers
Readme
mithril-materialized
Typed Mithril components with Material Design foundations, accessible interaction patterns, and no external JavaScript UI runtime.
Documentation · npm · Changelog · Repository
Version 4 release
Version 4 adds the Compact Minimal design preset and standardizes field layout across the library. It also includes Dialog and AlertDialog abstractions, typed menus, CommandPalette, SnackbarQueue, Avatar and AvatarGroup, Skeleton and EmptyState, VirtualList, and virtualized DataTable rows.
Breaking layout change
SearchSelect, FileUpload, LikertScale, Rating, SingleRangeSlider, and DoubleRangeSlider now default their outer wrapper to col s12. Pass className: '' for a classless inline layout, or provide an explicit width such as className: 'col s6'.
Compact Minimal preset
import 'mithril-materialized/index.css';
import 'mithril-materialized/presets/compact-minimal.css';
document.documentElement.dataset.mmPreset = 'compact-minimal';The preset compacts typography, controls, forms, menus, navigation, dialogs, tables, pickers, feedback, and display components. Light, dark, and automatic color themes remain independent of density.
Installation
npm install mithril mithril-materializedSupported Components
Components marked with an * are not included in the original materialize-css library.
- Buttons
- Button
- FlatButton
- RoundButton
- SubmitButton
- Inputs
- TextInput
- TextArea
- AutoComplete
- UrlInput
- EmailInput
- NumberInput
- ColorInput
- RangeInput* (with vertical, double-thumb support, and smart tooltip display)
- Chips
- Pickers
- DatePicker (with optional week numbers and date range selection)*
- TimePicker (with inline mode and switchable AM/PM/24h)*
- Selections
- Select
- SearchSelect*, a searchable select dropdown (supports async remote loading via
loadOptions) - Options
- RadioButtons (HTML labels/descriptions require explicit
allowHtml: true) - Switch
- Dropdown
- ToggleButton* (single toggle button component)
- Collections
- Basic, Link and Avatar Collections
- Collapsible or accordion
- Theme & Upload
- ThemeSwitcher* (light/dark/auto theme switching)
- ThemeToggle* (simple light/dark toggle)
- FileUpload* (drag-and-drop with validation and preview)
- Navigation
- Sidenav (responsive navigation drawer)
- Breadcrumb* (navigation path indicator)
- Wizard/Stepper* (multi-step process guidance)
- Others
- Dialog and AlertDialog* (accessible confirmation and destructive-action dialogs)
- Menu and ContextMenu* (typed action menus with keyboard navigation)
- CommandPalette* (searchable keyboard command launcher)
- ModalPanel
- MaterialBox
- Carousel
- Pagination
- PaginationControls*
- Parallax
- Toast* (notifications with optional actions)
- SnackbarQueue* (ordered notifications with actions and accessible announcements)
- Badge* (labels and notification indicators)
- Layout & Display
- Avatar and AvatarGroup* (identity images, initials, icons, and grouped overflow)
- Skeleton and EmptyState* (loading and no-content states)
- Masonry* (Pinterest-style responsive grid layout)
- ImageList* (responsive image galleries with various layouts)
- Timeline* (vertical timeline with events and milestones)
- Rating*
- Rating (configurable range, step size, density, and custom icons)
- Data & Tables
- DataTable* (sorting, filtering, pagination, selection, and optional fixed-height virtualization)
- VirtualList* (fixed-height virtualized rendering for large lists)
- TreeView* (hierarchical data with expand/collapse, selection, and customizable icons)
- Additional
- Label
- HelperText
- CodeBlock
- Icon, a simple wrapper for creating icons using material-icons font
- MaterialIcon, for creating the close/clear and caret as SVG
Usage
Online flems examples: FlatButton and Select.
Quick Start
Install the package:
npm install mithril mithril-materializedImport the CSS (optional, for Material Design styling):
import 'mithril-materialized/index.css';Use components in your app:
import m from 'mithril'; import { TextInput, Button, RangeInput, DatePicker, DataTable, TreeView, ThemeToggle, FileUpload, Sidenav, Breadcrumb, Wizard, Masonry, Timeline, ImageList } from 'mithril-materialized'; const MyComponent = () => ({ view: () => m('.container', [ // Theme toggle in header m('nav', [ m('.nav-wrapper', [ m('.right', m(ThemeToggle)) ]) ]), // Breadcrumb navigation m(Breadcrumb, { items: [ { text: 'Home', href: '/' }, { text: 'Products', href: '/products' }, { text: 'Details', active: true } ] }), // Form inputs m(TextInput, { label: 'Your name', onchange: (value) => console.log(value) }), // Enhanced range sliders with smart tooltips m(RangeInput, { label: 'Volume', min: 0, max: 100, valueDisplay: 'auto', // Show tooltip on drag onchange: (value) => console.log('Volume:', value) }), m(RangeInput, { label: 'Price Range', min: 0, max: 1000, minmax: true, minValue: 100, maxValue: 500, valueDisplay: 'always', // Always show values onchange: (min, max) => console.log('Range:', min, '-', max) }), m(RangeInput, { label: 'Vertical Slider', min: 0, max: 100, vertical: true, height: '200px', valueDisplay: 'auto', tooltipPos: 'right', onchange: (value) => console.log('Vertical:', value) }), // Enhanced DatePicker with range selection m(DatePicker, { label: 'Event Date', helperText: 'Select a single date', format: 'mmmm d, yyyy', onchange: (value) => console.log('Date:', value) }), m(DatePicker, { dateRange: true, label: 'Project Timeline', helperText: 'Select start and end dates', format: 'mmmm d, yyyy', minDateRange: 1, maxDateRange: 30, onchange: (value) => console.log('Date range:', value) }), m(Button, { label: 'Submit', onclick: () => alert('Hello!') }), // File upload m(FileUpload, { accept: 'image/*', multiple: true, onFilesSelected: (files) => console.log(files) }), // TreeView for hierarchical data m(TreeView, { data: [ { id: 'root', label: 'Project Root', expanded: true, children: [ { id: 'src', label: 'src/' }, { id: 'docs', label: 'docs/' }, ] } ], selectionMode: 'multiple', iconType: 'caret', showConnectors: true, onselection: (selectedIds) => console.log('Selected:', selectedIds) }), // Layout components m(Masonry, { items: [ { id: 1, title: 'Card 1', content: 'Short content' }, { id: 2, title: 'Card 2', content: 'Much longer content...' }, { id: 3, title: 'Card 3', content: 'Medium content' } ], columnWidth: 250, gap: 16, renderItem: (item) => m('.card', [ m('.card-content', [ m('span.card-title', item.title), m('p', item.content) ]) ]) }), m(Timeline, { events: [ { id: 1, title: 'Project Started', date: '2024-01-15', description: 'Initial project kickoff', type: 'milestone' }, { id: 2, title: 'First Release', date: '2024-03-20', description: 'Released version 1.0', type: 'release' } ] }), m(ImageList, { images: [ { src: '/image1.jpg', alt: 'Image 1' }, { src: '/image2.jpg', alt: 'Image 2' }, { src: '/image3.jpg', alt: 'Image 3' } ], layout: 'masonry', // 'grid' | 'masonry' | 'quilted' cols: 3 }) ]) });
Integration with Build Tools
Webpack/Vite/Parcel: The library works out-of-the-box with modern bundlers.
CSS Framework Integration: You can use the components with any CSS framework. The included CSS provides Material Design styling, but you can override it with your own styles.
TypeScript: Full TypeScript support with comprehensive type definitions included.
See the live documentation for examples and component APIs.
Note: The date range picker is now fully implemented with comprehensive validation and formatting support.
Contributing
We welcome contributions! Priority areas for community involvement:
- Usage: Accessibility improvements, performance optimizations
- Documentation: Examples, guides, API documentation
- Testing: Unit tests, visual regression tests, browser compatibility
See our contributing guide for detailed information.
Button semantics
Button, LargeButton, SmallButton, and FlatButton render native <button> elements for actions. Use href when the component represents navigation; it then renders an <a> without a button type.
m(Button, { label: 'Save', onclick: save });
m(Button, { label: 'Read the docs', href: '/docs' });Migration: If you relied on the previous anchor markup for navigation, add
href. Action buttons now correctly use native button semantics.
Async SearchSelect
Use loadOptions(query) to retrieve options remotely. The component displays loading, empty, and error states; i18n customizes their messages.
m(SearchSelect<number>, {
label: 'Remote search',
checkedId: selectedIds,
options: [],
loadOptions: (query) => fetchOptions(query),
onchange: (ids) => {
selectedIds = ids;
},
});SearchSelect uses combobox/listbox ARIA roles and supports ArrowDown, ArrowUp, Enter/Space, and Escape.
Feedback and empty states
import { EmptyState, Skeleton, snackbar } from 'mithril-materialized';
snackbar({
message: 'Project deleted',
dismissible: true,
action: { label: 'Undo', onclick: restoreProject },
});
m(Skeleton, { shape: 'text', count: 3 });
m(Skeleton, { shape: 'circular', width: 48, margin: '0 0 16px' });
m(EmptyState, {
title: 'No projects yet',
description: 'Create a project to start organizing your work.',
primaryAction: { label: 'Create project', onclick: createProject },
});Command palette
Create the generic component once and keep it stable between redraws.
import { CommandPalette } from 'mithril-materialized';
const ProjectCommands = CommandPalette<'new' | 'settings'>();
m(ProjectCommands, {
enableGlobalShortcut: true,
commands: [
{ id: 'new', label: 'New project', group: 'Project', execute: createProject },
{ id: 'settings', label: 'Open settings', execute: openSettings },
],
});Avatars
Images fall back once to explicit text, deterministic initials, or an icon. Use alt: '' for decorative avatars and native links or buttons for interaction.
import { Avatar, AvatarGroup } from 'mithril-materialized';
m(Avatar, { src: user.photo, name: user.name, alt: user.name });
m(AvatarGroup, { max: 3, totalCount: 8, ariaLabel: 'Project members' }, [
m(Avatar, { name: 'Ada Lovelace', alt: 'Ada Lovelace' }),
m(Avatar, { name: 'Grace Hopper', alt: 'Grace Hopper' }),
m(Avatar, { name: 'Katherine Johnson', alt: 'Katherine Johnson' }),
]);Large-data virtualization
Both APIs require fixed item/row heights; variable-height virtualization is intentionally unsupported.
import { DataTable, VirtualList } from 'mithril-materialized';
const UserList = VirtualList<User>();
m(UserList, {
items: users,
height: 400,
itemHeight: 48,
overscan: 2,
getItemKey: (user) => user.id,
renderItem: (user) => user.name,
});
m(DataTable<User>, {
data: users,
columns,
getRowKey: (user) => user.id,
virtualization: { viewportHeight: 480, rowHeight: 48, overscan: 2 },
});Build instructions
This pnpm workspace contains the published library in packages/lib and the documentation application in packages/example.
pnpm install
pnpm startUse pnpm test and pnpm build from packages/lib for package validation and distribution output.
Styling and CSS
CSS Usage
The library includes carefully crafted CSS that provides Material Design styling without external dependencies. You can import the ready-to-use CSS:
import 'mithril-materialized/index.css';Important: The CSS styling is completely independent of the original materialize-css. This means:
- No conflicting styles from materialize-css
- Smaller CSS bundle size
- Custom optimizations for better performance
- No external font dependencies
Modular CSS architecture
Tree-shakable CSS modules for optimal bundle sizes! Import only the CSS you need:
// Option 1: Import everything (64KB total)
import 'mithril-materialized/index.css';
// Option 2: Import only what you need (modular approach)
import 'mithril-materialized/core.css'; // Essential styles (18KB)
import 'mithril-materialized/forms.css'; // Form components only
import 'mithril-materialized/components.css'; // Interactive components
// Option 3: Advanced components only when needed
import 'mithril-materialized/pickers.css'; // Date/Time pickers
import 'mithril-materialized/advanced.css'; // Carousel, sidenav, etc.
import 'mithril-materialized/utilities.css'; // Badges, icons, cardsCSS Modules Available:
core.css(18KB) - Essential foundation (normalize, grid, typography, variables)components.css- Interactive components (buttons, dropdowns, modals, tabs)forms.css- All form components (inputs, selects, switches, file upload)pickers.css- Date and time picker componentsadvanced.css- Specialized components (carousel, sidenav, navbar, preloader)utilities.css- Visual utilities (badges, cards, icons, toast, chips)
Compact Minimal preset
The optional Compact Minimal preset provides a denser, low-elevation desktop-tool presentation without changing component APIs or the default spacious design:
import 'mithril-materialized/index.css';
import 'mithril-materialized/presets/compact-minimal.css';
document.documentElement.dataset.mmPreset = 'compact-minimal';Density and visual style remain independent of color. Combine the preset with light, dark, or automatic theme selection, and remove the attribute to return to the default:
delete document.documentElement.dataset.mmPreset;The preset covers buttons, form controls, selects, menus, navigation, dialogs, CommandPalette, DataTable, VirtualList, Snackbar, Avatar, Skeleton, and EmptyState. Coarse pointers automatically retain larger control and menu targets. Its semantic typography scale also reduces heading, body, label, and control sizes while preserving the existing font family and readable hierarchy.
Virtualization remains runtime geometry, so configure its fixed height explicitly:
m(DataTable, {
data,
columns,
virtualization: { viewportHeight: 360, rowHeight: 36, overscan: 2 },
});Override semantic tokens after the preset import when product-specific tuning is needed:
[data-mm-preset="compact-minimal"] {
--mm-control-height: 34px;
--mm-row-height: 38px;
--mm-heading-2-font-size: 1.875rem;
--mm-surface-radius: 2px;
}Form grid convention
Field-like controls default their outer wrapper to col s12, including SearchSelect, FileUpload, LikertScale, Rating, SingleRangeSlider, and DoubleRangeSlider. Pass className to replace that width:
m('.row', [
m(TextInput, { className: 'col s6', label: 'Name' }),
m(SearchSelect, { className: 'col s6', options }),
]);ToggleButton and ToggleGroup remain inline controls. Migration note: starting with the next major release, the six components listed above gain the full-width default. Consumers that relied on their previous classless layout should pass className: ''; use an explicit grid class such as className: 'col s6' when a fixed width is intended.
Bundle Size Optimization:
- Full bundle: 64KB gzipped (44KB JS + 20KB CSS)
- Modular approach can reduce CSS by 30-50%
- Use only
core.css+ specific modules for your use case
Dark theme support
Built-in dark theme support with CSS custom properties:
import { ThemeManager, ThemeSwitcher } from 'mithril-materialized';
// Programmatic theme control
ThemeManager.setTheme('dark'); // 'light' | 'dark' | 'auto'
ThemeManager.toggle(); // Toggle between light/dark
ThemeManager.getTheme(); // Get current theme
// UI Components
m(ThemeSwitcher, {
onThemeChange: (theme) => console.log('Theme:', theme)
});
m(ThemeToggle); // Simple toggle buttonCSS Custom Properties: All colors use CSS variables for runtime theme switching:
:root {
--mm-primary-color: #26a69a;
--mm-background-color: #ffffff;
--mm-text-primary: rgba(0, 0, 0, 0.87);
}
[data-theme="dark"] {
--mm-primary-color: #80cbc4;
--mm-background-color: #121212;
--mm-text-primary: rgba(255, 255, 255, 0.87);
}SASS Usage
For advanced customization, you can use the SASS source files directly:
// Import all SASS components
@import 'mithril-materialized/sass/materialize.scss';
// Or import individual components
@import 'mithril-materialized/sass/components/buttons';
@import 'mithril-materialized/sass/components/forms';
@import 'mithril-materialized/sass/components/grid';SASS Variables: You can customize colors, spacing, and other design tokens by overriding SASS variables before importing:
// Customize Material Design variables
$primary-color: #2196F3;
$secondary-color: #FF9800;
// Then import the library
@import 'mithril-materialized/sass/materialize.scss';Custom Styles
ModalPanel overrides
ModalPanel now exposes stable slot classes and --mm-modal-* tokens so you can override styles without relying on broad selectors.
Slot classes:
.mm-modal-overlay.mm-modal-surface.mm-modal-close-button.mm-modal-content.mm-modal-content-with-close.mm-modal-title.mm-modal-footer
Common tokens:
:root {
--mm-modal-overlay-background: rgba(0, 0, 0, 0.5);
--mm-modal-overlay-z-index: 1002;
--mm-modal-z-index: 1003;
--mm-modal-width: 75%;
--mm-modal-max-width: 75%;
--mm-modal-max-height: 85%;
--mm-modal-border-radius: 4px;
--mm-modal-shadow: 0 24px 38px 3px rgba(0, 0, 0, 0.14),
0 9px 46px 8px rgba(0, 0, 0, 0.12),
0 11px 15px -7px rgba(0, 0, 0, 0.2);
--mm-modal-content-padding: 24px;
--mm-modal-content-padding-top-with-close: 48px;
--mm-modal-title-margin: 0 0 20px 0;
--mm-modal-footer-padding: 4px 6px;
--mm-modal-footer-border-top: 1px solid var(--mm-border-color, rgba(160, 160, 160, 0.2));
--mm-modal-close-top: 8px;
--mm-modal-close-right: 8px;
--mm-modal-close-padding: 8px;
--mm-modal-close-z-index: 2;
--mm-modal-bottom-sheet-max-height: var(--mm-modal-max-height, 85%);
--mm-modal-bottom-sheet-border-radius: 8px 8px 0 0;
}Backward compatibility note:
- Existing
.modaland.modal-*classes are retained. - Existing
classNameusage onModalPanelstill works. - If you previously used
!importantto beat inline styles, prefer these slot classes and tokens first.
The library includes these additional styles for enhanced functionality:
/* For the switch */
.clear,
.clear-10,
.clear-15 {
clear: both;
/* overflow: hidden; Precaution pour IE 7 */
}
.clear-10 {
margin-bottom: 10px;
}
.clear-15 {
margin-bottom: 15px;
}
span.mandatory {
margin-left: 5px;
color: red;
}
label+.switch {
margin-top: 1rem;
}
/* For the color input */
input[type='color']:not(.browser-default) {
margin: 0px 0 8px 0;
/** Copied from input[type=number] */
background-color: transparent;
border: none;
border-bottom: 1px solid #9e9e9e;
border-radius: 0;
outline: none;
height: 3rem;
width: 100%;
font-size: 16px;
padding: 0;
-webkit-box-shadow: none;
box-shadow: none;
-webkit-box-sizing: content-box;
box-sizing: content-box;
-webkit-transition: border 0.3s, -webkit-box-shadow 0.3s;
transition: border 0.3s, -webkit-box-shadow 0.3s;
transition: box-shadow 0.3s, border 0.3s;
transition: box-shadow 0.3s, border 0.3s, -webkit-box-shadow 0.3s;
}
/* For the options' label */
.input-field.options > label {
top: -2.5rem;
}
/* For the code block */
.codeblock {
margin: 1.5rem 0 2.5rem 0;
}
.codeblock > div {
margin-bottom: 1rem;
}
.codeblock > label {
display: inline-block;
}