#679 day view without sidebar on mobile - look only

This commit is contained in:
lethemanh
2026-04-06 09:34:43 +07:00
parent fbb31e4a80
commit aa96a39b28
21 changed files with 664 additions and 117 deletions
@@ -0,0 +1,180 @@
import { CalendarApi } from '@fullcalendar/core'
import {
act,
render,
screen,
fireEvent,
waitFor,
RenderResult
} from '@testing-library/react'
import React from 'react'
import { DatePickerMobile } from '@/components/Menubar/components/DatePickerMobile'
jest.mock('twake-i18n', () => ({
useI18n: (): { t: (key: string) => string; lang: string } => ({
t: (key: string) => key,
lang: 'en'
})
}))
jest.mock('@linagora/twake-mui', () => {
const actual = jest.requireActual<typeof import('@linagora/twake-mui')>(
'@linagora/twake-mui'
)
return {
...actual,
useTheme: (): { palette: { grey: { 500: string } } } => ({
palette: { grey: { 500: '#9e9e9e' } }
})
}
})
const scrollIntoViewMock = jest.fn()
const originalScrollIntoView = window.HTMLElement.prototype.scrollIntoView
beforeAll(() => {
window.HTMLElement.prototype.scrollIntoView = scrollIntoViewMock
})
afterAll(() => {
window.HTMLElement.prototype.scrollIntoView = originalScrollIntoView
})
function makeCalendarApi(initialDate: Date): CalendarApi & {
getDate: jest.Mock
gotoDate: jest.Mock
} {
let _date = initialDate
const mockApi = {
getDate: jest.fn(() => _date),
gotoDate: jest.fn((d: Date) => {
_date = d
})
}
return mockApi as unknown as CalendarApi & typeof mockApi
}
describe('DatePickerMobile', () => {
beforeEach(() => {
jest.clearAllMocks()
scrollIntoViewMock.mockClear()
})
const setup = async (
initialDate: Date
): Promise<
RenderResult & { calendarApi: CalendarApi; onDateChange: jest.Mock }
> => {
const calendarApi = makeCalendarApi(initialDate)
const onDateChange = jest.fn()
const renderResult = await act(() =>
render(
<DatePickerMobile
calendarRef={{ current: calendarApi }}
currentDate={initialDate}
onDateChange={onDateChange}
/>
)
)
return { ...renderResult, calendarApi, onDateChange }
}
const expectNavigatedDate = (
calendarApi: CalendarApi,
expected: { day: number; month: number; year: number }
): void => {
// eslint-disable-next-line @typescript-eslint/unbound-method
const gotoDateMock = calendarApi.gotoDate as jest.Mock<void, [Date]>
const navigatedDate: Date = gotoDateMock.mock.calls[0][0]
expect(navigatedDate.getDate()).toBe(expected.day)
expect(navigatedDate.getMonth()).toBe(expected.month)
expect(navigatedDate.getFullYear()).toBe(expected.year)
}
const testMonthNavigation = async (
initialDate: Date,
monthToClick: number,
expected: { day: number; month: number; year: number }
): Promise<void> => {
const { calendarApi } = await setup(initialDate)
const monthButton = screen.getByText(`months.short.${monthToClick}`)
act(() => {
fireEvent.click(monthButton)
})
await waitFor(() => {
// eslint-disable-next-line @typescript-eslint/unbound-method
expect(calendarApi.gotoDate).toHaveBeenCalled()
})
expectNavigatedDate(calendarApi, expected)
}
it('calls calendarApi.gotoDate and onDateChange with the selected date', async () => {
const initialDate = new Date(2025, 5, 15) // June 15, 2025
const { calendarApi, onDateChange } = await setup(initialDate)
const day20 = screen.getByRole('gridcell', { name: '20' })
act(() => {
fireEvent.click(day20)
})
await waitFor(() => {
// eslint-disable-next-line @typescript-eslint/unbound-method
expect(calendarApi.gotoDate).toHaveBeenCalled()
})
expectNavigatedDate(calendarApi, { day: 20, month: 5, year: 2025 })
// eslint-disable-next-line @typescript-eslint/unbound-method
const gotoDateMock = calendarApi.gotoDate as jest.Mock<void, [Date]>
expect(onDateChange).toHaveBeenCalledWith(gotoDateMock.mock.calls[0][0])
})
it('navigates to the clicked month while keeping the current day', async () => {
await testMonthNavigation(
new Date(2025, 5, 15), // June 15, 2025
8,
{ day: 15, month: 8, year: 2025 }
)
})
it('clamps the day to the last valid day when switching to a shorter month', async () => {
await testMonthNavigation(
new Date(2025, 0, 31), // Jan 31, 2025
1,
{ day: 28, month: 1, year: 2025 }
)
})
it('scrollIntoView is called on the correct month button when currentDate changes to another month', async () => {
const initialDate = new Date(2025, 5, 15) // June 15, 2025 (month index 5)
const { rerender, calendarApi, onDateChange } = await setup(initialDate)
// Simulate parent updating currentDate to August (e.g. user picked a day in August)
const newDate = new Date(2025, 7, 5) // August 5, 2025 (month index 7)
act(() => {
rerender(
<DatePickerMobile
calendarRef={{ current: calendarApi }}
currentDate={newDate}
onDateChange={onDateChange}
/>
)
})
await waitFor(() => {
// scrollIntoView should have been called at least once (initial mount + rerender)
expect(scrollIntoViewMock).toHaveBeenCalledWith({
behavior: 'smooth',
block: 'nearest',
inline: 'center'
})
})
// The last call should correspond to August (index 7) button being highlighted
const augustButton = screen.getByText('months.short.7')
expect(augustButton).toBeInTheDocument()
})
})
+13 -23
View File
@@ -14,8 +14,6 @@ import { AVAILABLE_LANGUAGES } from './features/Settings/constants'
import { default as HandleLogin } from './features/User/HandleLogin'
import { CallbackResume } from './features/User/LoginCallback'
import { useInitializeApp } from './features/User/useInitializeApp'
import { ScreenTooSmall } from './ScreenTooSmall'
import { useScreenSizeDetection } from './useScreenSizeDetection'
import { WebSocketGate } from './websocket/WebSocketGate'
import {
@@ -65,8 +63,6 @@ function App(): JSX.Element {
useInitializeApp()
const { isTooSmall } = useScreenSizeDetection()
return (
<TwakeMuiThemeProvider>
<I18n
@@ -74,25 +70,19 @@ function App(): JSX.Element {
lang={lang}
locales={dateLocales}
>
{isTooSmall ? (
<ScreenTooSmall />
) : (
<>
<Suspense fallback={<Loading />}>
<WebSocketGate />
<Router history={history}>
<Routes>
<Route path="/" element={<HandleLogin />} />
<Route path="/calendar" element={<CalendarLayout />} />
<Route path="/callback" element={<CallbackResume />} />
<Route path="/error" element={<ErrorPage />} />
</Routes>
</Router>
<ErrorSnackbar error={error} type="user" />
</Suspense>
{appLoading && <Loading />}
</>
)}
<Suspense fallback={<Loading />}>
<WebSocketGate />
<Router history={history}>
<Routes>
<Route path="/" element={<HandleLogin />} />
<Route path="/calendar" element={<CalendarLayout />} />
<Route path="/callback" element={<CallbackResume />} />
<Route path="/error" element={<ErrorPage />} />
</Routes>
</Router>
<ErrorSnackbar error={error} type="user" />
</Suspense>
{appLoading && <Loading />}
</I18n>
</TwakeMuiThemeProvider>
)
+3
View File
@@ -87,6 +87,9 @@
align-items center
padding 0.5rem 0
font-family "Inter", sans-serif
gap 6px
&--mobile
flex-direction column-reverse !important
/* sidebar*/
.sidebar-calendar
+28 -14
View File
@@ -63,7 +63,7 @@ interface CalendarAppProps {
currentView: string
}
export default function CalendarApp({
const CalendarApp: React.FC<CalendarAppProps> = ({
calendarRef,
onDateChange,
onViewChange,
@@ -72,12 +72,12 @@ export default function CalendarApp({
onCloseSidebar,
setCurrentView,
currentView
}: CalendarAppProps): JSX.Element {
}: CalendarAppProps) => {
const [selectedDate, setSelectedDate] = useState(new Date())
const [debouncedDate, setDebouncedDate] = useState(new Date())
useEffect(() => {
const t = setTimeout(() => setDebouncedDate(selectedDate), 300)
return () => clearTimeout(t)
return (): void => clearTimeout(t)
}, [selectedDate])
const [selectedMiniDate, setSelectedMiniDate] = useState(new Date())
const userId = useAppSelector(state => state.user.userData?.openpaasId) ?? ''
@@ -93,7 +93,7 @@ export default function CalendarApp({
state => state.settings.hideDeclinedEvents
)
const { isTablet } = useScreenSizeDetection()
const { isTablet, isTooSmall: isMobile } = useScreenSizeDetection()
const hiddenDays = useMemo(() => {
if (!hideWorkingDays || !workingDays || workingDays.length === 0) return []
@@ -135,16 +135,16 @@ export default function CalendarApp({
useEffect(() => {
const handler = errorHandler.current
handler.setErrorCallback(setEventErrors)
return () => handler.setErrorCallback(() => {})
return (): void => handler.setErrorCallback(() => {})
}, [])
const handleErrorClose = () => {
const handleErrorClose = (): void => {
setEventErrors([])
errorHandler.current.clearAll()
}
useEffect(() => {
const updateSelectedCalendars = () => {
const updateSelectedCalendars = (): void => {
if (initialLoadRef.current && calendarIds.length > 0 && userId) {
const cached = localStorage.getItem('selectedCalendars')
if (cached && cached.length > 0) {
@@ -171,7 +171,7 @@ export default function CalendarApp({
}, [selectedCalendars, calendarIds.length])
useEffect(() => {
const updateSelectedCalendarsOnCalendarChange = () => {
const updateSelectedCalendarsOnCalendarChange = (): void => {
if (calendarIds.length === 0) return
const validCalendarIds = new Set(calendarIds)
setSelectedCalendars(prev => {
@@ -237,7 +237,13 @@ export default function CalendarApp({
// Listen for eventModalError event to reopen modal on API failure
useEffect(() => {
const handleEventModalError = (event: CustomEvent) => {
const handleEventModalError = (e: Event): void => {
const event = e as CustomEvent<{
type: 'create' | 'update'
eventId: string
calId: string
typeOfAction: string
}>
if (event.detail?.type === 'create') {
// Reopen create event modal
setAnchorEl(document.body)
@@ -286,7 +292,7 @@ export default function CalendarApp({
'eventModalError',
handleEventModalError as EventListener
)
return () => {
return (): void => {
window.removeEventListener(
'eventModalError',
handleEventModalError as EventListener
@@ -319,7 +325,7 @@ export default function CalendarApp({
calendarRef.current?.changeView(targetView)
}
})
return () => cancelAnimationFrame(id)
return (): void => cancelAnimationFrame(id)
}, [view, isTablet, currentView, calendarRef])
// Event handlers
const eventHandlers = useCalendarEventHandlers({
@@ -541,7 +547,9 @@ export default function CalendarApp({
.toUpperCase()
return (
<div className="fc-daygrid-day-top">
<div
className={`fc-daygrid-day-top ${isTablet || isMobile ? 'fc-daygrid-day-top--mobile' : ''}`}
>
<small>{weekDay}</small>
{arg.view.type !== CALENDAR_VIEWS.dayGridMonth && (
<span
@@ -559,8 +567,12 @@ export default function CalendarApp({
viewWillUnmount={viewHandlers.handleViewWillUnmount}
eventClick={eventHandlers.handleEventClick}
eventAllow={eventHandlers.handleEventAllow}
eventDrop={eventHandlers.handleEventDrop}
eventResize={eventHandlers.handleEventResize}
eventDrop={arg => {
void eventHandlers.handleEventDrop(arg)
}}
eventResize={arg => {
void eventHandlers.handleEventResize(arg)
}}
eventContent={viewHandlers.handleEventContent}
eventDidMount={viewHandlers.handleEventDidMount}
/>
@@ -599,3 +611,5 @@ export default function CalendarApp({
</main>
)
}
export default CalendarApp
+14 -19
View File
@@ -12,7 +12,7 @@ import CalendarApp from './Calendar'
import { CALENDAR_VIEWS } from './utils/constants'
import { setView } from '@/features/Settings/SettingsSlice'
export default function CalendarLayout() {
export default function CalendarLayout(): JSX.Element {
const calendarRef = useRef<CalendarApi | null>(null)
const dispatch = useAppDispatch()
const error = useAppSelector(state => state.calendars.error)
@@ -20,33 +20,28 @@ export default function CalendarLayout() {
const tempcalendars = useAppSelector(state => state.calendars.templist)
const view = useAppSelector(state => state.settings.view)
const { isTablet } = useScreenSizeDetection()
const { isTablet, isTooSmall: isMobile } = useScreenSizeDetection()
const [openSidebar, setOpenSideBar] = useState(false)
const [currentDate, setCurrentDate] = useState<Date>(new Date())
const [currentView, setCurrentView] = useState<string>(
isTablet ? CALENDAR_VIEWS.timeGridDay : CALENDAR_VIEWS.timeGridWeek
isTablet || isMobile
? CALENDAR_VIEWS.timeGridDay
: CALENDAR_VIEWS.timeGridWeek
)
useEffect(() => {
const setView = () =>
setCurrentView(prev => {
if (
prev !== CALENDAR_VIEWS.timeGridDay &&
prev !== CALENDAR_VIEWS.timeGridWeek
) {
return prev
}
return isTablet
const setView = (): void =>
setCurrentView(
isTablet || isMobile
? CALENDAR_VIEWS.timeGridDay
: CALENDAR_VIEWS.timeGridWeek
})
)
setView()
}, [isTablet])
}, [isTablet, isMobile])
const isInIframe = useMemo(() => new CozyBridge().isInIframe(), [])
const handleRefresh = async () => {
const handleRefresh = async (): Promise<void> => {
// Get current calendar range
if (calendarRef.current) {
const view = calendarRef.current.view
@@ -69,7 +64,7 @@ export default function CalendarLayout() {
}
}
const handleDateChange = (date: Date) => {
const handleDateChange = (date: Date): void => {
setCurrentDate(date)
}
@@ -96,14 +91,14 @@ export default function CalendarLayout() {
}
// Cleanup on unmount
return () => {
return (): void => {
document.body.classList.remove('fullscreen-view')
}
}, [view])
const menubarProps: MenubarProps = {
calendarRef,
onRefresh: handleRefresh,
onRefresh: () => void handleRefresh(),
currentDate,
onDateChange: handleDateChange,
currentView,
+9 -1
View File
@@ -32,7 +32,6 @@ a.fc-timegrid-axis-cushion
.fc-daygrid-day-top .fc-daygrid-day-number,
span.fc-daygrid-day-number
color #243b55
margin 0 6px 0 0
font-family Roboto
font-size 28px
font-style normal
@@ -75,6 +74,15 @@ span.fc-daygrid-day-number.current-date
span.fc-daygrid-day-number.current-date:after
background-color #FB9E3A
.fc-daygrid-day-top--mobile .fc-daygrid-day-number
font-size 22px
width 38px
line-height 29px
.fc-daygrid-day-top--mobile .fc-daygrid-day-number:after
width 36px
height 36px
td.fc-timegrid-slot.fc-timegrid-slot-label.fc-scrollgrid-shrink,
td.fc-timegrid-slot.fc-timegrid-slot-label.fc-timegrid-slot-minor
border 0
+8 -2
View File
@@ -21,8 +21,12 @@ export interface CalendarSidebarProps {
currentView: string
}
export default function Sidebar(sharedProps: CalendarSidebarProps) {
const { isTablet } = useScreenSizeDetection()
const Sidebar: React.FC<CalendarSidebarProps> = (
sharedProps: CalendarSidebarProps
) => {
const { isTablet, isTooSmall: isMobile } = useScreenSizeDetection()
if (isMobile) return null
return isTablet ? (
<TabletSidebar {...sharedProps} />
@@ -30,3 +34,5 @@ export default function Sidebar(sharedProps: CalendarSidebarProps) {
<DesktopSidebar {...sharedProps} />
)
}
export default Sidebar
+3 -3
View File
@@ -6,11 +6,11 @@ import { AppListMenu } from './AppListMenu'
import SearchBar from './EventSearchBar'
import { MainTitle } from './MainTitle'
import { SharedMenubarProps } from './Menubar'
import { NavigationControls } from './NavigationControls'
import { NavigationControls } from './components/NavigationControls'
import { SelectView } from './SelectView'
import { UserMenu } from './UserMenu'
export function DesktopMenubar({
export const DesktopMenubar: React.FC<SharedMenubarProps> = ({
calendarRef,
currentView,
isIframe,
@@ -29,7 +29,7 @@ export function DesktopMenubar({
user,
userMenuAnchorEl,
onUserMenuClose
}: SharedMenubarProps) {
}) => {
const { t } = useI18n()
return (
+1
View File
@@ -39,6 +39,7 @@
width 100%
z-index 1100
height 60px
min-height 60px
background-color #fff
.menubar-item
+23 -11
View File
@@ -11,6 +11,7 @@ import { useI18n } from 'twake-i18n'
import { DesktopMenubar } from './DesktopMenubar'
import './Menubar.styl'
import { TabletMenubar } from './TabletMenubar'
import { MobileMenubar } from './MobileMenuBar'
export type AppIconProps = {
name: string
@@ -64,7 +65,7 @@ export const Menubar: React.FC<MenubarProps> = ({
null
)
const dispatch = useAppDispatch()
const { isTablet } = useScreenSizeDetection()
const { isTablet, isTooSmall: isMobile } = useScreenSizeDetection()
useEffect(() => {
const resetMenuAnchorsOnResize = (): void => {
@@ -84,9 +85,9 @@ export const Menubar: React.FC<MenubarProps> = ({
return null
}
const handleNavigation = async (action: 'prev' | 'next' | 'today') => {
const handleNavigation = (action: 'prev' | 'next' | 'today'): void => {
if (!calendarRef.current) return
await dispatch(setView('calendar'))
dispatch(setView('calendar'))
switch (action) {
case 'prev':
calendarRef.current.prev()
@@ -106,31 +107,31 @@ export const Menubar: React.FC<MenubarProps> = ({
}
}
const handleViewChange = async (view: string) => {
const handleViewChange = (view: string): void => {
// Notify parent about view change
if (onViewChange) {
onViewChange(view)
}
}
const handleAppMenuOpen = (event: React.MouseEvent<HTMLElement>) =>
const handleAppMenuOpen = (event: React.MouseEvent<HTMLElement>): void =>
setAnchorEl(event.currentTarget)
const handleAppMenuClose = () => setAnchorEl(null)
const handleAppMenuClose = (): void => setAnchorEl(null)
const handleUserMenuOpen = (event: React.MouseEvent<HTMLElement>) =>
const handleUserMenuOpen = (event: React.MouseEvent<HTMLElement>): void =>
setUserMenuAnchorEl(event.currentTarget)
const handleUserMenuClose = () => {
const handleUserMenuClose = (): void => {
setUserMenuAnchorEl(null)
}
const handleSettingsClick = () => {
const handleSettingsClick = (): void => {
dispatch(setView('settings'))
handleUserMenuClose()
}
const handleLogoutClick = async () => {
const handleLogoutClick = async (): Promise<void> => {
const logoutUrl = await Logout()
sessionStorage.removeItem('tokenSet')
redirectTo(logoutUrl.href)
@@ -161,11 +162,22 @@ export const Menubar: React.FC<MenubarProps> = ({
onUserMenuOpen: handleUserMenuOpen,
onUserMenuClose: handleUserMenuClose,
onSettingsClick: handleSettingsClick,
onLogoutClick: handleLogoutClick,
onLogoutClick: () => void handleLogoutClick(),
onNavigate: handleNavigation,
user
}
if (isMobile) {
return (
<MobileMenubar
calendarRef={calendarRef}
currentDate={currentDate}
onDateChange={onDateChange}
handleNavigation={handleNavigation}
/>
)
}
return isTablet ? (
<TabletMenubar {...sharedProps} />
) : (
+87
View File
@@ -0,0 +1,87 @@
import { CalendarApi } from '@fullcalendar/core'
import { IconButton, Stack } from '@linagora/twake-mui'
import ArrowDropDownIcon from '@mui/icons-material/ArrowDropDown'
import ArrowDropUpIcon from '@mui/icons-material/ArrowDropUp'
import React, { useState } from 'react'
import { useI18n } from 'twake-i18n'
import SearchBar from './EventSearchBar'
import './Menubar.styl'
import { DatePickerMobile } from './components/DatePickerMobile'
import { Typography } from '@mui/material'
import { SmallNavigationControls } from './components/SmallNavigationControls'
export type MobileMenubarProps = {
calendarRef: React.RefObject<CalendarApi | null>
currentDate: Date
onDateChange?: (date: Date) => void
handleNavigation: (action: 'prev' | 'next' | 'today') => void
}
export const MobileMenubar: React.FC<MobileMenubarProps> = ({
calendarRef,
currentDate,
onDateChange,
handleNavigation
}) => {
const { t } = useI18n()
const [openDatePicker, setOpenDatePicker] = useState(false)
// Use i18n for month names instead of date-fns
const monthIndex = currentDate.getMonth()
const year = currentDate.getFullYear()
const monthName = t(`months.standalone.${monthIndex}`)
const dateLabel = `${monthName} ${year}`
return (
<>
<header className="menubar">
<div className="left-menu">
<div className="menu-items">
<SmallNavigationControls onNavigate={handleNavigation} />
</div>
<div className="menu-items">
<Stack direction="row" className="current-date-time">
<Typography
sx={{ lineHeight: 'unset' }}
onClick={() => setOpenDatePicker(prev => !prev)}
>
{dateLabel}
</Typography>
<IconButton
size="small"
onClick={() => setOpenDatePicker(prev => !prev)}
aria-label={
openDatePicker
? t('menubar.hideDatePicker')
: t('menubar.showDatePicker')
}
title={
openDatePicker
? t('menubar.hideDatePicker')
: t('menubar.showDatePicker')
}
aria-expanded={openDatePicker}
>
{openDatePicker ? <ArrowDropUpIcon /> : <ArrowDropDownIcon />}
</IconButton>
</Stack>
</div>
</div>
<div className="right-menu">
<div className="search-container">
<SearchBar />
</div>
</div>
</header>
{openDatePicker ? (
<DatePickerMobile
calendarRef={calendarRef}
currentDate={currentDate}
onDateChange={onDateChange}
/>
) : null}
</>
)
}
+5 -36
View File
@@ -1,16 +1,14 @@
import { IconButton, Stack } from '@linagora/twake-mui'
import ChevronLeftIcon from '@mui/icons-material/ChevronLeft'
import ChevronRightIcon from '@mui/icons-material/ChevronRight'
import { IconButton } from '@linagora/twake-mui'
import MenuIcon from '@mui/icons-material/Menu'
import RefreshIcon from '@mui/icons-material/Refresh'
import TodayIcon from '@mui/icons-material/Today'
import { useI18n } from 'twake-i18n'
import SearchBar from './EventSearchBar'
import { MainTitle } from './MainTitle'
import { SharedMenubarProps } from './Menubar'
import { UserMenu } from './UserMenu'
import { SmallNavigationControls } from './components/SmallNavigationControls'
export function TabletMenubar({
export const TabletMenubar: React.FC<SharedMenubarProps> = ({
calendarRef,
currentView,
isIframe,
@@ -26,7 +24,7 @@ export function TabletMenubar({
onUserMenuClose,
onViewChange,
onDateChange
}: SharedMenubarProps) {
}: SharedMenubarProps) => {
const { t } = useI18n()
return (
@@ -52,36 +50,7 @@ export function TabletMenubar({
)}
<div className="menu-items" style={{ marginLeft: 0 }}>
<div className="navigation-controls">
<Stack direction="row">
<IconButton
onClick={() => onNavigate('prev')}
aria-label={t('menubar.prev')}
title={t('menubar.prev')}
>
<ChevronLeftIcon sx={{ height: 20 }} />
</IconButton>
<IconButton
color="primary"
sx={{
border: '1px solid',
borderRadius: '12px'
}}
onClick={() => onNavigate('today')}
aria-label={t('menubar.today')}
title={t('menubar.today')}
>
<TodayIcon />
</IconButton>
<IconButton
onClick={() => onNavigate('next')}
aria-label={t('menubar.next')}
title={t('menubar.next')}
>
<ChevronRightIcon sx={{ height: 20 }} />
</IconButton>
</Stack>
</div>
<SmallNavigationControls onNavigate={onNavigate} />
</div>
<div className="menu-items">
@@ -0,0 +1,93 @@
import { CalendarApi } from '@fullcalendar/core'
import { useTheme } from '@linagora/twake-mui'
import { StaticDatePicker } from '@mui/x-date-pickers/StaticDatePicker'
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider'
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'
import React from 'react'
import { useI18n } from 'twake-i18n'
import dayjs from 'dayjs'
import { PickerValue } from '@mui/x-date-pickers/internals'
import { MonthSelector } from './MonthSelector'
export type DatePickerMobileProps = {
calendarRef: React.RefObject<CalendarApi | null>
currentDate: Date
onDateChange?: (date: Date) => void
}
export const DatePickerMobile: React.FC<DatePickerMobileProps> = ({
calendarRef,
currentDate,
onDateChange
}) => {
const { t, lang } = useI18n()
const theme = useTheme()
const onChangeDate = (newDate: PickerValue): void => {
if (newDate && calendarRef.current) {
const d = newDate.toDate()
calendarRef.current.gotoDate(d)
onDateChange?.(d)
}
}
const onMonthChange = (monthIndex: number): void => {
if (!calendarRef.current) return
const currentCalendarDate = calendarRef.current.getDate()
const year = currentCalendarDate.getFullYear()
const lastDayOfMonth = new Date(year, monthIndex + 1, 0).getDate()
const clampedDay = Math.min(currentCalendarDate.getDate(), lastDayOfMonth)
onChangeDate(dayjs(new Date(year, monthIndex, clampedDay)))
}
return (
<LocalizationProvider
key={lang}
dateAdapter={AdapterDayjs}
adapterLocale={lang ?? 'en'}
localeText={{
okButtonLabel: t('common.ok'),
cancelButtonLabel: t('common.cancel'),
todayButtonLabel: t('menubar.today')
}}
>
<StaticDatePicker
value={dayjs(currentDate)}
onChange={onChangeDate}
showDaysOutsideCurrentMonth
slots={{ calendarHeader: () => null, actionBar: () => null }}
sx={{ width: '100%', marginTop: '10px' }}
slotProps={{
toolbar: { hidden: true },
layout: {
sx: {
'.MuiDateCalendar-root': {
width: '100%',
margin: 0,
maxWidth: 'unset',
maxHeight: 'unset',
height: '400px'
},
'.MuiDayCalendar-header': {
width: '100%',
justifyContent: 'space-around'
},
'.MuiDayCalendar-weekContainer': {
width: '100%',
justifyContent: 'space-around'
}
}
},
day: {
sx: {
'&.MuiPickersDay-dayOutsideMonth': {
color: theme.palette.grey[500]
}
}
}
}}
/>
<MonthSelector currentDate={currentDate} onMonthChange={onMonthChange} />
</LocalizationProvider>
)
}
@@ -0,0 +1,63 @@
import { Box, Button, radius } from '@linagora/twake-mui'
import React, { useEffect, useRef } from 'react'
import { useI18n } from 'twake-i18n'
export type MonthSelectorProps = {
currentDate: Date
onMonthChange: (monthIndex: number) => void
}
export const MonthSelector: React.FC<MonthSelectorProps> = ({
currentDate,
onMonthChange
}) => {
const { t } = useI18n()
const monthScrollRef = useRef<HTMLDivElement>(null)
useEffect(() => {
const container = monthScrollRef.current
if (!container) return
const selectedIndex = currentDate.getMonth()
const button = container.children[selectedIndex] as HTMLElement | undefined
if (button) {
button.scrollIntoView({
behavior: 'smooth',
block: 'nearest',
inline: 'center'
})
}
}, [currentDate])
return (
<Box
ref={monthScrollRef}
sx={{
display: 'flex',
overflowX: 'auto',
gap: 2,
px: 2,
py: 1,
scrollbarWidth: 'none',
'&::-webkit-scrollbar': { display: 'none' },
backgroundColor: '#FFF'
}}
>
{Array.from({ length: 12 }).map((_, i) => {
const isSelected = currentDate.getMonth() === i
return (
<Button
key={i}
size="large"
variant={isSelected ? 'contained' : 'outlined'}
sx={{
borderRadius: radius.md
}}
onClick={() => onMonthChange(i)}
>
{t(`months.short.${i}`)}
</Button>
)
})}
</Box>
)
}
@@ -3,11 +3,9 @@ import ChevronLeftIcon from '@mui/icons-material/ChevronLeft'
import ChevronRightIcon from '@mui/icons-material/ChevronRight'
import { useI18n } from 'twake-i18n'
export function NavigationControls({
onNavigate
}: {
export const NavigationControls: React.FC<{
onNavigate: (action: 'today' | 'next' | 'prev') => void
}) {
}> = ({ onNavigate }) => {
const { t } = useI18n()
return (
<div className="navigation-controls">
@@ -0,0 +1,44 @@
import { IconButton, Stack } from '@linagora/twake-mui'
import ChevronLeftIcon from '@mui/icons-material/ChevronLeft'
import ChevronRightIcon from '@mui/icons-material/ChevronRight'
import TodayIcon from '@mui/icons-material/Today'
import { useI18n } from 'twake-i18n'
export const SmallNavigationControls: React.FC<{
onNavigate: (action: 'today' | 'next' | 'prev') => void
}> = ({ onNavigate }) => {
const { t } = useI18n()
return (
<div className="navigation-controls">
<Stack direction="row">
<IconButton
onClick={() => onNavigate('prev')}
aria-label={t('menubar.prev')}
title={t('menubar.prev')}
>
<ChevronLeftIcon sx={{ height: 20 }} />
</IconButton>
<IconButton
color="primary"
aria-label={t('menubar.today')}
title={t('menubar.today')}
sx={{
border: '1px solid',
borderRadius: '12px'
}}
onClick={() => onNavigate('today')}
>
<TodayIcon />
</IconButton>
<IconButton
onClick={() => onNavigate('next')}
aria-label={t('menubar.next')}
title={t('menubar.next')}
>
<ChevronRightIcon sx={{ height: 20 }} />
</IconButton>
</Stack>
</div>
)
}
+20
View File
@@ -0,0 +1,20 @@
declare module '@linagora/twake-mui' {
export * from '@mui/material'
import type { AvatarProps as MuiAvatarProps } from '@mui/material'
export type AvatarSize = 'xs' | 's' | 'm' | 'l' | 'xl'
export type AvatarDisplay = 'initial' | 'inline'
export interface AvatarProps extends Omit<MuiAvatarProps, 'color'> {
color?: string
size?: AvatarSize | number
border?: boolean
innerBorder?: boolean
disabled?: boolean
display?: AvatarDisplay
}
export const Avatar: React.FC<AvatarProps>
export const radius: Record<string, string | number>
}
+17 -1
View File
@@ -247,7 +247,9 @@
"logoAlt": "Calendar",
"settings": "Settings",
"help": "Help",
"logout": "Logout"
"logout": "Logout",
"hideDatePicker": "Hide date picker",
"showDatePicker": "Show date picker"
},
"settings": {
"title": "Settings",
@@ -365,6 +367,20 @@
"9": "October",
"10": "November",
"11": "December"
},
"short": {
"0": "Jan",
"1": "Feb",
"2": "Mar",
"3": "Apr",
"4": "May",
"5": "Jun",
"6": "Jul",
"7": "Aug",
"8": "Sep",
"9": "Oct",
"10": "Nov",
"11": "Dec"
}
},
"mobile": {
+17 -1
View File
@@ -248,7 +248,9 @@
"settings": "Paramètres",
"help": "Aide",
"logout": "Déconnexion",
"toggleSidebar": "Afficher/masquer la barre latérale"
"toggleSidebar": "Afficher/masquer la barre latérale",
"hideDatePicker": "Masquer le sélecteur de date",
"showDatePicker": "Afficher le sélecteur de date"
},
"settings": {
"title": "Paramètres",
@@ -366,6 +368,20 @@
"9": "Octobre",
"10": "Novembre",
"11": "Décembre"
},
"short": {
"0": "Jan",
"1": "Fév",
"2": "Mar",
"3": "Avr",
"4": "Mai",
"5": "Juin",
"6": "Juil",
"7": "Aoû",
"8": "Sep",
"9": "Oct",
"10": "Nov",
"11": "Déc"
}
},
"mobile": {
+17 -1
View File
@@ -248,7 +248,9 @@
"settings": "Настройки",
"help": "Помощь",
"logout": "Выйти",
"toggleSidebar": "Показать/скрыть боковую панель"
"toggleSidebar": "Показать/скрыть боковую панель",
"hideDatePicker": "Скрыть выбор даты",
"showDatePicker": "Показать выбор даты"
},
"settings": {
"title": "Настройки",
@@ -366,6 +368,20 @@
"9": "Октябрь",
"10": "Ноябрь",
"11": "Декабрь"
},
"short": {
"0": "Янв",
"1": "Фев",
"2": "Мар",
"3": "Апр",
"4": "Май",
"5": "Июн",
"6": "Июл",
"7": "Авг",
"8": "Сен",
"9": "Окт",
"10": "Ноя",
"11": "Дек"
}
},
"mobile": {
+17 -1
View File
@@ -246,7 +246,9 @@
"settings": "Cài đặt",
"help": "Giúp đỡ",
"logout": "Đăng xuất",
"toggleSidebar": "Ẩn/hiện thanh bên"
"toggleSidebar": "Ẩn/hiện thanh bên",
"hideDatePicker": "Ẩn chọn ngày",
"showDatePicker": "Hiện chọn ngày"
},
"settings": {
"title": "Cài đặt",
@@ -364,6 +366,20 @@
"9": "Tháng 10",
"10": "Tháng 11",
"11": "Tháng 12"
},
"short": {
"0": "Th1",
"1": "Th2",
"2": "Th3",
"3": "Th4",
"4": "Th5",
"5": "Th6",
"6": "Th7",
"7": "Th8",
"8": "Th9",
"9": "Th10",
"10": "Th11",
"11": "Th12"
}
},
"mobile": {