refactor(edge/groups): migrate view to react [EE-4683] (#10592)

pull/10631/head
Chaim Lev-Ari 2023-11-14 12:57:27 +02:00 committed by GitHub
parent 1f2f4525e3
commit 99b39da03d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 199 additions and 228 deletions

View File

@ -1,126 +0,0 @@
<div class="datatable">
<rd-widget>
<rd-widget-body classes="no-padding">
<div class="toolBar">
<div class="toolBarTitle vertical-center">
<div class="widget-icon space-right">
<pr-icon icon="'layout-grid'"></pr-icon>
</div>
Edge Groups
</div>
<div class="searchBar vertical-center leading-none">
<pr-icon icon="'search'" class-name="'searchIcon'"></pr-icon>
<input
type="text"
class="searchInput"
ng-model="$ctrl.state.textFilter"
ng-change="$ctrl.onTextFilterChange()"
placeholder="Search..."
ng-model-options="{ debounce: 300 }"
data-cy="edgeGroup-searchInput"
/>
</div>
<div class="actionBar">
<button
type="button"
class="btn btn-sm btn-danger"
ng-disabled="$ctrl.state.selectedItemCount === 0"
ng-click="$ctrl.removeAction($ctrl.state.selectedItems)"
data-cy="edgeGroup-removeEdgeGroupButton"
>
<pr-icon icon="'trash-2'"></pr-icon> Remove
</button>
<button type="button" class="btn btn-sm btn-primary" ui-sref="edge.groups.new" data-cy="edgeGroup-addEdgeGroupButton">
<pr-icon icon="'plus'"></pr-icon> Add Edge group
</button>
</div>
</div>
<div class="table-responsive">
<table class="table-hover nowrap-cells table" data-cy="edgeGroup-edgeGroupTable">
<thead>
<tr>
<th class="flex">
<span class="md-checkbox">
<input id="select_all" type="checkbox" ng-model="$ctrl.state.selectAll" ng-change="$ctrl.selectAll()" data-cy="edgeGroup-selectAllCheckbox" />
<label for="select_all"></label>
</span>
<table-column-header
col-title="'Name'"
can-sort="true"
is-sorted="$ctrl.state.orderBy === 'Name'"
is-sorted-desc="$ctrl.state.orderBy === 'Name' && $ctrl.state.reverseOrder"
ng-click="$ctrl.changeOrderBy('Name')"
></table-column-header>
</th>
<th>
<table-column-header
col-title="'Environments Count'"
can-sort="true"
is-sorted="$ctrl.state.orderBy === 'TrustedEndpoints.length'"
is-sorted-desc="$ctrl.state.orderBy === 'TrustedEndpoints.length' && $ctrl.state.reverseOrder"
ng-click="$ctrl.changeOrderBy('TrustedEndpoints.length')"
></table-column-header>
</th>
<th>
<table-column-header
col-title="'Group Type'"
can-sort="true"
is-sorted="$ctrl.state.orderBy === 'Dynamic'"
is-sorted-desc="$ctrl.state.orderBy === 'Dynamic' && $ctrl.state.reverseOrder"
ng-click="$ctrl.changeOrderBy('Dynamic')"
></table-column-header>
</th>
</tr>
</thead>
<tbody>
<tr
dir-paginate="item in ($ctrl.state.filteredDataSet = ($ctrl.dataset | filter:$ctrl.state.textFilter | orderBy:$ctrl.state.orderBy:$ctrl.state.reverseOrder | itemsPerPage: $ctrl.state.paginatedItemLimit)) track by $index"
ng-class="{ active: item.Checked }"
>
<td>
<span class="md-checkbox">
<input
id="select_{{ $index }}"
type="checkbox"
ng-model="item.Checked"
ng-disabled="item.HasEdgeStack || item.HasEdgeJob"
ng-click="$ctrl.selectItem(item, $event)"
/>
<label for="select_{{ $index }}"></label>
</span>
<a ui-sref="edge.groups.edit({groupId: item.Id})">{{ item.Name }}</a>
<span ng-if="item.HasEdgeStack || item.HasEdgeJob" class="label label-info image-tag space-left">in use</span>
</td>
<td>{{ item.TrustedEndpoints.length }}</td>
<td>{{ item.Dynamic ? 'Dynamic' : 'Static' }}</td>
</tr>
<tr ng-if="!$ctrl.dataset">
<td colspan="4" class="text-muted text-center">Loading...</td>
</tr>
<tr ng-if="$ctrl.state.filteredDataSet.length === 0">
<td colspan="4" class="text-muted text-center"> No Edge group available. </td>
</tr>
</tbody>
</table>
</div>
<div class="footer" ng-if="$ctrl.dataset">
<div class="infoBar" ng-if="$ctrl.state.selectedItemCount !== 0"> {{ $ctrl.state.selectedItemCount }} item(s) selected </div>
<div class="paginationControls">
<form class="form-inline">
<span class="limitSelector">
<span class="mr-1"> Items per page </span>
<select class="form-control" ng-model="$ctrl.state.paginatedItemLimit" ng-change="$ctrl.changePaginationLimit()" data-cy="component-paginationSelect">
<option value="0">All</option>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
</span>
<dir-pagination-controls max-size="5"></dir-pagination-controls>
</form>
</div>
</div>
</rd-widget-body>
</rd-widget>
</div>

View File

@ -1,17 +0,0 @@
import angular from 'angular';
export class EdgeGroupsDatatableController {
/* @ngInject */
constructor($scope, $controller) {
const allowSelection = this.allowSelection;
angular.extend(this, $controller('GenericDatatableController', { $scope: $scope }));
this.allowSelection = allowSelection.bind(this);
}
/**
* Override this method to allow/deny selection
*/
allowSelection(item) {
return !item.HasEdgeStack;
}
}

View File

@ -1,17 +0,0 @@
import angular from 'angular';
import { EdgeGroupsDatatableController } from './groupsDatatableController';
angular.module('portainer.edge').component('edgeGroupsDatatable', {
templateUrl: './groupsDatatable.html',
controller: EdgeGroupsDatatableController,
bindings: {
dataset: '<',
titleIcon: '@',
tableKey: '@',
orderBy: '@',
removeAction: '<',
updateAction: '<',
reverseOrder: '<',
},
});

View File

@ -5,7 +5,8 @@ import { withCurrentUser } from '@/react-tools/withCurrentUser';
import { withReactQuery } from '@/react-tools/withReactQuery';
import { withUIRouter } from '@/react-tools/withUIRouter';
import { WaitingRoomView } from '@/react/edge/edge-devices/WaitingRoomView';
import { ListView } from '@/react/edge/edge-stacks/ListView';
import { ListView as EdgeStacksListView } from '@/react/edge/edge-stacks/ListView';
import { ListView as EdgeGroupsListView } from '@/react/edge/edge-groups/ListView';
export const viewsModule = angular
.module('portainer.edge.react.views', [])
@ -15,5 +16,9 @@ export const viewsModule = angular
)
.component(
'edgeStacksView',
r2a(withUIRouter(withCurrentUser(ListView)), [])
r2a(withUIRouter(withCurrentUser(EdgeStacksListView)), [])
)
.component(
'edgeGroupsView',
r2a(withUIRouter(withCurrentUser(EdgeGroupsListView)), [])
).name;

