nitro-web 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client/index.ts CHANGED
@@ -12,6 +12,7 @@ export * from '../types'
12
12
  // Main app functions
13
13
  export { setupApp, updateJwt, middleware } from './app'
14
14
  export { createStore, exposedStoreData, preloadedStoreData, setStoreWrapper, getSignoutStore, getInitialStore } from './store'
15
+ export { useFetchDoc, useFetchCol, useFetchSharedCol, clearCache } from './use-fetch'
15
16
 
16
17
  // Component Pages
17
18
  export { Signin } from '../components/auth/signin'
@@ -27,16 +28,19 @@ export { Accordion } from '../components/partials/element/accordion'
27
28
  export { Avatar } from '../components/partials/element/avatar'
28
29
  export { Button, Spinner } from '../components/partials/element/button'
29
30
  export { Calendar, type CalendarProps } from '../components/partials/element/calendar'
31
+ export { ContentWrapper, ErrorBanner, LoadingBanner } from '../components/partials/element/content-wrapper'
30
32
  export { Dropdown, type DropdownProps, type DropdownOption } from '../components/partials/element/dropdown'
31
33
  export { Filters, type FilterType, usePushChangesToPath } from '../components/partials/element/filters'
34
+ export { FormModal, ConfirmModal } from '../components/partials/element/form-modal'
32
35
  export { GithubLink } from '../components/partials/element/github-link'
33
36
  export { ImageDrop } from '../components/partials/element/image-drop'
34
37
  export { Initials, getColorByLetter } from '../components/partials/element/initials'
35
38
  export { Message, type MessageIcons } from '../components/partials/element/message'
36
39
  export { Modal } from '../components/partials/element/modal'
37
- export { Sidebar, type SidebarProps } from '../components/partials/element/sidebar'
40
+ export { Pagination, type PaginationProps } from '../components/partials/element/pagination'
41
+ export { Sidebar, getIsActive, type SidebarProps } from '../components/partials/element/sidebar'
38
42
  export { TimePicker, type TimePickerProps } from '../components/partials/element/timepicker'
39
- export { Tooltip } from '../components/partials/element/tooltip'
43
+ export { Tooltip, type TooltipProps } from '../components/partials/element/tooltip'
40
44
  export { Topbar } from '../components/partials/element/topbar'
41
45
  export { Table, type TableColumn, type TableProps, type TableRow, type TableRowType } from '../components/partials/element/table'
42
46
  export { LoadingWithDots, LoadingOverlay } from '../components/partials/element/loading'
