0.4.1 • Published 6 months ago

petite-kdu v0.4.1

Weekly downloads
-
License
MIT
Repository
github
Last release
6 months ago

petite-kdu

petite-kdu is an alternative distribution of Kdu optimized for progressive enhancement. It provides the same template syntax and reactivity mental model as standard Kdu. However, it is specifically optimized for "sprinkling" a small amount of interactions on an existing HTML page rendered by a server framework.

  • Only ~6kb
  • Kdu-compatible template syntax
  • DOM-based, mutates in place
  • Driven by @kdujs/reactivity

Status

  • This is pretty new. There are probably bugs and there might still be API changes, so use at your own risk. Is it usable though? Very much.

  • The issue list is intentionally disabled because I have higher priority things to focus on for now and don't want to be distracted. If you found a bug, you'll have to either workaround it or submit a PR to fix it yourself. That said, feel free to use the discussions tab to help each other out.

  • Feature requests are unlikely to be accepted at this time - the scope of this project is intentionally kept to a bare minimum.

Usage

petite-kdu can be used without a build step. Simply load it from a CDN:

<script src="https://unpkg.com/petite-kdu" defer init></script>

<!-- anywhere on the page -->
<div k-scope="{ count: 0 }">
  {{ count }}
  <button @click="count++">inc</button>
</div>
  • Use k-scope to mark regions on the page that should be controlled by petite-kdu.
  • The defer attribute makes the script execute after HTML content is parsed.
  • The init attribute tells petite-kdu to automatically query and initialize all elements that have k-scope on the page.

Manual Init

If you don't want the auto init, remove the init attribute and move the scripts to end of <body>:

<script src="https://unpkg.com/petite-kdu"></script>
<script>
  PetiteKdu.createApp().mount()
</script>

Or, use the ES module build:

<script type="module">
  import { createApp } from 'https://unpkg.com/petite-kdu?module'
  createApp().mount()
</script>

Production CDN URLs

The short CDN URL is meant for prototyping. For production usage, use a fully resolved CDN URL to avoid resolving and redirect cost:

  • Global build: https://unpkg.com/petite-kdu/dist/petite-kdu.iife.js
    • exposes PetiteKdu global, supports auto init
  • ESM build: https://unpkg.com/petite-kdu/dist/petite-kdu.es.js
    • Must be used with <script type="module">

Root Scope

The createApp function accepts a data object that serves as the root scope for all expressions. This can be used to bootstrap simple, one-off apps:

<script type="module">
  import { createApp } from 'https://unpkg.com/petite-kdu?module'

  createApp({
    // exposed to all expressions
    count: 0,
    // getters
    get plusOne() {
      return this.count + 1
    },
    // methods
    increment() {
      this.count++
    }
  }).mount()
</script>

<!-- k-scope value can be omitted -->
<div k-scope>
  <p>{{ count }}</p>
  <p>{{ plusOne }}</p>
  <button @click="increment">increment</button>
</div>

Note k-scope doesn't need to have a value here and simply serves as a hint for petite-kdu to process the element.

Explicit Mount Target

You can specify a mount target (selector or element) to limit petite-kdu to only that region of the page:

createApp().mount('#only-this-div')

This also means you can have multiple petite-kdu apps to control different regions on the same page:

createApp({
  // root scope for app one
}).mount('#app1')

createApp({
  // root scope for app two
}).mount('#app2')

Lifecycle Events

You can listen to the special kdu:mounted and kdu:unmounted lifecycle events for each element (the kdu: prefixed is required in 0.4.0+):

<div
  k-if="show"
  @kdu:mounted="console.log('mounted on: ', $el)"
  @kdu:unmounted="console.log('unmounted: ', $el)"
></div>

k-effect

Use k-effect to execute reactive inline statements:

<div k-scope="{ count: 0 }">
  <div k-effect="$el.textContent = count"></div>
  <button @click="count++">++</button>
</div>

The effect uses count which is a reactive data source, so it will re-run whenever count changes.

Another example of replacing the todo-focus directive found in the original Kdu TodoMVC example:

<input k-effect="if (todo === editedTodo) $el.focus()" />

Components

The concept of "Components" are different in petite-kdu, as it is much more bare-bones.

First, reusable scope logic can be created with functions:

<script type="module">
  import { createApp } from 'https://unpkg.com/petite-kdu?module'

  function Counter(props) {
    return {
      count: props.initialCount,
      inc() {
        this.count++
      },
      mounted() {
        console.log(`I'm mounted!`)
      }
    }
  }

  createApp({
    Counter
  }).mount()
</script>

<div k-scope="Counter({ initialCount: 1 })" @kdu:mounted="mounted">
  <p>{{ count }}</p>
  <button @click="inc">increment</button>
</div>

<div k-scope="Counter({ initialCount: 2 })">
  <p>{{ count }}</p>
  <button @click="inc">increment</button>
</div>

Components with Template

If you also want to reuse a piece of template, you can provide a special $template key on a scope object. The value can be the template string, or an ID selector to a <template> element:

<script type="module">
  import { createApp } from 'https://unpkg.com/petite-kdu?module'

  function Counter(props) {
    return {
      $template: '#counter-template',
      count: props.initialCount,
      inc() {
        this.count++
      }
    }
  }

  createApp({
    Counter
  }).mount()
