Code Monkey home page Code Monkey logo

kalendaryo's Introduction

Kalendaryo

Coverage Status Build Status npm npm license

Build flexible react date components using primitives βš›οΈ + πŸ“…fns

Problem

You want a date component that's:
βœ”οΈ Laid out the way you want
βœ”οΈ Functions the way you want
βœ”οΈ Flexible for your use case

This solution

Kalendaryo is an unopinionated React component for building calendars. It has no opinions about what your calendar component should look or function like but rather only helps you deal with those unique constraints by providing various variables your calendar component needs such as the calendar's state data and methods for getting(i.e. all the days in a month) and setting(i.e. selecting the date from a day) plus many more!

See the Basic Usage section to see how you can build a basic calendar component with Kalendaryo, or see the Examples section to see more examples built with Kalendaryo.


Table of Contents

Installation

This package expects you to have >= [email protected]

npm i -d kalendaryo // <-- for npm peeps
yarn add kalendaryo // <-- for yarn peeps

Basic Usage

// Step 1: Import the component
import Kalendaryo from 'kalendaryo'

// Step 2: Invoke and pass your desired calendar as a function in the render prop
const BasicCalendar = () => <Kalendaryo render={MyCalendar} />

// Step 3: Build your calendar!
function MyCalendar(kalendaryo) {
  const {
    getFormattedDate,
    getWeeksInMonth,
    getDayLabelsInWeek,
    setDatePrevMonth,
    setDateNextMonth,
    setSelectedDate
  } = kalendaryo

  const currentDate = getFormattedDate("MMMM YYYY")
  const weeksInCurrentMonth = getWeeksInMonth()
  const dayLabels = getDayLabelsInWeek()
  const selectDay = date => () => setSelectedDate(date)

  /* For this basic example we're going to build a calendar that has:
   *  1. A header where you have:
   *      1.1 Controls for moving to the previous/next month of the current date
   *      1.2 A label for current month & year of the current date
   *  2. A body where you have:
   *      2.1 A row for the label of the days of a week
   *      2.2 Rows containing the days of each week in the current date's month where you can:
   *          2.2.1 Select a date by clicking on a day
   */
  return (
    <div className="my-calendar">
      // (1)
      <div className="my-calendar-header">
        // (1.1)
        <button onClick={setDatePrevMonth}>&larr;</button>

        // (1.2)
        <span className="text-white">{currentDate}</span>

        // (1.1)
        <button onClick={setDateNextMonth}>&rarr;</button>
      </div>

      // (2)
      <div className="my-calendar-body">
        // (2.1)
        <div className="week day-labels">
          {dayLabels.map(label => (
            <div key={label} className="day">{label}</div>
          ))}
        </div>

        // (2.2)
        {weeksInCurrentMonth.map((week, i) => (
          <div className="week" key={i}>
            {week.map(day => (
              <div
                key={day.label}
                // (2.2.1)
                onClick={selectDay(day.dateValue)}
              >
                {day.label}
              </div>
            ))}
          </div>
        ))}
      </div>
    </div>
  )
}

See this basic usage snippet in action here!

API

This section contains descriptions of the various things the <Kalendaryo /> component has to offer which are split into three parts:

  • state: Description of the component's state that could change
  • props: Description of the component's props that you can change or hook into
  • methods: Description of the component's various helper methods you can use from the render prop

State

#date

type: Date
default: new Date()

Is the state for the current date the component is in. By convention, this should only change when the calendar changes its current date, i.e. moving to and from a month or year on the calendar.

#selectedDate

type: Date
default: new Date()

Is the state for the selected date on the component. By convention, this should only change when the calendar receives a date selection input from the user, i.e. selecting a day on the calendar.

Props

#startCurrentDateAt

type: Date
required: false
default: new Date()

Modifies the initial value of #date. Great for when you want your calendar to boot up in some date other than today.

Note: Passing non-Date types to this prop sets the #date state to today.

const birthday = new Date(1995, 4, 27)

<Kalendaryo startCurrentDateAt={birthday} />

#startSelectedDateAt

type: Date
required: false
default: new Date()

