All files / src/core/dom usePopupStateHOC.ts

17.64% Statements 3/17
0% Branches 0/3
0% Functions 0/7
20% Lines 3/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39  1x 1x                                               1x                        
import type { ComponentPublicInstance } from '@doraemon-ui/miniprogram.core-js'
 
export type PopupStateFunc<Props extends Record<string, any>> = {
  render: (props: Props, callback?: () => void) => void
  destroy: (callback?: () => void) => void
  update: (props: Props, callback?: () => void) => void
}

export function usePopupStateHOC<
  Instance extends ComponentPublicInstance,
  Props = Instance['$props'] & Instance['$data']
  >(statePropName: string = 'visible') {
  return (container: Instance): PopupStateFunc<Props> => {
    const render = (props: Props, callback?: () => void) => {
      Object.assign(container, props)
      container.$nextTick(() => callback?.())
    }
 
    const update = (props: Props, callback?: () => void) => {
      if (props[statePropName] !== undefined) {
        delete props[statePropName]
      }
      render(props, callback)
    }
 
    const open = (props: Props, callback?: () => void) => {
      render({ ...props, [statePropName]: true }, callback)
    }
 
    const close = (callback?: () => void) => render({ [statePropName]: false } as Props, callback)
 
    return {
      render: open,
      destroy: close,
      update
    }
  }
}