@@ -0,0 +1,164 @@
1
+ // Generally we avoid using external hooks inline with FP principles, except in rare cases
2
+ import { useState, useEffect, Dispatch, SetStateAction } from 'react'
3
+ import { request, showError, getResponseErrors, setTimeoutPromise } from 'nitro-web/util'
4
+ import { Errors, SharedCollection } from 'nitro-web/types'
5
+ import { injectedConfig } from 'nitro-web'
6
+
7
+ // Cache duration in milliseconds (5 minutes)
8
+ const CACHE_DURATION = 5 * 60 * 1000
9
+ const delay = () => injectedConfig.env === 'development' ? 0 : 0 // read lazily to avoid circular dependency
10
+ const delaySharedCollection = () => injectedConfig.env === 'development' ? 0 : 0 // read lazily to avoid circular dependency
11
+
12
+ // Typed from the project's useTracked global, i.e. the project's Store
13
+ type Store = ReturnType<typeof useTracked>[0]
14
+ type SharedCollections = NonNullable<Store['sharedCollections']>
15
+ type Col = SharedCollection<{ _id?: string }>
16
+ const emptyCol: Col = { rows: [], total: 0 }
17
+ type GetSharedCollectionFn = (prev: Col) => Col
18
+
19
+ type CollectionReturn<T> = {
20
+ rows: T[],
21
+ total: number,
22
+ errors?: Errors,
23
+ isLoading: boolean,
24
+ refetch: () => void,
25
+ setRows: React.Dispatch<React.SetStateAction<T[]>>
26
+ }
27
+ type DocumentReturn<T> = {
28
+ data?: T,
29
+ errors?: Errors,
30
+ isLoading: boolean,
31
+ refetch: () => void,
32
+ setData: React.Dispatch<React.SetStateAction<T>>
33
+ }
34
+
35
+ /** Fetches a document */
36
+ export function useFetchDoc<T>(endpoint?: string, queryString?: string) {
37
+ return useFetchResource<T>(endpoint, queryString || '', true) as DocumentReturn<T>
38
+ }
39
+
40
+ /** Fetches a collection */
41
+ export function useFetchCol<T>(endpoint?: string, queryString?: string) {
42
+ return useFetchResource<T>(endpoint, queryString) as CollectionReturn<T>
43
+ }
44
+
45
+ /** Fetches a shared collection (e.g. options), which is cached on the store */
46
+ export function useFetchSharedCol<K extends keyof SharedCollections>(endpoint: string | undefined, collectionKey: K) {
47
+ const [{ sharedCollections }, setStore] = useTracked()
48
+ const { rows: rows2, total, errors, isLoading, lastFetched = 0 } = (sharedCollections?.[collectionKey] ?? emptyCol) as Col
49
+ const [refreshCount, setRefreshCount] = useState(0)
50
+
51
+ useEffect(() => {
52
+ let mounted = true
53
+
54
+ ;(async function () {
55
+ try {
56
+ const cacheFresh = Date.now() - lastFetched < CACHE_DURATION
57
+ if (!endpoint || isLoading || (refreshCount === 0 && cacheFresh)) return
58
+ setResource((prev) => ({ ...prev, isLoading: true, errors: [] }))
59
+ const { rows, total } = await request(`get /api${endpoint}`)
60
+ if (delaySharedCollection()) await setTimeoutPromise(() => {}, delaySharedCollection())
61
+ if (!mounted) return
62
+ setResource((prev) => ({ ...prev, rows: rows, total: total, isLoading: false, lastFetched: Date.now(), errors: [] }))
63
+ } catch (error) {
64
+ if (!mounted) return
65
+ showError(setStore, error)
66
+ setResource((prev) => ({ ...prev, isLoading: false, lastFetched: Date.now(), errors: getResponseErrors(error) }))
67
+ }
68
+ })()
69
+
70
+ return () => {
71
+ mounted = false
72
+ }
73
+ }, [refreshCount, collectionKey, endpoint])
74
+
75
+ function refetch() {
76
+ setRefreshCount(prev => prev + 1)
77
+ }
78
+
79
+ function setResource(getSharedCollectionFn: GetSharedCollectionFn) {
80
+ setStore((prev) => ({
81
+ ...prev,
82
+ sharedCollections: {
83
+ ...prev.sharedCollections,
84
+ [collectionKey]: getSharedCollectionFn((prev.sharedCollections?.[collectionKey] ?? emptyCol) as Col),
85
+ },
86
+ }))
87
+ }
88
+
89
+ const rows = rows2 as SharedCollections[K]['rows']
90
+ return { rows, total, errors, isLoading, refetch }
91
+ }
92
+
93
+ /** Base hook to fetch a collection or document (does not persist the data in the data-store) */
94
+ function useFetchResource<T>(endpoint?: string, queryString?: string, isDocument?: boolean) {
95
+ const [, setStore] = useTracked()
96
+ const [rows, setRows] = useState<T[]>([])
97
+ const [data, setData] = useState<T | undefined>()
98
+ const [total, setTotal] = useState(0)
99
+ const [errors, setErrors] = useState<Errors>([])
100
+ const [isLoading, setIsLoading] = useState(!!endpoint)
101
+ const [refreshCount, setRefreshCount] = useState(0)
102
+
103
+ useEffect(() => {
104
+ let mounted = true
105
+
106
+ ;(async function () {
107
+ try {
108
+ if (!endpoint) return
109
+ setIsLoading(true)
110
+ const response = await request(`get /api${endpoint}${queryString}`)
111
+ if (delay()) await setTimeoutPromise(() => {}, delay())
112
+ if (mounted) {
113
+ if (isDocument) {
114
+ setData(response || undefined)
115
+ } else {
116
+ setRows(response.rows || [])
117
+ setTotal(response.total || 0)
118
+ }
119
+ setErrors([])
120
+ setIsLoading(false)
121
+ }
122
+ } catch (error) {
123
+ if (mounted) {
124
+ showError(setStore, error)
125
+ setErrors(getResponseErrors(error))
126
+ setIsLoading(false)
127
+ }
128
+ }
129
+ })()
130
+
131
+ return () => {
132
+ mounted = false
133
+ }
134
+ }, [refreshCount, endpoint, queryString])
135
+
136
+ function refetch() {
137
+ setRefreshCount(prev => prev + 1)
138
+ }
139
+
140
+ return isDocument === true ? { data, errors, isLoading, refetch, setData } : { rows, total, errors, isLoading, refetch, setRows }
141
+ }
142
+
143
+ /** Clears a shared collection's cache (without refetching). Optionally appends an item immediately. */
144
+ export function clearCache<K extends keyof SharedCollections>(
145
+ setStore: Dispatch<SetStateAction<Store>>,
146
+ collectionKey: K,
147
+ append?: SharedCollections[K]['rows'][number]
148
+ ) {
149
+ setStore((prev) => {
150
+ const col = (prev.sharedCollections?.[collectionKey] ?? emptyCol) as Col
151
+ const id = (append as Col['rows'][number] | undefined)?._id
152
+ return {
153
+ ...prev,
154
+ sharedCollections: {
155
+ ...prev.sharedCollections,
156
+ [collectionKey]: {
157
+ ...col,
158
+ rows: append && !col.rows.some((r) => r._id === id) ? [...col.rows, append as Col['rows'][number]] : col.rows,
159
+ lastFetched: 0,
160
+ },
161
+ },
162
+ }
163
+ })
164
+ }
@@ -433,10 +433,19 @@ export async function userSigninGetStore(user, isDesktop) {
433
433
  export async function getStore(user, _req) {
434
434
  // Initial store (req only passed from the /store route, not after signin)
435
435
  return {
436
- user: user || undefined,
436
+ user: user ? { ...user, companyRole: getCompanyRole(user) } : undefined,
437
437
  }
438
438
  }
439
439
 
440
+ /**
441
+ * The user's role in their active company (expects user.company to be populated)
442
+ * @param {object} user
443
+ * @returns {string|undefined}
444
+ */
445
+ export function getCompanyRole(user) {
446
+ return user?.company?.users?.find(u => String(u._id) === String(user._id))?.role
447
+ }
448
+
440
449
  /* ---- Helpers (not easily overridable) ----- */
441
450
 
442
451
  /**
@@ -0,0 +1,52 @@
1
+ import React from 'react'
2
+ import type { Errors } from 'nitro-web/types'
3
+ import { Spinner, twMerge } from 'nitro-web'
4
+
5
+ interface ContentWrapperProps<T = unknown> {
6
+ children: (data: T) => React.ReactNode
7
+ data?: T
8
+ isLoading?: boolean
9
+ errors?: Errors | null
10
+ loadingMessage?: string
11
+ errorTitle?: string
12
+ }
13
+
14
+ // Owns the loading and error states, so children only render once the data is there
15
+ export const ContentWrapper = <T,>({ children, data, isLoading, errors, loadingMessage, errorTitle }: ContentWrapperProps<T>) => {
16
+ return (
17
+ <React.Fragment>
18
+ {
19
+ isLoading
20
+ ? <LoadingBanner loadingMessage={loadingMessage} />
21
+ : (errors && errors.length > 0)
22
+ ? <ErrorBanner errors={errors} errorTitle={errorTitle} />
23
+ : (data ? children(data) : null)
24
+ }
25
+ </React.Fragment>
26
+ )
27
+ }
28
+
29
+ export function ErrorBanner({ errors, errorTitle='Something went wrong', className }: {
30
+ errors?: Errors | null,
31
+ errorTitle?: string,
32
+ className?: string,
33
+ }) {
34
+ if (!errors || errors.length === 0) return null
35
+ return (
36
+ <div className={twMerge('p-5 border bg-danger/[0.03] border-danger text-danger-foreground rounded', className)}>
37
+ <h3 className="mb-1 font-semibold">{errorTitle}</h3>
38
+ {errors.map((error, i) => (
39
+ <p key={i}>{error.detail}</p>
40
+ ))}
41
+ </div>
42
+ )
43
+ }
44
+
45
+ export function LoadingBanner({ loadingMessage='One moment...', className }: { loadingMessage?: string, className?: string }) {
46
+ return (
47
+ <div className={`p-8 flex flex-col items-center justify-center gap-4 ${className||''}`}>
48
+ <Spinner className="size-3.5" />
49
+ <p className="font-medium">{loadingMessage}</p>
50
+ </div>
51
+ )
52
+ }
@@ -0,0 +1,154 @@
1
+ import { Fragment, useRef, useState } from 'react'
2
+ import { twMerge } from 'nitro-web'
3
+ import { Modal } from './modal'
4
+ import { Button as BaseButton } from './button'
5
+
6
+ interface ModalProps {
7
+ elements?: { Button?: typeof BaseButton } // pass your project's extended Button
8
+ isOpen: boolean
9
+ onClose: () => void
10
+ title: string
11
+ subtitle?: React.ReactNode
12
+ children?: React.ReactNode
13
+ maxWidth?: string
14
+ className?: string
15
+ titleClassName?: string
16
+ subtitleClassName?: string
17
+ }
18
+
19
+ interface ConfirmModalProps extends ModalProps {
20
+ onSubmit: () => Promise<void> | void
21
+ confirmText?: string
22
+ }
23
+
24
+ interface FormModalProps extends ModalProps {
25
+ onSubmit?: () => Promise<void> | void
26
+ submitText?: string
27
+ submitIcon?: React.ReactNode
28
+ footerNote?: React.ReactNode
29
+ xClassName?: string
30
+ }
31
+
32
+ // Confirm dialog, prevents double submissions and picks a danger button for remove/delete titles
33
+ export function ConfirmModal({
34
+ isOpen,
35
+ onClose,
36
+ onSubmit,
37
+ title = 'Warning',
38
+ subtitle = 'Are you sure you want to proceed?',
39
+ confirmText = 'Confirm',
40
+ children,
41
+ elements,
42
+ className,
43
+ titleClassName,
44
+ subtitleClassName,
45
+ }: ConfirmModalProps) {
46
+ const [isLoading, setIsLoading] = useState(false)
47
+ const Button = elements?.Button || BaseButton
48
+
49
+ // Cache the values to prevent flickering when closing
50
+ const cached = useRef({ title, subtitle, confirmText, children })
51
+ if (isOpen) cached.current = { title, subtitle, confirmText, children }
52
+
53
+ async function handleSubmit() {
54
+ if (isLoading) return
55
+ setIsLoading(true)
56
+ try {
57
+ await onSubmit()
58
+ } finally {
59
+ setIsLoading(false)
60
+ }
61
+ }
62
+
63
+ return (
64
+ <Modal
65
+ show={isOpen}
66
+ setShow={onClose}
67
+ maxWidth="480px"
68
+ className={twMerge('p-9 pt-8 rounded-md flex flex-col items-center gap-4', className)}
69
+ >
70
+ <div className="text-center">
71
+ <h3 className={twMerge('h3 text-[18px] mb-2.5', titleClassName)}>{cached.current.title}</h3>
72
+ {cached.current.subtitle && <p className={twMerge('h5 text-gray-500 mb-0', subtitleClassName)}>{cached.current.subtitle}</p>}
73
+ </div>
74
+ {cached.current.children}
75
+ <div className="self-stretch flex mt-1.5">
76
+ <Button className="flex-1"
77
+ color={title.match(/remove|delete/i) ? 'danger' : 'primary'}
78
+ onClick={handleSubmit}
79
+ isLoading={isLoading}
80
+ >
81
+ {cached.current.confirmText}
82
+ </Button>
83
+ </div>
84
+ </Modal>
85
+ )
86
+ }
87
+
88
+ // Form dialog with a header, optional submit button and footer note, prevents double submissions
89
+ export function FormModal({
90
+ isOpen,
91
+ onClose,
92
+ title,
93
+ subtitle,
94
+ children,
95
+ onSubmit,
96
+ submitText = 'Submit',
97
+ submitIcon,
98
+ footerNote,
99
+ maxWidth = '560px',
100
+ elements,
101
+ className,
102
+ titleClassName,
103
+ subtitleClassName,
104
+ xClassName,
105
+ }: FormModalProps) {
106
+ const [isLoading, setIsLoading] = useState(false)
107
+ const Button = elements?.Button || BaseButton
108
+
109
+ // Cache the values to prevent flickering when closing
110
+ const cached = useRef({ title, subtitle, submitText, submitIcon, footerNote, children })
111
+ if (isOpen) cached.current = { title, subtitle, submitText, submitIcon, footerNote, children }
112
+
113
+ async function handleSubmit() {
114
+ if (isLoading || !onSubmit) return
115
+ setIsLoading(true)
116
+ try {
117
+ await onSubmit()
118
+ } finally {
119
+ setIsLoading(false)
120
+ }
121
+ }
122
+
123
+ return (
124
+ <Modal
125
+ show={isOpen}
126
+ setShow={onClose}
127
+ maxWidth={maxWidth}
128
+ className={twMerge('p-8 rounded-md flex flex-col gap-5', className)}
129
+ xClassName={twMerge('bg-[rgba(62,68,140,0.06)] hover:bg-[rgba(62,68,140,0.11)] rounded-md right-0 p-2.5 m-[11px]', xClassName)}
130
+ >
131
+ {(cached.current.title || cached.current.subtitle) && (
132
+ <Fragment>
133
+ <div className={twMerge('-m-8 mb-0 px-8 py-[18px] bg-[rgba(63,68,142,0.06)] rounded-t-md', titleClassName)}>
134
+ <h3 className="h3 text-[15.5px] mb-0 pb-0">{cached.current.title}</h3>
135
+ </div>
136
+ {cached.current.subtitle && (
137
+ <p className={twMerge('h5 text-gray-500 mb-0 text-left', subtitleClassName)}>{cached.current.subtitle}</p>
138
+ )}
139
+ </Fragment>
140
+ )}
141
+ {cached.current.children}
142
+ {onSubmit && (
143
+ <div className="self-stretch flex mt-1.5">
144
+ <Button className="flex-1" color="primary" onClick={handleSubmit} isLoading={isLoading} IconRight={cached.current.submitIcon}>
145
+ {cached.current.submitText}
146
+ </Button>
147
+ </div>
148
+ )}
149
+ {cached.current.footerNote && (
150
+ <div className="-mt-1 text-xs text-gray-500 flex items-center justify-center gap-1.5">{cached.current.footerNote}</div>
151
+ )}
152
+ </Modal>
153
+ )
154
+ }
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react'
2
2
  import { ImageIcon } from 'lucide-react'
3
3
  import { DropHandler } from 'nitro-web'
4
4
  import { deepFind, getErrorFromState, s3Image, twMerge } from 'nitro-web/util'
5
- import type { Errors, MonasteryImage } from 'nitro-web/types'
5
+ import type { Errors, MonasteryFile } from 'nitro-web/types'
6
6
 
7
7
  type ImageDropProps = {
8
8
  awsUrl?: string
@@ -20,7 +20,7 @@ type ImageDropProps = {
20
20
  inheritedNote?: string
21
21
  }
22
22
 
23
- type ImageValue = File | MonasteryImage | null
23
+ type ImageValue = File | MonasteryFile | null
24
24
 
25
25
  export function ImageDrop({ awsUrl, className, id, name, onChange, state, inheritedUrl, inheritedNote }: ImageDropProps) {
26
26
  // A friendlier Drop for images: the whole area is clickable, with an outlined image icon and a preview
@@ -0,0 +1,61 @@
1
+ import { useEffect, useMemo, useRef, useState } from 'react'
2
+ import { useNavigate, useLocation } from 'react-router-dom'
3
+ import { queryObject, queryString, twMerge } from 'nitro-web'
4
+ import { ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight } from 'lucide-react'
5
+ import { Button as BaseButton } from './button'
6
+
7
+ export type PaginationProps = {
8
+ total: number
9
+ perPage?: number
10
+ className?: string
11
+ elements?: { Button?: typeof BaseButton } // pass your project's extended Button
12
+ }
13
+
14
+ export function Pagination({ total, perPage=16, className, elements }: PaginationProps) {
15
+ // Page controls driven by the `?page=` query param
16
+ const Button = elements?.Button || BaseButton
17
+ const navigate = useNavigate()
18
+ const location = useLocation()
19
+ const query = useMemo(() => ({ ...queryObject(location.search) }), [location.search])
20
+ const [currentPage, setCurrentPage] = useState(parseInt(query.page as string || '1'))
21
+ const totalPages = useMemo(() => Math.ceil(total / perPage), [total, perPage])
22
+ const locationRef = useRef(location)
23
+
24
+ useEffect(() => {
25
+ setCurrentPage(parseInt(query.page as string || '1'))
26
+ }, [query.page])
27
+
28
+ useEffect(() => {
29
+ locationRef.current = location
30
+ }, [location])
31
+
32
+ const goToPage = (page: number) => {
33
+ const updatedQuery = { ...query, page: String(page) }
34
+ navigate(`${locationRef.current.pathname}${queryString(updatedQuery)}`)
35
+ }
36
+
37
+ return (
38
+ <div className={twMerge('flex items-center justify-center gap-7 text-xs font-medium', className)}>
39
+ <span>Page {currentPage} of {totalPages}</span>
40
+
41
+ <div className="flex items-center gap-[7px]">
42
+ {[
43
+ { Icon: ChevronsLeft, page: 1, disabled: currentPage === 1 },
44
+ { Icon: ChevronLeft, page: currentPage - 1, disabled: currentPage === 1 },
45
+ { Icon: ChevronRight, page: currentPage + 1, disabled: currentPage === totalPages },
46
+ { Icon: ChevronsRight, page: totalPages, disabled: currentPage === totalPages },
47
+ ].map(({ Icon, page, disabled }, i) => (
48
+ <Button
49
+ key={i}
50
+ onClick={() => goToPage(page)}
51
+ disabled={disabled}
52
+ color="white"
53
+ size="sm"
54
+ IconCenter={<Icon size={16} strokeWidth={2.2} />}
55
+ className={`h-[31px] ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
56
+ />
57
+ ))}
58
+ </div>
59
+ </div>
60
+ )
61
+ }
@@ -2,23 +2,19 @@
2
2
  import { css } from 'twin.macro'
3
3
  import avatarImg from 'nitro-web/client/imgs/avatar.jpg'
4
4
  import { injectedConfig } from 'nitro-web'
5
- import {
6
- Bars3Icon,
7
- HomeIcon,
8
- UsersIcon,
9
- ArrowLeftCircleIcon,
10
- PaintBrushIcon,
11
- } from '@heroicons/react/24/outline'
12
- import { XIcon } from 'lucide-react'
5
+ import React from 'react'
6
+ import { House, LogOut, Menu, Paintbrush, Users, XIcon } from 'lucide-react'
13
7
 
14
8
  const sidebarWidth = 'w-80'
15
9
 
16
10
  export type SidebarProps = {
17
11
  Logo?: React.FC<{ width?: string, height?: string }>;
18
- menu?: { name: string; to: string; Icon: React.FC<{ className?: string }> }[]
19
- links?: { name: string; to: string; initial: string }[]
12
+ menu?: { name: string; to: string; toMatcher?: ToMatcher; Icon: React.FC<{ className?: string }> }[]
13
+ links?: { name: string; to: string; toMatcher?: ToMatcher; initial: string }[]
20
14
  }
21
15
 
16
+ type ToMatcher = (pathname: string, search?: string) => boolean
17
+
22
18
  function classNames(...classes: string[]) {
23
19
  return classes.filter(Boolean).join(' ')
24
20
  }
@@ -26,7 +22,7 @@ function classNames(...classes: string[]) {
26
22
  export function Sidebar({ Logo, menu, links }: SidebarProps) {
27
23
  const [sidebarOpen, setSidebarOpen] = useState(false)
28
24
  return (
29
- <>
25
+ <React.Fragment>
30
26
  {/* desktop sidebar */}
