Coder Social home page Coder Social logo

intergalacticspacehighway / react-native-popper Goto Github PK

View Code? Open in Web Editor NEW
103.0 2.0 3.0 1.44 MB

Helps you create customizable and accessible Popovers / Tooltips with React Native.

Home Page: https://react-native-popper.netlify.app/

License: MIT License

JavaScript 4.27% TypeScript 95.73%
popovers reactnative tooltips

react-native-popper's Introduction

react-native-popper

Create fully customizable popovers and tooltips.

Playground

Popover Example

Tooltip Example - (CodeSandbox - as we need react-native-web 0.15+ for hover events.)

Features

  • Includes Popover and Tooltip.
  • Fully customizable.
  • Can be controlled or uncontrolled.
  • Handles focus trap, autofocus and dismiss on Escape on web.
  • Shifts accessibility focus to first item on Android and iOS.
  • Has "multiple" mode which can be used to open multiple popovers.

Install

# yarn
yarn add react-native-popper

# npm
npm i react-native-popper

Import

import { Popover, Tooltip } from 'react-native-popper';

Usage

  1. Uncontrolled

Popover:

<Popover
  trigger={
    <Pressable>
      <Text>Press me</Text>
    </Pressable>
  }
>
  <Popover.Backdrop />
  <Popover.Content>
    <Popover.Arrow />
    <Text>Hello World</Text>
  </Popover.Content>
</Popover>

Tooltip:

<Tooltip
  trigger={
    <Pressable>
      <Text>Press me</Text>
    </Pressable>
  }
>
  <Tooltip.Content>
    <Tooltip.Arrow />
    <Text>Hello World</Text>
  </Tooltip.Content>
</Tooltip>
  1. Controlled

Popover:

const [isOpen, setIsOpen] = React.useState(false);

return (
  <Popover
    isOpen={isOpen}
    onOpenChange={setIsOpen}
    trigger={
      <Pressable>
        <Text>Press me</Text>
      </Pressable>
    }
  >
    <Popover.Backdrop />
    <Popover.Content>
      <Popover.Arrow />
      <Text>Hello World</Text>
    </Popover.Content>
  </Popover>
);

Tooltip:

const [isOpen, setIsOpen] = React.useState(false);

return (
  <Tooltip
    isOpen={isOpen}
    onOpenChange={setIsOpen}
    trigger={
      <Pressable>
        <Text>Press me</Text>
      </Pressable>
    }
  >
    <Tooltip.Content>
      <Tooltip.Arrow />
      <Text>Hello World</Text>
    </Tooltip.Content>
  </Tooltip>
);

API

Popover or Tooltip

Prop Type Default Description
trigger (Required) React Element or Ref - Element or ref which will be used as a Trigger
on "press", "longpress", "hover" "press" for Popover "hover for Tooltips" The action type which should trigger the Popover
isOpen boolean false Useful for controlled popovers
onOpenChange (isOpen: boolean) => void - Use this to listen change events. Also to set state for controlled popovers.
onRequestClose () => void - Use this to handle hardware back button press. Similar to React Native Modal's onRequestClose
defaultIsOpen boolean false Specifies initial visibility of popover
placement string bottom "top", "bottom", "left", "right", "top left", "top right", "left top", "left bottom", "right top", "right bottom", "bottom left", "bottom right"
shouldOverlapWithTrigger boolean false Whether the popover should overlap with trigger
placement string bottom "top", "bottom", "left", "right", "top left", "top right", "left top", "left bottom", "right top", "right bottom", "bottom left", "bottom right"
offset number 0 Distance between popover and trigger's main axis
animated boolean true Determines whether the content should animate
animationEntryDuration number 150 Duration of entry animation
animationExitDuration number 150 Duration of exit animation
crossOffset number 0 Distance between popover and trigger's cross axis
shouldFlip boolean true Whether the popover should flip if there's less space.
mode 'single' | 'multiple' 'single' If you need to render multiple popovers at once on Android/iOS, use 'multiple' option. Note - Accessibility focus won't be shifted in this case. Refer mode section
isKeyboardDismissable (Web only) boolean true Determines whether popover can be dismissed with Escape key on web
shouldCloseOnOutsideClick (Web only) boolean true Determines whether popover can be dismissed when clicked outside of popover content and trigger.
autoFocus (Web only) boolean true Shifts focus to first focusable element on web.
trapFocus (Web only) boolean true Traps focus into the opened popover
restoreFocus (Web only) boolean true Restores focus to the triggered element

