cristianbote / goober Goto Github PK
View Code? Open in Web Editor NEWπ₯ goober, a less than 1KB π css-in-js alternative with a familiar API
Home Page: https://goober.rocks
License: MIT License
π₯ goober, a less than 1KB π css-in-js alternative with a familiar API
Home Page: https://goober.rocks
License: MIT License
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
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.
This is all @michael-klein's initiative πto add support for web-components with a parametrized target for styled
.
@michael-klein feel free to add more details. I've created this, to just put it on the roadmap π―
Thanks for the great library gatsby-plugin-goober
but couldn't get the tests passing.
I am not really good with the tests π¬.
Figure out of this feature is needed
Should support @keyframes
I found this guy with the name Nikhil Saraf who published goober fork under his name as @nksaraf/goober on npm!!
Github https://github.com/nksaraf
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.
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
Hey! π
Great initiative! Was wondering how your project is so much smaller than the other ones though, would be good to maybe add a write-up about this to the README.
Just an idea πΈ
As @UpperCod stated on twitter(https://twitter.com/Uppercod/status/1118912434239090688).
&:hover,
&:focus {
border: 0;
span {
index: unset;
}
}
// Should get transpiled to:
&:hover,
&:focus {
border: 0;
}
&:hover span,
&:focus span {
index: unset;
}
He kindly already has a fix for this #47! π
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 />
There's an issue where using the same web component twice would end-up not styled, but with the className generated.
Add unit/e2e tests for everything.
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.
Seems that refs for functional components can not be forwarded. Goober should handle that.
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?
Apparently we can go as low as IE10 π but we need to document it.
devDependency
@emotion/core was updated from 10.0.22
to 10.0.27
.devDependency
@emotion/styled was updated from 10.0.23
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.
There is a collection of frequently asked questions. If those donβt help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot π΄
Create a next.js template, to make it easier for people to adopt it.
Line 21 in 8319170
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
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
:
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!
As @jviide built this https://github.com/jviide/babel-plugin-transform-styledodo we could leverage it and create a babel plugin, to help people used with the styled.div
pattern.
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"
}
});
@import url('https://fonts.googleapis.com/css?family=Roboto');
will translate into {https://fonts.googleapis.com/css?family=Roboto');}
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;
`;
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?
It'll be helpful to have a lerna
monorepo, so we could have the same related packages inside one main repo.
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
We should benchmark and create a baseline for each part of the project.
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.
Should support @media
queries
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
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
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"
I've tried adding it, but it went over the 1000B
so it's under our target. It's not that difficult to add support for it, basically here: https://github.com/cristianbote/goober/blob/master/src/core/parse.js#L37 we should just do a regex transform.
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';
devDependency
@babel/core was updated from 7.7.7
to 7.8.0
.devDependency
@babel/plugin-transform-react-jsx was updated from 7.8.0
to 7.8.3
.devDependency
@babel/preset-env was updated from 7.8.0
to 7.8.2
.π¨ 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.
There is a collection of frequently asked questions. If those donβt help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot π΄
Seems like there's a issue with nested selectors and media queries.
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)?
Hi, thank you for you awesome tool? Is it possible to share with postcss plugins?
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.
Could we update the type defs for Goober to have the autocompletion as well?
Thinking that, on the client, instead of always recreating the sheet
, we should:
existent
sheet elementThank you for the great library! We currently use styled-components and find ourselves needing styles based on props fairly often. (i.e., https://www.styled-components.com/docs/basics#passed-props)
Haven't looked into styled-components' internals, but would this be possible without too much bloat?
Maintenance could be dreadful, so, having the functionality broke down into pure functions, maybe?, could make it easier to maintain.
To make it easier to adopt goober, we should have a preact-cli template, ready to go!
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
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.