refactor(docker/networks): migrate macvlan nodes selector to react [EE-4669] (#10183)

pull/10184/head
Chaim Lev-Ari 2023-09-11 15:27:04 +01:00 committed by GitHub
parent 09aa1d35a8
commit 60477ae287
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 315 additions and 220 deletions

View File

@ -1,129 +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="'hard-drive'"></pr-icon>
</div>
{{ $ctrl.titleText }}
</div>
</div>
<div class="searchBar vertical-center">
<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 for a macvlan..."
auto-focus
ng-model-options="{ debounce: 300 }"
/>
</div>
<div class="table-responsive">
<table class="table-hover nowrap-cells table">
<thead>
<tr>
<th>
<div class="vertical-center">
<span class="md-checkbox">
<input id="select_all" type="checkbox" ng-model="$ctrl.state.selectAll" ng-change="$ctrl.selectAll()" />
<label for="select_all"></label>
</span>
<table-column-header
col-title="'Name'"
can-sort="true"
is-sorted="$ctrl.state.orderBy === 'Hostname'"
is-sorted-desc="$ctrl.state.orderBy === 'Hostname' && $ctrl.state.reverseOrder"
ng-click="$ctrl.changeOrderBy('Hostname')"
></table-column-header>
</div>
</th>
<th>
<table-column-header
col-title="'Role'"
can-sort="true"
is-sorted="$ctrl.state.orderBy === 'Role'"
is-sorted-desc="$ctrl.state.orderBy === 'Role' && $ctrl.state.reverseOrder"
ng-click="$ctrl.changeOrderBy('Role')"
></table-column-header>
</th>
<th>
<table-column-header
col-title="'Engine'"
can-sort="true"
is-sorted="$ctrl.state.orderBy === 'EngineVersion'"
is-sorted-desc="$ctrl.state.orderBy === 'EngineVersion' && $ctrl.state.reverseOrder"
ng-click="$ctrl.changeOrderBy('EngineVersion')"
></table-column-header>
</th>
<th ng-if="$ctrl.showIpAddressColumn">
<table-column-header
col-title="'IP Address'"
can-sort="true"
is-sorted="$ctrl.state.orderBy === 'Addr'"
is-sorted-desc="$ctrl.state.orderBy === 'Addr' && $ctrl.state.reverseOrder"
ng-click="$ctrl.changeOrderBy('Addr')"
></table-column-header>
</th>
<th>
<table-column-header
col-title="'Status'"
can-sort="true"
is-sorted="$ctrl.state.orderBy === 'Status'"
is-sorted-desc="$ctrl.state.orderBy === 'Status' && $ctrl.state.reverseOrder"
ng-click="$ctrl.changeOrderBy('Status')"
></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))"
ng-class="{ active: item.Checked }"
>
<td>
<span class="md-checkbox">
<input id="select_{{ $index }}" type="checkbox" ng-model="item.Checked" ng-click="$ctrl.selectItem(item, $event)" />
<label for="select_{{ $index }}"></label>
</span>
<a ui-sref="docker.nodes.node({id: item.Id})" ng-if="$ctrl.accessToNodeDetails">{{ item.Hostname }}</a>
<span ng-if="!$ctrl.accessToNodeDetails">{{ item.Hostname }}</span>
</td>
<td>{{ item.Role }}</td>
<td>{{ item.EngineVersion }}</td>
<td ng-if="$ctrl.showIpAddressColumn">{{ item.Addr }}</td>
<td>
<span class="label label-{{ item.Status | nodestatusbadge }}">{{ item.Status }}</span>
</td>
</tr>
<tr ng-if="!$ctrl.dataset">
<td colspan="7" class="text-muted text-center">Loading...</td>
</tr>
<tr ng-if="$ctrl.state.filteredDataSet.length === 0">
<td colspan="7" class="text-muted text-center">No node available.</td>
</tr>
</tbody>
</table>
</div>
<div class="footer" ng-if="$ctrl.dataset">
<div class="paginationControls">
<form class="form-inline vertical-center">
<span class="limitSelector">
<span style="margin-right: 5px"> 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,15 +0,0 @@
angular.module('portainer.docker').component('macvlanNodesDatatable', {
templateUrl: './macvlanNodesDatatable.html',
controller: 'GenericDatatableController',
bindings: {
titleText: '@',
titleIcon: '@',
dataset: '<',
tableKey: '@',
orderBy: '@',
reverseOrder: '<',
showIpAddressColumn: '<',
accessToNodeDetails: '<',
state: '=',
},
});

