最近ReactのスタイリングをするときにStyled-componentを使うのにはまってるんですが、hyperappでも同じようにできたらいいなぁと思って探してみたらあったので紹介です。
Picostyle
Picostyle is a 0.4 KB CSS-in-JS library for use with frameworks that expose an h function.
Picostyleは0.4kbのCSS-in-JSのライブラリで、h
関数を公開しているフレームワークと共に使うそうで、現在動作確認ができているのが、hyperappとpicodomの2つです。
インストール
npmやyarn、cndからのインストールが可能です。
npm i --save picostyle
yarn add picostyle
<script src="https://unpkg.com/picostyle"></script>
scriptタグで読み込んだ場合、window.picostyle
でアクセスできるようになるそうです。
使い方
picostyleはh
関数を公開しているフレームワークと共に使われます。そして、picostyle
関数にh
関数をわたすと、そのh
関数と同様の振る舞いをする高階関数を返します。
import { h } from "some-framework"
import picostyle from "picostyle"
const style = picostyle(h)
この高階関数はタグ名または、スタイルの適用されていないコンポーネントを受け取り、スタイル(JSON)を受け取る関数を返します。
// Styled component from tag name
const Wrapper = style("div")({
minHeight: "100vh",
background: "#000",
})
// Styling an un-styled component
const Component = text => h("h1", {}, text)
const Text = style(Component)({
color: "#fff",
})
もし、propsの値からスタイルを定義したい場合は、JSONのかわりに関数を渡すことができます。
// Here we set the color of the button, based on the color prop
const Button = style("button")(props => ({
color: props.color
}))
picostyleは受けとったJSON(または関数)を単純なCSSに変更し、ドキュメントの先頭のスタイルタグに埋め込みます。picostyleによるスタイル付けされたコンポーネントはユニークな識別子をクラス名として持っています。
そして、出力はInlineStyleではなくStyleSheetであるため、MediaQuery、擬似クラス、ネストした子要素などの複雑なスタイルを書けるみたいです。
サンプル
http://sosukesuzuki.me/ 僕のgh-pagesですが、これはhyperappとpicostyleで作りました。
リポジトリは、https://github.com/sosukesuzuki/sosukesuzuki.github.io/ です。
(追記:2018.4.6、僕のgh-pagesは更新されHyperappを使ったものではなくなりました。)
感想
便利だけど、それこそStyled-componentsのようにCSSみたいに書けたらいいですね。