@stacksjs/components 0.2.928 → 0.2.930

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.
@@ -44,7 +44,7 @@ export const disabledIsoList = disabledDates.map(d => new Date(d).toISOString())
44
44
 
45
45
  <script client>
46
46
  const emit = defineEmits()
47
- const locale = {{ locale }}
47
+ const locale = useReactiveProp('locale', {{ locale }})
48
48
  const firstDayOfWeek = {{ firstDayOfWeek }}
49
49
  const highlightToday = {{ highlightToday }}
50
50
  /*
@@ -65,9 +65,19 @@ const minIso = {{ minIsoValue }}
65
65
  const maxIso = {{ maxIsoValue }}
66
66
  const minDate = minIso ? new Date(minIso) : null
67
67
  const maxDate = maxIso ? new Date(maxIso) : null
68
+ const liveMin = useReactiveProp('minDate', minDate, { parse: value => value })
69
+ const liveMax = useReactiveProp('maxDate', maxDate, { parse: value => value })
70
+ function dateOrNull(value) {
71
+ if (value == null || value === '' || value === false) return null
72
+ const date = new Date(value)
73
+ return Number.isFinite(date.getTime()) ? date : null
74
+ }
75
+ const minimumDate = derived(() => dateOrNull(liveMin()))
76
+ const maximumDate = derived(() => dateOrNull(liveMax()))
68
77
  const disabledDates = ({{ disabledIsoList }}).map(s => new Date(s))
69
78
  const initialValueIso = {{ initialValueIso }}
70
79
  const initialValue = initialValueIso ? new Date(initialValueIso) : null
80
+ const liveValue = useReactiveProp('value', initialValueIso, { parse: value => value })
71
81
 
72
82
  const mode = {{ mode }}
73
83
  const startIso = {{ initialStartIso }}
@@ -80,6 +90,12 @@ const currentMonth = state(new Date(initialStart || initialValue || today))
80
90
  const selectedDate = state(initialValue)
81
91
  const rangeStart = state(initialStart)
82
92
  const rangeEnd = state(initialEnd)
93
+ effect(() => {
94
+ const value = dateOrNull(liveValue())
95
+ if (mode !== 'single') return
96
+ selectedDate.set(value)
97
+ if (value) currentMonth.set(new Date(value))
98
+ })
83
99
  /*
84
100
  * The day under the cursor while a range is half-made, so the span previews
85
101
  * before the second click. Without it a range picker gives no feedback between
@@ -95,8 +111,10 @@ function isSameDay(d1, d2) {
95
111
  function isToday(d) { return isSameDay(d, today) }
96
112
 
97
113
  function isDisabled(d) {
98
- if (minDate && d < minDate) return true
99
- if (maxDate && d > maxDate) return true
114
+ const min = minimumDate()
115
+ const max = maximumDate()
116
+ if (min && d < min) return true
117
+ if (max && d > max) return true
100
118
  return disabledDates.some(x => isSameDay(x, d))
101
119
  }
102
120
 
@@ -105,19 +123,19 @@ function getFirstDayOfMonth(d) { return new Date(d.getFullYear(), d.getMonth(),
105
123
 
106
124
  const monthYearLabel = derived(() => {
107
125
  const m = currentMonth()
108
- return `${m.toLocaleDateString(locale, { month: 'long' })} ${m.getFullYear()}`
126
+ return `${m.toLocaleDateString(locale(), { month: 'long' })} ${m.getFullYear()}`
109
127
  })
110
128
 
111
- const dayNames = (() => {
129
+ const dayNames = derived(() => {
112
130
  const days = []
113
131
  const baseDate = new Date(2024, 0, firstDayOfWeek)
114
132
  for (let i = 0; i < 7; i++) {
115
133
  const day = new Date(baseDate)
116
134
  day.setDate(baseDate.getDate() + i)
117
- days.push(day.toLocaleDateString(locale, { weekday: 'short' }))
135
+ days.push(day.toLocaleDateString(locale(), { weekday: 'short' }))
118
136
  }
119
137
  return days
120
- })()
138
+ })
121
139
 
122
140
  const calendarDays = derived(() => {
123
141
  const month = currentMonth()
@@ -299,8 +317,8 @@ defineExpose({ selectedDate, currentMonth, selectDate, rangeStart, rangeEnd })
299
317
  :class="dayClasses(day)"
300
318
  @click="selectDate(day.date)"
301
319
  @mouseenter="onDayHover(day.date)"
302
- :aria-label="day.date.toLocaleDateString(locale)"
303
- :aria-selected="isRangeEnd(day.date)"
320
+ :aria-label="day.date.toLocaleDateString(locale())"
321
+ :aria-selected="mode === 'range' ? isRangeEnd(day.date) : isSameDay(day.date, selectedDate())"
304
322
  :disabled="isDisabled(day.date)"
305
323
  x-text="day.date.getDate()"
306
324
  ></button>
@@ -0,0 +1,233 @@
1
+ <script server>
2
+ export const value = $props.value || null
3
+ export const timeZone = $props.timeZone || 'UTC'
4
+ export const locale = $props.locale || 'en-US'
5
+ export const minDate = $props.minDate || null
6
+ export const maxDate = $props.maxDate || null
7
+ export const suggestedTime = $props.suggestedTime || null
8
+ export const disabled = $bool($props.disabled)
9
+ export const clearable = $bool($props.clearable, true)
10
+ const step = $num($props.minuteStep, 1)
11
+ export const minuteStep = Number.isInteger(step) && step > 0 && 60 % step === 0 ? step : 1
12
+ export const placeholder = $props.placeholder || 'Choose date and time'
13
+ export const label = $props.label || 'Schedule'
14
+ export const instanceId = $uid
15
+ export const rootClasses = `relative inline-block ${$props.className || ''}`.trim()
16
+ export const triggerClasses = 'inline-flex items-center gap-2 rounded-control bg-field px-3 py-2 text-sm text-fg ring-1 ring-inset ring-line-strong hover:bg-field-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:cursor-not-allowed disabled:opacity-50'
17
+ export const panelClasses = 'absolute left-0 z-30 w-96 max-w-[calc(100vw-2rem)] max-h-[calc(100dvh-2rem)] overflow-y-auto rounded-panel bg-panel p-4 shadow-lg ring-1 ring-line'
18
+ </script>
19
+
20
+ <script client>
21
+ import { measureTooltipPosition, trackBrowserPopup, trackNativePopup } from '../../utils/tooltip-position'
22
+ import { dateTimeFields, dateTimeInstant, dateTimePreset, dateTimeToIso, formatDateTime, validTimeZone } from './date-time'
23
+ const emit = defineEmits()
24
+ const instanceId = {{ instanceId }}
25
+ const label = useReactiveProp('label', {{ label }})
26
+ const rootRef = useRef('dateTimeRoot')
27
+ const triggerRef = useRef('dateTimeTrigger')
28
+ const value = useReactiveProp('value', {{ value }}, { parse: value => value })
29
+ const timeZone = useReactiveProp('timeZone', {{ timeZone }})
30
+ const locale = useReactiveProp('locale', {{ locale }})
31
+ const minimum = useReactiveProp('minDate', {{ minDate }}, { parse: value => value })
32
+ const maximum = useReactiveProp('maxDate', {{ maxDate }}, { parse: value => value })
33
+ const suggested = useReactiveProp('suggestedTime', {{ suggestedTime }}, { parse: value => value })
34
+ const disabled = useReactiveProp('disabled', {{ disabled }})
35
+ const clearable = useReactiveProp('clearable', {{ clearable }})
36
+ const placeholder = useReactiveProp('placeholder', {{ placeholder }})
37
+ const minuteStep = useReactiveProp('minuteStep', {{ minuteStep }}, { parse: value => {
38
+ const n = Number(value)
39
+ return Number.isInteger(n) && n > 0 && 60 % n === 0 ? n : 1
40
+ } })
41
+ const isOpen = state(false)
42
+ const mounted = state(false)
43
+ const tree = window.stx._host
44
+ const nativePicker = !!tree.isNative
45
+ let stopPositioning = null
46
+ const draftDate = state('')
47
+ const draftTime = state('09:00')
48
+ const original = state(null)
49
+ const committed = state(null)
50
+
51
+ function loadDraft(instant, zone) {
52
+ const iso = dateTimeInstant(instant)
53
+ const fields = dateTimeFields(iso || new Date(), zone)
54
+ original.set(iso)
55
+ draftDate.set(fields ? fields.date : '')
56
+ draftTime.set(iso && fields ? fields.time : '09:00')
57
+ }
58
+ effect(() => { committed.set(dateTimeInstant(value())) })
59
+ effect(() => { loadDraft(committed(), timeZone()) })
60
+ effect(() => { if (disabled()) close(false) })
61
+
62
+ const suggestion = derived(() => dateTimeInstant(suggested()))
63
+ const displayValue = derived(() => formatDateTime(committed(), timeZone(), locale()) || committed() || placeholder())
64
+ const panelId = 'date-time-panel-' + instanceId
65
+ const timeId = 'date-time-clock-' + instanceId
66
+ const zoneId = 'date-time-zone-' + instanceId
67
+ const errorId = 'date-time-error-' + instanceId
68
+ const titleId = 'date-time-title-' + instanceId
69
+
70
+ // Calendar's Date represents a civil day in the browser; its midnight is not
71
+ // the scheduled instant. Only the timezone converter creates that instant.
72
+ function calendarDate(instant) {
73
+ const fields = dateTimeFields(instant, timeZone())
74
+ if (!fields) return null
75
+ const parts = fields.date.split('-').map(Number)
76
+ return new Date(parts[0], parts[1] - 1, parts[2])
77
+ }
78
+ const calendarValue = derived(() => {
79
+ const parts = draftDate().split('-').map(Number)
80
+ return parts.length === 3 && parts.every(Number.isFinite) ? new Date(parts[0], parts[1] - 1, parts[2]) : null
81
+ })
82
+ const calendarMin = derived(() => calendarDate(minimum()))
83
+ const calendarMax = derived(() => calendarDate(maximum()))
84
+ const candidate = derived(() => {
85
+ const date = draftDate()
86
+ const time = draftTime()
87
+ const zone = timeZone()
88
+ // Reopening an existing folded minute must keep the original occurrence,
89
+ // including seconds, until the user actually changes the civil fields.
90
+ const fields = dateTimeFields(original(), zone)
91
+ if (fields && fields.date === date && fields.time === time) return original()
92
+ return dateTimeToIso(date, time, zone)
93
+ })
94
+ function boundsError(iso) {
95
+ if (!iso) return 'Choose a valid date and time. This clock time may not exist in the selected timezone.'
96
+ const minValue = minimum()
97
+ const maxValue = maximum()
98
+ const min = dateTimeInstant(minValue)
99
+ const max = dateTimeInstant(maxValue)
100
+ if (minValue && !min) return 'The earliest allowed time is invalid.'
101
+ if (maxValue && !max) return 'The latest allowed time is invalid.'
102
+ if (min && Date.parse(iso) < Date.parse(min)) return 'Choose a time at or after the earliest allowed time.'
103
+ if (max && Date.parse(iso) > Date.parse(max)) return 'Choose a time at or before the latest allowed time.'
104
+ return ''
105
+ }
106
+ const error = derived(() => {
107
+ if (!validTimeZone(timeZone())) return 'Choose a valid workspace timezone.'
108
+ if (Number(draftTime().slice(3, 5)) % minuteStep() !== 0) return 'Choose a time matching the minute increment.'
109
+ return boundsError(candidate())
110
+ })
111
+
112
+ function focusElement(element) {
113
+ if (!element || element.isConnected === false || !element.focus || (nativePicker && !window.craft?.capabilities?.viewFocus)) return
114
+ try {
115
+ const result = element.focus()
116
+ if (result && result.catch) result.catch(error => console.warn('[stx:date-time-picker] ' + String(error)))
117
+ }
118
+ catch (error) { console.warn('[stx:date-time-picker] ' + String(error)) }
119
+ }
120
+
121
+ function close(restoreFocus = true) {
122
+ if (!isOpen()) return
123
+ isOpen.set(false)
124
+ emit('close')
125
+ if (restoreFocus) focusElement(triggerRef.value)
126
+ }
127
+ function open() {
128
+ if (disabled() || isOpen()) return
129
+ loadDraft(committed(), timeZone())
130
+ isOpen.set(true)
131
+ emit('open')
132
+ nextTick(() => {
133
+ const root = rootRef.value
134
+ const input = root && root.querySelector('[data-date-time-clock]')
135
+ if (isOpen()) focusElement(input)
136
+ })
137
+ }
138
+ function toggle() { isOpen() ? close() : open() }
139
+ function commit(iso, preset) {
140
+ if (disabled() || !validTimeZone(timeZone()) || boundsError(iso)) return
141
+ committed.set(iso)
142
+ original.set(iso)
143
+ const fields = dateTimeFields(iso, timeZone())
144
+ draftDate.set(fields.date)
145
+ draftTime.set(fields.time)
146
+ emit('change', { value: iso, timeZone: timeZone(), preset })
147
+ close()
148
+ }
149
+ function apply() { if (!error()) commit(candidate(), null) }
150
+ function presetDisabled(preset) { return disabled() || !validTimeZone(timeZone()) || !!boundsError(dateTimePreset(preset, timeZone(), new Date(), suggested())) }
151
+ function choosePreset(preset) { commit(dateTimePreset(preset, timeZone(), new Date(), suggested()), preset) }
152
+ function clear() {
153
+ if (disabled()) return
154
+ committed.set(null)
155
+ original.set(null)
156
+ emit('change', { value: null, timeZone: timeZone(), preset: null })
157
+ close()
158
+ }
159
+ function onCalendarChange(event) {
160
+ const date = event && event.detail ? event.detail : event
161
+ if (!date || !Number.isFinite(date.getTime())) return
162
+ draftDate.set(date.getFullYear() + '-' + String(date.getMonth() + 1).padStart(2, '0') + '-' + String(date.getDate()).padStart(2, '0'))
163
+ }
164
+
165
+ onMount(() => {
166
+ mounted.set(true)
167
+ useEventListener('click', event => {
168
+ const root = rootRef.value
169
+ if (isOpen() && root && !root.contains(event.target) && window.stx.overlays.isTop(instanceId)) close(false)
170
+ }, { target: document, capture: true })
171
+ })
172
+ effect(() => {
173
+ if (!mounted()) return
174
+ if (stopPositioning) { stopPositioning(); stopPositioning = null }
175
+ if (!isOpen()) { window.stx.overlays.close(instanceId); return }
176
+ const root = rootRef.value
177
+ const panel = root && root.querySelector('[data-date-time-panel]')
178
+ const trigger = triggerRef.value
179
+ try {
180
+ if (nativePicker && (!window.craft?.capabilities?.viewMeasure || !window.craft?.capabilities?.viewNonModalPresentation))
181
+ throw new Error('Native DateTimePicker requires viewMeasure and viewNonModalPresentation')
182
+ window.stx.overlays.open(instanceId, { modal: false, root: nativePicker ? panel : null, panel: () => root, onEscape: () => close(), onBackdrop: () => close(false) })
183
+ if (nativePicker) stopPositioning = trackNativePopup(trigger, panel, 'bottom', style => tree.setStyle(panel, style))
184
+ else {
185
+ const place = () => {
186
+ measureTooltipPosition(trigger, panel, 'bottom').then(point => {
187
+ if (!point || !isOpen() || !panel.isConnected) return
188
+ panel.style.left = point.left + 'px'
189
+ panel.style.top = point.top + 'px'
190
+ }).catch(error => console.warn('[stx:date-time-picker] ' + String(error)))
191
+ }
192
+ place()
193
+ stopPositioning = trackBrowserPopup(trigger, panel, place)
194
+ }
195
+ }
196
+ catch (error) {
197
+ window.stx.overlays.close(instanceId)
198
+ console.warn('[stx:date-time-picker] ' + String(error))
199
+ close(false)
200
+ }
201
+ })
202
+ onDestroy(() => {
203
+ mounted.set(false)
204
+ isOpen.set(false)
205
+ if (stopPositioning) stopPositioning()
206
+ window.stx.overlays.close(instanceId)
207
+ })
208
+ defineExpose({ open, close })
209
+ </script>
210
+
211
+ <div class="{{ rootClasses }}" x-ref="dateTimeRoot" data-date-time-picker>
212
+ <button type="button" class="{{ triggerClasses }}" x-ref="dateTimeTrigger" data-date-time-trigger :disabled="disabled" aria-haspopup="dialog" :aria-expanded="isOpen() ? 'true' : 'false'" :aria-controls="panelId" :aria-label="label" @click="toggle()">
213
+ <span x-text="displayValue"></span>
214
+ </button>
215
+ <div :if="isOpen" class="{{ panelClasses }}" role="dialog" data-native="Modal" visible="false" :id="panelId" :aria-labelledby="titleId" :aria-describedby="zoneId" data-date-time-panel>
216
+ <h3 class="mb-2 text-sm font-semibold text-fg" :id="titleId" x-text="label">{{ label }}</h3>
217
+ <p class="mb-3 text-xs text-fg-muted" :id="zoneId">Timezone: <span x-text="timeZone"></span></p>
218
+ <div class="mb-3 flex flex-wrap gap-2">
219
+ <button type="button" class="rounded-control bg-surface px-2 py-1 text-xs text-fg hover:bg-surface-hover" data-date-time-preset="hour" :disabled="presetDisabled('hour')" @click="choosePreset('hour')">In an hour</button>
220
+ <button type="button" class="rounded-control bg-surface px-2 py-1 text-xs text-fg hover:bg-surface-hover" data-date-time-preset="tomorrow" :disabled="presetDisabled('tomorrow')" @click="choosePreset('tomorrow')">Tomorrow morning</button>
221
+ <button :if="suggestion" type="button" class="rounded-control bg-surface px-2 py-1 text-xs text-fg hover:bg-surface-hover" data-date-time-preset="suggested" :disabled="presetDisabled('suggested')" @click="choosePreset('suggested')">Next best time</button>
222
+ </div>
223
+ <Calendar :value="calendarValue()" :minDate="calendarMin()" :maxDate="calendarMax()" :locale="locale" @change.stop="onCalendarChange" className="max-w-none p-0 shadow-none" />
224
+ <label class="mt-3 block text-xs font-medium text-fg" :for="timeId">Time</label>
225
+ <input type="time" class="mt-1 w-full rounded-control bg-field px-3 py-2 text-sm text-fg ring-1 ring-line-strong focus:ring-2 focus:ring-accent" :id="timeId" data-date-time-clock x-model="draftTime" :step="minuteStep() * 60" :aria-invalid="error() ? 'true' : null" :aria-describedby="error() ? errorId : zoneId" @keydown.enter.prevent="apply()" />
226
+ <p class="mt-2 text-xs text-danger-fg" :id="errorId" role="status" aria-live="polite" x-text="error"></p>
227
+ <div class="mt-3 flex justify-end gap-2">
228
+ <button :if="clearable" type="button" class="mr-auto rounded-control px-3 py-2 text-sm text-fg-muted hover:bg-surface-hover" data-date-time-clear @click="clear()">Clear</button>
229
+ <button type="button" class="rounded-control px-3 py-2 text-sm text-fg hover:bg-surface-hover" data-date-time-cancel @click="close()">Cancel</button>
230
+ <button type="button" class="rounded-control bg-accent-solid px-3 py-2 text-sm text-accent-ink disabled:opacity-50" :disabled="!!error()" data-date-time-apply @click="apply()">Apply</button>
231
+ </div>
232
+ </div>
233
+ </div>
@@ -51,6 +51,7 @@ export const wash = SETTINGS_NATIVE.rowWash
51
51
  */
