feat: implement Tabs component

This commit is contained in:
Hossein Mehrabi 2023-02-13 21:34:20 +03:30
parent 36df81df77
commit c55c38a275
26 changed files with 788 additions and 51 deletions

View File

@ -2,11 +2,13 @@ import { Global, SerializedStyles } from '@emotion/react'
import React, { useMemo } from 'react'
import { ButtonStyles } from '../Button/Button.styles'
import { LsdIconStyles } from '../Icons/LsdIcon/LsdIcon.styles'
import { TabItemStyles } from '../TabItem/TabItem.styles'
import { TabsStyles } from '../Tabs/Tabs.styles'
import { defaultThemes, Theme, withTheme } from '../Theme'
import { TypographyStyles } from '../Typography/Typography.styles'
const componentStyles: Array<ReturnType<typeof withTheme> | SerializedStyles> =
[ButtonStyles, TypographyStyles, LsdIconStyles]
[ButtonStyles, TypographyStyles, LsdIconStyles, TabItemStyles, TabsStyles]
export const CSSBaseline: React.FC<{ theme?: Theme }> = ({
theme = defaultThemes.light,

View File

@ -1,17 +1,22 @@
import { LsdIcon } from '../LsdIcon'
export const FolderIcon = LsdIcon((props) => (
<svg
width="14"
height="14"
viewBox="0 0 14 14"
fill="none"
xmlns="http://www.w3.org/2000/svg"
{...props}
>
<path
d="M5.34925 3.50001L6.51591 4.66668H11.6667V10.5H2.33341V3.50001H5.34925ZM5.83341 2.33334H2.33341C1.69175 2.33334 1.17258 2.85834 1.17258 3.50001L1.16675 10.5C1.16675 11.1417 1.69175 11.6667 2.33341 11.6667H11.6667C12.3084 11.6667 12.8334 11.1417 12.8334 10.5V4.66668C12.8334 4.02501 12.3084 3.50001 11.6667 3.50001H7.00008L5.83341 2.33334Z"
fill="black"
/>
</svg>
))
export const FolderIcon = LsdIcon(
(props) => (
<svg
width="14"
height="14"
viewBox="0 0 14 14"
fill="none"
xmlns="http://www.w3.org/2000/svg"
{...props}
>
<path
d="M5.34925 3.50001L6.51591 4.66668H11.6667V10.5H2.33341V3.50001H5.34925ZM5.83341 2.33334H2.33341C1.69175 2.33334 1.17258 2.85834 1.17258 3.50001L1.16675 10.5C1.16675 11.1417 1.69175 11.6667 2.33341 11.6667H11.6667C12.3084 11.6667 12.8334 11.1417 12.8334 10.5V4.66668C12.8334 4.02501 12.3084 3.50001 11.6667 3.50001H7.00008L5.83341 2.33334Z"
fill="black"
/>
</svg>
),
{
filled: true,
},
)

View File

@ -1,17 +1,22 @@
import { LsdIcon } from '../LsdIcon'
export const NavigateBeforeIcon = LsdIcon((props) => (
<svg
width="14"
height="14"
viewBox="0 0 14 14"
fill="none"
xmlns="http://www.w3.org/2000/svg"
{...props}
>
<path
d="M9.16137 4.3225L8.33887 3.5L4.83887 7L8.33887 10.5L9.16137 9.6775L6.4897 7L9.16137 4.3225Z"
fill="black"
/>
</svg>
))
export const NavigateBeforeIcon = LsdIcon(
(props) => (
<svg
width="14"
height="14"
viewBox="0 0 14 14"
fill="none"
xmlns="http://www.w3.org/2000/svg"
{...props}
>
<path
d="M9.16137 4.3225L8.33887 3.5L4.83887 7L8.33887 10.5L9.16137 9.6775L6.4897 7L9.16137 4.3225Z"
fill="black"
/>
</svg>
),
{
filled: true,
},
)

View File

@ -1,17 +1,22 @@
import { LsdIcon } from '../LsdIcon'
export const NavigateNextIcon = LsdIcon((props) => (
<svg
width="14"
height="14"
viewBox="0 0 14 14"
fill="none"
xmlns="http://www.w3.org/2000/svg"
{...props}
>
<path
d="M5.66137 3.5L4.83887 4.3225L7.51053 7L4.83887 9.6775L5.66137 10.5L9.16137 7L5.66137 3.5Z"
fill="black"
/>
</svg>
))
export const NavigateNextIcon = LsdIcon(
(props) => (
<svg
width="14"
height="14"
viewBox="0 0 14 14"
fill="none"
xmlns="http://www.w3.org/2000/svg"
{...props}
>
<path
d="M5.66137 3.5L4.83887 4.3225L7.51053 7L4.83887 9.6775L5.66137 10.5L9.16137 7L5.66137 3.5Z"
fill="black"
/>
</svg>
),
{
filled: true,
},
)

View File

@ -0,0 +1,32 @@
import { createContext, MutableRefObject, useContext, useMemo } from 'react'
export interface IResizeObserverContext {
observe: (id: string, ref: MutableRefObject<Element>) => void
unobserve: (id: string) => void
ready?: boolean
rect: Record<string, DOMRect>
}
export const ResizeObserverContext = createContext<IResizeObserverContext>(
null as any,
)
export const useResizeObserverAPI = () => {
const { observe, unobserve, ready } = useContext(ResizeObserverContext) ?? {}
return useMemo(
() => ({
observe,
unobserve,
ready,
}),
[observe, unobserve, ready],
)
}
export const useDOMRect = (id: string, defaultValue?: any) => {
const ctx = useContext(ResizeObserverContext)
return ctx?.rect?.[id] ?? defaultValue
}

View File

@ -0,0 +1,83 @@
import { omit } from 'lodash'
import React, { MutableRefObject, useEffect, useRef, useState } from 'react'
import { settleSync } from '../../utils/promise.utils'
import { ResizeObserverContext } from './ResizeObserverContext'
export const ResizeObserverProvider: React.FC<React.PropsWithChildren<{}>> = ({
children,
}) => {
const ro = useRef<ResizeObserver>()
const elements = useRef<Record<string, MutableRefObject<Element>>>({})
const [rects, setRects] = useState<Record<string, DOMRect>>({})
const [ready, setReady] = useState(false)
const onChange = (id: string) => {
const el = elements.current[id]
if (!el || !el.current) return
settleSync(() => {
setRects((val) => ({
...val,
[id]: el.current.getBoundingClientRect(),
}))
})
}
useEffect(() => {
if (typeof window === 'undefined' || typeof ResizeObserver === 'undefined')
return
ro.current = new ResizeObserver((entries) => {
settleSync(() => {
const arr = Object.entries(elements.current)
entries
.map((entry) => arr.find(([id, ref]) => ref.current === entry.target))
.forEach((map) => {
if (map && map.length === 2) {
const [id] = map
onChange(id)
}
})
})
})
setReady(true)
return () => {
ro.current?.disconnect()
}
}, [])
const observe = (id: string, elementRef: MutableRefObject<Element>) => {
if (!ro.current) return
elements.current[id] = elementRef
onChange(id)
elementRef.current instanceof Element &&
ro.current.observe(elementRef.current)
}
const unobserve = (id: string) => {
if (!ro.current) return
const el = elements.current[id]
if (!el) return
el.current instanceof Element && ro.current.unobserve(el.current)
delete elements.current[id]
setRects((val) => omit(val, id))
}
return (
<ResizeObserverContext.Provider
value={{
observe,
unobserve,
rect: rects,
ready,
}}
>
{children}
</ResizeObserverContext.Provider>
)
}

View File

@ -0,0 +1 @@
export { ResizeObserverProvider } from './ResizeObserverProvider'

View File

@ -0,0 +1,11 @@
export const tabItemClasses = {
root: `lsd-tab-item`,
text: `lsd-tab-item--text`,
icon: `lsd-tab-item--icon`,
disabled: 'lsd-tab-item--disabled',
selected: 'lsd-tab-item--selected',
small: 'lsd-tab-item--small',
medium: 'lsd-tab-item--medium',
large: 'lsd-tab-item--large',
}

View File

@ -0,0 +1,43 @@
import { Meta, Story } from '@storybook/react'
import { useStorybookIconComponent } from '../../utils/storybook.utils'
import { TabItem, TabItemProps } from './TabItem'
export default {
title: 'TabItem',
component: TabItem,
argTypes: {
size: {
type: {
name: 'enum',
value: ['small', 'medium', 'large'],
},
defaultValue: 'large',
},
icon: {
type: {
name: 'enum',
value: useStorybookIconComponent.options,
},
defaultValue: 'FolderIcon',
},
},
} as Meta
export const Root: Story<TabItemProps & { icon: string }> = ({
icon,
...args
}) => {
const Icon = useStorybookIconComponent(icon)
return (
<TabItem {...args} icon={Icon && <Icon color="primary" />}>
Tab
</TabItem>
)
}
Root.args = {
disabled: false,
selected: false,
size: 'large',
}

View File

@ -0,0 +1,70 @@
import { css } from '@emotion/react'
import { tabItemClasses } from './TabItem.classes'
export const TabItemStyles = css`
.${tabItemClasses.root} {
background: rgb(var(--lsd-surface-primary));
border: 1px solid transparent;
cursor: pointer;
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
&:hover {
text-decoration: underline;
}
}
.${tabItemClasses.text} {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.${tabItemClasses.icon} {
margin-left: 14px;
}
.${tabItemClasses.selected} {
border: 1px solid rgb(var(--lsd-border-primary));
&:hover {
text-decoration: none;
}
}
.${tabItemClasses.disabled} {
cursor: default;
opacity: 0.34;
&:hover {
text-decoration: none;
}
}
.${tabItemClasses.small} {
padding: 6px 12px;
.${tabItemClasses.icon} {
margin-left: 10px;
}
}
.${tabItemClasses.medium} {
padding: 6px 14px;
.${tabItemClasses.icon} {
margin-left: 12px;
}
}
.${tabItemClasses.large} {
padding: 10px 18px;
.${tabItemClasses.icon} {
margin-left: 14px;
}
}
`

View File

@ -0,0 +1,61 @@
import clsx from 'clsx'
import React from 'react'
import { useTabsContext } from '../Tabs/Tab.context'
import { Typography } from '../Typography'
import { tabItemClasses } from './TabItem.classes'
export type TabItemProps = React.ButtonHTMLAttributes<HTMLButtonElement> & {
name: string
selected?: boolean
inactive?: boolean
icon?: React.ReactNode
size?: 'small' | 'medium' | 'large'
}
export const TabItem: React.FC<TabItemProps> & {
classes: typeof tabItemClasses
} = ({
name,
size: _size = 'large',
selected: _selected = false,
inactive = false,
icon,
children,
...props
}) => {
const tabs = useTabsContext()
const size = tabs?.size ?? _size
const selected = tabs ? tabs.activeTab === name : _selected
const onClick: React.MouseEventHandler<HTMLButtonElement> = (event) => {
props.onClick && props.onClick(event)
if (inactive) return
tabs?.setActiveTab && tabs.setActiveTab(name)
}
return (
<button
{...props}
className={clsx(
props.className,
tabItemClasses.root,
tabItemClasses[size],
selected && tabItemClasses.selected,
props.disabled && tabItemClasses.disabled,
)}
onClick={onClick}
>
<Typography
component="span"
className={tabItemClasses.text}
variant={size === 'small' ? 'label2' : 'label1'}
>
{children}
</Typography>
{icon && <span className={tabItemClasses.icon}>{icon}</span>}
</button>
)
}
TabItem.classes = tabItemClasses

View File

@ -0,0 +1 @@
export * from './TabItem'

View File

@ -0,0 +1,13 @@
import React from 'react'
import { TabsProps } from './Tabs'
export type TabContextType = {
activeTab?: string | null
setActiveTab: (name: string) => void
size?: TabsProps['size']
}
export const TabsContext = React.createContext<TabContextType>(null as any)
export const useTabsContext = () => React.useContext(TabsContext)

View File

@ -0,0 +1,7 @@
export const tabsClasses = {
root: `lsd-tabs`,
fullWidth: 'lsd-tabs--full-width',
withScrollControls: 'lsd-tabs--with-scroll-controls',
leftScrollControl: 'lsd-tabs__left-scroll-control',
rightScrollControl: 'lsd-tabs__right-scroll-control',
}

View File

@ -0,0 +1,63 @@
import { Meta, Story } from '@storybook/react'
import { useStorybookIconComponent } from '../../utils/storybook.utils'
import { TabItem } from '../TabItem'
import { Tabs, TabsProps } from './Tabs'
export default {
title: 'Tabs',
component: Tabs,
argTypes: {
size: {
type: {
name: 'enum',
value: ['small', 'medium', 'large'],
},
defaultValue: 'large',
},
icon: {
type: {
name: 'enum',
value: useStorybookIconComponent.options,
},
defaultValue: 'FolderIcon',
},
tabs: {
type: {
name: 'number',
},
defaultValue: 4,
},
},
} as Meta
export const Root: Story<
TabsProps & {
icon: string
tabs: number
}
> = ({ icon, tabs, ...args }) => {
const IconComponent = useStorybookIconComponent(icon)
return (
<div style={{ width: '100%' }}>
<Tabs {...args} activeTab="Tab 1">
{new Array(Math.max(1, tabs)).fill(null).map((tab, index) => (
<TabItem
key={index}
name={`Tab ${index + 1}`}
icon={
IconComponent && <IconComponent color="primary"></IconComponent>
}
>
{`Tab ${index + 1}`}
</TabItem>
))}
</Tabs>
</div>
)
}
Root.args = {
fullWidth: false,
scrollControls: true,
}

View File

@ -0,0 +1,47 @@
import { css } from '@emotion/react'
import { tabsClasses } from './Tabs.classes'
export const TabsStyles = css`
.${tabsClasses.root} {
display: flex;
flex-direction: row;
overflow: auto;
& > * {
flex-shrink: 0;
}
}
.${tabsClasses.fullWidth} {
width: 100%;
justify-content: stretch;
& > * {
width: 100%;
flex: 1 0;
}
}
.${tabsClasses.root} {
&::-webkit-scrollbar {
display: none;
}
-ms-overflow-style: none;
scrollbar-width: none;
}
.${tabsClasses.leftScrollControl} {
left: 0;
}
.${tabsClasses.rightScrollControl} {
right: 0;
}
.${tabsClasses.rightScrollControl}, .${tabsClasses.leftScrollControl} {
top: 0;
flex: 0 1;
position: sticky;
}
`

View File

@ -0,0 +1,87 @@
import clsx from 'clsx'
import React, { useEffect, useRef, useState } from 'react'
import { useHorizontalScroll } from '../../utils/useHorizontalScroll'
import { NavigateBeforeIcon, NavigateNextIcon } from '../Icons'
import { TabItem } from '../TabItem'
import { TabsContext } from './Tab.context'
import { tabsClasses } from './Tabs.classes'
export type TabsProps = Omit<
React.HTMLAttributes<HTMLDivElement>,
'onChange'
> & {
activeTab?: string | null
fullWidth?: boolean
onChange?: (activeTab: string) => void
size?: 'small' | 'medium' | 'large'
scrollControls?: boolean
}
export const Tabs: React.FC<TabsProps> & {
classes: typeof tabsClasses
} = ({
size = 'large',
fullWidth = false,
scrollControls = false,
onChange,
activeTab,
children,
...props
}) => {
const ref = useRef<HTMLDivElement>(null)
const [value, setValue] = useState(activeTab)
const setActiveTab = (tab: string) => {
if (onChange) onChange(tab)
else setValue(tab)
}
useEffect(() => setValue(activeTab), [activeTab])
const scroll = useHorizontalScroll(
ref as React.MutableRefObject<HTMLElement>,
{ scrollBehavior: 'smooth', deps: [children] },
)
const canScroll = scroll.left !== 0 || scroll.right !== 0
return (
<TabsContext.Provider value={{ activeTab: value, setActiveTab, size }}>
<div
ref={ref}
{...props}
className={clsx(
props.className,
tabsClasses.root,
fullWidth && tabsClasses.fullWidth,
scrollControls && canScroll && tabsClasses.withScrollControls,
)}
>
{scrollControls && canScroll && (
<TabItem
inactive
name="Prev"
disabled={scroll.left === 0}
onClick={() => scroll.toLeft()}
className={tabsClasses.leftScrollControl}
>
<NavigateBeforeIcon color="primary" />
</TabItem>
)}
{children}
{scrollControls && canScroll && (
<TabItem
inactive
name="Next"
disabled={scroll.right === 0}
onClick={() => scroll.toRight()}
className={tabsClasses.rightScrollControl}
>
<NavigateNextIcon color="primary" />
</TabItem>
)}
</div>
</TabsContext.Provider>
)
}
Tabs.classes = tabsClasses

View File

@ -0,0 +1 @@
export * from './Tabs'

View File

@ -1,6 +1,7 @@
import { Global, ThemeProvider as EmotionThemeProvider } from '@emotion/react'
import React from 'react'
import { CSSBaseline } from '../CSSBaseline'
import { ResizeObserverProvider } from '../ResizeObserver'
import { Theme } from './types'
export type ThemeProviderProps = React.PropsWithChildren<{
@ -12,11 +13,13 @@ export const ThemeProvider: React.FC<ThemeProviderProps> = ({
children,
}) => {
return (
<ThemeContext.Provider value={{ theme }}>
<EmotionThemeProvider theme={theme}>{children}</EmotionThemeProvider>
<CSSBaseline theme={theme} />
<Global styles={theme.globalStyles} />
</ThemeContext.Provider>
<ResizeObserverProvider>
<ThemeContext.Provider value={{ theme }}>
<EmotionThemeProvider theme={theme}>{children}</EmotionThemeProvider>
<CSSBaseline theme={theme} />
<Global styles={theme.globalStyles} />
</ThemeContext.Provider>
</ResizeObserverProvider>
)
}

View File

@ -1,3 +1,5 @@
export * from './components/Button'
export * from './components/Icons'
export * from './components/TabItem'
export * from './components/Tabs'
export * from './components/Theme'

View File

@ -0,0 +1,9 @@
export const createCounter = (start = 0) => {
let i = start - 1
return () => {
i++
return i
}
}

View File

@ -0,0 +1,21 @@
export const settle = async <R, E = Error>(
promise: Promise<R> | (() => Promise<R>),
): Promise<[R, undefined] | [undefined, E]> => {
try {
const result: R =
typeof promise === 'function' ? await promise() : await promise
return [result, undefined]
} catch (error) {
return [undefined, error as E]
}
}
export const settleSync = <R, E = Error>(
func: () => R,
): [R, undefined] | [undefined, E] => {
try {
return [func(), undefined]
} catch (error) {
return [undefined, error as E]
}
}

View File

@ -0,0 +1,12 @@
import React from 'react'
import * as Icons from '../components/Icons'
import { LsdIconProps } from '../components/Icons'
export const useStorybookIconComponent = (name: string) => {
const Component = (Icons as any)[name]
if (!Component) return undefined
return Component as React.ComponentType<LsdIconProps>
}
useStorybookIconComponent.options = ['None', ...Object.keys(Icons)]

View File

@ -0,0 +1,28 @@
import { useEffect, useMemo } from 'react'
export const useEventListener = <
T = any,
E extends { addEventListener: any; removeEventListener: any } = any,
>(
key: string | (() => string),
element: E | (() => E),
listener: (event: T) => void,
options?: boolean | AddEventListenerOptions,
deps?: any[],
) => {
const _key = useMemo(() => (typeof key === 'string' ? key : key()), [])
const _element = useMemo(
() => (typeof element === 'function' ? element() : element),
[element],
)
useEffect(() => {
if (!_element?.addEventListener || !_element?.removeEventListener) return
_element.addEventListener(_key, listener, options)
return () => {
_element.removeEventListener(_key, listener, options)
}
}, [_key, _element])
}

View File

@ -0,0 +1,88 @@
import React, { useEffect, useMemo, useRef, useState } from 'react'
import { useEventListener } from './useEventListener'
import { useResizeObserver } from './useResizeObserver'
export type UseHorizontalScrollReturnType = {
right: number
left: number
toRight: (width?: number) => void
toLeft: (width?: number) => void
}
const calcAvailableWidth = (
direction: number,
scrollLeft: number,
scrollWidth: number,
clientWidth: number,
) => (direction === -1 ? scrollLeft : scrollWidth - (clientWidth + scrollLeft))
export const useHorizontalScroll = (
ref: React.MutableRefObject<HTMLElement>,
options?: {
scrollBehavior?: ScrollBehavior
deps?: any[]
},
) => {
const rect = useResizeObserver(ref)
const [scroll, setScroll] = useState(ref?.current?.scrollLeft ?? 0)
const [leftAvailableWidth, setLeftAvailableWidth] = useState(0)
const [rightAvailableWidth, setRightAvailableWidth] = useState(0)
const timeoutRef = useRef(null)
useEventListener<MouseEvent>(
'scroll',
ref.current,
(event) => {
setScroll((event.target as HTMLDivElement).scrollLeft)
},
{ passive: true },
[],
)
const onChange = () => {
timeoutRef.current && clearTimeout(timeoutRef.current)
if (!ref.current) return
const { scrollLeft, scrollWidth, clientWidth } = ref.current
setRightAvailableWidth(
calcAvailableWidth(1, scrollLeft, scrollWidth, clientWidth),
)
setLeftAvailableWidth(
calcAvailableWidth(-1, scrollLeft, scrollWidth, clientWidth),
)
}
useEffect(onChange, [rect, scroll, options?.deps])
const toScroll = (direction: number, width?: number) => {
const { clientWidth, scrollLeft } = ref.current
const firstChildInViewport = Array.from(ref.current.childNodes).find(
(child) => (child as HTMLElement).getBoundingClientRect().x >= 0,
)
const w = Math.max(
width ?? clientWidth / 3,
firstChildInViewport
? (firstChildInViewport as HTMLElement).clientWidth
: 0,
)
ref.current.scrollTo({
behavior: options?.scrollBehavior ?? 'smooth',
left: scrollLeft + w * direction,
})
}
return useMemo<UseHorizontalScrollReturnType>(
() => ({
right: rightAvailableWidth,
left: leftAvailableWidth,
toRight: toScroll.bind(null, 1),
toLeft: toScroll.bind(null, -1),
}),
[rightAvailableWidth, leftAvailableWidth],
)
}

View File

@ -0,0 +1,37 @@
import { MutableRefObject, useEffect, useMemo } from 'react'
import {
useDOMRect,
useResizeObserverAPI,
} from '../components/ResizeObserver/ResizeObserverContext'
import { createCounter } from './counter.util'
const defaultValue =
typeof DOMRectReadOnly === 'undefined'
? null
: new DOMRectReadOnly(0, 0, 0, 0)
const genId = createCounter()
export const useResizeObserver = (
ref: MutableRefObject<any>,
refId?: string,
): DOMRect => {
const api = useResizeObserverAPI()
const id = useMemo(() => refId ?? genId().toString(), [refId])
const rect = useDOMRect(id) ?? defaultValue
useEffect(() => {
if (!api || !api.ready) return
if (ref.current) {
api.observe(id, ref)
}
return () => {
api.unobserve(id)
}
}, [api.ready, ref.current])
return rect
}