Merge pull request #733 from lethemanh/681-day-view-with-sidebar-on-mobile

681 day view with sidebar on mobile
This commit is contained in:
lethemanh
2026-04-07 17:19:16 +07:00
committed by GitHub
30 changed files with 1018 additions and 407 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 { default as HandleLogin } from './features/User/HandleLogin'
import { CallbackResume } from './features/User/LoginCallback' import { CallbackResume } from './features/User/LoginCallback'
import { useInitializeApp } from './features/User/useInitializeApp' import { useInitializeApp } from './features/User/useInitializeApp'
import { ScreenTooSmall } from './ScreenTooSmall'
import { useScreenSizeDetection } from './useScreenSizeDetection'
import { WebSocketGate } from './websocket/WebSocketGate' import { WebSocketGate } from './websocket/WebSocketGate'
import { import {
@@ -65,8 +63,6 @@ function App(): JSX.Element {
useInitializeApp() useInitializeApp()
const { isTooSmall } = useScreenSizeDetection()
return ( return (
<TwakeMuiThemeProvider> <TwakeMuiThemeProvider>
<I18n <I18n
@@ -74,25 +70,19 @@ function App(): JSX.Element {
lang={lang} lang={lang}
locales={dateLocales} locales={dateLocales}
> >
{isTooSmall ? ( <Suspense fallback={<Loading />}>
<ScreenTooSmall /> <WebSocketGate />
) : ( <Router history={history}>
<> <Routes>
<Suspense fallback={<Loading />}> <Route path="/" element={<HandleLogin />} />
<WebSocketGate /> <Route path="/calendar" element={<CalendarLayout />} />
<Router history={history}> <Route path="/callback" element={<CallbackResume />} />
<Routes> <Route path="/error" element={<ErrorPage />} />
<Route path="/" element={<HandleLogin />} /> </Routes>
<Route path="/calendar" element={<CalendarLayout />} /> </Router>
<Route path="/callback" element={<CallbackResume />} /> <ErrorSnackbar error={error} type="user" />
<Route path="/error" element={<ErrorPage />} /> </Suspense>
</Routes> {appLoading && <Loading />}
</Router>
<ErrorSnackbar error={error} type="user" />
</Suspense>
{appLoading && <Loading />}
</>
)}
</I18n> </I18n>
</TwakeMuiThemeProvider> </TwakeMuiThemeProvider>
) )
+3
View File
@@ -87,6 +87,9 @@
align-items center align-items center
padding 0.5rem 0 padding 0.5rem 0
font-family "Inter", sans-serif font-family "Inter", sans-serif
gap 6px
&--mobile
flex-direction column-reverse !important
/* sidebar*/ /* sidebar*/
.sidebar-calendar .sidebar-calendar
+30 -15
View File
@@ -63,7 +63,7 @@ interface CalendarAppProps {
currentView: string currentView: string
} }
export default function CalendarApp({ const CalendarApp: React.FC<CalendarAppProps> = ({
calendarRef, calendarRef,
onDateChange, onDateChange,
onViewChange, onViewChange,
@@ -72,12 +72,12 @@ export default function CalendarApp({
onCloseSidebar, onCloseSidebar,
setCurrentView, setCurrentView,
currentView currentView
}: CalendarAppProps): JSX.Element { }: CalendarAppProps) => {
const [selectedDate, setSelectedDate] = useState(new Date()) const [selectedDate, setSelectedDate] = useState(new Date())
const [debouncedDate, setDebouncedDate] = useState(new Date()) const [debouncedDate, setDebouncedDate] = useState(new Date())
useEffect(() => { useEffect(() => {
const t = setTimeout(() => setDebouncedDate(selectedDate), 300) const t = setTimeout(() => setDebouncedDate(selectedDate), 300)
return () => clearTimeout(t) return (): void => clearTimeout(t)
}, [selectedDate]) }, [selectedDate])
const [selectedMiniDate, setSelectedMiniDate] = useState(new Date()) const [selectedMiniDate, setSelectedMiniDate] = useState(new Date())
const userId = useAppSelector(state => state.user.userData?.openpaasId) ?? '' const userId = useAppSelector(state => state.user.userData?.openpaasId) ?? ''
@@ -93,7 +93,7 @@ export default function CalendarApp({
state => state.settings.hideDeclinedEvents state => state.settings.hideDeclinedEvents
) )
const { isTablet } = useScreenSizeDetection() const { isTablet, isTooSmall: isMobile } = useScreenSizeDetection()
const hiddenDays = useMemo(() => { const hiddenDays = useMemo(() => {
if (!hideWorkingDays || !workingDays || workingDays.length === 0) return [] if (!hideWorkingDays || !workingDays || workingDays.length === 0) return []
@@ -135,16 +135,16 @@ export default function CalendarApp({
useEffect(() => { useEffect(() => {
const handler = errorHandler.current const handler = errorHandler.current
handler.setErrorCallback(setEventErrors) handler.setErrorCallback(setEventErrors)
return () => handler.setErrorCallback(() => {}) return (): void => handler.setErrorCallback(() => {})
}, []) }, [])
const handleErrorClose = () => { const handleErrorClose = (): void => {
setEventErrors([]) setEventErrors([])
errorHandler.current.clearAll() errorHandler.current.clearAll()
} }
useEffect(() => { useEffect(() => {
const updateSelectedCalendars = () => { const updateSelectedCalendars = (): void => {
if (initialLoadRef.current && calendarIds.length > 0 && userId) { if (initialLoadRef.current && calendarIds.length > 0 && userId) {
const cached = localStorage.getItem('selectedCalendars') const cached = localStorage.getItem('selectedCalendars')
if (cached && cached.length > 0) { if (cached && cached.length > 0) {
@@ -171,7 +171,7 @@ export default function CalendarApp({
}, [selectedCalendars, calendarIds.length]) }, [selectedCalendars, calendarIds.length])
useEffect(() => { useEffect(() => {
const updateSelectedCalendarsOnCalendarChange = () => { const updateSelectedCalendarsOnCalendarChange = (): void => {
if (calendarIds.length === 0) return if (calendarIds.length === 0) return
const validCalendarIds = new Set(calendarIds) const validCalendarIds = new Set(calendarIds)
setSelectedCalendars(prev => { setSelectedCalendars(prev => {
@@ -237,7 +237,13 @@ export default function CalendarApp({
// Listen for eventModalError event to reopen modal on API failure // Listen for eventModalError event to reopen modal on API failure
useEffect(() => { 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') { if (event.detail?.type === 'create') {
// Reopen create event modal // Reopen create event modal
setAnchorEl(document.body) setAnchorEl(document.body)
@@ -286,7 +292,7 @@ export default function CalendarApp({
'eventModalError', 'eventModalError',
handleEventModalError as EventListener handleEventModalError as EventListener
) )
return () => { return (): void => {
window.removeEventListener( window.removeEventListener(
'eventModalError', 'eventModalError',
handleEventModalError as EventListener handleEventModalError as EventListener
@@ -319,7 +325,7 @@ export default function CalendarApp({
calendarRef.current?.changeView(targetView) calendarRef.current?.changeView(targetView)
} }
}) })
return () => cancelAnimationFrame(id) return (): void => cancelAnimationFrame(id)
}, [view, isTablet, currentView, calendarRef]) }, [view, isTablet, currentView, calendarRef])
// Event handlers // Event handlers
const eventHandlers = useCalendarEventHandlers({ const eventHandlers = useCalendarEventHandlers({
@@ -379,6 +385,7 @@ export default function CalendarApp({
tempUsers={tempUsers} tempUsers={tempUsers}
setTempUsers={setTempUsers} setTempUsers={setTempUsers}
currentView={currentView} currentView={currentView}
onDateChange={onDateChange}
/> />
<div className="calendar"> <div className="calendar">
<ImportAlert /> <ImportAlert />
@@ -499,7 +506,7 @@ export default function CalendarApp({
hour12: false hour12: false
}} }}
datesSet={arg => { datesSet={arg => {
setCurrentView(arg.view.type) onViewChange?.(arg.view.type)
const calendarCurrentDate = const calendarCurrentDate =
calendarRef.current?.getDate() || new Date(arg.start) calendarRef.current?.getDate() || new Date(arg.start)
setDisplayedDateAndRange(calendarCurrentDate) setDisplayedDateAndRange(calendarCurrentDate)
@@ -541,7 +548,9 @@ export default function CalendarApp({
.toUpperCase() .toUpperCase()
return ( return (
<div className="fc-daygrid-day-top"> <div
className={`fc-daygrid-day-top ${isTablet || isMobile ? 'fc-daygrid-day-top--mobile' : ''}`}
>
<small>{weekDay}</small> <small>{weekDay}</small>
{arg.view.type !== CALENDAR_VIEWS.dayGridMonth && ( {arg.view.type !== CALENDAR_VIEWS.dayGridMonth && (
<span <span
@@ -559,8 +568,12 @@ export default function CalendarApp({
viewWillUnmount={viewHandlers.handleViewWillUnmount} viewWillUnmount={viewHandlers.handleViewWillUnmount}
eventClick={eventHandlers.handleEventClick} eventClick={eventHandlers.handleEventClick}
eventAllow={eventHandlers.handleEventAllow} eventAllow={eventHandlers.handleEventAllow}
eventDrop={eventHandlers.handleEventDrop} eventDrop={arg => {
eventResize={eventHandlers.handleEventResize} void eventHandlers.handleEventDrop(arg)
}}
eventResize={arg => {
void eventHandlers.handleEventResize(arg)
}}
eventContent={viewHandlers.handleEventContent} eventContent={viewHandlers.handleEventContent}
eventDidMount={viewHandlers.handleEventDidMount} eventDidMount={viewHandlers.handleEventDidMount}
/> />
@@ -599,3 +612,5 @@ export default function CalendarApp({
</main> </main>
) )
} }
export default CalendarApp
+14 -21
View File
@@ -12,7 +12,7 @@ import CalendarApp from './Calendar'
import { CALENDAR_VIEWS } from './utils/constants' import { CALENDAR_VIEWS } from './utils/constants'
import { setView } from '@/features/Settings/SettingsSlice' import { setView } from '@/features/Settings/SettingsSlice'
export default function CalendarLayout() { export default function CalendarLayout(): JSX.Element {
const calendarRef = useRef<CalendarApi | null>(null) const calendarRef = useRef<CalendarApi | null>(null)
const dispatch = useAppDispatch() const dispatch = useAppDispatch()
const error = useAppSelector(state => state.calendars.error) const error = useAppSelector(state => state.calendars.error)
@@ -20,33 +20,28 @@ export default function CalendarLayout() {
const tempcalendars = useAppSelector(state => state.calendars.templist) const tempcalendars = useAppSelector(state => state.calendars.templist)
const view = useAppSelector(state => state.settings.view) const view = useAppSelector(state => state.settings.view)
const { isTablet } = useScreenSizeDetection() const { isTablet, isTooSmall: isMobile } = useScreenSizeDetection()
const [openSidebar, setOpenSideBar] = useState(false) const [openSidebar, setOpenSideBar] = useState(false)
const [currentDate, setCurrentDate] = useState<Date>(new Date()) const [currentDate, setCurrentDate] = useState<Date>(new Date())
const [currentView, setCurrentView] = useState<string>( const [currentView, setCurrentView] = useState<string>(
isTablet ? CALENDAR_VIEWS.timeGridDay : CALENDAR_VIEWS.timeGridWeek isTablet || isMobile
? CALENDAR_VIEWS.timeGridDay
: CALENDAR_VIEWS.timeGridWeek
) )
useEffect(() => { useEffect(() => {
const setView = () => const setView = (): void =>
setCurrentView(prev => { setCurrentView(
if ( isTablet || isMobile
prev !== CALENDAR_VIEWS.timeGridDay &&
prev !== CALENDAR_VIEWS.timeGridWeek
) {
return prev
}
return isTablet
? CALENDAR_VIEWS.timeGridDay ? CALENDAR_VIEWS.timeGridDay
: CALENDAR_VIEWS.timeGridWeek : CALENDAR_VIEWS.timeGridWeek
}) )
setView() setView()
}, [isTablet]) }, [isTablet, isMobile])
const isInIframe = useMemo(() => new CozyBridge().isInIframe(), []) const isInIframe = useMemo(() => new CozyBridge().isInIframe(), [])
const handleRefresh = async () => { const handleRefresh = async (): Promise<void> => {
// Get current calendar range // Get current calendar range
if (calendarRef.current) { if (calendarRef.current) {
const view = calendarRef.current.view const view = calendarRef.current.view
@@ -69,7 +64,7 @@ export default function CalendarLayout() {
} }
} }
const handleDateChange = (date: Date) => { const handleDateChange = (date: Date): void => {
setCurrentDate(date) setCurrentDate(date)
} }
@@ -77,8 +72,6 @@ export default function CalendarLayout() {
if (!calendarRef.current) return if (!calendarRef.current) return
dispatch(setView('calendar')) dispatch(setView('calendar'))
calendarRef.current.changeView(view)
// Notify parent about view change // Notify parent about view change
setCurrentView(view) setCurrentView(view)
@@ -96,14 +89,14 @@ export default function CalendarLayout() {
} }
// Cleanup on unmount // Cleanup on unmount
return () => { return (): void => {
document.body.classList.remove('fullscreen-view') document.body.classList.remove('fullscreen-view')
} }
}, [view]) }, [view])
const menubarProps: MenubarProps = { const menubarProps: MenubarProps = {
calendarRef, calendarRef,
onRefresh: handleRefresh, onRefresh: () => void handleRefresh(),
currentDate, currentDate,
onDateChange: handleDateChange, onDateChange: handleDateChange,
currentView, currentView,
+9 -1
View File
@@ -32,7 +32,6 @@ a.fc-timegrid-axis-cushion
.fc-daygrid-day-top .fc-daygrid-day-number, .fc-daygrid-day-top .fc-daygrid-day-number,
span.fc-daygrid-day-number span.fc-daygrid-day-number
color #243b55 color #243b55
margin 0 6px 0 0
font-family Roboto font-family Roboto
font-size 28px font-size 28px
font-style normal font-style normal
@@ -75,6 +74,15 @@ span.fc-daygrid-day-number.current-date
span.fc-daygrid-day-number.current-date:after span.fc-daygrid-day-number.current-date:after
background-color #FB9E3A 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-scrollgrid-shrink,
td.fc-timegrid-slot.fc-timegrid-slot-label.fc-timegrid-slot-minor td.fc-timegrid-slot.fc-timegrid-slot-label.fc-timegrid-slot-minor
border 0 border 0
-148
View File
@@ -1,148 +0,0 @@
import { CalendarApi } from '@fullcalendar/core'
import { Box, Button, Drawer, radius } from '@linagora/twake-mui'
import AddIcon from '@mui/icons-material/Add'
import CalendarViewDayOutlinedIcon from '@mui/icons-material/CalendarViewDayOutlined'
import CalendarViewMonthOutlinedIcon from '@mui/icons-material/CalendarViewMonthOutlined'
import CalendarViewWeekOutlinedIcon from '@mui/icons-material/CalendarViewWeekOutlined'
import { Dispatch, MutableRefObject, SetStateAction } from 'react'
import { useI18n } from 'twake-i18n'
import { User } from '../Attendees/PeopleSearch'
import { FieldWithLabel } from '../Event/components/FieldWithLabel'
import CalendarSelection from './CalendarSelection'
import { MiniCalendar } from './MiniCalendar'
import { TempCalendarsInput } from './TempCalendarsInput'
interface CalendarSidebarProps {
isTablet: boolean
open: boolean
onClose: () => void
calendarRef: MutableRefObject<CalendarApi | null>
isIframe?: boolean
onCreateEvent: () => void
onViewChange: (view: string) => void
selectedMiniDate: Date
setSelectedMiniDate: (date: Date) => void
selectedCalendars: string[]
setSelectedCalendars: Dispatch<SetStateAction<string[]>>
tempUsers: User[]
setTempUsers: Dispatch<SetStateAction<User[]>>
}
export default function Sidebar({
isTablet,
open,
onClose,
calendarRef,
isIframe,
onCreateEvent,
onViewChange,
selectedMiniDate,
setSelectedMiniDate,
selectedCalendars,
setSelectedCalendars,
tempUsers,
setTempUsers
}: CalendarSidebarProps) {
const { t } = useI18n()
return (
<Drawer
variant={isTablet ? 'temporary' : 'permanent'}
open={isTablet ? open : true}
onClose={onClose}
className="sidebar"
sx={{
[`& .MuiDrawer-paper`]: {
paddingTop: isTablet ? 2 : 0,
paddingBottom: 3,
paddingLeft: 3,
paddingRight: 2,
width: '270px',
marginTop: isTablet ? 0 : '70px'
},
zIndex: isTablet ? 3000 : 5
}}
slotProps={{ paper: { className: 'sidebar' } }}
>
{!isTablet && (
<>
<Box
sx={{
position: 'sticky',
top: 0,
zIndex: 10,
backgroundColor: '#fff',
paddingTop: isIframe ? '10px' : 3
}}
>
<Button
size="medium"
variant="contained"
fullWidth
onClick={onCreateEvent}
sx={{
borderRadius: radius.lg,
fontSize: '16px',
fontWeight: 500,
lineHeight: 'normal'
}}
>
<AddIcon sx={{ marginRight: 0.5, fontSize: '20px' }} />{' '}
{t('event.createEvent')}
</Button>
</Box>
<Box>
<MiniCalendar
calendarRef={calendarRef}
selectedDate={selectedMiniDate}
setSelectedMiniDate={setSelectedMiniDate}
/>
</Box>
</>
)}
{isTablet && (
<FieldWithLabel label={t('sidebar.displayMode')} isExpanded={false}>
<Button
variant="text"
onClick={() => onViewChange('timeGridDay')}
startIcon={<CalendarViewDayOutlinedIcon />}
>
{t('menubar.views.day')}
</Button>
<Button
variant="text"
onClick={() => {
onViewChange('timeGridWeek')
}}
startIcon={<CalendarViewWeekOutlinedIcon />}
>
{t('menubar.views.week')}
</Button>
<Button
variant="text"
onClick={() => onViewChange('dayGridMonth')}
startIcon={<CalendarViewMonthOutlinedIcon />}
>
{t('menubar.views.month')}
</Button>
</FieldWithLabel>
)}
<Box sx={{ mb: 3, mt: 2 }}>
<TempCalendarsInput
tempUsers={tempUsers}
setTempUsers={setTempUsers}
handleToggleEventPreview={onCreateEvent}
/>
</Box>
<Box className="calendarList">
<CalendarSelection
selectedCalendars={selectedCalendars}
setSelectedCalendars={setSelectedCalendars}
/>
</Box>
</Drawer>
)
}
@@ -0,0 +1,125 @@
import { Drawer, IconButton, Box } from '@linagora/twake-mui'
import { CalendarSidebarProps } from './SideBar'
import { SidebarCommonContent } from './SidebarCommonContent'
import { ViewSwitcher } from './ViewSwitcher'
import { MainTitle } from '@/components/Menubar/MainTitle'
import HelpOutlineIcon from '@mui/icons-material/HelpOutline'
import { useI18n } from 'twake-i18n'
import { AppListMenu } from '@/components/Menubar/AppListMenu'
import { UserMenu } from '@/components/Menubar/UserMenu'
import { useAppSelector } from '@/app/hooks'
import { useUtilMenus } from '../hooks/useUtilMenus'
export const MobileSidebar: React.FC<CalendarSidebarProps> = ({
open,
onClose,
onViewChange,
onCreateEvent,
tempUsers,
setTempUsers,
selectedCalendars,
setSelectedCalendars,
currentView,
isIframe,
calendarRef,
onDateChange
}) => {
const { t } = useI18n()
const user = useAppSelector(state => state.user.userData)
const {
anchorEl,
supportLink,
userMenuAnchorEl,
handleAppMenuOpen,
handleAppMenuClose,
handleUserMenuOpen,
handleUserMenuClose,
handleSettingsClick,
handleLogoutClick
} = useUtilMenus()
return (
<Drawer
variant="temporary"
open={open}
onClose={onClose}
className="sidebar"
sx={{
[`& .MuiDrawer-paper`]: {
paddingTop: 2,
paddingBottom: 3,
paddingLeft: 3,
paddingRight: 2,
width: '270px',
marginTop: 0
}
}}
slotProps={{ paper: { className: 'sidebar' } }}
>
{!isIframe && (
<Box
display="flex"
flexDirection="row"
justifyContent="space-between"
sx={{ mb: 2 }}
>
<MainTitle
calendarRef={calendarRef}
currentView={currentView}
onViewChange={onViewChange}
onDateChange={onDateChange}
/>
<Box display="flex" alignItems="center">
{supportLink && (
<IconButton
component="a"
href={supportLink}
target="_blank"
rel="noopener noreferrer"
style={{ marginRight: 4 }}
aria-label={t('menubar.help')}
title={t('menubar.help')}
>
<HelpOutlineIcon fontSize="small" />
</IconButton>
)}
<AppListMenu
anchorEl={anchorEl}
onAppMenuOpen={handleAppMenuOpen}
onAppMenuClose={handleAppMenuClose}
iconSize="small"
/>
<UserMenu
anchorEl={userMenuAnchorEl}
onClose={handleUserMenuClose}
onSettingsClick={handleSettingsClick}
onLogoutClick={() => void handleLogoutClick()}
onUserMenuOpen={handleUserMenuOpen}
isIframe={isIframe}
user={user}
size="s"
/>
</Box>
</Box>
)}
<ViewSwitcher
onClose={onClose}
onViewChange={onViewChange}
currentView={currentView}
/>
<SidebarCommonContent
onCreateEvent={onCreateEvent}
tempUsers={tempUsers}
setTempUsers={setTempUsers}
selectedCalendars={selectedCalendars}
setSelectedCalendars={setSelectedCalendars}
/>
</Drawer>
)
}
+13 -3
View File
@@ -4,6 +4,7 @@ import { Dispatch, MutableRefObject, SetStateAction } from 'react'
import { User } from '../../Attendees/PeopleSearch' import { User } from '../../Attendees/PeopleSearch'
import { DesktopSidebar } from './DesktopSidebar' import { DesktopSidebar } from './DesktopSidebar'
import { TabletSidebar } from './TabletSidebar' import { TabletSidebar } from './TabletSidebar'
import { MobileSidebar } from './MobileSidebar'
export interface CalendarSidebarProps { export interface CalendarSidebarProps {
open: boolean open: boolean
@@ -19,14 +20,23 @@ export interface CalendarSidebarProps {
tempUsers: User[] tempUsers: User[]
setTempUsers: Dispatch<SetStateAction<User[]>> setTempUsers: Dispatch<SetStateAction<User[]>>
currentView: string currentView: string
onDateChange?: (date: Date) => void
} }
export default function Sidebar(sharedProps: CalendarSidebarProps) { const Sidebar: React.FC<CalendarSidebarProps> = (
const { isTablet } = useScreenSizeDetection() sharedProps: CalendarSidebarProps
) => {
const { isTablet, isTooSmall: isMobile } = useScreenSizeDetection()
return isTablet ? ( if (isMobile) {
return <MobileSidebar {...sharedProps} />
}
return isTablet || isMobile ? (
<TabletSidebar {...sharedProps} /> <TabletSidebar {...sharedProps} />
) : ( ) : (
<DesktopSidebar {...sharedProps} /> <DesktopSidebar {...sharedProps} />
) )
} }
export default Sidebar
@@ -1,39 +1,9 @@
import { import { Drawer } from '@linagora/twake-mui'
Drawer,
ListItemIcon,
ListItemText,
MenuItem,
MenuList,
useTheme
} from '@linagora/twake-mui'
import CalendarViewDayOutlinedIcon from '@mui/icons-material/CalendarViewDayOutlined'
import CalendarViewMonthOutlinedIcon from '@mui/icons-material/CalendarViewMonthOutlined'
import CalendarViewWeekOutlinedIcon from '@mui/icons-material/CalendarViewWeekOutlined'
import { useI18n } from 'twake-i18n'
import { FieldWithLabel } from '../../Event/components/FieldWithLabel'
import { CALENDAR_VIEWS } from '../utils/constants'
import { CalendarSidebarProps } from './SideBar' import { CalendarSidebarProps } from './SideBar'
import { SidebarCommonContent } from './SidebarCommonContent' import { SidebarCommonContent } from './SidebarCommonContent'
import { ViewSwitcher } from './ViewSwitcher'
const VIEW_OPTIONS = [ export const TabletSidebar: React.FC<CalendarSidebarProps> = ({
{
label: 'menubar.views.day',
value: CALENDAR_VIEWS.timeGridDay,
icon: <CalendarViewDayOutlinedIcon />
},
{
label: 'menubar.views.week',
value: CALENDAR_VIEWS.timeGridWeek,
icon: <CalendarViewWeekOutlinedIcon />
},
{
label: 'menubar.views.month',
value: CALENDAR_VIEWS.dayGridMonth,
icon: <CalendarViewMonthOutlinedIcon />
}
]
export function TabletSidebar({
open, open,
onClose, onClose,
onViewChange, onViewChange,
@@ -43,15 +13,7 @@ export function TabletSidebar({
selectedCalendars, selectedCalendars,
setSelectedCalendars, setSelectedCalendars,
currentView currentView
}: CalendarSidebarProps) { }) => {
const { t } = useI18n()
const theme = useTheme()
const changeViewAndClose = (view: string): void => {
onViewChange(view)
onClose()
}
return ( return (
<Drawer <Drawer
variant="temporary" variant="temporary"
@@ -70,43 +32,11 @@ export function TabletSidebar({
}} }}
slotProps={{ paper: { className: 'sidebar' } }} slotProps={{ paper: { className: 'sidebar' } }}
> >
<FieldWithLabel label={t('sidebar.displayMode')} isExpanded={false}> <ViewSwitcher
<MenuList> onClose={onClose}
{VIEW_OPTIONS.map(option => { onViewChange={onViewChange}
const isSelected = option.value === currentView currentView={currentView}
return ( />
<MenuItem
key={option.value}
selected={isSelected}
onClick={() => changeViewAndClose(option.value)}
>
<ListItemIcon
sx={{
color: isSelected
? theme.palette.primary.main
: theme.palette.text.primary
}}
>
{option.icon}
</ListItemIcon>
<ListItemText
primary={t(option.label)}
primaryTypographyProps={{
sx: {
fontSize: '14px',
fontWeight: 500,
lineHeight: '20px',
color: isSelected
? theme.palette.primary.main
: theme.palette.text.primary
}
}}
/>
</MenuItem>
)
})}
</MenuList>
</FieldWithLabel>
<SidebarCommonContent <SidebarCommonContent
onCreateEvent={onCreateEvent} onCreateEvent={onCreateEvent}
@@ -0,0 +1,85 @@
import React from 'react'
import {
ListItemIcon,
ListItemText,
MenuItem,
MenuList,
useTheme
} from '@linagora/twake-mui'
import CalendarViewDayOutlinedIcon from '@mui/icons-material/CalendarViewDayOutlined'
import CalendarViewMonthOutlinedIcon from '@mui/icons-material/CalendarViewMonthOutlined'
import CalendarViewWeekOutlinedIcon from '@mui/icons-material/CalendarViewWeekOutlined'
import { useI18n } from 'twake-i18n'
import { FieldWithLabel } from '../../Event/components/FieldWithLabel'
import { CALENDAR_VIEWS } from '../utils/constants'
import { CalendarSidebarProps } from './SideBar'
const VIEW_OPTIONS = [
{
label: 'menubar.views.day',
value: CALENDAR_VIEWS.timeGridDay,
icon: <CalendarViewDayOutlinedIcon />
},
{
label: 'menubar.views.week',
value: CALENDAR_VIEWS.timeGridWeek,
icon: <CalendarViewWeekOutlinedIcon />
},
{
label: 'menubar.views.month',
value: CALENDAR_VIEWS.dayGridMonth,
icon: <CalendarViewMonthOutlinedIcon />
}
]
export const ViewSwitcher: React.FC<
Pick<CalendarSidebarProps, 'onClose' | 'onViewChange' | 'currentView'>
> = ({ onClose, onViewChange, currentView }) => {
const { t } = useI18n()
const theme = useTheme()
const changeViewAndClose = (view: string): void => {
onViewChange(view)
onClose()
}
return (
<FieldWithLabel label={t('sidebar.displayMode')} isExpanded={false}>
<MenuList>
{VIEW_OPTIONS.map(option => {
const isSelected = option.value === currentView
return (
<MenuItem
key={option.value}
selected={isSelected}
onClick={() => changeViewAndClose(option.value)}
>
<ListItemIcon
sx={{
color: isSelected
? theme.palette.primary.main
: theme.palette.text.primary
}}
>
{option.icon}
</ListItemIcon>
<ListItemText
primary={t(option.label)}
primaryTypographyProps={{
sx: {
fontSize: '14px',
fontWeight: 500,
lineHeight: '20px',
color: isSelected
? theme.palette.primary.main
: theme.palette.text.primary
}
}}
/>
</MenuItem>
)
})}
</MenuList>
</FieldWithLabel>
)
}
@@ -2,7 +2,9 @@
import { useCallback } from 'react' import { useCallback } from 'react'
import { createViewHandlers, ViewHandlersProps } from '../handlers/viewHandlers' import { createViewHandlers, ViewHandlersProps } from '../handlers/viewHandlers'
export const useCalendarViewHandlers = (props: ViewHandlersProps) => { export const useCalendarViewHandlers = (
props: ViewHandlersProps
): ReturnType<typeof createViewHandlers> => {
const viewHandlers = createViewHandlers(props) const viewHandlers = createViewHandlers(props)
return { return {
@@ -0,0 +1,77 @@
import { useAppDispatch } from '@/app/hooks'
import { setView } from '@/features/Settings/SettingsSlice'
import { Logout } from '@/features/User/oidcAuth'
import { useScreenSizeDetection } from '@/useScreenSizeDetection'
import { redirectTo } from '@/utils/navigation'
import { useEffect, useState } from 'react'
export const useUtilMenus = (): {
anchorEl: null | HTMLElement
userMenuAnchorEl: null | HTMLElement
supportLink: string
handleAppMenuOpen: (event: React.MouseEvent<HTMLElement>) => void
handleAppMenuClose: () => void
handleUserMenuOpen: (event: React.MouseEvent<HTMLElement>) => void
handleUserMenuClose: () => void
handleSettingsClick: () => void
handleLogoutClick: () => Promise<void>
} => {
const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null)
const [userMenuAnchorEl, setUserMenuAnchorEl] = useState<null | HTMLElement>(
null
)
const supportLink = window.SUPPORT_URL
const dispatch = useAppDispatch()
const { isTablet, isTooSmall: isMobile } = useScreenSizeDetection()
useEffect(() => {
const resetMenuAnchorsOnResize = (): void => {
setAnchorEl(null)
setUserMenuAnchorEl(null)
}
resetMenuAnchorsOnResize()
}, [isTablet, isMobile])
const handleAppMenuOpen = (event: React.MouseEvent<HTMLElement>): void =>
setAnchorEl(event.currentTarget)
const handleAppMenuClose = (): void => setAnchorEl(null)
const handleUserMenuOpen = (event: React.MouseEvent<HTMLElement>): void =>
setUserMenuAnchorEl(event.currentTarget)
const handleUserMenuClose = (): void => {
setUserMenuAnchorEl(null)
}
const handleSettingsClick = (): void => {
dispatch(setView('settings'))
handleUserMenuClose()
}
const handleLogoutClick = async (): Promise<void> => {
try {
const logoutUrl = await Logout()
redirectTo(logoutUrl.href)
} catch (error) {
console.error('Logout failed:', error)
} finally {
sessionStorage.removeItem('tokenSet')
handleUserMenuClose()
}
}
return {
anchorEl,
userMenuAnchorEl,
supportLink,
handleAppMenuOpen,
handleAppMenuClose,
handleUserMenuOpen,
handleUserMenuClose,
handleSettingsClick,
handleLogoutClick
}
}
+4 -7
View File
@@ -3,15 +3,12 @@ import WidgetsOutlinedIcon from '@mui/icons-material/WidgetsOutlined'
import { useI18n } from 'twake-i18n' import { useI18n } from 'twake-i18n'
import { AppIcon, AppIconProps } from './AppIcon' import { AppIcon, AppIconProps } from './AppIcon'
export function AppListMenu({ export const AppListMenu: React.FC<{
anchorEl,
onAppMenuOpen,
onAppMenuClose
}: {
anchorEl: HTMLElement | null anchorEl: HTMLElement | null
onAppMenuOpen: (event: React.MouseEvent<HTMLElement, MouseEvent>) => void onAppMenuOpen: (event: React.MouseEvent<HTMLElement, MouseEvent>) => void
onAppMenuClose: () => void onAppMenuClose: () => void
}) { iconSize?: 'inherit' | 'small' | 'medium' | 'large'
}> = ({ anchorEl, onAppMenuOpen, onAppMenuClose, iconSize = 'inherit' }) => {
const { t } = useI18n() const { t } = useI18n()
const applist: AppIconProps[] = window.appList ?? [] const applist: AppIconProps[] = window.appList ?? []
@@ -27,7 +24,7 @@ export function AppListMenu({
aria-label={t('menubar.apps')} aria-label={t('menubar.apps')}
title={t('menubar.apps')} title={t('menubar.apps')}
> >
<WidgetsOutlinedIcon /> <WidgetsOutlinedIcon fontSize={iconSize} />
</IconButton> </IconButton>
<Popover <Popover
+3 -3
View File
@@ -6,11 +6,11 @@ import { AppListMenu } from './AppListMenu'
import SearchBar from './EventSearchBar' import SearchBar from './EventSearchBar'
import { MainTitle } from './MainTitle' import { MainTitle } from './MainTitle'
import { SharedMenubarProps } from './Menubar' import { SharedMenubarProps } from './Menubar'
import { NavigationControls } from './NavigationControls' import { NavigationControls } from './components/NavigationControls'
import { SelectView } from './SelectView' import { SelectView } from './SelectView'
import { UserMenu } from './UserMenu' import { UserMenu } from './UserMenu'
export function DesktopMenubar({ export const DesktopMenubar: React.FC<SharedMenubarProps> = ({
calendarRef, calendarRef,
currentView, currentView,
isIframe, isIframe,
@@ -29,7 +29,7 @@ export function DesktopMenubar({
user, user,
userMenuAnchorEl, userMenuAnchorEl,
onUserMenuClose onUserMenuClose
}: SharedMenubarProps) { }) => {
const { t } = useI18n() const { t } = useI18n()
return ( return (
+17 -13
View File
@@ -6,6 +6,7 @@ import { Button } from '@linagora/twake-mui'
import React from 'react' import React from 'react'
import { useI18n } from 'twake-i18n' import { useI18n } from 'twake-i18n'
import { CALENDAR_VIEWS } from '../Calendar/utils/constants' import { CALENDAR_VIEWS } from '../Calendar/utils/constants'
import { useScreenSizeDetection } from '@/useScreenSizeDetection'
export type MainTitleProps = { export type MainTitleProps = {
calendarRef: React.RefObject<CalendarApi | null> calendarRef: React.RefObject<CalendarApi | null>
@@ -14,33 +15,36 @@ export type MainTitleProps = {
onDateChange?: (date: Date) => void onDateChange?: (date: Date) => void
} }
export function MainTitle({ export const MainTitle: React.FC<MainTitleProps> = ({
calendarRef, calendarRef,
currentView, currentView,
onViewChange, onViewChange,
onDateChange onDateChange
}: MainTitleProps) { }: MainTitleProps) => {
const { t } = useI18n() const { t } = useI18n()
const dispatch = useAppDispatch() const dispatch = useAppDispatch()
const { isTablet, isTooSmall: isMobile } = useScreenSizeDetection()
const handleLogoClick = async () => { const isDesktop = !isTablet && !isMobile
const handleLogoClick = (): void => {
if (!calendarRef.current) return if (!calendarRef.current) return
await dispatch(setView('calendar')) dispatch(setView('calendar'))
if (currentView !== CALENDAR_VIEWS.timeGridWeek) { if (currentView !== CALENDAR_VIEWS.timeGridWeek && isDesktop) {
calendarRef.current.changeView(CALENDAR_VIEWS.timeGridWeek) calendarRef.current.changeView(CALENDAR_VIEWS.timeGridWeek)
if (onViewChange) { onViewChange?.(CALENDAR_VIEWS.timeGridWeek)
onViewChange(CALENDAR_VIEWS.timeGridWeek) }
}
if (currentView !== CALENDAR_VIEWS.timeGridDay && !isDesktop) {
calendarRef.current.changeView(CALENDAR_VIEWS.timeGridDay)
onViewChange?.(CALENDAR_VIEWS.timeGridDay)
} }
calendarRef.current.today() calendarRef.current.today()
if (onDateChange) { onDateChange?.(calendarRef.current.getDate())
const newDate = calendarRef.current.getDate()
onDateChange(newDate)
}
} }
return ( return (
@@ -51,7 +55,7 @@ export function MainTitle({
style={{ background: 'none', border: 0, padding: 0, cursor: 'pointer' }} style={{ background: 'none', border: 0, padding: 0, cursor: 'pointer' }}
> >
<img <img
className="logo" className={`logo ${isMobile ? 'logo--mobile' : ''}`}
src={logo} src={logo}
alt={t('menubar.logoAlt')} alt={t('menubar.logoAlt')}
onClick={handleLogoClick} onClick={handleLogoClick}
+5
View File
@@ -39,6 +39,7 @@
width 100% width 100%
z-index 1100 z-index 1100
height 60px height 60px
min-height 60px
background-color #fff background-color #fff
.menubar-item .menubar-item
@@ -54,6 +55,10 @@
max-width 230px max-width 230px
margin-left 1rem margin-left 1rem
&--mobile
max-width 130px
margin-left 0
.nav-month .nav-month
padding-right 2px padding-right 2px
padding-left 2px padding-left 2px
+33 -45
View File
@@ -1,16 +1,16 @@
import { useAppDispatch, useAppSelector } from '@/app/hooks' import { useAppDispatch, useAppSelector } from '@/app/hooks'
import { setView } from '@/features/Settings/SettingsSlice' import { setView } from '@/features/Settings/SettingsSlice'
import { Logout } from '@/features/User/oidcAuth'
import { userData } from '@/features/User/userDataTypes' import { userData } from '@/features/User/userDataTypes'
import { useScreenSizeDetection } from '@/useScreenSizeDetection' import { useScreenSizeDetection } from '@/useScreenSizeDetection'
import { redirectTo } from '@/utils/navigation'
import { CalendarApi } from '@fullcalendar/core' import { CalendarApi } from '@fullcalendar/core'
import React, { useEffect, useState } from 'react' import React, { useEffect } from 'react'
import { push } from 'redux-first-history' import { push } from 'redux-first-history'
import { useI18n } from 'twake-i18n' import { useI18n } from 'twake-i18n'
import { DesktopMenubar } from './DesktopMenubar' import { DesktopMenubar } from './DesktopMenubar'
import './Menubar.styl' import './Menubar.styl'
import { TabletMenubar } from './TabletMenubar' import { TabletMenubar } from './TabletMenubar'
import { MobileMenubar } from './MobileMenuBar'
import { useUtilMenus } from '../Calendar/hooks/useUtilMenus'
export type AppIconProps = { export type AppIconProps = {
name: string name: string
@@ -58,21 +58,21 @@ export const Menubar: React.FC<MenubarProps> = ({
const { t } = useI18n() // deliberately NOT using f() const { t } = useI18n() // deliberately NOT using f()
const user = useAppSelector(state => state.user.userData) const user = useAppSelector(state => state.user.userData)
const supportLink = window.SUPPORT_URL
const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null)
const [userMenuAnchorEl, setUserMenuAnchorEl] = useState<null | HTMLElement>(
null
)
const dispatch = useAppDispatch()
const { isTablet } = useScreenSizeDetection()
useEffect(() => { const {
const resetMenuAnchorsOnResize = (): void => { anchorEl,
setAnchorEl(null) userMenuAnchorEl,
setUserMenuAnchorEl(null) supportLink,
} handleAppMenuOpen,
resetMenuAnchorsOnResize() handleAppMenuClose,
}, [isTablet]) handleUserMenuOpen,
handleUserMenuClose,
handleSettingsClick,
handleLogoutClick
} = useUtilMenus()
const dispatch = useAppDispatch()
const { isTablet, isTooSmall: isMobile } = useScreenSizeDetection()
useEffect(() => { useEffect(() => {
if (!user) { if (!user) {
@@ -84,9 +84,9 @@ export const Menubar: React.FC<MenubarProps> = ({
return null return null
} }
const handleNavigation = async (action: 'prev' | 'next' | 'today') => { const handleNavigation = (action: 'prev' | 'next' | 'today'): void => {
if (!calendarRef.current) return if (!calendarRef.current) return
await dispatch(setView('calendar')) dispatch(setView('calendar'))
switch (action) { switch (action) {
case 'prev': case 'prev':
calendarRef.current.prev() calendarRef.current.prev()
@@ -106,37 +106,13 @@ export const Menubar: React.FC<MenubarProps> = ({
} }
} }
const handleViewChange = async (view: string) => { const handleViewChange = (view: string): void => {
// Notify parent about view change // Notify parent about view change
if (onViewChange) { if (onViewChange) {
onViewChange(view) onViewChange(view)
} }
} }
const handleAppMenuOpen = (event: React.MouseEvent<HTMLElement>) =>
setAnchorEl(event.currentTarget)
const handleAppMenuClose = () => setAnchorEl(null)
const handleUserMenuOpen = (event: React.MouseEvent<HTMLElement>) =>
setUserMenuAnchorEl(event.currentTarget)
const handleUserMenuClose = () => {
setUserMenuAnchorEl(null)
}
const handleSettingsClick = () => {
dispatch(setView('settings'))
handleUserMenuClose()
}
const handleLogoutClick = async () => {
const logoutUrl = await Logout()
sessionStorage.removeItem('tokenSet')
redirectTo(logoutUrl.href)
handleUserMenuClose()
}
// Use i18n for month names instead of date-fns // Use i18n for month names instead of date-fns
const monthIndex = currentDate.getMonth() const monthIndex = currentDate.getMonth()
const year = currentDate.getFullYear() const year = currentDate.getFullYear()
@@ -161,11 +137,23 @@ export const Menubar: React.FC<MenubarProps> = ({
onUserMenuOpen: handleUserMenuOpen, onUserMenuOpen: handleUserMenuOpen,
onUserMenuClose: handleUserMenuClose, onUserMenuClose: handleUserMenuClose,
onSettingsClick: handleSettingsClick, onSettingsClick: handleSettingsClick,
onLogoutClick: handleLogoutClick, onLogoutClick: () => void handleLogoutClick(),
onNavigate: handleNavigation, onNavigate: handleNavigation,
user user
} }
if (isMobile) {
return (
<MobileMenubar
calendarRef={calendarRef}
currentDate={currentDate}
onDateChange={onDateChange}
handleNavigation={handleNavigation}
onOpenSidebar={onToggleSidebar}
/>
)
}
return isTablet ? ( return isTablet ? (
<TabletMenubar {...sharedProps} /> <TabletMenubar {...sharedProps} />
) : ( ) : (
+93
View File
@@ -0,0 +1,93 @@
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 MenuIcon from '@mui/icons-material/Menu'
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
onOpenSidebar: () => void
}
export const MobileMenubar: React.FC<MobileMenubarProps> = ({
calendarRef,
currentDate,
onDateChange,
handleNavigation,
onOpenSidebar
}) => {
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">
<IconButton onClick={onOpenSidebar}>
<MenuIcon />
</IconButton>
<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 { IconButton } from '@linagora/twake-mui'
import ChevronLeftIcon from '@mui/icons-material/ChevronLeft'
import ChevronRightIcon from '@mui/icons-material/ChevronRight'
import MenuIcon from '@mui/icons-material/Menu' import MenuIcon from '@mui/icons-material/Menu'
import RefreshIcon from '@mui/icons-material/Refresh' import RefreshIcon from '@mui/icons-material/Refresh'
import TodayIcon from '@mui/icons-material/Today'
import { useI18n } from 'twake-i18n' import { useI18n } from 'twake-i18n'
import SearchBar from './EventSearchBar' import SearchBar from './EventSearchBar'
import { MainTitle } from './MainTitle' import { MainTitle } from './MainTitle'
import { SharedMenubarProps } from './Menubar' import { SharedMenubarProps } from './Menubar'
import { UserMenu } from './UserMenu' import { UserMenu } from './UserMenu'
import { SmallNavigationControls } from './components/SmallNavigationControls'
export function TabletMenubar({ export const TabletMenubar: React.FC<SharedMenubarProps> = ({
calendarRef, calendarRef,
currentView, currentView,
isIframe, isIframe,
@@ -26,7 +24,7 @@ export function TabletMenubar({
onUserMenuClose, onUserMenuClose,
onViewChange, onViewChange,
onDateChange onDateChange
}: SharedMenubarProps) { }: SharedMenubarProps) => {
const { t } = useI18n() const { t } = useI18n()
return ( return (
@@ -52,36 +50,7 @@ export function TabletMenubar({
)} )}
<div className="menu-items" style={{ marginLeft: 0 }}> <div className="menu-items" style={{ marginLeft: 0 }}>
<div className="navigation-controls"> <SmallNavigationControls onNavigate={onNavigate} />
<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>
</div> </div>
<div className="menu-items"> <div className="menu-items">
+4 -2
View File
@@ -25,6 +25,7 @@ export type UserMenuProps = {
onUserMenuOpen: (event: MouseEvent<HTMLElement>) => void onUserMenuOpen: (event: MouseEvent<HTMLElement>) => void
user: userData | null user: userData | null
isIframe?: boolean isIframe?: boolean
size?: 's' | 'm' | 'l'
} }
export function UserMenu({ export function UserMenu({
@@ -34,7 +35,8 @@ export function UserMenu({
onLogoutClick, onLogoutClick,
onUserMenuOpen, onUserMenuOpen,
user, user,
isIframe = false isIframe = false,
size = 'm'
}: UserMenuProps): JSX.Element { }: UserMenuProps): JSX.Element {
const { t } = useI18n() const { t } = useI18n()
const theme = useTheme() const theme = useTheme()
@@ -50,7 +52,7 @@ export function UserMenu({
title={isIframe ? t('menubar.settings') : t('menubar.userProfile')} title={isIframe ? t('menubar.settings') : t('menubar.userProfile')}
> >
{!isIframe ? ( {!isIframe ? (
<Avatar color={stringToGradient(displayName)} size="m"> <Avatar color={stringToGradient(displayName)} size={size}>
{getInitials(displayName)} {getInitials(displayName)}
</Avatar> </Avatar>
) : ( ) : (
@@ -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,64 @@
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'}
aria-pressed={isSelected}
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 ChevronRightIcon from '@mui/icons-material/ChevronRight'
import { useI18n } from 'twake-i18n' import { useI18n } from 'twake-i18n'
export function NavigationControls({ export const NavigationControls: React.FC<{
onNavigate
}: {
onNavigate: (action: 'today' | 'next' | 'prev') => void onNavigate: (action: 'today' | 'next' | 'prev') => void
}) { }> = ({ onNavigate }) => {
const { t } = useI18n() const { t } = useI18n()
return ( return (
<div className="navigation-controls"> <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", "logoAlt": "Calendar",
"settings": "Settings", "settings": "Settings",
"help": "Help", "help": "Help",
"logout": "Logout" "logout": "Logout",
"hideDatePicker": "Hide date picker",
"showDatePicker": "Show date picker"
}, },
"settings": { "settings": {
"title": "Settings", "title": "Settings",
@@ -365,6 +367,20 @@
"9": "October", "9": "October",
"10": "November", "10": "November",
"11": "December" "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": { "mobile": {
+19 -3
View File
@@ -232,8 +232,8 @@
}, },
"menubar": { "menubar": {
"today": "Aujourd'hui", "today": "Aujourd'hui",
"next": "Précédent", "next": "Suivant",
"prev": "Suivant", "prev": "Précédent",
"refresh": "Actualiser", "refresh": "Actualiser",
"viewSelector": "Sélectionner la vue", "viewSelector": "Sélectionner la vue",
"languageSelector": "Sélectionner la langue", "languageSelector": "Sélectionner la langue",
@@ -248,7 +248,9 @@
"settings": "Paramètres", "settings": "Paramètres",
"help": "Aide", "help": "Aide",
"logout": "Déconnexion", "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": { "settings": {
"title": "Paramètres", "title": "Paramètres",
@@ -366,6 +368,20 @@
"9": "Octobre", "9": "Octobre",
"10": "Novembre", "10": "Novembre",
"11": "Décembre" "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": { "mobile": {
+17 -1
View File
@@ -248,7 +248,9 @@
"settings": "Настройки", "settings": "Настройки",
"help": "Помощь", "help": "Помощь",
"logout": "Выйти", "logout": "Выйти",
"toggleSidebar": "Показать/скрыть боковую панель" "toggleSidebar": "Показать/скрыть боковую панель",
"hideDatePicker": "Скрыть выбор даты",
"showDatePicker": "Показать выбор даты"
}, },
"settings": { "settings": {
"title": "Настройки", "title": "Настройки",
@@ -366,6 +368,20 @@
"9": "Октябрь", "9": "Октябрь",
"10": "Ноябрь", "10": "Ноябрь",
"11": "Декабрь" "11": "Декабрь"
},
"short": {
"0": "Янв",
"1": "Фев",
"2": "Мар",
"3": "Апр",
"4": "Май",
"5": "Июн",
"6": "Июл",
"7": "Авг",
"8": "Сен",
"9": "Окт",
"10": "Ноя",
"11": "Дек"
} }
}, },
"mobile": { "mobile": {
+17 -1
View File
@@ -246,7 +246,9 @@
"settings": "Cài đặt", "settings": "Cài đặt",
"help": "Giúp đỡ", "help": "Giúp đỡ",
"logout": "Đăng xuất", "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": { "settings": {
"title": "Cài đặt", "title": "Cài đặt",
@@ -364,6 +366,20 @@
"9": "Tháng 10", "9": "Tháng 10",
"10": "Tháng 11", "10": "Tháng 11",
"11": "Tháng 12" "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": { "mobile": {