52
52
  import { SettingsWindowTree } from './native'
53
53
  import { SettingsWindowView } from './view'
54
+ import { settingsStorageName } from './core'
54
55
  import { registerComponentApi } from '../../utils/component-api'
55
56
 
56
57
  const emit = defineEmits(['pane', 'search', 'navigate'])
@@ -76,10 +77,19 @@ const searchFocus = state(false)
76
77
  let stopCommands = null
77
78
  let unregister = null
78
79
 
79
- /** The app's own storage on a native host, which stx serves as localStorage. */
80
- const nativeStorage = {
81
- get: name => (typeof localStorage === 'undefined' ? null : localStorage.getItem(name)),
82
- set: (name, value) => { if (typeof localStorage !== 'undefined') localStorage.setItem(name, value) },
80
+ /*
81
+ * The last open pane, kept under `stx:settings:<key>`: local storage in a
82
+ * browser, the app's own storage on a native host. One signal for both, and
83
+ * no storage at all without a key. Made on mount, where the window has always
84
+ * read it, and stored as the bare pane id it has always been (no JSON quotes),
85
+ * so a pane remembered by an earlier version still opens.
86
+ */
87
+ const storageKey = {{ storageKey }}
88
+ const paneAsIs = { read: value => value, write: value => value }
89
+ let rememberedPane = null
90
+ const paneStorage = {
91
+ get: () => (rememberedPane ? rememberedPane() || null : null),
92
+ set: (_name, value) => { if (rememberedPane) rememberedPane.set(value) },
83
93
  }
84
94
 
85
95
  function onSearchInput(event) {
@@ -106,7 +116,7 @@ function focusSearch() {
106
116
  if (!settings) return
107
117
  if (!native) { settings.focusSearch(); return }
108
118
  searchFocus.set(false)
109
- setTimeout(() => searchFocus.set(true), 0)
119
+ nextTick(() => searchFocus.set(true))
110
120
  }
111
121
 
112
122
  const callbacks = {
@@ -121,13 +131,14 @@ const callbacks = {
121
131
  onMount(() => {
122
132
  const root = rootRef()
123
133
  if (!root) return
134
+ if (storageKey) rememberedPane = useLocalStorage(settingsStorageName(storageKey), '', { serializer: paneAsIs })
124
135
 
125
136
  if (native) {
126
137
  const craftHost = typeof craft === 'undefined' ? null : craft
127
138
  settings = new SettingsWindowTree(window.stx._host, root, {
128
139
  pane: asText(openPane()),
129
- storageKey: {{ storageKey }},
130
- storage: nativeStorage,
140
+ storageKey,
141
+ storage: paneStorage,
131
142
  wash: () => (craftHost && craftHost.appearance && craftHost.appearance.colorScheme() === 'dark' ? wash.dark : wash.light),
132
143
  }, {
133
144
  ...callbacks,
@@ -155,7 +166,8 @@ onMount(() => {
155
166
  else {
156
167
  settings = new SettingsWindowView(root, {
157
168
  pane: asText(openPane()),
158
- storageKey: {{ storageKey }},
169
+ storageKey,
170
+ storage: paneStorage,
159
171
  globalKeys: {{ globalKeys }},
160
172
  }, callbacks)
161
173
  }
@@ -0,0 +1,117 @@
1
+ // src/ui/date-time-picker/date-time.ts
2
+ var formatters = new Map;
3
+ function formatter(timeZone) {
4
+ let value = formatters.get(timeZone);
5
+ if (!value) {
6
+ value = new Intl.DateTimeFormat("en-CA", { timeZone, calendar: "iso8601", numberingSystem: "latn", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23" });
7
+ if (formatters.size >= 64)
8
+ formatters.clear();
9
+ formatters.set(timeZone, value);
10
+ }
11
+ return value;
12
+ }
13
+ function validTimeZone(timeZone) {
14
+ if (typeof timeZone !== "string" || !timeZone)
15
+ return false;
16
+ try {
17
+ formatter(timeZone);
18
+ return true;
19
+ } catch {
20
+ return false;
21
+ }
22
+ }
23
+ function dateTimeInstant(value) {
24
+ if (value == null || value === "")
25
+ return null;
26
+ if (typeof value !== "string" && !(value instanceof Date))
27
+ return null;
28
+ if (typeof value === "string") {
29
+ const iso = /^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/i.exec(value);
30
+ if (!iso || civilTimestamp(iso[1], iso[2]) == null)
31
+ return null;
32
+ }
33
+ const date = new Date(value instanceof Date ? value.getTime() : value);
34
+ return Number.isFinite(date.getTime()) ? date.toISOString() : null;
35
+ }
36
+ function dateTimeFields(value, timeZone) {
37
+ const instant = dateTimeInstant(value);
38
+ if (!instant)
39
+ return null;
40
+ try {
41
+ const parts = Object.fromEntries(formatter(timeZone).formatToParts(new Date(instant)).map((part) => [part.type, part.value]));
42
+ return { date: `${parts.year.padStart(4, "0")}-${parts.month}-${parts.day}`, time: `${parts.hour}:${parts.minute}` };
43
+ } catch {
44
+ return null;
45
+ }
46
+ }
47
+ function civilTimestamp(date, time) {
48
+ const day = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date);
49
+ const clock = /^(\d{2}):(\d{2})$/.exec(time);
50
+ if (!day || !clock)
51
+ return null;
52
+ const [year, month, number, hour, minute] = [+day[1], +day[2], +day[3], +clock[1], +clock[2]];
53
+ if (year < 100 || month < 1 || month > 12 || number < 1 || hour > 23 || minute > 59)
54
+ return null;
55
+ const timestamp = Date.UTC(year, month - 1, number, hour, minute);
56
+ const actual = new Date(timestamp);
57
+ return actual.getUTCFullYear() === year && actual.getUTCMonth() === month - 1 && actual.getUTCDate() === number ? timestamp : null;
58
+ }
59
+ function dateTimeToIso(date, time, timeZone, disambiguation = "earlier") {
60
+ const guess = civilTimestamp(date, time);
61
+ if (guess == null || !validTimeZone(timeZone))
62
+ return null;
63
+ const offsets = new Set;
64
+ for (const delta of [-2, -1, 0, 1, 2]) {
65
+ const timestamp = guess + delta * 86400000;
66
+ const fields = dateTimeFields(new Date(timestamp), timeZone);
67
+ if (!fields)
68
+ continue;
69
+ const civil = civilTimestamp(fields.date, fields.time);
70
+ if (civil != null)
71
+ offsets.add(civil - timestamp);
72
+ }
73
+ const candidates = [];
74
+ for (const offset of offsets) {
75
+ const candidate = guess - offset;
76
+ const fields = dateTimeFields(new Date(candidate), timeZone);
77
+ if (fields?.date === date && fields.time === time)
78
+ candidates.push(candidate);
79
+ }
80
+ if (!candidates.length)
81
+ return null;
82
+ return new Date(disambiguation === "later" ? Math.max(...candidates) : Math.min(...candidates)).toISOString();
83
+ }
84
+ function formatDateTime(value, timeZone, locale = "en-US") {
85
+ const instant = dateTimeInstant(value);
86
+ if (!instant)
87
+ return null;
88
+ try {
89
+ return new Intl.DateTimeFormat(locale, { timeZone, year: "numeric", month: "short", day: "numeric", hour: "numeric", minute: "2-digit", timeZoneName: "short" }).format(new Date(instant));
90
+ } catch {
91
+ return null;
92
+ }
93
+ }
94
+ function dateTimePreset(preset, timeZone, now = new Date, suggested = null) {
95
+ if (!validTimeZone(timeZone) || !Number.isFinite(now.getTime()))
96
+ return null;
97
+ if (preset === "hour")
98
+ return new Date(now.getTime() + 3600000).toISOString();
99
+ if (preset === "suggested")
100
+ return dateTimeInstant(suggested);
101
+ const fields = dateTimeFields(now, timeZone);
102
+ if (!fields)
103
+ return null;
104
+ const midnight = civilTimestamp(fields.date, "00:00");
105
+ if (midnight == null)
106
+ return null;
107
+ const tomorrow = new Date(midnight + 86400000).toISOString().slice(0, 10);
108
+ return dateTimeToIso(tomorrow, "09:00", timeZone);
109
+ }
110
+ export {
111
+ dateTimeFields,
112
+ dateTimeInstant,
113
+ dateTimePreset,
114
+ dateTimeToIso,
115
+ formatDateTime,
116
+ validTimeZone
117
+ };
package/dist/index.d.ts CHANGED
@@ -50,6 +50,7 @@ export * from './ui/breadcrumb/index';
50
50
  export * from './ui/button/index';
51
51
  export * from './ui/calendar/index';
52
52
  export * from './ui/date-range-picker/index';
53
+ export * from './ui/date-time-picker/index';
53
54
  export * from './ui/empty-state/index';
54
55
  export * from './ui/error-state/index';
55
56
  export * from './ui/theme-toggle/index';