adaptive-ui-engine
v1.2.2
Published
UI that reads data and adapts in real time — blur, color, animation speed and glow shift based on emotional context.
Maintainers
Readme
adaptive-ui-engine
A UI engine that adapts in real-time based on context — time of day, cognitive load, and user state.
Documentation · Quick Start · CLI · Contributing
Overview
adaptive-ui-engine is a context-aware UI resolution engine built by Aporia Labs. Instead of static design tokens or simple dark/light mode switching, it continuously evaluates the environment your user is in and resolves the optimal UI tension, spacing, contrast, and interaction density accordingly.
The engine operates across three layers:
- Circadian Layer — adjusts UI based on the time of day, respecting natural human attention cycles
- Cognitive Load Layer — tracks user interaction patterns to estimate mental load
- Decision Matrix — applies your custom rules across 6 distinct contextual dimensions
This makes it suitable for productivity apps, medical dashboards, focus tools, and any interface where UX quality directly affects user performance.
Features
- Circadian Layer — Tension modifier driven by time-of-day curve (dawn, morning, peak, afternoon, dusk, night)
- Cognitive Load Tracking — Real-time estimation of user mental load from interaction events (clicks, keystrokes, scroll velocity, error rate)
- Decision Matrix — 6-context resolution engine (focus, ambient, stress, fatigue, alert, neutral) with weighted scoring
- Matrix Validation CLI — Validate your
matrix.jsonfiles before deployment with--strictand--verboseflags - Zero runtime dependencies — pure Node.js, no framework lock-in
- TypeScript definitions included
- ESM + CJS dual build
Installation
npm install adaptive-ui-engineyarn add adaptive-ui-enginepnpm add adaptive-ui-engineRequirements: Node.js >= 18.0.0
Quick Start
import { AdaptiveUIEngine } from 'adaptive-ui-engine';
import matrix from './matrix.json' assert { type: 'json' };
// Initialize the engine with your decision matrix
const engine = new AdaptiveUIEngine({
matrix,
trackCognition: true,
locale: 'UTC',
});
// Resolve the current UI context
const context = engine.resolve();
console.log(context);
// {
// profile: 'focus',
// tension: 0.74,
// circadianMultiplier: 0.91,
// cognitiveMultiplier: 1.18,
// spacing: 'compact',
// contrast: 'high',
// animationDuration: 120,
// recommendedTheme: 'dark-focused'
// }
// Apply to your CSS variables
document.documentElement.style.setProperty('--ui-tension', context.tension);
document.documentElement.style.setProperty('--ui-spacing', context.spacing);Attaching to a DOM Element
import { AdaptiveUIEngine, attachCognitiveTracking } from 'adaptive-ui-engine';
const engine = new AdaptiveUIEngine({ matrix });
// Attach tracking to an element — engine will observe interactions automatically
const detach = attachCognitiveTracking(engine, document.getElementById('app'));
// Later, clean up
detach();API Reference
new AdaptiveUIEngine(options)
Creates a new engine instance.
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| matrix | DecisionMatrix | required | Your context decision matrix object |
| trackCognition | boolean | false | Enable automatic cognitive load tracking |
| locale | string | 'UTC' | IANA timezone for circadian calculations |
| updateInterval | number | 60000 | How often (ms) to re-evaluate context |
| onContextChange | function | undefined | Callback fired when resolved context changes |
engine.resolve()
Resolves the current UI context based on all active layers.
const context = engine.resolve();Returns: ResolvedContext
interface ResolvedContext {
profile: 'focus' | 'ambient' | 'stress' | 'fatigue' | 'alert' | 'neutral';
tension: number; // 0.0 – 1.0
circadianMultiplier: number; // 0.5 – 1.5
cognitiveMultiplier: number; // 0.5 – 2.0
spacing: 'loose' | 'normal' | 'compact';
contrast: 'low' | 'medium' | 'high';
animationDuration: number; // milliseconds
recommendedTheme: string;
}engine.getCircadianMultiplier()
Returns the raw circadian tension multiplier for the current time.
const circadian = engine.getCircadianMultiplier();
// 0.82 (post-lunch dip, afternoon)The curve follows a natural human alertness model:
| Time Window | Phase | Multiplier Range | |-------------|-------|-----------------| | 05:00 – 07:00 | Dawn | 0.6 – 0.8 | | 07:00 – 10:00 | Morning ramp | 0.8 – 1.1 | | 10:00 – 13:00 | Peak | 1.0 – 1.2 | | 13:00 – 15:00 | Afternoon dip | 0.7 – 0.9 | | 15:00 – 19:00 | Secondary peak | 0.9 – 1.1 | | 19:00 – 23:00 | Dusk wind-down | 0.6 – 0.8 | | 23:00 – 05:00 | Night | 0.5 – 0.65 |
engine.getCognitiveMultiplier()
Returns the current estimated cognitive load multiplier based on tracked interaction data.
const load = engine.getCognitiveMultiplier();
// 1.34 (elevated — user has been clicking rapidly with some errors)Factors tracked (when trackCognition: true or attachCognitiveTracking() is used):
- Click rate per minute
- Keystroke velocity
- Scroll acceleration
- Error / correction events
- Idle periods
- Tab switches (if Page Visibility API is available)
attachCognitiveTracking(engine, element)
Attaches event listeners to the given DOM element. The engine uses these events to continuously update its cognitive load estimate.
import { attachCognitiveTracking } from 'adaptive-ui-engine';
const detach = attachCognitiveTracking(engine, document.body);
// When done (e.g. component unmount):
detach();Returns: () => void — cleanup function that removes all listeners.
Decision Matrix Format
The decision matrix defines how the engine scores and selects a UI profile. Create a matrix.json in your project:
{
"version": 2,
"profiles": {
"focus": {
"description": "Deep work mode — high contrast, minimal distractions",
"spacing": "compact",
"contrast": "high",
"animationDuration": 100,
"theme": "dark-focused",
"rules": {
"circadian": { "min": 0.85, "weight": 0.4 },
"cognitive": { "max": 1.2, "weight": 0.35 },
"hour": { "range": [9, 13], "weight": 0.25 }
}
},
"ambient": {
"description": "Relaxed browsing — loose spacing, soft contrast",
"spacing": "loose",
"contrast": "low",
"animationDuration": 300,
"theme": "light-soft",
"rules": {
"circadian": { "max": 0.75, "weight": 0.5 },
"cognitive": { "max": 0.9, "weight": 0.3 },
"hour": { "range": [19, 23], "weight": 0.2 }
}
},
"stress": {
"description": "High cognitive load detected — reduce visual noise",
"spacing": "loose",
"contrast": "medium",
"animationDuration": 80,
"theme": "neutral-calm",
"rules": {
"cognitive": { "min": 1.5, "weight": 0.7 },
"circadian": { "any": true, "weight": 0.3 }
}
},
"fatigue": {
"description": "Late night or low alertness — high contrast, large text",
"spacing": "loose",
"contrast": "high",
"animationDuration": 200,
"theme": "night-readable",
"rules": {
"hour": { "range": [22, 5], "weight": 0.5 },
"circadian": { "max": 0.65, "weight": 0.3 },
"cognitive": { "min": 1.3, "weight": 0.2 }
}
},
"alert": {
"description": "Time-sensitive mode — maximum clarity",
"spacing": "compact",
"contrast": "high",
"animationDuration": 60,
"theme": "high-alert",
"rules": {
"cognitive": { "min": 1.7, "weight": 0.6 },
"circadian": { "min": 0.9, "weight": 0.4 }
}
},
"neutral": {
"description": "Default balanced mode",
"spacing": "normal",
"contrast": "medium",
"animationDuration": 180,
"theme": "default",
"rules": {
"circadian": { "range": [0.75, 0.95], "weight": 0.5 },
"cognitive": { "range": [0.9, 1.3], "weight": 0.5 }
}
}
},
"fallback": "neutral"
}CLI Usage
The package ships with a validation CLI to check your matrix files before committing them.
Basic Validation
npx validate-matrix matrix.jsonStrict Mode (fails on warnings)
npx validate-matrix matrix.json --strictVerbose Output
npx validate-matrix matrix.json --verboseValidating matrix.json...
[OK] Schema version: 2
[OK] All 6 profiles present (focus, ambient, stress, fatigue, alert, neutral)
[OK] Fallback profile "neutral" exists
[WARN] Profile "ambient": circadian.min not set — will match any circadian value
[OK] Rule weights sum correctly in all profiles
[OK] No overlapping rule ranges detected between adjacent profiles
[OK] animationDuration within acceptable range (50ms – 600ms) for all profiles
Validation complete: 1 warning, 0 errorsGlobal Install
npm install -g adaptive-ui-engine
validate-matrix matrix.json --strict --verboseReact Integration Example
import { useEffect, useState } from 'react';
import { AdaptiveUIEngine, attachCognitiveTracking } from 'adaptive-ui-engine';
import matrix from './matrix.json';
const engine = new AdaptiveUIEngine({ matrix, trackCognition: true });
export function useAdaptiveUI() {
const [context, setContext] = useState(() => engine.resolve());
useEffect(() => {
const engine2 = new AdaptiveUIEngine({
matrix,
trackCognition: true,
updateInterval: 30000,
onContextChange: (ctx) => setContext(ctx),
});
const detach = attachCognitiveTracking(engine2, document.body);
return detach;
}, []);
return context;
}Contributing
Contributions are welcome. Please read our guidelines before opening a pull request.
- Fork the repository: github.com/AporiaLab/adaptive-ui-engine
- Create a feature branch:
git checkout -b feat/your-feature - Write tests for any new behavior
- Run
npm test— all tests must pass - Submit a pull request with a clear description
Development Setup
git clone https://github.com/AporiaLab/adaptive-ui-engine.git
cd adaptive-ui-engine
npm install
npm run build
npm testReporting Issues
Please open an issue at github.com/AporiaLab/adaptive-ui-engine/issues with:
- Node.js version
- Package version
- Minimal reproduction case
Support the Project
If this library has saved you time, consider donating Bitcoin to support continued development:
Bitcoin:
bc1q9wpg3nrg5kywxlkkzsdd4lwkrfgd5j84jdpmjmLicense
MIT License — Copyright (c) 2025 Aporia Labs
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
