Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Accessible ♿, Delightful ✨, & Fast 🚀

License

NotificationsYou must be signed in to change notification settings

mattixbrand/bottomsheet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

npm statnpm versiongzip sizesizemodule formats: cjs, es, and modern

Logo with the text Accessible, Delightful and Performant

bottomsheet is built on top of[@react-spring/web] and[@use-gesture/react]. It busts the myth that accessibility and supporting keyboard navigation and screen readers are allegedly at odds with delightful, beautiful, and highly animated UIs. Every animation and transition use CSS custom properties instead of manipulating them directly, allowing complete control over the experience from CSS alone.

Latest Supported Library

Reactnpm versionReact-Domnpm versionNextJSnpm version@React-Spring/Webnpm versionUse-Gesture/Reactnpm version

Installation

NPM

npm install @mattixes/bottomsheet

OR

npm install --save @mattixes/bottomsheet

YARN

yarn add @mattixes/bottomsheet

PNPM

pnpm install @mattixes/bottomsheet

Getting started

Basic usage

import{useState}from'react'import{BottomSheet}from'@mattixes/bottomsheet'// if setting up the CSS is tricky, you can add this to your page somewhere:// <link rel="stylesheet" href="https://unpkg.com/@mattixes/bottomsheet@0.1.0/dist/style.css" crossorigin="anonymous">import'@mattixes/bottomsheet/dist/style.css'exportdefaultfunctionExample(){const[open,setOpen]=useState(false)return(<><buttononClick={()=>setOpen(true)}>Open</button><BottomSheetopen={open}>My awesome content here</BottomSheet></>)}

TypeScript

TS support is baked in, and if you're using thesnapTo API useBottomSheetRef:

