Giter Site home page Giter Site logo

adrienpoly / stimulus-flatpickr Goto Github PK

View Code? Open in Web Editor NEW
404.0 5.0 29.0 2.1 MB

A modest, yet powerful wrapper of Flatpickr πŸ“† for Stimulus

License: MIT License

JavaScript 75.99% HTML 15.49% CSS 8.52%
stimulus stimulusjs flatpickr rails wrapper-library stimulus-controller

stimulus-flatpickr's Introduction

πŸ“† Stimulus-Flatpickr Wrapper

npm version CircleCi build status Coverage

Modest yet powerful wrapper of Flatpickr for Stimulus
Only ~1kb


  • Simple: create advanced datepickers with less code
  • Backend Friendly: easily pass backend information to the datepicker (locals, availabilities, date formats etc)
  • strftime friendly: converts automatically strftime formats to flatpickr formating tokens
  • Disable days of week: easily disable days of week (ie: all sundays)
  • Turbolinks: make all your datepickers compatible with Turbolinks by design
  • Getters: all Flatpickr elements are available as targets
  • Events/hooks: all flatpickr events/hooks are directly available in your Stimulus Controller.
  • Example: detailed example for adavanced usage of flatpickr
  • MIT Licensed: free for personal and commercial use

A modest wrapper of Flatpickr for Stimulus

By using this wrapper of Flatpickr for Stimulus you can make all configurations for the Datepicker directly with the data-attributes of the HTML. This makes it very handy to create datepicker with server generate html and pass information from the backend to the datepicker.

Here is a simple example:

<%= form_with model: Appointement.new, authenticity_token: true do |f| %>
  <%= f.text_field :start_time,
    data: {
      controller: "flatpickr",
      flatpickr_min_date: Time.zone.now #disables past dates
    } %>
<% end %>

πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡

datetime picker result

Example

An example of a Rails app showcasing

  • localization of the datepicker 🌍
  • localization of the date formats 🌍
  • availabilities in the date picker πŸ“…
  • Fully boosted with Turbolinks πŸš€

is available here : Rails Stimulus Flatpickr

Install

This assumes that you have Stimulus already installed. For Rails(5.1+) app please refer this doc (https://github.com/rails/webpacker/blob/master/docs/integrations.md#stimulus) to get started with Stimulus.

In your project just add the flatpickr and stimulus-flatpickr package.

yarn add flatpickr
yarn add stimulus-flatpickr

or

npm i flatpickr
npm i stimulus-flatpickr

Note: Do not use both yarn and npm to install packages, this might lead to an error: ...It is advised not to mix package managers in order to avoid resolution inconsistencies caused by unsynchronized lock files

Using importmap

./bin/importmap pin flatpickr stimulus-flatpickr@beta

Basic usage

If you only need to convert an input field in a DateTime picker, you just need to register a standard Stimulus controller and add some markup to your input field.

Register a Flatpickr Controller

manually register a new Stimulus controller in your main JS entry point.

// ./packs/application.js
import { Application } from 'stimulus'
import { definitionsFromContext } from 'stimulus/webpack-helpers'

const application = Application.start()
const context = require.context('../controllers', true, /\.js$/)
application.load(definitionsFromContext(context))

// import Flatpickr
import Flatpickr from 'stimulus-flatpickr'

// Import style for flatpickr
require("flatpickr/dist/flatpickr.css")

// Manually register Flatpickr as a stimulus controller
application.register('flatpickr', Flatpickr)

Note:

  • Setup: By Manually registering Flatpickr controller, you don't need to create a flatpickr_controller.js file. However, To add custom behavior you will have to create the flatpickr_controller.js file. Read more details about it below.
  • Style: You can always choose different theme for calender by requiring different .css file. You can find them inside your app's root directory node_modules/flatpickr/dist/themes
  • Deployment: In Production environment, include <%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> in your application.html.erb file in order to load the calendar style.

Using it with Rails

You can now create forms and input fields easily by adding a data-controller="flatpickr" attribute to the input fields and pass options with the Stimulus Controller states : data-flatpickr-the-option.

<%= form_with model: Appointement.new, authenticity_token: true do |f| %>
  <%= f.text_field :start_time,
    data: {
      controller: "flatpickr",
      flatpickr_date_format: "Y-m-d",
      flatpickr_min_date: Time.zone.now
    } %>
<% end %>

πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡

datetime picker result

Options & conventions

All options for Flatpickr can be found here.

All options are in camelCase (JS) and must be converted to lower_snake_case in the data-attribute. lower_snake_case is automatically converted to kebab-case when rails render the HTML.

<%= f.text_field :start_time,
  data: {
    controller: "flatpickr",
    flatpickr_enable_time: true
  }
} %>

will output this HTML:

<input data-controller="flatpickr" data-flatpickr-enable-time="true" type="text" name="appointement[start_time]" />

HTML markup

If you are not using Rails or simply wants to markup your HTML directly, simply add a html data-controller="flatpickr" to your input field and some options html data-flatpickr-some-option="value" options must be converted from camelCase to kebab-case

Advanced Usage

If you need more than just displaying the standard DateTime picker, then you can extend the stimulus-flatpickr wrapper controller. This is necessary when you need to:

  • set a custom language
  • create custom callbacks
  • perform JS business logic

Skip basics installation steps from above!

Extends the controller

create a new Stimulus controller that will inherit from stimulus-flatpickr

// ./controllers/flatpickr_controller.js
// import stimulus-flatpickr wrapper controller to extend it
import Flatpickr from 'stimulus-flatpickr'

// you can also import a translation file
import { French } from 'flatpickr/dist/l10n/fr.js'

// import a theme (could be in your main CSS entry too...)
import 'flatpickr/dist/themes/dark.css'

// create a new Stimulus controller by extending stimulus-flatpickr wrapper controller
export default class extends Flatpickr {
  initialize() {
    // sets your language (you can also set some global setting for all time pickers)
    this.config = {
      locale: French
    }
  }

  // all flatpickr hooks are available as callbacks in your Stimulus controller
  change(selectedDates, dateStr, instance) {
    console.log('the callback returns the selected dates', selectedDates)
    console.log('but returns it also as a string', dateStr)
    console.log('and the flatpickr instance', instance)
  }
}

Global settings for all datepickers

As we have seen just above you can easily from your rails erb code pass the flatpickr options. This is great for passing dynamic options that might change (ie enableDate, dateFormat etc).

If all your datepickers share some global settings you can define them in your initialize() or connect() function.

initialize() {
   //global options
    this.config = {
      enableTime: true,
      time_24hr: true
    };
  }

or with connect()

connect() {
   //global options
    this.config = {
      ...this.config, //spread options in case some where defined in initialize
      enableTime: true,
      time_24hr: true
    };

    //always call super.connect()
    super.connect();
  }

HTML markup

Then in the same way as above you can now create forms and input fields easily by adding a data-controller="flatpickr" attribute to the input fields and pass options with the Stimulus Controller states : data-flatpick-the-option.

<%= form_with model: Appointement.new, authenticity_token: true do |f| %>
  <%= f.text_field :start_time,
                    data: {
                      controller: "flatpickr",
                      flatpickr_date_format: "Y-m-d",
                      flatpickr_min_date: Time.zone.now }
  %>
  <% end %>

πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡

datetime picker result

Date and Time formats

Flatpickr has custom formatting tokens. in Rails (and other backends) formats are based on strftime standard.

This package automatically converts strftime datetime formats to the nearest Flatpickr format.

With this solution, it becomes handy to localize your date formats. t("date.formats.long") outputs "%B %d, %Y"for the local :en and it outputs "%e %B %Y" for the locale :fr.

<%= form_with model: appointment do |f| %>
  <%= f.text_field :start_at,
      data: {
        controller: "flatpickr",
        flatpickr_alt_format: t("date.formats.long"),
        flatpickr_alt_input: true,
        flatpickr_min_date: Time.zone.now,
      } %>
<% end %>

πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡

datetime picker result

Enable/Disable days of week

With Flatpickr to disable certain days of the week, you need to use the disable js function. Obviously passing a function through data-attributes is not easy πŸ˜„.

The wrapper introduce two new configuration options:

  • disableDaysOfWeek: pass an array of days to disable (all others are enabled)
  • enableDaysOfWeek: pass an array of days to enable (all others are disabled)
Code Result
   <%= form_with model: Appointement.new, authenticity_token: true do |f| %>
     <%= f.text_field :start_time,
       data: {
         controller: "flatpickr",
         flatpickr_disable_days_of_week: [5,6], #disables saturdays and sundays
         flatpickr_disable: ["2018-09-25", "2018-09-26"] #disables individual dates
       } %>
   <% end %>
   

datetime picker result days of week

Callbacks

All Flatpickr events/hooks are available as callbacks in the extended controller as demonstrated above for the onChange hook.

Just add the function to your Stimulus Controller in camelCase without on.

onChange -> change(){}

Instance and its methods

You can access the flatpickr instance from your Stimulus controller by calling this.fp. Also, the instance methods are available through this instance call.

yourFunction () {
  // ...
  this.fp.clear()
  this.fp.close()
}

Custom elements

If you want to display additional information on the calendar, you can wrap the Flatpickr controller arround custom elements. You can use the predefined target instance to attach the input element to the date picker.

Example:

<div data-controller="flatpickr">
  <!-- the flatpicker instance -->
  <input type="text" placeholder="Select Date.." data-flatpickr-target="instance" />
  <!-- the custom element -->
  <input type="text" data-flatpickr-target="custom" />
</div>

In the stimulus controller, add the target:

static targets = ['custom']

yourFunction () {
  //...
  this.customTarget
}

Getters

Elements

In your controller you can access the Flapickr elements using some Stimulus like targets.

this.calendarContainerTarget : Self-explanatory. This is the div.flatpickr-calendar element.

this.currentYearElementTarget: The input holding the current year.

this.daysTarget : The container for all the day elements.

this.daysContainerTarget : The container for all the day elements.

this.inputTarget : The text input element associated with flatpickr.

this.nextMonthNavTarget : The β€œright arrow” element responsible for incrementing the current month.

this.monthNavTarget : The container with the month navigation.

this.prevMonthNavTarget : The β€œleft arrow” element responsible for decrementing the current month.

this.selectedDateElemTarget: the selected date element.

this.todayDateElemTarget: today element.

this.weekdayContainerTarget: the container we all the days of the week.

