Skip to content

Commit

Permalink
#534: toggleSelected now can be a function
Browse files Browse the repository at this point in the history
  • Loading branch information
t1m0n committed Jun 24, 2023
1 parent 13873c2 commit 0b37605
Show file tree
Hide file tree
Showing 6 changed files with 48 additions and 10 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

### v3.4.0
* added new method `getViewDates()` allows you to get all dates that should be currently displayed in calendar [#536](https://github.com/t1m0n/air-datepicker/issues/536)
* `toggleSelected` now can be a function [#534](https://github.com/t1m0n/air-datepicker/issues/534)

### v3.3.5
* added handling of optional chaining operator in dist package [#518](https://github.com/t1m0n/air-datepicker/issues/518)
Expand Down
1 change: 1 addition & 0 deletions docs/locales/en.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ export default {
optsAltField: 'An additional text field where the date with the format from the {fieldName} field will be written',
optsAltFieldDateFormat: 'Date format for alternative field',
optsToggleSelected: 'If {true}, then clicking on the active cell will remove the selection from it',
optsToggleSelectedFunc: 'Also could be a function. It receives datepicker instance and date which user tries to unselect. If function will return {true} then selection will be removed, otherwise it will remain.',
optsKeyboardNav: 'Enables keyboard navigation. It only works if the element on which the calendar is initialized is a text field.',
optsKeyboardNavListTitle: 'Key combinations:',
optsKeyboardNavMonthForward: 'next month',
Expand Down
1 change: 1 addition & 0 deletions docs/locales/ru.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ export default {
optsAltField: 'Дополнительное текстовое поле, куда будет записываться дата с форматом из поля {fieldName}',
optsAltFieldDateFormat: 'Формат даты дополнительного поля',
optsToggleSelected: 'Если {true}, то клик на активной ячейке снимет с нее выделение',
optsToggleSelectedFunc: 'Так же может быть функцией, в качестве параметров она получает экземпляр календаря и дату, которую пользователь пытается выбрать повторно. Если функция вернет {true}, то выделение будет снято, в противном случае выделение останется.',
optsKeyboardNav: 'Включает навигацию по календарю с помощью клавиатуры. Работает только в случае когда элемент, на котором инициализируется календарь, является текстовым полем.',
optsKeyboardNavListTitle: 'Сочетания клавиш:',
optsKeyboardNavMonthForward: 'переход на месяц вперед',
Expand Down
5 changes: 4 additions & 1 deletion docs/pages/docs.js
Original file line number Diff line number Diff line change
Expand Up @@ -148,10 +148,13 @@ function Docs({} = {}) {
<Param name={'altFieldDateFormat'} type={'string | (date) => string'} defaultValue={'"T"'}>
<Paragraph id={'optsAltFieldDateFormat'} />
</Param>
<Param name={'toggleSelected'} type={'boolean'} defaultValue={'true'}>
<Param name={'toggleSelected'} type={'boolean | ({datepicker, date}) => boolean'} defaultValue={'true'}>
<Paragraph id={'optsToggleSelected'} values={{
true: <Code inline>true</Code>
}} />
<Paragraph id={'optsToggleSelectedFunc'} values={{
true: <Code inline>true</Code>
}} />
</Param>
<Param name={'keyboardNav'} type={'boolean'} defaultValue={'true'}>
<Paragraph id={'optsKeyboardNav'} />
Expand Down
19 changes: 10 additions & 9 deletions src/datepicker.js
Original file line number Diff line number Diff line change
Expand Up @@ -869,22 +869,23 @@ export default class Datepicker {
}

_handleAlreadySelectedDates(alreadySelectedDate, newSelectedDate) {
let {range, toggleSelected} = this.opts;
const {range, toggleSelected} = this.opts;
const isFunc = typeof toggleSelected === 'function';
let shouldToggle = isFunc ? toggleSelected({datepicker: this, date: newSelectedDate}) : toggleSelected;

if (range) {
if (!toggleSelected) {
if (!shouldToggle) {
// Add possibility to select same date when range is true
if (this.selectedDates.length !== 2) {
this.selectDate(newSelectedDate);
}
} else {
this.unselectDate(newSelectedDate);
}
} else if (toggleSelected) {
this.unselectDate(newSelectedDate);
}

// Change last selected date to be able to change time when clicking on this cell
if (!toggleSelected) {
if (shouldToggle) {
this.unselectDate(newSelectedDate);
} else {
// Change last selected date to be able to change time when clicking on this cell
this._updateLastSelectedDate(alreadySelectedDate);
}
}
Expand Down Expand Up @@ -1084,7 +1085,7 @@ export default class Datepicker {
this.rangeDateTo = null;
}

update = (newOpts) => {
update = (newOpts = {}) => {
let prevOpts = deepMerge({}, this.opts);
deepMerge(this.opts, newOpts);

Expand Down
31 changes: 31 additions & 0 deletions tests/options.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,37 @@ describe('OPTIONS TESTS', () => {

expect(dp.selectedDates).toHaveLength(1);
});

it('should receive correct arguments if it is a function', function (done) {
let date = new Date();

init({
toggleSelected: ({datepicker, date}) => {
expect(datepicker).toBeInstanceOf(Datepicker);
expect(date).toBeInstanceOf(Date);

done();
}
});

dp.selectDate(date);
dp.getCell(date).click();
});

it('should handle option as function correctly', function () {
let date = new Date();

init({
toggleSelected: () => {
return false;
}
});

dp.selectDate(date);
dp.getCell(date).click();

expect(dp.selectedDates).toHaveLength(1);
});
});

describe('keyboardNav', () => {
Expand Down

0 comments on commit 0b37605

Please sign in to comment.