View File

@ -1,7 +0,0 @@
<page-header title="'Edge Groups'" breadcrumbs="['Edge Groups']" reload="true"> </page-header>
<div class="row">
<div class="col-sm-12">
<edge-groups-datatable title-icon="dice-4" table-key="EdgeGroups" order-by="Name" dataset="$ctrl.items" remove-action="$ctrl.removeAction"></edge-groups-datatable>
</div>
</div>

View File

@ -1,47 +0,0 @@
import _ from 'lodash-es';
import { confirmDelete } from '@@/modals/confirm';
export class EdgeGroupsController {
/* @ngInject */
constructor($async, $state, EdgeGroupService, Notifications) {
this.$async = $async;
this.$state = $state;
this.EdgeGroupService = EdgeGroupService;
this.Notifications = Notifications;
this.removeAction = this.removeAction.bind(this);
this.removeActionAsync = this.removeActionAsync.bind(this);
}
async $onInit() {
try {
this.items = await this.EdgeGroupService.groups();
} catch (err) {
this.items = [];
this.Notifications.error('Failure', err, 'Unable to retrieve Edge groups');
}
}
removeAction(selectedItems) {
return this.$async(this.removeActionAsync, selectedItems);
}
async removeActionAsync(selectedItems) {
if (!(await confirmDelete('Do you want to remove the selected Edge Group(s)?'))) {
return;
}
for (let item of selectedItems) {
try {
await this.EdgeGroupService.remove(item.Id);
this.Notifications.success('Edge Group successfully removed', item.Name);
_.remove(this.items, item);
} catch (err) {
this.Notifications.error('Failure', err, 'Unable to remove Edge Group');
}
}
this.$state.reload();
}
}