Popover.Backdrop or Tooltip.Backdrop

  • Renders a Pressable component. Useful to add click outside to close functionality.

  • Accepts all Pressable Props.

Popover.Content or Tooltip.Content

  • Pass the popover content as children here.
  • Accepts accessibilityLabel prop. This will be announced by the screenreader when popup opens.

Popover.Arrow or Tooltip.Arrow

Props Type Required Default Description
height number No 10 Arrow height
width number No 16 Arrow width
style ViewStyle No - Style will be passed to the View which is used as Arrow
children ReactNode No - Supply custom Arrow. You pass anything square. Refer CustomArrowExample
  • When using mode="multiple" or Tooltip, we use custom Portal to prevent shifting accessibility focus when opened. To use this Portal, we need to wrap the app with OverlayProvider.
import { OverlayProvider } from 'react-native-popper';

function App() {
    return <OverlayProvider>{/*Your app*/}</OverlayProvider>
}

Phew, That's it!

Why not always use a custom Portal instead of RN's built in Modal?

  • RN's built in Modal shifts accessibility focus to the first element when it opens. This is hard to achieve using a custom Portal.
  • Tooltips don't need to shift accessibility focus.
  • Thus,
  • On Web, we use ReactDOM's Portal in all cases.
  • On Android/iOS,
    • For Popovers, defaults to RN modal (can be overriden via mode prop. Needs OverlayProvider).
    • For Tooltips, defaults to custom Portal (Needs OverlayProvider)

Why are Popover and Tooltip separate components?

Reason: Different Accessibility requirements.

  • For Tooltips, we add aria-describedby on trigger and role="tooltip" on the Tooltip content and default "on" prop is set to "hover".
    • On Android/iOS we use custom Portal, so it doesn't shift accessibility focus.
  • For Popovers, we add aria-controls on trigger and role="dialog" on it's content. Also, Popover comes with focus trapping options.
    • On Android/iOS, we use RN's build in Modal which shifts the accessibility focus to first element. Also, refer mode section

Examples

  • Checkout examples directory. It has a lot of examples including animations.
cd examples
// Install dependencies
yarn
// web
yarn web
// iOS
yarn iOS
// Android
yarn android
  • Mode prop accepts single and multiple values. Defaults to single.
  • When set to single, it uses RN's built-in Modal which shifts accessibility focus to the first element when opened.
  • RN's built in modal doesn't support multiple popups at once unless they are nested. If you need multiple popup support without nesting use mode="multiple".
  • To use mode="multiple", wrap the entire app with OverlayProvider which enables custom Portal like functionality.
  • I am still figuring out if we can make this simple.

Limitations

  • Currently we have built in fade animation support. I am still figuring out how we can extract the layout info and use it to provide custom animation config externally. This can be useful when you want to animate depending upon popover content dimensions.

Known issues

  • When on="hover" is passed and Backdrop is used, it may lead to flickers as Backdrop hijacks pointer events. To mitigate this, either set pointerEvents= "none" on backdrop or remove backdrop completely. I am looking how to handle this in a more simple way.

Accessibility

Web

ARIA attributes

  • If the mode is set to 'popover', the Popover.Content element has role set to dialog. If the mode is set to 'tooltip', the Popover.Content has role set to tooltip.
  • The trigger has aria-haspopup set to true to denote that it triggers a popover.
  • The trigger has aria-controls set to the id of the Popover.Content to associate the popover and the trigger.
  • The trigger has aria-expanded set to true or false depending on the open/closed state of the popover.

Behaviour

  • When the popover is opened, focus is moved to the first focusable element inside Popover.Content. If you set autoFocus to false, focus will not return.
  • When the popover is closed, focus returns to the trigger. If you set restoreFocus to false, focus will not return.
  • Hitting the Esc key while the popover is open will close the popover. If you set isKeyboardDismissable to false, it will not close.
  • Focus will be contained within the Popver.Content. If you set trapFocus to false, it will not be contained.

Android/iOS

  • When mode is set to popover, accessibility focus will be automatically shifted to first element. Check out this demo.

Credits

License

MIT

react-native-popper's People

Contributors

alexisbronchart avatar intergalacticspacehighway avatar nandorojo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

react-native-popper's Issues

Ability to Open a Popover when another one is already open

