@a4ui/core 0.33.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,120 @@
1
+ // Input + Apply button with explicit idle/loading/success/error states.
2
+ // Rejected coupons surface as { ok: false } and render inline; unexpected
3
+ // rejections from `onApply` are not caught here, so they propagate as
4
+ // unhandled rejections instead of being silently swallowed.
5
+ import { CircleCheck, X } from 'lucide-solid'
6
+ import type { JSX } from 'solid-js'
7
+ import { createSignal, Show } from 'solid-js'
8
+
9
+ import { cn } from '../lib/cn'
10
+ import { Button } from './Button'
11
+ import { Input } from './Input'
12
+ import { Spinner } from './Spinner'
13
+
14
+ export interface CouponFieldProps {
15
+ /** Validate/apply a coupon code. Resolve with `{ ok: false }` for a rejected
16
+ * code — do not throw for expected rejections, only for unexpected failures. */
17
+ onApply: (code: string) => Promise<{ ok: boolean; message?: string; discount?: string }>
18
+ placeholder?: string
19
+ class?: string
20
+ }
21
+
22
+ type State =
23
+ | { status: 'idle' | 'loading' }
24
+ | { status: 'success'; code: string; discount?: string }
25
+ | { status: 'error'; message: string }
26
+
27
+ /**
28
+ * Coupon/promo code input with an "Apply" button. Tracks explicit
29
+ * idle/loading/success/error state: loading shows a spinner and disables the
30
+ * input, success shows the applied discount with a way to remove it and try
31
+ * another code, error shows the failure message inline and lets the user retry.
32
+ * Rejections are read from the resolved `{ ok: false }` result, not caught
33
+ * exceptions — an unexpected throw from `onApply` propagates uncaught.
34
+ *
35
+ * @example
36
+ * ```tsx
37
+ * <CouponField
38
+ * onApply={async (code) => {
39
+ * const res = await api.applyCoupon(code)
40
+ * return res.valid
41
+ * ? { ok: true, discount: '-$10' }
42
+ * : { ok: false, message: 'That code has expired.' }
43
+ * }}
44
+ * />
45
+ * ```
46
+ */
47
+ export function CouponField(props: CouponFieldProps): JSX.Element {
48
+ const [code, setCode] = createSignal('')
49
+ const [state, setState] = createSignal<State>({ status: 'idle' })
50
+
51
+ const apply = async (): Promise<void> => {
52
+ const value = code().trim()
53
+ if (!value || state().status === 'loading') return
54
+ setState({ status: 'loading' })
55
+ const result = await props.onApply(value)
56
+ if (result.ok) {
57
+ setState({ status: 'success', code: value, discount: result.discount })
58
+ } else {
59
+ setState({ status: 'error', message: result.message ?? 'This code could not be applied.' })
60
+ }
61
+ }
62
+
63
+ const remove = (): void => {
64
+ setCode('')
65
+ setState({ status: 'idle' })
66
+ }
67
+
68
+ const isLoading = () => state().status === 'loading'
69
+ const isSuccess = () => state().status === 'success'
70
+
71
+ return (
72
+ <div class={cn('flex flex-col gap-2', props.class)}>
73
+ <Show
74
+ when={!isSuccess()}
75
+ fallback={
76
+ <div class="flex items-center justify-between rounded-md border border-emerald-500/30 bg-emerald-500/10 px-3 py-2 text-sm">
77
+ <span class="flex items-center gap-2 text-emerald-500">
78
+ <CircleCheck class="h-4 w-4 shrink-0" />
79
+ <span class="text-foreground">
80
+ {(state() as { status: 'success'; code: string; discount?: string }).discount ?? 'Discount'}{' '}
81
+ applied
82
+ </span>
83
+ </span>
84
+ <button
85
+ type="button"
86
+ aria-label="Remove coupon"
87
+ onClick={remove}
88
+ class="text-muted-foreground hover:text-foreground"
89
+ >
90
+ <X class="h-4 w-4" />
91
+ </button>
92
+ </div>
93
+ }
94
+ >
95
+ <div class="flex gap-2">
96
+ <Input
97
+ value={code()}
98
+ onInput={setCode}
99
+ disabled={isLoading()}
100
+ placeholder={props.placeholder ?? 'Coupon code'}
101
+ onKeyDown={(ev) => {
102
+ if (ev.key === 'Enter') {
103
+ ev.preventDefault()
104
+ void apply()
105
+ }
106
+ }}
107
+ />
108
+ <Button variant="outline" disabled={isLoading() || !code().trim()} onClick={() => void apply()}>
109
+ <Show when={isLoading()} fallback="Apply">
110
+ <Spinner class="h-4 w-4" label="Applying coupon" />
111
+ </Show>
112
+ </Button>
113
+ </div>
114
+ <Show when={state().status === 'error'}>
115
+ <p class="text-sm text-destructive">{(state() as { status: 'error'; message: string }).message}</p>
116
+ </Show>
117
+ </Show>
118
+ </div>
119
+ )
120
+ }
@@ -0,0 +1,112 @@
1
+ // FollowingPointer — hides the native cursor over `children` and renders a
2
+ // custom arrow + label chip that follows the mouse instead. Position is
3
+ // written straight to the DOM node's `transform` on every pointermove (same
4
+ // "skip the signal, touch the ref directly" idiom as Magnetic.tsx) rather
5
+ // than through a reactive signal, so the follow is jank-free. No-op (native
6
+ // cursor kept, nothing custom rendered) under motionReduced().
7
+ import { onCleanup, onMount, Show, type JSX } from 'solid-js'
8
+
9
+ import { cn } from '../lib/cn'
10
+ import { motionReduced } from '../lib/motion'
11
+
12
+ export interface FollowingPointerProps {
13
+ label?: JSX.Element
14
+ /** Tone of the custom cursor + label chip. @default 'primary' */
15
+ color?: 'primary' | 'accent'
16
+ children: JSX.Element
17
+ class?: string
18
+ }
19
+
20
+ /**
21
+ * Wraps `children` in a `relative` container that hides the native cursor
22
+ * and renders a custom pointer — a small arrow glyph plus a rounded label
23
+ * chip in the given tone — that follows the mouse within the container.
24
+ * Hidden until the pointer enters, hidden again on leave. Under
25
+ * {@link motionReduced}, the native cursor is kept and nothing custom is
26
+ * rendered. Listeners are cleaned up on unmount.
27
+ *
28
+ * @example
29
+ * ```tsx
30
+ * <FollowingPointer label="Alex" color="accent">
31
+ * <div class="grid h-48 place-items-center rounded-lg border">Hover me</div>
32
+ * </FollowingPointer>
33
+ * ```
34
+ */
35
+ export function FollowingPointer(props: FollowingPointerProps): JSX.Element {
36
+ let root: HTMLDivElement | undefined
37
+ let pointerEl: HTMLDivElement | undefined
38
+
39
+ onMount(() => {
40
+ if (motionReduced() || !root || !pointerEl) return
41
+
42
+ const handlePointerMove = (event: PointerEvent): void => {
43
+ const rect = root!.getBoundingClientRect()
44
+ const x = event.clientX - rect.left
45
+ const y = event.clientY - rect.top
46
+ pointerEl!.style.transform = `translate(${x}px, ${y}px)`
47
+ }
48
+
49
+ const handlePointerEnter = (event: PointerEvent): void => {
50
+ pointerEl!.style.opacity = '1'
51
+ handlePointerMove(event)
52
+ }
53
+
54
+ const handlePointerLeave = (): void => {
55
+ pointerEl!.style.opacity = '0'
56
+ }
57
+
58
+ root.addEventListener('pointermove', handlePointerMove)
59
+ root.addEventListener('pointerenter', handlePointerEnter)
60
+ root.addEventListener('pointerleave', handlePointerLeave)
61
+
62
+ onCleanup(() => {
63
+ root!.removeEventListener('pointermove', handlePointerMove)
64
+ root!.removeEventListener('pointerenter', handlePointerEnter)
65
+ root!.removeEventListener('pointerleave', handlePointerLeave)
66
+ })
67
+ })
68
+
69
+ const tone = (): 'primary' | 'accent' => (props.color === 'accent' ? 'accent' : 'primary')
70
+
71
+ return (
72
+ <div ref={root} class={cn('relative', !motionReduced() && 'cursor-none', props.class)}>
73
+ {props.children}
74
+ <Show when={!motionReduced()}>
75
+ <div
76
+ ref={pointerEl}
77
+ aria-hidden="true"
78
+ class="pointer-events-none absolute left-0 top-0 z-50 flex items-center opacity-0 transition-opacity duration-150 will-change-transform"
79
+ >
80
+ <svg
81
+ width="20"
82
+ height="20"
83
+ viewBox="0 0 20 20"
84
+ class={cn(
85
+ '-translate-x-0.5 -translate-y-0.5 drop-shadow',
86
+ tone() === 'accent' ? 'text-accent' : 'text-primary',
87
+ )}
88
+ >
89
+ <path
90
+ d="M2 2 L18 9 L10 11 L8 18 Z"
91
+ fill="currentColor"
92
+ stroke="hsl(var(--background))"
93
+ stroke-width="1"
94
+ />
95
+ </svg>
96
+ <Show when={props.label}>
97
+ <div
98
+ class={cn(
99
+ 'ml-2 whitespace-nowrap rounded-full px-2.5 py-1 text-xs font-medium shadow-lg',
100
+ tone() === 'accent'
101
+ ? 'bg-accent text-accent-foreground'
102
+ : 'bg-primary text-primary-foreground',
103
+ )}
104
+ >
105
+ {props.label}
106
+ </div>
107
+ </Show>
108
+ </div>
109
+ </Show>
110
+ </div>
111
+ )
112
+ }
@@ -0,0 +1,283 @@
1
+ // GanttChart — a read-only project schedule chart built from plain flex/grid
2
+ // `div`s (no SVG, no date library). Each task is a row with its name in a
3
+ // fixed-width left column and a bar positioned on a proportional time axis
4
+ // (left%/width% derived from the task's start/end within the overall date
5
+ // range), mirroring BarChart's percentage-of-max layout idiom. Dependency
6
+ // arrows are drawn as right-angle elbow connectors using bordered divs so
7
+ // the whole chart stays in the same box-model coordinate space as the bars.
8
+ import { createMemo, For, Show, type JSX } from 'solid-js'
9
+
10
+ import { cn } from '../lib/cn'
11
+
12
+ const DAY_MS = 24 * 60 * 60 * 1000
13
+ /** Header height (`h-8`) in px — the coordinate origin for row overlays. */
14
+ const HEADER_HEIGHT = 32
15
+ /** Per-task row height (`h-10`) in px. */
16
+ const ROW_HEIGHT = 40
17
+ /** Candidate tick spacings (days); the smallest that keeps ticks readable wins. */
18
+ const TICK_STEP_DAYS = [1, 2, 3, 7, 14, 30, 60, 90, 180]
19
+
20
+ /** A single bar rendered by {@link GanttChart}. */
21
+ export interface GanttTask {
22
+ id: string
23
+ name: string
24
+ /** ISO date, `'YYYY-MM-DD'`. */
25
+ start: string
26
+ /** ISO date, `'YYYY-MM-DD'`. */
27
+ end: string
28
+ /** Ids of tasks that must finish before this one starts; drawn as elbow connectors. */
29
+ dependencies?: string[]
30
+ /** Bar color. Defaults to `'primary'`. */
31
+ tone?: 'primary' | 'accent'
32
+ }
33
+
34
+ export interface GanttChartProps {
35
+ tasks: GanttTask[]
36
+ class?: string
37
+ }
38
+
39
+ interface Tick {
40
+ label: string
41
+ percent: number
42
+ }
43
+
44
+ interface Connector {
45
+ id: string
46
+ /** Elbow's vertical run: x of the dependency's end, from its row to the dependent's row. */
47
+ xFrom: number
48
+ yFrom: number
49
+ xTo: number
50
+ yTo: number
51
+ arrowRight: boolean
52
+ }
53
+
54
+ function pickStepDays(totalDays: number): number {
55
+ const target = totalDays / 8
56
+ return TICK_STEP_DAYS.find((step) => step >= target) ?? TICK_STEP_DAYS[TICK_STEP_DAYS.length - 1]
57
+ }
58
+
59
+ function formatTick(date: Date): string {
60
+ return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' })
61
+ }
62
+
63
+ /**
64
+ * Read-only Gantt chart: a header row of date ticks over a proportional time
65
+ * axis, one row per task with a colored bar spanning `start`–`end`, elbow
66
+ * connectors for `dependencies`, and a "today" marker when today falls
67
+ * within the overall range. Horizontal scroll kicks in when the range is
68
+ * wide relative to the container.
69
+ *
70
+ * @example
71
+ * ```tsx
72
+ * <GanttChart
73
+ * tasks={[
74
+ * { id: 'design', name: 'Design', start: '2026-01-05', end: '2026-01-16', tone: 'accent' },
75
+ * { id: 'build', name: 'Build', start: '2026-01-19', end: '2026-02-06', dependencies: ['design'] },
76
+ * { id: 'launch', name: 'Launch', start: '2026-02-09', end: '2026-02-10', dependencies: ['build'] },
77
+ * ]}
78
+ * />
79
+ * ```
80
+ */
81
+ export function GanttChart(props: GanttChartProps): JSX.Element {
82
+ const range = createMemo(() => {
83
+ if (props.tasks.length === 0) return null
84
+ let min = Number.POSITIVE_INFINITY
85
+ let max = Number.NEGATIVE_INFINITY
86
+ for (const task of props.tasks) {
87
+ const start = new Date(task.start).getTime()
88
+ const end = new Date(task.end).getTime()
89
+ if (start < min) min = start
90
+ if (end > max) max = end
91
+ }
92
+ // Guard a zero-width range (single task, start === end) so percentages stay finite.
93
+ const totalMs = Math.max(max - min, DAY_MS)
94
+ return { min, max: min + totalMs, totalMs }
95
+ })
96
+
97
+ const percentFor = (isoOrTime: string | number): number => {
98
+ const r = range()
99
+ if (!r) return 0
100
+ const time = typeof isoOrTime === 'string' ? new Date(isoOrTime).getTime() : isoOrTime
101
+ return Math.min(100, Math.max(0, ((time - r.min) / r.totalMs) * 100))
102
+ }
103
+
104
+ const ticks = createMemo<Tick[]>(() => {
105
+ const r = range()
106
+ if (!r) return []
107
+ const totalDays = Math.max(1, Math.round(r.totalMs / DAY_MS))
108
+ const step = pickStepDays(totalDays)
109
+ const out: Tick[] = []
110
+ for (let d = 0; d <= totalDays; d += step) {
111
+ out.push({ label: formatTick(new Date(r.min + d * DAY_MS)), percent: (d / totalDays) * 100 })
112
+ }
113
+ return out
114
+ })
115
+
116
+ const todayPercent = createMemo<number | null>(() => {
117
+ const r = range()
118
+ if (!r) return null
119
+ const now = new Date()
120
+ const today = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate())
121
+ if (today < r.min || today > r.max) return null
122
+ return percentFor(today)
123
+ })
124
+
125
+ const rowIndex = createMemo(() => {
126
+ const map = new Map<string, number>()
127
+ props.tasks.forEach((task, i) => map.set(task.id, i))
128
+ return map
129
+ })
130
+
131
+ const connectors = createMemo<Connector[]>(() => {
132
+ const byId = new Map(props.tasks.map((t) => [t.id, t]))
133
+ const index = rowIndex()
134
+ const out: Connector[] = []
135
+ for (const task of props.tasks) {
136
+ for (const depId of task.dependencies ?? []) {
137
+ const dep = byId.get(depId)
138
+ if (!dep || dep.id === task.id) continue
139
+ const iDep = index.get(dep.id)
140
+ const iTask = index.get(task.id)
141
+ if (iDep === undefined || iTask === undefined) continue
142
+ const xFrom = percentFor(dep.end)
143
+ const xTo = percentFor(task.start)
144
+ out.push({
145
+ id: `${dep.id}->${task.id}`,
146
+ xFrom,
147
+ yFrom: iDep * ROW_HEIGHT + ROW_HEIGHT / 2,
148
+ xTo,
149
+ yTo: iTask * ROW_HEIGHT + ROW_HEIGHT / 2,
150
+ arrowRight: xTo >= xFrom,
151
+ })
152
+ }
153
+ }
154
+ return out
155
+ })
156
+
157
+ return (
158
+ <div class={cn('overflow-x-auto rounded-lg border border-border bg-card', props.class)}>
159
+ <Show
160
+ when={props.tasks.length > 0}
161
+ fallback={<p class="p-4 text-sm text-muted-foreground">No tasks to display.</p>}
162
+ >
163
+ <div class="flex min-w-[640px]">
164
+ {/* Names column */}
165
+ <div class="w-40 shrink-0 border-r border-border">
166
+ <div class="flex h-8 items-center px-3 text-xs font-medium text-muted-foreground">Task</div>
167
+ <For each={props.tasks}>
168
+ {(task, i) => (
169
+ <div
170
+ class={cn(
171
+ 'flex h-10 items-center border-t border-border px-3',
172
+ i() % 2 === 1 && 'bg-muted',
173
+ )}
174
+ >
175
+ <span class="truncate text-sm text-foreground" title={task.name}>
176
+ {task.name}
177
+ </span>
178
+ </div>
179
+ )}
180
+ </For>
181
+ </div>
182
+
183
+ {/* Chart column: header ticks, rows, connectors and the today marker all
184
+ share this box as their coordinate space (percent for x, px for y). */}
185
+ <div class="relative flex-1">
186
+ {/* Vertical gridlines, one per tick, spanning the whole chart column. */}
187
+ <div class="pointer-events-none absolute inset-0">
188
+ <For each={ticks()}>
189
+ {(tick) => (
190
+ <div
191
+ class="absolute inset-y-0 border-l border-border/40"
192
+ style={{ left: `${tick.percent}%` }}
193
+ />
194
+ )}
195
+ </For>
196
+ </div>
197
+
198
+ <div class="relative h-8">
199
+ <For each={ticks()}>
200
+ {(tick) => (
201
+ <span
202
+ class="absolute top-1/2 -translate-y-1/2 whitespace-nowrap pl-1 text-[11px] text-muted-foreground"
203
+ style={{ left: `${tick.percent}%` }}
204
+ >
205
+ {tick.label}
206
+ </span>
207
+ )}
208
+ </For>
209
+ </div>
210
+
211
+ <For each={props.tasks}>
212
+ {(task, i) => {
213
+ const left = () => percentFor(task.start)
214
+ const width = () => Math.max(percentFor(task.end) - left(), 1)
215
+ return (
216
+ <div class={cn('relative h-10 border-t border-border', i() % 2 === 1 && 'bg-muted')}>
217
+ <div
218
+ title={`${task.name}: ${task.start} → ${task.end}`}
219
+ class={cn(
220
+ 'absolute inset-y-2 rounded',
221
+ task.tone === 'accent' ? 'bg-accent' : 'bg-primary',
222
+ )}
223
+ style={{ left: `${left()}%`, width: `${width()}%` }}
224
+ />
225
+ </div>
226
+ )
227
+ }}
228
+ </For>
229
+
230
+ {/* Dependency connectors: elbow (vertical run at the predecessor's end,
231
+ horizontal run into the dependent's start) as bordered divs. */}
232
+ <div
233
+ class="pointer-events-none absolute inset-x-0 bottom-0"
234
+ style={{ top: `${HEADER_HEIGHT}px` }}
235
+ >
236
+ <For each={connectors()}>
237
+ {(c) => (
238
+ <>
239
+ <div
240
+ class="absolute border-l border-border"
241
+ style={{
242
+ left: `${c.xFrom}%`,
243
+ top: `${Math.min(c.yFrom, c.yTo)}px`,
244
+ height: `${Math.abs(c.yTo - c.yFrom)}px`,
245
+ }}
246
+ />
247
+ <div
248
+ class="absolute border-t border-border"
249
+ style={{
250
+ top: `${c.yTo}px`,
251
+ left: `${Math.min(c.xFrom, c.xTo)}%`,
252
+ width: `${Math.abs(c.xTo - c.xFrom)}%`,
253
+ }}
254
+ />
255
+ <div
256
+ class={cn(
257
+ 'absolute h-0 w-0 border-y-4 border-y-transparent',
258
+ c.arrowRight ? 'border-l-8 border-l-border' : 'border-r-8 border-r-border',
259
+ )}
260
+ style={{
261
+ top: `${c.yTo - 4}px`,
262
+ left: c.arrowRight ? `calc(${c.xTo}% - 8px)` : `${c.xTo}%`,
263
+ }}
264
+ />
265
+ </>
266
+ )}
267
+ </For>
268
+ </div>
269
+
270
+ {/* "Today" marker, spanning the header + every row. */}
271
+ <Show when={todayPercent() !== null}>
272
+ <div
273
+ class="pointer-events-none absolute inset-y-0 border-l border-primary"
274
+ style={{ left: `${todayPercent()}%` }}
275
+ title="Today"
276
+ />
277
+ </Show>
278
+ </div>
279
+ </div>
280
+ </Show>
281
+ </div>
282
+ )
283
+ }