useTableCompactMode.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. Copyright (C) 2025 QuantumNous
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <https://www.gnu.org/licenses/>.
  13. For commercial licensing, please contact support@quantumnous.com
  14. */
  15. import { useState, useEffect, useCallback } from 'react';
  16. import { getTableCompactMode, setTableCompactMode } from '../../helpers';
  17. import { TABLE_COMPACT_MODES_KEY } from '../../constants';
  18. /**
  19. * 自定义 Hook:管理表格紧凑/自适应模式
  20. * 返回 [compactMode, setCompactMode]。
  21. * 内部使用 localStorage 保存状态,并监听 storage 事件保持多标签页同步。
  22. */
  23. export function useTableCompactMode(tableKey = 'global') {
  24. const [compactMode, setCompactModeState] = useState(() =>
  25. getTableCompactMode(tableKey),
  26. );
  27. const setCompactMode = useCallback(
  28. (value) => {
  29. setCompactModeState(value);
  30. setTableCompactMode(value, tableKey);
  31. },
  32. [tableKey],
  33. );
  34. useEffect(() => {
  35. const handleStorage = (e) => {
  36. if (e.key === TABLE_COMPACT_MODES_KEY) {
  37. try {
  38. const modes = JSON.parse(e.newValue || '{}');
  39. setCompactModeState(!!modes[tableKey]);
  40. } catch {
  41. // ignore parse error
  42. }
  43. }
  44. };
  45. window.addEventListener('storage', handleStorage);
  46. return () => window.removeEventListener('storage', handleStorage);
  47. }, [tableKey]);
  48. return [compactMode, setCompactMode];
  49. }