Skip to content
This repository was archived by the owner on Sep 20, 2024. It is now read-only.

Commit d5fbb49

Browse files
feat(c-radio): create context and group composable
1 parent 19741d8 commit d5fbb49

File tree

4 files changed

+58
-0
lines changed

4 files changed

+58
-0
lines changed

packages/c-radio/package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@
2828
},
2929
"dependencies": {
3030
"@chakra-ui/vue-system": "workspace:*",
31+
"@chakra-ui/vue-composables": "workspace:*",
32+
"@chakra-ui/vue-utils": "workspace:*",
3133
"@zag-js/radio-group": "0.7.0",
3234
"@zag-js/vue": "0.7.0"
3335
},

packages/c-radio/src/radio-context.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import * as radio from "@zag-js/radio-group"
2+
import { createContext } from "@chakra-ui/vue-utils"
3+
import type { UseRadioGroupReturn } from "./use-radio-group"
4+
5+
export type RadioContext = Parameters<
6+
ReturnType<typeof radio.connect>["getRadioProps"]
7+
>[0]
8+
9+
export const [RadioProvider, useRadioContext] = createContext<RadioContext>({
10+
name: "CRadioContext",
11+
strict: true,
12+
})
13+
14+
export type RadioGroupContext = radio.Context
15+
16+
export const [RadioGroupProvider, useRadioGroupContext] =
17+
createContext<UseRadioGroupReturn>({
18+
name: "CRadioGroupContext",
19+
strict: true,
20+
})
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { computed, getCurrentInstance, reactive } from "vue"
2+
import { normalizeProps, useMachine } from "@zag-js/vue"
3+
import * as radio from "@zag-js/radio-group"
4+
import { useId } from "@chakra-ui/vue-composables"
5+
import type { RadioGroupContext } from "./radio-context"
6+
7+
export type UseRadioGroupProps = RadioGroupContext & {
8+
modelValue?: RadioGroupContext["value"]
9+
}
10+
11+
export const useRadioGroup = (props: UseRadioGroupProps) => {
12+
const reactiveProps = reactive(props)
13+
const instance = getCurrentInstance()
14+
15+
const [state, send] = useMachine(
16+
radio.machine({
17+
...reactiveProps,
18+
id: useId().value,
19+
value: reactiveProps.modelValue ?? reactiveProps.value,
20+
onChange(details) {
21+
instance?.emit("change", details.value)
22+
instance?.emit("update:modelValue", details.value)
23+
},
24+
})
25+
)
26+
27+
return computed(() => radio.connect(state.value, send, normalizeProps))
28+
}
29+
30+
export type UseRadioGroupReturn = ReturnType<typeof useRadioGroup>

pnpm-lock.yaml

Lines changed: 6 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)