62 lines
1.7 KiB
TypeScript
62 lines
1.7 KiB
TypeScript
import { useState } from 'react'
|
|
import type { NoteEditorProps } from '../interfaces/note-editor'
|
|
import { isTitleValid, normalizeTitle } from '../lib/noteValidation'
|
|
import NoteForm from './NoteForm'
|
|
import NoteReadView from './NoteReadView'
|
|
|
|
function NoteEditor(props: NoteEditorProps) {
|
|
const [editing, setEditing] = useState(props.mode === 'create')
|
|
const [title, setTitle] = useState(props.mode === 'edit' ? props.note.title : '')
|
|
const [content, setContent] = useState(props.mode === 'edit' ? props.note.content : '')
|
|
const [titleMissing, setTitleMissing] = useState(false)
|
|
|
|
const handleTitleChange = (value: string) => {
|
|
setTitle(value)
|
|
if (titleMissing && isTitleValid(value)) setTitleMissing(false)
|
|
}
|
|
|
|
const handleSubmit = () => {
|
|
if (!isTitleValid(title)) {
|
|
setTitleMissing(true)
|
|
return
|
|
}
|
|
const safeTitle = normalizeTitle(title)
|
|
if (props.mode === 'create') {
|
|
props.onCreate(safeTitle, content)
|
|
} else {
|
|
props.onUpdate(props.note.id, { title: safeTitle, content })
|
|
setEditing(false)
|
|
}
|
|
}
|
|
|
|
if (props.mode === 'create' || editing) {
|
|
return (
|
|
<NoteForm
|
|
title={title}
|
|
content={content}
|
|
titleMissing={titleMissing}
|
|
cancelLabel="Annuler"
|
|
onTitleChange={handleTitleChange}
|
|
onContentChange={setContent}
|
|
onCancel={props.mode === 'create' ? props.onCancelCreate : () => setEditing(false)}
|
|
onSubmit={handleSubmit}
|
|
/>
|
|
)
|
|
}
|
|
|
|
const { note } = props
|
|
return (
|
|
<NoteReadView
|
|
note={note}
|
|
onEdit={() => {
|
|
setTitle(note.title)
|
|
setContent(note.content)
|
|
setEditing(true)
|
|
}}
|
|
onDelete={props.onDelete}
|
|
/>
|
|
)
|
|
}
|
|
|
|
export default NoteEditor
|