Created
March 31, 2024 08:12
-
-
Save meysam81/7495a8e7724066fcd597681e74416df3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect } from 'react'; | |
import styles from './MotdForm.module.css'; | |
const MotdForm = () => { | |
const [motd, setMotd] = useState(''); | |
const [isEditing, setIsEditing] = useState(false); | |
const MOTD_EXPIRATION_KEY = 'motdExpiration'; | |
const MOTD_KEY = 'motd'; | |
useEffect(() => { | |
const savedMotd = localStorage.getItem(MOTD_KEY); | |
const expiration = localStorage.getItem(MOTD_EXPIRATION_KEY); | |
if (savedMotd && !isExpired(expiration)) { | |
setMotd(savedMotd); | |
setIsEditing(false); | |
} else { | |
clearMotd(); | |
} | |
}, []); | |
const handleInputChange = (e) => { | |
setMotd(e.target.value); | |
}; | |
const handleSubmit = (e) => { | |
e.preventDefault(); | |
localStorage.setItem(MOTD_KEY, motd); | |
const expiration = getTomorrowDate(); | |
localStorage.setItem(MOTD_EXPIRATION_KEY, expiration); | |
setIsEditing(false); | |
}; | |
const handleDoubleClick = () => { | |
setIsEditing(true); | |
}; | |
const clearMotd = () => { | |
localStorage.removeItem(MOTD_KEY); | |
localStorage.removeItem(MOTD_EXPIRATION_KEY); | |
setMotd(''); | |
setIsEditing(false); | |
}; | |
const isExpired = (expiration) => { | |
const now = new Date(); | |
const expireDate = new Date(expiration); | |
return now >= expireDate; | |
}; | |
const getTomorrowDate = () => { | |
const tomorrow = new Date(); | |
tomorrow.setDate(tomorrow.getDate() + 1); | |
return tomorrow.toISOString(); | |
}; | |
return ( | |
<div className={styles.container}> | |
<div className={styles['motd-form-container']}> | |
{isEditing ? ( | |
<form onSubmit={handleSubmit} className={styles.form}> | |
<input | |
type="text" | |
value={motd} | |
onChange={handleInputChange} | |
autoFocus | |
className={styles.input} | |
/> | |
<button type="submit" className={styles.button}>Save</button> | |
<button type="button" onClick={clearMotd} className={styles.button}> | |
Clear | |
</button> | |
</form> | |
) : ( | |
<div | |
onDoubleClick={handleDoubleClick} | |
className={styles.motdText} | |
> | |
{motd ? ( | |
<h2>{motd}</h2> | |
) : ( | |
<p>Double click here to set your Message of the Day</p> | |
)} | |
</div> | |
)} | |
</div> | |
</div> | |
); | |
}; | |
export default MotdForm; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment