iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🌕

Luna UI - Declarative UI for JS/Moonbit: Lightweight, Fast, and WebComponents First

に公開

As a UI library geek, I have tried various UI libraries, starting with React, and have finally decided to build my own.

Since existing libraries haven't been able to solve my frustrations after all these years—or remain difficult to solve—it is time for me to build exactly what I really want.

  • Portability via a lightweight runtime
  • Fine-grained reactivity using Signals
  • Small enough that compile-time optimization is unnecessary
  • Supports WebComponents SSR + Hydration (possibly the first in the world)

Thus, I created Luna. I have also built a documentation site.

https://luna.mizchi.workers.dev/

It is written in Moonbit+Luna itself and built from scratch using SSG.

GitHub

https://github.com/mizchi/luna.mbt

Frustrations with Existing UI Libraries

  • React: Too heavy. Slow performance due to compatibility with legacy assets. I don't care for the direction of RSC implementation.
  • Qwik/Solid: Compile-time expansion is cumbersome.
  • Svelte/Vue: SFC (Single File Components) are difficult to integrate into the ecosystem.
  • Preact: I believe it has the best approach, but Signals were added as an afterthought, and the ecosystem is lukewarm.
  • Common problem: Low interoperability. Other than Qwik, I am dissatisfied with SSR speed. There is nothing that is WebComponents First.

Based on these points, I am designing this with reference to preact/signal, assuming WebComponents SSR + Hydration as a premise.

From my experience with Qwik, Preact, and Svelte, I believe Qwik's optimization is overly complex; if the core is sufficiently lightweight, the preact-style lightweight core is enough.

I considered extending preact, but given the integration of SSR Hydration and native SSR, vertical integration is required for SSR optimization, so I decided to build it from scratch.

Deliverables

🌕 Luna UI - A signal-based declarative UI library written in MoonBit. It can be used with Moonbit/JS.

In a comparison I ran using the sample code described below, while implementing the same logic in luna and preact, preact was 20kb, while luna was 6.7kb. In practice, this changes depending on which features are treeshaken, but this result itself can be called a huge success.

Sample Code: tsx

Since I wrapped the output of the Moonbit JS backend with jsx-runtime, you can use JSX directly in your JS builds.

$ npm add @luna_ui/luna

You can introduce it like this:

import { createSignal, createMemo, render, For, Show } from '@luna_ui/luna';

function Counter() {
  const [count, setCount] = createSignal(0);
  const doubled = createMemo(() => count() * 2);
  const isEven = createMemo(() => count() % 2 === 0);

  return (
    <div>
      <h1>Luna Counter Example</h1>
      <p>Count: {count}</p>
      <p>Doubled: {doubled}</p>
      <p>{() => isEven() ? 'Even' : 'Odd'}</p>
      <div class="buttons">
        <button onClick={() => setCount(c => c - 1)}>-</button>
        <button onClick={() => setCount(c => c + 1)}>+</button>
        <button onClick={() => setCount(0)}>Reset</button>
      </div>
    </div>
  );
}
//...
const app = document.getElementById('app');
if (app) {
  render(app, <App />);
}

Sample project assuming tsx:

https://github.com/mizchi/luna-tsx-example

Sample Code: Moonbit

Here is the Moonbit version.

fn main {
  let doc = @js_dom.document()
  guard doc.getElementById("app") is Some(el)

  let count = @signal.signal(0)
  let app = @dom.div([
    p([@dom.text_dyn(fn() { "Count: " + count.get().to_string() })]),
    button(
      on=@events().click(fn(_) { count.update(fn(n) { n + 1 }) }),
      [text("Click me")],
    ),
  ])
  @dom.render(el |> @dom.DomElement::from_jsdom, app)
}

I felt that connecting two builds—vite and moonbit—was complex, so I also built vite-plugin-moonbit to integrate them nicely.

https://github.com/mizchi/vite-plugin-moonbit

Once installed, you can do this:

import { greet } from 'mbt:username/app';

moon build --target js generates .d.ts files. From the vite side, it resolves symbols from namespaces within Moonbit and resolves them with types. Isn't that convenient?

I also integrated an error reporter, which displays the results of moon build --watch as vite errors and outputs the build error details. Without this, it was difficult when type errors were not being output. (You can set it to manual via options as well.)

Moonbit does not have JSX yet, so it is written in a functional DSL style.

I say "yet" because that proposal is currently underway and is being implemented.

