1
0
Fork 0

Added Statistics calculation

Statistics now show calculated values
This commit is contained in:
Techognito 2025-09-04 17:30:00 +02:00
parent fe87374e47
commit fc0f69dacb
2147 changed files with 141321 additions and 39 deletions

View file

@ -0,0 +1,88 @@
import { Locale as DateFnsLocale } from 'date-fns/locale';
import { AdapterFormats, AdapterOptions, MuiPickersAdapter } from "../models/index.js";
import { AdapterDateFnsBase } from "../AdapterDateFnsBase/index.js";
declare module '@mui/x-date-pickers/models' {
interface PickerValidDateLookup {
'date-fns': Date;
}
}
/**
* Based on `@date-io/date-fns`
*
* MIT License
*
* Copyright (c) 2017 Dmitriy Kovalenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export declare class AdapterDateFns extends AdapterDateFnsBase<DateFnsLocale> implements MuiPickersAdapter<DateFnsLocale> {
constructor({
locale,
formats
}?: AdapterOptions<DateFnsLocale, never>);
parse: (value: string, format: string) => Date | null;
isValid: (value: Date | null) => value is Date;
format: (value: Date, formatKey: keyof AdapterFormats) => string;
formatByString: (value: Date, formatString: string) => string;
isEqual: (value: Date | null, comparing: Date | null) => boolean;
isSameYear: (value: Date, comparing: Date) => boolean;
isSameMonth: (value: Date, comparing: Date) => boolean;
isSameDay: (value: Date, comparing: Date) => boolean;
isSameHour: (value: Date, comparing: Date) => boolean;
isAfter: (value: Date, comparing: Date) => boolean;
isAfterYear: (value: Date, comparing: Date) => boolean;
isAfterDay: (value: Date, comparing: Date) => boolean;
isBefore: (value: Date, comparing: Date) => boolean;
isBeforeYear: (value: Date, comparing: Date) => boolean;
isBeforeDay: (value: Date, comparing: Date) => boolean;
isWithinRange: (value: Date, [start, end]: [Date, Date]) => boolean;
startOfYear: (value: Date) => Date;
startOfMonth: (value: Date) => Date;
startOfWeek: (value: Date) => Date;
startOfDay: (value: Date) => Date;
endOfYear: (value: Date) => Date;
endOfMonth: (value: Date) => Date;
endOfWeek: (value: Date) => Date;
endOfDay: (value: Date) => Date;
addYears: (value: Date, amount: number) => Date;
addMonths: (value: Date, amount: number) => Date;
addWeeks: (value: Date, amount: number) => Date;
addDays: (value: Date, amount: number) => Date;
addHours: (value: Date, amount: number) => Date;
addMinutes: (value: Date, amount: number) => Date;
addSeconds: (value: Date, amount: number) => Date;
getYear: (value: Date) => number;
getMonth: (value: Date) => number;
getDate: (value: Date) => number;
getHours: (value: Date) => number;
getMinutes: (value: Date) => number;
getSeconds: (value: Date) => number;
getMilliseconds: (value: Date) => number;
setYear: (value: Date, year: number) => Date;
setMonth: (value: Date, month: number) => Date;
setDate: (value: Date, date: number) => Date;
setHours: (value: Date, hours: number) => Date;
setMinutes: (value: Date, minutes: number) => Date;
setSeconds: (value: Date, seconds: number) => Date;
setMilliseconds: (value: Date, milliseconds: number) => Date;
getDaysInMonth: (value: Date) => number;
getWeekArray: (value: Date) => Date[][];
getWeekNumber: (value: Date) => number;
getYearRange: ([start, end]: [Date, Date]) => Date[];
}

View file

@ -0,0 +1,285 @@
import { addDays } from 'date-fns/addDays';
import { addSeconds } from 'date-fns/addSeconds';
import { addMinutes } from 'date-fns/addMinutes';
import { addHours } from 'date-fns/addHours';
import { addWeeks } from 'date-fns/addWeeks';
import { addMonths } from 'date-fns/addMonths';
import { addYears } from 'date-fns/addYears';
import { endOfDay } from 'date-fns/endOfDay';
import { endOfWeek } from 'date-fns/endOfWeek';
import { endOfYear } from 'date-fns/endOfYear';
import { format as dateFnsFormat, longFormatters } from 'date-fns/format';
import { getDate } from 'date-fns/getDate';
import { getDaysInMonth } from 'date-fns/getDaysInMonth';
import { getHours } from 'date-fns/getHours';
import { getMinutes } from 'date-fns/getMinutes';
import { getMonth } from 'date-fns/getMonth';
import { getSeconds } from 'date-fns/getSeconds';
import { getMilliseconds } from 'date-fns/getMilliseconds';
import { getWeek } from 'date-fns/getWeek';
import { getYear } from 'date-fns/getYear';
import { isAfter } from 'date-fns/isAfter';
import { isBefore } from 'date-fns/isBefore';
import { isEqual } from 'date-fns/isEqual';
import { isSameDay } from 'date-fns/isSameDay';
import { isSameYear } from 'date-fns/isSameYear';
import { isSameMonth } from 'date-fns/isSameMonth';
import { isSameHour } from 'date-fns/isSameHour';
import { isValid } from 'date-fns/isValid';
import { parse as dateFnsParse } from 'date-fns/parse';
import { setDate } from 'date-fns/setDate';
import { setHours } from 'date-fns/setHours';
import { setMinutes } from 'date-fns/setMinutes';
import { setMonth } from 'date-fns/setMonth';
import { setSeconds } from 'date-fns/setSeconds';
import { setMilliseconds } from 'date-fns/setMilliseconds';
import { setYear } from 'date-fns/setYear';
import { startOfDay } from 'date-fns/startOfDay';
import { startOfMonth } from 'date-fns/startOfMonth';
import { endOfMonth } from 'date-fns/endOfMonth';
import { startOfWeek } from 'date-fns/startOfWeek';
import { startOfYear } from 'date-fns/startOfYear';
import { isWithinInterval } from 'date-fns/isWithinInterval';
import { enUS } from 'date-fns/locale/en-US';
import { AdapterDateFnsBase } from "../AdapterDateFnsBase/index.js";
/**
* Based on `@date-io/date-fns`
*
* MIT License
*
* Copyright (c) 2017 Dmitriy Kovalenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export class AdapterDateFns extends AdapterDateFnsBase {
constructor({
locale,
formats
} = {}) {
/* v8 ignore start */
if (process.env.NODE_ENV !== 'production') {
if (typeof addDays !== 'function') {
throw new Error(['MUI: The `date-fns` package v2.x is not compatible with this adapter.', 'Please, install v3.x or v4.x of the package or use the `AdapterDateFnsV2` instead.'].join('\n'));
}
if (!longFormatters) {
throw new Error('MUI: The minimum supported `date-fns` package version compatible with this adapter is `3.2.x`.');
}
}
/* v8 ignore stop */
super({
locale: locale ?? enUS,
formats,
longFormatters
});
}
// TODO: explicit return types can be removed once there is only one date-fns version supported
parse = (value, format) => {
if (value === '') {
return null;
}
return dateFnsParse(value, format, new Date(), {
locale: this.locale
});
};
isValid = value => {
if (value == null) {
return false;
}
return isValid(value);
};
format = (value, formatKey) => {
return this.formatByString(value, this.formats[formatKey]);
};
formatByString = (value, formatString) => {
return dateFnsFormat(value, formatString, {
locale: this.locale
});
};
isEqual = (value, comparing) => {
if (value === null && comparing === null) {
return true;
}
if (value === null || comparing === null) {
return false;
}
return isEqual(value, comparing);
};
isSameYear = (value, comparing) => {
return isSameYear(value, comparing);
};
isSameMonth = (value, comparing) => {
return isSameMonth(value, comparing);
};
isSameDay = (value, comparing) => {
return isSameDay(value, comparing);
};
isSameHour = (value, comparing) => {
return isSameHour(value, comparing);
};
isAfter = (value, comparing) => {
return isAfter(value, comparing);
};
isAfterYear = (value, comparing) => {
return isAfter(value, endOfYear(comparing));
};
isAfterDay = (value, comparing) => {
return isAfter(value, endOfDay(comparing));
};
isBefore = (value, comparing) => {
return isBefore(value, comparing);
};
isBeforeYear = (value, comparing) => {
return isBefore(value, this.startOfYear(comparing));
};
isBeforeDay = (value, comparing) => {
return isBefore(value, this.startOfDay(comparing));
};
isWithinRange = (value, [start, end]) => {
return isWithinInterval(value, {
start,
end
});
};
startOfYear = value => {
return startOfYear(value);
};
startOfMonth = value => {
return startOfMonth(value);
};
startOfWeek = value => {
return startOfWeek(value, {
locale: this.locale
});
};
startOfDay = value => {
return startOfDay(value);
};
endOfYear = value => {
return endOfYear(value);
};
endOfMonth = value => {
return endOfMonth(value);
};
endOfWeek = value => {
return endOfWeek(value, {
locale: this.locale
});
};
endOfDay = value => {
return endOfDay(value);
};
addYears = (value, amount) => {
return addYears(value, amount);
};
addMonths = (value, amount) => {
return addMonths(value, amount);
};
addWeeks = (value, amount) => {
return addWeeks(value, amount);
};
addDays = (value, amount) => {
return addDays(value, amount);
};
addHours = (value, amount) => {
return addHours(value, amount);
};
addMinutes = (value, amount) => {
return addMinutes(value, amount);
};
addSeconds = (value, amount) => {
return addSeconds(value, amount);
};
getYear = value => {
return getYear(value);
};
getMonth = value => {
return getMonth(value);
};
getDate = value => {
return getDate(value);
};
getHours = value => {
return getHours(value);
};
getMinutes = value => {
return getMinutes(value);
};
getSeconds = value => {
return getSeconds(value);
};
getMilliseconds = value => {
return getMilliseconds(value);
};
setYear = (value, year) => {
return setYear(value, year);
};
setMonth = (value, month) => {
return setMonth(value, month);
};
setDate = (value, date) => {
return setDate(value, date);
};
setHours = (value, hours) => {
return setHours(value, hours);
};
setMinutes = (value, minutes) => {
return setMinutes(value, minutes);
};
setSeconds = (value, seconds) => {
return setSeconds(value, seconds);
};
setMilliseconds = (value, milliseconds) => {
return setMilliseconds(value, milliseconds);
};
getDaysInMonth = value => {
return getDaysInMonth(value);
};
getWeekArray = value => {
const start = this.startOfWeek(this.startOfMonth(value));
const end = this.endOfWeek(this.endOfMonth(value));
let count = 0;
let current = start;
const nestedWeeks = [];
while (this.isBefore(current, end)) {
const weekNumber = Math.floor(count / 7);
nestedWeeks[weekNumber] = nestedWeeks[weekNumber] || [];
nestedWeeks[weekNumber].push(current);
current = this.addDays(current, 1);
count += 1;
}
return nestedWeeks;
};
getWeekNumber = value => {
return getWeek(value, {
locale: this.locale
});
};
getYearRange = ([start, end]) => {
const startDate = this.startOfYear(start);
const endDate = this.endOfYear(end);
const years = [];
let current = startDate;
while (this.isBefore(current, endDate)) {
years.push(current);
current = this.addYears(current, 1);
}
return years;
};
}

View file

@ -0,0 +1 @@
export { AdapterDateFns } from "./AdapterDateFns.js";

View file

@ -0,0 +1 @@
export { AdapterDateFns } from "./AdapterDateFns.js";

View file

@ -0,0 +1,64 @@
import { MakeRequired } from '@mui/x-internals/types';
import { AdapterFormats, AdapterOptions, DateBuilderReturnType, FieldFormatTokenMap, MuiPickersAdapter } from "../models/index.js";
type DateFnsLocaleBase = {
formatLong: {
date: (...args: Array<any>) => any;
time: (...args: Array<any>) => any;
dateTime: (...args: Array<any>) => any;
};
code?: string;
};
type DateFnsAdapterBaseOptions<DateFnsLocale extends DateFnsLocaleBase> = MakeRequired<AdapterOptions<DateFnsLocale, never>, 'locale'> & {
longFormatters: Record<'p' | 'P', (token: string, formatLong: DateFnsLocaleBase['formatLong']) => string>;
lib?: string;
};
/**
* Based on `@date-io/date-fns`
*
* MIT License
*
* Copyright (c) 2017 Dmitriy Kovalenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export declare class AdapterDateFnsBase<DateFnsLocale extends DateFnsLocaleBase> implements Pick<MuiPickersAdapter<DateFnsLocale>, 'date' | 'getInvalidDate' | 'getTimezone' | 'setTimezone' | 'toJsDate' | 'getCurrentLocaleCode' | 'is12HourCycleInCurrentLocale' | 'expandFormat' | 'formatNumber'> {
isMUIAdapter: boolean;
isTimezoneCompatible: boolean;
lib: string;
locale: DateFnsLocale;
formats: AdapterFormats;
formatTokenMap: FieldFormatTokenMap;
escapedCharacters: {
start: string;
end: string;
};
longFormatters: DateFnsAdapterBaseOptions<DateFnsLocale>['longFormatters'];
constructor(props: DateFnsAdapterBaseOptions<DateFnsLocale>);
date: <T extends string | null | undefined>(value?: T) => DateBuilderReturnType<T>;
getInvalidDate: () => Date;
getTimezone: () => string;
setTimezone: (value: Date) => Date;
toJsDate: (value: Date) => Date;
getCurrentLocaleCode: () => string;
is12HourCycleInCurrentLocale: () => boolean;
expandFormat: (format: string) => string;
formatNumber: (numberToFormat: string) => string;
getDayOfWeek: (value: Date) => number;
}
export {};

View file

@ -0,0 +1,286 @@
import _extends from "@babel/runtime/helpers/esm/extends";
const formatTokenMap = {
// Year
y: {
sectionType: 'year',
contentType: 'digit',
maxLength: 4
},
yy: 'year',
yyy: {
sectionType: 'year',
contentType: 'digit',
maxLength: 4
},
yyyy: 'year',
// Month
M: {
sectionType: 'month',
contentType: 'digit',
maxLength: 2
},
MM: 'month',
MMMM: {
sectionType: 'month',
contentType: 'letter'
},
MMM: {
sectionType: 'month',
contentType: 'letter'
},
L: {
sectionType: 'month',
contentType: 'digit',
maxLength: 2
},
LL: 'month',
LLL: {
sectionType: 'month',
contentType: 'letter'
},
LLLL: {
sectionType: 'month',
contentType: 'letter'
},
// Day of the month
d: {
sectionType: 'day',
contentType: 'digit',
maxLength: 2
},
dd: 'day',
do: {
sectionType: 'day',
contentType: 'digit-with-letter'
},
// Day of the week
E: {
sectionType: 'weekDay',
contentType: 'letter'
},
EE: {
sectionType: 'weekDay',
contentType: 'letter'
},
EEE: {
sectionType: 'weekDay',
contentType: 'letter'
},
EEEE: {
sectionType: 'weekDay',
contentType: 'letter'
},
EEEEE: {
sectionType: 'weekDay',
contentType: 'letter'
},
i: {
sectionType: 'weekDay',
contentType: 'digit',
maxLength: 1
},
ii: 'weekDay',
iii: {
sectionType: 'weekDay',
contentType: 'letter'
},
iiii: {
sectionType: 'weekDay',
contentType: 'letter'
},
// eslint-disable-next-line id-denylist
e: {
sectionType: 'weekDay',
contentType: 'digit',
maxLength: 1
},
ee: 'weekDay',
eee: {
sectionType: 'weekDay',
contentType: 'letter'
},
eeee: {
sectionType: 'weekDay',
contentType: 'letter'
},
eeeee: {
sectionType: 'weekDay',
contentType: 'letter'
},
eeeeee: {
sectionType: 'weekDay',
contentType: 'letter'
},
c: {
sectionType: 'weekDay',
contentType: 'digit',
maxLength: 1
},
cc: 'weekDay',
ccc: {
sectionType: 'weekDay',
contentType: 'letter'
},
cccc: {
sectionType: 'weekDay',
contentType: 'letter'
},
ccccc: {
sectionType: 'weekDay',
contentType: 'letter'
},
cccccc: {
sectionType: 'weekDay',
contentType: 'letter'
},
// Meridiem
a: 'meridiem',
aa: 'meridiem',
aaa: 'meridiem',
// Hours
H: {
sectionType: 'hours',
contentType: 'digit',
maxLength: 2
},
HH: 'hours',
h: {
sectionType: 'hours',
contentType: 'digit',
maxLength: 2
},
hh: 'hours',
// Minutes
m: {
sectionType: 'minutes',
contentType: 'digit',
maxLength: 2
},
mm: 'minutes',
// Seconds
s: {
sectionType: 'seconds',
contentType: 'digit',
maxLength: 2
},
ss: 'seconds'
};
const defaultFormats = {
year: 'yyyy',
month: 'LLLL',
monthShort: 'MMM',
dayOfMonth: 'd',
dayOfMonthFull: 'do',
weekday: 'EEEE',
weekdayShort: 'EEEEEE',
hours24h: 'HH',
hours12h: 'hh',
meridiem: 'aa',
minutes: 'mm',
seconds: 'ss',
fullDate: 'PP',
keyboardDate: 'P',
shortDate: 'MMM d',
normalDate: 'd MMMM',
normalDateWithWeekday: 'EEE, MMM d',
fullTime12h: 'hh:mm aa',
fullTime24h: 'HH:mm',
keyboardDateTime12h: 'P hh:mm aa',
keyboardDateTime24h: 'P HH:mm'
};
/**
* Based on `@date-io/date-fns`
*
* MIT License
*
* Copyright (c) 2017 Dmitriy Kovalenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export class AdapterDateFnsBase {
isMUIAdapter = true;
isTimezoneCompatible = false;
formatTokenMap = (() => formatTokenMap)();
escapedCharacters = {
start: "'",
end: "'"
};
constructor(props) {
const {
locale,
formats,
longFormatters,
lib
} = props;
this.locale = locale;
this.formats = _extends({}, defaultFormats, formats);
this.longFormatters = longFormatters;
this.lib = lib || 'date-fns';
}
date = value => {
if (typeof value === 'undefined') {
return new Date();
}
if (value === null) {
return null;
}
return new Date(value);
};
getInvalidDate = () => new Date('Invalid Date');
getTimezone = () => {
return 'default';
};
setTimezone = value => {
return value;
};
toJsDate = value => {
return value;
};
getCurrentLocaleCode = () => {
// `code` is undefined only in `date-fns` types, but all locales have it
return this.locale.code;
};
// Note: date-fns input types are more lenient than this adapter, so we need to expose our more
// strict signature and delegate to the more lenient signature. Otherwise, we have downstream type errors upon usage.
is12HourCycleInCurrentLocale = () => {
return /a/.test(this.locale.formatLong.time({
width: 'short'
}));
};
expandFormat = format => {
const longFormatRegexp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
// @see https://github.com/date-fns/date-fns/blob/master/src/format/index.js#L31
return format.match(longFormatRegexp).map(token => {
const firstCharacter = token[0];
if (firstCharacter === 'p' || firstCharacter === 'P') {
const longFormatter = this.longFormatters[firstCharacter];
return longFormatter(token, this.locale.formatLong);
}
return token;
}).join('');
};
formatNumber = numberToFormat => {
return numberToFormat;
};
getDayOfWeek = value => {
return value.getDay() + 1;
};
}

View file

@ -0,0 +1 @@
export { AdapterDateFnsBase } from "./AdapterDateFnsBase.js";

View file

@ -0,0 +1 @@
export { AdapterDateFnsBase } from "./AdapterDateFnsBase.js";

View file

@ -0,0 +1,89 @@
import { Locale as DateFnsLocale } from 'date-fns-jalali/locale';
import { AdapterFormats, AdapterOptions, MuiPickersAdapter } from "../models/index.js";
import { AdapterDateFnsBase } from "../AdapterDateFnsBase/index.js";
declare module '@mui/x-date-pickers/models' {
interface PickerValidDateLookup {
'date-fns-jalali': Date;
}
}
/**
* Based on `@date-io/date-fns-jalali`
*
* MIT License
*
* Copyright (c) 2017 Dmitriy Kovalenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export declare class AdapterDateFnsJalali extends AdapterDateFnsBase<DateFnsLocale> implements MuiPickersAdapter<DateFnsLocale> {
constructor({
locale,
formats
}?: AdapterOptions<DateFnsLocale, never>);
parse: (value: string, format: string) => Date | null;
isValid: (value: Date | null) => value is Date;
format: (value: Date, formatKey: keyof AdapterFormats) => string;
formatByString: (value: Date, formatString: string) => string;
formatNumber: (numberToFormat: string) => string;
isEqual: (value: Date | null, comparing: Date | null) => boolean;
isSameYear: (value: Date, comparing: Date) => boolean;
isSameMonth: (value: Date, comparing: Date) => boolean;
isSameDay: (value: Date, comparing: Date) => boolean;
isSameHour: (value: Date, comparing: Date) => boolean;
isAfter: (value: Date, comparing: Date) => boolean;
isAfterYear: (value: Date, comparing: Date) => boolean;
isAfterDay: (value: Date, comparing: Date) => boolean;
isBefore: (value: Date, comparing: Date) => boolean;
isBeforeYear: (value: Date, comparing: Date) => boolean;
isBeforeDay: (value: Date, comparing: Date) => boolean;
isWithinRange: (value: Date, [start, end]: [Date, Date]) => boolean;
startOfYear: (value: Date) => Date;
startOfMonth: (value: Date) => Date;
startOfWeek: (value: Date) => Date;
startOfDay: (value: Date) => Date;
endOfYear: (value: Date) => Date;
endOfMonth: (value: Date) => Date;
endOfWeek: (value: Date) => Date;
endOfDay: (value: Date) => Date;
addYears: (value: Date, amount: number) => Date;
addMonths: (value: Date, amount: number) => Date;
addWeeks: (value: Date, amount: number) => Date;
addDays: (value: Date, amount: number) => Date;
addHours: (value: Date, amount: number) => Date;
addMinutes: (value: Date, amount: number) => Date;
addSeconds: (value: Date, amount: number) => Date;
getYear: (value: Date) => number;
getMonth: (value: Date) => number;
getDate: (value: Date) => number;
getHours: (value: Date) => number;
getMinutes: (value: Date) => number;
getSeconds: (value: Date) => number;
getMilliseconds: (value: Date) => number;
setYear: (value: Date, year: number) => Date;
setMonth: (value: Date, month: number) => Date;
setDate: (value: Date, date: number) => Date;
setHours: (value: Date, hours: number) => Date;
setMinutes: (value: Date, minutes: number) => Date;
setSeconds: (value: Date, seconds: number) => Date;
setMilliseconds: (value: Date, milliseconds: number) => Date;
getDaysInMonth: (value: Date) => number;
getWeekArray: (value: Date) => Date[][];
getWeekNumber: (date: Date) => number;
getYearRange: ([start, end]: [Date, Date]) => Date[];
}

View file

@ -0,0 +1,327 @@
import _extends from "@babel/runtime/helpers/esm/extends";
import { addSeconds } from 'date-fns-jalali/addSeconds';
import { addMinutes } from 'date-fns-jalali/addMinutes';
import { addHours } from 'date-fns-jalali/addHours';
import { addDays } from 'date-fns-jalali/addDays';
import { addWeeks } from 'date-fns-jalali/addWeeks';
import { addMonths } from 'date-fns-jalali/addMonths';
import { addYears } from 'date-fns-jalali/addYears';
import { endOfDay } from 'date-fns-jalali/endOfDay';
import { endOfWeek } from 'date-fns-jalali/endOfWeek';
import { endOfYear } from 'date-fns-jalali/endOfYear';
import { format as dateFnsFormat, longFormatters } from 'date-fns-jalali/format';
import { getHours } from 'date-fns-jalali/getHours';
import { getSeconds } from 'date-fns-jalali/getSeconds';
import { getMilliseconds } from 'date-fns-jalali/getMilliseconds';
import { getWeek } from 'date-fns-jalali/getWeek';
import { getYear } from 'date-fns-jalali/getYear';
import { getMonth } from 'date-fns-jalali/getMonth';
import { getDate } from 'date-fns-jalali/getDate';
import { getDaysInMonth } from 'date-fns-jalali/getDaysInMonth';
import { getMinutes } from 'date-fns-jalali/getMinutes';
import { isAfter } from 'date-fns-jalali/isAfter';
import { isBefore } from 'date-fns-jalali/isBefore';
import { isEqual } from 'date-fns-jalali/isEqual';
import { isSameDay } from 'date-fns-jalali/isSameDay';
import { isSameYear } from 'date-fns-jalali/isSameYear';
import { isSameMonth } from 'date-fns-jalali/isSameMonth';
import { isSameHour } from 'date-fns-jalali/isSameHour';
import { isValid } from 'date-fns-jalali/isValid';
import { parse as dateFnsParse } from 'date-fns-jalali/parse';
import { setDate } from 'date-fns-jalali/setDate';
import { setHours } from 'date-fns-jalali/setHours';
import { setMinutes } from 'date-fns-jalali/setMinutes';
import { setMonth } from 'date-fns-jalali/setMonth';
import { setSeconds } from 'date-fns-jalali/setSeconds';
import { setMilliseconds } from 'date-fns-jalali/setMilliseconds';
import { setYear } from 'date-fns-jalali/setYear';
import { startOfDay } from 'date-fns-jalali/startOfDay';
import { startOfMonth } from 'date-fns-jalali/startOfMonth';
import { endOfMonth } from 'date-fns-jalali/endOfMonth';
import { startOfWeek } from 'date-fns-jalali/startOfWeek';
import { startOfYear } from 'date-fns-jalali/startOfYear';
import { isWithinInterval } from 'date-fns-jalali/isWithinInterval';
import { faIR as defaultLocale } from 'date-fns-jalali/locale/fa-IR';
import { AdapterDateFnsBase } from "../AdapterDateFnsBase/index.js";
const defaultFormats = {
year: 'yyyy',
month: 'LLLL',
monthShort: 'MMM',
dayOfMonth: 'd',
dayOfMonthFull: 'do',
weekday: 'EEEE',
weekdayShort: 'EEEEEE',
hours24h: 'HH',
hours12h: 'hh',
meridiem: 'aa',
minutes: 'mm',
seconds: 'ss',
fullDate: 'PPP',
keyboardDate: 'P',
shortDate: 'd MMM',
normalDate: 'd MMMM',
normalDateWithWeekday: 'EEE, d MMMM',
fullTime12h: 'hh:mm aaa',
fullTime24h: 'HH:mm',
keyboardDateTime12h: 'P hh:mm aa',
keyboardDateTime24h: 'P HH:mm'
};
const NUMBER_SYMBOL_MAP = {
'1': '۱',
'2': '۲',
'3': '۳',
'4': '۴',
'5': '۵',
'6': '۶',
'7': '۷',
'8': '۸',
'9': '۹',
'0': '۰'
};
/**
* Based on `@date-io/date-fns-jalali`
*
* MIT License
*
* Copyright (c) 2017 Dmitriy Kovalenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export class AdapterDateFnsJalali extends AdapterDateFnsBase {
constructor({
locale,
formats
} = {}) {
/* v8 ignore start */
if (process.env.NODE_ENV !== 'production') {
if (typeof addDays !== 'function') {
throw new Error(['MUI: The `date-fns-jalali` package v2.x is not compatible with this adapter.', 'Please, install v3.x or v4.x of the package or use the `AdapterDateFnsJalaliV2` instead.'].join('\n'));
}
if (!longFormatters) {
throw new Error('MUI: The minimum supported `date-fns-jalali` package version compatible with this adapter is `3.2.x`.');
}
}
/* v8 ignore stop */
super({
locale: locale ?? defaultLocale,
// some formats are different in jalali adapter,
// this ensures that `AdapterDateFnsBase` formats are overridden
formats: _extends({}, defaultFormats, formats),
longFormatters,
lib: 'date-fns-jalali'
});
}
// TODO: explicit return types can be removed once there is only one date-fns version supported
parse = (value, format) => {
if (value === '') {
return null;
}
return dateFnsParse(value, format, new Date(), {
locale: this.locale
});
};
isValid = value => {
if (value == null) {
return false;
}
return isValid(value);
};
format = (value, formatKey) => {
return this.formatByString(value, this.formats[formatKey]);
};
formatByString = (value, formatString) => {
return dateFnsFormat(value, formatString, {
locale: this.locale
});
};
formatNumber = numberToFormat => {
return numberToFormat.replace(/\d/g, match => NUMBER_SYMBOL_MAP[match]).replace(/,/g, '،');
};
isEqual = (value, comparing) => {
if (value === null && comparing === null) {
return true;
}
if (value === null || comparing === null) {
return false;
}
return isEqual(value, comparing);
};
isSameYear = (value, comparing) => {
return isSameYear(value, comparing);
};
isSameMonth = (value, comparing) => {
return isSameMonth(value, comparing);
};
isSameDay = (value, comparing) => {
return isSameDay(value, comparing);
};
isSameHour = (value, comparing) => {
return isSameHour(value, comparing);
};
isAfter = (value, comparing) => {
return isAfter(value, comparing);
};
isAfterYear = (value, comparing) => {
return isAfter(value, this.endOfYear(comparing));
};
isAfterDay = (value, comparing) => {
return isAfter(value, this.endOfDay(comparing));
};
isBefore = (value, comparing) => {
return isBefore(value, comparing);
};
isBeforeYear = (value, comparing) => {
return isBefore(value, this.startOfYear(comparing));
};
isBeforeDay = (value, comparing) => {
return isBefore(value, this.startOfDay(comparing));
};
isWithinRange = (value, [start, end]) => {
return isWithinInterval(value, {
start,
end
});
};
startOfYear = value => {
return startOfYear(value);
};
startOfMonth = value => {
return startOfMonth(value);
};
startOfWeek = value => {
return startOfWeek(value, {
locale: this.locale
});
};
startOfDay = value => {
return startOfDay(value);
};
endOfYear = value => {
return endOfYear(value);
};
endOfMonth = value => {
return endOfMonth(value);
};
endOfWeek = value => {
return endOfWeek(value, {
locale: this.locale
});
};
endOfDay = value => {
return endOfDay(value);
};
addYears = (value, amount) => {
return addYears(value, amount);
};
addMonths = (value, amount) => {
return addMonths(value, amount);
};
addWeeks = (value, amount) => {
return addWeeks(value, amount);
};
addDays = (value, amount) => {
return addDays(value, amount);
};
addHours = (value, amount) => {
return addHours(value, amount);
};
addMinutes = (value, amount) => {
return addMinutes(value, amount);
};
addSeconds = (value, amount) => {
return addSeconds(value, amount);
};
getYear = value => {
return getYear(value);
};
getMonth = value => {
return getMonth(value);
};
getDate = value => {
return getDate(value);
};
getHours = value => {
return getHours(value);
};
getMinutes = value => {
return getMinutes(value);
};
getSeconds = value => {
return getSeconds(value);
};
getMilliseconds = value => {
return getMilliseconds(value);
};
setYear = (value, year) => {
return setYear(value, year);
};
setMonth = (value, month) => {
return setMonth(value, month);
};
setDate = (value, date) => {
return setDate(value, date);
};
setHours = (value, hours) => {
return setHours(value, hours);
};
setMinutes = (value, minutes) => {
return setMinutes(value, minutes);
};
setSeconds = (value, seconds) => {
return setSeconds(value, seconds);
};
setMilliseconds = (value, milliseconds) => {
return setMilliseconds(value, milliseconds);
};
getDaysInMonth = value => {
return getDaysInMonth(value);
};
getWeekArray = value => {
const start = this.startOfWeek(this.startOfMonth(value));
const end = this.endOfWeek(this.endOfMonth(value));
let count = 0;
let current = start;
const nestedWeeks = [];
while (this.isBefore(current, end)) {
const weekNumber = Math.floor(count / 7);
nestedWeeks[weekNumber] = nestedWeeks[weekNumber] || [];
nestedWeeks[weekNumber].push(current);
current = this.addDays(current, 1);
count += 1;
}
return nestedWeeks;
};
getWeekNumber = date => {
return getWeek(date, {
locale: this.locale
});
};
getYearRange = ([start, end]) => {
const startDate = this.startOfYear(start);
const endDate = this.endOfYear(end);
const years = [];
let current = startDate;
while (this.isBefore(current, endDate)) {
years.push(current);
current = this.addYears(current, 1);
}
return years;
};
}

View file

@ -0,0 +1 @@
export { AdapterDateFnsJalali } from "./AdapterDateFnsJalali.js";

View file

@ -0,0 +1 @@
export { AdapterDateFnsJalali } from "./AdapterDateFnsJalali.js";

View file

@ -0,0 +1,89 @@
import type { Locale as DateFnsLocale } from 'date-fns-jalali';
import { AdapterFormats, AdapterOptions, MuiPickersAdapter } from "../models/index.js";
import { AdapterDateFnsBase } from "../AdapterDateFnsBase/index.js";
declare module '@mui/x-date-pickers/models' {
interface PickerValidDateLookup {
'date-fns-jalali': Date;
}
}
/**
* Based on `@date-io/date-fns-jalali`
*
* MIT License
*
* Copyright (c) 2017 Dmitriy Kovalenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export declare class AdapterDateFnsJalali extends AdapterDateFnsBase<DateFnsLocale> implements MuiPickersAdapter<DateFnsLocale> {
constructor({
locale,
formats
}?: AdapterOptions<DateFnsLocale, never>);
parse: (value: string, format: string) => Date | null;
isValid: (value: Date | null) => value is Date;
format: (value: Date, formatKey: keyof AdapterFormats) => string;
formatByString: (value: Date, formatString: string) => string;
formatNumber: (numberToFormat: string) => string;
isEqual: (value: Date | null, comparing: Date | null) => boolean;
isSameYear: (value: Date, comparing: Date) => boolean;
isSameMonth: (value: Date, comparing: Date) => boolean;
isSameDay: (value: Date, comparing: Date) => boolean;
isSameHour: (value: Date, comparing: Date) => boolean;
isAfter: (value: Date, comparing: Date) => boolean;
isAfterYear: (value: Date, comparing: Date) => boolean;
isAfterDay: (value: Date, comparing: Date) => boolean;
isBefore: (value: Date, comparing: Date) => boolean;
isBeforeYear: (value: Date, comparing: Date) => boolean;
isBeforeDay: (value: Date, comparing: Date) => boolean;
isWithinRange: (value: Date, [start, end]: [Date, Date]) => boolean;
startOfYear: (value: Date) => Date;
startOfMonth: (value: Date) => Date;
startOfWeek: (value: Date) => Date;
startOfDay: (value: Date) => Date;
endOfYear: (value: Date) => Date;
endOfMonth: (value: Date) => Date;
endOfWeek: (value: Date) => Date;
endOfDay: (value: Date) => Date;
addYears: (value: Date, amount: number) => Date;
addMonths: (value: Date, amount: number) => Date;
addWeeks: (value: Date, amount: number) => Date;
addDays: (value: Date, amount: number) => Date;
addHours: (value: Date, amount: number) => Date;
addMinutes: (value: Date, amount: number) => Date;
addSeconds: (value: Date, amount: number) => Date;
getYear: (value: Date) => number;
getMonth: (value: Date) => number;
getDate: (value: Date) => number;
getHours: (value: Date) => number;
getMinutes: (value: Date) => number;
getSeconds: (value: Date) => number;
getMilliseconds: (value: Date) => number;
setYear: (value: Date, year: number) => Date;
setMonth: (value: Date, month: number) => Date;
setDate: (value: Date, date: number) => Date;
setHours: (value: Date, hours: number) => Date;
setMinutes: (value: Date, minutes: number) => Date;
setSeconds: (value: Date, seconds: number) => Date;
setMilliseconds: (value: Date, milliseconds: number) => Date;
getDaysInMonth: (value: Date) => number;
getWeekArray: (value: Date) => Date[][];
getWeekNumber: (date: Date) => number;
getYearRange: ([start, end]: [Date, Date]) => Date[];
}

View file

@ -0,0 +1,330 @@
import _extends from "@babel/runtime/helpers/esm/extends";
// date-fns-jalali@<3 has no exports field defined
// See https://github.com/date-fns/date-fns/issues/1781
/* eslint-disable import/extensions */
/* v8 ignore start */
// @ts-nocheck
import addSeconds from 'date-fns-jalali/addSeconds/index.js';
import addMinutes from 'date-fns-jalali/addMinutes/index.js';
import addHours from 'date-fns-jalali/addHours/index.js';
import addDays from 'date-fns-jalali/addDays/index.js';
import addWeeks from 'date-fns-jalali/addWeeks/index.js';
import addMonths from 'date-fns-jalali/addMonths/index.js';
import addYears from 'date-fns-jalali/addYears/index.js';
import endOfDay from 'date-fns-jalali/endOfDay/index.js';
import endOfWeek from 'date-fns-jalali/endOfWeek/index.js';
import endOfYear from 'date-fns-jalali/endOfYear/index.js';
import dateFnsFormat from 'date-fns-jalali/format/index.js';
import getHours from 'date-fns-jalali/getHours/index.js';
import getSeconds from 'date-fns-jalali/getSeconds/index.js';
import getMilliseconds from 'date-fns-jalali/getMilliseconds/index.js';
import getWeek from 'date-fns-jalali/getWeek/index.js';
import getYear from 'date-fns-jalali/getYear/index.js';
import getMonth from 'date-fns-jalali/getMonth/index.js';
import getDate from 'date-fns-jalali/getDate/index.js';
import getDaysInMonth from 'date-fns-jalali/getDaysInMonth/index.js';
import getMinutes from 'date-fns-jalali/getMinutes/index.js';
import isAfter from 'date-fns-jalali/isAfter/index.js';
import isBefore from 'date-fns-jalali/isBefore/index.js';
import isEqual from 'date-fns-jalali/isEqual/index.js';
import isSameDay from 'date-fns-jalali/isSameDay/index.js';
import isSameYear from 'date-fns-jalali/isSameYear/index.js';
import isSameMonth from 'date-fns-jalali/isSameMonth/index.js';
import isSameHour from 'date-fns-jalali/isSameHour/index.js';
import isValid from 'date-fns-jalali/isValid/index.js';
import dateFnsParse from 'date-fns-jalali/parse/index.js';
import setDate from 'date-fns-jalali/setDate/index.js';
import setHours from 'date-fns-jalali/setHours/index.js';
import setMinutes from 'date-fns-jalali/setMinutes/index.js';
import setMonth from 'date-fns-jalali/setMonth/index.js';
import setSeconds from 'date-fns-jalali/setSeconds/index.js';
import setMilliseconds from 'date-fns-jalali/setMilliseconds/index.js';
import setYear from 'date-fns-jalali/setYear/index.js';
import startOfDay from 'date-fns-jalali/startOfDay/index.js';
import startOfMonth from 'date-fns-jalali/startOfMonth/index.js';
import endOfMonth from 'date-fns-jalali/endOfMonth/index.js';
import startOfWeek from 'date-fns-jalali/startOfWeek/index.js';
import startOfYear from 'date-fns-jalali/startOfYear/index.js';
import isWithinInterval from 'date-fns-jalali/isWithinInterval/index.js';
import defaultLocale from 'date-fns-jalali/locale/fa-IR/index.js';
import longFormatters from 'date-fns-jalali/_lib/format/longFormatters/index.js';
/* v8 ignore end */
import { AdapterDateFnsBase } from "../AdapterDateFnsBase/index.js";
const defaultFormats = {
year: 'yyyy',
month: 'LLLL',
monthShort: 'MMM',
dayOfMonth: 'd',
dayOfMonthFull: 'do',
weekday: 'EEEE',
weekdayShort: 'EEEEEE',
hours24h: 'HH',
hours12h: 'hh',
meridiem: 'aa',
minutes: 'mm',
seconds: 'ss',
fullDate: 'PPP',
keyboardDate: 'P',
shortDate: 'd MMM',
normalDate: 'd MMMM',
normalDateWithWeekday: 'EEE, d MMMM',
fullTime12h: 'hh:mm aaa',
fullTime24h: 'HH:mm',
keyboardDateTime12h: 'P hh:mm aa',
keyboardDateTime24h: 'P HH:mm'
};
const NUMBER_SYMBOL_MAP = {
'1': '۱',
'2': '۲',
'3': '۳',
'4': '۴',
'5': '۵',
'6': '۶',
'7': '۷',
'8': '۸',
'9': '۹',
'0': '۰'
};
/**
* Based on `@date-io/date-fns-jalali`
*
* MIT License
*
* Copyright (c) 2017 Dmitriy Kovalenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export class AdapterDateFnsJalali extends AdapterDateFnsBase {
constructor({
locale,
formats
} = {}) {
/* v8 ignore start */
if (process.env.NODE_ENV !== 'production') {
if (typeof addDays !== 'function') {
throw new Error(['MUI: This adapter is only compatible with `date-fns-jalali` v2.x package versions.', 'Please, install v2.x of the package or use the `AdapterDateFnsJalali` instead.'].join('\n'));
}
}
/* v8 ignore stop */
super({
locale: locale ?? defaultLocale,
// some formats are different in jalali adapter,
// this ensures that `AdapterDateFnsBase` formats are overridden
formats: _extends({}, defaultFormats, formats),
longFormatters,
lib: 'date-fns-jalali'
});
}
parse = (value, format) => {
if (value === '') {
return null;
}
return dateFnsParse(value, format, new Date(), {
locale: this.locale
});
};
isValid = value => {
if (value == null) {
return false;
}
return isValid(value);
};
format = (value, formatKey) => {
return this.formatByString(value, this.formats[formatKey]);
};
formatByString = (value, formatString) => {
return dateFnsFormat(value, formatString, {
locale: this.locale
});
};
formatNumber = numberToFormat => {
return numberToFormat.replace(/\d/g, match => NUMBER_SYMBOL_MAP[match]).replace(/,/g, '،');
};
isEqual = (value, comparing) => {
if (value === null && comparing === null) {
return true;
}
if (value === null || comparing === null) {
return false;
}
return isEqual(value, comparing);
};
isSameYear = (value, comparing) => {
return isSameYear(value, comparing);
};
isSameMonth = (value, comparing) => {
return isSameMonth(value, comparing);
};
isSameDay = (value, comparing) => {
return isSameDay(value, comparing);
};
isSameHour = (value, comparing) => {
return isSameHour(value, comparing);
};
isAfter = (value, comparing) => {
return isAfter(value, comparing);
};
isAfterYear = (value, comparing) => {
return isAfter(value, this.endOfYear(comparing));
};
isAfterDay = (value, comparing) => {
return isAfter(value, this.endOfDay(comparing));
};
isBefore = (value, comparing) => {
return isBefore(value, comparing);
};
isBeforeYear = (value, comparing) => {
return isBefore(value, this.startOfYear(comparing));
};
isBeforeDay = (value, comparing) => {
return isBefore(value, this.startOfDay(comparing));
};
isWithinRange = (value, [start, end]) => {
return isWithinInterval(value, {
start,
end
});
};
startOfYear = value => {
return startOfYear(value);
};
startOfMonth = value => {
return startOfMonth(value);
};
startOfWeek = value => {
return startOfWeek(value, {
locale: this.locale
});
};
startOfDay = value => {
return startOfDay(value);
};
endOfYear = value => {
return endOfYear(value);
};
endOfMonth = value => {
return endOfMonth(value);
};
endOfWeek = value => {
return endOfWeek(value, {
locale: this.locale
});
};
endOfDay = value => {
return endOfDay(value);
};
addYears = (value, amount) => {
return addYears(value, amount);
};
addMonths = (value, amount) => {
return addMonths(value, amount);
};
addWeeks = (value, amount) => {
return addWeeks(value, amount);
};
addDays = (value, amount) => {
return addDays(value, amount);
};
addHours = (value, amount) => {
return addHours(value, amount);
};
addMinutes = (value, amount) => {
return addMinutes(value, amount);
};
addSeconds = (value, amount) => {
return addSeconds(value, amount);
};
getYear = value => {
return getYear(value);
};
getMonth = value => {
return getMonth(value);
};
getDate = value => {
return getDate(value);
};
getHours = value => {
return getHours(value);
};
getMinutes = value => {
return getMinutes(value);
};
getSeconds = value => {
return getSeconds(value);
};
getMilliseconds = value => {
return getMilliseconds(value);
};
setYear = (value, year) => {
return setYear(value, year);
};
setMonth = (value, month) => {
return setMonth(value, month);
};
setDate = (value, date) => {
return setDate(value, date);
};
setHours = (value, hours) => {
return setHours(value, hours);
};
setMinutes = (value, minutes) => {
return setMinutes(value, minutes);
};
setSeconds = (value, seconds) => {
return setSeconds(value, seconds);
};
setMilliseconds = (value, milliseconds) => {
return setMilliseconds(value, milliseconds);
};
getDaysInMonth = value => {
return getDaysInMonth(value);
};
getWeekArray = value => {
const start = this.startOfWeek(this.startOfMonth(value));
const end = this.endOfWeek(this.endOfMonth(value));
let count = 0;
let current = start;
const nestedWeeks = [];
while (this.isBefore(current, end)) {
const weekNumber = Math.floor(count / 7);
nestedWeeks[weekNumber] = nestedWeeks[weekNumber] || [];
nestedWeeks[weekNumber].push(current);
current = this.addDays(current, 1);
count += 1;
}
return nestedWeeks;
};
getWeekNumber = date => {
return getWeek(date, {
locale: this.locale
});
};
getYearRange = ([start, end]) => {
const startDate = this.startOfYear(start);
const endDate = this.endOfYear(end);
const years = [];
let current = startDate;
while (this.isBefore(current, endDate)) {
years.push(current);
current = this.addYears(current, 1);
}
return years;
};
}

View file

@ -0,0 +1 @@
export { AdapterDateFnsJalali } from "./AdapterDateFnsJalaliV2.js";

View file

@ -0,0 +1 @@
export { AdapterDateFnsJalali } from "./AdapterDateFnsJalaliV2.js";

View file

@ -0,0 +1,88 @@
import type { Locale as DateFnsLocale } from 'date-fns';
import { AdapterFormats, AdapterOptions, MuiPickersAdapter } from "../models/index.js";
import { AdapterDateFnsBase } from "../AdapterDateFnsBase/index.js";
declare module '@mui/x-date-pickers/models' {
interface PickerValidDateLookup {
'date-fns': Date;
}
}
/**
* Based on `@date-io/date-fns`
*
* MIT License
*
* Copyright (c) 2017 Dmitriy Kovalenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export declare class AdapterDateFns extends AdapterDateFnsBase<DateFnsLocale> implements MuiPickersAdapter<DateFnsLocale> {
constructor({
locale,
formats
}?: AdapterOptions<DateFnsLocale, never>);
parse: (value: string, format: string) => Date | null;
isValid: (value: Date | null) => value is Date;
format: (value: Date, formatKey: keyof AdapterFormats) => string;
formatByString: (value: Date, formatString: string) => string;
isEqual: (value: Date | null, comparing: Date | null) => boolean;
isSameYear: (value: Date, comparing: Date) => boolean;
isSameMonth: (value: Date, comparing: Date) => boolean;
isSameDay: (value: Date, comparing: Date) => boolean;
isSameHour: (value: Date, comparing: Date) => boolean;
isAfter: (value: Date, comparing: Date) => boolean;
isAfterYear: (value: Date, comparing: Date) => boolean;
isAfterDay: (value: Date, comparing: Date) => boolean;
isBefore: (value: Date, comparing: Date) => boolean;
isBeforeYear: (value: Date, comparing: Date) => boolean;
isBeforeDay: (value: Date, comparing: Date) => boolean;
isWithinRange: (value: Date, [start, end]: [Date, Date]) => boolean;
startOfYear: (value: Date) => Date;
startOfMonth: (value: Date) => Date;
startOfWeek: (value: Date) => Date;
startOfDay: (value: Date) => Date;
endOfYear: (value: Date) => Date;
endOfMonth: (value: Date) => Date;
endOfWeek: (value: Date) => Date;
endOfDay: (value: Date) => Date;
addYears: (value: Date, amount: number) => Date;
addMonths: (value: Date, amount: number) => Date;
addWeeks: (value: Date, amount: number) => Date;
addDays: (value: Date, amount: number) => Date;
addHours: (value: Date, amount: number) => Date;
addMinutes: (value: Date, amount: number) => Date;
addSeconds: (value: Date, amount: number) => Date;
getYear: (value: Date) => number;
getMonth: (value: Date) => number;
getDate: (value: Date) => number;
getHours: (value: Date) => number;
getMinutes: (value: Date) => number;
getSeconds: (value: Date) => number;
getMilliseconds: (value: Date) => number;
setYear: (value: Date, year: number) => Date;
setMonth: (value: Date, month: number) => Date;
setDate: (value: Date, date: number) => Date;
setHours: (value: Date, hours: number) => Date;
setMinutes: (value: Date, minutes: number) => Date;
setSeconds: (value: Date, seconds: number) => Date;
setMilliseconds: (value: Date, milliseconds: number) => Date;
getDaysInMonth: (value: Date) => number;
getWeekArray: (value: Date) => Date[][];
getWeekNumber: (value: Date) => number;
getYearRange: ([start, end]: [Date, Date]) => Date[];
}

View file

@ -0,0 +1,288 @@
// date-fns@<3 has no exports field defined
// See https://github.com/date-fns/date-fns/issues/1781
/* eslint-disable import/extensions */
/* v8 ignore start */
// @ts-nocheck
import addDays from 'date-fns/addDays/index.js';
import addSeconds from 'date-fns/addSeconds/index.js';
import addMinutes from 'date-fns/addMinutes/index.js';
import addHours from 'date-fns/addHours/index.js';
import addWeeks from 'date-fns/addWeeks/index.js';
import addMonths from 'date-fns/addMonths/index.js';
import addYears from 'date-fns/addYears/index.js';
import endOfDay from 'date-fns/endOfDay/index.js';
import endOfWeek from 'date-fns/endOfWeek/index.js';
import endOfYear from 'date-fns/endOfYear/index.js';
import dateFnsFormat from 'date-fns/format/index.js';
import getDate from 'date-fns/getDate/index.js';
import getDaysInMonth from 'date-fns/getDaysInMonth/index.js';
import getHours from 'date-fns/getHours/index.js';
import getMinutes from 'date-fns/getMinutes/index.js';
import getMonth from 'date-fns/getMonth/index.js';
import getSeconds from 'date-fns/getSeconds/index.js';
import getMilliseconds from 'date-fns/getMilliseconds/index.js';
import getWeek from 'date-fns/getWeek/index.js';
import getYear from 'date-fns/getYear/index.js';
import isAfter from 'date-fns/isAfter/index.js';
import isBefore from 'date-fns/isBefore/index.js';
import isEqual from 'date-fns/isEqual/index.js';
import isSameDay from 'date-fns/isSameDay/index.js';
import isSameYear from 'date-fns/isSameYear/index.js';
import isSameMonth from 'date-fns/isSameMonth/index.js';
import isSameHour from 'date-fns/isSameHour/index.js';
import isValid from 'date-fns/isValid/index.js';
import dateFnsParse from 'date-fns/parse/index.js';
import setDate from 'date-fns/setDate/index.js';
import setHours from 'date-fns/setHours/index.js';
import setMinutes from 'date-fns/setMinutes/index.js';
import setMonth from 'date-fns/setMonth/index.js';
import setSeconds from 'date-fns/setSeconds/index.js';
import setMilliseconds from 'date-fns/setMilliseconds/index.js';
import setYear from 'date-fns/setYear/index.js';
import startOfDay from 'date-fns/startOfDay/index.js';
import startOfMonth from 'date-fns/startOfMonth/index.js';
import endOfMonth from 'date-fns/endOfMonth/index.js';
import startOfWeek from 'date-fns/startOfWeek/index.js';
import startOfYear from 'date-fns/startOfYear/index.js';
import isWithinInterval from 'date-fns/isWithinInterval/index.js';
import defaultLocale from 'date-fns/locale/en-US/index.js';
import longFormatters from 'date-fns/_lib/format/longFormatters/index.js';
/* v8 ignore end */
import { AdapterDateFnsBase } from "../AdapterDateFnsBase/index.js";
/**
* Based on `@date-io/date-fns`
*
* MIT License
*
* Copyright (c) 2017 Dmitriy Kovalenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export class AdapterDateFns extends AdapterDateFnsBase {
constructor({
locale,
formats
} = {}) {
/* v8 ignore start */
if (process.env.NODE_ENV !== 'production') {
if (typeof addDays !== 'function') {
throw new Error(['MUI: This adapter is only compatible with `date-fns` v2.x package versions.', 'Please, install v2.x of the package or use the `AdapterDateFns` instead.'].join('\n'));
}
}
/* v8 ignore stop */
super({
locale: locale ?? defaultLocale,
formats,
longFormatters
});
}
parse = (value, format) => {
if (value === '') {
return null;
}
return dateFnsParse(value, format, new Date(), {
locale: this.locale
});
};
isValid = value => {
if (value == null) {
return false;
}
return isValid(value);
};
format = (value, formatKey) => {
return this.formatByString(value, this.formats[formatKey]);
};
formatByString = (value, formatString) => {
return dateFnsFormat(value, formatString, {
locale: this.locale
});
};
isEqual = (value, comparing) => {
if (value === null && comparing === null) {
return true;
}
if (value === null || comparing === null) {
return false;
}
return isEqual(value, comparing);
};
isSameYear = (value, comparing) => {
return isSameYear(value, comparing);
};
isSameMonth = (value, comparing) => {
return isSameMonth(value, comparing);
};
isSameDay = (value, comparing) => {
return isSameDay(value, comparing);
};
isSameHour = (value, comparing) => {
return isSameHour(value, comparing);
};
isAfter = (value, comparing) => {
return isAfter(value, comparing);
};
isAfterYear = (value, comparing) => {
return isAfter(value, endOfYear(comparing));
};
isAfterDay = (value, comparing) => {
return isAfter(value, endOfDay(comparing));
};
isBefore = (value, comparing) => {
return isBefore(value, comparing);
};
isBeforeYear = (value, comparing) => {
return isBefore(value, this.startOfYear(comparing));
};
isBeforeDay = (value, comparing) => {
return isBefore(value, this.startOfDay(comparing));
};
isWithinRange = (value, [start, end]) => {
return isWithinInterval(value, {
start,
end
});
};
startOfYear = value => {
return startOfYear(value);
};
startOfMonth = value => {
return startOfMonth(value);
};
startOfWeek = value => {
return startOfWeek(value, {
locale: this.locale
});
};
startOfDay = value => {
return startOfDay(value);
};
endOfYear = value => {
return endOfYear(value);
};
endOfMonth = value => {
return endOfMonth(value);
};
endOfWeek = value => {
return endOfWeek(value, {
locale: this.locale
});
};
endOfDay = value => {
return endOfDay(value);
};
addYears = (value, amount) => {
return addYears(value, amount);
};
addMonths = (value, amount) => {
return addMonths(value, amount);
};
addWeeks = (value, amount) => {
return addWeeks(value, amount);
};
addDays = (value, amount) => {
return addDays(value, amount);
};
addHours = (value, amount) => {
return addHours(value, amount);
};
addMinutes = (value, amount) => {
return addMinutes(value, amount);
};
addSeconds = (value, amount) => {
return addSeconds(value, amount);
};
getYear = value => {
return getYear(value);
};
getMonth = value => {
return getMonth(value);
};
getDate = value => {
return getDate(value);
};
getHours = value => {
return getHours(value);
};
getMinutes = value => {
return getMinutes(value);
};
getSeconds = value => {
return getSeconds(value);
};
getMilliseconds = value => {
return getMilliseconds(value);
};
setYear = (value, year) => {
return setYear(value, year);
};
setMonth = (value, month) => {
return setMonth(value, month);
};
setDate = (value, date) => {
return setDate(value, date);
};
setHours = (value, hours) => {
return setHours(value, hours);
};
setMinutes = (value, minutes) => {
return setMinutes(value, minutes);
};
setSeconds = (value, seconds) => {
return setSeconds(value, seconds);
};
setMilliseconds = (value, milliseconds) => {
return setMilliseconds(value, milliseconds);
};
getDaysInMonth = value => {
return getDaysInMonth(value);
};
getWeekArray = value => {
const start = this.startOfWeek(this.startOfMonth(value));
const end = this.endOfWeek(this.endOfMonth(value));
let count = 0;
let current = start;
const nestedWeeks = [];
while (this.isBefore(current, end)) {
const weekNumber = Math.floor(count / 7);
nestedWeeks[weekNumber] = nestedWeeks[weekNumber] || [];
nestedWeeks[weekNumber].push(current);
current = this.addDays(current, 1);
count += 1;
}
return nestedWeeks;
};
getWeekNumber = value => {
return getWeek(value, {
locale: this.locale
});
};
getYearRange = ([start, end]) => {
const startDate = this.startOfYear(start);
const endDate = this.endOfYear(end);
const years = [];
let current = startDate;
while (this.isBefore(current, endDate)) {
years.push(current);
current = this.addYears(current, 1);
}
return years;
};
}

View file

@ -0,0 +1 @@
export { AdapterDateFns } from "./AdapterDateFnsV2.js";

View file

@ -0,0 +1 @@
export { AdapterDateFns } from "./AdapterDateFnsV2.js";

View file

@ -0,0 +1,126 @@
import dayjs, { Dayjs } from 'dayjs';
import { FieldFormatTokenMap, MuiPickersAdapter, AdapterFormats, AdapterOptions, PickersTimezone, DateBuilderReturnType } from "../models/index.js";
declare module '@mui/x-date-pickers/models' {
interface PickerValidDateLookup {
dayjs: Dayjs;
}
}
/**
* Based on `@date-io/dayjs`
*
* MIT License
*
* Copyright (c) 2017 Dmitriy Kovalenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export declare class AdapterDayjs implements MuiPickersAdapter<string> {
isMUIAdapter: boolean;
isTimezoneCompatible: boolean;
lib: string;
locale?: string;
formats: AdapterFormats;
escapedCharacters: {
start: string;
end: string;
};
formatTokenMap: FieldFormatTokenMap;
constructor({
locale,
formats
}?: AdapterOptions<string, never>);
private setLocaleToValue;
private hasUTCPlugin;
private hasTimezonePlugin;
private isSame;
/**
* Replaces "default" by undefined and "system" by the system timezone before passing it to `dayjs`.
*/
private cleanTimezone;
private createSystemDate;
private createUTCDate;
private createTZDate;
private getLocaleFormats;
/**
* If the new day does not have the same offset as the old one (when switching to summer day time for example),
* Then dayjs will not automatically adjust the offset (moment does).
* We have to parse again the value to make sure the `fixOffset` method is applied.
* See https://github.com/iamkun/dayjs/blob/b3624de619d6e734cd0ffdbbd3502185041c1b60/src/plugin/timezone/index.js#L72
*/
private adjustOffset;
date: <T extends string | null | undefined>(value?: T, timezone?: PickersTimezone) => DateBuilderReturnType<T>;
getInvalidDate: () => dayjs.Dayjs;
getTimezone: (value: Dayjs) => string;
setTimezone: (value: Dayjs, timezone: PickersTimezone) => Dayjs;
toJsDate: (value: Dayjs) => Date;
parse: (value: string, format: string) => dayjs.Dayjs | null;
getCurrentLocaleCode: () => string;
is12HourCycleInCurrentLocale: () => boolean;
expandFormat: (format: string) => string;
isValid: (value: Dayjs | null) => value is Dayjs;
format: (value: Dayjs, formatKey: keyof AdapterFormats) => string;
formatByString: (value: Dayjs, formatString: string) => string;
formatNumber: (numberToFormat: string) => string;
isEqual: (value: Dayjs | null, comparing: Dayjs | null) => boolean;
isSameYear: (value: Dayjs, comparing: Dayjs) => boolean;
isSameMonth: (value: Dayjs, comparing: Dayjs) => boolean;
isSameDay: (value: Dayjs, comparing: Dayjs) => boolean;
isSameHour: (value: Dayjs, comparing: Dayjs) => boolean;
isAfter: (value: Dayjs, comparing: Dayjs) => boolean;
isAfterYear: (value: Dayjs, comparing: Dayjs) => boolean;
isAfterDay: (value: Dayjs, comparing: Dayjs) => boolean;
isBefore: (value: Dayjs, comparing: Dayjs) => boolean;
isBeforeYear: (value: Dayjs, comparing: Dayjs) => boolean;
isBeforeDay: (value: Dayjs, comparing: Dayjs) => boolean;
isWithinRange: (value: Dayjs, [start, end]: [Dayjs, Dayjs]) => boolean;
startOfYear: (value: Dayjs) => dayjs.Dayjs;
startOfMonth: (value: Dayjs) => dayjs.Dayjs;
startOfWeek: (value: Dayjs) => dayjs.Dayjs;
startOfDay: (value: Dayjs) => dayjs.Dayjs;
endOfYear: (value: Dayjs) => dayjs.Dayjs;
endOfMonth: (value: Dayjs) => dayjs.Dayjs;
endOfWeek: (value: Dayjs) => dayjs.Dayjs;
endOfDay: (value: Dayjs) => dayjs.Dayjs;
addYears: (value: Dayjs, amount: number) => dayjs.Dayjs;
addMonths: (value: Dayjs, amount: number) => dayjs.Dayjs;
addWeeks: (value: Dayjs, amount: number) => dayjs.Dayjs;
addDays: (value: Dayjs, amount: number) => dayjs.Dayjs;
addHours: (value: Dayjs, amount: number) => dayjs.Dayjs;
addMinutes: (value: Dayjs, amount: number) => dayjs.Dayjs;
addSeconds: (value: Dayjs, amount: number) => dayjs.Dayjs;
getYear: (value: Dayjs) => number;
getMonth: (value: Dayjs) => number;
getDate: (value: Dayjs) => number;
getHours: (value: Dayjs) => number;
getMinutes: (value: Dayjs) => number;
getSeconds: (value: Dayjs) => number;
getMilliseconds: (value: Dayjs) => number;
setYear: (value: Dayjs, year: number) => dayjs.Dayjs;
setMonth: (value: Dayjs, month: number) => dayjs.Dayjs;
setDate: (value: Dayjs, date: number) => dayjs.Dayjs;
setHours: (value: Dayjs, hours: number) => dayjs.Dayjs;
setMinutes: (value: Dayjs, minutes: number) => dayjs.Dayjs;
setSeconds: (value: Dayjs, seconds: number) => dayjs.Dayjs;
setMilliseconds: (value: Dayjs, milliseconds: number) => dayjs.Dayjs;
getDaysInMonth: (value: Dayjs) => number;
getWeekArray: (value: Dayjs) => dayjs.Dayjs[][];
getWeekNumber: (value: Dayjs) => number;
getDayOfWeek(value: Dayjs): number;
getYearRange: ([start, end]: [Dayjs, Dayjs]) => dayjs.Dayjs[];
}

View file

@ -0,0 +1,553 @@
import _extends from "@babel/runtime/helpers/esm/extends";
/* v8 ignore start */
import dayjs from 'dayjs';
// dayjs has no exports field defined
// See https://github.com/iamkun/dayjs/issues/2562
/* eslint-disable import/extensions */
import weekOfYearPlugin from 'dayjs/plugin/weekOfYear.js';
import customParseFormatPlugin from 'dayjs/plugin/customParseFormat.js';
import localizedFormatPlugin from 'dayjs/plugin/localizedFormat.js';
import isBetweenPlugin from 'dayjs/plugin/isBetween.js';
import advancedFormatPlugin from 'dayjs/plugin/advancedFormat.js';
/* v8 ignore stop */
/* eslint-enable import/extensions */
import { warnOnce } from '@mui/x-internals/warning';
dayjs.extend(localizedFormatPlugin);
dayjs.extend(weekOfYearPlugin);
dayjs.extend(isBetweenPlugin);
dayjs.extend(advancedFormatPlugin);
const formatTokenMap = {
// Year
YY: 'year',
YYYY: {
sectionType: 'year',
contentType: 'digit',
maxLength: 4
},
// Month
M: {
sectionType: 'month',
contentType: 'digit',
maxLength: 2
},
MM: 'month',
MMM: {
sectionType: 'month',
contentType: 'letter'
},
MMMM: {
sectionType: 'month',
contentType: 'letter'
},
// Day of the month
D: {
sectionType: 'day',
contentType: 'digit',
maxLength: 2
},
DD: 'day',
Do: {
sectionType: 'day',
contentType: 'digit-with-letter'
},
// Day of the week
d: {
sectionType: 'weekDay',
contentType: 'digit',
maxLength: 2
},
dd: {
sectionType: 'weekDay',
contentType: 'letter'
},
ddd: {
sectionType: 'weekDay',
contentType: 'letter'
},
dddd: {
sectionType: 'weekDay',
contentType: 'letter'
},
// Meridiem
A: 'meridiem',
a: 'meridiem',
// Hours
H: {
sectionType: 'hours',
contentType: 'digit',
maxLength: 2
},
HH: 'hours',
h: {
sectionType: 'hours',
contentType: 'digit',
maxLength: 2
},
hh: 'hours',
// Minutes
m: {
sectionType: 'minutes',
contentType: 'digit',
maxLength: 2
},
mm: 'minutes',
// Seconds
s: {
sectionType: 'seconds',
contentType: 'digit',
maxLength: 2
},
ss: 'seconds'
};
const defaultFormats = {
year: 'YYYY',
month: 'MMMM',
monthShort: 'MMM',
dayOfMonth: 'D',
dayOfMonthFull: 'Do',
weekday: 'dddd',
weekdayShort: 'dd',
hours24h: 'HH',
hours12h: 'hh',
meridiem: 'A',
minutes: 'mm',
seconds: 'ss',
fullDate: 'll',
keyboardDate: 'L',
shortDate: 'MMM D',
normalDate: 'D MMMM',
normalDateWithWeekday: 'ddd, MMM D',
fullTime12h: 'hh:mm A',
fullTime24h: 'HH:mm',
keyboardDateTime12h: 'L hh:mm A',
keyboardDateTime24h: 'L HH:mm'
};
const MISSING_UTC_PLUGIN = ['Missing UTC plugin', 'To be able to use UTC or timezones, you have to enable the `utc` plugin', 'Find more information on https://mui.com/x/react-date-pickers/timezone/#day-js-and-utc'].join('\n');
const MISSING_TIMEZONE_PLUGIN = ['Missing timezone plugin', 'To be able to use timezones, you have to enable both the `utc` and the `timezone` plugin', 'Find more information on https://mui.com/x/react-date-pickers/timezone/#day-js-and-timezone'].join('\n');
/**
* Based on `@date-io/dayjs`
*
* MIT License
*
* Copyright (c) 2017 Dmitriy Kovalenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export class AdapterDayjs {
isMUIAdapter = true;
isTimezoneCompatible = true;
lib = 'dayjs';
escapedCharacters = {
start: '[',
end: ']'
};
formatTokenMap = (() => formatTokenMap)();
constructor({
locale,
formats
} = {}) {
this.locale = locale;
this.formats = _extends({}, defaultFormats, formats);
// Moved plugins to the constructor to allow for users to use options on the library
// for reference: https://github.com/mui/mui-x/pull/11151
dayjs.extend(customParseFormatPlugin);
}
setLocaleToValue = value => {
const expectedLocale = this.getCurrentLocaleCode();
if (expectedLocale === value.locale()) {
return value;
}
return value.locale(expectedLocale);
};
hasUTCPlugin = () => typeof dayjs.utc !== 'undefined';
hasTimezonePlugin = () => typeof dayjs.tz !== 'undefined';
isSame = (value, comparing, comparisonTemplate) => {
const comparingInValueTimezone = this.setTimezone(comparing, this.getTimezone(value));
return value.format(comparisonTemplate) === comparingInValueTimezone.format(comparisonTemplate);
};
/**
* Replaces "default" by undefined and "system" by the system timezone before passing it to `dayjs`.
*/
cleanTimezone = timezone => {
switch (timezone) {
case 'default':
{
return undefined;
}
case 'system':
{
return dayjs.tz.guess();
}
default:
{
return timezone;
}
}
};
createSystemDate = value => {
let date;
if (this.hasUTCPlugin() && this.hasTimezonePlugin()) {
const timezone = dayjs.tz.guess();
if (timezone === 'UTC') {
date = dayjs(value);
} /* v8 ignore next 3 */else {
// We can't change the system timezone in the tests
date = dayjs.tz(value, timezone);
}
} else {
date = dayjs(value);
}
return this.setLocaleToValue(date);
};
createUTCDate = value => {
/* v8 ignore next 3 */
if (!this.hasUTCPlugin()) {
throw new Error(MISSING_UTC_PLUGIN);
}
return this.setLocaleToValue(dayjs.utc(value));
};
createTZDate = (value, timezone) => {
/* v8 ignore next 3 */
if (!this.hasUTCPlugin()) {
throw new Error(MISSING_UTC_PLUGIN);
}
/* v8 ignore next 3 */
if (!this.hasTimezonePlugin()) {
throw new Error(MISSING_TIMEZONE_PLUGIN);
}
const keepLocalTime = value !== undefined && !value.endsWith('Z');
return this.setLocaleToValue(dayjs(value).tz(this.cleanTimezone(timezone), keepLocalTime));
};
getLocaleFormats = () => {
const locales = dayjs.Ls;
const locale = this.locale || 'en';
let localeObject = locales[locale];
if (localeObject === undefined) {
/* v8 ignore start */
if (process.env.NODE_ENV !== 'production') {
warnOnce(['MUI X: Your locale has not been found.', 'Either the locale key is not a supported one. Locales supported by dayjs are available here: https://github.com/iamkun/dayjs/tree/dev/src/locale.', "Or you forget to import the locale from 'dayjs/locale/{localeUsed}'", 'fallback on English locale.']);
}
/* v8 ignore stop */
localeObject = locales.en;
}
return localeObject.formats;
};
/**
* If the new day does not have the same offset as the old one (when switching to summer day time for example),
* Then dayjs will not automatically adjust the offset (moment does).
* We have to parse again the value to make sure the `fixOffset` method is applied.
* See https://github.com/iamkun/dayjs/blob/b3624de619d6e734cd0ffdbbd3502185041c1b60/src/plugin/timezone/index.js#L72
*/
adjustOffset = value => {
if (!this.hasTimezonePlugin()) {
return value;
}
const timezone = this.getTimezone(value);
if (timezone !== 'UTC') {
const fixedValue = value.tz(this.cleanTimezone(timezone), true);
// TODO: Simplify the case when we raise the `dayjs` peer dep to 1.11.12 (https://github.com/iamkun/dayjs/releases/tag/v1.11.12)
/* v8 ignore next 3 */
// @ts-ignore
if (fixedValue.$offset === (value.$offset ?? 0)) {
return value;
}
// Change only what is needed to avoid creating a new object with unwanted data
// Especially important when used in an environment where utc or timezone dates are used only in some places
// Reference: https://github.com/mui/mui-x/issues/13290
// @ts-ignore
value.$offset = fixedValue.$offset;
}
return value;
};
date = (value, timezone = 'default') => {
if (value === null) {
return null;
}
if (timezone === 'UTC') {
return this.createUTCDate(value);
}
if (timezone === 'system' || timezone === 'default' && !this.hasTimezonePlugin()) {
return this.createSystemDate(value);
}
return this.createTZDate(value, timezone);
};
getInvalidDate = () => dayjs(new Date('Invalid date'));
getTimezone = value => {
if (this.hasTimezonePlugin()) {
// @ts-ignore
const zone = value.$x?.$timezone;
if (zone) {
return zone;
}
}
if (this.hasUTCPlugin() && value.isUTC()) {
return 'UTC';
}
return 'system';
};
setTimezone = (value, timezone) => {
if (this.getTimezone(value) === timezone) {
return value;
}
if (timezone === 'UTC') {
/* v8 ignore next 3 */
if (!this.hasUTCPlugin()) {
throw new Error(MISSING_UTC_PLUGIN);
}
return value.utc();
}
// We know that we have the UTC plugin.
// Otherwise, the value timezone would always equal "system".
// And it would be caught by the first "if" of this method.
if (timezone === 'system') {
return value.local();
}
if (!this.hasTimezonePlugin()) {
if (timezone === 'default') {
return value;
}
/* v8 ignore next */
throw new Error(MISSING_TIMEZONE_PLUGIN);
}
return this.setLocaleToValue(dayjs.tz(value, this.cleanTimezone(timezone)));
};
toJsDate = value => {
return value.toDate();
};
parse = (value, format) => {
if (value === '') {
return null;
}
return dayjs(value, format, this.locale, true);
};
getCurrentLocaleCode = () => {
return this.locale || 'en';
};
is12HourCycleInCurrentLocale = () => {
/* v8 ignore next */
return /A|a/.test(this.getLocaleFormats().LT || '');
};
expandFormat = format => {
const localeFormats = this.getLocaleFormats();
// @see https://github.com/iamkun/dayjs/blob/dev/src/plugin/localizedFormat/index.js
const t = formatBis => formatBis.replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g, (_, a, b) => a || b.slice(1));
return format.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g, (_, a, b) => {
const B = b && b.toUpperCase();
return a || localeFormats[b] || t(localeFormats[B]);
});
};
isValid = value => {
if (value == null) {
return false;
}
return value.isValid();
};
format = (value, formatKey) => {
return this.formatByString(value, this.formats[formatKey]);
};
formatByString = (value, formatString) => {
return this.setLocaleToValue(value).format(formatString);
};
formatNumber = numberToFormat => {
return numberToFormat;
};
isEqual = (value, comparing) => {
if (value === null && comparing === null) {
return true;
}
if (value === null || comparing === null) {
return false;
}
return value.toDate().getTime() === comparing.toDate().getTime();
};
isSameYear = (value, comparing) => {
return this.isSame(value, comparing, 'YYYY');
};
isSameMonth = (value, comparing) => {
return this.isSame(value, comparing, 'YYYY-MM');
};
isSameDay = (value, comparing) => {
return this.isSame(value, comparing, 'YYYY-MM-DD');
};
isSameHour = (value, comparing) => {
return value.isSame(comparing, 'hour');
};
isAfter = (value, comparing) => {
return value > comparing;
};
isAfterYear = (value, comparing) => {
if (!this.hasUTCPlugin()) {
return value.isAfter(comparing, 'year');
}
return !this.isSameYear(value, comparing) && value.utc() > comparing.utc();
};
isAfterDay = (value, comparing) => {
if (!this.hasUTCPlugin()) {
return value.isAfter(comparing, 'day');
}
return !this.isSameDay(value, comparing) && value.utc() > comparing.utc();
};
isBefore = (value, comparing) => {
return value < comparing;
};
isBeforeYear = (value, comparing) => {
if (!this.hasUTCPlugin()) {
return value.isBefore(comparing, 'year');
}
return !this.isSameYear(value, comparing) && value.utc() < comparing.utc();
};
isBeforeDay = (value, comparing) => {
if (!this.hasUTCPlugin()) {
return value.isBefore(comparing, 'day');
}
return !this.isSameDay(value, comparing) && value.utc() < comparing.utc();
};
isWithinRange = (value, [start, end]) => {
return value >= start && value <= end;
};
startOfYear = value => {
return this.adjustOffset(value.startOf('year'));
};
startOfMonth = value => {
return this.adjustOffset(value.startOf('month'));
};
startOfWeek = value => {
return this.adjustOffset(this.setLocaleToValue(value).startOf('week'));
};
startOfDay = value => {
return this.adjustOffset(value.startOf('day'));
};
endOfYear = value => {
return this.adjustOffset(value.endOf('year'));
};
endOfMonth = value => {
return this.adjustOffset(value.endOf('month'));
};
endOfWeek = value => {
return this.adjustOffset(this.setLocaleToValue(value).endOf('week'));
};
endOfDay = value => {
return this.adjustOffset(value.endOf('day'));
};
addYears = (value, amount) => {
return this.adjustOffset(value.add(amount, 'year'));
};
addMonths = (value, amount) => {
return this.adjustOffset(value.add(amount, 'month'));
};
addWeeks = (value, amount) => {
return this.adjustOffset(value.add(amount, 'week'));
};
addDays = (value, amount) => {
return this.adjustOffset(value.add(amount, 'day'));
};
addHours = (value, amount) => {
return this.adjustOffset(value.add(amount, 'hour'));
};
addMinutes = (value, amount) => {
return this.adjustOffset(value.add(amount, 'minute'));
};
addSeconds = (value, amount) => {
return this.adjustOffset(value.add(amount, 'second'));
};
getYear = value => {
return value.year();
};
getMonth = value => {
return value.month();
};
getDate = value => {
return value.date();
};
getHours = value => {
return value.hour();
};
getMinutes = value => {
return value.minute();
};
getSeconds = value => {
return value.second();
};
getMilliseconds = value => {
return value.millisecond();
};
setYear = (value, year) => {
return this.adjustOffset(value.set('year', year));
};
setMonth = (value, month) => {
return this.adjustOffset(value.set('month', month));
};
setDate = (value, date) => {
return this.adjustOffset(value.set('date', date));
};
setHours = (value, hours) => {
return this.adjustOffset(value.set('hour', hours));
};
setMinutes = (value, minutes) => {
return this.adjustOffset(value.set('minute', minutes));
};
setSeconds = (value, seconds) => {
return this.adjustOffset(value.set('second', seconds));
};
setMilliseconds = (value, milliseconds) => {
return this.adjustOffset(value.set('millisecond', milliseconds));
};
getDaysInMonth = value => {
return value.daysInMonth();
};
getWeekArray = value => {
const start = this.startOfWeek(this.startOfMonth(value));
const end = this.endOfWeek(this.endOfMonth(value));
let count = 0;
let current = start;
const nestedWeeks = [];
while (current < end) {
const weekNumber = Math.floor(count / 7);
nestedWeeks[weekNumber] = nestedWeeks[weekNumber] || [];
nestedWeeks[weekNumber].push(current);
current = this.addDays(current, 1);
count += 1;
}
return nestedWeeks;
};
getWeekNumber = value => {
return value.week();
};
getDayOfWeek(value) {
return value.day() + 1;
}
getYearRange = ([start, end]) => {
const startDate = this.startOfYear(start);
const endDate = this.endOfYear(end);
const years = [];
let current = startDate;
while (this.isBefore(current, endDate)) {
years.push(current);
current = this.addYears(current, 1);
}
return years;
};
}

View file

@ -0,0 +1 @@
export { AdapterDayjs } from "./AdapterDayjs.js";

View file

@ -0,0 +1 @@
export { AdapterDayjs } from "./AdapterDayjs.js";

View file

@ -0,0 +1,108 @@
import { DateTime } from 'luxon';
import { AdapterFormats, AdapterOptions, DateBuilderReturnType, FieldFormatTokenMap, MuiPickersAdapter, PickersTimezone } from "../models/index.js";
declare module '@mui/x-date-pickers/models' {
interface PickerValidDateLookup {
luxon: DateTime;
}
}
/**
* Based on `@date-io/luxon`
*
* MIT License
*
* Copyright (c) 2017 Dmitriy Kovalenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export declare class AdapterLuxon implements MuiPickersAdapter<string> {
isMUIAdapter: boolean;
isTimezoneCompatible: boolean;
lib: string;
locale: string;
formats: AdapterFormats;
escapedCharacters: {
start: string;
end: string;
};
formatTokenMap: FieldFormatTokenMap;
constructor({
locale,
formats
}?: AdapterOptions<string, never>);
private setLocaleToValue;
date: <T extends string | null | undefined>(value?: T, timezone?: PickersTimezone) => DateBuilderReturnType<T>;
getInvalidDate: () => DateTime<true> | DateTime<false>;
getTimezone: (value: DateTime) => string;
setTimezone: (value: DateTime, timezone: PickersTimezone) => DateTime;
toJsDate: (value: DateTime) => Date;
parse: (value: string, formatString: string) => DateTime<true> | DateTime<false> | null;
getCurrentLocaleCode: () => string;
is12HourCycleInCurrentLocale: () => boolean;
expandFormat: (format: string) => string;
isValid: (value: DateTime | null) => value is DateTime;
format: (value: DateTime, formatKey: keyof AdapterFormats) => string;
formatByString: (value: DateTime, format: string) => string;
formatNumber: (numberToFormat: string) => string;
isEqual: (value: DateTime | null, comparing: DateTime | null) => boolean;
isSameYear: (value: DateTime, comparing: DateTime) => boolean;
isSameMonth: (value: DateTime, comparing: DateTime) => boolean;
isSameDay: (value: DateTime, comparing: DateTime) => boolean;
isSameHour: (value: DateTime, comparing: DateTime) => boolean;
isAfter: (value: DateTime, comparing: DateTime) => boolean;
isAfterYear: (value: DateTime, comparing: DateTime) => boolean;
isAfterDay: (value: DateTime, comparing: DateTime) => boolean;
isBefore: (value: DateTime, comparing: DateTime) => boolean;
isBeforeYear: (value: DateTime, comparing: DateTime) => boolean;
isBeforeDay: (value: DateTime, comparing: DateTime) => boolean;
isWithinRange: (value: DateTime, [start, end]: [DateTime, DateTime]) => boolean;
startOfYear: (value: DateTime) => DateTime<boolean>;
startOfMonth: (value: DateTime) => DateTime<boolean>;
startOfWeek: (value: DateTime) => DateTime<boolean>;
startOfDay: (value: DateTime) => DateTime<boolean>;
endOfYear: (value: DateTime) => DateTime<boolean>;
endOfMonth: (value: DateTime) => DateTime<boolean>;
endOfWeek: (value: DateTime) => DateTime<boolean>;
endOfDay: (value: DateTime) => DateTime<boolean>;
addYears: (value: DateTime, amount: number) => DateTime<boolean>;
addMonths: (value: DateTime, amount: number) => DateTime<boolean>;
addWeeks: (value: DateTime, amount: number) => DateTime<boolean>;
addDays: (value: DateTime, amount: number) => DateTime<boolean>;
addHours: (value: DateTime, amount: number) => DateTime<boolean>;
addMinutes: (value: DateTime, amount: number) => DateTime<boolean>;
addSeconds: (value: DateTime, amount: number) => DateTime<boolean>;
getYear: (value: DateTime) => number;
getMonth: (value: DateTime) => number;
getDate: (value: DateTime) => number;
getHours: (value: DateTime) => number;
getMinutes: (value: DateTime) => number;
getSeconds: (value: DateTime) => number;
getMilliseconds: (value: DateTime) => number;
setYear: (value: DateTime, year: number) => DateTime<boolean>;
setMonth: (value: DateTime, month: number) => DateTime<boolean>;
setDate: (value: DateTime, date: number) => DateTime<boolean>;
setHours: (value: DateTime, hours: number) => DateTime<boolean>;
setMinutes: (value: DateTime, minutes: number) => DateTime<boolean>;
setSeconds: (value: DateTime, seconds: number) => DateTime<boolean>;
setMilliseconds: (value: DateTime, milliseconds: number) => DateTime<boolean>;
getDaysInMonth: (value: DateTime) => import("luxon").PossibleDaysInMonth;
getWeekArray: (value: DateTime) => DateTime<boolean>[][];
getWeekNumber: (value: DateTime) => number;
getDayOfWeek: (value: DateTime) => number;
getYearRange: ([start, end]: [DateTime, DateTime]) => DateTime<boolean>[];
}

View file

@ -0,0 +1,500 @@
import _extends from "@babel/runtime/helpers/esm/extends";
import { DateTime, Info } from 'luxon';
const formatTokenMap = {
// Year
y: {
sectionType: 'year',
contentType: 'digit',
maxLength: 4
},
yy: 'year',
yyyy: {
sectionType: 'year',
contentType: 'digit',
maxLength: 4
},
// Month
L: {
sectionType: 'month',
contentType: 'digit',
maxLength: 2
},
LL: 'month',
LLL: {
sectionType: 'month',
contentType: 'letter'
},
LLLL: {
sectionType: 'month',
contentType: 'letter'
},
M: {
sectionType: 'month',
contentType: 'digit',
maxLength: 2
},
MM: 'month',
MMM: {
sectionType: 'month',
contentType: 'letter'
},
MMMM: {
sectionType: 'month',
contentType: 'letter'
},
// Day of the month
d: {
sectionType: 'day',
contentType: 'digit',
maxLength: 2
},
dd: 'day',
// Day of the week
c: {
sectionType: 'weekDay',
contentType: 'digit',
maxLength: 1
},
ccc: {
sectionType: 'weekDay',
contentType: 'letter'
},
cccc: {
sectionType: 'weekDay',
contentType: 'letter'
},
E: {
sectionType: 'weekDay',
contentType: 'digit',
maxLength: 2
},
EEE: {
sectionType: 'weekDay',
contentType: 'letter'
},
EEEE: {
sectionType: 'weekDay',
contentType: 'letter'
},
// Meridiem
a: 'meridiem',
// Hours
H: {
sectionType: 'hours',
contentType: 'digit',
maxLength: 2
},
HH: 'hours',
h: {
sectionType: 'hours',
contentType: 'digit',
maxLength: 2
},
hh: 'hours',
// Minutes
m: {
sectionType: 'minutes',
contentType: 'digit',
maxLength: 2
},
mm: 'minutes',
// Seconds
s: {
sectionType: 'seconds',
contentType: 'digit',
maxLength: 2
},
ss: 'seconds'
};
const defaultFormats = {
year: 'yyyy',
month: 'LLLL',
monthShort: 'MMM',
dayOfMonth: 'd',
// Full day of the month format (i.e. 3rd) is not supported
// Falling back to regular format
dayOfMonthFull: 'd',
weekday: 'cccc',
weekdayShort: 'ccccc',
hours24h: 'HH',
hours12h: 'hh',
meridiem: 'a',
minutes: 'mm',
seconds: 'ss',
fullDate: 'DD',
keyboardDate: 'D',
shortDate: 'MMM d',
normalDate: 'd MMMM',
normalDateWithWeekday: 'EEE, MMM d',
fullTime12h: 'hh:mm a',
fullTime24h: 'HH:mm',
keyboardDateTime12h: 'D hh:mm a',
keyboardDateTime24h: 'D T'
};
/**
* Based on `@date-io/luxon`
*
* MIT License
*
* Copyright (c) 2017 Dmitriy Kovalenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export class AdapterLuxon {
isMUIAdapter = true;
isTimezoneCompatible = true;
lib = 'luxon';
escapedCharacters = {
start: "'",
end: "'"
};
formatTokenMap = (() => formatTokenMap)();
constructor({
locale,
formats
} = {}) {
this.locale = locale || 'en-US';
this.formats = _extends({}, defaultFormats, formats);
}
setLocaleToValue = value => {
const expectedLocale = this.getCurrentLocaleCode();
if (expectedLocale === value.locale) {
return value;
}
return value.setLocale(expectedLocale);
};
date = (value, timezone = 'default') => {
if (value === null) {
return null;
}
if (typeof value === 'undefined') {
// @ts-ignore
return DateTime.fromJSDate(new Date(), {
locale: this.locale,
zone: timezone
});
}
// @ts-ignore
return DateTime.fromISO(value, {
locale: this.locale,
zone: timezone
});
};
getInvalidDate = () => DateTime.fromJSDate(new Date('Invalid Date'));
getTimezone = value => {
// When using the system zone, we want to return "system", not something like "Europe/Paris"
if (value.zone.type === 'system') {
return 'system';
}
return value.zoneName;
};
setTimezone = (value, timezone) => {
if (!value.zone.equals(Info.normalizeZone(timezone))) {
return value.setZone(timezone);
}
return value;
};
toJsDate = value => {
return value.toJSDate();
};
parse = (value, formatString) => {
if (value === '') {
return null;
}
return DateTime.fromFormat(value, formatString, {
locale: this.locale
});
};
getCurrentLocaleCode = () => {
return this.locale;
};
/* v8 ignore start */
is12HourCycleInCurrentLocale = () => {
if (typeof Intl === 'undefined' || typeof Intl.DateTimeFormat === 'undefined') {
return true; // Luxon defaults to en-US if Intl not found
}
return Boolean(new Intl.DateTimeFormat(this.locale, {
hour: 'numeric'
})?.resolvedOptions()?.hour12);
};
/* v8 ignore stop */
expandFormat = format => {
// Extract escaped section to avoid extending them
const catchEscapedSectionsRegexp = /''|'(''|[^'])+('|$)|[^']*/g;
// This RegExp tests if a string is only mad of supported tokens
const validTokens = [...Object.keys(this.formatTokenMap), 'yyyyy'];
const isWordComposedOfTokens = new RegExp(`^(${validTokens.join('|')})+$`);
// Extract words to test if they are a token or a word to escape.
const catchWordsRegexp = /(?:^|[^a-z])([a-z]+)(?:[^a-z]|$)|([a-z]+)/gi;
return format.match(catchEscapedSectionsRegexp).map(token => {
const firstCharacter = token[0];
if (firstCharacter === "'") {
return token;
}
const expandedToken = DateTime.expandFormat(token, {
locale: this.locale
});
return expandedToken.replace(catchWordsRegexp, (substring, g1, g2) => {
const word = g1 || g2; // words are either in group 1 or group 2
if (isWordComposedOfTokens.test(word)) {
return substring;
}
return `'${substring}'`;
});
}).join('')
// The returned format can contain `yyyyy` which means year between 4 and 6 digits.
// This value is supported by luxon parser but not luxon formatter.
// To avoid conflicts, we replace it by 4 digits which is enough for most use-cases.
.replace('yyyyy', 'yyyy');
};
isValid = value => {
if (value === null) {
return false;
}
return value.isValid;
};
format = (value, formatKey) => {
return this.formatByString(value, this.formats[formatKey]);
};
formatByString = (value, format) => {
return value.setLocale(this.locale).toFormat(format);
};
formatNumber = numberToFormat => {
return numberToFormat;
};
isEqual = (value, comparing) => {
if (value === null && comparing === null) {
return true;
}
if (value === null || comparing === null) {
return false;
}
return +value === +comparing;
};
isSameYear = (value, comparing) => {
const comparingInValueTimezone = this.setTimezone(comparing, this.getTimezone(value));
return value.hasSame(comparingInValueTimezone, 'year');
};
isSameMonth = (value, comparing) => {
const comparingInValueTimezone = this.setTimezone(comparing, this.getTimezone(value));
return value.hasSame(comparingInValueTimezone, 'month');
};
isSameDay = (value, comparing) => {
const comparingInValueTimezone = this.setTimezone(comparing, this.getTimezone(value));
return value.hasSame(comparingInValueTimezone, 'day');
};
isSameHour = (value, comparing) => {
const comparingInValueTimezone = this.setTimezone(comparing, this.getTimezone(value));
return value.hasSame(comparingInValueTimezone, 'hour');
};
isAfter = (value, comparing) => {
return value > comparing;
};
isAfterYear = (value, comparing) => {
const comparingInValueTimezone = this.setTimezone(comparing, this.getTimezone(value));
const diff = value.diff(this.endOfYear(comparingInValueTimezone), 'years').toObject();
return diff.years > 0;
};
isAfterDay = (value, comparing) => {
const comparingInValueTimezone = this.setTimezone(comparing, this.getTimezone(value));
const diff = value.diff(this.endOfDay(comparingInValueTimezone), 'days').toObject();
return diff.days > 0;
};
isBefore = (value, comparing) => {
return value < comparing;
};
isBeforeYear = (value, comparing) => {
const comparingInValueTimezone = this.setTimezone(comparing, this.getTimezone(value));
const diff = value.diff(this.startOfYear(comparingInValueTimezone), 'years').toObject();
return diff.years < 0;
};
isBeforeDay = (value, comparing) => {
const comparingInValueTimezone = this.setTimezone(comparing, this.getTimezone(value));
const diff = value.diff(this.startOfDay(comparingInValueTimezone), 'days').toObject();
return diff.days < 0;
};
isWithinRange = (value, [start, end]) => {
return this.isEqual(value, start) || this.isEqual(value, end) || this.isAfter(value, start) && this.isBefore(value, end);
};
startOfYear = value => {
return value.startOf('year');
};
startOfMonth = value => {
return value.startOf('month');
};
startOfWeek = value => {
return this.setLocaleToValue(value).startOf('week', {
useLocaleWeeks: true
});
};
startOfDay = value => {
return value.startOf('day');
};
endOfYear = value => {
return value.endOf('year');
};
endOfMonth = value => {
return value.endOf('month');
};
endOfWeek = value => {
return this.setLocaleToValue(value).endOf('week', {
useLocaleWeeks: true
});
};
endOfDay = value => {
return value.endOf('day');
};
addYears = (value, amount) => {
return value.plus({
years: amount
});
};
addMonths = (value, amount) => {
return value.plus({
months: amount
});
};
addWeeks = (value, amount) => {
return value.plus({
weeks: amount
});
};
addDays = (value, amount) => {
return value.plus({
days: amount
});
};
addHours = (value, amount) => {
return value.plus({
hours: amount
});
};
addMinutes = (value, amount) => {
return value.plus({
minutes: amount
});
};
addSeconds = (value, amount) => {
return value.plus({
seconds: amount
});
};
getYear = value => {
return value.get('year');
};
getMonth = value => {
// See https://github.com/moment/luxon/blob/master/docs/moment.md#major-functional-differences
return value.get('month') - 1;
};
getDate = value => {
return value.get('day');
};
getHours = value => {
return value.get('hour');
};
getMinutes = value => {
return value.get('minute');
};
getSeconds = value => {
return value.get('second');
};
getMilliseconds = value => {
return value.get('millisecond');
};
setYear = (value, year) => {
return value.set({
year
});
};
setMonth = (value, month) => {
return value.set({
month: month + 1
});
};
setDate = (value, date) => {
return value.set({
day: date
});
};
setHours = (value, hours) => {
return value.set({
hour: hours
});
};
setMinutes = (value, minutes) => {
return value.set({
minute: minutes
});
};
setSeconds = (value, seconds) => {
return value.set({
second: seconds
});
};
setMilliseconds = (value, milliseconds) => {
return value.set({
millisecond: milliseconds
});
};
getDaysInMonth = value => {
return value.daysInMonth;
};
getWeekArray = value => {
const firstDay = this.startOfWeek(this.startOfMonth(value));
const lastDay = this.endOfWeek(this.endOfMonth(value));
const {
days
} = lastDay.diff(firstDay, 'days').toObject();
const weeks = [];
new Array(Math.round(days)).fill(0).map((_, i) => i).map(day => firstDay.plus({
days: day
})).forEach((v, i) => {
if (i === 0 || i % 7 === 0 && i > 6) {
weeks.push([v]);
return;
}
weeks[weeks.length - 1].push(v);
});
return weeks;
};
getWeekNumber = value => {
/* v8 ignore next */
return value.localWeekNumber ?? value.weekNumber;
};
getDayOfWeek = value => {
return value.localWeekday ?? value.weekday;
};
getYearRange = ([start, end]) => {
const startDate = this.startOfYear(start);
const endDate = this.endOfYear(end);
const years = [];
let current = startDate;
while (this.isBefore(current, endDate)) {
years.push(current);
current = this.addYears(current, 1);
}
return years;
};
}

View file

@ -0,0 +1 @@
export { AdapterLuxon } from "./AdapterLuxon.js";

View file

@ -0,0 +1 @@
export { AdapterLuxon } from "./AdapterLuxon.js";

View file

@ -0,0 +1,114 @@
import defaultMoment, { Moment } from 'moment';
import { AdapterFormats, AdapterOptions, DateBuilderReturnType, FieldFormatTokenMap, MuiPickersAdapter, PickersTimezone } from "../models/index.js";
declare module '@mui/x-date-pickers/models' {
interface PickerValidDateLookup {
moment: Moment;
}
}
/**
* Based on `@date-io/moment`
*
* MIT License
*
* Copyright (c) 2017 Dmitriy Kovalenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export declare class AdapterMoment implements MuiPickersAdapter<string> {
isMUIAdapter: boolean;
isTimezoneCompatible: boolean;
lib: string;
moment: typeof defaultMoment;
locale?: string;
formats: AdapterFormats;
escapedCharacters: {
start: string;
end: string;
};
formatTokenMap: FieldFormatTokenMap;
constructor({
locale,
formats,
instance
}?: AdapterOptions<string, typeof defaultMoment>);
private setLocaleToValue;
private hasTimezonePlugin;
private createSystemDate;
private createUTCDate;
private createTZDate;
date: <T extends string | null | undefined>(value?: T, timezone?: PickersTimezone) => DateBuilderReturnType<T>;
getInvalidDate: () => defaultMoment.Moment;
getTimezone: (value: Moment) => string;
setTimezone: (value: Moment, timezone: PickersTimezone) => Moment;
toJsDate: (value: Moment) => Date;
parse: (value: string, format: string) => defaultMoment.Moment | null;
getCurrentLocaleCode: () => string;
is12HourCycleInCurrentLocale: () => boolean;
expandFormat: (format: string) => string;
isValid: (value: Moment | null) => value is Moment;
format: (value: Moment, formatKey: keyof AdapterFormats) => string;
formatByString: (value: Moment, formatString: string) => string;
formatNumber: (numberToFormat: string) => string;
isEqual: (value: Moment | null, comparing: Moment | null) => boolean;
isSameYear: (value: Moment, comparing: Moment) => boolean;
isSameMonth: (value: Moment, comparing: Moment) => boolean;
isSameDay: (value: Moment, comparing: Moment) => boolean;
isSameHour: (value: Moment, comparing: Moment) => boolean;
isAfter: (value: Moment, comparing: Moment) => boolean;
isAfterYear: (value: Moment, comparing: Moment) => boolean;
isAfterDay: (value: Moment, comparing: Moment) => boolean;
isBefore: (value: Moment, comparing: Moment) => boolean;
isBeforeYear: (value: Moment, comparing: Moment) => boolean;
isBeforeDay: (value: Moment, comparing: Moment) => boolean;
isWithinRange: (value: Moment, [start, end]: [Moment, Moment]) => boolean;
startOfYear: (value: Moment) => defaultMoment.Moment;
startOfMonth: (value: Moment) => defaultMoment.Moment;
startOfWeek: (value: Moment) => defaultMoment.Moment;
startOfDay: (value: Moment) => defaultMoment.Moment;
endOfYear: (value: Moment) => defaultMoment.Moment;
endOfMonth: (value: Moment) => defaultMoment.Moment;
endOfWeek: (value: Moment) => defaultMoment.Moment;
endOfDay: (value: Moment) => defaultMoment.Moment;
addYears: (value: Moment, amount: number) => defaultMoment.Moment;
addMonths: (value: Moment, amount: number) => defaultMoment.Moment;
addWeeks: (value: Moment, amount: number) => defaultMoment.Moment;
addDays: (value: Moment, amount: number) => defaultMoment.Moment;
addHours: (value: Moment, amount: number) => defaultMoment.Moment;
addMinutes: (value: Moment, amount: number) => defaultMoment.Moment;
addSeconds: (value: Moment, amount: number) => defaultMoment.Moment;
getYear: (value: Moment) => number;
getMonth: (value: Moment) => number;
getDate: (value: Moment) => number;
getHours: (value: Moment) => number;
getMinutes: (value: Moment) => number;
getSeconds: (value: Moment) => number;
getMilliseconds: (value: Moment) => number;
setYear: (value: Moment, year: number) => defaultMoment.Moment;
setMonth: (value: Moment, month: number) => defaultMoment.Moment;
setDate: (value: Moment, date: number) => defaultMoment.Moment;
setHours: (value: Moment, hours: number) => defaultMoment.Moment;
setMinutes: (value: Moment, minutes: number) => defaultMoment.Moment;
setSeconds: (value: Moment, seconds: number) => defaultMoment.Moment;
setMilliseconds: (value: Moment, milliseconds: number) => defaultMoment.Moment;
getDaysInMonth: (value: Moment) => number;
getWeekArray: (value: Moment) => defaultMoment.Moment[][];
getWeekNumber: (value: Moment) => number;
getDayOfWeek: (value: Moment) => number;
getYearRange([start, end]: [Moment, Moment]): defaultMoment.Moment[];
}

View file

@ -0,0 +1,468 @@
import _extends from "@babel/runtime/helpers/esm/extends";
import defaultMoment from 'moment';
// From https://momentjs.com/docs/#/displaying/format/
const formatTokenMap = {
// Year
Y: 'year',
YY: 'year',
YYYY: {
sectionType: 'year',
contentType: 'digit',
maxLength: 4
},
// Month
M: {
sectionType: 'month',
contentType: 'digit',
maxLength: 2
},
MM: 'month',
MMM: {
sectionType: 'month',
contentType: 'letter'
},
MMMM: {
sectionType: 'month',
contentType: 'letter'
},
// Day of the month
D: {
sectionType: 'day',
contentType: 'digit',
maxLength: 2
},
DD: 'day',
Do: {
sectionType: 'day',
contentType: 'digit-with-letter'
},
// Day of the week
E: {
sectionType: 'weekDay',
contentType: 'digit',
maxLength: 1
},
// eslint-disable-next-line id-denylist
e: {
sectionType: 'weekDay',
contentType: 'digit',
maxLength: 1
},
d: {
sectionType: 'weekDay',
contentType: 'digit',
maxLength: 1
},
dd: {
sectionType: 'weekDay',
contentType: 'letter'
},
ddd: {
sectionType: 'weekDay',
contentType: 'letter'
},
dddd: {
sectionType: 'weekDay',
contentType: 'letter'
},
// Meridiem
A: 'meridiem',
a: 'meridiem',
// Hours
H: {
sectionType: 'hours',
contentType: 'digit',
maxLength: 2
},
HH: 'hours',
h: {
sectionType: 'hours',
contentType: 'digit',
maxLength: 2
},
hh: 'hours',
// Minutes
m: {
sectionType: 'minutes',
contentType: 'digit',
maxLength: 2
},
mm: 'minutes',
// Seconds
s: {
sectionType: 'seconds',
contentType: 'digit',
maxLength: 2
},
ss: 'seconds'
};
const defaultFormats = {
year: 'YYYY',
month: 'MMMM',
monthShort: 'MMM',
dayOfMonth: 'D',
dayOfMonthFull: 'Do',
weekday: 'dddd',
weekdayShort: 'ddd',
hours24h: 'HH',
hours12h: 'hh',
meridiem: 'A',
minutes: 'mm',
seconds: 'ss',
fullDate: 'll',
keyboardDate: 'L',
shortDate: 'MMM D',
normalDate: 'D MMMM',
normalDateWithWeekday: 'ddd, MMM D',
fullTime12h: 'hh:mm A',
fullTime24h: 'HH:mm',
keyboardDateTime12h: 'L hh:mm A',
keyboardDateTime24h: 'L HH:mm'
};
const MISSING_TIMEZONE_PLUGIN = ['Missing timezone plugin', 'To be able to use timezones, you have to pass the default export from `moment-timezone` to the `dateLibInstance` prop of `LocalizationProvider`', 'Find more information on https://mui.com/x/react-date-pickers/timezone/#moment-and-timezone'].join('\n');
/**
* Based on `@date-io/moment`
*
* MIT License
*
* Copyright (c) 2017 Dmitriy Kovalenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export class AdapterMoment {
isMUIAdapter = true;
isTimezoneCompatible = true;
lib = 'moment';
escapedCharacters = {
start: '[',
end: ']'
};
formatTokenMap = (() => formatTokenMap)();
constructor({
locale,
formats,
instance
} = {}) {
this.moment = instance || defaultMoment;
this.locale = locale;
this.formats = _extends({}, defaultFormats, formats);
}
setLocaleToValue = value => {
const expectedLocale = this.getCurrentLocaleCode();
if (expectedLocale === value.locale()) {
return value;
}
return value.locale(expectedLocale);
};
hasTimezonePlugin = () => typeof this.moment.tz !== 'undefined';
createSystemDate = value => {
const parsedValue = this.moment(value).local();
if (this.locale === undefined) {
return parsedValue;
}
return parsedValue.locale(this.locale);
};
createUTCDate = value => {
const parsedValue = this.moment.utc(value);
if (this.locale === undefined) {
return parsedValue;
}
return parsedValue.locale(this.locale);
};
createTZDate = (value, timezone) => {
/* v8 ignore next 3 */
if (!this.hasTimezonePlugin()) {
throw new Error(MISSING_TIMEZONE_PLUGIN);
}
const parsedValue = timezone === 'default' ? this.moment(value) : this.moment.tz(value, timezone);
if (this.locale === undefined) {
return parsedValue;
}
return parsedValue.locale(this.locale);
};
date = (value, timezone = 'default') => {
if (value === null) {
return null;
}
if (timezone === 'UTC') {
return this.createUTCDate(value);
}
if (timezone === 'system' || timezone === 'default' && !this.hasTimezonePlugin()) {
return this.createSystemDate(value);
}
return this.createTZDate(value, timezone);
};
getInvalidDate = () => this.moment(new Date('Invalid Date'));
getTimezone = value => {
// @ts-ignore
// eslint-disable-next-line no-underscore-dangle
const zone = value._z?.name;
const defaultZone = value.isUTC() ? 'UTC' : 'system';
// @ts-ignore
return zone ?? this.moment.defaultZone?.name ?? defaultZone;
};
setTimezone = (value, timezone) => {
if (this.getTimezone(value) === timezone) {
return value;
}
if (timezone === 'UTC') {
return value.clone().utc();
}
if (timezone === 'system') {
return value.clone().local();
}
if (!this.hasTimezonePlugin()) {
/* v8 ignore next 3 */
if (timezone !== 'default') {
throw new Error(MISSING_TIMEZONE_PLUGIN);
}
return value;
}
const cleanZone = timezone === 'default' ?
// @ts-ignore
this.moment.defaultZone?.name ?? 'system' : timezone;
if (cleanZone === 'system') {
return value.clone().local();
}
const newValue = value.clone();
newValue.tz(cleanZone);
return newValue;
};
toJsDate = value => {
return value.toDate();
};
parse = (value, format) => {
if (value === '') {
return null;
}
if (this.locale) {
return this.moment(value, format, this.locale, true);
}
return this.moment(value, format, true);
};
getCurrentLocaleCode = () => {
return this.locale || defaultMoment.locale();
};
is12HourCycleInCurrentLocale = () => {
return /A|a/.test(defaultMoment.localeData(this.getCurrentLocaleCode()).longDateFormat('LT'));
};
expandFormat = format => {
// @see https://github.com/moment/moment/blob/develop/src/lib/format/format.js#L6
const localFormattingTokens = /(\[[^[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})|./g;
return format.match(localFormattingTokens).map(token => {
const firstCharacter = token[0];
if (firstCharacter === 'L' || firstCharacter === ';') {
return defaultMoment.localeData(this.getCurrentLocaleCode()).longDateFormat(token);
}
return token;
}).join('');
};
isValid = value => {
if (value == null) {
return false;
}
return value.isValid();
};
format = (value, formatKey) => {
return this.formatByString(value, this.formats[formatKey]);
};
formatByString = (value, formatString) => {
const clonedDate = value.clone();
clonedDate.locale(this.getCurrentLocaleCode());
return clonedDate.format(formatString);
};
formatNumber = numberToFormat => {
return numberToFormat;
};
isEqual = (value, comparing) => {
if (value === null && comparing === null) {
return true;
}
if (value === null || comparing === null) {
return false;
}
return value.isSame(comparing);
};
isSameYear = (value, comparing) => {
return value.isSame(comparing, 'year');
};
isSameMonth = (value, comparing) => {
return value.isSame(comparing, 'month');
};
isSameDay = (value, comparing) => {
return value.isSame(comparing, 'day');
};
isSameHour = (value, comparing) => {
return value.isSame(comparing, 'hour');
};
isAfter = (value, comparing) => {
return value.isAfter(comparing);
};
isAfterYear = (value, comparing) => {
return value.isAfter(comparing, 'year');
};
isAfterDay = (value, comparing) => {
return value.isAfter(comparing, 'day');
};
isBefore = (value, comparing) => {
return value.isBefore(comparing);
};
isBeforeYear = (value, comparing) => {
return value.isBefore(comparing, 'year');
};
isBeforeDay = (value, comparing) => {
return value.isBefore(comparing, 'day');
};
isWithinRange = (value, [start, end]) => {
return value.isBetween(start, end, null, '[]');
};
startOfYear = value => {
return value.clone().startOf('year');
};
startOfMonth = value => {
return value.clone().startOf('month');
};
startOfWeek = value => {
return this.setLocaleToValue(value.clone()).startOf('week');
};
startOfDay = value => {
return value.clone().startOf('day');
};
endOfYear = value => {
return value.clone().endOf('year');
};
endOfMonth = value => {
return value.clone().endOf('month');
};
endOfWeek = value => {
return this.setLocaleToValue(value.clone()).endOf('week');
};
endOfDay = value => {
return value.clone().endOf('day');
};
addYears = (value, amount) => {
return amount < 0 ? value.clone().subtract(Math.abs(amount), 'years') : value.clone().add(amount, 'years');
};
addMonths = (value, amount) => {
return amount < 0 ? value.clone().subtract(Math.abs(amount), 'months') : value.clone().add(amount, 'months');
};
addWeeks = (value, amount) => {
return amount < 0 ? value.clone().subtract(Math.abs(amount), 'weeks') : value.clone().add(amount, 'weeks');
};
addDays = (value, amount) => {
return amount < 0 ? value.clone().subtract(Math.abs(amount), 'days') : value.clone().add(amount, 'days');
};
addHours = (value, amount) => {
return amount < 0 ? value.clone().subtract(Math.abs(amount), 'hours') : value.clone().add(amount, 'hours');
};
addMinutes = (value, amount) => {
return amount < 0 ? value.clone().subtract(Math.abs(amount), 'minutes') : value.clone().add(amount, 'minutes');
};
addSeconds = (value, amount) => {
return amount < 0 ? value.clone().subtract(Math.abs(amount), 'seconds') : value.clone().add(amount, 'seconds');
};
getYear = value => {
return value.get('year');
};
getMonth = value => {
return value.get('month');
};
getDate = value => {
return value.get('date');
};
getHours = value => {
return value.get('hours');
};
getMinutes = value => {
return value.get('minutes');
};
getSeconds = value => {
return value.get('seconds');
};
getMilliseconds = value => {
return value.get('milliseconds');
};
setYear = (value, year) => {
return value.clone().year(year);
};
setMonth = (value, month) => {
return value.clone().month(month);
};
setDate = (value, date) => {
return value.clone().date(date);
};
setHours = (value, hours) => {
return value.clone().hours(hours);
};
setMinutes = (value, minutes) => {
return value.clone().minutes(minutes);
};
setSeconds = (value, seconds) => {
return value.clone().seconds(seconds);
};
setMilliseconds = (value, milliseconds) => {
return value.clone().milliseconds(milliseconds);
};
getDaysInMonth = value => {
return value.daysInMonth();
};
getWeekArray = value => {
const start = this.startOfWeek(this.startOfMonth(value));
const end = this.endOfWeek(this.endOfMonth(value));
let count = 0;
let current = start;
let currentDayOfYear = current.get('dayOfYear');
const nestedWeeks = [];
while (current.isBefore(end)) {
const weekNumber = Math.floor(count / 7);
nestedWeeks[weekNumber] = nestedWeeks[weekNumber] || [];
nestedWeeks[weekNumber].push(current);
const prevDayOfYear = currentDayOfYear;
current = this.addDays(current, 1);
currentDayOfYear = current.get('dayOfYear');
// If there is a TZ change at midnight, adding 1 day may only increase the date by 23 hours to 11pm
// To fix, bump the date into the next day (add 12 hours) and then revert to the start of the day
// See https://github.com/moment/moment/issues/4743#issuecomment-811306874 for context.
if (prevDayOfYear === currentDayOfYear) {
current = current.add(12, 'h').startOf('day');
}
count += 1;
}
return nestedWeeks;
};
getWeekNumber = value => {
return value.week();
};
getDayOfWeek = value => {
return value.day() + 1;
};
getYearRange([start, end]) {
const startDate = this.startOfYear(start);
const endDate = this.endOfYear(end);
const years = [];
let current = startDate;
while (this.isBefore(current, endDate)) {
years.push(current);
current = this.addYears(current, 1);
}
return years;
}
}

View file

@ -0,0 +1 @@
export { AdapterMoment } from "./AdapterMoment.js";

View file

@ -0,0 +1 @@
export { AdapterMoment } from "./AdapterMoment.js";

View file

@ -0,0 +1,62 @@
import defaultHMoment, { Moment } from 'moment-hijri';
import { AdapterMoment } from "../AdapterMoment/index.js";
import { AdapterOptions, DateBuilderReturnType, FieldFormatTokenMap, MuiPickersAdapter } from "../models/index.js";
declare module '@mui/x-date-pickers/models' {
interface PickerValidDateLookup {
'moment-hijri': Moment;
}
}
/**
* Based on `@date-io/hijri`
*
* MIT License
*
* Copyright (c) 2017 Dmitriy Kovalenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export declare class AdapterMomentHijri extends AdapterMoment implements MuiPickersAdapter<string> {
lib: string;
moment: typeof defaultHMoment;
isTimezoneCompatible: boolean;
formatTokenMap: FieldFormatTokenMap;
constructor({
formats,
instance
}?: AdapterOptions<string, typeof defaultHMoment>);
date: <T extends string | null | undefined>(value?: T) => DateBuilderReturnType<T>;
getTimezone: () => string;
setTimezone: (value: Moment) => Moment;
parse: (value: string, format: string) => defaultHMoment.Moment | null;
formatNumber: (numberToFormat: string) => string;
startOfYear: (value: Moment) => defaultHMoment.Moment;
startOfMonth: (value: Moment) => defaultHMoment.Moment;
endOfYear: (value: Moment) => defaultHMoment.Moment;
endOfMonth: (value: Moment) => defaultHMoment.Moment;
addYears: (value: Moment, amount: number) => defaultHMoment.Moment;
addMonths: (value: Moment, amount: number) => defaultHMoment.Moment;
getYear: (value: Moment) => number;
getMonth: (value: Moment) => number;
getDate: (value: Moment) => number;
setYear: (value: Moment, year: number) => defaultHMoment.Moment;
setMonth: (value: Moment, month: number) => defaultHMoment.Moment;
setDate: (value: Moment, date: number) => defaultHMoment.Moment;
getWeekNumber: (value: Moment) => number;
getYearRange: ([start, end]: [Moment, Moment]) => defaultHMoment.Moment[];
}

View file

@ -0,0 +1,222 @@
import _extends from "@babel/runtime/helpers/esm/extends";
/* v8 ignore next */
import defaultHMoment from 'moment-hijri';
import { AdapterMoment } from "../AdapterMoment/index.js";
// From https://momentjs.com/docs/#/displaying/format/
const formatTokenMap = {
// Year
iY: {
sectionType: 'year',
contentType: 'letter'
},
iYY: {
sectionType: 'year',
contentType: 'letter'
},
iYYYY: {
sectionType: 'year',
contentType: 'letter'
},
// Month
iM: 'month',
iMM: 'month',
iMMM: {
sectionType: 'month',
contentType: 'letter'
},
iMMMM: {
sectionType: 'month',
contentType: 'letter'
},
// Day of the month
iD: {
sectionType: 'day',
contentType: 'digit',
maxLength: 2
},
iDD: 'day',
// Meridiem
A: 'meridiem',
a: 'meridiem',
// Hours
H: {
sectionType: 'hours',
contentType: 'digit',
maxLength: 2
},
HH: 'hours',
h: {
sectionType: 'hours',
contentType: 'digit',
maxLength: 2
},
hh: 'hours',
// Minutes
m: {
sectionType: 'minutes',
contentType: 'digit',
maxLength: 2
},
mm: 'minutes',
// Seconds
s: {
sectionType: 'seconds',
contentType: 'digit',
maxLength: 2
},
ss: 'seconds'
};
const defaultFormats = {
year: 'iYYYY',
month: 'iMMMM',
monthShort: 'iMMM',
dayOfMonth: 'iD',
// Full day of the month format (i.e. 3rd) is not supported
// Falling back to regular format
dayOfMonthFull: 'iD',
weekday: 'dddd',
weekdayShort: 'ddd',
hours24h: 'HH',
hours12h: 'hh',
meridiem: 'A',
minutes: 'mm',
seconds: 'ss',
fullDate: 'iYYYY, iMMMM Do',
shortDate: 'iD iMMM',
normalDate: 'dddd, iD iMMM',
normalDateWithWeekday: 'DD iMMMM',
fullTime12h: 'hh:mm A',
fullTime24h: 'HH:mm',
keyboardDate: 'iYYYY/iMM/iDD',
keyboardDateTime12h: 'iYYYY/iMM/iDD hh:mm A',
keyboardDateTime24h: 'iYYYY/iMM/iDD HH:mm'
};
const NUMBER_SYMBOL_MAP = {
'1': '١',
'2': '٢',
'3': '٣',
'4': '٤',
'5': '٥',
'6': '٦',
'7': '٧',
'8': '٨',
'9': '٩',
'0': '٠'
};
/**
* Based on `@date-io/hijri`
*
* MIT License
*
* Copyright (c) 2017 Dmitriy Kovalenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export class AdapterMomentHijri extends AdapterMoment {
lib = 'moment-hijri';
isTimezoneCompatible = false;
formatTokenMap = (() => formatTokenMap)();
constructor({
formats,
instance
} = {}) {
super({
locale: 'ar-SA',
instance
});
this.moment = instance || defaultHMoment;
this.locale = 'ar-SA';
this.formats = _extends({}, defaultFormats, formats);
}
date = value => {
if (value === null) {
return null;
}
return this.moment(value).locale('ar-SA');
};
/* v8 ignore next 3 */
getTimezone = () => {
return 'default';
};
/* v8 ignore next 3 */
setTimezone = value => {
return value;
};
parse = (value, format) => {
if (value === '') {
return null;
}
return this.moment(value, format, true).locale('ar-SA');
};
formatNumber = numberToFormat => {
return numberToFormat.replace(/\d/g, match => NUMBER_SYMBOL_MAP[match]).replace(/,/g, '،');
};
startOfYear = value => {
return value.clone().startOf('iYear');
};
startOfMonth = value => {
return value.clone().startOf('iMonth');
};
endOfYear = value => {
return value.clone().endOf('iYear');
};
endOfMonth = value => {
return value.clone().endOf('iMonth');
};
addYears = (value, amount) => {
return amount < 0 ? value.clone().subtract(Math.abs(amount), 'iYear') : value.clone().add(amount, 'iYear');
};
addMonths = (value, amount) => {
return amount < 0 ? value.clone().subtract(Math.abs(amount), 'iMonth') : value.clone().add(amount, 'iMonth');
};
getYear = value => {
return value.iYear();
};
getMonth = value => {
return value.iMonth();
};
getDate = value => {
return value.iDate();
};
setYear = (value, year) => {
return value.clone().iYear(year);
};
setMonth = (value, month) => {
return value.clone().iMonth(month);
};
setDate = (value, date) => {
return value.clone().iDate(date);
};
getWeekNumber = value => {
return value.iWeek();
};
getYearRange = ([start, end]) => {
// moment-hijri only supports dates between 1356-01-01 H and 1499-12-29 H
// We need to throw if outside min/max bounds, otherwise the while loop below will be infinite.
if (start.isBefore('1937-03-14')) {
throw new Error('min date must be on or after 1356-01-01 H (1937-03-14)');
}
if (end.isAfter('2076-11-26')) {
throw new Error('max date must be on or before 1499-12-29 H (2076-11-26)');
}
return super.getYearRange([start, end]);
};
}

View file

@ -0,0 +1 @@
export { AdapterMomentHijri } from "./AdapterMomentHijri.js";

View file

@ -0,0 +1 @@
export { AdapterMomentHijri } from "./AdapterMomentHijri.js";

View file

@ -0,0 +1,66 @@
import defaultJMoment, { Moment } from 'moment-jalaali';
import { AdapterMoment } from "../AdapterMoment/index.js";
import { AdapterOptions, DateBuilderReturnType, FieldFormatTokenMap, MuiPickersAdapter } from "../models/index.js";
declare module '@mui/x-date-pickers/models' {
interface PickerValidDateLookup {
'moment-jalaali': Moment;
}
}
/**
* Based on `@date-io/jalaali`
*
* MIT License
*
* Copyright (c) 2017 Dmitriy Kovalenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export declare class AdapterMomentJalaali extends AdapterMoment implements MuiPickersAdapter<string> {
isTimezoneCompatible: boolean;
lib: string;
moment: typeof defaultJMoment;
formatTokenMap: FieldFormatTokenMap;
constructor({
formats,
instance
}?: AdapterOptions<string, typeof defaultJMoment>);
date: <T extends string | null | undefined>(value?: T) => DateBuilderReturnType<T>;
getTimezone: () => string;
setTimezone: (value: Moment) => Moment;
parse: (value: string, format: string) => defaultJMoment.Moment | null;
formatNumber: (numberToFormat: string) => string;
isSameYear: (value: Moment, comparing: Moment) => boolean;
isSameMonth: (value: Moment, comparing: Moment) => boolean;
isAfterYear: (value: Moment, comparing: Moment) => boolean;
isBeforeYear: (value: Moment, comparing: Moment) => boolean;
startOfYear: (value: Moment) => defaultJMoment.Moment;
startOfMonth: (value: Moment) => defaultJMoment.Moment;
endOfYear: (value: Moment) => defaultJMoment.Moment;
endOfMonth: (value: Moment) => defaultJMoment.Moment;
addYears: (value: Moment, amount: number) => defaultJMoment.Moment;
addMonths: (value: Moment, amount: number) => defaultJMoment.Moment;
getYear: (value: Moment) => number;
getMonth: (value: Moment) => number;
getDate: (value: Moment) => number;
getDaysInMonth: (value: Moment) => number;
setYear: (value: Moment, year: number) => defaultJMoment.Moment;
setMonth: (value: Moment, month: number) => defaultJMoment.Moment;
setDate: (value: Moment, date: number) => defaultJMoment.Moment;
getWeekNumber: (value: Moment) => number;
}

View file

@ -0,0 +1,220 @@
import _extends from "@babel/runtime/helpers/esm/extends";
/* v8 ignore next */
import defaultJMoment from 'moment-jalaali';
import { AdapterMoment } from "../AdapterMoment/index.js";
// From https://momentjs.com/docs/#/displaying/format/
const formatTokenMap = {
// Year
jYY: 'year',
jYYYY: {
sectionType: 'year',
contentType: 'digit',
maxLength: 4
},
// Month
jM: {
sectionType: 'month',
contentType: 'digit',
maxLength: 2
},
jMM: 'month',
jMMM: {
sectionType: 'month',
contentType: 'letter'
},
jMMMM: {
sectionType: 'month',
contentType: 'letter'
},
// Day of the month
jD: {
sectionType: 'day',
contentType: 'digit',
maxLength: 2
},
jDD: 'day',
// Meridiem
A: 'meridiem',
a: 'meridiem',
// Hours
H: {
sectionType: 'hours',
contentType: 'digit',
maxLength: 2
},
HH: 'hours',
h: {
sectionType: 'hours',
contentType: 'digit',
maxLength: 2
},
hh: 'hours',
// Minutes
m: {
sectionType: 'minutes',
contentType: 'digit',
maxLength: 2
},
mm: 'minutes',
// Seconds
s: {
sectionType: 'seconds',
contentType: 'digit',
maxLength: 2
},
ss: 'seconds'
};
const defaultFormats = {
year: 'jYYYY',
month: 'jMMMM',
monthShort: 'jMMM',
dayOfMonth: 'jD',
// Full day of the month format (i.e. 3rd) is not supported
// Falling back to regular format
dayOfMonthFull: 'jD',
weekday: 'dddd',
weekdayShort: 'ddd',
hours24h: 'HH',
hours12h: 'hh',
meridiem: 'A',
minutes: 'mm',
seconds: 'ss',
fullDate: 'jYYYY, jMMMM Do',
keyboardDate: 'jYYYY/jMM/jDD',
shortDate: 'jD jMMM',
normalDate: 'dddd, jD jMMM',
normalDateWithWeekday: 'DD MMMM',
fullTime12h: 'hh:mm A',
fullTime24h: 'HH:mm',
keyboardDateTime12h: 'jYYYY/jMM/jDD hh:mm A',
keyboardDateTime24h: 'jYYYY/jMM/jDD HH:mm'
};
const NUMBER_SYMBOL_MAP = {
'1': '۱',
'2': '۲',
'3': '۳',
'4': '۴',
'5': '۵',
'6': '۶',
'7': '۷',
'8': '۸',
'9': '۹',
'0': '۰'
};
/**
* Based on `@date-io/jalaali`
*
* MIT License
*
* Copyright (c) 2017 Dmitriy Kovalenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export class AdapterMomentJalaali extends AdapterMoment {
isTimezoneCompatible = false;
lib = 'moment-jalaali';
formatTokenMap = (() => formatTokenMap)();
constructor({
formats,
instance
} = {}) {
super({
locale: 'fa',
instance
});
this.moment = instance || defaultJMoment;
this.locale = 'fa';
this.formats = _extends({}, defaultFormats, formats);
}
date = value => {
if (value === null) {
return null;
}
return this.moment(value).locale('fa');
};
getTimezone = () => {
return 'default';
};
setTimezone = value => {
return value;
};
parse = (value, format) => {
if (value === '') {
return null;
}
return this.moment(value, format, true).locale('fa');
};
formatNumber = numberToFormat => {
return numberToFormat.replace(/\d/g, match => NUMBER_SYMBOL_MAP[match]).replace(/,/g, '،');
};
isSameYear = (value, comparing) => {
return value.jYear() === comparing.jYear();
};
isSameMonth = (value, comparing) => {
return value.jYear() === comparing.jYear() && value.jMonth() === comparing.jMonth();
};
isAfterYear = (value, comparing) => {
return value.jYear() > comparing.jYear();
};
isBeforeYear = (value, comparing) => {
return value.jYear() < comparing.jYear();
};
startOfYear = value => {
return value.clone().startOf('jYear');
};
startOfMonth = value => {
return value.clone().startOf('jMonth');
};
endOfYear = value => {
return value.clone().endOf('jYear');
};
endOfMonth = value => {
return value.clone().endOf('jMonth');
};
addYears = (value, amount) => {
return amount < 0 ? value.clone().subtract(Math.abs(amount), 'jYear') : value.clone().add(amount, 'jYear');
};
addMonths = (value, amount) => {
return amount < 0 ? value.clone().subtract(Math.abs(amount), 'jMonth') : value.clone().add(amount, 'jMonth');
};
getYear = value => {
return value.jYear();
};
getMonth = value => {
return value.jMonth();
};
getDate = value => {
return value.jDate();
};
getDaysInMonth = value => {
return this.moment.jDaysInMonth(value.jYear(), value.jMonth());
};
setYear = (value, year) => {
return value.clone().jYear(year);
};
setMonth = (value, month) => {
return value.clone().jMonth(month);
};
setDate = (value, date) => {
return value.clone().jDate(date);
};
getWeekNumber = value => {
return value.jWeek();
};
}

View file

@ -0,0 +1 @@
export { AdapterMomentJalaali } from "./AdapterMomentJalaali.js";

View file

@ -0,0 +1 @@
export { AdapterMomentJalaali } from "./AdapterMomentJalaali.js";

View file

@ -0,0 +1,18 @@
import * as React from 'react';
import { DateCalendarProps } from "./DateCalendar.types.js";
type DateCalendarComponent = ((props: DateCalendarProps & React.RefAttributes<HTMLDivElement>) => React.JSX.Element) & {
propTypes?: any;
};
/**
* Demos:
*
* - [DatePicker](https://mui.com/x/react-date-pickers/date-picker/)
* - [DateCalendar](https://mui.com/x/react-date-pickers/date-calendar/)
* - [Validation](https://mui.com/x/react-date-pickers/validation/)
*
* API:
*
* - [DateCalendar API](https://mui.com/x/api/date-pickers/date-calendar/)
*/
export declare const DateCalendar: DateCalendarComponent;
export {};

View file

@ -0,0 +1,591 @@
'use client';
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _extends from "@babel/runtime/helpers/esm/extends";
const _excluded = ["autoFocus", "onViewChange", "value", "defaultValue", "referenceDate", "disableFuture", "disablePast", "onChange", "onYearChange", "onMonthChange", "reduceAnimations", "shouldDisableDate", "shouldDisableMonth", "shouldDisableYear", "view", "views", "openTo", "className", "classes", "disabled", "readOnly", "minDate", "maxDate", "disableHighlightToday", "focusedView", "onFocusedViewChange", "showDaysOutsideCurrentMonth", "fixedWeekNumber", "dayOfWeekFormatter", "slots", "slotProps", "loading", "renderLoading", "displayWeekNumber", "yearsOrder", "yearsPerRow", "monthsPerRow", "timezone"];
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import useSlotProps from '@mui/utils/useSlotProps';
import { styled, useThemeProps } from '@mui/material/styles';
import composeClasses from '@mui/utils/composeClasses';
import useId from '@mui/utils/useId';
import useEventCallback from '@mui/utils/useEventCallback';
import { useCalendarState } from "./useCalendarState.js";
import { PickersFadeTransitionGroup } from "./PickersFadeTransitionGroup.js";
import { DayCalendar } from "./DayCalendar.js";
import { MonthCalendar } from "../MonthCalendar/index.js";
import { YearCalendar } from "../YearCalendar/index.js";
import { useViews } from "../internals/hooks/useViews.js";
import { PickersCalendarHeader } from "../PickersCalendarHeader/index.js";
import { findClosestEnabledDate, mergeDateAndTime } from "../internals/utils/date-utils.js";
import { PickerViewRoot } from "../internals/components/PickerViewRoot/index.js";
import { useReduceAnimations } from "../internals/hooks/useReduceAnimations.js";
import { getDateCalendarUtilityClass } from "./dateCalendarClasses.js";
import { useControlledValue } from "../internals/hooks/useControlledValue.js";
import { singleItemValueManager } from "../internals/utils/valueManagers.js";
import { VIEW_HEIGHT } from "../internals/constants/dimensions.js";
import { usePickerPrivateContext } from "../internals/hooks/usePickerPrivateContext.js";
import { useApplyDefaultValuesToDateValidationProps } from "../managers/useDateManager.js";
import { usePickerAdapter } from "../hooks/usePickerAdapter.js";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const useUtilityClasses = classes => {
const slots = {
root: ['root'],
viewTransitionContainer: ['viewTransitionContainer']
};
return composeClasses(slots, getDateCalendarUtilityClass, classes);
};
function useDateCalendarDefaultizedProps(props, name) {
const themeProps = useThemeProps({
props,
name
});
const reduceAnimations = useReduceAnimations(themeProps.reduceAnimations);
const validationProps = useApplyDefaultValuesToDateValidationProps(themeProps);
return _extends({}, themeProps, validationProps, {
loading: themeProps.loading ?? false,
openTo: themeProps.openTo ?? 'day',
views: themeProps.views ?? ['year', 'day'],
reduceAnimations,
renderLoading: themeProps.renderLoading ?? (() => /*#__PURE__*/_jsx("span", {
children: "..."
}))
});
}
const DateCalendarRoot = styled(PickerViewRoot, {
name: 'MuiDateCalendar',
slot: 'Root'
})({
display: 'flex',
flexDirection: 'column',
height: VIEW_HEIGHT
});
const DateCalendarViewTransitionContainer = styled(PickersFadeTransitionGroup, {
name: 'MuiDateCalendar',
slot: 'ViewTransitionContainer'
})({});
/**
* Demos:
*
* - [DatePicker](https://mui.com/x/react-date-pickers/date-picker/)
* - [DateCalendar](https://mui.com/x/react-date-pickers/date-calendar/)
* - [Validation](https://mui.com/x/react-date-pickers/validation/)
*
* API:
*
* - [DateCalendar API](https://mui.com/x/api/date-pickers/date-calendar/)
*/
export const DateCalendar = /*#__PURE__*/React.forwardRef(function DateCalendar(inProps, ref) {
const adapter = usePickerAdapter();
const {
ownerState
} = usePickerPrivateContext();
const id = useId();
const props = useDateCalendarDefaultizedProps(inProps, 'MuiDateCalendar');
const {
autoFocus,
onViewChange,
value: valueProp,
defaultValue,
referenceDate: referenceDateProp,
disableFuture,
disablePast,
onChange,
onMonthChange,
reduceAnimations,
shouldDisableDate,
shouldDisableMonth,
shouldDisableYear,
view: inView,
views,
openTo,
className,
classes: classesProp,
disabled,
readOnly,
minDate,
maxDate,
disableHighlightToday,
focusedView: focusedViewProp,
onFocusedViewChange,
showDaysOutsideCurrentMonth,
fixedWeekNumber,
dayOfWeekFormatter,
slots,
slotProps,
loading,
renderLoading,
displayWeekNumber,
yearsOrder,
yearsPerRow,
monthsPerRow,
timezone: timezoneProp
} = props,
other = _objectWithoutPropertiesLoose(props, _excluded);
const {
value,
handleValueChange,
timezone
} = useControlledValue({
name: 'DateCalendar',
timezone: timezoneProp,
value: valueProp,
defaultValue,
referenceDate: referenceDateProp,
onChange,
valueManager: singleItemValueManager
});
const {
view,
setView,
focusedView,
setFocusedView,
goToNextView,
setValueAndGoToNextView
} = useViews({
view: inView,
views,
openTo,
onChange: handleValueChange,
onViewChange,
autoFocus,
focusedView: focusedViewProp,
onFocusedViewChange
});
const {
referenceDate,
calendarState,
setVisibleDate,
isDateDisabled,
onMonthSwitchingAnimationEnd
} = useCalendarState({
value,
referenceDate: referenceDateProp,
reduceAnimations,
onMonthChange,
minDate,
maxDate,
shouldDisableDate,
disablePast,
disableFuture,
timezone,
getCurrentMonthFromVisibleDate: (visibleDate, prevMonth) => {
if (adapter.isSameMonth(visibleDate, prevMonth)) {
return prevMonth;
}
return adapter.startOfMonth(visibleDate);
}
});
// When disabled, limit the view to the selected date
const minDateWithDisabled = disabled && value || minDate;
const maxDateWithDisabled = disabled && value || maxDate;
const gridLabelId = `${id}-grid-label`;
const hasFocus = focusedView !== null;
const CalendarHeader = slots?.calendarHeader ?? PickersCalendarHeader;
const calendarHeaderProps = useSlotProps({
elementType: CalendarHeader,
externalSlotProps: slotProps?.calendarHeader,
additionalProps: {
views,
view,
currentMonth: calendarState.currentMonth,
onViewChange: setView,
onMonthChange: month => setVisibleDate({
target: month,
reason: 'header-navigation'
}),
minDate: minDateWithDisabled,
maxDate: maxDateWithDisabled,
disabled,
disablePast,
disableFuture,
reduceAnimations,
timezone,
labelId: gridLabelId
},
ownerState
});
const handleDateMonthChange = useEventCallback(newDate => {
const startOfMonth = adapter.startOfMonth(newDate);
const endOfMonth = adapter.endOfMonth(newDate);
const closestEnabledDate = isDateDisabled(newDate) ? findClosestEnabledDate({
adapter,
date: newDate,
minDate: adapter.isBefore(minDate, startOfMonth) ? startOfMonth : minDate,
maxDate: adapter.isAfter(maxDate, endOfMonth) ? endOfMonth : maxDate,
disablePast,
disableFuture,
isDateDisabled,
timezone
}) : newDate;
if (closestEnabledDate) {
setValueAndGoToNextView(closestEnabledDate, 'finish');
setVisibleDate({
target: closestEnabledDate,
reason: 'cell-interaction'
});
} else {
goToNextView();
setVisibleDate({
target: startOfMonth,
reason: 'cell-interaction'
});
}
});
const handleDateYearChange = useEventCallback(newDate => {
const startOfYear = adapter.startOfYear(newDate);
const endOfYear = adapter.endOfYear(newDate);
const closestEnabledDate = isDateDisabled(newDate) ? findClosestEnabledDate({
adapter,
date: newDate,
minDate: adapter.isBefore(minDate, startOfYear) ? startOfYear : minDate,
maxDate: adapter.isAfter(maxDate, endOfYear) ? endOfYear : maxDate,
disablePast,
disableFuture,
isDateDisabled,
timezone
}) : newDate;
if (closestEnabledDate) {
setValueAndGoToNextView(closestEnabledDate, 'finish');
setVisibleDate({
target: closestEnabledDate,
reason: 'cell-interaction'
});
} else {
goToNextView();
setVisibleDate({
target: startOfYear,
reason: 'cell-interaction'
});
}
});
const handleSelectedDayChange = useEventCallback(day => {
if (day) {
// If there is a date already selected, then we want to keep its time
return handleValueChange(mergeDateAndTime(adapter, day, value ?? referenceDate), 'finish', view);
}
return handleValueChange(day, 'finish', view);
});
React.useEffect(() => {
if (adapter.isValid(value)) {
setVisibleDate({
target: value,
reason: 'controlled-value-change'
});
}
}, [value]); // eslint-disable-line
const classes = useUtilityClasses(classesProp);
const baseDateValidationProps = {
disablePast,
disableFuture,
maxDate,
minDate
};
const commonViewProps = {
disableHighlightToday,
readOnly,
disabled,
timezone,
gridLabelId,
slots,
slotProps
};
const prevOpenViewRef = React.useRef(view);
React.useEffect(() => {
// If the view change and the focus was on the previous view
// Then we update the focus.
if (prevOpenViewRef.current === view) {
return;
}
if (focusedView === prevOpenViewRef.current) {
setFocusedView(view, true);
}
prevOpenViewRef.current = view;
}, [focusedView, setFocusedView, view]);
const selectedDays = React.useMemo(() => [value], [value]);
return /*#__PURE__*/_jsxs(DateCalendarRoot, _extends({
ref: ref,
className: clsx(classes.root, className),
ownerState: ownerState
}, other, {
children: [/*#__PURE__*/_jsx(CalendarHeader, _extends({}, calendarHeaderProps, {
slots: slots,
slotProps: slotProps
})), /*#__PURE__*/_jsx(DateCalendarViewTransitionContainer, {
reduceAnimations: reduceAnimations,
className: classes.viewTransitionContainer,
transKey: view,
ownerState: ownerState,
children: /*#__PURE__*/_jsxs("div", {
children: [view === 'year' && /*#__PURE__*/_jsx(YearCalendar, _extends({}, baseDateValidationProps, commonViewProps, {
value: value,
onChange: handleDateYearChange,
shouldDisableYear: shouldDisableYear,
hasFocus: hasFocus,
onFocusedViewChange: isViewFocused => setFocusedView('year', isViewFocused),
yearsOrder: yearsOrder,
yearsPerRow: yearsPerRow,
referenceDate: referenceDate
})), view === 'month' && /*#__PURE__*/_jsx(MonthCalendar, _extends({}, baseDateValidationProps, commonViewProps, {
hasFocus: hasFocus,
className: className,
value: value,
onChange: handleDateMonthChange,
shouldDisableMonth: shouldDisableMonth,
onFocusedViewChange: isViewFocused => setFocusedView('month', isViewFocused),
monthsPerRow: monthsPerRow,
referenceDate: referenceDate
})), view === 'day' && /*#__PURE__*/_jsx(DayCalendar, _extends({}, calendarState, baseDateValidationProps, commonViewProps, {
onMonthSwitchingAnimationEnd: onMonthSwitchingAnimationEnd,
hasFocus: hasFocus,
onFocusedDayChange: focusedDate => setVisibleDate({
target: focusedDate,
reason: 'cell-interaction'
}),
reduceAnimations: reduceAnimations,
selectedDays: selectedDays,
onSelectedDaysChange: handleSelectedDayChange,
shouldDisableDate: shouldDisableDate,
shouldDisableMonth: shouldDisableMonth,
shouldDisableYear: shouldDisableYear,
onFocusedViewChange: isViewFocused => setFocusedView('day', isViewFocused),
showDaysOutsideCurrentMonth: showDaysOutsideCurrentMonth,
fixedWeekNumber: fixedWeekNumber,
dayOfWeekFormatter: dayOfWeekFormatter,
displayWeekNumber: displayWeekNumber,
loading: loading,
renderLoading: renderLoading
}))]
})
})]
}));
});
if (process.env.NODE_ENV !== "production") DateCalendar.displayName = "DateCalendar";
process.env.NODE_ENV !== "production" ? DateCalendar.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the TypeScript types and run "pnpm proptypes" |
// ----------------------------------------------------------------------
/**
* If `true`, the main element is focused during the first mount.
* This main element is:
* - the element chosen by the visible view if any (i.e: the selected day on the `day` view).
* - the `input` element if there is a field rendered.
*/
autoFocus: PropTypes.bool,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
className: PropTypes.string,
/**
* Formats the day of week displayed in the calendar header.
* @param {PickerValidDate} date The date of the day of week provided by the adapter.
* @returns {string} The name to display.
* @default (date: PickerValidDate) => adapter.format(date, 'weekdayShort').charAt(0).toUpperCase()
*/
dayOfWeekFormatter: PropTypes.func,
/**
* The default selected value.
* Used when the component is not controlled.
*/
defaultValue: PropTypes.object,
/**
* If `true`, the component is disabled.
* When disabled, the value cannot be changed and no interaction is possible.
* @default false
*/
disabled: PropTypes.bool,
/**
* If `true`, disable values after the current date for date components, time for time components and both for date time components.
* @default false
*/
disableFuture: PropTypes.bool,
/**
* If `true`, today's date is rendering without highlighting with circle.
* @default false
*/
disableHighlightToday: PropTypes.bool,
/**
* If `true`, disable values before the current date for date components, time for time components and both for date time components.
* @default false
*/
disablePast: PropTypes.bool,
/**
* If `true`, the week number will be display in the calendar.
*/
displayWeekNumber: PropTypes.bool,
/**
* The day view will show as many weeks as needed after the end of the current month to match this value.
* Put it to 6 to have a fixed number of weeks in Gregorian calendars
*/
fixedWeekNumber: PropTypes.number,
/**
* Controlled focused view.
*/
focusedView: PropTypes.oneOf(['day', 'month', 'year']),
/**
* If `true`, calls `renderLoading` instead of rendering the day calendar.
* Can be used to preload information and show it in calendar.
* @default false
*/
loading: PropTypes.bool,
/**
* Maximal selectable date.
* @default 2099-12-31
*/
maxDate: PropTypes.object,
/**
* Minimal selectable date.
* @default 1900-01-01
*/
minDate: PropTypes.object,
/**
* Months rendered per row.
* @default 3
*/
monthsPerRow: PropTypes.oneOf([3, 4]),
/**
* Callback fired when the value changes.
* @template TValue The value type. It will be the same type as `value` or `null`. It can be in `[start, end]` format in case of range value.
* @template TView The view type. Will be one of date or time views.
* @param {TValue} value The new value.
* @param {PickerSelectionState | undefined} selectionState Indicates if the date selection is complete.
* @param {TView | undefined} selectedView Indicates the view in which the selection has been made.
*/
onChange: PropTypes.func,
/**
* Callback fired on focused view change.
* @template TView Type of the view. It will vary based on the Picker type and the `views` it uses.
* @param {TView} view The new view to focus or not.
* @param {boolean} hasFocus `true` if the view should be focused.
*/
onFocusedViewChange: PropTypes.func,
/**
* Callback fired on month change.
* @param {PickerValidDate} month The new month.
*/
onMonthChange: PropTypes.func,
/**
* Callback fired on view change.
* @template TView Type of the view. It will vary based on the Picker type and the `views` it uses.
* @param {TView} view The new view.
*/
onViewChange: PropTypes.func,
/**
* Callback fired on year change.
* @param {PickerValidDate} year The new year.
*/
onYearChange: PropTypes.func,
/**
* The default visible view.
* Used when the component view is not controlled.
* Must be a valid option from `views` list.
*/
openTo: PropTypes.oneOf(['day', 'month', 'year']),
/**
* If `true`, the component is read-only.
* When read-only, the value cannot be changed but the user can interact with the interface.
* @default false
*/
readOnly: PropTypes.bool,
/**
* If `true`, disable heavy animations.
* @default `@media(prefers-reduced-motion: reduce)` || `navigator.userAgent` matches Android <10 or iOS <13
*/
reduceAnimations: PropTypes.bool,
/**
* The date used to generate the new value when both `value` and `defaultValue` are empty.
* @default The closest valid date using the validation props, except callbacks such as `shouldDisableDate`.
*/
referenceDate: PropTypes.object,
/**
* Component displaying when passed `loading` true.
* @returns {React.ReactNode} The node to render when loading.
* @default () => <span>...</span>
*/
renderLoading: PropTypes.func,
/**
* Disable specific date.
*
* Warning: This function can be called multiple times (for example when rendering date calendar, checking if focus can be moved to a certain date, etc.). Expensive computations can impact performance.
*
* @param {PickerValidDate} day The date to test.
* @returns {boolean} If `true` the date will be disabled.
*/
shouldDisableDate: PropTypes.func,
/**
* Disable specific month.
* @param {PickerValidDate} month The month to test.
* @returns {boolean} If `true`, the month will be disabled.
*/
shouldDisableMonth: PropTypes.func,
/**
* Disable specific year.
* @param {PickerValidDate} year The year to test.
* @returns {boolean} If `true`, the year will be disabled.
*/
shouldDisableYear: PropTypes.func,
/**
* If `true`, days outside the current month are rendered:
*
* - if `fixedWeekNumber` is defined, renders days to have the weeks requested.
*
* - if `fixedWeekNumber` is not defined, renders day to fill the first and last week of the current month.
*
* - ignored if `calendars` equals more than `1` on range pickers.
* @default false
*/
showDaysOutsideCurrentMonth: PropTypes.bool,
/**
* The props used for each component slot.
* @default {}
*/
slotProps: PropTypes.object,
/**
* Overridable component slots.
* @default {}
*/
slots: PropTypes.object,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
/**
* Choose which timezone to use for the value.
* Example: "default", "system", "UTC", "America/New_York".
* If you pass values from other timezones to some props, they will be converted to this timezone before being used.
* @see See the {@link https://mui.com/x/react-date-pickers/timezone/ timezones documentation} for more details.
* @default The timezone of the `value` or `defaultValue` prop is defined, 'default' otherwise.
*/
timezone: PropTypes.string,
/**
* The selected value.
* Used when the component is controlled.
*/
value: PropTypes.object,
/**
* The visible view.
* Used when the component view is controlled.
* Must be a valid option from `views` list.
*/
view: PropTypes.oneOf(['day', 'month', 'year']),
/**
* Available views.
*/
views: PropTypes.arrayOf(PropTypes.oneOf(['day', 'month', 'year']).isRequired),
/**
* Years are displayed in ascending (chronological) order by default.
* If `desc`, years are displayed in descending order.
* @default 'asc'
*/
yearsOrder: PropTypes.oneOf(['asc', 'desc']),
/**
* Years rendered per row.
* @default 3
*/
yearsPerRow: PropTypes.oneOf([3, 4])
} : void 0;

View file

@ -0,0 +1,87 @@
import * as React from 'react';
import { SxProps } from '@mui/system';
import { Theme } from '@mui/material/styles';
import { SlotComponentProps } from '@mui/utils/types';
import { DefaultizedProps } from '@mui/x-internals/types';
import { PickersCalendarHeader, PickersCalendarHeaderProps, PickersCalendarHeaderSlots, PickersCalendarHeaderSlotProps } from "../PickersCalendarHeader/index.js";
import { DayCalendarSlots, DayCalendarSlotProps, ExportedDayCalendarProps } from "./DayCalendar.js";
import { DateCalendarClasses } from "./dateCalendarClasses.js";
import { BaseDateValidationProps } from "../internals/models/validation.js";
import { ExportedUseViewsOptions } from "../internals/hooks/useViews.js";
import { DateView, PickerOwnerState, PickerValidDate, TimezoneProps } from "../models/index.js";
import { ExportedYearCalendarProps, YearCalendarSlots, YearCalendarSlotProps } from "../YearCalendar/YearCalendar.types.js";
import { ExportedMonthCalendarProps, MonthCalendarSlots, MonthCalendarSlotProps } from "../MonthCalendar/MonthCalendar.types.js";
import { ExportedValidateDateProps } from "../validation/validateDate.js";
import { FormProps } from "../internals/models/formProps.js";
import { PickerValue } from "../internals/models/index.js";
export interface DateCalendarSlots extends PickersCalendarHeaderSlots, DayCalendarSlots, MonthCalendarSlots, YearCalendarSlots {
/**
* Custom component for calendar header.
* Check the [PickersCalendarHeader](https://mui.com/x/api/date-pickers/pickers-calendar-header/) component.
* @default PickersCalendarHeader
*/
calendarHeader?: React.ElementType<PickersCalendarHeaderProps>;
}
export interface DateCalendarSlotProps extends PickersCalendarHeaderSlotProps, DayCalendarSlotProps, MonthCalendarSlotProps, YearCalendarSlotProps {
calendarHeader?: SlotComponentProps<typeof PickersCalendarHeader, {}, PickerOwnerState>;
}
export interface ExportedDateCalendarProps extends ExportedDayCalendarProps, ExportedMonthCalendarProps, ExportedYearCalendarProps, ExportedValidateDateProps, TimezoneProps, FormProps {
/**
* If `true`, disable heavy animations.
* @default `@media(prefers-reduced-motion: reduce)` || `navigator.userAgent` matches Android <10 or iOS <13
*/
reduceAnimations?: boolean;
/**
* Component displaying when passed `loading` true.
* @returns {React.ReactNode} The node to render when loading.
* @default () => <span>...</span>
*/
renderLoading?: () => React.ReactNode;
/**
* Callback fired on year change.
* @param {PickerValidDate} year The new year.
*/
onYearChange?: (year: PickerValidDate) => void;
/**
* Callback fired on month change.
* @param {PickerValidDate} month The new month.
*/
onMonthChange?: (month: PickerValidDate) => void;
}
export interface DateCalendarProps extends ExportedDateCalendarProps, ExportedUseViewsOptions<PickerValue, DateView> {
/**
* The selected value.
* Used when the component is controlled.
*/
value?: PickerValidDate | null;
/**
* The default selected value.
* Used when the component is not controlled.
*/
defaultValue?: PickerValidDate | null;
/**
* The date used to generate the new value when both `value` and `defaultValue` are empty.
* @default The closest valid date using the validation props, except callbacks such as `shouldDisableDate`.
*/
referenceDate?: PickerValidDate;
className?: string;
/**
* Override or extend the styles applied to the component.
*/
classes?: Partial<DateCalendarClasses>;
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx?: SxProps<Theme>;
/**
* Overridable component slots.
* @default {}
*/
slots?: DateCalendarSlots;
/**
* The props used for each component slot.
* @default {}
*/
slotProps?: DateCalendarSlotProps;
}
export type DateCalendarDefaultizedProps = DefaultizedProps<DateCalendarProps, 'views' | 'openTo' | 'loading' | 'reduceAnimations' | 'renderLoading' | keyof BaseDateValidationProps>;

View file

@ -0,0 +1 @@
export {};

View file

@ -0,0 +1,85 @@
import * as React from 'react';
import { DefaultizedProps, SlotComponentPropsFromProps } from '@mui/x-internals/types';
import { PickerDayOwnerState, PickersDayProps } from "../PickersDay/index.js";
import { ExportedPickersDayProps } from "../PickersDay/PickersDay.types.js";
import { PickerOnChangeFn } from "../internals/hooks/useViews.js";
import { SlideDirection, SlideTransitionProps } from "./PickersSlideTransition.js";
import { BaseDateValidationProps, DayValidationProps, MonthValidationProps, YearValidationProps } from "../internals/models/validation.js";
import { DayCalendarClasses } from "./dayCalendarClasses.js";
import { PickerValidDate, TimezoneProps } from "../models/index.js";
import { FormProps } from "../internals/models/formProps.js";
export interface DayCalendarSlots {
/**
* Custom component for day.
* Check the [PickersDay](https://mui.com/x/api/date-pickers/pickers-day/) component.
* @default PickersDay
*/
day?: React.ElementType<PickersDayProps>;
}
export interface DayCalendarSlotProps {
day?: SlotComponentPropsFromProps<PickersDayProps, {}, PickerDayOwnerState>;
}
export interface ExportedDayCalendarProps extends ExportedPickersDayProps {
/**
* If `true`, calls `renderLoading` instead of rendering the day calendar.
* Can be used to preload information and show it in calendar.
* @default false
*/
loading?: boolean;
/**
* Component rendered on the "day" view when `props.loading` is true.
* @returns {React.ReactNode} The node to render when loading.
* @default () => "..."
*/
renderLoading?: () => React.ReactNode;
/**
* Formats the day of week displayed in the calendar header.
* @param {PickerValidDate} date The date of the day of week provided by the adapter.
* @returns {string} The name to display.
* @default (date: PickerValidDate) => adapter.format(date, 'weekdayShort').charAt(0).toUpperCase()
*/
dayOfWeekFormatter?: (date: PickerValidDate) => string;
/**
* If `true`, the week number will be display in the calendar.
*/
displayWeekNumber?: boolean;
/**
* The day view will show as many weeks as needed after the end of the current month to match this value.
* Put it to 6 to have a fixed number of weeks in Gregorian calendars
*/
fixedWeekNumber?: number;
}
export interface DayCalendarProps extends ExportedDayCalendarProps, DayValidationProps, MonthValidationProps, YearValidationProps, Required<BaseDateValidationProps>, DefaultizedProps<TimezoneProps, 'timezone'>, FormProps {
className?: string;
currentMonth: PickerValidDate;
selectedDays: (PickerValidDate | null)[];
onSelectedDaysChange: PickerOnChangeFn;
focusedDay: PickerValidDate | null;
isMonthSwitchingAnimating: boolean;
onFocusedDayChange: (newFocusedDay: PickerValidDate) => void;
onMonthSwitchingAnimationEnd: () => void;
reduceAnimations: boolean;
slideDirection: SlideDirection;
TransitionProps?: Partial<SlideTransitionProps>;
hasFocus: boolean;
onFocusedViewChange?: (newHasFocus: boolean) => void;
gridLabelId?: string;
/**
* Override or extend the styles applied to the component.
*/
classes?: Partial<DayCalendarClasses>;
/**
* Overridable component slots.
* @default {}
*/
slots?: DayCalendarSlots;
/**
* The props used for each component slot.
* @default {}
*/
slotProps?: DayCalendarSlotProps;
}
/**
* @ignore - do not document.
*/
export declare function DayCalendar(inProps: DayCalendarProps): React.JSX.Element;

View file

@ -0,0 +1,440 @@
'use client';
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _extends from "@babel/runtime/helpers/esm/extends";
const _excluded = ["parentProps", "day", "focusedDay", "selectedDays", "isDateDisabled", "currentMonthNumber", "isViewFocused"],
_excluded2 = ["ownerState"];
import * as React from 'react';
import useEventCallback from '@mui/utils/useEventCallback';
import Typography from '@mui/material/Typography';
import useSlotProps from '@mui/utils/useSlotProps';
import { useRtl } from '@mui/system/RtlProvider';
import { styled, useThemeProps } from '@mui/material/styles';
import composeClasses from '@mui/utils/composeClasses';
import clsx from 'clsx';
import { PickersDay } from "../PickersDay/index.js";
import { usePickerAdapter, usePickerTranslations } from "../hooks/index.js";
import { useNow } from "../internals/hooks/useUtils.js";
import { DAY_SIZE, DAY_MARGIN } from "../internals/constants/dimensions.js";
import { PickersSlideTransition } from "./PickersSlideTransition.js";
import { useIsDateDisabled } from "./useIsDateDisabled.js";
import { findClosestEnabledDate, getWeekdays } from "../internals/utils/date-utils.js";
import { getDayCalendarUtilityClass } from "./dayCalendarClasses.js";
import { usePickerDayOwnerState } from "../PickersDay/usePickerDayOwnerState.js";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const useUtilityClasses = classes => {
const slots = {
root: ['root'],
header: ['header'],
weekDayLabel: ['weekDayLabel'],
loadingContainer: ['loadingContainer'],
slideTransition: ['slideTransition'],
monthContainer: ['monthContainer'],
weekContainer: ['weekContainer'],
weekNumberLabel: ['weekNumberLabel'],
weekNumber: ['weekNumber']
};
return composeClasses(slots, getDayCalendarUtilityClass, classes);
};
const weeksContainerHeight = (DAY_SIZE + DAY_MARGIN * 2) * 6;
const PickersCalendarDayRoot = styled('div', {
name: 'MuiDayCalendar',
slot: 'Root'
})({});
const PickersCalendarDayHeader = styled('div', {
name: 'MuiDayCalendar',
slot: 'Header'
})({
display: 'flex',
justifyContent: 'center',
alignItems: 'center'
});
const PickersCalendarWeekDayLabel = styled(Typography, {
name: 'MuiDayCalendar',
slot: 'WeekDayLabel'
})(({
theme
}) => ({
width: 36,
height: 40,
margin: '0 2px',
textAlign: 'center',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
color: (theme.vars || theme).palette.text.secondary
}));
const PickersCalendarWeekNumberLabel = styled(Typography, {
name: 'MuiDayCalendar',
slot: 'WeekNumberLabel'
})(({
theme
}) => ({
width: 36,
height: 40,
margin: '0 2px',
textAlign: 'center',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
color: (theme.vars || theme).palette.text.disabled
}));
const PickersCalendarWeekNumber = styled(Typography, {
name: 'MuiDayCalendar',
slot: 'WeekNumber'
})(({
theme
}) => _extends({}, theme.typography.caption, {
width: DAY_SIZE,
height: DAY_SIZE,
padding: 0,
margin: `0 ${DAY_MARGIN}px`,
color: (theme.vars || theme).palette.text.disabled,
fontSize: '0.75rem',
alignItems: 'center',
justifyContent: 'center',
display: 'inline-flex'
}));
const PickersCalendarLoadingContainer = styled('div', {
name: 'MuiDayCalendar',
slot: 'LoadingContainer'
})({
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
minHeight: weeksContainerHeight
});
const PickersCalendarSlideTransition = styled(PickersSlideTransition, {
name: 'MuiDayCalendar',
slot: 'SlideTransition'
})({
minHeight: weeksContainerHeight
});
const PickersCalendarWeekContainer = styled('div', {
name: 'MuiDayCalendar',
slot: 'MonthContainer'
})({
overflow: 'hidden'
});
const PickersCalendarWeek = styled('div', {
name: 'MuiDayCalendar',
slot: 'WeekContainer'
})({
margin: `${DAY_MARGIN}px 0`,
display: 'flex',
justifyContent: 'center'
});
function WrappedDay(_ref) {
let {
parentProps,
day,
focusedDay,
selectedDays,
isDateDisabled,
currentMonthNumber,
isViewFocused
} = _ref,
other = _objectWithoutPropertiesLoose(_ref, _excluded);
const {
disabled,
disableHighlightToday,
isMonthSwitchingAnimating,
showDaysOutsideCurrentMonth,
slots,
slotProps,
timezone
} = parentProps;
const adapter = usePickerAdapter();
const now = useNow(timezone);
const isFocusableDay = focusedDay != null && adapter.isSameDay(day, focusedDay);
const isFocusedDay = isViewFocused && isFocusableDay;
const isSelected = selectedDays.some(selectedDay => adapter.isSameDay(selectedDay, day));
const isToday = adapter.isSameDay(day, now);
const isDisabled = React.useMemo(() => disabled || isDateDisabled(day), [disabled, isDateDisabled, day]);
const isOutsideCurrentMonth = React.useMemo(() => adapter.getMonth(day) !== currentMonthNumber, [adapter, day, currentMonthNumber]);
const ownerState = usePickerDayOwnerState({
day,
selected: isSelected,
disabled: isDisabled,
today: isToday,
outsideCurrentMonth: isOutsideCurrentMonth,
disableMargin: undefined,
// This prop can only be defined using slotProps.day so the ownerState for useSlotProps cannot have its value.
disableHighlightToday,
showDaysOutsideCurrentMonth
});
const Day = slots?.day ?? PickersDay;
// We don't want to pass to ownerState down, to avoid re-rendering all the day whenever a prop changes.
const _useSlotProps = useSlotProps({
elementType: Day,
externalSlotProps: slotProps?.day,
additionalProps: _extends({
disableHighlightToday,
showDaysOutsideCurrentMonth,
role: 'gridcell',
isAnimating: isMonthSwitchingAnimating,
// it is used in date range dragging logic by accessing `dataset.timestamp`
'data-timestamp': adapter.toJsDate(day).valueOf()
}, other),
ownerState: _extends({}, ownerState, {
day,
isDayDisabled: isDisabled,
isDaySelected: isSelected
})
}),
dayProps = _objectWithoutPropertiesLoose(_useSlotProps, _excluded2);
const isFirstVisibleCell = React.useMemo(() => {
const startOfMonth = adapter.startOfMonth(adapter.setMonth(day, currentMonthNumber));
if (!showDaysOutsideCurrentMonth) {
return adapter.isSameDay(day, startOfMonth);
}
return adapter.isSameDay(day, adapter.startOfWeek(startOfMonth));
}, [currentMonthNumber, day, showDaysOutsideCurrentMonth, adapter]);
const isLastVisibleCell = React.useMemo(() => {
const endOfMonth = adapter.endOfMonth(adapter.setMonth(day, currentMonthNumber));
if (!showDaysOutsideCurrentMonth) {
return adapter.isSameDay(day, endOfMonth);
}
return adapter.isSameDay(day, adapter.endOfWeek(endOfMonth));
}, [currentMonthNumber, day, showDaysOutsideCurrentMonth, adapter]);
return /*#__PURE__*/_jsx(Day, _extends({}, dayProps, {
day: day,
disabled: isDisabled,
autoFocus: !isOutsideCurrentMonth && isFocusedDay,
today: isToday,
outsideCurrentMonth: isOutsideCurrentMonth,
isFirstVisibleCell: isFirstVisibleCell,
isLastVisibleCell: isLastVisibleCell,
selected: isSelected,
tabIndex: isFocusableDay ? 0 : -1,
"aria-selected": isSelected,
"aria-current": isToday ? 'date' : undefined
}));
}
/**
* @ignore - do not document.
*/
export function DayCalendar(inProps) {
const props = useThemeProps({
props: inProps,
name: 'MuiDayCalendar'
});
const adapter = usePickerAdapter();
const {
onFocusedDayChange,
className,
classes: classesProp,
currentMonth,
selectedDays,
focusedDay,
loading,
onSelectedDaysChange,
onMonthSwitchingAnimationEnd,
readOnly,
reduceAnimations,
renderLoading = () => /*#__PURE__*/_jsx("span", {
children: "..."
}),
slideDirection,
TransitionProps,
disablePast,
disableFuture,
minDate,
maxDate,
shouldDisableDate,
shouldDisableMonth,
shouldDisableYear,
dayOfWeekFormatter = date => adapter.format(date, 'weekdayShort').charAt(0).toUpperCase(),
hasFocus,
onFocusedViewChange,
gridLabelId,
displayWeekNumber,
fixedWeekNumber,
timezone
} = props;
const now = useNow(timezone);
const classes = useUtilityClasses(classesProp);
const isRtl = useRtl();
const isDateDisabled = useIsDateDisabled({
shouldDisableDate,
shouldDisableMonth,
shouldDisableYear,
minDate,
maxDate,
disablePast,
disableFuture,
timezone
});
const translations = usePickerTranslations();
const handleDaySelect = useEventCallback(day => {
if (readOnly) {
return;
}
onSelectedDaysChange(day);
});
const focusDay = day => {
if (!isDateDisabled(day)) {
onFocusedDayChange(day);
onFocusedViewChange?.(true);
}
};
const handleKeyDown = useEventCallback((event, day) => {
switch (event.key) {
case 'ArrowUp':
focusDay(adapter.addDays(day, -7));
event.preventDefault();
break;
case 'ArrowDown':
focusDay(adapter.addDays(day, 7));
event.preventDefault();
break;
case 'ArrowLeft':
{
const newFocusedDayDefault = adapter.addDays(day, isRtl ? 1 : -1);
const nextAvailableMonth = adapter.addMonths(day, isRtl ? 1 : -1);
const closestDayToFocus = findClosestEnabledDate({
adapter,
date: newFocusedDayDefault,
minDate: isRtl ? newFocusedDayDefault : adapter.startOfMonth(nextAvailableMonth),
maxDate: isRtl ? adapter.endOfMonth(nextAvailableMonth) : newFocusedDayDefault,
isDateDisabled,
timezone
});
focusDay(closestDayToFocus || newFocusedDayDefault);
event.preventDefault();
break;
}
case 'ArrowRight':
{
const newFocusedDayDefault = adapter.addDays(day, isRtl ? -1 : 1);
const nextAvailableMonth = adapter.addMonths(day, isRtl ? -1 : 1);
const closestDayToFocus = findClosestEnabledDate({
adapter,
date: newFocusedDayDefault,
minDate: isRtl ? adapter.startOfMonth(nextAvailableMonth) : newFocusedDayDefault,
maxDate: isRtl ? newFocusedDayDefault : adapter.endOfMonth(nextAvailableMonth),
isDateDisabled,
timezone
});
focusDay(closestDayToFocus || newFocusedDayDefault);
event.preventDefault();
break;
}
case 'Home':
focusDay(adapter.startOfWeek(day));
event.preventDefault();
break;
case 'End':
focusDay(adapter.endOfWeek(day));
event.preventDefault();
break;
case 'PageUp':
focusDay(adapter.addMonths(day, 1));
event.preventDefault();
break;
case 'PageDown':
focusDay(adapter.addMonths(day, -1));
event.preventDefault();
break;
default:
break;
}
});
const handleFocus = useEventCallback((event, day) => focusDay(day));
const handleBlur = useEventCallback((event, day) => {
if (focusedDay != null && adapter.isSameDay(focusedDay, day)) {
onFocusedViewChange?.(false);
}
});
const currentMonthNumber = adapter.getMonth(currentMonth);
const currentYearNumber = adapter.getYear(currentMonth);
const validSelectedDays = React.useMemo(() => selectedDays.filter(day => !!day).map(day => adapter.startOfDay(day)), [adapter, selectedDays]);
// need a new ref whenever the `key` of the transition changes: https://reactcommunity.org/react-transition-group/transition/#Transition-prop-nodeRef.
const transitionKey = `${currentYearNumber}-${currentMonthNumber}`;
// eslint-disable-next-line react-hooks/exhaustive-deps
const slideNodeRef = React.useMemo(() => /*#__PURE__*/React.createRef(), [transitionKey]);
const weeksToDisplay = React.useMemo(() => {
const toDisplay = adapter.getWeekArray(currentMonth);
let nextMonth = adapter.addMonths(currentMonth, 1);
while (fixedWeekNumber && toDisplay.length < fixedWeekNumber) {
const additionalWeeks = adapter.getWeekArray(nextMonth);
const hasCommonWeek = adapter.isSameDay(toDisplay[toDisplay.length - 1][0], additionalWeeks[0][0]);
additionalWeeks.slice(hasCommonWeek ? 1 : 0).forEach(week => {
if (toDisplay.length < fixedWeekNumber) {
toDisplay.push(week);
}
});
nextMonth = adapter.addMonths(nextMonth, 1);
}
return toDisplay;
}, [currentMonth, fixedWeekNumber, adapter]);
return /*#__PURE__*/_jsxs(PickersCalendarDayRoot, {
role: "grid",
"aria-labelledby": gridLabelId,
className: classes.root,
children: [/*#__PURE__*/_jsxs(PickersCalendarDayHeader, {
role: "row",
className: classes.header,
children: [displayWeekNumber && /*#__PURE__*/_jsx(PickersCalendarWeekNumberLabel, {
variant: "caption",
role: "columnheader",
"aria-label": translations.calendarWeekNumberHeaderLabel,
className: classes.weekNumberLabel,
children: translations.calendarWeekNumberHeaderText
}), getWeekdays(adapter, now).map((weekday, i) => /*#__PURE__*/_jsx(PickersCalendarWeekDayLabel, {
variant: "caption",
role: "columnheader",
"aria-label": adapter.format(weekday, 'weekday'),
className: classes.weekDayLabel,
children: dayOfWeekFormatter(weekday)
}, i.toString()))]
}), loading ? /*#__PURE__*/_jsx(PickersCalendarLoadingContainer, {
className: classes.loadingContainer,
children: renderLoading()
}) : /*#__PURE__*/_jsx(PickersCalendarSlideTransition, _extends({
transKey: transitionKey,
onExited: onMonthSwitchingAnimationEnd,
reduceAnimations: reduceAnimations,
slideDirection: slideDirection,
className: clsx(className, classes.slideTransition)
}, TransitionProps, {
nodeRef: slideNodeRef,
children: /*#__PURE__*/_jsx(PickersCalendarWeekContainer, {
ref: slideNodeRef,
role: "rowgroup",
className: classes.monthContainer,
children: weeksToDisplay.map((week, index) => /*#__PURE__*/_jsxs(PickersCalendarWeek, {
role: "row",
className: classes.weekContainer
// fix issue of announcing row 1 as row 2
// caused by week day labels row
,
"aria-rowindex": index + 1,
children: [displayWeekNumber && /*#__PURE__*/_jsx(PickersCalendarWeekNumber, {
className: classes.weekNumber,
role: "rowheader",
"aria-label": translations.calendarWeekNumberAriaLabelText(adapter.getWeekNumber(week[0])),
children: translations.calendarWeekNumberText(adapter.getWeekNumber(week[0]))
}), week.map((day, dayIndex) => /*#__PURE__*/_jsx(WrappedDay, {
parentProps: props,
day: day,
selectedDays: validSelectedDays,
isViewFocused: hasFocus,
focusedDay: focusedDay,
onKeyDown: handleKeyDown,
onFocus: handleFocus,
onBlur: handleBlur,
onDaySelect: handleDaySelect,
isDateDisabled: isDateDisabled,
currentMonthNumber: currentMonthNumber
// fix issue of announcing column 1 as column 2 when `displayWeekNumber` is enabled
,
"aria-colindex": dayIndex + 1
}, day.toString()))]
}, `week-${week[0]}`))
})
}))]
});
}

View file

@ -0,0 +1,18 @@
import * as React from 'react';
import { PickersFadeTransitionGroupClasses } from "./pickersFadeTransitionGroupClasses.js";
export interface ExportedPickersFadeTransitionGroupProps {
className?: string;
reduceAnimations: boolean;
transKey: React.Key;
/**
* Override or extend the styles applied to the component.
*/
classes?: Partial<PickersFadeTransitionGroupClasses>;
}
export interface PickersFadeTransitionGroupProps extends ExportedPickersFadeTransitionGroupProps {
children: React.ReactElement<any>;
}
/**
* @ignore - do not document.
*/
export declare function PickersFadeTransitionGroup(inProps: PickersFadeTransitionGroupProps): React.JSX.Element;

View file

@ -0,0 +1,63 @@
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
const _excluded = ["children"];
import * as React from 'react';
import clsx from 'clsx';
import { TransitionGroup } from 'react-transition-group';
import Fade from '@mui/material/Fade';
import { styled, useTheme, useThemeProps } from '@mui/material/styles';
import composeClasses from '@mui/utils/composeClasses';
import { getPickersFadeTransitionGroupUtilityClass } from "./pickersFadeTransitionGroupClasses.js";
import { jsx as _jsx } from "react/jsx-runtime";
const useUtilityClasses = classes => {
const slots = {
root: ['root']
};
return composeClasses(slots, getPickersFadeTransitionGroupUtilityClass, classes);
};
const PickersFadeTransitionGroupRoot = styled(TransitionGroup, {
name: 'MuiPickersFadeTransitionGroup',
slot: 'Root'
})({
display: 'block',
position: 'relative'
});
/**
* @ignore - do not document.
*/
export function PickersFadeTransitionGroup(inProps) {
const props = useThemeProps({
props: inProps,
name: 'MuiPickersFadeTransitionGroup'
});
const {
className,
reduceAnimations,
transKey,
classes: classesProp
} = props;
const {
children
} = props,
other = _objectWithoutPropertiesLoose(props, _excluded);
const classes = useUtilityClasses(classesProp);
const theme = useTheme();
if (reduceAnimations) {
return children;
}
return /*#__PURE__*/_jsx(PickersFadeTransitionGroupRoot, {
className: clsx(classes.root, className),
ownerState: other,
children: /*#__PURE__*/_jsx(Fade, {
appear: false,
mountOnEnter: true,
unmountOnExit: true,
timeout: {
appear: theme.transitions.duration.enteringScreen,
enter: theme.transitions.duration.enteringScreen,
exit: 0
},
children: children
}, transKey)
});
}

View file

@ -0,0 +1,25 @@
import * as React from 'react';
import { CSSTransitionProps } from 'react-transition-group/CSSTransition';
import { PickersSlideTransitionClasses } from "./pickersSlideTransitionClasses.js";
import { PickerOwnerState } from "../models/pickers.js";
export type SlideDirection = 'right' | 'left';
export interface PickerSlideTransitionOwnerState extends PickerOwnerState {
slideDirection: SlideDirection;
}
export interface ExportedSlideTransitionProps {
/**
* Override or extend the styles applied to the component.
*/
classes?: Partial<PickersSlideTransitionClasses>;
}
export interface SlideTransitionProps extends Omit<CSSTransitionProps, 'timeout'>, ExportedSlideTransitionProps {
children: React.ReactElement<any>;
className?: string;
reduceAnimations: boolean;
slideDirection: SlideDirection;
transKey: React.Key;
}
/**
* @ignore - do not document.
*/
export declare function PickersSlideTransition(inProps: SlideTransitionProps): React.JSX.Element;

View file

@ -0,0 +1,143 @@
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
const _excluded = ["children", "className", "reduceAnimations", "slideDirection", "transKey", "classes"];
import * as React from 'react';
import clsx from 'clsx';
import { styled, useTheme, useThemeProps } from '@mui/material/styles';
import composeClasses from '@mui/utils/composeClasses';
import { CSSTransition, TransitionGroup } from 'react-transition-group';
import { getPickersSlideTransitionUtilityClass, pickersSlideTransitionClasses } from "./pickersSlideTransitionClasses.js";
import { usePickerPrivateContext } from "../internals/hooks/usePickerPrivateContext.js";
import { jsx as _jsx } from "react/jsx-runtime";
const useUtilityClasses = (classes, ownerState) => {
const {
slideDirection
} = ownerState;
const slots = {
root: ['root'],
exit: ['slideExit'],
enterActive: ['slideEnterActive'],
enter: [`slideEnter-${slideDirection}`],
exitActive: [`slideExitActiveLeft-${slideDirection}`]
};
return composeClasses(slots, getPickersSlideTransitionUtilityClass, classes);
};
const PickersSlideTransitionRoot = styled(TransitionGroup, {
name: 'MuiPickersSlideTransition',
slot: 'Root',
overridesResolver: (_, styles) => [styles.root, {
[`.${pickersSlideTransitionClasses['slideEnter-left']}`]: styles['slideEnter-left']
}, {
[`.${pickersSlideTransitionClasses['slideEnter-right']}`]: styles['slideEnter-right']
}, {
[`.${pickersSlideTransitionClasses.slideEnterActive}`]: styles.slideEnterActive
}, {
[`.${pickersSlideTransitionClasses.slideExit}`]: styles.slideExit
}, {
[`.${pickersSlideTransitionClasses['slideExitActiveLeft-left']}`]: styles['slideExitActiveLeft-left']
}, {
[`.${pickersSlideTransitionClasses['slideExitActiveLeft-right']}`]: styles['slideExitActiveLeft-right']
}]
})(({
theme
}) => {
const slideTransition = theme.transitions.create('transform', {
duration: theme.transitions.duration.complex,
easing: 'cubic-bezier(0.35, 0.8, 0.4, 1)'
});
return {
display: 'block',
position: 'relative',
overflowX: 'hidden',
'& > *': {
position: 'absolute',
top: 0,
right: 0,
left: 0
},
[`& .${pickersSlideTransitionClasses['slideEnter-left']}`]: {
willChange: 'transform',
transform: 'translate(100%)',
zIndex: 1
},
[`& .${pickersSlideTransitionClasses['slideEnter-right']}`]: {
willChange: 'transform',
transform: 'translate(-100%)',
zIndex: 1
},
[`& .${pickersSlideTransitionClasses.slideEnterActive}`]: {
transform: 'translate(0%)',
transition: slideTransition
},
[`& .${pickersSlideTransitionClasses.slideExit}`]: {
transform: 'translate(0%)'
},
[`& .${pickersSlideTransitionClasses['slideExitActiveLeft-left']}`]: {
willChange: 'transform',
transform: 'translate(-100%)',
transition: slideTransition,
zIndex: 0
},
[`& .${pickersSlideTransitionClasses['slideExitActiveLeft-right']}`]: {
willChange: 'transform',
transform: 'translate(100%)',
transition: slideTransition,
zIndex: 0
}
};
});
/**
* @ignore - do not document.
*/
export function PickersSlideTransition(inProps) {
const props = useThemeProps({
props: inProps,
name: 'MuiPickersSlideTransition'
});
const {
children,
className,
reduceAnimations,
slideDirection,
transKey,
classes: classesProp
} = props,
other = _objectWithoutPropertiesLoose(props, _excluded);
const {
ownerState: pickerOwnerState
} = usePickerPrivateContext();
const ownerState = _extends({}, pickerOwnerState, {
slideDirection
});
const classes = useUtilityClasses(classesProp, ownerState);
const theme = useTheme();
if (reduceAnimations) {
return /*#__PURE__*/_jsx("div", {
className: clsx(classes.root, className),
children: children
});
}
const transitionClasses = {
exit: classes.exit,
enterActive: classes.enterActive,
enter: classes.enter,
exitActive: classes.exitActive
};
return /*#__PURE__*/_jsx(PickersSlideTransitionRoot, {
className: clsx(classes.root, className),
childFactory: element => /*#__PURE__*/React.cloneElement(element, {
classNames: transitionClasses
}),
role: "presentation",
ownerState: ownerState,
children: /*#__PURE__*/_jsx(CSSTransition, _extends({
mountOnEnter: true,
unmountOnExit: true,
timeout: theme.transitions.duration.complex,
classNames: transitionClasses
}, other, {
children: children
}), transKey)
});
}

View file

@ -0,0 +1,9 @@
export interface DateCalendarClasses {
/** Styles applied to the root element. */
root: string;
/** Styles applied to the transition group element. */
viewTransitionContainer: string;
}
export type DateCalendarClassKey = keyof DateCalendarClasses;
export declare const getDateCalendarUtilityClass: (slot: string) => string;
export declare const dateCalendarClasses: DateCalendarClasses;

View file

@ -0,0 +1,4 @@
import generateUtilityClass from '@mui/utils/generateUtilityClass';
import generateUtilityClasses from '@mui/utils/generateUtilityClasses';
export const getDateCalendarUtilityClass = slot => generateUtilityClass('MuiDateCalendar', slot);
export const dateCalendarClasses = generateUtilityClasses('MuiDateCalendar', ['root', 'viewTransitionContainer']);

View file

@ -0,0 +1,23 @@
export interface DayCalendarClasses {
/** Styles applied to the root element. */
root: string;
/** Styles applied to the header element. */
header: string;
/** Styles applied to the week day label element. */
weekDayLabel: string;
/** Styles applied to the loading container element. */
loadingContainer: string;
/** Styles applied to the slide transition element. */
slideTransition: string;
/** Styles applied to the month container element. */
monthContainer: string;
/** Styles applied to the week container element. */
weekContainer: string;
/** Styles applied to the week number header */
weekNumberLabel: string;
/** Styles applied to the week number element */
weekNumber: string;
}
export type DayCalendarClassKey = keyof DayCalendarClasses;
export declare const getDayCalendarUtilityClass: (slot: string) => string;
export declare const dayCalendarClasses: DayCalendarClasses;

View file

@ -0,0 +1,4 @@
import generateUtilityClass from '@mui/utils/generateUtilityClass';
import generateUtilityClasses from '@mui/utils/generateUtilityClasses';
export const getDayCalendarUtilityClass = slot => generateUtilityClass('MuiDayCalendar', slot);
export const dayCalendarClasses = generateUtilityClasses('MuiDayCalendar', ['root', 'header', 'weekDayLabel', 'loadingContainer', 'slideTransition', 'monthContainer', 'weekContainer', 'weekNumberLabel', 'weekNumber']);

View file

@ -0,0 +1,12 @@
export { DateCalendar } from "./DateCalendar.js";
export type { DateCalendarProps, DateCalendarSlots, DateCalendarSlotProps } from "./DateCalendar.types.js";
export { getDateCalendarUtilityClass, dateCalendarClasses } from "./dateCalendarClasses.js";
export type { DateCalendarClassKey, DateCalendarClasses } from "./dateCalendarClasses.js";
export { dayCalendarClasses } from "./dayCalendarClasses.js";
export type { DayCalendarClassKey, DayCalendarClasses } from "./dayCalendarClasses.js";
export type { PickersFadeTransitionGroupProps, ExportedPickersFadeTransitionGroupProps } from "./PickersFadeTransitionGroup.js";
export { pickersFadeTransitionGroupClasses } from "./pickersFadeTransitionGroupClasses.js";
export type { PickersFadeTransitionGroupClassKey, PickersFadeTransitionGroupClasses } from "./pickersFadeTransitionGroupClasses.js";
export { pickersSlideTransitionClasses } from "./pickersSlideTransitionClasses.js";
export type { PickersSlideTransitionClassKey, PickersSlideTransitionClasses } from "./pickersSlideTransitionClasses.js";
export type { ExportedSlideTransitionProps } from "./PickersSlideTransition.js";

View file

@ -0,0 +1,5 @@
export { DateCalendar } from "./DateCalendar.js";
export { getDateCalendarUtilityClass, dateCalendarClasses } from "./dateCalendarClasses.js";
export { dayCalendarClasses } from "./dayCalendarClasses.js";
export { pickersFadeTransitionGroupClasses } from "./pickersFadeTransitionGroupClasses.js";
export { pickersSlideTransitionClasses } from "./pickersSlideTransitionClasses.js";

View file

@ -0,0 +1,7 @@
export interface PickersFadeTransitionGroupClasses {
/** Styles applied to the root element. */
root: string;
}
export type PickersFadeTransitionGroupClassKey = keyof PickersFadeTransitionGroupClasses;
export declare const getPickersFadeTransitionGroupUtilityClass: (slot: string) => string;
export declare const pickersFadeTransitionGroupClasses: PickersFadeTransitionGroupClasses;

View file

@ -0,0 +1,4 @@
import generateUtilityClass from '@mui/utils/generateUtilityClass';
import generateUtilityClasses from '@mui/utils/generateUtilityClasses';
export const getPickersFadeTransitionGroupUtilityClass = slot => generateUtilityClass('MuiPickersFadeTransitionGroup', slot);
export const pickersFadeTransitionGroupClasses = generateUtilityClasses('MuiPickersFadeTransitionGroup', ['root']);

View file

@ -0,0 +1,19 @@
export interface PickersSlideTransitionClasses {
/** Styles applied to the root element. */
root: string;
/** Styles applied to content element sliding in from left. */
'slideEnter-left': string;
/** Styles applied to content element sliding in from right. */
'slideEnter-right': string;
/** Styles applied to the element entering (transitioning into) the container. */
slideEnterActive: string;
/** Styles applied to the element leaving (transitioning out of) the container. */
slideExit: string;
/** Styles applied to the element on the left leaving (transitioning out of) the container. */
'slideExitActiveLeft-left': string;
/** Styles applied to the element on the right leaving (transitioning out of) the container. */
'slideExitActiveLeft-right': string;
}
export type PickersSlideTransitionClassKey = keyof PickersSlideTransitionClasses;
export declare const getPickersSlideTransitionUtilityClass: (slot: string) => string;
export declare const pickersSlideTransitionClasses: PickersSlideTransitionClasses;

View file

@ -0,0 +1,4 @@
import generateUtilityClass from '@mui/utils/generateUtilityClass';
import generateUtilityClasses from '@mui/utils/generateUtilityClasses';
export const getPickersSlideTransitionUtilityClass = slot => generateUtilityClass('MuiPickersSlideTransition', slot);
export const pickersSlideTransitionClasses = generateUtilityClasses('MuiPickersSlideTransition', ['root', 'slideEnter-left', 'slideEnter-right', 'slideEnterActive', 'slideExit', 'slideExitActiveLeft-left', 'slideExitActiveLeft-right']);

View file

@ -0,0 +1,27 @@
import { SlideDirection } from "./PickersSlideTransition.js";
import { PickersTimezone, PickerValidDate } from "../models/index.js";
import { DateCalendarDefaultizedProps } from "./DateCalendar.types.js";
interface CalendarState {
currentMonth: PickerValidDate;
focusedDay: PickerValidDate | null;
isMonthSwitchingAnimating: boolean;
slideDirection: SlideDirection;
}
interface UseCalendarStateParameters extends Pick<DateCalendarDefaultizedProps, 'referenceDate' | 'disableFuture' | 'disablePast' | 'minDate' | 'maxDate' | 'onMonthChange' | 'onYearChange' | 'reduceAnimations' | 'shouldDisableDate'> {
value: PickerValidDate | null;
timezone: PickersTimezone;
getCurrentMonthFromVisibleDate: (focusedDay: PickerValidDate, prevMonth: PickerValidDate) => PickerValidDate;
}
interface UseCalendarStateReturnValue {
referenceDate: PickerValidDate;
calendarState: CalendarState;
setVisibleDate: (parameters: SetVisibleDateParameters) => void;
isDateDisabled: (day: PickerValidDate | null) => boolean;
onMonthSwitchingAnimationEnd: () => void;
}
export declare const useCalendarState: (params: UseCalendarStateParameters) => UseCalendarStateReturnValue;
interface SetVisibleDateParameters {
target: PickerValidDate;
reason: 'header-navigation' | 'cell-interaction' | 'controlled-value-change';
}
export {};

View file

@ -0,0 +1,156 @@
'use client';
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import useEventCallback from '@mui/utils/useEventCallback';
import { useIsDateDisabled } from "./useIsDateDisabled.js";
import { singleItemValueManager } from "../internals/utils/valueManagers.js";
import { SECTION_TYPE_GRANULARITY } from "../internals/utils/getDefaultReferenceDate.js";
import { findClosestEnabledDate } from "../internals/utils/date-utils.js";
import { usePickerAdapter } from "../hooks/usePickerAdapter.js";
const createCalendarStateReducer = (reduceAnimations, adapter) => (state, action) => {
switch (action.type) {
case 'setVisibleDate':
return _extends({}, state, {
slideDirection: action.direction,
currentMonth: action.month,
isMonthSwitchingAnimating: !adapter.isSameMonth(action.month, state.currentMonth) && !reduceAnimations && !action.skipAnimation,
focusedDay: action.focusedDay
});
case 'changeMonthTimezone':
{
const newTimezone = action.newTimezone;
if (adapter.getTimezone(state.currentMonth) === newTimezone) {
return state;
}
let newCurrentMonth = adapter.setTimezone(state.currentMonth, newTimezone);
if (adapter.getMonth(newCurrentMonth) !== adapter.getMonth(state.currentMonth)) {
newCurrentMonth = adapter.setMonth(newCurrentMonth, adapter.getMonth(state.currentMonth));
}
return _extends({}, state, {
currentMonth: newCurrentMonth
});
}
case 'finishMonthSwitchingAnimation':
return _extends({}, state, {
isMonthSwitchingAnimating: false
});
default:
throw new Error('missing support');
}
};
export const useCalendarState = params => {
const {
value,
referenceDate: referenceDateProp,
disableFuture,
disablePast,
maxDate,
minDate,
onMonthChange,
onYearChange,
reduceAnimations,
shouldDisableDate,
timezone,
getCurrentMonthFromVisibleDate
} = params;
const adapter = usePickerAdapter();
const reducerFn = React.useRef(createCalendarStateReducer(Boolean(reduceAnimations), adapter)).current;
const referenceDate = React.useMemo(() => {
return singleItemValueManager.getInitialReferenceValue({
value,
adapter,
timezone,
props: params,
referenceDate: referenceDateProp,
granularity: SECTION_TYPE_GRANULARITY.day
});
},
// We want the `referenceDate` to update on prop and `timezone` change (https://github.com/mui/mui-x/issues/10804)
// eslint-disable-next-line react-hooks/exhaustive-deps
[referenceDateProp, timezone]);
const [calendarState, dispatch] = React.useReducer(reducerFn, {
isMonthSwitchingAnimating: false,
focusedDay: referenceDate,
currentMonth: adapter.startOfMonth(referenceDate),
slideDirection: 'left'
});
const isDateDisabled = useIsDateDisabled({
shouldDisableDate,
minDate,
maxDate,
disableFuture,
disablePast,
timezone
});
// Ensure that `calendarState.currentMonth` timezone is updated when `referenceDate` (or timezone changes)
// https://github.com/mui/mui-x/issues/10804
React.useEffect(() => {
dispatch({
type: 'changeMonthTimezone',
newTimezone: adapter.getTimezone(referenceDate)
});
}, [referenceDate, adapter]);
const setVisibleDate = useEventCallback(({
target,
reason
}) => {
if (reason === 'cell-interaction' && calendarState.focusedDay != null && adapter.isSameDay(target, calendarState.focusedDay)) {
return;
}
const skipAnimation = reason === 'cell-interaction';
let month;
let focusedDay;
if (reason === 'cell-interaction') {
month = getCurrentMonthFromVisibleDate(target, calendarState.currentMonth);
focusedDay = target;
} else {
month = adapter.isSameMonth(target, calendarState.currentMonth) ? calendarState.currentMonth : adapter.startOfMonth(target);
focusedDay = target;
// If the date is disabled, we try to find a non-disabled date inside the same month.
if (isDateDisabled(focusedDay)) {
const startOfMonth = adapter.startOfMonth(target);
const endOfMonth = adapter.endOfMonth(target);
focusedDay = findClosestEnabledDate({
adapter,
date: focusedDay,
minDate: adapter.isBefore(minDate, startOfMonth) ? startOfMonth : minDate,
maxDate: adapter.isAfter(maxDate, endOfMonth) ? endOfMonth : maxDate,
disablePast,
disableFuture,
isDateDisabled,
timezone
});
}
}
const hasChangedMonth = !adapter.isSameMonth(calendarState.currentMonth, month);
const hasChangedYear = !adapter.isSameYear(calendarState.currentMonth, month);
if (hasChangedMonth) {
onMonthChange?.(month);
}
if (hasChangedYear) {
onYearChange?.(adapter.startOfYear(month));
}
dispatch({
type: 'setVisibleDate',
month,
direction: adapter.isAfterDay(month, calendarState.currentMonth) ? 'left' : 'right',
focusedDay: calendarState.focusedDay != null && focusedDay != null && adapter.isSameDay(focusedDay, calendarState.focusedDay) ? calendarState.focusedDay : focusedDay,
skipAnimation
});
});
const onMonthSwitchingAnimationEnd = React.useCallback(() => {
dispatch({
type: 'finishMonthSwitchingAnimation'
});
}, []);
return {
referenceDate,
calendarState,
setVisibleDate,
isDateDisabled,
onMonthSwitchingAnimationEnd
};
};

View file

@ -0,0 +1,13 @@
import { DefaultizedProps } from '@mui/x-internals/types';
import { ValidateDateProps } from "../validation/index.js";
import { PickerValidDate, TimezoneProps } from "../models/index.js";
export declare const useIsDateDisabled: ({
shouldDisableDate,
shouldDisableMonth,
shouldDisableYear,
minDate,
maxDate,
disableFuture,
disablePast,
timezone
}: ValidateDateProps & DefaultizedProps<TimezoneProps, "timezone">) => (day: PickerValidDate | null) => boolean;

View file

@ -0,0 +1,31 @@
'use client';
import * as React from 'react';
import { validateDate } from "../validation/index.js";
import { usePickerAdapter } from "../hooks/usePickerAdapter.js";
export const useIsDateDisabled = ({
shouldDisableDate,
shouldDisableMonth,
shouldDisableYear,
minDate,
maxDate,
disableFuture,
disablePast,
timezone
}) => {
const adapter = usePickerAdapter();
return React.useCallback(day => validateDate({
adapter,
value: day,
timezone,
props: {
shouldDisableDate,
shouldDisableMonth,
shouldDisableYear,
minDate,
maxDate,
disableFuture,
disablePast
}
}) !== null, [adapter, shouldDisableDate, shouldDisableMonth, shouldDisableYear, minDate, maxDate, disableFuture, disablePast, timezone]);
};

View file

@ -0,0 +1,17 @@
import * as React from 'react';
import { DateFieldProps } from "./DateField.types.js";
type DateFieldComponent = (<TEnableAccessibleFieldDOMStructure extends boolean = true>(props: DateFieldProps<TEnableAccessibleFieldDOMStructure> & React.RefAttributes<HTMLDivElement>) => React.JSX.Element) & {
propTypes?: any;
};
/**
* Demos:
*
* - [DateField](http://mui.com/x/react-date-pickers/date-field/)
* - [Fields](https://mui.com/x/react-date-pickers/fields/)
*
* API:
*
* - [DateField API](https://mui.com/x/api/date-pickers/date-field/)
*/
declare const DateField: DateFieldComponent;
export { DateField };

View file

@ -0,0 +1,328 @@
'use client';
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
const _excluded = ["slots", "slotProps"];
import * as React from 'react';
import PropTypes from 'prop-types';
import { useThemeProps } from '@mui/material/styles';
import refType from '@mui/utils/refType';
import { useDateField } from "./useDateField.js";
import { PickerFieldUI, useFieldTextFieldProps } from "../internals/components/PickerFieldUI.js";
import { CalendarIcon } from "../icons/index.js";
import { jsx as _jsx } from "react/jsx-runtime";
/**
* Demos:
*
* - [DateField](http://mui.com/x/react-date-pickers/date-field/)
* - [Fields](https://mui.com/x/react-date-pickers/fields/)
*
* API:
*
* - [DateField API](https://mui.com/x/api/date-pickers/date-field/)
*/
const DateField = /*#__PURE__*/React.forwardRef(function DateField(inProps, inRef) {
const themeProps = useThemeProps({
props: inProps,
name: 'MuiDateField'
});
const {
slots,
slotProps
} = themeProps,
other = _objectWithoutPropertiesLoose(themeProps, _excluded);
const textFieldProps = useFieldTextFieldProps({
slotProps,
ref: inRef,
externalForwardedProps: other
});
const fieldResponse = useDateField(textFieldProps);
return /*#__PURE__*/_jsx(PickerFieldUI, {
slots: slots,
slotProps: slotProps,
fieldResponse: fieldResponse,
defaultOpenPickerIcon: CalendarIcon
});
});
if (process.env.NODE_ENV !== "production") DateField.displayName = "DateField";
process.env.NODE_ENV !== "production" ? DateField.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the TypeScript types and run "pnpm proptypes" |
// ----------------------------------------------------------------------
/**
* If `true`, the `input` element is focused during the first mount.
* @default false
*/
autoFocus: PropTypes.bool,
className: PropTypes.string,
/**
* If `true`, a clear button will be shown in the field allowing value clearing.
* @default false
*/
clearable: PropTypes.bool,
/**
* The position at which the clear button is placed.
* If the field is not clearable, the button is not rendered.
* @default 'end'
*/
clearButtonPosition: PropTypes.oneOf(['end', 'start']),
/**
* The color of the component.
* It supports both default and custom theme colors, which can be added as shown in the
* [palette customization guide](https://mui.com/material-ui/customization/palette/#custom-colors).
* @default 'primary'
*/
color: PropTypes.oneOf(['error', 'info', 'primary', 'secondary', 'success', 'warning']),
component: PropTypes.elementType,
/**
* The default value. Use when the component is not controlled.
*/
defaultValue: PropTypes.object,
/**
* If `true`, the component is disabled.
* When disabled, the value cannot be changed and no interaction is possible.
* @default false
*/
disabled: PropTypes.bool,
/**
* If `true`, disable values after the current date for date components, time for time components and both for date time components.
* @default false
*/
disableFuture: PropTypes.bool,
/**
* If `true`, disable values before the current date for date components, time for time components and both for date time components.
* @default false
*/
disablePast: PropTypes.bool,
/**
* @default true
*/
enableAccessibleFieldDOMStructure: PropTypes.bool,
/**
* If `true`, the component is displayed in focused state.
*/
focused: PropTypes.bool,
/**
* Format of the date when rendered in the input(s).
*/
format: PropTypes.string,
/**
* Density of the format when rendered in the input.
* Setting `formatDensity` to `"spacious"` will add a space before and after each `/`, `-` and `.` character.
* @default "dense"
*/
formatDensity: PropTypes.oneOf(['dense', 'spacious']),
/**
* Props applied to the [`FormHelperText`](https://mui.com/material-ui/api/form-helper-text/) element.
* @deprecated Use `slotProps.formHelperText` instead. This prop will be removed in a future major release. See [Migrating from deprecated APIs](https://mui.com/material-ui/migration/migrating-from-deprecated-apis/) for more details.
*/
FormHelperTextProps: PropTypes.object,
/**
* If `true`, the input will take up the full width of its container.
* @default false
*/
fullWidth: PropTypes.bool,
/**
* The helper text content.
*/
helperText: PropTypes.node,
/**
* If `true`, the label is hidden.
* This is used to increase density for a `FilledInput`.
* Be sure to add `aria-label` to the `input` element.
* @default false
*/
hiddenLabel: PropTypes.bool,
/**
* The id of the `input` element.
* Use this prop to make `label` and `helperText` accessible for screen readers.
*/
id: PropTypes.string,
/**
* Props applied to the [`InputLabel`](https://mui.com/material-ui/api/input-label/) element.
* Pointer events like `onClick` are enabled if and only if `shrink` is `true`.
* @deprecated Use `slotProps.inputLabel` instead. This prop will be removed in a future major release. See [Migrating from deprecated APIs](https://mui.com/material-ui/migration/migrating-from-deprecated-apis/) for more details.
*/
InputLabelProps: PropTypes.object,
/**
* [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input#attributes) applied to the `input` element.
* @deprecated Use `slotProps.htmlInput` instead. This prop will be removed in a future major release. See [Migrating from deprecated APIs](https://mui.com/material-ui/migration/migrating-from-deprecated-apis/) for more details.
*/
inputProps: PropTypes.object,
/**
* Props applied to the Input element.
* It will be a [`FilledInput`](https://mui.com/material-ui/api/filled-input/),
* [`OutlinedInput`](https://mui.com/material-ui/api/outlined-input/) or [`Input`](https://mui.com/material-ui/api/input/)
* component depending on the `variant` prop value.
* @deprecated Use `slotProps.input` instead. This prop will be removed in a future major release. See [Migrating from deprecated APIs](https://mui.com/material-ui/migration/migrating-from-deprecated-apis/) for more details.
*/
InputProps: PropTypes.object,
/**
* Pass a ref to the `input` element.
*/
inputRef: refType,
/**
* The label content.
*/
label: PropTypes.node,
/**
* If `dense` or `normal`, will adjust vertical spacing of this and contained components.
* @default 'none'
*/
margin: PropTypes.oneOf(['dense', 'none', 'normal']),
/**
* Maximal selectable date.
* @default 2099-12-31
*/
maxDate: PropTypes.object,
/**
* Minimal selectable date.
* @default 1900-01-01
*/
minDate: PropTypes.object,
/**
* Name attribute of the `input` element.
*/
name: PropTypes.string,
onBlur: PropTypes.func,
/**
* Callback fired when the value changes.
* @template TValue The value type. It will be the same type as `value` or `null`. It can be in `[start, end]` format in case of range value.
* @template TError The validation error type. It will be either `string` or a `null`. It can be in `[start, end]` format in case of range value.
* @param {TValue} value The new value.
* @param {FieldChangeHandlerContext<TError>} context The context containing the validation result of the current value.
*/
onChange: PropTypes.func,
/**
* Callback fired when the clear button is clicked.
*/
onClear: PropTypes.func,
/**
* Callback fired when the error associated with the current value changes.
* When a validation error is detected, the `error` parameter contains a non-null value.
* This can be used to render an appropriate form error.
* @template TError The validation error type. It will be either `string` or a `null`. It can be in `[start, end]` format in case of range value.
* @template TValue The value type. It will be the same type as `value` or `null`. It can be in `[start, end]` format in case of range value.
* @param {TError} error The reason why the current value is not valid.
* @param {TValue} value The value associated with the error.
*/
onError: PropTypes.func,
onFocus: PropTypes.func,
/**
* Callback fired when the selected sections change.
* @param {FieldSelectedSections} newValue The new selected sections.
*/
onSelectedSectionsChange: PropTypes.func,
/**
* The position at which the opening button is placed.
* If there is no Picker to open, the button is not rendered
* @default 'end'
*/
openPickerButtonPosition: PropTypes.oneOf(['end', 'start']),
/**
* If `true`, the component is read-only.
* When read-only, the value cannot be changed but the user can interact with the interface.
* @default false
*/
readOnly: PropTypes.bool,
/**
* The date used to generate a part of the new value that is not present in the format when both `value` and `defaultValue` are empty.
* For example, on time fields it will be used to determine the date to set.
* @default The closest valid date using the validation props, except callbacks such as `shouldDisableDate`. Value is rounded to the most granular section used.
*/
referenceDate: PropTypes.object,
/**
* If `true`, the label is displayed as required and the `input` element is required.
* @default false
*/
required: PropTypes.bool,
/**
* The currently selected sections.
* This prop accepts four formats:
* 1. If a number is provided, the section at this index will be selected.
* 2. If a string of type `FieldSectionType` is provided, the first section with that name will be selected.
* 3. If `"all"` is provided, all the sections will be selected.
* 4. If `null` is provided, no section will be selected.
* If not provided, the selected sections will be handled internally.
*/
selectedSections: PropTypes.oneOfType([PropTypes.oneOf(['all', 'day', 'empty', 'hours', 'meridiem', 'minutes', 'month', 'seconds', 'weekDay', 'year']), PropTypes.number]),
/**
* Disable specific date.
*
* Warning: This function can be called multiple times (for example when rendering date calendar, checking if focus can be moved to a certain date, etc.). Expensive computations can impact performance.
*
* @param {PickerValidDate} day The date to test.
* @returns {boolean} If `true` the date will be disabled.
*/
shouldDisableDate: PropTypes.func,
/**
* Disable specific month.
* @param {PickerValidDate} month The month to test.
* @returns {boolean} If `true`, the month will be disabled.
*/
shouldDisableMonth: PropTypes.func,
/**
* Disable specific year.
* @param {PickerValidDate} year The year to test.
* @returns {boolean} If `true`, the year will be disabled.
*/
shouldDisableYear: PropTypes.func,
/**
* If `true`, the format will respect the leading zeroes (for example on dayjs, the format `M/D/YYYY` will render `8/16/2018`)
* If `false`, the format will always add leading zeroes (for example on dayjs, the format `M/D/YYYY` will render `08/16/2018`)
*
* Warning n°1: Luxon is not able to respect the leading zeroes when using macro tokens (for example "DD"), so `shouldRespectLeadingZeros={true}` might lead to inconsistencies when using `AdapterLuxon`.
*
* Warning n°2: When `shouldRespectLeadingZeros={true}`, the field will add an invisible character on the sections containing a single digit to make sure `onChange` is fired.
* If you need to get the clean value from the input, you can remove this character using `input.value.replace(/\u200e/g, '')`.
*
* Warning n°3: When used in strict mode, dayjs and moment require to respect the leading zeros.
* This mean that when using `shouldRespectLeadingZeros={false}`, if you retrieve the value directly from the input (not listening to `onChange`) and your format contains tokens without leading zeros, the value will not be parsed by your library.
*
* @default false
*/
shouldRespectLeadingZeros: PropTypes.bool,
/**
* The size of the component.
* @default 'medium'
*/
size: PropTypes.oneOf(['medium', 'small']),
/**
* The props used for each component slot.
* @default {}
*/
slotProps: PropTypes.object,
/**
* Overridable component slots.
* @default {}
*/
slots: PropTypes.object,
style: PropTypes.object,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
/**
* Choose which timezone to use for the value.
* Example: "default", "system", "UTC", "America/New_York".
* If you pass values from other timezones to some props, they will be converted to this timezone before being used.
* @see See the {@link https://mui.com/x/react-date-pickers/timezone/ timezones documentation} for more details.
* @default The timezone of the `value` or `defaultValue` prop is defined, 'default' otherwise.
*/
timezone: PropTypes.string,
/**
* The ref object used to imperatively interact with the field.
*/
unstableFieldRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
/**
* The selected value.
* Used when the component is controlled.
*/
value: PropTypes.object,
/**
* The variant to use.
* @default 'outlined'
*/
variant: PropTypes.oneOf(['filled', 'outlined', 'standard'])
} : void 0;
export { DateField };

View file

@ -0,0 +1,22 @@
import { MakeOptional } from '@mui/x-internals/types';
import { DateValidationError, BuiltInFieldTextFieldProps } from "../models/index.js";
import { UseFieldInternalProps } from "../internals/hooks/useField/index.js";
import { ExportedValidateDateProps } from "../validation/validateDate.js";
import { PickerValue } from "../internals/models/index.js";
import { ExportedPickerFieldUIProps, PickerFieldUISlotProps, PickerFieldUISlots } from "../internals/components/PickerFieldUI.js";
export interface UseDateFieldProps<TEnableAccessibleFieldDOMStructure extends boolean> extends MakeOptional<UseFieldInternalProps<PickerValue, TEnableAccessibleFieldDOMStructure, DateValidationError>, 'format'>, ExportedValidateDateProps, ExportedPickerFieldUIProps {}
export type DateFieldProps<TEnableAccessibleFieldDOMStructure extends boolean = true> = UseDateFieldProps<TEnableAccessibleFieldDOMStructure> & Omit<BuiltInFieldTextFieldProps<TEnableAccessibleFieldDOMStructure>, keyof UseDateFieldProps<TEnableAccessibleFieldDOMStructure>> & {
/**
* Overridable component slots.
* @default {}
*/
slots?: DateFieldSlots;
/**
* The props used for each component slot.
* @default {}
*/
slotProps?: DateFieldSlotProps;
};
export type DateFieldOwnerState<TEnableAccessibleFieldDOMStructure extends boolean> = DateFieldProps<TEnableAccessibleFieldDOMStructure>;
export interface DateFieldSlots extends PickerFieldUISlots {}
export interface DateFieldSlotProps extends PickerFieldUISlotProps {}

View file

@ -0,0 +1 @@
export {};

View file

@ -0,0 +1,3 @@
export { DateField } from "./DateField.js";
export { useDateField as unstable_useDateField } from "./useDateField.js";
export type { UseDateFieldProps, DateFieldProps } from "./DateField.types.js";

View file

@ -0,0 +1,2 @@
export { DateField } from "./DateField.js";
export { useDateField as unstable_useDateField } from "./useDateField.js";

View file

@ -0,0 +1,2 @@
import { UseDateFieldProps } from "./DateField.types.js";
export declare const useDateField: <TEnableAccessibleFieldDOMStructure extends boolean, TProps extends UseDateFieldProps<TEnableAccessibleFieldDOMStructure>>(props: TProps) => import("../internals/index.js").UseFieldReturnValue<TEnableAccessibleFieldDOMStructure, TProps>;

View file

@ -0,0 +1,11 @@
'use client';
import { useField } from "../internals/hooks/useField/index.js";
import { useDateManager } from "../managers/index.js";
export const useDateField = props => {
const manager = useDateManager(props);
return useField({
manager,
props
});
};

View file

@ -0,0 +1,17 @@
import * as React from 'react';
import { DatePickerProps } from "./DatePicker.types.js";
type DatePickerComponent = (<TEnableAccessibleFieldDOMStructure extends boolean = true>(props: DatePickerProps<TEnableAccessibleFieldDOMStructure> & React.RefAttributes<HTMLDivElement>) => React.JSX.Element) & {
propTypes?: any;
};
/**
* Demos:
*
* - [DatePicker](https://mui.com/x/react-date-pickers/date-picker/)
* - [Validation](https://mui.com/x/react-date-pickers/validation/)
*
* API:
*
* - [DatePicker API](https://mui.com/x/api/date-pickers/date-picker/)
*/
declare const DatePicker: DatePickerComponent;
export { DatePicker };

View file

@ -0,0 +1,369 @@
'use client';
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
const _excluded = ["desktopModeMediaQuery"];
import * as React from 'react';
import PropTypes from 'prop-types';
import useMediaQuery from '@mui/material/useMediaQuery';
import { useThemeProps } from '@mui/material/styles';
import refType from '@mui/utils/refType';
import { DesktopDatePicker } from "../DesktopDatePicker/index.js";
import { MobileDatePicker } from "../MobileDatePicker/index.js";
import { DEFAULT_DESKTOP_MODE_MEDIA_QUERY } from "../internals/utils/utils.js";
import { jsx as _jsx } from "react/jsx-runtime";
/**
* Demos:
*
* - [DatePicker](https://mui.com/x/react-date-pickers/date-picker/)
* - [Validation](https://mui.com/x/react-date-pickers/validation/)
*
* API:
*
* - [DatePicker API](https://mui.com/x/api/date-pickers/date-picker/)
*/
const DatePicker = /*#__PURE__*/React.forwardRef(function DatePicker(inProps, ref) {
const props = useThemeProps({
props: inProps,
name: 'MuiDatePicker'
});
const {
desktopModeMediaQuery = DEFAULT_DESKTOP_MODE_MEDIA_QUERY
} = props,
other = _objectWithoutPropertiesLoose(props, _excluded);
// defaults to `true` in environments where `window.matchMedia` would not be available (i.e. test/jsdom)
const isDesktop = useMediaQuery(desktopModeMediaQuery, {
defaultMatches: true
});
if (isDesktop) {
return /*#__PURE__*/_jsx(DesktopDatePicker, _extends({
ref: ref
}, other));
}
return /*#__PURE__*/_jsx(MobileDatePicker, _extends({
ref: ref
}, other));
});
if (process.env.NODE_ENV !== "production") DatePicker.displayName = "DatePicker";
process.env.NODE_ENV !== "production" ? DatePicker.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the TypeScript types and run "pnpm proptypes" |
// ----------------------------------------------------------------------
/**
* If `true`, the main element is focused during the first mount.
* This main element is:
* - the element chosen by the visible view if any (i.e: the selected day on the `day` view).
* - the `input` element if there is a field rendered.
*/
autoFocus: PropTypes.bool,
className: PropTypes.string,
/**
* If `true`, the Picker will close after submitting the full date.
* @default `true` for desktop, `false` for mobile (based on the chosen wrapper and `desktopModeMediaQuery` prop).
*/
closeOnSelect: PropTypes.bool,
/**
* Formats the day of week displayed in the calendar header.
* @param {PickerValidDate} date The date of the day of week provided by the adapter.
* @returns {string} The name to display.
* @default (date: PickerValidDate) => adapter.format(date, 'weekdayShort').charAt(0).toUpperCase()
*/
dayOfWeekFormatter: PropTypes.func,
/**
* The default value.
* Used when the component is not controlled.
*/
defaultValue: PropTypes.object,
/**
* CSS media query when `Mobile` mode will be changed to `Desktop`.
* @default '@media (pointer: fine)'
* @example '@media (min-width: 720px)' or theme.breakpoints.up("sm")
*/
desktopModeMediaQuery: PropTypes.string,
/**
* If `true`, the component is disabled.
* When disabled, the value cannot be changed and no interaction is possible.
* @default false
*/
disabled: PropTypes.bool,
/**
* If `true`, disable values after the current date for date components, time for time components and both for date time components.
* @default false
*/
disableFuture: PropTypes.bool,
/**
* If `true`, today's date is rendering without highlighting with circle.
* @default false
*/
disableHighlightToday: PropTypes.bool,
/**
* If `true`, the button to open the Picker will not be rendered (it will only render the field).
* @deprecated Use the [field component](https://mui.com/x/react-date-pickers/fields/) instead.
* @default false
*/
disableOpenPicker: PropTypes.bool,
/**
* If `true`, disable values before the current date for date components, time for time components and both for date time components.
* @default false
*/
disablePast: PropTypes.bool,
/**
* If `true`, the week number will be display in the calendar.
*/
displayWeekNumber: PropTypes.bool,
/**
* @default true
*/
enableAccessibleFieldDOMStructure: PropTypes.any,
/**
* The day view will show as many weeks as needed after the end of the current month to match this value.
* Put it to 6 to have a fixed number of weeks in Gregorian calendars
*/
fixedWeekNumber: PropTypes.number,
/**
* Format of the date when rendered in the input(s).
* Defaults to localized format based on the used `views`.
*/
format: PropTypes.string,
/**
* Density of the format when rendered in the input.
* Setting `formatDensity` to `"spacious"` will add a space before and after each `/`, `-` and `.` character.
* @default "dense"
*/
formatDensity: PropTypes.oneOf(['dense', 'spacious']),
/**
* Pass a ref to the `input` element.
*/
inputRef: refType,
/**
* The label content.
*/
label: PropTypes.node,
/**
* If `true`, calls `renderLoading` instead of rendering the day calendar.
* Can be used to preload information and show it in calendar.
* @default false
*/
loading: PropTypes.bool,
/**
* Locale for components texts.
* Allows overriding texts coming from `LocalizationProvider` and `theme`.
*/
localeText: PropTypes.object,
/**
* Maximal selectable date.
* @default 2099-12-31
*/
maxDate: PropTypes.object,
/**
* Minimal selectable date.
* @default 1900-01-01
*/
minDate: PropTypes.object,
/**
* Months rendered per row.
* @default 3
*/
monthsPerRow: PropTypes.oneOf([3, 4]),
/**
* Name attribute used by the `input` element in the Field.
*/
name: PropTypes.string,
/**
* Callback fired when the value is accepted.
* @template TValue The value type. It will be the same type as `value` or `null`. It can be in `[start, end]` format in case of range value.
* @template TError The validation error type. It will be either `string` or a `null`. It can be in `[start, end]` format in case of range value.
* @param {TValue} value The value that was just accepted.
* @param {FieldChangeHandlerContext<TError>} context The context containing the validation result of the current value.
*/
onAccept: PropTypes.func,
/**
* Callback fired when the value changes.
* @template TValue The value type. It will be the same type as `value` or `null`. It can be in `[start, end]` format in case of range value.
* @template TError The validation error type. It will be either `string` or a `null`. It can be in `[start, end]` format in case of range value.
* @param {TValue} value The new value.
* @param {FieldChangeHandlerContext<TError>} context The context containing the validation result of the current value.
*/
onChange: PropTypes.func,
/**
* Callback fired when the popup requests to be closed.
* Use in controlled mode (see `open`).
*/
onClose: PropTypes.func,
/**
* Callback fired when the error associated with the current value changes.
* When a validation error is detected, the `error` parameter contains a non-null value.
* This can be used to render an appropriate form error.
* @template TError The validation error type. It will be either `string` or a `null`. It can be in `[start, end]` format in case of range value.
* @template TValue The value type. It will be the same type as `value` or `null`. It can be in `[start, end]` format in case of range value.
* @param {TError} error The reason why the current value is not valid.
* @param {TValue} value The value associated with the error.
*/
onError: PropTypes.func,
/**
* Callback fired on month change.
* @param {PickerValidDate} month The new month.
*/
onMonthChange: PropTypes.func,
/**
* Callback fired when the popup requests to be opened.
* Use in controlled mode (see `open`).
*/
onOpen: PropTypes.func,
/**
* Callback fired when the selected sections change.
* @param {FieldSelectedSections} newValue The new selected sections.
*/
onSelectedSectionsChange: PropTypes.func,
/**
* Callback fired on view change.
* @template TView Type of the view. It will vary based on the Picker type and the `views` it uses.
* @param {TView} view The new view.
*/
onViewChange: PropTypes.func,
/**
* Callback fired on year change.
* @param {PickerValidDate} year The new year.
*/
onYearChange: PropTypes.func,
/**
* Control the popup or dialog open state.
* @default false
*/
open: PropTypes.bool,
/**
* The default visible view.
* Used when the component view is not controlled.
* Must be a valid option from `views` list.
*/
openTo: PropTypes.oneOf(['day', 'month', 'year']),
/**
* Force rendering in particular orientation.
*/
orientation: PropTypes.oneOf(['landscape', 'portrait']),
/**
* If `true`, the component is read-only.
* When read-only, the value cannot be changed but the user can interact with the interface.
* @default false
*/
readOnly: PropTypes.bool,
/**
* If `true`, disable heavy animations.
* @default `@media(prefers-reduced-motion: reduce)` || `navigator.userAgent` matches Android <10 or iOS <13
*/
reduceAnimations: PropTypes.bool,
/**
* The date used to generate the new value when both `value` and `defaultValue` are empty.
* @default The closest valid date-time using the validation props, except callbacks like `shouldDisable<...>`.
*/
referenceDate: PropTypes.object,
/**
* Component displaying when passed `loading` true.
* @returns {React.ReactNode} The node to render when loading.
* @default () => <span>...</span>
*/
renderLoading: PropTypes.func,
/**
* The currently selected sections.
* This prop accepts four formats:
* 1. If a number is provided, the section at this index will be selected.
* 2. If a string of type `FieldSectionType` is provided, the first section with that name will be selected.
* 3. If `"all"` is provided, all the sections will be selected.
* 4. If `null` is provided, no section will be selected.
* If not provided, the selected sections will be handled internally.
*/
selectedSections: PropTypes.oneOfType([PropTypes.oneOf(['all', 'day', 'empty', 'hours', 'meridiem', 'minutes', 'month', 'seconds', 'weekDay', 'year']), PropTypes.number]),
/**
* Disable specific date.
*
* Warning: This function can be called multiple times (for example when rendering date calendar, checking if focus can be moved to a certain date, etc.). Expensive computations can impact performance.
*
* @param {PickerValidDate} day The date to test.
* @returns {boolean} If `true` the date will be disabled.
*/
shouldDisableDate: PropTypes.func,
/**
* Disable specific month.
* @param {PickerValidDate} month The month to test.
* @returns {boolean} If `true`, the month will be disabled.
*/
shouldDisableMonth: PropTypes.func,
/**
* Disable specific year.
* @param {PickerValidDate} year The year to test.
* @returns {boolean} If `true`, the year will be disabled.
*/
shouldDisableYear: PropTypes.func,
/**
* If `true`, days outside the current month are rendered:
*
* - if `fixedWeekNumber` is defined, renders days to have the weeks requested.
*
* - if `fixedWeekNumber` is not defined, renders day to fill the first and last week of the current month.
*
* - ignored if `calendars` equals more than `1` on range pickers.
* @default false
*/
showDaysOutsideCurrentMonth: PropTypes.bool,
/**
* The props used for each component slot.
* @default {}
*/
slotProps: PropTypes.object,
/**
* Overridable component slots.
* @default {}
*/
slots: PropTypes.object,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
/**
* Choose which timezone to use for the value.
* Example: "default", "system", "UTC", "America/New_York".
* If you pass values from other timezones to some props, they will be converted to this timezone before being used.
* @see See the {@link https://mui.com/x/react-date-pickers/timezone/ timezones documentation} for more details.
* @default The timezone of the `value` or `defaultValue` prop is defined, 'default' otherwise.
*/
timezone: PropTypes.string,
/**
* The selected value.
* Used when the component is controlled.
*/
value: PropTypes.object,
/**
* The visible view.
* Used when the component view is controlled.
* Must be a valid option from `views` list.
*/
view: PropTypes.oneOf(['day', 'month', 'year']),
/**
* Define custom view renderers for each section.
* If `null`, the section will only have field editing.
* If `undefined`, internally defined view will be used.
*/
viewRenderers: PropTypes.shape({
day: PropTypes.func,
month: PropTypes.func,
year: PropTypes.func
}),
/**
* Available views.
*/
views: PropTypes.arrayOf(PropTypes.oneOf(['day', 'month', 'year']).isRequired),
/**
* Years are displayed in ascending (chronological) order by default.
* If `desc`, years are displayed in descending order.
* @default 'asc'
*/
yearsOrder: PropTypes.oneOf(['asc', 'desc']),
/**
* Years rendered per row.
* @default 4 on desktop, 3 on mobile
*/
yearsPerRow: PropTypes.oneOf([3, 4])
} : void 0;
export { DatePicker };

View file

@ -0,0 +1,38 @@
import { DesktopDatePickerProps, DesktopDatePickerSlots, DesktopDatePickerSlotProps } from "../DesktopDatePicker/index.js";
import { BaseSingleInputFieldProps } from "../internals/models/index.js";
import { MobileDatePickerProps, MobileDatePickerSlots, MobileDatePickerSlotProps } from "../MobileDatePicker/index.js";
import { ValidateDateProps } from "../validation/validateDate.js";
export interface DatePickerSlots extends DesktopDatePickerSlots, MobileDatePickerSlots {}
export interface DatePickerSlotProps<TEnableAccessibleFieldDOMStructure extends boolean> extends DesktopDatePickerSlotProps<TEnableAccessibleFieldDOMStructure>, MobileDatePickerSlotProps<TEnableAccessibleFieldDOMStructure> {}
export interface DatePickerProps<TEnableAccessibleFieldDOMStructure extends boolean = true> extends DesktopDatePickerProps<TEnableAccessibleFieldDOMStructure>, MobileDatePickerProps<TEnableAccessibleFieldDOMStructure> {
/**
* CSS media query when `Mobile` mode will be changed to `Desktop`.
* @default '@media (pointer: fine)'
* @example '@media (min-width: 720px)' or theme.breakpoints.up("sm")
*/
desktopModeMediaQuery?: string;
/**
* Overridable component slots.
* @default {}
*/
slots?: DatePickerSlots;
/**
* The props used for each component slot.
* @default {}
*/
slotProps?: DatePickerSlotProps<TEnableAccessibleFieldDOMStructure>;
/**
* Years rendered per row.
* @default 4 on desktop, 3 on mobile
*/
yearsPerRow?: 3 | 4;
/**
* If `true`, the Picker will close after submitting the full date.
* @default `true` for desktop, `false` for mobile (based on the chosen wrapper and `desktopModeMediaQuery` prop).
*/
closeOnSelect?: boolean;
}
/**
* Props the field can receive when used inside a Date Picker (<DatePicker />, <DesktopDatePicker /> or <MobileDatePicker /> component).
*/
export type DatePickerFieldProps = ValidateDateProps & BaseSingleInputFieldProps;

View file

@ -0,0 +1 @@
export {};

View file

@ -0,0 +1,25 @@
import * as React from 'react';
import { BaseToolbarProps, ExportedBaseToolbarProps } from "../internals/models/props/toolbar.js";
import { DatePickerToolbarClasses } from "./datePickerToolbarClasses.js";
export interface DatePickerToolbarProps extends BaseToolbarProps, ExportedDatePickerToolbarProps {}
export interface ExportedDatePickerToolbarProps extends ExportedBaseToolbarProps {
/**
* Override or extend the styles applied to the component.
*/
classes?: Partial<DatePickerToolbarClasses>;
}
type DatePickerToolbarComponent = ((props: DatePickerToolbarProps & React.RefAttributes<HTMLDivElement>) => React.JSX.Element) & {
propTypes?: any;
};
/**
* Demos:
*
* - [DatePicker](https://mui.com/x/react-date-pickers/date-picker/)
* - [Custom components](https://mui.com/x/react-date-pickers/custom-components/)
*
* API:
*
* - [DatePickerToolbar API](https://mui.com/x/api/date-pickers/date-picker-toolbar/)
*/
export declare const DatePickerToolbar: DatePickerToolbarComponent;
export {};

View file

@ -0,0 +1,127 @@
'use client';
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
const _excluded = ["toolbarFormat", "toolbarPlaceholder", "className", "classes"];
import * as React from 'react';
import clsx from 'clsx';
import PropTypes from 'prop-types';
import Typography from '@mui/material/Typography';
import { styled, useThemeProps } from '@mui/material/styles';
import composeClasses from '@mui/utils/composeClasses';
import { PickersToolbar } from "../internals/components/PickersToolbar.js";
import { usePickerAdapter, usePickerContext, usePickerTranslations } from "../hooks/index.js";
import { getDatePickerToolbarUtilityClass } from "./datePickerToolbarClasses.js";
import { resolveDateFormat } from "../internals/utils/date-utils.js";
import { useToolbarOwnerState } from "../internals/hooks/useToolbarOwnerState.js";
import { jsx as _jsx } from "react/jsx-runtime";
const useUtilityClasses = classes => {
const slots = {
root: ['root'],
title: ['title']
};
return composeClasses(slots, getDatePickerToolbarUtilityClass, classes);
};
const DatePickerToolbarRoot = styled(PickersToolbar, {
name: 'MuiDatePickerToolbar',
slot: 'Root'
})({});
const DatePickerToolbarTitle = styled(Typography, {
name: 'MuiDatePickerToolbar',
slot: 'Title'
})({
variants: [{
props: {
pickerOrientation: 'landscape'
},
style: {
margin: 'auto 16px auto auto'
}
}]
});
/**
* Demos:
*
* - [DatePicker](https://mui.com/x/react-date-pickers/date-picker/)
* - [Custom components](https://mui.com/x/react-date-pickers/custom-components/)
*
* API:
*
* - [DatePickerToolbar API](https://mui.com/x/api/date-pickers/date-picker-toolbar/)
*/
export const DatePickerToolbar = /*#__PURE__*/React.forwardRef(function DatePickerToolbar(inProps, ref) {
const props = useThemeProps({
props: inProps,
name: 'MuiDatePickerToolbar'
});
const {
toolbarFormat,
toolbarPlaceholder = '',
className,
classes: classesProp
} = props,
other = _objectWithoutPropertiesLoose(props, _excluded);
const adapter = usePickerAdapter();
const {
value,
views,
orientation
} = usePickerContext();
const translations = usePickerTranslations();
const ownerState = useToolbarOwnerState();
const classes = useUtilityClasses(classesProp);
const dateText = React.useMemo(() => {
if (!adapter.isValid(value)) {
return toolbarPlaceholder;
}
const formatFromViews = resolveDateFormat(adapter, {
format: toolbarFormat,
views
}, true);
return adapter.formatByString(value, formatFromViews);
}, [value, toolbarFormat, toolbarPlaceholder, adapter, views]);
return /*#__PURE__*/_jsx(DatePickerToolbarRoot, _extends({
ref: ref,
toolbarTitle: translations.datePickerToolbarTitle,
className: clsx(classes.root, className)
}, other, {
children: /*#__PURE__*/_jsx(DatePickerToolbarTitle, {
variant: "h4",
align: orientation === 'landscape' ? 'left' : 'center',
ownerState: ownerState,
className: classes.title,
children: dateText
})
}));
});
if (process.env.NODE_ENV !== "production") DatePickerToolbar.displayName = "DatePickerToolbar";
process.env.NODE_ENV !== "production" ? DatePickerToolbar.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the TypeScript types and run "pnpm proptypes" |
// ----------------------------------------------------------------------
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
className: PropTypes.string,
/**
* If `true`, show the toolbar even in desktop mode.
* @default `true` for Desktop, `false` for Mobile.
*/
hidden: PropTypes.bool,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
titleId: PropTypes.string,
/**
* Toolbar date format.
*/
toolbarFormat: PropTypes.string,
/**
* Toolbar value placeholderit is displayed when the value is empty.
* @default ""
*/
toolbarPlaceholder: PropTypes.node
} : void 0;

View file

@ -0,0 +1,9 @@
export interface DatePickerToolbarClasses {
/** Styles applied to the root element. */
root: string;
/** Styles applied to the title element. */
title: string;
}
export type DatePickerToolbarClassKey = keyof DatePickerToolbarClasses;
export declare function getDatePickerToolbarUtilityClass(slot: string): string;
export declare const datePickerToolbarClasses: DatePickerToolbarClasses;

View file

@ -0,0 +1,6 @@
import generateUtilityClass from '@mui/utils/generateUtilityClass';
import generateUtilityClasses from '@mui/utils/generateUtilityClasses';
export function getDatePickerToolbarUtilityClass(slot) {
return generateUtilityClass('MuiDatePickerToolbar', slot);
}
export const datePickerToolbarClasses = generateUtilityClasses('MuiDatePickerToolbar', ['root', 'title']);

View file

@ -0,0 +1,6 @@
export { DatePicker } from "./DatePicker.js";
export type { DatePickerProps, DatePickerSlots, DatePickerSlotProps, DatePickerFieldProps } from "./DatePicker.types.js";
export { DatePickerToolbar } from "./DatePickerToolbar.js";
export type { DatePickerToolbarProps } from "./DatePickerToolbar.js";
export { datePickerToolbarClasses } from "./datePickerToolbarClasses.js";
export type { DatePickerToolbarClassKey, DatePickerToolbarClasses } from "./datePickerToolbarClasses.js";

View file

@ -0,0 +1,3 @@
export { DatePicker } from "./DatePicker.js";
export { DatePickerToolbar } from "./DatePickerToolbar.js";
export { datePickerToolbarClasses } from "./datePickerToolbarClasses.js";

View file

@ -0,0 +1,43 @@
import * as React from 'react';
import { DefaultizedProps } from '@mui/x-internals/types';
import { DateCalendarSlots, DateCalendarSlotProps, ExportedDateCalendarProps } from "../DateCalendar/DateCalendar.types.js";
import { DateValidationError, DateView } from "../models/index.js";
import { BasePickerInputProps } from "../internals/models/props/basePickerProps.js";
import { LocalizedComponent } from "../locales/utils/pickersLocaleTextApi.js";
import { DatePickerToolbarProps, ExportedDatePickerToolbarProps } from "./DatePickerToolbar.js";
import { PickerViewRendererLookup } from "../internals/hooks/usePicker/index.js";
import { DateViewRendererProps } from "../dateViewRenderers/index.js";
import { PickerValue } from "../internals/models/index.js";
import { ValidateDatePropsToDefault } from "../validation/validateDate.js";
export interface BaseDatePickerSlots extends DateCalendarSlots {
/**
* Custom component for the toolbar rendered above the views.
* @default DatePickerToolbar
*/
toolbar?: React.JSXElementConstructor<DatePickerToolbarProps>;
}
export interface BaseDatePickerSlotProps extends DateCalendarSlotProps {
toolbar?: ExportedDatePickerToolbarProps;
}
export type DatePickerViewRenderers<TView extends DateView> = PickerViewRendererLookup<PickerValue, TView, DateViewRendererProps<TView>>;
export interface BaseDatePickerProps extends BasePickerInputProps<PickerValue, DateView, DateValidationError>, ExportedDateCalendarProps {
/**
* Overridable component slots.
* @default {}
*/
slots?: BaseDatePickerSlots;
/**
* The props used for each component slot.
* @default {}
*/
slotProps?: BaseDatePickerSlotProps;
/**
* Define custom view renderers for each section.
* If `null`, the section will only have field editing.
* If `undefined`, internally defined view will be used.
*/
viewRenderers?: Partial<DatePickerViewRenderers<DateView>>;
}
type UseDatePickerDefaultizedProps<Props extends BaseDatePickerProps> = LocalizedComponent<DefaultizedProps<Props, 'views' | 'openTo' | ValidateDatePropsToDefault>>;
export declare function useDatePickerDefaultizedProps<Props extends BaseDatePickerProps>(props: Props, name: string): UseDatePickerDefaultizedProps<Props>;
export {};

View file

@ -0,0 +1,33 @@
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import { useThemeProps } from '@mui/material/styles';
import { applyDefaultViewProps } from "../internals/utils/views.js";
import { DatePickerToolbar } from "./DatePickerToolbar.js";
import { useApplyDefaultValuesToDateValidationProps } from "../managers/useDateManager.js";
export function useDatePickerDefaultizedProps(props, name) {
const themeProps = useThemeProps({
props,
name
});
const validationProps = useApplyDefaultValuesToDateValidationProps(themeProps);
const localeText = React.useMemo(() => {
if (themeProps.localeText?.toolbarTitle == null) {
return themeProps.localeText;
}
return _extends({}, themeProps.localeText, {
datePickerToolbarTitle: themeProps.localeText.toolbarTitle
});
}, [themeProps.localeText]);
return _extends({}, themeProps, validationProps, {
localeText
}, applyDefaultViewProps({
views: themeProps.views,
openTo: themeProps.openTo,
defaultViews: ['year', 'day'],
defaultOpenTo: 'day'
}), {
slots: _extends({
toolbar: DatePickerToolbar
}, themeProps.slots)
});
}

View file

@ -0,0 +1,17 @@
import * as React from 'react';
import { DateTimeFieldProps } from "./DateTimeField.types.js";
type DateTimeFieldComponent = (<TEnableAccessibleFieldDOMStructure extends boolean = true>(props: DateTimeFieldProps<TEnableAccessibleFieldDOMStructure> & React.RefAttributes<HTMLDivElement>) => React.JSX.Element) & {
propTypes?: any;
};
/**
* Demos:
*
* - [DateTimeField](http://mui.com/x/react-date-pickers/date-time-field/)
* - [Fields](https://mui.com/x/react-date-pickers/fields/)
*
* API:
*
* - [DateTimeField API](https://mui.com/x/api/date-pickers/date-time-field/)
*/
declare const DateTimeField: DateTimeFieldComponent;
export { DateTimeField };

View file

@ -0,0 +1,368 @@
'use client';
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
const _excluded = ["slots", "slotProps"];
import * as React from 'react';
import PropTypes from 'prop-types';
import { useThemeProps } from '@mui/material/styles';
import refType from '@mui/utils/refType';
import { useDateTimeField } from "./useDateTimeField.js";
import { PickerFieldUI, useFieldTextFieldProps } from "../internals/components/PickerFieldUI.js";
import { CalendarIcon } from "../icons/index.js";
import { jsx as _jsx } from "react/jsx-runtime";
/**
* Demos:
*
* - [DateTimeField](http://mui.com/x/react-date-pickers/date-time-field/)
* - [Fields](https://mui.com/x/react-date-pickers/fields/)
*
* API:
*
* - [DateTimeField API](https://mui.com/x/api/date-pickers/date-time-field/)
*/
const DateTimeField = /*#__PURE__*/React.forwardRef(function DateTimeField(inProps, inRef) {
const themeProps = useThemeProps({
props: inProps,
name: 'MuiDateTimeField'
});
const {
slots,
slotProps
} = themeProps,
other = _objectWithoutPropertiesLoose(themeProps, _excluded);
const textFieldProps = useFieldTextFieldProps({
slotProps,
ref: inRef,
externalForwardedProps: other
});
const fieldResponse = useDateTimeField(textFieldProps);
return /*#__PURE__*/_jsx(PickerFieldUI, {
slots: slots,
slotProps: slotProps,
fieldResponse: fieldResponse,
defaultOpenPickerIcon: CalendarIcon
});
});
if (process.env.NODE_ENV !== "production") DateTimeField.displayName = "DateTimeField";
process.env.NODE_ENV !== "production" ? DateTimeField.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the TypeScript types and run "pnpm proptypes" |
// ----------------------------------------------------------------------
/**
* 12h/24h view for hour selection clock.
* @default adapter.is12HourCycleInCurrentLocale()
*/
ampm: PropTypes.bool,
/**
* If `true`, the `input` element is focused during the first mount.
* @default false
*/
autoFocus: PropTypes.bool,
className: PropTypes.string,
/**
* If `true`, a clear button will be shown in the field allowing value clearing.
* @default false
*/
clearable: PropTypes.bool,
/**
* The position at which the clear button is placed.
* If the field is not clearable, the button is not rendered.
* @default 'end'
*/
clearButtonPosition: PropTypes.oneOf(['end', 'start']),
/**
* The color of the component.
* It supports both default and custom theme colors, which can be added as shown in the
* [palette customization guide](https://mui.com/material-ui/customization/palette/#custom-colors).
* @default 'primary'
*/
color: PropTypes.oneOf(['error', 'info', 'primary', 'secondary', 'success', 'warning']),
component: PropTypes.elementType,
/**
* The default value. Use when the component is not controlled.
*/
defaultValue: PropTypes.object,
/**
* If `true`, the component is disabled.
* When disabled, the value cannot be changed and no interaction is possible.
* @default false
*/
disabled: PropTypes.bool,
/**
* If `true`, disable values after the current date for date components, time for time components and both for date time components.
* @default false
*/
disableFuture: PropTypes.bool,
/**
* Do not ignore date part when validating min/max time.
* @default false
*/
disableIgnoringDatePartForTimeValidation: PropTypes.bool,
/**
* If `true`, disable values before the current date for date components, time for time components and both for date time components.
* @default false
*/
disablePast: PropTypes.bool,
/**
* @default true
*/
enableAccessibleFieldDOMStructure: PropTypes.bool,
/**
* If `true`, the component is displayed in focused state.
*/
focused: PropTypes.bool,
/**
* Format of the date when rendered in the input(s).
*/
format: PropTypes.string,
/**
* Density of the format when rendered in the input.
* Setting `formatDensity` to `"spacious"` will add a space before and after each `/`, `-` and `.` character.
* @default "dense"
*/
formatDensity: PropTypes.oneOf(['dense', 'spacious']),
/**
* Props applied to the [`FormHelperText`](https://mui.com/material-ui/api/form-helper-text/) element.
* @deprecated Use `slotProps.formHelperText` instead. This prop will be removed in a future major release. See [Migrating from deprecated APIs](https://mui.com/material-ui/migration/migrating-from-deprecated-apis/) for more details.
*/
FormHelperTextProps: PropTypes.object,
/**
* If `true`, the input will take up the full width of its container.
* @default false
*/
fullWidth: PropTypes.bool,
/**
* The helper text content.
*/
helperText: PropTypes.node,
/**
* If `true`, the label is hidden.
* This is used to increase density for a `FilledInput`.
* Be sure to add `aria-label` to the `input` element.
* @default false
*/
hiddenLabel: PropTypes.bool,
/**
* The id of the `input` element.
* Use this prop to make `label` and `helperText` accessible for screen readers.
*/
id: PropTypes.string,
/**
* Props applied to the [`InputLabel`](https://mui.com/material-ui/api/input-label/) element.
* Pointer events like `onClick` are enabled if and only if `shrink` is `true`.
* @deprecated Use `slotProps.inputLabel` instead. This prop will be removed in a future major release. See [Migrating from deprecated APIs](https://mui.com/material-ui/migration/migrating-from-deprecated-apis/) for more details.
*/
InputLabelProps: PropTypes.object,
/**
* [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input#attributes) applied to the `input` element.
* @deprecated Use `slotProps.htmlInput` instead. This prop will be removed in a future major release. See [Migrating from deprecated APIs](https://mui.com/material-ui/migration/migrating-from-deprecated-apis/) for more details.
*/
inputProps: PropTypes.object,
/**
* Props applied to the Input element.
* It will be a [`FilledInput`](https://mui.com/material-ui/api/filled-input/),
* [`OutlinedInput`](https://mui.com/material-ui/api/outlined-input/) or [`Input`](https://mui.com/material-ui/api/input/)
* component depending on the `variant` prop value.
* @deprecated Use `slotProps.input` instead. This prop will be removed in a future major release. See [Migrating from deprecated APIs](https://mui.com/material-ui/migration/migrating-from-deprecated-apis/) for more details.
*/
InputProps: PropTypes.object,
/**
* Pass a ref to the `input` element.
*/
inputRef: refType,
/**
* The label content.
*/
label: PropTypes.node,
/**
* If `dense` or `normal`, will adjust vertical spacing of this and contained components.
* @default 'none'
*/
margin: PropTypes.oneOf(['dense', 'none', 'normal']),
/**
* Maximal selectable date.
* @default 2099-12-31
*/
maxDate: PropTypes.object,
/**
* Maximal selectable moment of time with binding to date, to set max time in each day use `maxTime`.
*/
maxDateTime: PropTypes.object,
/**
* Maximal selectable time.
* The date part of the object will be ignored unless `props.disableIgnoringDatePartForTimeValidation === true`.
*/
maxTime: PropTypes.object,
/**
* Minimal selectable date.
* @default 1900-01-01
*/
minDate: PropTypes.object,
/**
* Minimal selectable moment of time with binding to date, to set min time in each day use `minTime`.
*/
minDateTime: PropTypes.object,
/**
* Minimal selectable time.
* The date part of the object will be ignored unless `props.disableIgnoringDatePartForTimeValidation === true`.
*/
minTime: PropTypes.object,
/**
* Step over minutes.
* @default 1
*/
minutesStep: PropTypes.number,
/**
* Name attribute of the `input` element.
*/
name: PropTypes.string,
onBlur: PropTypes.func,
/**
* Callback fired when the value changes.
* @template TValue The value type. It will be the same type as `value` or `null`. It can be in `[start, end]` format in case of range value.
* @template TError The validation error type. It will be either `string` or a `null`. It can be in `[start, end]` format in case of range value.
* @param {TValue} value The new value.
* @param {FieldChangeHandlerContext<TError>} context The context containing the validation result of the current value.
*/
onChange: PropTypes.func,
/**
* Callback fired when the clear button is clicked.
*/
onClear: PropTypes.func,
/**
* Callback fired when the error associated with the current value changes.
* When a validation error is detected, the `error` parameter contains a non-null value.
* This can be used to render an appropriate form error.
* @template TError The validation error type. It will be either `string` or a `null`. It can be in `[start, end]` format in case of range value.
* @template TValue The value type. It will be the same type as `value` or `null`. It can be in `[start, end]` format in case of range value.
* @param {TError} error The reason why the current value is not valid.
* @param {TValue} value The value associated with the error.
*/
onError: PropTypes.func,
onFocus: PropTypes.func,
/**
* Callback fired when the selected sections change.
* @param {FieldSelectedSections} newValue The new selected sections.
*/
onSelectedSectionsChange: PropTypes.func,
/**
* The position at which the opening button is placed.
* If there is no Picker to open, the button is not rendered
* @default 'end'
*/
openPickerButtonPosition: PropTypes.oneOf(['end', 'start']),
/**
* If `true`, the component is read-only.
* When read-only, the value cannot be changed but the user can interact with the interface.
* @default false
*/
readOnly: PropTypes.bool,
/**
* The date used to generate a part of the new value that is not present in the format when both `value` and `defaultValue` are empty.
* For example, on time fields it will be used to determine the date to set.
* @default The closest valid date using the validation props, except callbacks such as `shouldDisableDate`. Value is rounded to the most granular section used.
*/
referenceDate: PropTypes.object,
/**
* If `true`, the label is displayed as required and the `input` element is required.
* @default false
*/
required: PropTypes.bool,
/**
* The currently selected sections.
* This prop accepts four formats:
* 1. If a number is provided, the section at this index will be selected.
* 2. If a string of type `FieldSectionType` is provided, the first section with that name will be selected.
* 3. If `"all"` is provided, all the sections will be selected.
* 4. If `null` is provided, no section will be selected.
* If not provided, the selected sections will be handled internally.
*/
selectedSections: PropTypes.oneOfType([PropTypes.oneOf(['all', 'day', 'empty', 'hours', 'meridiem', 'minutes', 'month', 'seconds', 'weekDay', 'year']), PropTypes.number]),
/**
* Disable specific date.
*
* Warning: This function can be called multiple times (for example when rendering date calendar, checking if focus can be moved to a certain date, etc.). Expensive computations can impact performance.
*
* @param {PickerValidDate} day The date to test.
* @returns {boolean} If `true` the date will be disabled.
*/
shouldDisableDate: PropTypes.func,
/**
* Disable specific month.
* @param {PickerValidDate} month The month to test.
* @returns {boolean} If `true`, the month will be disabled.
*/
shouldDisableMonth: PropTypes.func,
/**
* Disable specific time.
* @param {PickerValidDate} value The value to check.
* @param {TimeView} view The clock type of the timeValue.
* @returns {boolean} If `true` the time will be disabled.
*/
shouldDisableTime: PropTypes.func,
/**
* Disable specific year.
* @param {PickerValidDate} year The year to test.
* @returns {boolean} If `true`, the year will be disabled.
*/
shouldDisableYear: PropTypes.func,
/**
* If `true`, the format will respect the leading zeroes (for example on dayjs, the format `M/D/YYYY` will render `8/16/2018`)
* If `false`, the format will always add leading zeroes (for example on dayjs, the format `M/D/YYYY` will render `08/16/2018`)
*
* Warning n°1: Luxon is not able to respect the leading zeroes when using macro tokens (for example "DD"), so `shouldRespectLeadingZeros={true}` might lead to inconsistencies when using `AdapterLuxon`.
*
* Warning n°2: When `shouldRespectLeadingZeros={true}`, the field will add an invisible character on the sections containing a single digit to make sure `onChange` is fired.
* If you need to get the clean value from the input, you can remove this character using `input.value.replace(/\u200e/g, '')`.
*
* Warning n°3: When used in strict mode, dayjs and moment require to respect the leading zeros.
* This mean that when using `shouldRespectLeadingZeros={false}`, if you retrieve the value directly from the input (not listening to `onChange`) and your format contains tokens without leading zeros, the value will not be parsed by your library.
*
* @default false
*/
shouldRespectLeadingZeros: PropTypes.bool,
/**
* The size of the component.
* @default 'medium'
*/
size: PropTypes.oneOf(['medium', 'small']),
/**
* The props used for each component slot.
* @default {}
*/
slotProps: PropTypes.object,
/**
* Overridable component slots.
* @default {}
*/
slots: PropTypes.object,
style: PropTypes.object,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
/**
* Choose which timezone to use for the value.
* Example: "default", "system", "UTC", "America/New_York".
* If you pass values from other timezones to some props, they will be converted to this timezone before being used.
* @see See the {@link https://mui.com/x/react-date-pickers/timezone/ timezones documentation} for more details.
* @default The timezone of the `value` or `defaultValue` prop is defined, 'default' otherwise.
*/
timezone: PropTypes.string,
/**
* The ref object used to imperatively interact with the field.
*/
unstableFieldRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
/**
* The selected value.
* Used when the component is controlled.
*/
value: PropTypes.object,
/**
* The variant to use.
* @default 'outlined'
*/
variant: PropTypes.oneOf(['filled', 'outlined', 'standard'])
} : void 0;
export { DateTimeField };

View file

@ -0,0 +1,22 @@
import { MakeOptional } from '@mui/x-internals/types';
import { DateTimeValidationError, BuiltInFieldTextFieldProps } from "../models/index.js";
import { UseFieldInternalProps } from "../internals/hooks/useField/index.js";
import { ExportedValidateDateTimeProps } from "../validation/validateDateTime.js";
import { AmPmProps } from "../internals/models/props/time.js";
import { PickerValue } from "../internals/models/index.js";
import { ExportedPickerFieldUIProps, PickerFieldUISlotProps, PickerFieldUISlots } from "../internals/components/PickerFieldUI.js";
export interface UseDateTimeFieldProps<TEnableAccessibleFieldDOMStructure extends boolean> extends MakeOptional<UseFieldInternalProps<PickerValue, TEnableAccessibleFieldDOMStructure, DateTimeValidationError>, 'format'>, ExportedValidateDateTimeProps, ExportedPickerFieldUIProps, AmPmProps {}
export type DateTimeFieldProps<TEnableAccessibleFieldDOMStructure extends boolean = true> = UseDateTimeFieldProps<TEnableAccessibleFieldDOMStructure> & Omit<BuiltInFieldTextFieldProps<TEnableAccessibleFieldDOMStructure>, keyof UseDateTimeFieldProps<TEnableAccessibleFieldDOMStructure>> & {
/**
* Overridable component slots.
* @default {}
*/
slots?: DateTimeFieldSlots;
/**
* The props used for each component slot.
* @default {}
*/
slotProps?: DateTimeFieldSlotProps;
};
export interface DateTimeFieldSlots extends PickerFieldUISlots {}
export interface DateTimeFieldSlotProps extends PickerFieldUISlotProps {}

View file

@ -0,0 +1 @@
export {};

View file

@ -0,0 +1,3 @@
export { DateTimeField } from "./DateTimeField.js";
export { useDateTimeField as unstable_useDateTimeField } from "./useDateTimeField.js";
export type { UseDateTimeFieldProps, DateTimeFieldProps } from "./DateTimeField.types.js";

View file

@ -0,0 +1,2 @@
export { DateTimeField } from "./DateTimeField.js";
export { useDateTimeField as unstable_useDateTimeField } from "./useDateTimeField.js";

View file

@ -0,0 +1,2 @@
import { UseDateTimeFieldProps } from "./DateTimeField.types.js";
export declare const useDateTimeField: <TEnableAccessibleFieldDOMStructure extends boolean, TProps extends UseDateTimeFieldProps<TEnableAccessibleFieldDOMStructure>>(props: TProps) => import("../internals/index.js").UseFieldReturnValue<TEnableAccessibleFieldDOMStructure, TProps>;

View file

@ -0,0 +1,11 @@
'use client';
import { useField } from "../internals/hooks/useField/index.js";
import { useDateTimeManager } from "../managers/index.js";
export const useDateTimeField = props => {
const manager = useDateTimeManager(props);
return useField({
manager,
props
});
};

View file

@ -0,0 +1,17 @@
import * as React from 'react';
import { DateTimePickerProps } from "./DateTimePicker.types.js";
type DateTimePickerComponent = (<TEnableAccessibleFieldDOMStructure extends boolean = true>(props: DateTimePickerProps<TEnableAccessibleFieldDOMStructure> & React.RefAttributes<HTMLDivElement>) => React.JSX.Element) & {
propTypes?: any;
};
/**
* Demos:
*
* - [DateTimePicker](https://mui.com/x/react-date-pickers/date-time-picker/)
* - [Validation](https://mui.com/x/react-date-pickers/validation/)
*
* API:
*
* - [DateTimePicker API](https://mui.com/x/api/date-pickers/date-time-picker/)
*/
declare const DateTimePicker: DateTimePickerComponent;
export { DateTimePicker };

View file

@ -0,0 +1,439 @@
'use client';
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
const _excluded = ["desktopModeMediaQuery"];
import * as React from 'react';
import PropTypes from 'prop-types';
import useMediaQuery from '@mui/material/useMediaQuery';
import { useThemeProps } from '@mui/material/styles';
import refType from '@mui/utils/refType';
import { DesktopDateTimePicker } from "../DesktopDateTimePicker/index.js";
import { MobileDateTimePicker } from "../MobileDateTimePicker/index.js";
import { DEFAULT_DESKTOP_MODE_MEDIA_QUERY } from "../internals/utils/utils.js";
import { jsx as _jsx } from "react/jsx-runtime";
/**
* Demos:
*
* - [DateTimePicker](https://mui.com/x/react-date-pickers/date-time-picker/)
* - [Validation](https://mui.com/x/react-date-pickers/validation/)
*
* API:
*
* - [DateTimePicker API](https://mui.com/x/api/date-pickers/date-time-picker/)
*/
const DateTimePicker = /*#__PURE__*/React.forwardRef(function DateTimePicker(inProps, ref) {
const props = useThemeProps({
props: inProps,
name: 'MuiDateTimePicker'
});
const {
desktopModeMediaQuery = DEFAULT_DESKTOP_MODE_MEDIA_QUERY
} = props,
other = _objectWithoutPropertiesLoose(props, _excluded);
// defaults to `true` in environments where `window.matchMedia` would not be available (i.e. test/jsdom)
const isDesktop = useMediaQuery(desktopModeMediaQuery, {
defaultMatches: true
});
if (isDesktop) {
return /*#__PURE__*/_jsx(DesktopDateTimePicker, _extends({
ref: ref
}, other));
}
return /*#__PURE__*/_jsx(MobileDateTimePicker, _extends({
ref: ref
}, other));
});
if (process.env.NODE_ENV !== "production") DateTimePicker.displayName = "DateTimePicker";
process.env.NODE_ENV !== "production" ? DateTimePicker.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the TypeScript types and run "pnpm proptypes" |
// ----------------------------------------------------------------------
/**
* 12h/24h view for hour selection clock.
* @default adapter.is12HourCycleInCurrentLocale()
*/
ampm: PropTypes.bool,
/**
* Display ampm controls under the clock (instead of in the toolbar).
* @default true on desktop, false on mobile
*/
ampmInClock: PropTypes.bool,
/**
* If `true`, the main element is focused during the first mount.
* This main element is:
* - the element chosen by the visible view if any (i.e: the selected day on the `day` view).
* - the `input` element if there is a field rendered.
*/
autoFocus: PropTypes.bool,
className: PropTypes.string,
/**
* If `true`, the Picker will close after submitting the full date.
* @default false
*/
closeOnSelect: PropTypes.bool,
/**
* Formats the day of week displayed in the calendar header.
* @param {PickerValidDate} date The date of the day of week provided by the adapter.
* @returns {string} The name to display.
* @default (date: PickerValidDate) => adapter.format(date, 'weekdayShort').charAt(0).toUpperCase()
*/
dayOfWeekFormatter: PropTypes.func,
/**
* The default value.
* Used when the component is not controlled.
*/
defaultValue: PropTypes.object,
/**
* CSS media query when `Mobile` mode will be changed to `Desktop`.
* @default '@media (pointer: fine)'
* @example '@media (min-width: 720px)' or theme.breakpoints.up("sm")
*/
desktopModeMediaQuery: PropTypes.string,
/**
* If `true`, the component is disabled.
* When disabled, the value cannot be changed and no interaction is possible.
* @default false
*/
disabled: PropTypes.bool,
/**
* If `true`, disable values after the current date for date components, time for time components and both for date time components.
* @default false
*/
disableFuture: PropTypes.bool,
/**
* If `true`, today's date is rendering without highlighting with circle.
* @default false
*/
disableHighlightToday: PropTypes.bool,
/**
* Do not ignore date part when validating min/max time.
* @default false
*/
disableIgnoringDatePartForTimeValidation: PropTypes.bool,
/**
* If `true`, the button to open the Picker will not be rendered (it will only render the field).
* @deprecated Use the [field component](https://mui.com/x/react-date-pickers/fields/) instead.
* @default false
*/
disableOpenPicker: PropTypes.bool,
/**
* If `true`, disable values before the current date for date components, time for time components and both for date time components.
* @default false
*/
disablePast: PropTypes.bool,
/**
* If `true`, the week number will be display in the calendar.
*/
displayWeekNumber: PropTypes.bool,
/**
* @default true
*/
enableAccessibleFieldDOMStructure: PropTypes.any,
/**
* The day view will show as many weeks as needed after the end of the current month to match this value.
* Put it to 6 to have a fixed number of weeks in Gregorian calendars
*/
fixedWeekNumber: PropTypes.number,
/**
* Format of the date when rendered in the input(s).
* Defaults to localized format based on the used `views`.
*/
format: PropTypes.string,
/**
* Density of the format when rendered in the input.
* Setting `formatDensity` to `"spacious"` will add a space before and after each `/`, `-` and `.` character.
* @default "dense"
*/
formatDensity: PropTypes.oneOf(['dense', 'spacious']),
/**
* Pass a ref to the `input` element.
*/
inputRef: refType,
/**
* The label content.
*/
label: PropTypes.node,
/**
* If `true`, calls `renderLoading` instead of rendering the day calendar.
* Can be used to preload information and show it in calendar.
* @default false
*/
loading: PropTypes.bool,
/**
* Locale for components texts.
* Allows overriding texts coming from `LocalizationProvider` and `theme`.
*/
localeText: PropTypes.object,
/**
* Maximal selectable date.
* @default 2099-12-31
*/
maxDate: PropTypes.object,
/**
* Maximal selectable moment of time with binding to date, to set max time in each day use `maxTime`.
*/
maxDateTime: PropTypes.object,
/**
* Maximal selectable time.
* The date part of the object will be ignored unless `props.disableIgnoringDatePartForTimeValidation === true`.
*/
maxTime: PropTypes.object,
/**
* Minimal selectable date.
* @default 1900-01-01
*/
minDate: PropTypes.object,
/**
* Minimal selectable moment of time with binding to date, to set min time in each day use `minTime`.
*/
minDateTime: PropTypes.object,
/**
* Minimal selectable time.
* The date part of the object will be ignored unless `props.disableIgnoringDatePartForTimeValidation === true`.
*/
minTime: PropTypes.object,
/**
* Step over minutes.
* @default 1
*/
minutesStep: PropTypes.number,
/**
* Months rendered per row.
* @default 3
*/
monthsPerRow: PropTypes.oneOf([3, 4]),
/**
* Name attribute used by the `input` element in the Field.
*/
name: PropTypes.string,
/**
* Callback fired when the value is accepted.
* @template TValue The value type. It will be the same type as `value` or `null`. It can be in `[start, end]` format in case of range value.
* @template TError The validation error type. It will be either `string` or a `null`. It can be in `[start, end]` format in case of range value.
* @param {TValue} value The value that was just accepted.
* @param {FieldChangeHandlerContext<TError>} context The context containing the validation result of the current value.
*/
onAccept: PropTypes.func,
/**
* Callback fired when the value changes.
* @template TValue The value type. It will be the same type as `value` or `null`. It can be in `[start, end]` format in case of range value.
* @template TError The validation error type. It will be either `string` or a `null`. It can be in `[start, end]` format in case of range value.
* @param {TValue} value The new value.
* @param {FieldChangeHandlerContext<TError>} context The context containing the validation result of the current value.
*/
onChange: PropTypes.func,
/**
* Callback fired when the popup requests to be closed.
* Use in controlled mode (see `open`).
*/
onClose: PropTypes.func,
/**
* Callback fired when the error associated with the current value changes.
* When a validation error is detected, the `error` parameter contains a non-null value.
* This can be used to render an appropriate form error.
* @template TError The validation error type. It will be either `string` or a `null`. It can be in `[start, end]` format in case of range value.
* @template TValue The value type. It will be the same type as `value` or `null`. It can be in `[start, end]` format in case of range value.
* @param {TError} error The reason why the current value is not valid.
* @param {TValue} value The value associated with the error.
*/
onError: PropTypes.func,
/**
* Callback fired on month change.
* @param {PickerValidDate} month The new month.
*/
onMonthChange: PropTypes.func,
/**
* Callback fired when the popup requests to be opened.
* Use in controlled mode (see `open`).
*/
onOpen: PropTypes.func,
/**
* Callback fired when the selected sections change.
* @param {FieldSelectedSections} newValue The new selected sections.
*/
onSelectedSectionsChange: PropTypes.func,
/**
* Callback fired on view change.
* @template TView Type of the view. It will vary based on the Picker type and the `views` it uses.
* @param {TView} view The new view.
*/
onViewChange: PropTypes.func,
/**
* Callback fired on year change.
* @param {PickerValidDate} year The new year.
*/
onYearChange: PropTypes.func,
/**
* Control the popup or dialog open state.
* @default false
*/
open: PropTypes.bool,
/**
* The default visible view.
* Used when the component view is not controlled.
* Must be a valid option from `views` list.
*/
openTo: PropTypes.oneOf(['day', 'hours', 'meridiem', 'minutes', 'month', 'seconds', 'year']),
/**
* Force rendering in particular orientation.
*/
orientation: PropTypes.oneOf(['landscape', 'portrait']),
/**
* If `true`, the component is read-only.
* When read-only, the value cannot be changed but the user can interact with the interface.
* @default false
*/
readOnly: PropTypes.bool,
/**
* If `true`, disable heavy animations.
* @default `@media(prefers-reduced-motion: reduce)` || `navigator.userAgent` matches Android <10 or iOS <13
*/
reduceAnimations: PropTypes.bool,
/**
* The date used to generate the new value when both `value` and `defaultValue` are empty.
* @default The closest valid date-time using the validation props, except callbacks like `shouldDisable<...>`.
*/
referenceDate: PropTypes.object,
/**
* Component displaying when passed `loading` true.
* @returns {React.ReactNode} The node to render when loading.
* @default () => <span>...</span>
*/
renderLoading: PropTypes.func,
/**
* The currently selected sections.
* This prop accepts four formats:
* 1. If a number is provided, the section at this index will be selected.
* 2. If a string of type `FieldSectionType` is provided, the first section with that name will be selected.
* 3. If `"all"` is provided, all the sections will be selected.
* 4. If `null` is provided, no section will be selected.
* If not provided, the selected sections will be handled internally.
*/
selectedSections: PropTypes.oneOfType([PropTypes.oneOf(['all', 'day', 'empty', 'hours', 'meridiem', 'minutes', 'month', 'seconds', 'weekDay', 'year']), PropTypes.number]),
/**
* Disable specific date.
*
* Warning: This function can be called multiple times (for example when rendering date calendar, checking if focus can be moved to a certain date, etc.). Expensive computations can impact performance.
*
* @param {PickerValidDate} day The date to test.
* @returns {boolean} If `true` the date will be disabled.
*/
shouldDisableDate: PropTypes.func,
/**
* Disable specific month.
* @param {PickerValidDate} month The month to test.
* @returns {boolean} If `true`, the month will be disabled.
*/
shouldDisableMonth: PropTypes.func,
/**
* Disable specific time.
* @param {PickerValidDate} value The value to check.
* @param {TimeView} view The clock type of the timeValue.
* @returns {boolean} If `true` the time will be disabled.
*/
shouldDisableTime: PropTypes.func,
/**
* Disable specific year.
* @param {PickerValidDate} year The year to test.
* @returns {boolean} If `true`, the year will be disabled.
*/
shouldDisableYear: PropTypes.func,
/**
* If `true`, days outside the current month are rendered:
*
* - if `fixedWeekNumber` is defined, renders days to have the weeks requested.
*
* - if `fixedWeekNumber` is not defined, renders day to fill the first and last week of the current month.
*
* - ignored if `calendars` equals more than `1` on range pickers.
* @default false
*/
showDaysOutsideCurrentMonth: PropTypes.bool,
/**
* If `true`, disabled digital clock items will not be rendered.
* @default false
*/
skipDisabled: PropTypes.bool,
/**
* The props used for each component slot.
* @default {}
*/
slotProps: PropTypes.object,
/**
* Overridable component slots.
* @default {}
*/
slots: PropTypes.object,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
/**
* Amount of time options below or at which the single column time renderer is used.
* @default 24
*/
thresholdToRenderTimeInASingleColumn: PropTypes.number,
/**
* The time steps between two time unit options.
* For example, if `timeSteps.minutes = 8`, then the available minute options will be `[0, 8, 16, 24, 32, 40, 48, 56]`.
* When single column time renderer is used, only `timeSteps.minutes` will be used.
* @default{ hours: 1, minutes: 5, seconds: 5 }
*/
timeSteps: PropTypes.shape({
hours: PropTypes.number,
minutes: PropTypes.number,
seconds: PropTypes.number
}),
/**
* Choose which timezone to use for the value.
* Example: "default", "system", "UTC", "America/New_York".
* If you pass values from other timezones to some props, they will be converted to this timezone before being used.
* @see See the {@link https://mui.com/x/react-date-pickers/timezone/ timezones documentation} for more details.
* @default The timezone of the `value` or `defaultValue` prop is defined, 'default' otherwise.
*/
timezone: PropTypes.string,
/**
* The selected value.
* Used when the component is controlled.
*/
value: PropTypes.object,
/**
* The visible view.
* Used when the component view is controlled.
* Must be a valid option from `views` list.
*/
view: PropTypes.oneOf(['day', 'hours', 'meridiem', 'minutes', 'month', 'seconds', 'year']),
/**
* Define custom view renderers for each section.
* If `null`, the section will only have field editing.
* If `undefined`, internally defined view will be used.
*/
viewRenderers: PropTypes.shape({
day: PropTypes.func,
hours: PropTypes.func,
meridiem: PropTypes.func,
minutes: PropTypes.func,
month: PropTypes.func,
seconds: PropTypes.func,
year: PropTypes.func
}),
/**
* Available views.
*/
views: PropTypes.arrayOf(PropTypes.oneOf(['day', 'hours', 'minutes', 'month', 'seconds', 'year']).isRequired),
/**
* Years are displayed in ascending (chronological) order by default.
* If `desc`, years are displayed in descending order.
* @default 'asc'
*/
yearsOrder: PropTypes.oneOf(['asc', 'desc']),
/**
* Years rendered per row.
* @default 4 on desktop, 3 on mobile
*/
yearsPerRow: PropTypes.oneOf([3, 4])
} : void 0;
export { DateTimePicker };

View file

@ -0,0 +1,34 @@
import { DesktopDateTimePickerProps, DesktopDateTimePickerSlots, DesktopDateTimePickerSlotProps } from "../DesktopDateTimePicker/index.js";
import { BaseSingleInputFieldProps } from "../internals/models/index.js";
import { MobileDateTimePickerProps, MobileDateTimePickerSlots, MobileDateTimePickerSlotProps } from "../MobileDateTimePicker/index.js";
import { ValidateDateTimeProps } from "../validation/index.js";
import { ExportedYearCalendarProps } from "../YearCalendar/YearCalendar.types.js";
export interface DateTimePickerSlots extends DesktopDateTimePickerSlots, MobileDateTimePickerSlots {}
export interface DateTimePickerSlotProps<TEnableAccessibleFieldDOMStructure extends boolean> extends DesktopDateTimePickerSlotProps<TEnableAccessibleFieldDOMStructure>, MobileDateTimePickerSlotProps<TEnableAccessibleFieldDOMStructure> {}
export interface DateTimePickerProps<TEnableAccessibleFieldDOMStructure extends boolean = true> extends DesktopDateTimePickerProps<TEnableAccessibleFieldDOMStructure>, ExportedYearCalendarProps, Omit<MobileDateTimePickerProps<TEnableAccessibleFieldDOMStructure>, 'views'> {
/**
* CSS media query when `Mobile` mode will be changed to `Desktop`.
* @default '@media (pointer: fine)'
* @example '@media (min-width: 720px)' or theme.breakpoints.up("sm")
*/
desktopModeMediaQuery?: string;
/**
* Overridable component slots.
* @default {}
*/
slots?: DateTimePickerSlots;
/**
* The props used for each component slot.
* @default {}
*/
slotProps?: DateTimePickerSlotProps<TEnableAccessibleFieldDOMStructure>;
/**
* Years rendered per row.
* @default 4 on desktop, 3 on mobile
*/
yearsPerRow?: 3 | 4;
}
/**
* Props the field can receive when used inside a Date Time Picker (<DateTimePicker />, <DesktopDateTimePicker /> or <MobileDateTimePicker /> component).
*/
export type DateTimePickerFieldProps = ValidateDateTimeProps & BaseSingleInputFieldProps;

View file

@ -0,0 +1 @@
export {};

View file

@ -0,0 +1,39 @@
import * as React from 'react';
import { DateTimePickerTabsClasses } from "./dateTimePickerTabsClasses.js";
import { ExportedBaseTabsProps } from "../internals/models/props/tabs.js";
export interface DateTimePickerTabsProps extends ExportedBaseTabsProps {
/**
* Toggles visibility of the tabs allowing view switching.
* @default `window.innerHeight < 667` for `DesktopDateTimePicker` and `MobileDateTimePicker`, `displayStaticWrapperAs === 'desktop'` for `StaticDateTimePicker`
*/
hidden?: boolean;
/**
* Date tab icon.
* @default DateRange
*/
dateIcon?: React.ReactNode;
/**
* Time tab icon.
* @default Time
*/
timeIcon?: React.ReactNode;
/**
* Override or extend the styles applied to the component.
*/
classes?: Partial<DateTimePickerTabsClasses>;
}
/**
* Demos:
*
* - [DateTimePicker](https://mui.com/x/react-date-pickers/date-time-picker/)
* - [Custom slots and subcomponents](https://mui.com/x/react-date-pickers/custom-components/)
*
* API:
*
* - [DateTimePickerTabs API](https://mui.com/x/api/date-pickers/date-time-picker-tabs/)
*/
declare const DateTimePickerTabs: {
(inProps: DateTimePickerTabsProps): React.JSX.Element | null;
propTypes: any;
};
export { DateTimePickerTabs };

View file

@ -0,0 +1,142 @@
'use client';
import * as React from 'react';
import clsx from 'clsx';
import PropTypes from 'prop-types';
import Tab from '@mui/material/Tab';
import Tabs, { tabsClasses } from '@mui/material/Tabs';
import { styled, useThemeProps } from '@mui/material/styles';
import composeClasses from '@mui/utils/composeClasses';
import { TimeIcon, DateRangeIcon } from "../icons/index.js";
import { usePickerTranslations } from "../hooks/usePickerTranslations.js";
import { getDateTimePickerTabsUtilityClass } from "./dateTimePickerTabsClasses.js";
import { isDatePickerView } from "../internals/utils/date-utils.js";
import { usePickerPrivateContext } from "../internals/hooks/usePickerPrivateContext.js";
import { usePickerContext } from "../hooks/index.js";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const viewToTab = view => {
if (isDatePickerView(view)) {
return 'date';
}
return 'time';
};
const tabToView = tab => {
if (tab === 'date') {
return 'day';
}
return 'hours';
};
const useUtilityClasses = classes => {
const slots = {
root: ['root']
};
return composeClasses(slots, getDateTimePickerTabsUtilityClass, classes);
};
const DateTimePickerTabsRoot = styled(Tabs, {
name: 'MuiDateTimePickerTabs',
slot: 'Root'
})(({
theme
}) => ({
boxShadow: `0 -1px 0 0 inset ${(theme.vars || theme).palette.divider}`,
'&:last-child': {
boxShadow: `0 1px 0 0 inset ${(theme.vars || theme).palette.divider}`,
[`& .${tabsClasses.indicator}`]: {
bottom: 'auto',
top: 0
}
}
}));
/**
* Demos:
*
* - [DateTimePicker](https://mui.com/x/react-date-pickers/date-time-picker/)
* - [Custom slots and subcomponents](https://mui.com/x/react-date-pickers/custom-components/)
*
* API:
*
* - [DateTimePickerTabs API](https://mui.com/x/api/date-pickers/date-time-picker-tabs/)
*/
const DateTimePickerTabs = function DateTimePickerTabs(inProps) {
const props = useThemeProps({
props: inProps,
name: 'MuiDateTimePickerTabs'
});
const {
dateIcon = /*#__PURE__*/_jsx(DateRangeIcon, {}),
timeIcon = /*#__PURE__*/_jsx(TimeIcon, {}),
hidden = typeof window === 'undefined' || window.innerHeight < 667,
className,
classes: classesProp,
sx
} = props;
const translations = usePickerTranslations();
const {
ownerState
} = usePickerPrivateContext();
const {
view,
setView
} = usePickerContext();
const classes = useUtilityClasses(classesProp);
const handleChange = (event, value) => {
setView(tabToView(value));
};
if (hidden) {
return null;
}
return /*#__PURE__*/_jsxs(DateTimePickerTabsRoot, {
ownerState: ownerState,
variant: "fullWidth",
value: viewToTab(view),
onChange: handleChange,
className: clsx(className, classes.root),
sx: sx,
children: [/*#__PURE__*/_jsx(Tab, {
value: "date",
"aria-label": translations.dateTableLabel,
icon: /*#__PURE__*/_jsx(React.Fragment, {
children: dateIcon
})
}), /*#__PURE__*/_jsx(Tab, {
value: "time",
"aria-label": translations.timeTableLabel,
icon: /*#__PURE__*/_jsx(React.Fragment, {
children: timeIcon
})
})]
});
};
if (process.env.NODE_ENV !== "production") DateTimePickerTabs.displayName = "DateTimePickerTabs";
process.env.NODE_ENV !== "production" ? DateTimePickerTabs.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the TypeScript types and run "pnpm proptypes" |
// ----------------------------------------------------------------------
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
className: PropTypes.string,
/**
* Date tab icon.
* @default DateRange
*/
dateIcon: PropTypes.node,
/**
* Toggles visibility of the tabs allowing view switching.
* @default `window.innerHeight < 667` for `DesktopDateTimePicker` and `MobileDateTimePicker`, `displayStaticWrapperAs === 'desktop'` for `StaticDateTimePicker`
*/
hidden: PropTypes.bool,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
/**
* Time tab icon.
* @default Time
*/
timeIcon: PropTypes.node
} : void 0;
export { DateTimePickerTabs };

View file

@ -0,0 +1,47 @@
import * as React from 'react';
import { BaseToolbarProps, ExportedBaseToolbarProps } from "../internals/models/props/toolbar.js";
import { DateTimePickerToolbarClasses } from "./dateTimePickerToolbarClasses.js";
import { DateOrTimeViewWithMeridiem, PickerValue } from "../internals/models/index.js";
import { DateTimeValidationError } from "../models/index.js";
import { SetValueActionOptions } from "../internals/components/PickerProvider.js";
export interface ExportedDateTimePickerToolbarProps extends ExportedBaseToolbarProps {
/**
* Override or extend the styles applied to the component.
*/
classes?: Partial<DateTimePickerToolbarClasses>;
}
export interface DateTimePickerToolbarProps extends ExportedDateTimePickerToolbarProps, BaseToolbarProps {
/**
* If provided, it will be used instead of `dateTimePickerToolbarTitle` from localization.
*/
toolbarTitle?: React.ReactNode;
ampm?: boolean;
ampmInClock?: boolean;
}
/**
* If `forceDesktopVariant` is set to `true`, the toolbar will always be rendered in the desktop mode.
* If `onViewChange` is defined, the toolbar will call it instead of calling the default handler from `usePickerContext`.
* This is used by the Date Time Range Picker Toolbar.
*/
export declare const DateTimePickerToolbarOverrideContext: React.Context<{
value: PickerValue;
setValue: (value: PickerValue, options?: SetValueActionOptions<DateTimeValidationError>) => void;
forceDesktopVariant: boolean;
setView: (view: DateOrTimeViewWithMeridiem) => void;
view: DateOrTimeViewWithMeridiem | null;
} | null>;
/**
* Demos:
*
* - [DateTimePicker](https://mui.com/x/react-date-pickers/date-time-picker/)
* - [Custom components](https://mui.com/x/react-date-pickers/custom-components/)
*
* API:
*
* - [DateTimePickerToolbar API](https://mui.com/x/api/date-pickers/date-time-picker-toolbar/)
*/
declare function DateTimePickerToolbar(inProps: DateTimePickerToolbarProps): React.JSX.Element;
declare namespace DateTimePickerToolbar {
var propTypes: any;
}
export { DateTimePickerToolbar };

View file

@ -0,0 +1,410 @@
'use client';
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
const _excluded = ["ampm", "ampmInClock", "toolbarFormat", "toolbarPlaceholder", "toolbarTitle", "className", "classes"];
import * as React from 'react';
import clsx from 'clsx';
import PropTypes from 'prop-types';
import { styled, useThemeProps } from '@mui/material/styles';
import composeClasses from '@mui/utils/composeClasses';
import { shouldForwardProp } from '@mui/system/createStyled';
import { PickersToolbarText } from "../internals/components/PickersToolbarText.js";
import { PickersToolbar } from "../internals/components/PickersToolbar.js";
import { PickersToolbarButton } from "../internals/components/PickersToolbarButton.js";
import { usePickerAdapter, usePickerTranslations } from "../hooks/index.js";
import { dateTimePickerToolbarClasses, getDateTimePickerToolbarUtilityClass } from "./dateTimePickerToolbarClasses.js";
import { useMeridiemMode } from "../internals/hooks/date-helpers-hooks.js";
import { MULTI_SECTION_CLOCK_SECTION_WIDTH } from "../internals/constants/dimensions.js";
import { formatMeridiem } from "../internals/utils/date-utils.js";
import { pickersToolbarTextClasses } from "../internals/components/pickersToolbarTextClasses.js";
import { pickersToolbarClasses } from "../internals/components/pickersToolbarClasses.js";
import { usePickerContext } from "../hooks/usePickerContext.js";
import { useToolbarOwnerState } from "../internals/hooks/useToolbarOwnerState.js";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const useUtilityClasses = (classes, ownerState) => {
const {
pickerOrientation,
toolbarDirection
} = ownerState;
const slots = {
root: ['root'],
dateContainer: ['dateContainer'],
timeContainer: ['timeContainer', toolbarDirection === 'rtl' && 'timeLabelReverse'],
timeDigitsContainer: ['timeDigitsContainer', toolbarDirection === 'rtl' && 'timeLabelReverse'],
separator: ['separator'],
ampmSelection: ['ampmSelection', pickerOrientation === 'landscape' && 'ampmLandscape'],
ampmLabel: ['ampmLabel']
};
return composeClasses(slots, getDateTimePickerToolbarUtilityClass, classes);
};
const DateTimePickerToolbarRoot = styled(PickersToolbar, {
name: 'MuiDateTimePickerToolbar',
slot: 'Root',
shouldForwardProp: prop => shouldForwardProp(prop) && prop !== 'toolbarVariant'
})(({
theme
}) => ({
paddingLeft: 16,
paddingRight: 16,
justifyContent: 'space-around',
position: 'relative',
variants: [{
props: {
toolbarVariant: 'desktop'
},
style: {
borderBottom: `1px solid ${(theme.vars || theme).palette.divider}`,
[`& .${pickersToolbarClasses.content} .${pickersToolbarTextClasses.root}[data-selected]`]: {
color: (theme.vars || theme).palette.primary.main,
fontWeight: theme.typography.fontWeightBold
}
}
}, {
props: {
toolbarVariant: 'desktop',
pickerOrientation: 'landscape'
},
style: {
borderRight: `1px solid ${(theme.vars || theme).palette.divider}`
}
}, {
props: {
toolbarVariant: 'desktop',
pickerOrientation: 'portrait'
},
style: {
paddingLeft: 24,
paddingRight: 0
}
}]
}));
const DateTimePickerToolbarDateContainer = styled('div', {
name: 'MuiDateTimePickerToolbar',
slot: 'DateContainer'
})({
display: 'flex',
flexDirection: 'column',
alignItems: 'flex-start'
});
const DateTimePickerToolbarTimeContainer = styled('div', {
name: 'MuiDateTimePickerToolbar',
slot: 'TimeContainer',
shouldForwardProp: prop => shouldForwardProp(prop) && prop !== 'toolbarVariant'
})({
display: 'flex',
flexDirection: 'row',
variants: [{
props: {
toolbarDirection: 'rtl'
},
style: {
flexDirection: 'row-reverse'
}
}, {
props: {
toolbarVariant: 'desktop',
pickerOrientation: 'portrait'
},
style: {
gap: 9,
marginRight: 4,
alignSelf: 'flex-end'
}
}, {
props: ({
pickerOrientation,
toolbarVariant
}) => pickerOrientation === 'landscape' && toolbarVariant !== 'desktop',
style: {
flexDirection: 'column'
}
}, {
props: ({
pickerOrientation,
toolbarVariant,
toolbarDirection
}) => pickerOrientation === 'landscape' && toolbarVariant !== 'desktop' && toolbarDirection === 'rtl',
style: {
flexDirection: 'column-reverse'
}
}]
});
const DateTimePickerToolbarTimeDigitsContainer = styled('div', {
name: 'MuiDateTimePickerToolbar',
slot: 'TimeDigitsContainer',
shouldForwardProp: prop => shouldForwardProp(prop) && prop !== 'toolbarVariant'
})({
display: 'flex',
variants: [{
props: {
toolbarDirection: 'rtl'
},
style: {
flexDirection: 'row-reverse'
}
}, {
props: {
toolbarVariant: 'desktop'
},
style: {
gap: 1.5
}
}]
});
const DateTimePickerToolbarSeparator = styled(PickersToolbarText, {
name: 'MuiDateTimePickerToolbar',
slot: 'Separator',
shouldForwardProp: prop => shouldForwardProp(prop) && prop !== 'toolbarVariant'
})({
margin: '0 4px 0 2px',
cursor: 'default',
variants: [{
props: {
toolbarVariant: 'desktop'
},
style: {
margin: 0
}
}]
});
// Taken from TimePickerToolbar
const DateTimePickerToolbarAmPmSelection = styled('div', {
name: 'MuiDateTimePickerToolbar',
slot: 'AmPmSelection',
overridesResolver: (props, styles) => [{
[`.${dateTimePickerToolbarClasses.ampmLabel}`]: styles.ampmLabel
}, {
[`&.${dateTimePickerToolbarClasses.ampmLandscape}`]: styles.ampmLandscape
}, styles.ampmSelection]
})({
display: 'flex',
flexDirection: 'column',
marginRight: 'auto',
marginLeft: 12,
[`& .${dateTimePickerToolbarClasses.ampmLabel}`]: {
fontSize: 17
},
variants: [{
props: {
pickerOrientation: 'landscape'
},
style: {
margin: '4px 0 auto',
flexDirection: 'row',
justifyContent: 'space-around',
width: '100%'
}
}]
});
/**
* If `forceDesktopVariant` is set to `true`, the toolbar will always be rendered in the desktop mode.
* If `onViewChange` is defined, the toolbar will call it instead of calling the default handler from `usePickerContext`.
* This is used by the Date Time Range Picker Toolbar.
*/
export const DateTimePickerToolbarOverrideContext = /*#__PURE__*/React.createContext(null);
/**
* Demos:
*
* - [DateTimePicker](https://mui.com/x/react-date-pickers/date-time-picker/)
* - [Custom components](https://mui.com/x/react-date-pickers/custom-components/)
*
* API:
*
* - [DateTimePickerToolbar API](https://mui.com/x/api/date-pickers/date-time-picker-toolbar/)
*/
if (process.env.NODE_ENV !== "production") DateTimePickerToolbarOverrideContext.displayName = "DateTimePickerToolbarOverrideContext";
function DateTimePickerToolbar(inProps) {
const props = useThemeProps({
props: inProps,
name: 'MuiDateTimePickerToolbar'
});
const {
ampm,
ampmInClock,
toolbarFormat,
toolbarPlaceholder = '',
toolbarTitle: inToolbarTitle,
className,
classes: classesProp
} = props,
other = _objectWithoutPropertiesLoose(props, _excluded);
const {
value: valueContext,
setValue: setValueContext,
disabled,
readOnly,
variant,
orientation,
view: viewContext,
setView: setViewContext,
views
} = usePickerContext();
const translations = usePickerTranslations();
const ownerState = useToolbarOwnerState();
const classes = useUtilityClasses(classesProp, ownerState);
const adapter = usePickerAdapter();
const overrides = React.useContext(DateTimePickerToolbarOverrideContext);
const value = overrides ? overrides.value : valueContext;
const setValue = overrides ? overrides.setValue : setValueContext;
const view = overrides ? overrides.view : viewContext;
const setView = overrides ? overrides.setView : setViewContext;
const {
meridiemMode,
handleMeridiemChange
} = useMeridiemMode(value, ampm, newValue => setValue(newValue, {
changeImportance: 'set'
}));
const toolbarVariant = overrides?.forceDesktopVariant ? 'desktop' : variant;
const isDesktop = toolbarVariant === 'desktop';
const showAmPmControl = Boolean(ampm && !ampmInClock);
const toolbarTitle = inToolbarTitle ?? translations.dateTimePickerToolbarTitle;
const dateText = React.useMemo(() => {
if (!adapter.isValid(value)) {
return toolbarPlaceholder;
}
if (toolbarFormat) {
return adapter.formatByString(value, toolbarFormat);
}
return adapter.format(value, 'shortDate');
}, [value, toolbarFormat, toolbarPlaceholder, adapter]);
const formatSection = (format, fallback) => {
if (!adapter.isValid(value)) {
return fallback;
}
return adapter.format(value, format);
};
return /*#__PURE__*/_jsxs(DateTimePickerToolbarRoot, _extends({
className: clsx(classes.root, className),
toolbarTitle: toolbarTitle,
toolbarVariant: toolbarVariant
}, other, {
ownerState: ownerState,
children: [/*#__PURE__*/_jsxs(DateTimePickerToolbarDateContainer, {
className: classes.dateContainer,
ownerState: ownerState,
children: [views.includes('year') && /*#__PURE__*/_jsx(PickersToolbarButton, {
tabIndex: -1,
variant: "subtitle1",
onClick: () => setView('year'),
selected: view === 'year',
value: formatSection('year', '')
}), views.includes('day') && /*#__PURE__*/_jsx(PickersToolbarButton, {
tabIndex: -1,
variant: isDesktop ? 'h5' : 'h4',
onClick: () => setView('day'),
selected: view === 'day',
value: dateText
})]
}), /*#__PURE__*/_jsxs(DateTimePickerToolbarTimeContainer, {
className: classes.timeContainer,
ownerState: ownerState,
toolbarVariant: toolbarVariant,
children: [/*#__PURE__*/_jsxs(DateTimePickerToolbarTimeDigitsContainer, {
className: classes.timeDigitsContainer,
ownerState: ownerState,
toolbarVariant: toolbarVariant,
children: [views.includes('hours') && /*#__PURE__*/_jsxs(React.Fragment, {
children: [/*#__PURE__*/_jsx(PickersToolbarButton, {
variant: isDesktop ? 'h5' : 'h3',
width: isDesktop && orientation === 'portrait' ? MULTI_SECTION_CLOCK_SECTION_WIDTH : undefined,
onClick: () => setView('hours'),
selected: view === 'hours',
value: formatSection(ampm ? 'hours12h' : 'hours24h', '--')
}), /*#__PURE__*/_jsx(DateTimePickerToolbarSeparator, {
variant: isDesktop ? 'h5' : 'h3',
value: ":",
className: classes.separator,
ownerState: ownerState,
toolbarVariant: toolbarVariant
}), /*#__PURE__*/_jsx(PickersToolbarButton, {
variant: isDesktop ? 'h5' : 'h3',
width: isDesktop && orientation === 'portrait' ? MULTI_SECTION_CLOCK_SECTION_WIDTH : undefined,
onClick: () => setView('minutes'),
selected: view === 'minutes' || !views.includes('minutes') && view === 'hours',
value: formatSection('minutes', '--'),
disabled: !views.includes('minutes')
})]
}), views.includes('seconds') && /*#__PURE__*/_jsxs(React.Fragment, {
children: [/*#__PURE__*/_jsx(DateTimePickerToolbarSeparator, {
variant: isDesktop ? 'h5' : 'h3',
value: ":",
className: classes.separator,
ownerState: ownerState,
toolbarVariant: toolbarVariant
}), /*#__PURE__*/_jsx(PickersToolbarButton, {
variant: isDesktop ? 'h5' : 'h3',
width: isDesktop && orientation === 'portrait' ? MULTI_SECTION_CLOCK_SECTION_WIDTH : undefined,
onClick: () => setView('seconds'),
selected: view === 'seconds',
value: formatSection('seconds', '--')
})]
})]
}), showAmPmControl && !isDesktop && /*#__PURE__*/_jsxs(DateTimePickerToolbarAmPmSelection, {
className: classes.ampmSelection,
ownerState: ownerState,
children: [/*#__PURE__*/_jsx(PickersToolbarButton, {
variant: "subtitle2",
selected: meridiemMode === 'am',
typographyClassName: classes.ampmLabel,
value: formatMeridiem(adapter, 'am'),
onClick: readOnly ? undefined : () => handleMeridiemChange('am'),
disabled: disabled
}), /*#__PURE__*/_jsx(PickersToolbarButton, {
variant: "subtitle2",
selected: meridiemMode === 'pm',
typographyClassName: classes.ampmLabel,
value: formatMeridiem(adapter, 'pm'),
onClick: readOnly ? undefined : () => handleMeridiemChange('pm'),
disabled: disabled
})]
}), ampm && isDesktop && /*#__PURE__*/_jsx(PickersToolbarButton, {
variant: "h5",
onClick: () => setView('meridiem'),
selected: view === 'meridiem',
value: value && meridiemMode ? formatMeridiem(adapter, meridiemMode) : '--',
width: MULTI_SECTION_CLOCK_SECTION_WIDTH
})]
})]
}));
}
process.env.NODE_ENV !== "production" ? DateTimePickerToolbar.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the TypeScript types and run "pnpm proptypes" |
// ----------------------------------------------------------------------
ampm: PropTypes.bool,
ampmInClock: PropTypes.bool,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
className: PropTypes.string,
/**
* If `true`, show the toolbar even in desktop mode.
* @default `true` for Desktop, `false` for Mobile.
*/
hidden: PropTypes.bool,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
titleId: PropTypes.string,
/**
* Toolbar date format.
*/
toolbarFormat: PropTypes.string,
/**
* Toolbar value placeholderit is displayed when the value is empty.
* @default ""
*/
toolbarPlaceholder: PropTypes.node,
/**
* If provided, it will be used instead of `dateTimePickerToolbarTitle` from localization.
*/
toolbarTitle: PropTypes.node
} : void 0;
export { DateTimePickerToolbar };

Some files were not shown because too many files have changed in this diff Show more