@vladislav-rsh/calendar
v0.2.0
Published
Reusable React calendar component and date helpers.
Maintainers
Readme
@vladislav-rsh/calendar
Reusable React calendar component and date helpers.
Русская версия
Описание
@vladislav-rsh/calendar - React-библиотека для отображения календаря месяца и выбора даты. В пакет входит готовый компонент Calendar, хук useCalendar для собственной разметки календаря и набор date helpers для работы с днями, месяцами, годами, названиями месяцев и дней недели. Библиотека поддерживает локализацию через стандартный Intl, выбор первого дня недели, controlled и uncontrolled сценарии выбора даты, Tailwind-стилизацию через classNames и unstyled, а также поставляется с TypeScript-типами и отдельным CSS-файлом.
Установка
Из npm:
npm install @vladislav-rsh/calendarПакет использует react и react-dom как peer dependencies. Они должны быть установлены в вашем приложении.
Из GitHub Packages:
npm config set @vladislav-rsh:registry https://npm.pkg.github.com
npm install @vladislav-rsh/calendarGitHub Packages использует отдельное имя @vladislav-rsh/calendar, потому что npm-пакеты в GitHub Packages должны быть опубликованы под GitHub scope владельца репозитория.
Использование
Импортируйте компонент и стили:
import { useState } from 'react';
import { Calendar } from '@vladislav-rsh/calendar';
import '@vladislav-rsh/calendar/style.css';
export function Example() {
const [selectedDate, setSelectedDate] = useState(new Date());
return (
<Calendar
locale="ru-RU"
selectedDate={selectedDate}
onDateSelect={setSelectedDate}
weekStartsOn={1}
/>
);
}Tailwind CSS
Если вы хотите полностью стилизовать календарь через Tailwind, включите unstyled и передайте классы для нужных слотов:
<Calendar
unstyled
className="w-full max-w-sm rounded-2xl border border-slate-200 bg-white p-4"
classNames={{
header: 'mb-4 flex items-center justify-between gap-2',
navButton: 'inline-flex h-9 w-9 items-center justify-center rounded-lg bg-slate-100 text-slate-700 hover:bg-slate-200',
title: 'flex items-baseline gap-2 text-lg font-semibold capitalize',
month: 'text-slate-900',
year: 'text-slate-500',
weekdays: 'mb-2 grid grid-cols-7 gap-1',
weekday: 'text-center text-xs font-medium text-slate-500',
grid: 'grid grid-cols-7 gap-1',
day: 'aspect-square rounded-lg text-sm hover:bg-slate-100',
daySelected: 'bg-blue-600 text-white hover:bg-blue-600',
dayToday: 'ring-1 ring-amber-500',
emptyDay: 'aspect-square',
}}
/>Доступные ключи classNames: root, header, navButton, title, month, year, weekdays, weekday, grid, day, daySelected, dayToday, emptyDay.
Свойства Calendar
| Prop | Тип | По умолчанию | Описание |
| --- | --- | --- | --- |
| locale | string | 'en-US' | Локаль для названий месяцев, дней недели и доступных подписей дат. |
| selectedDate | Date | текущая дата | Выбранная дата. Если передана, компонент работает как controlled component. |
| onDateSelect | (date: Date) => void | undefined | Вызывается при выборе дня. |
| weekStartsOn | 0 \| 1 | 1 | Первый день недели: 0 - воскресенье, 1 - понедельник. |
| className | string | '' | Дополнительный CSS-класс для корневого элемента календаря. |
| classNames | CalendarClassNames | {} | Классы для отдельных частей календаря. |
| unstyled | boolean | false | Отключает встроенные стили и позволяет полностью стилизовать календарь самостоятельно. |
Public API
import {
Calendar,
CalendarClassNames,
createDate,
createMonth,
createYear,
getMonthNames,
getMonthNumberOfDays,
getWeekDaysNames,
getWeekNumber,
useCalendar,
} from '@vladislav-rsh/calendar';Пакет также экспортирует TypeScript-типы:
import type {
CalendarProps,
CreateDateParams,
CreateMonthParams,
CreateYearParams,
UseCalendarParams,
WeekStartsOn,
} from '@vladislav-rsh/calendar';Стили
Базовые стили календаря доступны отдельным импортом:
import '@vladislav-rsh/calendar/style.css';Разработка
npm run lint
npm test
npm run build
npm run pack:dry-runnpm run build собирает ESM, CommonJS, CSS и TypeScript declarations в папку dist.
Публикация
Пакет готов к публикации в npm и GitHub Packages через GitHub Actions:
Publish to npmпубликует@vladislav-rsh/calendarв npm registry.Publish to GitHub Packagesпубликует тот же пакет как@vladislav-rsh/calendarв GitHub Packages, чтобы он отображался в разделе Packages репозитория.
Перед первым npm-релизом нужно создать automation token в npm и добавить его в GitHub repository secrets как NPM_TOKEN. Затем обновите версию в package.json, создайте GitHub Release, и workflows опубликуют пакет автоматически.
Лицензия
MIT.
English version
Description
@vladislav-rsh/calendar is a lightweight React library for rendering a monthly calendar and selecting dates. It works well for forms, dashboards, account pages, and other interfaces that need a simple calendar without a heavy datepicker toolkit. For full Tailwind-based styling, the package exposes per-slot class names and an unstyled mode.
The package includes a ready-to-use Calendar component, a useCalendar hook for custom calendar layouts, and date helpers for days, months, years, month names, and weekday names. It supports locales through the standard Intl API, configurable week starts, controlled and uncontrolled date selection, TypeScript types, and a separate CSS file.
Installation
From npm:
npm install @vladislav-rsh/calendarThe package uses react and react-dom as peer dependencies. They must be installed in your application.
From GitHub Packages:
npm config set @vladislav-rsh:registry https://npm.pkg.github.com
npm install @vladislav-rsh/calendarGitHub Packages uses the separate @vladislav-rsh/calendar name because npm packages in GitHub Packages must be published under the repository owner's GitHub scope.
Usage
Import the component and styles:
import { useState } from 'react';
import { Calendar } from '@vladislav-rsh/calendar';
import '@vladislav-rsh/calendar/style.css';
export function Example() {
const [selectedDate, setSelectedDate] = useState(new Date());
return (
<Calendar
locale="en-US"
selectedDate={selectedDate}
onDateSelect={setSelectedDate}
weekStartsOn={1}
/>
);
}Tailwind CSS
If you want to fully style the calendar with Tailwind, enable unstyled and pass classes for the required slots:
<Calendar
unstyled
className="w-full max-w-sm rounded-2xl border border-slate-200 bg-white p-4"
classNames={{
header: 'mb-4 flex items-center justify-between gap-2',
navButton: 'inline-flex h-9 w-9 items-center justify-center rounded-lg bg-slate-100 text-slate-700 hover:bg-slate-200',
title: 'flex items-baseline gap-2 text-lg font-semibold capitalize',
month: 'text-slate-900',
year: 'text-slate-500',
weekdays: 'mb-2 grid grid-cols-7 gap-1',
weekday: 'text-center text-xs font-medium text-slate-500',
grid: 'grid grid-cols-7 gap-1',
day: 'aspect-square rounded-lg text-sm hover:bg-slate-100',
daySelected: 'bg-blue-600 text-white hover:bg-blue-600',
dayToday: 'ring-1 ring-amber-500',
emptyDay: 'aspect-square',
}}
/>Available classNames keys: root, header, navButton, title, month, year, weekdays, weekday, grid, day, daySelected, dayToday, emptyDay.
Calendar props
| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| locale | string | 'en-US' | Locale for month names, weekday names, and accessible date labels. |
| selectedDate | Date | current date | Selected date. When provided, the component works as a controlled component. |
| onDateSelect | (date: Date) => void | undefined | Called when a day is selected. |
| weekStartsOn | 0 \| 1 | 1 | First day of week: 0 for Sunday, 1 for Monday. |
| className | string | '' | Extra CSS class for the calendar root element. |
| classNames | CalendarClassNames | {} | Classes for individual calendar slots. |
| unstyled | boolean | false | Disables built-in styles and lets you fully style the calendar yourself. |
Public API
import {
Calendar,
CalendarClassNames,
createDate,
createMonth,
createYear,
getMonthNames,
getMonthNumberOfDays,
getWeekDaysNames,
getWeekNumber,
useCalendar,
} from '@vladislav-rsh/calendar';The package also exports TypeScript types:
import type {
CalendarProps,
CreateDateParams,
CreateMonthParams,
CreateYearParams,
UseCalendarParams,
WeekStartsOn,
} from '@vladislav-rsh/calendar';Styles
Base calendar styles are available through a separate import:
import '@vladislav-rsh/calendar/style.css';Development
npm run lint
npm test
npm run build
npm run pack:dry-runnpm run build emits ESM, CommonJS, CSS, and TypeScript declarations into dist.
Publishing
The package is ready to publish to npm and GitHub Packages through GitHub Actions:
Publish to npmpublishes@vladislav-rsh/calendarto the npm registry.Publish to GitHub Packagespublishes the same package as@vladislav-rsh/calendarto GitHub Packages so it appears in the repository Packages section.
Before the first npm release, create an npm automation token and add it to GitHub repository secrets as NPM_TOKEN. Then update the version in package.json, create a GitHub Release, and the workflows will publish the package automatically.
License
MIT.
