@oslokommune/punkt-react 20.1.0 → 20.1.3

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.
@@ -15,7 +15,6 @@ export const DatepickerInputs = ({ state }: { state: IDatepickerState }) => {
15
15
  readOnly,
16
16
  required,
17
17
  label,
18
- name,
19
18
  placeholder,
20
19
  hasError,
21
20
  helptext,
@@ -38,6 +37,7 @@ export const DatepickerInputs = ({ state }: { state: IDatepickerState }) => {
38
37
  handleRangeFromChange,
39
38
  handleRangeToChange,
40
39
  handleRangeBlur,
40
+ rangeToValue,
41
41
  handleMultipleBlur,
42
42
  handleTagRemoved,
43
43
  handleSingleKeydown,
@@ -82,7 +82,6 @@ export const DatepickerInputs = ({ state }: { state: IDatepickerState }) => {
82
82
  className={inputClasses}
83
83
  type={inputType}
84
84
  id={inputId}
85
- name={name ?? id}
86
85
  placeholder={placeholder}
87
86
  readOnly={readOnly || (isIOSDevice && !readOnly)}
88
87
  disabled={isInputDisabled}
@@ -113,7 +112,6 @@ export const DatepickerInputs = ({ state }: { state: IDatepickerState }) => {
113
112
  className={inputClasses}
114
113
  type={inputType}
115
114
  id={inputId}
116
- name={name ? `${name}-from` : `${id}-from`}
117
115
  value={values[0] ?? ''}
118
116
  min={minStr}
119
117
  max={maxStr}
@@ -141,8 +139,7 @@ export const DatepickerInputs = ({ state }: { state: IDatepickerState }) => {
141
139
  className={inputClasses}
142
140
  type={inputType}
143
141
  id={`${id}-to`}
144
- name={name ? `${name}-to` : `${id}-to`}
145
- value={values[1] ?? ''}
142
+ value={rangeToValue}
146
143
  min={minStr}
147
144
  max={maxStr}
148
145
  readOnly={readOnly || (isIOSDevice && !readOnly)}
@@ -172,7 +169,6 @@ export const DatepickerInputs = ({ state }: { state: IDatepickerState }) => {
172
169
  className={inputClasses}
173
170
  type={inputType}
174
171
  id={inputId}
175
- name={name ?? id}
176
172
  value={values[0] ?? ''}
177
173
  min={minStr}
178
174
  max={maxStr}
@@ -1,55 +1,23 @@
1
- import type { TPktStrings, IPktStringsProps, TPktStringsOverride } from 'shared-strings'
2
- import type { ChangeEvent, InputHTMLAttributes, ReactNode } from 'react'
1
+ import type { TPktStrings, TPktStringsOverride } from 'shared-strings'
2
+ import type { ChangeEvent, FocusEventHandler, InputHTMLAttributes, ReactNode } from 'react'
3
+ import type { IPktDatepickerBase, TDatepickerStringsNamespace } from 'shared-types'
3
4
  import type { TPktInputSize } from 'shared-types/size'
4
5
 
5
- export type TDatepickerStrings = 'generic' | 'datepicker' | 'validation' | 'forms' | 'dates' | 'calendar'
6
+ export type TDatepickerStrings = TDatepickerStringsNamespace
6
7
 
7
8
  export interface IPktDatepicker
8
- extends Omit<InputHTMLAttributes<HTMLInputElement>, 'value' | 'onChange'>, IPktStringsProps<TDatepickerStrings> {
9
+ extends
10
+ Omit<IPktDatepickerBase, 'helptext' | 'helptextDropdown' | 'errorMessage'>,
11
+ Omit<InputHTMLAttributes<HTMLInputElement>, keyof IPktDatepickerBase | 'onChange'> {
9
12
  id: string
10
13
  label: string
11
- ariaDescribedby?: string
12
-
13
- // Datepicker-specific
14
- value?: string | string[]
15
- dateformat?: string
16
- multiple?: boolean
17
- maxlength?: number
18
- range?: boolean
19
- showRangeLabels?: boolean
20
- weeknumbers?: boolean
21
- withcontrols?: boolean
22
- excludedates?: string[]
23
- excludeweekdays?: string[]
24
- currentmonth?: string
25
- today?: string
26
- calendarOpen?: boolean
27
- timezone?: string
28
-
29
- // InputWrapper props
30
- fullwidth?: boolean
31
- inputSize?: TPktInputSize
32
- hasFieldset?: boolean
33
- inline?: boolean
34
- counter?: boolean
35
14
  helptext?: string | ReactNode
36
15
  helptextDropdown?: string | ReactNode
37
- helptextDropdownButton?: string
38
- hasError?: boolean
39
16
  errorMessage?: string | ReactNode
40
- optionalTag?: boolean
41
- optionalText?: string
42
- requiredTag?: boolean
43
- requiredText?: string
44
- tagText?: string
45
- useWrapper?: boolean
46
17
 
47
18
  // Events
48
19
  onChange?: (e: ChangeEvent<HTMLInputElement>) => void
49
20
  onValueChange?: (values: string[]) => void
50
-
51
- // React standard
52
- className?: string
53
21
  }
54
22
 
55
23
  export interface IDatepickerState {
@@ -92,7 +60,7 @@ export interface IDatepickerState {
92
60
  optionalText?: string
93
61
  requiredTag: boolean
94
62
  requiredText?: string
95
- tagText?: string
63
+ tagText?: string | null
96
64
  useWrapper: boolean
97
65
  className?: string
98
66
  minStr?: string
@@ -119,9 +87,13 @@ export interface IDatepickerState {
119
87
  changeInputRef: React.RefObject<HTMLInputElement | null>
120
88
  btnRef: React.RefObject<HTMLButtonElement | null>
121
89
  wrapperRef: React.RefObject<HTMLDivElement | null>
90
+ rootRef: React.RefObject<HTMLDivElement | null>
122
91
 
123
- // onChange passthrough for hidden input
92
+ // Passthrough for hidden input
124
93
  onChange?: (e: ChangeEvent<HTMLInputElement>) => void
94
+ onFocus?: FocusEventHandler<HTMLInputElement>
95
+ onBlur?: FocusEventHandler<HTMLInputElement>
96
+ reportFocusChange: FocusEventHandler<HTMLDivElement>
125
97
 
126
98
  // Calendar callbacks
127
99
  toggleCalendar: () => void
@@ -135,6 +107,8 @@ export interface IDatepickerState {
135
107
  handleRangeFromChange: (e: React.ChangeEvent<HTMLInputElement>) => void
136
108
  handleRangeToChange: (e: React.ChangeEvent<HTMLInputElement>) => void
137
109
  handleRangeBlur: () => void
110
+ rangeToValue: string
111
+ calendarSelected: string[]
138
112
  handleMultipleBlur: (e: React.FocusEvent<HTMLInputElement>) => void
139
113
  handleTagRemoved: (date: string) => void
140
114
 
@@ -1,5 +1,5 @@
1
1
  import { useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'
2
- import type { TPktInputSize } from 'shared-types/size'
2
+ import { DATEPICKER_DEFAULTS } from 'shared-types'
3
3
  import { valueToArray } from 'shared-utils/value-utils'
4
4
  import { isIOS } from 'shared-utils/device-utils'
5
5
  import { newDate, filterSelectableDates } from 'shared-utils/date-utils'
@@ -11,11 +11,16 @@ import {
11
11
  processDateSelection,
12
12
  handleDatepickerKeydown,
13
13
  validateRangeOrder,
14
+ datepickerHasCounter,
15
+ datepickerLimitReached,
16
+ completeRangeWithTo,
17
+ rangeCalendarSelection,
14
18
  } from 'shared-utils/datepicker-utils'
15
19
 
16
20
  import type { IPktDatepicker, IDatepickerState } from './types'
17
21
  import { usePktStrings } from '../../hooks/usePktStrings'
18
22
  import { setNativeInputValue } from '../../utils/nativeInputValue'
23
+ import { createFocusWithinTracker } from 'shared-utils/forms/focus-within'
19
24
 
20
25
  export function useDatepickerState(props: IPktDatepicker, ref: React.ForwardedRef<HTMLDivElement>): IDatepickerState {
21
26
  const {
@@ -23,45 +28,47 @@ export function useDatepickerState(props: IPktDatepicker, ref: React.ForwardedRe
23
28
  label,
24
29
  value,
25
30
  defaultValue,
26
- dateformat = 'dd.MM.yyyy',
27
- multiple = false,
31
+ dateformat = DATEPICKER_DEFAULTS.dateformat,
32
+ multiple = DATEPICKER_DEFAULTS.multiple,
28
33
  maxlength,
29
- range = false,
30
- showRangeLabels = false,
31
- weeknumbers = false,
32
- withcontrols = false,
34
+ range = DATEPICKER_DEFAULTS.range,
35
+ showRangeLabels = DATEPICKER_DEFAULTS.showRangeLabels,
36
+ weeknumbers = DATEPICKER_DEFAULTS.weeknumbers,
37
+ withcontrols = DATEPICKER_DEFAULTS.withcontrols,
33
38
  excludedates,
34
39
  excludeweekdays,
35
40
  currentmonth,
36
41
  today,
37
42
  calendarOpen: calendarOpenProp,
38
43
  timezone,
39
- fullwidth = false,
40
- inputSize = 'medium' as TPktInputSize,
41
- hasFieldset = false,
44
+ fullwidth = DATEPICKER_DEFAULTS.fullwidth,
45
+ inputSize = DATEPICKER_DEFAULTS.inputSize,
46
+ hasFieldset,
42
47
  counter,
43
- inline = false,
48
+ inline = DATEPICKER_DEFAULTS.inline,
44
49
  helptext,
45
50
  helptextDropdown,
46
51
  helptextDropdownButton,
47
- hasError = false,
52
+ hasError = DATEPICKER_DEFAULTS.hasError,
48
53
  errorMessage,
49
- optionalTag = false,
54
+ optionalTag = DATEPICKER_DEFAULTS.optionalTag,
50
55
  optionalText,
51
- requiredTag = false,
56
+ requiredTag = DATEPICKER_DEFAULTS.requiredTag,
52
57
  requiredText,
53
58
  tagText,
54
- useWrapper = true,
59
+ useWrapper = DATEPICKER_DEFAULTS.useWrapper,
55
60
  strings: stringsProp,
56
- disabled = false,
61
+ disabled = DATEPICKER_DEFAULTS.disabled,
57
62
  readOnly = false,
58
- required = false,
63
+ required = DATEPICKER_DEFAULTS.required,
59
64
  name,
60
65
  min,
61
66
  max,
62
67
  placeholder,
63
68
  onChange,
64
69
  onValueChange,
70
+ onFocus,
71
+ onBlur,
65
72
  className,
66
73
  ...restProps
67
74
  } = props
@@ -86,8 +93,15 @@ export function useDatepickerState(props: IPktDatepicker, ref: React.ForwardedRe
86
93
  setInternalValue(normalizeValue(value))
87
94
  }
88
95
 
96
+ const [toWithoutFrom, setToWithoutFrom] = useState<string | null>(null)
97
+ const rangeToValue = values[0] ? (values[1] ?? '') : (toWithoutFrom ?? '')
98
+ const calendarSelected = useMemo(
99
+ () => (range ? rangeCalendarSelection(values[0], values[1]) : values),
100
+ [range, values],
101
+ )
102
+
89
103
  // Calendar state
90
- const [calendarOpen, setCalendarOpen] = useState(calendarOpenProp ?? false)
104
+ const [calendarOpen, setCalendarOpen] = useState(calendarOpenProp ?? DATEPICKER_DEFAULTS.calendarOpen)
91
105
 
92
106
  const [prevCalendarOpenProp, setPrevCalendarOpenProp] = useState(calendarOpenProp)
93
107
  if (calendarOpenProp !== prevCalendarOpenProp) {
@@ -101,6 +115,7 @@ export function useDatepickerState(props: IPktDatepicker, ref: React.ForwardedRe
101
115
  const changeInputRef = useRef<HTMLInputElement>(null)
102
116
  const btnRef = useRef<HTMLButtonElement>(null)
103
117
  const wrapperRef = useRef<HTMLDivElement>(null)
118
+ const rootRef = useRef<HTMLDivElement>(null)
104
119
 
105
120
  // Derived state
106
121
  const inputType = useMemo(() => getDatepickerInputType(), [])
@@ -151,9 +166,9 @@ export function useDatepickerState(props: IPktDatepicker, ref: React.ForwardedRe
151
166
  return undefined
152
167
  }, [currentmonth, maxStr])
153
168
 
154
- const isInputDisabled = disabled || (multiple && maxlength != null && values.length >= maxlength)
169
+ const isInputDisabled = disabled || (multiple && datepickerLimitReached(maxlength, values.length))
155
170
  // Telleren vises av seg selv når det er noe å telle, men kan slås av eksplisitt
156
- const hasCounter = counter ?? (multiple && maxlength != null)
171
+ const hasCounter = datepickerHasCounter(counter, multiple, maxlength)
157
172
  const inputId = `${id}-input`
158
173
  const formValue = values.join(',')
159
174
 
@@ -204,6 +219,35 @@ export function useDatepickerState(props: IPktDatepicker, ref: React.ForwardedRe
204
219
  setCalendarOpen(false)
205
220
  }, [])
206
221
 
222
+ const focusField = useCallback(() => inputRef.current?.focus(), [])
223
+
224
+ const focusIsWithin = useCallback((selector: string) => {
225
+ const active = document.activeElement
226
+ return !!active && !!rootRef.current?.contains(active) && !!active.closest(selector)
227
+ }, [])
228
+
229
+ // Focus and blur for the whole datepicker, reported through the named hidden input
230
+ const [focusTracker] = useState(() =>
231
+ createFocusWithinTracker(
232
+ (node) => !!rootRef.current?.contains(node),
233
+ (type, relatedTarget) => {
234
+ if (type === 'blur') setToWithoutFrom(null)
235
+ changeInputRef.current?.dispatchEvent(
236
+ new FocusEvent(type === 'focus' ? 'focusin' : 'focusout', { bubbles: true, relatedTarget }),
237
+ )
238
+ },
239
+ ),
240
+ )
241
+
242
+ const reportFocusChange = useCallback(
243
+ (e: React.FocusEvent<HTMLDivElement>) => {
244
+ if (e.target === changeInputRef.current) return
245
+ if (e.type === 'focus') focusTracker.focusin(e.relatedTarget)
246
+ else focusTracker.focusout(e.relatedTarget)
247
+ },
248
+ [focusTracker],
249
+ )
250
+
207
251
  // Outside click / Escape
208
252
  useEffect(() => {
209
253
  if (!calendarOpen) return
@@ -221,8 +265,8 @@ export function useDatepickerState(props: IPktDatepicker, ref: React.ForwardedRe
221
265
 
222
266
  const handleKeydown = (e: KeyboardEvent) => {
223
267
  if (e.key === 'Escape') {
268
+ if (focusIsWithin('.pkt-datepicker')) focusField()
224
269
  hideCalendar()
225
- inputRef.current?.focus()
226
270
  }
227
271
  }
228
272
 
@@ -232,7 +276,7 @@ export function useDatepickerState(props: IPktDatepicker, ref: React.ForwardedRe
232
276
  document.removeEventListener('click', handleClick, true)
233
277
  document.removeEventListener('keydown', handleKeydown)
234
278
  }
235
- }, [calendarOpen, hideCalendar])
279
+ }, [calendarOpen, hideCalendar, focusField, focusIsWithin])
236
280
 
237
281
  // iOS auto-open on focus
238
282
  const handleFocus = useCallback(() => {
@@ -243,25 +287,40 @@ export function useDatepickerState(props: IPktDatepicker, ref: React.ForwardedRe
243
287
 
244
288
  // Calendar date selection
245
289
  const handleDateSelected = useCallback(
246
- (selected: string[]) => {
290
+ (calendarSelected: string[]) => {
291
+ const selected = range
292
+ ? completeRangeWithTo(calendarSelected, values[0] ? null : toWithoutFrom, excludedates, excludeweekdays)
293
+ : calendarSelected
247
294
  const processed = processDateSelection(selected, multiple, range)
248
295
  const newValues = valueToArray(processed)
249
296
 
297
+ setToWithoutFrom(null)
250
298
  updateValues(newValues)
251
299
  dispatchChange(newValues)
252
300
 
253
- if (!multiple && !range) {
254
- hideCalendar()
255
- inputRef.current?.focus()
301
+ if (!multiple && (!range || newValues.length === 2)) {
302
+ focusField()
303
+ if (!range || selected !== calendarSelected) hideCalendar()
256
304
  }
257
305
  },
258
- [multiple, range, updateValues, dispatchChange, hideCalendar],
306
+ [
307
+ multiple,
308
+ range,
309
+ values,
310
+ toWithoutFrom,
311
+ excludedates,
312
+ excludeweekdays,
313
+ updateValues,
314
+ dispatchChange,
315
+ hideCalendar,
316
+ focusField,
317
+ ],
259
318
  )
260
319
 
261
320
  const handleCalendarClose = useCallback(() => {
321
+ if (focusIsWithin('.pkt-calendar-popup')) focusField()
262
322
  hideCalendar()
263
- inputRef.current?.focus()
264
- }, [hideCalendar])
323
+ }, [hideCalendar, focusField, focusIsWithin])
265
324
 
266
325
  // Single mode input change
267
326
  const handleSingleInputChange = useCallback(
@@ -278,18 +337,22 @@ export function useDatepickerState(props: IPktDatepicker, ref: React.ForwardedRe
278
337
  const handleRangeFromChange = useCallback(
279
338
  (e: React.ChangeEvent<HTMLInputElement>) => {
280
339
  const fromVal = e.target.value
281
- const toVal = values[1] ?? ''
282
- const newValues = [fromVal, toVal].filter(Boolean)
340
+ setToWithoutFrom(fromVal ? null : rangeToValue || null)
341
+ const newValues = fromVal ? [fromVal, rangeToValue].filter(Boolean) : []
283
342
  updateValues(newValues)
284
343
  dispatchChange(newValues)
285
344
  },
286
- [values, updateValues, dispatchChange],
345
+ [rangeToValue, updateValues, dispatchChange],
287
346
  )
288
347
 
289
348
  const handleRangeToChange = useCallback(
290
349
  (e: React.ChangeEvent<HTMLInputElement>) => {
291
350
  const fromVal = values[0] ?? ''
292
351
  const toVal = e.target.value
352
+ if (!fromVal) {
353
+ setToWithoutFrom(toVal || null)
354
+ return
355
+ }
293
356
  const newValues = [fromVal, toVal].filter(Boolean)
294
357
  updateValues(newValues)
295
358
  dispatchChange(newValues)
@@ -423,6 +486,7 @@ export function useDatepickerState(props: IPktDatepicker, ref: React.ForwardedRe
423
486
  window.clearTimeout(resetTimeout)
424
487
  resetTimeout = window.setTimeout(() => {
425
488
  setInternalValue(initialValuesRef.current)
489
+ setToWithoutFrom(null)
426
490
  setCalendarOpen(false)
427
491
  if (changeInputRef.current) {
428
492
  changeInputRef.current.value = initialValuesRef.current.join(',')
@@ -487,7 +551,7 @@ export function useDatepickerState(props: IPktDatepicker, ref: React.ForwardedRe
487
551
  placeholder,
488
552
  fullwidth,
489
553
  inputSize,
490
- hasFieldset,
554
+ hasFieldset: hasFieldset ?? false,
491
555
  inline,
492
556
  helptext,
493
557
  helptextDropdown,
@@ -520,7 +584,11 @@ export function useDatepickerState(props: IPktDatepicker, ref: React.ForwardedRe
520
584
  changeInputRef,
521
585
  btnRef,
522
586
  wrapperRef,
587
+ rootRef,
523
588
  onChange,
589
+ onFocus,
590
+ onBlur,
591
+ reportFocusChange,
524
592
  toggleCalendar,
525
593
  hideCalendar,
526
594
  handleDateSelected,
@@ -530,6 +598,8 @@ export function useDatepickerState(props: IPktDatepicker, ref: React.ForwardedRe
530
598
  handleRangeFromChange,
531
599
  handleRangeToChange,
532
600
  handleRangeBlur,
601
+ rangeToValue,
602
+ calendarSelected,
533
603
  handleMultipleBlur,
534
604
  handleTagRemoved,
535
605
  handleSingleKeydown,