@super-calendar/solid 0.0.0-stage → 2.16.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,76 @@
1
+ import {
2
+ loadEventSource,
3
+ type CalendarEvent,
4
+ type EventSource,
5
+ type EventSourceOptions,
6
+ } from "@super-calendar/core/vanilla";
7
+ import { createEffect, createMemo, createSignal, untrack, type Accessor } from "solid-js";
8
+
9
+ /** Reactive state for a refreshable calendar feed. */
10
+ export interface EventSourceState<T> {
11
+ /** Last successful batch, retained during loading and errors. */
12
+ events: Accessor<CalendarEvent<T>[]>;
13
+ loading: Accessor<boolean>;
14
+ error: Accessor<Error | null>;
15
+ /** Reload now. Does nothing after the owning component or root is disposed. */
16
+ refetch: () => Promise<void>;
17
+ }
18
+
19
+ /** Load a reactive URL or async function, with optional polling and owned cleanup. */
20
+ export function createEventSource<T = unknown>(
21
+ source: Accessor<EventSource<T>>,
22
+ options: Accessor<EventSourceOptions<T>> = () => ({}),
23
+ ): EventSourceState<T> {
24
+ const [events, setEvents] = createSignal<CalendarEvent<T>[]>([]);
25
+ const [loading, setLoading] = createSignal(true);
26
+ const [error, setError] = createSignal<Error | null>(null);
27
+ let generation = 0;
28
+ let controller: AbortController | undefined;
29
+ let active = false;
30
+ const configuration = createMemo(() => ({ source: source(), ...options() }));
31
+
32
+ const load = async (manual: boolean, value: ReturnType<typeof configuration>) => {
33
+ if (!active) return;
34
+ const current = ++generation;
35
+ controller?.abort();
36
+ controller = typeof AbortController === "undefined" ? undefined : new AbortController();
37
+ if (manual) setLoading(true);
38
+ try {
39
+ const next = await loadEventSource({
40
+ ...value,
41
+ signal: controller?.signal,
42
+ });
43
+ if (current !== generation) return;
44
+ setEvents(next);
45
+ setError(null);
46
+ } catch (cause) {
47
+ if (current !== generation) return;
48
+ setError(cause instanceof Error ? cause : new Error(String(cause)));
49
+ } finally {
50
+ if (current === generation) setLoading(false);
51
+ }
52
+ };
53
+
54
+ createEffect(configuration, (value) => {
55
+ active = true;
56
+ void load(true, value);
57
+ const interval = value.refetchIntervalMs;
58
+ const timer =
59
+ interval && Number.isFinite(interval) && interval > 0 && interval <= 2 ** 31 - 1
60
+ ? setInterval(() => void load(false, value), interval)
61
+ : undefined;
62
+ return () => {
63
+ active = false;
64
+ generation++;
65
+ controller?.abort();
66
+ if (timer !== undefined) clearInterval(timer);
67
+ };
68
+ });
69
+
70
+ return {
71
+ events,
72
+ loading,
73
+ error,
74
+ refetch: () => (active ? load(true, untrack(configuration)) : Promise.resolve()),
75
+ };
76
+ }
package/src/index.ts ADDED
@@ -0,0 +1,106 @@
1
+ export {
2
+ backgroundBandsForDay,
3
+ buildMonthGrid,
4
+ daySelectionState,
5
+ defaultCalendarLabels,
6
+ expandRecurringEvents,
7
+ getViewDays,
8
+ isAllDayEvent,
9
+ isBackgroundEvent,
10
+ isDateSelectable,
11
+ isRangeEndpoint,
12
+ isWithinDateRange,
13
+ layoutDayEvents,
14
+ layoutMonthWeek,
15
+ loadEventSource,
16
+ nextDateRange,
17
+ parseICalendar,
18
+ toICalendar,
19
+ weekdayFormatToken,
20
+ type BusinessHours,
21
+ type BusinessHoursBand,
22
+ type CalendarEvent,
23
+ type CalendarHandle,
24
+ type CalendarLabels,
25
+ type CalendarMode,
26
+ type CreateGhostArgs,
27
+ type DateRange,
28
+ type DateSelectionConstraints,
29
+ type DaySelectionState,
30
+ type EventAccessibilityLabelContext,
31
+ type EventAccessibilityLabeler,
32
+ type EventSource,
33
+ type EventSourceOptions,
34
+ type ICalEvent,
35
+ type ICalendarEvent,
36
+ type MonthEventSegment,
37
+ type MonthGrid,
38
+ type MonthGridDay,
39
+ type MonthGridWeek,
40
+ type MonthGridWeekday,
41
+ type MonthWeekEvents,
42
+ type PositionedEvent,
43
+ type RecurrenceFrequency,
44
+ type RecurrenceRule,
45
+ type ScrollToTimeOptions,
46
+ type TimeGridMode,
47
+ type ToICalendarOptions,
48
+ type UseDateRangeOptions,
49
+ type UseMonthGridOptions,
50
+ type WeekStartsOn,
51
+ type WeekdayFormat,
52
+ } from "@super-calendar/core/vanilla";
53
+ export { createEventSource, type EventSourceState } from "./createEventSource";
54
+ export {
55
+ Agenda,
56
+ type AgendaProps,
57
+ type AgendaSlot,
58
+ type SolidAgendaEvent,
59
+ type SolidAgendaEventArgs,
60
+ } from "./Agenda";
61
+ export { Calendar, type CalendarProps, type CalendarSlot } from "./Calendar";
62
+ export {
63
+ DatePicker,
64
+ DateRangePicker,
65
+ type DatePickerProps,
66
+ type DatePickerSlot,
67
+ type DateRangePickerProps,
68
+ } from "./DateRangePicker";
69
+ export { MonthList, type MonthListProps, type MonthListSlot } from "./MonthList";
70
+ export {
71
+ MonthView,
72
+ type MonthViewProps,
73
+ type MonthViewSlot,
74
+ type SolidMonthEvent,
75
+ type SolidMonthEventArgs,
76
+ } from "./MonthView";
77
+ export {
78
+ ResourceTimeline,
79
+ type Resource,
80
+ type ResourceEventArgs,
81
+ type ResourceTimelineProps,
82
+ type ResourceTimelineSlot,
83
+ } from "./ResourceTimeline";
84
+ export { type ResolvedSlot, type SlotDefault, type SlotStyleProps } from "./slots";
85
+ export {
86
+ createDateRange,
87
+ createMonthGrid,
88
+ createNow,
89
+ type DateRangeOptions,
90
+ type NowOptions,
91
+ } from "./state";
92
+ export type { CSSProperties } from "./styles";
93
+ export {
94
+ darkSolidTheme,
95
+ defaultSolidTheme,
96
+ mergeSolidTheme,
97
+ type SolidCalendarTheme,
98
+ } from "./theme";
99
+ export {
100
+ TimeGrid,
101
+ type SolidRenderEvent,
102
+ type SolidRenderEventArgs,
103
+ type TimeGridProps,
104
+ type TimeGridSlot,
105
+ } from "./TimeGrid";
106
+ export { YearView, type YearViewProps, type YearViewSlot } from "./YearView";
package/src/props.ts ADDED
@@ -0,0 +1,24 @@
1
+ import { merge } from "solid-js";
2
+
3
+ type Defaulted<P, D> = Omit<P, keyof D> & {
4
+ [K in keyof D]-?: K extends keyof P ? Exclude<P[K], undefined> : D[K];
5
+ };
6
+
7
+ // Solid 2's merge preserves explicit undefined. Forwarded optional calendar props
8
+ // need the same defaults as omitted props, while keeping false, zero, and empty strings.
9
+ export function withDefaults<P extends object, D extends Partial<P>>(
10
+ fallback: D,
11
+ props: P,
12
+ ): Defaulted<P, D> {
13
+ const resolved: Record<string, unknown> = {};
14
+ for (const key of Object.keys(fallback)) {
15
+ Object.defineProperty(resolved, key, {
16
+ enumerable: true,
17
+ get() {
18
+ const value: unknown = Reflect.get(props, key);
19
+ return value === undefined ? Reflect.get(fallback, key) : value;
20
+ },
21
+ });
22
+ }
23
+ return merge(props, resolved) as Defaulted<P, D>;
24
+ }
package/src/slots.ts ADDED
@@ -0,0 +1,91 @@
1
+ // Per-slot styling for the DOM renderer.
2
+ //
3
+ // Every component styles itself with inline styles driven by the theme object, so
4
+ // zero-config consumers get a full look with no stylesheet. But inline styles beat
5
+ // external CSS, so a Tailwind (or plain CSS) class can't override them. This module
6
+ // closes that gap: each styleable element is a named "slot" that accepts a `class`
7
+ // and/or an inline `style` override.
8
+ //
9
+ // The contract: a slot's *structural* styles (the layout the component needs to not
10
+ // fall apart -- grid templates, flex, positioning) always apply. Its *themed* styles
11
+ // (colours, typography, spacing, borders) apply only when no class is supplied for
12
+ // that slot; supply a class and you own those, so your Tailwind classes win instead
13
+ // of losing to inline styles. A per-slot inline `style` override always merges last.
14
+
15
+ import type { JSX } from "@solidjs/web";
16
+ import { createMemo } from "solid-js";
17
+ import { css, type CSSProperties } from "./styles";
18
+
19
+ /** Join truthy class names (a dependency-free clsx-lite). */
20
+ export function cn(...parts: Array<string | false | null | undefined>): string | undefined {
21
+ const out = parts.filter(Boolean).join(" ");
22
+ return out || undefined;
23
+ }
24
+
25
+ /**
26
+ * Per-slot styling overrides. Give a slot a Tailwind/CSS class and/or an inline
27
+ * style; missing slots keep the built-in look.
28
+ */
29
+ export interface SlotStyleProps<Slot extends string> {
30
+ /**
31
+ * Class names per slot (e.g. Tailwind). Supplying a class for a slot drops the
32
+ * built-in *themed* inline styles for that slot so the class fully controls its
33
+ * look; the *structural* styles the layout depends on are kept.
34
+ */
35
+ classNames?: Partial<Record<Slot, string>>;
36
+ /** Inline style overrides per slot, merged last (win over defaults and classes). */
37
+ styles?: Partial<Record<Slot, CSSProperties>>;
38
+ }
39
+
40
+ /** A slot's built-in styling, split so classes can replace the look but not the layout. */
41
+ export interface SlotDefault {
42
+ /** Structural styles kept even when a class is supplied. */
43
+ base?: CSSProperties;
44
+ /** Themed styles (colour, type, spacing) dropped when a class is supplied. */
45
+ themed?: CSSProperties;
46
+ }
47
+
48
+ /** The props a resolved slot spreads onto an element. */
49
+ export interface ResolvedSlot {
50
+ class: string | undefined;
51
+ style: JSX.CSSProperties | undefined;
52
+ "data-slot": string;
53
+ }
54
+
55
+ /**
56
+ * Build a reactive slot resolver. `slot(name, defaults)` returns the props to
57
+ * spread on that element: a merged `class`, the resolved inline `style`, and a
58
+ * stable `data-slot` hook for CSS/testing.
59
+ */
60
+ export function createSlots<Slot extends string>(props: SlotStyleProps<Slot>) {
61
+ const classes = createMemo(() => props.classNames);
62
+ const overrides = createMemo(() => props.styles);
63
+ return (name: Slot, defaults?: SlotDefault): ResolvedSlot => {
64
+ const slotClass = classes()?.[name];
65
+ const override = overrides()?.[name];
66
+ const style: CSSProperties = {
67
+ ...defaults?.base,
68
+ ...(slotClass ? undefined : defaults?.themed),
69
+ ...override,
70
+ };
71
+ return {
72
+ class: cn(slotClass),
73
+ // Omit an empty style object so the DOM stays clean when a slot has no styles.
74
+ style: Object.keys(style).length ? css(style) : undefined,
75
+ "data-slot": name,
76
+ };
77
+ };
78
+ }
79
+
80
+ /**
81
+ * Turn a map of boolean state flags into present/absent `data-*` attributes, so
82
+ * consumers can target state with CSS/Tailwind variants (e.g. `data-[today]:...`).
83
+ * A true flag renders the attribute (empty value); a false/undefined one omits it.
84
+ */
85
+ export function dataState(
86
+ flags: Record<string, boolean | undefined>,
87
+ ): Record<string, "" | undefined> {
88
+ const out: Record<string, "" | undefined> = {};
89
+ for (const key in flags) if (flags[key]) out[key] = "";
90
+ return out;
91
+ }
package/src/state.ts ADDED
@@ -0,0 +1,62 @@
1
+ import {
2
+ buildMonthGrid,
3
+ isDateSelectable,
4
+ nextDateRange,
5
+ toZonedTime,
6
+ type DateRange,
7
+ type DateSelectionConstraints,
8
+ type UseMonthGridOptions,
9
+ } from "@super-calendar/core/vanilla";
10
+ import { startOfDay } from "date-fns";
11
+ import { createEffect, createMemo, createSignal, untrack, type Accessor } from "solid-js";
12
+
13
+ export interface NowOptions {
14
+ enabled?: boolean;
15
+ now?: Date;
16
+ timeZone?: string;
17
+ tickMs?: number;
18
+ }
19
+
20
+ /** A clock accessor that follows reactive overrides and stops ticking on disposal. */
21
+ export function createNow(options: Accessor<NowOptions> = () => ({})): Accessor<Date> {
22
+ const [instant, setInstant] = createSignal(untrack(() => new Date()));
23
+ createEffect(options, (value) => {
24
+ if (value.enabled === false || value.now) return;
25
+ setInstant(new Date());
26
+ const timer = setInterval(() => setInstant(new Date()), value.tickMs ?? 60_000);
27
+ return () => clearInterval(timer);
28
+ });
29
+ return createMemo(() => {
30
+ const value = options();
31
+ const now = value.now ?? instant();
32
+ return value.timeZone ? toZonedTime(now, value.timeZone) : now;
33
+ });
34
+ }
35
+
36
+ export interface DateRangeOptions extends DateSelectionConstraints {
37
+ initialRange?: DateRange | null;
38
+ }
39
+
40
+ /** Reactive range selection. Pass a getter so constraints can change after mounting. */
41
+ export function createDateRange(options: Accessor<DateRangeOptions> = () => ({})) {
42
+ const [range, setRange] = createSignal(untrack(() => options().initialRange ?? null));
43
+ return {
44
+ range,
45
+ setRange,
46
+ reset: () => setRange(null),
47
+ onPressDate: (date: Date) => setRange((current) => nextDateRange(current, date, options())),
48
+ selectRange: (a: Date, b: Date) => {
49
+ if (!isDateSelectable(a, options()) || !isDateSelectable(b, options())) return;
50
+ const [start, end] = a <= b ? [a, b] : [b, a];
51
+ setRange({ start: startOfDay(start), end: startOfDay(end) });
52
+ },
53
+ };
54
+ }
55
+
56
+ /** A reactive, renderer-independent month grid. */
57
+ export function createMonthGrid(
58
+ month: Accessor<Date>,
59
+ options: Accessor<UseMonthGridOptions> = () => ({}),
60
+ ) {
61
+ return createMemo(() => buildMonthGrid(month(), options()));
62
+ }
package/src/styles.ts ADDED
@@ -0,0 +1,68 @@
1
+ import type { JSX } from "@solidjs/web";
2
+ import type * as CSS from "csstype";
3
+
4
+ /** Inline styles accept CSS property names or camelCase names. Numeric lengths use pixels. */
5
+ export type CSSProperties = CSS.Properties<string | number> &
6
+ CSS.PropertiesHyphen<string | number> & {
7
+ [key: `--${string}`]: string | number | undefined;
8
+ };
9
+
10
+ export interface ElementRef<T> {
11
+ current: T;
12
+ }
13
+
14
+ export type DomKeyboardEvent<T = HTMLElement> = KeyboardEvent & { currentTarget: T };
15
+ export type DomPointerEvent<T = HTMLElement> = PointerEvent & { currentTarget: T };
16
+ export type DomMouseEvent<T = HTMLElement> = MouseEvent & { currentTarget: T };
17
+
18
+ const UNITLESS = new Set([
19
+ "animation-iteration-count",
20
+ "aspect-ratio",
21
+ "border-image-outset",
22
+ "border-image-slice",
23
+ "border-image-width",
24
+ "column-count",
25
+ "fill-opacity",
26
+ "flex",
27
+ "flex-grow",
28
+ "flex-shrink",
29
+ "font-weight",
30
+ "grid-area",
31
+ "grid-column",
32
+ "grid-column-end",
33
+ "grid-column-start",
34
+ "grid-row",
35
+ "grid-row-end",
36
+ "grid-row-start",
37
+ "line-height",
38
+ "opacity",
39
+ "order",
40
+ "orphans",
41
+ "scale",
42
+ "stroke-dasharray",
43
+ "stroke-dashoffset",
44
+ "stroke-miterlimit",
45
+ "stroke-opacity",
46
+ "stroke-width",
47
+ "tab-size",
48
+ "widows",
49
+ "z-index",
50
+ "zoom",
51
+ "-webkit-line-clamp",
52
+ ]);
53
+
54
+ export function css(style?: CSSProperties): JSX.CSSProperties | undefined {
55
+ if (!style) return undefined;
56
+ const result: Record<string, string | number> = {};
57
+ for (const [property, value] of Object.entries(style)) {
58
+ if (value == null) continue;
59
+ const name = property.startsWith("--")
60
+ ? property
61
+ : property.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`).replace(/^ms-/, "-ms-");
62
+ result[name] =
63
+ typeof value === "number" && value !== 0 && !UNITLESS.has(name) && !name.startsWith("--")
64
+ ? `${value}px`
65
+ : value;
66
+ }
67
+ return result;
68
+ }
package/src/theme.ts ADDED
@@ -0,0 +1,44 @@
1
+ // Theme for the Solid renderer. The DOM components style themselves with
2
+ // plain inline styles driven by this object, so consumers don't need to import
3
+ // a stylesheet or configure their bundler for CSS. Colours come from the shared
4
+ // @super-calendar/core token palette (one source for both renderers); only the
5
+ // DOM-specific pixel metrics and font stack live here.
6
+ import { type CalendarColors, darkColors, lightColors } from "@super-calendar/core/vanilla";
7
+
8
+ /**
9
+ * Theme for the Solid renderer. Combines the shared color palette from
10
+ * `@super-calendar/core` with the DOM-specific pixel metrics and font stack.
11
+ */
12
+ export type SolidCalendarTheme = CalendarColors & {
13
+ /** Row height of a day cell, in px. */
14
+ cellHeight: number;
15
+ /** Diameter of the day badge, in px. */
16
+ dayBadgeSize: number;
17
+ /**
18
+ * Height of the selection band strip, in px (the default pill look). The pill's
19
+ * corner radius is half this. Ignored when `fillCellOnSelection` is set, where
20
+ * the band fills the whole cell instead.
21
+ */
22
+ rangeBandHeight: number;
23
+ /** Font stack for the calendar. */
24
+ fontFamily: string;
25
+ };
26
+
27
+ const SYSTEM_FONT =
28
+ '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif';
29
+
30
+ const METRICS = { cellHeight: 48, dayBadgeSize: 34, rangeBandHeight: 32, fontFamily: SYSTEM_FONT };
31
+
32
+ /** The default light theme: the core light palette plus the DOM metrics. */
33
+ export const defaultSolidTheme: SolidCalendarTheme = { ...lightColors, ...METRICS };
34
+
35
+ /** The dark theme: the core dark palette plus the DOM metrics. */
36
+ export const darkSolidTheme: SolidCalendarTheme = { ...darkColors, ...METRICS };
37
+
38
+ /** Merge a partial override onto a base theme (defaults to {@link defaultSolidTheme}). */
39
+ export function mergeSolidTheme(
40
+ overrides?: Partial<SolidCalendarTheme>,
41
+ base: SolidCalendarTheme = defaultSolidTheme,
42
+ ): SolidCalendarTheme {
43
+ return overrides ? { ...base, ...overrides } : base;
44
+ }
package/src/touch.ts ADDED
@@ -0,0 +1,61 @@
1
+ export type EventGrab = {
2
+ readonly box: HTMLElement;
3
+ readonly pointerId: number;
4
+ readonly pointerType: string;
5
+ readonly clientX: number;
6
+ readonly clientY: number;
7
+ };
8
+
9
+ export function waitForHold(
10
+ grab: EventGrab,
11
+ delay: number,
12
+ threshold: number,
13
+ onHold: () => void,
14
+ onTap: () => void,
15
+ onCancel: () => void,
16
+ ): () => void {
17
+ const detach = () => {
18
+ clearTimeout(timer);
19
+ document.removeEventListener("pointermove", move);
20
+ document.removeEventListener("pointerup", up);
21
+ document.removeEventListener("pointercancel", cancelPointer);
22
+ document.removeEventListener("pointerdown", anotherPointer);
23
+ };
24
+ const cancel = () => {
25
+ detach();
26
+ onCancel();
27
+ };
28
+ const move = (event: PointerEvent) => {
29
+ if (
30
+ event.pointerId === grab.pointerId &&
31
+ Math.hypot(event.clientX - grab.clientX, event.clientY - grab.clientY) > threshold
32
+ ) {
33
+ cancel();
34
+ }
35
+ };
36
+ const up = (event: PointerEvent) => {
37
+ if (event.pointerId === grab.pointerId) {
38
+ detach();
39
+ onTap();
40
+ }
41
+ };
42
+ const cancelPointer = (event: PointerEvent) => {
43
+ if (event.pointerId === grab.pointerId) {
44
+ cancel();
45
+ }
46
+ };
47
+ const anotherPointer = (event: PointerEvent) => {
48
+ if (event.pointerId !== grab.pointerId) {
49
+ cancel();
50
+ }
51
+ };
52
+ const timer = setTimeout(() => {
53
+ detach();
54
+ onHold();
55
+ }, delay);
56
+ document.addEventListener("pointermove", move);
57
+ document.addEventListener("pointerup", up);
58
+ document.addEventListener("pointercancel", cancelPointer);
59
+ document.addEventListener("pointerdown", anotherPointer);
60
+ return cancel;
61
+ }