UPD duration inputs now close automatically

This commit is contained in:
Shaun Orssaud 2024-02-20 12:46:13 +09:00
parent 3eb1f59845
commit feb7b4cad3
2 changed files with 39 additions and 16 deletions

View File

@ -1,4 +1,4 @@
import React, { useState } from 'react';
import React, { useState, useEffect, useRef } from 'react';
import styled from 'styled-components';
const DurationInputWrapper = styled.div`
@ -21,13 +21,27 @@ const DurationInput: React.FC<DurationInputProps> = ({ onDurationChange }) => {
const [hours, setHours] = useState(0);
const [minutes, setMinutes] = useState(0);
const [seconds, setSeconds] = useState(0);
const durationInputRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (durationInputRef.current && !durationInputRef.current.contains(event.target as Node)) {
onDurationChange({ days, hours, minutes, seconds });
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [onDurationChange, days, hours, minutes, seconds]);
const handleDurationChange = () => {
onDurationChange({ days, hours, minutes, seconds });
};
return (
<DurationInputWrapper>
<DurationInputWrapper ref={durationInputRef}>
<Input
type="number"
value={days}
@ -64,4 +78,4 @@ const DurationInput: React.FC<DurationInputProps> = ({ onDurationChange }) => {
);
};
export default DurationInput;
export default DurationInput;

View File

@ -1,5 +1,4 @@
// DurationInputWithFloatingBox.tsx
import React, { useState } from 'react';
import React, { useEffect, useRef } from 'react';
import styled from 'styled-components';
import DurationInput from './DurationInput';
@ -12,15 +11,6 @@ const FloatingBoxWrapper = styled.div`
background: #555555;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
border-radius: 8px;
display: flex;
flex-direction: column;
align-items: stretch;
`;
const CloseButton = styled.button`
margin-top: 10px;
cursor: pointer;
flex: 1;
`;
interface DurationInputWithFloatingBoxProps {
@ -30,10 +20,29 @@ interface DurationInputWithFloatingBoxProps {
}
const DurationInputWithFloatingBox: React.FC<DurationInputWithFloatingBoxProps> = ({ isOpen, onClose, onDurationChange }) => {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (ref.current && !ref.current.contains(event.target as Node)) {
onClose();
}
};
if (isOpen) {
document.addEventListener('mousedown', handleClickOutside);
} else {
document.removeEventListener('mousedown', handleClickOutside);
}
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [isOpen, onClose]);
return (
<FloatingBoxWrapper style={{ display: isOpen ? 'flex' : 'none' }}>
<FloatingBoxWrapper style={{ display: isOpen ? 'block' : 'none' }} ref={ref}>
<DurationInput onDurationChange={onDurationChange} />
<CloseButton onClick={onClose}>Close</CloseButton>
</FloatingBoxWrapper>
);
};