Skip to content

Commit

Permalink
frontend: Add create resource UI
Browse files Browse the repository at this point in the history
These changes introduce a new UI feature that allows users to create
resources from the associated list view. Clicking the 'Create' button
opens up the EditorDialog used in the generic 'Create / Apply' button,
now accepting generic YAML/JSON text rather than explicitly expecting an
item that looks like a Kubernetes resource. The dialog box also includes
a generic template for each resource.

Fixes: #1820

Signed-off-by: Evangelos Skopelitis <eskopelitis@microsoft.com>
  • Loading branch information
skoeva committed Jul 8, 2024
1 parent c309b09 commit 5268668
Show file tree
Hide file tree
Showing 17 changed files with 332 additions and 44 deletions.
39 changes: 39 additions & 0 deletions frontend/src/components/common/CreateResourceButton.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Meta, StoryFn } from '@storybook/react';
import React from 'react';
import { Provider } from 'react-redux';
import store from '../../redux/stores/store';
import { CreateResourceButton, CreateResourceButtonProps } from './CreateResourceButton';

export default {
title: 'CreateResourceButton',
component: CreateResourceButton,
decorators: [
Story => (
<Provider store={store}>
<Story />
</Provider>
),
],
} as Meta;

const Template: StoryFn<CreateResourceButtonProps> = args => <CreateResourceButton {...args} />;

export const ConfigMap = Template.bind({});
ConfigMap.args = {
resource: 'Config Map',
};

export const Lease = Template.bind({});
Lease.args = {
resource: 'Lease',
};

export const RuntimeClass = Template.bind({});
RuntimeClass.args = {
resource: 'RuntimeClass',
};

export const Secret = Template.bind({});
Secret.args = {
resource: 'Secret',
};
142 changes: 142 additions & 0 deletions frontend/src/components/common/CreateResourceButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import React from 'react';
import { useTranslation } from 'react-i18next';
import { useDispatch } from 'react-redux';
import { getCluster } from '../../lib/cluster';
import { apply } from '../../lib/k8s/apiProxy';
import { KubeObject, KubeObjectInterface } from '../../lib/k8s/cluster';
import ConfigMap from '../../lib/k8s/configMap';
import { Lease } from '../../lib/k8s/lease';
import { RuntimeClass } from '../../lib/k8s/runtime';
import Secret from '../../lib/k8s/secret';
import { clusterAction } from '../../redux/clusterActionSlice';
import { EventStatus, HeadlampEventType, useEventCallback } from '../../redux/headlampEventSlice';
import { ActionButton, AuthVisible, EditorDialog } from '../common';

export interface CreateResourceButtonProps {
resource: KubeObject;
resourceName: string;
}

