2020-08-08 22:18:37 +00:00
// @flow
2021-10-26 03:41:28 +00:00
import invariant from "invariant" ;
2021-07-15 20:19:09 +00:00
import { observer } from "mobx-react" ;
2020-08-09 05:53:59 +00:00
import * as React from "react" ;
2021-07-15 20:19:09 +00:00
import { useState } from "react" ;
import { useTranslation , Trans } from "react-i18next" ;
import { useHistory } from "react-router-dom" ;
2020-08-08 22:18:37 +00:00
import Button from "components/Button" ;
import Flex from "components/Flex" ;
import HelpText from "components/HelpText" ;
2021-10-26 03:41:28 +00:00
import useStores from "hooks/useStores" ;
2021-07-20 09:06:10 +00:00
import useToasts from "hooks/useToasts" ;
2020-08-09 05:53:59 +00:00
import { documentUrl } from "utils/routeHelpers" ;
2020-08-08 22:18:37 +00:00
type Props = {
2021-10-26 03:41:28 +00:00
documentId : string ,
2020-08-08 22:18:37 +00:00
onSubmit : ( ) => void ,
} ;
2021-10-26 03:41:28 +00:00
function DocumentTemplatize ( { documentId , onSubmit } : Props ) {
2021-07-15 20:19:09 +00:00
const [ isSaving , setIsSaving ] = useState ( ) ;
const history = useHistory ( ) ;
2021-07-20 09:06:10 +00:00
const { showToast } = useToasts ( ) ;
2021-07-15 20:19:09 +00:00
const { t } = useTranslation ( ) ;
2021-10-26 03:41:28 +00:00
const { documents } = useStores ( ) ;
const document = documents . get ( documentId ) ;
invariant ( document , "Document must exist" ) ;
2020-08-08 22:18:37 +00:00
2021-07-15 20:19:09 +00:00
const handleSubmit = React . useCallback (
async ( ev : SyntheticEvent < > ) => {
ev . preventDefault ( ) ;
setIsSaving ( true ) ;
2020-08-08 22:18:37 +00:00
2021-07-15 20:19:09 +00:00
try {
const template = await document . templatize ( ) ;
history . push ( documentUrl ( template ) ) ;
2021-07-20 09:06:10 +00:00
showToast ( t ( "Template created, go ahead and customize it" ) , {
2021-07-15 20:19:09 +00:00
type : "info" ,
} ) ;
onSubmit ( ) ;
} catch ( err ) {
2021-07-20 09:06:10 +00:00
showToast ( err . message , { type : "error" } ) ;
2021-07-15 20:19:09 +00:00
} finally {
setIsSaving ( false ) ;
}
} ,
2021-07-20 09:06:10 +00:00
[ document , showToast , history , onSubmit , t ]
2021-07-15 20:19:09 +00:00
) ;
2020-08-08 22:18:37 +00:00
2021-07-15 20:19:09 +00:00
return (
< Flex column >
< form onSubmit = { handleSubmit } >
< HelpText >
< Trans
defaults = "Creating a template from <em>{{titleWithDefault}}</em> is a non-destructive action – we'll make a copy of the document and turn it into a template that can be used as a starting point for new documents."
values = { { titleWithDefault : document . titleWithDefault } }
components = { { em : < strong / > } }
/ >
< / H e l p T e x t >
< Button type = "submit" >
{ isSaving ? ` ${ t ( "Creating" ) } … ` : t ( "Create template" ) }
< / B u t t o n >
< / f o r m >
< / F l e x >
) ;
2020-08-08 22:18:37 +00:00
}
2021-07-15 20:19:09 +00:00
export default observer ( DocumentTemplatize ) ;