npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

kliui-date-picker-library

v1.0.2

Published

library for date pickers

Downloads

7

Readme

Tестовое задание библиотека Modsen DatePicker

About the library

This library allows you to add a calendar to your application. It is also possible to add functionality to the calendar using various decorators.

Installation

For the library to work correctly you need:

  • install the styled-components package via npm or yarn:
npm install styled-components
yarn add styled-components
  • install the package via npm or yarn:
npm install @lkvasikl/modsen-datepicker-library
yarn add @lkvasikl/modsen-datepicker-library

Usage

import ReactDOM from "react-dom/client";
import {
  CalendarConfigurator,
  withMondaysFirst,
  withRange,
  withTodos,
  DateProvider,
  Calendar,
  DatePicker,
} from "kliui-date-picker-library";

const root = ReactDOM.createRoot(document.getElementById("root"));

const calendarService = new CalendarConfigurator(Calendar);
calendarService.addDecorator(withMondaysFirst);
calendarService.addDecorator(withRange, { rangeStart: new Date() });
calendarService.addDecorator(withTodos);

const CalendarPicker = calendarService.getDecorator();

root.render(
  <>
    <DateProvider>
      <DatePicker Calendar={CalendarPicker} />
    </DateProvider>

    <DateProvider>
      <Calendar withWeekdays={true} rangeStart={new Date()} />
    </DateProvider>
  </>
);

CalendarService:

A class that has two methods:

  1. getDecorator() - allows you to get a decorated calendar component;
  2. addDecorator(decorator) - allows you to add functionality to your calendar.

Functionality description [decorator]:

  • withMondayFirst: for displaying calendar weekdays starting from Monday. By default - Sunday;
  • withHolidays: allows you to highlight holidays with blue color;
  • withMinAndMaxDate: allows to set restrictions for dates (min and/or max);
  • withoutWeekdays: weekdays are hidden;
  • withRange: adds the ability to display a range of dates on the calendar;
  • withTodos: adds the ability to add and interact with a to-do list;

To use the calendar, you MUST wrap the component in DateProvider:

<DateProvider>
  <Calendar withTodos={true} />
</DateProvider>

Usage variants:

There are two options of usage available:

  1. You can use Calendar Component and pass all settings as props:
import {
  DateProvider,
  Calendar,
} from "kliui-date-picker-library";

...
<DateProvider>
  <Calendar withTodos={true} minDate={new Date()} />
</DateProvider>;
  1. You can use DatePicker Component and set options of Calendar with decorators:
import {
  DateProvider,
  Calendar,
  CalendarConfigurator,
  withRange,
  withTodos
} from "kliui-date-picker-library";

const calendarService = new CalendarConfigurator(Calendar);
calendarService.addDecorator(withRange, { rangeStart: new Date() });
calendarService.addDecorator(withTodos);

const CalendarPicker = calendarService.getDecorator();

...
<DateProvider>
    <DatePicker Calendar={CalendarPicker} />
</DateProvider>;

Содержание

Техническое задание

Необходимо реализовать библиотеку Javascript - DatePicker, для работы с различными видами календаря. Цель состоит в том, чтобы создать базовую библиотеку, которую можно настраивать и расширять.

Необходимый функционал:

  • Просмотр календаря;
  • Выбор диапазона для календаря;
  • Дефолтный календарь с заранее установленным диапазоном;
  • Возможность выбора начала недели(с понедельника или воскресенья);
  • Выбор вида календаря (по неделям, месяцам и т.д.);
  • Реализовать возможность при клике на определенный день добавлять список задач и сохранять их в localStorage;
  • Возможность переключения на предыдущий(ую)/следующий(ую) неделю/месяц/год;
  • Возможность выбора максимальной даты календаря;
  • Возможность выбора минимальной даты для календаря;
  • Возможность скрывать/показывать выходные дни и выделять праздничные дни другим цветом;
  • Возможность перейти в календаре на введенную пользователем дату;
  • Стилизация календаря.

Дополнительный функционал:

  • Развернуть приложение на хостинге (heroku, vercel);
  • Настроить CI/CD, используя GitHub Actions;
  • Собрать проект с нуля(с настройками всех конфигов: rollup, eslint, prettier, husky).

Пример графического представления:

Ссылка на макет: Макет "DatePicker".

Также проект предполагает:

  • Придерживаться требований по написанию и организации кода react приложения. Ссылка на требования: Требования к тестовому заданию;

  • Разделить библиотеку на два основных компонента: представления и логики. Для реализации логики приложения необходимо использовать порождающий паттерн программирования "Декоратор", который позволяет динамически добавлять объектам новую функциональность, оборачивая их в полезные «обёртки» (см. подробнее паттерн Декоратор). При помощи паттерна создать сервисный класс, в котором вы будете задавать конфигурацию и создавать календарь;

  • Настроить конфигурации babel, eslint, prettier;

  • Подключить и настроить бандлер Rollup для сборки проекта в библиотеку;

  • Подключить и настроить Storybook для проверки работоспособности вашей библиотеки;

  • Добавить обработку ошибок через паттерн Error Boundaries;

  • Добавить проверку типов в React компонентах, передаваемых параметров и подобных объектов;

  • Использовать алиасы для импортирования файлов;

  • В приложении допускается использование языка typescript;

  • Нельзя использовать какие-либо сторонние библиотеки.

Используемые технологии

Для react

  • node.js - программная платформа, основанная на движке V8 (транслирующем JavaScript в машинный код);
  • babel - транспайлер, преобразующий код из одного стандарта в другой;
  • eslint - линтер для JavaScript кода;
  • yarn - менеджер пакетов;
  • rollup - сборщик ES-модулей;
  • storybook - инструмент, используемый для разработки компонентов пользовательского интерфейса в изоляции;
  • react - JavaScript-библиотека для создания пользовательских интерфейсов;
  • prop-types - набор валидаторов, которые могут быть использованы для проверки получаемых данных;
  • styled-components - система стилизации react компонентов;
  • jest — интеграционное тестирование (rtl) + unit-тестирование.

Для react native

Will be soon...

Структура проекта

Структура проекта

Тестирование

Реализовать e2e тестирование c полным покрытием функционала приложения:

  • Сервис для конфигурации DatePicker-компонента;
  • Графическое (компонент модуля и т.д.).

Полезные ссылки

React

Rollup

Storybook

Eslint

Babel

Тестирование Jest

Styled-components

Husky