All files / src SharedFoldersWidget.tsx

68.51% Statements 37/54
50% Branches 13/26
76.47% Functions 13/17
72.34% Lines 34/47

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195                                                                      5x 5x         5x                 7x   7x 7x 7x   7x 7x                                   7x                             7x 3x 3x 3x   2x 2x 5x   2x       7x 5x 5x 5x 5x       5x       7x 1x     6x               6x 7x 9x   6x               2x                 6x                                     12x                                                      
import React, { useEffect, useMemo, useRef, useState } from 'react';
import {
  useReplayMode,
  useStream,
  useWidgetRuntimeSnapshot
} from '@ska-octopus-widget-sdk/widget-sdk';
import { streamDocs } from './graphql/ops';
 
import Box from '@mui/material/Box';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import Typography from '@mui/material/Typography';
import Badge from '@mui/material/Badge';
import Divider from '@mui/material/Divider';
import TextField from '@mui/material/TextField';
 
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faFolderOpen } from '@fortawesome/free-solid-svg-icons';
 
import gsap from 'gsap';
import styles from './SharedFoldersWidget.module.css';
 
/* ──────────────────────────────────────────────── /
/ Types /
/ ──────────────────────────────────────────────── */
export interface SharedFoldersWidgetProps {
  instanceId?: string;
}
 
/* ──────────────────────────────────────────────── /
/ Helpers /
/ ──────────────────────────────────────────────── */
function animateNumber(el: HTMLElement, end: number) {
  const obj = { val: parseInt(el.textContent || '0', 10) || 0 };
  gsap.to(obj, {
    val: end,
    duration: 0.4,
    ease: 'power2.out',
    onUpdate: () => {
      el.textContent = Math.floor(obj.val).toString();
    }
  });
}
 
/* ──────────────────────────────────────────────── /
/ Component /
/ ──────────────────────────────────────────────── */
export default function SharedFoldersWidget(cfg: SharedFoldersWidgetProps) {
  const replayModeActive = useReplayMode();
  /** local state: { folderName: count } */
  const [folders, setFolders] = useState<Record<string, number>>({});
  const refs = useRef<Record<string, HTMLElement>>({}); // span refs for GSAP
  const [filter, setFilter] = useState('');
  /* GraphQL subscription */
  const vars = useMemo(() => cfg, [cfg]);
  const { data, error } = useStream({
    document: streamDocs[0],
    variables: vars,
    onData: (incoming: any) => {
      if (replayModeActive) return;
      const arr = (incoming as any)?.sharedFolderCounts?.folders;
      if (!Array.isArray(arr)) return;
      const nextFolders: Record<string, number> = {};
      arr.forEach((f: { folder: string; count: number }) => {
        nextFolders[f.folder] = f.count;
      });
      setFolders(nextFolders);
    },
    replaySnapshot: {
      instanceId: cfg.instanceId,
      key: 'shared-folders:stream'
    }
  });
  useWidgetRuntimeSnapshot(cfg.instanceId, {
    capture: () => ({
      sharedFolders: {
        folders
      }
    }),
    apply: (snapshot) => {
      const nextFolders = (snapshot as any)?.sharedFolders?.folders;
      if (nextFolders && typeof nextFolders === 'object') {
        setFolders(nextFolders as Record<string, number>);
      }
    }
  });
 
  /* update state when new data arrives */
  useEffect(() => {
    Iif (replayModeActive) return;
    const arr = data?.sharedFolderCounts?.folders;
    if (!Array.isArray(arr)) return;
 
    const incoming: Record<string, number> = {};
    arr.forEach((f: { folder: string; count: number }) => {
      incoming[f.folder] = f.count;
    });
    setFolders(incoming);
  }, [data, replayModeActive]);
 
  /* animate number changes */
  useEffect(() => {
    Object.entries(folders).forEach(([name, count]) => {
      const el = refs.current[name];
      Iif (!el) return;
      Iif (replayModeActive) {
        el.textContent = String(count);
        return;
      }
      animateNumber(el, count);
    });
  }, [folders, replayModeActive]);
 
  if (error) {
    return <Typography color="error">{String(error)}</Typography>;
  }
 
  const palette = {
    bg: 'var(--widget-bg, #fafafa)',
    border: 'var(--widget-border, #e0e0e0)',
    title: 'var(--widget-title, #333)',
    accent: 'var(--accent-color, #0077cc)'
  };
 
  // sort and then apply filter
  const items = Object.entries(folders)
    .sort(([a], [b]) => a.localeCompare(b))
    .filter(([name]) => name.toLowerCase().includes(filter.trim().toLowerCase()));
 
  return (
    <div className={styles.shared}>
      {/* Filter input */}
      <TextField
        className={styles.filterInput}
        size="small"
        placeholder="Filter folders…"
        value={filter}
        onChange={(e) => setFilter(e.target.value)}
      />
 
      <Divider sx={{ mb: 1 }} />
 
      {/* Scrollable list container */}
      <Box className={styles.listContainer}>
        <List dense disablePadding>
          {items.map(([name, count]) => (
            <ListItem key={name} className={styles.item}>
              <ListItemIcon sx={{ minWidth: 30, color: palette.accent }}>
                <FontAwesomeIcon icon={faFolderOpen} />
              </ListItemIcon>
 
              <ListItemText primary={name} primaryTypographyProps={{ noWrap: true }} />
 
              <Badge
                sx={{
                  '& .MuiBadge-badge': {
                    backgroundColor: palette.accent,
                    color: '#fff',
                    fontFamily: 'ui-monospace, monospace',
                    minWidth: '2ch'
                  }
                }}
                badgeContent={
                  <span
                    ref={(el) => {
                      if (el) refs.current[name] = el;
                    }}
                  >
                    {count}
                  </span>
                }
              />
            </ListItem>
          ))}
 
          {items.length === 0 && (
            <Typography
              sx={{
                py: 2,
                textAlign: 'center',
                opacity: 0.6,
                fontStyle: 'italic'
              }}
            >
              No folders match your filter
            </Typography>
          )}
        </List>
      </Box>
    </div>
  );
}