31
27
  <div css={style} className={
32
28
  'fixed inset-y-0 z-50 flex flex-col ease-in-out lg:left-0 lg:translate-x-0 lg:!delay-0 lg:!duration-0 ' +
@@ -64,7 +60,7 @@ export function Sidebar({ Logo, menu, links }: SidebarProps) {
64
60
  {/* mobile sidebar topbar */}
65
61
  <div className="sticky top-0 z-40 flex items-center gap-x-6 bg-white px-4 py-4 shadow-sm sm:px-6 lg:hidden">
66
62
  <button type="button" onClick={() => setSidebarOpen(true)} className="-m-2.5 p-2.5 text-gray-700 lg:hidden">
67
- <Bars3Icon aria-hidden="true" className="size-6" />
63
+ <Menu aria-hidden="true" className="size-6" />
68
64
  </button>
69
65
  <div className="flex-1 text-sm/6 font-semibold text-gray-900">Dashboard</div>
70
66
  <Link to="#">
@@ -73,7 +69,7 @@ export function Sidebar({ Logo, menu, links }: SidebarProps) {
73
69
  </div>
74
70
 
75
71
  <div class={`${sidebarWidth}`} />
76
- </>
72
+ </React.Fragment>
77
73
  )
78
74
  }
79
75
 
@@ -82,17 +78,13 @@ function SidebarContents ({ Logo, menu, links }: SidebarProps) {
82
78
  const [store] = useTracked()
83
79
  const user = store.user
84
80
 
85
- function isActive(path: string) {
86
- if (path == '/' && location.pathname == path) return 'is-active'
87
- else if (path != '/' && location.pathname.match(`^${path}`)) return 'is-active'
88
- else return ''
89
- }
81
+ const isActive = (item: { to: string, toMatcher?: ToMatcher }) => getIsActive(location, item)
90
82
 
91
83
  const _menu = menu || [
92
- { name: 'Dashboard', to: '/', Icon: HomeIcon },
93
- { name: injectedConfig.isDemo ? 'Design System' : 'Style Guide', to: '/styleguide', Icon: PaintBrushIcon },
94
- { name: 'Pricing', to: '/pricing', Icon: UsersIcon },
95
- { name: 'Signout', to: '/signout', Icon: ArrowLeftCircleIcon },
84
+ { name: 'Dashboard', to: '/', Icon: House },
85
+ { name: injectedConfig.isDemo ? 'Design System' : 'Style Guide', to: '/styleguide', Icon: Paintbrush },
86
+ { name: 'Pricing', to: '/pricing', Icon: Users },
87
+ { name: 'Signout', to: '/signout', Icon: LogOut },
96
88
  ]
97
89
 
98
90
  const _links = links || [
@@ -103,7 +95,7 @@ function SidebarContents ({ Logo, menu, links }: SidebarProps) {
103
95
  return (
104
96
  <div className="flex grow flex-col gap-y-8 overflow-y-auto bg-white py-5 px-10 lg:border-r lg:border-gray-200">
105
97
  {Logo && (
106
- <div className="flex h-16 shrink-0 items-center gap-2 justify-bedtween">
98
+ <div className="flex h-16 shrink-0 items-center gap-2 justify-between">
107
99
  <Link to="/">
108
100
  <Logo width="70" height={undefined} />
109
101
  </Link>
@@ -119,7 +111,7 @@ function SidebarContents ({ Logo, menu, links }: SidebarProps) {
119
111
  <Link
120
112
  to={item.to}
121
113
  className={classNames(
122
- isActive(item.to)
114
+ isActive(item)
123
115
  ? 'bg-gray-50 text-indigo-600'
124
116
  : 'text-gray-700 hover:bg-gray-50 hover:text-indigo-600',
125
117
  'group flex gap-x-3 items-center rounded-md p-2 text-md/6 font-semibold'
@@ -128,7 +120,7 @@ function SidebarContents ({ Logo, menu, links }: SidebarProps) {
128
120
  { item.Icon &&
129
121
  <item.Icon
130
122
  className={classNames(
131
- isActive(item.to) ? 'text-indigo-600' : 'text-gray-400 group-hover:text-indigo-600',
123
+ isActive(item) ? 'text-indigo-600' : 'text-gray-400 group-hover:text-indigo-600',
132
124
  'size-5 shrink-0'
133
125
  )}
134
126
  />
@@ -147,7 +139,7 @@ function SidebarContents ({ Logo, menu, links }: SidebarProps) {
147
139
  <Link
148
140
  to={team.to}
149
141
  className={classNames(
150
- isActive(team.to)
142
+ isActive(team)
151
143
  ? 'bg-gray-50 text-indigo-600'
152
144
  : 'text-gray-700 hover:bg-gray-50 hover:text-indigo-600',
153
145
  'group flex gap-x-3 rounded-md p-2 text-md/6 font-semibold'
@@ -155,7 +147,7 @@ function SidebarContents ({ Logo, menu, links }: SidebarProps) {
155
147
  >
156
148
  <span
157
149
  className={classNames(
158
- isActive(team.to)
150
+ isActive(team)
159
151
  ? 'border-indigo-600 text-indigo-600'
160
152
  : 'border-gray-200 text-gray-400 group-hover:border-indigo-600 group-hover:text-indigo-600',
161
153
  'flex size-6 shrink-0 items-center justify-center rounded-lg border bg-white text-[0.625rem] font-medium'
@@ -193,3 +185,14 @@ const style = css`
193
185
  transition: transform 300ms, opacity 300ms, left 0ms 0ms;
194
186
  }
195
187
  `
188
+
189
+ // Active class for a menu/tab item, `toMatcher` overrides the default path prefix match
190
+ export function getIsActive(
191
+ location: { pathname: string, search: string },
192
+ item?: { toMatcher?: ToMatcher, to?: string } | null
193
+ ) {
194
+ if (item?.toMatcher) return item.toMatcher(location.pathname, location.search) ? 'is-active' : ''
195
+ else if (item?.to == '/' && location.pathname == item.to) return 'is-active'
196
+ else if (item?.to && item.to != '/' && location.pathname.match(`^${item.to}`)) return 'is-active'
197
+ else return ''
198
+ }