@radix-ui/react-password-toggle-field 0.1.0-rc.1745439717073

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.
package/dist/index.mjs ADDED
@@ -0,0 +1,307 @@
1
+ "use client";
2
+
3
+ // src/password-toggle-field.tsx
4
+ import * as React from "react";
5
+ import { flushSync } from "react-dom";
6
+ import { composeEventHandlers } from "@radix-ui/primitive";
7
+ import { useControllableState } from "@radix-ui/react-use-controllable-state";
8
+ import { Primitive } from "@radix-ui/react-primitive";
9
+ import { useComposedRefs } from "@radix-ui/react-compose-refs";
10
+ import { useId } from "@radix-ui/react-id";
11
+ import { useIsHydrated } from "@radix-ui/react-use-is-hydrated";
12
+ import { useEffectEvent } from "@radix-ui/react-use-effect-event";
13
+ import { createContextScope } from "@radix-ui/react-context";
14
+ import { jsx } from "react/jsx-runtime";
15
+ var PASSWORD_TOGGLE_FIELD_NAME = "PasswordToggleField";
16
+ var [createPasswordToggleFieldContext] = createContextScope(PASSWORD_TOGGLE_FIELD_NAME);
17
+ var [PasswordToggleFieldProvider, usePasswordToggleFieldContext] = createPasswordToggleFieldContext(PASSWORD_TOGGLE_FIELD_NAME);
18
+ var INITIAL_FOCUS_STATE = {
19
+ clickTriggered: false,
20
+ selectionStart: null,
21
+ selectionEnd: null
22
+ };
23
+ var PasswordToggleField = ({
24
+ __scopePasswordToggleField,
25
+ ...props
26
+ }) => {
27
+ const baseId = useId(props.id);
28
+ const defaultInputId = `${baseId}-input`;
29
+ const [inputIdState, setInputIdState] = React.useState(defaultInputId);
30
+ const inputId = inputIdState ?? defaultInputId;
31
+ const syncInputId = React.useCallback(
32
+ (providedId) => setInputIdState(providedId != null ? String(providedId) : null),
33
+ []
34
+ );
35
+ const { visible: visibleProp, defaultVisible, onVisiblityChange, children } = props;
36
+ const [visible = false, setVisible] = useControllableState({
37
+ caller: PASSWORD_TOGGLE_FIELD_NAME,
38
+ prop: visibleProp,
39
+ defaultProp: defaultVisible ?? false,
40
+ onChange: onVisiblityChange
41
+ });
42
+ const inputRef = React.useRef(null);
43
+ const focusState = React.useRef(INITIAL_FOCUS_STATE);
44
+ return /* @__PURE__ */ jsx(
45
+ PasswordToggleFieldProvider,
46
+ {
47
+ scope: __scopePasswordToggleField,
48
+ inputId,
49
+ inputRef,
50
+ setVisible,
51
+ syncInputId,
52
+ visible,
53
+ focusState,
54
+ children
55
+ }
56
+ );
57
+ };
58
+ PasswordToggleField.displayName = PASSWORD_TOGGLE_FIELD_NAME;
59
+ var PASSWORD_TOGGLE_FIELD_INPUT_NAME = PASSWORD_TOGGLE_FIELD_NAME + "Input";
60
+ var PasswordToggleFieldInput = React.forwardRef(
61
+ ({
62
+ __scopePasswordToggleField,
63
+ autoComplete = "current-password",
64
+ autoCapitalize = "off",
65
+ spellCheck = false,
66
+ id: idProp,
67
+ ...props
68
+ }, forwardedRef) => {
69
+ const { visible, inputRef, inputId, syncInputId, setVisible, focusState } = usePasswordToggleFieldContext(PASSWORD_TOGGLE_FIELD_INPUT_NAME, __scopePasswordToggleField);
70
+ React.useEffect(() => {
71
+ syncInputId(idProp);
72
+ }, [idProp, syncInputId]);
73
+ const _setVisible = useEffectEvent(setVisible);
74
+ React.useEffect(() => {
75
+ const inputElement = inputRef.current;
76
+ const form = inputElement?.form;
77
+ if (!form) {
78
+ return;
79
+ }
80
+ const controller = new AbortController();
81
+ form.addEventListener(
82
+ "reset",
83
+ (event) => {
84
+ if (!event.defaultPrevented) {
85
+ _setVisible(false);
86
+ }
87
+ },
88
+ { signal: controller.signal }
89
+ );
90
+ form.addEventListener(
91
+ "submit",
92
+ () => {
93
+ _setVisible(false);
94
+ },
95
+ { signal: controller.signal }
96
+ );
97
+ return () => {
98
+ controller.abort();
99
+ };
100
+ }, [inputRef, _setVisible]);
101
+ return /* @__PURE__ */ jsx(
102
+ Primitive.input,
103
+ {
104
+ ...props,
105
+ id: idProp ?? inputId,
106
+ autoCapitalize,
107
+ autoComplete,
108
+ ref: useComposedRefs(forwardedRef, inputRef),
109
+ spellCheck,
110
+ type: visible ? "text" : "password",
111
+ onBlur: composeEventHandlers(props.onBlur, (event) => {
112
+ const { selectionStart, selectionEnd } = event.currentTarget;
113
+ focusState.current.selectionStart = selectionStart;
114
+ focusState.current.selectionEnd = selectionEnd;
115
+ })
116
+ }
117
+ );
118
+ }
119
+ );
120
+ PasswordToggleFieldInput.displayName = PASSWORD_TOGGLE_FIELD_INPUT_NAME;
121
+ var PASSWORD_TOGGLE_FIELD_TOGGLE_NAME = PASSWORD_TOGGLE_FIELD_NAME + "Toggle";
122
+ var PasswordToggleFieldToggle = React.forwardRef(
123
+ ({
124
+ __scopePasswordToggleField,
125
+ onClick,
126
+ onPointerDown,
127
+ onPointerCancel,
128
+ onPointerUp,
129
+ onFocus,
130
+ children,
131
+ "aria-label": ariaLabelProp,
132
+ "aria-controls": ariaControls,
133
+ "aria-hidden": ariaHidden,
134
+ tabIndex,
135
+ ...props
136
+ }, forwardedRef) => {
137
+ const { setVisible, visible, inputRef, inputId, focusState } = usePasswordToggleFieldContext(
138
+ PASSWORD_TOGGLE_FIELD_TOGGLE_NAME,
139
+ __scopePasswordToggleField
140
+ );
141
+ const [internalAriaLabel, setInternalAriaLabel] = React.useState(void 0);
142
+ const elementRef = React.useRef(null);
143
+ const ref = useComposedRefs(forwardedRef, elementRef);
144
+ const isHydrated = useIsHydrated();
145
+ React.useEffect(() => {
146
+ const element = elementRef.current;
147
+ if (!element || ariaLabelProp) {
148
+ setInternalAriaLabel(void 0);
149
+ return;
150
+ }
151
+ const DEFAULT_ARIA_LABEL = visible ? "Hide password" : "Show password";
152
+ function checkForInnerTextLabel(textContent) {
153
+ const text = textContent ? textContent : void 0;
154
+ setInternalAriaLabel(text ? void 0 : DEFAULT_ARIA_LABEL);
155
+ }
156
+ checkForInnerTextLabel(element.textContent);
157
+ const observer = new MutationObserver((entries) => {
158
+ let textContent;
159
+ for (const entry of entries) {
160
+ if (entry.type === "characterData") {
161
+ if (element.textContent) {
162
+ textContent = element.textContent;
163
+ }
164
+ }
165
+ }
166
+ checkForInnerTextLabel(textContent);
167
+ });
168
+ observer.observe(element, { characterData: true, subtree: true });
169
+ return () => {
170
+ observer.disconnect();
171
+ };
172
+ }, [visible, ariaLabelProp]);
173
+ const ariaLabel = ariaLabelProp || internalAriaLabel;
174
+ if (!isHydrated) {
175
+ ariaHidden ??= true;
176
+ tabIndex ??= -1;
177
+ } else {
178
+ ariaControls ??= inputId;
179
+ }
180
+ React.useEffect(() => {
181
+ let cleanup = () => {
182
+ };
183
+ const ownerWindow = elementRef.current?.ownerDocument?.defaultView || window;
184
+ const reset = () => focusState.current.clickTriggered = false;
185
+ const handlePointerUp = () => cleanup = requestIdleCallback(ownerWindow, reset);
186
+ ownerWindow.addEventListener("pointerup", handlePointerUp);
187
+ return () => {
188
+ cleanup();
189
+ ownerWindow.removeEventListener("pointerup", handlePointerUp);
190
+ };
191
+ }, [focusState]);
192
+ return /* @__PURE__ */ jsx(
193
+ Primitive.button,
194
+ {
195
+ "aria-controls": ariaControls,
196
+ "aria-hidden": ariaHidden,
197
+ "aria-label": ariaLabel,
198
+ ref,
199
+ id: inputId,
200
+ ...props,
201
+ onPointerDown: composeEventHandlers(onPointerDown, () => {
202
+ focusState.current.clickTriggered = true;
203
+ }),
204
+ onPointerCancel: (event) => {
205
+ onPointerCancel?.(event);
206
+ focusState.current = INITIAL_FOCUS_STATE;
207
+ },
208
+ onClick: (event) => {
209
+ onClick?.(event);
210
+ if (event.defaultPrevented) {
211
+ focusState.current = INITIAL_FOCUS_STATE;
212
+ return;
213
+ }
214
+ flushSync(() => {
215
+ setVisible((s) => !s);
216
+ });
217
+ if (focusState.current.clickTriggered) {
218
+ const input = inputRef.current;
219
+ if (input) {
220
+ const { selectionStart, selectionEnd } = focusState.current;
221
+ input.focus();
222
+ if (selectionStart !== null || selectionEnd !== null) {
223
+ requestAnimationFrame(() => {
224
+ if (input.ownerDocument.activeElement === input) {
225
+ input.selectionStart = selectionStart;
226
+ input.selectionEnd = selectionEnd;
227
+ }
228
+ });
229
+ }
230
+ }
231
+ }
232
+ focusState.current = INITIAL_FOCUS_STATE;
233
+ },
234
+ onPointerUp: (event) => {
235
+ onPointerUp?.(event);
236
+ setTimeout(() => {
237
+ focusState.current = INITIAL_FOCUS_STATE;
238
+ }, 50);
239
+ },
240
+ type: "button",
241
+ children
242
+ }
243
+ );
244
+ }
245
+ );
246
+ PasswordToggleFieldToggle.displayName = PASSWORD_TOGGLE_FIELD_TOGGLE_NAME;
247
+ var PASSWORD_TOGGLE_FIELD_SLOT_NAME = PASSWORD_TOGGLE_FIELD_NAME + "Slot";
248
+ var PasswordToggleFieldSlot = ({
249
+ __scopePasswordToggleField,
250
+ ...props
251
+ }) => {
252
+ const { visible } = usePasswordToggleFieldContext(
253
+ PASSWORD_TOGGLE_FIELD_SLOT_NAME,
254
+ __scopePasswordToggleField
255
+ );
256
+ return "render" in props ? (
257
+ //
258
+ props.render({ visible })
259
+ ) : visible ? props.visible : props.hidden;
260
+ };
261
+ PasswordToggleFieldSlot.displayName = PASSWORD_TOGGLE_FIELD_SLOT_NAME;
262
+ var PASSWORD_TOGGLE_FIELD_ICON_NAME = PASSWORD_TOGGLE_FIELD_NAME + "Icon";
263
+ var PasswordToggleFieldIcon = React.forwardRef(
264
+ ({
265
+ __scopePasswordToggleField,
266
+ // @ts-expect-error
267
+ children,
268
+ ...props
269
+ }, forwardedRef) => {
270
+ const { visible } = usePasswordToggleFieldContext(
271
+ PASSWORD_TOGGLE_FIELD_ICON_NAME,
272
+ __scopePasswordToggleField
273
+ );
274
+ const { visible: visibleIcon, hidden: hiddenIcon, ...domProps } = props;
275
+ return /* @__PURE__ */ jsx(Primitive.svg, { ...domProps, ref: forwardedRef, "aria-hidden": true, asChild: true, children: visible ? visibleIcon : hiddenIcon });
276
+ }
277
+ );
278
+ PasswordToggleFieldIcon.displayName = PASSWORD_TOGGLE_FIELD_ICON_NAME;
279
+ function requestIdleCallback(window2, callback, options) {
280
+ if (window2.requestIdleCallback) {
281
+ const id2 = window2.requestIdleCallback(callback, options);
282
+ return () => {
283
+ window2.cancelIdleCallback(id2);
284
+ };
285
+ }
286
+ const start = Date.now();
287
+ const id = window2.setTimeout(() => {
288
+ const timeRemaining = () => Math.max(0, 50 - (Date.now() - start));
289
+ callback({ didTimeout: false, timeRemaining });
290
+ }, 1);
291
+ return () => {
292
+ window2.clearTimeout(id);
293
+ };
294
+ }
295
+ export {
296
+ PasswordToggleFieldIcon as Icon,
297
+ PasswordToggleFieldInput as Input,
298
+ PasswordToggleField,
299
+ PasswordToggleFieldIcon,
300
+ PasswordToggleFieldInput,
301
+ PasswordToggleFieldSlot,
302
+ PasswordToggleFieldToggle,
303
+ PasswordToggleField as Root,
304
+ PasswordToggleFieldSlot as Slot,
305
+ PasswordToggleFieldToggle as Toggle
306
+ };
307
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/password-toggle-field.tsx"],
4
+ "sourcesContent": ["import * as React from 'react';\nimport { flushSync } from 'react-dom';\nimport { composeEventHandlers } from '@radix-ui/primitive';\nimport { useControllableState } from '@radix-ui/react-use-controllable-state';\nimport { Primitive } from '@radix-ui/react-primitive';\nimport { useComposedRefs } from '@radix-ui/react-compose-refs';\nimport { useId } from '@radix-ui/react-id';\nimport { useIsHydrated } from '@radix-ui/react-use-is-hydrated';\nimport { useEffectEvent } from '@radix-ui/react-use-effect-event';\nimport type { Scope } from '@radix-ui/react-context';\nimport { createContextScope } from '@radix-ui/react-context';\n\nconst PASSWORD_TOGGLE_FIELD_NAME = 'PasswordToggleField';\n\n/* -------------------------------------------------------------------------------------------------\n * PasswordToggleFieldProvider\n * -----------------------------------------------------------------------------------------------*/\n\ntype InternalFocusState = {\n clickTriggered: boolean;\n selectionStart: number | null;\n selectionEnd: number | null;\n};\n\ninterface PasswordToggleFieldContextValue {\n inputId: string;\n inputRef: React.RefObject<HTMLInputElement | null>;\n visible: boolean;\n setVisible: React.Dispatch<React.SetStateAction<boolean>>;\n syncInputId: (providedId: string | number | undefined) => void;\n focusState: React.RefObject<InternalFocusState>;\n}\n\nconst [createPasswordToggleFieldContext] = createContextScope(PASSWORD_TOGGLE_FIELD_NAME);\nconst [PasswordToggleFieldProvider, usePasswordToggleFieldContext] =\n createPasswordToggleFieldContext<PasswordToggleFieldContextValue>(PASSWORD_TOGGLE_FIELD_NAME);\n\n/* -------------------------------------------------------------------------------------------------\n * PasswordToggleField\n * -----------------------------------------------------------------------------------------------*/\n\ntype ScopedProps<P> = P & { __scopePasswordToggleField?: Scope };\n\ninterface PasswordToggleFieldProps {\n id?: string;\n visible?: boolean;\n defaultVisible?: boolean;\n onVisiblityChange?: (visible: boolean) => void;\n children?: React.ReactNode;\n}\n\nconst INITIAL_FOCUS_STATE: InternalFocusState = {\n clickTriggered: false,\n selectionStart: null,\n selectionEnd: null,\n};\n\nconst PasswordToggleField: React.FC<PasswordToggleFieldProps> = ({\n __scopePasswordToggleField,\n ...props\n}: ScopedProps<PasswordToggleFieldProps>) => {\n const baseId = useId(props.id);\n const defaultInputId = `${baseId}-input`;\n const [inputIdState, setInputIdState] = React.useState<null | string>(defaultInputId);\n const inputId = inputIdState ?? defaultInputId;\n const syncInputId = React.useCallback(\n (providedId: string | number | undefined) =>\n setInputIdState(providedId != null ? String(providedId) : null),\n []\n );\n\n const { visible: visibleProp, defaultVisible, onVisiblityChange, children } = props;\n const [visible = false, setVisible] = useControllableState({\n caller: PASSWORD_TOGGLE_FIELD_NAME,\n prop: visibleProp,\n defaultProp: defaultVisible ?? false,\n onChange: onVisiblityChange,\n });\n\n const inputRef = React.useRef<HTMLInputElement | null>(null);\n const focusState = React.useRef<InternalFocusState>(INITIAL_FOCUS_STATE);\n\n return (\n <PasswordToggleFieldProvider\n scope={__scopePasswordToggleField}\n inputId={inputId}\n inputRef={inputRef}\n setVisible={setVisible}\n syncInputId={syncInputId}\n visible={visible}\n focusState={focusState}\n >\n {children}\n </PasswordToggleFieldProvider>\n );\n};\nPasswordToggleField.displayName = PASSWORD_TOGGLE_FIELD_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * PasswordToggleFieldInput\n * -----------------------------------------------------------------------------------------------*/\n\nconst PASSWORD_TOGGLE_FIELD_INPUT_NAME = PASSWORD_TOGGLE_FIELD_NAME + 'Input';\n\ntype PrimitiveInputProps = React.ComponentPropsWithoutRef<'input'>;\n\ninterface PasswordToggleFieldOwnProps {\n autoComplete?: 'current-password' | 'new-password';\n}\n\ninterface PasswordToggleFieldInputProps\n extends PasswordToggleFieldOwnProps,\n Omit<PrimitiveInputProps, keyof PasswordToggleFieldOwnProps | 'type'> {\n autoComplete?: 'current-password' | 'new-password';\n}\n\nconst PasswordToggleFieldInput = React.forwardRef<HTMLInputElement, PasswordToggleFieldInputProps>(\n (\n {\n __scopePasswordToggleField,\n autoComplete = 'current-password',\n autoCapitalize = 'off',\n spellCheck = false,\n id: idProp,\n ...props\n }: ScopedProps<PasswordToggleFieldInputProps>,\n forwardedRef\n ) => {\n const { visible, inputRef, inputId, syncInputId, setVisible, focusState } =\n usePasswordToggleFieldContext(PASSWORD_TOGGLE_FIELD_INPUT_NAME, __scopePasswordToggleField);\n\n React.useEffect(() => {\n syncInputId(idProp);\n }, [idProp, syncInputId]);\n\n // We want to reset the visibility to `false` to revert the input to\n // `type=\"password\"` when:\n // - The form is reset (for consistency with other form controls)\n // - The form is submitted (to prevent the browser from remembering the\n // input's value.\n //\n // See \"Keeping things secure\":\n // https://technology.blog.gov.uk/2021/04/19/simple-things-are-complicated-making-a-show-password-option/)\n const _setVisible = useEffectEvent(setVisible);\n React.useEffect(() => {\n const inputElement = inputRef.current;\n const form = inputElement?.form;\n if (!form) {\n return;\n }\n\n const controller = new AbortController();\n form.addEventListener(\n 'reset',\n (event) => {\n if (!event.defaultPrevented) {\n _setVisible(false);\n }\n },\n { signal: controller.signal }\n );\n form.addEventListener(\n 'submit',\n () => {\n // always reset the visibility on submit regardless of whether the\n // default action is prevented\n _setVisible(false);\n },\n { signal: controller.signal }\n );\n return () => {\n controller.abort();\n };\n }, [inputRef, _setVisible]);\n\n return (\n <Primitive.input\n {...props}\n id={idProp ?? inputId}\n autoCapitalize={autoCapitalize}\n autoComplete={autoComplete}\n ref={useComposedRefs(forwardedRef, inputRef)}\n spellCheck={spellCheck}\n type={visible ? 'text' : 'password'}\n onBlur={composeEventHandlers(props.onBlur, (event) => {\n // get the cursor position\n const { selectionStart, selectionEnd } = event.currentTarget;\n focusState.current.selectionStart = selectionStart;\n focusState.current.selectionEnd = selectionEnd;\n })}\n />\n );\n }\n);\nPasswordToggleFieldInput.displayName = PASSWORD_TOGGLE_FIELD_INPUT_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * PasswordToggleFieldToggle\n * -----------------------------------------------------------------------------------------------*/\n\nconst PASSWORD_TOGGLE_FIELD_TOGGLE_NAME = PASSWORD_TOGGLE_FIELD_NAME + 'Toggle';\n\ntype PrimitiveButtonProps = React.ComponentPropsWithoutRef<'button'>;\n\ninterface PasswordToggleFieldToggleProps extends Omit<PrimitiveButtonProps, 'type'> {}\n\nconst PasswordToggleFieldToggle = React.forwardRef<\n HTMLButtonElement,\n PasswordToggleFieldToggleProps\n>(\n (\n {\n __scopePasswordToggleField,\n onClick,\n onPointerDown,\n onPointerCancel,\n onPointerUp,\n onFocus,\n children,\n 'aria-label': ariaLabelProp,\n 'aria-controls': ariaControls,\n 'aria-hidden': ariaHidden,\n tabIndex,\n ...props\n }: ScopedProps<PasswordToggleFieldToggleProps>,\n forwardedRef\n ) => {\n const { setVisible, visible, inputRef, inputId, focusState } = usePasswordToggleFieldContext(\n PASSWORD_TOGGLE_FIELD_TOGGLE_NAME,\n __scopePasswordToggleField\n );\n const [internalAriaLabel, setInternalAriaLabel] = React.useState<string | undefined>(undefined);\n const elementRef = React.useRef<HTMLButtonElement>(null);\n const ref = useComposedRefs(forwardedRef, elementRef);\n const isHydrated = useIsHydrated();\n\n React.useEffect(() => {\n const element = elementRef.current;\n if (!element || ariaLabelProp) {\n setInternalAriaLabel(undefined);\n return;\n }\n\n const DEFAULT_ARIA_LABEL = visible ? 'Hide password' : 'Show password';\n\n function checkForInnerTextLabel(textContent: string | undefined | null) {\n const text = textContent ? textContent : undefined;\n // If the element has inner text, no need to force an aria-label.\n setInternalAriaLabel(text ? undefined : DEFAULT_ARIA_LABEL);\n }\n\n checkForInnerTextLabel(element.textContent);\n\n const observer = new MutationObserver((entries) => {\n let textContent: string | undefined;\n for (const entry of entries) {\n if (entry.type === 'characterData') {\n if (element.textContent) {\n textContent = element.textContent;\n }\n }\n }\n checkForInnerTextLabel(textContent);\n });\n observer.observe(element, { characterData: true, subtree: true });\n return () => {\n observer.disconnect();\n };\n }, [visible, ariaLabelProp]);\n\n const ariaLabel = ariaLabelProp || internalAriaLabel;\n\n // Before hydration the button will not work, but we want to render it\n // regardless to prevent potential layout shift. Hide it from assistive tech\n // by default. Post-hydration it will be visible, focusable and associated\n // with the input via aria-controls.\n if (!isHydrated) {\n ariaHidden ??= true;\n tabIndex ??= -1;\n } else {\n ariaControls ??= inputId;\n }\n\n React.useEffect(() => {\n let cleanup = () => {};\n const ownerWindow = elementRef.current?.ownerDocument?.defaultView || window;\n const reset = () => (focusState.current.clickTriggered = false);\n const handlePointerUp = () => (cleanup = requestIdleCallback(ownerWindow, reset));\n ownerWindow.addEventListener('pointerup', handlePointerUp);\n return () => {\n cleanup();\n ownerWindow.removeEventListener('pointerup', handlePointerUp);\n };\n }, [focusState]);\n\n return (\n <Primitive.button\n aria-controls={ariaControls}\n aria-hidden={ariaHidden}\n aria-label={ariaLabel}\n ref={ref}\n id={inputId}\n {...props}\n onPointerDown={composeEventHandlers(onPointerDown, () => {\n focusState.current.clickTriggered = true;\n })}\n onPointerCancel={(event) => {\n // do not use `composeEventHandlers` here because we always want to\n // reset the ref on cancellation, regardless of whether the user has\n // called preventDefault on the event\n onPointerCancel?.(event);\n focusState.current = INITIAL_FOCUS_STATE;\n }}\n // do not use `composeEventHandlers` here because we always want to\n // reset the ref after click, regardless of whether the user has\n // called preventDefault on the event\n onClick={(event) => {\n onClick?.(event);\n if (event.defaultPrevented) {\n focusState.current = INITIAL_FOCUS_STATE;\n return;\n }\n\n flushSync(() => {\n setVisible((s) => !s);\n });\n if (focusState.current.clickTriggered) {\n const input = inputRef.current;\n if (input) {\n const { selectionStart, selectionEnd } = focusState.current;\n input.focus();\n if (selectionStart !== null || selectionEnd !== null) {\n // wait a tick so that focus has settled, then restore select position\n requestAnimationFrame(() => {\n // make sure the input still has focus (developer may have\n // programatically moved focus elsewhere)\n if (input.ownerDocument.activeElement === input) {\n input.selectionStart = selectionStart;\n input.selectionEnd = selectionEnd;\n }\n });\n }\n }\n }\n focusState.current = INITIAL_FOCUS_STATE;\n }}\n onPointerUp={(event) => {\n onPointerUp?.(event);\n // if click handler hasn't been called at this point, it may have been\n // intercepted, in which case we still want to reset our internal\n // state\n setTimeout(() => {\n focusState.current = INITIAL_FOCUS_STATE;\n }, 50);\n }}\n type=\"button\"\n >\n {children}\n </Primitive.button>\n );\n }\n);\nPasswordToggleFieldToggle.displayName = PASSWORD_TOGGLE_FIELD_TOGGLE_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * PasswordToggleFieldSlot\n * -----------------------------------------------------------------------------------------------*/\n\nconst PASSWORD_TOGGLE_FIELD_SLOT_NAME = PASSWORD_TOGGLE_FIELD_NAME + 'Slot';\n\ninterface PasswordToggleFieldSlotDeclarativeProps {\n visible: React.ReactNode;\n hidden: React.ReactNode;\n}\n\ninterface PasswordToggleFieldSlotRenderProps {\n render: (args: { visible: boolean }) => React.ReactElement;\n}\n\ntype PasswordToggleFieldSlotProps =\n | PasswordToggleFieldSlotDeclarativeProps\n | PasswordToggleFieldSlotRenderProps;\n\nconst PasswordToggleFieldSlot: React.FC<PasswordToggleFieldSlotProps> = ({\n __scopePasswordToggleField,\n ...props\n}: ScopedProps<PasswordToggleFieldSlotProps>) => {\n const { visible } = usePasswordToggleFieldContext(\n PASSWORD_TOGGLE_FIELD_SLOT_NAME,\n __scopePasswordToggleField\n );\n\n return 'render' in props\n ? //\n props.render({ visible })\n : visible\n ? props.visible\n : props.hidden;\n};\nPasswordToggleFieldSlot.displayName = PASSWORD_TOGGLE_FIELD_SLOT_NAME;\n\n/* -------------------------------------------------------------------------------------------------\n * PasswordToggleFieldIcon\n * -----------------------------------------------------------------------------------------------*/\n\nconst PASSWORD_TOGGLE_FIELD_ICON_NAME = PASSWORD_TOGGLE_FIELD_NAME + 'Icon';\n\ntype PrimitiveSvgProps = React.ComponentPropsWithoutRef<'svg'>;\n\ninterface PasswordToggleFieldIconProps extends Omit<PrimitiveSvgProps, 'children'> {\n visible: React.ReactElement;\n hidden: React.ReactElement;\n}\n\nconst PasswordToggleFieldIcon = React.forwardRef<SVGSVGElement, PasswordToggleFieldIconProps>(\n (\n {\n __scopePasswordToggleField,\n // @ts-expect-error\n children,\n ...props\n }: ScopedProps<PasswordToggleFieldIconProps>,\n forwardedRef\n ) => {\n const { visible } = usePasswordToggleFieldContext(\n PASSWORD_TOGGLE_FIELD_ICON_NAME,\n __scopePasswordToggleField\n );\n const { visible: visibleIcon, hidden: hiddenIcon, ...domProps } = props;\n return (\n <Primitive.svg {...domProps} ref={forwardedRef} aria-hidden asChild>\n {visible ? visibleIcon : hiddenIcon}\n </Primitive.svg>\n );\n }\n);\nPasswordToggleFieldIcon.displayName = PASSWORD_TOGGLE_FIELD_ICON_NAME;\n\nexport {\n PasswordToggleField,\n PasswordToggleFieldInput,\n PasswordToggleFieldToggle,\n PasswordToggleFieldSlot,\n PasswordToggleFieldIcon,\n //\n PasswordToggleField as Root,\n PasswordToggleFieldInput as Input,\n PasswordToggleFieldToggle as Toggle,\n PasswordToggleFieldSlot as Slot,\n PasswordToggleFieldIcon as Icon,\n};\nexport type {\n PasswordToggleFieldProps,\n PasswordToggleFieldInputProps,\n PasswordToggleFieldToggleProps,\n PasswordToggleFieldIconProps,\n PasswordToggleFieldSlotProps,\n};\n\nfunction requestIdleCallback(\n window: Window,\n callback: IdleRequestCallback,\n options?: IdleRequestOptions\n): () => void {\n if ((window as any).requestIdleCallback) {\n const id = window.requestIdleCallback(callback, options);\n return () => {\n window.cancelIdleCallback(id);\n };\n }\n const start = Date.now();\n const id = window.setTimeout(() => {\n const timeRemaining = () => Math.max(0, 50 - (Date.now() - start));\n callback({ didTimeout: false, timeRemaining });\n }, 1);\n return () => {\n window.clearTimeout(id);\n };\n}\n"],
5
+ "mappings": ";;;AAAA,YAAY,WAAW;AACvB,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;AACrC,SAAS,4BAA4B;AACrC,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;AAChC,SAAS,aAAa;AACtB,SAAS,qBAAqB;AAC9B,SAAS,sBAAsB;AAE/B,SAAS,0BAA0B;AAyE/B;AAvEJ,IAAM,6BAA6B;AAqBnC,IAAM,CAAC,gCAAgC,IAAI,mBAAmB,0BAA0B;AACxF,IAAM,CAAC,6BAA6B,6BAA6B,IAC/D,iCAAkE,0BAA0B;AAgB9F,IAAM,sBAA0C;AAAA,EAC9C,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,cAAc;AAChB;AAEA,IAAM,sBAA0D,CAAC;AAAA,EAC/D;AAAA,EACA,GAAG;AACL,MAA6C;AAC3C,QAAM,SAAS,MAAM,MAAM,EAAE;AAC7B,QAAM,iBAAiB,GAAG,MAAM;AAChC,QAAM,CAAC,cAAc,eAAe,IAAU,eAAwB,cAAc;AACpF,QAAM,UAAU,gBAAgB;AAChC,QAAM,cAAoB;AAAA,IACxB,CAAC,eACC,gBAAgB,cAAc,OAAO,OAAO,UAAU,IAAI,IAAI;AAAA,IAChE,CAAC;AAAA,EACH;AAEA,QAAM,EAAE,SAAS,aAAa,gBAAgB,mBAAmB,SAAS,IAAI;AAC9E,QAAM,CAAC,UAAU,OAAO,UAAU,IAAI,qBAAqB;AAAA,IACzD,QAAQ;AAAA,IACR,MAAM;AAAA,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AU,KAAK,cAAc,eAAW,MAAC,SAAO,MAChE,oBAAU,cAAc,YAC3B;AAAA,EAEJ;AACF;AACA,wBAAwB,cAAc;AAuBtC,SAAS,oBACPA,SACA,UACA,SACY;AACZ,MAAKA,QAAe,qBAAqB;AACvC,UAAMC,MAAKD,QAAO,oBAAoB,UAAU,OAAO;AACvD,WAAO,MAAM;AACX,MAAAA,QAAO,mBAAmBC,GAAE;AAAA,IAC9B;AAAA,EACF;AACA,QAAM,QAAQ,KAAK,IAAI;AACvB,QAAM,KAAKD,QAAO,WAAW,MAAM;AACjC,UAAM,gBAAgB,MAAM,KAAK,IAAI,GAAG,MAAM,KAAK,IAAI,IAAI,MAAM;AACjE,aAAS,EAAE,YAAY,OAAO,cAAc,CAAC;AAAA,EAC/C,GAAG,CAAC;AACJ,SAAO,MAAM;AACX,IAAAA,QAAO,aAAa,EAAE;AAAA,EACxB;AACF;",
6
+ "names": ["window", "id"]
7
+ }
package/package.json ADDED
@@ -0,0 +1,76 @@
1
+ {
2
+ "name": "@radix-ui/react-password-toggle-field",
3
+ "version": "0.1.0-rc.1745439717073",
4
+ "license": "MIT",
5
+ "source": "./src/index.ts",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.mjs",
8
+ "files": [
9
+ "src",
10
+ "dist",
11
+ "README.md"
12
+ ],
13
+ "sideEffects": false,
14
+ "dependencies": {
15
+ "@radix-ui/react-compose-refs": "1.1.2",
16
+ "@radix-ui/primitive": "1.1.2",
17
+ "@radix-ui/react-primitive": "2.1.1-rc.1745439717073",
18
+ "@radix-ui/react-context": "1.1.2",
19
+ "@radix-ui/react-use-effect-event": "0.0.2",
20
+ "@radix-ui/react-use-controllable-state": "1.2.2",
21
+ "@radix-ui/react-use-is-hydrated": "0.1.0",
22
+ "@radix-ui/react-id": "1.1.1"
23
+ },
24
+ "devDependencies": {
25
+ "@types/react": "^19.0.7",
26
+ "@types/react-dom": "^19.0.3",
27
+ "eslint": "^9.18.0",
28
+ "react": "^19.0.0",
29
+ "react-dom": "^19.0.0",
30
+ "typescript": "^5.7.3",
31
+ "@repo/builder": "0.0.0",
32
+ "@repo/typescript-config": "0.0.0",
33
+ "@repo/eslint-config": "0.0.0"
34
+ },
35
+ "peerDependencies": {
36
+ "@types/react": "*",
37
+ "@types/react-dom": "*",
38
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
39
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
40
+ },
41
+ "peerDependenciesMeta": {
42
+ "@types/react": {
43
+ "optional": true
44
+ },
45
+ "@types/react-dom": {
46
+ "optional": true
47
+ }
48
+ },
49
+ "homepage": "https://radix-ui.com/primitives",
50
+ "repository": {
51
+ "type": "git",
52
+ "url": "git+https://github.com/radix-ui/primitives.git"
53
+ },
54
+ "bugs": {
55
+ "url": "https://github.com/radix-ui/primitives/issues"
56
+ },
57
+ "scripts": {
58
+ "lint": "eslint --max-warnings 0 src",
59
+ "clean": "rm -rf dist",
60
+ "typecheck": "tsc --noEmit",
61
+ "build": "radix-build"
62
+ },
63
+ "types": "./dist/index.d.ts",
64
+ "exports": {
65
+ ".": {
66
+ "import": {
67
+ "types": "./dist/index.d.mts",
68
+ "default": "./dist/index.mjs"
69
+ },
70
+ "require": {
71
+ "types": "./dist/index.d.ts",
72
+ "default": "./dist/index.js"
73
+ }
74
+ }
75
+ }
76
+ }
package/src/index.ts ADDED
@@ -0,0 +1,21 @@
1
+ 'use client';
2
+ export type {
3
+ PasswordToggleFieldProps,
4
+ PasswordToggleFieldInputProps,
5
+ PasswordToggleFieldToggleProps,
6
+ PasswordToggleFieldIconProps,
7
+ PasswordToggleFieldSlotProps,
8
+ } from './password-toggle-field';
9
+ export {
10
+ PasswordToggleField,
11
+ PasswordToggleFieldInput,
12
+ PasswordToggleFieldToggle,
13
+ PasswordToggleFieldIcon,
14
+ PasswordToggleFieldSlot,
15
+ //
16
+ Root,
17
+ Input,
18
+ Toggle,
19
+ Icon,
20
+ Slot,
21
+ } from './password-toggle-field';
@@ -0,0 +1,219 @@
1
+ import { axe } from 'vitest-axe';
2
+ import type { RenderResult } from '@testing-library/react';
3
+ import { act, cleanup, render, screen } from '@testing-library/react';
4
+ import * as PasswordToggleField from './password-toggle-field';
5
+ import { afterEach, describe, it, beforeEach, expect } from 'vitest';
6
+ import { userEvent, type UserEvent } from '@testing-library/user-event';
7
+
8
+ describe('given a default PasswordToggleField', () => {
9
+ let rendered: RenderResult;
10
+ let user: UserEvent;
11
+
12
+ afterEach(cleanup);
13
+
14
+ beforeEach(() => {
15
+ user = userEvent.setup();
16
+ rendered = render(
17
+ <>
18
+ <label htmlFor="password">Password</label>
19
+ <PasswordToggleField.Root>
20
+ <PasswordToggleField.Input id="password" />
21
+ <PasswordToggleField.Toggle>
22
+ <PasswordToggleField.Slot visible="Hide" hidden="Show" />
23
+ </PasswordToggleField.Toggle>
24
+ </PasswordToggleField.Root>
25
+ </>
26
+ );
27
+ });
28
+
29
+ afterEach(cleanup);
30
+
31
+ it('should have no accessibility violations', async () => {
32
+ expect(await axe(rendered.container)).toHaveNoViolations();
33
+ });
34
+
35
+ it('should initially be hidden', () => {
36
+ const toggle = screen.getByRole('button', { name: 'Show' });
37
+ expect(toggle.textContent).toBe('Show');
38
+ });
39
+
40
+ it('toggles the children when clicked', async () => {
41
+ const toggle = screen.getByRole('button', { name: 'Show' });
42
+ await act(async () => await user.click(toggle));
43
+ expect(toggle.textContent).toBe('Hide');
44
+ });
45
+
46
+ it('should initially render input as `type=password`', async () => {
47
+ const input = screen.getByLabelText<HTMLInputElement>('Password');
48
+ expect(input.type).toBe('password');
49
+ });
50
+
51
+ it('should initially render input as `type=text` when toggled', async () => {
52
+ const input = screen.getByLabelText<HTMLInputElement>('Password');
53
+ const toggle = screen.getByRole('button', { name: 'Show' });
54
+ await act(async () => await user.click(toggle));
55
+ expect(input.type).toBe('text');
56
+ });
57
+
58
+ it('should re-focus the input after toggling', async () => {
59
+ const input = screen.getByLabelText<HTMLInputElement>('Password');
60
+ const toggle = screen.getByRole('button', { name: 'Show' });
61
+ await act(async () => await user.click(toggle));
62
+ expect(document.activeElement).toBe(input);
63
+ });
64
+
65
+ it("should restore the input's selection after toggling", async () => {
66
+ const input = screen.getByLabelText<HTMLInputElement>('Password');
67
+ const toggle = screen.getByRole('button', { name: 'Show' });
68
+ await act(async () => await user.click(input));
69
+ await act(async () => await user.type(input, 'p'));
70
+ await act(async () => await user.click(toggle));
71
+ // selection should be at the end of the input value
72
+ expect(input.selectionStart).toBe(1);
73
+ expect(input.selectionEnd).toBe(1);
74
+
75
+ await act(async () => await user.type(input, 'assword'));
76
+ input.selectionStart = 0;
77
+ input.selectionEnd = 4;
78
+
79
+ await act(async () => await user.click(toggle));
80
+ expect(input.selectionStart).toBe(0);
81
+ expect(input.selectionEnd).toBe(4);
82
+ });
83
+ });
84
+
85
+ describe('given a PasswordToggleField with an Icon', () => {
86
+ let rendered: RenderResult;
87
+ let user: UserEvent;
88
+
89
+ afterEach(cleanup);
90
+
91
+ beforeEach(() => {
92
+ user = userEvent.setup();
93
+ rendered = render(
94
+ <>
95
+ <label htmlFor="password">Password</label>
96
+ <PasswordToggleField.Root>
97
+ <PasswordToggleField.Input id="password" />
98
+ <PasswordToggleField.Toggle>
99
+ <PasswordToggleField.Icon
100
+ visible={<EyeOpenIcon data-testid="open" />}
101
+ hidden={<EyeClosedIcon data-testid="closed" />}
102
+ />
103
+ </PasswordToggleField.Toggle>
104
+ </PasswordToggleField.Root>
105
+ </>
106
+ );
107
+ });
108
+
109
+ afterEach(cleanup);
110
+
111
+ it('should have no accessibility violations', async () => {
112
+ expect(await axe(rendered.container)).toHaveNoViolations();
113
+ });
114
+
115
+ it('should initially be hidden', () => {
116
+ const icon = screen.getByTestId('closed');
117
+ expect(icon).toBeVisible();
118
+ expect(screen.queryByTestId('open')).not.toBeInTheDocument();
119
+ });
120
+
121
+ it('toggles the icon when clicked', async () => {
122
+ const toggle = screen.getByRole('button', { name: 'Show password' });
123
+ await act(async () => await user.click(toggle));
124
+ expect(screen.getByTestId('open')).toBeVisible();
125
+ expect(screen.queryByTestId('closed')).not.toBeInTheDocument();
126
+ });
127
+
128
+ it('should initially render input as `type=password`', async () => {
129
+ const input = screen.getByLabelText<HTMLInputElement>('Password');
130
+ expect(input.type).toBe('password');
131
+ });
132
+
133
+ it('should initially render input as `type=text` when toggled', async () => {
134
+ const input = screen.getByLabelText<HTMLInputElement>('Password');
135
+ const toggle = screen.getByRole('button', { name: 'Show password' });
136
+ await act(async () => await user.click(toggle));
137
+ expect(input.type).toBe('text');
138
+ });
139
+
140
+ it('should retain its value when toggled', async () => {
141
+ const input = screen.getByLabelText('Password');
142
+ const toggle = screen.getByRole('button', { name: 'Show password' });
143
+ await act(async () => await user.type(input, 'pass123'));
144
+ await act(async () => await user.click(toggle));
145
+ expect(input).toHaveValue('pass123');
146
+ });
147
+ });
148
+
149
+ describe('given a PasswordToggleField in a form', () => {
150
+ let user: UserEvent;
151
+
152
+ afterEach(cleanup);
153
+
154
+ beforeEach(() => {
155
+ user = userEvent.setup();
156
+ render(
157
+ <form onSubmit={(e) => e.preventDefault()}>
158
+ <label htmlFor="password">Password</label>
159
+ <PasswordToggleField.Root>
160
+ <PasswordToggleField.Input id="password" />
161
+ <PasswordToggleField.Toggle>
162
+ <PasswordToggleField.Slot visible="Hide" hidden="Show" />
163
+ </PasswordToggleField.Toggle>
164
+ </PasswordToggleField.Root>
165
+ <button>Submit</button>
166
+ </form>
167
+ );
168
+ });
169
+
170
+ afterEach(cleanup);
171
+
172
+ it('should reset visibility to hidden after submission', async () => {
173
+ const toggle = screen.getByRole('button', { name: 'Show' });
174
+ const input = screen.getByLabelText<HTMLInputElement>('Password');
175
+ await act(() => user.click(toggle));
176
+ expect(input.type).toBe('text');
177
+ const submitButton = screen.getByText('Submit');
178
+ await act(() => user.click(submitButton));
179
+ expect(input.type).toBe('password');
180
+ });
181
+ });
182
+
183
+ function EyeClosedIcon(props: React.SVGProps<SVGSVGElement>) {
184
+ return (
185
+ <svg
186
+ width="15"
187
+ height="15"
188
+ viewBox="0 0 15 15"
189
+ fill="currentColor"
190
+ xmlns="http://www.w3.org/2000/svg"
191
+ {...props}
192
+ >
193
+ <path
194
+ d="M14.7649 6.07596C14.9991 6.22231 15.0703 6.53079 14.9239 6.76495C14.4849 7.46743 13.9632 8.10645 13.3702 8.66305L14.5712 9.86406C14.7664 10.0593 14.7664 10.3759 14.5712 10.5712C14.3759 10.7664 14.0593 10.7664 13.8641 10.5712L12.6011 9.30817C11.805 9.90283 10.9089 10.3621 9.93375 10.651L10.383 12.3277C10.4544 12.5944 10.2961 12.8685 10.0294 12.94C9.76267 13.0115 9.4885 12.8532 9.41704 12.5865L8.95917 10.8775C8.48743 10.958 8.00036 10.9999 7.50001 10.9999C6.99965 10.9999 6.51257 10.958 6.04082 10.8775L5.58299 12.5864C5.51153 12.8532 5.23737 13.0115 4.97064 12.94C4.7039 12.8686 4.5456 12.5944 4.61706 12.3277L5.06625 10.651C4.09111 10.3621 3.19503 9.90282 2.3989 9.30815L1.1359 10.5712C0.940638 10.7664 0.624058 10.7664 0.428798 10.5712C0.233537 10.3759 0.233537 10.0593 0.428798 9.86405L1.62982 8.66303C1.03682 8.10643 0.515113 7.46742 0.0760677 6.76495C-0.0702867 6.53079 0.000898544 6.22231 0.235065 6.07596C0.469231 5.9296 0.777703 6.00079 0.924058 6.23496C1.40354 7.00213 1.989 7.68057 2.66233 8.2427C2.67315 8.25096 2.6837 8.25972 2.69397 8.26898C4.00897 9.35527 5.65537 9.99991 7.50001 9.99991C10.3078 9.99991 12.6564 8.5063 14.076 6.23495C14.2223 6.00079 14.5308 5.9296 14.7649 6.07596Z"
195
+ fillRule="evenodd"
196
+ clipRule="evenodd"
197
+ />
198
+ </svg>
199
+ );
200
+ }
201
+
202
+ function EyeOpenIcon(props: React.SVGProps<SVGSVGElement>) {
203
+ return (
204
+ <svg
205
+ width="15"
206
+ height="15"
207
+ viewBox="0 0 15 15"
208
+ fill="currentColor"
209
+ xmlns="http://www.w3.org/2000/svg"
210
+ {...props}
211
+ >
212
+ <path
213
+ d="M7.5 11C4.80285 11 2.52952 9.62184 1.09622 7.50001C2.52952 5.37816 4.80285 4 7.5 4C10.1971 4 12.4705 5.37816 13.9038 7.50001C12.4705 9.62183 10.1971 11 7.5 11ZM7.5 3C4.30786 3 1.65639 4.70638 0.0760002 7.23501C-0.0253338 7.39715 -0.0253334 7.60288 0.0760014 7.76501C1.65639 10.2936 4.30786 12 7.5 12C10.6921 12 13.3436 10.2936 14.924 7.76501C15.0253 7.60288 15.0253 7.39715 14.924 7.23501C13.3436 4.70638 10.6921 3 7.5 3ZM7.5 9.5C8.60457 9.5 9.5 8.60457 9.5 7.5C9.5 6.39543 8.60457 5.5 7.5 5.5C6.39543 5.5 5.5 6.39543 5.5 7.5C5.5 8.60457 6.39543 9.5 7.5 9.5Z"
214
+ fillRule="evenodd"
215
+ clipRule="evenodd"
216
+ />
217
+ </svg>
218
+ );
219
+ }