Skip to content

Commit

Permalink
chore(react): add machine debugger
Browse files Browse the repository at this point in the history
  • Loading branch information
segunadebayo committed Sep 5, 2024
1 parent d83c76f commit dbaa8a1
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
Binary file modified bun.lockb
Binary file not shown.
1 change: 1 addition & 0 deletions packages/react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@
"@types/react": "18.3.5",
"@types/react-dom": "18.3.0",
"@vitejs/plugin-react": "4.3.1",
"@zag-js/stringify-state": "0.65.1",
"globby": "14.0.2",
"jsdom": "24.1.3",
"lucide-react": "0.438.0",
Expand Down
63 changes: 63 additions & 0 deletions packages/react/src/use-debugger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { stringifyState } from '@zag-js/stringify-state'
import { useLayoutEffect } from 'react'

interface Service {
initialContext: { id: string }
state: Record<string, unknown>
subscribe: (callback: () => void) => () => void
}

export const useDebugger = (service: Service) => {
useLayoutEffect(() => {
const syncPre = () => {
let group = document.getElementById('__zag-debug')

if (!group) {
group = document.createElement('div')
group.id = '__zag-debug'
Object.assign(group.style, {
position: 'fixed',
top: '0',
right: '0',
zIndex: '9999',
display: 'flex',
flexDirection: 'column',
gap: '4px',
boxSizing: 'border-box',
})

document.body.appendChild(group)
}

const id = service.initialContext.id
let pre = document.getElementById(id)

if (!pre) {
pre = document.createElement('pre')
pre.id = id
Object.assign(pre.style, {
padding: '4px',
background: 'white',
border: '1px solid black',
borderRadius: '4px',
maxHeight: '300px',
overflow: 'auto',
})
group.appendChild(pre)
}

pre.textContent = stringifyState(service.state)

return () => {
pre.remove()
}
}

const removePre = syncPre()
const unsubscribe = service.subscribe(syncPre)
return () => {
removePre()
unsubscribe()
}
}, [service])
}

0 comments on commit dbaa8a1

Please sign in to comment.