Overriding connect & disconnect

if you need to override the connect function in the extended controller, you need to call super

connect(){
  // ...
  // define global settings as explained in the global settings section before super
  // ...

  // always call super.connect()
  super.connect();

  // ...
  // Your code can access this.fp flatpickr instance
  // ...
}

Internationalization

To handle multiple language to translate your datepicker and convert the date formats, you can have a look at the example app. stimulus-flatpickr makes it straight forward to handle locales.

CSS

This wrapper does not include any CSS. Flatpickr CSS should be loaded separately from the main Flatpickr package as you would normally do.

Contributing

Bug reports and pull requests are welcome.

To contribute:

Fork the project.

Install dependencies

$ yarn install

Start the test watcher

$ yarn test:watch

Running one-off test runs can be done with:

$ yarn test

You can test locally also the results with the playground project ./playground

$ yarn start:playground

Then :

πŸ‘ Write some tests

πŸ’ͺ Add your feature

πŸš€ Send a PR

License

This package is available as open source under the terms of the MIT License.

stimulus-flatpickr's People

Contributors

abhinaykumar avatar adrienpoly avatar dependabot[bot] avatar jgorman avatar kzkn avatar paydaylight avatar ramiro6 avatar tacman avatar thatosmk avatar thomasvanholder 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  avatar  avatar

stimulus-flatpickr's Issues

Initial value ignores the format specified

Hi! Thanks for this controller. Everything works for me apart from the formatting of the initial value. I am using the controller like this:

        <%= f.text_field :published_at,
          class: "form-text",
          data: {
            controller: "datetime-picker",
            datetime_picker_enable_time: true,
            datetime_picker_alt_format: "D, F j Y at h:i K",
            datetime_picker_date_format: "D, F j Y at h:i K",
            datetime_picker_time_24hr: false,
            datetime_picker_min_date: 10.years.ago
          } %>

When I select a date/time, it is formatted as expected in the text field. However when the flatpikr is first rendered, the current value of published_at is displayed as "2020-01-27 21:06:07 +0200" in the input field. How can I ensure that the initial value is formatted as "D, F j Y at h:i K" too? Thanks!

A way to pass a list of disabled days of week

Hey there. I had a case when I needed to disable Sundays on my calendar. Flatpickr handle this through a function passed to disabled configuration option.

Passing a function within data-attributes is not very convenient so I handled the case by passing a list of days to disable and override the initializer:

input data-controller="flatpickr" data-flatpickr-disabled-days-of-week="[0]"
initialize() {
  const disabled_days = this.element.dataset.flatpickrDisabledDaysOfWeek
  this.config = {}
  if (disabled_days)
    this.config.disable = [
      function(date) {
        return disabled_days.includes(date.getDay())
      }
    ]
}

I thing this pattern is rather common, but I'm not really sure on how of if it should be handled with a stimulus-flatpickr specific option.

Hope this helps.

Can this be used with the upcoming rails default of import maps?

This is not an issue, (at least at this point) - but more of a question.

I've spent quit a bit of time over the last few week looking at rails 7 alpha trying to gauge how hard it's going to be to move my 3 puny apps forward and what approach will cause the least amount of pain. I've tried both new rails 7 apps and trying to add the gems (cssbundling-rails, jsbundling-rails, import maps-rails) to a branch on an existing app.

Since the esbuild approach is more or less using node packages without webpacker, I have managed to get most stuff working in an existing app (or a new rails 6 demo/test app). My apps are mainly pure Rails with some stimulus.js.

I do use two stimulus wrapper apps. Stimulus-flatpickr and Stimulus-autocomplete. I haven't tried real hard, but I can't get either of them to work with the import maps option. There are configuration option that I have not tried (maybe a little over my head at this time) that may get it to work (preload??)

Since stimulus also exists outside of the rails world, maybe someone has the answer (will it work with import maps?). I don't think the flatpickr controller is registering/firing, but can't think of a way to verify that. Then there is the flatpickr.css dependency that has caused some problems if not set up right.

My importmap.rb file

# Pin npm packages by running ./bin/importmap

pin "application", preload: true
pin "@hotwired/stimulus", to: "https://ga.jspm.io/npm:@hotwired/[email protected]/dist/stimulus.js"
pin "@hotwired/stimulus-loading", to: "stimulus-loading.js"
pin_all_from "app/javascript/controllers", under: "controllers"
pin "stimulus-flatpickr", to: "https://ga.jspm.io/npm:[email protected]/dist/index.js"
pin "flatpickr", to: "https://ga.jspm.io/npm:[email protected]/dist/flatpickr.js"
# pin "stimulus", to: "https://ga.jspm.io/npm:[email protected]/dist/stimulus.js"

Hopefully Rails will have some upgrade procedures to lessen the pain, but this is a big jump (back to before webpacker!)

If someone can point me so some example/document, I'd be grateful.

Edit

Tried a few more things with no results just a different error

Exception with thrown value: Error: Unable to resolve specifier 'stimulus' from https://ga.jspm.io/npm:[email protected]/dist/index.js

Guss it want @hotwire/stimulus

this.fp should be available sooner

Suppose you want to do something like:

new Cleave(
  this.fp.altInput,
  {
    date: true,
    datePattern: ["m", "d", "Y"],
  }
);

