@typescript-calendar-lib/react 0.1.1 → 0.3.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.
package/dist/index.js ADDED
@@ -0,0 +1,279 @@
1
+ import { buildMonthGrid, createDate, getMonthName, getWeekdayHeaders, isDateInRange, isSameDay } from "@typescript-calendar-lib/core";
2
+ import { jsx, jsxs } from "react/jsx-runtime";
3
+ import { buildMonthData, clearSelection, createCalendarState, getCursorDate, getSelectedDate, goToToday, moveCursor, navigateMonth, rebuildState, resolveOptions, selectDate } from "@typescript-calendar-lib/tui";
4
+ import { useCallback, useEffect, useRef, useState } from "react";
5
+ //#region src/cell-classes.ts
6
+ /** 日付セルの状態(週末・今日・ハイライト・範囲)に応じたCSSクラスを組み立てる */
7
+ function getCellClasses(date, options) {
8
+ const classes = [];
9
+ const dow = date.getDay();
10
+ if (dow === 0 || dow === 6) classes.push("is-weekend");
11
+ if (options.today && isSameDay(date, options.today)) classes.push("is-today");
12
+ if (options.highlight && isSameDay(date, options.highlight)) classes.push("is-highlight");
13
+ if (options.range && isDateInRange(date, options.range)) classes.push("is-in-range");
14
+ return classes.join(" ");
15
+ }
16
+ //#endregion
17
+ //#region src/size.ts
18
+ /** 組み込みサイズ名のみ真を返す(未知の文字列はカスタムサイズとして扱わない) */
19
+ function isSizeName(size) {
20
+ return typeof size === "string" && [
21
+ "sm",
22
+ "md",
23
+ "lg"
24
+ ].includes(size);
25
+ }
26
+ function toCssLength(value) {
27
+ return typeof value === "number" ? `${value}px` : value;
28
+ }
29
+ function buildSizeStyle(size) {
30
+ if (isSizeName(size)) return {};
31
+ const style = {};
32
+ if (size.width !== void 0) style["--cal-cell-w"] = toCssLength(size.width);
33
+ if (size.height !== void 0) style["--cal-cell-h"] = toCssLength(size.height);
34
+ return style;
35
+ }
36
+ //#endregion
37
+ //#region src/themes.ts
38
+ const THEMES = {
39
+ default: { className: "calendar-theme-default" },
40
+ modern: { className: "calendar-theme-modern" },
41
+ minimal: { className: "calendar-theme-minimal" },
42
+ rounded: { className: "calendar-theme-rounded" },
43
+ retro: { className: "calendar-theme-retro" }
44
+ };
45
+ function resolveTheme(theme) {
46
+ if (theme === void 0) return THEMES.default;
47
+ if (typeof theme === "string") return THEMES[theme] ?? THEMES.default;
48
+ return theme;
49
+ }
50
+ /** 各カラースキームで定義する CSS 変数(SCHEME_VALUES の並び順の定義) */
51
+ const SCHEME_KEYS = [
52
+ "--cal-bg",
53
+ "--cal-fg",
54
+ "--cal-accent",
55
+ "--cal-weekend-fg",
56
+ "--cal-border",
57
+ "--cal-header-bg",
58
+ "--cal-highlight-bg",
59
+ "--cal-highlight-fg",
60
+ "--cal-range-bg",
61
+ "--cal-today-bg",
62
+ "--cal-today-fg"
63
+ ];
64
+ const COLOR_SCHEMES = Object.fromEntries(Object.entries({
65
+ default: [
66
+ "#ffffff",
67
+ "#1e293b",
68
+ "#dc2626",
69
+ "#94a3b8",
70
+ "#e2e8f0",
71
+ "#f8fafc",
72
+ "#dc2626",
73
+ "#ffffff",
74
+ "#fef3c7",
75
+ "#fff7ed",
76
+ "#c2410c"
77
+ ],
78
+ ocean: [
79
+ "#f0f9ff",
80
+ "#0f172a",
81
+ "#0e7490",
82
+ "#7dd3fc",
83
+ "#bae6fd",
84
+ "#e0f2fe",
85
+ "#0e7490",
86
+ "#ffffff",
87
+ "#dff3fe",
88
+ "#cffafe",
89
+ "#155e75"
90
+ ],
91
+ forest: [
92
+ "#f0fdf4",
93
+ "#052e16",
94
+ "#15803d",
95
+ "#86efac",
96
+ "#bbf7d0",
97
+ "#dcfce7",
98
+ "#15803d",
99
+ "#ffffff",
100
+ "#dcfce7",
101
+ "#f0fdf4",
102
+ "#166534"
103
+ ],
104
+ sunset: [
105
+ "#fffaf5",
106
+ "#431407",
107
+ "#ea580c",
108
+ "#fdba74",
109
+ "#fed7aa",
110
+ "#ffedd5",
111
+ "#ea580c",
112
+ "#ffffff",
113
+ "#ffedd5",
114
+ "#fff7ed",
115
+ "#9a3412"
116
+ ],
117
+ mono: [
118
+ "#ffffff",
119
+ "#111827",
120
+ "#374151",
121
+ "#d1d5db",
122
+ "#e5e7eb",
123
+ "#f3f4f6",
124
+ "#111827",
125
+ "#ffffff",
126
+ "#f3f4f6",
127
+ "#e5e7eb",
128
+ "#111827"
129
+ ],
130
+ midnight: [
131
+ "#0f172a",
132
+ "#e2e8f0",
133
+ "#38bdf8",
134
+ "#475569",
135
+ "#1e293b",
136
+ "#1e293b",
137
+ "#38bdf8",
138
+ "#0f172a",
139
+ "#0c4a6e",
140
+ "#0c4a6e",
141
+ "#7dd3fc"
142
+ ],
143
+ blossom: [
144
+ "#fffaff",
145
+ "#500724",
146
+ "#db2777",
147
+ "#f9a8d4",
148
+ "#fbcfe8",
149
+ "#fdf2f8",
150
+ "#db2777",
151
+ "#ffffff",
152
+ "#fce7f3",
153
+ "#fdf2f8",
154
+ "#be185d"
155
+ ]
156
+ }).map(([name, values]) => [name, Object.fromEntries(SCHEME_KEYS.map((key, i) => [key, values[i]]))]));
157
+ function resolveColorScheme(scheme) {
158
+ if (scheme === void 0) return COLOR_SCHEMES.default;
159
+ if (typeof scheme === "string") return COLOR_SCHEMES[scheme] ?? COLOR_SCHEMES.default;
160
+ return scheme;
161
+ }
162
+ //#endregion
163
+ //#region src/hooks.ts
164
+ /** undefined を含む日付を値(時刻)で比較する */
165
+ function sameDateValue(a, b) {
166
+ return (a?.getTime() ?? -1) === (b?.getTime() ?? -1);
167
+ }
168
+ /** オプションの「値」が等しいか比較する(Date は getTime、参照ではない) */
169
+ function sameOptionsValue(a, b) {
170
+ return a.initialYear === b.initialYear && a.initialMonth === b.initialMonth && a.locale === b.locale && a.weekStart === b.weekStart && sameDateValue(a.today, b.today) && sameDateValue(a.highlight, b.highlight) && sameDateValue(a.range?.from, b.range?.from) && sameDateValue(a.range?.to, b.range?.to);
171
+ }
172
+ /**
173
+ * tui の不変状態マシンを包む React hook。
174
+ * カレンダーのインタラクティブ操作をシンプルに利用できる。
175
+ *
176
+ * `options` の値(locale / weekStart / today / highlight / range /
177
+ * initialYear / initialMonth)が変わると、カーソル・選択を保ったまま
178
+ * 状態が再構築される。比較は値(Date は getTime)で行うため、インラインで
179
+ * オプションを渡しても値が同じなら再構築されない。
180
+ *
181
+ * `today` を省略した場合、最初に解決された値が状態に固定され、以降も
182
+ * 引き継がれる(毎レンダリング `new Date()` を渡さなくてよい)。
183
+ */
184
+ function useCalendarState(options = {}) {
185
+ const [state, setState] = useState(() => createCalendarState({
186
+ initialYear: options.initialYear,
187
+ initialMonth: options.initialMonth,
188
+ today: options.today,
189
+ locale: options.locale,
190
+ weekStart: options.weekStart,
191
+ highlight: options.highlight,
192
+ range: options.range
193
+ }));
194
+ const prevOptions = useRef(options);
195
+ useEffect(() => {
196
+ if (sameOptionsValue(prevOptions.current, options)) return;
197
+ const prevInitialYear = prevOptions.current.initialYear;
198
+ const prevInitialMonth = prevOptions.current.initialMonth;
199
+ prevOptions.current = options;
200
+ setState((prev) => {
201
+ const resolved = resolveOptions({
202
+ today: options.today ?? prev.options.today,
203
+ locale: options.locale ?? prev.options.locale,
204
+ weekStart: options.weekStart ?? prev.options.weekStart,
205
+ highlight: options.highlight,
206
+ range: options.range
207
+ });
208
+ const year = options.initialYear !== void 0 && options.initialYear !== prevInitialYear ? options.initialYear : prev.year;
209
+ const month = options.initialMonth !== void 0 && options.initialMonth !== prevInitialMonth ? options.initialMonth : prev.month;
210
+ const monthData = buildMonthData(year, month, resolved);
211
+ return rebuildState(year, month, prev.cursor, prev.selectedDate, resolved, monthData);
212
+ });
213
+ }, [options]);
214
+ return {
215
+ state,
216
+ moveCursor: useCallback((direction) => setState((prev) => moveCursor(prev, direction)), []),
217
+ goNext: useCallback(() => setState((prev) => navigateMonth(prev, "next")), []),
218
+ goPrev: useCallback(() => setState((prev) => navigateMonth(prev, "prev")), []),
219
+ goToday: useCallback(() => setState((prev) => goToToday(prev)), []),
220
+ selectDate: useCallback(() => setState((prev) => selectDate(prev)), []),
221
+ clearSelection: useCallback(() => setState((prev) => clearSelection(prev)), []),
222
+ cursorDate: getCursorDate(state),
223
+ selectedDate: getSelectedDate(state)
224
+ };
225
+ }
226
+ //#endregion
227
+ //#region src/index.tsx
228
+ /** 月カレンダーコンポーネント */
229
+ function Calendar({ year, month, locale = "en", weekStart = "sunday", highlight, range, today, theme = "default", colorScheme = "default", size = "md", style, interactive = false, onDateClick, onDateHover }) {
230
+ const cellDate = (day) => createDate(year, month - 1, day);
231
+ const cellClass = (day) => getCellClasses(cellDate(day), {
232
+ today,
233
+ highlight,
234
+ range
235
+ }) || void 0;
236
+ const handleCellClick = (day) => {
237
+ if (interactive && onDateClick) onDateClick(cellDate(day));
238
+ };
239
+ const handleCellHover = (day) => {
240
+ if (interactive && onDateHover) onDateHover(cellDate(day));
241
+ };
242
+ return /* @__PURE__ */ jsxs("div", {
243
+ className: `calendar ${resolveTheme(theme).className}${isSizeName(size) ? ` calendar-size-${size}` : ""}${interactive ? " calendar-interactive" : ""}`,
244
+ style: {
245
+ ...resolveColorScheme(colorScheme),
246
+ ...buildSizeStyle(size),
247
+ ...style
248
+ },
249
+ children: [/* @__PURE__ */ jsx("div", {
250
+ className: "calendar-header",
251
+ children: /* @__PURE__ */ jsxs("h2", { children: [
252
+ getMonthName(locale, month),
253
+ " ",
254
+ year
255
+ ] })
256
+ }), /* @__PURE__ */ jsxs("table", { children: [/* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsx("tr", { children: getWeekdayHeaders(locale, weekStart).map((day) => /* @__PURE__ */ jsx("th", { children: day }, day)) }) }), /* @__PURE__ */ jsx("tbody", { children: buildMonthGrid(year, month, weekStart).map((row, i) => {
257
+ if (row.every((d) => d === null)) return null;
258
+ return /* @__PURE__ */ jsx("tr", { children: row.map((day, j) => {
259
+ if (day === null) return /* @__PURE__ */ jsx("td", {}, j);
260
+ return /* @__PURE__ */ jsx("td", {
261
+ className: cellClass(day),
262
+ children: interactive ? /* @__PURE__ */ jsx("button", {
263
+ type: "button",
264
+ className: "calendar-day-btn",
265
+ onClick: () => handleCellClick(day),
266
+ onMouseEnter: () => handleCellHover(day),
267
+ tabIndex: 0,
268
+ "aria-label": `${getMonthName(locale, month)} ${day}, ${year}`,
269
+ children: day
270
+ }) : day
271
+ }, day);
272
+ }) }, i);
273
+ }) })] })]
274
+ });
275
+ }
276
+ //#endregion
277
+ export { COLOR_SCHEMES, Calendar, Calendar as default, THEMES, resolveColorScheme, resolveTheme, useCalendarState };
278
+
279
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/cell-classes.ts","../src/size.ts","../src/themes.ts","../src/hooks.ts","../src/index.tsx"],"sourcesContent":["import { isDateInRange, isSameDay } from \"@typescript-calendar-lib/core\";\n\n// ─── セル状態クラス ───────────────────────────────────────\n\nexport interface CellStateOptions {\n today?: Date;\n highlight?: Date;\n range?: { from: Date; to: Date };\n}\n\n// 範囲の from > to は不正入力として RangeError(isDateInRange が検証する)\n\n/** 日付セルの状態(週末・今日・ハイライト・範囲)に応じたCSSクラスを組み立てる */\nexport function getCellClasses(date: Date, options: CellStateOptions): string {\n const classes: string[] = [];\n const dow = date.getDay();\n if (dow === 0 || dow === 6) classes.push(\"is-weekend\");\n if (options.today && isSameDay(date, options.today)) classes.push(\"is-today\");\n if (options.highlight && isSameDay(date, options.highlight))\n classes.push(\"is-highlight\");\n if (options.range && isDateInRange(date, options.range))\n classes.push(\"is-in-range\");\n return classes.join(\" \");\n}\n","import type { CSSProperties } from \"react\";\n\n// ─── セルサイズ ───────────────────────────────────────────\n\n/** 組み込みサイズ名 */\nexport type CalendarSizeName = \"sm\" | \"md\" | \"lg\";\n\n/** カスタムセルサイズ。数値は px、文字列は CSS 長さのまま渡す */\nexport interface CalendarCustomSize {\n width?: number | string;\n height?: number | string;\n}\n\n/** セルサイズ指定 */\nexport type CalendarSize = CalendarSizeName | CalendarCustomSize;\n\n/** 組み込みサイズ名のみ真を返す(未知の文字列はカスタムサイズとして扱わない) */\nexport function isSizeName(size: CalendarSize): size is CalendarSizeName {\n return typeof size === \"string\" && [\"sm\", \"md\", \"lg\"].includes(size);\n}\n\nfunction toCssLength(value: number | string): string {\n return typeof value === \"number\" ? `${value}px` : value;\n}\n\nexport function buildSizeStyle(size: CalendarSize): CSSProperties {\n if (isSizeName(size)) return {};\n const style: Record<string, string> = {};\n if (size.width !== undefined) style[\"--cal-cell-w\"] = toCssLength(size.width);\n if (size.height !== undefined)\n style[\"--cal-cell-h\"] = toCssLength(size.height);\n return style;\n}\n","// ─── テーマ ───────────────────────────────────────────────\n\n/** 組み込みテーマ名。カスタムテーマは ReactTheme オブジェクトを直接渡せる */\nexport type ThemeName = \"default\" | \"modern\" | \"minimal\" | \"rounded\" | \"retro\";\n\n/** React の見た目定義。テーマは主に CSS クラスで切り替える */\nexport interface ReactTheme {\n /** root 要素に追加するクラス */\n className: string;\n}\n\nexport const THEMES: Record<ThemeName, ReactTheme> = {\n default: { className: \"calendar-theme-default\" },\n modern: { className: \"calendar-theme-modern\" },\n minimal: { className: \"calendar-theme-minimal\" },\n rounded: { className: \"calendar-theme-rounded\" },\n retro: { className: \"calendar-theme-retro\" },\n};\n\nexport function resolveTheme(theme?: ThemeName | ReactTheme): ReactTheme {\n if (theme === undefined) return THEMES.default;\n if (typeof theme === \"string\") return THEMES[theme] ?? THEMES.default;\n return theme;\n}\n\n// ─── カラースキーム ───────────────────────────────────────\n\n/** 組み込みカラースキーム名。カスタムは CSS 変数マップを直接渡せる */\nexport type ColorSchemeName =\n | \"default\"\n | \"ocean\"\n | \"forest\"\n | \"sunset\"\n | \"mono\"\n | \"midnight\"\n | \"blossom\";\n\n/** CSS カスタムプロパティ(--cal-*)の値マップ */\nexport type ReactColorScheme = Record<`--cal-${string}`, string>;\n\n/** 各カラースキームで定義する CSS 変数(SCHEME_VALUES の並び順の定義) */\nconst SCHEME_KEYS = [\n \"--cal-bg\",\n \"--cal-fg\",\n \"--cal-accent\",\n \"--cal-weekend-fg\",\n \"--cal-border\",\n \"--cal-header-bg\",\n \"--cal-highlight-bg\",\n \"--cal-highlight-fg\",\n \"--cal-range-bg\",\n \"--cal-today-bg\",\n \"--cal-today-fg\",\n] as const;\n\n/** カラースキームごとの値を SCHEME_KEYS の並びで定義する */\nconst SCHEME_VALUES: Record<ColorSchemeName, readonly string[]> = {\n default: [\n \"#ffffff\",\n \"#1e293b\",\n \"#dc2626\",\n \"#94a3b8\",\n \"#e2e8f0\",\n \"#f8fafc\",\n \"#dc2626\",\n \"#ffffff\",\n \"#fef3c7\",\n \"#fff7ed\",\n \"#c2410c\",\n ],\n ocean: [\n \"#f0f9ff\",\n \"#0f172a\",\n \"#0e7490\",\n \"#7dd3fc\",\n \"#bae6fd\",\n \"#e0f2fe\",\n \"#0e7490\",\n \"#ffffff\",\n \"#dff3fe\",\n \"#cffafe\",\n \"#155e75\",\n ],\n forest: [\n \"#f0fdf4\",\n \"#052e16\",\n \"#15803d\",\n \"#86efac\",\n \"#bbf7d0\",\n \"#dcfce7\",\n \"#15803d\",\n \"#ffffff\",\n \"#dcfce7\",\n \"#f0fdf4\",\n \"#166534\",\n ],\n sunset: [\n \"#fffaf5\",\n \"#431407\",\n \"#ea580c\",\n \"#fdba74\",\n \"#fed7aa\",\n \"#ffedd5\",\n \"#ea580c\",\n \"#ffffff\",\n \"#ffedd5\",\n \"#fff7ed\",\n \"#9a3412\",\n ],\n mono: [\n \"#ffffff\",\n \"#111827\",\n \"#374151\",\n \"#d1d5db\",\n \"#e5e7eb\",\n \"#f3f4f6\",\n \"#111827\",\n \"#ffffff\",\n \"#f3f4f6\",\n \"#e5e7eb\",\n \"#111827\",\n ],\n midnight: [\n \"#0f172a\",\n \"#e2e8f0\",\n \"#38bdf8\",\n \"#475569\",\n \"#1e293b\",\n \"#1e293b\",\n \"#38bdf8\",\n \"#0f172a\",\n \"#0c4a6e\",\n \"#0c4a6e\",\n \"#7dd3fc\",\n ],\n blossom: [\n \"#fffaff\",\n \"#500724\",\n \"#db2777\",\n \"#f9a8d4\",\n \"#fbcfe8\",\n \"#fdf2f8\",\n \"#db2777\",\n \"#ffffff\",\n \"#fce7f3\",\n \"#fdf2f8\",\n \"#be185d\",\n ],\n};\n\nexport const COLOR_SCHEMES: Record<ColorSchemeName, ReactColorScheme> =\n Object.fromEntries(\n Object.entries(SCHEME_VALUES).map(([name, values]) => [\n name,\n Object.fromEntries(SCHEME_KEYS.map((key, i) => [key, values[i]!])),\n ]),\n ) as Record<ColorSchemeName, ReactColorScheme>;\n\nexport function resolveColorScheme(\n scheme?: ColorSchemeName | ReactColorScheme,\n): ReactColorScheme {\n if (scheme === undefined) return COLOR_SCHEMES.default;\n if (typeof scheme === \"string\") {\n return COLOR_SCHEMES[scheme] ?? COLOR_SCHEMES.default;\n }\n return scheme;\n}\n","import type {\n CalendarState,\n CalendarStateOptions,\n Direction,\n MonthDirection,\n} from \"@typescript-calendar-lib/tui\";\nimport {\n buildMonthData,\n clearSelection,\n createCalendarState,\n getCursorDate,\n getSelectedDate,\n goToToday,\n moveCursor,\n navigateMonth,\n rebuildState,\n resolveOptions,\n selectDate,\n} from \"@typescript-calendar-lib/tui\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nexport interface UseCalendarStateOptions\n extends Pick<\n CalendarStateOptions,\n \"locale\" | \"weekStart\" | \"today\" | \"highlight\" | \"range\"\n > {\n initialYear?: number;\n initialMonth?: number;\n}\n\nexport interface UseCalendarStateReturn {\n /** 現在のカレンダー状態 */\n state: CalendarState;\n /** カーソルを指定方向に移動 (wrap around) */\n moveCursor: (direction: Direction) => void;\n /** 前月/翌月へ移動 */\n goNext: () => void;\n goPrev: () => void;\n /** 今日の月へジャンプ */\n goToday: () => void;\n /** カーソル位置の日付を選択 */\n selectDate: () => void;\n /** 選択を解除 */\n clearSelection: () => void;\n /** カーソル位置の日付(null の場合あり) */\n cursorDate: Date | null;\n /** 選択済み日付(null の場合あり) */\n selectedDate: Date | null;\n}\n\n/** undefined を含む日付を値(時刻)で比較する */\nfunction sameDateValue(a: Date | undefined, b: Date | undefined): boolean {\n return (a?.getTime() ?? -1) === (b?.getTime() ?? -1);\n}\n\n/** オプションの「値」が等しいか比較する(Date は getTime、参照ではない) */\nfunction sameOptionsValue(\n a: UseCalendarStateOptions,\n b: UseCalendarStateOptions,\n): boolean {\n return (\n a.initialYear === b.initialYear &&\n a.initialMonth === b.initialMonth &&\n a.locale === b.locale &&\n a.weekStart === b.weekStart &&\n sameDateValue(a.today, b.today) &&\n sameDateValue(a.highlight, b.highlight) &&\n sameDateValue(a.range?.from, b.range?.from) &&\n sameDateValue(a.range?.to, b.range?.to)\n );\n}\n\n/**\n * tui の不変状態マシンを包む React hook。\n * カレンダーのインタラクティブ操作をシンプルに利用できる。\n *\n * `options` の値(locale / weekStart / today / highlight / range /\n * initialYear / initialMonth)が変わると、カーソル・選択を保ったまま\n * 状態が再構築される。比較は値(Date は getTime)で行うため、インラインで\n * オプションを渡しても値が同じなら再構築されない。\n *\n * `today` を省略した場合、最初に解決された値が状態に固定され、以降も\n * 引き継がれる(毎レンダリング `new Date()` を渡さなくてよい)。\n */\nexport function useCalendarState(\n options: UseCalendarStateOptions = {},\n): UseCalendarStateReturn {\n const [state, setState] = useState<CalendarState>(() =>\n createCalendarState({\n initialYear: options.initialYear,\n initialMonth: options.initialMonth,\n today: options.today,\n locale: options.locale,\n weekStart: options.weekStart,\n highlight: options.highlight,\n range: options.range,\n }),\n );\n\n // options の「値の変化」を検知して状態を再構築する。\n // 初回は prevOptions が同一なので何もしない。値が同じままの再レンダリング\n // でも何もしないため、インラインリテラルを毎回渡しても無限ループしない。\n const prevOptions = useRef(options);\n useEffect(() => {\n if (sameOptionsValue(prevOptions.current, options)) return;\n // initialYear/initialMonth は「初期値」。値が実際に変わった時だけ適用し、\n // 変わっていない場合はナビゲーション後の現在位置 (prev.year/month) を維持する\n // (options 変更で表示月が初期値に引き戻されるのを防ぐ)。\n const prevInitialYear = prevOptions.current.initialYear;\n const prevInitialMonth = prevOptions.current.initialMonth;\n prevOptions.current = options;\n setState((prev) => {\n const resolved = resolveOptions({\n // today が省略されたら前回の値を引き継ぐ(状態に固定された今日を維持)\n today: options.today ?? prev.options.today,\n locale: options.locale ?? prev.options.locale,\n weekStart: options.weekStart ?? prev.options.weekStart,\n highlight: options.highlight,\n range: options.range,\n });\n const year =\n options.initialYear !== undefined &&\n options.initialYear !== prevInitialYear\n ? options.initialYear\n : prev.year;\n const month =\n options.initialMonth !== undefined &&\n options.initialMonth !== prevInitialMonth\n ? options.initialMonth\n : prev.month;\n // 範囲外の month は rebuildState 側で正規化される(state と monthData の乖離を防ぐ)\n const monthData = buildMonthData(year, month, resolved);\n return rebuildState(\n year,\n month,\n prev.cursor,\n prev.selectedDate,\n resolved,\n monthData,\n );\n });\n }, [options]);\n\n return {\n state,\n moveCursor: useCallback(\n (direction: Direction) => setState((prev) => moveCursor(prev, direction)),\n [],\n ),\n goNext: useCallback(\n () => setState((prev) => navigateMonth(prev, \"next\")),\n [],\n ),\n goPrev: useCallback(\n () => setState((prev) => navigateMonth(prev, \"prev\")),\n [],\n ),\n goToday: useCallback(() => setState((prev) => goToToday(prev)), []),\n selectDate: useCallback(() => setState((prev) => selectDate(prev)), []),\n clearSelection: useCallback(\n () => setState((prev) => clearSelection(prev)),\n [],\n ),\n cursorDate: getCursorDate(state),\n selectedDate: getSelectedDate(state),\n };\n}\n\nexport type { Direction, MonthDirection };\n","import type { CalendarOptions } from \"@typescript-calendar-lib/core\";\nimport {\n buildMonthGrid,\n createDate,\n getMonthName,\n getWeekdayHeaders,\n} from \"@typescript-calendar-lib/core\";\nimport type { CSSProperties } from \"react\";\nimport { getCellClasses } from \"./cell-classes.ts\";\nimport type { CalendarSize } from \"./size.ts\";\nimport { buildSizeStyle, isSizeName } from \"./size.ts\";\nimport type {\n ColorSchemeName,\n ReactColorScheme,\n ReactTheme,\n ThemeName,\n} from \"./themes.ts\";\nimport { resolveColorScheme, resolveTheme } from \"./themes.ts\";\nimport \"./calendar.css\";\n\nexport type {\n CalendarCustomSize,\n CalendarSize,\n CalendarSizeName,\n} from \"./size.ts\";\n\nexport interface CalendarProps {\n year: number;\n month: number;\n locale?: CalendarOptions[\"locale\"];\n weekStart?: CalendarOptions[\"weekStart\"];\n highlight?: Date;\n /** 範囲強調 */\n range?: { from: Date; to: Date };\n /** 今日の基準日。カラースキームの today 着色に使用 */\n today?: Date;\n /** 見た目テーマ。既定は \"default\" */\n theme?: ThemeName | ReactTheme;\n /** カラースキーム。既定は \"default\" */\n colorScheme?: ColorSchemeName | ReactColorScheme;\n /** セルサイズ。既定は \"md\"。{ width, height } で自由に指定できる */\n size?: CalendarSize;\n /** root 要素に追加するスタイル。CSS変数(--cal-*)で自由に上書きできる */\n style?: CSSProperties;\n\n // ── インタラクション ──\n\n /** インタラクティブモードを有効にする。セルクリック・ホバー・キーボード選択が可能になる */\n interactive?: boolean;\n /** セルクリック時のコールバック */\n onDateClick?: (date: Date) => void;\n /** セルホバー時のコールバック */\n onDateHover?: (date: Date) => void;\n}\n\n/** 月カレンダーコンポーネント */\nexport function Calendar({\n year,\n month,\n locale = \"en\",\n weekStart = \"sunday\",\n highlight,\n range,\n today,\n theme = \"default\",\n colorScheme = \"default\",\n size = \"md\",\n style,\n interactive = false,\n onDateClick,\n onDateHover,\n}: CalendarProps) {\n const cellDate = (day: number): Date => createDate(year, month - 1, day);\n const cellClass = (day: number): string | undefined =>\n getCellClasses(cellDate(day), { today, highlight, range }) || undefined;\n\n const handleCellClick = (day: number) => {\n if (interactive && onDateClick) onDateClick(cellDate(day));\n };\n\n const handleCellHover = (day: number) => {\n if (interactive && onDateHover) onDateHover(cellDate(day));\n };\n\n return (\n <div\n className={`calendar ${resolveTheme(theme).className}${isSizeName(size) ? ` calendar-size-${size}` : \"\"}${interactive ? \" calendar-interactive\" : \"\"}`}\n style={{\n ...(resolveColorScheme(colorScheme) as CSSProperties),\n ...buildSizeStyle(size),\n ...style,\n }}\n >\n <div className=\"calendar-header\">\n <h2>\n {getMonthName(locale, month)} {year}\n </h2>\n </div>\n <table>\n <thead>\n <tr>\n {getWeekdayHeaders(locale, weekStart).map((day) => (\n <th key={day}>{day}</th>\n ))}\n </tr>\n </thead>\n <tbody>\n {buildMonthGrid(year, month, weekStart).map((row, i) => {\n if (row.every((d) => d === null)) return null;\n return (\n // biome-ignore lint/suspicious/noArrayIndexKey: 月グリッドは静的で並び順が変わらない\n <tr key={i}>\n {row.map((day, j) => {\n if (day === null)\n // biome-ignore lint/suspicious/noArrayIndexKey: パディングセルは位置が唯一の識別子\n return <td key={j} />;\n return (\n <td key={day} className={cellClass(day)}>\n {interactive ? (\n <button\n type=\"button\"\n className=\"calendar-day-btn\"\n onClick={() => handleCellClick(day)}\n onMouseEnter={() => handleCellHover(day)}\n tabIndex={0}\n aria-label={`${getMonthName(locale, month)} ${day}, ${year}`}\n >\n {day}\n </button>\n ) : (\n day\n )}\n </td>\n );\n })}\n </tr>\n );\n })}\n </tbody>\n </table>\n </div>\n );\n}\n\nexport default Calendar;\n\nexport type {\n UseCalendarStateOptions,\n UseCalendarStateReturn,\n} from \"./hooks.ts\";\nexport { useCalendarState } from \"./hooks.ts\";\nexport type {\n ColorSchemeName,\n ReactColorScheme,\n ReactTheme,\n ThemeName,\n} from \"./themes.ts\";\nexport {\n COLOR_SCHEMES,\n resolveColorScheme,\n resolveTheme,\n THEMES,\n} from \"./themes.ts\";\n"],"mappings":";;;;;;AAaA,SAAgB,eAAe,MAAY,SAAmC;CAC5E,MAAM,UAAoB,CAAC;CAC3B,MAAM,MAAM,KAAK,OAAO;CACxB,IAAI,QAAQ,KAAK,QAAQ,GAAG,QAAQ,KAAK,YAAY;CACrD,IAAI,QAAQ,SAAS,UAAU,MAAM,QAAQ,KAAK,GAAG,QAAQ,KAAK,UAAU;CAC5E,IAAI,QAAQ,aAAa,UAAU,MAAM,QAAQ,SAAS,GACxD,QAAQ,KAAK,cAAc;CAC7B,IAAI,QAAQ,SAAS,cAAc,MAAM,Q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AG;KACnC,UAAA,cACC,oBAAC,UAAD;MACE,MAAK;MACL,WAAU;MACV,eAAe,gBAAgB,GAAG;MAClC,oBAAoB,gBAAgB,GAAG;MACvC,UAAU;MACV,cAAY,GAAG,aAAa,QAAQ,KAAK,EAAE,GAAG,IAAI,IAAI;MAErD,UAAA;KACK,CAAA,IAER;IAEA,GAfK,GAeL;GAER,CAAC,EACC,GAxBK,CAwBL;EAER,CAAC,EACI,CAAA,CACF,EAAA,CAAA,CACJ;;AAET"}
package/package.json CHANGED
@@ -1,25 +1,40 @@
1
1
  {
2
2
  "name": "@typescript-calendar-lib/react",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
- "main": "src/index.tsx",
6
- "types": "src/index.tsx",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://github.com/nazozokc/typescript-calendar-lib"
8
+ },
9
+ "main": "./dist/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "development": "./src/index.tsx",
15
+ "default": "./dist/index.js"
16
+ },
17
+ "./calendar.css": "./dist/calendar.css"
18
+ },
7
19
  "files": [
8
- "src"
20
+ "dist"
9
21
  ],
