otion
Atomic CSS-in-JS with a featherweight runtime.
Usage
Install the library with a package manager of choice, e.g.:
npm install otion
Introduction through examples
The code snippets below are deliberately framework-agnostic. Please refer to the project's repository for information about integrations.
Basic concepts of atomicity
; // Style rules are auto-injected to a `<style>` element in the `<head>`documentclassName = ;documentclassName = ; // Class names of identical rules match, as guaranteed by a hash functionconsole; // In this case, a space-separated string of unique class names is returneddocumentclassName = ;
Numbers assigned to non-unitless properties are postfixed with "px"
documentclassName = ;
At-rules like media queries can be used and combined with pseudos
documentclassName = ;
Fallback values are accepted when auto-prefixing isn't enough
documentclassName = ;
Using keyframes to animate values of given properties over time
// A unique name is attached to the generated `@keyframes` ruleconst pulse = ; // The former rule only gets injected upon usage, as it's lazily initializedconst className = ;
Advanced selectors may be used as an escape hatch from strict atomicity
These should be used sparingly, as selectors are not parsed, but transformed as strings. Overly specific selectors void the main advantages of atomicity, so it's best to avoid them. The characters ,
and &
shall not be part of attribute selector values, otherwise, styling is not guaranteed to work.
const className = ;
Custom properties may be defined with type safety in mind
However, please be advised that the recommended method of defining custom property values is within inline or global styles.
/* css.d.ts *//* See: https://github.com/frenic/csstype#what-should-i-do-when-i-get-type-errors */ ; /* Augment the module below with custom or even missing properties */declare
const className = ;
Server-side rendering
While prerendering a page, browser object models are inaccessible and thus, styles cannot be injected dynamically. However, a VirtualInjector
can collect the styles instead of applying them through injection, as seen in the Next.js example:
;; // Options may be customized, as shown laterconst sharedOptions = {};const injector = ; // Shall be called before the underlying page is rendered; // Obtain HTML code of the pagelet html = ; // Statically insert collected styles as the last element of `<head>`const styleTag = ;html = html;
During runtime, the same options should be provided before hydration, as shown below:
; ; // Make sure to rehydrate only in browser environmentsif typeof window !== "undefined" ; ;
Deno support
For convenient resolution of the library, an import map should be used. Unlike with Node, development and production builds are separated into different bundles.
/* import_map.json */ { "imports": { "otion/dev": "https://cdn.pika.dev/otion@X.Y.Z/runtime-deno-dev", "otion": "https://cdn.pika.dev/otion@X.Y.Z/runtime-deno" }}
deno run --importmap=import_map.json --unstable mod.ts
Security
User-specified data shall be escaped manually using CSS.escape()
or an equivalent method.
Customization
Injector options
nonce
In order to prevent harmful code injection on the web, a Content Security Policy (CSP) may be put in place. During server-side rendering, a cryptographic nonce (number used once) may be embedded when generating a page on demand:
; // Usage with webpack: https://webpack.js.org/guides/csp/const injector = ;
The same nonce
parameter should be supplied to the client-side injector:
; const isDev = processenvNODE_ENV !== "production";;
target
Changes the destination of the injected rules. By default, a <style id="__otion">
element in the <head>
during runtime, which gets created if unavailable.
Instance options
prefix
A custom auto-prefixer method may be used as a replacement for the built-in tiny-css-prefixer
:
;; // v4 ;
Instance creation
Separate instances of otion are necessary when managing styles of multiple browsing contexts (e.g. an <iframe>
besides the main document). This option should be used along with a custom target
for injection:
; const iframeDocument = document0 contentDocument; const instance = ;instance;
What's missing
Global styles
Being unique by nature, non-scoped styles should not be decomposed into atomic rules. This library doesn't support injecting global styles, as they may cause unexpected side-effects. However, ordinary CSS can still be used for style sheet normalization and defining the values of CSS Custom Properties.
Contrary to otion-managed styles, CSS referenced from a <link>
tag may persist in the cache during page changes. Global styles are suitable for application-wide styling (e.g. normalization/reset), while inlining the scoped rules generated by otion accounts for faster page transitions due to the varying nature of per-page styles.
By omitting global styling functionality on purpose, otion can maintain its low bundle footprint while also encouraging performance-focused development patterns.
Theming
Many CSS-in-JS libraries tend to ship their own theming solutions. Contrary to others, otion doesn't embrace a single recommended method, leaving more choices for developers. Concepts below are encouraged:
- CSS Custom Properties (with a polyfill for IE 11)
- A singleton or value providers (e.g. React Context)