If you put this in connect() then it'll re-run every time the element is re-added to the DOM, which seems to be erroneous, as event listeners persist across removal and re-adding to the DOM. So you just want to do this once, e.g. in initialize or onReady.

Input values are reset on going back/forward

The input values of flatpickr are reset to default value on first going back and on second return removed.
I have observed the issue on Safari, app with turbolinks and flatpickr with altInput.

Expected behaviour

flatpickr should keep last typed value on returning back
P.S. I haven't tested the issue on other environment yet

Stimulus 3.0 support

Hi, I am getting the following error when I try to compile:

ERROR in ./node_modules/stimulus-flatpickr/dist/index.m.js 1:0-38
Module not found: Error: Can't resolve 'stimulus' in '/Users/tabuna/develop/orchid-project/platform/node_modules/stimulus-flatpickr/dist'

This only happens on version 3 of the stimulus package.
Are there any plans to support this for the new version of the package?

Can't register flatpickr controller with Rails 7

On a rails 7 app, I can't load the custom flatpickr controller. The connect and change methods are not working:
app/javascript/controllers/flatpickr_controller.js:

import Flatpickr from 'stimulus-flatpickr'

// Connects to data-controller="flatpickr"
export default class extends Flatpickr {
  connect() {
		console.log("connected");
  }

	change(selectedDates, dateStr, instance) {
    console.log('the callback returns the selected dates', selectedDates)
    console.log('but returns it also as a string', dateStr)
    console.log('and the flatpickr instance', instance)
  }
}

app/javascript/controllers/application.js:

import { Application } from "@hotwired/stimulus"

const application = Application.start()

// Configure Stimulus development experience
application.debug = false
window.Stimulus   = application

export { application }

// import Flatpickr
import Flatpickr from 'stimulus-flatpickr'

// Manually register Flatpickr as a stimulus controller
application.register('flatpickr', Flatpickr)

HTML:

<%= form_with url: "/fetch_total_expenses" do |f| %>
			<%= f.text_field :fetch_total_expenses,
					data: {
						controller: "flatpickr",
						flatpickr_date_format: "Y-m-d",
						flatpickr_max_date: Time.zone.now,
						mode: "range",
						flatpickr_default_date: [params[:start],params[:end]]
					} %>
		<% end %>

Any idea why I can't override the flatpickr controller? Thanks for your help.

Question: Copy one flatpickr input field to another

What would be the best way, that when one input field changes it updates another input field with the the same Date/Time values? This would be a one way copy β€” where the other field can then be changed independently.

I tried create a mimic stimulus controller that would copy the value on input, however this doesn't work β€” and I'm also using the altInput so there are other DOM elements in the input tag to facilitate the formatted date.

Could not find a declaration file for module 'stimulus-flatpickr'

Hi, I tried importing the stimulus-flatpickr for my rails app but at the time of compilation it returns an error like this:

00:13:37 webpack.1 | ERROR in ./node_modules/stimulus-flatpickr/dist/index.m.js
00:13:37 webpack.1 | Module not found: Error: Can't resolve 'flatpickr' in '/XYZ/XYZ/node_modules/stimulus-flatpickr/dist'
00:13:37 webpack.1 | resolve 'flatpickr' in '/XYZ/XYZ/node_modules/stimulus-flatpickr/dist'
00:13:37 webpack.1 |   Parsed request is a module
00:13:37 webpack.1 |   using description file: /XYZ/XYZ/node_modules/stimulus-flatpickr/package.json (relative path: ./dist)
00:13:37 webpack.1 |     Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |     resolve as module
00:13:37 webpack.1 |       looking for modules in /XYZ/XYZ/app/javascript
00:13:37 webpack.1 |         using description file: /XYZ/XYZ/package.json (relative path: ./app/javascript)
00:13:37 webpack.1 |           Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |           using description file: /XYZ/XYZ/package.json (relative path: ./app/javascript/flatpickr)
00:13:37 webpack.1 |             no extension
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/app/javascript/flatpickr doesn't exist
00:13:37 webpack.1 |             .tsx
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/app/javascript/flatpickr.tsx doesn't exist
00:13:37 webpack.1 |             .ts
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/app/javascript/flatpickr.ts doesn't exist
00:13:37 webpack.1 |             .mjs
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/app/javascript/flatpickr.mjs doesn't exist
00:13:37 webpack.1 |             .js
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/app/javascript/flatpickr.js doesn't exist
00:13:37 webpack.1 |             .sass
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/app/javascript/flatpickr.sass doesn't exist
00:13:37 webpack.1 |             .scss
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/app/javascript/flatpickr.scss doesn't exist
00:13:37 webpack.1 |             .css
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/app/javascript/flatpickr.css doesn't exist
00:13:37 webpack.1 |             .module.sass
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/app/javascript/flatpickr.module.sass doesn't exist
00:13:37 webpack.1 |             .module.scss
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/app/javascript/flatpickr.module.scss doesn't exist
00:13:37 webpack.1 |             .module.css
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/app/javascript/flatpickr.module.css doesn't exist
00:13:37 webpack.1 |             .png
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/app/javascript/flatpickr.png doesn't exist
00:13:37 webpack.1 |             .svg
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/app/javascript/flatpickr.svg doesn't exist
00:13:37 webpack.1 |             .gif
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/app/javascript/flatpickr.gif doesn't exist
00:13:37 webpack.1 |             .jpeg
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/app/javascript/flatpickr.jpeg doesn't exist
00:13:37 webpack.1 |             .jpg
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/app/javascript/flatpickr.jpg doesn't exist
00:13:37 webpack.1 |             as directory
00:13:37 webpack.1 |               /XYZ/XYZ/app/javascript/flatpickr doesn't exist
00:13:37 webpack.1 |       /XYZ/XYZ/node_modules/stimulus-flatpickr/dist/node_modules doesn't exist or is not a directory
00:13:37 webpack.1 |       /XYZ/XYZ/node_modules/stimulus-flatpickr/node_modules doesn't exist or is not a directory
00:13:37 webpack.1 |       /XYZ/XYZ/node_modules/node_modules doesn't exist or is not a directory
00:13:37 webpack.1 |       /XYZ/XYZ/node_modules doesn't exist or is not a directory
00:13:37 webpack.1 |       /XYZ/XYZ/node_modules doesn't exist or is not a directory
00:13:37 webpack.1 |       /Users/node_modules doesn't exist or is not a directory
00:13:37 webpack.1 |       /node_modules doesn't exist or is not a directory
00:13:37 webpack.1 |       looking for modules in /XYZ/XYZ/node_modules
00:13:37 webpack.1 |         using description file: /XYZ/XYZ/package.json (relative path: ./node_modules)
00:13:37 webpack.1 |           Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |           using description file: /XYZ/XYZ/package.json (relative path: ./node_modules/flatpickr)
00:13:37 webpack.1 |             no extension
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/node_modules/flatpickr doesn't exist
00:13:37 webpack.1 |             .tsx
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/node_modules/flatpickr.tsx doesn't exist
00:13:37 webpack.1 |             .ts
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/node_modules/flatpickr.ts doesn't exist
00:13:37 webpack.1 |             .mjs
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/node_modules/flatpickr.mjs doesn't exist
00:13:37 webpack.1 |             .js
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/node_modules/flatpickr.js doesn't exist
00:13:37 webpack.1 |             .sass
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/node_modules/flatpickr.sass doesn't exist
00:13:37 webpack.1 |             .scss
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/node_modules/flatpickr.scss doesn't exist
00:13:37 webpack.1 |             .css
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/node_modules/flatpickr.css doesn't exist
00:13:37 webpack.1 |             .module.sass
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/node_modules/flatpickr.module.sass doesn't exist
00:13:37 webpack.1 |             .module.scss
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/node_modules/flatpickr.module.scss doesn't exist
00:13:37 webpack.1 |             .module.css
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/node_modules/flatpickr.module.css doesn't exist
00:13:37 webpack.1 |             .png
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/node_modules/flatpickr.png doesn't exist
00:13:37 webpack.1 |             .svg
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/node_modules/flatpickr.svg doesn't exist
00:13:37 webpack.1 |             .gif
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/node_modules/flatpickr.gif doesn't exist
00:13:37 webpack.1 |             .jpeg
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/node_modules/flatpickr.jpeg doesn't exist
00:13:37 webpack.1 |             .jpg
00:13:37 webpack.1 |               Field 'browser' doesn't contain a valid alias configuration
00:13:37 webpack.1 |               /XYZ/XYZ/node_modules/flatpickr.jpg doesn't exist
00:13:37 webpack.1 |             as directory
00:13:37 webpack.1 |               /XYZ/XYZ/node_modules/flatpickr doesn't exist
00:13:37 webpack.1 | [/XYZ/XYZ/app/javascript/flatpickr]
00:13:37 webpack.1 | [/XYZ/XYZ/app/javascript/flatpickr.tsx]
00:13:37 webpack.1 | [/XYZ/XYZ/app/javascript/flatpickr.ts]
00:13:37 webpack.1 | [/XYZ/XYZ/app/javascript/flatpickr.mjs]
00:13:37 webpack.1 | [/XYZ/XYZ/app/javascript/flatpickr.js]
00:13:37 webpack.1 | [/XYZ/XYZ/app/javascript/flatpickr.sass]
00:13:37 webpack.1 | [/XYZ/XYZ/app/javascript/flatpickr.scss]
00:13:37 webpack.1 | [/XYZ/XYZ/app/javascript/flatpickr.css]
00:13:37 webpack.1 | [/XYZ/XYZ/app/javascript/flatpickr.module.sass]
00:13:37 webpack.1 | [/XYZ/XYZ/app/javascript/flatpickr.module.scss]
00:13:37 webpack.1 | [/XYZ/XYZ/app/javascript/flatpickr.module.css]
00:13:37 webpack.1 | [/XYZ/XYZ/app/javascript/flatpickr.png]
00:13:37 webpack.1 | [/XYZ/XYZ/app/javascript/flatpickr.svg]
00:13:37 webpack.1 | [/XYZ/XYZ/app/javascript/flatpickr.gif]
00:13:37 webpack.1 | [/XYZ/XYZ/app/javascript/flatpickr.jpeg]
00:13:37 webpack.1 | [/XYZ/XYZ/app/javascript/flatpickr.jpg]
00:13:37 webpack.1 | [/XYZ/XYZ/node_modules/stimulus-flatpickr/dist/node_modules]
00:13:37 webpack.1 | [/XYZ/XYZ/node_modules/stimulus-flatpickr/node_modules]
00:13:37 webpack.1 | [/XYZ/XYZ/node_modules/node_modules]
00:13:37 webpack.1 | [/XYZ/XYZ/node_modules]
00:13:37 webpack.1 | [/XYZ/XYZ/node_modules]
00:13:37 webpack.1 | [/Users/node_modules]
00:13:37 webpack.1 | [/node_modules]
00:13:37 webpack.1 | [/XYZ/XYZ/node_modules/flatpickr]
00:13:37 webpack.1 | [/XYZ/XYZ/node_modules/flatpickr.tsx]
00:13:37 webpack.1 | [/XYZ/XYZ/node_modules/flatpickr.ts]
00:13:37 webpack.1 | [/XYZ/XYZ/node_modules/flatpickr.mjs]
00:13:37 webpack.1 | [/XYZ/XYZ/node_modules/flatpickr.js]
00:13:37 webpack.1 | [/XYZ/XYZ/node_modules/flatpickr.sass]
00:13:37 webpack.1 | [/XYZ/XYZ/node_modules/flatpickr.scss]
00:13:37 webpack.1 | [/XYZ/XYZ/node_modules/flatpickr.css]
00:13:37 webpack.1 | [/XYZ/XYZ/node_modules/flatpickr.module.sass]
00:13:37 webpack.1 | [/XYZ/XYZ/node_modules/flatpickr.module.scss]
00:13:37 webpack.1 | [/XYZ/XYZ/node_modules/flatpickr.module.css]
00:13:37 webpack.1 | [/XYZ/XYZ/node_modules/flatpickr.png]
00:13:37 webpack.1 | [/XYZ/XYZ/node_modules/flatpickr.svg]
00:13:37 webpack.1 | [/XYZ/XYZ/node_modules/flatpickr.gif]
00:13:37 webpack.1 | [/XYZ/XYZ/node_modules/flatpickr.jpeg]
00:13:37 webpack.1 | [/XYZ/XYZ/node_modules/flatpickr.jpg]
00:13:37 webpack.1 | β„Ή ο½’wdmο½£: Failed to compile.