First off, thank you for making a simple light weight popover component that works on android, iOS, and Web!
I have either a suggestion or a bug, please point me in the right direction. :)

The follow behavior is seen in Web and Android (haven't tested iOS)

Expected Behavior:
When one popover is open, I should be able to click on a trigger of another popover and the app will close the first and open the second

Actual Behavior:
When one popover is open, previously clickable items are not clickable until the popover is closed.

GIF
react-native-popper-andoird

Menu example accessiblity

Any chance you could critique my menu component for accessiblity? Not really familiar with good accessiblity, so I was wondering how to optimize this menu component with props, etc:

import React, {
  ReactNode,
  createContext,
  useContext,
  useMemo,
  useState,
  ComponentProps,
  useRef,
  useImperativeHandle,
} from 'react'

import { View, Text, SxProp, Pressable as Press, Theme as DripsyTheme } from 'dripsy'
import { Popover } from 'react-native-popper'
import { Sizes } from '../types'

type MenuProps = {
  children: ReactNode
  /*
   * Default: `240`
   */
  width?: number
  height?: number
  menu?: React.Ref<MenuRef>
  sx?: SxProp
} & Omit<ComponentProps<typeof Popover>, 'isOpen' | 'children' | 'onOpenChange'>

const MenuVisibleContext = createContext({
  visible: false,
  onClose() {
    //
  },
  onShow() {
    //
  },
  onChange(next: boolean) {
    //
  },
})

const useMenuVisibleContext = () => useContext(MenuVisibleContext)

function MenuProvider({ children }: { children: ReactNode }) {
  const [visible, setVisible] = useState(false)

  return (
    <MenuVisibleContext.Provider
      value={useMemo(
        () => ({
          visible,
          onShow: () => setVisible(true),
          onClose: () => setVisible(false),
          onChange: setVisible,
        }),
        [visible]
      )}
    >
      {children}
    </MenuVisibleContext.Provider>
  )
}
 
const Menu = function Menu(props: MenuProps) {
  return (
    <MenuProvider>
      <MenuWithContext {...props} />
    </MenuProvider>
  )
}

function MenuDivider() {
  return <View sx={{ height: 1, width: '100%', bg: 'mutedText', my: 2 }} />
}

function MenuWithContext({
  children,
  width = 240,
  height,
  menu,
  ...props
}: MenuProps) {
  const { visible, onChange } = useMenuVisibleContext()

  useImperativeHandle(menu, () => ({
    show: () => onChange(true),
    close: () => onChange(false),
  }))

  return (
    <Popover offset={2} {...props} isOpen={visible} onOpenChange={onChange}>
      <Popover.Backdrop />
      <Popover.Content>
        <View
          sx={{
            width,
            height,
            borderWidth: 1,
            bg: 'background',
            borderRadius: 3,
            borderColor: 'mutedText',
            py: 2,
          }}
        >
          {children}
        </View>
      </Popover.Content>
    </Popover>
  )
}

type MenuItemProps = {
  children: string | ReactNode
  onPress?: () => void
  prefix?: ReactNode
  suffix?: ReactNode
  disabled?: boolean
  color?: keyof DripsyTheme['colors']
  /*
   * default: `true`
   */
  shouldCloseOnPress?: boolean
}

function MenuItem({
  children,
  onPress,
  prefix,
  suffix,
  disabled = false,
  color,
  shouldCloseOnPress = true,
}: MenuItemProps) {
  const { onClose } = useMenuVisibleContext()

  const composePress = () => {
    onPress?.()
    if (shouldCloseOnPress) {
      onClose()
    }
  }

  return (
    <Press disabled={disabled} onPress={composePress}>
      {({ hovered, pressed }) => {
        return (
          <View
            sx={{
              px: 3,
              py: 2,
              bg: hovered || pressed ? 'muted2' : undefined,
              flexDirection: 'row',
              alignItems: 'center',
              opacity: disabled ? 0.7 : 1,
              cursor: disabled ? 'not-allowed' : 'pointer',
            }}
          >
            {!!prefix && <View sx={{ mr: 2 }}>{prefix}</View>}
            <View sx={{ flex: 1 }}>
              <Text
                sx={{
                  color: color ?? (hovered || pressed ? 'text' : 'muted7'),
                }}
              >
                {children}
              </Text>
            </View>
            {!!suffix && <View sx={{ ml: 2 }}>{suffix}</View>}
          </View>
        )
      }}
    </Press>
  )
}

type MenuSectionProps = {
  children: ReactNode
  title: string
}

function MenuSection({ children, title }: MenuSectionProps) {
  return (
    <View>
      <Text sx={{ py: 2, px: 3, color: 'mutedText' }}>{title}</Text>
      {children}
    </View>
  )
}

type MenuTriggerProps = {
  children: ReactNode
  onPress?: never
} & (
  | {
      unstyled?: true
    }
  | ({
      unstyled?: false
    } & ComponentProps<typeof Button>)
)

const TriggerContext = React.createContext(false)

const MenuTrigger = React.forwardRef(function MenuTrigger(
  { unstyled = true, ...props }: MenuTriggerProps,
  ref
) {
  let node = <Button ref={ref} {...props} />
  if (unstyled) {
    node = <Press ref={ref} {...(props as any)} />
  }

  return <TriggerContext.Provider value={true}>{node}</TriggerContext.Provider>
})

type MenuIconButtonProps = {
  size?: Sizes
  shape?: 'square' | 'circle' | 'none'
  icon: IconProps['icon']
  onPress?: never // internal usage only
}
 
Menu.Trigger = MenuTrigger
Menu.Section = MenuSection
Menu.Item = MenuItem
Menu.Divider = MenuDivider

export { Menu }

Tooltip stays open after clicking trigger an hovering out

I have a action button with a Tooltip on it.

When i click this button and i hover out, the tooltip should close.

Right now, i need to manually click outside the trigger for the tooltip to disapear.

Screen.Recording.2022-11-25.at.11.56.48.AM.mov

Add `onDismiss` prop

If we could just forward onDismiss down to the modal, then I could refrain from opening other modals until this one is hidden.

Add customizable `Modal` component from react-native-screens

Now that react-native-screens has an overlay view that allows multiple overlays on iOS (and in the future Android), it would be great if this lib exposed a way to pass a custom Modal component. I envision something roughly like this:

const CustomModal = (props) => {
  if (Platform.OS !== 'ios') {
    return <Modal {...props} />
  }

  const { visible, children } = props

  return <OverlayView style={StyleSheet.absoluteFill}>{visible && children}</OverlayView>
}

return <Popover Modal={CustomModal} />

Even better, what if this library had a plugin, like react-native-popper/window, such that all you had to do is this:

import { WindowOverlay } from 'react-native-popper/window'

<Popover Modal={WindowOverlay} />

This way, only users of react-native-popper/window need to install react-native-screens.

Custom animations

Is there any way to customize the animation config? Or if not, could I provide a function as a child to do my own (such as with Moti)? I'd like to fade in down.

Modal Support

Hey guys, I'm trying to use this package currently, I've hit a little bit of a problem tho, when using it in conjunction with the react native modal it causes the popped item to appear below it instead of on top.
Is there any way that behaviour could be changed? If so I'd appreciate it a lot!

Thanks for the amazing package,
Luis Bizarro

Trouble dismissing the modal when outside Pressable component is pressed on web.

I'm running into some trouble when trying to dismiss the modal when a pressable is pressed outside of the modal on web. The modal currently works as expected when pressing outside of the popper if the element isn't another pressable, however when pressing another pressable e.i a button, the popper stays open.

Any guidance on this would be great.

Next.js support

Hey there, I think there's some sort of issue with a dependency. I'm trying to import this in my Next.js app, and I'm seeing this:

Screen Shot 2021-07-23 at 6 12 14 PM

Any idea what that might be?

When running yarn why dom-helpers, I get this:

=> Found "[email protected]"
info Reasons this module exists
   - "_project_#@beatgig#components#@material-ui#pickers#react-transition-group" depends on it
   - Hoisted from "_project_#@beatgig#components#@material-ui#pickers#react-transition-group#dom-helpers"
info Disk size without dependencies: "984KB"
info Disk size with unique dependencies: "2.76MB"
info Disk size with transitive dependencies: "2.8MB"
info Number of shared dependencies: 3
=> Found "@react-aria/overlays#[email protected]"
info This module exists because "_project_#expo-next-app#react-native-popper#@react-native-aria#overlays#@react-aria#overlays" depends on it.
info Disk size without dependencies: "932KB"
info Disk size with unique dependencies: "1.6MB"
info Disk size with transitive dependencies: "1.64MB"
info Number of shared dependencies: 2
✨  Done in 1.34s.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.