@helpwave/hightide
Version:
helpwave's component and theming library
1 lines • 65.4 kB
Source Map (JSON)
{"version":3,"sources":["../../../src/components/user-input/DateAndTimePicker.tsx","../../../src/hooks/useLanguage.tsx","../../../src/hooks/useLocalStorage.tsx","../../../src/hooks/useTranslation.ts","../../../src/util/noop.ts","../../../src/util/array.ts","../../../src/util/date.ts","../../../src/components/Button.tsx","../../../src/components/date/TimePicker.tsx","../../../src/components/date/DatePicker.tsx","../../../src/components/date/YearMonthPicker.tsx","../../../src/components/Expandable.tsx","../../../src/components/date/DayPicker.tsx"],"sourcesContent":["import type { ReactNode } from 'react'\nimport clsx from 'clsx'\nimport type { Languages } from '../../hooks/useLanguage'\nimport type { PropsForTranslation } from '../../hooks/useTranslation'\nimport { useTranslation } from '../../hooks/useTranslation'\nimport { noop } from '../../util/noop'\nimport { addDuration, subtractDuration } from '../../util/date'\nimport { SolidButton } from '../Button'\nimport type { TimePickerProps } from '../date/TimePicker'\nimport { TimePicker } from '../date/TimePicker'\nimport type { DatePickerProps } from '../date/DatePicker'\nimport { DatePicker } from '../date/DatePicker'\n\ntype TimeTranslation = {\n clear: string,\n change: string,\n year: string,\n month: string,\n day: string,\n january: string,\n february: string,\n march: string,\n april: string,\n may: string,\n june: string,\n july: string,\n august: string,\n september: string,\n october: string,\n november: string,\n december: string,\n}\n\nconst defaultTimeTranslation: Record<Languages, TimeTranslation> = {\n en: {\n clear: 'Clear',\n change: 'Change',\n year: 'Year',\n month: 'Month',\n day: 'Day',\n january: 'January',\n february: 'Febuary',\n march: 'March',\n april: 'April',\n may: 'May',\n june: 'June',\n july: 'July',\n august: 'August',\n september: 'September',\n october: 'October',\n november: 'November',\n december: 'December',\n },\n de: {\n clear: 'Entfernen',\n change: 'Ändern',\n year: 'Jahr',\n month: 'Monat',\n day: 'Tag',\n january: 'Januar',\n february: 'Febuar',\n march: 'März',\n april: 'April',\n may: 'Mai',\n june: 'Juni',\n july: 'Juli',\n august: 'August',\n september: 'September',\n october: 'October',\n november: 'November',\n december: 'December',\n }\n}\n\nexport type DateTimePickerMode = 'date' | 'time' | 'dateTime'\n\nexport type DateTimePickerProps = {\n mode?: DateTimePickerMode,\n value?: Date,\n start?: Date,\n end?: Date,\n onChange?: (date: Date) => void,\n onFinish?: (date: Date) => void,\n onRemove?: () => void,\n datePickerProps?: Omit<DatePickerProps, 'onChange' | 'value' | 'start' | 'end'>,\n timePickerProps?: Omit<TimePickerProps, 'onChange' | 'time' | 'maxHeight'>,\n}\n\n/**\n * A Component for picking a Date and Time\n */\nexport const DateTimePicker = ({\n overwriteTranslation,\n value = new Date(),\n start = subtractDuration(new Date(), { years: 50 }),\n end = addDuration(new Date(), { years: 50 }),\n mode = 'dateTime',\n onFinish = noop,\n onChange = noop,\n onRemove = noop,\n timePickerProps,\n datePickerProps,\n}: PropsForTranslation<TimeTranslation, DateTimePickerProps>) => {\n const translation = useTranslation(defaultTimeTranslation, overwriteTranslation)\n\n const useDate = mode === 'dateTime' || mode === 'date'\n const useTime = mode === 'dateTime' || mode === 'time'\n\n let dateDisplay: ReactNode\n let timeDisplay: ReactNode\n\n if (useDate) {\n dateDisplay = (\n <DatePicker\n {...datePickerProps}\n className=\"min-w-[320px] min-h-[250px]\"\n yearMonthPickerProps={{ maxHeight: 218 }}\n value={value}\n start={start}\n end={end}\n onChange={onChange}\n />\n )\n }\n if (useTime) {\n timeDisplay = (\n <TimePicker\n {...timePickerProps}\n className={clsx('h-full', { 'justify-between w-full': mode === 'time' })}\n maxHeight={250}\n time={value}\n onChange={onChange}\n />\n )\n }\n\n return (\n <div className=\"col w-fit\">\n <div className=\"row gap-x-4\">\n {dateDisplay}\n {timeDisplay}\n </div>\n <div className=\"row justify-end\">\n <div className=\"row gap-x-2 mt-1\">\n <SolidButton size=\"medium\" color=\"negative\" onClick={onRemove}>{translation.clear}</SolidButton>\n <SolidButton\n size=\"medium\"\n onClick={() => onFinish(value)}\n >\n {translation.change}\n </SolidButton>\n </div>\n </div>\n </div>\n )\n}\n","import type { Dispatch, PropsWithChildren, SetStateAction } from 'react'\nimport { createContext, useContext, useEffect, useState } from 'react'\nimport { useLocalStorage } from './useLocalStorage'\n\nexport const languages = ['en', 'de'] as const\nexport type Languages = typeof languages[number]\nexport const languagesLocalNames: Record<Languages, string> = {\n en: 'English',\n de: 'Deutsch',\n}\n\nexport const DEFAULT_LANGUAGE = 'en'\n\nexport type LanguageContextValue = {\n language: Languages,\n setLanguage: Dispatch<SetStateAction<Languages>>,\n}\n\nexport const LanguageContext = createContext<LanguageContextValue>({ language: DEFAULT_LANGUAGE, setLanguage: (v) => v })\n\nexport const useLanguage = () => useContext(LanguageContext)\n\nexport const useLocale = (overWriteLanguage?: Languages) => {\n const { language } = useLanguage()\n const mapping: Record<Languages, string> = {\n en: 'en-US',\n de: 'de-DE'\n }\n return mapping[overWriteLanguage ?? language]\n}\n\ntype ProvideLanguageProps = {\n initialLanguage?: Languages,\n}\n\nexport const ProvideLanguage = ({ initialLanguage, children }: PropsWithChildren<ProvideLanguageProps>) => {\n const [language, setLanguage] = useState<Languages>(initialLanguage ?? DEFAULT_LANGUAGE)\n const [storedLanguage, setStoredLanguage] = useLocalStorage<Languages>('language', initialLanguage ?? DEFAULT_LANGUAGE)\n\n useEffect(() => {\n if(language !== initialLanguage && initialLanguage){\n console.warn('LanguageProvider initial state changed: Prefer using useLanguages\\'s setLanguage instead')\n setLanguage(initialLanguage)\n }\n }, [initialLanguage]) // eslint-disable-line react-hooks/exhaustive-deps\n\n useEffect(() => {\n // TODO set locale of html tag here as well\n setStoredLanguage(language)\n }, [language, setStoredLanguage])\n\n useEffect(() => {\n if (storedLanguage !== null) {\n setLanguage(storedLanguage)\n return\n }\n\n const languagesToTestAgainst = Object.values(languages)\n\n const matchingBrowserLanguages = window.navigator.languages\n .map(language => languagesToTestAgainst.find((test) => language === test || language.split('-')[0] === test))\n .filter(entry => entry !== undefined)\n\n if (matchingBrowserLanguages.length === 0) return\n\n const firstMatch = matchingBrowserLanguages[0] as Languages\n setLanguage(firstMatch)\n }, []) // eslint-disable-line react-hooks/exhaustive-deps\n\n return (\n <LanguageContext.Provider value={{\n language,\n setLanguage\n }}>\n {children}\n </LanguageContext.Provider>\n )\n}\n","import type { Dispatch, SetStateAction } from 'react'\nimport { useCallback, useEffect, useState } from 'react'\nimport { LocalStorageService } from '../util/storage'\n\ntype SetValue<T> = Dispatch<SetStateAction<T>>\nexport const useLocalStorage = <T, >(key: string, initValue: T): [T, SetValue<T>] => {\n const get = useCallback((): T => {\n if (typeof window === 'undefined') {\n return initValue\n }\n const storageService = new LocalStorageService()\n const value = storageService.get<T>(key)\n return value || initValue\n }, [initValue, key])\n\n const [storedValue, setStoredValue] = useState<T>(get)\n\n const setValue: SetValue<T> = useCallback(value => {\n const newValue = value instanceof Function ? value(storedValue) : value\n const storageService = new LocalStorageService()\n storageService.set(key, value)\n\n setStoredValue(newValue)\n }, [storedValue, setStoredValue, key])\n\n useEffect(() => {\n setStoredValue(get())\n }, []) // eslint-disable-line react-hooks/exhaustive-deps\n\n return [storedValue, setValue]\n}","import type { Languages } from './useLanguage'\nimport { useLanguage } from './useLanguage'\n\nexport type Translation<T> = Record<Languages, T>\n\ntype OverwriteTranslationType<Translation extends Record<string, unknown>> = {\n language?: Languages,\n translation?: Partial<Record<Languages, Partial<Translation>>>,\n}\n\n/**\n * Adds the `language` prop to the component props.\n *\n * @param Translation the type of the translation object\n *\n * @param Props the type of the component props, defaults to `Record<string, never>`,\n * if you don't expect any other props other than `language` and get an\n * error when using your component (because it uses `forwardRef` etc.)\n * you can try out `Record<string, unknown>`, this might resolve your\n * problem as `SomeType & never` is still `never` but `SomeType & unknown`\n * is `SomeType` which means that adding back props (like `ref` etc.)\n * works properly\n */\nexport type PropsForTranslation<\n Translation extends Record<string, unknown>,\n Props = Record<string, never>\n> = Props & {\n overwriteTranslation?: OverwriteTranslationType<Translation>,\n};\n\nexport const useTranslation = <Translation extends Record<string, unknown>>(\n defaults: Record<Languages, Translation>,\n translationOverwrite: OverwriteTranslationType<Translation> = {}\n) : Translation => {\n const { language: languageProp, translation: overwrite } = translationOverwrite\n const { language: inferredLanguage } = useLanguage()\n const usedLanguage = languageProp ?? inferredLanguage\n let defaultValues: Translation = defaults[usedLanguage]\n if (overwrite && overwrite[usedLanguage]) {\n defaultValues = { ...defaultValues, ...overwrite[usedLanguage] }\n }\n return defaultValues\n}\n","export const noop = () => undefined\n","export const equalSizeGroups = <T >(array: T[], groupSize: number): T[][] => {\n if (groupSize <= 0) {\n console.warn(`group size should be greater than 0: groupSize = ${groupSize}`)\n return [[...array]]\n }\n\n const groups = []\n for (let i = 0; i < array.length; i += groupSize) {\n groups.push(array.slice(i, Math.min(i + groupSize, array.length)))\n }\n return groups\n}\n\n/**\n * @param start\n * @param end inclusive\n * @param allowEmptyRange Whether the range can be defined empty via end < start\n */\nexport const range = (start: number, end: number, allowEmptyRange: boolean = false): number[] => {\n if (end < start) {\n if (!allowEmptyRange) {\n console.warn(`range: end (${end}) < start (${start}) should be allowed explicitly, set allowEmptyRange to true`)\n }\n return []\n }\n return Array.from({ length: end - start + 1 }, (_, index) => index + start)\n}\n\n/** Finds the closest match\n * @param list The list of all possible matches\n * @param firstCloser Return whether item1 is closer than item2\n */\nexport const closestMatch = <T >(list: T[], firstCloser: (item1: T, item2: T) => boolean) => {\n return list.reduce((item1, item2) => {\n return firstCloser(item1, item2) ? item1 : item2\n })\n}\n\n/**\n * returns the item in middle of a list and its neighbours before and after\n * e.g. [1,2,3,4,5,6] for item = 1 would return [5,6,1,2,3]\n */\nexport const getNeighbours = <T >(list: T[], item: T, neighbourDistance: number = 2) => {\n const index = list.indexOf(item)\n const totalItems = neighbourDistance * 2 + 1\n if (list.length < totalItems) {\n console.warn('List is to short')\n return list\n }\n\n if (index === -1) {\n console.error('item not found in list')\n return list.splice(0, totalItems)\n }\n\n let start = index - neighbourDistance\n if (start < 0) {\n start += list.length\n }\n const end = (index + neighbourDistance + 1) % list.length\n\n const result: T[] = []\n let ignoreOnce = list.length === totalItems\n for (let i = start; i !== end || ignoreOnce; i = (i + 1) % list.length) {\n result.push(list[i]!)\n if (end === i && ignoreOnce) {\n ignoreOnce = false\n }\n }\n return result\n}\n\nexport const createLoopingListWithIndex = <T >(list: T[], startIndex: number = 0, length: number = 0, forwards: boolean = true) => {\n if (length < 0) {\n console.warn(`createLoopingList: length must be >= 0, given ${length}`)\n } else if (length === 0) {\n length = list.length\n }\n\n const returnList: [number, T][] = []\n\n if (forwards) {\n for (let i = startIndex; returnList.length < length; i = (i + 1) % list.length) {\n returnList.push([i, list[i]!])\n }\n } else {\n for (let i = startIndex; returnList.length < length; i = i === 0 ? i = list.length - 1 : i - 1) {\n returnList.push([i, list[i]!])\n }\n }\n\n return returnList\n}\n\nexport const createLoopingList = <T >(list: T[], startIndex: number = 0, length: number = 0, forwards: boolean = true) => {\n return createLoopingListWithIndex(list, startIndex, length, forwards).map(([_, item]) => item)\n}\n\nexport const ArrayUtil = {\n unique: <T>(list: T[]): T[] => {\n const seen = new Set<T>()\n return list.filter((item) => {\n if (seen.has(item)) {\n return false\n }\n seen.add(item)\n return true\n })\n },\n\n difference: <T>(list: T[], removeList: T[]): T[] => {\n const remove = new Set<T>(removeList)\n return list.filter((item) => !remove.has(item))\n }\n}\n","import { equalSizeGroups } from './array'\n\nexport const monthsList = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'] as const\nexport type Month = typeof monthsList[number]\n\nexport const weekDayList = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'] as const\nexport type WeekDay = typeof weekDayList[number]\n\nexport const formatDate = (date: Date) => {\n const year = date.getFullYear().toString().padStart(4, '0')\n const month = (date.getMonth() + 1).toString().padStart(2, '0')\n const day = (date.getDate()).toString().padStart(2, '0')\n return `${year}-${month}-${day}`\n}\n\nexport const formatDateTime = (date: Date) => {\n const dateString = formatDate(date)\n const hours = date.getHours().toString().padStart(2, '0')\n const minutes = date.getMinutes().toString().padStart(2, '0')\n return `${dateString}T${hours}:${minutes}`\n}\n\nexport const getDaysInMonth = (year: number, month: number): number => {\n const lastDayOfMonth = new Date(year, month + 1, 0)\n return lastDayOfMonth.getDate()\n}\n\nexport type Duration = {\n years?: number,\n months?: number,\n days?: number,\n hours?: number,\n minutes?: number,\n seconds?: number,\n milliseconds?: number,\n}\n\nexport const changeDuration = (date: Date, duration: Duration, isAdding?: boolean): Date => {\n const {\n years = 0,\n months = 0,\n days = 0,\n hours = 0,\n minutes = 0,\n seconds = 0,\n milliseconds = 0,\n } = duration\n\n // Check ranges\n if (years < 0) {\n console.error(`Range error years must be greater than 0: received ${years}`)\n return new Date(date)\n }\n if (months < 0 || months > 11) {\n console.error(`Range error month must be 0 <= month <= 11: received ${months}`)\n return new Date(date)\n }\n if (days < 0) {\n console.error(`Range error days must be greater than 0: received ${days}`)\n return new Date(date)\n }\n if (hours < 0 || hours > 23) {\n console.error(`Range error hours must be 0 <= hours <= 23: received ${hours}`)\n return new Date(date)\n }\n if (minutes < 0 || minutes > 59) {\n console.error(`Range error minutes must be 0 <= minutes <= 59: received ${minutes}`)\n return new Date(date)\n }\n if (seconds < 0 || seconds > 59) {\n console.error(`Range error seconds must be 0 <= seconds <= 59: received ${seconds}`)\n return new Date(date)\n }\n if (milliseconds < 0) {\n console.error(`Range error seconds must be greater than 0: received ${milliseconds}`)\n return new Date(date)\n }\n\n const multiplier = isAdding ? 1 : -1\n\n const newDate = new Date(date)\n\n newDate.setFullYear(newDate.getFullYear() + multiplier * years)\n\n newDate.setMonth(newDate.getMonth() + multiplier * months)\n\n newDate.setDate(newDate.getDate() + multiplier * days)\n\n newDate.setHours(newDate.getHours() + multiplier * hours)\n\n newDate.setMinutes(newDate.getMinutes() + multiplier * minutes)\n\n newDate.setSeconds(newDate.getSeconds() + multiplier * seconds)\n\n newDate.setMilliseconds(newDate.getMilliseconds() + multiplier * milliseconds)\n\n return newDate\n}\n\nexport const addDuration = (date: Date, duration: Duration): Date => {\n return changeDuration(date, duration, true)\n}\n\nexport const subtractDuration = (date: Date, duration: Duration): Date => {\n return changeDuration(date, duration, false)\n}\n\nexport const getBetweenDuration = (startDate: Date, endDate: Date): Duration => {\n const durationInMilliseconds = endDate.getTime() - startDate.getTime()\n\n const millisecondsInSecond = 1000\n const millisecondsInMinute = 60 * millisecondsInSecond\n const millisecondsInHour = 60 * millisecondsInMinute\n const millisecondsInDay = 24 * millisecondsInHour\n const millisecondsInMonth = 30 * millisecondsInDay // Rough estimation, can be adjusted\n\n const years = Math.floor(durationInMilliseconds / (365.25 * millisecondsInDay))\n const months = Math.floor(durationInMilliseconds / millisecondsInMonth)\n const days = Math.floor(durationInMilliseconds / millisecondsInDay)\n const hours = Math.floor((durationInMilliseconds % millisecondsInDay) / millisecondsInHour)\n const seconds = Math.floor((durationInMilliseconds % millisecondsInHour) / millisecondsInSecond)\n const milliseconds = durationInMilliseconds % millisecondsInSecond\n\n return {\n years,\n months,\n days,\n hours,\n seconds,\n milliseconds,\n }\n}\n\n/** Checks if a given date is in the range of two dates\n *\n * An undefined value for startDate or endDate means no bound for the start or end respectively\n */\nexport const isInTimeSpan = (value: Date, startDate?: Date, endDate?: Date): boolean => {\n if(startDate && endDate) {\n console.assert(startDate <= endDate)\n return startDate <= value && value <= endDate\n } else if (startDate) {\n return startDate <= value\n } else if(endDate) {\n return endDate >= value\n } else {\n return true\n }\n}\n\n/** Compare two dates on the year, month, day */\nexport const equalDate = (date1: Date, date2: Date) => {\n return date1.getFullYear() === date2.getFullYear()\n && date1.getMonth() === date2.getMonth()\n && date1.getDate() === date2.getDate()\n}\n\nexport const getWeeksForCalenderMonth = (date: Date, weekStart: WeekDay, weeks: number = 6) => {\n const month = date.getMonth()\n const year = date.getFullYear()\n\n const dayList: Date[] = []\n let currentDate = new Date(year, month, 1) // Start of month\n const weekStartIndex = weekDayList.indexOf(weekStart)\n\n // Move the current day to the week before\n while (currentDate.getDay() !== weekStartIndex) {\n currentDate = subtractDuration(currentDate, { days: 1 })\n }\n\n while (dayList.length < 7 * weeks) {\n const date = new Date(currentDate)\n date.setHours(date.getHours(), date.getMinutes()) // To make sure we are not overwriting the time\n dayList.push(date)\n currentDate = addDuration(currentDate, { days: 1 })\n }\n\n // weeks\n return equalSizeGroups(dayList, 7)\n}\n","import type { PropsWithChildren, ButtonHTMLAttributes, ReactNode } from 'react'\nimport clsx from 'clsx'\n\nexport type SolidButtonColor = 'primary' | 'secondary' | 'tertiary' | 'positive' | 'warning'| 'negative'\nexport type OutlineButtonColor = 'primary'\nexport type TextButtonColor = 'negative' | 'neutral'\n\ntype ButtonSizes = 'small' | 'medium' | 'large'\n\n/**\n * The shard properties between all button types\n */\nexport type ButtonProps = PropsWithChildren<{\n /**\n * @default 'medium'\n */\n size?: ButtonSizes,\n}> & ButtonHTMLAttributes<Element>\n\nexport const ButtonSizePaddings: Record<ButtonSizes, string> = {\n small: 'btn-sm',\n medium: 'btn-md',\n large: 'btn-lg'\n}\n\ntype ButtonWithIconsProps = ButtonProps & {\n startIcon?: ReactNode,\n endIcon?: ReactNode,\n}\n\nexport type SolidButtonProps = ButtonWithIconsProps & {\n color?: SolidButtonColor,\n}\n\nexport type OutlineButtonProps = ButtonWithIconsProps & {\n color?: OutlineButtonColor,\n}\n\nexport type TextButtonProps = ButtonWithIconsProps & {\n color?: TextButtonColor,\n}\n\n/**\n * A button with a solid background and different sizes\n */\nconst SolidButton = ({\n children,\n disabled = false,\n color = 'primary',\n size = 'medium',\n startIcon,\n endIcon,\n onClick,\n className,\n ...restProps\n }: SolidButtonProps) => {\n const colorClasses = {\n primary: 'bg-button-solid-primary-background text-button-solid-primary-text',\n secondary: 'bg-button-solid-secondary-background text-button-solid-secondary-text',\n tertiary: 'bg-button-solid-tertiary-background text-button-solid-tertiary-text',\n positive: 'bg-button-solid-positive-background text-button-solid-positive-text',\n warning: 'bg-button-solid-warning-background text-button-solid-warning-text',\n negative: 'bg-button-solid-negative-background text-button-solid-negative-text',\n }[color]\n\n const iconColorClasses = {\n primary: 'text-button-solid-primary-icon',\n secondary: 'text-button-solid-secondary-icon',\n tertiary: 'text-button-solid-tertiary-icon',\n positive: 'text-button-solid-positive-icon',\n warning: 'text-button-solid-warning-icon',\n negative: 'text-button-solid-negative-icon',\n }[color]\n\n return (\n <button\n onClick={disabled ? undefined : onClick}\n disabled={disabled || onClick === undefined}\n className={clsx(\n className,\n {\n 'text-disabled-text bg-disabled-background': disabled,\n [clsx(colorClasses, 'hover:brightness-90')]: !disabled\n },\n ButtonSizePaddings[size]\n )}\n {...restProps}\n >\n {startIcon && (\n <span\n className={clsx({\n [iconColorClasses]: !disabled,\n [`text-disabled-icon`]: disabled\n })}\n >\n {startIcon}\n </span>\n )}\n {children}\n {endIcon && (\n <span\n className={clsx({\n [iconColorClasses]: !disabled,\n [`text-disabled-icon`]: disabled\n })}\n >\n {endIcon}\n </span>\n )}\n </button>\n )\n}\n\n/**\n * A button with an outline border and different sizes\n */\nconst OutlineButton = ({\n children,\n disabled = false,\n color = 'primary',\n size = 'medium',\n startIcon,\n endIcon,\n onClick,\n className,\n ...restProps\n }: OutlineButtonProps) => {\n const colorClasses = {\n primary: 'bg-transparent border-2 border-button-outline-primary-text text-button-outline-primary-text',\n }[color]\n\n const iconColorClasses = {\n primary: 'text-button-outline-primary-icon',\n }[color]\n return (\n <button\n onClick={disabled ? undefined : onClick}\n disabled={disabled || onClick === undefined}\n className={clsx(\n className, {\n 'text-disabled-text border-disabled-outline)': disabled,\n [clsx(colorClasses, 'hover:brightness-80')]: !disabled,\n },\n ButtonSizePaddings[size]\n )}\n {...restProps}\n >\n {startIcon && (\n <span\n className={clsx({\n [iconColorClasses]: !disabled,\n [`text-disabled-icon`]: disabled\n })}\n >\n {startIcon}\n </span>\n )}\n {children}\n {endIcon && (\n <span\n className={clsx({\n [iconColorClasses]: !disabled,\n [`text-disabled-icon`]: disabled\n })}\n >\n {endIcon}\n </span>\n )}\n </button>\n )\n}\n\n/**\n * A text that is a button that can have different sizes\n */\nconst TextButton = ({\n children,\n disabled = false,\n color = 'neutral',\n size = 'medium',\n startIcon,\n endIcon,\n onClick,\n className,\n ...restProps\n }: TextButtonProps) => {\n const colorClasses = {\n negative: 'bg-transparent text-button-text-negative-text',\n neutral: 'bg-transparent text-button-text-neutral-text',\n }[color]\n\n const iconColorClasses = {\n negative: 'text-button-text-negative-icon',\n neutral: 'text-button-text-neutral-icon',\n }[color]\n return (\n <button\n onClick={disabled ? undefined : onClick}\n disabled={disabled || onClick === undefined}\n className={clsx(\n className, {\n 'text-disabled-text': disabled,\n [clsx(colorClasses, 'hover:bg-button-text-hover-background rounded-full')]: !disabled,\n },\n ButtonSizePaddings[size]\n )}\n {...restProps}\n >\n {startIcon && (\n <span\n className={clsx({\n [iconColorClasses]: !disabled,\n [`text-disabled-icon`]: disabled\n })}\n >\n {startIcon}\n </span>\n )}\n {children}\n {endIcon && (\n <span\n className={clsx({\n [iconColorClasses]: !disabled,\n [`text-disabled-icon`]: disabled\n })}\n >\n {endIcon}\n </span>\n )}\n </button>\n )\n}\n\n// TODO Icon button\n\nexport { SolidButton, OutlineButton, TextButton }\n","import { useEffect, useRef, useState } from 'react'\nimport { Scrollbars } from 'react-custom-scrollbars-2'\nimport { noop } from '../../util/noop'\nimport { closestMatch, range } from '../../util/array'\nimport clsx from 'clsx'\n\ntype MinuteIncrement = '1min' | '5min' | '10min' | '15min' | '30min'\n\nexport type TimePickerProps = {\n time?: Date,\n onChange?: (time: Date) => void,\n is24HourFormat?: boolean,\n minuteIncrement?: MinuteIncrement,\n maxHeight?: number,\n className?: string,\n}\n\nexport const TimePicker = ({\n time = new Date(),\n onChange = noop,\n is24HourFormat = true,\n minuteIncrement = '5min',\n maxHeight = 300,\n className = ''\n}: TimePickerProps) => {\n const minuteRef = useRef<HTMLButtonElement>(null)\n const hourRef = useRef<HTMLButtonElement>(null)\n\n const isPM = time.getHours() >= 11\n const hours = is24HourFormat ? range(0, 23) : range(1, 12)\n let minutes = range(0, 59)\n\n useEffect(() => {\n const scrollToItem = () => {\n if (minuteRef.current) {\n const container = minuteRef.current.parentElement!\n\n const hasOverflow = container.scrollHeight > maxHeight\n if (hasOverflow) {\n minuteRef.current.scrollIntoView({\n behavior: 'instant',\n block: 'nearest',\n })\n }\n }\n }\n scrollToItem()\n }, [minuteRef, minuteRef.current]) // eslint-disable-line\n\n useEffect(() => {\n const scrollToItem = () => {\n if (hourRef.current) {\n const container = hourRef.current.parentElement!\n\n const hasOverflow = container.scrollHeight > maxHeight\n if (hasOverflow) {\n hourRef.current.scrollIntoView({\n behavior: 'instant',\n block: 'nearest',\n })\n }\n }\n }\n scrollToItem()\n }, [hourRef, hourRef.current]) // eslint-disable-line\n\n switch (minuteIncrement) {\n case '5min':\n minutes = minutes.filter(value => value % 5 === 0)\n break\n case '10min':\n minutes = minutes.filter(value => value % 10 === 0)\n break\n case '15min':\n minutes = minutes.filter(value => value % 15 === 0)\n break\n case '30min':\n minutes = minutes.filter(value => value % 30 === 0)\n break\n }\n\n const closestMinute = closestMatch(minutes, (item1, item2) => Math.abs(item1 - time.getMinutes()) < Math.abs(item2 - time.getMinutes()))\n\n const style = (selected: boolean) => clsx('chip-full hover:brightness-90 hover:bg-primary hover:text-on-primary rounded-md mr-3',\n { 'bg-primary text-on-primary': selected, 'bg-white text-black': !selected })\n\n const onChangeWrapper = (transformer: (newDate: Date) => void) => {\n const newDate = new Date(time)\n transformer(newDate)\n onChange(newDate)\n }\n\n return (\n <div className={clsx('row gap-x-2 w-fit min-w-[150px] select-none', className)}>\n <Scrollbars autoHeight autoHeightMax={maxHeight} style={{ height: '100%' }}>\n <div className=\"col gap-y-1 h-full\">\n {hours.map(hour => {\n const currentHour = hour === time.getHours() - (!is24HourFormat && isPM ? 12 : 0)\n return (\n <button\n key={hour}\n ref={currentHour ? hourRef : undefined}\n className={style(currentHour)}\n onClick={() => onChangeWrapper(newDate => newDate.setHours(hour + (!is24HourFormat && isPM ? 12 : 0)))}\n >\n {hour.toString().padStart(2, '0')}\n </button>\n )\n })}\n </div>\n </Scrollbars>\n <Scrollbars autoHeight autoHeightMax={maxHeight} style={{ height: '100%' }}>\n <div className=\"col gap-y-1 h-full\">\n {minutes.map(minute => {\n const currentMinute = minute === closestMinute\n return (\n <button\n key={minute + minuteIncrement} // minute increment so that scroll works\n ref={currentMinute ? minuteRef : undefined}\n className={style(currentMinute)}\n onClick={() => onChangeWrapper(newDate => newDate.setMinutes(minute))}\n >\n {minute.toString().padStart(2, '0')}\n </button>\n )\n })}\n </div>\n </Scrollbars>\n {!is24HourFormat && (\n <div className=\"col gap-y-1\">\n <button\n className={style(!isPM)}\n onClick={() => onChangeWrapper(newDate => isPM && newDate.setHours(newDate.getHours() - 12))}\n >\n AM\n </button>\n <button\n className={style(isPM)}\n onClick={() => onChangeWrapper(newDate => !isPM && newDate.setHours(newDate.getHours() + 12))}\n >\n PM\n </button>\n </div>\n )}\n </div>\n )\n}\n\nexport const ControlledTimePicker = ({\n time,\n onChange = noop,\n ...props\n }: TimePickerProps) => {\n const [value, setValue] = useState(time)\n useEffect(() => setValue(time), [time])\n\n return (\n <TimePicker\n {...props}\n time={value}\n onChange={time1 => {\n setValue(time1)\n onChange(time1)\n }}\n />\n )\n}\n","import { useEffect, useState } from 'react'\nimport { ArrowDown, ArrowUp, ChevronDown } from 'lucide-react'\nimport type { Languages } from '../../hooks/useLanguage'\nimport type { PropsForTranslation } from '../../hooks/useTranslation'\nimport { useTranslation } from '../../hooks/useTranslation'\nimport { noop } from '../../util/noop'\nimport { addDuration, isInTimeSpan, subtractDuration } from '../../util/date'\nimport clsx from 'clsx'\nimport { SolidButton, TextButton } from '../Button'\nimport { useLocale } from '../../hooks/useLanguage'\nimport type { YearMonthPickerProps } from './YearMonthPicker'\nimport { YearMonthPicker } from './YearMonthPicker'\nimport type { DayPickerProps } from './DayPicker'\nimport { DayPicker } from './DayPicker'\n\ntype DatePickerTranslation = {\n today: string,\n}\n\nconst defaultDatePickerTranslation: Record<Languages, DatePickerTranslation> = {\n en: {\n today: 'Today',\n },\n de: {\n today: 'Heute',\n }\n}\n\ntype DisplayMode = 'yearMonth' | 'day'\n\nexport type DatePickerProps = {\n value?: Date,\n start?: Date,\n end?: Date,\n initialDisplay?: DisplayMode,\n onChange?: (date: Date) => void,\n dayPickerProps?: Omit<DayPickerProps, 'displayedMonth' | 'onChange' | 'selected'>,\n yearMonthPickerProps?: Omit<YearMonthPickerProps, 'displayedYearMonth' | 'onChange' | 'start' | 'end'>,\n className?: string,\n}\n\n/**\n * A Component for picking a date\n */\nexport const DatePicker = ({\n overwriteTranslation,\n value = new Date(),\n start = subtractDuration(new Date(), { years: 50 }),\n end = addDuration(new Date(), { years: 50 }),\n initialDisplay = 'day',\n onChange = noop,\n yearMonthPickerProps,\n dayPickerProps,\n className = ''\n }: PropsForTranslation<DatePickerTranslation, DatePickerProps>) => {\n const locale = useLocale()\n const translation = useTranslation(defaultDatePickerTranslation, overwriteTranslation)\n const [displayedMonth, setDisplayedMonth] = useState<Date>(value)\n const [displayMode, setDisplayMode] = useState<DisplayMode>(initialDisplay)\n\n useEffect(() => {\n setDisplayedMonth(value)\n }, [value])\n\n return (\n <div className={clsx('col gap-y-4', className)}>\n <div className=\"row items-center justify-between h-7\">\n <TextButton\n className={clsx('row gap-x-1 items-center cursor-pointer select-none', {\n 'text-disabled-text': displayMode !== 'day',\n })}\n onClick={() => setDisplayMode(displayMode === 'day' ? 'yearMonth' : 'day')}\n >\n {`${new Intl.DateTimeFormat(locale, { month: 'long' }).format(displayedMonth)} ${displayedMonth.getFullYear()}`}\n <ChevronDown size={16}/>\n </TextButton>\n {displayMode === 'day' && (\n <div className=\"row justify-end\">\n <SolidButton\n size=\"small\"\n color=\"primary\"\n disabled={!isInTimeSpan(subtractDuration(displayedMonth, { months: 1 }), start, end)}\n onClick={() => {\n setDisplayedMonth(subtractDuration(displayedMonth, { months: 1 }))\n }}\n >\n <ArrowUp size={20}/>\n </SolidButton>\n <SolidButton\n size=\"small\"\n color=\"primary\"\n disabled={!isInTimeSpan(addDuration(displayedMonth, { months: 1 }), start, end)}\n onClick={() => {\n setDisplayedMonth(addDuration(displayedMonth, { months: 1 }))\n }}\n >\n <ArrowDown size={20}/>\n </SolidButton>\n </div>\n )}\n </div>\n {displayMode === 'yearMonth' ? (\n <YearMonthPicker\n {...yearMonthPickerProps}\n displayedYearMonth={value}\n start={start}\n end={end}\n onChange={newDate => {\n setDisplayedMonth(newDate)\n setDisplayMode('day')\n }}\n />\n ) : (\n <div>\n <DayPicker\n {...dayPickerProps}\n displayedMonth={displayedMonth}\n start={start}\n end={end}\n selected={value}\n onChange={date => {\n onChange(date)\n }}\n />\n <div className=\"mt-2\">\n <TextButton\n onClick={() => {\n const newDate = new Date()\n newDate.setHours(value.getHours(), value.getMinutes())\n onChange(newDate)\n }}\n >\n {translation.today}\n </TextButton>\n </div>\n </div>\n )}\n </div>\n )\n}\n\n/**\n * Example for the Date Picker\n */\nexport const ControlledDatePicker = ({\n value = new Date(),\n onChange = noop,\n ...props\n }: DatePickerProps) => {\n const [date, setDate] = useState<Date>(value)\n\n useEffect(() => setDate(value), [value])\n\n return (\n <DatePicker\n {...props}\n value={date}\n onChange={date1 => {\n setDate(date1)\n onChange(date1)\n }}\n />\n )\n}\n","import { useEffect, useRef, useState } from 'react'\nimport { Scrollbars } from 'react-custom-scrollbars-2'\nimport { noop } from '../../util/noop'\nimport { equalSizeGroups, range } from '../../util/array'\nimport clsx from 'clsx'\nimport { Expandable } from '../Expandable'\nimport { addDuration, monthsList, subtractDuration } from '../../util/date'\nimport { useLocale } from '../../hooks/useLanguage'\n\nexport type YearMonthPickerProps = {\n displayedYearMonth?: Date,\n start?: Date,\n end?: Date,\n onChange?: (date: Date) => void,\n className?: string,\n maxHeight?: number,\n showValueOpen?: boolean,\n}\n\n// TODO use a dynamically loading infinite list here\nexport const YearMonthPicker = ({\n displayedYearMonth = new Date(),\n start = subtractDuration(new Date(), { years: 50 }),\n end = addDuration(new Date(), { years: 50 }),\n onChange = noop,\n className = '',\n maxHeight = 300,\n showValueOpen = true\n }: YearMonthPickerProps) => {\n const locale = useLocale()\n const ref = useRef<HTMLDivElement>(null)\n\n useEffect(() => {\n const scrollToItem = () => {\n if (ref.current) {\n ref.current.scrollIntoView({\n behavior: 'instant',\n block: 'center',\n })\n }\n }\n\n scrollToItem()\n }, [ref])\n\n if (end < start) {\n console.error(`startYear: (${start}) less than endYear: (${end})`)\n return null\n }\n\n const years = range(start.getFullYear(), end.getFullYear())\n\n return (\n <div className={clsx('col select-none', className)}>\n <Scrollbars autoHeight autoHeightMax={maxHeight} style={{ height: '100%' }}>\n <div className=\"col gap-y-1 mr-3\">\n {years.map(year => {\n const selectedYear = displayedYearMonth.getFullYear() === year\n return (\n <Expandable\n key={year}\n ref={(displayedYearMonth.getFullYear() ?? new Date().getFullYear()) === year ? ref : undefined}\n label={<span className={clsx({ 'text-primary font-bold': selectedYear })}>{year}</span>}\n initialExpansion={showValueOpen && selectedYear}\n >\n <div className=\"col gap-y-1 px-2 pb-2\">\n {equalSizeGroups([...monthsList], 3).map((monthList, index) => (\n <div key={index} className=\"row\">\n {monthList.map(month => {\n const monthIndex = monthsList.indexOf(month)\n const newDate = new Date(year, monthIndex)\n\n const selectedMonth = selectedYear && monthIndex === displayedYearMonth.getMonth()\n const firstOfMonth = new Date(year, monthIndex, 1)\n const lastOfMonth = new Date(year, monthIndex, 1)\n const isAfterStart = start === undefined || start <= addDuration(subtractDuration(lastOfMonth, { days: 1 }), { months: 1 })\n const isBeforeEnd = end === undefined || firstOfMonth <= end\n const isValid = isAfterStart && isBeforeEnd\n return (\n <button\n key={month}\n disabled={!isValid}\n className={clsx(\n 'chip hover:brightness-95 flex-1',\n {\n 'bg-gray-50 text-black': !selectedMonth && isValid,\n 'bg-primary text-on-primary': selectedMonth && isValid,\n 'bg-disabled-background text-disabled-text': !isValid\n }\n )}\n onClick={() => {\n onChange(newDate)\n }}\n >\n {new Intl.DateTimeFormat(locale, { month: 'short' }).format(newDate)}\n </button>\n )\n })}\n </div>\n ))}\n </div>\n </Expandable>\n )\n })}\n </div>\n </Scrollbars>\n </div>\n )\n}\n\nexport const ControlledYearMonthPicker = ({\n displayedYearMonth = new Date(),\n onChange = noop,\n ...props\n }: YearMonthPickerProps) => {\n const [yearMonth, setYearMonth] = useState<Date>(displayedYearMonth)\n\n useEffect(() => setYearMonth(displayedYearMonth), [displayedYearMonth])\n\n return (\n <YearMonthPicker\n displayedYearMonth={yearMonth}\n onChange={date => {\n setYearMonth(date)\n onChange(date)\n }}\n {...props}\n />\n )\n}\n","import type { PropsWithChildren, ReactNode } from 'react'\nimport { forwardRef, useState } from 'react'\nimport { ChevronDown, ChevronUp } from 'lucide-react'\nimport clsx from 'clsx'\n\ntype IconBuilder = (expanded: boolean) => ReactNode\n\nexport type ExpandableProps = PropsWithChildren<{\n label: ReactNode,\n icon?: IconBuilder,\n initialExpansion?: boolean,\n /**\n * Whether the expansion should only happen when the header is clicked or on the entire component\n */\n clickOnlyOnHeader?: boolean,\n className?: string,\n headerClassName?: string,\n}>\n\nconst DefaultIcon: IconBuilder = (expanded) => expanded ?\n (<ChevronUp size={16} className=\"min-w-[16px]\"/>)\n : (<ChevronDown size={16} className=\"min-w-[16px]\"/>)\n\n/**\n * A Component for showing and hiding content\n */\nexport const Expandable = forwardRef<HTMLDivElement, ExpandableProps>(({\n children,\n label,\n icon,\n initialExpansion = false,\n clickOnlyOnHeader = true,\n className = '',\n headerClassName = ''\n }, ref) => {\n const [isExpanded, setIsExpanded] = useState(initialExpansion)\n icon ??= DefaultIcon\n\n return (\n <div\n ref={ref}\n className={clsx('col bg-surface text-on-surface group rounded-lg shadow-sm', { 'cursor-pointer': !clickOnlyOnHeader }, className)}\n onClick={() => !clickOnlyOnHeader && setIsExpanded(!isExpanded)}\n >\n <button\n className={clsx('btn-md rounded-lg justify-between items-center bg-surface text-on-surface', { 'group-hover:brightness-95': !isExpanded }, headerClassName)}\n onClick={() => clickOnlyOnHeader && setIsExpanded(!isExpanded)}\n >\n {label}\n {icon(isExpanded)}\n </button>\n {isExpanded && (\n <div className=\"col\">\n {children}\n </div>\n )}\n </div>\n )\n})\n\nExpandable.displayName = 'Expandable'\n","import type { WeekDay } from '../../util/date'\nimport { isInTimeSpan } from '../../util/date'\nimport { equalDate, getWeeksForCalenderMonth } from '../../util/date'\nimport { noop } from '../../util/noop'\nimport clsx from 'clsx'\nimport { useLocale } from '../../hooks/useLanguage'\nimport { useEffect, useState } from 'react'\n\nexport type DayPickerProps = {\n displayedMonth: Date,\n selected?: Date,\n start?: Date,\n end?: Date,\n onChange?: (date: Date) => void,\n weekStart?: WeekDay,\n markToday?: boolean,\n className?: string,\n}\n\n/**\n * A component for selecting a day of a month\n */\nexport const DayPicker = ({\n displayedMonth,\n selected,\n start,\n end,\n onChange = noop,\n weekStart = 'monday',\n markToday = true,\n className = ''\n }: DayPickerProps) => {\n const locale = useLocale()\n const month = displayedMonth.getMonth()\n const weeks = getWeeksForCalenderMonth(displayedMonth, weekStart)\n\n return (\n <div className={clsx('col gap-y-1 min-w-[220px] select-none', className)}>\n <div className=\"row text-center\">\n {weeks[0]!.map((weekDay, index) => (\n <div key={index} className=\"flex-1 font-semibold\">\n {new Intl.DateTimeFormat(locale, { weekday: 'long' }).format(weekDay).substring(0, 2)}\n </div>\n ))}\n </div>\n {weeks.map((week, index) => (\n <div key={index} className=\"row text-center\">\n {week.map((date) => {\n const isSelected = !!selected && equalDate(selected, date)\n const isToday = equalDate(new Date(), date)\n const isSameMonth = date.getMonth() === month\n const isDayValid = isInTimeSpan(date, start, end)\n return (\n <button\n disabled={!isDayValid}\n key={date.getDate()}\n className={clsx(\n 'flex-1 rounded-full border-2 border-transparent shadow-sm',\n {\n 'text-gray-700 bg-gray-100': !isSameMonth && isDayValid,\n 'text-black bg-white': !isSelected && isSameMonth && isDayValid,\n 'text-on-primary bg-primary': isSelected,\n 'border-black': isToday && markToday,\n 'hover:brightness-90 hover:bg-primary hover:text-on-primary': isDayValid,\n 'text-disabled-text bg-disabled-background': !isDayValid\n }\n )}\n onClick={() => onChange(date)}\n >\n {date.getDate()}\n </button>\n )\n })}\n </div>\n ))}\n </div>\n )\n}\n\nexport const DayPickerControlled = ({ displayedMonth, onChange = noop, ...restProps }: DayPickerProps) => {\n const [date, setDate] = useState(displayedMonth)\n\n useEffect(() => setDate(displayedMonth), [displayedMonth])\n\n return (\n <DayPicker\n displayedMonth={date}\n onChange={newDate => {\n setDate(newDate)\n onChange(newDate)\n }}\n {...restProps}\n />\n )\n}\n"],"mappings":";AACA,OAAOA,WAAU;;;ACAjB,SAAS,eAAe,YAAY,aAAAC,YAAW,YAAAC,iBAAgB;;;ACA/D,SAAS,aAAa,WAAW,gBAAgB;;;ADqE7C;AA3DG,IAAM,mBAAmB;AAOzB,IAAM,kBAAkB,cAAoC,EAAE,UAAU,kBAAkB,aAAa,CAAC,MAAM,EAAE,CAAC;AAEjH,IAAM,cAAc,MAAM,WAAW,eAAe;AAEpD,IAAM,YAAY,CAAC,sBAAkC;AAC1D,QAAM,EAAE,SAAS,IAAI,YAAY;AACjC,QAAM,UAAqC;AAAA,IACzC,IAAI;AAAA,IACJ,IAAI;AAAA,EACN;AACA,SAAO,QAAQ,qBAAqB,QAAQ;AAC9C;;;AECO,IAAM,iBAAiB,CAC5B,UACA,uBAA8D,CAAC,MAC9C;AACjB,QAAM,EAAE,UAAU,cAAc,aAAa,UAAU,IAAI;AAC3D,QAAM,EAAE,UAAU,iBAAiB,IAAI,YAAY;AACnD,QAAM,eAAe,gBAAgB;AACrC,MAAI,gBAA6B,SAAS,YAAY;AACtD,MAAI,aAAa,UAAU,YAAY,GAAG;AACxC,oBAAgB,EAAE,GAAG,eAAe,GAAG,UAAU,YAAY,EAAE;AAAA,EACjE;AACA,SAAO;AACT;;;AC1CO,IAAM,OAAO,MAAM;;;ACAnB,IAAM,kBAAkB,CAAK,OAAY,cAA6B;AAC3E,MAAI,aAAa,GAAG;AAClB,YAAQ,KAAK,oDAAoD,SAAS,EAAE;AAC5E,WAAO,CAAC,CAAC,GAAG,KAAK,CAAC;AAAA,EACpB;AAEA,QAAM,SAAS,CAAC;AAChB,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,WAAW;AAChD,WAAO,KAAK,MAAM,MAAM,GAAG,KAAK,IAAI,IAAI,WAAW,MAAM,MAAM,CAAC,CAAC;AAAA,EACnE;AACA,SAAO;AACT;AAOO,IAAM,QAAQ,CAAC,OAAe,KAAa,kBAA2B,UAAoB;AAC/F,MAAI,MAAM,OAAO;AACf,QAAI,CAAC,iBAAiB;AACpB,cAAQ,KAAK,eAAe,GAAG,cAAc,KAAK,6DAA6D;AAAA,IACjH;AACA,WAAO,CAAC;AAAA,EACV;AACA,SAAO,MAAM,KAAK,EAAE,QAAQ,MAAM,QAAQ,EAAE,GAAG,CAAC,GAAG,UAAU,QAAQ,KAAK;AAC5E;AAMO,IAAM,eAAe,CAAK,MAAW,gBAAiD;AAC3F,SAAO,KAAK,OAAO,CAAC,OAAO,UAAU;AACnC,WAAO,YAAY,OAAO,KAAK,IAAI,QAAQ;AAAA,EAC7C,CAAC;AACH;;;AClCO,IAAM,aAAa,CAAC,WAAW,YAAY,SAAS,SAAS,OAAO,QAAQ,QAAQ,UAAU,aAAa,WAAW,YAAY,UAAU;AAG5I,IAAM,cAAc,CAAC,UAAU,UAAU,WAAW,aAAa,YAAY,UAAU,UAAU;AAgCjG,IAAM,iBAAiB,CAAC,MAAY,UAAoB,aAA6B;AAC1F,QAAM;AAAA,IACJ,QAAQ;AAA