@oslokommune/punkt-react 20.1.1 → 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.
@@ -1,3 +1,5 @@
1
+ import type { IFormFieldCommonProps } from './form-field';
2
+ import type { TPktInputSize } from './size';
1
3
  /**
2
4
  * Internationalization strings for the datepicker component family.
3
5
  * Shared between Elements and React packages.
@@ -44,3 +46,77 @@ export declare const defaultSingleStrings: IDatepickerStrings;
44
46
  * Default strings for range datepicker
45
47
  */
46
48
  export declare const defaultRangeStrings: IDatepickerStrings;
49
+ /** String catalogue namespaces read by the datepicker. */
50
+ export type TDatepickerStringsNamespace = 'forms' | 'validation' | 'generic' | 'datepicker' | 'dates' | 'calendar';
51
+ /**
52
+ * Datepicker props shared by React, Elements, and typed component specs.
53
+ *
54
+ * @remarks Lists only the input-wrapper props the datepicker forwards. It does not support
55
+ * `counterPosition`, `layout` or `role`. The wrapper's `size` is `inputSize` here, and the
56
+ * counter counts dates against `maxlength` instead of `counterMaxLength`.
57
+ *
58
+ * React requires `id` and `label`, and widens `helptext`, `helptextDropdown` and
59
+ * `errorMessage` to `ReactNode`. Elements widens `min`, `max`, `maxlength`, `currentmonth`,
60
+ * `today`, `ariaDescribedby` and `helptextDropdownButton` to `| null` (Lit uses `null` for an
61
+ * unset attribute), `useWrapper` to `Booleanish`, and omits `form`, which is a getter
62
+ * returning the associated `HTMLFormElement`, not the form id.
63
+ *
64
+ * `counter` and `hasFieldset` are tri-state: `null` means the component derives the value.
65
+ */
66
+ export interface IPktDatepickerBase extends IFormFieldCommonProps<TDatepickerStringsNamespace> {
67
+ id?: string;
68
+ name?: string;
69
+ form?: string;
70
+ /** ISO dates. Comma-separated when given as a string with `multiple` or `range`. */
71
+ value?: string | string[];
72
+ dateformat?: string;
73
+ currentmonth?: string;
74
+ excludeweekdays?: string[];
75
+ excludedates?: string[];
76
+ min?: string | number;
77
+ max?: string | number;
78
+ weeknumbers?: boolean;
79
+ withcontrols?: boolean;
80
+ multiple?: boolean;
81
+ maxlength?: number;
82
+ range?: boolean;
83
+ showRangeLabels?: boolean;
84
+ today?: string;
85
+ calendarOpen?: boolean;
86
+ timezone?: string;
87
+ required?: boolean;
88
+ ariaDescribedby?: string;
89
+ inline?: boolean;
90
+ fullwidth?: boolean;
91
+ useWrapper?: boolean;
92
+ counter?: boolean | null;
93
+ inputSize?: TPktInputSize;
94
+ hasFieldset?: boolean | null;
95
+ }
96
+ /**
97
+ * Documented Datepicker props (subset of `IPktDatepickerBase`).
98
+ * Used for typed component specs in documentation.
99
+ */
100
+ export type IDatepickerSpecProps = Pick<IPktDatepickerBase, 'name' | 'form' | 'label' | 'helptext' | 'helptextDropdown' | 'helptextDropdownButton' | 'dateformat' | 'currentmonth' | 'value' | 'excludeweekdays' | 'excludedates' | 'min' | 'max' | 'weeknumbers' | 'withcontrols' | 'multiple' | 'maxlength' | 'range' | 'showRangeLabels' | 'today' | 'calendarOpen' | 'hasError' | 'errorMessage' | 'disabled' | 'fullwidth' | 'inputSize' | 'required' | 'requiredTag' | 'requiredText' | 'optionalTag' | 'optionalText' | 'tagText' | 'useWrapper' | 'id' | 'ariaDescribedby' | 'inline' | 'hasFieldset' | 'counter'>;
101
+ /**
102
+ * Default values for pkt-datepicker. Single source of truth for both frameworks.
103
+ * `counter` and `hasFieldset` are intentionally absent: `null` lets the component derive them.
104
+ */
105
+ export declare const DATEPICKER_DEFAULTS: {
106
+ readonly dateformat: 'dd.MM.yyyy';
107
+ readonly multiple: false;
108
+ readonly range: false;
109
+ readonly showRangeLabels: false;
110
+ readonly weeknumbers: false;
111
+ readonly withcontrols: false;
112
+ readonly calendarOpen: false;
113
+ readonly required: false;
114
+ readonly requiredTag: false;
115
+ readonly optionalTag: false;
116
+ readonly hasError: false;
117
+ readonly disabled: false;
118
+ readonly inline: false;
119
+ readonly fullwidth: false;
120
+ readonly useWrapper: true;
121
+ readonly inputSize: 'medium';
122
+ };
@@ -0,0 +1,20 @@
1
+ // ../../shared-types/datepicker.ts
2
+ var e = {
3
+ dateformat: "dd.MM.yyyy",
4
+ multiple: !1,
5
+ range: !1,
6
+ showRangeLabels: !1,
7
+ weeknumbers: !1,
8
+ withcontrols: !1,
9
+ calendarOpen: !1,
10
+ required: !1,
11
+ requiredTag: !1,
12
+ optionalTag: !1,
13
+ hasError: !1,
14
+ disabled: !1,
15
+ inline: !1,
16
+ fullwidth: !1,
17
+ useWrapper: !0,
18
+ inputSize: "medium"
19
+ };
20
+ export { e as DATEPICKER_DEFAULTS };
@@ -53,8 +53,8 @@ export { MESSAGEBOX_SKINS, MESSAGEBOX_LIGHT_ONLY_SKINS, MESSAGEBOX_DEFAULTS } fr
53
53
  export type { IPktMessageboxBase, IMessageboxSpecProps } from './messagebox';
