@registrucentras/rc-ses-react-components 1.9.0 → 1.10.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.
Files changed (24) hide show
  1. package/dist/assets/icons/PencilSimpleLineIcon.d.ts +1 -1
  2. package/dist/components/common/SegmentedControl/components/SegmentButton/index.d.ts +19 -0
  3. package/dist/components/common/SegmentedControl/index.d.ts +14 -0
  4. package/dist/components/form/inputs/SearchInput/index.d.ts +10 -0
  5. package/dist/library/index.d.ts +2 -0
  6. package/dist/library/types.d.ts +3 -1
  7. package/dist/registrucentras-rc-ses-react-components.cjs +10 -10
  8. package/dist/registrucentras-rc-ses-react-components.js +2240 -2042
  9. package/dist/stories/components/display/SegmentedControl.stories.d.ts +202 -0
  10. package/package.json +1 -1
  11. package/src/assets/icons/PencilSimpleLineIcon.tsx +8 -2
  12. package/src/components/common/SegmentedControl/components/SegmentButton/index.test.tsx +85 -0
  13. package/src/components/common/SegmentedControl/components/SegmentButton/index.tsx +110 -0
  14. package/src/components/common/SegmentedControl/index.test.tsx +164 -0
  15. package/src/components/common/SegmentedControl/index.tsx +188 -0
  16. package/src/components/common/SelectableCardList/components/SelectableCardListItem.test.tsx +74 -1
  17. package/src/components/common/SelectableCardList/components/SelectableCardListItem.tsx +16 -1
  18. package/src/components/form/inputs/SearchInput/index.test.tsx +68 -2
  19. package/src/components/form/inputs/SearchInput/index.tsx +24 -13
  20. package/src/i18n/namespaces/common/en.json +4 -0
  21. package/src/i18n/namespaces/common/lt.json +4 -0
  22. package/src/library/index.ts +2 -0
  23. package/src/library/types.ts +8 -0
  24. package/src/stories/components/display/SegmentedControl.stories.tsx +311 -0