Modifies the initial value of #selectedDate. Great for when you want your calendar's selected date to boot up in another date than today.

Note: Passing non-Date types to this prop sets the #selectedDate state to today.

const birthday = new Date(1988, 4, 27)

<Kalendaryo startSelectedDateAt={birthday} />

#defaultFormat

type: String
required: false
default: 'MM/DD/YY'

Modifies the default format value on the #getFormattedDate method. Accepts any format that date-fns' format function can support.

const myFormat = 'yyyy-mm-dd'

<Kalendaryo defaultFormat={myFormat} />

#startWeekAt

type: Number[0..6]
required: false
default: 0

Modifies the starting day index of the weeks returned from #getWeeksInMonth & #getDayLabelsInWeek. Defaults to 0 (sunday)

const monday = 1

<Kalendaryo startWeekAt={monday} />

#onChange

type: func(state: Object): void
required: false

Callback prop for listening to state changes on the #date & #selectedDate states.

const logState = (state) => console.log(state)

<Kalendaryo onChange={logState}/>

#onDateChange

type: func(date: Date): void
required: false

Callback prop for listening to state changes only to the #date state.

const logDateState = (date) => console.log(date)

<Kalendaryo onDateChange={logDateState} />

#onSelectedChange

type: func(date: Date): void
required: false

Callback prop for listening to state changes only to the #selectedDate state.

const logSelectedDateState = (selectedDate) => console.log(selectedDate)

<Kalendaryo onSelectedChange={logSelectedDateState} />

#render

type: func(props: Object): void
required: true

Callback prop responsible for rendering the date component. This function receives an object which has the state, methods, as well as props you pass that are invalid(see passing variables to the render prop for more information).

const MyCalendar = (kalendaryo) => {
  console.log(kalendaryo)
  return <p>Some layout</p>
}

<Kalendaryo render={MyCalendar} />

Passing variables to the render prop

Sometimes you may need to have states other than the #date and #selectedDate state, i.e for a date range calendar component, you may need to have a state for its startDate and endDate and may need to create the calendar component as a method inside the date range calendar's class like so:

class DateRangeCalendar extends React.Component {
  state = {
    startDate: null,
    endDate: null
  }

  Calendar = (props) => {
    const { startDate, endDate } = this.state
    return // Your calendar layout
  }

  setDateRange = (selectedDate) => {
    // Logic for updating the start and end date states
  }

  render() {
    return <Kalendaryo onSelectedChange={this.setDateRange} render={this.Calendar} />
  }
}

This however, leaves the Calendar component tightly coupled to the DateRangeCalendar component and makes it a little bit harder for us to keep track of what's going on with what.

If only we could separate the DateRangeCalendar's state logic and Calendar's UI rendering

To solve this, the Kalendaryo component can receive unknown props. These are props that gets passed to the render prop callback when it does not convey any meaning to the Kalendaryo component.

With unknown props we can pass any arbitrary variable to Kalendaryo as long as it does not know what to do with it i.e. the startDate and endDate states. We would then have no need to put the Calendar function inside of the DateRangeCalendar class since the states are now an injected dependency to the Calendar e.g

class DateRangeCalendar extends React.Component {
  state = {
    startDate: null,
    endDate: null
  }

  setDateRange = (selectedDate) => {
    // Logic for updating the start and end date states
  }

  render() {
    return (
      <Kalendaryo
        startDate={this.state.startDate}
        endDate={this.state.endDate}
        onSelectedChange={this.setDateRange}
        render={Calendar}
      />
    )
  }
}

function Calendar(props) {
  const { startDate, endDate } = props
  return // Your calendar component
}

With this, the Calendar and DateRangeCalendar are now separated to the things they're solely responsible for.

Methods

#getFormattedDate

type: func(date?: Date | format?: String, format?: String): String
throws: Error exception when the types of the given argument are invalid

Returns the date formatted by the given format string. You can invoke this in four ways:

  • getFormattedDate() - Returns the #date state formatted as the value set on the #defaultFormat prop

  • getFormattedDate(date) - Returns the given date argument formatted as the value set on the #defaultFormat prop

  • getFormattedDate(format) - Returns the #date state formatted to the given format string argument

  • getFormattedDate(date, format) - Returns the given date argument formatted to the given format string argument