and VSCode throws and error like this:

module "/XYZ/node_modules/stimulus-flatpickr/dist/index"
Could not find a declaration file for module 'stimulus-flatpickr'. '/XYZ/node_modules/stimulus-flatpickr/dist/index.js' implicitly has an 'any' type.
  Try `npm install @types/stimulus-flatpickr` if it exists or add a new declaration (.d.ts) file containing `declare module 'stimulus-flatpickr';`ts(7016)

I followed the instructions provided on the readme. Can you please confirm if this is a genuine error or I missed something?

Application details:

Rails: 6.0.3
Ruby: 2.7.1
Webpacker: 4.0

Please let me know if you need more details.

Thanks a lot for creating this plugin!!

Flatpickr Events are not triggered

The Problem I have is that my Events are not triggered. The Flatpickr works, but the change Method is not working sadly. Any JS Events are sadly not fired. I want to achieve to have a change method, so when somebody chooses a date or changes it, that I get the selected Day and can check in my available method, which hours are still available.

// ./controllers/flatpickr_controller.js
// import stimulus-flatpickr wrapper controller to extend it
`import Flatpickr from 'stimulus-flatpickr'`

// you can also import a translation file
`import { French } from 'flatpickr/dist/l10n/fr.js'`

// import a theme (could be in your main CSS entry too...)
`import 'flatpickr/dist/themes/dark.css'`

// create a new Stimulus controller by extending stimulus-flatpickr wrapper controller

export default class extends Flatpickr {
  initialize() {
    // sets your language (you can also set some global setting for all time pickers)
    this.config = {
      locale: French
    }

    console.log("Hello");
    console.log(Flatpickr);
  }

  open(){
    console.log("Are you Open?")
  }

  // all flatpickr hooks are available as callbacks in your Stimulus controller