View File

@ -1,8 +0,0 @@
import angular from 'angular';
import { EdgeGroupsController } from './edgeGroupsViewController';
angular.module('portainer.edge').component('edgeGroupsView', {
templateUrl: './edgeGroupsView.html',
controller: EdgeGroupsController,
});

View File

@ -0,0 +1,37 @@
import { LayoutGrid } from 'lucide-react';
import { Datatable } from '@@/datatables';
import { useTableState } from '@@/datatables/useTableState';
import { createPersistedStore } from '@@/datatables/types';
import { useEdgeGroups } from '../queries/useEdgeGroups';
import { columns } from './columns';
import { TableActions } from './TableActions';
const tableKey = 'edge-groups';
const settingsStore = createPersistedStore(tableKey);
export function EdgeGroupsDatatable() {
const tableState = useTableState(settingsStore, tableKey);
const edgeGroupsQuery = useEdgeGroups();
return (
<Datatable
title="Edge Groups"
titleIcon={LayoutGrid}
columns={columns}
dataset={edgeGroupsQuery.data || []}
settingsManager={tableState}
emptyContentLabel="No Edge group available."
isLoading={edgeGroupsQuery.isLoading}
renderTableActions={(selectedItems) => (
<TableActions selectedItems={selectedItems} />
)}
isRowSelectable={({ original: item }) =>
!(item.HasEdgeStack || item.HasEdgeJob || item.HasEdgeConfig)
}
/>
);
}

View File

@ -0,0 +1,12 @@
import { PageHeader } from '@@/PageHeader';
import { EdgeGroupsDatatable } from './EdgeGroupsDatatable';
export function ListView() {
return (
<>
<PageHeader title="Edge Groups" breadcrumbs="Edge Groups" reload />
<EdgeGroupsDatatable />
</>
);
}

View File

@ -0,0 +1,37 @@
import { notifySuccess } from '@/portainer/services/notifications';
import { AddButton } from '@@/buttons';
import { DeleteButton } from '@@/buttons/DeleteButton';
import { EdgeGroup } from '../types';
import { useDeleteEdgeGroupsMutation } from './useDeleteEdgeGroupMutation';
export function TableActions({
selectedItems,
}: {
selectedItems: Array<EdgeGroup>;
}) {
const removeMutation = useDeleteEdgeGroupsMutation();
return (
<div className="flex items-center gap-2">
<DeleteButton
confirmMessage="Do you want to remove the selected Edge Group(s)?"
disabled={selectedItems.length === 0}
onConfirmed={() => handleRemove(selectedItems)}
/>
<AddButton>Add Edge group</AddButton>
</div>
);
async function handleRemove(selectedItems: Array<EdgeGroup>) {
const ids = selectedItems.map((item) => item.Id);
removeMutation.mutate(ids, {
onSuccess: () => {
notifySuccess('Success', 'Edge Group(s) removed');
},
});
}
}

