11import React , { useState , useEffect } from 'react' ;
22import Editor from 'react-simple-code-editor' ;
33import { highlight , languages } from 'prismjs/components/prism-core' ;
4+ import { saveAs } from 'file-saver' ;
45import Modal from './ParentModal' ;
56import './file-edit.css' ;
67import 'prismjs/components/prism-clike' ;
@@ -11,6 +12,14 @@ import { actionType as T } from '../../reducer';
1112const FileEditModal = ( { superState, dispatcher } ) => {
1213 const [ codeStuff , setCodeStuff ] = useState ( '' ) ;
1314 const [ fileName , setFileName ] = useState ( '' ) ;
15+ const [ dirButton , setDirButton ] = useState ( false ) ;
16+
17+ useEffect ( ( ) => {
18+ if ( navigator . userAgent . indexOf ( 'Edg' ) !== - 1 || navigator . userAgent . indexOf ( 'Chrome' ) !== - 1 ) {
19+ setDirButton ( true ) ;
20+ }
21+ } , [ ] ) ;
22+
1423 const close = ( ) => dispatcher ( { type : T . EDIT_TEXTFILE , payload : { show : false } } ) ;
1524 // TODO - Save file
1625 async function submit ( ) {
@@ -25,6 +34,23 @@ const FileEditModal = ({ superState, dispatcher }) => {
2534 dispatcher ( { type : T . EDIT_TEXTFILE , payload : { show : false } } ) ;
2635 }
2736
37+ async function saveAsSubmit ( ) {
38+ const handle = await window . showSaveFilePicker ( ) ;
39+ const stream = await handle . createWritable ( ) ;
40+ await stream . write ( codeStuff ) ;
41+ await stream . close ( ) ;
42+ // dispatcher({ type: T.EDIT_TEXTFILE, payload: { show: false } });
43+ }
44+
45+ async function saveSubmit ( ) {
46+ // eslint-disable-next-line no-alert
47+ const newFileName = prompt ( 'Filename:' ) ;
48+ const bytes = new TextEncoder ( ) . encode ( codeStuff ) ;
49+ const blob = new Blob ( [ bytes ] , { type : 'application/json;charset=utf-8' } ) ;
50+ saveAs ( blob , newFileName ) ;
51+ // dispatcher({ type: T.EDIT_TEXTFILE, payload: { show: false } });
52+ }
53+
2854 useEffect ( ( ) => {
2955 if ( superState . fileObj ) {
3056 setFileName ( superState . fileObj . name ) ;
@@ -44,7 +70,16 @@ const FileEditModal = ({ superState, dispatcher }) => {
4470 >
4571 < div className = "File Edit Container" >
4672 < div className = "footer" >
47- < button type = "submit" className = "btn btn-primary" onClick = { submit } > Save</ button >
73+ { fileName
74+ && (
75+ < button type = "submit" className = "btn btn-primary" onClick = { submit } > Save</ button >
76+ ) }
77+ { dirButton && (
78+ < button type = "submit" className = "btn btn-primary" onClick = { saveAsSubmit } > Save As</ button >
79+ ) }
80+ { ! dirButton && (
81+ < button type = "submit" className = "btn btn-primary" onClick = { saveSubmit } > Save As</ button >
82+ ) }
4883 </ div >
4984 < div
5085 style = { {
0 commit comments