@ahrowe/ui 0.41.0 → 0.41.1
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-types/common/hooks/useOverlay.d.ts +4 -1
- package/dist/cjs-types/common/popover/popover.types.d.ts +1 -1
- package/dist/esm/common/ahroweProvider/ahroweProvider.mjs +1 -1
- package/dist/esm/common/ahroweProvider/ahroweProvider.mjs.map +1 -1
- package/dist/esm/common/calendar/calendar.mjs +1 -1
- package/dist/esm/common/calendar/calendar.mjs.map +1 -1
- package/dist/esm/common/hooks/useOverlay.mjs +1 -1
- package/dist/esm/common/hooks/useOverlay.mjs.map +1 -1
- package/dist/esm/common/modal/modal.mjs +1 -1
- package/dist/esm/common/modal/modal.mjs.map +1 -1
- package/dist/esm/common/otpInput/otpInput.mjs +1 -1
- package/dist/esm/common/otpInput/otpInput.mjs.map +1 -1
- package/dist/esm/common/popover/popover.mjs +1 -1
- package/dist/esm/common/popover/popover.mjs.map +1 -1
- package/dist/esm/common/popover/popover.types.mjs.map +1 -1
- package/dist/esm/common/timer/timer.mjs +1 -1
- package/dist/esm/common/timer/timer.mjs.map +1 -1
- package/dist/esm/common/virtualList/virtualList.mjs +1 -1
- package/dist/esm/common/virtualList/virtualList.mjs.map +1 -1
- package/dist/index.cjs +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/types/common/hooks/useOverlay.d.ts +4 -1
- package/dist/types/common/popover/popover.types.d.ts +1 -1
- package/docs/Modal.md +1 -1
- package/docs/Popover.md +2 -2
- package/package.json +1 -1
|
@@ -6,7 +6,10 @@ export interface UseOverlayArgs {
|
|
|
6
6
|
containerRef: RefObject<HTMLElement | null>;
|
|
7
7
|
/** Called when Escape is pressed while this is the topmost overlay. Omit to not handle Escape. */
|
|
8
8
|
onEscape?: () => void;
|
|
9
|
-
/**
|
|
9
|
+
/**
|
|
10
|
+
* Keep Tab inside the panel and restore focus to the previously focused element on close, unless
|
|
11
|
+
* an overlay opened after this one is still open.
|
|
12
|
+
*/
|
|
10
13
|
trapFocus?: boolean;
|
|
11
14
|
/** Prevent the page behind the overlay from scrolling. */
|
|
12
15
|
lockScroll?: boolean;
|
|
@@ -53,7 +53,7 @@ export interface PopoverProps extends Omit<HtmlProps, 'content'> {
|
|
|
53
53
|
offset?: number;
|
|
54
54
|
/** Render the arrow pointing at the trigger (default `true`). */
|
|
55
55
|
withArrow?: boolean;
|
|
56
|
-
/** Close
|
|
56
|
+
/** Close on a click outside, or when focus leaves the trigger and panel (default `true`). */
|
|
57
57
|
closeOnOutsideClick?: boolean;
|
|
58
58
|
/** Close when pressing Escape (default `true`). */
|
|
59
59
|
closeOnEscape?: boolean;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";import e from"../configProvider/configProvider.mjs";import t from"../scrollbarProvider/index.mjs";import n from"../themeProvider/themeProvider.mjs";import{PortalHostContext as r}from"../bodyEnd/portalHostContext.mjs";import i from"../toast/toastHost.mjs";import{useCallback as a,useContext as o,useEffect as s,useLayoutEffect as c,useState as l,useSyncExternalStore as u}from"react";import{jsx as d,jsxs as f}from"react/jsx-runtime";var p=()=>()=>{};function m({children:m,themes:h,currentThemeId:g,defaultProps:_,presentation:v,toast:y,scrollbars:b}){let x=o(r)!==void 0,S=u(p,()=>!0,()=>!1),[C]=l(()=>typeof document>`u`?null:document.createElement(`div`)),w=a(e=>{let t=e?.parentElement?.lastElementChild;
|
|
1
|
+
"use client";import e from"../configProvider/configProvider.mjs";import t from"../scrollbarProvider/index.mjs";import n from"../themeProvider/themeProvider.mjs";import{PortalHostContext as r}from"../bodyEnd/portalHostContext.mjs";import i from"../toast/toastHost.mjs";import{useCallback as a,useContext as o,useEffect as s,useLayoutEffect as c,useState as l,useSyncExternalStore as u}from"react";import{jsx as d,jsxs as f}from"react/jsx-runtime";var p=()=>()=>{};function m({children:m,themes:h,currentThemeId:g,defaultProps:_,presentation:v,toast:y,scrollbars:b}){let x=o(r)!==void 0,S=u(p,()=>!0,()=>!1),[C]=l(()=>typeof document>`u`?null:document.createElement(`div`)),w=a(e=>{let t=e?.parentElement?.lastElementChild;t&&C&&C.parentNode!==t&&t.appendChild(C)},[C]),T=!x&&b!==!1;c(()=>{if(!T||!C)return;let e=getComputedStyle(C).getPropertyValue(`--background-accent-light`).trim(),t=document.documentElement.style;return t.setProperty(`--ahrowe-page-scrollbar-thumb`,e),()=>{t.removeProperty(`--ahrowe-page-scrollbar-thumb`)}},[T,C,h,g]);let E=x&&(y!==void 0||b!==void 0);s(()=>{E&&console.warn("[AhroweProvider] `toast` and `scrollbars` are read by the outermost AhroweProvider only. Set them there.")},[E]);let D=f(r.Provider,{value:S?C:null,children:[d(`template`,{ref:w}),d(i,{...y,children:m}),d(`div`,{})]});return d(e,{defaultProps:_,presentation:v,children:d(n,{themes:h,currentThemeId:g,children:x?m:b===!1?D:d(t,{children:D})})})}export{m as default};
|
|
2
2
|
//# sourceMappingURL=ahroweProvider.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ahroweProvider.mjs","names":[],"sources":["../../../../package/common/ahroweProvider/ahroweProvider.tsx"],"sourcesContent":["import {\n useCallback,\n useContext,\n useEffect,\n useLayoutEffect,\n useState,\n useSyncExternalStore,\n type ReactElement,\n} from 'react';\n\nimport ConfigProvider from 'components/common/configProvider';\nimport ScrollbarProvider from 'components/common/scrollbarProvider';\nimport ThemeProvider from 'components/common/themeProvider';\nimport ToastHost from '../toast/toastHost';\nimport { PortalHostContext } from '../bodyEnd/portalHostContext';\nimport type { AhroweProviderProps } from './ahroweProvider.types';\n\nconst subscribeToNothing = () => () => {};\n\nfunction AhroweProvider({\n children,\n themes,\n currentThemeId,\n defaultProps,\n presentation,\n toast,\n scrollbars,\n}: AhroweProviderProps): ReactElement {\n // A nested provider themes and configures its section only. A second toast list would stack\n // over the first in the same corner, and a second host would split the portals in two.\n const isNested = useContext(PortalHostContext) !== undefined;\n\n // The server renders no portal, so hydration must not either: `false` there, and `true` from\n // the first render of an app that is not hydrating.\n const canPortal = useSyncExternalStore(\n subscribeToNothing,\n () => true,\n () => false,\n );\n\n // Created up front instead of rendered: a rendered host exists only after the first commit, so\n // a modal open on the first render mounted a commit late and its initial focus found nothing.\n const [host] = useState(() => (typeof document === 'undefined' ? null : document.createElement('div')));\n\n // Attached from a marker before the app, because refs attach in tree order: this way the host is\n // in the page before any layout effect runs. The slot stays last, so panels paint above the app.\n const attachHost = useCallback(\n (marker: HTMLTemplateElement | null) => {\n const slot = marker?.parentElement?.lastElementChild;\n if (!slot || !host) return;\n slot
|
|
1
|
+
{"version":3,"file":"ahroweProvider.mjs","names":[],"sources":["../../../../package/common/ahroweProvider/ahroweProvider.tsx"],"sourcesContent":["import {\n useCallback,\n useContext,\n useEffect,\n useLayoutEffect,\n useState,\n useSyncExternalStore,\n type ReactElement,\n} from 'react';\n\nimport ConfigProvider from 'components/common/configProvider';\nimport ScrollbarProvider from 'components/common/scrollbarProvider';\nimport ThemeProvider from 'components/common/themeProvider';\nimport ToastHost from '../toast/toastHost';\nimport { PortalHostContext } from '../bodyEnd/portalHostContext';\nimport type { AhroweProviderProps } from './ahroweProvider.types';\n\nconst subscribeToNothing = () => () => {};\n\nfunction AhroweProvider({\n children,\n themes,\n currentThemeId,\n defaultProps,\n presentation,\n toast,\n scrollbars,\n}: AhroweProviderProps): ReactElement {\n // A nested provider themes and configures its section only. A second toast list would stack\n // over the first in the same corner, and a second host would split the portals in two.\n const isNested = useContext(PortalHostContext) !== undefined;\n\n // The server renders no portal, so hydration must not either: `false` there, and `true` from\n // the first render of an app that is not hydrating.\n const canPortal = useSyncExternalStore(\n subscribeToNothing,\n () => true,\n () => false,\n );\n\n // Created up front instead of rendered: a rendered host exists only after the first commit, so\n // a modal open on the first render mounted a commit late and its initial focus found nothing.\n const [host] = useState(() => (typeof document === 'undefined' ? null : document.createElement('div')));\n\n // Attached from a marker before the app, because refs attach in tree order: this way the host is\n // in the page before any layout effect runs. The slot stays last, so panels paint above the app.\n const attachHost = useCallback(\n (marker: HTMLTemplateElement | null) => {\n const slot = marker?.parentElement?.lastElementChild;\n if (!slot || !host) return;\n // No cleanup, and no move when already in place: the host leaves with its slot anyway, and\n // StrictMode's extra detach and reattach otherwise took a focused element in it along.\n if (host.parentNode !== slot) slot.appendChild(host);\n },\n [host],\n );\n\n // Read from the host rather than `themes`, for the resolved value, `var()` references included.\n const stylesPage = !isNested && scrollbars !== false;\n useLayoutEffect(() => {\n if (!stylesPage || !host) return;\n const thumb = getComputedStyle(host).getPropertyValue('--background-accent-light').trim();\n const page = document.documentElement.style;\n page.setProperty('--ahrowe-page-scrollbar-thumb', thumb);\n return () => {\n page.removeProperty('--ahrowe-page-scrollbar-thumb');\n };\n }, [stylesPage, host, themes, currentThemeId]);\n\n const ignoresRootProps = isNested && (toast !== undefined || scrollbars !== undefined);\n useEffect(() => {\n if (ignoresRootProps) {\n console.warn(\n '[AhroweProvider] `toast` and `scrollbars` are read by the outermost AhroweProvider only. Set them there.',\n );\n }\n }, [ignoresRootProps]);\n\n const root = (\n <PortalHostContext.Provider value={canPortal ? host : null}>\n <template ref={attachHost} />\n <ToastHost {...toast}>{children}</ToastHost>\n <div />\n </PortalHostContext.Provider>\n );\n\n return (\n <ConfigProvider defaultProps={defaultProps} presentation={presentation}>\n <ThemeProvider themes={themes} currentThemeId={currentThemeId}>\n {/* Around the portal slot too, so the scrollbars of the panels in it are styled as well. */}\n {isNested ? children : scrollbars === false ? root : <ScrollbarProvider>{root}</ScrollbarProvider>}\n </ThemeProvider>\n </ConfigProvider>\n );\n}\n\nexport default AhroweProvider;\n"],"mappings":"8bAiBA,IAAM,UAAiC,CAAC,EAExC,SAAS,EAAe,CACtB,WACA,SACA,iBACA,eACA,eACA,QACA,cACoC,CAGpC,IAAM,EAAW,EAAW,CAAiB,IAAM,IAAA,GAI7C,EAAY,EAChB,MACM,OACA,EACR,EAIM,CAAC,GAAQ,MAAgB,OAAO,SAAa,IAAc,KAAO,SAAS,cAAc,KAAK,CAAE,EAIhG,EAAa,EAChB,GAAuC,CACtC,IAAM,EAAO,GAAQ,eAAe,iBAC/B,GAAS,GAGV,EAAK,aAAe,GAAM,EAAK,YAAY,CAAI,CACrD,EACA,CAAC,CAAI,CACP,EAGM,EAAa,CAAC,GAAY,IAAe,GAC/C,MAAsB,CACpB,GAAI,CAAC,GAAc,CAAC,EAAM,OAC1B,IAAM,EAAQ,iBAAiB,CAAI,CAAC,CAAC,iBAAiB,2BAA2B,CAAC,CAAC,KAAK,EAClF,EAAO,SAAS,gBAAgB,MAEtC,OADA,EAAK,YAAY,gCAAiC,CAAK,MAC1C,CACX,EAAK,eAAe,+BAA+B,CACrD,CACF,EAAG,CAAC,EAAY,EAAM,EAAQ,CAAc,CAAC,EAE7C,IAAM,EAAmB,IAAa,IAAU,IAAA,IAAa,IAAe,IAAA,IAC5E,MAAgB,CACV,GACF,QAAQ,KACN,0GACF,CAEJ,EAAG,CAAC,CAAgB,CAAC,EAErB,IAAM,EACJ,EAAC,EAAkB,SAAnB,CAA4B,MAAO,EAAY,EAAO,KAAtD,SAAA,CACE,EAAC,WAAD,CAAU,IAAK,CAAa,CAAA,EAC5B,EAAC,EAAD,CAAW,GAAI,EAAQ,UAAoB,CAAA,EAC3C,EAAC,MAAD,CAAM,CAAA,CACoB,IAG9B,OACE,EAAC,EAAD,CAA8B,eAA4B,eACxD,SAAA,EAAC,EAAD,CAAuB,SAAwB,iBAE5C,SAAA,EAAW,EAAW,IAAe,GAAQ,EAAO,EAAC,EAAD,CAAA,SAAoB,CAAwB,CAAA,CACpF,CAAA,CACD,CAAA,CAEpB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";import{useComponentDefaults as e}from"../configProvider/useComponentDefaults.mjs";import{useLabels as t}from"../configProvider/useLabels.mjs";import{mergeRefs as n}from"../utils/mergeRefs.mjs";import{asDay as r,dateToDay as i,dayToDate as a}from"../utils/day.mjs";import{CalendarView as o}from"./calendar.types.mjs";import{addDays as
|
|
1
|
+
"use client";import{useComponentDefaults as e}from"../configProvider/useComponentDefaults.mjs";import{useLabels as t}from"../configProvider/useLabels.mjs";import{mergeRefs as n}from"../utils/mergeRefs.mjs";import{asDay as r,dateToDay as i,dayToDate as a}from"../utils/day.mjs";import{CalendarView as o}from"./calendar.types.mjs";import{addDays as ee,dayDiff as s,hiddenDaySet as te,periodRange as ne,rangeWithNeighbours as re,shownDay as ie,shownDays as c,startOfDay as l,stepDate as u}from"./dates.mjs";import{formatPeriodTitle as d,localeWeekStart as ae}from"./format.mjs";import oe from"./components/agendaList/agendaList.mjs";import se from"./components/calendarHeader/calendarHeader.mjs";import ce from"./components/compactMonth/compactMonth.mjs";import le from"./components/monthView/monthView.mjs";import ue from"./components/timeGrid/timeGrid.mjs";import de from"./calendar.module.mjs";import{useEffect as f,useLayoutEffect as p,useRef as m,useState as h}from"react";import fe from"classnames";import{jsx as g,jsxs as pe}from"react/jsx-runtime";var me=[o.Month,o.Week,o.Day,o.Agenda],he=600,ge={previous:`Previous`,next:`Next`,today:`Today`,viewSwitcher:`Calendar view`,month:`Month`,week:`Week`,day:`Day`,agenda:`Agenda`,allDay:`All day`,more:e=>`+${e} more`,eventCount:e=>e===1?`1 event`:`${e} events`,noEvents:`No events`,newEvent:`New event`};function _(_){let{events:v,date:y,defaultDate:_e,onDateChange:ve,view:b,defaultView:ye=o.Month,onViewChange:be,views:x=me,locale:S,weekStartsOn:xe,slotMinutes:Se=15,hiddenDays:Ce,scrollToHour:we,onRangeChange:C,onEventClick:w,onEventChange:T,onSlotCreate:E,renderEvent:D,labels:O,ref:k,className:A,style:Te,classNames:j,styles:M,...Ee}=e(`Calendar`,_),N=t(`Calendar`,O,ge),P=xe??ae(S),F=te(Ce),I=m(null),De=m(null),[L,Oe]=h(0),[ke,Ae]=h(1),[je,Me]=h(()=>{let e=r(_e);return e?a(e):l(new Date)}),R=r(y),z=ie(R?a(R):je,F),[Ne,Pe]=h(ye),B=b??Ne;p(()=>{let e=I.current;if(!e)return;let t=()=>Oe(e.getBoundingClientRect().width);t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let V=L>0&&L<he,H=re(B,z,P,F),U=`${i(H.start)}/${i(H.end)}`,W=m({range:H,onRangeChange:C}),G=m(null);p(()=>{W.current={range:H,onRangeChange:C}}),f(()=>{G.current!==U&&(G.current=U,W.current.onRangeChange?.(W.current.range))},[U]);function K(e){let t=l(e);i(t)!==i(z)&&(Ae(t>z?1:-1),y===void 0&&Me(t),ve?.(i(t)))}function q(e){e!==B&&(b===void 0&&Pe(e),be?.(e))}let[J,Y]=h(()=>new Map);function Fe(e){let t=T?.(e);if(typeof t?.then!=`function`)return;let n=String(e.event.id),r={start:e.start,end:e.end};Y(e=>new Map(e).set(n,r));let i=()=>Y(e=>{if(e.get(n)!==r)return e;let t=new Map(e);return t.delete(n),t});t.then(i,i)}let X=J.size===0?v:v.map(e=>{let t=J.get(String(e.id));return t?{...e,...t}:e}),Z={events:X,date:z,view:B,locale:S,weekStartsOn:P,slotMinutes:Se,hidden:F,scrollToHour:we,text:N,onDateChange:K,onOpenDay:x.includes(o.Day)?e=>{K(e),q(o.Day)}:void 0,onEventClick:w,onEventChange:T&&Fe,onSlotCreate:E,renderEvent:D,classNames:j,slotStyles:M},Q=ne(B,z,P),$=c(Q.start,s(Q.start,Q.end),F),Ie={start:$[0],end:ee($[$.length-1],1)};function Le(){switch(B){case o.Week:case o.Day:return g(ue,{...Z,zoomRef:De});case o.Agenda:return g(oe,{events:X,start:Q.start,days:s(Q.start,Q.end),hidden:F,scrollTo:z,showDayHeaders:!0,locale:S,text:N,onEventClick:w,renderEvent:D,classNames:j,slotStyles:M});default:return g(V?ce:le,{...Z})}}return pe(`div`,{...Ee,ref:n(I,k),className:fe(de.calendar,A,j?.root),style:{...Te,...M?.root},children:[g(se,{className:j?.header,style:M?.header,compact:V,title:d(B,z,Ie,S),direction:ke,view:B,views:x,text:N,onStep:e=>K(u(B,z,e,F)),onToday:()=>K(new Date),onViewChange:q}),Le()]})}export{_ as default};
|
|
2
2
|
//# sourceMappingURL=calendar.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"calendar.mjs","names":[],"sources":["../../../../package/common/calendar/calendar.tsx"],"sourcesContent":["import { useEffect, useLayoutEffect, useRef, useState, type ReactElement } from 'react';\nimport cx from 'classnames';\n\nimport { useComponentDefaults, useLabels } from '../configProvider';\nimport { mergeRefs } from '../utils/mergeRefs';\nimport { asDay, dayToDate } from '../utils/day';\nimport {\n CalendarView,\n type CalendarEvent,\n type CalendarEventChange,\n type CalendarLabels,\n type CalendarProps,\n} from './calendar.types';\nimport {\n dayDiff,\n dateToDay,\n addDays,\n hiddenDaySet,\n periodRange,\n rangeWithNeighbours,\n shownDay,\n shownDays,\n startOfDay,\n stepDate,\n} from './dates';\nimport { formatPeriodTitle, localeWeekStart } from './format';\nimport AgendaList from './components/agendaList';\nimport CalendarHeader from './components/calendarHeader';\nimport CompactMonth from './components/compactMonth';\nimport MonthView from './components/monthView';\nimport TimeGrid from './components/timeGrid';\nimport type { TimeGridZoom } from './components/timeGrid/timeGrid.types';\nimport type { CalendarViewProps } from './view.types';\n\nimport styles from './calendar.module.pcss';\n\nconst ALL_VIEWS = [CalendarView.Month, CalendarView.Week, CalendarView.Day, CalendarView.Agenda];\n\n/** Below this width the month view folds into the compact month with a day list. */\nconst COMPACT_WIDTH = 600;\n\nconst DEFAULT_LABELS: Required<CalendarLabels> = {\n previous: 'Previous',\n next: 'Next',\n today: 'Today',\n viewSwitcher: 'Calendar view',\n month: 'Month',\n week: 'Week',\n day: 'Day',\n agenda: 'Agenda',\n allDay: 'All day',\n more: (count) => `+${count} more`,\n eventCount: (count) => (count === 1 ? '1 event' : `${count} events`),\n noEvents: 'No events',\n newEvent: 'New event',\n};\n\nfunction Calendar<E extends CalendarEvent = CalendarEvent>(props: CalendarProps<E>): ReactElement {\n const {\n events,\n date: controlledDate,\n defaultDate,\n onDateChange,\n view: controlledView,\n defaultView = CalendarView.Month,\n onViewChange,\n views = ALL_VIEWS,\n locale,\n weekStartsOn: weekStartsOnProp,\n slotMinutes = 15,\n hiddenDays,\n scrollToHour,\n onRangeChange,\n onEventClick,\n onEventChange,\n onSlotCreate,\n renderEvent,\n labels,\n ref,\n className,\n style,\n classNames,\n styles: slotStyles,\n ...rest\n } = useComponentDefaults('Calendar', props);\n const text = useLabels('Calendar', labels, DEFAULT_LABELS);\n const weekStartsOn = weekStartsOnProp ?? localeWeekStart(locale);\n const hidden = hiddenDaySet(hiddenDays);\n\n const rootRef = useRef<HTMLDivElement>(null);\n const zoomRef = useRef<TimeGridZoom | null>(null);\n const [width, setWidth] = useState(0);\n const [direction, setDirection] = useState<1 | -1>(1);\n\n // `date` is a day, the same wherever the calendar is opened, and read as its first local moment.\n const [internalDate, setInternalDate] = useState(() => {\n const initial = asDay(defaultDate);\n return initial ? dayToDate(initial) : startOfDay(new Date());\n });\n const controlledDay = asDay(controlledDate);\n // Only ever a day the views show. The selection itself is left alone: a hidden day in `date` is\n // the parent's, and stepping on from it lands where the parent would expect.\n const date = shownDay(controlledDay ? dayToDate(controlledDay) : internalDate, hidden);\n const [internalView, setInternalView] = useState(defaultView);\n const view = controlledView ?? internalView;\n\n // The layout switch follows the calendar's own width rather than the viewport's, so it also\n // happens in a sidebar on a wide screen. Width 0 means no layout (server, jsdom): stay wide.\n useLayoutEffect(() => {\n const root = rootRef.current;\n if (!root) return;\n // The border box, both times: an observer's `contentRect` leaves the border out, and 600px\n // wide would then read as 598.\n const measure = () => setWidth(root.getBoundingClientRect().width);\n measure();\n const observer = new ResizeObserver(measure);\n observer.observe(root);\n return () => observer.disconnect();\n }, []);\n const compact = width > 0 && width < COMPACT_WIDTH;\n\n // Reported per range, not per render: `date` is a new object on every render of a controlled\n // parent. Not `useEffectEvent` for the latest callback, which React only has from 19.2.\n const range = rangeWithNeighbours(view, date, weekStartsOn, hidden);\n const rangeKey = `${dateToDay(range.start)}/${dateToDay(range.end)}`;\n const latest = useRef({ range, onRangeChange });\n useLayoutEffect(() => {\n latest.current = { range, onRangeChange };\n });\n useEffect(() => {\n latest.current.onRangeChange?.(latest.current.range);\n }, [rangeKey]);\n\n function changeDate(next: Date) {\n const day = startOfDay(next);\n if (dateToDay(day) === dateToDay(date)) return;\n setDirection(day > date ? 1 : -1);\n if (controlledDate === undefined) setInternalDate(day);\n onDateChange?.(dateToDay(day));\n }\n\n function changeView(next: CalendarView) {\n if (next === view) return;\n if (controlledView === undefined) setInternalView(next);\n onViewChange?.(next);\n }\n\n // Moves whose promise has not settled yet, drawn where they were dropped meanwhile.\n const [pending, setPending] = useState<ReadonlyMap<string, { start: Date; end: Date }>>(() => new Map());\n function changeEvent(change: CalendarEventChange<E>) {\n const result = onEventChange?.(change);\n if (typeof (result as Promise<unknown> | undefined)?.then !== 'function') return;\n const key = String(change.event.id);\n const entry = { start: change.start, end: change.end };\n setPending((current) => new Map(current).set(key, entry));\n // A later move of the same event owns the entry by then, and keeps it.\n const settle = () =>\n setPending((current) => {\n if (current.get(key) !== entry) return current;\n const next = new Map(current);\n next.delete(key);\n return next;\n });\n (result as Promise<unknown>).then(settle, settle);\n }\n const shownEvents =\n pending.size === 0\n ? events\n : events.map((event) => {\n const moved = pending.get(String(event.id));\n return moved ? { ...event, ...moved } : event;\n });\n\n const viewProps: CalendarViewProps<E> = {\n events: shownEvents,\n date,\n view,\n locale,\n weekStartsOn,\n slotMinutes,\n hidden,\n scrollToHour,\n text,\n onDateChange: changeDate,\n onOpenDay: views.includes(CalendarView.Day)\n ? (day) => {\n changeDate(day);\n changeView(CalendarView.Day);\n }\n : undefined,\n onEventClick,\n onEventChange: onEventChange && changeEvent,\n onSlotCreate,\n renderEvent,\n classNames,\n slotStyles,\n };\n\n // The week's title names the days it shows, not the ones it hides at either end.\n const period = periodRange(view, date, weekStartsOn);\n const columns = shownDays(period.start, dayDiff(period.start, period.end), hidden);\n const titleRange = { start: columns[0], end: addDays(columns[columns.length - 1], 1) };\n\n function renderView() {\n switch (view) {\n case CalendarView.Week:\n case CalendarView.Day:\n return <TimeGrid {...viewProps} zoomRef={zoomRef} />;\n case CalendarView.Agenda: {\n return (\n <AgendaList\n events={shownEvents}\n start={period.start}\n days={dayDiff(period.start, period.end)}\n hidden={hidden}\n scrollTo={date}\n showDayHeaders\n locale={locale}\n text={text}\n onEventClick={onEventClick}\n renderEvent={renderEvent}\n classNames={classNames}\n slotStyles={slotStyles}\n />\n );\n }\n default:\n return compact ? <CompactMonth {...viewProps} /> : <MonthView {...viewProps} />;\n }\n }\n\n return (\n <div\n {...rest}\n ref={mergeRefs(rootRef, ref)}\n className={cx(styles.calendar, className, classNames?.root)}\n style={{ ...style, ...slotStyles?.root }}\n >\n <CalendarHeader\n className={classNames?.header}\n style={slotStyles?.header}\n compact={compact}\n title={formatPeriodTitle(view, date, titleRange, locale)}\n direction={direction}\n view={view}\n views={views}\n text={text}\n onStep={(step) => changeDate(stepDate(view, date, step, hidden))}\n onToday={() => changeDate(new Date())}\n onViewChange={changeView}\n />\n {renderView()}\n </div>\n );\n}\n\nexport default Calendar;\n"],"mappings":"8hCAoCA,IAAM,GAAY,CAAC,EAAa,MAAO,EAAa,KAAM,EAAa,IAAK,EAAa,MAAM,EAGzF,GAAgB,IAEhB,EAA2C,CAC/C,SAAU,WACV,KAAM,OACN,MAAO,QACP,aAAc,gBACd,MAAO,QACP,KAAM,OACN,IAAK,MACL,OAAQ,SACR,OAAQ,UACR,KAAO,GAAU,IAAI,EAAM,OAC3B,WAAa,GAAW,IAAU,EAAI,UAAY,GAAG,EAAM,SAC3D,SAAU,YACV,SAAU,WACZ,EAEA,SAAS,EAAkD,EAAuC,CAChG,GAAM,CACJ,SACA,KAAM,EACN,eACA,gBACA,KAAM,EACN,eAAc,EAAa,MAC3B,gBACA,QAAQ,GACR,SACA,aAAc,GACd,eAAc,GACd,aACA,eACA,gBACA,eACA,gBACA,eACA,cACA,SACA,MACA,aACA,SACA,aACA,OAAQ,EACR,GAAG,GACD,EAAqB,WAAY,CAA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AAK,EAAQ,EAAQ,EAAQ,OAAS,GAAI,CAAC,CAAE,EAErF,SAAS,IAAa,CACpB,OAAQ,EAAR,CACE,KAAK,EAAa,KAClB,KAAK,EAAa,IAChB,OAAO,EAAC,GAAD,CAAU,GAAI,EAAoB,UAAU,CAAA,EACrD,KAAK,EAAa,OAChB,OACE,EAAC,GAAD,CACE,OAAQ,EACR,MAAO,EAAO,MACd,KAAM,EAAQ,EAAO,MAAO,EAAO,GAAG,EAC9B,SACR,SAAU,EACV,eAAA,GACQ,SACF,OACQ,eACD,cACD,aACA,YACb,CAAA,EAGL,QACE,OAAiB,EAAV,EAAW,GAAkC,GAAnC,CAAc,GAAI,CAAY,CAA+B,CAClF,CACF,CAEA,OACE,EAAC,MAAD,CACE,GAAI,EACJ,IAAK,EAAU,EAAS,CAAG,EAC3B,UAAW,EAAG,GAAO,SAAU,GAAW,GAAY,IAAI,EAC1D,MAAO,CAAE,GAAG,GAAO,GAAG,GAAY,IAAK,EAJzC,SAAA,CAME,EAAC,GAAD,CACE,UAAW,GAAY,OACvB,MAAO,GAAY,OACV,UACT,MAAO,GAAkB,EAAM,EAAM,GAAY,CAAM,EAC5C,aACL,OACC,QACD,OACN,OAAS,GAAS,EAAW,GAAS,EAAM,EAAM,EAAM,CAAM,CAAC,EAC/D,YAAe,EAAW,IAAI,IAAM,EACpC,aAAc,CACf,CAAA,EACA,GAAW,CACT,GAET"}
|
|
1
|
+
{"version":3,"file":"calendar.mjs","names":[],"sources":["../../../../package/common/calendar/calendar.tsx"],"sourcesContent":["import { useEffect, useLayoutEffect, useRef, useState, type ReactElement } from 'react';\nimport cx from 'classnames';\n\nimport { useComponentDefaults, useLabels } from '../configProvider';\nimport { mergeRefs } from '../utils/mergeRefs';\nimport { asDay, dayToDate } from '../utils/day';\nimport {\n CalendarView,\n type CalendarEvent,\n type CalendarEventChange,\n type CalendarLabels,\n type CalendarProps,\n} from './calendar.types';\nimport {\n dayDiff,\n dateToDay,\n addDays,\n hiddenDaySet,\n periodRange,\n rangeWithNeighbours,\n shownDay,\n shownDays,\n startOfDay,\n stepDate,\n} from './dates';\nimport { formatPeriodTitle, localeWeekStart } from './format';\nimport AgendaList from './components/agendaList';\nimport CalendarHeader from './components/calendarHeader';\nimport CompactMonth from './components/compactMonth';\nimport MonthView from './components/monthView';\nimport TimeGrid from './components/timeGrid';\nimport type { TimeGridZoom } from './components/timeGrid/timeGrid.types';\nimport type { CalendarViewProps } from './view.types';\n\nimport styles from './calendar.module.pcss';\n\nconst ALL_VIEWS = [CalendarView.Month, CalendarView.Week, CalendarView.Day, CalendarView.Agenda];\n\n/** Below this width the month view folds into the compact month with a day list. */\nconst COMPACT_WIDTH = 600;\n\nconst DEFAULT_LABELS: Required<CalendarLabels> = {\n previous: 'Previous',\n next: 'Next',\n today: 'Today',\n viewSwitcher: 'Calendar view',\n month: 'Month',\n week: 'Week',\n day: 'Day',\n agenda: 'Agenda',\n allDay: 'All day',\n more: (count) => `+${count} more`,\n eventCount: (count) => (count === 1 ? '1 event' : `${count} events`),\n noEvents: 'No events',\n newEvent: 'New event',\n};\n\nfunction Calendar<E extends CalendarEvent = CalendarEvent>(props: CalendarProps<E>): ReactElement {\n const {\n events,\n date: controlledDate,\n defaultDate,\n onDateChange,\n view: controlledView,\n defaultView = CalendarView.Month,\n onViewChange,\n views = ALL_VIEWS,\n locale,\n weekStartsOn: weekStartsOnProp,\n slotMinutes = 15,\n hiddenDays,\n scrollToHour,\n onRangeChange,\n onEventClick,\n onEventChange,\n onSlotCreate,\n renderEvent,\n labels,\n ref,\n className,\n style,\n classNames,\n styles: slotStyles,\n ...rest\n } = useComponentDefaults('Calendar', props);\n const text = useLabels('Calendar', labels, DEFAULT_LABELS);\n const weekStartsOn = weekStartsOnProp ?? localeWeekStart(locale);\n const hidden = hiddenDaySet(hiddenDays);\n\n const rootRef = useRef<HTMLDivElement>(null);\n const zoomRef = useRef<TimeGridZoom | null>(null);\n const [width, setWidth] = useState(0);\n const [direction, setDirection] = useState<1 | -1>(1);\n\n // `date` is a day, the same wherever the calendar is opened, and read as its first local moment.\n const [internalDate, setInternalDate] = useState(() => {\n const initial = asDay(defaultDate);\n return initial ? dayToDate(initial) : startOfDay(new Date());\n });\n const controlledDay = asDay(controlledDate);\n // Only ever a day the views show. The selection itself is left alone: a hidden day in `date` is\n // the parent's, and stepping on from it lands where the parent would expect.\n const date = shownDay(controlledDay ? dayToDate(controlledDay) : internalDate, hidden);\n const [internalView, setInternalView] = useState(defaultView);\n const view = controlledView ?? internalView;\n\n // The layout switch follows the calendar's own width rather than the viewport's, so it also\n // happens in a sidebar on a wide screen. Width 0 means no layout (server, jsdom): stay wide.\n useLayoutEffect(() => {\n const root = rootRef.current;\n if (!root) return;\n // The border box, both times: an observer's `contentRect` leaves the border out, and 600px\n // wide would then read as 598.\n const measure = () => setWidth(root.getBoundingClientRect().width);\n measure();\n const observer = new ResizeObserver(measure);\n observer.observe(root);\n return () => observer.disconnect();\n }, []);\n const compact = width > 0 && width < COMPACT_WIDTH;\n\n // Reported per range, not per render: `date` is a new object on every render of a controlled\n // parent. Not `useEffectEvent` for the latest callback, which React only has from 19.2.\n // An effect, since controlled props move the range too; `reported` keeps StrictMode's re-run\n // from reporting a range twice, which a consumer fetching in the callback pays for.\n const range = rangeWithNeighbours(view, date, weekStartsOn, hidden);\n const rangeKey = `${dateToDay(range.start)}/${dateToDay(range.end)}`;\n const latest = useRef({ range, onRangeChange });\n const reported = useRef<string | null>(null);\n useLayoutEffect(() => {\n latest.current = { range, onRangeChange };\n });\n useEffect(() => {\n if (reported.current === rangeKey) return;\n reported.current = rangeKey;\n latest.current.onRangeChange?.(latest.current.range);\n }, [rangeKey]);\n\n function changeDate(next: Date) {\n const day = startOfDay(next);\n if (dateToDay(day) === dateToDay(date)) return;\n setDirection(day > date ? 1 : -1);\n if (controlledDate === undefined) setInternalDate(day);\n onDateChange?.(dateToDay(day));\n }\n\n function changeView(next: CalendarView) {\n if (next === view) return;\n if (controlledView === undefined) setInternalView(next);\n onViewChange?.(next);\n }\n\n // Moves whose promise has not settled yet, drawn where they were dropped meanwhile.\n const [pending, setPending] = useState<ReadonlyMap<string, { start: Date; end: Date }>>(() => new Map());\n function changeEvent(change: CalendarEventChange<E>) {\n const result = onEventChange?.(change);\n if (typeof (result as Promise<unknown> | undefined)?.then !== 'function') return;\n const key = String(change.event.id);\n const entry = { start: change.start, end: change.end };\n setPending((current) => new Map(current).set(key, entry));\n // A later move of the same event owns the entry by then, and keeps it.\n const settle = () =>\n setPending((current) => {\n if (current.get(key) !== entry) return current;\n const next = new Map(current);\n next.delete(key);\n return next;\n });\n (result as Promise<unknown>).then(settle, settle);\n }\n const shownEvents =\n pending.size === 0\n ? events\n : events.map((event) => {\n const moved = pending.get(String(event.id));\n return moved ? { ...event, ...moved } : event;\n });\n\n const viewProps: CalendarViewProps<E> = {\n events: shownEvents,\n date,\n view,\n locale,\n weekStartsOn,\n slotMinutes,\n hidden,\n scrollToHour,\n text,\n onDateChange: changeDate,\n onOpenDay: views.includes(CalendarView.Day)\n ? (day) => {\n changeDate(day);\n changeView(CalendarView.Day);\n }\n : undefined,\n onEventClick,\n onEventChange: onEventChange && changeEvent,\n onSlotCreate,\n renderEvent,\n classNames,\n slotStyles,\n };\n\n // The week's title names the days it shows, not the ones it hides at either end.\n const period = periodRange(view, date, weekStartsOn);\n const columns = shownDays(period.start, dayDiff(period.start, period.end), hidden);\n const titleRange = { start: columns[0], end: addDays(columns[columns.length - 1], 1) };\n\n function renderView() {\n switch (view) {\n case CalendarView.Week:\n case CalendarView.Day:\n return <TimeGrid {...viewProps} zoomRef={zoomRef} />;\n case CalendarView.Agenda: {\n return (\n <AgendaList\n events={shownEvents}\n start={period.start}\n days={dayDiff(period.start, period.end)}\n hidden={hidden}\n scrollTo={date}\n showDayHeaders\n locale={locale}\n text={text}\n onEventClick={onEventClick}\n renderEvent={renderEvent}\n classNames={classNames}\n slotStyles={slotStyles}\n />\n );\n }\n default:\n return compact ? <CompactMonth {...viewProps} /> : <MonthView {...viewProps} />;\n }\n }\n\n return (\n <div\n {...rest}\n ref={mergeRefs(rootRef, ref)}\n className={cx(styles.calendar, className, classNames?.root)}\n style={{ ...style, ...slotStyles?.root }}\n >\n <CalendarHeader\n className={classNames?.header}\n style={slotStyles?.header}\n compact={compact}\n title={formatPeriodTitle(view, date, titleRange, locale)}\n direction={direction}\n view={view}\n views={views}\n text={text}\n onStep={(step) => changeDate(stepDate(view, date, step, hidden))}\n onToday={() => changeDate(new Date())}\n onViewChange={changeView}\n />\n {renderView()}\n </div>\n );\n}\n\nexport default Calendar;\n"],"mappings":"6hCAoCA,IAAM,GAAY,CAAC,EAAa,MAAO,EAAa,KAAM,EAAa,IAAK,EAAa,MAAM,EAGzF,GAAgB,IAEhB,GAA2C,CAC/C,SAAU,WACV,KAAM,OACN,MAAO,QACP,aAAc,gBACd,MAAO,QACP,KAAM,OACN,IAAK,MACL,OAAQ,SACR,OAAQ,UACR,KAAO,GAAU,IAAI,EAAM,OAC3B,WAAa,GAAW,IAAU,EAAI,UAAY,GAAG,EAAM,SAC3D,SAAU,YACV,SAAU,WACZ,EAEA,SAAS,EAAkD,EAAuC,CAChG,GAAM,CACJ,SACA,KAAM,EACN,eACA,gBACA,KAAM,EACN,eAAc,EAAa,MAC3B,gBACA,QAAQ,GACR,SACA,aAAc,GACd,eAAc,GACd,cACA,gBACA,gBACA,eACA,gBACA,eACA,cACA,SACA,MACA,YACA,SACA,aACA,OAAQ,EACR,GAAG,IACD,EAAqB,WAAY,CAAK,EACpC,EAAO,EAAU,WAAY,EAAQ,EAAc,EACnD,EAAe,IAAoB,GAAgB,CAAM,EACzD,EAAS,GAAa,EAAU,EAEhC,EAAU,EAAuB,IAAI,EACrC,GAAU,EAA4B,IAAI,EAC1C,CAAC,EAAO,IAAY,EAAS,CAAC,EAC9B,CAAC,GAAW,IAAgB,EAAiB,CAAC,EAG9C,CAAC,GAAc,IAAmB,MAAe,CACrD,IAAM,EAAU,EAAM,EAAW,EACjC,OAAO,E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AO,EAAO,MACd,KAAM,EAAQ,EAAO,MAAO,EAAO,GAAG,EAC9B,SACR,SAAU,EACV,eAAA,GACQ,SACF,OACQ,eACD,cACD,aACA,YACb,CAAA,EAGL,QACE,OAAiB,EAAV,EAAW,GAAkC,GAAnC,CAAc,GAAI,CAAY,CAA+B,CAClF,CACF,CAEA,OACE,GAAC,MAAD,CACE,GAAI,GACJ,IAAK,EAAU,EAAS,CAAG,EAC3B,UAAW,GAAG,GAAO,SAAU,EAAW,GAAY,IAAI,EAC1D,MAAO,CAAE,GAAG,GAAO,GAAG,GAAY,IAAK,EAJzC,SAAA,CAME,EAAC,GAAD,CACE,UAAW,GAAY,OACvB,MAAO,GAAY,OACV,UACT,MAAO,EAAkB,EAAM,EAAM,GAAY,CAAM,EAC5C,aACL,OACC,QACD,OACN,OAAS,GAAS,EAAW,EAAS,EAAM,EAAM,EAAM,CAAM,CAAC,EAC/D,YAAe,EAAW,IAAI,IAAM,EACpC,aAAc,CACf,CAAA,EACA,GAAW,CACT,GAET"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";import{tabbablesIn as e}from"./useFocusBoundary.mjs";import{useEffect as t,useRef as n}from"react";function r({isActive:r,containerRef:o,onEscape:s,trapFocus:c=!0,lockScroll:d=!0}){let f=n(s);t(()=>{f.current=s});let p=n(0);r&&p.current===0&&(p.current=i++),!r&&p.current!==0&&(p.current=0),t(()=>{if(!r)return;let t=p.current;a.add(t);let n=()=>t===Math.max(...a),i=document.activeElement;if(c){let t=o.current;(e(t)[0]??t)?.focus()}function s(t){if(!n())return;if(t.key===`Escape`&&f.current){t.preventDefault(),f.current();return}if(t.key!==`Tab`||!c)return;let r=e(o.current);if(r.length===0){t.preventDefault();return}let i=r[0],a=r[r.length-1],s=document.activeElement;o.current?.contains(s)?!t.shiftKey&&s===a?(t.preventDefault(),i.focus()):t.shiftKey&&s===i&&(t.preventDefault(),a.focus()):(t.preventDefault(),i.focus())}return window.addEventListener(`keydown`,s),d&&l(),()=>{window.removeEventListener(`keydown`,s),d&&u(),a.delete(t)
|
|
1
|
+
"use client";import{tabbablesIn as e}from"./useFocusBoundary.mjs";import{useEffect as t,useRef as n}from"react";function r({isActive:r,containerRef:o,onEscape:s,trapFocus:c=!0,lockScroll:d=!0}){let f=n(s);t(()=>{f.current=s});let p=n(0);r&&p.current===0&&(p.current=i++),!r&&p.current!==0&&(p.current=0),t(()=>{if(!r)return;let t=p.current;a.add(t);let n=()=>t===Math.max(...a),i=document.activeElement;if(c){let t=o.current;(e(t)[0]??t)?.focus()}function s(t){if(!n())return;if(t.key===`Escape`&&f.current){t.preventDefault(),f.current();return}if(t.key!==`Tab`||!c)return;let r=e(o.current);if(r.length===0){t.preventDefault();return}let i=r[0],a=r[r.length-1],s=document.activeElement;o.current?.contains(s)?!t.shiftKey&&s===a?(t.preventDefault(),i.focus()):t.shiftKey&&s===i&&(t.preventDefault(),a.focus()):(t.preventDefault(),i.focus())}let m=new Set,h=e=>e.code||e.key;function g(e){e.repeat?!m.has(h(e))&&o.current?.contains(e.target)&&(e.preventDefault(),e.stopPropagation()):m.add(h(e))}function _(e){m.delete(h(e))}return window.addEventListener(`keydown`,s),window.addEventListener(`keydown`,g,!0),window.addEventListener(`keyup`,_,!0),d&&l(),()=>{window.removeEventListener(`keydown`,s),window.removeEventListener(`keydown`,g,!0),window.removeEventListener(`keyup`,_,!0),d&&u(),a.delete(t);let e=[...a].some(e=>e>t);c&&!e&&i?.focus()}},[r,c,d,o])}var i=1,a=new Set,o=0,s=``,c=``;function l(){let{body:e}=document;if(o===0){s=e.style.overflow,c=e.style.paddingRight;let t=window.innerWidth-document.documentElement.clientWidth;if(t>0){let n=parseFloat(window.getComputedStyle(e).paddingRight)||0;e.style.paddingRight=`${n+t}px`}e.style.overflow=`hidden`}o+=1}function u(){--o,!(o>0)&&(o=0,document.body.style.overflow=s,document.body.style.paddingRight=c)}export{r as useOverlay};
|
|
2
2
|
//# sourceMappingURL=useOverlay.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useOverlay.mjs","names":[],"sources":["../../../../package/common/hooks/useOverlay.ts"],"sourcesContent":["import { useEffect, useRef, type RefObject } from 'react';\nimport { tabbablesIn } from './useFocusBoundary';\n\nexport interface UseOverlayArgs {\n /** Whether the overlay is currently visible. Everything below is set up while this is true. */\n isActive: boolean;\n /** The overlay panel. Focus is trapped inside it and Escape is scoped to it. */\n containerRef: RefObject<HTMLElement | null>;\n /** Called when Escape is pressed while this is the topmost overlay. Omit to not handle Escape. */\n onEscape?: () => void;\n
|
|
1
|
+
{"version":3,"file":"useOverlay.mjs","names":[],"sources":["../../../../package/common/hooks/useOverlay.ts"],"sourcesContent":["import { useEffect, useRef, type RefObject } from 'react';\nimport { tabbablesIn } from './useFocusBoundary';\n\nexport interface UseOverlayArgs {\n /** Whether the overlay is currently visible. Everything below is set up while this is true. */\n isActive: boolean;\n /** The overlay panel. Focus is trapped inside it and Escape is scoped to it. */\n containerRef: RefObject<HTMLElement | null>;\n /** Called when Escape is pressed while this is the topmost overlay. Omit to not handle Escape. */\n onEscape?: () => void;\n /**\n * Keep Tab inside the panel and restore focus to the previously focused element on close, unless\n * an overlay opened after this one is still open.\n */\n trapFocus?: boolean;\n /** Prevent the page behind the overlay from scrolling. */\n lockScroll?: boolean;\n}\n\n/**\n * The three behaviours every blocking overlay needs: Escape to dismiss, a focus trap, and a\n * scroll lock on the page behind it.\n *\n * They share one module-level stack because they share one question: overlays nest (a\n * ConfirmModal opened from inside a Modal), every instance listens on `document`, and only the\n * innermost one may react. Without the stack, Escape would close every open layer at once and\n * the outer trap would yank focus out of the inner panel on the next Tab.\n *\n * The scroll lock is reference-counted for the same reason: the page stays locked until the last\n * overlay closes, and the body's original inline styles are restored rather than cleared.\n */\nexport function useOverlay({ isActive, containerRef, onEscape, trapFocus = true, lockScroll = true }: UseOverlayArgs) {\n const onEscapeRef = useRef(onEscape);\n useEffect(() => {\n onEscapeRef.current = onEscape;\n });\n\n // The layer's position in the stack is claimed during render, not in the effect below, because\n // effects run child-first: an overlay opened from *inside* another one (a menu in a modal) has\n // its effect run before its own parent's and would come out as the lower layer. Render runs\n // parent-first, which is the order the layers are actually nested in. DOM order is no help\n // either — React commits the inner portal ahead of the outer one.\n const orderRef = useRef(0);\n if (isActive && orderRef.current === 0) orderRef.current = nextLayerOrder++;\n if (!isActive && orderRef.current !== 0) orderRef.current = 0;\n\n useEffect(() => {\n if (!isActive) return;\n\n const order = orderRef.current;\n activeLayers.add(order);\n const isTopmost = () => order === Math.max(...activeLayers);\n\n const previouslyFocused = document.activeElement as HTMLElement | null;\n if (trapFocus) {\n const container = containerRef.current;\n (tabbablesIn(container)[0] ?? container)?.focus();\n }\n\n function onKeyDown(event: KeyboardEvent) {\n if (!isTopmost()) return;\n\n if (event.key === 'Escape' && onEscapeRef.current) {\n event.preventDefault();\n onEscapeRef.current();\n return;\n }\n\n if (event.key !== 'Tab' || !trapFocus) return;\n const focusables = tabbablesIn(containerRef.current);\n // Nothing to move to inside the panel, but Tab must still not escape it.\n if (focusables.length === 0) {\n event.preventDefault();\n return;\n }\n const first = focusables[0];\n const last = focusables[focusables.length - 1];\n const active = document.activeElement;\n if (!containerRef.current?.contains(active)) {\n event.preventDefault();\n first.focus();\n } else if (!event.shiftKey && active === last) {\n event.preventDefault();\n first.focus();\n } else if (event.shiftKey && active === first) {\n event.preventDefault();\n last.focus();\n }\n }\n\n // A key held as this opened would repeat into what it focused: a held Enter pressed Close.\n // Outside the panel it still repeats, since suggestions open while the user types.\n const pressedSinceOpen = new Set<string>();\n const keyId = (event: KeyboardEvent) => event.code || event.key;\n function onKeyDownCapture(event: KeyboardEvent) {\n if (!event.repeat) pressedSinceOpen.add(keyId(event));\n else if (!pressedSinceOpen.has(keyId(event)) && containerRef.current?.contains(event.target as Node)) {\n event.preventDefault();\n event.stopPropagation();\n }\n }\n function onKeyUp(event: KeyboardEvent) {\n pressedSinceOpen.delete(keyId(event));\n }\n\n // `window`, not `document`: a key event on a focused element reaches both, but a synthetic\n // one dispatched straight at `window` (as tests and some consumers do) never reaches\n // `document`, since it sits above it in the propagation path.\n window.addEventListener('keydown', onKeyDown);\n window.addEventListener('keydown', onKeyDownCapture, true);\n window.addEventListener('keyup', onKeyUp, true);\n if (lockScroll) acquireScrollLock();\n\n return () => {\n window.removeEventListener('keydown', onKeyDown);\n window.removeEventListener('keydown', onKeyDownCapture, true);\n window.removeEventListener('keyup', onKeyUp, true);\n if (lockScroll) releaseScrollLock();\n activeLayers.delete(order);\n // Modal closes a commit late, so a Popover opened by the same click already holds the focus.\n const coveredByLaterLayer = [...activeLayers].some((other) => other > order);\n if (trapFocus && !coveredByLaterLayer) previouslyFocused?.focus();\n };\n }, [isActive, trapFocus, lockScroll, containerRef]);\n}\n\n/** Monotonic, so a layer opened later always outranks one opened earlier. */\nlet nextLayerOrder = 1;\nconst activeLayers = new Set<number>();\n\nlet scrollLockCount = 0;\nlet previousOverflow = '';\nlet previousPaddingRight = '';\n\nfunction acquireScrollLock() {\n const { body } = document;\n if (scrollLockCount === 0) {\n previousOverflow = body.style.overflow;\n previousPaddingRight = body.style.paddingRight;\n // Removing the page's scrollbar reclaims its width, so everything behind the overlay would\n // shift right by that amount without the compensating padding.\n const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;\n if (scrollbarWidth > 0) {\n const current = parseFloat(window.getComputedStyle(body).paddingRight) || 0;\n body.style.paddingRight = `${current + scrollbarWidth}px`;\n }\n body.style.overflow = 'hidden';\n }\n scrollLockCount += 1;\n}\n\nfunction releaseScrollLock() {\n scrollLockCount -= 1;\n if (scrollLockCount > 0) return;\n scrollLockCount = 0;\n document.body.style.overflow = previousOverflow;\n document.body.style.paddingRight = previousPaddingRight;\n}\n"],"mappings":"gHA+BA,SAAgB,EAAW,CAAE,WAAU,eAAc,WAAU,YAAY,GAAM,aAAa,IAAwB,CACpH,IAAM,EAAc,EAAO,CAAQ,EACnC,MAAgB,CACd,EAAY,QAAU,CACxB,CAAC,EAOD,IAA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OAAO,EAAM,CAAK,CAAC,CACtC,CAUA,OALA,OAAO,iBAAiB,UAAW,CAAS,EAC5C,OAAO,iBAAiB,UAAW,EAAkB,EAAI,EACzD,OAAO,iBAAiB,QAAS,EAAS,EAAI,EAC1C,GAAY,EAAkB,MAErB,CACX,OAAO,oBAAoB,UAAW,CAAS,EAC/C,OAAO,oBAAoB,UAAW,EAAkB,EAAI,EAC5D,OAAO,oBAAoB,QAAS,EAAS,EAAI,EAC7C,GAAY,EAAkB,EAClC,EAAa,OAAO,CAAK,EAEzB,IAAM,EAAsB,CAAC,GAAG,CAAY,CAAC,CAAC,KAAM,GAAU,EAAQ,CAAK,EACvE,GAAa,CAAC,GAAqB,GAAmB,MAAM,CAClE,CACF,EAAG,CAAC,EAAU,EAAW,EAAY,CAAY,CAAC,CACpD,CAGA,IAAI,EAAiB,EACf,EAAe,IAAI,IAErB,EAAkB,EAClB,EAAmB,GACnB,EAAuB,GAE3B,SAAS,GAAoB,CAC3B,GAAM,CAAE,QAAS,SACjB,GAAI,IAAoB,EAAG,CACzB,EAAmB,EAAK,MAAM,SAC9B,EAAuB,EAAK,MAAM,aAGlC,IAAM,EAAiB,OAAO,WAAa,SAAS,gBAAgB,YACpE,GAAI,EAAiB,EAAG,CACtB,IAAM,EAAU,WAAW,OAAO,iBAAiB,CAAI,CAAC,CAAC,YAAY,GAAK,EAC1E,EAAK,MAAM,aAAe,GAAG,EAAU,EAAe,GACxD,CACA,EAAK,MAAM,SAAW,QACxB,CACA,GAAmB,CACrB,CAEA,SAAS,GAAoB,CAC3B,IACI,IAAkB,KACtB,EAAkB,EAClB,SAAS,KAAK,MAAM,SAAW,EAC/B,SAAS,KAAK,MAAM,aAAe,EACrC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";import{useComponentDefaults as e}from"../configProvider/useComponentDefaults.mjs";import{useLabels as t}from"../configProvider/useLabels.mjs";import{usePresentationDefault as n}from"../configProvider/usePresentationDefault.mjs";import r from"../bodyEnd/bodyEnd.mjs";import i from"../styles/sheet.module.mjs";import{useVisualViewportSize as a}from"../hooks/useVisualViewportSize.mjs";import o from"../hooks/useSheet.mjs";import{useOverlay as s}from"../hooks/useOverlay.mjs";import c from"../styles/scrollFade.module.mjs";import l from"./modal.module.mjs";import{useScrollEdges as u}from"../hooks/useScrollEdges.mjs";import{useEffect as d,useId as f,useRef as p,useState as m}from"react";import h from"classnames";import{FontAwesomeIcon as g}from"@fortawesome/react-fontawesome";import{faXmark as _}from"@fortawesome/free-solid-svg-icons";import{jsx as v,jsxs as y}from"react/jsx-runtime";var b={close:`Close`};function x(x){let{children:S=null,title:C,isOpen:w=!1,onClose:T=()=>null,footer:E=null,className:D=``,style:O,hideHeader:k=!1,closeOnEscape:A=!0,presentation:j,classNames:M,styles:N,labels:P,...F}=e(`Modal`,x),I=t(`Modal`,P,b),[L,R]=m(w),[z,B]=m(w),V=p(null),H=p(null),U=f(),{height:W,offsetTop:G}=a(),K=n(),{isSheet:q,sheetStyle:J}=o(j??K);d(()=>{w
|
|
1
|
+
"use client";import{useComponentDefaults as e}from"../configProvider/useComponentDefaults.mjs";import{useLabels as t}from"../configProvider/useLabels.mjs";import{usePresentationDefault as n}from"../configProvider/usePresentationDefault.mjs";import r from"../bodyEnd/bodyEnd.mjs";import i from"../styles/sheet.module.mjs";import{useVisualViewportSize as a}from"../hooks/useVisualViewportSize.mjs";import o from"../hooks/useSheet.mjs";import{useOverlay as s}from"../hooks/useOverlay.mjs";import c from"../styles/scrollFade.module.mjs";import l from"./modal.module.mjs";import{useScrollEdges as u}from"../hooks/useScrollEdges.mjs";import{useEffect as d,useId as f,useRef as p,useState as m}from"react";import h from"classnames";import{FontAwesomeIcon as g}from"@fortawesome/react-fontawesome";import{faXmark as _}from"@fortawesome/free-solid-svg-icons";import{jsx as v,jsxs as y}from"react/jsx-runtime";var b={close:`Close`};function x(x){let{children:S=null,title:C,isOpen:w=!1,onClose:T=()=>null,footer:E=null,className:D=``,style:O,hideHeader:k=!1,closeOnEscape:A=!0,presentation:j,classNames:M,styles:N,labels:P,...F}=e(`Modal`,x),I=t(`Modal`,P,b),[L,R]=m(w),[z,B]=m(w),V=p(null),H=p(null),U=f(),{height:W,offsetTop:G}=a(),K=n(),{isSheet:q,sheetStyle:J}=o(j??K);d(()=>{if(w){R(!0);let e=setTimeout(()=>B(!0),1);return()=>clearTimeout(e)}B(!1);let e=setTimeout(()=>R(!1),300);return()=>clearTimeout(e)},[w]),s({isActive:L&&z,containerRef:V,onEscape:A?T:void 0});let{hasStart:Y,hasEnd:X}=u(H,{isEnabled:L&&z});if(!L)return null;let Z=!k&&!!C;return v(r,{children:y(`div`,{className:h(l.modalContainer,M?.container),style:{height:W,top:G,...N?.container},children:[v(`div`,{className:h(l.modalWrapper,z&&l.modalWrapperShown,M?.backdrop),style:N?.backdrop,onClick:T}),z&&y(`div`,{...F,ref:V,role:`dialog`,"aria-modal":`true`,"aria-labelledby":Z&&!F[`aria-label`]?U:void 0,tabIndex:-1,className:h(l.modal,z&&l.modalShown,q&&[i.sheet,i.sheetSurface,l.modalSheet],D,M?.modal),style:{...q?J:void 0,...O,...N?.modal},onClick:e=>e.stopPropagation(),children:[!k&&y(`div`,{className:h(l.modalHeader,M?.header),style:N?.header,children:[v(`div`,{id:U,className:M?.title,style:N?.title,children:C}),v(`button`,{type:`button`,onClick:T,"aria-label":I.close,className:h(l.modalCloseButton,M?.closeButton),style:N?.closeButton,children:v(g,{icon:_})})]}),v(`div`,{ref:H,className:h(l.modalBody,c.scrollFade,c.scrollFadeY,Y&&c.scrollFadeFadedStart,X&&c.scrollFadeFadedEnd,M?.body),style:N?.body,children:S}),E&&v(`div`,{className:h(l.modalFooter,M?.footer),style:N?.footer,children:E})]})]})})}export{x as default};
|
|
2
2
|
//# sourceMappingURL=modal.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"modal.mjs","names":[],"sources":["../../../../package/common/modal/modal.tsx"],"sourcesContent":["import cx from 'classnames';\nimport BodyEnd from 'components/common/bodyEnd';\n\nimport styles from './modal.module.pcss';\nimport sheetStyles from 'components/common/styles/sheet.module.pcss';\nimport { FontAwesomeIcon } from '@fortawesome/react-fontawesome';\nimport { faXmark as closeIcon } from '@fortawesome/free-solid-svg-icons';\nimport { ModalProps } from './modal.types';\nimport type { ModalLabels } from './modal.types';\nimport { useEffect, useId, useRef, useState } from 'react';\nimport { useVisualViewportSize } from 'components/common/hooks/useVisualViewportSize';\nimport { useOverlay } from 'components/common/hooks/useOverlay';\nimport { useSheet } from 'components/common/hooks/useSheet';\nimport { useScrollEdges } from 'components/common/hooks/useScrollEdges';\nimport fadeStyles from 'components/common/styles/scrollFade.module.pcss';\nimport { useComponentDefaults, useLabels, usePresentationDefault } from 'components/common/configProvider';\n\nconst DEFAULT_LABELS: Required<ModalLabels> = {\n close: 'Close',\n};\n\nfunction Modal(props: ModalProps) {\n const {\n children = null,\n title,\n isOpen = false,\n onClose = () => null,\n footer = null,\n className = '',\n style,\n hideHeader = false,\n closeOnEscape = true,\n presentation: presentationProp,\n classNames,\n styles: slotStyles,\n labels,\n ...rest\n } = useComponentDefaults('Modal', props);\n const text = useLabels('Modal', labels, DEFAULT_LABELS);\n const [isRendered, setIsRendered] = useState(isOpen);\n const [animateIn, setAnimateIn] = useState(isOpen);\n const modalRef = useRef<HTMLDivElement>(null);\n const bodyRef = useRef<HTMLDivElement>(null);\n const titleId = useId();\n // Centering/sizing against the actually-visible viewport (not the full layout viewport) keeps\n // the modal — and whatever's focused inside it — from ending up under a mobile keyboard.\n const { height: viewportHeight, offsetTop: viewportOffsetTop } = useVisualViewportSize();\n // Explicit prop → this component's global default → the app-wide one. There's no built-in\n // fallback to add: `Default` and no presentation at all both mean the ordinary centred dialog.\n const appPresentation = usePresentationDefault();\n const presentation = presentationProp ?? appPresentation;\n const { isSheet, sheetStyle } = useSheet(presentation);\n\n useEffect(() => {\n if (isOpen) {\n // eslint-disable-next-line react-hooks/set-state-in-effect\n setIsRendered(
|
|
1
|
+
{"version":3,"file":"modal.mjs","names":[],"sources":["../../../../package/common/modal/modal.tsx"],"sourcesContent":["import cx from 'classnames';\nimport BodyEnd from 'components/common/bodyEnd';\n\nimport styles from './modal.module.pcss';\nimport sheetStyles from 'components/common/styles/sheet.module.pcss';\nimport { FontAwesomeIcon } from '@fortawesome/react-fontawesome';\nimport { faXmark as closeIcon } from '@fortawesome/free-solid-svg-icons';\nimport { ModalProps } from './modal.types';\nimport type { ModalLabels } from './modal.types';\nimport { useEffect, useId, useRef, useState } from 'react';\nimport { useVisualViewportSize } from 'components/common/hooks/useVisualViewportSize';\nimport { useOverlay } from 'components/common/hooks/useOverlay';\nimport { useSheet } from 'components/common/hooks/useSheet';\nimport { useScrollEdges } from 'components/common/hooks/useScrollEdges';\nimport fadeStyles from 'components/common/styles/scrollFade.module.pcss';\nimport { useComponentDefaults, useLabels, usePresentationDefault } from 'components/common/configProvider';\n\nconst DEFAULT_LABELS: Required<ModalLabels> = {\n close: 'Close',\n};\n\nfunction Modal(props: ModalProps) {\n const {\n children = null,\n title,\n isOpen = false,\n onClose = () => null,\n footer = null,\n className = '',\n style,\n hideHeader = false,\n closeOnEscape = true,\n presentation: presentationProp,\n classNames,\n styles: slotStyles,\n labels,\n ...rest\n } = useComponentDefaults('Modal', props);\n const text = useLabels('Modal', labels, DEFAULT_LABELS);\n const [isRendered, setIsRendered] = useState(isOpen);\n const [animateIn, setAnimateIn] = useState(isOpen);\n const modalRef = useRef<HTMLDivElement>(null);\n const bodyRef = useRef<HTMLDivElement>(null);\n const titleId = useId();\n // Centering/sizing against the actually-visible viewport (not the full layout viewport) keeps\n // the modal — and whatever's focused inside it — from ending up under a mobile keyboard.\n const { height: viewportHeight, offsetTop: viewportOffsetTop } = useVisualViewportSize();\n // Explicit prop → this component's global default → the app-wide one. There's no built-in\n // fallback to add: `Default` and no presentation at all both mean the ordinary centred dialog.\n const appPresentation = usePresentationDefault();\n const presentation = presentationProp ?? appPresentation;\n const { isSheet, sheetStyle } = useSheet(presentation);\n\n // Cancelled on a flip back, or a reopen during the close animation is hidden by its late unmount.\n useEffect(() => {\n if (isOpen) {\n // eslint-disable-next-line react-hooks/set-state-in-effect\n setIsRendered(true);\n const id = setTimeout(() => setAnimateIn(true), 1);\n return () => clearTimeout(id);\n }\n setAnimateIn(false);\n const id = setTimeout(() => setIsRendered(false), 300);\n return () => clearTimeout(id);\n }, [isOpen]);\n\n // Keyed on `animateIn` rather than `isOpen`, because the panel this needs to focus and trap\n // focus inside of only mounts once that flips.\n useOverlay({\n isActive: isRendered && animateIn,\n containerRef: modalRef,\n onEscape: closeOnEscape ? onClose : undefined,\n });\n\n const { hasStart, hasEnd } = useScrollEdges(bodyRef, { isEnabled: isRendered && animateIn });\n\n if (!isRendered) return null;\n\n const hasHeaderTitle = !hideHeader && !!title;\n\n return (\n <BodyEnd>\n <div\n className={cx(styles.modalContainer, classNames?.container)}\n style={{ height: viewportHeight, top: viewportOffsetTop, ...slotStyles?.container }}\n >\n <div\n className={cx(styles.modalWrapper, animateIn && styles.modalWrapperShown, classNames?.backdrop)}\n style={slotStyles?.backdrop}\n onClick={onClose}\n />\n {animateIn && (\n <div\n {...rest}\n ref={modalRef}\n role='dialog'\n aria-modal='true'\n // aria-labelledby would outrank aria-label, which is the only way to name a title with no text.\n aria-labelledby={hasHeaderTitle && !rest['aria-label'] ? titleId : undefined}\n // Focusable so the trap has somewhere to put focus when the content has no tabbables.\n tabIndex={-1}\n className={cx(\n styles.modal,\n animateIn && styles.modalShown,\n // The panel is its own sheet surface here: there's no inner panel to fill, since\n // Modal already splits itself into a fixed header and a scrolling body.\n isSheet && [sheetStyles.sheet, sheetStyles.sheetSurface, styles.modalSheet],\n className,\n classNames?.modal,\n )}\n style={{ ...(isSheet ? sheetStyle : undefined), ...style, ...slotStyles?.modal }}\n onClick={(e) => e.stopPropagation()}\n >\n {!hideHeader && (\n <div className={cx(styles.modalHeader, classNames?.header)} style={slotStyles?.header}>\n <div id={titleId} className={classNames?.title} style={slotStyles?.title}>\n {title}\n </div>\n <button\n type='button'\n onClick={onClose}\n aria-label={text.close}\n className={cx(styles.modalCloseButton, classNames?.closeButton)}\n style={slotStyles?.closeButton}\n >\n <FontAwesomeIcon icon={closeIcon} />\n </button>\n </div>\n )}\n <div\n ref={bodyRef}\n className={cx(\n styles.modalBody,\n fadeStyles.scrollFade,\n fadeStyles.scrollFadeY,\n hasStart && fadeStyles.scrollFadeFadedStart,\n hasEnd && fadeStyles.scrollFadeFadedEnd,\n classNames?.body,\n )}\n style={slotStyles?.body}\n >\n {children}\n </div>\n {footer && (\n <div className={cx(styles.modalFooter, classNames?.footer)} style={slotStyles?.footer}>\n {footer}\n </div>\n )}\n </div>\n )}\n </div>\n </BodyEnd>\n );\n}\n\nexport default Modal;\n"],"mappings":"o4BAiBA,IAAM,EAAwC,CAC5C,MAAO,OACT,EAEA,SAAS,EAAM,EAAmB,CAChC,GAAM,CACJ,WAAW,KACX,QACA,SAAS,GACT,cAAgB,KAChB,SAAS,KACT,YAAY,GACZ,QACA,aAAa,GACb,gBAAgB,GAChB,aAAc,EACd,aACA,OAAQ,EACR,SACA,GAAG,GACD,EAAqB,QAAS,CAAK,EACjC,EAAO,EAAU,QAAS,EAAQ,CAAc,EAChD,CAAC,EAAY,GAAiB,EAAS,CAAM,EAC7C,CAAC,EAAW,GAAgB,EAAS,CAAM,EAC3C,EAAW,EAAuB,IAAI,EACtC,EAAU,EAAuB,IAAI,EACrC,EAAU,EAAM,EAGhB,CAAE,OAAQ,EAAgB,UAAW,GAAsB,EAAsB,EAGjF,EAAkB,EAAuB,EAEzC,CAAE,UAAS,cAAe,EADX,GAAoB,CACY,EAGrD,MAAgB,CACd,GAAI,EAAQ,CAEV,EAAc,EAAI,EAClB,IAAM,EAAK,eAAiB,EAAa,EAAI,EAAG,CAAC,EACjD,UAAa,aAAa,CAAE,CAC9B,CACA,EAAa,EAAK,EAClB,IAAM,EAAK,eAAiB,EAAc,EAAK,EAAG,GAAG,EACrD,UAAa,aAAa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O,GAAY,YAEnB,SAAA,EAAC,EAAD,CAAiB,KAAM,CAAY,CAAA,CAC7B,CAAA,CACL,IAEP,EAAC,MAAD,CACE,IAAK,EACL,UAAW,EACT,EAAO,UACP,EAAW,WACX,EAAW,YACX,GAAY,EAAW,qBACvB,GAAU,EAAW,mBACrB,GAAY,IACd,EACA,MAAO,GAAY,KAElB,UACE,CAAA,EACJ,GACC,EAAC,MAAD,CAAK,UAAW,EAAG,EAAO,YAAa,GAAY,MAAM,EAAG,MAAO,GAAY,OAC5E,SAAA,CACE,CAAA,CAEJ,CAEJ,CAAA,CAAA,CACE,CAAA,CAAA,CAAA,CAEb"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";import{useComponentDefaults as e}from"../configProvider/useComponentDefaults.mjs";import{useLabels as t}from"../configProvider/useLabels.mjs";import n from"../tooltip/tooltip.mjs";import{OtpInputCharset as r}from"./otpInput.types.mjs";import i from"./otpInput.module.mjs";import{useEffect as a,useRef as o,useState as s}from"react";import c from"classnames";import{jsx as l,jsxs as u}from"react/jsx-runtime";var d=/[0-9]/g,f=/[a-zA-Z0-9]/g,
|
|
1
|
+
"use client";import{useComponentDefaults as e}from"../configProvider/useComponentDefaults.mjs";import{useLabels as t}from"../configProvider/useLabels.mjs";import n from"../tooltip/tooltip.mjs";import{OtpInputCharset as r}from"./otpInput.types.mjs";import i from"./otpInput.module.mjs";import{useEffect as a,useRef as o,useState as s}from"react";import c from"classnames";import{jsx as l,jsxs as u}from"react/jsx-runtime";var d=/[0-9]/g,f=/[a-zA-Z0-9]/g,ee={field:`One-time code`,digit:(e,t)=>`Digit ${e} of ${t}`};function p(e,t){let n=t===r.Alphanumeric?f:d;return(e.match(n)||[]).join(``)}function m(d){let{length:f=6,value:m,onChange:h=()=>{},onComplete:g=()=>{},formValidator:_=null,charset:v=r.Numeric,masked:y=!1,groupAfter:b=[],label:x=``,isValid:S=!0,errorMessage:C=``,isRequired:w=!1,clearOnError:T=!1,clearErrorDelay:E=900,disabled:D=!1,autoFocus:O=!1,className:k=``,style:A,classNames:j,styles:M,labels:N,...P}=e(`OtpInput`,d),F=t(`OtpInput`,N,ee),I=(_?_.value:m)??``,[,L]=s(0),[R,z]=s(!1),[B,V]=s(!1),[H,U]=s(!1),[W,G]=s(!1),[K,q]=s(!1),J=o([]);a(()=>{if(!_)return;_.validate();let e=()=>L(e=>e+1);return _.registerOnUpdateListener(e),()=>_.removeOnUpdateListener(e)},[_]),a(()=>{if(!O)return;let e=Math.min(I.length,f-1);J.current[e]?.focus()},[]);let Y=_?_.touched&&_.hasError():!S||!!C,X=_?_.getCurrentErrorMessage():C||``;Y!==K&&(q(Y),Y&&z(!0),G(Y&&T)),a(()=>{if(!R)return;let e=window.setTimeout(()=>z(!1),400);return()=>window.clearTimeout(e)},[R]),a(()=>{if(!W||!T)return;let e=window.setTimeout(()=>{G(!1),Z(``),J.current[0]?.focus()},E);return()=>window.clearTimeout(e)},[W,T,E]);function Z(e){let t=I.length===f,n=p(e,v).slice(0,f);_&&_.set(n),h?.(n),n.length===f&&!t&&g?.(n)}function Q(e,t){let n=I.split(``);n[e]=t,Z(n.join(``))}function te(e,t){if(D)return;if(t===``){Q(e,``);return}let n=p(t,v);if(!n)return;let r=Math.min(e,I.length);if(t.length>1){$(r,n);return}Q(r,n),r<f-1?J.current[r+1]?.focus():J.current[r]?.blur()}function $(e,t){let n=p(t,v);if(!n)return;let r=I.padEnd(f,` `).split(``),i=e;for(let e of n){if(i>=f)break;r[i]=e,i+=1}Z(r.join(``).trimEnd());let a=Math.min(i,f-1);J.current[a]?.focus(),i>=f&&J.current[f-1]?.blur()}function ne(e,t){if(D)return;let n=t.clipboardData.getData(`text`);n&&(t.preventDefault(),$(Math.min(e,I.length),n))}function re(e,t){if(!D){if(t.key.length===1&&!t.ctrlKey&&!t.metaKey&&!t.altKey){let n=p(t.key,v);if(n&&I[e]===n){t.preventDefault(),Q(e,n),e<f-1?J.current[e+1]?.focus():J.current[e]?.blur();return}}if(t.key===`Backspace`){if(I[e]){Q(e,``);return}e>0&&(t.preventDefault(),Q(e-1,``),J.current[e-1]?.focus());return}if(t.key===`Delete`){I[e]&&Q(e,``);return}if(t.key===`ArrowLeft`&&e>0){t.preventDefault(),J.current[e-1]?.focus();return}t.key===`ArrowRight`&&e<f-1&&(t.preventDefault(),J.current[e+1]?.focus())}}function ie(e){e.target.select()}function ae(){V(!0)}function oe(e){e.currentTarget.contains(e.relatedTarget)||(V(!1),_&&(_.touched=!0))}return u(`div`,{...P,className:c(i.otpInput,D&&i.otpInputDisabled,k),style:A,children:[x&&u(`div`,{className:c(i.otpInputLabel,j?.label),style:M?.label,children:[x,w&&l(`span`,{className:i.otpInputRequiredMark,children:` *`})]}),l(`div`,{role:`group`,"aria-label":x||F.field,className:c(i.otpInputBoxes,R&&i.otpInputBoxesShake,j?.inputs),style:M?.inputs,onFocus:ae,onBlur:oe,onMouseEnter:()=>U(!0),onMouseLeave:()=>U(!1),children:Array.from({length:f},(e,t)=>{let n=I[t]||``;return u(`div`,{className:i.otpInputBoxWrapper,children:[l(`input`,{ref:e=>{J.current[t]=e},type:y?`password`:`text`,inputMode:v===r.Numeric?`numeric`:`text`,pattern:v===r.Numeric?`[0-9]*`:void 0,autoComplete:t===0?`one-time-code`:`off`,maxLength:1,disabled:D,value:n,"aria-label":F.digit(t+1,f),"aria-invalid":Y||void 0,className:c(i.otpInputBox,Y&&i.otpInputBoxError,n&&i.otpInputBoxFilled,j?.input),style:M?.input,onChange:e=>te(t,e.target.value),onKeyDown:e=>re(t,e),onPaste:e=>ne(t,e),onFocus:ie}),b.includes(t+1)&&t<f-1&&l(`span`,{className:c(i.otpInputSeparator,j?.separator),style:M?.separator})]},t)})}),l(n,{variant:`error`,message:X,isVisible:Y&&(B||H)})]})}export{m as default};
|
|
2
2
|
//# sourceMappingURL=otpInput.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"otpInput.mjs","names":[],"sources":["../../../../package/common/otpInput/otpInput.tsx"],"sourcesContent":["import { useEffect, useRef, useState, type ReactElement } from 'react';\nimport cx from 'classnames';\nimport Tooltip from 'components/common/tooltip';\nimport { useComponentDefaults, useLabels } from '../configProvider';\n\nimport { OtpInputCharset, type OtpInputLabels, type OtpInputProps } from './otpInput.types';\nimport styles from './otpInput.module.pcss';\n\nconst NUMERIC_RE = /[0-9]/g;\nconst ALPHANUMERIC_RE = /[a-zA-Z0-9]/g;\n\nconst DEFAULT_LABELS: Required<OtpInputLabels> = {\n field: 'One-time code',\n digit: (position, length) => `Digit ${position} of ${length}`,\n};\n\nfunction filterChars(raw: string, charset: OtpInputCharset): string {\n const re = charset === OtpInputCharset.Alphanumeric ? ALPHANUMERIC_RE : NUMERIC_RE;\n return (raw.match(re) || []).join('');\n}\n\nfunction OtpInput(props: OtpInputProps): ReactElement {\n const {\n length = 6,\n value,\n onChange = () => {},\n onComplete = () => {},\n formValidator = null,\n charset = OtpInputCharset.Numeric,\n masked = false,\n groupAfter = [],\n label = '',\n isValid = true,\n errorMessage = '',\n isRequired = false,\n clearOnError = false,\n clearErrorDelay = 900,\n disabled = false,\n autoFocus = false,\n className = '',\n style,\n classNames,\n styles: slotStyles,\n labels,\n ...rest\n } = useComponentDefaults('OtpInput', props);\n const text = useLabels('OtpInput', labels, DEFAULT_LABELS);\n\n const currentValue = (formValidator ? (formValidator.value as string) : value) ?? '';\n const [, forceUpdate] = useState(0);\n const [isShaking, setIsShaking] = useState(false);\n const [isFocused, setIsFocused] = useState(false);\n const [isHovered, setIsHovered] = useState(false);\n const inputRefs = useRef<Array<HTMLInputElement | null>>([]);\n const wasErrorRef = useRef(false);\n\n useEffect(() => {\n if (!formValidator) return;\n formValidator.validate();\n const listener = () => forceUpdate((n) => n + 1);\n formValidator.registerOnUpdateListener(listener);\n return () => formValidator.removeOnUpdateListener(listener);\n }, [formValidator]);\n\n useEffect(() => {\n if (!autoFocus) return;\n const firstEmpty = Math.min(currentValue.length, length - 1);\n inputRefs.current[firstEmpty]?.focus();\n // Only run once, on mount.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const showError = formValidator ? formValidator.touched && formValidator.hasError() : !isValid || !!errorMessage;\n const displayedErrorMessage = formValidator ? formValidator.getCurrentErrorMessage() : errorMessage || '';\n\n useEffect(() => {\n const justErrored = showError && !wasErrorRef.current;\n wasErrorRef.current = showError;\n if (!justErrored) return;\n\n setIsShaking(true);\n const shakeTimeoutId = window.setTimeout(() => setIsShaking(false), 400);\n const clearTimeoutId = clearOnError\n ? window.setTimeout(() => {\n commit('');\n inputRefs.current[0]?.focus();\n }, clearErrorDelay)\n : null;\n\n return () => {\n window.clearTimeout(shakeTimeoutId);\n if (clearTimeoutId != null) window.clearTimeout(clearTimeoutId);\n };\n // Only re-evaluate on an actual error-state or config change, not on every value/render.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [showError, clearOnError, clearErrorDelay]);\n\n function commit(next: string) {\n const wasComplete = currentValue.length === length;\n const clipped = filterChars(next, charset).slice(0, length);\n if (formValidator) {\n formValidator.set(clipped);\n }\n onChange?.(clipped);\n // Only fire once per genuinely new completion (going from partial to full), not on every\n // keystroke made while correcting an already-full code.\n if (clipped.length === length && !wasComplete) {\n onComplete?.(clipped);\n }\n }\n\n function setCharAt(index: number, char: string) {\n const chars = currentValue.split('');\n chars[index] = char;\n commit(chars.join(''));\n }\n\n function handleChange(index: number, rawInput: string) {\n if (disabled) return;\n if (rawInput === '') {\n // Box was cleared (e.g. select + delete) — Backspace itself is handled in onKeyDown.\n setCharAt(index, '');\n return;\n }\n\n const filtered = filterChars(rawInput, charset);\n if (!filtered) {\n // Typed an invalid/disallowed character — the controlled `value` re-render discards it.\n return;\n }\n\n // Clicking straight into a box past the contiguous filled prefix (skipping ahead of\n // empty boxes) fills the next expected slot instead, rather than leaving a gap before it\n // that setCharAt/distributeFrom can't represent in a plain string and would silently collapse.\n const targetIndex = Math.min(index, currentValue.length);\n\n if (rawInput.length > 1) {\n // Mobile autofill / SMS suggestions can drop the whole code into one box, bypassing maxLength.\n distributeFrom(targetIndex, filtered);\n return;\n }\n\n setCharAt(targetIndex, filtered);\n if (targetIndex < length - 1) {\n inputRefs.current[targetIndex + 1]?.focus();\n } else {\n inputRefs.current[targetIndex]?.blur();\n }\n }\n\n function distributeFrom(startIndex: number, chars: string) {\n const clean = filterChars(chars, charset);\n if (!clean) return;\n const existing = currentValue.padEnd(length, ' ').split('');\n let cursor = startIndex;\n for (const char of clean) {\n if (cursor >= length) break;\n existing[cursor] = char;\n cursor += 1;\n }\n commit(existing.join('').trimEnd());\n const nextFocus = Math.min(cursor, length - 1);\n inputRefs.current[nextFocus]?.focus();\n if (cursor >= length) {\n inputRefs.current[length - 1]?.blur();\n }\n }\n\n function handlePaste(index: number, event: React.ClipboardEvent<HTMLInputElement>) {\n if (disabled) return;\n const pasted = event.clipboardData.getData('text');\n if (!pasted) return;\n event.preventDefault();\n // Same clamp as handleChange — pasting into a box past the filled prefix starts at the\n // next expected slot instead of leaving an unrepresentable gap before it.\n distributeFrom(Math.min(index, currentValue.length), pasted);\n }\n\n function handleKeyDown(index: number, event: React.KeyboardEvent<HTMLInputElement>) {\n if (disabled) return;\n\n // React's controlled-input onChange never fires when the resulting value is identical to\n // what's already rendered (its value tracker sees no change) — so retyping the exact digit\n // already in a box would otherwise silently do nothing. keydown always fires, so handle that\n // one case here and skip the native edit entirely.\n if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {\n const typed = filterChars(event.key, charset);\n if (typed && currentValue[index] === typed) {\n event.preventDefault();\n setCharAt(index, typed);\n if (index < length - 1) {\n inputRefs.current[index + 1]?.focus();\n } else {\n inputRefs.current[index]?.blur();\n }\n return;\n }\n }\n\n if (event.key === 'Backspace') {\n if (currentValue[index]) {\n setCharAt(index, '');\n return;\n }\n if (index > 0) {\n event.preventDefault();\n setCharAt(index - 1, '');\n inputRefs.current[index - 1]?.focus();\n }\n return;\n }\n if (event.key === 'Delete') {\n if (currentValue[index]) setCharAt(index, '');\n return;\n }\n if (event.key === 'ArrowLeft' && index > 0) {\n event.preventDefault();\n inputRefs.current[index - 1]?.focus();\n return;\n }\n if (event.key === 'ArrowRight' && index < length - 1) {\n event.preventDefault();\n inputRefs.current[index + 1]?.focus();\n }\n }\n\n function handleFocus(event: React.FocusEvent<HTMLInputElement>) {\n event.target.select();\n }\n\n function handleGroupFocus() {\n setIsFocused(true);\n }\n\n function handleGroupBlur(event: React.FocusEvent<HTMLDivElement>) {\n // Auto-advance moves focus between boxes constantly while typing — only treat this as\n // leaving the group once focus actually lands outside it, not on the next box.\n if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;\n setIsFocused(false);\n if (formValidator) formValidator.touched = true;\n }\n\n return (\n <div {...rest} className={cx(styles.otpInput, disabled && styles.otpInputDisabled, className)} style={style}>\n {label && (\n <div className={cx(styles.otpInputLabel, classNames?.label)} style={slotStyles?.label}>\n {label}\n {isRequired && <span className={styles.otpInputRequiredMark}> *</span>}\n </div>\n )}\n <div\n role='group'\n aria-label={label || text.field}\n className={cx(styles.otpInputBoxes, isShaking && styles.otpInputBoxesShake, classNames?.inputs)}\n style={slotStyles?.inputs}\n onFocus={handleGroupFocus}\n onBlur={handleGroupBlur}\n onMouseEnter={() => setIsHovered(true)}\n onMouseLeave={() => setIsHovered(false)}\n >\n {Array.from({ length }, (_, index) => {\n const char = currentValue[index] || '';\n return (\n <div key={index} className={styles.otpInputBoxWrapper}>\n <input\n ref={(el) => {\n inputRefs.current[index] = el;\n }}\n type={masked ? 'password' : 'text'}\n inputMode={charset === OtpInputCharset.Numeric ? 'numeric' : 'text'}\n pattern={charset === OtpInputCharset.Numeric ? '[0-9]*' : undefined}\n autoComplete={index === 0 ? 'one-time-code' : 'off'}\n maxLength={1}\n disabled={disabled}\n value={char}\n aria-label={text.digit(index + 1, length)}\n aria-invalid={showError || undefined}\n className={cx(\n styles.otpInputBox,\n showError && styles.otpInputBoxError,\n char && styles.otpInputBoxFilled,\n classNames?.input,\n )}\n style={slotStyles?.input}\n onChange={(e) => handleChange(index, e.target.value)}\n onKeyDown={(e) => handleKeyDown(index, e)}\n onPaste={(e) => handlePaste(index, e)}\n onFocus={handleFocus}\n />\n {groupAfter.includes(index + 1) && index < length - 1 && (\n <span className={cx(styles.otpInputSeparator, classNames?.separator)} style={slotStyles?.separator} />\n )}\n </div>\n );\n })}\n </div>\n <Tooltip variant='error' message={displayedErrorMessage} isVisible={showError && (isFocused || isHovered)} />\n </div>\n );\n}\n\nexport default OtpInput;\n"],"mappings":"qaAQA,IAAM,EAAa,SACb,EAAkB,eAElB,EAA2C,CAC/C,MAAO,gBACP,OAAQ,EAAU,IAAW,SAAS,EAAS,MAAM,GACvD,EAEA,SAAS,EAAY,EAAa,EAAkC,CAClE,IAAM,EAAK,IAAY,EAAgB,aAAe,EAAkB,EACxE,OAAQ,EAAI,MAAM,CAAE,GAAK,CAAC,EAAA,CAAG,KAAK,EAAE,CACtC,CAEA,SAAS,EAAS,EAAoC,CACpD,GAAM,CACJ,SAAS,EACT,QACA,eAAiB,CAAC,EAClB,iBAAmB,CAAC,EACpB,gBAAgB,KAChB,UAAU,EAAgB,QAC1B,SAAS,GACT,aAAa,CAAC,EACd,QAAQ,GACR,UAAU,GACV,eAAe,GACf,aAAa,GACb,eAAe,GACf,kBAAkB,IAClB,WAAW,GACX,YAAY,GACZ,YAAY,GACZ,QACA,aACA,OAAQ,EACR,SACA,GAAG,GACD,EAAqB,WAAY,CAAK,EACpC,EAAO,EAAU,WAAY,EAAQ,CAAc,EAEnD,GAAgB,EAAiB,EAAc,MAAmB,IAAU,GAC5E,EAAG,GAAe,EAAS,CAAC,EAC5B,CAAC,EAAW,GAAgB,EAAS,EAAK,EAC1C,CAAC,EAAW,GAAgB,EAAS,EAAK,EAC1C,CAAC,EAAW,GAAgB,EAAS,EAAK,EAC1C,EAAY,EAAuC,CAAC,CAAC,EACrD,EAAc,EAAO,EAAK,EAEhC,MAAgB,CACd,GAAI,CAAC,EAAe,OACpB,EAAc,SAAS,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EAAG,EAAO,cAAe,GAAa,EAAO,mBAAoB,GAAY,MAAM,EAC9F,MAAO,GAAY,OACnB,QAAS,GACT,OAAQ,GACR,iBAAoB,EAAa,EAAI,EACrC,iBAAoB,EAAa,EAAK,EAErC,SAAA,MAAM,KAAK,CAAE,QAAO,GAAI,EAAG,IAAU,CACpC,IAAM,EAAO,EAAa,IAAU,GACpC,OACE,EAAC,MAAD,CAAiB,UAAW,EAAO,mBAAnC,SAAA,CACE,EAAC,QAAD,CACE,IAAM,GAAO,CACX,EAAU,QAAQ,GAAS,CAC7B,EACA,KAAM,EAAS,WAAa,OAC5B,UAAW,IAAY,EAAgB,QAAU,UAAY,OAC7D,QAAS,IAAY,EAAgB,QAAU,SAAW,IAAA,GAC1D,aAAc,IAAU,EAAI,gBAAkB,MAC9C,UAAW,EACD,WACV,MAAO,EACP,aAAY,EAAK,MAAM,EAAQ,EAAG,CAAM,EACxC,eAAc,GAAa,IAAA,GAC3B,UAAW,EACT,EAAO,YACP,GAAa,EAAO,iBACpB,GAAQ,EAAO,kBACf,GAAY,KACd,EACA,MAAO,GAAY,MACnB,SAAW,GAAM,EAAa,EAAO,EAAE,OAAO,KAAK,EACnD,UAAY,GAAM,GAAc,EAAO,CAAC,EACxC,QAAU,GAAM,EAAY,EAAO,CAAC,EACpC,QAAS,EACV,CAAA,EACA,EAAW,SAAS,EAAQ,CAAC,GAAK,EAAQ,EAAS,GAClD,EAAC,OAAD,CAAM,UAAW,EAAG,EAAO,kBAAmB,GAAY,SAAS,EAAG,MAAO,GAAY,SAAY,CAAA,CAEpG,CA7BK,EAAA,CA6BL,CAET,CAAC,CACE,CAAA,EACL,EAAC,EAAD,CAAS,QAAQ,QAAQ,QAAS,EAAuB,UAAW,IAAc,GAAa,EAAa,CAAA,CACzG,GAET"}
|
|
1
|
+
{"version":3,"file":"otpInput.mjs","names":[],"sources":["../../../../package/common/otpInput/otpInput.tsx"],"sourcesContent":["import { useEffect, useRef, useState, type ReactElement } from 'react';\nimport cx from 'classnames';\nimport Tooltip from 'components/common/tooltip';\nimport { useComponentDefaults, useLabels } from '../configProvider';\n\nimport { OtpInputCharset, type OtpInputLabels, type OtpInputProps } from './otpInput.types';\nimport styles from './otpInput.module.pcss';\n\nconst NUMERIC_RE = /[0-9]/g;\nconst ALPHANUMERIC_RE = /[a-zA-Z0-9]/g;\n\nconst DEFAULT_LABELS: Required<OtpInputLabels> = {\n field: 'One-time code',\n digit: (position, length) => `Digit ${position} of ${length}`,\n};\n\nfunction filterChars(raw: string, charset: OtpInputCharset): string {\n const re = charset === OtpInputCharset.Alphanumeric ? ALPHANUMERIC_RE : NUMERIC_RE;\n return (raw.match(re) || []).join('');\n}\n\nfunction OtpInput(props: OtpInputProps): ReactElement {\n const {\n length = 6,\n value,\n onChange = () => {},\n onComplete = () => {},\n formValidator = null,\n charset = OtpInputCharset.Numeric,\n masked = false,\n groupAfter = [],\n label = '',\n isValid = true,\n errorMessage = '',\n isRequired = false,\n clearOnError = false,\n clearErrorDelay = 900,\n disabled = false,\n autoFocus = false,\n className = '',\n style,\n classNames,\n styles: slotStyles,\n labels,\n ...rest\n } = useComponentDefaults('OtpInput', props);\n const text = useLabels('OtpInput', labels, DEFAULT_LABELS);\n\n const currentValue = (formValidator ? (formValidator.value as string) : value) ?? '';\n const [, forceUpdate] = useState(0);\n const [isShaking, setIsShaking] = useState(false);\n const [isFocused, setIsFocused] = useState(false);\n const [isHovered, setIsHovered] = useState(false);\n const [pendingClear, setPendingClear] = useState(false);\n const [wasError, setWasError] = useState(false);\n const inputRefs = useRef<Array<HTMLInputElement | null>>([]);\n\n useEffect(() => {\n if (!formValidator) return;\n formValidator.validate();\n const listener = () => forceUpdate((n) => n + 1);\n formValidator.registerOnUpdateListener(listener);\n return () => formValidator.removeOnUpdateListener(listener);\n }, [formValidator]);\n\n useEffect(() => {\n if (!autoFocus) return;\n const firstEmpty = Math.min(currentValue.length, length - 1);\n inputRefs.current[firstEmpty]?.focus();\n // Only run once, on mount.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const showError = formValidator ? formValidator.touched && formValidator.hasError() : !isValid || !!errorMessage;\n const displayedErrorMessage = formValidator ? formValidator.getCurrentErrorMessage() : errorMessage || '';\n\n // State set during render, not a ref read in an effect: the ref survives a remount (StrictMode,\n // <Activity>), so the re-run saw no new error and dropped the pending clear.\n if (showError !== wasError) {\n setWasError(showError);\n if (showError) setIsShaking(true);\n setPendingClear(showError && clearOnError);\n }\n\n useEffect(() => {\n if (!isShaking) return;\n const id = window.setTimeout(() => setIsShaking(false), 400);\n return () => window.clearTimeout(id);\n }, [isShaking]);\n\n useEffect(() => {\n if (!pendingClear || !clearOnError) return;\n const id = window.setTimeout(() => {\n setPendingClear(false);\n commit('');\n inputRefs.current[0]?.focus();\n }, clearErrorDelay);\n return () => window.clearTimeout(id);\n // commit is recreated every render; listing it would restart the delay on each keystroke.\n // oxlint-disable-next-line react-hooks/exhaustive-deps\n }, [pendingClear, clearOnError, clearErrorDelay]);\n\n function commit(next: string) {\n const wasComplete = currentValue.length === length;\n const clipped = filterChars(next, charset).slice(0, length);\n if (formValidator) {\n formValidator.set(clipped);\n }\n onChange?.(clipped);\n // Only fire once per genuinely new completion (going from partial to full), not on every\n // keystroke made while correcting an already-full code.\n if (clipped.length === length && !wasComplete) {\n onComplete?.(clipped);\n }\n }\n\n function setCharAt(index: number, char: string) {\n const chars = currentValue.split('');\n chars[index] = char;\n commit(chars.join(''));\n }\n\n function handleChange(index: number, rawInput: string) {\n if (disabled) return;\n if (rawInput === '') {\n // Box was cleared (e.g. select + delete) — Backspace itself is handled in onKeyDown.\n setCharAt(index, '');\n return;\n }\n\n const filtered = filterChars(rawInput, charset);\n if (!filtered) {\n // Typed an invalid/disallowed character — the controlled `value` re-render discards it.\n return;\n }\n\n // Clicking straight into a box past the contiguous filled prefix (skipping ahead of\n // empty boxes) fills the next expected slot instead, rather than leaving a gap before it\n // that setCharAt/distributeFrom can't represent in a plain string and would silently collapse.\n const targetIndex = Math.min(index, currentValue.length);\n\n if (rawInput.length > 1) {\n // Mobile autofill / SMS suggestions can drop the whole code into one box, bypassing maxLength.\n distributeFrom(targetIndex, filtered);\n return;\n }\n\n setCharAt(targetIndex, filtered);\n if (targetIndex < length - 1) {\n inputRefs.current[targetIndex + 1]?.focus();\n } else {\n inputRefs.current[targetIndex]?.blur();\n }\n }\n\n function distributeFrom(startIndex: number, chars: string) {\n const clean = filterChars(chars, charset);\n if (!clean) return;\n const existing = currentValue.padEnd(length, ' ').split('');\n let cursor = startIndex;\n for (const char of clean) {\n if (cursor >= length) break;\n existing[cursor] = char;\n cursor += 1;\n }\n commit(existing.join('').trimEnd());\n const nextFocus = Math.min(cursor, length - 1);\n inputRefs.current[nextFocus]?.focus();\n if (cursor >= length) {\n inputRefs.current[length - 1]?.blur();\n }\n }\n\n function handlePaste(index: number, event: React.ClipboardEvent<HTMLInputElement>) {\n if (disabled) return;\n const pasted = event.clipboardData.getData('text');\n if (!pasted) return;\n event.preventDefault();\n // Same clamp as handleChange — pasting into a box past the filled prefix starts at the\n // next expected slot instead of leaving an unrepresentable gap before it.\n distributeFrom(Math.min(index, currentValue.length), pasted);\n }\n\n function handleKeyDown(index: number, event: React.KeyboardEvent<HTMLInputElement>) {\n if (disabled) return;\n\n // React's controlled-input onChange never fires when the resulting value is identical to\n // what's already rendered (its value tracker sees no change) — so retyping the exact digit\n // already in a box would otherwise silently do nothing. keydown always fires, so handle that\n // one case here and skip the native edit entirely.\n if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {\n const typed = filterChars(event.key, charset);\n if (typed && currentValue[index] === typed) {\n event.preventDefault();\n setCharAt(index, typed);\n if (index < length - 1) {\n inputRefs.current[index + 1]?.focus();\n } else {\n inputRefs.current[index]?.blur();\n }\n return;\n }\n }\n\n if (event.key === 'Backspace') {\n if (currentValue[index]) {\n setCharAt(index, '');\n return;\n }\n if (index > 0) {\n event.preventDefault();\n setCharAt(index - 1, '');\n inputRefs.current[index - 1]?.focus();\n }\n return;\n }\n if (event.key === 'Delete') {\n if (currentValue[index]) setCharAt(index, '');\n return;\n }\n if (event.key === 'ArrowLeft' && index > 0) {\n event.preventDefault();\n inputRefs.current[index - 1]?.focus();\n return;\n }\n if (event.key === 'ArrowRight' && index < length - 1) {\n event.preventDefault();\n inputRefs.current[index + 1]?.focus();\n }\n }\n\n function handleFocus(event: React.FocusEvent<HTMLInputElement>) {\n event.target.select();\n }\n\n function handleGroupFocus() {\n setIsFocused(true);\n }\n\n function handleGroupBlur(event: React.FocusEvent<HTMLDivElement>) {\n // Auto-advance moves focus between boxes constantly while typing — only treat this as\n // leaving the group once focus actually lands outside it, not on the next box.\n if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;\n setIsFocused(false);\n if (formValidator) formValidator.touched = true;\n }\n\n return (\n <div {...rest} className={cx(styles.otpInput, disabled && styles.otpInputDisabled, className)} style={style}>\n {label && (\n <div className={cx(styles.otpInputLabel, classNames?.label)} style={slotStyles?.label}>\n {label}\n {isRequired && <span className={styles.otpInputRequiredMark}> *</span>}\n </div>\n )}\n <div\n role='group'\n aria-label={label || text.field}\n className={cx(styles.otpInputBoxes, isShaking && styles.otpInputBoxesShake, classNames?.inputs)}\n style={slotStyles?.inputs}\n onFocus={handleGroupFocus}\n onBlur={handleGroupBlur}\n onMouseEnter={() => setIsHovered(true)}\n onMouseLeave={() => setIsHovered(false)}\n >\n {Array.from({ length }, (_, index) => {\n const char = currentValue[index] || '';\n return (\n <div key={index} className={styles.otpInputBoxWrapper}>\n <input\n ref={(el) => {\n inputRefs.current[index] = el;\n }}\n type={masked ? 'password' : 'text'}\n inputMode={charset === OtpInputCharset.Numeric ? 'numeric' : 'text'}\n pattern={charset === OtpInputCharset.Numeric ? '[0-9]*' : undefined}\n autoComplete={index === 0 ? 'one-time-code' : 'off'}\n maxLength={1}\n disabled={disabled}\n value={char}\n aria-label={text.digit(index + 1, length)}\n aria-invalid={showError || undefined}\n className={cx(\n styles.otpInputBox,\n showError && styles.otpInputBoxError,\n char && styles.otpInputBoxFilled,\n classNames?.input,\n )}\n style={slotStyles?.input}\n onChange={(e) => handleChange(index, e.target.value)}\n onKeyDown={(e) => handleKeyDown(index, e)}\n onPaste={(e) => handlePaste(index, e)}\n onFocus={handleFocus}\n />\n {groupAfter.includes(index + 1) && index < length - 1 && (\n <span className={cx(styles.otpInputSeparator, classNames?.separator)} style={slotStyles?.separator} />\n )}\n </div>\n );\n })}\n </div>\n <Tooltip variant='error' message={displayedErrorMessage} isVisible={showError && (isFocused || isHovered)} />\n </div>\n );\n}\n\nexport default OtpInput;\n"],"mappings":"qaAQA,IAAM,EAAa,SACb,EAAkB,eAElB,GAA2C,CAC/C,MAAO,gBACP,OAAQ,EAAU,IAAW,SAAS,EAAS,MAAM,GACvD,EAEA,SAAS,EAAY,EAAa,EAAkC,CAClE,IAAM,EAAK,IAAY,EAAgB,aAAe,EAAkB,EACxE,OAAQ,EAAI,MAAM,CAAE,GAAK,CAAC,EAAA,CAAG,KAAK,EAAE,CACtC,CAEA,SAAS,EAAS,EAAoC,CACpD,GAAM,CACJ,SAAS,EACT,QACA,eAAiB,CAAC,EAClB,iBAAmB,CAAC,EACpB,gBAAgB,KAChB,UAAU,EAAgB,QAC1B,SAAS,GACT,aAAa,CAAC,EACd,QAAQ,GACR,UAAU,GACV,eAAe,GACf,aAAa,GACb,eAAe,GACf,kBAAkB,IAClB,WAAW,GACX,YAAY,GACZ,YAAY,GACZ,QACA,aACA,OAAQ,EACR,SACA,GAAG,GACD,EAAqB,WAAY,CAAK,EACpC,EAAO,EAAU,WAAY,EAAQ,EAAc,EAEnD,GAAgB,EAAiB,EAAc,MAAmB,IAAU,GAC5E,EAAG,GAAe,EAAS,CAAC,EAC5B,CAAC,EAAW,GAAgB,EAAS,EAAK,EAC1C,CAAC,EAAW,GAAgB,EAAS,EAAK,EAC1C,CAAC,EAAW,GAAgB,EAAS,EAAK,EAC1C,CAAC,EAAc,GAAmB,EAAS,EAAK,EAChD,CAAC,EA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,QAAQ,QAAS,EAAuB,UAAW,IAAc,GAAa,EAAa,CAAA,CACzG,GAET"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";import{useComponentDefaults as e}from"../configProvider/useComponentDefaults.mjs";import{usePresentationDefault as t}from"../configProvider/usePresentationDefault.mjs";import{Presentation as n}from"../configProvider/presentation.types.mjs";import r from"../bodyEnd/bodyEnd.mjs";import i from"./popover.module.mjs";import a from"../styles/sheet.module.mjs";import
|
|
1
|
+
"use client";import{useComponentDefaults as e}from"../configProvider/useComponentDefaults.mjs";import{usePresentationDefault as t}from"../configProvider/usePresentationDefault.mjs";import{Presentation as n}from"../configProvider/presentation.types.mjs";import r from"../bodyEnd/bodyEnd.mjs";import i from"./popover.module.mjs";import a from"../styles/sheet.module.mjs";import ee from"../sheetBackdrop/sheetBackdrop.mjs";import{PopoverAlign as te,PopoverPlacement as ne,PopoverTrigger as o}from"./popover.types.mjs";import{usePopoverPosition as re}from"./usePopoverPosition.mjs";import{tabbablesIn as s,useFocusBoundary as ie}from"../hooks/useFocusBoundary.mjs";import ae from"../hooks/useSheet.mjs";import{useOverlay as c}from"../hooks/useOverlay.mjs";import{useCallback as l,useEffect as u,useRef as d,useState as f}from"react";import p from"classnames";import{jsx as m,jsxs as h}from"react/jsx-runtime";var oe=1e3;function g(e,t){return e?{current:e}:t}function _(_){let{children:se=null,anchor:v,content:ce=null,placement:y=ne.Bottom,align:le=te.Center,trigger:b=o.Click,isOpen:x,defaultOpen:ue=!1,onOpenChange:S=()=>{},offset:C=10,withArrow:w=!0,closeOnOutsideClick:T=!0,closeOnEscape:de=!0,openDelay:E=100,closeDelay:fe=120,disabled:D=!1,focusOnOpen:O=`keyboard`,closeOnTriggerClick:pe=!0,width:me=`auto`,constrainWidth:he=!0,presentation:ge,className:_e,style:ve,classNames:k,styles:A,...ye}=e(`Popover`,_),j=d(null),M=d(null),N=d(null),P=d(null),F=d(void 0),I=d(!1),L=d(!1),R=d(!1),z=d(null);function B(){I.current=!0}function be(e){B(),z.current=e.target}let[V,xe]=f(()=>({anchor:v,ref:g(v,j)}));V.anchor!==v&&xe({anchor:v,ref:g(v,j)});let H=V.ref,U=d(null),W=v!==void 0;u(()=>{if(!W)return;function e(e){U.current={target:e.target,keyboard:e.detail===0,time:performance.now()}}return document.addEventListener(`click`,e,!0),()=>document.removeEventListener(`click`,e,!0)},[W]);let G=x!==void 0,[Se,Ce]=f(ue),K=G?x:Se,q=d(S);u(()=>{q.current=S});let J=l((e,t=!1)=>{D&&e||(e&&(R.current=t),G||Ce(e),q.current(e,{fromKeyboard:t}))},[D,G]),we=t(),Te=ge??we??n.Default,{isSheet:Ee,sheetStyle:De}=ae(Te),Y=Ee&&b===o.Click;re({isOpen:!!K&&!Y,placement:y,align:le,offset:C,triggerRef:H,floatingRef:M,panelRef:N,arrowRef:w?P:{current:null},matchTriggerWidth:me===`trigger`});let{restoreFocusToTrigger:X,focusAfterTrigger:Oe}=ie({triggerRef:H,contentRef:M}),Z=d(X);u(()=>{Z.current=X});let Q=d(!1),ke=l(e=>{if(M.current=e,Q.current=!1,e)return()=>{M.current=null;let t=document.activeElement;Q.current=!!t&&(e.contains(t)||t===z.current)}},[]);u(()=>{if(K||!Q.current)return;Q.current=!1;let e=document.activeElement;(!e||e===document.body)&&Z.current()},[K]),c({isActive:!!K,containerRef:N,onEscape:de?()=>{M.current?.contains(document.activeElement)&&X(),J(!1,!0)}:void 0,trapFocus:!1,lockScroll:Y}),u(()=>{if(!K){R.current=!1;return}let e=U.current;U.current=null;let t=!!v&&!!e?.keyboard&&v.contains(e.target)&&performance.now()-e.time<oe;if(!(O===!0||O===`keyboard`&&(R.current||t))||b!==o.Click)return;let n=s(N.current);n.length!==0&&(M.current?.setAttribute(`role`,`dialog`),n[0].focus())},[K,b,O,v]);function Ae(e){if(e.key!==`Tab`||b!==o.Click)return;let t=s(N.current);if(t.length===0)return;let n=document.activeElement;!e.shiftKey&&n===t[t.length-1]?(e.preventDefault(),Oe(),J(!1,!0)):e.shiftKey&&n===t[0]&&(e.preventDefault(),X(),J(!1,!0))}u(()=>{if(!K)return;I.current=!1,L.current=!1;function e(e){return!!(M.current?.contains(e)||j.current?.contains(e)||H.current?.contains(e))}function t(t){let n=I.current;return I.current=!1,n||e(t.target)}function n(e){L.current=!t(e)}function r(e){let n=L.current;L.current=!1,!t(e)&&n&&J(!1)}function i(n){if(t(n))return;let r=n.relatedTarget;r&&(r===z.current||e(r))&&J(!1,!L.current)}return T&&b!==o.Hover&&(window.addEventListener(`mousedown`,n),window.addEventListener(`mouseup`,r),document.addEventListener(`focusin`,i)),()=>{window.removeEventListener(`mousedown`,n),window.removeEventListener(`mouseup`,r),document.removeEventListener(`focusin`,i)}},[K,T,b,J,H]),u(()=>()=>clearTimeout(F.current),[]);function $(e){clearTimeout(F.current),F.current=setTimeout(()=>J(e),e?E:fe)}function je(e){K||e.key!==`ArrowDown`&&e.key!==`ArrowUp`||(e.preventDefault(),J(!0,!0))}let Me=b===o.Click?{onClick:e=>{(!K||pe)&&J(!K,e.detail===0)},onKeyDown:je}:b===o.Hover?{onMouseEnter:()=>$(!0),onMouseLeave:()=>$(!1)}:{onFocus:()=>J(!0),onBlur:()=>J(!1)},Ne=b===o.Hover?{onMouseEnter:()=>$(!0),onMouseLeave:()=>$(!1)}:{};return h(`div`,{...ye,className:p(i.popover,_e,k?.root),style:{...ve,...A?.root},children:[m(`div`,{ref:j,className:p(i.popoverTrigger,k?.trigger),style:A?.trigger,...Me,children:se}),K&&h(r,{children:[Y&&m(ee,{onClose:()=>{T&&J(!1)},className:k?.backdrop,style:A?.backdrop}),h(`div`,{ref:ke,className:p(Y?a.sheet:i.popoverFloating,k?.floating),style:{...Y?De:void 0,...A?.floating},"data-placement":y,onKeyDown:Ae,onMouseDownCapture:B,onMouseUpCapture:B,onFocusCapture:be,...Ne,children:[m(`div`,{ref:N,className:p(i.popoverPanel,he&&i.popoverPanelConstrained,Y&&a.sheetPanel,k?.panel),style:A?.panel,children:ce}),w&&!Y&&m(`div`,{ref:P,className:p(i.popoverArrow,k?.arrow),style:A?.arrow})]})]})]})}export{_ as default};
|
|
2
2
|
//# sourceMappingURL=popover.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"popover.mjs","names":[],"sources":["../../../../package/common/popover/popover.tsx"],"sourcesContent":["import { useRef, useEffect, useState, useCallback, type RefObject } from 'react';\nimport cx from 'classnames';\nimport BodyEnd from 'components/common/bodyEnd';\n\nimport styles from './popover.module.pcss';\nimport sheetStyles from '../styles/sheet.module.pcss';\nimport SheetBackdrop from '../sheetBackdrop';\nimport { usePopoverPosition } from './usePopoverPosition';\nimport { useFocusBoundary, tabbablesIn } from '../hooks/useFocusBoundary';\nimport { useSheet } from '../hooks/useSheet';\nimport { useOverlay } from '../hooks/useOverlay';\nimport { useComponentDefaults, usePresentationDefault } from '../configProvider';\nimport { Presentation } from '../configProvider/presentation.types';\nimport { PopoverPlacement, PopoverAlign, PopoverTrigger, type PopoverProps } from './popover.types';\n\n/**\n * How long after its click an anchored popover still counts as opened by it: long enough for the\n * render the click causes, short enough that an old keypress does not decide a later open.\n */\nconst ACTIVATION_WINDOW_MS = 1000;\n\nfunction toReference(\n anchor: HTMLElement | null | undefined,\n triggerRef: RefObject<HTMLElement | null>,\n): RefObject<HTMLElement | null> {\n return anchor ? { current: anchor } : triggerRef;\n}\n\nfunction Popover(props: PopoverProps) {\n const {\n children = null,\n anchor,\n content = null,\n placement = PopoverPlacement.Bottom,\n align = PopoverAlign.Center,\n trigger = PopoverTrigger.Click,\n isOpen,\n defaultOpen = false,\n onOpenChange = () => {},\n offset = 10,\n withArrow = true,\n closeOnOutsideClick = true,\n closeOnEscape = true,\n openDelay = 100,\n closeDelay = 120,\n disabled = false,\n focusOnOpen = 'keyboard',\n closeOnTriggerClick = true,\n width = 'auto',\n constrainWidth = true,\n presentation: presentationProp,\n className,\n style,\n classNames,\n styles: slotStyles,\n ...rest\n } = useComponentDefaults('Popover', props);\n const triggerRef = useRef<HTMLDivElement>(null);\n const floatingRef = useRef<HTMLDivElement>(null);\n const panelRef = useRef<HTMLDivElement>(null);\n const arrowRef = useRef<HTMLDivElement>(null);\n const hoverTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n // Set from a capture handler on the panel, which React fires for its whole\n // React subtree — including children that portal elsewhere in the DOM, such as\n // a Dropdown's list inside a DatePicker's calendar. A DOM `contains` check\n // cannot see those, and without this the panel closes when one is used.\n const panelInteractedRef = useRef(false);\n // An outside click is a press that starts and ends outside while the panel is open. One that\n // starts inside is a drag, such as selecting a field's text, and Chromium and WebKit send its\n // `mouseup` to wherever it ends. One that started before the panel opened is the gesture that\n // opened it, such as Calendar's drag to create, which opens an editor on `pointerup`.\n const pressStartedOutsideRef = useRef(false);\n // Whether the open that is running came from the keyboard, which is what the\n // default `focusOnOpen` follows and what `onOpenChange` reports. A click raised\n // by Enter or Space reports `detail === 0`, where a pointer press counts the\n // clicks; an open with no trigger event at all, such as a panel that appears\n // while the user types, leaves this false.\n const openedByKeyboardRef = useRef(false);\n function markPanelInteraction() {\n panelInteractedRef.current = true;\n }\n\n // What the panel is placed against, and where the focus goes back to. A new object exactly when\n // `anchor` changes, which is what restarts the position tracking for the new element: state, not\n // a memo, because a memo React chose to drop would restart it for no reason.\n const [reference, setReference] = useState(() => ({ anchor, ref: toReference(anchor, triggerRef) }));\n if (reference.anchor !== anchor) setReference({ anchor, ref: toReference(anchor, triggerRef) });\n const referenceRef = reference.ref;\n\n // An anchored popover is opened by its consumer through `isOpen`, so none of the key handling\n // below sees how. The click that caused it does: Enter and Space raise one with `detail === 0`,\n // the same test the trigger uses. Not `:focus-visible`, which a text field matches after a\n // mouse click too, and which stays on a keyboard-focused button that is then clicked.\n const activationRef = useRef<{ target: Node; keyboard: boolean; time: number } | null>(null);\n const anchored = anchor !== undefined;\n useEffect(() => {\n if (!anchored) return;\n function onClick(event: MouseEvent) {\n activationRef.current = { target: event.target as Node, keyboard: event.detail === 0, time: performance.now() };\n }\n // Capturing, so it is recorded before the consumer's own handler opens the panel.\n document.addEventListener('click', onClick, true);\n return () => document.removeEventListener('click', onClick, true);\n }, [anchored]);\n\n const isControlled = isOpen !== undefined;\n const [internalOpen, setInternalOpen] = useState(defaultOpen);\n const open = isControlled ? isOpen : internalOpen;\n\n // Keep the outside-click/Escape listeners pointed at the latest setter without re-subscribing.\n const onOpenChangeRef = useRef(onOpenChange);\n useEffect(() => {\n onOpenChangeRef.current = onOpenChange;\n });\n\n const setOpen = useCallback(\n (next: boolean, fromKeyboard = false) => {\n if (disabled && next) return;\n if (next) openedByKeyboardRef.current = fromKeyboard;\n if (!isControlled) setInternalOpen(next);\n onOpenChangeRef.current(next, { fromKeyboard });\n },\n [disabled, isControlled],\n );\n\n // Explicit prop → this component's global default → the app-wide one → anchored.\n const appPresentation = usePresentationDefault();\n const presentation = presentationProp ?? appPresentation ?? Presentation.Default;\n const { isSheet: sheetPresentation, sheetStyle } = useSheet(presentation);\n // Hover and focus are pointer affordances that open something small next to what caused them;\n // a sheet is a deliberate, screen-owning open. Only a click asks for one.\n const isSheet = sheetPresentation && trigger === PopoverTrigger.Click;\n\n // A sheet isn't anchored to anything, so there's nothing to track, flip or clamp.\n usePopoverPosition({\n isOpen: !!open && !isSheet,\n placement,\n align,\n offset,\n triggerRef: referenceRef,\n floatingRef,\n panelRef,\n arrowRef: withArrow ? arrowRef : { current: null },\n matchTriggerWidth: width === 'trigger',\n });\n\n // Registered for as long as it's open, not just as a sheet: this is what puts the popover on\n // the overlay stack, so an enclosing Modal knows something sits above it and neither drags\n // focus out of this (portaled, so outside the modal's panel) panel nor closes itself on the\n // Escape meant for this. Focus isn't trapped: a Popover is deliberately non-modal, and it\n // already moves focus into the panel on open by itself.\n const { restoreFocusToTrigger, focusAfterTrigger } = useFocusBoundary({\n triggerRef: referenceRef,\n contentRef: floatingRef,\n });\n\n useOverlay({\n isActive: !!open,\n containerRef: panelRef,\n onEscape: closeOnEscape\n ? () => {\n // Hand focus back to the trigger when it currently sits inside the panel.\n if (floatingRef.current?.contains(document.activeElement)) restoreFocusToTrigger();\n setOpen(false, true);\n }\n : undefined,\n trapFocus: false,\n lockScroll: isSheet,\n });\n\n // The panel is portaled to the end of the DOM, so Tab never flows into it naturally. When we\n // manage focus (click trigger + focusable content), move focus in on open and, on Tab out of\n // either end, close and continue focus as if the panel sat right after the trigger.\n useEffect(() => {\n if (!open) {\n openedByKeyboardRef.current = false;\n return;\n }\n const activation = activationRef.current;\n activationRef.current = null;\n const anchorKeyed =\n !!anchor &&\n !!activation?.keyboard &&\n anchor.contains(activation.target) &&\n performance.now() - activation.time < ACTIVATION_WINDOW_MS;\n const takeFocus =\n focusOnOpen === true || (focusOnOpen === 'keyboard' && (openedByKeyboardRef.current || anchorKeyed));\n if (!takeFocus || trigger !== PopoverTrigger.Click) return;\n const focusables = tabbablesIn(panelRef.current);\n if (focusables.length === 0) return;\n // Only claim the dialog role when we're actually managing focus for real content.\n floatingRef.current?.setAttribute('role', 'dialog');\n focusables[0].focus();\n }, [open, trigger, focusOnOpen, anchor]);\n\n function handleFloatingKeyDown(event: React.KeyboardEvent) {\n if (event.key !== 'Tab' || trigger !== PopoverTrigger.Click) return;\n const focusables = tabbablesIn(panelRef.current);\n if (focusables.length === 0) return;\n const active = document.activeElement;\n if (!event.shiftKey && active === focusables[focusables.length - 1]) {\n event.preventDefault();\n focusAfterTrigger();\n setOpen(false, true);\n } else if (event.shiftKey && active === focusables[0]) {\n event.preventDefault();\n restoreFocusToTrigger();\n setOpen(false, true);\n }\n }\n\n // Outside click. Registered only while open and only for the relevant trigger mode; Escape is\n // handled by `useOverlay` above, which scopes it to the innermost open layer.\n useEffect(() => {\n if (!open) return;\n // Focus that landed in the panel before these listeners existed (ours on open, or content\n // that focuses itself on mount) set the flag with nothing to clear it, and the first\n // click outside was swallowed.\n panelInteractedRef.current = false;\n pressStartedOutsideRef.current = false;\n\n function isInside(event: Event) {\n // Read and clear: the flag describes this one event, and the panel's React\n // handler has already run by the time this does.\n const inPanelSubtree = panelInteractedRef.current;\n panelInteractedRef.current = false;\n const target = event.target as Node;\n const inPanel = floatingRef.current?.contains(target);\n // Both: with an anchor, `children` still toggle the panel, and a press on them is theirs.\n const inTrigger = triggerRef.current?.contains(target) || referenceRef.current?.contains(target);\n return Boolean(inPanelSubtree || inPanel || inTrigger);\n }\n function onMouseDown(event: MouseEvent) {\n pressStartedOutsideRef.current = !isInside(event);\n }\n function onMouseUp(event: MouseEvent) {\n const pressStartedOutside = pressStartedOutsideRef.current;\n pressStartedOutsideRef.current = false;\n if (!isInside(event) && pressStartedOutside) setOpen(false);\n }\n // Keyboard counterpart to the outside click: once focus leaves both the trigger\n // and the (portaled) panel — e.g. tabbing on to the next element — close.\n function onFocusIn(event: FocusEvent) {\n if (!isInside(event)) setOpen(false, true);\n }\n\n if (closeOnOutsideClick && trigger !== PopoverTrigger.Hover) {\n window.addEventListener('mousedown', onMouseDown);\n window.addEventListener('mouseup', onMouseUp);\n document.addEventListener('focusin', onFocusIn);\n }\n return () => {\n window.removeEventListener('mousedown', onMouseDown);\n window.removeEventListener('mouseup', onMouseUp);\n document.removeEventListener('focusin', onFocusIn);\n };\n }, [open, closeOnOutsideClick, trigger, setOpen, referenceRef]);\n\n useEffect(() => () => clearTimeout(hoverTimer.current), []);\n\n function scheduleHover(next: boolean) {\n clearTimeout(hoverTimer.current);\n hoverTimer.current = setTimeout(() => setOpen(next), next ? openDelay : closeDelay);\n }\n\n // Opening from the keyboard without the trigger having to be a button that\n // happens to toggle on Enter: the arrow keys are what the menu-button pattern\n // asks for, and what a consumer reaches for first.\n function handleTriggerKeyDown(event: React.KeyboardEvent) {\n if (open || (event.key !== 'ArrowDown' && event.key !== 'ArrowUp')) return;\n event.preventDefault();\n setOpen(true, true);\n }\n\n const triggerHandlers =\n trigger === PopoverTrigger.Click\n ? {\n onClick: (event: React.MouseEvent) => {\n // A field that opens a picker keeps it open when clicked again, so\n // that placing the caret in the field does not close the panel.\n if (open && !closeOnTriggerClick) return;\n setOpen(!open, event.detail === 0);\n },\n onKeyDown: handleTriggerKeyDown,\n }\n : trigger === PopoverTrigger.Hover\n ? { onMouseEnter: () => scheduleHover(true), onMouseLeave: () => scheduleHover(false) }\n : { onFocus: () => setOpen(true), onBlur: () => setOpen(false) };\n\n const floatingHoverHandlers =\n trigger === PopoverTrigger.Hover\n ? { onMouseEnter: () => scheduleHover(true), onMouseLeave: () => scheduleHover(false) }\n : {};\n\n return (\n <div\n {...rest}\n className={cx(styles.popover, className, classNames?.root)}\n style={{ ...style, ...slotStyles?.root }}\n >\n <div\n ref={triggerRef}\n className={cx(styles.popoverTrigger, classNames?.trigger)}\n style={slotStyles?.trigger}\n {...triggerHandlers}\n >\n {children}\n </div>\n {open && (\n <BodyEnd>\n {isSheet && (\n <SheetBackdrop\n onClose={() => {\n if (closeOnOutsideClick) setOpen(false);\n }}\n className={classNames?.backdrop}\n style={slotStyles?.backdrop}\n />\n )}\n <div\n ref={floatingRef}\n className={cx(isSheet ? sheetStyles.sheet : styles.popoverFloating, classNames?.floating)}\n style={{ ...(isSheet ? sheetStyle : undefined), ...slotStyles?.floating }}\n data-placement={placement}\n onKeyDown={handleFloatingKeyDown}\n onMouseDownCapture={markPanelInteraction}\n onMouseUpCapture={markPanelInteraction}\n onFocusCapture={markPanelInteraction}\n {...floatingHoverHandlers}\n >\n <div\n ref={panelRef}\n className={cx(\n styles.popoverPanel,\n constrainWidth && styles.popoverPanelConstrained,\n isSheet && sheetStyles.sheetPanel,\n classNames?.panel,\n )}\n style={slotStyles?.panel}\n >\n {content}\n </div>\n {withArrow && !isSheet && (\n <div ref={arrowRef} className={cx(styles.popoverArrow, classNames?.arrow)} style={slotStyles?.arrow} />\n )}\n </div>\n </BodyEnd>\n )}\n </div>\n );\n}\n\nexport default Popover;\n"],"mappings":"w4BAmBA,IAAM,GAAuB,IAE7B,SAAS,EACP,EACA,EAC+B,CAC/B,OAAO,EAAS,CAAE,QAAS,CAAO,EAAI,CACxC,CAEA,SA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AAiB,GAAY,QAAQ,EACxF,MAAO,CAAE,GAAI,EAAU,GAAa,IAAA,GAAY,GAAG,GAAY,QAAS,EACxE,iBAAgB,EAChB,UAAW,GACX,mBAAoB,EACpB,iBAAkB,EAClB,eAAgB,EAChB,GAAI,GATN,SAAA,CAWE,EAAC,MAAD,CACE,IAAK,EACL,UAAW,EACT,EAAO,aACP,IAAkB,EAAO,wBACzB,GAAW,EAAY,WACvB,GAAY,KACd,EACA,MAAO,GAAY,MAElB,SAAA,CACE,CAAA,EACJ,GAAa,CAAC,GACb,EAAC,MAAD,CAAK,IAAK,EAAU,UAAW,EAAG,EAAO,aAAc,GAAY,KAAK,EAAG,MAAO,GAAY,KAAQ,CAAA,CAErG,CACE,CAAA,CAAA,CAAA,CAAA,CAER,GAET"}
|
|
1
|
+
{"version":3,"file":"popover.mjs","names":[],"sources":["../../../../package/common/popover/popover.tsx"],"sourcesContent":["import { useRef, useEffect, useState, useCallback, type RefObject } from 'react';\nimport cx from 'classnames';\nimport BodyEnd from 'components/common/bodyEnd';\n\nimport styles from './popover.module.pcss';\nimport sheetStyles from '../styles/sheet.module.pcss';\nimport SheetBackdrop from '../sheetBackdrop';\nimport { usePopoverPosition } from './usePopoverPosition';\nimport { useFocusBoundary, tabbablesIn } from '../hooks/useFocusBoundary';\nimport { useSheet } from '../hooks/useSheet';\nimport { useOverlay } from '../hooks/useOverlay';\nimport { useComponentDefaults, usePresentationDefault } from '../configProvider';\nimport { Presentation } from '../configProvider/presentation.types';\nimport { PopoverPlacement, PopoverAlign, PopoverTrigger, type PopoverProps } from './popover.types';\n\n/**\n * How long after its click an anchored popover still counts as opened by it: long enough for the\n * render the click causes, short enough that an old keypress does not decide a later open.\n */\nconst ACTIVATION_WINDOW_MS = 1000;\n\nfunction toReference(\n anchor: HTMLElement | null | undefined,\n triggerRef: RefObject<HTMLElement | null>,\n): RefObject<HTMLElement | null> {\n return anchor ? { current: anchor } : triggerRef;\n}\n\nfunction Popover(props: PopoverProps) {\n const {\n children = null,\n anchor,\n content = null,\n placement = PopoverPlacement.Bottom,\n align = PopoverAlign.Center,\n trigger = PopoverTrigger.Click,\n isOpen,\n defaultOpen = false,\n onOpenChange = () => {},\n offset = 10,\n withArrow = true,\n closeOnOutsideClick = true,\n closeOnEscape = true,\n openDelay = 100,\n closeDelay = 120,\n disabled = false,\n focusOnOpen = 'keyboard',\n closeOnTriggerClick = true,\n width = 'auto',\n constrainWidth = true,\n presentation: presentationProp,\n className,\n style,\n classNames,\n styles: slotStyles,\n ...rest\n } = useComponentDefaults('Popover', props);\n const triggerRef = useRef<HTMLDivElement>(null);\n const floatingRef = useRef<HTMLDivElement>(null);\n const panelRef = useRef<HTMLDivElement>(null);\n const arrowRef = useRef<HTMLDivElement>(null);\n const hoverTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n // Set from a capture handler on the panel, which React fires for its whole\n // React subtree — including children that portal elsewhere in the DOM, such as\n // a Dropdown's list inside a DatePicker's calendar. A DOM `contains` check\n // cannot see those, and without this the panel closes when one is used.\n const panelInteractedRef = useRef(false);\n // An outside click is a press that starts and ends outside while the panel is open. One that\n // starts inside is a drag, such as selecting a field's text, and Chromium and WebKit send its\n // `mouseup` to wherever it ends. One that started before the panel opened is the gesture that\n // opened it, such as Calendar's drag to create, which opens an editor on `pointerup`.\n const pressStartedOutsideRef = useRef(false);\n // Whether the open that is running came from the keyboard, which is what the\n // default `focusOnOpen` follows and what `onOpenChange` reports. A click raised\n // by Enter or Space reports `detail === 0`, where a pointer press counts the\n // clicks; an open with no trigger event at all, such as a panel that appears\n // while the user types, leaves this false.\n const openedByKeyboardRef = useRef(false);\n // A nested portal sits outside the panel's DOM; this is how focus leaving one counts as leaving.\n const lastPanelFocusRef = useRef<EventTarget | null>(null);\n function markPanelInteraction() {\n panelInteractedRef.current = true;\n }\n function markPanelFocus(event: React.FocusEvent) {\n markPanelInteraction();\n lastPanelFocusRef.current = event.target;\n }\n\n // What the panel is placed against, and where the focus goes back to. A new object exactly when\n // `anchor` changes, which is what restarts the position tracking for the new element: state, not\n // a memo, because a memo React chose to drop would restart it for no reason.\n const [reference, setReference] = useState(() => ({ anchor, ref: toReference(anchor, triggerRef) }));\n if (reference.anchor !== anchor) setReference({ anchor, ref: toReference(anchor, triggerRef) });\n const referenceRef = reference.ref;\n\n // An anchored popover is opened by its consumer through `isOpen`, so none of the key handling\n // below sees how. The click that caused it does: Enter and Space raise one with `detail === 0`,\n // the same test the trigger uses. Not `:focus-visible`, which a text field matches after a\n // mouse click too, and which stays on a keyboard-focused button that is then clicked.\n const activationRef = useRef<{ target: Node; keyboard: boolean; time: number } | null>(null);\n const anchored = anchor !== undefined;\n useEffect(() => {\n if (!anchored) return;\n function onClick(event: MouseEvent) {\n activationRef.current = { target: event.target as Node, keyboard: event.detail === 0, time: performance.now() };\n }\n // Capturing, so it is recorded before the consumer's own handler opens the panel.\n document.addEventListener('click', onClick, true);\n return () => document.removeEventListener('click', onClick, true);\n }, [anchored]);\n\n const isControlled = isOpen !== undefined;\n const [internalOpen, setInternalOpen] = useState(defaultOpen);\n const open = isControlled ? isOpen : internalOpen;\n\n // Keep the outside-click/Escape listeners pointed at the latest setter without re-subscribing.\n const onOpenChangeRef = useRef(onOpenChange);\n useEffect(() => {\n onOpenChangeRef.current = onOpenChange;\n });\n\n const setOpen = useCallback(\n (next: boolean, fromKeyboard = false) => {\n if (disabled && next) return;\n if (next) openedByKeyboardRef.current = fromKeyboard;\n if (!isControlled) setInternalOpen(next);\n onOpenChangeRef.current(next, { fromKeyboard });\n },\n [disabled, isControlled],\n );\n\n // Explicit prop → this component's global default → the app-wide one → anchored.\n const appPresentation = usePresentationDefault();\n const presentation = presentationProp ?? appPresentation ?? Presentation.Default;\n const { isSheet: sheetPresentation, sheetStyle } = useSheet(presentation);\n // Hover and focus are pointer affordances that open something small next to what caused them;\n // a sheet is a deliberate, screen-owning open. Only a click asks for one.\n const isSheet = sheetPresentation && trigger === PopoverTrigger.Click;\n\n // A sheet isn't anchored to anything, so there's nothing to track, flip or clamp.\n usePopoverPosition({\n isOpen: !!open && !isSheet,\n placement,\n align,\n offset,\n triggerRef: referenceRef,\n floatingRef,\n panelRef,\n arrowRef: withArrow ? arrowRef : { current: null },\n matchTriggerWidth: width === 'trigger',\n });\n\n // Registered for as long as it's open, not just as a sheet: this is what puts the popover on\n // the overlay stack, so an enclosing Modal knows something sits above it and neither drags\n // focus out of this (portaled, so outside the modal's panel) panel nor closes itself on the\n // Escape meant for this. Focus isn't trapped: a Popover is deliberately non-modal, and it\n // already moves focus into the panel on open by itself.\n const { restoreFocusToTrigger, focusAfterTrigger } = useFocusBoundary({\n triggerRef: referenceRef,\n contentRef: floatingRef,\n });\n const restoreFocusRef = useRef(restoreFocusToTrigger);\n useEffect(() => {\n restoreFocusRef.current = restoreFocusToTrigger;\n });\n\n // Focus inside the panel returns to the trigger however it closes, as with `hidePopover()`. Read\n // in a ref cleanup, while the panel is still in the DOM; moved in an effect, because StrictMode\n // detaches a new panel's refs once more right after it took the focus.\n const focusLeftWithPanelRef = useRef(false);\n const floatingCallbackRef = useCallback((node: HTMLDivElement | null) => {\n floatingRef.current = node;\n focusLeftWithPanelRef.current = false;\n if (!node) return;\n return () => {\n floatingRef.current = null;\n const active = document.activeElement;\n focusLeftWithPanelRef.current = !!active && (node.contains(active) || active === lastPanelFocusRef.current);\n };\n }, []);\n useEffect(() => {\n if (open || !focusLeftWithPanelRef.current) return;\n focusLeftWithPanelRef.current = false;\n const active = document.activeElement;\n if (!active || active === document.body) restoreFocusRef.current();\n }, [open]);\n\n useOverlay({\n isActive: !!open,\n containerRef: panelRef,\n onEscape: closeOnEscape\n ? () => {\n // Hand focus back to the trigger when it currently sits inside the panel.\n if (floatingRef.current?.contains(document.activeElement)) restoreFocusToTrigger();\n setOpen(false, true);\n }\n : undefined,\n trapFocus: false,\n lockScroll: isSheet,\n });\n\n // The panel is portaled to the end of the DOM, so Tab never flows into it naturally. When we\n // manage focus (click trigger + focusable content), move focus in on open and, on Tab out of\n // either end, close and continue focus as if the panel sat right after the trigger.\n useEffect(() => {\n if (!open) {\n openedByKeyboardRef.current = false;\n return;\n }\n const activation = activationRef.current;\n activationRef.current = null;\n const anchorKeyed =\n !!anchor &&\n !!activation?.keyboard &&\n anchor.contains(activation.target) &&\n performance.now() - activation.time < ACTIVATION_WINDOW_MS;\n const takeFocus =\n focusOnOpen === true || (focusOnOpen === 'keyboard' && (openedByKeyboardRef.current || anchorKeyed));\n if (!takeFocus || trigger !== PopoverTrigger.Click) return;\n const focusables = tabbablesIn(panelRef.current);\n if (focusables.length === 0) return;\n // Only claim the dialog role when we're actually managing focus for real content.\n floatingRef.current?.setAttribute('role', 'dialog');\n focusables[0].focus();\n }, [open, trigger, focusOnOpen, anchor]);\n\n function handleFloatingKeyDown(event: React.KeyboardEvent) {\n if (event.key !== 'Tab' || trigger !== PopoverTrigger.Click) return;\n const focusables = tabbablesIn(panelRef.current);\n if (focusables.length === 0) return;\n const active = document.activeElement;\n if (!event.shiftKey && active === focusables[focusables.length - 1]) {\n event.preventDefault();\n focusAfterTrigger();\n setOpen(false, true);\n } else if (event.shiftKey && active === focusables[0]) {\n event.preventDefault();\n restoreFocusToTrigger();\n setOpen(false, true);\n }\n }\n\n // Outside click. Registered only while open and only for the relevant trigger mode; Escape is\n // handled by `useOverlay` above, which scopes it to the innermost open layer.\n useEffect(() => {\n if (!open) return;\n // Focus that landed in the panel before these listeners existed (ours on open, or content\n // that focuses itself on mount) set the flag with nothing to clear it, and the first\n // click outside was swallowed.\n panelInteractedRef.current = false;\n pressStartedOutsideRef.current = false;\n\n function containsNode(node: Node) {\n // Both trigger refs: with an anchor, `children` still toggle the panel, and a press on them is theirs.\n return Boolean(\n floatingRef.current?.contains(node) ||\n triggerRef.current?.contains(node) ||\n referenceRef.current?.contains(node),\n );\n }\n function isInside(event: Event) {\n // Read and clear: the flag describes this one event, and the panel's React\n // handler has already run by the time this does.\n const inPanelSubtree = panelInteractedRef.current;\n panelInteractedRef.current = false;\n return inPanelSubtree || containsNode(event.target as Node);\n }\n function onMouseDown(event: MouseEvent) {\n pressStartedOutsideRef.current = !isInside(event);\n }\n function onMouseUp(event: MouseEvent) {\n const pressStartedOutside = pressStartedOutsideRef.current;\n pressStartedOutsideRef.current = false;\n if (!isInside(event) && pressStartedOutside) setOpen(false);\n }\n // Keyboard counterpart to the outside click. Only focus that comes from inside closes it: code\n // moving focus elsewhere (a Modal restoring it) must not, nor `null`, focus back from another tab.\n function onFocusIn(event: FocusEvent) {\n if (isInside(event)) return;\n const from = event.relatedTarget as Node | null;\n if (!from || (from !== lastPanelFocusRef.current && !containsNode(from))) return;\n // A press on an outside field focuses it before its `mouseup`, and that is not the keyboard.\n setOpen(false, !pressStartedOutsideRef.current);\n }\n\n if (closeOnOutsideClick && trigger !== PopoverTrigger.Hover) {\n window.addEventListener('mousedown', onMouseDown);\n window.addEventListener('mouseup', onMouseUp);\n document.addEventListener('focusin', onFocusIn);\n }\n return () => {\n window.removeEventListener('mousedown', onMouseDown);\n window.removeEventListener('mouseup', onMouseUp);\n document.removeEventListener('focusin', onFocusIn);\n };\n }, [open, closeOnOutsideClick, trigger, setOpen, referenceRef]);\n\n useEffect(() => () => clearTimeout(hoverTimer.current), []);\n\n function scheduleHover(next: boolean) {\n clearTimeout(hoverTimer.current);\n hoverTimer.current = setTimeout(() => setOpen(next), next ? openDelay : closeDelay);\n }\n\n // Opening from the keyboard without the trigger having to be a button that\n // happens to toggle on Enter: the arrow keys are what the menu-button pattern\n // asks for, and what a consumer reaches for first.\n function handleTriggerKeyDown(event: React.KeyboardEvent) {\n if (open || (event.key !== 'ArrowDown' && event.key !== 'ArrowUp')) return;\n event.preventDefault();\n setOpen(true, true);\n }\n\n const triggerHandlers =\n trigger === PopoverTrigger.Click\n ? {\n onClick: (event: React.MouseEvent) => {\n // A field that opens a picker keeps it open when clicked again, so\n // that placing the caret in the field does not close the panel.\n if (open && !closeOnTriggerClick) return;\n setOpen(!open, event.detail === 0);\n },\n onKeyDown: handleTriggerKeyDown,\n }\n : trigger === PopoverTrigger.Hover\n ? { onMouseEnter: () => scheduleHover(true), onMouseLeave: () => scheduleHover(false) }\n : { onFocus: () => setOpen(true), onBlur: () => setOpen(false) };\n\n const floatingHoverHandlers =\n trigger === PopoverTrigger.Hover\n ? { onMouseEnter: () => scheduleHover(true), onMouseLeave: () => scheduleHover(false) }\n : {};\n\n return (\n <div\n {...rest}\n className={cx(styles.popover, className, classNames?.root)}\n style={{ ...style, ...slotStyles?.root }}\n >\n <div\n ref={triggerRef}\n className={cx(styles.popoverTrigger, classNames?.trigger)}\n style={slotStyles?.trigger}\n {...triggerHandlers}\n >\n {children}\n </div>\n {open && (\n <BodyEnd>\n {isSheet && (\n <SheetBackdrop\n onClose={() => {\n if (closeOnOutsideClick) setOpen(false);\n }}\n className={classNames?.backdrop}\n style={slotStyles?.backdrop}\n />\n )}\n <div\n ref={floatingCallbackRef}\n className={cx(isSheet ? sheetStyles.sheet : styles.popoverFloating, classNames?.floating)}\n style={{ ...(isSheet ? sheetStyle : undefined), ...slotStyles?.floating }}\n data-placement={placement}\n onKeyDown={handleFloatingKeyDown}\n onMouseDownCapture={markPanelInteraction}\n onMouseUpCapture={markPanelInteraction}\n onFocusCapture={markPanelFocus}\n {...floatingHoverHandlers}\n >\n <div\n ref={panelRef}\n className={cx(\n styles.popoverPanel,\n constrainWidth && styles.popoverPanelConstrained,\n isSheet && sheetStyles.sheetPanel,\n classNames?.panel,\n )}\n style={slotStyles?.panel}\n >\n {content}\n </div>\n {withArrow && !isSheet && (\n <div ref={arrowRef} className={cx(styles.popoverArrow, classNames?.arrow)} style={slotStyles?.arrow} />\n )}\n </div>\n </BodyEnd>\n )}\n </div>\n );\n}\n\nexport default Popover;\n"],"mappings":"y4BAmBA,IAAM,GAAuB,IAE7B,SAAS,EACP,EACA,EAC+B,CAC/B,OAAO,EAAS,CAAE,QAAS,CAAO,EAAI,CACxC,CAEA,SAAS,EAAQ,EAAqB,CACpC,GAAM,CACJ,YAAW,K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,CAAE,EACpF,CAAE,YAAe,EAAQ,EAAI,EAAG,WAAc,EAAQ,EAAK,CAAE,EAE/D,GACJ,IAAY,EAAe,MACvB,CAAE,iBAAoB,EAAc,EAAI,EAAG,iBAAoB,EAAc,EAAK,CAAE,EACpF,CAAC,EAEP,OACE,EAAC,MAAD,CACE,GAAI,GACJ,UAAW,EAAG,EAAO,QAAS,GAAW,GAAY,IAAI,EACzD,MAAO,CAAE,GAAG,GAAO,GAAG,GAAY,IAAK,EAHzC,SAAA,CAKE,EAAC,MAAD,CACE,IAAK,EACL,UAAW,EAAG,EAAO,eAAgB,GAAY,OAAO,EACxD,MAAO,GAAY,QACnB,GAAI,GAEH,WACE,CAAA,EACJ,GACC,EAAC,EAAD,CAAA,SAAA,CACG,GACC,EAAC,GAAD,CACE,YAAe,CACT,GAAqB,EAAQ,EAAK,CACxC,EACA,UAAW,GAAY,SACvB,MAAO,GAAY,QACpB,CAAA,EAEH,EAAC,MAAD,CACE,IAAK,GACL,UAAW,EAAG,EAAU,EAAY,MAAQ,EAAO,gBAAiB,GAAY,QAAQ,EACxF,MAAO,CAAE,GAAI,EAAU,GAAa,IAAA,GAAY,GAAG,GAAY,QAAS,EACxE,iBAAgB,EAChB,UAAW,GACX,mBAAoB,EACpB,iBAAkB,EAClB,eAAgB,GAChB,GAAI,GATN,SAAA,CAWE,EAAC,MAAD,CACE,IAAK,EACL,UAAW,EACT,EAAO,aACP,IAAkB,EAAO,wBACzB,GAAW,EAAY,WACvB,GAAY,KACd,EACA,MAAO,GAAY,MAElB,SAAA,EACE,CAAA,EACJ,GAAa,CAAC,GACb,EAAC,MAAD,CAAK,IAAK,EAAU,UAAW,EAAG,EAAO,aAAc,GAAY,KAAK,EAAG,MAAO,GAAY,KAAQ,CAAA,CAErG,CACE,CAAA,CAAA,CAAA,CAAA,CAER,GAET"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"popover.types.mjs","names":[],"sources":["../../../../package/common/popover/popover.types.ts"],"sourcesContent":["import type { CSSProperties, ReactNode } from 'react';\nimport type { SlotClassNames, SlotStyles, HtmlProps } from '../types/slots.types';\nimport type { Presentation } from '../configProvider/presentation.types';\n\n/** Preferred side of the trigger the panel opens on. Flips to the opposite side when there's no room. */\nexport enum PopoverPlacement {\n Top = 'top',\n Bottom = 'bottom',\n Left = 'left',\n Right = 'right',\n}\n\n/** Alignment along the trigger's cross axis (horizontal for top/bottom, vertical for left/right). */\nexport enum PopoverAlign {\n Start = 'start',\n Center = 'center',\n End = 'end',\n}\n\n/** What opens the popover. */\nexport enum PopoverTrigger {\n Click = 'click',\n Hover = 'hover',\n Focus = 'focus',\n}\n\nexport type PopoverSlots = 'root' | 'trigger' | 'floating' | 'panel' | 'arrow' | 'backdrop';\n\nexport interface PopoverProps extends Omit<HtmlProps, 'content'> {\n /** The trigger element. */\n children?: ReactNode;\n /**\n * Place the panel against this element instead of `children`, for one Popover does not wrap.\n * Open it with `isOpen`; `null` falls back to `children`.\n */\n anchor?: HTMLElement | null;\n /** The popover body. */\n content?: ReactNode;\n /** Preferred side (default `Bottom`). */\n placement?: PopoverPlacement;\n /** Cross-axis alignment (default `Center`). */\n align?: PopoverAlign;\n /** What opens the popover (default `Click`). */\n trigger?: PopoverTrigger;\n /** Controlled open state. Omit for uncontrolled. */\n isOpen?: boolean;\n /** Initial open state when uncontrolled (default `false`). */\n defaultOpen?: boolean;\n /**\n * Fires whenever the popover wants to open or close. `fromKeyboard` says\n * whether a key caused it, which is what a menu needs in order to put the\n * focus on an entry only when the pointer was not what opened it.\n */\n onOpenChange?: (isOpen: boolean, meta: { fromKeyboard: boolean }) => void;\n /** Gap in px between trigger and panel (default `10`). */\n offset?: number;\n /** Render the arrow pointing at the trigger (default `true`). */\n withArrow?: boolean;\n /** Close
|
|
1
|
+
{"version":3,"file":"popover.types.mjs","names":[],"sources":["../../../../package/common/popover/popover.types.ts"],"sourcesContent":["import type { CSSProperties, ReactNode } from 'react';\nimport type { SlotClassNames, SlotStyles, HtmlProps } from '../types/slots.types';\nimport type { Presentation } from '../configProvider/presentation.types';\n\n/** Preferred side of the trigger the panel opens on. Flips to the opposite side when there's no room. */\nexport enum PopoverPlacement {\n Top = 'top',\n Bottom = 'bottom',\n Left = 'left',\n Right = 'right',\n}\n\n/** Alignment along the trigger's cross axis (horizontal for top/bottom, vertical for left/right). */\nexport enum PopoverAlign {\n Start = 'start',\n Center = 'center',\n End = 'end',\n}\n\n/** What opens the popover. */\nexport enum PopoverTrigger {\n Click = 'click',\n Hover = 'hover',\n Focus = 'focus',\n}\n\nexport type PopoverSlots = 'root' | 'trigger' | 'floating' | 'panel' | 'arrow' | 'backdrop';\n\nexport interface PopoverProps extends Omit<HtmlProps, 'content'> {\n /** The trigger element. */\n children?: ReactNode;\n /**\n * Place the panel against this element instead of `children`, for one Popover does not wrap.\n * Open it with `isOpen`; `null` falls back to `children`.\n */\n anchor?: HTMLElement | null;\n /** The popover body. */\n content?: ReactNode;\n /** Preferred side (default `Bottom`). */\n placement?: PopoverPlacement;\n /** Cross-axis alignment (default `Center`). */\n align?: PopoverAlign;\n /** What opens the popover (default `Click`). */\n trigger?: PopoverTrigger;\n /** Controlled open state. Omit for uncontrolled. */\n isOpen?: boolean;\n /** Initial open state when uncontrolled (default `false`). */\n defaultOpen?: boolean;\n /**\n * Fires whenever the popover wants to open or close. `fromKeyboard` says\n * whether a key caused it, which is what a menu needs in order to put the\n * focus on an entry only when the pointer was not what opened it.\n */\n onOpenChange?: (isOpen: boolean, meta: { fromKeyboard: boolean }) => void;\n /** Gap in px between trigger and panel (default `10`). */\n offset?: number;\n /** Render the arrow pointing at the trigger (default `true`). */\n withArrow?: boolean;\n /** Close on a click outside, or when focus leaves the trigger and panel (default `true`). */\n closeOnOutsideClick?: boolean;\n /** Close when pressing Escape (default `true`). */\n closeOnEscape?: boolean;\n /** Delay in ms before a hover-triggered popover opens (default `100`). */\n openDelay?: number;\n /** Delay in ms before a hover-triggered popover closes (default `120`). */\n closeDelay?: number;\n /** Prevent the popover from opening. */\n disabled?: boolean;\n /**\n * Move focus into the panel when it opens, and claim `role=\"dialog\"` with it.\n * `'keyboard'` (the default) does it only when the open came from the\n * keyboard: the panel is portaled to the end of the document, so Tab never\n * reaches it on its own, while a click leaves the focus where the pointer\n * already put it. `true` always, `false` never.\n */\n focusOnOpen?: boolean | 'keyboard';\n /**\n * Whether clicking the trigger while the panel is open closes it (default\n * `true`). A menu button should toggle; a text field that opens a picker\n * should not, or clicking into it to place the caret would close the panel.\n */\n closeOnTriggerClick?: boolean;\n /**\n * `'trigger'` gives the panel at least the trigger's width, for a list that\n * should line up with the field it belongs to. `'auto'` (the default) lets it\n * size to its own content.\n */\n width?: 'auto' | 'trigger';\n /**\n * Cap the panel at a readable measure (default `true`). Off for a panel with\n * its own width, a calendar or a media grid.\n */\n constrainWidth?: boolean;\n /** Where the panel opens: anchored to the trigger (`Default`), pinned to the bottom of the\n * screen, or the latter only on a small touch screen. Only a `Click` trigger presents as a\n * sheet. */\n presentation?: Presentation;\n\n className?: string;\n style?: CSSProperties;\n classNames?: SlotClassNames<PopoverSlots>;\n styles?: SlotStyles<PopoverSlots>;\n}\n"],"mappings":"aAKA,IAAY,EAAL,SAAA,EAAA,OACL,GAAA,IAAA,MACA,EAAA,OAAA,SACA,EAAA,KAAA,OACA,EAAA,MAAA,SACF,EAAA,CAAA,CAAA,EAGY,EAAL,SAAA,EAAA,OACL,GAAA,MAAA,QACA,EAAA,OAAA,SACA,EAAA,IAAA,OACF,EAAA,CAAA,CAAA,EAGY,EAAL,SAAA,EAAA,OACL,GAAA,MAAA,QACA,EAAA,MAAA,QACA,EAAA,MAAA,SACF,EAAA,CAAA,CAAA"}
|