@tamagui/checkbox 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/index.ts"],
4
+ "sourcesContent": ["export * from './Checkbox'\n"],
5
+ "mappings": "AAAA,cAAc;",
6
+ "names": []
7
+ }
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@tamagui/checkbox",
3
+ "version": "1.3.0",
4
+ "sideEffects": [
5
+ "*.css"
6
+ ],
7
+ "source": "src/index.ts",
8
+ "types": "./types/index.d.ts",
9
+ "main": "dist/cjs",
10
+ "module": "dist/esm",
11
+ "module:jsx": "dist/jsx",
12
+ "files": [
13
+ "src",
14
+ "types",
15
+ "dist"
16
+ ],
17
+ "scripts": {
18
+ "build": "tamagui-build",
19
+ "watch": "tamagui-build --watch"
20
+ },
21
+ "dependencies": {
22
+ "@radix-ui/react-use-previous": "^0.1.1",
23
+ "@tamagui/core": "^1.3.0",
24
+ "@tamagui/create-context": "^1.3.0",
25
+ "@tamagui/focusable": "^1.3.0",
26
+ "@tamagui/font-size": "^1.3.0",
27
+ "@tamagui/get-size": "^1.3.0",
28
+ "@tamagui/helpers-tamagui": "^1.3.0",
29
+ "@tamagui/label": "^1.3.0",
30
+ "@tamagui/stacks": "^1.3.0",
31
+ "@tamagui/use-controllable-state": "^1.3.0"
32
+ },
33
+ "peerDependencies": {
34
+ "react": "*",
35
+ "react-dom": "*"
36
+ },
37
+ "devDependencies": {
38
+ "@tamagui/build": "^1.3.0",
39
+ "react": "^18.2.0",
40
+ "react-dom": "^18.2.0"
41
+ },
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "gitHead": "a49cc7ea6b93ba384e77a4880ae48ac4a5635c14"
46
+ }
@@ -0,0 +1,386 @@
1
+ // fork of radix
2
+ // https://github.com/radix-ui/primitives/tree/main/packages/react/checkbox/src/Checkbox.tsx
3
+
4
+ import { usePrevious } from '@radix-ui/react-use-previous'
5
+ import {
6
+ GetProps,
7
+ SizeTokens,
8
+ TamaguiElement,
9
+ composeEventHandlers,
10
+ getConfig,
11
+ getVariableValue,
12
+ isWeb,
13
+ mergeProps,
14
+ styled,
15
+ useComposedRefs,
16
+ useMediaPropsActive,
17
+ useTheme,
18
+ withStaticProperties,
19
+ } from '@tamagui/core'
20
+ import type { Scope } from '@tamagui/create-context'
21
+ import { createContextScope } from '@tamagui/create-context'
22
+ import { registerFocusable } from '@tamagui/focusable'
23
+ import { getFontSize } from '@tamagui/font-size'
24
+ import { getSize, stepTokenUpOrDown } from '@tamagui/get-size'
25
+ import { useGetThemedIcon } from '@tamagui/helpers-tamagui'
26
+ import { useLabelContext } from '@tamagui/label'
27
+ import { ThemeableStack, YStack } from '@tamagui/stacks'
28
+ import { useControllableState } from '@tamagui/use-controllable-state'
29
+ import * as React from 'react'
30
+
31
+ export type CheckedState = boolean | 'indeterminate'
32
+
33
+ export function isIndeterminate(checked?: CheckedState): checked is 'indeterminate' {
34
+ return checked === 'indeterminate'
35
+ }
36
+
37
+ export function getState(checked: CheckedState) {
38
+ return isIndeterminate(checked) ? 'indeterminate' : checked ? 'checked' : 'unchecked'
39
+ }
40
+
41
+ type InputProps = any //Radix.ComponentPropsWithoutRef<'input'>
42
+ interface BubbleInputProps extends Omit<InputProps, 'checked'> {
43
+ checked: CheckedState
44
+ control: HTMLElement | null
45
+ bubbles: boolean
46
+
47
+ isHidden?: boolean
48
+ }
49
+
50
+ export const BubbleInput = (props: BubbleInputProps) => {
51
+ const { checked, bubbles = true, control, isHidden, ...inputProps } = props
52
+ const ref = React.useRef<HTMLInputElement>(null)
53
+ const prevChecked = usePrevious(checked)
54
+ // const controlSize = useSize(control)
55
+
56
+ // Bubble checked change to parents (e.g form change event)
57
+ React.useEffect(() => {
58
+ const input = ref.current!
59
+ const inputProto = window.HTMLInputElement.prototype
60
+ const descriptor = Object.getOwnPropertyDescriptor(
61
+ inputProto,
62
+ 'checked'
63
+ ) as PropertyDescriptor
64
+ const setChecked = descriptor.set
65
+
66
+ if (prevChecked !== checked && setChecked) {
67
+ const event = new Event('click', { bubbles })
68
+ input.indeterminate = isIndeterminate(checked)
69
+ setChecked.call(input, isIndeterminate(checked) ? false : checked)
70
+ input.dispatchEvent(event)
71
+ }
72
+ }, [prevChecked, checked, bubbles])
73
+
74
+ return (
75
+ <input
76
+ type="checkbox"
77
+ defaultChecked={isIndeterminate(checked) ? false : checked}
78
+ {...inputProps}
79
+ tabIndex={-1}
80
+ ref={ref}
81
+ aria-hidden={isHidden}
82
+ style={{
83
+ ...(isHidden
84
+ ? {
85
+ // ...controlSize,
86
+ position: 'absolute',
87
+ pointerEvents: 'none',
88
+ opacity: 0,
89
+ margin: 0,
90
+ }
91
+ : {
92
+ appearance: 'auto',
93
+ accentColor: 'var(--color6)',
94
+ }),
95
+
96
+ ...props.style,
97
+ }}
98
+ />
99
+ )
100
+ }
101
+
102
+ /* -------------------------------------------------------------------------------------------------
103
+ * CheckboxIndicator
104
+ * -----------------------------------------------------------------------------------------------*/
105
+
106
+ const INDICATOR_NAME = 'CheckboxIndicator'
107
+
108
+ const CheckboxIndicatorFrame = styled(ThemeableStack, {
109
+ name: INDICATOR_NAME,
110
+ })
111
+
112
+ type CheckboxIndicatorFrameProps = GetProps<typeof CheckboxIndicatorFrame>
113
+
114
+ export type CheckboxIndicatorProps = CheckboxIndicatorFrameProps & {
115
+ /**
116
+ * Used to force mounting when more control is needed. Useful when
117
+ * controlling animation with React animation libraries.
118
+ */
119
+ forceMount?: true
120
+ /**
121
+ * Used to disable passing styles down to children.
122
+ */
123
+ disablePassStyles?: boolean
124
+ }
125
+
126
+ const CheckboxIndicator = React.forwardRef<TamaguiElement, CheckboxIndicatorProps>(
127
+ (props: ScopedProps<CheckboxIndicatorProps>, forwardedRef) => {
128
+ const {
129
+ __scopeCheckbox,
130
+ children: childrenProp,
131
+ forceMount,
132
+ disablePassStyles,
133
+ ...indicatorProps
134
+ } = props
135
+ const context = useCheckboxContext(INDICATOR_NAME, __scopeCheckbox)
136
+ const iconSize =
137
+ (typeof context.size === 'number'
138
+ ? context.size * 0.65
139
+ : getFontSize(context.size)) * context.scaleIcon
140
+ const theme = useTheme()
141
+ const getThemedIcon = useGetThemedIcon({ size: iconSize, color: theme.color })
142
+
143
+ const childrens = React.Children.toArray(childrenProp)
144
+ const children = childrens.map((child) => {
145
+ if (disablePassStyles || !React.isValidElement(child)) {
146
+ return child
147
+ }
148
+ return getThemedIcon(child)
149
+ })
150
+
151
+ if (forceMount || isIndeterminate(context.state) || context.state === true)
152
+ return (
153
+ <CheckboxIndicatorFrame
154
+ theme="active"
155
+ data-state={getState(context.state)}
156
+ data-disabled={context.disabled ? '' : undefined}
157
+ pointerEvents="none"
158
+ {...indicatorProps}
159
+ ref={forwardedRef}
160
+ >
161
+ {children}
162
+ </CheckboxIndicatorFrame>
163
+ )
164
+
165
+ return null
166
+ }
167
+ )
168
+
169
+ CheckboxIndicator.displayName = INDICATOR_NAME
170
+
171
+ /* -------------------------------------------------------------------------------------------------
172
+ * Checkbox
173
+ * -----------------------------------------------------------------------------------------------*/
174
+
175
+ const CHECKBOX_NAME = 'Checkbox'
176
+
177
+ export const CheckboxFrame = styled(ThemeableStack, {
178
+ name: CHECKBOX_NAME,
179
+ tag: 'button',
180
+ backgroundColor: '$background',
181
+ alignItems: 'center',
182
+ justifyContent: 'center',
183
+ pressTheme: true,
184
+ focusable: true,
185
+ borderWidth: 2,
186
+ borderColor: 'transparent',
187
+
188
+ focusStyle: {
189
+ borderColor: '$borderColorFocus',
190
+ },
191
+
192
+ variants: {
193
+ size: {
194
+ '...size': (val, { tokens }) => {
195
+ const radiusToken = getVariableValue(getSize(val)) / 8
196
+ return {
197
+ borderRadius: radiusToken,
198
+ }
199
+ },
200
+ },
201
+ } as const,
202
+
203
+ defaultVariants: {
204
+ size: '$true',
205
+ },
206
+ })
207
+
208
+ type ScopedProps<P> = P & { __scopeCheckbox?: Scope }
209
+ const [createCheckboxContext, createCheckboxScope] = createContextScope(CHECKBOX_NAME)
210
+
211
+ type CheckboxContextValue = {
212
+ state: CheckedState
213
+ disabled?: boolean
214
+ size: SizeTokens
215
+ scaleIcon: number
216
+ }
217
+
218
+ const [CheckboxProvider, useCheckboxContext] =
219
+ createCheckboxContext<CheckboxContextValue>(CHECKBOX_NAME)
220
+
221
+ type CheckboxFrameProps = GetProps<typeof CheckboxFrame>
222
+ export interface CheckboxProps
223
+ extends Omit<CheckboxFrameProps, 'checked' | 'defaultChecked'> {
224
+ checked?: CheckedState
225
+ defaultChecked?: CheckedState
226
+ required?: boolean
227
+ onCheckedChange?(checked: CheckedState): void
228
+ labelledBy?: string
229
+ name?: string
230
+ value?: string
231
+ native?: boolean
232
+ scaleIcon?: number
233
+ sizeAdjust?: number
234
+ }
235
+
236
+ export const Checkbox = withStaticProperties(
237
+ CheckboxFrame.extractable(
238
+ React.forwardRef<HTMLButtonElement, CheckboxProps>(
239
+ (props: ScopedProps<CheckboxProps>, forwardedRef) => {
240
+ const {
241
+ __scopeCheckbox,
242
+ labelledBy: ariaLabelledby,
243
+ name,
244
+ checked: checkedProp,
245
+ defaultChecked,
246
+ required,
247
+ scaleIcon = 1,
248
+ sizeAdjust = 0,
249
+ disabled,
250
+ value = 'on',
251
+ onCheckedChange,
252
+ native,
253
+ ...checkboxProps
254
+ } = props
255
+ const [button, setButton] = React.useState<HTMLButtonElement | null>(null)
256
+ const composedRefs = useComposedRefs(forwardedRef, (node) => setButton(node))
257
+ const hasConsumerStoppedPropagationRef = React.useRef(false)
258
+ const propsActive = useMediaPropsActive(props)
259
+ // We set this to true by default so that events bubble to forms without JS (SSR)
260
+ const isFormControl = isWeb
261
+ ? button
262
+ ? Boolean(button.closest('form'))
263
+ : true
264
+ : false
265
+ const [checked = false, setChecked] = useControllableState({
266
+ prop: checkedProp,
267
+ defaultProp: defaultChecked!,
268
+ onChange: onCheckedChange,
269
+ })
270
+
271
+ const adjustedSizeToken = stepTokenUpOrDown('size', propsActive.size, sizeAdjust)
272
+ const size = Math.floor(getVariableValue(adjustedSizeToken) * 0.5)
273
+
274
+ const labelId = useLabelContext(button)
275
+ const labelledBy = ariaLabelledby || labelId
276
+
277
+ if (!isWeb) {
278
+ // eslint-disable-next-line react-hooks/rules-of-hooks
279
+ React.useEffect(() => {
280
+ if (!props.id) return
281
+ return registerFocusable(props.id, {
282
+ focusAndSelect: () => {
283
+ setChecked((x) => !x)
284
+ },
285
+ focus: () => {},
286
+ })
287
+ }, [props.id, setChecked])
288
+ }
289
+
290
+ return (
291
+ // YStack is here to provide theme for native input
292
+ <YStack asChild theme={checkboxProps.theme}>
293
+ <CheckboxProvider
294
+ scope={__scopeCheckbox}
295
+ state={checked}
296
+ disabled={disabled}
297
+ size={size}
298
+ scaleIcon={scaleIcon}
299
+ >
300
+ {isWeb && native ? (
301
+ <BubbleInput
302
+ control={button}
303
+ bubbles={!hasConsumerStoppedPropagationRef.current}
304
+ name={name}
305
+ value={value}
306
+ checked={checked}
307
+ required={required}
308
+ disabled={disabled}
309
+ id={props.id}
310
+ />
311
+ ) : (
312
+ <>
313
+ <CheckboxFrame
314
+ width={size}
315
+ height={size}
316
+ theme={checked ? 'active' : null}
317
+ tag="button"
318
+ role="checkbox"
319
+ aria-labelledby={labelledBy}
320
+ aria-checked={isIndeterminate(checked) ? 'mixed' : checked}
321
+ aria-required={required}
322
+ data-state={getState(checked)}
323
+ data-disabled={disabled ? '' : undefined}
324
+ disabled={disabled}
325
+ {...checkboxProps}
326
+ ref={composedRefs}
327
+ {...(isWeb && {
328
+ type: 'button',
329
+ value: value,
330
+ onKeyDown: composeEventHandlers(
331
+ (props as React.HTMLProps<HTMLButtonElement>).onKeyDown,
332
+ (event) => {
333
+ // According to WAI ARIA, Checkboxes don't activate on enter keypress
334
+ if (event.key === 'Enter') event.preventDefault()
335
+ }
336
+ ),
337
+ })}
338
+ onPress={composeEventHandlers(props.onPress as any, (event) => {
339
+ setChecked((prevChecked) =>
340
+ isIndeterminate(prevChecked) ? true : !prevChecked
341
+ )
342
+ if (isFormControl) {
343
+ hasConsumerStoppedPropagationRef.current =
344
+ event.isPropagationStopped()
345
+ // if checkbox is in a form, stop propagation from the button so that we only propagate
346
+ // one click event (from the input). We propagate changes from an input so that native
347
+ // form validation works and form events reflect checkbox updates.
348
+ if (!hasConsumerStoppedPropagationRef.current)
349
+ event.stopPropagation()
350
+ }
351
+ })}
352
+ />
353
+
354
+ {isWeb && isFormControl ? (
355
+ <BubbleInput
356
+ isHidden
357
+ control={button}
358
+ bubbles={!hasConsumerStoppedPropagationRef.current}
359
+ name={name}
360
+ value={value}
361
+ checked={checked}
362
+ required={required}
363
+ disabled={disabled}
364
+ />
365
+ ) : null}
366
+ </>
367
+ )}
368
+ </CheckboxProvider>
369
+ </YStack>
370
+ )
371
+ }
372
+ )
373
+ ),
374
+ {
375
+ Indicator: CheckboxIndicator,
376
+ }
377
+ )
378
+
379
+ Checkbox.displayName = CHECKBOX_NAME
380
+
381
+ export { createCheckboxScope }
382
+
383
+ const cloneElementWithPropOrder = (child: any, props: Object) => {
384
+ const next = mergeProps(child.props, props, false, getConfig().shorthands)[0]
385
+ return React.cloneElement({ ...child, props: null }, next)
386
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './Checkbox'