@@ -0,0 +1,188 @@
1
+ import React, { useCallback, useImperativeHandle, useMemo, useRef, useState } from 'react'
2
+ import { useTranslation } from 'react-i18next'
3
+
4
+ import { grey } from '@/theme/palette'
5
+
6
+ import RcSesSegmentButton, { type RcSesSegmentOption } from './components/SegmentButton'
7
+
8
+ export type { RcSesSegmentOption }
9
+
10
+ export interface RcSesSegmentedControlProps {
11
+ options: RcSesSegmentOption[]
12
+ value: string
13
+ onChange: (value: string) => void
14
+ size?: 'small' | 'regular'
15
+ role?: 'radiogroup' | 'tablist'
16
+ disableBg?: boolean
17
+ ariaLabel?: string
18
+ }
19
+
20
+ const RcSesSegmentedControl = React.forwardRef<
21
+ HTMLDivElement,
22
+ RcSesSegmentedControlProps
23
+ >(
24
+ (
25
+ {
26
+ options,
27
+ value,
28
+ onChange,
29
+ size = 'regular',
30
+ role = 'radiogroup',
31
+ disableBg = false,
32
+ ariaLabel,
33
+ },
34
+ ref,
35
+ ) => {
36
+ const { t } = useTranslation('common')
37
+ const [focusIndex, setFocusIndex] = useState(() => {
38
+ const selectedIndex = options.findIndex((opt) => opt.id === value && !opt.disabled)
39
+ if (selectedIndex !== -1) return selectedIndex
40
+ return Math.max(
41
+ 0,
42
+ options.findIndex((opt) => !opt.disabled),
43
+ )
44
+ })
45
+ const containerRef = useRef<HTMLDivElement>(null)
46
+ const buttonRefs = useRef<(HTMLButtonElement | null)[]>([])
47
+
48
+ useImperativeHandle(ref, () => containerRef.current as HTMLDivElement)
49
+
50
+ React.useEffect(() => {
51
+ const selectedIndex = options.findIndex((opt) => opt.id === value && !opt.disabled)
52
+ if (selectedIndex !== -1) setFocusIndex(selectedIndex)
53
+ }, [value, options])
54
+
55
+ const getEnabledIndices = useCallback(
56
+ () => options.map((opt, i) => (!opt.disabled ? i : -1)).filter((i) => i !== -1),
57
+ [options],
58
+ )
59
+
60
+ const focusSegment = useCallback((index: number) => {
61
+ setFocusIndex(index)
62
+ buttonRefs.current[index]?.focus()
63
+ }, [])
64
+
65
+ const handleKeyDown = useCallback(
66
+ (e: React.KeyboardEvent<HTMLButtonElement>, index: number) => {
67
+ const enabledIndices = getEnabledIndices()
68
+ const currentPos = enabledIndices.indexOf(index)
69
+
70
+ switch (e.key) {
71
+ case 'ArrowLeft':
72
+ case 'ArrowUp': {
73
+ e.preventDefault()
74
+ const prevIndex =
75
+ currentPos > 0
76
+ ? enabledIndices[currentPos - 1]
77
+ : enabledIndices[enabledIndices.length - 1]
78
+ focusSegment(prevIndex)
79
+ onChange(options[prevIndex].id)
80
+ break
81
+ }
82
+
83
+ case 'ArrowRight':
84
+ case 'ArrowDown': {
85
+ e.preventDefault()
86
+ const nextIndex =
87
+ currentPos < enabledIndices.length - 1
88
+ ? enabledIndices[currentPos + 1]
89
+ : enabledIndices[0]
90
+ focusSegment(nextIndex)
91
+ onChange(options[nextIndex].id)
92
+ break
93
+ }
94
+
95
+ case 'Home': {
96
+ e.preventDefault()
97
+ const firstIndex = enabledIndices[0]
98
+ focusSegment(firstIndex)
99
+ onChange(options[firstIndex].id)
100
+ break
101
+ }
102
+
103
+ case 'End': {
104
+ e.preventDefault()
105
+ const lastIndex = enabledIndices[enabledIndices.length - 1]
106
+ focusSegment(lastIndex)
107
+ onChange(options[lastIndex].id)
108
+ break
109
+ }
110
+
111
+ case 'Enter':
112
+ case ' ':
113
+ e.preventDefault()
114
+ onChange(options[index].id)
115
+ break
116
+
117
+ default:
118
+ break
119
+ }
120
+ },
121
+ [focusSegment, getEnabledIndices, onChange, options],
122
+ )
123
+
124
+ const handleSegmentClick = useCallback(
125
+ (optionId: string, index: number) => {
126
+ onChange(optionId)
127
+ setFocusIndex(index)
128
+ },
129
+ [onChange],
130
+ )
131
+
132
+ const handleFocus = useCallback((index: number) => {
133
+ setFocusIndex(index)
134
+ }, [])
135
+
136
+ const isSelected = useCallback((optionId: string) => value === optionId, [value])
137
+ const ariaRole = role === 'tablist' ? 'tab' : 'radio'
138
+ const defaultAriaLabel =
139
+ ariaLabel ||
140
+ t(
141
+ role === 'tablist'
142
+ ? 'components.SegmentedControl.tabs'
143
+ : 'components.SegmentedControl.options',
144
+ )
145
+ const finalAriaLabel = defaultAriaLabel
146
+
147
+ const containerStyles = useMemo<React.CSSProperties>(
148
+ () => ({
149
+ display: 'flex',
150
+ flexWrap: 'wrap',
151
+ gap: '2px 8px',
152
+ padding: '4px',
153
+ backgroundColor: disableBg ? 'transparent' : grey['50'],
154
+ width: 'fit-content',
155
+ borderRadius: '8px',
156
+ }),
157
+ [disableBg],
158
+ )
159
+
160
+ return (
161
+ <div
162
+ ref={containerRef}
163
+ role={role}
164
+ aria-label={finalAriaLabel}
165
+ style={containerStyles}
166
+ >
167
+ {options.map((option, index) => (
168
+ <RcSesSegmentButton
169
+ key={option.id}
170
+ ref={(el) => {
171
+ buttonRefs.current[index] = el
172
+ }}
173
+ option={option}
174
+ isSelected={isSelected(option.id)}
175
+ isFocused={focusIndex === index && !option.disabled}
176
+ size={size}
177
+ ariaRole={ariaRole}
178
+ onClick={(optionId) => handleSegmentClick(optionId, index)}
179
+ onKeyDown={(e) => handleKeyDown(e, index)}
180
+ onFocus={() => handleFocus(index)}
181
+ />
182
+ ))}
183
+ </div>
184
+ )
185
+ },
186
+ )
187
+
188
+ export default RcSesSegmentedControl
@@ -1,5 +1,5 @@
1
1
  import { ThemeProvider } from '@mui/material/styles'
