Git Product home page Git Product logo

csz's Introduction

csz

Runtime CSS modules with SASS like preprocessing

A framework agnostic css-in-js solution that uses stylis to parse styles from tagged template literals and append them to the head of the document at runtime. Loading in stylesheets dynamically – from .css files – is supported out of the box, so you can write your styles in .css files and import them via url without having to worry about flashes of unstyled content.

Features

  • Efficient caching of styles
  • Import styles from regular .css files
  • Available as an ES module (from unpkg.com)
  • Styles scoped under unique namespaces .csz-lur7p80ssnq
  • Global style injection :global(selector)
  • Nested selectors a { &:hover {} }
  • Vendor prefixing -moz-placeholder
  • Flat stylesheets color: red; h1 { color: red; }
  • Minification of appended styles
  • Keyframe and animation namespacing

Usage

The package is designed to be used as an ES module. You can import it directly from unpkg.com:

import css from 'https://unpkg.com/csz';

// static
const inlined = css`background: blue;`; // generate class name for ruleset

// dynamic (from stylesheet)
const relative = css`/index.css`; // generate class name for file contents
const absolute = css`https://example.com/index.css`; // generate class name for file contents

Both variations (static and dynamic) are sync and return a string in a format similar to csz-b60d61b8. If a ruleset is provided as a string then it is processed immediately but if a filepath is provided then processing is deferred until the contents of the file has been fetched and parsed.

NOTE: File paths starting with / must be relative to the current hostname, so if you are running your app on example.com and require /styles/index.css then csz will try fetch it from example.com/styles/index.css.

Styles imported from a file are inevitably going to take some amount of time to download. Whilst the stylesheet is being downloaded a temporary ruleset is applied to the element which hides it (using display: none) until the fetched files have been processed. This was implemented to prevent flashes of unstyled content.

See below for an example of what a raw ruleset might look like and how it looks like after processing.

Example stylesheet (unprocessed)
font-size: 2em;

// line comments
/* block comments */

:global(body) {background:red}

h1 {
  h2 {
    h3 {
      content:'nesting'
    }
  }
}

@media (max-width: 600px) {
  & {display:none}
}

&:before {
  animation: slide 3s ease infinite
}

@keyframes slide {
  from { opacity: 0}
  to { opacity: 1}
}

& {
  display: flex
}

&::placeholder {
  color:red
}
Example stylesheet (processed)
  .csz-a4B7ccH9 {font-size: 2em;}

  body {background:red}
  h1 h2 h3 {content: 'nesting'}

  @media (max-width: 600px) {
    .csz-a4B7ccH9 {display:none}
  }

  .csz-a4B7ccH9:before {
    -webkit-animation: slide-id 3s ease infinite;
    animation: slide-id 3s ease infinite;
  }


  @-webkit-keyframes slide-id {
    from { opacity: 0}
    to { opacity: 1}
  }
  @keyframes slide-id {
    from { opacity: 0}
    to { opacity: 1}
  }

  .csz-a4B7ccH9 {
    display:-webkit-box;
    display:-webkit-flex;
    display:-ms-flexbox;
    display:flex;
  }

  .csz-a4B7ccH9::-webkit-input-placeholder {color:red;}
  .csz-a4B7ccH9::-moz-placeholder {color:red;}
  .csz-a4B7ccH9:-ms-input-placeholder {color:red;}
  .csz-a4B7ccH9::placeholder {color:red;}

Example

This library is framework agnostic but here is a contrived example of how you can style a React component conditionally based upon some state; demonstrating switching between static and dynamic styles on the fly.

import css from 'https://unpkg.com/csz';

export default () => {
  const [toggle, setToggle] = React.useState(false);
  return (
    <div
      className={toggle
        ? css`/index.css`
        : css`background: blue;`}
    >
      <h1>Hello World!</h1>
      <button onClick={e => setToggle(!toggle)}>Toggle</button>
    </div>
  );
};

Implementation

I was inspired by emotion and styled-components but unfortunately neither of these packages expose an es module compatible build and come with quite a lot of extraneous functionality that isn't required when the scope of the project is restricted to runtime only class name generation and ruleset isolation.

csz's People

Contributors

bratberg avatar fredkschott avatar fuzetsu avatar lukejacksonn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

csz's Issues

More efficient caching and handling collisions

