Skip to content

⚙️ Crank.js with tagged templates

License

Notifications You must be signed in to change notification settings

aidenybai/hacky

Repository files navigation

⚙️ HackyCode SizeNPM Version

<2kbtagged template alternative for Crank.js

Hacky is something that I've always wanted. I've used React previously, but I findhooks too magicaland JSX afinicky processthat requires a build step.

When I discovered Crank.js, I fell in love because of how intuitive it was to understand. Imagine Hacky asCrank.js with tagged templates,but with a lightweight core and simplistic API.

If you're looking for something a bit more comprehensive, check outMillion— Virtual DOM into the future! 💥🦁✨

-Aiden (@aidenybai)

random.catAPI Example

Below is an implementation of arandom.catAPI fetcher example using Hacky (Live Demo).

import{html,render}from'https://cdn.skypack.dev/hacky';

constfetchCat=async(url='https://aws.random.cat/meow')=>{
constres=awaitfetch(url);
const{file}=awaitres.json();
returnfile;
};

function*Cats({width,height}){
const[cats,setCats]=this.createState([]);
const[message,setMessage]=this.createState('Fetch cat image');
const[disabled,setDisabled]=this.createState(false);

constaddCat=async()=>{
setMessage('Fetching...');
setDisabled(true);

try{
constnewCat=awaitfetchCat();
setCats([...cats(),newCat]);
setMessage('Fetch cat image');
setDisabled(false);
}catch(err){
console.error(err);
setMessage('Failed to fetch. Retrying...');
setTimeout(()=>addCat(),1000);
}
};

while(true){
constcatImages=cats().map(
(cat)=>html`<imgkey=${cat}src=${cat}width=${width}height=${height}/>`,
);
yieldhtml`
<buttondisabled=${disabled()}onClick=${addCat}style= "width: 100%">${message()}</button>
<div>${catImages}</div>
`;
}
}

render(html`<${Cats}width=${100}height=${100}/>`,document.body);

render()function has a standard interface that is used in many Virtual DOM libraries. First argument is a Virtual DOM to render, and the second one is a DOM node that will be used as the live DOM reference.

htmltagged templates can produce Virtual DOM nodes, which define your DOM view.

this.createState()function will instantiate a new state reference, in which you can mutate by destructuring the getter (index0) and setter (index1).

Acknowledgments

Hacky takes heavy inspiration fromCrank.js,and depends onMillion.Feel free to check them out if you interested in an alternative library to use.

License

Million isMIT-licensedopen-source software byAiden Bai.