fleet/frontend/pages/queries/edit/components/SaveQueryModal/SaveQueryModal.tsx
Jacob Shandling 67c45d5417
UI – refactor forms and form fields (#16159)
## Addresses #15325 

- Define shared global styles for forms (`form` and `.form`s) and
`.form-field`s
- Sweep through the app, updating each form from being locally styled to
first prioritizing the global styles and only defining local styles
where needed for custom behavior
- Remove lots of unnecessary nesting of elements
- Other small bug fixes and improvements

### Samples, before (L) | after (R):
**Save query modal**
![Screenshot 2024-01-17 at 11 49
14 AM](https://github.com/fleetdm/fleet/assets/61553566/14f209fb-31db-41ef-8e63-e0d8994698c1)

**Edit query form**
![Screenshot 2024-01-17 at 11 50
35 AM](https://github.com/fleetdm/fleet/assets/61553566/b07e70ea-3095-4e4f-be73-95a3c499839b)

**Add hosts modal**
![Screenshot 2024-01-17 at 11 51
48 AM](https://github.com/fleetdm/fleet/assets/61553566/4ef1f410-a823-41d1-b2f6-ea8eb5231f93)


## QA Plan:
@xpkoala here's the same list from the issue, freshly de-checked for you
to use if it's helpful:
* Please check error states of each field

#### Specified by issue:
##### In "Save query" modal:
- [ ] Reduce space between checkboxes and their help text to 8px/0.5rem
for the following fields:
   - [ ] Observers can run
   - [ ] Discard data 
- [ ] Update the following checkbox labels to have normal font weight
(not bold):
   - [ ]  Discard data

##### On "Edit query" page:
- [ ] Update the following checkbox labels to have normal font weight
(not bold):
   - [ ] Observers can run
   - [ ] Discard data

##### In "Add hosts" modal, for copy text fields: 
- [ ]  match typical form form field styles
- [ ] Adjust the positioning of the copy icon to keep it from being too
far down

##### Further locations to check
- [ ] ChangeEmailForm.jsx 
- [ ] ChangePasswordForm.jsx 
- [ ] ConfirmInviteForm.jsx 
- [ ] ConfirmSSOInviteForm.jsx
- [ ] EnrollSecretModal.tsx
- [ ] ForgotPasswordForm.jsx
- [ ] LoginForm.tsx
- [ ] EditPackForm.tsx
- [ ] (New)PackForm.tsx
- [ ] AdminDetails.jsx
- [ ] ConfirmationPage.tsx
- [ ] FleetDetails.jsx
- [ ] OrgDetails.jsx
- [ ] ResetPasswordForm.tsx
- [ ] UserSettingsForm.jsx
- [ ] EditTeamModal.tsx
- [ ] IdpSection.tsx 
- [ ] DeleteIntegrationModal.tsx
- [ ] IntegrationForm.tsx 
- [ ] EndUserMigrationSection.tsx
- [ ] RequestCSRModal.tsx
- [ ] Advanced.tsx 
- [ ] Agents.tsx 
- [ ] FleetDesktop.tsx
- [ ] HostStatusWebhook.tsx front
- [ ] Info.tsx 
- [ ] Smtp.tsx 
- [ ] Sso.tsx 
- [ ] Statistics.tsx
- [ ] WebAddress.tsx
- [ ] CreateTeamModal.tsx
- [ ] DeleteTeamModal.tsx
- [ ] EditTeamModal.tsx
- [ ] AgentOptionsPage.tsx
- updated the layout of this page to align with the rest of the forms in
the UI – can easily revert if it's not what we want
- [ ] AddMemberModal.tsx
- [ ] RemoveMemberModal.tsx
- [ ] UserForm.tsx 
  - Used by both `EditUserModal` and `CreateUserModal`
  - A few different conditions that cause different rendering behavior 
- [ ] DeleteHostModal.tsx
- [ ] TransferHostModal.tsx
- [ ] LabelForm.tsx
- [ ] MacOSTargetForm.tsx
- [ ] WindowsTargetForm.tsx 
- [ ] BootstrapPackageListltem.ts
- [ ] EndUserAuthForm.tsx
- [ ] PackQueryEditorModal.tsx
- [ ] PolicyForm.tsx 
- [ ] SaveNewPolicyModal.tsx
- [ ] ConfirmSaveChangesModal.tsx
- [ ] Query automations modal
- [ ] Policy automations modal - addresses #16010 
- [ ] SoftwareAutomationsModal

## Checklist for submitter
- [x] Changes file added for user-visible changes in `changes/`
- [x] Manual QA for all new/changed functionality

---------

Co-authored-by: Jacob Shandling <jacob@fleetdm.com>
Co-authored-by: RachelElysia <71795832+RachelElysia@users.noreply.github.com>
2024-01-18 10:48:44 -05:00

261 lines
8.1 KiB
TypeScript

import React, { useState, useEffect, useCallback } from "react";
import { pull, size } from "lodash";
import useDeepEffect from "hooks/useDeepEffect";
import Checkbox from "components/forms/fields/Checkbox";
// @ts-ignore
import InputField from "components/forms/fields/InputField";
// @ts-ignore
import Dropdown from "components/forms/fields/Dropdown";
import Button from "components/buttons/Button";
import Modal from "components/Modal";
import {
FREQUENCY_DROPDOWN_OPTIONS,
LOGGING_TYPE_OPTIONS,
MIN_OSQUERY_VERSION_OPTIONS,
SCHEDULE_PLATFORM_DROPDOWN_OPTIONS,
} from "utilities/constants";
import RevealButton from "components/buttons/RevealButton";
import { SelectedPlatformString } from "interfaces/platform";
import {
ICreateQueryRequestBody,
ISchedulableQuery,
QueryLoggingOption,
} from "interfaces/schedulable_query";
import DiscardDataOption from "../DiscardDataOption";
const baseClass = "save-query-modal";
export interface ISaveQueryModalProps {
queryValue: string;
apiTeamIdForQuery?: number; // query will be global if omitted
isLoading: boolean;
saveQuery: (formData: ICreateQueryRequestBody) => void;
toggleSaveQueryModal: () => void;
backendValidators: { [key: string]: string };
existingQuery?: ISchedulableQuery;
queryReportsDisabled?: boolean;
}
const validateQueryName = (name: string) => {
const errors: { [key: string]: string } = {};
if (!name) {
errors.name = "Query name must be present";
}
const valid = !size(errors);
return { valid, errors };
};
const SaveQueryModal = ({
queryValue,
apiTeamIdForQuery,
isLoading,
saveQuery,
toggleSaveQueryModal,
backendValidators,
existingQuery,
queryReportsDisabled,
}: ISaveQueryModalProps): JSX.Element => {
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [selectedFrequency, setSelectedFrequency] = useState(
existingQuery?.interval ?? 3600
);
const [
selectedPlatformOptions,
setSelectedPlatformOptions,
] = useState<SelectedPlatformString>(existingQuery?.platform ?? "");
const [
selectedMinOsqueryVersionOptions,
setSelectedMinOsqueryVersionOptions,
] = useState(existingQuery?.min_osquery_version ?? "");
const [
selectedLoggingType,
setSelectedLoggingType,
] = useState<QueryLoggingOption>(existingQuery?.logging ?? "snapshot");
const [observerCanRun, setObserverCanRun] = useState(false);
const [discardData, setDiscardData] = useState(false);
const [errors, setErrors] = useState<{ [key: string]: string }>(
backendValidators
);
const [showAdvancedOptions, setShowAdvancedOptions] = useState(false);
const toggleAdvancedOptions = () => {
setShowAdvancedOptions(!showAdvancedOptions);
};
useDeepEffect(() => {
if (name) {
setErrors({});
}
}, [name]);
useEffect(() => {
setErrors(backendValidators);
}, [backendValidators]);
const onClickSaveQuery = (evt: React.MouseEvent<HTMLFormElement>) => {
evt.preventDefault();
const { valid, errors: newErrors } = validateQueryName(name);
setErrors({
...errors,
...newErrors,
});
if (valid) {
saveQuery({
// from modal fields
name,
description,
interval: selectedFrequency,
observer_can_run: observerCanRun,
discard_data: discardData,
platform: selectedPlatformOptions,
min_osquery_version: selectedMinOsqueryVersionOptions,
logging: selectedLoggingType,
// from previous New query page
query: queryValue,
// from doubly previous ManageQueriesPage
team_id: apiTeamIdForQuery,
});
}
};
const onChangeSelectPlatformOptions = useCallback(
(values: string) => {
const valArray = values.split(",");
// Remove All if another OS is chosen
// else if Remove OS if All is chosen
if (valArray.indexOf("") === 0 && valArray.length > 1) {
// TODO - inmprove type safety of all 3 options
setSelectedPlatformOptions(
pull(valArray, "").join(",") as SelectedPlatformString
);
} else if (valArray.length > 1 && valArray.indexOf("") > -1) {
setSelectedPlatformOptions("");
} else {
setSelectedPlatformOptions(values as SelectedPlatformString);
}
},
[setSelectedPlatformOptions]
);
return (
<Modal title={"Save query"} onExit={toggleSaveQueryModal}>
<form
onSubmit={onClickSaveQuery}
className={baseClass}
autoComplete="off"
>
<InputField
name="name"
onChange={(value: string) => setName(value)}
value={name}
error={errors.name}
inputClassName={`${baseClass}__name`}
label="Name"
autofocus
ignore1password
/>
<InputField
name="description"
onChange={(value: string) => setDescription(value)}
value={description}
inputClassName={`${baseClass}__description`}
label="Description"
type="textarea"
helpText="What information does your query reveal? (optional)"
/>
<Dropdown
searchable={false}
options={FREQUENCY_DROPDOWN_OPTIONS}
onChange={(value: number) => {
setSelectedFrequency(value);
}}
placeholder={"Every hour"}
value={selectedFrequency}
label="Frequency"
wrapperClassName={`${baseClass}__form-field form-field--frequency`}
helpText="This is how often your query collects data."
/>
<Checkbox
name="observerCanRun"
onChange={setObserverCanRun}
value={observerCanRun}
wrapperClassName={"observer-can-run-wrapper"}
helpText="Users with the Observer role will be able to run this query as a live query."
>
Observers can run
</Checkbox>
<RevealButton
isShowing={showAdvancedOptions}
className={"advanced-options-toggle"}
hideText={"Hide advanced options"}
showText={"Show advanced options"}
caretPosition={"after"}
onClick={toggleAdvancedOptions}
/>
{showAdvancedOptions && (
<>
<Dropdown
options={SCHEDULE_PLATFORM_DROPDOWN_OPTIONS}
placeholder="Select"
label="Platforms"
onChange={onChangeSelectPlatformOptions}
value={selectedPlatformOptions}
multi
wrapperClassName={`${baseClass}__form-field form-field--platform`}
helpText="By default, your query collects data on all compatible platforms."
/>
<Dropdown
options={MIN_OSQUERY_VERSION_OPTIONS}
onChange={setSelectedMinOsqueryVersionOptions}
placeholder="Select"
value={selectedMinOsqueryVersionOptions}
label="Minimum osquery version"
wrapperClassName={`${baseClass}__form-field ${baseClass}__form-field--osquer-vers`}
/>
<Dropdown
options={LOGGING_TYPE_OPTIONS}
onChange={setSelectedLoggingType}
placeholder="Select"
value={selectedLoggingType}
label="Logging"
wrapperClassName={`${baseClass}__form-field ${baseClass}__form-field--logging`}
/>
{queryReportsDisabled !== undefined && (
<DiscardDataOption
{...{
queryReportsDisabled,
selectedLoggingType,
discardData,
setDiscardData,
breakHelpText: true,
}}
/>
)}
</>
)}
<div className="modal-cta-wrap">
<Button
type="submit"
variant="brand"
className="save-query-loading"
isLoading={isLoading}
>
Save
</Button>
<Button onClick={toggleSaveQueryModal} variant="inverse">
Cancel
</Button>
</div>
</form>
</Modal>
);
};
export default SaveQueryModal;