export function CreateResourceButton(props: CreateResourceButtonProps) {
const { resource, resourceName } = props;
const { t } = useTranslation(['glossary', 'translation']);
const [openDialog, setOpenDialog] = React.useState(false);
const [errorMessage, setErrorMessage] = React.useState('');
const dispatchCreateEvent = useEventCallback(HeadlampEventType.CREATE_RESOURCE);
const dispatch = useDispatch();

const applyFunc = async (newItems: KubeObjectInterface[], clusterName: string) => {
await Promise.allSettled(newItems.map(newItem => apply(newItem, clusterName))).then(
(values: any) => {
values.forEach((value: any, index: number) => {
if (value.status === 'rejected') {
let msg;
const kind = newItems[index].kind;
const name = newItems[index].metadata.name;
const apiVersion = newItems[index].apiVersion;
if (newItems.length === 1) {
msg = t('translation|Failed to create {{ kind }} {{ name }}.', { kind, name });
} else {
msg = t('translation|Failed to create {{ kind }} {{ name }} in {{ apiVersion }}.', {
kind,
name,
apiVersion,
});
}
setErrorMessage(msg);
setOpenDialog(true);
throw msg;
}
});
}
);
};

function handleSave(newItemDefs: KubeObjectInterface[]) {
let massagedNewItemDefs = newItemDefs;
const cancelUrl = location.pathname;

// check if all yaml objects are valid
for (let i = 0; i < massagedNewItemDefs.length; i++) {
if (massagedNewItemDefs[i].kind === 'List') {
// flatten this List kind with the items that it has which is a list of valid k8s resources
const deletedItem = massagedNewItemDefs.splice(i, 1);
massagedNewItemDefs = massagedNewItemDefs.concat(deletedItem[0].items);
}
if (!massagedNewItemDefs[i].metadata?.name) {
setErrorMessage(
t(`translation|Invalid: One or more of resources doesn't have a name property`)
);
return;
}
if (!massagedNewItemDefs[i].kind) {
setErrorMessage(t('translation|Invalid: Please set a kind to the resource'));
return;
}
}
// all resources name
const resourceNames = massagedNewItemDefs.map(newItemDef => newItemDef.metadata.name);
setOpenDialog(false);

const clusterName = getCluster() || '';

dispatch(
clusterAction(() => applyFunc(massagedNewItemDefs, clusterName), {
startMessage: t('translation|Applying {{ newItemName }}…', {
newItemName: resourceNames.join(','),
}),
cancelledMessage: t('translation|Cancelled applying {{ newItemName }}.', {
newItemName: resourceNames.join(','),
}),
successMessage: t('translation|Applied {{ newItemName }}.', {
newItemName: resourceNames.join(','),
}),
errorMessage: t('translation|Failed to apply {{ newItemName }}.', {
newItemName: resourceNames.join(','),
}),
cancelUrl,
})
);

dispatchCreateEvent({
status: EventStatus.CONFIRMED,
});
}

function getCurrentResource(resourceName: string) {
switch (resourceName) {
case 'ConfigMap':
return ConfigMap;
case 'Lease':
return Lease;
case 'RuntimeClass':
return RuntimeClass;
case 'Secret':
return Secret;
}
}

return (
<AuthVisible item={getCurrentResource(resourceName)} authVerb="create">
<ActionButton
color="primary"
description={t('translation|Create {{ resourceName }}', { resourceName })}
icon={'mdi:plus-circle'}
onClick={() => {
setOpenDialog(true);
}}
/>

<EditorDialog
item={resource}
open={openDialog}
onClose={() => setOpenDialog(false)}
onSave={handleSave}
saveLabel={t('translation|Apply')}
errorMessage={errorMessage}
onEditorChanged={() => setErrorMessage('')}
title={t('translation|Create {{ resourceName }}', { resourceName })}
/>
</AuthVisible>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<DocumentFragment />
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<DocumentFragment />
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<DocumentFragment />
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<DocumentFragment />
1 change: 1 addition & 0 deletions frontend/src/components/common/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const checkExports = [
'Chart',
'ConfirmDialog',
'ConfirmButton',
'CreateResourceButton',
'Dialog',
'EmptyContent',
'ErrorPage',
Expand Down
1 change: 1 addition & 0 deletions frontend/src/components/common/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,4 @@ export { default as ConfirmButton } from './ConfirmButton';
export * from './NamespacesAutocomplete';
export * from './Table/Table';
export { default as Table } from './Table';
export * from './CreateResourceButton';
21 changes: 20 additions & 1 deletion frontend/src/components/configmap/List.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,32 @@
import { useTranslation } from 'react-i18next';
import ConfigMap from '../../lib/k8s/configMap';
import ConfigMap, { KubeConfigMap } from '../../lib/k8s/configMap';
import { CreateResourceButton } from '../common/CreateResourceButton';
import ResourceListView from '../common/Resource/ResourceListView';

const BASE_EMPTY_CONFIG_MAP: KubeConfigMap = {
apiVersion: 'v1',
kind: 'ConfigMap',
metadata: {
creationTimestamp: '2023-04-27T20:31:27Z',
name: 'my-pvc',
namespace: 'default',
resourceVersion: '1234',
uid: 'abc-1234',
},
data: {},
};

export default function ConfigMapList() {
const { t } = useTranslation(['glossary', 'translation']);

return (
<ResourceListView
title={t('glossary|Config Maps')}
headerProps={{
titleSideActions: [
<CreateResourceButton resource={BASE_EMPTY_CONFIG_MAP} resourceName="ConfigMap" />,
],
}}
resourceClass={ConfigMap}
columns={[
'name',
Expand Down
25 changes: 24 additions & 1 deletion frontend/src/components/lease/List.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,35 @@
import { useTranslation } from 'react-i18next';
import { Lease } from '../../lib/k8s/lease';
import { KubeLease, Lease } from '../../lib/k8s/lease';
import { CreateResourceButton } from '../common/CreateResourceButton';
import ResourceListView from '../common/Resource/ResourceListView';

const LEASE_DUMMY_DATA: KubeLease = {
apiVersion: 'coordination.k8s.io/v1',
kind: 'Lease',
metadata: {
name: 'lease',
namespace: 'default',
creationTimestamp: '2023-04-27T20:31:27Z',
uid: '123',
},
spec: {
holderIdentity: 'holder',
leaseDurationSeconds: 10,
leaseTransitions: 1,
renewTime: '2021-03-01T00:00:00Z',
},
};

export function LeaseList() {
const { t } = useTranslation(['glossary', 'translation']);
return (
<ResourceListView
title={t('glossary|Lease')}
headerProps={{
titleSideActions: [
<CreateResourceButton resource={LEASE_DUMMY_DATA} resourceName="Lease" />,
],
}}
resourceClass={Lease}
columns={[
'name',
Expand Down
36 changes: 35 additions & 1 deletion frontend/src/components/runtimeClass/List.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,47 @@
import { useTranslation } from 'react-i18next';
import { RuntimeClass } from '../../lib/k8s/runtime';
import { KubeRuntimeClass, RuntimeClass } from '../../lib/k8s/runtime';
import { CreateResourceButton } from '../common/CreateResourceButton';
import ResourceListView from '../common/Resource/ResourceListView';

const BASE_RC: KubeRuntimeClass = {
apiVersion: 'node.k8s.io/v1',
kind: 'RuntimeClass',
metadata: {
name: 'runtime-class',
namespace: 'default',
creationTimestamp: '2023-04-27T20:31:27Z',
uid: '123',
},
handler: 'handler',
overhead: {
cpu: '100m',
memory: '128Mi',
},
scheduling: {
nodeSelector: {
key: 'value',
},
tolerations: [
{
key: 'key',
operator: 'Equal',
value: 'value',
effect: 'NoSchedule',
tolerationSeconds: 10,
},
],
},
};

export function RuntimeClassList() {
const { t } = useTranslation(['glossary', 'translation']);

return (
<ResourceListView
title={t('glossary|RuntimeClass')}
headerProps={{
titleSideActions: [<CreateResourceButton resource={BASE_RC} resourceName="RuntimeClass" />],
}}
resourceClass={RuntimeClass}
columns={[
'name',
Expand Down
22 changes: 21 additions & 1 deletion frontend/src/components/secret/List.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,33 @@
import { useTranslation } from 'react-i18next';
import Secret from '../../lib/k8s/secret';
import Secret, { KubeSecret } from '../../lib/k8s/secret';
import { CreateResourceButton } from '../common/CreateResourceButton';
import ResourceListView from '../common/Resource/ResourceListView';

const BASE_EMPTY_SECRET: KubeSecret = {
apiVersion: 'v1',
kind: 'Secret',
metadata: {
creationTimestamp: '2023-04-27T20:31:27Z',
name: 'my-pvc',
namespace: 'default',
resourceVersion: '1234',
uid: 'abc-1234',
},
data: {},
type: 'bla',
};

export default function SecretList() {
const { t } = useTranslation(['glossary', 'translation']);

return (
<ResourceListView
title={t('Secrets')}
headerProps={{
titleSideActions: [
<CreateResourceButton resource={BASE_EMPTY_SECRET} resourceName="Secret" />,
],
}}
resourceClass={Secret}
columns={[
'name',
Expand Down
17 changes: 9 additions & 8 deletions frontend/src/i18n/locales/de/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,15 @@
"Something went wrong.": "Etwas ist schief gelaufen.",
"No": "Nein",
"Yes": "Ja",
"Failed to create {{ kind }} {{ name }}.": "Erstellung von {{ kind }} fehlgeschlagen {{ name }}.",
"Failed to create {{ kind }} {{ name }} in {{ apiVersion }}.": "Fehler beim Erstellen von {{ kind }} {{ name }} in {{ apiVersion }}.",
"Invalid: One or more of resources doesn't have a name property": "Ungültig: Eine oder mehrere der Ressourcen haben keine Namenseigenschaft",
"Invalid: Please set a kind to the resource": "Ungültig: Bitte geben Sie einen Typ für die Ressource an",
"Applying {{ newItemName }}…": "Anwenden von {{ newItemName }}…",
"Cancelled applying {{ newItemName }}.": "Die Anwendung von {{ newItemName }} wurde abgebrochen.",
"Applied {{ newItemName }}.": "Angewandt {{ newItemName }}.",
"Failed to apply {{ newItemName }}.": "Die Anwendung von {{ newItemName }} ist fehlgeschlagen.",
"Create {{ resourceName }}": "",
"Toggle fullscreen": "Vollbild ein/aus",
"Close": "Schließen",
"Uh-oh! Something went wrong.": "Oh-oh! Etwas ist schief gelaufen.",
Expand Down Expand Up @@ -154,14 +163,6 @@
"Read more": "Mehr lesen",
"Dismiss": "Schließen",
"Install the metrics-server to get usage data.": "Installieren Sie den Metriken-Server, um Nutzungsdaten zu erhalten.",
"Failed to create {{ kind }} {{ name }}.": "Erstellung von {{ kind }} fehlgeschlagen {{ name }}.",
"Failed to create {{ kind }} {{ name }} in {{ apiVersion }}.": "Fehler beim Erstellen von {{ kind }} {{ name }} in {{ apiVersion }}.",
"Invalid: One or more of resources doesn't have a name property": "Ungültig: Eine oder mehrere der Ressourcen haben keine Namenseigenschaft",
"Invalid: Please set a kind to the resource": "Ungültig: Bitte geben Sie einen Typ für die Ressource an",
"Applying {{ newItemName }}…": "Anwenden von {{ newItemName }}…",
"Cancelled applying {{ newItemName }}.": "Die Anwendung von {{ newItemName }} wurde abgebrochen.",
"Applied {{ newItemName }}.": "Angewandt {{ newItemName }}.",
"Failed to apply {{ newItemName }}.": "Die Anwendung von {{ newItemName }} ist fehlgeschlagen.",
"Create / Apply": "Erstellen / Anwenden",
"Create": "Erstellen",
"Deleting item {{ itemName }}…": "Lösche Element {{ itemName }} …",
Expand Down
Loading

0 comments on commit 5268668

Please sign in to comment.