UNPKG

@neo4j-ndl/react

Version:

React implementation of Neo4j Design System

78 lines (77 loc) 3.5 kB
/** * * Copyright (c) "Neo4j" * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useTableNav = useTableNav; const react_1 = require("react"); const data_grid_nav_1 = require("./data-grid-nav"); function useTableNav(options) { // Store the actual class instance in a ref so we only create it once const instanceRef = (0, react_1.useRef)(null); if (instanceRef.current === null) { instanceRef.current = new data_grid_nav_1.DataGridNav(options); } // A piece of state to force a re-render when you want to react to instance changes const [, setVersion] = (0, react_1.useState)(0); const forceUpdate = (0, react_1.useCallback)(() => setVersion((v) => v + 1), []); // Wrap the instance in a proxy that intercepts reads/writes const proxiedInstance = (0, react_1.useMemo)(() => { const handler = { get(target, prop, receiver) { const value = Reflect.get(target, prop, receiver); // If it's a function (a class method), we can intercept calls: if (typeof value === 'function') { // eslint-disable-next-line @typescript-eslint/no-explicit-any return (...args) => { // Call the original method const result = value.apply(target, args); // Example: force re-render if the method is known to change internal state // or if you want to force re-render after *every* method call, remove the condition if (['enable', 'disable'].includes(String(prop))) { forceUpdate(); } return result; }; } // Otherwise, it's a property. Just return it. return value; }, // Trap for property assignments, so React can re-render on changes set(target, prop, newValue, receiver) { // eslint-disable-next-line @typescript-eslint/naming-convention const result = Reflect.set(target, prop, newValue, receiver); // Force re-render after setting *any* property forceUpdate(); return result; }, }; return new Proxy(instanceRef.current, handler); // We only want to create a new Proxy if the instanceRef or forceUpdate changes }, [forceUpdate]); return { listeners: { onKeyDown: (e) => proxiedInstance.tableKeyDown(e.nativeEvent), onKeyUp: () => proxiedInstance.tableKeyUp(), }, tableNav: proxiedInstance, }; } //# sourceMappingURL=index.js.map