Refactor top-level template routes

* Fix repeated api calls from useEffect hook by wrapping the breadcrumb
setter with useCallback

* Rework the top-level routes to remove some old patterns and bring it more
into alignment with how it's done on the projects screen
This commit is contained in:
Jake McDermott 2020-12-16 13:41:46 -05:00
parent d82f68c88e
commit 5cb580be7a
No known key found for this signature in database
GPG Key ID: 0E56ED990CDFCB4F
5 changed files with 122 additions and 166 deletions

View File

@ -137,10 +137,10 @@ function Project({ i18n, setBreadcrumb }) {
);
}
let showCardHeader = true;
if (['edit', 'schedules/'].some(name => location.pathname.includes(name))) {
showCardHeader = false;
}
const showCardHeader = !(
location.pathname.endsWith('edit') ||
location.pathname.includes('schedules/')
);
return (
<PageSection>

View File

@ -1,19 +1,21 @@
/* eslint react/no-unused-state: 0 */
import React, { useState } from 'react';
import { withRouter, Redirect, useHistory } from 'react-router-dom';
import { CardBody } from '../../../components/Card';
import { JobTemplatesAPI } from '../../../api';
import { JobTemplate } from '../../../types';
import { getAddedAndRemoved } from '../../../util/lists';
import JobTemplateForm from '../shared/JobTemplateForm';
import ContentLoading from '../../../components/ContentLoading';
function JobTemplateEdit({ template }) {
const { id, type } = template;
const history = useHistory();
const [formSubmitError, setFormSubmitError] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const detailsUrl = `/templates/${type}/${id}/details`;
const detailsUrl = `/templates/${template.type}/${template.id}/details`;
const handleSubmit = async values => {
const {
@ -28,6 +30,7 @@ function JobTemplateEdit({ template }) {
} = values;
setFormSubmitError(null);
setIsLoading(true);
remainingValues.project = values.project.id;
remainingValues.webhook_credential = webhook_credential?.id || null;
try {
@ -38,8 +41,10 @@ function JobTemplateEdit({ template }) {
submitCredentials(credentials),
]);
history.push(detailsUrl);
} catch (err) {
setFormSubmitError(err);
} catch (error) {
setFormSubmitError(error);
} finally {
setIsLoading(false);
}
};
@ -94,12 +99,14 @@ function JobTemplateEdit({ template }) {
history.push(detailsUrl);
};
const canEdit = template.summary_fields.user_capabilities.edit;
const canEdit = template?.summary_fields?.user_capabilities?.edit;
if (!canEdit) {
return <Redirect to={detailsUrl} />;
}
if (isLoading) {
return <ContentLoading />;
}
return (
<CardBody>
<JobTemplateForm
@ -112,7 +119,7 @@ function JobTemplateEdit({ template }) {
);
}
JobTemplateForm.propTypes = {
JobTemplateEdit.propTypes = {
template: JobTemplate.isRequired,
};

View File

@ -13,6 +13,7 @@ import {
useRouteMatch,
} from 'react-router-dom';
import RoutedTabs from '../../components/RoutedTabs';
import { useConfig } from '../../contexts/Config';
import useRequest from '../../util/useRequest';
import ContentError from '../../components/ContentError';
import JobList from '../../components/JobList';
@ -24,15 +25,16 @@ import JobTemplateEdit from './JobTemplateEdit';
import { JobTemplatesAPI, OrganizationsAPI } from '../../api';
import TemplateSurvey from './TemplateSurvey';
function Template({ i18n, me, setBreadcrumb }) {
function Template({ i18n, setBreadcrumb }) {
const match = useRouteMatch();
const location = useLocation();
const { id: templateId } = useParams();
const match = useRouteMatch();
const { me = {} } = useConfig();
const {
result: { isNotifAdmin, template },
isLoading: hasRolesandTemplateLoading,
error: rolesAndTemplateError,
isLoading,
error: contentError,
request: loadTemplateAndRoles,
} = useRequest(
useCallback(async () => {
@ -44,9 +46,8 @@ function Template({ i18n, me, setBreadcrumb }) {
role_level: 'notification_admin_role',
}),
]);
if (actions.data.actions.PUT) {
if (data.webhook_service && data?.related?.webhook_key) {
if (actions?.data?.actions?.PUT) {
if (data?.webhook_service && data?.related?.webhook_key) {
const {
data: { webhook_key },
} = await JobTemplatesAPI.readWebhookKey(templateId);
@ -54,35 +55,40 @@ function Template({ i18n, me, setBreadcrumb }) {
data.webhook_key = webhook_key;
}
}
setBreadcrumb(data);
return {
template: data,
isNotifAdmin: notifAdminRes.data.results.length > 0,
};
}, [setBreadcrumb, templateId]),
}, [templateId]),
{ isNotifAdmin: false, template: null }
);
useEffect(() => {
loadTemplateAndRoles();
}, [loadTemplateAndRoles, location.pathname]);
useEffect(() => {
if (template) {
setBreadcrumb(template);
}
}, [template, setBreadcrumb]);
const createSchedule = data => {
return JobTemplatesAPI.createSchedule(templateId, data);
return JobTemplatesAPI.createSchedule(template.id, data);
};
const loadScheduleOptions = useCallback(() => {
return JobTemplatesAPI.readScheduleOptions(templateId);
}, [templateId]);
return JobTemplatesAPI.readScheduleOptions(template.id);
}, [template]);
const loadSchedules = useCallback(
params => {
return JobTemplatesAPI.readSchedules(templateId, params);
return JobTemplatesAPI.readSchedules(template.id, params);
},
[templateId]
[template]
);
const canSeeNotificationsTab = me.is_system_auditor || isNotifAdmin;
const canSeeNotificationsTab = me?.is_system_auditor || isNotifAdmin;
const canAddAndEditSurvey =
template?.summary_fields?.user_capabilities.edit ||
template?.summary_fields?.user_capabilities.delete;
@ -131,17 +137,7 @@ function Template({ i18n, me, setBreadcrumb }) {
tab.id = n;
});
let showCardHeader = true;
if (
location.pathname.endsWith('edit') ||
location.pathname.includes('schedules/')
) {
showCardHeader = false;
}
const contentError = rolesAndTemplateError;
if (!hasRolesandTemplateLoading && contentError) {
if (contentError) {
return (
<PageSection>
<Card>
@ -158,38 +154,37 @@ function Template({ i18n, me, setBreadcrumb }) {
);
}
const showCardHeader = !(
location.pathname.endsWith('edit') ||
location.pathname.includes('schedules/')
);
return (
<PageSection>
<Card>
{showCardHeader && <RoutedTabs tabsArray={tabsArray} />}
<Switch>
<Redirect
from="/templates/:templateType/:id"
to="/templates/:templateType/:id/details"
exact
/>
{template && (
{template && (
<Switch>
<Redirect
from="/templates/:templateType/:id"
to="/templates/:templateType/:id/details"
exact
/>
<Route key="details" path="/templates/:templateType/:id/details">
<JobTemplateDetail
hasTemplateLoading={hasRolesandTemplateLoading}
hasTemplateLoading={isLoading}
template={template}
/>
</Route>
)}
{template && (
<Route key="edit" path="/templates/:templateType/:id/edit">
<JobTemplateEdit template={template} />
</Route>
)}
{template && (
<Route key="access" path="/templates/:templateType/:id/access">
<ResourceAccessList
resource={template}
apiModel={JobTemplatesAPI}
/>
</Route>
)}
{template && (
<Route
key="schedules"
path="/templates/:templateType/:id/schedules"
@ -202,43 +197,39 @@ function Template({ i18n, me, setBreadcrumb }) {
loadScheduleOptions={loadScheduleOptions}
/>
</Route>
)}
{canSeeNotificationsTab && (
<Route path="/templates/:templateType/:id/notifications">
<NotificationList
id={Number(templateId)}
canToggleNotifications={isNotifAdmin}
apiModel={JobTemplatesAPI}
/>
</Route>
)}
{template?.id && (
{canSeeNotificationsTab && (
<Route path="/templates/:templateType/:id/notifications">
<NotificationList
id={Number(templateId)}
canToggleNotifications={isNotifAdmin}
apiModel={JobTemplatesAPI}
/>
</Route>
)}
<Route path="/templates/:templateType/:id/completed_jobs">
<JobList defaultParams={{ job__job_template: template.id }} />
</Route>
)}
{template && (
<Route path="/templates/:templateType/:id/survey">
<TemplateSurvey
template={template}
canEdit={canAddAndEditSurvey}
/>
</Route>
)}
{!hasRolesandTemplateLoading && (
<Route key="not-found" path="*">
<ContentError isNotFound>
{match.params.id && (
<Link
to={`/templates/${match.params.templateType}/${match.params.id}/details`}
>
{i18n._(t`View Template Details`)}
</Link>
)}
</ContentError>
</Route>
)}
</Switch>
{!isLoading && (
<Route key="not-found" path="*">
<ContentError isNotFound>
{match.params.id && (
<Link
to={`/templates/${match?.params?.templateType}/${templateId}/details`}
>
{i18n._(t`View Template Details`)}
</Link>
)}
</ContentError>
</Route>
)}
</Switch>
)}
</Card>
</PageSection>
);

View File

@ -1,10 +1,9 @@
import React, { useState } from 'react';
import React, { useState, useCallback, useRef } from 'react';
import { withI18n } from '@lingui/react';
import { t } from '@lingui/macro';
import { Route, withRouter, Switch, useRouteMatch } from 'react-router-dom';
import { Route, withRouter, Switch } from 'react-router-dom';
import { PageSection } from '@patternfly/react-core';
import { Config } from '../../contexts/Config';
import Breadcrumbs from '../../components/Breadcrumbs/Breadcrumbs';
import { TemplateList } from './TemplateList';
import Template from './Template';
@ -13,101 +12,58 @@ import JobTemplateAdd from './JobTemplateAdd';
import WorkflowJobTemplateAdd from './WorkflowJobTemplateAdd';
function Templates({ i18n }) {
const match = useRouteMatch();
const [breadcrumbConfig, setBreadcrumbs] = useState({
const initBreadcrumbs = useRef({
'/templates': i18n._(t`Templates`),
'/templates/job_template/add': i18n._(t`Create New Job Template`),
'/templates/workflow_job_template/add': i18n._(
t`Create New Workflow Template`
),
});
const setBreadCrumbConfig = (template, schedule) => {
if (!template) {
return;
}
const breadcrumb = {
'/templates': i18n._(t`Templates`),
'/templates/job_template/add': i18n._(t`Create New Job Template`),
'/templates/workflow_job_template/add': i18n._(
t`Create New Workflow Template`
),
[`/templates/${template.type}/${template.id}`]: `${template.name}`,
[`/templates/${template.type}/${template.id}/details`]: i18n._(
t`Details`
),
[`/templates/${template.type}/${template.id}/edit`]: i18n._(
t`Edit Details`
),
[`/templates/${template.type}/${template.id}/access`]: i18n._(t`Access`),
[`/templates/${template.type}/${template.id}/notifications`]: i18n._(
t`Notifications`
),
[`/templates/${template.type}/${template.id}/completed_jobs`]: i18n._(
t`Completed Jobs`
),
[`/templates/${template.type}/${template.id}/survey`]: i18n._(t`Survey`),
[`/templates/${template.type}/${template.id}/survey/add`]: i18n._(
t`Add Question`
),
[`/templates/${template.type}/${template.id}/survey/edit`]: i18n._(
t`Edit Question`
),
[`/templates/${template.type}/${template.id}/schedules`]: i18n._(
t`Schedules`
),
[`/templates/${template.type}/${template.id}/schedules/add`]: i18n._(
t`Create New Schedule`
),
[`/templates/${template.type}/${template.id}/schedules/${schedule &&
schedule.id}`]: `${schedule && schedule.name}`,
[`/templates/${template.type}/${template.id}/schedules/${schedule &&
schedule.id}/details`]: i18n._(t`Schedule Details`),
[`/templates/${template.type}/${template.id}/schedules/${schedule &&
schedule.id}/edit`]: i18n._(t`Edit Details`),
};
setBreadcrumbs(breadcrumb);
};
const [breadcrumbConfig, setBreadcrumbs] = useState(initBreadcrumbs.current);
const setBreadcrumbConfig = useCallback(
(template, schedule) => {
if (!template) return;
const templatePath = `/templates/${template.type}/${template.id}`;
const schedulesPath = `${templatePath}/schedules`;
const surveyPath = `${templatePath}/survey`;
setBreadcrumbs({
...initBreadcrumbs.current,
[templatePath]: `${template.name}`,
[`${templatePath}/details`]: i18n._(t`Details`),
[`${templatePath}/edit`]: i18n._(t`Edit Details`),
[`${templatePath}/access`]: i18n._(t`Access`),
[`${templatePath}/notifications`]: i18n._(t`Notifications`),
[`${templatePath}/completed_jobs`]: i18n._(t`Completed Jobs`),
[surveyPath]: i18n._(t`Survey`),
[`${surveyPath}add`]: i18n._(t`Add Question`),
[`${surveyPath}/edit`]: i18n._(t`Edit Question`),
[schedulesPath]: i18n._(t`Schedules`),
[`${schedulesPath}/add`]: i18n._(t`Create New Schedule`),
[`${schedulesPath}/${schedule?.id}`]: `${schedule?.name}`,
[`${schedulesPath}/details`]: i18n._(t`Schedule Details`),
[`${schedulesPath}/edit`]: i18n._(t`Edit Details`),
});
},
[i18n]
);
return (
<>
<Breadcrumbs breadcrumbConfig={breadcrumbConfig} />
<Switch>
<Route path={`${match.path}/job_template/add`}>
<Route path="/templates/job_template/add">
<JobTemplateAdd />
</Route>
<Route path={`${match.path}/workflow_job_template/add`}>
<Route path="/templates/workflow_job_template/add">
<WorkflowJobTemplateAdd />
</Route>
<Route
path={`${match.path}/job_template/:id`}
render={({ match: newRouteMatch }) => (
<Config>
{({ me }) => (
<Template
setBreadcrumb={setBreadCrumbConfig}
me={me || {}}
match={newRouteMatch}
/>
)}
</Config>
)}
/>
<Route
path={`${match.path}/workflow_job_template/:id`}
render={({ match: newRouteMatch }) => (
<Config>
{({ me }) => (
<WorkflowJobTemplate
setBreadcrumb={setBreadCrumbConfig}
me={me || {}}
match={newRouteMatch}
/>
)}
</Config>
)}
/>
<Route path={`${match.path}`}>
<Route path="/templates/job_template/:id">
<Template setBreadcrumb={setBreadcrumbConfig} />
</Route>
<Route path="/templates/workflow_job_template/:id">
<WorkflowJobTemplate setBreadcrumb={setBreadcrumbConfig} />
</Route>
<Route path="/templates">
<PageSection>
<TemplateList />
</PageSection>

View File

@ -13,6 +13,7 @@ import {
useRouteMatch,
} from 'react-router-dom';
import RoutedTabs from '../../components/RoutedTabs';
import { useConfig } from '../../contexts/Config';
import useRequest from '../../util/useRequest';
import AppendBody from '../../components/AppendBody';
import ContentError from '../../components/ContentError';
@ -27,10 +28,11 @@ import { WorkflowJobTemplatesAPI, OrganizationsAPI } from '../../api';
import TemplateSurvey from './TemplateSurvey';
import { Visualizer } from './WorkflowJobTemplateVisualizer';
function WorkflowJobTemplate({ i18n, me, setBreadcrumb }) {
function WorkflowJobTemplate({ i18n, setBreadcrumb }) {
const location = useLocation();
const { id: templateId } = useParams();
const match = useRouteMatch();
const { id: templateId } = useParams();
const { me = {} } = useConfig();
const {
result: { isNotifAdmin, template },