vigetlabs / ca11y

A lightweight accessible dependency-free datepicker
http://code.viget.com/ca11y
26 stars 6 forks source link

Allow Configurable `Parse` and `Format` Methods #20

Closed solomonhawk closed 8 years ago

solomonhawk commented 8 years ago

Related to #13

Purpose:

Allow users to override the default date parsing and formatting that Ca11y does.

Implementation:

This could be entirely left to userland code as Dan outlined in #13.

import Ca11y     from 'ca11y'
import strftime  from 'strftime'

const myInput = document.querySelector('.input')

// user defines format/parse methods and is responsible for calling them
function format(date) {
  return strftime('%F %T', date) // simple e.g.
}

function parse(str) {
  const date = new Date(str) // simple e.g.

  return { 
    valid: !isNaN(date), // basic validation
    date: date
  }
}

function createChangeHandler(instance) {
  return function onChange(e) {
    const result = parse(e.target.value)

    if (result.valid) {
      instance.setDate(result.date)
    }
  }
}

const options = {
  // when a day is selected, propagate the change back to the input
  onDaySelected(date) {
    myInput.value = format(date)
  }
}

// create a new Ca11y instance, lib is responsible for merging defaults with options
const calendar = new Ca11y(options)

// tie changes to the input back to Ca11y
myInput.addEventListener('change', createChangeHandler(calendar), false)
greypants commented 8 years ago

I think I would like to include some parse methods that could be modularly imported and used. something like import parse from 'ca11y/parse'

greypants commented 8 years ago

In addition to returning the js date object, I'm going to return the following key/value pairs that should make it pretty easy to format your date however you want.

key value
d Day of the month as digits; no leading zero for single-digit days.
dd Day of the month as digits; leading zero for single-digit days.
ddd Day of the week as a three-letter abbreviation.
dddd Day of the week as its full name.
m Month as digits; no leading zero for single-digit months.
mm Month as digits; leading zero for single-digit months.
mmm Month as a three-letter abbreviation.
mmmm Month as its full name.
yy Year as last two digits; leading zero for years less than 10.
yyyy Year represented by four digits.

Format naming seems pretty universal, but I grabbed it from here specifically: http://blog.stevenlevithan.com/archives/date-time-format