View File

@ -37,23 +37,14 @@
<!-- network-card-input -->
<!-- nodes-selector -->
<div ng-if="$ctrl.applicationState.endpoint.mode.agentProxy && $ctrl.applicationState.endpoint.mode.provider === 'DOCKER_SWARM_MODE'">
<div class="form-group">
<div class="col-sm-12">
<macvlan-nodes-datatable
title-text="Select the nodes where you want to deploy the local configuration"
title-icon="hard-drive"
dataset="$ctrl.nodes"
table-key="nodes"
state="$ctrl.data.DatatableState"
order-by="Hostname"
show-ip-address-column="$ctrl.applicationState.endpoint.apiVersion >= 1.25"
access-to-node-details="$ctrl.isAdmin"
name="node_selector"
ng-model="tmp"
ng-required="$ctrl.requiredNodeSelection()"
></macvlan-nodes-datatable>
</div>
</div>
<macvlan-nodes-selector
dataset="$ctrl.nodes"
is-ip-column-visible="$ctrl.applicationState.endpoint.apiVersion >= 1.25"
have-access-to-node="$ctrl.isAdmin"
value="$ctrl.data.DatatableState.selectedItems"
on-change="($ctrl.onChangeSelectedNodes)"
></macvlan-nodes-selector>
<div class="form-group" ng-show="macvlanConfigurationForm.node_selector.$invalid">
<div class="col-sm-12 small text-warning">
<div ng-messages="macvlanConfigurationForm.node_selector.$error">

View File

