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

@lkvasikl/modsen-datepicker-library

v1.1.1

Published

Date picker library

Downloads

13

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 {
  CalendarService,
  withWeekends,
  withMondayFirst,
  withHolidays,
  withRange,
  DateProvider,
  withTodos,
  DatePicker,
  CalendarProvider,
} from "@lkvasikl/modsen-datepicker-library";

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

const calendarService = new CalendarService();

calendarService.addDecorator(withMondayFirst);
calendarService.addDecorator(withHolidays);
calendarService.addDecorator(withWeekends);
calendarService.addDecorator(withRange);
calendarService.addDecorator(withTodos);

const Calendar = calendarService.getCalendar();

const renderApp = () => {
  root.render(
    <>
      <CalendarProvider>
        <DateProvider>
          <Calendar
            minDate={new Date(2023, 0, 1)}
            maxDate={new Date(2025, 11, 1)}
          />
        </DateProvider>
      </CalendarProvider>

      <CalendarProvider>
        <DatePicker label="Date" Calendar={Calendar} />
      </CalendarProvider>
    </>,
  );
};

renderApp();

CalendarService:

A class that has two methods:

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

For the calendar to work correctly, you MUST to wrap it in CalendarProvider.

const calendarService = new CalendarService();
const Calendar = calendarService.getCalendar();

<CalendarProvider>
  <Calendar />
</CalendarProvider>;

Functionality description [decorator]:

  • withMondayFirst: you can use this decorator to display the calendar weekdays starting from Monday. By default - Sunday;
  • withHolidays: allows you to display Belarusian holidays in orange;
  • withWeekends: weekends are highlighted in red;
  • 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;
  • Pass the props minDate to set the minimum date in the Calendar;
  • Pass the props maxDate to set the maximum date in the Calendar.

To set the minimum and maximum dates, you MUST wrap the component in DateProvider:

const calendarService = new CalendarService();
const Calendar = calendarService.getCalendar();

<CalendarProvider>
  <DateProvider>
    <Calendar minDate={new Date(2023, 0, 1)} maxDate={new Date(2025, 11, 1)} />
  </DateProvider>
</CalendarProvider>;

You can also use the ready-made DatePicker component. You need to pass the following props into it:

  1. label: text that will be displayed above the input field;
  2. Calendar: calendar obtained using the function getCalendar(). It can be wrapped in the necessary decorators.
const calendarService = new CalendarService();
const Calendar = calendarService.getCalendar();

<CalendarProvider>
  <DatePicker label="Date" Calendar={Calendar} />
</CalendarProvider>;

Содержание

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

Необходимо реализовать библиотеку 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