-
Notifications
You must be signed in to change notification settings - Fork 931
Expand file tree
/
Copy pathPackageForm.tsx
More file actions
496 lines (449 loc) · 16.3 KB
/
Copy pathPackageForm.tsx
File metadata and controls
496 lines (449 loc) · 16.3 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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
// Used in AddPackageModal.tsx and EditSoftwareModal.tsx
import React, { useState, useEffect, useCallback } from "react";
import classnames from "classnames";
import useGitOpsMode from "hooks/useGitOpsMode";
import { LEARN_MORE_ABOUT_BASE_LINK } from "utilities/constants";
import {
getExtensionFromFileName,
getFileDetails,
} from "utilities/file/fileUtils";
import getDefaultInstallScript from "utilities/software_install_scripts";
import getDefaultUninstallScript from "utilities/software_uninstall_scripts";
import { ILabelSummary } from "interfaces/label";
import { SoftwareCategory } from "interfaces/software";
import { isScriptOnlyPackageType } from "interfaces/package_type";
import { notify } from "components/ToastNotification";
import Button from "components/buttons/Button";
import TooltipWrapper from "components/TooltipWrapper";
import FileUploader from "components/FileUploader";
import {
CUSTOM_TARGET_OPTIONS,
generateHelpText,
generateSelectedLabels,
getCustomTarget,
getTargetType,
} from "pages/SoftwarePage/helpers";
import { DropdownTargetLabelSelector } from "components/TargetLabelSelector";
import SoftwareOptionsSelector from "pages/SoftwarePage/components/forms/SoftwareOptionsSelector";
import InfoBanner from "components/InfoBanner";
import CustomLink from "components/CustomLink";
import PackageAdvancedOptions from "../PackageAdvancedOptions";
import { createTooltipContent, generateFormValidation } from "./helpers";
import SoftwareDeploySlider from "../SoftwareDeploySelector";
export const baseClass = "package-form";
export interface IPackageFormData {
software: File | null;
preInstallQuery?: string;
installScript: string;
postInstallScript?: string;
uninstallScript?: string;
selfService: boolean;
targetType: string;
customTarget: string;
labelTargets: Record<string, boolean>;
automaticInstall: boolean; // Used on add but not edit
categories: string[];
}
export interface IPackageFormValidation {
isValid: boolean;
software: { isValid: boolean };
preInstallQuery?: { isValid: boolean; message?: string };
installScript?: { isValid: boolean; message?: string };
uninstallScript?: { isValid: boolean; message?: string };
customTarget?: { isValid: boolean };
}
const getGraphicName = (ext: string) => {
if (ext === "sh") {
return "file-sh";
} else if (ext === "ps1") {
return "file-ps1";
} else if (ext === "py") {
return "file-py";
}
return "file-pkg";
};
const renderSoftwareDeployWarningBanner = () => (
<InfoBanner
color="yellow"
className={`${baseClass}__deploy-warning`}
cta={
<CustomLink
url={`${LEARN_MORE_ABOUT_BASE_LINK}/query-templates-for-automatic-install-software`}
text="Learn more"
newTab
/>
}
>
Installing software over existing installations might cause issues.
Fleet's policy may not detect these existing installations. Please
create a test fleet in Fleet to verify a smooth installation.
</InfoBanner>
);
const renderFileTypeMessage = () => {
return (
<>
<TooltipWrapper tipContent="Supports .pkg, .sh, and .py">
macOS
</TooltipWrapper>
, <TooltipWrapper tipContent="Supports .ipa">iOS/iPadOS</TooltipWrapper>,{" "}
<TooltipWrapper tipContent="Supports .msi, .exe, .ps1">
Windows
</TooltipWrapper>
, or{" "}
<TooltipWrapper tipContent="Supports .deb, .rpm, .tar.gz, .sh, and .py">
Linux
</TooltipWrapper>
</>
);
};
interface IPackageFormProps {
labels: ILabelSummary[];
showSchemaButton?: boolean;
onCancel: () => void;
onSubmit: (formData: IPackageFormData) => void;
onClickShowSchema?: () => void;
onClickPreviewEndUserExperience: (isIosOrIpadosApp: boolean) => void;
isEditingSoftware?: boolean;
isFleetMaintainedApp?: boolean;
defaultSoftware?: any; // TODO
defaultInstallScript?: string;
defaultPreInstallQuery?: string;
defaultPostInstallScript?: string;
defaultUninstallScript?: string;
defaultSelfService?: boolean;
defaultCategories?: SoftwareCategory[] | null;
className?: string;
/** Indicates that this PackageForm deals with an entity that can be managed by GitOps, and so should be disabled when gitops mode is enabled */
gitopsCompatible?: boolean;
/** When provided, the categories list is fetched dynamically for this fleet. */
teamId?: number;
}
// application/gzip is used for .tar.gz files because browsers can't handle double-extensions correctly
const ACCEPTED_EXTENSIONS =
".pkg,.msi,.exe,.deb,.rpm,application/gzip,.tgz,.sh,.ps1,.py,.ipa";
const PackageForm = ({
labels,
showSchemaButton = false,
onClickShowSchema,
onCancel,
onSubmit,
onClickPreviewEndUserExperience,
isEditingSoftware = false,
isFleetMaintainedApp = false,
defaultSoftware,
defaultInstallScript,
defaultPreInstallQuery,
defaultPostInstallScript,
defaultUninstallScript,
defaultSelfService,
defaultCategories,
className,
gitopsCompatible = false,
teamId,
}: IPackageFormProps) => {
const { gitOpsModeEnabled, repoURL } = useGitOpsMode("software");
const initialFormData: IPackageFormData = {
software: defaultSoftware || null,
installScript: defaultInstallScript || "",
preInstallQuery: defaultPreInstallQuery || "",
postInstallScript: defaultPostInstallScript || "",
uninstallScript: defaultUninstallScript || "",
selfService: defaultSelfService || false,
targetType: getTargetType(defaultSoftware),
customTarget: getCustomTarget(defaultSoftware),
labelTargets: generateSelectedLabels(defaultSoftware),
automaticInstall: false,
categories: defaultCategories || [],
};
const [formData, setFormData] = useState<IPackageFormData>(initialFormData);
const [formValidation, setFormValidation] = useState<IPackageFormValidation>({
isValid: false,
software: { isValid: false },
});
const onFileSelect = (files: FileList | null) => {
if (files && files.length > 0) {
const file = files[0];
// Only populate default install/uninstall scripts when adding (but not editing) software
if (isEditingSoftware) {
const newData = { ...formData, software: file };
setFormData(newData);
setFormValidation(generateFormValidation(newData));
} else {
let newDefaultInstallScript: string;
try {
newDefaultInstallScript = getDefaultInstallScript(file.name);
} catch (e) {
notify.error(`${e}`, { response: e });
return;
}
let newDefaultUninstallScript: string;
try {
newDefaultUninstallScript = getDefaultUninstallScript(file.name);
} catch (e) {
notify.error(`${e}`, { response: e });
return;
}
const newData = {
...formData,
software: file,
installScript: newDefaultInstallScript || "",
uninstallScript: newDefaultUninstallScript || "",
};
setFormData(newData);
setFormValidation(generateFormValidation(newData));
}
}
};
const onFormSubmit = (evt: React.FormEvent<HTMLFormElement>) => {
evt.preventDefault();
onSubmit(formData);
};
const onChangeInstallScript = (value: string) => {
const newData = { ...formData, installScript: value };
setFormData(newData);
setFormValidation(generateFormValidation(newData));
};
const onChangePreInstallQuery = (value?: string) => {
const newData = { ...formData, preInstallQuery: value };
setFormData(newData);
setFormValidation(generateFormValidation(newData));
};
const onChangePostInstallScript = (value?: string) => {
const newData = { ...formData, postInstallScript: value };
setFormData(newData);
setFormValidation(generateFormValidation(newData));
};
const onChangeUninstallScript = (value?: string) => {
const newData = { ...formData, uninstallScript: value };
setFormData(newData);
setFormValidation(generateFormValidation(newData));
};
const onToggleAutomaticInstall = useCallback(
(value?: boolean) => {
const automaticInstall =
typeof value === "boolean" ? value : !formData.automaticInstall;
setFormData({ ...formData, automaticInstall });
},
[formData]
);
const onToggleSelfService = () => {
const newData = { ...formData, selfService: !formData.selfService };
setFormData(newData);
setFormValidation(generateFormValidation(newData));
};
const onSelectCategory = ({
name,
value,
}: {
name: string;
value: boolean;
}) => {
let newCategories: string[];
if (value) {
// Add the name if not already present
newCategories = formData.categories.includes(name)
? formData.categories
: [...formData.categories, name];
} else {
// Remove the name if present
newCategories = formData.categories.filter((cat) => cat !== name);
}
const newData = {
...formData,
categories: newCategories,
};
setFormData(newData);
setFormValidation(generateFormValidation(newData));
};
const onSelectTargetType = (value: string) => {
const newData = { ...formData, targetType: value };
setFormData(newData);
setFormValidation(generateFormValidation(newData));
};
const onSelectCustomTarget = (value: string) => {
const newData = { ...formData, customTarget: value };
setFormData(newData);
setFormValidation(generateFormValidation(newData));
};
const onSelectLabel = ({ name, value }: { name: string; value: boolean }) => {
const newData = {
...formData,
labelTargets: { ...formData.labelTargets, [name]: value },
};
setFormData(newData);
setFormValidation(generateFormValidation(newData));
};
const disableFieldsForGitOps = gitopsCompatible && gitOpsModeEnabled;
const isSubmitDisabled = !formValidation.isValid || disableFieldsForGitOps;
const submitTooltipContent = createTooltipContent(
formValidation,
repoURL,
disableFieldsForGitOps
);
const classNames = classnames(baseClass, className);
const ext = getExtensionFromFileName(formData?.software?.name || "");
const isExePackage = ext === "exe";
const isTarballPackage = ext === "tar.gz";
const isScriptPackage = isScriptOnlyPackageType(ext);
const isIpaPackage = ext === "ipa";
// We currently don't support replacing a tarball package, and FMAs use the
// page-level Versions modal to switch versions rather than a file replace.
const canEditFile =
isEditingSoftware && !isTarballPackage && !isFleetMaintainedApp;
// If a user preselects automatic install and then uploads a:
// exe, tarball, script, or ipa which automatic install is not supported,
// the form will default back to manual install
useEffect(() => {
if (
(isExePackage || isTarballPackage || isScriptPackage || isIpaPackage) &&
formData.automaticInstall
) {
onToggleAutomaticInstall(false);
}
}, [
formData.automaticInstall,
isExePackage,
isTarballPackage,
isScriptPackage,
isIpaPackage,
onToggleAutomaticInstall,
]);
// Show advanced options for any selected package except .ipa (includes script packages).
const showAdvancedOptions = formData.software && !isIpaPackage;
const showDeploySoftwareSlider =
!!formData.software && // show after selection
!gitOpsModeEnabled && // hide in gitOps mode
!isEditingSoftware && // show only on add, not edit
// automatic install is not supported for ipa packages, exe, tarball, or script packages
!isIpaPackage &&
!isExePackage &&
!isTarballPackage &&
!isScriptPackage;
// 4.83+ Show deploy slider on add if the package type supports it.
// Hide from gitOps mode
const renderSoftwareDeploySlider = () => (
<>
<SoftwareDeploySlider
deploySoftware={formData.automaticInstall}
onToggleDeploySoftware={onToggleAutomaticInstall}
/>
{formData.automaticInstall && renderSoftwareDeployWarningBanner()}
</>
);
// GitOps mode hides SoftwareOptionsSelector and TargetLabelSelector
// 4.83 Removed option/targets from Add page
const showOptionsTargetsSelectors = !gitOpsModeEnabled && isEditingSoftware;
const renderSoftwareOptionsSelector = () => (
<SoftwareOptionsSelector
formData={formData}
onToggleSelfService={onToggleSelfService}
onSelectCategory={onSelectCategory}
isEditingSoftware={isEditingSoftware}
onClickPreviewEndUserExperience={() =>
onClickPreviewEndUserExperience(isIpaPackage)
}
teamId={teamId}
/>
);
const renderTargetLabelSelector = () => (
<DropdownTargetLabelSelector
selectedTargetType={formData.targetType}
selectedCustomTarget={formData.customTarget}
selectedLabels={formData.labelTargets}
customTargetOptions={CUSTOM_TARGET_OPTIONS}
className={`${baseClass}__target`}
onSelectTargetType={onSelectTargetType}
onSelectCustomTarget={onSelectCustomTarget}
onSelectLabel={onSelectLabel}
labels={labels || []}
dropdownHelpText={
formData.targetType === "Custom" &&
generateHelpText(formData.automaticInstall, formData.customTarget)
}
/>
);
return (
<div className={classNames}>
<form className={`${baseClass}__form`} onSubmit={onFormSubmit}>
<FileUploader
canEdit={canEditFile}
graphicName={getGraphicName(ext || "")}
accept={ACCEPTED_EXTENSIONS}
message={renderFileTypeMessage()}
onFileUpload={onFileSelect}
buttonMessage="Choose file"
buttonType="brand-inverse-icon"
className={`${baseClass}__file-uploader`}
fileDetails={
formData.software ? getFileDetails(formData.software) : undefined
}
gitopsCompatible={gitopsCompatible}
gitOpsModeEnabled={gitOpsModeEnabled}
/>
{(showDeploySoftwareSlider || showOptionsTargetsSelectors) && ( // Only show container if one of the two components will be rendered to avoid extra gap spacing
<div
// including `form` class here keeps the children fields subject to the global form
// children styles
className={
gitopsCompatible && gitOpsModeEnabled
? `${baseClass}__form-fields--gitops-disabled form`
: "form"
}
>
{showDeploySoftwareSlider && renderSoftwareDeploySlider()}
{showOptionsTargetsSelectors && (
<div className={`${baseClass}__form-frame`}>
{renderSoftwareOptionsSelector()}
{renderTargetLabelSelector()}
</div>
)}
</div>
)}
{showAdvancedOptions && (
<PackageAdvancedOptions
showSchemaButton={showSchemaButton}
selectedPackage={formData.software}
errors={{
preInstallQuery: formValidation.preInstallQuery?.message,
}}
preInstallQuery={formData.preInstallQuery}
installScript={formData.installScript}
postInstallScript={formData.postInstallScript}
uninstallScript={formData.uninstallScript}
onClickShowSchema={onClickShowSchema}
onChangePreInstallQuery={onChangePreInstallQuery}
onChangeInstallScript={onChangeInstallScript}
onChangePostInstallScript={onChangePostInstallScript}
onChangeUninstallScript={onChangeUninstallScript}
gitopsCompatible={gitopsCompatible}
gitOpsModeEnabled={gitOpsModeEnabled}
/>
)}
<div className={`${baseClass}__action-buttons`}>
{submitTooltipContent ? (
<TooltipWrapper
tipContent={submitTooltipContent}
underline={false}
showArrow
tipOffset={10}
position="left"
>
<Button type="submit" disabled={isSubmitDisabled}>
{isEditingSoftware ? "Save" : "Add software"}
</Button>
</TooltipWrapper>
) : (
<Button type="submit" disabled={isSubmitDisabled}>
{isEditingSoftware ? "Save" : "Add software"}
</Button>
)}
<Button variant="inverse" onClick={onCancel}>
Cancel
</Button>
</div>
</form>
</div>
);
};
// Allows form not to re-render as long as its props don't change
export default React.memo(PackageForm);