-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy pathFileEditContainer.tsx
More file actions
200 lines (182 loc) · 8.1 KB
/
FileEditContainer.tsx
File metadata and controls
200 lines (182 loc) · 8.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import React, { useEffect, useMemo, useState } from 'react';
import getFileContents from '@/api/server/files/getFileContents';
import { httpErrorToHuman } from '@/api/http';
import SpinnerOverlay from '@/components/elements/SpinnerOverlay';
import saveFileContents from '@/api/server/files/saveFileContents';
import FileManagerBreadcrumbs from '@/components/server/files/FileManagerBreadcrumbs';
import { useHistory, useLocation, useParams } from 'react-router';
import FileNameModal from '@/components/server/files/FileNameModal';
import Can from '@/components/elements/Can';
import FlashMessageRender from '@/components/FlashMessageRender';
import PageContentBlock from '@/components/elements/PageContentBlock';
import { ServerError } from '@/components/elements/ScreenBlock';
import tw from 'twin.macro';
import Button from '@/components/elements/Button';
import Select from '@/components/elements/Select';
import modes from '@/modes';
import useFlash from '@/plugins/useFlash';
import { ServerContext } from '@/state/server';
import ErrorBoundary from '@/components/elements/ErrorBoundary';
import { encodePathSegments, hashToPath } from '@/helpers';
import { dirname } from 'pathe';
import CodemirrorEditor from '@/components/elements/CodemirrorEditor';
import { debounce } from 'debounce';
// Helper to generate localStorage key for draft
const getDraftKey = (uuid: string, directory: string) => `pterodactyl:draft:${uuid}:${directory}`;
export default () => {
const [error, setError] = useState('');
const { action } = useParams<{ action: 'new' | string }>();
const [loading, setLoading] = useState(action === 'edit');
const [content, setContent] = useState('');
const [modalVisible, setModalVisible] = useState(false);
const [mode, setMode] = useState('text/plain');
const history = useHistory();
const { hash } = useLocation();
const id = ServerContext.useStoreState((state) => state.server.data!.id);
const uuid = ServerContext.useStoreState((state) => state.server.data!.uuid);
const setDirectory = ServerContext.useStoreActions((actions) => actions.files.setDirectory);
const { addError, clearFlashes } = useFlash();
const directory = ServerContext.useStoreState((state) => state.files.directory);
let fetchFileContent: null | (() => Promise<string>) = null;
// Set directory from hash for new files (persists on refresh)
useEffect(() => {
if (action !== 'new') return;
const path = hashToPath(hash);
// For new files, the hash IS the directory (not a file path)
setDirectory(path || '/');
}, [action, hash, setDirectory]);
// Load draft content from localStorage for new files
useEffect(() => {
if (action !== 'new' || !uuid || !directory) return;
const draftKey = getDraftKey(uuid, directory);
const savedDraft = localStorage.getItem(draftKey);
if (savedDraft) {
setContent(savedDraft);
}
}, [action, uuid, directory]);
useEffect(() => {
if (action === 'new') return;
setError('');
setLoading(true);
const path = hashToPath(hash);
setDirectory(dirname(path));
getFileContents(uuid, path)
.then(setContent)
.catch((error) => {
console.error(error);
setError(httpErrorToHuman(error));
})
.then(() => setLoading(false));
}, [action, uuid, hash]);
// Debounced draft save function for new files
const saveDraft = useMemo(
() =>
debounce((draftContent: string) => {
if (action === 'new' && uuid && directory) {
localStorage.setItem(getDraftKey(uuid, directory), draftContent);
}
}, 1000),
[action, uuid, directory]
);
const save = (name?: string) => {
if (!fetchFileContent) {
return;
}
setLoading(true);
clearFlashes('files:view');
fetchFileContent()
.then((fileContent) => saveFileContents(uuid, name || hashToPath(hash), fileContent))
.then(() => {
// Clear draft from localStorage after successful save
if (action === 'new' && uuid && directory) {
localStorage.removeItem(getDraftKey(uuid, directory));
}
if (name) {
history.push(`/server/${id}/files/edit#/${encodePathSegments(name)}`);
return;
}
return Promise.resolve();
})
.catch((error) => {
console.error(error);
addError({ message: httpErrorToHuman(error), key: 'files:view' });
})
.then(() => setLoading(false));
};
if (error) {
return <ServerError message={error} onBack={() => history.goBack()} />;
}
return (
<PageContentBlock>
<FlashMessageRender byKey={'files:view'} css={tw`mb-4`} />
<ErrorBoundary>
<div css={tw`mb-4`}>
<FileManagerBreadcrumbs withinFileEditor isNewFile={action !== 'edit'} />
</div>
</ErrorBoundary>
{hash.replace(/^#/, '').endsWith('.pteroignore') && (
<div css={tw`mb-4 p-4 border-l-4 bg-neutral-900 rounded border-cyan-400`}>
<p css={tw`text-neutral-300 text-sm`}>
You're editing a <code css={tw`font-mono bg-black rounded py-px px-1`}>.pteroignore</code>{' '}
file. Any files or directories listed in here will be excluded from backups. Wildcards are
supported by using an asterisk (<code css={tw`font-mono bg-black rounded py-px px-1`}>*</code>).
You can negate a prior rule by prepending an exclamation point (
<code css={tw`font-mono bg-black rounded py-px px-1`}>!</code>).
</p>
</div>
)}
<FileNameModal
visible={modalVisible}
onDismissed={() => setModalVisible(false)}
onFileNamed={(name) => {
setModalVisible(false);
save(name);
}}
/>
<div css={tw`relative`}>
<SpinnerOverlay visible={loading} />
<CodemirrorEditor
mode={mode}
filename={hash.replace(/^#/, '')}
onModeChanged={setMode}
initialContent={content}
fetchContent={(value) => {
fetchFileContent = value;
}}
onContentSaved={() => {
if (action !== 'edit') {
setModalVisible(true);
} else {
save();
}
}}
onContentChanged={action === 'new' ? saveDraft : undefined}
/>
</div>
<div css={tw`flex justify-end mt-4`}>
<div css={tw`flex-1 sm:flex-none rounded bg-neutral-900 mr-4`}>
<Select value={mode} onChange={(e) => setMode(e.currentTarget.value)}>
{modes.map((mode) => (
<option key={`${mode.name}_${mode.mime}`} value={mode.mime}>
{mode.name}
</option>
))}
</Select>
</div>
{action === 'edit' ? (
<Can action={'file.update'}>
<Button css={tw`flex-1 sm:flex-none`} onClick={() => save()}>
Save Content
</Button>
</Can>
) : (
<Can action={'file.create'}>
<Button css={tw`flex-1 sm:flex-none`} onClick={() => setModalVisible(true)}>
Create File
</Button>
</Can>
)}
</div>
</PageContentBlock>
);
};