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 🙏

© 2024 – Pkg Stats / Ryan Hefner

ajo

v0.1.21

Published

ajo is a JavaScript view library for building user interfaces

Downloads

22

Readme

Ajo

Ajo is a lightweight and efficient JavaScript library for building dynamic user interfaces. It combines the best ideas from Incremental DOM and Crank.js to offer a unique approach to UI development.

Key Features

  • Efficient in-place DOM updates
  • Generator-based state management
  • JSX syntax support
  • Lightweight design
  • Server-Side Rendering (SSR) support

Quick Start

Installation

npm install ajo

Basic Usage

/** @jsx h */
import { h, render } from 'ajo'

const Greeting = ({ name }) => <h1>Hello, {name}!</h1>

function* Counter() {
  let count = 0

  const increment = () => {
    count++
    this.render()
  }

  while (true) {
    yield (
      <>
        <p>Count: {count}</p>
        <button set:onclick={increment}>Increment</button>
      </>
    )
  }
}

function* App() {
  while (true) {
    yield (
      <>
        <Greeting name="Ajo Developer" />
        <Counter />
      </>
    )
  }
}

render(<App />, document.body)

Core Concepts

HTML Attributes vs DOM Properties

Ajo distinguishes between HTML attributes and DOM properties. Use regular attributes for HTML attributes, and the set: prefix to set DOM properties directly:

<input
  type="text"
  id="username"
  class="form-input"
  placeholder="Enter username"
  set:value={inputValue}
  set:onclick={handleClick}
  set:disabled={isDisabled}
/>

In this example:

  • type, id, class, and placeholder are regular HTML attributes.
  • set:value, set:onclick, and set:disabled are DOM properties set directly on the element.

Special Attributes

Ajo uses special attributes for optimization and control:

  • key: For efficient list rendering
  • skip: To prevent rendering of child elements
  • memo: For memoization of components or elements
  • ref: To get references to DOM nodes or component instances
<TodoItem
  key={todo.id}
  memo={[todo.completed]}
  ref={el => el ? todosRefs.add(el) : todosRefs.delete(todo.id)}
>
  <TodoTitle>{todo.title}</TodoTitle>
  <div set:innerHTML={marked(todo.content)} skip></div>
</TodoItem>

Stateless and Stateful Components

Stateless components are simple functions:

const Greeting = ({ name }) => <h1>Hello, {name}!</h1>

Stateful components use generator functions:

function* Counter() {
  let count = 0
  while (true) {
    yield (
      <button set:onclick={() => { count++; this.render(); }}>
        {count}
      </button>
    )
  }
}

State handling in Ajo is straightforward:

  • State is managed using regular variables within the generator function.
  • The this.render() method triggers a re-render when state changes.
  • Each iteration of the generator function represents a new render cycle.
function* Timer() {
  let seconds = 0
  const intervalId = setInterval(() => {
    seconds++
    this.render()  // Trigger a re-render
  }, 1000)

  try {
    while (true) {
      yield <div>Seconds: {seconds}</div>
    }
  } finally {
    clearInterval(intervalId)  // Cleanup
  }
}

Component Lifecycle

Stateful components have a simple lifecycle:

  • Initialization: When the generator is first called
  • Rendering: Each time the generator yields
  • Cleanup: When the generator's finally block is executed
function* LifecycleDemo() {
  console.log('Initialized')
  try {
    while (true) {
      console.log('Rendering')
      yield <div>Hello, Ajo!</div>
    }
  } finally {
    console.log('Cleanup')
  }
}

attr: Attributes

Use the attr: prefix to add HTML attributes to a component's root element:

function* CustomButton(props) {
  while (true) yield <>{props.children}</>
}
CustomButton.is = 'button'

// Usage
<CustomButton attr:class="primary" attr:id="submit-btn">
  Click me
</CustomButton>

Component.attrs and Component.is

Use Component.attrs to set default attributes for a component:

function* CustomButton(props) {
  while (true) yield <>{props.children}</>
}
CustomButton.attrs = { class: 'btn btn-primary' }

Use Component.is to specify the HTML element for a component:

function* CustomInput(props) {
  while (true) yield <>{props.children}</>
}
CustomInput.is = 'input'

API

ajo module

h(type, props?, ...children)

Creates virtual DOM elements.

const element = h('div', { class: 'container' }, 'Hello, Ajo!')

render(vnode, container)

Renders a virtual DOM tree into a DOM element.

render(h(App), document.body)

Fragment({ children })

A component for grouping elements without adding extra nodes to the DOM.

const List = () => (
  <Fragment>
    <li>Item 1</li>
    <li>Item 2</li>
  </Fragment>
)

context(defaultValue)

Creates a context with an optional default value.

const ThemeContext = context('light')

// In a stateless component:
const StatelessComponent = () => {
  const theme = ThemeContext()
  return <div>Current theme: {theme}</div>
}

// In a stateful component:
function* StatefulComponent() {
  while (true) {
    const theme = ThemeContext()
    yield <div>Current theme: {theme}</div>
  }
}

// Setting context value:
function* App() {
  ThemeContext('dark')
  while (true) {
    yield (
      <>
        <FunctionalComponent />
        <StatefulComponent />
      </>
    )
  }
}

Stateful Components and Component Methods

Ajo's stateful components are implemented as generator functions and have access to several special methods:

function* StatefulComponent(props) {
  // Component logic here
  while (true) {
    yield (/* JSX */)
  }
}

Component methods:

  • this.render(): Triggers a re-render of the component. It's the primary method for updating the component's UI after state changes.

    function* Counter() {
      let count = 0
      const increment = () => {
        count++
        this.render()  // Re-render to reflect the new count
      }
      while (true) {
        yield <button set:onclick={increment}>{count}</button>
      }
    }
  • this.next(): Advances the generator to the next yield point. It's automatically called by this.render() and is rarely used directly.

  • this.throw(error): Throws an error in the generator. Useful for error propagation and creating error boundaries. Ajo automatically calls this method when an error occurs during rendering.

    function* ErrorBoundary(props) {
      try {
        while (true) {
          yield <div>{props.children}</div>
        }
      } catch (error) {
        yield <div>An error occurred: {error.message}</div>
      }
    }
  • this.return(): Completes the generator execution. It's automatically called by Ajo when a component is unmounted, but can be used manually to reset a component's state.

    function* ResetableComponent() {
      let count = 0
      const reset = () => {
        this.return()  // Reset the generator
        this.render()  // Re-render from the beginning
      }
      while (true) {
        yield (
          <div>
            <p>Count: {count}</p>
            <button set:onclick={() => { count++; this.render(); }}>Increment</button>
            <button set:onclick={reset}>Reset</button>
          </div>
        )
      }
    }
  • this.$args: Provides access to the current args of the component.

    function* DynamicGreeting() {
      while (true) {
        yield <h1>Hello, {this.$args.name}!</h1>
      }
    }

These methods provide powerful control over the component's lifecycle and state management, allowing for efficient and flexible UI updates. Note that this.throw() and this.return() are often called automatically by Ajo in response to errors or component unmounting, respectively, but can also be used manually when needed.

ajo/html module

For server-side rendering:

render(vnode)

Renders a virtual DOM tree to an HTML string.

import { render } from 'ajo/html'
import { App } from './components'

const html = render(<App />)

html(vnode)

Generates an iterator of HTML strings for streaming.

import { html } from 'ajo/html'
import { App } from './components'

for (const chunk of html(<App />)) {
  // Send chunk to the client
  stream.write(chunk)
}

License

ISC © Cristian Falcone