function MyCalendar(kalendaryo) {
  const birthday = new Date(1988, 4, 27)
  const myFormattedDate = kalendaryo.getFormattedDate(birthday, 'yyyy-mm-dd')

  return <p>My birthday is at {myFormattedDate}</p>
}

<Kalendaryo render={MyCalendar} />

#getDateNextMonth

type: func(date?: Date | amount?: Number, amount?: Number): Date
throws: Error exception when the types of the given argument are invalid

Returns a date with months added from the given amount. You can invoke this in four ways:

  • getDateNextMonth() - Returns the #date state with 1 month added to it

  • getDateNextMonth(date) - Returns the given date argument with 1 month added to it

  • getDateNextMonth(amount) - Returns the #date state with the months added to it from the given amount argument

  • getDateNextMonth(date, amount) - Returns the given date argument with the months added to it from the given amount argument

function MyCalendar(kalendaryo) {
  const nextMonth = kalendaryo.getDateNextMonth()
  const nextMonthFormatted = kalendaryo.getFormattedDate(nextMonth, 'MMMM')

  return <p>The next month from today is: {nextMonthFormatted}</p>
}

<Kalendaryo render={MyCalendar} />

#getDatePrevMonth

type: func(date?: Date | amount?: Number, amount?: Number): Date
throws: Error exception when the types of the given argument are invalid

Returns a date with months subtracted from the given amount. You can invoke this in four ways:

  • getDatePrevMonth() - Returns the #date state with 1 month subtracted to it

  • getDatePrevMonth(date) - Returns the given date argument with 1 month subtracted to it

  • getDatePrevMonth(amount) - Returns the #date state with the months subtracted to it from the given amount argument

  • getDatePrevMonth(date, amount) - Returns the given date argument with the months subtracted to it from the given amount argument

function MyCalendar(kalendaryo) {
  const prevMonth = kalendaryo.getDatePrevMonth()
  const prevMonthFormatted = kalendaryo.getFormattedDate(prevMonth, 'MMMM')

  return <p>The previous month from today is: {prevMonthFormatted}</p>
}

<Kalendaryo render={MyCalendar} />

#getDaysInMonth

type: func(date?: Date): DayObject[]
throws: Error exception when the types of the given argument are invalid

Returns an array of Day Objects for the month of a given date

  • getDaysInMonth() - Returns all the days in the month of the #date state

  • getDaysInMonth(date) - Returns all the days in the month of the given date argument

function MyCalendar(kalendaryo) {
  const nextMonth = kalendaryo.getDateNextMonth()
  const daysNextMonth = kalendaryo.getDaysInMonth(nextMonth)

  return (
    <div>
      {daysNextMonth.map((day) => (
        <p
          key={day.label}
          onClick={() => console.log(day.dateValue)}
        >
          {day.label}
        </p>
      ))}
    </div>
  )
}

<Kalendaryo render={MyCalendar} />

#getWeeksInMonth

type: func(date?: Date, startingDayIndex?: Number): Week[DayObject[]]
throws: Error exception when the types of the given argument are invalid

Returns an array of weeks, each containing their respective days for the month of the given date

  • getWeeksInMonth() - Returns an array of weeks for the month of the #date state, with the weeks starting at the value specified from the #startWeekAt prop

  • getWeeksInMonth(date) - Returns an array of weeks for the month of the given date argument, with the weeks starting at the value specified from the #startWeekAt prop

  • getWeeksInMonth(date, startingDayIndex) - Returns an array of weeks for the month of the given date argument, with the weeks starting at the value specified from the given startingDayIndex argument

function MyCalendar(kalendaryo) {
  const prevMonth = kalendaryo.getDatePrevMonth()
  const weeksPrevMonth = kalendaryo.getWeeksInMonth(prevMonth, 1)

  return (
    <div>
      {weeksPrevMonth.map((week, i) => (
        <div class="week" key={i}>
          {week.map((day) => (
            <p
              key={day.label}
              onClick={() => console.log(day.dateValue)}
            >
              {day.label}
            </p>
          ))}
        </div>
      ))}
    </div>
  )
}