2
- import { render, screen } from '@testing-library/react'
2
+ import { fireEvent, render, screen } from '@testing-library/react'
3
3
  import { type ReactElement } from 'react'
4
4
  import { describe, expect, test, vi } from 'vitest'
5
5
 
@@ -94,4 +94,77 @@ describe('SelectableCardListItem', () => {
94
94
  expect(screen.getByText('List entry A')).toBeInTheDocument()
95
95
  expect(screen.getByText('List entry B')).toBeInTheDocument()
96
96
  })
97
+
98
+ test('calls onSelect once when Enter key is pressed on radio', () => {
99
+ const onSelect = vi.fn()
100
+ renderItem(
101
+ <SelectableCardListItem
102
+ title='Test'
103
+ selected={false}
104
+ onSelect={onSelect}
105
+ listItems={[]}
106
+ />,
107
+ )
108
+
109
+ const radio = screen.getByRole('radio')
110
+ radio.focus()
111
+ fireEvent.keyDown(radio, { key: 'Enter', code: 'Enter' })
112
+
113
+ expect(onSelect).toHaveBeenCalledTimes(1)
114
+ })
115
+
116
+ test('calls onSelect once when radio is clicked (no double-call)', () => {
117
+ const onSelect = vi.fn()
118
+ renderItem(
119
+ <SelectableCardListItem
120
+ title='Test'
121
+ selected={false}
122
+ onSelect={onSelect}
123
+ listItems={[]}
124
+ />,
125
+ )
126
+
127
+ const radio = screen.getByRole('radio')
128
+ fireEvent.click(radio)
129
+
130
+ expect(onSelect).toHaveBeenCalledTimes(1)
131
+ })
132
+
133
+ test('calls onSelect once when card is clicked outside radio', () => {
134
+ const onSelect = vi.fn()
135
+ renderItem(
136
+ <SelectableCardListItem
137
+ title='Test title'
138
+ selected={false}
139
+ onSelect={onSelect}
140
+ listItems={[]}
141
+ />,
142
+ )
143
+
144
+ // click on the title area (outside the radio)
145
+ const titleElement = screen.getByRole('heading', { name: 'Test title' })
146
+ fireEvent.click(titleElement)
147
+
148
+ expect(onSelect).toHaveBeenCalledTimes(1)
149
+ })
150
+
151
+ test('loading card is not selectable', () => {
152
+ const onSelect = vi.fn()
153
+ const { container } = renderItem(
154
+ <SelectableCardListItem
155
+ title='Loading'
156
+ selected={false}
157
+ onSelect={onSelect}
158
+ isLoading
159
+ listItems={[]}
160
+ />,
161
+ )
162
+
163
+ // no radio is rendered while loading, so there is no keyboard tab stop
164
+ expect(screen.queryByRole('radio')).toBeNull()
165
+
166
+ // mouse clicks are blocked by pointer-events on the card root
167
+ const card = container.querySelector('.MuiCard-root')
168
+ expect(card).toHaveStyle('pointer-events: none')
169
+ })
97
170
  })