View File

@ -0,0 +1,5 @@
import { createColumnHelper } from '@tanstack/react-table';
import { EdgeGroupListItemResponse } from '../../queries/useEdgeGroups';
export const columnHelper = createColumnHelper<EdgeGroupListItemResponse>();

View File

@ -0,0 +1,13 @@
import { columnHelper } from './helper';
import { name } from './name';
export const columns = [
name,
columnHelper.accessor((group) => group.TrustedEndpoints.length, {
header: 'Environments Count',
}),
columnHelper.accessor('Dynamic', {
header: 'Group Type',
cell: ({ getValue }) => (getValue() ? 'Dynamic' : 'Static'),
}),
];

View File

@ -0,0 +1,34 @@
import { CellContext } from '@tanstack/react-table';
import { Link } from '@@/Link';
import { EdgeGroupListItemResponse } from '../../queries/useEdgeGroups';
import { columnHelper } from './helper';
export const name = columnHelper.accessor('Name', {
header: 'Name',
cell: NameCell,
});
function NameCell({
renderValue,
row: { original: item },
}: CellContext<EdgeGroupListItemResponse, unknown>) {
const name = renderValue() || '';
if (typeof name !== 'string') {
return null;
}
return (
<>
<Link to=".edit" params={{ groupId: item.Id }} title={name}>
{name}
</Link>
{(item.HasEdgeJob || item.HasEdgeStack) && (
<span className="label label-info image-tag space-left">in use</span>
)}
</>
);
}

View File

@ -0,0 +1 @@
export { ListView } from './ListView';

View File

@ -0,0 +1,35 @@
import { useMutation, useQueryClient } from 'react-query';
import { promiseSequence } from '@/portainer/helpers/promise-utils';
import axios, { parseAxiosError } from '@/portainer/services/axios';
import {
mutationOptions,
withError,
withInvalidate,
} from '@/react-tools/react-query';
import { EdgeGroup } from '../types';
import { buildUrl } from '../queries/build-url';
import { queryKeys } from '../queries/query-keys';
export function useDeleteEdgeGroupsMutation() {
const queryClient = useQueryClient();
return useMutation(
(edgeGroupIds: Array<EdgeGroup['Id']>) =>
promiseSequence(
edgeGroupIds.map((edgeGroupId) => () => deleteEdgeGroup(edgeGroupId))
),
mutationOptions(
withError('Unable to delete Edge Group(s)'),
withInvalidate(queryClient, [queryKeys.base()])
)
);
}
async function deleteEdgeGroup(id: EdgeGroup['Id']) {
try {
await axios.delete(buildUrl({ id }));
} catch (e) {
throw parseAxiosError(e, 'Unable to delete edge Group');
}
}

View File

@ -1,3 +1,10 @@
export function buildUrl() {
return '/edge_groups';
import { EdgeGroup } from '../types';
export function buildUrl({
action,
id,
}: { id?: EdgeGroup['Id']; action?: string } = {}) {
const baseUrl = '/edge_groups';
const url = id ? `${baseUrl}/${id}` : baseUrl;
return action ? `${url}/${action}` : url;
}

View File

@ -1,15 +1,22 @@
import { useQuery } from 'react-query';
import axios, { parseAxiosError } from '@/portainer/services/axios';
import { EnvironmentType } from '@/react/portainer/environments/types';
import {
EnvironmentId,
EnvironmentType,
} from '@/react/portainer/environments/types';
import { EdgeGroup } from '../types';
import { queryKeys } from './query-keys';
import { buildUrl } from './build-url';
interface EdgeGroupListItemResponse extends EdgeGroup {
export interface EdgeGroupListItemResponse extends EdgeGroup {
EndpointTypes: Array<EnvironmentType>;
HasEdgeStack?: boolean;
HasEdgeJob?: boolean;
HasEdgeConfig?: boolean;
TrustedEndpoints: Array<EnvironmentId>;
}
async function getEdgeGroups() {