<Kalendaryo render={MyCalendar} />

#getDayLabelsInWeek

type: func(dayLabelFormat?: String): String[]

Returns an array of strings for each day on a week

  • getDayLabelsInWeek() - Returns an array of each day on a week formatted as 'ddd' and starts on the week index based on the value set on the #startWeekAt prop

  • getDayLabelsInWeek(dayLabelFormat) - Returns an array of each day on a week formatted as the given dayLabelFormat argument and starts on the week index based on the value set on the #startWeekAt prop


#setDate

type: func(date: Date): void
throws: Error exception when the types of the given argument are invalid

Updates the #date state to the given date

function MyCalendar(kalendaryo) {
  const birthday = new Date(1988, 4, 27)
  const currentDate = kalendaryo.getFormattedDate()
  const setDateToBday = () => kalendaryo.setDate(birthday)

  return (
    <div>
      <p>The date is: {currentDate}</p>
      <button onClick={setDateToBday}>Set date to my birthday</button>
    </div>
  )
}

<Kalendaryo render={MyCalendar} />

#setSelectedDate

type: func(selectedDate: Date): void
throws: Error exception when the types of the given argument are invalid

Updates the #selectedDate state to the given selected date

function MyCalendar(kalendaryo) {
  const birthday = new Date(1988, 4, 27)
  const currentDate = kalendaryo.getFormattedDate()
  const selectedDate = kalendaryo.getFormattedDate(kalendaryo.selectedDate)
  const selectBdayDate = () => kalendaryo.setSelectedDate(birthday)

  return (
    <div>
      <p>The date is: {currentDate}</p>
      <p>The selected date is: {selectedDate}</p>
      <button onClick={selectBdayDate}>Set selected date to my birthday!</button>
    </div>
  )
}

<Kalendaryo render={MyCalendar} />

#pickDate

type: func(date: Date): void
throws: Error exception when the types of the given argument are invalid

Updates both the #date & #selectedDate state to the given date

function MyCalendar(kalendaryo) {
  const birthday = new Date(1988, 4, 27)
  const currentDate = kalendaryo.getFormattedDate()
  const selectedDate = kalendaryo.getFormattedDate(kalendaryo.selectedDate)
  const selectBday = () => kalendaryo.pickDate(birthday)

  return (
    <div>
      <p>The date is: {currentDate}</p>
      <p>The selected date is: {selectedDate}</p>
      <button onClick={selectBday}>Set date and selected date to my birthday!</button>
    </div>
  )
}

<Kalendaryo render={MyCalendar} />

#setDateNextMonth

type: func(): void

Updates the #date state by adding 1 month

function MyCalendar(kalendaryo) {
  const formattedDate = kalendaryo.getFormattedDate()
  return (
    <div>
      <p>The date today is {formattedDate}</p>
      <button onClick={kalendaryo.setDateNextMonth}>Click to set date to the next month</button>
    </div>
  )
}

#setDatePrevMonth

type: func(): void

Updates the #date state by subtracting 1 month

function MyCalendar(kalendaryo) {
  const formattedDate = kalendaryo.getFormattedDate()
  return (
    <div>
      <p>The date today is {formattedDate}</p>
      <button onClick={kalendaryo.setDatePrevMonth}>Click to set date to the previous month</button>
    </div>
  )
}

Examples

Inspiration

This project is heavily inspired from Downshift by Kent C. Dodds, a component library that uses render props to expose certain APIs for you to build flexible and accessible autocomplete, dropdown, combobox, etc. components.

Without it, I would not have been able to create this very first OSS project of mine, so thanks Mr. Dodds and Contributors for it! ❀️

kalendaryo's People

Contributors

dependabot[bot] avatar donysukardi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

kalendaryo's Issues

Add more examples

Hi! I'm looking for anyone who can add in more examples of Kalendaryo in use to the examples section of the docs. Open to anyone, just send a PR with the link of your example on the docs and follow these two rules:

Your examples must be...

  1. In Codesandbox
  2. Unique(design-wise or functionality-wise) from other examples

Happy hacking! πŸŽƒ

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


No npm token specified.

An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.