diff options
author | Nick Van Doorn <vandoorn.nick@gmail.com> | 2019-03-29 00:35:56 -0700 |
---|---|---|
committer | Nick Van Doorn <vandoorn.nick@gmail.com> | 2019-03-29 00:35:56 -0700 |
commit | 65220cc8db0d7c63f49627526466d54969958fe1 (patch) | |
tree | e2989cb16576f177e60f75f9a733487adfd868f5 /src/use-sunlight.js | |
parent | 51687fe7a2de2d4ed2800af46f9b6a9ac6c929ee (diff) |
Init commit
Diffstat (limited to 'src/use-sunlight.js')
-rw-r--r-- | src/use-sunlight.js | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/src/use-sunlight.js b/src/use-sunlight.js new file mode 100644 index 0000000..2ca279b --- /dev/null +++ b/src/use-sunlight.js @@ -0,0 +1,32 @@ +import { useState } from 'react' +import { useGeolocation as globalUseGeolocation } from './use-geolocation' +import { useInterval } from './use-interval' +import suncalc from 'suncalc' + +export const computeLightLevel = ( + { loading, latitude, longitude }, + date = new Date() +) => { + if (loading || !latitude || !longitude) return 0 + let { altitude } = suncalc.getPosition(date, latitude, longitude) + if (altitude < 0) { + altitude += 2 * Math.PI + } + // on or below the horizon is considered "no light" + if (altitude >= Math.PI) return 0 + // otherwise, return a relative altitude + // where n is an int in [0,10] + // and 10 represents the zenith (straight over your head) + return Math.round(10 * Math.sin(altitude)) +} + +// make a location hook injectable such that we can test this +export const useSunlight = (useGeolocation = globalUseGeolocation) => { + const geoLocation = useGeolocation() + + const [lightLevel, setLightLevel] = useState(computeLightLevel(geoLocation)) + useInterval(() => { + setLightLevel(computeLightLevel(geoLocation)) + }, 1000) + return [lightLevel] +} |