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

ame ui-core time-picker #64

Merged
merged 1 commit into from
May 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
39 changes: 39 additions & 0 deletions ui-core/src/components/Modal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import React, { useEffect, useRef } from 'react';
import { useModalPosition } from './hooks/useModalPosition';
import useClickOutside from './hooks/useOutsideClick';

type ModalProps = {
inputRef: React.RefObject<HTMLInputElement>;
isOpen: boolean;
onClose: () => void;
children: React.ReactNode;
};

const InputModal: React.FC<ModalProps> = ({ inputRef, isOpen, onClose, children }) => {
const modalRef = useRef<HTMLDivElement>(null);
const { modalPosition, calculatePosition } = useModalPosition(inputRef, modalRef);

useEffect(() => {
if (isOpen) {
calculatePosition();
}
}, [calculatePosition, isOpen]);

useClickOutside(modalRef, onClose);

if (!isOpen) return null;

return (
<div className="modal-overlay">
<div
ref={modalRef}
className="modal-content"
style={{ top: modalPosition.top, left: modalPosition.left }}
>
{children}
</div>
</div>
);
};

export default InputModal;
48 changes: 48 additions & 0 deletions ui-core/src/components/hooks/useModalPosition.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { useState, useEffect, useCallback } from 'react';

export const useModalPosition = (
inputRef: React.RefObject<HTMLInputElement>,
modalRef: React.RefObject<HTMLDivElement>,
offset: number = 3, // Default offset below the input
padding: number = 10 // Default padding to ensure the modal stays within the viewport
) => {
const [modalPosition, setModalPosition] = useState<{ top: number; left: number }>({
top: 0,
left: 0,
});

const calculatePosition = useCallback(() => {
if (inputRef.current && modalRef.current) {
const inputRect = inputRef.current.getBoundingClientRect();
const modalRect = modalRef.current.getBoundingClientRect();

// Center the modal horizontally relative to the input element
let left = inputRect.left + inputRect.width / 2 - modalRect.width / 2;
// Set the top position directly below the input element with a slight offset
let top = inputRect.bottom + window.scrollY - offset; // Apply the offset below the input

// Adjust if modal goes beyond viewport
if (left + modalRect.width > window.innerWidth) {
left = window.innerWidth - modalRect.width - padding; // Apply padding to position modal inside viewport
} else if (left < 0) {
left = padding; // Apply padding
}

if (top + modalRect.height > window.innerHeight) {
top = window.innerHeight - modalRect.height - padding; // Apply padding to position modal inside viewport
}

setModalPosition({ top, left });
}
}, [inputRef, modalRef, offset, padding]);

useEffect(() => {
calculatePosition();
// Recalculate position on window resize to handle dynamic content changes
const handleResize = () => calculatePosition();
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, [calculatePosition]);

return { modalPosition, calculatePosition };
};
21 changes: 21 additions & 0 deletions ui-core/src/components/hooks/useOutsideClick.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { useEffect } from 'react';

const useClickOutside = (
ref: React.RefObject<HTMLElement>,
handler: (event: MouseEvent) => void
) => {
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (ref.current && !ref.current.contains(event.target as Node)) {
handler(event);
}
};

document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [ref, handler]);
};

export default useClickOutside;
2 changes: 1 addition & 1 deletion ui-core/src/components/inputs/FieldWrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export type FieldWrapperProps = {
disabled?: boolean;
statusWithMessage?: statusWithMessage;
small?: boolean;
children: React.ReactNode;
children?: React.ReactNode;
className?: string;
};

Expand Down
107 changes: 107 additions & 0 deletions ui-core/src/components/inputs/TimePicker.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import React, { useState, useCallback, useRef } from 'react';
import InputModal from '../Modal';
import Input, { InputProps } from './Input';

const TimePicker: React.FC<InputProps> = (props) => {
const [selectedHour, setSelectedHour] = useState<string>('00');
const [selectedMinute, setSelectedMinute] = useState<string>('00');
const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
const inputRef = useRef<HTMLInputElement>(null);

const handleHourClick = useCallback((hour: string) => {
setSelectedHour(hour);
}, []);

const handleMinuteClick = useCallback((minute: string) => {
setSelectedMinute(minute);
}, []);

const handleMinuteButtonClick = useCallback((action: 'UP' | 'DOWN') => {
setSelectedMinute((prevMinute) => {
let newMinute = prevMinute !== null ? parseInt(prevMinute) : 0;
if (action === 'UP' && newMinute < 59) {
newMinute++;
} else if (action === 'DOWN' && newMinute > 0) {
newMinute--;
}
return newMinute.toString().padStart(2, '0');
});
}, []);

const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const value = event.target.value;
const [hour, minute] = value.split(':');
if (hour !== undefined && minute !== undefined) {
setSelectedHour(hour);
setSelectedMinute(minute);
}
};