@@ -33,6 +33,18 @@ const SelectableCardListItem = ({
33
33
  <Radio
34
34
  aria-label={`Select ${title}`}
35
35
  checked={selected}
36
+ onChange={(e) => {
37
+ e.stopPropagation()
38
+ onSelect()
39
+ }}
40
+ onClick={(e) => e.stopPropagation()}
41
+ onKeyDown={(e) => {
42
+ if (e.key === 'Enter') {
43
+ e.preventDefault()
44
+ e.stopPropagation()
45
+ onSelect()
46
+ }
47
+ }}
36
48
  sx={{
37
49
  p: 0,
38
50
  height: '1.25rem',
@@ -78,8 +90,11 @@ const SelectableCardListItem = ({
78
90
  borderRadius: '0.75rem',
79
91
  padding: { xs: '1rem' },
80
92
  borderColor: selected ? palette.primary.main : palette.grey[300],
81
- transition: 'all 0.2s ease',
93
+ transition: 'border-color 0.2s ease',
82
94
  gap: { xs: '0.5rem', md: '0.25rem' },
95
+ '&:has(input:focus-visible)': {
96
+ borderColor: palette.grey[900],
97
+ },
83
98
  }}
84
99
  title={titleTemplate}
85
100
  slotProps={{
@@ -135,7 +135,7 @@ describe('RcSesSearchInput', () => {
135
135
  expect(onSearch).not.toHaveBeenCalled()
136
136
  })
137
137
 
138
- test('does not call onSearch on Enter when search button is enabled (shouldSearchOnEnter=false)', () => {
138
+ test('calls onSearch on Enter when search button is enabled', () => {
139
139
  const onSearch = vi.fn()
140
140
  render(<TestWrapper onSearch={onSearch} defaultValue='hello' />)
141
141
 
@@ -143,7 +143,7 @@ describe('RcSesSearchInput', () => {
143
143
  fireEvent.click(input)
144
144
  fireEvent.keyDown(input, { key: 'Enter', code: 'Enter', charCode: 13 })
145
145
 
146
- expect(onSearch).not.toHaveBeenCalled()
146
+ expect(onSearch).toHaveBeenCalledWith('hello')
147
147
  })
148
148
 
149
149
  test('does not call onSearch when slotProps.field.onKeyDown calls preventDefault', () => {
@@ -200,4 +200,70 @@ describe('RcSesSearchInput', () => {
200
200
  expect(fieldOnChange).toHaveBeenCalled()
201
201
  })
202
202
  })
203
+
204
+ describe('onSearch callback', () => {
205
+ test('calls onSearch when Enter is pressed', () => {
206
+ const onSearch = vi.fn()
207
+ render(
208
+ <TestWrapper onSearch={onSearch} defaultValue='query' showSearchButton={false} />,
209
+ )
210
+
211
+ const input = screen.getByRole('textbox')
212
+ fireEvent.keyDown(input, { key: 'Enter', code: 'Enter', charCode: 13 })
213
+
214
+ expect(onSearch).toHaveBeenCalledWith('query')
215
+ })
216
+
217
+ test('calls onSearch when search button is clicked', () => {
218
+ const onSearch = vi.fn()
219
+ render(<TestWrapper onSearch={onSearch} defaultValue='query' />)
220
+
221
+ const button = screen.getByRole('button', { name: 'searchButtonLabel' })
222
+ fireEvent.click(button)
223
+
224
+ expect(onSearch).toHaveBeenCalledWith('query')
225
+ })
226
+
227
+ test('does not call onSearch when value is empty', () => {
228
+ const onSearch = vi.fn()
229
+ render(<TestWrapper onSearch={onSearch} showSearchButton={false} />)
230
+
231
+ const input = screen.getByRole('textbox')
232
+ fireEvent.keyDown(input, { key: 'Enter', code: 'Enter', charCode: 13 })
233
+
234
+ expect(onSearch).not.toHaveBeenCalled()
235
+ })
236
+
237
+ test('does not call parent form onSubmit when nested in a form', () => {
238
+ const parentFormOnSubmit = vi.fn((e) => e.preventDefault())
239
+ const searchOnSearch = vi.fn()
240
+
241
+ const NestedFormWrapper = () => {
242
+ const { control } = useForm({ defaultValues: { search: 'query' } })
243
+ return (
244
+ <ThemeProvider theme={theme}>
245
+ <form onSubmit={parentFormOnSubmit}>
246
+ <RcSesSearchInput
247
+ id='search'
248
+ name='search'
249
+ control={control}
250
+ label='Search'
251
+ errors={undefined}
252
+ onSearch={searchOnSearch}
253
+ showSearchButton={false}
254
+ />
255
+ </form>
256
+ </ThemeProvider>
257
+ )
258
+ }
259
+
260
+ render(<NestedFormWrapper />)
261
+
262
+ const input = screen.getByRole('textbox')
263
+ fireEvent.keyDown(input, { key: 'Enter', code: 'Enter', charCode: 13 })
264
+
265
+ expect(parentFormOnSubmit).not.toHaveBeenCalled()
266
+ expect(searchOnSearch).toHaveBeenCalledWith('query')
267
+ })
268
+ })
203
269
  })
@@ -42,6 +42,16 @@ type Props = Pick<TControllerProps, ImmediateControllerProps> &
42
42
  }
43
43
  }
44
44
 
45
+ /**
46
+ * Search input component with react-hook-form integration.
47
+ *
48
+ * ⚠️ Warning: This component renders an inner `<form>` element and uses `stopPropagation()`
49
+ * to prevent submit events from bubbling to parent forms. If nested inside another form,
50
+ * React will log a `validateDOMNesting` warning in development mode — this is expected
51
+ * for client-side rendering and does not affect functionality. Note this is not SSR-safe:
52
+ * an HTML parser drops the nested `<form>` tag, so under SSR/hydration the Enter key
53
+ * would submit the parent form instead.
54
+ */
45
55
  const RcSesSearchInput = React.forwardRef<HTMLInputElement, Props>((props, ref) => {
46
56
  const [hasSearchAttempted, setHasSearchAttempted] = React.useState(false)
47
57
  const internalInputRef = useRef<HTMLInputElement>(null)
@@ -115,32 +125,31 @@ const RcSesSearchInput = React.forwardRef<HTMLInputElement, Props>((props, ref)
115
125
  labelOnTop: slotProps?.wrapper?.labelOnTop ?? !sideLabel,
116
126
  }
117
127
 
118
- const shouldSearchOnEnter =
119
- !shouldRenderSearchButton || !!mergedSearchButtonProps.disabled
120
-
121
128
  const hasSearchValue = `${value ?? ''}`.trim().length > 0
122
129
  const visibleErrors = hasSearchAttempted ? errors : undefined
123
130
 
124
- const handleSearchClick: NonNullable<ButtonProps['onClick']> = (event) => {
131
+ const handleFormSubmit: React.FormEventHandler<HTMLFormElement> = (event) => {
132
+ event.preventDefault()
133
+ event.stopPropagation()
125
134
  setHasSearchAttempted(true)
126
- mergedSearchButtonProps.onClick?.(event)
127
135
 
128
- if (!event.defaultPrevented && hasSearchValue) {
136
+ if (hasSearchValue) {
129
137
  onSearch(value ?? '')
138
+ } else {
139
+ onBlur()
130
140
  }
131
141
  }
132
142
 
133
143
  const handleFieldKeyDown: NonNullable<TFieldProps['onKeyDown']> = (event) => {
134
144
  slotProps?.field?.onKeyDown?.(event)
135
145
 
136
- if (!event.defaultPrevented && shouldSearchOnEnter && event.key === 'Enter') {
137
- setHasSearchAttempted(true)
146
+ if (!event.defaultPrevented && event.key === 'Enter') {
138
147
  event.preventDefault()
139
-
140
- if (hasSearchValue) {
141
- onSearch(value ?? '')
148
+ const form = internalInputRef.current?.form
149
+ if (form?.requestSubmit) {
150
+ form.requestSubmit()
142
151
  } else {
143
- onBlur()
152
+ form?.dispatchEvent(new Event('submit', { cancelable: true, bubbles: true }))
144
153
  }
145
154
  }
146
155
  }
@@ -213,6 +222,8 @@ const RcSesSearchInput = React.forwardRef<HTMLInputElement, Props>((props, ref)
213
222
  {...mergedWrapperProps}
214
223
  >
215
224
  <Box
225
+ component='form'
226
+ onSubmit={handleFormSubmit}
216
227
  sx={{
217
228
  alignItems: 'stretch',
218
229
  display: 'flex',
@@ -254,8 +265,8 @@ const RcSesSearchInput = React.forwardRef<HTMLInputElement, Props>((props, ref)
254
265
 
255
266
  {shouldRenderSearchButton && (
256
267
  <RcSesButton
268
+ type='submit'
257
269
  disabled={disabled || mergedSearchButtonProps.disabled || !hasSearchValue}
258
- onClick={handleSearchClick}
259
270
  sx={[
260
271
  {
261
272
  flexShrink: 0,
@@ -10,6 +10,10 @@
10
10
  },
11
11
  "Button": {
12
12
  "loading": "Loading"
13
+ },
14
+ "SegmentedControl": {
15
+ "options": "Options",
16
+ "tabs": "Tabs"
13
17
  }
14
18
  }
15
19
  }
@@ -10,6 +10,10 @@
10
10
  },
11
11
  "Button": {
12
12
  "loading": "Kraunasi"
13
+ },
14
+ "SegmentedControl": {
15
+ "options": "Parinktys",
16
+ "tabs": "Skirtukai"
13
17
  }
14
18
  }
15
19
  }
@@ -14,6 +14,7 @@ import DataPagination from '@/components/common/DataPagination'
14
14
  import RcSesIconWithCircularBackground from '@/components/common/IconWithCircularBackground'
15
15
  import RcSesImageCard from '@/components/common/ImageCard'
16
16
  import ListWithIcons from '@/components/common/ListWithIcons'
17
+ import RcSesSegmentedControl from '@/components/common/SegmentedControl'
17
18
  import RcSesSnackbar from '@/components/common/Snackbar'
18
19
  import {
19
20
  RcSesSnackbarProvider,
@@ -80,6 +81,7 @@ export {
80
81
  RcSesSnackbarProvider,
81
82
  RcSesModal,
82
83
  }
84
+ export { RcSesSegmentedControl }
83
85
  export { RcSesCheckbox, RcSesCheckboxFormControl, RcSesSimpleCheckbox }
84
86
  export { useSnackbar }
85
87
  export { RcSesDatepicker }
@@ -1,6 +1,11 @@
1
1
  import { RcSesCardProps } from '@/components/common/Card'
2
2
  import { ListWithIconsProps } from '@/components/common/ListWithIcons'
3
3
  import { ListWithIconsItemData } from '@/components/common/ListWithIcons/ListWithIcons.types'
4
+ import {
5
+ RcSesSegmentOption,
6
+ RcSesSegmentedControlProps,
7
+ } from '@/components/common/SegmentedControl'
8
+ import { RcSesSegmentButtonProps } from '@/components/common/SegmentedControl/components/SegmentButton'
4
9
  import { RcSesFormControlLabelProps } from '@/components/form/inputs/FormControlLabel'
5
10
  import { SimpleCheckboxProps } from '@/components/form/inputs/SimpleCheckbox'
6
11
  import { RcSesCardFormContainerProps } from '@/components/layout/ServiceFormContainer/CardFormContainer'
@@ -28,6 +33,9 @@ export type {
28
33
  RcSesLoaderSize,
29
34
  RcSesCardFormContainerProps,
30
35
  RcSesCardProps,
36
+ RcSesSegmentedControlProps,
37
+ RcSesSegmentButtonProps,
38
+ RcSesSegmentOption,
31
39
  ServiceWizardStepperProps,
32
40
  SimpleCheckboxProps,
33
41
  RcSesFormControlLabelProps,