Use the string as the key for the cache and the hash as the data value. Calculate the hash only when creating a new key. Store the hash values in a second lookup map and check when creating a new hash value to detect collisions.

OR

Do what picostyle does and increment a classname counter for each new unique string value.

Avoid duplicate css class names by replacing Math.random()

Suggest replacing Math.random() with a perfect 32bit hash function to avoid collisions which could cause duplicate css class names

Robert Jenkins' 32 bit integer hash function

import stylis from './stylis.js'

const cache = {}
let seed = 0;  // or Math.random() * 4294967295;
const p = new Uint32Array(1);
const hash = () => {
  //Math.random()
  p[0] = seed++;
  p[0] = (p[0]+0x7ed55d16) + (p[0]<<12);
  p[0] = (p[0]^0xc761c23c) ^ (p[0]>>19);
  p[0] = (p[0]+0x165667b1) + (p[0]<<5);
  p[0] = (p[0]+0xd3a2646c) ^ (p[0]<<9);
  p[0] = (p[0]+0xfd7046c5) + (p[0]<<3);
  p[0] = (p[0]^0xb55a4f09) ^ (p[0]>>16);
  return p[0].toString(16);
}

const sheet = document.createElement('style')
document.head.appendChild(sheet)

Sample output

"1: b48681b6"
"2: e267b84c"
"3: b0910e9c"
"4: c797201d"
"5: fe0d66ee"
"6: f2b32b34"
"7: f3ced760"
"8: 92daf2f4"
"9: b5b9ef41"

Math.random() vs 32bit Hash function performance

https://jsbench.me/

Using cache with Math.random() to prevent collision

const cache = {
abc123: true,
def123: true,
aba123: true,
bab123: true,
bcb123: true,
cdc123: true,
dde123: true,
}
const hash = Math.random().toString(36).replace('0.', '')
cache[hash]
844,675 ops/s ±2.41%
65.03% slower

Using 32bit hash function

let seed = 0; // or Math.random() * 4294967295;
const p = new Uint32Array(1);
p[0] = seed++;
p[0] = (p[0]+0x7ed55d16) + (p[0]<<12);
p[0] = (p[0]^0xc761c23c) ^ (p[0]>>19);
p[0] = (p[0]+0x165667b1) + (p[0]<<5);
p[0] = (p[0]+0xd3a2646c) ^ (p[0]<<9);
p[0] = (p[0]+0xfd7046c5) + (p[0]<<3);
p[0] = (p[0]^0xb55a4f09) ^ (p[0]>>16);
p[0].toString(16);

2,415,448 ops/s ±0.52%
fastest

Fetch should consider document.baseURI

Hi, I am using this library in a project that deploy itself in a path under the root domain. All my dependecies work well because I use a <base href=/PATH/ > in my index.html but the library is using fetch with absolute paths so it ignores the base. I have solved my problem using a helper function that prepend the preffix before calling css but I think that maybe it will be useful for other users (and it is easy to add, I think).

using csz's file import in snowpack setup breaks the dev server's hmr.

i have put this question on pika discuss forum as well. putting it here as i think its intertwined with snowpack's way of importing css files.
i have one component.css file which i am importing like this in component.tsx file.

const componentStyle = css`/component.css`

// usage
<div className={componentStyle}>
// ..some html here//
</div>

since this css file is not imported using top level import but is inside csz's template literal.
any changes made to this landing.css file doesn't reflect .. i have to restart the snowpack's dev server to see the new changes.
i explored my sources tab in chrome's console tool. since snowpack didn't encountered any import of css file it was not served and hence this doesn't work.
but some where down the line csz's framework takes care of that adding the style to the dom.
i am not sure this is the ideal scenario for snowpack to pick up file (which is not imported using import but is inside css string literal )and serve it.
is there a setup or repo which i can use it as a reference where csz is used in a snowpack setup and also css files are imported in .jsx/.tsx files.

A better css parser

My rudimentary regex implementation is not going to cut it. I would like to employ something like stylis

Worth adding custom class names?

Do you think adding custom css class name support is worth it from a debugging perspective?

Example:
.my-class-name-af28f1eb
.another-class-name-e3fd91bc
instead of
.csz-af28f1eb
.csz-e3fd91bc

I'm not sure how you would support this since your css function call uses a template string.
css('background: blue', 'my-class-name')

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.