https://github.com/moonbitlang/moonbit-evolution/issues/19

It should feel much more natural once this is available. Currently, it is a DSL based on functions, but I intend for it to have a decent writing experience as it is.

Demos in Action

I want to convey its potential through actual working demos.

Demo: Shooting Game

This is a game I built for benchmarking.

This is not an HTML Canvas; it generates a 100x100 DOM and rewrites it in real-time every frame.

When tested with DevTools, there is almost no JS overhead, and it maintains 60FPS. Even on my smartphone, it was buttery smooth.

When I prototyped an equivalent in React, it only reached about 12FPS.

The bundle size also stays lightweight at 6.4kb.

Source code is here:

https://github.com/mizchi/luna.mbt/tree/main/src/examples/game

Demo: TodoMVC

I feel like I don't see it much lately, but I built a TodoMVC, which is often created as a benchmark when making frameworks.

https://luna.mizchi.workers.dev/demo/todomvc/

I thought this was a good subject for a real-world use case.

Source code:

https://github.com/mizchi/luna.mbt/tree/main/src/examples/todomvc

Demo: Sol Framework

I am building a framework called Sol, equivalent to Next.js. With Luna and Sol, it's Moon and Sun, get it?

This is still a PoC with designs yet to be finalized, but a demo deployed to Cloudflare Workers is running.

As far as I know, I am unaware of any other framework that has implemented this.

Given the recent vulnerabilities in React, I am planning and implementing a secure design. I will write another article once it becomes available for use.

Astra SSG: SSG for Documentation

I have always felt that it is lame for the documentation of frameworks or UI libraries to be written using tools other than themselves.

Therefore, I built a static site generator using Luna from scratch.

The name is astra. Is it confusing with astro? Combining it with the Sol framework mentioned later, I matched the terminology to Latin celestial-related terms, and this is how it ended up...

Documentation: https://luna.mizchi.workers.dev/

This documentation site was implemented using an SSG implemented with Luna. As a framework, it is implemented with reference to docusaurus, but I have added features I wanted, such as automatically sorting documents using prefixes like 00_.

$ npx @luna_ui/astra new mydocs
$ cd mydocs
$ npx @luna_ui/astra dev
$ npx @luna_ui/astra build # Generates dist-docs/*

However, it is still an implementation with several fixed assumptions, and there are few configurable elements. This is a task for the future.

In fact, the markdown compiler I made the other day was created for this purpose.

https://github.com/mizchi/markdown.mbt

Why I implemented it in MoonBit

This is an old story, but there has been a "double template problem" since ancient times where the same templates were described on the client and server, and the client took over the logic.

Next.js was the first to practically address this problem. SSR is not just generating HTML on the server. It is only realized by injecting the active parts of JS into the client.

From my experience with Next.js and Qwik, if you want to perform hydration and optimization during SSR, you need vertical integration of the client runtime and server SSR. This is a very difficult task, and it is somehow realized through the means of ensuring idempotency using the same language, namely Node.js and the browser. This is the reason why SSR + Hydration is almost never realized outside of Node.js.

But if it's Moonbit, which can cross-compile into multiple languages, couldn't we realize this even with different backends?

MoonBit can compile into multiple targets:

MoonBit → JavaScript (Browser)
        → Native (SSR Server)
        → Wasm-GC (WasmEdge)

Moonbit's strength is its expressive power as a language that can withstand complex designs like Hydration, and the fact that it can generate lightweight JS that is almost equivalent to JS via the JS Backend. And the wasm-gc backend is also lightweight, and there is a fast native backend. My local benchmarks show that native builds are about 5 times faster.

However, in the Sol Framework, which currently performs SSR, the majority of the server is implemented as bindings to Hono, so it only works with JS. For now, the goal is to run it on the Cloudflare Workers JS backend.

Please give it a try

I think I have been able to express the potential of Moonbit.

While the completeness of Astra and Sol is not great, the Luna core itself is quite tested and should probably be quite usable.

I want to work on themes like these next:

  • Assemble samples for WebComponents and loaders
  • Make an editor that can preview in real-time
  • Build a headless UI framework equivalent to radix-ui
  • Create a WebComponents Registry on Cloudflare Worker
  • Enable SSR with a Native Server
  • Support Wasm and run on wasmedge

Please give it a try. I would love to hear your feedback.

https://github.com/mizchi/luna.mbt

(That said, there are limits to building this alone, so I would like to establish proper governance or find a company to sponsor me if possible.)

Discussion