diaREact/resources/js/components/pages/Form.tsx
2022-02-11 17:26:15 +01:00

111 lines
3.8 KiB
TypeScript

import * as React from 'react';
import {EncryptStorage} from 'storage-encryption';
import {Button, Stack, TextField} from "@mui/material";
import MDEditor from '@uiw/react-md-editor';
let encryptStorage = new EncryptStorage('test'); // TODO la clef doit venir de l'utilisateur
export default function PageForm({setListPages, csrf, url, passphrase}) {
const isPassphraseSet = passphrase !== null;
const onSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
encryptStorage = new EncryptStorage(passphrase);
let HTMLForm : HTMLFormElement = event.currentTarget;
let decryptedFormData = new FormData(HTMLForm);
let encryptedFormData = new FormData();
for (let [key, value] of decryptedFormData.entries()) {
encryptStorage.encrypt('uuid'+key, value);
let newEncryptedString = localStorage.getItem('uuid'+key);
if (newEncryptedString) {
encryptedFormData.append(key, newEncryptedString);
}
}
encryptedFormData.append('_token', csrf);
let response = await fetch(url, {
method: 'POST',
body: encryptedFormData
});
const json = await response.json();
const uuid = json.uuid;
for (let key of decryptedFormData.keys()) {
let newEncryptedString = localStorage.getItem('uuid'+key);
localStorage.setItem(uuid+key, ""+newEncryptedString);
localStorage.removeItem("uuid"+key);
}
if (json.success) {
HTMLForm.reset();
setListPages(previousList => [
...previousList,
{
id: uuid,
date: json.date,
title: decryptedFormData.get("title"),
content: decryptedFormData.get("text"),
}]);
}
}
if (isPassphraseSet) {
return (
/* <Stack
component="form"
sx={{
width: '25ch',
}}
spacing={2}
noValidate
autoComplete="off"
>
<TextField
label="Titre"
id="title"
name="title"
variant="outlined"
size="small"
/>
<MDEditor
value={value}
onChange={setValue}
/>
<MDEditor.Markdown source={value} />
<TextField
label="Texte"
name="content"
id="filled-hidden-label-normal"
defaultValue="Normal"
variant="outlined"
multiline
maxRows={15}
/>
<Button variant="contained" component="span" onClick={onSubmit}>
Enregistrer
</Button>
</Stack>*/
<div className="container">
<div className="row justify-content-center">
<div className="col-md-8">
<div className="card">
<form action={url} id="postPage" method="post" onSubmit={onSubmit}>
<label htmlFor="title">Titre:</label>
<input id="title" name="title"/>
<hr/>
<label htmlFor="text">Texte:</label>
<textarea id="text" name="text"/>
<hr/>
<input type="submit" value="Enregistrer"/>
</form>
</div>
</div>
</div>
</div>
);
}
return (<div></div>);
}