1+ import {
2+ createContext ,
3+ useContext ,
4+ useState ,
5+ PropsWithChildren ,
6+ ReactNode ,
7+ useRef
8+ } from "react" ;
9+
10+ import {
11+ AlertDialog ,
12+ AlertDialogBody ,
13+ AlertDialogFooter ,
14+ AlertDialogHeader ,
15+ AlertDialogContent ,
16+ AlertDialogOverlay ,
17+ useDisclosure ,
18+ Button ,
19+ ButtonProps ,
20+ } from '@chakra-ui/react'
21+
22+ export interface DialogProps {
23+ title ?: string | ReactNode ;
24+ accept ?: {
25+ title ?: string ;
26+ onClick ?: ( ) => void ;
27+ options ?: ButtonProps
28+ } ,
29+ decline ?: {
30+ title ?: string ;
31+ onClick ?: ( ) => void ;
32+ options ?: ButtonProps
33+ } ,
34+ content ?: ReactNode ;
35+ }
36+
37+ interface DialogContextData {
38+ show : ( content : DialogProps ) => void ;
39+ }
40+
41+ const DialogContext = createContext < DialogContextData > ( { } as DialogContextData ) ;
42+
43+ export const DialogProvider = ( { children } : PropsWithChildren ) => {
44+ const { isOpen, onOpen, onClose } = useDisclosure ( )
45+
46+ const cancelRef = useRef ( )
47+ const [ dialog , setDialog ] = useState < DialogProps | null > ( null ) ;
48+
49+ const show = ( content : DialogProps ) => {
50+ setDialog ( content ) ;
51+ onOpen ( ) ;
52+ }
53+
54+ return (
55+ < DialogContext . Provider value = { { show } } >
56+ { children }
57+ { dialog && (
58+ < AlertDialog
59+ isOpen = { isOpen }
60+ leastDestructiveRef = { cancelRef as any }
61+ onClose = { onClose }
62+ >
63+ < AlertDialogOverlay >
64+ < AlertDialogContent >
65+ { typeof dialog . title === 'string' ? (
66+ < AlertDialogHeader fontSize = 'lg' fontWeight = 'bold' >
67+ { dialog . title }
68+ </ AlertDialogHeader >
69+ ) : dialog . title }
70+
71+ < AlertDialogBody >
72+ { dialog . content }
73+ </ AlertDialogBody >
74+
75+ < AlertDialogFooter >
76+ < Button
77+ ref = { cancelRef as any }
78+ onClick = { ( ) => {
79+ onClose ( ) ;
80+ dialog ?. decline ?. onClick && dialog ?. decline ?. onClick ( )
81+ } }
82+ { ...dialog ?. decline ?. options } >
83+ { dialog . decline ?. title || 'Yes' }
84+ </ Button >
85+ < Button
86+ colorScheme = 'red'
87+ ml = { 3 }
88+ onClick = { ( ) => {
89+ onClose ( )
90+ dialog ?. accept ?. onClick && dialog ?. accept ?. onClick ( )
91+ } }
92+ { ...dialog ?. accept ?. options } >
93+ { dialog . accept ?. title || 'No' }
94+ </ Button >
95+ </ AlertDialogFooter >
96+ </ AlertDialogContent >
97+ </ AlertDialogOverlay >
98+ </ AlertDialog >
99+ ) }
100+ </ DialogContext . Provider >
101+ ) ;
102+ }
103+
104+ export function useDialog ( ) : DialogContextData {
105+ const context = useContext ( DialogContext ) ;
106+
107+ if ( ! context ) {
108+ throw new Error ( "o useDialog deve ser utilizado dentro de um DialogProvider" ) ;
109+ }
110+
111+ return context ;
112+ }
0 commit comments