</script>

<template id="counter-template">
  My count is {{ count }}
  <button @click="inc">++</button>
</template>

<!-- reuse it -->
<div k-scope="Counter({ initialCount: 1 })"></div>
<div k-scope="Counter({ initialCount: 2 })"></div>

The <template> approach is recommended over inline strings because it is more efficient to clone from a native template element.

Global State Management

You can use the reactive method (re-exported from @kdujs/reactivity) to create global state singletons:

<script type="module">
  import { createApp, reactive } from 'https://unpkg.com/petite-kdu?module'

  const store = reactive({
    count: 0,
    inc() {
      this.count++
    }
  })

  // manipulate it here
  store.inc()

  createApp({
    // share it with app scopes
    store
  }).mount()
</script>

<div k-scope="{ localCount: 0 }">
  <p>Global {{ store.count }}</p>
  <button @click="store.inc">increment</button>

  <p>Local {{ localCount }}</p>
  <button @click="localCount++">increment</button>
</div>

Custom Directives

Custom directives are also supported but with a different interface:

const myDirective = (ctx) => {
  // the element the directive is on
  ctx.el
  // the raw value expression
  // e.g. k-my-dir="x" then this would be "x"
  ctx.exp
  // k-my-dir:foo -> "foo"
  ctx.arg
  // k-my-dir.mod -> { mod: true }
  ctx.modifiers
  // evaluate the expression and get its value
  ctx.get()
  // evaluate arbitrary expression in current scope
  ctx.get(`${ctx.exp} + 10`)

  // run reactive effect
  ctx.effect(() => {
    // this will re-run every time the get() value changes
    console.log(ctx.get())
  })

  return () => {
    // cleanup if the element is unmounted
  }
}

// register the directive
createApp().directive('my-dir', myDirective).mount()

This is how k-html is implemented:

const html = ({ el, get, effect }) => {
  effect(() => {
    el.innerHTML = get()
  })
}

Custom Delimiters (0.3+)

You can use custom delimiters by passing $delimiters to your root scope. This is useful when working alongside a server-side templating language that also uses mustaches:

createApp({
  $delimiters: ['${', '}']
}).mount()

Features

petite-kdu only

  • k-scope
  • k-effect
  • @kdu:mounted & @kdu:unmounted events

Has Different Behavior

  • In expressions, $el points to the current element the directive is bound to (instead of component root element)
  • createApp() accepts global state instead of a component
  • Components are simplified into object-returning functions
  • Custom directives have a different interface

Kdu Compatible

  • {{ }} text bindings (configurable with custom delimiters)
  • k-bind (including : shorthand and class/style special handling)
  • k-on (including @ shorthand and all modifiers)
  • k-model (all input types + non-string :value bindings)
  • k-if / k-else / k-else-if
  • k-for
  • k-show
  • k-html
  • k-text
  • k-pre
  • k-once
  • k-cloak
  • reactive()
  • nextTick()
  • Template refs

Not Supported

Some features are dropped because they have a relatively low utility/size ratio in the context of progressive enhancement. If you need these features, you should probably just use standard Kdu.

  • ref(), computed() etc.
  • Render functions (petite-kdu has no virtual DOM)
  • Reactivity for Collection Types (Map, Set, etc., removed for smaller size)
  • Transition, KeepAlive, Teleport, Suspense
  • k-for deep destructure
  • k-on="object"
  • k-is & <component :is="xxx">
  • k-bind:style auto-prefixing

Comparison with standard Kdu

The point of petite-kdu is not just about being small. It's about using the optimal implementation for the intended use case (progressive enhancement).

Standard Kdu can be used with or without a build step. When using a build setup (e.g. with Single-File Components), we pre-compile all the templates so there's no template processing to be done at runtime. And thanks to tree-shaking, we can ship optional features in standard Kdu that doesn't bloat your bundle size when not used. This is the optimal usage of standard Kdu, but since it involves a build setup, it is better suited when building SPAs or apps with relatively heavy interactions.

When using standard Kdu without a build step and mounting to in-DOM templates, it is much less optimal because:

  • We have to ship the Kdu template compiler to the browser (13kb extra size)
  • The compiler will have to retrieve the template string from already instantiated DOM
  • The compiler then compiles the string into a JavaScript render function
  • Kdu then replaces existing DOM templates with new DOM generated from the render function.

petite-kdu avoids all this overhead by walking the existing DOM and attaching fine-grained reactive effects to the elements directly. The DOM is the template. This means petite-kdu is much more efficient in progressive enhancement scenarios.

Security and CSP

petite-kdu evaluates JavaScript expressions in the templates. This means if petite-kdu is mounted on a region of the DOM that contains non-sanitized HTML from user data, it may lead to XSS attacks. If your page renders user-submitted HTML, you should prefer initializing petite-kdu using explicit mount target so that it only processes parts that are controlled by you. You can also sanitize any user-submitted HTML for the k-scope attribute.

petite-kdu evaluates the expressions using new Function(), which may be prohibited in strict CSP settings. There is no plan to provide a CSP build because it involves shipping an expression parser which defeats the purpose of being lightweight. If you have strict CSP requirements, you should probably use standard Kdu and pre-compile the templates.

License

MIT

0.4.1

6 months ago