summaryrefslogtreecommitdiff
path: root/src/sunlight-theme.js
blob: 84933567c598e6bb19b618e6f58c449b51c1f466 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import React from 'react'
import { useSunlight } from 'use-sunlight'
import { ThemeProvider } from 'emotion-theming'

const notFn = t => typeof t !== 'function'

const pipeReducer = (a, b) => arg => b(a(arg))

const pipe = (...fns) => {
  if (fns.some(notFn)) throw new Error('All middleware must be a function')
  return fns.reduce(pipeReducer, k => k)
}

export const SunlightTheme = ({ children, middleware }) => {
  const [lightLevel] = useSunlight()
  const theme = { lightLevel }
  // if we have at least one middleware function,
  // apply them in a pipe (left to right)
  const transformedTheme =
    middleware && middleware.length ? pipe(...middleware)(theme) : theme
  return <ThemeProvider theme={transformedTheme}>{children}</ThemeProvider>
}