Giter VIP home page Giter VIP logo

goober's Introduction

goober

πŸ₯œ goober, a less than 1KB css-in-js solution.

Backers on Open Collective Sponsors on Open Collective

version status gzip size downloads coverage Slack

πŸͺ’ The Great Shave Off Challenge

Can you shave off bytes from goober? Do it and you're gonna get paid! More info here

Motivation

I've always wondered if you could get a working solution for css-in-js with a smaller footprint. While I was working on a side project I wanted to use styled-components, or more accurately the styled pattern. Looking at the JavaScript bundle sizes, I quickly realized that I would have to include ~12kB(styled-components) or ~11kB(emotion) just so I can use the styled paradigm. So, I embarked on a mission to create a smaller alternative for these well established APIs.

Why the peanuts emoji?

It's a pun on the tagline.

css-in-js at the cost of peanuts! πŸ₯œgoober

Talks and Podcasts

Table of contents

Usage

The API is inspired by emotion styled function. Meaning, you call it with your tagName, and it returns a vDOM component for that tag. Note, setup needs to be ran before the styled function is used.

import { h } from 'preact';
import { styled, setup } from 'goober';

// Should be called here, and just once
setup(h);

const Icon = styled('span')`
    display: flex;
    flex: 1;
    color: red;
`;

const Button = styled('button')`
    background: dodgerblue;
    color: white;
    border: ${Math.random()}px solid white;

    &:focus,
    &:hover {
        padding: 1em;
    }

    .otherClass {
        margin: 0;
    }

    ${Icon} {
        color: black;
    }
`;

Examples

Comparison and tradeoffs

In this section I would like to compare goober, as objectively as I can, with the latest versions of two most well known css-in-js packages: styled-components and emotion.

I've used the following markers to reflect the state of each feature:

  • βœ… Supported
  • 🟑 Partially supported
  • πŸ›‘ Not supported

Here we go:

Feature name Goober Styled Components Emotion
Base bundle size 1.25 kB 12.6 kB 7.4 kB
Framework agnostic βœ… πŸ›‘ πŸ›‘
Render with target *1 βœ… πŸ›‘ πŸ›‘
css api βœ… βœ… βœ…
css prop βœ… βœ… βœ…
styled βœ… βœ… βœ…
styled.<tag> βœ… *2 βœ… βœ…
default export πŸ›‘ βœ… βœ…
as βœ… βœ… βœ…
.withComponent πŸ›‘ βœ… βœ…
.attrs πŸ›‘ βœ… πŸ›‘
shouldForwardProp βœ… βœ… βœ…
keyframes βœ… βœ… βœ…
Labels πŸ›‘ πŸ›‘ βœ…
ClassNames πŸ›‘ πŸ›‘ βœ…
Global styles βœ… βœ… βœ…
SSR βœ… βœ… βœ…
Theming βœ… βœ… βœ…
Tagged Templates βœ… βœ… βœ…
Object styles βœ… βœ… βœ…
Dynamic styles βœ… βœ… βœ…

Footnotes

  • [1] goober can render in any dom target. Meaning you can use goober to define scoped styles in any context. Really useful for web-components.
  • [2] Supported only via babel-plugin-transform-goober

SSR

You can get the critical CSS for SSR via extractCss. Take a look at this example: CodeSandbox: SSR with Preact and goober and read the full explanation for extractCSS and targets below.

Benchmarks

The results are included inside the build output as well.

Browser

Coming soon!

SSR

The benchmark is testing the following scenario:

import styled from '<packageName>';

// Create the dynamic styled component
const Foo = styled('div')((props) => ({
    opacity: props.counter > 0.5 ? 1 : 0,
    '@media (min-width: 1px)': {
        rule: 'all'
    },
    '&:hover': {
        another: 1,
        display: 'space'
    }
}));

// Serialize the component
renderToString(<Foo counter={Math.random()} />);

The results are:

goober x 200,437 ops/sec Β±1.93% (87 runs sampled)
[email protected] x 12,650 ops/sec Β±9.09% (48 runs sampled)
[email protected] x 104,229 ops/sec Β±2.06% (88 runs sampled)

Fastest is: goober

API

As you can see, goober supports most of the CSS syntax. If you find any issues, please submit a ticket, or open a PR with a fix.

