From mboxrd@z Thu Jan  1 00:00:00 1970
Return-Path: <pdm-devel-bounces@lists.proxmox.com>
Received: from firstgate.proxmox.com (firstgate.proxmox.com [212.224.123.68])
	by lore.proxmox.com (Postfix) with ESMTPS id 015981FF164
	for <inbox@lore.proxmox.com>; Fri, 28 Feb 2025 16:25:25 +0100 (CET)
Received: from firstgate.proxmox.com (localhost [127.0.0.1])
	by firstgate.proxmox.com (Proxmox) with ESMTP id E00E2124FD;
	Fri, 28 Feb 2025 16:25:21 +0100 (CET)
From: Stefan Hanreich <s.hanreich@proxmox.com>
To: pdm-devel@lists.proxmox.com
Date: Fri, 28 Feb 2025 16:18:00 +0100
Message-Id: <20250228151803.158984-24-s.hanreich@proxmox.com>
X-Mailer: git-send-email 2.39.5
In-Reply-To: <20250228151803.158984-1-s.hanreich@proxmox.com>
References: <20250228151803.158984-1-s.hanreich@proxmox.com>
MIME-Version: 1.0
X-SPAM-LEVEL: Spam detection results:  0
 AWL -0.224 Adjusted score from AWL reputation of From: address
 BAYES_00                 -1.9 Bayes spam probability is 0 to 1%
 DMARC_MISSING             0.1 Missing DMARC policy
 KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment
 KAM_LAZY_DOMAIN_SECURITY 1 Sending domain does not have any anti-forgery
 methods
 RCVD_IN_VALIDITY_CERTIFIED_BLOCKED 0.001 ADMINISTRATOR NOTICE: The query to
 Validity was blocked. See
 https://knowledge.validity.com/hc/en-us/articles/20961730681243 for more
 information.
 RCVD_IN_VALIDITY_RPBL_BLOCKED 0.001 ADMINISTRATOR NOTICE: The query to
 Validity was blocked. See
 https://knowledge.validity.com/hc/en-us/articles/20961730681243 for more
 information.
 RCVD_IN_VALIDITY_SAFE_BLOCKED 0.001 ADMINISTRATOR NOTICE: The query to
 Validity was blocked. See
 https://knowledge.validity.com/hc/en-us/articles/20961730681243 for more
 information.
 RDNS_NONE 0.793 Delivered to internal network by a host with no rDNS
 SPF_HELO_NONE           0.001 SPF: HELO does not publish an SPF Record
 SPF_NONE                0.001 SPF: sender does not publish an SPF Record
 URIBL_BLOCKED 0.001 ADMINISTRATOR NOTICE: The query to URIBL was blocked. See
 http://wiki.apache.org/spamassassin/DnsBlocklists#dnsbl-block for more
 information. [mod.rs]
Subject: [pdm-devel] [PATCH proxmox-datacenter-manager 10/13] ui: sdn: add
 AddZoneWindow component
X-BeenThere: pdm-devel@lists.proxmox.com
X-Mailman-Version: 2.1.29
Precedence: list
List-Id: Proxmox Datacenter Manager development discussion
 <pdm-devel.lists.proxmox.com>
List-Unsubscribe: <https://lists.proxmox.com/cgi-bin/mailman/options/pdm-devel>, 
 <mailto:pdm-devel-request@lists.proxmox.com?subject=unsubscribe>
List-Archive: <http://lists.proxmox.com/pipermail/pdm-devel/>
List-Post: <mailto:pdm-devel@lists.proxmox.com>
List-Help: <mailto:pdm-devel-request@lists.proxmox.com?subject=help>
List-Subscribe: <https://lists.proxmox.com/cgi-bin/mailman/listinfo/pdm-devel>, 
 <mailto:pdm-devel-request@lists.proxmox.com?subject=subscribe>
Reply-To: Proxmox Datacenter Manager development discussion
 <pdm-devel@lists.proxmox.com>
Content-Type: text/plain; charset="us-ascii"
Content-Transfer-Encoding: 7bit
Errors-To: pdm-devel-bounces@lists.proxmox.com
Sender: "pdm-devel" <pdm-devel-bounces@lists.proxmox.com>

Adds an edit window for creating a new zone. This windows shows a form
containing all fields required to create new zone via the create_zone
API endpoint.

Signed-off-by: Stefan Hanreich <s.hanreich@proxmox.com>
---
 ui/src/sdn/evpn/add_zone.rs | 229 ++++++++++++++++++++++++++++++++++++
 ui/src/sdn/evpn/mod.rs      |   3 +
 2 files changed, 232 insertions(+)
 create mode 100644 ui/src/sdn/evpn/add_zone.rs

diff --git a/ui/src/sdn/evpn/add_zone.rs b/ui/src/sdn/evpn/add_zone.rs
new file mode 100644
index 0000000..3b6b0cb
--- /dev/null
+++ b/ui/src/sdn/evpn/add_zone.rs
@@ -0,0 +1,229 @@
+use std::{collections::HashSet, rc::Rc};
+
+use anyhow::{bail, Error};
+use pdm_client::types::{ListController, SDN_ID_SCHEMA};
+use proxmox_yew_comp::{EditWindow, SchemaValidation};
+use pwt::{
+    css,
+    props::{
+        ContainerBuilder, CssBorderBuilder, CssPaddingBuilder, ExtractPrimaryKey, FieldBuilder,
+        SubmitCallback, WidgetBuilder, WidgetStyleBuilder,
+    },
+    state::{Selection, Store},
+    tr,
+    widget::{
+        data_table::{DataTable, DataTableColumn, DataTableHeader, MultiSelectMode},
+        error_message,
+        form::{
+            Field, FormContext, ManagedField, ManagedFieldContext, ManagedFieldMaster,
+            ManagedFieldState, Number,
+        },
+        Column, Container, GridPicker, InputPanel,
+    },
+};
+use pwt_macros::widget;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use yew::{function_component, virtual_dom::Key, Callback, Html, Properties};
+
+#[derive(Properties, PartialEq)]
+pub struct AddZoneWindowProps {
+    pub controllers: Rc<Vec<ListController>>,
+    pub on_submit_callback: SubmitCallback<FormContext>,
+    pub on_close_callback: Callback<()>,
+}
+
+#[function_component]
+pub fn AddZoneWindow(props: &AddZoneWindowProps) -> Html {
+    let controllers = props.controllers.clone();
+
+    EditWindow::new(tr!("Add VRF"))
+        .renderer(move |form_ctx: &FormContext| {
+            InputPanel::new()
+                .class(css::FlexFit)
+                .padding(4)
+                .width("auto")
+                .with_field(
+                    tr!("Zone ID"),
+                    Field::new()
+                        .name("zone")
+                        .schema(&SDN_ID_SCHEMA)
+                        .required(true),
+                )
+                .with_field(
+                    tr!("VRF VXLAN VNI"),
+                    Number::<u32>::new()
+                        .min(1)
+                        .max(16777215)
+                        .name("vrf-vxlan")
+                        .required(true),
+                )
+                .with_custom_child(
+                    Column::new()
+                        .with_child(ControllerTable::new(controllers.clone()).name("remotes"))
+                        .with_optional_child(
+                            form_ctx
+                                .read()
+                                .get_field_valid("remotes")
+                                .and_then(|result| result.err().as_deref().map(error_message)),
+                        ),
+                )
+                .into()
+        })
+        .on_close(props.on_close_callback.clone())
+        .on_submit(Some(props.on_submit_callback.clone()))
+        .into()
+}
+
+#[widget(comp=ManagedFieldMaster<ControllerTableComponent>, @input)]
+#[derive(Clone, PartialEq, Properties)]
+struct ControllerTable {
+    controllers: Rc<Vec<ListController>>,
+}
+
+impl ControllerTable {
+    pub fn new(controllers: Rc<Vec<ListController>>) -> Self {
+        yew::props!(Self { controllers })
+    }
+}
+
+#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
+struct ControllerTableEntry {
+    remote: String,
+    controller: String,
+    #[serde(skip)]
+    asn: u32,
+}
+
+impl ExtractPrimaryKey for ControllerTableEntry {
+    fn extract_key(&self) -> Key {
+        Key::from(format!("{}/{}", self.remote, self.controller))
+    }
+}
+
+struct ControllerTableComponent {
+    store: Store<ControllerTableEntry>,
+    selection: Selection,
+}
+
+enum ControllerTableMsg {
+    SelectionChange,
+}
+
+impl ManagedField for ControllerTableComponent {
+    type Properties = ControllerTable;
+    type Message = ControllerTableMsg;
+    type ValidateClosure = ();
+
+    fn validation_args(_props: &Self::Properties) -> Self::ValidateClosure {}
+
+    fn validator(_props: &Self::ValidateClosure, value: &Value) -> Result<Value, Error> {
+        let selected_entries: Vec<ControllerTableEntry> = serde_json::from_value(value.clone())?;
+
+        if selected_entries.is_empty() {
+            bail!("at least one remote needs to be selected");
+        }
+
+        let mut unique = HashSet::new();
+
+        if !selected_entries
+            .iter()
+            .all(|entry| unique.insert(entry.remote.as_str()))
+        {
+            bail!("can only create the zone once per remote!")
+        }
+
+        Ok(value.clone())
+    }
+
+    fn setup(_props: &Self::Properties) -> ManagedFieldState {
+        ManagedFieldState {
+            value: Value::Null,
+            valid: Ok(()),
+            default: Value::Array(Vec::new()),
+            radio_group: false,
+            unique: false,
+        }
+    }
+
+    fn create(ctx: &ManagedFieldContext<Self>) -> Self {
+        let link = ctx.link().clone();
+        let selection = Selection::new().multiselect(true).on_select(move |_| {
+            link.send_message(Self::Message::SelectionChange);
+        });
+
+        let store = Store::new();
+        store.set_data(
+            ctx.props()
+                .controllers
+                .iter()
+                .map(|controller| ControllerTableEntry {
+                    remote: controller.remote.clone(),
+                    controller: controller.controller.controller.clone(),
+                    asn: controller.controller.asn.expect("EVPN controller has ASN"),
+                })
+                .collect(),
+        );
+
+        Self { store, selection }
+    }
+
+    fn update(&mut self, ctx: &ManagedFieldContext<Self>, msg: Self::Message) -> bool {
+        match msg {
+            Self::Message::SelectionChange => {
+                let read_guard = self.store.read();
+
+                ctx.link().update_value(
+                    serde_json::to_value(
+                        self.selection
+                            .selected_keys()
+                            .iter()
+                            // todo: handle miss?
+                            .filter_map(|key| read_guard.lookup_record(key))
+                            .collect::<Vec<_>>(),
+                    )
+                    .unwrap(),
+                );
+            }
+        }
+
+        false
+    }
+
+    fn view(&self, _ctx: &ManagedFieldContext<Self>) -> Html {
+        let table = DataTable::new(COLUMNS.with(Rc::clone), self.store.clone())
+            .multiselect_mode(MultiSelectMode::Simple)
+            .border(true)
+            .class(css::FlexFit);
+
+        Container::new()
+            .with_child(GridPicker::new(table).selection(self.selection.clone()))
+            .into()
+    }
+}
+
+thread_local! {
+    static COLUMNS: Rc<Vec<DataTableHeader<ControllerTableEntry>>> =
+        Rc::new(vec![
+            DataTableColumn::selection_indicator().into(),
+            DataTableColumn::new(tr!("Remote"))
+                .flex(1)
+                .render(move |item: &ControllerTableEntry| item.remote.as_str().into())
+                .sorter(|a: &ControllerTableEntry, b: &ControllerTableEntry| {
+                    a.remote.cmp(&b.remote)
+                })
+                .into(),
+            DataTableColumn::new(tr!("Controller"))
+                .flex(1)
+                .render(move |item: &ControllerTableEntry| item.controller.as_str().into())
+                .sorter(|a: &ControllerTableEntry, b: &ControllerTableEntry| {
+                    a.controller.cmp(&b.controller)
+                })
+                .into(),
+            DataTableColumn::new(tr!("ASN"))
+                .flex(1)
+                .render(move |item: &ControllerTableEntry| item.asn.into())
+                .sorter(|a: &ControllerTableEntry, b: &ControllerTableEntry| a.asn.cmp(&b.asn))
+                .into(),
+        ]);
+}
diff --git a/ui/src/sdn/evpn/mod.rs b/ui/src/sdn/evpn/mod.rs
index 4db42b4..f02eb7b 100644
--- a/ui/src/sdn/evpn/mod.rs
+++ b/ui/src/sdn/evpn/mod.rs
@@ -6,3 +6,6 @@ pub use vrf_tree::VrfTree;
 
 mod add_vnet;
 pub use add_vnet::AddVnetWindow;
+
+mod add_zone;
+pub use add_zone::AddZoneWindow;
-- 
2.39.5


_______________________________________________
pdm-devel mailing list
pdm-devel@lists.proxmox.com
https://lists.proxmox.com/cgi-bin/mailman/listinfo/pdm-devel