MostJS
Lightweight frontend library written with javascript
Install / Use
/learn @e-aub/MostJSREADME
MostJS Framework Documentation
Introduction
MostJS is a lightweight frontend framework that gives you complete control over your code without imposing restrictive patterns. It provides a simple yet powerful approach to building web applications, allowing you to use the framework's utilities while maintaining the freedom to incorporate your preferred JavaScript techniques.
Unlike larger frameworks that dictate how your application should be structured, MostJS provides essential tools for creating reactive web applications while keeping the core API minimal and approachable.
Table of Contents
Getting Started
Installation
You can install MostJS via npm:
# Using npm
npm i @hacker_man/most-js
Using CDN
For direct use in browsers without a build step:
import { anything } from 'https://cdn.jsdelivr.net/npm/@hacker_man/most-js@1.3.0/index.js'
Basic Usage
Here's a simple example showing how to create a counter application:
import { Div, H1, P, Button, useState, render } from 'https://cdn.jsdelivr.net/npm/@hacker_man/most-js@1.3.0/index.js';
const App = () => {
const [count, setCount] = useState(0);
return Div({ className: 'app' }, [
H1({}, ["Hello, MostJS!"]),
P({}, [`Current count: ${count}`]),
Button({
onClick: () => setCount((count)=>{count + 1})
}, ["Increment"])
]);
}
// Render your app to the DOM
render("App", App);
Core Concepts
Virtual DOM
MostJS uses a virtual DOM approach to efficiently update the real DOM. The virtual DOM is a lightweight JavaScript representation of the actual DOM, allowing the framework to perform optimized updates.
Why use a Virtual DOM?
- Performance: By comparing virtual DOM trees before updating the real DOM, MostJS minimizes expensive DOM operations.
- Simplicity: Developers can describe the UI declaratively without worrying about manual DOM manipulations.
At its core, MostJS's virtual DOM nodes are simple JavaScript objects with the following structure:
{
tag: 'div', // HTML tag or component name
props: { /* ... */ }, // Element attributes, event handlers, etc.
children: [], // Child nodes or text content
ref: null // Reference to actual DOM element (populated after rendering)
}
Creating Elements
In MostJS, you create virtual DOM elements using the Create function:
Create(tag, props, ...children)
Parameters:
tag: The HTML tag name (like 'div', 'span', etc.)props: An object containing attributes, event handlers, and other propertieschildren: An array of child elements or text content
Example:
const element = Create('div', {
className: 'container',
id: 'main',
onClick: () => console.log('Clicked!')
}, [
Create('h1', {}, ["Title"]),
Create('p', {}, ["Content"])
]);
Under the hood, the Create function does the following:
- Processes children, converting strings and numbers to text nodes
- Returns a virtual DOM node object with the specified tag, props, and children
Creation Components
MostJS provides creation-components, which are predefined functions that use the Create function internally, making your code cleaner and more readable.
Example:
import { Div, P } from 'https://cdn.jsdelivr.net/npm/@hacker_man/most-js@1.3.0/index.js';
return Div({ className: 'container' }, [
P({ id: "greeting" }, ["Hello world"])
]);
Available Creation Components
MostJS includes creation components for most common HTML elements. Each one follows the same pattern - accepting props and children, then forwarding them to the Create function with the appropriate tag name:
Button: For<button>elementsDiv: For<div>elementsUl: For<ul>elementsLi: For<li>elementsH1throughH6: For heading elementsInput: For<input>elementsP: For paragraph elementsSpan: For<span>elementsLink: For<a>elements (with special routing behavior)Aside: For<aside>elementsHeader: For<header>elementsHr: For<hr>elementsBlockquote: For<blockquote>elementsFooter: For<footer>elementsSection: For<section>elementsLabel: For<label>elementsMain: For<main>elements
Special Case: Link Component
The Link component deserves special attention as it integrates with the MostJS router:
- Requires an
hrefprop - Automatically opens external links in a new tab
- Intercepts click events to trigger client-side routing
- Supports a
renderparameter to control whether the new route should be rendered or just change path
Link(props= {}, children= [], render=true)
render parameter is for choosing to just push the path but not render anything you can acheive same result with
router.pushOnly()
Components
MostJS components are functions that return virtual DOM nodes. Unlike some other frameworks, components in MostJS are pure JavaScript functions, making them intuitive and flexible.
The Component function is used to render and manage reusable components:
Component(componentFn, props, title)
Parameters:
componentFn: The component function to renderprops: Properties to pass to the componenttitle: A unique identifier for the component (required)
Example:
import { Div, Component } from 'https://cdn.jsdelivr.net/npm/@hacker_man/most-js@1.3.0/index.js';
import Sidebar from './Sidebar.js';
import MainContent from './MainContent.js';
const App = () => {
return Div({ className: 'app' }, [
Component(Sidebar, { isCollapsed: false }, "sidebar"),
Component(MainContent, { title: "Welcome" }, "main-content")
]);
};
Under the hood, Component does the following:
- Registers the component function with its title
- Manages component state tracking
- Handles the component stack for context during rendering
- Captures and returns the component's virtual DOM representation
State Management
MostJS provides a simple state management system with the useState fucntion, inspired by React's hook system.
useState
The useState hook allows components to maintain and update state:
const [state, setState] = useState(initialValue);
Parameters:
initialValue: Initial state value (can be a value or function)
Returns:
- An array containing:
state: Current state valuesetState: Function to update the state
Example:
import { Div, Button, useState } from 'https://cdn.jsdelivr.net/npm/@hacker_man/most-js@1.3.0/index.js';
const Counter = () => {
const [count, setCount] = useState(0);
return Div({}, [
`Count: ${count}`,
Button({ onClick: () => setCount(count + 1) }, ["Increment"])
]);
};
How it works:
The useState implementation:
- Identifies the current component from the component stack
- Retrieves or initializes the component's state storage
- Gets or sets the state at the current index
- Provides a setter function that:
- Accepts a new value or a function to compute a new value
- Performs equality checks based on the state type
- Triggers a re-render only when the state actually changes
Handling References
useRef
The useRef hook provides direct access to DOM elements:
const elementRef = useRef(referenceId);
Parameters:
referenceId: A unique string identifier that matches areferenceprop on an element
Returns:
- The actual DOM element
Example:
import { Div, Input, Button, useRef } from 'https://cdn.jsdelivr.net/npm/@hacker_man/most-js@1.3.0/index.js';
const SearchField = () => {
const inputRef = useRef("search-input");
const focusInput = () => {
inputRef.focus();
};
return Div({}, [
Input({
reference: "search-input",
placeholder: "Search..."
}, []),
Button({ onClick: focusInput }, ["Focus Search"])
]);
};
How it works:
The reference system in MostJS:
- Uses a global map to store references to DOM elements
- Requires elements to have a
referenceprop with a unique identifier - During element creation, elements with a
referenceprop are added to the refs map - The
useReffunction retrieves an element from therefsmap using the provided identifier.
If the reference is not found, it returnsundefined.
This can happen when elements are rendered conditionally and the reference was never attached.
