Browse Source

per Fred & Fab

namnguyen 6 tháng trước cách đây
mục cha
commit
bafa9f08d7

+ 2 - 1
doc/gui/extension/example_library/example_library.py

@@ -37,8 +37,9 @@ class ExampleLibrary(ElementLibrary):
                 "data",
                 {
                     "data": ElementProperty(PropertyType.data),
-                    "rows_per_page": ElementProperty(PropertyType.number),
                 },
+                # The name of the React component (BasicTable) that implements this custom
+                # element, exported as BasicTable in front-end/src/index.ts
                 react_component="BasicTable",
             ),
         }

+ 22 - 77
doc/gui/extension/example_library/front-end/src/BasicTable.tsx

@@ -1,97 +1,58 @@
-import React, { useEffect, useMemo, useState } from "react";
+import React, { useEffect, useMemo, useRef, useState } from "react";
 import {
     createRequestDataUpdateAction,
-    RowType,
-    RowValue,
     useDispatch,
     useDispatchRequestUpdateOnFirstRender,
     useModule,
+    TaipyDynamicProps,
+    TableValueType,
+    RowType,
+    RowValue,
 } from "taipy-gui";
 
-interface BasicTableProps {
-    id?: string;
-    updateVarName?: string;
-    updateVars?: string;
-    data: Record<string, Record<string, unknown>>;
-    rowsPerPage?: number;
+interface BasicTableProps extends TaipyDynamicProps {
+    data: TableValueType;
 }
 
 const BasicTable = (props: BasicTableProps) => {
-    const {
-        data,
-        rowsPerPage,
-        updateVarName = "",
-        updateVars = "",
-        id
-    } = props;
-    const [value, setValue] = useState<Record<string, unknown>>({});
-    const [currentPage, setCurrentPage] = useState(1);
+    const { data, updateVarName = "", updateVars = "", id } = props;
+    const [value, setValue] = useState<TableValueType>({});
+    const pageKey = useRef("no-page-key");
     const dispatch = useDispatch();
     const module = useModule();
     const refresh = data?.__taipy_refresh !== undefined;
-    useDispatchRequestUpdateOnFirstRender(dispatch, id, module, updateVars, updateVarName);
+    useDispatchRequestUpdateOnFirstRender(dispatch, id, module, updateVars);
 
-    // Memoize column order
     const [colsOrder] = useMemo(() => {
         const colsOrder = Object.keys(value || {});
         return [colsOrder, value || {}];
     }, [value]);
 
-    // Memoize rows
     const rows = useMemo(() => {
         const rows: RowType[] = [];
         if (value) {
-            colsOrder.forEach(
-                (col) =>
-                    value[col] &&
-                    (value[col] as RowValue[]).forEach(
-                        (val, idx) => (rows[idx] = rows[idx] || {}) && (rows[idx][col] = val),
-                    ),
-            );
+            colsOrder.forEach((col) => {
+                if (value[col]) {
+                    value[col].forEach((val: RowValue, idx: number) => {
+                        rows[idx] = rows[idx] || {};
+                        rows[idx][col] = val;
+                    });
+                }
+            });
         }
         return rows;
     }, [value, colsOrder]);
 
-    // Memoize paginated rows
-    const paginatedRows = useMemo(() => {
-        if (rowsPerPage === undefined) {
-            return rows;
-        }
-        const startIndex = (currentPage - 1) * rowsPerPage;
-        return rows.slice(startIndex, startIndex + rowsPerPage);
-    }, [rows, currentPage, props.rowsPerPage]);
-
     useEffect(() => {
         if (refresh || !data) {
             dispatch(
-                createRequestDataUpdateAction(
-                    updateVarName,
-                    id,
-                    module,
-                    colsOrder,
-                    "",
-                    {},
-                    true,
-                    "TabularLibrary",
-                ),
+                createRequestDataUpdateAction(updateVarName, id, module, colsOrder, pageKey.current, {}, true, "ExampleLibrary")
             );
         } else {
-            setValue(data);
+            setValue(data[pageKey.current]);
         }
     }, [refresh, data, colsOrder, updateVarName, id, dispatch, module]);
 
-    // Handle next page
-    const handleNextPage = () => {
-        if (rowsPerPage) {
-            setCurrentPage((prevPage) => Math.min(prevPage + 1, Math.ceil(rows.length / rowsPerPage)));
-        }
-    };
-
-    // Handle previous page
-    const handlePreviousPage = () => {
-        setCurrentPage((prevPage) => Math.max(prevPage - 1, 1));
-    };
-
     return (
         <div>
             <table border={1} cellPadding={10} cellSpacing={0}>
@@ -101,7 +62,7 @@ const BasicTable = (props: BasicTableProps) => {
                     ))}
                 </thead>
                 <tbody>
-                    {paginatedRows.map((row, index) => (
+                    {rows.map((row, index) => (
                         <tr key={"row" + index}>
                             {colsOrder.map((col, cidx) => (
                                 <td key={"val" + index + "-" + cidx}>{row[col]}</td>
@@ -110,22 +71,6 @@ const BasicTable = (props: BasicTableProps) => {
                     ))}
                 </tbody>
             </table>
-            {rowsPerPage !== undefined && (
-                <div>
-                    <button onClick={handlePreviousPage} disabled={currentPage === 1}>
-                        Previous
-                    </button>
-                    <span>
-                        Page {currentPage} of {Math.ceil(rows.length / rowsPerPage)}
-                    </span>
-                    <button
-                        onClick={handleNextPage}
-                        disabled={currentPage === Math.ceil(rows.length / rowsPerPage)}
-                    >
-                        Next
-                    </button>
-                </div>
-            )}
         </div>
     );
 };

+ 18 - 21
doc/gui/extension/table_data.py

@@ -1,32 +1,29 @@
+from docutils.nodes import title
+
 from example_library import ExampleLibrary
-from faker import Faker
+import pandas as pd
+
 
 from taipy.gui import Gui
 
-fake = Faker()
+chessboard = [
+    ["♖", "♘", "♗", "♕", "♔", "♗", "♘", "♖"],
+    ["♙", "♙", "♙", "♙", "♙", "♙", "♙", "♙"],
+    ["", "", "", "", "", "", "", ""],
+    ["", "", "", "", "", "", "", ""],
+    ["", "", "", "", "", "", "", ""],
+    ["", "", "", "", "", "", "", ""],
+    ["♟", "♟", "♟", "♟", "♟", "♟", "♟", "♟"],
+    ["♜", "♞", "♝", "♛", "♚", "♝", "♞", "♜"]
+]
 
-data = {
-    "Employee ID": list(range(101, 201)),
-    "Name": [fake.name() for _ in range(100)],
-    "Department": [
-        fake.random_element(
-            elements=("Human Resources", "Engineering", "Marketing", "Sales", "Customer Support")
-        )
-        for _ in range(100)
-    ],
-    "Role": [
-        fake.random_element(
-            elements=("HR Manager", "Software Engineer", "Marketing Director", "Sales Executive", "Support Specialist")
-        )
-        for _ in range(100)
-    ],
-    "Location": [fake.city() for _ in range(100)]
-}
+# Create a DataFrame to represent the chessboard
+data = pd.DataFrame(chessboard, index=[8, 7, 6, 5, 4, 3, 2, 1], columns=["A", "B", "C", "D", "E", "F", "G", "H"])
 
 page = """
-## Employee Directory
+## Chess Game
 <|{data}|example.basic_table|>
 """
 
 if __name__ == "__main__":
-    Gui(page, libraries=[ExampleLibrary()]).run(port=3001, use_reloader=True, title="Basic Table", debug=True)
+    Gui(page, libraries=[ExampleLibrary()]).run(title="Chess Game")