Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TACT-346: Goal setting rework: Additional improvements #879

Merged
merged 4 commits into from
Jul 7, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion components/pages/Goals/components/GoalList/GoalItem/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,13 @@ export class GoalItemStore {
};

handleChangeTargetDate = (date: string) => {
return this.parent.callbacks?.onUpdateGoal({ ...this.goal, targetDate: date });
return this.parent.callbacks?.onUpdateGoal({
...this.goal,
startDate: DatePickerHelpers.isStartDateAfterEndDate(this.goal?.startDate, date)
? ''
: this.goal?.startDate,
targetDate: date
});
};

handleChangeTitle = (title: string) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Editor } from '../../../../../shared/Editor';
import React from 'react';
import { FormError } from "../../../../../shared/FormError";
import { GoalEmojiSelect } from "../../../components/GoalEmojiSelect";
import { GOAL_TITLE_MAX_LENGTH } from '../constants';

export const GoalCreationDescription = observer(
function GoalCreationDescription() {
Expand Down Expand Up @@ -58,6 +59,7 @@ export const GoalCreationDescription = observer(
boxShadow: 'none',
borderBottomWidth: 2,
}}
maxLength={GOAL_TITLE_MAX_LENGTH}
onKeyDown={store.handleTitleKeyDown}
_invalid={{
boxShadow: 'none',
Expand Down
2 changes: 2 additions & 0 deletions components/pages/Goals/modals/GoalCreationModal/constants.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { GoalStatus } from "../../types";

export const GOAL_TITLE_MAX_LENGTH = 50;

export const GOALS_STATUSES_TITLES = {
[GoalStatus.TODO]: 'Todo',
[GoalStatus.WONT_DO]: 'Won\'t do',
Expand Down
5 changes: 5 additions & 0 deletions components/pages/Goals/modals/GoalCreationModal/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,11 @@ export class GoalCreationModalStore {

handleTargetDateChange = (value: string) => {
this.goal.targetDate = value;

if (DatePickerHelpers.isStartDateAfterEndDate(this.goal?.startDate, value)) {
this.goal.startDate = '';
}

return this.handleUpdate({ ...this.goal, targetDate: value });
}

Expand Down
24 changes: 22 additions & 2 deletions components/shared/DatePicker/components/DatePickerInput/index.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,37 @@
import React, { forwardRef, InputHTMLAttributes } from 'react';
import React, { forwardRef, InputHTMLAttributes, KeyboardEvent, useEffect } from 'react';
import { useRefWithCallback } from '../../../../../helpers/useRefWithCallback';
import { observer } from 'mobx-react-lite';
import { useDatePickerStore } from '../../store';
import { chakra } from '@chakra-ui/react';

export const DatePickerInput = observer(
forwardRef<HTMLInputElement, InputHTMLAttributes<HTMLInputElement>>(
function DatePickerInput(props, inputRef) {
const store = useDatePickerStore();
const ref = useRefWithCallback(inputRef, store.setInputRef);

useEffect(() => {
if (store.editablePosition) {
store.setSelection();
}
}, [store.editablePosition, store]);

const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
store.onInputKeyDown(event, props.onKeyDown);
};

return (
<div className='input-wrapper'>
<input ref={ref} {...props} />
<chakra.input
ref={ref}
{...props}
value={props.value || store.intermediateValue}
onChange={undefined}
onInput={store.handleInputValueChange}
onMouseUp={store.onInputClick}
onKeyDown={onKeyDown}
onDoubleClick={store.handleAreaEvent}
/>
</div>
);
}
Expand Down
238 changes: 235 additions & 3 deletions components/shared/DatePicker/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,57 @@ import moment from 'moment';
import { KeyboardEvent, SyntheticEvent } from 'react';
import { NavigationHelper } from '../../../helpers/NavigationHelper';
import { NavigationDirections } from '../../../types/navigation';
import { DATE_FORMAT } from '../../../helpers/DateHelper';

export const DATE_PICKER_DATE_FORMAT = 'dd.MM.yyyy';
kamilsk marked this conversation as resolved.
Show resolved Hide resolved

export enum EditablePosition {
DAY = 'day',
MONTH = 'month',
YEAR = 'year',
}

export type InputParams = Record<EditablePosition, {
edited: boolean;
filled: boolean;
}>;

export class DatePickerStore {
value: string;
intermediateValue: string = 'DD.MM.YYYY';
kamilsk marked this conversation as resolved.
Show resolved Hide resolved
initialValue: string;
callbacks: DatePickerCallbacks;

datePickerRef: ReactDatePicker;
inputRef: HTMLInputElement;
isFocused = false;
isCalendarFocused = false;
isClickedOutside = false;
isFocused: boolean = false;
isCalendarFocused: boolean = false;
isClickedOutside: boolean = false;
editablePosition: EditablePosition = EditablePosition.DAY;
nextEditablePosition: EditablePosition = EditablePosition.MONTH;
prevEditablePosition: EditablePosition = EditablePosition.YEAR;

selectionPositionsMap: Record<EditablePosition, [number, number]> = {
[EditablePosition.DAY]: [0, 2],
[EditablePosition.MONTH]: [3, 5],
[EditablePosition.YEAR]: [6, 10],
};
inputParams: InputParams = {
[EditablePosition.DAY]: {
edited: false,
filled: false,
},
[EditablePosition.YEAR]: {
edited: false,
filled: false,
},
[EditablePosition.MONTH]: {
edited: false,
filled: false,
},
};

setSelectionTimeout: NodeJS.Timeout;

constructor(public root: RootStore) {
makeAutoObservable(this, {}, { autoBind: true });
Expand All @@ -33,6 +71,10 @@ export class DatePickerStore {
return value ? moment(value).toDate() : undefined;
};

updateInputParams = (params: Partial<InputParams>) => {
this.inputParams = { ...this.inputParams, ...params };
};

handleFocus = () => {
if (!this.isFocused) {
this.isFocused = true;
Expand All @@ -45,6 +87,24 @@ export class DatePickerStore {
this.isFocused = false;
this.isCalendarFocused = false;

this.updateInputParams({
[EditablePosition.DAY]: {
edited: false,
filled: false,
},
[EditablePosition.YEAR]: {
edited: false,
filled: false,
},
[EditablePosition.MONTH]: {
edited: false,
filled: false,
},
});
this.editablePosition = EditablePosition.DAY;
this.nextEditablePosition = EditablePosition.MONTH;
this.prevEditablePosition = EditablePosition.YEAR;

if (toggleFocus) {
this.callbacks?.onFocusToggle?.(false);
}
Expand Down Expand Up @@ -79,6 +139,11 @@ export class DatePickerStore {
e.stopPropagation();
};

preventEvent = (event: SyntheticEvent | KeyboardEvent) => {
event.preventDefault();
event.stopPropagation();
};

handleKeyDown = (e: KeyboardEvent) => {
this.handleAreaEvent(e);

Expand Down Expand Up @@ -148,11 +213,178 @@ export class DatePickerStore {
this.inputRef = ref;
};

changeSelection = (currPosition: number) => {
this.updateSelection(currPosition);
this.setSelection();
};

updateSelection = (currPosition: number) => {
if (currPosition <= 2) {
this.editablePosition = EditablePosition.DAY;
this.nextEditablePosition = EditablePosition.MONTH;
this.prevEditablePosition = EditablePosition.YEAR;
} else if (currPosition > 2 && currPosition <= 5) {
this.editablePosition = EditablePosition.MONTH;
this.nextEditablePosition = EditablePosition.YEAR;
this.prevEditablePosition = EditablePosition.DAY;
} else if (currPosition > 5) {
this.editablePosition = EditablePosition.YEAR;
this.nextEditablePosition = EditablePosition.DAY;
this.prevEditablePosition = EditablePosition.MONTH;
}
kamilsk marked this conversation as resolved.
Show resolved Hide resolved
};

setSelection = (editablePosition: EditablePosition = this.editablePosition) => {
const [start, end] = this.selectionPositionsMap[editablePosition];

if (editablePosition !== this.editablePosition) {
this.updateSelection(start);
}

this.setSelectionTimeout = setTimeout(() => {
this.inputRef.setSelectionRange(start, end);
})
};

getValuesMap = (inputValue: string) => {
const [inputDay, inputMonth, inputYear] = inputValue.split('.');
const [storedDay, storedMonth, storedYear] = this.value
? moment(this.value).format(DATE_FORMAT).split('.')
: this.intermediateValue.split('.');

return {
[EditablePosition.DAY]: {
inputValue: inputDay,
storedValue: storedDay
},
[EditablePosition.MONTH]: {
inputValue: inputMonth,
storedValue: storedMonth
},
[EditablePosition.YEAR]: {
inputValue: inputYear,
storedValue: storedYear
}
};
}

handleInputValueChange = (event: SyntheticEvent<HTMLInputElement>) => {
const input = event.target as HTMLInputElement;

this.updateSelection(input.selectionStart);
this.setSelection();

if (this.value && !/(\d|D){1,2}\.(\d|M){1,2}\.(\d|Y){1,4}/.test(input.value)) {
kamilsk marked this conversation as resolved.
Show resolved Hide resolved
return;
}

let shouldMoveToNextPosition = false;
const valuesMap = this.getValuesMap(input.value);

const additionalZeros = this.editablePosition === EditablePosition.YEAR ? '0000' : '00';
const currentValue =
this.inputParams[this.editablePosition].edited &&
!this.inputParams[this.editablePosition].filled
? `${additionalZeros}${valuesMap[this.editablePosition].storedValue}`.slice(-additionalZeros.length)
: additionalZeros;

const formattedValue = `${currentValue}${valuesMap[this.editablePosition].inputValue}`.slice(-additionalZeros.length);

let correctDay = valuesMap[EditablePosition.DAY].inputValue;
let correctMonth = valuesMap[EditablePosition.MONTH].inputValue;
let correctYear = valuesMap[EditablePosition.YEAR].inputValue;

if (this.editablePosition === EditablePosition.DAY) {
const daysInMonth = correctMonth !== 'MM' && correctYear !== 'YYYY'
? moment(`${correctYear}-${correctMonth}`, 'YYYY-MM').daysInMonth()
: 31;

const formattedDay = Number(formattedValue) ? formattedValue : '1';
correctDay = Number(formattedDay) <= daysInMonth ? formattedDay : daysInMonth.toString();

if ((correctDay[0] !== '0' || Number(formattedDay) > Number(daysInMonth.toString()[0])) && correctDay.length === 2) {
shouldMoveToNextPosition = true;
}
} else {
if (this.editablePosition === EditablePosition.MONTH) {
const formattedMonth = Number(formattedValue) ? formattedValue : '1';
correctMonth = Number(formattedMonth) <= 12 ? formattedMonth : `0${formattedValue[1]}`;

if ((correctMonth[0] !== '0' && correctMonth.length === 2) || Number(correctMonth) > 1) {
shouldMoveToNextPosition = true;
}
} else if (this.editablePosition === EditablePosition.YEAR) {
correctYear = formattedValue;
}

const daysInMonth = correctMonth !== 'MM' && correctYear !== 'YYYY'
? moment(`${correctYear}-${correctMonth}`, 'YYYY-MM').daysInMonth()
: 31;
correctDay = Number(correctDay) > daysInMonth ? daysInMonth.toString() : correctDay;
}

this.updateInputParams({
[this.editablePosition]: {
filled: !String(formattedValue).includes('0') || shouldMoveToNextPosition,
edited: true,
},
});

const finalValue = `${correctDay}.${correctMonth}.${correctYear}`;

if (!this.value) {
this.intermediateValue = finalValue;
}

if (this.value || !/[a-zA-Z]/.test(finalValue)) {
this.handleChange(moment(finalValue, DATE_FORMAT).toDate());
this.intermediateValue = 'DD.MM.YYYY';
}

if (shouldMoveToNextPosition) {
this.setSelection(this.nextEditablePosition);
}
}

onInputKeyDown = (
event: KeyboardEvent<HTMLInputElement>,
onKeyDown?: (event: KeyboardEvent<HTMLInputElement>) => void
) => {
if (
((event.key === 'Tab' && !event.shiftKey) || event.key === 'ArrowRight') &&
this.editablePosition !== EditablePosition.YEAR
) {
this.preventEvent(event);
this.setSelection(this.nextEditablePosition);
} else if (
((event.key === 'Tab' && event.shiftKey) || event.key === 'ArrowLeft') &&
this.editablePosition !== EditablePosition.DAY
) {
this.preventEvent(event);
this.setSelection(this.prevEditablePosition);
} else if (event.key === 'Enter') {
this.preventEvent(event);
this.handleSave(this.value);
this.datePickerRef.setOpen(false);
} else {
onKeyDown?.(event);
}
};

onInputClick = (event: SyntheticEvent<HTMLInputElement>) => {
this.preventEvent(event);
this.changeSelection((event.target as HTMLInputElement).selectionStart);
};

update = ({ value, onFocusToggle, onChanged, onNavigate }: DatePickerProps) => {
this.value = value;
this.initialValue = value;
this.callbacks = { onChanged, onFocusToggle, onNavigate };
};

destroy = () => {
clearTimeout(this.setSelectionTimeout);
};
}

export const {
Expand Down
3 changes: 2 additions & 1 deletion components/shared/DatePicker/view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { Tooltip } from '../Tooltip';
import cn from 'classnames';
import { useRefWithCallback } from '../../../helpers/useRefWithCallback';
import { DatePickerInput } from './components/DatePickerInput';
import { DATE_FORMAT } from '../../../helpers/DateHelper';

export const DatePickerView = observer(forwardRef<ReactDatePicker, DatePickerViewProps>(
function DatePickerView(
Expand Down Expand Up @@ -81,7 +82,7 @@ export const DatePickerView = observer(forwardRef<ReactDatePicker, DatePickerVie
onChange={store.handleChange}
portalId="date-picker-portal"
tabIndex={tabIndex}
placeholderText={!store.currentValue && store.isFocused ? 'DD.MM.YYYY' : ''}
placeholderText={!store.currentValue && store.isFocused ? DATE_FORMAT : ''}
onFocus={store.handleFocus}
onBlur={() => store.handleBlur(false)}
onCalendarClose={() => store.handleBlur(false)}
Expand Down
Loading