@webority/mobile-ui 0.12.0 → 0.13.0
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/lib/commonjs/components/BottomNavigation/BottomNavigation.js +1 -1
- package/lib/commonjs/components/BottomSheet/BottomSheet.js +1 -1
- package/lib/commonjs/components/Card/Card.js +1 -1
- package/lib/commonjs/components/DatePicker/DatePicker.js +1 -1
- package/lib/commonjs/components/DateRangePicker/DateRangePicker.js +1 -1
- package/lib/commonjs/components/DecimalInput/DecimalInput.js +1 -1
- package/lib/commonjs/components/DecimalInput/index.js +1 -1
- package/lib/commonjs/components/Input/Input.js +1 -1
- package/lib/commonjs/components/LoaderOverlay/LoaderOverlay.js +1 -1
- package/lib/commonjs/components/Menu/MenuSurface.js +1 -1
- package/lib/commonjs/components/Modal/Modal.js +1 -1
- package/lib/commonjs/components/ModalSafeArea/ModalSafeArea.js +1 -0
- package/lib/commonjs/components/OptionSheet/OptionSheet.js +1 -1
- package/lib/commonjs/components/PhoneNumberInput/PhoneNumberInput.js +1 -1
- package/lib/commonjs/components/ProfilePicker/ProfilePicker.js +1 -1
- package/lib/commonjs/components/SearchBar/SearchBar.js +1 -1
- package/lib/commonjs/components/SignaturePad/SignaturePad.js +1 -1
- package/lib/commonjs/components/Slider/Slider.js +1 -1
- package/lib/commonjs/components/TimePicker/TimePicker.js +1 -1
- package/lib/commonjs/components/Tooltip/Tooltip.js +1 -1
- package/lib/commonjs/components/index.js +1 -1
- package/lib/commonjs/form/useForm.js +1 -1
- package/lib/commonjs/hooks/useDragToDismiss.js +1 -1
- package/lib/module/components/BottomNavigation/BottomNavigation.js +1 -1
- package/lib/module/components/BottomSheet/BottomSheet.js +1 -1
- package/lib/module/components/Card/Card.js +1 -1
- package/lib/module/components/DatePicker/DatePicker.js +1 -1
- package/lib/module/components/DateRangePicker/DateRangePicker.js +1 -1
- package/lib/module/components/DecimalInput/DecimalInput.js +1 -1
- package/lib/module/components/DecimalInput/index.js +1 -1
- package/lib/module/components/Input/Input.js +1 -1
- package/lib/module/components/LoaderOverlay/LoaderOverlay.js +1 -1
- package/lib/module/components/Menu/MenuSurface.js +1 -1
- package/lib/module/components/Modal/Modal.js +1 -1
- package/lib/module/components/ModalSafeArea/ModalSafeArea.js +1 -0
- package/lib/module/components/OptionSheet/OptionSheet.js +1 -1
- package/lib/module/components/PhoneNumberInput/PhoneNumberInput.js +1 -1
- package/lib/module/components/SearchBar/SearchBar.js +1 -1
- package/lib/module/components/Slider/Slider.js +1 -1
- package/lib/module/components/TimePicker/TimePicker.js +1 -1
- package/lib/module/components/Tooltip/Tooltip.js +1 -1
- package/lib/module/components/index.js +1 -1
- package/lib/module/form/useForm.js +1 -1
- package/lib/module/hooks/useDragToDismiss.js +1 -1
- package/lib/typescript/commonjs/components/DecimalInput/DecimalInput.d.ts +16 -3
- package/lib/typescript/commonjs/components/DecimalInput/index.d.ts +1 -1
- package/lib/typescript/commonjs/components/ModalSafeArea/ModalSafeArea.d.ts +26 -0
- package/lib/typescript/commonjs/components/index.d.ts +1 -1
- package/lib/typescript/module/components/DecimalInput/DecimalInput.d.ts +16 -3
- package/lib/typescript/module/components/DecimalInput/index.d.ts +1 -1
- package/lib/typescript/module/components/ModalSafeArea/ModalSafeArea.d.ts +26 -0
- package/lib/typescript/module/components/index.d.ts +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.useForm=useForm;var _react=require("react"),_equal=require("./equal.js"),_path=require("./path.js");const rulesFor=(e,r)=>{if(!e||"function"==typeof e)return[];const t=e[r];return t?Array.isArray(t)?t:[t]:[]};function useForm(e){const r=(0,_react.useRef)(e);r.current=e;const t=(0,_react.useRef)(e.initialValues),[u,a]=(0,_react.useState)(e.initialValues),[c,n]=(0,_react.useState)({}),[s,o]=(0,_react.useState)({}),[l,i]=(0,_react.useState)(!1),[f,_]=(0,_react.useState)(!1),[d,v]=(0,_react.useState)(0),b=(0,_react.useRef)({values:u,errors:c,touched:s,submitCount:d});b.current={values:u,errors:c,touched:s,submitCount:d};const h=(0,_react.useRef)(new Map),y=(0,_react.useRef)([]),C=(0,_react.useRef)(null),k=(0,_react.useRef)({values:e.initialValues,version:0});(0,_equal.valuesEqual)(e.initialValues,k.current.values)||(k.current={values:e.initialValues,version:k.current.version+1});const p=k.current.version;(0,_react.useEffect)(()=>{if(!r.current.enableReinitialize)return;const e=r.current.initialValues;t.current=e,b.current.values=e,b.current.errors={},b.current.touched={},a(e),n({}),o({})},[p]);const m=(0,_react.useCallback)(async e=>{const t=r.current.validate,u=b.current.values;if("function"==typeof t){return(await t(u)??{})[e]||void 0}const a=(0,_path.getPath)(u,e);for(const r of rulesFor(t,e)){const e=await r(a,u);if(e)return e}},[]),g=(0,_react.useCallback)(async e=>{const t=r.current.validate;if(!t)return{};if("function"==typeof t)return await t(e)??{};const u={};return await Promise.all(Object.keys(t).map(async r=>{const a=(0,_path.getPath)(e,r);for(const c of rulesFor(t,r)){const t=await c(a,e);if(t){u[r]=t;break}}})),u},[]),F=(0,_react.useCallback)(async e=>{const r=await m(e);n(t=>{if(t[e]===r)return t;const u={...t};return r?u[e]=r:delete u[e],b.current.errors=u,u})},[m]),w=(0,_react.useCallback)(async()=>{_(!0);const e=await g(b.current.values);return _(!1),b.current.errors=e,n(e),e},[g]),q=(0,_react.useCallback)((e,t,u)=>{const c=(0,_path.setPath)(b.current.values,e,t);b.current.values=c,a(c);const n=r.current,s=Boolean(b.current.errors[e])&&"blur"===n.revalidateOn;(u??(!s&&(b.current.touched[e]||b.current.submitCount>0||"change"===n.validateOn)))&&F(e)},[F]),E=(0,_react.useCallback)(e=>{o(r=>{if(r[e])return r;const t={...r,[e]:!0};return b.current.touched=t,t}),F(e)},[F]),P=(0,_react.useCallback)((e,r=!0,t)=>{const u={...b.current.touched,[e]:r};b.current.touched=u,o(u),(t??r)&&F(e)},[F]),S=(0,_react.useCallback)((e,r)=>{n(t=>{const u={...t};return r?u[e]=r:delete u[e],b.current.errors=u,u})},[]),V=(0,_react.useCallback)(e=>{b.current.errors=e,n(e)},[]),O=(0,_react.useCallback)((e,r)=>{const t="function"==typeof e?e(b.current.values):{...b.current.values,...e};b.current.values=t,a(t),r&&w()},[w]),j=(0,_react.useCallback)(e=>{const r=e?{...t.current,...e}:t.current;t.current=r,b.current.values=r,b.current.errors={},b.current.touched={},b.current.submitCount=0,a(r),n({}),o({}),v(0)},[]),R=(0,_react.useCallback)((e,r)=>{r?(h.current.set(e,r),y.current.includes(e)||y.current.push(e)):(h.current.delete(e),y.current=y.current.filter(r=>r!==e))},[]),M=(0,_react.useCallback)(e=>{C.current=e},[]),x=(0,_react.useCallback)(e=>{const r=y.current,t=C.current,u=t?r.indexOf(t):-1,a=r[u+e];a&&(C.current=a,h.current.get(a)?.focus?.())},[]),B=(0,_react.useCallback)(()=>x(1),[x]),A=(0,_react.useCallback)(()=>x(-1),[x]),T=(0,_react.useMemo)(()=>({setErrors:V,setFieldError:S,reset:j,setSubmitting:i}),[V,S,j]),z=(0,_react.useCallback)(()=>{(async()=>{const e=r.current,t=b.current.values;b.current.submitCount+=1,v(e=>e+1),_(!0);
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.useForm=useForm;var _react=require("react"),_equal=require("./equal.js"),_path=require("./path.js");const rulesFor=(e,r)=>{if(!e||"function"==typeof e)return[];const t=e[r];return t?Array.isArray(t)?t:[t]:[]};function useForm(e){const r=(0,_react.useRef)(e);r.current=e;const t=(0,_react.useRef)(e.initialValues),[u,a]=(0,_react.useState)(e.initialValues),[c,n]=(0,_react.useState)({}),[s,o]=(0,_react.useState)({}),[l,i]=(0,_react.useState)(!1),[f,_]=(0,_react.useState)(!1),[d,v]=(0,_react.useState)(0),b=(0,_react.useRef)({values:u,errors:c,touched:s,submitCount:d});b.current={values:u,errors:c,touched:s,submitCount:d};const h=(0,_react.useRef)(new Map),y=(0,_react.useRef)([]),C=(0,_react.useRef)(null),k=(0,_react.useRef)({values:e.initialValues,version:0});(0,_equal.valuesEqual)(e.initialValues,k.current.values)||(k.current={values:e.initialValues,version:k.current.version+1});const p=k.current.version;(0,_react.useEffect)(()=>{if(!r.current.enableReinitialize)return;const e=r.current.initialValues;t.current=e,b.current.values=e,b.current.errors={},b.current.touched={},a(e),n({}),o({})},[p]);const m=(0,_react.useCallback)(async e=>{const t=r.current.validate,u=b.current.values;if("function"==typeof t){return(await t(u)??{})[e]||void 0}const a=(0,_path.getPath)(u,e);for(const r of rulesFor(t,e)){const e=await r(a,u);if(e)return e}},[]),g=(0,_react.useCallback)(async e=>{const t=r.current.validate;if(!t)return{};if("function"==typeof t)return await t(e)??{};const u={};return await Promise.all(Object.keys(t).map(async r=>{const a=(0,_path.getPath)(e,r);for(const c of rulesFor(t,r)){const t=await c(a,e);if(t){u[r]=t;break}}})),u},[]),F=(0,_react.useCallback)(async e=>{const r=await m(e);n(t=>{if(t[e]===r)return t;const u={...t};return r?u[e]=r:delete u[e],b.current.errors=u,u})},[m]),w=(0,_react.useCallback)(async()=>{_(!0);const e=await g(b.current.values);return _(!1),b.current.errors=e,n(e),e},[g]),q=(0,_react.useCallback)((e,t,u)=>{const c=(0,_path.setPath)(b.current.values,e,t);b.current.values=c,a(c);const n=r.current,s=Boolean(b.current.errors[e])&&"blur"===n.revalidateOn;(u??(!s&&(b.current.touched[e]||b.current.submitCount>0||"change"===n.validateOn)))&&F(e)},[F]),E=(0,_react.useCallback)(e=>{o(r=>{if(r[e])return r;const t={...r,[e]:!0};return b.current.touched=t,t}),F(e)},[F]),P=(0,_react.useCallback)((e,r=!0,t)=>{const u={...b.current.touched,[e]:r};b.current.touched=u,o(u),(t??r)&&F(e)},[F]),S=(0,_react.useCallback)((e,r)=>{n(t=>{const u={...t};return r?u[e]=r:delete u[e],b.current.errors=u,u})},[]),V=(0,_react.useCallback)(e=>{b.current.errors=e,n(e)},[]),O=(0,_react.useCallback)((e,r)=>{const t="function"==typeof e?e(b.current.values):{...b.current.values,...e};b.current.values=t,a(t),r&&w()},[w]),j=(0,_react.useCallback)(e=>{const r=e?{...t.current,...e}:t.current;t.current=r,b.current.values=r,b.current.errors={},b.current.touched={},b.current.submitCount=0,a(r),n({}),o({}),v(0)},[]),R=(0,_react.useCallback)((e,r)=>{r?(h.current.set(e,r),y.current.includes(e)||y.current.push(e)):(h.current.delete(e),y.current=y.current.filter(r=>r!==e))},[]),M=(0,_react.useCallback)(e=>{C.current=e},[]),x=(0,_react.useCallback)(e=>{const r=y.current,t=C.current,u=t?r.indexOf(t):-1,a=r[u+e];a&&(C.current=a,h.current.get(a)?.focus?.())},[]),B=(0,_react.useCallback)(()=>x(1),[x]),A=(0,_react.useCallback)(()=>x(-1),[x]),T=(0,_react.useMemo)(()=>({setErrors:V,setFieldError:S,reset:j,setSubmitting:i}),[V,S,j]),z=(0,_react.useRef)(!1),N=(0,_react.useCallback)(()=>{z.current||(z.current=!0,(async()=>{try{const e=r.current,t=b.current.values;let u;b.current.submitCount+=1,v(e=>e+1),_(!0);try{u=await g(t)}finally{_(!1)}const a=new Set([...y.current,...Object.keys(u)]),c={...b.current.touched};a.forEach(e=>{c[e]=!0}),b.current.touched=c,b.current.errors=u,o(c),n(u);const s=y.current.find(e=>u[e])??Object.keys(u).find(e=>u[e]);if(s)return void h.current.get(s)?.focus?.();i(!0);try{await e.onSubmit(t,T)}finally{i(!1)}}finally{z.current=!1}})())},[g,T]),D=(0,_react.useMemo)(()=>{const e={};for(const r of Object.keys(c))c[r]&&(s[r]||d>0)&&(e[r]=c[r]);return e},[c,s,d]),G=(0,_react.useMemo)(()=>{const e=r.current.validate;if(!e)return!0;if("function"==typeof e)return Object.values(c).every(e=>!e);for(const r of Object.keys(e)){const t=(0,_path.getPath)(u,r);for(const a of rulesFor(e,r)){const e=a(t,u);if("string"==typeof e&&e)return!1}}return!0},[u,c]),H=(0,_react.useMemo)(()=>!(0,_equal.valuesEqual)(u,t.current),[u]);return{values:u,errors:D,rawErrors:c,touched:s,dirty:H,isValid:G,isSubmitting:l,isValidating:f,submitCount:d,setFieldValue:q,setFieldTouched:P,setFieldError:S,setValues:O,setErrors:V,reset:j,validate:w,validateField:m,submit:N,handleBlur:E,focusNext:B,focusPrev:A,registerField:R,getFieldState:e=>{const r=(0,_path.getPath)(u,e),a=c[e],n=!!s[e];return{value:r,error:n||d>0?a:void 0,rawError:a,touched:n,dirty:!(0,_equal.valuesEqual)(r,(0,_path.getPath)(t.current,e))}},getFieldProps:e=>({name:e,value:(0,_path.getPath)(u,e),error:s[e]||d>0?c[e]:void 0,touched:!!s[e],onChange:r=>q(e,r),onChangeText:r=>q(e,r),onBlur:()=>E(e),onFocus:()=>M(e),setValue:(r,t)=>q(e,r,t)})}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.useDragToDismiss=exports.createDragToDismissController=exports.DRAG_DISMISS_VELOCITY=exports.DRAG_DISMISS_DISTANCE=void 0;var _react=require("react"),_reactNative=require("react-native"),_reactNativeGestureHandler=require("react-native-gesture-handler"),_index=require("../theme/index.js");const DRAG_DISMISS_DISTANCE=exports.DRAG_DISMISS_DISTANCE=100,DRAG_DISMISS_VELOCITY=exports.DRAG_DISMISS_VELOCITY=.5,createDragToDismissController=({drag:e,travel:t,onDismiss:r},s)=>{const{snappy:a}=s.spring,springBack=()=>_reactNative.Animated.spring(e,{toValue:0,damping:a.damping,stiffness:a.stiffness,mass:a.mass,useNativeDriver:!0}).start();return{move:t=>{(0,_index.setNativeValue)(e,Math.max(0,t))},release:(a,i)=>{a>DRAG_DISMISS_DISTANCE||i>DRAG_DISMISS_VELOCITY?_reactNative.Animated.timing(e,{toValue:"function"==typeof t?t():t,duration:s.duration.fast,easing:_reactNative.Easing.bezier(...s.easing.accelerate),useNativeDriver:!0}).start(()=>r()):springBack()},cancel:springBack}};exports.createDragToDismissController=createDragToDismissController;const useDragToDismiss=e=>{const{drag:t,travel:r,onDismiss:s,contentAtTop:a,scrollGesture:i}=e,{motion:n}=(0,_index.useTheme)();return(0,_react.useMemo)(()=>{const e=createDragToDismissController({drag:t,travel:r,onDismiss:s},n),o=_reactNativeGestureHandler.Gesture.Pan().runOnJS(!0).activeOffsetY(6).failOffsetX([-12,12]).onUpdate(t=>e.move(t.translationY)).onEnd(t=>e.release(t.translationY,t.velocityY/1e3)).onFinalize((t
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.useDragToDismiss=exports.createDragToDismissController=exports.DRAG_DISMISS_VELOCITY=exports.DRAG_DISMISS_DISTANCE=void 0;var _react=require("react"),_reactNative=require("react-native"),_reactNativeGestureHandler=require("react-native-gesture-handler"),_index=require("../theme/index.js");const DRAG_DISMISS_DISTANCE=exports.DRAG_DISMISS_DISTANCE=100,DRAG_DISMISS_VELOCITY=exports.DRAG_DISMISS_VELOCITY=.5,createDragToDismissController=({drag:e,travel:t,onDismiss:r},s)=>{const{snappy:a}=s.spring,springBack=()=>_reactNative.Animated.spring(e,{toValue:0,damping:a.damping,stiffness:a.stiffness,mass:a.mass,useNativeDriver:!0}).start();return{move:t=>{(0,_index.setNativeValue)(e,Math.max(0,t))},release:(a,i)=>{a>DRAG_DISMISS_DISTANCE||i>DRAG_DISMISS_VELOCITY?_reactNative.Animated.timing(e,{toValue:"function"==typeof t?t():t,duration:s.duration.fast,easing:_reactNative.Easing.bezier(...s.easing.accelerate),useNativeDriver:!0}).start(()=>r()):springBack()},cancel:springBack}};exports.createDragToDismissController=createDragToDismissController;const useDragToDismiss=e=>{const{drag:t,travel:r,onDismiss:s,contentAtTop:a,scrollGesture:i}=e,{motion:n}=(0,_index.useTheme)();return(0,_react.useMemo)(()=>{const e=createDragToDismissController({drag:t,travel:r,onDismiss:s},n),o=_reactNativeGestureHandler.Gesture.Pan().runOnJS(!0).activeOffsetY(6).failOffsetX([-12,12]).onUpdate(t=>e.move(t.translationY)).onEnd(t=>e.release(t.translationY,t.velocityY/1e3)).onFinalize((_e,t)=>{t||e.cancel()});let l=0,D=!1;const c=_reactNativeGestureHandler.Gesture.Pan().runOnJS(!0).activeOffsetY(8).failOffsetX([-12,12]).onBegin(()=>{l=0,D=!1}).onUpdate(t=>{if(!D){if(a&&!a())return;D=!0,l=t.translationY}e.move(t.translationY-l)}).onEnd(t=>{D&&e.release(t.translationY-l,t.velocityY/1e3)}).onFinalize((_e,t)=>{!t&&D&&e.cancel()});return i&&c.simultaneousWithExternalGesture(i),{handleGesture:o,sheetGesture:c}},[t,r,s,a,i,n])};exports.useDragToDismiss=useDragToDismiss;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import React,{forwardRef,useEffect,useMemo,useRef}from"react";import{Animated,LayoutAnimation,Platform,Pressable,StyleSheet,Text,View}from"react-native";import{useSafeAreaInsets}from"react-native-safe-area-context";import{useReducedMotion}from"../../hooks/useReducedMotion.js";import{createAnimatedValue,useTheme}from"../../theme/index.js";import{triggerHaptic}from"../../utils/index.js";import{smoothCorners}from"../../utils/corners.js";import{supportsBoxShadow,toBoxShadow}from"../../utils/shadows.js";import{renderSlotIcon}from"../AppIcon/index.js";import{useScreenReaderEnabled}from"./useScreenReaderEnabled.js";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";const DEFAULT_ICON_SIZE=18,DEFAULT_LABEL_MAX_FONT_SCALE=1.2,ICON_WRAP_AIR=4,PILL_AIR=8,DEFAULT_PILL_MAX_WIDTH=64,TILE_MAX_WIDTH=96,DEFAULT_PILL_INSET=16,DEFAULT_UNDERLINE_HEIGHT=3,DEFAULT_FLOATING_MARGIN=16,DEFAULT_FLOATING_RADIUS=28,DEFAULT_BUBBLE_SIZE=48,DEFAULT_BUBBLE_LIFT=14,DEFAULT_CENTER_SIZE=48,DEFAULT_CENTER_ICON_SIZE=24,CENTER_KEY="__webority_center_action__",TAB_PADDING_VERTICAL=6,BAR_PADDING_HORIZONTAL=4,BAR_PADDING_TOP=6,BAR_PADDING_TOP_BUBBLE=8,FLOATING_BAR_PADDING_VERTICAL=6,FLOATING_BAR_PADDING_HORIZONTAL=8,EXPANDED_FLEX=1.5,SOLID_INACTIVE_OPACITY=.7,TILE_INSET=2,TILE_LABEL_GAP=2,formatBadge=e=>null==e||!1===e?null:!0===e||"·"===e?{text:"",isDot:!0}:"number"==typeof e?e<=0?null:{text:e>99?"99+":String(e),isDot:!1}:"string"==typeof e?0===e.length?null:{text:e,isDot:!1}:null,badgeAccessibilitySuffix=e=>null==e||!1===e?"":"number"==typeof e?e>0?`, ${e} unread`:"":!0===e||"·"===e?", new updates":"string"==typeof e&&e.length>0?`, ${e}`:"",BottomNavigation=forwardRef((e,t)=>{const{tabs:i,centerAction:n,activeTab:o,onChange:r,haptic:a="selection",showLabels:l=!0,variant:s="pill",indicatorPosition:d="bottom",radius:c,indicatorRadius:u="auto",elevation:h,iconSize:m,marginHorizontal:p,marginVertical:g,paddingHorizontal:b,paddingVertical:y,border:f,minimizeOnScroll:x=!1,scrollDirection:_="idle",accessory:A,style:I,indicatorStyle:R,labelStyle:S,labelMaxFontScale:E,testID:w}=e,L=useTheme(),T=useSafeAreaInsets(),D=useMemo(()=>buildStyles(L),[L]),v=L.components.bottomNavigation,C=m??v?.iconSize??18,j=v?.pillHeight??C+4+8,B=v?.pillMaxWidth??64,N=v?.pillInset??16,V=v?.floatingMargin??16,P=v?.floatingRadius??28,M=v?.bubbleSize??48,k=v?.bubbleLift??14,F=useReducedMotion(),H=useScreenReaderEnabled(x),[z,O]=React.useState(null);useEffect(()=>{null!==z&&z!==_&&O(null)},[z,_]);const W=x&&!H&&"down"===_&&null===z,[U,G]=React.useState(W);useEffect(()=>{U!==W&&(F||"web"===Platform.OS||LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut),G(W))},[U,W,F]);const $="function"==typeof A?A({minimized:U}):A,X=null!=$&&!1!==$,Z=U&&X,[Y,K]=React.useState(0),q=X&&!Z?Y+L.spacing.xs:0,J="tile"===s,Q="floating"===s||J,ee="bubble"===s,te="expand"===s,ie="solid"===s,ne="pill"===s||Q||ie,oe=Math.max(0,i.findIndex(e=>e.key===o)),[re,ae]=React.useState(0),[le,se]=React.useState(0),de=n?Math.ceil(i.length/2):i.length,ce=i.length+(n?1:0),[ue,he]=React.useState({width:0,height:0}),me=n?.size??48,pe=void 0!==n?.gap,ge=Math.max(0,n?.gap??0),be=pe?(ue.width||me)+2*ge:0,ye=pe?i.length>0?Math.max(0,re-be)/i.length:0:ce>0?re/ce:0,fe=pe?be:ye,xe=useRef(createAnimatedValue(oe)).current,_e=useRef({}),Ae=useRef({});i.forEach(e=>{_e.current[e.key]||(_e.current[e.key]=new Animated.Value(1)),Ae.current[e.key]||(Ae.current[e.key]=createAnimatedValue(e.key===o?1:0))});const Ie=ye>0?J?Math.min(ye-4,96):Math.min(ye-N,B):0,Re=ye>0?(ye-Ie)/2:0,Se=ye>0?(ye-M)/2:0,hasLabel=e=>l&&!U&&!1!==e.showLabel&&e.label.trim().length>0,Ee=i[oe],we=Ee&&!hasLabel(Ee)&&le>0?le/2:6+(C+4)/2,Le=we-k-M/2,Te=Math.max(0,le-4),De=J?2:we-j/2,ve=useRef(oe);useEffect(()=>{if(ve.current===oe)return;ve.current=oe;const e=Animated.spring(xe,{toValue:oe,tension:120,friction:14,useNativeDriver:!0});return e.start(),()=>e.stop()},[oe,xe]);const Ce=Math.max(1,i.length-1),je=useMemo(()=>{const e=[],t=[];for(let i=0;i<=Ce;i++)e.push(i),t.push(i<de?i*ye:i*ye+fe);return xe.interpolate({inputRange:e,outputRange:t})},[xe,Ce,de,ye,fe]),Be=i.map(e=>e.key).join(" "),Ne=ee||te;useEffect(()=>{const e=Be.split(" ").flatMap(e=>{const t=e===o?1:0,i=Ae.current[e];return i?Ne?[Animated.spring(i,{toValue:t,tension:140,friction:13,useNativeDriver:!1})]:(i.setValue(t),[]):[]});if(0===e.length)return;const t=Animated.parallel(e);return t.start(),()=>t.stop()},[o,Be,Ne]);const popIcon=e=>{Animated.sequence([Animated.timing(e,{toValue:1.15,duration:120,useNativeDriver:!0}),Animated.spring(e,{toValue:1,tension:200,friction:8,useNativeDriver:!0})]).start()},Ve=useRef(new Animated.Value(1)).current,{colors:Pe}=L,Me=ie?Pe.primary:Pe.background.elevated,ke=ie?Pe.onPrimary:Pe.primary,Fe=ie?Pe.onPrimary:J?Pe.text.primary:Pe.text.tertiary,He=ie?Pe.onPrimary:Pe.primaryMuted,ze=ie?Pe.primary:ee?Pe.onPrimary:ke,Oe=p??V,We=g??(Q?V:0),Ue=We>0,Ge=y??(Q?6:ee?8:6),$e=b??(Q?8:4),Xe=Ue?Ge:Math.max(Ge,T.bottom),Ze=Ue?Math.max(We,T.bottom):0,Ye="full"===c,Ke=Q?le+q+2*Ge+2*StyleSheet.hairlineWidth:le+q+Ge+Xe,qe=Ye?le>0?Ke/2:L.radius.full:c??v?.borderRadius??(J?L.radius.full:Q?P:0),Je=void 0!==c||void 0!==v?.borderRadius,activeBgRadius=(e,t)=>"number"==typeof u?Math.max(0,Math.min(u,e/2)):"auto"===u&&Je?Math.min(qe,e/2):t,Qe="underline"===s?Math.max($e,Ye&&0===le?0:qe):$e,et=h??"none",tt=L.shadows[et],it="none"===et?null:supportsBoxShadow()?{boxShadow:toBoxShadow(tt)}:tt,nt=f?StyleSheet.hairlineWidth:0,ot=ie?Pe.primary:Pe.border.primary,rt=n?.lift??0,at=Ge+nt+q,lt=n&&le>0?Math.max(0,(ue.height||me)/2+rt-le/2-at):0,st=n?_jsx(View,{style:[D.centerCell,pe?{flex:0,marginHorizontal:ge}:null],pointerEvents:"box-none",children:_jsx(Pressable,{onPress:()=>{if(!n)return;const e=n.haptic??a;!1!==e&&triggerHaptic(e),popIcon(Ve),n.onPress()},onLayout:e=>{const{width:t,height:i}=e.nativeEvent.layout;he(e=>e.width===t&&e.height===i?e:{width:t,height:i})},accessibilityRole:"button",accessibilityLabel:n.label,hitSlop:{top:6,bottom:6,left:6,right:6},style:({pressed:e})=>[{top:-rt},e?{opacity:.85}:null],testID:n.testID??(w?`${w}-center`:void 0),children:n.content?_jsx(Animated.View,{style:{transform:[{scale:Ve}]},children:n.content}):_jsx(View,{style:[D.centerCircle,{width:me,height:me,borderRadius:me/2,...smoothCorners,backgroundColor:n.color??Pe.primary}],children:_jsx(Animated.View,{style:{transform:[{scale:Ve}]},children:renderSlotIcon(n.icon??"add",{color:n.iconColor??Pe.onPrimary,size:n.iconSize??24,disabled:!1})})})})},CENTER_KEY):null,dt=X?_jsx(View,{style:Z?D.accessoryInline:D.accessoryStacked,onLayout:e=>K(e.nativeEvent.layout.height),testID:w?`${w}-accessory`:void 0,children:$}):null,ct=_jsxs(View,{style:Z?[D.tabRow,D.tabRowInline]:D.tabRow,onLayout:e=>{const{width:t,height:i}=e.nativeEvent.layout;ae(t),se(i)},children:[ne&&Ie>0&&(!J||Te>0)?_jsx(Animated.View,{pointerEvents:"none",style:[D.pill,{width:Ie,height:J?Te:j,left:Re,top:De,backgroundColor:He,borderRadius:J?activeBgRadius(Te,Te/2):activeBgRadius(j,L.radius.full),...smoothCorners,transform:[{translateX:je}]},R]}):null,ee&&ye>0?_jsx(Animated.View,{pointerEvents:"none",style:[D.bubble,L.shadows.md,{width:M,height:M,borderRadius:M/2,...smoothCorners,left:Se,top:Le,backgroundColor:Pe.primary,borderColor:Pe.background.elevated,transform:[{translateX:je}]},R]}):null,(ut=i.map(e=>{const t=e.key===o,i=t?ke:Fe,n=t?ze:Fe,l="string"==typeof e.icon?{name:e.icon,variant:"bold"}:e.icon,s=t?e.activeIcon??l:e.icon,d=_e.current[e.key],c=Ae.current[e.key],u=formatBadge(e.badge??null),h=badgeAccessibilitySuffix(e.badge??null),m=ie&&!t?.7:1,p=ee&&t||ie?Pe.primary:Pe.background.elevated,g=hasLabel(e),b=g&&(!te||t),y=_jsxs(Animated.View,{style:[D.iconWrap,{width:C+4,height:C+4,opacity:m,transform:[{scale:d}]}],children:[renderSlotIcon(s,{color:n,size:C,focused:t,disabled:!1}),u?_jsx(View,{style:[u.isDot?D.badgeDot:D.badgePill,{backgroundColor:Pe.error,borderColor:p}],children:u.isDot?null:_jsx(Text,{style:[D.badgeText,{color:Pe.onError}],numberOfLines:1,children:u.text})}):null]}),f=ee?_jsx(Animated.View,{style:{top:c.interpolate({inputRange:[0,1],outputRange:[0,-k]})},children:y}):y,x=b?_jsx(Animated.Text,{numberOfLines:1,maxFontSizeMultiplier:E??L.maxFontSizeMultiplier??1.2,style:[D.label,te?D.labelInline:null,{color:i,opacity:te?c:m,fontWeight:t?L.typography.fontWeight.semibold:L.typography.fontWeight.normal},S],children:e.label}):null,A=_jsx(Pressable,{onPress:()=>(e=>{U&&O(_),e.key!==o&&!1!==a&&triggerHaptic(a);const t=_e.current[e.key];t&&popIcon(t),r(e.key)})(e),accessibilityRole:"tab",accessibilityState:{selected:t},"aria-selected":t,accessibilityLabel:`${e.label}${h}`,accessibilityHint:`Switches to ${e.label}`,hitSlop:{top:6,bottom:6,left:6,right:6},style:({pressed:e})=>[D.tab,J?D.tabTile:null,e?{opacity:.85}:null],testID:w?`${w}-tab-${e.key}`:void 0,children:te?_jsxs(View,{style:[D.expandPill,{height:j,paddingHorizontal:t&&g?L.spacing.md:Math.max(0,(j-(C+4))/2)}],children:[_jsx(View,{pointerEvents:"none",style:[D.expandFill,{borderRadius:activeBgRadius(j,j/2),...smoothCorners,backgroundColor:t?Pe.primaryMuted:"transparent"},t?R:null]}),f,x]}):_jsxs(_Fragment,{children:[f,x]})},e.key);return te?_jsx(Animated.View,{style:{flex:c.interpolate({inputRange:[0,1],outputRange:[1,g?1.5:1]})},children:A},e.key):A}),st?[...ut.slice(0,de),st,...ut.slice(de)]:ut),"underline"===s&&ye>0?_jsx(Animated.View,{pointerEvents:"none",style:[D.underline,"top"===d?D.underlineTop:D.underlineBottom,"top"===d?{top:-Ge-q}:{bottom:-Ge},{width:ye,height:v?.underlineHeight??3,backgroundColor:Pe.primary,transform:[{translateX:je}]},R]}):null]});var ut;return _jsx(View,{ref:t,testID:w,accessibilityRole:"tablist",style:[D.outer,{paddingHorizontal:Oe,paddingTop:Math.max(We,lt),paddingBottom:Ze},I],children:_jsxs(View,{style:[Q?D.floatingBar:D.dockedBar,Z?D.barInline:null,it,{backgroundColor:Me,borderColor:ot,borderRadius:qe,...smoothCorners},Q?{borderWidth:nt,paddingHorizontal:$e,paddingVertical:Ge}:{borderTopWidth:nt,borderBottomWidth:nt,borderLeftWidth:nt,borderRightWidth:nt,paddingHorizontal:Qe,paddingTop:Ge,paddingBottom:Xe}],children:[dt,ct]})})});BottomNavigation.displayName="BottomNavigation";const buildStyles=e=>StyleSheet.create({outer:{backgroundColor:"transparent"},dockedBar:{paddingHorizontal:4},floatingBar:{paddingVertical:6,paddingHorizontal:8},tabRow:{flexDirection:"row",alignItems:"stretch",position:"relative"},tabRowInline:{flex:1},barInline:{flexDirection:"row",alignItems:"center"},accessoryStacked:{marginBottom:e.spacing.xs},accessoryInline:{flexShrink:0,marginRight:e.spacing.xs},tab:{flex:1,minHeight:44,alignItems:"center",justifyContent:"center",paddingVertical:6,gap:4},tabTile:{paddingVertical:8,gap:2},centerCell:{flex:1,minHeight:44,alignItems:"center",justifyContent:"center"},centerCircle:{alignItems:"center",justifyContent:"center"},iconWrap:{alignItems:"center",justifyContent:"center",position:"relative"},label:{fontSize:e.typography.fontSize.xs,lineHeight:e.typography.fontSize.xs*e.typography.lineHeight.tight,textAlign:"center",includeFontPadding:!1},labelInline:{fontSize:e.typography.fontSize.sm,lineHeight:e.typography.fontSize.sm*e.typography.lineHeight.tight,flexShrink:1,includeFontPadding:!1},expandPill:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:e.spacing.xs},expandFill:{position:"absolute",top:0,right:0,bottom:0,left:0,overflow:"hidden"},pill:{position:"absolute",left:0},bubble:{position:"absolute",left:0,borderWidth:3},underline:{position:"absolute",left:0,height:3},underlineBottom:{borderTopLeftRadius:2,borderTopRightRadius:2,...smoothCorners},underlineTop:{borderBottomLeftRadius:2,borderBottomRightRadius:2,...smoothCorners},badgePill:{position:"absolute",top:-4,right:-8,minWidth:18,height:18,borderRadius:9,...smoothCorners,paddingHorizontal:4,paddingVertical:2,alignItems:"center",justifyContent:"center",borderWidth:1.5},badgeDot:{position:"absolute",top:-2,right:-2,width:10,height:10,borderRadius:5,...smoothCorners,borderWidth:1.5},badgeText:{fontSize:10,fontWeight:"700",lineHeight:12,textAlign:"center",includeFontPadding:!1}});export{BottomNavigation};export default BottomNavigation;
|
|
1
|
+
"use strict";import React,{forwardRef,useEffect,useMemo,useRef}from"react";import{Animated,LayoutAnimation,Platform,Pressable,StyleSheet,Text,View}from"react-native";import{useSafeAreaInsets}from"react-native-safe-area-context";import{useReducedMotion}from"../../hooks/useReducedMotion.js";import{createAnimatedValue,useTheme}from"../../theme/index.js";import{triggerHaptic}from"../../utils/index.js";import{smoothCorners}from"../../utils/corners.js";import{supportsBoxShadow,toBoxShadow}from"../../utils/shadows.js";import{renderSlotIcon}from"../AppIcon/index.js";import{useScreenReaderEnabled}from"./useScreenReaderEnabled.js";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";const DEFAULT_ICON_SIZE=18,DEFAULT_LABEL_MAX_FONT_SCALE=1.2,ICON_WRAP_AIR=4,PILL_AIR=8,DEFAULT_PILL_MAX_WIDTH=64,TILE_MAX_WIDTH=96,DEFAULT_PILL_INSET=16,DEFAULT_UNDERLINE_HEIGHT=3,DEFAULT_FLOATING_MARGIN=16,DEFAULT_FLOATING_RADIUS=28,DEFAULT_BUBBLE_SIZE=48,DEFAULT_BUBBLE_LIFT=14,DEFAULT_CENTER_SIZE=48,DEFAULT_CENTER_ICON_SIZE=24,CENTER_KEY="__webority_center_action__",TAB_PADDING_VERTICAL=6,BAR_PADDING_HORIZONTAL=4,BAR_PADDING_TOP=6,BAR_PADDING_TOP_BUBBLE=8,FLOATING_BAR_PADDING_VERTICAL=6,FLOATING_BAR_PADDING_HORIZONTAL=8,EXPANDED_FLEX=1.5,SOLID_INACTIVE_OPACITY=.7,TILE_INSET=2,TILE_LABEL_GAP=2,formatBadge=e=>null==e||!1===e?null:!0===e||"·"===e?{text:"",isDot:!0}:"number"==typeof e?e<=0?null:{text:e>99?"99+":String(e),isDot:!1}:"string"==typeof e?0===e.length?null:{text:e,isDot:!1}:null,badgeAccessibilitySuffix=e=>null==e||!1===e?"":"number"==typeof e?e>0?`, ${e} unread`:"":!0===e||"·"===e?", new updates":"string"==typeof e&&e.length>0?`, ${e}`:"",BottomNavigation=forwardRef((e,t)=>{const{tabs:i,centerAction:n,activeTab:o,onChange:r,haptic:a="selection",showLabels:l=!0,variant:s="pill",indicatorPosition:d="bottom",radius:c,indicatorRadius:u="auto",elevation:h,iconSize:m,marginHorizontal:p,marginVertical:g,paddingHorizontal:b,paddingVertical:y,border:f,minimizeOnScroll:x=!1,scrollDirection:_="idle",accessory:A,style:I,indicatorStyle:R,labelStyle:S,labelMaxFontScale:E,testID:w}=e,L=useTheme(),T=useSafeAreaInsets(),D=useMemo(()=>buildStyles(L),[L]),v=L.components.bottomNavigation,C=m??v?.iconSize??18,j=v?.pillHeight??C+4+8,B=v?.pillMaxWidth??64,N=v?.pillInset??16,V=v?.floatingMargin??16,P=v?.floatingRadius??28,M=v?.bubbleSize??48,k=v?.bubbleLift??14,F=useReducedMotion(),H=useScreenReaderEnabled(x),[z,O]=React.useState(null);useEffect(()=>{null!==z&&z!==_&&O(null)},[z,_]);const W=x&&!H&&"down"===_&&null===z,[U,G]=React.useState(W);useEffect(()=>{U!==W&&(F||"web"===Platform.OS||LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut),G(W))},[U,W,F]);const $="function"==typeof A?A({minimized:U}):A,X=null!=$&&!1!==$,Z=U&&X,[Y,K]=React.useState(0),q=X&&!Z?Y+L.spacing.xs:0,J="tile"===s,Q="floating"===s||J,ee="bubble"===s,te="expand"===s,ie="solid"===s,ne="pill"===s||Q||ie,oe=Math.max(0,i.findIndex(e=>e.key===o)),[re,ae]=React.useState(0),[le,se]=React.useState(0),de=n?Math.ceil(i.length/2):i.length,ce=i.length+(n?1:0),[ue,he]=React.useState({width:0,height:0}),me=n?.size??48,pe=void 0!==n?.gap,ge=Math.max(0,n?.gap??0),be=pe?(ue.width||me)+2*ge:0,ye=pe?i.length>0?Math.max(0,re-be)/i.length:0:ce>0?re/ce:0,fe=pe?be:ye,xe=useRef(createAnimatedValue(oe)).current,Ae=useRef({}),Ie=useRef({});i.forEach(e=>{Ae.current[e.key]||(Ae.current[e.key]=new Animated.Value(1)),Ie.current[e.key]||(Ie.current[e.key]=createAnimatedValue(e.key===o?1:0))});const Re=ye>0?J?Math.min(ye-4,96):Math.min(ye-N,B):0,Se=ye>0?(ye-Re)/2:0,Ee=ye>0?(ye-M)/2:0,hasLabel=e=>l&&!U&&!1!==e.showLabel&&e.label.trim().length>0,we=i[oe],Le=we&&!hasLabel(we)&&le>0?le/2:6+(C+4)/2,Te=Le-k-M/2,De=Math.max(0,le-4),ve=J?2:Le-j/2,Ce=useRef(oe);useEffect(()=>{if(Ce.current===oe)return;Ce.current=oe;const e=Animated.spring(xe,{toValue:oe,tension:120,friction:14,useNativeDriver:!0});return e.start(),()=>e.stop()},[oe,xe]);const je=Math.max(1,i.length-1),Be=useMemo(()=>{const e=[],t=[];for(let i=0;i<=je;i++)e.push(i),t.push(i<de?i*ye:i*ye+fe);return xe.interpolate({inputRange:e,outputRange:t})},[xe,je,de,ye,fe]),Ne=i.map(e=>e.key).join(" "),Ve=ee||te;useEffect(()=>{const e=Ne.split(" ").flatMap(e=>{const t=e===o?1:0,i=Ie.current[e];return i?Ve?[Animated.spring(i,{toValue:t,tension:140,friction:13,useNativeDriver:!1})]:(i.setValue(t),[]):[]});if(0===e.length)return;const t=Animated.parallel(e);return t.start(),()=>t.stop()},[o,Ne,Ve]);const popIcon=e=>{Animated.sequence([Animated.timing(e,{toValue:1.15,duration:120,useNativeDriver:!0}),Animated.spring(e,{toValue:1,tension:200,friction:8,useNativeDriver:!0})]).start()},Pe=useRef(new Animated.Value(1)).current,{colors:Me}=L,ke=ie?Me.primary:Me.background.elevated,Fe=ie?Me.onPrimary:Me.primary,He=ie?Me.onPrimary:J?Me.text.primary:Me.text.tertiary,ze=ie?Me.onPrimary:Me.primaryMuted,Oe=ie?Me.primary:ee?Me.onPrimary:Fe,We=p??V,Ue=g??(Q?V:0),Ge=Ue>0,$e=y??(Q?6:ee?8:6),Xe=b??(Q?8:4),Ze=Ge?$e:Math.max($e,T.bottom),Ye=Ge?Math.max(Ue,T.bottom):0,Ke="full"===c,qe=Q?le+q+2*$e+2*StyleSheet.hairlineWidth:le+q+$e+Ze,Je=Ke?le>0?qe/2:L.radius.full:c??v?.borderRadius??(J?L.radius.full:Q?P:0),Qe=void 0!==c||void 0!==v?.borderRadius,activeBgRadius=(e,t)=>"number"==typeof u?Math.max(0,Math.min(u,e/2)):"auto"===u&&Qe?Math.min(Je,e/2):t,et="underline"===s?Math.max(Xe,Ke&&0===le?0:Je):Xe,tt=h??"none",it=L.shadows[tt],nt="none"===tt?null:supportsBoxShadow()?{boxShadow:toBoxShadow(it)}:it,ot=f?StyleSheet.hairlineWidth:0,rt=ie?Me.primary:Me.border.primary,at=n?.lift??0,lt=$e+ot+q,st=n&&le>0?Math.max(0,(ue.height||me)/2+at-le/2-lt):0,dt=n?_jsx(View,{style:[D.centerCell,pe?{flex:0,marginHorizontal:ge}:null],pointerEvents:"box-none",children:_jsx(Pressable,{onPress:()=>{if(!n)return;const e=n.haptic??a;!1!==e&&triggerHaptic(e),popIcon(Pe),n.onPress()},onLayout:e=>{const{width:t,height:i}=e.nativeEvent.layout;he(e=>e.width===t&&e.height===i?e:{width:t,height:i})},accessibilityRole:"button",accessibilityLabel:n.label,hitSlop:{top:6,bottom:6,left:6,right:6},style:({pressed:e})=>[{top:-at},e?{opacity:.85}:null],testID:n.testID??(w?`${w}-center`:void 0),children:n.content?_jsx(Animated.View,{style:{transform:[{scale:Pe}]},children:n.content}):_jsx(View,{style:[D.centerCircle,{width:me,height:me,borderRadius:me/2,...smoothCorners,backgroundColor:n.color??Me.primary}],children:_jsx(Animated.View,{style:{transform:[{scale:Pe}]},children:renderSlotIcon(n.icon??"add",{color:n.iconColor??Me.onPrimary,size:n.iconSize??24,disabled:!1})})})})},CENTER_KEY):null,ct=X?_jsx(View,{style:Z?D.accessoryInline:D.accessoryStacked,onLayout:e=>K(e.nativeEvent.layout.height),testID:w?`${w}-accessory`:void 0,children:$}):null,ut=_jsxs(View,{style:Z?[D.tabRow,D.tabRowInline]:D.tabRow,onLayout:e=>{const{width:t,height:i}=e.nativeEvent.layout;ae(t),se(i)},children:[ne&&Re>0&&(!J||De>0)?_jsx(Animated.View,{pointerEvents:"none",style:[D.pill,{width:Re,height:J?De:j,left:Se,top:ve,backgroundColor:ze,borderRadius:J?activeBgRadius(De,De/2):activeBgRadius(j,L.radius.full),...smoothCorners,transform:[{translateX:Be}]},R]}):null,ee&&ye>0?_jsx(Animated.View,{pointerEvents:"none",style:[D.bubble,L.shadows.md,{width:M,height:M,borderRadius:M/2,...smoothCorners,left:Ee,top:Te,backgroundColor:Me.primary,borderColor:Me.background.elevated,transform:[{translateX:Be}]},R]}):null,(ht=i.map(e=>{const t=e.key===o,i=t?Fe:He,n=t?Oe:He,l="string"==typeof e.icon?{name:e.icon,variant:"bold"}:e.icon,s=t?e.activeIcon??l:e.icon,d=Ae.current[e.key],c=Ie.current[e.key],u=formatBadge(e.badge??null),h=badgeAccessibilitySuffix(e.badge??null),m=ie&&!t?.7:1,p=ee&&t||ie?Me.primary:Me.background.elevated,g=hasLabel(e),b=g&&(!te||t),y=_jsxs(Animated.View,{style:[D.iconWrap,{width:C+4,height:C+4,opacity:m,transform:[{scale:d}]}],children:[renderSlotIcon(s,{color:n,size:C,focused:t,disabled:!1}),u?_jsx(View,{style:[u.isDot?D.badgeDot:D.badgePill,{backgroundColor:Me.error,borderColor:p}],children:u.isDot?null:_jsx(Text,{style:[D.badgeText,{color:Me.onError}],numberOfLines:1,children:u.text})}):null]}),f=ee?_jsx(Animated.View,{style:{top:c.interpolate({inputRange:[0,1],outputRange:[0,-k]})},children:y}):y,x=b?_jsx(Animated.Text,{numberOfLines:1,maxFontSizeMultiplier:E??L.maxFontSizeMultiplier??1.2,style:[D.label,te?D.labelInline:null,{color:i,opacity:te?c:m,fontWeight:t?L.typography.fontWeight.semibold:L.typography.fontWeight.normal},S],children:e.label}):null,A=_jsx(Pressable,{onPress:()=>(e=>{U&&O(_),e.key!==o&&!1!==a&&triggerHaptic(a);const t=Ae.current[e.key];t&&popIcon(t),r(e.key)})(e),accessibilityRole:"tab",accessibilityState:{selected:t},"aria-selected":t,accessibilityLabel:`${e.label}${h}`,accessibilityHint:`Switches to ${e.label}`,hitSlop:{top:6,bottom:6,left:6,right:6},style:({pressed:e})=>[D.tab,J?D.tabTile:null,e?{opacity:.85}:null],testID:w?`${w}-tab-${e.key}`:void 0,children:te?_jsxs(View,{style:[D.expandPill,{height:j,paddingHorizontal:t&&g?L.spacing.md:Math.max(0,(j-(C+4))/2)}],children:[_jsx(View,{pointerEvents:"none",style:[D.expandFill,{borderRadius:activeBgRadius(j,j/2),...smoothCorners,backgroundColor:t?Me.primaryMuted:"transparent"},t?R:null]}),f,x]}):_jsxs(_Fragment,{children:[f,x]})},e.key);return te?_jsx(Animated.View,{style:{flex:c.interpolate({inputRange:[0,1],outputRange:[1,g?1.5:1]})},children:A},e.key):A}),dt?[...ht.slice(0,de),dt,...ht.slice(de)]:ht),"underline"===s&&ye>0?_jsx(Animated.View,{pointerEvents:"none",style:[D.underline,"top"===d?D.underlineTop:D.underlineBottom,"top"===d?{top:-$e-q}:{bottom:-$e},{width:ye,height:v?.underlineHeight??3,backgroundColor:Me.primary,transform:[{translateX:Be}]},R]}):null]});var ht;return _jsx(View,{ref:t,testID:w,accessibilityRole:"tablist",style:[D.outer,{paddingHorizontal:We,paddingTop:Math.max(Ue,st),paddingBottom:Ye},I],children:_jsxs(View,{style:[Q?D.floatingBar:D.dockedBar,Z?D.barInline:null,nt,{backgroundColor:ke,borderColor:rt,borderRadius:Je,...smoothCorners},Q?{borderWidth:ot,paddingHorizontal:Xe,paddingVertical:$e}:{borderTopWidth:ot,borderBottomWidth:ot,borderLeftWidth:ot,borderRightWidth:ot,paddingHorizontal:et,paddingTop:$e,paddingBottom:Ze}],children:[ct,ut]})})});BottomNavigation.displayName="BottomNavigation";const buildStyles=e=>StyleSheet.create({outer:{backgroundColor:"transparent"},dockedBar:{paddingHorizontal:4},floatingBar:{paddingVertical:6,paddingHorizontal:8},tabRow:{flexDirection:"row",alignItems:"stretch",position:"relative"},tabRowInline:{flex:1},barInline:{flexDirection:"row",alignItems:"center"},accessoryStacked:{marginBottom:e.spacing.xs},accessoryInline:{flexShrink:0,marginRight:e.spacing.xs},tab:{flex:1,minHeight:44,alignItems:"center",justifyContent:"center",paddingVertical:6,gap:4},tabTile:{paddingVertical:8,gap:2},centerCell:{flex:1,minHeight:44,alignItems:"center",justifyContent:"center"},centerCircle:{alignItems:"center",justifyContent:"center"},iconWrap:{alignItems:"center",justifyContent:"center",position:"relative"},label:{fontSize:e.typography.fontSize.xs,lineHeight:e.typography.fontSize.xs*e.typography.lineHeight.tight,textAlign:"center",includeFontPadding:!1},labelInline:{fontSize:e.typography.fontSize.sm,lineHeight:e.typography.fontSize.sm*e.typography.lineHeight.tight,flexShrink:1,includeFontPadding:!1},expandPill:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:e.spacing.xs},expandFill:{position:"absolute",top:0,right:0,bottom:0,left:0,overflow:"hidden"},pill:{position:"absolute",left:0},bubble:{position:"absolute",left:0,borderWidth:3},underline:{position:"absolute",left:0,height:3},underlineBottom:{borderTopLeftRadius:2,borderTopRightRadius:2,...smoothCorners},underlineTop:{borderBottomLeftRadius:2,borderBottomRightRadius:2,...smoothCorners},badgePill:{position:"absolute",top:-4,right:-8,minWidth:18,height:18,borderRadius:9,...smoothCorners,paddingHorizontal:4,paddingVertical:2,alignItems:"center",justifyContent:"center",borderWidth:1.5},badgeDot:{position:"absolute",top:-2,right:-2,width:10,height:10,borderRadius:5,...smoothCorners,borderWidth:1.5},badgeText:{fontSize:10,fontWeight:"700",lineHeight:12,textAlign:"center",includeFontPadding:!1}});export{BottomNavigation};export default BottomNavigation;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{createContext,forwardRef,useCallback,useContext,useEffect,useImperativeHandle,useMemo,useRef,useState}from"react";import{Dimensions,Modal,Platform,ScrollView,StyleSheet,useWindowDimensions,View}from"react-native";import{Gesture,GestureDetector,GestureHandlerRootView}from"react-native-gesture-handler";import{useReanimatedKeyboardAnimation}from"react-native-keyboard-controller";import Animated,{Easing,runOnJS,useAnimatedStyle,useDerivedValue,useSharedValue,withSpring,withTiming}from"react-native-reanimated";import{SafeAreaProvider,useSafeAreaInsets}from"react-native-safe-area-context";import{useTheme}from"../../theme/index.js";import{triggerHaptic}from"../../utils/index.js";import{smoothCorners}from"../../utils/corners.js";import{ToastHost}from"../Toast/ToastProvider.js";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const TABLET_MIN_SHORT_SIDE=600,DIALOG_MAX_WIDTH=560,BottomSheetContext=createContext(null);export const useBottomSheet=()=>{const e=useContext(BottomSheetContext);if(!e)throw new Error("useBottomSheet must be used inside a <BottomSheet>.");return e};const SPRING_CONFIG={damping:20,stiffness:240,mass:1},CLOSE_VELOCITY_THRESHOLD=1e3,DRAG_ACTIVATION_OFFSET=10,BottomSheet=forwardRef((e,t)=>{const{snapPoints:o,index:s,onChange:n,onAnimate:r,onAfterClose:a,enablePanDownToClose:l=!0,enableBackdropPress:i=!0,confirmDismiss:u,scrollable:c=!1,scrollRef:d,onScroll:h,onContentSizeChange:m,onScrollLayout:f,scrollEventThrottle:b,keyboardBehavior:p="shift",mode:S="modal",presentation:g="sheet",handleIndicatorStyle:v,containerStyle:y,header:w,footer:C,headerStyle:x,footerStyle:k,children:R,accessibilityLabel:_,accessibilityViewIsModal:I,testID:j}=e,T=useTheme(),M=useSafeAreaInsets(),[V,D]=useState(()=>Dimensions.get("window").height),[O,A]=useState(()=>Dimensions.get("window").width),H=useCallback(e=>{const{height:t,width:o}=e.nativeEvent.layout;t>0&&D(e=>e===t?e:t),o>0&&A(e=>e===o?e:o)},[]),P=useWindowDimensions(),B="dialog"===g||"auto"===g&&Math.min(P.width,P.height)>=600,E=Math.min(560,O-2*T.spacing.xl),[G,L]=useState({top:M.top,bottom:M.bottom}),N="modal"===S?G.top:M.top,F="modal"===S?G.bottom:M.bottom,J=o.includes("content"),[z,Y]=useMeasuredHeight(),[$,q]=useMeasuredHeight(),[W,K,X]=useMeasuredHeight(),[U,Q]=useMeasuredHeight(),Z=B?T.spacing.md:z,ee=J?Math.min(Z+(null!=w?$:0)+W+(null!=C?U:0)+F,V-N):0,te=useCallback((e,t)=>{J&&X(t),m?.(e,t)},[J,m,X]),oe=useMemo(()=>resolveSnapPoints(o,V,ee),[o,V,ee]),se=V,ne=oe[oe.length-1]??0,re=useSharedValue(se),ae=useSharedValue(se),le=useSharedValue(-1),[ie,ue]=useState(-1),ce=useRef(!1),[de,he]=useState(!1),[me,fe]=useState(!1),be=useRef(!1),pe=useRef(a);pe.current=a;const[Se,ge]=useState(!1),ve=useRef(-1),ye=useRef(!1);ye.current="modal"===S?me:Se;const we=useRef(u);we.current=u;const Ce=useRef(!1),xe=useRef(!0),ke=useRef([]),Re=useCallback(e=>{const t=ke.current;ke.current=[];for(const o of t)o(e)},[]);useEffect(()=>(xe.current=!0,()=>{xe.current=!1,Re(!1)}),[Re]);const _e=useCallback(e=>{if(e<0||e>=oe.length)return se;const t=oe[e];return B?(V-t)/2:V-t},[oe,V,se,B]),Ie=useCallback(e=>{ve.current=e;ie!==e&&(ue(e),le.value=e,n?.(e))},[ie,le,n]),je=useCallback(()=>{ce.current=!1,le.value<0&&(be.current=!0,"modal"===S?(he(!1),"ios"!==Platform.OS&&fe(!1)):ge(!1))},[S,le]),Te=useCallback(()=>{be.current&&fe(!1)},[]);useEffect(()=>{("modal"===S?!me:!Se)&&be.current&&(be.current=!1,pe.current?.(),Re(!0))},[S,me,Se,Re]);const Me=useCallback((e,t,o)=>{ce.current=!0,r?.(t,o),re.value=withSpring(e,SPRING_CONFIG,e=>{"worklet";e&&runOnJS(je)()})},[r,re,je]),Ve=useCallback(e=>{const t="number"==typeof e?clamp(e,0,oe.length-1):ie>=0?ie:0,o=le.value,s=_e(t);be.current=!1,Re(!1),"modal"===S?(fe(!0),he(!0)):ge(!0),o<0&&(re.value=se),Ie(t),Me(s,o,t)},[Me,se,ie,le,S,oe.length,Ie,Re,re,_e]),De=useCallback(()=>{if(0===oe.length)return;const e=le.value,t=_e(0);Ie(0),Me(t,e,0)},[Me,le,oe.length,Ie,_e]),Oe=useCallback(()=>new Promise(e=>{if(ve.current<0)return void(ye.current?ke.current.push(e):e(!0));ke.current.push(e);const t=le.value;Ie(-1),ce.current=!0,r?.(t,-1),re.value=withTiming(se,{duration:T.motion.duration.fast,easing:Easing.bezier(...T.motion.easing.accelerate)},e=>{"worklet";e&&runOnJS(je)()})}),[se,le,je,r,Ie,re,T.motion.duration.fast,T.motion.easing.accelerate]),Ae=useCallback(async()=>{await Oe()},[Oe]),He=useCallback((e,t,o)=>{const s=we.current;if(!s)return void e();if(Ce.current)return void t?.();const n=s();"boolean"!=typeof n?(Ce.current=!0,o?.(),n.then(o=>{Ce.current=!1,o&&xe.current&&ve.current>=0?e():t?.()},e=>{throw Ce.current=!1,e})):(n?e:t)?.()},[]),Pe=useCallback(()=>new Promise(e=>{ve.current<0?Oe().then(e):He(()=>{Oe().then(e)},()=>e(!1))}),[Oe,He]),Be=useCallback(()=>{He(()=>{Ae()})},[Ae,He]);useImperativeHandle(t,()=>({expand:Ve,collapse:De,close:Ae,requestClose:Pe}),[Ve,De,Ae,Pe]),useEffect(()=>{"number"==typeof s&&s!==ie&&(-1===s?Ae():Ve(s))},[s]);const Ee=useRef({hostHeight:V,contentSnap:ee});useEffect(()=>{const e=Ee.current;e.hostHeight===V&&e.contentSnap===ee||(Ee.current={hostHeight:V,contentSnap:ee},e.hostHeight===V&&le.value<0||(re.value=withSpring(_e(le.value),SPRING_CONFIG)))},[V,ee]);const Ge=V-ne,Le=useMemo(()=>oe.map(e=>V-e),[oe,V]),Ne=useCallback(()=>{const e=ve.current;e<0||Me(_e(e),e,e)},[Me,_e]),Fe=useCallback((e,t)=>{const o=le.value;-1!==e?(Ie(e),Me(t,o,e)):He(()=>{triggerHaptic("selection"),Ae()},Ne,Ne)},[Me,Ae,le,He,Ie,Ne]),Je=useMemo(()=>Gesture.Native().withTestId(j?`${j}-content-gesture`:"bottom-sheet-content-gesture"),[j]),ze=useMemo(()=>{const e=Le,t=se,o=Ge,s=l;return Gesture.Pan().withTestId(j?`${j}-pan-gesture`:"bottom-sheet-pan-gesture").activeOffsetY([-10,10]).failOffsetX([-15,15]).onStart(()=>{"worklet";ae.value=re.value}).onUpdate(e=>{"worklet";const t=ae.value+e.translationY;re.value=t<o?o+.25*(t-o):t}).onEnd(o=>{"worklet";const n=re.value;if(o.velocityY>1e3)return s?void runOnJS(Fe)(-1,t):void runOnJS(Fe)(0,e[0]);let r=0,a=Math.abs(n-e[0]);for(let t=1;t<e.length;t++){const o=Math.abs(n-e[t]);o<a&&(a=o,r=t)}const l=e[0];s&&n-l>80?runOnJS(Fe)(-1,t):runOnJS(Fe)(r,e[r])})},[se,ae,l,Fe,Ge,Le,j,re]),{height:Ye}=useReanimatedKeyboardAnimation(),$e="shift"===p,qe=useDerivedValue(()=>$e?Ye.value:0),We=oe[ie>=0?ie:0]??ne,Ke=T.spacing.md,Xe=useAnimatedStyle(()=>{if(B){const e=qe.value,t=V+e-We-Ke,o=e<0&&re.value>t?t:re.value;return{top:o<N?N:o}}const e=re.value+qe.value,t=qe.value<0?N:Ge;return{top:e<t?t:e}}),Ue=useAnimatedStyle(()=>{const e=qe.value;if(B){const t=V+e-We-Ke,o=e<0&&re.value>t?t:re.value,s=V+e-Ke-(o<N?N:o);return{height:s<0?0:s>We?We:s}}const t=e<0?N:Ge,o=re.value+e,s=V+e-(o<t?t:o);return{height:s<0?0:s>ne?ne:s}}),Qe=ie>=0,Ze=useMemo(()=>buildStyles(T),[T]),et=useCallback(()=>{i&&He(()=>{triggerHaptic("selection"),Ae()})},[i,Ae,He]),tt=useMemo(()=>Gesture.Tap().withTestId(j?`${j}-backdrop-gesture`:"bottom-sheet-backdrop-gesture").maxDuration(250).onEnd((e,t)=>{"worklet";t&&runOnJS(et)()}),[et,j]),ot=useMemo(()=>({snapIndex:ie,snapPoints:oe,expand:Ve,collapse:De,close:Ae,requestClose:Pe}),[ie,oe,Ve,De,Ae,Pe]);if("inline"===S&&!Se)return null;if("modal"===S&&!me)return null;const st=_jsxs(View,{collapsable:!1,style:["modal"===S?Ze.backdropModal:Ze.backdropInline,{backgroundColor:T.colors.background.overlay}],onLayout:H,testID:j,accessibilityViewIsModal:I??Qe,children:[_jsx(GestureDetector,{gesture:tt,children:_jsx(Animated.View,{style:StyleSheet.absoluteFill,accessibilityRole:"button",accessibilityLabel:"Close bottom sheet"})}),_jsx(Animated.View,{accessibilityRole:"alert",accessibilityLabel:_,accessibilityViewIsModal:I??Qe,style:[Ze.sheet,{height:ne,backgroundColor:T.colors.background.elevated,borderTopLeftRadius:T.radius["2xl"],borderTopRightRadius:T.radius["2xl"],...smoothCorners,...T.shadows.xl},B?{height:We,left:(O-E)/2,right:void 0,width:E,borderBottomLeftRadius:T.radius["2xl"],borderBottomRightRadius:T.radius["2xl"]}:null,y,Xe],children:_jsxs(SheetBody,{style:[Ze.body,Ue],keyboardOffset:qe,children:[B?_jsx(View,{style:{height:T.spacing.md}}):_jsx(GestureDetector,{gesture:ze,children:_jsx(View,{style:Ze.handleRow,onLayout:J?Y:void 0,accessible:!0,accessibilityLabel:"Drag handle",accessibilityHint:"Drag up or down to resize the sheet, or swipe down to close it",testID:j?`${j}-handle`:"bottom-sheet-handle",children:_jsx(View,{style:[Ze.handle,{backgroundColor:T.components.bottomSheet?.handleColor??T.colors.border.primary},v]})})}),null!=w&&_jsx(View,{style:[Ze.header,x],onLayout:J?q:void 0,children:w}),c?_jsx(GestureDetector,{gesture:Je,children:_jsx(ScrollView,{ref:d,style:Ze.scrollContent,onScroll:h,onContentSizeChange:te,onLayout:f,scrollEventThrottle:b,keyboardShouldPersistTaps:"always",keyboardDismissMode:"none",children:R})}):_jsx(View,{style:Ze.content,children:J?_jsx(View,{onLayout:K,children:R}):R}),null!=C&&_jsx(View,{style:[Ze.footer,k],onLayout:J?Q:void 0,children:C})]})})]}),nt=_jsx(BottomSheetContext.Provider,{value:ot,children:st});return"modal"===S?_jsx(Modal,{transparent:!0,visible:de,onRequestClose:Be,onDismiss:"ios"===Platform.OS?Te:void 0,statusBarTranslucent:!0,navigationBarTranslucent:!0,animationType:"none",supportedOrientations:["portrait","landscape"],children:_jsxs(SafeAreaProvider,{style:Ze.modalRoot,children:[_jsx(InsetsProbe,{onChange:L}),"android"===Platform.OS?_jsx(GestureHandlerRootView,{style:Ze.modalRoot,children:nt}):nt,_jsx(ToastHost,{})]})}):nt}),InsetsProbe=({onChange:e})=>{const{top:t,bottom:o}=useSafeAreaInsets();return useEffect(()=>{e(e=>e.top===t&&e.bottom===o?e:{top:t,bottom:o})},[t,o,e]),null},SheetBody=({style:e,keyboardOffset:t,children:o})=>{const s=useSafeAreaInsets().bottom,n=useAnimatedStyle(()=>{const e=s+t.value;return{paddingBottom:e>0?e:0}});return _jsx(Animated.View,{style:[e,n],children:o})};BottomSheet.displayName="BottomSheet";const useMeasuredHeight=()=>{const[e,t]=useState(0),o=useCallback(e=>{t(t=>t===e?t:e)},[]);return[e,useCallback(e=>o(e.nativeEvent.layout.height),[o]),o]},resolveSnapPoints=(e,t,o)=>[...e.map(e=>{if("number"==typeof e)return e;if("content"===e)return o;const s=parseFloat(e);return Number.isNaN(s)?0:s/100*t})].sort((e,t)=>e-t),clamp=(e,t,o)=>Math.min(Math.max(e,t),o),buildStyles=e=>StyleSheet.create({backdropModal:{flex:1},backdropInline:{...StyleSheet.absoluteFill},sheet:{position:"absolute",left:0,right:0,overflow:"hidden"},body:{overflow:"hidden"},handleRow:{alignItems:"center",justifyContent:"center",alignSelf:"stretch",paddingTop:12,paddingBottom:24},header:{},footer:{},handle:{width:36,height:4,borderRadius:2,...smoothCorners},content:{flex:1,overflow:"hidden"},scrollContent:{flex:1},modalRoot:{flex:1}});export{BottomSheet};export default BottomSheet;
|
|
1
|
+
"use strict";import{createContext,forwardRef,useCallback,useContext,useEffect,useImperativeHandle,useMemo,useRef,useState}from"react";import{Dimensions,Modal,Platform,ScrollView,StyleSheet,useWindowDimensions,View}from"react-native";import{Gesture,GestureDetector,GestureHandlerRootView}from"react-native-gesture-handler";import{useReanimatedKeyboardAnimation}from"react-native-keyboard-controller";import Animated,{Easing,runOnJS,useAnimatedStyle,useDerivedValue,useSharedValue,withSpring,withTiming}from"react-native-reanimated";import{useSafeAreaInsets}from"react-native-safe-area-context";import{useTheme}from"../../theme/index.js";import{triggerHaptic}from"../../utils/index.js";import{smoothCorners}from"../../utils/corners.js";import{ModalSafeArea,useModalInsets}from"../ModalSafeArea/ModalSafeArea.js";import{ToastHost}from"../Toast/ToastProvider.js";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const TABLET_MIN_SHORT_SIDE=600,DIALOG_MAX_WIDTH=560,BottomSheetContext=createContext(null);export const useBottomSheet=()=>{const e=useContext(BottomSheetContext);if(!e)throw new Error("useBottomSheet must be used inside a <BottomSheet>.");return e};const SPRING_CONFIG={damping:20,stiffness:240,mass:1},CLOSE_VELOCITY_THRESHOLD=1e3,DRAG_ACTIVATION_OFFSET=10,BottomSheet=forwardRef((e,t)=>{const{snapPoints:o,index:s,onChange:n,onAnimate:r,onAfterClose:a,enablePanDownToClose:l=!0,enableBackdropPress:i=!0,confirmDismiss:u,scrollable:c=!1,scrollRef:d,onScroll:h,onContentSizeChange:m,onScrollLayout:f,scrollEventThrottle:b,keyboardBehavior:S="shift",mode:p="modal",presentation:g="sheet",handleIndicatorStyle:y,containerStyle:v,header:w,footer:x,headerStyle:C,footerStyle:k,children:R,accessibilityLabel:M,accessibilityViewIsModal:I,testID:_}=e,j=useTheme(),T=useSafeAreaInsets(),[V,D]=useState(()=>Dimensions.get("window").height),[O,A]=useState(()=>Dimensions.get("window").width),H=useCallback(e=>{const{height:t,width:o}=e.nativeEvent.layout;t>0&&D(e=>e===t?e:t),o>0&&A(e=>e===o?e:o)},[]),B=useWindowDimensions(),E="dialog"===g||"auto"===g&&Math.min(B.width,B.height)>=600,P=Math.min(560,O-2*j.spacing.xl),[G,L]=useModalInsets(),N="modal"===p?G.top:T.top,F="modal"===p?G.bottom:T.bottom,J=o.includes("content"),[z,Y]=useMeasuredHeight(),[$,q]=useMeasuredHeight(),[W,K,X]=useMeasuredHeight(),[U,Q]=useMeasuredHeight(),Z=E?j.spacing.md:z,ee=J?Math.min(Z+(null!=w?$:0)+W+(null!=x?U:0)+F,V-N):0,te=useCallback((e,t)=>{J&&X(t),m?.(e,t)},[J,m,X]),oe=useMemo(()=>resolveSnapPoints(o,V,ee),[o,V,ee]),se=V,ne=oe[oe.length-1]??0,re=useSharedValue(se),ae=useSharedValue(se),le=useSharedValue(-1),[ie,ue]=useState(-1),ce=useRef(!1),[de,he]=useState(!1),[me,fe]=useState(!1),be=useRef(!1),Se=useRef(a);Se.current=a;const[pe,ge]=useState(!1),ye=useRef(-1),ve=useRef(!1);ve.current="modal"===p?me:pe;const we=useRef(u);we.current=u;const xe=useRef(!1),Ce=useRef(!0),ke=useRef([]),Re=useCallback(e=>{const t=ke.current;ke.current=[];for(const o of t)o(e)},[]);useEffect(()=>(Ce.current=!0,()=>{Ce.current=!1,Re(!1)}),[Re]);const Me=useCallback(e=>{if(e<0||e>=oe.length)return se;const t=oe[e];return E?(V-t)/2:V-t},[oe,V,se,E]),Ie=useCallback(e=>{ye.current=e;ie!==e&&(ue(e),le.value=e,n?.(e))},[ie,le,n]),je=useCallback(()=>{ce.current=!1,le.value<0&&(be.current=!0,"modal"===p?(he(!1),"ios"!==Platform.OS&&fe(!1)):ge(!1))},[p,le]),Te=useCallback(()=>{be.current&&fe(!1)},[]);useEffect(()=>{("modal"===p?!me:!pe)&&be.current&&(be.current=!1,Se.current?.(),Re(!0))},[p,me,pe,Re]);const Ve=useCallback((e,t,o)=>{ce.current=!0,r?.(t,o),re.value=withSpring(e,SPRING_CONFIG,e=>{"worklet";e&&runOnJS(je)()})},[r,re,je]),De=useCallback(e=>{const t="number"==typeof e?clamp(e,0,oe.length-1):ie>=0?ie:0,o=le.value,s=Me(t);be.current=!1,Re(!1),"modal"===p?(fe(!0),he(!0)):ge(!0),o<0&&(re.value=se),Ie(t),Ve(s,o,t)},[Ve,se,ie,le,p,oe.length,Ie,Re,re,Me]),Oe=useCallback(()=>{if(0===oe.length)return;const e=le.value,t=Me(0);Ie(0),Ve(t,e,0)},[Ve,le,oe.length,Ie,Me]),Ae=useCallback(()=>new Promise(e=>{if(ye.current<0)return void(ve.current?ke.current.push(e):e(!0));ke.current.push(e);const t=le.value;Ie(-1),ce.current=!0,r?.(t,-1),re.value=withTiming(se,{duration:j.motion.duration.fast,easing:Easing.bezier(...j.motion.easing.accelerate)},e=>{"worklet";e&&runOnJS(je)()})}),[se,le,je,r,Ie,re,j.motion.duration.fast,j.motion.easing.accelerate]),He=useCallback(async()=>{await Ae()},[Ae]),Be=useCallback((e,t,o)=>{const s=we.current;if(!s)return void e();if(xe.current)return void t?.();const n=s();"boolean"!=typeof n?(xe.current=!0,o?.(),n.then(o=>{xe.current=!1,o&&Ce.current&&ye.current>=0?e():t?.()},e=>{throw xe.current=!1,e})):(n?e:t)?.()},[]),Ee=useCallback(()=>new Promise(e=>{ye.current<0?Ae().then(e):Be(()=>{Ae().then(e)},()=>e(!1))}),[Ae,Be]),Pe=useCallback(()=>{Be(()=>{He()})},[He,Be]);useImperativeHandle(t,()=>({expand:De,collapse:Oe,close:He,requestClose:Ee}),[De,Oe,He,Ee]),useEffect(()=>{"number"==typeof s&&s!==ie&&(-1===s?He():De(s))},[s]);const Ge=useRef({hostHeight:V,contentSnap:ee});useEffect(()=>{const e=Ge.current;e.hostHeight===V&&e.contentSnap===ee||(Ge.current={hostHeight:V,contentSnap:ee},e.hostHeight===V&&le.value<0||(re.value=withSpring(Me(le.value),SPRING_CONFIG)))},[V,ee]);const Le=V-ne,Ne=useMemo(()=>oe.map(e=>V-e),[oe,V]),Fe=useCallback(()=>{const e=ye.current;e<0||Ve(Me(e),e,e)},[Ve,Me]),Je=useCallback((e,t)=>{const o=le.value;-1!==e?(Ie(e),Ve(t,o,e)):Be(()=>{triggerHaptic("selection"),He()},Fe,Fe)},[Ve,He,le,Be,Ie,Fe]),ze=useMemo(()=>Gesture.Native().withTestId(_?`${_}-content-gesture`:"bottom-sheet-content-gesture"),[_]),Ye=useMemo(()=>{const e=Ne,t=se,o=Le,s=l;return Gesture.Pan().withTestId(_?`${_}-pan-gesture`:"bottom-sheet-pan-gesture").activeOffsetY([-10,10]).failOffsetX([-15,15]).onStart(()=>{"worklet";ae.value=re.value}).onUpdate(e=>{"worklet";const t=ae.value+e.translationY;re.value=t<o?o+.25*(t-o):t}).onEnd(o=>{"worklet";const n=re.value;if(o.velocityY>1e3)return s?void runOnJS(Je)(-1,t):void runOnJS(Je)(0,e[0]);let r=0,a=Math.abs(n-e[0]);for(let t=1;t<e.length;t++){const o=Math.abs(n-e[t]);o<a&&(a=o,r=t)}const l=e[0];s&&n-l>80?runOnJS(Je)(-1,t):runOnJS(Je)(r,e[r])})},[se,ae,l,Je,Le,Ne,_,re]),{height:$e}=useReanimatedKeyboardAnimation(),qe="shift"===S,We=useDerivedValue(()=>qe?$e.value:0),Ke=oe[ie>=0?ie:0]??ne,Xe=j.spacing.md,Ue=useAnimatedStyle(()=>{if(E){const e=We.value,t=V+e-Ke-Xe,o=e<0&&re.value>t?t:re.value;return{top:o<N?N:o}}const e=re.value+We.value,t=We.value<0?N:Le;return{top:e<t?t:e}}),Qe=useAnimatedStyle(()=>{const e=We.value;if(E){const t=V+e-Ke-Xe,o=e<0&&re.value>t?t:re.value,s=V+e-Xe-(o<N?N:o);return{height:s<0?0:s>Ke?Ke:s}}const t=e<0?N:Le,o=re.value+e,s=V+e-(o<t?t:o);return{height:s<0?0:s>ne?ne:s}}),Ze=ie>=0,et=useMemo(()=>buildStyles(j),[j]),tt=useCallback(()=>{i&&Be(()=>{triggerHaptic("selection"),He()})},[i,He,Be]),ot=useMemo(()=>Gesture.Tap().withTestId(_?`${_}-backdrop-gesture`:"bottom-sheet-backdrop-gesture").maxDuration(250).onEnd((_e,e)=>{"worklet";e&&runOnJS(tt)()}),[tt,_]),st=useMemo(()=>({snapIndex:ie,snapPoints:oe,expand:De,collapse:Oe,close:He,requestClose:Ee}),[ie,oe,De,Oe,He,Ee]);if("inline"===p&&!pe)return null;if("modal"===p&&!me)return null;const nt=_jsxs(View,{collapsable:!1,style:["modal"===p?et.backdropModal:et.backdropInline,{backgroundColor:j.colors.background.overlay}],onLayout:H,testID:_,accessibilityViewIsModal:I??Ze,children:[_jsx(GestureDetector,{gesture:ot,children:_jsx(Animated.View,{style:StyleSheet.absoluteFill,accessibilityRole:"button",accessibilityLabel:"Close bottom sheet"})}),_jsx(Animated.View,{accessibilityRole:"alert",accessibilityLabel:M,accessibilityViewIsModal:I??Ze,style:[et.sheet,{height:ne,backgroundColor:j.colors.background.elevated,borderTopLeftRadius:j.radius["2xl"],borderTopRightRadius:j.radius["2xl"],...smoothCorners,...j.shadows.xl},E?{height:Ke,left:(O-P)/2,right:void 0,width:P,borderBottomLeftRadius:j.radius["2xl"],borderBottomRightRadius:j.radius["2xl"]}:null,v,Ue],children:_jsxs(SheetBody,{style:[et.body,Qe],keyboardOffset:We,children:[E?_jsx(View,{style:{height:j.spacing.md}}):_jsx(GestureDetector,{gesture:Ye,children:_jsx(View,{style:et.handleRow,onLayout:J?Y:void 0,accessible:!0,accessibilityLabel:"Drag handle",accessibilityHint:"Drag up or down to resize the sheet, or swipe down to close it",testID:_?`${_}-handle`:"bottom-sheet-handle",children:_jsx(View,{style:[et.handle,{backgroundColor:j.components.bottomSheet?.handleColor??j.colors.border.primary},y]})})}),null!=w&&_jsx(View,{style:[et.header,C],onLayout:J?q:void 0,children:w}),c?_jsx(GestureDetector,{gesture:ze,children:_jsx(ScrollView,{ref:d,style:et.scrollContent,onScroll:h,onContentSizeChange:te,onLayout:f,scrollEventThrottle:b,keyboardShouldPersistTaps:"always",keyboardDismissMode:"none",children:R})}):_jsx(View,{style:et.content,children:J?_jsx(View,{onLayout:K,children:R}):R}),null!=x&&_jsx(View,{style:[et.footer,k],onLayout:J?Q:void 0,children:x})]})})]}),rt=_jsx(BottomSheetContext.Provider,{value:st,children:nt});return"modal"===p?_jsx(Modal,{transparent:!0,visible:de,onRequestClose:Pe,onDismiss:"ios"===Platform.OS?Te:void 0,statusBarTranslucent:!0,navigationBarTranslucent:!0,animationType:"none",supportedOrientations:["portrait","landscape"],children:_jsxs(ModalSafeArea,{onInsets:L,children:["android"===Platform.OS?_jsx(GestureHandlerRootView,{style:et.modalRoot,children:rt}):rt,_jsx(ToastHost,{})]})}):rt}),SheetBody=({style:e,keyboardOffset:t,children:o})=>{const s=useSafeAreaInsets().bottom,n=useAnimatedStyle(()=>{const e=s+t.value;return{paddingBottom:e>0?e:0}});return _jsx(Animated.View,{style:[e,n],children:o})};BottomSheet.displayName="BottomSheet";const useMeasuredHeight=()=>{const[e,t]=useState(0),o=useCallback(e=>{t(t=>t===e?t:e)},[]);return[e,useCallback(e=>o(e.nativeEvent.layout.height),[o]),o]},resolveSnapPoints=(e,t,o)=>[...e.map(e=>{if("number"==typeof e)return e;if("content"===e)return o;const s=parseFloat(e);return Number.isNaN(s)?0:s/100*t})].sort((e,t)=>e-t),clamp=(e,t,o)=>Math.min(Math.max(e,t),o),buildStyles=e=>StyleSheet.create({backdropModal:{flex:1},backdropInline:{...StyleSheet.absoluteFill},sheet:{position:"absolute",left:0,right:0,overflow:"hidden"},body:{overflow:"hidden"},handleRow:{alignItems:"center",justifyContent:"center",alignSelf:"stretch",paddingTop:12,paddingBottom:24},header:{},footer:{},handle:{width:36,height:4,borderRadius:2,...smoothCorners},content:{flex:1,overflow:"hidden"},scrollContent:{flex:1},modalRoot:{flex:1}});export{BottomSheet};export default BottomSheet;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import React,{forwardRef,useMemo}from"react";import{Animated,Image,Pressable,StyleSheet,View}from"react-native";import{useControllableState}from"../../hooks/useControllableState.js";import{usePressAnimation}from"../../hooks/usePressAnimation.js";import{Gradient,useTheme}from"../../theme/index.js";import{smoothCorners}from"../../utils/corners.js";import{resolveHaptic,triggerHaptic}from"../../utils/hapticUtils.js";import{mergeRefs}from"../../utils/mergeRefs.js";import{supportsBoxShadow,toBoxShadow}from"../../utils/shadows.js";import{squircleHostRadius}from"../../utils/squircle.js";import{AppIcon}from"../AppIcon/AppIcon.js";import{useContextMenu}from"../Menu/useContextMenu.js";import{Skeleton,SkeletonText}from"../Skeleton/index.js";import{SquircleFill,useSquircle}from"../SquircleFill/SquircleFill.js";import{Text}from"../Text/index.js";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";const paddingMap={none:"none",sm:"sm",md:"lg",lg:"xl",xl:"2xl"},Card=forwardRef((e,t)=>{const{children:o,variant:i="elevated",elevation:r="sm",radius:s="lg",padding:l="md",interactive:a=!1,bg:n,header:d,title:c,lead:u,action:h,headerActions:m,collapsible:p=!1,collapsed:g,defaultCollapsed:b=!1,onCollapsedChange:y,collapsedSummary:x,onRemove:f,removeLabel:S="Remove",separatorHeight:v=StyleSheet.hairlineWidth,footer:j,imageSource:w,imageHeight:C=160,imageAspectRatio:_,imageOverlay:R,loading:k=!1,gradient:A,onPress:T,haptic:B,contextMenu:H,accessibilityLabel:I,accessibilityHint:L,accessibilityRole:P,style:V,containerStyle:F,headerStyle:M,bodyStyle:z,footerStyle:q,borderRadius:W,testID:D,onLayout:O,...E}=e,N=useTheme(),G=a||"function"==typeof T,$=useContextMenu(H,{haptic:B,testID:D,accessibilityActions:E.accessibilityActions,onAccessibilityAction:E.onAccessibilityAction}),U=useMemo(()=>mergeRefs(t,$.hostRef),[t,$.hostRef]),J=G||$.enabled,{scale:K,pressIn:Q,pressOut:X}=usePressAnimation({enabled:J}),Y=useMemo(()=>buildStyles(N),[N]),Z=Boolean(w),ee=N.spacing[paddingMap[l]],te=useMemo(()=>A?"string"==typeof A?N.gradients[A]??null:A:null,[A,N.gradients]),oe="flat"===i,ie=oe?0:W??N.radius[s],re=resolveBackground(N,n),[se,le]=useControllableState({value:g,defaultValue:b,onChange:y}),ae=p&&se,ne=hasBuiltInHeaderContent(e),de=Boolean(d)||ne,ce=useSquircle(!Z&&!te&&!oe,ie,O),ue=StyleSheet.flatten([V,F])??{},he=ue.backgroundColor,me=ue.borderColor,pe=he??re??("filled"===i?N.colors.background.secondary:N.colors.background.elevated),ge="outlined"===i?N.colors.border.width:0,be=me??N.colors.border.primary,ye="elevated"===i&&supportsBoxShadow()?toBoxShadow(N.shadows[r]):void 0,xe=ce.active&&"elevated"===i&&!ye,fe=ce.active&&!xe?{backgroundColor:"transparent",borderColor:"transparent"}:null,Se=useMemo(()=>{const e={borderRadius:xe&&ce.size?squircleHostRadius(ce.size.width,ce.size.height,ie):ie,...smoothCorners,padding:Z?0:ee,overflow:ce.active?"visible":"hidden"};switch(i){case"flat":return{...e,backgroundColor:re??N.colors.background.elevated,borderBottomWidth:v,borderBottomColor:N.colors.border.primary};case"outlined":return{...e,backgroundColor:ce.active?"transparent":re??N.colors.background.elevated,borderWidth:N.colors.border.width,borderColor:ce.active?"transparent":N.colors.border.primary};case"filled":return{...e,backgroundColor:ce.active?"transparent":re??N.colors.background.secondary};default:return{...e,backgroundColor:re??N.colors.background.elevated,...ye?{boxShadow:ye}:N.shadows[r]}}},[N,i,r,ie,Z,ee,ce.active,ce.size,ye,xe,re,v]),ve=useMemo(()=>({..."number"==typeof _?{width:"100%",aspectRatio:_}:{width:"100%",height:C},borderTopLeftRadius:ie,borderTopRightRadius:ie,borderBottomLeftRadius:0,borderBottomRightRadius:0,...smoothCorners}),[ie,_,C]),je="string"==typeof c?c:"",we=_jsxs(_Fragment,{children:[_jsxs(View,{style:Y.titleColumn,children:["string"==typeof c?_jsx(Text,{variant:"title",accessibilityRole:"header",children:c}):c,u?_jsx(Text,{variant:"bodySmall",style:Y.lead,children:u}):null,ae&&x?_jsx(Text,{variant:"caption",style:Y.lead,children:x}):null]}),isCardTextAction(h)?_jsx(CardTextActionButton,{action:h,haptic:B}):h?_jsx(View,{style:Y.actionNode,children:h}):null,m,p?_jsx(CardIconAction,{icon:ae?"chevron-down":"chevron-up",label:`${ae?"Show":"Hide"} ${je}`.trim(),expanded:!ae,onPress:()=>le(!ae),haptic:B}):null,f?_jsx(CardIconAction,{icon:"trash",label:S,onPress:f,color:N.colors.toneText.error,haptic:B}):null]}),Ce=_jsxs(_Fragment,{children:[de?_jsx(View,{style:[Y.header,!d&&Y.headerRow,ae&&Y.headerFolded,M],children:d??we}):null,ae?null:_jsx(View,{style:[de||j?Y.body:null,z],children:o}),j&&!ae?_jsx(View,{style:[Y.footer,q],children:j}):null]}),
|
|
1
|
+
"use strict";import React,{forwardRef,useMemo}from"react";import{Animated,Image,Pressable,StyleSheet,View}from"react-native";import{useControllableState}from"../../hooks/useControllableState.js";import{usePressAnimation}from"../../hooks/usePressAnimation.js";import{Gradient,useTheme}from"../../theme/index.js";import{smoothCorners}from"../../utils/corners.js";import{resolveHaptic,triggerHaptic}from"../../utils/hapticUtils.js";import{mergeRefs}from"../../utils/mergeRefs.js";import{supportsBoxShadow,toBoxShadow}from"../../utils/shadows.js";import{squircleHostRadius}from"../../utils/squircle.js";import{AppIcon}from"../AppIcon/AppIcon.js";import{useContextMenu}from"../Menu/useContextMenu.js";import{Skeleton,SkeletonText}from"../Skeleton/index.js";import{SquircleFill,useSquircle}from"../SquircleFill/SquircleFill.js";import{Text}from"../Text/index.js";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";const paddingMap={none:"none",sm:"sm",md:"lg",lg:"xl",xl:"2xl"},Card=forwardRef((e,t)=>{const{children:o,variant:i="elevated",elevation:r="sm",radius:s="lg",padding:l="md",interactive:a=!1,bg:n,header:d,title:c,lead:u,action:h,headerActions:m,collapsible:p=!1,collapsed:g,defaultCollapsed:b=!1,onCollapsedChange:y,collapsedSummary:x,onRemove:f,removeLabel:S="Remove",separatorHeight:v=StyleSheet.hairlineWidth,footer:j,imageSource:w,imageHeight:C=160,imageAspectRatio:_,imageOverlay:R,loading:k=!1,gradient:A,onPress:T,haptic:B,contextMenu:H,accessibilityLabel:I,accessibilityHint:L,accessibilityRole:P,style:V,containerStyle:F,headerStyle:M,bodyStyle:z,footerStyle:q,borderRadius:W,testID:D,onLayout:O,...E}=e,N=useTheme(),G=a||"function"==typeof T,$=useContextMenu(H,{haptic:B,testID:D,accessibilityActions:E.accessibilityActions,onAccessibilityAction:E.onAccessibilityAction}),U=useMemo(()=>mergeRefs(t,$.hostRef),[t,$.hostRef]),J=G||$.enabled,{scale:K,pressIn:Q,pressOut:X}=usePressAnimation({enabled:J}),Y=useMemo(()=>buildStyles(N),[N]),Z=Boolean(w),ee=N.spacing[paddingMap[l]],te=useMemo(()=>A?"string"==typeof A?N.gradients[A]??null:A:null,[A,N.gradients]),oe="flat"===i,ie=oe?0:W??N.radius[s],re=resolveBackground(N,n),[se,le]=useControllableState({value:g,defaultValue:b,onChange:y}),ae=p&&se,ne=hasBuiltInHeaderContent(e),de=Boolean(d)||ne,ce=useSquircle(!Z&&!te&&!oe,ie,O),ue=StyleSheet.flatten([V,F])??{},he=ue.backgroundColor,me=ue.borderColor,pe=he??re??("filled"===i?N.colors.background.secondary:N.colors.background.elevated),ge="outlined"===i?N.colors.border.width:0,be=me??N.colors.border.primary,ye="elevated"===i&&supportsBoxShadow()?toBoxShadow(N.shadows[r]):void 0,xe=ce.active&&"elevated"===i&&!ye,fe=ce.active&&!xe?{backgroundColor:"transparent",borderColor:"transparent"}:null,Se=useMemo(()=>{const e={borderRadius:xe&&ce.size?squircleHostRadius(ce.size.width,ce.size.height,ie):ie,...smoothCorners,padding:Z?0:ee,overflow:ce.active?"visible":"hidden"};switch(i){case"flat":return{...e,backgroundColor:re??N.colors.background.elevated,borderBottomWidth:v,borderBottomColor:N.colors.border.primary};case"outlined":return{...e,backgroundColor:ce.active?"transparent":re??N.colors.background.elevated,borderWidth:N.colors.border.width,borderColor:ce.active?"transparent":N.colors.border.primary};case"filled":return{...e,backgroundColor:ce.active?"transparent":re??N.colors.background.secondary};default:return{...e,backgroundColor:re??N.colors.background.elevated,...ye?{boxShadow:ye}:N.shadows[r]}}},[N,i,r,ie,Z,ee,ce.active,ce.size,ye,xe,re,v]),ve=useMemo(()=>({..."number"==typeof _?{width:"100%",aspectRatio:_}:{width:"100%",height:C},borderTopLeftRadius:ie,borderTopRightRadius:ie,borderBottomLeftRadius:0,borderBottomRightRadius:0,...smoothCorners}),[ie,_,C]),je="string"==typeof c?c:"",we=_jsxs(_Fragment,{children:[_jsxs(View,{style:Y.titleColumn,children:["string"==typeof c?_jsx(Text,{variant:"title",accessibilityRole:"header",children:c}):c,u?_jsx(Text,{variant:"bodySmall",style:Y.lead,children:u}):null,ae&&x?_jsx(Text,{variant:"caption",style:Y.lead,children:x}):null]}),isCardTextAction(h)?_jsx(CardTextActionButton,{action:h,haptic:B}):h?_jsx(View,{style:Y.actionNode,children:h}):null,m,p?_jsx(CardIconAction,{icon:ae?"chevron-down":"chevron-up",label:`${ae?"Show":"Hide"} ${je}`.trim(),expanded:!ae,onPress:()=>le(!ae),haptic:B}):null,f?_jsx(CardIconAction,{icon:"trash",label:S,onPress:f,color:N.colors.toneText.error,haptic:B}):null]}),Ce=_jsxs(_Fragment,{children:[de?_jsx(View,{style:[Y.header,!d&&Y.headerRow,ae&&Y.headerFolded,M],children:d??we}):null,ae?null:_jsx(View,{style:[de||j?Y.body:null,z],children:o}),j&&!ae?_jsx(View,{style:[Y.footer,q],children:j}):null]}),Re=Z?_jsxs(_Fragment,{children:[_jsxs(View,{style:Y.imageWrapper,children:[_jsx(Image,{source:w,resizeMode:"cover",style:ve,accessibilityLabel:"",accessible:!1}),R?_jsx(View,{pointerEvents:"box-none",style:Y.imageOverlay,children:R}):null]}),_jsx(View,{style:{padding:ee},children:Ce})]}):Ce,ke=te?_jsxs(_Fragment,{children:[_jsx(Gradient,{gradient:te,style:StyleSheet.absoluteFill}),Re]}):ce.active&&ce.size?_jsxs(_Fragment,{children:[_jsx(SquircleFill,{width:ce.size.width,height:ce.size.height,radius:ie,fill:pe,stroke:ge?be:void 0,strokeWidth:ge,outset:ge}),Re]}):Re;let Ae;if(J){const handlePress=e=>{if(!G)return;const t=resolveHaptic(B,"selection");t&&triggerHaptic(t),T?.(e)};Ae=_jsx(Animated.View,{style:[{transform:[{scale:K}]}],children:_jsx(Pressable,{ref:U,onPress:handlePress,onPressIn:Q,onPressOut:X,android_ripple:{color:N.colors.surface.pressed,borderless:!1},accessibilityRole:P??(G?"button":void 0),accessibilityLabel:I,accessibilityHint:L,testID:D,onLayout:ce.onLayout,style:[Se,V,F,fe],...E,...$.hostProps,children:ke})})}else Ae=_jsx(View,{ref:t,accessibilityLabel:I,accessibilityHint:L,accessibilityRole:P,testID:D,onLayout:ce.onLayout,style:[Se,V,F,fe],...E,children:ke});return k?_jsx(CardSkeleton,{...e}):$.enabled?_jsxs(_Fragment,{children:[Ae,$.renderSurface(_jsx(View,{style:[Se,V,F,fe,Y.preview],children:ke}))]}):Ae});Card.displayName="Card";const CardSkeleton=({variant:e="elevated",elevation:t,radius:o="lg",padding:i="md",bg:r,header:s,footer:l,imageSource:a,imageHeight:n=160,imageAspectRatio:d,borderRadius:c,containerStyle:u,headerStyle:h,bodyStyle:m,footerStyle:p,style:g,...b})=>{const y=useTheme(),x=paddingMap[i],f=y.spacing[x],S="flat"===e?0:c??y.radius[o],v=void 0!==s||hasBuiltInHeaderContent(b),j=resolveBackground(y,r)??y.colors.background.elevated,w="outlined"===e?1:0,C="outlined"===e?y.colors.border.primary:void 0;return _jsxs(View,{style:[{backgroundColor:j,borderRadius:S,...smoothCorners,borderWidth:w,borderColor:C,overflow:"hidden"},u,g],accessibilityRole:"progressbar",accessibilityLabel:"Loading",accessibilityState:{busy:!0},"aria-busy":!0,children:[void 0!==a?_jsx(Skeleton,{width:"100%",height:d?void 0:n,style:d?{aspectRatio:d,width:"100%"}:void 0}):null,v?_jsx(View,{style:[{padding:f,paddingBottom:y.spacing.sm},h],children:_jsx(Skeleton,{shape:"text",width:"60%",height:18})}):null,_jsx(View,{style:[{padding:f},m],children:_jsx(SkeletonText,{lines:3,fontSize:14,lastLineWidth:"55%"})}),void 0!==l?_jsx(View,{style:[{padding:f,paddingTop:y.spacing.sm,flexDirection:"row"},p],children:_jsx(Skeleton,{width:88,height:32,shape:"rounded"})}):null]})};CardSkeleton.displayName="CardSkeleton",Card.Skeleton=CardSkeleton;const hasBuiltInHeaderContent=e=>Boolean(e.title||e.lead||e.action||e.headerActions||e.collapsible||e.onRemove),isCardTextAction=e=>"object"==typeof e&&null!==e&&!React.isValidElement(e)&&"label"in e&&"onPress"in e,HIT_TARGET=44,CardIconAction=({icon:e,label:t,onPress:o,expanded:i,color:r,haptic:s})=>{const l=useTheme();return _jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:t,accessibilityState:void 0===i?void 0:{expanded:i},"aria-expanded":i,onPress:()=>{const e=resolveHaptic(s,"selection");e&&triggerHaptic(e),o()},style:iconActionStyle,children:_jsx(AppIcon,{name:e,size:20,color:r??l.colors.text.primary})})},CardTextActionButton=({action:e,haptic:t})=>{const o=useTheme();return _jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:e.accessibilityLabel??e.label,onPress:()=>{const o=resolveHaptic(t,"selection");o&&triggerHaptic(o),e.onPress()},style:textActionStyle,children:_jsx(Text,{variant:"label",weight:"semibold",color:o.colors.primary,children:e.label})})},iconActionStyle={width:44,height:44,alignItems:"center",justifyContent:"center"},textActionStyle={minWidth:44,minHeight:44,alignItems:"center",justifyContent:"center"},resolveBackground=(e,t)=>{if(null==t)return;return e.colors.background[t]??t},buildStyles=e=>StyleSheet.create({header:{marginBottom:e.spacing.md},headerRow:{flexDirection:"row",alignItems:"center",gap:e.spacing.sm},headerFolded:{marginBottom:0},titleColumn:{flex:1},lead:{marginTop:e.spacing.xs},actionNode:{flexShrink:0},body:{flexShrink:1},footer:{marginTop:e.spacing.md},imageWrapper:{position:"relative"},imageOverlay:{...StyleSheet.absoluteFill},preview:{margin:0,marginTop:0,marginBottom:0,marginLeft:0,marginRight:0,marginStart:0,marginEnd:0,marginHorizontal:0,marginVertical:0,position:"relative",top:0,left:0,width:"100%",height:"100%"}});export{Card};export default Card;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{useCallback,useEffect,useMemo,useRef,useState}from"react";import{AccessibilityInfo,Animated,Easing,Modal,Pressable,StyleSheet,Text,View}from"react-native";import{GestureDetector,GestureHandlerRootView}from"react-native-gesture-handler";import{useSafeAreaInsets}from"react-native-safe-area-context";import{useDragToDismiss}from"../../hooks/useDragToDismiss.js";import{createAnimatedValue,setNativeValue,useTheme}from"../../theme/index.js";import{resolveHaptic,triggerHaptic}from"../../utils/index.js";import{smoothCorners}from"../../utils/corners.js";import{defaultIcons}from"../AppIcon/defaultIcons.js";import{PickerTrigger}from"../PickerTrigger/index.js";import{ToastHost}from"../Toast/ToastProvider.js";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";const GRID_SIZE=12,DECADE_SPAN=10,startOfDay=e=>new Date(e.getFullYear(),e.getMonth(),e.getDate()),isSameDay=(e,t)=>e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate(),toIso=e=>`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`,addMonths=(e,t)=>new Date(e.getFullYear(),e.getMonth()+t,1),buildMonthMatrix=(e,t)=>{const a=e.getFullYear(),r=e.getMonth(),i=(new Date(a,r,1).getDay()-t+7)%7,s=[];for(let e=0;e<42;e+=1){const t=new Date(a,r,1-i+e);s.push({date:t,inMonth:t.getMonth()===r,iso:toIso(t)})}return s},weekdayLabels=(e,t)=>{const a=new Intl.DateTimeFormat(e,{weekday:"short"}),r=[];for(let e=0;e<7;e+=1){const i=new Date(1970,0,4+(t+e)%7);r.push(a.format(i))}return r},formatMonthYear=(e,t)=>new Intl.DateTimeFormat(t,{month:"long",year:"numeric"}).format(e),formatLongDate=(e,t)=>new Intl.DateTimeFormat(t,{weekday:"long",year:"numeric",month:"long",day:"numeric"}).format(e),decadeStartFor=e=>10*Math.floor(e/10),buildYearCells=e=>{const t=e-4;return Array.from({length:12},(e,a)=>t+a)},buildDecadeCells=e=>{const t=decadeStartFor(e)-40;return Array.from({length:12},(e,a)=>t+10*a)},DatePicker=e=>{const{value:t,onChange:a,onClose:r,minDate:i,maxDate:s,disabledDates:o,mode:n="modal",locale:l="en-IN",weekStartsOn:c=0,title:d="Select Date",confirmLabel:u="Confirm",cancelLabel:g="Cancel",style:m,containerStyle:y,headerLabelStyle:p,navButtonStyle:h,footerButtonStyle:f,haptic:b,testID:x,label:D,placeholder:w,helperText:v,error:C,required:S,disabled:j,size:k,variant:P,clearable:T,onClear:V,formatValue:_,triggerStyle:R}=e,A=void 0!==e.visible,[I,M]=useState(!1),F=A?e.visible:I,L=A?x:x?`${x}-calendar`:void 0,B=useTheme(),Y=useSafeAreaInsets(),z=useMemo(()=>buildStyles(B),[B]),[H,N]=useState(()=>startOfDay(new Date));useEffect(()=>{F&&N(startOfDay(new Date))},[F]);const $=t?startOfDay(t):H,[W,E]=useState($),[O,G]=useState(t?startOfDay(t):null),[q,X]=useState("days"),Z=useRef(createAnimatedValue(0)).current,J=useRef(createAnimatedValue(0)).current,K=useRef(createAnimatedValue(0)).current,Q=useRef(0),U=useRef(createAnimatedValue(0)).current,ee=useRef(createAnimatedValue(1)).current,te=useRef(createAnimatedValue(1)).current,ae=useRef(createAnimatedValue(1)).current,re=useRef(createAnimatedValue(1)).current,ie=useRef(createAnimatedValue(1)).current;useEffect(()=>{if(t){const e=startOfDay(t);G(e),E(e)}else G(null)},[t]),useEffect(()=>{if("modal"===n&&F){Z.setValue(0),setNativeValue(J,0),setNativeValue(K,0);const e=Animated.parallel([Animated.timing(Z,{toValue:1,duration:B.motion.duration.normal,easing:Easing.out(Easing.cubic),useNativeDriver:!1}),Animated.spring(J,{toValue:1,damping:B.motion.spring.gentle.damping,stiffness:B.motion.spring.gentle.stiffness,mass:B.motion.spring.gentle.mass,useNativeDriver:!0})]);return e.start(),()=>e.stop()}},[F,n,Z,J,K,B.motion]);const se=useMemo(()=>{const e=new Set;return o?.forEach(t=>e.add(toIso(startOfDay(t)))),e},[o]),oe=useMemo(()=>i?startOfDay(i):null,[i]),ne=useMemo(()=>s?startOfDay(s):null,[s]),le=useCallback(e=>!!(oe&&e.getTime()<oe.getTime())||(!!(ne&&e.getTime()>ne.getTime())||!!se.has(toIso(e))),[oe,ne,se]),ce=useMemo(()=>buildMonthMatrix(W,c),[W,c]),de=useMemo(()=>buildYearCells(W.getFullYear()),[W]),ue=useMemo(()=>buildDecadeCells(W.getFullYear()),[W]),ge=useMemo(()=>weekdayLabels(l,c),[l,c]),me=useMemo(()=>{if("days"===q)return formatMonthYear(W,l);if("years"===q){return`${de[0]} - ${de[de.length-1]}`}return`${ue[0]} - ${ue[ue.length-1]+9}`},[W,ue,l,q,de]),ye=useCallback(e=>!!(oe&&e<oe.getFullYear())||!!(ne&&e>ne.getFullYear()),[oe,ne]),pe=useCallback(e=>!!(oe&&e+10-1<oe.getFullYear())||!!(ne&&e>ne.getFullYear()),[oe,ne]),he=useCallback(e=>{!1!==b&&triggerHaptic("impactLight");const t=e>0?1:-1,a=B.components.datePicker?.monthSlideDistance??32,r=B.components.datePicker?.monthSlideOutDuration??B.motion.duration.fast??140,i=B.components.datePicker?.monthSlideInDuration??B.motion.duration.fast??160;Animated.sequence([Animated.parallel([Animated.timing(U,{toValue:-t*a,duration:r,easing:Easing.out(Easing.quad),useNativeDriver:!0}),Animated.timing(ee,{toValue:0,duration:r,useNativeDriver:!0})]),Animated.timing(U,{toValue:t*a,duration:0,useNativeDriver:!0}),Animated.parallel([Animated.timing(U,{toValue:0,duration:i,easing:Easing.out(Easing.cubic),useNativeDriver:!0}),Animated.timing(ee,{toValue:1,duration:i,useNativeDriver:!0})])]).start();const s=addMonths(W,e);E(s),AccessibilityInfo.announceForAccessibility(formatMonthYear(s,l))},[W,b,l,ee,U,B.components.datePicker,B.motion.duration.fast]),fe=useCallback(()=>{"days"!==q?(!1!==b&&triggerHaptic("impactLight"),E("years"===q?e=>new Date(e.getFullYear()-12,e.getMonth(),1):e=>new Date(e.getFullYear()-120,e.getMonth(),1))):he(-1)},[he,q,b]),be=useCallback(()=>{"days"!==q?(!1!==b&&triggerHaptic("impactLight"),E("years"===q?e=>new Date(e.getFullYear()+12,e.getMonth(),1):e=>new Date(e.getFullYear()+120,e.getMonth(),1))):he(1)},[he,q,b]),xe=useCallback(()=>{const e=B.components.datePicker?.viewTransitionDuration??B.motion.duration.normal??200;setNativeValue(ae,0),setNativeValue(re,.9),Animated.parallel([Animated.timing(ae,{toValue:1,duration:e,easing:Easing.out(Easing.cubic),useNativeDriver:!0}),Animated.timing(re,{toValue:1,duration:e,easing:Easing.out(Easing.cubic),useNativeDriver:!0})]).start()},[ae,re,B.components.datePicker,B.motion.duration.normal]),De=useCallback(()=>{const e=resolveHaptic(b,"selection");e&&triggerHaptic(e);const t=B.components.datePicker?.headerPressDuration??80,a=B.components.datePicker?.headerReleaseDuration??100;Animated.sequence([Animated.timing(ie,{toValue:.96,duration:t,useNativeDriver:!0}),Animated.timing(ie,{toValue:1,duration:a,useNativeDriver:!0})]).start(),X(e=>"days"===e?"years":"years"===e?"decades":"years"),xe()},[xe,ie,b,B.components.datePicker]),we=useCallback(e=>{const t=resolveHaptic(b,"selection");t&&triggerHaptic(t),E(t=>new Date(e,t.getMonth(),1)),X("days"),xe()},[xe,b]),ve=useCallback(e=>{const t=resolveHaptic(b,"selection");t&&triggerHaptic(t),E(t=>new Date(e+4,t.getMonth(),1)),X("years"),xe()},[xe,b]),Ce=useCallback(e=>{if(le(e.date))return;const t=resolveHaptic(b,"selection");t&&triggerHaptic(t),G(e.date),e.inMonth||E(new Date(e.date.getFullYear(),e.date.getMonth(),1)),setNativeValue(te,.7),Animated.spring(te,{toValue:1,damping:B.motion.spring.bouncy.damping,stiffness:B.motion.spring.bouncy.stiffness,mass:B.motion.spring.bouncy.mass,useNativeDriver:!0}).start()},[le,te,B.motion.spring.bouncy,b]),Se=useCallback(()=>{A||M(!1),r?.()},[A,r]),je=useCallback(()=>{"modal"===n?Animated.parallel([Animated.timing(Z,{toValue:0,duration:B.motion.duration.fast,easing:Easing.bezier(...B.motion.easing.accelerate),useNativeDriver:!1}),Animated.timing(J,{toValue:0,duration:B.motion.duration.fast,easing:Easing.bezier(...B.motion.easing.accelerate),useNativeDriver:!0})]).start(()=>{Se()}):Se()},[Z,n,Se,J,B.motion.duration.fast,B.motion.easing.accelerate]),{handleGesture:ke}=useDragToDismiss({drag:K,travel:()=>Q.current||320,onDismiss:je}),Pe=useCallback(()=>{!1!==b&&triggerHaptic("selection"),je()},[je,b]),Te=useCallback(()=>{O&&(!1!==b&&triggerHaptic("notificationSuccess"),a?.(O),je())},[je,a,O,b]),Ve=J.interpolate({inputRange:[0,1],outputRange:[320,0]}),_e=_jsx(View,{style:z.titleRow,children:_jsx(Text,{style:z.title,accessibilityRole:"header",children:d})}),Re=_jsxs(View,{style:[z.card,m,y],accessibilityRole:"modal"===n?void 0:"none",accessible:!1,testID:L,children:["modal"===n?_jsx(GestureDetector,{gesture:ke,children:_jsxs(View,{style:z.grabArea,children:[_jsx(View,{style:z.handle}),_e]})}):_e,_jsxs(View,{style:z.headerRow,children:[_jsx(Pressable,{onPress:fe,style:({pressed:e})=>[z.navBtn,e&&z.navBtnPressed,h],accessibilityRole:"button",accessibilityLabel:"days"===q?"Previous month":"years"===q?"Previous years":"Previous decades",hitSlop:8,children:_jsx(Text,{style:z.navText,children:"‹"})}),_jsx(Pressable,{onPress:De,style:[z.headerLabelWrap,p],accessibilityRole:"button",accessibilityLabel:"days"===q?`${me}, switch to year selection`:"years"===q?`${me}, switch to decade selection`:`${me}, switch to year selection`,hitSlop:8,children:_jsxs(Animated.View,{style:[z.headerLabelInner,{transform:[{scale:ie}],opacity:"days"===q?ee:1}],children:[_jsx(Animated.Text,{style:[z.headerLabel,{transform:[{translateX:"days"===q?U:0}]}],accessibilityLiveRegion:"polite",children:me}),_jsx(View,{style:z.headerCaret,children:(B.icons?.chevronDown??defaultIcons.chevronDown)({size:B.typography.fontSize.sm,color:B.colors.text.secondary})})]})}),_jsx(Pressable,{onPress:be,style:({pressed:e})=>[z.navBtn,e&&z.navBtnPressed,h],accessibilityRole:"button",accessibilityLabel:"days"===q?"Next month":"years"===q?"Next years":"Next decades",hitSlop:8,children:_jsx(Text,{style:z.navText,children:"›"})})]}),"days"===q?_jsxs(_Fragment,{children:[_jsx(View,{style:z.weekdayRow,children:ge.map((e,t)=>_jsx(View,{style:z.weekdayCell,children:_jsx(Text,{style:z.weekdayText,children:e})},`${e}-${t}`))}),_jsx(Animated.View,{style:[z.grid,{opacity:ee,transform:[{translateX:U}]}],children:Array.from({length:6}).map((e,t)=>_jsx(View,{style:z.gridRow,children:ce.slice(7*t,7*t+7).map(e=>{const t=le(e.date),a=!!O&&isSameDay(e.date,O),r=isSameDay(e.date,H),i=a?B.colors.primary:"transparent",s=r&&!a?B.colors.primary:"transparent",o=a?B.colors.onPrimary:e.inMonth?t?B.colors.text.disabled:B.colors.text.primary:B.colors.text.tertiary,n=t?.3:e.inMonth?1:.4;return _jsx(Pressable,{disabled:t,onPress:()=>Ce(e),accessibilityRole:"button",accessibilityLabel:formatLongDate(e.date,l),accessibilityState:{selected:a,disabled:t},"aria-selected":a,"aria-disabled":t,style:z.dayCell,children:_jsx(Animated.View,{style:[z.dayInner,{backgroundColor:i,borderColor:s,borderWidth:r&&!a?1.5:0,opacity:n},a?{transform:[{scale:te}]}:null],children:_jsx(Text,{style:[z.dayText,{color:o}],children:e.date.getDate()})})},e.iso)})},`r-${t}`))})]}):_jsx(Animated.View,"years"===q?{style:[z.yearGrid,{opacity:ae,transform:[{scale:re}]}],children:Array.from({length:3}).map((e,t)=>_jsx(View,{style:z.gridRow,children:de.slice(4*t,4*t+4).map(e=>{const t=ye(e),a=!!O&&O.getFullYear()===e,r=H.getFullYear()===e,i=a?B.colors.primary:"transparent",s=r&&!a?B.colors.primary:"transparent",o=a?B.colors.onPrimary:t?B.colors.text.disabled:B.colors.text.primary,n=t?.3:1;return _jsx(Pressable,{disabled:t,onPress:()=>we(e),accessibilityRole:"button",accessibilityLabel:`Year ${e}`,accessibilityState:{selected:a,disabled:t},"aria-selected":a,"aria-disabled":t,style:z.yearCell,children:_jsx(View,{style:[z.yearInner,{backgroundColor:i,borderColor:s,borderWidth:r&&!a?1.5:0,opacity:n}],children:_jsx(Text,{style:[z.yearText,{color:o}],children:e})})},`year-${e}`)})},`yr-${t}`))}:{style:[z.yearGrid,{opacity:ae,transform:[{scale:re}]}],children:Array.from({length:3}).map((e,t)=>_jsx(View,{style:z.gridRow,children:ue.slice(4*t,4*t+4).map(e=>{const t=e+10-1,a=pe(e),r=!!O&&decadeStartFor(O.getFullYear())===e,i=decadeStartFor(H.getFullYear())===e,s=r?B.colors.primary:"transparent",o=i&&!r?B.colors.primary:"transparent",n=r?B.colors.onPrimary:a?B.colors.text.disabled:B.colors.text.primary,l=a?.3:1;return _jsx(Pressable,{disabled:a,onPress:()=>ve(e),accessibilityRole:"button",accessibilityLabel:`Decade ${e} to ${t}`,accessibilityState:{selected:r,disabled:a},"aria-selected":r,"aria-disabled":a,style:z.yearCell,children:_jsxs(View,{style:[z.yearInner,{backgroundColor:s,borderColor:o,borderWidth:i&&!r?1.5:0,opacity:l}],children:[_jsx(Text,{style:[z.yearText,{color:n}],children:`${e}s`}),_jsx(Text,{style:[z.decadeRangeText,{color:r?B.colors.onPrimary:B.colors.text.tertiary}],children:`${e}-${t}`})]})},`decade-${e}`)})},`dec-${t}`))}),_jsxs(View,{style:z.footer,children:[_jsx(Pressable,{onPress:Pe,style:({pressed:e})=>[z.footerBtn,z.footerCancel,e&&z.footerBtnPressed,f],accessibilityRole:"button",accessibilityLabel:g,children:_jsx(Text,{style:[z.footerBtnText,{color:B.colors.text.secondary}],children:g})}),_jsx(Pressable,{onPress:Te,disabled:!O,style:({pressed:e})=>[z.footerBtn,z.footerConfirm,{backgroundColor:B.colors.primary,opacity:O?1:.5},e&&{backgroundColor:B.colors.primaryHover},f],accessibilityRole:"button",accessibilityLabel:u,accessibilityState:{disabled:!O},"aria-disabled":!O,children:_jsx(Text,{style:[z.footerBtnText,{color:B.colors.onPrimary}],children:u})})]})]}),Ae=t?(_??(e=>e.toLocaleDateString()))(t):void 0,Ie=!A;if("inline"===n)return F||Ie?Ie?_jsxs(_Fragment,{children:[_jsx(PickerTrigger,{label:D,value:Ae,placeholder:w,helperText:v,error:C,required:S,disabled:j,size:k,variant:P,clearable:T,onClear:V,onPress:()=>M(!0),triggerStyle:R,testID:x}),F?Re:null]}):Re:null;const Me=_jsx(Modal,{visible:F,transparent:!0,statusBarTranslucent:!0,navigationBarTranslucent:!0,animationType:"none",onRequestClose:je,children:_jsxs(GestureHandlerRootView,{collapsable:!1,style:[z.backdrop,{backgroundColor:B.colors.background.overlay}],children:[_jsx(Pressable,{style:StyleSheet.absoluteFill,onPress:je,accessibilityLabel:"Dismiss"}),_jsx(Animated.View,{style:[z.sheetWrap,{paddingBottom:Math.max(Y.bottom,B.spacing.lg),opacity:J,transform:[{translateY:Animated.add(Ve,K)}]}],onLayout:e=>{Q.current=e.nativeEvent.layout.height},accessibilityViewIsModal:!0,accessibilityRole:"none",children:Re}),_jsx(ToastHost,{})]})});return Ie?_jsxs(_Fragment,{children:[_jsx(PickerTrigger,{label:D,value:Ae,placeholder:w,helperText:v,error:C,required:S,disabled:j,size:k,variant:P,clearable:T,onClear:V,onPress:()=>M(!0),triggerStyle:R,testID:x}),Me]}):Me},buildStyles=e=>{const t=e.shadows.lg;return StyleSheet.create({backdrop:{...StyleSheet.absoluteFill},sheetWrap:{position:"absolute",left:0,right:0,bottom:0,paddingHorizontal:e.spacing.md,paddingBottom:e.spacing.lg},card:{backgroundColor:e.colors.background.elevated,borderRadius:e.radius.xl,...smoothCorners,padding:e.spacing.lg,shadowColor:t.shadowColor,shadowOffset:t.shadowOffset,shadowOpacity:t.shadowOpacity,shadowRadius:t.shadowRadius,elevation:t.elevation},grabArea:{marginTop:-e.spacing.lg,paddingTop:e.spacing.sm},handle:{alignSelf:"center",width:36,height:4,borderRadius:e.radius.full,...smoothCorners,backgroundColor:e.colors.border.secondary,marginBottom:e.spacing.sm},titleRow:{marginBottom:e.spacing.sm},title:{fontSize:e.typography.fontSize.lg,fontWeight:e.typography.fontWeight.semibold,color:e.colors.text.primary},headerRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",marginBottom:e.spacing.md},navBtn:{width:e.components.datePicker?.navButtonSize??36,height:e.components.datePicker?.navButtonSize??36,borderRadius:e.radius.full,...smoothCorners,alignItems:"center",justifyContent:"center",backgroundColor:e.colors.background.secondary},navBtnPressed:{backgroundColor:e.colors.surface.pressed},navText:{fontSize:e.components.datePicker?.navTextFontSize??22,lineHeight:e.components.datePicker?.navTextLineHeight??24,color:e.colors.text.primary,fontWeight:e.typography.fontWeight.semibold},headerLabelWrap:{flex:1,alignItems:"center"},headerLabelInner:{flexDirection:"row",alignItems:"center",justifyContent:"center"},headerLabel:{fontSize:e.typography.fontSize.base,fontWeight:e.typography.fontWeight.semibold,color:e.colors.text.primary},headerCaret:{marginLeft:e.spacing.xs,alignItems:"center",justifyContent:"center"},weekdayRow:{flexDirection:"row",marginBottom:e.spacing.xs},weekdayCell:{flex:1,alignItems:"center",paddingVertical:e.spacing.xs},weekdayText:{fontSize:e.typography.fontSize.xs,fontWeight:e.typography.fontWeight.medium,color:e.colors.text.tertiary,letterSpacing:e.typography.letterSpacing.wide},grid:{},gridRow:{flexDirection:"row"},dayCell:{flex:1,aspectRatio:1,alignItems:"center",justifyContent:"center",padding:e.components.datePicker?.dayCellPadding??2},dayInner:{width:"100%",height:"100%",borderRadius:e.components.datePicker?.dayInnerBorderRadius??e.radius.full,...smoothCorners,alignItems:"center",justifyContent:"center"},dayText:{fontSize:e.typography.fontSize.sm,fontWeight:e.typography.fontWeight.medium},yearGrid:{},yearCell:{flex:1,aspectRatio:1.6,alignItems:"center",justifyContent:"center",padding:e.components.datePicker?.yearCellPadding??4},yearInner:{width:"100%",height:"100%",borderRadius:e.components.datePicker?.yearInnerBorderRadius??e.radius.lg,...smoothCorners,alignItems:"center",justifyContent:"center"},yearText:{fontSize:e.typography.fontSize.base,fontWeight:e.typography.fontWeight.semibold},decadeRangeText:{fontSize:e.typography.fontSize.xs,fontWeight:e.typography.fontWeight.medium,marginTop:e.components.datePicker?.decadeRangeMarginTop??2},footer:{flexDirection:"row",justifyContent:"flex-end",alignItems:"center",marginTop:e.spacing.lg,gap:e.spacing.sm},footerBtn:{paddingHorizontal:e.spacing.lg,paddingVertical:e.spacing.sm,borderRadius:e.radius.md,...smoothCorners,minHeight:e.components.datePicker?.footerButtonMinHeight??40,alignItems:"center",justifyContent:"center"},footerCancel:{backgroundColor:"transparent"},footerConfirm:{},footerBtnPressed:{opacity:.85},footerBtnText:{fontSize:e.typography.fontSize.sm,fontWeight:e.typography.fontWeight.semibold}})};export{DatePicker};export default DatePicker;
|
|
1
|
+
"use strict";import{useCallback,useEffect,useMemo,useRef,useState}from"react";import{AccessibilityInfo,Animated,Easing,Modal,Pressable,StyleSheet,Text,View}from"react-native";import{GestureDetector,GestureHandlerRootView}from"react-native-gesture-handler";import{useDragToDismiss}from"../../hooks/useDragToDismiss.js";import{createAnimatedValue,setNativeValue,useTheme}from"../../theme/index.js";import{resolveHaptic,triggerHaptic}from"../../utils/index.js";import{smoothCorners}from"../../utils/corners.js";import{defaultIcons}from"../AppIcon/defaultIcons.js";import{ModalSafeArea,useModalInsets}from"../ModalSafeArea/ModalSafeArea.js";import{PickerTrigger}from"../PickerTrigger/index.js";import{ToastHost}from"../Toast/ToastProvider.js";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";const GRID_SIZE=12,DECADE_SPAN=10,startOfDay=e=>new Date(e.getFullYear(),e.getMonth(),e.getDate()),isSameDay=(e,t)=>e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate(),toIso=e=>`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`,addMonths=(e,t)=>new Date(e.getFullYear(),e.getMonth()+t,1),buildMonthMatrix=(e,t)=>{const a=e.getFullYear(),r=e.getMonth(),i=(new Date(a,r,1).getDay()-t+7)%7,s=[];for(let e=0;e<42;e+=1){const t=new Date(a,r,1-i+e);s.push({date:t,inMonth:t.getMonth()===r,iso:toIso(t)})}return s},weekdayLabels=(e,t)=>{const a=new Intl.DateTimeFormat(e,{weekday:"short"}),r=[];for(let e=0;e<7;e+=1){const i=new Date(1970,0,4+(t+e)%7);r.push(a.format(i))}return r},formatMonthYear=(e,t)=>new Intl.DateTimeFormat(t,{month:"long",year:"numeric"}).format(e),formatLongDate=(e,t)=>new Intl.DateTimeFormat(t,{weekday:"long",year:"numeric",month:"long",day:"numeric"}).format(e),decadeStartFor=e=>10*Math.floor(e/10),buildYearCells=e=>{const t=e-4;return Array.from({length:12},(e,a)=>t+a)},buildDecadeCells=e=>{const t=decadeStartFor(e)-40;return Array.from({length:12},(e,a)=>t+10*a)},DatePicker=e=>{const{value:t,onChange:a,onClose:r,minDate:i,maxDate:s,disabledDates:o,mode:n="modal",locale:l="en-IN",weekStartsOn:c=0,title:d="Select Date",confirmLabel:u="Confirm",cancelLabel:g="Cancel",style:m,containerStyle:y,headerLabelStyle:p,navButtonStyle:h,footerButtonStyle:f,haptic:b,testID:x,label:D,placeholder:w,helperText:v,error:C,required:S,disabled:j,size:k,variant:P,clearable:T,onClear:V,formatValue:_,triggerStyle:A}=e,R=void 0!==e.visible,[M,I]=useState(!1),F=R?e.visible:M,L=R?x:x?`${x}-calendar`:void 0,B=useTheme(),[Y,z]=useModalInsets(),H=useMemo(()=>buildStyles(B),[B]),[N,$]=useState(()=>startOfDay(new Date));useEffect(()=>{F&&$(startOfDay(new Date))},[F]);const W=t?startOfDay(t):N,[E,O]=useState(W),[G,q]=useState(t?startOfDay(t):null),[X,Z]=useState("days"),J=useRef(createAnimatedValue(0)).current,K=useRef(createAnimatedValue(0)).current,Q=useRef(createAnimatedValue(0)).current,U=useRef(0),ee=useRef(createAnimatedValue(0)).current,te=useRef(createAnimatedValue(1)).current,ae=useRef(createAnimatedValue(1)).current,re=useRef(createAnimatedValue(1)).current,ie=useRef(createAnimatedValue(1)).current,se=useRef(createAnimatedValue(1)).current;useEffect(()=>{if(t){const e=startOfDay(t);q(e),O(e)}else q(null)},[t]),useEffect(()=>{if("modal"===n&&F){J.setValue(0),setNativeValue(K,0),setNativeValue(Q,0);const e=Animated.parallel([Animated.timing(J,{toValue:1,duration:B.motion.duration.normal,easing:Easing.out(Easing.cubic),useNativeDriver:!1}),Animated.spring(K,{toValue:1,damping:B.motion.spring.gentle.damping,stiffness:B.motion.spring.gentle.stiffness,mass:B.motion.spring.gentle.mass,useNativeDriver:!0})]);return e.start(),()=>e.stop()}},[F,n,J,K,Q,B.motion]);const oe=useMemo(()=>{const e=new Set;return o?.forEach(t=>e.add(toIso(startOfDay(t)))),e},[o]),ne=useMemo(()=>i?startOfDay(i):null,[i]),le=useMemo(()=>s?startOfDay(s):null,[s]),ce=useCallback(e=>!!(ne&&e.getTime()<ne.getTime())||(!!(le&&e.getTime()>le.getTime())||!!oe.has(toIso(e))),[ne,le,oe]),de=useMemo(()=>buildMonthMatrix(E,c),[E,c]),ue=useMemo(()=>buildYearCells(E.getFullYear()),[E]),ge=useMemo(()=>buildDecadeCells(E.getFullYear()),[E]),me=useMemo(()=>weekdayLabels(l,c),[l,c]),ye=useMemo(()=>{if("days"===X)return formatMonthYear(E,l);if("years"===X){return`${ue[0]} - ${ue[ue.length-1]}`}return`${ge[0]} - ${ge[ge.length-1]+9}`},[E,ge,l,X,ue]),pe=useCallback(e=>!!(ne&&e<ne.getFullYear())||!!(le&&e>le.getFullYear()),[ne,le]),he=useCallback(e=>!!(ne&&e+10-1<ne.getFullYear())||!!(le&&e>le.getFullYear()),[ne,le]),fe=useCallback(e=>{!1!==b&&triggerHaptic("impactLight");const t=e>0?1:-1,a=B.components.datePicker?.monthSlideDistance??32,r=B.components.datePicker?.monthSlideOutDuration??B.motion.duration.fast??140,i=B.components.datePicker?.monthSlideInDuration??B.motion.duration.fast??160;Animated.sequence([Animated.parallel([Animated.timing(ee,{toValue:-t*a,duration:r,easing:Easing.out(Easing.quad),useNativeDriver:!0}),Animated.timing(te,{toValue:0,duration:r,useNativeDriver:!0})]),Animated.timing(ee,{toValue:t*a,duration:0,useNativeDriver:!0}),Animated.parallel([Animated.timing(ee,{toValue:0,duration:i,easing:Easing.out(Easing.cubic),useNativeDriver:!0}),Animated.timing(te,{toValue:1,duration:i,useNativeDriver:!0})])]).start();const s=addMonths(E,e);O(s),AccessibilityInfo.announceForAccessibility(formatMonthYear(s,l))},[E,b,l,te,ee,B.components.datePicker,B.motion.duration.fast]),be=useCallback(()=>{"days"!==X?(!1!==b&&triggerHaptic("impactLight"),O("years"===X?e=>new Date(e.getFullYear()-12,e.getMonth(),1):e=>new Date(e.getFullYear()-120,e.getMonth(),1))):fe(-1)},[fe,X,b]),xe=useCallback(()=>{"days"!==X?(!1!==b&&triggerHaptic("impactLight"),O("years"===X?e=>new Date(e.getFullYear()+12,e.getMonth(),1):e=>new Date(e.getFullYear()+120,e.getMonth(),1))):fe(1)},[fe,X,b]),De=useCallback(()=>{const e=B.components.datePicker?.viewTransitionDuration??B.motion.duration.normal??200;setNativeValue(re,0),setNativeValue(ie,.9),Animated.parallel([Animated.timing(re,{toValue:1,duration:e,easing:Easing.out(Easing.cubic),useNativeDriver:!0}),Animated.timing(ie,{toValue:1,duration:e,easing:Easing.out(Easing.cubic),useNativeDriver:!0})]).start()},[re,ie,B.components.datePicker,B.motion.duration.normal]),we=useCallback(()=>{const e=resolveHaptic(b,"selection");e&&triggerHaptic(e);const t=B.components.datePicker?.headerPressDuration??80,a=B.components.datePicker?.headerReleaseDuration??100;Animated.sequence([Animated.timing(se,{toValue:.96,duration:t,useNativeDriver:!0}),Animated.timing(se,{toValue:1,duration:a,useNativeDriver:!0})]).start(),Z(e=>"days"===e?"years":"years"===e?"decades":"years"),De()},[De,se,b,B.components.datePicker]),ve=useCallback(e=>{const t=resolveHaptic(b,"selection");t&&triggerHaptic(t),O(t=>new Date(e,t.getMonth(),1)),Z("days"),De()},[De,b]),Ce=useCallback(e=>{const t=resolveHaptic(b,"selection");t&&triggerHaptic(t),O(t=>new Date(e+4,t.getMonth(),1)),Z("years"),De()},[De,b]),Se=useCallback(e=>{if(ce(e.date))return;const t=resolveHaptic(b,"selection");t&&triggerHaptic(t),q(e.date),e.inMonth||O(new Date(e.date.getFullYear(),e.date.getMonth(),1)),setNativeValue(ae,.7),Animated.spring(ae,{toValue:1,damping:B.motion.spring.bouncy.damping,stiffness:B.motion.spring.bouncy.stiffness,mass:B.motion.spring.bouncy.mass,useNativeDriver:!0}).start()},[ce,ae,B.motion.spring.bouncy,b]),je=useCallback(()=>{R||I(!1),r?.()},[R,r]),ke=useCallback(()=>{"modal"===n?Animated.parallel([Animated.timing(J,{toValue:0,duration:B.motion.duration.fast,easing:Easing.bezier(...B.motion.easing.accelerate),useNativeDriver:!1}),Animated.timing(K,{toValue:0,duration:B.motion.duration.fast,easing:Easing.bezier(...B.motion.easing.accelerate),useNativeDriver:!0})]).start(()=>{je()}):je()},[J,n,je,K,B.motion.duration.fast,B.motion.easing.accelerate]),{handleGesture:Pe}=useDragToDismiss({drag:Q,travel:()=>U.current||320,onDismiss:ke}),Te=useCallback(()=>{!1!==b&&triggerHaptic("selection"),ke()},[ke,b]),Ve=useCallback(()=>{G&&(!1!==b&&triggerHaptic("notificationSuccess"),a?.(G),ke())},[ke,a,G,b]),Ae=K.interpolate({inputRange:[0,1],outputRange:[320,0]}),Re=_jsx(View,{style:H.titleRow,children:_jsx(Text,{style:H.title,accessibilityRole:"header",children:d})}),Me=_jsxs(View,{style:[H.card,m,y],accessibilityRole:"modal"===n?void 0:"none",accessible:!1,testID:L,children:["modal"===n?_jsx(GestureDetector,{gesture:Pe,children:_jsxs(View,{style:H.grabArea,children:[_jsx(View,{style:H.handle}),Re]})}):Re,_jsxs(View,{style:H.headerRow,children:[_jsx(Pressable,{onPress:be,style:({pressed:e})=>[H.navBtn,e&&H.navBtnPressed,h],accessibilityRole:"button",accessibilityLabel:"days"===X?"Previous month":"years"===X?"Previous years":"Previous decades",hitSlop:8,children:_jsx(Text,{style:H.navText,children:"‹"})}),_jsx(Pressable,{onPress:we,style:[H.headerLabelWrap,p],accessibilityRole:"button",accessibilityLabel:"days"===X?`${ye}, switch to year selection`:"years"===X?`${ye}, switch to decade selection`:`${ye}, switch to year selection`,hitSlop:8,children:_jsxs(Animated.View,{style:[H.headerLabelInner,{transform:[{scale:se}],opacity:"days"===X?te:1}],children:[_jsx(Animated.Text,{style:[H.headerLabel,{transform:[{translateX:"days"===X?ee:0}]}],accessibilityLiveRegion:"polite",children:ye}),_jsx(View,{style:H.headerCaret,children:(B.icons?.chevronDown??defaultIcons.chevronDown)({size:B.typography.fontSize.sm,color:B.colors.text.secondary})})]})}),_jsx(Pressable,{onPress:xe,style:({pressed:e})=>[H.navBtn,e&&H.navBtnPressed,h],accessibilityRole:"button",accessibilityLabel:"days"===X?"Next month":"years"===X?"Next years":"Next decades",hitSlop:8,children:_jsx(Text,{style:H.navText,children:"›"})})]}),"days"===X?_jsxs(_Fragment,{children:[_jsx(View,{style:H.weekdayRow,children:me.map((e,t)=>_jsx(View,{style:H.weekdayCell,children:_jsx(Text,{style:H.weekdayText,children:e})},`${e}-${t}`))}),_jsx(Animated.View,{style:[H.grid,{opacity:te,transform:[{translateX:ee}]}],children:Array.from({length:6}).map((e,t)=>_jsx(View,{style:H.gridRow,children:de.slice(7*t,7*t+7).map(e=>{const t=ce(e.date),a=!!G&&isSameDay(e.date,G),r=isSameDay(e.date,N),i=a?B.colors.primary:"transparent",s=r&&!a?B.colors.primary:"transparent",o=a?B.colors.onPrimary:e.inMonth?t?B.colors.text.disabled:B.colors.text.primary:B.colors.text.tertiary,n=t?.3:e.inMonth?1:.4;return _jsx(Pressable,{disabled:t,onPress:()=>Se(e),accessibilityRole:"button",accessibilityLabel:formatLongDate(e.date,l),accessibilityState:{selected:a,disabled:t},"aria-selected":a,"aria-disabled":t,style:H.dayCell,children:_jsx(Animated.View,{style:[H.dayInner,{backgroundColor:i,borderColor:s,borderWidth:r&&!a?1.5:0,opacity:n},a?{transform:[{scale:ae}]}:null],children:_jsx(Text,{style:[H.dayText,{color:o}],children:e.date.getDate()})})},e.iso)})},`r-${t}`))})]}):_jsx(Animated.View,"years"===X?{style:[H.yearGrid,{opacity:re,transform:[{scale:ie}]}],children:Array.from({length:3}).map((e,t)=>_jsx(View,{style:H.gridRow,children:ue.slice(4*t,4*t+4).map(e=>{const t=pe(e),a=!!G&&G.getFullYear()===e,r=N.getFullYear()===e,i=a?B.colors.primary:"transparent",s=r&&!a?B.colors.primary:"transparent",o=a?B.colors.onPrimary:t?B.colors.text.disabled:B.colors.text.primary,n=t?.3:1;return _jsx(Pressable,{disabled:t,onPress:()=>ve(e),accessibilityRole:"button",accessibilityLabel:`Year ${e}`,accessibilityState:{selected:a,disabled:t},"aria-selected":a,"aria-disabled":t,style:H.yearCell,children:_jsx(View,{style:[H.yearInner,{backgroundColor:i,borderColor:s,borderWidth:r&&!a?1.5:0,opacity:n}],children:_jsx(Text,{style:[H.yearText,{color:o}],children:e})})},`year-${e}`)})},`yr-${t}`))}:{style:[H.yearGrid,{opacity:re,transform:[{scale:ie}]}],children:Array.from({length:3}).map((e,t)=>_jsx(View,{style:H.gridRow,children:ge.slice(4*t,4*t+4).map(e=>{const t=e+10-1,a=he(e),r=!!G&&decadeStartFor(G.getFullYear())===e,i=decadeStartFor(N.getFullYear())===e,s=r?B.colors.primary:"transparent",o=i&&!r?B.colors.primary:"transparent",n=r?B.colors.onPrimary:a?B.colors.text.disabled:B.colors.text.primary,l=a?.3:1;return _jsx(Pressable,{disabled:a,onPress:()=>Ce(e),accessibilityRole:"button",accessibilityLabel:`Decade ${e} to ${t}`,accessibilityState:{selected:r,disabled:a},"aria-selected":r,"aria-disabled":a,style:H.yearCell,children:_jsxs(View,{style:[H.yearInner,{backgroundColor:s,borderColor:o,borderWidth:i&&!r?1.5:0,opacity:l}],children:[_jsx(Text,{style:[H.yearText,{color:n}],children:`${e}s`}),_jsx(Text,{style:[H.decadeRangeText,{color:r?B.colors.onPrimary:B.colors.text.tertiary}],children:`${e}-${t}`})]})},`decade-${e}`)})},`dec-${t}`))}),_jsxs(View,{style:H.footer,children:[_jsx(Pressable,{onPress:Te,style:({pressed:e})=>[H.footerBtn,H.footerCancel,e&&H.footerBtnPressed,f],accessibilityRole:"button",accessibilityLabel:g,children:_jsx(Text,{style:[H.footerBtnText,{color:B.colors.text.secondary}],children:g})}),_jsx(Pressable,{onPress:Ve,disabled:!G,style:({pressed:e})=>[H.footerBtn,H.footerConfirm,{backgroundColor:B.colors.primary,opacity:G?1:.5},e&&{backgroundColor:B.colors.primaryHover},f],accessibilityRole:"button",accessibilityLabel:u,accessibilityState:{disabled:!G},"aria-disabled":!G,children:_jsx(Text,{style:[H.footerBtnText,{color:B.colors.onPrimary}],children:u})})]})]}),Ie=t?(_??(e=>e.toLocaleDateString()))(t):void 0,Fe=!R;if("inline"===n)return F||Fe?Fe?_jsxs(_Fragment,{children:[_jsx(PickerTrigger,{label:D,value:Ie,placeholder:w,helperText:v,error:C,required:S,disabled:j,size:k,variant:P,clearable:T,onClear:V,onPress:()=>I(!0),triggerStyle:A,testID:x}),F?Me:null]}):Me:null;const Le=_jsx(Modal,{visible:F,transparent:!0,statusBarTranslucent:!0,navigationBarTranslucent:!0,animationType:"none",onRequestClose:ke,children:_jsx(ModalSafeArea,{onInsets:z,children:_jsxs(GestureHandlerRootView,{collapsable:!1,style:[H.backdrop,{backgroundColor:B.colors.background.overlay}],children:[_jsx(Pressable,{style:StyleSheet.absoluteFill,onPress:ke,accessibilityLabel:"Dismiss"}),_jsx(Animated.View,{style:[H.sheetWrap,{paddingBottom:Math.max(Y.bottom,B.spacing.lg),opacity:K,transform:[{translateY:Animated.add(Ae,Q)}]}],onLayout:e=>{U.current=e.nativeEvent.layout.height},accessibilityViewIsModal:!0,accessibilityRole:"none",children:Me}),_jsx(ToastHost,{})]})})});return Fe?_jsxs(_Fragment,{children:[_jsx(PickerTrigger,{label:D,value:Ie,placeholder:w,helperText:v,error:C,required:S,disabled:j,size:k,variant:P,clearable:T,onClear:V,onPress:()=>I(!0),triggerStyle:A,testID:x}),Le]}):Le},buildStyles=e=>{const t=e.shadows.lg;return StyleSheet.create({backdrop:{...StyleSheet.absoluteFill},sheetWrap:{position:"absolute",left:0,right:0,bottom:0,paddingHorizontal:e.spacing.md,paddingBottom:e.spacing.lg},card:{backgroundColor:e.colors.background.elevated,borderRadius:e.radius.xl,...smoothCorners,padding:e.spacing.lg,shadowColor:t.shadowColor,shadowOffset:t.shadowOffset,shadowOpacity:t.shadowOpacity,shadowRadius:t.shadowRadius,elevation:t.elevation},grabArea:{marginTop:-e.spacing.lg,paddingTop:e.spacing.sm},handle:{alignSelf:"center",width:36,height:4,borderRadius:e.radius.full,...smoothCorners,backgroundColor:e.colors.border.secondary,marginBottom:e.spacing.sm},titleRow:{marginBottom:e.spacing.sm},title:{fontSize:e.typography.fontSize.lg,fontWeight:e.typography.fontWeight.semibold,color:e.colors.text.primary},headerRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",marginBottom:e.spacing.md},navBtn:{width:e.components.datePicker?.navButtonSize??36,height:e.components.datePicker?.navButtonSize??36,borderRadius:e.radius.full,...smoothCorners,alignItems:"center",justifyContent:"center",backgroundColor:e.colors.background.secondary},navBtnPressed:{backgroundColor:e.colors.surface.pressed},navText:{fontSize:e.components.datePicker?.navTextFontSize??22,lineHeight:e.components.datePicker?.navTextLineHeight??24,color:e.colors.text.primary,fontWeight:e.typography.fontWeight.semibold},headerLabelWrap:{flex:1,alignItems:"center"},headerLabelInner:{flexDirection:"row",alignItems:"center",justifyContent:"center"},headerLabel:{fontSize:e.typography.fontSize.base,fontWeight:e.typography.fontWeight.semibold,color:e.colors.text.primary},headerCaret:{marginLeft:e.spacing.xs,alignItems:"center",justifyContent:"center"},weekdayRow:{flexDirection:"row",marginBottom:e.spacing.xs},weekdayCell:{flex:1,alignItems:"center",paddingVertical:e.spacing.xs},weekdayText:{fontSize:e.typography.fontSize.xs,fontWeight:e.typography.fontWeight.medium,color:e.colors.text.tertiary,letterSpacing:e.typography.letterSpacing.wide},grid:{},gridRow:{flexDirection:"row"},dayCell:{flex:1,aspectRatio:1,alignItems:"center",justifyContent:"center",padding:e.components.datePicker?.dayCellPadding??2},dayInner:{width:"100%",height:"100%",borderRadius:e.components.datePicker?.dayInnerBorderRadius??e.radius.full,...smoothCorners,alignItems:"center",justifyContent:"center"},dayText:{fontSize:e.typography.fontSize.sm,fontWeight:e.typography.fontWeight.medium},yearGrid:{},yearCell:{flex:1,aspectRatio:1.6,alignItems:"center",justifyContent:"center",padding:e.components.datePicker?.yearCellPadding??4},yearInner:{width:"100%",height:"100%",borderRadius:e.components.datePicker?.yearInnerBorderRadius??e.radius.lg,...smoothCorners,alignItems:"center",justifyContent:"center"},yearText:{fontSize:e.typography.fontSize.base,fontWeight:e.typography.fontWeight.semibold},decadeRangeText:{fontSize:e.typography.fontSize.xs,fontWeight:e.typography.fontWeight.medium,marginTop:e.components.datePicker?.decadeRangeMarginTop??2},footer:{flexDirection:"row",justifyContent:"flex-end",alignItems:"center",marginTop:e.spacing.lg,gap:e.spacing.sm},footerBtn:{paddingHorizontal:e.spacing.lg,paddingVertical:e.spacing.sm,borderRadius:e.radius.md,...smoothCorners,minHeight:e.components.datePicker?.footerButtonMinHeight??40,alignItems:"center",justifyContent:"center"},footerCancel:{backgroundColor:"transparent"},footerConfirm:{},footerBtnPressed:{opacity:.85},footerBtnText:{fontSize:e.typography.fontSize.sm,fontWeight:e.typography.fontWeight.semibold}})};export{DatePicker};export default DatePicker;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{forwardRef,useCallback,useEffect,useMemo,useRef,useState}from"react";import{Animated,Easing,Modal,Pressable,StyleSheet,Text,View}from"react-native";import{GestureDetector,GestureHandlerRootView}from"react-native-gesture-handler";import{
|
|
1
|
+
"use strict";import{forwardRef,useCallback,useEffect,useMemo,useRef,useState}from"react";import{Animated,Easing,Modal,Pressable,StyleSheet,Text,View}from"react-native";import{GestureDetector,GestureHandlerRootView}from"react-native-gesture-handler";import{useDragToDismiss}from"../../hooks/useDragToDismiss.js";import{createAnimatedValue,setNativeValue,useTheme}from"../../theme/index.js";import{triggerHaptic}from"../../utils/index.js";import{smoothCorners}from"../../utils/corners.js";import{Calendar}from"../Calendar/index.js";import{daysBetween,startOfDay,startOfMonth}from"../Calendar/calendarDates.js";import{ModalSafeArea,useModalInsets}from"../ModalSafeArea/ModalSafeArea.js";import{PickerTrigger}from"../PickerTrigger/index.js";import{ToastHost}from"../Toast/ToastProvider.js";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";const formatRangePart=(e,t)=>new Intl.DateTimeFormat(t,{weekday:"short",day:"numeric",month:"short"}).format(e),DateRangePicker=forwardRef((e,t)=>{const{visible:a,value:r,onChange:s,onClose:o,label:i,placeholder:n,helperText:l,error:d,required:c,disabled:g,size:m,variant:u,clearable:f,onClear:p,formatValue:h,triggerStyle:y,minDate:b,maxDate:x,disabledDates:D,markedDates:S,strikeMarkedInRange:v,locale:R="en-IN",weekStartsOn:j=0,title:C="Select Date Range",confirmLabel:k="Confirm",cancelLabel:w="Cancel",maxRange:T,haptic:P,style:_,containerStyle:V,headerLabelStyle:M,navButtonStyle:B,footerButtonStyle:A,testID:I}=e,O=void 0!==a,[H,z]=useState(!1),L=O?a:H,E=O?I:I?`${I}-calendar`:void 0,N=useTheme(),[W,$]=useModalInsets(),F=useMemo(()=>buildStyles(N),[N]),[G,q]=useState(()=>startOfMonth(r.start??new Date)),[Y,J]=useState(r.start?startOfDay(r.start):null),[K,Q]=useState(r.end?startOfDay(r.end):null),U=useRef(createAnimatedValue(0)).current,X=useRef(createAnimatedValue(0)).current,Z=useRef(createAnimatedValue(0)).current,ee=useRef(0);useEffect(()=>{if(r.start){const e=startOfDay(r.start);J(e),q(startOfMonth(e))}else J(null);r.end?Q(startOfDay(r.end)):Q(null)},[r.start,r.end]),useEffect(()=>{let e;return L&&(U.setValue(0),setNativeValue(X,0),setNativeValue(Z,0),e=Animated.parallel([Animated.timing(U,{toValue:1,duration:N.motion.duration.normal,easing:Easing.out(Easing.cubic),useNativeDriver:!1}),Animated.spring(X,{toValue:1,damping:N.motion.spring.gentle.damping,stiffness:N.motion.spring.gentle.stiffness,mass:N.motion.spring.gentle.mass,useNativeDriver:!0})]),e.start()),()=>e?.stop()},[L,U,X,Z,N.motion]);const te=useCallback(e=>{if(e.end&&T&&daysBetween(e.start,e.end)+1>T)return!1!==P&&triggerHaptic("notificationWarning"),J(e.end),void Q(null);J(e.start),Q(e.end??null)},[T,P]),ae=useCallback(()=>{O?o?.():z(!1)},[O,o]),re=useCallback(()=>{Animated.parallel([Animated.timing(U,{toValue:0,duration:N.motion.duration.fast,easing:Easing.bezier(...N.motion.easing.accelerate),useNativeDriver:!1}),Animated.timing(X,{toValue:0,duration:N.motion.duration.fast,easing:Easing.bezier(...N.motion.easing.accelerate),useNativeDriver:!0})]).start(()=>{ae()})},[U,ae,X,N.motion.duration.fast,N.motion.easing.accelerate]),{handleGesture:se}=useDragToDismiss({drag:Z,travel:()=>ee.current||320,onDismiss:re}),oe=useCallback(()=>{!1!==P&&triggerHaptic("selection"),re()},[re,P]),ie=useCallback(()=>{Y&&K&&(!1!==P&&triggerHaptic("notificationSuccess"),s?.({start:Y,end:K}),re())},[re,s,Y,K,P]),ne=X.interpolate({inputRange:[0,1],outputRange:[320,0]}),le=useMemo(()=>Y&&K?`${formatRangePart(Y,R)} — ${formatRangePart(K,R)}`:Y?`${formatRangePart(Y,R)} — …`:"—",[Y,K,R]),de=!Y||!K,ce=_jsxs(View,{style:[F.card,_,V],ref:t,accessible:!1,testID:E,children:[_jsx(GestureDetector,{gesture:se,children:_jsxs(View,{style:F.grabArea,children:[_jsx(View,{style:F.handle}),_jsxs(View,{style:F.titleRow,children:[_jsx(Text,{style:F.title,accessibilityRole:"header",children:C}),_jsx(Text,{style:F.subtitle,accessibilityLiveRegion:"polite",children:le})]})]})}),_jsx(Calendar,{mode:"range",value:Y?{start:Y,end:K??void 0}:null,onChange:te,month:G,onMonthChange:q,minDate:b,maxDate:x,disabledDates:D,markedDates:S,strikeMarkedInRange:v,weekStartsOn:j,locale:R,haptic:P,headerLabelStyle:M,navButtonStyle:B,testID:E?`${E}-grid`:void 0}),_jsxs(View,{style:F.footer,children:[_jsx(Pressable,{onPress:oe,style:({pressed:e})=>[F.footerBtn,F.footerCancel,e&&F.footerBtnPressed,A],accessibilityRole:"button",accessibilityLabel:w,children:_jsx(Text,{style:[F.footerBtnText,{color:N.colors.text.secondary}],children:w})}),_jsx(Pressable,{onPress:ie,disabled:de,style:({pressed:e})=>[F.footerBtn,F.footerConfirm,{backgroundColor:N.colors.primary,opacity:de?.5:1},e&&{backgroundColor:N.colors.primaryHover},A],accessibilityRole:"button",accessibilityLabel:k,accessibilityState:{disabled:de},"aria-disabled":de,children:_jsx(Text,{style:[F.footerBtnText,{color:N.colors.onPrimary}],children:k})})]})]}),ge=useMemo(()=>{if(!r.start||!r.end)return"";const e={start:r.start,end:r.end};return h?h(e):`${e.start.toLocaleDateString()} – ${e.end.toLocaleDateString()}`},[r.start,r.end,h]);return _jsxs(_Fragment,{children:[O?null:_jsx(PickerTrigger,{label:i,placeholder:n,helperText:l,error:d,required:c,disabled:g,size:m,variant:u,clearable:f,onClear:p,value:ge,onPress:()=>z(!0),triggerStyle:y,testID:I}),_jsx(Modal,{visible:L,transparent:!0,statusBarTranslucent:!0,navigationBarTranslucent:!0,animationType:"none",onRequestClose:re,children:_jsx(ModalSafeArea,{onInsets:$,children:_jsxs(GestureHandlerRootView,{collapsable:!1,style:[F.backdrop,{backgroundColor:N.colors.background.overlay}],children:[_jsx(Pressable,{style:StyleSheet.absoluteFill,onPress:re,accessibilityLabel:"Dismiss"}),_jsx(Animated.View,{style:[F.sheetWrap,{paddingBottom:Math.max(W.bottom,N.spacing.lg),opacity:X,transform:[{translateY:Animated.add(ne,Z)}]}],onLayout:e=>{ee.current=e.nativeEvent.layout.height},accessibilityViewIsModal:!0,accessibilityRole:"none",children:ce}),_jsx(ToastHost,{})]})})})]})});DateRangePicker.displayName="DateRangePicker";const buildStyles=e=>{const t=e.shadows.lg;return StyleSheet.create({backdrop:{...StyleSheet.absoluteFill},sheetWrap:{position:"absolute",left:0,right:0,bottom:0,paddingHorizontal:e.spacing.md,paddingBottom:e.spacing.lg},card:{backgroundColor:e.colors.background.elevated,borderRadius:e.radius.xl,...smoothCorners,padding:e.spacing.lg,shadowColor:t.shadowColor,shadowOffset:t.shadowOffset,shadowOpacity:t.shadowOpacity,shadowRadius:t.shadowRadius,elevation:t.elevation},grabArea:{marginTop:-e.spacing.lg,paddingTop:e.spacing.sm},handle:{alignSelf:"center",width:36,height:4,borderRadius:e.radius.full,...smoothCorners,backgroundColor:e.colors.border.secondary,marginBottom:e.spacing.sm},titleRow:{marginBottom:e.spacing.sm},title:{fontSize:e.typography.fontSize.lg,fontWeight:e.typography.fontWeight.semibold,color:e.colors.text.primary},subtitle:{marginTop:e.spacing.xxs,fontSize:e.typography.fontSize.sm,color:e.colors.text.secondary},footer:{flexDirection:"row",justifyContent:"flex-end",alignItems:"center",marginTop:e.spacing.lg,gap:e.spacing.sm},footerBtn:{paddingHorizontal:e.spacing.lg,paddingVertical:e.spacing.sm,borderRadius:e.radius.md,...smoothCorners,minHeight:e.components.dateRangePicker?.footerButtonMinHeight??40,alignItems:"center",justifyContent:"center"},footerCancel:{backgroundColor:"transparent"},footerConfirm:{},footerBtnPressed:{opacity:.85},footerBtnText:{fontSize:e.typography.fontSize.sm,fontWeight:e.typography.fontWeight.semibold}})};export{DateRangePicker};export default DateRangePicker;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{forwardRef,useEffect,useState}from"react";import{Platform}from"react-native";import{Input}from"../Input/index.js";import{jsx as _jsx}from"react/jsx-runtime";export function cleanDecimalText(e,{whole:t,signed:n,decimals:r,allowExponent:a}={}){const
|
|
1
|
+
"use strict";import{forwardRef,useEffect,useState}from"react";import{Platform}from"react-native";import{Input}from"../Input/index.js";import{jsx as _jsx}from"react/jsx-runtime";export function cleanDecimalText(e,{whole:t,signed:n,decimals:r,allowExponent:a}={}){const o=String(e??"");if(a)return o.replace(/[^\d.eE+-]/g,"");const i=Boolean(n)&&o.replace(/[^\d.,-]/g,"").startsWith("-");let l=o.replace(t?/\D/g:/[^\d.,]/g,"");const c=l.search(/[.,]/);if(-1!==c){const e=l.slice(c+1).replace(/[.,]/g,"");l=l.slice(0,c+1)+(null==r?e:e.slice(0,r))}return(i?"-":"")+l}export function isUnclearDecimalComma(e){return/,\d{3}$/.test(String(e??""))}export function pointDecimalText(e){return isUnclearDecimalComma(e)?e:e.replace(",",".")}export function parseDecimalText(e){if(isUnclearDecimalComma(e))return"";const t=pointDecimalText(e);if(""===t||"-"===t||"."===t||"-."===t)return"";const n=Number(t);return Number.isFinite(n)?n:""}const textOf=e=>null==e||""===e?"":String(e);function keyboardFor({whole:e,signed:t,allowExponent:n}){return n?"ios"===Platform.OS?"numbers-and-punctuation":"default":t?"numeric":e?"number-pad":"decimal-pad"}const DecimalInput=forwardRef((e,t)=>{const{symbol:n,value:r,onChange:a,onBlur:o,min:i,max:l,whole:c=!1,signed:m=!1,decimals:s,allowExponent:u=!1,numeric:p=!1,unclearCommaMessage:d="Use a point for the decimal mark. A comma before three digits could mean thousands.",error:f,readOnly:x=!1,disabled:D=!1,...g}=e,[b,h]=useState(textOf(r));useEffect(()=>{p&&h(e=>parseDecimalText(e)===r?e:textOf(r))},[p,r]);const T=x||D,w={whole:c,signed:m,decimals:s,allowExponent:u},C=p?b:textOf(r);return _jsx(Input,{prefix:n,keyboardType:keyboardFor(w),autoCapitalize:"none",autoCorrect:!1,readOnly:x,disabled:D,...g,ref:t,error:f??(isUnclearDecimalComma(C)?d:void 0),value:C,onChangeText:T?void 0:e=>{const t=cleanDecimalText(e,w),n=u?""===t?"":Number(t):parseDecimalText(t);""!==n&&Number.isFinite(n)&&(null!=l&&n>l||null!=i&&n<i)||(p?(h(t),a?.(parseDecimalText(t))):a?.(t))},onBlur:T?void 0:e=>{const t=pointDecimalText(C);t!==C&&(p?h(t):a?.(t)),o?.(e)}})});DecimalInput.displayName="DecimalInput";export{DecimalInput};export default DecimalInput;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";export{cleanDecimalText,DecimalInput,default,parseDecimalText}from"./DecimalInput.js";
|
|
1
|
+
"use strict";export{cleanDecimalText,DecimalInput,default,isUnclearDecimalComma,parseDecimalText,pointDecimalText}from"./DecimalInput.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{forwardRef,useCallback,useEffect,useMemo,useRef,useState}from"react";import{Animated,Easing,Pressable,StyleSheet,Text,TextInput,View}from"react-native";import{useReducedMotion}from"../../hooks/index.js";import{createAnimatedValue,fontFor,setNativeValue,useTheme}from"../../theme/index.js";import{mergeRefs,triggerHaptic}from"../../utils/index.js";import{defaultIcons}from"../AppIcon/defaultIcons.js";import{renderSlotIcon}from"../AppIcon/slotIcon.js";import{Button}from"../Button/index.js";import{FieldBase,FieldErrorGlyph,FieldLabel,fieldTextAsString,hasFieldText,RequiredPlaceholder,resolveFieldSize,resolveFieldTextStyle}from"../FieldBase/FieldBase.js";import{useFloatingLabel}from"../FieldBase/useFloatingLabel.js";import{NotationInkContext,useNotationInk}from"../Notation/Notation.js";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const multilineMinHeightMap={sm:72,md:92,lg:110},Input=forwardRef((e,t)=>{const{label:i,help:o,placeholder:n,value:l,onChangeText:r,error:s,helperText:a,type:d="input",secureTextEntry:c=!1,showPasswordToggle:u=!1,disabled:f=!1,multiline:p=!1,leftIcon:g,rightIcon:m,unit:x,unitStyle:h,prefix:y,prefixStyle:S,readOnly:b=!1,action:v,actionStyle:j,size:F="md",variant:w,labelMode:z,required:T=!1,maxLength:I,showCounter:R=!0,textAlign:V,format:_,parse:k,style:A,containerStyle:C,inputStyle:N,labelStyle:D,messageStyle:H,borderRadius:L,onFocus:P,onBlur:E,accessibilityLabel:M,testID:B,editable:O,...G}=e,q=useTheme(),W=useMemo(()=>buildStyles(q),[q]),$=resolveFieldSize(q,F),X=multilineMinHeightMap[F],J=Math.round(1.4*$.fontSize),K=w??q.components.input?.defaultVariant??q.components.field?.defaultVariant??"outlined",Q=z??q.components.input?.defaultLabelMode??"top",[U,Y]=useState(!1),[Z,ee]=useState(!1),te="password"===d||u||c,ie="password"===d||u,oe="textarea"===d||p,ne=oe?Math.round(.1*$.fontSize):0,le="string"==typeof l&&l.length>0,re=hasFieldText(s),se=!0===s||re,ae=hasFieldText(a),de=re||!se&&ae,ce=hasFieldText(i),ue=hasFieldText(y),fe=!f&&!1!==O,pe=U||le||ue,ge=useRef(null),me=useMemo(()=>mergeRefs(ge,t),[t]),xe=useCallback(()=>{fe&&ge.current?.focus()},[fe]),he=ce&&"float"===Q,ye=useRef(createAnimatedValue(0)).current,Se=useRef(createAnimatedValue(de?1:0)).current;useEffect(()=>{const e=Animated.timing(Se,{toValue:de?1:0,duration:q.motion.duration.fast,easing:Easing.bezier(...q.motion.easing.standard),useNativeDriver:!0});return e.start(),()=>e.stop()},[de,Se,q.motion.duration.fast,q.motion.easing.standard]);const be=useReducedMotion(),ve=q.components.input?.shakeOnError??!1,je=useRef(se);useEffect(()=>{if(!ve)return void(je.current=se);let e;return se&&!je.current&&(be||(setNativeValue(ye,0),e=Animated.sequence([Animated.timing(ye,{toValue:1,duration:50,useNativeDriver:!0}),Animated.timing(ye,{toValue:-1,duration:50,useNativeDriver:!0}),Animated.timing(ye,{toValue:1,duration:50,useNativeDriver:!0}),Animated.timing(ye,{toValue:-1,duration:50,useNativeDriver:!0}),Animated.timing(ye,{toValue:0,duration:100,useNativeDriver:!0})]),e.start()),triggerHaptic("notificationError")),je.current=se,()=>e?.stop()},[se,ye,ve,be]);const Fe=useCallback(e=>{Y(!0),P?.(e)},[P]),we=useCallback(e=>{Y(!1),E?.(e)},[E]),ze=useCallback(()=>{triggerHaptic("selection"),ee(e=>!e)},[]),Te=useMemo(()=>{const e=q.components.input?.fillColors?.[K];if(!e)return;const t={};return void 0!==e.idleEmpty&&(t.backgroundIdleEmpty=e.idleEmpty),void 0!==e.idleFilled&&(t.backgroundIdleFilled=e.idleFilled),void 0!==e.focus&&(t.backgroundFocused=e.focus),void 0!==e.error&&(t.backgroundError=e.error),void 0!==e.disabled&&(t.backgroundDisabled=e.disabled),Object.keys(t).length>0?t:void 0},[q.components.input?.fillColors,K]),Ie=q.colors.field.caret,Re=L??q.components.input?.borderRadius,Ve=q.components.input?.tintLabelOnFocus??!1,
|
|
1
|
+
"use strict";import{forwardRef,useCallback,useEffect,useMemo,useRef,useState}from"react";import{Animated,Easing,Pressable,StyleSheet,Text,TextInput,View}from"react-native";import{useReducedMotion}from"../../hooks/index.js";import{createAnimatedValue,fontFor,setNativeValue,useTheme}from"../../theme/index.js";import{mergeRefs,triggerHaptic}from"../../utils/index.js";import{defaultIcons}from"../AppIcon/defaultIcons.js";import{renderSlotIcon}from"../AppIcon/slotIcon.js";import{Button}from"../Button/index.js";import{FieldBase,FieldErrorGlyph,FieldLabel,fieldTextAsString,hasFieldText,RequiredPlaceholder,resolveFieldSize,resolveFieldTextStyle}from"../FieldBase/FieldBase.js";import{useFloatingLabel}from"../FieldBase/useFloatingLabel.js";import{NotationInkContext,useNotationInk}from"../Notation/Notation.js";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const multilineMinHeightMap={sm:72,md:92,lg:110},Input=forwardRef((e,t)=>{const{label:i,help:o,placeholder:n,value:l,onChangeText:r,error:s,helperText:a,type:d="input",secureTextEntry:c=!1,showPasswordToggle:u=!1,disabled:f=!1,multiline:p=!1,leftIcon:g,rightIcon:m,unit:x,unitStyle:h,prefix:y,prefixStyle:S,readOnly:b=!1,action:v,actionStyle:j,size:F="md",variant:w,labelMode:z,required:T=!1,maxLength:I,showCounter:R=!0,textAlign:V,format:_,parse:k,style:A,containerStyle:C,inputStyle:N,labelStyle:D,messageStyle:H,borderRadius:L,onFocus:P,onBlur:E,accessibilityLabel:M,testID:B,editable:O,...G}=e,q=useTheme(),W=useMemo(()=>buildStyles(q),[q]),$=resolveFieldSize(q,F),X=multilineMinHeightMap[F],J=Math.round(1.4*$.fontSize),K=w??q.components.input?.defaultVariant??q.components.field?.defaultVariant??"outlined",Q=z??q.components.input?.defaultLabelMode??"top",[U,Y]=useState(!1),[Z,ee]=useState(!1),te="password"===d||u||c,ie="password"===d||u,oe="textarea"===d||p,ne=oe?Math.round(.1*$.fontSize):0,le="string"==typeof l&&l.length>0,re=hasFieldText(s),se=!0===s||re,ae=hasFieldText(a),de=re||!se&&ae,ce=hasFieldText(i),ue=hasFieldText(y),fe=!f&&!1!==O,pe=U||le||ue,ge=useRef(null),me=useMemo(()=>mergeRefs(ge,t),[t]),xe=useCallback(()=>{fe&&ge.current?.focus()},[fe]),he=ce&&"float"===Q,ye=useRef(createAnimatedValue(0)).current,Se=useRef(createAnimatedValue(de?1:0)).current;useEffect(()=>{const e=Animated.timing(Se,{toValue:de?1:0,duration:q.motion.duration.fast,easing:Easing.bezier(...q.motion.easing.standard),useNativeDriver:!0});return e.start(),()=>e.stop()},[de,Se,q.motion.duration.fast,q.motion.easing.standard]);const be=useReducedMotion(),ve=q.components.input?.shakeOnError??!1,je=useRef(se);useEffect(()=>{if(!ve)return void(je.current=se);let e;return se&&!je.current&&(be||(setNativeValue(ye,0),e=Animated.sequence([Animated.timing(ye,{toValue:1,duration:50,useNativeDriver:!0}),Animated.timing(ye,{toValue:-1,duration:50,useNativeDriver:!0}),Animated.timing(ye,{toValue:1,duration:50,useNativeDriver:!0}),Animated.timing(ye,{toValue:-1,duration:50,useNativeDriver:!0}),Animated.timing(ye,{toValue:0,duration:100,useNativeDriver:!0})]),e.start()),triggerHaptic("notificationError")),je.current=se,()=>e?.stop()},[se,ye,ve,be]);const Fe=useCallback(e=>{Y(!0),P?.(e)},[P]),we=useCallback(e=>{Y(!1),E?.(e)},[E]),ze=useCallback(()=>{triggerHaptic("selection"),ee(e=>!e)},[]),Te=useMemo(()=>{const e=q.components.input?.fillColors?.[K];if(!e)return;const t={};return void 0!==e.idleEmpty&&(t.backgroundIdleEmpty=e.idleEmpty),void 0!==e.idleFilled&&(t.backgroundIdleFilled=e.idleFilled),void 0!==e.focus&&(t.backgroundFocused=e.focus),void 0!==e.error&&(t.backgroundError=e.error),void 0!==e.disabled&&(t.backgroundDisabled=e.disabled),Object.keys(t).length>0?t:void 0},[q.components.input?.fillColors,K]),Ie=q.colors.field.caret,Re=L??q.components.input?.borderRadius,Ve=q.components.input?.tintLabelOnFocus??!1,ke=U&&Ve?q.colors.field.borderFocused:q.colors.field.label,Ae=ye.interpolate({inputRange:[-1,0,1],outputRange:[-6,0,6]}),Ce=Boolean(m)||Boolean(x)||ie,Ne="underline"===K,De=g?$.iconSize+q.spacing.md+1+q.spacing.md:0,He=useFloatingLabel({label:i,enabled:he,floated:pe,required:T,variant:K,sizeTokens:$,leadingOffset:De,trailingOffset:Ce?$.iconSize+q.spacing.sm:0,textAlign:V,paddingLeft:Ne?0:$.paddingHorizontal,lineHeight:oe?J:void 0,restNudge:ne,floatTrim:oe?2:0,color:ke,style:D}),Le=resolveFieldTextStyle(q,{disabled:f}),Pe=Le.color,Ee=Le.placeholderColor,Me=T&&!ce&&!le&&"string"==typeof n&&n.length>0,Be=se?s:a,Oe=R&&"number"==typeof I&&"string"==typeof l?`${l.length} / ${I}`:null,Ge=se?q.colors.field.message:q.colors.text.secondary,qe=useNotationInk(H,$.messageFontSize,Ge),We=M??fieldTextAsString(i)??n,$e=q.colors.field,Xe=f?$e.iconDisabled:U?$e.iconFocused:$e.icon,Je={focused:U,disabled:f,error:se,color:Xe,size:$.iconSize},renderSlot=e=>renderSlotIcon(e,Je),Ke=(()=>{if(ie){const e=(Z?q.icons?.eyeOff:q.icons?.eye)??(Z?defaultIcons.eyeOff:defaultIcons.eye);return _jsx(Pressable,{onPress:ze,disabled:!fe,hitSlop:8,accessibilityRole:"button",accessibilityLabel:Z?"Hide password":"Show password",children:e({size:$.iconSize,color:Xe})})}const e=x?_jsx(Text,{style:[W.unit,{fontSize:$.fontSize,color:Ee},h],children:x}):null,t=m?_jsx(View,{children:renderSlot(m)}):null;return e&&t?_jsxs(View,{style:W.trailingRow,children:[e,t]}):e??t})(),Qe=g?_jsx(View,{children:renderSlot(g)}):null,Ue=StyleSheet.flatten(S),Ye=Ue?.fontSize??$.fontSize,Ze=Ue?.color??Ee,et=useMemo(()=>({fontSize:Ye,color:Ze}),[Ye,Ze]),tt=ue?"string"==typeof y||"number"==typeof y?_jsx(Text,{style:[W.prefix,{fontSize:$.fontSize,color:Ee,marginRight:q.spacing.xs,lineHeight:oe?J:void 0,paddingTop:oe?ne:void 0},S],children:y}):_jsx(View,{style:[W.prefixNode,{marginRight:q.spacing.xs,minHeight:oe?J:void 0,justifyContent:"center",paddingTop:oe?ne:void 0}],children:_jsx(Text,{style:[W.prefix,{fontSize:$.fontSize,color:Ee,lineHeight:oe?J:void 0},S],children:_jsx(NotationInkContext.Provider,{value:et,children:y})})}):null,it=v?_jsx(Button,{variant:v.variant??"outline",tone:v.tone??"primary",size:F,title:v.label,leftIcon:v.icon,loading:v.loading,disabled:f||v.disabled,onPress:v.onPress,pressAnimation:!1,testID:v.testID,style:[W.action,{minHeight:$.minHeight,alignSelf:oe?"flex-start":"stretch"},j]}):null;return _jsxs(Animated.View,{style:[W.container,{transform:[{translateX:Ae}]},A],children:[ce&&!he?_jsx(FieldLabel,{size:F,required:T,help:o,color:ke,style:D,children:i}):null,_jsxs(View,{style:[W.fieldRow,{columnGap:q.spacing.sm,alignItems:oe?"flex-start":"stretch"}],children:[_jsxs(View,{style:W.fieldWrapper,children:[_jsxs(FieldBase,{size:F,variant:K,focused:U,disabled:f,error:se,filled:le,minHeight:oe?X:void 0,borderRadius:Re,fillOverrides:Te,leading:Qe,leadingDivider:null!=g,paddingLeft:Ne?0:void 0,trailing:Ke,slotAlign:oe?"top":"center",slotLineHeight:oe?J:void 0,topNotch:He.topNotch,onPress:xe,pressFeedback:!1,style:C,children:[tt,_jsxs(View,{style:W.inputWrap,children:[_jsx(TextInput,{ref:me,style:[W.input,{color:Pe,fontSize:$.fontSize,...Le.weightStyle,paddingLeft:Ne?0:void 0,minHeight:oe?X-2*$.paddingVertical:void 0,lineHeight:oe?J:void 0,paddingTop:oe?ne:void 0,textAlignVertical:oe?"top":"center"},N],textAlign:V,placeholder:he&&!pe||Me?void 0:n,placeholderTextColor:Ee,value:_&&null!=l?_(l):l,onChangeText:e=>{r&&r(k?k(e):e)},onFocus:Fe,onBlur:we,editable:fe,readOnly:b,secureTextEntry:te&&!Z,multiline:oe,autoCapitalize:te?"none":void 0,autoCorrect:!te&&void 0,maxLength:I,selectionColor:Ie,accessibilityLabel:We,accessibilityState:{disabled:f},"aria-disabled":f,testID:B,...G}),Me?_jsx(RequiredPlaceholder,{text:n,color:Ee,fontSize:$.fontSize,weightStyle:Le.weightStyle,align:oe?"top":"center",paddingTop:oe?ne:void 0,textAlign:V}):null]})]}),He.node]}),it]}),de||Oe?_jsxs(View,{style:[W.footerRow,{marginTop:$.messageGap}],children:[de?_jsxs(Animated.View,{style:[W.messageRow,{columnGap:q.spacing.xs+2,opacity:Se}],accessibilityLiveRegion:se?"polite":"none",children:[se?_jsx(FieldErrorGlyph,{size:$.messageFontSize,color:Ge}):null,_jsx(Text,{style:[W.messageText,{color:Ge,fontSize:$.messageFontSize,...fontFor(q,"normal")},H],children:_jsx(NotationInkContext.Provider,{value:qe,children:Be})})]}):_jsx(View,{style:W.footerSpacer}),Oe?_jsx(Text,{style:[W.counterText,{color:q.colors.text.tertiary,fontSize:$.messageFontSize,...fontFor(q,"normal")}],children:Oe}):null]}):null]})});Input.displayName="Input";const buildStyles=e=>StyleSheet.create({container:{width:"100%"},fieldRow:{flexDirection:"row"},fieldWrapper:{position:"relative",overflow:"visible",flex:1},action:{flexShrink:0},input:{padding:0,margin:0,includeFontPadding:!1},prefix:{flexShrink:0,includeFontPadding:!1},prefixNode:{flexShrink:0},inputWrap:{flex:1,alignSelf:"stretch",justifyContent:"center"},unit:{includeFontPadding:!1},trailingRow:{flexDirection:"row",alignItems:"center",columnGap:8},footerRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",columnGap:8},footerSpacer:{flex:1},messageRow:{flex:1,flexDirection:"row",alignItems:"center"},messageText:{flexShrink:1,includeFontPadding:!1},counterText:{flexShrink:0,includeFontPadding:!1}});export{Input};export default Input;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{useEffect,useMemo,useRef,useState}from"react";import{AccessibilityInfo,Animated,BackHandler,Easing,StyleSheet}from"react-native";import{useReducedMotion}from"../../hooks/useReducedMotion.js";import{createAnimatedValue,useTheme}from"../../theme/index.js";import{Spinner}from"../Spinner/index.js";import{jsx as _jsx}from"react/jsx-runtime";const DEFAULT_SHOW_DELAY_MS=150,DEFAULT_MIN_VISIBLE_MS=400;let state={refCount:0,message:void 0};const listeners=new Set,notify=()=>{for(const e of listeners)e()},subscribe=e=>(listeners.add(e),()=>{listeners.delete(e)}),getState=()=>state,show=e=>{state={refCount:state.refCount+1,message:e??state.message},notify()},hide=()=>{if(state.refCount<=0)return;const e=state.refCount-1;state={refCount:e,message:0===e?void 0:state.message},notify()},reset=()=>{0===state.refCount&&void 0===state.message||(state={refCount:0,message:void 0},notify())},isVisible=()=>state.refCount>0,wrap=async(e,t)=>{show(t);try{return await("function"==typeof e?e():e)}finally{hide()}};export const loader={show:show,hide:hide,wrap:wrap,isVisible:isVisible,reset:reset};export const useLoader=()=>loader;export const LoaderOverlay=({renderIndicator:e,backdropColor:t,showDelayMs:s=150,minVisibleMs:r=400,testID:n})=>{const i=useTheme(),o=useReducedMotion(),
|
|
1
|
+
"use strict";import{useEffect,useMemo,useRef,useState,useSyncExternalStore}from"react";import{AccessibilityInfo,Animated,BackHandler,Easing,StyleSheet}from"react-native";import{useReducedMotion}from"../../hooks/useReducedMotion.js";import{createAnimatedValue,useTheme}from"../../theme/index.js";import{Spinner}from"../Spinner/index.js";import{jsx as _jsx}from"react/jsx-runtime";const DEFAULT_SHOW_DELAY_MS=150,DEFAULT_MIN_VISIBLE_MS=400;let state={refCount:0,message:void 0};const listeners=new Set,notify=()=>{for(const e of listeners)e()},subscribe=e=>(listeners.add(e),()=>{listeners.delete(e)}),getState=()=>state,show=e=>{state={refCount:state.refCount+1,message:e??state.message},notify()},hide=()=>{if(state.refCount<=0)return;const e=state.refCount-1;state={refCount:e,message:0===e?void 0:state.message},notify()},reset=()=>{0===state.refCount&&void 0===state.message||(state={refCount:0,message:void 0},notify())},isVisible=()=>state.refCount>0,wrap=async(e,t)=>{show(t);try{return await("function"==typeof e?e():e)}finally{hide()}};export const loader={show:show,hide:hide,wrap:wrap,isVisible:isVisible,reset:reset};export const useLoader=()=>loader;export const LoaderOverlay=({renderIndicator:e,backdropColor:t,showDelayMs:s=150,minVisibleMs:r=400,testID:n})=>{const i=useTheme(),o=useReducedMotion(),a=useSyncExternalStore(subscribe,getState),[u,l]=useState(!1),c=useRef(null),f=useRef(null),d=useRef(null),m=useRef(createAnimatedValue(0)).current,y=a.refCount>0;useEffect(()=>{if(y)return null!==f.current&&(clearTimeout(f.current),f.current=null),void(u||null!==c.current||(c.current=setTimeout(()=>{c.current=null,0!==getState().refCount&&(d.current=Date.now(),l(!0))},s)));if(null!==c.current&&(clearTimeout(c.current),c.current=null),u&&null===f.current){const e=null!==d.current?Date.now()-d.current:r,t=Math.max(0,r-e);f.current=setTimeout(()=>{f.current=null,d.current=null,l(!1)},t)}},[y,u,s,r]),useEffect(()=>()=>{null!==c.current&&clearTimeout(c.current),null!==f.current&&clearTimeout(f.current)},[]),useEffect(()=>{u?o?m.setValue(1):Animated.timing(m,{toValue:1,duration:i.motion.duration.normal,easing:Easing.bezier(...i.motion.easing.standard),useNativeDriver:!0}).start():m.setValue(0)},[u,o,m,i]),useEffect(()=>{if(!u)return;const e=BackHandler.addEventListener("hardwareBackPress",()=>!0);return()=>{e.remove()}},[u]);const b=a.message;useEffect(()=>{u&&b&&AccessibilityInfo.announceForAccessibility(b)},[u,b]);const S=useMemo(()=>buildStyles(),[]);return u?_jsx(Animated.View,{pointerEvents:"auto",testID:n,accessible:!0,accessibilityViewIsModal:!0,accessibilityLiveRegion:"polite",accessibilityLabel:b??"Loading",accessibilityRole:"progressbar",accessibilityState:{busy:!0},"aria-busy":!0,style:[S.overlay,{backgroundColor:t??i.colors.background.overlay,opacity:m}],children:e?e(b):_jsx(Spinner,{size:"lg",message:b})}):null};const buildStyles=()=>StyleSheet.create({overlay:{...StyleSheet.absoluteFill,alignItems:"center",justifyContent:"center",zIndex:1e3}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{useCallback,useEffect,useMemo,useRef,useState}from"react";import{Animated,Easing,Modal,Platform,Pressable,ScrollView,StyleSheet,useWindowDimensions,View}from"react-native";import{useSafeAreaInsets}from"react-native-safe-area-context";import{useReducedMotion}from"../../hooks/useReducedMotion.js";import{createAnimatedValue,setNativeValue,useTheme}from"../../theme/index.js";import{smoothCorners}from"../../utils/corners.js";import{resolveHaptic,triggerHaptic}from"../../utils/hapticUtils.js";import{claimAnchoredSurface,computePlacement,PLACEMENT_MARGIN,placementRoom}from"../../utils/placement.js";import{Breakpoints}from"../../utils/responsive.js";import{AppIcon}from"../AppIcon/AppIcon.js";import{renderSlotIcon}from"../AppIcon/slotIcon.js";import{Divider}from"../Divider/index.js";import{OptionSheet}from"../OptionSheet/index.js";import{Text}from"../Text/index.js";import{ToastHost}from"../Toast/ToastProvider.js";import{FOCUS_DELAY_MS,focusHost}from"./focusHost.js";import{visibleGroups,visibleTopActions,wantsSheet}from"./menuModel.js";import{webOnly}from"./webOnly.js";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";const MENU_MIN_WIDTH=180,MENU_MAX_WIDTH=280,ROW_MIN_HEIGHT=48,TOP_ACTION_MIN_HEIGHT=64,ICON_SIZE=20,PREVIEW_LIFT=1.02,BACK_KEY="__menu-back",TOP_PREFIX="__menu-top:",WEB_CHECKABLE_ROLE=webOnly({role:"menuitemcheckbox"});export const MenuSurface=e=>{const{open:t,anchor:s,items:i,title:o,topActions:r,placement:n,presentation:l,unavailable:a,context:c=!1,preview:u,onClose:d,restoreFocusTo:m,haptic:p,accessibilityLabel:b,closeLabel:f,backLabel:h,testID:y}=e,x=useTheme(),g=useMemo(()=>buildStyles(x),[x]),_=useSafeAreaInsets(),v=useWindowDimensions(),w=useReducedMotion(),j=useMemo(()=>visibleGroups(i,a),[i,a]),A=useMemo(()=>visibleTopActions(r,a),[r,a]),k="sheet"===l||"auto"===l&&v.width<Breakpoints.lg&&wantsSheet(j,A),[I,S]=useState(null),[E,R]=useState(null),T=useRef(d);T.current=d;const C=useRef(m);C.current=m;const L=useRef(null),D=useRef(!1),M=useRef(!1),O=useRef(new Map),P=useRef(null),H=useCallback(()=>{if(!D.current)return;D.current=!1;const e=L.current;L.current=null,e?e():focusHost(C.current?.())},[]);useEffect(()=>{if(t)return M.current=!0,D.current=!1,L.current=null,claimAnchoredSurface(()=>T.current());M.current&&(M.current=!1,D.current=!0,S(null),R(null),k||"ios"===Platform.OS||H())},[t]);const V=useCallback(e=>{if(e.disabled)return;const t=resolveHaptic(p,"selection");t&&triggerHaptic(t),e.key!==BACK_KEY?e.submenu?S(e):(L.current=e.onPress??null,T.current()):S(null)},[p]),B=useMemo(()=>({width:v.width,height:v.height,insets:_}),[v.width,v.height,_]),N=useMemo(()=>{if(!s||!E)return null;const e=s.x+s.width/2>B.width/2?"end":"start";return computePlacement(s,E,B,n,{align:e})},[s,E,B,n]);let F=B.height-_.top-_.bottom-2*PLACEMENT_MARGIN;if(s&&N){const e=placementRoom(s,B);F="top"===N.placement?e.above:e.below}const K=Math.min(280,B.width-_.left-_.right-2*PLACEMENT_MARGIN),W=t&&null!==N,G=useRef(createAnimatedValue(0)).current,z=useRef(createAnimatedValue(1)).current;useEffect(()=>{if(!W)return setNativeValue(G,0),void setNativeValue(z,1);const e=[Animated.timing(G,{toValue:1,duration:x.motion.duration.fast,easing:Easing.bezier(...x.motion.easing.decelerate),useNativeDriver:!0})];c&&!w&&e.push(Animated.spring(z,{toValue:1.02,damping:x.motion.spring.snappy.damping,stiffness:x.motion.spring.snappy.stiffness,mass:x.motion.spring.snappy.mass,useNativeDriver:!0}));const t=Animated.parallel(e);return t.start(),()=>t.stop()},[W,c,w,G,z,x.motion]);const $=useCallback(e=>{const{width:t,height:s}=e.nativeEvent.layout;R(e=>e&&e.width===t&&e.height===s?e:{width:t,height:s})},[]),Y=c&&"top"===N?.placement,U=I?.submenu?[I.submenu]:j,X=Y?[...U].reverse().map(e=>[...e].reverse()):U,q=[];if(I)q.push({key:BACK_KEY,label:I.label});else for(const e of A)q.push({key:`${TOP_PREFIX}${e.key}`,label:e.label,item:e});for(const e of X)for(const t of e)q.push({key:t.key,label:t.label,item:t});const Z=q[0]?.key;useEffect(()=>{if(!W||k||!Z)return;const e=setTimeout(()=>focusHost(O.current.get(Z)),FOCUS_DELAY_MS);return()=>clearTimeout(e)},[W,k,Z]);const setItemRef=e=>t=>{t?O.current.set(e,t):O.current.delete(e)},J=webOnly({onKeyDown:e=>{const t=e.key??e.nativeEvent?.key??"",s=q.length,i=q.findIndex(e=>e.key===P.current);let o=-1;if("ArrowDown"===t)o=(i+1)%s;else if("ArrowUp"===t)o=i<=0?s-1:i-1;else if("Home"===t)o=0;else if("End"===t)o=s-1;else{if("ArrowLeft"===t&&I)return e.preventDefault?.(),void S(null);if("ArrowRight"===t&&q[i]?.item?.submenu)return e.preventDefault?.(),void V(q[i].item);if(1===t.length&&""!==t.trim()){const e=t.toLowerCase();for(let t=1;t<=s;t+=1){const r=(i+t)%s;if(q[r].label.toLowerCase().startsWith(e)){o=r;break}}}}o>=0&&(e.preventDefault?.(),(e=>{const t=q[e];t&&focusHost(O.current.get(t.key))})(o))}});if(k){const e=I?.submenu?[{key:BACK_KEY,label:h,icon:"chevron-left"},...I.submenu]:[...A,...j.flat()],s=new Set(e.filter(e=>e.checked).map(e=>e.key));return _jsx(OptionSheet,{open:t,onClose:d,onAfterClose:H,title:I?.label??o,options:e,labelOf:e=>e.label,getValue:e=>e.key,disabledOf:e=>Boolean(e.disabled),destructiveOf:e=>Boolean(e.destructive),descriptionOf:e=>e.description,iconOf:e=>{const t=e;return renderSlotIcon(t.icon,{color:t.destructive?x.colors.toneText.error:x.colors.text.secondary,size:20,disabled:Boolean(t.disabled)})},isSelected:e=>s.has(String(e)),onSelect:e=>V(e),accessibilityLabel:b??o,testID:y?`${y}-sheet`:void 0})}const inkFor=e=>e.disabled?x.colors.text.disabled:e.destructive?x.colors.toneText.error:x.colors.text.primary,Q=_jsxs(_Fragment,I?{children:[_jsxs(Pressable,{ref:setItemRef(BACK_KEY),onPress:()=>S(null),onFocus:()=>{P.current=BACK_KEY},accessibilityRole:"menuitem",accessibilityLabel:`${h}, ${I.label}`,android_ripple:{color:x.colors.surface.pressed,borderless:!1},style:({pressed:e})=>[g.row,e?g.pressed:null],children:[_jsx(View,{style:g.icon,children:_jsx(AppIcon,{name:"chevron-left",size:20,color:x.colors.text.secondary})}),_jsx(Text,{variant:"body",weight:"semibold",numberOfLines:1,style:g.labels,children:I.label})]}),_jsx(Divider,{spacing:"none"})]}:{children:[o?_jsx(Text,{variant:"caption",color:"secondary",accessibilityRole:"header",numberOfLines:2,style:g.title,children:o}):null,A.length>0?_jsxs(_Fragment,{children:[_jsx(View,{style:g.topRow,children:A.map(e=>{const t=`${TOP_PREFIX}${e.key}`,s=Boolean(e.disabled),i=inkFor(e);return _jsxs(Pressable,{ref:setItemRef(t),onPress:()=>V(e),onFocus:()=>{P.current=t},disabled:s,accessibilityRole:"menuitem",accessibilityLabel:e.accessibilityLabel??e.label,accessibilityState:{disabled:s},"aria-disabled":s,testID:e.testID,style:({pressed:e})=>[g.topAction,e?g.pressed:null],children:[renderSlotIcon(e.icon,{color:i,size:20,disabled:s}),_jsx(Text,{variant:"caption",color:i,numberOfLines:1,children:e.label})]},t)})}),_jsx(Divider,{spacing:"none"})]}):null]});return _jsxs(Modal,{visible:t,transparent:!0,statusBarTranslucent:!0,presentationStyle:"overFullScreen",animationType:"none",onRequestClose:d,onDismiss:H,children:[_jsx(Pressable,{style:[StyleSheet.absoluteFill,c?g.scrim:null],onPress:d,accessibilityRole:"button",accessibilityLabel:f,testID:y?`${y}-scrim`:void 0}),c&&u&&s?_jsx(Animated.View,{pointerEvents:"none",accessibilityElementsHidden:!0,importantForAccessibility:"no-hide-descendants",style:[g.preview,{left:s.x,top:s.y,width:s.width,height:s.height,transform:[{scale:z}]}],children:u}):null,_jsx(Animated.View,{accessibilityRole:"menu",accessibilityLabel:I?.label??b??o,onLayout:$,testID:y?`${y}-menu`:void 0,...J,style:[g.anchored,{left:N?.x??0,top:N?.y??0,maxWidth:K,opacity:W?G:0}],children:_jsx(View,{style:g.surface,children:_jsxs(View,{style:[g.clip,{maxHeight:F}],children:[Q,_jsx(ScrollView,{style:g.scroll,bounces:!1,keyboardShouldPersistTaps:"handled",children:X.map((e,t)=>{const s=e.some(e=>null!=e.icon);return _jsxs(View,{children:[t>0?_jsx(Divider,{spacing:"none"}):null,e.map(e=>((e,t)=>{const s=Boolean(e.disabled),i=inkFor(e);return _jsxs(Pressable,{ref:setItemRef(e.key),onPress:()=>V(e),onFocus:()=>{P.current=e.key},disabled:s,accessibilityRole:"menuitem",accessibilityLabel:e.accessibilityLabel??e.label,accessibilityState:{disabled:s,checked:e.checked},"aria-disabled":s,"aria-checked":e.checked,...void 0!==e.checked?WEB_CHECKABLE_ROLE:null,android_ripple:{color:x.colors.surface.pressed,borderless:!1},testID:e.testID,style:({pressed:e})=>[g.row,e?g.pressed:null],children:[t?_jsx(View,{style:g.icon,children:renderSlotIcon(e.icon,{color:i,size:20,disabled:s})}):null,_jsxs(View,{style:g.labels,children:[_jsx(Text,{variant:"body",color:i,numberOfLines:2,children:e.label}),e.description?_jsx(Text,{variant:"caption",color:"secondary",numberOfLines:2,children:e.description}):null]}),e.detail?_jsx(Text,{variant:"caption",color:"tertiary",children:e.detail}):null,e.checked?_jsx(AppIcon,{name:"check",size:20,color:x.colors.primary}):null,e.submenu?_jsx(AppIcon,{name:"chevron-right",size:20,color:x.colors.text.tertiary}):null]},e.key)})(e,s))]},e[0].key)})})]})})}),_jsx(ToastHost,{})]})};const buildStyles=e=>StyleSheet.create({scrim:{backgroundColor:e.colors.background.overlay},preview:{position:"absolute"},anchored:{position:"absolute",minWidth:180},surface:{backgroundColor:e.colors.background.elevated,borderRadius:e.radius.md,...smoothCorners,...e.shadows.lg},clip:{borderRadius:e.radius.md,...smoothCorners,overflow:"hidden"},scroll:{flexGrow:0,flexShrink:1},title:{paddingHorizontal:e.spacing.md,paddingTop:e.spacing.sm,paddingBottom:e.spacing.xs},row:{flexDirection:"row",alignItems:"center",gap:e.spacing.md,minHeight:48,paddingHorizontal:e.spacing.md,paddingVertical:e.spacing.sm},pressed:{backgroundColor:e.colors.surface.pressed},icon:{width:20,alignItems:"center"},labels:{flexGrow:1,flexShrink:1},topRow:{flexDirection:"row",padding:e.spacing.xs,gap:e.spacing.xs},topAction:{flexGrow:1,flexBasis:0,alignItems:"center",justifyContent:"center",gap:e.spacing.xs,minHeight:64,borderRadius:e.radius.sm,...smoothCorners}});
|
|
1
|
+
"use strict";import{useCallback,useEffect,useMemo,useRef,useState}from"react";import{Animated,Easing,Modal,Platform,Pressable,ScrollView,StyleSheet,useWindowDimensions,View}from"react-native";import{useSafeAreaInsets}from"react-native-safe-area-context";import{useReducedMotion}from"../../hooks/useReducedMotion.js";import{createAnimatedValue,setNativeValue,useTheme}from"../../theme/index.js";import{smoothCorners}from"../../utils/corners.js";import{resolveHaptic,triggerHaptic}from"../../utils/hapticUtils.js";import{claimAnchoredSurface,computePlacement,PLACEMENT_MARGIN,placementRoom}from"../../utils/placement.js";import{Breakpoints}from"../../utils/responsive.js";import{AppIcon}from"../AppIcon/AppIcon.js";import{renderSlotIcon}from"../AppIcon/slotIcon.js";import{Divider}from"../Divider/index.js";import{ModalSafeArea,useModalInsets}from"../ModalSafeArea/ModalSafeArea.js";import{OptionSheet}from"../OptionSheet/index.js";import{Text}from"../Text/index.js";import{ToastHost}from"../Toast/ToastProvider.js";import{FOCUS_DELAY_MS,focusHost}from"./focusHost.js";import{visibleGroups,visibleTopActions,wantsSheet}from"./menuModel.js";import{webOnly}from"./webOnly.js";import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";const MENU_MIN_WIDTH=180,MENU_MAX_WIDTH=280,ROW_MIN_HEIGHT=48,TOP_ACTION_MIN_HEIGHT=64,ICON_SIZE=20,PREVIEW_LIFT=1.02,BACK_KEY="__menu-back",TOP_PREFIX="__menu-top:",WEB_CHECKABLE_ROLE=webOnly({role:"menuitemcheckbox"});export const MenuSurface=e=>{const{open:t,anchor:s,items:o,title:i,topActions:r,placement:n,presentation:l,unavailable:a,context:c=!1,preview:u,onClose:d,restoreFocusTo:m,haptic:p,accessibilityLabel:b,closeLabel:f,backLabel:h,testID:y}=e,x=useTheme(),g=useMemo(()=>buildStyles(x),[x]),_=useSafeAreaInsets(),[v,w]=useModalInsets(),j=useMemo(()=>({..._,top:v.top,bottom:v.bottom}),[_,v]),A=useWindowDimensions(),S=useReducedMotion(),I=useMemo(()=>visibleGroups(o,a),[o,a]),k=useMemo(()=>visibleTopActions(r,a),[r,a]),E="sheet"===l||"auto"===l&&A.width<Breakpoints.lg&&wantsSheet(I,k),[R,T]=useState(null),[M,C]=useState(null),L=useRef(d);L.current=d;const D=useRef(m);D.current=m;const O=useRef(null),P=useRef(!1),H=useRef(!1),V=useRef(new Map),B=useRef(null),N=useCallback(()=>{if(!P.current)return;P.current=!1;const e=O.current;O.current=null,e?e():focusHost(D.current?.())},[]);useEffect(()=>{if(t)return H.current=!0,P.current=!1,O.current=null,claimAnchoredSurface(()=>L.current());H.current&&(H.current=!1,P.current=!0,T(null),C(null),E||"ios"===Platform.OS||N())},[t]);const F=useCallback(e=>{if(e.disabled)return;const t=resolveHaptic(p,"selection");t&&triggerHaptic(t),e.key!==BACK_KEY?e.submenu?T(e):(O.current=e.onPress??null,L.current()):T(null)},[p]),K=useMemo(()=>({width:A.width,height:A.height,insets:j}),[A.width,A.height,j]),W=useMemo(()=>{if(!s||!M)return null;const e=s.x+s.width/2>K.width/2?"end":"start";return computePlacement(s,M,K,n,{align:e})},[s,M,K,n]);let G=K.height-j.top-j.bottom-2*PLACEMENT_MARGIN;if(s&&W){const e=placementRoom(s,K);G="top"===W.placement?e.above:e.below}const z=Math.min(280,K.width-j.left-j.right-2*PLACEMENT_MARGIN),$=t&&null!==W,Y=useRef(createAnimatedValue(0)).current,U=useRef(createAnimatedValue(1)).current;useEffect(()=>{if(!$)return setNativeValue(Y,0),void setNativeValue(U,1);const e=[Animated.timing(Y,{toValue:1,duration:x.motion.duration.fast,easing:Easing.bezier(...x.motion.easing.decelerate),useNativeDriver:!0})];c&&!S&&e.push(Animated.spring(U,{toValue:1.02,damping:x.motion.spring.snappy.damping,stiffness:x.motion.spring.snappy.stiffness,mass:x.motion.spring.snappy.mass,useNativeDriver:!0}));const t=Animated.parallel(e);return t.start(),()=>t.stop()},[$,c,S,Y,U,x.motion]);const X=useCallback(e=>{const{width:t,height:s}=e.nativeEvent.layout;C(e=>e&&e.width===t&&e.height===s?e:{width:t,height:s})},[]),q=c&&"top"===W?.placement,Z=R?.submenu?[R.submenu]:I,J=q?[...Z].reverse().map(e=>[...e].reverse()):Z,Q=[];if(R)Q.push({key:BACK_KEY,label:R.label});else for(const e of k)Q.push({key:`${TOP_PREFIX}${e.key}`,label:e.label,item:e});for(const e of J)for(const t of e)Q.push({key:t.key,label:t.label,item:t});const ee=Q[0]?.key;useEffect(()=>{if(!$||E||!ee)return;const e=setTimeout(()=>focusHost(V.current.get(ee)),FOCUS_DELAY_MS);return()=>clearTimeout(e)},[$,E,ee]);const setItemRef=e=>t=>{t?V.current.set(e,t):V.current.delete(e)},te=webOnly({onKeyDown:e=>{const t=e.key??e.nativeEvent?.key??"",s=Q.length,o=Q.findIndex(e=>e.key===B.current);let i=-1;if("ArrowDown"===t)i=(o+1)%s;else if("ArrowUp"===t)i=o<=0?s-1:o-1;else if("Home"===t)i=0;else if("End"===t)i=s-1;else{if("ArrowLeft"===t&&R)return e.preventDefault?.(),void T(null);if("ArrowRight"===t&&Q[o]?.item?.submenu)return e.preventDefault?.(),void F(Q[o].item);if(1===t.length&&""!==t.trim()){const e=t.toLowerCase();for(let t=1;t<=s;t+=1){const r=(o+t)%s;if(Q[r].label.toLowerCase().startsWith(e)){i=r;break}}}}i>=0&&(e.preventDefault?.(),(e=>{const t=Q[e];t&&focusHost(V.current.get(t.key))})(i))}});if(E){const e=R?.submenu?[{key:BACK_KEY,label:h,icon:"chevron-left"},...R.submenu]:[...k,...I.flat()],s=new Set(e.filter(e=>e.checked).map(e=>e.key));return _jsx(OptionSheet,{open:t,onClose:d,onAfterClose:N,title:R?.label??i,options:e,labelOf:e=>e.label,getValue:e=>e.key,disabledOf:e=>Boolean(e.disabled),destructiveOf:e=>Boolean(e.destructive),descriptionOf:e=>e.description,iconOf:e=>{const t=e;return renderSlotIcon(t.icon,{color:t.destructive?x.colors.toneText.error:x.colors.text.secondary,size:20,disabled:Boolean(t.disabled)})},isSelected:e=>s.has(String(e)),onSelect:e=>F(e),accessibilityLabel:b??i,testID:y?`${y}-sheet`:void 0})}const inkFor=e=>e.disabled?x.colors.text.disabled:e.destructive?x.colors.toneText.error:x.colors.text.primary,se=_jsxs(_Fragment,R?{children:[_jsxs(Pressable,{ref:setItemRef(BACK_KEY),onPress:()=>T(null),onFocus:()=>{B.current=BACK_KEY},accessibilityRole:"menuitem",accessibilityLabel:`${h}, ${R.label}`,android_ripple:{color:x.colors.surface.pressed,borderless:!1},style:({pressed:e})=>[g.row,e?g.pressed:null],children:[_jsx(View,{style:g.icon,children:_jsx(AppIcon,{name:"chevron-left",size:20,color:x.colors.text.secondary})}),_jsx(Text,{variant:"body",weight:"semibold",numberOfLines:1,style:g.labels,children:R.label})]}),_jsx(Divider,{spacing:"none"})]}:{children:[i?_jsx(Text,{variant:"caption",color:"secondary",accessibilityRole:"header",numberOfLines:2,style:g.title,children:i}):null,k.length>0?_jsxs(_Fragment,{children:[_jsx(View,{style:g.topRow,children:k.map(e=>{const t=`${TOP_PREFIX}${e.key}`,s=Boolean(e.disabled),o=inkFor(e);return _jsxs(Pressable,{ref:setItemRef(t),onPress:()=>F(e),onFocus:()=>{B.current=t},disabled:s,accessibilityRole:"menuitem",accessibilityLabel:e.accessibilityLabel??e.label,accessibilityState:{disabled:s},"aria-disabled":s,testID:e.testID,style:({pressed:e})=>[g.topAction,e?g.pressed:null],children:[renderSlotIcon(e.icon,{color:o,size:20,disabled:s}),_jsx(Text,{variant:"caption",color:o,numberOfLines:1,children:e.label})]},t)})}),_jsx(Divider,{spacing:"none"})]}):null]});return _jsx(Modal,{visible:t,transparent:!0,statusBarTranslucent:!0,presentationStyle:"overFullScreen",animationType:"none",onRequestClose:d,onDismiss:N,children:_jsxs(ModalSafeArea,{onInsets:w,children:[_jsx(Pressable,{style:[StyleSheet.absoluteFill,c?g.scrim:null],onPress:d,accessibilityRole:"button",accessibilityLabel:f,testID:y?`${y}-scrim`:void 0}),c&&u&&s?_jsx(Animated.View,{pointerEvents:"none",accessibilityElementsHidden:!0,importantForAccessibility:"no-hide-descendants",style:[g.preview,{left:s.x,top:s.y,width:s.width,height:s.height,transform:[{scale:U}]}],children:u}):null,_jsx(Animated.View,{accessibilityRole:"menu",accessibilityLabel:R?.label??b??i,onLayout:X,testID:y?`${y}-menu`:void 0,...te,style:[g.anchored,{left:W?.x??0,top:W?.y??0,maxWidth:z,opacity:$?Y:0}],children:_jsx(View,{style:g.surface,children:_jsxs(View,{style:[g.clip,{maxHeight:G}],children:[se,_jsx(ScrollView,{style:g.scroll,bounces:!1,keyboardShouldPersistTaps:"handled",children:J.map((e,t)=>{const s=e.some(e=>null!=e.icon);return _jsxs(View,{children:[t>0?_jsx(Divider,{spacing:"none"}):null,e.map(e=>((e,t)=>{const s=Boolean(e.disabled),o=inkFor(e);return _jsxs(Pressable,{ref:setItemRef(e.key),onPress:()=>F(e),onFocus:()=>{B.current=e.key},disabled:s,accessibilityRole:"menuitem",accessibilityLabel:e.accessibilityLabel??e.label,accessibilityState:{disabled:s,checked:e.checked},"aria-disabled":s,"aria-checked":e.checked,...void 0!==e.checked?WEB_CHECKABLE_ROLE:null,android_ripple:{color:x.colors.surface.pressed,borderless:!1},testID:e.testID,style:({pressed:e})=>[g.row,e?g.pressed:null],children:[t?_jsx(View,{style:g.icon,children:renderSlotIcon(e.icon,{color:o,size:20,disabled:s})}):null,_jsxs(View,{style:g.labels,children:[_jsx(Text,{variant:"body",color:o,numberOfLines:2,children:e.label}),e.description?_jsx(Text,{variant:"caption",color:"secondary",numberOfLines:2,children:e.description}):null]}),e.detail?_jsx(Text,{variant:"caption",color:"tertiary",children:e.detail}):null,e.checked?_jsx(AppIcon,{name:"check",size:20,color:x.colors.primary}):null,e.submenu?_jsx(AppIcon,{name:"chevron-right",size:20,color:x.colors.text.tertiary}):null]},e.key)})(e,s))]},e[0].key)})})]})})}),_jsx(ToastHost,{})]})})};const buildStyles=e=>StyleSheet.create({scrim:{backgroundColor:e.colors.background.overlay},preview:{position:"absolute"},anchored:{position:"absolute",minWidth:180},surface:{backgroundColor:e.colors.background.elevated,borderRadius:e.radius.md,...smoothCorners,...e.shadows.lg},clip:{borderRadius:e.radius.md,...smoothCorners,overflow:"hidden"},scroll:{flexGrow:0,flexShrink:1},title:{paddingHorizontal:e.spacing.md,paddingTop:e.spacing.sm,paddingBottom:e.spacing.xs},row:{flexDirection:"row",alignItems:"center",gap:e.spacing.md,minHeight:48,paddingHorizontal:e.spacing.md,paddingVertical:e.spacing.sm},pressed:{backgroundColor:e.colors.surface.pressed},icon:{width:20,alignItems:"center"},labels:{flexGrow:1,flexShrink:1},topRow:{flexDirection:"row",padding:e.spacing.xs,gap:e.spacing.xs},topAction:{flexGrow:1,flexBasis:0,alignItems:"center",justifyContent:"center",gap:e.spacing.xs,minHeight:64,borderRadius:e.radius.sm,...smoothCorners}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";import{forwardRef,useCallback,useEffect,useMemo,useRef,useState}from"react";import{AccessibilityInfo,Animated,Dimensions,Easing,Platform,Pressable,Modal as RNModal,StyleSheet,View}from"react-native";import{
|
|
1
|
+
"use strict";import{forwardRef,useCallback,useEffect,useMemo,useRef,useState}from"react";import{AccessibilityInfo,Animated,Dimensions,Easing,Platform,Pressable,Modal as RNModal,StyleSheet,View}from"react-native";import{createAnimatedValue,useTheme}from"../../theme/index.js";import{smoothCorners}from"../../utils/corners.js";import{resolveHaptic,triggerHaptic}from"../../utils/hapticUtils.js";import{squircleHostRadius}from"../../utils/squircle.js";import{ModalSafeArea,useModalInsets}from"../ModalSafeArea/ModalSafeArea.js";import{SquircleFill,useSquircle}from"../SquircleFill/SquircleFill.js";import{ToastHost}from"../Toast/ToastProvider.js";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";export const MODAL_DISMISS_GRACE_MS=300;const Modal=forwardRef((e,t)=>{const{visible:s,onRequestClose:o,presentation:r="centered",backdropOpacity:i,backdropPressClose:a=!0,animationDuration:n,accessibilityLabel:l,hardwareBackPress:c=!0,children:u,contentStyle:d,backdropStyle:m,restoreFocusRef:f,onDismissed:p,haptic:g,testID:b}=e,h=useTheme(),[S,y]=useModalInsets(),x=n??h.motion.duration.normal,v=Dimensions.get("window").height,A=h.components.modal,M=A?.scaleStartValue??.9,C=useRef(createAnimatedValue(M)).current,R=useRef(createAnimatedValue(0)).current,j=useRef(createAnimatedValue(v)).current,w=useRef(null),T=useRef(!1),[k,V]=useState(s),D=useMemo(()=>buildStyles(h),[h]),_=useMemo(()=>{const e=h.colors.background.overlay;if("number"!=typeof i)return e;const t=e.match(/^rgba?\(([^)]+)\)$/);if(!t)return e;const[s,o,r]=t[1].split(",").map(e=>e.trim());return`rgba(${s}, ${o}, ${r}, ${i})`},[h.colors.background.overlay,i]);useEffect(()=>{s&&V(!0)},[s]),useEffect(()=>{const e=[];if(s&&k)if("bottom"===r){const t=Animated.spring(j,{toValue:0,damping:h.motion.spring.gentle.damping,stiffness:h.motion.spring.gentle.stiffness,mass:h.motion.spring.gentle.mass,useNativeDriver:!0});t.start(),e.push(t)}else{const t=Animated.parallel([Animated.spring(C,{toValue:1,damping:h.motion.spring.gentle.damping,stiffness:h.motion.spring.gentle.stiffness,mass:h.motion.spring.gentle.mass,useNativeDriver:!0}),Animated.timing(R,{toValue:1,duration:x,useNativeDriver:!0})]);t.start(),e.push(t)}else if(k){const t=h.motion.duration.fast,s=Easing.bezier(...h.motion.easing.accelerate),o=Animated.parallel(["bottom"===r?Animated.timing(j,{toValue:v,duration:t,easing:s,useNativeDriver:!0}):Animated.parallel([Animated.timing(C,{toValue:M,duration:t,easing:s,useNativeDriver:!0}),Animated.timing(R,{toValue:0,duration:t,easing:s,useNativeDriver:!0})])]);o.start(({finished:e})=>{e&&V(!1)}),e.push(o)}return()=>e.forEach(e=>e.stop())},[s,k,r,x,C,R,j,v,h.motion.spring.gentle.damping,h.motion.spring.gentle.stiffness,h.motion.spring.gentle.mass,h.motion.duration.fast,h.motion.easing.accelerate,M]),useEffect(()=>{if("web"===Platform.OS)return;let e,t;return s?(e=setTimeout(()=>{w.current&&AccessibilityInfo.sendAccessibilityEvent(w.current,"focus")},150),T.current=!0):T.current&&(T.current=!1,f&&f.current&&(t=setTimeout(()=>{const e=f.current;e&&AccessibilityInfo.sendAccessibilityEvent(e,"focus")},x))),()=>{e&&clearTimeout(e),t&&clearTimeout(t)}},[s,x,f]);const E=useRef(!1);useEffect(()=>{if(s)return void(E.current=!0);if(!E.current)return;if(E.current=!1,!p)return;const e=setTimeout(p,300);return()=>clearTimeout(e)},[s,p]);const I=useCallback(()=>{if(!a)return;const e=resolveHaptic(g,"selection");e&&triggerHaptic(e),o()},[a,o,g]),q=useCallback(()=>{c&&o()},[c,o]),z=useSquircle("bottom"!==r&&"fullScreen"!==r,h.radius.xl),H=useMemo(()=>"fullScreen"===r?[D.fullScreenContent,{backgroundColor:h.colors.background.elevated}]:"bottom"===r?[D.bottomContent,{backgroundColor:h.colors.background.elevated,borderTopLeftRadius:h.radius.xl,borderTopRightRadius:h.radius.xl,...smoothCorners,paddingTop:h.spacing.lg,paddingHorizontal:h.spacing.lg,paddingBottom:h.spacing.lg+S.bottom},h.shadows.xl]:[D.centeredContent,{backgroundColor:h.colors.background.elevated,borderRadius:z.active&&z.size?squircleHostRadius(z.size.width,z.size.height,h.radius.xl):h.radius.xl,...smoothCorners,padding:h.spacing.xl},h.shadows.xl],[r,h,D,S.bottom,z.active,z.size]),N=useMemo(()=>"bottom"===r?D.bottomWrapper:"fullScreen"===r?D.fullScreenWrapper:D.centeredWrapper,[r,D]),P=useMemo(()=>"bottom"===r?{transform:[{translateY:j}]}:"fullScreen"===r?{opacity:R}:{opacity:R,transform:[{scale:C}]},[r,C,R,j]);return _jsx(RNModal,{visible:k,transparent:!0,statusBarTranslucent:!0,navigationBarTranslucent:!0,animationType:"none",onRequestClose:q,testID:b,children:_jsx(View,{ref:e=>{w.current=e,"function"==typeof t?t(e):t&&(t.current=e)},style:D.root,accessible:!1,accessibilityViewIsModal:!0,accessibilityRole:"alert",accessibilityLabel:l,children:_jsxs(ModalSafeArea,{onInsets:y,children:[_jsxs(View,{collapsable:!1,style:[StyleSheet.absoluteFill,N,{backgroundColor:_},m],children:[_jsx(Pressable,{style:StyleSheet.absoluteFill,onPress:I,accessibilityRole:"button",accessibilityLabel:"Close modal",disabled:!a}),_jsxs(Animated.View,{style:[H,P,d],onLayout:z.onLayout,pointerEvents:"auto",children:[z.active&&z.size?_jsx(SquircleFill,{width:z.size.width,height:z.size.height,radius:h.radius.xl,fill:h.colors.background.elevated}):null,u]})]}),_jsx(ToastHost,{})]})})})});Modal.displayName="Modal";const buildStyles=e=>StyleSheet.create({root:{flex:1},centeredWrapper:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:16},centeredContent:{maxWidth:"90%",width:"90%"},bottomWrapper:{flex:1,justifyContent:"flex-end"},bottomContent:{width:"100%"},fullScreenWrapper:{flex:1},fullScreenContent:{flex:1}});export{Modal};export default Modal;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";import{useEffect,useState}from"react";import{StyleSheet}from"react-native";import{SafeAreaProvider,useSafeAreaInsets}from"react-native-safe-area-context";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";export const useModalInsets=()=>{const{top:e,bottom:t}=useSafeAreaInsets();return useState({top:e,bottom:t})};export const InsetsProbe=({onChange:e})=>{const{top:t,bottom:s}=useSafeAreaInsets();return useEffect(()=>{e(e=>e.top===t&&e.bottom===s?e:{top:t,bottom:s})},[t,s,e]),null};export const ModalSafeArea=({onInsets:e,children:t})=>_jsxs(SafeAreaProvider,{style:styles.fill,children:[_jsx(InsetsProbe,{onChange:e}),t]});const styles=StyleSheet.create({fill:{flex:1}});
|