onekit-js
v3.1.8
Published
Javascript lib
Readme
OneKit JS – Full Documentation (Beginner → Advanced)
A complete, fully expanded documentation covering all features of OneKit JS.
Installation
NPM Install
npm install onekit-jsImporting into Your Project
ECMAScript Modules (Vite, Webpack, CRA, Next.js)
import { ok, reactive } from 'onekit-js';CDN / UMD
<script src="./node_modules/onekit-js/dist/onekit.js"></script>
<script>
const { ok, reactive } = OneKit;
</script>Basic Usage
import { ok, reactive, watch } from 'onekit-js';
const state = reactive({ count: 0 });
watch(state, 'count', (next) => ok('#count').text(next));
ok('#inc').click(() => state.count++);
ok('#dec').click(() => state.count--);HTML:
<div>Count: <span id="count">0</span></div>
<button id="inc">+</button>
<button id="dec">-</button>Element Selectors (Beginner → Advanced)
OneKit provides a simple universal selector utility: ok().
Basic Selectors
ok('#id')
ok('.class')
ok('tag')Select Multiple
ok('.item').each(el => console.log(el));Chainable Methods
ok('#title')
.text('Hello')
.class('active')
.css({ color: 'red' })
.click(() => console.log('clicked'));Supported Methods
.text().html().append().prepend().remove().hide()/.show().class()/.remove_class().css().val()(for inputs).attr().on()/.click()/.hover()
Reactive State
const state = reactive({ name: 'OneKit', count: 0 });
watch(state, 'name', (next, prev) => {
console.log(`Name changed: ${prev} → ${next}`);
});Deep nesting works automatically:
const app = reactive({ user: { profile: { age: 20 } } });
watch(app.user.profile, 'age', console.log);DOM Utilities
Add class
ok('#box').class('active');Remove class
ok('#box').remove_class('active');Toggle class
ok('#box').toggle_class('active');Attributes & CSS
ok('#box').attr('data-x', 1);
ok('#box').css({ width: '100px', background: 'red' });Form Utilities
ok('#form').form_data();Component System
Define a Component
register('counter-box', {
template: `
<div>
<h3>{{title}}</h3>
<p>Count: {{count}}</p>
<button onclick="this.increase()">+</button>
</div>
`,
props: { title: 'Default Title' },
data: () => ({ count: 0 }),
methods: {
increase() {
this.count++;
this.update();
}
}
});Mount Component
mount(create('counter-box', { title: 'My Counter' }), '#app');Virtual DOM
const oldNode = createElement('p', {}, 'Hello');
const newNode = createElement('p', {}, 'Updated');
const el = render(oldNode);
patch(el, newNode, oldNode);Benefits:
- Fast diffing
- Efficient rendering
- Auto cleanup
API Requests
get('/api/users').then(res => console.log(res.data));
post('/api/save', { name: 'John' });
put('/api/update/1', { age: 21 });
delete('/api/user/1');Supports:
- global interceptors
- error catching
- timeouts
Storage
Local Storage
localStorage.set('user', { name: 'John' });
localStorage.get('user');
localStorage.remove('user');Session Storage
sessionStorage.set('token', 'abc');Router
OneKit provides a flexible client-side router for handling navigation and routing in single-page applications.
Basic Usage
import { router } from 'onekit-js';
// Add routes with handlers
router.addRoute({ path: '/home', handler: showHome });
router.addRoute({ path: '/about', handler: showAbout });
// Navigate programmatically
router.navigate('/home');
// Get current path
const currentPath = router.getCurrentPath();Route Definition
interface Route {
path: string;
component?: any; // For component-based routing
handler?: () => void; // For function-based routing
}Advanced Features
Route Parameters
// Define route with parameters
router.addRoute({ path: '/user/:id', handler: showUser });
// Access parameters in handler
function showUser() {
const pathParts = router.getCurrentPath().split('/');
const userId = pathParts[pathParts.length - 1];
// Load user data for userId
}Route Guards
// Add route with guard
router.addRoute({
path: '/admin',
handler: showAdmin,
guard: () => checkAdminAccess()
});
function checkAdminAccess() {
// Return true if user has admin access
return user.isAdmin;
}Nested Routes
// Parent route
router.addRoute({ path: '/dashboard', handler: showDashboard });
// Child routes
router.addRoute({ path: '/dashboard/profile', handler: showProfile });
router.addRoute({ path: '/dashboard/settings', handler: showSettings });Navigation Methods
Programmatic Navigation
// Navigate to a route
router.navigate('/home');
// Navigate with query parameters
router.navigate('/search?q=javascript');
// Navigate with state
router.navigate('/product/123', { from: 'catalog' });Link Handling
// Handle navigation links
ok('a[data-route]').on('click', (e) => {
e.preventDefault();
const path = e.target.getAttribute('data-route');
router.navigate(path);
});
// HTML with data-route attributes
<nav>
<a href="#" data-route="/home">Home</a>
<a href="#" data-route="/about">About</a>
<a href="#" data-route="/contact">Contact</a>
</nav>Route Matching
Exact Matching
router.addRoute({ path: '/home', handler: showHome }); // Exact matchWildcard Routes
// Catch-all route for 404 handling
router.addRoute({ path: '*', handler: show404 });Integration with Components
// Component-based routing
router.addRoute({
path: '/counter',
component: 'counter-component'
});
// Mount component when route is activated
function showCounter() {
mount(create('counter-component'), '#app');
}Browser History Integration
// Listen for browser back/forward buttons
window.addEventListener('popstate', () => {
const path = window.location.pathname;
router.navigate(path, { replace: true });
});
// Update browser history
router.navigate('/new-path', { push: true });Example SPA Implementation
import { router, ok } from 'onekit-js';
// Route handlers
function showHome() {
ok('#app').html(`
<h1>Home</h1>
<p>Welcome to our SPA!</p>
<nav>
<a href="#" data-route="/about">About</a>
<a href="#" data-route="/contact">Contact</a>
</nav>
`);
}
function showAbout() {
ok('#app').html(`
<h1>About</h1>
<p>Learn more about us.</p>
<a href="#" data-route="/home">Back to Home</a>
`);
}
function show404() {
ok('#app').html(`
<h1>404 - Page Not Found</h1>
<a href="#" data-route="/home">Go Home</a>
`);
}
// Set up routes
router.addRoute({ path: '/home', handler: showHome });
router.addRoute({ path: '/about', handler: showAbout });
router.addRoute({ path: '*', handler: show404 });
// Handle navigation
ok('body').on('click', '[data-route]', (e) => {
e.preventDefault();
router.navigate(e.target.getAttribute('data-route'));
});
// Initialize app
router.navigate('/home');Utilities
debounce
debounce(() => console.log('done'), 500);throttle
throttle(() => console.log('scroll'), 200);deepClone
const clone = deepClone(obj);generateId
generateId();Animations
ok('#box').fade_in(300);
ok('#box').fade_out(300);
ok('#box').slide_up(400);
ok('#box').slide_down(400);
ok('#box').bounce(800);Template Syntax (okjs)
const view = okjs`
[div]
[h1]Title[/h1]
[button onclick=${() => alert('Hi')}]Click[/button]
[/div]
`;Supports:
- loops
- conditions
- dynamic props
Template Directives
OneKit provides powerful template directives for declarative DOM manipulation and reactive updates.
ok-if Directive
Conditionally show/hide elements based on reactive state.
<div ok-if="user.loggedIn">
<p>Welcome, {{user.name}}!</p>
</div>const state = reactive({ user: { loggedIn: false, name: 'John' } });ok-for Directive
Render lists with automatic DOM updates.
<ul>
<li ok-for="item in items">{{item.name}}</li>
</ul>const state = reactive({
items: [
{ name: 'Item 1' },
{ name: 'Item 2' }
]
});With index:
<li ok-for="(item, index) in items">{{index + 1}}. {{item.name}}</li>ok-bind Directive
Bind reactive data to element attributes.
<input ok-bind:value="message" />
<img ok-bind:src="imageUrl" ok-bind:alt="imageAlt" />
<div ok-bind:class="dynamicClass"></div>
<div ok-bind:style="dynamicStyle"></div>const state = reactive({
message: 'Hello',
imageUrl: 'image.jpg',
imageAlt: 'An image',
dynamicClass: 'active',
dynamicStyle: { color: 'red' }
});ok-model Directive
Two-way data binding for form inputs.
<input ok-model="name" type="text" />
<textarea ok-model="bio"></textarea>
<select ok-model="country">
<option value="us">USA</option>
<option value="ca">Canada</option>
</select>
<input ok-model="agree" type="checkbox" />const form = reactive({
name: '',
bio: '',
country: 'us',
agree: false
});ok-on Directive
Attach event listeners with reactive expressions.
<button ok-on:click="increment()">+</button>
<button ok-on:click.prevent="submitForm()">Submit</button>
<input ok-on:input="updateValue($event.target.value)" />const state = reactive({ count: 0 });
function increment() {
state.count++;
}
function submitForm() {
// Handle form submission
}
function updateValue(value) {
state.inputValue = value;
}Event modifiers:
.prevent- callsevent.preventDefault().stop- callsevent.stopPropagation()
ok-show Directive
Show/hide elements with CSS display (similar to ok-if but uses visibility).
<div ok-show="isVisible">
This content can be shown/hidden
</div>const state = reactive({ isVisible: true });Reactive Integration
Directives automatically react to state changes:
<div ok-if="showDetails" ok-bind:class="theme">
<h2 ok-bind="title"></h2>
<p ok-for="detail in details">{{detail}}</p>
</div>const app = reactive({
showDetails: true,
theme: 'dark-theme',
title: 'Dynamic Title',
details: ['Detail 1', 'Detail 2']
});
// Changes automatically update the DOM
app.showDetails = false;
app.details.push('Detail 3');Accessibility
announce('Item added');
trapFocus(modalElement);Features:
- Screen reader announcements
- Focus trapping
- Auto ARIA labels
Web Components
class MyElement extends HTMLElement {
connectedCallback() {
this.innerHTML = '<p>Hello</p>';
}
}
customElements.define('my-element', MyElement);Theme System
ok('body').class('theme-dark');Automatically stores theme in localStorage.
Dependency Injection
di.register('logger', () => ({ log: msg => console.log(msg) }));
const logger = di.resolve('logger');
logger.log('Hello');Plugin System
ok.extend('highlight', function(color='yellow'){ this.css({ background: color }); });
ok('.item').highlight('pink');Error Handling
try {
riskyFunction();
} catch (error) {
errorHandler(error);
}OneKit provides:
- global error hooks
- error boundaries in components
- safe DOM writes
Forms
const data = ok('#register').form_data();
console.log(data);Automatically extracts:
- inputs
- selects
- checkboxes
- files
Build & Development
Vite Development
npm run dev:viteNormal Development
npm run devBuild
npm run buildTesting
npm testSupports:
- Tree-shaking
- ES Modules
- TypeScript mappings
License
ISC License