@ -12,11 +12,18 @@ angular.module('portainer.docker').controller('NetworkMacvlanFormController', [
this.options = [];
ctrl.onChangeSelectedNodes = onChangeSelectedNodes.bind(ctrl);
function onChangeSelectedNodes(nodes) {
return $scope.$evalAsync(() => {
ctrl.data.DatatableState.selectedItems = nodes;
});
}
ctrl.requiredNodeSelection = function () {
if (ctrl.data.Scope !== 'local' || ctrl.data.DatatableState === undefined) {
return false;
}
return ctrl.data.DatatableState.selectedItemCount === 0;
return ctrl.data.DatatableState.selectedItems.length;
};
ctrl.requiredConfigSelection = function () {

View File

@ -1,5 +1,5 @@
import _ from 'lodash-es';
import { joinCommand, taskStatusBadge, trimSHA } from './utils';
import { joinCommand, taskStatusBadge, nodeStatusBadge, trimSHA } from './utils';
function includeString(text, values) {
return values.some(function (val) {
@ -75,15 +75,7 @@ angular
return 'success';
};
})
.filter('nodestatusbadge', function () {
'use strict';
return function (text) {
if (text === 'down' || text === 'Unhealthy') {
return 'danger';
}
return 'success';
};
})
.filter('nodestatusbadge', () => nodeStatusBadge)
.filter('dockerNodeAvailabilityBadge', function () {
'use strict';
return function (text) {

View File

@ -1,5 +1,5 @@
import { NodeStatus, TaskState } from 'docker-types/generated/1.41';
import _ from 'lodash';
import { TaskState } from 'docker-types/generated/1.41';
export function trimSHA(imageName: string) {
if (!imageName) {
@ -53,3 +53,11 @@ export function taskStatusBadge(text?: TaskState) {
}
return 'default';
}
export function nodeStatusBadge(text: NodeStatus['State']) {
if (text === 'down' || text === 'unknown' || text === 'disconnected') {
return 'danger';
}
return 'success';
}

View File

@ -1,47 +0,0 @@
export function NodeViewModel(data) {
this.Model = data;
this.Id = data.ID;
this.Version = data.Version.Index;
this.Name = data.Spec.Name;
this.Role = data.Spec.Role;
this.CreatedAt = data.CreatedAt;
this.UpdatedAt = data.UpdatedAt;
this.Availability = data.Spec.Availability;
var labels = data.Spec.Labels;
if (labels) {
this.Labels = Object.keys(labels).map(function (key) {
return { key: key, value: labels[key], originalKey: key, originalValue: labels[key], added: true };
});
} else {
this.Labels = [];
}
var engineLabels = data.Description.Engine.Labels;
if (engineLabels) {
this.EngineLabels = Object.keys(engineLabels).map(function (key) {
return { key: key, value: engineLabels[key] };
});
} else {
this.EngineLabels = [];
}
this.Hostname = data.Description.Hostname;
this.PlatformArchitecture = data.Description.Platform.Architecture;
this.PlatformOS = data.Description.Platform.OS;
this.CPUs = data.Description.Resources.NanoCPUs;
this.Memory = data.Description.Resources.MemoryBytes;
this.EngineVersion = data.Description.Engine.EngineVersion;
this.Plugins = data.Description.Engine.Plugins;
this.Status = data.Status.State;
if (data.Status.Addr) {
this.Addr = data.Status.Addr;
}
if (data.ManagerStatus) {
this.Leader = data.ManagerStatus.Leader;
this.Reachability = data.ManagerStatus.Reachability;
this.ManagerAddr = data.ManagerStatus.Addr;
}
}

120
app/docker/models/node.ts Normal file
View File

@ -0,0 +1,120 @@
import {
Node,
EngineDescription,
ManagerStatus,
NodeDescription,
NodeSpec,
NodeStatus,
ObjectVersion,
Platform,
ResourceObject,
} from 'docker-types/generated/1.41';
type WithRequiredProperty<Type, Key extends keyof Type> = Type & {
[Property in Key]-?: Type[Property];
};
export class NodeViewModel {
Model: Node;
Id: Node['ID'];
Version: ObjectVersion['Index'];
Name: NodeSpec['Name'];
Role: NodeSpec['Role'];
CreatedAt: Node['CreatedAt'];
UpdatedAt: Node['UpdatedAt'];
Availability: NodeSpec['Availability'];
Labels: Array<{
key: string;
value: string;
originalKey: string;
originalValue: string;
added: boolean;
}>;
EngineLabels: Array<{ key: string; value: string }>;
Hostname: NodeDescription['Hostname'];
PlatformArchitecture: Platform['Architecture'];
PlatformOS: Platform['OS'];
CPUs: ResourceObject['NanoCPUs'];
Memory: ResourceObject['MemoryBytes'];
EngineVersion: EngineDescription['EngineVersion'];
Plugins: EngineDescription['Plugins'];
Status: NodeStatus['State'];
Addr: WithRequiredProperty<NodeStatus, 'Addr'>['Addr'] = '';
Leader: ManagerStatus['Leader'];
Reachability: ManagerStatus['Reachability'];
ManagerAddr: ManagerStatus['Addr'];
constructor(data: Node) {
this.Model = data;
this.Id = data.ID;
this.Version = data.Version?.Index;
this.Name = data.Spec?.Name;
this.Role = data.Spec?.Role;
this.CreatedAt = data.CreatedAt;
this.UpdatedAt = data.UpdatedAt;
this.Availability = data.Spec?.Availability;
const labels = data.Spec?.Labels;
if (labels) {
this.Labels = Object.keys(labels).map((key) => ({
key,
value: labels[key],
originalKey: key,
originalValue: labels[key],
added: true,
}));
} else {
this.Labels = [];
}
const engineLabels = data.Description?.Engine?.Labels;
if (engineLabels) {
this.EngineLabels = Object.keys(engineLabels).map((key) => ({
key,
value: engineLabels[key],
}));
} else {
this.EngineLabels = [];
}
this.Hostname = data.Description?.Hostname;
this.PlatformArchitecture = data.Description?.Platform?.Architecture;
this.PlatformOS = data.Description?.Platform?.OS;
this.CPUs = data.Description?.Resources?.NanoCPUs;
this.Memory = data.Description?.Resources?.MemoryBytes;
this.EngineVersion = data.Description?.Engine?.EngineVersion;
this.Plugins = data.Description?.Engine?.Plugins;
this.Status = data.Status?.State;
if (data.Status?.Addr) {
this.Addr = data.Status?.Addr;
}
if (data.ManagerStatus) {
this.Leader = data.ManagerStatus.Leader;
this.Reachability = data.ManagerStatus.Reachability;
this.ManagerAddr = data.ManagerStatus.Addr;
}
}
}

View File

@ -27,11 +27,13 @@ import { StacksDatatable } from '@/react/docker/stacks/ListView/StacksDatatable'
import { containersModule } from './containers';
import { servicesModule } from './services';
import { networksModule } from './networks';
const ngModule = angular
.module('portainer.docker.react.components', [
containersModule,
servicesModule,
networksModule,
])
.component('dockerfileDetails', r2a(DockerfileDetails, ['image']))
.component('dockerHealthStatus', r2a(HealthStatus, ['health']))

View File

@ -0,0 +1,18 @@
import angular from 'angular';
import { r2a } from '@/react-tools/react2angular';
import { MacvlanNodesSelector } from '@/react/docker/networks/CreateView/MacvlanNodesSelector/MacvlanNodesSelector';
import { withUIRouter } from '@/react-tools/withUIRouter';
export const networksModule = angular
.module('portainer.docker.react.components.networks', [])
.component(
'macvlanNodesSelector',
r2a(withUIRouter(MacvlanNodesSelector), [
'dataset',
'isIpColumnVisible',
'haveAccessToNode',
'value',
'onChange',
])
).name;

View File

@ -0,0 +1,55 @@
import { HardDrive } from 'lucide-react';
import { NodeViewModel } from '@/docker/models/node';
import { Datatable } from '@@/datatables';
import { createPersistedStore } from '@@/datatables/types';
import { useTableState } from '@@/datatables/useTableState';
import { mergeOptions } from '@@/datatables/extend-options/mergeOptions';
import { withMeta } from '@@/datatables/extend-options/withMeta';
import { withControlledSelected } from '@@/datatables/extend-options/withControlledSelected';
import { useColumns } from './columns';
const tableKey = 'macvlan-nodes-selector';
const store = createPersistedStore(tableKey);
export function MacvlanNodesSelector({
dataset,
isIpColumnVisible,
haveAccessToNode,
value,
onChange,
}: {
dataset?: Array<NodeViewModel>;
isIpColumnVisible: boolean;
haveAccessToNode: boolean;
value: Array<NodeViewModel>;
onChange(value: Array<NodeViewModel>): void;
}) {
const columns = useColumns(isIpColumnVisible);
const tableState = useTableState(store, tableKey);
return (
<Datatable<NodeViewModel>
title="Select the nodes where you want to deploy the local configuration"
titleIcon={HardDrive}
columns={columns}
dataset={dataset || []}
isLoading={!dataset}
emptyContentLabel="No node available"
settingsManager={tableState}
extendTableOptions={mergeOptions(
withMeta({
table: 'macvlan-nodes',
haveAccessToNode,
}),
withControlledSelected(
(ids) =>
onChange(dataset?.filter((n) => n.Id && ids.includes(n.Id)) || []),
value.map((n) => n.Id || '')
)
)}
/>
);
}

View File

@ -0,0 +1,5 @@
import { createColumnHelper } from '@tanstack/react-table';
import { NodeViewModel } from '@/docker/models/node';
export const columnHelper = createColumnHelper<NodeViewModel>();

View File

@ -0,0 +1,20 @@
import _ from 'lodash';
import { columnHelper } from './column-helper';
import { name } from './name';
import { status } from './status';
export function useColumns(isIpColumnVisible: boolean) {
return _.compact([
name,
columnHelper.accessor('Role', {}),
columnHelper.accessor('EngineVersion', {
header: 'Engine',
}),
isIpColumnVisible &&
columnHelper.accessor('Addr', {
header: 'IP Address',
}),
status,
]);
}

View File

@ -0,0 +1,38 @@
import { CellContext } from '@tanstack/react-table';
import { NodeViewModel } from '@/docker/models/node';
import { Link } from '@@/Link';
import { isTableMeta } from '../types';
import { columnHelper } from './column-helper';
export const name = columnHelper.accessor('Hostname', {
header: 'Name',
cell: Cell,
});
function Cell({
getValue,
row: { original: item },
table: {
options: { meta },
},
}: CellContext<NodeViewModel, NodeViewModel['Hostname']>) {
if (!isTableMeta(meta)) {
throw new Error('Invalid table meta');
}
const value = getValue();
if (!meta.haveAccessToNode) {
return <>{value}</>;
}
return (
<Link to="docker.nodes.node" params={{ id: item.Id }}>
{value}
</Link>
);
}

View File

@ -0,0 +1,16 @@
import clsx from 'clsx';
import { nodeStatusBadge } from '@/docker/filters/utils';
import { columnHelper } from './column-helper';
export const status = columnHelper.accessor('Status', {
cell: ({ getValue }) => {
const value = getValue();
return (
<span className={clsx('label', `label-${nodeStatusBadge(value)}`)}>
{value}
</span>
);
},
});

View File

@ -0,0 +1,14 @@
import { TableMeta as BaseTableMeta } from '@tanstack/react-table';
import { NodeViewModel } from '@/docker/models/node';
export type TableMeta = BaseTableMeta<NodeViewModel> & {
table: 'macvlan-nodes';
haveAccessToNode: boolean;
};
export function isTableMeta(
meta?: BaseTableMeta<NodeViewModel>
): meta is TableMeta {
return !!meta && meta.table === 'macvlan-nodes';
}