styled(tagName: String | Function, forwardRef?: Function)

  • @param {String|Function} tagName The name of the DOM element you'd like the styles to be applied to
  • @param {Function} forwardRef Forward ref function. Usually React.forwardRef
  • @returns {Function} Returns the tag template function.
import { styled } from 'goober';

const Btn = styled('button')`
    border-radius: 4px;
`;

Different ways of customizing the styles

Tagged templates functions
import { styled } from 'goober';

const Btn = styled('button')`
    border-radius: ${(props) => props.size}px;
`;

<Btn size={20} />;
Function that returns a string
import { styled } from 'goober';

const Btn = styled('button')(
    (props) => `
  border-radius: ${props.size}px;
`
);

<Btn size={20} />;
JSON/Object
import { styled } from 'goober';

const Btn = styled('button')((props) => ({
    borderRadius: props.size + 'px'
}));

<Btn size={20} />;
Arrays
import { styled } from 'goober';

const Btn = styled('button')([
    { color: 'tomato' },
    ({ isPrimary }) => ({ background: isPrimary ? 'cyan' : 'gray' })
]);

<Btn />; // This will render the `Button` with `background: gray;`
<Btn isPrimary />; // This will render the `Button` with `background: cyan;`
Forward ref function

As goober is JSX library agnostic, you need to pass in the forward ref function for the library you are using. Here's how you do it for React.

const Title = styled('h1', React.forwardRef)`
    font-weight: bold;
    color: dodgerblue;
`;

setup(pragma: Function, prefixer?: Function, theme?: Function, forwardProps?: Function)

The call to setup() should occur only once. It should be called in the entry file of your project.

Given the fact that react uses createElement for the transformed elements and preact uses h, setup should be called with the proper pragma function. This was added to reduce the bundled size and being able to bundle an esmodule version. At the moment, it's the best tradeoff I can think of.

import React from 'react';
import { setup } from 'goober';

setup(React.createElement);

With prefixer

import React from 'react';
import { setup } from 'goober';

const customPrefixer = (key, value) => `${key}: ${value};\n`;

setup(React.createElement, customPrefixer);

With theme

import React, { createContext, useContext, createElement } from 'react';
import { setup, styled } from 'goober';

const theme = { primary: 'blue' };
const ThemeContext = createContext(theme);
const useTheme = () => useContext(ThemeContext);

setup(createElement, undefined, useTheme);

const ContainerWithTheme = styled('div')`
    color: ${(props) => props.theme.primary};
`;

With forwardProps

The forwardProps function offers a way to achieve the same shouldForwardProps functionality as emotion and styled-components (with transient props) offer. The difference here is that the function receives the whole props and you are in charge of removing the props that should not end up in the DOM.

This is a super useful functionality when paired with theme object, variants, or any other customisation one might need.

import React from 'react';
import { setup, styled } from 'goober';

setup(React.createElement, undefined, undefined, (props) => {
    for (let prop in props) {
        // Or any other conditions.
        // This could also check if this is a dev build and not remove the props
        if (prop === 'size') {
            delete props[prop];
        }
    }
});

The functionality of "transient props" (with a "$" prefix) can be implemented as follows:

import React from 'react';
import { setup, styled } from 'goober';

setup(React.createElement, undefined, undefined, (props) => {
    for (let prop in props) {
        if (prop[0] === '$') {
            delete props[prop];
        }
    }
});

Alternatively you can use goober/should-forward-prop addon to pass only the filter function and not have to deal with the full props object.

import React from 'react';
import { setup, styled } from 'goober';
import { shouldForwardProp } from 'goober/should-forward-prop';

setup(
    React.createElement,
    undefined,
    undefined,
    // This package accepts a `filter` function. If you return false that prop
    // won't be included in the forwarded props.
    shouldForwardProp((prop) => {
        return prop !== 'size';
    })
);

css(taggedTemplate)

  • @returns {String} Returns the className.

To create a className, you need to call css with your style rules in a tagged template.

import { css } from "goober";

const BtnClassName = css`
  border-radius: 4px;
`;

// vanilla JS
const btn = document.querySelector("#btn");
// BtnClassName === 'g016232'
btn.classList.add(BtnClassName);

// JSX
// BtnClassName === 'g016232'
const App => <button className={BtnClassName}>click</button>

Different ways of customizing css