54
54
  export { CALENDAR_DEFAULTS } from './calendar';
55
55
  export type { IPktCalendarBase, ICalendarSpecProps, IDateConstraints, ICalendarGridDimensions, IGridCellPosition, TDateRangeMap, ISelectionState, ISelectionOptions, } from './calendar';
56
- export type { IDatepickerStrings } from './datepicker';
57
- export { defaultSingleStrings, defaultRangeStrings } from './datepicker';
56
+ export type { IDatepickerStrings, TDatepickerStringsNamespace, IPktDatepickerBase, IDatepickerSpecProps, } from './datepicker';
57
+ export { defaultSingleStrings, defaultRangeStrings, DATEPICKER_DEFAULTS } from './datepicker';
58
58
  export type { ITimepickerStrings } from './timepicker';
59
59
  export { defaultTimepickerStrings } from './timepicker';
60
60
  export { PROGRESSBAR_DEFAULTS, PROGRESSBAR_ROLES, PROGRESSBAR_SKINS, PROGRESSBAR_STATUS_PLACEMENTS, PROGRESSBAR_STATUS_TYPES, PROGRESSBAR_TITLE_POSITIONS, } from './progressbar';
@@ -17,8 +17,9 @@ import { TEXTINPUT_DEFAULTS as v } from "./textinput.js";
17
17
  import { TAG_DEFAULTS as y } from "./tag.js";
18
18
  import { MESSAGEBOX_DEFAULTS as b, MESSAGEBOX_LIGHT_ONLY_SKINS as x } from "./messagebox.js";
19
19
  import "./calendar.js";
20
- import { PROGRESSBAR_DEFAULTS as S } from "./progressbar.js";
20
+ import { DATEPICKER_DEFAULTS as S } from "./datepicker.js";
21
+ import { PROGRESSBAR_DEFAULTS as C } from "./progressbar.js";
21
22
  import "./combobox.js";