  change(selectedDates, dateStr, instance) {
    console.log('the callback returns the selected dates', selectedDates)
    console.log('but returns it also as a string', dateStr)
    console.log('and the flatpickr instance', instance)
  }
}`
// ./packs/applitcation.js
import "controllers"
import "bootstrap"

// document.addEventListener('turbolinks:load', () => {
//   flatpickr("[data-behavior='flatpickr']", {
// ./packs/application.js
import { Application } from 'stimulus'
import { definitionsFromContext } from 'stimulus/webpack-helpers'

const application = Application.start()
const context = require.context('../controllers', true, /\.js$/)
application.load(definitionsFromContext(context))

// import Flatpickr
import Flatpickr from 'stimulus-flatpickr'

// Import style for flatpickr
require("flatpickr/dist/flatpickr.css")

// Manually register Flatpickr as a stimulus controller
application.register('flatpickr', Flatpickr)
// Day Booking Field
 <%= f.text_field :day, class: 'calender_input_flatpickr', data:{
                        controller: "flatpickr",
                        flatpickr_date_format: "d.m.Y",
                        flatpickr_min_date: Time.zone.now,
                      }, placeholder: "Datum auswΓ€hlen",
                        label: "Startdatum" %>

Can't get Flatpickr to display the Rails date value from my database....

Hi! First of all, thanks very much for making Stimulus-Flatpickr, it's very handy to have a Rails-friendly version!

This may seem very basic, but I can't figure out how to make Flatpickr display the date I already have in my database's "due_date" field, when I go to Edit a record. Here's what I'm trying to do, using default_date, but it doesn't display anything:

Btw, my 'due_date' is a Rails Date field...ie, t.date "due_date"...

<%= form.text_field :due_date, data: { controller: "flatpickr", flatpickr_default_date: ?????? flatpickr_alt_format: t("date.formats.long"), flatpickr_alt_input: true, flatpickr_min_date: Time.zone.now }, class:"border" %>

For default_date, I've tried:
flatpickr_default_date: invoice.due_date
flatpickr_default_date: :due_date

I'm not sure what else to try. I have used default_date successfully to put today's date in there (flatpickr_default_date: Time.zone.now), but that's the extent of my success. I just can't seem to successfully display an existing value from my database...

Hmmmm, could it be that I need to turn my due_date field into a string field?

Any guidance would be appreciated, thanks!

Exact argument format

Hi, I have some difficulties with specifying parameters.

For example:

 <input data-controller="flatpickr" data-flatpickr-enable-time="true"

it work.

 <input data-controller="flatpickr" data-flatpickr-enable-time="1"

not work.

Can we do something about this?

Support Stimulus 2.0 Values API

Support for Stimulus 2.0's Values API would be useful, so that flatpickr options could be provided as attributes like data-flatpickr-the-option-value (in addition to deprecated support for data-flatpickr-the-option).

I think that support would be straight-forward and I could likely provide a PR.

(And thanks for providing this helpful and clean library!)

Should be able choose which element the controller binds flatpickr to

Perhaps this is my lack of understanding in stimulus, but the behavior seems strange.

div data-controller="flatpickr"
  div data-target="flatpickr.selection"
  = text_field_tag :start_date, nil, class: 'form-control', data: { controller: 'flatpickr' }

flatpickr_controller.js:

export default class extends Flatpickr {
  static targets = ['selection']

  change(selectedDates, dateStr, instance) {
    console.log(this.hasSelectionTarget)
  }
}

Upon selecting a date, console shows false. However, if I add flatpickr_wrap: true to my config in the view, then the console shows true when selecting a date. I don't understand why as the generated HTML looks very similar.

Getting started on development

Hi @adrienpoly this is a great package and good to see Stimulus-based packages arriving. We are using it in crowdAI.

This is more of a general how-to than a specific bug, I hope that is OK.

I think there is a bug around the 24 hour time configuration. In any case I can't make it work on crowdAI. I thought I could debug the package, in the way that one can debug a Rubygem. So far, I've tried this:

  1. Forked the repo
  2. Tried to add it from the fork
yarn add git+ssh//[email protected]:https://github.com/seanfcarroll/stimulus-flatpickr

But in fact this is not ideal. It would be better to be able to work locally on the dev environment.

I was wondering if you might have some ideas on how to develop with a local copy of the package?

Support all Flatpickr actions on input group elements?

Flatpickr can parse an input group of elements, as in their example flatpickr + external elements.

Flatpickr also binds click handlers for any elements in the input group that with the data-attributes: data-open, data-close, data-toggle, data-clear

I'd like to have a Bootstrap input-group with a (Font Awesome) icon toggle element:

<%= tag.div class: 'input-group', data: { controller: 'flatpickr' } do %>
  <%= form.text_field :held_on, class: 'form-control', data: { target: 'flatpickr.instance' } %>
  <%= tag.span class: 'input-group-append add-on', data: { target: 'flatpickr.toggle' } do %>
    <%= tag.span(icon('fas', 'calendar-alt'), class: 'input-group-text') %>
  <% end %>
<% end %>

I see input-group can be used since #35 added an instance target. However, I don't see any other targets. It doesn't look like stimulus-flatpickr supports an element in the group firing these built-in Flatpickr handlers.

Is this something you would be open to adding or accepting a PR for?

If so, does adding targets that mirror Flatpickr (toggle, open, close, clear) seem like the right approach? That would replicate Flatpickr's data-toggle behavior if the target data-target="flatpickr.toggle" exists.

Roadmap for the project

Hi @adrienpoly, I have been using this library for some of the personal projects and I really like how seamlessly it integrates with Stimulus. I was wondering if you have any roadmap for this project so that people can pick and start working towards it?

Support Stimulus 3

The package name has changed to @hotwire/stimulus

ERROR in ./node_modules/stimulus-flatpickr/dist/index.m.js 1:0-36
Module not found: Error: Can't resolve 'stimulus' in '/Users/scott/Code/Ollie/OllieOrder/node_modules/stimulus-flatpickr/dist'

`enable_time: true` doesn't seem to work

I've been struggling to get Flatpickr to allow time selection. I'm using some custom code to generate the data attributes in HTML but I can confirm that HTML (from element inspector) shows the correct data-flatpickr-enable-time attribute:

<input autocomplete="off" data-controller="flatpickr" data-flatpickr-date-format="Y-m-d h:i K" data-flatpickr-enable-time="true" value="" type="text" name="shipment[dispatched_at]" readonly="readonly">

When a date is selected, the default time of 12 PM shows up but it can't be changed.

Plugins support?

How can we add support for these plugins?

https://flatpickr.js.org/plugins/#rangeplugin-beta

https://github.com/flatpickr/flatpickr/tree/master/src/plugins

I kind of solved it by importing for example the rangePlugin from flatpicker plugins folder:

 import rangePlugin from 'flatpickr/dist/plugins/rangePlugin.js'

And i used it in the config:

connect(){
  this.config = {
      mode: 'range', 
      plugins: [new rangePlugin({ input: "#secondRangeInput"})]
    }
  super.connect()
}

and then in the view i did:

<%= text_field_tag :starts_at, nil,
      placeholder: 'select',
      data: {
       // ...
        controller: 'flatpickr',
        flatpickr_mode: 'range',
       // ...
      } %>
<%= text_field_tag :ends_at, nil, id: 'secondRangeInput' %>

It works but i feel this should be part of the stimulus-flatpicker's api without having to import stuff.

Thanks,

Khalil Gharbaoui

time_24hr option is not applied

as discussed in the issue #9 the time_24hr option is not applied.

<%= f.text_field :start_at,
    data: {
      controller: "flatpickr",
      flatpickr_time_24hr: true,
    } %>

gets converted to data-flatpickr-time-24hr in the html

in the controller the function kebabCase() is called to convert time_24hrwhich return time_24hr and not time-24hr therefore the option is not applied.

solution

change the kebabCase() function to replace _by -

@hotwire dependency change?

Copied from the stimulus npm page:

Stimulus has moved to @hotwired/stimulus. This package now just depends on that new package and exports everything from it for backwards compatibility.

Would it be ok to change the package dependency for this project to the new one?

Doesn't show Date flatpicker without error

Hi, After trying couple of times. I would like to know how I can solve the issue. I'm using rails 6.1

I added the Stimulus reflex to my yarn:
"stimulus": "^2.0.0",
"stimulus-flatpickr": "^1.4.0",
"stimulus_reflex": "^3.4.0",
I also have a stimulus reflex due to some other functionality. now I added this to my index.js inside controller folder:

import { Application } from "stimulus"
import { definitionsFromContext } from "stimulus/webpack-helpers"
import StimulusReflex from 'stimulus_reflex'
import consumer from '../channels/consumer'

const application = Application.start()
const context = require.context("controllers", true, /_controller\.js$/)
application.load(definitionsFromContext(context))
StimulusReflex.initialize(application, { consumer })


// import Flatpickr
import Flatpickr from 'stimulus-flatpickr'

// Import style for flatpickr
require("flatpickr/dist/flatpickr.css")


// Manually register Flatpickr as a stimulus controller
application.register('flatpickr', Flatpickr)

Then I have a form of form_with:
with the field of text_field:

        <%= invoice.text_field :departure_date__c,
              data: {
                controller: "flatpickr",
                flatpickr_min_date: Time.zone.now #disables past dates
              }, class:"form-control"
          %>

Then I when I tried to view there is not flatpickr:

image

Then is that possible to use instead of text_field, I can use date_field?

Thank you in advance

Builds are not up to date

Hi!

It seems the builds are not up to date. I've been trying to use the monthSelectorType option with no luck until I've realized that the builds don't include these changes yet.

Not a big problem as the sources can be imported instead, but it's a bit confusing.

Thanks so much for the controller, it's just amazing :)

Best/any way to do trigger Flatpickr from another Stimulus controller?

First of all, thanks again for Stimulus-Flatpickr, it's been working great for setting due dates on Invoices in my app! I have a Due Date field which displays the due date of that invoice in a plain English format ("August 30, 2021") and when the user clicks on that, they can pick a new due date with the Flatpickr pop-up. Thanks for making that easy.

Now, I wanted to create a Due Date Shortcut drop-down/select menu, with options like "Today", "In Seven Days", "in 14 days", etc., so a user doesn't have to pick a date manually. So I've created a Select UI drop-down element with those items, and a new Stimulus controller that reads the select whenever it occurs, but I'm wondering about the best way to proceed from here. Ultimately, I want to read the Invoice's Issued date (also a Flatpickr field), then add the number of days selected in the shortcut (for example, 14 days) to that Issued date, and then update the Due Date Flatpcikr field to reflect the new due date in plain English ("Sept 14, 2021").

Any general advice on going about that? In some rough experiments, I'm able to put a Stimulus target on my Due Date flatpickr field, and can use my Shortcut Stimulus controller to change the numeric date value of the field (like "2022-01-01"), but I can't figure out how to change the plain English text that appears in the field (like "August 30, 2021"). But that might not still get me where I need to go, because I still need a way, in my shortcut Javascript controller, to add the user's shortcut choice to the Issue date of the invoice, and then insert that new date into the Due Date field ("2022-01-01"), and update its plain English text ("Jan 1, 2022").

Any ideas appreciated, thanks much!

Rails 7 new stimulus module

I am using Rails 7 and now stimulus is imported a little bit differently
instead of:
import { Controller } from 'stimulus';
it should be
import { Controller } from '@hotwired/stimulus';

Using the first one throws
✘ [ERROR] Could not resolve "stimulus"

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.