Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: set up favorites worker. #58

Merged
merged 1 commit into from
Oct 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/components/src/input/mod.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ const Close = styled(CloseIcon)`
position: absolute;
right: 10px;
`
const StyledInput = styled.input<{
const StyledInput = styled.input.attrs({ autoComplete: 'one-time-code' })<{
$color: string
$size: Size
$fontSize: string
Expand Down
48 changes: 39 additions & 9 deletions packages/ui/src/components/favoriteStop.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import styled from 'styled-components'
import { useCallback, useMemo } from 'react'
import { Star } from '@busmap/components/icons/star'
import { Tooltip } from '@busmap/components/tooltip'
import { SY30T } from '@busmap/components/colors'

import type { FC } from 'react'
import type { Stop } from '../types.js'
import { useGlobals } from '../globals.js'
import { useStorage, useStorageDispatch } from '../contexts/storage.js'

interface FavoriteStopProps {
stop?: Stop
favorite: boolean
}
import type { FC } from 'react'
import type { Favorite } from '../contexts/storage.js'

const Tip = styled(Tooltip)`
display: flex;
Expand All @@ -20,12 +19,43 @@ const Button = styled.button`
margin: 0;
background: none;
`
const FavoriteStop: FC<FavoriteStopProps> = ({ stop, favorite = false }) => {
const worker = new Worker(new URL('../workers/favorites.ts', import.meta.url), {
type: 'module'
})
const FavoriteStop: FC = () => {
const storage = useStorage()
const storageDispatch = useStorageDispatch()
const { agency, route, direction, stop } = useGlobals()
const favorite = useMemo(() => {
return storage.favorites?.find(fav => {
return (
`${fav.route.id}${fav.direction.id}${fav.stop.id}` ===
`${route?.id}${direction?.id}${stop?.id}`
)
})
}, [storage.favorites, stop, route, direction])
const onClick = useCallback(() => {
if (favorite) {
storageDispatch({ type: 'favoriteRemove', value: favorite })
worker.postMessage({ action: 'stop', favorite })
} else if (agency && route && direction && stop) {
const add: Favorite = {
stop: stop,
agency: agency,
route: { id: route.id, title: route.title ?? route.shortTitle },
direction: { id: direction.id, title: direction.title ?? direction.shortTitle }
}

storageDispatch({ type: 'favoriteAdd', value: add })
worker.postMessage({ action: 'start', favorite: add })
}
}, [storageDispatch, agency, route, direction, stop, favorite])

if (stop) {
return (
<Tip title={favorite ? 'Favorite stop.' : 'Add to favorites.'}>
<Tip title={favorite ? 'Remove favorite.' : 'Add favorite.'}>
<Button>
<Star size="small" color={SY30T} outlined={!favorite} />
<Star size="small" color={SY30T} outlined={!favorite} onClick={onClick} />
</Button>
</Tip>
)
Expand Down
15 changes: 15 additions & 0 deletions packages/ui/src/components/favorites.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { useStorage } from '../contexts/storage.js'

import type { FC } from 'react'

const Favorites: FC = () => {
const { favorites } = useStorage()

if (!favorites || !favorites.length) {
return <div>⭐ You can select your favorite stops from the bus selector tab. ⭐</div>
}

return favorites.map(fav => <p key={fav.stop.id}>{fav.stop.title}</p>)
}

export { Favorites }
2 changes: 1 addition & 1 deletion packages/ui/src/components/selectors/stops.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ const Stops: FC<Props> = ({
onClear={onClear ?? true}
onSelect={onSelect}
/>
<FavoriteStop stop={selected} favorite={false} />
<FavoriteStop />
</FormItem>
)
}
Expand Down
6 changes: 4 additions & 2 deletions packages/ui/src/components/selectors/useSelectorProps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ interface SelectorProps<T> {
}
interface SelectorSpreadProps<T> {
onClear: AutoSuggestProps<T>['onClear']
caseInsensitive: boolean
inputBoundByItems: boolean
size: AutoSuggestProps<T>['size']
color: AutoSuggestProps<T>['color']
value: AutoSuggestProps<T>['value']
selectOnTextMatch: AutoSuggestProps<T>['selectOnTextMatch']
caseInsensitive: AutoSuggestProps<T>['caseInsensitive']
}

const useSelectorProps = <T>({ selected }: SelectorProps<T>): SelectorSpreadProps<T> => {
Expand All @@ -23,8 +24,9 @@ const useSelectorProps = <T>({ selected }: SelectorProps<T>): SelectorSpreadProp
const props = useMemo(
() => ({
onClear: true,
caseInsensitive: true,
caseInsensitive: false,
inputBoundByItems: true,
selectOnTextMatch: true,
size: 'small' as AutoSuggestProps<T>['size'],
color: isLightMode ? 'black' : PB90T,
value: selected ?? undefined,
Expand Down
74 changes: 72 additions & 2 deletions packages/ui/src/contexts/storage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,21 @@ import { isAMode, isASpeedUnit, isAPredictionFormat } from './util.js'

import type { FC, ReactNode, Dispatch } from 'react'
import type { Mode, SpeedUnit, PredictionFormat } from './util.js'
import type { Agency, RouteName, DirectionName, Stop } from '../types.js'

interface Favorite {
agency: Agency
route: RouteName
direction: DirectionName
stop: Stop
}
interface StorageState {
predsFormat?: PredictionFormat
vehicleSpeedUnit?: SpeedUnit
vehicleColorPredicted?: boolean
themeMode?: Mode
favorites?: Favorite[]
}

interface PredsFormatUpdate {
type: 'predsFormat'
value?: PredictionFormat
Expand All @@ -28,16 +35,54 @@ interface ThemeModeUpdate {
type: 'themeMode'
value?: Mode
}
interface FavoriteAdded {
type: 'favoriteAdd'
value: Favorite
}
interface FavoriteRemoved {
type: 'favoriteRemove'
value: Favorite
}
type StorageAction =
| PredsFormatUpdate
| VehicleSpeedUnitUpdate
| VehicleColorPredictedUpdate
| ThemeModeUpdate
| FavoriteAdded
| FavoriteRemoved

const reducer = (state: StorageState, action: StorageAction) => {
switch (action.type) {
case 'themeMode':
return { ...state, themeMode: action.value }
case 'favoriteAdd': {
if (Array.isArray(state.favorites)) {
return {
...state,
favorites: [...state.favorites, action.value]
}
}

return { ...state, favorites: [action.value] }
}
case 'favoriteRemove': {
if (Array.isArray(state.favorites)) {
const { value } = action
const { route, direction, stop } = value
const toRemove = `${route.id}${direction.id}${stop.id}`

return {
...state,
favorites: state.favorites.filter(fav => {
const thisFav = `${fav.route.id}${fav.direction.id}${fav.stop.id}`

return toRemove !== thisFav
})
}
}

return state
}
case 'predsFormat':
return { ...state, predsFormat: action.value }
case 'vehicleSpeedUnit':
Expand All @@ -52,7 +97,8 @@ const KEYS = {
themeMode: 'busmap-themeMode',
vehicleSpeedUnit: 'busmap-vehicleSpeedUnit',
vehicleColorPredicted: 'busmap-vehicleColorPredicted',
predsFormat: 'busmap-predsFormat'
predsFormat: 'busmap-predsFormat',
favorites: 'busmap-favorites'
}
const StorageDispatch = createContext<Dispatch<StorageAction>>(() => {})
const Storage = createContext<StorageState>({})
Expand All @@ -62,6 +108,7 @@ const init = (): StorageState => {
const vehicleSpeedUnit = localStorage.getItem(KEYS.vehicleSpeedUnit)
const vehicleColorPredicted = localStorage.getItem(KEYS.vehicleColorPredicted)
const predsFormat = localStorage.getItem(KEYS.predsFormat)
const favoritesJson = localStorage.getItem(KEYS.favorites)

if (isAMode(themeMode)) {
state.themeMode = themeMode
Expand All @@ -79,12 +126,34 @@ const init = (): StorageState => {
state.vehicleColorPredicted = vehicleColorPredicted !== 'false'
}

if (favoritesJson) {
let favorites: Favorite[] | null = null

try {
favorites = JSON.parse(favoritesJson) as Favorite[]
} catch (err) {
// Ignore
}

if (favorites) {
state.favorites = favorites
}
}

return state
}
const StorageProvider: FC<{ children: ReactNode }> = ({ children }) => {
const [storage, dispatch] = useReducer(reducer, {}, init)
const context = useMemo(() => storage, [storage])

useEffect(() => {
if (storage.favorites) {
localStorage.setItem(KEYS.favorites, JSON.stringify(storage.favorites))
} else {
localStorage.removeItem(KEYS.favorites)
}
}, [storage.favorites])

useEffect(() => {
if (storage.themeMode) {
localStorage.setItem(KEYS.themeMode, storage.themeMode)
Expand Down Expand Up @@ -134,3 +203,4 @@ const useStorageDispatch = () => {
}

export { StorageProvider, useStorage, useStorageDispatch }
export type { Favorite }
5 changes: 5 additions & 0 deletions packages/ui/src/home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { useTheme } from './contexts/settings/theme.js'
import { BusSelector } from './components/busSelector.js'
import { Loading } from './components/loading.js'
import { Settings } from './components/settings/index.js'
import { Favorites } from './components/favorites.js'
import { Info } from './components/info.js'
import { Predictions } from './components/predictions.js'
import { Anchor } from './components/anchor.js'
Expand Down Expand Up @@ -143,6 +144,7 @@ const Home: FC<HomeProps> = () => {
<Tab name="select" label="🚌" />
<Tab name="info" label="ℹ️" />
<Tab name="settings" label="⚙️" />
<Tab name="favorites" label="⭐" />
<Tab name="profile" label="👤" />
<Tab name="login" label="Sign In" />
</TabList>
Expand All @@ -155,6 +157,9 @@ const Home: FC<HomeProps> = () => {
<TabPanel name="settings">
<Settings />
</TabPanel>
<TabPanel name="favorites">
<Favorites />
</TabPanel>
<TabPanel name="profile">
<p>Profile</p>
</TabPanel>
Expand Down
Empty file.
1 change: 1 addition & 0 deletions packages/ui/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ export type {
Agency,
Stop,
Direction,
DirectionName,
RouteName,
Route,
Pred,
Expand Down
17 changes: 17 additions & 0 deletions packages/ui/src/workers/favorites.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import type { Favorite } from '../contexts/storage.js'

interface FavoriteMessage {
action: 'start' | 'stop' | 'close'
favorite?: Favorite
}

addEventListener('message', (evt: MessageEvent<FavoriteMessage>) => {
postMessage(`thanks for sending ${evt.data}`)

if (evt.data.action === 'close') {
postMessage(`Closing worker ${self.name}`)
self.close()
}
})

export type { FavoriteMessage }