MCPcopy
hub / github.com/cristianbote/goober

github.com/cristianbote/goober @v2.1.19 sqlite

repository ↗ · DeepWiki ↗ · release v2.1.19 ↗
68 symbols 178 edges 70 files 4 documented · 6%
README

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

  • React Round Up 👉 https://reactroundup.com/wrangle-your-css-in-js-for-peanuts-using-goober-ft-cristian-bote-rru-177
  • ReactDay Berlin 2019 👉 https://www.youtube.com/watch?v=k4-AVy3acqk
  • PodRocket by LogRocket 👉 https://podrocket.logrocket.com/goober
  • ngParty 👉 https://www.youtube.com/watch?v=XKFvOBDPeB0

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 🛑 ✅ *3
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
  • [3] Emotion has a framework-agnostic css function. See https://emotion.sh/docs/@emotion/css

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)
styled-components@5.2.1 x 12,650 ops/sec ±9.09% (48 runs sampled)
emotion@11.0.0 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.

```js import { css } from 'goober';

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

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

Extension points exported contracts — how you extend this code

DefaultTheme (Interface)
(no doc)
goober.d.ts
CSSAttribute (Interface)
(no doc)
global/global.d.ts
DefaultTheme (Interface)
(no doc)
ts-tests/test-api.tsx
StyledFunction (Interface)
(no doc)
goober.d.ts
ButtonProps (Interface)
(no doc)
ts-tests/test-api.tsx
CSSAttribute (Interface)
(no doc)
goober.d.ts

Core symbols most depended-on inside this repo

styled
called by 52
src/styled.js
parse
called by 20
src/core/parse.js
extractCss
called by 19
src/core/update.js
getSheet
called by 16
src/core/get-sheet.js
setup
called by 15
src/styled.js
update
called by 12
src/core/update.js
astish
called by 11
src/core/astish.js
hash
called by 10
src/core/hash.js

Shape

Function 62
Interface 6

Languages

TypeScript100%

Modules by API surface

ts-tests/test-api.tsx7 symbols
benchmarks/perf.cjs5 symbols
packages/babel-plugin-transform-goober/index.js4 symbols
src/styled.js3 symbols
src/core/__tests__/compile.test.js3 symbols
goober.d.ts3 symbols
benchmarks/perf.compare.modern.cjs3 symbols
benchmarks/perf.compare.cjs3 symbols
src/core/update.js2 symbols
src/core/hash.js2 symbols
src/__tests__/styled.test.js2 symbols
should-forward-prop/src/index.js2 symbols

Dependencies from manifests, versioned

@ampproject/filesize4.0.0 · 1×
@babel/core7.2.2 · 1×
@babel/plugin-transform-react-jsx7.7.0 · 1×
@babel/preset-env7.3.1 · 1×
@docusaurus/core2.0.0-alpha.70 · 1×
@docusaurus/preset-classic2.0.0-alpha.70 · 1×
@docusaurus/theme-search-algolia2.0.0-alpha.70 · 1×
@emotion/core11.0.0 · 1×
@emotion/react11.1.4 · 1×
@emotion/styled11.0.0 · 1×
@mdx-js/react1.6.21 · 1×
@preact/preset-vite2.10.2 · 1×

For agents

$ claude mcp add goober \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact