@medplum/react-scheduling 5.1.38 → 5.1.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.cjs +4 -2
- package/dist/cjs/index.cjs.map +4 -4
- package/dist/cjs/index.d.ts +182 -35
- package/dist/esm/index.d.ts +182 -35
- package/dist/esm/index.mjs +4 -2
- package/dist/esm/index.mjs.map +4 -4
- package/package.json +11 -11
package/dist/esm/index.mjs
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import{getReferenceString as getReferenceString3}from"@medplum/core";import{AsyncAutocomplete}from"@medplum/react";import{useMedplum,useResource}from"@medplum/react-hooks";import{useCallback}from"react";import{assertNever,parseReference}from"@medplum/core";var BOOKABLE_ACTOR_TYPES=["Practitioner","Location","Device"];function isBookableActorType(value){return BOOKABLE_ACTOR_TYPES.includes(value)}function getActorType(reference){return parseReference(reference)[0]}function getActorTypeLabel(resourceType){switch(resourceType){case"Device":return"Device";case"HealthcareService":return"Healthcare Service";case"Location":return"Room";case"Patient":return"Patient";case"Practitioner":return"Provider";case"PractitionerRole":return"Practitioner Role";case"RelatedPerson":return"Related Person"}return assertNever(resourceType)}var REQUIRED_ACTOR_TYPES=new Set(["Practitioner"]);function isActorTypeRequired(actorType){return REQUIRED_ACTOR_TYPES.has(actorType)}import{assertNever as assertNever2,getDisplayString,getReferenceString as getReferenceString2,isDefined as isDefined2,lazy,serviceTypeIncludesService}from"@medplum/core";import{getReferenceString,isDefined}from"@medplum/core";var MAX_FIND_WINDOW_DAYS=31,MS_PER_DAY=1440*60*1e3,MAX_LISTED_DAYS=366,formatters=new Map;function getFormatter(key,options,locale){let formatter=formatters.get(key);return formatter||(formatter=new Intl.DateTimeFormat(locale,options),formatters.set(key,formatter)),formatter}function getZonedParts(date,timezone){let parts=getFormatter(`parts:${timezone??""}`,{timeZone:timezone,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23"},"en-US").formatToParts(date),read=type=>Number(parts.find(p=>p.type===type)?.value);return{year:read("year"),month:read("month"),day:read("day"),hour:read("hour"),minute:read("minute")}}function formatZonedTime(date,timezone,options){return getFormatter(`time:${timezone??""}${options?.withTimezone?":named":""}`,{timeZone:timezone,hour:"numeric",minute:"2-digit",timeZoneName:options?.withTimezone?TIMEZONE_NAME_STYLE:void 0}).format(date)}function formatDayHeading(date){return getFormatter("dayHeading",{weekday:"long",month:"long",day:"numeric"}).format(date)}function getTimezoneOffsetMs(instant,timezone){let{year,month,day,hour,minute}=getZonedParts(instant,timezone);return Date.UTC(year,month-1,day,hour,minute)-Math.floor(instant.getTime()/6e4)*6e4}function getBrowserTimezone(){return getFormatter("resolved",{}).resolvedOptions().timeZone}var TIMEZONE_NAME_STYLE="shortGeneric",TIMEZONE_LABEL_INSTANT=new Date(0);function formatTimezoneLabel(timezone){return getFormatter(`zoneName:${timezone??""}`,{timeZone:timezone,timeZoneName:TIMEZONE_NAME_STYLE}).formatToParts(TIMEZONE_LABEL_INSTANT).find(part=>part.type==="timeZoneName")?.value??""}function isViewerTimezone(timezone,viewer){return!timezone||timezone===(viewer??getBrowserTimezone())}function parseZonedTime(day,time,timezone){let match=/^(\d{1,2}):(\d{2})$/.exec(time.trim());if(!match)return;let hour=Number(match[1]),minute=Number(match[2]);if(hour>23||minute>59)return;if(!timezone)return new Date(day.getFullYear(),day.getMonth(),day.getDate(),hour,minute);let wallClock=Date.UTC(day.getFullYear(),day.getMonth(),day.getDate(),hour,minute),guess=getTimezoneOffsetMs(new Date(wallClock),timezone),offset3=getTimezoneOffsetMs(new Date(wallClock-guess),timezone);return new Date(wallClock-offset3)}function filterByTimeOfDay(appointments,timeOfDay,timezone){return timeOfDay==="any"?[...appointments]:appointments.filter(appointment=>{if(!appointment.start)return!1;let{hour}=getZonedParts(new Date(appointment.start),timezone);return timeOfDay==="morning"?hour<12:hour>=12})}function groupAppointmentsByDay(appointments,timezone,searched){let days=new Map;for(let appointment of appointments){if(!appointment.start)continue;let dayKey=getZonedDayKey(new Date(appointment.start),timezone),groups=days.get(dayKey);groups||(groups=new Map,days.set(dayKey,groups));let groupKey=getActorGroupKey(appointment),group=groups.get(groupKey);group?group.push(appointment):groups.set(groupKey,[appointment])}for(let day of enumerateDateRange(searched??{},MAX_LISTED_DAYS)){let key=getDayKey(day.getFullYear(),day.getMonth()+1,day.getDate());days.has(key)||days.set(key,new Map)}return[...days.entries()].sort(([left],[right])=>left.localeCompare(right)).map(([dayKey,groups])=>({key:dayKey,date:parseDayKey(dayKey),groups:[...groups.entries()].map(([groupKey,groupAppointments])=>toSlotGroup(groupKey,groupAppointments)).sort((left,right)=>left.key.localeCompare(right.key))}))}function toSlotGroup(key,appointments){let sorted=[...appointments].sort((left,right)=>(left.start??"").localeCompare(right.start??""));return{key,actors:sorted[0]?.participant?.map(participant=>participant.actor).filter(isDefined)??[],durationMinutes:getDurationMinutes(sorted[0]),appointments:sorted}}function getActorGroupKey(appointment){return getActorsKey((appointment.participant??[]).map(participant=>participant.actor).filter(isDefined))}function getActorsKey(actors){return actors.map(actor=>getReferenceString(actor)).filter(isDefined).sort((left,right)=>left.localeCompare(right)).join("+")}function getDurationMinutes(appointment){if(!appointment?.start||!appointment.end)return 0;let start=new Date(appointment.start).getTime(),end=new Date(appointment.end).getTime();return Math.round((end-start)/6e4)}function getAppointmentKey(appointment){return`${appointment.start}/${appointment.end}/${getActorGroupKey(appointment)}`}function getZonedDayKey(date,timezone){let{year,month,day}=getZonedParts(date,timezone);return getDayKey(year,month,day)}function getDayKey(year,month,day){return`${year}-${pad(month)}-${pad(day)}`}function parseDayKey(key){let[year,month,day]=key.split("-").map(Number);return new Date(year,month-1,day)}function pad(value){return value.toString().padStart(2,"0")}function getNativeInputType(type){return import.meta.env.NODE_ENV==="test"?"text":type}function startOfDay(date){return new Date(date.getFullYear(),date.getMonth(),date.getDate())}function endOfDay(date){let result=new Date(date);return result.setHours(23,59,59,999),result}function addDays(date,days){let result=new Date(date);return result.setDate(result.getDate()+days),result}function startOfZonedDay(year,month,day,timezone){return parseZonedTime(new Date(year,month-1,day),"00:00",timezone)}function getZonedDayRange(day,timezone){let now=new Date,opens=startOfZonedDay(day.getFullYear(),day.getMonth()+1,day.getDate(),timezone)??day,start=opens>now?opens:now,parts=getZonedParts(start,timezone),nextMidnight=startOfZonedDay(parts.year,parts.month,parts.day+1,timezone);return{start,end:nextMidnight??addDays(new Date(start.getFullYear(),start.getMonth(),start.getDate()),1)}}function endOfMonth(date){return endOfDay(new Date(date.getFullYear(),date.getMonth()+1,0))}function enumerateDateRange(range,limit=MAX_FIND_WINDOW_DAYS){if(!range.start||!range.end)return range.start?[range.start]:[];let days=[];for(let day=range.start;day<=range.end&&days.length<limit;day=addDays(day,1))days.push(day);return days}function getFindWindowError(range){let{start,end}=range;if(!(!start||!end))return getDayCount(start,end)>MAX_FIND_WINDOW_DAYS?`Choose at most ${MAX_FIND_WINDOW_DAYS} days at a time.`:void 0}function getDayCount(start,end){return Math.ceil((end.getTime()-start.getTime())/MS_PER_DAY)}function getCandidateActor(candidate){return candidate.schedule.actor[0]}function getCandidateDisplay(candidate){let actor=getCandidateActor(candidate);return actor.display??(candidate.actorResource&&getDisplayString(candidate.actorResource))??actor.reference??`Schedule/${candidate.schedule.id}`}var DEFAULT_COUNT=25;function getActorCriteria(actorType,query){switch(actorType){case"Practitioner":return{"actor:Practitioner.active:not":"false",...query?{"actor:Practitioner.name":query}:void 0};case"Location":return{"actor:Location.status:not":"inactive",...query?{"actor:Location.name":query}:void 0};case"Device":return{"actor:Device.status:not":"inactive",...query?{"actor:Device.device-name":query}:void 0};case"HealthcareService":case"Patient":case"PractitionerRole":case"RelatedPerson":throw new Error(`Got unsupported actor type ${actorType}`);default:return assertNever2(actorType)}}async function searchScheduleCandidates(medplum,service,options){let count=(options.count??DEFAULT_COUNT).toString(),actorCriteria=getActorCriteria(options.actorType,options.query),tokens=service?getServiceTypeTokens(service):[],typeCriteria=tokens.length>0?{"service-type":tokens.join(",")}:{},bundle=await medplum.search("Schedule",{...typeCriteria,...actorCriteria,"active:not":"false",_count:count,_include:"Schedule:actor"},{signal:options.signal}),actorsByReference=new Map,schedules=[];for(let entry of bundle.entry??[]){let resource=entry.resource;resource?.id&&(entry.search?.mode==="include"?actorsByReference.set(`${resource.resourceType}/${resource.id}`,resource):resource.resourceType==="Schedule"&&schedules.push(resource))}let found=schedules.map(schedule=>toScheduleCandidate(schedule,service,actorsByReference)).filter(isDefined2);return(await filterCandidatesByLocation(medplum,found,options.location,{signal:options.signal})).sort((left,right)=>getCandidateDisplay(left).localeCompare(getCandidateDisplay(right)))}function getServiceTypeTokens(service){let tokens=(service.type??[]).flatMap(concept=>concept.coding??[]).filter(coding=>coding.code).map(coding=>coding.system?`${coding.system}|${coding.code}`:coding.code);return[...new Set(tokens)]}function toScheduleCandidate(schedule,service,actors){if(schedule.active===!1||service&&!serviceTypeIncludesService(schedule.serviceType,service)||schedule.actor.length!==1)return;let actor=schedule.actor[0],referenceStr=actor.reference;if(!(!referenceStr||!isBookableActorType(getActorType(actor))))return{schedule,actorResource:actors.get(referenceStr)}}var MAX_LOCATION_DEPTH=4;async function filterCandidatesByLocation(medplum,candidates,location,options){let locationReference=location&&getReferenceString2(location);if(!locationReference)return[...candidates];let getRoles=lazy(()=>searchRolesByPractitioner(medplum,candidates,options)),verdicts=await Promise.all(candidates.map(async candidate=>isCandidateAtLocation(candidate,medplum,locationReference,getRoles,options)));return candidates.filter((_,index2)=>verdicts[index2])}async function searchRolesByPractitioner(medplum,candidates,options){let byPractitioner=new Map,references=[...new Set(candidates.filter(candidate=>getActorType(getCandidateActor(candidate))==="Practitioner").map(candidate=>getCandidateActor(candidate).reference))];if(references.length===0)return byPractitioner;let roles;try{roles=await medplum.searchResources("PractitionerRole",{practitioner:references.join(","),"active:not":"false",_count:"1000"},{signal:options?.signal})}catch{return byPractitioner}for(let role of roles){let reference=role.practitioner?.reference;if(!reference)continue;let held=byPractitioner.get(reference);held?held.push(role):byPractitioner.set(reference,[role])}return byPractitioner}async function isCandidateAtLocation(candidate,medplum,locationReference,getRoles,options){let actor=candidate.actorResource,actorReference=getCandidateActor(candidate),actorType=getActorType(actorReference);switch(actorType){case"Location":return isWithinLocation(medplum,actorReference.reference,locationReference,options);case"Device":{let device=actor?.resourceType==="Device"?actor:void 0;return isWithinLocation(medplum,device?.location?.reference,locationReference,options)}case"Practitioner":return isPractitionerAtLocation(actorReference.reference,locationReference,getRoles);case"HealthcareService":case"Patient":case"PractitionerRole":case"RelatedPerson":return!0;default:return assertNever2(actorType)}}async function isPractitionerAtLocation(actorReference,locationReference,getRoles){let roles=await getRoles(),practiceLocations=((actorReference?roles.get(actorReference):void 0)??[]).flatMap(role=>role.location??[]);return practiceLocations.length===0?!0:practiceLocations.some(roleLocation=>roleLocation.reference===locationReference)}async function isWithinLocation(medplum,reference,locationReference,options){if(!reference)return!0;let current=reference;for(let depth=0;depth<MAX_LOCATION_DEPTH;depth++){if(current===locationReference)return!0;let location=await readLocation(medplum,current,options);if(!location)return!0;let parent=location.partOf?.reference;if(!parent)return!1;current=parent}return!0}async function readLocation(medplum,reference,options){try{return await medplum.readReference({reference},{signal:options?.signal})}catch{return}}function getSelectedCandidates(selections){return BOOKABLE_ACTOR_TYPES.flatMap(actorType=>selections[actorType]??[])}function toScheduleReference(candidate){return{reference:`Schedule/${candidate.schedule.id}`}}function getSelectionError(selections){let missing=[...REQUIRED_ACTOR_TYPES].find(actorType=>!selections[actorType]?.length);return missing?`Choose at least one ${getActorTypeLabel(missing).toLowerCase()}`:void 0}function getActorCombinations(selections){let chosen=getSelectedCandidates(selections);return chosen.length>0?[toActorCombination(chosen)]:[]}function toActorCombination(candidates){let actors=candidates.map(getCandidateActor);return{key:getActorsKey(actors),label:candidates.map(getCandidateDisplay).join(" \xB7 "),actors,schedules:candidates.map(toScheduleReference)}}import{Stack,Text}from"@mantine/core";import{jsx,jsxs}from"react/jsx-runtime";function AppointmentOptionRow(props){return jsxs(Stack,{gap:0,children:[jsx(Text,{size:"sm",children:props.label}),props.detail&&jsx(Text,{size:"xs",c:"dimmed",children:props.detail})]})}import{Fragment,jsx as jsx2,jsxs as jsxs2}from"react/jsx-runtime";function AppointmentActorSelect(props){let{actorType,service,location,defaultValue,onChange,error,disabled}=props,medplum=useMedplum(),resolvedService=useResource(service),locationReference=location&&getReferenceString3(location),label=getActorTypeLabel(actorType),noun=label.toLowerCase(),required=isActorTypeRequired(actorType),search=useCallback(async(query,signal)=>resolvedService?searchScheduleCandidates(medplum,resolvedService,{actorType,query,location:locationReference?{reference:locationReference}:void 0,signal}):[],[medplum,resolvedService,locationReference,actorType]),handleChange=useCallback(candidates=>onChange(candidates),[onChange]);return jsx2(AsyncAutocomplete,{name:actorType,label,required,placeholder:`Search ${noun}s`,error,disabled,defaultValue:defaultValue?[...defaultValue]:void 0,toOption,loadOptions:search,itemComponent:CandidateItem,emptyComponent:()=>jsxs2(Fragment,{children:["No ",noun,"s found"]}),onChange:handleChange})}function toOption(candidate){return{value:candidate.schedule.id,label:getCandidateDisplay(candidate),resource:candidate}}function CandidateItem(props){return jsx2(AppointmentOptionRow,{label:props.label,detail:props.resource.schedule.comment})}import{isDefined as isDefined6}from"@medplum/core";import{useMedplum as useMedplum4}from"@medplum/react-hooks";import{useCallback as useCallback5}from"react";import{Alert,Button as Button2,Checkbox,Group as Group2,Loader,Pill,Stack as Stack4,Text as Text4,TextInput}from"@mantine/core";import{createReference,formatDate,getIdentifier,getIdentifierByType,getReferenceString as getReferenceString8,getSchedulingRequirements,getSchedulingTimezone,isDefined as isDefined5,MRN_IDENTIFIER_TYPE,normalizeErrorString as normalizeErrorString2,REQUIRES_DIAGNOSIS_CODE as REQUIRES_DIAGNOSIS_CODE2,REQUIRES_MEDICAL_NECESSITY_CODE as REQUIRES_MEDICAL_NECESSITY_CODE2,REQUIRES_PROCEDURE_CODE as REQUIRES_PROCEDURE_CODE2,SchedulingMedicalNecessityURI}from"@medplum/core";import{CalendarDateInput,ReferenceDisplay as ReferenceDisplay2,ResourceInput,ValueSetAutocomplete}from"@medplum/react";import{forwardRef,createElement}from"react";var defaultAttributes={outline:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"},filled:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none"}};var createReactComponent=(type,iconName,iconNamePascal,iconNode)=>{let Component5=forwardRef(({color="currentColor",size=24,stroke=2,title,className,children,...rest},ref)=>createElement("svg",{ref,...defaultAttributes[type],width:size,height:size,className:["tabler-icon",`tabler-icon-${iconName}`,className].join(" "),...type==="filled"?{fill:color}:{strokeWidth:stroke,stroke:color},...rest},[title&&createElement("title",{key:"svg-title"},title),...iconNode.map(([tag,attrs])=>createElement(tag,attrs)),...Array.isArray(children)?children:[children]]));return Component5.displayName=`${iconNamePascal}`,Component5};var __iconNode=[["path",{d:"M11.5 21h-5.5a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v4.5",key:"svg-0"}],["path",{d:"M16 3v4",key:"svg-1"}],["path",{d:"M8 3v4",key:"svg-2"}],["path",{d:"M4 11h16",key:"svg-3"}],["path",{d:"M15 18a3 3 0 1 0 6 0a3 3 0 1 0 -6 0",key:"svg-4"}],["path",{d:"M20.2 20.2l1.8 1.8",key:"svg-5"}]],IconCalendarSearch=createReactComponent("outline","calendar-search","CalendarSearch",__iconNode);var __iconNode2=[["path",{d:"M5 12l5 5l10 -10",key:"svg-0"}]],IconCheck=createReactComponent("outline","check","Check",__iconNode2);var __iconNode3=[["path",{d:"M6 9l6 6l6 -6",key:"svg-0"}]],IconChevronDown=createReactComponent("outline","chevron-down","ChevronDown",__iconNode3);var __iconNode4=[["path",{d:"M15 6l-6 6l6 6",key:"svg-0"}]],IconChevronLeft=createReactComponent("outline","chevron-left","ChevronLeft",__iconNode4);var __iconNode5=[["path",{d:"M9 6l6 6l-6 6",key:"svg-0"}]],IconChevronRight=createReactComponent("outline","chevron-right","ChevronRight",__iconNode5);var __iconNode6=[["path",{d:"M10.585 10.587a2 2 0 0 0 2.829 2.828",key:"svg-0"}],["path",{d:"M16.681 16.673a8.717 8.717 0 0 1 -4.681 1.327c-3.6 0 -6.6 -2 -9 -6c1.272 -2.12 2.712 -3.678 4.32 -4.674m2.86 -1.146a9.055 9.055 0 0 1 1.82 -.18c3.6 0 6.6 2 9 6c-.666 1.11 -1.379 2.067 -2.138 2.87",key:"svg-1"}],["path",{d:"M3 3l18 18",key:"svg-2"}]],IconEyeOff=createReactComponent("outline","eye-off","EyeOff",__iconNode6);var __iconNode7=[["path",{d:"M10 12a2 2 0 1 0 4 0a2 2 0 0 0 -4 0",key:"svg-0"}],["path",{d:"M21 12c-2.4 4 -5.4 6 -9 6c-3.6 0 -6.6 -2 -9 -6c2.4 -4 5.4 -6 9 -6c3.6 0 6.6 2 9 6",key:"svg-1"}]],IconEye=createReactComponent("outline","eye","Eye",__iconNode7);var __iconNode8=[["path",{d:"M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0",key:"svg-0"}],["path",{d:"M12 9h.01",key:"svg-1"}],["path",{d:"M11 12h1v4h1",key:"svg-2"}]],IconInfoCircle=createReactComponent("outline","info-circle","InfoCircle",__iconNode8);var __iconNode9=[["path",{d:"M5 12l14 0",key:"svg-0"}]],IconMinus=createReactComponent("outline","minus","Minus",__iconNode9);var __iconNode10=[["path",{d:"M12 5l0 14",key:"svg-0"}],["path",{d:"M5 12l14 0",key:"svg-1"}]],IconPlus=createReactComponent("outline","plus","Plus",__iconNode10);var __iconNode11=[["path",{d:"M18.364 4.636a9 9 0 0 1 .203 12.519l-.203 .21l-4.243 4.242a3 3 0 0 1 -4.097 .135l-.144 -.135l-4.244 -4.243a9 9 0 0 1 12.728 -12.728zm-6.364 3.364a3 3 0 1 0 0 6a3 3 0 0 0 0 -6",key:"svg-0"}]],IconMapPinFilled=createReactComponent("filled","map-pin-filled","MapPinFilled",__iconNode11);import{Fragment as Fragment2,useCallback as useCallback4,useEffect as useEffect2,useMemo as useMemo2,useRef,useState as useState3}from"react";import{Stack as Stack3,Text as Text3,Title}from"@mantine/core";import{Button,Group,Paper,Stack as Stack2,Text as Text2}from"@mantine/core";import{getReferenceString as getReferenceString4}from"@medplum/core";import{ReferenceDisplay}from"@medplum/react";var AppointmentFinder_default={timeGrid:"AppointmentFinder_timeGrid",layout:"AppointmentFinder_layout",form:"AppointmentFinder_form",results:"AppointmentFinder_results",codePill:"AppointmentFinder_codePill",requiredLabel:"AppointmentFinder_requiredLabel"};import{jsx as jsx3,jsxs as jsxs3}from"react/jsx-runtime";function ActorLabel(props){let label=getActorTypeLabel(getActorType(props.actor));return jsxs3(Stack2,{gap:2,children:[jsx3(Text2,{size:"xs",c:"dimmed",tt:"uppercase",children:label}),jsx3(Text2,{size:"sm",fw:500,children:jsx3(ReferenceDisplay,{value:props.actor,link:!1})})]})}function AppointmentSlotGroupCard(props){let{group,onSelectAppointment,timezone,viewerTimezone,selected,disabled}=props,withTimezone=!isViewerTimezone(timezone,viewerTimezone);return jsxs3(Paper,{withBorder:!0,p:"md","data-testid":`slot-group-${group.key}`,children:[jsxs3(Group,{justify:"space-between",align:"flex-start",wrap:"nowrap",mb:"sm",children:[jsx3(Group,{gap:"lg",align:"flex-start",wrap:"wrap",children:group.actors.map(actor=>jsx3(ActorLabel,{actor},getReferenceString4(actor)??actor.display))}),group.durationMinutes>0&&jsxs3(Text2,{size:"xs",c:"dimmed",style:{whiteSpace:"nowrap"},children:[group.durationMinutes," min visit"]})]}),jsx3(Group,{gap:"xs",className:AppointmentFinder_default.timeGrid,children:group.appointments.map(appointment=>jsx3(Button,{variant:selected===appointment?"filled":"outline",size:"sm",disabled,onClick:()=>onSelectAppointment(appointment),children:appointment.start?formatZonedTime(new Date(appointment.start),timezone,{withTimezone}):""},appointment.start))})]})}import{jsx as jsx4,jsxs as jsxs4}from"react/jsx-runtime";function AppointmentDayTimes(props){let{date,groups,onSelectAppointment,timezone,viewerTimezone,selected}=props;return jsxs4(Stack3,{gap:"xs",children:[jsx4(Title,{order:4,children:formatDayHeading(date)}),groups.length===0&&jsx4(Text3,{c:"dimmed",children:"No times are offered on this day."}),groups.map(group=>jsx4(AppointmentSlotGroupCard,{group,timezone,viewerTimezone,selected,onSelectAppointment},group.key))]})}import{CPT,HTTP_HL7_ORG,REQUIRES_DIAGNOSIS_CODE,REQUIRES_MEDICAL_NECESSITY_CODE,REQUIRES_PROCEDURE_CODE}from"@medplum/core";import{valueSetElementToCoding}from"@medplum/react";var DEFAULT_PROCEDURE_VALUE_SET=`${CPT}/vs`,DEFAULT_DIAGNOSIS_VALUE_SET=`${HTTP_HL7_ORG}/fhir/sid/icd-10-cm/vs`,EMPTY_REQUIREMENT_VALUES={procedure:[],diagnosis:[],medicalNecessity:!1},REQUIREMENT_ANSWERS={[REQUIRES_PROCEDURE_CODE]:values=>values.procedure.length>0,[REQUIRES_DIAGNOSIS_CODE]:values=>values.diagnosis.length>0,[REQUIRES_MEDICAL_NECESSITY_CODE]:values=>values.medicalNecessity};function isRequirementAnswered(requirement,values){return REQUIREMENT_ANSWERS[requirement](values)}function hasRequiredValues(values,requirements){return[...requirements].every(requirement=>isRequirementAnswered(requirement,values))}function toCodings(elements){return elements.map(element=>valueSetElementToCoding(element)).filter(coding=>!!coding.code)}import{formatCodeableConcept,getDisplayString as getDisplayString2,getReferenceString as getReferenceString6,hasSchedulingParameters}from"@medplum/core";import{AsyncAutocomplete as AsyncAutocomplete2}from"@medplum/react";import{useMedplum as useMedplum2}from"@medplum/react-hooks";import{useCallback as useCallback2}from"react";import{getExtensions,getReferenceString as getReferenceString5,isDefined as isDefined3,schedulingDurationToMinutes,SchedulingParametersURI}from"@medplum/core";function getServiceDurationMinutes(service){return getExtensions(service,[SchedulingParametersURI,"duration"]).map(subextension=>schedulingDurationToMinutes(subextension.valueDuration)).find(isDefined3)}function isServiceKeptAtLocation(service,location){let reference=location&&getReferenceString5(location),held=service.location??[];return!reference||held.length===0?!0:held.some(site=>site.reference===reference)}import{jsx as jsx5}from"react/jsx-runtime";var SERVICE_PAGE_SIZE=25,SERVICE_SEARCH_CRITERIA={_count:String(SERVICE_PAGE_SIZE),_sort:"name"};function AppointmentServiceSelect(props){let{location,defaultValue,onChange,label="Visit type",error,disabled}=props,medplum=useMedplum2(),locationReference=location&&getReferenceString6(location),loadOptions=useCallback2(async(input,signal)=>{let criteria=new URLSearchParams(SERVICE_SEARCH_CRITERIA);input&&criteria.set("name",input);let searches=locationReference?[withParam(criteria,"location",locationReference),withParam(criteria,"location:missing","true")]:[criteria],services=(await Promise.all(searches.map(async params=>medplum.searchResources("HealthcareService",params,{signal})))).flatMap(page=>page.filter(hasSchedulingParameters));return services.sort((left,right)=>(left.name??"").localeCompare(right.name??"")),services.slice(0,SERVICE_PAGE_SIZE)},[medplum,locationReference]),handleChange=useCallback2(services=>onChange(services[0]),[onChange]);return jsx5(AsyncAutocomplete2,{name:"service",label,placeholder:"Search visit types",required:!0,maxValues:1,error,disabled,defaultValue,toOption:toOption2,loadOptions,itemComponent:ServiceItem,onChange:handleChange})}function withParam(criteria,name,value){let params=new URLSearchParams(criteria);return params.set(name,value),params}function toOption2(service){return{value:service.id,label:getDisplayString2(service),resource:service}}function ServiceItem(props){return jsx5(AppointmentOptionRow,{label:props.label,detail:formatServiceDetail(props.resource)})}function formatServiceDetail(service){let category=formatCodeableConcept(service.type?.[0]),duration=getServiceDurationMinutes(service);return[category,duration!==void 0?`${duration} min`:void 0].filter(Boolean).join(" \xB7 ")||void 0}import{useCallback as useCallback3,useMemo,useState as useState2}from"react";import{getReferenceString as getReferenceString7,isDefined as isDefined4,isError,normalizeErrorString}from"@medplum/core";import{useMedplum as useMedplum3}from"@medplum/react-hooks";import{useEffect,useState}from"react";var DEFAULT_COUNT2=20,URL_SEPARATOR=`
|
|
2
|
-
`;function useProposedAppointments(options){let{service,combinations,range,count=DEFAULT_COUNT2}=options,medplum=useMedplum3(),[answered,setAnswered]=useState(NOTHING_ASKED),{start,end}=range,windowError=getFindWindowError(range),serviceReference=service&&getReferenceString7(service),urls=serviceReference&&start&&end&&!windowError?combinations.map(combination=>buildFindUrl(medplum,serviceReference,combination,start,end,count)):[],urlsKey=urls.join(URL_SEPARATOR),stale=answered.key!==urlsKey;return useEffect(()=>{if(!urlsKey)return;let controller=new AbortController,requests=urlsKey.split(URL_SEPARATOR);return Promise.allSettled(requests.map(async url=>medplum.get(url,{signal:controller.signal}))).then(results=>{if(controller.signal.aborted)return;let failure=results.find(result=>result.status==="rejected");setAnswered(failure&&results.every(result=>result.status==="rejected")?{key:urlsKey,appointments:[],error:toError(failure.reason)}:{key:urlsKey,appointments:collectAppointments(results),error:void 0})}).catch(reason=>{controller.signal.aborted||setAnswered({key:urlsKey,appointments:[],error:toError(reason)})}),()=>controller.abort()},[medplum,urlsKey]),{appointments:urls.length===0?NOTHING_ASKED.appointments:answered.appointments,requestCount:urls.length,loading:urls.length>0&&stale,error:stale?void 0:answered.error,windowError}}var NOTHING_ASKED={key:"",appointments:[],error:void 0};function toError(reason){return isError(reason)?reason:new Error(normalizeErrorString(reason),{cause:reason})}function buildFindUrl(medplum,serviceReference,combination,start,end,count){let url=medplum.fhirUrl("Appointment","$find");url.searchParams.set("start",start.toISOString()),url.searchParams.set("end",end.toISOString()),url.searchParams.set("service-type-reference",serviceReference);for(let schedule of combination.schedules)schedule.reference&&url.searchParams.append("schedule",schedule.reference);return url.searchParams.set("_count",count.toString()),url.toString()}function collectAppointments(results){return results.filter(result=>result.status==="fulfilled").flatMap(result=>(result.value.entry??[]).map(entry=>entry.resource).filter(isDefined4))}var MORE_DAYS=2,TIMES_PER_DAY=50;function useDaySearch(options){let{service,combinations,timezone,defaultStart,onDaysChanged}=options,[daySearch,setDaySearch]=useState2(()=>openDaySearch(defaultStart??new Date)),siteWindow=useMemo(()=>toSiteWindow(daySearch.range,timezone),[daySearch.range,timezone]),search=useProposedAppointments({service,combinations,range:siteWindow,count:TIMES_PER_DAY*getDayCount(siteWindow.start,siteWindow.end)}),selectedDayRange=useMemo(()=>({start:daySearch.original.start,end:daySearch.range.end}),[daySearch.original.start,daySearch.range.end]),{timeResultsByDay,hasTimes}=useMemo(()=>{let times=search.loading?daySearch.found:[...daySearch.found,...search.appointments],grouped=groupAppointmentsByDay(times,timezone,selectedDayRange);return{timeResultsByDay:grouped,hasTimes:grouped.some(day=>day.groups.length>0)}},[search.loading,search.appointments,daySearch.found,timezone,selectedDayRange]),chooseDayRange=useCallback3((start,end)=>{setDaySearch(openDaySearch(start,end)),onDaysChanged?.()},[onDaysChanged]),showMoreDays=useCallback3(()=>{setDaySearch(previous=>({original:previous.original,range:nextWindow(previous.range),found:[...previous.found,...search.appointments]}))},[search.appointments]),reset=useCallback3(()=>{setDaySearch(previous=>({original:previous.original,range:previous.original,found:[]}))},[]),loadingFirstDays=search.loading&&daySearch.range.start.getTime()===daySearch.original.start.getTime();return{selectedDayRange,timeResultsByDay,hasTimes,loadingFirstDays,loadingMoreDays:search.loading&&!loadingFirstDays,findRequestError:search.error,windowError:search.windowError,chooseDayRange,showMoreDays,reset}}function floorToNow(date){let now=new Date;return date>now?date:now}function openDaySearch(start,end=start){let from=floorToNow(start),window2={start:from,end:endOfDay(end>from?end:from)};return{original:window2,range:window2,found:[]}}function toSiteWindow(days,timezone){return{start:getZonedDayRange(days.start,timezone).start,end:getZonedDayRange(days.end,timezone).end}}function nextWindow(range){let start=startOfDay(addDays(range.end,1));return{start,end:endOfDay(addDays(start,MORE_DAYS-1))}}import{Fragment as Fragment3,jsx as jsx6,jsxs as jsxs5}from"react/jsx-runtime";var LOCATION_SEARCH_CRITERIA={_count:"25",_sort:"name","physical-type:not":"ro,bd"},PATIENT_SEARCH_CRITERIA={_count:"25",_sort:"name,birthdate"},NO_MARKED_DATES=[];function AppointmentProposalForm(props){let{defaultLocation,defaultService,defaultPatient,defaultStart,mrnSystem,onToggleTimeFinder,onChangeService,onChangeTime,procedureBinding=DEFAULT_PROCEDURE_VALUE_SET,diagnosisBinding=DEFAULT_DIAGNOSIS_VALUE_SET,onBook}=props,[location,setLocation]=useState3(defaultLocation),[service,setService]=useState3(defaultService),[selections,setSelections]=useState3({}),[month,setMonth]=useState3(defaultStart),[finding,setFinding]=useState3(!1),[chosen,setChosen]=useState3(void 0),[actorFieldsKey,setActorFieldsKey]=useState3(0),[serviceFieldKey,setServiceFieldKey]=useState3(0),[patient,setPatient]=useState3(defaultPatient),[requirementValues,setRequirementValues]=useState3(EMPTY_REQUIREMENT_VALUES),[booking,setBooking]=useState3(!1),[booked,setBooked]=useState3(!1),[bookError,setBookError]=useState3(void 0),selectionError=getSelectionError(selections),requirements=useMemo2(()=>getSchedulingRequirements(service),[service]),requirementsOutstanding=!hasRequiredValues(requirementValues,requirements),searching=finding&&!selectionError,combinations=useMemo2(()=>searching?getActorCombinations(selections):[],[searching,selections]),timezone=useMemo2(()=>{let[first]=getSelectedCandidates(selections);return service?getSchedulingTimezone(service,first?.schedule,first?.actorResource):void 0},[service,selections]),clearChosen=useCallback4(()=>setChosen(void 0),[]),daySearch=useDaySearch({service,combinations,timezone,defaultStart,onDaysChanged:clearChosen}),{reset:resetDaySearch}=daySearch,settled=!daySearch.loadingFirstDays&&!daySearch.findRequestError&&!daySearch.windowError,reported=useRef(!1);useEffect2(()=>{reported.current!==searching&&(reported.current=searching,onToggleTimeFinder?.(searching))},[searching,onToggleTimeFinder]);let reportedTime=useRef(void 0);useEffect2(()=>{reportedTime.current!==chosen&&(reportedTime.current=chosen,onChangeTime?.(toRange(chosen)))},[chosen,onChangeTime]);let patientItem=useCallback4(option=>jsx6(AppointmentOptionRow,{label:option.label,detail:formatPatientDetail(option.resource,mrnSystem)}),[mrnSystem]);function toggleFinder(){setFinding(!finding)}let chooseResources=useCallback4(update=>{setSelections(update),setChosen(void 0),resetDaySearch()},[resetDaySearch]);function chooseService(next){setService(next),onChangeService?.(next),setRequirementValues(EMPTY_REQUIREMENT_VALUES),clearResources()}function chooseLocation(next){setLocation(next),clearResources(),service&&!isServiceKeptAtLocation(service,next)&&(setService(void 0),onChangeService?.(void 0),setServiceFieldKey(key=>key+1))}function clearResources(){setSelections({}),setChosen(void 0),setActorFieldsKey(key=>key+1),resetDaySearch()}function chooseTime(next){setChosen(next),setBooked(!1)}function choosePatient(next){setPatient(next),setBooked(!1)}function chooseRequirementValues(next){setRequirementValues(next),setBooked(!1)}async function bookAppointment(){if(!(!chosen||!patient||requirementsOutstanding)){setBooking(!0),setBookError(void 0);try{await onBook(buildBooking(chosen,patient,requirementValues,requirements)),setBooked(!0)}catch(error){setBookError(error)}finally{setBooking(!1)}}}return jsxs5("div",{className:AppointmentFinder_default.layout,children:[jsxs5(Stack4,{className:AppointmentFinder_default.form,gap:"sm",children:[jsx6(ResourceInput,{resourceType:"Location",name:"location",label:"Location",placeholder:"Any location",searchCriteria:LOCATION_SEARCH_CRITERIA,defaultValue:defaultLocation,onChange:chooseLocation}),jsx6(AppointmentServiceSelect,{location,defaultValue:service,onChange:chooseService},serviceFieldKey),BOOKABLE_ACTOR_TYPES.map(actorType=>jsx6(ActorField,{actorType,service,location,disabled:!service,onChange:chooseResources},`${actorType}-${actorFieldsKey}`)),jsx6(ChosenTime,{appointment:chosen,timezone,searching,blockedBy:service?selectionError:"Choose a visit type",onToggleFinder:toggleFinder}),searching&&jsxs5(Stack4,{gap:4,children:[jsx6(CalendarDateInput,{availableDates:NO_MARKED_DATES,allowUnavailableDates:!0,earliestDate:new Date,month,range:daySearch.selectedDayRange,onChangeMonth:setMonth,onClick:daySearch.chooseDayRange,onSelectRange:daySearch.chooseDayRange}),daySearch.windowError&&jsx6(Alert,{color:"yellow",children:daySearch.windowError})]}),jsx6(ResourceInput,{resourceType:"Patient",name:"patient",label:"Patient",placeholder:"Search patients by name",required:!0,searchCriteria:PATIENT_SEARCH_CRITERIA,defaultValue:defaultPatient,itemComponent:patientItem,onChange:choosePatient}),service&&requirements.size>0&&jsxs5(Fragment2,{children:[requirements.has(REQUIRES_PROCEDURE_CODE2)&&jsx6(ValueSetAutocomplete,{name:"procedure-code",label:"Procedure codes",required:!0,creatable:!1,itemComponent:RequirementCodeItem,pillComponent:RequirementCodePill,binding:procedureBinding,onChange:elements=>chooseRequirementValues({...requirementValues,procedure:toCodings(elements)})}),requirements.has(REQUIRES_DIAGNOSIS_CODE2)&&jsx6(ValueSetAutocomplete,{name:"diagnosis-code",label:"Diagnosis codes",required:!0,creatable:!1,itemComponent:RequirementCodeItem,pillComponent:RequirementCodePill,binding:diagnosisBinding,onChange:elements=>chooseRequirementValues({...requirementValues,diagnosis:toCodings(elements)})}),requirements.has(REQUIRES_MEDICAL_NECESSITY_CODE2)&&jsx6(Checkbox,{classNames:{label:AppointmentFinder_default.requiredLabel},label:"Medical necessity confirmed",required:!0,checked:requirementValues.medicalNecessity,onChange:event=>chooseRequirementValues({...requirementValues,medicalNecessity:event.currentTarget.checked})})]},service.id),bookError!==void 0&&jsx6(Alert,{color:"red",children:normalizeErrorString2(bookError)}),jsx6(Button2,{fullWidth:!0,disabled:!chosen||!patient||booked||requirementsOutstanding,loading:booking,onClick:bookAppointment,children:"Book appointment"})]}),searching&&jsxs5(Stack4,{className:AppointmentFinder_default.results,gap:"lg",children:[daySearch.loadingFirstDays&&jsx6(Loader,{size:"sm"}),daySearch.findRequestError&&jsx6(Alert,{color:"red",children:normalizeErrorString2(daySearch.findRequestError)}),!daySearch.loadingFirstDays&&daySearch.hasTimes&&daySearch.timeResultsByDay.map(day=>jsx6(AppointmentDayTimes,{date:day.date,groups:day.groups,timezone,selected:chosen,onSelectAppointment:chooseTime},day.key)),settled&&jsxs5(Fragment3,{children:[!daySearch.hasTimes&&jsx6(Text4,{c:"dimmed",ta:"center",children:"No times are available for this selection."}),jsx6(Button2,{variant:"subtle",loading:daySearch.loadingMoreDays,onClick:daySearch.showMoreDays,children:"Show more days"})]})]})]})}function ChosenTime(props){let{appointment,timezone,searching,blockedBy,onToggleFinder}=props;return jsxs5(Fragment3,{children:[appointment?.start&&jsx6(TextInput,{label:"Date & time",readOnly:!0,value:formatZonedDateTime(new Date(appointment.start),timezone),inputWrapperOrder:["label","input","description"],description:jsx6(ChosenTimeCommitment,{appointment})}),jsxs5(Stack4,{gap:4,children:[jsx6(Button2,{variant:"outline",fullWidth:!0,leftSection:jsx6(IconCalendarSearch,{size:16,stroke:1.8}),disabled:!!blockedBy,onClick:onToggleFinder,children:getFinderLabel(searching,!!appointment)}),blockedBy&&jsxs5(Text4,{size:"xs",c:"dimmed",children:[blockedBy," first."]})]})]})}function ChosenTimeCommitment(props){let{appointment}=props,actors=(appointment.participant??[]).map(participant=>participant.actor).filter(isDefined5),durationMinutes=getDurationMinutes(appointment);return jsxs5(Fragment3,{children:[durationMinutes>0&&`${durationMinutes} min visit`,actors.map((actor,index2)=>{let actorLabel=getActorTypeLabel(getActorType(actor));return jsxs5(Fragment2,{children:[(index2>0||durationMinutes>0)&&" \xB7 ",actorLabel,": ",jsx6(ReferenceDisplay2,{value:actor,link:!1})]},getReferenceString8(actor)??actor.display)})]})}function getFinderLabel(searching,chosen){return searching?"Close time finder":chosen?"Change time":"Find a time"}function RequirementCodeItem(props){let{label,resource,active}=props;return jsxs5(Group2,{wrap:"nowrap",gap:"xs",children:[active&&jsx6(IconCheck,{size:12}),jsxs5(Text4,{size:"sm",children:[jsx6(Text4,{span:!0,fw:600,children:resource.code})," ",jsx6(Text4,{span:!0,children:label})]})]})}function RequirementCodePill(props){let{item,disabled,onRemove}=props,code=item.resource.code;return jsx6(Pill,{className:AppointmentFinder_default.codePill,withRemoveButton:!disabled,onRemove,title:item.label,children:code?`${code} \xB7 ${item.label}`:item.label})}function ActorField(props){let{actorType,service,location,disabled,onChange}=props,handleChange=useCallback4(candidates=>onChange(selections=>({...selections,[actorType]:candidates})),[onChange,actorType]);return jsx6(AppointmentActorSelect,{actorType,service,location,disabled,onChange:handleChange})}function buildBooking(proposal,patient,values,requirements){let patientReference=getReferenceString8(patient),procedure=requirements.has(REQUIRES_PROCEDURE_CODE2)?values.procedure:[],diagnosis=requirements.has(REQUIRES_DIAGNOSIS_CODE2)?values.diagnosis:[],serviceType=[...proposal.serviceType??[],...procedure.map(coding=>({coding:[coding]}))],reasonCode=[...proposal.reasonCode??[],...diagnosis.map(coding=>({coding:[coding]}))],extension=[...proposal.extension??[],...requirements.has(REQUIRES_MEDICAL_NECESSITY_CODE2)?[{url:SchedulingMedicalNecessityURI,valueBoolean:values.medicalNecessity}]:[]];return{...proposal,participant:[...proposal.participant.filter(participant=>participant.actor?.reference!==patientReference),{actor:createReference(patient),required:"required",status:"needs-action"}],...serviceType.length>0&&{serviceType},...reasonCode.length>0&&{reasonCode},...extension.length>0&&{extension}}}function formatPatientDetail(patient,mrnSystem){let mrn=getMedicalRecordNumber(patient,mrnSystem);return[formatDate(patient.birthDate),mrn&&`MRN ${mrn}`].filter(Boolean).join(" \xB7 ")||void 0}function getMedicalRecordNumber(patient,mrnSystem){return getIdentifierByType(patient,MRN_IDENTIFIER_TYPE)??(mrnSystem?getIdentifier(patient,mrnSystem):void 0)}function toRange(appointment){if(!(!appointment?.start||!appointment.end))return{start:new Date(appointment.start),end:new Date(appointment.end)}}function formatZonedDateTime(value,timezone){return new Intl.DateTimeFormat(void 0,{timeZone:timezone,weekday:"long",month:"long",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:isViewerTimezone(timezone)?void 0:"shortGeneric"}).format(value)}import{jsx as jsx7}from"react/jsx-runtime";function AppointmentBookingForm(props){let{onBooked,...formProps}=props,medplum=useMedplum4(),book=useCallback5(async proposal=>{let written=await medplum.post(medplum.fhirUrl("Appointment","$book"),{resourceType:"Parameters",parameter:[{name:"appointment",resource:proposal}]}),booking=readBooking(written);medplum.notifyResourceModified({resourceType:"Appointment",operation:"create",id:booking.appointment.id,resource:booking.appointment});for(let slot of booking.slots)medplum.notifyResourceModified({resourceType:"Slot",operation:"create",id:slot.id,resource:slot});try{await onBooked(booking)}catch(error){console.error(error)}},[medplum,onBooked]);return jsx7(AppointmentProposalForm,{...formProps,onBook:book})}function readBooking(written){let resources=(written.entry??[]).map(entry=>entry.resource).filter(isDefined6),appointment=resources.find(resource=>resource.resourceType==="Appointment");if(!appointment)throw new Error("$book returned no appointment");return{appointment,slots:resources.filter(resource=>resource.resourceType==="Slot")}}function r(e){var t,f,n="";if(typeof e=="string"||typeof e=="number")n+=e;else if(typeof e=="object")if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(f=r(e[t]))&&(n&&(n+=" "),n+=f)}else for(f in e)e[f]&&(n&&(n+=" "),n+=f);return n}function clsx(){for(var e,t,f=0,n="",o=arguments.length;f<o;f++)(e=arguments[f])&&(t=r(e))&&(n&&(n+=" "),n+=t);return n}var clsx_default=clsx;import{useMemo as useMemo4}from"react";var NativeTemporal=globalThis.Temporal;var expectedPositive=(entityName,num)=>`Non-positive ${entityName}: ${num}`,expectedFinite=(entityName,num)=>`Non-finite ${entityName}: ${num}`,forbiddenBigIntToNumber=entityName=>`Cannot convert bigint to ${entityName}`,invalidObject="Invalid object",numberOutOfRange=(entityName,val,min,max)=>invalidEntity(entityName,val)+`; must be between ${min}-${max}`,invalidEntity=(fieldName,val)=>`Invalid ${fieldName}: ${val}`;var nanoInMicro=1e3,nanoInMilli=1e6,nanoInSec=1e9,nanoInMinute=6e10,nanoInHour=36e11;function normalizeOptions(options){return options===void 0?Object.create(null):requireObjectLike(options)}function toFiniteNumber(arg,entityName="number"){if(typeof arg=="bigint")throw new TypeError(forbiddenBigIntToNumber(entityName));if(arg=Number(arg),!Number.isFinite(arg))throw new RangeError(expectedFinite(entityName,arg));return arg}function toIntegerWithTrunc(arg,entityName){return Math.trunc(toFiniteNumber(arg,entityName))||0}function toPositiveIntegerWithTruncation(arg,entityName){return requireNumberIsPositive(toIntegerWithTrunc(arg,entityName),entityName)}function requireNumberIsPositive(num,entityName="number"){if(num<=0)throw new RangeError(expectedPositive(entityName,num));return num}function constrainToRange(num,min,max){return Math.min(Math.max(num,min),max)}function isObjectLike(arg){return arg!==null&&(typeof arg=="object"||typeof arg=="function")}function requireObjectLike(arg){if(!isObjectLike(arg))throw new TypeError(invalidObject);return arg}function createDiffFunc(unit){return(date0,date1,options)=>{let normOptions=normalizeDiffOptions(options);if(normOptions.roundingMode)return date0.until(date1,{...normOptions,largestUnit:unit,smallestUnit:unit})[unit];let duration=date0.until(date1,{...normOptions,largestUnit:unit});if(isTimeUnit(unit))return duration.total(unit);let relativeTo=!("day"in date0)&&"toPlainDate"in date0?date0.toPlainDate({day:1}):date0;return duration.total({unit,relativeTo})}}function isTimeUnit(unit){return unit==="hours"||unit==="minutes"||unit==="seconds"||unit==="milliseconds"||unit==="microseconds"||unit==="nanoseconds"}var diffYears=createDiffFunc("years"),diffMonths=createDiffFunc("months"),diffWeeks=createDiffFunc("weeks"),diffDays=createDiffFunc("days"),diffHours=createDiffFunc("hours"),diffMinutes=createDiffFunc("minutes"),diffSeconds=createDiffFunc("seconds"),diffMilliseconds=createDiffFunc("milliseconds"),diffMicroseconds=createDiffFunc("microseconds"),diffNanoseconds=createDiffFunc("nanoseconds");function normalizeDiffOptions(options){return typeof options=="string"?{roundingMode:options}:options||{}}var invalidEntity2=invalidEntity;var missingField=fieldName=>`Missing ${fieldName}`;var invalidChoice=(fieldName,val,choiceMap)=>invalidEntity(fieldName,val)+"; must be "+Object.keys(choiceMap).join(),forbiddenValueOf="Cannot use valueOf",invalidCallingContext="Invalid calling context";var exoticCalendarRequired=(calendarId,remedy)=>`Unknown calendar ${calendarId}; might need ${remedy}`,invalidTimeZone=calendarId=>invalidEntity("TimeZone",calendarId),outOfBoundsDate="Out-of-bounds date";var failedParse=s=>`Cannot parse: ${s}`,invalidSubstring=substring=>`Invalid substring: ${substring}`;var constrainToRange2=constrainToRange;function throwRangeError(message){throw new RangeError(message)}function throwTypeError(message){throw new TypeError(message)}function clampProp(props,propName,min,max,overflow){return clampEntity(propName,((props2,propName2)=>{let propVal=props2[propName2];return propVal===void 0&&throwTypeError(missingField(propName2)),propVal})(props,propName),min,max,overflow)}function clampEntity(entityName,num,min,max,overflow,choices){let clamped=constrainToRange2(num,min,max);return overflow&&num!==clamped&&throwRangeError(((entityName2,val,min2,max2,choices2)=>choices2?numberOutOfRange(entityName2,choices2[val],choices2[min2],choices2[max2]):numberOutOfRange(entityName2,val,min2,max2))(entityName,num,min,max,choices)),clamped}function memoize(generator,MapClass=Map){let map=new MapClass;return(key,...otherArgs)=>{if(map.has(key))return map.get(key);let val=generator(key,...otherArgs);return map.set(key,val),val}}var createNameDescriptors=name=>createPropDescriptors({name},1),createPropDescriptors=(propVals,readonly)=>mapProps(value=>({value,configurable:1,writable:!readonly}),propVals),createStringTagDescriptors=value=>({[Symbol.toStringTag]:{value,configurable:1}});function mapProps(transformer,props){let res={};for(let propName in props)res[propName]=transformer(props[propName],propName);return res}function zipPropsConst(propNames,propVal){let res={};for(let propName of propNames)res[propName]=propVal;return res}function createPropGetters(propNames){let getters={};for(let propName of propNames)getters[propName]=slots=>slots[propName];return getters}function pluckProps(propNames,props,dest=Object.create(null)){for(let propName of propNames)dest[propName]=props[propName];return dest}function bindArgs(f,...boundArgs){return(...dynamicArgs)=>f(...boundArgs,...dynamicArgs)}function noop(){}function capitalize(s){return s[0].toUpperCase()+s.substring(1)}function createRegExp(meat){return new RegExp(`^${meat}$`,"i")}function parseSubsecNano(fracStr){return parseInt(fracStr.padEnd(9,"0"))}function parseSign(s){return s&&s!=="+"?-1:1}function parseInt0(s){return s===void 0?0:parseInt(s)}function padNumber(digits,num){return String(num).padStart(digits,"0")}var padNumber2=bindArgs(padNumber,2);function compareNumbers(a,b){return Math.sign(a-b)}function divFloorBigInt(num,denom){let whole=num/denom;return num%denom<0n?whole-1n:whole}function divModFloorBigInt(num,divisor){let quotient=divFloorBigInt(num,divisor);return[quotient,num-quotient*divisor]}function divModFloor(num,divisor){return[Math.floor(num/divisor),modFloor(num,divisor)]}function modFloor(num,divisor){return(num%divisor+divisor)%divisor}function divTrunc(num,divisor){return Math.trunc(num/divisor)||0}function hasHalf(num){return Math.abs(num%1)===.5}function normalizeEraName(era){let normalized=era.normalize("NFD").toLowerCase().replace(/[^a-z0-9]/g,"");return normalized==="bc"||normalized==="b"?"bce":normalized==="ad"||normalized==="a"?"ce":normalized}var isoCalendarImpl=void 0;function getCalendarSlotId(calendar){return calendar===isoCalendarImpl?"iso8601":calendar===0?"gregory":calendar.id}function formatMonthCode(monthCodeNumber,isLeapMonth){return"M"+padNumber2(monthCodeNumber)+(isLeapMonth?"L":"")}var unitNameMap={nanosecond:0,microsecond:1,millisecond:2,second:3,minute:4,hour:5,day:6,week:7,month:8,year:9},unitNamesAsc=Object.keys(unitNameMap);var nanoInMicro2=nanoInMicro,nanoInMilli2=nanoInMilli,nanoInSec2=nanoInSec,nanoInMinute2=nanoInMinute,nanoInHour2=nanoInHour,nanoInUtcDay=864e11;var bigNanoInMilli=BigInt(nanoInMilli2),bigNanoInSec=BigInt(nanoInSec2);var bigNanoInUtcDay=BigInt(nanoInUtcDay);var timeFieldNamesAsc=unitNamesAsc.slice(0,6),timeGetters=createPropGetters(timeFieldNamesAsc);var calendarDateFieldNamesAsc=["day","month","year"];function validateTimeFields(timeFields){return constrainTimeFields(timeFields,1),timeFields}var maxValues={hour:23,minute:59,second:59};function constrainTimeFields(timeFields,overflow){let constrainedFields={};for(let fieldName of timeFieldNamesAsc)constrainedFields[fieldName]=clampEntity(fieldName,timeFields[fieldName],0,maxValues[fieldName]||999,overflow);return constrainedFields}function timeFieldsToNano(timeFields){return timeFieldsToSec(timeFields)*nanoInSec2+timeFieldsToSubsecNano(timeFields)}function timeFieldsToSec(timeFields){return 3600*timeFields.hour+60*timeFields.minute+timeFields.second}function timeFieldsToSubsecNano(timeFields){return timeFields.millisecond*nanoInMilli2+timeFields.microsecond*nanoInMicro2+timeFields.nanosecond}function nanoToTimeFields(timeNano){let[timeMilli,nanoAfterMilli]=divModFloor(timeNano,nanoInMilli2),[microsecond,nanosecond]=divModFloor(nanoAfterMilli,nanoInMicro2);return milliToTimeFields(timeMilli,microsecond,nanosecond)}function milliToTimeFields(timeMilli,microsecond=0,nanosecond=0){let[hour,milliAfterHour]=divModFloor(timeMilli,36e5),[minute,milliAfterMinute]=divModFloor(milliAfterHour,6e4),[second,millisecond]=divModFloor(milliAfterMinute,1e3);return{hour,minute,second,millisecond,microsecond,nanosecond}}function epochNanoToSecMod(epochNano){let[epochSec,nano]=divModFloorBigInt(epochNano,bigNanoInSec);return[Number(epochSec),Number(nano)]}function isoDateTimeToEpochNano(isoDateTime){return isoDateToEpochNano(isoDateTime)+BigInt(timeFieldsToNano(isoDateTime))}function isoDateToEpochNano(isoDate){return BigInt(isoDateToEpochDays(isoDate))*bigNanoInUtcDay}function isoDateToEpochDays(isoDate){return isoArgsToEpochDays(isoDate.year,isoDate.month,isoDate.day)}function isoArgsToEpochDays(isoYear,isoMonth=1,isoDay=1){let monthIndex=isoMonth-1;return isoYear+=Math.floor(monthIndex/12),isoMonth=modFloor(monthIndex,12),Date.UTC(isoYear%400-400,isoMonth,0)/864e5+146097*(divTrunc(isoYear,400)+1)+isoDay}function epochNanoToIsoDateTime(epochNano){let[epochDays,nanoAfterDay]=divModFloorBigInt(epochNano,bigNanoInUtcDay);return{...epochDaysToIsoDate(Number(epochDays)),...nanoToTimeFields(Number(nanoAfterDay))}}function epochDaysToIsoDate(epochDays){let legacyDate=new Date(864e5*modFloor(epochDays,146097));return{year:legacyDate.getUTCFullYear()+400*Math.floor(epochDays/146097),month:legacyDate.getUTCMonth()+1,day:legacyDate.getUTCDate()}}function computeIsoMonthCodeParts(month){return[month,0]}function computeIsoFieldsFromParts(year,month,day){return{year,month,day}}function computeIsoDaysInMonth(year,month){switch(month){case 2:return computeIsoInLeapYear(year)?29:28;case 4:case 6:case 9:case 11:return 30}return 31}function computeIsoDaysInYear(year){return computeIsoInLeapYear(year)?366:365}function computeIsoInLeapYear(year){return year%4==0&&(year%100!=0||year%400==0)}function computeIsoDayOfWeek(isoDateFields){return modFloor(isoArgsToEpochDays(isoDateFields.year,isoDateFields.month,isoDateFields.day)+4,7)||7}function computeIsoDayOfYear(isoDateFields){return isoArgsToEpochDays(isoDateFields.year,isoDateFields.month,isoDateFields.day)-isoArgsToEpochDays(isoDateFields.year)+1}function computeIsoWeekFields(isoDateFields){let yearOfWeek3=isoDateFields.year,weekOfYear4=Math.floor((computeIsoDayOfYear(isoDateFields)-computeIsoDayOfWeek(isoDateFields)+10)/7),weeksInYear=computeIsoWeeksInYear(yearOfWeek3);return weekOfYear4<1?weekOfYear4=weeksInYear=computeIsoWeeksInYear(--yearOfWeek3):weekOfYear4>weeksInYear&&(weekOfYear4=1,weeksInYear=computeIsoWeeksInYear(++yearOfWeek3)),{weekOfYear:weekOfYear4,yearOfWeek:yearOfWeek3,Be:weeksInYear}}function computeIsoWeeksInYear(year){let y0DayOfWeek=computeIsoDayOfWeek({year,month:1,day:1});return y0DayOfWeek===4||y0DayOfWeek===3&&computeIsoInLeapYear(year)?53:52}function computeGregoryEraFields({year}){return year<1?{era:"bce",eraYear:1-year}:{era:"ce",eraYear:year}}function validateIsoDateTimeFields(isoDateTime){return validateIsoDateFields(isoDateTime),validateTimeFields(isoDateTime)}function validateIsoDateFields(isoInternals){return constrainIsoDateFields(isoInternals,1),isoInternals}function constrainIsoDateFields(isoDate,overflow){let{year}=isoDate,month=clampProp(isoDate,"month",1,12,overflow);return{year,month,day:clampProp(isoDate,"day",1,computeIsoDaysInMonth(year,month),overflow)}}function computeCalendarDateFields(calendar,isoDate){return calendar?calendar.ae(isoDate):isoDate}function computeCalendarMonthCodeParts(calendar,year,month){return calendar?calendar.L(year,month):computeIsoMonthCodeParts(month)}function computeCalendarEraFields(calendar,isoDate){return calendar===0?computeGregoryEraFields(isoDate):calendar&&calendar.h?.(isoDate)||{}}function computeCalendarIsoFieldsFromParts(calendar,year,month,day){return calendar?calendar.de(year,month,day):computeIsoFieldsFromParts(year,month,day)}function computeCalendarMonthsInYearForYear(calendar,year){return calendar?calendar.j(year):12}function computeCalendarDaysInMonthForYearMonth(calendar,year,month){return calendar?calendar.o(year,month):computeIsoDaysInMonth(year,month)}function computeCalendarMonthCode(calendar,isoDate){let{year,month}=computeCalendarDateFields(calendar,isoDate),[monthCodeNumber,isLeapMonth]=computeCalendarMonthCodeParts(calendar,year,month);return formatMonthCode(monthCodeNumber,isLeapMonth)}function computeCalendarInLeapYear(calendar,isoDate){let{year}=computeCalendarDateFields(calendar,isoDate);return calendar?calendar.q(year):computeIsoInLeapYear(year)}function computeCalendarMonthsInYear(calendar,isoDate){let{year}=computeCalendarDateFields(calendar,isoDate);return computeCalendarMonthsInYearForYear(calendar,year)}function computeCalendarDaysInMonth(calendar,isoDate){let{year,month}=computeCalendarDateFields(calendar,isoDate);return computeCalendarDaysInMonthForYearMonth(calendar,year,month)}function computeCalendarDaysInYear(calendar,isoDate){let{year}=computeCalendarDateFields(calendar,isoDate);return calendar?calendar.i(year):computeIsoDaysInYear(year)}function computeCalendarDayOfYear(calendar,isoDate){if(!calendar)return computeIsoDayOfYear(isoDate);let{year}=computeCalendarDateFields(calendar,isoDate),yearStartIsoDate=computeCalendarIsoFieldsFromParts(calendar,year,1,1);return isoDateToEpochDays(isoDate)-isoDateToEpochDays(yearStartIsoDate)+1}function computeCalendarWeekOfYear(calendar,isoDate){return calendar===isoCalendarImpl?computeIsoWeekFields(isoDate).weekOfYear:void 0}function computeCalendarYearOfWeek(calendar,isoDate){return calendar===isoCalendarImpl?computeIsoWeekFields(isoDate).yearOfWeek:void 0}var requireString=bindArgs(requireType,"string");function requireType(typeName,arg,entityName=typeName){return typeof arg!==typeName&&throwTypeError(invalidEntity2(entityName,arg)),arg}function requireNumberIsInteger(num,entityName="number"){return Number.isInteger(num)||throwRangeError(((entityName2,num2)=>`Non-integer ${entityName2}: ${num2}`)(entityName,num)),num||0}function toString(arg){return typeof arg=="symbol"&&throwTypeError("Cannot convert Symbol to string"),String(arg)}function toStringViaPrimitive(arg,entityName){return isObjectLike(arg)?String(arg):requireString(arg,entityName)}function toStrictInteger(arg,entityName){return requireNumberIsInteger(toFiniteNumber(arg,entityName),entityName)}var epochDisambigMap={compatible:0,reject:1,earlier:2,later:3};var roundingModeFuncs=[Math.floor,num=>hasHalf(num)?Math.floor(num):Math.round(num),Math.ceil,num=>hasHalf(num)?Math.ceil(num):Math.round(num),Math.trunc,num=>hasHalf(num)?Math.trunc(num)||0:Math.round(num),num=>num<0?Math.floor(num):Math.ceil(num),num=>Math.sign(num)*Math.round(Math.abs(num))||0,num=>hasHalf(num)?(num=Math.trunc(num)||0)+num%2:Math.round(num)];function coerceChoiceOption(optionName,enumNameMap,options,defaultChoice=0){let enumArg=options[optionName];if(enumArg===void 0)return defaultChoice;let enumStr=toString(enumArg),enumNum=enumNameMap[enumStr];return enumNum===void 0&&throwRangeError(invalidChoice(optionName,enumStr,enumNameMap)),enumNum}var coerceEpochDisambig=bindArgs(coerceChoiceOption,"disambiguation",epochDisambigMap);function combineDateAndTime(isoDate,time){return pluckProps(calendarDateFieldNamesAsc,isoDate,pluckProps(timeFieldNamesAsc,time))}var epochNanoMax=BigInt(1e8)*bigNanoInUtcDay,epochNanoMin=BigInt(-1e8)*bigNanoInUtcDay,plainDateEpochNanoMin=epochNanoMin-bigNanoInUtcDay;function checkIsoDateInBounds(isoDate,allowPlainDateLowerEdge=1){return checkIsoDateEpochNanoInBounds(isoDateToEpochNano(isoDate),allowPlainDateLowerEdge),isoDate}function checkIsoDateTimeInBounds(isoDateTime){let epochNano=isoDateToEpochNano(isoDateTime);return checkIsoDateEpochNanoInBounds(epochNano),epochNano!==plainDateEpochNanoMin||timeFieldsToNano(isoDateTime)||throwRangeError(outOfBoundsDate),isoDateTime}function checkIsoDateEpochNanoInBounds(epochNano,allowPlainDateLowerEdge=1){(epochNano<(allowPlainDateLowerEdge?plainDateEpochNanoMin:epochNanoMin)||epochNano>epochNanoMax)&&throwRangeError(outOfBoundsDate)}function checkEpochNanoInBounds(epochNano){return(epochNano<epochNanoMin||epochNano>epochNanoMax)&&throwRangeError(outOfBoundsDate),epochNano}function isoDateTimeAndOffsetToEpochNano(isoDateTime,offsetNano){return checkEpochNanoInBounds(isoDateToEpochNano(isoDateTime)+BigInt(timeFieldsToNano(isoDateTime)-offsetNano))}function createEpochNanoSlots(epochNano){return{epochNanoseconds:epochNano}}function createZonedEpochNanoSlots(epochNano,timeZone,calendar){return{calendar,timeZone,epochNanoseconds:epochNano}}function createDateTimeSlots(isoDateTime,calendar){return pluckProps(timeFieldNamesAsc,isoDateTime,createDateSlots(isoDateTime,calendar))}function createDateSlots(isoDate,calendar){return pluckProps(calendarDateFieldNamesAsc,isoDate,{calendar})}function getEpochMilli(slots){return epochNano=slots.epochNanoseconds,Number(divFloorBigInt(epochNano,bigNanoInMilli));var epochNano}function getEpochNano(slots){return slots.epochNanoseconds}function roundToMinute(offsetNano){return roundNumberToInc(offsetNano,nanoInMinute2,7)}function roundNumberToInc(num,roundingInc,roundingMode){return roundWithMode(num/roundingInc,roundingMode)*roundingInc}function roundWithMode(num,roundingMode){return roundingModeFuncs[roundingMode](num)}var zonedEpochSlotsToIso=memoize(_zonedEpochSlotsToIso,WeakMap);function _zonedEpochSlotsToIso(slots){let{epochNanoseconds,timeZone}=slots,offsetNanoseconds4=timeZone.B(epochNanoseconds);return{...epochNanoToIsoDateTime(epochNanoseconds+BigInt(offsetNanoseconds4)),offsetNanoseconds:offsetNanoseconds4}}function getMatchingInstantFor(timeZone,isoDateTime,offsetNano,offsetDisambig=0,epochDisambig=0,epochFuzzy,hasZ){if(offsetNano!==void 0&&offsetDisambig===1&&(offsetDisambig===1||hasZ))return isoDateTimeAndOffsetToEpochNano(isoDateTime,offsetNano);offsetDisambig!==2&&offsetDisambig!==0||checkIsoDateInBounds(isoDateTime,0);let possibleEpochNanos=timeZone.N(isoDateTime);if(offsetNano!==void 0&&offsetDisambig!==3){let matchingEpochNano=((possibleEpochNanos2,isoDateTime2,offsetNano2,fuzzy)=>{let zonedEpochNano=isoDateTimeToEpochNano(isoDateTime2);fuzzy&&(offsetNano2=roundToMinute(offsetNano2));for(let possibleEpochNano of possibleEpochNanos2){let possibleOffsetNano=Number(zonedEpochNano-possibleEpochNano);if(fuzzy&&(possibleOffsetNano=roundToMinute(possibleOffsetNano)),possibleOffsetNano===offsetNano2)return possibleEpochNano}})(possibleEpochNanos,isoDateTime,offsetNano,epochFuzzy);if(matchingEpochNano!==void 0)return matchingEpochNano;offsetDisambig===0&&throwRangeError("Invalid TimeZone offset")}return hasZ?isoDateTimeToEpochNano(isoDateTime):getSingleInstantFor(timeZone,isoDateTime,epochDisambig,possibleEpochNanos)}function getSingleInstantFor(timeZone,isoDateTime,disambig=0,possibleEpochNanos=timeZone.N(isoDateTime)){if(possibleEpochNanos.length===1)return possibleEpochNanos[0];if(disambig===1&&throwRangeError("Ambiguous offset"),possibleEpochNanos.length)return possibleEpochNanos[disambig===3?1:0];let zonedEpochNano=isoDateTimeToEpochNano(isoDateTime),gapNano=((timeZone2,zonedEpochNano2)=>{let startOffsetNano=timeZone2.B(zonedEpochNano2-bigNanoInUtcDay);return(gapNano2=>(gapNano2>nanoInUtcDay&&throwRangeError("Out-of-bounds TimeZone gap"),gapNano2))(timeZone2.B(zonedEpochNano2+bigNanoInUtcDay)-startOffsetNano)})(timeZone,zonedEpochNano),shiftedIsoDateTime=epochNanoToIsoDateTime(zonedEpochNano+BigInt(gapNano*(disambig===2?-1:1)));return(possibleEpochNanos=timeZone.N(shiftedIsoDateTime))[disambig===2?0:possibleEpochNanos.length-1]}var maxDurationSeconds=2**53;var offsetRegExp=createRegExp("([+-])(\\d{2})(?::?(\\d{2})(?::?(\\d{2})(?:[.,](\\d{1,9}))?)?)?");function parseOffsetNano(s){let offsetNano=parseOffsetNanoMaybe(s);return offsetNano===void 0&&throwRangeError(failedParse(s)),offsetNano}function parseOffsetNanoMaybe(s,onlyHourMinute){let parts=offsetRegExp.exec(s);if(parts&&(s2=>(s3=>{s3[0]!=="T"&&s3[0]!=="t"||(s3=s3.slice(1));let fractionIndex=s3.search(/[.,]/),main=fractionIndex<0?s3:s3.slice(0,fractionIndex),parts2=main.split(":");return parts2.length===1?/^(?:\d{2}|\d{4}|\d{6})$/i.test(main):(parts2.length===2||parts2.length===3)&&parts2.every(part=>part.length===2&&/^\d{2}$/i.test(part))})(s2.slice(1)))(parts[0]))return((parts2,onlyHourMinute2)=>{let firstSubMinutePart=parts2[4]||parts2[5];return onlyHourMinute2&&firstSubMinutePart&&throwRangeError(invalidSubstring(firstSubMinutePart)),offsetNano=(parseInt0(parts2[2])*nanoInHour2+parseInt0(parts2[3])*nanoInMinute2+parseInt0(parts2[4])*nanoInSec2+parseSubsecNano(parts2[5]||""))*parseSign(parts2[1]),Math.abs(offsetNano)>=nanoInUtcDay&&throwRangeError("Out-of-bounds offset"),offsetNano;var offsetNano})(parts,onlyHourMinute)}var dateFieldRefiners={era:toStringViaPrimitive,month:toPositiveIntegerWithTruncation,monthCode(monthCode,entityName){if(typeof monthCode=="string")return monthCode;if(monthCode&&typeof monthCode=="object"){let monthCodeToString=monthCode.toString;if(typeof monthCodeToString=="function")return requireString(monthCodeToString.call(monthCode),entityName)}return requireString(monthCode,entityName)},day:toPositiveIntegerWithTruncation},timeFieldRefiners=zipPropsConst(timeFieldNamesAsc,toIntegerWithTrunc);var dateTimeFieldRefiners=Object.assign({},dateFieldRefiners,timeFieldRefiners),zonedDateTimeFieldRefiners={offset(offsetString){return parseOffsetNano(toStringViaPrimitive(offsetString))},...dateTimeFieldRefiners};var RawDateTimeFormat=Intl.DateTimeFormat;function formatEpochMilliToPartsRecord(intlFormat,epochMilli){epochMilli<-864e13&&throwRangeError(outOfBoundsDate);let parts=intlFormat.formatToParts(epochMilli),hash={};for(let part of parts)hash[part.type]=part.value;return hash}var timeZonePeriodDaysByName={El_Aaiun:17,Tucuman:12,Tirane:11,Riga:10,Simferopol:9,Vienna:9,Tunis:8,Boa_Vista:6,Fortaleza:6,Maceio:6,Noronha:6,Recife:6,Gaza:6,Hebron:6,DeNoronha:6},minPossibleTransitionSec=-388152e4;function formatInstantIsoAuto(instantSlots){return formatIsoDateTimeFields(epochNanoToIsoDateTime(instantSlots.epochNanoseconds),void 0)+"Z"}function formatZonedDateTimeIsoAuto(zonedDateTimeSlots){let calendar=zonedDateTimeSlots.calendar,timeZone=zonedDateTimeSlots.timeZone,offsetNano=timeZone.B(zonedDateTimeSlots.epochNanoseconds);return formatIsoDateTimeFields(epochNanoToIsoDateTime(zonedDateTimeSlots.epochNanoseconds+BigInt(offsetNano)),void 0)+formatOffsetNano(roundToMinute(offsetNano))+formatTimeZone(timeZone.id,0)+(calendar===isoCalendarImpl?"":formatCalendarId(getCalendarSlotId(calendar),0))}function formatDateTimeIsoAuto(isoDateTimeSlots){let calendar=isoDateTimeSlots.calendar;return formatIsoDateTimeFields(isoDateTimeSlots,void 0)+(calendar===isoCalendarImpl?"":formatCalendarId(getCalendarSlotId(calendar),0))}function formatIsoDateTimeFields(isoDateTime,subsecDigits){return formatIsoDateFields(isoDateTime)+"T"+formatTimeFields(isoDateTime,subsecDigits)}function formatIsoDateFields(isoDateFields){return formatIsoYearMonthFields(isoDateFields)+"-"+padNumber2(isoDateFields.day)}function formatIsoYearMonthFields(isoDateFields){let{year}=isoDateFields;return(year<0||year>9999?getSignStr(year)+padNumber(6,Math.abs(year)):padNumber(4,year))+"-"+padNumber2(isoDateFields.month)}function formatTimeFields(timeFields,subsecDigits){let parts=[padNumber2(timeFields.hour),padNumber2(timeFields.minute)];return subsecDigits!==-1&&parts.push(padNumber2(timeFields.second)+((millisecond,microsecond,nanosecond,subsecDigits2)=>formatSubsecNano(millisecond*nanoInMilli2+microsecond*nanoInMicro2+nanosecond,subsecDigits2))(timeFields.millisecond,timeFields.microsecond,timeFields.nanosecond,subsecDigits)),parts.join(":")}function formatOffsetNano(offsetNano,offsetDisplay=0){if(offsetDisplay===1)return"";let[hour,nanoRemainder0]=divModFloor(Math.abs(offsetNano),nanoInHour2),[minute,nanoRemainder1]=divModFloor(nanoRemainder0,nanoInMinute2),[second,nanoRemainder2]=divModFloor(nanoRemainder1,nanoInSec2);return getSignStr(offsetNano)+padNumber2(hour)+":"+padNumber2(minute)+(second||nanoRemainder2?":"+padNumber2(second)+formatSubsecNano(nanoRemainder2):"")}function formatTimeZone(timeZoneId,timeZoneDisplay){return timeZoneDisplay!==1?"["+(timeZoneDisplay===2?"!":"")+timeZoneId+"]":""}function formatCalendarId(calendarId,isCritical){return"["+(isCritical?"!":"")+"u-ca="+calendarId+"]"}var trailingZerosRE=/0+$/;function formatSubsecNano(totalNano,subsecDigits){let s=padNumber(9,totalNano);return s=subsecDigits===void 0?s.replace(trailingZerosRE,""):s.slice(0,subsecDigits),s?"."+s:""}function getSignStr(num){return num<0?"-":"+"}var icuRegExp=/^(AC|AE|AG|AR|AS|BE|BS|CA|CN|CS|CT|EA|EC|IE|IS|JS|MI|NE|NS|PL|PN|PR|PS|SS|VS)T$/,badCharactersRegExp=/[^\w\/:+-]+/;function refineTimeZoneId(rawId){return resolveTimeZoneId(requireString(rawId))}function resolveTimeZoneId(rawId){return resolveTimeZoneRecord(rawId).id}function resolveTimeZoneRecord(rawId){let upperRawId=rawId.toUpperCase(),offsetRecord=(upperRawId2=>{let offsetNano=parseOffsetNanoMaybe(upperRawId2,1);if(offsetNano!==void 0)return{id:formatOffsetNano(offsetNano),X:offsetNano,m:offsetNano}})(upperRawId);if(offsetRecord)return{kind:"fixed",...offsetRecord};let normId=upperRawId==="UTC"?"UTC":(rawId2=>(badCharactersRegExp.test(rawId2)&&throwRangeError(invalidTimeZone(rawId2)),icuRegExp.test(rawId2)&&throwRangeError("Forbidden ICU TimeZone"),rawId2.toLowerCase().split("/").map((part,partI)=>(part.length<=3||/\d/.test(part))&&!/etc|yap/.test(part)?part.toUpperCase():part.replace(/baja|dumont|[a-z]+/g,(a,i)=>a.length<=2&&!partI||a==="in"||a==="chat"?a.toUpperCase():a.length>2||!i?capitalize(a).replace(/island|noronha|murdo|rivadavia|urville/,capitalize):a)).join("/")))(rawId);return queryNamedTimeZoneRecord(normId)}var queryNamedTimeZoneRecord=memoize(normId=>{if(normId==="UTC")return{kind:"utc",id:normId,m:normId};let upperNormId=normId.toUpperCase(),format=queryTimeZoneIntlFormat(upperNormId);return{kind:"named",id:normId,format,m:format.resolvedOptions().timeZone}}),queryTimeZoneIntlFormat=memoize(upperNormId=>new RawDateTimeFormat("en-u-hc-h23",{calendar:"iso8601",timeZone:upperNormId,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}));function queryTimeZone(rawTimeZoneId){let record=resolveTimeZoneRecord(rawTimeZoneId);return queryTimeZoneRecord(record.id,record)}var queryTimeZoneRecord=memoize((normTimeZoneId,record)=>record.kind==="named"?new IntlTimeZone(normTimeZoneId,record.m,record.format):new FixedTimeZone(normTimeZoneId,record.m,record.kind==="fixed"?record.X:0)),FixedTimeZone=class{constructor(id,compareKey,offsetNano){this.id=id,this.m=compareKey,this.X=offsetNano}B(){return this.X}N(isoDateTime){return[isoDateTimeAndOffsetToEpochNano(isoDateTime,this.X)]}O(){}},IntlTimeZone=class{constructor(id,compareKey,format){this.id=id,this.m=compareKey,this.ke=((computeOffsetSec,periodDays)=>{let getSample=memoize(computeOffsetSec),getSplit=memoize(createSplitTuple),periodSec=86400*periodDays;function getOffsetSec(epochSec){let[startEpochSec,endEpochSec]=computePeriod(epochSec,periodSec),clampedStartEpochSec=clampIntlSampleEpochSec(startEpochSec),clampedEndEpochSec=clampIntlSampleEpochSec(endEpochSec),startOffsetSec=getSample(clampedStartEpochSec),endOffsetSec=getSample(clampedEndEpochSec);return startOffsetSec===endOffsetSec?startOffsetSec:pinch(getSplit(clampedStartEpochSec,clampedEndEpochSec),startOffsetSec,endOffsetSec,epochSec)}function pinch(split,startOffsetSec,endOffsetSec,forEpochSec){let offsetSec,splitDurSec;for(;(forEpochSec===void 0||(offsetSec=forEpochSec<split[0]?startOffsetSec:forEpochSec>=split[1]?endOffsetSec:void 0)===void 0)&&(splitDurSec=split[1]-split[0]);){let middleEpochSec=split[0]+Math.floor(splitDurSec/2);computeOffsetSec(middleEpochSec)===endOffsetSec?split[1]=middleEpochSec:split[0]=middleEpochSec+1}return offsetSec}return{xe(zonedEpochSec){let wideOffsetSec0=getOffsetSec(zonedEpochSec-86400),wideOffsetSec1=getOffsetSec(zonedEpochSec+86400),wideUtcEpochSec0=zonedEpochSec-wideOffsetSec0,wideUtcEpochSec1=zonedEpochSec-wideOffsetSec1;if(wideOffsetSec0===wideOffsetSec1)return[wideUtcEpochSec0];let narrowOffsetSec0=getOffsetSec(wideUtcEpochSec0);return narrowOffsetSec0===getOffsetSec(wideUtcEpochSec1)?[zonedEpochSec-narrowOffsetSec0]:wideOffsetSec0>wideOffsetSec1?[wideUtcEpochSec0,wideUtcEpochSec1]:[]},we:getOffsetSec,O:function getTransition(epochSec,direction){if(direction>0&&epochSec>=864e10)return;if(direction<0){if(epochSec<=minPossibleTransitionSec)return;let lookaheadEpochSec=getCurrentEpochSec()+94867200;if(epochSec>lookaheadEpochSec)return getTransition(lookaheadEpochSec,-1)}let searchEpochSec=direction>0?Math.max(epochSec,minPossibleTransitionSec):epochSec,[startEpochSec,endEpochSec]=computePeriod(searchEpochSec,periodSec),inc=periodSec*direction,searchLimit=direction>0?Math.max(epochSec,getCurrentEpochSec())+94867200:minPossibleTransitionSec,inBounds=()=>direction<0?endEpochSec>searchLimit:startEpochSec<searchLimit;for(;inBounds();){let clampedStartEpochSec=clampIntlSampleEpochSec(startEpochSec),clampedEndEpochSec=clampIntlSampleEpochSec(endEpochSec),startOffsetSec=getSample(clampedStartEpochSec),endOffsetSec=getSample(clampedEndEpochSec);if(startOffsetSec!==endOffsetSec){let split=getSplit(clampedStartEpochSec,clampedEndEpochSec);pinch(split,startOffsetSec,endOffsetSec);let transitionEpochSec=split[0];if((compareNumbers(transitionEpochSec,epochSec)||1)===direction)return transitionEpochSec}startEpochSec+=inc,endEpochSec+=inc}}}})((format2=>epochSec=>{let intlParts=formatEpochMilliToPartsRecord(format2,1e3*epochSec);return 86400*isoArgsToEpochDays((intlParts2=>{let relatedYear=intlParts2.relatedYear;if(relatedYear!==void 0)return parseInt(relatedYear);let year=parseInt(intlParts2.year);return intlParts2.era!==void 0&&normalizeEraName(intlParts2.era)==="bce"?1-year:year})(intlParts),parseInt(intlParts.month),parseInt(intlParts.day))+3600*parseInt(intlParts.hour)+60*parseInt(intlParts.minute)+parseInt(intlParts.second)-epochSec})(format),(timeZoneId=>{let timeZoneName=timeZoneId.split("/").pop();return timeZonePeriodDaysByName[timeZoneName]||60})(id))}B(epochNano){return this.ke.we((epochNano2=>epochNanoToSecMod(epochNano2)[0])(epochNano))*nanoInSec2}N(isoDateTime){let zonedEpochSec=86400*isoDateToEpochDays(isoDateTime)+timeFieldsToSec(isoDateTime),subsecNano=timeFieldsToSubsecNano(isoDateTime);return this.ke.xe(zonedEpochSec).map(epochSec=>checkEpochNanoInBounds(BigInt(epochSec)*bigNanoInSec+BigInt(subsecNano)))}O(epochNano,direction){let[epochSec,subsecNano]=epochNanoToSecMod(epochNano),resEpochSec=this.ke.O(epochSec+(direction>0||subsecNano?1:0),direction);if(resEpochSec!==void 0)return BigInt(resEpochSec)*bigNanoInSec}};function getCurrentEpochSec(){return Math.floor(Date.now()/1e3)}function createSplitTuple(startEpochSec,endEpochSec){return[startEpochSec,endEpochSec]}function computePeriod(epochSec,periodSec){let startEpochSec=Math.floor(epochSec/periodSec)*periodSec;return[startEpochSec,startEpochSec+periodSec]}function clampIntlSampleEpochSec(epochSec){return constrainToRange2(epochSec,-1e10,864e10)}function timeRegExpStr(separatorIndex){return`(\\d{2})(?:(:?)(\\d{2})(?:\\${separatorIndex}(\\d{2})(?:[.,](\\d{1,9}))?)?)?`}var dateTimeRegExpStr="(?:(?:([+-])(\\d{6}))|(\\d{4}))(-?)(\\d{2})\\4(\\d{2})(?:[T ]"+timeRegExpStr(8)+"(Z|([+-])"+timeRegExpStr(15)+")?)?";var dateTimeRegExp=createRegExp(dateTimeRegExpStr+"((?:\\[(!?)([^\\]]*)\\]){0,9})"),timeRegExp=createRegExp("T?"+timeRegExpStr(2)+`(([+-])${timeRegExpStr(9)})?((?:\\[(!?)([^\\]]*)\\]){0,9})`);function instantToZonedDateTime(instantSlots,timeZone,calendar){return createZonedEpochNanoSlots(instantSlots.epochNanoseconds,timeZone,calendar)}function plainDateTimeToZonedDateTime(plainDateTimeSlots,timeZone,options){let epochNano=getSingleInstantFor(timeZone,plainDateTimeSlots,(options2=>coerceEpochDisambig(normalizeOptions(options2)))(options));return createZonedEpochNanoSlots(checkEpochNanoInBounds(epochNano),timeZone,plainDateTimeSlots.calendar)}function epochMilliToInstant(epochMilli){return createEpochNanoSlots(checkEpochNanoInBounds(BigInt(toStrictInteger(epochMilli))*bigNanoInMilli))}function createOptionsTransformer(shapeFieldNames,invalidShapeFieldNames,ignoredFieldNames,defaultShapeFields,dateStyleReplacementFields){let shapeFieldNameSet=new Set(shapeFieldNames),invalidShapeFieldNameSet=new Set(invalidShapeFieldNames),ignoredFieldNameSet=new Set(ignoredFieldNames);return(options,allowPartialOverlap)=>{let dateStyle,timeStyle,granularShapeFields={},modifierFields={},otherFields={},hasInvalidGranularShapeFields=0,hasInvalidStyleFields=0;for(let name of Object.keys(options)){let value=options[name];value===void 0||ignoredFieldNameSet.has(name)||(shapeFieldNameSet.has(name)?name==="dateStyle"?dateStyle=value:name==="timeStyle"?timeStyle=value:granularShapeFields[name]=value:name==="era"?modifierFields[name]=value:invalidShapeFieldNameSet.has(name)?name==="dateStyle"||name==="timeStyle"?hasInvalidStyleFields=1:hasInvalidGranularShapeFields=1:otherFields[name]=value)}let hasDateStyle=dateStyle!==void 0,hasTimeStyle=timeStyle!==void 0,hasAnyStyle=hasDateStyle||hasTimeStyle,hasGranularShapeFields=Object.keys(granularShapeFields).length>0,hasInvalids=hasInvalidGranularShapeFields||hasInvalidStyleFields,hasShapeFields=hasGranularShapeFields||hasDateStyle||hasTimeStyle,hasModifierFields=Object.keys(modifierFields).length>0;(!allowPartialOverlap&&hasInvalids||allowPartialOverlap&&hasInvalids&&!hasShapeFields||hasAnyStyle&&(hasGranularShapeFields||hasModifierFields||hasInvalidGranularShapeFields))&&throwTypeError("Invalid formatting options");let transformedOptions={};return hasAnyStyle||hasShapeFields||Object.assign(transformedOptions,defaultShapeFields),Object.assign(transformedOptions,granularShapeFields,modifierFields,otherFields),hasDateStyle&&(dateStyleReplacementFields?Object.assign(transformedOptions,dateStyleReplacementFields[dateStyle]):transformedOptions.dateStyle=dateStyle),hasTimeStyle&&(transformedOptions.timeStyle=timeStyle),transformedOptions}}var dateDefaultShapeFields={year:"numeric",month:"numeric",day:"numeric"},timeDefaultShapeFields={hour:"numeric",minute:"numeric",second:"numeric"},dateTimeDefaultShapeFields=Object.assign({},dateDefaultShapeFields,timeDefaultShapeFields),dateShapeFieldNames=["weekday","year","month","day","dateStyle"],timeShapeFieldNames=["dayPeriod","hour","minute","second","fractionalSecondDigits","timeStyle"],dateTimeShapeFieldNames=dateShapeFieldNames.concat(timeShapeFieldNames);var transformZonedOptions=createOptionsTransformer(dateTimeShapeFieldNames,[],[],{...dateTimeDefaultShapeFields,timeZoneName:"short"});var PlainYearMonthBranding="PlainYearMonth",PlainMonthDayBranding="PlainMonthDay",PlainDateBranding="PlainDate",PlainDateTimeBranding="PlainDateTime",PlainTimeBranding="PlainTime",ZonedDateTimeBranding="ZonedDateTime",InstantBranding="Instant",DurationBranding="Duration",CalendarBranding="Calendar";function defineTemporalClass(branding,cls,getSlots,...getterMaps){return Object.defineProperties(cls,createNameDescriptors(branding)),Object.defineProperties(cls.prototype,createStringTagDescriptors("Temporal."+branding)),Object.defineProperties(cls.prototype,mapProps(getter=>({get(){return getter(getSlots(this))},configurable:1}),Object.assign({},...getterMaps))),cls}var attachDebugString=noop.name==="noop"?instance=>{Object.defineProperty(instance,"_str_",{value:instance.toJSON()})}:noop;function invalidRecordType(){throwTypeError(invalidCallingContext)}function forbiddenValueOf2(){throwTypeError(forbiddenValueOf)}var dateFieldGetters$1={era(slots){return computeCalendarEraFields(slots.calendar,slots).era},eraYear(slots){return computeCalendarEraFields(slots.calendar,slots).eraYear},year(slots){return computeCalendarDateFields(slots.calendar,slots).year},month(slots){return computeCalendarDateFields(slots.calendar,slots).month},monthCode(slots){return computeCalendarMonthCode(slots.calendar,slots)},day(slots){return computeCalendarDateFields(slots.calendar,slots).day}};var yearMonthDerivedGetters={daysInMonth(slots){return computeCalendarDaysInMonth(slots.calendar,slots)},daysInYear(slots){return computeCalendarDaysInYear(slots.calendar,slots)},monthsInYear(slots){return computeCalendarMonthsInYear(slots.calendar,slots)},inLeapYear(slots){return computeCalendarInLeapYear(slots.calendar,slots)}},dateDerivedGetters={dayOfWeek(slots){return computeIsoDayOfWeek(slots)},dayOfYear(slots){return computeCalendarDayOfYear(slots.calendar,slots)},weekOfYear(slots){return computeCalendarWeekOfYear(slots.calendar,slots)},yearOfWeek(slots){return computeCalendarYearOfWeek(slots.calendar,slots)},daysInWeek(){return 7},daysInMonth(slots){return computeCalendarDaysInMonth(slots.calendar,slots)},daysInYear(slots){return computeCalendarDaysInYear(slots.calendar,slots)},monthsInYear(slots){return computeCalendarMonthsInYear(slots.calendar,slots)},inLeapYear(slots){return computeCalendarInLeapYear(slots.calendar,slots)}};function createNativeGetters(shimGetters){return createPropGetters(Object.keys(shimGetters))}var timeGetters2=createNativeGetters(timeGetters);var dateFieldGetters=createNativeGetters(dateFieldGetters$1);createNativeGetters(yearMonthDerivedGetters),createNativeGetters(dateDerivedGetters);var PlainYearMonthRecordBranding=`${PlainYearMonthBranding}Record`,PlainMonthDayRecordBranding=`${PlainMonthDayBranding}Record`,PlainDateRecordBranding=`${PlainDateBranding}Record`,PlainDateTimeRecordBranding=`${PlainDateTimeBranding}Record`,PlainTimeRecordBranding=`${PlainTimeBranding}Record`,ZonedDateTimeRecordBranding=`${ZonedDateTimeBranding}Record`,InstantRecordBranding=`${InstantBranding}Record`,DurationRecordBranding=`${DurationBranding}Record`,CalendarRecordBranding=`${CalendarBranding}Record`,calendarMap=new WeakMap,instantMap=new WeakMap,zonedDateTimeMap=new WeakMap,plainDateTimeMap=new WeakMap;function getCalendarSlots(record){return getCalendarSlotsIfPresent(record)||invalidRecordType()}function getCalendarSlotsIfPresent(record){return calendarMap.get(record)}function getInstantSlots(record){return getInstantSlotsIfPresent(record)||invalidRecordType()}function getInstantSlotsIfPresent(record){return instantMap.get(record)}function setInstantSlots(instance,slots){instantMap.set(instance,slots)}function getZonedDateTimeSlots(record){return getZonedDateTimeSlotsIfPresent(record)||invalidRecordType()}function getZonedDateTimeSlotsIfPresent(record){return zonedDateTimeMap.get(record)}function setZonedDateTimeSlots(instance,slots){zonedDateTimeMap.set(instance,slots)}function getPlainDateTimeSlots(record){return getPlainDateTimeSlotsIfPresent(record)||invalidRecordType()}function getPlainDateTimeSlotsIfPresent(record){return plainDateTimeMap.get(record)}function setPlainDateTimeSlots(instance,slots){plainDateTimeMap.set(instance,slots)}function getCalendarRecordId(record){return getCalendarSlots(record).id}function getCalendarRecordImplCreator(record){let getImpl=getCalendarSlots(record).ue;return getImpl||throwRangeError(exoticCalendarRequired(getCalendarRecordId(record),"getExotic or getAny")),getImpl}function refineNativeCalendarArgMaybe(calendarRecord){if(calendarRecord!==void 0)return getValidatedCalendarId(calendarRecord)}function getValidatedCalendarId(record){return getCalendarRecordImplCreator(record),getCalendarRecordId(record)}var getNativePlainDateTime=getPlainDateTimeSlots,NativePlainDateTimeRecord=defineTemporalClass(PlainDateTimeRecordBranding,class{get calendarId(){return getNativePlainDateTime(this).calendarId}toJSON(){return getNativePlainDateTime(this).toJSON()}valueOf(){return getNativePlainDateTime(this).valueOf()}},getNativePlainDateTime,dateFieldGetters,timeGetters2);function createNativePlainDateTimeRecord(native){let instance=Object.create(NativePlainDateTimeRecord.prototype);return setPlainDateTimeSlots(instance,native),attachDebugString(instance),instance}function create$5(isoYear,isoMonth,isoDay,hour,minute,second,millisecond,microsecond,nanosecond,calendar){return createNativePlainDateTimeRecord(new NativeTemporal.PlainDateTime(isoYear,isoMonth,isoDay,hour,minute,second,millisecond,microsecond,nanosecond,refineNativeCalendarArgMaybe(calendar)))}function toZonedDateTime$1(record,timeZoneId,options){return createNativeZonedDateTimeRecord(getNativePlainDateTime(record).toZonedDateTime(timeZoneId,options))}var getNativeZonedDateTime=getZonedDateTimeSlots,NativeZonedDateTimeRecord=defineTemporalClass(ZonedDateTimeRecordBranding,class{get calendarId(){return getNativeZonedDateTime(this).calendarId}get timeZoneId(){return getNativeZonedDateTime(this).timeZoneId}get epochMilliseconds(){return getNativeZonedDateTime(this).epochMilliseconds}get epochNanoseconds(){return getNativeZonedDateTime(this).epochNanoseconds}toJSON(){return getNativeZonedDateTime(this).toJSON()}valueOf(){return getNativeZonedDateTime(this).valueOf()}},getNativeZonedDateTime,dateFieldGetters,timeGetters2);function createNativeZonedDateTimeRecord(native){let instance=Object.create(NativeZonedDateTimeRecord.prototype);return setZonedDateTimeSlots(instance,native),attachDebugString(instance),instance}function offsetNanoseconds(record){return getNativeZonedDateTime(record).offsetNanoseconds}var getNativeInstant=getInstantSlots,NativeInstantRecord=defineTemporalClass(InstantRecordBranding,class{get epochMilliseconds(){return getNativeInstant(this).epochMilliseconds}get epochNanoseconds(){return getNativeInstant(this).epochNanoseconds}toJSON(){return getNativeInstant(this).toJSON()}valueOf(){return getNativeInstant(this).valueOf()}});function createNativeInstantRecord(native){let instance=Object.create(NativeInstantRecord.prototype);return setInstantSlots(instance,native),attachDebugString(instance),instance}function fromEpochMilliseconds(epochMilliseconds){return createNativeInstantRecord(NativeTemporal.Instant.fromEpochMilliseconds(epochMilliseconds))}function toZonedDateTimeISO(record,timeZoneId){return createNativeZonedDateTimeRecord(getNativeInstant(record).toZonedDateTimeISO(timeZoneId))}function refineShimCalendarArgMaybe(calendarRecord){return calendarRecord===void 0?isoCalendarImpl:getCalendarRecordImpl(calendarRecord)}function getCalendarRecordImpl(record){return getCalendarRecordImplCreator(record)()}var getShimPlainDateTimeSlots=getPlainDateTimeSlots,ShimPlainDateTimeRecord=defineTemporalClass(PlainDateTimeRecordBranding,class{get calendarId(){return getCalendarSlotId(getShimPlainDateTimeSlots(this).calendar)}toJSON(){return formatDateTimeIsoAuto(getShimPlainDateTimeSlots(this))}valueOf(){return forbiddenValueOf2()}},getShimPlainDateTimeSlots,dateFieldGetters$1,timeGetters);function createShimPlainDateTimeRecord(slots){let instance=Object.create(ShimPlainDateTimeRecord.prototype);return setPlainDateTimeSlots(instance,slots),attachDebugString(instance),instance}function create$52(isoYear,isoMonth,isoDay,hour=0,minute=0,second=0,millisecond=0,microsecond=0,nanosecond=0,calendar){let fields=checkIsoDateTimeInBounds(validateIsoDateTimeFields(mapProps(toIntegerWithTrunc,{year:isoYear,month:isoMonth,day:isoDay,hour,minute,second,millisecond,microsecond,nanosecond}))),calendarImpl=refineShimCalendarArgMaybe(calendar);return createShimPlainDateTimeRecord(createDateTimeSlots(fields,calendarImpl))}function toZonedDateTime$12(record,timeZoneId,options){return createShimZonedDateTimeRecord(plainDateTimeToZonedDateTime(getShimPlainDateTimeSlots(record),queryTimeZone(refineTimeZoneId(timeZoneId)),options))}var getShimZonedDateTimeSlots=getZonedDateTimeSlots,ShimZonedDateTimeRecord=defineTemporalClass(ZonedDateTimeRecordBranding,class{get calendarId(){return getCalendarSlotId(getShimZonedDateTimeSlots(this).calendar)}get timeZoneId(){return getShimZonedDateTimeSlots(this).timeZone.id}get epochMilliseconds(){return getEpochMilli(getShimZonedDateTimeSlots(this))}get epochNanoseconds(){return getEpochNano(getShimZonedDateTimeSlots(this))}toJSON(){return formatZonedDateTimeIsoAuto(getShimZonedDateTimeSlots(this))}valueOf(){return forbiddenValueOf2()}},getShimZonedDateTimeIsoSlots,dateFieldGetters$1,timeGetters);function createShimZonedDateTimeRecord(slots){let instance=Object.create(ShimZonedDateTimeRecord.prototype);return setZonedDateTimeSlots(instance,slots),attachDebugString(instance),instance}function getShimZonedDateTimeIsoSlots(record){let slots=getShimZonedDateTimeSlots(record);return{...zonedEpochSlotsToIso(slots),calendar:slots.calendar}}function offsetNanoseconds2(record){return zonedEpochSlotsToIso(getShimZonedDateTimeSlots(record)).offsetNanoseconds}var endOfHour2=alignedZonedTime(slots=>({hour:slots.hour,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0}),nanoInHour2-1),endOfMinute2=alignedZonedTime(slots=>({hour:slots.hour,minute:slots.minute,second:0,millisecond:0,microsecond:0,nanosecond:0}),nanoInMinute2-1),endOfSecond2=alignedZonedTime(slots=>({hour:slots.hour,minute:slots.minute,second:slots.second,millisecond:0,microsecond:0,nanosecond:0}),nanoInSec2-1),endOfMillisecond2=alignedZonedTime(slots=>({hour:slots.hour,minute:slots.minute,second:slots.second,millisecond:slots.millisecond,microsecond:0,nanosecond:0}),nanoInMilli2-1),endOfMicrosecond2=alignedZonedTime(slots=>({hour:slots.hour,minute:slots.minute,second:slots.second,millisecond:slots.millisecond,microsecond:slots.microsecond,nanosecond:0}),nanoInMicro2-1);function alignedZonedTime(computeAlignment,nanoDelta=0){return record=>{let slots=getShimZonedDateTimeSlots(record),{timeZone}=slots,isoDateTime=zonedEpochSlotsToIso(slots),alignedIsoDateTime=combineDateAndTime(isoDateTime,computeAlignment(isoDateTime)),epochNanoseconds=getMatchingInstantFor(timeZone,alignedIsoDateTime,isoDateTime.offsetNanoseconds,2,0,1)+BigInt(nanoDelta);return createShimZonedDateTimeRecord({...slots,epochNanoseconds:checkEpochNanoInBounds(epochNanoseconds)})}}var getShimInstantSlots=getInstantSlots,ShimInstantRecord=defineTemporalClass(InstantRecordBranding,class{get epochMilliseconds(){return getEpochMilli(getShimInstantSlots(this))}get epochNanoseconds(){return getEpochNano(getShimInstantSlots(this))}toJSON(){return formatInstantIsoAuto(getShimInstantSlots(this))}valueOf(){return forbiddenValueOf2()}});function createShimInstantRecord(slots){let instance=Object.create(ShimInstantRecord.prototype);return setInstantSlots(instance,slots),attachDebugString(instance),instance}function fromEpochMilliseconds2(epochMilliseconds){return createShimInstantRecord(epochMilliToInstant(epochMilliseconds))}function toZonedDateTimeISO2(record,timeZoneId){return createShimZonedDateTimeRecord(instantToZonedDateTime(getShimInstantSlots(record),queryTimeZone(refineTimeZoneId(timeZoneId))))}var offsetNanoseconds3=NativeTemporal?offsetNanoseconds:offsetNanoseconds2;var create=NativeTemporal?create$5:create$52;var toZonedDateTime=NativeTemporal?toZonedDateTime$1:toZonedDateTime$12;var fromEpochMilliseconds3=NativeTemporal?fromEpochMilliseconds:fromEpochMilliseconds2;var toZonedDateTimeISO3=NativeTemporal?toZonedDateTimeISO:toZonedDateTimeISO2;function addWeeks3(m,n){let a=dateToUtcArray(m);return a[2]+=n*7,arrayToUtcDate(a)}function addDays4(m,n){let a=dateToUtcArray(m);return a[2]+=n,arrayToUtcDate(a)}function addMs(m,n){let a=dateToUtcArray(m);return a[6]+=n,arrayToUtcDate(a)}function diffWeeks4(m0,m1){return diffDays4(m0,m1)/7}function diffDays4(m0,m1){return(m1.valueOf()-m0.valueOf())/(1e3*60*60*24)}function diffHours4(m0,m1){return(m1.valueOf()-m0.valueOf())/(1e3*60*60)}function diffMinutes4(m0,m1){return(m1.valueOf()-m0.valueOf())/(1e3*60)}function diffSeconds4(m0,m1){return(m1.valueOf()-m0.valueOf())/1e3}function diffDayAndTime(m0,m1){let m0day=startOfDay5(m0),m1day=startOfDay5(m1);return{years:0,months:0,days:Math.round(diffDays4(m0day,m1day)),milliseconds:m1.valueOf()-m1day.valueOf()-(m0.valueOf()-m0day.valueOf())}}function diffWholeWeeks(m0,m1){let d=diffWholeDays(m0,m1);return d!==null&&d%7===0?d/7:null}function diffWholeDays(m0,m1){return timeAsMs(m0)===timeAsMs(m1)?Math.round(diffDays4(m0,m1)):null}function startOfDay5(m){return arrayToUtcDate([m.getUTCFullYear(),m.getUTCMonth(),m.getUTCDate()])}function startOfHour4(m){return arrayToUtcDate([m.getUTCFullYear(),m.getUTCMonth(),m.getUTCDate(),m.getUTCHours()])}function startOfMinute4(m){return arrayToUtcDate([m.getUTCFullYear(),m.getUTCMonth(),m.getUTCDate(),m.getUTCHours(),m.getUTCMinutes()])}function startOfSecond4(m){return arrayToUtcDate([m.getUTCFullYear(),m.getUTCMonth(),m.getUTCDate(),m.getUTCHours(),m.getUTCMinutes(),m.getUTCSeconds()])}function weekOfYear3(marker,dow,doy){let y=marker.getUTCFullYear(),w=weekOfGivenYear(marker,y,dow,doy);if(w<1)return weekOfGivenYear(marker,y-1,dow,doy);let nextW=weekOfGivenYear(marker,y+1,dow,doy);return nextW>=1?Math.min(w,nextW):w}function weekOfGivenYear(marker,year,dow,doy){let firstWeekStart=arrayToUtcDate([year,0,1+firstWeekOffset(year,dow,doy)]),dayStart=startOfDay5(marker),days=Math.round(diffDays4(firstWeekStart,dayStart));return Math.floor(days/7)+1}function firstWeekOffset(year,dow,doy){let fwd=7+dow-doy;return-((7+arrayToUtcDate([year,0,fwd]).getUTCDay()-dow)%7)+fwd-1}function dateToLocalArray(date){return[date.getFullYear(),date.getMonth(),date.getDate(),date.getHours(),date.getMinutes(),date.getSeconds(),date.getMilliseconds()]}function arrayToLocalDate(a){return new Date(a[0],a[1]||0,a[2]==null?1:a[2],a[3]||0,a[4]||0,a[5]||0)}function dateToUtcArray(date){return[date.getUTCFullYear(),date.getUTCMonth(),date.getUTCDate(),date.getUTCHours(),date.getUTCMinutes(),date.getUTCSeconds(),date.getUTCMilliseconds()]}function arrayToUtcDate(a){return a.length===1&&(a=a.concat([0])),new Date(Date.UTC(...a))}function isValidDate(m){return!isNaN(m.valueOf())}function timeAsMs(m){return m.getUTCHours()*1e3*60*60+m.getUTCMinutes()*1e3*60+m.getUTCSeconds()*1e3+m.getUTCMilliseconds()}var calendarSystemClassMap={};function registerCalendarSystem(name,theClass){calendarSystemClassMap[name]=theClass}function createCalendarSystem(name){return new calendarSystemClassMap[name]}var GregorianCalendarSystem=class{getMarkerYear(d){return d.getUTCFullYear()}getMarkerMonth(d){return d.getUTCMonth()}getMarkerDay(d){return d.getUTCDate()}arrayToMarker(arr){return arrayToUtcDate(arr)}markerToArray(marker){return dateToUtcArray(marker)}};registerCalendarSystem("gregory",GregorianCalendarSystem);function parseRange(input,dateEnv){let start=null,end=null;return input.start&&(start=dateEnv.createMarker(input.start)),input.end&&(end=dateEnv.createMarker(input.end)),!start&&!end||start&&end&&end<start?null:{start,end}}function invertRanges(ranges,constraintRange){let invertedRanges=[],{start}=constraintRange,i,dateRange;for(ranges.sort(compareRanges),i=0;i<ranges.length;i+=1)dateRange=ranges[i],dateRange.start>start&&invertedRanges.push({start,end:dateRange.start}),dateRange.end>start&&(start=dateRange.end);return start<constraintRange.end&&invertedRanges.push({start,end:constraintRange.end}),invertedRanges}function compareRanges(range0,range1){return range0.start.valueOf()-range1.start.valueOf()}function intersectRanges(range0,range1){let{start,end}=range0,newRange=null;return range1.start!==null&&(start===null?start=range1.start:start=new Date(Math.max(start.valueOf(),range1.start.valueOf()))),range1.end!=null&&(end===null?end=range1.end:end=new Date(Math.min(end.valueOf(),range1.end.valueOf()))),(start===null||end===null||start<end)&&(newRange={start,end}),newRange}function rangesEqual(range0,range1){return(range0.start===null?null:range0.start.valueOf())===(range1.start===null?null:range1.start.valueOf())&&(range0.end===null?null:range0.end.valueOf())===(range1.end===null?null:range1.end.valueOf())}function rangesIntersect(range0,range1){return(range0.end===null||range1.start===null||range0.end>range1.start)&&(range0.start===null||range1.end===null||range0.start<range1.end)}function rangeContainsRange(outerRange,innerRange){return(outerRange.start===null||innerRange.start!==null&&innerRange.start>=outerRange.start)&&(outerRange.end===null||innerRange.end!==null&&innerRange.end<=outerRange.end)}function rangeContainsMarker(range,date){return(range.start===null||date>=range.start)&&(range.end===null||date<range.end)}function constrainMarkerToRange(date,range){return range.start!=null&&date<range.start?range.start:range.end!=null&&date>=range.end?new Date(range.end.valueOf()-1):date}function expandZonedInstant(dateInfo,calendarSystem){let a=calendarSystem.markerToArray(dateInfo.marker);return{marker:dateInfo.marker,instantMs:dateInfo.instantMs,timeZoneOffset:(dateInfo.marker.valueOf()-dateInfo.instantMs)/6e4,array:a,year:a[0],month:a[1],day:a[2],hour:a[3],minute:a[4],second:a[5],millisecond:a[6]}}function createVerboseFormattingArg(start,end,context){let startInfo=expandZonedInstant(start,context.calendarSystem),endInfo=end?expandZonedInstant(end,context.calendarSystem):null;return{date:startInfo,start:startInfo,end:endInfo,timeZone:context.timeZone,localeCodes:context.locale.codes}}function isInt(n){return n%1===0}function padStart(val,len){let s=String(val);return"000".substr(0,len-s.length)+s}var INTERNAL_UNITS=["years","months","days","milliseconds"],PARSE_RE=/^(-?)(?:(\d+)\.)?(\d+):(\d\d)(?::(\d\d)(?:\.(\d\d\d))?)?/;function createDuration(input,unit){return typeof input=="string"?parseString(input):typeof input=="object"&&input?parseObject(input):typeof input=="number"?parseObject({[unit||"milliseconds"]:input}):null}function parseString(s){let m=PARSE_RE.exec(s);if(m){let sign=m[1]?-1:1;return{years:0,months:0,days:sign*(m[2]?parseInt(m[2],10):0),milliseconds:sign*((m[3]?parseInt(m[3],10):0)*60*60*1e3+(m[4]?parseInt(m[4],10):0)*60*1e3+(m[5]?parseInt(m[5],10):0)*1e3+(m[6]?parseInt(m[6],10):0))}}return null}function parseObject(obj){let duration={years:obj.years||obj.year||0,months:obj.months||obj.month||0,days:obj.days||obj.day||0,milliseconds:(obj.hours||obj.hour||0)*60*60*1e3+(obj.minutes||obj.minute||0)*60*1e3+(obj.seconds||obj.second||0)*1e3+(obj.milliseconds||obj.millisecond||obj.ms||0)},weeks=obj.weeks||obj.week;return weeks&&(duration.days+=weeks*7,duration.specifiedWeeks=!0),duration}function durationsEqual(d0,d1){return d0.years===d1.years&&d0.months===d1.months&&d0.days===d1.days&&d0.milliseconds===d1.milliseconds}function addDurations(d0,d1){return{years:d0.years+d1.years,months:d0.months+d1.months,days:d0.days+d1.days,milliseconds:d0.milliseconds+d1.milliseconds}}function subtractDurations(d1,d0){return{years:d1.years-d0.years,months:d1.months-d0.months,days:d1.days-d0.days,milliseconds:d1.milliseconds-d0.milliseconds}}function multiplyDuration(d,n){return{years:d.years*n,months:d.months*n,days:d.days*n,milliseconds:d.milliseconds*n}}function asRoughYears(dur){return asRoughDays(dur)/365}function asRoughMonths(dur){return asRoughDays(dur)/30}function asRoughDays(dur){return asRoughMs(dur)/864e5}function asRoughMs(dur){return dur.years*(365*864e5)+dur.months*(30*864e5)+dur.days*864e5+dur.milliseconds}function wholeDivideDurations(numerator,denominator){let res=null;for(let i=0;i<INTERNAL_UNITS.length;i+=1){let unit=INTERNAL_UNITS[i];if(denominator[unit]){let localRes=numerator[unit]/denominator[unit];if(!isInt(localRes)||res!==null&&res!==localRes)return null;res=localRes}else if(numerator[unit])return null}return res}function greatestDurationDenominator(dur){let ms=dur.milliseconds;if(ms){if(ms%1e3!==0)return{unit:"millisecond",value:ms};if(ms%(1e3*60)!==0)return{unit:"second",value:ms/1e3};if(ms%(1e3*60*60)!==0)return{unit:"minute",value:ms/(1e3*60)};if(ms)return{unit:"hour",value:ms/(1e3*60*60)}}return dur.days?dur.specifiedWeeks&&dur.days%7===0?{unit:"week",value:dur.days/7}:{unit:"day",value:dur.days}:dur.months?{unit:"month",value:dur.months}:dur.years?{unit:"year",value:dur.years}:{unit:"millisecond",value:0}}function buildIsoString(marker,timeZoneOffset,stripZeroTime=!1){let s=marker.toISOString();return s=s.replace(".000",""),stripZeroTime&&(s=s.replace("T00:00:00Z","")),s.length>10&&(timeZoneOffset==null?s=s.replace("Z",""):timeZoneOffset!==0&&(s=s.replace("Z",formatTimeZoneOffset(timeZoneOffset,!0)))),s}function formatDayString(marker){return marker.toISOString().replace(/T.*$/,"")}function formatIsoTimeString(marker){return padStart(marker.getUTCHours(),2)+":"+padStart(marker.getUTCMinutes(),2)+":"+padStart(marker.getUTCSeconds(),2)}function formatTimeZoneOffset(minutes,doIso=!1){let sign=minutes<0?"-":"+",abs=Math.abs(minutes),hours=Math.floor(abs/60),mins=Math.round(abs%60);return doIso?`${sign+padStart(hours,2)}:${padStart(mins,2)}`:`GMT${sign}${hours}${mins?`:${padStart(mins,2)}`:""}`}function joinDateTimeFormatParts(parts){let s="";for(let part of parts)s+=part.value;return s}var ISO_RE=/^\s*(\d{4})(-?(\d{2})(-?(\d{2})([T ](\d{2}):?(\d{2})(:?(\d{2})(\.(\d+))?)?(Z|(([-+])(\d{2})(:?(\d{2}))?))?)?)?)?$/;function parse(str){let m=ISO_RE.exec(str);if(m){let marker=new Date(Date.UTC(Number(m[1]),m[3]?Number(m[3])-1:0,Number(m[5]||1),Number(m[7]||0),Number(m[8]||0),Number(m[10]||0),m[12]?+`0.${m[12]}`*1e3:0));if(isValidDate(marker)){let timeZoneOffset=null;return m[13]&&(timeZoneOffset=(m[15]==="-"?-1:1)*(Number(m[16]||0)*60+Number(m[18]||0))),{marker,isTimeUnspecified:!m[6],timeZoneOffset}}}return null}var DateEnv=class{constructor(settings){this.timeZone=settings.timeZone,this.calendarSystem=createCalendarSystem(settings.calendarSystem),this.locale=settings.locale,this.weekDow=settings.locale.week.dow,this.weekDoy=settings.locale.week.doy,settings.weekNumberCalculation==="ISO"&&(this.weekDow=1,this.weekDoy=4),typeof settings.firstDay=="number"&&(this.weekDow=settings.firstDay),typeof settings.weekNumberCalculation=="function"&&(this.weekNumberFunc=settings.weekNumberCalculation),this.weekTextLong=settings.weekTextLong,this.weekTextShort=settings.weekTextShort??settings.weekTextLong,this.cmdFormatter=settings.cmdFormatter}createMarker(input){let meta=this.createMarkerMeta(input);return meta===null?null:meta.marker}createNowMarker(){return this.timestampToMarker(new Date().valueOf())}createMarkerMeta(input){if(typeof input=="string")return this.parse(input);let marker=null,instantMs;return typeof input=="number"?(marker=this.timestampToMarker(input),instantMs=input):input instanceof Date?(input=input.valueOf(),isNaN(input)||(marker=this.timestampToMarker(input),instantMs=input)):Array.isArray(input)&&(marker=arrayToUtcDate(input)),marker===null||!isValidDate(marker)?null:{marker,isTimeUnspecified:!1,instantMs}}parse(s){let parts=parse(s);if(parts===null)return null;let{marker}=parts,instantMs;return parts.timeZoneOffset!==null&&(instantMs=marker.valueOf()-parts.timeZoneOffset*60*1e3,marker=this.timestampToMarker(instantMs)),{marker,isTimeUnspecified:parts.isTimeUnspecified,instantMs}}getYear(marker){return this.calendarSystem.getMarkerYear(marker)}getMonth(marker){return this.calendarSystem.getMarkerMonth(marker)}getDay(marker){return this.calendarSystem.getMarkerDay(marker)}add(marker,dur){let a=this.calendarSystem.markerToArray(marker);return a[0]+=dur.years,a[1]+=dur.months,a[2]+=dur.days,a[6]+=dur.milliseconds,this.calendarSystem.arrayToMarker(a)}subtract(marker,dur){let a=this.calendarSystem.markerToArray(marker);return a[0]-=dur.years,a[1]-=dur.months,a[2]-=dur.days,a[6]-=dur.milliseconds,this.calendarSystem.arrayToMarker(a)}addYears(marker,n){let a=this.calendarSystem.markerToArray(marker);return a[0]+=n,this.calendarSystem.arrayToMarker(a)}addMonths(marker,n){let a=this.calendarSystem.markerToArray(marker);return a[1]+=n,this.calendarSystem.arrayToMarker(a)}diffWholeYears(m0,m1){let{calendarSystem}=this;return timeAsMs(m0)===timeAsMs(m1)&&calendarSystem.getMarkerDay(m0)===calendarSystem.getMarkerDay(m1)&&calendarSystem.getMarkerMonth(m0)===calendarSystem.getMarkerMonth(m1)?calendarSystem.getMarkerYear(m1)-calendarSystem.getMarkerYear(m0):null}diffWholeMonths(m0,m1){let{calendarSystem}=this;return timeAsMs(m0)===timeAsMs(m1)&&calendarSystem.getMarkerDay(m0)===calendarSystem.getMarkerDay(m1)?calendarSystem.getMarkerMonth(m1)-calendarSystem.getMarkerMonth(m0)+(calendarSystem.getMarkerYear(m1)-calendarSystem.getMarkerYear(m0))*12:null}greatestWholeUnit(m0,m1){let n=this.diffWholeYears(m0,m1);return n!==null?{unit:"year",value:n}:(n=this.diffWholeMonths(m0,m1),n!==null?{unit:"month",value:n}:(n=diffWholeWeeks(m0,m1),n!==null?{unit:"week",value:n}:(n=diffWholeDays(m0,m1),n!==null?{unit:"day",value:n}:(n=diffHours4(m0,m1),isInt(n)?{unit:"hour",value:n}:(n=diffMinutes4(m0,m1),isInt(n)?{unit:"minute",value:n}:(n=diffSeconds4(m0,m1),isInt(n)?{unit:"second",value:n}:{unit:"millisecond",value:m1.valueOf()-m0.valueOf()}))))))}countDurationsBetween(m0,m1,d){let diff3;return d.years&&(diff3=this.diffWholeYears(m0,m1),diff3!==null)?diff3/asRoughYears(d):d.months&&(diff3=this.diffWholeMonths(m0,m1),diff3!==null)?diff3/asRoughMonths(d):d.days&&(diff3=diffWholeDays(m0,m1),diff3!==null)?diff3/asRoughDays(d):(m1.valueOf()-m0.valueOf())/asRoughMs(d)}startOf(m,unit){return unit==="year"?this.startOfYear(m):unit==="month"?this.startOfMonth(m):unit==="week"?this.startOfWeek(m):unit==="day"?startOfDay5(m):unit==="hour"?startOfHour4(m):unit==="minute"?startOfMinute4(m):unit==="second"?startOfSecond4(m):null}startOfYear(m){return this.calendarSystem.arrayToMarker([this.calendarSystem.getMarkerYear(m)])}startOfMonth(m){return this.calendarSystem.arrayToMarker([this.calendarSystem.getMarkerYear(m),this.calendarSystem.getMarkerMonth(m)])}startOfWeek(m){return this.calendarSystem.arrayToMarker([this.calendarSystem.getMarkerYear(m),this.calendarSystem.getMarkerMonth(m),m.getUTCDate()-(m.getUTCDay()-this.weekDow+7)%7])}computeWeekNumber(marker){return this.weekNumberFunc?this.weekNumberFunc(this.toDate(marker)):weekOfYear3(marker,this.weekDow,this.weekDoy)}formatToParts(marker,formatter,dateOptions={}){return formatter.formatToParts(this.toZonedInstant(marker,dateOptions.instantMs),this)}formatRangeToParts(start,end,formatter,dateOptions={}){let{endInstantMs}=dateOptions;return dateOptions.isEndExclusive&&(end=addMs(end,-1),endInstantMs!=null&&(endInstantMs-=1)),formatter.formatRangeToParts(this.toZonedInstant(start,dateOptions.startInstantMs),this.toZonedInstant(end,endInstantMs),this)}toZonedInstant(marker,instantMs){return instantMs==null&&(instantMs=this.toDate(marker).valueOf()),{marker:this.timestampToMarker(instantMs),instantMs}}formatIso(marker,extraOptions={}){let timeZoneOffset=null;return extraOptions.omitTimeZoneOffset||(timeZoneOffset=this.offsetForMarker(marker)),buildIsoString(marker,timeZoneOffset,extraOptions.omitTime)}timestampToMarker(ms){if(this.timeZone==="local")return arrayToUtcDate(dateToLocalArray(new Date(ms)));if(this.timeZone==="UTC")return new Date(ms);let zdt=toZonedDateTimeISO3(fromEpochMilliseconds3(ms),this.timeZone);return new Date(Date.UTC(zdt.year,zdt.month-1,zdt.day,zdt.hour,zdt.minute,zdt.second,zdt.millisecond))}offsetForMarker(m){return this.timeZone==="local"?-arrayToLocalDate(dateToUtcArray(m)).getTimezoneOffset():this.timeZone==="UTC"?0:offsetNanoseconds3(toZonedDateTime(create(m.getUTCFullYear(),m.getUTCMonth()+1,m.getUTCDate(),m.getUTCHours(),m.getUTCMinutes(),m.getUTCSeconds(),m.getUTCMilliseconds()),this.timeZone))/(1e9*60)}toDate(m){return this.timeZone==="local"?arrayToLocalDate(dateToUtcArray(m)):this.timeZone==="UTC"?new Date(m.valueOf()):new Date(toZonedDateTime(create(m.getUTCFullYear(),m.getUTCMonth()+1,m.getUTCDate(),m.getUTCHours(),m.getUTCMinutes(),m.getUTCSeconds(),m.getUTCMilliseconds()),this.timeZone).epochMilliseconds)}},EXTENDED_SETTINGS=new Set(["week","meridiem","omitZeroMinute","omitCommas","forceCommas","omitTrailing","weekdayJustify"]),MERIDIEM_RE=/([ap])\.?m\.?/i,COMMA_RE=/,/g,LTR_RE=/\u200e/g,TRAILING_RE=/[\s.,]+$/,WHITESPACE_ONLY_RE=/^\s+$/,NativeDateFormatter=class{constructor(options){let standardOptions={},extendedOptions={};for(let name in options)EXTENDED_SETTINGS.has(name)?extendedOptions[name]=options[name]:standardOptions[name]=options[name];standardOptions.timeZoneName&&(standardOptions.timeZoneName="shortOffset"),this.timeZoneOnly=Object.keys(standardOptions).length===1&&!!standardOptions.timeZoneName,this.weekOnly=!!(!Object.keys(standardOptions).length&&extendedOptions.week),this.timeZoneOnly||(standardOptions.timeZoneName&&(standardOptions.hour||(standardOptions.hour="2-digit"),standardOptions.minute||(standardOptions.minute="2-digit")),extendedOptions.omitZeroMinute&&(standardOptions.second||standardOptions.fractionalSecondDigits)&&delete extendedOptions.omitZeroMinute),this.standardOptions=standardOptions,this.extendedOptions=extendedOptions}formatToParts(date,context){let{extendedOptions}=this;if(this.timeZoneOnly)return this.getFormats(context).normalFormat.formatToParts(date.instantMs).filter(part=>part.type==="timeZoneName");if(this.weekOnly)return formatWeekNumberParts(context.computeWeekNumber(date.marker),context.weekTextLong,context.weekTextShort,context.locale,extendedOptions.week);let{normalFormat,zeroFormat}=this.getFormats(context),parts=(zeroFormat&&!date.marker.getUTCMinutes()?zeroFormat:normalFormat).formatToParts(date.instantMs);return postProcessParts(parts,extendedOptions)}formatRangeToParts(start,end,context){let{extendedOptions}=this;if(this.timeZoneOnly||this.weekOnly)return this.formatToParts(start,context).map(part=>({source:part.type==="literal"?"shared":"startRange",...part}));let{normalFormat,zeroFormat}=this.getFormats(context),parts=(zeroFormat&&!start.marker.getUTCMinutes()&&!end.marker.getUTCMinutes()?zeroFormat:normalFormat).formatRangeToParts(start.instantMs,end.instantMs);return postProcessRangeParts(parts,extendedOptions)}getFormats(context){if(this.cachedContext!==context){let{extendedOptions}=this,{codes}=context.locale,standardOptions={...this.standardOptions,timeZone:context.timeZone==="local"?void 0:context.timeZone},normalFormat=new Intl.DateTimeFormat(codes,standardOptions),zeroFormat;if(extendedOptions.omitZeroMinute){let zeroProps={...standardOptions};delete zeroProps.minute,zeroFormat=new Intl.DateTimeFormat(codes,zeroProps)}this.cachedContext=context,this.cachedFormats={normalFormat,zeroFormat}}return this.cachedFormats}};function processPartsLoop(parts,extendedOptions){let priorLiteral;for(let part of parts){let isLiteral=part.type==="literal";if(isLiteral||part.type==="dayPeriod"){let s=part.value;if(s=s.replace(LTR_RE,""),extendedOptions.omitCommas&&(s=s.replace(COMMA_RE,"")),!isLiteral){let{meridiem}=extendedOptions;meridiem===!1?s=s.replace(MERIDIEM_RE,""):meridiem==="narrow"?s=s.replace(MERIDIEM_RE,(_m0,m1)=>m1.toLocaleLowerCase()):meridiem==="short"?s=s.replace(MERIDIEM_RE,(_m0,m1)=>`${m1.toLocaleLowerCase()}m`):meridiem==="lowercase"&&(s=s.replace(MERIDIEM_RE,m0=>m0.toLocaleLowerCase())),priorLiteral&&(priorLiteral.value=priorLiteral.value.trimEnd())}part.value=s}priorLiteral=isLiteral?part:void 0}}function postProcessParts(parts,extendedOptions){if(processPartsLoop(parts,extendedOptions),extendedOptions.weekdayJustify&&parts.length===3&&WHITESPACE_ONLY_RE.test(parts[1].value)&&parts[extendedOptions.weekdayJustify==="start"?2:0].type==="weekday"&&parts.reverse(),extendedOptions.forceCommas)for(let part of parts)part.type==="literal"&&WHITESPACE_ONLY_RE.test(part.value)&&(part.value=`,${part.value}`);return extendedOptions.omitTrailing&&stripTrailingLiteral(parts),parts.filter(part=>part.value)}function postProcessRangeParts(parts,extendedOptions){if(processPartsLoop(parts,extendedOptions),extendedOptions.forceCommas)for(let part of parts)part.type==="literal"&&WHITESPACE_ONLY_RE.test(part.value)&&(part.value=`,${part.value}`);return extendedOptions.omitTrailing&&stripTrailingLiteral(parts),parts.filter(part=>part.value)}function stripTrailingLiteral(parts){let lastPart=parts[parts.length-1];lastPart?.type==="literal"&&(lastPart.value=lastPart.value.replace(TRAILING_RE,""),lastPart.value||parts.pop())}function formatWeekNumberParts(num,weekTextLong,weekTextShort,locale,display){let parts=[];return display==="long"?parts.push({type:"literal",value:weekTextLong}):(display==="short"||display==="narrow")&&parts.push({type:"literal",value:weekTextShort}),(display==="long"||display==="short")&&parts.push({type:"literal",value:" "}),parts.push({type:"week",value:locale.simpleNumberFormat.format(num)}),locale.options.direction==="rtl"&&parts.reverse(),parts}var CmdDateFormatter=class{constructor(cmdStr){this.cmdStr=cmdStr}formatToParts(date,context){let res=context.cmdFormatter(this.cmdStr,createVerboseFormattingArg(date,null,context));return Array.isArray(res)?res:[{type:"literal",value:res}]}formatRangeToParts(start,end,context){let res=context.cmdFormatter(this.cmdStr,createVerboseFormattingArg(start,end,context));return Array.isArray(res)?res.map(part=>({source:"shared",...part})):[{source:"shared",type:"literal",value:res}]}},FuncDateFormatter=class{constructor(func){this.func=func}formatToParts(date,context){return[{type:"literal",value:this.func(createVerboseFormattingArg(date,null,context))}]}formatRangeToParts(start,end,context){return[{source:"shared",type:"literal",value:this.func(createVerboseFormattingArg(start,end,context))}]}};var classNames={popoverZ:"fc-ZK",isolate:"fc-5R",borderBoxRoot:"fc-O6",notAllowed:"fc-fF",noScrollbars:"fc-Rp",noShrink:"fc-tp",calendarScreenRoot:"fc-MU",safeTiles:"fc-rr",calendarPrintRoot:"fc-ob",cursorPointer:"fc-iz",cursorResizeT:"fc-W6",cursorResizeB:"fc-9e",cursorResizeS:"fc-wb",cursorResizeE:"fc-0b",cursorColResizer:"fc-Gz",hit:"fc-wZ",hitX:"fc-oJ",hitY:"fc-9A",hitXSkinny:"fc-Yf",selectNone:"fc-AQ",invisible:"fc-MJ",borderless:"fc-Yq",borderlessX:"fc-3R",borderlessY:"fc-dv",borderlessTop:"fc-Yk",borderlessBottom:"fc-b1",borderlessStart:"fc-W7",borderlessEnd:"fc-Eu",flexRow:"fc-bH",flexCol:"fc-Ih",grow:"fc-BH",liquid:"fc-1Y",minHeight0:"fc-Ux",liquidX:"fc-ZM",printTable:"fc-Gx",noPadding:"fc-33",noPaddingY:"fc-5V",noMargin:"fc-b4",noMarginY:"fc-H8",noMarginX:"fc-Oq",whiteSpaceNoWrap:"fc-oX",whiteSpacePre:"fc-LF",overflowAnchorNone:"fc-Gg",pointerEventsNone:"fc-87",crop:"fc-5o",cropNowrap:"fc-7P",rel:"fc-XV",abs:"fc-Ew",start0:"fc-bN",end0:"fc-cH",fill:"fc-wd",fillTop:"fc-sd",fillX:"fc-ar",fillY:"fc-0H",fillStart:"fc-63",sticky:"fc-WL",stickyT:"fc-i6",stickyS:"fc-n4",tableHeaderSticky:"fc-q0",contentBox:"fc-F2",offscreen:"fc-rZ",alignCenter:"fc-dG",alignStart:"fc-jB",alignEnd:"fc-6B",footerScrollbarSticky:"fc-89",footerScrollbar:"fc-Se",breakInsideAvoid:"fc-qu",printCellContentMinHeight:"fc-sn",flowRoot:"fc-os",z0:"fc-P0",z1:"fc-hB",z2:"fc-b7",z3:"fc-BR",z4:"fc-eM",z5:"fc-zy",z1000:"fc-xI",z9999:"fc-hJ",focusZ2:"fc-0t",internalTimelineSlot:"fc-wp",internalEvent:"fc-ZR",internalEventMirror:"fc-Ai",internalEventDraggable:"fc-cj",internalEventSelected:"fc-dI",internalEventResizable:"fc-td",internalEventResizer:"fc-AJ",internalEventResizerStart:"fc-0y",internalEventResizerEnd:"fc-oN",internalBgEvent:"fc-vZ",internalMoreLink:"fc-Gh",internalNavLink:"fc-JP",internalPopover:"fc-WR",internalView:"fc-25",internalScroller:"fc-8b"};function joinClassNames(...args){return args.filter(Boolean).join(" ")}function fracToCssDim(frac){return frac*100+"%"}function createFormatter(input){return typeof input=="object"&&input?new NativeDateFormatter(input):typeof input=="string"?new CmdDateFormatter(input):typeof input=="function"?new FuncDateFormatter(input):null}function warn(...args){console.warn("FullCalendar:",...args)}var warnedClassNameOptions={};function refineClassName(input,optionName){return!input||typeof input=="string"?input:(warnInvalidClassName(optionName),"")}function refineClassNameGenerator(input,optionName){return typeof input=="function"?renderProps=>refineClassName(input(renderProps),optionName):refineClassName(input,optionName)}function warnInvalidClassName(optionName){warnedClassNameOptions[optionName]||(warn(`Invalid option \`${optionName}\`: expected a className string or a falsy value.`),warnedClassNameOptions[optionName]=!0)}function preventDefault(ev){ev.preventDefault()}function buildDelegationHandler(selector,handler){return ev=>{let matchedChild=ev.target.closest(selector);matchedChild&&handler.call(matchedChild,ev,matchedChild)}}function listenBySelector(container,eventType,selector,handler){let attachedHandler=buildDelegationHandler(selector,handler);return container.addEventListener(eventType,attachedHandler),()=>{container.removeEventListener(eventType,attachedHandler)}}function listenToHoverBySelector(container,selector,onMouseEnter,onMouseLeave){let currentMatchedChild;return listenBySelector(container,"mouseover",selector,(mouseOverEv,matchedChild)=>{if(matchedChild!==currentMatchedChild){currentMatchedChild=matchedChild,onMouseEnter(mouseOverEv,matchedChild);let realOnMouseLeave=mouseLeaveEv=>{currentMatchedChild=null,onMouseLeave(mouseLeaveEv,matchedChild),matchedChild.removeEventListener("mouseleave",realOnMouseLeave)};matchedChild.addEventListener("mouseleave",realOnMouseLeave)}})}var transitionEventNames=["webkitTransitionEnd","otransitionend","oTransitionEnd","msTransitionEnd","transitionend"];function whenTransitionDone(el,callback){let realCallback=ev=>{callback(ev),transitionEventNames.forEach(eventName=>{el.removeEventListener(eventName,realCallback)})};transitionEventNames.forEach(eventName=>{el.addEventListener(eventName,realCallback)})}function createAriaClickAttrs(handler){return{onClick:handler,...createAriaKeyboardAttrs(handler)}}function createAriaKeyboardAttrs(handler){return{tabIndex:0,onKeyDown(ev){(ev.key==="Enter"||ev.key===" ")&&(handler(ev),ev.preventDefault())}}}var guidNumber=0;function guid(){return guidNumber+=1,String(guidNumber)}function disableCursor(){document.body.classList.add(classNames.notAllowed)}function enableCursor(){document.body.classList.remove(classNames.notAllowed)}function preventSelection(el){el.style.userSelect="none",el.style.webkitUserSelect="none",el.addEventListener("selectstart",preventDefault)}function allowSelection(el){el.style.userSelect="",el.style.webkitUserSelect="",el.removeEventListener("selectstart",preventDefault)}function preventContextMenu(el){el.addEventListener("contextmenu",preventDefault)}function allowContextMenu(el){el.removeEventListener("contextmenu",preventDefault)}function parseFieldSpecs(input){let specs=[],tokens=[],i,token;for(typeof input=="string"?tokens=input.split(/\s*,\s*/):typeof input=="function"?tokens=[input]:Array.isArray(input)&&(tokens=input),i=0;i<tokens.length;i+=1)token=tokens[i],typeof token=="string"?specs.push(token.charAt(0)==="-"?{field:token.substring(1),order:-1}:{field:token,order:1}):typeof token=="function"&&specs.push({func:token});return specs}function compareByFieldSpecs(obj0,obj1,fieldSpecs){let i,cmp;for(i=0;i<fieldSpecs.length;i+=1)if(cmp=compareByFieldSpec(obj0,obj1,fieldSpecs[i]),cmp)return cmp;return 0}function compareByFieldSpec(obj0,obj1,fieldSpec){return fieldSpec.func?fieldSpec.func(obj0,obj1):flexibleCompare(obj0[fieldSpec.field],obj1[fieldSpec.field])*(fieldSpec.order||1)}function flexibleCompare(a,b){return!a&&!b?0:b==null?-1:a==null?1:typeof a=="string"||typeof b=="string"?String(a).localeCompare(String(b)):a-b}function formatWithOrdinals(formatter,args,fallbackText){return typeof formatter=="function"?formatter(...args):typeof formatter=="string"?args.reduce((str,arg,index2)=>str.replace("$"+index2,arg||""),formatter):fallbackText}function compareNumbers2(a,b){return a-b}function valuesIdentical(a,b){return a===b}function computeViewBorderless(options){let borderless=options.borderless;return{borderlessX:!!(options.borderlessX??borderless),borderlessTop:!!(options.borderlessTop??borderless),borderlessBottom:!!(options.borderlessBottom??borderless)}}var{hasOwnProperty}=Object.prototype;function filterHash(hash,func){let filtered={};for(let key in hash)func(hash[key],key)&&(filtered[key]=hash[key]);return filtered}function mapHash(hash,func){let newHash={};for(let key in hash)newHash[key]=func(hash[key],key);return newHash}function hashValuesToArray(obj){let a=[];for(let key in obj)a.push(obj[key]);return a}function arrayToHash(a){let hash={};for(let item of a)hash[item]=!0;return hash}function isMaybePropsEqualDepth1(props0,props1){return typeof props0=="object"&&props0&&typeof props1=="object"&&props1?isPropsEqualWithFunc(props0,props1,isPropsEqualShallow):props0===props1}function isPropsEqualWithFunc(props0,props1,valuesEqual){if(props0===props1)return!0;for(let key in props0)if(hasOwnProperty.call(props0,key)&&!(key in props1))return!1;for(let key in props1)if(hasOwnProperty.call(props1,key)&&(!(key in props0)||!valuesEqual(props0[key],props1[key],key)))return!1;return!0}function isMaybePropsEqualShallow(props0,props1){return typeof props0=="object"&&typeof props1=="object"&&props0&&props1?isPropsEqualShallow(props0,props1):props0===props1}function isPropsEqualShallow(props0,props1){return isPropsEqualWithFunc(props0,props1,valuesIdentical)}function isPropsEqualWithMap(props0,props1,equalityFuncMap){return isPropsEqualWithFunc(props0,props1,(val0,val1,key)=>{let equalityFunc=equalityFuncMap[key];return equalityFunc?equalityFunc(val0,val1):val0===val1})}function getUnequalProps(props0,props1){let keys=[];for(let key in props0)hasOwnProperty.call(props0,key)&&(key in props1||keys.push(key));for(let key in props1)hasOwnProperty.call(props1,key)&&props0[key]!==props1[key]&&keys.push(key);return keys}function mergeMaybePropsDepth1(props0,props1){return props0?mergePropsWithFunc(props0,props1,mergePropsShallow):props1}function mergePropsWithFunc(props0,props1,mergeValues){let dest={};for(let key in props0)hasOwnProperty.call(props0,key)&&(key in props1||(dest[key]=props0[key]));for(let key in props1)hasOwnProperty.call(props1,key)&&(key in props0?dest[key]=mergeValues(props0[key],props1[key]):dest[key]=props1[key]);return dest}function mergePropsShallow(props0,props1){return Object.assign({},props0,props1)}function flatArray(items){let res=[];for(let item of items)if(Array.isArray(item))for(let subItem of item)res.push(subItem);else res.push(item);return res}function flatMapArray(inputs,mapFunc){let res=[];for(let i=0;i<inputs.length;i+=1){let output=mapFunc(inputs[i],i);if(Array.isArray(output))for(let subOutput of output)res.push(subOutput);else res.push(output)}return res}function isMaybeArraysEqual(array0,array1){return Array.isArray(array0)&&Array.isArray(array1)?isArraysEqual(array0,array1):array0===array1}function isArraysEqual(array0,array1,itemsEqual=valuesIdentical){if(array0===array1)return!0;let len=array0.length,i;if(len!==array1.length)return!1;for(i=0;i<len;i+=1)if(!itemsEqual(array0[i],array1[i]))return!1;return!0}var BASE_OPTION_REFINERS={navLinkDayClick:identity,navLinkWeekClick:identity,duration:createDuration,buttons:identity,toolbarElements:identity,prevText:String,nextText:String,prevYearText:String,nextYearText:String,todayText:String,yearText:String,monthText:String,weekTextLong:String,weekTextShort:String,dayText:String,listText:identity,todayHint:identity,prevHint:identity,nextHint:identity,buttonDisplay:identity,buttonGroupClass:refineClassNameGenerator,buttonClass:refineClassNameGenerator,defaultAllDayEventDuration:createDuration,defaultTimedEventDuration:createDuration,nextDayThreshold:createDuration,scrollTime:createDuration,scrollTimeReset:Boolean,slotMinTime:createDuration,slotMaxTime:createDuration,popoverFormat:createFormatter,slotDuration:createDuration,snapDuration:createDuration,headerToolbar:identity,footerToolbar:identity,forceEventDuration:Boolean,dayLaneClass:refineClassNameGenerator,dayLaneInnerClass:refineClassNameGenerator,dayLaneDidMount:identity,dayLaneWillUnmount:identity,initialView:String,aspectRatio:Number,weekends:Boolean,weekNumberCalculation:identity,weekNumbers:Boolean,weekNumberHeaderClass:refineClassNameGenerator,weekNumberHeaderInnerClass:refineClassNameGenerator,weekNumberHeaderContent:identity,weekNumberHeaderDidMount:identity,weekNumberHeaderWillUnmount:identity,inlineWeekNumberClass:refineClassNameGenerator,inlineWeekNumberContent:identity,inlineWeekNumberDidMount:identity,inlineWeekNumberWillUnmount:identity,editable:Boolean,controller:identity,nowIndicator:Boolean,nowIndicatorSnap:identity,nowIndicatorHeaderClass:refineClassNameGenerator,nowIndicatorHeaderContent:identity,nowIndicatorHeaderDidMount:identity,nowIndicatorHeaderWillUnmount:identity,nowIndicatorDotClass:refineClassName,nowIndicatorLineClass:refineClassNameGenerator,nowIndicatorLineContent:identity,nowIndicatorLineDidMount:identity,nowIndicatorLineWillUnmount:identity,showNonCurrentDates:Boolean,lazyFetching:Boolean,startParam:String,endParam:String,timeZoneParam:String,timeZone:String,locales:identity,locale:identity,dragRevertDuration:Number,dragScroll:Boolean,allDayMaintainDuration:Boolean,unselectAuto:Boolean,dropAccept:identity,eventOrder:parseFieldSpecs,eventOrderStrict:Boolean,eventSlicing:Boolean,eventPrintLayout:String,longPressDelay:Number,eventDragMinDistance:Number,expandRows:Boolean,height:identity,contentHeight:identity,direction:String,colorScheme:String,weekNumberFormat:createFormatter,eventResizableFromStart:Boolean,displayEventTime:Boolean,displayEventEnd:Boolean,progressiveEventRendering:Boolean,businessHours:identity,initialDate:identity,now:identity,eventDataTransform:identity,tableHeaderSticky:identity,footerScrollbarSticky:identity,defaultAllDay:Boolean,eventSourceFailure:identity,eventSourceSuccess:identity,eventDisplay:String,eventStartEditable:Boolean,eventDurationEditable:Boolean,eventOverlap:identity,eventConstraint:identity,eventAllow:identity,eventColor:String,eventContrastColor:String,eventDidMount:identity,eventWillUnmount:identity,eventContent:identity,eventClass:refineClassNameGenerator,eventInnerClass:refineClassNameGenerator,eventTimeClass:refineClassNameGenerator,eventTitleClass:refineClassNameGenerator,eventBeforeClass:refineClassNameGenerator,eventAfterClass:refineClassNameGenerator,listItemEventClass:refineClassNameGenerator,listItemEventInnerClass:refineClassNameGenerator,listItemEventTimeClass:refineClassNameGenerator,listItemEventTitleClass:refineClassNameGenerator,listItemEventBeforeClass:refineClassNameGenerator,listItemEventAfterClass:refineClassNameGenerator,blockEventClass:refineClassNameGenerator,blockEventInnerClass:refineClassNameGenerator,blockEventTimeClass:refineClassNameGenerator,blockEventTitleClass:refineClassNameGenerator,blockEventBeforeClass:refineClassNameGenerator,blockEventAfterClass:refineClassNameGenerator,rowEventClass:refineClassNameGenerator,rowEventInnerClass:refineClassNameGenerator,rowEventTimeClass:refineClassNameGenerator,rowEventTitleClass:refineClassNameGenerator,rowEventTitleSticky:Boolean,rowEventBeforeClass:refineClassNameGenerator,rowEventBeforeContent:identity,rowEventAfterClass:refineClassNameGenerator,rowEventAfterContent:identity,columnEventClass:refineClassNameGenerator,columnEventInnerClass:refineClassNameGenerator,columnEventTimeClass:refineClassNameGenerator,columnEventTitleClass:refineClassNameGenerator,columnEventTitleSticky:Boolean,columnEventBeforeClass:refineClassNameGenerator,columnEventAfterClass:refineClassNameGenerator,backgroundEventClass:refineClassNameGenerator,backgroundEventDidMount:identity,backgroundEventWillUnmount:identity,backgroundEventContent:identity,backgroundEventInnerClass:refineClassNameGenerator,backgroundEventTitleClass:refineClassNameGenerator,backgroundEventColor:String,selectConstraint:identity,selectOverlap:identity,selectAllow:identity,droppable:Boolean,unselectCancel:String,slotHeaderFormat:identity,slotLaneClass:refineClassNameGenerator,slotLaneDidMount:identity,slotLaneWillUnmount:identity,slotHeaderClass:refineClassNameGenerator,slotHeaderInnerClass:refineClassNameGenerator,slotHeaderContent:identity,slotHeaderDidMount:identity,slotHeaderWillUnmount:identity,slotHeaderAlign:identity,slotHeaderSticky:identity,slotHeaderRowClass:refineClassName,slotHeaderDividerClass:refineClassNameGenerator,dayMaxEvents:identity,dayMaxEventRows:identity,dayMinWidth:Number,slotHeaderInterval:createDuration,dayHeaderClass:refineClassNameGenerator,dayHeaderInnerClass:refineClassNameGenerator,dayHeaderContent:identity,dayHeaderDidMount:identity,dayHeaderWillUnmount:identity,dayHeaderAlign:identity,_dayHeaderSticky:identity,dayHeaderRowClass:refineClassName,dayHeaderDividerClass:refineClassNameGenerator,dayRowClass:refineClassName,dayCellDidMount:identity,dayCellWillUnmount:identity,dayCellClass:refineClassNameGenerator,dayCellInnerClass:refineClassNameGenerator,dayCellTopContent:identity,dayCellTopClass:refineClassNameGenerator,dayCellTopInnerClass:refineClassNameGenerator,dayCellBottomClass:refineClassNameGenerator,allDaySlot:Boolean,allDayText:String,allDayHeaderClass:refineClassNameGenerator,allDayHeaderInnerClass:refineClassNameGenerator,allDayHeaderContent:identity,allDayHeaderDidMount:identity,allDayHeaderWillUnmount:identity,timedText:String,slotMinWidth:Number,slotMinHeight:Number,navLinks:Boolean,eventTimeFormat:createFormatter,rerenderDelay:Number,moreLinkText:identity,moreLinkHint:identity,selectMinDistance:Number,selectable:Boolean,selectLongPressDelay:Number,eventLongPressDelay:Number,selectMirror:Boolean,eventMaxStack:Number,eventMinHeight:Number,eventMinWidth:Number,eventShortHeight:Number,slotEventOverlap:Boolean,firstDay:Number,dayCount:Number,dateAlignment:String,dateIncrement:createDuration,hiddenDays:identity,fixedWeekCount:Boolean,validRange:identity,visibleRange:identity,titleFormat:identity,eventInteractive:Boolean,noEventsText:String,viewHint:identity,viewChangeHint:String,navLinkHint:identity,closeHint:String,eventsHint:String,headingLevel:Number,moreLinkClick:identity,moreLinkContent:identity,moreLinkDidMount:identity,moreLinkWillUnmount:identity,moreLinkClass:refineClassNameGenerator,moreLinkInnerClass:refineClassNameGenerator,rowMoreLinkClass:refineClassNameGenerator,rowMoreLinkInnerClass:refineClassNameGenerator,columnMoreLinkClass:refineClassNameGenerator,columnMoreLinkInnerClass:refineClassNameGenerator,navLinkClass:refineClassName,monthStartFormat:createFormatter,dayCellFormat:createFormatter,handleCustomRendering:identity,customRenderingMetaMap:identity,popoverClass:refineClassName,popoverCloseClass:refineClassName,popoverCloseContent:identity,dayNarrowWidth:Number,borderless:Boolean,borderlessX:Boolean,borderlessTop:Boolean,borderlessBottom:Boolean,fillerClass:refineClassNameGenerator,headerToolbarClass:refineClassNameGenerator,footerToolbarClass:refineClassNameGenerator,toolbarClass:refineClassNameGenerator,toolbarSectionClass:refineClassNameGenerator,toolbarTitleClass:refineClassName,tableClass:refineClassNameGenerator,tableHeaderClass:refineClassNameGenerator,tableBodyClass:refineClassNameGenerator,nonBusinessHoursClass:refineClassName,highlightClass:refineClassName,dayHeaders:Boolean,dayHeaderFormat:createFormatter,allDayDividerClass:refineClassName,listDaysClass:refineClassName,listDayClass:refineClassNameGenerator,listDayFormat:createFalsableFormatter,listDayAltFormat:createFalsableFormatter,listDayHeaderDidMount:identity,listDayHeaderWillUnmount:identity,listDayHeaderClass:refineClassNameGenerator,listDayHeaderInnerClass:refineClassNameGenerator,listDayHeaderContent:identity,listDayBodyClass:refineClassNameGenerator,noEventsClass:refineClassNameGenerator,noEventsInnerClass:refineClassNameGenerator,noEventsContent:identity,noEventsDidMount:identity,noEventsWillUnmount:identity,multiMonthMaxColumns:Number,singleMonthMinWidth:Number,singleMonthTitleFormat:createFormatter,singleMonthDidMount:identity,singleMonthWillUnmount:identity,singleMonthClass:refineClassNameGenerator,singleMonthHeaderClass:refineClassNameGenerator,singleMonthHeaderInnerClass:refineClassNameGenerator},BASE_OPTION_DEFAULTS={buttonDisplay:"auto",eventDisplay:"auto",defaultTimedEventDuration:"01:00:00",defaultAllDayEventDuration:{day:1},forceEventDuration:!1,nextDayThreshold:"00:00:00",initialView:"",aspectRatio:1.35,weekends:!0,weekNumbers:!1,weekNumberCalculation:"local",editable:!1,nowIndicator:!1,scrollTime:"06:00:00",scrollTimeReset:!0,slotMinTime:"00:00:00",slotMaxTime:"24:00:00",showNonCurrentDates:!0,lazyFetching:!0,startParam:"start",endParam:"end",timeZoneParam:"timeZone",timeZone:"local",locales:[],locale:"",dragRevertDuration:500,dragScroll:!0,allDayMaintainDuration:!1,unselectAuto:!0,dropAccept:"*",eventOrder:"start,-duration,allDay,title",eventSlicing:!0,eventPrintLayout:"auto",popoverFormat:{month:"long",day:"numeric",year:"numeric"},longPressDelay:1e3,eventDragMinDistance:5,expandRows:!1,navLinks:!1,selectable:!1,eventMinHeight:15,eventMinWidth:30,eventShortHeight:30,monthStartFormat:{month:"long",day:"numeric"},dayCellFormat:{day:"numeric",omitTrailing:!0},headingLevel:2,outerBorder:!0,dayNarrowWidth:80,eventOverlap:!0,slotHeaderAlign:"start",slotHeaderSticky:!0,dayHeaderAlign:"start",_dayHeaderSticky:!0,rowEventTitleSticky:!0,columnEventTitleSticky:!0,nowIndicatorSnap:"auto",dayHeaders:!0},CALENDAR_LISTENER_REFINERS={datesSet:identity,eventsSet:identity,eventAdd:identity,eventChange:identity,eventRemove:identity,eventClick:identity,eventMouseEnter:identity,eventMouseLeave:identity,select:identity,unselect:identity,loading:identity,_unmount:identity,_beforeprint:identity,_afterprint:identity,_noDateSelect:identity,_noEventDrop:identity,_noEventResize:identity,_timeScrollRequest:identity,dateClick:identity,eventDragStart:identity,eventDragStop:identity,eventDrop:identity,eventResizeStart:identity,eventResizeStop:identity,eventResize:identity,drop:identity,eventReceive:identity,eventLeave:identity},CALENDAR_ONLY_OPTION_REFINERS={class:refineClassNameGenerator,className:refineClassNameGenerator,viewClass:refineClassNameGenerator,viewDidMount:identity,viewWillUnmount:identity,views:identity,plugins:identity,initialEvents:identity,events:identity,eventSources:identity},VIEW_ONLY_OPTION_REFINERS={type:String,component:identity,class:refineClassNameGenerator,className:refineClassNameGenerator,content:identity,didMount:identity,willUnmount:identity,buttonTextKey:String,dateProfileGeneratorClass:identity,usesMinMaxTime:Boolean,disallowAmbigTitle:Boolean},COMPLEX_OPTION_COMPARATORS={dateIncrement:isMaybePropsEqualShallow,headerToolbar:isMaybePropsEqualShallow,footerToolbar:isMaybePropsEqualShallow,buttons:isMaybePropsEqualDepth1,plugins:isMaybeArraysEqual,events:isMaybeArraysEqual,eventSources:isMaybeArraysEqual,resources:isMaybeArraysEqual};function refineProps(input,refiners){let refined={},extra={};for(let propName in refiners)propName in input&&(refined[propName]=refiners[propName](input[propName],propName));for(let propName in input)propName in refiners||(extra[propName]=input[propName]);return{refined,extra}}function identity(raw){return raw}function createFalsableFormatter(input){return input===!1?null:createFormatter(input)}function buildEventInstanceRange(start,end,instantStartMs,instantEndMs){let range={start,end};return instantStartMs!=null&&(range.instantStartMs=instantStartMs),instantEndMs!=null&&(range.instantEndMs=instantEndMs),range}function resolveEdgeInstantMs(marker,instantMs,dateEnv){return instantMs??dateEnv.toDate(marker).valueOf()}function buildRangeEdgeOutput(marker,instantMs,dateEnv,omitTime){let canonicalMarker=instantMs!=null?dateEnv.timestampToMarker(instantMs):marker,timeZoneOffset=instantMs!=null?Math.round((canonicalMarker.valueOf()-instantMs)/6e4):dateEnv.offsetForMarker(marker);return!omitTime&&instantMs!=null?{marker:canonicalMarker,date:new Date(instantMs),dateStr:buildIsoString(canonicalMarker,timeZoneOffset)}:{marker:canonicalMarker,date:dateEnv.toDate(marker),dateStr:omitTime?dateEnv.formatIso(marker,{omitTime}):buildIsoString(marker,timeZoneOffset)}}function getRangeInstantStartMs(range,dateEnv){return resolveEdgeInstantMs(range.start,range.instantStartMs,dateEnv)}function getRangeInstantEndMs(range,dateEnv){return resolveEdgeInstantMs(range.end,range.instantEndMs,dateEnv)}function canonicalRangeEndMarker(range,dateEnv){return range.instantEndMs!=null?dateEnv.timestampToMarker(range.instantEndMs):range.end}function rangeHasInstants(range){return range.instantStartMs!=null||range.instantEndMs!=null}function instanceRangesIntersect(range0,range1,dateEnv){return rangeHasInstants(range0)||rangeHasInstants(range1)?getRangeInstantStartMs(range0,dateEnv)<getRangeInstantEndMs(range1,dateEnv)&&getRangeInstantEndMs(range0,dateEnv)>getRangeInstantStartMs(range1,dateEnv):rangesIntersect(range0,range1)}function instanceRangeContainsRange(outerRange,innerRange,dateEnv){if(rangeHasInstants(outerRange)||rangeHasInstants(innerRange)){let outerStartMs=outerRange.start!=null?resolveEdgeInstantMs(outerRange.start,outerRange.instantStartMs,dateEnv):-1/0,outerEndMs=outerRange.end!=null?resolveEdgeInstantMs(outerRange.end,outerRange.instantEndMs,dateEnv):1/0;return outerStartMs<=getRangeInstantStartMs(innerRange,dateEnv)&&outerEndMs>=getRangeInstantEndMs(innerRange,dateEnv)}return rangeContainsRange(outerRange,innerRange)}function addDurationToEdge(edge,duration,dateEnv){if(edge.instantMs!=null&&!duration.years&&!duration.months&&!duration.days){let durMs=asRoughMs(duration),instantMs=edge.instantMs+durMs,marker=dateEnv.timestampToMarker(instantMs);return marker>edge.marker?{marker,instantMs}:{marker:addMs(edge.marker,durMs),instantMs}}return{marker:dateEnv.add(edge.marker,duration)}}function buildValidInstanceRange(start,end,dateEnv){if(start.instantMs==null&&end.instantMs==null)return end.marker>start.marker?buildEventInstanceRange(start.marker,end.marker):null;let startMs=resolveEdgeInstantMs(start.marker,start.instantMs,dateEnv),endMs=resolveEdgeInstantMs(end.marker,end.instantMs,dateEnv);return endMs<=startMs?null:buildEventInstanceRange(start.marker,end.marker>start.marker?end.marker:addMs(start.marker,endMs-startMs),start.instantMs,end.instantMs)}function createEventInstance(defId,range){return{instanceId:guid(),defId,range}}function computeAlignedDayRange(timedRange){let dayCnt=Math.floor(diffDays4(timedRange.start,timedRange.end))||1,start=startOfDay5(timedRange.start),end=addDays4(start,dayCnt);return{start,end}}function computeVisibleDayRange(timedRange,nextDayThreshold=createDuration(0)){let startDay=null,endDay=null;if(timedRange.end){endDay=startOfDay5(timedRange.end);let endTimeMS=timedRange.end.valueOf()-endDay.valueOf();endTimeMS&&endTimeMS>=asRoughMs(nextDayThreshold)&&(endDay=addDays4(endDay,1))}return timedRange.start&&(startDay=startOfDay5(timedRange.start),endDay&&endDay<=startDay&&(endDay=addDays4(startDay,1))),{start:startDay,end:endDay}}function diffDates(date0,date1,dateEnv,largeUnit){return largeUnit==="year"?createDuration(dateEnv.diffWholeYears(date0,date1),"year"):largeUnit==="month"?createDuration(dateEnv.diffWholeMonths(date0,date1),"month"):diffDayAndTime(date0,date1)}function parseRecurring(refined,defaultAllDay,dateEnv,recurringTypes){for(let i=0;i<recurringTypes.length;i+=1){let parsed=recurringTypes[i].parse(refined,dateEnv);if(parsed){let{allDay}=refined;return allDay==null&&(allDay=defaultAllDay,allDay==null&&(allDay=parsed.allDayGuess,allDay==null&&(allDay=!1))),{allDay,duration:parsed.duration,typeData:parsed.typeData,typeId:i}}}return null}function expandRecurring(eventStore,framingRange,context){let{dateEnv,pluginHooks,options}=context,{defs,instances}=eventStore;instances=filterHash(instances,instance=>!defs[instance.defId].recurringDef);for(let defId in defs){let def=defs[defId];if(def.recurringDef){let{duration}=def.recurringDef;duration||(duration=def.allDay?options.defaultAllDayEventDuration:options.defaultTimedEventDuration);let starts=expandRecurringRanges(def,duration,framingRange,dateEnv,pluginHooks.recurringTypes);for(let start of starts){let instance=createEventInstance(defId,{start,end:dateEnv.add(start,duration)});instances[instance.instanceId]=instance}}}return{defs,instances}}function expandRecurringRanges(eventDef,duration,framingRange,dateEnv,recurringTypes){let markers=recurringTypes[eventDef.recurringDef.typeId].expand(eventDef.recurringDef.typeData,{start:dateEnv.subtract(framingRange.start,duration),end:framingRange.end},dateEnv);return eventDef.allDay&&(markers=markers.map(startOfDay5)),markers}function parseEvents(rawEvents,eventSource,context,allowOpenRange,defIdMap,instanceIdMap){let eventStore=createEmptyEventStore(),eventRefiners=buildEventRefiners(context);for(let rawEvent of rawEvents){let tuple=parseEvent(rawEvent,eventSource,context,allowOpenRange,eventRefiners,defIdMap,instanceIdMap);tuple&&eventTupleToStore(tuple,eventStore)}return eventStore}function eventTupleToStore(tuple,eventStore=createEmptyEventStore()){return eventStore.defs[tuple.def.defId]=tuple.def,tuple.instance&&(eventStore.instances[tuple.instance.instanceId]=tuple.instance),eventStore}function getRelevantEvents(eventStore,instanceId){let instance=eventStore.instances[instanceId];if(instance){let def=eventStore.defs[instance.defId],newStore=filterEventStoreDefs(eventStore,lookDef=>isEventDefsGrouped(def,lookDef));return newStore.defs[def.defId]=def,newStore.instances[instance.instanceId]=instance,newStore}return createEmptyEventStore()}function isEventDefsGrouped(def0,def1){return!!(def0.groupId&&def0.groupId===def1.groupId)}function createEmptyEventStore(){return{defs:{},instances:{}}}function mergeEventStores(store0,store1){return{defs:{...store0.defs,...store1.defs},instances:{...store0.instances,...store1.instances}}}function filterEventStoreDefs(eventStore,filterFunc){let defs=filterHash(eventStore.defs,filterFunc),instances=filterHash(eventStore.instances,instance=>defs[instance.defId]);return{defs,instances}}function excludeSubEventStore(master,sub){let{defs,instances}=master,filteredDefs={},filteredInstances={};for(let defId in defs)sub.defs[defId]||(filteredDefs[defId]=defs[defId]);for(let instanceId in instances)!sub.instances[instanceId]&&filteredDefs[instances[instanceId].defId]&&(filteredInstances[instanceId]=instances[instanceId]);return{defs:filteredDefs,instances:filteredInstances}}function normalizeConstraint(input,context){return Array.isArray(input)?parseEvents(input,null,context,!0):typeof input=="object"&&input?parseEvents([input],null,context,!0):input!=null?String(input):null}var EVENT_UI_REFINERS={display:String,editable:Boolean,startEditable:Boolean,durationEditable:Boolean,constraint:identity,overlap:identity,allow:identity,class:refineClassName,className:refineClassName,color:String,contrastColor:String},EMPTY_EVENT_UI={display:null,startEditable:null,durationEditable:null,constraints:[],overlap:null,allows:[],color:"",contrastColor:"",className:""};function createEventUi(refined,context){let constraint=normalizeConstraint(refined.constraint,context);return{display:refined.display||null,startEditable:refined.startEditable!=null?refined.startEditable:refined.editable,durationEditable:refined.durationEditable!=null?refined.durationEditable:refined.editable,constraints:constraint!=null?[constraint]:[],overlap:refined.overlap!=null?refined.overlap:null,allows:refined.allow!=null?[refined.allow]:[],color:refined.color||"",contrastColor:refined.contrastColor||"",className:(refined.class??refined.className)||""}}function combineEventUis(uis){return uis.reduce(combineTwoEventUis,EMPTY_EVENT_UI)}function combineTwoEventUis(item0,item1){return{display:item1.display!=null?item1.display:item0.display,startEditable:item1.startEditable!=null?item1.startEditable:item0.startEditable,durationEditable:item1.durationEditable!=null?item1.durationEditable:item0.durationEditable,constraints:item0.constraints.concat(item1.constraints),overlap:typeof item1.overlap=="boolean"?item1.overlap:item0.overlap,allows:item0.allows.concat(item1.allows),color:item1.color||item0.color,contrastColor:item1.contrastColor||item0.contrastColor,className:joinClassNames(item0.className,item1.className)}}var EVENT_NON_DATE_REFINERS={id:String,groupId:String,title:String,url:String,interactive:Boolean},EVENT_DATE_REFINERS={start:identity,end:identity,date:identity,allDay:Boolean},EVENT_REFINERS={...EVENT_NON_DATE_REFINERS,...EVENT_DATE_REFINERS,extendedProps:identity};function parseEvent(raw,eventSource,context,allowOpenRange,refiners=buildEventRefiners(context),defIdMap,instanceIdMap){let{refined,extra}=refineEventDef(raw,context,refiners),defaultAllDay=computeIsDefaultAllDay(eventSource,context),recurringRes=parseRecurring(refined,defaultAllDay,context.dateEnv,context.pluginHooks.recurringTypes);if(recurringRes){let def=parseEventDef(refined,extra,eventSource?eventSource.sourceId:"",recurringRes.allDay,!!recurringRes.duration,context,defIdMap);return def.recurringDef={typeId:recurringRes.typeId,typeData:recurringRes.typeData,duration:recurringRes.duration},{def,instance:null}}let singleRes=parseSingle(refined,defaultAllDay,context,allowOpenRange);if(singleRes){let def=parseEventDef(refined,extra,eventSource?eventSource.sourceId:"",singleRes.allDay,singleRes.hasEnd,context,defIdMap),instance=createEventInstance(def.defId,singleRes.range);return instanceIdMap&&def.publicId&&instanceIdMap[def.publicId]&&(instance.instanceId=instanceIdMap[def.publicId]),{def,instance}}return null}function refineEventDef(raw,context,refiners=buildEventRefiners(context)){return refineProps(raw,refiners)}function buildEventRefiners(context){return{...EVENT_UI_REFINERS,...EVENT_REFINERS,...context.pluginHooks.eventRefiners}}function parseEventDef(refined,extra,sourceId,allDay,hasEnd,context,defIdMap){let def={title:refined.title||"",groupId:refined.groupId||"",publicId:refined.id||"",url:refined.url||"",recurringDef:null,defId:(defIdMap&&refined.id?defIdMap[refined.id]:"")||guid(),sourceId,allDay,hasEnd,interactive:refined.interactive,ui:createEventUi(refined,context),extendedProps:{...refined.extendedProps||{},...extra}};for(let memberAdder of context.pluginHooks.eventDefMemberAdders)Object.assign(def,memberAdder(refined));return Object.freeze(def.ui.className),Object.freeze(def.extendedProps),def}function parseSingle(refined,defaultAllDay,context,allowOpenRange){let{allDay}=refined,startMeta,startMarker=null,hasEnd=!1,endMeta,endMarker=null,startInput=refined.start!=null?refined.start:refined.date;if(startMeta=context.dateEnv.createMarkerMeta(startInput),startMeta)startMarker=startMeta.marker;else if(!allowOpenRange)return null;refined.end!=null&&(endMeta=context.dateEnv.createMarkerMeta(refined.end)),allDay==null&&(defaultAllDay!=null?allDay=defaultAllDay:allDay=(!startMeta||startMeta.isTimeUnspecified)&&(!endMeta||endMeta.isTimeUnspecified)),allDay&&startMarker&&(startMarker=startOfDay5(startMarker));let startInstantMs=!allDay&&startMeta?startMeta.instantMs:void 0,range=null;if(endMeta&&(endMarker=allDay?startOfDay5(endMeta.marker):endMeta.marker,startMarker?allDay?endMarker>startMarker&&(range=buildEventInstanceRange(startMarker,endMarker)):range=buildValidInstanceRange({marker:startMarker,instantMs:startInstantMs},{marker:endMarker,instantMs:endMeta.instantMs},context.dateEnv):range=buildEventInstanceRange(startMarker,endMarker,void 0,allDay?void 0:endMeta.instantMs)),range)hasEnd=!0;else if(allowOpenRange)range=buildEventInstanceRange(startMarker,null,startInstantMs);else{hasEnd=context.options.forceEventDuration||!1;let endEdge=addDurationToEdge({marker:startMarker,instantMs:startInstantMs},allDay?context.options.defaultAllDayEventDuration:context.options.defaultTimedEventDuration,context.dateEnv);range=buildEventInstanceRange(startMarker,endEdge.marker,startInstantMs,endEdge.instantMs)}return{allDay,hasEnd,range}}function computeIsDefaultAllDay(eventSource,context){let res=null;return eventSource&&(res=eventSource.defaultAllDay),res==null&&(res=context.options.defaultAllDay),res}var STANDARD_PROPS={start:identity,end:identity,allDay:Boolean};function parseDateSpan(raw,dateEnv,defaultDuration){let span=parseOpenDateSpan(raw,dateEnv);if(!span)return null;let{range}=span;if(!range.start)return null;if(!range.end){if(defaultDuration==null)return null;let endEdge=addDurationToEdge({marker:range.start,instantMs:span.instantStartMs},defaultDuration,dateEnv);range.end=endEdge.marker,endEdge.instantMs!=null&&(span.instantEndMs=endEdge.instantMs)}return span}function parseOpenDateSpan(raw,dateEnv){let{refined:standardProps,extra}=refineProps(raw,STANDARD_PROPS),startMeta=standardProps.start?dateEnv.createMarkerMeta(standardProps.start):null,endMeta=standardProps.end?dateEnv.createMarkerMeta(standardProps.end):null,{allDay}=standardProps;allDay==null&&(allDay=startMeta&&startMeta.isTimeUnspecified&&(!endMeta||endMeta.isTimeUnspecified));let range={start:startMeta?startMeta.marker:null,end:endMeta?endMeta.marker:null};if(!allDay&&startMeta&&endMeta&&(startMeta.instantMs!=null||endMeta.instantMs!=null)){let validRange=buildValidInstanceRange({marker:startMeta.marker,instantMs:startMeta.instantMs},{marker:endMeta.marker,instantMs:endMeta.instantMs},dateEnv);if(!validRange&&startMeta.instantMs!=null&&endMeta.instantMs!=null)return null;validRange&&(range={start:validRange.start,end:validRange.end})}let span={range,allDay,...extra};return allDay?(delete span.instantStartMs,delete span.instantEndMs):(startMeta?.instantMs!=null&&(span.instantStartMs=startMeta.instantMs),endMeta?.instantMs!=null&&(span.instantEndMs=endMeta.instantMs)),span}function isDateSpansEqual(span0,span1){return rangesEqual(span0.range,span1.range)&&span0.allDay===span1.allDay&&isSpanPropsEqual(span0,span1)}function isSpanPropsEqual(span0,span1){for(let propName in span1)if(propName!=="range"&&propName!=="allDay"&&span0[propName]!==span1[propName])return!1;for(let propName in span0)if(!(propName in span1))return!1;return!0}function buildDateSpanApi(span,dateEnv){return{...buildRangeApi(span.range,dateEnv,span.allDay,span),allDay:span.allDay}}function buildRangeApiWithTimeZone(range,dateEnv,omitTime){return{...buildRangeApi(range,dateEnv,omitTime),timeZone:dateEnv.timeZone}}function buildRangeApi(range,dateEnv,omitTime,rangeMeta){let instantStartMs=rangeMeta?.instantStartMs??range.instantStartMs,instantEndMs=rangeMeta?.instantEndMs??range.instantEndMs,start=buildRangeEdgeOutput(range.start,instantStartMs,dateEnv,omitTime),end=buildRangeEdgeOutput(range.end,instantEndMs,dateEnv,omitTime);return{start:start.date,end:end.date,startStr:start.dateStr,endStr:end.dateStr}}function getDateSpanInstantStartMs(dateSpan,dateEnv){return resolveEdgeInstantMs(dateSpan.range.start,dateSpan.instantStartMs,dateEnv)}function getDateSpanInstantEndMs(dateSpan,dateEnv){return resolveEdgeInstantMs(dateSpan.range.end,dateSpan.instantEndMs,dateEnv)}function fabricateEventRange(dateSpan,eventUiBases,context){let res=refineEventDef({editable:!1},context),def=parseEventDef(res.refined,res.extra,"",dateSpan.allDay,!0,context);return{def,ui:compileEventUi(def,eventUiBases),instance:createEventInstance(def.defId,dateSpan.range),range:dateSpan.range,isStart:!0,isEnd:!0}}function triggerDateSelect(selection,pev,context){context.emitter.trigger("select",{...buildDateSpanApiWithContext(selection,context),jsEvent:pev?pev.origEvent:null,view:context.viewApi||context.calendarApi.view})}function triggerDateUnselect(pev,context){context.emitter.trigger("unselect",{jsEvent:pev?pev.origEvent:null,view:context.viewApi||context.calendarApi.view})}function buildDateSpanApiWithContext(dateSpan,context){let props={};for(let transform of context.pluginHooks.dateSpanTransforms)Object.assign(props,transform(dateSpan,context));return Object.assign(props,buildDateSpanApi(dateSpan,context.dateEnv)),props}function getDefaultEventEnd(allDay,marker,context){let{dateEnv,options}=context,end=marker;return allDay?(end=startOfDay5(end),end=dateEnv.add(end,options.defaultAllDayEventDuration)):end=dateEnv.add(end,options.defaultTimedEventDuration),end}function getDefaultEventEndEdge(allDay,start,context){return allDay?{marker:getDefaultEventEnd(!0,start.marker,context)}:addDurationToEdge(start,context.options.defaultTimedEventDuration,context.dateEnv)}function applyMutationToEventStore(eventStore,eventConfigBase,mutation,context){let eventConfigs=compileEventUis(eventStore.defs,eventConfigBase),dest=createEmptyEventStore();for(let defId in eventStore.defs){let def=eventStore.defs[defId];dest.defs[defId]=applyMutationToEventDef(def,eventConfigs[defId],mutation,context)}for(let instanceId in eventStore.instances){let instance=eventStore.instances[instanceId],def=dest.defs[instance.defId];dest.instances[instanceId]=applyMutationToEventInstance(instance,def,eventConfigs[instance.defId],mutation,context)}return dest}function applyMutationToEventDef(eventDef,eventConfig,mutation,context){let standardProps=mutation.standardProps||{};standardProps.hasEnd==null&&eventConfig.durationEditable&&(mutation.startDelta||mutation.endDelta)&&(standardProps.hasEnd=!0);let copy={...eventDef,...standardProps,ui:{...eventDef.ui,...standardProps.ui}};mutation.extendedProps&&(copy.extendedProps={...copy.extendedProps,...mutation.extendedProps});for(let applier of context.pluginHooks.eventDefMutationAppliers)applier(copy,mutation,context);return!copy.hasEnd&&context.options.forceEventDuration&&(copy.hasEnd=!0),copy}function applyMutationToEventInstance(eventInstance,eventDef,eventConfig,mutation,context){let forceAllDay=mutation.standardProps&&mutation.standardProps.allDay===!0,clearEnd=mutation.standardProps&&mutation.standardProps.hasEnd===!1,copy={...eventInstance};if(forceAllDay&&(copy.range=computeAlignedDayRange(copy.range)),mutation.datesDelta&&eventConfig.startEditable&&(copy.range=buildInstanceRange(addDeltaToRangeEdge(copy.range.start,copy.range.instantStartMs,mutation.datesDelta,mutation.instantDatesDeltaMs,context),addDeltaToRangeEdge(copy.range.end,copy.range.instantEndMs,mutation.datesDelta,mutation.instantDatesDeltaMs,context))),mutation.startDelta&&eventConfig.durationEditable&&(copy.range=buildInstanceRange(addDeltaToRangeEdge(copy.range.start,copy.range.instantStartMs,mutation.startDelta,mutation.instantStartDeltaMs,context),{marker:copy.range.end,instantMs:copy.range.instantEndMs})),mutation.endDelta&&eventConfig.durationEditable&&(copy.range=buildInstanceRange({marker:copy.range.start,instantMs:copy.range.instantStartMs},addDeltaToRangeEdge(copy.range.end,copy.range.instantEndMs,mutation.endDelta,mutation.instantEndDeltaMs,context))),clearEnd){let startEdge={marker:copy.range.start,instantMs:copy.range.instantStartMs};copy.range=buildInstanceRange(startEdge,getDefaultEventEndEdge(eventDef.allDay,startEdge,context))}if(eventDef.allDay&&(copy.range={start:startOfDay5(copy.range.start),end:startOfDay5(copy.range.end)}),eventDef.allDay){if(copy.range.end<=copy.range.start){let startEdge={marker:copy.range.start};copy.range=buildInstanceRange(startEdge,getDefaultEventEndEdge(!0,startEdge,context))}}else{let startEdge={marker:copy.range.start,instantMs:copy.range.instantStartMs};copy.range=buildValidInstanceRange(startEdge,{marker:copy.range.end,instantMs:copy.range.instantEndMs},context.dateEnv)??buildInstanceRange(startEdge,getDefaultEventEndEdge(!1,startEdge,context))}return copy}function addDeltaToRangeEdge(marker,instantMs,delta,instantDeltaMs,context){if(instantDeltaMs!=null){let newInstantMs=resolveEdgeInstantMs(marker,instantMs,context.dateEnv)+instantDeltaMs;return{marker:context.dateEnv.timestampToMarker(newInstantMs),instantMs:newInstantMs}}return{marker:context.dateEnv.add(instantMs!=null?context.dateEnv.timestampToMarker(instantMs):marker,delta)}}function buildInstanceRange(start,end){return buildEventInstanceRange(start.marker,end.marker,start.instantMs,end.instantMs)}var EventSourceImpl=class{constructor(context,internalEventSource){this.context=context,this.internalEventSource=internalEventSource}remove(){this.context.dispatch({type:"REMOVE_EVENT_SOURCE",sourceId:this.internalEventSource.sourceId})}refetch(){this.context.dispatch({type:"FETCH_EVENT_SOURCES",sourceIds:[this.internalEventSource.sourceId],isRefetch:!0})}get id(){return this.internalEventSource.publicId}get url(){return this.internalEventSource.meta.url}get format(){return this.internalEventSource.meta.format}},EventImpl=class _EventImpl{constructor(context,def,instance){this._context=context,this._def=def,this._instance=instance||null}setProp(name,val){if(name in EVENT_DATE_REFINERS)warn(`Cannot set date-related event property \`${name}\`. Use a method instead.`);else if(name==="id")val=EVENT_NON_DATE_REFINERS[name](val),this.mutate({standardProps:{publicId:val}});else if(name in EVENT_NON_DATE_REFINERS)val=EVENT_NON_DATE_REFINERS[name](val),this.mutate({standardProps:{[name]:val}});else if(name in EVENT_UI_REFINERS){let ui=EVENT_UI_REFINERS[name](val);name==="editable"?ui={startEditable:val,durationEditable:val}:ui={[name]:val},this.mutate({standardProps:{ui}})}else warn(`Cannot set event property \`${name}\`. Use setExtendedProp instead.`)}setExtendedProp(name,val){this.mutate({extendedProps:{[name]:val}})}setStart(startInput,options={}){let{dateEnv}=this._context,startMeta=dateEnv.createMarkerMeta(startInput);if(startMeta&&this._instance){let instanceRange=this._instance.range,startDelta=diffDates(instanceRange.start,startMeta.marker,dateEnv,options.granularity),instantDeltaMs=computeInstantDeltaMs(startMeta,getRangeInstantStartMs(instanceRange,dateEnv),options.granularity);options.maintainDuration?this.mutate({datesDelta:startDelta,instantDatesDeltaMs:instantDeltaMs}):this.mutate({startDelta,instantStartDeltaMs:instantDeltaMs})}}setEnd(endInput,options={}){let{dateEnv}=this._context,endMeta=null;if(!(endInput!=null&&(endMeta=dateEnv.createMarkerMeta(endInput),!endMeta))&&this._instance)if(endMeta){let instanceRange=this._instance.range,endDelta=diffDates(canonicalRangeEndMarker(instanceRange,dateEnv),endMeta.marker,dateEnv,options.granularity),instantDeltaMs=computeInstantDeltaMs(endMeta,getRangeInstantEndMs(instanceRange,dateEnv),options.granularity);this.mutate({endDelta,instantEndDeltaMs:instantDeltaMs})}else this.mutate({standardProps:{hasEnd:!1}})}setDates(startInput,endInput,options={}){let{dateEnv}=this._context,standardProps={allDay:options.allDay},startMeta=dateEnv.createMarkerMeta(startInput),endMeta=null;if(startMeta&&!(endInput!=null&&(endMeta=dateEnv.createMarkerMeta(endInput),!endMeta))&&this._instance){let instanceRange=this._instance.range,skipInstants=options.allDay===!0,instantStartDeltaMs=skipInstants?void 0:computeInstantDeltaMs(startMeta,getRangeInstantStartMs(instanceRange,dateEnv),options.granularity),instantEndDeltaMs=skipInstants||!endMeta?void 0:computeInstantDeltaMs(endMeta,getRangeInstantEndMs(instanceRange,dateEnv),options.granularity);options.allDay===!0&&(instanceRange=computeAlignedDayRange(instanceRange));let startDelta=diffDates(instanceRange.start,startMeta.marker,dateEnv,options.granularity);if(endMeta){let endDelta=diffDates(canonicalRangeEndMarker(instanceRange,dateEnv),endMeta.marker,dateEnv,options.granularity);durationsEqual(startDelta,endDelta)&&instantStartDeltaMs===instantEndDeltaMs?this.mutate({datesDelta:startDelta,instantDatesDeltaMs:instantStartDeltaMs,standardProps}):this.mutate({startDelta,endDelta,instantStartDeltaMs,instantEndDeltaMs,standardProps})}else standardProps.hasEnd=!1,this.mutate({datesDelta:startDelta,instantDatesDeltaMs:instantStartDeltaMs,standardProps})}}moveStart(deltaInput){let delta=createDuration(deltaInput);delta&&this.mutate({startDelta:delta})}moveEnd(deltaInput){let delta=createDuration(deltaInput);delta&&this.mutate({endDelta:delta})}moveDates(deltaInput){let delta=createDuration(deltaInput);delta&&this.mutate({datesDelta:delta})}setAllDay(allDay,options={}){let standardProps={allDay},{maintainDuration}=options;maintainDuration==null&&(maintainDuration=this._context.options.allDayMaintainDuration),this._def.allDay!==allDay&&(standardProps.hasEnd=maintainDuration),this.mutate({standardProps})}formatRange(formatInput){let{dateEnv}=this._context,instance=this._instance,formatter=createFormatter(formatInput),start=buildRangeEdgeOutput(instance.range.start,instance.range.instantStartMs,dateEnv);if(this._def.hasEnd){let end=buildRangeEdgeOutput(instance.range.end,instance.range.instantEndMs,dateEnv);return joinDateTimeFormatParts(dateEnv.formatRangeToParts(start.marker,end.marker,formatter,{startInstantMs:start.date.valueOf(),endInstantMs:end.date.valueOf()}))}return joinDateTimeFormatParts(dateEnv.formatToParts(start.marker,formatter,{instantMs:start.date.valueOf()}))}mutate(mutation){let instance=this._instance;if(instance){let def=this._def,context=this._context,{eventStore}=context.getCurrentData(),relevantEvents=getRelevantEvents(eventStore,instance.instanceId);relevantEvents=applyMutationToEventStore(relevantEvents,{"":{display:"",startEditable:!0,durationEditable:!0,constraints:[],overlap:null,allows:[],color:"",contrastColor:"",className:""}},mutation,context);let oldEvent=new _EventImpl(context,def,instance);this._def=relevantEvents.defs[def.defId],this._instance=relevantEvents.instances[instance.instanceId],context.dispatch({type:"MERGE_EVENTS",eventStore:relevantEvents}),context.emitter.trigger("eventChange",{oldEvent,event:this,relatedEvents:buildEventApis(relevantEvents,context,instance),revert(){context.dispatch({type:"RESET_EVENTS",eventStore})}})}}remove(){let context=this._context,asStore=eventApiToStore(this);context.dispatch({type:"REMOVE_EVENTS",eventStore:asStore}),context.emitter.trigger("eventRemove",{event:this,relatedEvents:[],revert(){context.dispatch({type:"MERGE_EVENTS",eventStore:asStore})}})}get source(){let{sourceId}=this._def;return sourceId?new EventSourceImpl(this._context,this._context.getCurrentData().eventSources[sourceId]):null}get start(){let instance=this._instance;return instance?buildRangeEdgeOutput(instance.range.start,instance.range.instantStartMs,this._context.dateEnv,this._def.allDay).date:null}get end(){let instance=this._instance;return instance&&this._def.hasEnd?buildRangeEdgeOutput(instance.range.end,instance.range.instantEndMs,this._context.dateEnv,this._def.allDay).date:null}get startStr(){let instance=this._instance;return instance?buildRangeEdgeOutput(instance.range.start,instance.range.instantStartMs,this._context.dateEnv,this._def.allDay).dateStr:""}get endStr(){let instance=this._instance;return instance&&this._def.hasEnd?buildRangeEdgeOutput(instance.range.end,instance.range.instantEndMs,this._context.dateEnv,this._def.allDay).dateStr:""}get id(){return this._def.publicId}get groupId(){return this._def.groupId}get allDay(){return this._def.allDay}get title(){return this._def.title}get url(){return this._def.url}get display(){return this._def.ui.display||"auto"}get startEditable(){return this._def.ui.startEditable}get durationEditable(){return this._def.ui.durationEditable}get constraint(){return this._def.ui.constraints[0]||null}get overlap(){return this._def.ui.overlap}get allow(){return this._def.ui.allows[0]||null}get color(){return this._def.ui.color}get contrastColor(){return this._def.ui.contrastColor}get className(){return this._def.ui.className}get extendedProps(){return this._def.extendedProps}toPlainObject(settings={}){let def=this._def,{ui}=def,{startStr,endStr}=this,res={allDay:def.allDay};return def.title&&(res.title=def.title),startStr&&(res.start=startStr),endStr&&(res.end=endStr),def.publicId&&(res.id=def.publicId),def.groupId&&(res.groupId=def.groupId),def.url&&(res.url=def.url),ui.display&&ui.display!=="auto"&&(res.display=ui.display),ui.color&&(res.color=ui.color),ui.contrastColor&&(res.contrastColor=ui.contrastColor),ui.className&&(res.className=ui.className),Object.keys(def.extendedProps).length&&(settings.collapseExtendedProps?Object.assign(res,def.extendedProps):res.extendedProps=def.extendedProps),res}toJSON(){return this.toPlainObject()}};function computeInstantDeltaMs(meta,fromInstantMs,granularity){return meta.instantMs!=null&&!granularity?meta.instantMs-fromInstantMs:void 0}function eventApiToStore(eventApi){let def=eventApi._def,instance=eventApi._instance;return{defs:{[def.defId]:def},instances:instance?{[instance.instanceId]:instance}:{}}}function buildEventApis(eventStore,context,excludeInstance){let{defs,instances}=eventStore,eventApis=[],excludeInstanceId=excludeInstance?excludeInstance.instanceId:"";for(let id in instances){let instance=instances[id],def=defs[instance.defId];instance.instanceId!==excludeInstanceId&&eventApis.push(new EventImpl(context,def,instance))}return eventApis}function sliceEventStore(eventStore,eventUiBases,framingRange,nextDayThreshold){let inverseBgByGroupId={},inverseBgByDefId={},defByGroupId={},bgRanges=[],fgRanges=[],eventUis=compileEventUis(eventStore.defs,eventUiBases);for(let defId in eventStore.defs){let def=eventStore.defs[defId];eventUis[def.defId].display==="inverse-background"&&(def.groupId?(inverseBgByGroupId[def.groupId]=[],defByGroupId[def.groupId]||(defByGroupId[def.groupId]=def)):inverseBgByDefId[defId]=[])}for(let instanceId in eventStore.instances){let instance=eventStore.instances[instanceId],def=eventStore.defs[instance.defId],ui=eventUis[def.defId],origRange=instance.range,normalRange=!def.allDay&&nextDayThreshold?computeVisibleDayRange(origRange,nextDayThreshold):origRange,slicedRange=intersectRanges(normalRange,framingRange);slicedRange&&(ui.display==="inverse-background"?def.groupId?inverseBgByGroupId[def.groupId].push(slicedRange):inverseBgByDefId[instance.defId].push(slicedRange):ui.display!=="none"&&(ui.display==="background"?bgRanges:fgRanges).push({def,ui,instance,range:buildSlicedEventRange(origRange,normalRange,slicedRange),isStart:normalRange.start&&normalRange.start.valueOf()===slicedRange.start.valueOf(),isEnd:normalRange.end&&normalRange.end.valueOf()===slicedRange.end.valueOf()}))}for(let groupId in inverseBgByGroupId){let ranges=inverseBgByGroupId[groupId],invertedRanges=invertRanges(ranges,framingRange);for(let invertedRange of invertedRanges){let def=defByGroupId[groupId],ui=eventUis[def.defId];bgRanges.push({def,ui,instance:null,range:invertedRange,isStart:!1,isEnd:!1})}}for(let defId in inverseBgByDefId){let ranges=inverseBgByDefId[defId],invertedRanges=invertRanges(ranges,framingRange);for(let invertedRange of invertedRanges)bgRanges.push({def:eventStore.defs[defId],ui:eventUis[defId],instance:null,range:invertedRange,isStart:!1,isEnd:!1})}return{bg:bgRanges,fg:fgRanges}}function buildSlicedEventRange(origRange,normalRange,slicedRange){return normalRange!==origRange?slicedRange:buildEventInstanceRange(slicedRange.start,slicedRange.end,slicedRange.start.valueOf()===origRange.start.valueOf()?origRange.instantStartMs:void 0,slicedRange.end.valueOf()===origRange.end.valueOf()?origRange.instantEndMs:void 0)}function hasBgRendering(def){return def.ui.display==="background"||def.ui.display==="inverse-background"}function setElEventRange(el,eventRange){el.fcEventRange=eventRange}function getElEventRange(el){return el.fcEventRange||el.parentNode.fcEventRange||null}function compileEventUis(eventDefs,eventUiBases){return mapHash(eventDefs,eventDef=>compileEventUi(eventDef,eventUiBases))}function compileEventUi(eventDef,eventUiBases){let uis=[],fallbackBase=eventUiBases[""],defBase=eventUiBases[eventDef.defId];return fallbackBase&&uis.push(fallbackBase),defBase&&uis.push(defBase),uis.push(eventDef.ui),combineEventUis(uis)}function sortEventSegs(segs,eventOrderSpecs){let objs=segs.map(buildSegCompareObj);return objs.sort((obj0,obj1)=>compareByFieldSpecs(obj0,obj1,eventOrderSpecs)),objs.map(c=>c._seg)}function buildSegCompareObj(seg){let{eventRange}=seg,eventDef=eventRange.def,range=eventRange.instance?eventRange.instance.range:eventRange.range,start=range.start?range.start.valueOf():0,end=range.end?range.end.valueOf():0;return{...eventDef.extendedProps,...eventDef,id:eventDef.publicId,start,end,duration:end-start,allDay:Number(eventDef.allDay),_seg:seg}}function computeEventRangeDraggable(eventRange,context){let{pluginHooks}=context,transformers=pluginHooks.isDraggableTransformers,{def,ui}=eventRange,val=ui.startEditable;for(let transformer of transformers)val=transformer(val,def,ui,context);return val}function buildEventRangeTimeText(timeFormat,eventRange,slicedStart,slicedEnd,isStart,isEnd,context,defaultDisplayEventTime=!0,defaultDisplayEventEnd=!0){let{dateEnv,options}=context,{def}=eventRange,{range}=eventRange.instance,canonicalStart=buildRangeEdgeOutput(range.start,range.instantStartMs,dateEnv),canonicalEnd=buildRangeEdgeOutput(range.end,range.instantEndMs,dateEnv),{displayEventTime,displayEventEnd}=options;displayEventTime==null&&(displayEventTime=defaultDisplayEventTime!==!1),displayEventEnd==null&&(displayEventEnd=defaultDisplayEventEnd!==!1);let startDate=!isStart&&slicedStart&&startOfDay5(slicedStart).valueOf()!==startOfDay5(canonicalStart.marker).valueOf()?slicedStart:canonicalStart.marker,endDate=!isEnd&&slicedEnd&&startOfDay5(addMs(slicedEnd,-1)).valueOf()!==startOfDay5(addMs(canonicalEnd.marker,-1)).valueOf()?slicedEnd:canonicalEnd.marker,startInstantMs=startDate===canonicalStart.marker?canonicalStart.date.valueOf():void 0,endInstantMs=endDate===canonicalEnd.marker?canonicalEnd.date.valueOf():void 0;if(displayEventTime&&!def.allDay){if(displayEventEnd&&(isStart||isEnd)&&def.hasEnd){let rangeParts=dateEnv.formatRangeToParts(startDate,endDate,timeFormat,{startInstantMs,endInstantMs}),multiDaySeparator=detectMultiDayTimes(rangeParts);return multiDaySeparator!=null?joinDateTimeFormatParts(dateEnv.formatToParts(startDate,timeFormat,{instantMs:startInstantMs}))+multiDaySeparator+joinDateTimeFormatParts(dateEnv.formatToParts(endDate,timeFormat,{instantMs:endInstantMs})):joinDateTimeFormatParts(rangeParts)}if(isStart)return joinDateTimeFormatParts(dateEnv.formatToParts(startDate,timeFormat,{instantMs:startInstantMs}))}return""}var dateUnits=new Set(["year","month","day"]);function detectMultiDayTimes(parts){let sharedPart,hasDatePart=!1;for(let part of parts)part.source==="shared"&&(sharedPart=part),dateUnits.has(part.type)&&(hasDatePart=!0);return hasDatePart?sharedPart.value:void 0}function getEventRangeMeta(eventRange,todayRange,nowDate,nowMs){let segRange=eventRange.range;return{isPast:segRange.instantEndMs!=null&&nowMs!=null?segRange.instantEndMs<=nowMs:segRange.end<=(nowDate||todayRange.start),isFuture:segRange.instantStartMs!=null&&nowMs!=null?segRange.instantStartMs>=nowMs:segRange.start>=(nowDate||todayRange.end),isToday:todayRange&&rangeContainsMarker(todayRange,segRange.start)}}function buildEventRangeKey(eventRange){return eventRange.instance?eventRange.instance.instanceId:`${eventRange.def.defId}:${eventRange.range.start.toISOString()}`}function getEventTagAndAttrs(eventRange,context){let{def,instance}=eventRange,{url}=def;if(url)return["a",{href:url},!0];let{emitter,options}=context,{eventInteractive}=options;eventInteractive==null&&(eventInteractive=def.interactive,eventInteractive==null&&(eventInteractive=!!emitter.hasHandlers("eventClick")));let attrs;return eventInteractive&&(attrs=createAriaKeyboardAttrs(ev=>{emitter.trigger("eventClick",{el:ev.target,event:new EventImpl(context,def,instance),jsEvent:ev,view:context.viewApi})}),attrs={role:"button",...attrs}),["div",attrs,eventInteractive]}var classNamesRe=/(^c|C)lass(Name)?$/,contentRe=/Content$/,lifecycleRe=/(DidMount|WillUnmount)$/,handlerRe=/^on[A-Z]/,customMergeFuncs={buttons:mergeMaybePropsDepth1};function mergeViewOptionsMap(...hashes){let merged={};for(let hash of hashes)for(let viewName in hash){let viewOptions=hash[viewName];merged[viewName]?merged[viewName]=mergeCalendarOptions(merged[viewName],viewOptions):merged[viewName]=viewOptions}return merged}function mergeCalendarOptions(...optionSets){let dest={};for(let options of optionSets)for(let name in options)if(name in dest){let mergeFunc=customMergeFuncs[name]||(classNamesRe.test(name)?joinFuncishClassNames:contentRe.test(name)?mergeContentInjectors:lifecycleRe.test(name)?mergeLifecycleCallbacks:void 0);dest[name]=mergeFunc?mergeFunc(dest[name],options[name],name):options[name]}else dest[name]=options[name];return dest}function joinFuncishClassNames(input0,input1,optionName){let isFunc0=typeof input0=="function",isFunc1=typeof input1=="function";if(isFunc0||isFunc1){let combinedFunc=info=>joinClassNames(refineClassName(isFunc0?input0(info):input0,optionName),refineClassName(isFunc1?input1(info):input1,optionName));return combinedFunc.parts=[input0,input1],combinedFunc}return joinClassNames(refineClassName(input0,optionName),refineClassName(input1,optionName))}function mergeContentInjectors(contentGenerator0,contentGenerator1){if(typeof contentGenerator1=="function"){let combinedFunc=renderProps=>{let res=contentGenerator1(renderProps);return res===!0?typeof contentGenerator0=="function"?contentGenerator0(renderProps):contentGenerator0:res};return combinedFunc.parts=[contentGenerator0,contentGenerator1],combinedFunc}return contentGenerator1??contentGenerator0}function mergeLifecycleCallbacks(fn0,fn1){if(fn0&&fn1){let combinedFunc=(...args)=>{fn0(...args),fn1(...args)};return combinedFunc.parts=[fn0,fn1],combinedFunc}return fn0||fn1}function isNonHandlerPropsEqual(obj0,obj1){let keys=getUnequalProps(obj0,obj1);for(let key of keys)if(!handlerRe.test(key))return!1;return!0}function isMergedPropsEqual(val0,val1){let parts0=val0&&val0.parts,parts1=val1&&val1.parts;if(parts0&&parts1){let count0=parts0.length,count1=parts1.length;if(count0!==count1)return!1;for(let i=0;i<count0;i++)if(!(parts0[i]===parts1[i]||isMergedPropsEqual(parts0[i],parts1[i])))return!1;return!0}return!1}var globalLocales=[],MINIMAL_RAW_EN_LOCALE={code:"en",week:{dow:0,doy:4},direction:"ltr",todayText:"Today",prevText:"Prev",nextText:"Next",prevYearText:"Prev year",nextYearText:"Next year",yearText:"Year",monthText:"Month",weekTextLong:"Week",dayText:"Day",listText:"List",closeHint:"Close",eventsHint:"Events",allDayText:"All-day",timedText:"Timed",moreLinkText:"more",noEventsText:"No events to display"},RAW_EN_LOCALE={...MINIMAL_RAW_EN_LOCALE,weekTextShort:"W",todayHint:(unitText,unit)=>unit==="day"?"Today":`This ${unitText}`,prevHint:"Previous $0",nextHint:"Next $0",viewHint:"$0 view",viewChangeHint:"Change view",navLinkHint:"Go to $0",moreLinkHint(eventCnt){return`Show ${eventCnt} more event${eventCnt===1?"":"s"}`}};function organizeRawLocales(explicitRawLocales){let defaultCode=explicitRawLocales.length>0?explicitRawLocales[0].code:"en",allRawLocales=globalLocales.concat(explicitRawLocales),rawLocaleMap={en:RAW_EN_LOCALE};for(let rawLocale of allRawLocales)rawLocaleMap[rawLocale.code]=rawLocale;return{map:rawLocaleMap,defaultCode}}function buildLocale(inputSingular,available){return typeof inputSingular=="object"&&!Array.isArray(inputSingular)?parseLocale(inputSingular.code,[inputSingular.code],inputSingular):queryLocale(inputSingular,available)}function queryLocale(codeArg,available){let codes=[].concat(codeArg||[]),raw=queryRawLocale(codes,available)||RAW_EN_LOCALE;return parseLocale(codeArg,codes,raw)}function queryRawLocale(codes,available){for(let i=0;i<codes.length;i+=1){let parts=codes[i].toLocaleLowerCase().split("-");for(let j=parts.length;j>0;j-=1){let simpleId=parts.slice(0,j).join("-");if(available[simpleId])return available[simpleId]}}return null}function parseLocale(codeArg,codes,raw){let merged=mergeCalendarOptions(MINIMAL_RAW_EN_LOCALE,raw);delete merged.code;let{week}=merged;return delete merged.week,{codeArg,codes,week,simpleNumberFormat:new Intl.NumberFormat(codeArg),options:merged}}var JsonRequestError=class extends Error{constructor(message,response){super(message),this.response=response}};function requestJson(method,url,params){method=method.toUpperCase();let fetchOptions={method};return method==="GET"?url+=(url.indexOf("?")===-1?"?":"&")+new URLSearchParams(params):(fetchOptions.body=new URLSearchParams(params),fetchOptions.headers={"Content-Type":"application/x-www-form-urlencoded"}),fetch(url,fetchOptions).then(fetchRes=>{if(fetchRes.ok)return fetchRes.json().then(parsedResponse=>[parsedResponse,fetchRes],()=>{throw new JsonRequestError("Failure parsing JSON",fetchRes)});throw new JsonRequestError("Request failed",fetchRes)})}function handleDateProfile(dateProfile,context){context.emitter.trigger("datesSet",{...buildRangeApiWithTimeZone(dateProfile.activeRange,context.dateEnv),view:context.viewApi})}function handleEventStore(eventStore,context){let{emitter}=context;emitter.hasHandlers("eventsSet")&&emitter.trigger("eventsSet",buildEventApis(eventStore,context))}var eventSourceDef$2={ignoreRange:!0,parseMeta(refined){return Array.isArray(refined.events)?refined.events:null},fetch(arg,successCallback){successCallback({rawEvents:arg.eventSource.meta})}},arrayEventSourcePlugin={name:"array-event-source",eventSourceDefs:[eventSourceDef$2]};function unpromisify(func,normalizedSuccessCallback,normalizedFailureCallback){let isResolved=!1,wrappedSuccess=function(res2){isResolved||(isResolved=!0,normalizedSuccessCallback(res2))},wrappedFailure=function(error){isResolved||(isResolved=!0,normalizedFailureCallback(error))},res=func(wrappedSuccess,wrappedFailure);res&&typeof res.then=="function"&&res.then(wrappedSuccess,wrappedFailure)}var eventSourceDef$1={parseMeta(refined){return typeof refined.events=="function"?refined.events:null},fetch(arg,successCallback,errorCallback){let{dateEnv}=arg.context,func=arg.eventSource.meta;unpromisify(func.bind(null,buildRangeApiWithTimeZone(arg.range,dateEnv)),rawEvents=>successCallback({rawEvents}),errorCallback)}},funcEventSourcePlugin={name:"func-event-source",eventSourceDefs:[eventSourceDef$1]},JSON_FEED_EVENT_SOURCE_REFINERS={method:String,extraParams:identity,startParam:String,endParam:String,timeZoneParam:String},eventSourceDef={parseMeta(refined){return refined.url&&(refined.format==="json"||!refined.format)?{url:refined.url,format:"json",method:(refined.method||"GET").toUpperCase(),extraParams:refined.extraParams,startParam:refined.startParam,endParam:refined.endParam,timeZoneParam:refined.timeZoneParam}:null},fetch(arg,successCallback,errorCallback){let{meta}=arg.eventSource,requestParams=buildRequestParams(meta,arg.range,arg.context);requestJson(meta.method,meta.url,requestParams).then(([rawEvents,response])=>{successCallback({rawEvents,response})},errorCallback)}},jsonFeedEventSourcePlugin={name:"json-event-source",eventSourceRefiners:JSON_FEED_EVENT_SOURCE_REFINERS,eventSourceDefs:[eventSourceDef]};function buildRequestParams(meta,range,context){let{dateEnv,options}=context,startParam,endParam,timeZoneParam,customRequestParams,params={};return startParam=meta.startParam,startParam==null&&(startParam=options.startParam),endParam=meta.endParam,endParam==null&&(endParam=options.endParam),timeZoneParam=meta.timeZoneParam,timeZoneParam==null&&(timeZoneParam=options.timeZoneParam),typeof meta.extraParams=="function"?customRequestParams=meta.extraParams():customRequestParams=meta.extraParams||{},Object.assign(params,customRequestParams),params[startParam]=dateEnv.formatIso(range.start),params[endParam]=dateEnv.formatIso(range.end),dateEnv.timeZone!=="local"&&(params[timeZoneParam]=dateEnv.timeZone),params}var changeHandlerPlugin={name:"change-handler",optionChangeHandlers:{controller(controller,context){controller._setApi(context.calendarApi)},events(events,context){handleEventSources([events],context)},eventSources:handleEventSources}};function handleEventSources(inputs,context){let unfoundSources=hashValuesToArray(context.getCurrentData().eventSources);if(unfoundSources.length===1&&inputs.length===1&&Array.isArray(unfoundSources[0]._raw)&&Array.isArray(inputs[0])){context.dispatch({type:"RESET_RAW_EVENTS",sourceId:unfoundSources[0].sourceId,rawEvents:inputs[0]});return}let newInputs=[];for(let input of inputs){let inputFound=!1;for(let i=0;i<unfoundSources.length;i+=1)if(unfoundSources[i]._raw===input){unfoundSources.splice(i,1),inputFound=!0;break}inputFound||newInputs.push(input)}for(let unfoundSource of unfoundSources)context.dispatch({type:"REMOVE_EVENT_SOURCE",sourceId:unfoundSource.sourceId});for(let newInput of newInputs)context.calendarApi.addEventSource(newInput)}var EVENT_SOURCE_REFINERS={id:String,defaultAllDay:Boolean,url:String,format:String,events:identity,eventDataTransform:identity,success:identity,failure:identity};function parseEventSource(raw,context,refiners=buildEventSourceRefiners(context)){let rawObj;if(typeof raw=="string"?rawObj={url:raw}:typeof raw=="function"||Array.isArray(raw)?rawObj={events:raw}:typeof raw=="object"&&raw&&(rawObj=raw),rawObj){let{refined,extra}=refineProps(rawObj,refiners),metaRes=buildEventSourceMeta(refined,context);if(metaRes)return{_raw:raw,isFetching:!1,latestFetchId:"",fetchRange:null,defaultAllDay:refined.defaultAllDay,eventDataTransform:refined.eventDataTransform,success:refined.success,failure:refined.failure,publicId:refined.id||"",sourceId:guid(),sourceDefId:metaRes.sourceDefId,meta:metaRes.meta,ui:createEventUi(refined,context),extendedProps:extra}}return null}function buildEventSourceRefiners(context){return{...EVENT_UI_REFINERS,...EVENT_SOURCE_REFINERS,...context.pluginHooks.eventSourceRefiners}}function buildEventSourceMeta(raw,context){let defs=context.pluginHooks.eventSourceDefs;for(let i=defs.length-1;i>=0;i-=1){let meta=defs[i].parseMeta(raw);if(meta)return{sourceDefId:i,meta}}return null}function initEventSources(calendarOptions,dateProfile,context){let activeRange=dateProfile?dateProfile.activeRange:null;return addSources({},parseInitialSources(calendarOptions,context),activeRange,context)}function reduceEventSources(eventSources,action,dateProfile,context){let activeRange=dateProfile?dateProfile.activeRange:null;switch(action.type){case"ADD_EVENT_SOURCES":return addSources(eventSources,action.sources,activeRange,context);case"REMOVE_EVENT_SOURCE":return removeSource(eventSources,action.sourceId);case"PREV":case"NEXT":case"CHANGE_DATE":case"CHANGE_VIEW_TYPE":return dateProfile?fetchDirtySources(eventSources,activeRange,context):eventSources;case"FETCH_EVENT_SOURCES":return fetchSourcesByIds(eventSources,action.sourceIds?arrayToHash(action.sourceIds):excludeStaticSources(eventSources,context),activeRange,action.isRefetch||!1,context);case"RECEIVE_EVENTS":case"RECEIVE_EVENT_ERROR":return receiveResponse(eventSources,action.sourceId,action.fetchId,action.fetchRange);case"REMOVE_ALL_EVENT_SOURCES":return{};default:return eventSources}}function reduceEventSourcesNewTimeZone(eventSources,dateProfile,context){let activeRange=dateProfile?dateProfile.activeRange:null;return fetchSourcesByIds(eventSources,excludeStaticSources(eventSources,context),activeRange,!0,context)}function computeEventSourcesLoading(eventSources){for(let sourceId in eventSources)if(eventSources[sourceId].isFetching)return!0;return!1}function addSources(eventSourceHash,sources,fetchRange,context){let hash={};for(let source of sources)hash[source.sourceId]=source;return fetchRange&&(hash=fetchDirtySources(hash,fetchRange,context)),{...eventSourceHash,...hash}}function removeSource(eventSourceHash,sourceId){return filterHash(eventSourceHash,eventSource=>eventSource.sourceId!==sourceId)}function fetchDirtySources(sourceHash,fetchRange,context){return fetchSourcesByIds(sourceHash,filterHash(sourceHash,eventSource=>isSourceDirty(eventSource,fetchRange,context)),fetchRange,!1,context)}function isSourceDirty(eventSource,fetchRange,context){return doesSourceNeedRange(eventSource,context)?!context.options.lazyFetching||!eventSource.fetchRange||eventSource.isFetching||fetchRange.start<eventSource.fetchRange.start||fetchRange.end>eventSource.fetchRange.end:!eventSource.latestFetchId}function fetchSourcesByIds(prevSources,sourceIdHash,fetchRange,isRefetch,context){let nextSources={};for(let sourceId in prevSources){let source=prevSources[sourceId];sourceIdHash[sourceId]?nextSources[sourceId]=fetchSource(source,fetchRange,isRefetch,context):nextSources[sourceId]=source}return nextSources}function fetchSource(eventSource,fetchRange,isRefetch,context){let{options,calendarApi}=context,sourceDef=context.pluginHooks.eventSourceDefs[eventSource.sourceDefId],fetchId=guid();return sourceDef.fetch({eventSource,range:fetchRange,isRefetch,context},res=>{let{rawEvents}=res;options.eventSourceSuccess&&(rawEvents=options.eventSourceSuccess.call(calendarApi,rawEvents,res.response)||rawEvents),eventSource.success&&(rawEvents=eventSource.success.call(calendarApi,rawEvents,res.response)||rawEvents),context.dispatch({type:"RECEIVE_EVENTS",sourceId:eventSource.sourceId,fetchId,fetchRange,rawEvents})},error=>{let errorHandled=!1;options.eventSourceFailure&&(options.eventSourceFailure.call(calendarApi,error),errorHandled=!0),eventSource.failure&&(eventSource.failure(error),errorHandled=!0),errorHandled||warn(`Unhandled event source error: ${error.message}`,error),context.dispatch({type:"RECEIVE_EVENT_ERROR",sourceId:eventSource.sourceId,fetchId,fetchRange,error})}),{...eventSource,isFetching:!0,latestFetchId:fetchId}}function receiveResponse(sourceHash,sourceId,fetchId,fetchRange){let eventSource=sourceHash[sourceId];return eventSource&&fetchId===eventSource.latestFetchId?{...sourceHash,[sourceId]:{...eventSource,isFetching:!1,fetchRange}}:sourceHash}function excludeStaticSources(eventSources,context){return filterHash(eventSources,eventSource=>doesSourceNeedRange(eventSource,context))}function parseInitialSources(rawOptions,context){let refiners=buildEventSourceRefiners(context),rawSources=[].concat(rawOptions.eventSources||[]),sources=[];rawOptions.initialEvents&&rawSources.unshift(rawOptions.initialEvents),rawOptions.events&&rawSources.unshift(rawOptions.events);for(let rawSource of rawSources){let source=parseEventSource(rawSource,context,refiners);source&&sources.push(source)}return sources}function doesSourceNeedRange(eventSource,context){return!context.pluginHooks.eventSourceDefs[eventSource.sourceDefId].ignoreRange}var SIMPLE_RECURRING_REFINERS={daysOfWeek:identity,startTime:createDuration,endTime:createDuration,duration:createDuration,startRecur:identity,endRecur:identity},recurring={parse(refined,dateEnv){if(refined.daysOfWeek||refined.startTime||refined.endTime||refined.startRecur||refined.endRecur){let recurringData={daysOfWeek:refined.daysOfWeek||null,startTime:refined.startTime||null,endTime:refined.endTime||null,startRecur:refined.startRecur?dateEnv.createMarker(refined.startRecur):null,endRecur:refined.endRecur?dateEnv.createMarker(refined.endRecur):null,dateEnv},duration;return refined.duration&&(duration=refined.duration),!duration&&refined.startTime&&refined.endTime&&(duration=subtractDurations(refined.endTime,refined.startTime)),{allDayGuess:!refined.startTime&&!refined.endTime,duration,typeData:recurringData}}return null},expand(typeData,framingRange,dateEnv){let clippedFramingRange=intersectRanges(framingRange,{start:typeData.startRecur,end:typeData.endRecur});return clippedFramingRange?expandRanges(typeData.daysOfWeek,typeData.startTime,typeData.dateEnv,dateEnv,clippedFramingRange):[]}},simpleRecurringEventsPlugin={name:"simple-recurring-event",recurringTypes:[recurring],eventRefiners:SIMPLE_RECURRING_REFINERS};function expandRanges(daysOfWeek,startTime,eventDateEnv,calendarDateEnv,framingRange){let dowHash=daysOfWeek?arrayToHash(daysOfWeek):null,dayMarker=startOfDay5(framingRange.start),endMarker=framingRange.end,instanceStarts=[];for(startTime&&(startTime.milliseconds<0?endMarker=addDays4(endMarker,1):startTime.milliseconds>=1e3*60*60*24&&(dayMarker=addDays4(dayMarker,-1)));dayMarker<endMarker;){let instanceStart;(!dowHash||dowHash[dayMarker.getUTCDay()])&&(startTime?instanceStart=calendarDateEnv.add(dayMarker,startTime):instanceStart=dayMarker,instanceStarts.push(calendarDateEnv.createMarker(eventDateEnv.toDate(instanceStart)))),dayMarker=addDays4(dayMarker,1)}return instanceStarts}var globalPlugins=[arrayEventSourcePlugin,funcEventSourcePlugin,jsonFeedEventSourcePlugin,simpleRecurringEventsPlugin,changeHandlerPlugin,{name:"misc",isLoadingFuncs:[state=>computeEventSourcesLoading(state.eventSources)],propSetHandlers:{dateProfile:handleDateProfile,eventStore:handleEventStore}}];var blankButtonState={text:"",hint:"",isDisabled:!1},CalendarController=class{constructor(handleDateChange){this.handleDateChange=handleDateChange}today(){this.calendarApi?.today()}prev(){this.calendarApi?.prev()}next(){this.calendarApi?.next()}prevYear(){this.calendarApi?.prevYear()}nextYear(){this.calendarApi?.nextYear()}gotoDate(zonedDateInput){this.calendarApi?.gotoDate(zonedDateInput)}incrementDate(duration){this.calendarApi?.incrementDate(duration)}changeView(viewType){this.calendarApi?.changeView(viewType)}get view(){return this.calendarApi?.view}getDate(){return this.calendarApi?.getDate()}getButtonState(){let{calendarApi}=this;return calendarApi&&calendarApi.getButtonState()||{today:blankButtonState,prev:blankButtonState,next:blankButtonState,prevYear:blankButtonState,nextYear:blankButtonState}}_setApi(calendarApi){this.calendarApi!==calendarApi&&(this.calendarApi&&(this.calendarApi.off("datesSet",this.handleDateChange),this.calendarApi=void 0),calendarApi&&(this.calendarApi=calendarApi,calendarApi.on("datesSet",this.handleDateChange)))}};import{useCallback as useCallback6,useState as useState5}from"react";import{jsx as jsx9}from"react/jsx-runtime";import React,{forwardRef as forwardRef2,useState as useState4,useEffect as useEffect3,useImperativeHandle}from"react";import{flushSync as flushSync2}from"react-dom";import{createContext,Component,isValidElement,createElement as createElement2}from"react";import{flushSync}from"react-dom";function memoize2(workerFunc,resEquality,teardownFunc){let currentArgs,currentRes;return function(...newArgs){if(!currentArgs)currentRes=workerFunc.apply(this,newArgs);else if(!isArraysEqual(currentArgs,newArgs)){teardownFunc&&teardownFunc(currentRes);let res=workerFunc.apply(this,newArgs);(!resEquality||!resEquality(res,currentRes))&&(currentRes=res)}return currentArgs=newArgs,currentRes}}function memoizeObjArg(workerFunc,resEquality,teardownFunc){let currentArg,currentRes;return newArg=>{if(!currentArg)currentRes=workerFunc.call(this,newArg);else if(!isPropsEqualShallow(currentArg,newArg)){teardownFunc&&teardownFunc(currentRes);let res=workerFunc.call(this,newArg);(!resEquality||!resEquality(res,currentRes))&&(currentRes=res)}return currentArg=newArg,currentRes}}var ViewContextType=createContext({});function buildViewContext(viewSpec,viewApi,viewOptions,dateProfileGenerator,dateEnv,nowManager,pluginHooks,dispatch,getCurrentData,emitter,calendarApi,baseId,registerInteractiveComponent,unregisterInteractiveComponent){return{dateEnv,nowManager,options:viewOptions,pluginHooks,emitter,dispatch,getCurrentData,calendarApi,viewSpec,viewApi,dateProfileGenerator,baseId,registerInteractiveComponent,unregisterInteractiveComponent}}var PureComponent=class extends Component{shouldComponentUpdate(nextProps,nextState){return!isPropsEqualWithMap(this.props,nextProps,this.propEquality)||!isPropsEqualWithMap(this.state,nextState,this.stateEquality)}};PureComponent.addPropsEquality=addPropsEquality;PureComponent.addStateEquality=addStateEquality;PureComponent.contextType=ViewContextType;PureComponent.prototype.propEquality={};PureComponent.prototype.stateEquality={};var BaseComponent=class extends PureComponent{};BaseComponent.contextType=ViewContextType;function addPropsEquality(propEquality){let hash=Object.create(this.prototype.propEquality);Object.assign(hash,propEquality),this.prototype.propEquality=hash}function addStateEquality(stateEquality){let hash=Object.create(this.prototype.stateEquality);Object.assign(hash,stateEquality),this.prototype.stateEquality=hash}function setRef(ref,current){typeof ref=="function"?ref(current):ref&&(ref.current=current)}var ContentInjector=class extends BaseComponent{constructor(){super(...arguments),this.id=guid(),this.queuedDomNodes=[],this.currentDomNodes=[],this.handleEl=el=>{this.el=el,this.props.elRef&&setRef(this.props.elRef,el)}}render(){let{props,context}=this,{options}=context,{customGenerator,defaultGenerator,renderProps}=props,attrs=buildElAttrs(props,"",this.handleEl),useDefault=!1,innerContent,queuedDomNodes=[],currentGeneratorMeta;if(customGenerator!=null){let customGeneratorRes=typeof customGenerator=="function"?customGenerator(renderProps):customGenerator;if(customGeneratorRes===!0)useDefault=!0;else{let isObject=customGeneratorRes&&typeof customGeneratorRes=="object";isObject&&"html"in customGeneratorRes?attrs.dangerouslySetInnerHTML={__html:customGeneratorRes.html}:isObject&&"domNodes"in customGeneratorRes?queuedDomNodes=Array.prototype.slice.call(customGeneratorRes.domNodes):(isObject?isValidElement(customGeneratorRes):typeof customGeneratorRes!="function")?innerContent=customGeneratorRes:currentGeneratorMeta=customGeneratorRes}}else useDefault=!hasCustomRenderingHandler(props.generatorName,options);return useDefault&&defaultGenerator&&(innerContent=defaultGenerator(renderProps)),this.queuedDomNodes=queuedDomNodes,this.currentGeneratorMeta=currentGeneratorMeta,createElement2(props.tag,attrs,innerContent)}componentDidMount(){this.applyQueueudDomNodes(),this.triggerCustomRendering(!0)}componentDidUpdate(){this.applyQueueudDomNodes(),this.triggerCustomRendering(!0)}componentWillUnmount(){this.triggerCustomRendering(!1)}triggerCustomRendering(isActive){let{props,context}=this,{handleCustomRendering,customRenderingMetaMap}=context.options;if(handleCustomRendering){let generatorMeta=this.currentGeneratorMeta??customRenderingMetaMap?.[props.generatorName];generatorMeta&&handleCustomRendering({id:this.id,isActive,containerEl:this.el,generatorMeta,renderProps:props.renderProps})}}applyQueueudDomNodes(){let{queuedDomNodes,currentDomNodes}=this,{el}=this;if(!isArraysEqual(queuedDomNodes,currentDomNodes)){for(let domNode of currentDomNodes)domNode.remove();for(let newNode of queuedDomNodes)el.appendChild(newNode);this.currentDomNodes=queuedDomNodes}}};ContentInjector.addPropsEquality({renderProps:isPropsEqualShallow,attrs:isNonHandlerPropsEqual,style:isPropsEqualShallow});function hasCustomRenderingHandler(generatorName,options){return!!(options.handleCustomRendering&&generatorName&&options.customRenderingMetaMap?.[generatorName])}function buildElAttrs(props,className,elRef){let attrs={...props.attrs,ref:elRef};return(props.className||className)&&(attrs.className=joinClassNames(className,props.className,attrs.className)),props.style&&(attrs.style=props.style),attrs}var RenderId=createContext(0),ContentContainer=class extends Component{constructor(){super(...arguments),this.InnerContent=InnerContentInjector.bind(void 0,this),this.handleEl=el=>{this.el=el,this.props.elRef&&(setRef(this.props.elRef,el),el&&this.didMountMisfire&&this.componentDidMount())}}render(){let{props}=this,generatedClassName=generateClassName(props.classNameGenerator,props.renderProps);if(props.children){let attrs=buildElAttrs(props,generatedClassName,this.handleEl),children=props.children(this.InnerContent,props.renderProps,attrs);return props.tag?createElement2(props.tag,attrs,children):children}else return createElement2(ContentInjector,{...props,elRef:this.handleEl,tag:props.tag||"div",className:joinClassNames(props.className,generatedClassName),renderId:this.context})}componentDidMount(){this.el?this.props.didMount?.({...this.props.renderProps,el:this.el}):this.didMountMisfire=!0}componentWillUnmount(){this.props.willUnmount?.({...this.props.renderProps,el:this.el})}};ContentContainer.contextType=RenderId;function InnerContentInjector(containerComponent,props){let parentProps=containerComponent.props;return createElement2(ContentInjector,{renderProps:parentProps.renderProps,generatorName:parentProps.generatorName,customGenerator:parentProps.customGenerator,defaultGenerator:parentProps.defaultGenerator,renderId:containerComponent.context,...props})}function generateClassName(classNameGenerator,renderProps){return(typeof classNameGenerator=="function"?classNameGenerator(renderProps):classNameGenerator)||""}function renderText(renderProps){return renderProps.text}function getIsHeightAuto(options){return options.height==="auto"||options.contentHeight==="auto"}function getTableHeaderSticky(options){let{tableHeaderSticky}=options;return(tableHeaderSticky==null||tableHeaderSticky==="auto")&&(tableHeaderSticky=getIsHeightAuto(options)),tableHeaderSticky}function getFooterScrollbarSticky(options){let isHeightAuto=getIsHeightAuto(options),{footerScrollbarSticky}=options;return(footerScrollbarSticky==null||footerScrollbarSticky==="auto")&&(footerScrollbarSticky=isHeightAuto),!!footerScrollbarSticky&&isHeightAuto}function getScrollerSyncerClass(pluginHooks){let ScrollerSyncer=pluginHooks.scrollerSyncerClass;if(!ScrollerSyncer)throw new RangeError("Must import @fullcalendar/scrollgrid");return ScrollerSyncer}var NowTimerRunner=class{constructor(handleChange){this.handleChange=handleChange,this.isMounted=!1,this.handleRefresh=()=>{let timing=this.computeTiming();(timing.nowDate.valueOf()!==this.nowDate.valueOf()||timing.nowMs!==this.nowMs)&&(this.nowDate=timing.nowDate,this.nowMs=timing.nowMs,this.todayRange=timing.todayRange,this.handleChange()),this.clearTimeout(),this.setTimeout(timing.waitMs)},this.handleVisibilityChange=()=>{document.hidden||this.handleRefresh()}}update(input){if(this.isMounted){if(input.unit!==this.unit||input.unitValue!==this.unitValue||input.nowIndicatorSnap!==this.nowIndicatorSnap||input.nowManager!==this.nowManager||input.dateEnv!==this.dateEnv){this.unit=input.unit,this.unitValue=input.unitValue,this.nowIndicatorSnap=input.nowIndicatorSnap,this.nowManager=input.nowManager,this.dateEnv=input.dateEnv;let timing=this.computeTiming();this.nowDate=timing.nowDate,this.nowMs=timing.nowMs,this.todayRange=timing.todayRange,this.clearTimeout(),this.setTimeout(timing.waitMs)}}else{this.isMounted=!0,this.unit=input.unit,this.unitValue=input.unitValue,this.nowIndicatorSnap=input.nowIndicatorSnap,this.nowManager=input.nowManager,this.dateEnv=input.dateEnv;let timing=this.computeTiming();this.nowDate=timing.nowDate,this.nowMs=timing.nowMs,this.todayRange=timing.todayRange,this.setTimeout(timing.waitMs),this.nowManager.addResetListener(this.handleRefresh),typeof document<"u"&&document.addEventListener("visibilitychange",this.handleVisibilityChange)}return{nowDate:this.nowDate,nowMs:this.nowMs,todayRange:this.todayRange}}destroy(){this.isMounted&&(this.isMounted=!1,this.clearTimeout(),this.nowManager.removeResetListener(this.handleRefresh),typeof document<"u"&&document.removeEventListener("visibilitychange",this.handleVisibilityChange))}computeTiming(){let{unit,unitValue,nowIndicatorSnap,dateEnv}=this,unroundedNowMs=this.nowManager.getEpochMs(),unroundedNow=dateEnv.timestampToMarker(unroundedNowMs);nowIndicatorSnap==="auto"&&(nowIndicatorSnap=/year|month|week|day/.test(unit)||(unitValue||1)===1);let nowDate,nowMs,waitMs;if(nowIndicatorSnap){nowDate=dateEnv.startOf(unroundedNow,unit),nowMs=resolveSnappedInstant(nowDate,unroundedNowMs,dateEnv);let nextUnitStart=dateEnv.add(nowDate,createDuration(1,unit));waitMs=resolveNextSnappedInstant(nextUnitStart,unroundedNowMs,dateEnv)-unroundedNowMs}else nowDate=unroundedNow,nowMs=unroundedNowMs,waitMs=1e3*60;return waitMs=Math.min(1e3*60*60*24,waitMs),{nowDate,nowMs,todayRange:buildDayRange(nowDate),waitMs}}setTimeout(waitMs=this.computeTiming().waitMs){this.timeoutId=setTimeout(()=>{let timing=this.computeTiming();this.nowDate=timing.nowDate,this.nowMs=timing.nowMs,this.todayRange=timing.todayRange,this.handleChange(),this.setTimeout(timing.waitMs)},waitMs)}clearTimeout(){this.timeoutId&&clearTimeout(this.timeoutId)}};function resolveSnappedInstant(snappedMarker,rawMs,dateEnv){let offsetMs=dateEnv.timestampToMarker(rawMs).valueOf()-rawMs,candidateMs=snappedMarker.valueOf()-offsetMs;return dateEnv.timestampToMarker(candidateMs).valueOf()===snappedMarker.valueOf()?candidateMs:dateEnv.toDate(snappedMarker).valueOf()}function resolveNextSnappedInstant(nextUnitStart,rawMs,dateEnv){let nextSnappedMs=resolveSnappedInstant(nextUnitStart,rawMs,dateEnv),transitionMs=findNextOffsetTransitionMs(rawMs,dateEnv,Math.min(nextSnappedMs-rawMs,2880*60*1e3));return transitionMs!=null?Math.min(nextSnappedMs,transitionMs):nextSnappedMs}function findNextOffsetTransitionMs(rawMs,dateEnv,horizonMs){if(horizonMs<=0)return;let startOffsetMs=offsetAt(rawMs,dateEnv),lowerMs=rawMs,upperMs=rawMs+horizonMs;if(offsetAt(upperMs,dateEnv)!==startOffsetMs){for(;upperMs-lowerMs>1;){let middleMs=Math.floor((lowerMs+upperMs)/2);offsetAt(middleMs,dateEnv)===startOffsetMs?lowerMs=middleMs:upperMs=middleMs}return upperMs>rawMs?upperMs:void 0}}function offsetAt(instantMs,dateEnv){return dateEnv.timestampToMarker(instantMs).valueOf()-instantMs}function buildDayRange(date){let start=startOfDay5(date),end=addDays4(start,1);return{start,end}}function isDimsEqual(v0,v1){return v0!=null&&(v0===v1||Math.abs(v0-v1)<.01)}var nativeBorderBoxEnabled=!0,configMap=new Map,afterSizeCallbacks=new Set,isHandling=!1,isStalling=!1,isAcquiringImmediately=!1;function afterSize(callback){afterSizeCallbacks.add(callback),!isHandling&&!isStalling&&(isStalling=!0,requestAnimationFrame(()=>{isStalling=!1,flushAfterSize()}))}function flushAfterSize(){for(let flushedCallback of afterSizeCallbacks.values())afterSizeCallbacks.delete(flushedCallback),flushedCallback()}function flushSyncWithSizeBatching(callback){let wasHandling=isHandling;isHandling=!0,isAcquiringImmediately=!0;try{flushSync(callback),wasHandling||flushSync(()=>{flushAfterSize(),isHandling=!1})}finally{isHandling=wasHandling,isAcquiringImmediately=!1}}var globalResizeObserver=typeof ResizeObserver<"u"&&new ResizeObserver(entries=>{isHandling=!0;for(let entry of entries){let el=entry.target,config2=configMap.get(el),width,height;if(entry.borderBoxSize&&nativeBorderBoxEnabled){let borderBoxSize=entry.borderBoxSize[0]||entry.borderBoxSize;width=borderBoxSize.inlineSize,height=borderBoxSize.blockSize}else({width,height}=el.getBoundingClientRect());let shouldFire=!1;isDimsEqual(config2.width,width)||(config2.width=width,shouldFire=config2.watchWidth),isDimsEqual(config2.height,height)||(config2.height=height,shouldFire||(shouldFire=config2.watchHeight)),shouldFire&&config2.callback(width,height)}flushSync(()=>{flushAfterSize(),isHandling=!1})});function watchSize(el,callback,watchWidth2=!0,watchHeight2=!0){let config2={callback,watchWidth:watchWidth2,watchHeight:watchHeight2};if(configMap.set(el,config2),isAcquiringImmediately){let{width,height}=el.getBoundingClientRect();config2.width=width,config2.height=height,callback(width,height)}return globalResizeObserver&&globalResizeObserver.observe(el,{box:"border-box"}),()=>{configMap.delete(el),globalResizeObserver&&globalResizeObserver.unobserve(el)}}function watchWidth(el,callback){return watchSize(el,callback,!0)}function watchHeight(el,callback){return watchSize(el,(_width,height)=>callback(height),!1,!0)}import{jsx as jsx8,jsxs as jsxs6,Fragment as Fragment4}from"react/jsx-runtime";var DateProfileGenerator=class{constructor(props){this.props=props,this.initHiddenDays()}buildPrev(currentDateProfile,currentDate,nowDate,forceToValid){let{dateEnv}=this.props,prevDate=dateEnv.subtract(dateEnv.startOf(currentDate,currentDateProfile.currentRangeUnit),currentDateProfile.dateIncrement);return this.build(prevDate,nowDate,-1,forceToValid)}buildNext(currentDateProfile,currentDate,nowDate,forceToValid){let{dateEnv}=this.props,nextDate=dateEnv.add(dateEnv.startOf(currentDate,currentDateProfile.currentRangeUnit),currentDateProfile.dateIncrement);return this.build(nextDate,nowDate,1,forceToValid)}build(currentDate,nowDate,direction,forceToValid=!0){let{props}=this,validRange,currentInfo,isRangeAllDay,renderRange,activeRange,isValid;return validRange=this.buildValidRange(nowDate),validRange=this.trimHiddenDays(validRange),forceToValid&&(currentDate=constrainMarkerToRange(currentDate,validRange)),currentInfo=this.buildCurrentRangeInfo(currentDate,direction),isRangeAllDay=/^(year|month|week|day)$/.test(currentInfo.unit),renderRange=this.buildRenderRange(this.trimHiddenDays(currentInfo.range),currentInfo.unit,isRangeAllDay),renderRange=this.trimHiddenDays(renderRange),activeRange=renderRange,props.showNonCurrentDates||(activeRange=intersectRanges(activeRange,currentInfo.range)),activeRange=this.adjustActiveRange(activeRange),activeRange=intersectRanges(activeRange,validRange),isValid=rangesIntersect(currentInfo.range,validRange),rangeContainsMarker(renderRange,currentDate)||(currentDate=renderRange.start),{currentDate,validRange,currentRange:currentInfo.range,currentRangeUnit:currentInfo.unit,isRangeAllDay,activeRange,renderRange,slotMinTime:props.slotMinTime,slotMaxTime:props.slotMaxTime,isValid,dateIncrement:this.buildDateIncrement(currentInfo.duration)}}buildValidRange(nowDate){let input=this.props.validRangeInput,simpleInput=typeof input=="function"?input.call(this.props.calendarApi,this.props.dateEnv.toDate(nowDate)):input;return this.refineRange(simpleInput)||{start:null,end:null}}buildCurrentRangeInfo(date,direction){let{props}=this,duration=null,unit=null,range=null,dayCount;return props.duration?(duration=props.duration,unit=props.durationUnit,range=this.buildRangeFromDuration(date,direction,duration,unit)):(dayCount=this.props.dayCount)?(unit="day",range=this.buildRangeFromDayCount(date,direction,dayCount)):(range=this.buildCustomVisibleRange(date))?unit=props.dateEnv.greatestWholeUnit(range.start,range.end).unit:(duration=this.getFallbackDuration(),unit=greatestDurationDenominator(duration).unit,range=this.buildRangeFromDuration(date,direction,duration,unit)),{duration,unit,range}}getFallbackDuration(){return createDuration({day:1})}adjustActiveRange(range){let{dateEnv,usesMinMaxTime,slotMinTime,slotMaxTime}=this.props,{start,end}=range;return usesMinMaxTime&&(asRoughDays(slotMinTime)<0&&(start=startOfDay5(start),start=dateEnv.add(start,slotMinTime)),asRoughDays(slotMaxTime)>1&&(end=startOfDay5(end),end=addDays4(end,-1),end=dateEnv.add(end,slotMaxTime))),{start,end}}buildRangeFromDuration(date,direction,duration,unit){let{dateEnv,dateAlignment}=this.props,start,end,res;if(!dateAlignment){let{dateIncrement}=this.props;dateIncrement&&asRoughMs(dateIncrement)<asRoughMs(duration)?dateAlignment=greatestDurationDenominator(dateIncrement).unit:dateAlignment=unit}asRoughDays(duration)<=1&&this.isHiddenDay(start)&&(start=this.skipHiddenDays(start,direction),start=startOfDay5(start));function computeRes(){start=dateEnv.startOf(date,dateAlignment),end=dateEnv.add(start,duration),res={start,end}}return computeRes(),this.trimHiddenDays(res)||(date=this.skipHiddenDays(date,direction),computeRes()),res}buildRangeFromDayCount(date,direction,dayCount){let{dateEnv,dateAlignment}=this.props,runningCount=0,start=date,end;dateAlignment&&(start=dateEnv.startOf(start,dateAlignment)),start=startOfDay5(start),start=this.skipHiddenDays(start,direction),end=start;do end=addDays4(end,1),this.isHiddenDay(end)||(runningCount+=1);while(runningCount<dayCount);return{start,end}}buildCustomVisibleRange(date){let{props}=this,input=props.visibleRangeInput,simpleInput=typeof input=="function"?input.call(props.calendarApi,props.dateEnv.toDate(date)):input,range=this.refineRange(simpleInput);return range&&(range.start==null||range.end==null)?null:range}buildRenderRange(currentRange,currentRangeUnit,isRangeAllDay){return currentRange}buildDateIncrement(fallback){let{dateIncrement}=this.props,customAlignment;return dateIncrement||((customAlignment=this.props.dateAlignment)?createDuration(1,customAlignment):fallback||createDuration({days:1}))}refineRange(rangeInput){if(rangeInput){let range=parseRange(rangeInput,this.props.dateEnv);return range&&(range=computeVisibleDayRange(range)),range}return null}initHiddenDays(){let hiddenDays=this.props.hiddenDays||[],isHiddenDayHash=[],dayCnt=0,i;for(this.props.weekends===!1&&hiddenDays.push(0,6),i=0;i<7;i+=1)(isHiddenDayHash[i]=hiddenDays.indexOf(i)!==-1)||(dayCnt+=1);if(!dayCnt)throw new Error("invalid hiddenDays");this.isHiddenDayHash=isHiddenDayHash}trimHiddenDays(range){let{start,end}=range;return start&&(start=this.skipHiddenDays(start)),end&&(end=this.skipHiddenDays(end,-1,!0)),start==null||end==null||start<end?{start,end}:null}isHiddenDay(day){return day instanceof Date&&(day=day.getUTCDay()),this.isHiddenDayHash[day]}skipHiddenDays(date,inc=1,isExclusive=!1){for(;this.isHiddenDayHash[(date.getUTCDay()+(isExclusive?inc:0)+7)%7];)date=addDays4(date,inc);return date}};function computeMajorUnit(dateProfile,dateEnv){let{currentRange}=dateProfile;if(dateProfile.currentRangeUnit==="year")return dateEnv.diffWholeYears(currentRange.start,currentRange.end)>1?"year":"month";if(dateProfile.currentRangeUnit==="month"){if(dateEnv.diffWholeMonths(currentRange.start,currentRange.end)>1)return"month"}else if(dateProfile.currentRangeUnit==="week"){if(diffWholeWeeks(currentRange.start,currentRange.end)>1)return"week"}else if(dateProfile.currentRangeUnit==="day"&&diffWholeDays(currentRange.start,currentRange.end)>1)return"day"}function isMajorUnit(dateMarker,majorUnit,dateEnv){if(dateMarker.valueOf()===startOfDay5(dateMarker).valueOf()){if(majorUnit==="year")return!dateEnv.getMonth(dateMarker)&&dateEnv.getDay(dateMarker)===1;if(majorUnit==="month")return dateEnv.getDay(dateMarker)===1;if(majorUnit==="week")return dateMarker.getUTCDay()===dateEnv.weekDow;if(majorUnit==="day")return!0}return!1}function reduceEventStore(eventStore,action,eventSources,dateProfile,context){switch(action.type){case"RECEIVE_EVENTS":return receiveRawEvents(eventStore,eventSources[action.sourceId],action.fetchId,action.fetchRange,action.rawEvents,context);case"RESET_RAW_EVENTS":return resetRawEvents(eventStore,eventSources[action.sourceId],action.rawEvents,dateProfile.activeRange,context);case"ADD_EVENTS":return addEvent(eventStore,action.eventStore,dateProfile?dateProfile.activeRange:null,context);case"RESET_EVENTS":return action.eventStore;case"MERGE_EVENTS":return mergeEventStores(eventStore,action.eventStore);case"PREV":case"NEXT":case"CHANGE_DATE":case"CHANGE_VIEW_TYPE":return dateProfile?expandRecurring(eventStore,dateProfile.activeRange,context):eventStore;case"REMOVE_EVENTS":return excludeSubEventStore(eventStore,action.eventStore);case"REMOVE_EVENT_SOURCE":return excludeEventsBySourceId(eventStore,action.sourceId);case"REMOVE_ALL_EVENT_SOURCES":return filterEventStoreDefs(eventStore,eventDef=>!eventDef.sourceId);case"REMOVE_ALL_EVENTS":return createEmptyEventStore();default:return eventStore}}function receiveRawEvents(eventStore,eventSource,fetchId,fetchRange,rawEvents,context){if(eventSource&&fetchId===eventSource.latestFetchId){let subset=parseEvents(transformRawEvents(rawEvents,eventSource,context),eventSource,context);return fetchRange&&(subset=expandRecurring(subset,fetchRange,context)),mergeEventStores(excludeEventsBySourceId(eventStore,eventSource.sourceId),subset)}return eventStore}function resetRawEvents(existingEventStore,eventSource,rawEvents,activeRange,context){let{defIdMap,instanceIdMap}=buildPublicIdMaps(existingEventStore),newEventStore=parseEvents(transformRawEvents(rawEvents,eventSource,context),eventSource,context,!1,defIdMap,instanceIdMap);return expandRecurring(newEventStore,activeRange,context)}function transformRawEvents(rawEvents,eventSource,context){let calEachTransform=context.options.eventDataTransform,sourceEachTransform=eventSource?eventSource.eventDataTransform:null;return sourceEachTransform&&(rawEvents=transformEachRawEvent(rawEvents,sourceEachTransform)),calEachTransform&&(rawEvents=transformEachRawEvent(rawEvents,calEachTransform)),rawEvents}function transformEachRawEvent(rawEvents,func){let refinedEvents;if(!func)refinedEvents=rawEvents;else{refinedEvents=[];for(let rawEvent of rawEvents){let refinedEvent=func(rawEvent);refinedEvent?refinedEvents.push(refinedEvent):refinedEvent==null&&refinedEvents.push(rawEvent)}}return refinedEvents}function addEvent(eventStore,subset,expandRange,context){return expandRange&&(subset=expandRecurring(subset,expandRange,context)),mergeEventStores(eventStore,subset)}function rezoneEventStoreDates(eventStore,oldDateEnv,newDateEnv){let{defs}=eventStore,instances=mapHash(eventStore.instances,instance=>{if(defs[instance.defId].allDay)return instance;let{instantStartMs,instantEndMs}=instance.range,start=instantStartMs!=null?newDateEnv.timestampToMarker(instantStartMs):newDateEnv.createMarker(oldDateEnv.toDate(instance.range.start)),end=instantEndMs!=null?newDateEnv.timestampToMarker(instantEndMs):newDateEnv.createMarker(oldDateEnv.toDate(instance.range.end));return{...instance,range:buildValidInstanceRange({marker:start,instantMs:instantStartMs},{marker:end,instantMs:instantEndMs},newDateEnv)??buildEventInstanceRange(start,addMs(start,getRangeInstantEndMs(instance.range,oldDateEnv)-getRangeInstantStartMs(instance.range,oldDateEnv)),instantStartMs)}});return{defs,instances}}function excludeEventsBySourceId(eventStore,sourceId){return filterEventStoreDefs(eventStore,eventDef=>eventDef.sourceId!==sourceId)}function excludeInstances(eventStore,removals){return{defs:eventStore.defs,instances:filterHash(eventStore.instances,instance=>!removals[instance.instanceId])}}function buildPublicIdMaps(eventStore){let{defs,instances}=eventStore,defIdMap={},instanceIdMap={};for(let defId in defs){let def=defs[defId],{publicId}=def;publicId&&(defIdMap[publicId]=defId)}for(let instanceId in instances){let instance=instances[instanceId],def=defs[instance.defId],{publicId}=def;publicId&&(instanceIdMap[publicId]=instanceId)}return{defIdMap,instanceIdMap}}var Interaction=class{constructor(settings){this.component=settings.component,this.isHitComboAllowed=settings.isHitComboAllowed||null}destroy(){}};function parseInteractionSettings(component,input){return{component,el:input.el,useEventCenter:input.useEventCenter!=null?input.useEventCenter:!0,isHitComboAllowed:input.isHitComboAllowed||null}}function interactionSettingsToStore(settings){return{[settings.component.uid]:settings}}var interactionSettingsStore={};var Emitter=class{constructor(){this.handlers={},this.thisContext=null}setThisContext(thisContext){this.thisContext=thisContext}setOptions(options){this.options=options}on(type,handler){addToHash(this.handlers,type,handler)}off(type,handler){removeFromHash(this.handlers,type,handler)}trigger(type,...args){let attachedHandlers=this.handlers[type]||[],optionHandler=this.options&&this.options[type],handlers=[].concat(optionHandler||[],attachedHandlers);for(let handler of handlers)handler.apply(this.thisContext,args)}hasHandlers(type){return!!(this.handlers[type]&&this.handlers[type].length||this.options&&this.options[type])}};function addToHash(hash,type,handler){(hash[type]||(hash[type]=[])).push(handler)}function removeFromHash(hash,type,handler){handler?hash[type]&&(hash[type]=hash[type].filter(func=>func!==handler)):delete hash[type]}import{Component as Component2,createElement as createElement3,Fragment as Fragment$1}from"react";function refinePluginDef(input){return{name:input.name,premiumReleaseDate:input.premiumReleaseDate?new Date(input.premiumReleaseDate):void 0,reducers:input.reducers||[],isLoadingFuncs:input.isLoadingFuncs||[],contextInit:[].concat(input.contextInit||[]),eventRefiners:input.eventRefiners||{},eventDefMemberAdders:input.eventDefMemberAdders||[],eventSourceRefiners:input.eventSourceRefiners||{},isDraggableTransformers:input.isDraggableTransformers||[],eventDragMutationMassagers:input.eventDragMutationMassagers||[],eventDefMutationAppliers:input.eventDefMutationAppliers||[],dateSelectionTransformers:input.dateSelectionTransformers||[],datePointTransforms:input.datePointTransforms||[],dateSpanTransforms:input.dateSpanTransforms||[],views:input.views||{},viewPropsTransformers:input.viewPropsTransformers||[],isPropsValid:input.isPropsValid||null,externalDefTransforms:input.externalDefTransforms||[],viewContainerAppends:input.viewContainerAppends||[],eventDropTransformers:input.eventDropTransformers||[],componentInteractions:input.componentInteractions||[],calendarInteractions:input.calendarInteractions||[],eventSourceDefs:input.eventSourceDefs||[],cmdFormatter:input.cmdFormatter,recurringTypes:input.recurringTypes||[],initialView:input.initialView||"",elementDraggingImpl:input.elementDraggingImpl,optionChangeHandlers:input.optionChangeHandlers||{},scrollerSyncerClass:input.scrollerSyncerClass||null,listenerRefiners:input.listenerRefiners||{},optionRefiners:input.optionRefiners||{},optionDefaults:input.optionDefaults?[input.optionDefaults]:[],propSetHandlers:input.propSetHandlers||{}}}function buildPluginHooks(pluginDefs,globalDefs){let pluginsByName={},hooks={premiumReleaseDate:void 0,reducers:[],isLoadingFuncs:[],contextInit:[],eventRefiners:{},eventDefMemberAdders:[],eventSourceRefiners:{},isDraggableTransformers:[],eventDragMutationMassagers:[],eventDefMutationAppliers:[],dateSelectionTransformers:[],datePointTransforms:[],dateSpanTransforms:[],views:{},viewPropsTransformers:[],isPropsValid:null,externalDefTransforms:[],viewContainerAppends:[],eventDropTransformers:[],componentInteractions:[],calendarInteractions:[],eventSourceDefs:[],cmdFormatter:null,recurringTypes:[],initialView:"",elementDraggingImpl:null,optionChangeHandlers:{},scrollerSyncerClass:null,listenerRefiners:{},optionRefiners:{},optionDefaults:[],propSetHandlers:{}};function addDefs(defs){for(let unrefinedDef of defs){let{name}=unrefinedDef;if(!name)throw new Error("Plugin must specify a name");if(!pluginsByName[name]){let def=pluginsByName[name]=refinePluginDef(unrefinedDef);hooks=combineHooks(hooks,def),addDefs(unrefinedDef.deps||[])}}}return pluginDefs&&addDefs(pluginDefs),addDefs(globalDefs),hooks}function buildBuildPluginHooks(){let currentOverrideDefs=[],currentGlobalDefs=[],currentHooks;return(overrideDefs,globalDefs)=>((!currentHooks||!isArraysEqual(overrideDefs,currentOverrideDefs)||!isArraysEqual(globalDefs,currentGlobalDefs))&&(currentHooks=buildPluginHooks(overrideDefs,globalDefs)),currentOverrideDefs=overrideDefs,currentGlobalDefs=globalDefs,currentHooks)}function combineHooks(hooks0,hooks1){return{premiumReleaseDate:compareOptionalDates(hooks0.premiumReleaseDate,hooks1.premiumReleaseDate),reducers:hooks0.reducers.concat(hooks1.reducers),isLoadingFuncs:hooks0.isLoadingFuncs.concat(hooks1.isLoadingFuncs),contextInit:hooks0.contextInit.concat(hooks1.contextInit),eventRefiners:{...hooks0.eventRefiners,...hooks1.eventRefiners},eventDefMemberAdders:hooks0.eventDefMemberAdders.concat(hooks1.eventDefMemberAdders),eventSourceRefiners:{...hooks0.eventSourceRefiners,...hooks1.eventSourceRefiners},isDraggableTransformers:hooks0.isDraggableTransformers.concat(hooks1.isDraggableTransformers),eventDragMutationMassagers:hooks0.eventDragMutationMassagers.concat(hooks1.eventDragMutationMassagers),eventDefMutationAppliers:hooks0.eventDefMutationAppliers.concat(hooks1.eventDefMutationAppliers),dateSelectionTransformers:hooks0.dateSelectionTransformers.concat(hooks1.dateSelectionTransformers),datePointTransforms:hooks0.datePointTransforms.concat(hooks1.datePointTransforms),dateSpanTransforms:hooks0.dateSpanTransforms.concat(hooks1.dateSpanTransforms),views:mergeViewOptionsMap(hooks0.views,hooks1.views),viewPropsTransformers:hooks0.viewPropsTransformers.concat(hooks1.viewPropsTransformers),isPropsValid:hooks1.isPropsValid||hooks0.isPropsValid,externalDefTransforms:hooks0.externalDefTransforms.concat(hooks1.externalDefTransforms),viewContainerAppends:hooks0.viewContainerAppends.concat(hooks1.viewContainerAppends),eventDropTransformers:hooks0.eventDropTransformers.concat(hooks1.eventDropTransformers),calendarInteractions:hooks0.calendarInteractions.concat(hooks1.calendarInteractions),componentInteractions:hooks0.componentInteractions.concat(hooks1.componentInteractions),eventSourceDefs:hooks0.eventSourceDefs.concat(hooks1.eventSourceDefs),cmdFormatter:hooks1.cmdFormatter||hooks0.cmdFormatter,recurringTypes:hooks0.recurringTypes.concat(hooks1.recurringTypes),initialView:hooks0.initialView||hooks1.initialView,elementDraggingImpl:hooks0.elementDraggingImpl||hooks1.elementDraggingImpl,optionChangeHandlers:{...hooks0.optionChangeHandlers,...hooks1.optionChangeHandlers},scrollerSyncerClass:hooks0.scrollerSyncerClass||hooks1.scrollerSyncerClass,listenerRefiners:{...hooks0.listenerRefiners,...hooks1.listenerRefiners},optionRefiners:{...hooks0.optionRefiners,...hooks1.optionRefiners},optionDefaults:hooks0.optionDefaults.concat(hooks1.optionDefaults),propSetHandlers:{...hooks0.propSetHandlers,...hooks1.propSetHandlers}}}function compareOptionalDates(date0,date1){return date0===void 0?date1:date1===void 0?date0:new Date(Math.max(date0.valueOf(),date1.valueOf()))}function compileViewDefs(defaultConfigs,overrideConfigs){let hash={},viewType;for(viewType in defaultConfigs)ensureViewDef(viewType,hash,defaultConfigs,overrideConfigs);for(viewType in overrideConfigs)ensureViewDef(viewType,hash,defaultConfigs,overrideConfigs);return hash}function ensureViewDef(viewType,hash,defaultConfigs,overrideConfigs){if(hash[viewType])return hash[viewType];let viewDef=buildViewDef(viewType,hash,defaultConfigs,overrideConfigs);return viewDef&&(hash[viewType]=viewDef),viewDef}function buildViewDef(viewType,hash,defaultConfigs,overrideConfigs){let defaultConfig=defaultConfigs[viewType],overrideConfig=overrideConfigs[viewType],queryProp=name=>defaultConfig&&defaultConfig[name]!==null?defaultConfig[name]:overrideConfig&&overrideConfig[name]!==null?overrideConfig[name]:null,theComponent=queryProp("component"),superType=queryProp("superType"),superDef=null;if(superType){if(superType===viewType)throw new Error("Can't have a custom view type that references itself");superDef=ensureViewDef(superType,hash,defaultConfigs,overrideConfigs)}return!theComponent&&superDef&&(theComponent=superDef.component),theComponent?{type:viewType,component:theComponent,defaults:mergeCalendarOptions(superDef?superDef.defaults:{},defaultConfig?defaultConfig.rawOptions:{}),overrides:mergeCalendarOptions(superDef?superDef.overrides:{},overrideConfig?overrideConfig.rawOptions:{})}:null}function parseViewConfigs(inputs){return mapHash(inputs,parseViewConfig)}function parseViewConfig(input){let rawOptions=typeof input=="function"?{component:input}:input,{component}=rawOptions;return rawOptions.content?component=createViewHookComponent(rawOptions.content):component&&!(component.prototype instanceof BaseComponent)&&(component=createViewHookComponent(component)),{superType:rawOptions.type,component,rawOptions}}function createViewHookComponent(contentGenerator){return viewProps=>jsx8(ViewContextType.Consumer,{children:context=>{let{options,viewSpec}=context,renderProps={...viewProps,nextDayThreshold:options.nextDayThreshold,...computeViewBorderless(options),options:{headerToolbar:options.headerToolbar,footerToolbar:options.footerToolbar},isHeightAuto:getIsHeightAuto(options),view:context.viewApi};return jsx8(ContentContainer,{tag:"div",className:joinClassNames(generateClassName(options.viewClass,renderProps),generateClassName(viewSpec.optionDefaults.class,renderProps),generateClassName(viewSpec.optionDefaults.className,renderProps),generateClassName(viewSpec.optionOverrides.class,renderProps),generateClassName(viewSpec.optionOverrides.className,renderProps)),renderProps,generatorName:void 0,customGenerator:contentGenerator,didMount:options.didMount||options.viewDidMount,willUnmount:options.willUnmount||options.viewWillUnmount})}})}function buildViewSpecs(defaultInputs,optionOverrides,dynamicOptionOverrides){let defaultConfigs=parseViewConfigs(defaultInputs),overrideConfigs=parseViewConfigs(optionOverrides.views),viewDefs=compileViewDefs(defaultConfigs,overrideConfigs);return mapHash(viewDefs,viewDef=>buildViewSpec(viewDef,overrideConfigs,optionOverrides,dynamicOptionOverrides))}function buildViewSpec(viewDef,overrideConfigs,optionOverrides,dynamicOptionOverrides){let durationInput=viewDef.overrides.duration||viewDef.defaults.duration||dynamicOptionOverrides.duration||optionOverrides.duration,duration=null,durationUnit="",singleUnit="",singleUnitOverrides={};if(durationInput&&(duration=createDurationCached(durationInput),duration)){let denom=greatestDurationDenominator(duration);durationUnit=denom.unit,denom.value===1&&(singleUnit=durationUnit,singleUnitOverrides=overrideConfigs[durationUnit]?overrideConfigs[durationUnit].rawOptions:{})}return{type:viewDef.type,component:viewDef.component,duration,durationUnit,singleUnit,optionDefaults:viewDef.defaults,optionOverrides:{...singleUnitOverrides,...viewDef.overrides}}}var durationInputMap={};function createDurationCached(durationInput){let json=JSON.stringify(durationInput),res=durationInputMap[json];return res===void 0&&(res=createDuration(durationInput),durationInputMap[json]=res),res}function reduceViewType(viewType,action){return action.type==="CHANGE_VIEW_TYPE"&&(viewType=action.viewType),viewType}function reduceCurrentDate(currentDate,action){return action.type==="CHANGE_DATE"?action.dateMarker:currentDate}function getInitialDate(options,dateEnv,nowManager){let initialDateInput=options.initialDate;return initialDateInput!=null?dateEnv.createMarker(initialDateInput):nowManager.getDateMarker()}function reduceDynamicOptionOverrides(dynamicOptionOverrides,action){return action.type==="SET_OPTION"?{...dynamicOptionOverrides,[action.optionName]:action.rawOptionValue}:dynamicOptionOverrides}function reduceDateProfile(currentDateProfile,action,currentDate,nowDate,dateProfileGenerator){let dp;switch(action.type){case"CHANGE_VIEW_TYPE":return dateProfileGenerator.build(action.dateMarker||currentDate,nowDate);case"CHANGE_DATE":return dateProfileGenerator.build(action.dateMarker,nowDate);case"PREV":if(dp=dateProfileGenerator.buildPrev(currentDateProfile,currentDate,nowDate),dp.isValid)return dp;break;case"NEXT":if(dp=dateProfileGenerator.buildNext(currentDateProfile,currentDate,nowDate),dp.isValid)return dp;break}return currentDateProfile}function reduceDateSelection(currentSelection,action){switch(action.type){case"UNSELECT_DATES":return null;case"SELECT_DATES":return action.selection;default:return currentSelection}}function reduceSelectedEvent(currentInstanceId,action){switch(action.type){case"UNSELECT_EVENT":return"";case"SELECT_EVENT":return action.eventInstanceId;default:return currentInstanceId}}function reduceEventDrag(currentDrag,action){let newDrag;switch(action.type){case"UNSET_EVENT_DRAG":return null;case"SET_EVENT_DRAG":return newDrag=action.state,{affectedEvents:newDrag.affectedEvents,mutatedEvents:newDrag.mutatedEvents,isEvent:newDrag.isEvent};default:return currentDrag}}function reduceEventResize(currentResize,action){let newResize;switch(action.type){case"UNSET_EVENT_RESIZE":return null;case"SET_EVENT_RESIZE":return newResize=action.state,{affectedEvents:newResize.affectedEvents,mutatedEvents:newResize.mutatedEvents,isEvent:newResize.isEvent};default:return currentResize}}function parseToolbars(calendarOptions,viewSpecs,calendarApi){let header=calendarOptions.headerToolbar?parseToolbar(calendarOptions.headerToolbar,calendarOptions,viewSpecs,calendarApi):null,footer=calendarOptions.footerToolbar?parseToolbar(calendarOptions.footerToolbar,calendarOptions,viewSpecs,calendarApi):null;return{header,footer}}function parseToolbar(sectionStrHash,calendarOptions,viewSpecs,calendarApi){let isRtl=calendarOptions.direction==="rtl",viewsWithButtons=[],hasTitle=!1;function processSectionStr(sectionStr){let sectionRes=parseSection(sectionStr,calendarOptions,viewSpecs,calendarApi);return viewsWithButtons.push(...sectionRes.viewsWithButtons),hasTitle=hasTitle||sectionRes.hasTitle,sectionRes.widgets}return{sectionWidgets:{start:processSectionStr(sectionStrHash[isRtl?"right":"left"]||sectionStrHash.start||""),center:processSectionStr(sectionStrHash.center||""),end:processSectionStr(sectionStrHash[isRtl?"left":"right"]||sectionStrHash.end||"")},viewsWithButtons,hasTitle}}function parseSection(sectionStr,calendarOptions,viewSpecs,calendarApi){let calendarButtons=calendarOptions.buttons||{},customElements=calendarOptions.toolbarElements||{},sectionSubstrs=sectionStr?sectionStr.split(" "):[],viewsWithButtons=[],hasTitle=!1;return{widgets:sectionSubstrs.map(buttonGroupStr=>buttonGroupStr.split(",").map(name=>{if(name==="title")return hasTitle=!0,{name};if(customElements[name])return{name,customElement:customElements[name]};let viewSpec,buttonInput=calendarButtons[name]||{},buttonText,buttonHint,buttonClick;if(viewSpec=viewSpecs[name]){viewsWithButtons.push(name);let buttonTextKey=viewSpec.optionDefaults.buttonTextKey;buttonText=buttonInput.text||(buttonTextKey?calendarOptions[buttonTextKey]:"")||(viewSpec.singleUnit?calendarOptions[viewSpec.singleUnit+"TextLong"]||calendarOptions[viewSpec.singleUnit+"Text"]:"")||name,buttonHint=formatWithOrdinals(buttonInput.hint||calendarOptions.viewHint,[buttonText,name],buttonText),buttonClick=ev=>{buttonInput?.click?.(ev),ev.defaultPrevented||calendarApi.changeView(name)}}else buttonText=buttonInput.text||calendarOptions[name+"TextLong"]||calendarOptions[name+"Text"]||name,name==="prevYear"?buttonHint=formatWithOrdinals(buttonInput.hint||calendarOptions.prevHint,[calendarOptions.yearText,"year"],buttonText):name==="nextYear"?buttonHint=formatWithOrdinals(buttonInput.hint||calendarOptions.nextHint,[calendarOptions.yearText,"year"],buttonText):buttonHint=currentUnit=>formatWithOrdinals(buttonInput.hint||calendarOptions[name+"Hint"],[calendarOptions[currentUnit+"TextLong"]||calendarOptions[currentUnit+"Text"],currentUnit],buttonText),buttonClick=ev=>{buttonInput?.click?.(ev),ev.defaultPrevented||calendarApi[name]?.()};return{name,isView:!!viewSpec,buttonText,buttonHint,buttonDisplay:buttonInput.display,buttonIconClass:buttonInput.iconClass,buttonIconContent:buttonInput.iconContent,buttonClick,buttonIsPrimary:buttonInput.isPrimary||!1,buttonClass:buttonInput.class??buttonInput.className,buttonDidMount:buttonInput.didMount,buttonWillUnmount:buttonInput.willUnmount}})),viewsWithButtons,hasTitle}}var ViewImpl=class{constructor(type,getCurrentData,dateEnv){this.type=type,this.getCurrentData=getCurrentData,this.dateEnv=dateEnv}get calendar(){return this.getCurrentData().calendarApi}get title(){return this.getCurrentData().viewTitle}get activeStart(){return this.dateEnv.toDate(this.getCurrentData().dateProfile.activeRange.start)}get activeEnd(){return this.dateEnv.toDate(this.getCurrentData().dateProfile.activeRange.end)}get currentStart(){return this.dateEnv.toDate(this.getCurrentData().dateProfile.currentRange.start)}get currentEnd(){return this.dateEnv.toDate(this.getCurrentData().dateProfile.currentRange.end)}getOption(name){return this.getCurrentData().options[name]}},DEF_DEFAULTS={startTime:"09:00",endTime:"17:00",daysOfWeek:[1,2,3,4,5],display:"inverse-background",className:"",groupId:"_businessHours"};function parseBusinessHours(input,context){return parseEvents(refineInputs(input),null,context)}function refineInputs(input){let rawDefs;return input===!0?rawDefs=[{}]:Array.isArray(input)?rawDefs=input.filter(rawDef=>rawDef.daysOfWeek):typeof input=="object"&&input?rawDefs=[input]:rawDefs=[],rawDefs=rawDefs.map(rawDef=>({...DEF_DEFAULTS,...rawDef})),rawDefs}function buildTitle(dateProfile,viewOptions,dateEnv){let range;/^(year|month)$/.test(dateProfile.currentRangeUnit)?range=dateProfile.currentRange:range=dateProfile.activeRange;let parts,options={isEndExclusive:dateProfile.isRangeAllDay};return viewOptions.titleFormat?parts=dateEnv.formatRangeToParts(range.start,range.end,createFormatter(viewOptions.titleFormat),options):(parts=dateEnv.formatRangeToParts(range.start,range.end,createFormatter(buildTitleFormat(dateProfile,viewOptions.disallowAmbigTitle,"long")),options),hasTwoMonths(parts)&&(parts=dateEnv.formatRangeToParts(range.start,range.end,createFormatter(buildTitleFormat(dateProfile,viewOptions.disallowAmbigTitle,"short")),options))),joinDateTimeFormatParts(parts)}function buildTitleFormat(dateProfile,disallowAmbigTitle,monthFormat){let{currentRangeUnit}=dateProfile;if(currentRangeUnit==="year")return{year:"numeric"};if(currentRangeUnit==="month")return{year:"numeric",month:monthFormat};if(!disallowAmbigTitle){let days=diffWholeDays(dateProfile.currentRange.start,dateProfile.currentRange.end);if(days!==null&&days>1)return{year:"numeric",month:monthFormat}}return{year:"numeric",month:"long",day:"numeric"}}function hasTwoMonths(parts){let hasStartMonth=!1,hasEndMonth=!1;for(let part of parts)part.type==="month"&&(part.source==="startRange"&&(hasStartMonth=!0),part.source==="endRange"&&(hasEndMonth=!0));return hasStartMonth&&hasEndMonth}var CalendarNowManager=class{constructor(){this.resetListeners=new Set}handleInput(dateEnv,nowInput){let oldDateEnv=this.dateEnv;if(dateEnv!==oldDateEnv&&(typeof nowInput=="function"?this.nowFn=nowInput:oldDateEnv||(this.nowAnchorDate=nowInput?resolveInputToDate(nowInput,dateEnv):new Date,this.nowAnchorQueried=Date.now()),this.dateEnv=dateEnv,oldDateEnv))for(let resetListener of this.resetListeners.values())resetListener()}getDateMarker(){return this.dateEnv.timestampToMarker(this.getEpochMs())}getEpochMs(){return this.nowAnchorDate?this.nowAnchorDate.valueOf()+(Date.now()-this.nowAnchorQueried):resolveInputToDate(this.nowFn(),this.dateEnv).valueOf()}addResetListener(handler){this.resetListeners.add(handler)}removeResetListener(handler){this.resetListeners.delete(handler)}};function resolveInputToDate(input,dateEnv){let meta=dateEnv.createMarkerMeta(input);return meta.instantMs!=null?new Date(meta.instantMs):dateEnv.toDate(meta.marker)}var CalendarDataManager=class{constructor(config2){this.computeCurrentViewData=memoize2(this._computeCurrentViewData),this.organizeRawLocales=memoize2(organizeRawLocales),this.buildLocale=memoize2(buildLocale),this.buildPluginHooks=buildBuildPluginHooks(),this.buildDateEnv=memoize2(buildDateEnv),this.parseToolbars=memoize2(parseToolbars),this.buildViewSpecs=memoize2(buildViewSpecs),this.buildDateProfileGenerator=memoizeObjArg(buildDateProfileGenerator),this.buildViewApi=memoize2(buildViewApi),this.buildViewUiProps=memoizeObjArg(buildViewUiProps),this.buildEventUiBySource=memoize2(buildEventUiBySource,isPropsEqualShallow),this.buildEventUiBases=memoize2(buildEventUiBases),this.parseContextBusinessHours=memoizeObjArg(parseContextBusinessHours),this.buildToolbarProps=memoize2(buildToolbarProps),this.buildTitle=memoize2(buildTitle),this.nowManager=new CalendarNowManager,this.isDrainingActionQueue=!1,this.actionQueue=[],this.optionOverrides={},this.emitter=new Emitter,this.currentCalendarOptionsRefiners={},this.currentCalendarOptionsInput={},this.currentCalendarOptionsRefined={},this.currentViewOptionsInput={},this.currentViewOptionsRefined={},this.optionsForRefining=[],this.optionsForHandling=[],this.getCurrentData=()=>this.data,this.handleNowChange=()=>{this.dispatch({type:"UPDATE_NOW"})},this.dispatch=action=>{this.actionQueue.push(action),this.isDrainingActionQueue||this.drainActionQueue()},this.config=config2,this.nowManager=new CalendarNowManager,this.nowTimer=new NowTimerRunner(this.handleNowChange)}destroy(){this.nowTimer.destroy()}update(optionOverrides){return this.optionOverrides=optionOverrides,this.actionQueue.push({type:"IDLE"}),this.drainActionQueue(),this.data}resetOptions(optionOverrides,changedOptionNames){changedOptionNames===void 0?this.optionOverrides=optionOverrides:(this.optionOverrides={...this.optionOverrides,...optionOverrides},this.optionsForRefining.push(...changedOptionNames)),this.dispatch({type:"RESET_OPTIONS"})}drainActionQueue(){let calendarContext,{state,data}=this,isInit=!state,{actionQueue}=this,actionsComplete=[];for(this.isDrainingActionQueue=!0;actionQueue.length;){let action=actionQueue.shift();({state,data,calendarContext}=this.reduce(state,data,action)),this.state=state,this.data=data,action.type!=="IDLE"&&actionsComplete.push(action)}if(this.isDrainingActionQueue=!1,isInit){let controllerOption=calendarContext.options.controller;controllerOption&&controllerOption._setApi(this.config.calendarApi)}if(!isInit&&actionsComplete.length){let{onDataChange}=this.config;onDataChange&&onDataChange(this.data,actionsComplete)}}reduce(prevState,prevData,action){let{config:config2}=this,isInit=!prevState,dynamicOptionOverrides=isInit?{}:reduceDynamicOptionOverrides(prevState.dynamicOptionOverrides,action),optionsData=this.computeOptionsData(this.optionOverrides,dynamicOptionOverrides,config2.calendarApi),currentViewType=isInit?optionsData.calendarOptions.initialView||optionsData.pluginHooks.initialView:reduceViewType(prevState.currentViewType,action),currentViewData=this.computeCurrentViewData(currentViewType,optionsData,this.optionOverrides,dynamicOptionOverrides);config2.calendarApi.currentDataManager=this,this.emitter.setThisContext(config2.calendarApi),this.emitter.setOptions(currentViewData.options);let calendarContext={nowManager:this.nowManager,dateEnv:optionsData.dateEnv,options:optionsData.calendarOptions,pluginHooks:optionsData.pluginHooks,calendarApi:config2.calendarApi,dispatch:this.dispatch,emitter:this.emitter,getCurrentData:this.getCurrentData},{nowDate}=this.nowTimer.update({unit:"day",unitValue:1,nowIndicatorSnap:"auto",nowManager:this.nowManager,dateEnv:optionsData.dateEnv}),currentDate=isInit?getInitialDate(optionsData.calendarOptions,optionsData.dateEnv,this.nowManager):reduceCurrentDate(prevState.currentDate,action),dateProfile;isInit?dateProfile=currentViewData.dateProfileGenerator.build(currentDate,nowDate):(dateProfile=prevState.dateProfile,prevData&&prevData.dateProfileGenerator!==currentViewData.dateProfileGenerator&&(dateProfile=currentViewData.dateProfileGenerator.build(currentDate,nowDate)),dateProfile=reduceDateProfile(dateProfile,action,currentDate,nowDate,currentViewData.dateProfileGenerator)),(action&&(action.type==="PREV"||action.type==="NEXT")||!rangeContainsMarker(dateProfile.activeRange,currentDate))&&(currentDate=dateProfile.currentRange.start);let eventSources=isInit?initEventSources(optionsData.calendarOptions,dateProfile,calendarContext):reduceEventSources(prevState.eventSources,action,dateProfile,calendarContext),eventStore=isInit?createEmptyEventStore():reduceEventStore(prevState.eventStore,action,eventSources,dateProfile,calendarContext),isEventsLoading=computeEventSourcesLoading(eventSources),renderableEventStore=isInit?createEmptyEventStore():isEventsLoading&&!currentViewData.options.progressiveEventRendering&&prevState.renderableEventStore||eventStore,{eventUiSingleBase,selectionConfig}=this.buildViewUiProps(calendarContext),eventUiBySource=this.buildEventUiBySource(eventSources),eventUiBases=isInit?{}:this.buildEventUiBases(renderableEventStore.defs,eventUiSingleBase,eventUiBySource),newState={dynamicOptionOverrides,currentViewType,currentDate,dateProfile,eventSources,eventStore,renderableEventStore,selectionConfig,eventUiBases,businessHours:this.parseContextBusinessHours(calendarContext),dateSelection:isInit?null:reduceDateSelection(prevState.dateSelection,action),eventSelection:isInit?"":reduceSelectedEvent(prevState.eventSelection,action),eventDrag:isInit?null:reduceEventDrag(prevState.eventDrag,action),eventResize:isInit?null:reduceEventResize(prevState.eventResize,action),nowDate},contextAndState={...calendarContext,...newState};for(let reducer of optionsData.pluginHooks.reducers)Object.assign(newState,reducer(prevState,action,contextAndState));let wasLoading=prevState?computeIsLoading(prevState,calendarContext):!1,isLoading=computeIsLoading(newState,calendarContext);!wasLoading&&isLoading?this.emitter.trigger("loading",!0):wasLoading&&!isLoading&&this.emitter.trigger("loading",!1);let viewTitle=this.buildTitle(dateProfile,currentViewData.options,optionsData.dateEnv),toolbarProps=this.buildToolbarProps(currentViewData.viewSpec,dateProfile,currentViewData.dateProfileGenerator,currentDate,nowDate,viewTitle),newData={viewTitle,nowManager:this.nowManager,calendarApi:config2.calendarApi,dispatch:this.dispatch,emitter:this.emitter,getCurrentData:this.getCurrentData,toolbarProps,...optionsData,...currentViewData,...newState},changeHandlers=optionsData.pluginHooks.optionChangeHandlers,prevCalendarOptions=prevData&&prevData.calendarOptions,newCalendarOptions=optionsData.calendarOptions;if(prevCalendarOptions&&prevCalendarOptions!==newCalendarOptions){prevCalendarOptions.timeZone!==newCalendarOptions.timeZone&&(newState.eventSources=newData.eventSources=reduceEventSourcesNewTimeZone(newData.eventSources,dateProfile,newData),newState.eventStore=newData.eventStore=rezoneEventStoreDates(newData.eventStore,prevData.dateEnv,newData.dateEnv),newState.renderableEventStore=newData.renderableEventStore=rezoneEventStoreDates(newData.renderableEventStore,prevData.dateEnv,newData.dateEnv));for(let optionName in changeHandlers)(this.optionsForHandling.indexOf(optionName)!==-1||prevCalendarOptions[optionName]!==newCalendarOptions[optionName])&&changeHandlers[optionName](newCalendarOptions[optionName],newData)}return this.optionsForHandling=[],{state:newState,data:newData,calendarContext}}computeOptionsData(optionOverrides,dynamicOptionOverrides,calendarApi){if(!this.optionsForRefining.length&&optionOverrides===this.stableOptionOverrides&&dynamicOptionOverrides===this.stableDynamicOptionOverrides)return this.stableCalendarOptionsData;let{refinedOptions,pluginHooks,localeDefaults,availableLocaleData}=this.processRawCalendarOptions(optionOverrides,dynamicOptionOverrides),dateEnv=this.buildDateEnv(refinedOptions.timeZone,refinedOptions.locale,refinedOptions.weekNumberCalculation,refinedOptions.firstDay,refinedOptions.weekTextLong,refinedOptions.weekTextShort,pluginHooks,availableLocaleData),viewSpecs=this.buildViewSpecs(pluginHooks.views,this.stableOptionOverrides,this.stableDynamicOptionOverrides),toolbarConfig=this.parseToolbars(refinedOptions,viewSpecs,calendarApi);return this.stableCalendarOptionsData={calendarOptions:refinedOptions,pluginHooks,dateEnv,viewSpecs,toolbarConfig,localeDefaults,availableRawLocales:availableLocaleData.map}}processRawCalendarOptions(optionOverrides,dynamicOptionOverrides){let{locales,locale}=mergeCalendarOptions(BASE_OPTION_DEFAULTS,optionOverrides,dynamicOptionOverrides),availableLocaleData=this.organizeRawLocales(locales),availableRawLocales=availableLocaleData.map,localeDefaults=this.buildLocale(locale||availableLocaleData.defaultCode,availableRawLocales).options,pluginHooks=this.buildPluginHooks(optionOverrides.plugins||[],globalPlugins),refiners=this.currentCalendarOptionsRefiners={...BASE_OPTION_REFINERS,...CALENDAR_LISTENER_REFINERS,...CALENDAR_ONLY_OPTION_REFINERS,...pluginHooks.listenerRefiners,...pluginHooks.optionRefiners},raw=mergeCalendarOptions(BASE_OPTION_DEFAULTS,...pluginHooks.optionDefaults,localeDefaults,filterKnownOptions(mergeCalendarOptions(optionOverrides,dynamicOptionOverrides),refiners)),refined={},currentRaw=this.currentCalendarOptionsInput,currentRefined=this.currentCalendarOptionsRefined,anyChanges=!1;for(let optionName in raw)this.optionsForRefining.indexOf(optionName)===-1&&(raw[optionName]===currentRaw[optionName]||COMPLEX_OPTION_COMPARATORS[optionName]&&optionName in currentRaw&&COMPLEX_OPTION_COMPARATORS[optionName](currentRaw[optionName],raw[optionName])||isMergedPropsEqual(currentRaw[optionName],raw[optionName]))?refined[optionName]=currentRefined[optionName]:refiners[optionName]&&(refined[optionName]=refiners[optionName](raw[optionName],optionName),anyChanges=!0);return anyChanges&&(this.currentCalendarOptionsInput=raw,this.currentCalendarOptionsRefined=refined,this.stableOptionOverrides=optionOverrides,this.stableDynamicOptionOverrides=dynamicOptionOverrides),this.optionsForHandling.push(...this.optionsForRefining),this.optionsForRefining=[],{rawOptions:this.currentCalendarOptionsInput,refinedOptions:this.currentCalendarOptionsRefined,pluginHooks,availableLocaleData,localeDefaults}}_computeCurrentViewData(viewType,optionsData,optionOverrides,dynamicOptionOverrides){let viewSpec=optionsData.viewSpecs[viewType];if(!viewSpec)throw new Error(`viewType "${viewType}" is not available. Please make sure you've loaded all neccessary plugins`);let{refinedOptions}=this.processRawViewOptions(viewSpec,optionsData.pluginHooks,optionsData.localeDefaults,optionOverrides,dynamicOptionOverrides);this.nowManager.handleInput(optionsData.dateEnv,refinedOptions.now);let dateProfileGenerator=this.buildDateProfileGenerator({dateProfileGeneratorClass:viewSpec.optionDefaults.dateProfileGeneratorClass,duration:viewSpec.duration,durationUnit:viewSpec.durationUnit,usesMinMaxTime:viewSpec.optionDefaults.usesMinMaxTime,dateEnv:optionsData.dateEnv,calendarApi:this.config.calendarApi,slotMinTime:refinedOptions.slotMinTime,slotMaxTime:refinedOptions.slotMaxTime,showNonCurrentDates:refinedOptions.showNonCurrentDates,dayCount:refinedOptions.dayCount,dateAlignment:refinedOptions.dateAlignment,dateIncrement:refinedOptions.dateIncrement,hiddenDays:refinedOptions.hiddenDays,weekends:refinedOptions.weekends,validRangeInput:refinedOptions.validRange,visibleRangeInput:refinedOptions.visibleRange,fixedWeekCount:refinedOptions.fixedWeekCount}),viewApi=this.buildViewApi(viewType,this.getCurrentData,optionsData.dateEnv);return{viewSpec,options:refinedOptions,dateProfileGenerator,viewApi}}processRawViewOptions(viewSpec,pluginHooks,localeDefaults,optionOverrides,dynamicOptionOverrides){let refiners={...BASE_OPTION_REFINERS,...CALENDAR_LISTENER_REFINERS,...CALENDAR_ONLY_OPTION_REFINERS,...VIEW_ONLY_OPTION_REFINERS,...pluginHooks.listenerRefiners,...pluginHooks.optionRefiners},raw=mergeCalendarOptions(BASE_OPTION_DEFAULTS,...pluginHooks.optionDefaults,viewSpec.optionDefaults,localeDefaults,filterKnownOptions(mergeCalendarOptions(optionOverrides,viewSpec.optionOverrides,dynamicOptionOverrides),refiners)),refined={},currentRaw=this.currentViewOptionsInput,currentRefined=this.currentViewOptionsRefined,anyChanges=!1;for(let optionName in raw)raw[optionName]===currentRaw[optionName]||COMPLEX_OPTION_COMPARATORS[optionName]&&COMPLEX_OPTION_COMPARATORS[optionName](raw[optionName],currentRaw[optionName])||isMergedPropsEqual(currentRaw[optionName],raw[optionName])?refined[optionName]=currentRefined[optionName]:(raw[optionName]===this.currentCalendarOptionsInput[optionName]||COMPLEX_OPTION_COMPARATORS[optionName]&&COMPLEX_OPTION_COMPARATORS[optionName](raw[optionName],this.currentCalendarOptionsInput[optionName])?optionName in this.currentCalendarOptionsRefined&&(refined[optionName]=this.currentCalendarOptionsRefined[optionName]):refiners[optionName]&&(refined[optionName]=refiners[optionName](raw[optionName],optionName)),anyChanges=!0);return anyChanges&&(this.currentViewOptionsInput=raw,this.currentViewOptionsRefined=refined),{rawOptions:this.currentViewOptionsInput,refinedOptions:this.currentViewOptionsRefined}}};function buildDateEnv(timeZone,explicitLocale,weekNumberCalculation,firstDay,weekTextLong,weekTextShort,pluginHooks,availableLocaleData){let locale=buildLocale(explicitLocale||availableLocaleData.defaultCode,availableLocaleData.map);return new DateEnv({calendarSystem:"gregory",timeZone,locale,weekNumberCalculation,firstDay,weekTextLong,weekTextShort,cmdFormatter:pluginHooks.cmdFormatter})}function buildDateProfileGenerator(props){let DateProfileGeneratorClass=props.dateProfileGeneratorClass||DateProfileGenerator;return new DateProfileGeneratorClass(props)}function buildViewApi(type,getCurrentData,dateEnv){return new ViewImpl(type,getCurrentData,dateEnv)}function buildEventUiBySource(eventSources){return mapHash(eventSources,eventSource=>eventSource.ui)}function buildEventUiBases(eventDefs,eventUiSingleBase,eventUiBySource){let eventUiBases={"":eventUiSingleBase};for(let defId in eventDefs){let def=eventDefs[defId];def.sourceId&&eventUiBySource[def.sourceId]&&(eventUiBases[defId]=eventUiBySource[def.sourceId])}return eventUiBases}function buildViewUiProps(calendarContext){let{options}=calendarContext;return{eventUiSingleBase:createEventUi({display:options.eventDisplay,editable:options.editable,startEditable:options.eventStartEditable,durationEditable:options.eventDurationEditable,constraint:options.eventConstraint,overlap:typeof options.eventOverlap=="boolean"?options.eventOverlap:void 0,allow:options.eventAllow},calendarContext),selectionConfig:createEventUi({constraint:options.selectConstraint,overlap:typeof options.selectOverlap=="boolean"?options.selectOverlap:void 0,allow:options.selectAllow},calendarContext)}}function computeIsLoading(state,context){for(let isLoadingFunc of context.pluginHooks.isLoadingFuncs)if(isLoadingFunc(state))return!0;return!1}function parseContextBusinessHours(calendarContext){return parseBusinessHours(calendarContext.options.businessHours,calendarContext)}var warnedUnknownOptions={};function filterKnownOptions(options,optionRefiners){let knownOptions={};for(let optionName in options)optionRefiners[optionName]?knownOptions[optionName]=options[optionName]:warnedUnknownOptions[optionName]||(warn(`Unknown option \`${optionName}\`.`),warnedUnknownOptions[optionName]=!0);return knownOptions}function buildToolbarProps(viewSpec,dateProfile,dateProfileGenerator,currentDate,nowDate,title){let todayInfo=dateProfileGenerator.build(nowDate,nowDate,void 0,!1),prevInfo=dateProfileGenerator.buildPrev(dateProfile,currentDate,nowDate,!1),nextInfo=dateProfileGenerator.buildNext(dateProfile,currentDate,nowDate,!1);return{title,selectedButton:viewSpec.type,navUnit:viewSpec.singleUnit,isTodayEnabled:todayInfo.isValid&&!rangeContainsMarker(dateProfile.currentRange,nowDate),isPrevEnabled:prevInfo.isValid,isNextEnabled:nextInfo.isValid}}var CalendarApiImpl=class{getCurrentData(){return this.currentDataManager.getCurrentData()}dispatch(action){this.currentDataManager.dispatch(action)}get view(){return this.getCurrentData().viewApi}batchRendering(callback){callback()}setOption(name,val){this.dispatch({type:"SET_OPTION",optionName:name,rawOptionValue:val})}getOption(name){return this.currentDataManager.currentCalendarOptionsInput[name]}getAvailableLocaleCodes(){return Object.keys(this.getCurrentData().availableRawLocales)}on(handlerName,handler){let{currentDataManager}=this;currentDataManager.currentCalendarOptionsRefiners[handlerName]?currentDataManager.emitter.on(handlerName,handler):warn(`Unknown listener \`${handlerName}\`.`)}off(handlerName,handler){this.currentDataManager.emitter.off(handlerName,handler)}trigger(handlerName,...args){this.currentDataManager.emitter.trigger(handlerName,...args)}changeView(viewType,dateOrRange){this.batchRendering(()=>{if(this.unselect(),dateOrRange)if(dateOrRange.start&&dateOrRange.end)this.dispatch({type:"CHANGE_VIEW_TYPE",viewType}),this.dispatch({type:"SET_OPTION",optionName:"visibleRange",rawOptionValue:dateOrRange});else{let{dateEnv}=this.getCurrentData();this.dispatch({type:"CHANGE_VIEW_TYPE",viewType,dateMarker:dateEnv.createMarker(dateOrRange)})}else this.dispatch({type:"CHANGE_VIEW_TYPE",viewType})})}zoomTo(dateMarker,viewType){let state=this.getCurrentData(),spec;viewType=viewType||"day",spec=state.viewSpecs[viewType]||this.getUnitViewSpec(viewType),this.unselect(),spec?this.dispatch({type:"CHANGE_VIEW_TYPE",viewType:spec.type,dateMarker}):this.dispatch({type:"CHANGE_DATE",dateMarker})}getUnitViewSpec(unit){let{viewSpecs,toolbarConfig}=this.getCurrentData(),viewTypes=[].concat(toolbarConfig.header?toolbarConfig.header.viewsWithButtons:[],toolbarConfig.footer?toolbarConfig.footer.viewsWithButtons:[]),i,spec;for(let viewType in viewSpecs)viewTypes.push(viewType);for(i=0;i<viewTypes.length;i+=1)if(spec=viewSpecs[viewTypes[i]],spec&&spec.singleUnit===unit)return spec;return null}prev(){this.unselect(),this.dispatch({type:"PREV"})}next(){this.unselect(),this.dispatch({type:"NEXT"})}prevYear(){let state=this.getCurrentData();this.unselect(),this.dispatch({type:"CHANGE_DATE",dateMarker:state.dateEnv.addYears(state.currentDate,-1)})}nextYear(){let state=this.getCurrentData();this.unselect(),this.dispatch({type:"CHANGE_DATE",dateMarker:state.dateEnv.addYears(state.currentDate,1)})}today(){let state=this.getCurrentData();this.unselect(),this.dispatch({type:"CHANGE_DATE",dateMarker:state.nowManager.getDateMarker()})}gotoDate(zonedDateInput){let state=this.getCurrentData();this.unselect(),this.dispatch({type:"CHANGE_DATE",dateMarker:state.dateEnv.createMarker(zonedDateInput)})}incrementDate(deltaInput){let state=this.getCurrentData(),delta=createDuration(deltaInput);delta&&(this.unselect(),this.dispatch({type:"CHANGE_DATE",dateMarker:state.dateEnv.add(state.currentDate,delta)}))}getDate(){let state=this.getCurrentData();return state.dateEnv.toDate(state.currentDate)}formatDate(d,formatter){let{dateEnv}=this.getCurrentData(),dateMeta=dateEnv.createMarkerMeta(d);return joinDateTimeFormatParts(dateEnv.formatToParts(dateMeta.marker,createFormatter(formatter),{instantMs:dateMeta.instantMs}))}formatRange(d0,d1,settings){let{dateEnv}=this.getCurrentData(),startMeta=dateEnv.createMarkerMeta(d0),endMeta=dateEnv.createMarkerMeta(d1);return joinDateTimeFormatParts(dateEnv.formatRangeToParts(startMeta.marker,endMeta.marker,createFormatter(settings),{isEndExclusive:settings.isEndExclusive,startInstantMs:startMeta.instantMs,endInstantMs:endMeta.instantMs}))}formatIso(d,omitTime){let{dateEnv}=this.getCurrentData();return dateEnv.formatIso(dateEnv.createMarker(d),{omitTime})}select(dateOrObj,endDate){let selectionInput;endDate==null?dateOrObj.start!=null?selectionInput=dateOrObj:selectionInput={start:dateOrObj,end:null}:selectionInput={start:dateOrObj,end:endDate};let state=this.getCurrentData(),selection=parseDateSpan(selectionInput,state.dateEnv,createDuration({days:1}));selection&&(this.dispatch({type:"SELECT_DATES",selection}),triggerDateSelect(selection,null,state))}unselect(pev){let state=this.getCurrentData();state.dateSelection&&(this.dispatch({type:"UNSELECT_DATES"}),triggerDateUnselect(pev,state))}addEvent(eventInput,sourceInput){if(eventInput instanceof EventImpl){let def=eventInput._def,instance=eventInput._instance;return this.getCurrentData().eventStore.defs[def.defId]||(this.dispatch({type:"ADD_EVENTS",eventStore:eventTupleToStore({def,instance})}),this.triggerEventAdd(eventInput)),eventInput}let state=this.getCurrentData(),eventSource;if(sourceInput instanceof EventSourceImpl)eventSource=sourceInput.internalEventSource;else if(typeof sourceInput=="boolean")sourceInput&&([eventSource]=hashValuesToArray(state.eventSources));else if(sourceInput!=null){let sourceApi=this.getEventSourceById(sourceInput);if(!sourceApi)return warn(`Unknown event source ID \`${sourceInput}\`.`),null;eventSource=sourceApi.internalEventSource}let tuple=parseEvent(eventInput,eventSource,state,!1);if(tuple){let newEventApi=new EventImpl(state,tuple.def,tuple.def.recurringDef?null:tuple.instance);return this.dispatch({type:"ADD_EVENTS",eventStore:eventTupleToStore(tuple)}),this.triggerEventAdd(newEventApi),newEventApi}return null}triggerEventAdd(eventApi){let{emitter}=this.getCurrentData();emitter.trigger("eventAdd",{event:eventApi,relatedEvents:[],revert:()=>{this.dispatch({type:"REMOVE_EVENTS",eventStore:eventApiToStore(eventApi)})}})}getEventById(id){let state=this.getCurrentData(),{defs,instances}=state.eventStore;id=String(id);for(let defId in defs){let def=defs[defId];if(def.publicId===id){if(def.recurringDef)return new EventImpl(state,def,null);for(let instanceId in instances){let instance=instances[instanceId];if(instance.defId===def.defId)return new EventImpl(state,def,instance)}}}return null}getEvents(){let currentData=this.getCurrentData();return buildEventApis(currentData.eventStore,currentData)}removeAllEvents(){this.dispatch({type:"REMOVE_ALL_EVENTS"})}getEventSources(){let state=this.getCurrentData(),sourceHash=state.eventSources,sourceApis=[];for(let internalId in sourceHash)sourceApis.push(new EventSourceImpl(state,sourceHash[internalId]));return sourceApis}getEventSourceById(id){let state=this.getCurrentData(),sourceHash=state.eventSources;id=String(id);for(let sourceId in sourceHash)if(sourceHash[sourceId].publicId===id)return new EventSourceImpl(state,sourceHash[sourceId]);return null}addEventSource(sourceInput){let state=this.getCurrentData();if(sourceInput instanceof EventSourceImpl)return state.eventSources[sourceInput.internalEventSource.sourceId]||this.dispatch({type:"ADD_EVENT_SOURCES",sources:[sourceInput.internalEventSource]}),sourceInput;let eventSource=parseEventSource(sourceInput,state);return eventSource?(this.dispatch({type:"ADD_EVENT_SOURCES",sources:[eventSource]}),new EventSourceImpl(state,eventSource)):null}removeAllEventSources(){this.dispatch({type:"REMOVE_ALL_EVENT_SOURCES"})}refetchEvents(){this.dispatch({type:"FETCH_EVENT_SOURCES",isRefetch:!0})}scrollToTime(timeInput){let time=createDuration(timeInput);time&&this.trigger("_timeScrollRequest",time)}getButtonState(){let currentData=this.getCurrentData(),{toolbarProps}=currentData,options=currentData.calendarOptions,buttonConfigs=options.buttons||{},viewSpecs=currentData.viewSpecs,currentUnit=currentData.viewSpec.singleUnit,currentHintOrdinal=[currentUnit?getSingleUnitText(currentUnit,options):"",currentUnit],buttonState={today:{text:options.todayText,hint:formatWithOrdinals(options.todayHint,currentHintOrdinal,options.todayText),isDisabled:!toolbarProps.isTodayEnabled},prev:{text:options.prevText,hint:formatWithOrdinals(options.prevHint,currentHintOrdinal,options.prevText),isDisabled:!toolbarProps.isPrevEnabled},next:{text:options.nextText,hint:formatWithOrdinals(options.nextHint,currentHintOrdinal,options.nextText),isDisabled:!toolbarProps.isNextEnabled},prevYear:{text:options.prevYearText,hint:formatWithOrdinals(options.prevHint,[options.yearText,"year"],options.prevYearText),isDisabled:!1},nextYear:{text:options.prevYearText,hint:formatWithOrdinals(options.nextHint,[options.yearText,"year"],options.nextYearText),isDisabled:!1}};for(let viewSpecName in viewSpecs){let viewSpec=viewSpecs[viewSpecName],{singleUnit}=viewSpec,buttonTextKey=viewSpec.optionDefaults.buttonTextKey,buttonText=buttonConfigs[viewSpecName]?.text||(buttonTextKey?options[buttonTextKey]:"")||(singleUnit?getSingleUnitText(singleUnit,options):"")||viewSpecName,buttonHint=formatWithOrdinals(options.viewHint,[buttonText,viewSpecName],buttonText);buttonState[viewSpecName]={text:buttonText,hint:buttonHint}}return buttonState}};function getSingleUnitText(singleUnit,options){return options[singleUnit+"TextLong"]||options[singleUnit+"Text"]}var CalendarMediaRoot=class extends Component2{constructor(){super(...arguments),this.state={forPrint:!1},this.handleBeforePrint=()=>{flushSyncWithSizeBatching(()=>{this.setState({forPrint:!0})})},this.handleAfterPrint=()=>{this.setState({forPrint:!1})}}render(){return this.props?.children(this.state.forPrint)}componentDidMount(){let{props}=this,{emitter}=props;emitter.on("_beforeprint",this.handleBeforePrint),emitter.on("_afterprint",this.handleAfterPrint)}componentWillUnmount(){let{props}=this,{emitter}=props;emitter.off("_beforeprint",this.handleBeforePrint),emitter.off("_afterprint",this.handleAfterPrint)}};function computeRootClassName(options,forPrint){let borderlessX=options.borderlessX??options.borderless,borderlessTop=options.borderlessTop??options.borderless,borderlessBottom=options.borderlessBottom??options.borderless,calendarDisplayData={borderlessX:!!borderlessX,borderlessTop:!!borderlessTop,borderlessBottom:!!borderlessBottom};return joinClassNames(generateClassName(options.class,calendarDisplayData),generateClassName(options.className,calendarDisplayData),classNames.borderBoxRoot,classNames.isolate,classNames.flexCol,forPrint?classNames.calendarPrintRoot:classNames.calendarScreenRoot)}var ButtonIcon=class extends BaseComponent{render(){let{contentGenerator,className}=this.props;if(contentGenerator)return jsx8(ContentContainer,{tag:"span",style:{display:"contents"},attrs:{"aria-hidden":!0},renderProps:{},generatorName:void 0,customGenerator:contentGenerator});if(className!==void 0)return jsx8("span",{"aria-hidden":!0,className})}},ToolbarSection=class extends BaseComponent{render(){let{props}=this,{options}=this.context,children=props.widgetGroups.map(widgetGroup=>this.renderWidgetGroup(widgetGroup));return createElement3("div",{className:generateClassName(options.toolbarSectionClass,{name:props.name})},...children)}renderWidgetGroup(widgetGroup){let{props,context}=this,{options}=context,children=[],isOnlyButtons=!0,isOnlyView=!0;for(let widget of widgetGroup){let{name,isView}=widget;name==="title"?isOnlyButtons=!1:isView||(isOnlyView=!1)}for(let widget of widgetGroup){let{name,customElement,buttonHint}=widget;if(name==="title")children.push(jsx8("div",{role:"heading","aria-level":options.headingLevel,id:props.titleId,className:joinClassNames(options.toolbarTitleClass),children:props.title}));else if(customElement)children.push(jsx8(ContentContainer,{tag:"span",style:{display:"contents"},renderProps:{},generatorName:void 0,customGenerator:customElement}));else{let isSelected=name===props.selectedButton,isDisabled=!props.isTodayEnabled&&name==="today"||!props.isPrevEnabled&&name==="prev"||!props.isNextEnabled&&name==="next",buttonDisplay=widget.buttonDisplay??options.buttonDisplay;buttonDisplay==="auto"&&(buttonDisplay=widget.buttonIconContent||widget.buttonIconClass?"icon":"text");let iconNode;buttonDisplay!=="text"&&(iconNode=jsx8(ButtonIcon,{className:widget.buttonIconClass,contentGenerator:widget.buttonIconContent}));let inGroup=widgetGroup.length>1&&isOnlyButtons,buttonGroup=inGroup?{hasSelection:isOnlyView}:null,renderProps={name,text:widget.buttonText,isPrimary:widget.buttonIsPrimary,isSelected,isDisabled,isIconOnly:buttonDisplay==="icon",buttonGroup};children.push(jsx8(ContentContainer,{tag:"button",attrs:{type:"button",disabled:isDisabled,...isOnlyButtons&&isOnlyView?{role:"tab","aria-selected":isSelected}:{"aria-pressed":isSelected},"aria-label":typeof buttonHint=="function"?buttonHint(props.navUnit):buttonHint,onClick:widget.buttonClick},className:joinClassNames(generateClassName(options.buttonClass,renderProps),!isDisabled&&classNames.cursorPointer,inGroup&&joinClassNames(isSelected?classNames.z1:classNames.z0,classNames.focusZ2)),renderProps,generatorName:void 0,classNameGenerator:widget.buttonClass,didMount:widget.buttonDidMount,willUnmount:widget.buttonWillUnmount,children:()=>buttonDisplay==="text"?widget.buttonText:buttonDisplay==="icon"?iconNode:buttonDisplay==="icon-text"?jsxs6(Fragment4,{children:[iconNode,widget.buttonText]}):jsxs6(Fragment4,{children:[widget.buttonText,iconNode]})}))}}return children.length>1?createElement3("div",{role:isOnlyButtons&&isOnlyView?"tablist":void 0,"aria-label":isOnlyButtons&&isOnlyView?options.viewChangeHint:void 0,className:joinClassNames(generateClassName(options.buttonGroupClass,{hasSelection:isOnlyView}),classNames.isolate)},...children):children[0]}},Toolbar=class extends BaseComponent{render(){let{props}=this,options=this.context.options,{sectionWidgets}=props.model,{borderlessX,borderlessTop,borderlessBottom}=computeViewBorderless(options),toolbarClassOption=props.isHeader?options.headerToolbarClass:options.footerToolbarClass;return jsxs6("div",{className:joinClassNames(generateClassName(toolbarClassOption,{borderlessX,borderlessTop,borderlessBottom}),generateClassName(options.toolbarClass,{borderlessX,borderlessTop,borderlessBottom})),children:[this.renderSection("start",sectionWidgets.start),this.renderSection("center",sectionWidgets.center),this.renderSection("end",sectionWidgets.end)]})}renderSection(name,widgetGroups){let{props}=this;return jsx8(ToolbarSection,{name,widgetGroups,title:props.title,titleId:props.titleId,navUnit:props.navUnit,selectedButton:props.selectedButton,isTodayEnabled:props.isTodayEnabled,isPrevEnabled:props.isPrevEnabled,isNextEnabled:props.isNextEnabled},name)}},EventClicking=class extends Interaction{constructor(settings){super(settings),this.handleSegClick=(ev,segEl)=>{let{component}=this,{context}=component,eventRange=getElEventRange(segEl);eventRange&&component.isValidSegDownEl(ev.target)&&context.emitter.trigger("eventClick",{el:segEl,event:new EventImpl(component.context,eventRange.def,eventRange.instance),jsEvent:ev,view:context.viewApi})},this.destroy=listenBySelector(settings.el,"click",`.${classNames.internalEvent}`,this.handleSegClick)}},EventHovering=class extends Interaction{constructor(settings){super(settings),this.handleEventElRemove=el=>{el===this.currentSegEl&&this.handleSegLeave(null,this.currentSegEl)},this.handleSegEnter=(ev,segEl)=>{getElEventRange(segEl)&&(this.currentSegEl=segEl,this.triggerEvent("eventMouseEnter",ev,segEl))},this.handleSegLeave=(ev,segEl)=>{this.currentSegEl&&(this.currentSegEl=null,this.triggerEvent("eventMouseLeave",ev,segEl))},this.removeHoverListeners=listenToHoverBySelector(settings.el,`.${classNames.internalEvent}`,this.handleSegEnter,this.handleSegLeave)}destroy(){this.removeHoverListeners()}triggerEvent(publicEvName,ev,segEl){let{component}=this,{context}=component,eventRange=getElEventRange(segEl);(!ev||component.isValidSegDownEl(ev.target))&&context.emitter.trigger(publicEvName,{el:segEl,event:new EventImpl(context,eventRange.def,eventRange.instance),jsEvent:ev,view:context.viewApi})}},CalendarInner=class extends PureComponent{constructor(){super(...arguments),this.buildViewContext=memoize2(buildViewContext),this.buildViewPropTransformers=memoize2(buildViewPropTransformers),this.interactionsStore={},this.calendarInteractions=[],this.registerInteractiveComponent=(component,settingsInput)=>{let settings=parseInteractionSettings(component,settingsInput),interactionClasses=[EventClicking,EventHovering];settingsInput.disableHits||(interactionClasses=interactionClasses.concat(this.props.pluginHooks.componentInteractions));let interactions=interactionClasses.map(TheInteractionClass=>new TheInteractionClass(settings));this.interactionsStore[component.uid]=interactions,interactionSettingsStore[component.uid]=settings},this.unregisterInteractiveComponent=component=>{let listeners=this.interactionsStore[component.uid];if(listeners){for(let listener of listeners)listener.destroy();delete this.interactionsStore[component.uid]}delete interactionSettingsStore[component.uid]}}get viewTitleId(){return this.props.baseId+"title"}render(){let{props}=this,{toolbarConfig,options}=props,viewHeight,viewHeightLiquid=!1,viewAspectRatio;props.forPrint||getIsHeightAuto(options)||(options.height!=null?viewHeightLiquid=!0:options.contentHeight!=null?viewHeight=options.contentHeight:viewAspectRatio=Math.max(options.aspectRatio,.5));let viewContext=this.buildViewContext(props.viewSpec,props.viewApi,props.options,props.dateProfileGenerator,props.dateEnv,props.nowManager,props.pluginHooks,props.dispatch,props.getCurrentData,props.emitter,props.calendarApi,props.baseId,this.registerInteractiveComponent,this.unregisterInteractiveComponent);return jsxs6(ViewContextType.Provider,{value:viewContext,children:[toolbarConfig.header&&jsx8(Toolbar,{model:toolbarConfig.header,isHeader:!0,titleId:this.viewTitleId,...props.toolbarProps}),jsxs6("div",{className:joinClassNames(classNames.flexCol,classNames.rel,classNames.overflowAnchorNone,classNames.minHeight0,viewHeightLiquid&&classNames.liquid),style:{height:viewHeight,aspectRatio:viewAspectRatio!=null?String(viewAspectRatio):void 0},children:[this.renderView(joinClassNames((viewHeightLiquid||viewHeight)&&classNames.liquid,viewAspectRatio!=null&&classNames.fill,classNames.internalView)),this.buildAppendContent()]}),toolbarConfig.footer&&jsx8(Toolbar,{model:toolbarConfig.footer,isHeader:!1,...props.toolbarProps})]})}renderView(className){let{props}=this,{pluginHooks,viewSpec,toolbarConfig,toolbarProps}=props,viewProps={className,dateProfile:props.dateProfile,businessHours:props.businessHours,eventStore:props.renderableEventStore,eventUiBases:props.eventUiBases,dateSelection:props.dateSelection,eventSelection:props.eventSelection,eventDrag:props.eventDrag,eventResize:props.eventResize,forPrint:props.forPrint,labelId:toolbarConfig.header&&toolbarConfig.header.hasTitle?this.viewTitleId:void 0,labelStr:toolbarConfig.header&&toolbarConfig.header.hasTitle?void 0:toolbarProps.title},transformers=this.buildViewPropTransformers(pluginHooks.viewPropsTransformers),contentProps={...props,toolbarProps,forPrint:props.forPrint};for(let transformer of transformers)Object.assign(viewProps,transformer.transform(viewProps,contentProps));let ViewComponent=viewSpec.component;return jsx8(ViewComponent,{...viewProps})}buildAppendContent(){let{props}=this;return jsx8(Fragment4,{children:props.pluginHooks.viewContainerAppends.map((buildAppendContent,i)=>jsx8(Fragment$1,{children:buildAppendContent(props)},i))})}componentDidMount(){let{props}=this;this.calendarInteractions=props.pluginHooks.calendarInteractions.map(CalendarInteractionClass=>new CalendarInteractionClass(props));let{propSetHandlers}=props.pluginHooks;for(let propName in propSetHandlers)propSetHandlers[propName](props[propName],props);for(let callback of props.pluginHooks.contextInit)callback(props)}componentDidUpdate(prevProps){let{props}=this,{propSetHandlers}=props.pluginHooks;for(let propName in propSetHandlers)props[propName]!==prevProps[propName]&&propSetHandlers[propName](props[propName],props)}componentWillUnmount(){let{props}=this;for(let interaction of this.calendarInteractions)interaction.destroy();this.calendarInteractions=[],props.emitter.trigger("_unmount")}};function buildViewPropTransformers(theClasses){return theClasses.map(TheClass=>new TheClass)}var Calendar=forwardRef2((props,ref)=>{let baseId=useStableId(props.id),[_revision,setRevision]=useState4("");function handleDataChange(_data,actions){(needsSyncRender(actions)?flushSync2:runNormal)(()=>{setRevision(guid())})}let[calendarApi]=useState4(()=>new CalendarApiImpl),[calendarDataManager]=useState4(()=>new CalendarDataManager({calendarApi,onDataChange:handleDataChange}));useEffect3(()=>()=>{calendarDataManager.destroy()},[]),useImperativeHandle(ref,()=>({getApi:()=>calendarApi}),[]);let data=calendarDataManager.update(props);return jsx9(CalendarMediaRoot,{emitter:data.emitter,children:forPrint=>{let options=data.calendarOptions,isRtl=options.direction==="rtl",className=computeRootClassName(options,forPrint);return jsx9("div",{dir:isRtl?"rtl":void 0,className,style:{height:options.height},"data-color-scheme":options.colorScheme||void 0,children:jsx9(CalendarInner,{...data,baseId,forPrint})})}})});function needsSyncRender(actions){for(let action of actions)if(action.type==="SET_EVENT_DRAG"||action.type==="UNSET_EVENT_DRAG"||action.type==="SET_EVENT_RESIZE"||action.type==="UNSET_EVENT_RESIZE"||action.type==="MERGE_EVENTS")return!0;return!1}function runNormal(f){f()}var warnedStableId=!1;function useStableId(fallbackId){if(React.useId)return React.useId();let[uid]=useState4(()=>guid());return fallbackId?fallbackId+":":(warnedStableId||(warnedStableId=!0,warn("Missing `id` prop. Provide one for better SSR support in React 17.")),`fc:${uid}:`)}function useCalendarController(){let handleDateChange=useCallback6(()=>{setControllerWrap({controller:controllerWrap.controller})},[]),[controllerWrap,setControllerWrap]=useState5(()=>({controller:new CalendarController(handleDateChange)}));return controllerWrap.controller}import{jsx as jsx13}from"react/jsx-runtime";import{Component as Component3}from"react";import{jsx as jsx10,jsxs as jsxs7,Fragment as Fragment5}from"react/jsx-runtime";function getAppendableRoot(el){let root=el.getRootNode();return root instanceof Document?root.body||root.documentElement:root}function computeElIsRtl(el){return getComputedStyle(el).direction==="rtl"}var PIXEL_PROP_RE=/(top|left|right|bottom|width|height)$/i;function applyStyle(el,props){for(let propName in props)applyStyleProp(el,propName,props[propName])}function applyStyleProp(el,name,val){val==null?el.style[name]="":typeof val=="number"&&PIXEL_PROP_RE.test(name)?el.style[name]=`${val}px`:el.style[name]=val}function getEventTargetViaRoot(ev){return ev.composedPath?.()[0]??ev.target}var NowTimer=class extends Component3{constructor(props,context){super(props,context),this.handleChange=()=>{this.forceUpdate()},this.runner=new NowTimerRunner(this.handleChange)}render(){let{props,context}=this,{nowDate,nowMs,todayRange}=this.runner.update({nowManager:context.nowManager,unit:props.unit,unitValue:props.unitValue,nowIndicatorSnap:context.options.nowIndicatorSnap,dateEnv:context.dateEnv});return props.children(nowDate,todayRange,nowMs)}componentWillUnmount(){this.runner.destroy()}};NowTimer.contextType=ViewContextType;var FULL_DATE_FORMAT=createFormatter({year:"numeric",month:"long",day:"numeric"}),WEEK_FORMAT=createFormatter({week:"long"}),WEEKDAY_ONLY_FORMAT=createFormatter({weekday:"long"});function findWeekdayText(parts){for(let part of parts)if(part.type==="weekday")return part.value;return""}function findDayNumberText(parts){for(let part of parts)if(part.type==="day")return part.value;return""}function findMonthText(parts){for(let part of parts)if(part.type==="month")return part.value;return""}function buildDateStr(context,dateMarker,viewType="day"){return joinDateTimeFormatParts(context.dateEnv.formatToParts(dateMarker,viewType==="week"?WEEK_FORMAT:FULL_DATE_FORMAT))}function buildNavLinkAttrs(context,dateMarker,viewType="day",dateStr=buildDateStr(context,dateMarker,viewType),isTabbable=!0){let{dateEnv,options,calendarApi}=context,zonedDate=dateEnv.toDate(dateMarker),handleInteraction=ev=>{let customAction=viewType==="day"?options.navLinkDayClick:viewType==="week"?options.navLinkWeekClick:null;typeof customAction=="function"?customAction.call(calendarApi,dateEnv.toDate(dateMarker),ev):(typeof customAction=="string"&&(viewType=customAction),calendarApi.zoomTo(dateMarker,viewType))};return{role:"link","aria-label":formatWithOrdinals(options.navLinkHint,[dateStr,zonedDate],dateStr),className:joinClassNames(options.navLinkClass,classNames.cursorPointer,classNames.internalNavLink),...isTabbable?createAriaClickAttrs(handleInteraction):{onClick:handleInteraction}}}function getDateMeta(dateMarker,dateEnv,dateProfile,todayRange,nowDate){let isDisabled=!!(dateProfile&&(!dateProfile.activeRange||!rangeContainsMarker(dateProfile.activeRange,dateMarker)));return{date:dateEnv.toDate(dateMarker),dow:dateMarker.getUTCDay(),isDisabled,isOther:!isDisabled&&!!(dateProfile&&!rangeContainsMarker(dateProfile.currentRange,dateMarker)),isToday:!isDisabled&&!!(todayRange&&rangeContainsMarker(todayRange,dateMarker)),isPast:!isDisabled&&!!(nowDate?dateMarker<nowDate:todayRange&&dateMarker<todayRange.start),isFuture:!isDisabled&&!!(nowDate?dateMarker>nowDate:todayRange&&dateMarker>=todayRange.end)}}var ViewContainer=class extends BaseComponent{constructor(){super(...arguments),this.refineRenderProps=memoizeObjArg(refineRenderProps)}render(){let{props,context}=this,{options,viewSpec}=context,renderProps=this.refineRenderProps({...computeViewBorderless(options),options:{headerToolbar:options.headerToolbar,footerToolbar:options.footerToolbar},isHeightAuto:getIsHeightAuto(options),viewApi:context.viewApi});return jsx10(ContentContainer,{elRef:props.elRef,tag:props.tag||"div",attrs:props.attrs,style:props.style,className:joinClassNames(props.className,generateClassName(options.viewClass,renderProps),generateClassName(viewSpec.optionDefaults.class,renderProps),generateClassName(viewSpec.optionDefaults.className,renderProps),generateClassName(viewSpec.optionOverrides.class,renderProps),generateClassName(viewSpec.optionOverrides.className,renderProps)),renderProps,generatorName:void 0,didMount:options.didMount||options.viewDidMount,willUnmount:options.willUnmount||options.viewWillUnmount,children:()=>props.children})}};function refineRenderProps(raw){return{view:raw.viewApi,borderlessX:raw.borderlessX,borderlessTop:raw.borderlessTop,borderlessBottom:raw.borderlessBottom,options:raw.options,isHeightAuto:raw.isHeightAuto}}var DateComponent=class extends BaseComponent{constructor(){super(...arguments),this.uid=guid()}prepareHits(){}queryHit(isRtl,positionLeft,positionTop,elWidth,elHeight){return null}isValidSegDownEl(el){return!this.props.eventDrag&&!this.props.eventResize&&!el.closest(`.${classNames.internalEventMirror}`)}isValidDateDownEl(el){return!el.closest(`.${classNames.internalEvent}:not(.${classNames.internalBgEvent})`)&&!el.closest(`.${classNames.internalMoreLink}`)&&!el.closest(`.${classNames.internalNavLink}`)&&!el.closest(`.${classNames.internalPopover}`)}},DelayedRunner=class{constructor(drainedOption){this.drainedOption=drainedOption,this.isRunning=!1,this.isDirty=!1,this.pauseDepths={},this.timeoutId=0}request(delay){this.isDirty=!0,this.isPaused()||(this.clearTimeout(),delay==null?this.tryDrain():this.timeoutId=setTimeout(this.tryDrain.bind(this),delay))}pause(scope=""){let{pauseDepths}=this;pauseDepths[scope]=(pauseDepths[scope]||0)+1,this.clearTimeout()}resume(scope="",force){let{pauseDepths}=this;scope in pauseDepths&&(force?delete pauseDepths[scope]:(pauseDepths[scope]-=1,pauseDepths[scope]<=0&&delete pauseDepths[scope]),this.tryDrain())}isPaused(){return Object.keys(this.pauseDepths).length}tryDrain(){if(!this.isRunning&&!this.isPaused()){for(this.isRunning=!0;this.isDirty;)this.isDirty=!1,this.drained();this.isRunning=!1}}clear(){this.clearTimeout(),this.isDirty=!1,this.pauseDepths={}}clearTimeout(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=0)}drained(){this.drainedOption&&this.drainedOption()}},ScrollListener=class{constructor(el){this.el=el,this.emitter=new Emitter,this.isScroll=!1,this.isScrollRecent=!1,this.isWheelRecent=!1,this.isMouseDown=!1,this.isTouchDown=!1,this.isMouse=!1,this.isTouch=!1,this.isWheel=!1,this.handleScroll=()=>{this.isScrollRecent=!0,this.isMouseDown&&(this.isMouse=!0),this.isTouchDown&&(this.isTouch=!0),this.isWheelRecent&&(this.isWheel=!0),this.startScroll(),this.emitter.trigger("scroll",this.getIsDevice()),this.scrollWaiter.request(500)},this.handleScrollWait=()=>{this.isScrollRecent=!1,this.isTouchDown||this.endScroll()},this.handleWheel=()=>{this.isWheelRecent=!0,this.wheelWaiter.request(500)},this.handleWheelWait=()=>{this.isWheelRecent=!1},this.handleMouseDown=()=>{this.isMouseDown=!0},this.handleMouseUp=()=>{this.isMouseDown=!1},this.handleTouchStart=()=>{this.isTouchDown=!0},this.handleTouchEnd=()=>{this.isTouchDown=!1,this.isScrollRecent||this.endScroll()},this.wheelWaiter=new DelayedRunner(this.handleWheelWait),this.scrollWaiter=new DelayedRunner(this.handleScrollWait),el.addEventListener("scroll",this.handleScroll,{passive:!0}),el.addEventListener("wheel",this.handleWheel,{passive:!0}),el.addEventListener("mousedown",this.handleMouseDown),el.addEventListener("mouseup",this.handleMouseUp),el.addEventListener("touchstart",this.handleTouchStart,{passive:!0}),el.addEventListener("touchend",this.handleTouchEnd)}destroy(){let{el}=this;el.removeEventListener("scroll",this.handleScroll,{passive:!0}),el.removeEventListener("wheel",this.handleWheel,{passive:!0}),el.removeEventListener("mousedown",this.handleMouseDown),el.removeEventListener("mouseup",this.handleMouseUp),el.removeEventListener("touchstart",this.handleTouchStart,{passive:!0}),el.removeEventListener("touchend",this.handleTouchEnd)}startScroll(){this.isScroll||(this.isScroll=!0,this.emitter.trigger("scrollStart",this.getIsDevice()))}endScroll(){this.isScroll&&(this.scrollWaiter.clear(),this.wheelWaiter.clear(),this.isScroll=!1,this.isWheelRecent=!1,this.emitter.trigger("scrollEnd",this.getIsDevice()),this.isMouse=!1,this.isTouch=!1,this.isWheel=!1)}getIsDevice(){return this.isWheel||this.isMouse||this.isTouch}},Scroller=class extends DateComponent{constructor(){super(...arguments),this.handleEl=el=>{this.el&&(this.el=null,this._isUnmounting=!0,this.listener.destroy()),el&&(this.el=el,this._isUnmounting=!1,this.listener=new ScrollListener(el))},this.handleHRuler=el=>{this.disconnectHRuler&&(this.disconnectHRuler(),this.disconnectHRuler=void 0,this.clientWidth!==void 0&&(this.clientWidth=void 0,setRef(this.props.clientWidthRef,null))),el&&(this.disconnectHRuler=watchWidth(el,clientWidth=>{this._isUnmounting||clientWidth!==this.clientWidth&&(this.clientWidth=clientWidth,setRef(this.props.clientWidthRef,clientWidth))}))},this.handleVRuler=el=>{this.disconnectVRuler&&(this.disconnectVRuler(),this.disconnectVRuler=void 0,this.clientHeight!==void 0&&(this.clientHeight=void 0,setRef(this.props.clientHeightRef,null))),el&&(this.disconnectVRuler=watchHeight(el,clientHeight=>{if(this._isUnmounting)return;clientHeight!==this.clientHeight&&(this.clientHeight=clientHeight,setRef(this.props.clientHeightRef,clientHeight));let bottomScrollbarWidth=Math.round(this.el.getBoundingClientRect().height-clientHeight);bottomScrollbarWidth!==this.bottomScrollbarWidth&&(this.bottomScrollbarWidth=bottomScrollbarWidth,setRef(this.props.bottomScrollbarWidthRef,bottomScrollbarWidth))}))}}render(){let{props}=this,fallbackOverflow=props.horizontal||props.vertical?"hidden":"";return jsxs7("div",{ref:this.handleEl,className:joinClassNames(props.className,classNames.noPadding,classNames.rel,props.hideScrollbars&&classNames.noScrollbars,classNames.internalScroller),style:{...props.style,overflowX:props.horizontal?"auto":fallbackOverflow,overflowY:props.vertical?"auto":fallbackOverflow},children:[props.children,!!props.clientWidthRef&&jsx10("div",{ref:this.handleHRuler,className:classNames.fillTop}),!!(props.clientHeightRef||props.bottomScrollbarWidthRef)&&jsx10("div",{ref:this.handleVRuler,className:classNames.fillStart})]})}endScroll(){this.listener.endScroll()}get x(){let{el}=this;return el?getNormalizedScrollX(el):0}get y(){let{el}=this;return el?el.scrollTop:0}scrollTo({x:x2,y}){let{el}=this;el&&(y!=null&&(el.scrollTop=y),x2!=null&&setNormalizedScrollX(el,x2))}addScrollStartListener(handler){this.listener.emitter.on("scrollStart",handler)}removeScrollStartListener(handler){this.listener.emitter.off("scrollStart",handler)}addScrollEndListener(handler){this.listener.emitter.on("scrollEnd",handler)}removeScrollEndListener(handler){this.listener.emitter.off("scrollEnd",handler)}};function getNormalizedScrollX(el){let{scrollLeft}=el;return computeElIsRtl(el)?getNormalizedRtlScrollX(scrollLeft,el):scrollLeft}function setNormalizedScrollX(el,x2){let isRtl=computeElIsRtl(el);el.scrollLeft=isRtl?getNormalizedRtlScrollLeft(x2,el):x2}function getNormalizedRtlScrollX(scrollLeft,el){switch(getRtlScrollerSystem()){case"positive":return el.scrollWidth-el.clientWidth-scrollLeft;case"negative":return-scrollLeft}return scrollLeft}function getNormalizedRtlScrollLeft(x2,el){switch(getRtlScrollerSystem()){case"positive":return el.scrollWidth-el.clientWidth-x2;case"negative":return-x2}return x2}var _rtlScrollerSystem;function getRtlScrollerSystem(){return _rtlScrollerSystem||(_rtlScrollerSystem=detectRtlScrollerSystem())}function detectRtlScrollerSystem(){let el=document.createElement("div");el.style.position="absolute",el.style.top="-1000px",el.style.width="100px",el.style.height="100px",el.style.overflow="scroll",el.style.direction="rtl";let innerEl=document.createElement("div");innerEl.style.width="200px",innerEl.style.height="200px",el.appendChild(innerEl),document.body.appendChild(el);let system;return el.scrollLeft>0?system="positive":(el.scrollLeft=50,el.scrollLeft>0?system="reverse":system="negative"),el.remove(),system}var StandardEvent=class extends BaseComponent{constructor(){super(...arguments),this.buildPublicEvent=memoize2((context,eventDef,eventInstance)=>new EventImpl(context,eventDef,eventInstance)),this.handleEl=el=>{this.el=el,setRef(this.props.elRef,el),el&&setElEventRange(el,this.props.eventRange)}}render(){let{props,context}=this,{options}=context,{eventRange}=props,eventUi=eventRange.ui,timeFormat=options.eventTimeFormat||props.defaultTimeFormat,timeText=props.forcedTimeText??buildEventRangeTimeText(timeFormat,eventRange,props.slicedStart,props.slicedEnd,props.isStart,props.isEnd,context,props.defaultDisplayEventTime,props.defaultDisplayEventEnd),[tag,attrs,isInteractive]=getEventTagAndAttrs(eventRange,context),eventApi=this.buildPublicEvent(context,eventRange.def,eventRange.instance),isDraggable=!props.disableDragging&&computeEventRangeDraggable(eventRange,context),isBlock=/row|column/.test(props.display),subcontentRenderProps={event:eventApi,isNarrow:props.isNarrow||!1,isShort:props.isShort||!1,timeText},renderProps={event:eventApi,view:context.viewApi,timeText,color:eventUi.color||options.eventColor,contrastColor:eventUi.contrastColor||options.eventContrastColor,isDraggable,isStartResizable:!props.disableResizing&&props.isStart&&eventUi.durationEditable&&options.eventResizableFromStart,isEndResizable:!props.disableResizing&&props.isEnd&&eventUi.durationEditable,isMirror:props.isMirror,isStart:!!props.isStart,isEnd:!!props.isEnd,isFirst:!!props.isFirst,isLast:!!props.isLast,isPast:!!props.isPast,isFuture:!!props.isFuture,isToday:!!props.isToday,isSelected:!!props.isSelected,isDragging:!!props.isDragging,isResizing:!!props.isResizing,isInteractive,isNarrow:props.isNarrow||!1,isShort:props.isShort||!1,level:props.level||0,timeClass:joinClassNames(generateClassName(options.eventTimeClass,subcontentRenderProps),isBlock&&generateClassName(options.blockEventTimeClass,subcontentRenderProps),props.display==="row"&&generateClassName(options.rowEventTimeClass,subcontentRenderProps),props.display==="column"&&generateClassName(options.columnEventTimeClass,subcontentRenderProps),props.display==="list-item"&&generateClassName(options.listItemEventTimeClass,subcontentRenderProps)),titleClass:joinClassNames(generateClassName(options.eventTitleClass,subcontentRenderProps),isBlock&&generateClassName(options.blockEventTitleClass,subcontentRenderProps),props.display==="row"&&generateClassName(options.rowEventTitleClass,subcontentRenderProps),props.display==="column"&&generateClassName(options.columnEventTitleClass,subcontentRenderProps),props.display==="list-item"&&generateClassName(options.listItemEventTitleClass,subcontentRenderProps),props.display==="row"&&options.rowEventTitleSticky&&classNames.stickyS,props.display==="column"&&options.columnEventTitleSticky&&classNames.stickyT),options:{eventOverlap:!!options.eventOverlap}},outerClassName=joinClassNames(isBlock&&generateClassName(options.blockEventClass,renderProps),props.display==="row"&&generateClassName(options.rowEventClass,renderProps),props.display==="column"&&generateClassName(options.columnEventClass,renderProps),props.display==="list-item"&&generateClassName(options.listItemEventClass,renderProps),eventUi.className,props.className,props.display==="column"?classNames.flexCol:classNames.flexRow,(eventRange.def.url||isDraggable)&&classNames.cursorPointer,classNames.internalEvent,props.isMirror&&classNames.internalEventMirror,isDraggable&&classNames.internalEventDraggable,renderProps.isSelected&&classNames.internalEventSelected,(renderProps.isStartResizable||renderProps.isEndResizable)&&classNames.internalEventResizable),beforeClassName=joinClassNames(generateClassName(options.eventBeforeClass,renderProps),isBlock&&generateClassName(options.blockEventBeforeClass,renderProps),props.display==="row"&&generateClassName(options.rowEventBeforeClass,renderProps),props.display==="column"&&generateClassName(options.columnEventBeforeClass,renderProps),props.display==="list-item"&&generateClassName(options.listItemEventBeforeClass,renderProps)),afterClassName=joinClassNames(generateClassName(options.eventAfterClass,renderProps),isBlock&&generateClassName(options.blockEventAfterClass,renderProps),props.display==="row"&&generateClassName(options.rowEventAfterClass,renderProps),props.display==="column"&&generateClassName(options.columnEventAfterClass,renderProps),props.display==="list-item"&&generateClassName(options.listItemEventAfterClass,renderProps)),innerClassName=joinClassNames(generateClassName(options.eventInnerClass,renderProps),isBlock&&generateClassName(options.blockEventInnerClass,renderProps),props.display==="row"&&generateClassName(options.rowEventInnerClass,renderProps),props.display==="column"&&generateClassName(options.columnEventInnerClass,renderProps),props.display==="list-item"&&generateClassName(options.listItemEventInnerClass,renderProps),!props.disableLiquid&&classNames.liquid),beforeContent=props.display==="row"&&options.rowEventBeforeContent,afterContent=props.display==="row"&&options.rowEventAfterContent;return jsx10(ContentContainer,{tag,attrs:{...props.attrs,...attrs,dir:props.isDragging&&options.direction==="rtl"?"rtl":void 0},className:outerClassName,style:{"--fc-event-color":renderProps.color,"--fc-event-contrast-color":renderProps.contrastColor},elRef:this.handleEl,renderProps,generatorName:"eventContent",customGenerator:options.eventContent,defaultGenerator:renderInnerContent,classNameGenerator:options.eventClass,didMount:options.eventDidMount,willUnmount:options.eventWillUnmount,children:InnerContent=>jsxs7(Fragment5,{children:[!!(renderProps.isSelected&&isBlock)&&jsx10("div",{className:props.display==="column"?classNames.hitX:classNames.hitY}),(beforeClassName||beforeContent)&&jsxs7("div",{className:joinClassNames(beforeClassName,!props.disableZindexes&&classNames.z1,renderProps.isStartResizable&&joinClassNames(props.display==="column"?classNames.cursorResizeT:classNames.cursorResizeS,classNames.internalEventResizer,classNames.internalEventResizerStart)),children:[beforeContent&&jsx10(ContentContainer,{tag:"div",style:{display:"contents"},attrs:{"aria-hidden":!0},renderProps,generatorName:void 0,customGenerator:beforeContent}),!!(renderProps.isStartResizable&&renderProps.isSelected)&&jsx10("div",{className:classNames.hit})]}),jsx10(InnerContent,{tag:"div",className:joinClassNames(innerClassName,!props.disableZindexes&&classNames.z0)}),(afterClassName||afterContent)&&jsxs7("div",{className:joinClassNames(afterClassName,!props.disableZindexes&&classNames.z1,renderProps.isEndResizable&&joinClassNames(props.display==="column"?classNames.cursorResizeB:classNames.cursorResizeE,classNames.internalEventResizer,classNames.internalEventResizerEnd)),children:[afterContent&&jsx10(ContentContainer,{tag:"div",style:{display:"contents"},attrs:{"aria-hidden":!0},renderProps,generatorName:void 0,customGenerator:afterContent}),!!(renderProps.isEndResizable&&renderProps.isSelected)&&jsx10("div",{className:classNames.hit})]})]})})}componentDidUpdate(prevProps){this.el&&this.props.eventRange!==prevProps.eventRange&&setElEventRange(this.el,this.props.eventRange)}};StandardEvent.addPropsEquality({seg:isPropsEqualShallow});function renderInnerContent(innerProps){return jsxs7(Fragment5,{children:[innerProps.timeText&&jsx10("div",{className:innerProps.timeClass,children:innerProps.timeText}),jsx10("div",{className:innerProps.titleClass,children:innerProps.event.title||jsx10(Fragment5,{children:"\xA0"})})]})}import{jsx as jsx11,jsxs as jsxs8,Fragment as Fragment6}from"react/jsx-runtime";import{createRef,Component as Component4,createElement as createElement4}from"react";import{createPortal}from"react-dom";function pointInsideRect(point,rect){return point.left>=rect.left&&point.left<rect.right&&point.top>=rect.top&&point.top<rect.bottom}function intersectRects(rect1,rect2){let res={left:Math.max(rect1.left,rect2.left),right:Math.min(rect1.right,rect2.right),top:Math.max(rect1.top,rect2.top),bottom:Math.min(rect1.bottom,rect2.bottom)};return res.left<res.right&&res.top<res.bottom?res:!1}function constrainPoint(point,rect){return{left:Math.min(Math.max(point.left,rect.left),rect.right),top:Math.min(Math.max(point.top,rect.top),rect.bottom)}}function getRectCenter(rect){return{left:(rect.left+rect.right)/2,top:(rect.top+rect.bottom)/2}}function diffPoints(point1,point2){return{left:point1.left-point2.left,top:point1.top-point2.top}}function computeEdges(el,getPadding=!1){let computedStyle=window.getComputedStyle(el),borderLeft=parseInt(computedStyle.borderLeftWidth,10)||0,borderRight=parseInt(computedStyle.borderRightWidth,10)||0,borderTop=parseInt(computedStyle.borderTopWidth,10)||0,borderBottom=parseInt(computedStyle.borderBottomWidth,10)||0,badScrollbarWidths=computeScrollbarWidthsForEl(el),scrollbarLeftRight=badScrollbarWidths.y-borderLeft-borderRight,scrollbarBottom=badScrollbarWidths.x-borderTop-borderBottom,res={borderLeft,borderRight,borderTop,borderBottom,scrollbarBottom,scrollbarLeft:0,scrollbarRight:0};return computedStyle.direction==="rtl"?res.scrollbarLeft=scrollbarLeftRight:res.scrollbarRight=scrollbarLeftRight,getPadding&&(res.paddingLeft=parseInt(computedStyle.paddingLeft,10)||0,res.paddingRight=parseInt(computedStyle.paddingRight,10)||0,res.paddingTop=parseInt(computedStyle.paddingTop,10)||0,res.paddingBottom=parseInt(computedStyle.paddingBottom,10)||0),res}function computeInnerRect(el,goWithinPadding=!1,doFromWindowViewport){let outerRect=doFromWindowViewport?el.getBoundingClientRect():computeRect(el),edges=computeEdges(el,goWithinPadding),res={left:outerRect.left+edges.borderLeft+edges.scrollbarLeft,right:outerRect.right-edges.borderRight-edges.scrollbarRight,top:outerRect.top+edges.borderTop,bottom:outerRect.bottom-edges.borderBottom-edges.scrollbarBottom};return goWithinPadding&&(res.left+=edges.paddingLeft,res.right-=edges.paddingRight,res.top+=edges.paddingTop,res.bottom-=edges.paddingBottom),res}function computeRect(el){let rect=el.getBoundingClientRect();return{left:rect.left+window.scrollX,top:rect.top+window.scrollY,right:rect.right+window.scrollX,bottom:rect.bottom+window.scrollY}}function computeClippedClientRect(el){let clippingParents=getClippingParents(el),rect=el.getBoundingClientRect();for(let clippingParent of clippingParents){let intersection=intersectRects(rect,clippingParent.getBoundingClientRect());if(intersection)rect=intersection;else return null}return rect}function getClippingParents(el){let parents=[];for(;el instanceof HTMLElement;){let computedStyle=window.getComputedStyle(el);if(computedStyle.position==="fixed")break;/(auto|scroll)/.test(computedStyle.overflow+computedStyle.overflowY+computedStyle.overflowX)&&parents.push(el),el=el.parentNode}return parents}function computeScrollbarWidthsForEl(el){return{x:el.offsetHeight-el.clientHeight,y:el.offsetWidth-el.clientWidth}}var Slicer=class{constructor(){this.sliceBusinessHours=memoize2(this._sliceBusinessHours),this.sliceDateSelection=memoize2(this._sliceDateSpan),this.sliceEventStore=memoize2(this._sliceEventStore),this.sliceEventDrag=memoize2(this._sliceInteraction),this.sliceEventResize=memoize2(this._sliceInteraction),this.forceDayIfListItem=!1}intersectDateSpan(dateSpan,activeRange,...extraArgs){let activeDateSpanRange=intersectRanges(dateSpan.range,activeRange);if(activeDateSpanRange){let slicedDateSpan={...dateSpan,range:activeDateSpanRange};return activeDateSpanRange.start.valueOf()!==dateSpan.range.start.valueOf()&&delete slicedDateSpan.instantStartMs,activeDateSpanRange.end.valueOf()!==dateSpan.range.end.valueOf()&&delete slicedDateSpan.instantEndMs,slicedDateSpan}return null}sliceDateSpan(dateSpan,...extraArgs){return this.sliceRange(dateSpan.range,...extraArgs)}sliceProps(props,dateProfile,nextDayThreshold,context,...extraArgs){let{eventUiBases}=props,eventSegs=this.sliceEventStore(props.eventStore,eventUiBases,dateProfile,nextDayThreshold,...extraArgs);return{dateSelectionSegs:this.sliceDateSelection(props.dateSelection,dateProfile,nextDayThreshold,eventUiBases,context,...extraArgs),businessHourSegs:this.sliceBusinessHours(props.businessHours,dateProfile,nextDayThreshold,context,...extraArgs),fgEventSegs:eventSegs.fg,bgEventSegs:eventSegs.bg,eventDrag:this.sliceEventDrag(props.eventDrag,eventUiBases,dateProfile,nextDayThreshold,...extraArgs),eventResize:this.sliceEventResize(props.eventResize,eventUiBases,dateProfile,nextDayThreshold,...extraArgs),eventSelection:props.eventSelection}}sliceNowDate(date,dateProfile,nextDayThreshold,context,...extraArgs){return this._sliceDateSpan({range:{start:date,end:addMs(date,1)},allDay:!1},dateProfile,nextDayThreshold,{},context,...extraArgs)}_sliceBusinessHours(businessHours,dateProfile,nextDayThreshold,context,...extraArgs){return businessHours?this._sliceEventStore(expandRecurring(businessHours,computeActiveRange(dateProfile,!!nextDayThreshold),context),{},dateProfile,nextDayThreshold,...extraArgs).bg:[]}_sliceEventStore(eventStore,eventUiBases,dateProfile,nextDayThreshold,...extraArgs){if(eventStore){let rangeRes=sliceEventStore(eventStore,eventUiBases,computeActiveRange(dateProfile,!!nextDayThreshold),nextDayThreshold);return{bg:this.sliceEventRanges(rangeRes.bg,extraArgs),fg:this.sliceEventRanges(rangeRes.fg,extraArgs)}}return{bg:[],fg:[]}}_sliceInteraction(interaction,eventUiBases,dateProfile,nextDayThreshold,...extraArgs){if(!interaction)return null;let rangeRes=sliceEventStore(interaction.mutatedEvents,eventUiBases,computeActiveRange(dateProfile,!!nextDayThreshold),nextDayThreshold);return{segs:this.sliceEventRanges(rangeRes.fg,extraArgs),affectedInstances:interaction.affectedEvents.instances,isEvent:interaction.isEvent}}_sliceDateSpan(dateSpan,dateProfile,nextDayThreshold,eventUiBases,context,...extraArgs){if(!dateSpan)return[];let activeRange=computeActiveRange(dateProfile,!!nextDayThreshold),slicedDateSpan=this.intersectDateSpan(dateSpan,activeRange,...extraArgs);if(slicedDateSpan){dateSpan=slicedDateSpan;let eventRange=fabricateEventRange(dateSpan,eventUiBases,context),segs=this.sliceDateSpan(dateSpan,...extraArgs);for(let seg of segs)seg.eventRange=eventRange;return segs}return[]}sliceEventRanges(eventRanges,extraArgs){let segs=[];for(let eventRange of eventRanges)segs.push(...this.sliceEventRange(eventRange,extraArgs));return segs}sliceEventRange(eventRange,extraArgs){let dateRange=eventRange.range;this.forceDayIfListItem&&eventRange.ui.display==="list-item"&&(dateRange={start:dateRange.start,end:addDays4(dateRange.start,1)});let segs=this.sliceRange(dateRange,...extraArgs);for(let seg of segs)seg.eventRange=eventRange,seg.isStart=eventRange.isStart&&seg.isStart,seg.isEnd=eventRange.isEnd&&seg.isEnd;return segs}};function computeActiveRange(dateProfile,isComponentAllDay){let range=dateProfile.activeRange;return isComponentAllDay?range:{start:addMs(range.start,dateProfile.slotMinTime.milliseconds),end:addMs(range.end,dateProfile.slotMaxTime.milliseconds-864e5)}}var DayTableModel=class{constructor(daySeries,breakOnWeeks,dateEnv,majorUnit="",activeRange){this.daySeries=daySeries,this.dateEnv=dateEnv,this.majorUnit=majorUnit,this.activeRange=activeRange;let{dates}=daySeries,daysPerRow,firstDay,rowCount;if(breakOnWeeks){for(firstDay=dates[0].getUTCDay(),daysPerRow=1;daysPerRow<dates.length&&dates[daysPerRow].getUTCDay()!==firstDay;daysPerRow+=1);rowCount=Math.ceil(dates.length/daysPerRow)}else rowCount=1,daysPerRow=dates.length;this.rowCount=rowCount,this.colCount=daysPerRow,this.cellRows=this.buildCells(),this.headerDates=this.buildHeaderDates()}buildCells(){let rows=[];for(let row=0;row<this.rowCount;row+=1){let cells=[];for(let col=0;col<this.colCount;col+=1)cells.push(this.buildCell(row,col));rows.push(cells)}return rows}buildCell(row,col){let date=this.daySeries.dates[row*this.colCount+col];return{key:date.toISOString(),date,isMajor:this.cellIsMajor(date),isDisabled:this.activeRange===null||this.activeRange!==void 0&&!rangeContainsMarker(this.activeRange,date)}}cellIsMajor(dateMarker){return this.majorUnit?isMajorUnit(dateMarker,this.majorUnit,this.dateEnv):!1}buildHeaderDates(){let dates=[];for(let col=0;col<this.colCount;col+=1)dates.push(this.cellRows[0][col].date);return dates}};function buildDayGridRanges(seriesRange,daysPerRow){let ranges=[];if(seriesRange){let{start,end}=seriesRange,index2=start;for(;index2<end;){let row=Math.floor(index2/daysPerRow),nextIndex=Math.min((row+1)*daysPerRow,end);ranges.push({row,start:index2%daysPerRow,end:(nextIndex-1)%daysPerRow+1,isStart:seriesRange.isStart&&index2===start,isEnd:seriesRange.isEnd&&nextIndex===end}),index2=nextIndex}}return ranges}var DayTableSlicer=class extends Slicer{constructor(){super(...arguments),this.forceDayIfListItem=!0}sliceRange(dateRange,dayTableModel){return buildDayGridRanges(dayTableModel.daySeries.sliceRange(dateRange),dayTableModel.colCount)}},DaySeriesSlicer=class extends Slicer{constructor(){super(...arguments),this.forceDayIfListItem=!0}sliceRange(dateRange,daySeries){return buildDayGridRanges(daySeries.sliceRange(dateRange),daySeries.cnt)}},firstSunday=new Date(2592e5);function buildDateRowConfigs(dates,datesRepDistinctDays,dateProfile,todayRange,dayHeaderFormat,context){let rowConfig=buildDateRowConfig(dates,datesRepDistinctDays,dateProfile,todayRange,dayHeaderFormat,context),majorUnit=computeMajorUnit(dateProfile,context.dateEnv);if(datesRepDistinctDays&&majorUnit!=="day")for(let dataConfig of rowConfig.dataConfigs)isMajorUnit(dataConfig.dateMarker,majorUnit,context.dateEnv)&&(dataConfig.renderProps.isMajor=!0);return[rowConfig]}function buildDateRowConfig(dateMarkers,datesRepDistinctDays,dateProfile,todayRange,dayHeaderFormat,context,colSpan,isMajorMod,totalDateCnt){return{isDateRow:!0,renderConfig:buildDateRenderConfig(dayHeaderFormat,datesRepDistinctDays,context),dataConfigs:buildDateDataConfigs(dateMarkers,datesRepDistinctDays,dateProfile,todayRange,dayHeaderFormat,context,colSpan,void 0,void 0,void 0,void 0,isMajorMod,totalDateCnt)}}function buildDateRenderConfig(dayHeaderFormat,datesRepDistinctDays,context){let{options}=context;return{generatorName:"dayHeaderContent",customGenerator:options.dayHeaderContent,classNameGenerator:options.dayHeaderClass,innerClassNameGenerator:options.dayHeaderInnerClass,didMount:options.dayHeaderDidMount,willUnmount:options.dayHeaderWillUnmount,align:options.dayHeaderAlign,sticky:options._dayHeaderSticky,dayHeaderFormat,datesRepDistinctDays}}var dowDates=[];for(let dow=0;dow<7;dow++)dowDates.push(addDays4(new Date(2592e5),dow));function buildDateDataConfigs(dateMarkers,datesRepDistinctDays,dateProfile,todayRange,dayHeaderFormat,context,colSpan=1,keyPrefix="",extraRenderProps={},extraAttrs={},className="",isMajorMod,totalDateCnt=dateMarkers.length){let{dateEnv,viewApi,options}=context;return datesRepDistinctDays?dateMarkers.map((dateMarker,i)=>{let dateMeta=getDateMeta(dateMarker,dateEnv,dateProfile,todayRange),isMajor=isMajorMod!=null&&!(i%isMajorMod),hasNavLink=options.navLinks&&!dateMeta.isDisabled&&totalDateCnt>1,renderProps={...dateMeta,...extraRenderProps,isMajor,isSticky:!1,inPopover:!1,hasNavLink,view:viewApi},fullDateStr=buildDateStr(context,dateMarker);return{key:keyPrefix+dateMarker.toUTCString(),dateMarker,renderProps,attrs:{"aria-label":fullDateStr,...dateMeta.isToday?{"aria-current":"date"}:{},"data-date":formatDayString(dateMarker),...extraAttrs},innerAttrs:hasNavLink?buildNavLinkAttrs(context,dateMarker,void 0,fullDateStr):{"aria-hidden":!0},colSpan,hasNavLink,className}}):dateMarkers.map((dateMarker,i)=>{let dow=dateMarker.getUTCDay(),normDate=addDays4(firstSunday,dow),dateMeta={date:dateEnv.toDate(dateMarker),dow,isDisabled:!1,isFuture:!1,isPast:!1,isToday:!1,isOther:!1},isMajor=isMajorMod!=null&&!(i%isMajorMod),renderProps={...dateMeta,date:dowDates[dow],isMajor,isSticky:!1,inPopover:!1,hasNavLink:!1,view:viewApi,...extraRenderProps},fullWeekDayStr=joinDateTimeFormatParts(dateEnv.formatToParts(normDate,WEEKDAY_ONLY_FORMAT));return{key:keyPrefix+String(dow),dateMarker,renderProps,attrs:{"aria-label":fullWeekDayStr,...extraAttrs},innerAttrs:{"aria-hidden":!0},colSpan,className}})}var RefMap=class{constructor(masterCallback,ignoreDeletes=!1){this.masterCallback=masterCallback,this.ignoreDeletes=ignoreDeletes,this.rev="",this.current=new Map,this.callbacks=new Map,this.handleValue=(val,key)=>{let{current,callbacks}=this,priorExists=current.has(key),priorVal=priorExists?current.get(key):null,anyChange=!1;val===null?priorExists&&!this.ignoreDeletes&&(current.delete(key),callbacks.delete(key),anyChange=!0):(anyChange=priorVal!==val,current.set(key,val)),anyChange&&(this.rev=guid(),this.masterCallback&&this.masterCallback(val,key,priorVal))}}createRef(key){let refCallback=this.callbacks.get(key);return refCallback||(refCallback=val=>{this.handleValue(val,key)},this.callbacks.set(key,refCallback)),refCallback}},Ruler=class extends BaseComponent{constructor(){super(...arguments),this.elRef=createRef()}render(){return jsx11("div",{ref:this.elRef})}componentDidMount(){this._isUnmounting=!1;let{props}=this,el=this.elRef.current;this.disconnectWidth=watchWidth(el,width=>{this._isUnmounting||setRef(props.widthRef,width)})}componentWillUnmount(){this._isUnmounting=!0,this.disconnectWidth();let{props}=this;props.widthRef&&setRef(props.widthRef,null)}};function getDayGridSegKey(seg){return`${seg.eventRange.instance.instanceId}:${seg.start}`}function splitSegsByRow(segs,rowCount){let byRow=[];for(let row=0;row<rowCount;row++)byRow[row]=[];for(let seg of segs)byRow[seg.row].push(seg);return byRow}function splitInteractionByRow(ui,rowCount){let byRow=[];if(ui){for(let row=0;row<rowCount;row++)byRow[row]={affectedInstances:ui.affectedInstances,isEvent:ui.isEvent,segs:[]};for(let seg of ui.segs)byRow[seg.row].segs.push(seg)}else for(let row=0;row<rowCount;row++)byRow[row]=null;return byRow}var BgEvent=class extends BaseComponent{constructor(){super(...arguments),this.buildPublicEvent=memoize2((context,eventDef,eventInstance)=>new EventImpl(context,eventDef,eventInstance)),this.handleEl=el=>{this.el=el,el&&setElEventRange(el,this.props.eventRange)}}render(){let{props,context}=this,{eventRange}=props,{options}=context,eventUi=eventRange.ui,eventApi=this.buildPublicEvent(context,eventRange.def,eventRange.instance),subcontentRenderProps={event:eventApi,isNarrow:props.isNarrow||!1,isShort:props.isShort||!1},renderProps={event:eventApi,view:context.viewApi,timeText:"",color:eventUi.color||options.backgroundEventColor,contrastColor:eventUi.contrastColor,isDraggable:!1,isStartResizable:!1,isEndResizable:!1,isMirror:!1,isStart:props.isStart,isEnd:props.isEnd,isFirst:!1,isLast:!1,isPast:props.isPast,isFuture:props.isFuture,isToday:props.isToday,isSelected:!1,isDragging:!1,isResizing:!1,isInteractive:!1,level:0,isNarrow:props.isNarrow||!1,isShort:props.isShort||!1,timeClass:"",titleClass:generateClassName(options.backgroundEventTitleClass,subcontentRenderProps),options:{eventOverlap:!!options.eventOverlap}},outerClassName=joinClassNames(eventUi.className,classNames.fill,classNames.internalEvent,classNames.internalBgEvent,props.isVertical?classNames.flexCol:classNames.flexRow),innerClassName=joinClassNames(generateClassName(options.backgroundEventInnerClass,renderProps),classNames.liquid);return jsx11(ContentContainer,{tag:"div",className:outerClassName,style:{"--fc-event-color":renderProps.color,"--fc-event-contrast-color":renderProps.contrastColor},defaultGenerator:renderInnerContent2,elRef:this.handleEl,renderProps,generatorName:"backgroundEventContent",customGenerator:options.backgroundEventContent,classNameGenerator:options.backgroundEventClass,didMount:options.backgroundEventDidMount,willUnmount:options.backgroundEventWillUnmount,children:InnerContent=>jsx11(InnerContent,{tag:"div",className:innerClassName})})}componentDidUpdate(prevProps){this.el&&this.props.eventRange!==prevProps.eventRange&&setElEventRange(this.el,this.props.eventRange)}};function renderInnerContent2(props){let{title}=props.event;return title&&jsx11("div",{className:props.titleClass,children:props.event.title})}function renderFill(fillType,options){return jsx11("div",{className:joinClassNames(fillType==="non-business"?options.nonBusinessHoursClass:fillType==="highlight"?options.highlightClass:void 0,classNames.fill)})}var COL_BORDER_WIDTH=1,ROW_BORDER_WIDTH=1,SPACE_FROM_VIEWPORT=10,MorePopover=class extends DateComponent{constructor(){super(...arguments),this.getDateMeta=memoize2(getDateMeta),this.closeRef=createRef(),this.focusStartRef=createRef(),this.focusEndRef=createRef(),this.handleRootEl=rootEl=>{this.rootEl=rootEl,rootEl?this.context.registerInteractiveComponent(this,{el:rootEl,useEventCenter:!1}):this.context.unregisterInteractiveComponent(this)},this.handleDocumentMouseDown=ev=>{let target=getEventTargetViaRoot(ev);this.rootEl.contains(target)||this.handleClose()},this.handleDocumentKeyDown=ev=>{ev.key==="Escape"&&this.handleClose()},this.handleClose=()=>{let{onClose}=this.props;onClose&&onClose()}}render(){let{props,context}=this,{options,dateEnv,viewApi}=context,{startDate,todayRange,dateProfile}=props,dateMeta=this.getDateMeta(startDate,dateEnv,dateProfile,todayRange),textParts=dateEnv.formatToParts(startDate,options.popoverFormat),text=joinDateTimeFormatParts(textParts),dayHeaderRenderProps={...dateMeta,isMajor:!1,isNarrow:!1,isSticky:!1,inPopover:!0,level:0,hasNavLink:!1,text,textParts,get weekdayText(){return findWeekdayText(textParts)},get dayNumberText(){return findDayNumberText(textParts)},view:viewApi},dayCellRenderProps={...dateMeta,isMajor:!1,isNarrow:!1,inPopover:!0,hasNavLink:!1,get weekdayText(){return findWeekdayText(textParts)},get dayNumberText(){return findDayNumberText(textParts)},get monthText(){return findMonthText(textParts)},view:viewApi,text:"",textParts:[],options:{businessHours:!!options.businessHours}},fullDateStr=formatDayString(startDate),{dayHeaderAlign}=options,align=typeof dayHeaderAlign=="function"?dayHeaderAlign({level:0,inPopover:!0,isNarrow:!1}):dayHeaderAlign,isRtl=computeElIsRtl(props.alignEl);return createPortal(jsxs8("div",{"data-date":fullDateStr,id:props.id,role:"dialog","aria-labelledby":props.titleId,className:joinClassNames(options.popoverClass,classNames.flexCol,classNames.popoverZ,classNames.abs,classNames.borderBoxRoot,classNames.internalPopover),style:{top:0,left:0},dir:isRtl?"rtl":void 0,"data-color-scheme":options.colorScheme||void 0,ref:this.handleRootEl,children:[jsx11("div",{tabIndex:0,style:{outline:"none"},ref:this.focusStartRef}),jsxs8("div",{className:joinClassNames(generateClassName(options.dayHeaderClass,dayHeaderRenderProps),classNames.flexCol,classNames.borderlessX,classNames.borderlessTop,align==="center"?classNames.alignCenter:align==="end"?classNames.alignEnd:classNames.alignStart),children:[jsx11("div",{children:jsx11(ContentContainer,{tag:"div",attrs:{id:props.titleId},generatorName:"dayHeaderContent",renderProps:dayHeaderRenderProps,customGenerator:options.dayHeaderContent,defaultGenerator:renderText2,classNameGenerator:options.dayHeaderInnerClass,didMount:options.dayHeaderDidMount,willUnmount:options.dayHeaderWillUnmount})}),jsx11(ContentContainer,{tag:"button",attrs:{"aria-label":options.closeHint,...createAriaClickAttrs(this.handleClose)},elRef:this.closeRef,className:joinClassNames(options.popoverCloseClass,classNames.flexRow,classNames.cursorPointer),renderProps:{},customGenerator:options.popoverCloseContent,generatorName:"popoverCloseContent"})]}),jsx11("div",{className:joinClassNames(generateClassName(options.dayCellClass,dayCellRenderProps),classNames.flexCol,classNames.borderless),children:jsx11("div",{className:generateClassName(options.dayCellInnerClass,dayCellRenderProps),children:props.children})}),jsx11("div",{tabIndex:0,style:{outline:"none"},ref:this.focusEndRef})]}),getAppendableRoot(props.alignEl))}queryHit(isRtl,positionLeft,positionTop,elWidth,elHeight){let{rootEl,props}=this;return positionLeft>=0&&positionLeft<elWidth&&positionTop>=0&&positionTop<elHeight?{dateProfile:props.dateProfile,dateSpan:{allDay:!props.forceTimed,range:{start:props.startDate,end:props.endDate},...props.dateSpanProps},getDayEl:()=>rootEl,rect:{left:0,top:0,right:elWidth,bottom:elHeight},layer:1}:null}componentDidMount(){document.addEventListener("mousedown",this.handleDocumentMouseDown),document.addEventListener("keydown",this.handleDocumentKeyDown),this.focusStartRef.current.addEventListener("focus",this.handleClose),this.focusEndRef.current.addEventListener("focus",this.handleClose),this.closeRef.current.focus({preventScroll:!0}),this.updateSize()}componentWillUnmount(){document.removeEventListener("mousedown",this.handleDocumentMouseDown),document.removeEventListener("keydown",this.handleDocumentKeyDown),this.focusStartRef.current.removeEventListener("focus",this.handleClose),this.focusEndRef.current.removeEventListener("focus",this.handleClose)}updateSize(){let{alignEl,alignParentTop}=this.props,{rootEl:popoverEl}=this,isRtl=computeElIsRtl(alignEl),alignmentRect=computeClippedClientRect(alignEl);if(alignmentRect){let popoverDims=popoverEl.getBoundingClientRect(),popoverVPTop=alignParentTop?alignEl.closest(alignParentTop).getBoundingClientRect().top-ROW_BORDER_WIDTH:alignmentRect.top,popoverVPLeft=isRtl?alignmentRect.right-popoverDims.width:alignmentRect.left;popoverVPTop=Math.max(popoverVPTop,SPACE_FROM_VIEWPORT),popoverVPLeft=Math.min(popoverVPLeft,document.documentElement.clientWidth-SPACE_FROM_VIEWPORT-popoverDims.width),popoverVPLeft=Math.max(popoverVPLeft,SPACE_FROM_VIEWPORT);let{offsetParent}=popoverEl,top,left;if(!offsetParent||offsetParent===document.body)top=popoverVPTop+window.scrollY,left=popoverVPLeft+window.scrollX;else{let offsetParentRect=offsetParent.getBoundingClientRect();top=popoverVPTop-offsetParentRect.top+offsetParent.scrollTop,left=popoverVPLeft-offsetParentRect.left+offsetParent.scrollLeft}applyStyle(popoverEl,{top,left})}}};function renderText2(renderProps){return renderProps.text}function computeEarliestStart(segs){return segs.reduce(pickEarliestStart).eventRange.range.start}function computeLatestEnd(segs){return segs.reduce(pickLatestEnd).eventRange.range.end}function pickEarliestStart(r0,r1){return r0.eventRange.range.start<r1.eventRange.range.start?r0:r1}function pickLatestEnd(r0,r1){return r0.eventRange.range.end>r1.eventRange.range.end?r0:r1}var MoreLinkTrigger=class extends BaseComponent{render(){let{props,context}=this,{options}=context,renderProps=buildMoreLinkRenderProps(props.num,props.isNarrow,props.isMicro,props.display,context);return jsx11(ContentContainer,{tag:"div",elRef:props.elRef,className:joinClassNames(generateClassName(props.display==="row"?options.rowMoreLinkClass:options.columnMoreLinkClass,renderProps),props.className,props.display==="row"?classNames.flexRow:classNames.flexCol,classNames.internalMoreLink,classNames.cursorPointer),style:props.style,attrs:props.attrs,renderProps,generatorName:"moreLinkContent",customGenerator:options.moreLinkContent,defaultGenerator:renderMoreLinkText,classNameGenerator:options.moreLinkClass,didMount:props.didMount,willUnmount:props.willUnmount,children:InnerContent=>jsx11(InnerContent,{tag:"div",className:joinClassNames(generateClassName(options.moreLinkInnerClass,renderProps),generateClassName(props.display==="row"?options.rowMoreLinkInnerClass:options.columnMoreLinkInnerClass,renderProps),props.display==="row"?classNames.stickyS:classNames.stickyT)})})}},MoreLinkContainer=class extends BaseComponent{constructor(){super(...arguments),this.state={isPopoverOpen:!1},this.handleLinkEl=linkEl=>{this.linkEl=linkEl,this.props.elRef&&setRef(this.props.elRef,linkEl)},this.handleClick=ev=>{let{props,context}=this,{dateEnv,options}=context,{moreLinkClick}=options,date=computeRange(props).start;function buildPublicSeg(seg){let{def,instance,range}=seg.eventRange,start=buildRangeEdgeOutput(range.start,range.instantStartMs,dateEnv),end=buildRangeEdgeOutput(range.end,range.instantEndMs,dateEnv);return{event:new EventImpl(context,def,instance),start:start.date,end:end.date,isStart:seg.isStart,isEnd:seg.isEnd}}typeof moreLinkClick=="function"&&(moreLinkClick=moreLinkClick({date:dateEnv.toDate(date),allDay:!!props.allDayDate,allSegs:props.segs.map(buildPublicSeg),hiddenSegs:props.hiddenSegs.map(buildPublicSeg),jsEvent:ev,view:context.viewApi})),!moreLinkClick||moreLinkClick==="popover"?this.setState({isPopoverOpen:!0}):typeof moreLinkClick=="string"&&context.calendarApi.zoomTo(date,moreLinkClick)},this.handlePopoverClose=()=>{this.linkEl&&this.linkEl.focus(),this.setState({isPopoverOpen:!1})}}render(){let{props,state,context}=this,{options,baseId}=context,moreCnt=props.hiddenSegs.length,range=computeRange(props),popoverId=baseId+"popover-"+range.start.toISOString(),renderProps=buildMoreLinkRenderProps(moreCnt,props.isNarrow,props.isMicro,props.display,context),hint=formatWithOrdinals(options.moreLinkHint,[moreCnt],renderProps.longText);return jsxs8(Fragment6,{children:[!!moreCnt&&jsx11(MoreLinkTrigger,{num:moreCnt,display:props.display,isNarrow:props.isNarrow,isMicro:props.isMicro,elRef:this.handleLinkEl,className:props.className,style:props.style,attrs:{...props.attrs,...createAriaClickAttrs(this.handleClick),title:hint,role:"button","aria-haspopup":"dialog","aria-expanded":state.isPopoverOpen,"aria-controls":state.isPopoverOpen?popoverId:void 0},didMount:options.moreLinkDidMount,willUnmount:options.moreLinkWillUnmount}),state.isPopoverOpen&&jsx11(MorePopover,{id:popoverId,titleId:popoverId+"-title",startDate:range.start,endDate:range.end,dateProfile:props.dateProfile,todayRange:props.todayRange,dateSpanProps:props.dateSpanProps,alignEl:props.alignElRef?props.alignElRef.current:this.linkEl,alignParentTop:props.alignParentTop,forceTimed:props.forceTimed,onClose:this.handlePopoverClose,children:props.popoverContent()})]})}};function renderMoreLinkText(props){return props.text}function buildMoreLinkRenderProps(num,isNarrow,isMicro,display,context){let{viewApi,options,calendarApi}=context,numericText=`+${num}`,longText=typeof options.moreLinkText=="function"?options.moreLinkText.call(calendarApi,num):`${numericText} ${options.moreLinkText}`;return{num,numericText,longText,text:isMicro||display==="column"?numericText:longText,isNarrow,view:viewApi}}function computeRange(props){return props.allDayDate?{start:props.allDayDate,end:addDays4(props.allDayDate,1)}:{start:computeEarliestStart(props.hiddenSegs),end:computeLatestEnd(props.hiddenSegs)}}var DEFAULT_TABLE_EVENT_TIME_FORMAT=createFormatter({hour:"numeric",minute:"2-digit",omitZeroMinute:!0,meridiem:"narrow"});function hasListItemDisplay(range,eventRange){let{display}=eventRange.ui;return display==="list-item"||display==="auto"&&!eventRange.def.allDay&&range.end-range.start===1&&range.isStart&&range.isEnd}var DAY_GRID_NON_BUSINESS_Z_CLASS=classNames.z1,DAY_GRID_BG_EVENT_Z_CLASS=classNames.z2,DAY_GRID_HIGHLIGHT_Z_CLASS=classNames.z3,DAY_GRID_CELL_CONTENT_Z_CLASS=classNames.z4,DAY_GRID_EVENT_Z_CLASS=classNames.z5,DAY_GRID_INTERACTION_Z_CLASS=classNames.z1000,DayGridMoreLink=class extends BaseComponent{render(){let{props}=this;return jsx11(MoreLinkContainer,{display:"row",className:joinClassNames(props.className,DAY_GRID_CELL_CONTENT_Z_CLASS),isNarrow:props.isNarrow,isMicro:props.isMicro,dateProfile:props.dateProfile,todayRange:props.todayRange,allDayDate:props.allDayDate,segs:props.segs,hiddenSegs:props.hiddenSegs,alignElRef:props.alignElRef,alignParentTop:props.alignParentTop,dateSpanProps:props.dateSpanProps,popoverContent:()=>jsx11(Fragment6,{children:props.segs.map(seg=>{let{eventRange}=seg,{instanceId}=eventRange.instance,isDragging=!!(props.eventDrag&&props.eventDrag.affectedInstances[instanceId]),isResizing=!!(props.eventResize&&props.eventResize.affectedInstances[instanceId]);return jsx11("div",{style:{visibility:isDragging||isResizing?"hidden":void 0},children:jsx11(StandardEvent,{display:hasListItemDisplay(seg,eventRange)?"list-item":"row",eventRange,isStart:seg.isStart,isEnd:seg.isEnd,isDragging,isResizing,isMirror:!1,isSelected:instanceId===props.eventSelection,defaultTimeFormat:DEFAULT_TABLE_EVENT_TIME_FORMAT,defaultDisplayEventEnd:!1,...getEventRangeMeta(eventRange,props.todayRange)})},instanceId)})})})}},DayGridCell=class extends DateComponent{constructor(){super(...arguments),this.getDateMeta=memoize2(getDayGridCellDateMeta),this.refineRenderProps=memoizeObjArg(refineRenderProps2),this.rootElRef=createRef(),this.handleBodyEl=bodyEl=>{this.disconnectBodyHeight&&(this.disconnectBodyHeight(),this.disconnectBodyHeight=void 0,this.headerHeight=void 0,setRef(this.props.headerHeightRef,null),setRef(this.props.mainHeightRef,null)),bodyEl&&(this.props.headerHeightRef||this.props.mainHeightRef)&&(this.disconnectBodyHeight=watchSize(bodyEl,(_bodyWidth,bodyHeight)=>{if(this._isUnmounting)return;let{props}=this,rootEl=this.rootElRef.current;if(!rootEl)return;let mainRect=bodyEl.getBoundingClientRect(),rootRect=rootEl.getBoundingClientRect(),headerHeight=mainRect.top-rootRect.top;isDimsEqual(this.headerHeight,headerHeight)||(this.headerHeight=headerHeight,setRef(props.headerHeightRef,headerHeight)),setRef(props.mainHeightRef,bodyHeight)}))}}render(){let{props,context}=this,{options,dateEnv}=context,{tableMode}=props,isMonthStart=props.showDayNumber&&shouldDisplayMonthStart(props.date,props.dateProfile.currentRange,dateEnv),dateMeta=this.getDateMeta(props.date,dateEnv,props.dateProfile,props.todayRange,props.isDisabled),baseClassName=joinClassNames(classNames.borderlessTop,classNames.borderlessEnd,!props.borderStart&&classNames.borderlessStart,!(tableMode&&props.borderBottom)&&classNames.borderlessBottom,!tableMode&&props.width==null&&classNames.liquid,!tableMode&&classNames.flexCol,classNames.rel,classNames.noMargin,classNames.noPadding),CellTag=tableMode?"td":"div",cellStyle=tableMode?void 0:{width:props.width},hasNavLink=options.navLinks,renderProps=this.refineRenderProps({date:props.date,isMajor:props.isMajor,isNarrow:props.isNarrow,dateMeta,hasLabel:props.showDayNumber,hasMonthLabel:isMonthStart,hasNavLink,renderProps:props.renderProps,viewApi:context.viewApi,dateEnv:context.dateEnv,monthStartFormat:options.monthStartFormat,dayCellFormat:options.dayCellFormat,businessHours:!!options.businessHours});if(dateMeta.isDisabled)return jsx11(CellTag,{role:"gridcell","aria-disabled":!0,className:joinClassNames(generateClassName(options.dayCellClass,renderProps),props.className,baseClassName),style:cellStyle,children:props.fills});let fullDateStr=buildDateStr(context,props.date);return jsx11(ContentContainer,{tag:CellTag,elRef:this.rootElRef,className:joinClassNames(props.className,baseClassName),attrs:{...props.attrs,role:"gridcell","aria-label":fullDateStr,...renderProps.isToday?{"aria-current":"date"}:{},"data-date":formatDayString(props.date)},style:cellStyle,renderProps,generatorName:"dayCellTopContent",customGenerator:options.dayCellTopContent,defaultGenerator:renderTopInner,classNameGenerator:options.dayCellClass,didMount:options.dayCellDidMount,willUnmount:options.dayCellWillUnmount,children:InnerContent=>jsxs8(Fragment6,{children:[props.fills,jsx11("div",{className:joinClassNames(classNames.rel,DAY_GRID_CELL_CONTENT_Z_CLASS,generateClassName(options.dayCellTopClass,renderProps)),children:props.showDayNumber&&jsx11(InnerContent,{tag:"div",attrs:hasNavLink?buildNavLinkAttrs(context,props.date,void 0,fullDateStr):{"aria-hidden":!0},className:generateClassName(options.dayCellTopInnerClass,renderProps)})}),jsxs8("div",{className:joinClassNames(!tableMode&&classNames.flexCol,!tableMode&&(props.fgLiquidHeight?classNames.liquid:classNames.grow),tableMode&&classNames.printCellContentMinHeight),ref:this.handleBodyEl,children:[jsx11("div",{className:joinClassNames(classNames.rel,generateClassName(options.dayCellInnerClass,renderProps)),style:{minHeight:props.fgHeight},children:props.fg}),jsx11(DayGridMoreLink,{className:classNames.rel,allDayDate:props.date,segs:props.segs,hiddenSegs:props.hiddenSegs,alignElRef:this.rootElRef,alignParentTop:props.showDayNumber?"[role=row]":`.${classNames.internalView}`,dateSpanProps:props.dateSpanProps,dateProfile:props.dateProfile,eventSelection:props.eventSelection,eventDrag:props.eventDrag,eventResize:props.eventResize,todayRange:props.todayRange,isNarrow:props.isNarrow,isMicro:props.isMicro})]}),jsx11("div",{className:joinClassNames(classNames.rel,DAY_GRID_CELL_CONTENT_Z_CLASS,generateClassName(options.dayCellBottomClass,renderProps))})]})})}componentDidMount(){this._isUnmounting=!1}componentWillUnmount(){this._isUnmounting=!0}};function getDayGridCellDateMeta(date,dateEnv,dateProfile,todayRange,isDisabled){return{...getDateMeta(date,dateEnv,dateProfile,todayRange),isDisabled}}function renderTopInner(props){return props.text||jsx11(Fragment6,{children:"\xA0"})}function shouldDisplayMonthStart(date,currentRange,dateEnv){let{start:currentStart,end:currentEnd}=currentRange,currentEndIncl=addMs(currentEnd,-1),currentFirstYear=dateEnv.getYear(currentStart),currentFirstMonth=dateEnv.getMonth(currentStart),currentLastYear=dateEnv.getYear(currentEndIncl),currentLastMonth=dateEnv.getMonth(currentEndIncl);return!(currentFirstYear===currentLastYear&¤tFirstMonth===currentLastMonth)&&(date.valueOf()===currentStart.valueOf()||dateEnv.getDay(date)===1&&date.valueOf()<currentEnd.valueOf())}function refineRenderProps2(raw){let{date,dateEnv,hasLabel,hasMonthLabel,hasNavLink,businessHours}=raw,textParts=[],text="";return hasLabel&&(textParts=dateEnv.formatToParts(date,hasMonthLabel?raw.monthStartFormat:raw.dayCellFormat),text=joinDateTimeFormatParts(textParts)),{...raw.dateMeta,...raw.renderProps,text,textParts,isMajor:raw.isMajor,isNarrow:raw.isNarrow,inPopover:!1,hasNavLink,get weekdayText(){return findWeekdayText(textParts)},get dayNumberText(){return findDayNumberText(textParts)},get monthText(){return findMonthText(textParts)},options:{businessHours},view:raw.viewApi}}var MeasuredHeightHarness=class extends Component4{constructor(){super(...arguments),this.rootElRef=createRef(),this._isUnmounting=!1}render(){let{props}=this;return jsx11("div",{className:props.className,style:props.style,ref:this.rootElRef,children:props.children})}componentDidMount(){this._isUnmounting=!1;let rootEl=this.rootElRef.current;this.disconnectHeight=watchHeight(rootEl,height=>{this._isUnmounting||(this.height=height,setRef(this.props.heightRef,height))})}componentDidUpdate(prevProps){let{heightRef}=this.props;prevProps.heightRef!==heightRef&&(setRef(prevProps.heightRef,null),this.height!=null&&setRef(heightRef,this.height))}componentWillUnmount(){this._isUnmounting=!0,this.disconnectHeight?.(),setRef(this.props.heightRef,null)}};function doSpansIntersect(a,b){return a.start<b.end&&b.start<a.end}function intersectSpans(a,b){let start=Math.max(a.start,b.start),end=Math.min(a.end,b.end);return start<end?{start,end}:null}function getSpanLength(span){return span.end-span.start}function findIntersections(entries,span){let index2=findLowerBoundByStart(entries,span.start);index2>0&&index2--;let matches=[];for(;index2<entries.length;index2++){let entry=entries[index2];if(entry.start>=span.end)break;doSpansIntersect(entry,span)&&matches.push(entry)}return matches}function subtractCoveredSpans(span,covered){let result=[],cursor=span.start;for(let item of covered)if(!(item.end<=cursor)&&(item.start>=span.end||(item.start>cursor&&result.push({start:cursor,end:Math.min(item.start,span.end)}),cursor=Math.max(cursor,item.end),cursor>=span.end)))break;return cursor<span.end&&result.push({start:cursor,end:span.end}),result}function addToUnion(spans,addition){let result=[],pending={...addition},inserted=!1;for(let span of spans)span.end<=pending.start?result.push(span):pending.end<=span.start?(inserted||(result.push(pending),inserted=!0),result.push(span)):pending={start:Math.min(pending.start,span.start),end:Math.max(pending.end,span.end)};inserted||result.push(pending),spans.splice(0,spans.length,...result)}function insertLaterally(entries,entry){entries.splice(findLowerBoundByStart(entries,entry.start),0,entry)}function findLowerBoundByStart(entries,start){let low=0,high=entries.length;for(;low<high;){let middle=low+high>>>1;entries[middle].start<start?low=middle+1:high=middle}return low}var GEOMETRY_TOLERANCE=1e-6,DEFAULT_UNMEASURED_EVENT_THICKNESS=20;function buildLevelLimitedLayout(segs,eventOrderStrict,eventSlicing,maxLevels,moreLinkLevelTax,sliceHeights){let{segLevels,excludedSegs}=buildSegLevels(segs,eventOrderStrict,maxLevels),placement=placeExtraSlicesInLevels(convertSegLevelsToWholeSlices(segLevels),convertSegsToWholeSlices(excludedSegs),eventOrderStrict,eventSlicing,moreLinkLevelTax),resolution=resolveLevelCoords(placement.sliceLevels,sliceHeights);return{renderSlices:flatArray(placement.sliceLevels),hiddenSlices:placement.hiddenSlices,sliceLevels:placement.sliceLevels,sliceCoords:resolution.sliceCoords,isSettled:resolution.isSettled}}function buildPixelLimitedLayout(segs,eventOrderStrict,eventSlicing,sliceHeights,canvasHeight,levelCapacity,moreLinkHeight){let{segLevels,excludedSegs}=buildSegLevels(segs,eventOrderStrict,levelCapacity),domWholeSliceLevels=convertSegLevelsToWholeSlices(segLevels),domExcludedWholeSlices=convertSegsToWholeSlices(excludedSegs),wholeResolution=resolveLevelCoords(domWholeSliceLevels,sliceHeights,canvasHeight);if(canvasHeight==null||moreLinkHeight==null)return{renderSlices:flatArray(domWholeSliceLevels),hiddenSlices:domExcludedWholeSlices,sliceLevels:domWholeSliceLevels,sliceCoords:wholeResolution.sliceCoords,isSettled:wholeResolution.isSettled};let excludedWholeSlices=wholeResolution.excludedSlices.concat(domExcludedWholeSlices);excludedWholeSlices.sort(compareByEventOrder);let placement=placeExtraSlicesInLevels(wholeResolution.placementSliceLevels,excludedWholeSlices,eventOrderStrict,eventSlicing,eventSlicing?1:0,!0,!0),sliceResolution=resolveLevelCoords(placement.sliceLevels,sliceHeights),moreLinkEventMax=Math.max(0,canvasHeight-moreLinkHeight),pixelPrunedSlices=prunePixelLimitedSliceLevels(placement.sliceLevels,placement.hiddenSlices,sliceResolution.sliceCoords,sliceHeights,canvasHeight,moreLinkEventMax),renderSlices=flatArray(domWholeSliceLevels).concat(placement.addedSlices),isSettled=wholeResolution.isSettled&&sliceResolution.isSettled;return{renderSlices,hiddenSlices:pixelPrunedSlices.concat(placement.hiddenSlices),sliceLevels:placement.sliceLevels,sliceCoords:sliceResolution.sliceCoords,isSettled}}function buildSegLevels(segs,eventOrderStrict,maxLevels=1/0){let segLevels=[],excludedSegs=[];for(let seg of segs){let levelIndex=findPackedLevelIndex(segLevels,seg,eventOrderStrict);if(levelIndex>=maxLevels)excludedSegs.push(seg);else{for(;segLevels.length<=levelIndex;)segLevels.push([]);insertLaterally(segLevels[levelIndex],seg)}}return{segLevels,excludedSegs}}function findPackedLevelIndex(levels,span,orderStrict){let levelIndex=0;if(orderStrict)for(let i=0;i<levels.length;i++)findIntersections(levels[i],span).length&&(levelIndex=i+1);else for(;levelIndex<levels.length&&findIntersections(levels[levelIndex],span).length;)levelIndex++;return levelIndex}function convertSegLevelsToWholeSlices(segLevels){return segLevels.map(level=>convertSegsToWholeSlices(level))}function convertSegsToWholeSlices(segs){return segs.map(createWholeSlice)}function resolveLevelCoords(sliceLevels,sliceHeights,maxPixels=1/0){let placementSliceLevels=[],sliceCoords=new Map,isSettled=!0,excludedSlices=[];for(let levelIndex=0;levelIndex<sliceLevels.length;levelIndex++)for(let slice of sliceLevels[levelIndex]){let sliceHeight=sliceHeights.get(getSliceKey(slice));if(sliceHeight===void 0){isSettled=!1;continue}let{bottom:levelCoord,levelIndex:packedLevelIndex}=computeLateralSpanPlacement(placementSliceLevels,slice,sliceCoords,sliceHeights);if(levelCoord+sliceHeight<=maxPixels+GEOMETRY_TOLERANCE){for(;placementSliceLevels.length<=packedLevelIndex;)placementSliceLevels.push([]);insertLaterally(placementSliceLevels[packedLevelIndex],slice),sliceCoords.set(getSliceKey(slice),levelCoord)}else excludedSlices.push(slice)}return{placementSliceLevels,sliceCoords,isSettled,excludedSlices}}function computeLateralSpanPlacement(sliceLevels,span,sliceCoords,sliceHeights){let bottom=0,levelIndex=0;for(let i=0;i<sliceLevels.length;i++){let level=sliceLevels[i];for(let slice of findIntersections(level,span)){let key=getSliceKey(slice),sliceTop=sliceCoords.get(key),sliceHeight=sliceHeights.get(key);sliceTop!==void 0&&sliceHeight!==void 0&&(bottom=Math.max(bottom,sliceTop+sliceHeight),levelIndex=i+1)}}return{bottom,levelIndex}}function recomputeVisibleCoords(sliceLevels,sliceHeights,sliceCoords){let visibleLevels=sliceLevels.map(level=>level.filter(slice=>sliceCoords.has(getSliceKey(slice)))),freshCoords=resolveLevelCoords(visibleLevels,sliceHeights).sliceCoords;for(let[key,coord]of freshCoords)sliceCoords.set(key,coord)}function getSliceBottom(slice,sliceCoords,sliceHeights){let key=getSliceKey(slice),coord=sliceCoords.get(key),height=sliceHeights.get(key);return coord===void 0||height===void 0?void 0:coord+height}function prunePixelLimitedSliceLevels(sliceLevels,initialHiddenSlices,sliceCoords,sliceHeights,maxPixelHeight,moreLinkMaxPixelHeight){let moreLinkGroups=[],pixelPrunedSlices=[],sliceHideQueue=[],sliceHideIndex=0;for(let hiddenSlice of initialHiddenSlices)addHiddenSliceToGroups(moreLinkGroups,hiddenSlice);for(enqueueViolators();sliceHideIndex<sliceHideQueue.length;){let slice=sliceHideQueue[sliceHideIndex++],sliceBottom=getSliceBottom(slice,sliceCoords,sliceHeights);if(sliceBottom===void 0||!violatesPixelBoundary(slice,sliceBottom))continue;sliceCoords.delete(getSliceKey(slice)),pixelPrunedSlices.push(slice);let newMoreLinkSpans=addHiddenSliceToGroups(moreLinkGroups,slice);recomputeVisibleCoords(sliceLevels,sliceHeights,sliceCoords);for(let newMoreLinkSpan of newMoreLinkSpans)enqueueViolators(newMoreLinkSpan)}return pixelPrunedSlices;function violatesPixelBoundary(slice,sliceBottom){return sliceBottom>maxPixelHeight+GEOMETRY_TOLERANCE||sliceBottom>moreLinkMaxPixelHeight+GEOMETRY_TOLERANCE&&findIntersections(moreLinkGroups,slice).length>0}function enqueueViolators(withinSpan){for(let level of sliceLevels){let candidates=withinSpan?findIntersections(level,withinSpan):level;for(let slice of candidates){let sliceBottom=getSliceBottom(slice,sliceCoords,sliceHeights);sliceBottom!==void 0&&violatesPixelBoundary(slice,sliceBottom)&&sliceHideQueue.push(slice)}}}}function placeExtraSlicesInLevels(sliceLevels,extraSlices,eventOrderStrict,eventSlicing,moreLinkLevelTax,requiresSlicing=!1,taxDeepestOccupiedLevel=!1){let addedSliceSet=new Set,hiddenSlices=[],moreLinkGroups=[],moreLinkReservations=[],placementState={levels:sliceLevels,moreLinkReservations,eventOrderStrict},work=[];for(pushFire(extraSlices,requiresSlicing);work.length;){let item=work.pop();item.type==="fire"?fire(item.slice,item.requiresSlicing):fireMoreLink(item.span)}return{sliceLevels,hiddenSlices,addedSlices:[...addedSliceSet]};function fire(slice,requiresSlicing2){if(!requiresSlicing2){let levelIndex=findInsertionLevel(slice,placementState);if(levelIndex!==null){insertLaterally(sliceLevels[levelIndex],slice),addedSliceSet.add(slice);return}}if(!eventSlicing){hide(slice);return}let plan=findBestSlicePlan(slice,placementState,requiresSlicing2);if(!plan){hide(slice);return}for(let visibleSlice of plan.slices)insertLaterally(sliceLevels[plan.levelIndex],visibleSlice),addedSliceSet.add(visibleSlice);for(let hiddenSlice of subtractSpansFromSlice(slice,plan.slices))hide(hiddenSlice)}function hide(slice){hiddenSlices.push(slice);let newMoreLinkSpans=addHiddenSliceToGroups(moreLinkGroups,slice);if(moreLinkLevelTax)for(let i=newMoreLinkSpans.length-1;i>=0;i--)work.push({type:"moreLink",span:newMoreLinkSpans[i]})}function fireMoreLink(span){if(!sliceLevels.length)return;let taxedLevelIndex=sliceLevels.length-1,victims=findIntersections(sliceLevels[taxedLevelIndex],span);if(taxDeepestOccupiedLevel)for(;!victims.length&&taxedLevelIndex>0;)taxedLevelIndex--,victims=findIntersections(sliceLevels[taxedLevelIndex],span);insertLaterally(moreLinkReservations,{...span,levelIndex:taxedLevelIndex});let taxedLevel=sliceLevels[taxedLevelIndex];for(let victim of victims)taxedLevel.splice(taxedLevel.indexOf(victim),1),addedSliceSet.delete(victim),eventSlicing?(hide(intersectSlice(victim,span)),pushFire(subtractSpansFromSlice(victim,[span]),!1)):hide(victim)}function pushFire(slices,requiresSlicing2){for(let i=slices.length-1;i>=0;i--)work.push({type:"fire",slice:slices[i],requiresSlicing:requiresSlicing2})}}function findInsertionLevel(slice,state){let fence=computeLevelFence(slice,state);for(let levelIndex=fence.min;levelIndex<fence.maxExclusive;levelIndex++)if(!findIntersections(state.levels[levelIndex],slice).length)return levelIndex;return null}function computeLevelFence(slice,state){let{levels}=state,min=0,maxExclusive=levels.length;for(let reservation of findIntersections(state.moreLinkReservations,slice))maxExclusive=Math.min(maxExclusive,reservation.levelIndex);if(state.eventOrderStrict)for(let levelIndex=0;levelIndex<levels.length;levelIndex++)for(let other of findIntersections(levels[levelIndex],slice))other.sourceSeg.orderIndex<slice.sourceSeg.orderIndex?min=Math.max(min,levelIndex+1):other.sourceSeg.orderIndex>slice.sourceSeg.orderIndex&&(maxExclusive=Math.min(maxExclusive,levelIndex));return{min,maxExclusive}}var MAX_SLICES_PER_PLAN=3,EXTRA_SLICE_PENALTY=.15;function findBestSlicePlan(slice,state,requiresSlicing){let selected=null,sourceLength=getSpanLength(slice);for(let levelIndex=0;levelIndex<state.levels.length;levelIndex++){let blockers=findIntersections(state.levels[levelIndex],slice);for(let reservation of state.moreLinkReservations)levelIndex>=reservation.levelIndex&&addToUnion(blockers,reservation);let runs=subtractSpansFromSlice(slice,blockers).filter(run=>isWithinLevelFence(run,levelIndex,state)).sort((a,b)=>getSpanLength(b)-getSpanLength(a)||a.start-b.start),visibleLength=0;for(let sliceCount=1;sliceCount<=Math.min(MAX_SLICES_PER_PLAN,runs.length)&&(visibleLength+=getSpanLength(runs[sliceCount-1]),!(requiresSlicing&&visibleLength>=sourceLength-GEOMETRY_TOLERANCE));sliceCount++){let candidate={levelIndex,slices:runs.slice(0,sliceCount),score:visibleLength/sourceLength-EXTRA_SLICE_PENALTY*(sliceCount-1)};isBetterSlicePlan(candidate,selected)&&(selected=candidate)}}return selected&&selected.slices.sort(compareByEventOrder),selected}function isWithinLevelFence(slice,levelIndex,state){let fence=computeLevelFence(slice,state);return levelIndex>=fence.min&&levelIndex<fence.maxExclusive}function isBetterSlicePlan(candidate,current){return!current||candidate.score>current.score?!0:candidate.score<current.score?!1:candidate.slices.length!==current.slices.length?candidate.slices.length<current.slices.length:candidate.levelIndex<current.levelIndex}function groupLaterallyIntersecting(hiddenSlices){let groups=[];for(let slice of hiddenSlices)addHiddenSliceToGroups(groups,slice);return finalizeHiddenGroups(groups)}function addHiddenSliceToGroups(groups,slice){let newSpans=subtractCoveredSpans(slice,groups),untouchedGroups=[],mergedSlices=[slice],start=slice.start,end=slice.end;for(let group of groups)intersectSpans(group,slice)?(mergedSlices.push(...group.hiddenSlices),start=Math.min(start,group.start),end=Math.max(end,group.end)):untouchedGroups.push(group);return mergedSlices.sort(compareByEventOrder),insertLaterally(untouchedGroups,{start,end,hiddenSlices:mergedSlices}),groups.splice(0,groups.length,...untouchedGroups),newSpans}function finalizeHiddenGroups(groups){return groups.map(group=>{let hiddenSlices=mergeAdjacentSlices(group.hiddenSlices);return{key:getSliceKey(hiddenSlices[0]),start:group.start,end:group.end,hiddenSlices}})}function getSliceKey(slice){return isPartialSlice(slice)?`${slice.sourceSeg.key}:${slice.start}:slice`:slice.sourceSeg.key}function isPartialSlice(slice){return slice.start!==slice.sourceSeg.start||slice.end!==slice.sourceSeg.end}function compareByEventOrder(a,b){return a.sourceSeg.orderIndex-b.sourceSeg.orderIndex||a.start-b.start||b.end-a.end}function sortByEventOrder(slices){return[...slices].sort(compareByEventOrder)}function compareByAxisOrder(a,b){return a.start-b.start||a.sourceSeg.orderIndex-b.sourceSeg.orderIndex}function sortByAxisOrder(items){return[...items].sort(compareByAxisOrder)}function mergeAdjacentSlices(slices){let merged=[];for(let slice of slices){let previous=merged[merged.length-1];previous&&previous.sourceSeg===slice.sourceSeg?merged[merged.length-1]=createNarrowerSlice(createWholeSlice(previous.sourceSeg),previous.start,Math.max(previous.end,slice.end)):merged.push(slice)}return merged}function subtractSpansFromSlice(slice,covered){return subtractCoveredSpans(slice,covered).map(span=>createNarrowerSlice(slice,span.start,span.end))}function intersectSlice(slice,barrier){let intersection=intersectSpans(slice,barrier);return intersection?createNarrowerSlice(slice,intersection.start,intersection.end):null}function createWholeSlice(sourceSeg){return{sourceSeg,start:sourceSeg.start,end:sourceSeg.end,isStart:sourceSeg.isStart,isEnd:sourceSeg.isEnd}}function createNarrowerSlice(parent,start,end){return{sourceSeg:parent.sourceSeg,start,end,isStart:parent.isStart&&start===parent.start,isEnd:parent.isEnd&&end===parent.end}}var DEFAULT_UNMEASURED_EVENT_AREA_HEIGHT=150,DEFAULT_LEVEL_CAPACITY=estimateLevelCapacity(DEFAULT_UNMEASURED_EVENT_AREA_HEIGHT,DEFAULT_UNMEASURED_EVENT_THICKNESS);function buildDayGridSegSources(eventOrderedSegs){return eventOrderedSegs.map((seg,orderIndex)=>({...seg,key:getDayGridSegKey(seg),orderIndex}))}function buildDayGridLevelPlacements(eventOrderedSegs,maxLevels,moreLinkLevelTax,orderStrict,eventSlicing,columnCount,sliceHeights){let sourceSegs=buildDayGridSegSources(eventOrderedSegs),layout=buildLevelLimitedLayout(sourceSegs,orderStrict,eventSlicing,maxLevels,moreLinkLevelTax,sliceHeights);return buildDayGridPlacementLayout(sourceSegs,layout,sliceHeights,columnCount)}function buildDayGridPixelPlacements(eventOrderedSegs,orderStrict,eventSlicing,columnCount,canvasHeight,moreLinkHeight,levelCapacity,sliceHeights){let sourceSegs=buildDayGridSegSources(eventOrderedSegs),layout=buildPixelLimitedLayout(sourceSegs,orderStrict,eventSlicing,sliceHeights,canvasHeight,levelCapacity,moreLinkHeight);return buildDayGridPlacementLayout(sourceSegs,layout,sliceHeights,columnCount)}function buildDayGridPopoverSegs(eventOrderedSegs,hiddenSlices,column){return{segs:flatMapArray(eventOrderedSegs,source=>cutSegToColumn(source,column)??[]),hiddenSegs:flatMapArray(hiddenSlices,slice=>cutSegToColumn(slice.sourceSeg,column,slice)??[])}}function cutSegToColumn(source,column,intersectionSpan=source){if(intersectionSpan.start>=column+1||column>=intersectionSpan.end)return null;let{key,orderIndex,...seg}=source;return{...seg,start:column,end:column+1,isStart:seg.isStart&&source.start===column,isEnd:seg.isEnd&&source.end-1===column}}function resolveDayGridPlacementMode(dayMaxEvents,dayMaxEventRows){return dayMaxEvents===!0||dayMaxEventRows===!0?"auto":typeof dayMaxEvents=="number"?"maxEvents":typeof dayMaxEventRows=="number"?"maxEventRows":"unlimited"}function computeDayGridDomCandidateMaxLevels(mode,dayMaxEvents,dayMaxEventRows,maxDomLevels){switch(mode){case"auto":return maxDomLevels;case"maxEvents":return dayMaxEvents;case"maxEventRows":return dayMaxEventRows;default:return 1/0}}function computeDayGridMoreLinkLevelTax(mode){return mode==="maxEventRows"?1:0}function buildDayGridPlacementLayout(sourceSegs,layout,sliceHeights,columnCount){let{hiddenSlices,renderSlices,sliceCoords}=layout,eventOrderedHiddenSlices=sortByEventOrder(hiddenSlices),slicesByStart=federateSlicesByStart(renderSlices,columnCount),columns=Array.from({length:columnCount},(_,column)=>({renderSlices:slicesByStart[column],contentHeight:0,...buildDayGridPopoverSegs(sourceSegs,eventOrderedHiddenSlices,column)}));for(let slice of renderSlices){let key=getSliceKey(slice),sliceTop=sliceCoords.get(key);if(sliceTop===void 0)continue;let sliceBottom=sliceTop+sliceHeights.get(key);for(let column=slice.start;column<slice.end;column+=1)columns[column].contentHeight=Math.max(columns[column].contentHeight,sliceBottom)}return{columns,sliceCoords}}function federateSlicesByStart(renderSlices,columnCount){let slicesByStart=Array.from({length:columnCount},()=>[]);for(let slice of renderSlices)slicesByStart[slice.start].push(slice);for(let slices of slicesByStart)slices.sort(compareByEventOrder);return slicesByStart}function estimateLevelCapacity(eventAreaHeight,eventHeight){return Math.max(1,Math.ceil(eventAreaHeight/eventHeight))}var DEFAULT_PRINT_MAX_LEVELS=200;function planPrintDomCandidates(eventOrderedSegs,eventOrderStrict,eventSlicing){let{segLevels,excludedSegs}=buildSegLevels(eventOrderedSegs,eventOrderStrict,DEFAULT_PRINT_MAX_LEVELS),placement=placeExtraSlicesInLevels(convertSegLevelsToWholeSlices(segLevels),convertSegsToWholeSlices(excludedSegs),eventOrderStrict,eventSlicing,0);return{sliceLevels:placement.sliceLevels,hiddenSlices:placement.hiddenSlices}}function buildPrintEventBands(levels,printEventThicknesses,getPrintEventKey=slice=>slice.sourceSeg.key,defaultPrintEventThickness=DEFAULT_UNMEASURED_EVENT_THICKNESS){let bands=[];for(let levelIndex=0;levelIndex<levels.length;levelIndex++){let entries=levels[levelIndex];if(!entries?.length)continue;let thickness=0,slices=entries.map(slice=>(thickness=Math.max(thickness,printEventThicknesses.get(getPrintEventKey(slice))??defaultPrintEventThickness),slice));bands.push({levelIndex,slices,thickness})}return bands}function buildDayGridPrintPlan(eventOrderedSegs,orderStrict,eventSlicing,columnCount){let sourceSegs=buildDayGridSegSources(eventOrderedSegs),candidatePlan=planPrintDomCandidates(sourceSegs,orderStrict,eventSlicing);return{...candidatePlan,hiddenSlices:sortByEventOrder(candidatePlan.hiddenSlices),sourceSegs,columnCount}}function buildDayGridPrintColumns(plan,printSegHeights){let columns=Array.from({length:plan.columnCount},()=>[]);for(let band of buildPrintEventBands(plan.sliceLevels,printSegHeights,getDayGridPrintSliceKey)){let slicesByColumn=Array(plan.columnCount).fill(null);for(let slice of band.slices)slicesByColumn[slice.start]=slice;for(let column=0;column<plan.columnCount;column++)columns[column].push({levelIndex:band.levelIndex,thickness:band.thickness,slice:slicesByColumn[column]})}return columns}function getDayGridPrintSliceKey(slice){return`${slice.sourceSeg.key}:${slice.start}:${slice.end}`}var DEFAULT_WEEK_NUM_FORMAT=createFormatter({week:"narrow"}),DayGridRow=class extends BaseComponent{constructor(){super(...arguments),this.headerHeightRefMap=new RefMap(()=>{afterSize(this.handleSegPositioning)}),this.mainHeightRefMap=new RefMap(()=>{(this.props.dayMaxEvents===!0||this.props.dayMaxEventRows===!0)&&afterSize(this.handleSegPositioning)}),this.sliceHeightRefMap=new RefMap(()=>{afterSize(this.handleSegPositioning)}),this.handlePrintSegHeightChange=()=>{afterSize(this.handlePrintSegHeights)},this.printSegHeightRefMap=new RefMap(this.handlePrintSegHeightChange),this.buildWeekNumberRenderProps=memoize2(buildWeekNumberRenderProps),this.buildPrintPlan=memoize2(buildDayGridPrintPlan),this.sortEventSegs=memoize2(sortEventSegs),this.levelCapacity=DEFAULT_LEVEL_CAPACITY,this.handleRootEl=rootEl=>{this.disconnectHeight?.(),this.disconnectHeight=void 0,setRef(this.props.rootElRef,rootEl),rootEl&&(this.disconnectHeight=watchHeight(rootEl,contentHeight=>{setRef(this.props.heightRef,contentHeight)}))},this.handleSegPositioning=()=>{this._isUnmounting||this.props.forPrint||(this.updateAutoPlacementRatchets(),this.forceUpdate())},this.handlePrintSegHeights=()=>{this._isUnmounting||!this.props.forPrint||this.forceUpdate()}}render(){let{props,context,headerHeightRefMap,mainHeightRefMap}=this,{cells,tableMode}=props,{options}=context,weekDateMarker=props.cells[0].date,fgEventSegs=this.sortEventSegs(props.fgEventSegs,options.eventOrder),screenFgLiquidHeight=props.dayMaxEvents===!0||props.dayMaxEventRows===!0,printPlan=null,printColumns=null,screenColumns=null,screenSliceCoords=new Map,screenMainOffsetsByCol=[],screenHeightsByCol=[];if(props.forPrint)printPlan=this.buildPrintPlan(fgEventSegs,options.eventOrderStrict,options.eventSlicing,cells.length),printColumns=buildDayGridPrintColumns(printPlan,this.printSegHeightRefMap.current);else{let placementMode=resolveDayGridPlacementMode(props.dayMaxEvents,props.dayMaxEventRows),[maxMainTop,minMainHeight]=this.computeFgDims(),screenLayout=placementMode==="auto"?buildDayGridPixelPlacements(fgEventSegs,options.eventOrderStrict,options.eventSlicing,cells.length,minMainHeight,props.moreLinkHeight,this.levelCapacity,this.sliceHeightRefMap.current):buildDayGridLevelPlacements(fgEventSegs,computeDayGridDomCandidateMaxLevels(placementMode,props.dayMaxEvents,props.dayMaxEventRows,1/0),computeDayGridMoreLinkLevelTax(placementMode),options.eventOrderStrict,options.eventSlicing,cells.length,this.sliceHeightRefMap.current);if(screenColumns=screenLayout.columns,screenSliceCoords=screenLayout.sliceCoords,maxMainTop!=null)for(let col=0;col<cells.length;col++){let cellHeaderHeight=headerHeightRefMap.current.get(cells[col].key),mainOffset=cellHeaderHeight!=null?maxMainTop-cellHeaderHeight:void 0;screenMainOffsetsByCol.push(mainOffset),screenHeightsByCol.push(mainOffset!=null?screenColumns[col].contentHeight+mainOffset:void 0)}}let highlightSegs=this.getHighlightSegs(),hasNavLink=options.navLinks,fullWeekStr=buildDateStr(context,weekDateMarker,"week"),weekNumberRenderProps=this.buildWeekNumberRenderProps(weekDateMarker,context,props.cellIsNarrow,hasNavLink),fillsByCol=cells.map(()=>[]),weekNumberNode=props.showWeekNumbers&&!props.cellIsMicro?jsx11(ContentContainer,{tag:"div",attrs:{...hasNavLink?buildNavLinkAttrs(context,weekDateMarker,"week",fullWeekStr,!1):{},role:void 0,"aria-hidden":!0},className:DAY_GRID_EVENT_Z_CLASS,renderProps:weekNumberRenderProps,generatorName:"inlineWeekNumberContent",customGenerator:options.inlineWeekNumberContent,defaultGenerator:renderText,classNameGenerator:options.inlineWeekNumberClass,didMount:options.inlineWeekNumberDidMount,willUnmount:options.inlineWeekNumberWillUnmount}):null;return tableMode&&weekNumberNode&&fillsByCol[0].push(jsx11("div",{className:joinClassNames(classNames.fillY,classNames.start0,classNames.pointerEventsNone),style:{width:this.computeSpanWidth(0,cells.length)},children:weekNumberNode},"week-number")),this.appendFillSegs(fillsByCol,props.businessHourSegs,"non-business",DAY_GRID_NON_BUSINESS_Z_CLASS),this.appendFillSegs(fillsByCol,props.bgEventSegs,"bg-event",DAY_GRID_BG_EVENT_Z_CLASS),this.appendFillSegs(fillsByCol,highlightSegs,"highlight",DAY_GRID_HIGHLIGHT_Z_CLASS),jsxs8(tableMode?"tr":"div",{role:props.role,"aria-label":props.role==="row"?fullWeekStr:void 0,className:joinClassNames(options.dayRowClass,props.className,tableMode&&classNames.borderless,!tableMode&&classNames.flexRow,!tableMode&&classNames.rel,!tableMode&&classNames.borderlessX,!tableMode&&classNames.borderlessTop,!tableMode&&!props.borderBottom&&classNames.borderlessBottom,classNames.isolate),style:{flexBasis:tableMode?void 0:props.basis},ref:this.handleRootEl,children:[!tableMode&&weekNumberNode,props.cells.map((cell,col)=>{let printPopover=printPlan?buildDayGridPopoverSegs(printPlan.sourceSegs,printPlan.hiddenSlices,col):null,fg;return printPlan?fg=this.renderPrintBandSlots(printColumns[col]):fg=[...this.renderLevelFgSegs(screenMainOffsetsByCol[col],screenColumns[col].renderSlices,screenSliceCoords),...this.renderMirrorFgSegs(col,screenMainOffsetsByCol[col],screenSliceCoords)],jsx11(DayGridCell,{dateProfile:props.dateProfile,todayRange:props.todayRange,date:cell.date,isMajor:cell.isMajor,isDisabled:cell.isDisabled,showDayNumber:props.showDayNumbers,isNarrow:props.cellIsNarrow,isMicro:props.cellIsMicro,borderStart:!!col,borderBottom:props.borderBottom,tableMode,fills:fillsByCol[col],segs:printPopover?printPopover.segs:screenColumns[col].segs,hiddenSegs:printPopover?printPopover.hiddenSegs:screenColumns[col].hiddenSegs,fgLiquidHeight:printPlan?!1:screenFgLiquidHeight,fg,eventDrag:printPlan?null:props.eventDrag,eventResize:printPlan?null:props.eventResize,eventSelection:props.eventSelection,renderProps:cell.renderProps,dateSpanProps:cell.dateSpanProps,attrs:cell.attrs,className:cell.className,fgHeight:printPlan?void 0:screenHeightsByCol[col],width:props.colWidth,headerHeightRef:printPlan?void 0:headerHeightRefMap.createRef(cell.key),mainHeightRef:printPlan?void 0:mainHeightRefMap.createRef(cell.key)},cell.key)})]})}renderMirrorFgSegs(col,mainOffset,sliceCoords){let{props}=this,{eventSelection}=props,nodes=[];for(let seg of this.getMirrorSegs()){if(seg.start!==col)continue;let key=getDayGridSegKey(seg),{eventRange}=seg,{instanceId}=eventRange.instance,top=mainOffset!=null?mainOffset+(sliceCoords.get(key)??0):void 0,isDragging=!!(props.eventDrag&&props.eventDrag.affectedInstances[instanceId]),isResizing=!!(props.eventResize&&props.eventResize.affectedInstances[instanceId]),isSelected=instanceId===eventSelection;nodes.push(jsx11(MeasuredHeightHarness,{className:joinClassNames(classNames.abs,classNames.start0,DAY_GRID_INTERACTION_Z_CLASS),style:{top,width:this.computeSpanWidth(seg.start,seg.end)},heightRef:null,children:this.renderEventContent(seg,eventRange,{isDragging,isResizing,isMirror:!0,isSelected})},`mirror:${key}`))}return nodes}renderLevelFgSegs(mainOffset,slices,sliceCoords){let{props}=this,{eventSelection}=props,nodes=[];for(let slice of slices){let key=getSliceKey(slice),sliceTop=sliceCoords.get(key),{eventRange}=slice.sourceSeg,{instanceId}=eventRange.instance,top=mainOffset!=null&&sliceTop!=null?mainOffset+sliceTop:void 0,isDragging=!!(props.eventDrag&&props.eventDrag.affectedInstances[instanceId]),isResizing=!!(props.eventResize&&props.eventResize.affectedInstances[instanceId]),isInvisible=isDragging||isResizing||top==null,isSelected=instanceId===eventSelection;nodes.push(jsx11(MeasuredHeightHarness,{className:joinClassNames(classNames.abs,classNames.start0,isSelected?DAY_GRID_INTERACTION_Z_CLASS:DAY_GRID_EVENT_Z_CLASS),style:{visibility:isInvisible?"hidden":void 0,top,width:this.computeSpanWidth(slice.start,slice.end)},heightRef:this.sliceHeightRefMap.createRef(key),children:this.renderEventContent(slice,eventRange,{isDragging,isResizing,isSelected})},key))}return nodes}renderEventContent(range,eventRange,interaction){let{props}=this,isListItem=hasListItemDisplay(range,eventRange);return jsx11(StandardEvent,{display:isListItem?"list-item":"row",eventRange,isStart:range.isStart,isEnd:range.isEnd,isDragging:!!interaction.isDragging,isResizing:!!interaction.isResizing,isMirror:!!interaction.isMirror,isSelected:!!interaction.isSelected,isNarrow:props.cellIsNarrow,defaultTimeFormat:DEFAULT_TABLE_EVENT_TIME_FORMAT,defaultDisplayEventEnd:props.cells.length===1,disableResizing:isListItem,forcedTimeText:props.cellIsMicro?"":void 0,...getEventRangeMeta(eventRange,props.todayRange)})}renderPrintBandSlots(slots){let{printSegHeightRefMap}=this;return slots.map(slot=>{let{slice}=slot,eventNode=null;if(slice){let sliceKey=getDayGridPrintSliceKey(slice);eventNode=jsx11(MeasuredHeightHarness,{className:joinClassNames(classNames.rel,classNames.flowRoot,DAY_GRID_EVENT_Z_CLASS),style:{width:this.computeSpanWidth(slice.start,slice.end)},heightRef:printSegHeightRefMap.createRef(sliceKey),children:this.renderEventContent(slice,slice.sourceSeg.eventRange,{})},sliceKey)}return jsx11("div",{className:classNames.breakInsideAvoid,style:{height:slot.thickness},children:eventNode},slot.levelIndex)})}computeSpanWidth(start,end){let span=end-start,percentWidth=`${span*100}%`,crossedBorderWidth=this.props.tableMode&&start===0?0:Math.max(0,span-1)*COL_BORDER_WIDTH;return crossedBorderWidth?`calc(${percentWidth} + ${crossedBorderWidth}px)`:percentWidth}appendFillSegs(fillsByCol,segs,fillType,zClassName){let{props,context}=this,{todayRange}=props;for(let seg of segs)fillsByCol[seg.start].push(jsx11("div",{className:joinClassNames(classNames.fillY,classNames.start0,zClassName),style:{width:this.computeSpanWidth(seg.start,seg.end)},children:fillType==="bg-event"?jsx11(BgEvent,{eventRange:seg.eventRange,isStart:seg.isStart,isEnd:seg.isEnd,isNarrow:props.cellIsNarrow,isVertical:!1,...getEventRangeMeta(seg.eventRange,todayRange)}):renderFill(fillType,context.options)},`${fillType}:${buildEventRangeKey(seg.eventRange)}:${seg.start}:${seg.end}`))}componentDidMount(){this._isUnmounting=!1}componentDidUpdate(prevProps){prevProps.forPrint&&!this.props.forPrint&&(this.printSegHeightRefMap=new RefMap(this.handlePrintSegHeightChange))}componentWillUnmount(){this._isUnmounting=!0,this.disconnectHeight?.(),setRef(this.props.heightRef,null)}computeFgDims(){let{cells}=this.props,headerHeightMap=this.headerHeightRefMap.current,mainHeightMap=this.mainHeightRefMap.current,maxMainTop,minMainBottom,isComplete=!0;for(let cell of cells){if(cell.isDisabled)continue;let mainTop=headerHeightMap.get(cell.key),mainHeight=mainHeightMap.get(cell.key);if((mainTop==null||mainHeight==null)&&(isComplete=!1),mainTop!=null&&((maxMainTop===void 0||mainTop>maxMainTop)&&(maxMainTop=mainTop),mainHeight!=null)){let mainBottom=mainTop+mainHeight;(minMainBottom===void 0||mainBottom<minMainBottom)&&(minMainBottom=mainBottom)}}return[maxMainTop,isComplete&&minMainBottom!=null&&maxMainTop!=null?minMainBottom-maxMainTop:void 0]}updateAutoPlacementRatchets(){if(resolveDayGridPlacementMode(this.props.dayMaxEvents,this.props.dayMaxEventRows)!=="auto")return;let[,canvasHeight]=this.computeFgDims();if(canvasHeight!=null){let smallestSliceHeight=Math.min(...this.sliceHeightRefMap.current.values());this.levelCapacity=Math.max(this.levelCapacity,estimateLevelCapacity(canvasHeight,smallestSliceHeight))}}getMirrorSegs(){let{props}=this;return props.eventResize&&props.eventResize.segs.length?props.eventResize.segs:[]}getHighlightSegs(){let{props}=this;return props.eventDrag&&props.eventDrag.segs.length?props.eventDrag.segs:props.eventResize&&props.eventResize.segs.length?props.eventResize.segs:props.dateSelectionSegs}};function buildWeekNumberRenderProps(weekDateMarker,context,isNarrow,hasNavLink){let{dateEnv,options}=context,weekNum=dateEnv.computeWeekNumber(weekDateMarker),weekNumTextParts=dateEnv.formatToParts(weekDateMarker,options.weekNumberFormat||DEFAULT_WEEK_NUM_FORMAT),weekNumText=joinDateTimeFormatParts(weekNumTextParts),weekDateZoned=dateEnv.toDate(weekDateMarker);return{num:weekNum,text:weekNumText,textParts:weekNumTextParts,date:weekDateZoned,isNarrow,hasNavLink}}var DaySeriesModel=class{constructor(range,dateProfileGenerator){let date=range.start,{end}=range,entries=[],dates=[],dayIndex=-1;for(;date<end;)dateProfileGenerator.isHiddenDay(date)?entries.push({kind:"hidden",previousIndex:dayIndex,nextIndex:dayIndex+1}):(dayIndex+=1,entries.push({kind:"visible",index:dayIndex}),dates.push(date)),date=addDays4(date,1);this.rangeStart=range.start,this.dates=dates,this.entries=entries,this.cnt=dates.length}sliceRange(range){let firstResult=this.getDateIndex(range.start),lastResult=this.getDateIndex(addDays4(range.end,-1)),firstIndex=getFirstVisibleIndex(firstResult),lastIndex=getLastVisibleIndex(lastResult),clippedFirstIndex=Math.max(0,firstIndex),clippedLastIndex=Math.min(this.cnt-1,lastIndex);return clippedFirstIndex<=clippedLastIndex?{start:clippedFirstIndex,end:clippedLastIndex+1,isStart:firstResult.kind==="visible"&&firstIndex===clippedFirstIndex,isEnd:lastResult.kind==="visible"&&lastIndex===clippedLastIndex}:null}getDateIndex(date){let dayOffset=Math.floor(diffDays4(this.rangeStart,date));return dayOffset<0?{kind:"before",index:-1}:dayOffset>=this.entries.length?{kind:"after",index:this.cnt}:this.entries[dayOffset]}};function getFirstVisibleIndex(result){return result.kind==="hidden"?result.nextIndex:result.index}function getLastVisibleIndex(result){return result.kind==="hidden"?result.previousIndex:result.index}function buildDayTableModel(dateProfile,dateProfileGenerator,dateEnv){let daySeries=new DaySeriesModel(dateProfile.renderRange,dateProfileGenerator),breakOnWeeks=/year|month|week/.test(dateProfile.currentRangeUnit),majorUnit=!breakOnWeeks&&computeMajorUnit(dateProfile,dateEnv);return new DayTableModel(daySeries,breakOnWeeks,dateEnv,majorUnit!=="day"?majorUnit:void 0,dateProfile.activeRange)}function computeColWidth(colCount,colMinWidth,viewportWidth){return viewportWidth==null?[void 0,void 0]:viewportWidth/colCount<colMinWidth?[colMinWidth*colCount,colMinWidth]:[viewportWidth,void 0]}function computeTopFromDate(date,cellRows,rowHeightMap){let top=0;for(let cells of cellRows){let key=cells[0].key,start=cells[0].date,end=cells[cells.length-1].date;if(date>=start&&date<=end)return top;let rowHeight=rowHeightMap.get(key);if(rowHeight==null)return;top+=rowHeight}return top}function computeColFromPosition(positionLeft,elWidth,colWidth,colCount,isRtl){let realColWidth=colWidth??elWidth/colCount,colFromLeft=Math.floor(positionLeft/realColWidth),col=isRtl?colCount-colFromLeft-1:colFromLeft,left=colFromLeft*realColWidth,right=left+realColWidth;return{col,left,right}}function computeRowFromPosition(positionTop,cellRows,rowHeightMap){let row=0,top=0,bottom=0;for(let cells of cellRows){let key=cells[0].key;if(top=bottom,bottom=top+rowHeightMap.get(key),positionTop<bottom)break;row++}return{row,top,bottom}}function getRowEl(rootEl,row){return rootEl.querySelectorAll("[role=row]")[row]}function getCellEl(rowEl,col){return rowEl.querySelectorAll("[role=gridcell]")[col]}var dayMicroWidth=60,dayHeaderMicroFormat=createFormatter({weekday:"narrow"});function createDayHeaderFormatter(explicitFormat,datesRepDistinctDays,dateCnt){return explicitFormat||computeFallbackHeaderFormat(datesRepDistinctDays,dateCnt)}function computeFallbackHeaderFormat(datesRepDistinctDays,dayCnt){return datesRepDistinctDays?dayCnt>1?createFormatter({weekday:"short",weekdayJustify:"start",day:"numeric",omitCommas:!0,omitTrailing:!0}):createFormatter({weekday:"long",weekdayJustify:"start",day:"numeric",omitCommas:!0,omitTrailing:!0}):createFormatter({weekday:"short"})}var DayGridRows=class extends DateComponent{constructor(){super(...arguments),this.state={},this.splitBusinessHourSegs=memoize2(splitSegsByRow),this.splitBgEventSegs=memoize2(splitAllDaySegsByRow),this.splitFgEventSegs=memoize2(splitSegsByRow),this.splitDateSelectionSegs=memoize2(splitSegsByRow),this.splitEventDrag=memoize2(splitInteractionByRow),this.splitEventResize=memoize2(splitInteractionByRow),this.rowHeightRefMap=new RefMap((height,key)=>{let{rowHeightRefMap}=this.props;rowHeightRefMap&&rowHeightRefMap.handleValue(height,key)}),this.handleMoreLinkEl=el=>{this.disconnectMoreLinkHeight?.(),this.disconnectMoreLinkHeight=void 0,el&&(this.disconnectMoreLinkHeight=watchHeight(el,height=>{this._isUnmounting||this.setState({moreLinkHeight:height})}))},this.handleRootEl=rootEl=>{this.rootEl=rootEl,rootEl?this.context.registerInteractiveComponent(this,{el:rootEl,isHitComboAllowed:this.props.isHitComboAllowed}):this.context.unregisterInteractiveComponent(this)}}render(){let{props,state,context,rowHeightRefMap}=this,{options}=context,{cellRows,tableMode}=props,rowCount=cellRows.length,firstCellKey=cellRows[0]?.[0]?.key||"",fgEventSegsByRow=this.splitFgEventSegs(props.fgEventSegs,rowCount),bgEventSegsByRow=this.splitBgEventSegs(props.bgEventSegs,rowCount),businessHourSegsByRow=this.splitBusinessHourSegs(props.businessHourSegs,rowCount),dateSelectionSegsByRow=this.splitDateSelectionSegs(props.dateSelectionSegs,rowCount),eventDragByRow=this.splitEventDrag(props.eventDrag,rowCount),eventResizeByRow=this.splitEventResize(props.eventResize,rowCount),isHeightAuto=getIsHeightAuto(options),rowHeightsRedistribute=!props.forPrint&&!isHeightAuto,rowBasis=computeRowBasis(props.visibleWidth,rowCount,isHeightAuto,options),needsMoreLinkProbe=!props.forPrint&&resolveDayGridPlacementMode(props.dayMaxEvents,props.dayMaxEventRows)==="auto";return jsxs8(Fragment6,{children:[jsx11(tableMode?"tbody":"div",{role:"rowgroup",className:joinClassNames(props.className,!tableMode&&!props.forPrint&&classNames.flexCol),style:tableMode?void 0:{width:props.width},ref:this.handleRootEl,children:cellRows.map((cells,row)=>jsx11(DayGridRow,{role:"row",dateProfile:props.dateProfile,todayRange:props.todayRange,cells,cellIsNarrow:props.cellIsNarrow,cellIsMicro:props.cellIsMicro,showDayNumbers:rowCount>1,showWeekNumbers:rowCount>1&&options.weekNumbers,forPrint:props.forPrint,tableMode,borderBottom:row<rowCount-1,className:rowHeightsRedistribute?classNames.grow:void 0,fgEventSegs:fgEventSegsByRow[row],bgEventSegs:bgEventSegsByRow[row],businessHourSegs:businessHourSegsByRow[row],dateSelectionSegs:dateSelectionSegsByRow[row],eventSelection:props.eventSelection,eventDrag:eventDragByRow[row],eventResize:eventResizeByRow[row],dayMaxEvents:props.dayMaxEvents,dayMaxEventRows:props.dayMaxEventRows,colWidth:props.colWidth,basis:rowBasis,moreLinkHeight:state.moreLinkHeight,heightRef:rowHeightRefMap.createRef(cells[0].key)},firstCellKey+":"+cells[0].key))}),needsMoreLinkProbe&&jsx11(MoreLinkTrigger,{num:1,display:"row",isNarrow:props.cellIsNarrow,isMicro:props.cellIsMicro,elRef:this.handleMoreLinkEl,className:classNames.offscreen,attrs:{"aria-hidden":!0,inert:""}})]})}componentDidMount(){this._isUnmounting=!1}componentWillUnmount(){this._isUnmounting=!0,this.disconnectMoreLinkHeight?.()}queryHit(isRtl,positionLeft,positionTop,elWidth){let{props}=this,colCount=props.cellRows[0].length,{col,left,right}=computeColFromPosition(positionLeft,elWidth,props.colWidth,colCount,isRtl),{row,top,bottom}=computeRowFromPosition(positionTop,props.cellRows,this.rowHeightRefMap.current),cell=props.cellRows[row][col],cellStartDate=cell.date,cellEndDate=addDays4(cellStartDate,1);return{dateProfile:props.dateProfile,dateSpan:{range:{start:cellStartDate,end:cellEndDate},allDay:!0,...cell.dateSpanProps},getDayEl:()=>getCellEl(getRowEl(this.rootEl,row),col),rect:{left,right,top,bottom},layer:0}}};function isSegAllDay(seg){return seg.eventRange.def.allDay}function splitAllDaySegsByRow(segs,rowCnt){return splitSegsByRow(segs.filter(isSegAllDay),rowCnt)}function computeRowBasis(visibleWidth,rowCount,isHeightAuto,options){if(visibleWidth!=null){let rowBasis=visibleWidth/options.aspectRatio/6;return rowCount>6||isHeightAuto?rowBasis:0}return 0}var DayGridHeaderCell=class extends BaseComponent{constructor(){super(...arguments),this.state={},this.buildDayHeaderText=memoize2(buildDayHeaderText),this.handleInnerEl=innerEl=>{this.disconnectSize&&(this.disconnectSize(),this.disconnectSize=void 0),innerEl?this.disconnectSize=watchSize(innerEl,(width,height)=>{this._isUnmounting||(setRef(this.props.innerHeightRef,height),this.setState({innerWidth:width}))}):setRef(this.props.innerHeightRef,null)}}render(){let{props,state,context}=this,{renderConfig,dataConfig,tableMode}=props,colSpan=dataConfig.colSpan||1,totalColWidth=props.colWidth!=null?props.colWidth*colSpan:void 0,isLiquid=!tableMode&&totalColWidth==null,isSpanning=isLiquid&&colSpan>1,style=tableMode?void 0:isSpanning?{flexGrow:colSpan,flexBasis:0,minWidth:0}:{width:totalColWidth},isDisabled=dataConfig.renderProps.isDisabled,finalRenderProps=renderConfig.dayHeaderFormat?this.buildDayHeaderRenderProps(dataConfig.renderProps,props.cellIsNarrow,props.rowLevel,props.cellIsMicro,dataConfig.dateMarker,renderConfig.dayHeaderFormat,!!renderConfig.datesRepDistinctDays,context.dateEnv):{...dataConfig.renderProps,isNarrow:props.cellIsNarrow,level:props.rowLevel},alignInput=renderConfig.align,align=typeof alignInput=="function"?alignInput({level:props.rowLevel,inPopover:dataConfig.renderProps.inPopover,isNarrow:props.cellIsNarrow}):alignInput,stickyInput=renderConfig.sticky,isSticky=!tableMode&&props.rowLevel>0&&stickyInput!==!1&&(align!=="center"||totalColWidth!=null&&props.viewportWidth!=null&&totalColWidth>props.viewportWidth*.75),edgeCoord;isSticky&&(align==="center"?state.innerWidth!=null&&(edgeCoord=`calc(50% - ${state.innerWidth/2}px)`):edgeCoord=typeof stickyInput=="number"||typeof stickyInput=="string"?stickyInput:0);let alignClassName=align==="center"?classNames.alignCenter:align==="end"?classNames.alignEnd:classNames.alignStart;return jsx11(ContentContainer,{tag:tableMode?"th":"div",attrs:{role:"columnheader","aria-colspan":dataConfig.colSpan,colSpan:tableMode?colSpan:void 0,...dataConfig.attrs},className:joinClassNames(dataConfig.className,classNames.noMargin,classNames.noPadding,!tableMode&&classNames.flexCol,classNames.borderlessTop,classNames.borderlessEnd,!props.borderStart&&classNames.borderlessStart,!(tableMode&&props.borderBottom)&&classNames.borderlessBottom,!tableMode&&alignClassName,isLiquid&&!isSpanning&&classNames.liquid,!isSticky&&classNames.crop),style,renderProps:finalRenderProps,generatorName:renderConfig.generatorName,customGenerator:renderConfig.customGenerator,defaultGenerator:renderText,classNameGenerator:isDisabled?void 0:renderConfig.classNameGenerator,didMount:renderConfig.didMount,willUnmount:renderConfig.willUnmount,children:InnerContainer=>jsx11("div",{ref:this.handleInnerEl,className:joinClassNames(classNames.flexCol,classNames.noShrink,classNames.whiteSpaceNoWrap,tableMode&&alignClassName,isSticky&&classNames.sticky),style:{left:edgeCoord,right:edgeCoord},children:jsx11(InnerContainer,{tag:"div",attrs:dataConfig.innerAttrs,className:generateClassName(renderConfig.innerClassNameGenerator,finalRenderProps)})})})}componentDidMount(){this._isUnmounting=!1}componentWillUnmount(){this._isUnmounting=!0}buildDayHeaderRenderProps(renderProps,cellIsNarrow,rowLevel,cellIsMicro,dateMarker,dayHeaderFormat,datesRepDistinctDays,dateEnv){let baseText=this.buildDayHeaderText(datesRepDistinctDays?dateMarker:renderProps.date,dayHeaderFormat,datesRepDistinctDays,dateEnv),textData=cellIsMicro?this.buildDayHeaderText(dateMarker,dayHeaderMicroFormat,!1,dateEnv):baseText;return{...renderProps,isNarrow:cellIsNarrow,level:rowLevel,text:textData.text,textParts:textData.textParts,weekdayText:cellIsMicro?textData.text:baseText.weekdayText,dayNumberText:baseText.dayNumberText}}};function buildDayHeaderText(date,formatter,includeDayNumber,dateEnv){let textParts=dateEnv.formatToParts(date,formatter);return{text:joinDateTimeFormatParts(textParts),textParts,weekdayText:findWeekdayText(textParts),dayNumberText:includeDayNumber?findDayNumberText(textParts):""}}var DayGridHeaderRow=class extends BaseComponent{constructor(){super(...arguments),this.innerHeightRefMap=new RefMap(()=>{afterSize(this.handleInnerHeights)}),this.handleInnerHeights=()=>{if(this._isUnmounting)return;let innerHeightMap=this.innerHeightRefMap.current,max=0;for(let innerHeight of innerHeightMap.values())max=Math.max(max,innerHeight);this.currentInnerHeight!==max&&(this.currentInnerHeight=max,setRef(this.props.innerHeightRef,max))}}render(){let{props,context}=this,{tableMode}=props,{options}=context;return jsx11(tableMode?"tr":"div",{role:props.role,"aria-rowindex":props.rowIndex!=null?1+props.rowIndex:void 0,className:joinClassNames(options.dayHeaderRowClass,props.className,tableMode&&classNames.borderless,!tableMode&&classNames.flexRow,!tableMode&&classNames.contentBox,!tableMode&&classNames.borderlessX,!tableMode&&classNames.borderlessTop,!tableMode&&!props.borderBottom&&classNames.borderlessBottom),style:{height:props.height},children:props.dataConfigs.map((dataConfig,cellI)=>jsx11(DayGridHeaderCell,{renderConfig:props.renderConfig,dataConfig,borderStart:!!cellI,colWidth:props.colWidth,viewportWidth:props.viewportWidth,innerHeightRef:this.innerHeightRefMap.createRef(dataConfig.key),cellIsNarrow:props.cellIsNarrow,cellIsMicro:props.cellIsMicro,rowLevel:props.rowLevel,tableMode,borderBottom:props.borderBottom},dataConfig.key))})}componentDidMount(){this._isUnmounting=!1}componentWillUnmount(){this._isUnmounting=!0,this.currentInnerHeight=void 0,setRef(this.props.innerHeightRef,null)}},DayGridHeaderRows=class extends BaseComponent{render(){let{props}=this,{headerTiers,tableMode}=props;return headerTiers.map((rowConfig,i)=>createElement4(DayGridHeaderRow,{...rowConfig,key:i,role:"row",borderBottom:i<headerTiers.length-1,colWidth:props.colWidth,viewportWidth:props.viewportWidth,cellIsNarrow:props.cellIsNarrow,cellIsMicro:props.cellIsMicro,rowLevel:headerTiers.length-i-1,tableMode}))}},DayGridLayoutPrint=class extends BaseComponent{render(){let{props,context}=this,{options}=context,tableDisplayInfo={borderlessX:props.borderlessX,borderlessTop:props.borderlessTop,borderlessBottom:props.borderlessBottom,multiMonthColumns:props.multiMonthColumns};return jsxs8("table",{role:"presentation",className:joinClassNames(generateClassName(options.tableClass,tableDisplayInfo),classNames.printTable),style:props.style,children:[jsx11("colgroup",{children:props.cellRows[0].map(cell=>jsx11("col",{},cell.key))}),props.showHeader&&jsxs8("thead",{ref:props.headerElRef,role:"rowgroup",className:generateClassName(options.tableHeaderClass,{...tableDisplayInfo,isSticky:!1}),children:[jsx11(DayGridHeaderRows,{tableMode:!0,headerTiers:props.headerTiers,cellIsNarrow:props.cellIsNarrow,cellIsMicro:props.cellIsMicro}),jsx11("tr",{role:"presentation",children:jsx11("th",{role:"presentation",colSpan:props.cellRows[0].length,className:joinClassNames(classNames.noPadding,generateClassName(options.dayHeaderDividerClass,{isSticky:!1,multiMonthColumns:props.multiMonthColumns,options:{allDaySlot:!!options.allDaySlot}}))})})]}),jsx11(DayGridRows,{dateProfile:props.dateProfile,todayRange:props.todayRange,cellRows:props.cellRows,forPrint:!0,tableMode:!0,className:generateClassName(options.tableBodyClass,tableDisplayInfo),dayMaxEvents:void 0,dayMaxEventRows:props.dayMaxEventRows,fgEventSegs:props.fgEventSegs,bgEventSegs:props.bgEventSegs,businessHourSegs:props.businessHourSegs,dateSelectionSegs:[],eventDrag:null,eventResize:null,eventSelection:props.eventSelection,visibleWidth:props.visibleWidth,cellIsNarrow:props.cellIsNarrow,cellIsMicro:props.cellIsMicro,rowHeightRefMap:props.rowHeightRefMap})]})}};import{jsx as jsx12,jsxs as jsxs9,Fragment as Fragment7}from"react/jsx-runtime";import{createRef as createRef2}from"react";var DayGridHeader=class extends BaseComponent{render(){let{props}=this;return jsx12("div",{role:"rowgroup",className:joinClassNames(props.className,classNames.flexCol,props.width==null&&classNames.liquid),style:{width:props.width},children:jsx12(DayGridHeaderRows,{headerTiers:props.headerTiers,colWidth:props.colWidth,viewportWidth:props.viewportWidth,cellIsNarrow:props.cellIsNarrow,cellIsMicro:props.cellIsMicro})})}},DayGridLayoutNormal=class extends BaseComponent{constructor(){super(...arguments),this.state={},this.handleScroller=scroller=>{setRef(this.props.scrollerRef,scroller)},this.handleTotalWidth=totalWidth=>{this._isUnmounting||this.setState({totalWidth})},this.handleClientWidth=clientWidth=>{this._isUnmounting||this.setState({clientWidth})}}render(){let{props,state,context}=this,{options}=context,{borderlessX,borderlessTop,borderlessBottom}=computeViewBorderless(options),{totalWidth,clientWidth}=state,endScrollbarWidth=totalWidth!=null&&clientWidth!=null?totalWidth-clientWidth:void 0;endScrollbarWidth<3&&(endScrollbarWidth=0);let verticalScrollbars=!props.forPrint&&!getIsHeightAuto(options),tableHeaderSticky=!props.forPrint&&getTableHeaderSticky(options),colCount=props.cellRows[0].length,measuredColWidth=clientWidth!=null?clientWidth/colCount:void 0,cellIsMicro=measuredColWidth!=null&&measuredColWidth<=dayMicroWidth,cellIsNarrow=cellIsMicro||measuredColWidth!=null&&measuredColWidth<=options.dayNarrowWidth;return props.forPrint?jsx12(DayGridLayoutPrint,{dateProfile:props.dateProfile,todayRange:props.todayRange,cellRows:props.cellRows,headerTiers:props.headerTiers,showHeader:!!options.dayHeaders,fgEventSegs:props.fgEventSegs,bgEventSegs:props.bgEventSegs,businessHourSegs:props.businessHourSegs,eventSelection:props.eventSelection,dayMaxEventRows:options.dayMaxEventRows,borderlessX,borderlessTop,borderlessBottom,multiMonthColumns:0,visibleWidth:totalWidth,cellIsNarrow,cellIsMicro,rowHeightRefMap:props.rowHeightRefMap}):jsxs9(Fragment7,{children:[options.dayHeaders&&jsxs9("div",{className:joinClassNames(generateClassName(options.tableHeaderClass,{isSticky:tableHeaderSticky,borderlessX,borderlessTop,borderlessBottom,multiMonthColumns:0}),classNames.flexCol,tableHeaderSticky&&classNames.tableHeaderSticky),children:[jsxs9("div",{className:classNames.flexRow,children:[jsx12(DayGridHeader,{headerTiers:props.headerTiers,cellIsNarrow,cellIsMicro}),!!endScrollbarWidth&&jsx12("div",{className:joinClassNames(generateClassName(options.fillerClass,{inTableHeader:!0}),classNames.borderlessY,classNames.borderlessEnd),style:{minWidth:endScrollbarWidth}})]}),jsx12("div",{className:generateClassName(options.dayHeaderDividerClass,{isSticky:tableHeaderSticky,multiMonthColumns:0,options:{allDaySlot:!!options.allDaySlot}})})]}),jsx12(Scroller,{vertical:verticalScrollbars,className:joinClassNames(generateClassName(options.tableBodyClass,{borderlessX,borderlessTop,borderlessBottom,multiMonthColumns:0}),!props.forPrint&&classNames.flexCol,verticalScrollbars&&classNames.liquid),ref:this.handleScroller,clientWidthRef:this.handleClientWidth,children:jsx12(DayGridRows,{dateProfile:props.dateProfile,todayRange:props.todayRange,cellRows:props.cellRows,forPrint:props.forPrint,isHitComboAllowed:props.isHitComboAllowed,className:classNames.grow,dayMaxEvents:props.forPrint?void 0:options.dayMaxEvents,dayMaxEventRows:options.dayMaxEventRows,fgEventSegs:props.fgEventSegs,bgEventSegs:props.bgEventSegs,businessHourSegs:props.businessHourSegs,dateSelectionSegs:props.dateSelectionSegs,eventDrag:props.eventDrag,eventResize:props.eventResize,eventSelection:props.eventSelection,visibleWidth:totalWidth,cellIsNarrow,cellIsMicro,rowHeightRefMap:props.rowHeightRefMap})}),jsx12(Ruler,{widthRef:this.handleTotalWidth})]})}componentDidMount(){this._isUnmounting=!1}componentWillUnmount(){this._isUnmounting=!0}},FooterScrollbar=class extends BaseComponent{constructor(){super(...arguments),this.rootElRef=createRef2()}render(){let{props}=this;return jsx12("div",{ref:this.rootElRef,className:joinClassNames(classNames.footerScrollbar,props.isSticky&&classNames.footerScrollbarSticky),children:jsx12(Scroller,{horizontal:!0,ref:props.scrollerRef,children:jsx12("div",{style:{minWidth:props.canvasWidth}})})})}componentDidMount(){this._isUnmounting=!1,this.disconnectHeight=watchHeight(this.rootElRef.current,height=>{this._isUnmounting||setRef(this.props.scrollbarWidthRef,height)})}componentWillUnmount(){this._isUnmounting=!0,this.disconnectHeight(),setRef(this.props.scrollbarWidthRef,null)}},DayGridLayoutPannable=class extends BaseComponent{constructor(){super(...arguments),this.state={},this.headerScrollerRef=createRef2(),this.bodyScrollerRef=createRef2(),this.footerScrollerRef=createRef2(),this.handleTotalWidth=totalWidth=>{this._isUnmounting||this.setState({totalWidth})},this.handleClientWidth=clientWidth=>{this._isUnmounting||this.setState({clientWidth})}}render(){let{props,state,context}=this,{options}=context,{borderlessX,borderlessTop,borderlessBottom}=computeViewBorderless(options),{totalWidth,clientWidth}=state,endScrollbarWidth=totalWidth!=null&&clientWidth!=null?totalWidth-clientWidth:void 0,verticalScrollbars=!props.forPrint&&!getIsHeightAuto(options),tableHeaderSticky=!props.forPrint&&getTableHeaderSticky(options),footerScrollbarSticky=!props.forPrint&&getFooterScrollbarSticky(options),colCount=props.cellRows[0].length,[canvasWidth,appliedColWidth]=computeColWidth(colCount,props.dayMinWidth,clientWidth),measuredColWidth=appliedColWidth??(clientWidth!=null?clientWidth/colCount:void 0),cellIsMicro=measuredColWidth!=null&&measuredColWidth<=dayMicroWidth,cellIsNarrow=cellIsMicro||measuredColWidth!=null&&measuredColWidth<=options.dayNarrowWidth;return props.forPrint?jsx12(DayGridLayoutPrint,{dateProfile:props.dateProfile,todayRange:props.todayRange,cellRows:props.cellRows,headerTiers:props.headerTiers,showHeader:!!options.dayHeaders,fgEventSegs:props.fgEventSegs,bgEventSegs:props.bgEventSegs,businessHourSegs:props.businessHourSegs,eventSelection:props.eventSelection,dayMaxEventRows:options.dayMaxEventRows,borderlessX,borderlessTop,borderlessBottom,multiMonthColumns:0,visibleWidth:totalWidth,cellIsNarrow,cellIsMicro,rowHeightRefMap:props.rowHeightRefMap}):jsxs9(Fragment7,{children:[options.dayHeaders&&jsxs9("div",{className:joinClassNames(generateClassName(options.tableHeaderClass,{isSticky:tableHeaderSticky,borderlessX,borderlessTop,borderlessBottom,multiMonthColumns:0}),classNames.flexCol,tableHeaderSticky&&classNames.tableHeaderSticky),children:[jsxs9(Scroller,{horizontal:!0,hideScrollbars:!0,className:classNames.flexRow,ref:this.headerScrollerRef,children:[jsx12(DayGridHeader,{headerTiers:props.headerTiers,colWidth:appliedColWidth,viewportWidth:clientWidth,width:canvasWidth,cellIsNarrow,cellIsMicro}),!!endScrollbarWidth&&jsx12("div",{className:joinClassNames(generateClassName(options.fillerClass,{inTableHeader:!0}),classNames.borderlessY,classNames.borderlessEnd),style:{minWidth:endScrollbarWidth}})]}),jsx12("div",{className:generateClassName(options.dayHeaderDividerClass,{isSticky:tableHeaderSticky,multiMonthColumns:0,options:{allDaySlot:!!options.allDaySlot}})})]}),jsx12(Scroller,{vertical:verticalScrollbars,horizontal:!0,hideScrollbars:footerScrollbarSticky||props.forPrint,className:joinClassNames(generateClassName(options.tableBodyClass,{borderlessX,borderlessTop,borderlessBottom,multiMonthColumns:0}),!props.forPrint&&classNames.flexCol,verticalScrollbars&&classNames.liquid),ref:this.bodyScrollerRef,clientWidthRef:this.handleClientWidth,children:jsx12(DayGridRows,{dateProfile:props.dateProfile,todayRange:props.todayRange,cellRows:props.cellRows,forPrint:props.forPrint,isHitComboAllowed:props.isHitComboAllowed,className:classNames.grow,dayMaxEvents:props.forPrint?void 0:options.dayMaxEvents,dayMaxEventRows:options.dayMaxEventRows,fgEventSegs:props.fgEventSegs,bgEventSegs:props.bgEventSegs,businessHourSegs:props.businessHourSegs,dateSelectionSegs:props.dateSelectionSegs,eventDrag:props.eventDrag,eventResize:props.eventResize,eventSelection:props.eventSelection,colWidth:appliedColWidth,width:canvasWidth,visibleWidth:totalWidth,cellIsNarrow,cellIsMicro,rowHeightRefMap:props.rowHeightRefMap})}),!!footerScrollbarSticky&&jsx12(FooterScrollbar,{isSticky:!0,canvasWidth,scrollerRef:this.footerScrollerRef}),jsx12(Ruler,{widthRef:this.handleTotalWidth})]})}componentDidMount(){this._isUnmounting=!1;let ScrollerSyncer=getScrollerSyncerClass(this.context.pluginHooks);this.syncedScroller=new ScrollerSyncer(!0),setRef(this.props.scrollerRef,this.syncedScroller),this.updateSyncedScroller()}componentDidUpdate(){this.updateSyncedScroller()}componentWillUnmount(){this._isUnmounting=!0,this.syncedScroller.destroy()}updateSyncedScroller(){this.syncedScroller.handleChildren([this.headerScrollerRef.current,this.bodyScrollerRef.current,this.footerScrollerRef.current])}},DayGridLayout=class extends BaseComponent{constructor(){super(...arguments),this.scrollerRef=createRef2(),this.rowHeightRefMap=new RefMap(()=>{afterSize(this.updateScrollY)}),this.scrollDate=null,this.updateScrollY=()=>{if(this._isUnmounting)return;let rowHeightMap=this.rowHeightRefMap.current,scroller=this.scrollerRef.current;if(scroller&&this.scrollDate){let scrollTop=computeTopFromDate(this.scrollDate,this.props.cellRows,rowHeightMap);scrollTop!=null&&(scrollTop&&scrollTop++,scroller.scrollTo({y:scrollTop}))}},this.handleScrollEnd=isDevice=>{isDevice&&(this.scrollDate=null)}}render(){let{props,context}=this,{options}=context,{borderlessX,borderlessTop,borderlessBottom}=computeViewBorderless(options),dateSelectionSegs=props.forPrint?[]:props.dateSelectionSegs,eventDrag=props.forPrint?null:props.eventDrag,eventResize=props.forPrint?null:props.eventResize,commonLayoutProps={...props,dateSelectionSegs,eventDrag,eventResize,scrollerRef:this.scrollerRef,rowHeightRefMap:this.rowHeightRefMap};return jsx12(ViewContainer,{viewSpec:context.viewSpec,attrs:{role:"grid","aria-rowcount":props.headerTiers.length+props.cellRows.length,"aria-colcount":props.cellRows[0].length,"aria-labelledby":props.labelId,"aria-label":props.labelStr},className:joinClassNames(props.className,!props.forPrint&&classNames.flexCol,!props.forPrint&&generateClassName(options.tableClass,{borderlessX,borderlessTop,borderlessBottom,multiMonthColumns:0})),children:options.dayMinWidth?jsx12(DayGridLayoutPannable,{...commonLayoutProps,dayMinWidth:options.dayMinWidth}):jsx12(DayGridLayoutNormal,{...commonLayoutProps})})}componentDidMount(){this._isUnmounting=!1,this.props.forPrint||(this.resetScroll(),this.scrollerRef.current?.addScrollEndListener(this.handleScrollEnd))}componentDidUpdate(prevProps){prevProps.forPrint&&!this.props.forPrint&&(this.scrollerRef.current?.addScrollEndListener(this.handleScrollEnd),this.resetScroll()),prevProps.dateProfile!==this.props.dateProfile&&this.context.options.scrollTimeReset&&this.resetScroll()}componentWillUnmount(){this._isUnmounting=!0,this.scrollerRef.current?.removeScrollEndListener(this.handleScrollEnd)}resetScroll(){this.scrollDate=this.props.dateProfile.currentDate,this.updateScrollY(),this.scrollerRef.current?.scrollTo({x:0})}};var TableDateProfileGenerator=class extends DateProfileGenerator{buildRenderRange(currentRange,currentRangeUnit,isRangeAllDay){let renderRange=super.buildRenderRange(currentRange,currentRangeUnit,isRangeAllDay),{props}=this;return buildDayTableRenderRange({currentRange:renderRange,snapToWeek:/^(year|month)$/.test(currentRangeUnit),fixedWeekCount:props.fixedWeekCount,dateEnv:props.dateEnv})}};function buildDayTableRenderRange(props){let{dateEnv,currentRange}=props,{start,end}=currentRange,endOfWeek4;if(props.snapToWeek&&(start=dateEnv.startOfWeek(start),endOfWeek4=dateEnv.startOfWeek(end),endOfWeek4.valueOf()!==end.valueOf()&&(end=addWeeks3(endOfWeek4,1))),props.fixedWeekCount){let lastMonthRenderStart=dateEnv.startOfWeek(dateEnv.startOfMonth(addDays4(currentRange.end,-1))),rowCount=Math.ceil(diffWeeks4(lastMonthRenderStart,end));end=addWeeks3(end,6-rowCount)}return{start,end}}var DayGridView=class extends BaseComponent{constructor(){super(...arguments),this.buildDayTableModel=memoize2(buildDayTableModel),this.buildDateRowConfigs=memoize2(buildDateRowConfigs),this.createDayHeaderFormatter=memoize2(createDayHeaderFormatter),this.slicer=new DayTableSlicer}render(){let{props,context}=this,{dateProfile}=props,{options,dateEnv}=context,dayTableModel=this.buildDayTableModel(dateProfile,context.dateProfileGenerator,dateEnv),datesRepDistinctDays=dayTableModel.rowCount===1,dayHeaderFormat=this.createDayHeaderFormatter(context.options.dayHeaderFormat,datesRepDistinctDays,dayTableModel.colCount),slicedProps=this.slicer.sliceProps(props,dateProfile,options.nextDayThreshold,context,dayTableModel);return jsx13(NowTimer,{unit:"day",children:(nowDate,todayRange)=>{let headerTiers=this.buildDateRowConfigs(dayTableModel.headerDates,datesRepDistinctDays,dateProfile,todayRange,dayHeaderFormat,context);return jsx13(DayGridLayout,{labelId:props.labelId,labelStr:props.labelStr,dateProfile,todayRange,cellRows:dayTableModel.cellRows,forPrint:props.forPrint,className:props.className,headerTiers,fgEventSegs:slicedProps.fgEventSegs,bgEventSegs:slicedProps.bgEventSegs,businessHourSegs:slicedProps.businessHourSegs,dateSelectionSegs:slicedProps.dateSelectionSegs,eventDrag:slicedProps.eventDrag,eventResize:slicedProps.eventResize,eventSelection:slicedProps.eventSelection})}})}},dayGridPlugin={name:"daygrid",initialView:"dayGridMonth",views:{dayGrid:{component:DayGridView,dateProfileGeneratorClass:TableDateProfileGenerator},dayGridDay:{type:"dayGrid",duration:{days:1}},dayGridWeek:{type:"dayGrid",duration:{weeks:1}},dayGridMonth:{type:"dayGrid",duration:{months:1},fixedWeekCount:!0},dayGridYear:{type:"dayGrid",duration:{years:1}}}};var ElementDragging=class{constructor(el,selector){this.emitter=new Emitter}destroy(){}setMirrorIsVisible(bool){}setMirrorNeedsRevert(bool){}setAutoScrollEnabled(bool){}},config={};function isInteractionValid(interaction,dateProfile,context){let{instances}=interaction.mutatedEvents;for(let instanceId in instances)if(!rangeContainsRange(dateProfile.validRange,instances[instanceId].range))return!1;return isNewPropsValid({eventDrag:interaction},context)}function isDateSelectionValid(dateSelection,dateProfile,context){return rangeContainsRange(dateProfile.validRange,dateSelection.range)?isNewPropsValid({dateSelection},context):!1}function isNewPropsValid(newProps,context){let calendarState=context.getCurrentData(),props={businessHours:calendarState.businessHours,dateSelection:"",eventStore:calendarState.eventStore,eventUiBases:calendarState.eventUiBases,eventSelection:"",eventDrag:null,eventResize:null,...newProps};return(context.pluginHooks.isPropsValid||isPropsValid)(props,context)}function isPropsValid(state,context,dateSpanMeta={},filterConfig){return!(state.eventDrag&&!isInteractionPropsValid(state,context,dateSpanMeta,filterConfig)||state.dateSelection&&!isDateSelectionPropsValid(state,context,dateSpanMeta,filterConfig))}function isInteractionPropsValid(state,context,dateSpanMeta,filterConfig){let currentState=context.getCurrentData(),interaction=state.eventDrag,subjectEventStore=interaction.mutatedEvents,subjectDefs=subjectEventStore.defs,subjectInstances=subjectEventStore.instances,subjectConfigs=compileEventUis(subjectDefs,interaction.isEvent?state.eventUiBases:{"":currentState.selectionConfig});filterConfig&&(subjectConfigs=mapHash(subjectConfigs,filterConfig));let otherEventStore=excludeInstances(state.eventStore,interaction.affectedEvents.instances),otherDefs=otherEventStore.defs,otherInstances=otherEventStore.instances,otherConfigs=compileEventUis(otherDefs,state.eventUiBases);for(let subjectInstanceId in subjectInstances){let subjectInstance=subjectInstances[subjectInstanceId],subjectRange=subjectInstance.range,subjectConfig=subjectConfigs[subjectInstance.defId],subjectDef=subjectDefs[subjectInstance.defId];if(!allConstraintsPass(subjectConfig.constraints,subjectRange,otherEventStore,state.businessHours,context))return!1;let{eventOverlap}=context.options,eventOverlapFunc=typeof eventOverlap=="function"?eventOverlap:null;for(let otherInstanceId in otherInstances){let otherInstance=otherInstances[otherInstanceId];if(instanceRangesIntersect(subjectRange,otherInstance.range,context.dateEnv)&&(otherConfigs[otherInstance.defId].overlap===!1&&interaction.isEvent||subjectConfig.overlap===!1||eventOverlapFunc&&!eventOverlapFunc(new EventImpl(context,otherDefs[otherInstance.defId],otherInstance),new EventImpl(context,subjectDef,subjectInstance))))return!1}let calendarEventStore=currentState.eventStore;for(let subjectAllow of subjectConfig.allows){let subjectDateSpan={...dateSpanMeta,range:subjectInstance.range,allDay:subjectDef.allDay},origDef=calendarEventStore.defs[subjectDef.defId],origInstance=calendarEventStore.instances[subjectInstanceId],eventApi;if(origDef?eventApi=new EventImpl(context,origDef,origInstance):eventApi=new EventImpl(context,subjectDef),!subjectAllow(buildDateSpanApiWithContext(subjectDateSpan,context),eventApi))return!1}}return!0}function isDateSelectionPropsValid(state,context,dateSpanMeta,filterConfig){let relevantEventStore=state.eventStore,relevantDefs=relevantEventStore.defs,relevantInstances=relevantEventStore.instances,selection=state.dateSelection,selectionRange=buildEventInstanceRange(selection.range.start,selection.range.end,selection.instantStartMs,selection.instantEndMs),{selectionConfig}=context.getCurrentData();if(filterConfig&&(selectionConfig=filterConfig(selectionConfig)),!allConstraintsPass(selectionConfig.constraints,selectionRange,relevantEventStore,state.businessHours,context))return!1;let{selectOverlap}=context.options,selectOverlapFunc=typeof selectOverlap=="function"?selectOverlap:null;for(let relevantInstanceId in relevantInstances){let relevantInstance=relevantInstances[relevantInstanceId];if(instanceRangesIntersect(selectionRange,relevantInstance.range,context.dateEnv)&&(selectionConfig.overlap===!1||selectOverlapFunc&&!selectOverlapFunc(new EventImpl(context,relevantDefs[relevantInstance.defId],relevantInstance),null)))return!1}for(let selectionAllow of selectionConfig.allows){let fullDateSpan={...dateSpanMeta,...selection};if(!selectionAllow(buildDateSpanApiWithContext(fullDateSpan,context),null))return!1}return!0}function allConstraintsPass(constraints,subjectRange,otherEventStore,businessHoursUnexpanded,context){for(let constraint of constraints)if(!anyRangesContainRange(constraintToRanges(constraint,subjectRange,otherEventStore,businessHoursUnexpanded,context),subjectRange,context))return!1;return!0}function constraintToRanges(constraint,subjectRange,otherEventStore,businessHoursUnexpanded,context){return constraint==="businessHours"?eventStoreToRanges(expandRecurring(businessHoursUnexpanded,subjectRange,context)):typeof constraint=="string"?eventStoreToRanges(filterEventStoreDefs(otherEventStore,eventDef=>eventDef.groupId===constraint)):typeof constraint=="object"&&constraint?eventStoreToRanges(expandRecurring(constraint,subjectRange,context)):[]}function eventStoreToRanges(eventStore){let{instances}=eventStore,ranges=[];for(let instanceId in instances)ranges.push(instances[instanceId].range);return ranges}function anyRangesContainRange(outerRanges,innerRange,context){for(let outerRange of outerRanges)if(instanceRangeContainsRange(outerRange,innerRange,context.dateEnv))return!0;return!1}config.touchMouseIgnoreWait=500;var ignoreMouseDepth=0,listenerCnt=0,isWindowTouchMoveCancelled=!1,PointerDragging=class{constructor(containerEl){this.subjectEl=null,this.selector="",this.handleSelector="",this.shouldIgnoreMove=!1,this.shouldWatchScroll=!0,this.isDragging=!1,this.isTouchDragging=!1,this.wasTouchScroll=!1,this.handleMouseDown=ev=>{if(!this.shouldIgnoreMouse()&&isPrimaryMouseButton(ev)&&this.tryStart(ev)){let pev=this.createEventFromMouse(ev,!0);this.emitter.trigger("pointerdown",pev),this.initScrollWatch(pev),this.shouldIgnoreMove||document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseup",this.handleMouseUp)}},this.handleMouseMove=ev=>{let pev=this.createEventFromMouse(ev);this.recordCoords(pev),this.emitter.trigger("pointermove",pev)},this.handleMouseUp=ev=>{document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp),this.emitter.trigger("pointerup",this.createEventFromMouse(ev)),this.cleanup()},this.handleTouchStart=ev=>{if(this.tryStart(ev)){this.isTouchDragging=!0;let pev=this.createEventFromTouch(ev,!0);this.emitter.trigger("pointerdown",pev),this.initScrollWatch(pev);let targetEl=ev.target;this.shouldIgnoreMove||targetEl.addEventListener("touchmove",this.handleTouchMove),targetEl.addEventListener("touchend",this.handleTouchEnd),targetEl.addEventListener("touchcancel",this.handleTouchEnd),window.addEventListener("scroll",this.handleTouchScroll,!0)}},this.handleTouchMove=ev=>{if(this.isDragging){let pev=this.createEventFromTouch(ev);this.recordCoords(pev),this.emitter.trigger("pointermove",pev)}},this.handleTouchEnd=ev=>{if(this.isDragging){let targetEl=ev.target;targetEl.removeEventListener("touchmove",this.handleTouchMove),targetEl.removeEventListener("touchend",this.handleTouchEnd),targetEl.removeEventListener("touchcancel",this.handleTouchEnd),window.removeEventListener("scroll",this.handleTouchScroll,!0),this.emitter.trigger("pointerup",this.createEventFromTouch(ev)),this.cleanup(),this.isTouchDragging=!1,startIgnoringMouse()}},this.handleTouchScroll=()=>{this.wasTouchScroll=!0},this.handleScroll=ev=>{if(!this.shouldIgnoreMove){let pageX=window.scrollX-this.prevScrollX+this.prevPageX,pageY=window.scrollY-this.prevScrollY+this.prevPageY;this.emitter.trigger("pointermove",{origEvent:ev,isTouch:this.isTouchDragging,subjectEl:this.subjectEl,pageX,pageY,deltaX:pageX-this.origPageX,deltaY:pageY-this.origPageY})}},this.containerEl=containerEl,this.emitter=new Emitter,containerEl.addEventListener("mousedown",this.handleMouseDown),containerEl.addEventListener("touchstart",this.handleTouchStart,{passive:!0}),listenerCreated()}destroy(){this.containerEl.removeEventListener("mousedown",this.handleMouseDown),this.containerEl.removeEventListener("touchstart",this.handleTouchStart,{passive:!0}),listenerDestroyed()}cancel(){this.isDragging&&this.cleanup()}tryStart(ev){let subjectEl=this.querySubjectEl(ev),downEl=ev.target;return subjectEl&&(!this.handleSelector||downEl.closest(this.handleSelector))?(this.subjectEl=subjectEl,this.isDragging=!0,this.wasTouchScroll=!1,!0):!1}cleanup(){isWindowTouchMoveCancelled=!1,this.isDragging=!1,this.subjectEl=null,this.destroyScrollWatch()}querySubjectEl(ev){return this.selector?ev.target.closest(this.selector):this.containerEl}shouldIgnoreMouse(){return ignoreMouseDepth||this.isTouchDragging}cancelTouchScroll(){this.isDragging&&(isWindowTouchMoveCancelled=!0)}initScrollWatch(ev){this.shouldWatchScroll&&(this.recordCoords(ev),window.addEventListener("scroll",this.handleScroll,!0))}recordCoords(ev){this.shouldWatchScroll&&(this.prevPageX=ev.pageX,this.prevPageY=ev.pageY,this.prevScrollX=window.scrollX,this.prevScrollY=window.scrollY)}destroyScrollWatch(){this.shouldWatchScroll&&window.removeEventListener("scroll",this.handleScroll,!0)}createEventFromMouse(ev,isFirst){let deltaX=0,deltaY=0;return isFirst?(this.origPageX=ev.pageX,this.origPageY=ev.pageY):(deltaX=ev.pageX-this.origPageX,deltaY=ev.pageY-this.origPageY),{origEvent:ev,isTouch:!1,subjectEl:this.subjectEl,pageX:ev.pageX,pageY:ev.pageY,deltaX,deltaY}}createEventFromTouch(ev,isFirst){let touches=ev.touches,pageX,pageY,deltaX=0,deltaY=0;return touches&&touches.length?(pageX=touches[0].pageX,pageY=touches[0].pageY):(pageX=ev.pageX,pageY=ev.pageY),isFirst?(this.origPageX=pageX,this.origPageY=pageY):(deltaX=pageX-this.origPageX,deltaY=pageY-this.origPageY),{origEvent:ev,isTouch:!0,subjectEl:this.subjectEl,pageX,pageY,deltaX,deltaY}}};function isPrimaryMouseButton(ev){return ev.button===0&&!ev.ctrlKey}function startIgnoringMouse(){ignoreMouseDepth+=1,setTimeout(()=>{ignoreMouseDepth-=1},config.touchMouseIgnoreWait)}function listenerCreated(){listenerCnt+=1,listenerCnt===1&&window.addEventListener("touchmove",onWindowTouchMove,{passive:!1})}function listenerDestroyed(){listenerCnt-=1,listenerCnt||window.removeEventListener("touchmove",onWindowTouchMove,{passive:!1})}function onWindowTouchMove(ev){isWindowTouchMoveCancelled&&ev.preventDefault()}var ElementMirror=class{constructor(){this.isVisible=!1,this.sourceEl=null,this.mirrorEl=null,this.sourceElRect=null,this.parentNode=document.body,this.zIndex=9999,this.revertDuration=0,this.colorScheme=""}start(sourceEl,pageX,pageY){this.sourceEl=sourceEl,this.sourceElRect=this.sourceEl.getBoundingClientRect(),this.origScreenX=pageX-window.scrollX,this.origScreenY=pageY-window.scrollY,this.deltaX=0,this.deltaY=0,this.updateElPosition()}handleMove(pageX,pageY){this.deltaX=pageX-window.scrollX-this.origScreenX,this.deltaY=pageY-window.scrollY-this.origScreenY,this.updateElPosition()}setIsVisible(bool){bool?this.isVisible||(this.mirrorEl&&this.mirrorEl.style.setProperty("display","","important"),this.isVisible=bool,this.updateElPosition()):this.isVisible&&(this.mirrorEl&&this.mirrorEl.style.setProperty("display","none","important"),this.isVisible=bool)}stop(needsRevertAnimation,callback){let done=()=>{this.cleanup(),callback()};needsRevertAnimation&&this.mirrorEl&&this.isVisible&&this.revertDuration&&(this.deltaX||this.deltaY)?this.doRevertAnimation(done,this.revertDuration):setTimeout(done,0)}doRevertAnimation(callback,revertDuration){let mirrorEl=this.mirrorEl,finalSourceElRect=this.sourceEl.getBoundingClientRect();mirrorEl.style.transition="top "+revertDuration+"ms,left "+revertDuration+"ms",applyStyle(mirrorEl,{left:finalSourceElRect.left,top:finalSourceElRect.top}),whenTransitionDone(mirrorEl,()=>{mirrorEl.style.transition="",callback()})}cleanup(){this.mirrorEl&&(this.mirrorEl.remove(),this.mirrorEl=null),this.sourceEl=null}updateElPosition(){this.sourceEl&&this.isVisible&&applyStyle(this.getMirrorEl(),{left:this.sourceElRect.left+this.deltaX,top:this.sourceElRect.top+this.deltaY})}getMirrorEl(){let sourceElRect=this.sourceElRect,mirrorEl=this.mirrorEl;return mirrorEl||(mirrorEl=this.mirrorEl=this.sourceEl.cloneNode(!0),mirrorEl.style.userSelect="none",mirrorEl.style.webkitUserSelect="none",mirrorEl.style.pointerEvents="none",this.colorScheme&&mirrorEl.setAttribute("data-color-scheme",this.colorScheme),mirrorEl.classList.add(classNames.borderBoxRoot),applyStyle(mirrorEl,{position:"fixed",zIndex:this.zIndex,visibility:"",width:sourceElRect.right-sourceElRect.left,height:sourceElRect.bottom-sourceElRect.top,right:"auto",bottom:"auto",margin:0}),this.parentNode.appendChild(mirrorEl)),mirrorEl}},ScrollController=class{getMaxScrollTop(){return this.getScrollHeight()-this.getClientHeight()}getMaxScrollLeft(){return this.getScrollWidth()-this.getClientWidth()}canScrollVertically(){return this.getMaxScrollTop()>0}canScrollHorizontally(){return this.getMaxScrollLeft()>0}canScrollUp(){return this.getScrollTop()>0}canScrollDown(){return this.getScrollTop()<this.getMaxScrollTop()}canScrollLeft(){return this.getScrollLeft()>0}canScrollRight(){return this.getScrollLeft()<this.getMaxScrollLeft()}},ElementScrollController=class extends ScrollController{constructor(el){super(),this.el=el}getScrollTop(){return this.el.scrollTop}getScrollLeft(){return this.el.scrollLeft}setScrollTop(top){this.el.scrollTop=top}setScrollLeft(left){this.el.scrollLeft=left}getScrollWidth(){return this.el.scrollWidth}getScrollHeight(){return this.el.scrollHeight}getClientHeight(){return this.el.clientHeight}getClientWidth(){return this.el.clientWidth}},WindowScrollController=class extends ScrollController{getScrollTop(){return window.scrollY}getScrollLeft(){return window.scrollX}setScrollTop(n){window.scroll(window.scrollX,n)}setScrollLeft(n){window.scroll(n,window.scrollY)}getScrollWidth(){return document.documentElement.scrollWidth}getScrollHeight(){return document.documentElement.scrollHeight}getClientHeight(){return document.documentElement.clientHeight}getClientWidth(){return document.documentElement.clientWidth}},ScrollGeomCache=class extends ScrollController{constructor(scrollController,doesListening){super(),this.handleScroll=()=>{this.scrollTop=this.scrollController.getScrollTop(),this.scrollLeft=this.scrollController.getScrollLeft(),this.handleScrollChange()},this.scrollController=scrollController,this.doesListening=doesListening,this.scrollTop=this.origScrollTop=scrollController.getScrollTop(),this.scrollLeft=this.origScrollLeft=scrollController.getScrollLeft(),this.scrollWidth=scrollController.getScrollWidth(),this.scrollHeight=scrollController.getScrollHeight(),this.clientWidth=scrollController.getClientWidth(),this.clientHeight=scrollController.getClientHeight(),this.clientRect=this.computeClientRect(),this.doesListening&&this.getEventTarget().addEventListener("scroll",this.handleScroll)}destroy(){this.doesListening&&this.getEventTarget().removeEventListener("scroll",this.handleScroll)}getScrollTop(){return this.scrollTop}getScrollLeft(){return this.scrollLeft}setScrollTop(top){this.scrollController.setScrollTop(top),this.doesListening||(this.scrollTop=Math.max(Math.min(top,this.getMaxScrollTop()),0),this.handleScrollChange())}setScrollLeft(top){this.scrollController.setScrollLeft(top),this.doesListening||(this.scrollLeft=Math.max(Math.min(top,this.getMaxScrollLeft()),0),this.handleScrollChange())}getClientWidth(){return this.clientWidth}getClientHeight(){return this.clientHeight}getScrollWidth(){return this.scrollWidth}getScrollHeight(){return this.scrollHeight}handleScrollChange(){}},ElementScrollGeomCache=class extends ScrollGeomCache{constructor(el,doesListening){super(new ElementScrollController(el),doesListening)}getEventTarget(){return this.scrollController.el}computeClientRect(){return computeInnerRect(this.scrollController.el)}},WindowScrollGeomCache=class extends ScrollGeomCache{constructor(doesListening){super(new WindowScrollController,doesListening)}getEventTarget(){return window}computeClientRect(){return{left:this.scrollLeft,right:this.scrollLeft+this.clientWidth,top:this.scrollTop,bottom:this.scrollTop+this.clientHeight}}handleScrollChange(){this.clientRect=this.computeClientRect()}},getTime=typeof performance=="function"?performance.now:Date.now,AutoScroller=class{constructor(){this.isEnabled=!0,this.scrollQuery=[window,`.${classNames.internalScroller}`],this.edgeThreshold=50,this.maxVelocity=300,this.pointerScreenX=null,this.pointerScreenY=null,this.isAnimating=!1,this.scrollCaches=null,this.everMovedUp=!1,this.everMovedDown=!1,this.everMovedLeft=!1,this.everMovedRight=!1,this.animate=()=>{if(this.isAnimating){let edge=this.computeBestEdge(this.pointerScreenX+window.scrollX,this.pointerScreenY+window.scrollY);if(edge){let now=getTime();this.handleSide(edge,(now-this.msSinceRequest)/1e3),this.requestAnimation(now)}else this.isAnimating=!1}}}start(pageX,pageY,scrollStartEl){this.isEnabled&&(this.scrollCaches=this.buildCaches(scrollStartEl),this.pointerScreenX=null,this.pointerScreenY=null,this.everMovedUp=!1,this.everMovedDown=!1,this.everMovedLeft=!1,this.everMovedRight=!1,this.handleMove(pageX,pageY))}handleMove(pageX,pageY){if(this.isEnabled){let pointerScreenX=pageX-window.scrollX,pointerScreenY=pageY-window.scrollY,yDelta=this.pointerScreenY===null?0:pointerScreenY-this.pointerScreenY,xDelta=this.pointerScreenX===null?0:pointerScreenX-this.pointerScreenX;yDelta<0?this.everMovedUp=!0:yDelta>0&&(this.everMovedDown=!0),xDelta<0?this.everMovedLeft=!0:xDelta>0&&(this.everMovedRight=!0),this.pointerScreenX=pointerScreenX,this.pointerScreenY=pointerScreenY,this.isAnimating||(this.isAnimating=!0,this.requestAnimation(getTime()))}}stop(){if(this.isEnabled){this.isAnimating=!1;for(let scrollCache of this.scrollCaches)scrollCache.destroy();this.scrollCaches=null}}requestAnimation(now){this.msSinceRequest=now,requestAnimationFrame(this.animate)}handleSide(edge,seconds){let{scrollCache}=edge,{edgeThreshold}=this,invDistance=edgeThreshold-edge.distance,velocity=invDistance*invDistance/(edgeThreshold*edgeThreshold)*this.maxVelocity*seconds,sign=1;switch(edge.name){case"left":sign=-1;case"right":scrollCache.setScrollLeft(scrollCache.getScrollLeft()+velocity*sign);break;case"top":sign=-1;case"bottom":scrollCache.setScrollTop(scrollCache.getScrollTop()+velocity*sign);break}}computeBestEdge(left,top){let{edgeThreshold}=this,bestSide=null,scrollCaches=this.scrollCaches||[];for(let scrollCache of scrollCaches){let rect=scrollCache.clientRect,leftDist=left-rect.left,rightDist=rect.right-left,topDist=top-rect.top,bottomDist=rect.bottom-top;leftDist>=0&&rightDist>=0&&topDist>=0&&bottomDist>=0&&(topDist<=edgeThreshold&&this.everMovedUp&&scrollCache.canScrollUp()&&(!bestSide||bestSide.distance>topDist)&&(bestSide={scrollCache,name:"top",distance:topDist}),bottomDist<=edgeThreshold&&this.everMovedDown&&scrollCache.canScrollDown()&&(!bestSide||bestSide.distance>bottomDist)&&(bestSide={scrollCache,name:"bottom",distance:bottomDist}),leftDist<=edgeThreshold&&this.everMovedLeft&&scrollCache.canScrollLeft()&&(!bestSide||bestSide.distance>leftDist)&&(bestSide={scrollCache,name:"left",distance:leftDist}),rightDist<=edgeThreshold&&this.everMovedRight&&scrollCache.canScrollRight()&&(!bestSide||bestSide.distance>rightDist)&&(bestSide={scrollCache,name:"right",distance:rightDist}))}return bestSide}buildCaches(scrollStartEl){return this.queryScrollEls(scrollStartEl).map(el=>el===window?new WindowScrollGeomCache(!1):new ElementScrollGeomCache(el,!1))}queryScrollEls(scrollStartEl){let els=[];for(let query of this.scrollQuery)typeof query=="object"?els.push(query):els.push(...Array.prototype.slice.call(scrollStartEl.getRootNode().querySelectorAll(query)));return els}},FeaturefulElementDragging=class extends ElementDragging{constructor(containerEl,selector){super(containerEl),this.containerEl=containerEl,this.delay=null,this.minDistance=0,this.touchScrollAllowed=!0,this.mirrorNeedsRevert=!1,this.isInteracting=!1,this.isDragging=!1,this.isDelayEnded=!1,this.isDistanceSurpassed=!1,this.delayTimeoutId=null,this.onPointerDown=ev=>{this.isDragging||(this.isInteracting=!0,this.isDelayEnded=!1,this.isDistanceSurpassed=!1,this.emitter.trigger("pointerdown",ev),this.isInteracting&&(preventSelection(document.body),preventContextMenu(document.body),ev.isTouch||ev.origEvent.preventDefault(),this.mirror.setIsVisible(!1),this.mirror.start(ev.subjectEl,ev.pageX,ev.pageY),this.startDelay(ev),this.minDistance||this.handleDistanceSurpassed(ev)))},this.onPointerMove=ev=>{if(this.isInteracting){if(this.emitter.trigger("pointermove",ev),!this.isDistanceSurpassed){let minDistance=this.minDistance,distanceSq,{deltaX,deltaY}=ev;distanceSq=deltaX*deltaX+deltaY*deltaY,distanceSq>=minDistance*minDistance&&this.handleDistanceSurpassed(ev)}this.isDragging&&(ev.origEvent.type!=="scroll"&&(this.mirror.handleMove(ev.pageX,ev.pageY),this.autoScroller.handleMove(ev.pageX,ev.pageY)),this.emitter.trigger("dragmove",ev))}},this.onPointerUp=ev=>{this.isInteracting&&(this.isInteracting=!1,allowSelection(document.body),allowContextMenu(document.body),this.emitter.trigger("pointerup",ev),this.isDragging&&(this.autoScroller.stop(),this.tryStopDrag(ev)),this.delayTimeoutId&&(clearTimeout(this.delayTimeoutId),this.delayTimeoutId=null))};let pointer=this.pointer=new PointerDragging(containerEl);pointer.emitter.on("pointerdown",this.onPointerDown),pointer.emitter.on("pointermove",this.onPointerMove),pointer.emitter.on("pointerup",this.onPointerUp),selector&&(pointer.selector=selector),this.mirror=new ElementMirror,this.autoScroller=new AutoScroller}destroy(){this.pointer.destroy(),this.onPointerUp({})}startDelay(ev){typeof this.delay=="number"?this.delayTimeoutId=setTimeout(()=>{this.delayTimeoutId=null,this.handleDelayEnd(ev)},this.delay):this.handleDelayEnd(ev)}handleDelayEnd(ev){this.isDelayEnded=!0,this.tryStartDrag(ev)}handleDistanceSurpassed(ev){this.isDistanceSurpassed=!0,this.tryStartDrag(ev)}tryStartDrag(ev){this.isDelayEnded&&this.isDistanceSurpassed&&(!this.pointer.wasTouchScroll||this.touchScrollAllowed)&&(this.isDragging=!0,this.mirrorNeedsRevert=!1,this.autoScroller.start(ev.pageX,ev.pageY,this.containerEl),this.emitter.trigger("dragstart",ev),this.touchScrollAllowed===!1&&this.pointer.cancelTouchScroll())}tryStopDrag(ev){this.mirror.stop(this.mirrorNeedsRevert,this.stopDrag.bind(this,ev))}stopDrag(ev){this.isDragging=!1,this.emitter.trigger("dragend",ev)}cancel(){this.isInteracting&&(this.isInteracting=!1,this.pointer.cancel())}setMirrorIsVisible(bool){this.mirror.setIsVisible(bool)}setMirrorNeedsRevert(bool){this.mirrorNeedsRevert=bool}setAutoScrollEnabled(bool){this.autoScroller.isEnabled=bool}},OffsetTracker=class{constructor(el){this.el=el,this.origRect=computeRect(el),this.isRtl=computeElIsRtl(el),this.scrollCaches=getClippingParents(el).map(scrollEl=>new ElementScrollGeomCache(scrollEl,!0))}destroy(){for(let scrollCache of this.scrollCaches)scrollCache.destroy()}computeLeft(){let left=this.origRect.left;for(let scrollCache of this.scrollCaches)left+=scrollCache.origScrollLeft-scrollCache.getScrollLeft();return left}computeTop(){let top=this.origRect.top;for(let scrollCache of this.scrollCaches)top+=scrollCache.origScrollTop-scrollCache.getScrollTop();return top}isWithinClipping(pageX,pageY){let point={left:pageX,top:pageY};for(let scrollCache of this.scrollCaches)if(!isIgnoredClipping(scrollCache.getEventTarget())&&!pointInsideRect(point,scrollCache.clientRect))return!1;return!0}};function isIgnoredClipping(node){let tagName=node.tagName;return tagName==="HTML"||tagName==="BODY"}var HitDragging=class{constructor(dragging,droppableStore){this.useSubjectCenter=!1,this.requireInitial=!0,this.disablePointCheck=!1,this.initialHit=null,this.movingHit=null,this.finalHit=null,this.handlePointerDown=ev=>{let{dragging:dragging2}=this;this.initialHit=null,this.movingHit=null,this.finalHit=null,this.prepareHits(),this.processFirstCoord(ev),this.initialHit||!this.requireInitial?this.emitter.trigger("pointerdown",ev):dragging2.cancel()},this.handleDragStart=ev=>{this.emitter.trigger("dragstart",ev),this.handleMove(ev,!0)},this.handleDragMove=ev=>{this.emitter.trigger("dragmove",ev),this.handleMove(ev)},this.handlePointerUp=ev=>{this.releaseHits(),this.emitter.trigger("pointerup",ev)},this.handleDragEnd=ev=>{this.movingHit&&this.emitter.trigger("hitupdate",null,!0,ev),this.finalHit=this.movingHit,this.movingHit=null,this.emitter.trigger("dragend",ev)},this.droppableStore=droppableStore,dragging.emitter.on("pointerdown",this.handlePointerDown),dragging.emitter.on("dragstart",this.handleDragStart),dragging.emitter.on("dragmove",this.handleDragMove),dragging.emitter.on("pointerup",this.handlePointerUp),dragging.emitter.on("dragend",this.handleDragEnd),this.dragging=dragging,this.emitter=new Emitter}processFirstCoord(ev){let origPoint={left:ev.pageX,top:ev.pageY},adjustedPoint=origPoint,subjectEl=ev.subjectEl,subjectRect;subjectEl instanceof HTMLElement&&(subjectRect=computeRect(subjectEl),adjustedPoint=constrainPoint(adjustedPoint,subjectRect));let initialHit=this.initialHit=this.queryHitForOffset(adjustedPoint.left,adjustedPoint.top);if(initialHit){if(this.useSubjectCenter&&subjectRect){let slicedSubjectRect=intersectRects(subjectRect,initialHit.rect);slicedSubjectRect&&(adjustedPoint=getRectCenter(slicedSubjectRect))}this.coordAdjust=diffPoints(adjustedPoint,origPoint)}else this.coordAdjust={left:0,top:0}}handleMove(ev,forceHandle){let hit=this.queryHitForOffset(ev.pageX+this.coordAdjust.left,ev.pageY+this.coordAdjust.top);(forceHandle||!isHitsEqual(this.movingHit,hit))&&(this.movingHit=hit,this.emitter.trigger("hitupdate",hit,!1,ev))}prepareHits(){this.offsetTrackers=mapHash(this.droppableStore,interactionSettings=>(interactionSettings.component.prepareHits(),new OffsetTracker(interactionSettings.el)))}releaseHits(){let{offsetTrackers}=this;for(let id in offsetTrackers)offsetTrackers[id].destroy();this.offsetTrackers={}}queryHitForOffset(offsetLeft,offsetTop){let{droppableStore,offsetTrackers}=this,bestHit=null;for(let id in droppableStore){let component=droppableStore[id].component,offsetTracker=offsetTrackers[id];if(offsetTracker&&offsetTracker.isWithinClipping(offsetLeft,offsetTop)){let originLeft=offsetTracker.computeLeft(),originTop=offsetTracker.computeTop(),positionLeft=offsetLeft-originLeft,positionTop=offsetTop-originTop,{origRect}=offsetTracker,width=origRect.right-origRect.left,height=origRect.bottom-origRect.top;if(positionLeft>=0&&positionLeft<width&&positionTop>=0&&positionTop<height){let hit=component.queryHit(offsetTracker.isRtl,positionLeft,positionTop,width,height);hit&&rangeContainsRange(hit.dateProfile.activeRange,hit.dateSpan.range)&&(this.disablePointCheck||offsetTracker.el.contains(offsetTracker.el.getRootNode().elementFromPoint(positionLeft+originLeft-window.scrollX,positionTop+originTop-window.scrollY)))&&(!bestHit||hit.layer>bestHit.layer)&&(hit.componentId=id,hit.context=component.context,hit.rect.left+=originLeft,hit.rect.right+=originLeft,hit.rect.top+=originTop,hit.rect.bottom+=originTop,bestHit=hit)}}}return bestHit}};function isHitsEqual(hit0,hit1){return!hit0&&!hit1?!0:!!hit0!=!!hit1?!1:isDateSpansEqual(hit0.dateSpan,hit1.dateSpan)}function buildDatePointApiWithContext(dateSpan,context){let props={};for(let transform of context.pluginHooks.datePointTransforms)Object.assign(props,transform(dateSpan,context));return Object.assign(props,buildDatePointApi(dateSpan,context.dateEnv)),props}function buildDatePointApi(span,dateEnv){let start=buildRangeEdgeOutput(span.range.start,span.instantStartMs,dateEnv,span.allDay);return{date:start.date,dateStr:start.dateStr,allDay:span.allDay}}var DateClicking=class extends Interaction{constructor(settings){super(settings),this.handlePointerDown=pev=>{let{dragging}=this,downEl=pev.origEvent.target;this.component.context.emitter.hasHandlers("dateClick")&&this.component.isValidDateDownEl(downEl)||dragging.cancel()},this.handleDragEnd=ev=>{let{component}=this,{pointer}=this.dragging;if(!pointer.wasTouchScroll){let{initialHit,finalHit}=this.hitDragging;if(initialHit&&finalHit&&isHitsEqual(initialHit,finalHit)){let{context}=component,data={...buildDatePointApiWithContext(initialHit.dateSpan,context),dayEl:initialHit.getDayEl(),jsEvent:ev.origEvent,view:context.viewApi||context.calendarApi.view};context.emitter.trigger("dateClick",data)}}},this.dragging=new FeaturefulElementDragging(settings.el),this.dragging.autoScroller.isEnabled=!1;let hitDragging=this.hitDragging=new HitDragging(this.dragging,interactionSettingsToStore(settings));hitDragging.emitter.on("pointerdown",this.handlePointerDown),hitDragging.emitter.on("dragend",this.handleDragEnd)}destroy(){this.dragging.destroy()}},DateSelecting=class extends Interaction{constructor(settings){super(settings),this.dragSelection=null,this.handlePointerDown=ev=>{let{component:component2,dragging:dragging2}=this,{options:options2}=component2.context;options2.selectable&&component2.isValidDateDownEl(ev.origEvent.target)?dragging2.delay=ev.isTouch?getComponentTouchDelay$1(component2):null:dragging2.cancel()},this.handleDragStart=ev=>{this.component.context.calendarApi.unselect(ev)},this.handleHitUpdate=(hit,isFinal)=>{let{context}=this.component,dragSelection=null,isInvalid=!1;if(hit){let initialHit=this.hitDragging.initialHit;hit.componentId===initialHit.componentId&&this.isHitComboAllowed&&!this.isHitComboAllowed(initialHit,hit)||(dragSelection=joinHitsIntoSelection(initialHit,hit,context.pluginHooks.dateSelectionTransformers)),(!dragSelection||!isDateSelectionValid(dragSelection,hit.dateProfile,context))&&(isInvalid=!0,dragSelection=null)}dragSelection?context.dispatch({type:"SELECT_DATES",selection:dragSelection}):isFinal||context.dispatch({type:"UNSELECT_DATES"}),isInvalid?disableCursor():enableCursor(),isFinal||(this.dragSelection=dragSelection)},this.handlePointerUp=pev=>{this.dragSelection?(triggerDateSelect(this.dragSelection,pev,this.component.context),this.dragSelection=null):this.component.context.emitter.trigger("_noDateSelect")};let{component}=settings,{options}=component.context,dragging=this.dragging=new FeaturefulElementDragging(settings.el);dragging.touchScrollAllowed=!1,dragging.minDistance=options.selectMinDistance||0,dragging.autoScroller.isEnabled=options.dragScroll;let hitDragging=this.hitDragging=new HitDragging(this.dragging,interactionSettingsToStore(settings));hitDragging.emitter.on("pointerdown",this.handlePointerDown),hitDragging.emitter.on("dragstart",this.handleDragStart),hitDragging.emitter.on("hitupdate",this.handleHitUpdate),hitDragging.emitter.on("pointerup",this.handlePointerUp)}destroy(){this.dragging.destroy()}};function getComponentTouchDelay$1(component){let{options}=component.context,delay=options.selectLongPressDelay;return delay==null&&(delay=options.longPressDelay),delay}function joinHitsIntoSelection(hit0,hit1,dateSelectionTransformers){let dateSpan0=hit0.dateSpan,dateSpan1=hit1.dateSpan,hasInstants=dateSpan0.instantStartMs!=null||dateSpan1.instantStartMs!=null,entries=[{date:dateSpan0.range.start,ms:getDateSpanInstantStartMs(dateSpan0,hit0.context.dateEnv)},{date:dateSpan0.range.end,ms:getDateSpanInstantEndMs(dateSpan0,hit0.context.dateEnv)},{date:dateSpan1.range.start,ms:getDateSpanInstantStartMs(dateSpan1,hit1.context.dateEnv)},{date:dateSpan1.range.end,ms:getDateSpanInstantEndMs(dateSpan1,hit1.context.dateEnv)}];entries.sort(hasInstants?(entry0,entry1)=>compareNumbers2(entry0.ms,entry1.ms):(entry0,entry1)=>compareNumbers2(entry0.date.valueOf(),entry1.date.valueOf()));let props={};for(let transformer of dateSelectionTransformers){let res=transformer(hit0,hit1);if(res===!1)return null;res&&Object.assign(props,res)}if(hasInstants){let validRange=buildValidInstanceRange({marker:entries[0].date,instantMs:entries[0].ms},{marker:entries[3].date,instantMs:entries[3].ms},hit0.context.dateEnv);if(!validRange)return null;props.range={start:validRange.start,end:validRange.end}}else props.range={start:entries[0].date,end:entries[3].date};return props.allDay=dateSpan0.allDay,hasInstants&&(props.instantStartMs=entries[0].ms,props.instantEndMs=entries[3].ms),props}function computeHitInstantDeltaMs(hit0,hit1){let startMs0=hit0.dateSpan.allDay?null:hit0.dateSpan.instantStartMs,startMs1=hit1.dateSpan.allDay?null:hit1.dateSpan.instantStartMs;return startMs0!=null&&startMs1!=null?startMs1-startMs0:null}function computeHitDelta(hit0,hit1,options={}){let instantDeltaMs=computeHitInstantDeltaMs(hit0,hit1),date0=options.date0||hit0.dateSpan.range.start,date1=options.date1||hit1.dateSpan.range.start;return{delta:instantDeltaMs!=null?createDuration(instantDeltaMs):diffDates(date0,date1,hit0.context.dateEnv,options.largeUnit),instantDeltaMs}}var EventDragging=class _EventDragging extends Interaction{constructor(settings){super(settings),this.subjectEl=null,this.isDragging=!1,this.eventRange=null,this.relevantEvents=null,this.receivingContext=null,this.validMutation=null,this.mutatedRelevantEvents=null,this.handlePointerDown=ev=>{let origTarget=ev.origEvent.target,{component:component2,dragging:dragging2}=this,{mirror}=dragging2,{options:options2}=component2.context,initialContext=component2.context;this.subjectEl=ev.subjectEl;let eventInstanceId=(this.eventRange=getElEventRange(ev.subjectEl)).instance.instanceId;this.relevantEvents=getRelevantEvents(initialContext.getCurrentData().eventStore,eventInstanceId),dragging2.minDistance=ev.isTouch?0:options2.eventDragMinDistance,dragging2.delay=ev.isTouch&&eventInstanceId!==component2.props.eventSelection?getComponentTouchDelay(component2):null,mirror.parentNode=getAppendableRoot(origTarget),mirror.revertDuration=options2.dragRevertDuration,mirror.colorScheme=options2.colorScheme||"",component2.isValidSegDownEl(origTarget)&&!origTarget.closest(`.${classNames.internalEventResizer}`)?this.isDragging=ev.subjectEl.classList.contains(classNames.internalEventDraggable):dragging2.cancel()},this.handleDragStart=ev=>{let initialContext=this.component.context,eventRange=this.eventRange,eventInstanceId=eventRange.instance.instanceId;ev.isTouch?eventInstanceId!==this.component.props.eventSelection&&initialContext.dispatch({type:"SELECT_EVENT",eventInstanceId}):initialContext.dispatch({type:"UNSELECT_EVENT"}),this.isDragging&&(initialContext.calendarApi.unselect(ev),initialContext.emitter.trigger("eventDragStart",{el:this.subjectEl,event:new EventImpl(initialContext,eventRange.def,eventRange.instance),jsEvent:ev.origEvent,view:initialContext.viewApi}))},this.handleHitUpdate=(hit,isFinal)=>{if(!this.isDragging)return;let relevantEvents=this.relevantEvents,initialHit=this.hitDragging.initialHit,initialContext=this.component.context,receivingContext=null,mutation=null,mutatedRelevantEvents=null,isInvalid=!1,interaction={affectedEvents:relevantEvents,mutatedEvents:createEmptyEventStore(),isEvent:!0};if(hit){receivingContext=hit.context;let receivingOptions=receivingContext.options;initialContext===receivingContext||receivingOptions.editable&&receivingOptions.droppable?(mutation=computeEventMutation(initialHit,hit,this.eventRange.instance.range.start,receivingContext.getCurrentData().pluginHooks.eventDragMutationMassagers),mutation&&(mutatedRelevantEvents=applyMutationToEventStore(relevantEvents,receivingContext.getCurrentData().eventUiBases,mutation,receivingContext),interaction.mutatedEvents=mutatedRelevantEvents,isInteractionValid(interaction,hit.dateProfile,receivingContext)||(isInvalid=!0,mutation=null,mutatedRelevantEvents=null,interaction.mutatedEvents=createEmptyEventStore()))):receivingContext=null}this.displayDrag(receivingContext,interaction),isInvalid?disableCursor():enableCursor(),isFinal||(initialContext===receivingContext&&isHitsEqual(initialHit,hit)&&(mutation=null),this.dragging.setMirrorNeedsRevert(!mutation),this.dragging.setMirrorIsVisible(!hit||!this.subjectEl.getRootNode().querySelector(`.${classNames.internalEventMirror}`)),this.receivingContext=receivingContext,this.validMutation=mutation,this.mutatedRelevantEvents=mutatedRelevantEvents)},this.handlePointerUp=()=>{this.isDragging||this.cleanup()},this.handleDragEnd=ev=>{if(this.isDragging){let initialContext=this.component.context,initialView=initialContext.viewApi,{receivingContext,validMutation}=this,eventDef=this.eventRange.def,eventInstance=this.eventRange.instance,eventApi=new EventImpl(initialContext,eventDef,eventInstance),relevantEvents=this.relevantEvents,mutatedRelevantEvents=this.mutatedRelevantEvents,{finalHit}=this.hitDragging;if(this.clearDrag(),initialContext.emitter.trigger("eventDragStop",{el:this.subjectEl,event:eventApi,jsEvent:ev.origEvent,view:initialView}),validMutation){if(receivingContext===initialContext){let updatedEventApi=new EventImpl(initialContext,mutatedRelevantEvents.defs[eventDef.defId],eventInstance?mutatedRelevantEvents.instances[eventInstance.instanceId]:null);initialContext.dispatch({type:"MERGE_EVENTS",eventStore:mutatedRelevantEvents});let eventChangeData={oldEvent:eventApi,event:updatedEventApi,relatedEvents:buildEventApis(mutatedRelevantEvents,initialContext,eventInstance),revert(){initialContext.dispatch({type:"MERGE_EVENTS",eventStore:relevantEvents})}},transformed={};for(let transformer of initialContext.getCurrentData().pluginHooks.eventDropTransformers)Object.assign(transformed,transformer(validMutation,initialContext));initialContext.emitter.trigger("eventDrop",{...eventChangeData,...transformed,el:ev.subjectEl,delta:validMutation.datesDelta,jsEvent:ev.origEvent,view:initialView}),initialContext.emitter.trigger("eventChange",eventChangeData)}else if(receivingContext){let eventRemoveData={event:eventApi,relatedEvents:buildEventApis(relevantEvents,initialContext,eventInstance),revert(){initialContext.dispatch({type:"MERGE_EVENTS",eventStore:relevantEvents})}};initialContext.emitter.trigger("eventLeave",{...eventRemoveData,draggedEl:ev.subjectEl,view:initialView}),initialContext.dispatch({type:"REMOVE_EVENTS",eventStore:relevantEvents}),initialContext.emitter.trigger("eventRemove",eventRemoveData);let addedEventDef=mutatedRelevantEvents.defs[eventDef.defId],addedEventInstance=mutatedRelevantEvents.instances[eventInstance.instanceId],addedEventApi=new EventImpl(receivingContext,addedEventDef,addedEventInstance);receivingContext.dispatch({type:"MERGE_EVENTS",eventStore:mutatedRelevantEvents});let eventAddData={event:addedEventApi,relatedEvents:buildEventApis(mutatedRelevantEvents,receivingContext,addedEventInstance),revert(){receivingContext.dispatch({type:"REMOVE_EVENTS",eventStore:mutatedRelevantEvents})}};receivingContext.emitter.trigger("eventAdd",eventAddData),ev.isTouch&&receivingContext.dispatch({type:"SELECT_EVENT",eventInstanceId:eventInstance.instanceId}),receivingContext.emitter.trigger("drop",{...buildDatePointApiWithContext(finalHit.dateSpan,receivingContext),draggedEl:ev.subjectEl,jsEvent:ev.origEvent,view:finalHit.context.viewApi}),receivingContext.emitter.trigger("eventReceive",{...eventAddData,draggedEl:ev.subjectEl,view:finalHit.context.viewApi})}}else initialContext.emitter.trigger("_noEventDrop")}this.cleanup()};let{component}=this,{options}=component.context,dragging=this.dragging=new FeaturefulElementDragging(settings.el);dragging.pointer.selector=_EventDragging.SELECTOR,dragging.touchScrollAllowed=!1,dragging.autoScroller.isEnabled=options.dragScroll;let hitDragging=this.hitDragging=new HitDragging(this.dragging,interactionSettingsStore);hitDragging.useSubjectCenter=settings.useEventCenter,hitDragging.emitter.on("pointerdown",this.handlePointerDown),hitDragging.emitter.on("dragstart",this.handleDragStart),hitDragging.emitter.on("hitupdate",this.handleHitUpdate),hitDragging.emitter.on("pointerup",this.handlePointerUp),hitDragging.emitter.on("dragend",this.handleDragEnd)}destroy(){this.dragging.destroy()}displayDrag(nextContext,state){let initialContext=this.component.context,prevContext=this.receivingContext;prevContext&&prevContext!==nextContext&&(prevContext===initialContext?prevContext.dispatch({type:"SET_EVENT_DRAG",state:{affectedEvents:state.affectedEvents,mutatedEvents:createEmptyEventStore(),isEvent:!0}}):prevContext.dispatch({type:"UNSET_EVENT_DRAG"})),nextContext&&nextContext.dispatch({type:"SET_EVENT_DRAG",state})}clearDrag(){let initialCalendar=this.component.context,{receivingContext}=this;receivingContext&&receivingContext.dispatch({type:"UNSET_EVENT_DRAG"}),initialCalendar!==receivingContext&&initialCalendar.dispatch({type:"UNSET_EVENT_DRAG"})}cleanup(){this.isDragging=!1,this.eventRange=null,this.relevantEvents=null,this.receivingContext=null,this.validMutation=null,this.mutatedRelevantEvents=null}};EventDragging.SELECTOR=`.${classNames.internalEventDraggable}, .${classNames.internalEventResizable}`;function computeEventMutation(hit0,hit1,eventInstanceStart,massagers){let dateSpan0=hit0.dateSpan,dateSpan1=hit1.dateSpan,date0=dateSpan0.range.start,date1=dateSpan1.range.start,standardProps={};dateSpan0.allDay!==dateSpan1.allDay&&(standardProps.allDay=dateSpan1.allDay,standardProps.hasEnd=hit1.context.options.allDayMaintainDuration,dateSpan1.allDay?date0=startOfDay5(eventInstanceStart):date0=eventInstanceStart);let{delta,instantDeltaMs}=computeHitDelta(hit0,hit1,{date0,date1,largeUnit:hit0.componentId===hit1.componentId?hit0.largeUnit:null});delta.milliseconds&&(standardProps.allDay=!1);let mutation={datesDelta:delta,...instantDeltaMs!=null?{instantDatesDeltaMs:instantDeltaMs}:{},standardProps};for(let massager of massagers)massager(mutation,hit0,hit1);return mutation}function getComponentTouchDelay(component){let{options}=component.context,delay=options.eventLongPressDelay;return delay==null&&(delay=options.longPressDelay),delay}var EventResizing=class extends Interaction{constructor(settings){super(settings),this.draggingSegEl=null,this.draggingEventRange=null,this.eventRange=null,this.relevantEvents=null,this.validMutation=null,this.mutatedRelevantEvents=null,this.handlePointerDown=ev=>{let{component:component2}=this,segEl=this.querySegEl(ev),eventRange=this.eventRange=getElEventRange(segEl);this.dragging.minDistance=component2.context.options.eventDragMinDistance,this.component.isValidSegDownEl(ev.origEvent.target)&&!(ev.isTouch&&this.component.props.eventSelection!==eventRange.instance.instanceId)||this.dragging.cancel()},this.handleDragStart=ev=>{let{context}=this.component,eventRange=this.eventRange;this.relevantEvents=getRelevantEvents(context.getCurrentData().eventStore,this.eventRange.instance.instanceId);let segEl=this.querySegEl(ev);this.draggingSegEl=segEl,this.draggingEventRange=getElEventRange(segEl),context.calendarApi.unselect(),context.emitter.trigger("eventResizeStart",{el:segEl,event:new EventImpl(context,eventRange.def,eventRange.instance),jsEvent:ev.origEvent,view:context.viewApi})},this.handleHitUpdate=(hit,isFinal,ev)=>{let{context}=this.component,relevantEvents=this.relevantEvents,initialHit=this.hitDragging.initialHit,eventInstance=this.eventRange.instance,mutation=null,mutatedRelevantEvents=null,isInvalid=!1,interaction={affectedEvents:relevantEvents,mutatedEvents:createEmptyEventStore(),isEvent:!0};hit&&(hit.componentId===initialHit.componentId&&this.isHitComboAllowed&&!this.isHitComboAllowed(initialHit,hit)||(mutation=computeMutation(initialHit,hit,ev.subjectEl.classList.contains(classNames.internalEventResizerStart),eventInstance.range))),mutation&&(mutatedRelevantEvents=applyMutationToEventStore(relevantEvents,context.getCurrentData().eventUiBases,mutation,context),interaction.mutatedEvents=mutatedRelevantEvents,isInteractionValid(interaction,hit.dateProfile,context)||(isInvalid=!0,mutation=null,mutatedRelevantEvents=null,interaction.mutatedEvents=null)),mutatedRelevantEvents?context.dispatch({type:"SET_EVENT_RESIZE",state:interaction}):context.dispatch({type:"UNSET_EVENT_RESIZE"}),isInvalid?disableCursor():enableCursor(),isFinal||(mutation&&isHitsEqual(initialHit,hit)&&(mutation=null),this.validMutation=mutation,this.mutatedRelevantEvents=mutatedRelevantEvents)},this.handleDragEnd=ev=>{let{context}=this.component,eventDef=this.eventRange.def,eventInstance=this.eventRange.instance,eventApi=new EventImpl(context,eventDef,eventInstance),relevantEvents=this.relevantEvents,mutatedRelevantEvents=this.mutatedRelevantEvents;if(context.emitter.trigger("eventResizeStop",{el:this.draggingSegEl,event:eventApi,jsEvent:ev.origEvent,view:context.viewApi}),this.validMutation){let updatedEventApi=new EventImpl(context,mutatedRelevantEvents.defs[eventDef.defId],eventInstance?mutatedRelevantEvents.instances[eventInstance.instanceId]:null);context.dispatch({type:"MERGE_EVENTS",eventStore:mutatedRelevantEvents});let eventChangeData={oldEvent:eventApi,event:updatedEventApi,relatedEvents:buildEventApis(mutatedRelevantEvents,context,eventInstance),revert(){context.dispatch({type:"MERGE_EVENTS",eventStore:relevantEvents})}};context.emitter.trigger("eventResize",{...eventChangeData,el:this.draggingSegEl,startDelta:this.validMutation.startDelta||createDuration(0),endDelta:this.validMutation.endDelta||createDuration(0),jsEvent:ev.origEvent,view:context.viewApi}),context.emitter.trigger("eventChange",eventChangeData)}else context.emitter.trigger("_noEventResize");this.draggingEventRange=null,this.relevantEvents=null,this.validMutation=null};let{component}=settings,dragging=this.dragging=new FeaturefulElementDragging(settings.el);dragging.pointer.selector=`.${classNames.internalEventResizer}`,dragging.touchScrollAllowed=!1,dragging.autoScroller.isEnabled=component.context.options.dragScroll;let hitDragging=this.hitDragging=new HitDragging(this.dragging,interactionSettingsToStore(settings));hitDragging.emitter.on("pointerdown",this.handlePointerDown),hitDragging.emitter.on("dragstart",this.handleDragStart),hitDragging.emitter.on("hitupdate",this.handleHitUpdate),hitDragging.emitter.on("dragend",this.handleDragEnd)}destroy(){this.dragging.destroy()}querySegEl(ev){return ev.subjectEl.closest(`.${classNames.internalEvent}`)}};function computeMutation(hit0,hit1,isFromStart,instanceRange){let{context}=hit0,date0=hit0.dateSpan.range.start,date1=hit1.dateSpan.range.start,{delta,instantDeltaMs}=computeHitDelta(hit0,hit1,{date0,date1,largeUnit:hit0.largeUnit});if(isFromStart){let newStart=addDeltaToRangeEdge(instanceRange.start,instanceRange.instantStartMs,delta,instantDeltaMs??void 0,context);if(newStart.instantMs!=null?newStart.instantMs<getRangeInstantEndMs(instanceRange,context.dateEnv):newStart.marker<instanceRange.end)return{startDelta:delta,...instantDeltaMs!=null?{instantStartDeltaMs:instantDeltaMs}:{}}}else{let newEnd=addDeltaToRangeEdge(instanceRange.end,instanceRange.instantEndMs,delta,instantDeltaMs??void 0,context);if(newEnd.instantMs!=null?newEnd.instantMs>getRangeInstantStartMs(instanceRange,context.dateEnv):newEnd.marker>instanceRange.start)return{endDelta:delta,...instantDeltaMs!=null?{instantEndDeltaMs:instantDeltaMs}:{}}}return null}var UnselectAuto=class{constructor(context){this.context=context,this.isRecentPointerDateSelect=!1,this.matchesCancel=!1,this.matchesEvent=!1,this.onSelect=selectInfo=>{selectInfo.jsEvent&&(this.isRecentPointerDateSelect=!0)},this.onDocumentPointerDown=pev=>{let unselectCancel=this.context.options.unselectCancel,downEl=getEventTargetViaRoot(pev.origEvent);this.matchesCancel=!!downEl.closest(unselectCancel),this.matchesEvent=!!downEl.closest(EventDragging.SELECTOR)},this.onDocumentPointerUp=pev=>{let{context:context2}=this,{documentPointer:documentPointer2}=this,calendarState=context2.getCurrentData();if(!documentPointer2.wasTouchScroll){if(calendarState.dateSelection&&!this.isRecentPointerDateSelect){let unselectAuto=context2.options.unselectAuto;unselectAuto&&(!unselectAuto||!this.matchesCancel)&&context2.calendarApi.unselect(pev)}calendarState.eventSelection&&!this.matchesEvent&&context2.dispatch({type:"UNSELECT_EVENT"})}this.isRecentPointerDateSelect=!1};let documentPointer=this.documentPointer=new PointerDragging(document);documentPointer.shouldIgnoreMove=!0,documentPointer.shouldWatchScroll=!1,documentPointer.emitter.on("pointerdown",this.onDocumentPointerDown),documentPointer.emitter.on("pointerup",this.onDocumentPointerUp),context.emitter.on("select",this.onSelect)}destroy(){this.context.emitter.off("select",this.onSelect),this.documentPointer.destroy()}},interactionPlugin={name:"interaction",componentInteractions:[DateClicking,DateSelecting,EventDragging,EventResizing],calendarInteractions:[UnselectAuto],elementDraggingImpl:FeaturefulElementDragging};config.dataAttrPrefix="";import{jsx as jsx14,jsxs as jsxs10}from"react/jsx-runtime";var xxsTextClass="fc-classic-vQz",outlineWidthClass="fc-classic-0Bj",outlineWidthFocusClass="fc-classic-uqo",outlineOffsetClass="fc-classic-3Xj",outlineInsetClass="fc-classic-fFh",primaryOutlineColorClass="fc-classic-zIi",strongSolidPressableClass="fc-classic-BaR",mutedHoverClass="fc-classic-4yP",mutedHoverPressableClass=`${mutedHoverClass} fc-classic-tCP fc-classic-8gz`,faintHoverClass="fc-classic-Ubk",faintHoverPressableClass=`${faintHoverClass} fc-classic-OIx fc-classic-28F`,buttonIconClass="fc-classic-XUJ",blockPointerResizerClass="fc-classic-1EY fc-classic-pps fc-classic-vs6",rowPointerResizerClass=`${blockPointerResizerClass} fc-classic-AWB fc-classic-hza`,columnPointerResizerClass=`${blockPointerResizerClass} fc-classic-MaV fc-classic-uuA`,blockTouchResizerClass="fc-classic-1EY fc-classic-3wQ fc-classic-wsy fc-classic-lNM fc-classic-Jk3 fc-classic-AAA",rowTouchResizerClass=`${blockTouchResizerClass} fc-classic-ERR fc-classic-Dq8`,columnTouchResizerClass=`${blockTouchResizerClass} fc-classic-1V6 fc-classic-F99`,getDayClass=info=>joinClassNames("fc-classic-wsy",info.isMajor?"fc-classic-C0k":"fc-classic-C1x",info.isDisabled?"fc-classic-iYS":info.isToday&&"fc-classic-hbn"),getSlotClass=info=>joinClassNames("fc-classic-wsy fc-classic-C1x",info.isMinor&&"fc-classic-TN2"),dayRowCommonClasses={listItemEventClass:info=>joinClassNames("fc-classic-Ika fc-classic-7A6 fc-classic-Fvv",info.isNarrow?"fc-classic-148":"fc-classic-cKZ",info.isSelected?joinClassNames("fc-classic-k3f",info.isDragging&&"fc-classic-qNs"):info.isInteractive?mutedHoverPressableClass:mutedHoverClass),listItemEventBeforeClass:info=>joinClassNames("fc-classic-Mjo",info.isNarrow?"fc-classic-148":"fc-classic-rVY"),listItemEventInnerClass:info=>joinClassNames("fc-classic-dl1 fc-classic-1sP fc-classic-XpK fc-classic-z5u fc-classic-aTF",info.isNarrow?xxsTextClass:"fc-classic-a3B"),listItemEventTimeClass:"fc-classic-F1o fc-classic-TZ4 fc-classic-pKG fc-classic-1Zl",listItemEventTitleClass:"fc-classic-F1o fc-classic-DIS fc-classic-TZ4 fc-classic-pKG fc-classic-OLq",rowEventClass:info=>joinClassNames(info.isStart&&joinClassNames("fc-classic-kmj",info.isNarrow?"fc-classic-qvL":"fc-classic-Jzj"),info.isEnd&&joinClassNames("fc-classic-Skl",info.isNarrow?"fc-classic-9hC":"fc-classic-3e1")),rowEventInnerClass:"fc-classic-z5u fc-classic-aTF",rowEventTimeClass:"fc-classic-F1o",rowEventTitleClass:"fc-classic-F1o",rowMoreLinkClass:info=>joinClassNames("fc-classic-Ika fc-classic-wsy fc-classic-Fvv",info.isNarrow?"fc-classic-148 fc-classic-0Pr":"fc-classic-sI7 fc-classic-cKZ fc-classic-d0j",mutedHoverPressableClass),rowMoreLinkInnerClass:info=>joinClassNames("fc-classic-7A6",info.isNarrow?xxsTextClass:"fc-classic-a3B")},expanderIconClass="fc-classic-vnf fc-classic-mAY",continuationArrowClass="fc-classic-rVY fc-classic-XM3 fc-classic-rif fc-classic-lMo",index={name:"theme-classic",optionDefaults:{className:"fc-classic-yth fc-classic-n5m",viewClass:info=>{let hasBorderTop=info.options.headerToolbar||!info.borderlessTop,hasBorderBottom=info.options.footerToolbar||!info.borderlessBottom,hasBorderX=!info.borderlessX;return joinClassNames("fc-classic-Jk3 fc-classic-GAX fc-classic-C1x",hasBorderTop&&"fc-classic-ku3",hasBorderBottom&&"fc-classic-zi1",hasBorderX&&"fc-classic-1Wx")},toolbarClass:info=>joinClassNames("fc-classic-dl1 fc-classic-1sP fc-classic-dNl fc-classic-XpK fc-classic-N2M fc-classic-wwb",info.borderlessX&&"fc-classic-Apf"),toolbarSectionClass:"fc-classic-yi0 fc-classic-dl1 fc-classic-1sP fc-classic-XpK fc-classic-wwb",toolbarTitleClass:"fc-classic-AVD fc-classic-DIS",buttonGroupClass:"fc-classic-dl1 fc-classic-1sP fc-classic-XpK",buttonClass:info=>joinClassNames("fc-classic-dl6 fc-classic-1Wx fc-classic-dl1 fc-classic-1sP fc-classic-XpK fc-classic-sOR fc-classic-lYz fc-classic-vwH fc-classic-9yp fc-classic-RnT fc-classic-cfp fc-classic-Z9U",info.isIconOnly?"fc-classic-Eaq":"fc-classic-Apf",info.buttonGroup?"fc-classic-uk6 fc-classic-Tuc":"fc-classic-Ig4",info.isSelected?"fc-classic-rQI fc-classic-Adi":"fc-classic-vXO fc-classic-bqK fc-classic-aIH fc-classic-nQ5 fc-classic-JWq fc-classic-9Rj fc-classic-5ky",info.isDisabled&&"fc-classic-Q3Z fc-classic-3Lc"),buttons:{prev:{iconContent:()=>chevronLeft(`${buttonIconClass} fc-classic-asP`)},next:{iconContent:()=>chevronLeft(`${buttonIconClass} fc-classic-jmT fc-classic-jY6`)},prevYear:{iconContent:()=>chevronsLeft(`${buttonIconClass} fc-classic-asP`)},nextYear:{iconContent:()=>chevronsLeft(`${buttonIconClass} fc-classic-jmT fc-classic-jY6`)}},eventColor:"var(--fc-classic-event)",eventContrastColor:"var(--fc-classic-event-contrast)",eventClass:info=>joinClassNames(info.isDragging&&"fc-classic-n5m",info.event.url&&"fc-classic-JiE",info.isSelected?joinClassNames(outlineWidthClass,info.isDragging?"fc-classic-1kP":"fc-classic-tkw"):outlineWidthFocusClass,primaryOutlineColorClass),backgroundEventColor:"var(--fc-classic-background-event)",backgroundEventClass:"fc-classic-hsC fc-classic-jsy fc-classic-DO7",backgroundEventTitleClass:info=>joinClassNames("fc-classic-MGT fc-classic-L1Y",info.isNarrow?`fc-classic-KUX ${xxsTextClass}`:"fc-classic-XJa fc-classic-a3B"),listItemEventClass:"fc-classic-XpK",listItemEventBeforeClass:"fc-classic-lNM fc-classic-AAA",listItemEventInnerClass:"fc-classic-GAX",blockEventClass:info=>joinClassNames("fc-classic-bCs fc-classic-eYX fc-classic-d0j fc-classic-DO7 fc-classic-YjJ fc-classic-vwH",info.isDragging&&!info.isSelected&&"fc-classic-iTG",outlineOffsetClass),blockEventInnerClass:"fc-classic-i9F fc-classic-cfp",blockEventTimeClass:"fc-classic-TZ4 fc-classic-pKG fc-classic-1Zl",blockEventTitleClass:"fc-classic-TZ4 fc-classic-pKG fc-classic-OLq",rowEventClass:info=>joinClassNames("fc-classic-Ika fc-classic-JIC",info.isStart&&"fc-classic-3J4",info.isEnd&&"fc-classic-USt"),rowEventBeforeClass:info=>joinClassNames(info.isStartResizable&&joinClassNames(info.isSelected?rowTouchResizerClass:rowPointerResizerClass,"fc-classic-11a")),rowEventAfterClass:info=>joinClassNames(info.isEndResizable&&joinClassNames(info.isSelected?rowTouchResizerClass:rowPointerResizerClass,"fc-classic-bEw")),rowEventInnerClass:info=>joinClassNames("fc-classic-dl1 fc-classic-1sP fc-classic-XpK",info.isNarrow?xxsTextClass:"fc-classic-a3B"),rowEventTimeClass:"fc-classic-DIS",columnEventClass:info=>joinClassNames("fc-classic-1Wx fc-classic-A3h fc-classic-yKG",info.isStart&&"fc-classic-ku3 fc-classic-Z7Q",info.isEnd&&"fc-classic-Ika fc-classic-zi1 fc-classic-2qh"),columnEventBeforeClass:info=>joinClassNames(info.isStartResizable&&joinClassNames(info.isSelected?columnTouchResizerClass:columnPointerResizerClass,"fc-classic-YDC")),columnEventAfterClass:info=>joinClassNames(info.isEndResizable&&joinClassNames(info.isSelected?columnTouchResizerClass:columnPointerResizerClass,"fc-classic-fJL")),columnEventInnerClass:info=>joinClassNames("fc-classic-dl1",info.isShort?"fc-classic-KUX fc-classic-1sP fc-classic-XpK fc-classic-NWN":"fc-classic-oQ2 fc-classic-sgX"),columnEventTimeClass:info=>joinClassNames(!info.isShort&&"fc-classic-166",xxsTextClass),columnEventTitleClass:info=>joinClassNames(!info.isShort&&"fc-classic-2rx",info.isShort||info.isNarrow?xxsTextClass:"fc-classic-a3B"),moreLinkClass:`${outlineWidthFocusClass} ${primaryOutlineColorClass}`,moreLinkInnerClass:"fc-classic-TZ4 fc-classic-pKG",columnMoreLinkClass:`fc-classic-Ika fc-classic-Fvv fc-classic-wsy fc-classic-d0j fc-classic-4MR ${strongSolidPressableClass} fc-classic-vwH fc-classic-A3h fc-classic-yKG ${outlineOffsetClass}`,columnMoreLinkInnerClass:info=>joinClassNames("fc-classic-KUX",info.isNarrow?xxsTextClass:"fc-classic-a3B"),dayHeaderAlign:info=>info.inPopover?"start":"center",dayHeaderClass:info=>joinClassNames("fc-classic-E9P",info.isDisabled&&"fc-classic-iYS",info.inPopover?"fc-classic-zi1 fc-classic-C1x fc-classic-k3f":joinClassNames("fc-classic-wsy",info.isMajor?"fc-classic-C0k":"fc-classic-C1x")),dayHeaderInnerClass:info=>joinClassNames("fc-classic-rVY fc-classic-cJ3 fc-classic-dl1 fc-classic-sgX",info.isNarrow?xxsTextClass:"fc-classic-9yp"),dayHeaderDividerClass:"fc-classic-zi1 fc-classic-C1x",dayCellClass:getDayClass,dayCellTopClass:info=>joinClassNames(info.isNarrow?"fc-classic-toR":"fc-classic-84e","fc-classic-dl1 fc-classic-1sP fc-classic-LMv"),dayCellTopInnerClass:info=>joinClassNames("fc-classic-rVY fc-classic-TZ4",info.isNarrow?`fc-classic-cJ3 ${xxsTextClass}`:"fc-classic-V9v fc-classic-9yp",info.isOther&&"fc-classic-taq",info.monthText&&"fc-classic-DIS"),dayCellInnerClass:info=>joinClassNames(info.inPopover&&"fc-classic-3N5"),popoverClass:"fc-classic-Jk3 fc-classic-GAX fc-classic-wsy fc-classic-C1x fc-classic-tkw fc-classic-aNc fc-classic-n5m",popoverCloseClass:`fc-classic-bCs fc-classic-1EY fc-classic-2ik fc-classic-2w8 ${outlineWidthFocusClass} ${primaryOutlineColorClass} fc-classic-Z9U`,popoverCloseContent:()=>x("fc-classic-XUJ fc-classic-9yp fc-classic-mAY"),dayLaneClass:getDayClass,dayLaneInnerClass:info=>info.isStack?"fc-classic-gMS":info.isNarrow?"fc-classic-148":"fc-classic-Jzj fc-classic-B3G",slotLaneClass:getSlotClass,listDayHeaderClass:"fc-classic-zi1 fc-classic-C1x fc-classic-SDU fc-classic-nHS fc-classic-dl1 fc-classic-1sP fc-classic-XpK fc-classic-N2M",listDayHeaderInnerClass:"fc-classic-Apf fc-classic-dl6 fc-classic-9yp fc-classic-DIS",singleMonthClass:info=>joinClassNames(info.multiMonthColumns>1&&"fc-classic-jD5",info.multiMonthColumns===1&&!info.isLast&&"fc-classic-zi1 fc-classic-C1x"),singleMonthHeaderClass:info=>joinClassNames(info.multiMonthColumns>1?"fc-classic-cM0":"fc-classic-dl6 fc-classic-zi1 fc-classic-C1x fc-classic-Jk3","fc-classic-XpK"),singleMonthHeaderInnerClass:"fc-classic-1Po fc-classic-DIS",tableHeaderClass:"fc-classic-Jk3",fillerClass:"fc-classic-wsy fc-classic-C1x fc-classic-lMo",dayHeaderRowClass:"fc-classic-wsy fc-classic-C1x",dayRowClass:"fc-classic-wsy fc-classic-C1x",slotHeaderRowClass:"fc-classic-wsy fc-classic-C1x",slotHeaderClass:getSlotClass,navLinkClass:`fc-classic-Eu0 ${outlineWidthFocusClass} ${outlineInsetClass} ${primaryOutlineColorClass}`,inlineWeekNumberClass:info=>joinClassNames("fc-classic-1EY fc-classic-n9G fc-classic-rbS fc-classic-C2g fc-classic-KUX fc-classic-HXA fc-classic-m9h fc-classic-k3f",info.isNarrow?xxsTextClass:"fc-classic-9yp"),nonBusinessHoursClass:"fc-classic-iYS",highlightClass:"fc-classic-hLU",resourceDayHeaderAlign:"center",resourceDayHeaderClass:info=>joinClassNames("fc-classic-wsy",info.isMajor?"fc-classic-C0k":"fc-classic-C1x"),resourceDayHeaderInnerClass:info=>joinClassNames("fc-classic-rVY fc-classic-cJ3 fc-classic-dl1 fc-classic-sgX",info.isNarrow?xxsTextClass:"fc-classic-9yp"),resourceColumnHeaderClass:"fc-classic-wsy fc-classic-C1x fc-classic-E9P",resourceColumnHeaderInnerClass:"fc-classic-bvX fc-classic-9yp",resourceColumnResizerClass:"fc-classic-1EY fc-classic-AWB fc-classic-4Tv fc-classic-dnf",resourceGroupHeaderClass:"fc-classic-wsy fc-classic-C1x fc-classic-k3f",resourceGroupHeaderInnerClass:"fc-classic-bvX fc-classic-9yp",resourceCellClass:"fc-classic-wsy fc-classic-C1x",resourceCellInnerClass:"fc-classic-bvX fc-classic-9yp",resourceIndentClass:"fc-classic-Mde fc-classic-kp0 fc-classic-E9P",resourceExpanderClass:`fc-classic-bCs ${outlineWidthFocusClass} ${primaryOutlineColorClass}`,resourceExpanderContent:info=>info.isExpanded?minusSquare(expanderIconClass):plusSquare(expanderIconClass),resourceHeaderRowClass:"fc-classic-wsy fc-classic-C1x",resourceRowClass:"fc-classic-wsy fc-classic-C1x",resourceColumnDividerClass:"fc-classic-1Wx fc-classic-C1x fc-classic-a7i fc-classic-k3f",resourceGroupLaneClass:"fc-classic-wsy fc-classic-C1x fc-classic-k3f",resourceLaneClass:"fc-classic-wsy fc-classic-C1x",resourceLaneBottomClass:info=>info.options.eventOverlap&&"fc-classic-zrJ",timelineBottomClass:"fc-classic-zrJ"},views:{dayGrid:{...dayRowCommonClasses,dayCellBottomClass:"fc-classic-toR"},multiMonth:{...dayRowCommonClasses,dayCellBottomClass:"fc-classic-toR",tableClass:info=>joinClassNames(info.multiMonthColumns>1&&"fc-classic-C1x fc-classic-wsy")},timeGrid:{...dayRowCommonClasses,dayCellBottomClass:"fc-classic-mhE",weekNumberHeaderClass:"fc-classic-XpK fc-classic-LMv",weekNumberHeaderInnerClass:info=>joinClassNames("fc-classic-rVY fc-classic-cJ3",info.isNarrow?xxsTextClass:"fc-classic-9yp"),allDayHeaderClass:"fc-classic-XpK fc-classic-LMv",allDayHeaderInnerClass:info=>joinClassNames("fc-classic-rVY fc-classic-2tF fc-classic-2HE",info.isNarrow?xxsTextClass:"fc-classic-9yp"),allDayDividerClass:"fc-classic-JIC fc-classic-C1x fc-classic-8ub fc-classic-k3f",slotHeaderClass:"fc-classic-LMv",slotHeaderInnerClass:info=>joinClassNames("fc-classic-rVY fc-classic-cJ3",info.isNarrow?xxsTextClass:"fc-classic-9yp"),slotHeaderDividerClass:"fc-classic-USt fc-classic-C1x",nowIndicatorHeaderClass:"fc-classic-rbS fc-classic-a10 fc-classic-XM3 fc-classic-rif fc-classic-jIH fc-classic-0qY",nowIndicatorLineClass:"fc-classic-ku3 fc-classic-sYT"},list:{listDayClass:info=>joinClassNames(!info.isLast&&"fc-classic-zi1 fc-classic-C1x"),listItemEventClass:info=>joinClassNames("fc-classic-bCs fc-classic-Apf fc-classic-dl6 fc-classic-wwb fc-classic-ku3 fc-classic-C1x",info.isInteractive?joinClassNames(faintHoverPressableClass,outlineInsetClass):faintHoverClass),listItemEventBeforeClass:"fc-classic-GOm",listItemEventInnerClass:"fc-classic-eF2",listItemEventTimeClass:"fc-classic-88I fc-classic-yi0 fc-classic-roZ fc-classic-kMV fc-classic-TZ4 fc-classic-pKG fc-classic-IPx fc-classic-9yp",listItemEventTitleClass:info=>joinClassNames("fc-classic-1El fc-classic-2KU fc-classic-TZ4 fc-classic-pKG fc-classic-9yp",info.event.url&&"fc-classic-Ogp"),noEventsClass:"fc-classic-k3f fc-classic-dl1 fc-classic-sgX fc-classic-XpK fc-classic-E9P",noEventsInnerClass:"fc-classic-OUe fc-classic-jGI fc-classic-P9h"},timeline:{rowEventClass:info=>joinClassNames(info.isEnd&&"fc-classic-9hC","fc-classic-XpK"),rowEventBeforeClass:info=>!info.isStart&&`${continuationArrowClass} fc-classic-Bda fc-classic-5JV`,rowEventAfterClass:info=>!info.isEnd&&`${continuationArrowClass} fc-classic-hhi fc-classic-LaM`,rowEventInnerClass:info=>info.options.eventOverlap?"fc-classic-2rx":"fc-classic-End",rowEventTimeClass:"fc-classic-oQ2",rowEventTitleClass:"fc-classic-oQ2",rowMoreLinkClass:`fc-classic-9hC fc-classic-Ika fc-classic-wsy fc-classic-d0j fc-classic-4MR ${strongSolidPressableClass} fc-classic-vwH`,rowMoreLinkInnerClass:"fc-classic-KUX fc-classic-a3B",slotHeaderAlign:info=>info.isTime?"start":"center",slotHeaderClass:info=>joinClassNames("fc-classic-E9P",!info.level&&"fc-classic-pKG"),slotHeaderInnerClass:info=>joinClassNames("fc-classic-fn8 fc-classic-V9v fc-classic-9yp",info.hasNavLink&&"fc-classic-Eu0"),slotHeaderDividerClass:"fc-classic-zi1 fc-classic-C1x",nowIndicatorHeaderClass:"fc-classic-n9G fc-classic-J04 fc-classic-ybF fc-classic-Pqk fc-classic-bLA fc-classic-sYT",nowIndicatorLineClass:"fc-classic-3J4 fc-classic-sYT"}}};function chevronLeft(className){return jsx14("svg",{xmlns:"http://www.w3.org/2000/svg",className,width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx14("polyline",{points:"15 18 9 12 15 6"})})}function chevronsLeft(className){return jsxs10("svg",{xmlns:"http://www.w3.org/2000/svg",className,width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx14("polyline",{points:"11 17 6 12 11 7"}),jsx14("polyline",{points:"18 17 13 12 18 7"})]})}function x(className){return jsxs10("svg",{xmlns:"http://www.w3.org/2000/svg",className,width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx14("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsx14("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function plusSquare(className){return jsxs10("svg",{xmlns:"http://www.w3.org/2000/svg",className,width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx14("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),jsx14("line",{x1:"12",y1:"8",x2:"12",y2:"16"}),jsx14("line",{x1:"8",y1:"12",x2:"16",y2:"12"})]})}function minusSquare(className){return jsxs10("svg",{xmlns:"http://www.w3.org/2000/svg",className,width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx14("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),jsx14("line",{x1:"8",y1:"12",x2:"16",y2:"12"})]})}import{jsx as jsx16}from"react/jsx-runtime";import{jsx as jsx15,jsxs as jsxs11,Fragment as Fragment8}from"react/jsx-runtime";import{createRef as createRef3,createElement as createElement5}from"react";function buildDayColsFromSeries(daySeries,dateEnv,config2={}){let{slotRange,majorUnit="",activeRange}=config2;return daySeries.dates.map(date=>({key:date.toISOString(),date,range:slotRange?{start:dateEnv.add(date,slotRange.slotMinTime),end:dateEnv.add(date,slotRange.slotMaxTime)}:{start:date,end:addDays4(date,1)},isMajor:majorUnit?isMajorUnit(date,majorUnit,dateEnv):!1,isDisabled:activeRange===null||activeRange!==void 0&&!rangeContainsMarker(activeRange,date)}))}var EMPTY_EVENT_STORE=createEmptyEventStore(),Splitter=class{constructor(){this.getKeysForEventDefs=memoize2(this._getKeysForEventDefs),this.splitDateSelection=memoize2(this._splitDateSpan),this.splitEventStore=memoize2(this._splitEventStore),this.splitIndividualUi=memoize2(this._splitIndividualUi),this.splitEventDrag=memoize2(this._splitInteraction),this.splitEventResize=memoize2(this._splitInteraction),this.eventUiBuilders={}}splitProps(props){let keyInfos=this.getKeyInfo(props),defKeys=this.getKeysForEventDefs(props.eventStore),dateSelections=this.splitDateSelection(props.dateSelection),individualUi=this.splitIndividualUi(props.eventUiBases,defKeys),eventStores=this.splitEventStore(props.eventStore,defKeys),eventDrags=this.splitEventDrag(props.eventDrag),eventResizes=this.splitEventResize(props.eventResize),splitProps={};this.eventUiBuilders=mapHash(keyInfos,(info,key)=>this.eventUiBuilders[key]||memoize2(buildEventUiForKey));for(let key in keyInfos){let keyInfo=keyInfos[key],eventStore=eventStores[key]||EMPTY_EVENT_STORE,buildEventUi=this.eventUiBuilders[key];splitProps[key]={businessHours:keyInfo.businessHours||props.businessHours,dateSelection:dateSelections[key]||null,eventStore,eventUiBases:buildEventUi(props.eventUiBases[""],keyInfo.ui,individualUi[key]),eventDrag:eventDrags[key]||null,eventResize:eventResizes[key]||null,eventSelection:eventStore.instances[props.eventSelection]?props.eventSelection:""}}return splitProps}_splitDateSpan(dateSpan){let dateSpans={};if(dateSpan){let keys=this.getKeysForDateSpan(dateSpan);for(let key of keys)dateSpans[key]=dateSpan}return dateSpans}_getKeysForEventDefs(eventStore){return mapHash(eventStore.defs,eventDef=>this.getKeysForEventDef(eventDef))}_splitEventStore(eventStore,defKeys){let{defs,instances}=eventStore,splitStores={};for(let defId in defs)for(let key of defKeys[defId])splitStores[key]||(splitStores[key]=createEmptyEventStore()),splitStores[key].defs[defId]=defs[defId];for(let instanceId in instances){let instance=instances[instanceId];for(let key of defKeys[instance.defId])splitStores[key]&&(splitStores[key].instances[instanceId]=instance)}return splitStores}_splitIndividualUi(eventUiBases,defKeys){let splitHashes={};for(let defId in eventUiBases)if(defId)for(let key of defKeys[defId])splitHashes[key]||(splitHashes[key]={}),splitHashes[key][defId]=eventUiBases[defId];return splitHashes}_splitInteraction(interaction){let splitStates={};if(interaction){let affectedStores=this._splitEventStore(interaction.affectedEvents,this._getKeysForEventDefs(interaction.affectedEvents)),mutatedKeysByDefId=this._getKeysForEventDefs(interaction.mutatedEvents),mutatedStores=this._splitEventStore(interaction.mutatedEvents,mutatedKeysByDefId),populate=key=>{splitStates[key]||(splitStates[key]={affectedEvents:affectedStores[key]||EMPTY_EVENT_STORE,mutatedEvents:mutatedStores[key]||EMPTY_EVENT_STORE,isEvent:interaction.isEvent})};for(let key in affectedStores)populate(key);for(let key in mutatedStores)populate(key)}return splitStates}};function buildEventUiForKey(allUi,eventUiForKey,individualUi){let baseParts=[];allUi&&baseParts.push(allUi),eventUiForKey&&baseParts.push(eventUiForKey);let stuff={"":combineEventUis(baseParts)};return individualUi&&Object.assign(stuff,individualUi),stuff}var AllDaySplitter=class extends Splitter{getKeyInfo(){return{allDay:{},timed:{}}}getKeysForDateSpan(dateSpan){return dateSpan.allDay?["allDay"]:["timed"]}getKeysForEventDef(eventDef){return eventDef.allDay?hasBgRendering(eventDef)?["timed","allDay"]:["allDay"]:["timed"]}},DayTimeColsSlicer=class extends Slicer{sliceRange(range,dayRanges){let segs=[];for(let col=0;col<dayRanges.length;col+=1){let segRange=intersectRanges(range,dayRanges[col]);segRange&&segs.push({startDate:segRange.start,endDate:segRange.end,isStart:segRange.start.valueOf()===range.start.valueOf(),isEnd:segRange.end.valueOf()===range.end.valueOf(),col})}return segs}};function organizeSegsByCol(segs,colCount){let segsByCol=[],i;for(i=0;i<colCount;i+=1)segsByCol.push([]);if(segs)for(i=0;i<segs.length;i+=1)segsByCol[segs[i].col].push(segs[i]);return segsByCol}function splitInteractionByCol(ui,colCount){let byRow=[];if(ui){for(let i=0;i<colCount;i+=1)byRow[i]={affectedInstances:ui.affectedInstances,isEvent:ui.isEvent,segs:[]};for(let seg of ui.segs)byRow[seg.col].segs.push(seg)}else for(let i=0;i<colCount;i+=1)byRow[i]=null;return byRow}var STOCK_SUB_DURATIONS=[{hours:1},{minutes:30},{minutes:15},{seconds:30},{seconds:15}];function buildSlatMetas(slotMinTime,slotMaxTime,explicitLabelInterval,slotDuration,dateEnv){let dayStart=new Date(0),slatTime=slotMinTime,slatIterator=createDuration(0),labelInterval=explicitLabelInterval||computeLabelInterval(slotDuration),metas=[],i=0;for(;asRoughMs(slatTime)<asRoughMs(slotMaxTime);){let date=dateEnv.add(dayStart,slatTime),isLabeled=wholeDivideDurations(slatIterator,labelInterval)!==null;metas.push({date,time:slatTime,key:date.toISOString(),isoTimeStr:formatIsoTimeString(date),isLabeled,isFirst:i===0}),slatTime=addDurations(slatTime,slotDuration),slatIterator=addDurations(slatIterator,slotDuration),i+=1}return metas}function computeLabelInterval(slotDuration){let i,labelInterval,slotsPerLabel;for(i=STOCK_SUB_DURATIONS.length-1;i>=0;i-=1)if(labelInterval=createDuration(STOCK_SUB_DURATIONS[i]),slotsPerLabel=wholeDivideDurations(labelInterval,slotDuration),slotsPerLabel!==null&&slotsPerLabel>1)return labelInterval;return slotDuration}var TimeGridAllDayHeader=class extends BaseComponent{constructor(){super(...arguments),this.innerElRef=createRef3()}render(){let{props}=this,{options,viewApi}=this.context,renderProps={text:options.allDayText,view:viewApi,isNarrow:props.isNarrow};return jsx15(ContentContainer,{tag:"div",attrs:{role:"rowheader"},className:joinClassNames(classNames.flexRow,classNames.noMargin,classNames.noPadding,classNames.contentBox),style:{width:props.width},renderProps,generatorName:"allDayHeaderContent",customGenerator:options.allDayHeaderContent,defaultGenerator:renderAllDayInner,classNameGenerator:options.allDayHeaderClass,didMount:options.allDayHeaderDidMount,willUnmount:options.allDayHeaderWillUnmount,children:InnerContent=>jsx15("div",{className:joinClassNames(classNames.flexRow,classNames.noShrink,classNames.whiteSpacePre),ref:this.innerElRef,children:jsx15(InnerContent,{tag:"div",className:generateClassName(options.allDayHeaderInnerClass,renderProps)})})})}componentDidMount(){this._isUnmounting=!1;let{props}=this,innerEl=this.innerElRef.current;this.disconnectInnerWidth=watchWidth(innerEl,width=>{this._isUnmounting||setRef(props.innerWidthRef,width)})}componentWillUnmount(){this._isUnmounting=!0,this.disconnectInnerWidth(),setRef(this.props.innerWidthRef,null)}};function renderAllDayInner(renderProps){return renderProps.text}var TimeGridAllDayLane=class extends DateComponent{constructor(){super(...arguments),this.state={},this.heightRef=createRef3(),this.handleMoreLinkEl=el=>{this.disconnectMoreLinkHeight?.(),this.disconnectMoreLinkHeight=void 0,el&&(this.disconnectMoreLinkHeight=watchHeight(el,height=>{this._isUnmounting||this.setState({moreLinkHeight:height})}))},this.handleRootEl=rootEl=>{this.rootEl=rootEl,rootEl?this.context.registerInteractiveComponent(this,{el:rootEl}):this.context.unregisterInteractiveComponent(this)}}render(){let{props,state}=this,needsMoreLinkProbe=!props.forPrint&&resolveDayGridPlacementMode(props.dayMaxEvents,props.dayMaxEventRows)==="auto";return jsxs11(Fragment8,{children:[jsx15(DayGridRow,{...props,moreLinkHeight:state.moreLinkHeight,rootElRef:this.handleRootEl,heightRef:this.heightRef}),needsMoreLinkProbe&&jsx15(MoreLinkTrigger,{num:1,display:"row",isNarrow:props.cellIsNarrow,isMicro:props.cellIsMicro,elRef:this.handleMoreLinkEl,className:classNames.offscreen,attrs:{"aria-hidden":!0,inert:""}})]})}componentDidMount(){this._isUnmounting=!1}componentWillUnmount(){this._isUnmounting=!0,this.disconnectMoreLinkHeight?.()}queryHit(isRtl,positionLeft,positionTop,elWidth){let{props,heightRef}=this,colCount=props.cells.length,{col,left,right}=computeColFromPosition(positionLeft,elWidth,props.colWidth,colCount,isRtl),cell=props.cells[col],cellStartDate=cell.date,cellEndDate=addDays4(cellStartDate,1);return{dateProfile:props.dateProfile,dateSpan:{range:{start:cellStartDate,end:cellEndDate},allDay:!0,...cell.dateSpanProps},getDayEl:()=>getCellEl(this.rootEl,col),rect:{left,right,top:0,bottom:heightRef.current},layer:0}}};function computeSlatHeight(expandRows,slatCnt,explicitSlatMinHeight=0,slatInnerHeight,scrollerHeight){if(!slatInnerHeight||!scrollerHeight)return[void 0,!1];let slatMinHeight=Math.max(slatInnerHeight+1,explicitSlatMinHeight),slatLiquidHeight=scrollerHeight/slatCnt,slatLiquid,slatHeight;return expandRows&&slatLiquidHeight>=slatMinHeight?(slatLiquid=!0,slatHeight=slatLiquidHeight):(slatLiquid=!1,slatHeight=slatMinHeight),[slatHeight,slatLiquid]}function computeDateTopFrac(date,dateProfile,startOfDayDate){return startOfDayDate||(startOfDayDate=startOfDay5(date)),computeTimeTopFrac(createDuration(date.valueOf()-startOfDayDate.valueOf()),dateProfile)}function computeTimeTopFrac(time,dateProfile){let startMs=asRoughMs(dateProfile.slotMinTime),endMs=asRoughMs(dateProfile.slotMaxTime),frac=(time.milliseconds-startMs)/(endMs-startMs);return frac=Math.max(0,frac),frac=Math.min(1,frac),frac}function computeFgSegVerticals(segs,dateProfile,colDate,slatCnt,slatHeight,eventMinHeight,eventShortHeight){let res=[];if(slatHeight!=null){let totalHeight=slatHeight*slatCnt;for(let seg of segs){let startFrac=computeDateTopFrac(seg.startDate,dateProfile,colDate),endFrac=computeDateTopFrac(seg.endDate,dateProfile,colDate),startCoord=startFrac*totalHeight,endCoord=endFrac*totalHeight,height=endCoord-startCoord;eventMinHeight!=null&&height<eventMinHeight&&(height=eventMinHeight,endCoord=startCoord+height),res.push({start:startCoord,end:endCoord,size:height,isShort:height<=eventShortHeight})}}return res}function buildTimeGridSegPlacements(segs,segVerticals,eventOrderStrict,eventMaxStack){let sourceSegs=[],segVerticalBySeg=new Map;for(let orderIndex=0;orderIndex<segs.length;orderIndex+=1){let seg=segs[orderIndex],segVertical=segVerticals[orderIndex];if(segVertical){let sourceSeg={...seg,key:seg.eventRange.instance.instanceId,start:segVertical.start,end:segVertical.end,orderIndex};sourceSegs.push(sourceSeg),segVerticalBySeg.set(sourceSeg,segVertical)}}let layout=layoutTimeGridColumnByMaxLevel(sourceSegs,eventMaxStack??1/0,{orderStrict:eventOrderStrict??!1});return{placements:layout.domOrderedPlacements.map(placement=>{let seg=placement.sourceSeg;return{seg,segVertical:segVerticalBySeg.get(seg),levelCoord:placement.levelCoord,thickness:placement.thickness,stackDepth:placement.backwardDepth,stackForward:placement.forwardDepth}}),hiddenGroups:layout.moreLinkGroups.map(group=>{let groupSegs=group.hiddenSlices.map(slice=>slice.sourceSeg);return{key:group.key,start:group.start,end:group.end,segs:groupSegs}})}}function layoutTimeGridColumnByMaxLevel(eventOrderedSegs,maxLevels,options){let{segLevels,excludedSegs}=buildSegLevels(eventOrderedSegs,options.orderStrict,maxLevels),placements=positionTimeGridPlacements(segLevels),moreLinkGroups=groupLaterallyIntersecting(convertSegsToWholeSlices(excludedSegs));return{domOrderedPlacements:sortByAxisOrder(placements),moreLinkGroups}}function positionTimeGridPlacements(levels){let placementLevels=levels.map((level,levelIndex)=>level.map(sourceSeg=>({sourceSeg,start:sourceSeg.start,end:sourceSeg.end,isStart:sourceSeg.isStart,isEnd:sourceSeg.isEnd,levelIndex}))),placements=flatArray(placementLevels),collidersByKey=new Map,parentByKey=new Map(placements.map(placement=>[placement.sourceSeg.key,placement.sourceSeg.key]));for(let placement of placements){let colliders=[];for(let levelIndex=placement.levelIndex+1;levelIndex<levels.length;levelIndex+=1)colliders.push(...findIntersections(placementLevels[levelIndex],placement));collidersByKey.set(placement.sourceSeg.key,colliders);for(let collider of colliders)unionPlacementKeys(parentByKey,placement.sourceSeg.key,collider.sourceSeg.key)}let maxLevelByRoot=new Map;for(let placement of placements){let root=findPlacementRoot(parentByKey,placement.sourceSeg.key);maxLevelByRoot.set(root,Math.max(maxLevelByRoot.get(root)??0,placement.levelIndex))}let backwardDepthByKey=new Map(placements.map(placement=>[placement.sourceSeg.key,0])),forwardDepthByKey=new Map(placements.map(placement=>[placement.sourceSeg.key,0]));for(let placement of placements){let depth=backwardDepthByKey.get(placement.sourceSeg.key)+1;for(let collider of collidersByKey.get(placement.sourceSeg.key))backwardDepthByKey.set(collider.sourceSeg.key,Math.max(backwardDepthByKey.get(collider.sourceSeg.key),depth))}for(let index2=placements.length-1;index2>=0;index2-=1){let placement=placements[index2],depth=0;for(let collider of collidersByKey.get(placement.sourceSeg.key))depth=Math.max(depth,forwardDepthByKey.get(collider.sourceSeg.key)+1);forwardDepthByKey.set(placement.sourceSeg.key,depth)}return placements.map(placement=>{let key=placement.sourceSeg.key,levelCount=maxLevelByRoot.get(findPlacementRoot(parentByKey,key))+1,farLevel=levelCount;for(let collider of collidersByKey.get(key))farLevel=Math.min(farLevel,collider.levelIndex);let levelCoord=placement.levelIndex/levelCount,thickness=(farLevel-placement.levelIndex)/levelCount;return{...placement,levelCoord,thickness,levelEndCoord:levelCoord+thickness,backwardDepth:backwardDepthByKey.get(key),forwardDepth:forwardDepthByKey.get(key)}})}function findPlacementRoot(parentByKey,key){let parent=parentByKey.get(key);if(parent===key)return key;let root=findPlacementRoot(parentByKey,parent);return parentByKey.set(key,root),root}function unionPlacementKeys(parentByKey,first,second){let firstRoot=findPlacementRoot(parentByKey,first),secondRoot=findPlacementRoot(parentByKey,second);firstRoot!==secondRoot&&parentByKey.set(secondRoot,firstRoot)}var ESTIMATED_SLAT_HEIGHT=50,isBrowserPrintQuirky=typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("firefox");function computeTimeGridPrintMode(forPrint,eventPrintLayout){return forPrint&&(eventPrintLayout==="stack"||eventPrintLayout!=="grid"&&isBrowserPrintQuirky)?"stack":"positioned"}var DEFAULT_TIME_FORMAT=createFormatter({hour:"numeric",minute:"2-digit",meridiem:!1}),TimeGridEvent=class extends BaseComponent{render(){let{props}=this;return jsx15(StandardEvent,{...props,display:"column",level:props.level,isNarrow:props.isNarrow,isShort:props.isShort,className:props.isLiquid?classNames.liquid:"",disableLiquid:!props.isLiquid,defaultTimeFormat:DEFAULT_TIME_FORMAT})}},TimeGridMoreLink=class extends BaseComponent{render(){let{props}=this;return jsx15("div",{className:joinClassNames(classNames.abs,classNames.flexCol,classNames.end0,classNames.z9999),style:{top:props.top,height:props.height},children:jsx15(MoreLinkContainer,{className:classNames.liquid,display:"column",allDayDate:null,segs:props.hiddenSegs,hiddenSegs:props.hiddenSegs,dateSpanProps:props.dateSpanProps,dateProfile:props.dateProfile,todayRange:props.todayRange,popoverContent:()=>renderPlainFgSegs(props.hiddenSegs,props,!1),forceTimed:!0,isNarrow:props.isNarrow,isMicro:props.isMicro})})}},NowIndicatorDot=props=>jsx15(ViewContextType.Consumer,{children:context=>{let{options}=context;return jsx15("div",{className:joinClassNames(props.className,options.nowIndicatorDotClass),style:props.style})}}),NowIndicatorLineContainer=props=>jsx15(ViewContextType.Consumer,{children:context=>{let{options}=context,renderProps={date:context.dateEnv.toDate(props.date),view:context.viewApi};return jsx15(ContentContainer,{elRef:props.elRef,tag:props.tag||"div",attrs:props.attrs,className:props.className,style:props.style,renderProps,generatorName:"nowIndicatorLineContent",customGenerator:options.nowIndicatorLineContent,classNameGenerator:options.nowIndicatorLineClass,didMount:options.nowIndicatorLineDidMount,willUnmount:options.nowIndicatorLineWillUnmount,children:props.children})}});function TimeGridNowIndicatorLine(props){let top=props.totalHeight!=null?props.totalHeight*computeDateTopFrac(props.nowDate,props.dateProfile,props.dayDate):void 0;return jsxs11("div",{className:joinClassNames(classNames.fill,classNames.pointerEventsNone,classNames.z2),children:[jsx15(NowIndicatorLineContainer,{className:joinClassNames(classNames.fillX,classNames.noMarginX,classNames.borderlessX),style:{top},date:props.nowDate}),(props.showDot??!0)&&jsx15(NowIndicatorDot,{className:joinClassNames(classNames.abs,classNames.start0),style:{top}})]})}var TimeGridCol=class extends BaseComponent{constructor(){super(...arguments),this.sortEventSegs=memoize2(sortEventSegs),this.getDateMeta=memoize2(getDateMeta)}render(){let{props,context}=this,{options,dateEnv}=context,isSelectMirror=options.selectMirror,mirrorSegs=props.eventDrag&&props.eventDrag.segs||props.eventResize&&props.eventResize.segs||isSelectMirror&&props.dateSelectionSegs||[],dateMeta=this.getDateMeta(props.date,dateEnv,props.dateProfile,props.todayRange),baseClassName=joinClassNames(classNames.borderlessY,classNames.borderlessEnd,!props.borderStart&&classNames.borderlessStart,props.width==null&&classNames.liquid,classNames.rel,classNames.z1),baseStyle={width:props.width},isStack=this.getIsStack(),renderProps={...dateMeta,...props.renderProps,isStack,isNarrow:props.isNarrow,isMajor:props.isMajor,view:context.viewApi};if(dateMeta.isDisabled)return jsx15("div",{role:"gridcell","aria-disabled":!0,className:joinClassNames(generateClassName(options.dayLaneClass,renderProps),baseClassName),style:baseStyle});let innerClassName=joinClassNames(generateClassName(options.dayLaneInnerClass,renderProps),!isStack&&classNames.fill,classNames.z1),sortedFgSegs=this.sortEventSegs(props.fgEventSegs,options.eventOrder);return jsx15(ContentContainer,{tag:"div",attrs:{...props.attrs,role:"gridcell",...dateMeta.isToday?{"aria-current":"date"}:{},"data-date":formatDayString(props.date)},className:baseClassName,style:baseStyle,renderProps,generatorName:void 0,classNameGenerator:options.dayLaneClass,didMount:options.dayLaneDidMount,willUnmount:options.dayLaneWillUnmount,children:()=>jsxs11(Fragment8,{children:[this.renderFillSegs(props.businessHourSegs,"non-business"),this.renderFillSegs(props.bgEventSegs,"bg-event"),this.renderFillSegs(props.dateSelectionSegs,"highlight"),jsx15("div",{className:innerClassName,children:this.renderFgSegs(sortedFgSegs,!1)}),!!mirrorSegs.length&&jsx15("div",{className:innerClassName,children:this.renderFgSegs(mirrorSegs,!0)}),this.renderNowIndicator(props.nowIndicatorSegs)]})})}renderFgSegs(sortedFgSegs,isMirror){let{props}=this;return this.getIsStack()?renderPlainFgSegs(sortedFgSegs,props,isMirror):isMirror?this.renderPositionedMirrorSegs(sortedFgSegs):this.renderPositionedFgSegs(sortedFgSegs)}renderPositionedFgSegs(segs){let{eventMaxStack,eventOrderStrict}=this.context.options,segVerticals=this.computeSegVerticals(segs),{placements,hiddenGroups}=buildTimeGridSegPlacements(segs,segVerticals,eventOrderStrict,eventMaxStack);return jsxs11(Fragment8,{children:[placements.map(placement=>this.renderPositionedSeg(placement.seg,placement.segVertical,this.computeSegHStyle(placement),placement.stackDepth,!1)),this.renderHiddenGroups(hiddenGroups)]})}renderPositionedMirrorSegs(segs){let segVerticals=this.computeSegVerticals(segs);return segs.map((seg,index2)=>this.renderPositionedSeg(seg,segVerticals[index2]||{},{left:0,right:0,zIndex:0},0,!0))}renderPositionedSeg(seg,segVertical,hStyle,level,isMirror){let{props}=this,{eventRange}=seg,{instanceId}=eventRange.instance,isSelected=instanceId===props.eventSelection;isSelected&&(hStyle.zIndex+=1e3);let isDragging=!!(props.eventDrag&&props.eventDrag.affectedInstances[instanceId]),isResizing=!!(props.eventResize&&props.eventResize.affectedInstances[instanceId]),isInvisible=!isMirror&&(isDragging||isResizing);return jsx15("div",{className:joinClassNames(classNames.abs,classNames.flexCol),style:{visibility:isInvisible?"hidden":void 0,top:segVertical.start,height:segVertical.size,...hStyle},children:jsx15(TimeGridEvent,{eventRange,slicedStart:seg.startDate,slicedEnd:seg.endDate,isStart:seg.isStart,isEnd:seg.isEnd,isDragging,isResizing,isMirror,isSelected,level,isNarrow:props.isNarrow,isShort:segVertical.isShort||!1,isLiquid:!0,...getEventRangeMeta(eventRange,props.todayRange,props.nowDate,props.nowMs)})},instanceId)}computeSegVerticals(segs){let{props,context}=this,isMeasured=props.slatHeight!=null;return computeFgSegVerticals(segs,props.dateProfile,props.date,props.slatCnt,props.slatHeight??ESTIMATED_SLAT_HEIGHT,isMeasured?context.options.eventMinHeight:void 0,context.options.eventShortHeight)}renderHiddenGroups(hiddenGroups){let{dateSpanProps,dateProfile,todayRange,nowDate,nowMs,eventSelection,eventDrag,eventResize,isNarrow,isMicro}=this.props;return jsx15(Fragment8,{children:hiddenGroups.map(hiddenGroup=>jsx15(TimeGridMoreLink,{hiddenSegs:hiddenGroup.segs,top:hiddenGroup.start,height:hiddenGroup.end-hiddenGroup.start,isNarrow,isMicro,dateSpanProps,dateProfile,todayRange,nowDate,nowMs,eventSelection,eventDrag,eventResize},hiddenGroup.key))})}renderFillSegs(segs,fillType){let{props,context}=this,segVerticals=this.computeSegVerticals(segs);return jsx15(Fragment8,{children:segs.map((seg,index2)=>{let{eventRange}=seg,segVertical=segVerticals[index2]||{};return jsx15("div",{className:classNames.fillX,style:{top:segVertical.start,height:segVertical.size,marginInlineStart:-1},children:fillType==="bg-event"?jsx15(BgEvent,{eventRange,isStart:seg.isStart,isEnd:seg.isEnd,isNarrow:props.isNarrow,isShort:segVertical.isShort||!1,isVertical:!0,...getEventRangeMeta(eventRange,props.todayRange,props.nowDate,props.nowMs)}):renderFill(fillType,context.options)},buildEventRangeKey(eventRange))})})}renderNowIndicator(segs){let{props}=this;if(!(props.forPrint||this.getIsStack()))return segs.map((seg,i)=>jsx15(TimeGridNowIndicatorLine,{nowDate:seg.startDate,dayDate:props.date,dateProfile:props.dateProfile,totalHeight:props.slatHeight!=null?props.slatHeight*props.slatCnt:void 0,showDot:seg.showDot??!0},i))}computeSegHStyle(segRect){let{options}=this.context,shouldOverlap=options.slotEventOverlap,nearCoord=segRect.levelCoord,farCoord=segRect.levelCoord+segRect.thickness;shouldOverlap&&(farCoord=Math.min(1,nearCoord+(farCoord-nearCoord)*2));let props={zIndex:segRect.stackDepth+1,insetInlineStart:fracToCssDim(nearCoord),insetInlineEnd:fracToCssDim(1-farCoord),marginInlineEnd:void 0};return shouldOverlap&&segRect.stackForward&&(props.marginInlineEnd=20),props}getIsStack(){let{eventPrintLayout}=this.context.options;return computeTimeGridPrintMode(this.props.forPrint,eventPrintLayout)==="stack"}};function renderPlainFgSegs(sortedFgSegs,{todayRange,nowDate,nowMs,eventSelection,eventDrag,eventResize},isMirror){return jsx15(Fragment8,{children:sortedFgSegs.map(seg=>{let{eventRange}=seg,{instanceId}=eventRange.instance,isDragging=!!(eventDrag&&eventDrag.affectedInstances[instanceId]),isResizing=!!(eventResize&&eventResize.affectedInstances[instanceId]),isInvisible=isDragging||isResizing;return jsx15("div",{className:classNames.breakInsideAvoid,style:{visibility:isInvisible?"hidden":void 0},children:jsx15(TimeGridEvent,{eventRange,slicedStart:seg.startDate,slicedEnd:seg.endDate,isStart:seg.isStart,isEnd:seg.isEnd,isDragging,isResizing,isMirror,isSelected:instanceId===eventSelection,level:0,isShort:!1,isNarrow:!1,disableResizing:!0,...getEventRangeMeta(eventRange,todayRange,nowDate,nowMs)})},instanceId)})})}var TimeGridCols=class extends DateComponent{constructor(){super(...arguments),this.processSlotOptions=memoize2(processSlotOptions),this.handleRootEl=el=>{this.rootEl=el,el?this.context.registerInteractiveComponent(this,{el,isHitComboAllowed:this.props.isHitComboAllowed}):this.context.unregisterInteractiveComponent(this)}}render(){let{props}=this;return jsx15("div",{role:props.role,className:joinClassNames(props.className,classNames.flexRow),ref:this.handleRootEl,children:props.cells.map((cell,col)=>jsx15(TimeGridCol,{dateProfile:props.dateProfile,nowDate:props.nowDate,nowMs:props.nowMs,todayRange:props.todayRange,date:cell.date,isMajor:cell.isMajor,slatCnt:props.slatCnt,renderProps:cell.renderProps,attrs:cell.attrs,dateSpanProps:cell.dateSpanProps,forPrint:props.forPrint,borderStart:!!col,isNarrow:props.cellIsNarrow,isMicro:props.cellIsMicro,fgEventSegs:props.fgEventSegsByCol[col],bgEventSegs:props.bgEventSegsByCol[col],businessHourSegs:props.businessHourSegsByCol[col],nowIndicatorSegs:props.nowIndicatorSegsByCol[col],dateSelectionSegs:props.dateSelectionSegsByCol[col],eventDrag:props.eventDragByCol[col],eventResize:props.eventResizeByCol[col],eventSelection:props.eventSelection,width:props.colWidth,slatHeight:props.slatHeight},cell.key))})}queryHit(isRtl,positionLeft,positionTop,elWidth){let{dateProfile,cells,colWidth,slatHeight}=this.props,{dateEnv,options}=this.context,{snapDuration,snapsPerSlot}=this.processSlotOptions(options.slotDuration,options.snapDuration),colCount=cells.length,{col,left,right}=computeColFromPosition(positionLeft,elWidth,colWidth,colCount,isRtl),cell=cells[col],slatIndex=Math.floor(positionTop/slatHeight),slatTop=slatIndex*slatHeight,partial=(positionTop-slatTop)/slatHeight,localSnapIndex=Math.floor(partial*snapsPerSlot),snapIndex=slatIndex*snapsPerSlot+localSnapIndex,time=addDurations(dateProfile.slotMinTime,multiplyDuration(snapDuration,snapIndex)),start=dateEnv.add(cell.date,time),end=dateEnv.add(start,snapDuration);return{dateProfile,dateSpan:{range:{start,end},allDay:!1,...cell.dateSpanProps},getDayEl:()=>getCellEl(this.rootEl,col),rect:{left,right,top:slatTop,bottom:slatTop+slatHeight},layer:0}}};TimeGridCols.addPropsEquality({style:isPropsEqualShallow});function processSlotOptions(slotDuration,snapDurationOverride){let snapDuration=snapDurationOverride||slotDuration,snapsPerSlot=wholeDivideDurations(slotDuration,snapDuration);return snapsPerSlot===null&&(snapDuration=slotDuration,snapsPerSlot=1),{snapDuration,snapsPerSlot}}var NowIndicatorHeaderContainer=props=>jsx15(ViewContextType.Consumer,{children:context=>{let{options}=context,renderProps={date:context.dateEnv.toDate(props.date),view:context.viewApi};return jsx15(ContentContainer,{elRef:props.elRef,tag:props.tag||"div",attrs:props.attrs,className:props.className,style:props.style,renderProps,generatorName:"nowIndicatorHeaderContent",customGenerator:options.nowIndicatorHeaderContent,classNameGenerator:options.nowIndicatorHeaderClass,didMount:options.nowIndicatorHeaderDidMount,willUnmount:options.nowIndicatorHeaderWillUnmount,children:props.children})}});function TimeGridNowIndicatorArrow(props){return jsx15("div",{className:joinClassNames(classNames.fill,classNames.crop,classNames.pointerEventsNone,classNames.z2),children:jsx15(NowIndicatorHeaderContainer,{className:classNames.abs,style:{top:props.totalHeight!=null?props.totalHeight*computeDateTopFrac(props.nowDate,props.dateProfile):void 0},date:props.nowDate})})}var DEFAULT_SLAT_LABEL_FORMAT=createFormatter({hour:"numeric",minute:"2-digit",omitZeroMinute:!0,meridiem:"short"}),TimeGridSlatHeader=class extends BaseComponent{constructor(){super(...arguments),this.createRenderProps=memoize2(createRenderProps),this.innerElRef=createRef3()}render(){let{props,context}=this,{options}=context,headerFormat=options.slotHeaderFormat==null?DEFAULT_SLAT_LABEL_FORMAT:Array.isArray(options.slotHeaderFormat)?createFormatter(options.slotHeaderFormat[0]):createFormatter(options.slotHeaderFormat),renderProps=this.createRenderProps(props.date,props.time,!props.isLabeled,props.isNarrow,props.isFirst,headerFormat,context),className=joinClassNames(props.liquidHeight&&classNames.liquid,classNames.flexRow,classNames.alignStart,classNames.noMargin,classNames.noPadding,classNames.borderlessX,classNames.borderlessBottom,!props.borderTop&&classNames.borderlessTop);return props.isLabeled?jsx15(ContentContainer,{tag:"div",attrs:{"data-time":props.isoTimeStr},style:{height:props.height},className,renderProps,generatorName:"slotHeaderContent",customGenerator:options.slotHeaderContent,defaultGenerator:renderInnerContent3,classNameGenerator:options.slotHeaderClass,didMount:options.slotHeaderDidMount,willUnmount:options.slotHeaderWillUnmount,children:InnerContent=>jsx15("div",{ref:this.innerElRef,className:joinClassNames(classNames.noShrink,classNames.whiteSpaceNoWrap,classNames.flexRow),children:jsx15(InnerContent,{tag:"div",className:generateClassName(options.slotHeaderInnerClass,renderProps)})})}):jsx15("div",{className:joinClassNames(generateClassName(options.slotHeaderClass,renderProps),className),style:{height:props.height}})}componentDidMount(){this._isUnmounting=!1;let{props}=this,innerEl=this.innerElRef.current;innerEl&&(this.disconnectInnerSize=watchSize(innerEl,(width,height)=>{this._isUnmounting||(setRef(props.innerWidthRef,width),setRef(props.innerHeightRef,height))}))}componentWillUnmount(){let{props}=this;this._isUnmounting=!0,this.disconnectInnerSize&&(this.disconnectInnerSize(),setRef(props.innerWidthRef,null),setRef(props.innerHeightRef,null))}};function createRenderProps(date,time,isMinor,isNarrow,isFirst,headerFormat,context){return{...getDateMeta(date,context.dateEnv),level:0,text:joinDateTimeFormatParts(context.dateEnv.formatToParts(date,headerFormat)),time,isMajor:!1,isMinor,isTime:!0,isNarrow,hasNavLink:!1,isFirst,view:context.viewApi}}function renderInnerContent3(props){return props.text}var TimeGridSlatLane=class extends BaseComponent{constructor(){super(...arguments),this.getDateMeta=memoize2(getDateMeta)}render(){let{props,context}=this,{options}=context,renderProps={...this.getDateMeta(props.date,context.dateEnv),time:props.time,isMajor:!1,isMinor:!props.isLabeled,view:context.viewApi};return jsx15(ContentContainer,{tag:"div",attrs:{"data-time":props.isoTimeStr},className:joinClassNames(classNames.noMargin,classNames.noPadding,classNames.liquid,classNames.borderlessX,classNames.borderlessBottom,!props.borderTop&&classNames.borderlessTop),renderProps,generatorName:void 0,classNameGenerator:options.slotLaneClass,didMount:options.slotLaneDidMount,willUnmount:options.slotLaneWillUnmount})}},DEFAULT_WEEK_NUM_FORMAT2=createFormatter({week:"short"}),TimeGridWeekNumber=class extends BaseComponent{constructor(){super(...arguments),this.innerElRef=createRef3()}render(){let{props,context}=this,{options,dateEnv}=context,range=props.dateProfile.renderRange,hasNavLink=diffDays4(range.start,range.end)===1&&options.navLinks,weekDateMarker=range.start,fullDateStr=buildDateStr(context,weekDateMarker,"week"),weekNum=dateEnv.computeWeekNumber(weekDateMarker),weekTextParts=dateEnv.formatToParts(weekDateMarker,options.weekNumberFormat||DEFAULT_WEEK_NUM_FORMAT2),weekText=joinDateTimeFormatParts(weekTextParts),weekDateZoned=dateEnv.toDate(weekDateMarker),weekNumberRenderProps={num:weekNum,text:weekText,textParts:weekTextParts,date:weekDateZoned,isNarrow:props.isNarrow,hasNavLink,options:{dayMinWidth:options.dayMinWidth}};return jsx15(ContentContainer,{tag:"div",attrs:{role:"gridcell","aria-label":fullDateStr},className:joinClassNames(classNames.flexRow,classNames.noMargin,classNames.noPadding,props.isLiquid?classNames.liquid:classNames.contentBox),style:{width:props.width},renderProps:weekNumberRenderProps,generatorName:"weekNumberHeaderContent",customGenerator:options.weekNumberHeaderContent,defaultGenerator:renderText,classNameGenerator:options.weekNumberHeaderClass,didMount:options.weekNumberHeaderDidMount,willUnmount:options.weekNumberHeaderWillUnmount,children:InnerContent=>jsx15("div",{ref:this.innerElRef,className:joinClassNames(classNames.flexRow,classNames.noShrink,classNames.whiteSpaceNoWrap),children:jsx15(InnerContent,{tag:"div",attrs:hasNavLink?buildNavLinkAttrs(context,range.start,"week",fullDateStr):{"aria-label":fullDateStr},className:generateClassName(options.weekNumberHeaderInnerClass,weekNumberRenderProps)})})})}componentDidMount(){this._isUnmounting=!1;let{props}=this,innerEl=this.innerElRef.current;this.disconnectInnerSize=watchSize(innerEl,(width,height)=>{this._isUnmounting||(setRef(props.innerWidthRef,width),setRef(props.innerHeightRef,height))})}componentWillUnmount(){let{props}=this;this._isUnmounting=!0,this.disconnectInnerSize(),setRef(props.innerWidthRef,null),setRef(props.innerHeightRef,null)}};function TimeGridAxisEmpty(props){return jsx15("div",{role:"gridcell",className:props.isLiquid?classNames.liquid:classNames.contentBox,style:{width:props.width}})}var TimeGridLayoutPannable=class extends BaseComponent{constructor(){super(...arguments),this.state={headerTierHeights:[]},this.headerLabelInnerWidthRefMap=new RefMap(()=>{afterSize(this.handleAxisWidths)}),this.headerLabelInnerHeightRefMap=new RefMap(()=>{afterSize(this.handleHeaderHeights)}),this.headerMainInnerHeightRefMap=new RefMap(()=>{afterSize(this.handleHeaderHeights)}),this.handleAllDayLabelInnerWidth=width=>{this.allDayLabelInnerWidth=width,afterSize(this.handleAxisWidths)},this.slatLabelInnerWidthRefMap=new RefMap(()=>{afterSize(this.handleAxisWidths)}),this.slatLabelInnerHeightRefMap=new RefMap(()=>{afterSize(this.handleSlatInnerHeights)}),this.headerScrollerRef=createRef3(),this.allDayScrollerRef=createRef3(),this.mainScrollerRef=createRef3(),this.footScrollerRef=createRef3(),this.axisScrollerRef=createRef3(),this.handleTotalWidth=totalWidth=>{this._isUnmounting||this.setState({totalWidth})},this.handleBodyHeight=bodyHeight=>{this._isUnmounting||this.setState({bodyHeight})},this.handleClientWidth=clientWidth=>{this._isUnmounting||this.setState({clientWidth})},this.handleClientHeight=clientHeight=>{this._isUnmounting||this.setState({clientHeight})},this.handleStickyBottomScrollbarWidth=sticykBottomScrollbarWidth=>{this._isUnmounting||this.setState({sticykBottomScrollbarWidth})},this.handleHeaderHeights=()=>{if(this._isUnmounting)return;let headerLabelInnerHeightMap=this.headerLabelInnerHeightRefMap.current,headerMainInnerHeightMap=this.headerMainInnerHeightRefMap.current,heights=[];for(let[tierNum,mainHeight]of headerMainInnerHeightMap.entries())heights[tierNum]=Math.max(headerLabelInnerHeightMap.get(tierNum)||0,mainHeight);this.setState({headerTierHeights:heights})},this.handleSlatInnerHeights=()=>{if(this._isUnmounting)return;let slatLabelInnerHeightMap=this.slatLabelInnerHeightRefMap.current,max=0;for(let slatLabelInnerHeight of slatLabelInnerHeightMap.values())max=Math.max(max,slatLabelInnerHeight);this.state.slatInnerHeight!==max&&this.setState({slatInnerHeight:max})},this.handleAxisWidths=()=>{if(this._isUnmounting)return;let headerLabelInnerWidthMap=this.headerLabelInnerWidthRefMap.current,slatLabelInnerWidthMap=this.slatLabelInnerWidthRefMap.current,max=this.allDayLabelInnerWidth||0;for(let headerLabelInnerWidth of headerLabelInnerWidthMap.values())max=Math.max(max,headerLabelInnerWidth);for(let slatLableInnerWidth of slatLabelInnerWidthMap.values())max=Math.max(max,slatLableInnerWidth);this.state.axisWidth!==max&&this.setState({axisWidth:max})}}render(){let{props,state,context,headerLabelInnerWidthRefMap,headerLabelInnerHeightRefMap,headerMainInnerHeightRefMap,slatLabelInnerWidthRefMap,slatLabelInnerHeightRefMap}=this,{nowDate,headerTiers,forPrint}=props,nowTimeMs=nowDate.valueOf()-startOfDay5(nowDate).valueOf(),{axisWidth,totalWidth,clientWidth,clientHeight,bodyHeight,sticykBottomScrollbarWidth}=state,{options}=context,{borderlessX,borderlessTop,borderlessBottom}=computeViewBorderless(options),endScrollbarWidth=totalWidth!=null&&clientWidth!=null&&axisWidth!=null?totalWidth-clientWidth-(axisWidth+1):void 0,verticalScrolling=!forPrint&&!getIsHeightAuto(options),tableHeaderSticky=!forPrint&&getTableHeaderSticky(options),footerScrollbarSticky=!forPrint&&getFooterScrollbarSticky(options),printStackEnabled=computeTimeGridPrintMode(forPrint,options.eventPrintLayout)==="stack",absPrint=forPrint&&!printStackEnabled,simplePrint=forPrint&&printStackEnabled,colCount=props.cells.length,[canvasWidth,appliedColWidth]=computeColWidth(colCount,props.dayMinWidth,clientWidth),measuredColWidth=appliedColWidth??(clientWidth!=null?clientWidth/colCount:void 0),cellIsMicro=measuredColWidth!=null&&measuredColWidth<=dayMicroWidth,cellIsNarrow=cellIsMicro||measuredColWidth!=null&&measuredColWidth<=options.dayNarrowWidth,slatCnt=props.slatMetas.length,[slatHeight,slatLiquidHeight]=computeSlatHeight(verticalScrolling&&options.expandRows,slatCnt,options.slotMinHeight,state.slatInnerHeight,clientHeight);this.slatHeight=slatHeight;let totalSlatHeight=(slatHeight||0)*slatCnt,forcedBodyHeight=absPrint?totalSlatHeight:void 0,rowsNotExpanding=verticalScrolling&&!options.expandRows&&clientHeight!=null&&clientHeight>totalSlatHeight,firstBodyRowIndex=options.dayHeaders?headerTiers.length+1:1,bottomScrollbarWidth=footerScrollbarSticky?sticykBottomScrollbarWidth:bodyHeight!=null&&clientHeight!=null?bodyHeight-clientHeight:void 0;return jsxs11(Fragment8,{children:[options.dayHeaders&&jsxs11("div",{className:joinClassNames(generateClassName(options.tableHeaderClass,{isSticky:tableHeaderSticky,borderlessX,borderlessTop,borderlessBottom,multiMonthColumns:0}),classNames.flexCol,tableHeaderSticky&&classNames.tableHeaderSticky,classNames.z1),children:[jsxs11("div",{className:classNames.flexRow,children:[jsx15("div",{role:"rowgroup",className:classNames.contentBox,style:{width:axisWidth},children:headerTiers.map((rowConfig,tierNum)=>jsx15("div",{role:"row","aria-rowindex":tierNum+1,className:joinClassNames(options.dayHeaderRowClass,classNames.flexRow,classNames.contentBox,classNames.borderlessX,classNames.borderlessTop,tierNum===props.headerTiers.length-1&&classNames.borderlessBottom),style:{height:state.headerTierHeights[tierNum]},children:options.weekNumbers&&rowConfig.isDateRow?jsx15(TimeGridWeekNumber,{dateProfile:props.dateProfile,innerWidthRef:headerLabelInnerWidthRefMap.createRef(tierNum),innerHeightRef:headerLabelInnerHeightRefMap.createRef(tierNum),width:void 0,isLiquid:!0,isNarrow:cellIsNarrow}):jsx15(TimeGridAxisEmpty,{width:void 0,isLiquid:!0})},tierNum))}),jsx15("div",{className:generateClassName(options.slotHeaderDividerClass,{inTableHeader:!0,options:{dayMinWidth:options.dayMinWidth}})}),jsxs11(Scroller,{horizontal:!0,hideScrollbars:!0,className:joinClassNames(classNames.flexRow,classNames.liquid),ref:this.headerScrollerRef,children:[jsx15("div",{role:"rowgroup",className:canvasWidth==null?classNames.liquid:"",style:{width:canvasWidth},children:props.headerTiers.map((rowConfig,tierNum)=>createElement5(DayGridHeaderRow,{...rowConfig,key:tierNum,role:"row",rowIndex:tierNum,borderBottom:tierNum<props.headerTiers.length-1,height:state.headerTierHeights[tierNum],colWidth:appliedColWidth,viewportWidth:clientWidth,innerHeightRef:headerMainInnerHeightRefMap.createRef(tierNum),cellIsNarrow,cellIsMicro,rowLevel:props.headerTiers.length-tierNum-1}))}),!!endScrollbarWidth&&jsx15("div",{className:joinClassNames(generateClassName(options.fillerClass,{inTableHeader:!0}),classNames.borderlessY,classNames.borderlessEnd),style:{minWidth:endScrollbarWidth}})]})]}),jsx15("div",{className:generateClassName(options.dayHeaderDividerClass,{isSticky:tableHeaderSticky,multiMonthColumns:0,options:{allDaySlot:!!options.allDaySlot}})})]}),jsxs11("div",{role:"rowgroup",className:joinClassNames(generateClassName(options.tableBodyClass,{borderlessX,borderlessTop,borderlessBottom,multiMonthColumns:0}),classNames.flexCol,verticalScrolling&&classNames.liquid,classNames.isolate,classNames.z0),children:[options.allDaySlot&&jsxs11(Fragment8,{children:[jsxs11("div",{role:"row","aria-rowindex":firstBodyRowIndex,className:joinClassNames(classNames.flexRow,classNames.z1),children:[jsx15(TimeGridAllDayHeader,{width:axisWidth,innerWidthRef:this.handleAllDayLabelInnerWidth,isNarrow:cellIsNarrow}),jsx15("div",{className:generateClassName(options.slotHeaderDividerClass,{inTableHeader:!1,options:{dayMinWidth:options.dayMinWidth}})}),jsxs11(Scroller,{horizontal:!0,hideScrollbars:!0,className:joinClassNames(classNames.flexRow,classNames.liquidX),ref:this.allDayScrollerRef,children:[jsx15("div",{className:classNames.flexRow,style:{width:canvasWidth},children:jsx15(TimeGridAllDayLane,{dateProfile:props.dateProfile,todayRange:props.todayRange,cells:props.cells,showDayNumbers:!1,forPrint,isHitComboAllowed:props.isHitComboAllowed,className:joinClassNames(classNames.borderless,classNames.liquidX),cellIsNarrow,cellIsMicro,fgEventSegs:props.fgEventSegs,bgEventSegs:props.bgEventSegs,businessHourSegs:props.businessHourSegs,dateSelectionSegs:props.dateSelectionSegs,eventSelection:props.eventSelection,eventDrag:props.eventDrag,eventResize:props.eventResize,dayMaxEvents:props.dayMaxEvents,dayMaxEventRows:props.dayMaxEventRows,colWidth:appliedColWidth})}),!!endScrollbarWidth&&jsx15("div",{className:joinClassNames(generateClassName(options.fillerClass,{inTableHeader:!1}),classNames.borderlessY,classNames.borderlessEnd),style:{minWidth:endScrollbarWidth}})]})]}),jsx15("div",{className:joinClassNames(options.allDayDividerClass,classNames.z2)})]}),jsxs11("div",{role:"row","aria-rowindex":firstBodyRowIndex+(options.allDaySlot?1:0),className:joinClassNames(classNames.flexRow,classNames.rel,verticalScrolling&&classNames.liquid,classNames.z0),children:[jsx15(Scroller,{vertical:verticalScrolling,hideScrollbars:!0,className:joinClassNames(classNames.flexCol,classNames.contentBox),style:{width:axisWidth},ref:this.axisScrollerRef,clientHeightRef:this.handleBodyHeight,children:!simplePrint&&jsx15(Fragment8,{children:jsxs11("div",{role:"rowheader","aria-label":options.timedText,className:joinClassNames(classNames.flexCol,classNames.grow,classNames.rel),style:{height:forcedBodyHeight},children:[jsx15("div",{"aria-hidden":!0,className:joinClassNames(classNames.flexCol,verticalScrolling&&options.expandRows&&classNames.grow,absPrint&&classNames.fillX),children:props.slatMetas.map((slatMeta,slatI)=>createElement5(TimeGridSlatHeader,{...slatMeta,key:slatMeta.key,innerWidthRef:slatLabelInnerWidthRefMap.createRef(slatMeta.key),innerHeightRef:slatLabelInnerHeightRefMap.createRef(slatMeta.key),borderTop:!!slatI,isNarrow:cellIsNarrow,height:slatLiquidHeight?void 0:slatHeight,liquidHeight:slatLiquidHeight}))}),!forPrint&&options.nowIndicator&&rangeContainsMarker(props.dateProfile.currentRange,nowDate)&&nowTimeMs>=props.dateProfile.slotMinTime.milliseconds&&nowTimeMs<props.dateProfile.slotMaxTime.milliseconds&&jsx15(TimeGridNowIndicatorArrow,{nowDate,dateProfile:props.dateProfile,totalHeight:slatHeight!=null?slatHeight*slatCnt:void 0}),!!(rowsNotExpanding||bottomScrollbarWidth)&&jsx15("div",{className:joinClassNames(generateClassName(options.fillerClass,{inTableHeader:!1}),classNames.borderlessX,classNames.borderlessBottom,rowsNotExpanding&&classNames.liquid),style:{minHeight:bottomScrollbarWidth}})]})})}),jsx15("div",{className:generateClassName(options.slotHeaderDividerClass,{inTableHeader:!1,options:{dayMinWidth:options.dayMinWidth}})}),jsxs11("div",{className:joinClassNames(classNames.flexCol,classNames.liquid),children:[jsx15(Scroller,{vertical:verticalScrolling,horizontal:!0,hideScrollbars:footerScrollbarSticky||forPrint,className:joinClassNames(classNames.flexCol,classNames.rel,verticalScrolling&&classNames.liquid),ref:this.mainScrollerRef,clientWidthRef:this.handleClientWidth,clientHeightRef:this.handleClientHeight,children:jsxs11("div",{className:joinClassNames(classNames.flexCol,classNames.grow,classNames.rel),style:{width:canvasWidth,height:forcedBodyHeight},children:[jsx15(TimeGridCols,{dateProfile:props.dateProfile,nowDate:props.nowDate,nowMs:props.nowMs,todayRange:props.todayRange,cells:props.cells,slatCnt,forPrint,isHitComboAllowed:props.isHitComboAllowed,className:simplePrint?"":classNames.fill,fgEventSegsByCol:props.fgEventSegsByCol,bgEventSegsByCol:props.bgEventSegsByCol,businessHourSegsByCol:props.businessHourSegsByCol,nowIndicatorSegsByCol:props.nowIndicatorSegsByCol,dateSelectionSegsByCol:props.dateSelectionSegsByCol,eventDragByCol:props.eventDragByCol,eventResizeByCol:props.eventResizeByCol,eventSelection:props.eventSelection,colWidth:appliedColWidth,slatHeight,cellIsNarrow,cellIsMicro}),!simplePrint&&jsxs11(Fragment8,{children:[jsx15("div",{"aria-hidden":!0,className:joinClassNames(classNames.flexCol,verticalScrolling&&options.expandRows&&classNames.grow,absPrint?classNames.fillX:classNames.rel),children:props.slatMetas.map((slatMeta,slatI)=>jsx15("div",{className:joinClassNames(classNames.flexRow,slatLiquidHeight&&classNames.liquid),style:{height:slatLiquidHeight?"":slatHeight},children:createElement5(TimeGridSlatLane,{...slatMeta,key:slatMeta.key,borderTop:!!slatI})},slatMeta.key))}),rowsNotExpanding&&jsx15("div",{className:joinClassNames(generateClassName(options.fillerClass,{inTableHeader:!1}),classNames.borderlessX,classNames.borderlessBottom,classNames.liquid)})]})]})}),!!footerScrollbarSticky&&jsx15(FooterScrollbar,{isSticky:!0,canvasWidth,scrollerRef:this.footScrollerRef,scrollbarWidthRef:this.handleStickyBottomScrollbarWidth})]})]})]}),jsx15(Ruler,{widthRef:this.handleTotalWidth})]})}componentDidMount(){this._isUnmounting=!1,this.initScrollers(),this.updateSlatHeight()}componentDidUpdate(){this.updateScrollers(),this.updateSlatHeight()}componentWillUnmount(){this._isUnmounting=!0,this.destroyScrollers(),this.prevSlatHeight=void 0,setRef(this.props.slatHeightRef,null)}updateSlatHeight(){this.prevSlatHeight!==this.slatHeight&&setRef(this.props.slatHeightRef,this.prevSlatHeight=this.slatHeight)}initScrollers(){let ScrollerSyncer=getScrollerSyncerClass(this.context.pluginHooks);this.dayScroller=new ScrollerSyncer(!0),this.timeScroller=new ScrollerSyncer,setRef(this.props.dayScrollerRef,this.dayScroller),setRef(this.props.timeScrollerRef,this.timeScroller),this.updateScrollers()}updateScrollers(){this.dayScroller.handleChildren([this.headerScrollerRef.current,this.allDayScrollerRef.current,this.mainScrollerRef.current,this.footScrollerRef.current]),this.timeScroller.handleChildren([this.axisScrollerRef.current,this.mainScrollerRef.current])}destroyScrollers(){setRef(this.props.dayScrollerRef,null),setRef(this.props.timeScrollerRef,null)}};TimeGridLayoutPannable.addPropsEquality({headerTierHeights:isArraysEqual});var TimeGridLayoutNormal=class extends BaseComponent{constructor(){super(...arguments),this.state={},this.headerLabelInnerWidthRefMap=new RefMap(()=>{afterSize(this.handleAxisInnerWidths)}),this.handleAllDayLabelInnerWidth=width=>{this.allDayLabelInnerWidth=width,afterSize(this.handleAxisInnerWidths)},this.handleWeekNumberInnerWidth=width=>{this.weekNumberInnerWidth=width,afterSize(this.handleAxisInnerWidths)},this.slatLabelInnerWidthRefMap=new RefMap(()=>{afterSize(this.handleAxisInnerWidths)}),this.slatLabelInnerHeightRefMap=new RefMap(()=>{afterSize(this.handleSlatInnerHeights)}),this.handleTotalWidth=totalWidth=>{this._isUnmounting||requestAnimationFrame(()=>{this._isUnmounting||this.setState({totalWidth})})},this.handleClientWidth=clientWidth=>{this._isUnmounting||this.setState({clientWidth})},this.handleClientHeight=clientHeight=>{this._isUnmounting||this.setState({clientHeight})},this.handleAxisInnerWidths=()=>{if(this._isUnmounting)return;let headerLabelInnerWidthMap=this.headerLabelInnerWidthRefMap.current,slatLabelInnerWidthMap=this.slatLabelInnerWidthRefMap.current,max=Math.max(this.weekNumberInnerWidth||0,this.allDayLabelInnerWidth||0);for(let headerLabelInnerWidth of headerLabelInnerWidthMap.values())max=Math.max(max,headerLabelInnerWidth);for(let slatLabelInnerWidth of slatLabelInnerWidthMap.values())max=Math.max(max,slatLabelInnerWidth);this.state.axisWidth!==max&&this.setState({axisWidth:max})},this.handleSlatInnerHeights=()=>{if(this._isUnmounting)return;let slatLabelInnerHeightMap=this.slatLabelInnerHeightRefMap.current,max=0;for(let slatLabelInnerHeight of slatLabelInnerHeightMap.values())max=Math.max(max,slatLabelInnerHeight);this.state.slatInnerHeight!==max&&this.setState({slatInnerHeight:max})}}render(){let{props,state,context,slatLabelInnerWidthRefMap,slatLabelInnerHeightRefMap,headerLabelInnerWidthRefMap}=this,{nowDate,forPrint}=props,nowTimeMs=nowDate.valueOf()-startOfDay5(nowDate).valueOf(),{axisWidth,clientWidth,totalWidth}=state,{options}=context,{borderlessX,borderlessTop,borderlessBottom}=computeViewBorderless(options),endScrollbarWidth=totalWidth!=null&&clientWidth!=null&&!forPrint?totalWidth-clientWidth:void 0,verticalScrolling=!forPrint&&!getIsHeightAuto(options),tableHeaderSticky=!forPrint&&getTableHeaderSticky(options),slatCnt=props.slatMetas.length,[slatHeight,slatLiquidHeight]=computeSlatHeight(verticalScrolling&&options.expandRows,slatCnt,options.slotMinHeight,state.slatInnerHeight,state.clientHeight);this.slatHeight=slatHeight;let totalSlatHeight=(slatHeight||0)*slatCnt,rowsNotExpanding=verticalScrolling&&!options.expandRows&&state.clientHeight!=null&&state.clientHeight>totalSlatHeight,printStackEnabled=computeTimeGridPrintMode(forPrint,options.eventPrintLayout)==="stack",absPrint=forPrint&&!printStackEnabled,simplePrint=forPrint&&printStackEnabled,forcedBodyHeight=absPrint?totalSlatHeight:void 0,colCount=props.cells.length,measuredColWidth=clientWidth!=null?clientWidth/colCount:void 0,cellIsMicro=measuredColWidth!=null&&measuredColWidth<=dayMicroWidth,cellIsNarrow=cellIsMicro||measuredColWidth!=null&&measuredColWidth<=options.dayNarrowWidth;return jsxs11(Fragment8,{children:[options.dayHeaders&&jsxs11("div",{role:"rowgroup",className:joinClassNames(generateClassName(options.tableHeaderClass,{isSticky:tableHeaderSticky,borderlessX,borderlessTop,borderlessBottom,multiMonthColumns:0}),classNames.flexCol,tableHeaderSticky&&classNames.tableHeaderSticky,classNames.z1),children:[props.headerTiers.map((rowConfig,tierNum)=>jsxs11("div",{role:"row",className:classNames.flexRow,children:[jsx15("div",{className:joinClassNames(options.dayHeaderRowClass,classNames.flexRow,classNames.borderlessX,classNames.borderlessTop,tierNum===props.headerTiers.length-1&&classNames.borderlessBottom),children:options.weekNumbers&&rowConfig.isDateRow?jsx15(TimeGridWeekNumber,{dateProfile:props.dateProfile,innerWidthRef:this.handleWeekNumberInnerWidth,innerHeightRef:headerLabelInnerWidthRefMap.createRef(tierNum),width:axisWidth,isLiquid:!1,isNarrow:cellIsNarrow}):jsx15(TimeGridAxisEmpty,{width:axisWidth,isLiquid:!1})}),jsx15("div",{className:generateClassName(options.slotHeaderDividerClass,{inTableHeader:!0,options:{dayMinWidth:options.dayMinWidth}})}),jsx15(DayGridHeaderRow,{...rowConfig,className:classNames.liquid,borderBottom:tierNum<props.headerTiers.length-1,viewportWidth:clientWidth,cellIsNarrow,cellIsMicro,rowLevel:props.headerTiers.length-tierNum-1}),!!endScrollbarWidth&&jsx15("div",{className:joinClassNames(generateClassName(options.fillerClass,{inTableHeader:!0}),classNames.borderlessY,classNames.borderlessEnd),style:{minWidth:endScrollbarWidth}})]},tierNum)),jsx15("div",{className:generateClassName(options.dayHeaderDividerClass,{isSticky:tableHeaderSticky,multiMonthColumns:0,options:{allDaySlot:!!options.allDaySlot}})})]}),jsxs11("div",{role:"rowgroup",className:joinClassNames(generateClassName(options.tableBodyClass,{borderlessX,borderlessTop,borderlessBottom,multiMonthColumns:0}),classNames.flexCol,verticalScrolling&&classNames.liquid,classNames.isolate,classNames.z0),children:[options.allDaySlot&&jsxs11(Fragment8,{children:[jsxs11("div",{role:"row",className:joinClassNames(classNames.flexRow,classNames.z1),children:[jsx15(TimeGridAllDayHeader,{width:axisWidth,innerWidthRef:this.handleAllDayLabelInnerWidth,isNarrow:cellIsNarrow}),jsx15("div",{className:generateClassName(options.slotHeaderDividerClass,{inTableHeader:!1,options:{dayMinWidth:options.dayMinWidth}})}),jsx15(TimeGridAllDayLane,{dateProfile:props.dateProfile,todayRange:props.todayRange,cells:props.cells,showDayNumbers:!1,forPrint,isHitComboAllowed:props.isHitComboAllowed,className:joinClassNames(classNames.liquidX,classNames.borderless),cellIsNarrow,cellIsMicro,fgEventSegs:props.fgEventSegs,bgEventSegs:props.bgEventSegs,businessHourSegs:props.businessHourSegs,dateSelectionSegs:props.dateSelectionSegs,eventDrag:props.eventDrag,eventResize:props.eventResize,eventSelection:props.eventSelection,dayMaxEvents:props.dayMaxEvents,dayMaxEventRows:props.dayMaxEventRows}),!!endScrollbarWidth&&jsx15("div",{className:joinClassNames(generateClassName(options.fillerClass,{inTableHeader:!1}),classNames.borderlessY,classNames.borderlessEnd),style:{minWidth:endScrollbarWidth}})]}),jsx15("div",{className:joinClassNames(options.allDayDividerClass,classNames.z2)})]}),jsx15(Scroller,{vertical:verticalScrolling,className:joinClassNames(classNames.flexCol,classNames.rel,verticalScrolling&&classNames.liquid,classNames.z0),ref:props.timeScrollerRef,clientWidthRef:this.handleClientWidth,clientHeightRef:this.handleClientHeight,children:jsxs11("div",{className:joinClassNames(classNames.flexCol,classNames.grow,classNames.rel),style:{height:forcedBodyHeight},children:[jsxs11("div",{role:"row",className:joinClassNames(classNames.flexRow,!simplePrint&&classNames.fill),children:[jsx15("div",{role:"rowheader","aria-label":options.timedText,className:classNames.contentBox,style:{width:axisWidth}}),jsx15("div",{className:generateClassName(options.slotHeaderDividerClass,{inTableHeader:!1,options:{dayMinWidth:options.dayMinWidth}})}),jsx15(TimeGridCols,{dateProfile:props.dateProfile,nowDate:props.nowDate,nowMs:props.nowMs,todayRange:props.todayRange,cells:props.cells,slatCnt,forPrint,isHitComboAllowed:props.isHitComboAllowed,className:classNames.liquid,fgEventSegsByCol:props.fgEventSegsByCol,bgEventSegsByCol:props.bgEventSegsByCol,businessHourSegsByCol:props.businessHourSegsByCol,nowIndicatorSegsByCol:props.nowIndicatorSegsByCol,dateSelectionSegsByCol:props.dateSelectionSegsByCol,eventDragByCol:props.eventDragByCol,eventResizeByCol:props.eventResizeByCol,eventSelection:props.eventSelection,slatHeight,cellIsNarrow,cellIsMicro})]}),!simplePrint&&jsxs11(Fragment8,{children:[jsx15("div",{"aria-hidden":!0,className:joinClassNames(classNames.flexCol,verticalScrolling&&options.expandRows&&classNames.grow,absPrint?classNames.fillX:classNames.rel),children:props.slatMetas.map((slatMeta,slatI)=>jsxs11("div",{className:joinClassNames(slatLiquidHeight&&classNames.liquid,classNames.flexRow),style:{height:slatLiquidHeight?void 0:slatHeight},children:[jsx15("div",{className:classNames.flexCol,style:{width:axisWidth},children:createElement5(TimeGridSlatHeader,{...slatMeta,key:slatMeta.key,innerWidthRef:slatLabelInnerWidthRefMap.createRef(slatMeta.key),innerHeightRef:slatLabelInnerHeightRefMap.createRef(slatMeta.key),borderTop:!!slatI,isNarrow:cellIsNarrow})}),jsx15("div",{className:generateClassName(options.slotHeaderDividerClass,{inTableHeader:!1,options:{dayMinWidth:options.dayMinWidth}}),style:{visibility:"hidden"}}),createElement5(TimeGridSlatLane,{...slatMeta,key:slatMeta.key,borderTop:!!slatI})]},slatMeta.key))}),rowsNotExpanding&&jsx15("div",{className:joinClassNames(generateClassName(options.fillerClass,{inTableHeader:!1}),classNames.borderlessX,classNames.borderlessBottom,classNames.liquid)}),!forPrint&&options.nowIndicator&&rangeContainsMarker(props.dateProfile.currentRange,nowDate)&&nowTimeMs>=props.dateProfile.slotMinTime.milliseconds&&nowTimeMs<props.dateProfile.slotMaxTime.milliseconds&&jsx15(TimeGridNowIndicatorArrow,{nowDate,dateProfile:props.dateProfile,totalHeight:slatHeight!=null?slatHeight*slatCnt:void 0})]})]})})]}),jsx15(Ruler,{widthRef:this.handleTotalWidth})]})}componentDidMount(){this._isUnmounting=!1,this.updateSlatHeight()}componentDidUpdate(){this.updateSlatHeight()}componentWillUnmount(){this._isUnmounting=!0,this.prevSlatHeight=void 0,setRef(this.props.slatHeightRef,null)}updateSlatHeight(){this.prevSlatHeight!==this.slatHeight&&setRef(this.props.slatHeightRef,this.prevSlatHeight=this.slatHeight)}};function buildEmptySegCols(segsByCol){return segsByCol.map(()=>[])}function buildEmptyInteractionCols(interactionsByCol){return interactionsByCol.map(()=>null)}var TimeGridLayout=class extends BaseComponent{constructor(){super(...arguments),this.buildSlatMetas=memoize2(buildSlatMetas),this.dayScrollerRef=createRef3(),this.timeScrollerRef=createRef3(),this.scrollState={},this.handleSlatHeight=slatHeight=>{this._isUnmounting||(this.slatHeight=slatHeight,slatHeight!=null&&afterSize(this.applyTimeScroll))},this.handleTimeScrollRequest=scrollTime=>{this.scrollState.time=scrollTime,this.scrollState.y=void 0,this.applyTimeScroll()},this.handleTimeScrollEnd=isDevice=>{if(isDevice){let y=this.timeScrollerRef.current.y;this.props.forPrint||(this.scrollState.y=y,this.scrollState.time=void 0)}},this.applyTimeScroll=()=>{let timeScroller=this.timeScrollerRef.current,{slatHeight,scrollState}=this,{y,time}=scrollState;y==null&&time&&slatHeight!=null&&timeScroller&&(y=computeTimeTopFrac(time,this.props.dateProfile)*(slatHeight*this.currentSlatCnt),y&&y++,scrollState.y=y),y!=null&&timeScroller.scrollTo({y})}}render(){let{props,context}=this,{dateProfile}=props,{options,dateEnv}=context,{dayMinWidth}=options,{borderlessX,borderlessTop,borderlessBottom}=computeViewBorderless(options),slatMetas=this.buildSlatMetas(dateProfile.slotMinTime,dateProfile.slotMaxTime,options.slotHeaderInterval,options.slotDuration,dateEnv);this.currentSlatCnt=slatMetas.length;let dateSelectionSegs=props.forPrint?[]:props.dateSelectionSegs,eventDrag=props.forPrint?null:props.eventDrag,eventResize=props.forPrint?null:props.eventResize,dateSelectionSegsByCol=props.forPrint?buildEmptySegCols(props.dateSelectionSegsByCol):props.dateSelectionSegsByCol,eventDragByCol=props.forPrint?buildEmptyInteractionCols(props.eventDragByCol):props.eventDragByCol,eventResizeByCol=props.forPrint?buildEmptyInteractionCols(props.eventResizeByCol):props.eventResizeByCol,commonLayoutProps={dateProfile,nowDate:props.nowDate,nowMs:props.nowMs,todayRange:props.todayRange,cells:props.cells,slatMetas,forPrint:props.forPrint,isHitComboAllowed:props.isHitComboAllowed,headerTiers:props.headerTiers,fgEventSegs:props.fgEventSegs,bgEventSegs:props.bgEventSegs,businessHourSegs:props.businessHourSegs,dateSelectionSegs,eventDrag,eventResize,...getAllDayMaxEventProps(options),fgEventSegsByCol:props.fgEventSegsByCol,bgEventSegsByCol:props.bgEventSegsByCol,businessHourSegsByCol:props.businessHourSegsByCol,nowIndicatorSegsByCol:props.nowIndicatorSegsByCol,dateSelectionSegsByCol,eventDragByCol,eventResizeByCol,eventSelection:props.eventSelection,timeScrollerRef:this.timeScrollerRef,timeScrollState:this.scrollState,slatHeightRef:this.handleSlatHeight,borderlessX,borderlessBottom};return jsx15(ViewContainer,{attrs:{role:"grid","aria-colcount":props.cells.length,"aria-labelledby":props.labelId,"aria-label":props.labelStr},className:joinClassNames(props.className,generateClassName(options.tableClass,{borderlessX,borderlessTop,borderlessBottom,multiMonthColumns:0}),!props.forPrint&&classNames.flexCol,classNames.isolate),viewSpec:context.viewSpec,children:dayMinWidth?jsx15(TimeGridLayoutPannable,{...commonLayoutProps,dayMinWidth,dayScrollerRef:this.dayScrollerRef}):jsx15(TimeGridLayoutNormal,{...commonLayoutProps})})}componentDidMount(){this._isUnmounting=!1,this.resetScroll(),this.context.emitter.on("_timeScrollRequest",this.handleTimeScrollRequest);let timeScroller=this.timeScrollerRef.current;timeScroller&&timeScroller.addScrollEndListener(this.handleTimeScrollEnd)}componentDidUpdate(prevProps){prevProps.dateProfile!==this.props.dateProfile&&this.context.options.scrollTimeReset?this.resetScroll():prevProps.forPrint&&!this.props.forPrint&&this.applyTimeScroll()}componentWillUnmount(){this._isUnmounting=!0,this.context.emitter.off("_timeScrollRequest",this.handleTimeScrollRequest);let timeScroller=this.timeScrollerRef.current;timeScroller&&timeScroller.removeScrollEndListener(this.handleTimeScrollEnd)}resetScroll(){this.handleTimeScrollRequest(this.context.options.scrollTime);let dayScroller=this.dayScrollerRef.current;dayScroller&&dayScroller.scrollTo({x:0})}},AUTO_ALL_DAY_MAX_EVENT_ROWS=5;function getAllDayMaxEventProps(options){let{dayMaxEvents,dayMaxEventRows}=options;return(dayMaxEvents===!0||dayMaxEventRows===!0)&&(dayMaxEvents=void 0,dayMaxEventRows=AUTO_ALL_DAY_MAX_EVENT_ROWS),{dayMaxEvents,dayMaxEventRows}}var TimeGridView=class extends DateComponent{constructor(){super(...arguments),this.createDayHeaderFormatter=memoize2(createDayHeaderFormatter),this.buildDaySeries=memoize2((dateProfile,dateProfileGenerator)=>new DaySeriesModel(dateProfile.renderRange,dateProfileGenerator)),this.buildDayCols=memoize2(buildDayColsFromSeries),this.extractColDates=memoize2(cols=>cols.map(col=>col.date)),this.extractColRanges=memoize2(cols=>cols.map(col=>col.range)),this.buildDateRowConfigs=memoize2(buildDateRowConfigs),this.splitFgEventSegs=memoize2(organizeSegsByCol),this.splitBgEventSegs=memoize2(organizeSegsByCol),this.splitBusinessHourSegs=memoize2(organizeSegsByCol),this.splitNowIndicatorSegs=memoize2(organizeSegsByCol),this.splitDateSelectionSegs=memoize2(organizeSegsByCol),this.splitEventDrag=memoize2(splitInteractionByCol),this.splitEventResize=memoize2(splitInteractionByCol),this.allDaySplitter=new AllDaySplitter,this.daySeriesSlicer=new DaySeriesSlicer,this.dayTimeColsSlicer=new DayTimeColsSlicer}render(){let{props,context}=this,{dateProfile}=props,{options,dateProfileGenerator}=context,daySeries=this.buildDaySeries(dateProfile,dateProfileGenerator),cols=this.buildDayCols(daySeries,context.dateEnv,{slotRange:dateProfile,activeRange:dateProfile.activeRange}),colDates=this.extractColDates(cols),dayRanges=this.extractColRanges(cols),splitProps=this.allDaySplitter.splitProps(props),allDayProps=this.daySeriesSlicer.sliceProps(splitProps.allDay,dateProfile,options.nextDayThreshold,context,daySeries),timedProps=this.dayTimeColsSlicer.sliceProps(splitProps.timed,dateProfile,null,context,dayRanges),dayHeaderFormat=this.createDayHeaderFormatter(context.options.dayHeaderFormat,!0,cols.length);return jsx16(NowTimer,{unit:options.nowIndicator?"minute":"day",children:(nowDate,todayRange,nowMs)=>{let colCount=cols.length,nowIndicatorSeg=!props.forPrint&&options.nowIndicator&&this.dayTimeColsSlicer.sliceNowDate(nowDate,dateProfile,options.nextDayThreshold,context,dayRanges),fgEventSegsByCol=this.splitFgEventSegs(timedProps.fgEventSegs,colCount),bgEventSegsByCol=this.splitBgEventSegs(timedProps.bgEventSegs,colCount),businessHourSegsByCol=this.splitBusinessHourSegs(timedProps.businessHourSegs,colCount),nowIndicatorSegsByCol=this.splitNowIndicatorSegs(nowIndicatorSeg,colCount),dateSelectionSegsByCol=this.splitDateSelectionSegs(timedProps.dateSelectionSegs,colCount),eventDragByCol=this.splitEventDrag(timedProps.eventDrag,colCount),eventResizeByCol=this.splitEventResize(timedProps.eventResize,colCount),headerTiers=this.buildDateRowConfigs(colDates,!0,props.dateProfile,todayRange,dayHeaderFormat,context);return jsx16(TimeGridLayout,{labelId:props.labelId,labelStr:props.labelStr,dateProfile,nowDate,nowMs,todayRange,cells:cols,forPrint:props.forPrint,className:props.className,headerTiers,fgEventSegs:allDayProps.fgEventSegs,bgEventSegs:allDayProps.bgEventSegs,businessHourSegs:allDayProps.businessHourSegs,dateSelectionSegs:allDayProps.dateSelectionSegs,eventDrag:allDayProps.eventDrag,eventResize:allDayProps.eventResize,fgEventSegsByCol,bgEventSegsByCol,businessHourSegsByCol,nowIndicatorSegsByCol,dateSelectionSegsByCol,eventDragByCol,eventResizeByCol,eventSelection:props.eventSelection})}})}},timeGridPlugin={name:"timegrid",initialView:"timeGridWeek",deps:[dayGridPlugin],views:{timeGrid:{component:TimeGridView,usesMinMaxTime:!0,allDaySlot:!0,slotDuration:"00:30:00",slotEventOverlap:!0},timeGridDay:{type:"timeGrid",duration:{days:1}},timeGridWeek:{type:"timeGrid",duration:{weeks:1}}}};import{Button as Button3,Group as Group3,Loader as Loader2,SegmentedControl,Title as Title2,useComputedColorScheme}from"@mantine/core";import{useDebouncedCallback}from"@mantine/hooks";import{assertNever as assertNever3}from"@medplum/core";import{useCallback as useCallback7,useEffect as useEffect4,useMemo as useMemo3,useRef as useRef2}from"react";var CalendarBase_default={wrapper:"CalendarBase_wrapper",calendar:"CalendarBase_calendar",listItemEventBefore:"CalendarBase_listItemEventBefore",clickable:"CalendarBase_clickable",selectedRange:"CalendarBase_selectedRange",eventTitle:"CalendarBase_eventTitle",eventTime:"CalendarBase_eventTime",eventInner:"CalendarBase_eventInner",shortEvent:"CalendarBase_shortEvent",backgroundEventInner:"CalendarBase_backgroundEventInner",backgroundEvent:"CalendarBase_backgroundEvent",nonBusinessHours:"CalendarBase_nonBusinessHours",event:"CalendarBase_event"};import{EMPTY,getReferenceString as getReferenceString9}from"@medplum/core";var DayIndexer=["sun","mon","tue","wed","thu","fri","sat"];function availableTimeToBusinessHoursEntry(availableTime){let startTime=availableTime.allDay?"00:00:00":availableTime.availableStartTime,endTime=availableTime.allDay?"24:00:00":availableTime.availableEndTime;if(!startTime||!endTime||!availableTime.daysOfWeek)return[];let daysOfWeek=availableTime.daysOfWeek.map(day=>DayIndexer.indexOf(day));return endTime<=startTime?[{daysOfWeek,startTime,endTime:"24:00:00"},{daysOfWeek:daysOfWeek.map(day=>(day+1)%7),startTime:"00:00:00",endTime}]:[{daysOfWeek,startTime,endTime}]}function filterBookedSlots(slots,appointments){let appointmentIndex=appointments.reduce((acc,appointment)=>((appointment.slot??EMPTY).forEach(slotRef=>{let key=getReferenceString9(slotRef);key&&(acc[key]=appointment)}),acc),{});return slots.filter(slot=>{let key=getReferenceString9(slot);if(key&&appointmentIndex[key]){let appointment=appointmentIndex[key];if(slot.start===appointment.start&&slot.end===appointment.end)return!1}return!0})}import{jsx as jsx17,jsxs as jsxs12}from"react/jsx-runtime";function appointmentsToEvents(appointments,schedule,extra){return appointments.filter(appointment=>appointment.start&&appointment.end).map(appointment=>{let name=appointment.participant.find(p=>p.actor?.reference?.startsWith("Patient/"))?.actor?.display??"No Patient";return{id:appointment.id,title:name,start:appointment.start,end:appointment.end,extendedProps:{type:"appointment",appointment,schedule},className:`appointment ${appointment.status}`,...extra}})}function slotTitle(slot){return slot.status==="free"?"Available":slot.status==="entered-in-error"?"Entered in error":"Blocked"}function slotsToEvents(slots,schedule,extra){return slots.map(slot=>({id:slot.id,start:slot.start,end:slot.end,title:slotTitle(slot),extendedProps:{type:"slot",slot,schedule},className:`slot ${slot.status}`,...extra}))}function CalendarBase(props){let colorScheme=useComputedColorScheme(),controller=useCalendarController(),{onRangeChange,className,availableTime,onSelectAppointment,onSelectSlot,onDoubleClickAppointment,onDoubleClickSlot,onSelectInterval,selection,loading,...fullCalendarProps}=props,eventSources=useMemo3(()=>props.eventSources.map(fhirSource=>{let{schedule,slots,appointments,...source}=fhirSource,filteredSlots=filterBookedSlots(slots,appointments),appointmentExtra={interactive:!!(props.onSelectAppointment||props.onDoubleClickAppointment)},slotExtra={interactive:!1,display:"background"};return{...source,events:[...appointmentsToEvents(appointments,schedule,appointmentExtra),...slotsToEvents(filteredSlots,schedule,slotExtra)]}}),[props.eventSources,props.onDoubleClickAppointment,props.onSelectAppointment]),rawEventClick=useCallback7(eventClickInfo=>{let ext=eventClickInfo.event.extendedProps;ext.type==="appointment"?onSelectAppointment?.(ext.appointment,ext.schedule):ext.type==="slot"?onSelectSlot?.(ext.slot,ext.schedule):assertNever3(ext)},[onSelectAppointment,onSelectSlot]),eventDoubleClickHandler=useCallback7(e=>{let ext=e.extendedProps;return ext?.type==="appointment"?(onDoubleClickAppointment?.(ext.appointment,ext.schedule),!0):(ext.type==="slot"?onDoubleClickSlot?.(ext.slot,ext.schedule):assertNever3(ext),!1)},[onDoubleClickAppointment,onDoubleClickSlot]),hasDoubleClickHandler=!!(onDoubleClickAppointment||onDoubleClickSlot),eventClickDebounced=useDebouncedCallback(rawEventClick??(()=>{}),100),eventClick=hasDoubleClickHandler?eventClickDebounced:rawEventClick,eventDataRef=useRef2(new WeakMap),eventDoubleClickRef=useRef2(eventDoubleClickHandler);useEffect4(()=>{eventDoubleClickRef.current=eventDoubleClickHandler},[eventDoubleClickHandler]);let handleDblClick=useCallback7(e=>{let event=eventDataRef.current.get(e.currentTarget);event&&(eventClickDebounced.cancel(),eventDoubleClickRef.current?.(event))},[eventClickDebounced]),businessHours=availableTime?.flatMap(availableTimeToBusinessHoursEntry),selectable=!!(onSelectInterval||selection),calendarRef=useRef2(null),startMs=selection?.start.getTime(),endMs=selection?.end.getTime();return useEffect4(()=>{let api=calendarRef.current?.getApi();api&&(startMs!==void 0&&endMs!==void 0?api.select(startMs,endMs):api.unselect())},[startMs,endMs]),jsxs12("div",{"data-testid":"calendar",className:clsx_default(CalendarBase_default.wrapper,className),children:[jsxs12(Group3,{justify:"space-between",pb:"sm",children:[jsxs12(Group3,{gap:"md",children:[jsxs12(Button3.Group,{children:[jsx17(Button3,{variant:"default",size:"xs","aria-label":"Previous",onClick:()=>controller.prev(),children:jsx17(IconChevronLeft,{size:12})}),jsx17(Button3,{variant:"default",size:"xs",onClick:()=>controller.today(),children:"Today"}),jsx17(Button3,{variant:"default",size:"xs","aria-label":"Next",onClick:()=>controller.next(),children:jsx17(IconChevronRight,{size:12})})]}),jsxs12(Group3,{children:[jsx17(Title2,{order:4,children:controller.view?.title}),loading&&jsx17(Loader2,{size:"sm"})]})]}),jsx17(SegmentedControl,{size:"xs",value:controller.view?.type,onChange:newView=>controller.changeView(newView),data:[{label:"Month",value:"dayGridMonth"},{label:"Week",value:"timeGridWeek"},{label:"Day",value:"timeGridDay"}]})]}),jsx17(Calendar,{height:"100%",plugins:[timeGridPlugin,dayGridPlugin,index,interactionPlugin],initialView:"timeGridWeek",slotMinHeight:38,colorScheme,displayEventEnd:!1,eventTimeFormat:{timeStyle:"short"},views:{timeGridWeek:{allDaySlot:!1},timeGridDay:{allDaySlot:!1}},selectable,unselectAuto:!1,select:eventInfo=>{eventInfo.jsEvent&&onSelectInterval?.({start:eventInfo.start,end:eventInfo.end})},...fullCalendarProps,ref:calendarRef,eventSources,controller,headerToolbar:!1,datesSet:info=>onRangeChange?.({start:info.start,end:info.end}),className:clsx_default(CalendarBase_default.calendar,controller.view?.type),eventDidMount:info=>{hasDoubleClickHandler&&(eventDataRef.current.set(info.el,info.event),info.el.addEventListener("dblclick",handleDblClick))},businessHours,eventClick,eventClass:evt=>clsx_default(props.eventClass,CalendarBase_default.event,{[CalendarBase_default.clickable]:evt.isInteractive,[CalendarBase_default.shortEvent]:evt.isShort}),eventTimeClass:clsx_default(props.eventTimeClass,CalendarBase_default.eventTime),eventTitleClass:clsx_default(props.eventTitleClass,CalendarBase_default.eventTitle),eventInnerClass:clsx_default(props.eventInnerClass,CalendarBase_default.eventInner),backgroundEventClass:clsx_default(props.backgroundEventClass,CalendarBase_default.backgroundEvent),backgroundEventInnerClass:clsx_default(props.backgroundEventInnerClass,CalendarBase_default.backgroundEventInner),listItemEventBeforeClass:clsx_default(props.listItemEventBeforeClass,CalendarBase_default.listItemEventBefore),nonBusinessHoursClass:clsx_default(props.nonBusinessHoursClass,CalendarBase_default.nonBusinessHours),dayLaneClass:clsx_default(props.dayLaneClass,selectable&&CalendarBase_default.clickable),dayCellClass:clsx_default(props.dayCellClass,selectable&&CalendarBase_default.clickable),highlightClass:clsx_default(props.highlightClass,CalendarBase_default.selectedRange)})]})}var Calendar_default={wrapper:"Calendar_wrapper",event:"Calendar_event",eventTitle:"Calendar_eventTitle",backgroundEvent:"Calendar_backgroundEvent",eventInner:"Calendar_eventInner",backgroundEventInner:"Calendar_backgroundEventInner"};import{jsx as jsx18}from"react/jsx-runtime";function Calendar2(props){let{slots,appointments,...baseProps}=props,eventSources=useMemo4(()=>[{appointments:appointments??[],slots:slots??[]}],[appointments,slots]);return jsx18(CalendarBase,{eventSources,...baseProps,nowIndicator:!0,className:clsx_default(props.className,Calendar_default.wrapper),eventClass:Calendar_default.event,eventInnerClass:Calendar_default.eventInner,backgroundEventClass:Calendar_default.backgroundEvent,backgroundEventInnerClass:Calendar_default.backgroundEventInner,eventTitleClass:Calendar_default.eventTitle})}import{useMantineTheme}from"@mantine/core";import{getExtensionValue,SchedulingScheduleColorURI}from"@medplum/core";import{useMemo as useMemo5}from"react";var FALLBACK_COLORS=["indigo","teal","pink","violet","blue","cyan","lime","red","yellow","grape","orange"];function resolveThemeColor(theme,explicit,fallbackIndex){return explicit&&Object.hasOwn(theme.colors,explicit)?explicit:FALLBACK_COLORS[fallbackIndex%FALLBACK_COLORS.length]}var MultiCalendar_default={eventInner:"MultiCalendar_eventInner",eventTime:"MultiCalendar_eventTime"};import{jsx as jsx19}from"react/jsx-runtime";function MultiCalendar(props){let theme=useMantineTheme(),{sources,...calendarBaseProps}=props,eventSources=useMemo5(()=>sources.map((source,i)=>{let colorName=source.color&&Object.hasOwn(theme.colors,source.color)?source.color:void 0;if(!colorName){let extColor=getExtensionValue(source.schedule,SchedulingScheduleColorURI);typeof extColor=="string"&&(colorName=extColor)}let color=theme.colors[resolveThemeColor(theme,colorName,i)][7];return{...source,color}}),[sources,theme]);return jsx19(CalendarBase,{eventSources,nowIndicator:!0,...calendarBaseProps,eventInnerClass:MultiCalendar_default.eventInner,eventTimeClass:MultiCalendar_default.eventTime,availableTime:props.availableTime,eventTimeFormat:{hour:"numeric",minute:"2-digit",omitZeroMinute:!0,meridiem:"lowercase"}})}import{ActionIcon,Anchor,Box,Button as Button4,Divider,Group as Group5,Paper as Paper2,Stack as Stack5,Switch,Text as Text6,Tooltip,VisuallyHidden}from"@mantine/core";import{clearScheduleParameter,getScheduleParameters as getScheduleParameters2}from"@medplum/core";import{Fragment as Fragment9,useId,useRef as useRef4,useState as useState7}from"react";import{getExtensions as getExtensions2,getScheduleParameters,isDayOfWeek,OperationOutcomeError,setScheduleParameter,validationError}from"@medplum/core";function getSingleValue(availableTime,url){let matches=getExtensions2(availableTime,url);if(matches.length>1)throw new OperationOutcomeError(validationError(`availableTime must set at most one ${url}, found ${matches.length}`));return matches[0]}function toAvailableTime(availableTime){let daysOfWeek=getExtensions2(availableTime,"daysOfWeek").map(subextension=>subextension.valueCode).filter(isDayOfWeek),allDay=getSingleValue(availableTime,"allDay"),start=getSingleValue(availableTime,"availableStartTime"),end=getSingleValue(availableTime,"availableEndTime");return allDay?.valueBoolean?{daysOfWeek,allDay:!0}:{daysOfWeek,availableStartTime:start?.valueTime,availableEndTime:end?.valueTime}}function getScheduleAvailability(schedule,service){let availability=getScheduleParameters(schedule,service,"availability");if(availability.length)return availability.flatMap(extension=>getExtensions2(extension,"availableTime")).map(toAvailableTime)}function getEffectiveAvailability(service,schedule){if(service)return(schedule&&getScheduleAvailability(schedule,service))??service.availableTime}function buildAvailableTimeExtension(entry){let days=(entry.daysOfWeek??[]).map(day=>({url:"daysOfWeek",valueCode:day}));if(entry.allDay)return{url:"availableTime",extension:[...days,{url:"allDay",valueBoolean:!0}]};if(!entry.availableStartTime||!entry.availableEndTime)throw new OperationOutcomeError(validationError("availableTime must set allDay, or both availableStartTime and availableEndTime",void 0,"required"));return{url:"availableTime",extension:[...days,{url:"availableStartTime",valueTime:entry.availableStartTime},{url:"availableEndTime",valueTime:entry.availableEndTime}]}}function buildAvailabilityExtension(availableTime){if(!availableTime.length)throw new OperationOutcomeError(validationError("availability must have at least one availableTime; to follow the service default, clear it instead",void 0,"required"));return{url:"availability",extension:availableTime.map(buildAvailableTimeExtension)}}function setScheduleAvailability(schedule,service,availableTime){return setScheduleParameter(schedule,service,buildAvailabilityExtension(availableTime))}var ScheduleAvailabilityEditor_default={week:"ScheduleAvailabilityEditor_week",dayCell:"ScheduleAvailabilityEditor_dayCell",rangeStart:"ScheduleAvailabilityEditor_rangeStart",rangeSeparator:"ScheduleAvailabilityEditor_rangeSeparator",rangeEnd:"ScheduleAvailabilityEditor_rangeEnd",addAction:"ScheduleAvailabilityEditor_addAction",removeAction:"ScheduleAvailabilityEditor_removeAction",unavailable:"ScheduleAvailabilityEditor_unavailable",overrideToggle:"ScheduleAvailabilityEditor_overrideToggle"};import{DAYS_OF_WEEK,isDayOfWeek as isDayOfWeek2}from"@medplum/core";var MINUTES_PER_DAY=1440,TIME_STEP_MINUTES=15,DEFAULT_RANGE={start:540,end:1020},DAY_LABELS={mon:"Monday",tue:"Tuesday",wed:"Wednesday",thu:"Thursday",fri:"Friday",sat:"Saturday",sun:"Sunday"},DAY_DISPLAY_ORDER=["sun","mon","tue","wed","thu","fri","sat"];function blankWeeklyAvailability(){let weekly={};for(let day of DAYS_OF_WEEK)weekly[day]={available:!1,ranges:[{...DEFAULT_RANGE}]};return weekly}function nextDayOfWeek(day){return DAYS_OF_WEEK[(DAYS_OF_WEEK.indexOf(day)+1)%DAYS_OF_WEEK.length]}function parseTimeOfDay(time){let match=/^(\d{1,2}):(\d{2})(?::(\d{2}(?:\.\d+)?))?$/.exec(time??"");if(!match)return;let hours=Number(match[1]),minutes=Number(match[2]);if(!(hours>23||minutes>59))return hours*60+minutes+Math.round(Number(match[3]??0)/60)}function formatTimeOfDay(minutes){let total=minutes%MINUTES_PER_DAY,hh=Math.floor(total/60).toString().padStart(2,"0"),mm=(total%60).toString().padStart(2,"0");return`${hh}:${mm}:00`}function normalizeRanges(ranges){let sorted=[...ranges].filter(range=>range.end>range.start).sort((a,b)=>a.start-b.start),merged=[];for(let range of sorted){let previous=merged[merged.length-1];previous&&range.start<=previous.end?merged[merged.length-1]={start:previous.start,end:Math.max(previous.end,range.end)}:merged.push(range)}return merged}function toWeeklyAvailability(availableTime){let weekly=blankWeeklyAvailability(),collected={};for(let day of DAYS_OF_WEEK)collected[day]=[];for(let entry of availableTime??[]){let days=(entry.daysOfWeek??[]).filter(isDayOfWeek2);if(entry.allDay===!0){for(let day of days)collected[day].push({start:0,end:MINUTES_PER_DAY});continue}let start=parseTimeOfDay(entry.availableStartTime),end=parseTimeOfDay(entry.availableEndTime);if(!(start===void 0||end===void 0))for(let day of days)end>start?collected[day].push({start,end}):(collected[day].push({start,end:MINUTES_PER_DAY}),end>0&&collected[nextDayOfWeek(day)].push({start:0,end}))}for(let day of DAYS_OF_WEEK){let ranges=normalizeRanges(collected[day]);ranges.length>0&&(weekly[day]={available:!0,ranges})}return weekly}function fromWeeklyAvailability(weekly){let availableTime=[];for(let day of DAYS_OF_WEEK)if(weekly[day].available)for(let range of weekly[day].ranges)range.start===0&&range.end===MINUTES_PER_DAY?availableTime.push({daysOfWeek:[day],allDay:!0}):availableTime.push({daysOfWeek:[day],availableStartTime:formatTimeOfDay(range.start),availableEndTime:formatTimeOfDay(range.end)});return availableTime}function hasAnyAvailableDay(weekly){return DAYS_OF_WEEK.some(day=>weekly[day].available&&weekly[day].ranges.length>0)}function formatMinutesOfDay(minutes){if(minutes===MINUTES_PER_DAY)return"12:00 AM";let hours=Math.floor(minutes/60),meridiem=hours<12?"AM":"PM";return`${hours%12===0?12:hours%12}:${(minutes%60).toString().padStart(2,"0")} ${meridiem}`}function ceilToTimeStep(minutes){return Math.ceil(minutes/TIME_STEP_MINUTES)*TIME_STEP_MINUTES}function timeOptions(min,max,include=[]){let options=new Set;for(let minutes=ceilToTimeStep(min);minutes<=max;minutes+=TIME_STEP_MINUTES)options.add(minutes);for(let time of include)time>=min&&time<=max&&options.add(time);return[...options].sort((a,b)=>a-b)}function nearestOption(options,value){let nearest;for(let option of options)(nearest===void 0||Math.abs(option-value)<Math.abs(nearest-value))&&(nearest=option);return nearest}function readMeridiem(query){let lower=query.toLowerCase();if(lower.includes("a"))return"am";if(lower.includes("p"))return"pm"}function rankMinutes(minutes){return minutes.length===2?0:minutes.length===0?1:2}function parseTimeQuery(query){let digits=query.replace(/[^0-9]/g,"");if(!digits)return[];let meridiem=readMeridiem(query);return[1,2].filter(hourDigits=>{let hour=Number(digits.slice(0,hourDigits)),minutes=digits.slice(hourDigits);return hourDigits<=digits.length&&hour>=1&&hour<=12&&minutes.length<=2&&(hourDigits===1||hour>=10||digits.startsWith("0"))}).map(hourDigits=>{let minutes=digits.slice(hourDigits);return{hour:Number(digits.slice(0,hourDigits)),minutes,meridiem,rank:rankMinutes(minutes)}}).sort((a,b)=>a.rank-b.rank)}function isTimeQuery(query){return parseTimeQuery(query).length>0}function matchesTimeQuery(minutes,query){let total=minutes===MINUTES_PER_DAY?0:minutes,hours=Math.floor(total/60);return(hours%12===0?12:hours%12)!==query.hour||query.meridiem&&query.meridiem!==(hours<12?"am":"pm")?!1:(total%60).toString().padStart(2,"0").startsWith(query.minutes)}function leadWithNearestHour(options,current){let byHour=new Map;options.forEach((option,index2)=>{let hour=Math.floor(option/60),distance=Math.abs(option-current),seen=byHour.get(hour);byHour.set(hour,seen?{index:seen.index,distance:Math.min(seen.distance,distance)}:{index:index2,distance})});let rotateAt=0,nearest=1/0;return byHour.forEach(entry=>{entry.distance<nearest&&(nearest=entry.distance,rotateAt=entry.index)}),rotateAt===0?options:[...options.slice(rotateAt),...options.slice(0,rotateAt)]}function typedTimes(query){return parseTimeQuery(query).filter(parsed=>parsed.minutes.length===2&&Number(parsed.minutes)<60).flatMap(parsed=>{let hour=parsed.hour%12,minutes=Number(parsed.minutes);return(parsed.meridiem?[parsed.meridiem]:["am","pm"]).map(meridiem=>(meridiem==="am"?hour:hour+12)*60+minutes)})}function filterTimeOptions(options,query,current){let queries=parseTimeQuery(query);if(queries.length===0)return options;let seen=new Set,matches=[];for(let parsed of queries){let matched=options.filter(option=>!seen.has(option)&&matchesTimeQuery(option,parsed));matched.forEach(option=>seen.add(option)),matches.push(...leadWithNearestHour(matched,current))}return matches}function canAddRange(ranges){return ranges.length>0&&ranges[ranges.length-1].end<=MINUTES_PER_DAY-TIME_STEP_MINUTES}function nextRange(ranges){let lastEnd=ranges[ranges.length-1].end,start=Math.max(ceilToTimeStep(lastEnd),Math.min(ceilToTimeStep(lastEnd+60),MINUTES_PER_DAY-TIME_STEP_MINUTES));return{start,end:Math.min(start+60,MINUTES_PER_DAY)}}import{Combobox,Group as Group4,InputBase,Text as Text5,useCombobox}from"@mantine/core";import{forwardRef as forwardRef3,useEffect as useEffect5,useImperativeHandle as useImperativeHandle2,useRef as useRef3,useState as useState6}from"react";import{jsx as jsx20,jsxs as jsxs13}from"react/jsx-runtime";var FLASH_DURATION_MS=700,INPUT_STYLES={input:{transition:"border-color 450ms"}},FLASH_STYLES={input:{...INPUT_STYLES.input,borderColor:"var(--mantine-primary-color-filled)"}},TimeSelect=forwardRef3(function(props,ref){let{value,min,max,label,onChange,disabled,testId,className}=props,[query,setQuery]=useState6(""),[typing,setTyping]=useState6(!1),inputRef=useRef3(null),activeOptionRef=useRef3(null),submitting=useRef3(!1),combobox=useCombobox({onDropdownClose:()=>combobox.resetSelectedOption()}),[flashId,setFlashId]=useState6(),flashing=flashId!==void 0;useImperativeHandle2(ref,()=>({flash:()=>setFlashId(previous=>(previous??0)+1)}),[]),useEffect5(()=>{if(flashId===void 0)return;let timer=setTimeout(()=>setFlashId(void 0),FLASH_DURATION_MS);return()=>clearTimeout(timer)},[flashId]);let{dropdownOpened,selectActiveOption}=combobox;useEffect5(()=>{if(!dropdownOpened)return;let frame=requestAnimationFrame(()=>{selectActiveOption(),activeOptionRef.current?.scrollIntoView({block:"center"})});return()=>cancelAnimationFrame(frame)},[dropdownOpened,selectActiveOption]);let display=formatMinutesOfDay(value),typed=typing?query:"",options=filterTimeOptions(timeOptions(min,max,[value,...typedTimes(typed)]),typed,value),scrollTo=options.includes(value)?value:nearestOption(options,value);function handleSubmit(selected){onChange(selected),setQuery(""),setTyping(!1),combobox.closeDropdown(),submitting.current=!0,inputRef.current?.blur(),submitting.current=!1}function handleBlur(){if(!submitting.current&&typing&&isTimeQuery(query)){let highlighted=options[combobox.getSelectedOptionIndex()]??options[0];highlighted!==void 0&&onChange(highlighted)}setTyping(!1),setQuery(""),combobox.closeDropdown()}return jsxs13(Combobox,{store:combobox,keepMounted:!1,onOptionSubmit:selected=>handleSubmit(Number(selected)),children:[jsx20(Combobox.Target,{children:jsx20(InputBase,{ref:inputRef,component:"input",type:"text",className,w:132,value:typing?query:display,placeholder:display,disabled,"aria-label":label,"data-testid":testId,"data-flashing":flashing||void 0,styles:flashing?FLASH_STYLES:INPUT_STYLES,rightSection:jsx20(Combobox.Chevron,{}),rightSectionPointerEvents:"none",onChange:e=>{setTyping(!0),setQuery(e.currentTarget.value),combobox.openDropdown(),combobox.selectFirstOption()},onFocus:()=>{setTyping(!0),setQuery(""),combobox.openDropdown()},onBlur:handleBlur,onClick:()=>combobox.openDropdown()})}),jsx20(Combobox.Dropdown,{children:jsx20(Combobox.Options,{mah:220,style:{overflowY:"auto"},children:options.length===0?jsx20(Combobox.Empty,{children:"No matching time"}):options.map(option=>jsx20(Combobox.Option,{value:option.toString(),active:option===value,ref:option===scrollTo?activeOptionRef:void 0,children:jsxs13(Group4,{justify:"space-between",gap:"xs",wrap:"nowrap",children:[jsx20(Text5,{span:!0,inherit:!0,children:formatMinutesOfDay(option)}),option===value&&jsx20(IconCheck,{size:14,stroke:1.8})]})},option))})})]})});import{Fragment as Fragment10,jsx as jsx21,jsxs as jsxs14}from"react/jsx-runtime";var AVAILABLE_READ_ONLY_SWITCH_STYLES={track:{backgroundColor:"var(--mantine-color-green-6)",borderColor:"transparent"}};function DayRow(props){let{day,value,readOnly,onChange,onAnnounce}=props,{available,ranges}=value,label=DAY_LABELS[day],endInputs=useRef4([]);function boundsAfter(index2){return index2===ranges.length-1?MINUTES_PER_DAY:ranges[index2+1].start}function setStart(index2,start){let range=ranges[index2],end=start>=range.end?Math.min(start+60,boundsAfter(index2)):range.end;end!==range.end&&(endInputs.current[index2]?.flash(),onAnnounce(`${label} block ${index2+1} end time changed to ${formatMinutesOfDay(end)}.`)),onChange({...value,ranges:ranges.with(index2,{start,end})})}function setEnd(index2,end){onChange({...value,ranges:ranges.with(index2,{...ranges[index2],end})})}let switchStyles=readOnly&&available?AVAILABLE_READ_ONLY_SWITCH_STYLES:void 0,canAdd=canAddRange(ranges);return jsxs14(Fragment10,{children:[jsxs14(Group5,{gap:"sm",wrap:"nowrap",className:ScheduleAvailabilityEditor_default.dayCell,children:[jsx21(Switch,{checked:available,onChange:e=>{let checked=e.currentTarget.checked;onChange({available:checked,ranges:checked&&ranges.length===0?[{...DEFAULT_RANGE}]:ranges})},color:"green.6",withThumbIndicator:!1,disabled:readOnly,styles:switchStyles,"aria-label":`Available on ${label}`,"data-testid":`schedule-availability-switch-${day}`}),jsx21(Text6,{fw:500,children:label})]}),available?ranges.map((range,index2)=>{let last=index2===ranges.length-1;return jsxs14(Fragment9,{children:[jsx21(TimeSelect,{className:ScheduleAvailabilityEditor_default.rangeStart,value:range.start,min:index2===0?0:ranges[index2-1].end,max:boundsAfter(index2)-1,onChange:start=>setStart(index2,start),disabled:readOnly,label:`${label} block ${index2+1} start time`,testId:`schedule-availability-start-${day}-${index2}`}),jsx21(Text6,{c:"dimmed",className:ScheduleAvailabilityEditor_default.rangeSeparator,children:"to"}),jsx21(TimeSelect,{ref:handle=>{endInputs.current[index2]=handle},className:ScheduleAvailabilityEditor_default.rangeEnd,value:range.end,min:range.start+1,max:boundsAfter(index2),onChange:end=>setEnd(index2,end),disabled:readOnly,label:`${label} block ${index2+1} end time`,testId:`schedule-availability-end-${day}-${index2}`}),last&&jsx21(ActionIcon,{className:ScheduleAvailabilityEditor_default.addAction,variant:"subtle",color:"gray",radius:"xl",onClick:()=>onChange({...value,ranges:[...ranges,nextRange(ranges)]}),disabled:readOnly||!canAdd,"aria-label":`Add another block of hours on ${label}`,"data-testid":`schedule-availability-add-${day}`,children:jsx21(IconPlus,{size:16,stroke:1.8})}),ranges.length>1&&jsx21(ActionIcon,{className:ScheduleAvailabilityEditor_default.removeAction,variant:"subtle",color:"gray",radius:"xl",onClick:()=>onChange({...value,ranges:ranges.toSpliced(index2,1)}),disabled:readOnly,"aria-label":`Remove ${label} block ${index2+1}`,"data-testid":`schedule-availability-remove-${day}-${index2}`,children:jsx21(IconMinus,{size:16,stroke:1.8})})]},index2)}):jsx21(Text6,{c:"dimmed",className:ScheduleAvailabilityEditor_default.unavailable,children:"Unavailable"})]})}function ScheduleAvailabilityEditor(props){let{schedule,service,timezone,onCancel}=props,editingDefault=schedule===void 0,[overriding,setOverriding]=useState7(()=>schedule?getScheduleParameters2(schedule,service,"availability").length>0:!0),[weekly,setWeekly]=useState7(()=>toWeeklyAvailability(getEffectiveAvailability(service,schedule))),[saving,setSaving]=useState7(!1),[announcement,setAnnouncement]=useState7({message:"",id:0}),reasonId=useId(),serviceName=service.name??"this visit service type",emptyWeek=(editingDefault||overriding)&&!hasAnyAvailableDay(weekly),emptyWeekReason=editingDefault?`Default availability must include at least one available day. Clearing every day would leave ${serviceName} bookable around the clock rather than never; to stop scheduling it, deactivate the visit service type.`:`Custom availability must include at least one available day. To stop scheduling ${serviceName} on this calendar, turn it off in schedule settings.`;function toggleOverriding(next){setOverriding(next),next||setWeekly(toWeeklyAvailability(service.availableTime))}async function handleSave(){if(!emptyWeek){setSaving(!0);try{if(props.schedule){let updated=overriding?setScheduleAvailability(props.schedule,service,fromWeeklyAvailability(weekly)):clearScheduleParameter(props.schedule,service,"availability");await props.onSave(updated)}else await props.onSave({...service,availableTime:fromWeeklyAvailability(weekly)})}catch(err){console.error(err)}finally{setSaving(!1)}}}let saveButton=jsx21(Tooltip,{label:emptyWeekReason,disabled:!emptyWeek,multiline:!0,w:300,withArrow:!0,position:"top",events:{hover:!0,focus:!0,touch:!0},children:jsx21(Button4,{onClick:handleSave,loading:saving,fullWidth:!onCancel,"data-disabled":emptyWeek||void 0,"aria-disabled":emptyWeek||void 0,"aria-describedby":emptyWeek?reasonId:void 0,children:"Save Settings"})});return jsxs14(Stack5,{gap:"lg",children:[jsx21(Text6,{c:"dimmed",children:editingDefault?`Set the default weekly working hours for ${serviceName}. Every calendar without hours of its own follows these.`:`Customize the weekly working hours on this calendar, in place of the default availability for ${serviceName}.`}),jsxs14(Paper2,{withBorder:!0,radius:"md",p:"xl",children:[!editingDefault&&jsxs14(Fragment10,{children:[jsxs14(Group5,{gap:"sm",wrap:"nowrap",className:ScheduleAvailabilityEditor_default.overrideToggle,children:[jsx21(Switch,{checked:overriding,onChange:e=>toggleOverriding(e.currentTarget.checked),color:"green.6",withThumbIndicator:!1,"aria-label":`Enable custom availability for ${serviceName}`,"data-testid":"schedule-availability-enable"}),jsxs14(Text6,{fw:500,children:["Enable custom availability for ",serviceName]})]}),jsx21(Divider,{my:"lg"})]}),jsx21(Box,{className:ScheduleAvailabilityEditor_default.week,opacity:overriding?1:.8,children:DAY_DISPLAY_ORDER.map(day=>jsx21(DayRow,{day,value:weekly[day],readOnly:!overriding,onChange:value=>setWeekly(prev=>({...prev,[day]:value})),onAnnounce:message=>setAnnouncement(previous=>({message,id:previous.id+1}))},day))}),jsx21(VisuallyHidden,{role:"status","aria-live":"polite","data-testid":"schedule-availability-announcement",children:jsx21(Fragment9,{children:announcement.message},announcement.id)}),jsxs14(Stack5,{gap:"sm",mt:"xl",children:[!editingDefault&&jsx21(Group5,{justify:"flex-start",children:jsxs14(Anchor,{component:"button",type:"button",onClick:()=>setWeekly(toWeeklyAvailability(service.availableTime)),disabled:!overriding,c:overriding?void 0:"dimmed",underline:overriding?"hover":"never","data-testid":"schedule-availability-reset",children:["Reset to default availability of ",serviceName]})}),timezone&&jsxs14(Text6,{c:"dimmed","data-testid":"schedule-availability-timezone",children:["All times are in local ",timezone," time zone."]})]})]}),emptyWeek&&jsx21(VisuallyHidden,{id:reasonId,"data-testid":"schedule-availability-empty-week",children:emptyWeekReason}),onCancel?jsxs14(Group5,{grow:!0,children:[jsx21(Button4,{variant:"default",onClick:onCancel,children:"Cancel"}),saveButton]}):saveButton]})}import{Alert as Alert3,CloseButton,Drawer,Group as Group9,Title as Title3,useMantineTheme as useMantineTheme2}from"@mantine/core";import{getExtensionValue as getExtensionValue3,getReferenceString as getReferenceString11,isDefined as isDefined9,normalizeErrorString as normalizeErrorString4,SchedulingScheduleColorURI as SchedulingScheduleColorURI2}from"@medplum/core";import{useMedplum as useMedplum7}from"@medplum/react-hooks";import{useCallback as useCallback10,useEffect as useEffect7,useMemo as useMemo6,useState as useState11}from"react";import{getReferenceString as getReferenceString10,isDefined as isDefined7,normalizeOperationOutcome}from"@medplum/core";import{useMedplum as useMedplum5,useResourceModified}from"@medplum/react";import{useCallback as useCallback8,useEffect as useEffect6,useRef as useRef5,useState as useState8}from"react";function isWithinRange(instant,range){if(!instant||!range)return!1;let time=new Date(instant).getTime();return time>=range.start.getTime()&&time<=range.end.getTime()}function useSchedulingSlots(schedules,range,options){let medplum=useMedplum5(),[slots,setSlots]=useState8(void 0),[loading,setLoading]=useState8(!1),[error,setError]=useState8(),onErrorRef=useRef5(options?.onError);useEffect6(()=>{onErrorRef.current=options?.onError},[options?.onError]);let handleError=useCallback8(error2=>{let outcome=normalizeOperationOutcome(error2);onErrorRef.current?.(outcome),setError(outcome)},[]),scheduleRefs=[...new Set(schedules.map(schedule=>getReferenceString10(schedule)))],scheduleRefsKey=scheduleRefs.join(","),rangeStart=range?.start?.toISOString(),rangeEnd=range?.end?.toISOString();return useResourceModified("Slot",event=>{if(event.operation==="delete"){event.id&&setSlots(state=>state?.filter(slot2=>slot2.id!==event.id));return}let slot=event.resource;slot&&(!slot.schedule.reference||!scheduleRefs.includes(slot.schedule.reference)||setSlots(state=>{if(event.operation==="create"){if(!isWithinRange(slot.start,range))return state;let current=state??[];return current.some(existing=>existing.id===slot.id)?current:[...current,slot]}return state?.map(existing=>existing.id===slot.id?slot:existing)}))}),useEffect6(()=>{if(scheduleRefsKey.length===0||!rangeStart||!rangeEnd)return()=>{};let active=!0;setLoading(!0);let refs=scheduleRefsKey.split(",");return Promise.all(refs.map(scheduleRef=>medplum.searchResources("Slot",[["_count","1000"],["schedule",scheduleRef],["start",`ge${rangeStart}`],["start",`le${rangeEnd}`],["status:not","entered-in-error"]]))).then(results=>{active&&(setSlots(results.flat()),setError(void 0))}).catch(error2=>active&&handleError(error2)).finally(()=>{active&&setLoading(!1)}),()=>{active=!1,setLoading(!1)}},[medplum,scheduleRefsKey,rangeStart,rangeEnd,handleError]),{slots,loading,error}}function useSchedulingAppointments(schedules,range,options){let medplum=useMedplum5(),[appointments,setAppointments]=useState8(void 0),[loading,setLoading]=useState8(!1),[error,setError]=useState8(),onErrorRef=useRef5(options?.onError);useEffect6(()=>{onErrorRef.current=options?.onError},[options?.onError]);let handleError=useCallback8(error2=>{let outcome=normalizeOperationOutcome(error2);onErrorRef.current?.(outcome),setError(outcome)},[]),actorRefs=[...new Set(schedules.flatMap(schedule=>schedule.actor.map(ref=>getReferenceString10(ref))).filter(isDefined7))],rangeStart=range?.start?.toISOString(),rangeEnd=range?.end?.toISOString(),actorRefsKey=actorRefs.join(",");return useResourceModified("Appointment",event=>{if(event.operation==="delete"){event.id&&setAppointments(state=>state?.filter(appointment2=>appointment2.id!==event.id));return}let appointment=event.resource;appointment&&appointment.participant.some(p=>p.actor?.reference&&actorRefs.includes(p.actor.reference))&&setAppointments(state=>{if(event.operation==="create"){if(!isWithinRange(appointment.start,range))return state;let current=state??[];return current.some(existing=>existing.id===appointment.id)?current:[...current,appointment]}return state?.map(existing=>existing.id===appointment.id?appointment:existing)})}),useEffect6(()=>{if(actorRefsKey.length===0||!rangeStart||!rangeEnd)return()=>{};let active=!0;setLoading(!0);let refs=actorRefsKey.split(",");return Promise.all(refs.map(actorRef=>medplum.searchResources("Appointment",[["_count","1000"],["actor",actorRef],["date",`ge${rangeStart}`],["date",`le${rangeEnd}`]]))).then(results=>{if(!active)return;setError(void 0);let byId=new Map;for(let appointment of results.flat())byId.set(appointment.id,appointment);setAppointments([...byId.values()])}).catch(error2=>active&&handleError(error2)).finally(()=>{active&&setLoading(!1)}),()=>{active=!1,setLoading(!1)}},[medplum,actorRefsKey,rangeStart,rangeEnd,handleError]),{appointments,loading,error}}function useSchedulingResources(schedules,range,options){let slotsResult=useSchedulingSlots(schedules,range,options),appointmentsResult=useSchedulingAppointments(schedules,range,options);return{slots:slotsResult.slots,appointments:appointmentsResult.appointments,loading:slotsResult.loading||appointmentsResult.loading,error:slotsResult.error??appointmentsResult.error}}import{Alert as Alert2,Badge,Button as Button5,Divider as Divider2,Stack as Stack6,Text as Text7}from"@mantine/core";import{formatCodeableConcept as formatCodeableConcept2,isDefined as isDefined8,normalizeErrorString as normalizeErrorString3,resolveId}from"@medplum/core";import{CodeableConceptInput,ReferenceDisplay as ReferenceDisplay3}from"@medplum/react";import{useMedplum as useMedplum6}from"@medplum/react-hooks";import{Fragment as Fragment11,useCallback as useCallback9,useState as useState9}from"react";import{HTTP_HL7_ORG as HTTP_HL7_ORG2,HTTP_TERMINOLOGY_HL7_ORG}from"@medplum/core";var APPOINTMENT_CANCELLATION_REASON_VALUE_SET=HTTP_HL7_ORG2+"/fhir/ValueSet/appointment-cancellation-reason",APPOINTMENT_CANCELLATION_REASON_CODE_SYSTEM=HTTP_TERMINOLOGY_HL7_ORG+"/CodeSystem/appointment-cancellation-reason";import{Fragment as Fragment12,jsx as jsx22,jsxs as jsxs15}from"react/jsx-runtime";var CANCELABLE_STATUSES=new Set(["pending","booked"]),STATUS_COLORS={proposed:"yellow",pending:"yellow",booked:"blue",arrived:"blue",fulfilled:"blue",cancelled:"red",noshow:"red","entered-in-error":"red","checked-in":"blue",waitlist:"gray"};function AppointmentDetails(props){let{appointment,onCancelled,cancellationReasonValueSet}=props,medplum=useMedplum6(),patient=getPatientParticipant(appointment)?.actor,otherActors=getOtherActors(appointment),[cancelling,setCancelling]=useState9(!1),[cancelError,setCancelError]=useState9(),[reason,setReason]=useState9(),cancel=useCallback9(async()=>{if(reason){setCancelling(!0),setCancelError(void 0);try{let cancelled=await medplum.post(medplum.fhirUrl("Appointment",appointment.id,"$cancel"),{resourceType:"Parameters",parameter:[{name:"cancelationReason",valueCodeableConcept:reason}]});medplum.notifyResourceModified({resourceType:"Appointment",operation:"update",id:cancelled.id,resource:cancelled});for(let slot of appointment.slot??[]){let id=resolveId(slot);id&&medplum.notifyResourceModified({resourceType:"Slot",operation:"delete",id})}try{await onCancelled?.(cancelled)}catch(error){console.error(error)}}catch(err){setCancelError(err)}finally{setCancelling(!1)}}},[appointment,medplum,onCancelled,reason]);return jsxs15(Stack6,{gap:"sm",children:[jsx22(Badge,{color:STATUS_COLORS[appointment.status],children:appointment.status}),jsx22(Detail,{label:"Patient",value:patient&&jsx22(ReferenceDisplay3,{link:!1,value:patient})}),jsx22(Detail,{label:"When",value:formatWhen(appointment)}),jsx22(Detail,{label:"Service",value:formatService(appointment)}),jsx22(Detail,{label:"With",value:otherActors.length>0?otherActors.map((actor,index2)=>jsxs15(Fragment11,{children:[index2>0&&", ",jsx22(ReferenceDisplay3,{value:actor,link:!1})]},actor.reference??`actor-${index2}`)):void 0}),jsx22(Detail,{label:"Notes",value:appointment.comment??appointment.description}),jsx22(Divider2,{}),jsx22(Detail,{label:"Cancellation reason",value:formatCodeableConcept2(appointment.cancelationReason)||void 0}),cancelError!==void 0&&jsx22(Alert2,{color:"red",title:"Could not cancel this appointment",children:normalizeErrorString3(cancelError)}),CANCELABLE_STATUSES.has(appointment.status)?jsxs15(Fragment12,{children:[jsx22(CodeableConceptInput,{name:"cancelationReason",path:"Appointment.cancelationReason",binding:cancellationReasonValueSet??APPOINTMENT_CANCELLATION_REASON_VALUE_SET,label:"Cancellation reason",placeholder:"Search reasons",maxValues:1,creatable:!1,withHelpText:!1,required:!0,onChange:setReason}),jsx22(Button5,{color:"red",variant:"light",loading:cancelling,disabled:!reason,onClick:cancel,children:"Cancel Appointment"})]}):jsx22(Text7,{size:"sm",c:"dimmed",children:appointment.status==="cancelled"?"This appointment is cancelled.":`An appointment in '${appointment.status}' status cannot be cancelled.`})]})}function Detail(props){return props.value?jsxs15(Stack6,{gap:0,children:[jsx22(Text7,{size:"xs",c:"dimmed",children:props.label}),jsx22(Text7,{size:"sm",children:props.value})]}):null}function getPatientParticipant(appointment){return appointment.participant.find(participant=>participant.actor?.reference?.startsWith("Patient/"))}function getOtherActors(appointment){let patient=getPatientParticipant(appointment);return appointment.participant.filter(participant=>participant!==patient).map(participant=>participant.actor).filter(isDefined8)}function formatWhen(appointment){if(!appointment.start)return;let start=new Date(appointment.start),times=[formatZonedTime(start),appointment.end&&formatZonedTime(new Date(appointment.end))].filter(Boolean).join(" \u2013 ");return`${formatDayHeading(start)} \xB7 ${times}`}function formatService(appointment){return(appointment.serviceType??[]).map(formatCodeableConcept2).filter(Boolean).join(", ")||formatCodeableConcept2(appointment.appointmentType)||void 0}import{Divider as Divider3,Stack as Stack7,Text as Text10}from"@mantine/core";import{Fragment as Fragment13}from"react";import{Avatar,Group as Group6,Text as Text8,ThemeIcon,UnstyledButton}from"@mantine/core";var CalendarRow_default={row:"CalendarRow_row",eyeSlot:"CalendarRow_eyeSlot",eyeOff:"CalendarRow_eyeOff",eyeHint:"CalendarRow_eyeHint"};import{jsx as jsx23,jsxs as jsxs16}from"react/jsx-runtime";function CalendarRow(props){let{item,icon,onToggle}=props,selected=item.selected??!0,interactive=!!onToggle,color=selected?props.color:"gray";return jsx23(UnstyledButton,{className:CalendarRow_default.row,onClick:interactive?()=>onToggle(item.id):void 0,"aria-pressed":interactive?selected:void 0,"data-selected":selected||void 0,"data-interactive":interactive||void 0,component:interactive?"button":"div",children:jsxs16(Group6,{gap:"sm",wrap:"nowrap",children:[icon?jsx23(ThemeIcon,{variant:"filled",color,radius:"sm",size:20,className:CalendarRow_default.icon,children:icon}):jsx23(Avatar,{src:item.imageUrl,name:item.label,color,radius:"xl",size:28}),jsx23(Text8,{truncate:!0,c:selected?void 0:"dimmed",children:item.label}),jsx23("div",{className:CalendarRow_default.eyeSlot,children:selected?interactive&&jsx23(IconEye,{size:16,"aria-hidden":"true",className:CalendarRow_default.eyeHint}):jsx23(IconEyeOff,{size:16,"aria-hidden":"true",className:CalendarRow_default.eyeOff})})]})})}import{ActionIcon as ActionIcon2,Box as Box2,Collapse,Group as Group7,Loader as Loader3,Text as Text9}from"@mantine/core";import{useState as useState10}from"react";var SectionHeader_default={chevron:"SectionHeader_chevron",title:"SectionHeader_title"};import{jsx as jsx24,jsxs as jsxs17}from"react/jsx-runtime";function SectionHeader(props){let{title,children,loading}=props,[collapsed,setCollapsed]=useState10(!1);return jsxs17(Box2,{children:[jsxs17(Group7,{gap:8,wrap:"nowrap",children:[jsx24(ActionIcon2,{variant:"subtle",color:"gray",radius:"xl",onClick:()=>setCollapsed(c=>!c),"aria-label":collapsed?`Show ${title.toLowerCase()}`:`Hide ${title.toLowerCase()}`,className:SectionHeader_default.chevron,"data-collapsed":collapsed||void 0,size:"md",children:jsx24(IconChevronDown,{size:20})}),jsx24(Text9,{fz:"md",fw:800,onClick:()=>setCollapsed(c=>!c),className:SectionHeader_default.title,children:title}),loading&&jsx24(Loader3,{size:"xs","aria-label":`Loading ${title.toLowerCase()}`})]}),jsx24(Collapse,{in:!collapsed,my:"xs",children})]})}import{jsx as jsx25,jsxs as jsxs18}from"react/jsx-runtime";var SECTIONS=[{actorType:"Practitioner",title:"Providers & Staff",emptyLabel:"providers or staff"},{actorType:"Device",title:"Devices",emptyLabel:"devices"},{actorType:"Location",title:"Rooms",emptyLabel:"rooms",icon:jsx25(IconMapPinFilled,{size:12})}];function CalendarsPanel(props){let{items,candidatesLoading,onToggle,className}=props;return jsxs18(Stack7,{gap:"xs",className,children:[jsx25(Text10,{fz:"lg",fw:800,py:"xs",children:"Calendars"}),jsx25(Divider3,{}),SECTIONS.map(section=>{let sectionItems=items[section.actorType];return jsxs18(Fragment13,{children:[jsx25(SectionHeader,{title:section.title,loading:candidatesLoading,children:sectionItems.length===0&&!candidatesLoading?jsxs18(Text10,{fz:"sm",c:"dimmed",p:"xs",children:["No ",section.emptyLabel," found"]}):jsx25(Stack7,{gap:2,children:sectionItems.map(item=>jsx25(CalendarRow,{item,color:item.color,onToggle:onToggle&&(id=>onToggle(section.actorType,id)),icon:section.icon},item.id))})}),jsx25(Divider3,{})]},section.actorType)})]})}import{Group as Group8,Text as Text11}from"@mantine/core";import{jsx as jsx26,jsxs as jsxs19}from"react/jsx-runtime";function CalendarTimezoneNotice(props){let{timezones,anyUnknown,viewerTimezone,className}=props;if(!timezones.some(timezone=>!isViewerTimezone(timezone,viewerTimezone))&&!anyUnknown)return null;let viewerLabel=formatTimezoneLabel(viewerTimezone);return jsxs19(Group8,{gap:6,wrap:"nowrap",align:"center",className,"data-testid":"calendar-timezone-notice",children:[jsx26(IconInfoCircle,{size:14,stroke:1.8,color:"var(--mantine-color-dimmed)"}),jsxs19(Text11,{size:"xs",c:"dimmed",children:["Calendar shown in your local time (",viewerLabel,")."]})]})}var SchedulingWorkspace_default={root:"SchedulingWorkspace_root",sidebar:"SchedulingWorkspace_sidebar",calendar:"SchedulingWorkspace_calendar",multiCalendar:"SchedulingWorkspace_multiCalendar",timezoneNotice:"SchedulingWorkspace_timezoneNotice",bookingPane:"SchedulingWorkspace_bookingPane",bookingPaneWide:"SchedulingWorkspace_bookingPaneWide",alert:"SchedulingWorkspace_alert"};import{getExtensionValue as getExtensionValue2,TimezoneExtensionURI}from"@medplum/core";function getCalendarTimezones(candidates){let timezones=[],anyUnknown=!1;for(let candidate of candidates){if(!candidate.actorResource){anyUnknown=!0;continue}let timezone=getExtensionValue2(candidate.actorResource,TimezoneExtensionURI);typeof timezone=="string"&&timezones.push(timezone)}return{timezones,anyUnknown}}import{jsx as jsx27,jsxs as jsxs20}from"react/jsx-runtime";var NO_CANDIDATES={Practitioner:[],Location:[],Device:[]},NONE_DESELECTED={Practitioner:new Set,Location:new Set,Device:new Set};function SchedulingWorkspace(props){let{procedureBinding,diagnosisBinding,onBooked,appointmentCancellationReasonValueSet}=props,medplum=useMedplum7(),theme=useMantineTheme2(),[schedulesLoadingError,setSchedulesLoadingError]=useState11(),[candidatesByActorType,setCandidatesByActorType]=useState11(NO_CANDIDATES),[candidatesLoading,setCandidatesLoading]=useState11(!1),[deselectedIds,setDeselectedIds]=useState11(NONE_DESELECTED),[range,setRange]=useState11(),[bookingSelection,setBookingSelection]=useState11(),[selectedAppointmentId,setSelectedAppointmentId]=useState11(),[highlight,setHighlight]=useState11(),[timeFinderOpen,setTimeFinderOpen]=useState11(!1);useEffect7(()=>{let controller=new AbortController;return setCandidatesLoading(!0),Promise.all(BOOKABLE_ACTOR_TYPES.map(async actorType=>{let candidates=await searchScheduleCandidates(medplum,void 0,{actorType,query:"",signal:controller.signal,count:100});return[actorType,candidates]})).then(results=>{controller.signal.aborted||(setSchedulesLoadingError(void 0),setCandidatesByActorType(Object.fromEntries(results)))}).catch(err=>{controller.signal.aborted||setSchedulesLoadingError(err)}).finally(()=>{controller.signal.aborted||setCandidatesLoading(!1)}),()=>controller.abort()},[medplum]);let colorByScheduleId=useMemo6(()=>{let all=BOOKABLE_ACTOR_TYPES.flatMap(actorType=>candidatesByActorType[actorType]),map=new Map;return all.forEach((candidate,i)=>{let extensionColor=getExtensionValue3(candidate.schedule,SchedulingScheduleColorURI2);map.set(candidate.schedule.id,resolveThemeColor(theme,extensionColor,i))}),map},[candidatesByActorType,theme]),activeCandidates=useMemo6(()=>BOOKABLE_ACTOR_TYPES.flatMap(actorType=>candidatesByActorType[actorType].filter(c=>!deselectedIds[actorType].has(c.schedule.id))),[candidatesByActorType,deselectedIds]),schedules=useMemo6(()=>activeCandidates.map(c=>c.schedule),[activeCandidates]),{slots,appointments,loading:resourcesLoading,error:resourcesError}=useSchedulingResources(schedules,range),sources=useMemo6(()=>activeCandidates.map(candidate=>{let scheduleReference=getReferenceString11(candidate.schedule),actorReferences=new Set(candidate.schedule.actor.map(actor=>actor.reference).filter(isDefined9));return{schedule:candidate.schedule,color:colorByScheduleId.get(candidate.schedule.id),slots:(slots??[]).filter(slot=>slot.schedule?.reference===scheduleReference),appointments:(appointments??[]).filter(appointment=>(appointment.participant??[]).some(participant=>participant.actor?.reference&&actorReferences.has(participant.actor.reference)))}}),[activeCandidates,slots,appointments,colorByScheduleId]),{timezones,anyUnknown}=useMemo6(()=>getCalendarTimezones(activeCandidates),[activeCandidates]),startBooking=useCallback10(interval=>{setBookingSelection(interval),setHighlight(interval)},[]),closeBooking=useCallback10(()=>{setBookingSelection(void 0),setHighlight(void 0),setTimeFinderOpen(!1)},[]),toggleCandidate=useCallback10((actorType,id)=>{setDeselectedIds(prev=>({...prev,[actorType]:toggleId(prev[actorType],id)}))},[]),finishBooking=useCallback10(booking=>(closeBooking(),onBooked?.(booking)),[closeBooking,onBooked]),selectAppointment=useCallback10(appointment=>{appointment.id&&setSelectedAppointmentId(appointment.id)},[]),closeAppointment=useCallback10(()=>setSelectedAppointmentId(void 0),[]),openAppointment=useMemo6(()=>{if(selectedAppointmentId)return(appointments??[]).find(a=>a.id===selectedAppointmentId)},[appointments,selectedAppointmentId]),toItem=(candidate,selected)=>{let color=colorByScheduleId.get(candidate.schedule.id);if(!color)throw new Error("Got candidate without resolved color");return{id:candidate.schedule.id,label:getCandidateDisplay(candidate),color,selected}},panelItems=Object.fromEntries(BOOKABLE_ACTOR_TYPES.map(actorType=>[actorType,candidatesByActorType[actorType].map(c=>toItem(c,!deselectedIds[actorType].has(c.schedule.id)))])),displayError=resourcesError??schedulesLoadingError;return jsxs20("div",{className:`${SchedulingWorkspace_default.root} ${props.className??""}`,children:[jsx27("div",{className:SchedulingWorkspace_default.sidebar,children:jsx27(CalendarsPanel,{items:panelItems,candidatesLoading,onToggle:toggleCandidate})}),jsxs20("div",{className:SchedulingWorkspace_default.calendar,children:[displayError!==void 0&&jsx27(Alert3,{color:"red",mb:"xs",children:normalizeErrorString4(displayError)}),jsx27(MultiCalendar,{className:SchedulingWorkspace_default.multiCalendar,sources,onRangeChange:setRange,loading:resourcesLoading,onSelectInterval:startBooking,onSelectAppointment:selectAppointment,selection:highlight}),jsx27(CalendarTimezoneNotice,{className:SchedulingWorkspace_default.timezoneNotice,timezones,anyUnknown})]}),jsx27(Drawer,{opened:openAppointment!==void 0,onClose:closeAppointment,position:"right",title:"Appointment details",closeButtonProps:{"aria-label":"Close appointment details"},children:openAppointment&&jsx27(AppointmentDetails,{appointment:openAppointment,cancellationReasonValueSet:appointmentCancellationReasonValueSet,onCancelled:props.onCancelled})}),bookingSelection&&jsxs20("div",{className:clsx_default(SchedulingWorkspace_default.bookingPane,{[SchedulingWorkspace_default.bookingPaneWide]:timeFinderOpen}),children:[jsxs20(Group9,{justify:"space-between",wrap:"nowrap",mb:"sm",children:[jsx27(Title3,{order:4,children:"Book appointment"}),jsx27(CloseButton,{"aria-label":"Close booking form",onClick:closeBooking})]}),jsx27(AppointmentBookingForm,{defaultStart:bookingSelection.start,procedureBinding,diagnosisBinding,onToggleTimeFinder:setTimeFinderOpen,onChangeTime:setHighlight,onBooked:finishBooking},bookingSelection.start.toDateString())]})]})}function toggleId(ids,id){let next=new Set(ids);return next.has(id)?next.delete(id):next.add(id),next}export{AppointmentActorSelect,AppointmentBookingForm,AppointmentDayTimes,AppointmentOptionRow,AppointmentProposalForm,AppointmentServiceSelect,AppointmentSlotGroupCard,BOOKABLE_ACTOR_TYPES,Calendar2 as Calendar,DEFAULT_DIAGNOSIS_VALUE_SET,DEFAULT_PROCEDURE_VALUE_SET,EMPTY_REQUIREMENT_VALUES,MAX_FIND_WINDOW_DAYS,MultiCalendar,REQUIRED_ACTOR_TYPES,ScheduleAvailabilityEditor,SchedulingWorkspace,addDays,endOfDay,endOfMonth,enumerateDateRange,filterByTimeOfDay,filterCandidatesByLocation,formatDayHeading,formatTimezoneLabel,formatZonedTime,getActorCombinations,getActorGroupKey,getActorType,getActorTypeLabel,getActorsKey,getAppointmentKey,getBrowserTimezone,getCandidateActor,getCandidateDisplay,getDayCount,getDurationMinutes,getEffectiveAvailability,getFindWindowError,getNativeInputType,getSelectedCandidates,getSelectionError,getZonedDayRange,groupAppointmentsByDay,hasRequiredValues,isActorTypeRequired,isBookableActorType,isRequirementAnswered,isViewerTimezone,parseDayKey,parseZonedTime,searchScheduleCandidates,setScheduleAvailability,startOfDay,toCodings,useProposedAppointments,useSchedulingAppointments,useSchedulingResources,useSchedulingSlots};
|
|
1
|
+
import{getReferenceString as getReferenceString3}from"@medplum/core";import{AsyncAutocomplete}from"@medplum/react";import{useMedplum,useResource}from"@medplum/react-hooks";import{useCallback}from"react";import{assertNever,isResource,parseReference}from"@medplum/core";var BOOKABLE_ACTOR_TYPES=["Practitioner","Location","Device"];function isBookableActorType(value){return BOOKABLE_ACTOR_TYPES.includes(value)}function getActorType(actor){return isResource(actor)?actor.resourceType:parseReference(actor)[0]}function getActorTypeLabel(resourceType){switch(resourceType){case"Device":return"Device";case"HealthcareService":return"Healthcare Service";case"Location":return"Room";case"Patient":return"Patient";case"Practitioner":return"Provider";case"PractitionerRole":return"Practitioner Role";case"RelatedPerson":return"Related Person"}return assertNever(resourceType)}var REQUIRED_ACTOR_TYPES=new Set(["Practitioner"]);function isActorTypeRequired(actorType){return REQUIRED_ACTOR_TYPES.has(actorType)}import{assertNever as assertNever2,getDisplayString,getReferenceString as getReferenceString2,isDefined as isDefined2,lazy,serviceTypeIncludesService}from"@medplum/core";import{getReferenceString,isDefined}from"@medplum/core";var MAX_FIND_WINDOW_DAYS=31,MS_PER_DAY=1440*60*1e3,MAX_LISTED_DAYS=366,formatters=new Map;function getFormatter(key,options,locale){let formatter=formatters.get(key);return formatter||(formatter=new Intl.DateTimeFormat(locale,options),formatters.set(key,formatter)),formatter}function getZonedParts(date,timezone){let parts=getFormatter(`parts:${timezone??""}`,{timeZone:timezone,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23"},"en-US").formatToParts(date),read=type=>Number(parts.find(p=>p.type===type)?.value);return{year:read("year"),month:read("month"),day:read("day"),hour:read("hour"),minute:read("minute")}}function formatZonedTime(date,timezone,options){return getFormatter(`time:${timezone??""}${options?.withTimezone?":named":""}`,{timeZone:timezone,hour:"numeric",minute:"2-digit",timeZoneName:options?.withTimezone?TIMEZONE_NAME_STYLE:void 0}).format(date)}function formatDayHeading(date){return getFormatter("dayHeading",{weekday:"long",month:"long",day:"numeric"}).format(date)}function getTimezoneOffsetMs(instant,timezone){let{year,month,day,hour,minute}=getZonedParts(instant,timezone);return Date.UTC(year,month-1,day,hour,minute)-Math.floor(instant.getTime()/6e4)*6e4}function getBrowserTimezone(){return getFormatter("resolved",{}).resolvedOptions().timeZone}var TIMEZONE_NAME_STYLE="shortGeneric",TIMEZONE_LABEL_INSTANT=new Date(0);function formatTimezoneLabel(timezone){return getFormatter(`zoneName:${timezone??""}`,{timeZone:timezone,timeZoneName:TIMEZONE_NAME_STYLE}).formatToParts(TIMEZONE_LABEL_INSTANT).find(part=>part.type==="timeZoneName")?.value??""}function isViewerTimezone(timezone,viewer){return!timezone||timezone===(viewer??getBrowserTimezone())}function parseZonedTime(day,time,timezone){let match=/^(\d{1,2}):(\d{2})$/.exec(time.trim());if(!match)return;let hour=Number(match[1]),minute=Number(match[2]);if(hour>23||minute>59)return;if(!timezone)return new Date(day.getFullYear(),day.getMonth(),day.getDate(),hour,minute);let wallClock=Date.UTC(day.getFullYear(),day.getMonth(),day.getDate(),hour,minute),guess=getTimezoneOffsetMs(new Date(wallClock),timezone),offset3=getTimezoneOffsetMs(new Date(wallClock-guess),timezone);return new Date(wallClock-offset3)}function filterByTimeOfDay(appointments,timeOfDay,timezone){return timeOfDay==="any"?[...appointments]:appointments.filter(appointment=>{if(!appointment.start)return!1;let{hour}=getZonedParts(new Date(appointment.start),timezone);return timeOfDay==="morning"?hour<12:hour>=12})}function groupAppointmentsByDay(appointments,timezone,searched,actorResources){let days=new Map;for(let appointment of appointments){if(!appointment.start)continue;let dayKey=getZonedDayKey(new Date(appointment.start),timezone),groups=days.get(dayKey);groups||(groups=new Map,days.set(dayKey,groups));let groupKey=getActorGroupKey(appointment),group=groups.get(groupKey);group?group.push(appointment):groups.set(groupKey,[appointment])}for(let day of enumerateDateRange(searched??{},MAX_LISTED_DAYS)){let key=getDayKey(day.getFullYear(),day.getMonth()+1,day.getDate());days.has(key)||days.set(key,new Map)}return[...days.entries()].sort(([left],[right])=>left.localeCompare(right)).map(([dayKey,groups])=>({key:dayKey,date:parseDayKey(dayKey),groups:[...groups.entries()].map(([groupKey,groupAppointments])=>toSlotGroup(groupKey,groupAppointments,actorResources)).sort((left,right)=>left.key.localeCompare(right.key))}))}function toSlotGroup(key,appointments,actorResources){let sorted=[...appointments].sort((left,right)=>(left.start??"").localeCompare(right.start??""));return{key,actors:getAppointmentActors(sorted[0],actorResources),durationMinutes:getDurationMinutes(sorted[0]),appointments:sorted}}function getAppointmentActors(appointment,actorResources){return(appointment?.participant??[]).map(participant=>participant.actor).filter(isDefined).map(actor=>{let reference=getReferenceString(actor);return(reference?actorResources?.get(reference):void 0)??actor})}function getActorGroupKey(appointment){return getActorsKey((appointment.participant??[]).map(participant=>participant.actor).filter(isDefined))}function getActorsKey(actors){return actors.map(actor=>getReferenceString(actor)).filter(isDefined).sort((left,right)=>left.localeCompare(right)).join("+")}function getDurationMinutes(appointment){if(!appointment?.start||!appointment.end)return 0;let start=new Date(appointment.start).getTime(),end=new Date(appointment.end).getTime();return Math.round((end-start)/6e4)}function getAppointmentKey(appointment){return`${appointment.start}/${appointment.end}/${getActorGroupKey(appointment)}`}function getZonedDayKey(date,timezone){let{year,month,day}=getZonedParts(date,timezone);return getDayKey(year,month,day)}function getDayKey(year,month,day){return`${year}-${pad(month)}-${pad(day)}`}function parseDayKey(key){let[year,month,day]=key.split("-").map(Number);return new Date(year,month-1,day)}function pad(value){return value.toString().padStart(2,"0")}function getNativeInputType(type){return import.meta.env.NODE_ENV==="test"?"text":type}function startOfDay(date){return new Date(date.getFullYear(),date.getMonth(),date.getDate())}function endOfDay(date){let result=new Date(date);return result.setHours(23,59,59,999),result}function addDays(date,days){let result=new Date(date);return result.setDate(result.getDate()+days),result}function startOfZonedDay(year,month,day,timezone){return parseZonedTime(new Date(year,month-1,day),"00:00",timezone)}function getZonedDayRange(day,timezone){let now=new Date,opens=startOfZonedDay(day.getFullYear(),day.getMonth()+1,day.getDate(),timezone)??day,start=opens>now?opens:now,parts=getZonedParts(start,timezone),nextMidnight=startOfZonedDay(parts.year,parts.month,parts.day+1,timezone);return{start,end:nextMidnight??addDays(new Date(start.getFullYear(),start.getMonth(),start.getDate()),1)}}function endOfMonth(date){return endOfDay(new Date(date.getFullYear(),date.getMonth()+1,0))}function enumerateDateRange(range,limit=MAX_FIND_WINDOW_DAYS){if(!range.start||!range.end)return range.start?[range.start]:[];let days=[];for(let day=range.start;day<=range.end&&days.length<limit;day=addDays(day,1))days.push(day);return days}function getFindWindowError(range){let{start,end}=range;if(!(!start||!end))return getDayCount(start,end)>MAX_FIND_WINDOW_DAYS?`Choose at most ${MAX_FIND_WINDOW_DAYS} days at a time.`:void 0}function getDayCount(start,end){return Math.ceil((end.getTime()-start.getTime())/MS_PER_DAY)}function getCandidateActor(candidate){return candidate.schedule.actor[0]}function getCandidateDisplay(candidate){let actor=getCandidateActor(candidate);return getActorResourceName(candidate.actorResource)??actor.display??actor.reference??`Schedule/${candidate.schedule.id}`}function getActorResourceName(resource){if(!resource)return;let display=getDisplayString(resource);return display===getReferenceString2(resource)?void 0:display}var nextRequirementId=0;function createActorRequirement(candidates=[]){return nextRequirementId++,{id:`requirement-${nextRequirementId}`,candidates}}var DEFAULT_COUNT=25;function getActorCriteria(actorType,query){switch(actorType){case"Practitioner":return{"actor:Practitioner.active:not":"false",...query?{"actor:Practitioner.name":query}:void 0};case"Location":return{"actor:Location.status:not":"inactive",...query?{"actor:Location.name":query}:void 0};case"Device":return{"actor:Device.status:not":"inactive",...query?{"actor:Device.device-name":query}:void 0};case"HealthcareService":case"Patient":case"PractitionerRole":case"RelatedPerson":throw new Error(`Got unsupported actor type ${actorType}`);default:return assertNever2(actorType)}}async function searchScheduleCandidates(medplum,service,options){let count=(options.count??DEFAULT_COUNT).toString(),actorCriteria=getActorCriteria(options.actorType,options.query),tokens=service?getServiceTypeTokens(service):[],typeCriteria=tokens.length>0?{"service-type":tokens.join(",")}:{},bundle=await medplum.search("Schedule",{...typeCriteria,...actorCriteria,"active:not":"false",_count:count,_include:"Schedule:actor"},{signal:options.signal}),actorsByReference=new Map,schedules=[];for(let entry of bundle.entry??[]){let resource=entry.resource;resource?.id&&(resource.resourceType==="Schedule"?schedules.push(resource):actorsByReference.set(`${resource.resourceType}/${resource.id}`,resource))}let found=schedules.map(schedule=>toScheduleCandidate(schedule,service,actorsByReference)).filter(isDefined2);return(await filterCandidatesByLocation(medplum,found,options.location,{signal:options.signal})).sort((left,right)=>getCandidateDisplay(left).localeCompare(getCandidateDisplay(right)))}function getServiceTypeTokens(service){let tokens=(service.type??[]).flatMap(concept=>concept.coding??[]).filter(coding=>coding.code).map(coding=>coding.system?`${coding.system}|${coding.code}`:coding.code);return[...new Set(tokens)]}function toScheduleCandidate(schedule,service,actors){if(schedule.active===!1||service&&!serviceTypeIncludesService(schedule.serviceType,service)||schedule.actor.length!==1)return;let actor=schedule.actor[0],referenceStr=actor.reference;if(!(!referenceStr||!isBookableActorType(getActorType(actor))))return{schedule,actorResource:actors.get(referenceStr)}}var MAX_LOCATION_DEPTH=4;async function filterCandidatesByLocation(medplum,candidates,location,options){let locationReference=location&&getReferenceString2(location);if(!locationReference)return[...candidates];let getRoles=lazy(()=>searchRolesByPractitioner(medplum,candidates,options)),verdicts=await Promise.all(candidates.map(async candidate=>isCandidateAtLocation(candidate,medplum,locationReference,getRoles,options)));return candidates.filter((_,index2)=>verdicts[index2])}async function searchRolesByPractitioner(medplum,candidates,options){let byPractitioner=new Map,references=[...new Set(candidates.filter(candidate=>getActorType(getCandidateActor(candidate))==="Practitioner").map(candidate=>getCandidateActor(candidate).reference))];if(references.length===0)return byPractitioner;let roles;try{roles=await medplum.searchResources("PractitionerRole",{practitioner:references.join(","),"active:not":"false",_count:"1000"},{signal:options?.signal})}catch{return byPractitioner}for(let role of roles){let reference=role.practitioner?.reference;if(!reference)continue;let held=byPractitioner.get(reference);held?held.push(role):byPractitioner.set(reference,[role])}return byPractitioner}async function isCandidateAtLocation(candidate,medplum,locationReference,getRoles,options){let actor=candidate.actorResource,actorReference=getCandidateActor(candidate),actorType=getActorType(actorReference);switch(actorType){case"Location":return isWithinLocation(medplum,actorReference.reference,locationReference,options);case"Device":{let device=actor?.resourceType==="Device"?actor:void 0;return isWithinLocation(medplum,device?.location?.reference,locationReference,options)}case"Practitioner":return isPractitionerAtLocation(actorReference.reference,locationReference,getRoles);case"HealthcareService":case"Patient":case"PractitionerRole":case"RelatedPerson":return!0;default:return assertNever2(actorType)}}async function isPractitionerAtLocation(actorReference,locationReference,getRoles){let roles=await getRoles(),practiceLocations=((actorReference?roles.get(actorReference):void 0)??[]).flatMap(role=>role.location??[]);return practiceLocations.length===0?!0:practiceLocations.some(roleLocation=>roleLocation.reference===locationReference)}async function isWithinLocation(medplum,reference,locationReference,options){if(!reference)return!0;let current=reference;for(let depth=0;depth<MAX_LOCATION_DEPTH;depth++){if(current===locationReference)return!0;let location=await readLocation(medplum,current,options);if(!location)return!0;let parent=location.partOf?.reference;if(!parent)return!1;current=parent}return!0}async function readLocation(medplum,reference,options){try{return await medplum.readReference({reference},{signal:options?.signal})}catch{return}}function getSelectedCandidates(selections){return getRequirements(selections).flatMap(requirement=>[...requirement.candidates])}function getRequirements(selections){return BOOKABLE_ACTOR_TYPES.flatMap(actorType=>selections[actorType]??[])}function getFilledRequirements(selections){return getRequirements(selections).filter(requirement=>requirement.candidates.length>0)}function getSelectedActorResources(selections){let resources=new Map;for(let candidate of getSelectedCandidates(selections)){let reference=getReferenceString2(getCandidateActor(candidate));reference&&candidate.actorResource&&resources.set(reference,candidate.actorResource)}return resources}function toScheduleReference(candidate){return{reference:`Schedule/${candidate.schedule.id}`}}var MAX_ACTOR_COMBINATIONS=100,listAlternatives=new Intl.ListFormat("en",{type:"disjunction"});function getSelectionError(selections){let missing=[...REQUIRED_ACTOR_TYPES].find(actorType=>!(selections[actorType]??[]).some(requirement=>requirement.candidates.length>0));if(missing)return{message:`Choose at least one ${getActorTypeLabel(missing).toLowerCase()} first.`,severity:"incomplete"};if(countActorCombinations(selections)>MAX_ACTOR_COMBINATIONS)return{message:`Too many combinations to search at once. Remove a few ${listAlternatives.format(getSelectedActorTypes(selections).map(getActorTypePluralLabel))} to find a time.`,severity:"invalid"};if(getActorCombinations(selections).length===0)return{message:"Nobody can fill every row at once.",severity:"invalid"}}function getSelectedActorTypes(selections){return BOOKABLE_ACTOR_TYPES.filter(actorType=>(selections[actorType]??[]).some(requirement=>requirement.candidates.length>0))}function getActorTypePluralLabel(actorType){return`${getActorTypeLabel(actorType).toLowerCase()}s`}function getUnsatisfiableRows(selections){let actorType=BOOKABLE_ACTOR_TYPES.find(candidateType=>{let alone={[candidateType]:selections[candidateType]};return getFilledRequirements(alone).length>0&&getActorCombinations(alone).length===0});return actorType&&{actorType,message:"Name someone else in one of them."}}function countActorCombinations(selections){let requirements=getFilledRequirements(selections);return requirements.length===0?0:requirements.reduce((total,requirement)=>total*requirement.candidates.length,1)}function getActorCombinations(selections){let requirements=getFilledRequirements(selections);if(requirements.length===0)return[];let combinations=cartesianProduct(requirements.map(requirement=>requirement.candidates)).filter(chosen=>!hasRepeatedActor(chosen)).map(toActorCombination),byKey=new Map;for(let combination of combinations)byKey.has(combination.key)||byKey.set(combination.key,combination);return[...byKey.values()]}function cartesianProduct(lists){return lists.reduce((tuples,list)=>tuples.flatMap(tuple=>list.map(item=>[...tuple,item])),[[]])}function hasRepeatedActor(candidates){let actors=candidates.map(candidate=>getCandidateActor(candidate).reference);return new Set(actors).size!==actors.length}function toActorCombination(candidates){let actors=candidates.map(getCandidateActor);return{key:getActorsKey(actors),label:candidates.map(getCandidateDisplay).join(" \xB7 "),actors,schedules:candidates.map(toScheduleReference)}}import{Stack,Text}from"@mantine/core";import{jsx,jsxs}from"react/jsx-runtime";function AppointmentOptionRow(props){return jsxs(Stack,{gap:0,children:[jsx(Text,{size:"sm",children:props.label}),props.detail&&jsx(Text,{size:"xs",c:"dimmed",children:props.detail})]})}import{Fragment,jsx as jsx2,jsxs as jsxs2}from"react/jsx-runtime";function AppointmentActorSelect(props){let{actorType,service,location,defaultValue,onChange,error,disabled}=props,medplum=useMedplum(),resolvedService=useResource(service),locationReference=location&&getReferenceString3(location),lowercaseLabel=getActorTypeLabel(actorType).toLowerCase(),label=props.label??getActorTypeLabel(actorType),required=props.required??isActorTypeRequired(actorType),placeholder=props.placeholder??`Search ${lowercaseLabel}s`,search=useCallback(async(query,signal)=>resolvedService?searchScheduleCandidates(medplum,resolvedService,{actorType,query,location:locationReference?{reference:locationReference}:void 0,signal}):[],[medplum,resolvedService,locationReference,actorType]),handleChange=useCallback(candidates=>onChange(candidates),[onChange]);return jsx2(AsyncAutocomplete,{name:actorType,label,required,withAsterisk:props.withAsterisk,description:props.description,placeholder,error,disabled,defaultValue:defaultValue?[...defaultValue]:void 0,toOption,loadOptions:search,itemComponent:CandidateItem,emptyComponent:EMPTY_COMPONENTS[actorType],onChange:handleChange})}var EMPTY_COMPONENTS=Object.fromEntries(BOOKABLE_ACTOR_TYPES.map(actorType=>{let noun=getActorTypeLabel(actorType).toLowerCase();return[actorType,()=>jsxs2(Fragment,{children:["No ",noun,"s found"]})]}));function toOption(candidate){return{value:candidate.schedule.id,label:getCandidateDisplay(candidate),resource:candidate}}function CandidateItem(props){return jsx2(AppointmentOptionRow,{label:props.label,detail:props.resource.schedule.comment})}import{ActionIcon,Box,Button,Group,Input,Stack as Stack2,Text as Text2}from"@mantine/core";import{forwardRef,createElement}from"react";var defaultAttributes={outline:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"},filled:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none"}};var createReactComponent=(type,iconName,iconNamePascal,iconNode)=>{let Component5=forwardRef(({color="currentColor",size=24,stroke=2,title,className,children,...rest},ref)=>createElement("svg",{ref,...defaultAttributes[type],width:size,height:size,className:["tabler-icon",`tabler-icon-${iconName}`,className].join(" "),...type==="filled"?{fill:color}:{strokeWidth:stroke,stroke:color},...rest},[title&&createElement("title",{key:"svg-title"},title),...iconNode.map(([tag,attrs])=>createElement(tag,attrs)),...Array.isArray(children)?children:[children]]));return Component5.displayName=`${iconNamePascal}`,Component5};var __iconNode=[["path",{d:"M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0",key:"svg-0"}],["path",{d:"M12 8v4",key:"svg-1"}],["path",{d:"M12 16h.01",key:"svg-2"}]],IconAlertCircle=createReactComponent("outline","alert-circle","AlertCircle",__iconNode);var __iconNode2=[["path",{d:"M11.5 21h-5.5a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v4.5",key:"svg-0"}],["path",{d:"M16 3v4",key:"svg-1"}],["path",{d:"M8 3v4",key:"svg-2"}],["path",{d:"M4 11h16",key:"svg-3"}],["path",{d:"M15 18a3 3 0 1 0 6 0a3 3 0 1 0 -6 0",key:"svg-4"}],["path",{d:"M20.2 20.2l1.8 1.8",key:"svg-5"}]],IconCalendarSearch=createReactComponent("outline","calendar-search","CalendarSearch",__iconNode2);var __iconNode3=[["path",{d:"M5 12l5 5l10 -10",key:"svg-0"}]],IconCheck=createReactComponent("outline","check","Check",__iconNode3);var __iconNode4=[["path",{d:"M6 9l6 6l6 -6",key:"svg-0"}]],IconChevronDown=createReactComponent("outline","chevron-down","ChevronDown",__iconNode4);var __iconNode5=[["path",{d:"M15 6l-6 6l6 6",key:"svg-0"}]],IconChevronLeft=createReactComponent("outline","chevron-left","ChevronLeft",__iconNode5);var __iconNode6=[["path",{d:"M9 6l6 6l-6 6",key:"svg-0"}]],IconChevronRight=createReactComponent("outline","chevron-right","ChevronRight",__iconNode6);var __iconNode7=[["path",{d:"M10.585 10.587a2 2 0 0 0 2.829 2.828",key:"svg-0"}],["path",{d:"M16.681 16.673a8.717 8.717 0 0 1 -4.681 1.327c-3.6 0 -6.6 -2 -9 -6c1.272 -2.12 2.712 -3.678 4.32 -4.674m2.86 -1.146a9.055 9.055 0 0 1 1.82 -.18c3.6 0 6.6 2 9 6c-.666 1.11 -1.379 2.067 -2.138 2.87",key:"svg-1"}],["path",{d:"M3 3l18 18",key:"svg-2"}]],IconEyeOff=createReactComponent("outline","eye-off","EyeOff",__iconNode7);var __iconNode8=[["path",{d:"M10 12a2 2 0 1 0 4 0a2 2 0 0 0 -4 0",key:"svg-0"}],["path",{d:"M21 12c-2.4 4 -5.4 6 -9 6c-3.6 0 -6.6 -2 -9 -6c2.4 -4 5.4 -6 9 -6c3.6 0 6.6 2 9 6",key:"svg-1"}]],IconEye=createReactComponent("outline","eye","Eye",__iconNode8);var __iconNode9=[["path",{d:"M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0",key:"svg-0"}],["path",{d:"M12 9h.01",key:"svg-1"}],["path",{d:"M11 12h1v4h1",key:"svg-2"}]],IconInfoCircle=createReactComponent("outline","info-circle","InfoCircle",__iconNode9);var __iconNode10=[["path",{d:"M5 12l14 0",key:"svg-0"}]],IconMinus=createReactComponent("outline","minus","Minus",__iconNode10);var __iconNode11=[["path",{d:"M12 5l0 14",key:"svg-0"}],["path",{d:"M5 12l14 0",key:"svg-1"}]],IconPlus=createReactComponent("outline","plus","Plus",__iconNode11);var __iconNode12=[["path",{d:"M18 6l-12 12",key:"svg-0"}],["path",{d:"M6 6l12 12",key:"svg-1"}]],IconX=createReactComponent("outline","x","X",__iconNode12);var __iconNode13=[["path",{d:"M18.364 4.636a9 9 0 0 1 .203 12.519l-.203 .21l-4.243 4.242a3 3 0 0 1 -4.097 .135l-.144 -.135l-4.244 -4.243a9 9 0 0 1 12.728 -12.728zm-6.364 3.364a3 3 0 1 0 0 6a3 3 0 0 0 0 -6",key:"svg-0"}]],IconMapPinFilled=createReactComponent("filled","map-pin-filled","MapPinFilled",__iconNode13);import{useCallback as useCallback2}from"react";import{Fragment as Fragment2,jsx as jsx3,jsxs as jsxs3}from"react/jsx-runtime";var CONTROL_SIZE="lg";function AppointmentActorSelections(props){let{value,service,location,disabled,errors,onChange}=props,changeRequirements=useCallback2((actorType,requirements)=>{onChange({...value,[actorType]:requirements})},[onChange,value]);return jsx3(Fragment2,{children:BOOKABLE_ACTOR_TYPES.map(actorType=>jsx3(ActorTypeRows,{actorType,requirements:value[actorType],service,location,disabled,error:errors?.[actorType],onChange:changeRequirements},actorType))})}function ActorTypeRows(props){let{actorType,service,location,disabled,error,onChange}=props,label=getActorTypeLabel(actorType),lowercaseLabel=label.toLowerCase(),required=isActorTypeRequired(actorType),rows=props.requirements?.length?props.requirements:[getBlankRequirement(actorType)],several=rows.length>1,canAddAnother=(rows.at(-1)?.candidates.length??0)>0;function change(next){onChange(actorType,next)}return jsxs3(Stack2,{gap:4,role:"group","aria-label":label,children:[several&&jsx3(Input.Label,{labelElement:"div",required,children:label}),rows.map((row,index2)=>jsxs3(Group,{align:"flex-end",wrap:"nowrap",gap:"xs",children:[jsx3(Box,{flex:1,miw:0,children:jsx3(AppointmentActorSelect,{actorType,service,location,disabled,label:several?jsx3(RowLabel,{index:index2,label}):label,placeholder:row.candidates.length>0?"or\u2026":`Search ${lowercaseLabel}s`,required,withAsterisk:!several&&required,defaultValue:row.candidates,onChange:candidates=>change(rows.map(held=>held.id===row.id?{...held,candidates}:held))})}),several&&jsx3(ActionIcon,{variant:"subtle",color:"gray",radius:"xl",size:CONTROL_SIZE,disabled,"aria-label":`Remove ${lowercaseLabel} ${index2+1}`,onClick:()=>change(rows.filter(held=>held.id!==row.id)),children:jsx3(IconX,{size:16,stroke:1.8})})]},row.id)),canAddAnother&&jsxs3(Button,{variant:"subtle",size:"compact-sm",leftSection:jsx3(IconPlus,{size:14,stroke:1.8}),disabled,style:{alignSelf:"flex-start"},onClick:()=>change([...rows,createActorRequirement()]),children:["Add another ",lowercaseLabel]}),error&&jsx3(Text2,{size:"xs",c:"red",role:"alert",children:error})]})}function RowLabel(props){let{index:index2,label}=props;return jsxs3(Fragment2,{children:[index2>0&&jsxs3(Fragment2,{children:[jsx3(Text2,{span:!0,c:"teal",fw:600,inherit:!0,children:"And"})," "]}),jsxs3(Text2,{span:!0,c:"dimmed",fw:400,inherit:!0,children:[label," ",index2+1]})]})}function getBlankRequirement(actorType){return{id:`${actorType}-blank`,candidates:[]}}import{isDefined as isDefined5}from"@medplum/core";import{useMedplum as useMedplum4}from"@medplum/react-hooks";import{useCallback as useCallback6}from"react";import{Alert,Button as Button3,Checkbox,Group as Group3,Loader,Pill,Stack as Stack5,Text as Text5,TextInput}from"@mantine/core";import{createReference,formatDate,getIdentifier,getIdentifierByType,getReferenceString as getReferenceString8,getSchedulingRequirements,getSchedulingTimezone,MRN_IDENTIFIER_TYPE,normalizeErrorString as normalizeErrorString2,REQUIRES_DIAGNOSIS_CODE as REQUIRES_DIAGNOSIS_CODE2,REQUIRES_MEDICAL_NECESSITY_CODE as REQUIRES_MEDICAL_NECESSITY_CODE2,REQUIRES_PROCEDURE_CODE as REQUIRES_PROCEDURE_CODE2,SchedulingMedicalNecessityURI}from"@medplum/core";import{CalendarDateInput,ResourceInput,ResourceName as ResourceName2,ValueSetAutocomplete}from"@medplum/react";import{Fragment as Fragment3,useCallback as useCallback5,useEffect as useEffect2,useMemo as useMemo2,useRef,useState as useState3}from"react";import{Stack as Stack4,Text as Text4,Title}from"@mantine/core";import{Button as Button2,Group as Group2,Paper,Stack as Stack3,Text as Text3}from"@mantine/core";import{getReferenceString as getReferenceString4}from"@medplum/core";import{ResourceName}from"@medplum/react";var AppointmentFinder_default={timeGrid:"AppointmentFinder_timeGrid",layout:"AppointmentFinder_layout",form:"AppointmentFinder_form",results:"AppointmentFinder_results",codePill:"AppointmentFinder_codePill",requiredLabel:"AppointmentFinder_requiredLabel"};import{jsx as jsx4,jsxs as jsxs4}from"react/jsx-runtime";function ActorLabel(props){let label=getActorTypeLabel(getActorType(props.actor));return jsxs4(Stack3,{gap:2,children:[jsx4(Text3,{size:"xs",c:"dimmed",tt:"uppercase",children:label}),jsx4(Text3,{size:"sm",fw:500,children:jsx4(ResourceName,{value:props.actor,link:!1,inherit:!0})})]})}function AppointmentSlotGroupCard(props){let{group,onSelectAppointment,timezone,viewerTimezone,selected,disabled}=props,withTimezone=!isViewerTimezone(timezone,viewerTimezone);return jsxs4(Paper,{withBorder:!0,p:"md","data-testid":`slot-group-${group.key}`,children:[jsxs4(Group2,{justify:"space-between",align:"flex-start",wrap:"nowrap",mb:"sm",children:[jsx4(Group2,{gap:"lg",align:"flex-start",wrap:"wrap",children:group.actors.map(actor=>jsx4(ActorLabel,{actor},getReferenceString4(actor)))}),group.durationMinutes>0&&jsxs4(Text3,{size:"xs",c:"dimmed",style:{whiteSpace:"nowrap"},children:[group.durationMinutes," min visit"]})]}),jsx4(Group2,{gap:"xs",className:AppointmentFinder_default.timeGrid,children:group.appointments.map(appointment=>jsx4(Button2,{variant:selected===appointment?"filled":"outline",size:"sm",disabled,onClick:()=>onSelectAppointment(appointment),children:appointment.start?formatZonedTime(new Date(appointment.start),timezone,{withTimezone}):""},appointment.start))})]})}import{jsx as jsx5,jsxs as jsxs5}from"react/jsx-runtime";function AppointmentDayTimes(props){let{date,groups,onSelectAppointment,timezone,viewerTimezone,selected}=props;return jsxs5(Stack4,{gap:"xs",children:[jsx5(Title,{order:4,children:formatDayHeading(date)}),groups.length===0&&jsx5(Text4,{c:"dimmed",children:"No times are offered on this day."}),groups.map(group=>jsx5(AppointmentSlotGroupCard,{group,timezone,viewerTimezone,selected,onSelectAppointment},group.key))]})}import{CPT,HTTP_HL7_ORG,REQUIRES_DIAGNOSIS_CODE,REQUIRES_MEDICAL_NECESSITY_CODE,REQUIRES_PROCEDURE_CODE}from"@medplum/core";import{valueSetElementToCoding}from"@medplum/react";var DEFAULT_PROCEDURE_VALUE_SET=`${CPT}/vs`,DEFAULT_DIAGNOSIS_VALUE_SET=`${HTTP_HL7_ORG}/fhir/sid/icd-10-cm/vs`,EMPTY_REQUIREMENT_VALUES={procedure:[],diagnosis:[],medicalNecessity:!1},REQUIREMENT_ANSWERS={[REQUIRES_PROCEDURE_CODE]:values=>values.procedure.length>0,[REQUIRES_DIAGNOSIS_CODE]:values=>values.diagnosis.length>0,[REQUIRES_MEDICAL_NECESSITY_CODE]:values=>values.medicalNecessity};function isRequirementAnswered(requirement,values){return REQUIREMENT_ANSWERS[requirement](values)}function hasRequiredValues(values,requirements){return[...requirements].every(requirement=>isRequirementAnswered(requirement,values))}function toCodings(elements){return elements.map(element=>valueSetElementToCoding(element)).filter(coding=>!!coding.code)}import{formatCodeableConcept,getDisplayString as getDisplayString2,getReferenceString as getReferenceString6,hasSchedulingParameters}from"@medplum/core";import{AsyncAutocomplete as AsyncAutocomplete2}from"@medplum/react";import{useMedplum as useMedplum2}from"@medplum/react-hooks";import{useCallback as useCallback3}from"react";import{getExtensions,getReferenceString as getReferenceString5,isDefined as isDefined3,schedulingDurationToMinutes,SchedulingParametersURI}from"@medplum/core";function getServiceDurationMinutes(service){return getExtensions(service,[SchedulingParametersURI,"duration"]).map(subextension=>schedulingDurationToMinutes(subextension.valueDuration)).find(isDefined3)}function isServiceKeptAtLocation(service,location){let reference=location&&getReferenceString5(location),held=service.location??[];return!reference||held.length===0?!0:held.some(site=>site.reference===reference)}import{jsx as jsx6}from"react/jsx-runtime";var SERVICE_PAGE_SIZE=25,SERVICE_SEARCH_CRITERIA={"active:not":"false",_count:String(SERVICE_PAGE_SIZE),_sort:"name"};function AppointmentServiceSelect(props){let{location,defaultValue,onChange,label="Visit type",error,disabled}=props,medplum=useMedplum2(),locationReference=location&&getReferenceString6(location),loadOptions=useCallback3(async(input,signal)=>{let criteria=new URLSearchParams(SERVICE_SEARCH_CRITERIA);input&&criteria.set("name",input);let searches=locationReference?[withParam(criteria,"location",locationReference),withParam(criteria,"location:missing","true")]:[criteria],services=(await Promise.all(searches.map(async params=>medplum.searchResources("HealthcareService",params,{signal})))).flatMap(page=>page.filter(hasSchedulingParameters));return services.sort((left,right)=>(left.name??"").localeCompare(right.name??"")),services.slice(0,SERVICE_PAGE_SIZE)},[medplum,locationReference]),handleChange=useCallback3(services=>onChange(services[0]),[onChange]);return jsx6(AsyncAutocomplete2,{name:"service",label,placeholder:"Search visit types",required:!0,maxValues:1,error,disabled,defaultValue,toOption:toOption2,loadOptions,itemComponent:ServiceItem,onChange:handleChange})}function withParam(criteria,name,value){let params=new URLSearchParams(criteria);return params.set(name,value),params}function toOption2(service){return{value:service.id,label:getDisplayString2(service),resource:service}}function ServiceItem(props){return jsx6(AppointmentOptionRow,{label:props.label,detail:formatServiceDetail(props.resource)})}function formatServiceDetail(service){let category=formatCodeableConcept(service.type?.[0]),duration=getServiceDurationMinutes(service);return[category,duration!==void 0?`${duration} min`:void 0].filter(Boolean).join(" \xB7 ")||void 0}import{useCallback as useCallback4,useMemo,useState as useState2}from"react";import{getReferenceString as getReferenceString7,isDefined as isDefined4,isError,normalizeErrorString}from"@medplum/core";import{useMedplum as useMedplum3}from"@medplum/react-hooks";import{useEffect,useState}from"react";var DEFAULT_COUNT2=20,URL_SEPARATOR=`
|
|
2
|
+
`;function useProposedAppointments(options){let{service,combinations,range,count=DEFAULT_COUNT2}=options,medplum=useMedplum3(),[answered,setAnswered]=useState(NOTHING_ASKED),{start,end}=range,windowError=getFindWindowError(range),serviceReference=service&&getReferenceString7(service),urls=serviceReference&&start&&end&&!windowError?combinations.map(combination=>buildFindUrl(medplum,serviceReference,combination,start,end,count)):[],urlsKey=urls.join(URL_SEPARATOR),stale=answered.key!==urlsKey;return useEffect(()=>{if(!urlsKey)return;let controller=new AbortController,requests=urlsKey.split(URL_SEPARATOR);return Promise.allSettled(requests.map(async url=>medplum.get(url,{signal:controller.signal}))).then(results=>{if(controller.signal.aborted)return;let failure=results.find(result=>result.status==="rejected");setAnswered(failure&&results.every(result=>result.status==="rejected")?{key:urlsKey,appointments:[],error:toError(failure.reason)}:{key:urlsKey,appointments:collectAppointments(results),error:void 0})}).catch(reason=>{controller.signal.aborted||setAnswered({key:urlsKey,appointments:[],error:toError(reason)})}),()=>controller.abort()},[medplum,urlsKey]),{appointments:urls.length===0?NOTHING_ASKED.appointments:answered.appointments,requestCount:urls.length,loading:urls.length>0&&stale,error:stale?void 0:answered.error,windowError}}var NOTHING_ASKED={key:"",appointments:[],error:void 0};function toError(reason){return isError(reason)?reason:new Error(normalizeErrorString(reason),{cause:reason})}function buildFindUrl(medplum,serviceReference,combination,start,end,count){let url=medplum.fhirUrl("Appointment","$find");url.searchParams.set("start",start.toISOString()),url.searchParams.set("end",end.toISOString()),url.searchParams.set("service-type-reference",serviceReference);for(let schedule of combination.schedules)schedule.reference&&url.searchParams.append("schedule",schedule.reference);return url.searchParams.set("_count",count.toString()),url.toString()}function collectAppointments(results){return results.filter(result=>result.status==="fulfilled").flatMap(result=>(result.value.entry??[]).map(entry=>entry.resource).filter(isDefined4))}var MORE_DAYS=2,TIMES_PER_DAY=65,COMBINATION_WAVE=6;function useDaySearch(options){let{service,combinations,timezone,defaultStart,actorResources,onResultsReplaced}=options,[daySearch,setDaySearch]=useState2(()=>openDaySearch(defaultStart??new Date)),[combinationLimit,setCombinationLimit]=useState2(COMBINATION_WAVE),searchedCombinations=useMemo(()=>combinations.slice(0,combinationLimit),[combinations,combinationLimit]),siteWindow=useMemo(()=>toSiteWindow(daySearch.range,timezone),[daySearch.range,timezone]),search=useProposedAppointments({service,combinations:searchedCombinations,range:siteWindow,count:TIMES_PER_DAY*getDayCount(siteWindow.start,siteWindow.end)}),selectedDayRange=useMemo(()=>({start:daySearch.original.start,end:daySearch.range.end}),[daySearch.original.start,daySearch.range.end]),{timeResultsByDay,hasTimes}=useMemo(()=>{let times=search.loading?daySearch.found:[...daySearch.found,...search.appointments],grouped=groupAppointmentsByDay(times,timezone,selectedDayRange,actorResources);return{timeResultsByDay:grouped,hasTimes:grouped.some(day=>day.groups.length>0)}},[search.loading,search.appointments,daySearch.found,timezone,selectedDayRange,actorResources]),chooseDayRange=useCallback4((start,end)=>{setDaySearch(openDaySearch(start,end)),onResultsReplaced?.()},[onResultsReplaced]),showMoreDays=useCallback4(()=>{setDaySearch(previous=>({original:previous.original,range:nextWindow(previous.range),found:[...previous.found,...search.appointments]}))},[search.appointments]),reset=useCallback4(()=>{setDaySearch(backToFirstWindow),setCombinationLimit(COMBINATION_WAVE)},[]),searchMoreCombinations=useCallback4(()=>{setCombinationLimit(limit=>limit+COMBINATION_WAVE),setDaySearch(reaskEveryDayOnShow),onResultsReplaced?.()},[onResultsReplaced]),loadingFirstDays=search.loading&&daySearch.range.start.getTime()===daySearch.original.start.getTime();return{selectedDayRange,timeResultsByDay,hasTimes,loadingFirstDays,loadingMoreDays:search.loading&&!loadingFirstDays,findRequestError:search.error,windowError:search.windowError,searchedCombinationCount:searchedCombinations.length,totalCombinationCount:combinations.length,hasMoreCombinations:combinations.length>searchedCombinations.length,searchMoreCombinations,chooseDayRange,showMoreDays,reset}}function backToFirstWindow(previous){return{original:previous.original,range:previous.original,found:[]}}function reaskEveryDayOnShow(previous){return{original:previous.original,range:{start:previous.original.start,end:previous.range.end},found:[]}}function floorToNow(date){let now=new Date;return date>now?date:now}function openDaySearch(start,end=start){let from=floorToNow(start),window2={start:from,end:endOfDay(end>from?end:from)};return{original:window2,range:window2,found:[]}}function toSiteWindow(days,timezone){return{start:getZonedDayRange(days.start,timezone).start,end:getZonedDayRange(days.end,timezone).end}}function nextWindow(range){let start=startOfDay(addDays(range.end,1));return{start,end:endOfDay(addDays(start,MORE_DAYS-1))}}import{Fragment as Fragment4,jsx as jsx7,jsxs as jsxs6}from"react/jsx-runtime";var LOCATION_SEARCH_CRITERIA={_count:"25",_sort:"name","physical-type:not":"ro,bd"},NO_SERVICE_BLOCKER={message:"Choose a visit type first.",severity:"incomplete"},PATIENT_SEARCH_CRITERIA={_count:"25",_sort:"name,birthdate"},NO_MARKED_DATES=[];function AppointmentProposalForm(props){let{defaultLocation,defaultService,defaultPatient,defaultStart,mrnSystem,onToggleTimeFinder,onChangeService,onChangeTime,procedureBinding=DEFAULT_PROCEDURE_VALUE_SET,diagnosisBinding=DEFAULT_DIAGNOSIS_VALUE_SET,onBook}=props,[location,setLocation]=useState3(defaultLocation),[service,setService]=useState3(defaultService),[selections,setSelections]=useState3({}),[month,setMonth]=useState3(defaultStart),[finding,setFinding]=useState3(!1),[chosen,setChosen]=useState3(void 0),[actorFieldsKey,setActorFieldsKey]=useState3(0),[serviceFieldKey,setServiceFieldKey]=useState3(0),[patient,setPatient]=useState3(defaultPatient),[requirementValues,setRequirementValues]=useState3(EMPTY_REQUIREMENT_VALUES),[booking,setBooking]=useState3(!1),[booked,setBooked]=useState3(!1),[bookError,setBookError]=useState3(void 0),selectionError=useMemo2(()=>getSelectionError(selections),[selections]),requirements=useMemo2(()=>getSchedulingRequirements(service),[service]),requirementsOutstanding=!hasRequiredValues(requirementValues,requirements),actorErrors=useMemo2(()=>{let unsatisfiable=getUnsatisfiableRows(selections);return unsatisfiable&&{[unsatisfiable.actorType]:unsatisfiable.message}},[selections]),searching=finding&&!selectionError,combinations=useMemo2(()=>searching?getActorCombinations(selections):[],[searching,selections]),timezone=useMemo2(()=>{let[first]=getSelectedCandidates(selections);return service?getSchedulingTimezone(service,first?.schedule,first?.actorResource):void 0},[service,selections]),clearChosen=useCallback5(()=>setChosen(void 0),[]),actorResources=useMemo2(()=>getSelectedActorResources(selections),[selections]),daySearch=useDaySearch({service,combinations,timezone,defaultStart,actorResources,onResultsReplaced:clearChosen}),{reset:resetDaySearch}=daySearch,settled=!daySearch.loadingFirstDays&&!daySearch.findRequestError&&!daySearch.windowError,chosenActors=getAppointmentActors(chosen,actorResources),reported=useRef(!1);useEffect2(()=>{reported.current!==searching&&(reported.current=searching,onToggleTimeFinder?.(searching))},[searching,onToggleTimeFinder]);let reportedTime=useRef(void 0);useEffect2(()=>{reportedTime.current!==chosen&&(reportedTime.current=chosen,onChangeTime?.(toRange(chosen)))},[chosen,onChangeTime]);let patientItem=useCallback5(option=>jsx7(AppointmentOptionRow,{label:option.label,detail:formatPatientDetail(option.resource,mrnSystem)}),[mrnSystem]);function toggleFinder(){setFinding(!finding)}let chooseResources=useCallback5(next=>{setSelections(next),setChosen(void 0),resetDaySearch()},[resetDaySearch]);function chooseService(next){setService(next),onChangeService?.(next),setRequirementValues(EMPTY_REQUIREMENT_VALUES),clearResources()}function chooseLocation(next){setLocation(next),clearResources(),service&&!isServiceKeptAtLocation(service,next)&&(setService(void 0),onChangeService?.(void 0),setServiceFieldKey(key=>key+1))}function clearResources(){setSelections({}),setChosen(void 0),setActorFieldsKey(key=>key+1),resetDaySearch()}function chooseTime(next){setChosen(next),setBooked(!1)}function choosePatient(next){setPatient(next),setBooked(!1)}function chooseRequirementValues(next){setRequirementValues(next),setBooked(!1)}async function bookAppointment(){if(!(!chosen||!patient||requirementsOutstanding)){setBooking(!0),setBookError(void 0);try{await onBook(buildBooking(chosen,patient,requirementValues,requirements)),setBooked(!0)}catch(error){setBookError(error)}finally{setBooking(!1)}}}return jsxs6("div",{className:AppointmentFinder_default.layout,children:[jsxs6(Stack5,{className:AppointmentFinder_default.form,gap:"sm",children:[jsx7(ResourceInput,{resourceType:"Location",name:"location",label:"Location",placeholder:"Any location",searchCriteria:LOCATION_SEARCH_CRITERIA,defaultValue:defaultLocation,onChange:chooseLocation}),jsx7(AppointmentServiceSelect,{location,defaultValue:service,onChange:chooseService},serviceFieldKey),jsx7(AppointmentActorSelections,{value:selections,service,location,disabled:!service,errors:actorErrors,onChange:chooseResources},`actors-${actorFieldsKey}`),jsx7(ChosenTime,{appointment:chosen,timezone,actors:chosenActors,searching,blockedBy:service?selectionError:NO_SERVICE_BLOCKER,onToggleFinder:toggleFinder}),searching&&jsxs6(Stack5,{gap:4,children:[jsx7(CalendarDateInput,{availableDates:NO_MARKED_DATES,allowUnavailableDates:!0,earliestDate:new Date,month,range:daySearch.selectedDayRange,onChangeMonth:setMonth,onClick:daySearch.chooseDayRange,onSelectRange:daySearch.chooseDayRange}),daySearch.windowError&&jsx7(Alert,{color:"yellow",children:daySearch.windowError})]}),jsx7(ResourceInput,{resourceType:"Patient",name:"patient",label:"Patient",placeholder:"Search patients by name",required:!0,searchCriteria:PATIENT_SEARCH_CRITERIA,defaultValue:defaultPatient,itemComponent:patientItem,onChange:choosePatient}),service&&requirements.size>0&&jsxs6(Fragment3,{children:[requirements.has(REQUIRES_PROCEDURE_CODE2)&&jsx7(ValueSetAutocomplete,{name:"procedure-code",label:"Procedure codes",required:!0,itemComponent:RequirementCodeItem,pillComponent:RequirementCodePill,binding:procedureBinding,onChange:elements=>chooseRequirementValues({...requirementValues,procedure:toCodings(elements)})}),requirements.has(REQUIRES_DIAGNOSIS_CODE2)&&jsx7(ValueSetAutocomplete,{name:"diagnosis-code",label:"Diagnosis codes",required:!0,itemComponent:RequirementCodeItem,pillComponent:RequirementCodePill,binding:diagnosisBinding,onChange:elements=>chooseRequirementValues({...requirementValues,diagnosis:toCodings(elements)})}),requirements.has(REQUIRES_MEDICAL_NECESSITY_CODE2)&&jsx7(Checkbox,{classNames:{label:AppointmentFinder_default.requiredLabel},label:"Medical necessity confirmed",required:!0,checked:requirementValues.medicalNecessity,onChange:event=>chooseRequirementValues({...requirementValues,medicalNecessity:event.currentTarget.checked})})]},service.id),bookError!==void 0&&jsx7(Alert,{color:"red",children:normalizeErrorString2(bookError)}),jsx7(Button3,{fullWidth:!0,disabled:!chosen||!patient||booked||requirementsOutstanding,loading:booking,onClick:bookAppointment,children:"Book appointment"})]}),searching&&jsxs6(Stack5,{className:AppointmentFinder_default.results,gap:"lg",children:[daySearch.loadingFirstDays&&jsx7(Loader,{size:"sm"}),daySearch.findRequestError&&jsx7(Alert,{color:"red",children:normalizeErrorString2(daySearch.findRequestError)}),!daySearch.loadingFirstDays&&daySearch.hasTimes&&daySearch.timeResultsByDay.map(day=>jsx7(AppointmentDayTimes,{date:day.date,groups:day.groups,timezone,selected:chosen,onSelectAppointment:chooseTime},day.key)),settled&&jsxs6(Fragment4,{children:[!daySearch.hasTimes&&jsx7(Text5,{c:"dimmed",ta:"center",children:daySearch.hasMoreCombinations?"No times yet for the options searched so far.":"No times are available for this selection."}),daySearch.hasMoreCombinations&&jsxs6(Stack5,{gap:4,children:[jsx7(Text5,{size:"xs",c:"dimmed",ta:"center",children:getSearchedOptionsHint(daySearch.searchedCombinationCount,daySearch.totalCombinationCount)}),jsx7(Button3,{variant:"subtle",onClick:daySearch.searchMoreCombinations,children:"Search more options"})]}),jsx7(Button3,{variant:"subtle",loading:daySearch.loadingMoreDays,onClick:daySearch.showMoreDays,children:"Show more days"})]})]})]})}function ChosenTime(props){let{appointment,timezone,actors,searching,blockedBy,onToggleFinder}=props;return jsxs6(Fragment4,{children:[appointment?.start&&jsx7(TextInput,{label:"Date & time",readOnly:!0,value:formatZonedDateTime(new Date(appointment.start),timezone),inputWrapperOrder:["label","input","description"],description:jsx7(ChosenTimeCommitment,{appointment,actors})}),jsxs6(Stack5,{gap:4,children:[jsx7(Button3,{variant:"outline",fullWidth:!0,leftSection:jsx7(IconCalendarSearch,{size:16,stroke:1.8}),disabled:!!blockedBy,onClick:onToggleFinder,children:getFinderLabel(searching,!!appointment)}),blockedBy&&jsx7(BlockerMessage,{blocker:blockedBy})]})]})}function BlockerMessage(props){let{message,severity}=props.blocker;return severity==="incomplete"?jsx7(Text5,{size:"xs",c:"dimmed",children:message}):jsxs6(Group3,{gap:6,wrap:"nowrap",children:[jsx7(IconAlertCircle,{size:16,stroke:1.8,color:"var(--mantine-color-error)",style:{flexShrink:0}}),jsx7(Text5,{size:"xs",c:"var(--mantine-color-error)",children:message})]})}function ChosenTimeCommitment(props){let{appointment,actors}=props,durationMinutes=getDurationMinutes(appointment);return jsxs6(Fragment4,{children:[durationMinutes>0&&`${durationMinutes} min visit`,actors.map((actor,index2)=>{let actorLabel=getActorTypeLabel(getActorType(actor));return jsxs6(Fragment3,{children:[(index2>0||durationMinutes>0)&&" \xB7 ",actorLabel,": ",jsx7(ResourceName2,{value:actor,link:!1,inherit:!0})]},getReferenceString8(actor))})]})}function getFinderLabel(searching,chosen){return searching?"Close time finder":chosen?"Change time":"Find a time"}function RequirementCodeItem(props){let{label,resource,active}=props;return jsxs6(Group3,{wrap:"nowrap",gap:"xs",children:[active&&jsx7(IconCheck,{size:12}),jsxs6(Text5,{size:"sm",children:[jsx7(Text5,{span:!0,fw:600,children:resource.code})," ",jsx7(Text5,{span:!0,children:label})]})]})}function RequirementCodePill(props){let{item,disabled,onRemove}=props,code=item.resource.code;return jsx7(Pill,{className:AppointmentFinder_default.codePill,withRemoveButton:!disabled,onRemove,title:item.label,children:code&&code!==item.label?`${code} \xB7 ${item.label}`:item.label})}function buildBooking(proposal,patient,values,requirements){let patientReference=getReferenceString8(patient),procedure=requirements.has(REQUIRES_PROCEDURE_CODE2)?values.procedure:[],diagnosis=requirements.has(REQUIRES_DIAGNOSIS_CODE2)?values.diagnosis:[],serviceType=[...proposal.serviceType??[],...procedure.map(coding=>({coding:[coding]}))],reasonCode=[...proposal.reasonCode??[],...diagnosis.map(coding=>({coding:[coding]}))],extension=[...proposal.extension??[],...requirements.has(REQUIRES_MEDICAL_NECESSITY_CODE2)?[{url:SchedulingMedicalNecessityURI,valueBoolean:values.medicalNecessity}]:[]];return{...proposal,participant:[...proposal.participant.filter(participant=>participant.actor?.reference!==patientReference),{actor:createReference(patient),required:"required",status:"needs-action"}],...serviceType.length>0&&{serviceType},...reasonCode.length>0&&{reasonCode},...extension.length>0&&{extension}}}function formatPatientDetail(patient,mrnSystem){let mrn=getMedicalRecordNumber(patient,mrnSystem);return[formatDate(patient.birthDate),mrn&&`MRN ${mrn}`].filter(Boolean).join(" \xB7 ")||void 0}function getMedicalRecordNumber(patient,mrnSystem){return getIdentifierByType(patient,MRN_IDENTIFIER_TYPE)??(mrnSystem?getIdentifier(patient,mrnSystem):void 0)}function toRange(appointment){if(!(!appointment?.start||!appointment.end))return{start:new Date(appointment.start),end:new Date(appointment.end)}}function getSearchedOptionsHint(searched,total){return`Showing times for ${searched} of ${total} ways of holding this visit.`}function formatZonedDateTime(value,timezone){return new Intl.DateTimeFormat(void 0,{timeZone:timezone,weekday:"long",month:"long",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:isViewerTimezone(timezone)?void 0:"shortGeneric"}).format(value)}import{jsx as jsx8}from"react/jsx-runtime";function AppointmentBookingForm(props){let{onBooked,...formProps}=props,medplum=useMedplum4(),book=useCallback6(async proposal=>{let written=await medplum.post(medplum.fhirUrl("Appointment","$book"),{resourceType:"Parameters",parameter:[{name:"appointment",resource:proposal}]}),booking=readBooking(written);medplum.notifyResourceModified({resourceType:"Appointment",operation:"create",id:booking.appointment.id,resource:booking.appointment});for(let slot of booking.slots)medplum.notifyResourceModified({resourceType:"Slot",operation:"create",id:slot.id,resource:slot});try{await onBooked(booking)}catch(error){console.error(error)}},[medplum,onBooked]);return jsx8(AppointmentProposalForm,{...formProps,onBook:book})}function readBooking(written){let resources=(written.entry??[]).map(entry=>entry.resource).filter(isDefined5),appointment=resources.find(resource=>resource.resourceType==="Appointment");if(!appointment)throw new Error("$book returned no appointment");return{appointment,slots:resources.filter(resource=>resource.resourceType==="Slot")}}function r(e){var t,f,n="";if(typeof e=="string"||typeof e=="number")n+=e;else if(typeof e=="object")if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(f=r(e[t]))&&(n&&(n+=" "),n+=f)}else for(f in e)e[f]&&(n&&(n+=" "),n+=f);return n}function clsx(){for(var e,t,f=0,n="",o=arguments.length;f<o;f++)(e=arguments[f])&&(t=r(e))&&(n&&(n+=" "),n+=t);return n}var clsx_default=clsx;import{useMemo as useMemo4}from"react";var NativeTemporal=globalThis.Temporal;var expectedPositive=(entityName,num)=>`Non-positive ${entityName}: ${num}`,expectedFinite=(entityName,num)=>`Non-finite ${entityName}: ${num}`,forbiddenBigIntToNumber=entityName=>`Cannot convert bigint to ${entityName}`,invalidObject="Invalid object",numberOutOfRange=(entityName,val,min,max)=>invalidEntity(entityName,val)+`; must be between ${min}-${max}`,invalidEntity=(fieldName,val)=>`Invalid ${fieldName}: ${val}`;var nanoInMicro=1e3,nanoInMilli=1e6,nanoInSec=1e9,nanoInMinute=6e10,nanoInHour=36e11;function normalizeOptions(options){return options===void 0?Object.create(null):requireObjectLike(options)}function toFiniteNumber(arg,entityName="number"){if(typeof arg=="bigint")throw new TypeError(forbiddenBigIntToNumber(entityName));if(arg=Number(arg),!Number.isFinite(arg))throw new RangeError(expectedFinite(entityName,arg));return arg}function toIntegerWithTrunc(arg,entityName){return Math.trunc(toFiniteNumber(arg,entityName))||0}function toPositiveIntegerWithTruncation(arg,entityName){return requireNumberIsPositive(toIntegerWithTrunc(arg,entityName),entityName)}function requireNumberIsPositive(num,entityName="number"){if(num<=0)throw new RangeError(expectedPositive(entityName,num));return num}function constrainToRange(num,min,max){return Math.min(Math.max(num,min),max)}function isObjectLike(arg){return arg!==null&&(typeof arg=="object"||typeof arg=="function")}function requireObjectLike(arg){if(!isObjectLike(arg))throw new TypeError(invalidObject);return arg}function createDiffFunc(unit){return(date0,date1,options)=>{let normOptions=normalizeDiffOptions(options);if(normOptions.roundingMode)return date0.until(date1,{...normOptions,largestUnit:unit,smallestUnit:unit})[unit];let duration=date0.until(date1,{...normOptions,largestUnit:unit});if(isTimeUnit(unit))return duration.total(unit);let relativeTo=!("day"in date0)&&"toPlainDate"in date0?date0.toPlainDate({day:1}):date0;return duration.total({unit,relativeTo})}}function isTimeUnit(unit){return unit==="hours"||unit==="minutes"||unit==="seconds"||unit==="milliseconds"||unit==="microseconds"||unit==="nanoseconds"}var diffYears=createDiffFunc("years"),diffMonths=createDiffFunc("months"),diffWeeks=createDiffFunc("weeks"),diffDays=createDiffFunc("days"),diffHours=createDiffFunc("hours"),diffMinutes=createDiffFunc("minutes"),diffSeconds=createDiffFunc("seconds"),diffMilliseconds=createDiffFunc("milliseconds"),diffMicroseconds=createDiffFunc("microseconds"),diffNanoseconds=createDiffFunc("nanoseconds");function normalizeDiffOptions(options){return typeof options=="string"?{roundingMode:options}:options||{}}var invalidEntity2=invalidEntity;var missingField=fieldName=>`Missing ${fieldName}`;var invalidChoice=(fieldName,val,choiceMap)=>invalidEntity(fieldName,val)+"; must be "+Object.keys(choiceMap).join(),forbiddenValueOf="Cannot use valueOf",invalidCallingContext="Invalid calling context";var exoticCalendarRequired=(calendarId,remedy)=>`Unknown calendar ${calendarId}; might need ${remedy}`,invalidTimeZone=calendarId=>invalidEntity("TimeZone",calendarId),outOfBoundsDate="Out-of-bounds date";var failedParse=s=>`Cannot parse: ${s}`,invalidSubstring=substring=>`Invalid substring: ${substring}`;var constrainToRange2=constrainToRange;function throwRangeError(message){throw new RangeError(message)}function throwTypeError(message){throw new TypeError(message)}function clampProp(props,propName,min,max,overflow){return clampEntity(propName,((props2,propName2)=>{let propVal=props2[propName2];return propVal===void 0&&throwTypeError(missingField(propName2)),propVal})(props,propName),min,max,overflow)}function clampEntity(entityName,num,min,max,overflow,choices){let clamped=constrainToRange2(num,min,max);return overflow&&num!==clamped&&throwRangeError(((entityName2,val,min2,max2,choices2)=>choices2?numberOutOfRange(entityName2,choices2[val],choices2[min2],choices2[max2]):numberOutOfRange(entityName2,val,min2,max2))(entityName,num,min,max,choices)),clamped}function memoize(generator,MapClass=Map){let map=new MapClass;return(key,...otherArgs)=>{if(map.has(key))return map.get(key);let val=generator(key,...otherArgs);return map.set(key,val),val}}var createNameDescriptors=name=>createPropDescriptors({name},1),createPropDescriptors=(propVals,readonly)=>mapProps(value=>({value,configurable:1,writable:!readonly}),propVals),createStringTagDescriptors=value=>({[Symbol.toStringTag]:{value,configurable:1}});function mapProps(transformer,props){let res={};for(let propName in props)res[propName]=transformer(props[propName],propName);return res}function zipPropsConst(propNames,propVal){let res={};for(let propName of propNames)res[propName]=propVal;return res}function createPropGetters(propNames){let getters={};for(let propName of propNames)getters[propName]=slots=>slots[propName];return getters}function pluckProps(propNames,props,dest=Object.create(null)){for(let propName of propNames)dest[propName]=props[propName];return dest}function bindArgs(f,...boundArgs){return(...dynamicArgs)=>f(...boundArgs,...dynamicArgs)}function noop(){}function capitalize(s){return s[0].toUpperCase()+s.substring(1)}function createRegExp(meat){return new RegExp(`^${meat}$`,"i")}function parseSubsecNano(fracStr){return parseInt(fracStr.padEnd(9,"0"))}function parseSign(s){return s&&s!=="+"?-1:1}function parseInt0(s){return s===void 0?0:parseInt(s)}function padNumber(digits,num){return String(num).padStart(digits,"0")}var padNumber2=bindArgs(padNumber,2);function compareNumbers(a,b){return Math.sign(a-b)}function divFloorBigInt(num,denom){let whole=num/denom;return num%denom<0n?whole-1n:whole}function divModFloorBigInt(num,divisor){let quotient=divFloorBigInt(num,divisor);return[quotient,num-quotient*divisor]}function divModFloor(num,divisor){return[Math.floor(num/divisor),modFloor(num,divisor)]}function modFloor(num,divisor){return(num%divisor+divisor)%divisor}function divTrunc(num,divisor){return Math.trunc(num/divisor)||0}function hasHalf(num){return Math.abs(num%1)===.5}function normalizeEraName(era){let normalized=era.normalize("NFD").toLowerCase().replace(/[^a-z0-9]/g,"");return normalized==="bc"||normalized==="b"?"bce":normalized==="ad"||normalized==="a"?"ce":normalized}var isoCalendarImpl=void 0;function getCalendarSlotId(calendar){return calendar===isoCalendarImpl?"iso8601":calendar===0?"gregory":calendar.id}function formatMonthCode(monthCodeNumber,isLeapMonth){return"M"+padNumber2(monthCodeNumber)+(isLeapMonth?"L":"")}var unitNameMap={nanosecond:0,microsecond:1,millisecond:2,second:3,minute:4,hour:5,day:6,week:7,month:8,year:9},unitNamesAsc=Object.keys(unitNameMap);var nanoInMicro2=nanoInMicro,nanoInMilli2=nanoInMilli,nanoInSec2=nanoInSec,nanoInMinute2=nanoInMinute,nanoInHour2=nanoInHour,nanoInUtcDay=864e11;var bigNanoInMilli=BigInt(nanoInMilli2),bigNanoInSec=BigInt(nanoInSec2);var bigNanoInUtcDay=BigInt(nanoInUtcDay);var timeFieldNamesAsc=unitNamesAsc.slice(0,6),timeGetters=createPropGetters(timeFieldNamesAsc);var calendarDateFieldNamesAsc=["day","month","year"];function validateTimeFields(timeFields){return constrainTimeFields(timeFields,1),timeFields}var maxValues={hour:23,minute:59,second:59};function constrainTimeFields(timeFields,overflow){let constrainedFields={};for(let fieldName of timeFieldNamesAsc)constrainedFields[fieldName]=clampEntity(fieldName,timeFields[fieldName],0,maxValues[fieldName]||999,overflow);return constrainedFields}function timeFieldsToNano(timeFields){return timeFieldsToSec(timeFields)*nanoInSec2+timeFieldsToSubsecNano(timeFields)}function timeFieldsToSec(timeFields){return 3600*timeFields.hour+60*timeFields.minute+timeFields.second}function timeFieldsToSubsecNano(timeFields){return timeFields.millisecond*nanoInMilli2+timeFields.microsecond*nanoInMicro2+timeFields.nanosecond}function nanoToTimeFields(timeNano){let[timeMilli,nanoAfterMilli]=divModFloor(timeNano,nanoInMilli2),[microsecond,nanosecond]=divModFloor(nanoAfterMilli,nanoInMicro2);return milliToTimeFields(timeMilli,microsecond,nanosecond)}function milliToTimeFields(timeMilli,microsecond=0,nanosecond=0){let[hour,milliAfterHour]=divModFloor(timeMilli,36e5),[minute,milliAfterMinute]=divModFloor(milliAfterHour,6e4),[second,millisecond]=divModFloor(milliAfterMinute,1e3);return{hour,minute,second,millisecond,microsecond,nanosecond}}function epochNanoToSecMod(epochNano){let[epochSec,nano]=divModFloorBigInt(epochNano,bigNanoInSec);return[Number(epochSec),Number(nano)]}function isoDateTimeToEpochNano(isoDateTime){return isoDateToEpochNano(isoDateTime)+BigInt(timeFieldsToNano(isoDateTime))}function isoDateToEpochNano(isoDate){return BigInt(isoDateToEpochDays(isoDate))*bigNanoInUtcDay}function isoDateToEpochDays(isoDate){return isoArgsToEpochDays(isoDate.year,isoDate.month,isoDate.day)}function isoArgsToEpochDays(isoYear,isoMonth=1,isoDay=1){let monthIndex=isoMonth-1;return isoYear+=Math.floor(monthIndex/12),isoMonth=modFloor(monthIndex,12),Date.UTC(isoYear%400-400,isoMonth,0)/864e5+146097*(divTrunc(isoYear,400)+1)+isoDay}function epochNanoToIsoDateTime(epochNano){let[epochDays,nanoAfterDay]=divModFloorBigInt(epochNano,bigNanoInUtcDay);return{...epochDaysToIsoDate(Number(epochDays)),...nanoToTimeFields(Number(nanoAfterDay))}}function epochDaysToIsoDate(epochDays){let legacyDate=new Date(864e5*modFloor(epochDays,146097));return{year:legacyDate.getUTCFullYear()+400*Math.floor(epochDays/146097),month:legacyDate.getUTCMonth()+1,day:legacyDate.getUTCDate()}}function computeIsoMonthCodeParts(month){return[month,0]}function computeIsoFieldsFromParts(year,month,day){return{year,month,day}}function computeIsoDaysInMonth(year,month){switch(month){case 2:return computeIsoInLeapYear(year)?29:28;case 4:case 6:case 9:case 11:return 30}return 31}function computeIsoDaysInYear(year){return computeIsoInLeapYear(year)?366:365}function computeIsoInLeapYear(year){return year%4==0&&(year%100!=0||year%400==0)}function computeIsoDayOfWeek(isoDateFields){return modFloor(isoArgsToEpochDays(isoDateFields.year,isoDateFields.month,isoDateFields.day)+4,7)||7}function computeIsoDayOfYear(isoDateFields){return isoArgsToEpochDays(isoDateFields.year,isoDateFields.month,isoDateFields.day)-isoArgsToEpochDays(isoDateFields.year)+1}function computeIsoWeekFields(isoDateFields){let yearOfWeek3=isoDateFields.year,weekOfYear4=Math.floor((computeIsoDayOfYear(isoDateFields)-computeIsoDayOfWeek(isoDateFields)+10)/7),weeksInYear=computeIsoWeeksInYear(yearOfWeek3);return weekOfYear4<1?weekOfYear4=weeksInYear=computeIsoWeeksInYear(--yearOfWeek3):weekOfYear4>weeksInYear&&(weekOfYear4=1,weeksInYear=computeIsoWeeksInYear(++yearOfWeek3)),{weekOfYear:weekOfYear4,yearOfWeek:yearOfWeek3,Be:weeksInYear}}function computeIsoWeeksInYear(year){let y0DayOfWeek=computeIsoDayOfWeek({year,month:1,day:1});return y0DayOfWeek===4||y0DayOfWeek===3&&computeIsoInLeapYear(year)?53:52}function computeGregoryEraFields({year}){return year<1?{era:"bce",eraYear:1-year}:{era:"ce",eraYear:year}}function validateIsoDateTimeFields(isoDateTime){return validateIsoDateFields(isoDateTime),validateTimeFields(isoDateTime)}function validateIsoDateFields(isoInternals){return constrainIsoDateFields(isoInternals,1),isoInternals}function constrainIsoDateFields(isoDate,overflow){let{year}=isoDate,month=clampProp(isoDate,"month",1,12,overflow);return{year,month,day:clampProp(isoDate,"day",1,computeIsoDaysInMonth(year,month),overflow)}}function computeCalendarDateFields(calendar,isoDate){return calendar?calendar.ae(isoDate):isoDate}function computeCalendarMonthCodeParts(calendar,year,month){return calendar?calendar.L(year,month):computeIsoMonthCodeParts(month)}function computeCalendarEraFields(calendar,isoDate){return calendar===0?computeGregoryEraFields(isoDate):calendar&&calendar.h?.(isoDate)||{}}function computeCalendarIsoFieldsFromParts(calendar,year,month,day){return calendar?calendar.de(year,month,day):computeIsoFieldsFromParts(year,month,day)}function computeCalendarMonthsInYearForYear(calendar,year){return calendar?calendar.j(year):12}function computeCalendarDaysInMonthForYearMonth(calendar,year,month){return calendar?calendar.o(year,month):computeIsoDaysInMonth(year,month)}function computeCalendarMonthCode(calendar,isoDate){let{year,month}=computeCalendarDateFields(calendar,isoDate),[monthCodeNumber,isLeapMonth]=computeCalendarMonthCodeParts(calendar,year,month);return formatMonthCode(monthCodeNumber,isLeapMonth)}function computeCalendarInLeapYear(calendar,isoDate){let{year}=computeCalendarDateFields(calendar,isoDate);return calendar?calendar.q(year):computeIsoInLeapYear(year)}function computeCalendarMonthsInYear(calendar,isoDate){let{year}=computeCalendarDateFields(calendar,isoDate);return computeCalendarMonthsInYearForYear(calendar,year)}function computeCalendarDaysInMonth(calendar,isoDate){let{year,month}=computeCalendarDateFields(calendar,isoDate);return computeCalendarDaysInMonthForYearMonth(calendar,year,month)}function computeCalendarDaysInYear(calendar,isoDate){let{year}=computeCalendarDateFields(calendar,isoDate);return calendar?calendar.i(year):computeIsoDaysInYear(year)}function computeCalendarDayOfYear(calendar,isoDate){if(!calendar)return computeIsoDayOfYear(isoDate);let{year}=computeCalendarDateFields(calendar,isoDate),yearStartIsoDate=computeCalendarIsoFieldsFromParts(calendar,year,1,1);return isoDateToEpochDays(isoDate)-isoDateToEpochDays(yearStartIsoDate)+1}function computeCalendarWeekOfYear(calendar,isoDate){return calendar===isoCalendarImpl?computeIsoWeekFields(isoDate).weekOfYear:void 0}function computeCalendarYearOfWeek(calendar,isoDate){return calendar===isoCalendarImpl?computeIsoWeekFields(isoDate).yearOfWeek:void 0}var requireString=bindArgs(requireType,"string");function requireType(typeName,arg,entityName=typeName){return typeof arg!==typeName&&throwTypeError(invalidEntity2(entityName,arg)),arg}function requireNumberIsInteger(num,entityName="number"){return Number.isInteger(num)||throwRangeError(((entityName2,num2)=>`Non-integer ${entityName2}: ${num2}`)(entityName,num)),num||0}function toString(arg){return typeof arg=="symbol"&&throwTypeError("Cannot convert Symbol to string"),String(arg)}function toStringViaPrimitive(arg,entityName){return isObjectLike(arg)?String(arg):requireString(arg,entityName)}function toStrictInteger(arg,entityName){return requireNumberIsInteger(toFiniteNumber(arg,entityName),entityName)}var epochDisambigMap={compatible:0,reject:1,earlier:2,later:3};var roundingModeFuncs=[Math.floor,num=>hasHalf(num)?Math.floor(num):Math.round(num),Math.ceil,num=>hasHalf(num)?Math.ceil(num):Math.round(num),Math.trunc,num=>hasHalf(num)?Math.trunc(num)||0:Math.round(num),num=>num<0?Math.floor(num):Math.ceil(num),num=>Math.sign(num)*Math.round(Math.abs(num))||0,num=>hasHalf(num)?(num=Math.trunc(num)||0)+num%2:Math.round(num)];function coerceChoiceOption(optionName,enumNameMap,options,defaultChoice=0){let enumArg=options[optionName];if(enumArg===void 0)return defaultChoice;let enumStr=toString(enumArg),enumNum=enumNameMap[enumStr];return enumNum===void 0&&throwRangeError(invalidChoice(optionName,enumStr,enumNameMap)),enumNum}var coerceEpochDisambig=bindArgs(coerceChoiceOption,"disambiguation",epochDisambigMap);function combineDateAndTime(isoDate,time){return pluckProps(calendarDateFieldNamesAsc,isoDate,pluckProps(timeFieldNamesAsc,time))}var epochNanoMax=BigInt(1e8)*bigNanoInUtcDay,epochNanoMin=BigInt(-1e8)*bigNanoInUtcDay,plainDateEpochNanoMin=epochNanoMin-bigNanoInUtcDay;function checkIsoDateInBounds(isoDate,allowPlainDateLowerEdge=1){return checkIsoDateEpochNanoInBounds(isoDateToEpochNano(isoDate),allowPlainDateLowerEdge),isoDate}function checkIsoDateTimeInBounds(isoDateTime){let epochNano=isoDateToEpochNano(isoDateTime);return checkIsoDateEpochNanoInBounds(epochNano),epochNano!==plainDateEpochNanoMin||timeFieldsToNano(isoDateTime)||throwRangeError(outOfBoundsDate),isoDateTime}function checkIsoDateEpochNanoInBounds(epochNano,allowPlainDateLowerEdge=1){(epochNano<(allowPlainDateLowerEdge?plainDateEpochNanoMin:epochNanoMin)||epochNano>epochNanoMax)&&throwRangeError(outOfBoundsDate)}function checkEpochNanoInBounds(epochNano){return(epochNano<epochNanoMin||epochNano>epochNanoMax)&&throwRangeError(outOfBoundsDate),epochNano}function isoDateTimeAndOffsetToEpochNano(isoDateTime,offsetNano){return checkEpochNanoInBounds(isoDateToEpochNano(isoDateTime)+BigInt(timeFieldsToNano(isoDateTime)-offsetNano))}function createEpochNanoSlots(epochNano){return{epochNanoseconds:epochNano}}function createZonedEpochNanoSlots(epochNano,timeZone,calendar){return{calendar,timeZone,epochNanoseconds:epochNano}}function createDateTimeSlots(isoDateTime,calendar){return pluckProps(timeFieldNamesAsc,isoDateTime,createDateSlots(isoDateTime,calendar))}function createDateSlots(isoDate,calendar){return pluckProps(calendarDateFieldNamesAsc,isoDate,{calendar})}function getEpochMilli(slots){return epochNano=slots.epochNanoseconds,Number(divFloorBigInt(epochNano,bigNanoInMilli));var epochNano}function getEpochNano(slots){return slots.epochNanoseconds}function roundToMinute(offsetNano){return roundNumberToInc(offsetNano,nanoInMinute2,7)}function roundNumberToInc(num,roundingInc,roundingMode){return roundWithMode(num/roundingInc,roundingMode)*roundingInc}function roundWithMode(num,roundingMode){return roundingModeFuncs[roundingMode](num)}var zonedEpochSlotsToIso=memoize(_zonedEpochSlotsToIso,WeakMap);function _zonedEpochSlotsToIso(slots){let{epochNanoseconds,timeZone}=slots,offsetNanoseconds4=timeZone.B(epochNanoseconds);return{...epochNanoToIsoDateTime(epochNanoseconds+BigInt(offsetNanoseconds4)),offsetNanoseconds:offsetNanoseconds4}}function getMatchingInstantFor(timeZone,isoDateTime,offsetNano,offsetDisambig=0,epochDisambig=0,epochFuzzy,hasZ){if(offsetNano!==void 0&&offsetDisambig===1&&(offsetDisambig===1||hasZ))return isoDateTimeAndOffsetToEpochNano(isoDateTime,offsetNano);offsetDisambig!==2&&offsetDisambig!==0||checkIsoDateInBounds(isoDateTime,0);let possibleEpochNanos=timeZone.N(isoDateTime);if(offsetNano!==void 0&&offsetDisambig!==3){let matchingEpochNano=((possibleEpochNanos2,isoDateTime2,offsetNano2,fuzzy)=>{let zonedEpochNano=isoDateTimeToEpochNano(isoDateTime2);fuzzy&&(offsetNano2=roundToMinute(offsetNano2));for(let possibleEpochNano of possibleEpochNanos2){let possibleOffsetNano=Number(zonedEpochNano-possibleEpochNano);if(fuzzy&&(possibleOffsetNano=roundToMinute(possibleOffsetNano)),possibleOffsetNano===offsetNano2)return possibleEpochNano}})(possibleEpochNanos,isoDateTime,offsetNano,epochFuzzy);if(matchingEpochNano!==void 0)return matchingEpochNano;offsetDisambig===0&&throwRangeError("Invalid TimeZone offset")}return hasZ?isoDateTimeToEpochNano(isoDateTime):getSingleInstantFor(timeZone,isoDateTime,epochDisambig,possibleEpochNanos)}function getSingleInstantFor(timeZone,isoDateTime,disambig=0,possibleEpochNanos=timeZone.N(isoDateTime)){if(possibleEpochNanos.length===1)return possibleEpochNanos[0];if(disambig===1&&throwRangeError("Ambiguous offset"),possibleEpochNanos.length)return possibleEpochNanos[disambig===3?1:0];let zonedEpochNano=isoDateTimeToEpochNano(isoDateTime),gapNano=((timeZone2,zonedEpochNano2)=>{let startOffsetNano=timeZone2.B(zonedEpochNano2-bigNanoInUtcDay);return(gapNano2=>(gapNano2>nanoInUtcDay&&throwRangeError("Out-of-bounds TimeZone gap"),gapNano2))(timeZone2.B(zonedEpochNano2+bigNanoInUtcDay)-startOffsetNano)})(timeZone,zonedEpochNano),shiftedIsoDateTime=epochNanoToIsoDateTime(zonedEpochNano+BigInt(gapNano*(disambig===2?-1:1)));return(possibleEpochNanos=timeZone.N(shiftedIsoDateTime))[disambig===2?0:possibleEpochNanos.length-1]}var maxDurationSeconds=2**53;var offsetRegExp=createRegExp("([+-])(\\d{2})(?::?(\\d{2})(?::?(\\d{2})(?:[.,](\\d{1,9}))?)?)?");function parseOffsetNano(s){let offsetNano=parseOffsetNanoMaybe(s);return offsetNano===void 0&&throwRangeError(failedParse(s)),offsetNano}function parseOffsetNanoMaybe(s,onlyHourMinute){let parts=offsetRegExp.exec(s);if(parts&&(s2=>(s3=>{s3[0]!=="T"&&s3[0]!=="t"||(s3=s3.slice(1));let fractionIndex=s3.search(/[.,]/),main=fractionIndex<0?s3:s3.slice(0,fractionIndex),parts2=main.split(":");return parts2.length===1?/^(?:\d{2}|\d{4}|\d{6})$/i.test(main):(parts2.length===2||parts2.length===3)&&parts2.every(part=>part.length===2&&/^\d{2}$/i.test(part))})(s2.slice(1)))(parts[0]))return((parts2,onlyHourMinute2)=>{let firstSubMinutePart=parts2[4]||parts2[5];return onlyHourMinute2&&firstSubMinutePart&&throwRangeError(invalidSubstring(firstSubMinutePart)),offsetNano=(parseInt0(parts2[2])*nanoInHour2+parseInt0(parts2[3])*nanoInMinute2+parseInt0(parts2[4])*nanoInSec2+parseSubsecNano(parts2[5]||""))*parseSign(parts2[1]),Math.abs(offsetNano)>=nanoInUtcDay&&throwRangeError("Out-of-bounds offset"),offsetNano;var offsetNano})(parts,onlyHourMinute)}var dateFieldRefiners={era:toStringViaPrimitive,month:toPositiveIntegerWithTruncation,monthCode(monthCode,entityName){if(typeof monthCode=="string")return monthCode;if(monthCode&&typeof monthCode=="object"){let monthCodeToString=monthCode.toString;if(typeof monthCodeToString=="function")return requireString(monthCodeToString.call(monthCode),entityName)}return requireString(monthCode,entityName)},day:toPositiveIntegerWithTruncation},timeFieldRefiners=zipPropsConst(timeFieldNamesAsc,toIntegerWithTrunc);var dateTimeFieldRefiners=Object.assign({},dateFieldRefiners,timeFieldRefiners),zonedDateTimeFieldRefiners={offset(offsetString){return parseOffsetNano(toStringViaPrimitive(offsetString))},...dateTimeFieldRefiners};var RawDateTimeFormat=Intl.DateTimeFormat;function formatEpochMilliToPartsRecord(intlFormat,epochMilli){epochMilli<-864e13&&throwRangeError(outOfBoundsDate);let parts=intlFormat.formatToParts(epochMilli),hash={};for(let part of parts)hash[part.type]=part.value;return hash}var timeZonePeriodDaysByName={El_Aaiun:17,Tucuman:12,Tirane:11,Riga:10,Simferopol:9,Vienna:9,Tunis:8,Boa_Vista:6,Fortaleza:6,Maceio:6,Noronha:6,Recife:6,Gaza:6,Hebron:6,DeNoronha:6},minPossibleTransitionSec=-388152e4;function formatInstantIsoAuto(instantSlots){return formatIsoDateTimeFields(epochNanoToIsoDateTime(instantSlots.epochNanoseconds),void 0)+"Z"}function formatZonedDateTimeIsoAuto(zonedDateTimeSlots){let calendar=zonedDateTimeSlots.calendar,timeZone=zonedDateTimeSlots.timeZone,offsetNano=timeZone.B(zonedDateTimeSlots.epochNanoseconds);return formatIsoDateTimeFields(epochNanoToIsoDateTime(zonedDateTimeSlots.epochNanoseconds+BigInt(offsetNano)),void 0)+formatOffsetNano(roundToMinute(offsetNano))+formatTimeZone(timeZone.id,0)+(calendar===isoCalendarImpl?"":formatCalendarId(getCalendarSlotId(calendar),0))}function formatDateTimeIsoAuto(isoDateTimeSlots){let calendar=isoDateTimeSlots.calendar;return formatIsoDateTimeFields(isoDateTimeSlots,void 0)+(calendar===isoCalendarImpl?"":formatCalendarId(getCalendarSlotId(calendar),0))}function formatIsoDateTimeFields(isoDateTime,subsecDigits){return formatIsoDateFields(isoDateTime)+"T"+formatTimeFields(isoDateTime,subsecDigits)}function formatIsoDateFields(isoDateFields){return formatIsoYearMonthFields(isoDateFields)+"-"+padNumber2(isoDateFields.day)}function formatIsoYearMonthFields(isoDateFields){let{year}=isoDateFields;return(year<0||year>9999?getSignStr(year)+padNumber(6,Math.abs(year)):padNumber(4,year))+"-"+padNumber2(isoDateFields.month)}function formatTimeFields(timeFields,subsecDigits){let parts=[padNumber2(timeFields.hour),padNumber2(timeFields.minute)];return subsecDigits!==-1&&parts.push(padNumber2(timeFields.second)+((millisecond,microsecond,nanosecond,subsecDigits2)=>formatSubsecNano(millisecond*nanoInMilli2+microsecond*nanoInMicro2+nanosecond,subsecDigits2))(timeFields.millisecond,timeFields.microsecond,timeFields.nanosecond,subsecDigits)),parts.join(":")}function formatOffsetNano(offsetNano,offsetDisplay=0){if(offsetDisplay===1)return"";let[hour,nanoRemainder0]=divModFloor(Math.abs(offsetNano),nanoInHour2),[minute,nanoRemainder1]=divModFloor(nanoRemainder0,nanoInMinute2),[second,nanoRemainder2]=divModFloor(nanoRemainder1,nanoInSec2);return getSignStr(offsetNano)+padNumber2(hour)+":"+padNumber2(minute)+(second||nanoRemainder2?":"+padNumber2(second)+formatSubsecNano(nanoRemainder2):"")}function formatTimeZone(timeZoneId,timeZoneDisplay){return timeZoneDisplay!==1?"["+(timeZoneDisplay===2?"!":"")+timeZoneId+"]":""}function formatCalendarId(calendarId,isCritical){return"["+(isCritical?"!":"")+"u-ca="+calendarId+"]"}var trailingZerosRE=/0+$/;function formatSubsecNano(totalNano,subsecDigits){let s=padNumber(9,totalNano);return s=subsecDigits===void 0?s.replace(trailingZerosRE,""):s.slice(0,subsecDigits),s?"."+s:""}function getSignStr(num){return num<0?"-":"+"}var icuRegExp=/^(AC|AE|AG|AR|AS|BE|BS|CA|CN|CS|CT|EA|EC|IE|IS|JS|MI|NE|NS|PL|PN|PR|PS|SS|VS)T$/,badCharactersRegExp=/[^\w\/:+-]+/;function refineTimeZoneId(rawId){return resolveTimeZoneId(requireString(rawId))}function resolveTimeZoneId(rawId){return resolveTimeZoneRecord(rawId).id}function resolveTimeZoneRecord(rawId){let upperRawId=rawId.toUpperCase(),offsetRecord=(upperRawId2=>{let offsetNano=parseOffsetNanoMaybe(upperRawId2,1);if(offsetNano!==void 0)return{id:formatOffsetNano(offsetNano),X:offsetNano,m:offsetNano}})(upperRawId);if(offsetRecord)return{kind:"fixed",...offsetRecord};let normId=upperRawId==="UTC"?"UTC":(rawId2=>(badCharactersRegExp.test(rawId2)&&throwRangeError(invalidTimeZone(rawId2)),icuRegExp.test(rawId2)&&throwRangeError("Forbidden ICU TimeZone"),rawId2.toLowerCase().split("/").map((part,partI)=>(part.length<=3||/\d/.test(part))&&!/etc|yap/.test(part)?part.toUpperCase():part.replace(/baja|dumont|[a-z]+/g,(a,i)=>a.length<=2&&!partI||a==="in"||a==="chat"?a.toUpperCase():a.length>2||!i?capitalize(a).replace(/island|noronha|murdo|rivadavia|urville/,capitalize):a)).join("/")))(rawId);return queryNamedTimeZoneRecord(normId)}var queryNamedTimeZoneRecord=memoize(normId=>{if(normId==="UTC")return{kind:"utc",id:normId,m:normId};let upperNormId=normId.toUpperCase(),format=queryTimeZoneIntlFormat(upperNormId);return{kind:"named",id:normId,format,m:format.resolvedOptions().timeZone}}),queryTimeZoneIntlFormat=memoize(upperNormId=>new RawDateTimeFormat("en-u-hc-h23",{calendar:"iso8601",timeZone:upperNormId,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}));function queryTimeZone(rawTimeZoneId){let record=resolveTimeZoneRecord(rawTimeZoneId);return queryTimeZoneRecord(record.id,record)}var queryTimeZoneRecord=memoize((normTimeZoneId,record)=>record.kind==="named"?new IntlTimeZone(normTimeZoneId,record.m,record.format):new FixedTimeZone(normTimeZoneId,record.m,record.kind==="fixed"?record.X:0)),FixedTimeZone=class{constructor(id,compareKey,offsetNano){this.id=id,this.m=compareKey,this.X=offsetNano}B(){return this.X}N(isoDateTime){return[isoDateTimeAndOffsetToEpochNano(isoDateTime,this.X)]}O(){}},IntlTimeZone=class{constructor(id,compareKey,format){this.id=id,this.m=compareKey,this.ke=((computeOffsetSec,periodDays)=>{let getSample=memoize(computeOffsetSec),getSplit=memoize(createSplitTuple),periodSec=86400*periodDays;function getOffsetSec(epochSec){let[startEpochSec,endEpochSec]=computePeriod(epochSec,periodSec),clampedStartEpochSec=clampIntlSampleEpochSec(startEpochSec),clampedEndEpochSec=clampIntlSampleEpochSec(endEpochSec),startOffsetSec=getSample(clampedStartEpochSec),endOffsetSec=getSample(clampedEndEpochSec);return startOffsetSec===endOffsetSec?startOffsetSec:pinch(getSplit(clampedStartEpochSec,clampedEndEpochSec),startOffsetSec,endOffsetSec,epochSec)}function pinch(split,startOffsetSec,endOffsetSec,forEpochSec){let offsetSec,splitDurSec;for(;(forEpochSec===void 0||(offsetSec=forEpochSec<split[0]?startOffsetSec:forEpochSec>=split[1]?endOffsetSec:void 0)===void 0)&&(splitDurSec=split[1]-split[0]);){let middleEpochSec=split[0]+Math.floor(splitDurSec/2);computeOffsetSec(middleEpochSec)===endOffsetSec?split[1]=middleEpochSec:split[0]=middleEpochSec+1}return offsetSec}return{xe(zonedEpochSec){let wideOffsetSec0=getOffsetSec(zonedEpochSec-86400),wideOffsetSec1=getOffsetSec(zonedEpochSec+86400),wideUtcEpochSec0=zonedEpochSec-wideOffsetSec0,wideUtcEpochSec1=zonedEpochSec-wideOffsetSec1;if(wideOffsetSec0===wideOffsetSec1)return[wideUtcEpochSec0];let narrowOffsetSec0=getOffsetSec(wideUtcEpochSec0);return narrowOffsetSec0===getOffsetSec(wideUtcEpochSec1)?[zonedEpochSec-narrowOffsetSec0]:wideOffsetSec0>wideOffsetSec1?[wideUtcEpochSec0,wideUtcEpochSec1]:[]},we:getOffsetSec,O:function getTransition(epochSec,direction){if(direction>0&&epochSec>=864e10)return;if(direction<0){if(epochSec<=minPossibleTransitionSec)return;let lookaheadEpochSec=getCurrentEpochSec()+94867200;if(epochSec>lookaheadEpochSec)return getTransition(lookaheadEpochSec,-1)}let searchEpochSec=direction>0?Math.max(epochSec,minPossibleTransitionSec):epochSec,[startEpochSec,endEpochSec]=computePeriod(searchEpochSec,periodSec),inc=periodSec*direction,searchLimit=direction>0?Math.max(epochSec,getCurrentEpochSec())+94867200:minPossibleTransitionSec,inBounds=()=>direction<0?endEpochSec>searchLimit:startEpochSec<searchLimit;for(;inBounds();){let clampedStartEpochSec=clampIntlSampleEpochSec(startEpochSec),clampedEndEpochSec=clampIntlSampleEpochSec(endEpochSec),startOffsetSec=getSample(clampedStartEpochSec),endOffsetSec=getSample(clampedEndEpochSec);if(startOffsetSec!==endOffsetSec){let split=getSplit(clampedStartEpochSec,clampedEndEpochSec);pinch(split,startOffsetSec,endOffsetSec);let transitionEpochSec=split[0];if((compareNumbers(transitionEpochSec,epochSec)||1)===direction)return transitionEpochSec}startEpochSec+=inc,endEpochSec+=inc}}}})((format2=>epochSec=>{let intlParts=formatEpochMilliToPartsRecord(format2,1e3*epochSec);return 86400*isoArgsToEpochDays((intlParts2=>{let relatedYear=intlParts2.relatedYear;if(relatedYear!==void 0)return parseInt(relatedYear);let year=parseInt(intlParts2.year);return intlParts2.era!==void 0&&normalizeEraName(intlParts2.era)==="bce"?1-year:year})(intlParts),parseInt(intlParts.month),parseInt(intlParts.day))+3600*parseInt(intlParts.hour)+60*parseInt(intlParts.minute)+parseInt(intlParts.second)-epochSec})(format),(timeZoneId=>{let timeZoneName=timeZoneId.split("/").pop();return timeZonePeriodDaysByName[timeZoneName]||60})(id))}B(epochNano){return this.ke.we((epochNano2=>epochNanoToSecMod(epochNano2)[0])(epochNano))*nanoInSec2}N(isoDateTime){let zonedEpochSec=86400*isoDateToEpochDays(isoDateTime)+timeFieldsToSec(isoDateTime),subsecNano=timeFieldsToSubsecNano(isoDateTime);return this.ke.xe(zonedEpochSec).map(epochSec=>checkEpochNanoInBounds(BigInt(epochSec)*bigNanoInSec+BigInt(subsecNano)))}O(epochNano,direction){let[epochSec,subsecNano]=epochNanoToSecMod(epochNano),resEpochSec=this.ke.O(epochSec+(direction>0||subsecNano?1:0),direction);if(resEpochSec!==void 0)return BigInt(resEpochSec)*bigNanoInSec}};function getCurrentEpochSec(){return Math.floor(Date.now()/1e3)}function createSplitTuple(startEpochSec,endEpochSec){return[startEpochSec,endEpochSec]}function computePeriod(epochSec,periodSec){let startEpochSec=Math.floor(epochSec/periodSec)*periodSec;return[startEpochSec,startEpochSec+periodSec]}function clampIntlSampleEpochSec(epochSec){return constrainToRange2(epochSec,-1e10,864e10)}function timeRegExpStr(separatorIndex){return`(\\d{2})(?:(:?)(\\d{2})(?:\\${separatorIndex}(\\d{2})(?:[.,](\\d{1,9}))?)?)?`}var dateTimeRegExpStr="(?:(?:([+-])(\\d{6}))|(\\d{4}))(-?)(\\d{2})\\4(\\d{2})(?:[T ]"+timeRegExpStr(8)+"(Z|([+-])"+timeRegExpStr(15)+")?)?";var dateTimeRegExp=createRegExp(dateTimeRegExpStr+"((?:\\[(!?)([^\\]]*)\\]){0,9})"),timeRegExp=createRegExp("T?"+timeRegExpStr(2)+`(([+-])${timeRegExpStr(9)})?((?:\\[(!?)([^\\]]*)\\]){0,9})`);function instantToZonedDateTime(instantSlots,timeZone,calendar){return createZonedEpochNanoSlots(instantSlots.epochNanoseconds,timeZone,calendar)}function plainDateTimeToZonedDateTime(plainDateTimeSlots,timeZone,options){let epochNano=getSingleInstantFor(timeZone,plainDateTimeSlots,(options2=>coerceEpochDisambig(normalizeOptions(options2)))(options));return createZonedEpochNanoSlots(checkEpochNanoInBounds(epochNano),timeZone,plainDateTimeSlots.calendar)}function epochMilliToInstant(epochMilli){return createEpochNanoSlots(checkEpochNanoInBounds(BigInt(toStrictInteger(epochMilli))*bigNanoInMilli))}function createOptionsTransformer(shapeFieldNames,invalidShapeFieldNames,ignoredFieldNames,defaultShapeFields,dateStyleReplacementFields){let shapeFieldNameSet=new Set(shapeFieldNames),invalidShapeFieldNameSet=new Set(invalidShapeFieldNames),ignoredFieldNameSet=new Set(ignoredFieldNames);return(options,allowPartialOverlap)=>{let dateStyle,timeStyle,granularShapeFields={},modifierFields={},otherFields={},hasInvalidGranularShapeFields=0,hasInvalidStyleFields=0;for(let name of Object.keys(options)){let value=options[name];value===void 0||ignoredFieldNameSet.has(name)||(shapeFieldNameSet.has(name)?name==="dateStyle"?dateStyle=value:name==="timeStyle"?timeStyle=value:granularShapeFields[name]=value:name==="era"?modifierFields[name]=value:invalidShapeFieldNameSet.has(name)?name==="dateStyle"||name==="timeStyle"?hasInvalidStyleFields=1:hasInvalidGranularShapeFields=1:otherFields[name]=value)}let hasDateStyle=dateStyle!==void 0,hasTimeStyle=timeStyle!==void 0,hasAnyStyle=hasDateStyle||hasTimeStyle,hasGranularShapeFields=Object.keys(granularShapeFields).length>0,hasInvalids=hasInvalidGranularShapeFields||hasInvalidStyleFields,hasShapeFields=hasGranularShapeFields||hasDateStyle||hasTimeStyle,hasModifierFields=Object.keys(modifierFields).length>0;(!allowPartialOverlap&&hasInvalids||allowPartialOverlap&&hasInvalids&&!hasShapeFields||hasAnyStyle&&(hasGranularShapeFields||hasModifierFields||hasInvalidGranularShapeFields))&&throwTypeError("Invalid formatting options");let transformedOptions={};return hasAnyStyle||hasShapeFields||Object.assign(transformedOptions,defaultShapeFields),Object.assign(transformedOptions,granularShapeFields,modifierFields,otherFields),hasDateStyle&&(dateStyleReplacementFields?Object.assign(transformedOptions,dateStyleReplacementFields[dateStyle]):transformedOptions.dateStyle=dateStyle),hasTimeStyle&&(transformedOptions.timeStyle=timeStyle),transformedOptions}}var dateDefaultShapeFields={year:"numeric",month:"numeric",day:"numeric"},timeDefaultShapeFields={hour:"numeric",minute:"numeric",second:"numeric"},dateTimeDefaultShapeFields=Object.assign({},dateDefaultShapeFields,timeDefaultShapeFields),dateShapeFieldNames=["weekday","year","month","day","dateStyle"],timeShapeFieldNames=["dayPeriod","hour","minute","second","fractionalSecondDigits","timeStyle"],dateTimeShapeFieldNames=dateShapeFieldNames.concat(timeShapeFieldNames);var transformZonedOptions=createOptionsTransformer(dateTimeShapeFieldNames,[],[],{...dateTimeDefaultShapeFields,timeZoneName:"short"});var PlainYearMonthBranding="PlainYearMonth",PlainMonthDayBranding="PlainMonthDay",PlainDateBranding="PlainDate",PlainDateTimeBranding="PlainDateTime",PlainTimeBranding="PlainTime",ZonedDateTimeBranding="ZonedDateTime",InstantBranding="Instant",DurationBranding="Duration",CalendarBranding="Calendar";function defineTemporalClass(branding,cls,getSlots,...getterMaps){return Object.defineProperties(cls,createNameDescriptors(branding)),Object.defineProperties(cls.prototype,createStringTagDescriptors("Temporal."+branding)),Object.defineProperties(cls.prototype,mapProps(getter=>({get(){return getter(getSlots(this))},configurable:1}),Object.assign({},...getterMaps))),cls}var attachDebugString=noop.name==="noop"?instance=>{Object.defineProperty(instance,"_str_",{value:instance.toJSON()})}:noop;function invalidRecordType(){throwTypeError(invalidCallingContext)}function forbiddenValueOf2(){throwTypeError(forbiddenValueOf)}var dateFieldGetters$1={era(slots){return computeCalendarEraFields(slots.calendar,slots).era},eraYear(slots){return computeCalendarEraFields(slots.calendar,slots).eraYear},year(slots){return computeCalendarDateFields(slots.calendar,slots).year},month(slots){return computeCalendarDateFields(slots.calendar,slots).month},monthCode(slots){return computeCalendarMonthCode(slots.calendar,slots)},day(slots){return computeCalendarDateFields(slots.calendar,slots).day}};var yearMonthDerivedGetters={daysInMonth(slots){return computeCalendarDaysInMonth(slots.calendar,slots)},daysInYear(slots){return computeCalendarDaysInYear(slots.calendar,slots)},monthsInYear(slots){return computeCalendarMonthsInYear(slots.calendar,slots)},inLeapYear(slots){return computeCalendarInLeapYear(slots.calendar,slots)}},dateDerivedGetters={dayOfWeek(slots){return computeIsoDayOfWeek(slots)},dayOfYear(slots){return computeCalendarDayOfYear(slots.calendar,slots)},weekOfYear(slots){return computeCalendarWeekOfYear(slots.calendar,slots)},yearOfWeek(slots){return computeCalendarYearOfWeek(slots.calendar,slots)},daysInWeek(){return 7},daysInMonth(slots){return computeCalendarDaysInMonth(slots.calendar,slots)},daysInYear(slots){return computeCalendarDaysInYear(slots.calendar,slots)},monthsInYear(slots){return computeCalendarMonthsInYear(slots.calendar,slots)},inLeapYear(slots){return computeCalendarInLeapYear(slots.calendar,slots)}};function createNativeGetters(shimGetters){return createPropGetters(Object.keys(shimGetters))}var timeGetters2=createNativeGetters(timeGetters);var dateFieldGetters=createNativeGetters(dateFieldGetters$1);createNativeGetters(yearMonthDerivedGetters),createNativeGetters(dateDerivedGetters);var PlainYearMonthRecordBranding=`${PlainYearMonthBranding}Record`,PlainMonthDayRecordBranding=`${PlainMonthDayBranding}Record`,PlainDateRecordBranding=`${PlainDateBranding}Record`,PlainDateTimeRecordBranding=`${PlainDateTimeBranding}Record`,PlainTimeRecordBranding=`${PlainTimeBranding}Record`,ZonedDateTimeRecordBranding=`${ZonedDateTimeBranding}Record`,InstantRecordBranding=`${InstantBranding}Record`,DurationRecordBranding=`${DurationBranding}Record`,CalendarRecordBranding=`${CalendarBranding}Record`,calendarMap=new WeakMap,instantMap=new WeakMap,zonedDateTimeMap=new WeakMap,plainDateTimeMap=new WeakMap;function getCalendarSlots(record){return getCalendarSlotsIfPresent(record)||invalidRecordType()}function getCalendarSlotsIfPresent(record){return calendarMap.get(record)}function getInstantSlots(record){return getInstantSlotsIfPresent(record)||invalidRecordType()}function getInstantSlotsIfPresent(record){return instantMap.get(record)}function setInstantSlots(instance,slots){instantMap.set(instance,slots)}function getZonedDateTimeSlots(record){return getZonedDateTimeSlotsIfPresent(record)||invalidRecordType()}function getZonedDateTimeSlotsIfPresent(record){return zonedDateTimeMap.get(record)}function setZonedDateTimeSlots(instance,slots){zonedDateTimeMap.set(instance,slots)}function getPlainDateTimeSlots(record){return getPlainDateTimeSlotsIfPresent(record)||invalidRecordType()}function getPlainDateTimeSlotsIfPresent(record){return plainDateTimeMap.get(record)}function setPlainDateTimeSlots(instance,slots){plainDateTimeMap.set(instance,slots)}function getCalendarRecordId(record){return getCalendarSlots(record).id}function getCalendarRecordImplCreator(record){let getImpl=getCalendarSlots(record).ue;return getImpl||throwRangeError(exoticCalendarRequired(getCalendarRecordId(record),"getExotic or getAny")),getImpl}function refineNativeCalendarArgMaybe(calendarRecord){if(calendarRecord!==void 0)return getValidatedCalendarId(calendarRecord)}function getValidatedCalendarId(record){return getCalendarRecordImplCreator(record),getCalendarRecordId(record)}var getNativePlainDateTime=getPlainDateTimeSlots,NativePlainDateTimeRecord=defineTemporalClass(PlainDateTimeRecordBranding,class{get calendarId(){return getNativePlainDateTime(this).calendarId}toJSON(){return getNativePlainDateTime(this).toJSON()}valueOf(){return getNativePlainDateTime(this).valueOf()}},getNativePlainDateTime,dateFieldGetters,timeGetters2);function createNativePlainDateTimeRecord(native){let instance=Object.create(NativePlainDateTimeRecord.prototype);return setPlainDateTimeSlots(instance,native),attachDebugString(instance),instance}function create$5(isoYear,isoMonth,isoDay,hour,minute,second,millisecond,microsecond,nanosecond,calendar){return createNativePlainDateTimeRecord(new NativeTemporal.PlainDateTime(isoYear,isoMonth,isoDay,hour,minute,second,millisecond,microsecond,nanosecond,refineNativeCalendarArgMaybe(calendar)))}function toZonedDateTime$1(record,timeZoneId,options){return createNativeZonedDateTimeRecord(getNativePlainDateTime(record).toZonedDateTime(timeZoneId,options))}var getNativeZonedDateTime=getZonedDateTimeSlots,NativeZonedDateTimeRecord=defineTemporalClass(ZonedDateTimeRecordBranding,class{get calendarId(){return getNativeZonedDateTime(this).calendarId}get timeZoneId(){return getNativeZonedDateTime(this).timeZoneId}get epochMilliseconds(){return getNativeZonedDateTime(this).epochMilliseconds}get epochNanoseconds(){return getNativeZonedDateTime(this).epochNanoseconds}toJSON(){return getNativeZonedDateTime(this).toJSON()}valueOf(){return getNativeZonedDateTime(this).valueOf()}},getNativeZonedDateTime,dateFieldGetters,timeGetters2);function createNativeZonedDateTimeRecord(native){let instance=Object.create(NativeZonedDateTimeRecord.prototype);return setZonedDateTimeSlots(instance,native),attachDebugString(instance),instance}function offsetNanoseconds(record){return getNativeZonedDateTime(record).offsetNanoseconds}var getNativeInstant=getInstantSlots,NativeInstantRecord=defineTemporalClass(InstantRecordBranding,class{get epochMilliseconds(){return getNativeInstant(this).epochMilliseconds}get epochNanoseconds(){return getNativeInstant(this).epochNanoseconds}toJSON(){return getNativeInstant(this).toJSON()}valueOf(){return getNativeInstant(this).valueOf()}});function createNativeInstantRecord(native){let instance=Object.create(NativeInstantRecord.prototype);return setInstantSlots(instance,native),attachDebugString(instance),instance}function fromEpochMilliseconds(epochMilliseconds){return createNativeInstantRecord(NativeTemporal.Instant.fromEpochMilliseconds(epochMilliseconds))}function toZonedDateTimeISO(record,timeZoneId){return createNativeZonedDateTimeRecord(getNativeInstant(record).toZonedDateTimeISO(timeZoneId))}function refineShimCalendarArgMaybe(calendarRecord){return calendarRecord===void 0?isoCalendarImpl:getCalendarRecordImpl(calendarRecord)}function getCalendarRecordImpl(record){return getCalendarRecordImplCreator(record)()}var getShimPlainDateTimeSlots=getPlainDateTimeSlots,ShimPlainDateTimeRecord=defineTemporalClass(PlainDateTimeRecordBranding,class{get calendarId(){return getCalendarSlotId(getShimPlainDateTimeSlots(this).calendar)}toJSON(){return formatDateTimeIsoAuto(getShimPlainDateTimeSlots(this))}valueOf(){return forbiddenValueOf2()}},getShimPlainDateTimeSlots,dateFieldGetters$1,timeGetters);function createShimPlainDateTimeRecord(slots){let instance=Object.create(ShimPlainDateTimeRecord.prototype);return setPlainDateTimeSlots(instance,slots),attachDebugString(instance),instance}function create$52(isoYear,isoMonth,isoDay,hour=0,minute=0,second=0,millisecond=0,microsecond=0,nanosecond=0,calendar){let fields=checkIsoDateTimeInBounds(validateIsoDateTimeFields(mapProps(toIntegerWithTrunc,{year:isoYear,month:isoMonth,day:isoDay,hour,minute,second,millisecond,microsecond,nanosecond}))),calendarImpl=refineShimCalendarArgMaybe(calendar);return createShimPlainDateTimeRecord(createDateTimeSlots(fields,calendarImpl))}function toZonedDateTime$12(record,timeZoneId,options){return createShimZonedDateTimeRecord(plainDateTimeToZonedDateTime(getShimPlainDateTimeSlots(record),queryTimeZone(refineTimeZoneId(timeZoneId)),options))}var getShimZonedDateTimeSlots=getZonedDateTimeSlots,ShimZonedDateTimeRecord=defineTemporalClass(ZonedDateTimeRecordBranding,class{get calendarId(){return getCalendarSlotId(getShimZonedDateTimeSlots(this).calendar)}get timeZoneId(){return getShimZonedDateTimeSlots(this).timeZone.id}get epochMilliseconds(){return getEpochMilli(getShimZonedDateTimeSlots(this))}get epochNanoseconds(){return getEpochNano(getShimZonedDateTimeSlots(this))}toJSON(){return formatZonedDateTimeIsoAuto(getShimZonedDateTimeSlots(this))}valueOf(){return forbiddenValueOf2()}},getShimZonedDateTimeIsoSlots,dateFieldGetters$1,timeGetters);function createShimZonedDateTimeRecord(slots){let instance=Object.create(ShimZonedDateTimeRecord.prototype);return setZonedDateTimeSlots(instance,slots),attachDebugString(instance),instance}function getShimZonedDateTimeIsoSlots(record){let slots=getShimZonedDateTimeSlots(record);return{...zonedEpochSlotsToIso(slots),calendar:slots.calendar}}function offsetNanoseconds2(record){return zonedEpochSlotsToIso(getShimZonedDateTimeSlots(record)).offsetNanoseconds}var endOfHour2=alignedZonedTime(slots=>({hour:slots.hour,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0}),nanoInHour2-1),endOfMinute2=alignedZonedTime(slots=>({hour:slots.hour,minute:slots.minute,second:0,millisecond:0,microsecond:0,nanosecond:0}),nanoInMinute2-1),endOfSecond2=alignedZonedTime(slots=>({hour:slots.hour,minute:slots.minute,second:slots.second,millisecond:0,microsecond:0,nanosecond:0}),nanoInSec2-1),endOfMillisecond2=alignedZonedTime(slots=>({hour:slots.hour,minute:slots.minute,second:slots.second,millisecond:slots.millisecond,microsecond:0,nanosecond:0}),nanoInMilli2-1),endOfMicrosecond2=alignedZonedTime(slots=>({hour:slots.hour,minute:slots.minute,second:slots.second,millisecond:slots.millisecond,microsecond:slots.microsecond,nanosecond:0}),nanoInMicro2-1);function alignedZonedTime(computeAlignment,nanoDelta=0){return record=>{let slots=getShimZonedDateTimeSlots(record),{timeZone}=slots,isoDateTime=zonedEpochSlotsToIso(slots),alignedIsoDateTime=combineDateAndTime(isoDateTime,computeAlignment(isoDateTime)),epochNanoseconds=getMatchingInstantFor(timeZone,alignedIsoDateTime,isoDateTime.offsetNanoseconds,2,0,1)+BigInt(nanoDelta);return createShimZonedDateTimeRecord({...slots,epochNanoseconds:checkEpochNanoInBounds(epochNanoseconds)})}}var getShimInstantSlots=getInstantSlots,ShimInstantRecord=defineTemporalClass(InstantRecordBranding,class{get epochMilliseconds(){return getEpochMilli(getShimInstantSlots(this))}get epochNanoseconds(){return getEpochNano(getShimInstantSlots(this))}toJSON(){return formatInstantIsoAuto(getShimInstantSlots(this))}valueOf(){return forbiddenValueOf2()}});function createShimInstantRecord(slots){let instance=Object.create(ShimInstantRecord.prototype);return setInstantSlots(instance,slots),attachDebugString(instance),instance}function fromEpochMilliseconds2(epochMilliseconds){return createShimInstantRecord(epochMilliToInstant(epochMilliseconds))}function toZonedDateTimeISO2(record,timeZoneId){return createShimZonedDateTimeRecord(instantToZonedDateTime(getShimInstantSlots(record),queryTimeZone(refineTimeZoneId(timeZoneId))))}var offsetNanoseconds3=NativeTemporal?offsetNanoseconds:offsetNanoseconds2;var create=NativeTemporal?create$5:create$52;var toZonedDateTime=NativeTemporal?toZonedDateTime$1:toZonedDateTime$12;var fromEpochMilliseconds3=NativeTemporal?fromEpochMilliseconds:fromEpochMilliseconds2;var toZonedDateTimeISO3=NativeTemporal?toZonedDateTimeISO:toZonedDateTimeISO2;function addWeeks3(m,n){let a=dateToUtcArray(m);return a[2]+=n*7,arrayToUtcDate(a)}function addDays4(m,n){let a=dateToUtcArray(m);return a[2]+=n,arrayToUtcDate(a)}function addMs(m,n){let a=dateToUtcArray(m);return a[6]+=n,arrayToUtcDate(a)}function diffWeeks4(m0,m1){return diffDays4(m0,m1)/7}function diffDays4(m0,m1){return(m1.valueOf()-m0.valueOf())/(1e3*60*60*24)}function diffHours4(m0,m1){return(m1.valueOf()-m0.valueOf())/(1e3*60*60)}function diffMinutes4(m0,m1){return(m1.valueOf()-m0.valueOf())/(1e3*60)}function diffSeconds4(m0,m1){return(m1.valueOf()-m0.valueOf())/1e3}function diffDayAndTime(m0,m1){let m0day=startOfDay5(m0),m1day=startOfDay5(m1);return{years:0,months:0,days:Math.round(diffDays4(m0day,m1day)),milliseconds:m1.valueOf()-m1day.valueOf()-(m0.valueOf()-m0day.valueOf())}}function diffWholeWeeks(m0,m1){let d=diffWholeDays(m0,m1);return d!==null&&d%7===0?d/7:null}function diffWholeDays(m0,m1){return timeAsMs(m0)===timeAsMs(m1)?Math.round(diffDays4(m0,m1)):null}function startOfDay5(m){return arrayToUtcDate([m.getUTCFullYear(),m.getUTCMonth(),m.getUTCDate()])}function startOfHour4(m){return arrayToUtcDate([m.getUTCFullYear(),m.getUTCMonth(),m.getUTCDate(),m.getUTCHours()])}function startOfMinute4(m){return arrayToUtcDate([m.getUTCFullYear(),m.getUTCMonth(),m.getUTCDate(),m.getUTCHours(),m.getUTCMinutes()])}function startOfSecond4(m){return arrayToUtcDate([m.getUTCFullYear(),m.getUTCMonth(),m.getUTCDate(),m.getUTCHours(),m.getUTCMinutes(),m.getUTCSeconds()])}function weekOfYear3(marker,dow,doy){let y=marker.getUTCFullYear(),w=weekOfGivenYear(marker,y,dow,doy);if(w<1)return weekOfGivenYear(marker,y-1,dow,doy);let nextW=weekOfGivenYear(marker,y+1,dow,doy);return nextW>=1?Math.min(w,nextW):w}function weekOfGivenYear(marker,year,dow,doy){let firstWeekStart=arrayToUtcDate([year,0,1+firstWeekOffset(year,dow,doy)]),dayStart=startOfDay5(marker),days=Math.round(diffDays4(firstWeekStart,dayStart));return Math.floor(days/7)+1}function firstWeekOffset(year,dow,doy){let fwd=7+dow-doy;return-((7+arrayToUtcDate([year,0,fwd]).getUTCDay()-dow)%7)+fwd-1}function dateToLocalArray(date){return[date.getFullYear(),date.getMonth(),date.getDate(),date.getHours(),date.getMinutes(),date.getSeconds(),date.getMilliseconds()]}function arrayToLocalDate(a){return new Date(a[0],a[1]||0,a[2]==null?1:a[2],a[3]||0,a[4]||0,a[5]||0)}function dateToUtcArray(date){return[date.getUTCFullYear(),date.getUTCMonth(),date.getUTCDate(),date.getUTCHours(),date.getUTCMinutes(),date.getUTCSeconds(),date.getUTCMilliseconds()]}function arrayToUtcDate(a){return a.length===1&&(a=a.concat([0])),new Date(Date.UTC(...a))}function isValidDate(m){return!isNaN(m.valueOf())}function timeAsMs(m){return m.getUTCHours()*1e3*60*60+m.getUTCMinutes()*1e3*60+m.getUTCSeconds()*1e3+m.getUTCMilliseconds()}var calendarSystemClassMap={};function registerCalendarSystem(name,theClass){calendarSystemClassMap[name]=theClass}function createCalendarSystem(name){return new calendarSystemClassMap[name]}var GregorianCalendarSystem=class{getMarkerYear(d){return d.getUTCFullYear()}getMarkerMonth(d){return d.getUTCMonth()}getMarkerDay(d){return d.getUTCDate()}arrayToMarker(arr){return arrayToUtcDate(arr)}markerToArray(marker){return dateToUtcArray(marker)}};registerCalendarSystem("gregory",GregorianCalendarSystem);function parseRange(input,dateEnv){let start=null,end=null;return input.start&&(start=dateEnv.createMarker(input.start)),input.end&&(end=dateEnv.createMarker(input.end)),!start&&!end||start&&end&&end<start?null:{start,end}}function invertRanges(ranges,constraintRange){let invertedRanges=[],{start}=constraintRange,i,dateRange;for(ranges.sort(compareRanges),i=0;i<ranges.length;i+=1)dateRange=ranges[i],dateRange.start>start&&invertedRanges.push({start,end:dateRange.start}),dateRange.end>start&&(start=dateRange.end);return start<constraintRange.end&&invertedRanges.push({start,end:constraintRange.end}),invertedRanges}function compareRanges(range0,range1){return range0.start.valueOf()-range1.start.valueOf()}function intersectRanges(range0,range1){let{start,end}=range0,newRange=null;return range1.start!==null&&(start===null?start=range1.start:start=new Date(Math.max(start.valueOf(),range1.start.valueOf()))),range1.end!=null&&(end===null?end=range1.end:end=new Date(Math.min(end.valueOf(),range1.end.valueOf()))),(start===null||end===null||start<end)&&(newRange={start,end}),newRange}function rangesEqual(range0,range1){return(range0.start===null?null:range0.start.valueOf())===(range1.start===null?null:range1.start.valueOf())&&(range0.end===null?null:range0.end.valueOf())===(range1.end===null?null:range1.end.valueOf())}function rangesIntersect(range0,range1){return(range0.end===null||range1.start===null||range0.end>range1.start)&&(range0.start===null||range1.end===null||range0.start<range1.end)}function rangeContainsRange(outerRange,innerRange){return(outerRange.start===null||innerRange.start!==null&&innerRange.start>=outerRange.start)&&(outerRange.end===null||innerRange.end!==null&&innerRange.end<=outerRange.end)}function rangeContainsMarker(range,date){return(range.start===null||date>=range.start)&&(range.end===null||date<range.end)}function constrainMarkerToRange(date,range){return range.start!=null&&date<range.start?range.start:range.end!=null&&date>=range.end?new Date(range.end.valueOf()-1):date}function expandZonedInstant(dateInfo,calendarSystem){let a=calendarSystem.markerToArray(dateInfo.marker);return{marker:dateInfo.marker,instantMs:dateInfo.instantMs,timeZoneOffset:(dateInfo.marker.valueOf()-dateInfo.instantMs)/6e4,array:a,year:a[0],month:a[1],day:a[2],hour:a[3],minute:a[4],second:a[5],millisecond:a[6]}}function createVerboseFormattingArg(start,end,context){let startInfo=expandZonedInstant(start,context.calendarSystem),endInfo=end?expandZonedInstant(end,context.calendarSystem):null;return{date:startInfo,start:startInfo,end:endInfo,timeZone:context.timeZone,localeCodes:context.locale.codes}}function isInt(n){return n%1===0}function padStart(val,len){let s=String(val);return"000".substr(0,len-s.length)+s}var INTERNAL_UNITS=["years","months","days","milliseconds"],PARSE_RE=/^(-?)(?:(\d+)\.)?(\d+):(\d\d)(?::(\d\d)(?:\.(\d\d\d))?)?/;function createDuration(input,unit){return typeof input=="string"?parseString(input):typeof input=="object"&&input?parseObject(input):typeof input=="number"?parseObject({[unit||"milliseconds"]:input}):null}function parseString(s){let m=PARSE_RE.exec(s);if(m){let sign=m[1]?-1:1;return{years:0,months:0,days:sign*(m[2]?parseInt(m[2],10):0),milliseconds:sign*((m[3]?parseInt(m[3],10):0)*60*60*1e3+(m[4]?parseInt(m[4],10):0)*60*1e3+(m[5]?parseInt(m[5],10):0)*1e3+(m[6]?parseInt(m[6],10):0))}}return null}function parseObject(obj){let duration={years:obj.years||obj.year||0,months:obj.months||obj.month||0,days:obj.days||obj.day||0,milliseconds:(obj.hours||obj.hour||0)*60*60*1e3+(obj.minutes||obj.minute||0)*60*1e3+(obj.seconds||obj.second||0)*1e3+(obj.milliseconds||obj.millisecond||obj.ms||0)},weeks=obj.weeks||obj.week;return weeks&&(duration.days+=weeks*7,duration.specifiedWeeks=!0),duration}function durationsEqual(d0,d1){return d0.years===d1.years&&d0.months===d1.months&&d0.days===d1.days&&d0.milliseconds===d1.milliseconds}function addDurations(d0,d1){return{years:d0.years+d1.years,months:d0.months+d1.months,days:d0.days+d1.days,milliseconds:d0.milliseconds+d1.milliseconds}}function subtractDurations(d1,d0){return{years:d1.years-d0.years,months:d1.months-d0.months,days:d1.days-d0.days,milliseconds:d1.milliseconds-d0.milliseconds}}function multiplyDuration(d,n){return{years:d.years*n,months:d.months*n,days:d.days*n,milliseconds:d.milliseconds*n}}function asRoughYears(dur){return asRoughDays(dur)/365}function asRoughMonths(dur){return asRoughDays(dur)/30}function asRoughDays(dur){return asRoughMs(dur)/864e5}function asRoughMs(dur){return dur.years*(365*864e5)+dur.months*(30*864e5)+dur.days*864e5+dur.milliseconds}function wholeDivideDurations(numerator,denominator){let res=null;for(let i=0;i<INTERNAL_UNITS.length;i+=1){let unit=INTERNAL_UNITS[i];if(denominator[unit]){let localRes=numerator[unit]/denominator[unit];if(!isInt(localRes)||res!==null&&res!==localRes)return null;res=localRes}else if(numerator[unit])return null}return res}function greatestDurationDenominator(dur){let ms=dur.milliseconds;if(ms){if(ms%1e3!==0)return{unit:"millisecond",value:ms};if(ms%(1e3*60)!==0)return{unit:"second",value:ms/1e3};if(ms%(1e3*60*60)!==0)return{unit:"minute",value:ms/(1e3*60)};if(ms)return{unit:"hour",value:ms/(1e3*60*60)}}return dur.days?dur.specifiedWeeks&&dur.days%7===0?{unit:"week",value:dur.days/7}:{unit:"day",value:dur.days}:dur.months?{unit:"month",value:dur.months}:dur.years?{unit:"year",value:dur.years}:{unit:"millisecond",value:0}}function buildIsoString(marker,timeZoneOffset,stripZeroTime=!1){let s=marker.toISOString();return s=s.replace(".000",""),stripZeroTime&&(s=s.replace("T00:00:00Z","")),s.length>10&&(timeZoneOffset==null?s=s.replace("Z",""):timeZoneOffset!==0&&(s=s.replace("Z",formatTimeZoneOffset(timeZoneOffset,!0)))),s}function formatDayString(marker){return marker.toISOString().replace(/T.*$/,"")}function formatIsoTimeString(marker){return padStart(marker.getUTCHours(),2)+":"+padStart(marker.getUTCMinutes(),2)+":"+padStart(marker.getUTCSeconds(),2)}function formatTimeZoneOffset(minutes,doIso=!1){let sign=minutes<0?"-":"+",abs=Math.abs(minutes),hours=Math.floor(abs/60),mins=Math.round(abs%60);return doIso?`${sign+padStart(hours,2)}:${padStart(mins,2)}`:`GMT${sign}${hours}${mins?`:${padStart(mins,2)}`:""}`}function joinDateTimeFormatParts(parts){let s="";for(let part of parts)s+=part.value;return s}var ISO_RE=/^\s*(\d{4})(-?(\d{2})(-?(\d{2})([T ](\d{2}):?(\d{2})(:?(\d{2})(\.(\d+))?)?(Z|(([-+])(\d{2})(:?(\d{2}))?))?)?)?)?$/;function parse(str){let m=ISO_RE.exec(str);if(m){let marker=new Date(Date.UTC(Number(m[1]),m[3]?Number(m[3])-1:0,Number(m[5]||1),Number(m[7]||0),Number(m[8]||0),Number(m[10]||0),m[12]?+`0.${m[12]}`*1e3:0));if(isValidDate(marker)){let timeZoneOffset=null;return m[13]&&(timeZoneOffset=(m[15]==="-"?-1:1)*(Number(m[16]||0)*60+Number(m[18]||0))),{marker,isTimeUnspecified:!m[6],timeZoneOffset}}}return null}var DateEnv=class{constructor(settings){this.timeZone=settings.timeZone,this.calendarSystem=createCalendarSystem(settings.calendarSystem),this.locale=settings.locale,this.weekDow=settings.locale.week.dow,this.weekDoy=settings.locale.week.doy,settings.weekNumberCalculation==="ISO"&&(this.weekDow=1,this.weekDoy=4),typeof settings.firstDay=="number"&&(this.weekDow=settings.firstDay),typeof settings.weekNumberCalculation=="function"&&(this.weekNumberFunc=settings.weekNumberCalculation),this.weekTextLong=settings.weekTextLong,this.weekTextShort=settings.weekTextShort??settings.weekTextLong,this.cmdFormatter=settings.cmdFormatter}createMarker(input){let meta=this.createMarkerMeta(input);return meta===null?null:meta.marker}createNowMarker(){return this.timestampToMarker(new Date().valueOf())}createMarkerMeta(input){if(typeof input=="string")return this.parse(input);let marker=null,instantMs;return typeof input=="number"?(marker=this.timestampToMarker(input),instantMs=input):input instanceof Date?(input=input.valueOf(),isNaN(input)||(marker=this.timestampToMarker(input),instantMs=input)):Array.isArray(input)&&(marker=arrayToUtcDate(input)),marker===null||!isValidDate(marker)?null:{marker,isTimeUnspecified:!1,instantMs}}parse(s){let parts=parse(s);if(parts===null)return null;let{marker}=parts,instantMs;return parts.timeZoneOffset!==null&&(instantMs=marker.valueOf()-parts.timeZoneOffset*60*1e3,marker=this.timestampToMarker(instantMs)),{marker,isTimeUnspecified:parts.isTimeUnspecified,instantMs}}getYear(marker){return this.calendarSystem.getMarkerYear(marker)}getMonth(marker){return this.calendarSystem.getMarkerMonth(marker)}getDay(marker){return this.calendarSystem.getMarkerDay(marker)}add(marker,dur){let a=this.calendarSystem.markerToArray(marker);return a[0]+=dur.years,a[1]+=dur.months,a[2]+=dur.days,a[6]+=dur.milliseconds,this.calendarSystem.arrayToMarker(a)}subtract(marker,dur){let a=this.calendarSystem.markerToArray(marker);return a[0]-=dur.years,a[1]-=dur.months,a[2]-=dur.days,a[6]-=dur.milliseconds,this.calendarSystem.arrayToMarker(a)}addYears(marker,n){let a=this.calendarSystem.markerToArray(marker);return a[0]+=n,this.calendarSystem.arrayToMarker(a)}addMonths(marker,n){let a=this.calendarSystem.markerToArray(marker);return a[1]+=n,this.calendarSystem.arrayToMarker(a)}diffWholeYears(m0,m1){let{calendarSystem}=this;return timeAsMs(m0)===timeAsMs(m1)&&calendarSystem.getMarkerDay(m0)===calendarSystem.getMarkerDay(m1)&&calendarSystem.getMarkerMonth(m0)===calendarSystem.getMarkerMonth(m1)?calendarSystem.getMarkerYear(m1)-calendarSystem.getMarkerYear(m0):null}diffWholeMonths(m0,m1){let{calendarSystem}=this;return timeAsMs(m0)===timeAsMs(m1)&&calendarSystem.getMarkerDay(m0)===calendarSystem.getMarkerDay(m1)?calendarSystem.getMarkerMonth(m1)-calendarSystem.getMarkerMonth(m0)+(calendarSystem.getMarkerYear(m1)-calendarSystem.getMarkerYear(m0))*12:null}greatestWholeUnit(m0,m1){let n=this.diffWholeYears(m0,m1);return n!==null?{unit:"year",value:n}:(n=this.diffWholeMonths(m0,m1),n!==null?{unit:"month",value:n}:(n=diffWholeWeeks(m0,m1),n!==null?{unit:"week",value:n}:(n=diffWholeDays(m0,m1),n!==null?{unit:"day",value:n}:(n=diffHours4(m0,m1),isInt(n)?{unit:"hour",value:n}:(n=diffMinutes4(m0,m1),isInt(n)?{unit:"minute",value:n}:(n=diffSeconds4(m0,m1),isInt(n)?{unit:"second",value:n}:{unit:"millisecond",value:m1.valueOf()-m0.valueOf()}))))))}countDurationsBetween(m0,m1,d){let diff3;return d.years&&(diff3=this.diffWholeYears(m0,m1),diff3!==null)?diff3/asRoughYears(d):d.months&&(diff3=this.diffWholeMonths(m0,m1),diff3!==null)?diff3/asRoughMonths(d):d.days&&(diff3=diffWholeDays(m0,m1),diff3!==null)?diff3/asRoughDays(d):(m1.valueOf()-m0.valueOf())/asRoughMs(d)}startOf(m,unit){return unit==="year"?this.startOfYear(m):unit==="month"?this.startOfMonth(m):unit==="week"?this.startOfWeek(m):unit==="day"?startOfDay5(m):unit==="hour"?startOfHour4(m):unit==="minute"?startOfMinute4(m):unit==="second"?startOfSecond4(m):null}startOfYear(m){return this.calendarSystem.arrayToMarker([this.calendarSystem.getMarkerYear(m)])}startOfMonth(m){return this.calendarSystem.arrayToMarker([this.calendarSystem.getMarkerYear(m),this.calendarSystem.getMarkerMonth(m)])}startOfWeek(m){return this.calendarSystem.arrayToMarker([this.calendarSystem.getMarkerYear(m),this.calendarSystem.getMarkerMonth(m),m.getUTCDate()-(m.getUTCDay()-this.weekDow+7)%7])}computeWeekNumber(marker){return this.weekNumberFunc?this.weekNumberFunc(this.toDate(marker)):weekOfYear3(marker,this.weekDow,this.weekDoy)}formatToParts(marker,formatter,dateOptions={}){return formatter.formatToParts(this.toZonedInstant(marker,dateOptions.instantMs),this)}formatRangeToParts(start,end,formatter,dateOptions={}){let{endInstantMs}=dateOptions;return dateOptions.isEndExclusive&&(end=addMs(end,-1),endInstantMs!=null&&(endInstantMs-=1)),formatter.formatRangeToParts(this.toZonedInstant(start,dateOptions.startInstantMs),this.toZonedInstant(end,endInstantMs),this)}toZonedInstant(marker,instantMs){return instantMs==null&&(instantMs=this.toDate(marker).valueOf()),{marker:this.timestampToMarker(instantMs),instantMs}}formatIso(marker,extraOptions={}){let timeZoneOffset=null;return extraOptions.omitTimeZoneOffset||(timeZoneOffset=this.offsetForMarker(marker)),buildIsoString(marker,timeZoneOffset,extraOptions.omitTime)}timestampToMarker(ms){if(this.timeZone==="local")return arrayToUtcDate(dateToLocalArray(new Date(ms)));if(this.timeZone==="UTC")return new Date(ms);let zdt=toZonedDateTimeISO3(fromEpochMilliseconds3(ms),this.timeZone);return new Date(Date.UTC(zdt.year,zdt.month-1,zdt.day,zdt.hour,zdt.minute,zdt.second,zdt.millisecond))}offsetForMarker(m){return this.timeZone==="local"?-arrayToLocalDate(dateToUtcArray(m)).getTimezoneOffset():this.timeZone==="UTC"?0:offsetNanoseconds3(toZonedDateTime(create(m.getUTCFullYear(),m.getUTCMonth()+1,m.getUTCDate(),m.getUTCHours(),m.getUTCMinutes(),m.getUTCSeconds(),m.getUTCMilliseconds()),this.timeZone))/(1e9*60)}toDate(m){return this.timeZone==="local"?arrayToLocalDate(dateToUtcArray(m)):this.timeZone==="UTC"?new Date(m.valueOf()):new Date(toZonedDateTime(create(m.getUTCFullYear(),m.getUTCMonth()+1,m.getUTCDate(),m.getUTCHours(),m.getUTCMinutes(),m.getUTCSeconds(),m.getUTCMilliseconds()),this.timeZone).epochMilliseconds)}},EXTENDED_SETTINGS=new Set(["week","meridiem","omitZeroMinute","omitCommas","forceCommas","omitTrailing","weekdayJustify"]),MERIDIEM_RE=/([ap])\.?m\.?/i,COMMA_RE=/,/g,LTR_RE=/\u200e/g,TRAILING_RE=/[\s.,]+$/,WHITESPACE_ONLY_RE=/^\s+$/,NativeDateFormatter=class{constructor(options){let standardOptions={},extendedOptions={};for(let name in options)EXTENDED_SETTINGS.has(name)?extendedOptions[name]=options[name]:standardOptions[name]=options[name];standardOptions.timeZoneName&&(standardOptions.timeZoneName="shortOffset"),this.timeZoneOnly=Object.keys(standardOptions).length===1&&!!standardOptions.timeZoneName,this.weekOnly=!!(!Object.keys(standardOptions).length&&extendedOptions.week),this.timeZoneOnly||(standardOptions.timeZoneName&&(standardOptions.hour||(standardOptions.hour="2-digit"),standardOptions.minute||(standardOptions.minute="2-digit")),extendedOptions.omitZeroMinute&&(standardOptions.second||standardOptions.fractionalSecondDigits)&&delete extendedOptions.omitZeroMinute),this.standardOptions=standardOptions,this.extendedOptions=extendedOptions}formatToParts(date,context){let{extendedOptions}=this;if(this.timeZoneOnly)return this.getFormats(context).normalFormat.formatToParts(date.instantMs).filter(part=>part.type==="timeZoneName");if(this.weekOnly)return formatWeekNumberParts(context.computeWeekNumber(date.marker),context.weekTextLong,context.weekTextShort,context.locale,extendedOptions.week);let{normalFormat,zeroFormat}=this.getFormats(context),parts=(zeroFormat&&!date.marker.getUTCMinutes()?zeroFormat:normalFormat).formatToParts(date.instantMs);return postProcessParts(parts,extendedOptions)}formatRangeToParts(start,end,context){let{extendedOptions}=this;if(this.timeZoneOnly||this.weekOnly)return this.formatToParts(start,context).map(part=>({source:part.type==="literal"?"shared":"startRange",...part}));let{normalFormat,zeroFormat}=this.getFormats(context),parts=(zeroFormat&&!start.marker.getUTCMinutes()&&!end.marker.getUTCMinutes()?zeroFormat:normalFormat).formatRangeToParts(start.instantMs,end.instantMs);return postProcessRangeParts(parts,extendedOptions)}getFormats(context){if(this.cachedContext!==context){let{extendedOptions}=this,{codes}=context.locale,standardOptions={...this.standardOptions,timeZone:context.timeZone==="local"?void 0:context.timeZone},normalFormat=new Intl.DateTimeFormat(codes,standardOptions),zeroFormat;if(extendedOptions.omitZeroMinute){let zeroProps={...standardOptions};delete zeroProps.minute,zeroFormat=new Intl.DateTimeFormat(codes,zeroProps)}this.cachedContext=context,this.cachedFormats={normalFormat,zeroFormat}}return this.cachedFormats}};function processPartsLoop(parts,extendedOptions){let priorLiteral;for(let part of parts){let isLiteral=part.type==="literal";if(isLiteral||part.type==="dayPeriod"){let s=part.value;if(s=s.replace(LTR_RE,""),extendedOptions.omitCommas&&(s=s.replace(COMMA_RE,"")),!isLiteral){let{meridiem}=extendedOptions;meridiem===!1?s=s.replace(MERIDIEM_RE,""):meridiem==="narrow"?s=s.replace(MERIDIEM_RE,(_m0,m1)=>m1.toLocaleLowerCase()):meridiem==="short"?s=s.replace(MERIDIEM_RE,(_m0,m1)=>`${m1.toLocaleLowerCase()}m`):meridiem==="lowercase"&&(s=s.replace(MERIDIEM_RE,m0=>m0.toLocaleLowerCase())),priorLiteral&&(priorLiteral.value=priorLiteral.value.trimEnd())}part.value=s}priorLiteral=isLiteral?part:void 0}}function postProcessParts(parts,extendedOptions){if(processPartsLoop(parts,extendedOptions),extendedOptions.weekdayJustify&&parts.length===3&&WHITESPACE_ONLY_RE.test(parts[1].value)&&parts[extendedOptions.weekdayJustify==="start"?2:0].type==="weekday"&&parts.reverse(),extendedOptions.forceCommas)for(let part of parts)part.type==="literal"&&WHITESPACE_ONLY_RE.test(part.value)&&(part.value=`,${part.value}`);return extendedOptions.omitTrailing&&stripTrailingLiteral(parts),parts.filter(part=>part.value)}function postProcessRangeParts(parts,extendedOptions){if(processPartsLoop(parts,extendedOptions),extendedOptions.forceCommas)for(let part of parts)part.type==="literal"&&WHITESPACE_ONLY_RE.test(part.value)&&(part.value=`,${part.value}`);return extendedOptions.omitTrailing&&stripTrailingLiteral(parts),parts.filter(part=>part.value)}function stripTrailingLiteral(parts){let lastPart=parts[parts.length-1];lastPart?.type==="literal"&&(lastPart.value=lastPart.value.replace(TRAILING_RE,""),lastPart.value||parts.pop())}function formatWeekNumberParts(num,weekTextLong,weekTextShort,locale,display){let parts=[];return display==="long"?parts.push({type:"literal",value:weekTextLong}):(display==="short"||display==="narrow")&&parts.push({type:"literal",value:weekTextShort}),(display==="long"||display==="short")&&parts.push({type:"literal",value:" "}),parts.push({type:"week",value:locale.simpleNumberFormat.format(num)}),locale.options.direction==="rtl"&&parts.reverse(),parts}var CmdDateFormatter=class{constructor(cmdStr){this.cmdStr=cmdStr}formatToParts(date,context){let res=context.cmdFormatter(this.cmdStr,createVerboseFormattingArg(date,null,context));return Array.isArray(res)?res:[{type:"literal",value:res}]}formatRangeToParts(start,end,context){let res=context.cmdFormatter(this.cmdStr,createVerboseFormattingArg(start,end,context));return Array.isArray(res)?res.map(part=>({source:"shared",...part})):[{source:"shared",type:"literal",value:res}]}},FuncDateFormatter=class{constructor(func){this.func=func}formatToParts(date,context){return[{type:"literal",value:this.func(createVerboseFormattingArg(date,null,context))}]}formatRangeToParts(start,end,context){return[{source:"shared",type:"literal",value:this.func(createVerboseFormattingArg(start,end,context))}]}};var classNames={popoverZ:"fc-ZK",isolate:"fc-5R",borderBoxRoot:"fc-O6",notAllowed:"fc-fF",noScrollbars:"fc-Rp",noShrink:"fc-tp",calendarScreenRoot:"fc-MU",safeTiles:"fc-rr",calendarPrintRoot:"fc-ob",cursorPointer:"fc-iz",cursorResizeT:"fc-W6",cursorResizeB:"fc-9e",cursorResizeS:"fc-wb",cursorResizeE:"fc-0b",cursorColResizer:"fc-Gz",hit:"fc-wZ",hitX:"fc-oJ",hitY:"fc-9A",hitXSkinny:"fc-Yf",selectNone:"fc-AQ",invisible:"fc-MJ",borderless:"fc-Yq",borderlessX:"fc-3R",borderlessY:"fc-dv",borderlessTop:"fc-Yk",borderlessBottom:"fc-b1",borderlessStart:"fc-W7",borderlessEnd:"fc-Eu",flexRow:"fc-bH",flexCol:"fc-Ih",grow:"fc-BH",liquid:"fc-1Y",minHeight0:"fc-Ux",liquidX:"fc-ZM",printTable:"fc-Gx",noPadding:"fc-33",noPaddingY:"fc-5V",noMargin:"fc-b4",noMarginY:"fc-H8",noMarginX:"fc-Oq",whiteSpaceNoWrap:"fc-oX",whiteSpacePre:"fc-LF",overflowAnchorNone:"fc-Gg",pointerEventsNone:"fc-87",crop:"fc-5o",cropNowrap:"fc-7P",rel:"fc-XV",abs:"fc-Ew",start0:"fc-bN",end0:"fc-cH",fill:"fc-wd",fillTop:"fc-sd",fillX:"fc-ar",fillY:"fc-0H",fillStart:"fc-63",sticky:"fc-WL",stickyT:"fc-i6",stickyS:"fc-n4",tableHeaderSticky:"fc-q0",contentBox:"fc-F2",offscreen:"fc-rZ",alignCenter:"fc-dG",alignStart:"fc-jB",alignEnd:"fc-6B",footerScrollbarSticky:"fc-89",footerScrollbar:"fc-Se",breakInsideAvoid:"fc-qu",printCellContentMinHeight:"fc-sn",flowRoot:"fc-os",z0:"fc-P0",z1:"fc-hB",z2:"fc-b7",z3:"fc-BR",z4:"fc-eM",z5:"fc-zy",z1000:"fc-xI",z9999:"fc-hJ",focusZ2:"fc-0t",internalTimelineSlot:"fc-wp",internalEvent:"fc-ZR",internalEventMirror:"fc-Ai",internalEventDraggable:"fc-cj",internalEventSelected:"fc-dI",internalEventResizable:"fc-td",internalEventResizer:"fc-AJ",internalEventResizerStart:"fc-0y",internalEventResizerEnd:"fc-oN",internalBgEvent:"fc-vZ",internalMoreLink:"fc-Gh",internalNavLink:"fc-JP",internalPopover:"fc-WR",internalView:"fc-25",internalScroller:"fc-8b"};function joinClassNames(...args){return args.filter(Boolean).join(" ")}function fracToCssDim(frac){return frac*100+"%"}function createFormatter(input){return typeof input=="object"&&input?new NativeDateFormatter(input):typeof input=="string"?new CmdDateFormatter(input):typeof input=="function"?new FuncDateFormatter(input):null}function warn(...args){console.warn("FullCalendar:",...args)}var warnedClassNameOptions={};function refineClassName(input,optionName){return!input||typeof input=="string"?input:(warnInvalidClassName(optionName),"")}function refineClassNameGenerator(input,optionName){return typeof input=="function"?renderProps=>refineClassName(input(renderProps),optionName):refineClassName(input,optionName)}function warnInvalidClassName(optionName){warnedClassNameOptions[optionName]||(warn(`Invalid option \`${optionName}\`: expected a className string or a falsy value.`),warnedClassNameOptions[optionName]=!0)}function preventDefault(ev){ev.preventDefault()}function buildDelegationHandler(selector,handler){return ev=>{let matchedChild=ev.target.closest(selector);matchedChild&&handler.call(matchedChild,ev,matchedChild)}}function listenBySelector(container,eventType,selector,handler){let attachedHandler=buildDelegationHandler(selector,handler);return container.addEventListener(eventType,attachedHandler),()=>{container.removeEventListener(eventType,attachedHandler)}}function listenToHoverBySelector(container,selector,onMouseEnter,onMouseLeave){let currentMatchedChild;return listenBySelector(container,"mouseover",selector,(mouseOverEv,matchedChild)=>{if(matchedChild!==currentMatchedChild){currentMatchedChild=matchedChild,onMouseEnter(mouseOverEv,matchedChild);let realOnMouseLeave=mouseLeaveEv=>{currentMatchedChild=null,onMouseLeave(mouseLeaveEv,matchedChild),matchedChild.removeEventListener("mouseleave",realOnMouseLeave)};matchedChild.addEventListener("mouseleave",realOnMouseLeave)}})}var transitionEventNames=["webkitTransitionEnd","otransitionend","oTransitionEnd","msTransitionEnd","transitionend"];function whenTransitionDone(el,callback){let realCallback=ev=>{callback(ev),transitionEventNames.forEach(eventName=>{el.removeEventListener(eventName,realCallback)})};transitionEventNames.forEach(eventName=>{el.addEventListener(eventName,realCallback)})}function createAriaClickAttrs(handler){return{onClick:handler,...createAriaKeyboardAttrs(handler)}}function createAriaKeyboardAttrs(handler){return{tabIndex:0,onKeyDown(ev){(ev.key==="Enter"||ev.key===" ")&&(handler(ev),ev.preventDefault())}}}var guidNumber=0;function guid(){return guidNumber+=1,String(guidNumber)}function disableCursor(){document.body.classList.add(classNames.notAllowed)}function enableCursor(){document.body.classList.remove(classNames.notAllowed)}function preventSelection(el){el.style.userSelect="none",el.style.webkitUserSelect="none",el.addEventListener("selectstart",preventDefault)}function allowSelection(el){el.style.userSelect="",el.style.webkitUserSelect="",el.removeEventListener("selectstart",preventDefault)}function preventContextMenu(el){el.addEventListener("contextmenu",preventDefault)}function allowContextMenu(el){el.removeEventListener("contextmenu",preventDefault)}function parseFieldSpecs(input){let specs=[],tokens=[],i,token;for(typeof input=="string"?tokens=input.split(/\s*,\s*/):typeof input=="function"?tokens=[input]:Array.isArray(input)&&(tokens=input),i=0;i<tokens.length;i+=1)token=tokens[i],typeof token=="string"?specs.push(token.charAt(0)==="-"?{field:token.substring(1),order:-1}:{field:token,order:1}):typeof token=="function"&&specs.push({func:token});return specs}function compareByFieldSpecs(obj0,obj1,fieldSpecs){let i,cmp;for(i=0;i<fieldSpecs.length;i+=1)if(cmp=compareByFieldSpec(obj0,obj1,fieldSpecs[i]),cmp)return cmp;return 0}function compareByFieldSpec(obj0,obj1,fieldSpec){return fieldSpec.func?fieldSpec.func(obj0,obj1):flexibleCompare(obj0[fieldSpec.field],obj1[fieldSpec.field])*(fieldSpec.order||1)}function flexibleCompare(a,b){return!a&&!b?0:b==null?-1:a==null?1:typeof a=="string"||typeof b=="string"?String(a).localeCompare(String(b)):a-b}function formatWithOrdinals(formatter,args,fallbackText){return typeof formatter=="function"?formatter(...args):typeof formatter=="string"?args.reduce((str,arg,index2)=>str.replace("$"+index2,arg||""),formatter):fallbackText}function compareNumbers2(a,b){return a-b}function valuesIdentical(a,b){return a===b}function computeViewBorderless(options){let borderless=options.borderless;return{borderlessX:!!(options.borderlessX??borderless),borderlessTop:!!(options.borderlessTop??borderless),borderlessBottom:!!(options.borderlessBottom??borderless)}}var{hasOwnProperty}=Object.prototype;function filterHash(hash,func){let filtered={};for(let key in hash)func(hash[key],key)&&(filtered[key]=hash[key]);return filtered}function mapHash(hash,func){let newHash={};for(let key in hash)newHash[key]=func(hash[key],key);return newHash}function hashValuesToArray(obj){let a=[];for(let key in obj)a.push(obj[key]);return a}function arrayToHash(a){let hash={};for(let item of a)hash[item]=!0;return hash}function isMaybePropsEqualDepth1(props0,props1){return typeof props0=="object"&&props0&&typeof props1=="object"&&props1?isPropsEqualWithFunc(props0,props1,isPropsEqualShallow):props0===props1}function isPropsEqualWithFunc(props0,props1,valuesEqual){if(props0===props1)return!0;for(let key in props0)if(hasOwnProperty.call(props0,key)&&!(key in props1))return!1;for(let key in props1)if(hasOwnProperty.call(props1,key)&&(!(key in props0)||!valuesEqual(props0[key],props1[key],key)))return!1;return!0}function isMaybePropsEqualShallow(props0,props1){return typeof props0=="object"&&typeof props1=="object"&&props0&&props1?isPropsEqualShallow(props0,props1):props0===props1}function isPropsEqualShallow(props0,props1){return isPropsEqualWithFunc(props0,props1,valuesIdentical)}function isPropsEqualWithMap(props0,props1,equalityFuncMap){return isPropsEqualWithFunc(props0,props1,(val0,val1,key)=>{let equalityFunc=equalityFuncMap[key];return equalityFunc?equalityFunc(val0,val1):val0===val1})}function getUnequalProps(props0,props1){let keys=[];for(let key in props0)hasOwnProperty.call(props0,key)&&(key in props1||keys.push(key));for(let key in props1)hasOwnProperty.call(props1,key)&&props0[key]!==props1[key]&&keys.push(key);return keys}function mergeMaybePropsDepth1(props0,props1){return props0?mergePropsWithFunc(props0,props1,mergePropsShallow):props1}function mergePropsWithFunc(props0,props1,mergeValues){let dest={};for(let key in props0)hasOwnProperty.call(props0,key)&&(key in props1||(dest[key]=props0[key]));for(let key in props1)hasOwnProperty.call(props1,key)&&(key in props0?dest[key]=mergeValues(props0[key],props1[key]):dest[key]=props1[key]);return dest}function mergePropsShallow(props0,props1){return Object.assign({},props0,props1)}function flatArray(items){let res=[];for(let item of items)if(Array.isArray(item))for(let subItem of item)res.push(subItem);else res.push(item);return res}function flatMapArray(inputs,mapFunc){let res=[];for(let i=0;i<inputs.length;i+=1){let output=mapFunc(inputs[i],i);if(Array.isArray(output))for(let subOutput of output)res.push(subOutput);else res.push(output)}return res}function isMaybeArraysEqual(array0,array1){return Array.isArray(array0)&&Array.isArray(array1)?isArraysEqual(array0,array1):array0===array1}function isArraysEqual(array0,array1,itemsEqual=valuesIdentical){if(array0===array1)return!0;let len=array0.length,i;if(len!==array1.length)return!1;for(i=0;i<len;i+=1)if(!itemsEqual(array0[i],array1[i]))return!1;return!0}var BASE_OPTION_REFINERS={navLinkDayClick:identity,navLinkWeekClick:identity,duration:createDuration,buttons:identity,toolbarElements:identity,prevText:String,nextText:String,prevYearText:String,nextYearText:String,todayText:String,yearText:String,monthText:String,weekTextLong:String,weekTextShort:String,dayText:String,listText:identity,todayHint:identity,prevHint:identity,nextHint:identity,buttonDisplay:identity,buttonGroupClass:refineClassNameGenerator,buttonClass:refineClassNameGenerator,defaultAllDayEventDuration:createDuration,defaultTimedEventDuration:createDuration,nextDayThreshold:createDuration,scrollTime:createDuration,scrollTimeReset:Boolean,slotMinTime:createDuration,slotMaxTime:createDuration,popoverFormat:createFormatter,slotDuration:createDuration,snapDuration:createDuration,headerToolbar:identity,footerToolbar:identity,forceEventDuration:Boolean,dayLaneClass:refineClassNameGenerator,dayLaneInnerClass:refineClassNameGenerator,dayLaneDidMount:identity,dayLaneWillUnmount:identity,initialView:String,aspectRatio:Number,weekends:Boolean,weekNumberCalculation:identity,weekNumbers:Boolean,weekNumberHeaderClass:refineClassNameGenerator,weekNumberHeaderInnerClass:refineClassNameGenerator,weekNumberHeaderContent:identity,weekNumberHeaderDidMount:identity,weekNumberHeaderWillUnmount:identity,inlineWeekNumberClass:refineClassNameGenerator,inlineWeekNumberContent:identity,inlineWeekNumberDidMount:identity,inlineWeekNumberWillUnmount:identity,editable:Boolean,controller:identity,nowIndicator:Boolean,nowIndicatorSnap:identity,nowIndicatorHeaderClass:refineClassNameGenerator,nowIndicatorHeaderContent:identity,nowIndicatorHeaderDidMount:identity,nowIndicatorHeaderWillUnmount:identity,nowIndicatorDotClass:refineClassName,nowIndicatorLineClass:refineClassNameGenerator,nowIndicatorLineContent:identity,nowIndicatorLineDidMount:identity,nowIndicatorLineWillUnmount:identity,showNonCurrentDates:Boolean,lazyFetching:Boolean,startParam:String,endParam:String,timeZoneParam:String,timeZone:String,locales:identity,locale:identity,dragRevertDuration:Number,dragScroll:Boolean,allDayMaintainDuration:Boolean,unselectAuto:Boolean,dropAccept:identity,eventOrder:parseFieldSpecs,eventOrderStrict:Boolean,eventSlicing:Boolean,eventPrintLayout:String,longPressDelay:Number,eventDragMinDistance:Number,expandRows:Boolean,height:identity,contentHeight:identity,direction:String,colorScheme:String,weekNumberFormat:createFormatter,eventResizableFromStart:Boolean,displayEventTime:Boolean,displayEventEnd:Boolean,progressiveEventRendering:Boolean,businessHours:identity,initialDate:identity,now:identity,eventDataTransform:identity,tableHeaderSticky:identity,footerScrollbarSticky:identity,defaultAllDay:Boolean,eventSourceFailure:identity,eventSourceSuccess:identity,eventDisplay:String,eventStartEditable:Boolean,eventDurationEditable:Boolean,eventOverlap:identity,eventConstraint:identity,eventAllow:identity,eventColor:String,eventContrastColor:String,eventDidMount:identity,eventWillUnmount:identity,eventContent:identity,eventClass:refineClassNameGenerator,eventInnerClass:refineClassNameGenerator,eventTimeClass:refineClassNameGenerator,eventTitleClass:refineClassNameGenerator,eventBeforeClass:refineClassNameGenerator,eventAfterClass:refineClassNameGenerator,listItemEventClass:refineClassNameGenerator,listItemEventInnerClass:refineClassNameGenerator,listItemEventTimeClass:refineClassNameGenerator,listItemEventTitleClass:refineClassNameGenerator,listItemEventBeforeClass:refineClassNameGenerator,listItemEventAfterClass:refineClassNameGenerator,blockEventClass:refineClassNameGenerator,blockEventInnerClass:refineClassNameGenerator,blockEventTimeClass:refineClassNameGenerator,blockEventTitleClass:refineClassNameGenerator,blockEventBeforeClass:refineClassNameGenerator,blockEventAfterClass:refineClassNameGenerator,rowEventClass:refineClassNameGenerator,rowEventInnerClass:refineClassNameGenerator,rowEventTimeClass:refineClassNameGenerator,rowEventTitleClass:refineClassNameGenerator,rowEventTitleSticky:Boolean,rowEventBeforeClass:refineClassNameGenerator,rowEventBeforeContent:identity,rowEventAfterClass:refineClassNameGenerator,rowEventAfterContent:identity,columnEventClass:refineClassNameGenerator,columnEventInnerClass:refineClassNameGenerator,columnEventTimeClass:refineClassNameGenerator,columnEventTitleClass:refineClassNameGenerator,columnEventTitleSticky:Boolean,columnEventBeforeClass:refineClassNameGenerator,columnEventAfterClass:refineClassNameGenerator,backgroundEventClass:refineClassNameGenerator,backgroundEventDidMount:identity,backgroundEventWillUnmount:identity,backgroundEventContent:identity,backgroundEventInnerClass:refineClassNameGenerator,backgroundEventTitleClass:refineClassNameGenerator,backgroundEventColor:String,selectConstraint:identity,selectOverlap:identity,selectAllow:identity,droppable:Boolean,unselectCancel:String,slotHeaderFormat:identity,slotLaneClass:refineClassNameGenerator,slotLaneDidMount:identity,slotLaneWillUnmount:identity,slotHeaderClass:refineClassNameGenerator,slotHeaderInnerClass:refineClassNameGenerator,slotHeaderContent:identity,slotHeaderDidMount:identity,slotHeaderWillUnmount:identity,slotHeaderAlign:identity,slotHeaderSticky:identity,slotHeaderRowClass:refineClassName,slotHeaderDividerClass:refineClassNameGenerator,dayMaxEvents:identity,dayMaxEventRows:identity,dayMinWidth:Number,slotHeaderInterval:createDuration,dayHeaderClass:refineClassNameGenerator,dayHeaderInnerClass:refineClassNameGenerator,dayHeaderContent:identity,dayHeaderDidMount:identity,dayHeaderWillUnmount:identity,dayHeaderAlign:identity,_dayHeaderSticky:identity,dayHeaderRowClass:refineClassName,dayHeaderDividerClass:refineClassNameGenerator,dayRowClass:refineClassName,dayCellDidMount:identity,dayCellWillUnmount:identity,dayCellClass:refineClassNameGenerator,dayCellInnerClass:refineClassNameGenerator,dayCellTopContent:identity,dayCellTopClass:refineClassNameGenerator,dayCellTopInnerClass:refineClassNameGenerator,dayCellBottomClass:refineClassNameGenerator,allDaySlot:Boolean,allDayText:String,allDayHeaderClass:refineClassNameGenerator,allDayHeaderInnerClass:refineClassNameGenerator,allDayHeaderContent:identity,allDayHeaderDidMount:identity,allDayHeaderWillUnmount:identity,timedText:String,slotMinWidth:Number,slotMinHeight:Number,navLinks:Boolean,eventTimeFormat:createFormatter,rerenderDelay:Number,moreLinkText:identity,moreLinkHint:identity,selectMinDistance:Number,selectable:Boolean,selectLongPressDelay:Number,eventLongPressDelay:Number,selectMirror:Boolean,eventMaxStack:Number,eventMinHeight:Number,eventMinWidth:Number,eventShortHeight:Number,slotEventOverlap:Boolean,firstDay:Number,dayCount:Number,dateAlignment:String,dateIncrement:createDuration,hiddenDays:identity,fixedWeekCount:Boolean,validRange:identity,visibleRange:identity,titleFormat:identity,eventInteractive:Boolean,noEventsText:String,viewHint:identity,viewChangeHint:String,navLinkHint:identity,closeHint:String,eventsHint:String,headingLevel:Number,moreLinkClick:identity,moreLinkContent:identity,moreLinkDidMount:identity,moreLinkWillUnmount:identity,moreLinkClass:refineClassNameGenerator,moreLinkInnerClass:refineClassNameGenerator,rowMoreLinkClass:refineClassNameGenerator,rowMoreLinkInnerClass:refineClassNameGenerator,columnMoreLinkClass:refineClassNameGenerator,columnMoreLinkInnerClass:refineClassNameGenerator,navLinkClass:refineClassName,monthStartFormat:createFormatter,dayCellFormat:createFormatter,handleCustomRendering:identity,customRenderingMetaMap:identity,popoverClass:refineClassName,popoverCloseClass:refineClassName,popoverCloseContent:identity,dayNarrowWidth:Number,borderless:Boolean,borderlessX:Boolean,borderlessTop:Boolean,borderlessBottom:Boolean,fillerClass:refineClassNameGenerator,headerToolbarClass:refineClassNameGenerator,footerToolbarClass:refineClassNameGenerator,toolbarClass:refineClassNameGenerator,toolbarSectionClass:refineClassNameGenerator,toolbarTitleClass:refineClassName,tableClass:refineClassNameGenerator,tableHeaderClass:refineClassNameGenerator,tableBodyClass:refineClassNameGenerator,nonBusinessHoursClass:refineClassName,highlightClass:refineClassName,dayHeaders:Boolean,dayHeaderFormat:createFormatter,allDayDividerClass:refineClassName,listDaysClass:refineClassName,listDayClass:refineClassNameGenerator,listDayFormat:createFalsableFormatter,listDayAltFormat:createFalsableFormatter,listDayHeaderDidMount:identity,listDayHeaderWillUnmount:identity,listDayHeaderClass:refineClassNameGenerator,listDayHeaderInnerClass:refineClassNameGenerator,listDayHeaderContent:identity,listDayBodyClass:refineClassNameGenerator,noEventsClass:refineClassNameGenerator,noEventsInnerClass:refineClassNameGenerator,noEventsContent:identity,noEventsDidMount:identity,noEventsWillUnmount:identity,multiMonthMaxColumns:Number,singleMonthMinWidth:Number,singleMonthTitleFormat:createFormatter,singleMonthDidMount:identity,singleMonthWillUnmount:identity,singleMonthClass:refineClassNameGenerator,singleMonthHeaderClass:refineClassNameGenerator,singleMonthHeaderInnerClass:refineClassNameGenerator},BASE_OPTION_DEFAULTS={buttonDisplay:"auto",eventDisplay:"auto",defaultTimedEventDuration:"01:00:00",defaultAllDayEventDuration:{day:1},forceEventDuration:!1,nextDayThreshold:"00:00:00",initialView:"",aspectRatio:1.35,weekends:!0,weekNumbers:!1,weekNumberCalculation:"local",editable:!1,nowIndicator:!1,scrollTime:"06:00:00",scrollTimeReset:!0,slotMinTime:"00:00:00",slotMaxTime:"24:00:00",showNonCurrentDates:!0,lazyFetching:!0,startParam:"start",endParam:"end",timeZoneParam:"timeZone",timeZone:"local",locales:[],locale:"",dragRevertDuration:500,dragScroll:!0,allDayMaintainDuration:!1,unselectAuto:!0,dropAccept:"*",eventOrder:"start,-duration,allDay,title",eventSlicing:!0,eventPrintLayout:"auto",popoverFormat:{month:"long",day:"numeric",year:"numeric"},longPressDelay:1e3,eventDragMinDistance:5,expandRows:!1,navLinks:!1,selectable:!1,eventMinHeight:15,eventMinWidth:30,eventShortHeight:30,monthStartFormat:{month:"long",day:"numeric"},dayCellFormat:{day:"numeric",omitTrailing:!0},headingLevel:2,outerBorder:!0,dayNarrowWidth:80,eventOverlap:!0,slotHeaderAlign:"start",slotHeaderSticky:!0,dayHeaderAlign:"start",_dayHeaderSticky:!0,rowEventTitleSticky:!0,columnEventTitleSticky:!0,nowIndicatorSnap:"auto",dayHeaders:!0},CALENDAR_LISTENER_REFINERS={datesSet:identity,eventsSet:identity,eventAdd:identity,eventChange:identity,eventRemove:identity,eventClick:identity,eventMouseEnter:identity,eventMouseLeave:identity,select:identity,unselect:identity,loading:identity,_unmount:identity,_beforeprint:identity,_afterprint:identity,_noDateSelect:identity,_noEventDrop:identity,_noEventResize:identity,_timeScrollRequest:identity,dateClick:identity,eventDragStart:identity,eventDragStop:identity,eventDrop:identity,eventResizeStart:identity,eventResizeStop:identity,eventResize:identity,drop:identity,eventReceive:identity,eventLeave:identity},CALENDAR_ONLY_OPTION_REFINERS={class:refineClassNameGenerator,className:refineClassNameGenerator,viewClass:refineClassNameGenerator,viewDidMount:identity,viewWillUnmount:identity,views:identity,plugins:identity,initialEvents:identity,events:identity,eventSources:identity},VIEW_ONLY_OPTION_REFINERS={type:String,component:identity,class:refineClassNameGenerator,className:refineClassNameGenerator,content:identity,didMount:identity,willUnmount:identity,buttonTextKey:String,dateProfileGeneratorClass:identity,usesMinMaxTime:Boolean,disallowAmbigTitle:Boolean},COMPLEX_OPTION_COMPARATORS={dateIncrement:isMaybePropsEqualShallow,headerToolbar:isMaybePropsEqualShallow,footerToolbar:isMaybePropsEqualShallow,buttons:isMaybePropsEqualDepth1,plugins:isMaybeArraysEqual,events:isMaybeArraysEqual,eventSources:isMaybeArraysEqual,resources:isMaybeArraysEqual};function refineProps(input,refiners){let refined={},extra={};for(let propName in refiners)propName in input&&(refined[propName]=refiners[propName](input[propName],propName));for(let propName in input)propName in refiners||(extra[propName]=input[propName]);return{refined,extra}}function identity(raw){return raw}function createFalsableFormatter(input){return input===!1?null:createFormatter(input)}function buildEventInstanceRange(start,end,instantStartMs,instantEndMs){let range={start,end};return instantStartMs!=null&&(range.instantStartMs=instantStartMs),instantEndMs!=null&&(range.instantEndMs=instantEndMs),range}function resolveEdgeInstantMs(marker,instantMs,dateEnv){return instantMs??dateEnv.toDate(marker).valueOf()}function buildRangeEdgeOutput(marker,instantMs,dateEnv,omitTime){let canonicalMarker=instantMs!=null?dateEnv.timestampToMarker(instantMs):marker,timeZoneOffset=instantMs!=null?Math.round((canonicalMarker.valueOf()-instantMs)/6e4):dateEnv.offsetForMarker(marker);return!omitTime&&instantMs!=null?{marker:canonicalMarker,date:new Date(instantMs),dateStr:buildIsoString(canonicalMarker,timeZoneOffset)}:{marker:canonicalMarker,date:dateEnv.toDate(marker),dateStr:omitTime?dateEnv.formatIso(marker,{omitTime}):buildIsoString(marker,timeZoneOffset)}}function getRangeInstantStartMs(range,dateEnv){return resolveEdgeInstantMs(range.start,range.instantStartMs,dateEnv)}function getRangeInstantEndMs(range,dateEnv){return resolveEdgeInstantMs(range.end,range.instantEndMs,dateEnv)}function canonicalRangeEndMarker(range,dateEnv){return range.instantEndMs!=null?dateEnv.timestampToMarker(range.instantEndMs):range.end}function rangeHasInstants(range){return range.instantStartMs!=null||range.instantEndMs!=null}function instanceRangesIntersect(range0,range1,dateEnv){return rangeHasInstants(range0)||rangeHasInstants(range1)?getRangeInstantStartMs(range0,dateEnv)<getRangeInstantEndMs(range1,dateEnv)&&getRangeInstantEndMs(range0,dateEnv)>getRangeInstantStartMs(range1,dateEnv):rangesIntersect(range0,range1)}function instanceRangeContainsRange(outerRange,innerRange,dateEnv){if(rangeHasInstants(outerRange)||rangeHasInstants(innerRange)){let outerStartMs=outerRange.start!=null?resolveEdgeInstantMs(outerRange.start,outerRange.instantStartMs,dateEnv):-1/0,outerEndMs=outerRange.end!=null?resolveEdgeInstantMs(outerRange.end,outerRange.instantEndMs,dateEnv):1/0;return outerStartMs<=getRangeInstantStartMs(innerRange,dateEnv)&&outerEndMs>=getRangeInstantEndMs(innerRange,dateEnv)}return rangeContainsRange(outerRange,innerRange)}function addDurationToEdge(edge,duration,dateEnv){if(edge.instantMs!=null&&!duration.years&&!duration.months&&!duration.days){let durMs=asRoughMs(duration),instantMs=edge.instantMs+durMs,marker=dateEnv.timestampToMarker(instantMs);return marker>edge.marker?{marker,instantMs}:{marker:addMs(edge.marker,durMs),instantMs}}return{marker:dateEnv.add(edge.marker,duration)}}function buildValidInstanceRange(start,end,dateEnv){if(start.instantMs==null&&end.instantMs==null)return end.marker>start.marker?buildEventInstanceRange(start.marker,end.marker):null;let startMs=resolveEdgeInstantMs(start.marker,start.instantMs,dateEnv),endMs=resolveEdgeInstantMs(end.marker,end.instantMs,dateEnv);return endMs<=startMs?null:buildEventInstanceRange(start.marker,end.marker>start.marker?end.marker:addMs(start.marker,endMs-startMs),start.instantMs,end.instantMs)}function createEventInstance(defId,range){return{instanceId:guid(),defId,range}}function computeAlignedDayRange(timedRange){let dayCnt=Math.floor(diffDays4(timedRange.start,timedRange.end))||1,start=startOfDay5(timedRange.start),end=addDays4(start,dayCnt);return{start,end}}function computeVisibleDayRange(timedRange,nextDayThreshold=createDuration(0)){let startDay=null,endDay=null;if(timedRange.end){endDay=startOfDay5(timedRange.end);let endTimeMS=timedRange.end.valueOf()-endDay.valueOf();endTimeMS&&endTimeMS>=asRoughMs(nextDayThreshold)&&(endDay=addDays4(endDay,1))}return timedRange.start&&(startDay=startOfDay5(timedRange.start),endDay&&endDay<=startDay&&(endDay=addDays4(startDay,1))),{start:startDay,end:endDay}}function diffDates(date0,date1,dateEnv,largeUnit){return largeUnit==="year"?createDuration(dateEnv.diffWholeYears(date0,date1),"year"):largeUnit==="month"?createDuration(dateEnv.diffWholeMonths(date0,date1),"month"):diffDayAndTime(date0,date1)}function parseRecurring(refined,defaultAllDay,dateEnv,recurringTypes){for(let i=0;i<recurringTypes.length;i+=1){let parsed=recurringTypes[i].parse(refined,dateEnv);if(parsed){let{allDay}=refined;return allDay==null&&(allDay=defaultAllDay,allDay==null&&(allDay=parsed.allDayGuess,allDay==null&&(allDay=!1))),{allDay,duration:parsed.duration,typeData:parsed.typeData,typeId:i}}}return null}function expandRecurring(eventStore,framingRange,context){let{dateEnv,pluginHooks,options}=context,{defs,instances}=eventStore;instances=filterHash(instances,instance=>!defs[instance.defId].recurringDef);for(let defId in defs){let def=defs[defId];if(def.recurringDef){let{duration}=def.recurringDef;duration||(duration=def.allDay?options.defaultAllDayEventDuration:options.defaultTimedEventDuration);let starts=expandRecurringRanges(def,duration,framingRange,dateEnv,pluginHooks.recurringTypes);for(let start of starts){let instance=createEventInstance(defId,{start,end:dateEnv.add(start,duration)});instances[instance.instanceId]=instance}}}return{defs,instances}}function expandRecurringRanges(eventDef,duration,framingRange,dateEnv,recurringTypes){let markers=recurringTypes[eventDef.recurringDef.typeId].expand(eventDef.recurringDef.typeData,{start:dateEnv.subtract(framingRange.start,duration),end:framingRange.end},dateEnv);return eventDef.allDay&&(markers=markers.map(startOfDay5)),markers}function parseEvents(rawEvents,eventSource,context,allowOpenRange,defIdMap,instanceIdMap){let eventStore=createEmptyEventStore(),eventRefiners=buildEventRefiners(context);for(let rawEvent of rawEvents){let tuple=parseEvent(rawEvent,eventSource,context,allowOpenRange,eventRefiners,defIdMap,instanceIdMap);tuple&&eventTupleToStore(tuple,eventStore)}return eventStore}function eventTupleToStore(tuple,eventStore=createEmptyEventStore()){return eventStore.defs[tuple.def.defId]=tuple.def,tuple.instance&&(eventStore.instances[tuple.instance.instanceId]=tuple.instance),eventStore}function getRelevantEvents(eventStore,instanceId){let instance=eventStore.instances[instanceId];if(instance){let def=eventStore.defs[instance.defId],newStore=filterEventStoreDefs(eventStore,lookDef=>isEventDefsGrouped(def,lookDef));return newStore.defs[def.defId]=def,newStore.instances[instance.instanceId]=instance,newStore}return createEmptyEventStore()}function isEventDefsGrouped(def0,def1){return!!(def0.groupId&&def0.groupId===def1.groupId)}function createEmptyEventStore(){return{defs:{},instances:{}}}function mergeEventStores(store0,store1){return{defs:{...store0.defs,...store1.defs},instances:{...store0.instances,...store1.instances}}}function filterEventStoreDefs(eventStore,filterFunc){let defs=filterHash(eventStore.defs,filterFunc),instances=filterHash(eventStore.instances,instance=>defs[instance.defId]);return{defs,instances}}function excludeSubEventStore(master,sub){let{defs,instances}=master,filteredDefs={},filteredInstances={};for(let defId in defs)sub.defs[defId]||(filteredDefs[defId]=defs[defId]);for(let instanceId in instances)!sub.instances[instanceId]&&filteredDefs[instances[instanceId].defId]&&(filteredInstances[instanceId]=instances[instanceId]);return{defs:filteredDefs,instances:filteredInstances}}function normalizeConstraint(input,context){return Array.isArray(input)?parseEvents(input,null,context,!0):typeof input=="object"&&input?parseEvents([input],null,context,!0):input!=null?String(input):null}var EVENT_UI_REFINERS={display:String,editable:Boolean,startEditable:Boolean,durationEditable:Boolean,constraint:identity,overlap:identity,allow:identity,class:refineClassName,className:refineClassName,color:String,contrastColor:String},EMPTY_EVENT_UI={display:null,startEditable:null,durationEditable:null,constraints:[],overlap:null,allows:[],color:"",contrastColor:"",className:""};function createEventUi(refined,context){let constraint=normalizeConstraint(refined.constraint,context);return{display:refined.display||null,startEditable:refined.startEditable!=null?refined.startEditable:refined.editable,durationEditable:refined.durationEditable!=null?refined.durationEditable:refined.editable,constraints:constraint!=null?[constraint]:[],overlap:refined.overlap!=null?refined.overlap:null,allows:refined.allow!=null?[refined.allow]:[],color:refined.color||"",contrastColor:refined.contrastColor||"",className:(refined.class??refined.className)||""}}function combineEventUis(uis){return uis.reduce(combineTwoEventUis,EMPTY_EVENT_UI)}function combineTwoEventUis(item0,item1){return{display:item1.display!=null?item1.display:item0.display,startEditable:item1.startEditable!=null?item1.startEditable:item0.startEditable,durationEditable:item1.durationEditable!=null?item1.durationEditable:item0.durationEditable,constraints:item0.constraints.concat(item1.constraints),overlap:typeof item1.overlap=="boolean"?item1.overlap:item0.overlap,allows:item0.allows.concat(item1.allows),color:item1.color||item0.color,contrastColor:item1.contrastColor||item0.contrastColor,className:joinClassNames(item0.className,item1.className)}}var EVENT_NON_DATE_REFINERS={id:String,groupId:String,title:String,url:String,interactive:Boolean},EVENT_DATE_REFINERS={start:identity,end:identity,date:identity,allDay:Boolean},EVENT_REFINERS={...EVENT_NON_DATE_REFINERS,...EVENT_DATE_REFINERS,extendedProps:identity};function parseEvent(raw,eventSource,context,allowOpenRange,refiners=buildEventRefiners(context),defIdMap,instanceIdMap){let{refined,extra}=refineEventDef(raw,context,refiners),defaultAllDay=computeIsDefaultAllDay(eventSource,context),recurringRes=parseRecurring(refined,defaultAllDay,context.dateEnv,context.pluginHooks.recurringTypes);if(recurringRes){let def=parseEventDef(refined,extra,eventSource?eventSource.sourceId:"",recurringRes.allDay,!!recurringRes.duration,context,defIdMap);return def.recurringDef={typeId:recurringRes.typeId,typeData:recurringRes.typeData,duration:recurringRes.duration},{def,instance:null}}let singleRes=parseSingle(refined,defaultAllDay,context,allowOpenRange);if(singleRes){let def=parseEventDef(refined,extra,eventSource?eventSource.sourceId:"",singleRes.allDay,singleRes.hasEnd,context,defIdMap),instance=createEventInstance(def.defId,singleRes.range);return instanceIdMap&&def.publicId&&instanceIdMap[def.publicId]&&(instance.instanceId=instanceIdMap[def.publicId]),{def,instance}}return null}function refineEventDef(raw,context,refiners=buildEventRefiners(context)){return refineProps(raw,refiners)}function buildEventRefiners(context){return{...EVENT_UI_REFINERS,...EVENT_REFINERS,...context.pluginHooks.eventRefiners}}function parseEventDef(refined,extra,sourceId,allDay,hasEnd,context,defIdMap){let def={title:refined.title||"",groupId:refined.groupId||"",publicId:refined.id||"",url:refined.url||"",recurringDef:null,defId:(defIdMap&&refined.id?defIdMap[refined.id]:"")||guid(),sourceId,allDay,hasEnd,interactive:refined.interactive,ui:createEventUi(refined,context),extendedProps:{...refined.extendedProps||{},...extra}};for(let memberAdder of context.pluginHooks.eventDefMemberAdders)Object.assign(def,memberAdder(refined));return Object.freeze(def.ui.className),Object.freeze(def.extendedProps),def}function parseSingle(refined,defaultAllDay,context,allowOpenRange){let{allDay}=refined,startMeta,startMarker=null,hasEnd=!1,endMeta,endMarker=null,startInput=refined.start!=null?refined.start:refined.date;if(startMeta=context.dateEnv.createMarkerMeta(startInput),startMeta)startMarker=startMeta.marker;else if(!allowOpenRange)return null;refined.end!=null&&(endMeta=context.dateEnv.createMarkerMeta(refined.end)),allDay==null&&(defaultAllDay!=null?allDay=defaultAllDay:allDay=(!startMeta||startMeta.isTimeUnspecified)&&(!endMeta||endMeta.isTimeUnspecified)),allDay&&startMarker&&(startMarker=startOfDay5(startMarker));let startInstantMs=!allDay&&startMeta?startMeta.instantMs:void 0,range=null;if(endMeta&&(endMarker=allDay?startOfDay5(endMeta.marker):endMeta.marker,startMarker?allDay?endMarker>startMarker&&(range=buildEventInstanceRange(startMarker,endMarker)):range=buildValidInstanceRange({marker:startMarker,instantMs:startInstantMs},{marker:endMarker,instantMs:endMeta.instantMs},context.dateEnv):range=buildEventInstanceRange(startMarker,endMarker,void 0,allDay?void 0:endMeta.instantMs)),range)hasEnd=!0;else if(allowOpenRange)range=buildEventInstanceRange(startMarker,null,startInstantMs);else{hasEnd=context.options.forceEventDuration||!1;let endEdge=addDurationToEdge({marker:startMarker,instantMs:startInstantMs},allDay?context.options.defaultAllDayEventDuration:context.options.defaultTimedEventDuration,context.dateEnv);range=buildEventInstanceRange(startMarker,endEdge.marker,startInstantMs,endEdge.instantMs)}return{allDay,hasEnd,range}}function computeIsDefaultAllDay(eventSource,context){let res=null;return eventSource&&(res=eventSource.defaultAllDay),res==null&&(res=context.options.defaultAllDay),res}var STANDARD_PROPS={start:identity,end:identity,allDay:Boolean};function parseDateSpan(raw,dateEnv,defaultDuration){let span=parseOpenDateSpan(raw,dateEnv);if(!span)return null;let{range}=span;if(!range.start)return null;if(!range.end){if(defaultDuration==null)return null;let endEdge=addDurationToEdge({marker:range.start,instantMs:span.instantStartMs},defaultDuration,dateEnv);range.end=endEdge.marker,endEdge.instantMs!=null&&(span.instantEndMs=endEdge.instantMs)}return span}function parseOpenDateSpan(raw,dateEnv){let{refined:standardProps,extra}=refineProps(raw,STANDARD_PROPS),startMeta=standardProps.start?dateEnv.createMarkerMeta(standardProps.start):null,endMeta=standardProps.end?dateEnv.createMarkerMeta(standardProps.end):null,{allDay}=standardProps;allDay==null&&(allDay=startMeta&&startMeta.isTimeUnspecified&&(!endMeta||endMeta.isTimeUnspecified));let range={start:startMeta?startMeta.marker:null,end:endMeta?endMeta.marker:null};if(!allDay&&startMeta&&endMeta&&(startMeta.instantMs!=null||endMeta.instantMs!=null)){let validRange=buildValidInstanceRange({marker:startMeta.marker,instantMs:startMeta.instantMs},{marker:endMeta.marker,instantMs:endMeta.instantMs},dateEnv);if(!validRange&&startMeta.instantMs!=null&&endMeta.instantMs!=null)return null;validRange&&(range={start:validRange.start,end:validRange.end})}let span={range,allDay,...extra};return allDay?(delete span.instantStartMs,delete span.instantEndMs):(startMeta?.instantMs!=null&&(span.instantStartMs=startMeta.instantMs),endMeta?.instantMs!=null&&(span.instantEndMs=endMeta.instantMs)),span}function isDateSpansEqual(span0,span1){return rangesEqual(span0.range,span1.range)&&span0.allDay===span1.allDay&&isSpanPropsEqual(span0,span1)}function isSpanPropsEqual(span0,span1){for(let propName in span1)if(propName!=="range"&&propName!=="allDay"&&span0[propName]!==span1[propName])return!1;for(let propName in span0)if(!(propName in span1))return!1;return!0}function buildDateSpanApi(span,dateEnv){return{...buildRangeApi(span.range,dateEnv,span.allDay,span),allDay:span.allDay}}function buildRangeApiWithTimeZone(range,dateEnv,omitTime){return{...buildRangeApi(range,dateEnv,omitTime),timeZone:dateEnv.timeZone}}function buildRangeApi(range,dateEnv,omitTime,rangeMeta){let instantStartMs=rangeMeta?.instantStartMs??range.instantStartMs,instantEndMs=rangeMeta?.instantEndMs??range.instantEndMs,start=buildRangeEdgeOutput(range.start,instantStartMs,dateEnv,omitTime),end=buildRangeEdgeOutput(range.end,instantEndMs,dateEnv,omitTime);return{start:start.date,end:end.date,startStr:start.dateStr,endStr:end.dateStr}}function getDateSpanInstantStartMs(dateSpan,dateEnv){return resolveEdgeInstantMs(dateSpan.range.start,dateSpan.instantStartMs,dateEnv)}function getDateSpanInstantEndMs(dateSpan,dateEnv){return resolveEdgeInstantMs(dateSpan.range.end,dateSpan.instantEndMs,dateEnv)}function fabricateEventRange(dateSpan,eventUiBases,context){let res=refineEventDef({editable:!1},context),def=parseEventDef(res.refined,res.extra,"",dateSpan.allDay,!0,context);return{def,ui:compileEventUi(def,eventUiBases),instance:createEventInstance(def.defId,dateSpan.range),range:dateSpan.range,isStart:!0,isEnd:!0}}function triggerDateSelect(selection,pev,context){context.emitter.trigger("select",{...buildDateSpanApiWithContext(selection,context),jsEvent:pev?pev.origEvent:null,view:context.viewApi||context.calendarApi.view})}function triggerDateUnselect(pev,context){context.emitter.trigger("unselect",{jsEvent:pev?pev.origEvent:null,view:context.viewApi||context.calendarApi.view})}function buildDateSpanApiWithContext(dateSpan,context){let props={};for(let transform of context.pluginHooks.dateSpanTransforms)Object.assign(props,transform(dateSpan,context));return Object.assign(props,buildDateSpanApi(dateSpan,context.dateEnv)),props}function getDefaultEventEnd(allDay,marker,context){let{dateEnv,options}=context,end=marker;return allDay?(end=startOfDay5(end),end=dateEnv.add(end,options.defaultAllDayEventDuration)):end=dateEnv.add(end,options.defaultTimedEventDuration),end}function getDefaultEventEndEdge(allDay,start,context){return allDay?{marker:getDefaultEventEnd(!0,start.marker,context)}:addDurationToEdge(start,context.options.defaultTimedEventDuration,context.dateEnv)}function applyMutationToEventStore(eventStore,eventConfigBase,mutation,context){let eventConfigs=compileEventUis(eventStore.defs,eventConfigBase),dest=createEmptyEventStore();for(let defId in eventStore.defs){let def=eventStore.defs[defId];dest.defs[defId]=applyMutationToEventDef(def,eventConfigs[defId],mutation,context)}for(let instanceId in eventStore.instances){let instance=eventStore.instances[instanceId],def=dest.defs[instance.defId];dest.instances[instanceId]=applyMutationToEventInstance(instance,def,eventConfigs[instance.defId],mutation,context)}return dest}function applyMutationToEventDef(eventDef,eventConfig,mutation,context){let standardProps=mutation.standardProps||{};standardProps.hasEnd==null&&eventConfig.durationEditable&&(mutation.startDelta||mutation.endDelta)&&(standardProps.hasEnd=!0);let copy={...eventDef,...standardProps,ui:{...eventDef.ui,...standardProps.ui}};mutation.extendedProps&&(copy.extendedProps={...copy.extendedProps,...mutation.extendedProps});for(let applier of context.pluginHooks.eventDefMutationAppliers)applier(copy,mutation,context);return!copy.hasEnd&&context.options.forceEventDuration&&(copy.hasEnd=!0),copy}function applyMutationToEventInstance(eventInstance,eventDef,eventConfig,mutation,context){let forceAllDay=mutation.standardProps&&mutation.standardProps.allDay===!0,clearEnd=mutation.standardProps&&mutation.standardProps.hasEnd===!1,copy={...eventInstance};if(forceAllDay&&(copy.range=computeAlignedDayRange(copy.range)),mutation.datesDelta&&eventConfig.startEditable&&(copy.range=buildInstanceRange(addDeltaToRangeEdge(copy.range.start,copy.range.instantStartMs,mutation.datesDelta,mutation.instantDatesDeltaMs,context),addDeltaToRangeEdge(copy.range.end,copy.range.instantEndMs,mutation.datesDelta,mutation.instantDatesDeltaMs,context))),mutation.startDelta&&eventConfig.durationEditable&&(copy.range=buildInstanceRange(addDeltaToRangeEdge(copy.range.start,copy.range.instantStartMs,mutation.startDelta,mutation.instantStartDeltaMs,context),{marker:copy.range.end,instantMs:copy.range.instantEndMs})),mutation.endDelta&&eventConfig.durationEditable&&(copy.range=buildInstanceRange({marker:copy.range.start,instantMs:copy.range.instantStartMs},addDeltaToRangeEdge(copy.range.end,copy.range.instantEndMs,mutation.endDelta,mutation.instantEndDeltaMs,context))),clearEnd){let startEdge={marker:copy.range.start,instantMs:copy.range.instantStartMs};copy.range=buildInstanceRange(startEdge,getDefaultEventEndEdge(eventDef.allDay,startEdge,context))}if(eventDef.allDay&&(copy.range={start:startOfDay5(copy.range.start),end:startOfDay5(copy.range.end)}),eventDef.allDay){if(copy.range.end<=copy.range.start){let startEdge={marker:copy.range.start};copy.range=buildInstanceRange(startEdge,getDefaultEventEndEdge(!0,startEdge,context))}}else{let startEdge={marker:copy.range.start,instantMs:copy.range.instantStartMs};copy.range=buildValidInstanceRange(startEdge,{marker:copy.range.end,instantMs:copy.range.instantEndMs},context.dateEnv)??buildInstanceRange(startEdge,getDefaultEventEndEdge(!1,startEdge,context))}return copy}function addDeltaToRangeEdge(marker,instantMs,delta,instantDeltaMs,context){if(instantDeltaMs!=null){let newInstantMs=resolveEdgeInstantMs(marker,instantMs,context.dateEnv)+instantDeltaMs;return{marker:context.dateEnv.timestampToMarker(newInstantMs),instantMs:newInstantMs}}return{marker:context.dateEnv.add(instantMs!=null?context.dateEnv.timestampToMarker(instantMs):marker,delta)}}function buildInstanceRange(start,end){return buildEventInstanceRange(start.marker,end.marker,start.instantMs,end.instantMs)}var EventSourceImpl=class{constructor(context,internalEventSource){this.context=context,this.internalEventSource=internalEventSource}remove(){this.context.dispatch({type:"REMOVE_EVENT_SOURCE",sourceId:this.internalEventSource.sourceId})}refetch(){this.context.dispatch({type:"FETCH_EVENT_SOURCES",sourceIds:[this.internalEventSource.sourceId],isRefetch:!0})}get id(){return this.internalEventSource.publicId}get url(){return this.internalEventSource.meta.url}get format(){return this.internalEventSource.meta.format}},EventImpl=class _EventImpl{constructor(context,def,instance){this._context=context,this._def=def,this._instance=instance||null}setProp(name,val){if(name in EVENT_DATE_REFINERS)warn(`Cannot set date-related event property \`${name}\`. Use a method instead.`);else if(name==="id")val=EVENT_NON_DATE_REFINERS[name](val),this.mutate({standardProps:{publicId:val}});else if(name in EVENT_NON_DATE_REFINERS)val=EVENT_NON_DATE_REFINERS[name](val),this.mutate({standardProps:{[name]:val}});else if(name in EVENT_UI_REFINERS){let ui=EVENT_UI_REFINERS[name](val);name==="editable"?ui={startEditable:val,durationEditable:val}:ui={[name]:val},this.mutate({standardProps:{ui}})}else warn(`Cannot set event property \`${name}\`. Use setExtendedProp instead.`)}setExtendedProp(name,val){this.mutate({extendedProps:{[name]:val}})}setStart(startInput,options={}){let{dateEnv}=this._context,startMeta=dateEnv.createMarkerMeta(startInput);if(startMeta&&this._instance){let instanceRange=this._instance.range,startDelta=diffDates(instanceRange.start,startMeta.marker,dateEnv,options.granularity),instantDeltaMs=computeInstantDeltaMs(startMeta,getRangeInstantStartMs(instanceRange,dateEnv),options.granularity);options.maintainDuration?this.mutate({datesDelta:startDelta,instantDatesDeltaMs:instantDeltaMs}):this.mutate({startDelta,instantStartDeltaMs:instantDeltaMs})}}setEnd(endInput,options={}){let{dateEnv}=this._context,endMeta=null;if(!(endInput!=null&&(endMeta=dateEnv.createMarkerMeta(endInput),!endMeta))&&this._instance)if(endMeta){let instanceRange=this._instance.range,endDelta=diffDates(canonicalRangeEndMarker(instanceRange,dateEnv),endMeta.marker,dateEnv,options.granularity),instantDeltaMs=computeInstantDeltaMs(endMeta,getRangeInstantEndMs(instanceRange,dateEnv),options.granularity);this.mutate({endDelta,instantEndDeltaMs:instantDeltaMs})}else this.mutate({standardProps:{hasEnd:!1}})}setDates(startInput,endInput,options={}){let{dateEnv}=this._context,standardProps={allDay:options.allDay},startMeta=dateEnv.createMarkerMeta(startInput),endMeta=null;if(startMeta&&!(endInput!=null&&(endMeta=dateEnv.createMarkerMeta(endInput),!endMeta))&&this._instance){let instanceRange=this._instance.range,skipInstants=options.allDay===!0,instantStartDeltaMs=skipInstants?void 0:computeInstantDeltaMs(startMeta,getRangeInstantStartMs(instanceRange,dateEnv),options.granularity),instantEndDeltaMs=skipInstants||!endMeta?void 0:computeInstantDeltaMs(endMeta,getRangeInstantEndMs(instanceRange,dateEnv),options.granularity);options.allDay===!0&&(instanceRange=computeAlignedDayRange(instanceRange));let startDelta=diffDates(instanceRange.start,startMeta.marker,dateEnv,options.granularity);if(endMeta){let endDelta=diffDates(canonicalRangeEndMarker(instanceRange,dateEnv),endMeta.marker,dateEnv,options.granularity);durationsEqual(startDelta,endDelta)&&instantStartDeltaMs===instantEndDeltaMs?this.mutate({datesDelta:startDelta,instantDatesDeltaMs:instantStartDeltaMs,standardProps}):this.mutate({startDelta,endDelta,instantStartDeltaMs,instantEndDeltaMs,standardProps})}else standardProps.hasEnd=!1,this.mutate({datesDelta:startDelta,instantDatesDeltaMs:instantStartDeltaMs,standardProps})}}moveStart(deltaInput){let delta=createDuration(deltaInput);delta&&this.mutate({startDelta:delta})}moveEnd(deltaInput){let delta=createDuration(deltaInput);delta&&this.mutate({endDelta:delta})}moveDates(deltaInput){let delta=createDuration(deltaInput);delta&&this.mutate({datesDelta:delta})}setAllDay(allDay,options={}){let standardProps={allDay},{maintainDuration}=options;maintainDuration==null&&(maintainDuration=this._context.options.allDayMaintainDuration),this._def.allDay!==allDay&&(standardProps.hasEnd=maintainDuration),this.mutate({standardProps})}formatRange(formatInput){let{dateEnv}=this._context,instance=this._instance,formatter=createFormatter(formatInput),start=buildRangeEdgeOutput(instance.range.start,instance.range.instantStartMs,dateEnv);if(this._def.hasEnd){let end=buildRangeEdgeOutput(instance.range.end,instance.range.instantEndMs,dateEnv);return joinDateTimeFormatParts(dateEnv.formatRangeToParts(start.marker,end.marker,formatter,{startInstantMs:start.date.valueOf(),endInstantMs:end.date.valueOf()}))}return joinDateTimeFormatParts(dateEnv.formatToParts(start.marker,formatter,{instantMs:start.date.valueOf()}))}mutate(mutation){let instance=this._instance;if(instance){let def=this._def,context=this._context,{eventStore}=context.getCurrentData(),relevantEvents=getRelevantEvents(eventStore,instance.instanceId);relevantEvents=applyMutationToEventStore(relevantEvents,{"":{display:"",startEditable:!0,durationEditable:!0,constraints:[],overlap:null,allows:[],color:"",contrastColor:"",className:""}},mutation,context);let oldEvent=new _EventImpl(context,def,instance);this._def=relevantEvents.defs[def.defId],this._instance=relevantEvents.instances[instance.instanceId],context.dispatch({type:"MERGE_EVENTS",eventStore:relevantEvents}),context.emitter.trigger("eventChange",{oldEvent,event:this,relatedEvents:buildEventApis(relevantEvents,context,instance),revert(){context.dispatch({type:"RESET_EVENTS",eventStore})}})}}remove(){let context=this._context,asStore=eventApiToStore(this);context.dispatch({type:"REMOVE_EVENTS",eventStore:asStore}),context.emitter.trigger("eventRemove",{event:this,relatedEvents:[],revert(){context.dispatch({type:"MERGE_EVENTS",eventStore:asStore})}})}get source(){let{sourceId}=this._def;return sourceId?new EventSourceImpl(this._context,this._context.getCurrentData().eventSources[sourceId]):null}get start(){let instance=this._instance;return instance?buildRangeEdgeOutput(instance.range.start,instance.range.instantStartMs,this._context.dateEnv,this._def.allDay).date:null}get end(){let instance=this._instance;return instance&&this._def.hasEnd?buildRangeEdgeOutput(instance.range.end,instance.range.instantEndMs,this._context.dateEnv,this._def.allDay).date:null}get startStr(){let instance=this._instance;return instance?buildRangeEdgeOutput(instance.range.start,instance.range.instantStartMs,this._context.dateEnv,this._def.allDay).dateStr:""}get endStr(){let instance=this._instance;return instance&&this._def.hasEnd?buildRangeEdgeOutput(instance.range.end,instance.range.instantEndMs,this._context.dateEnv,this._def.allDay).dateStr:""}get id(){return this._def.publicId}get groupId(){return this._def.groupId}get allDay(){return this._def.allDay}get title(){return this._def.title}get url(){return this._def.url}get display(){return this._def.ui.display||"auto"}get startEditable(){return this._def.ui.startEditable}get durationEditable(){return this._def.ui.durationEditable}get constraint(){return this._def.ui.constraints[0]||null}get overlap(){return this._def.ui.overlap}get allow(){return this._def.ui.allows[0]||null}get color(){return this._def.ui.color}get contrastColor(){return this._def.ui.contrastColor}get className(){return this._def.ui.className}get extendedProps(){return this._def.extendedProps}toPlainObject(settings={}){let def=this._def,{ui}=def,{startStr,endStr}=this,res={allDay:def.allDay};return def.title&&(res.title=def.title),startStr&&(res.start=startStr),endStr&&(res.end=endStr),def.publicId&&(res.id=def.publicId),def.groupId&&(res.groupId=def.groupId),def.url&&(res.url=def.url),ui.display&&ui.display!=="auto"&&(res.display=ui.display),ui.color&&(res.color=ui.color),ui.contrastColor&&(res.contrastColor=ui.contrastColor),ui.className&&(res.className=ui.className),Object.keys(def.extendedProps).length&&(settings.collapseExtendedProps?Object.assign(res,def.extendedProps):res.extendedProps=def.extendedProps),res}toJSON(){return this.toPlainObject()}};function computeInstantDeltaMs(meta,fromInstantMs,granularity){return meta.instantMs!=null&&!granularity?meta.instantMs-fromInstantMs:void 0}function eventApiToStore(eventApi){let def=eventApi._def,instance=eventApi._instance;return{defs:{[def.defId]:def},instances:instance?{[instance.instanceId]:instance}:{}}}function buildEventApis(eventStore,context,excludeInstance){let{defs,instances}=eventStore,eventApis=[],excludeInstanceId=excludeInstance?excludeInstance.instanceId:"";for(let id in instances){let instance=instances[id],def=defs[instance.defId];instance.instanceId!==excludeInstanceId&&eventApis.push(new EventImpl(context,def,instance))}return eventApis}function sliceEventStore(eventStore,eventUiBases,framingRange,nextDayThreshold){let inverseBgByGroupId={},inverseBgByDefId={},defByGroupId={},bgRanges=[],fgRanges=[],eventUis=compileEventUis(eventStore.defs,eventUiBases);for(let defId in eventStore.defs){let def=eventStore.defs[defId];eventUis[def.defId].display==="inverse-background"&&(def.groupId?(inverseBgByGroupId[def.groupId]=[],defByGroupId[def.groupId]||(defByGroupId[def.groupId]=def)):inverseBgByDefId[defId]=[])}for(let instanceId in eventStore.instances){let instance=eventStore.instances[instanceId],def=eventStore.defs[instance.defId],ui=eventUis[def.defId],origRange=instance.range,normalRange=!def.allDay&&nextDayThreshold?computeVisibleDayRange(origRange,nextDayThreshold):origRange,slicedRange=intersectRanges(normalRange,framingRange);slicedRange&&(ui.display==="inverse-background"?def.groupId?inverseBgByGroupId[def.groupId].push(slicedRange):inverseBgByDefId[instance.defId].push(slicedRange):ui.display!=="none"&&(ui.display==="background"?bgRanges:fgRanges).push({def,ui,instance,range:buildSlicedEventRange(origRange,normalRange,slicedRange),isStart:normalRange.start&&normalRange.start.valueOf()===slicedRange.start.valueOf(),isEnd:normalRange.end&&normalRange.end.valueOf()===slicedRange.end.valueOf()}))}for(let groupId in inverseBgByGroupId){let ranges=inverseBgByGroupId[groupId],invertedRanges=invertRanges(ranges,framingRange);for(let invertedRange of invertedRanges){let def=defByGroupId[groupId],ui=eventUis[def.defId];bgRanges.push({def,ui,instance:null,range:invertedRange,isStart:!1,isEnd:!1})}}for(let defId in inverseBgByDefId){let ranges=inverseBgByDefId[defId],invertedRanges=invertRanges(ranges,framingRange);for(let invertedRange of invertedRanges)bgRanges.push({def:eventStore.defs[defId],ui:eventUis[defId],instance:null,range:invertedRange,isStart:!1,isEnd:!1})}return{bg:bgRanges,fg:fgRanges}}function buildSlicedEventRange(origRange,normalRange,slicedRange){return normalRange!==origRange?slicedRange:buildEventInstanceRange(slicedRange.start,slicedRange.end,slicedRange.start.valueOf()===origRange.start.valueOf()?origRange.instantStartMs:void 0,slicedRange.end.valueOf()===origRange.end.valueOf()?origRange.instantEndMs:void 0)}function hasBgRendering(def){return def.ui.display==="background"||def.ui.display==="inverse-background"}function setElEventRange(el,eventRange){el.fcEventRange=eventRange}function getElEventRange(el){return el.fcEventRange||el.parentNode.fcEventRange||null}function compileEventUis(eventDefs,eventUiBases){return mapHash(eventDefs,eventDef=>compileEventUi(eventDef,eventUiBases))}function compileEventUi(eventDef,eventUiBases){let uis=[],fallbackBase=eventUiBases[""],defBase=eventUiBases[eventDef.defId];return fallbackBase&&uis.push(fallbackBase),defBase&&uis.push(defBase),uis.push(eventDef.ui),combineEventUis(uis)}function sortEventSegs(segs,eventOrderSpecs){let objs=segs.map(buildSegCompareObj);return objs.sort((obj0,obj1)=>compareByFieldSpecs(obj0,obj1,eventOrderSpecs)),objs.map(c=>c._seg)}function buildSegCompareObj(seg){let{eventRange}=seg,eventDef=eventRange.def,range=eventRange.instance?eventRange.instance.range:eventRange.range,start=range.start?range.start.valueOf():0,end=range.end?range.end.valueOf():0;return{...eventDef.extendedProps,...eventDef,id:eventDef.publicId,start,end,duration:end-start,allDay:Number(eventDef.allDay),_seg:seg}}function computeEventRangeDraggable(eventRange,context){let{pluginHooks}=context,transformers=pluginHooks.isDraggableTransformers,{def,ui}=eventRange,val=ui.startEditable;for(let transformer of transformers)val=transformer(val,def,ui,context);return val}function buildEventRangeTimeText(timeFormat,eventRange,slicedStart,slicedEnd,isStart,isEnd,context,defaultDisplayEventTime=!0,defaultDisplayEventEnd=!0){let{dateEnv,options}=context,{def}=eventRange,{range}=eventRange.instance,canonicalStart=buildRangeEdgeOutput(range.start,range.instantStartMs,dateEnv),canonicalEnd=buildRangeEdgeOutput(range.end,range.instantEndMs,dateEnv),{displayEventTime,displayEventEnd}=options;displayEventTime==null&&(displayEventTime=defaultDisplayEventTime!==!1),displayEventEnd==null&&(displayEventEnd=defaultDisplayEventEnd!==!1);let startDate=!isStart&&slicedStart&&startOfDay5(slicedStart).valueOf()!==startOfDay5(canonicalStart.marker).valueOf()?slicedStart:canonicalStart.marker,endDate=!isEnd&&slicedEnd&&startOfDay5(addMs(slicedEnd,-1)).valueOf()!==startOfDay5(addMs(canonicalEnd.marker,-1)).valueOf()?slicedEnd:canonicalEnd.marker,startInstantMs=startDate===canonicalStart.marker?canonicalStart.date.valueOf():void 0,endInstantMs=endDate===canonicalEnd.marker?canonicalEnd.date.valueOf():void 0;if(displayEventTime&&!def.allDay){if(displayEventEnd&&(isStart||isEnd)&&def.hasEnd){let rangeParts=dateEnv.formatRangeToParts(startDate,endDate,timeFormat,{startInstantMs,endInstantMs}),multiDaySeparator=detectMultiDayTimes(rangeParts);return multiDaySeparator!=null?joinDateTimeFormatParts(dateEnv.formatToParts(startDate,timeFormat,{instantMs:startInstantMs}))+multiDaySeparator+joinDateTimeFormatParts(dateEnv.formatToParts(endDate,timeFormat,{instantMs:endInstantMs})):joinDateTimeFormatParts(rangeParts)}if(isStart)return joinDateTimeFormatParts(dateEnv.formatToParts(startDate,timeFormat,{instantMs:startInstantMs}))}return""}var dateUnits=new Set(["year","month","day"]);function detectMultiDayTimes(parts){let sharedPart,hasDatePart=!1;for(let part of parts)part.source==="shared"&&(sharedPart=part),dateUnits.has(part.type)&&(hasDatePart=!0);return hasDatePart?sharedPart.value:void 0}function getEventRangeMeta(eventRange,todayRange,nowDate,nowMs){let segRange=eventRange.range;return{isPast:segRange.instantEndMs!=null&&nowMs!=null?segRange.instantEndMs<=nowMs:segRange.end<=(nowDate||todayRange.start),isFuture:segRange.instantStartMs!=null&&nowMs!=null?segRange.instantStartMs>=nowMs:segRange.start>=(nowDate||todayRange.end),isToday:todayRange&&rangeContainsMarker(todayRange,segRange.start)}}function buildEventRangeKey(eventRange){return eventRange.instance?eventRange.instance.instanceId:`${eventRange.def.defId}:${eventRange.range.start.toISOString()}`}function getEventTagAndAttrs(eventRange,context){let{def,instance}=eventRange,{url}=def;if(url)return["a",{href:url},!0];let{emitter,options}=context,{eventInteractive}=options;eventInteractive==null&&(eventInteractive=def.interactive,eventInteractive==null&&(eventInteractive=!!emitter.hasHandlers("eventClick")));let attrs;return eventInteractive&&(attrs=createAriaKeyboardAttrs(ev=>{emitter.trigger("eventClick",{el:ev.target,event:new EventImpl(context,def,instance),jsEvent:ev,view:context.viewApi})}),attrs={role:"button",...attrs}),["div",attrs,eventInteractive]}var classNamesRe=/(^c|C)lass(Name)?$/,contentRe=/Content$/,lifecycleRe=/(DidMount|WillUnmount)$/,handlerRe=/^on[A-Z]/,customMergeFuncs={buttons:mergeMaybePropsDepth1};function mergeViewOptionsMap(...hashes){let merged={};for(let hash of hashes)for(let viewName in hash){let viewOptions=hash[viewName];merged[viewName]?merged[viewName]=mergeCalendarOptions(merged[viewName],viewOptions):merged[viewName]=viewOptions}return merged}function mergeCalendarOptions(...optionSets){let dest={};for(let options of optionSets)for(let name in options)if(name in dest){let mergeFunc=customMergeFuncs[name]||(classNamesRe.test(name)?joinFuncishClassNames:contentRe.test(name)?mergeContentInjectors:lifecycleRe.test(name)?mergeLifecycleCallbacks:void 0);dest[name]=mergeFunc?mergeFunc(dest[name],options[name],name):options[name]}else dest[name]=options[name];return dest}function joinFuncishClassNames(input0,input1,optionName){let isFunc0=typeof input0=="function",isFunc1=typeof input1=="function";if(isFunc0||isFunc1){let combinedFunc=info=>joinClassNames(refineClassName(isFunc0?input0(info):input0,optionName),refineClassName(isFunc1?input1(info):input1,optionName));return combinedFunc.parts=[input0,input1],combinedFunc}return joinClassNames(refineClassName(input0,optionName),refineClassName(input1,optionName))}function mergeContentInjectors(contentGenerator0,contentGenerator1){if(typeof contentGenerator1=="function"){let combinedFunc=renderProps=>{let res=contentGenerator1(renderProps);return res===!0?typeof contentGenerator0=="function"?contentGenerator0(renderProps):contentGenerator0:res};return combinedFunc.parts=[contentGenerator0,contentGenerator1],combinedFunc}return contentGenerator1??contentGenerator0}function mergeLifecycleCallbacks(fn0,fn1){if(fn0&&fn1){let combinedFunc=(...args)=>{fn0(...args),fn1(...args)};return combinedFunc.parts=[fn0,fn1],combinedFunc}return fn0||fn1}function isNonHandlerPropsEqual(obj0,obj1){let keys=getUnequalProps(obj0,obj1);for(let key of keys)if(!handlerRe.test(key))return!1;return!0}function isMergedPropsEqual(val0,val1){let parts0=val0&&val0.parts,parts1=val1&&val1.parts;if(parts0&&parts1){let count0=parts0.length,count1=parts1.length;if(count0!==count1)return!1;for(let i=0;i<count0;i++)if(!(parts0[i]===parts1[i]||isMergedPropsEqual(parts0[i],parts1[i])))return!1;return!0}return!1}var globalLocales=[],MINIMAL_RAW_EN_LOCALE={code:"en",week:{dow:0,doy:4},direction:"ltr",todayText:"Today",prevText:"Prev",nextText:"Next",prevYearText:"Prev year",nextYearText:"Next year",yearText:"Year",monthText:"Month",weekTextLong:"Week",dayText:"Day",listText:"List",closeHint:"Close",eventsHint:"Events",allDayText:"All-day",timedText:"Timed",moreLinkText:"more",noEventsText:"No events to display"},RAW_EN_LOCALE={...MINIMAL_RAW_EN_LOCALE,weekTextShort:"W",todayHint:(unitText,unit)=>unit==="day"?"Today":`This ${unitText}`,prevHint:"Previous $0",nextHint:"Next $0",viewHint:"$0 view",viewChangeHint:"Change view",navLinkHint:"Go to $0",moreLinkHint(eventCnt){return`Show ${eventCnt} more event${eventCnt===1?"":"s"}`}};function organizeRawLocales(explicitRawLocales){let defaultCode=explicitRawLocales.length>0?explicitRawLocales[0].code:"en",allRawLocales=globalLocales.concat(explicitRawLocales),rawLocaleMap={en:RAW_EN_LOCALE};for(let rawLocale of allRawLocales)rawLocaleMap[rawLocale.code]=rawLocale;return{map:rawLocaleMap,defaultCode}}function buildLocale(inputSingular,available){return typeof inputSingular=="object"&&!Array.isArray(inputSingular)?parseLocale(inputSingular.code,[inputSingular.code],inputSingular):queryLocale(inputSingular,available)}function queryLocale(codeArg,available){let codes=[].concat(codeArg||[]),raw=queryRawLocale(codes,available)||RAW_EN_LOCALE;return parseLocale(codeArg,codes,raw)}function queryRawLocale(codes,available){for(let i=0;i<codes.length;i+=1){let parts=codes[i].toLocaleLowerCase().split("-");for(let j=parts.length;j>0;j-=1){let simpleId=parts.slice(0,j).join("-");if(available[simpleId])return available[simpleId]}}return null}function parseLocale(codeArg,codes,raw){let merged=mergeCalendarOptions(MINIMAL_RAW_EN_LOCALE,raw);delete merged.code;let{week}=merged;return delete merged.week,{codeArg,codes,week,simpleNumberFormat:new Intl.NumberFormat(codeArg),options:merged}}var JsonRequestError=class extends Error{constructor(message,response){super(message),this.response=response}};function requestJson(method,url,params){method=method.toUpperCase();let fetchOptions={method};return method==="GET"?url+=(url.indexOf("?")===-1?"?":"&")+new URLSearchParams(params):(fetchOptions.body=new URLSearchParams(params),fetchOptions.headers={"Content-Type":"application/x-www-form-urlencoded"}),fetch(url,fetchOptions).then(fetchRes=>{if(fetchRes.ok)return fetchRes.json().then(parsedResponse=>[parsedResponse,fetchRes],()=>{throw new JsonRequestError("Failure parsing JSON",fetchRes)});throw new JsonRequestError("Request failed",fetchRes)})}function handleDateProfile(dateProfile,context){context.emitter.trigger("datesSet",{...buildRangeApiWithTimeZone(dateProfile.activeRange,context.dateEnv),view:context.viewApi})}function handleEventStore(eventStore,context){let{emitter}=context;emitter.hasHandlers("eventsSet")&&emitter.trigger("eventsSet",buildEventApis(eventStore,context))}var eventSourceDef$2={ignoreRange:!0,parseMeta(refined){return Array.isArray(refined.events)?refined.events:null},fetch(arg,successCallback){successCallback({rawEvents:arg.eventSource.meta})}},arrayEventSourcePlugin={name:"array-event-source",eventSourceDefs:[eventSourceDef$2]};function unpromisify(func,normalizedSuccessCallback,normalizedFailureCallback){let isResolved=!1,wrappedSuccess=function(res2){isResolved||(isResolved=!0,normalizedSuccessCallback(res2))},wrappedFailure=function(error){isResolved||(isResolved=!0,normalizedFailureCallback(error))},res=func(wrappedSuccess,wrappedFailure);res&&typeof res.then=="function"&&res.then(wrappedSuccess,wrappedFailure)}var eventSourceDef$1={parseMeta(refined){return typeof refined.events=="function"?refined.events:null},fetch(arg,successCallback,errorCallback){let{dateEnv}=arg.context,func=arg.eventSource.meta;unpromisify(func.bind(null,buildRangeApiWithTimeZone(arg.range,dateEnv)),rawEvents=>successCallback({rawEvents}),errorCallback)}},funcEventSourcePlugin={name:"func-event-source",eventSourceDefs:[eventSourceDef$1]},JSON_FEED_EVENT_SOURCE_REFINERS={method:String,extraParams:identity,startParam:String,endParam:String,timeZoneParam:String},eventSourceDef={parseMeta(refined){return refined.url&&(refined.format==="json"||!refined.format)?{url:refined.url,format:"json",method:(refined.method||"GET").toUpperCase(),extraParams:refined.extraParams,startParam:refined.startParam,endParam:refined.endParam,timeZoneParam:refined.timeZoneParam}:null},fetch(arg,successCallback,errorCallback){let{meta}=arg.eventSource,requestParams=buildRequestParams(meta,arg.range,arg.context);requestJson(meta.method,meta.url,requestParams).then(([rawEvents,response])=>{successCallback({rawEvents,response})},errorCallback)}},jsonFeedEventSourcePlugin={name:"json-event-source",eventSourceRefiners:JSON_FEED_EVENT_SOURCE_REFINERS,eventSourceDefs:[eventSourceDef]};function buildRequestParams(meta,range,context){let{dateEnv,options}=context,startParam,endParam,timeZoneParam,customRequestParams,params={};return startParam=meta.startParam,startParam==null&&(startParam=options.startParam),endParam=meta.endParam,endParam==null&&(endParam=options.endParam),timeZoneParam=meta.timeZoneParam,timeZoneParam==null&&(timeZoneParam=options.timeZoneParam),typeof meta.extraParams=="function"?customRequestParams=meta.extraParams():customRequestParams=meta.extraParams||{},Object.assign(params,customRequestParams),params[startParam]=dateEnv.formatIso(range.start),params[endParam]=dateEnv.formatIso(range.end),dateEnv.timeZone!=="local"&&(params[timeZoneParam]=dateEnv.timeZone),params}var changeHandlerPlugin={name:"change-handler",optionChangeHandlers:{controller(controller,context){controller._setApi(context.calendarApi)},events(events,context){handleEventSources([events],context)},eventSources:handleEventSources}};function handleEventSources(inputs,context){let unfoundSources=hashValuesToArray(context.getCurrentData().eventSources);if(unfoundSources.length===1&&inputs.length===1&&Array.isArray(unfoundSources[0]._raw)&&Array.isArray(inputs[0])){context.dispatch({type:"RESET_RAW_EVENTS",sourceId:unfoundSources[0].sourceId,rawEvents:inputs[0]});return}let newInputs=[];for(let input of inputs){let inputFound=!1;for(let i=0;i<unfoundSources.length;i+=1)if(unfoundSources[i]._raw===input){unfoundSources.splice(i,1),inputFound=!0;break}inputFound||newInputs.push(input)}for(let unfoundSource of unfoundSources)context.dispatch({type:"REMOVE_EVENT_SOURCE",sourceId:unfoundSource.sourceId});for(let newInput of newInputs)context.calendarApi.addEventSource(newInput)}var EVENT_SOURCE_REFINERS={id:String,defaultAllDay:Boolean,url:String,format:String,events:identity,eventDataTransform:identity,success:identity,failure:identity};function parseEventSource(raw,context,refiners=buildEventSourceRefiners(context)){let rawObj;if(typeof raw=="string"?rawObj={url:raw}:typeof raw=="function"||Array.isArray(raw)?rawObj={events:raw}:typeof raw=="object"&&raw&&(rawObj=raw),rawObj){let{refined,extra}=refineProps(rawObj,refiners),metaRes=buildEventSourceMeta(refined,context);if(metaRes)return{_raw:raw,isFetching:!1,latestFetchId:"",fetchRange:null,defaultAllDay:refined.defaultAllDay,eventDataTransform:refined.eventDataTransform,success:refined.success,failure:refined.failure,publicId:refined.id||"",sourceId:guid(),sourceDefId:metaRes.sourceDefId,meta:metaRes.meta,ui:createEventUi(refined,context),extendedProps:extra}}return null}function buildEventSourceRefiners(context){return{...EVENT_UI_REFINERS,...EVENT_SOURCE_REFINERS,...context.pluginHooks.eventSourceRefiners}}function buildEventSourceMeta(raw,context){let defs=context.pluginHooks.eventSourceDefs;for(let i=defs.length-1;i>=0;i-=1){let meta=defs[i].parseMeta(raw);if(meta)return{sourceDefId:i,meta}}return null}function initEventSources(calendarOptions,dateProfile,context){let activeRange=dateProfile?dateProfile.activeRange:null;return addSources({},parseInitialSources(calendarOptions,context),activeRange,context)}function reduceEventSources(eventSources,action,dateProfile,context){let activeRange=dateProfile?dateProfile.activeRange:null;switch(action.type){case"ADD_EVENT_SOURCES":return addSources(eventSources,action.sources,activeRange,context);case"REMOVE_EVENT_SOURCE":return removeSource(eventSources,action.sourceId);case"PREV":case"NEXT":case"CHANGE_DATE":case"CHANGE_VIEW_TYPE":return dateProfile?fetchDirtySources(eventSources,activeRange,context):eventSources;case"FETCH_EVENT_SOURCES":return fetchSourcesByIds(eventSources,action.sourceIds?arrayToHash(action.sourceIds):excludeStaticSources(eventSources,context),activeRange,action.isRefetch||!1,context);case"RECEIVE_EVENTS":case"RECEIVE_EVENT_ERROR":return receiveResponse(eventSources,action.sourceId,action.fetchId,action.fetchRange);case"REMOVE_ALL_EVENT_SOURCES":return{};default:return eventSources}}function reduceEventSourcesNewTimeZone(eventSources,dateProfile,context){let activeRange=dateProfile?dateProfile.activeRange:null;return fetchSourcesByIds(eventSources,excludeStaticSources(eventSources,context),activeRange,!0,context)}function computeEventSourcesLoading(eventSources){for(let sourceId in eventSources)if(eventSources[sourceId].isFetching)return!0;return!1}function addSources(eventSourceHash,sources,fetchRange,context){let hash={};for(let source of sources)hash[source.sourceId]=source;return fetchRange&&(hash=fetchDirtySources(hash,fetchRange,context)),{...eventSourceHash,...hash}}function removeSource(eventSourceHash,sourceId){return filterHash(eventSourceHash,eventSource=>eventSource.sourceId!==sourceId)}function fetchDirtySources(sourceHash,fetchRange,context){return fetchSourcesByIds(sourceHash,filterHash(sourceHash,eventSource=>isSourceDirty(eventSource,fetchRange,context)),fetchRange,!1,context)}function isSourceDirty(eventSource,fetchRange,context){return doesSourceNeedRange(eventSource,context)?!context.options.lazyFetching||!eventSource.fetchRange||eventSource.isFetching||fetchRange.start<eventSource.fetchRange.start||fetchRange.end>eventSource.fetchRange.end:!eventSource.latestFetchId}function fetchSourcesByIds(prevSources,sourceIdHash,fetchRange,isRefetch,context){let nextSources={};for(let sourceId in prevSources){let source=prevSources[sourceId];sourceIdHash[sourceId]?nextSources[sourceId]=fetchSource(source,fetchRange,isRefetch,context):nextSources[sourceId]=source}return nextSources}function fetchSource(eventSource,fetchRange,isRefetch,context){let{options,calendarApi}=context,sourceDef=context.pluginHooks.eventSourceDefs[eventSource.sourceDefId],fetchId=guid();return sourceDef.fetch({eventSource,range:fetchRange,isRefetch,context},res=>{let{rawEvents}=res;options.eventSourceSuccess&&(rawEvents=options.eventSourceSuccess.call(calendarApi,rawEvents,res.response)||rawEvents),eventSource.success&&(rawEvents=eventSource.success.call(calendarApi,rawEvents,res.response)||rawEvents),context.dispatch({type:"RECEIVE_EVENTS",sourceId:eventSource.sourceId,fetchId,fetchRange,rawEvents})},error=>{let errorHandled=!1;options.eventSourceFailure&&(options.eventSourceFailure.call(calendarApi,error),errorHandled=!0),eventSource.failure&&(eventSource.failure(error),errorHandled=!0),errorHandled||warn(`Unhandled event source error: ${error.message}`,error),context.dispatch({type:"RECEIVE_EVENT_ERROR",sourceId:eventSource.sourceId,fetchId,fetchRange,error})}),{...eventSource,isFetching:!0,latestFetchId:fetchId}}function receiveResponse(sourceHash,sourceId,fetchId,fetchRange){let eventSource=sourceHash[sourceId];return eventSource&&fetchId===eventSource.latestFetchId?{...sourceHash,[sourceId]:{...eventSource,isFetching:!1,fetchRange}}:sourceHash}function excludeStaticSources(eventSources,context){return filterHash(eventSources,eventSource=>doesSourceNeedRange(eventSource,context))}function parseInitialSources(rawOptions,context){let refiners=buildEventSourceRefiners(context),rawSources=[].concat(rawOptions.eventSources||[]),sources=[];rawOptions.initialEvents&&rawSources.unshift(rawOptions.initialEvents),rawOptions.events&&rawSources.unshift(rawOptions.events);for(let rawSource of rawSources){let source=parseEventSource(rawSource,context,refiners);source&&sources.push(source)}return sources}function doesSourceNeedRange(eventSource,context){return!context.pluginHooks.eventSourceDefs[eventSource.sourceDefId].ignoreRange}var SIMPLE_RECURRING_REFINERS={daysOfWeek:identity,startTime:createDuration,endTime:createDuration,duration:createDuration,startRecur:identity,endRecur:identity},recurring={parse(refined,dateEnv){if(refined.daysOfWeek||refined.startTime||refined.endTime||refined.startRecur||refined.endRecur){let recurringData={daysOfWeek:refined.daysOfWeek||null,startTime:refined.startTime||null,endTime:refined.endTime||null,startRecur:refined.startRecur?dateEnv.createMarker(refined.startRecur):null,endRecur:refined.endRecur?dateEnv.createMarker(refined.endRecur):null,dateEnv},duration;return refined.duration&&(duration=refined.duration),!duration&&refined.startTime&&refined.endTime&&(duration=subtractDurations(refined.endTime,refined.startTime)),{allDayGuess:!refined.startTime&&!refined.endTime,duration,typeData:recurringData}}return null},expand(typeData,framingRange,dateEnv){let clippedFramingRange=intersectRanges(framingRange,{start:typeData.startRecur,end:typeData.endRecur});return clippedFramingRange?expandRanges(typeData.daysOfWeek,typeData.startTime,typeData.dateEnv,dateEnv,clippedFramingRange):[]}},simpleRecurringEventsPlugin={name:"simple-recurring-event",recurringTypes:[recurring],eventRefiners:SIMPLE_RECURRING_REFINERS};function expandRanges(daysOfWeek,startTime,eventDateEnv,calendarDateEnv,framingRange){let dowHash=daysOfWeek?arrayToHash(daysOfWeek):null,dayMarker=startOfDay5(framingRange.start),endMarker=framingRange.end,instanceStarts=[];for(startTime&&(startTime.milliseconds<0?endMarker=addDays4(endMarker,1):startTime.milliseconds>=1e3*60*60*24&&(dayMarker=addDays4(dayMarker,-1)));dayMarker<endMarker;){let instanceStart;(!dowHash||dowHash[dayMarker.getUTCDay()])&&(startTime?instanceStart=calendarDateEnv.add(dayMarker,startTime):instanceStart=dayMarker,instanceStarts.push(calendarDateEnv.createMarker(eventDateEnv.toDate(instanceStart)))),dayMarker=addDays4(dayMarker,1)}return instanceStarts}var globalPlugins=[arrayEventSourcePlugin,funcEventSourcePlugin,jsonFeedEventSourcePlugin,simpleRecurringEventsPlugin,changeHandlerPlugin,{name:"misc",isLoadingFuncs:[state=>computeEventSourcesLoading(state.eventSources)],propSetHandlers:{dateProfile:handleDateProfile,eventStore:handleEventStore}}];var blankButtonState={text:"",hint:"",isDisabled:!1},CalendarController=class{constructor(handleDateChange){this.handleDateChange=handleDateChange}today(){this.calendarApi?.today()}prev(){this.calendarApi?.prev()}next(){this.calendarApi?.next()}prevYear(){this.calendarApi?.prevYear()}nextYear(){this.calendarApi?.nextYear()}gotoDate(zonedDateInput){this.calendarApi?.gotoDate(zonedDateInput)}incrementDate(duration){this.calendarApi?.incrementDate(duration)}changeView(viewType){this.calendarApi?.changeView(viewType)}get view(){return this.calendarApi?.view}getDate(){return this.calendarApi?.getDate()}getButtonState(){let{calendarApi}=this;return calendarApi&&calendarApi.getButtonState()||{today:blankButtonState,prev:blankButtonState,next:blankButtonState,prevYear:blankButtonState,nextYear:blankButtonState}}_setApi(calendarApi){this.calendarApi!==calendarApi&&(this.calendarApi&&(this.calendarApi.off("datesSet",this.handleDateChange),this.calendarApi=void 0),calendarApi&&(this.calendarApi=calendarApi,calendarApi.on("datesSet",this.handleDateChange)))}};import{useCallback as useCallback7,useState as useState5}from"react";import{jsx as jsx10}from"react/jsx-runtime";import React,{forwardRef as forwardRef2,useState as useState4,useEffect as useEffect3,useImperativeHandle}from"react";import{flushSync as flushSync2}from"react-dom";import{createContext,Component,isValidElement,createElement as createElement2}from"react";import{flushSync}from"react-dom";function memoize2(workerFunc,resEquality,teardownFunc){let currentArgs,currentRes;return function(...newArgs){if(!currentArgs)currentRes=workerFunc.apply(this,newArgs);else if(!isArraysEqual(currentArgs,newArgs)){teardownFunc&&teardownFunc(currentRes);let res=workerFunc.apply(this,newArgs);(!resEquality||!resEquality(res,currentRes))&&(currentRes=res)}return currentArgs=newArgs,currentRes}}function memoizeObjArg(workerFunc,resEquality,teardownFunc){let currentArg,currentRes;return newArg=>{if(!currentArg)currentRes=workerFunc.call(this,newArg);else if(!isPropsEqualShallow(currentArg,newArg)){teardownFunc&&teardownFunc(currentRes);let res=workerFunc.call(this,newArg);(!resEquality||!resEquality(res,currentRes))&&(currentRes=res)}return currentArg=newArg,currentRes}}var ViewContextType=createContext({});function buildViewContext(viewSpec,viewApi,viewOptions,dateProfileGenerator,dateEnv,nowManager,pluginHooks,dispatch,getCurrentData,emitter,calendarApi,baseId,registerInteractiveComponent,unregisterInteractiveComponent){return{dateEnv,nowManager,options:viewOptions,pluginHooks,emitter,dispatch,getCurrentData,calendarApi,viewSpec,viewApi,dateProfileGenerator,baseId,registerInteractiveComponent,unregisterInteractiveComponent}}var PureComponent=class extends Component{shouldComponentUpdate(nextProps,nextState){return!isPropsEqualWithMap(this.props,nextProps,this.propEquality)||!isPropsEqualWithMap(this.state,nextState,this.stateEquality)}};PureComponent.addPropsEquality=addPropsEquality;PureComponent.addStateEquality=addStateEquality;PureComponent.contextType=ViewContextType;PureComponent.prototype.propEquality={};PureComponent.prototype.stateEquality={};var BaseComponent=class extends PureComponent{};BaseComponent.contextType=ViewContextType;function addPropsEquality(propEquality){let hash=Object.create(this.prototype.propEquality);Object.assign(hash,propEquality),this.prototype.propEquality=hash}function addStateEquality(stateEquality){let hash=Object.create(this.prototype.stateEquality);Object.assign(hash,stateEquality),this.prototype.stateEquality=hash}function setRef(ref,current){typeof ref=="function"?ref(current):ref&&(ref.current=current)}var ContentInjector=class extends BaseComponent{constructor(){super(...arguments),this.id=guid(),this.queuedDomNodes=[],this.currentDomNodes=[],this.handleEl=el=>{this.el=el,this.props.elRef&&setRef(this.props.elRef,el)}}render(){let{props,context}=this,{options}=context,{customGenerator,defaultGenerator,renderProps}=props,attrs=buildElAttrs(props,"",this.handleEl),useDefault=!1,innerContent,queuedDomNodes=[],currentGeneratorMeta;if(customGenerator!=null){let customGeneratorRes=typeof customGenerator=="function"?customGenerator(renderProps):customGenerator;if(customGeneratorRes===!0)useDefault=!0;else{let isObject=customGeneratorRes&&typeof customGeneratorRes=="object";isObject&&"html"in customGeneratorRes?attrs.dangerouslySetInnerHTML={__html:customGeneratorRes.html}:isObject&&"domNodes"in customGeneratorRes?queuedDomNodes=Array.prototype.slice.call(customGeneratorRes.domNodes):(isObject?isValidElement(customGeneratorRes):typeof customGeneratorRes!="function")?innerContent=customGeneratorRes:currentGeneratorMeta=customGeneratorRes}}else useDefault=!hasCustomRenderingHandler(props.generatorName,options);return useDefault&&defaultGenerator&&(innerContent=defaultGenerator(renderProps)),this.queuedDomNodes=queuedDomNodes,this.currentGeneratorMeta=currentGeneratorMeta,createElement2(props.tag,attrs,innerContent)}componentDidMount(){this.applyQueueudDomNodes(),this.triggerCustomRendering(!0)}componentDidUpdate(){this.applyQueueudDomNodes(),this.triggerCustomRendering(!0)}componentWillUnmount(){this.triggerCustomRendering(!1)}triggerCustomRendering(isActive){let{props,context}=this,{handleCustomRendering,customRenderingMetaMap}=context.options;if(handleCustomRendering){let generatorMeta=this.currentGeneratorMeta??customRenderingMetaMap?.[props.generatorName];generatorMeta&&handleCustomRendering({id:this.id,isActive,containerEl:this.el,generatorMeta,renderProps:props.renderProps})}}applyQueueudDomNodes(){let{queuedDomNodes,currentDomNodes}=this,{el}=this;if(!isArraysEqual(queuedDomNodes,currentDomNodes)){for(let domNode of currentDomNodes)domNode.remove();for(let newNode of queuedDomNodes)el.appendChild(newNode);this.currentDomNodes=queuedDomNodes}}};ContentInjector.addPropsEquality({renderProps:isPropsEqualShallow,attrs:isNonHandlerPropsEqual,style:isPropsEqualShallow});function hasCustomRenderingHandler(generatorName,options){return!!(options.handleCustomRendering&&generatorName&&options.customRenderingMetaMap?.[generatorName])}function buildElAttrs(props,className,elRef){let attrs={...props.attrs,ref:elRef};return(props.className||className)&&(attrs.className=joinClassNames(className,props.className,attrs.className)),props.style&&(attrs.style=props.style),attrs}var RenderId=createContext(0),ContentContainer=class extends Component{constructor(){super(...arguments),this.InnerContent=InnerContentInjector.bind(void 0,this),this.handleEl=el=>{this.el=el,this.props.elRef&&(setRef(this.props.elRef,el),el&&this.didMountMisfire&&this.componentDidMount())}}render(){let{props}=this,generatedClassName=generateClassName(props.classNameGenerator,props.renderProps);if(props.children){let attrs=buildElAttrs(props,generatedClassName,this.handleEl),children=props.children(this.InnerContent,props.renderProps,attrs);return props.tag?createElement2(props.tag,attrs,children):children}else return createElement2(ContentInjector,{...props,elRef:this.handleEl,tag:props.tag||"div",className:joinClassNames(props.className,generatedClassName),renderId:this.context})}componentDidMount(){this.el?this.props.didMount?.({...this.props.renderProps,el:this.el}):this.didMountMisfire=!0}componentWillUnmount(){this.props.willUnmount?.({...this.props.renderProps,el:this.el})}};ContentContainer.contextType=RenderId;function InnerContentInjector(containerComponent,props){let parentProps=containerComponent.props;return createElement2(ContentInjector,{renderProps:parentProps.renderProps,generatorName:parentProps.generatorName,customGenerator:parentProps.customGenerator,defaultGenerator:parentProps.defaultGenerator,renderId:containerComponent.context,...props})}function generateClassName(classNameGenerator,renderProps){return(typeof classNameGenerator=="function"?classNameGenerator(renderProps):classNameGenerator)||""}function renderText(renderProps){return renderProps.text}function getIsHeightAuto(options){return options.height==="auto"||options.contentHeight==="auto"}function getTableHeaderSticky(options){let{tableHeaderSticky}=options;return(tableHeaderSticky==null||tableHeaderSticky==="auto")&&(tableHeaderSticky=getIsHeightAuto(options)),tableHeaderSticky}function getFooterScrollbarSticky(options){let isHeightAuto=getIsHeightAuto(options),{footerScrollbarSticky}=options;return(footerScrollbarSticky==null||footerScrollbarSticky==="auto")&&(footerScrollbarSticky=isHeightAuto),!!footerScrollbarSticky&&isHeightAuto}function getScrollerSyncerClass(pluginHooks){let ScrollerSyncer=pluginHooks.scrollerSyncerClass;if(!ScrollerSyncer)throw new RangeError("Must import @fullcalendar/scrollgrid");return ScrollerSyncer}var NowTimerRunner=class{constructor(handleChange){this.handleChange=handleChange,this.isMounted=!1,this.handleRefresh=()=>{let timing=this.computeTiming();(timing.nowDate.valueOf()!==this.nowDate.valueOf()||timing.nowMs!==this.nowMs)&&(this.nowDate=timing.nowDate,this.nowMs=timing.nowMs,this.todayRange=timing.todayRange,this.handleChange()),this.clearTimeout(),this.setTimeout(timing.waitMs)},this.handleVisibilityChange=()=>{document.hidden||this.handleRefresh()}}update(input){if(this.isMounted){if(input.unit!==this.unit||input.unitValue!==this.unitValue||input.nowIndicatorSnap!==this.nowIndicatorSnap||input.nowManager!==this.nowManager||input.dateEnv!==this.dateEnv){this.unit=input.unit,this.unitValue=input.unitValue,this.nowIndicatorSnap=input.nowIndicatorSnap,this.nowManager=input.nowManager,this.dateEnv=input.dateEnv;let timing=this.computeTiming();this.nowDate=timing.nowDate,this.nowMs=timing.nowMs,this.todayRange=timing.todayRange,this.clearTimeout(),this.setTimeout(timing.waitMs)}}else{this.isMounted=!0,this.unit=input.unit,this.unitValue=input.unitValue,this.nowIndicatorSnap=input.nowIndicatorSnap,this.nowManager=input.nowManager,this.dateEnv=input.dateEnv;let timing=this.computeTiming();this.nowDate=timing.nowDate,this.nowMs=timing.nowMs,this.todayRange=timing.todayRange,this.setTimeout(timing.waitMs),this.nowManager.addResetListener(this.handleRefresh),typeof document<"u"&&document.addEventListener("visibilitychange",this.handleVisibilityChange)}return{nowDate:this.nowDate,nowMs:this.nowMs,todayRange:this.todayRange}}destroy(){this.isMounted&&(this.isMounted=!1,this.clearTimeout(),this.nowManager.removeResetListener(this.handleRefresh),typeof document<"u"&&document.removeEventListener("visibilitychange",this.handleVisibilityChange))}computeTiming(){let{unit,unitValue,nowIndicatorSnap,dateEnv}=this,unroundedNowMs=this.nowManager.getEpochMs(),unroundedNow=dateEnv.timestampToMarker(unroundedNowMs);nowIndicatorSnap==="auto"&&(nowIndicatorSnap=/year|month|week|day/.test(unit)||(unitValue||1)===1);let nowDate,nowMs,waitMs;if(nowIndicatorSnap){nowDate=dateEnv.startOf(unroundedNow,unit),nowMs=resolveSnappedInstant(nowDate,unroundedNowMs,dateEnv);let nextUnitStart=dateEnv.add(nowDate,createDuration(1,unit));waitMs=resolveNextSnappedInstant(nextUnitStart,unroundedNowMs,dateEnv)-unroundedNowMs}else nowDate=unroundedNow,nowMs=unroundedNowMs,waitMs=1e3*60;return waitMs=Math.min(1e3*60*60*24,waitMs),{nowDate,nowMs,todayRange:buildDayRange(nowDate),waitMs}}setTimeout(waitMs=this.computeTiming().waitMs){this.timeoutId=setTimeout(()=>{let timing=this.computeTiming();this.nowDate=timing.nowDate,this.nowMs=timing.nowMs,this.todayRange=timing.todayRange,this.handleChange(),this.setTimeout(timing.waitMs)},waitMs)}clearTimeout(){this.timeoutId&&clearTimeout(this.timeoutId)}};function resolveSnappedInstant(snappedMarker,rawMs,dateEnv){let offsetMs=dateEnv.timestampToMarker(rawMs).valueOf()-rawMs,candidateMs=snappedMarker.valueOf()-offsetMs;return dateEnv.timestampToMarker(candidateMs).valueOf()===snappedMarker.valueOf()?candidateMs:dateEnv.toDate(snappedMarker).valueOf()}function resolveNextSnappedInstant(nextUnitStart,rawMs,dateEnv){let nextSnappedMs=resolveSnappedInstant(nextUnitStart,rawMs,dateEnv),transitionMs=findNextOffsetTransitionMs(rawMs,dateEnv,Math.min(nextSnappedMs-rawMs,2880*60*1e3));return transitionMs!=null?Math.min(nextSnappedMs,transitionMs):nextSnappedMs}function findNextOffsetTransitionMs(rawMs,dateEnv,horizonMs){if(horizonMs<=0)return;let startOffsetMs=offsetAt(rawMs,dateEnv),lowerMs=rawMs,upperMs=rawMs+horizonMs;if(offsetAt(upperMs,dateEnv)!==startOffsetMs){for(;upperMs-lowerMs>1;){let middleMs=Math.floor((lowerMs+upperMs)/2);offsetAt(middleMs,dateEnv)===startOffsetMs?lowerMs=middleMs:upperMs=middleMs}return upperMs>rawMs?upperMs:void 0}}function offsetAt(instantMs,dateEnv){return dateEnv.timestampToMarker(instantMs).valueOf()-instantMs}function buildDayRange(date){let start=startOfDay5(date),end=addDays4(start,1);return{start,end}}function isDimsEqual(v0,v1){return v0!=null&&(v0===v1||Math.abs(v0-v1)<.01)}var nativeBorderBoxEnabled=!0,configMap=new Map,afterSizeCallbacks=new Set,isHandling=!1,isStalling=!1,isAcquiringImmediately=!1;function afterSize(callback){afterSizeCallbacks.add(callback),!isHandling&&!isStalling&&(isStalling=!0,requestAnimationFrame(()=>{isStalling=!1,flushAfterSize()}))}function flushAfterSize(){for(let flushedCallback of afterSizeCallbacks.values())afterSizeCallbacks.delete(flushedCallback),flushedCallback()}function flushSyncWithSizeBatching(callback){let wasHandling=isHandling;isHandling=!0,isAcquiringImmediately=!0;try{flushSync(callback),wasHandling||flushSync(()=>{flushAfterSize(),isHandling=!1})}finally{isHandling=wasHandling,isAcquiringImmediately=!1}}var globalResizeObserver=typeof ResizeObserver<"u"&&new ResizeObserver(entries=>{isHandling=!0;for(let entry of entries){let el=entry.target,config2=configMap.get(el),width,height;if(entry.borderBoxSize&&nativeBorderBoxEnabled){let borderBoxSize=entry.borderBoxSize[0]||entry.borderBoxSize;width=borderBoxSize.inlineSize,height=borderBoxSize.blockSize}else({width,height}=el.getBoundingClientRect());let shouldFire=!1;isDimsEqual(config2.width,width)||(config2.width=width,shouldFire=config2.watchWidth),isDimsEqual(config2.height,height)||(config2.height=height,shouldFire||(shouldFire=config2.watchHeight)),shouldFire&&config2.callback(width,height)}flushSync(()=>{flushAfterSize(),isHandling=!1})});function watchSize(el,callback,watchWidth2=!0,watchHeight2=!0){let config2={callback,watchWidth:watchWidth2,watchHeight:watchHeight2};if(configMap.set(el,config2),isAcquiringImmediately){let{width,height}=el.getBoundingClientRect();config2.width=width,config2.height=height,callback(width,height)}return globalResizeObserver&&globalResizeObserver.observe(el,{box:"border-box"}),()=>{configMap.delete(el),globalResizeObserver&&globalResizeObserver.unobserve(el)}}function watchWidth(el,callback){return watchSize(el,callback,!0)}function watchHeight(el,callback){return watchSize(el,(_width,height)=>callback(height),!1,!0)}import{jsx as jsx9,jsxs as jsxs7,Fragment as Fragment5}from"react/jsx-runtime";var DateProfileGenerator=class{constructor(props){this.props=props,this.initHiddenDays()}buildPrev(currentDateProfile,currentDate,nowDate,forceToValid){let{dateEnv}=this.props,prevDate=dateEnv.subtract(dateEnv.startOf(currentDate,currentDateProfile.currentRangeUnit),currentDateProfile.dateIncrement);return this.build(prevDate,nowDate,-1,forceToValid)}buildNext(currentDateProfile,currentDate,nowDate,forceToValid){let{dateEnv}=this.props,nextDate=dateEnv.add(dateEnv.startOf(currentDate,currentDateProfile.currentRangeUnit),currentDateProfile.dateIncrement);return this.build(nextDate,nowDate,1,forceToValid)}build(currentDate,nowDate,direction,forceToValid=!0){let{props}=this,validRange,currentInfo,isRangeAllDay,renderRange,activeRange,isValid;return validRange=this.buildValidRange(nowDate),validRange=this.trimHiddenDays(validRange),forceToValid&&(currentDate=constrainMarkerToRange(currentDate,validRange)),currentInfo=this.buildCurrentRangeInfo(currentDate,direction),isRangeAllDay=/^(year|month|week|day)$/.test(currentInfo.unit),renderRange=this.buildRenderRange(this.trimHiddenDays(currentInfo.range),currentInfo.unit,isRangeAllDay),renderRange=this.trimHiddenDays(renderRange),activeRange=renderRange,props.showNonCurrentDates||(activeRange=intersectRanges(activeRange,currentInfo.range)),activeRange=this.adjustActiveRange(activeRange),activeRange=intersectRanges(activeRange,validRange),isValid=rangesIntersect(currentInfo.range,validRange),rangeContainsMarker(renderRange,currentDate)||(currentDate=renderRange.start),{currentDate,validRange,currentRange:currentInfo.range,currentRangeUnit:currentInfo.unit,isRangeAllDay,activeRange,renderRange,slotMinTime:props.slotMinTime,slotMaxTime:props.slotMaxTime,isValid,dateIncrement:this.buildDateIncrement(currentInfo.duration)}}buildValidRange(nowDate){let input=this.props.validRangeInput,simpleInput=typeof input=="function"?input.call(this.props.calendarApi,this.props.dateEnv.toDate(nowDate)):input;return this.refineRange(simpleInput)||{start:null,end:null}}buildCurrentRangeInfo(date,direction){let{props}=this,duration=null,unit=null,range=null,dayCount;return props.duration?(duration=props.duration,unit=props.durationUnit,range=this.buildRangeFromDuration(date,direction,duration,unit)):(dayCount=this.props.dayCount)?(unit="day",range=this.buildRangeFromDayCount(date,direction,dayCount)):(range=this.buildCustomVisibleRange(date))?unit=props.dateEnv.greatestWholeUnit(range.start,range.end).unit:(duration=this.getFallbackDuration(),unit=greatestDurationDenominator(duration).unit,range=this.buildRangeFromDuration(date,direction,duration,unit)),{duration,unit,range}}getFallbackDuration(){return createDuration({day:1})}adjustActiveRange(range){let{dateEnv,usesMinMaxTime,slotMinTime,slotMaxTime}=this.props,{start,end}=range;return usesMinMaxTime&&(asRoughDays(slotMinTime)<0&&(start=startOfDay5(start),start=dateEnv.add(start,slotMinTime)),asRoughDays(slotMaxTime)>1&&(end=startOfDay5(end),end=addDays4(end,-1),end=dateEnv.add(end,slotMaxTime))),{start,end}}buildRangeFromDuration(date,direction,duration,unit){let{dateEnv,dateAlignment}=this.props,start,end,res;if(!dateAlignment){let{dateIncrement}=this.props;dateIncrement&&asRoughMs(dateIncrement)<asRoughMs(duration)?dateAlignment=greatestDurationDenominator(dateIncrement).unit:dateAlignment=unit}asRoughDays(duration)<=1&&this.isHiddenDay(start)&&(start=this.skipHiddenDays(start,direction),start=startOfDay5(start));function computeRes(){start=dateEnv.startOf(date,dateAlignment),end=dateEnv.add(start,duration),res={start,end}}return computeRes(),this.trimHiddenDays(res)||(date=this.skipHiddenDays(date,direction),computeRes()),res}buildRangeFromDayCount(date,direction,dayCount){let{dateEnv,dateAlignment}=this.props,runningCount=0,start=date,end;dateAlignment&&(start=dateEnv.startOf(start,dateAlignment)),start=startOfDay5(start),start=this.skipHiddenDays(start,direction),end=start;do end=addDays4(end,1),this.isHiddenDay(end)||(runningCount+=1);while(runningCount<dayCount);return{start,end}}buildCustomVisibleRange(date){let{props}=this,input=props.visibleRangeInput,simpleInput=typeof input=="function"?input.call(props.calendarApi,props.dateEnv.toDate(date)):input,range=this.refineRange(simpleInput);return range&&(range.start==null||range.end==null)?null:range}buildRenderRange(currentRange,currentRangeUnit,isRangeAllDay){return currentRange}buildDateIncrement(fallback){let{dateIncrement}=this.props,customAlignment;return dateIncrement||((customAlignment=this.props.dateAlignment)?createDuration(1,customAlignment):fallback||createDuration({days:1}))}refineRange(rangeInput){if(rangeInput){let range=parseRange(rangeInput,this.props.dateEnv);return range&&(range=computeVisibleDayRange(range)),range}return null}initHiddenDays(){let hiddenDays=this.props.hiddenDays||[],isHiddenDayHash=[],dayCnt=0,i;for(this.props.weekends===!1&&hiddenDays.push(0,6),i=0;i<7;i+=1)(isHiddenDayHash[i]=hiddenDays.indexOf(i)!==-1)||(dayCnt+=1);if(!dayCnt)throw new Error("invalid hiddenDays");this.isHiddenDayHash=isHiddenDayHash}trimHiddenDays(range){let{start,end}=range;return start&&(start=this.skipHiddenDays(start)),end&&(end=this.skipHiddenDays(end,-1,!0)),start==null||end==null||start<end?{start,end}:null}isHiddenDay(day){return day instanceof Date&&(day=day.getUTCDay()),this.isHiddenDayHash[day]}skipHiddenDays(date,inc=1,isExclusive=!1){for(;this.isHiddenDayHash[(date.getUTCDay()+(isExclusive?inc:0)+7)%7];)date=addDays4(date,inc);return date}};function computeMajorUnit(dateProfile,dateEnv){let{currentRange}=dateProfile;if(dateProfile.currentRangeUnit==="year")return dateEnv.diffWholeYears(currentRange.start,currentRange.end)>1?"year":"month";if(dateProfile.currentRangeUnit==="month"){if(dateEnv.diffWholeMonths(currentRange.start,currentRange.end)>1)return"month"}else if(dateProfile.currentRangeUnit==="week"){if(diffWholeWeeks(currentRange.start,currentRange.end)>1)return"week"}else if(dateProfile.currentRangeUnit==="day"&&diffWholeDays(currentRange.start,currentRange.end)>1)return"day"}function isMajorUnit(dateMarker,majorUnit,dateEnv){if(dateMarker.valueOf()===startOfDay5(dateMarker).valueOf()){if(majorUnit==="year")return!dateEnv.getMonth(dateMarker)&&dateEnv.getDay(dateMarker)===1;if(majorUnit==="month")return dateEnv.getDay(dateMarker)===1;if(majorUnit==="week")return dateMarker.getUTCDay()===dateEnv.weekDow;if(majorUnit==="day")return!0}return!1}function reduceEventStore(eventStore,action,eventSources,dateProfile,context){switch(action.type){case"RECEIVE_EVENTS":return receiveRawEvents(eventStore,eventSources[action.sourceId],action.fetchId,action.fetchRange,action.rawEvents,context);case"RESET_RAW_EVENTS":return resetRawEvents(eventStore,eventSources[action.sourceId],action.rawEvents,dateProfile.activeRange,context);case"ADD_EVENTS":return addEvent(eventStore,action.eventStore,dateProfile?dateProfile.activeRange:null,context);case"RESET_EVENTS":return action.eventStore;case"MERGE_EVENTS":return mergeEventStores(eventStore,action.eventStore);case"PREV":case"NEXT":case"CHANGE_DATE":case"CHANGE_VIEW_TYPE":return dateProfile?expandRecurring(eventStore,dateProfile.activeRange,context):eventStore;case"REMOVE_EVENTS":return excludeSubEventStore(eventStore,action.eventStore);case"REMOVE_EVENT_SOURCE":return excludeEventsBySourceId(eventStore,action.sourceId);case"REMOVE_ALL_EVENT_SOURCES":return filterEventStoreDefs(eventStore,eventDef=>!eventDef.sourceId);case"REMOVE_ALL_EVENTS":return createEmptyEventStore();default:return eventStore}}function receiveRawEvents(eventStore,eventSource,fetchId,fetchRange,rawEvents,context){if(eventSource&&fetchId===eventSource.latestFetchId){let subset=parseEvents(transformRawEvents(rawEvents,eventSource,context),eventSource,context);return fetchRange&&(subset=expandRecurring(subset,fetchRange,context)),mergeEventStores(excludeEventsBySourceId(eventStore,eventSource.sourceId),subset)}return eventStore}function resetRawEvents(existingEventStore,eventSource,rawEvents,activeRange,context){let{defIdMap,instanceIdMap}=buildPublicIdMaps(existingEventStore),newEventStore=parseEvents(transformRawEvents(rawEvents,eventSource,context),eventSource,context,!1,defIdMap,instanceIdMap);return expandRecurring(newEventStore,activeRange,context)}function transformRawEvents(rawEvents,eventSource,context){let calEachTransform=context.options.eventDataTransform,sourceEachTransform=eventSource?eventSource.eventDataTransform:null;return sourceEachTransform&&(rawEvents=transformEachRawEvent(rawEvents,sourceEachTransform)),calEachTransform&&(rawEvents=transformEachRawEvent(rawEvents,calEachTransform)),rawEvents}function transformEachRawEvent(rawEvents,func){let refinedEvents;if(!func)refinedEvents=rawEvents;else{refinedEvents=[];for(let rawEvent of rawEvents){let refinedEvent=func(rawEvent);refinedEvent?refinedEvents.push(refinedEvent):refinedEvent==null&&refinedEvents.push(rawEvent)}}return refinedEvents}function addEvent(eventStore,subset,expandRange,context){return expandRange&&(subset=expandRecurring(subset,expandRange,context)),mergeEventStores(eventStore,subset)}function rezoneEventStoreDates(eventStore,oldDateEnv,newDateEnv){let{defs}=eventStore,instances=mapHash(eventStore.instances,instance=>{if(defs[instance.defId].allDay)return instance;let{instantStartMs,instantEndMs}=instance.range,start=instantStartMs!=null?newDateEnv.timestampToMarker(instantStartMs):newDateEnv.createMarker(oldDateEnv.toDate(instance.range.start)),end=instantEndMs!=null?newDateEnv.timestampToMarker(instantEndMs):newDateEnv.createMarker(oldDateEnv.toDate(instance.range.end));return{...instance,range:buildValidInstanceRange({marker:start,instantMs:instantStartMs},{marker:end,instantMs:instantEndMs},newDateEnv)??buildEventInstanceRange(start,addMs(start,getRangeInstantEndMs(instance.range,oldDateEnv)-getRangeInstantStartMs(instance.range,oldDateEnv)),instantStartMs)}});return{defs,instances}}function excludeEventsBySourceId(eventStore,sourceId){return filterEventStoreDefs(eventStore,eventDef=>eventDef.sourceId!==sourceId)}function excludeInstances(eventStore,removals){return{defs:eventStore.defs,instances:filterHash(eventStore.instances,instance=>!removals[instance.instanceId])}}function buildPublicIdMaps(eventStore){let{defs,instances}=eventStore,defIdMap={},instanceIdMap={};for(let defId in defs){let def=defs[defId],{publicId}=def;publicId&&(defIdMap[publicId]=defId)}for(let instanceId in instances){let instance=instances[instanceId],def=defs[instance.defId],{publicId}=def;publicId&&(instanceIdMap[publicId]=instanceId)}return{defIdMap,instanceIdMap}}var Interaction=class{constructor(settings){this.component=settings.component,this.isHitComboAllowed=settings.isHitComboAllowed||null}destroy(){}};function parseInteractionSettings(component,input){return{component,el:input.el,useEventCenter:input.useEventCenter!=null?input.useEventCenter:!0,isHitComboAllowed:input.isHitComboAllowed||null}}function interactionSettingsToStore(settings){return{[settings.component.uid]:settings}}var interactionSettingsStore={};var Emitter=class{constructor(){this.handlers={},this.thisContext=null}setThisContext(thisContext){this.thisContext=thisContext}setOptions(options){this.options=options}on(type,handler){addToHash(this.handlers,type,handler)}off(type,handler){removeFromHash(this.handlers,type,handler)}trigger(type,...args){let attachedHandlers=this.handlers[type]||[],optionHandler=this.options&&this.options[type],handlers=[].concat(optionHandler||[],attachedHandlers);for(let handler of handlers)handler.apply(this.thisContext,args)}hasHandlers(type){return!!(this.handlers[type]&&this.handlers[type].length||this.options&&this.options[type])}};function addToHash(hash,type,handler){(hash[type]||(hash[type]=[])).push(handler)}function removeFromHash(hash,type,handler){handler?hash[type]&&(hash[type]=hash[type].filter(func=>func!==handler)):delete hash[type]}import{Component as Component2,createElement as createElement3,Fragment as Fragment$1}from"react";function refinePluginDef(input){return{name:input.name,premiumReleaseDate:input.premiumReleaseDate?new Date(input.premiumReleaseDate):void 0,reducers:input.reducers||[],isLoadingFuncs:input.isLoadingFuncs||[],contextInit:[].concat(input.contextInit||[]),eventRefiners:input.eventRefiners||{},eventDefMemberAdders:input.eventDefMemberAdders||[],eventSourceRefiners:input.eventSourceRefiners||{},isDraggableTransformers:input.isDraggableTransformers||[],eventDragMutationMassagers:input.eventDragMutationMassagers||[],eventDefMutationAppliers:input.eventDefMutationAppliers||[],dateSelectionTransformers:input.dateSelectionTransformers||[],datePointTransforms:input.datePointTransforms||[],dateSpanTransforms:input.dateSpanTransforms||[],views:input.views||{},viewPropsTransformers:input.viewPropsTransformers||[],isPropsValid:input.isPropsValid||null,externalDefTransforms:input.externalDefTransforms||[],viewContainerAppends:input.viewContainerAppends||[],eventDropTransformers:input.eventDropTransformers||[],componentInteractions:input.componentInteractions||[],calendarInteractions:input.calendarInteractions||[],eventSourceDefs:input.eventSourceDefs||[],cmdFormatter:input.cmdFormatter,recurringTypes:input.recurringTypes||[],initialView:input.initialView||"",elementDraggingImpl:input.elementDraggingImpl,optionChangeHandlers:input.optionChangeHandlers||{},scrollerSyncerClass:input.scrollerSyncerClass||null,listenerRefiners:input.listenerRefiners||{},optionRefiners:input.optionRefiners||{},optionDefaults:input.optionDefaults?[input.optionDefaults]:[],propSetHandlers:input.propSetHandlers||{}}}function buildPluginHooks(pluginDefs,globalDefs){let pluginsByName={},hooks={premiumReleaseDate:void 0,reducers:[],isLoadingFuncs:[],contextInit:[],eventRefiners:{},eventDefMemberAdders:[],eventSourceRefiners:{},isDraggableTransformers:[],eventDragMutationMassagers:[],eventDefMutationAppliers:[],dateSelectionTransformers:[],datePointTransforms:[],dateSpanTransforms:[],views:{},viewPropsTransformers:[],isPropsValid:null,externalDefTransforms:[],viewContainerAppends:[],eventDropTransformers:[],componentInteractions:[],calendarInteractions:[],eventSourceDefs:[],cmdFormatter:null,recurringTypes:[],initialView:"",elementDraggingImpl:null,optionChangeHandlers:{},scrollerSyncerClass:null,listenerRefiners:{},optionRefiners:{},optionDefaults:[],propSetHandlers:{}};function addDefs(defs){for(let unrefinedDef of defs){let{name}=unrefinedDef;if(!name)throw new Error("Plugin must specify a name");if(!pluginsByName[name]){let def=pluginsByName[name]=refinePluginDef(unrefinedDef);hooks=combineHooks(hooks,def),addDefs(unrefinedDef.deps||[])}}}return pluginDefs&&addDefs(pluginDefs),addDefs(globalDefs),hooks}function buildBuildPluginHooks(){let currentOverrideDefs=[],currentGlobalDefs=[],currentHooks;return(overrideDefs,globalDefs)=>((!currentHooks||!isArraysEqual(overrideDefs,currentOverrideDefs)||!isArraysEqual(globalDefs,currentGlobalDefs))&&(currentHooks=buildPluginHooks(overrideDefs,globalDefs)),currentOverrideDefs=overrideDefs,currentGlobalDefs=globalDefs,currentHooks)}function combineHooks(hooks0,hooks1){return{premiumReleaseDate:compareOptionalDates(hooks0.premiumReleaseDate,hooks1.premiumReleaseDate),reducers:hooks0.reducers.concat(hooks1.reducers),isLoadingFuncs:hooks0.isLoadingFuncs.concat(hooks1.isLoadingFuncs),contextInit:hooks0.contextInit.concat(hooks1.contextInit),eventRefiners:{...hooks0.eventRefiners,...hooks1.eventRefiners},eventDefMemberAdders:hooks0.eventDefMemberAdders.concat(hooks1.eventDefMemberAdders),eventSourceRefiners:{...hooks0.eventSourceRefiners,...hooks1.eventSourceRefiners},isDraggableTransformers:hooks0.isDraggableTransformers.concat(hooks1.isDraggableTransformers),eventDragMutationMassagers:hooks0.eventDragMutationMassagers.concat(hooks1.eventDragMutationMassagers),eventDefMutationAppliers:hooks0.eventDefMutationAppliers.concat(hooks1.eventDefMutationAppliers),dateSelectionTransformers:hooks0.dateSelectionTransformers.concat(hooks1.dateSelectionTransformers),datePointTransforms:hooks0.datePointTransforms.concat(hooks1.datePointTransforms),dateSpanTransforms:hooks0.dateSpanTransforms.concat(hooks1.dateSpanTransforms),views:mergeViewOptionsMap(hooks0.views,hooks1.views),viewPropsTransformers:hooks0.viewPropsTransformers.concat(hooks1.viewPropsTransformers),isPropsValid:hooks1.isPropsValid||hooks0.isPropsValid,externalDefTransforms:hooks0.externalDefTransforms.concat(hooks1.externalDefTransforms),viewContainerAppends:hooks0.viewContainerAppends.concat(hooks1.viewContainerAppends),eventDropTransformers:hooks0.eventDropTransformers.concat(hooks1.eventDropTransformers),calendarInteractions:hooks0.calendarInteractions.concat(hooks1.calendarInteractions),componentInteractions:hooks0.componentInteractions.concat(hooks1.componentInteractions),eventSourceDefs:hooks0.eventSourceDefs.concat(hooks1.eventSourceDefs),cmdFormatter:hooks1.cmdFormatter||hooks0.cmdFormatter,recurringTypes:hooks0.recurringTypes.concat(hooks1.recurringTypes),initialView:hooks0.initialView||hooks1.initialView,elementDraggingImpl:hooks0.elementDraggingImpl||hooks1.elementDraggingImpl,optionChangeHandlers:{...hooks0.optionChangeHandlers,...hooks1.optionChangeHandlers},scrollerSyncerClass:hooks0.scrollerSyncerClass||hooks1.scrollerSyncerClass,listenerRefiners:{...hooks0.listenerRefiners,...hooks1.listenerRefiners},optionRefiners:{...hooks0.optionRefiners,...hooks1.optionRefiners},optionDefaults:hooks0.optionDefaults.concat(hooks1.optionDefaults),propSetHandlers:{...hooks0.propSetHandlers,...hooks1.propSetHandlers}}}function compareOptionalDates(date0,date1){return date0===void 0?date1:date1===void 0?date0:new Date(Math.max(date0.valueOf(),date1.valueOf()))}function compileViewDefs(defaultConfigs,overrideConfigs){let hash={},viewType;for(viewType in defaultConfigs)ensureViewDef(viewType,hash,defaultConfigs,overrideConfigs);for(viewType in overrideConfigs)ensureViewDef(viewType,hash,defaultConfigs,overrideConfigs);return hash}function ensureViewDef(viewType,hash,defaultConfigs,overrideConfigs){if(hash[viewType])return hash[viewType];let viewDef=buildViewDef(viewType,hash,defaultConfigs,overrideConfigs);return viewDef&&(hash[viewType]=viewDef),viewDef}function buildViewDef(viewType,hash,defaultConfigs,overrideConfigs){let defaultConfig=defaultConfigs[viewType],overrideConfig=overrideConfigs[viewType],queryProp=name=>defaultConfig&&defaultConfig[name]!==null?defaultConfig[name]:overrideConfig&&overrideConfig[name]!==null?overrideConfig[name]:null,theComponent=queryProp("component"),superType=queryProp("superType"),superDef=null;if(superType){if(superType===viewType)throw new Error("Can't have a custom view type that references itself");superDef=ensureViewDef(superType,hash,defaultConfigs,overrideConfigs)}return!theComponent&&superDef&&(theComponent=superDef.component),theComponent?{type:viewType,component:theComponent,defaults:mergeCalendarOptions(superDef?superDef.defaults:{},defaultConfig?defaultConfig.rawOptions:{}),overrides:mergeCalendarOptions(superDef?superDef.overrides:{},overrideConfig?overrideConfig.rawOptions:{})}:null}function parseViewConfigs(inputs){return mapHash(inputs,parseViewConfig)}function parseViewConfig(input){let rawOptions=typeof input=="function"?{component:input}:input,{component}=rawOptions;return rawOptions.content?component=createViewHookComponent(rawOptions.content):component&&!(component.prototype instanceof BaseComponent)&&(component=createViewHookComponent(component)),{superType:rawOptions.type,component,rawOptions}}function createViewHookComponent(contentGenerator){return viewProps=>jsx9(ViewContextType.Consumer,{children:context=>{let{options,viewSpec}=context,renderProps={...viewProps,nextDayThreshold:options.nextDayThreshold,...computeViewBorderless(options),options:{headerToolbar:options.headerToolbar,footerToolbar:options.footerToolbar},isHeightAuto:getIsHeightAuto(options),view:context.viewApi};return jsx9(ContentContainer,{tag:"div",className:joinClassNames(generateClassName(options.viewClass,renderProps),generateClassName(viewSpec.optionDefaults.class,renderProps),generateClassName(viewSpec.optionDefaults.className,renderProps),generateClassName(viewSpec.optionOverrides.class,renderProps),generateClassName(viewSpec.optionOverrides.className,renderProps)),renderProps,generatorName:void 0,customGenerator:contentGenerator,didMount:options.didMount||options.viewDidMount,willUnmount:options.willUnmount||options.viewWillUnmount})}})}function buildViewSpecs(defaultInputs,optionOverrides,dynamicOptionOverrides){let defaultConfigs=parseViewConfigs(defaultInputs),overrideConfigs=parseViewConfigs(optionOverrides.views),viewDefs=compileViewDefs(defaultConfigs,overrideConfigs);return mapHash(viewDefs,viewDef=>buildViewSpec(viewDef,overrideConfigs,optionOverrides,dynamicOptionOverrides))}function buildViewSpec(viewDef,overrideConfigs,optionOverrides,dynamicOptionOverrides){let durationInput=viewDef.overrides.duration||viewDef.defaults.duration||dynamicOptionOverrides.duration||optionOverrides.duration,duration=null,durationUnit="",singleUnit="",singleUnitOverrides={};if(durationInput&&(duration=createDurationCached(durationInput),duration)){let denom=greatestDurationDenominator(duration);durationUnit=denom.unit,denom.value===1&&(singleUnit=durationUnit,singleUnitOverrides=overrideConfigs[durationUnit]?overrideConfigs[durationUnit].rawOptions:{})}return{type:viewDef.type,component:viewDef.component,duration,durationUnit,singleUnit,optionDefaults:viewDef.defaults,optionOverrides:{...singleUnitOverrides,...viewDef.overrides}}}var durationInputMap={};function createDurationCached(durationInput){let json=JSON.stringify(durationInput),res=durationInputMap[json];return res===void 0&&(res=createDuration(durationInput),durationInputMap[json]=res),res}function reduceViewType(viewType,action){return action.type==="CHANGE_VIEW_TYPE"&&(viewType=action.viewType),viewType}function reduceCurrentDate(currentDate,action){return action.type==="CHANGE_DATE"?action.dateMarker:currentDate}function getInitialDate(options,dateEnv,nowManager){let initialDateInput=options.initialDate;return initialDateInput!=null?dateEnv.createMarker(initialDateInput):nowManager.getDateMarker()}function reduceDynamicOptionOverrides(dynamicOptionOverrides,action){return action.type==="SET_OPTION"?{...dynamicOptionOverrides,[action.optionName]:action.rawOptionValue}:dynamicOptionOverrides}function reduceDateProfile(currentDateProfile,action,currentDate,nowDate,dateProfileGenerator){let dp;switch(action.type){case"CHANGE_VIEW_TYPE":return dateProfileGenerator.build(action.dateMarker||currentDate,nowDate);case"CHANGE_DATE":return dateProfileGenerator.build(action.dateMarker,nowDate);case"PREV":if(dp=dateProfileGenerator.buildPrev(currentDateProfile,currentDate,nowDate),dp.isValid)return dp;break;case"NEXT":if(dp=dateProfileGenerator.buildNext(currentDateProfile,currentDate,nowDate),dp.isValid)return dp;break}return currentDateProfile}function reduceDateSelection(currentSelection,action){switch(action.type){case"UNSELECT_DATES":return null;case"SELECT_DATES":return action.selection;default:return currentSelection}}function reduceSelectedEvent(currentInstanceId,action){switch(action.type){case"UNSELECT_EVENT":return"";case"SELECT_EVENT":return action.eventInstanceId;default:return currentInstanceId}}function reduceEventDrag(currentDrag,action){let newDrag;switch(action.type){case"UNSET_EVENT_DRAG":return null;case"SET_EVENT_DRAG":return newDrag=action.state,{affectedEvents:newDrag.affectedEvents,mutatedEvents:newDrag.mutatedEvents,isEvent:newDrag.isEvent};default:return currentDrag}}function reduceEventResize(currentResize,action){let newResize;switch(action.type){case"UNSET_EVENT_RESIZE":return null;case"SET_EVENT_RESIZE":return newResize=action.state,{affectedEvents:newResize.affectedEvents,mutatedEvents:newResize.mutatedEvents,isEvent:newResize.isEvent};default:return currentResize}}function parseToolbars(calendarOptions,viewSpecs,calendarApi){let header=calendarOptions.headerToolbar?parseToolbar(calendarOptions.headerToolbar,calendarOptions,viewSpecs,calendarApi):null,footer=calendarOptions.footerToolbar?parseToolbar(calendarOptions.footerToolbar,calendarOptions,viewSpecs,calendarApi):null;return{header,footer}}function parseToolbar(sectionStrHash,calendarOptions,viewSpecs,calendarApi){let isRtl=calendarOptions.direction==="rtl",viewsWithButtons=[],hasTitle=!1;function processSectionStr(sectionStr){let sectionRes=parseSection(sectionStr,calendarOptions,viewSpecs,calendarApi);return viewsWithButtons.push(...sectionRes.viewsWithButtons),hasTitle=hasTitle||sectionRes.hasTitle,sectionRes.widgets}return{sectionWidgets:{start:processSectionStr(sectionStrHash[isRtl?"right":"left"]||sectionStrHash.start||""),center:processSectionStr(sectionStrHash.center||""),end:processSectionStr(sectionStrHash[isRtl?"left":"right"]||sectionStrHash.end||"")},viewsWithButtons,hasTitle}}function parseSection(sectionStr,calendarOptions,viewSpecs,calendarApi){let calendarButtons=calendarOptions.buttons||{},customElements=calendarOptions.toolbarElements||{},sectionSubstrs=sectionStr?sectionStr.split(" "):[],viewsWithButtons=[],hasTitle=!1;return{widgets:sectionSubstrs.map(buttonGroupStr=>buttonGroupStr.split(",").map(name=>{if(name==="title")return hasTitle=!0,{name};if(customElements[name])return{name,customElement:customElements[name]};let viewSpec,buttonInput=calendarButtons[name]||{},buttonText,buttonHint,buttonClick;if(viewSpec=viewSpecs[name]){viewsWithButtons.push(name);let buttonTextKey=viewSpec.optionDefaults.buttonTextKey;buttonText=buttonInput.text||(buttonTextKey?calendarOptions[buttonTextKey]:"")||(viewSpec.singleUnit?calendarOptions[viewSpec.singleUnit+"TextLong"]||calendarOptions[viewSpec.singleUnit+"Text"]:"")||name,buttonHint=formatWithOrdinals(buttonInput.hint||calendarOptions.viewHint,[buttonText,name],buttonText),buttonClick=ev=>{buttonInput?.click?.(ev),ev.defaultPrevented||calendarApi.changeView(name)}}else buttonText=buttonInput.text||calendarOptions[name+"TextLong"]||calendarOptions[name+"Text"]||name,name==="prevYear"?buttonHint=formatWithOrdinals(buttonInput.hint||calendarOptions.prevHint,[calendarOptions.yearText,"year"],buttonText):name==="nextYear"?buttonHint=formatWithOrdinals(buttonInput.hint||calendarOptions.nextHint,[calendarOptions.yearText,"year"],buttonText):buttonHint=currentUnit=>formatWithOrdinals(buttonInput.hint||calendarOptions[name+"Hint"],[calendarOptions[currentUnit+"TextLong"]||calendarOptions[currentUnit+"Text"],currentUnit],buttonText),buttonClick=ev=>{buttonInput?.click?.(ev),ev.defaultPrevented||calendarApi[name]?.()};return{name,isView:!!viewSpec,buttonText,buttonHint,buttonDisplay:buttonInput.display,buttonIconClass:buttonInput.iconClass,buttonIconContent:buttonInput.iconContent,buttonClick,buttonIsPrimary:buttonInput.isPrimary||!1,buttonClass:buttonInput.class??buttonInput.className,buttonDidMount:buttonInput.didMount,buttonWillUnmount:buttonInput.willUnmount}})),viewsWithButtons,hasTitle}}var ViewImpl=class{constructor(type,getCurrentData,dateEnv){this.type=type,this.getCurrentData=getCurrentData,this.dateEnv=dateEnv}get calendar(){return this.getCurrentData().calendarApi}get title(){return this.getCurrentData().viewTitle}get activeStart(){return this.dateEnv.toDate(this.getCurrentData().dateProfile.activeRange.start)}get activeEnd(){return this.dateEnv.toDate(this.getCurrentData().dateProfile.activeRange.end)}get currentStart(){return this.dateEnv.toDate(this.getCurrentData().dateProfile.currentRange.start)}get currentEnd(){return this.dateEnv.toDate(this.getCurrentData().dateProfile.currentRange.end)}getOption(name){return this.getCurrentData().options[name]}},DEF_DEFAULTS={startTime:"09:00",endTime:"17:00",daysOfWeek:[1,2,3,4,5],display:"inverse-background",className:"",groupId:"_businessHours"};function parseBusinessHours(input,context){return parseEvents(refineInputs(input),null,context)}function refineInputs(input){let rawDefs;return input===!0?rawDefs=[{}]:Array.isArray(input)?rawDefs=input.filter(rawDef=>rawDef.daysOfWeek):typeof input=="object"&&input?rawDefs=[input]:rawDefs=[],rawDefs=rawDefs.map(rawDef=>({...DEF_DEFAULTS,...rawDef})),rawDefs}function buildTitle(dateProfile,viewOptions,dateEnv){let range;/^(year|month)$/.test(dateProfile.currentRangeUnit)?range=dateProfile.currentRange:range=dateProfile.activeRange;let parts,options={isEndExclusive:dateProfile.isRangeAllDay};return viewOptions.titleFormat?parts=dateEnv.formatRangeToParts(range.start,range.end,createFormatter(viewOptions.titleFormat),options):(parts=dateEnv.formatRangeToParts(range.start,range.end,createFormatter(buildTitleFormat(dateProfile,viewOptions.disallowAmbigTitle,"long")),options),hasTwoMonths(parts)&&(parts=dateEnv.formatRangeToParts(range.start,range.end,createFormatter(buildTitleFormat(dateProfile,viewOptions.disallowAmbigTitle,"short")),options))),joinDateTimeFormatParts(parts)}function buildTitleFormat(dateProfile,disallowAmbigTitle,monthFormat){let{currentRangeUnit}=dateProfile;if(currentRangeUnit==="year")return{year:"numeric"};if(currentRangeUnit==="month")return{year:"numeric",month:monthFormat};if(!disallowAmbigTitle){let days=diffWholeDays(dateProfile.currentRange.start,dateProfile.currentRange.end);if(days!==null&&days>1)return{year:"numeric",month:monthFormat}}return{year:"numeric",month:"long",day:"numeric"}}function hasTwoMonths(parts){let hasStartMonth=!1,hasEndMonth=!1;for(let part of parts)part.type==="month"&&(part.source==="startRange"&&(hasStartMonth=!0),part.source==="endRange"&&(hasEndMonth=!0));return hasStartMonth&&hasEndMonth}var CalendarNowManager=class{constructor(){this.resetListeners=new Set}handleInput(dateEnv,nowInput){let oldDateEnv=this.dateEnv;if(dateEnv!==oldDateEnv&&(typeof nowInput=="function"?this.nowFn=nowInput:oldDateEnv||(this.nowAnchorDate=nowInput?resolveInputToDate(nowInput,dateEnv):new Date,this.nowAnchorQueried=Date.now()),this.dateEnv=dateEnv,oldDateEnv))for(let resetListener of this.resetListeners.values())resetListener()}getDateMarker(){return this.dateEnv.timestampToMarker(this.getEpochMs())}getEpochMs(){return this.nowAnchorDate?this.nowAnchorDate.valueOf()+(Date.now()-this.nowAnchorQueried):resolveInputToDate(this.nowFn(),this.dateEnv).valueOf()}addResetListener(handler){this.resetListeners.add(handler)}removeResetListener(handler){this.resetListeners.delete(handler)}};function resolveInputToDate(input,dateEnv){let meta=dateEnv.createMarkerMeta(input);return meta.instantMs!=null?new Date(meta.instantMs):dateEnv.toDate(meta.marker)}var CalendarDataManager=class{constructor(config2){this.computeCurrentViewData=memoize2(this._computeCurrentViewData),this.organizeRawLocales=memoize2(organizeRawLocales),this.buildLocale=memoize2(buildLocale),this.buildPluginHooks=buildBuildPluginHooks(),this.buildDateEnv=memoize2(buildDateEnv),this.parseToolbars=memoize2(parseToolbars),this.buildViewSpecs=memoize2(buildViewSpecs),this.buildDateProfileGenerator=memoizeObjArg(buildDateProfileGenerator),this.buildViewApi=memoize2(buildViewApi),this.buildViewUiProps=memoizeObjArg(buildViewUiProps),this.buildEventUiBySource=memoize2(buildEventUiBySource,isPropsEqualShallow),this.buildEventUiBases=memoize2(buildEventUiBases),this.parseContextBusinessHours=memoizeObjArg(parseContextBusinessHours),this.buildToolbarProps=memoize2(buildToolbarProps),this.buildTitle=memoize2(buildTitle),this.nowManager=new CalendarNowManager,this.isDrainingActionQueue=!1,this.actionQueue=[],this.optionOverrides={},this.emitter=new Emitter,this.currentCalendarOptionsRefiners={},this.currentCalendarOptionsInput={},this.currentCalendarOptionsRefined={},this.currentViewOptionsInput={},this.currentViewOptionsRefined={},this.optionsForRefining=[],this.optionsForHandling=[],this.getCurrentData=()=>this.data,this.handleNowChange=()=>{this.dispatch({type:"UPDATE_NOW"})},this.dispatch=action=>{this.actionQueue.push(action),this.isDrainingActionQueue||this.drainActionQueue()},this.config=config2,this.nowManager=new CalendarNowManager,this.nowTimer=new NowTimerRunner(this.handleNowChange)}destroy(){this.nowTimer.destroy()}update(optionOverrides){return this.optionOverrides=optionOverrides,this.actionQueue.push({type:"IDLE"}),this.drainActionQueue(),this.data}resetOptions(optionOverrides,changedOptionNames){changedOptionNames===void 0?this.optionOverrides=optionOverrides:(this.optionOverrides={...this.optionOverrides,...optionOverrides},this.optionsForRefining.push(...changedOptionNames)),this.dispatch({type:"RESET_OPTIONS"})}drainActionQueue(){let calendarContext,{state,data}=this,isInit=!state,{actionQueue}=this,actionsComplete=[];for(this.isDrainingActionQueue=!0;actionQueue.length;){let action=actionQueue.shift();({state,data,calendarContext}=this.reduce(state,data,action)),this.state=state,this.data=data,action.type!=="IDLE"&&actionsComplete.push(action)}if(this.isDrainingActionQueue=!1,isInit){let controllerOption=calendarContext.options.controller;controllerOption&&controllerOption._setApi(this.config.calendarApi)}if(!isInit&&actionsComplete.length){let{onDataChange}=this.config;onDataChange&&onDataChange(this.data,actionsComplete)}}reduce(prevState,prevData,action){let{config:config2}=this,isInit=!prevState,dynamicOptionOverrides=isInit?{}:reduceDynamicOptionOverrides(prevState.dynamicOptionOverrides,action),optionsData=this.computeOptionsData(this.optionOverrides,dynamicOptionOverrides,config2.calendarApi),currentViewType=isInit?optionsData.calendarOptions.initialView||optionsData.pluginHooks.initialView:reduceViewType(prevState.currentViewType,action),currentViewData=this.computeCurrentViewData(currentViewType,optionsData,this.optionOverrides,dynamicOptionOverrides);config2.calendarApi.currentDataManager=this,this.emitter.setThisContext(config2.calendarApi),this.emitter.setOptions(currentViewData.options);let calendarContext={nowManager:this.nowManager,dateEnv:optionsData.dateEnv,options:optionsData.calendarOptions,pluginHooks:optionsData.pluginHooks,calendarApi:config2.calendarApi,dispatch:this.dispatch,emitter:this.emitter,getCurrentData:this.getCurrentData},{nowDate}=this.nowTimer.update({unit:"day",unitValue:1,nowIndicatorSnap:"auto",nowManager:this.nowManager,dateEnv:optionsData.dateEnv}),currentDate=isInit?getInitialDate(optionsData.calendarOptions,optionsData.dateEnv,this.nowManager):reduceCurrentDate(prevState.currentDate,action),dateProfile;isInit?dateProfile=currentViewData.dateProfileGenerator.build(currentDate,nowDate):(dateProfile=prevState.dateProfile,prevData&&prevData.dateProfileGenerator!==currentViewData.dateProfileGenerator&&(dateProfile=currentViewData.dateProfileGenerator.build(currentDate,nowDate)),dateProfile=reduceDateProfile(dateProfile,action,currentDate,nowDate,currentViewData.dateProfileGenerator)),(action&&(action.type==="PREV"||action.type==="NEXT")||!rangeContainsMarker(dateProfile.activeRange,currentDate))&&(currentDate=dateProfile.currentRange.start);let eventSources=isInit?initEventSources(optionsData.calendarOptions,dateProfile,calendarContext):reduceEventSources(prevState.eventSources,action,dateProfile,calendarContext),eventStore=isInit?createEmptyEventStore():reduceEventStore(prevState.eventStore,action,eventSources,dateProfile,calendarContext),isEventsLoading=computeEventSourcesLoading(eventSources),renderableEventStore=isInit?createEmptyEventStore():isEventsLoading&&!currentViewData.options.progressiveEventRendering&&prevState.renderableEventStore||eventStore,{eventUiSingleBase,selectionConfig}=this.buildViewUiProps(calendarContext),eventUiBySource=this.buildEventUiBySource(eventSources),eventUiBases=isInit?{}:this.buildEventUiBases(renderableEventStore.defs,eventUiSingleBase,eventUiBySource),newState={dynamicOptionOverrides,currentViewType,currentDate,dateProfile,eventSources,eventStore,renderableEventStore,selectionConfig,eventUiBases,businessHours:this.parseContextBusinessHours(calendarContext),dateSelection:isInit?null:reduceDateSelection(prevState.dateSelection,action),eventSelection:isInit?"":reduceSelectedEvent(prevState.eventSelection,action),eventDrag:isInit?null:reduceEventDrag(prevState.eventDrag,action),eventResize:isInit?null:reduceEventResize(prevState.eventResize,action),nowDate},contextAndState={...calendarContext,...newState};for(let reducer of optionsData.pluginHooks.reducers)Object.assign(newState,reducer(prevState,action,contextAndState));let wasLoading=prevState?computeIsLoading(prevState,calendarContext):!1,isLoading=computeIsLoading(newState,calendarContext);!wasLoading&&isLoading?this.emitter.trigger("loading",!0):wasLoading&&!isLoading&&this.emitter.trigger("loading",!1);let viewTitle=this.buildTitle(dateProfile,currentViewData.options,optionsData.dateEnv),toolbarProps=this.buildToolbarProps(currentViewData.viewSpec,dateProfile,currentViewData.dateProfileGenerator,currentDate,nowDate,viewTitle),newData={viewTitle,nowManager:this.nowManager,calendarApi:config2.calendarApi,dispatch:this.dispatch,emitter:this.emitter,getCurrentData:this.getCurrentData,toolbarProps,...optionsData,...currentViewData,...newState},changeHandlers=optionsData.pluginHooks.optionChangeHandlers,prevCalendarOptions=prevData&&prevData.calendarOptions,newCalendarOptions=optionsData.calendarOptions;if(prevCalendarOptions&&prevCalendarOptions!==newCalendarOptions){prevCalendarOptions.timeZone!==newCalendarOptions.timeZone&&(newState.eventSources=newData.eventSources=reduceEventSourcesNewTimeZone(newData.eventSources,dateProfile,newData),newState.eventStore=newData.eventStore=rezoneEventStoreDates(newData.eventStore,prevData.dateEnv,newData.dateEnv),newState.renderableEventStore=newData.renderableEventStore=rezoneEventStoreDates(newData.renderableEventStore,prevData.dateEnv,newData.dateEnv));for(let optionName in changeHandlers)(this.optionsForHandling.indexOf(optionName)!==-1||prevCalendarOptions[optionName]!==newCalendarOptions[optionName])&&changeHandlers[optionName](newCalendarOptions[optionName],newData)}return this.optionsForHandling=[],{state:newState,data:newData,calendarContext}}computeOptionsData(optionOverrides,dynamicOptionOverrides,calendarApi){if(!this.optionsForRefining.length&&optionOverrides===this.stableOptionOverrides&&dynamicOptionOverrides===this.stableDynamicOptionOverrides)return this.stableCalendarOptionsData;let{refinedOptions,pluginHooks,localeDefaults,availableLocaleData}=this.processRawCalendarOptions(optionOverrides,dynamicOptionOverrides),dateEnv=this.buildDateEnv(refinedOptions.timeZone,refinedOptions.locale,refinedOptions.weekNumberCalculation,refinedOptions.firstDay,refinedOptions.weekTextLong,refinedOptions.weekTextShort,pluginHooks,availableLocaleData),viewSpecs=this.buildViewSpecs(pluginHooks.views,this.stableOptionOverrides,this.stableDynamicOptionOverrides),toolbarConfig=this.parseToolbars(refinedOptions,viewSpecs,calendarApi);return this.stableCalendarOptionsData={calendarOptions:refinedOptions,pluginHooks,dateEnv,viewSpecs,toolbarConfig,localeDefaults,availableRawLocales:availableLocaleData.map}}processRawCalendarOptions(optionOverrides,dynamicOptionOverrides){let{locales,locale}=mergeCalendarOptions(BASE_OPTION_DEFAULTS,optionOverrides,dynamicOptionOverrides),availableLocaleData=this.organizeRawLocales(locales),availableRawLocales=availableLocaleData.map,localeDefaults=this.buildLocale(locale||availableLocaleData.defaultCode,availableRawLocales).options,pluginHooks=this.buildPluginHooks(optionOverrides.plugins||[],globalPlugins),refiners=this.currentCalendarOptionsRefiners={...BASE_OPTION_REFINERS,...CALENDAR_LISTENER_REFINERS,...CALENDAR_ONLY_OPTION_REFINERS,...pluginHooks.listenerRefiners,...pluginHooks.optionRefiners},raw=mergeCalendarOptions(BASE_OPTION_DEFAULTS,...pluginHooks.optionDefaults,localeDefaults,filterKnownOptions(mergeCalendarOptions(optionOverrides,dynamicOptionOverrides),refiners)),refined={},currentRaw=this.currentCalendarOptionsInput,currentRefined=this.currentCalendarOptionsRefined,anyChanges=!1;for(let optionName in raw)this.optionsForRefining.indexOf(optionName)===-1&&(raw[optionName]===currentRaw[optionName]||COMPLEX_OPTION_COMPARATORS[optionName]&&optionName in currentRaw&&COMPLEX_OPTION_COMPARATORS[optionName](currentRaw[optionName],raw[optionName])||isMergedPropsEqual(currentRaw[optionName],raw[optionName]))?refined[optionName]=currentRefined[optionName]:refiners[optionName]&&(refined[optionName]=refiners[optionName](raw[optionName],optionName),anyChanges=!0);return anyChanges&&(this.currentCalendarOptionsInput=raw,this.currentCalendarOptionsRefined=refined,this.stableOptionOverrides=optionOverrides,this.stableDynamicOptionOverrides=dynamicOptionOverrides),this.optionsForHandling.push(...this.optionsForRefining),this.optionsForRefining=[],{rawOptions:this.currentCalendarOptionsInput,refinedOptions:this.currentCalendarOptionsRefined,pluginHooks,availableLocaleData,localeDefaults}}_computeCurrentViewData(viewType,optionsData,optionOverrides,dynamicOptionOverrides){let viewSpec=optionsData.viewSpecs[viewType];if(!viewSpec)throw new Error(`viewType "${viewType}" is not available. Please make sure you've loaded all neccessary plugins`);let{refinedOptions}=this.processRawViewOptions(viewSpec,optionsData.pluginHooks,optionsData.localeDefaults,optionOverrides,dynamicOptionOverrides);this.nowManager.handleInput(optionsData.dateEnv,refinedOptions.now);let dateProfileGenerator=this.buildDateProfileGenerator({dateProfileGeneratorClass:viewSpec.optionDefaults.dateProfileGeneratorClass,duration:viewSpec.duration,durationUnit:viewSpec.durationUnit,usesMinMaxTime:viewSpec.optionDefaults.usesMinMaxTime,dateEnv:optionsData.dateEnv,calendarApi:this.config.calendarApi,slotMinTime:refinedOptions.slotMinTime,slotMaxTime:refinedOptions.slotMaxTime,showNonCurrentDates:refinedOptions.showNonCurrentDates,dayCount:refinedOptions.dayCount,dateAlignment:refinedOptions.dateAlignment,dateIncrement:refinedOptions.dateIncrement,hiddenDays:refinedOptions.hiddenDays,weekends:refinedOptions.weekends,validRangeInput:refinedOptions.validRange,visibleRangeInput:refinedOptions.visibleRange,fixedWeekCount:refinedOptions.fixedWeekCount}),viewApi=this.buildViewApi(viewType,this.getCurrentData,optionsData.dateEnv);return{viewSpec,options:refinedOptions,dateProfileGenerator,viewApi}}processRawViewOptions(viewSpec,pluginHooks,localeDefaults,optionOverrides,dynamicOptionOverrides){let refiners={...BASE_OPTION_REFINERS,...CALENDAR_LISTENER_REFINERS,...CALENDAR_ONLY_OPTION_REFINERS,...VIEW_ONLY_OPTION_REFINERS,...pluginHooks.listenerRefiners,...pluginHooks.optionRefiners},raw=mergeCalendarOptions(BASE_OPTION_DEFAULTS,...pluginHooks.optionDefaults,viewSpec.optionDefaults,localeDefaults,filterKnownOptions(mergeCalendarOptions(optionOverrides,viewSpec.optionOverrides,dynamicOptionOverrides),refiners)),refined={},currentRaw=this.currentViewOptionsInput,currentRefined=this.currentViewOptionsRefined,anyChanges=!1;for(let optionName in raw)raw[optionName]===currentRaw[optionName]||COMPLEX_OPTION_COMPARATORS[optionName]&&COMPLEX_OPTION_COMPARATORS[optionName](raw[optionName],currentRaw[optionName])||isMergedPropsEqual(currentRaw[optionName],raw[optionName])?refined[optionName]=currentRefined[optionName]:(raw[optionName]===this.currentCalendarOptionsInput[optionName]||COMPLEX_OPTION_COMPARATORS[optionName]&&COMPLEX_OPTION_COMPARATORS[optionName](raw[optionName],this.currentCalendarOptionsInput[optionName])?optionName in this.currentCalendarOptionsRefined&&(refined[optionName]=this.currentCalendarOptionsRefined[optionName]):refiners[optionName]&&(refined[optionName]=refiners[optionName](raw[optionName],optionName)),anyChanges=!0);return anyChanges&&(this.currentViewOptionsInput=raw,this.currentViewOptionsRefined=refined),{rawOptions:this.currentViewOptionsInput,refinedOptions:this.currentViewOptionsRefined}}};function buildDateEnv(timeZone,explicitLocale,weekNumberCalculation,firstDay,weekTextLong,weekTextShort,pluginHooks,availableLocaleData){let locale=buildLocale(explicitLocale||availableLocaleData.defaultCode,availableLocaleData.map);return new DateEnv({calendarSystem:"gregory",timeZone,locale,weekNumberCalculation,firstDay,weekTextLong,weekTextShort,cmdFormatter:pluginHooks.cmdFormatter})}function buildDateProfileGenerator(props){let DateProfileGeneratorClass=props.dateProfileGeneratorClass||DateProfileGenerator;return new DateProfileGeneratorClass(props)}function buildViewApi(type,getCurrentData,dateEnv){return new ViewImpl(type,getCurrentData,dateEnv)}function buildEventUiBySource(eventSources){return mapHash(eventSources,eventSource=>eventSource.ui)}function buildEventUiBases(eventDefs,eventUiSingleBase,eventUiBySource){let eventUiBases={"":eventUiSingleBase};for(let defId in eventDefs){let def=eventDefs[defId];def.sourceId&&eventUiBySource[def.sourceId]&&(eventUiBases[defId]=eventUiBySource[def.sourceId])}return eventUiBases}function buildViewUiProps(calendarContext){let{options}=calendarContext;return{eventUiSingleBase:createEventUi({display:options.eventDisplay,editable:options.editable,startEditable:options.eventStartEditable,durationEditable:options.eventDurationEditable,constraint:options.eventConstraint,overlap:typeof options.eventOverlap=="boolean"?options.eventOverlap:void 0,allow:options.eventAllow},calendarContext),selectionConfig:createEventUi({constraint:options.selectConstraint,overlap:typeof options.selectOverlap=="boolean"?options.selectOverlap:void 0,allow:options.selectAllow},calendarContext)}}function computeIsLoading(state,context){for(let isLoadingFunc of context.pluginHooks.isLoadingFuncs)if(isLoadingFunc(state))return!0;return!1}function parseContextBusinessHours(calendarContext){return parseBusinessHours(calendarContext.options.businessHours,calendarContext)}var warnedUnknownOptions={};function filterKnownOptions(options,optionRefiners){let knownOptions={};for(let optionName in options)optionRefiners[optionName]?knownOptions[optionName]=options[optionName]:warnedUnknownOptions[optionName]||(warn(`Unknown option \`${optionName}\`.`),warnedUnknownOptions[optionName]=!0);return knownOptions}function buildToolbarProps(viewSpec,dateProfile,dateProfileGenerator,currentDate,nowDate,title){let todayInfo=dateProfileGenerator.build(nowDate,nowDate,void 0,!1),prevInfo=dateProfileGenerator.buildPrev(dateProfile,currentDate,nowDate,!1),nextInfo=dateProfileGenerator.buildNext(dateProfile,currentDate,nowDate,!1);return{title,selectedButton:viewSpec.type,navUnit:viewSpec.singleUnit,isTodayEnabled:todayInfo.isValid&&!rangeContainsMarker(dateProfile.currentRange,nowDate),isPrevEnabled:prevInfo.isValid,isNextEnabled:nextInfo.isValid}}var CalendarApiImpl=class{getCurrentData(){return this.currentDataManager.getCurrentData()}dispatch(action){this.currentDataManager.dispatch(action)}get view(){return this.getCurrentData().viewApi}batchRendering(callback){callback()}setOption(name,val){this.dispatch({type:"SET_OPTION",optionName:name,rawOptionValue:val})}getOption(name){return this.currentDataManager.currentCalendarOptionsInput[name]}getAvailableLocaleCodes(){return Object.keys(this.getCurrentData().availableRawLocales)}on(handlerName,handler){let{currentDataManager}=this;currentDataManager.currentCalendarOptionsRefiners[handlerName]?currentDataManager.emitter.on(handlerName,handler):warn(`Unknown listener \`${handlerName}\`.`)}off(handlerName,handler){this.currentDataManager.emitter.off(handlerName,handler)}trigger(handlerName,...args){this.currentDataManager.emitter.trigger(handlerName,...args)}changeView(viewType,dateOrRange){this.batchRendering(()=>{if(this.unselect(),dateOrRange)if(dateOrRange.start&&dateOrRange.end)this.dispatch({type:"CHANGE_VIEW_TYPE",viewType}),this.dispatch({type:"SET_OPTION",optionName:"visibleRange",rawOptionValue:dateOrRange});else{let{dateEnv}=this.getCurrentData();this.dispatch({type:"CHANGE_VIEW_TYPE",viewType,dateMarker:dateEnv.createMarker(dateOrRange)})}else this.dispatch({type:"CHANGE_VIEW_TYPE",viewType})})}zoomTo(dateMarker,viewType){let state=this.getCurrentData(),spec;viewType=viewType||"day",spec=state.viewSpecs[viewType]||this.getUnitViewSpec(viewType),this.unselect(),spec?this.dispatch({type:"CHANGE_VIEW_TYPE",viewType:spec.type,dateMarker}):this.dispatch({type:"CHANGE_DATE",dateMarker})}getUnitViewSpec(unit){let{viewSpecs,toolbarConfig}=this.getCurrentData(),viewTypes=[].concat(toolbarConfig.header?toolbarConfig.header.viewsWithButtons:[],toolbarConfig.footer?toolbarConfig.footer.viewsWithButtons:[]),i,spec;for(let viewType in viewSpecs)viewTypes.push(viewType);for(i=0;i<viewTypes.length;i+=1)if(spec=viewSpecs[viewTypes[i]],spec&&spec.singleUnit===unit)return spec;return null}prev(){this.unselect(),this.dispatch({type:"PREV"})}next(){this.unselect(),this.dispatch({type:"NEXT"})}prevYear(){let state=this.getCurrentData();this.unselect(),this.dispatch({type:"CHANGE_DATE",dateMarker:state.dateEnv.addYears(state.currentDate,-1)})}nextYear(){let state=this.getCurrentData();this.unselect(),this.dispatch({type:"CHANGE_DATE",dateMarker:state.dateEnv.addYears(state.currentDate,1)})}today(){let state=this.getCurrentData();this.unselect(),this.dispatch({type:"CHANGE_DATE",dateMarker:state.nowManager.getDateMarker()})}gotoDate(zonedDateInput){let state=this.getCurrentData();this.unselect(),this.dispatch({type:"CHANGE_DATE",dateMarker:state.dateEnv.createMarker(zonedDateInput)})}incrementDate(deltaInput){let state=this.getCurrentData(),delta=createDuration(deltaInput);delta&&(this.unselect(),this.dispatch({type:"CHANGE_DATE",dateMarker:state.dateEnv.add(state.currentDate,delta)}))}getDate(){let state=this.getCurrentData();return state.dateEnv.toDate(state.currentDate)}formatDate(d,formatter){let{dateEnv}=this.getCurrentData(),dateMeta=dateEnv.createMarkerMeta(d);return joinDateTimeFormatParts(dateEnv.formatToParts(dateMeta.marker,createFormatter(formatter),{instantMs:dateMeta.instantMs}))}formatRange(d0,d1,settings){let{dateEnv}=this.getCurrentData(),startMeta=dateEnv.createMarkerMeta(d0),endMeta=dateEnv.createMarkerMeta(d1);return joinDateTimeFormatParts(dateEnv.formatRangeToParts(startMeta.marker,endMeta.marker,createFormatter(settings),{isEndExclusive:settings.isEndExclusive,startInstantMs:startMeta.instantMs,endInstantMs:endMeta.instantMs}))}formatIso(d,omitTime){let{dateEnv}=this.getCurrentData();return dateEnv.formatIso(dateEnv.createMarker(d),{omitTime})}select(dateOrObj,endDate){let selectionInput;endDate==null?dateOrObj.start!=null?selectionInput=dateOrObj:selectionInput={start:dateOrObj,end:null}:selectionInput={start:dateOrObj,end:endDate};let state=this.getCurrentData(),selection=parseDateSpan(selectionInput,state.dateEnv,createDuration({days:1}));selection&&(this.dispatch({type:"SELECT_DATES",selection}),triggerDateSelect(selection,null,state))}unselect(pev){let state=this.getCurrentData();state.dateSelection&&(this.dispatch({type:"UNSELECT_DATES"}),triggerDateUnselect(pev,state))}addEvent(eventInput,sourceInput){if(eventInput instanceof EventImpl){let def=eventInput._def,instance=eventInput._instance;return this.getCurrentData().eventStore.defs[def.defId]||(this.dispatch({type:"ADD_EVENTS",eventStore:eventTupleToStore({def,instance})}),this.triggerEventAdd(eventInput)),eventInput}let state=this.getCurrentData(),eventSource;if(sourceInput instanceof EventSourceImpl)eventSource=sourceInput.internalEventSource;else if(typeof sourceInput=="boolean")sourceInput&&([eventSource]=hashValuesToArray(state.eventSources));else if(sourceInput!=null){let sourceApi=this.getEventSourceById(sourceInput);if(!sourceApi)return warn(`Unknown event source ID \`${sourceInput}\`.`),null;eventSource=sourceApi.internalEventSource}let tuple=parseEvent(eventInput,eventSource,state,!1);if(tuple){let newEventApi=new EventImpl(state,tuple.def,tuple.def.recurringDef?null:tuple.instance);return this.dispatch({type:"ADD_EVENTS",eventStore:eventTupleToStore(tuple)}),this.triggerEventAdd(newEventApi),newEventApi}return null}triggerEventAdd(eventApi){let{emitter}=this.getCurrentData();emitter.trigger("eventAdd",{event:eventApi,relatedEvents:[],revert:()=>{this.dispatch({type:"REMOVE_EVENTS",eventStore:eventApiToStore(eventApi)})}})}getEventById(id){let state=this.getCurrentData(),{defs,instances}=state.eventStore;id=String(id);for(let defId in defs){let def=defs[defId];if(def.publicId===id){if(def.recurringDef)return new EventImpl(state,def,null);for(let instanceId in instances){let instance=instances[instanceId];if(instance.defId===def.defId)return new EventImpl(state,def,instance)}}}return null}getEvents(){let currentData=this.getCurrentData();return buildEventApis(currentData.eventStore,currentData)}removeAllEvents(){this.dispatch({type:"REMOVE_ALL_EVENTS"})}getEventSources(){let state=this.getCurrentData(),sourceHash=state.eventSources,sourceApis=[];for(let internalId in sourceHash)sourceApis.push(new EventSourceImpl(state,sourceHash[internalId]));return sourceApis}getEventSourceById(id){let state=this.getCurrentData(),sourceHash=state.eventSources;id=String(id);for(let sourceId in sourceHash)if(sourceHash[sourceId].publicId===id)return new EventSourceImpl(state,sourceHash[sourceId]);return null}addEventSource(sourceInput){let state=this.getCurrentData();if(sourceInput instanceof EventSourceImpl)return state.eventSources[sourceInput.internalEventSource.sourceId]||this.dispatch({type:"ADD_EVENT_SOURCES",sources:[sourceInput.internalEventSource]}),sourceInput;let eventSource=parseEventSource(sourceInput,state);return eventSource?(this.dispatch({type:"ADD_EVENT_SOURCES",sources:[eventSource]}),new EventSourceImpl(state,eventSource)):null}removeAllEventSources(){this.dispatch({type:"REMOVE_ALL_EVENT_SOURCES"})}refetchEvents(){this.dispatch({type:"FETCH_EVENT_SOURCES",isRefetch:!0})}scrollToTime(timeInput){let time=createDuration(timeInput);time&&this.trigger("_timeScrollRequest",time)}getButtonState(){let currentData=this.getCurrentData(),{toolbarProps}=currentData,options=currentData.calendarOptions,buttonConfigs=options.buttons||{},viewSpecs=currentData.viewSpecs,currentUnit=currentData.viewSpec.singleUnit,currentHintOrdinal=[currentUnit?getSingleUnitText(currentUnit,options):"",currentUnit],buttonState={today:{text:options.todayText,hint:formatWithOrdinals(options.todayHint,currentHintOrdinal,options.todayText),isDisabled:!toolbarProps.isTodayEnabled},prev:{text:options.prevText,hint:formatWithOrdinals(options.prevHint,currentHintOrdinal,options.prevText),isDisabled:!toolbarProps.isPrevEnabled},next:{text:options.nextText,hint:formatWithOrdinals(options.nextHint,currentHintOrdinal,options.nextText),isDisabled:!toolbarProps.isNextEnabled},prevYear:{text:options.prevYearText,hint:formatWithOrdinals(options.prevHint,[options.yearText,"year"],options.prevYearText),isDisabled:!1},nextYear:{text:options.prevYearText,hint:formatWithOrdinals(options.nextHint,[options.yearText,"year"],options.nextYearText),isDisabled:!1}};for(let viewSpecName in viewSpecs){let viewSpec=viewSpecs[viewSpecName],{singleUnit}=viewSpec,buttonTextKey=viewSpec.optionDefaults.buttonTextKey,buttonText=buttonConfigs[viewSpecName]?.text||(buttonTextKey?options[buttonTextKey]:"")||(singleUnit?getSingleUnitText(singleUnit,options):"")||viewSpecName,buttonHint=formatWithOrdinals(options.viewHint,[buttonText,viewSpecName],buttonText);buttonState[viewSpecName]={text:buttonText,hint:buttonHint}}return buttonState}};function getSingleUnitText(singleUnit,options){return options[singleUnit+"TextLong"]||options[singleUnit+"Text"]}var CalendarMediaRoot=class extends Component2{constructor(){super(...arguments),this.state={forPrint:!1},this.handleBeforePrint=()=>{flushSyncWithSizeBatching(()=>{this.setState({forPrint:!0})})},this.handleAfterPrint=()=>{this.setState({forPrint:!1})}}render(){return this.props?.children(this.state.forPrint)}componentDidMount(){let{props}=this,{emitter}=props;emitter.on("_beforeprint",this.handleBeforePrint),emitter.on("_afterprint",this.handleAfterPrint)}componentWillUnmount(){let{props}=this,{emitter}=props;emitter.off("_beforeprint",this.handleBeforePrint),emitter.off("_afterprint",this.handleAfterPrint)}};function computeRootClassName(options,forPrint){let borderlessX=options.borderlessX??options.borderless,borderlessTop=options.borderlessTop??options.borderless,borderlessBottom=options.borderlessBottom??options.borderless,calendarDisplayData={borderlessX:!!borderlessX,borderlessTop:!!borderlessTop,borderlessBottom:!!borderlessBottom};return joinClassNames(generateClassName(options.class,calendarDisplayData),generateClassName(options.className,calendarDisplayData),classNames.borderBoxRoot,classNames.isolate,classNames.flexCol,forPrint?classNames.calendarPrintRoot:classNames.calendarScreenRoot)}var ButtonIcon=class extends BaseComponent{render(){let{contentGenerator,className}=this.props;if(contentGenerator)return jsx9(ContentContainer,{tag:"span",style:{display:"contents"},attrs:{"aria-hidden":!0},renderProps:{},generatorName:void 0,customGenerator:contentGenerator});if(className!==void 0)return jsx9("span",{"aria-hidden":!0,className})}},ToolbarSection=class extends BaseComponent{render(){let{props}=this,{options}=this.context,children=props.widgetGroups.map(widgetGroup=>this.renderWidgetGroup(widgetGroup));return createElement3("div",{className:generateClassName(options.toolbarSectionClass,{name:props.name})},...children)}renderWidgetGroup(widgetGroup){let{props,context}=this,{options}=context,children=[],isOnlyButtons=!0,isOnlyView=!0;for(let widget of widgetGroup){let{name,isView}=widget;name==="title"?isOnlyButtons=!1:isView||(isOnlyView=!1)}for(let widget of widgetGroup){let{name,customElement,buttonHint}=widget;if(name==="title")children.push(jsx9("div",{role:"heading","aria-level":options.headingLevel,id:props.titleId,className:joinClassNames(options.toolbarTitleClass),children:props.title}));else if(customElement)children.push(jsx9(ContentContainer,{tag:"span",style:{display:"contents"},renderProps:{},generatorName:void 0,customGenerator:customElement}));else{let isSelected=name===props.selectedButton,isDisabled=!props.isTodayEnabled&&name==="today"||!props.isPrevEnabled&&name==="prev"||!props.isNextEnabled&&name==="next",buttonDisplay=widget.buttonDisplay??options.buttonDisplay;buttonDisplay==="auto"&&(buttonDisplay=widget.buttonIconContent||widget.buttonIconClass?"icon":"text");let iconNode;buttonDisplay!=="text"&&(iconNode=jsx9(ButtonIcon,{className:widget.buttonIconClass,contentGenerator:widget.buttonIconContent}));let inGroup=widgetGroup.length>1&&isOnlyButtons,buttonGroup=inGroup?{hasSelection:isOnlyView}:null,renderProps={name,text:widget.buttonText,isPrimary:widget.buttonIsPrimary,isSelected,isDisabled,isIconOnly:buttonDisplay==="icon",buttonGroup};children.push(jsx9(ContentContainer,{tag:"button",attrs:{type:"button",disabled:isDisabled,...isOnlyButtons&&isOnlyView?{role:"tab","aria-selected":isSelected}:{"aria-pressed":isSelected},"aria-label":typeof buttonHint=="function"?buttonHint(props.navUnit):buttonHint,onClick:widget.buttonClick},className:joinClassNames(generateClassName(options.buttonClass,renderProps),!isDisabled&&classNames.cursorPointer,inGroup&&joinClassNames(isSelected?classNames.z1:classNames.z0,classNames.focusZ2)),renderProps,generatorName:void 0,classNameGenerator:widget.buttonClass,didMount:widget.buttonDidMount,willUnmount:widget.buttonWillUnmount,children:()=>buttonDisplay==="text"?widget.buttonText:buttonDisplay==="icon"?iconNode:buttonDisplay==="icon-text"?jsxs7(Fragment5,{children:[iconNode,widget.buttonText]}):jsxs7(Fragment5,{children:[widget.buttonText,iconNode]})}))}}return children.length>1?createElement3("div",{role:isOnlyButtons&&isOnlyView?"tablist":void 0,"aria-label":isOnlyButtons&&isOnlyView?options.viewChangeHint:void 0,className:joinClassNames(generateClassName(options.buttonGroupClass,{hasSelection:isOnlyView}),classNames.isolate)},...children):children[0]}},Toolbar=class extends BaseComponent{render(){let{props}=this,options=this.context.options,{sectionWidgets}=props.model,{borderlessX,borderlessTop,borderlessBottom}=computeViewBorderless(options),toolbarClassOption=props.isHeader?options.headerToolbarClass:options.footerToolbarClass;return jsxs7("div",{className:joinClassNames(generateClassName(toolbarClassOption,{borderlessX,borderlessTop,borderlessBottom}),generateClassName(options.toolbarClass,{borderlessX,borderlessTop,borderlessBottom})),children:[this.renderSection("start",sectionWidgets.start),this.renderSection("center",sectionWidgets.center),this.renderSection("end",sectionWidgets.end)]})}renderSection(name,widgetGroups){let{props}=this;return jsx9(ToolbarSection,{name,widgetGroups,title:props.title,titleId:props.titleId,navUnit:props.navUnit,selectedButton:props.selectedButton,isTodayEnabled:props.isTodayEnabled,isPrevEnabled:props.isPrevEnabled,isNextEnabled:props.isNextEnabled},name)}},EventClicking=class extends Interaction{constructor(settings){super(settings),this.handleSegClick=(ev,segEl)=>{let{component}=this,{context}=component,eventRange=getElEventRange(segEl);eventRange&&component.isValidSegDownEl(ev.target)&&context.emitter.trigger("eventClick",{el:segEl,event:new EventImpl(component.context,eventRange.def,eventRange.instance),jsEvent:ev,view:context.viewApi})},this.destroy=listenBySelector(settings.el,"click",`.${classNames.internalEvent}`,this.handleSegClick)}},EventHovering=class extends Interaction{constructor(settings){super(settings),this.handleEventElRemove=el=>{el===this.currentSegEl&&this.handleSegLeave(null,this.currentSegEl)},this.handleSegEnter=(ev,segEl)=>{getElEventRange(segEl)&&(this.currentSegEl=segEl,this.triggerEvent("eventMouseEnter",ev,segEl))},this.handleSegLeave=(ev,segEl)=>{this.currentSegEl&&(this.currentSegEl=null,this.triggerEvent("eventMouseLeave",ev,segEl))},this.removeHoverListeners=listenToHoverBySelector(settings.el,`.${classNames.internalEvent}`,this.handleSegEnter,this.handleSegLeave)}destroy(){this.removeHoverListeners()}triggerEvent(publicEvName,ev,segEl){let{component}=this,{context}=component,eventRange=getElEventRange(segEl);(!ev||component.isValidSegDownEl(ev.target))&&context.emitter.trigger(publicEvName,{el:segEl,event:new EventImpl(context,eventRange.def,eventRange.instance),jsEvent:ev,view:context.viewApi})}},CalendarInner=class extends PureComponent{constructor(){super(...arguments),this.buildViewContext=memoize2(buildViewContext),this.buildViewPropTransformers=memoize2(buildViewPropTransformers),this.interactionsStore={},this.calendarInteractions=[],this.registerInteractiveComponent=(component,settingsInput)=>{let settings=parseInteractionSettings(component,settingsInput),interactionClasses=[EventClicking,EventHovering];settingsInput.disableHits||(interactionClasses=interactionClasses.concat(this.props.pluginHooks.componentInteractions));let interactions=interactionClasses.map(TheInteractionClass=>new TheInteractionClass(settings));this.interactionsStore[component.uid]=interactions,interactionSettingsStore[component.uid]=settings},this.unregisterInteractiveComponent=component=>{let listeners=this.interactionsStore[component.uid];if(listeners){for(let listener of listeners)listener.destroy();delete this.interactionsStore[component.uid]}delete interactionSettingsStore[component.uid]}}get viewTitleId(){return this.props.baseId+"title"}render(){let{props}=this,{toolbarConfig,options}=props,viewHeight,viewHeightLiquid=!1,viewAspectRatio;props.forPrint||getIsHeightAuto(options)||(options.height!=null?viewHeightLiquid=!0:options.contentHeight!=null?viewHeight=options.contentHeight:viewAspectRatio=Math.max(options.aspectRatio,.5));let viewContext=this.buildViewContext(props.viewSpec,props.viewApi,props.options,props.dateProfileGenerator,props.dateEnv,props.nowManager,props.pluginHooks,props.dispatch,props.getCurrentData,props.emitter,props.calendarApi,props.baseId,this.registerInteractiveComponent,this.unregisterInteractiveComponent);return jsxs7(ViewContextType.Provider,{value:viewContext,children:[toolbarConfig.header&&jsx9(Toolbar,{model:toolbarConfig.header,isHeader:!0,titleId:this.viewTitleId,...props.toolbarProps}),jsxs7("div",{className:joinClassNames(classNames.flexCol,classNames.rel,classNames.overflowAnchorNone,classNames.minHeight0,viewHeightLiquid&&classNames.liquid),style:{height:viewHeight,aspectRatio:viewAspectRatio!=null?String(viewAspectRatio):void 0},children:[this.renderView(joinClassNames((viewHeightLiquid||viewHeight)&&classNames.liquid,viewAspectRatio!=null&&classNames.fill,classNames.internalView)),this.buildAppendContent()]}),toolbarConfig.footer&&jsx9(Toolbar,{model:toolbarConfig.footer,isHeader:!1,...props.toolbarProps})]})}renderView(className){let{props}=this,{pluginHooks,viewSpec,toolbarConfig,toolbarProps}=props,viewProps={className,dateProfile:props.dateProfile,businessHours:props.businessHours,eventStore:props.renderableEventStore,eventUiBases:props.eventUiBases,dateSelection:props.dateSelection,eventSelection:props.eventSelection,eventDrag:props.eventDrag,eventResize:props.eventResize,forPrint:props.forPrint,labelId:toolbarConfig.header&&toolbarConfig.header.hasTitle?this.viewTitleId:void 0,labelStr:toolbarConfig.header&&toolbarConfig.header.hasTitle?void 0:toolbarProps.title},transformers=this.buildViewPropTransformers(pluginHooks.viewPropsTransformers),contentProps={...props,toolbarProps,forPrint:props.forPrint};for(let transformer of transformers)Object.assign(viewProps,transformer.transform(viewProps,contentProps));let ViewComponent=viewSpec.component;return jsx9(ViewComponent,{...viewProps})}buildAppendContent(){let{props}=this;return jsx9(Fragment5,{children:props.pluginHooks.viewContainerAppends.map((buildAppendContent,i)=>jsx9(Fragment$1,{children:buildAppendContent(props)},i))})}componentDidMount(){let{props}=this;this.calendarInteractions=props.pluginHooks.calendarInteractions.map(CalendarInteractionClass=>new CalendarInteractionClass(props));let{propSetHandlers}=props.pluginHooks;for(let propName in propSetHandlers)propSetHandlers[propName](props[propName],props);for(let callback of props.pluginHooks.contextInit)callback(props)}componentDidUpdate(prevProps){let{props}=this,{propSetHandlers}=props.pluginHooks;for(let propName in propSetHandlers)props[propName]!==prevProps[propName]&&propSetHandlers[propName](props[propName],props)}componentWillUnmount(){let{props}=this;for(let interaction of this.calendarInteractions)interaction.destroy();this.calendarInteractions=[],props.emitter.trigger("_unmount")}};function buildViewPropTransformers(theClasses){return theClasses.map(TheClass=>new TheClass)}var Calendar=forwardRef2((props,ref)=>{let baseId=useStableId(props.id),[_revision,setRevision]=useState4("");function handleDataChange(_data,actions){(needsSyncRender(actions)?flushSync2:runNormal)(()=>{setRevision(guid())})}let[calendarApi]=useState4(()=>new CalendarApiImpl),[calendarDataManager]=useState4(()=>new CalendarDataManager({calendarApi,onDataChange:handleDataChange}));useEffect3(()=>()=>{calendarDataManager.destroy()},[]),useImperativeHandle(ref,()=>({getApi:()=>calendarApi}),[]);let data=calendarDataManager.update(props);return jsx10(CalendarMediaRoot,{emitter:data.emitter,children:forPrint=>{let options=data.calendarOptions,isRtl=options.direction==="rtl",className=computeRootClassName(options,forPrint);return jsx10("div",{dir:isRtl?"rtl":void 0,className,style:{height:options.height},"data-color-scheme":options.colorScheme||void 0,children:jsx10(CalendarInner,{...data,baseId,forPrint})})}})});function needsSyncRender(actions){for(let action of actions)if(action.type==="SET_EVENT_DRAG"||action.type==="UNSET_EVENT_DRAG"||action.type==="SET_EVENT_RESIZE"||action.type==="UNSET_EVENT_RESIZE"||action.type==="MERGE_EVENTS")return!0;return!1}function runNormal(f){f()}var warnedStableId=!1;function useStableId(fallbackId){if(React.useId)return React.useId();let[uid]=useState4(()=>guid());return fallbackId?fallbackId+":":(warnedStableId||(warnedStableId=!0,warn("Missing `id` prop. Provide one for better SSR support in React 17.")),`fc:${uid}:`)}function useCalendarController(){let handleDateChange=useCallback7(()=>{setControllerWrap({controller:controllerWrap.controller})},[]),[controllerWrap,setControllerWrap]=useState5(()=>({controller:new CalendarController(handleDateChange)}));return controllerWrap.controller}import{jsx as jsx14}from"react/jsx-runtime";import{Component as Component3}from"react";import{jsx as jsx11,jsxs as jsxs8,Fragment as Fragment6}from"react/jsx-runtime";function getAppendableRoot(el){let root=el.getRootNode();return root instanceof Document?root.body||root.documentElement:root}function computeElIsRtl(el){return getComputedStyle(el).direction==="rtl"}var PIXEL_PROP_RE=/(top|left|right|bottom|width|height)$/i;function applyStyle(el,props){for(let propName in props)applyStyleProp(el,propName,props[propName])}function applyStyleProp(el,name,val){val==null?el.style[name]="":typeof val=="number"&&PIXEL_PROP_RE.test(name)?el.style[name]=`${val}px`:el.style[name]=val}function getEventTargetViaRoot(ev){return ev.composedPath?.()[0]??ev.target}var NowTimer=class extends Component3{constructor(props,context){super(props,context),this.handleChange=()=>{this.forceUpdate()},this.runner=new NowTimerRunner(this.handleChange)}render(){let{props,context}=this,{nowDate,nowMs,todayRange}=this.runner.update({nowManager:context.nowManager,unit:props.unit,unitValue:props.unitValue,nowIndicatorSnap:context.options.nowIndicatorSnap,dateEnv:context.dateEnv});return props.children(nowDate,todayRange,nowMs)}componentWillUnmount(){this.runner.destroy()}};NowTimer.contextType=ViewContextType;var FULL_DATE_FORMAT=createFormatter({year:"numeric",month:"long",day:"numeric"}),WEEK_FORMAT=createFormatter({week:"long"}),WEEKDAY_ONLY_FORMAT=createFormatter({weekday:"long"});function findWeekdayText(parts){for(let part of parts)if(part.type==="weekday")return part.value;return""}function findDayNumberText(parts){for(let part of parts)if(part.type==="day")return part.value;return""}function findMonthText(parts){for(let part of parts)if(part.type==="month")return part.value;return""}function buildDateStr(context,dateMarker,viewType="day"){return joinDateTimeFormatParts(context.dateEnv.formatToParts(dateMarker,viewType==="week"?WEEK_FORMAT:FULL_DATE_FORMAT))}function buildNavLinkAttrs(context,dateMarker,viewType="day",dateStr=buildDateStr(context,dateMarker,viewType),isTabbable=!0){let{dateEnv,options,calendarApi}=context,zonedDate=dateEnv.toDate(dateMarker),handleInteraction=ev=>{let customAction=viewType==="day"?options.navLinkDayClick:viewType==="week"?options.navLinkWeekClick:null;typeof customAction=="function"?customAction.call(calendarApi,dateEnv.toDate(dateMarker),ev):(typeof customAction=="string"&&(viewType=customAction),calendarApi.zoomTo(dateMarker,viewType))};return{role:"link","aria-label":formatWithOrdinals(options.navLinkHint,[dateStr,zonedDate],dateStr),className:joinClassNames(options.navLinkClass,classNames.cursorPointer,classNames.internalNavLink),...isTabbable?createAriaClickAttrs(handleInteraction):{onClick:handleInteraction}}}function getDateMeta(dateMarker,dateEnv,dateProfile,todayRange,nowDate){let isDisabled=!!(dateProfile&&(!dateProfile.activeRange||!rangeContainsMarker(dateProfile.activeRange,dateMarker)));return{date:dateEnv.toDate(dateMarker),dow:dateMarker.getUTCDay(),isDisabled,isOther:!isDisabled&&!!(dateProfile&&!rangeContainsMarker(dateProfile.currentRange,dateMarker)),isToday:!isDisabled&&!!(todayRange&&rangeContainsMarker(todayRange,dateMarker)),isPast:!isDisabled&&!!(nowDate?dateMarker<nowDate:todayRange&&dateMarker<todayRange.start),isFuture:!isDisabled&&!!(nowDate?dateMarker>nowDate:todayRange&&dateMarker>=todayRange.end)}}var ViewContainer=class extends BaseComponent{constructor(){super(...arguments),this.refineRenderProps=memoizeObjArg(refineRenderProps)}render(){let{props,context}=this,{options,viewSpec}=context,renderProps=this.refineRenderProps({...computeViewBorderless(options),options:{headerToolbar:options.headerToolbar,footerToolbar:options.footerToolbar},isHeightAuto:getIsHeightAuto(options),viewApi:context.viewApi});return jsx11(ContentContainer,{elRef:props.elRef,tag:props.tag||"div",attrs:props.attrs,style:props.style,className:joinClassNames(props.className,generateClassName(options.viewClass,renderProps),generateClassName(viewSpec.optionDefaults.class,renderProps),generateClassName(viewSpec.optionDefaults.className,renderProps),generateClassName(viewSpec.optionOverrides.class,renderProps),generateClassName(viewSpec.optionOverrides.className,renderProps)),renderProps,generatorName:void 0,didMount:options.didMount||options.viewDidMount,willUnmount:options.willUnmount||options.viewWillUnmount,children:()=>props.children})}};function refineRenderProps(raw){return{view:raw.viewApi,borderlessX:raw.borderlessX,borderlessTop:raw.borderlessTop,borderlessBottom:raw.borderlessBottom,options:raw.options,isHeightAuto:raw.isHeightAuto}}var DateComponent=class extends BaseComponent{constructor(){super(...arguments),this.uid=guid()}prepareHits(){}queryHit(isRtl,positionLeft,positionTop,elWidth,elHeight){return null}isValidSegDownEl(el){return!this.props.eventDrag&&!this.props.eventResize&&!el.closest(`.${classNames.internalEventMirror}`)}isValidDateDownEl(el){return!el.closest(`.${classNames.internalEvent}:not(.${classNames.internalBgEvent})`)&&!el.closest(`.${classNames.internalMoreLink}`)&&!el.closest(`.${classNames.internalNavLink}`)&&!el.closest(`.${classNames.internalPopover}`)}},DelayedRunner=class{constructor(drainedOption){this.drainedOption=drainedOption,this.isRunning=!1,this.isDirty=!1,this.pauseDepths={},this.timeoutId=0}request(delay){this.isDirty=!0,this.isPaused()||(this.clearTimeout(),delay==null?this.tryDrain():this.timeoutId=setTimeout(this.tryDrain.bind(this),delay))}pause(scope=""){let{pauseDepths}=this;pauseDepths[scope]=(pauseDepths[scope]||0)+1,this.clearTimeout()}resume(scope="",force){let{pauseDepths}=this;scope in pauseDepths&&(force?delete pauseDepths[scope]:(pauseDepths[scope]-=1,pauseDepths[scope]<=0&&delete pauseDepths[scope]),this.tryDrain())}isPaused(){return Object.keys(this.pauseDepths).length}tryDrain(){if(!this.isRunning&&!this.isPaused()){for(this.isRunning=!0;this.isDirty;)this.isDirty=!1,this.drained();this.isRunning=!1}}clear(){this.clearTimeout(),this.isDirty=!1,this.pauseDepths={}}clearTimeout(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=0)}drained(){this.drainedOption&&this.drainedOption()}},ScrollListener=class{constructor(el){this.el=el,this.emitter=new Emitter,this.isScroll=!1,this.isScrollRecent=!1,this.isWheelRecent=!1,this.isMouseDown=!1,this.isTouchDown=!1,this.isMouse=!1,this.isTouch=!1,this.isWheel=!1,this.handleScroll=()=>{this.isScrollRecent=!0,this.isMouseDown&&(this.isMouse=!0),this.isTouchDown&&(this.isTouch=!0),this.isWheelRecent&&(this.isWheel=!0),this.startScroll(),this.emitter.trigger("scroll",this.getIsDevice()),this.scrollWaiter.request(500)},this.handleScrollWait=()=>{this.isScrollRecent=!1,this.isTouchDown||this.endScroll()},this.handleWheel=()=>{this.isWheelRecent=!0,this.wheelWaiter.request(500)},this.handleWheelWait=()=>{this.isWheelRecent=!1},this.handleMouseDown=()=>{this.isMouseDown=!0},this.handleMouseUp=()=>{this.isMouseDown=!1},this.handleTouchStart=()=>{this.isTouchDown=!0},this.handleTouchEnd=()=>{this.isTouchDown=!1,this.isScrollRecent||this.endScroll()},this.wheelWaiter=new DelayedRunner(this.handleWheelWait),this.scrollWaiter=new DelayedRunner(this.handleScrollWait),el.addEventListener("scroll",this.handleScroll,{passive:!0}),el.addEventListener("wheel",this.handleWheel,{passive:!0}),el.addEventListener("mousedown",this.handleMouseDown),el.addEventListener("mouseup",this.handleMouseUp),el.addEventListener("touchstart",this.handleTouchStart,{passive:!0}),el.addEventListener("touchend",this.handleTouchEnd)}destroy(){let{el}=this;el.removeEventListener("scroll",this.handleScroll,{passive:!0}),el.removeEventListener("wheel",this.handleWheel,{passive:!0}),el.removeEventListener("mousedown",this.handleMouseDown),el.removeEventListener("mouseup",this.handleMouseUp),el.removeEventListener("touchstart",this.handleTouchStart,{passive:!0}),el.removeEventListener("touchend",this.handleTouchEnd)}startScroll(){this.isScroll||(this.isScroll=!0,this.emitter.trigger("scrollStart",this.getIsDevice()))}endScroll(){this.isScroll&&(this.scrollWaiter.clear(),this.wheelWaiter.clear(),this.isScroll=!1,this.isWheelRecent=!1,this.emitter.trigger("scrollEnd",this.getIsDevice()),this.isMouse=!1,this.isTouch=!1,this.isWheel=!1)}getIsDevice(){return this.isWheel||this.isMouse||this.isTouch}},Scroller=class extends DateComponent{constructor(){super(...arguments),this.handleEl=el=>{this.el&&(this.el=null,this._isUnmounting=!0,this.listener.destroy()),el&&(this.el=el,this._isUnmounting=!1,this.listener=new ScrollListener(el))},this.handleHRuler=el=>{this.disconnectHRuler&&(this.disconnectHRuler(),this.disconnectHRuler=void 0,this.clientWidth!==void 0&&(this.clientWidth=void 0,setRef(this.props.clientWidthRef,null))),el&&(this.disconnectHRuler=watchWidth(el,clientWidth=>{this._isUnmounting||clientWidth!==this.clientWidth&&(this.clientWidth=clientWidth,setRef(this.props.clientWidthRef,clientWidth))}))},this.handleVRuler=el=>{this.disconnectVRuler&&(this.disconnectVRuler(),this.disconnectVRuler=void 0,this.clientHeight!==void 0&&(this.clientHeight=void 0,setRef(this.props.clientHeightRef,null))),el&&(this.disconnectVRuler=watchHeight(el,clientHeight=>{if(this._isUnmounting)return;clientHeight!==this.clientHeight&&(this.clientHeight=clientHeight,setRef(this.props.clientHeightRef,clientHeight));let bottomScrollbarWidth=Math.round(this.el.getBoundingClientRect().height-clientHeight);bottomScrollbarWidth!==this.bottomScrollbarWidth&&(this.bottomScrollbarWidth=bottomScrollbarWidth,setRef(this.props.bottomScrollbarWidthRef,bottomScrollbarWidth))}))}}render(){let{props}=this,fallbackOverflow=props.horizontal||props.vertical?"hidden":"";return jsxs8("div",{ref:this.handleEl,className:joinClassNames(props.className,classNames.noPadding,classNames.rel,props.hideScrollbars&&classNames.noScrollbars,classNames.internalScroller),style:{...props.style,overflowX:props.horizontal?"auto":fallbackOverflow,overflowY:props.vertical?"auto":fallbackOverflow},children:[props.children,!!props.clientWidthRef&&jsx11("div",{ref:this.handleHRuler,className:classNames.fillTop}),!!(props.clientHeightRef||props.bottomScrollbarWidthRef)&&jsx11("div",{ref:this.handleVRuler,className:classNames.fillStart})]})}endScroll(){this.listener.endScroll()}get x(){let{el}=this;return el?getNormalizedScrollX(el):0}get y(){let{el}=this;return el?el.scrollTop:0}scrollTo({x:x2,y}){let{el}=this;el&&(y!=null&&(el.scrollTop=y),x2!=null&&setNormalizedScrollX(el,x2))}addScrollStartListener(handler){this.listener.emitter.on("scrollStart",handler)}removeScrollStartListener(handler){this.listener.emitter.off("scrollStart",handler)}addScrollEndListener(handler){this.listener.emitter.on("scrollEnd",handler)}removeScrollEndListener(handler){this.listener.emitter.off("scrollEnd",handler)}};function getNormalizedScrollX(el){let{scrollLeft}=el;return computeElIsRtl(el)?getNormalizedRtlScrollX(scrollLeft,el):scrollLeft}function setNormalizedScrollX(el,x2){let isRtl=computeElIsRtl(el);el.scrollLeft=isRtl?getNormalizedRtlScrollLeft(x2,el):x2}function getNormalizedRtlScrollX(scrollLeft,el){switch(getRtlScrollerSystem()){case"positive":return el.scrollWidth-el.clientWidth-scrollLeft;case"negative":return-scrollLeft}return scrollLeft}function getNormalizedRtlScrollLeft(x2,el){switch(getRtlScrollerSystem()){case"positive":return el.scrollWidth-el.clientWidth-x2;case"negative":return-x2}return x2}var _rtlScrollerSystem;function getRtlScrollerSystem(){return _rtlScrollerSystem||(_rtlScrollerSystem=detectRtlScrollerSystem())}function detectRtlScrollerSystem(){let el=document.createElement("div");el.style.position="absolute",el.style.top="-1000px",el.style.width="100px",el.style.height="100px",el.style.overflow="scroll",el.style.direction="rtl";let innerEl=document.createElement("div");innerEl.style.width="200px",innerEl.style.height="200px",el.appendChild(innerEl),document.body.appendChild(el);let system;return el.scrollLeft>0?system="positive":(el.scrollLeft=50,el.scrollLeft>0?system="reverse":system="negative"),el.remove(),system}var StandardEvent=class extends BaseComponent{constructor(){super(...arguments),this.buildPublicEvent=memoize2((context,eventDef,eventInstance)=>new EventImpl(context,eventDef,eventInstance)),this.handleEl=el=>{this.el=el,setRef(this.props.elRef,el),el&&setElEventRange(el,this.props.eventRange)}}render(){let{props,context}=this,{options}=context,{eventRange}=props,eventUi=eventRange.ui,timeFormat=options.eventTimeFormat||props.defaultTimeFormat,timeText=props.forcedTimeText??buildEventRangeTimeText(timeFormat,eventRange,props.slicedStart,props.slicedEnd,props.isStart,props.isEnd,context,props.defaultDisplayEventTime,props.defaultDisplayEventEnd),[tag,attrs,isInteractive]=getEventTagAndAttrs(eventRange,context),eventApi=this.buildPublicEvent(context,eventRange.def,eventRange.instance),isDraggable=!props.disableDragging&&computeEventRangeDraggable(eventRange,context),isBlock=/row|column/.test(props.display),subcontentRenderProps={event:eventApi,isNarrow:props.isNarrow||!1,isShort:props.isShort||!1,timeText},renderProps={event:eventApi,view:context.viewApi,timeText,color:eventUi.color||options.eventColor,contrastColor:eventUi.contrastColor||options.eventContrastColor,isDraggable,isStartResizable:!props.disableResizing&&props.isStart&&eventUi.durationEditable&&options.eventResizableFromStart,isEndResizable:!props.disableResizing&&props.isEnd&&eventUi.durationEditable,isMirror:props.isMirror,isStart:!!props.isStart,isEnd:!!props.isEnd,isFirst:!!props.isFirst,isLast:!!props.isLast,isPast:!!props.isPast,isFuture:!!props.isFuture,isToday:!!props.isToday,isSelected:!!props.isSelected,isDragging:!!props.isDragging,isResizing:!!props.isResizing,isInteractive,isNarrow:props.isNarrow||!1,isShort:props.isShort||!1,level:props.level||0,timeClass:joinClassNames(generateClassName(options.eventTimeClass,subcontentRenderProps),isBlock&&generateClassName(options.blockEventTimeClass,subcontentRenderProps),props.display==="row"&&generateClassName(options.rowEventTimeClass,subcontentRenderProps),props.display==="column"&&generateClassName(options.columnEventTimeClass,subcontentRenderProps),props.display==="list-item"&&generateClassName(options.listItemEventTimeClass,subcontentRenderProps)),titleClass:joinClassNames(generateClassName(options.eventTitleClass,subcontentRenderProps),isBlock&&generateClassName(options.blockEventTitleClass,subcontentRenderProps),props.display==="row"&&generateClassName(options.rowEventTitleClass,subcontentRenderProps),props.display==="column"&&generateClassName(options.columnEventTitleClass,subcontentRenderProps),props.display==="list-item"&&generateClassName(options.listItemEventTitleClass,subcontentRenderProps),props.display==="row"&&options.rowEventTitleSticky&&classNames.stickyS,props.display==="column"&&options.columnEventTitleSticky&&classNames.stickyT),options:{eventOverlap:!!options.eventOverlap}},outerClassName=joinClassNames(isBlock&&generateClassName(options.blockEventClass,renderProps),props.display==="row"&&generateClassName(options.rowEventClass,renderProps),props.display==="column"&&generateClassName(options.columnEventClass,renderProps),props.display==="list-item"&&generateClassName(options.listItemEventClass,renderProps),eventUi.className,props.className,props.display==="column"?classNames.flexCol:classNames.flexRow,(eventRange.def.url||isDraggable)&&classNames.cursorPointer,classNames.internalEvent,props.isMirror&&classNames.internalEventMirror,isDraggable&&classNames.internalEventDraggable,renderProps.isSelected&&classNames.internalEventSelected,(renderProps.isStartResizable||renderProps.isEndResizable)&&classNames.internalEventResizable),beforeClassName=joinClassNames(generateClassName(options.eventBeforeClass,renderProps),isBlock&&generateClassName(options.blockEventBeforeClass,renderProps),props.display==="row"&&generateClassName(options.rowEventBeforeClass,renderProps),props.display==="column"&&generateClassName(options.columnEventBeforeClass,renderProps),props.display==="list-item"&&generateClassName(options.listItemEventBeforeClass,renderProps)),afterClassName=joinClassNames(generateClassName(options.eventAfterClass,renderProps),isBlock&&generateClassName(options.blockEventAfterClass,renderProps),props.display==="row"&&generateClassName(options.rowEventAfterClass,renderProps),props.display==="column"&&generateClassName(options.columnEventAfterClass,renderProps),props.display==="list-item"&&generateClassName(options.listItemEventAfterClass,renderProps)),innerClassName=joinClassNames(generateClassName(options.eventInnerClass,renderProps),isBlock&&generateClassName(options.blockEventInnerClass,renderProps),props.display==="row"&&generateClassName(options.rowEventInnerClass,renderProps),props.display==="column"&&generateClassName(options.columnEventInnerClass,renderProps),props.display==="list-item"&&generateClassName(options.listItemEventInnerClass,renderProps),!props.disableLiquid&&classNames.liquid),beforeContent=props.display==="row"&&options.rowEventBeforeContent,afterContent=props.display==="row"&&options.rowEventAfterContent;return jsx11(ContentContainer,{tag,attrs:{...props.attrs,...attrs,dir:props.isDragging&&options.direction==="rtl"?"rtl":void 0},className:outerClassName,style:{"--fc-event-color":renderProps.color,"--fc-event-contrast-color":renderProps.contrastColor},elRef:this.handleEl,renderProps,generatorName:"eventContent",customGenerator:options.eventContent,defaultGenerator:renderInnerContent,classNameGenerator:options.eventClass,didMount:options.eventDidMount,willUnmount:options.eventWillUnmount,children:InnerContent=>jsxs8(Fragment6,{children:[!!(renderProps.isSelected&&isBlock)&&jsx11("div",{className:props.display==="column"?classNames.hitX:classNames.hitY}),(beforeClassName||beforeContent)&&jsxs8("div",{className:joinClassNames(beforeClassName,!props.disableZindexes&&classNames.z1,renderProps.isStartResizable&&joinClassNames(props.display==="column"?classNames.cursorResizeT:classNames.cursorResizeS,classNames.internalEventResizer,classNames.internalEventResizerStart)),children:[beforeContent&&jsx11(ContentContainer,{tag:"div",style:{display:"contents"},attrs:{"aria-hidden":!0},renderProps,generatorName:void 0,customGenerator:beforeContent}),!!(renderProps.isStartResizable&&renderProps.isSelected)&&jsx11("div",{className:classNames.hit})]}),jsx11(InnerContent,{tag:"div",className:joinClassNames(innerClassName,!props.disableZindexes&&classNames.z0)}),(afterClassName||afterContent)&&jsxs8("div",{className:joinClassNames(afterClassName,!props.disableZindexes&&classNames.z1,renderProps.isEndResizable&&joinClassNames(props.display==="column"?classNames.cursorResizeB:classNames.cursorResizeE,classNames.internalEventResizer,classNames.internalEventResizerEnd)),children:[afterContent&&jsx11(ContentContainer,{tag:"div",style:{display:"contents"},attrs:{"aria-hidden":!0},renderProps,generatorName:void 0,customGenerator:afterContent}),!!(renderProps.isEndResizable&&renderProps.isSelected)&&jsx11("div",{className:classNames.hit})]})]})})}componentDidUpdate(prevProps){this.el&&this.props.eventRange!==prevProps.eventRange&&setElEventRange(this.el,this.props.eventRange)}};StandardEvent.addPropsEquality({seg:isPropsEqualShallow});function renderInnerContent(innerProps){return jsxs8(Fragment6,{children:[innerProps.timeText&&jsx11("div",{className:innerProps.timeClass,children:innerProps.timeText}),jsx11("div",{className:innerProps.titleClass,children:innerProps.event.title||jsx11(Fragment6,{children:"\xA0"})})]})}import{jsx as jsx12,jsxs as jsxs9,Fragment as Fragment7}from"react/jsx-runtime";import{createRef,Component as Component4,createElement as createElement4}from"react";import{createPortal}from"react-dom";function pointInsideRect(point,rect){return point.left>=rect.left&&point.left<rect.right&&point.top>=rect.top&&point.top<rect.bottom}function intersectRects(rect1,rect2){let res={left:Math.max(rect1.left,rect2.left),right:Math.min(rect1.right,rect2.right),top:Math.max(rect1.top,rect2.top),bottom:Math.min(rect1.bottom,rect2.bottom)};return res.left<res.right&&res.top<res.bottom?res:!1}function constrainPoint(point,rect){return{left:Math.min(Math.max(point.left,rect.left),rect.right),top:Math.min(Math.max(point.top,rect.top),rect.bottom)}}function getRectCenter(rect){return{left:(rect.left+rect.right)/2,top:(rect.top+rect.bottom)/2}}function diffPoints(point1,point2){return{left:point1.left-point2.left,top:point1.top-point2.top}}function computeEdges(el,getPadding=!1){let computedStyle=window.getComputedStyle(el),borderLeft=parseInt(computedStyle.borderLeftWidth,10)||0,borderRight=parseInt(computedStyle.borderRightWidth,10)||0,borderTop=parseInt(computedStyle.borderTopWidth,10)||0,borderBottom=parseInt(computedStyle.borderBottomWidth,10)||0,badScrollbarWidths=computeScrollbarWidthsForEl(el),scrollbarLeftRight=badScrollbarWidths.y-borderLeft-borderRight,scrollbarBottom=badScrollbarWidths.x-borderTop-borderBottom,res={borderLeft,borderRight,borderTop,borderBottom,scrollbarBottom,scrollbarLeft:0,scrollbarRight:0};return computedStyle.direction==="rtl"?res.scrollbarLeft=scrollbarLeftRight:res.scrollbarRight=scrollbarLeftRight,getPadding&&(res.paddingLeft=parseInt(computedStyle.paddingLeft,10)||0,res.paddingRight=parseInt(computedStyle.paddingRight,10)||0,res.paddingTop=parseInt(computedStyle.paddingTop,10)||0,res.paddingBottom=parseInt(computedStyle.paddingBottom,10)||0),res}function computeInnerRect(el,goWithinPadding=!1,doFromWindowViewport){let outerRect=doFromWindowViewport?el.getBoundingClientRect():computeRect(el),edges=computeEdges(el,goWithinPadding),res={left:outerRect.left+edges.borderLeft+edges.scrollbarLeft,right:outerRect.right-edges.borderRight-edges.scrollbarRight,top:outerRect.top+edges.borderTop,bottom:outerRect.bottom-edges.borderBottom-edges.scrollbarBottom};return goWithinPadding&&(res.left+=edges.paddingLeft,res.right-=edges.paddingRight,res.top+=edges.paddingTop,res.bottom-=edges.paddingBottom),res}function computeRect(el){let rect=el.getBoundingClientRect();return{left:rect.left+window.scrollX,top:rect.top+window.scrollY,right:rect.right+window.scrollX,bottom:rect.bottom+window.scrollY}}function computeClippedClientRect(el){let clippingParents=getClippingParents(el),rect=el.getBoundingClientRect();for(let clippingParent of clippingParents){let intersection=intersectRects(rect,clippingParent.getBoundingClientRect());if(intersection)rect=intersection;else return null}return rect}function getClippingParents(el){let parents=[];for(;el instanceof HTMLElement;){let computedStyle=window.getComputedStyle(el);if(computedStyle.position==="fixed")break;/(auto|scroll)/.test(computedStyle.overflow+computedStyle.overflowY+computedStyle.overflowX)&&parents.push(el),el=el.parentNode}return parents}function computeScrollbarWidthsForEl(el){return{x:el.offsetHeight-el.clientHeight,y:el.offsetWidth-el.clientWidth}}var Slicer=class{constructor(){this.sliceBusinessHours=memoize2(this._sliceBusinessHours),this.sliceDateSelection=memoize2(this._sliceDateSpan),this.sliceEventStore=memoize2(this._sliceEventStore),this.sliceEventDrag=memoize2(this._sliceInteraction),this.sliceEventResize=memoize2(this._sliceInteraction),this.forceDayIfListItem=!1}intersectDateSpan(dateSpan,activeRange,...extraArgs){let activeDateSpanRange=intersectRanges(dateSpan.range,activeRange);if(activeDateSpanRange){let slicedDateSpan={...dateSpan,range:activeDateSpanRange};return activeDateSpanRange.start.valueOf()!==dateSpan.range.start.valueOf()&&delete slicedDateSpan.instantStartMs,activeDateSpanRange.end.valueOf()!==dateSpan.range.end.valueOf()&&delete slicedDateSpan.instantEndMs,slicedDateSpan}return null}sliceDateSpan(dateSpan,...extraArgs){return this.sliceRange(dateSpan.range,...extraArgs)}sliceProps(props,dateProfile,nextDayThreshold,context,...extraArgs){let{eventUiBases}=props,eventSegs=this.sliceEventStore(props.eventStore,eventUiBases,dateProfile,nextDayThreshold,...extraArgs);return{dateSelectionSegs:this.sliceDateSelection(props.dateSelection,dateProfile,nextDayThreshold,eventUiBases,context,...extraArgs),businessHourSegs:this.sliceBusinessHours(props.businessHours,dateProfile,nextDayThreshold,context,...extraArgs),fgEventSegs:eventSegs.fg,bgEventSegs:eventSegs.bg,eventDrag:this.sliceEventDrag(props.eventDrag,eventUiBases,dateProfile,nextDayThreshold,...extraArgs),eventResize:this.sliceEventResize(props.eventResize,eventUiBases,dateProfile,nextDayThreshold,...extraArgs),eventSelection:props.eventSelection}}sliceNowDate(date,dateProfile,nextDayThreshold,context,...extraArgs){return this._sliceDateSpan({range:{start:date,end:addMs(date,1)},allDay:!1},dateProfile,nextDayThreshold,{},context,...extraArgs)}_sliceBusinessHours(businessHours,dateProfile,nextDayThreshold,context,...extraArgs){return businessHours?this._sliceEventStore(expandRecurring(businessHours,computeActiveRange(dateProfile,!!nextDayThreshold),context),{},dateProfile,nextDayThreshold,...extraArgs).bg:[]}_sliceEventStore(eventStore,eventUiBases,dateProfile,nextDayThreshold,...extraArgs){if(eventStore){let rangeRes=sliceEventStore(eventStore,eventUiBases,computeActiveRange(dateProfile,!!nextDayThreshold),nextDayThreshold);return{bg:this.sliceEventRanges(rangeRes.bg,extraArgs),fg:this.sliceEventRanges(rangeRes.fg,extraArgs)}}return{bg:[],fg:[]}}_sliceInteraction(interaction,eventUiBases,dateProfile,nextDayThreshold,...extraArgs){if(!interaction)return null;let rangeRes=sliceEventStore(interaction.mutatedEvents,eventUiBases,computeActiveRange(dateProfile,!!nextDayThreshold),nextDayThreshold);return{segs:this.sliceEventRanges(rangeRes.fg,extraArgs),affectedInstances:interaction.affectedEvents.instances,isEvent:interaction.isEvent}}_sliceDateSpan(dateSpan,dateProfile,nextDayThreshold,eventUiBases,context,...extraArgs){if(!dateSpan)return[];let activeRange=computeActiveRange(dateProfile,!!nextDayThreshold),slicedDateSpan=this.intersectDateSpan(dateSpan,activeRange,...extraArgs);if(slicedDateSpan){dateSpan=slicedDateSpan;let eventRange=fabricateEventRange(dateSpan,eventUiBases,context),segs=this.sliceDateSpan(dateSpan,...extraArgs);for(let seg of segs)seg.eventRange=eventRange;return segs}return[]}sliceEventRanges(eventRanges,extraArgs){let segs=[];for(let eventRange of eventRanges)segs.push(...this.sliceEventRange(eventRange,extraArgs));return segs}sliceEventRange(eventRange,extraArgs){let dateRange=eventRange.range;this.forceDayIfListItem&&eventRange.ui.display==="list-item"&&(dateRange={start:dateRange.start,end:addDays4(dateRange.start,1)});let segs=this.sliceRange(dateRange,...extraArgs);for(let seg of segs)seg.eventRange=eventRange,seg.isStart=eventRange.isStart&&seg.isStart,seg.isEnd=eventRange.isEnd&&seg.isEnd;return segs}};function computeActiveRange(dateProfile,isComponentAllDay){let range=dateProfile.activeRange;return isComponentAllDay?range:{start:addMs(range.start,dateProfile.slotMinTime.milliseconds),end:addMs(range.end,dateProfile.slotMaxTime.milliseconds-864e5)}}var DayTableModel=class{constructor(daySeries,breakOnWeeks,dateEnv,majorUnit="",activeRange){this.daySeries=daySeries,this.dateEnv=dateEnv,this.majorUnit=majorUnit,this.activeRange=activeRange;let{dates}=daySeries,daysPerRow,firstDay,rowCount;if(breakOnWeeks){for(firstDay=dates[0].getUTCDay(),daysPerRow=1;daysPerRow<dates.length&&dates[daysPerRow].getUTCDay()!==firstDay;daysPerRow+=1);rowCount=Math.ceil(dates.length/daysPerRow)}else rowCount=1,daysPerRow=dates.length;this.rowCount=rowCount,this.colCount=daysPerRow,this.cellRows=this.buildCells(),this.headerDates=this.buildHeaderDates()}buildCells(){let rows=[];for(let row=0;row<this.rowCount;row+=1){let cells=[];for(let col=0;col<this.colCount;col+=1)cells.push(this.buildCell(row,col));rows.push(cells)}return rows}buildCell(row,col){let date=this.daySeries.dates[row*this.colCount+col];return{key:date.toISOString(),date,isMajor:this.cellIsMajor(date),isDisabled:this.activeRange===null||this.activeRange!==void 0&&!rangeContainsMarker(this.activeRange,date)}}cellIsMajor(dateMarker){return this.majorUnit?isMajorUnit(dateMarker,this.majorUnit,this.dateEnv):!1}buildHeaderDates(){let dates=[];for(let col=0;col<this.colCount;col+=1)dates.push(this.cellRows[0][col].date);return dates}};function buildDayGridRanges(seriesRange,daysPerRow){let ranges=[];if(seriesRange){let{start,end}=seriesRange,index2=start;for(;index2<end;){let row=Math.floor(index2/daysPerRow),nextIndex=Math.min((row+1)*daysPerRow,end);ranges.push({row,start:index2%daysPerRow,end:(nextIndex-1)%daysPerRow+1,isStart:seriesRange.isStart&&index2===start,isEnd:seriesRange.isEnd&&nextIndex===end}),index2=nextIndex}}return ranges}var DayTableSlicer=class extends Slicer{constructor(){super(...arguments),this.forceDayIfListItem=!0}sliceRange(dateRange,dayTableModel){return buildDayGridRanges(dayTableModel.daySeries.sliceRange(dateRange),dayTableModel.colCount)}},DaySeriesSlicer=class extends Slicer{constructor(){super(...arguments),this.forceDayIfListItem=!0}sliceRange(dateRange,daySeries){return buildDayGridRanges(daySeries.sliceRange(dateRange),daySeries.cnt)}},firstSunday=new Date(2592e5);function buildDateRowConfigs(dates,datesRepDistinctDays,dateProfile,todayRange,dayHeaderFormat,context){let rowConfig=buildDateRowConfig(dates,datesRepDistinctDays,dateProfile,todayRange,dayHeaderFormat,context),majorUnit=computeMajorUnit(dateProfile,context.dateEnv);if(datesRepDistinctDays&&majorUnit!=="day")for(let dataConfig of rowConfig.dataConfigs)isMajorUnit(dataConfig.dateMarker,majorUnit,context.dateEnv)&&(dataConfig.renderProps.isMajor=!0);return[rowConfig]}function buildDateRowConfig(dateMarkers,datesRepDistinctDays,dateProfile,todayRange,dayHeaderFormat,context,colSpan,isMajorMod,totalDateCnt){return{isDateRow:!0,renderConfig:buildDateRenderConfig(dayHeaderFormat,datesRepDistinctDays,context),dataConfigs:buildDateDataConfigs(dateMarkers,datesRepDistinctDays,dateProfile,todayRange,dayHeaderFormat,context,colSpan,void 0,void 0,void 0,void 0,isMajorMod,totalDateCnt)}}function buildDateRenderConfig(dayHeaderFormat,datesRepDistinctDays,context){let{options}=context;return{generatorName:"dayHeaderContent",customGenerator:options.dayHeaderContent,classNameGenerator:options.dayHeaderClass,innerClassNameGenerator:options.dayHeaderInnerClass,didMount:options.dayHeaderDidMount,willUnmount:options.dayHeaderWillUnmount,align:options.dayHeaderAlign,sticky:options._dayHeaderSticky,dayHeaderFormat,datesRepDistinctDays}}var dowDates=[];for(let dow=0;dow<7;dow++)dowDates.push(addDays4(new Date(2592e5),dow));function buildDateDataConfigs(dateMarkers,datesRepDistinctDays,dateProfile,todayRange,dayHeaderFormat,context,colSpan=1,keyPrefix="",extraRenderProps={},extraAttrs={},className="",isMajorMod,totalDateCnt=dateMarkers.length){let{dateEnv,viewApi,options}=context;return datesRepDistinctDays?dateMarkers.map((dateMarker,i)=>{let dateMeta=getDateMeta(dateMarker,dateEnv,dateProfile,todayRange),isMajor=isMajorMod!=null&&!(i%isMajorMod),hasNavLink=options.navLinks&&!dateMeta.isDisabled&&totalDateCnt>1,renderProps={...dateMeta,...extraRenderProps,isMajor,isSticky:!1,inPopover:!1,hasNavLink,view:viewApi},fullDateStr=buildDateStr(context,dateMarker);return{key:keyPrefix+dateMarker.toUTCString(),dateMarker,renderProps,attrs:{"aria-label":fullDateStr,...dateMeta.isToday?{"aria-current":"date"}:{},"data-date":formatDayString(dateMarker),...extraAttrs},innerAttrs:hasNavLink?buildNavLinkAttrs(context,dateMarker,void 0,fullDateStr):{"aria-hidden":!0},colSpan,hasNavLink,className}}):dateMarkers.map((dateMarker,i)=>{let dow=dateMarker.getUTCDay(),normDate=addDays4(firstSunday,dow),dateMeta={date:dateEnv.toDate(dateMarker),dow,isDisabled:!1,isFuture:!1,isPast:!1,isToday:!1,isOther:!1},isMajor=isMajorMod!=null&&!(i%isMajorMod),renderProps={...dateMeta,date:dowDates[dow],isMajor,isSticky:!1,inPopover:!1,hasNavLink:!1,view:viewApi,...extraRenderProps},fullWeekDayStr=joinDateTimeFormatParts(dateEnv.formatToParts(normDate,WEEKDAY_ONLY_FORMAT));return{key:keyPrefix+String(dow),dateMarker,renderProps,attrs:{"aria-label":fullWeekDayStr,...extraAttrs},innerAttrs:{"aria-hidden":!0},colSpan,className}})}var RefMap=class{constructor(masterCallback,ignoreDeletes=!1){this.masterCallback=masterCallback,this.ignoreDeletes=ignoreDeletes,this.rev="",this.current=new Map,this.callbacks=new Map,this.handleValue=(val,key)=>{let{current,callbacks}=this,priorExists=current.has(key),priorVal=priorExists?current.get(key):null,anyChange=!1;val===null?priorExists&&!this.ignoreDeletes&&(current.delete(key),callbacks.delete(key),anyChange=!0):(anyChange=priorVal!==val,current.set(key,val)),anyChange&&(this.rev=guid(),this.masterCallback&&this.masterCallback(val,key,priorVal))}}createRef(key){let refCallback=this.callbacks.get(key);return refCallback||(refCallback=val=>{this.handleValue(val,key)},this.callbacks.set(key,refCallback)),refCallback}},Ruler=class extends BaseComponent{constructor(){super(...arguments),this.elRef=createRef()}render(){return jsx12("div",{ref:this.elRef})}componentDidMount(){this._isUnmounting=!1;let{props}=this,el=this.elRef.current;this.disconnectWidth=watchWidth(el,width=>{this._isUnmounting||setRef(props.widthRef,width)})}componentWillUnmount(){this._isUnmounting=!0,this.disconnectWidth();let{props}=this;props.widthRef&&setRef(props.widthRef,null)}};function getDayGridSegKey(seg){return`${seg.eventRange.instance.instanceId}:${seg.start}`}function splitSegsByRow(segs,rowCount){let byRow=[];for(let row=0;row<rowCount;row++)byRow[row]=[];for(let seg of segs)byRow[seg.row].push(seg);return byRow}function splitInteractionByRow(ui,rowCount){let byRow=[];if(ui){for(let row=0;row<rowCount;row++)byRow[row]={affectedInstances:ui.affectedInstances,isEvent:ui.isEvent,segs:[]};for(let seg of ui.segs)byRow[seg.row].segs.push(seg)}else for(let row=0;row<rowCount;row++)byRow[row]=null;return byRow}var BgEvent=class extends BaseComponent{constructor(){super(...arguments),this.buildPublicEvent=memoize2((context,eventDef,eventInstance)=>new EventImpl(context,eventDef,eventInstance)),this.handleEl=el=>{this.el=el,el&&setElEventRange(el,this.props.eventRange)}}render(){let{props,context}=this,{eventRange}=props,{options}=context,eventUi=eventRange.ui,eventApi=this.buildPublicEvent(context,eventRange.def,eventRange.instance),subcontentRenderProps={event:eventApi,isNarrow:props.isNarrow||!1,isShort:props.isShort||!1},renderProps={event:eventApi,view:context.viewApi,timeText:"",color:eventUi.color||options.backgroundEventColor,contrastColor:eventUi.contrastColor,isDraggable:!1,isStartResizable:!1,isEndResizable:!1,isMirror:!1,isStart:props.isStart,isEnd:props.isEnd,isFirst:!1,isLast:!1,isPast:props.isPast,isFuture:props.isFuture,isToday:props.isToday,isSelected:!1,isDragging:!1,isResizing:!1,isInteractive:!1,level:0,isNarrow:props.isNarrow||!1,isShort:props.isShort||!1,timeClass:"",titleClass:generateClassName(options.backgroundEventTitleClass,subcontentRenderProps),options:{eventOverlap:!!options.eventOverlap}},outerClassName=joinClassNames(eventUi.className,classNames.fill,classNames.internalEvent,classNames.internalBgEvent,props.isVertical?classNames.flexCol:classNames.flexRow),innerClassName=joinClassNames(generateClassName(options.backgroundEventInnerClass,renderProps),classNames.liquid);return jsx12(ContentContainer,{tag:"div",className:outerClassName,style:{"--fc-event-color":renderProps.color,"--fc-event-contrast-color":renderProps.contrastColor},defaultGenerator:renderInnerContent2,elRef:this.handleEl,renderProps,generatorName:"backgroundEventContent",customGenerator:options.backgroundEventContent,classNameGenerator:options.backgroundEventClass,didMount:options.backgroundEventDidMount,willUnmount:options.backgroundEventWillUnmount,children:InnerContent=>jsx12(InnerContent,{tag:"div",className:innerClassName})})}componentDidUpdate(prevProps){this.el&&this.props.eventRange!==prevProps.eventRange&&setElEventRange(this.el,this.props.eventRange)}};function renderInnerContent2(props){let{title}=props.event;return title&&jsx12("div",{className:props.titleClass,children:props.event.title})}function renderFill(fillType,options){return jsx12("div",{className:joinClassNames(fillType==="non-business"?options.nonBusinessHoursClass:fillType==="highlight"?options.highlightClass:void 0,classNames.fill)})}var COL_BORDER_WIDTH=1,ROW_BORDER_WIDTH=1,SPACE_FROM_VIEWPORT=10,MorePopover=class extends DateComponent{constructor(){super(...arguments),this.getDateMeta=memoize2(getDateMeta),this.closeRef=createRef(),this.focusStartRef=createRef(),this.focusEndRef=createRef(),this.handleRootEl=rootEl=>{this.rootEl=rootEl,rootEl?this.context.registerInteractiveComponent(this,{el:rootEl,useEventCenter:!1}):this.context.unregisterInteractiveComponent(this)},this.handleDocumentMouseDown=ev=>{let target=getEventTargetViaRoot(ev);this.rootEl.contains(target)||this.handleClose()},this.handleDocumentKeyDown=ev=>{ev.key==="Escape"&&this.handleClose()},this.handleClose=()=>{let{onClose}=this.props;onClose&&onClose()}}render(){let{props,context}=this,{options,dateEnv,viewApi}=context,{startDate,todayRange,dateProfile}=props,dateMeta=this.getDateMeta(startDate,dateEnv,dateProfile,todayRange),textParts=dateEnv.formatToParts(startDate,options.popoverFormat),text=joinDateTimeFormatParts(textParts),dayHeaderRenderProps={...dateMeta,isMajor:!1,isNarrow:!1,isSticky:!1,inPopover:!0,level:0,hasNavLink:!1,text,textParts,get weekdayText(){return findWeekdayText(textParts)},get dayNumberText(){return findDayNumberText(textParts)},view:viewApi},dayCellRenderProps={...dateMeta,isMajor:!1,isNarrow:!1,inPopover:!0,hasNavLink:!1,get weekdayText(){return findWeekdayText(textParts)},get dayNumberText(){return findDayNumberText(textParts)},get monthText(){return findMonthText(textParts)},view:viewApi,text:"",textParts:[],options:{businessHours:!!options.businessHours}},fullDateStr=formatDayString(startDate),{dayHeaderAlign}=options,align=typeof dayHeaderAlign=="function"?dayHeaderAlign({level:0,inPopover:!0,isNarrow:!1}):dayHeaderAlign,isRtl=computeElIsRtl(props.alignEl);return createPortal(jsxs9("div",{"data-date":fullDateStr,id:props.id,role:"dialog","aria-labelledby":props.titleId,className:joinClassNames(options.popoverClass,classNames.flexCol,classNames.popoverZ,classNames.abs,classNames.borderBoxRoot,classNames.internalPopover),style:{top:0,left:0},dir:isRtl?"rtl":void 0,"data-color-scheme":options.colorScheme||void 0,ref:this.handleRootEl,children:[jsx12("div",{tabIndex:0,style:{outline:"none"},ref:this.focusStartRef}),jsxs9("div",{className:joinClassNames(generateClassName(options.dayHeaderClass,dayHeaderRenderProps),classNames.flexCol,classNames.borderlessX,classNames.borderlessTop,align==="center"?classNames.alignCenter:align==="end"?classNames.alignEnd:classNames.alignStart),children:[jsx12("div",{children:jsx12(ContentContainer,{tag:"div",attrs:{id:props.titleId},generatorName:"dayHeaderContent",renderProps:dayHeaderRenderProps,customGenerator:options.dayHeaderContent,defaultGenerator:renderText2,classNameGenerator:options.dayHeaderInnerClass,didMount:options.dayHeaderDidMount,willUnmount:options.dayHeaderWillUnmount})}),jsx12(ContentContainer,{tag:"button",attrs:{"aria-label":options.closeHint,...createAriaClickAttrs(this.handleClose)},elRef:this.closeRef,className:joinClassNames(options.popoverCloseClass,classNames.flexRow,classNames.cursorPointer),renderProps:{},customGenerator:options.popoverCloseContent,generatorName:"popoverCloseContent"})]}),jsx12("div",{className:joinClassNames(generateClassName(options.dayCellClass,dayCellRenderProps),classNames.flexCol,classNames.borderless),children:jsx12("div",{className:generateClassName(options.dayCellInnerClass,dayCellRenderProps),children:props.children})}),jsx12("div",{tabIndex:0,style:{outline:"none"},ref:this.focusEndRef})]}),getAppendableRoot(props.alignEl))}queryHit(isRtl,positionLeft,positionTop,elWidth,elHeight){let{rootEl,props}=this;return positionLeft>=0&&positionLeft<elWidth&&positionTop>=0&&positionTop<elHeight?{dateProfile:props.dateProfile,dateSpan:{allDay:!props.forceTimed,range:{start:props.startDate,end:props.endDate},...props.dateSpanProps},getDayEl:()=>rootEl,rect:{left:0,top:0,right:elWidth,bottom:elHeight},layer:1}:null}componentDidMount(){document.addEventListener("mousedown",this.handleDocumentMouseDown),document.addEventListener("keydown",this.handleDocumentKeyDown),this.focusStartRef.current.addEventListener("focus",this.handleClose),this.focusEndRef.current.addEventListener("focus",this.handleClose),this.closeRef.current.focus({preventScroll:!0}),this.updateSize()}componentWillUnmount(){document.removeEventListener("mousedown",this.handleDocumentMouseDown),document.removeEventListener("keydown",this.handleDocumentKeyDown),this.focusStartRef.current.removeEventListener("focus",this.handleClose),this.focusEndRef.current.removeEventListener("focus",this.handleClose)}updateSize(){let{alignEl,alignParentTop}=this.props,{rootEl:popoverEl}=this,isRtl=computeElIsRtl(alignEl),alignmentRect=computeClippedClientRect(alignEl);if(alignmentRect){let popoverDims=popoverEl.getBoundingClientRect(),popoverVPTop=alignParentTop?alignEl.closest(alignParentTop).getBoundingClientRect().top-ROW_BORDER_WIDTH:alignmentRect.top,popoverVPLeft=isRtl?alignmentRect.right-popoverDims.width:alignmentRect.left;popoverVPTop=Math.max(popoverVPTop,SPACE_FROM_VIEWPORT),popoverVPLeft=Math.min(popoverVPLeft,document.documentElement.clientWidth-SPACE_FROM_VIEWPORT-popoverDims.width),popoverVPLeft=Math.max(popoverVPLeft,SPACE_FROM_VIEWPORT);let{offsetParent}=popoverEl,top,left;if(!offsetParent||offsetParent===document.body)top=popoverVPTop+window.scrollY,left=popoverVPLeft+window.scrollX;else{let offsetParentRect=offsetParent.getBoundingClientRect();top=popoverVPTop-offsetParentRect.top+offsetParent.scrollTop,left=popoverVPLeft-offsetParentRect.left+offsetParent.scrollLeft}applyStyle(popoverEl,{top,left})}}};function renderText2(renderProps){return renderProps.text}function computeEarliestStart(segs){return segs.reduce(pickEarliestStart).eventRange.range.start}function computeLatestEnd(segs){return segs.reduce(pickLatestEnd).eventRange.range.end}function pickEarliestStart(r0,r1){return r0.eventRange.range.start<r1.eventRange.range.start?r0:r1}function pickLatestEnd(r0,r1){return r0.eventRange.range.end>r1.eventRange.range.end?r0:r1}var MoreLinkTrigger=class extends BaseComponent{render(){let{props,context}=this,{options}=context,renderProps=buildMoreLinkRenderProps(props.num,props.isNarrow,props.isMicro,props.display,context);return jsx12(ContentContainer,{tag:"div",elRef:props.elRef,className:joinClassNames(generateClassName(props.display==="row"?options.rowMoreLinkClass:options.columnMoreLinkClass,renderProps),props.className,props.display==="row"?classNames.flexRow:classNames.flexCol,classNames.internalMoreLink,classNames.cursorPointer),style:props.style,attrs:props.attrs,renderProps,generatorName:"moreLinkContent",customGenerator:options.moreLinkContent,defaultGenerator:renderMoreLinkText,classNameGenerator:options.moreLinkClass,didMount:props.didMount,willUnmount:props.willUnmount,children:InnerContent=>jsx12(InnerContent,{tag:"div",className:joinClassNames(generateClassName(options.moreLinkInnerClass,renderProps),generateClassName(props.display==="row"?options.rowMoreLinkInnerClass:options.columnMoreLinkInnerClass,renderProps),props.display==="row"?classNames.stickyS:classNames.stickyT)})})}},MoreLinkContainer=class extends BaseComponent{constructor(){super(...arguments),this.state={isPopoverOpen:!1},this.handleLinkEl=linkEl=>{this.linkEl=linkEl,this.props.elRef&&setRef(this.props.elRef,linkEl)},this.handleClick=ev=>{let{props,context}=this,{dateEnv,options}=context,{moreLinkClick}=options,date=computeRange(props).start;function buildPublicSeg(seg){let{def,instance,range}=seg.eventRange,start=buildRangeEdgeOutput(range.start,range.instantStartMs,dateEnv),end=buildRangeEdgeOutput(range.end,range.instantEndMs,dateEnv);return{event:new EventImpl(context,def,instance),start:start.date,end:end.date,isStart:seg.isStart,isEnd:seg.isEnd}}typeof moreLinkClick=="function"&&(moreLinkClick=moreLinkClick({date:dateEnv.toDate(date),allDay:!!props.allDayDate,allSegs:props.segs.map(buildPublicSeg),hiddenSegs:props.hiddenSegs.map(buildPublicSeg),jsEvent:ev,view:context.viewApi})),!moreLinkClick||moreLinkClick==="popover"?this.setState({isPopoverOpen:!0}):typeof moreLinkClick=="string"&&context.calendarApi.zoomTo(date,moreLinkClick)},this.handlePopoverClose=()=>{this.linkEl&&this.linkEl.focus(),this.setState({isPopoverOpen:!1})}}render(){let{props,state,context}=this,{options,baseId}=context,moreCnt=props.hiddenSegs.length,range=computeRange(props),popoverId=baseId+"popover-"+range.start.toISOString(),renderProps=buildMoreLinkRenderProps(moreCnt,props.isNarrow,props.isMicro,props.display,context),hint=formatWithOrdinals(options.moreLinkHint,[moreCnt],renderProps.longText);return jsxs9(Fragment7,{children:[!!moreCnt&&jsx12(MoreLinkTrigger,{num:moreCnt,display:props.display,isNarrow:props.isNarrow,isMicro:props.isMicro,elRef:this.handleLinkEl,className:props.className,style:props.style,attrs:{...props.attrs,...createAriaClickAttrs(this.handleClick),title:hint,role:"button","aria-haspopup":"dialog","aria-expanded":state.isPopoverOpen,"aria-controls":state.isPopoverOpen?popoverId:void 0},didMount:options.moreLinkDidMount,willUnmount:options.moreLinkWillUnmount}),state.isPopoverOpen&&jsx12(MorePopover,{id:popoverId,titleId:popoverId+"-title",startDate:range.start,endDate:range.end,dateProfile:props.dateProfile,todayRange:props.todayRange,dateSpanProps:props.dateSpanProps,alignEl:props.alignElRef?props.alignElRef.current:this.linkEl,alignParentTop:props.alignParentTop,forceTimed:props.forceTimed,onClose:this.handlePopoverClose,children:props.popoverContent()})]})}};function renderMoreLinkText(props){return props.text}function buildMoreLinkRenderProps(num,isNarrow,isMicro,display,context){let{viewApi,options,calendarApi}=context,numericText=`+${num}`,longText=typeof options.moreLinkText=="function"?options.moreLinkText.call(calendarApi,num):`${numericText} ${options.moreLinkText}`;return{num,numericText,longText,text:isMicro||display==="column"?numericText:longText,isNarrow,view:viewApi}}function computeRange(props){return props.allDayDate?{start:props.allDayDate,end:addDays4(props.allDayDate,1)}:{start:computeEarliestStart(props.hiddenSegs),end:computeLatestEnd(props.hiddenSegs)}}var DEFAULT_TABLE_EVENT_TIME_FORMAT=createFormatter({hour:"numeric",minute:"2-digit",omitZeroMinute:!0,meridiem:"narrow"});function hasListItemDisplay(range,eventRange){let{display}=eventRange.ui;return display==="list-item"||display==="auto"&&!eventRange.def.allDay&&range.end-range.start===1&&range.isStart&&range.isEnd}var DAY_GRID_NON_BUSINESS_Z_CLASS=classNames.z1,DAY_GRID_BG_EVENT_Z_CLASS=classNames.z2,DAY_GRID_HIGHLIGHT_Z_CLASS=classNames.z3,DAY_GRID_CELL_CONTENT_Z_CLASS=classNames.z4,DAY_GRID_EVENT_Z_CLASS=classNames.z5,DAY_GRID_INTERACTION_Z_CLASS=classNames.z1000,DayGridMoreLink=class extends BaseComponent{render(){let{props}=this;return jsx12(MoreLinkContainer,{display:"row",className:joinClassNames(props.className,DAY_GRID_CELL_CONTENT_Z_CLASS),isNarrow:props.isNarrow,isMicro:props.isMicro,dateProfile:props.dateProfile,todayRange:props.todayRange,allDayDate:props.allDayDate,segs:props.segs,hiddenSegs:props.hiddenSegs,alignElRef:props.alignElRef,alignParentTop:props.alignParentTop,dateSpanProps:props.dateSpanProps,popoverContent:()=>jsx12(Fragment7,{children:props.segs.map(seg=>{let{eventRange}=seg,{instanceId}=eventRange.instance,isDragging=!!(props.eventDrag&&props.eventDrag.affectedInstances[instanceId]),isResizing=!!(props.eventResize&&props.eventResize.affectedInstances[instanceId]);return jsx12("div",{style:{visibility:isDragging||isResizing?"hidden":void 0},children:jsx12(StandardEvent,{display:hasListItemDisplay(seg,eventRange)?"list-item":"row",eventRange,isStart:seg.isStart,isEnd:seg.isEnd,isDragging,isResizing,isMirror:!1,isSelected:instanceId===props.eventSelection,defaultTimeFormat:DEFAULT_TABLE_EVENT_TIME_FORMAT,defaultDisplayEventEnd:!1,...getEventRangeMeta(eventRange,props.todayRange)})},instanceId)})})})}},DayGridCell=class extends DateComponent{constructor(){super(...arguments),this.getDateMeta=memoize2(getDayGridCellDateMeta),this.refineRenderProps=memoizeObjArg(refineRenderProps2),this.rootElRef=createRef(),this.handleBodyEl=bodyEl=>{this.disconnectBodyHeight&&(this.disconnectBodyHeight(),this.disconnectBodyHeight=void 0,this.headerHeight=void 0,setRef(this.props.headerHeightRef,null),setRef(this.props.mainHeightRef,null)),bodyEl&&(this.props.headerHeightRef||this.props.mainHeightRef)&&(this.disconnectBodyHeight=watchSize(bodyEl,(_bodyWidth,bodyHeight)=>{if(this._isUnmounting)return;let{props}=this,rootEl=this.rootElRef.current;if(!rootEl)return;let mainRect=bodyEl.getBoundingClientRect(),rootRect=rootEl.getBoundingClientRect(),headerHeight=mainRect.top-rootRect.top;isDimsEqual(this.headerHeight,headerHeight)||(this.headerHeight=headerHeight,setRef(props.headerHeightRef,headerHeight)),setRef(props.mainHeightRef,bodyHeight)}))}}render(){let{props,context}=this,{options,dateEnv}=context,{tableMode}=props,isMonthStart=props.showDayNumber&&shouldDisplayMonthStart(props.date,props.dateProfile.currentRange,dateEnv),dateMeta=this.getDateMeta(props.date,dateEnv,props.dateProfile,props.todayRange,props.isDisabled),baseClassName=joinClassNames(classNames.borderlessTop,classNames.borderlessEnd,!props.borderStart&&classNames.borderlessStart,!(tableMode&&props.borderBottom)&&classNames.borderlessBottom,!tableMode&&props.width==null&&classNames.liquid,!tableMode&&classNames.flexCol,classNames.rel,classNames.noMargin,classNames.noPadding),CellTag=tableMode?"td":"div",cellStyle=tableMode?void 0:{width:props.width},hasNavLink=options.navLinks,renderProps=this.refineRenderProps({date:props.date,isMajor:props.isMajor,isNarrow:props.isNarrow,dateMeta,hasLabel:props.showDayNumber,hasMonthLabel:isMonthStart,hasNavLink,renderProps:props.renderProps,viewApi:context.viewApi,dateEnv:context.dateEnv,monthStartFormat:options.monthStartFormat,dayCellFormat:options.dayCellFormat,businessHours:!!options.businessHours});if(dateMeta.isDisabled)return jsx12(CellTag,{role:"gridcell","aria-disabled":!0,className:joinClassNames(generateClassName(options.dayCellClass,renderProps),props.className,baseClassName),style:cellStyle,children:props.fills});let fullDateStr=buildDateStr(context,props.date);return jsx12(ContentContainer,{tag:CellTag,elRef:this.rootElRef,className:joinClassNames(props.className,baseClassName),attrs:{...props.attrs,role:"gridcell","aria-label":fullDateStr,...renderProps.isToday?{"aria-current":"date"}:{},"data-date":formatDayString(props.date)},style:cellStyle,renderProps,generatorName:"dayCellTopContent",customGenerator:options.dayCellTopContent,defaultGenerator:renderTopInner,classNameGenerator:options.dayCellClass,didMount:options.dayCellDidMount,willUnmount:options.dayCellWillUnmount,children:InnerContent=>jsxs9(Fragment7,{children:[props.fills,jsx12("div",{className:joinClassNames(classNames.rel,DAY_GRID_CELL_CONTENT_Z_CLASS,generateClassName(options.dayCellTopClass,renderProps)),children:props.showDayNumber&&jsx12(InnerContent,{tag:"div",attrs:hasNavLink?buildNavLinkAttrs(context,props.date,void 0,fullDateStr):{"aria-hidden":!0},className:generateClassName(options.dayCellTopInnerClass,renderProps)})}),jsxs9("div",{className:joinClassNames(!tableMode&&classNames.flexCol,!tableMode&&(props.fgLiquidHeight?classNames.liquid:classNames.grow),tableMode&&classNames.printCellContentMinHeight),ref:this.handleBodyEl,children:[jsx12("div",{className:joinClassNames(classNames.rel,generateClassName(options.dayCellInnerClass,renderProps)),style:{minHeight:props.fgHeight},children:props.fg}),jsx12(DayGridMoreLink,{className:classNames.rel,allDayDate:props.date,segs:props.segs,hiddenSegs:props.hiddenSegs,alignElRef:this.rootElRef,alignParentTop:props.showDayNumber?"[role=row]":`.${classNames.internalView}`,dateSpanProps:props.dateSpanProps,dateProfile:props.dateProfile,eventSelection:props.eventSelection,eventDrag:props.eventDrag,eventResize:props.eventResize,todayRange:props.todayRange,isNarrow:props.isNarrow,isMicro:props.isMicro})]}),jsx12("div",{className:joinClassNames(classNames.rel,DAY_GRID_CELL_CONTENT_Z_CLASS,generateClassName(options.dayCellBottomClass,renderProps))})]})})}componentDidMount(){this._isUnmounting=!1}componentWillUnmount(){this._isUnmounting=!0}};function getDayGridCellDateMeta(date,dateEnv,dateProfile,todayRange,isDisabled){return{...getDateMeta(date,dateEnv,dateProfile,todayRange),isDisabled}}function renderTopInner(props){return props.text||jsx12(Fragment7,{children:"\xA0"})}function shouldDisplayMonthStart(date,currentRange,dateEnv){let{start:currentStart,end:currentEnd}=currentRange,currentEndIncl=addMs(currentEnd,-1),currentFirstYear=dateEnv.getYear(currentStart),currentFirstMonth=dateEnv.getMonth(currentStart),currentLastYear=dateEnv.getYear(currentEndIncl),currentLastMonth=dateEnv.getMonth(currentEndIncl);return!(currentFirstYear===currentLastYear&¤tFirstMonth===currentLastMonth)&&(date.valueOf()===currentStart.valueOf()||dateEnv.getDay(date)===1&&date.valueOf()<currentEnd.valueOf())}function refineRenderProps2(raw){let{date,dateEnv,hasLabel,hasMonthLabel,hasNavLink,businessHours}=raw,textParts=[],text="";return hasLabel&&(textParts=dateEnv.formatToParts(date,hasMonthLabel?raw.monthStartFormat:raw.dayCellFormat),text=joinDateTimeFormatParts(textParts)),{...raw.dateMeta,...raw.renderProps,text,textParts,isMajor:raw.isMajor,isNarrow:raw.isNarrow,inPopover:!1,hasNavLink,get weekdayText(){return findWeekdayText(textParts)},get dayNumberText(){return findDayNumberText(textParts)},get monthText(){return findMonthText(textParts)},options:{businessHours},view:raw.viewApi}}var MeasuredHeightHarness=class extends Component4{constructor(){super(...arguments),this.rootElRef=createRef(),this._isUnmounting=!1}render(){let{props}=this;return jsx12("div",{className:props.className,style:props.style,ref:this.rootElRef,children:props.children})}componentDidMount(){this._isUnmounting=!1;let rootEl=this.rootElRef.current;this.disconnectHeight=watchHeight(rootEl,height=>{this._isUnmounting||(this.height=height,setRef(this.props.heightRef,height))})}componentDidUpdate(prevProps){let{heightRef}=this.props;prevProps.heightRef!==heightRef&&(setRef(prevProps.heightRef,null),this.height!=null&&setRef(heightRef,this.height))}componentWillUnmount(){this._isUnmounting=!0,this.disconnectHeight?.(),setRef(this.props.heightRef,null)}};function doSpansIntersect(a,b){return a.start<b.end&&b.start<a.end}function intersectSpans(a,b){let start=Math.max(a.start,b.start),end=Math.min(a.end,b.end);return start<end?{start,end}:null}function getSpanLength(span){return span.end-span.start}function findIntersections(entries,span){let index2=findLowerBoundByStart(entries,span.start);index2>0&&index2--;let matches=[];for(;index2<entries.length;index2++){let entry=entries[index2];if(entry.start>=span.end)break;doSpansIntersect(entry,span)&&matches.push(entry)}return matches}function subtractCoveredSpans(span,covered){let result=[],cursor=span.start;for(let item of covered)if(!(item.end<=cursor)&&(item.start>=span.end||(item.start>cursor&&result.push({start:cursor,end:Math.min(item.start,span.end)}),cursor=Math.max(cursor,item.end),cursor>=span.end)))break;return cursor<span.end&&result.push({start:cursor,end:span.end}),result}function addToUnion(spans,addition){let result=[],pending={...addition},inserted=!1;for(let span of spans)span.end<=pending.start?result.push(span):pending.end<=span.start?(inserted||(result.push(pending),inserted=!0),result.push(span)):pending={start:Math.min(pending.start,span.start),end:Math.max(pending.end,span.end)};inserted||result.push(pending),spans.splice(0,spans.length,...result)}function insertLaterally(entries,entry){entries.splice(findLowerBoundByStart(entries,entry.start),0,entry)}function findLowerBoundByStart(entries,start){let low=0,high=entries.length;for(;low<high;){let middle=low+high>>>1;entries[middle].start<start?low=middle+1:high=middle}return low}var GEOMETRY_TOLERANCE=1e-6,DEFAULT_UNMEASURED_EVENT_THICKNESS=20;function buildLevelLimitedLayout(segs,eventOrderStrict,eventSlicing,maxLevels,moreLinkLevelTax,sliceHeights){let{segLevels,excludedSegs}=buildSegLevels(segs,eventOrderStrict,maxLevels),placement=placeExtraSlicesInLevels(convertSegLevelsToWholeSlices(segLevels),convertSegsToWholeSlices(excludedSegs),eventOrderStrict,eventSlicing,moreLinkLevelTax),resolution=resolveLevelCoords(placement.sliceLevels,sliceHeights);return{renderSlices:flatArray(placement.sliceLevels),hiddenSlices:placement.hiddenSlices,sliceLevels:placement.sliceLevels,sliceCoords:resolution.sliceCoords,isSettled:resolution.isSettled}}function buildPixelLimitedLayout(segs,eventOrderStrict,eventSlicing,sliceHeights,canvasHeight,levelCapacity,moreLinkHeight){let{segLevels,excludedSegs}=buildSegLevels(segs,eventOrderStrict,levelCapacity),domWholeSliceLevels=convertSegLevelsToWholeSlices(segLevels),domExcludedWholeSlices=convertSegsToWholeSlices(excludedSegs),wholeResolution=resolveLevelCoords(domWholeSliceLevels,sliceHeights,canvasHeight);if(canvasHeight==null||moreLinkHeight==null)return{renderSlices:flatArray(domWholeSliceLevels),hiddenSlices:domExcludedWholeSlices,sliceLevels:domWholeSliceLevels,sliceCoords:wholeResolution.sliceCoords,isSettled:wholeResolution.isSettled};let excludedWholeSlices=wholeResolution.excludedSlices.concat(domExcludedWholeSlices);excludedWholeSlices.sort(compareByEventOrder);let placement=placeExtraSlicesInLevels(wholeResolution.placementSliceLevels,excludedWholeSlices,eventOrderStrict,eventSlicing,eventSlicing?1:0,!0,!0),sliceResolution=resolveLevelCoords(placement.sliceLevels,sliceHeights),moreLinkEventMax=Math.max(0,canvasHeight-moreLinkHeight),pixelPrunedSlices=prunePixelLimitedSliceLevels(placement.sliceLevels,placement.hiddenSlices,sliceResolution.sliceCoords,sliceHeights,canvasHeight,moreLinkEventMax),renderSlices=flatArray(domWholeSliceLevels).concat(placement.addedSlices),isSettled=wholeResolution.isSettled&&sliceResolution.isSettled;return{renderSlices,hiddenSlices:pixelPrunedSlices.concat(placement.hiddenSlices),sliceLevels:placement.sliceLevels,sliceCoords:sliceResolution.sliceCoords,isSettled}}function buildSegLevels(segs,eventOrderStrict,maxLevels=1/0){let segLevels=[],excludedSegs=[];for(let seg of segs){let levelIndex=findPackedLevelIndex(segLevels,seg,eventOrderStrict);if(levelIndex>=maxLevels)excludedSegs.push(seg);else{for(;segLevels.length<=levelIndex;)segLevels.push([]);insertLaterally(segLevels[levelIndex],seg)}}return{segLevels,excludedSegs}}function findPackedLevelIndex(levels,span,orderStrict){let levelIndex=0;if(orderStrict)for(let i=0;i<levels.length;i++)findIntersections(levels[i],span).length&&(levelIndex=i+1);else for(;levelIndex<levels.length&&findIntersections(levels[levelIndex],span).length;)levelIndex++;return levelIndex}function convertSegLevelsToWholeSlices(segLevels){return segLevels.map(level=>convertSegsToWholeSlices(level))}function convertSegsToWholeSlices(segs){return segs.map(createWholeSlice)}function resolveLevelCoords(sliceLevels,sliceHeights,maxPixels=1/0){let placementSliceLevels=[],sliceCoords=new Map,isSettled=!0,excludedSlices=[];for(let levelIndex=0;levelIndex<sliceLevels.length;levelIndex++)for(let slice of sliceLevels[levelIndex]){let sliceHeight=sliceHeights.get(getSliceKey(slice));if(sliceHeight===void 0){isSettled=!1;continue}let{bottom:levelCoord,levelIndex:packedLevelIndex}=computeLateralSpanPlacement(placementSliceLevels,slice,sliceCoords,sliceHeights);if(levelCoord+sliceHeight<=maxPixels+GEOMETRY_TOLERANCE){for(;placementSliceLevels.length<=packedLevelIndex;)placementSliceLevels.push([]);insertLaterally(placementSliceLevels[packedLevelIndex],slice),sliceCoords.set(getSliceKey(slice),levelCoord)}else excludedSlices.push(slice)}return{placementSliceLevels,sliceCoords,isSettled,excludedSlices}}function computeLateralSpanPlacement(sliceLevels,span,sliceCoords,sliceHeights){let bottom=0,levelIndex=0;for(let i=0;i<sliceLevels.length;i++){let level=sliceLevels[i];for(let slice of findIntersections(level,span)){let key=getSliceKey(slice),sliceTop=sliceCoords.get(key),sliceHeight=sliceHeights.get(key);sliceTop!==void 0&&sliceHeight!==void 0&&(bottom=Math.max(bottom,sliceTop+sliceHeight),levelIndex=i+1)}}return{bottom,levelIndex}}function recomputeVisibleCoords(sliceLevels,sliceHeights,sliceCoords){let visibleLevels=sliceLevels.map(level=>level.filter(slice=>sliceCoords.has(getSliceKey(slice)))),freshCoords=resolveLevelCoords(visibleLevels,sliceHeights).sliceCoords;for(let[key,coord]of freshCoords)sliceCoords.set(key,coord)}function getSliceBottom(slice,sliceCoords,sliceHeights){let key=getSliceKey(slice),coord=sliceCoords.get(key),height=sliceHeights.get(key);return coord===void 0||height===void 0?void 0:coord+height}function prunePixelLimitedSliceLevels(sliceLevels,initialHiddenSlices,sliceCoords,sliceHeights,maxPixelHeight,moreLinkMaxPixelHeight){let moreLinkGroups=[],pixelPrunedSlices=[],sliceHideQueue=[],sliceHideIndex=0;for(let hiddenSlice of initialHiddenSlices)addHiddenSliceToGroups(moreLinkGroups,hiddenSlice);for(enqueueViolators();sliceHideIndex<sliceHideQueue.length;){let slice=sliceHideQueue[sliceHideIndex++],sliceBottom=getSliceBottom(slice,sliceCoords,sliceHeights);if(sliceBottom===void 0||!violatesPixelBoundary(slice,sliceBottom))continue;sliceCoords.delete(getSliceKey(slice)),pixelPrunedSlices.push(slice);let newMoreLinkSpans=addHiddenSliceToGroups(moreLinkGroups,slice);recomputeVisibleCoords(sliceLevels,sliceHeights,sliceCoords);for(let newMoreLinkSpan of newMoreLinkSpans)enqueueViolators(newMoreLinkSpan)}return pixelPrunedSlices;function violatesPixelBoundary(slice,sliceBottom){return sliceBottom>maxPixelHeight+GEOMETRY_TOLERANCE||sliceBottom>moreLinkMaxPixelHeight+GEOMETRY_TOLERANCE&&findIntersections(moreLinkGroups,slice).length>0}function enqueueViolators(withinSpan){for(let level of sliceLevels){let candidates=withinSpan?findIntersections(level,withinSpan):level;for(let slice of candidates){let sliceBottom=getSliceBottom(slice,sliceCoords,sliceHeights);sliceBottom!==void 0&&violatesPixelBoundary(slice,sliceBottom)&&sliceHideQueue.push(slice)}}}}function placeExtraSlicesInLevels(sliceLevels,extraSlices,eventOrderStrict,eventSlicing,moreLinkLevelTax,requiresSlicing=!1,taxDeepestOccupiedLevel=!1){let addedSliceSet=new Set,hiddenSlices=[],moreLinkGroups=[],moreLinkReservations=[],placementState={levels:sliceLevels,moreLinkReservations,eventOrderStrict},work=[];for(pushFire(extraSlices,requiresSlicing);work.length;){let item=work.pop();item.type==="fire"?fire(item.slice,item.requiresSlicing):fireMoreLink(item.span)}return{sliceLevels,hiddenSlices,addedSlices:[...addedSliceSet]};function fire(slice,requiresSlicing2){if(!requiresSlicing2){let levelIndex=findInsertionLevel(slice,placementState);if(levelIndex!==null){insertLaterally(sliceLevels[levelIndex],slice),addedSliceSet.add(slice);return}}if(!eventSlicing){hide(slice);return}let plan=findBestSlicePlan(slice,placementState,requiresSlicing2);if(!plan){hide(slice);return}for(let visibleSlice of plan.slices)insertLaterally(sliceLevels[plan.levelIndex],visibleSlice),addedSliceSet.add(visibleSlice);for(let hiddenSlice of subtractSpansFromSlice(slice,plan.slices))hide(hiddenSlice)}function hide(slice){hiddenSlices.push(slice);let newMoreLinkSpans=addHiddenSliceToGroups(moreLinkGroups,slice);if(moreLinkLevelTax)for(let i=newMoreLinkSpans.length-1;i>=0;i--)work.push({type:"moreLink",span:newMoreLinkSpans[i]})}function fireMoreLink(span){if(!sliceLevels.length)return;let taxedLevelIndex=sliceLevels.length-1,victims=findIntersections(sliceLevels[taxedLevelIndex],span);if(taxDeepestOccupiedLevel)for(;!victims.length&&taxedLevelIndex>0;)taxedLevelIndex--,victims=findIntersections(sliceLevels[taxedLevelIndex],span);insertLaterally(moreLinkReservations,{...span,levelIndex:taxedLevelIndex});let taxedLevel=sliceLevels[taxedLevelIndex];for(let victim of victims)taxedLevel.splice(taxedLevel.indexOf(victim),1),addedSliceSet.delete(victim),eventSlicing?(hide(intersectSlice(victim,span)),pushFire(subtractSpansFromSlice(victim,[span]),!1)):hide(victim)}function pushFire(slices,requiresSlicing2){for(let i=slices.length-1;i>=0;i--)work.push({type:"fire",slice:slices[i],requiresSlicing:requiresSlicing2})}}function findInsertionLevel(slice,state){let fence=computeLevelFence(slice,state);for(let levelIndex=fence.min;levelIndex<fence.maxExclusive;levelIndex++)if(!findIntersections(state.levels[levelIndex],slice).length)return levelIndex;return null}function computeLevelFence(slice,state){let{levels}=state,min=0,maxExclusive=levels.length;for(let reservation of findIntersections(state.moreLinkReservations,slice))maxExclusive=Math.min(maxExclusive,reservation.levelIndex);if(state.eventOrderStrict)for(let levelIndex=0;levelIndex<levels.length;levelIndex++)for(let other of findIntersections(levels[levelIndex],slice))other.sourceSeg.orderIndex<slice.sourceSeg.orderIndex?min=Math.max(min,levelIndex+1):other.sourceSeg.orderIndex>slice.sourceSeg.orderIndex&&(maxExclusive=Math.min(maxExclusive,levelIndex));return{min,maxExclusive}}var MAX_SLICES_PER_PLAN=3,EXTRA_SLICE_PENALTY=.15;function findBestSlicePlan(slice,state,requiresSlicing){let selected=null,sourceLength=getSpanLength(slice);for(let levelIndex=0;levelIndex<state.levels.length;levelIndex++){let blockers=findIntersections(state.levels[levelIndex],slice);for(let reservation of state.moreLinkReservations)levelIndex>=reservation.levelIndex&&addToUnion(blockers,reservation);let runs=subtractSpansFromSlice(slice,blockers).filter(run=>isWithinLevelFence(run,levelIndex,state)).sort((a,b)=>getSpanLength(b)-getSpanLength(a)||a.start-b.start),visibleLength=0;for(let sliceCount=1;sliceCount<=Math.min(MAX_SLICES_PER_PLAN,runs.length)&&(visibleLength+=getSpanLength(runs[sliceCount-1]),!(requiresSlicing&&visibleLength>=sourceLength-GEOMETRY_TOLERANCE));sliceCount++){let candidate={levelIndex,slices:runs.slice(0,sliceCount),score:visibleLength/sourceLength-EXTRA_SLICE_PENALTY*(sliceCount-1)};isBetterSlicePlan(candidate,selected)&&(selected=candidate)}}return selected&&selected.slices.sort(compareByEventOrder),selected}function isWithinLevelFence(slice,levelIndex,state){let fence=computeLevelFence(slice,state);return levelIndex>=fence.min&&levelIndex<fence.maxExclusive}function isBetterSlicePlan(candidate,current){return!current||candidate.score>current.score?!0:candidate.score<current.score?!1:candidate.slices.length!==current.slices.length?candidate.slices.length<current.slices.length:candidate.levelIndex<current.levelIndex}function groupLaterallyIntersecting(hiddenSlices){let groups=[];for(let slice of hiddenSlices)addHiddenSliceToGroups(groups,slice);return finalizeHiddenGroups(groups)}function addHiddenSliceToGroups(groups,slice){let newSpans=subtractCoveredSpans(slice,groups),untouchedGroups=[],mergedSlices=[slice],start=slice.start,end=slice.end;for(let group of groups)intersectSpans(group,slice)?(mergedSlices.push(...group.hiddenSlices),start=Math.min(start,group.start),end=Math.max(end,group.end)):untouchedGroups.push(group);return mergedSlices.sort(compareByEventOrder),insertLaterally(untouchedGroups,{start,end,hiddenSlices:mergedSlices}),groups.splice(0,groups.length,...untouchedGroups),newSpans}function finalizeHiddenGroups(groups){return groups.map(group=>{let hiddenSlices=mergeAdjacentSlices(group.hiddenSlices);return{key:getSliceKey(hiddenSlices[0]),start:group.start,end:group.end,hiddenSlices}})}function getSliceKey(slice){return isPartialSlice(slice)?`${slice.sourceSeg.key}:${slice.start}:slice`:slice.sourceSeg.key}function isPartialSlice(slice){return slice.start!==slice.sourceSeg.start||slice.end!==slice.sourceSeg.end}function compareByEventOrder(a,b){return a.sourceSeg.orderIndex-b.sourceSeg.orderIndex||a.start-b.start||b.end-a.end}function sortByEventOrder(slices){return[...slices].sort(compareByEventOrder)}function compareByAxisOrder(a,b){return a.start-b.start||a.sourceSeg.orderIndex-b.sourceSeg.orderIndex}function sortByAxisOrder(items){return[...items].sort(compareByAxisOrder)}function mergeAdjacentSlices(slices){let merged=[];for(let slice of slices){let previous=merged[merged.length-1];previous&&previous.sourceSeg===slice.sourceSeg?merged[merged.length-1]=createNarrowerSlice(createWholeSlice(previous.sourceSeg),previous.start,Math.max(previous.end,slice.end)):merged.push(slice)}return merged}function subtractSpansFromSlice(slice,covered){return subtractCoveredSpans(slice,covered).map(span=>createNarrowerSlice(slice,span.start,span.end))}function intersectSlice(slice,barrier){let intersection=intersectSpans(slice,barrier);return intersection?createNarrowerSlice(slice,intersection.start,intersection.end):null}function createWholeSlice(sourceSeg){return{sourceSeg,start:sourceSeg.start,end:sourceSeg.end,isStart:sourceSeg.isStart,isEnd:sourceSeg.isEnd}}function createNarrowerSlice(parent,start,end){return{sourceSeg:parent.sourceSeg,start,end,isStart:parent.isStart&&start===parent.start,isEnd:parent.isEnd&&end===parent.end}}var DEFAULT_UNMEASURED_EVENT_AREA_HEIGHT=150,DEFAULT_LEVEL_CAPACITY=estimateLevelCapacity(DEFAULT_UNMEASURED_EVENT_AREA_HEIGHT,DEFAULT_UNMEASURED_EVENT_THICKNESS);function buildDayGridSegSources(eventOrderedSegs){return eventOrderedSegs.map((seg,orderIndex)=>({...seg,key:getDayGridSegKey(seg),orderIndex}))}function buildDayGridLevelPlacements(eventOrderedSegs,maxLevels,moreLinkLevelTax,orderStrict,eventSlicing,columnCount,sliceHeights){let sourceSegs=buildDayGridSegSources(eventOrderedSegs),layout=buildLevelLimitedLayout(sourceSegs,orderStrict,eventSlicing,maxLevels,moreLinkLevelTax,sliceHeights);return buildDayGridPlacementLayout(sourceSegs,layout,sliceHeights,columnCount)}function buildDayGridPixelPlacements(eventOrderedSegs,orderStrict,eventSlicing,columnCount,canvasHeight,moreLinkHeight,levelCapacity,sliceHeights){let sourceSegs=buildDayGridSegSources(eventOrderedSegs),layout=buildPixelLimitedLayout(sourceSegs,orderStrict,eventSlicing,sliceHeights,canvasHeight,levelCapacity,moreLinkHeight);return buildDayGridPlacementLayout(sourceSegs,layout,sliceHeights,columnCount)}function buildDayGridPopoverSegs(eventOrderedSegs,hiddenSlices,column){return{segs:flatMapArray(eventOrderedSegs,source=>cutSegToColumn(source,column)??[]),hiddenSegs:flatMapArray(hiddenSlices,slice=>cutSegToColumn(slice.sourceSeg,column,slice)??[])}}function cutSegToColumn(source,column,intersectionSpan=source){if(intersectionSpan.start>=column+1||column>=intersectionSpan.end)return null;let{key,orderIndex,...seg}=source;return{...seg,start:column,end:column+1,isStart:seg.isStart&&source.start===column,isEnd:seg.isEnd&&source.end-1===column}}function resolveDayGridPlacementMode(dayMaxEvents,dayMaxEventRows){return dayMaxEvents===!0||dayMaxEventRows===!0?"auto":typeof dayMaxEvents=="number"?"maxEvents":typeof dayMaxEventRows=="number"?"maxEventRows":"unlimited"}function computeDayGridDomCandidateMaxLevels(mode,dayMaxEvents,dayMaxEventRows,maxDomLevels){switch(mode){case"auto":return maxDomLevels;case"maxEvents":return dayMaxEvents;case"maxEventRows":return dayMaxEventRows;default:return 1/0}}function computeDayGridMoreLinkLevelTax(mode){return mode==="maxEventRows"?1:0}function buildDayGridPlacementLayout(sourceSegs,layout,sliceHeights,columnCount){let{hiddenSlices,renderSlices,sliceCoords}=layout,eventOrderedHiddenSlices=sortByEventOrder(hiddenSlices),slicesByStart=federateSlicesByStart(renderSlices,columnCount),columns=Array.from({length:columnCount},(_,column)=>({renderSlices:slicesByStart[column],contentHeight:0,...buildDayGridPopoverSegs(sourceSegs,eventOrderedHiddenSlices,column)}));for(let slice of renderSlices){let key=getSliceKey(slice),sliceTop=sliceCoords.get(key);if(sliceTop===void 0)continue;let sliceBottom=sliceTop+sliceHeights.get(key);for(let column=slice.start;column<slice.end;column+=1)columns[column].contentHeight=Math.max(columns[column].contentHeight,sliceBottom)}return{columns,sliceCoords}}function federateSlicesByStart(renderSlices,columnCount){let slicesByStart=Array.from({length:columnCount},()=>[]);for(let slice of renderSlices)slicesByStart[slice.start].push(slice);for(let slices of slicesByStart)slices.sort(compareByEventOrder);return slicesByStart}function estimateLevelCapacity(eventAreaHeight,eventHeight){return Math.max(1,Math.ceil(eventAreaHeight/eventHeight))}var DEFAULT_PRINT_MAX_LEVELS=200;function planPrintDomCandidates(eventOrderedSegs,eventOrderStrict,eventSlicing){let{segLevels,excludedSegs}=buildSegLevels(eventOrderedSegs,eventOrderStrict,DEFAULT_PRINT_MAX_LEVELS),placement=placeExtraSlicesInLevels(convertSegLevelsToWholeSlices(segLevels),convertSegsToWholeSlices(excludedSegs),eventOrderStrict,eventSlicing,0);return{sliceLevels:placement.sliceLevels,hiddenSlices:placement.hiddenSlices}}function buildPrintEventBands(levels,printEventThicknesses,getPrintEventKey=slice=>slice.sourceSeg.key,defaultPrintEventThickness=DEFAULT_UNMEASURED_EVENT_THICKNESS){let bands=[];for(let levelIndex=0;levelIndex<levels.length;levelIndex++){let entries=levels[levelIndex];if(!entries?.length)continue;let thickness=0,slices=entries.map(slice=>(thickness=Math.max(thickness,printEventThicknesses.get(getPrintEventKey(slice))??defaultPrintEventThickness),slice));bands.push({levelIndex,slices,thickness})}return bands}function buildDayGridPrintPlan(eventOrderedSegs,orderStrict,eventSlicing,columnCount){let sourceSegs=buildDayGridSegSources(eventOrderedSegs),candidatePlan=planPrintDomCandidates(sourceSegs,orderStrict,eventSlicing);return{...candidatePlan,hiddenSlices:sortByEventOrder(candidatePlan.hiddenSlices),sourceSegs,columnCount}}function buildDayGridPrintColumns(plan,printSegHeights){let columns=Array.from({length:plan.columnCount},()=>[]);for(let band of buildPrintEventBands(plan.sliceLevels,printSegHeights,getDayGridPrintSliceKey)){let slicesByColumn=Array(plan.columnCount).fill(null);for(let slice of band.slices)slicesByColumn[slice.start]=slice;for(let column=0;column<plan.columnCount;column++)columns[column].push({levelIndex:band.levelIndex,thickness:band.thickness,slice:slicesByColumn[column]})}return columns}function getDayGridPrintSliceKey(slice){return`${slice.sourceSeg.key}:${slice.start}:${slice.end}`}var DEFAULT_WEEK_NUM_FORMAT=createFormatter({week:"narrow"}),DayGridRow=class extends BaseComponent{constructor(){super(...arguments),this.headerHeightRefMap=new RefMap(()=>{afterSize(this.handleSegPositioning)}),this.mainHeightRefMap=new RefMap(()=>{(this.props.dayMaxEvents===!0||this.props.dayMaxEventRows===!0)&&afterSize(this.handleSegPositioning)}),this.sliceHeightRefMap=new RefMap(()=>{afterSize(this.handleSegPositioning)}),this.handlePrintSegHeightChange=()=>{afterSize(this.handlePrintSegHeights)},this.printSegHeightRefMap=new RefMap(this.handlePrintSegHeightChange),this.buildWeekNumberRenderProps=memoize2(buildWeekNumberRenderProps),this.buildPrintPlan=memoize2(buildDayGridPrintPlan),this.sortEventSegs=memoize2(sortEventSegs),this.levelCapacity=DEFAULT_LEVEL_CAPACITY,this.handleRootEl=rootEl=>{this.disconnectHeight?.(),this.disconnectHeight=void 0,setRef(this.props.rootElRef,rootEl),rootEl&&(this.disconnectHeight=watchHeight(rootEl,contentHeight=>{setRef(this.props.heightRef,contentHeight)}))},this.handleSegPositioning=()=>{this._isUnmounting||this.props.forPrint||(this.updateAutoPlacementRatchets(),this.forceUpdate())},this.handlePrintSegHeights=()=>{this._isUnmounting||!this.props.forPrint||this.forceUpdate()}}render(){let{props,context,headerHeightRefMap,mainHeightRefMap}=this,{cells,tableMode}=props,{options}=context,weekDateMarker=props.cells[0].date,fgEventSegs=this.sortEventSegs(props.fgEventSegs,options.eventOrder),screenFgLiquidHeight=props.dayMaxEvents===!0||props.dayMaxEventRows===!0,printPlan=null,printColumns=null,screenColumns=null,screenSliceCoords=new Map,screenMainOffsetsByCol=[],screenHeightsByCol=[];if(props.forPrint)printPlan=this.buildPrintPlan(fgEventSegs,options.eventOrderStrict,options.eventSlicing,cells.length),printColumns=buildDayGridPrintColumns(printPlan,this.printSegHeightRefMap.current);else{let placementMode=resolveDayGridPlacementMode(props.dayMaxEvents,props.dayMaxEventRows),[maxMainTop,minMainHeight]=this.computeFgDims(),screenLayout=placementMode==="auto"?buildDayGridPixelPlacements(fgEventSegs,options.eventOrderStrict,options.eventSlicing,cells.length,minMainHeight,props.moreLinkHeight,this.levelCapacity,this.sliceHeightRefMap.current):buildDayGridLevelPlacements(fgEventSegs,computeDayGridDomCandidateMaxLevels(placementMode,props.dayMaxEvents,props.dayMaxEventRows,1/0),computeDayGridMoreLinkLevelTax(placementMode),options.eventOrderStrict,options.eventSlicing,cells.length,this.sliceHeightRefMap.current);if(screenColumns=screenLayout.columns,screenSliceCoords=screenLayout.sliceCoords,maxMainTop!=null)for(let col=0;col<cells.length;col++){let cellHeaderHeight=headerHeightRefMap.current.get(cells[col].key),mainOffset=cellHeaderHeight!=null?maxMainTop-cellHeaderHeight:void 0;screenMainOffsetsByCol.push(mainOffset),screenHeightsByCol.push(mainOffset!=null?screenColumns[col].contentHeight+mainOffset:void 0)}}let highlightSegs=this.getHighlightSegs(),hasNavLink=options.navLinks,fullWeekStr=buildDateStr(context,weekDateMarker,"week"),weekNumberRenderProps=this.buildWeekNumberRenderProps(weekDateMarker,context,props.cellIsNarrow,hasNavLink),fillsByCol=cells.map(()=>[]),weekNumberNode=props.showWeekNumbers&&!props.cellIsMicro?jsx12(ContentContainer,{tag:"div",attrs:{...hasNavLink?buildNavLinkAttrs(context,weekDateMarker,"week",fullWeekStr,!1):{},role:void 0,"aria-hidden":!0},className:DAY_GRID_EVENT_Z_CLASS,renderProps:weekNumberRenderProps,generatorName:"inlineWeekNumberContent",customGenerator:options.inlineWeekNumberContent,defaultGenerator:renderText,classNameGenerator:options.inlineWeekNumberClass,didMount:options.inlineWeekNumberDidMount,willUnmount:options.inlineWeekNumberWillUnmount}):null;return tableMode&&weekNumberNode&&fillsByCol[0].push(jsx12("div",{className:joinClassNames(classNames.fillY,classNames.start0,classNames.pointerEventsNone),style:{width:this.computeSpanWidth(0,cells.length)},children:weekNumberNode},"week-number")),this.appendFillSegs(fillsByCol,props.businessHourSegs,"non-business",DAY_GRID_NON_BUSINESS_Z_CLASS),this.appendFillSegs(fillsByCol,props.bgEventSegs,"bg-event",DAY_GRID_BG_EVENT_Z_CLASS),this.appendFillSegs(fillsByCol,highlightSegs,"highlight",DAY_GRID_HIGHLIGHT_Z_CLASS),jsxs9(tableMode?"tr":"div",{role:props.role,"aria-label":props.role==="row"?fullWeekStr:void 0,className:joinClassNames(options.dayRowClass,props.className,tableMode&&classNames.borderless,!tableMode&&classNames.flexRow,!tableMode&&classNames.rel,!tableMode&&classNames.borderlessX,!tableMode&&classNames.borderlessTop,!tableMode&&!props.borderBottom&&classNames.borderlessBottom,classNames.isolate),style:{flexBasis:tableMode?void 0:props.basis},ref:this.handleRootEl,children:[!tableMode&&weekNumberNode,props.cells.map((cell,col)=>{let printPopover=printPlan?buildDayGridPopoverSegs(printPlan.sourceSegs,printPlan.hiddenSlices,col):null,fg;return printPlan?fg=this.renderPrintBandSlots(printColumns[col]):fg=[...this.renderLevelFgSegs(screenMainOffsetsByCol[col],screenColumns[col].renderSlices,screenSliceCoords),...this.renderMirrorFgSegs(col,screenMainOffsetsByCol[col],screenSliceCoords)],jsx12(DayGridCell,{dateProfile:props.dateProfile,todayRange:props.todayRange,date:cell.date,isMajor:cell.isMajor,isDisabled:cell.isDisabled,showDayNumber:props.showDayNumbers,isNarrow:props.cellIsNarrow,isMicro:props.cellIsMicro,borderStart:!!col,borderBottom:props.borderBottom,tableMode,fills:fillsByCol[col],segs:printPopover?printPopover.segs:screenColumns[col].segs,hiddenSegs:printPopover?printPopover.hiddenSegs:screenColumns[col].hiddenSegs,fgLiquidHeight:printPlan?!1:screenFgLiquidHeight,fg,eventDrag:printPlan?null:props.eventDrag,eventResize:printPlan?null:props.eventResize,eventSelection:props.eventSelection,renderProps:cell.renderProps,dateSpanProps:cell.dateSpanProps,attrs:cell.attrs,className:cell.className,fgHeight:printPlan?void 0:screenHeightsByCol[col],width:props.colWidth,headerHeightRef:printPlan?void 0:headerHeightRefMap.createRef(cell.key),mainHeightRef:printPlan?void 0:mainHeightRefMap.createRef(cell.key)},cell.key)})]})}renderMirrorFgSegs(col,mainOffset,sliceCoords){let{props}=this,{eventSelection}=props,nodes=[];for(let seg of this.getMirrorSegs()){if(seg.start!==col)continue;let key=getDayGridSegKey(seg),{eventRange}=seg,{instanceId}=eventRange.instance,top=mainOffset!=null?mainOffset+(sliceCoords.get(key)??0):void 0,isDragging=!!(props.eventDrag&&props.eventDrag.affectedInstances[instanceId]),isResizing=!!(props.eventResize&&props.eventResize.affectedInstances[instanceId]),isSelected=instanceId===eventSelection;nodes.push(jsx12(MeasuredHeightHarness,{className:joinClassNames(classNames.abs,classNames.start0,DAY_GRID_INTERACTION_Z_CLASS),style:{top,width:this.computeSpanWidth(seg.start,seg.end)},heightRef:null,children:this.renderEventContent(seg,eventRange,{isDragging,isResizing,isMirror:!0,isSelected})},`mirror:${key}`))}return nodes}renderLevelFgSegs(mainOffset,slices,sliceCoords){let{props}=this,{eventSelection}=props,nodes=[];for(let slice of slices){let key=getSliceKey(slice),sliceTop=sliceCoords.get(key),{eventRange}=slice.sourceSeg,{instanceId}=eventRange.instance,top=mainOffset!=null&&sliceTop!=null?mainOffset+sliceTop:void 0,isDragging=!!(props.eventDrag&&props.eventDrag.affectedInstances[instanceId]),isResizing=!!(props.eventResize&&props.eventResize.affectedInstances[instanceId]),isInvisible=isDragging||isResizing||top==null,isSelected=instanceId===eventSelection;nodes.push(jsx12(MeasuredHeightHarness,{className:joinClassNames(classNames.abs,classNames.start0,isSelected?DAY_GRID_INTERACTION_Z_CLASS:DAY_GRID_EVENT_Z_CLASS),style:{visibility:isInvisible?"hidden":void 0,top,width:this.computeSpanWidth(slice.start,slice.end)},heightRef:this.sliceHeightRefMap.createRef(key),children:this.renderEventContent(slice,eventRange,{isDragging,isResizing,isSelected})},key))}return nodes}renderEventContent(range,eventRange,interaction){let{props}=this,isListItem=hasListItemDisplay(range,eventRange);return jsx12(StandardEvent,{display:isListItem?"list-item":"row",eventRange,isStart:range.isStart,isEnd:range.isEnd,isDragging:!!interaction.isDragging,isResizing:!!interaction.isResizing,isMirror:!!interaction.isMirror,isSelected:!!interaction.isSelected,isNarrow:props.cellIsNarrow,defaultTimeFormat:DEFAULT_TABLE_EVENT_TIME_FORMAT,defaultDisplayEventEnd:props.cells.length===1,disableResizing:isListItem,forcedTimeText:props.cellIsMicro?"":void 0,...getEventRangeMeta(eventRange,props.todayRange)})}renderPrintBandSlots(slots){let{printSegHeightRefMap}=this;return slots.map(slot=>{let{slice}=slot,eventNode=null;if(slice){let sliceKey=getDayGridPrintSliceKey(slice);eventNode=jsx12(MeasuredHeightHarness,{className:joinClassNames(classNames.rel,classNames.flowRoot,DAY_GRID_EVENT_Z_CLASS),style:{width:this.computeSpanWidth(slice.start,slice.end)},heightRef:printSegHeightRefMap.createRef(sliceKey),children:this.renderEventContent(slice,slice.sourceSeg.eventRange,{})},sliceKey)}return jsx12("div",{className:classNames.breakInsideAvoid,style:{height:slot.thickness},children:eventNode},slot.levelIndex)})}computeSpanWidth(start,end){let span=end-start,percentWidth=`${span*100}%`,crossedBorderWidth=this.props.tableMode&&start===0?0:Math.max(0,span-1)*COL_BORDER_WIDTH;return crossedBorderWidth?`calc(${percentWidth} + ${crossedBorderWidth}px)`:percentWidth}appendFillSegs(fillsByCol,segs,fillType,zClassName){let{props,context}=this,{todayRange}=props;for(let seg of segs)fillsByCol[seg.start].push(jsx12("div",{className:joinClassNames(classNames.fillY,classNames.start0,zClassName),style:{width:this.computeSpanWidth(seg.start,seg.end)},children:fillType==="bg-event"?jsx12(BgEvent,{eventRange:seg.eventRange,isStart:seg.isStart,isEnd:seg.isEnd,isNarrow:props.cellIsNarrow,isVertical:!1,...getEventRangeMeta(seg.eventRange,todayRange)}):renderFill(fillType,context.options)},`${fillType}:${buildEventRangeKey(seg.eventRange)}:${seg.start}:${seg.end}`))}componentDidMount(){this._isUnmounting=!1}componentDidUpdate(prevProps){prevProps.forPrint&&!this.props.forPrint&&(this.printSegHeightRefMap=new RefMap(this.handlePrintSegHeightChange))}componentWillUnmount(){this._isUnmounting=!0,this.disconnectHeight?.(),setRef(this.props.heightRef,null)}computeFgDims(){let{cells}=this.props,headerHeightMap=this.headerHeightRefMap.current,mainHeightMap=this.mainHeightRefMap.current,maxMainTop,minMainBottom,isComplete=!0;for(let cell of cells){if(cell.isDisabled)continue;let mainTop=headerHeightMap.get(cell.key),mainHeight=mainHeightMap.get(cell.key);if((mainTop==null||mainHeight==null)&&(isComplete=!1),mainTop!=null&&((maxMainTop===void 0||mainTop>maxMainTop)&&(maxMainTop=mainTop),mainHeight!=null)){let mainBottom=mainTop+mainHeight;(minMainBottom===void 0||mainBottom<minMainBottom)&&(minMainBottom=mainBottom)}}return[maxMainTop,isComplete&&minMainBottom!=null&&maxMainTop!=null?minMainBottom-maxMainTop:void 0]}updateAutoPlacementRatchets(){if(resolveDayGridPlacementMode(this.props.dayMaxEvents,this.props.dayMaxEventRows)!=="auto")return;let[,canvasHeight]=this.computeFgDims();if(canvasHeight!=null){let smallestSliceHeight=Math.min(...this.sliceHeightRefMap.current.values());this.levelCapacity=Math.max(this.levelCapacity,estimateLevelCapacity(canvasHeight,smallestSliceHeight))}}getMirrorSegs(){let{props}=this;return props.eventResize&&props.eventResize.segs.length?props.eventResize.segs:[]}getHighlightSegs(){let{props}=this;return props.eventDrag&&props.eventDrag.segs.length?props.eventDrag.segs:props.eventResize&&props.eventResize.segs.length?props.eventResize.segs:props.dateSelectionSegs}};function buildWeekNumberRenderProps(weekDateMarker,context,isNarrow,hasNavLink){let{dateEnv,options}=context,weekNum=dateEnv.computeWeekNumber(weekDateMarker),weekNumTextParts=dateEnv.formatToParts(weekDateMarker,options.weekNumberFormat||DEFAULT_WEEK_NUM_FORMAT),weekNumText=joinDateTimeFormatParts(weekNumTextParts),weekDateZoned=dateEnv.toDate(weekDateMarker);return{num:weekNum,text:weekNumText,textParts:weekNumTextParts,date:weekDateZoned,isNarrow,hasNavLink}}var DaySeriesModel=class{constructor(range,dateProfileGenerator){let date=range.start,{end}=range,entries=[],dates=[],dayIndex=-1;for(;date<end;)dateProfileGenerator.isHiddenDay(date)?entries.push({kind:"hidden",previousIndex:dayIndex,nextIndex:dayIndex+1}):(dayIndex+=1,entries.push({kind:"visible",index:dayIndex}),dates.push(date)),date=addDays4(date,1);this.rangeStart=range.start,this.dates=dates,this.entries=entries,this.cnt=dates.length}sliceRange(range){let firstResult=this.getDateIndex(range.start),lastResult=this.getDateIndex(addDays4(range.end,-1)),firstIndex=getFirstVisibleIndex(firstResult),lastIndex=getLastVisibleIndex(lastResult),clippedFirstIndex=Math.max(0,firstIndex),clippedLastIndex=Math.min(this.cnt-1,lastIndex);return clippedFirstIndex<=clippedLastIndex?{start:clippedFirstIndex,end:clippedLastIndex+1,isStart:firstResult.kind==="visible"&&firstIndex===clippedFirstIndex,isEnd:lastResult.kind==="visible"&&lastIndex===clippedLastIndex}:null}getDateIndex(date){let dayOffset=Math.floor(diffDays4(this.rangeStart,date));return dayOffset<0?{kind:"before",index:-1}:dayOffset>=this.entries.length?{kind:"after",index:this.cnt}:this.entries[dayOffset]}};function getFirstVisibleIndex(result){return result.kind==="hidden"?result.nextIndex:result.index}function getLastVisibleIndex(result){return result.kind==="hidden"?result.previousIndex:result.index}function buildDayTableModel(dateProfile,dateProfileGenerator,dateEnv){let daySeries=new DaySeriesModel(dateProfile.renderRange,dateProfileGenerator),breakOnWeeks=/year|month|week/.test(dateProfile.currentRangeUnit),majorUnit=!breakOnWeeks&&computeMajorUnit(dateProfile,dateEnv);return new DayTableModel(daySeries,breakOnWeeks,dateEnv,majorUnit!=="day"?majorUnit:void 0,dateProfile.activeRange)}function computeColWidth(colCount,colMinWidth,viewportWidth){return viewportWidth==null?[void 0,void 0]:viewportWidth/colCount<colMinWidth?[colMinWidth*colCount,colMinWidth]:[viewportWidth,void 0]}function computeTopFromDate(date,cellRows,rowHeightMap){let top=0;for(let cells of cellRows){let key=cells[0].key,start=cells[0].date,end=cells[cells.length-1].date;if(date>=start&&date<=end)return top;let rowHeight=rowHeightMap.get(key);if(rowHeight==null)return;top+=rowHeight}return top}function computeColFromPosition(positionLeft,elWidth,colWidth,colCount,isRtl){let realColWidth=colWidth??elWidth/colCount,colFromLeft=Math.floor(positionLeft/realColWidth),col=isRtl?colCount-colFromLeft-1:colFromLeft,left=colFromLeft*realColWidth,right=left+realColWidth;return{col,left,right}}function computeRowFromPosition(positionTop,cellRows,rowHeightMap){let row=0,top=0,bottom=0;for(let cells of cellRows){let key=cells[0].key;if(top=bottom,bottom=top+rowHeightMap.get(key),positionTop<bottom)break;row++}return{row,top,bottom}}function getRowEl(rootEl,row){return rootEl.querySelectorAll("[role=row]")[row]}function getCellEl(rowEl,col){return rowEl.querySelectorAll("[role=gridcell]")[col]}var dayMicroWidth=60,dayHeaderMicroFormat=createFormatter({weekday:"narrow"});function createDayHeaderFormatter(explicitFormat,datesRepDistinctDays,dateCnt){return explicitFormat||computeFallbackHeaderFormat(datesRepDistinctDays,dateCnt)}function computeFallbackHeaderFormat(datesRepDistinctDays,dayCnt){return datesRepDistinctDays?dayCnt>1?createFormatter({weekday:"short",weekdayJustify:"start",day:"numeric",omitCommas:!0,omitTrailing:!0}):createFormatter({weekday:"long",weekdayJustify:"start",day:"numeric",omitCommas:!0,omitTrailing:!0}):createFormatter({weekday:"short"})}var DayGridRows=class extends DateComponent{constructor(){super(...arguments),this.state={},this.splitBusinessHourSegs=memoize2(splitSegsByRow),this.splitBgEventSegs=memoize2(splitAllDaySegsByRow),this.splitFgEventSegs=memoize2(splitSegsByRow),this.splitDateSelectionSegs=memoize2(splitSegsByRow),this.splitEventDrag=memoize2(splitInteractionByRow),this.splitEventResize=memoize2(splitInteractionByRow),this.rowHeightRefMap=new RefMap((height,key)=>{let{rowHeightRefMap}=this.props;rowHeightRefMap&&rowHeightRefMap.handleValue(height,key)}),this.handleMoreLinkEl=el=>{this.disconnectMoreLinkHeight?.(),this.disconnectMoreLinkHeight=void 0,el&&(this.disconnectMoreLinkHeight=watchHeight(el,height=>{this._isUnmounting||this.setState({moreLinkHeight:height})}))},this.handleRootEl=rootEl=>{this.rootEl=rootEl,rootEl?this.context.registerInteractiveComponent(this,{el:rootEl,isHitComboAllowed:this.props.isHitComboAllowed}):this.context.unregisterInteractiveComponent(this)}}render(){let{props,state,context,rowHeightRefMap}=this,{options}=context,{cellRows,tableMode}=props,rowCount=cellRows.length,firstCellKey=cellRows[0]?.[0]?.key||"",fgEventSegsByRow=this.splitFgEventSegs(props.fgEventSegs,rowCount),bgEventSegsByRow=this.splitBgEventSegs(props.bgEventSegs,rowCount),businessHourSegsByRow=this.splitBusinessHourSegs(props.businessHourSegs,rowCount),dateSelectionSegsByRow=this.splitDateSelectionSegs(props.dateSelectionSegs,rowCount),eventDragByRow=this.splitEventDrag(props.eventDrag,rowCount),eventResizeByRow=this.splitEventResize(props.eventResize,rowCount),isHeightAuto=getIsHeightAuto(options),rowHeightsRedistribute=!props.forPrint&&!isHeightAuto,rowBasis=computeRowBasis(props.visibleWidth,rowCount,isHeightAuto,options),needsMoreLinkProbe=!props.forPrint&&resolveDayGridPlacementMode(props.dayMaxEvents,props.dayMaxEventRows)==="auto";return jsxs9(Fragment7,{children:[jsx12(tableMode?"tbody":"div",{role:"rowgroup",className:joinClassNames(props.className,!tableMode&&!props.forPrint&&classNames.flexCol),style:tableMode?void 0:{width:props.width},ref:this.handleRootEl,children:cellRows.map((cells,row)=>jsx12(DayGridRow,{role:"row",dateProfile:props.dateProfile,todayRange:props.todayRange,cells,cellIsNarrow:props.cellIsNarrow,cellIsMicro:props.cellIsMicro,showDayNumbers:rowCount>1,showWeekNumbers:rowCount>1&&options.weekNumbers,forPrint:props.forPrint,tableMode,borderBottom:row<rowCount-1,className:rowHeightsRedistribute?classNames.grow:void 0,fgEventSegs:fgEventSegsByRow[row],bgEventSegs:bgEventSegsByRow[row],businessHourSegs:businessHourSegsByRow[row],dateSelectionSegs:dateSelectionSegsByRow[row],eventSelection:props.eventSelection,eventDrag:eventDragByRow[row],eventResize:eventResizeByRow[row],dayMaxEvents:props.dayMaxEvents,dayMaxEventRows:props.dayMaxEventRows,colWidth:props.colWidth,basis:rowBasis,moreLinkHeight:state.moreLinkHeight,heightRef:rowHeightRefMap.createRef(cells[0].key)},firstCellKey+":"+cells[0].key))}),needsMoreLinkProbe&&jsx12(MoreLinkTrigger,{num:1,display:"row",isNarrow:props.cellIsNarrow,isMicro:props.cellIsMicro,elRef:this.handleMoreLinkEl,className:classNames.offscreen,attrs:{"aria-hidden":!0,inert:""}})]})}componentDidMount(){this._isUnmounting=!1}componentWillUnmount(){this._isUnmounting=!0,this.disconnectMoreLinkHeight?.()}queryHit(isRtl,positionLeft,positionTop,elWidth){let{props}=this,colCount=props.cellRows[0].length,{col,left,right}=computeColFromPosition(positionLeft,elWidth,props.colWidth,colCount,isRtl),{row,top,bottom}=computeRowFromPosition(positionTop,props.cellRows,this.rowHeightRefMap.current),cell=props.cellRows[row][col],cellStartDate=cell.date,cellEndDate=addDays4(cellStartDate,1);return{dateProfile:props.dateProfile,dateSpan:{range:{start:cellStartDate,end:cellEndDate},allDay:!0,...cell.dateSpanProps},getDayEl:()=>getCellEl(getRowEl(this.rootEl,row),col),rect:{left,right,top,bottom},layer:0}}};function isSegAllDay(seg){return seg.eventRange.def.allDay}function splitAllDaySegsByRow(segs,rowCnt){return splitSegsByRow(segs.filter(isSegAllDay),rowCnt)}function computeRowBasis(visibleWidth,rowCount,isHeightAuto,options){if(visibleWidth!=null){let rowBasis=visibleWidth/options.aspectRatio/6;return rowCount>6||isHeightAuto?rowBasis:0}return 0}var DayGridHeaderCell=class extends BaseComponent{constructor(){super(...arguments),this.state={},this.buildDayHeaderText=memoize2(buildDayHeaderText),this.handleInnerEl=innerEl=>{this.disconnectSize&&(this.disconnectSize(),this.disconnectSize=void 0),innerEl?this.disconnectSize=watchSize(innerEl,(width,height)=>{this._isUnmounting||(setRef(this.props.innerHeightRef,height),this.setState({innerWidth:width}))}):setRef(this.props.innerHeightRef,null)}}render(){let{props,state,context}=this,{renderConfig,dataConfig,tableMode}=props,colSpan=dataConfig.colSpan||1,totalColWidth=props.colWidth!=null?props.colWidth*colSpan:void 0,isLiquid=!tableMode&&totalColWidth==null,isSpanning=isLiquid&&colSpan>1,style=tableMode?void 0:isSpanning?{flexGrow:colSpan,flexBasis:0,minWidth:0}:{width:totalColWidth},isDisabled=dataConfig.renderProps.isDisabled,finalRenderProps=renderConfig.dayHeaderFormat?this.buildDayHeaderRenderProps(dataConfig.renderProps,props.cellIsNarrow,props.rowLevel,props.cellIsMicro,dataConfig.dateMarker,renderConfig.dayHeaderFormat,!!renderConfig.datesRepDistinctDays,context.dateEnv):{...dataConfig.renderProps,isNarrow:props.cellIsNarrow,level:props.rowLevel},alignInput=renderConfig.align,align=typeof alignInput=="function"?alignInput({level:props.rowLevel,inPopover:dataConfig.renderProps.inPopover,isNarrow:props.cellIsNarrow}):alignInput,stickyInput=renderConfig.sticky,isSticky=!tableMode&&props.rowLevel>0&&stickyInput!==!1&&(align!=="center"||totalColWidth!=null&&props.viewportWidth!=null&&totalColWidth>props.viewportWidth*.75),edgeCoord;isSticky&&(align==="center"?state.innerWidth!=null&&(edgeCoord=`calc(50% - ${state.innerWidth/2}px)`):edgeCoord=typeof stickyInput=="number"||typeof stickyInput=="string"?stickyInput:0);let alignClassName=align==="center"?classNames.alignCenter:align==="end"?classNames.alignEnd:classNames.alignStart;return jsx12(ContentContainer,{tag:tableMode?"th":"div",attrs:{role:"columnheader","aria-colspan":dataConfig.colSpan,colSpan:tableMode?colSpan:void 0,...dataConfig.attrs},className:joinClassNames(dataConfig.className,classNames.noMargin,classNames.noPadding,!tableMode&&classNames.flexCol,classNames.borderlessTop,classNames.borderlessEnd,!props.borderStart&&classNames.borderlessStart,!(tableMode&&props.borderBottom)&&classNames.borderlessBottom,!tableMode&&alignClassName,isLiquid&&!isSpanning&&classNames.liquid,!isSticky&&classNames.crop),style,renderProps:finalRenderProps,generatorName:renderConfig.generatorName,customGenerator:renderConfig.customGenerator,defaultGenerator:renderText,classNameGenerator:isDisabled?void 0:renderConfig.classNameGenerator,didMount:renderConfig.didMount,willUnmount:renderConfig.willUnmount,children:InnerContainer=>jsx12("div",{ref:this.handleInnerEl,className:joinClassNames(classNames.flexCol,classNames.noShrink,classNames.whiteSpaceNoWrap,tableMode&&alignClassName,isSticky&&classNames.sticky),style:{left:edgeCoord,right:edgeCoord},children:jsx12(InnerContainer,{tag:"div",attrs:dataConfig.innerAttrs,className:generateClassName(renderConfig.innerClassNameGenerator,finalRenderProps)})})})}componentDidMount(){this._isUnmounting=!1}componentWillUnmount(){this._isUnmounting=!0}buildDayHeaderRenderProps(renderProps,cellIsNarrow,rowLevel,cellIsMicro,dateMarker,dayHeaderFormat,datesRepDistinctDays,dateEnv){let baseText=this.buildDayHeaderText(datesRepDistinctDays?dateMarker:renderProps.date,dayHeaderFormat,datesRepDistinctDays,dateEnv),textData=cellIsMicro?this.buildDayHeaderText(dateMarker,dayHeaderMicroFormat,!1,dateEnv):baseText;return{...renderProps,isNarrow:cellIsNarrow,level:rowLevel,text:textData.text,textParts:textData.textParts,weekdayText:cellIsMicro?textData.text:baseText.weekdayText,dayNumberText:baseText.dayNumberText}}};function buildDayHeaderText(date,formatter,includeDayNumber,dateEnv){let textParts=dateEnv.formatToParts(date,formatter);return{text:joinDateTimeFormatParts(textParts),textParts,weekdayText:findWeekdayText(textParts),dayNumberText:includeDayNumber?findDayNumberText(textParts):""}}var DayGridHeaderRow=class extends BaseComponent{constructor(){super(...arguments),this.innerHeightRefMap=new RefMap(()=>{afterSize(this.handleInnerHeights)}),this.handleInnerHeights=()=>{if(this._isUnmounting)return;let innerHeightMap=this.innerHeightRefMap.current,max=0;for(let innerHeight of innerHeightMap.values())max=Math.max(max,innerHeight);this.currentInnerHeight!==max&&(this.currentInnerHeight=max,setRef(this.props.innerHeightRef,max))}}render(){let{props,context}=this,{tableMode}=props,{options}=context;return jsx12(tableMode?"tr":"div",{role:props.role,"aria-rowindex":props.rowIndex!=null?1+props.rowIndex:void 0,className:joinClassNames(options.dayHeaderRowClass,props.className,tableMode&&classNames.borderless,!tableMode&&classNames.flexRow,!tableMode&&classNames.contentBox,!tableMode&&classNames.borderlessX,!tableMode&&classNames.borderlessTop,!tableMode&&!props.borderBottom&&classNames.borderlessBottom),style:{height:props.height},children:props.dataConfigs.map((dataConfig,cellI)=>jsx12(DayGridHeaderCell,{renderConfig:props.renderConfig,dataConfig,borderStart:!!cellI,colWidth:props.colWidth,viewportWidth:props.viewportWidth,innerHeightRef:this.innerHeightRefMap.createRef(dataConfig.key),cellIsNarrow:props.cellIsNarrow,cellIsMicro:props.cellIsMicro,rowLevel:props.rowLevel,tableMode,borderBottom:props.borderBottom},dataConfig.key))})}componentDidMount(){this._isUnmounting=!1}componentWillUnmount(){this._isUnmounting=!0,this.currentInnerHeight=void 0,setRef(this.props.innerHeightRef,null)}},DayGridHeaderRows=class extends BaseComponent{render(){let{props}=this,{headerTiers,tableMode}=props;return headerTiers.map((rowConfig,i)=>createElement4(DayGridHeaderRow,{...rowConfig,key:i,role:"row",borderBottom:i<headerTiers.length-1,colWidth:props.colWidth,viewportWidth:props.viewportWidth,cellIsNarrow:props.cellIsNarrow,cellIsMicro:props.cellIsMicro,rowLevel:headerTiers.length-i-1,tableMode}))}},DayGridLayoutPrint=class extends BaseComponent{render(){let{props,context}=this,{options}=context,tableDisplayInfo={borderlessX:props.borderlessX,borderlessTop:props.borderlessTop,borderlessBottom:props.borderlessBottom,multiMonthColumns:props.multiMonthColumns};return jsxs9("table",{role:"presentation",className:joinClassNames(generateClassName(options.tableClass,tableDisplayInfo),classNames.printTable),style:props.style,children:[jsx12("colgroup",{children:props.cellRows[0].map(cell=>jsx12("col",{},cell.key))}),props.showHeader&&jsxs9("thead",{ref:props.headerElRef,role:"rowgroup",className:generateClassName(options.tableHeaderClass,{...tableDisplayInfo,isSticky:!1}),children:[jsx12(DayGridHeaderRows,{tableMode:!0,headerTiers:props.headerTiers,cellIsNarrow:props.cellIsNarrow,cellIsMicro:props.cellIsMicro}),jsx12("tr",{role:"presentation",children:jsx12("th",{role:"presentation",colSpan:props.cellRows[0].length,className:joinClassNames(classNames.noPadding,generateClassName(options.dayHeaderDividerClass,{isSticky:!1,multiMonthColumns:props.multiMonthColumns,options:{allDaySlot:!!options.allDaySlot}}))})})]}),jsx12(DayGridRows,{dateProfile:props.dateProfile,todayRange:props.todayRange,cellRows:props.cellRows,forPrint:!0,tableMode:!0,className:generateClassName(options.tableBodyClass,tableDisplayInfo),dayMaxEvents:void 0,dayMaxEventRows:props.dayMaxEventRows,fgEventSegs:props.fgEventSegs,bgEventSegs:props.bgEventSegs,businessHourSegs:props.businessHourSegs,dateSelectionSegs:[],eventDrag:null,eventResize:null,eventSelection:props.eventSelection,visibleWidth:props.visibleWidth,cellIsNarrow:props.cellIsNarrow,cellIsMicro:props.cellIsMicro,rowHeightRefMap:props.rowHeightRefMap})]})}};import{jsx as jsx13,jsxs as jsxs10,Fragment as Fragment8}from"react/jsx-runtime";import{createRef as createRef2}from"react";var DayGridHeader=class extends BaseComponent{render(){let{props}=this;return jsx13("div",{role:"rowgroup",className:joinClassNames(props.className,classNames.flexCol,props.width==null&&classNames.liquid),style:{width:props.width},children:jsx13(DayGridHeaderRows,{headerTiers:props.headerTiers,colWidth:props.colWidth,viewportWidth:props.viewportWidth,cellIsNarrow:props.cellIsNarrow,cellIsMicro:props.cellIsMicro})})}},DayGridLayoutNormal=class extends BaseComponent{constructor(){super(...arguments),this.state={},this.handleScroller=scroller=>{setRef(this.props.scrollerRef,scroller)},this.handleTotalWidth=totalWidth=>{this._isUnmounting||this.setState({totalWidth})},this.handleClientWidth=clientWidth=>{this._isUnmounting||this.setState({clientWidth})}}render(){let{props,state,context}=this,{options}=context,{borderlessX,borderlessTop,borderlessBottom}=computeViewBorderless(options),{totalWidth,clientWidth}=state,endScrollbarWidth=totalWidth!=null&&clientWidth!=null?totalWidth-clientWidth:void 0;endScrollbarWidth<3&&(endScrollbarWidth=0);let verticalScrollbars=!props.forPrint&&!getIsHeightAuto(options),tableHeaderSticky=!props.forPrint&&getTableHeaderSticky(options),colCount=props.cellRows[0].length,measuredColWidth=clientWidth!=null?clientWidth/colCount:void 0,cellIsMicro=measuredColWidth!=null&&measuredColWidth<=dayMicroWidth,cellIsNarrow=cellIsMicro||measuredColWidth!=null&&measuredColWidth<=options.dayNarrowWidth;return props.forPrint?jsx13(DayGridLayoutPrint,{dateProfile:props.dateProfile,todayRange:props.todayRange,cellRows:props.cellRows,headerTiers:props.headerTiers,showHeader:!!options.dayHeaders,fgEventSegs:props.fgEventSegs,bgEventSegs:props.bgEventSegs,businessHourSegs:props.businessHourSegs,eventSelection:props.eventSelection,dayMaxEventRows:options.dayMaxEventRows,borderlessX,borderlessTop,borderlessBottom,multiMonthColumns:0,visibleWidth:totalWidth,cellIsNarrow,cellIsMicro,rowHeightRefMap:props.rowHeightRefMap}):jsxs10(Fragment8,{children:[options.dayHeaders&&jsxs10("div",{className:joinClassNames(generateClassName(options.tableHeaderClass,{isSticky:tableHeaderSticky,borderlessX,borderlessTop,borderlessBottom,multiMonthColumns:0}),classNames.flexCol,tableHeaderSticky&&classNames.tableHeaderSticky),children:[jsxs10("div",{className:classNames.flexRow,children:[jsx13(DayGridHeader,{headerTiers:props.headerTiers,cellIsNarrow,cellIsMicro}),!!endScrollbarWidth&&jsx13("div",{className:joinClassNames(generateClassName(options.fillerClass,{inTableHeader:!0}),classNames.borderlessY,classNames.borderlessEnd),style:{minWidth:endScrollbarWidth}})]}),jsx13("div",{className:generateClassName(options.dayHeaderDividerClass,{isSticky:tableHeaderSticky,multiMonthColumns:0,options:{allDaySlot:!!options.allDaySlot}})})]}),jsx13(Scroller,{vertical:verticalScrollbars,className:joinClassNames(generateClassName(options.tableBodyClass,{borderlessX,borderlessTop,borderlessBottom,multiMonthColumns:0}),!props.forPrint&&classNames.flexCol,verticalScrollbars&&classNames.liquid),ref:this.handleScroller,clientWidthRef:this.handleClientWidth,children:jsx13(DayGridRows,{dateProfile:props.dateProfile,todayRange:props.todayRange,cellRows:props.cellRows,forPrint:props.forPrint,isHitComboAllowed:props.isHitComboAllowed,className:classNames.grow,dayMaxEvents:props.forPrint?void 0:options.dayMaxEvents,dayMaxEventRows:options.dayMaxEventRows,fgEventSegs:props.fgEventSegs,bgEventSegs:props.bgEventSegs,businessHourSegs:props.businessHourSegs,dateSelectionSegs:props.dateSelectionSegs,eventDrag:props.eventDrag,eventResize:props.eventResize,eventSelection:props.eventSelection,visibleWidth:totalWidth,cellIsNarrow,cellIsMicro,rowHeightRefMap:props.rowHeightRefMap})}),jsx13(Ruler,{widthRef:this.handleTotalWidth})]})}componentDidMount(){this._isUnmounting=!1}componentWillUnmount(){this._isUnmounting=!0}},FooterScrollbar=class extends BaseComponent{constructor(){super(...arguments),this.rootElRef=createRef2()}render(){let{props}=this;return jsx13("div",{ref:this.rootElRef,className:joinClassNames(classNames.footerScrollbar,props.isSticky&&classNames.footerScrollbarSticky),children:jsx13(Scroller,{horizontal:!0,ref:props.scrollerRef,children:jsx13("div",{style:{minWidth:props.canvasWidth}})})})}componentDidMount(){this._isUnmounting=!1,this.disconnectHeight=watchHeight(this.rootElRef.current,height=>{this._isUnmounting||setRef(this.props.scrollbarWidthRef,height)})}componentWillUnmount(){this._isUnmounting=!0,this.disconnectHeight(),setRef(this.props.scrollbarWidthRef,null)}},DayGridLayoutPannable=class extends BaseComponent{constructor(){super(...arguments),this.state={},this.headerScrollerRef=createRef2(),this.bodyScrollerRef=createRef2(),this.footerScrollerRef=createRef2(),this.handleTotalWidth=totalWidth=>{this._isUnmounting||this.setState({totalWidth})},this.handleClientWidth=clientWidth=>{this._isUnmounting||this.setState({clientWidth})}}render(){let{props,state,context}=this,{options}=context,{borderlessX,borderlessTop,borderlessBottom}=computeViewBorderless(options),{totalWidth,clientWidth}=state,endScrollbarWidth=totalWidth!=null&&clientWidth!=null?totalWidth-clientWidth:void 0,verticalScrollbars=!props.forPrint&&!getIsHeightAuto(options),tableHeaderSticky=!props.forPrint&&getTableHeaderSticky(options),footerScrollbarSticky=!props.forPrint&&getFooterScrollbarSticky(options),colCount=props.cellRows[0].length,[canvasWidth,appliedColWidth]=computeColWidth(colCount,props.dayMinWidth,clientWidth),measuredColWidth=appliedColWidth??(clientWidth!=null?clientWidth/colCount:void 0),cellIsMicro=measuredColWidth!=null&&measuredColWidth<=dayMicroWidth,cellIsNarrow=cellIsMicro||measuredColWidth!=null&&measuredColWidth<=options.dayNarrowWidth;return props.forPrint?jsx13(DayGridLayoutPrint,{dateProfile:props.dateProfile,todayRange:props.todayRange,cellRows:props.cellRows,headerTiers:props.headerTiers,showHeader:!!options.dayHeaders,fgEventSegs:props.fgEventSegs,bgEventSegs:props.bgEventSegs,businessHourSegs:props.businessHourSegs,eventSelection:props.eventSelection,dayMaxEventRows:options.dayMaxEventRows,borderlessX,borderlessTop,borderlessBottom,multiMonthColumns:0,visibleWidth:totalWidth,cellIsNarrow,cellIsMicro,rowHeightRefMap:props.rowHeightRefMap}):jsxs10(Fragment8,{children:[options.dayHeaders&&jsxs10("div",{className:joinClassNames(generateClassName(options.tableHeaderClass,{isSticky:tableHeaderSticky,borderlessX,borderlessTop,borderlessBottom,multiMonthColumns:0}),classNames.flexCol,tableHeaderSticky&&classNames.tableHeaderSticky),children:[jsxs10(Scroller,{horizontal:!0,hideScrollbars:!0,className:classNames.flexRow,ref:this.headerScrollerRef,children:[jsx13(DayGridHeader,{headerTiers:props.headerTiers,colWidth:appliedColWidth,viewportWidth:clientWidth,width:canvasWidth,cellIsNarrow,cellIsMicro}),!!endScrollbarWidth&&jsx13("div",{className:joinClassNames(generateClassName(options.fillerClass,{inTableHeader:!0}),classNames.borderlessY,classNames.borderlessEnd),style:{minWidth:endScrollbarWidth}})]}),jsx13("div",{className:generateClassName(options.dayHeaderDividerClass,{isSticky:tableHeaderSticky,multiMonthColumns:0,options:{allDaySlot:!!options.allDaySlot}})})]}),jsx13(Scroller,{vertical:verticalScrollbars,horizontal:!0,hideScrollbars:footerScrollbarSticky||props.forPrint,className:joinClassNames(generateClassName(options.tableBodyClass,{borderlessX,borderlessTop,borderlessBottom,multiMonthColumns:0}),!props.forPrint&&classNames.flexCol,verticalScrollbars&&classNames.liquid),ref:this.bodyScrollerRef,clientWidthRef:this.handleClientWidth,children:jsx13(DayGridRows,{dateProfile:props.dateProfile,todayRange:props.todayRange,cellRows:props.cellRows,forPrint:props.forPrint,isHitComboAllowed:props.isHitComboAllowed,className:classNames.grow,dayMaxEvents:props.forPrint?void 0:options.dayMaxEvents,dayMaxEventRows:options.dayMaxEventRows,fgEventSegs:props.fgEventSegs,bgEventSegs:props.bgEventSegs,businessHourSegs:props.businessHourSegs,dateSelectionSegs:props.dateSelectionSegs,eventDrag:props.eventDrag,eventResize:props.eventResize,eventSelection:props.eventSelection,colWidth:appliedColWidth,width:canvasWidth,visibleWidth:totalWidth,cellIsNarrow,cellIsMicro,rowHeightRefMap:props.rowHeightRefMap})}),!!footerScrollbarSticky&&jsx13(FooterScrollbar,{isSticky:!0,canvasWidth,scrollerRef:this.footerScrollerRef}),jsx13(Ruler,{widthRef:this.handleTotalWidth})]})}componentDidMount(){this._isUnmounting=!1;let ScrollerSyncer=getScrollerSyncerClass(this.context.pluginHooks);this.syncedScroller=new ScrollerSyncer(!0),setRef(this.props.scrollerRef,this.syncedScroller),this.updateSyncedScroller()}componentDidUpdate(){this.updateSyncedScroller()}componentWillUnmount(){this._isUnmounting=!0,this.syncedScroller.destroy()}updateSyncedScroller(){this.syncedScroller.handleChildren([this.headerScrollerRef.current,this.bodyScrollerRef.current,this.footerScrollerRef.current])}},DayGridLayout=class extends BaseComponent{constructor(){super(...arguments),this.scrollerRef=createRef2(),this.rowHeightRefMap=new RefMap(()=>{afterSize(this.updateScrollY)}),this.scrollDate=null,this.updateScrollY=()=>{if(this._isUnmounting)return;let rowHeightMap=this.rowHeightRefMap.current,scroller=this.scrollerRef.current;if(scroller&&this.scrollDate){let scrollTop=computeTopFromDate(this.scrollDate,this.props.cellRows,rowHeightMap);scrollTop!=null&&(scrollTop&&scrollTop++,scroller.scrollTo({y:scrollTop}))}},this.handleScrollEnd=isDevice=>{isDevice&&(this.scrollDate=null)}}render(){let{props,context}=this,{options}=context,{borderlessX,borderlessTop,borderlessBottom}=computeViewBorderless(options),dateSelectionSegs=props.forPrint?[]:props.dateSelectionSegs,eventDrag=props.forPrint?null:props.eventDrag,eventResize=props.forPrint?null:props.eventResize,commonLayoutProps={...props,dateSelectionSegs,eventDrag,eventResize,scrollerRef:this.scrollerRef,rowHeightRefMap:this.rowHeightRefMap};return jsx13(ViewContainer,{viewSpec:context.viewSpec,attrs:{role:"grid","aria-rowcount":props.headerTiers.length+props.cellRows.length,"aria-colcount":props.cellRows[0].length,"aria-labelledby":props.labelId,"aria-label":props.labelStr},className:joinClassNames(props.className,!props.forPrint&&classNames.flexCol,!props.forPrint&&generateClassName(options.tableClass,{borderlessX,borderlessTop,borderlessBottom,multiMonthColumns:0})),children:options.dayMinWidth?jsx13(DayGridLayoutPannable,{...commonLayoutProps,dayMinWidth:options.dayMinWidth}):jsx13(DayGridLayoutNormal,{...commonLayoutProps})})}componentDidMount(){this._isUnmounting=!1,this.props.forPrint||(this.resetScroll(),this.scrollerRef.current?.addScrollEndListener(this.handleScrollEnd))}componentDidUpdate(prevProps){prevProps.forPrint&&!this.props.forPrint&&(this.scrollerRef.current?.addScrollEndListener(this.handleScrollEnd),this.resetScroll()),prevProps.dateProfile!==this.props.dateProfile&&this.context.options.scrollTimeReset&&this.resetScroll()}componentWillUnmount(){this._isUnmounting=!0,this.scrollerRef.current?.removeScrollEndListener(this.handleScrollEnd)}resetScroll(){this.scrollDate=this.props.dateProfile.currentDate,this.updateScrollY(),this.scrollerRef.current?.scrollTo({x:0})}};var TableDateProfileGenerator=class extends DateProfileGenerator{buildRenderRange(currentRange,currentRangeUnit,isRangeAllDay){let renderRange=super.buildRenderRange(currentRange,currentRangeUnit,isRangeAllDay),{props}=this;return buildDayTableRenderRange({currentRange:renderRange,snapToWeek:/^(year|month)$/.test(currentRangeUnit),fixedWeekCount:props.fixedWeekCount,dateEnv:props.dateEnv})}};function buildDayTableRenderRange(props){let{dateEnv,currentRange}=props,{start,end}=currentRange,endOfWeek4;if(props.snapToWeek&&(start=dateEnv.startOfWeek(start),endOfWeek4=dateEnv.startOfWeek(end),endOfWeek4.valueOf()!==end.valueOf()&&(end=addWeeks3(endOfWeek4,1))),props.fixedWeekCount){let lastMonthRenderStart=dateEnv.startOfWeek(dateEnv.startOfMonth(addDays4(currentRange.end,-1))),rowCount=Math.ceil(diffWeeks4(lastMonthRenderStart,end));end=addWeeks3(end,6-rowCount)}return{start,end}}var DayGridView=class extends BaseComponent{constructor(){super(...arguments),this.buildDayTableModel=memoize2(buildDayTableModel),this.buildDateRowConfigs=memoize2(buildDateRowConfigs),this.createDayHeaderFormatter=memoize2(createDayHeaderFormatter),this.slicer=new DayTableSlicer}render(){let{props,context}=this,{dateProfile}=props,{options,dateEnv}=context,dayTableModel=this.buildDayTableModel(dateProfile,context.dateProfileGenerator,dateEnv),datesRepDistinctDays=dayTableModel.rowCount===1,dayHeaderFormat=this.createDayHeaderFormatter(context.options.dayHeaderFormat,datesRepDistinctDays,dayTableModel.colCount),slicedProps=this.slicer.sliceProps(props,dateProfile,options.nextDayThreshold,context,dayTableModel);return jsx14(NowTimer,{unit:"day",children:(nowDate,todayRange)=>{let headerTiers=this.buildDateRowConfigs(dayTableModel.headerDates,datesRepDistinctDays,dateProfile,todayRange,dayHeaderFormat,context);return jsx14(DayGridLayout,{labelId:props.labelId,labelStr:props.labelStr,dateProfile,todayRange,cellRows:dayTableModel.cellRows,forPrint:props.forPrint,className:props.className,headerTiers,fgEventSegs:slicedProps.fgEventSegs,bgEventSegs:slicedProps.bgEventSegs,businessHourSegs:slicedProps.businessHourSegs,dateSelectionSegs:slicedProps.dateSelectionSegs,eventDrag:slicedProps.eventDrag,eventResize:slicedProps.eventResize,eventSelection:slicedProps.eventSelection})}})}},dayGridPlugin={name:"daygrid",initialView:"dayGridMonth",views:{dayGrid:{component:DayGridView,dateProfileGeneratorClass:TableDateProfileGenerator},dayGridDay:{type:"dayGrid",duration:{days:1}},dayGridWeek:{type:"dayGrid",duration:{weeks:1}},dayGridMonth:{type:"dayGrid",duration:{months:1},fixedWeekCount:!0},dayGridYear:{type:"dayGrid",duration:{years:1}}}};var ElementDragging=class{constructor(el,selector){this.emitter=new Emitter}destroy(){}setMirrorIsVisible(bool){}setMirrorNeedsRevert(bool){}setAutoScrollEnabled(bool){}},config={};function isInteractionValid(interaction,dateProfile,context){let{instances}=interaction.mutatedEvents;for(let instanceId in instances)if(!rangeContainsRange(dateProfile.validRange,instances[instanceId].range))return!1;return isNewPropsValid({eventDrag:interaction},context)}function isDateSelectionValid(dateSelection,dateProfile,context){return rangeContainsRange(dateProfile.validRange,dateSelection.range)?isNewPropsValid({dateSelection},context):!1}function isNewPropsValid(newProps,context){let calendarState=context.getCurrentData(),props={businessHours:calendarState.businessHours,dateSelection:"",eventStore:calendarState.eventStore,eventUiBases:calendarState.eventUiBases,eventSelection:"",eventDrag:null,eventResize:null,...newProps};return(context.pluginHooks.isPropsValid||isPropsValid)(props,context)}function isPropsValid(state,context,dateSpanMeta={},filterConfig){return!(state.eventDrag&&!isInteractionPropsValid(state,context,dateSpanMeta,filterConfig)||state.dateSelection&&!isDateSelectionPropsValid(state,context,dateSpanMeta,filterConfig))}function isInteractionPropsValid(state,context,dateSpanMeta,filterConfig){let currentState=context.getCurrentData(),interaction=state.eventDrag,subjectEventStore=interaction.mutatedEvents,subjectDefs=subjectEventStore.defs,subjectInstances=subjectEventStore.instances,subjectConfigs=compileEventUis(subjectDefs,interaction.isEvent?state.eventUiBases:{"":currentState.selectionConfig});filterConfig&&(subjectConfigs=mapHash(subjectConfigs,filterConfig));let otherEventStore=excludeInstances(state.eventStore,interaction.affectedEvents.instances),otherDefs=otherEventStore.defs,otherInstances=otherEventStore.instances,otherConfigs=compileEventUis(otherDefs,state.eventUiBases);for(let subjectInstanceId in subjectInstances){let subjectInstance=subjectInstances[subjectInstanceId],subjectRange=subjectInstance.range,subjectConfig=subjectConfigs[subjectInstance.defId],subjectDef=subjectDefs[subjectInstance.defId];if(!allConstraintsPass(subjectConfig.constraints,subjectRange,otherEventStore,state.businessHours,context))return!1;let{eventOverlap}=context.options,eventOverlapFunc=typeof eventOverlap=="function"?eventOverlap:null;for(let otherInstanceId in otherInstances){let otherInstance=otherInstances[otherInstanceId];if(instanceRangesIntersect(subjectRange,otherInstance.range,context.dateEnv)&&(otherConfigs[otherInstance.defId].overlap===!1&&interaction.isEvent||subjectConfig.overlap===!1||eventOverlapFunc&&!eventOverlapFunc(new EventImpl(context,otherDefs[otherInstance.defId],otherInstance),new EventImpl(context,subjectDef,subjectInstance))))return!1}let calendarEventStore=currentState.eventStore;for(let subjectAllow of subjectConfig.allows){let subjectDateSpan={...dateSpanMeta,range:subjectInstance.range,allDay:subjectDef.allDay},origDef=calendarEventStore.defs[subjectDef.defId],origInstance=calendarEventStore.instances[subjectInstanceId],eventApi;if(origDef?eventApi=new EventImpl(context,origDef,origInstance):eventApi=new EventImpl(context,subjectDef),!subjectAllow(buildDateSpanApiWithContext(subjectDateSpan,context),eventApi))return!1}}return!0}function isDateSelectionPropsValid(state,context,dateSpanMeta,filterConfig){let relevantEventStore=state.eventStore,relevantDefs=relevantEventStore.defs,relevantInstances=relevantEventStore.instances,selection=state.dateSelection,selectionRange=buildEventInstanceRange(selection.range.start,selection.range.end,selection.instantStartMs,selection.instantEndMs),{selectionConfig}=context.getCurrentData();if(filterConfig&&(selectionConfig=filterConfig(selectionConfig)),!allConstraintsPass(selectionConfig.constraints,selectionRange,relevantEventStore,state.businessHours,context))return!1;let{selectOverlap}=context.options,selectOverlapFunc=typeof selectOverlap=="function"?selectOverlap:null;for(let relevantInstanceId in relevantInstances){let relevantInstance=relevantInstances[relevantInstanceId];if(instanceRangesIntersect(selectionRange,relevantInstance.range,context.dateEnv)&&(selectionConfig.overlap===!1||selectOverlapFunc&&!selectOverlapFunc(new EventImpl(context,relevantDefs[relevantInstance.defId],relevantInstance),null)))return!1}for(let selectionAllow of selectionConfig.allows){let fullDateSpan={...dateSpanMeta,...selection};if(!selectionAllow(buildDateSpanApiWithContext(fullDateSpan,context),null))return!1}return!0}function allConstraintsPass(constraints,subjectRange,otherEventStore,businessHoursUnexpanded,context){for(let constraint of constraints)if(!anyRangesContainRange(constraintToRanges(constraint,subjectRange,otherEventStore,businessHoursUnexpanded,context),subjectRange,context))return!1;return!0}function constraintToRanges(constraint,subjectRange,otherEventStore,businessHoursUnexpanded,context){return constraint==="businessHours"?eventStoreToRanges(expandRecurring(businessHoursUnexpanded,subjectRange,context)):typeof constraint=="string"?eventStoreToRanges(filterEventStoreDefs(otherEventStore,eventDef=>eventDef.groupId===constraint)):typeof constraint=="object"&&constraint?eventStoreToRanges(expandRecurring(constraint,subjectRange,context)):[]}function eventStoreToRanges(eventStore){let{instances}=eventStore,ranges=[];for(let instanceId in instances)ranges.push(instances[instanceId].range);return ranges}function anyRangesContainRange(outerRanges,innerRange,context){for(let outerRange of outerRanges)if(instanceRangeContainsRange(outerRange,innerRange,context.dateEnv))return!0;return!1}config.touchMouseIgnoreWait=500;var ignoreMouseDepth=0,listenerCnt=0,isWindowTouchMoveCancelled=!1,PointerDragging=class{constructor(containerEl){this.subjectEl=null,this.selector="",this.handleSelector="",this.shouldIgnoreMove=!1,this.shouldWatchScroll=!0,this.isDragging=!1,this.isTouchDragging=!1,this.wasTouchScroll=!1,this.handleMouseDown=ev=>{if(!this.shouldIgnoreMouse()&&isPrimaryMouseButton(ev)&&this.tryStart(ev)){let pev=this.createEventFromMouse(ev,!0);this.emitter.trigger("pointerdown",pev),this.initScrollWatch(pev),this.shouldIgnoreMove||document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseup",this.handleMouseUp)}},this.handleMouseMove=ev=>{let pev=this.createEventFromMouse(ev);this.recordCoords(pev),this.emitter.trigger("pointermove",pev)},this.handleMouseUp=ev=>{document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp),this.emitter.trigger("pointerup",this.createEventFromMouse(ev)),this.cleanup()},this.handleTouchStart=ev=>{if(this.tryStart(ev)){this.isTouchDragging=!0;let pev=this.createEventFromTouch(ev,!0);this.emitter.trigger("pointerdown",pev),this.initScrollWatch(pev);let targetEl=ev.target;this.shouldIgnoreMove||targetEl.addEventListener("touchmove",this.handleTouchMove),targetEl.addEventListener("touchend",this.handleTouchEnd),targetEl.addEventListener("touchcancel",this.handleTouchEnd),window.addEventListener("scroll",this.handleTouchScroll,!0)}},this.handleTouchMove=ev=>{if(this.isDragging){let pev=this.createEventFromTouch(ev);this.recordCoords(pev),this.emitter.trigger("pointermove",pev)}},this.handleTouchEnd=ev=>{if(this.isDragging){let targetEl=ev.target;targetEl.removeEventListener("touchmove",this.handleTouchMove),targetEl.removeEventListener("touchend",this.handleTouchEnd),targetEl.removeEventListener("touchcancel",this.handleTouchEnd),window.removeEventListener("scroll",this.handleTouchScroll,!0),this.emitter.trigger("pointerup",this.createEventFromTouch(ev)),this.cleanup(),this.isTouchDragging=!1,startIgnoringMouse()}},this.handleTouchScroll=()=>{this.wasTouchScroll=!0},this.handleScroll=ev=>{if(!this.shouldIgnoreMove){let pageX=window.scrollX-this.prevScrollX+this.prevPageX,pageY=window.scrollY-this.prevScrollY+this.prevPageY;this.emitter.trigger("pointermove",{origEvent:ev,isTouch:this.isTouchDragging,subjectEl:this.subjectEl,pageX,pageY,deltaX:pageX-this.origPageX,deltaY:pageY-this.origPageY})}},this.containerEl=containerEl,this.emitter=new Emitter,containerEl.addEventListener("mousedown",this.handleMouseDown),containerEl.addEventListener("touchstart",this.handleTouchStart,{passive:!0}),listenerCreated()}destroy(){this.containerEl.removeEventListener("mousedown",this.handleMouseDown),this.containerEl.removeEventListener("touchstart",this.handleTouchStart,{passive:!0}),listenerDestroyed()}cancel(){this.isDragging&&this.cleanup()}tryStart(ev){let subjectEl=this.querySubjectEl(ev),downEl=ev.target;return subjectEl&&(!this.handleSelector||downEl.closest(this.handleSelector))?(this.subjectEl=subjectEl,this.isDragging=!0,this.wasTouchScroll=!1,!0):!1}cleanup(){isWindowTouchMoveCancelled=!1,this.isDragging=!1,this.subjectEl=null,this.destroyScrollWatch()}querySubjectEl(ev){return this.selector?ev.target.closest(this.selector):this.containerEl}shouldIgnoreMouse(){return ignoreMouseDepth||this.isTouchDragging}cancelTouchScroll(){this.isDragging&&(isWindowTouchMoveCancelled=!0)}initScrollWatch(ev){this.shouldWatchScroll&&(this.recordCoords(ev),window.addEventListener("scroll",this.handleScroll,!0))}recordCoords(ev){this.shouldWatchScroll&&(this.prevPageX=ev.pageX,this.prevPageY=ev.pageY,this.prevScrollX=window.scrollX,this.prevScrollY=window.scrollY)}destroyScrollWatch(){this.shouldWatchScroll&&window.removeEventListener("scroll",this.handleScroll,!0)}createEventFromMouse(ev,isFirst){let deltaX=0,deltaY=0;return isFirst?(this.origPageX=ev.pageX,this.origPageY=ev.pageY):(deltaX=ev.pageX-this.origPageX,deltaY=ev.pageY-this.origPageY),{origEvent:ev,isTouch:!1,subjectEl:this.subjectEl,pageX:ev.pageX,pageY:ev.pageY,deltaX,deltaY}}createEventFromTouch(ev,isFirst){let touches=ev.touches,pageX,pageY,deltaX=0,deltaY=0;return touches&&touches.length?(pageX=touches[0].pageX,pageY=touches[0].pageY):(pageX=ev.pageX,pageY=ev.pageY),isFirst?(this.origPageX=pageX,this.origPageY=pageY):(deltaX=pageX-this.origPageX,deltaY=pageY-this.origPageY),{origEvent:ev,isTouch:!0,subjectEl:this.subjectEl,pageX,pageY,deltaX,deltaY}}};function isPrimaryMouseButton(ev){return ev.button===0&&!ev.ctrlKey}function startIgnoringMouse(){ignoreMouseDepth+=1,setTimeout(()=>{ignoreMouseDepth-=1},config.touchMouseIgnoreWait)}function listenerCreated(){listenerCnt+=1,listenerCnt===1&&window.addEventListener("touchmove",onWindowTouchMove,{passive:!1})}function listenerDestroyed(){listenerCnt-=1,listenerCnt||window.removeEventListener("touchmove",onWindowTouchMove,{passive:!1})}function onWindowTouchMove(ev){isWindowTouchMoveCancelled&&ev.preventDefault()}var ElementMirror=class{constructor(){this.isVisible=!1,this.sourceEl=null,this.mirrorEl=null,this.sourceElRect=null,this.parentNode=document.body,this.zIndex=9999,this.revertDuration=0,this.colorScheme=""}start(sourceEl,pageX,pageY){this.sourceEl=sourceEl,this.sourceElRect=this.sourceEl.getBoundingClientRect(),this.origScreenX=pageX-window.scrollX,this.origScreenY=pageY-window.scrollY,this.deltaX=0,this.deltaY=0,this.updateElPosition()}handleMove(pageX,pageY){this.deltaX=pageX-window.scrollX-this.origScreenX,this.deltaY=pageY-window.scrollY-this.origScreenY,this.updateElPosition()}setIsVisible(bool){bool?this.isVisible||(this.mirrorEl&&this.mirrorEl.style.setProperty("display","","important"),this.isVisible=bool,this.updateElPosition()):this.isVisible&&(this.mirrorEl&&this.mirrorEl.style.setProperty("display","none","important"),this.isVisible=bool)}stop(needsRevertAnimation,callback){let done=()=>{this.cleanup(),callback()};needsRevertAnimation&&this.mirrorEl&&this.isVisible&&this.revertDuration&&(this.deltaX||this.deltaY)?this.doRevertAnimation(done,this.revertDuration):setTimeout(done,0)}doRevertAnimation(callback,revertDuration){let mirrorEl=this.mirrorEl,finalSourceElRect=this.sourceEl.getBoundingClientRect();mirrorEl.style.transition="top "+revertDuration+"ms,left "+revertDuration+"ms",applyStyle(mirrorEl,{left:finalSourceElRect.left,top:finalSourceElRect.top}),whenTransitionDone(mirrorEl,()=>{mirrorEl.style.transition="",callback()})}cleanup(){this.mirrorEl&&(this.mirrorEl.remove(),this.mirrorEl=null),this.sourceEl=null}updateElPosition(){this.sourceEl&&this.isVisible&&applyStyle(this.getMirrorEl(),{left:this.sourceElRect.left+this.deltaX,top:this.sourceElRect.top+this.deltaY})}getMirrorEl(){let sourceElRect=this.sourceElRect,mirrorEl=this.mirrorEl;return mirrorEl||(mirrorEl=this.mirrorEl=this.sourceEl.cloneNode(!0),mirrorEl.style.userSelect="none",mirrorEl.style.webkitUserSelect="none",mirrorEl.style.pointerEvents="none",this.colorScheme&&mirrorEl.setAttribute("data-color-scheme",this.colorScheme),mirrorEl.classList.add(classNames.borderBoxRoot),applyStyle(mirrorEl,{position:"fixed",zIndex:this.zIndex,visibility:"",width:sourceElRect.right-sourceElRect.left,height:sourceElRect.bottom-sourceElRect.top,right:"auto",bottom:"auto",margin:0}),this.parentNode.appendChild(mirrorEl)),mirrorEl}},ScrollController=class{getMaxScrollTop(){return this.getScrollHeight()-this.getClientHeight()}getMaxScrollLeft(){return this.getScrollWidth()-this.getClientWidth()}canScrollVertically(){return this.getMaxScrollTop()>0}canScrollHorizontally(){return this.getMaxScrollLeft()>0}canScrollUp(){return this.getScrollTop()>0}canScrollDown(){return this.getScrollTop()<this.getMaxScrollTop()}canScrollLeft(){return this.getScrollLeft()>0}canScrollRight(){return this.getScrollLeft()<this.getMaxScrollLeft()}},ElementScrollController=class extends ScrollController{constructor(el){super(),this.el=el}getScrollTop(){return this.el.scrollTop}getScrollLeft(){return this.el.scrollLeft}setScrollTop(top){this.el.scrollTop=top}setScrollLeft(left){this.el.scrollLeft=left}getScrollWidth(){return this.el.scrollWidth}getScrollHeight(){return this.el.scrollHeight}getClientHeight(){return this.el.clientHeight}getClientWidth(){return this.el.clientWidth}},WindowScrollController=class extends ScrollController{getScrollTop(){return window.scrollY}getScrollLeft(){return window.scrollX}setScrollTop(n){window.scroll(window.scrollX,n)}setScrollLeft(n){window.scroll(n,window.scrollY)}getScrollWidth(){return document.documentElement.scrollWidth}getScrollHeight(){return document.documentElement.scrollHeight}getClientHeight(){return document.documentElement.clientHeight}getClientWidth(){return document.documentElement.clientWidth}},ScrollGeomCache=class extends ScrollController{constructor(scrollController,doesListening){super(),this.handleScroll=()=>{this.scrollTop=this.scrollController.getScrollTop(),this.scrollLeft=this.scrollController.getScrollLeft(),this.handleScrollChange()},this.scrollController=scrollController,this.doesListening=doesListening,this.scrollTop=this.origScrollTop=scrollController.getScrollTop(),this.scrollLeft=this.origScrollLeft=scrollController.getScrollLeft(),this.scrollWidth=scrollController.getScrollWidth(),this.scrollHeight=scrollController.getScrollHeight(),this.clientWidth=scrollController.getClientWidth(),this.clientHeight=scrollController.getClientHeight(),this.clientRect=this.computeClientRect(),this.doesListening&&this.getEventTarget().addEventListener("scroll",this.handleScroll)}destroy(){this.doesListening&&this.getEventTarget().removeEventListener("scroll",this.handleScroll)}getScrollTop(){return this.scrollTop}getScrollLeft(){return this.scrollLeft}setScrollTop(top){this.scrollController.setScrollTop(top),this.doesListening||(this.scrollTop=Math.max(Math.min(top,this.getMaxScrollTop()),0),this.handleScrollChange())}setScrollLeft(top){this.scrollController.setScrollLeft(top),this.doesListening||(this.scrollLeft=Math.max(Math.min(top,this.getMaxScrollLeft()),0),this.handleScrollChange())}getClientWidth(){return this.clientWidth}getClientHeight(){return this.clientHeight}getScrollWidth(){return this.scrollWidth}getScrollHeight(){return this.scrollHeight}handleScrollChange(){}},ElementScrollGeomCache=class extends ScrollGeomCache{constructor(el,doesListening){super(new ElementScrollController(el),doesListening)}getEventTarget(){return this.scrollController.el}computeClientRect(){return computeInnerRect(this.scrollController.el)}},WindowScrollGeomCache=class extends ScrollGeomCache{constructor(doesListening){super(new WindowScrollController,doesListening)}getEventTarget(){return window}computeClientRect(){return{left:this.scrollLeft,right:this.scrollLeft+this.clientWidth,top:this.scrollTop,bottom:this.scrollTop+this.clientHeight}}handleScrollChange(){this.clientRect=this.computeClientRect()}},getTime=typeof performance=="function"?performance.now:Date.now,AutoScroller=class{constructor(){this.isEnabled=!0,this.scrollQuery=[window,`.${classNames.internalScroller}`],this.edgeThreshold=50,this.maxVelocity=300,this.pointerScreenX=null,this.pointerScreenY=null,this.isAnimating=!1,this.scrollCaches=null,this.everMovedUp=!1,this.everMovedDown=!1,this.everMovedLeft=!1,this.everMovedRight=!1,this.animate=()=>{if(this.isAnimating){let edge=this.computeBestEdge(this.pointerScreenX+window.scrollX,this.pointerScreenY+window.scrollY);if(edge){let now=getTime();this.handleSide(edge,(now-this.msSinceRequest)/1e3),this.requestAnimation(now)}else this.isAnimating=!1}}}start(pageX,pageY,scrollStartEl){this.isEnabled&&(this.scrollCaches=this.buildCaches(scrollStartEl),this.pointerScreenX=null,this.pointerScreenY=null,this.everMovedUp=!1,this.everMovedDown=!1,this.everMovedLeft=!1,this.everMovedRight=!1,this.handleMove(pageX,pageY))}handleMove(pageX,pageY){if(this.isEnabled){let pointerScreenX=pageX-window.scrollX,pointerScreenY=pageY-window.scrollY,yDelta=this.pointerScreenY===null?0:pointerScreenY-this.pointerScreenY,xDelta=this.pointerScreenX===null?0:pointerScreenX-this.pointerScreenX;yDelta<0?this.everMovedUp=!0:yDelta>0&&(this.everMovedDown=!0),xDelta<0?this.everMovedLeft=!0:xDelta>0&&(this.everMovedRight=!0),this.pointerScreenX=pointerScreenX,this.pointerScreenY=pointerScreenY,this.isAnimating||(this.isAnimating=!0,this.requestAnimation(getTime()))}}stop(){if(this.isEnabled){this.isAnimating=!1;for(let scrollCache of this.scrollCaches)scrollCache.destroy();this.scrollCaches=null}}requestAnimation(now){this.msSinceRequest=now,requestAnimationFrame(this.animate)}handleSide(edge,seconds){let{scrollCache}=edge,{edgeThreshold}=this,invDistance=edgeThreshold-edge.distance,velocity=invDistance*invDistance/(edgeThreshold*edgeThreshold)*this.maxVelocity*seconds,sign=1;switch(edge.name){case"left":sign=-1;case"right":scrollCache.setScrollLeft(scrollCache.getScrollLeft()+velocity*sign);break;case"top":sign=-1;case"bottom":scrollCache.setScrollTop(scrollCache.getScrollTop()+velocity*sign);break}}computeBestEdge(left,top){let{edgeThreshold}=this,bestSide=null,scrollCaches=this.scrollCaches||[];for(let scrollCache of scrollCaches){let rect=scrollCache.clientRect,leftDist=left-rect.left,rightDist=rect.right-left,topDist=top-rect.top,bottomDist=rect.bottom-top;leftDist>=0&&rightDist>=0&&topDist>=0&&bottomDist>=0&&(topDist<=edgeThreshold&&this.everMovedUp&&scrollCache.canScrollUp()&&(!bestSide||bestSide.distance>topDist)&&(bestSide={scrollCache,name:"top",distance:topDist}),bottomDist<=edgeThreshold&&this.everMovedDown&&scrollCache.canScrollDown()&&(!bestSide||bestSide.distance>bottomDist)&&(bestSide={scrollCache,name:"bottom",distance:bottomDist}),leftDist<=edgeThreshold&&this.everMovedLeft&&scrollCache.canScrollLeft()&&(!bestSide||bestSide.distance>leftDist)&&(bestSide={scrollCache,name:"left",distance:leftDist}),rightDist<=edgeThreshold&&this.everMovedRight&&scrollCache.canScrollRight()&&(!bestSide||bestSide.distance>rightDist)&&(bestSide={scrollCache,name:"right",distance:rightDist}))}return bestSide}buildCaches(scrollStartEl){return this.queryScrollEls(scrollStartEl).map(el=>el===window?new WindowScrollGeomCache(!1):new ElementScrollGeomCache(el,!1))}queryScrollEls(scrollStartEl){let els=[];for(let query of this.scrollQuery)typeof query=="object"?els.push(query):els.push(...Array.prototype.slice.call(scrollStartEl.getRootNode().querySelectorAll(query)));return els}},FeaturefulElementDragging=class extends ElementDragging{constructor(containerEl,selector){super(containerEl),this.containerEl=containerEl,this.delay=null,this.minDistance=0,this.touchScrollAllowed=!0,this.mirrorNeedsRevert=!1,this.isInteracting=!1,this.isDragging=!1,this.isDelayEnded=!1,this.isDistanceSurpassed=!1,this.delayTimeoutId=null,this.onPointerDown=ev=>{this.isDragging||(this.isInteracting=!0,this.isDelayEnded=!1,this.isDistanceSurpassed=!1,this.emitter.trigger("pointerdown",ev),this.isInteracting&&(preventSelection(document.body),preventContextMenu(document.body),ev.isTouch||ev.origEvent.preventDefault(),this.mirror.setIsVisible(!1),this.mirror.start(ev.subjectEl,ev.pageX,ev.pageY),this.startDelay(ev),this.minDistance||this.handleDistanceSurpassed(ev)))},this.onPointerMove=ev=>{if(this.isInteracting){if(this.emitter.trigger("pointermove",ev),!this.isDistanceSurpassed){let minDistance=this.minDistance,distanceSq,{deltaX,deltaY}=ev;distanceSq=deltaX*deltaX+deltaY*deltaY,distanceSq>=minDistance*minDistance&&this.handleDistanceSurpassed(ev)}this.isDragging&&(ev.origEvent.type!=="scroll"&&(this.mirror.handleMove(ev.pageX,ev.pageY),this.autoScroller.handleMove(ev.pageX,ev.pageY)),this.emitter.trigger("dragmove",ev))}},this.onPointerUp=ev=>{this.isInteracting&&(this.isInteracting=!1,allowSelection(document.body),allowContextMenu(document.body),this.emitter.trigger("pointerup",ev),this.isDragging&&(this.autoScroller.stop(),this.tryStopDrag(ev)),this.delayTimeoutId&&(clearTimeout(this.delayTimeoutId),this.delayTimeoutId=null))};let pointer=this.pointer=new PointerDragging(containerEl);pointer.emitter.on("pointerdown",this.onPointerDown),pointer.emitter.on("pointermove",this.onPointerMove),pointer.emitter.on("pointerup",this.onPointerUp),selector&&(pointer.selector=selector),this.mirror=new ElementMirror,this.autoScroller=new AutoScroller}destroy(){this.pointer.destroy(),this.onPointerUp({})}startDelay(ev){typeof this.delay=="number"?this.delayTimeoutId=setTimeout(()=>{this.delayTimeoutId=null,this.handleDelayEnd(ev)},this.delay):this.handleDelayEnd(ev)}handleDelayEnd(ev){this.isDelayEnded=!0,this.tryStartDrag(ev)}handleDistanceSurpassed(ev){this.isDistanceSurpassed=!0,this.tryStartDrag(ev)}tryStartDrag(ev){this.isDelayEnded&&this.isDistanceSurpassed&&(!this.pointer.wasTouchScroll||this.touchScrollAllowed)&&(this.isDragging=!0,this.mirrorNeedsRevert=!1,this.autoScroller.start(ev.pageX,ev.pageY,this.containerEl),this.emitter.trigger("dragstart",ev),this.touchScrollAllowed===!1&&this.pointer.cancelTouchScroll())}tryStopDrag(ev){this.mirror.stop(this.mirrorNeedsRevert,this.stopDrag.bind(this,ev))}stopDrag(ev){this.isDragging=!1,this.emitter.trigger("dragend",ev)}cancel(){this.isInteracting&&(this.isInteracting=!1,this.pointer.cancel())}setMirrorIsVisible(bool){this.mirror.setIsVisible(bool)}setMirrorNeedsRevert(bool){this.mirrorNeedsRevert=bool}setAutoScrollEnabled(bool){this.autoScroller.isEnabled=bool}},OffsetTracker=class{constructor(el){this.el=el,this.origRect=computeRect(el),this.isRtl=computeElIsRtl(el),this.scrollCaches=getClippingParents(el).map(scrollEl=>new ElementScrollGeomCache(scrollEl,!0))}destroy(){for(let scrollCache of this.scrollCaches)scrollCache.destroy()}computeLeft(){let left=this.origRect.left;for(let scrollCache of this.scrollCaches)left+=scrollCache.origScrollLeft-scrollCache.getScrollLeft();return left}computeTop(){let top=this.origRect.top;for(let scrollCache of this.scrollCaches)top+=scrollCache.origScrollTop-scrollCache.getScrollTop();return top}isWithinClipping(pageX,pageY){let point={left:pageX,top:pageY};for(let scrollCache of this.scrollCaches)if(!isIgnoredClipping(scrollCache.getEventTarget())&&!pointInsideRect(point,scrollCache.clientRect))return!1;return!0}};function isIgnoredClipping(node){let tagName=node.tagName;return tagName==="HTML"||tagName==="BODY"}var HitDragging=class{constructor(dragging,droppableStore){this.useSubjectCenter=!1,this.requireInitial=!0,this.disablePointCheck=!1,this.initialHit=null,this.movingHit=null,this.finalHit=null,this.handlePointerDown=ev=>{let{dragging:dragging2}=this;this.initialHit=null,this.movingHit=null,this.finalHit=null,this.prepareHits(),this.processFirstCoord(ev),this.initialHit||!this.requireInitial?this.emitter.trigger("pointerdown",ev):dragging2.cancel()},this.handleDragStart=ev=>{this.emitter.trigger("dragstart",ev),this.handleMove(ev,!0)},this.handleDragMove=ev=>{this.emitter.trigger("dragmove",ev),this.handleMove(ev)},this.handlePointerUp=ev=>{this.releaseHits(),this.emitter.trigger("pointerup",ev)},this.handleDragEnd=ev=>{this.movingHit&&this.emitter.trigger("hitupdate",null,!0,ev),this.finalHit=this.movingHit,this.movingHit=null,this.emitter.trigger("dragend",ev)},this.droppableStore=droppableStore,dragging.emitter.on("pointerdown",this.handlePointerDown),dragging.emitter.on("dragstart",this.handleDragStart),dragging.emitter.on("dragmove",this.handleDragMove),dragging.emitter.on("pointerup",this.handlePointerUp),dragging.emitter.on("dragend",this.handleDragEnd),this.dragging=dragging,this.emitter=new Emitter}processFirstCoord(ev){let origPoint={left:ev.pageX,top:ev.pageY},adjustedPoint=origPoint,subjectEl=ev.subjectEl,subjectRect;subjectEl instanceof HTMLElement&&(subjectRect=computeRect(subjectEl),adjustedPoint=constrainPoint(adjustedPoint,subjectRect));let initialHit=this.initialHit=this.queryHitForOffset(adjustedPoint.left,adjustedPoint.top);if(initialHit){if(this.useSubjectCenter&&subjectRect){let slicedSubjectRect=intersectRects(subjectRect,initialHit.rect);slicedSubjectRect&&(adjustedPoint=getRectCenter(slicedSubjectRect))}this.coordAdjust=diffPoints(adjustedPoint,origPoint)}else this.coordAdjust={left:0,top:0}}handleMove(ev,forceHandle){let hit=this.queryHitForOffset(ev.pageX+this.coordAdjust.left,ev.pageY+this.coordAdjust.top);(forceHandle||!isHitsEqual(this.movingHit,hit))&&(this.movingHit=hit,this.emitter.trigger("hitupdate",hit,!1,ev))}prepareHits(){this.offsetTrackers=mapHash(this.droppableStore,interactionSettings=>(interactionSettings.component.prepareHits(),new OffsetTracker(interactionSettings.el)))}releaseHits(){let{offsetTrackers}=this;for(let id in offsetTrackers)offsetTrackers[id].destroy();this.offsetTrackers={}}queryHitForOffset(offsetLeft,offsetTop){let{droppableStore,offsetTrackers}=this,bestHit=null;for(let id in droppableStore){let component=droppableStore[id].component,offsetTracker=offsetTrackers[id];if(offsetTracker&&offsetTracker.isWithinClipping(offsetLeft,offsetTop)){let originLeft=offsetTracker.computeLeft(),originTop=offsetTracker.computeTop(),positionLeft=offsetLeft-originLeft,positionTop=offsetTop-originTop,{origRect}=offsetTracker,width=origRect.right-origRect.left,height=origRect.bottom-origRect.top;if(positionLeft>=0&&positionLeft<width&&positionTop>=0&&positionTop<height){let hit=component.queryHit(offsetTracker.isRtl,positionLeft,positionTop,width,height);hit&&rangeContainsRange(hit.dateProfile.activeRange,hit.dateSpan.range)&&(this.disablePointCheck||offsetTracker.el.contains(offsetTracker.el.getRootNode().elementFromPoint(positionLeft+originLeft-window.scrollX,positionTop+originTop-window.scrollY)))&&(!bestHit||hit.layer>bestHit.layer)&&(hit.componentId=id,hit.context=component.context,hit.rect.left+=originLeft,hit.rect.right+=originLeft,hit.rect.top+=originTop,hit.rect.bottom+=originTop,bestHit=hit)}}}return bestHit}};function isHitsEqual(hit0,hit1){return!hit0&&!hit1?!0:!!hit0!=!!hit1?!1:isDateSpansEqual(hit0.dateSpan,hit1.dateSpan)}function buildDatePointApiWithContext(dateSpan,context){let props={};for(let transform of context.pluginHooks.datePointTransforms)Object.assign(props,transform(dateSpan,context));return Object.assign(props,buildDatePointApi(dateSpan,context.dateEnv)),props}function buildDatePointApi(span,dateEnv){let start=buildRangeEdgeOutput(span.range.start,span.instantStartMs,dateEnv,span.allDay);return{date:start.date,dateStr:start.dateStr,allDay:span.allDay}}var DateClicking=class extends Interaction{constructor(settings){super(settings),this.handlePointerDown=pev=>{let{dragging}=this,downEl=pev.origEvent.target;this.component.context.emitter.hasHandlers("dateClick")&&this.component.isValidDateDownEl(downEl)||dragging.cancel()},this.handleDragEnd=ev=>{let{component}=this,{pointer}=this.dragging;if(!pointer.wasTouchScroll){let{initialHit,finalHit}=this.hitDragging;if(initialHit&&finalHit&&isHitsEqual(initialHit,finalHit)){let{context}=component,data={...buildDatePointApiWithContext(initialHit.dateSpan,context),dayEl:initialHit.getDayEl(),jsEvent:ev.origEvent,view:context.viewApi||context.calendarApi.view};context.emitter.trigger("dateClick",data)}}},this.dragging=new FeaturefulElementDragging(settings.el),this.dragging.autoScroller.isEnabled=!1;let hitDragging=this.hitDragging=new HitDragging(this.dragging,interactionSettingsToStore(settings));hitDragging.emitter.on("pointerdown",this.handlePointerDown),hitDragging.emitter.on("dragend",this.handleDragEnd)}destroy(){this.dragging.destroy()}},DateSelecting=class extends Interaction{constructor(settings){super(settings),this.dragSelection=null,this.handlePointerDown=ev=>{let{component:component2,dragging:dragging2}=this,{options:options2}=component2.context;options2.selectable&&component2.isValidDateDownEl(ev.origEvent.target)?dragging2.delay=ev.isTouch?getComponentTouchDelay$1(component2):null:dragging2.cancel()},this.handleDragStart=ev=>{this.component.context.calendarApi.unselect(ev)},this.handleHitUpdate=(hit,isFinal)=>{let{context}=this.component,dragSelection=null,isInvalid=!1;if(hit){let initialHit=this.hitDragging.initialHit;hit.componentId===initialHit.componentId&&this.isHitComboAllowed&&!this.isHitComboAllowed(initialHit,hit)||(dragSelection=joinHitsIntoSelection(initialHit,hit,context.pluginHooks.dateSelectionTransformers)),(!dragSelection||!isDateSelectionValid(dragSelection,hit.dateProfile,context))&&(isInvalid=!0,dragSelection=null)}dragSelection?context.dispatch({type:"SELECT_DATES",selection:dragSelection}):isFinal||context.dispatch({type:"UNSELECT_DATES"}),isInvalid?disableCursor():enableCursor(),isFinal||(this.dragSelection=dragSelection)},this.handlePointerUp=pev=>{this.dragSelection?(triggerDateSelect(this.dragSelection,pev,this.component.context),this.dragSelection=null):this.component.context.emitter.trigger("_noDateSelect")};let{component}=settings,{options}=component.context,dragging=this.dragging=new FeaturefulElementDragging(settings.el);dragging.touchScrollAllowed=!1,dragging.minDistance=options.selectMinDistance||0,dragging.autoScroller.isEnabled=options.dragScroll;let hitDragging=this.hitDragging=new HitDragging(this.dragging,interactionSettingsToStore(settings));hitDragging.emitter.on("pointerdown",this.handlePointerDown),hitDragging.emitter.on("dragstart",this.handleDragStart),hitDragging.emitter.on("hitupdate",this.handleHitUpdate),hitDragging.emitter.on("pointerup",this.handlePointerUp)}destroy(){this.dragging.destroy()}};function getComponentTouchDelay$1(component){let{options}=component.context,delay=options.selectLongPressDelay;return delay==null&&(delay=options.longPressDelay),delay}function joinHitsIntoSelection(hit0,hit1,dateSelectionTransformers){let dateSpan0=hit0.dateSpan,dateSpan1=hit1.dateSpan,hasInstants=dateSpan0.instantStartMs!=null||dateSpan1.instantStartMs!=null,entries=[{date:dateSpan0.range.start,ms:getDateSpanInstantStartMs(dateSpan0,hit0.context.dateEnv)},{date:dateSpan0.range.end,ms:getDateSpanInstantEndMs(dateSpan0,hit0.context.dateEnv)},{date:dateSpan1.range.start,ms:getDateSpanInstantStartMs(dateSpan1,hit1.context.dateEnv)},{date:dateSpan1.range.end,ms:getDateSpanInstantEndMs(dateSpan1,hit1.context.dateEnv)}];entries.sort(hasInstants?(entry0,entry1)=>compareNumbers2(entry0.ms,entry1.ms):(entry0,entry1)=>compareNumbers2(entry0.date.valueOf(),entry1.date.valueOf()));let props={};for(let transformer of dateSelectionTransformers){let res=transformer(hit0,hit1);if(res===!1)return null;res&&Object.assign(props,res)}if(hasInstants){let validRange=buildValidInstanceRange({marker:entries[0].date,instantMs:entries[0].ms},{marker:entries[3].date,instantMs:entries[3].ms},hit0.context.dateEnv);if(!validRange)return null;props.range={start:validRange.start,end:validRange.end}}else props.range={start:entries[0].date,end:entries[3].date};return props.allDay=dateSpan0.allDay,hasInstants&&(props.instantStartMs=entries[0].ms,props.instantEndMs=entries[3].ms),props}function computeHitInstantDeltaMs(hit0,hit1){let startMs0=hit0.dateSpan.allDay?null:hit0.dateSpan.instantStartMs,startMs1=hit1.dateSpan.allDay?null:hit1.dateSpan.instantStartMs;return startMs0!=null&&startMs1!=null?startMs1-startMs0:null}function computeHitDelta(hit0,hit1,options={}){let instantDeltaMs=computeHitInstantDeltaMs(hit0,hit1),date0=options.date0||hit0.dateSpan.range.start,date1=options.date1||hit1.dateSpan.range.start;return{delta:instantDeltaMs!=null?createDuration(instantDeltaMs):diffDates(date0,date1,hit0.context.dateEnv,options.largeUnit),instantDeltaMs}}var EventDragging=class _EventDragging extends Interaction{constructor(settings){super(settings),this.subjectEl=null,this.isDragging=!1,this.eventRange=null,this.relevantEvents=null,this.receivingContext=null,this.validMutation=null,this.mutatedRelevantEvents=null,this.handlePointerDown=ev=>{let origTarget=ev.origEvent.target,{component:component2,dragging:dragging2}=this,{mirror}=dragging2,{options:options2}=component2.context,initialContext=component2.context;this.subjectEl=ev.subjectEl;let eventInstanceId=(this.eventRange=getElEventRange(ev.subjectEl)).instance.instanceId;this.relevantEvents=getRelevantEvents(initialContext.getCurrentData().eventStore,eventInstanceId),dragging2.minDistance=ev.isTouch?0:options2.eventDragMinDistance,dragging2.delay=ev.isTouch&&eventInstanceId!==component2.props.eventSelection?getComponentTouchDelay(component2):null,mirror.parentNode=getAppendableRoot(origTarget),mirror.revertDuration=options2.dragRevertDuration,mirror.colorScheme=options2.colorScheme||"",component2.isValidSegDownEl(origTarget)&&!origTarget.closest(`.${classNames.internalEventResizer}`)?this.isDragging=ev.subjectEl.classList.contains(classNames.internalEventDraggable):dragging2.cancel()},this.handleDragStart=ev=>{let initialContext=this.component.context,eventRange=this.eventRange,eventInstanceId=eventRange.instance.instanceId;ev.isTouch?eventInstanceId!==this.component.props.eventSelection&&initialContext.dispatch({type:"SELECT_EVENT",eventInstanceId}):initialContext.dispatch({type:"UNSELECT_EVENT"}),this.isDragging&&(initialContext.calendarApi.unselect(ev),initialContext.emitter.trigger("eventDragStart",{el:this.subjectEl,event:new EventImpl(initialContext,eventRange.def,eventRange.instance),jsEvent:ev.origEvent,view:initialContext.viewApi}))},this.handleHitUpdate=(hit,isFinal)=>{if(!this.isDragging)return;let relevantEvents=this.relevantEvents,initialHit=this.hitDragging.initialHit,initialContext=this.component.context,receivingContext=null,mutation=null,mutatedRelevantEvents=null,isInvalid=!1,interaction={affectedEvents:relevantEvents,mutatedEvents:createEmptyEventStore(),isEvent:!0};if(hit){receivingContext=hit.context;let receivingOptions=receivingContext.options;initialContext===receivingContext||receivingOptions.editable&&receivingOptions.droppable?(mutation=computeEventMutation(initialHit,hit,this.eventRange.instance.range.start,receivingContext.getCurrentData().pluginHooks.eventDragMutationMassagers),mutation&&(mutatedRelevantEvents=applyMutationToEventStore(relevantEvents,receivingContext.getCurrentData().eventUiBases,mutation,receivingContext),interaction.mutatedEvents=mutatedRelevantEvents,isInteractionValid(interaction,hit.dateProfile,receivingContext)||(isInvalid=!0,mutation=null,mutatedRelevantEvents=null,interaction.mutatedEvents=createEmptyEventStore()))):receivingContext=null}this.displayDrag(receivingContext,interaction),isInvalid?disableCursor():enableCursor(),isFinal||(initialContext===receivingContext&&isHitsEqual(initialHit,hit)&&(mutation=null),this.dragging.setMirrorNeedsRevert(!mutation),this.dragging.setMirrorIsVisible(!hit||!this.subjectEl.getRootNode().querySelector(`.${classNames.internalEventMirror}`)),this.receivingContext=receivingContext,this.validMutation=mutation,this.mutatedRelevantEvents=mutatedRelevantEvents)},this.handlePointerUp=()=>{this.isDragging||this.cleanup()},this.handleDragEnd=ev=>{if(this.isDragging){let initialContext=this.component.context,initialView=initialContext.viewApi,{receivingContext,validMutation}=this,eventDef=this.eventRange.def,eventInstance=this.eventRange.instance,eventApi=new EventImpl(initialContext,eventDef,eventInstance),relevantEvents=this.relevantEvents,mutatedRelevantEvents=this.mutatedRelevantEvents,{finalHit}=this.hitDragging;if(this.clearDrag(),initialContext.emitter.trigger("eventDragStop",{el:this.subjectEl,event:eventApi,jsEvent:ev.origEvent,view:initialView}),validMutation){if(receivingContext===initialContext){let updatedEventApi=new EventImpl(initialContext,mutatedRelevantEvents.defs[eventDef.defId],eventInstance?mutatedRelevantEvents.instances[eventInstance.instanceId]:null);initialContext.dispatch({type:"MERGE_EVENTS",eventStore:mutatedRelevantEvents});let eventChangeData={oldEvent:eventApi,event:updatedEventApi,relatedEvents:buildEventApis(mutatedRelevantEvents,initialContext,eventInstance),revert(){initialContext.dispatch({type:"MERGE_EVENTS",eventStore:relevantEvents})}},transformed={};for(let transformer of initialContext.getCurrentData().pluginHooks.eventDropTransformers)Object.assign(transformed,transformer(validMutation,initialContext));initialContext.emitter.trigger("eventDrop",{...eventChangeData,...transformed,el:ev.subjectEl,delta:validMutation.datesDelta,jsEvent:ev.origEvent,view:initialView}),initialContext.emitter.trigger("eventChange",eventChangeData)}else if(receivingContext){let eventRemoveData={event:eventApi,relatedEvents:buildEventApis(relevantEvents,initialContext,eventInstance),revert(){initialContext.dispatch({type:"MERGE_EVENTS",eventStore:relevantEvents})}};initialContext.emitter.trigger("eventLeave",{...eventRemoveData,draggedEl:ev.subjectEl,view:initialView}),initialContext.dispatch({type:"REMOVE_EVENTS",eventStore:relevantEvents}),initialContext.emitter.trigger("eventRemove",eventRemoveData);let addedEventDef=mutatedRelevantEvents.defs[eventDef.defId],addedEventInstance=mutatedRelevantEvents.instances[eventInstance.instanceId],addedEventApi=new EventImpl(receivingContext,addedEventDef,addedEventInstance);receivingContext.dispatch({type:"MERGE_EVENTS",eventStore:mutatedRelevantEvents});let eventAddData={event:addedEventApi,relatedEvents:buildEventApis(mutatedRelevantEvents,receivingContext,addedEventInstance),revert(){receivingContext.dispatch({type:"REMOVE_EVENTS",eventStore:mutatedRelevantEvents})}};receivingContext.emitter.trigger("eventAdd",eventAddData),ev.isTouch&&receivingContext.dispatch({type:"SELECT_EVENT",eventInstanceId:eventInstance.instanceId}),receivingContext.emitter.trigger("drop",{...buildDatePointApiWithContext(finalHit.dateSpan,receivingContext),draggedEl:ev.subjectEl,jsEvent:ev.origEvent,view:finalHit.context.viewApi}),receivingContext.emitter.trigger("eventReceive",{...eventAddData,draggedEl:ev.subjectEl,view:finalHit.context.viewApi})}}else initialContext.emitter.trigger("_noEventDrop")}this.cleanup()};let{component}=this,{options}=component.context,dragging=this.dragging=new FeaturefulElementDragging(settings.el);dragging.pointer.selector=_EventDragging.SELECTOR,dragging.touchScrollAllowed=!1,dragging.autoScroller.isEnabled=options.dragScroll;let hitDragging=this.hitDragging=new HitDragging(this.dragging,interactionSettingsStore);hitDragging.useSubjectCenter=settings.useEventCenter,hitDragging.emitter.on("pointerdown",this.handlePointerDown),hitDragging.emitter.on("dragstart",this.handleDragStart),hitDragging.emitter.on("hitupdate",this.handleHitUpdate),hitDragging.emitter.on("pointerup",this.handlePointerUp),hitDragging.emitter.on("dragend",this.handleDragEnd)}destroy(){this.dragging.destroy()}displayDrag(nextContext,state){let initialContext=this.component.context,prevContext=this.receivingContext;prevContext&&prevContext!==nextContext&&(prevContext===initialContext?prevContext.dispatch({type:"SET_EVENT_DRAG",state:{affectedEvents:state.affectedEvents,mutatedEvents:createEmptyEventStore(),isEvent:!0}}):prevContext.dispatch({type:"UNSET_EVENT_DRAG"})),nextContext&&nextContext.dispatch({type:"SET_EVENT_DRAG",state})}clearDrag(){let initialCalendar=this.component.context,{receivingContext}=this;receivingContext&&receivingContext.dispatch({type:"UNSET_EVENT_DRAG"}),initialCalendar!==receivingContext&&initialCalendar.dispatch({type:"UNSET_EVENT_DRAG"})}cleanup(){this.isDragging=!1,this.eventRange=null,this.relevantEvents=null,this.receivingContext=null,this.validMutation=null,this.mutatedRelevantEvents=null}};EventDragging.SELECTOR=`.${classNames.internalEventDraggable}, .${classNames.internalEventResizable}`;function computeEventMutation(hit0,hit1,eventInstanceStart,massagers){let dateSpan0=hit0.dateSpan,dateSpan1=hit1.dateSpan,date0=dateSpan0.range.start,date1=dateSpan1.range.start,standardProps={};dateSpan0.allDay!==dateSpan1.allDay&&(standardProps.allDay=dateSpan1.allDay,standardProps.hasEnd=hit1.context.options.allDayMaintainDuration,dateSpan1.allDay?date0=startOfDay5(eventInstanceStart):date0=eventInstanceStart);let{delta,instantDeltaMs}=computeHitDelta(hit0,hit1,{date0,date1,largeUnit:hit0.componentId===hit1.componentId?hit0.largeUnit:null});delta.milliseconds&&(standardProps.allDay=!1);let mutation={datesDelta:delta,...instantDeltaMs!=null?{instantDatesDeltaMs:instantDeltaMs}:{},standardProps};for(let massager of massagers)massager(mutation,hit0,hit1);return mutation}function getComponentTouchDelay(component){let{options}=component.context,delay=options.eventLongPressDelay;return delay==null&&(delay=options.longPressDelay),delay}var EventResizing=class extends Interaction{constructor(settings){super(settings),this.draggingSegEl=null,this.draggingEventRange=null,this.eventRange=null,this.relevantEvents=null,this.validMutation=null,this.mutatedRelevantEvents=null,this.handlePointerDown=ev=>{let{component:component2}=this,segEl=this.querySegEl(ev),eventRange=this.eventRange=getElEventRange(segEl);this.dragging.minDistance=component2.context.options.eventDragMinDistance,this.component.isValidSegDownEl(ev.origEvent.target)&&!(ev.isTouch&&this.component.props.eventSelection!==eventRange.instance.instanceId)||this.dragging.cancel()},this.handleDragStart=ev=>{let{context}=this.component,eventRange=this.eventRange;this.relevantEvents=getRelevantEvents(context.getCurrentData().eventStore,this.eventRange.instance.instanceId);let segEl=this.querySegEl(ev);this.draggingSegEl=segEl,this.draggingEventRange=getElEventRange(segEl),context.calendarApi.unselect(),context.emitter.trigger("eventResizeStart",{el:segEl,event:new EventImpl(context,eventRange.def,eventRange.instance),jsEvent:ev.origEvent,view:context.viewApi})},this.handleHitUpdate=(hit,isFinal,ev)=>{let{context}=this.component,relevantEvents=this.relevantEvents,initialHit=this.hitDragging.initialHit,eventInstance=this.eventRange.instance,mutation=null,mutatedRelevantEvents=null,isInvalid=!1,interaction={affectedEvents:relevantEvents,mutatedEvents:createEmptyEventStore(),isEvent:!0};hit&&(hit.componentId===initialHit.componentId&&this.isHitComboAllowed&&!this.isHitComboAllowed(initialHit,hit)||(mutation=computeMutation(initialHit,hit,ev.subjectEl.classList.contains(classNames.internalEventResizerStart),eventInstance.range))),mutation&&(mutatedRelevantEvents=applyMutationToEventStore(relevantEvents,context.getCurrentData().eventUiBases,mutation,context),interaction.mutatedEvents=mutatedRelevantEvents,isInteractionValid(interaction,hit.dateProfile,context)||(isInvalid=!0,mutation=null,mutatedRelevantEvents=null,interaction.mutatedEvents=null)),mutatedRelevantEvents?context.dispatch({type:"SET_EVENT_RESIZE",state:interaction}):context.dispatch({type:"UNSET_EVENT_RESIZE"}),isInvalid?disableCursor():enableCursor(),isFinal||(mutation&&isHitsEqual(initialHit,hit)&&(mutation=null),this.validMutation=mutation,this.mutatedRelevantEvents=mutatedRelevantEvents)},this.handleDragEnd=ev=>{let{context}=this.component,eventDef=this.eventRange.def,eventInstance=this.eventRange.instance,eventApi=new EventImpl(context,eventDef,eventInstance),relevantEvents=this.relevantEvents,mutatedRelevantEvents=this.mutatedRelevantEvents;if(context.emitter.trigger("eventResizeStop",{el:this.draggingSegEl,event:eventApi,jsEvent:ev.origEvent,view:context.viewApi}),this.validMutation){let updatedEventApi=new EventImpl(context,mutatedRelevantEvents.defs[eventDef.defId],eventInstance?mutatedRelevantEvents.instances[eventInstance.instanceId]:null);context.dispatch({type:"MERGE_EVENTS",eventStore:mutatedRelevantEvents});let eventChangeData={oldEvent:eventApi,event:updatedEventApi,relatedEvents:buildEventApis(mutatedRelevantEvents,context,eventInstance),revert(){context.dispatch({type:"MERGE_EVENTS",eventStore:relevantEvents})}};context.emitter.trigger("eventResize",{...eventChangeData,el:this.draggingSegEl,startDelta:this.validMutation.startDelta||createDuration(0),endDelta:this.validMutation.endDelta||createDuration(0),jsEvent:ev.origEvent,view:context.viewApi}),context.emitter.trigger("eventChange",eventChangeData)}else context.emitter.trigger("_noEventResize");this.draggingEventRange=null,this.relevantEvents=null,this.validMutation=null};let{component}=settings,dragging=this.dragging=new FeaturefulElementDragging(settings.el);dragging.pointer.selector=`.${classNames.internalEventResizer}`,dragging.touchScrollAllowed=!1,dragging.autoScroller.isEnabled=component.context.options.dragScroll;let hitDragging=this.hitDragging=new HitDragging(this.dragging,interactionSettingsToStore(settings));hitDragging.emitter.on("pointerdown",this.handlePointerDown),hitDragging.emitter.on("dragstart",this.handleDragStart),hitDragging.emitter.on("hitupdate",this.handleHitUpdate),hitDragging.emitter.on("dragend",this.handleDragEnd)}destroy(){this.dragging.destroy()}querySegEl(ev){return ev.subjectEl.closest(`.${classNames.internalEvent}`)}};function computeMutation(hit0,hit1,isFromStart,instanceRange){let{context}=hit0,date0=hit0.dateSpan.range.start,date1=hit1.dateSpan.range.start,{delta,instantDeltaMs}=computeHitDelta(hit0,hit1,{date0,date1,largeUnit:hit0.largeUnit});if(isFromStart){let newStart=addDeltaToRangeEdge(instanceRange.start,instanceRange.instantStartMs,delta,instantDeltaMs??void 0,context);if(newStart.instantMs!=null?newStart.instantMs<getRangeInstantEndMs(instanceRange,context.dateEnv):newStart.marker<instanceRange.end)return{startDelta:delta,...instantDeltaMs!=null?{instantStartDeltaMs:instantDeltaMs}:{}}}else{let newEnd=addDeltaToRangeEdge(instanceRange.end,instanceRange.instantEndMs,delta,instantDeltaMs??void 0,context);if(newEnd.instantMs!=null?newEnd.instantMs>getRangeInstantStartMs(instanceRange,context.dateEnv):newEnd.marker>instanceRange.start)return{endDelta:delta,...instantDeltaMs!=null?{instantEndDeltaMs:instantDeltaMs}:{}}}return null}var UnselectAuto=class{constructor(context){this.context=context,this.isRecentPointerDateSelect=!1,this.matchesCancel=!1,this.matchesEvent=!1,this.onSelect=selectInfo=>{selectInfo.jsEvent&&(this.isRecentPointerDateSelect=!0)},this.onDocumentPointerDown=pev=>{let unselectCancel=this.context.options.unselectCancel,downEl=getEventTargetViaRoot(pev.origEvent);this.matchesCancel=!!downEl.closest(unselectCancel),this.matchesEvent=!!downEl.closest(EventDragging.SELECTOR)},this.onDocumentPointerUp=pev=>{let{context:context2}=this,{documentPointer:documentPointer2}=this,calendarState=context2.getCurrentData();if(!documentPointer2.wasTouchScroll){if(calendarState.dateSelection&&!this.isRecentPointerDateSelect){let unselectAuto=context2.options.unselectAuto;unselectAuto&&(!unselectAuto||!this.matchesCancel)&&context2.calendarApi.unselect(pev)}calendarState.eventSelection&&!this.matchesEvent&&context2.dispatch({type:"UNSELECT_EVENT"})}this.isRecentPointerDateSelect=!1};let documentPointer=this.documentPointer=new PointerDragging(document);documentPointer.shouldIgnoreMove=!0,documentPointer.shouldWatchScroll=!1,documentPointer.emitter.on("pointerdown",this.onDocumentPointerDown),documentPointer.emitter.on("pointerup",this.onDocumentPointerUp),context.emitter.on("select",this.onSelect)}destroy(){this.context.emitter.off("select",this.onSelect),this.documentPointer.destroy()}},interactionPlugin={name:"interaction",componentInteractions:[DateClicking,DateSelecting,EventDragging,EventResizing],calendarInteractions:[UnselectAuto],elementDraggingImpl:FeaturefulElementDragging};config.dataAttrPrefix="";import{jsx as jsx15,jsxs as jsxs11}from"react/jsx-runtime";var xxsTextClass="fc-classic-vQz",outlineWidthClass="fc-classic-0Bj",outlineWidthFocusClass="fc-classic-uqo",outlineOffsetClass="fc-classic-3Xj",outlineInsetClass="fc-classic-fFh",primaryOutlineColorClass="fc-classic-zIi",strongSolidPressableClass="fc-classic-BaR",mutedHoverClass="fc-classic-4yP",mutedHoverPressableClass=`${mutedHoverClass} fc-classic-tCP fc-classic-8gz`,faintHoverClass="fc-classic-Ubk",faintHoverPressableClass=`${faintHoverClass} fc-classic-OIx fc-classic-28F`,buttonIconClass="fc-classic-XUJ",blockPointerResizerClass="fc-classic-1EY fc-classic-pps fc-classic-vs6",rowPointerResizerClass=`${blockPointerResizerClass} fc-classic-AWB fc-classic-hza`,columnPointerResizerClass=`${blockPointerResizerClass} fc-classic-MaV fc-classic-uuA`,blockTouchResizerClass="fc-classic-1EY fc-classic-3wQ fc-classic-wsy fc-classic-lNM fc-classic-Jk3 fc-classic-AAA",rowTouchResizerClass=`${blockTouchResizerClass} fc-classic-ERR fc-classic-Dq8`,columnTouchResizerClass=`${blockTouchResizerClass} fc-classic-1V6 fc-classic-F99`,getDayClass=info=>joinClassNames("fc-classic-wsy",info.isMajor?"fc-classic-C0k":"fc-classic-C1x",info.isDisabled?"fc-classic-iYS":info.isToday&&"fc-classic-hbn"),getSlotClass=info=>joinClassNames("fc-classic-wsy fc-classic-C1x",info.isMinor&&"fc-classic-TN2"),dayRowCommonClasses={listItemEventClass:info=>joinClassNames("fc-classic-Ika fc-classic-7A6 fc-classic-Fvv",info.isNarrow?"fc-classic-148":"fc-classic-cKZ",info.isSelected?joinClassNames("fc-classic-k3f",info.isDragging&&"fc-classic-qNs"):info.isInteractive?mutedHoverPressableClass:mutedHoverClass),listItemEventBeforeClass:info=>joinClassNames("fc-classic-Mjo",info.isNarrow?"fc-classic-148":"fc-classic-rVY"),listItemEventInnerClass:info=>joinClassNames("fc-classic-dl1 fc-classic-1sP fc-classic-XpK fc-classic-z5u fc-classic-aTF",info.isNarrow?xxsTextClass:"fc-classic-a3B"),listItemEventTimeClass:"fc-classic-F1o fc-classic-TZ4 fc-classic-pKG fc-classic-1Zl",listItemEventTitleClass:"fc-classic-F1o fc-classic-DIS fc-classic-TZ4 fc-classic-pKG fc-classic-OLq",rowEventClass:info=>joinClassNames(info.isStart&&joinClassNames("fc-classic-kmj",info.isNarrow?"fc-classic-qvL":"fc-classic-Jzj"),info.isEnd&&joinClassNames("fc-classic-Skl",info.isNarrow?"fc-classic-9hC":"fc-classic-3e1")),rowEventInnerClass:"fc-classic-z5u fc-classic-aTF",rowEventTimeClass:"fc-classic-F1o",rowEventTitleClass:"fc-classic-F1o",rowMoreLinkClass:info=>joinClassNames("fc-classic-Ika fc-classic-wsy fc-classic-Fvv",info.isNarrow?"fc-classic-148 fc-classic-0Pr":"fc-classic-sI7 fc-classic-cKZ fc-classic-d0j",mutedHoverPressableClass),rowMoreLinkInnerClass:info=>joinClassNames("fc-classic-7A6",info.isNarrow?xxsTextClass:"fc-classic-a3B")},expanderIconClass="fc-classic-vnf fc-classic-mAY",continuationArrowClass="fc-classic-rVY fc-classic-XM3 fc-classic-rif fc-classic-lMo",index={name:"theme-classic",optionDefaults:{className:"fc-classic-yth fc-classic-n5m",viewClass:info=>{let hasBorderTop=info.options.headerToolbar||!info.borderlessTop,hasBorderBottom=info.options.footerToolbar||!info.borderlessBottom,hasBorderX=!info.borderlessX;return joinClassNames("fc-classic-Jk3 fc-classic-GAX fc-classic-C1x",hasBorderTop&&"fc-classic-ku3",hasBorderBottom&&"fc-classic-zi1",hasBorderX&&"fc-classic-1Wx")},toolbarClass:info=>joinClassNames("fc-classic-dl1 fc-classic-1sP fc-classic-dNl fc-classic-XpK fc-classic-N2M fc-classic-wwb",info.borderlessX&&"fc-classic-Apf"),toolbarSectionClass:"fc-classic-yi0 fc-classic-dl1 fc-classic-1sP fc-classic-XpK fc-classic-wwb",toolbarTitleClass:"fc-classic-AVD fc-classic-DIS",buttonGroupClass:"fc-classic-dl1 fc-classic-1sP fc-classic-XpK",buttonClass:info=>joinClassNames("fc-classic-dl6 fc-classic-1Wx fc-classic-dl1 fc-classic-1sP fc-classic-XpK fc-classic-sOR fc-classic-lYz fc-classic-vwH fc-classic-9yp fc-classic-RnT fc-classic-cfp fc-classic-Z9U",info.isIconOnly?"fc-classic-Eaq":"fc-classic-Apf",info.buttonGroup?"fc-classic-uk6 fc-classic-Tuc":"fc-classic-Ig4",info.isSelected?"fc-classic-rQI fc-classic-Adi":"fc-classic-vXO fc-classic-bqK fc-classic-aIH fc-classic-nQ5 fc-classic-JWq fc-classic-9Rj fc-classic-5ky",info.isDisabled&&"fc-classic-Q3Z fc-classic-3Lc"),buttons:{prev:{iconContent:()=>chevronLeft(`${buttonIconClass} fc-classic-asP`)},next:{iconContent:()=>chevronLeft(`${buttonIconClass} fc-classic-jmT fc-classic-jY6`)},prevYear:{iconContent:()=>chevronsLeft(`${buttonIconClass} fc-classic-asP`)},nextYear:{iconContent:()=>chevronsLeft(`${buttonIconClass} fc-classic-jmT fc-classic-jY6`)}},eventColor:"var(--fc-classic-event)",eventContrastColor:"var(--fc-classic-event-contrast)",eventClass:info=>joinClassNames(info.isDragging&&"fc-classic-n5m",info.event.url&&"fc-classic-JiE",info.isSelected?joinClassNames(outlineWidthClass,info.isDragging?"fc-classic-1kP":"fc-classic-tkw"):outlineWidthFocusClass,primaryOutlineColorClass),backgroundEventColor:"var(--fc-classic-background-event)",backgroundEventClass:"fc-classic-hsC fc-classic-jsy fc-classic-DO7",backgroundEventTitleClass:info=>joinClassNames("fc-classic-MGT fc-classic-L1Y",info.isNarrow?`fc-classic-KUX ${xxsTextClass}`:"fc-classic-XJa fc-classic-a3B"),listItemEventClass:"fc-classic-XpK",listItemEventBeforeClass:"fc-classic-lNM fc-classic-AAA",listItemEventInnerClass:"fc-classic-GAX",blockEventClass:info=>joinClassNames("fc-classic-bCs fc-classic-eYX fc-classic-d0j fc-classic-DO7 fc-classic-YjJ fc-classic-vwH",info.isDragging&&!info.isSelected&&"fc-classic-iTG",outlineOffsetClass),blockEventInnerClass:"fc-classic-i9F fc-classic-cfp",blockEventTimeClass:"fc-classic-TZ4 fc-classic-pKG fc-classic-1Zl",blockEventTitleClass:"fc-classic-TZ4 fc-classic-pKG fc-classic-OLq",rowEventClass:info=>joinClassNames("fc-classic-Ika fc-classic-JIC",info.isStart&&"fc-classic-3J4",info.isEnd&&"fc-classic-USt"),rowEventBeforeClass:info=>joinClassNames(info.isStartResizable&&joinClassNames(info.isSelected?rowTouchResizerClass:rowPointerResizerClass,"fc-classic-11a")),rowEventAfterClass:info=>joinClassNames(info.isEndResizable&&joinClassNames(info.isSelected?rowTouchResizerClass:rowPointerResizerClass,"fc-classic-bEw")),rowEventInnerClass:info=>joinClassNames("fc-classic-dl1 fc-classic-1sP fc-classic-XpK",info.isNarrow?xxsTextClass:"fc-classic-a3B"),rowEventTimeClass:"fc-classic-DIS",columnEventClass:info=>joinClassNames("fc-classic-1Wx fc-classic-A3h fc-classic-yKG",info.isStart&&"fc-classic-ku3 fc-classic-Z7Q",info.isEnd&&"fc-classic-Ika fc-classic-zi1 fc-classic-2qh"),columnEventBeforeClass:info=>joinClassNames(info.isStartResizable&&joinClassNames(info.isSelected?columnTouchResizerClass:columnPointerResizerClass,"fc-classic-YDC")),columnEventAfterClass:info=>joinClassNames(info.isEndResizable&&joinClassNames(info.isSelected?columnTouchResizerClass:columnPointerResizerClass,"fc-classic-fJL")),columnEventInnerClass:info=>joinClassNames("fc-classic-dl1",info.isShort?"fc-classic-KUX fc-classic-1sP fc-classic-XpK fc-classic-NWN":"fc-classic-oQ2 fc-classic-sgX"),columnEventTimeClass:info=>joinClassNames(!info.isShort&&"fc-classic-166",xxsTextClass),columnEventTitleClass:info=>joinClassNames(!info.isShort&&"fc-classic-2rx",info.isShort||info.isNarrow?xxsTextClass:"fc-classic-a3B"),moreLinkClass:`${outlineWidthFocusClass} ${primaryOutlineColorClass}`,moreLinkInnerClass:"fc-classic-TZ4 fc-classic-pKG",columnMoreLinkClass:`fc-classic-Ika fc-classic-Fvv fc-classic-wsy fc-classic-d0j fc-classic-4MR ${strongSolidPressableClass} fc-classic-vwH fc-classic-A3h fc-classic-yKG ${outlineOffsetClass}`,columnMoreLinkInnerClass:info=>joinClassNames("fc-classic-KUX",info.isNarrow?xxsTextClass:"fc-classic-a3B"),dayHeaderAlign:info=>info.inPopover?"start":"center",dayHeaderClass:info=>joinClassNames("fc-classic-E9P",info.isDisabled&&"fc-classic-iYS",info.inPopover?"fc-classic-zi1 fc-classic-C1x fc-classic-k3f":joinClassNames("fc-classic-wsy",info.isMajor?"fc-classic-C0k":"fc-classic-C1x")),dayHeaderInnerClass:info=>joinClassNames("fc-classic-rVY fc-classic-cJ3 fc-classic-dl1 fc-classic-sgX",info.isNarrow?xxsTextClass:"fc-classic-9yp"),dayHeaderDividerClass:"fc-classic-zi1 fc-classic-C1x",dayCellClass:getDayClass,dayCellTopClass:info=>joinClassNames(info.isNarrow?"fc-classic-toR":"fc-classic-84e","fc-classic-dl1 fc-classic-1sP fc-classic-LMv"),dayCellTopInnerClass:info=>joinClassNames("fc-classic-rVY fc-classic-TZ4",info.isNarrow?`fc-classic-cJ3 ${xxsTextClass}`:"fc-classic-V9v fc-classic-9yp",info.isOther&&"fc-classic-taq",info.monthText&&"fc-classic-DIS"),dayCellInnerClass:info=>joinClassNames(info.inPopover&&"fc-classic-3N5"),popoverClass:"fc-classic-Jk3 fc-classic-GAX fc-classic-wsy fc-classic-C1x fc-classic-tkw fc-classic-aNc fc-classic-n5m",popoverCloseClass:`fc-classic-bCs fc-classic-1EY fc-classic-2ik fc-classic-2w8 ${outlineWidthFocusClass} ${primaryOutlineColorClass} fc-classic-Z9U`,popoverCloseContent:()=>x("fc-classic-XUJ fc-classic-9yp fc-classic-mAY"),dayLaneClass:getDayClass,dayLaneInnerClass:info=>info.isStack?"fc-classic-gMS":info.isNarrow?"fc-classic-148":"fc-classic-Jzj fc-classic-B3G",slotLaneClass:getSlotClass,listDayHeaderClass:"fc-classic-zi1 fc-classic-C1x fc-classic-SDU fc-classic-nHS fc-classic-dl1 fc-classic-1sP fc-classic-XpK fc-classic-N2M",listDayHeaderInnerClass:"fc-classic-Apf fc-classic-dl6 fc-classic-9yp fc-classic-DIS",singleMonthClass:info=>joinClassNames(info.multiMonthColumns>1&&"fc-classic-jD5",info.multiMonthColumns===1&&!info.isLast&&"fc-classic-zi1 fc-classic-C1x"),singleMonthHeaderClass:info=>joinClassNames(info.multiMonthColumns>1?"fc-classic-cM0":"fc-classic-dl6 fc-classic-zi1 fc-classic-C1x fc-classic-Jk3","fc-classic-XpK"),singleMonthHeaderInnerClass:"fc-classic-1Po fc-classic-DIS",tableHeaderClass:"fc-classic-Jk3",fillerClass:"fc-classic-wsy fc-classic-C1x fc-classic-lMo",dayHeaderRowClass:"fc-classic-wsy fc-classic-C1x",dayRowClass:"fc-classic-wsy fc-classic-C1x",slotHeaderRowClass:"fc-classic-wsy fc-classic-C1x",slotHeaderClass:getSlotClass,navLinkClass:`fc-classic-Eu0 ${outlineWidthFocusClass} ${outlineInsetClass} ${primaryOutlineColorClass}`,inlineWeekNumberClass:info=>joinClassNames("fc-classic-1EY fc-classic-n9G fc-classic-rbS fc-classic-C2g fc-classic-KUX fc-classic-HXA fc-classic-m9h fc-classic-k3f",info.isNarrow?xxsTextClass:"fc-classic-9yp"),nonBusinessHoursClass:"fc-classic-iYS",highlightClass:"fc-classic-hLU",resourceDayHeaderAlign:"center",resourceDayHeaderClass:info=>joinClassNames("fc-classic-wsy",info.isMajor?"fc-classic-C0k":"fc-classic-C1x"),resourceDayHeaderInnerClass:info=>joinClassNames("fc-classic-rVY fc-classic-cJ3 fc-classic-dl1 fc-classic-sgX",info.isNarrow?xxsTextClass:"fc-classic-9yp"),resourceColumnHeaderClass:"fc-classic-wsy fc-classic-C1x fc-classic-E9P",resourceColumnHeaderInnerClass:"fc-classic-bvX fc-classic-9yp",resourceColumnResizerClass:"fc-classic-1EY fc-classic-AWB fc-classic-4Tv fc-classic-dnf",resourceGroupHeaderClass:"fc-classic-wsy fc-classic-C1x fc-classic-k3f",resourceGroupHeaderInnerClass:"fc-classic-bvX fc-classic-9yp",resourceCellClass:"fc-classic-wsy fc-classic-C1x",resourceCellInnerClass:"fc-classic-bvX fc-classic-9yp",resourceIndentClass:"fc-classic-Mde fc-classic-kp0 fc-classic-E9P",resourceExpanderClass:`fc-classic-bCs ${outlineWidthFocusClass} ${primaryOutlineColorClass}`,resourceExpanderContent:info=>info.isExpanded?minusSquare(expanderIconClass):plusSquare(expanderIconClass),resourceHeaderRowClass:"fc-classic-wsy fc-classic-C1x",resourceRowClass:"fc-classic-wsy fc-classic-C1x",resourceColumnDividerClass:"fc-classic-1Wx fc-classic-C1x fc-classic-a7i fc-classic-k3f",resourceGroupLaneClass:"fc-classic-wsy fc-classic-C1x fc-classic-k3f",resourceLaneClass:"fc-classic-wsy fc-classic-C1x",resourceLaneBottomClass:info=>info.options.eventOverlap&&"fc-classic-zrJ",timelineBottomClass:"fc-classic-zrJ"},views:{dayGrid:{...dayRowCommonClasses,dayCellBottomClass:"fc-classic-toR"},multiMonth:{...dayRowCommonClasses,dayCellBottomClass:"fc-classic-toR",tableClass:info=>joinClassNames(info.multiMonthColumns>1&&"fc-classic-C1x fc-classic-wsy")},timeGrid:{...dayRowCommonClasses,dayCellBottomClass:"fc-classic-mhE",weekNumberHeaderClass:"fc-classic-XpK fc-classic-LMv",weekNumberHeaderInnerClass:info=>joinClassNames("fc-classic-rVY fc-classic-cJ3",info.isNarrow?xxsTextClass:"fc-classic-9yp"),allDayHeaderClass:"fc-classic-XpK fc-classic-LMv",allDayHeaderInnerClass:info=>joinClassNames("fc-classic-rVY fc-classic-2tF fc-classic-2HE",info.isNarrow?xxsTextClass:"fc-classic-9yp"),allDayDividerClass:"fc-classic-JIC fc-classic-C1x fc-classic-8ub fc-classic-k3f",slotHeaderClass:"fc-classic-LMv",slotHeaderInnerClass:info=>joinClassNames("fc-classic-rVY fc-classic-cJ3",info.isNarrow?xxsTextClass:"fc-classic-9yp"),slotHeaderDividerClass:"fc-classic-USt fc-classic-C1x",nowIndicatorHeaderClass:"fc-classic-rbS fc-classic-a10 fc-classic-XM3 fc-classic-rif fc-classic-jIH fc-classic-0qY",nowIndicatorLineClass:"fc-classic-ku3 fc-classic-sYT"},list:{listDayClass:info=>joinClassNames(!info.isLast&&"fc-classic-zi1 fc-classic-C1x"),listItemEventClass:info=>joinClassNames("fc-classic-bCs fc-classic-Apf fc-classic-dl6 fc-classic-wwb fc-classic-ku3 fc-classic-C1x",info.isInteractive?joinClassNames(faintHoverPressableClass,outlineInsetClass):faintHoverClass),listItemEventBeforeClass:"fc-classic-GOm",listItemEventInnerClass:"fc-classic-eF2",listItemEventTimeClass:"fc-classic-88I fc-classic-yi0 fc-classic-roZ fc-classic-kMV fc-classic-TZ4 fc-classic-pKG fc-classic-IPx fc-classic-9yp",listItemEventTitleClass:info=>joinClassNames("fc-classic-1El fc-classic-2KU fc-classic-TZ4 fc-classic-pKG fc-classic-9yp",info.event.url&&"fc-classic-Ogp"),noEventsClass:"fc-classic-k3f fc-classic-dl1 fc-classic-sgX fc-classic-XpK fc-classic-E9P",noEventsInnerClass:"fc-classic-OUe fc-classic-jGI fc-classic-P9h"},timeline:{rowEventClass:info=>joinClassNames(info.isEnd&&"fc-classic-9hC","fc-classic-XpK"),rowEventBeforeClass:info=>!info.isStart&&`${continuationArrowClass} fc-classic-Bda fc-classic-5JV`,rowEventAfterClass:info=>!info.isEnd&&`${continuationArrowClass} fc-classic-hhi fc-classic-LaM`,rowEventInnerClass:info=>info.options.eventOverlap?"fc-classic-2rx":"fc-classic-End",rowEventTimeClass:"fc-classic-oQ2",rowEventTitleClass:"fc-classic-oQ2",rowMoreLinkClass:`fc-classic-9hC fc-classic-Ika fc-classic-wsy fc-classic-d0j fc-classic-4MR ${strongSolidPressableClass} fc-classic-vwH`,rowMoreLinkInnerClass:"fc-classic-KUX fc-classic-a3B",slotHeaderAlign:info=>info.isTime?"start":"center",slotHeaderClass:info=>joinClassNames("fc-classic-E9P",!info.level&&"fc-classic-pKG"),slotHeaderInnerClass:info=>joinClassNames("fc-classic-fn8 fc-classic-V9v fc-classic-9yp",info.hasNavLink&&"fc-classic-Eu0"),slotHeaderDividerClass:"fc-classic-zi1 fc-classic-C1x",nowIndicatorHeaderClass:"fc-classic-n9G fc-classic-J04 fc-classic-ybF fc-classic-Pqk fc-classic-bLA fc-classic-sYT",nowIndicatorLineClass:"fc-classic-3J4 fc-classic-sYT"}}};function chevronLeft(className){return jsx15("svg",{xmlns:"http://www.w3.org/2000/svg",className,width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx15("polyline",{points:"15 18 9 12 15 6"})})}function chevronsLeft(className){return jsxs11("svg",{xmlns:"http://www.w3.org/2000/svg",className,width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx15("polyline",{points:"11 17 6 12 11 7"}),jsx15("polyline",{points:"18 17 13 12 18 7"})]})}function x(className){return jsxs11("svg",{xmlns:"http://www.w3.org/2000/svg",className,width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx15("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsx15("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function plusSquare(className){return jsxs11("svg",{xmlns:"http://www.w3.org/2000/svg",className,width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx15("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),jsx15("line",{x1:"12",y1:"8",x2:"12",y2:"16"}),jsx15("line",{x1:"8",y1:"12",x2:"16",y2:"12"})]})}function minusSquare(className){return jsxs11("svg",{xmlns:"http://www.w3.org/2000/svg",className,width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx15("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),jsx15("line",{x1:"8",y1:"12",x2:"16",y2:"12"})]})}import{jsx as jsx17}from"react/jsx-runtime";import{jsx as jsx16,jsxs as jsxs12,Fragment as Fragment9}from"react/jsx-runtime";import{createRef as createRef3,createElement as createElement5}from"react";function buildDayColsFromSeries(daySeries,dateEnv,config2={}){let{slotRange,majorUnit="",activeRange}=config2;return daySeries.dates.map(date=>({key:date.toISOString(),date,range:slotRange?{start:dateEnv.add(date,slotRange.slotMinTime),end:dateEnv.add(date,slotRange.slotMaxTime)}:{start:date,end:addDays4(date,1)},isMajor:majorUnit?isMajorUnit(date,majorUnit,dateEnv):!1,isDisabled:activeRange===null||activeRange!==void 0&&!rangeContainsMarker(activeRange,date)}))}var EMPTY_EVENT_STORE=createEmptyEventStore(),Splitter=class{constructor(){this.getKeysForEventDefs=memoize2(this._getKeysForEventDefs),this.splitDateSelection=memoize2(this._splitDateSpan),this.splitEventStore=memoize2(this._splitEventStore),this.splitIndividualUi=memoize2(this._splitIndividualUi),this.splitEventDrag=memoize2(this._splitInteraction),this.splitEventResize=memoize2(this._splitInteraction),this.eventUiBuilders={}}splitProps(props){let keyInfos=this.getKeyInfo(props),defKeys=this.getKeysForEventDefs(props.eventStore),dateSelections=this.splitDateSelection(props.dateSelection),individualUi=this.splitIndividualUi(props.eventUiBases,defKeys),eventStores=this.splitEventStore(props.eventStore,defKeys),eventDrags=this.splitEventDrag(props.eventDrag),eventResizes=this.splitEventResize(props.eventResize),splitProps={};this.eventUiBuilders=mapHash(keyInfos,(info,key)=>this.eventUiBuilders[key]||memoize2(buildEventUiForKey));for(let key in keyInfos){let keyInfo=keyInfos[key],eventStore=eventStores[key]||EMPTY_EVENT_STORE,buildEventUi=this.eventUiBuilders[key];splitProps[key]={businessHours:keyInfo.businessHours||props.businessHours,dateSelection:dateSelections[key]||null,eventStore,eventUiBases:buildEventUi(props.eventUiBases[""],keyInfo.ui,individualUi[key]),eventDrag:eventDrags[key]||null,eventResize:eventResizes[key]||null,eventSelection:eventStore.instances[props.eventSelection]?props.eventSelection:""}}return splitProps}_splitDateSpan(dateSpan){let dateSpans={};if(dateSpan){let keys=this.getKeysForDateSpan(dateSpan);for(let key of keys)dateSpans[key]=dateSpan}return dateSpans}_getKeysForEventDefs(eventStore){return mapHash(eventStore.defs,eventDef=>this.getKeysForEventDef(eventDef))}_splitEventStore(eventStore,defKeys){let{defs,instances}=eventStore,splitStores={};for(let defId in defs)for(let key of defKeys[defId])splitStores[key]||(splitStores[key]=createEmptyEventStore()),splitStores[key].defs[defId]=defs[defId];for(let instanceId in instances){let instance=instances[instanceId];for(let key of defKeys[instance.defId])splitStores[key]&&(splitStores[key].instances[instanceId]=instance)}return splitStores}_splitIndividualUi(eventUiBases,defKeys){let splitHashes={};for(let defId in eventUiBases)if(defId)for(let key of defKeys[defId])splitHashes[key]||(splitHashes[key]={}),splitHashes[key][defId]=eventUiBases[defId];return splitHashes}_splitInteraction(interaction){let splitStates={};if(interaction){let affectedStores=this._splitEventStore(interaction.affectedEvents,this._getKeysForEventDefs(interaction.affectedEvents)),mutatedKeysByDefId=this._getKeysForEventDefs(interaction.mutatedEvents),mutatedStores=this._splitEventStore(interaction.mutatedEvents,mutatedKeysByDefId),populate=key=>{splitStates[key]||(splitStates[key]={affectedEvents:affectedStores[key]||EMPTY_EVENT_STORE,mutatedEvents:mutatedStores[key]||EMPTY_EVENT_STORE,isEvent:interaction.isEvent})};for(let key in affectedStores)populate(key);for(let key in mutatedStores)populate(key)}return splitStates}};function buildEventUiForKey(allUi,eventUiForKey,individualUi){let baseParts=[];allUi&&baseParts.push(allUi),eventUiForKey&&baseParts.push(eventUiForKey);let stuff={"":combineEventUis(baseParts)};return individualUi&&Object.assign(stuff,individualUi),stuff}var AllDaySplitter=class extends Splitter{getKeyInfo(){return{allDay:{},timed:{}}}getKeysForDateSpan(dateSpan){return dateSpan.allDay?["allDay"]:["timed"]}getKeysForEventDef(eventDef){return eventDef.allDay?hasBgRendering(eventDef)?["timed","allDay"]:["allDay"]:["timed"]}},DayTimeColsSlicer=class extends Slicer{sliceRange(range,dayRanges){let segs=[];for(let col=0;col<dayRanges.length;col+=1){let segRange=intersectRanges(range,dayRanges[col]);segRange&&segs.push({startDate:segRange.start,endDate:segRange.end,isStart:segRange.start.valueOf()===range.start.valueOf(),isEnd:segRange.end.valueOf()===range.end.valueOf(),col})}return segs}};function organizeSegsByCol(segs,colCount){let segsByCol=[],i;for(i=0;i<colCount;i+=1)segsByCol.push([]);if(segs)for(i=0;i<segs.length;i+=1)segsByCol[segs[i].col].push(segs[i]);return segsByCol}function splitInteractionByCol(ui,colCount){let byRow=[];if(ui){for(let i=0;i<colCount;i+=1)byRow[i]={affectedInstances:ui.affectedInstances,isEvent:ui.isEvent,segs:[]};for(let seg of ui.segs)byRow[seg.col].segs.push(seg)}else for(let i=0;i<colCount;i+=1)byRow[i]=null;return byRow}var STOCK_SUB_DURATIONS=[{hours:1},{minutes:30},{minutes:15},{seconds:30},{seconds:15}];function buildSlatMetas(slotMinTime,slotMaxTime,explicitLabelInterval,slotDuration,dateEnv){let dayStart=new Date(0),slatTime=slotMinTime,slatIterator=createDuration(0),labelInterval=explicitLabelInterval||computeLabelInterval(slotDuration),metas=[],i=0;for(;asRoughMs(slatTime)<asRoughMs(slotMaxTime);){let date=dateEnv.add(dayStart,slatTime),isLabeled=wholeDivideDurations(slatIterator,labelInterval)!==null;metas.push({date,time:slatTime,key:date.toISOString(),isoTimeStr:formatIsoTimeString(date),isLabeled,isFirst:i===0}),slatTime=addDurations(slatTime,slotDuration),slatIterator=addDurations(slatIterator,slotDuration),i+=1}return metas}function computeLabelInterval(slotDuration){let i,labelInterval,slotsPerLabel;for(i=STOCK_SUB_DURATIONS.length-1;i>=0;i-=1)if(labelInterval=createDuration(STOCK_SUB_DURATIONS[i]),slotsPerLabel=wholeDivideDurations(labelInterval,slotDuration),slotsPerLabel!==null&&slotsPerLabel>1)return labelInterval;return slotDuration}var TimeGridAllDayHeader=class extends BaseComponent{constructor(){super(...arguments),this.innerElRef=createRef3()}render(){let{props}=this,{options,viewApi}=this.context,renderProps={text:options.allDayText,view:viewApi,isNarrow:props.isNarrow};return jsx16(ContentContainer,{tag:"div",attrs:{role:"rowheader"},className:joinClassNames(classNames.flexRow,classNames.noMargin,classNames.noPadding,classNames.contentBox),style:{width:props.width},renderProps,generatorName:"allDayHeaderContent",customGenerator:options.allDayHeaderContent,defaultGenerator:renderAllDayInner,classNameGenerator:options.allDayHeaderClass,didMount:options.allDayHeaderDidMount,willUnmount:options.allDayHeaderWillUnmount,children:InnerContent=>jsx16("div",{className:joinClassNames(classNames.flexRow,classNames.noShrink,classNames.whiteSpacePre),ref:this.innerElRef,children:jsx16(InnerContent,{tag:"div",className:generateClassName(options.allDayHeaderInnerClass,renderProps)})})})}componentDidMount(){this._isUnmounting=!1;let{props}=this,innerEl=this.innerElRef.current;this.disconnectInnerWidth=watchWidth(innerEl,width=>{this._isUnmounting||setRef(props.innerWidthRef,width)})}componentWillUnmount(){this._isUnmounting=!0,this.disconnectInnerWidth(),setRef(this.props.innerWidthRef,null)}};function renderAllDayInner(renderProps){return renderProps.text}var TimeGridAllDayLane=class extends DateComponent{constructor(){super(...arguments),this.state={},this.heightRef=createRef3(),this.handleMoreLinkEl=el=>{this.disconnectMoreLinkHeight?.(),this.disconnectMoreLinkHeight=void 0,el&&(this.disconnectMoreLinkHeight=watchHeight(el,height=>{this._isUnmounting||this.setState({moreLinkHeight:height})}))},this.handleRootEl=rootEl=>{this.rootEl=rootEl,rootEl?this.context.registerInteractiveComponent(this,{el:rootEl}):this.context.unregisterInteractiveComponent(this)}}render(){let{props,state}=this,needsMoreLinkProbe=!props.forPrint&&resolveDayGridPlacementMode(props.dayMaxEvents,props.dayMaxEventRows)==="auto";return jsxs12(Fragment9,{children:[jsx16(DayGridRow,{...props,moreLinkHeight:state.moreLinkHeight,rootElRef:this.handleRootEl,heightRef:this.heightRef}),needsMoreLinkProbe&&jsx16(MoreLinkTrigger,{num:1,display:"row",isNarrow:props.cellIsNarrow,isMicro:props.cellIsMicro,elRef:this.handleMoreLinkEl,className:classNames.offscreen,attrs:{"aria-hidden":!0,inert:""}})]})}componentDidMount(){this._isUnmounting=!1}componentWillUnmount(){this._isUnmounting=!0,this.disconnectMoreLinkHeight?.()}queryHit(isRtl,positionLeft,positionTop,elWidth){let{props,heightRef}=this,colCount=props.cells.length,{col,left,right}=computeColFromPosition(positionLeft,elWidth,props.colWidth,colCount,isRtl),cell=props.cells[col],cellStartDate=cell.date,cellEndDate=addDays4(cellStartDate,1);return{dateProfile:props.dateProfile,dateSpan:{range:{start:cellStartDate,end:cellEndDate},allDay:!0,...cell.dateSpanProps},getDayEl:()=>getCellEl(this.rootEl,col),rect:{left,right,top:0,bottom:heightRef.current},layer:0}}};function computeSlatHeight(expandRows,slatCnt,explicitSlatMinHeight=0,slatInnerHeight,scrollerHeight){if(!slatInnerHeight||!scrollerHeight)return[void 0,!1];let slatMinHeight=Math.max(slatInnerHeight+1,explicitSlatMinHeight),slatLiquidHeight=scrollerHeight/slatCnt,slatLiquid,slatHeight;return expandRows&&slatLiquidHeight>=slatMinHeight?(slatLiquid=!0,slatHeight=slatLiquidHeight):(slatLiquid=!1,slatHeight=slatMinHeight),[slatHeight,slatLiquid]}function computeDateTopFrac(date,dateProfile,startOfDayDate){return startOfDayDate||(startOfDayDate=startOfDay5(date)),computeTimeTopFrac(createDuration(date.valueOf()-startOfDayDate.valueOf()),dateProfile)}function computeTimeTopFrac(time,dateProfile){let startMs=asRoughMs(dateProfile.slotMinTime),endMs=asRoughMs(dateProfile.slotMaxTime),frac=(time.milliseconds-startMs)/(endMs-startMs);return frac=Math.max(0,frac),frac=Math.min(1,frac),frac}function computeFgSegVerticals(segs,dateProfile,colDate,slatCnt,slatHeight,eventMinHeight,eventShortHeight){let res=[];if(slatHeight!=null){let totalHeight=slatHeight*slatCnt;for(let seg of segs){let startFrac=computeDateTopFrac(seg.startDate,dateProfile,colDate),endFrac=computeDateTopFrac(seg.endDate,dateProfile,colDate),startCoord=startFrac*totalHeight,endCoord=endFrac*totalHeight,height=endCoord-startCoord;eventMinHeight!=null&&height<eventMinHeight&&(height=eventMinHeight,endCoord=startCoord+height),res.push({start:startCoord,end:endCoord,size:height,isShort:height<=eventShortHeight})}}return res}function buildTimeGridSegPlacements(segs,segVerticals,eventOrderStrict,eventMaxStack){let sourceSegs=[],segVerticalBySeg=new Map;for(let orderIndex=0;orderIndex<segs.length;orderIndex+=1){let seg=segs[orderIndex],segVertical=segVerticals[orderIndex];if(segVertical){let sourceSeg={...seg,key:seg.eventRange.instance.instanceId,start:segVertical.start,end:segVertical.end,orderIndex};sourceSegs.push(sourceSeg),segVerticalBySeg.set(sourceSeg,segVertical)}}let layout=layoutTimeGridColumnByMaxLevel(sourceSegs,eventMaxStack??1/0,{orderStrict:eventOrderStrict??!1});return{placements:layout.domOrderedPlacements.map(placement=>{let seg=placement.sourceSeg;return{seg,segVertical:segVerticalBySeg.get(seg),levelCoord:placement.levelCoord,thickness:placement.thickness,stackDepth:placement.backwardDepth,stackForward:placement.forwardDepth}}),hiddenGroups:layout.moreLinkGroups.map(group=>{let groupSegs=group.hiddenSlices.map(slice=>slice.sourceSeg);return{key:group.key,start:group.start,end:group.end,segs:groupSegs}})}}function layoutTimeGridColumnByMaxLevel(eventOrderedSegs,maxLevels,options){let{segLevels,excludedSegs}=buildSegLevels(eventOrderedSegs,options.orderStrict,maxLevels),placements=positionTimeGridPlacements(segLevels),moreLinkGroups=groupLaterallyIntersecting(convertSegsToWholeSlices(excludedSegs));return{domOrderedPlacements:sortByAxisOrder(placements),moreLinkGroups}}function positionTimeGridPlacements(levels){let placementLevels=levels.map((level,levelIndex)=>level.map(sourceSeg=>({sourceSeg,start:sourceSeg.start,end:sourceSeg.end,isStart:sourceSeg.isStart,isEnd:sourceSeg.isEnd,levelIndex}))),placements=flatArray(placementLevels),collidersByKey=new Map,parentByKey=new Map(placements.map(placement=>[placement.sourceSeg.key,placement.sourceSeg.key]));for(let placement of placements){let colliders=[];for(let levelIndex=placement.levelIndex+1;levelIndex<levels.length;levelIndex+=1)colliders.push(...findIntersections(placementLevels[levelIndex],placement));collidersByKey.set(placement.sourceSeg.key,colliders);for(let collider of colliders)unionPlacementKeys(parentByKey,placement.sourceSeg.key,collider.sourceSeg.key)}let maxLevelByRoot=new Map;for(let placement of placements){let root=findPlacementRoot(parentByKey,placement.sourceSeg.key);maxLevelByRoot.set(root,Math.max(maxLevelByRoot.get(root)??0,placement.levelIndex))}let backwardDepthByKey=new Map(placements.map(placement=>[placement.sourceSeg.key,0])),forwardDepthByKey=new Map(placements.map(placement=>[placement.sourceSeg.key,0]));for(let placement of placements){let depth=backwardDepthByKey.get(placement.sourceSeg.key)+1;for(let collider of collidersByKey.get(placement.sourceSeg.key))backwardDepthByKey.set(collider.sourceSeg.key,Math.max(backwardDepthByKey.get(collider.sourceSeg.key),depth))}for(let index2=placements.length-1;index2>=0;index2-=1){let placement=placements[index2],depth=0;for(let collider of collidersByKey.get(placement.sourceSeg.key))depth=Math.max(depth,forwardDepthByKey.get(collider.sourceSeg.key)+1);forwardDepthByKey.set(placement.sourceSeg.key,depth)}return placements.map(placement=>{let key=placement.sourceSeg.key,levelCount=maxLevelByRoot.get(findPlacementRoot(parentByKey,key))+1,farLevel=levelCount;for(let collider of collidersByKey.get(key))farLevel=Math.min(farLevel,collider.levelIndex);let levelCoord=placement.levelIndex/levelCount,thickness=(farLevel-placement.levelIndex)/levelCount;return{...placement,levelCoord,thickness,levelEndCoord:levelCoord+thickness,backwardDepth:backwardDepthByKey.get(key),forwardDepth:forwardDepthByKey.get(key)}})}function findPlacementRoot(parentByKey,key){let parent=parentByKey.get(key);if(parent===key)return key;let root=findPlacementRoot(parentByKey,parent);return parentByKey.set(key,root),root}function unionPlacementKeys(parentByKey,first,second){let firstRoot=findPlacementRoot(parentByKey,first),secondRoot=findPlacementRoot(parentByKey,second);firstRoot!==secondRoot&&parentByKey.set(secondRoot,firstRoot)}var ESTIMATED_SLAT_HEIGHT=50,isBrowserPrintQuirky=typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("firefox");function computeTimeGridPrintMode(forPrint,eventPrintLayout){return forPrint&&(eventPrintLayout==="stack"||eventPrintLayout!=="grid"&&isBrowserPrintQuirky)?"stack":"positioned"}var DEFAULT_TIME_FORMAT=createFormatter({hour:"numeric",minute:"2-digit",meridiem:!1}),TimeGridEvent=class extends BaseComponent{render(){let{props}=this;return jsx16(StandardEvent,{...props,display:"column",level:props.level,isNarrow:props.isNarrow,isShort:props.isShort,className:props.isLiquid?classNames.liquid:"",disableLiquid:!props.isLiquid,defaultTimeFormat:DEFAULT_TIME_FORMAT})}},TimeGridMoreLink=class extends BaseComponent{render(){let{props}=this;return jsx16("div",{className:joinClassNames(classNames.abs,classNames.flexCol,classNames.end0,classNames.z9999),style:{top:props.top,height:props.height},children:jsx16(MoreLinkContainer,{className:classNames.liquid,display:"column",allDayDate:null,segs:props.hiddenSegs,hiddenSegs:props.hiddenSegs,dateSpanProps:props.dateSpanProps,dateProfile:props.dateProfile,todayRange:props.todayRange,popoverContent:()=>renderPlainFgSegs(props.hiddenSegs,props,!1),forceTimed:!0,isNarrow:props.isNarrow,isMicro:props.isMicro})})}},NowIndicatorDot=props=>jsx16(ViewContextType.Consumer,{children:context=>{let{options}=context;return jsx16("div",{className:joinClassNames(props.className,options.nowIndicatorDotClass),style:props.style})}}),NowIndicatorLineContainer=props=>jsx16(ViewContextType.Consumer,{children:context=>{let{options}=context,renderProps={date:context.dateEnv.toDate(props.date),view:context.viewApi};return jsx16(ContentContainer,{elRef:props.elRef,tag:props.tag||"div",attrs:props.attrs,className:props.className,style:props.style,renderProps,generatorName:"nowIndicatorLineContent",customGenerator:options.nowIndicatorLineContent,classNameGenerator:options.nowIndicatorLineClass,didMount:options.nowIndicatorLineDidMount,willUnmount:options.nowIndicatorLineWillUnmount,children:props.children})}});function TimeGridNowIndicatorLine(props){let top=props.totalHeight!=null?props.totalHeight*computeDateTopFrac(props.nowDate,props.dateProfile,props.dayDate):void 0;return jsxs12("div",{className:joinClassNames(classNames.fill,classNames.pointerEventsNone,classNames.z2),children:[jsx16(NowIndicatorLineContainer,{className:joinClassNames(classNames.fillX,classNames.noMarginX,classNames.borderlessX),style:{top},date:props.nowDate}),(props.showDot??!0)&&jsx16(NowIndicatorDot,{className:joinClassNames(classNames.abs,classNames.start0),style:{top}})]})}var TimeGridCol=class extends BaseComponent{constructor(){super(...arguments),this.sortEventSegs=memoize2(sortEventSegs),this.getDateMeta=memoize2(getDateMeta)}render(){let{props,context}=this,{options,dateEnv}=context,isSelectMirror=options.selectMirror,mirrorSegs=props.eventDrag&&props.eventDrag.segs||props.eventResize&&props.eventResize.segs||isSelectMirror&&props.dateSelectionSegs||[],dateMeta=this.getDateMeta(props.date,dateEnv,props.dateProfile,props.todayRange),baseClassName=joinClassNames(classNames.borderlessY,classNames.borderlessEnd,!props.borderStart&&classNames.borderlessStart,props.width==null&&classNames.liquid,classNames.rel,classNames.z1),baseStyle={width:props.width},isStack=this.getIsStack(),renderProps={...dateMeta,...props.renderProps,isStack,isNarrow:props.isNarrow,isMajor:props.isMajor,view:context.viewApi};if(dateMeta.isDisabled)return jsx16("div",{role:"gridcell","aria-disabled":!0,className:joinClassNames(generateClassName(options.dayLaneClass,renderProps),baseClassName),style:baseStyle});let innerClassName=joinClassNames(generateClassName(options.dayLaneInnerClass,renderProps),!isStack&&classNames.fill,classNames.z1),sortedFgSegs=this.sortEventSegs(props.fgEventSegs,options.eventOrder);return jsx16(ContentContainer,{tag:"div",attrs:{...props.attrs,role:"gridcell",...dateMeta.isToday?{"aria-current":"date"}:{},"data-date":formatDayString(props.date)},className:baseClassName,style:baseStyle,renderProps,generatorName:void 0,classNameGenerator:options.dayLaneClass,didMount:options.dayLaneDidMount,willUnmount:options.dayLaneWillUnmount,children:()=>jsxs12(Fragment9,{children:[this.renderFillSegs(props.businessHourSegs,"non-business"),this.renderFillSegs(props.bgEventSegs,"bg-event"),this.renderFillSegs(props.dateSelectionSegs,"highlight"),jsx16("div",{className:innerClassName,children:this.renderFgSegs(sortedFgSegs,!1)}),!!mirrorSegs.length&&jsx16("div",{className:innerClassName,children:this.renderFgSegs(mirrorSegs,!0)}),this.renderNowIndicator(props.nowIndicatorSegs)]})})}renderFgSegs(sortedFgSegs,isMirror){let{props}=this;return this.getIsStack()?renderPlainFgSegs(sortedFgSegs,props,isMirror):isMirror?this.renderPositionedMirrorSegs(sortedFgSegs):this.renderPositionedFgSegs(sortedFgSegs)}renderPositionedFgSegs(segs){let{eventMaxStack,eventOrderStrict}=this.context.options,segVerticals=this.computeSegVerticals(segs),{placements,hiddenGroups}=buildTimeGridSegPlacements(segs,segVerticals,eventOrderStrict,eventMaxStack);return jsxs12(Fragment9,{children:[placements.map(placement=>this.renderPositionedSeg(placement.seg,placement.segVertical,this.computeSegHStyle(placement),placement.stackDepth,!1)),this.renderHiddenGroups(hiddenGroups)]})}renderPositionedMirrorSegs(segs){let segVerticals=this.computeSegVerticals(segs);return segs.map((seg,index2)=>this.renderPositionedSeg(seg,segVerticals[index2]||{},{left:0,right:0,zIndex:0},0,!0))}renderPositionedSeg(seg,segVertical,hStyle,level,isMirror){let{props}=this,{eventRange}=seg,{instanceId}=eventRange.instance,isSelected=instanceId===props.eventSelection;isSelected&&(hStyle.zIndex+=1e3);let isDragging=!!(props.eventDrag&&props.eventDrag.affectedInstances[instanceId]),isResizing=!!(props.eventResize&&props.eventResize.affectedInstances[instanceId]),isInvisible=!isMirror&&(isDragging||isResizing);return jsx16("div",{className:joinClassNames(classNames.abs,classNames.flexCol),style:{visibility:isInvisible?"hidden":void 0,top:segVertical.start,height:segVertical.size,...hStyle},children:jsx16(TimeGridEvent,{eventRange,slicedStart:seg.startDate,slicedEnd:seg.endDate,isStart:seg.isStart,isEnd:seg.isEnd,isDragging,isResizing,isMirror,isSelected,level,isNarrow:props.isNarrow,isShort:segVertical.isShort||!1,isLiquid:!0,...getEventRangeMeta(eventRange,props.todayRange,props.nowDate,props.nowMs)})},instanceId)}computeSegVerticals(segs){let{props,context}=this,isMeasured=props.slatHeight!=null;return computeFgSegVerticals(segs,props.dateProfile,props.date,props.slatCnt,props.slatHeight??ESTIMATED_SLAT_HEIGHT,isMeasured?context.options.eventMinHeight:void 0,context.options.eventShortHeight)}renderHiddenGroups(hiddenGroups){let{dateSpanProps,dateProfile,todayRange,nowDate,nowMs,eventSelection,eventDrag,eventResize,isNarrow,isMicro}=this.props;return jsx16(Fragment9,{children:hiddenGroups.map(hiddenGroup=>jsx16(TimeGridMoreLink,{hiddenSegs:hiddenGroup.segs,top:hiddenGroup.start,height:hiddenGroup.end-hiddenGroup.start,isNarrow,isMicro,dateSpanProps,dateProfile,todayRange,nowDate,nowMs,eventSelection,eventDrag,eventResize},hiddenGroup.key))})}renderFillSegs(segs,fillType){let{props,context}=this,segVerticals=this.computeSegVerticals(segs);return jsx16(Fragment9,{children:segs.map((seg,index2)=>{let{eventRange}=seg,segVertical=segVerticals[index2]||{};return jsx16("div",{className:classNames.fillX,style:{top:segVertical.start,height:segVertical.size,marginInlineStart:-1},children:fillType==="bg-event"?jsx16(BgEvent,{eventRange,isStart:seg.isStart,isEnd:seg.isEnd,isNarrow:props.isNarrow,isShort:segVertical.isShort||!1,isVertical:!0,...getEventRangeMeta(eventRange,props.todayRange,props.nowDate,props.nowMs)}):renderFill(fillType,context.options)},buildEventRangeKey(eventRange))})})}renderNowIndicator(segs){let{props}=this;if(!(props.forPrint||this.getIsStack()))return segs.map((seg,i)=>jsx16(TimeGridNowIndicatorLine,{nowDate:seg.startDate,dayDate:props.date,dateProfile:props.dateProfile,totalHeight:props.slatHeight!=null?props.slatHeight*props.slatCnt:void 0,showDot:seg.showDot??!0},i))}computeSegHStyle(segRect){let{options}=this.context,shouldOverlap=options.slotEventOverlap,nearCoord=segRect.levelCoord,farCoord=segRect.levelCoord+segRect.thickness;shouldOverlap&&(farCoord=Math.min(1,nearCoord+(farCoord-nearCoord)*2));let props={zIndex:segRect.stackDepth+1,insetInlineStart:fracToCssDim(nearCoord),insetInlineEnd:fracToCssDim(1-farCoord),marginInlineEnd:void 0};return shouldOverlap&&segRect.stackForward&&(props.marginInlineEnd=20),props}getIsStack(){let{eventPrintLayout}=this.context.options;return computeTimeGridPrintMode(this.props.forPrint,eventPrintLayout)==="stack"}};function renderPlainFgSegs(sortedFgSegs,{todayRange,nowDate,nowMs,eventSelection,eventDrag,eventResize},isMirror){return jsx16(Fragment9,{children:sortedFgSegs.map(seg=>{let{eventRange}=seg,{instanceId}=eventRange.instance,isDragging=!!(eventDrag&&eventDrag.affectedInstances[instanceId]),isResizing=!!(eventResize&&eventResize.affectedInstances[instanceId]),isInvisible=isDragging||isResizing;return jsx16("div",{className:classNames.breakInsideAvoid,style:{visibility:isInvisible?"hidden":void 0},children:jsx16(TimeGridEvent,{eventRange,slicedStart:seg.startDate,slicedEnd:seg.endDate,isStart:seg.isStart,isEnd:seg.isEnd,isDragging,isResizing,isMirror,isSelected:instanceId===eventSelection,level:0,isShort:!1,isNarrow:!1,disableResizing:!0,...getEventRangeMeta(eventRange,todayRange,nowDate,nowMs)})},instanceId)})})}var TimeGridCols=class extends DateComponent{constructor(){super(...arguments),this.processSlotOptions=memoize2(processSlotOptions),this.handleRootEl=el=>{this.rootEl=el,el?this.context.registerInteractiveComponent(this,{el,isHitComboAllowed:this.props.isHitComboAllowed}):this.context.unregisterInteractiveComponent(this)}}render(){let{props}=this;return jsx16("div",{role:props.role,className:joinClassNames(props.className,classNames.flexRow),ref:this.handleRootEl,children:props.cells.map((cell,col)=>jsx16(TimeGridCol,{dateProfile:props.dateProfile,nowDate:props.nowDate,nowMs:props.nowMs,todayRange:props.todayRange,date:cell.date,isMajor:cell.isMajor,slatCnt:props.slatCnt,renderProps:cell.renderProps,attrs:cell.attrs,dateSpanProps:cell.dateSpanProps,forPrint:props.forPrint,borderStart:!!col,isNarrow:props.cellIsNarrow,isMicro:props.cellIsMicro,fgEventSegs:props.fgEventSegsByCol[col],bgEventSegs:props.bgEventSegsByCol[col],businessHourSegs:props.businessHourSegsByCol[col],nowIndicatorSegs:props.nowIndicatorSegsByCol[col],dateSelectionSegs:props.dateSelectionSegsByCol[col],eventDrag:props.eventDragByCol[col],eventResize:props.eventResizeByCol[col],eventSelection:props.eventSelection,width:props.colWidth,slatHeight:props.slatHeight},cell.key))})}queryHit(isRtl,positionLeft,positionTop,elWidth){let{dateProfile,cells,colWidth,slatHeight}=this.props,{dateEnv,options}=this.context,{snapDuration,snapsPerSlot}=this.processSlotOptions(options.slotDuration,options.snapDuration),colCount=cells.length,{col,left,right}=computeColFromPosition(positionLeft,elWidth,colWidth,colCount,isRtl),cell=cells[col],slatIndex=Math.floor(positionTop/slatHeight),slatTop=slatIndex*slatHeight,partial=(positionTop-slatTop)/slatHeight,localSnapIndex=Math.floor(partial*snapsPerSlot),snapIndex=slatIndex*snapsPerSlot+localSnapIndex,time=addDurations(dateProfile.slotMinTime,multiplyDuration(snapDuration,snapIndex)),start=dateEnv.add(cell.date,time),end=dateEnv.add(start,snapDuration);return{dateProfile,dateSpan:{range:{start,end},allDay:!1,...cell.dateSpanProps},getDayEl:()=>getCellEl(this.rootEl,col),rect:{left,right,top:slatTop,bottom:slatTop+slatHeight},layer:0}}};TimeGridCols.addPropsEquality({style:isPropsEqualShallow});function processSlotOptions(slotDuration,snapDurationOverride){let snapDuration=snapDurationOverride||slotDuration,snapsPerSlot=wholeDivideDurations(slotDuration,snapDuration);return snapsPerSlot===null&&(snapDuration=slotDuration,snapsPerSlot=1),{snapDuration,snapsPerSlot}}var NowIndicatorHeaderContainer=props=>jsx16(ViewContextType.Consumer,{children:context=>{let{options}=context,renderProps={date:context.dateEnv.toDate(props.date),view:context.viewApi};return jsx16(ContentContainer,{elRef:props.elRef,tag:props.tag||"div",attrs:props.attrs,className:props.className,style:props.style,renderProps,generatorName:"nowIndicatorHeaderContent",customGenerator:options.nowIndicatorHeaderContent,classNameGenerator:options.nowIndicatorHeaderClass,didMount:options.nowIndicatorHeaderDidMount,willUnmount:options.nowIndicatorHeaderWillUnmount,children:props.children})}});function TimeGridNowIndicatorArrow(props){return jsx16("div",{className:joinClassNames(classNames.fill,classNames.crop,classNames.pointerEventsNone,classNames.z2),children:jsx16(NowIndicatorHeaderContainer,{className:classNames.abs,style:{top:props.totalHeight!=null?props.totalHeight*computeDateTopFrac(props.nowDate,props.dateProfile):void 0},date:props.nowDate})})}var DEFAULT_SLAT_LABEL_FORMAT=createFormatter({hour:"numeric",minute:"2-digit",omitZeroMinute:!0,meridiem:"short"}),TimeGridSlatHeader=class extends BaseComponent{constructor(){super(...arguments),this.createRenderProps=memoize2(createRenderProps),this.innerElRef=createRef3()}render(){let{props,context}=this,{options}=context,headerFormat=options.slotHeaderFormat==null?DEFAULT_SLAT_LABEL_FORMAT:Array.isArray(options.slotHeaderFormat)?createFormatter(options.slotHeaderFormat[0]):createFormatter(options.slotHeaderFormat),renderProps=this.createRenderProps(props.date,props.time,!props.isLabeled,props.isNarrow,props.isFirst,headerFormat,context),className=joinClassNames(props.liquidHeight&&classNames.liquid,classNames.flexRow,classNames.alignStart,classNames.noMargin,classNames.noPadding,classNames.borderlessX,classNames.borderlessBottom,!props.borderTop&&classNames.borderlessTop);return props.isLabeled?jsx16(ContentContainer,{tag:"div",attrs:{"data-time":props.isoTimeStr},style:{height:props.height},className,renderProps,generatorName:"slotHeaderContent",customGenerator:options.slotHeaderContent,defaultGenerator:renderInnerContent3,classNameGenerator:options.slotHeaderClass,didMount:options.slotHeaderDidMount,willUnmount:options.slotHeaderWillUnmount,children:InnerContent=>jsx16("div",{ref:this.innerElRef,className:joinClassNames(classNames.noShrink,classNames.whiteSpaceNoWrap,classNames.flexRow),children:jsx16(InnerContent,{tag:"div",className:generateClassName(options.slotHeaderInnerClass,renderProps)})})}):jsx16("div",{className:joinClassNames(generateClassName(options.slotHeaderClass,renderProps),className),style:{height:props.height}})}componentDidMount(){this._isUnmounting=!1;let{props}=this,innerEl=this.innerElRef.current;innerEl&&(this.disconnectInnerSize=watchSize(innerEl,(width,height)=>{this._isUnmounting||(setRef(props.innerWidthRef,width),setRef(props.innerHeightRef,height))}))}componentWillUnmount(){let{props}=this;this._isUnmounting=!0,this.disconnectInnerSize&&(this.disconnectInnerSize(),setRef(props.innerWidthRef,null),setRef(props.innerHeightRef,null))}};function createRenderProps(date,time,isMinor,isNarrow,isFirst,headerFormat,context){return{...getDateMeta(date,context.dateEnv),level:0,text:joinDateTimeFormatParts(context.dateEnv.formatToParts(date,headerFormat)),time,isMajor:!1,isMinor,isTime:!0,isNarrow,hasNavLink:!1,isFirst,view:context.viewApi}}function renderInnerContent3(props){return props.text}var TimeGridSlatLane=class extends BaseComponent{constructor(){super(...arguments),this.getDateMeta=memoize2(getDateMeta)}render(){let{props,context}=this,{options}=context,renderProps={...this.getDateMeta(props.date,context.dateEnv),time:props.time,isMajor:!1,isMinor:!props.isLabeled,view:context.viewApi};return jsx16(ContentContainer,{tag:"div",attrs:{"data-time":props.isoTimeStr},className:joinClassNames(classNames.noMargin,classNames.noPadding,classNames.liquid,classNames.borderlessX,classNames.borderlessBottom,!props.borderTop&&classNames.borderlessTop),renderProps,generatorName:void 0,classNameGenerator:options.slotLaneClass,didMount:options.slotLaneDidMount,willUnmount:options.slotLaneWillUnmount})}},DEFAULT_WEEK_NUM_FORMAT2=createFormatter({week:"short"}),TimeGridWeekNumber=class extends BaseComponent{constructor(){super(...arguments),this.innerElRef=createRef3()}render(){let{props,context}=this,{options,dateEnv}=context,range=props.dateProfile.renderRange,hasNavLink=diffDays4(range.start,range.end)===1&&options.navLinks,weekDateMarker=range.start,fullDateStr=buildDateStr(context,weekDateMarker,"week"),weekNum=dateEnv.computeWeekNumber(weekDateMarker),weekTextParts=dateEnv.formatToParts(weekDateMarker,options.weekNumberFormat||DEFAULT_WEEK_NUM_FORMAT2),weekText=joinDateTimeFormatParts(weekTextParts),weekDateZoned=dateEnv.toDate(weekDateMarker),weekNumberRenderProps={num:weekNum,text:weekText,textParts:weekTextParts,date:weekDateZoned,isNarrow:props.isNarrow,hasNavLink,options:{dayMinWidth:options.dayMinWidth}};return jsx16(ContentContainer,{tag:"div",attrs:{role:"gridcell","aria-label":fullDateStr},className:joinClassNames(classNames.flexRow,classNames.noMargin,classNames.noPadding,props.isLiquid?classNames.liquid:classNames.contentBox),style:{width:props.width},renderProps:weekNumberRenderProps,generatorName:"weekNumberHeaderContent",customGenerator:options.weekNumberHeaderContent,defaultGenerator:renderText,classNameGenerator:options.weekNumberHeaderClass,didMount:options.weekNumberHeaderDidMount,willUnmount:options.weekNumberHeaderWillUnmount,children:InnerContent=>jsx16("div",{ref:this.innerElRef,className:joinClassNames(classNames.flexRow,classNames.noShrink,classNames.whiteSpaceNoWrap),children:jsx16(InnerContent,{tag:"div",attrs:hasNavLink?buildNavLinkAttrs(context,range.start,"week",fullDateStr):{"aria-label":fullDateStr},className:generateClassName(options.weekNumberHeaderInnerClass,weekNumberRenderProps)})})})}componentDidMount(){this._isUnmounting=!1;let{props}=this,innerEl=this.innerElRef.current;this.disconnectInnerSize=watchSize(innerEl,(width,height)=>{this._isUnmounting||(setRef(props.innerWidthRef,width),setRef(props.innerHeightRef,height))})}componentWillUnmount(){let{props}=this;this._isUnmounting=!0,this.disconnectInnerSize(),setRef(props.innerWidthRef,null),setRef(props.innerHeightRef,null)}};function TimeGridAxisEmpty(props){return jsx16("div",{role:"gridcell",className:props.isLiquid?classNames.liquid:classNames.contentBox,style:{width:props.width}})}var TimeGridLayoutPannable=class extends BaseComponent{constructor(){super(...arguments),this.state={headerTierHeights:[]},this.headerLabelInnerWidthRefMap=new RefMap(()=>{afterSize(this.handleAxisWidths)}),this.headerLabelInnerHeightRefMap=new RefMap(()=>{afterSize(this.handleHeaderHeights)}),this.headerMainInnerHeightRefMap=new RefMap(()=>{afterSize(this.handleHeaderHeights)}),this.handleAllDayLabelInnerWidth=width=>{this.allDayLabelInnerWidth=width,afterSize(this.handleAxisWidths)},this.slatLabelInnerWidthRefMap=new RefMap(()=>{afterSize(this.handleAxisWidths)}),this.slatLabelInnerHeightRefMap=new RefMap(()=>{afterSize(this.handleSlatInnerHeights)}),this.headerScrollerRef=createRef3(),this.allDayScrollerRef=createRef3(),this.mainScrollerRef=createRef3(),this.footScrollerRef=createRef3(),this.axisScrollerRef=createRef3(),this.handleTotalWidth=totalWidth=>{this._isUnmounting||this.setState({totalWidth})},this.handleBodyHeight=bodyHeight=>{this._isUnmounting||this.setState({bodyHeight})},this.handleClientWidth=clientWidth=>{this._isUnmounting||this.setState({clientWidth})},this.handleClientHeight=clientHeight=>{this._isUnmounting||this.setState({clientHeight})},this.handleStickyBottomScrollbarWidth=sticykBottomScrollbarWidth=>{this._isUnmounting||this.setState({sticykBottomScrollbarWidth})},this.handleHeaderHeights=()=>{if(this._isUnmounting)return;let headerLabelInnerHeightMap=this.headerLabelInnerHeightRefMap.current,headerMainInnerHeightMap=this.headerMainInnerHeightRefMap.current,heights=[];for(let[tierNum,mainHeight]of headerMainInnerHeightMap.entries())heights[tierNum]=Math.max(headerLabelInnerHeightMap.get(tierNum)||0,mainHeight);this.setState({headerTierHeights:heights})},this.handleSlatInnerHeights=()=>{if(this._isUnmounting)return;let slatLabelInnerHeightMap=this.slatLabelInnerHeightRefMap.current,max=0;for(let slatLabelInnerHeight of slatLabelInnerHeightMap.values())max=Math.max(max,slatLabelInnerHeight);this.state.slatInnerHeight!==max&&this.setState({slatInnerHeight:max})},this.handleAxisWidths=()=>{if(this._isUnmounting)return;let headerLabelInnerWidthMap=this.headerLabelInnerWidthRefMap.current,slatLabelInnerWidthMap=this.slatLabelInnerWidthRefMap.current,max=this.allDayLabelInnerWidth||0;for(let headerLabelInnerWidth of headerLabelInnerWidthMap.values())max=Math.max(max,headerLabelInnerWidth);for(let slatLableInnerWidth of slatLabelInnerWidthMap.values())max=Math.max(max,slatLableInnerWidth);this.state.axisWidth!==max&&this.setState({axisWidth:max})}}render(){let{props,state,context,headerLabelInnerWidthRefMap,headerLabelInnerHeightRefMap,headerMainInnerHeightRefMap,slatLabelInnerWidthRefMap,slatLabelInnerHeightRefMap}=this,{nowDate,headerTiers,forPrint}=props,nowTimeMs=nowDate.valueOf()-startOfDay5(nowDate).valueOf(),{axisWidth,totalWidth,clientWidth,clientHeight,bodyHeight,sticykBottomScrollbarWidth}=state,{options}=context,{borderlessX,borderlessTop,borderlessBottom}=computeViewBorderless(options),endScrollbarWidth=totalWidth!=null&&clientWidth!=null&&axisWidth!=null?totalWidth-clientWidth-(axisWidth+1):void 0,verticalScrolling=!forPrint&&!getIsHeightAuto(options),tableHeaderSticky=!forPrint&&getTableHeaderSticky(options),footerScrollbarSticky=!forPrint&&getFooterScrollbarSticky(options),printStackEnabled=computeTimeGridPrintMode(forPrint,options.eventPrintLayout)==="stack",absPrint=forPrint&&!printStackEnabled,simplePrint=forPrint&&printStackEnabled,colCount=props.cells.length,[canvasWidth,appliedColWidth]=computeColWidth(colCount,props.dayMinWidth,clientWidth),measuredColWidth=appliedColWidth??(clientWidth!=null?clientWidth/colCount:void 0),cellIsMicro=measuredColWidth!=null&&measuredColWidth<=dayMicroWidth,cellIsNarrow=cellIsMicro||measuredColWidth!=null&&measuredColWidth<=options.dayNarrowWidth,slatCnt=props.slatMetas.length,[slatHeight,slatLiquidHeight]=computeSlatHeight(verticalScrolling&&options.expandRows,slatCnt,options.slotMinHeight,state.slatInnerHeight,clientHeight);this.slatHeight=slatHeight;let totalSlatHeight=(slatHeight||0)*slatCnt,forcedBodyHeight=absPrint?totalSlatHeight:void 0,rowsNotExpanding=verticalScrolling&&!options.expandRows&&clientHeight!=null&&clientHeight>totalSlatHeight,firstBodyRowIndex=options.dayHeaders?headerTiers.length+1:1,bottomScrollbarWidth=footerScrollbarSticky?sticykBottomScrollbarWidth:bodyHeight!=null&&clientHeight!=null?bodyHeight-clientHeight:void 0;return jsxs12(Fragment9,{children:[options.dayHeaders&&jsxs12("div",{className:joinClassNames(generateClassName(options.tableHeaderClass,{isSticky:tableHeaderSticky,borderlessX,borderlessTop,borderlessBottom,multiMonthColumns:0}),classNames.flexCol,tableHeaderSticky&&classNames.tableHeaderSticky,classNames.z1),children:[jsxs12("div",{className:classNames.flexRow,children:[jsx16("div",{role:"rowgroup",className:classNames.contentBox,style:{width:axisWidth},children:headerTiers.map((rowConfig,tierNum)=>jsx16("div",{role:"row","aria-rowindex":tierNum+1,className:joinClassNames(options.dayHeaderRowClass,classNames.flexRow,classNames.contentBox,classNames.borderlessX,classNames.borderlessTop,tierNum===props.headerTiers.length-1&&classNames.borderlessBottom),style:{height:state.headerTierHeights[tierNum]},children:options.weekNumbers&&rowConfig.isDateRow?jsx16(TimeGridWeekNumber,{dateProfile:props.dateProfile,innerWidthRef:headerLabelInnerWidthRefMap.createRef(tierNum),innerHeightRef:headerLabelInnerHeightRefMap.createRef(tierNum),width:void 0,isLiquid:!0,isNarrow:cellIsNarrow}):jsx16(TimeGridAxisEmpty,{width:void 0,isLiquid:!0})},tierNum))}),jsx16("div",{className:generateClassName(options.slotHeaderDividerClass,{inTableHeader:!0,options:{dayMinWidth:options.dayMinWidth}})}),jsxs12(Scroller,{horizontal:!0,hideScrollbars:!0,className:joinClassNames(classNames.flexRow,classNames.liquid),ref:this.headerScrollerRef,children:[jsx16("div",{role:"rowgroup",className:canvasWidth==null?classNames.liquid:"",style:{width:canvasWidth},children:props.headerTiers.map((rowConfig,tierNum)=>createElement5(DayGridHeaderRow,{...rowConfig,key:tierNum,role:"row",rowIndex:tierNum,borderBottom:tierNum<props.headerTiers.length-1,height:state.headerTierHeights[tierNum],colWidth:appliedColWidth,viewportWidth:clientWidth,innerHeightRef:headerMainInnerHeightRefMap.createRef(tierNum),cellIsNarrow,cellIsMicro,rowLevel:props.headerTiers.length-tierNum-1}))}),!!endScrollbarWidth&&jsx16("div",{className:joinClassNames(generateClassName(options.fillerClass,{inTableHeader:!0}),classNames.borderlessY,classNames.borderlessEnd),style:{minWidth:endScrollbarWidth}})]})]}),jsx16("div",{className:generateClassName(options.dayHeaderDividerClass,{isSticky:tableHeaderSticky,multiMonthColumns:0,options:{allDaySlot:!!options.allDaySlot}})})]}),jsxs12("div",{role:"rowgroup",className:joinClassNames(generateClassName(options.tableBodyClass,{borderlessX,borderlessTop,borderlessBottom,multiMonthColumns:0}),classNames.flexCol,verticalScrolling&&classNames.liquid,classNames.isolate,classNames.z0),children:[options.allDaySlot&&jsxs12(Fragment9,{children:[jsxs12("div",{role:"row","aria-rowindex":firstBodyRowIndex,className:joinClassNames(classNames.flexRow,classNames.z1),children:[jsx16(TimeGridAllDayHeader,{width:axisWidth,innerWidthRef:this.handleAllDayLabelInnerWidth,isNarrow:cellIsNarrow}),jsx16("div",{className:generateClassName(options.slotHeaderDividerClass,{inTableHeader:!1,options:{dayMinWidth:options.dayMinWidth}})}),jsxs12(Scroller,{horizontal:!0,hideScrollbars:!0,className:joinClassNames(classNames.flexRow,classNames.liquidX),ref:this.allDayScrollerRef,children:[jsx16("div",{className:classNames.flexRow,style:{width:canvasWidth},children:jsx16(TimeGridAllDayLane,{dateProfile:props.dateProfile,todayRange:props.todayRange,cells:props.cells,showDayNumbers:!1,forPrint,isHitComboAllowed:props.isHitComboAllowed,className:joinClassNames(classNames.borderless,classNames.liquidX),cellIsNarrow,cellIsMicro,fgEventSegs:props.fgEventSegs,bgEventSegs:props.bgEventSegs,businessHourSegs:props.businessHourSegs,dateSelectionSegs:props.dateSelectionSegs,eventSelection:props.eventSelection,eventDrag:props.eventDrag,eventResize:props.eventResize,dayMaxEvents:props.dayMaxEvents,dayMaxEventRows:props.dayMaxEventRows,colWidth:appliedColWidth})}),!!endScrollbarWidth&&jsx16("div",{className:joinClassNames(generateClassName(options.fillerClass,{inTableHeader:!1}),classNames.borderlessY,classNames.borderlessEnd),style:{minWidth:endScrollbarWidth}})]})]}),jsx16("div",{className:joinClassNames(options.allDayDividerClass,classNames.z2)})]}),jsxs12("div",{role:"row","aria-rowindex":firstBodyRowIndex+(options.allDaySlot?1:0),className:joinClassNames(classNames.flexRow,classNames.rel,verticalScrolling&&classNames.liquid,classNames.z0),children:[jsx16(Scroller,{vertical:verticalScrolling,hideScrollbars:!0,className:joinClassNames(classNames.flexCol,classNames.contentBox),style:{width:axisWidth},ref:this.axisScrollerRef,clientHeightRef:this.handleBodyHeight,children:!simplePrint&&jsx16(Fragment9,{children:jsxs12("div",{role:"rowheader","aria-label":options.timedText,className:joinClassNames(classNames.flexCol,classNames.grow,classNames.rel),style:{height:forcedBodyHeight},children:[jsx16("div",{"aria-hidden":!0,className:joinClassNames(classNames.flexCol,verticalScrolling&&options.expandRows&&classNames.grow,absPrint&&classNames.fillX),children:props.slatMetas.map((slatMeta,slatI)=>createElement5(TimeGridSlatHeader,{...slatMeta,key:slatMeta.key,innerWidthRef:slatLabelInnerWidthRefMap.createRef(slatMeta.key),innerHeightRef:slatLabelInnerHeightRefMap.createRef(slatMeta.key),borderTop:!!slatI,isNarrow:cellIsNarrow,height:slatLiquidHeight?void 0:slatHeight,liquidHeight:slatLiquidHeight}))}),!forPrint&&options.nowIndicator&&rangeContainsMarker(props.dateProfile.currentRange,nowDate)&&nowTimeMs>=props.dateProfile.slotMinTime.milliseconds&&nowTimeMs<props.dateProfile.slotMaxTime.milliseconds&&jsx16(TimeGridNowIndicatorArrow,{nowDate,dateProfile:props.dateProfile,totalHeight:slatHeight!=null?slatHeight*slatCnt:void 0}),!!(rowsNotExpanding||bottomScrollbarWidth)&&jsx16("div",{className:joinClassNames(generateClassName(options.fillerClass,{inTableHeader:!1}),classNames.borderlessX,classNames.borderlessBottom,rowsNotExpanding&&classNames.liquid),style:{minHeight:bottomScrollbarWidth}})]})})}),jsx16("div",{className:generateClassName(options.slotHeaderDividerClass,{inTableHeader:!1,options:{dayMinWidth:options.dayMinWidth}})}),jsxs12("div",{className:joinClassNames(classNames.flexCol,classNames.liquid),children:[jsx16(Scroller,{vertical:verticalScrolling,horizontal:!0,hideScrollbars:footerScrollbarSticky||forPrint,className:joinClassNames(classNames.flexCol,classNames.rel,verticalScrolling&&classNames.liquid),ref:this.mainScrollerRef,clientWidthRef:this.handleClientWidth,clientHeightRef:this.handleClientHeight,children:jsxs12("div",{className:joinClassNames(classNames.flexCol,classNames.grow,classNames.rel),style:{width:canvasWidth,height:forcedBodyHeight},children:[jsx16(TimeGridCols,{dateProfile:props.dateProfile,nowDate:props.nowDate,nowMs:props.nowMs,todayRange:props.todayRange,cells:props.cells,slatCnt,forPrint,isHitComboAllowed:props.isHitComboAllowed,className:simplePrint?"":classNames.fill,fgEventSegsByCol:props.fgEventSegsByCol,bgEventSegsByCol:props.bgEventSegsByCol,businessHourSegsByCol:props.businessHourSegsByCol,nowIndicatorSegsByCol:props.nowIndicatorSegsByCol,dateSelectionSegsByCol:props.dateSelectionSegsByCol,eventDragByCol:props.eventDragByCol,eventResizeByCol:props.eventResizeByCol,eventSelection:props.eventSelection,colWidth:appliedColWidth,slatHeight,cellIsNarrow,cellIsMicro}),!simplePrint&&jsxs12(Fragment9,{children:[jsx16("div",{"aria-hidden":!0,className:joinClassNames(classNames.flexCol,verticalScrolling&&options.expandRows&&classNames.grow,absPrint?classNames.fillX:classNames.rel),children:props.slatMetas.map((slatMeta,slatI)=>jsx16("div",{className:joinClassNames(classNames.flexRow,slatLiquidHeight&&classNames.liquid),style:{height:slatLiquidHeight?"":slatHeight},children:createElement5(TimeGridSlatLane,{...slatMeta,key:slatMeta.key,borderTop:!!slatI})},slatMeta.key))}),rowsNotExpanding&&jsx16("div",{className:joinClassNames(generateClassName(options.fillerClass,{inTableHeader:!1}),classNames.borderlessX,classNames.borderlessBottom,classNames.liquid)})]})]})}),!!footerScrollbarSticky&&jsx16(FooterScrollbar,{isSticky:!0,canvasWidth,scrollerRef:this.footScrollerRef,scrollbarWidthRef:this.handleStickyBottomScrollbarWidth})]})]})]}),jsx16(Ruler,{widthRef:this.handleTotalWidth})]})}componentDidMount(){this._isUnmounting=!1,this.initScrollers(),this.updateSlatHeight()}componentDidUpdate(){this.updateScrollers(),this.updateSlatHeight()}componentWillUnmount(){this._isUnmounting=!0,this.destroyScrollers(),this.prevSlatHeight=void 0,setRef(this.props.slatHeightRef,null)}updateSlatHeight(){this.prevSlatHeight!==this.slatHeight&&setRef(this.props.slatHeightRef,this.prevSlatHeight=this.slatHeight)}initScrollers(){let ScrollerSyncer=getScrollerSyncerClass(this.context.pluginHooks);this.dayScroller=new ScrollerSyncer(!0),this.timeScroller=new ScrollerSyncer,setRef(this.props.dayScrollerRef,this.dayScroller),setRef(this.props.timeScrollerRef,this.timeScroller),this.updateScrollers()}updateScrollers(){this.dayScroller.handleChildren([this.headerScrollerRef.current,this.allDayScrollerRef.current,this.mainScrollerRef.current,this.footScrollerRef.current]),this.timeScroller.handleChildren([this.axisScrollerRef.current,this.mainScrollerRef.current])}destroyScrollers(){setRef(this.props.dayScrollerRef,null),setRef(this.props.timeScrollerRef,null)}};TimeGridLayoutPannable.addPropsEquality({headerTierHeights:isArraysEqual});var TimeGridLayoutNormal=class extends BaseComponent{constructor(){super(...arguments),this.state={},this.headerLabelInnerWidthRefMap=new RefMap(()=>{afterSize(this.handleAxisInnerWidths)}),this.handleAllDayLabelInnerWidth=width=>{this.allDayLabelInnerWidth=width,afterSize(this.handleAxisInnerWidths)},this.handleWeekNumberInnerWidth=width=>{this.weekNumberInnerWidth=width,afterSize(this.handleAxisInnerWidths)},this.slatLabelInnerWidthRefMap=new RefMap(()=>{afterSize(this.handleAxisInnerWidths)}),this.slatLabelInnerHeightRefMap=new RefMap(()=>{afterSize(this.handleSlatInnerHeights)}),this.handleTotalWidth=totalWidth=>{this._isUnmounting||requestAnimationFrame(()=>{this._isUnmounting||this.setState({totalWidth})})},this.handleClientWidth=clientWidth=>{this._isUnmounting||this.setState({clientWidth})},this.handleClientHeight=clientHeight=>{this._isUnmounting||this.setState({clientHeight})},this.handleAxisInnerWidths=()=>{if(this._isUnmounting)return;let headerLabelInnerWidthMap=this.headerLabelInnerWidthRefMap.current,slatLabelInnerWidthMap=this.slatLabelInnerWidthRefMap.current,max=Math.max(this.weekNumberInnerWidth||0,this.allDayLabelInnerWidth||0);for(let headerLabelInnerWidth of headerLabelInnerWidthMap.values())max=Math.max(max,headerLabelInnerWidth);for(let slatLabelInnerWidth of slatLabelInnerWidthMap.values())max=Math.max(max,slatLabelInnerWidth);this.state.axisWidth!==max&&this.setState({axisWidth:max})},this.handleSlatInnerHeights=()=>{if(this._isUnmounting)return;let slatLabelInnerHeightMap=this.slatLabelInnerHeightRefMap.current,max=0;for(let slatLabelInnerHeight of slatLabelInnerHeightMap.values())max=Math.max(max,slatLabelInnerHeight);this.state.slatInnerHeight!==max&&this.setState({slatInnerHeight:max})}}render(){let{props,state,context,slatLabelInnerWidthRefMap,slatLabelInnerHeightRefMap,headerLabelInnerWidthRefMap}=this,{nowDate,forPrint}=props,nowTimeMs=nowDate.valueOf()-startOfDay5(nowDate).valueOf(),{axisWidth,clientWidth,totalWidth}=state,{options}=context,{borderlessX,borderlessTop,borderlessBottom}=computeViewBorderless(options),endScrollbarWidth=totalWidth!=null&&clientWidth!=null&&!forPrint?totalWidth-clientWidth:void 0,verticalScrolling=!forPrint&&!getIsHeightAuto(options),tableHeaderSticky=!forPrint&&getTableHeaderSticky(options),slatCnt=props.slatMetas.length,[slatHeight,slatLiquidHeight]=computeSlatHeight(verticalScrolling&&options.expandRows,slatCnt,options.slotMinHeight,state.slatInnerHeight,state.clientHeight);this.slatHeight=slatHeight;let totalSlatHeight=(slatHeight||0)*slatCnt,rowsNotExpanding=verticalScrolling&&!options.expandRows&&state.clientHeight!=null&&state.clientHeight>totalSlatHeight,printStackEnabled=computeTimeGridPrintMode(forPrint,options.eventPrintLayout)==="stack",absPrint=forPrint&&!printStackEnabled,simplePrint=forPrint&&printStackEnabled,forcedBodyHeight=absPrint?totalSlatHeight:void 0,colCount=props.cells.length,measuredColWidth=clientWidth!=null?clientWidth/colCount:void 0,cellIsMicro=measuredColWidth!=null&&measuredColWidth<=dayMicroWidth,cellIsNarrow=cellIsMicro||measuredColWidth!=null&&measuredColWidth<=options.dayNarrowWidth;return jsxs12(Fragment9,{children:[options.dayHeaders&&jsxs12("div",{role:"rowgroup",className:joinClassNames(generateClassName(options.tableHeaderClass,{isSticky:tableHeaderSticky,borderlessX,borderlessTop,borderlessBottom,multiMonthColumns:0}),classNames.flexCol,tableHeaderSticky&&classNames.tableHeaderSticky,classNames.z1),children:[props.headerTiers.map((rowConfig,tierNum)=>jsxs12("div",{role:"row",className:classNames.flexRow,children:[jsx16("div",{className:joinClassNames(options.dayHeaderRowClass,classNames.flexRow,classNames.borderlessX,classNames.borderlessTop,tierNum===props.headerTiers.length-1&&classNames.borderlessBottom),children:options.weekNumbers&&rowConfig.isDateRow?jsx16(TimeGridWeekNumber,{dateProfile:props.dateProfile,innerWidthRef:this.handleWeekNumberInnerWidth,innerHeightRef:headerLabelInnerWidthRefMap.createRef(tierNum),width:axisWidth,isLiquid:!1,isNarrow:cellIsNarrow}):jsx16(TimeGridAxisEmpty,{width:axisWidth,isLiquid:!1})}),jsx16("div",{className:generateClassName(options.slotHeaderDividerClass,{inTableHeader:!0,options:{dayMinWidth:options.dayMinWidth}})}),jsx16(DayGridHeaderRow,{...rowConfig,className:classNames.liquid,borderBottom:tierNum<props.headerTiers.length-1,viewportWidth:clientWidth,cellIsNarrow,cellIsMicro,rowLevel:props.headerTiers.length-tierNum-1}),!!endScrollbarWidth&&jsx16("div",{className:joinClassNames(generateClassName(options.fillerClass,{inTableHeader:!0}),classNames.borderlessY,classNames.borderlessEnd),style:{minWidth:endScrollbarWidth}})]},tierNum)),jsx16("div",{className:generateClassName(options.dayHeaderDividerClass,{isSticky:tableHeaderSticky,multiMonthColumns:0,options:{allDaySlot:!!options.allDaySlot}})})]}),jsxs12("div",{role:"rowgroup",className:joinClassNames(generateClassName(options.tableBodyClass,{borderlessX,borderlessTop,borderlessBottom,multiMonthColumns:0}),classNames.flexCol,verticalScrolling&&classNames.liquid,classNames.isolate,classNames.z0),children:[options.allDaySlot&&jsxs12(Fragment9,{children:[jsxs12("div",{role:"row",className:joinClassNames(classNames.flexRow,classNames.z1),children:[jsx16(TimeGridAllDayHeader,{width:axisWidth,innerWidthRef:this.handleAllDayLabelInnerWidth,isNarrow:cellIsNarrow}),jsx16("div",{className:generateClassName(options.slotHeaderDividerClass,{inTableHeader:!1,options:{dayMinWidth:options.dayMinWidth}})}),jsx16(TimeGridAllDayLane,{dateProfile:props.dateProfile,todayRange:props.todayRange,cells:props.cells,showDayNumbers:!1,forPrint,isHitComboAllowed:props.isHitComboAllowed,className:joinClassNames(classNames.liquidX,classNames.borderless),cellIsNarrow,cellIsMicro,fgEventSegs:props.fgEventSegs,bgEventSegs:props.bgEventSegs,businessHourSegs:props.businessHourSegs,dateSelectionSegs:props.dateSelectionSegs,eventDrag:props.eventDrag,eventResize:props.eventResize,eventSelection:props.eventSelection,dayMaxEvents:props.dayMaxEvents,dayMaxEventRows:props.dayMaxEventRows}),!!endScrollbarWidth&&jsx16("div",{className:joinClassNames(generateClassName(options.fillerClass,{inTableHeader:!1}),classNames.borderlessY,classNames.borderlessEnd),style:{minWidth:endScrollbarWidth}})]}),jsx16("div",{className:joinClassNames(options.allDayDividerClass,classNames.z2)})]}),jsx16(Scroller,{vertical:verticalScrolling,className:joinClassNames(classNames.flexCol,classNames.rel,verticalScrolling&&classNames.liquid,classNames.z0),ref:props.timeScrollerRef,clientWidthRef:this.handleClientWidth,clientHeightRef:this.handleClientHeight,children:jsxs12("div",{className:joinClassNames(classNames.flexCol,classNames.grow,classNames.rel),style:{height:forcedBodyHeight},children:[jsxs12("div",{role:"row",className:joinClassNames(classNames.flexRow,!simplePrint&&classNames.fill),children:[jsx16("div",{role:"rowheader","aria-label":options.timedText,className:classNames.contentBox,style:{width:axisWidth}}),jsx16("div",{className:generateClassName(options.slotHeaderDividerClass,{inTableHeader:!1,options:{dayMinWidth:options.dayMinWidth}})}),jsx16(TimeGridCols,{dateProfile:props.dateProfile,nowDate:props.nowDate,nowMs:props.nowMs,todayRange:props.todayRange,cells:props.cells,slatCnt,forPrint,isHitComboAllowed:props.isHitComboAllowed,className:classNames.liquid,fgEventSegsByCol:props.fgEventSegsByCol,bgEventSegsByCol:props.bgEventSegsByCol,businessHourSegsByCol:props.businessHourSegsByCol,nowIndicatorSegsByCol:props.nowIndicatorSegsByCol,dateSelectionSegsByCol:props.dateSelectionSegsByCol,eventDragByCol:props.eventDragByCol,eventResizeByCol:props.eventResizeByCol,eventSelection:props.eventSelection,slatHeight,cellIsNarrow,cellIsMicro})]}),!simplePrint&&jsxs12(Fragment9,{children:[jsx16("div",{"aria-hidden":!0,className:joinClassNames(classNames.flexCol,verticalScrolling&&options.expandRows&&classNames.grow,absPrint?classNames.fillX:classNames.rel),children:props.slatMetas.map((slatMeta,slatI)=>jsxs12("div",{className:joinClassNames(slatLiquidHeight&&classNames.liquid,classNames.flexRow),style:{height:slatLiquidHeight?void 0:slatHeight},children:[jsx16("div",{className:classNames.flexCol,style:{width:axisWidth},children:createElement5(TimeGridSlatHeader,{...slatMeta,key:slatMeta.key,innerWidthRef:slatLabelInnerWidthRefMap.createRef(slatMeta.key),innerHeightRef:slatLabelInnerHeightRefMap.createRef(slatMeta.key),borderTop:!!slatI,isNarrow:cellIsNarrow})}),jsx16("div",{className:generateClassName(options.slotHeaderDividerClass,{inTableHeader:!1,options:{dayMinWidth:options.dayMinWidth}}),style:{visibility:"hidden"}}),createElement5(TimeGridSlatLane,{...slatMeta,key:slatMeta.key,borderTop:!!slatI})]},slatMeta.key))}),rowsNotExpanding&&jsx16("div",{className:joinClassNames(generateClassName(options.fillerClass,{inTableHeader:!1}),classNames.borderlessX,classNames.borderlessBottom,classNames.liquid)}),!forPrint&&options.nowIndicator&&rangeContainsMarker(props.dateProfile.currentRange,nowDate)&&nowTimeMs>=props.dateProfile.slotMinTime.milliseconds&&nowTimeMs<props.dateProfile.slotMaxTime.milliseconds&&jsx16(TimeGridNowIndicatorArrow,{nowDate,dateProfile:props.dateProfile,totalHeight:slatHeight!=null?slatHeight*slatCnt:void 0})]})]})})]}),jsx16(Ruler,{widthRef:this.handleTotalWidth})]})}componentDidMount(){this._isUnmounting=!1,this.updateSlatHeight()}componentDidUpdate(){this.updateSlatHeight()}componentWillUnmount(){this._isUnmounting=!0,this.prevSlatHeight=void 0,setRef(this.props.slatHeightRef,null)}updateSlatHeight(){this.prevSlatHeight!==this.slatHeight&&setRef(this.props.slatHeightRef,this.prevSlatHeight=this.slatHeight)}};function buildEmptySegCols(segsByCol){return segsByCol.map(()=>[])}function buildEmptyInteractionCols(interactionsByCol){return interactionsByCol.map(()=>null)}var TimeGridLayout=class extends BaseComponent{constructor(){super(...arguments),this.buildSlatMetas=memoize2(buildSlatMetas),this.dayScrollerRef=createRef3(),this.timeScrollerRef=createRef3(),this.scrollState={},this.handleSlatHeight=slatHeight=>{this._isUnmounting||(this.slatHeight=slatHeight,slatHeight!=null&&afterSize(this.applyTimeScroll))},this.handleTimeScrollRequest=scrollTime=>{this.scrollState.time=scrollTime,this.scrollState.y=void 0,this.applyTimeScroll()},this.handleTimeScrollEnd=isDevice=>{if(isDevice){let y=this.timeScrollerRef.current.y;this.props.forPrint||(this.scrollState.y=y,this.scrollState.time=void 0)}},this.applyTimeScroll=()=>{let timeScroller=this.timeScrollerRef.current,{slatHeight,scrollState}=this,{y,time}=scrollState;y==null&&time&&slatHeight!=null&&timeScroller&&(y=computeTimeTopFrac(time,this.props.dateProfile)*(slatHeight*this.currentSlatCnt),y&&y++,scrollState.y=y),y!=null&&timeScroller.scrollTo({y})}}render(){let{props,context}=this,{dateProfile}=props,{options,dateEnv}=context,{dayMinWidth}=options,{borderlessX,borderlessTop,borderlessBottom}=computeViewBorderless(options),slatMetas=this.buildSlatMetas(dateProfile.slotMinTime,dateProfile.slotMaxTime,options.slotHeaderInterval,options.slotDuration,dateEnv);this.currentSlatCnt=slatMetas.length;let dateSelectionSegs=props.forPrint?[]:props.dateSelectionSegs,eventDrag=props.forPrint?null:props.eventDrag,eventResize=props.forPrint?null:props.eventResize,dateSelectionSegsByCol=props.forPrint?buildEmptySegCols(props.dateSelectionSegsByCol):props.dateSelectionSegsByCol,eventDragByCol=props.forPrint?buildEmptyInteractionCols(props.eventDragByCol):props.eventDragByCol,eventResizeByCol=props.forPrint?buildEmptyInteractionCols(props.eventResizeByCol):props.eventResizeByCol,commonLayoutProps={dateProfile,nowDate:props.nowDate,nowMs:props.nowMs,todayRange:props.todayRange,cells:props.cells,slatMetas,forPrint:props.forPrint,isHitComboAllowed:props.isHitComboAllowed,headerTiers:props.headerTiers,fgEventSegs:props.fgEventSegs,bgEventSegs:props.bgEventSegs,businessHourSegs:props.businessHourSegs,dateSelectionSegs,eventDrag,eventResize,...getAllDayMaxEventProps(options),fgEventSegsByCol:props.fgEventSegsByCol,bgEventSegsByCol:props.bgEventSegsByCol,businessHourSegsByCol:props.businessHourSegsByCol,nowIndicatorSegsByCol:props.nowIndicatorSegsByCol,dateSelectionSegsByCol,eventDragByCol,eventResizeByCol,eventSelection:props.eventSelection,timeScrollerRef:this.timeScrollerRef,timeScrollState:this.scrollState,slatHeightRef:this.handleSlatHeight,borderlessX,borderlessBottom};return jsx16(ViewContainer,{attrs:{role:"grid","aria-colcount":props.cells.length,"aria-labelledby":props.labelId,"aria-label":props.labelStr},className:joinClassNames(props.className,generateClassName(options.tableClass,{borderlessX,borderlessTop,borderlessBottom,multiMonthColumns:0}),!props.forPrint&&classNames.flexCol,classNames.isolate),viewSpec:context.viewSpec,children:dayMinWidth?jsx16(TimeGridLayoutPannable,{...commonLayoutProps,dayMinWidth,dayScrollerRef:this.dayScrollerRef}):jsx16(TimeGridLayoutNormal,{...commonLayoutProps})})}componentDidMount(){this._isUnmounting=!1,this.resetScroll(),this.context.emitter.on("_timeScrollRequest",this.handleTimeScrollRequest);let timeScroller=this.timeScrollerRef.current;timeScroller&&timeScroller.addScrollEndListener(this.handleTimeScrollEnd)}componentDidUpdate(prevProps){prevProps.dateProfile!==this.props.dateProfile&&this.context.options.scrollTimeReset?this.resetScroll():prevProps.forPrint&&!this.props.forPrint&&this.applyTimeScroll()}componentWillUnmount(){this._isUnmounting=!0,this.context.emitter.off("_timeScrollRequest",this.handleTimeScrollRequest);let timeScroller=this.timeScrollerRef.current;timeScroller&&timeScroller.removeScrollEndListener(this.handleTimeScrollEnd)}resetScroll(){this.handleTimeScrollRequest(this.context.options.scrollTime);let dayScroller=this.dayScrollerRef.current;dayScroller&&dayScroller.scrollTo({x:0})}},AUTO_ALL_DAY_MAX_EVENT_ROWS=5;function getAllDayMaxEventProps(options){let{dayMaxEvents,dayMaxEventRows}=options;return(dayMaxEvents===!0||dayMaxEventRows===!0)&&(dayMaxEvents=void 0,dayMaxEventRows=AUTO_ALL_DAY_MAX_EVENT_ROWS),{dayMaxEvents,dayMaxEventRows}}var TimeGridView=class extends DateComponent{constructor(){super(...arguments),this.createDayHeaderFormatter=memoize2(createDayHeaderFormatter),this.buildDaySeries=memoize2((dateProfile,dateProfileGenerator)=>new DaySeriesModel(dateProfile.renderRange,dateProfileGenerator)),this.buildDayCols=memoize2(buildDayColsFromSeries),this.extractColDates=memoize2(cols=>cols.map(col=>col.date)),this.extractColRanges=memoize2(cols=>cols.map(col=>col.range)),this.buildDateRowConfigs=memoize2(buildDateRowConfigs),this.splitFgEventSegs=memoize2(organizeSegsByCol),this.splitBgEventSegs=memoize2(organizeSegsByCol),this.splitBusinessHourSegs=memoize2(organizeSegsByCol),this.splitNowIndicatorSegs=memoize2(organizeSegsByCol),this.splitDateSelectionSegs=memoize2(organizeSegsByCol),this.splitEventDrag=memoize2(splitInteractionByCol),this.splitEventResize=memoize2(splitInteractionByCol),this.allDaySplitter=new AllDaySplitter,this.daySeriesSlicer=new DaySeriesSlicer,this.dayTimeColsSlicer=new DayTimeColsSlicer}render(){let{props,context}=this,{dateProfile}=props,{options,dateProfileGenerator}=context,daySeries=this.buildDaySeries(dateProfile,dateProfileGenerator),cols=this.buildDayCols(daySeries,context.dateEnv,{slotRange:dateProfile,activeRange:dateProfile.activeRange}),colDates=this.extractColDates(cols),dayRanges=this.extractColRanges(cols),splitProps=this.allDaySplitter.splitProps(props),allDayProps=this.daySeriesSlicer.sliceProps(splitProps.allDay,dateProfile,options.nextDayThreshold,context,daySeries),timedProps=this.dayTimeColsSlicer.sliceProps(splitProps.timed,dateProfile,null,context,dayRanges),dayHeaderFormat=this.createDayHeaderFormatter(context.options.dayHeaderFormat,!0,cols.length);return jsx17(NowTimer,{unit:options.nowIndicator?"minute":"day",children:(nowDate,todayRange,nowMs)=>{let colCount=cols.length,nowIndicatorSeg=!props.forPrint&&options.nowIndicator&&this.dayTimeColsSlicer.sliceNowDate(nowDate,dateProfile,options.nextDayThreshold,context,dayRanges),fgEventSegsByCol=this.splitFgEventSegs(timedProps.fgEventSegs,colCount),bgEventSegsByCol=this.splitBgEventSegs(timedProps.bgEventSegs,colCount),businessHourSegsByCol=this.splitBusinessHourSegs(timedProps.businessHourSegs,colCount),nowIndicatorSegsByCol=this.splitNowIndicatorSegs(nowIndicatorSeg,colCount),dateSelectionSegsByCol=this.splitDateSelectionSegs(timedProps.dateSelectionSegs,colCount),eventDragByCol=this.splitEventDrag(timedProps.eventDrag,colCount),eventResizeByCol=this.splitEventResize(timedProps.eventResize,colCount),headerTiers=this.buildDateRowConfigs(colDates,!0,props.dateProfile,todayRange,dayHeaderFormat,context);return jsx17(TimeGridLayout,{labelId:props.labelId,labelStr:props.labelStr,dateProfile,nowDate,nowMs,todayRange,cells:cols,forPrint:props.forPrint,className:props.className,headerTiers,fgEventSegs:allDayProps.fgEventSegs,bgEventSegs:allDayProps.bgEventSegs,businessHourSegs:allDayProps.businessHourSegs,dateSelectionSegs:allDayProps.dateSelectionSegs,eventDrag:allDayProps.eventDrag,eventResize:allDayProps.eventResize,fgEventSegsByCol,bgEventSegsByCol,businessHourSegsByCol,nowIndicatorSegsByCol,dateSelectionSegsByCol,eventDragByCol,eventResizeByCol,eventSelection:props.eventSelection})}})}},timeGridPlugin={name:"timegrid",initialView:"timeGridWeek",deps:[dayGridPlugin],views:{timeGrid:{component:TimeGridView,usesMinMaxTime:!0,allDaySlot:!0,slotDuration:"00:30:00",slotEventOverlap:!0},timeGridDay:{type:"timeGrid",duration:{days:1}},timeGridWeek:{type:"timeGrid",duration:{weeks:1}}}};import{Button as Button4,Group as Group4,Loader as Loader2,SegmentedControl,Title as Title2,useComputedColorScheme}from"@mantine/core";import{useDebouncedCallback}from"@mantine/hooks";import{assertNever as assertNever3}from"@medplum/core";import{useCallback as useCallback8,useEffect as useEffect4,useMemo as useMemo3,useRef as useRef2}from"react";var CalendarBase_default={wrapper:"CalendarBase_wrapper",calendar:"CalendarBase_calendar",listItemEventBefore:"CalendarBase_listItemEventBefore",clickable:"CalendarBase_clickable",selectedRange:"CalendarBase_selectedRange",eventTitle:"CalendarBase_eventTitle",eventTime:"CalendarBase_eventTime",eventInner:"CalendarBase_eventInner",shortEvent:"CalendarBase_shortEvent",backgroundEventInner:"CalendarBase_backgroundEventInner",backgroundEvent:"CalendarBase_backgroundEvent",nonBusinessHours:"CalendarBase_nonBusinessHours",event:"CalendarBase_event"};import{EMPTY,getReferenceString as getReferenceString9}from"@medplum/core";var DayIndexer=["sun","mon","tue","wed","thu","fri","sat"];function availableTimeToBusinessHoursEntry(availableTime){let startTime=availableTime.allDay?"00:00:00":availableTime.availableStartTime,endTime=availableTime.allDay?"24:00:00":availableTime.availableEndTime;if(!startTime||!endTime||!availableTime.daysOfWeek)return[];let daysOfWeek=availableTime.daysOfWeek.map(day=>DayIndexer.indexOf(day));return endTime<=startTime?[{daysOfWeek,startTime,endTime:"24:00:00"},{daysOfWeek:daysOfWeek.map(day=>(day+1)%7),startTime:"00:00:00",endTime}]:[{daysOfWeek,startTime,endTime}]}function filterBookedSlots(slots,appointments){let appointmentIndex=appointments.reduce((acc,appointment)=>((appointment.slot??EMPTY).forEach(slotRef=>{let key=getReferenceString9(slotRef);key&&(acc[key]=appointment)}),acc),{});return slots.filter(slot=>{let key=getReferenceString9(slot);if(key&&appointmentIndex[key]){let appointment=appointmentIndex[key];if(slot.start===appointment.start&&slot.end===appointment.end)return!1}return!0})}import{jsx as jsx18,jsxs as jsxs13}from"react/jsx-runtime";function appointmentsToEvents(appointments,schedule,extra){return appointments.filter(appointment=>appointment.start&&appointment.end).map(appointment=>{let name=appointment.participant.find(p=>p.actor?.reference?.startsWith("Patient/"))?.actor?.display??"No Patient";return{id:appointment.id,title:name,start:appointment.start,end:appointment.end,extendedProps:{type:"appointment",appointment,schedule},className:`appointment ${appointment.status}`,...extra}})}function slotTitle(slot){return slot.status==="free"?"Available":slot.status==="entered-in-error"?"Entered in error":"Blocked"}function slotsToEvents(slots,schedule,extra){return slots.map(slot=>({id:slot.id,start:slot.start,end:slot.end,title:slotTitle(slot),extendedProps:{type:"slot",slot,schedule},className:`slot ${slot.status}`,...extra}))}function CalendarBase(props){let colorScheme=useComputedColorScheme(),controller=useCalendarController(),{onRangeChange,className,availableTime,onSelectAppointment,onSelectSlot,onDoubleClickAppointment,onDoubleClickSlot,onSelectInterval,selection,loading,...fullCalendarProps}=props,eventSources=useMemo3(()=>props.eventSources.map(fhirSource=>{let{schedule,slots,appointments,...source}=fhirSource,filteredSlots=filterBookedSlots(slots,appointments),appointmentExtra={interactive:!!(props.onSelectAppointment||props.onDoubleClickAppointment)},slotExtra={interactive:!1,display:"background"};return{...source,events:[...appointmentsToEvents(appointments,schedule,appointmentExtra),...slotsToEvents(filteredSlots,schedule,slotExtra)]}}),[props.eventSources,props.onDoubleClickAppointment,props.onSelectAppointment]),rawEventClick=useCallback8(eventClickInfo=>{let ext=eventClickInfo.event.extendedProps;ext.type==="appointment"?onSelectAppointment?.(ext.appointment,ext.schedule):ext.type==="slot"?onSelectSlot?.(ext.slot,ext.schedule):assertNever3(ext)},[onSelectAppointment,onSelectSlot]),eventDoubleClickHandler=useCallback8(e=>{let ext=e.extendedProps;return ext?.type==="appointment"?(onDoubleClickAppointment?.(ext.appointment,ext.schedule),!0):(ext.type==="slot"?onDoubleClickSlot?.(ext.slot,ext.schedule):assertNever3(ext),!1)},[onDoubleClickAppointment,onDoubleClickSlot]),hasDoubleClickHandler=!!(onDoubleClickAppointment||onDoubleClickSlot),eventClickDebounced=useDebouncedCallback(rawEventClick??(()=>{}),100),eventClick=hasDoubleClickHandler?eventClickDebounced:rawEventClick,eventDataRef=useRef2(new WeakMap),eventDoubleClickRef=useRef2(eventDoubleClickHandler);useEffect4(()=>{eventDoubleClickRef.current=eventDoubleClickHandler},[eventDoubleClickHandler]);let handleDblClick=useCallback8(e=>{let event=eventDataRef.current.get(e.currentTarget);event&&(eventClickDebounced.cancel(),eventDoubleClickRef.current?.(event))},[eventClickDebounced]),businessHours=availableTime?.flatMap(availableTimeToBusinessHoursEntry),selectable=!!(onSelectInterval||selection),calendarRef=useRef2(null),startMs=selection?.start.getTime(),endMs=selection?.end.getTime();return useEffect4(()=>{let api=calendarRef.current?.getApi();api&&(startMs!==void 0&&endMs!==void 0?api.select(startMs,endMs):api.unselect())},[startMs,endMs]),jsxs13("div",{"data-testid":"calendar",className:clsx_default(CalendarBase_default.wrapper,className),children:[jsxs13(Group4,{justify:"space-between",pb:"sm",children:[jsxs13(Group4,{gap:"md",children:[jsxs13(Button4.Group,{children:[jsx18(Button4,{variant:"default",size:"xs","aria-label":"Previous",onClick:()=>controller.prev(),children:jsx18(IconChevronLeft,{size:12})}),jsx18(Button4,{variant:"default",size:"xs",onClick:()=>controller.today(),children:"Today"}),jsx18(Button4,{variant:"default",size:"xs","aria-label":"Next",onClick:()=>controller.next(),children:jsx18(IconChevronRight,{size:12})})]}),jsxs13(Group4,{children:[jsx18(Title2,{order:4,children:controller.view?.title}),loading&&jsx18(Loader2,{size:"sm"})]})]}),jsx18(SegmentedControl,{size:"xs",value:controller.view?.type,onChange:newView=>controller.changeView(newView),data:[{label:"Month",value:"dayGridMonth"},{label:"Week",value:"timeGridWeek"},{label:"Day",value:"timeGridDay"}]})]}),jsx18(Calendar,{height:"100%",plugins:[timeGridPlugin,dayGridPlugin,index,interactionPlugin],initialView:"timeGridWeek",slotMinHeight:38,colorScheme,displayEventEnd:!1,eventTimeFormat:{timeStyle:"short"},views:{timeGridWeek:{allDaySlot:!1},timeGridDay:{allDaySlot:!1}},selectable,unselectAuto:!1,select:eventInfo=>{eventInfo.jsEvent&&onSelectInterval?.({start:eventInfo.start,end:eventInfo.end})},...fullCalendarProps,ref:calendarRef,eventSources,controller,headerToolbar:!1,datesSet:info=>onRangeChange?.({start:info.start,end:info.end}),className:clsx_default(CalendarBase_default.calendar,controller.view?.type),eventDidMount:info=>{hasDoubleClickHandler&&(eventDataRef.current.set(info.el,info.event),info.el.addEventListener("dblclick",handleDblClick))},businessHours,eventClick,eventClass:evt=>clsx_default(props.eventClass,CalendarBase_default.event,{[CalendarBase_default.clickable]:evt.isInteractive,[CalendarBase_default.shortEvent]:evt.isShort}),eventTimeClass:clsx_default(props.eventTimeClass,CalendarBase_default.eventTime),eventTitleClass:clsx_default(props.eventTitleClass,CalendarBase_default.eventTitle),eventInnerClass:clsx_default(props.eventInnerClass,CalendarBase_default.eventInner),backgroundEventClass:clsx_default(props.backgroundEventClass,CalendarBase_default.backgroundEvent),backgroundEventInnerClass:clsx_default(props.backgroundEventInnerClass,CalendarBase_default.backgroundEventInner),listItemEventBeforeClass:clsx_default(props.listItemEventBeforeClass,CalendarBase_default.listItemEventBefore),nonBusinessHoursClass:clsx_default(props.nonBusinessHoursClass,CalendarBase_default.nonBusinessHours),dayLaneClass:clsx_default(props.dayLaneClass,selectable&&CalendarBase_default.clickable),dayCellClass:clsx_default(props.dayCellClass,selectable&&CalendarBase_default.clickable),highlightClass:clsx_default(props.highlightClass,CalendarBase_default.selectedRange)})]})}var Calendar_default={wrapper:"Calendar_wrapper",event:"Calendar_event",eventTitle:"Calendar_eventTitle",backgroundEvent:"Calendar_backgroundEvent",eventInner:"Calendar_eventInner",backgroundEventInner:"Calendar_backgroundEventInner"};import{jsx as jsx19}from"react/jsx-runtime";function Calendar2(props){let{slots,appointments,...baseProps}=props,eventSources=useMemo4(()=>[{appointments:appointments??[],slots:slots??[]}],[appointments,slots]);return jsx19(CalendarBase,{eventSources,...baseProps,nowIndicator:!0,className:clsx_default(props.className,Calendar_default.wrapper),eventClass:Calendar_default.event,eventInnerClass:Calendar_default.eventInner,backgroundEventClass:Calendar_default.backgroundEvent,backgroundEventInnerClass:Calendar_default.backgroundEventInner,eventTitleClass:Calendar_default.eventTitle})}import{useMantineTheme}from"@mantine/core";import{getExtensionValue,SchedulingScheduleColorURI}from"@medplum/core";import{useMemo as useMemo5}from"react";var FALLBACK_COLORS=["indigo","teal","pink","violet","blue","cyan","lime","red","yellow","grape","orange"];function resolveThemeColor(theme,explicit,fallbackIndex){return explicit&&Object.hasOwn(theme.colors,explicit)?explicit:FALLBACK_COLORS[fallbackIndex%FALLBACK_COLORS.length]}var MultiCalendar_default={eventInner:"MultiCalendar_eventInner",eventTime:"MultiCalendar_eventTime"};import{jsx as jsx20}from"react/jsx-runtime";function MultiCalendar(props){let theme=useMantineTheme(),{sources,...calendarBaseProps}=props,eventSources=useMemo5(()=>sources.map((source,i)=>{let colorName=source.color&&Object.hasOwn(theme.colors,source.color)?source.color:void 0;if(!colorName){let extColor=getExtensionValue(source.schedule,SchedulingScheduleColorURI);typeof extColor=="string"&&(colorName=extColor)}let color=theme.colors[resolveThemeColor(theme,colorName,i)][7];return{...source,color}}),[sources,theme]);return jsx20(CalendarBase,{eventSources,nowIndicator:!0,...calendarBaseProps,eventInnerClass:MultiCalendar_default.eventInner,eventTimeClass:MultiCalendar_default.eventTime,availableTime:props.availableTime,eventTimeFormat:{hour:"numeric",minute:"2-digit",omitZeroMinute:!0,meridiem:"lowercase"}})}import{ActionIcon as ActionIcon2,Anchor,Box as Box2,Button as Button5,Divider,Group as Group6,Paper as Paper2,Stack as Stack6,Switch,Text as Text7,Tooltip,VisuallyHidden}from"@mantine/core";import{clearScheduleParameter,getScheduleParameters as getScheduleParameters2}from"@medplum/core";import{Fragment as Fragment10,useId,useRef as useRef4,useState as useState7}from"react";import{getExtensions as getExtensions2,getScheduleParameters,isDayOfWeek,OperationOutcomeError,setScheduleParameter,validationError}from"@medplum/core";function getSingleValue(availableTime,url){let matches=getExtensions2(availableTime,url);if(matches.length>1)throw new OperationOutcomeError(validationError(`availableTime must set at most one ${url}, found ${matches.length}`));return matches[0]}function toAvailableTime(availableTime){let daysOfWeek=getExtensions2(availableTime,"daysOfWeek").map(subextension=>subextension.valueCode).filter(isDayOfWeek),allDay=getSingleValue(availableTime,"allDay"),start=getSingleValue(availableTime,"availableStartTime"),end=getSingleValue(availableTime,"availableEndTime");return allDay?.valueBoolean?{daysOfWeek,allDay:!0}:{daysOfWeek,availableStartTime:start?.valueTime,availableEndTime:end?.valueTime}}function getScheduleAvailability(schedule,service){let availability=getScheduleParameters(schedule,service,"availability");if(availability.length)return availability.flatMap(extension=>getExtensions2(extension,"availableTime")).map(toAvailableTime)}function getEffectiveAvailability(service,schedule){if(service)return(schedule&&getScheduleAvailability(schedule,service))??service.availableTime}function buildAvailableTimeExtension(entry){let days=(entry.daysOfWeek??[]).map(day=>({url:"daysOfWeek",valueCode:day}));if(entry.allDay)return{url:"availableTime",extension:[...days,{url:"allDay",valueBoolean:!0}]};if(!entry.availableStartTime||!entry.availableEndTime)throw new OperationOutcomeError(validationError("availableTime must set allDay, or both availableStartTime and availableEndTime",void 0,"required"));return{url:"availableTime",extension:[...days,{url:"availableStartTime",valueTime:entry.availableStartTime},{url:"availableEndTime",valueTime:entry.availableEndTime}]}}function buildAvailabilityExtension(availableTime){if(!availableTime.length)throw new OperationOutcomeError(validationError("availability must have at least one availableTime; to follow the service default, clear it instead",void 0,"required"));return{url:"availability",extension:availableTime.map(buildAvailableTimeExtension)}}function setScheduleAvailability(schedule,service,availableTime){return setScheduleParameter(schedule,service,buildAvailabilityExtension(availableTime))}var ScheduleAvailabilityEditor_default={week:"ScheduleAvailabilityEditor_week",dayCell:"ScheduleAvailabilityEditor_dayCell",rangeStart:"ScheduleAvailabilityEditor_rangeStart",rangeSeparator:"ScheduleAvailabilityEditor_rangeSeparator",rangeEnd:"ScheduleAvailabilityEditor_rangeEnd",addAction:"ScheduleAvailabilityEditor_addAction",removeAction:"ScheduleAvailabilityEditor_removeAction",unavailable:"ScheduleAvailabilityEditor_unavailable",overrideToggle:"ScheduleAvailabilityEditor_overrideToggle"};import{DAYS_OF_WEEK,isDayOfWeek as isDayOfWeek2}from"@medplum/core";var MINUTES_PER_DAY=1440,TIME_STEP_MINUTES=15,DEFAULT_RANGE={start:540,end:1020},DAY_LABELS={mon:"Monday",tue:"Tuesday",wed:"Wednesday",thu:"Thursday",fri:"Friday",sat:"Saturday",sun:"Sunday"},DAY_DISPLAY_ORDER=["sun","mon","tue","wed","thu","fri","sat"];function blankWeeklyAvailability(){let weekly={};for(let day of DAYS_OF_WEEK)weekly[day]={available:!1,ranges:[{...DEFAULT_RANGE}]};return weekly}function nextDayOfWeek(day){return DAYS_OF_WEEK[(DAYS_OF_WEEK.indexOf(day)+1)%DAYS_OF_WEEK.length]}function parseTimeOfDay(time){let match=/^(\d{1,2}):(\d{2})(?::(\d{2}(?:\.\d+)?))?$/.exec(time??"");if(!match)return;let hours=Number(match[1]),minutes=Number(match[2]);if(!(hours>23||minutes>59))return hours*60+minutes+Math.round(Number(match[3]??0)/60)}function formatTimeOfDay(minutes){let total=minutes%MINUTES_PER_DAY,hh=Math.floor(total/60).toString().padStart(2,"0"),mm=(total%60).toString().padStart(2,"0");return`${hh}:${mm}:00`}function normalizeRanges(ranges){let sorted=[...ranges].filter(range=>range.end>range.start).sort((a,b)=>a.start-b.start),merged=[];for(let range of sorted){let previous=merged[merged.length-1];previous&&range.start<=previous.end?merged[merged.length-1]={start:previous.start,end:Math.max(previous.end,range.end)}:merged.push(range)}return merged}function toWeeklyAvailability(availableTime){let weekly=blankWeeklyAvailability(),collected={};for(let day of DAYS_OF_WEEK)collected[day]=[];for(let entry of availableTime??[]){let days=(entry.daysOfWeek??[]).filter(isDayOfWeek2);if(entry.allDay===!0){for(let day of days)collected[day].push({start:0,end:MINUTES_PER_DAY});continue}let start=parseTimeOfDay(entry.availableStartTime),end=parseTimeOfDay(entry.availableEndTime);if(!(start===void 0||end===void 0))for(let day of days)end>start?collected[day].push({start,end}):(collected[day].push({start,end:MINUTES_PER_DAY}),end>0&&collected[nextDayOfWeek(day)].push({start:0,end}))}for(let day of DAYS_OF_WEEK){let ranges=normalizeRanges(collected[day]);ranges.length>0&&(weekly[day]={available:!0,ranges})}return weekly}function fromWeeklyAvailability(weekly){let availableTime=[];for(let day of DAYS_OF_WEEK)if(weekly[day].available)for(let range of weekly[day].ranges)range.start===0&&range.end===MINUTES_PER_DAY?availableTime.push({daysOfWeek:[day],allDay:!0}):availableTime.push({daysOfWeek:[day],availableStartTime:formatTimeOfDay(range.start),availableEndTime:formatTimeOfDay(range.end)});return availableTime}function hasAnyAvailableDay(weekly){return DAYS_OF_WEEK.some(day=>weekly[day].available&&weekly[day].ranges.length>0)}function formatMinutesOfDay(minutes){if(minutes===MINUTES_PER_DAY)return"12:00 AM";let hours=Math.floor(minutes/60),meridiem=hours<12?"AM":"PM";return`${hours%12===0?12:hours%12}:${(minutes%60).toString().padStart(2,"0")} ${meridiem}`}function ceilToTimeStep(minutes){return Math.ceil(minutes/TIME_STEP_MINUTES)*TIME_STEP_MINUTES}function timeOptions(min,max,include=[]){let options=new Set;for(let minutes=ceilToTimeStep(min);minutes<=max;minutes+=TIME_STEP_MINUTES)options.add(minutes);for(let time of include)time>=min&&time<=max&&options.add(time);return[...options].sort((a,b)=>a-b)}function nearestOption(options,value){let nearest;for(let option of options)(nearest===void 0||Math.abs(option-value)<Math.abs(nearest-value))&&(nearest=option);return nearest}function readMeridiem(query){let lower=query.toLowerCase();if(lower.includes("a"))return"am";if(lower.includes("p"))return"pm"}function rankMinutes(minutes){return minutes.length===2?0:minutes.length===0?1:2}function parseTimeQuery(query){let digits=query.replace(/[^0-9]/g,"");if(!digits)return[];let meridiem=readMeridiem(query);return[1,2].filter(hourDigits=>{let hour=Number(digits.slice(0,hourDigits)),minutes=digits.slice(hourDigits);return hourDigits<=digits.length&&hour>=1&&hour<=12&&minutes.length<=2&&(hourDigits===1||hour>=10||digits.startsWith("0"))}).map(hourDigits=>{let minutes=digits.slice(hourDigits);return{hour:Number(digits.slice(0,hourDigits)),minutes,meridiem,rank:rankMinutes(minutes)}}).sort((a,b)=>a.rank-b.rank)}function isTimeQuery(query){return parseTimeQuery(query).length>0}function matchesTimeQuery(minutes,query){let total=minutes===MINUTES_PER_DAY?0:minutes,hours=Math.floor(total/60);return(hours%12===0?12:hours%12)!==query.hour||query.meridiem&&query.meridiem!==(hours<12?"am":"pm")?!1:(total%60).toString().padStart(2,"0").startsWith(query.minutes)}function leadWithNearestHour(options,current){let byHour=new Map;options.forEach((option,index2)=>{let hour=Math.floor(option/60),distance=Math.abs(option-current),seen=byHour.get(hour);byHour.set(hour,seen?{index:seen.index,distance:Math.min(seen.distance,distance)}:{index:index2,distance})});let rotateAt=0,nearest=1/0;return byHour.forEach(entry=>{entry.distance<nearest&&(nearest=entry.distance,rotateAt=entry.index)}),rotateAt===0?options:[...options.slice(rotateAt),...options.slice(0,rotateAt)]}function typedTimes(query){return parseTimeQuery(query).filter(parsed=>parsed.minutes.length===2&&Number(parsed.minutes)<60).flatMap(parsed=>{let hour=parsed.hour%12,minutes=Number(parsed.minutes);return(parsed.meridiem?[parsed.meridiem]:["am","pm"]).map(meridiem=>(meridiem==="am"?hour:hour+12)*60+minutes)})}function filterTimeOptions(options,query,current){let queries=parseTimeQuery(query);if(queries.length===0)return options;let seen=new Set,matches=[];for(let parsed of queries){let matched=options.filter(option=>!seen.has(option)&&matchesTimeQuery(option,parsed));matched.forEach(option=>seen.add(option)),matches.push(...leadWithNearestHour(matched,current))}return matches}function canAddRange(ranges){return ranges.length>0&&ranges[ranges.length-1].end<=MINUTES_PER_DAY-TIME_STEP_MINUTES}function nextRange(ranges){let lastEnd=ranges[ranges.length-1].end,start=Math.max(ceilToTimeStep(lastEnd),Math.min(ceilToTimeStep(lastEnd+60),MINUTES_PER_DAY-TIME_STEP_MINUTES));return{start,end:Math.min(start+60,MINUTES_PER_DAY)}}import{Combobox,Group as Group5,InputBase,Text as Text6,useCombobox}from"@mantine/core";import{forwardRef as forwardRef3,useEffect as useEffect5,useImperativeHandle as useImperativeHandle2,useRef as useRef3,useState as useState6}from"react";import{jsx as jsx21,jsxs as jsxs14}from"react/jsx-runtime";var FLASH_DURATION_MS=700,INPUT_STYLES={input:{transition:"border-color 450ms"}},FLASH_STYLES={input:{...INPUT_STYLES.input,borderColor:"var(--mantine-primary-color-filled)"}},TimeSelect=forwardRef3(function(props,ref){let{value,min,max,label,onChange,disabled,testId,className}=props,[query,setQuery]=useState6(""),[typing,setTyping]=useState6(!1),inputRef=useRef3(null),activeOptionRef=useRef3(null),submitting=useRef3(!1),combobox=useCombobox({onDropdownClose:()=>combobox.resetSelectedOption()}),[flashId,setFlashId]=useState6(),flashing=flashId!==void 0;useImperativeHandle2(ref,()=>({flash:()=>setFlashId(previous=>(previous??0)+1)}),[]),useEffect5(()=>{if(flashId===void 0)return;let timer=setTimeout(()=>setFlashId(void 0),FLASH_DURATION_MS);return()=>clearTimeout(timer)},[flashId]);let{dropdownOpened,selectActiveOption}=combobox;useEffect5(()=>{if(!dropdownOpened)return;let frame=requestAnimationFrame(()=>{selectActiveOption(),activeOptionRef.current?.scrollIntoView({block:"center"})});return()=>cancelAnimationFrame(frame)},[dropdownOpened,selectActiveOption]);let display=formatMinutesOfDay(value),typed=typing?query:"",options=filterTimeOptions(timeOptions(min,max,[value,...typedTimes(typed)]),typed,value),scrollTo=options.includes(value)?value:nearestOption(options,value);function handleSubmit(selected){onChange(selected),setQuery(""),setTyping(!1),combobox.closeDropdown(),submitting.current=!0,inputRef.current?.blur(),submitting.current=!1}function handleBlur(){if(!submitting.current&&typing&&isTimeQuery(query)){let highlighted=options[combobox.getSelectedOptionIndex()]??options[0];highlighted!==void 0&&onChange(highlighted)}setTyping(!1),setQuery(""),combobox.closeDropdown()}return jsxs14(Combobox,{store:combobox,keepMounted:!1,onOptionSubmit:selected=>handleSubmit(Number(selected)),children:[jsx21(Combobox.Target,{children:jsx21(InputBase,{ref:inputRef,component:"input",type:"text",className,w:132,value:typing?query:display,placeholder:display,disabled,"aria-label":label,"data-testid":testId,"data-flashing":flashing||void 0,styles:flashing?FLASH_STYLES:INPUT_STYLES,rightSection:jsx21(Combobox.Chevron,{}),rightSectionPointerEvents:"none",onChange:e=>{setTyping(!0),setQuery(e.currentTarget.value),combobox.openDropdown(),combobox.selectFirstOption()},onFocus:()=>{setTyping(!0),setQuery(""),combobox.openDropdown()},onBlur:handleBlur,onClick:()=>combobox.openDropdown()})}),jsx21(Combobox.Dropdown,{children:jsx21(Combobox.Options,{mah:220,style:{overflowY:"auto"},children:options.length===0?jsx21(Combobox.Empty,{children:"No matching time"}):options.map(option=>jsx21(Combobox.Option,{value:option.toString(),active:option===value,ref:option===scrollTo?activeOptionRef:void 0,children:jsxs14(Group5,{justify:"space-between",gap:"xs",wrap:"nowrap",children:[jsx21(Text6,{span:!0,inherit:!0,children:formatMinutesOfDay(option)}),option===value&&jsx21(IconCheck,{size:14,stroke:1.8})]})},option))})})]})});import{Fragment as Fragment11,jsx as jsx22,jsxs as jsxs15}from"react/jsx-runtime";var AVAILABLE_READ_ONLY_SWITCH_STYLES={track:{backgroundColor:"var(--mantine-color-green-6)",borderColor:"transparent"}};function DayRow(props){let{day,value,readOnly,onChange,onAnnounce}=props,{available,ranges}=value,label=DAY_LABELS[day],endInputs=useRef4([]);function boundsAfter(index2){return index2===ranges.length-1?MINUTES_PER_DAY:ranges[index2+1].start}function setStart(index2,start){let range=ranges[index2],end=start>=range.end?Math.min(start+60,boundsAfter(index2)):range.end;end!==range.end&&(endInputs.current[index2]?.flash(),onAnnounce(`${label} block ${index2+1} end time changed to ${formatMinutesOfDay(end)}.`)),onChange({...value,ranges:ranges.with(index2,{start,end})})}function setEnd(index2,end){onChange({...value,ranges:ranges.with(index2,{...ranges[index2],end})})}let switchStyles=readOnly&&available?AVAILABLE_READ_ONLY_SWITCH_STYLES:void 0,canAdd=canAddRange(ranges);return jsxs15(Fragment11,{children:[jsxs15(Group6,{gap:"sm",wrap:"nowrap",className:ScheduleAvailabilityEditor_default.dayCell,children:[jsx22(Switch,{checked:available,onChange:e=>{let checked=e.currentTarget.checked;onChange({available:checked,ranges:checked&&ranges.length===0?[{...DEFAULT_RANGE}]:ranges})},color:"green.6",withThumbIndicator:!1,disabled:readOnly,styles:switchStyles,"aria-label":`Available on ${label}`,"data-testid":`schedule-availability-switch-${day}`}),jsx22(Text7,{fw:500,children:label})]}),available?ranges.map((range,index2)=>{let last=index2===ranges.length-1;return jsxs15(Fragment10,{children:[jsx22(TimeSelect,{className:ScheduleAvailabilityEditor_default.rangeStart,value:range.start,min:index2===0?0:ranges[index2-1].end,max:boundsAfter(index2)-1,onChange:start=>setStart(index2,start),disabled:readOnly,label:`${label} block ${index2+1} start time`,testId:`schedule-availability-start-${day}-${index2}`}),jsx22(Text7,{c:"dimmed",className:ScheduleAvailabilityEditor_default.rangeSeparator,children:"to"}),jsx22(TimeSelect,{ref:handle=>{endInputs.current[index2]=handle},className:ScheduleAvailabilityEditor_default.rangeEnd,value:range.end,min:range.start+1,max:boundsAfter(index2),onChange:end=>setEnd(index2,end),disabled:readOnly,label:`${label} block ${index2+1} end time`,testId:`schedule-availability-end-${day}-${index2}`}),last&&jsx22(ActionIcon2,{className:ScheduleAvailabilityEditor_default.addAction,variant:"subtle",color:"gray",radius:"xl",onClick:()=>onChange({...value,ranges:[...ranges,nextRange(ranges)]}),disabled:readOnly||!canAdd,"aria-label":`Add another block of hours on ${label}`,"data-testid":`schedule-availability-add-${day}`,children:jsx22(IconPlus,{size:16,stroke:1.8})}),ranges.length>1&&jsx22(ActionIcon2,{className:ScheduleAvailabilityEditor_default.removeAction,variant:"subtle",color:"gray",radius:"xl",onClick:()=>onChange({...value,ranges:ranges.toSpliced(index2,1)}),disabled:readOnly,"aria-label":`Remove ${label} block ${index2+1}`,"data-testid":`schedule-availability-remove-${day}-${index2}`,children:jsx22(IconMinus,{size:16,stroke:1.8})})]},index2)}):jsx22(Text7,{c:"dimmed",className:ScheduleAvailabilityEditor_default.unavailable,children:"Unavailable"})]})}function ScheduleAvailabilityEditor(props){let{schedule,service,timezone,onCancel}=props,editingDefault=schedule===void 0,[overriding,setOverriding]=useState7(()=>schedule?getScheduleParameters2(schedule,service,"availability").length>0:!0),[weekly,setWeekly]=useState7(()=>toWeeklyAvailability(getEffectiveAvailability(service,schedule))),[saving,setSaving]=useState7(!1),[announcement,setAnnouncement]=useState7({message:"",id:0}),reasonId=useId(),serviceName=service.name??"this visit service type",emptyWeek=(editingDefault||overriding)&&!hasAnyAvailableDay(weekly),emptyWeekReason=editingDefault?`Default availability must include at least one available day. Clearing every day would leave ${serviceName} bookable around the clock rather than never; to stop scheduling it, deactivate the visit service type.`:`Custom availability must include at least one available day. To stop scheduling ${serviceName} on this calendar, turn it off in schedule settings.`;function toggleOverriding(next){setOverriding(next),next||setWeekly(toWeeklyAvailability(service.availableTime))}async function handleSave(){if(!emptyWeek){setSaving(!0);try{if(props.schedule){let updated=overriding?setScheduleAvailability(props.schedule,service,fromWeeklyAvailability(weekly)):clearScheduleParameter(props.schedule,service,"availability");await props.onSave(updated)}else await props.onSave({...service,availableTime:fromWeeklyAvailability(weekly)})}catch(err){console.error(err)}finally{setSaving(!1)}}}let saveButton=jsx22(Tooltip,{label:emptyWeekReason,disabled:!emptyWeek,multiline:!0,w:300,withArrow:!0,position:"top",events:{hover:!0,focus:!0,touch:!0},children:jsx22(Button5,{onClick:handleSave,loading:saving,fullWidth:!onCancel,"data-disabled":emptyWeek||void 0,"aria-disabled":emptyWeek||void 0,"aria-describedby":emptyWeek?reasonId:void 0,children:"Save Settings"})});return jsxs15(Stack6,{gap:"lg",children:[jsx22(Text7,{c:"dimmed",children:editingDefault?`Set the default weekly working hours for ${serviceName}. Every calendar without hours of its own follows these.`:`Customize the weekly working hours on this calendar, in place of the default availability for ${serviceName}.`}),jsxs15(Paper2,{withBorder:!0,radius:"md",p:"xl",children:[!editingDefault&&jsxs15(Fragment11,{children:[jsxs15(Group6,{gap:"sm",wrap:"nowrap",className:ScheduleAvailabilityEditor_default.overrideToggle,children:[jsx22(Switch,{checked:overriding,onChange:e=>toggleOverriding(e.currentTarget.checked),color:"green.6",withThumbIndicator:!1,"aria-label":`Enable custom availability for ${serviceName}`,"data-testid":"schedule-availability-enable"}),jsxs15(Text7,{fw:500,children:["Enable custom availability for ",serviceName]})]}),jsx22(Divider,{my:"lg"})]}),jsx22(Box2,{className:ScheduleAvailabilityEditor_default.week,opacity:overriding?1:.8,children:DAY_DISPLAY_ORDER.map(day=>jsx22(DayRow,{day,value:weekly[day],readOnly:!overriding,onChange:value=>setWeekly(prev=>({...prev,[day]:value})),onAnnounce:message=>setAnnouncement(previous=>({message,id:previous.id+1}))},day))}),jsx22(VisuallyHidden,{role:"status","aria-live":"polite","data-testid":"schedule-availability-announcement",children:jsx22(Fragment10,{children:announcement.message},announcement.id)}),jsxs15(Stack6,{gap:"sm",mt:"xl",children:[!editingDefault&&jsx22(Group6,{justify:"flex-start",children:jsxs15(Anchor,{component:"button",type:"button",onClick:()=>setWeekly(toWeeklyAvailability(service.availableTime)),disabled:!overriding,c:overriding?void 0:"dimmed",underline:overriding?"hover":"never","data-testid":"schedule-availability-reset",children:["Reset to default availability of ",serviceName]})}),timezone&&jsxs15(Text7,{c:"dimmed","data-testid":"schedule-availability-timezone",children:["All times are in local ",timezone," time zone."]})]})]}),emptyWeek&&jsx22(VisuallyHidden,{id:reasonId,"data-testid":"schedule-availability-empty-week",children:emptyWeekReason}),onCancel?jsxs15(Group6,{grow:!0,children:[jsx22(Button5,{variant:"default",onClick:onCancel,children:"Cancel"}),saveButton]}):saveButton]})}import{Alert as Alert3,CloseButton,Drawer,Group as Group10,Title as Title3,useMantineTheme as useMantineTheme2}from"@mantine/core";import{getExtensionValue as getExtensionValue3,getReferenceString as getReferenceString11,isDefined as isDefined8,normalizeErrorString as normalizeErrorString4,SchedulingScheduleColorURI as SchedulingScheduleColorURI2}from"@medplum/core";import{useMedplum as useMedplum7}from"@medplum/react-hooks";import{useCallback as useCallback11,useEffect as useEffect7,useMemo as useMemo6,useState as useState11}from"react";import{getReferenceString as getReferenceString10,isDefined as isDefined6,normalizeOperationOutcome}from"@medplum/core";import{useMedplum as useMedplum5,useResourceModified}from"@medplum/react";import{useCallback as useCallback9,useEffect as useEffect6,useRef as useRef5,useState as useState8}from"react";function isWithinRange(instant,range){if(!instant||!range)return!1;let time=new Date(instant).getTime();return time>=range.start.getTime()&&time<=range.end.getTime()}function useSchedulingSlots(schedules,range,options){let medplum=useMedplum5(),[slots,setSlots]=useState8(void 0),[loading,setLoading]=useState8(!1),[error,setError]=useState8(),onErrorRef=useRef5(options?.onError);useEffect6(()=>{onErrorRef.current=options?.onError},[options?.onError]);let handleError=useCallback9(error2=>{let outcome=normalizeOperationOutcome(error2);onErrorRef.current?.(outcome),setError(outcome)},[]),scheduleRefs=[...new Set(schedules.map(schedule=>getReferenceString10(schedule)))],scheduleRefsKey=scheduleRefs.join(","),rangeStart=range?.start?.toISOString(),rangeEnd=range?.end?.toISOString();return useResourceModified("Slot",event=>{if(event.operation==="delete"){event.id&&setSlots(state=>state?.filter(slot2=>slot2.id!==event.id));return}let slot=event.resource;slot&&(!slot.schedule.reference||!scheduleRefs.includes(slot.schedule.reference)||setSlots(state=>{if(event.operation==="create"){if(!isWithinRange(slot.start,range))return state;let current=state??[];return current.some(existing=>existing.id===slot.id)?current:[...current,slot]}return state?.map(existing=>existing.id===slot.id?slot:existing)}))}),useEffect6(()=>{if(scheduleRefsKey.length===0||!rangeStart||!rangeEnd)return()=>{};let active=!0;setLoading(!0);let refs=scheduleRefsKey.split(",");return Promise.all(refs.map(scheduleRef=>medplum.searchResources("Slot",[["_count","1000"],["schedule",scheduleRef],["start",`ge${rangeStart}`],["start",`le${rangeEnd}`],["status:not","entered-in-error"]]))).then(results=>{active&&(setSlots(results.flat()),setError(void 0))}).catch(error2=>active&&handleError(error2)).finally(()=>{active&&setLoading(!1)}),()=>{active=!1,setLoading(!1)}},[medplum,scheduleRefsKey,rangeStart,rangeEnd,handleError]),{slots,loading,error}}function useSchedulingAppointments(schedules,range,options){let medplum=useMedplum5(),[appointments,setAppointments]=useState8(void 0),[loading,setLoading]=useState8(!1),[error,setError]=useState8(),onErrorRef=useRef5(options?.onError);useEffect6(()=>{onErrorRef.current=options?.onError},[options?.onError]);let handleError=useCallback9(error2=>{let outcome=normalizeOperationOutcome(error2);onErrorRef.current?.(outcome),setError(outcome)},[]),actorRefs=[...new Set(schedules.flatMap(schedule=>schedule.actor.map(ref=>getReferenceString10(ref))).filter(isDefined6))],rangeStart=range?.start?.toISOString(),rangeEnd=range?.end?.toISOString(),actorRefsKey=actorRefs.join(",");return useResourceModified("Appointment",event=>{if(event.operation==="delete"){event.id&&setAppointments(state=>state?.filter(appointment2=>appointment2.id!==event.id));return}let appointment=event.resource;appointment&&appointment.participant.some(p=>p.actor?.reference&&actorRefs.includes(p.actor.reference))&&setAppointments(state=>{if(event.operation==="create"){if(!isWithinRange(appointment.start,range))return state;let current=state??[];return current.some(existing=>existing.id===appointment.id)?current:[...current,appointment]}return state?.map(existing=>existing.id===appointment.id?appointment:existing)})}),useEffect6(()=>{if(actorRefsKey.length===0||!rangeStart||!rangeEnd)return()=>{};let active=!0;setLoading(!0);let refs=actorRefsKey.split(",");return Promise.all(refs.map(actorRef=>medplum.searchResources("Appointment",[["_count","1000"],["actor",actorRef],["date",`ge${rangeStart}`],["date",`le${rangeEnd}`]]))).then(results=>{if(!active)return;setError(void 0);let byId=new Map;for(let appointment of results.flat())byId.set(appointment.id,appointment);setAppointments([...byId.values()])}).catch(error2=>active&&handleError(error2)).finally(()=>{active&&setLoading(!1)}),()=>{active=!1,setLoading(!1)}},[medplum,actorRefsKey,rangeStart,rangeEnd,handleError]),{appointments,loading,error}}function useSchedulingResources(schedules,range,options){let slotsResult=useSchedulingSlots(schedules,range,options),appointmentsResult=useSchedulingAppointments(schedules,range,options);return{slots:slotsResult.slots,appointments:appointmentsResult.appointments,loading:slotsResult.loading||appointmentsResult.loading,error:slotsResult.error??appointmentsResult.error}}import{Alert as Alert2,Badge,Button as Button6,Divider as Divider2,Stack as Stack7,Text as Text8}from"@mantine/core";import{formatCodeableConcept as formatCodeableConcept2,isDefined as isDefined7,normalizeErrorString as normalizeErrorString3,resolveId}from"@medplum/core";import{CodeableConceptInput,ReferenceDisplay}from"@medplum/react";import{useMedplum as useMedplum6}from"@medplum/react-hooks";import{Fragment as Fragment12,useCallback as useCallback10,useState as useState9}from"react";import{HTTP_HL7_ORG as HTTP_HL7_ORG2,HTTP_TERMINOLOGY_HL7_ORG}from"@medplum/core";var APPOINTMENT_CANCELLATION_REASON_VALUE_SET=HTTP_HL7_ORG2+"/fhir/ValueSet/appointment-cancellation-reason",APPOINTMENT_CANCELLATION_REASON_CODE_SYSTEM=HTTP_TERMINOLOGY_HL7_ORG+"/CodeSystem/appointment-cancellation-reason";import{Fragment as Fragment13,jsx as jsx23,jsxs as jsxs16}from"react/jsx-runtime";var CANCELABLE_STATUSES=new Set(["pending","booked"]),STATUS_COLORS={proposed:"yellow",pending:"yellow",booked:"blue",arrived:"blue",fulfilled:"blue",cancelled:"red",noshow:"red","entered-in-error":"red","checked-in":"blue",waitlist:"gray"};function AppointmentDetails(props){let{appointment,onCancelled,cancellationReasonValueSet}=props,medplum=useMedplum6(),patient=getPatientParticipant(appointment)?.actor,otherActors=getOtherActors(appointment),[cancelling,setCancelling]=useState9(!1),[cancelError,setCancelError]=useState9(),[reason,setReason]=useState9(),cancel=useCallback10(async()=>{if(reason){setCancelling(!0),setCancelError(void 0);try{let cancelled=await medplum.post(medplum.fhirUrl("Appointment",appointment.id,"$cancel"),{resourceType:"Parameters",parameter:[{name:"cancelationReason",valueCodeableConcept:reason}]});medplum.notifyResourceModified({resourceType:"Appointment",operation:"update",id:cancelled.id,resource:cancelled});for(let slot of appointment.slot??[]){let id=resolveId(slot);id&&medplum.notifyResourceModified({resourceType:"Slot",operation:"delete",id})}try{await onCancelled?.(cancelled)}catch(error){console.error(error)}}catch(err){setCancelError(err)}finally{setCancelling(!1)}}},[appointment,medplum,onCancelled,reason]);return jsxs16(Stack7,{gap:"sm",children:[jsx23(Badge,{color:STATUS_COLORS[appointment.status],children:appointment.status}),jsx23(Detail,{label:"Patient",value:patient&&jsx23(ReferenceDisplay,{link:!1,value:patient})}),jsx23(Detail,{label:"When",value:formatWhen(appointment)}),jsx23(Detail,{label:"Service",value:formatService(appointment)}),jsx23(Detail,{label:"With",value:otherActors.length>0?otherActors.map((actor,index2)=>jsxs16(Fragment12,{children:[index2>0&&", ",jsx23(ReferenceDisplay,{value:actor,link:!1})]},actor.reference??`actor-${index2}`)):void 0}),jsx23(Detail,{label:"Notes",value:appointment.comment??appointment.description}),jsx23(Divider2,{}),jsx23(Detail,{label:"Cancellation reason",value:formatCodeableConcept2(appointment.cancelationReason)||void 0}),cancelError!==void 0&&jsx23(Alert2,{color:"red",title:"Could not cancel this appointment",children:normalizeErrorString3(cancelError)}),CANCELABLE_STATUSES.has(appointment.status)?jsxs16(Fragment13,{children:[jsx23(CodeableConceptInput,{name:"cancelationReason",path:"Appointment.cancelationReason",binding:cancellationReasonValueSet??APPOINTMENT_CANCELLATION_REASON_VALUE_SET,label:"Cancellation reason",placeholder:"Search reasons",maxValues:1,creatable:!1,withHelpText:!1,required:!0,onChange:setReason}),jsx23(Button6,{color:"red",variant:"light",loading:cancelling,disabled:!reason,onClick:cancel,children:"Cancel Appointment"})]}):jsx23(Text8,{size:"sm",c:"dimmed",children:appointment.status==="cancelled"?"This appointment is cancelled.":`An appointment in '${appointment.status}' status cannot be cancelled.`})]})}function Detail(props){return props.value?jsxs16(Stack7,{gap:0,children:[jsx23(Text8,{size:"xs",c:"dimmed",children:props.label}),jsx23(Text8,{size:"sm",children:props.value})]}):null}function getPatientParticipant(appointment){return appointment.participant.find(participant=>participant.actor?.reference?.startsWith("Patient/"))}function getOtherActors(appointment){let patient=getPatientParticipant(appointment);return appointment.participant.filter(participant=>participant!==patient).map(participant=>participant.actor).filter(isDefined7)}function formatWhen(appointment){if(!appointment.start)return;let start=new Date(appointment.start),times=[formatZonedTime(start),appointment.end&&formatZonedTime(new Date(appointment.end))].filter(Boolean).join(" \u2013 ");return`${formatDayHeading(start)} \xB7 ${times}`}function formatService(appointment){return(appointment.serviceType??[]).map(formatCodeableConcept2).filter(Boolean).join(", ")||formatCodeableConcept2(appointment.appointmentType)||void 0}import{Divider as Divider3,Stack as Stack8,Text as Text11}from"@mantine/core";import{Fragment as Fragment14}from"react";import{Avatar,Group as Group7,Text as Text9,ThemeIcon,UnstyledButton}from"@mantine/core";var CalendarRow_default={row:"CalendarRow_row",eyeSlot:"CalendarRow_eyeSlot",eyeOff:"CalendarRow_eyeOff",eyeHint:"CalendarRow_eyeHint"};import{jsx as jsx24,jsxs as jsxs17}from"react/jsx-runtime";function CalendarRow(props){let{item,icon,onToggle}=props,selected=item.selected??!0,interactive=!!onToggle,color=selected?props.color:"gray";return jsx24(UnstyledButton,{className:CalendarRow_default.row,onClick:interactive?()=>onToggle(item.id):void 0,"aria-pressed":interactive?selected:void 0,"data-selected":selected||void 0,"data-interactive":interactive||void 0,component:interactive?"button":"div",children:jsxs17(Group7,{gap:"sm",wrap:"nowrap",children:[icon?jsx24(ThemeIcon,{variant:"filled",color,radius:"sm",size:20,className:CalendarRow_default.icon,children:icon}):jsx24(Avatar,{src:item.imageUrl,name:item.label,color,radius:"xl",size:28}),jsx24(Text9,{truncate:!0,c:selected?void 0:"dimmed",children:item.label}),jsx24("div",{className:CalendarRow_default.eyeSlot,children:selected?interactive&&jsx24(IconEye,{size:16,"aria-hidden":"true",className:CalendarRow_default.eyeHint}):jsx24(IconEyeOff,{size:16,"aria-hidden":"true",className:CalendarRow_default.eyeOff})})]})})}import{ActionIcon as ActionIcon3,Box as Box3,Collapse,Group as Group8,Loader as Loader3,Text as Text10}from"@mantine/core";import{useState as useState10}from"react";var SectionHeader_default={chevron:"SectionHeader_chevron",title:"SectionHeader_title"};import{jsx as jsx25,jsxs as jsxs18}from"react/jsx-runtime";function SectionHeader(props){let{title,children,loading}=props,[collapsed,setCollapsed]=useState10(!1);return jsxs18(Box3,{children:[jsxs18(Group8,{gap:8,wrap:"nowrap",children:[jsx25(ActionIcon3,{variant:"subtle",color:"gray",radius:"xl",onClick:()=>setCollapsed(c=>!c),"aria-label":collapsed?`Show ${title.toLowerCase()}`:`Hide ${title.toLowerCase()}`,className:SectionHeader_default.chevron,"data-collapsed":collapsed||void 0,size:"md",children:jsx25(IconChevronDown,{size:20})}),jsx25(Text10,{fz:"md",fw:800,onClick:()=>setCollapsed(c=>!c),className:SectionHeader_default.title,children:title}),loading&&jsx25(Loader3,{size:"xs","aria-label":`Loading ${title.toLowerCase()}`})]}),jsx25(Collapse,{in:!collapsed,my:"xs",children})]})}import{jsx as jsx26,jsxs as jsxs19}from"react/jsx-runtime";var SECTIONS=[{actorType:"Practitioner",title:"Providers & Staff",emptyLabel:"providers or staff"},{actorType:"Device",title:"Devices",emptyLabel:"devices"},{actorType:"Location",title:"Rooms",emptyLabel:"rooms",icon:jsx26(IconMapPinFilled,{size:12})}];function CalendarsPanel(props){let{items,candidatesLoading,onToggle,className}=props;return jsxs19(Stack8,{gap:"xs",className,children:[jsx26(Text11,{fz:"lg",fw:800,py:"xs",children:"Calendars"}),jsx26(Divider3,{}),SECTIONS.map(section=>{let sectionItems=items[section.actorType];return jsxs19(Fragment14,{children:[jsx26(SectionHeader,{title:section.title,loading:candidatesLoading,children:sectionItems.length===0&&!candidatesLoading?jsxs19(Text11,{fz:"sm",c:"dimmed",p:"xs",children:["No ",section.emptyLabel," found"]}):jsx26(Stack8,{gap:2,children:sectionItems.map(item=>jsx26(CalendarRow,{item,color:item.color,onToggle:onToggle&&(id=>onToggle(section.actorType,id)),icon:section.icon},item.id))})}),jsx26(Divider3,{})]},section.actorType)})]})}import{Group as Group9,Text as Text12}from"@mantine/core";import{jsx as jsx27,jsxs as jsxs20}from"react/jsx-runtime";function CalendarTimezoneNotice(props){let{timezones,anyUnknown,viewerTimezone,className}=props;if(!timezones.some(timezone=>!isViewerTimezone(timezone,viewerTimezone))&&!anyUnknown)return null;let viewerLabel=formatTimezoneLabel(viewerTimezone);return jsxs20(Group9,{gap:6,wrap:"nowrap",align:"center",className,"data-testid":"calendar-timezone-notice",children:[jsx27(IconInfoCircle,{size:14,stroke:1.8,color:"var(--mantine-color-dimmed)"}),jsxs20(Text12,{size:"xs",c:"dimmed",children:["Calendar shown in your local time (",viewerLabel,")."]})]})}var SchedulingWorkspace_default={root:"SchedulingWorkspace_root",sidebar:"SchedulingWorkspace_sidebar",calendar:"SchedulingWorkspace_calendar",multiCalendar:"SchedulingWorkspace_multiCalendar",timezoneNotice:"SchedulingWorkspace_timezoneNotice",bookingPane:"SchedulingWorkspace_bookingPane",bookingPaneWide:"SchedulingWorkspace_bookingPaneWide",alert:"SchedulingWorkspace_alert"};import{getExtensionValue as getExtensionValue2,TimezoneExtensionURI}from"@medplum/core";function getCalendarTimezones(candidates){let timezones=[],anyUnknown=!1;for(let candidate of candidates){if(!candidate.actorResource){anyUnknown=!0;continue}let timezone=getExtensionValue2(candidate.actorResource,TimezoneExtensionURI);typeof timezone=="string"&&timezones.push(timezone)}return{timezones,anyUnknown}}import{jsx as jsx28,jsxs as jsxs21}from"react/jsx-runtime";var NO_CANDIDATES={Practitioner:[],Location:[],Device:[]},NONE_DESELECTED={Practitioner:new Set,Location:new Set,Device:new Set};function SchedulingWorkspace(props){let{procedureBinding,diagnosisBinding,onBooked,appointmentCancellationReasonValueSet}=props,medplum=useMedplum7(),theme=useMantineTheme2(),[schedulesLoadingError,setSchedulesLoadingError]=useState11(),[candidatesByActorType,setCandidatesByActorType]=useState11(NO_CANDIDATES),[candidatesLoading,setCandidatesLoading]=useState11(!1),[deselectedIds,setDeselectedIds]=useState11(NONE_DESELECTED),[range,setRange]=useState11(),[bookingSelection,setBookingSelection]=useState11(),[selectedAppointmentId,setSelectedAppointmentId]=useState11(),[highlight,setHighlight]=useState11(),[timeFinderOpen,setTimeFinderOpen]=useState11(!1);useEffect7(()=>{let controller=new AbortController;return setCandidatesLoading(!0),Promise.all(BOOKABLE_ACTOR_TYPES.map(async actorType=>{let candidates=await searchScheduleCandidates(medplum,void 0,{actorType,query:"",signal:controller.signal,count:100});return[actorType,candidates]})).then(results=>{controller.signal.aborted||(setSchedulesLoadingError(void 0),setCandidatesByActorType(Object.fromEntries(results)))}).catch(err=>{controller.signal.aborted||setSchedulesLoadingError(err)}).finally(()=>{controller.signal.aborted||setCandidatesLoading(!1)}),()=>controller.abort()},[medplum]);let colorByScheduleId=useMemo6(()=>{let all=BOOKABLE_ACTOR_TYPES.flatMap(actorType=>candidatesByActorType[actorType]),map=new Map;return all.forEach((candidate,i)=>{let extensionColor=getExtensionValue3(candidate.schedule,SchedulingScheduleColorURI2);map.set(candidate.schedule.id,resolveThemeColor(theme,extensionColor,i))}),map},[candidatesByActorType,theme]),activeCandidates=useMemo6(()=>BOOKABLE_ACTOR_TYPES.flatMap(actorType=>candidatesByActorType[actorType].filter(c=>!deselectedIds[actorType].has(c.schedule.id))),[candidatesByActorType,deselectedIds]),schedules=useMemo6(()=>activeCandidates.map(c=>c.schedule),[activeCandidates]),{slots,appointments,loading:resourcesLoading,error:resourcesError}=useSchedulingResources(schedules,range),sources=useMemo6(()=>activeCandidates.map(candidate=>{let scheduleReference=getReferenceString11(candidate.schedule),actorReferences=new Set(candidate.schedule.actor.map(actor=>actor.reference).filter(isDefined8));return{schedule:candidate.schedule,color:colorByScheduleId.get(candidate.schedule.id),slots:(slots??[]).filter(slot=>slot.schedule?.reference===scheduleReference),appointments:(appointments??[]).filter(appointment=>(appointment.participant??[]).some(participant=>participant.actor?.reference&&actorReferences.has(participant.actor.reference)))}}),[activeCandidates,slots,appointments,colorByScheduleId]),{timezones,anyUnknown}=useMemo6(()=>getCalendarTimezones(activeCandidates),[activeCandidates]),startBooking=useCallback11(interval=>{setBookingSelection(interval),setHighlight(interval)},[]),closeBooking=useCallback11(()=>{setBookingSelection(void 0),setHighlight(void 0),setTimeFinderOpen(!1)},[]),toggleCandidate=useCallback11((actorType,id)=>{setDeselectedIds(prev=>({...prev,[actorType]:toggleId(prev[actorType],id)}))},[]),finishBooking=useCallback11(booking=>(closeBooking(),onBooked?.(booking)),[closeBooking,onBooked]),selectAppointment=useCallback11(appointment=>{appointment.id&&setSelectedAppointmentId(appointment.id)},[]),closeAppointment=useCallback11(()=>setSelectedAppointmentId(void 0),[]),openAppointment=useMemo6(()=>{if(selectedAppointmentId)return(appointments??[]).find(a=>a.id===selectedAppointmentId)},[appointments,selectedAppointmentId]),toItem=(candidate,selected)=>{let color=colorByScheduleId.get(candidate.schedule.id);if(!color)throw new Error("Got candidate without resolved color");return{id:candidate.schedule.id,label:getCandidateDisplay(candidate),color,selected}},panelItems=Object.fromEntries(BOOKABLE_ACTOR_TYPES.map(actorType=>[actorType,candidatesByActorType[actorType].map(c=>toItem(c,!deselectedIds[actorType].has(c.schedule.id)))])),displayError=resourcesError??schedulesLoadingError;return jsxs21("div",{className:`${SchedulingWorkspace_default.root} ${props.className??""}`,children:[jsx28("div",{className:SchedulingWorkspace_default.sidebar,children:jsx28(CalendarsPanel,{items:panelItems,candidatesLoading,onToggle:toggleCandidate})}),jsxs21("div",{className:SchedulingWorkspace_default.calendar,children:[displayError!==void 0&&jsx28(Alert3,{color:"red",mb:"xs",children:normalizeErrorString4(displayError)}),jsx28(MultiCalendar,{className:SchedulingWorkspace_default.multiCalendar,sources,onRangeChange:setRange,loading:resourcesLoading,onSelectInterval:startBooking,onSelectAppointment:selectAppointment,selection:highlight}),jsx28(CalendarTimezoneNotice,{className:SchedulingWorkspace_default.timezoneNotice,timezones,anyUnknown})]}),jsx28(Drawer,{opened:openAppointment!==void 0,onClose:closeAppointment,position:"right",title:"Appointment details",closeButtonProps:{"aria-label":"Close appointment details"},children:openAppointment&&jsx28(AppointmentDetails,{appointment:openAppointment,cancellationReasonValueSet:appointmentCancellationReasonValueSet,onCancelled:props.onCancelled})}),bookingSelection&&jsxs21("div",{className:clsx_default(SchedulingWorkspace_default.bookingPane,{[SchedulingWorkspace_default.bookingPaneWide]:timeFinderOpen}),children:[jsxs21(Group10,{justify:"space-between",wrap:"nowrap",mb:"sm",children:[jsx28(Title3,{order:4,children:"Book appointment"}),jsx28(CloseButton,{"aria-label":"Close booking form",onClick:closeBooking})]}),jsx28(AppointmentBookingForm,{defaultStart:bookingSelection.start,procedureBinding,diagnosisBinding,onToggleTimeFinder:setTimeFinderOpen,onChangeTime:setHighlight,onBooked:finishBooking},bookingSelection.start.toDateString())]})]})}function toggleId(ids,id){let next=new Set(ids);return next.has(id)?next.delete(id):next.add(id),next}export{AppointmentActorSelect,AppointmentActorSelections,AppointmentBookingForm,AppointmentDayTimes,AppointmentOptionRow,AppointmentProposalForm,AppointmentServiceSelect,AppointmentSlotGroupCard,BOOKABLE_ACTOR_TYPES,Calendar2 as Calendar,DEFAULT_DIAGNOSIS_VALUE_SET,DEFAULT_PROCEDURE_VALUE_SET,EMPTY_REQUIREMENT_VALUES,MAX_ACTOR_COMBINATIONS,MAX_FIND_WINDOW_DAYS,MultiCalendar,REQUIRED_ACTOR_TYPES,ScheduleAvailabilityEditor,SchedulingWorkspace,addDays,countActorCombinations,createActorRequirement,endOfDay,endOfMonth,enumerateDateRange,filterByTimeOfDay,filterCandidatesByLocation,formatDayHeading,formatTimezoneLabel,formatZonedTime,getActorCombinations,getActorGroupKey,getActorType,getActorTypeLabel,getActorsKey,getAppointmentActors,getAppointmentKey,getBrowserTimezone,getCandidateActor,getCandidateDisplay,getDayCount,getDurationMinutes,getEffectiveAvailability,getFindWindowError,getNativeInputType,getRequirements,getSelectedActorResources,getSelectedCandidates,getSelectionError,getUnsatisfiableRows,getZonedDayRange,groupAppointmentsByDay,hasRequiredValues,isActorTypeRequired,isBookableActorType,isRequirementAnswered,isViewerTimezone,parseDayKey,parseZonedTime,searchScheduleCandidates,setScheduleAvailability,startOfDay,toCodings,useProposedAppointments,useSchedulingAppointments,useSchedulingResources,useSchedulingSlots};
|
|
3
3
|
/*! Bundled license information:
|
|
4
4
|
|
|
5
5
|
@tabler/icons-react/dist/esm/defaultAttributes.mjs:
|
|
6
6
|
@tabler/icons-react/dist/esm/createReactComponent.mjs:
|
|
7
|
+
@tabler/icons-react/dist/esm/icons/IconAlertCircle.mjs:
|
|
7
8
|
@tabler/icons-react/dist/esm/icons/IconCalendarSearch.mjs:
|
|
8
9
|
@tabler/icons-react/dist/esm/icons/IconCheck.mjs:
|
|
9
10
|
@tabler/icons-react/dist/esm/icons/IconChevronDown.mjs:
|
|
@@ -14,6 +15,7 @@ import{getReferenceString as getReferenceString3}from"@medplum/core";import{Asyn
|
|
|
14
15
|
@tabler/icons-react/dist/esm/icons/IconInfoCircle.mjs:
|
|
15
16
|
@tabler/icons-react/dist/esm/icons/IconMinus.mjs:
|
|
16
17
|
@tabler/icons-react/dist/esm/icons/IconPlus.mjs:
|
|
18
|
+
@tabler/icons-react/dist/esm/icons/IconX.mjs:
|
|
17
19
|
@tabler/icons-react/dist/esm/icons/IconMapPinFilled.mjs:
|
|
18
20
|
@tabler/icons-react/dist/esm/tabler-icons-react.mjs:
|
|
19
21
|
(**
|