- Zero dependencies
- Framework-free
- No transpilation needed \o/ #usetheplatform
Calque is a tiny helper library (only ~7KB) for the native web platform, aimed to help to build interfaces easily. The goal is to offer a declarative way to code UI components by writing bits of HTML, rather the traditional client-side scripting, and also providing a simple layer as Virtual DOM to update the view πΌοΈ changes.
It is all based on Web Standards, πͺpowered by JavaScript language, DOM & browser APIs. The library calques, or transcript, the HTML-like template inner data translating into the respective properties on the target ELEMENT_NODE type object. This approach aims to aid coding Web Components π€ππ, especially as an add-on for Custom Elements (which are awesome). They play a key role at micro frontends and make possible to reuse code on web platform.
NPM (Terminal)
$ npm install --save calque
import { innerHTML, html } from '../dist/calque.mjs';
window.customElements.define('my-component', class extends HTMLElement {
static get observedAttributes() { return ['name', 'data-list'];}
constructor(...args) {
super(...args);
this.showNodeName = this.showNodeName.bind(this);
}
attributeChangedCallback() { this.render(); }
connectedCallback() { this.render(); }
showNodeName() {
alert(this.nodeName);
this.setAttribute('name', 'Neo name');
}
render() {
const colorProp = 'color';
const name = this.getAttribute('name');
this[innerHTML] = html`
<p onblur="${(e)=>console.log(e.target.textContent)}"
contenteditable>
Temporary text
</p>
<h3 onclick="${this.showNodeName}"
style="${{[colorProp]: "red","font-size": name.length+"em"}}">
Hello, λ ${name}
</h3>
<aside>
<ul>${this.hasAttribute('data-list')
&& this.getAttribute('data-list').split(',').map(num => html`<li>${num}</li>`)}</ul>
<button onclick="${(function removeItem() {
if (this.hasAttribute('data-list')) {
let list = this.getAttribute('data-list');
let lastIndex = list.lastIndexOf(',');
this.setAttribute('data-list', list.slice(0, lastIndex));
} else {
console.warn('No data-list attribute found');
}
}).bind(this)}">-</button>
</aside>
`;
}
});
import {innerHTML, html} from '../calque.mjs';
function NeoTag() {
console.log(this.constructor);
this.count = 0;
return Reflect.construct(HTMLElement, [], this.constructor);
}
NeoTag.prototype = Object.create(HTMLElement.prototype);
NeoTag.prototype.constructor = NeoTag;
Object.setPrototypeOf(NeoTag, HTMLElement);
NeoTag.prototype.handlerClick = function click(){console.log('clicked', this);};
NeoTag.prototype.connectedCallback = function() {
this[innerHTML] = html`<p onclick="${this.handlerClick.bind(this)}">Neo Tag</p>`;
};
customElements.define('neo-tag', NeoTag);
document.body.appendChild(document.createElement('neo-tag'));
Calque updates the DOM nodes after the changes on component attributes to reflect the new values.
π§The motivation for this library comes basically inspired for what JSX represents for React, I must say that it's too boring to use React without JSX, because it simplifies the coding of a React component using a common HTML grammar.
With the advent of Web Components, it's now possible to achieve some features provide by frameworks and libraries, but using the timeless advantage of the native web. The component pattern is one of the major benefits of reusable Web Components, which enables to break the UI into distinct and small chunks of code providing a modular and reusable component to be used in many different contexts.
Web Components use a set of standardized APIs that are natively supported in all modern browsers. These UI components run on nearly all mobile devices and desktop browsers today.
Nothing new or needed to learn, the mantra is π - no third-party libraries/frameworks APIs to interact, just some conveniences. Using Calque is as easy as using template tags. This feature was added at ES6 as he Templates literals, which are simply functions that allow creating domain-specific languages (DSLs). For more details about The HTML templating, access the book ExploringJS by Dr. Axel Rauschmayer.
Just for curiosity, π€ In linguistics, a calque /kΓ¦lk/ or loan-translation is a borrowing of a compound word from another language where each component is translated into native words and then joined together.
This definition sums up the idea behind Calque, it intends to maximize the readability using the web markup lingua franca, at the same time, it enhances the component by bootstrapping his content and avoids some mandatory JS-DOM boilerplate codes.
When using the library, pay attention to this details mentioned below:
- Adding Event Listeners smoothly: use function reference
onevent="myFunction"
, not function invocationonevent="myFunction()"
. Note that in HTML, event listener names are written only in lowercase, such as onclick, onmouseover, etc. In some libraries, however, like JSX or lit-html, event listener names are written in camelCase or with the prefix @, such as onClick or @click, respectively. The philosophy behind Calque is to avoid at the most any divergence from common HTML syntax. - Passing inline CSS properties not only through strings but by literal objects too: when using styling objects, the JSON-based format is mandatory. for example, you can pass a JSON object for the style attribute as
{[myProp]: "7px", "border-color": myValue}
. OBS: single properties names will work{color: "blue"}
but are better to follow the standard rules. - Avoid use the innerHTML property directly. In JavaScript, you can use a variable value to access the respective property name (
var f='foo',o={foo:'bar'}; o[f] // outputs "bar"
), so instead of usedocument.body.innerHTML
ordocument.body["innerHTML"]
, you must import and use theinnerHTML
variable from CalqueJS, and them calldocument.body[innerHTML]
together with thehtml
tagged template function provided (html method is primarily a convenience function, and it can be especially useful when manipulating callback events). - Follow the best practices, we use double quotes for attributes values.
Use Serve as recommended Web Server, run:
$ npm i serve
There are quite a few things to be done:
- Attributes (not observed) updating
- Apply some code refactors (more functional programming style)
- Investigating Shadow DOM support
Code licensed under the MIT License.
βοΈ Suitable for web UI prototyping π
β’οΈ use at your own risk β£οΈ
π If you considering to use Calque, feel free to share your feedback, thanks a lot π
https://github.com/w3c/webcomponents/
https://developers.google.com/web/fundamentals/web-components/customelements
https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements
https://blog.usejournal.com/web-components-will-replace-your-frontend-framework-3b17a580831c