10
22
  "dependencies": {
11
- "@typescript-calendar/core": "workspace:*",
12
- "@typescript-calendar/tui": "workspace:*"
23
+ "@typescript-calendar-lib/core": "0.3.0",
24
+ "@typescript-calendar-lib/tui": "0.3.0"
13
25
  },
14
26
  "devDependencies": {
15
27
  "@testing-library/react": "^16",
28
+ "@tsdown/css": "^0.23.0",
16
29
  "@types/react": "^19",
17
30
  "jsdom": "^26",
18
31
  "react-dom": "19.2.8",
19
32
  "vitest": "^5"
20
33
  },
21
34
  "peerDependencies": {
22
- "typescript": "^5",
23
35
  "react": "^19"
36
+ },
37
+ "scripts": {
38
+ "build": "tsdown"
24
39
  }
25
- }
40
+ }
@@ -1,22 +0,0 @@
1
- import { isDateInRange, isSameDay } from "@typescript-calendar/core";
2
-
3
- // ─── セル状態クラス ───────────────────────────────────────
4
-
5
- export interface CellStateOptions {
6
- today?: Date;
7
- highlight?: Date;
8
- range?: { from: Date; to: Date };
9
- }
10
-
11
- /** 日付セルの状態(週末・今日・ハイライト・範囲)に応じたCSSクラスを組み立てる */
12
- export function getCellClasses(date: Date, options: CellStateOptions): string {
13
- const { today, highlight, range } = options;
14
- const classes: string[] = [];
15
- if (date.getDay() === 0 || date.getDay() === 6) classes.push("is-weekend");
16
- if (today !== undefined && isSameDay(date, today)) classes.push("is-today");
17
- if (highlight !== undefined && isSameDay(date, highlight))
18
- classes.push("is-highlight");
19
- if (range !== undefined && isDateInRange(date, range))
20
- classes.push("is-in-range");
21
- return classes.join(" ");
22
- }
package/src/global.d.ts DELETED
@@ -1 +0,0 @@
1
- declare module "*.css";
package/src/hooks.ts DELETED
@@ -1,107 +0,0 @@
1
- import type {
2
- CalendarState,
3
- CalendarStateOptions,
4
- Direction,
5
- MonthDirection,
6
- } from "@typescript-calendar/tui";
7
- import {
8
- createCalendarState,
9
- getCursorDate,
10
- getSelectedDate,
11
- navigateMonth,
12
- clearSelection as tuiClearSelection,
13
- goToToday as tuiGoToToday,
14
- moveCursor as tuiMoveCursor,
15
- selectDate as tuiSelectDate,
16
- } from "@typescript-calendar/tui";
17
- import { useCallback, useMemo, useState } from "react";
18
-
19
- export interface UseCalendarStateOptions
20
- extends Pick<
21
- CalendarStateOptions,
22
- "locale" | "weekStart" | "today" | "highlight" | "range"
23
- > {
24
- initialYear?: number;
25
- initialMonth?: number;
26
- }
27
-
28
- export interface UseCalendarStateReturn {
29
- /** 現在のカレンダー状態 */
30
- state: CalendarState;
31
- /** カーソルを指定方向に移動 (wrap around) */
32
- moveCursor: (direction: Direction) => void;
33
- /** 前月/翌月へ移動 */
34
- goNext: () => void;
35
- goPrev: () => void;
36
- /** 今日の月へジャンプ */
37
- goToday: () => void;
38
- /** カーソル位置の日付を選択 */
39
- selectDate: () => void;
40
- /** 選択を解除 */
41
- clearSelection: () => void;
42
- /** カーソル位置の日付(null の場合あり) */
43
- cursorDate: Date | null;
44
- /** 選択済み日付(null の場合あり) */
45
- selectedDate: Date | null;
46
- }
47
-
48
- /**
49
- * tui の不変状態マシンを包む React hook。
50
- * カレンダーのインタラクティブ操作をシンプルに利用できる。
51
- */
52
- export function useCalendarState(
53
- options: UseCalendarStateOptions = {},
54
- ): UseCalendarStateReturn {
55
- const [state, setState] = useState<CalendarState>(() =>
56
- createCalendarState({
57
- initialYear: options.initialYear,
58
- initialMonth: options.initialMonth,
59
- today: options.today,
60
- locale: options.locale,
61
- weekStart: options.weekStart,
62
- highlight: options.highlight,
63
- range: options.range,
64
- }),
65
- );
66
-
67
- const move = useCallback((direction: Direction) => {
68
- setState((prev) => tuiMoveCursor(prev, direction));
69
- }, []);
70
-
71
- const goNext = useCallback(() => {
72
- setState((prev) => navigateMonth(prev, "next"));
73
- }, []);
74
-
75
- const goPrev = useCallback(() => {
76
- setState((prev) => navigateMonth(prev, "prev"));
77
- }, []);
78
-
79
- const goToday = useCallback(() => {
80
- setState((prev) => tuiGoToToday(prev));
81
- }, []);
82
-
83
- const select = useCallback(() => {
84
- setState((prev) => tuiSelectDate(prev));
85
- }, []);
86
-
87
- const clear = useCallback(() => {
88
- setState((prev) => tuiClearSelection(prev));
89
- }, []);
90
-
91
- const cursorDate = useMemo(() => getCursorDate(state), [state]);
92
- const selectedDate = useMemo(() => getSelectedDate(state), [state]);
93
-
94
- return {
95
- state,
96
- moveCursor: move,
97
- goNext,
98
- goPrev,
99
- goToday,
100
- selectDate: select,
101
- clearSelection: clear,
102
- cursorDate,
103
- selectedDate,
104
- };
105
- }
106
-
107
- export type { Direction, MonthDirection };