Passing props to css tagged templates
import { css } from 'goober';

// JSX
const CustomButton = (props) => (
    <button
        className={css`
            border-radius: ${props.size}px;
        `}
    >
        click
    </button>
);
Using css with JSON/Object
import { css } from 'goober';
const BtnClassName = (props) =>
    css({
        background: props.color,
        borderRadius: props.radius + 'px'
    });

Notice: using css with object can reduce your bundle size.

We can also declare styles at the top of the file by wrapping css into a function that we call to get the className.

import { css } from 'goober';

const BtnClassName = (props) => css`
    border-radius: ${props.size}px;
`;

// vanilla JS
// BtnClassName({size:20}) -> g016360
const btn = document.querySelector('#btn');
btn.classList.add(BtnClassName({ size: 20 }));

// JSX
// BtnClassName({size:20}) -> g016360
const App = () => <button className={BtnClassName({ size: 20 })}>click</button>;

The difference between calling css directly and wrapping into a function is the timing of its execution. The former is when the component(file) is imported, the latter is when it is actually rendered.

If you use extractCSS for SSR, you may prefer to use the latter, or the styled API to avoid inconsistent results.

targets

By default, goober will append a style tag to the <head> of a document. You might want to target a different node, for instance, when you want to use goober with web components (so you'd want it to append style tags to individual shadowRoots). For this purpose, you can .bind a new target to the styled and css methods:

import * as goober from 'goober';
const target = document.getElementById('target');
const css = goober.css.bind({ target: target });
const styled = goober.styled.bind({ target: target });

If you don't provide a target, goober always defaults to <head> and in environments without a DOM (think certain SSR solutions), it will just use a plain string cache to store generated styles which you can extract with extractCSS(see below).

extractCss(target?)

  • @returns {String}

Returns the <style> tag that is rendered in a target and clears the style sheet. Defaults to <head>.

const { extractCss } = require('goober');

// After your app has rendered, just call it:
const styleTag = `<style id="_goober">${extractCss()}</style>`;

// Note: To be able to `hydrate` the styles you should use the proper `id` so `goober` can pick it up and use it as the target from now on

createGlobalStyles

To define your global styles you need to create a GlobalStyles component and use it as part of your tree. The createGlobalStyles is available at goober/global addon.

import { createGlobalStyles } from 'goober/global';

const GlobalStyles = createGlobalStyles`
  html,
  body {
    background: light;
  }

  * {
    box-sizing: border-box;
  }
`;

export default function App() {
    return (
        <div id="root">
            <GlobalStyles />
            <Navigation>
            <RestOfYourApp>
        </div>
    )
}

How about using glob function directly?

Before the global addon, goober/global, there was a method named glob that was part of the main package that would do the same thing, more or less. Having only that method to define global styles usually led to missing global styles from the extracted css, since the pattern did not enforce the evaluation of the styles at render time. The glob method is still exported from goober/global, in case you have a hard dependency on it. It still has the same API:

import { glob } from 'goober';

glob`
  html,
  body {
    background: light;
  }

  * {
    box-sizing: border-box;
  }
`;

keyframes

keyframes is a helpful method to define reusable animations that can be decoupled from the main style declaration and shared across components.

import { keyframes } from 'goober';

const rotate = keyframes`
    from, to {
        transform: rotate(0deg);
    }

    50% {
        transform: rotate(180deg);
    }
`;

const Wicked = styled('div')`
    background: tomato;
    color: white;
    animation: ${rotate} 1s ease-in-out;
`;

shouldForwardProp

To implement the shouldForwardProp without the need to provide the full loop over props you can use the goober/should-forward-prop addon.

import { h } from 'preact';
import { setup } from 'goober';
import { shouldForwardProp } from 'goober/should-forward-prop';

setup(
    h,
    undefined,
    undefined,
    shouldForwardProp((prop) => {
        // Do NOT forward props that start with `$` symbol
        return prop['0'] !== '$';
    })
);

Integrations

Babel plugin

You're in love with the styled.div syntax? Fear no more! We got you covered with a babel plugin that will take your lovely syntax from styled.tag and translate it to goober's styled("tag") call.

npm i --save-dev babel-plugin-transform-goober
# or
yarn add --dev babel-plugin-transform-goober

Visit the package in here for more info (https://github.com/cristianbote/goober/tree/master/packages/babel-plugin-transform-goober)

Babel macro plugin

A babel-plugin-macros macro for [πŸ₯œgoober][goober], rewriting styled.div syntax to styled('div') calls.

Usage

Once you've configured babel-plugin-macros, change your imports from goober to goober/macro.

Now you can create your components using styled.* syntax:.

import { styled } from 'goober/macro';

const Button = styled.button`
    margin: 0;
    padding: 1rem;
    font-size: 1rem;
    background-color: tomato;
`;

Want to use goober with Next.js? We've got you covered! Follow the example below or from the main examples directory.

npx create-next-app --example with-goober with-goober-app
# or
yarn create next-app --example with-goober with-goober-app

Want to use goober with Gatsby? We've got you covered! We have our own plugin to deal with styling your Gatsby projects.

npm i --save goober gatsby-plugin-goober
# or
yarn add goober gatsby-plugin-goober

Preact CLI plugin

If you use Goober with Preact CLI, you can use preact-cli-goober-ssr

npm i --save-dev preact-cli-goober-ssr
# or
yarn add --dev preact-cli-goober-ssr

# preact.config.js
const gooberPlugin = require('preact-cli-goober-ssr')

export default (config, env) => {
  gooberPlugin(config, env)
}

When you build your Preact application, this will run extractCss on your pre-rendered pages and add critical styles for each page.

CSS Prop

You can use a custom css prop to pass in styles on HTML elements with this Babel plugin.

Installation:

npm install --save-dev @agney/babel-plugin-goober-css-prop

List the plugin in .babelrc:

{
  "plugins": [
    "@agney/babel-plugin-goober-css-prop"
  ]
}

Usage:

<main
    css={`
        display: flex;
        min-height: 100vh;
        justify-content: center;
        align-items: center;
    `}
>
    <h1 css="color: dodgerblue">Goober</h1>
</main>

Features

  • Basic CSS parsing
  • Nested rules with pseudo selectors
  • Nested styled components
  • Extending Styles
  • Media queries (@media)
  • Keyframes (@keyframes)
  • Smart (lazy) client-side hydration
  • Styling any component
    • via const Btn = ({className}) => {...}; const TomatoBtn = styled(Btn)`color: tomato;`
  • Vanilla (via css function)
  • globalStyle (via glob) so one would be able to create global styles
  • target/extract from elements other than <head>
  • vendor prefixing

Sharing style

There are a couple of ways to effectively share/extend styles across components.

Extending

You can extend the desired component that needs to be enriched or overwritten with another set of css rules.

import { styled } from 'goober';

// Let's declare a primitive for our styled component
const Primitive = styled('span')`
    margin: 0;
    padding: 0;
`;

// Later on we could get the primitive shared styles and also add our owns
const Container = styled(Primitive)`
    padding: 1em;
`;

Using as prop

Another helpful way to extend a certain component is with the as property. Given our example above we could modify it like:

import { styled } from 'goober';

// Our primitive element
const Primitive = styled('span')`
    margin: 0;
    padding: 0;
`;

const Container = styled('div')`
    padding: 1em;
`;

// At composition/render time
<Primitive as={'div'} /> // <div class="go01234" />

// Or using the `Container`
<Primitive as={Container} /> // <div class="go01234 go56789" />

Autoprefixer

Autoprefixing is a helpful way to make sure the generated css will work seamlessly on the whole spectrum of browsers. With that in mind, the core goober package can't hold that logic to determine the autoprefixing needs, so we added a new package that you can choose to address them.

npm install goober
# or
yarn add goober

After the main package is installed it's time to bootstrap goober with it:

import { setup } from 'goober';
import { prefix } from 'goober/prefixer';

// Bootstrap goober
setup(React.createElement, prefix);

And voilΓ ! It is done!

TypeScript

goober comes with type definitions build in, making it easy to get started in TypeScript straight away.

Prop Types

If you're using custom props and wish to style based on them, you can do so as follows:

interface Props {
    size: number;
}

styled('div')<Props>`
    border-radius: ${(props) => props.size}px;
`;

// This also works!

styled<Props>('div')`
    border-radius: ${(props) => props.size}px;
`;

Extending Theme

If you're using a custom theme and want to add types to it, you can create a declaration file at the base of your project.

// goober.d.t.s

import 'goober';

declare module 'goober' {
    export interface DefaultTheme {
        colors: {
            primary: string;
        };
    }
}

You should now have autocompletion for your theme.

const ThemeContainer = styled('div')`
    background-color: ${(props) => props.theme.colors.primary};
`;

Browser support

goober supports all major browsers (Chrome, Edge, Firefox, Safari).

To support IE 11 and older browsers, make sure to use a tool like Babel to transform your code into code that works in the browsers you target.

Contributing

Feel free to try it out and checkout the examples. If you wanna fix something feel free to open a issue or a PR.

Backers

Thank you to all our backers! πŸ™

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website.

goober's People

Contributors

agneym avatar agriffis avatar alexey-koran avatar baosoy avatar chrstntdd avatar cindyvciandt avatar cristianbote avatar danielweck avatar dependabot[bot] avatar devrnt avatar dios-david avatar donysukardi avatar franciscop avatar gerhardsletten avatar greenkeeper[bot] avatar guybedford avatar hotell avatar iguessitsokay avatar jlalmes avatar jovidecroock avatar jviide avatar ksenginew avatar marvinhagemeister avatar michael-klein avatar pmkroeker avatar realstandal avatar rschristian avatar tenphi avatar vandreleal avatar wildpow 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

goober's Issues

(feature) `createGlobalStyle`

Should be awesome to have this feature.

Food for thought:

import { createGlobalStyle } from "goober";

const GlobalStyle = createGlobalStyle`
  body {
    display: block;
  }
`;

// Then to use it
<GlobalStyle />
import { styled } from "goober";

// Creating a 'style' tag would reflect the need for defining it globally?
const GlobalStyle = styled("style")`
  body {
    display: block;
  }
`;

// Then to use it
<GlobalStyle />

An in-range update of babel7 is breaking the build 🚨

There have been updates to the babel7 monorepo:

    • The devDependency @babel/core was updated from 7.7.7 to 7.8.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the babel7 group definition.

babel7 is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

css(taggedTemplate) styntax is returning a string instead of a function

I was following the documentation for the css syntax and trying to test it on my project I found that css is returning a string with the classname hash instead of returning a function as showed in the docs.

https://github.com/cristianbote/goober/blob/master/README.md#csstaggedtemplate

I took a look into the source code and it seems that returning the hash instead of the function seems intentional. So I'm guessing that this is matter of updating the docs? Or am I missing something?

Perf tests

We should benchmark and create a baseline for each part of the project.

(bug) Rule orders are not kept when extending a previously defined component

Having these defined:

const First = styled("div")`
    color: red;
`;

const Second = styled(First)`
    color: dodgerblue;
`;

// works
<First /> // red
<Second /> // dodgerblue

// does not
<Second /> // red
<First /> // red

This is mainly a concurrency issue. The css compilation starts when the component would end-up created. Should start at creation, or at least assign a slot and then commit to that slot when rendered.

An in-range update of emotion is breaking the build 🚨

There have been updates to the emotion monorepo:

    • The devDependency @emotion/core was updated from 10.0.22 to 10.0.27.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the emotion group definition.

emotion is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Handle refs in React

Seems that refs for functional components can not be forwarded. Goober should handle that.

next.js template

Create a next.js template, to make it easier for people to adopt it.

maybe helpful

similar implementation here, hope you find something helpful. the stylesheet implementation is especially nice, try it in an IDE.

//@ts-ignore
import {h} from 'preact'

import {Properties} from 'csstype'
export interface CSSProperties extends Properties<string | number> {}


//--------------------------------------------types ----------------------------------//
type DomProps = JSX.HTMLAttributes & JSX.DOMAttributes
type CSX = { 
  css?: CSSProperties,
  classes?: any
  styles?: any,
  toString?: any
}

type StyledCSX = DomProps & CSX
type Proptional<P> = CSSProperties | ((...args: P[]) => CSSProperties)


//--------------------------variable setup and statics------------------------------//
let cache = {}
let prefix = 'x'

let rules: CSSStyleRule[] = []
let insert = (rule: CSSStyleRule) => void rules.push(rule)

const hyph = s => s.replace(/[A-Z]|^ms/g, '-$&').toLowerCase()
const mx = (rule, media) => (media ? `${media}{${rule}}` : rule)
const rx = (cn, prop, val) => `.${cn}{${hyph(prop)}:${val}}`
const noAnd = s => s.replace(/&/g, '')
const parse = (obj, child = '', media?) =>
  Object.keys(obj).map(key => {
      const val = obj[key]
      if (val === null) return ''
      if (typeof val === 'object') {
        const m2 = /^@/.test(key) ? key : null
        const c2 = m2 ? child : child + key
        return parse(val, c2, m2 || media)
      }
      const _key = key + val + child + media
      if (cache[_key]) return cache[_key]
      const className = prefix + rules.length.toString(36)
      insert(mx(rx(className + noAnd(child), key, val), media))
      cache[_key] = className
      return className
    })
    .join(' ')


export const cxs = (...styles) => styles.map(style => parse(style)).join(' ').trim();


cxs.toString = () => rules.sort().join('')

cxs.reset = () => {
  cache = {}
  while (rules.length) rules.pop()
}

cxs.prefix = val => (prefix = val)

if (typeof document !== 'undefined') {
  const sheet = document.head.appendChild(document.createElement('style')).sheet as CSSStyleSheet
  insert = (rule: CSSStyleRule & string) => {
    rules.push(rule as CSSStyleRule)
    sheet.insertRule(rule, sheet.cssRules.length)
  }
}



export function styled<P = any>(C) {
  return (...args: Proptional<P>[]) => {
    const Comp = (props: P & StyledCSX) => {
      const stylePropKeys = [...Object.keys({}), 'css', 'classes', 'styles', 'toString']
      //const styleProps = Object.assign({ theme: defined(context.theme, props.theme, {}) }, props)
      const nextProps: any = {}
      for (let key in props) {
        if (stylePropKeys.includes(key)) continue
        nextProps[key] = props[key]
      }

      nextProps.className = [
        nextProps.className,
        ...args
          .map(proptional => (typeof proptional === 'function' ? proptional(props) : proptional))
          .filter(s => !!s)
          .map(s => cxs(s)),
        cxs(props.css || {}),
      ].join(' ').trim()

      return h(C, nextProps)
    }
    return Comp
  }
}

//arrow or function for constructor name, idk
export let withStyles = (c, s) => styled(c)(s);



export declare type CSSClassNames<K extends string> = Record<K, string>;

export function stylesheet<T extends string = any>(classes: Record<T, CSSProperties>): CSSClassNames<T> {
  //let $debugName = this.constructor.name.toString()
  const classNames = Object.getOwnPropertyNames(classes) as (T)[];
  const result = {} as CSSClassNames<T>
  for (let className of classNames) {
    const classDef = classes[className] as CSSProperties
    if (classDef) {
      //$debugName = className
      //classDef.$debugName = className
      result[className] = cxs(classDef);
    }
  }
  return result as Record<T, string>;
}

//export {cxs, styled, withStyles, stylesheet}
export default styled


supper hacky usage
```tsx
import { observable } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { cxs, styled, withStyles, stylesheet } from '../common/ux/styled/csx';


let csxcss1 = cxs({
  backgroundColor: 'yellow',
  border: 'peach 5px solid',
  ':hover': {
    backgroundColor: 'black'
  }
})

let csxcss3 = cxs({
  backgroundColor: 'gray',
  border: 'gray 5px solid',
  ':hover': {
    backgroundColor: 'black'
  }
})

let csxcss = observable.box(csxcss1)
csxcss.set(csxcss3)


const child = cxs({
  backgroundColor: 'aqua',
  color: 'black',
  '> span': {
    color: 'tomato'
  }
})

let someObject = {

}

let CxsChild = props => <div className={child} {...props}>im black CSX WITH '> SPAN' Selector<span>im tomato</span></div>
let CxsChildWithStyles = withStyles(CxsChild, {backgroundColor: 'green'})

//Give me your tired, your poor,Your huddled masses yearning to breathe free
let CxsChildWithStylesAndNewProps = withStyles(CxsChild, (props => ({backgroundColor: props.bg || 'red'})))

let CxsDiv = props => <div className={cxs({backgroundColor: 'yellow', border: 'green 5px solid'})} {...props}>cxs div</div>

let CxsDiv2 = props => <div className={csxcss3} {...props}>cxs div2</div>

let CxsDivMobxOverride = props => <div className={csxcss} {...props}>if this is gray mobx.box.set() works else if peach failed</div>



let StyledTester = styled('div')({
  backgroundColor: 'orange',
  border: 'teal 5px solid'
})

type BgProp = {
  bg?: 'green' | 'blue'
}

let CsxStyledWithProps = styled<BgProp>('div')(props => ({
  backgroundColor: props.bg || 'red',
  height: '50px',
  ':hover': {
    color: 'black',
    backgroundColor: 'purple'
  }
}))

let WrapperTest = styled(StyledTester)(({
  backgroundColor: 'blue'
}))


let cxsStylesheet = stylesheet({
  root: {
    background: 'green'
  }
})

export let WithStylesheetEz = observer((props) =>
<div>
  <div className={cxsStylesheet.root}>Using a stylesheet object, cool</div>
</div>
)



export let StyledPage = observer((props) =>
<div>
  <CxsChild />
  <CxsChildWithStyles>withStyles works if green</CxsChildWithStyles>
  <CxsChildWithStylesAndNewProps/>
  <CxsChildWithStylesAndNewProps bg="purple"/>
  <CxsDiv/>
  <CxsDivMobxOverride/>
  <CxsDiv2></CxsDiv2>
  <StyledTester>typestyled no props</StyledTester>
  <WrapperTest>overriding the above by wrapping with {String.raw`styled(ComponentName){backgroundColor: blue}`}</WrapperTest>
  <CsxStyledWithProps>
    {String.raw`hover me for black`}
  </CsxStyledWithProps>
  <WithStylesheetEz/>
</div>
)

export let DatasetsPage = StyledPage

css properties are trimmed for whitespace

transition: transform 300ms ease-out -> transition: transform300msease-out.

I think the whitespace removal should not be that eager to remove the properties πŸ˜„
Also, I should add a test for that.

Option for className or class?

_props.className = css.apply(_ctx, _args) + (_previousClassName ? " " + _previousClassName : "");

It would be great if we could utilise class instead of className

I utilize class as I'm writing direct one to one with static html

TypeError when using with TypeScript

Hi there! Amazing work with this library.

I'm using it with Preact's TypeScript template, and it's throwing an error since the type expects children to be a property on the goober StyledVNode:

image

When I change the definition to:

export const Text = styled<{ children: any }>("span")`
  color: lightblue;
`;

it works fine.

The examples don't seem to have to specify this, so is this something with my code or the library?

Here are my relevant dependencies:

    "goober": "^1.6.1",
    "preact": "^10.0.0",
    "typescript": "^3.7.4"

Much appreciated!

SSR Behavior

Firstly nice lib, a minimal css-in-js solution is sorely needed!

From what I can see and there is a single global style cache and the extractCss() function will extract ALL cached styles? Is it then the case that, when rendering different content per page, ALL styles are embedded on each page (eventually)?

Drop the extra function call for `css` API

While talking with @michael-klein about support for web-components, we realized that the extra call for vanilla/css API it's just in the way. So, let's drop it! πŸ’―

const FooClass = css`
  color: red;
`();

// should be
const FooClass = css`
  color: red;
`;

Theming solution?

Thanks for this absolute awesomeness! I'm super excited, as on one of my projects we are currently try to find powerful, yet very lightweight solutions, and goober seems to fit in perfectly.
However I use styled-components on other projects for many reasons, but one of them surely is the powerful theming built-in.
Do you plan something similar, or have any idea how to do something like that?

css returning same hash for different properties.

It seems like every call to css is outputting the same hash.

const tickLabel = css({
    'font-size': '1em',
    'cursor': 'default',
    'user-select': 'none',
    '>.tick>line': {
        'stroke-width': '1px',
        'stroke-opacity': 0.5,
        'shape-rendering': 'crispEdges',
    },
    '>path': {
        'stroke-width': '2px',
    },
});

const gridStyle = css({
    '>path': {
        stroke: 'none',
    },
    '>.tick>line': {
        'stroke-width': '1px',
        'stroke-opacity': 0.5,
    },
});
console.log(tickLabel, gridStyle);

outputs g015475 g015475

Could this be related to the caching update? Seemed to be working properly before that was added.

(feature) Should lazy hydrate on the client

Thinking that, on the client, instead of always recreating the sheet, we should:

  • Check for a existent sheet element
  • If exists, check for existing rule and do not write it again(might be causing flickering)

Where to discuss about and direction of goober? Should we keep gitter, slack or ...?

Currently goober has the gitter chat room to be able to chat and discuss. Recently I've setup a slack workspace as well. But I'm wondering what would be the best option? I'm currently online constantly on slack so I'm really inclined to move the discussion in there.

Would you as part of the community, use slack to get in touch and talk about goober?

Looking forward to your feedback! ✌️

Edit: Here's the slack space invite link https://join.slack.com/t/gooberdev/shared_invite/enQtOTM5NjUyOTcwNzI1LWUwNzg0NTQwODY1NDJmMzQ2NzdlODI4YTM3NWUwYjlkY2ZkNGVmMTFlNGMwZGUyOWQyZmI4OTYwYmRiMzE0NGQ

Add support for @import

@import url('https://fonts.googleapis.com/css?family=Roboto'); will translate into {https://fonts.googleapis.com/css?family=Roboto');}

Trim a few bytes, but mutate arguments

Goober trying be as small as possible. Does it make sense to trim bytes by using shift instead slice by mutating arguments in css()?

function css() {
    const val = arguments.shift();
    const ctx = this || {};
    const _val = val.call ? val(ctx.p) : val;

    return hash(
        _val.map ? compile(_val, arguments, ctx.p) : _val,
        getSheet(ctx.target),
        ctx.g,
        ctx.o
    );
}

1017B > 1014B

Bug - Cannot find csstypes

As csstypes is listed as a devDependency it cannot be found when trying to import to the types file.

node_modules/goober/src/goober.d.ts:1:57 - error TS2307: Cannot find module 'csstype'.

1 import { PropertiesHyphen as CSSPropertiesHyphen } from 'csstype';

Add in-memory cache for classNames and compiled css

At the moment, there's no cache system to bail the heavy lifting class and css generation. Adding it, improves the perf, quite a bit.

The test case was:
200 items, 1000 raf calls

Before
screenshot 2019-03-02 at 17 47 39

After
screenshot 2019-03-02 at 17 49 14

So, clearly, caching should be added. The thing that needs to be figured out, is when should the wipe/invalidation happen, since these are kept in memory.

@font-face escaping

There seems to be an issue with the @font-face notation. When supplied via glob() it gets double { } so this

@font-face { font-family: "Source Sans Pro"; font-style: normal; font-weight: 400; src: local("Source Sans Pro Regular"), local("SourceSansPro-Regular"), url(${woff2}) format("woff2"), url(${woff1}) format("woff"); } translates to

@font-face{{font-family:"Source Sans Pro";font-style:normal;font-weight:400;src:local("Source Sans Pro Regular"), local("SourceSansPro-Regular"),url(/c85615b296302af51e683eecb5e371d4.woff2) format("woff2"),url(/a75563d7b9e5b1db163971b9a2e66216.woff) format("woff");}}

Removing the double { resolved the issue and the browser loads the webfonts

Typescript - Expected X arguments, but got Y

Hi there! Awesome work with this library.

I'm using preact-custom-element with TypeScript, and it's throwing an error since when trying to use props inside a styled more than once

image

I'm getting:

Expected 1-2 arguments, but got 3.ts(2554)

The examples don't seem to have to specify this, so is this something with my code or the library?

Here are my relevant dependencies:

 "goober": "^1.6.3",
 "preact": "^10.2.1",
"typescript": "^3.7.5"

Type definitions for styled() functions

When using typescript with styled component libraries, you can pass the type of the props to the styled Component, to enforce correct property names and having autocompletion for the props object.

Example

type ParagaphType = {
  style?: object;
  color?: string;
};

const P = styled('div')<ParagaphType>`
  color: ${props => (props.color ? props.color : 'black')};
  margin: 0;
  padding: 0;
  ${props => props.style && { ...props.style }}
`;

With Goober, I'm getting the following typescript problem when implementing the same syntax.

image

Could we update the type defs for Goober to have the autocompletion as well?

Add support for object styles (JSS)

Basically now, styled API could bypass the whole tagged template processing, and go straight to object to css compilation.

const Element = styled("div")`
  color: red;

  &:hover {
    color: blue;
  }
`;

// This should bypass the tagged template processing
const Element = styled("div")({
  "color": "red",
  "&:hover": {
    "color": "blue"
  }
});

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.