Gathering detailed insights and metrics for stimulus-flatpickr
Gathering detailed insights and metrics for stimulus-flatpickr
Gathering detailed insights and metrics for stimulus-flatpickr
Gathering detailed insights and metrics for stimulus-flatpickr
npm install stimulus-flatpickr
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
415 Stars
229 Commits
30 Forks
5 Watching
18 Branches
10 Contributors
Updated on 19 Nov 2024
Minified
Minified + Gzipped
JavaScript (75.99%)
HTML (15.49%)
CSS (8.52%)
Cumulative downloads
Total Downloads
Last day
-11.7%
5,755
Compared to previous day
Last week
-3.7%
33,997
Compared to previous week
Last month
15.6%
148,096
Compared to previous month
Last year
-8.2%
1,606,475
Compared to previous year
49
Modest yet powerful wrapper of Flatpickr for Stimulus
Only ~1kb
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:
1<%= form_with model: Appointement.new, authenticity_token: true do |f| %> 2 <%= f.text_field :start_time, 3 data: { 4 controller: "flatpickr", 5 flatpickr_min_date: Time.zone.now #disables past dates 6 } %> 7<% end %>
👇👇👇👇👇👇
An example of a Rails app showcasing
is available here : Rails Stimulus Flatpickr
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.
1yarn add flatpickr 2yarn add stimulus-flatpickr
or
1npm i flatpickr 2npm 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
1./bin/importmap pin flatpickr stimulus-flatpickr@beta
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.
manually register a new Stimulus controller in your main JS entry point.
1// ./packs/application.js 2import { Application } from 'stimulus' 3import { definitionsFromContext } from 'stimulus/webpack-helpers' 4 5const application = Application.start() 6const context = require.context('../controllers', true, /\.js$/) 7application.load(definitionsFromContext(context)) 8 9// import Flatpickr 10import Flatpickr from 'stimulus-flatpickr' 11 12// Import style for flatpickr 13require("flatpickr/dist/flatpickr.css") 14 15// Manually register Flatpickr as a stimulus controller 16application.register('flatpickr', Flatpickr)
Note:
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..css
file. You can find them inside your app's root directory node_modules/flatpickr/dist/themes
<%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
in your application.html.erb
file in order to load the calendar style.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
.
1<%= form_with model: Appointement.new, authenticity_token: true do |f| %> 2 <%= f.text_field :start_time, 3 data: { 4 controller: "flatpickr", 5 flatpickr_date_format: "Y-m-d", 6 flatpickr_min_date: Time.zone.now 7 } %> 8<% end %>
👇👇👇👇👇👇
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.
1<%= f.text_field :start_time, 2 data: { 3 controller: "flatpickr", 4 flatpickr_enable_time: true 5 } 6} %>
will output this HTML:
1<input data-controller="flatpickr" data-flatpickr-enable-time="true" type="text" name="appointement[start_time]" />
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
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:
Skip basics installation steps from above!
create a new Stimulus controller that will inherit from stimulus-flatpickr
1// ./controllers/flatpickr_controller.js 2// import stimulus-flatpickr wrapper controller to extend it 3import Flatpickr from 'stimulus-flatpickr' 4 5// you can also import a translation file 6import { French } from 'flatpickr/dist/l10n/fr.js' 7 8// import a theme (could be in your main CSS entry too...) 9import 'flatpickr/dist/themes/dark.css' 10 11// create a new Stimulus controller by extending stimulus-flatpickr wrapper controller 12export default class extends Flatpickr { 13 initialize() { 14 // sets your language (you can also set some global setting for all time pickers) 15 this.config = { 16 locale: French 17 } 18 } 19 20 // all flatpickr hooks are available as callbacks in your Stimulus controller 21 change(selectedDates, dateStr, instance) { 22 console.log('the callback returns the selected dates', selectedDates) 23 console.log('but returns it also as a string', dateStr) 24 console.log('and the flatpickr instance', instance) 25 } 26}
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.
1initialize() { 2 //global options 3 this.config = { 4 enableTime: true, 5 time_24hr: true 6 }; 7 }
or with connect()
1connect() { 2 //global options 3 this.config = { 4 ...this.config, //spread options in case some where defined in initialize 5 enableTime: true, 6 time_24hr: true 7 }; 8 9 //always call super.connect() 10 super.connect(); 11 }
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
.
1<%= form_with model: Appointement.new, authenticity_token: true do |f| %> 2 <%= f.text_field :start_time, 3 data: { 4 controller: "flatpickr", 5 flatpickr_date_format: "Y-m-d", 6 flatpickr_min_date: Time.zone.now } 7 %> 8 <% end %>
👇👇👇👇👇👇
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
.
1<%= form_with model: appointment do |f| %> 2 <%= f.text_field :start_at, 3 data: { 4 controller: "flatpickr", 5 flatpickr_alt_format: t("date.formats.long"), 6 flatpickr_alt_input: true, 7 flatpickr_min_date: Time.zone.now, 8 } %> 9<% end %>
👇👇👇👇👇👇
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 %>
|
|
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(){}
You can access the flatpickr instance from your Stimulus controller by calling this.fp
. Also, the instance methods are available through this instance call.
1yourFunction () { 2 // ... 3 this.fp.clear() 4 this.fp.close() 5}
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:
1<div data-controller="flatpickr"> 2 <!-- the flatpicker instance --> 3 <input type="text" placeholder="Select Date.." data-flatpickr-target="instance" /> 4 <!-- the custom element --> 5 <input type="text" data-flatpickr-target="custom" /> 6</div>
In the stimulus controller, add the target:
1static targets = ['custom'] 2 3yourFunction () { 4 //... 5 this.customTarget 6}
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.
if you need to override the connect function in the extended controller, you need to call super
1connect(){ 2 // ... 3 // define global settings as explained in the global settings section before super 4 // ... 5 6 // always call super.connect() 7 super.connect(); 8 9 // ... 10 // Your code can access this.fp flatpickr instance 11 // ... 12}
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.
This wrapper does not include any CSS. Flatpickr CSS should be loaded separately from the main Flatpickr package as you would normally do.
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
This package is available as open source under the terms of the MIT License.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 4/12 approved changesets -- score normalized to 3
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
security policy file not detected
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
86 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More