Velvet is a universal CSS in JS library implemented in vanilla JavaScript. It offers runtime style injection and is library agnostic, ensuring compatibility with various frameworks. Inspired by React Native's StyleSheet API, Velvet is designed for developers looking for simple yet effective styling solutions while adhering to strict Content Security Policy.
Velvet is a versatile Vanilla JavaScript Universal CSS-in-JS library that enables developers to apply styles with ease while ensuring compatibility with Content Security Policy (CSP). Drawing inspiration from modern styling solutions like React Native's StyleSheet API and Facebook's StyleX, Velvet operates purely at runtime, eliminating the need for a pre-compilation step and enhancing its flexibility across projects.
Explore a live demonstration of Velvet on its Live Demo page.
Here are a few code snippets to illustrate how Velvet can be utilized in various scenarios:
import { useEffect } from 'react';
import { StyleSheet, inject } from 'velvet-style';
const styles = StyleSheet.create({
header: { color: 'red' }
});
const Header = ({ title }) => {
useEffect(() => {
return inject(styles.header, { nonce });
}, []);
return <h1 className={styles.header}>{title}</h1>;
};
import { useEffect, useRef } from 'react';
import { style, inject } from 'velvet-style';
const Button = ({ color, title }) => {
const className = useRef();
useEffect(() => {
className.current = style({ color });
return inject(className.current, { nonce });
}, [color]);
return <button className={className.current}>{title}</button>;
};
const debug = true;
const nonce = '2726c7f26c';
const styles = velvet.StyleSheet.create({
A: { color: 'red' },
B: { color: 'darkblue' }
});
function create_p(class_name, text) {
const p = document.createElement('p');
p.innerText = text;
p.classList.add(class_name);
velvet.inject(class_name, { nonce, debug });
document.body.appendChild(p);
}
create_p(styles.A, 'Hello');
create_p(styles.B, 'World');
<script>
class HelloWorld extends window.HTMLElement {
connectedCallback() {
const shadow = this.attachShadow({ mode: 'open' });
const class_name = velvet.style({ color: this.color });
const p = document.createElement('p');
p.innerText = `Hello ${this.name}`;
p.classList.add(class_name);
shadow.appendChild(p);
velvet.inject(class_name, { debug: true, target: shadow });
}
}
window.customElements.define('hello-world', HelloWorld);
const hello = document.createElement('hello-world');
document.body.appendChild(hello);
</script>
<hello-world name="Velvet" color="blue"></hello-world>
Velvet offers a simple yet powerful way to manage styles in JavaScript applications, allowing for greater adaptability and improved security compliance. For more information and detailed documentation, visit the project's GitHub page.
No comments yet.
Sign in to be the first to comment.