import{useRef}from'react';import{BottomSheet,BottomSheetRef}from'@mattixes/bottomsheet';exportdefaultfunctionExample(){constsheetRef=useRef<BottomSheetRef|any>();return(<BottomSheetopenref={sheetRef}// the first snap points height depends on the content, while the second one is equivalent to 60vhsnapPoints={({ minHeight, maxHeight})=>[minHeight,maxHeight/0.6]}// Opens the largest snap point by default, unless the user selected one previouslydefaultSnap={({ lastSnap, snapPoints})=>lastSnap??Math.max(...snapPoints)}><buttononClick={()=>{// Full typing for the arguments available in snapTo, yay!!sheetRef.current?.snapTo(({ maxHeight}:{maxHeight:number;})=>maxHeight);}}>        Expand to full height<br/></button></BottomSheet>);}

Customizing the CSS

Using CSS Custom Properties

These are all the variables available to customize the look and feel when using theprovided CSS.

:root {--rsbs-backdrop-bg:rgba(0,0,0,0.6);--rsbs-bg:#fff;--rsbs-handle-bg:hsla(0,0%,0%,0.14);--rsbs-max-w: auto;--rsbs-ml:env(safe-area-inset-left);--rsbs-mr:env(safe-area-inset-right);--rsbs-overlay-rounded:16px;}

Custom CSS

It's recommended that you copy fromstyle.css into your own project, and add this to yourpostcss.config.js setup (npm i postcss-custom-properties-fallback):

module.exports={plugins:{// Ensures the default variables are available'postcss-custom-properties-fallback':{importFrom:require.resolve('@mattixes/bottomsheet/defaults.json'),},},}

View demo code

MVP example, showing what you get by implementingopen,onDismiss and a singlesnap point always set tominHeight.

View demo code

A more elaborate example that showcases how snap points work. It also shows how it behaves if you want it to be open by default, and not closable. Notice how it responds if you resize the window, or scroll to the bottom and starts adjusting the height of the sheet without scrolling back up first.

View demo code

If you provide either aheader orfooter prop you'll enable the special behavior seen in this example. And they're not just sticky positioned, both areas support touch gestures.

View demo code

In most cases you use a bottom sheet the same way you do with a dialog: you want it to overlay the page and block out distractions. But there are times when you want a bottom sheet but without it taking all the attention and overlaying the entire page. Providingblocking={false} helps this use case. By doing so you disable a couple of behaviors that are there for accessibility (focus-locking and more) that prevents a screen reader or a keyboard user from accidentally leaving the bottom sheet.

API

props

All props you provide, likeclassName,style props or whatever else are spread onto the underlying<animated.div> instance, that you can style in your custom CSS using this selector:[data-rsbs-root].Just note that the component is mounted in a@reach/portal at the bottom of<body>, and not in the DOM hierarchy you render it in.

open

Type:boolean

The only required prop, beyondchildren. And it's controlled, so if you don't set this tofalse then it's not possible to close the bottom sheet. It's worth knowing that the bottom sheet won't render anything but a@reach/dialog placeholder whileopen isfalse. Thus ensure your components behave as expected with being unmounted when the sheet closed. We can't really allow it to render and mount while in a closed/hidden position as there's no stable way of preventing keyboard users or screen readers from accidentally interacting with the closed bottom sheet as long as it's in the dom. This is especially problematic given it implements ARIA to optimize for a11y.

onDismiss

Type:() => void

Called when the user do something that signal they want to dismiss the sheet:

  • hit theesc key.
  • tap on the backdrop.
  • swipes the sheet to the bottom of the viewport.

snapPoints

Type:(state) => number | number[]

This function should be pure as it's called often. You can choose to provide a single value or an array of values to customize the behavior. Thestate contains these values:

  • headerHeight – the current measured height of theheader.
  • footerHeight – if afooter prop is provided then this is its height.
  • height – the current height of the sheet.
  • minHeight – the minimum height needed to avoid a scrollbar. If there's not enough height available to avoid it then this will be the same asmaxHeight.
  • maxHeight – the maximum available height on the page, equivalent towindow.innerHeight and100vh.
<BottomSheet// Allow the user to select between minimun height to avoid a scrollbar, and fullscrensnapPoints={({ minHeight, maxHeight})=>[minHeight,maxHeight]}/>

defaultSnap

Type:number | (state) => number

Provide either a number, or a callback returning a number for the default position of the sheet when it opens.state use the same arguments assnapPoints, plus two more values:snapPoints andlastSnap.

<BottomSheet// the first snap points height depends on the content, while the second one is equivalent to 60vhsnapPoints={({ minHeight, maxHeight})=>[minHeight,maxHeight/0.6]}// Opens the largest snap point by default, unless the user selected one previouslydefaultSnap={({ lastSnap, snapPoints})=>lastSnap??Math.max(...snapPoints)}/>

header

Type:ReactNode

Supports the same value type as thechildren prop.

footer

Type:ReactNode

Supports the same value type as thechildren prop.

sibling

Type:ReactNode

Supports the same value type as thesibling prop. Renders the node as a child of[data-rsbs-root], but as a sibling to[data-rsbs-backdrop] and[data-rsbs-overlay]. This allows you to access the animation state and render elements on top of the bottom sheet, while being outside the overlay itself.

initialFocusRef

Type:React.Ref | false

A react ref to the element you want to get keyboard focus when opening.If not provided it's automatically selecting the first interactive element it finds.If set to false keyboard focus when opening is disabled.

blocking

Type:boolean

Enabled by default. Enables focus trapping of keyboard navigation, so you can't accidentally tab out of the bottom sheet and into the background. Also setsaria-hidden on the rest of the page to prevent Screen Readers from escaping as well.

scrollLocking

Type:boolean

iOS Safari, and some other mobile culprits, can be tricky if you're on a page that has scrolling overflow ondocument.body. Mobile browsers often prefer scrolling the page in these cases instead of letting you handle the touch interaction for UI such as the bottom sheet. Thus it's enabled by default. However it can be a bit agressive and can affect cases where you're putting a drag and drop element inside the bottom sheet. Such as<input type="range" /> and more. For these cases you can wrap them in a container and give them this data attribute[data-body-scroll-lock-ignore] to prevent intervention. Really handy if you're doing crazy stuff like putting mapbox-gl widgets inside bottom sheets.

expandOnContentDrag

Type:boolean

Disabled by default. By default, a user can expand the bottom sheet only by dragging a header or the overlay. This option enables expanding the bottom sheet on the content dragging.

Events

All events receiveSpringEvent as their argument. The payload varies, buttype is always present, which can be'OPEN' | 'RESIZE' | 'SNAP' | 'CLOSE' depending on the scenario.

onSpringStart

Type:(event: SpringEvent) => void

Fired on:OPEN | RESIZE | SNAP | CLOSE.

If you need to delay the open animation until you're ready, perhaps you're loading some data and showing an inline spinner meanwhile. You can return a Promise or use an async function to make the bottom sheet wait for your work to finish before it starts the open transition.

functionExample(){const[data,setData]=useState([])return(<BottomSheetonSpringStart={async(event)=>{if(event.type==='OPEN'){// the bottom sheet gently waitsconstdata=awaitfetch(/* . . . */)setData(data)// and now we can proceed}}}>{data.map(/* . . . */)}</BottomSheet>)}

onSpringCancel

Type:(event: SpringEvent) => void

Fired on:OPEN | CLOSE.

OPEN

In order to be as fluid and delightful as possible, the open state can be interrupted and redirected by the user without waiting for the open transition to complete. Maybe they changed their mind and decided to close the sheet because they tapped a button by mistake. This interruption can happen in a number of ways:

  • the user swipes the sheet below the fold, triggering anonDismiss event.
  • the user hits theesc key, triggering anonDismiss event.
  • the parent component setsopen tofalse before finishing the animation.
  • aRESIZE event happens, like when an Android device shows its soft keyboard when an text editable input receives focus, as it changes the viewport height.

CLOSE

If the user reopens the sheet before it's done animating it'll trigger this event. Most importantly though it can fire if the bottom sheet is unmounted without enough time to clean animate itself out of the view before it rolls back things likebody-scroll-lock,focus-trap and more. It'll still clean itself up even if React decides to be rude about it. But this also means that the event can fire after the component is unmounted, so you should avoid calling setState or similar without checking for the mounted status of your own wrapper component.

RESIZE

Type:{ source: 'window' | 'maxheightprop' | 'element }

Fires whenever there's been a window resize event, or if the header, footer or content have changed its height in such a way that the valid snap points have changed.source tells you what caused the resize. If the resize comes from awindow.onresize event it's set to'window'.'maxheightprop' is if themaxHeight prop is used, and is fired whenever it changes. And'element' is whenever the header, footer or content resize observers detect a change.

SNAP

Type:{ source: 'dragging' | 'custom' | string }

Fired after dragging ends, or when callingref.snapTo, and a transition to a valid snap point is happening.

source is'dragging' if the snapping is responding to a drag gesture that just ended. And it's set to'custom' when usingref.snapTo.

functionExample(){return(<BottomSheetonSpringStart={(event)=>{if(event.type==='SNAP'&&event.source==='dragging'){console.log('Starting a spring animation to user selected snap point')}}}/>)}

When usingsnapTo it's possible to use a differentsource than'custom':

functionExample(){constsheetRef=useRef()return(<BottomSheetref={sheetRef}snapPoints={({ minHeight, maxHeight})=>[minHeight,maxHeight]}onSpringEnd={(event)=>{if(event.type==='SNAP'&&event.source==='snap-to-bottom'){console.log('Just finished an imperativ transition to the bottom snap point')}}}><buttononClick={()=>sheetRef.current.snapTo(0,{source:'snap-to-bottom'})}>        Snap to bottom</button></BottomSheet>)}

onSpringEnd

Type:(event: SpringEvent) => void

Fired on:CLOSE.

Theyin toonSpringStart'syang. It has the same characteristics. Includingasync/await and Promise support for delaying a transition. ForCLOSE it gives you a hook into the step right after it has cleaned up everything after itself, and right before it unmounts itself. This can be useful if you have some logic that needs to perform some work before it's safe to unmount.

skipInitialTransition

Type:boolean

By default the initial open state is always transitioned to using an spring animation. SetskipInitialTransition totrue and the initialopen state will render as if it were the default state. Useful to avoid scenarios where the opening transition would be distracting.

ref

Methods available when setting aref on the sheet:

exportdefaultfunctionExample(){constsheetRef=React.useRef()return<BottomSheetopenref={sheetRef}/>}

snapTo

Type:(numberOrCallback: number | (state => number)) => void, options?: {source?: string, velocity?: number}

Same signature as thedefaultSnap prop, calling it will animate the sheet to the new snap point you return. You can either call it with a number, which is the height in px (it'll select the closest snap point that matches your value):ref.current.snapTo(200). Or:

ref.current.snapTo(({// Showing all the available props  headerHeight, footerHeight, height, minHeight, maxHeight, snapPoints, lastSnap})=>// Selecting the largest snap point, if you give it a number that doesn't match a snap point then it'll// select whichever snap point is nearest the value you gaveMath.max(...snapPoints))

There's an optional second argument you can use to overrideevent.source, as well as changing thevelocity:

ref.current.snapTo(({ snapPoints})=>Math.min(...snapPoints),{// Each property is optional, here showing their default valuessource:'custom',velocity:1,})

height

Type:number

The current snap point, in other words the height, of the bottom sheet. This value is updated outside the React render cycle, for performance reasons.

exportdefaultfunctionExample(){constsheetRef=React.useRef()return(<BottomSheetref={sheetRef}onSpringStart={()=>{console.log('Transition from:',sheetRef.current.height)requestAnimationFrame(()=>console.log('Transition to:',sheetRef.current.height))}}onSpringEnd={()=>console.log('Finished transition to:',sheetRef.current.height)}/>)}

Credits


[8]ページ先頭

©2009-2025 Movatter.jp