Preprocessor
The Choco preprocessor expands the use:choco
shorthand syntax, which allows you to use
headless instances easily, with a great DX and type-safety.
Here’s an example using the headless ToggleButton
class: with the shorthand syntax
the code is much cleaner. But both syntaxes are totally equivalent. The preprocessed shorthand is
also type-safe, so eg. TypeScript would complain if toggle
was used on a span
element.
<script lang="ts">
import { choco } from "chocobytes";
import { ToggleButton } from "chocobytes/headless/toggle.svelte.js";
const toggle = new ToggleButton();
</script>
<p>
<!-- The shorthand syntax... -->
<button use:choco={toggle}> Click me. </button>
<span>Active: {toggle.active}</span>
</p>
<p>
<!-- ...is expanded into this by the preprocessor -->
<button {...toggle.attributes} use:toggle.action> Click me. </button>
<span>Active: {toggle.active}</span>
</p>
<pre>{JSON.stringify(toggle.attributes, null, 2)}</pre>
<style>
button {
cursor: pointer;
opacity: 60%;
}
</style>
Under the hood the preprocessor takes advantage of the fact that all headless classes are
instances of a ChocoBase
class with a simple
contract, having attributes
to spread and an action
to use.