Ever since I got into libraries and frameworks, I wanted to create my own. My whole web dev journey started with jQuery, so naturally, I love method chaining. This always gave me an idea: why can’t you build UI like that as well?
const people = ref(['Jan', 'Andrew', 'Daniel'])
const PeopleList = ul().for(people, (item, index) => {
return li(item.name)
.if(() => index > 0)
.class('name')
})
PeopleList.mount('#app')
// Produces
// <ul>
// <li>Andrew</li>
// <li>Daniel</li>
// </ul>
I have always had this concept at the back of my head. Originally I wanted to create it as an extension to my Curry.ts library. Later on I wanted to include it in Beskydy as well, but I could never figure out all the implementation nuances.
Until Christmas 2023. What’s better than hanging out with relatives? Going down a rabbit hole, yes! (I did hang out with them, though)
The gist
Cascade is quite simple. It can do just a couple of things:
- Define components with the
reusablehelper or use native elements extended with Cascade’s core. Similar to Vue’ssetupfunction, it allows a lot of flexibility - Mount any component anywhere in the existing HTML page via the
mountfunction. We can extend existing pages with Cascade - Create reactive UI thanks to
@vue/reactivitypackage (I love Vue so much) - Lifecycle hooks (onInit, onMount, onBeforeDestroy, onDestroy, onVisibilityChange)
To best illustrate how Cascade works, here’s my reusable checkbox component taken from another project Hivecom records and slightly edited for a better example.
import { createId, div, input, label, reusable, span } from '@dolanske/cascade'
import { Ref } from '@vue/reactivity'
interface Props {
model: Ref<boolean>
label: string
icon: string
}
export default reusable('div', (ctx, props: Props) => {
const id = createId()
ctx.class('form-checkbox')
ctx.nest(
input('checkbox')
.name(id)
.id(id)
.attr('checked', props.model)
.model(props.model),
label().attr('for', id).nest(
span(props.label),
// Conditionally an icon, if it is provided on mount
div().html(props.icon).if(props.icon)
)
)
})
You can then use the component in your app like this.
import { fragment } from '@dolanske/cascade'
import { ref } from '@vue/reactivity'
import Checkbox from './Checkbox.ts'
// Root app component. Components used only once don't have to be defined
// as reusable. You may be familiar with the concept of fragments.
// Essentially it's a renderless component, which will render the provided
// child elements as its root.
const App = fragment().setup((ctx) => {
const checked = ref(false)
// Components don't return anything. Any nesting or additional functionality
// is exposed on the `ctx`, which holds the component's instance.
ctx.nest(
Checkbox().props({
model: checked,
label: 'I agree with the terms.'
})
)
})
App.mount('#app')
How does it work?
We have a list of native HTML elements, and each of these elements receives a factory function. This creates the component instance and that’s the main meat of Cascade. Here’s the implementation.
// Simple example of how cascade enhances HTML elements
const nativeHTMLElements = ['a', 'abbr', 'address', 'applet', 'article', 'aside'] // ... and so on
const $ = nativeHTMLElements.reduce((group, type) => {
group[type] = (children: ComponentChildren = []) => {
const root = document.createElement(type)
const inst = new Component(root)
inst.__children(children)
return inst
}
return group
}, {} as Record<string, (children?: ComponentChildren) => Component>)
Component instance
Every component is just a simple class instance, where the only difference is the root element it holds. Otherwise, all of the methods, lifecycle hooks and other properties are the same. Full implementation can be found here.
An example of how to extend the base functionality with your own. The entire component functionality is just a single class, which can be modified.
import { Component } from '@dolanske/cascade'
// For the sake of example I'll create something stupid
const noKids = new Component(document.createElement('div'))
noKids.prototype.flushChildren = function () {
this.el.replaceChildren()
return this
}
// return noKids
// Now this component will expose a new chained method
const el = noKids().children(document.createElement('div'))
el.flushChildren()
Here are a few notable features, which Cascade offers:
Model
.model(ref, modifiers)
Two-way binding to control an element’s value with a ref. You can use model() on input, select, textarea and details.
const pwd = ref('')
// When user inputs any value to the input, the ref's value is automatically updated
input('password').model(pwd)
You can also pass transforms, which alter the event value before it’s sent back.
import { Transform } from '@dolanske/cascade'
Transform.trim
Transform.number // Number(value)
Transform.integer // parseInt(value, 10)
Transform.uppercase
Transform.lowercase
Transform.capitalize
Transform.capitalizeAll
Transform.truncate(length)
Transform.clamp(min, max) // use after `number`
Transform.replace(pattern, replacement)
Transform.fallback(value) // used when the value is empty, null or NaN
ctx.model(age, { transforms: [Transform.number, Transform.clamp(0, 120)] })
Conditional rendering
.if(result) & .show(result)
Render elements only when the result is truthy.
// Inside .setup(() => {})
const display = ref(true)
ctx.nest(
button('Toggle').click(() => display.value = !display.value),
span('Now you see me').if(display)
)
If / else is not supported. Use a getter and a ternary.
ctx.nest(() => loggedIn.value ? Dashboard() : LoginForm())
Lists
.for(list, cb)
Iterate over the provided array / object / number and render the value returned from the callback for each item. Not required, but to ensure granular updates to reactive arrays, provide a unique key per item.
ctx.for(
users,
user => Row().props({ user }),
{ key: user => user.id }
)
Events
Bind native events to the underlying HTML node.
.on(eventName) + Built-in shorthands
ctx.on('click', (e) => {
e.stopPropagation()
clicked.value = true
})
Custom events can be typed via custom interface during component definition.
interface Props { user: User }
interface Events { remove: { id: number } }
const Row = reusable<Props, Events>('li', (ctx, props) => {
ctx.nest(
span(() => props.user.name),
// Payload is type checked against `Events['remove']`
button('×').click(() => ctx.emit('remove', { id: props.user.id })),
)
})
// Event name and payload are typed on the instance
Row().props({ user }).on('remove', (event, { id }) => remove(id))
You can provide event modifiers. The order matters as they run sequentially.
import { Modifier } from '@dolanske/cascade'
ctx.click(submit, { modifiers: [Modifier.prevent, Modifier.once] })
Modifier.if(expression) // only run when the ref / getter / boolean is truthy
Modifier.throttle(ms) // ignore events fired within `ms` of the last run
Modifier.delay(ms) // wait before running
Modifier.once // run once
Modifier.self // only when the event target is the element itself
Modifier.stop // stopPropagation()
Modifier.stopImmediate // stopImmediatePropagation()
Modifier.prevent // preventDefault()
Modifier.cancel // never run
I am quite proud of this project and if you’re interested in how the project is implemented, check out the GitHub repo. The whole API and functionality is described there in more detail.
