@stacksjs/components 0.2.929 → 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.
@@ -546,6 +546,7 @@ class SettingsWindowView {
546
546
  current = "";
547
547
  query = "";
548
548
  storageKey;
549
+ storage;
549
550
  typed = null;
550
551
  hits = [];
551
552
  highlighted = null;
@@ -566,6 +567,7 @@ class SettingsWindowView {
566
567
  this.root = root;
567
568
  this.callbacks = callbacks;
568
569
  this.storageKey = options.storageKey || "";
570
+ this.storage = options.storage ?? null;
569
571
  if (!root.id)
570
572
  root.id = `settings-${Math.random().toString(36).slice(2, 8)}`;
571
573
  this.list = this.own("[data-settings-list]");
@@ -692,7 +694,8 @@ class SettingsWindowView {
692
694
  if (!this.storageKey)
693
695
  return "";
694
696
  try {
695
- return localStorage.getItem(settingsStorageName(this.storageKey)) || "";
697
+ const name = settingsStorageName(this.storageKey);
698
+ return (this.storage ? this.storage.get(name) : localStorage.getItem(name)) || "";
696
699
  } catch {
697
700
  return "";
698
701
  }
@@ -701,7 +704,11 @@ class SettingsWindowView {
701
704
  if (!this.storageKey || !this.current)
702
705
  return;
703
706
  try {
704
- localStorage.setItem(settingsStorageName(this.storageKey), this.current);
707
+ const name = settingsStorageName(this.storageKey);
708
+ if (this.storage)
709
+ this.storage.set(name, this.current);
710
+ else
711
+ localStorage.setItem(name, this.current);
705
712
  } catch {}
706
713
  }
707
714
  describe() {
@@ -1,8 +1,8 @@
1
1
  export declare interface CalendarProps {
2
- value?: Date
2
+ value?: Date | string | null
3
3
  onChange?: (date: Date) => void
4
- minDate?: Date
5
- maxDate?: Date
4
+ minDate?: Date | string | null
5
+ maxDate?: Date | string | null
6
6
  disabledDates?: Date[]
7
7
  locale?: string
8
8
  firstDayOfWeek?: number
@@ -0,0 +1,22 @@
1
+ import type { DefineComponent } from '@stacksjs/stx';
2
+ declare function close(restoreFocus?: boolean): undefined;
3
+ declare function open(): undefined;
4
+ declare const __dtsx_component__: __DtsxStxComponentType;
5
+ export declare const value: unknown;
6
+ export declare const timeZone: unknown;
7
+ export declare const locale: unknown;
8
+ export declare const minDate: unknown;
9
+ export declare const maxDate: unknown;
10
+ export declare const suggestedTime: unknown;
11
+ export declare const disabled: ReturnType<typeof $bool>;
12
+ export declare const clearable: unknown;
13
+ declare const step: unknown;
14
+ export declare const minuteStep: boolean;
15
+ export declare const placeholder: unknown;
16
+ export declare const label: unknown;
17
+ export declare const instanceId: unknown;
18
+ export declare const rootClasses: unknown;
19
+ export declare 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';
20
+ export declare 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';
21
+ declare type __DtsxStxComponentType = DefineComponent<{ value?: unknown, timeZone?: string, locale?: string, minDate?: unknown, maxDate?: unknown, suggestedTime?: unknown, disabled?: unknown, clearable?: unknown, minuteStep?: unknown, placeholder?: string, label?: string }> & { readonly __stxExposed?: { open: typeof open, close: typeof close } }
22
+ export default __dtsx_component__;
@@ -0,0 +1,18 @@
1
+ export declare function validTimeZone(timeZone: string): boolean;
2
+ export declare function dateTimeInstant(value: DateTimeValue | undefined): string | null;
3
+ /** Workspace civil fields, independent of the browser or server's timezone. */
4
+ export declare function dateTimeFields(value: DateTimeValue, timeZone: string): DateTimeFields | null;
5
+ /**
6
+ * Resolve a civil minute to an instant. Gaps (including skipped days) return
7
+ * null. Folds choose the earlier occurrence unless explicitly asked for later.
8
+ * Probe both sides of the transition, including non-hour offset changes.
9
+ */
10
+ export declare function dateTimeToIso(date: string, time: string, timeZone: string, disambiguation?: 'earlier' | 'later'): string | null;
11
+ export declare function formatDateTime(value: DateTimeValue, timeZone: string, locale?: string): string | null;
12
+ /** Recommendations stay app-owned; the picker only accepts the supplied instant. */
13
+ export declare function dateTimePreset(preset: DateTimePreset, timeZone: string, now?: unknown, suggested?: DateTimeValue): string | null;
14
+ export declare interface DateTimeFields { date: string, time: string }
15
+ export declare interface DateTimeSelection { value: string | null, timeZone: string, preset: DateTimePreset | null }
16
+ /** An instant, displayed and edited in the caller's workspace timezone. */
17
+ export type DateTimeValue = Date | string | null;
18
+ export type DateTimePreset = 'hour' | 'tomorrow' | 'suggested';
@@ -0,0 +1,20 @@
1
+ import type { DateTimeSelection, DateTimeValue } from './date-time';
2
+ export declare interface DateTimePickerProps {
3
+ value?: DateTimeValue
4
+ timeZone?: string
5
+ locale?: string
6
+ minDate?: DateTimeValue
7
+ maxDate?: DateTimeValue
8
+ suggestedTime?: DateTimeValue
9
+ minuteStep?: number
10
+ disabled?: boolean
11
+ clearable?: boolean
12
+ label?: string
13
+ placeholder?: string
14
+ className?: string
15
+ onChange?: (selection: DateTimeSelection) => void
16
+ onOpen?: () => void
17
+ onClose?: () => void
18
+ }
19
+ export { default as DateTimePicker } from './DateTimePicker';
20
+ export * from './date-time';
@@ -1,6 +1,8 @@
1
+ import type { SettingsTreeStorage } from './native';
1
2
  export declare interface SettingsWindowOptions {
2
3
  pane?: string
3
4
  storageKey?: string
5
+ storage?: SettingsTreeStorage
4
6
  globalKeys?: boolean
5
7
  }
6
8
  export declare interface SettingsPaneDetail {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@stacksjs/components",
3
3
  "type": "module",
4
- "version": "0.2.929",
4
+ "version": "0.2.930",
5
5
  "description": "A modern component library built with STX, featuring headwind utility classes and TypeScript syntax highlighting.",
6
6
  "author": "Chris Breuer <chris@stacksjs.org>",
7
7
  "license": "MIT",
@@ -47,6 +47,11 @@
47
47
  "bun": "./stx-plugin.ts",
48
48
  "import": "./stx-plugin.ts"
49
49
  },
50
+ "./date-time-picker": {
51
+ "types": "./dist/ui/date-time-picker/date-time.d.ts",
52
+ "bun": "./dist/date-time-picker/date-time.js",
53
+ "import": "./dist/date-time-picker/date-time.js"
54
+ },
50
55
  "./render-surface": {
51
56
  "types": "./dist/ui/render-surface/render-surface.d.ts",
52
57
  "bun": "./dist/render-surface/render-surface.js",
@@ -139,8 +144,8 @@
139
144
  "dependencies": {
140
145
  "@iconify-json/f7": "^1.2.2",
141
146
  "@stacksjs/ts-css": "^0.3.11",
142
- "@stacksjs/stx": "0.2.929",
143
- "bun-plugin-stx": "0.2.929",
147
+ "@stacksjs/stx": "0.2.930",
148
+ "bun-plugin-stx": "0.2.930",
144
149
  "ts-syntax-highlighter": "^0.2.20",
145
150
  "ts-video-player": "^0.1.11"
146
151
  },
package/src/index.ts CHANGED
@@ -23,6 +23,7 @@ export * from './ui/breadcrumb'
23
23
  export * from './ui/button'
24
24
  export * from './ui/calendar'
25
25
  export * from './ui/date-range-picker'
26
+ export * from './ui/date-time-picker'
26
27
  export * from './ui/empty-state'
27
28
  export * from './ui/error-state'
28
29
  export * from './ui/theme-toggle'
@@ -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>
@@ -1,10 +1,10 @@
1
1
  export { default as Calendar } from './Calendar.stx'
2
2
 
3
3
  export interface CalendarProps {
4
- value?: Date
4
+ value?: Date | string | null
5
5
  onChange?: (date: Date) => void
6
- minDate?: Date
7
- maxDate?: Date
6
+ minDate?: Date | string | null
7
+ maxDate?: Date | string | null
8
8
  disabledDates?: Date[]
9
9
  locale?: string
10
10
  firstDayOfWeek?: number // 0 = Sunday, 1 = Monday, etc.
@@ -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>
@@ -0,0 +1,103 @@
1
+ /** An instant, displayed and edited in the caller's workspace timezone. */
2
+ export type DateTimeValue = Date | string | null
3
+ export type DateTimePreset = 'hour' | 'tomorrow' | 'suggested'
4
+ export interface DateTimeFields { date: string, time: string }
5
+ export interface DateTimeSelection { value: string | null, timeZone: string, preset: DateTimePreset | null }
6
+
7
+ const formatters = new Map<string, Intl.DateTimeFormat>()
8
+ function formatter(timeZone: string): Intl.DateTimeFormat {
9
+ let value = formatters.get(timeZone)
10
+ if (!value) {
11
+ 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' })
12
+ if (formatters.size >= 64) formatters.clear()
13
+ formatters.set(timeZone, value)
14
+ }
15
+ return value
16
+ }
17
+
18
+ export function validTimeZone(timeZone: string): boolean {
19
+ if (typeof timeZone !== 'string' || !timeZone) return false
20
+ try { formatter(timeZone); return true }
21
+ catch { return false }
22
+ }
23
+
24
+ export function dateTimeInstant(value: DateTimeValue | undefined): string | null {
25
+ if (value == null || value === '') return null
26
+ if (typeof value !== 'string' && !(value instanceof Date)) return null
27
+ if (typeof value === 'string') {
28
+ const iso = /^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/i.exec(value)
29
+ if (!iso || civilTimestamp(iso[1], iso[2]) == null) return null
30
+ }
31
+ const date = new Date(value instanceof Date ? value.getTime() : value)
32
+ return Number.isFinite(date.getTime()) ? date.toISOString() : null
33
+ }
34
+
35
+ /** Workspace civil fields, independent of the browser or server's timezone. */
36
+ export function dateTimeFields(value: DateTimeValue, timeZone: string): DateTimeFields | null {
37
+ const instant = dateTimeInstant(value)
38
+ if (!instant) return null
39
+ try {
40
+ const parts = Object.fromEntries(formatter(timeZone).formatToParts(new Date(instant)).map(part => [part.type, part.value]))
41
+ return { date: `${parts.year.padStart(4, '0')}-${parts.month}-${parts.day}`, time: `${parts.hour}:${parts.minute}` }
42
+ }
43
+ catch { return null }
44
+ }
45
+
46
+ function civilTimestamp(date: string, time: string): number | null {
47
+ const day = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date)
48
+ const clock = /^(\d{2}):(\d{2})$/.exec(time)
49
+ if (!day || !clock) return null
50
+ const [year, month, number, hour, minute] = [+day[1], +day[2], +day[3], +clock[1], +clock[2]]
51
+ if (year < 100 || month < 1 || month > 12 || number < 1 || hour > 23 || minute > 59) return null
52
+ const timestamp = Date.UTC(year, month - 1, number, hour, minute)
53
+ const actual = new Date(timestamp)
54
+ return actual.getUTCFullYear() === year && actual.getUTCMonth() === month - 1 && actual.getUTCDate() === number ? timestamp : null
55
+ }
56
+
57
+ /**
58
+ * Resolve a civil minute to an instant. Gaps (including skipped days) return
59
+ * null. Folds choose the earlier occurrence unless explicitly asked for later.
60
+ * Probe both sides of the transition, including non-hour offset changes.
61
+ */
62
+ export function dateTimeToIso(date: string, time: string, timeZone: string, disambiguation: 'earlier' | 'later' = 'earlier'): string | null {
63
+ const guess = civilTimestamp(date, time)
64
+ if (guess == null || !validTimeZone(timeZone)) return null
65
+ const offsets = new Set<number>()
66
+ for (const delta of [-2, -1, 0, 1, 2]) {
67
+ const timestamp = guess + delta * 86400000
68
+ const fields = dateTimeFields(new Date(timestamp), timeZone)
69
+ if (!fields) continue
70
+ const civil = civilTimestamp(fields.date, fields.time)
71
+ if (civil != null) offsets.add(civil - timestamp)
72
+ }
73
+ const candidates: number[] = []
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) candidates.push(candidate)
78
+ }
79
+ if (!candidates.length) return null
80
+ return new Date(disambiguation === 'later' ? Math.max(...candidates) : Math.min(...candidates)).toISOString()
81
+ }
82
+
83
+ export function formatDateTime(value: DateTimeValue, timeZone: string, locale = 'en-US'): string | null {
84
+ const instant = dateTimeInstant(value)
85
+ if (!instant) return null
86
+ try {
87
+ return new Intl.DateTimeFormat(locale, { timeZone, year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit', timeZoneName: 'short' }).format(new Date(instant))
88
+ }
89
+ catch { return null }
90
+ }
91
+
92
+ /** Recommendations stay app-owned; the picker only accepts the supplied instant. */
93
+ export function dateTimePreset(preset: DateTimePreset, timeZone: string, now = new Date(), suggested: DateTimeValue = null): string | null {
94
+ if (!validTimeZone(timeZone) || !Number.isFinite(now.getTime())) return null
95
+ if (preset === 'hour') return new Date(now.getTime() + 3600000).toISOString()
96
+ if (preset === 'suggested') return dateTimeInstant(suggested)
97
+ const fields = dateTimeFields(now, timeZone)
98
+ if (!fields) return null
99
+ const midnight = civilTimestamp(fields.date, '00:00')
100
+ if (midnight == null) return null
101
+ const tomorrow = new Date(midnight + 86400000).toISOString().slice(0, 10)
102
+ return dateTimeToIso(tomorrow, '09:00', timeZone)
103
+ }
@@ -0,0 +1,24 @@
1
+ export { default as DateTimePicker } from './DateTimePicker.stx'
2
+ export * from './date-time'
3
+ import type { DateTimeSelection, DateTimeValue } from './date-time'
4
+
5
+ export interface DateTimePickerProps {
6
+ value?: DateTimeValue
7
+ /** IANA workspace timezone. Defaults to UTC, never the server's timezone. */
8
+ timeZone?: string
9
+ locale?: string
10
+ minDate?: DateTimeValue
11
+ maxDate?: DateTimeValue
12
+ /** App-owned recommendation shown as “Next best time” when supplied. */
13
+ suggestedTime?: DateTimeValue
14
+ /** Positive divisor of 60; defaults to one minute. */
15
+ minuteStep?: number
16
+ disabled?: boolean
17
+ clearable?: boolean
18
+ label?: string
19
+ placeholder?: string
20
+ className?: string
21
+ onChange?: (selection: DateTimeSelection) => void
22
+ onOpen?: () => void
23
+ onClose?: () => void
24
+ }