22
- import { SELECT_DEFAULTS as C } from "./select.js";
23
- import { TABLE_DEFAULTS as w } from "./table.js";
24
- export { p as ACCORDION_LIGHT_ONLY_SKINS, u as ANIMATION_DEFAULT_PATH, m as BUTTON_DEFAULTS, i as CARD_DEFAULTS, a as CARD_LIGHT_ONLY_SKINS, o as CHECKBOX_DEFAULTS, l as CONSENT_DEFAULTS, n as DEFAULT_FOOTER_PERSONVERN_URL, r as DEFAULT_FOOTER_TILGJENGELIGHET_URL, e as DEFAULT_HEADER_FOOTER_URL, t as DEFAULT_HEADER_LOGO_LINK, d as ICON_DEFAULTS, g as INPUT_WRAPPER_DEFAULTS, h as LINKCARD_LIGHT_ONLY_SKINS, f as LOADER_DEFAULTS, b as MESSAGEBOX_DEFAULTS, x as MESSAGEBOX_LIGHT_ONLY_SKINS, c as OPTION_GROUP_DEFAULTS, S as PROGRESSBAR_DEFAULTS, s as RADIOBUTTON_DEFAULTS, C as SELECT_DEFAULTS, w as TABLE_DEFAULTS, y as TAG_DEFAULTS, _ as TEXTAREA_DEFAULTS, v as TEXTINPUT_DEFAULTS };
23
+ import { SELECT_DEFAULTS as w } from "./select.js";
24
+ import { TABLE_DEFAULTS as T } from "./table.js";
25
+ export { p as ACCORDION_LIGHT_ONLY_SKINS, u as ANIMATION_DEFAULT_PATH, m as BUTTON_DEFAULTS, i as CARD_DEFAULTS, a as CARD_LIGHT_ONLY_SKINS, o as CHECKBOX_DEFAULTS, l as CONSENT_DEFAULTS, S as DATEPICKER_DEFAULTS, n as DEFAULT_FOOTER_PERSONVERN_URL, r as DEFAULT_FOOTER_TILGJENGELIGHET_URL, e as DEFAULT_HEADER_FOOTER_URL, t as DEFAULT_HEADER_LOGO_LINK, d as ICON_DEFAULTS, g as INPUT_WRAPPER_DEFAULTS, h as LINKCARD_LIGHT_ONLY_SKINS, f as LOADER_DEFAULTS, b as MESSAGEBOX_DEFAULTS, x as MESSAGEBOX_LIGHT_ONLY_SKINS, c as OPTION_GROUP_DEFAULTS, C as PROGRESSBAR_DEFAULTS, s as RADIOBUTTON_DEFAULTS, w as SELECT_DEFAULTS, T as TABLE_DEFAULTS, y as TAG_DEFAULTS, _ as TEXTAREA_DEFAULTS, v as TEXTINPUT_DEFAULTS };
@@ -29,6 +29,24 @@ export declare const getDatepickerInputClasses: (fullwidth: boolean, showRangeLa
29
29
  * Generates button CSS classes for calendar toggle button.
30
30
  */
31
31
  export declare const getDatepickerButtonClasses: (inputSize?: TPktInputSize) => Record<string, boolean>;
32
+ /**
33
+ * An explicit `counter` wins. Otherwise the counter shows when multiple dates have a limit.
34
+ */
35
+ export declare const datepickerHasCounter: (counter: boolean | null | undefined, multiple: boolean, maxlength: number | null | undefined) => boolean;
36
+ /**
37
+ * A `maxlength` of 0 or less means no limit, as in the calendar.
38
+ */
39
+ export declare const datepickerLimitReached: (maxlength: number | null | undefined, count: number) => boolean;
40
+ /**
41
+ * A from-date picked in the calendar while the to-field holds a date completes the range,
42
+ * unless it comes after the to-date or the calendar would not allow the range.
43
+ */
44
+ export declare const completeRangeWithTo: (selected: string[], to: string | null | undefined, excludedates?: string[], excludeweekdays?: string[]) => string[];
45
+ /**
46
+ * What the calendar shows for a range: nothing without a from-date, and the to-date only
47
+ * once it completes the range.
48
+ */
49
+ export declare const rangeCalendarSelection: (from?: string, to?: string) => string[];
32
50
  /**
33
51
  * Generates range label CSS classes.
34
52
  */
@@ -1,7 +1,8 @@
1
1
  import { isIOS as e } from "./device-utils.js";
2
2
  import { isValidDateRange as t } from "./date-utils.js";
3
+ import { convertSelectedToDates as n, isRangeAllowed as r } from "./calendar/selection-manager.js";
3
4
  // ../../shared-utils/datepicker-utils.ts
4
- var n = () => e() ? "text" : "date", r = (e) => !e || e.length !== 2 || t(e[0], e[1]), i = (e, t, n, r, i, a, o = "medium") => ({
5
+ var i = () => e() ? "text" : "date", a = (e) => !e || e.length !== 2 || t(e[0], e[1]), o = (e, t, n, r, i, a, o = "medium") => ({
5
6
  "pkt-input": !0,
6
7
  "pkt-datepicker__input": !0,
7
8
  [`pkt-input--${o}`]: !0,
@@ -10,22 +11,30 @@ var n = () => e() ? "text" : "date", r = (e) => !e || e.length !== 2 || t(e[0],
10
11
  "pkt-datepicker--multiple": n,
11
12
  "pkt-datepicker--range": r,
12
13
  "ios-readonly-hack": i === !1 && a === "text"
13
- }), a = (e = "medium") => ({
14
+ }), s = (e = "medium") => ({
14
15
  "pkt-input-icon": !0,
15
16
  "pkt-btn": !0,
16
17
  "pkt-btn--icon-only": !0,
17
18
  "pkt-btn--tertiary": !0,
18
19
  [`pkt-btn--${e}`]: !0,
19
20
  "pkt-datepicker__calendar-button": !0
20
- }), o = (e) => ({
21
+ }), c = (e, t, n) => e ?? (t && !!n && n > 0), l = (e, t) => !!e && e > 0 && t >= e, u = (e, t, i = [], a = []) => {
22
+ if (!t || e.length !== 1 || e[0] > t) return e;
23
+ let [o, s] = n([e[0], t]);
24
+ return r(s, [o], n(i), a) ? [e[0], t] : e;
25
+ }, d = (e, t) => e ? t && t >= e ? [e, t] : [e] : [], f = (e) => ({
21
26
  "pkt-input-prefix": e,
22
27
  "pkt-hide": !e
23
- }), s = (e, t, n) => !t && !n ? Array.isArray(e) ? e[0] || "" : e : Array.isArray(e) ? e.join(",") : e, c = (e, t, n = !1) => {
28
+ }), p = (e, t, n) => !t && !n ? Array.isArray(e) ? e[0] || "" : e : Array.isArray(e) ? e.join(",") : e, m = (e, t, n = !1) => {
24
29
  if (!e || !t) return;
25
- let r = t.parentElement?.getBoundingClientRect() || t.getBoundingClientRect(), i = n ? r.height + 30 : r.height, a = e.getBoundingClientRect().height, o = n ? "calc(100% - 30px)" : "100%";
26
- r && typeof window < "u" && r.top + a > window.innerHeight && r.top - a > 0 && (o = `calc(100% - ${i}px - ${a}px)`), e.style.top = o;
27
- }, l = (e, t, n, r, i, a) => {
30
+ let r = t.parentElement?.getBoundingClientRect() || t.getBoundingClientRect(), i = n ? r.height + 30 : r.height, a = e.getBoundingClientRect().height, o = e instanceof Element && parseFloat(getComputedStyle(e).marginTop) || 0, s = n ? "calc(100% - 30px)" : "100%";
31
+ if (typeof window < "u") {
32
+ let e = r.top + r.height + o + a <= window.innerHeight, t = r.top - o - a >= 0;
33
+ !e && t && (s = `calc(100% - ${i}px - ${a}px - ${2 * o}px)`);
34
+ }
35
+ e.style.top = s;
36
+ }, h = (e, t, n, r, i, a) => {
28
37
  let { key: o } = e;
29
38
  o === "," && (e.preventDefault(), a ? a(e) : i && i()), (o === "Space" || o === " ") && (e.preventDefault(), t(e)), o === "Enter" && (e.preventDefault(), n ? n() : r ? r() : i && i());
30
39
  };
31
- export { a as getDatepickerButtonClasses, i as getDatepickerInputClasses, n as getDatepickerInputType, o as getRangeLabelClasses, c as handleCalendarPosition, l as handleDatepickerKeydown, s as processDateSelection, r as validateRangeOrder };
40
+ export { u as completeRangeWithTo, c as datepickerHasCounter, l as datepickerLimitReached, s as getDatepickerButtonClasses, o as getDatepickerInputClasses, i as getDatepickerInputType, f as getRangeLabelClasses, m as handleCalendarPosition, h as handleDatepickerKeydown, p as processDateSelection, d as rangeCalendarSelection, a as validateRangeOrder };
@@ -0,0 +1,13 @@
1
+ export type TFocusChange = 'focus' | 'blur';
2
+ /**
3
+ * Reports one `focus` when focus enters a composite form field and one `blur` when it leaves,
4
+ * like a native input. Moves between the field's own elements report nothing.
5
+ *
6
+ * Focus events while focus is already inside are ignored. Chrome sends them with a detached
7
+ * `relatedTarget` when it rebuilds the inner parts of a focused date input.
8
+ */
9
+ export declare const createFocusWithinTracker: (contains: (node: Node) => boolean, report: (type: TFocusChange, relatedTarget: EventTarget | null) => void) => {
10
+ focusin(relatedTarget: EventTarget | null): void;
11
+ focusout(relatedTarget: EventTarget | null): void;
12
+ reset(): void;
13
+ };
@@ -0,0 +1,16 @@
1
+ // ../../shared-utils/forms/focus-within.ts
2
+ var e = (e, t) => {
3
+ let n = !1, r = (t) => typeof Node < "u" && t instanceof Node && t.isConnected && e(t);
4
+ return {
5
+ focusin(e) {
6
+ n || r(e) ? n = !0 : (n = !0, t("focus", e));
7
+ },
8
+ focusout(e) {
9
+ r(e) || (n = !1, t("blur", e));
10
+ },
11
+ reset() {
12
+ n = !1;
13
+ }
14
+ };
15
+ };
16
+ export { e as createFocusWithinTracker };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oslokommune/punkt-react",
3
- "version": "20.1.1",
3
+ "version": "20.1.3",
4
4
  "description": "React komponentbibliotek til Punkt, designsystem for Oslo kommune",
5
5
  "homepage": "https://punkt.oslo.kommune.no",
6
6
  "author": "Team Designsystem, Oslo kommune",
@@ -102,5 +102,5 @@
102
102
  "url": "https://github.com/oslokommune/punkt/issues"
103
103
  },
104
104
  "license": "MIT",
105
- "gitHead": "16b8d7faae1ef12d518f3b8acd96dab7dc4862fd"
105
+ "gitHead": "0c893c54ea9c8fb6f5f3ff07d753586292f98039"
106
106
  }
@@ -1,6 +1,7 @@
1
1
  import '@testing-library/jest-dom'
2
2
 
3
- import { render, screen } from '@testing-library/react'
3
+ import { act, fireEvent, render, screen } from '@testing-library/react'
4
+ import { vi } from 'vitest'
4
5
 
5
6
  import { IPktDatepicker, PktDatepicker } from './Datepicker'
6
7
 
@@ -135,6 +136,198 @@ describe('PktDatepicker', () => {
135
136
  expect(counter).toBeInTheDocument()
136
137
  })
137
138
 
139
+ describe('counter', () => {
140
+ const counterFor = (props: Partial<IPktDatepicker>) =>
141
+ createDatepickerTest(props).container.querySelector('.pkt-input__counter')
142
+
143
+ test('hides the counter when counter is false', () => {
144
+ expect(counterFor({ multiple: true, maxlength: 3, counter: false })).not.toBeInTheDocument()
145
+ })
146
+
147
+ test('shows the counter when counter is set without a limit', () => {
148
+ expect(counterFor({ counter: true })).toBeInTheDocument()
149
+ })
150
+
151
+ test('shows no counter when maxlength is 0', () => {
152
+ expect(counterFor({ multiple: true, maxlength: 0 })).not.toBeInTheDocument()
153
+ })
154
+ })
155
+
156
+ test('keeps the input enabled when maxlength is 0', () => {
157
+ const { container } = createDatepickerTest({ multiple: true, maxlength: 0 })
158
+
159
+ expect(container.querySelector('input.pkt-datepicker__input')).not.toBeDisabled()
160
+ })
161
+
162
+ describe('focus and blur', () => {
163
+ const setup = (props: Partial<IPktDatepicker> = {}) => {
164
+ const onFocus = vi.fn()
165
+ const onBlur = vi.fn()
166
+ const { container } = createDatepickerTest({ onFocus, onBlur, ...props })
167
+ const outside = container.appendChild(document.createElement('button'))
168
+ const input = container.querySelector('input.pkt-datepicker__input') as HTMLInputElement
169
+ const button = container.querySelector('.pkt-datepicker__calendar-button') as HTMLElement
170
+ return { container, input, button, outside, onFocus, onBlur }
171
+ }
172
+
173
+ test('calls onFocus and onBlur once per visit, however focus moves inside', () => {
174
+ const { input, button, outside, onFocus, onBlur } = setup()
175
+ act(() => input.focus())
176
+ act(() => button.focus())
177
+ act(() => input.focus())
178
+ act(() => outside.focus())
179
+
180
+ expect(onFocus).toHaveBeenCalledTimes(1)
181
+ expect(onBlur).toHaveBeenCalledTimes(1)
182
+ })
183
+
184
+ test('calls onBlur with an event from the named field, as react-hook-form expects', () => {
185
+ const { input, outside, onBlur } = setup({ name: 'dato' })
186
+ act(() => input.focus())
187
+ act(() => outside.focus())
188
+
189
+ const event = onBlur.mock.calls[0][0]
190
+ expect(event.type).toBe('blur')
191
+ expect(event.target).toHaveAttribute('name', 'dato')
192
+ })
193
+
194
+ test('ignores focus events while focus is already inside', () => {
195
+ const { input, onFocus } = setup()
196
+ act(() => input.focus())
197
+ fireEvent.focusIn(input, { relatedTarget: document.createElement('span') })
198
+
199
+ expect(onFocus).toHaveBeenCalledTimes(1)
200
+ })
201
+
202
+ test('returns focus to the field after picking a date', () => {
203
+ const { container, input, button, onFocus, onBlur } = setup({
204
+ today: '2026-11-09',
205
+ currentmonth: '2026-11-01',
206
+ })
207
+ act(() => input.focus())
208
+ fireEvent.click(button)
209
+ const date = container.querySelector('.pkt-calendar__date:not(.pkt-calendar__date--disabled)') as HTMLElement
210
+ act(() => date.focus())
211
+ fireEvent.click(date)
212
+
213
+ expect(document.activeElement).toBe(input)
214
+ expect(onFocus).toHaveBeenCalledTimes(1)
215
+ expect(onBlur).not.toHaveBeenCalled()
216
+ })
217
+ })
218
+
219
+ describe('emptying range fields', () => {
220
+ const setup = (defaultValue = '2026-11-05,2026-11-12') => {
221
+ const onChange = vi.fn()
222
+ const onValueChange = vi.fn()
223
+ const { container } = createDatepickerTest({
224
+ range: true,
225
+ defaultValue,
226
+ onChange,
227
+ onValueChange,
228
+ today: '2026-11-09',
229
+ currentmonth: '2026-11-01',
230
+ })
231
+ const outside = container.appendChild(document.createElement('button'))
232
+ const from = container.querySelector(`#${datePickerId}-input`) as HTMLInputElement
233
+ const to = container.querySelector(`#${datePickerId}-to`) as HTMLInputElement
234
+ const type = (input: HTMLInputElement, text: string, next: HTMLElement) => {
235
+ act(() => input.focus())
236
+ fireEvent.change(input, { target: { value: text } })
237
+ act(() => next.focus())
238
+ }
239
+ const pick = (date: string) => {
240
+ fireEvent.click(container.querySelector('.pkt-datepicker__calendar-button')!)
241
+ fireEvent.click(container.querySelector(`[data-date="${date}"]`)!)
242
+ return container.querySelector('.pkt-calendar-popup') as HTMLElement
243
+ }
244
+ return { from, to, outside, type, pick, onChange, onValueChange }
245
+ }
246
+
247
+ test('keeps the from-date when the to-date is emptied', () => {
248
+ const { from, to, outside, type, onChange, onValueChange } = setup()
249
+ type(to, '', outside)
250
+
251
+ expect([from.value, to.value]).toEqual(['2026-11-05', ''])
252
+ expect(onValueChange).toHaveBeenLastCalledWith(['2026-11-05'])
253
+ expect(onChange).not.toHaveBeenCalled()
254
+ })
255
+
256
+ test('keeps the to-date in its field while focus stays inside', () => {
257
+ const { from, to, type, onValueChange } = setup()
258
+ type(from, '', to)
259
+
260
+ expect([from.value, to.value]).toEqual(['', '2026-11-12'])
261
+ expect(onValueChange).toHaveBeenLastCalledWith([])
262
+ })
263
+
264
+ test('clears a to-date with no from-date when focus leaves', () => {
265
+ const { from, to, outside, type } = setup()
266
+ type(from, '', to)
267
+ act(() => outside.focus())
268
+
269
+ expect([from.value, to.value]).toEqual(['', ''])
270
+ })
271
+
272
+ test('completes the range when a new from-date is typed', () => {
273
+ const { from, to, outside, type, onValueChange } = setup()
274
+ type(from, '', to)
275
+ type(from, '2026-11-03', outside)
276
+
277
+ expect([from.value, to.value]).toEqual(['2026-11-03', '2026-11-12'])
278
+ expect(onValueChange).toHaveBeenLastCalledWith(['2026-11-03', '2026-11-12'])
279
+ })
280
+
281
+ test('keeps a to-date typed before the from-date', () => {
282
+ const { from, to, outside, type, onValueChange } = setup('')
283
+ type(to, '2026-11-12', from)
284
+
285
+ expect([from.value, to.value]).toEqual(['', '2026-11-12'])
286
+
287
+ type(from, '2026-11-03', outside)
288
+
289
+ expect(onValueChange).toHaveBeenLastCalledWith(['2026-11-03', '2026-11-12'])
290
+ })
291
+
292
+ test('completes the range when a from-date is picked in the calendar', () => {
293
+ const { from, to, type, pick, onValueChange } = setup()
294
+ type(from, '', to)
295
+ const popup = pick('2026-11-03')
296
+
297
+ expect([from.value, to.value]).toEqual(['2026-11-03', '2026-11-12'])
298
+ expect(onValueChange).toHaveBeenLastCalledWith(['2026-11-03', '2026-11-12'])
299
+ expect(popup).toHaveAttribute('hidden')
300
+ })
301
+
302
+ test('shows only complete parts of the range in the calendar while typing', () => {
303
+ const { from, to } = setup()
304
+ const container = from.closest('.pkt-datepicker') as HTMLElement
305
+ fireEvent.click(container.querySelector('.pkt-datepicker__calendar-button')!)
306
+ const selected = () =>
307
+ Array.from(container.querySelectorAll('.pkt-calendar__date--selected')).map((d) =>
308
+ d.getAttribute('data-date'),
309
+ )
310
+
311
+ fireEvent.change(from, { target: { value: '' } })
312
+ expect(selected()).toEqual([])
313
+
314
+ fireEvent.change(from, { target: { value: '2026-11-03' } })
315
+ expect(selected()).toEqual(['2026-11-03', '2026-11-12'])
316
+
317
+ fireEvent.change(to, { target: { value: '' } })
318
+ expect(selected()).toEqual(['2026-11-03'])
319
+ })
320
+
321
+ test('starts a new range when the picked date comes after the to-date', () => {
322
+ const { from, to, type, pick, onValueChange } = setup()
323
+ type(from, '', to)
324
+ pick('2026-11-20')
325
+
326
+ expect([from.value, to.value]).toEqual(['2026-11-20', ''])
327
+ expect(onValueChange).toHaveBeenLastCalledWith(['2026-11-20'])
328
+ })
329
+ })
330
+
138
331
  test('handles disabled property correctly', () => {
139
332
  const { container } = createDatepickerTest({
140
333
  disabled: true,
@@ -147,6 +340,13 @@ describe('PktDatepicker', () => {
147
340
  expect(button).toBeDisabled()
148
341
  })
149
342
 
343
+ test('renders a label, not a fieldset, when hasFieldset is null', () => {
344
+ const { container } = createDatepickerTest({ hasFieldset: null })
345
+
346
+ expect(container.querySelector('fieldset')).not.toBeInTheDocument()
347
+ expect(container.querySelector('label')).toHaveTextContent(label)
348
+ })
349
+
150
350
  test('handles required attribute', () => {
151
351
  const { container } = createDatepickerTest({
152
352
  required: true,
@@ -200,11 +400,11 @@ describe('PktDatepicker', () => {
200
400
  expect(wrapper).toHaveClass('my-custom-class')
201
401
  })
202
402
 
203
- test('uses id for input name when no name specified', () => {
403
+ test('uses id as the form name when no name is specified', () => {
204
404
  const { container } = createDatepickerTest()
205
405
 
206
- const input = container.querySelector('input[type="date"]') as HTMLInputElement
207
- expect(input).toHaveAttribute('name', datePickerId)
406
+ const formInput = container.querySelector('input[aria-hidden="true"]') as HTMLInputElement
407
+ expect(formInput).toHaveAttribute('name', datePickerId)
208
408
  })
209
409
 
210
410
  test('uses custom name when specified', () => {
@@ -93,15 +93,15 @@ describe('PktDatepicker', () => {
93
93
  expect(toInput).toBeInTheDocument()
94
94
  })
95
95
 
96
- test('range inputs have distinct names', () => {
96
+ test('range inputs have no name, so only the hidden input is submitted', () => {
97
97
  const { container } = createDatepickerTest({
98
98
  range: true,
99
99
  name: 'dates',
100
100
  })
101
101
 
102
102
  const inputs = container.querySelectorAll('input[type="date"]') as NodeListOf<HTMLInputElement>
103
- expect(inputs[0]).toHaveAttribute('name', 'dates-from')
104
- expect(inputs[1]).toHaveAttribute('name', 'dates-to')
103
+ expect(inputs[0]).not.toHaveAttribute('name')
104
+ expect(inputs[1]).not.toHaveAttribute('name')
105
105
  })
106
106
  })
107
107
 
@@ -22,7 +22,13 @@ export const PktDatepicker = forwardRef<HTMLDivElement, IPktDatepicker>((props,
22
22
  .join(' ')
23
23
 
24
24
  return (
25
- <div className={outerClasses} id={state.id || undefined}>
25
+ <div
26
+ ref={state.rootRef}
27
+ className={outerClasses}
28
+ id={state.id || undefined}
29
+ onFocus={state.reportFocusChange}
30
+ onBlur={state.reportFocusChange}
31
+ >
26
32
  <PktInputWrapper
27
33
  strings={state.stringsOverride}
28
34
  ref={state.wrapperRef}
@@ -57,7 +63,7 @@ export const PktDatepicker = forwardRef<HTMLDivElement, IPktDatepicker>((props,
57
63
  range={state.range}
58
64
  weeknumbers={state.weeknumbers}
59
65
  withcontrols={state.withcontrols}
60
- selected={state.values}
66
+ selected={state.calendarSelected}
61
67
  earliest={state.minStr}
62
68
  latest={state.maxStr}
63
69
  excludedates={state.excludedates}
@@ -75,8 +81,11 @@ export const PktDatepicker = forwardRef<HTMLDivElement, IPktDatepicker>((props,
75
81
  <input
76
82
  ref={state.changeInputRef}
77
83
  type="text"
78
- name={state.name}
84
+ name={state.name ?? state.id}
85
+ form={props.form}
79
86
  onChange={state.onChange}
87
+ onFocus={state.onFocus}
88
+ onBlur={state.onBlur}
80
89
  tabIndex={-1}
81
90
  aria-hidden="true"
82
91
  className="pkt-visually-hidden"
@@ -183,9 +183,7 @@ describe('PktDatepicker', () => {
183
183
 
184
184
  describe('Controlled vs uncontrolled', () => {
185
185
  test('works as controlled component', () => {
186
- const { container, rerender } = render(
187
- <PktDatepicker id={datePickerId} label={label} value="2024-06-15" />,
188
- )
186
+ const { container, rerender } = render(<PktDatepicker id={datePickerId} label={label} value="2024-06-15" />)
189
187
 
190
188
  let input = container.querySelector('input[type="date"]') as HTMLInputElement
191
189
  expect(input.value).toBe('2024-06-15')
@@ -212,9 +210,7 @@ describe('PktDatepicker', () => {
212
210
  expect(inputs[0].value).toBe('2024-06-15')
213
211
  expect(inputs[1].value).toBe('2024-06-25')
214
212
 
215
- rerender(
216
- <PktDatepicker id={datePickerId} label={label} range value={['2024-07-01', '2024-07-31']} />,
217
- )
213
+ rerender(<PktDatepicker id={datePickerId} label={label} range value={['2024-07-01', '2024-07-31']} />)
218
214
 
219
215
  const updatedInputs = container.querySelectorAll('input[type="date"]') as NodeListOf<HTMLInputElement>
220
216
  expect(updatedInputs[0].value).toBe('2024-07-01')
@@ -230,12 +226,7 @@ describe('PktDatepicker', () => {
230
226
  expect(tags.length).toBe(1)
231
227
 
232
228
  rerender(
233
- <PktDatepicker
234
- id={datePickerId}
235
- label={label}
236
- multiple
237
- value={['2024-06-15', '2024-06-20', '2024-06-25']}
238
- />,
229
+ <PktDatepicker id={datePickerId} label={label} multiple value={['2024-06-15', '2024-06-20', '2024-06-25']} />,
239
230
  )
240
231
 
241
232
  tags = container.querySelectorAll('.pkt-date-tags .pkt-tag')
@@ -243,9 +234,7 @@ describe('PktDatepicker', () => {
243
234
  })
244
235
 
245
236
  test('calendarOpen prop controls calendar state', () => {
246
- const { container, rerender } = render(
247
- <PktDatepicker id={datePickerId} label={label} calendarOpen={false} />,
248
- )
237
+ const { container, rerender } = render(<PktDatepicker id={datePickerId} label={label} calendarOpen={false} />)
249
238
 
250
239
  let popup = container.querySelector('.pkt-calendar-popup')
251
240
  expect(popup).toHaveAttribute('hidden')
@@ -270,13 +259,47 @@ describe('PktDatepicker', () => {
270
259
  expect(formInput.value).toBe('2024-06-15')
271
260
  })
272
261
 
273
- test('form input has no name attribute when name is not set', () => {
262
+ test('form input uses the id as name when name is not set', () => {
274
263
  const { container } = createDatepickerTest({
275
264
  value: '2024-06-15',
276
265
  })
277
266
 
278
267
  const formInput = container.querySelector('input[aria-hidden="true"]') as HTMLInputElement
279
- expect(formInput).not.toHaveAttribute('name')
268
+ expect(formInput).toHaveAttribute('name', datePickerId)
269
+ })
270
+
271
+ test.each([
272
+ ['single', {}, '2024-06-15', '2024-06-15'],
273
+ ['range', { range: true }, '2024-06-15,2024-06-25', '2024-06-15,2024-06-25'],
274
+ ['multiple', { multiple: true }, '2024-06-15,2024-06-20', '2024-06-15,2024-06-20'],
275
+ ])('submits one entry in %s mode', (_mode, props, value, submitted) => {
276
+ const { container } = render(
277
+ <form>
278
+ <PktDatepicker id={datePickerId} label={label} name="dato" defaultValue={value} {...props} />
279
+ </form>,
280
+ )
281
+
282
+ const form = container.querySelector('form') as HTMLFormElement
283
+ expect([...new FormData(form).entries()]).toEqual([['dato', submitted]])
284
+ })
285
+
286
+ test('submits through the form attribute when placed outside the form', () => {
287
+ const { container } = render(
288
+ <>
289
+ <form id="external" />
290
+ <PktDatepicker
291
+ id={datePickerId}
292
+ label={label}
293
+ name="dato"
294
+ form="external"
295
+ range
296
+ defaultValue="2024-06-15,2024-06-25"
297
+ />
298
+ </>,
299
+ )
300
+
301
+ const form = container.querySelector('form') as HTMLFormElement
302
+ expect([...new FormData(form).entries()]).toEqual([['dato', '2024-06-15,2024-06-25']])
280
303
  })
281
304
 
282
305
  test('form input has comma-separated value for multiple', () => {