const formattedHour = selectedHour.padStart(2, '0');
const formattedMinute = selectedMinute.padStart(2, '0');
const selectedTime = `${formattedHour}:${formattedMinute}`;

const hours = [...Array(24).keys()].map((hour) => hour.toString().padStart(2, '0'));
const minutes = [...Array(12).keys()].map((minute) => (minute * 5).toString().padStart(2, '0'));

const openModal = () => {
setIsModalOpen(true);
};

const closeModal = () => setIsModalOpen(false);

return (
<div className="time-picker">
<Input
type="time"
name="time"
value={selectedTime}
onClick={openModal}
onChange={handleChange}
ref={inputRef}
{...props}
/>
<InputModal inputRef={inputRef} isOpen={isModalOpen} onClose={closeModal}>
<div className="time-picker-container">
<div className="time-grid">
{hours.map((hour) => (
<div
key={hour}
className={`hour ${selectedHour === hour ? 'selected' : ''}`}
onClick={() => handleHourClick(hour)}
>
{hour}
</div>
))}
</div>

<div className="time-separator">:</div>

<div className="minute-container">
<div className="time-grid">
{minutes.map((minute) => (
<div
key={minute}
className={`minute ${selectedMinute === minute ? 'selected' : ''}`}
onClick={() => handleMinuteClick(minute)}
>
{minute}
</div>
))}
</div>
<div className="minute-buttons">
<button onClick={() => handleMinuteButtonClick('DOWN')} className="minute-button">
-1mn
</button>
<button onClick={() => handleMinuteButtonClick('UP')} className="minute-button">
+1mn
</button>
</div>
</div>
</div>
</InputModal>
</div>
);
};

export default TimePicker;
21 changes: 21 additions & 0 deletions ui-core/src/hooks/useClickOutside.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { useEffect } from 'react';

const useClickOutside = (
ref: React.RefObject<HTMLElement>,
handler: (event: MouseEvent) => void
) => {
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (ref.current && !ref.current.contains(event.target as Node)) {
handler(event);
}
};

document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [ref, handler]);
};

export default useClickOutside;
1 change: 1 addition & 0 deletions ui-core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ export { default as TextArea, TextAreaProps } from './components/inputs/TextArea
export { default as RadioButton, RadioButtonProps } from './components/inputs/RadioButton';
export { default as RadioGroup, RadioGroupProps } from './components/inputs/RadioGroup';
export { default as Select, SelectOption, SelectProps } from './components/Select';
export { default as TimePicker } from './components/inputs/TimePicker';
38 changes: 38 additions & 0 deletions ui-core/src/stories/TimePicker.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import React from 'react';
import { Meta, StoryObj } from '@storybook/react';
import TimePicker from '../components/inputs/TimePicker';

import '@osrd-project/ui-core/dist/theme.css';

const meta: Meta<typeof TimePicker> = {
component: TimePicker,
args: {
disabled: false,
readOnly: false,
},
title: 'TimePicker',
tags: ['autodocs'],
decorators: [
(Story) => (
<div style={{ maxWidth: '7rem' }}>
<Story />
</div>
),
],
};

export default meta;
type Story = StoryObj<typeof TimePicker>;

export const Default: Story = {
args: {
label: 'Heure',
},
};

export const DisabledTimePicker: Story = {
args: {
disabled: true,
label: 'Heure',
},
};
15 changes: 11 additions & 4 deletions ui-core/src/styles/inputs/input.css
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,12 @@
}

&:focus-within {
.leading-content-wrapper, .trailing-content-wrapper, .input {
box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.5) inset, 0px 0px 0px 1px rgba(31, 27, 23, 1) inset;
.leading-content-wrapper,
.trailing-content-wrapper,
.input {
box-shadow:
0px 1px 3px rgba(0, 0, 0, 0.5) inset,
0px 0px 0px 1px rgba(31, 27, 23, 1) inset;
@apply bg-white-25;
}
}
Expand Down Expand Up @@ -77,7 +81,6 @@
border-radius: 0;
}


&:focus {
outline: none;
}
Expand Down Expand Up @@ -135,6 +138,11 @@
appearance: none;
-moz-appearance: textfield;
}

&[type='time']::-webkit-calendar-picker-indicator {
background: none;
display: none;
}
}

.trailing-content-wrapper {
Expand Down Expand Up @@ -202,7 +210,6 @@
&.with-leading-and-trailing {
border-radius: 0;
}

}

.trailing-content-wrapper {
Expand Down
Loading
Loading