All files / src/components/Publishing/LivePreview LivePreview.tsx

80.95% Statements 34/42
80.55% Branches 29/36
88.88% Functions 8/9
80% Lines 32/40

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 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285                                                                    1x 30x 30x 30x 30x 30x 30x 30x   30x             30x 24x   2x 2x     24x                   30x 5x 5x 5x   5x       30x 1x 1x   1x 1x             1x       30x 1x     30x 24x 24x                       30x   30x                                                                                                                                                                                                                                                                                                                                                        
import React, { useState, useEffect, useRef } from 'react';
import {
  Box,
  ToggleButton,
  ToggleButtonGroup,
  IconButton,
  Alert,
  Button,
  Paper,
  Typography,
} from '@mui/material';
import { BATbernLoader } from '@components/shared/BATbernLoader';
import {
  Computer as DesktopIcon,
  PhoneIphone as MobileIcon,
  Print as PrintIcon,
  Refresh as RefreshIcon,
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { usePublishing } from '@/hooks/usePublishing/usePublishing';
import { PublishingPhase } from '@/types/event.types';
 
type DeviceType = 'desktop' | 'mobile' | 'print';
 
interface DeviceDimensions {
  width: string;
  height: string;
}
 
export interface LivePreviewProps {
  eventCode: string;
  phase: PublishingPhase;
}
 
export const LivePreview: React.FC<LivePreviewProps> = ({ eventCode, phase }) => {
  const { t } = useTranslation('organizer');
  const { preview, fetchPreview, isLoadingPreview, previewError } = usePublishing(eventCode);
  const [device, setDevice] = useState<DeviceType>('desktop');
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [deviceAnnouncement, setDeviceAnnouncement] = useState('');
  const iframeRef = useRef<HTMLIFrameElement>(null);
  const prevPreviewRef = useRef(preview);
 
  const deviceDimensions: Record<DeviceType, DeviceDimensions> = {
    desktop: { width: '100%', height: '800px' },
    mobile: { width: '375px', height: '667px' },
    print: { width: '210mm', height: '297mm' },
  };
 
  // Auto-refresh when preview content changes
  useEffect(() => {
    if (prevPreviewRef.current && preview && prevPreviewRef.current !== preview) {
      // Content changed, reload iframe
      Eif (iframeRef.current) {
        iframeRef.current.src = preview.previewUrl;
      }
    }
    prevPreviewRef.current = preview;
  }, [preview]);
 
  // Fetch preview on mount or when phase/mode changes
  // DISABLED: Causes infinite loop because fetchPreview is not memoized
  // Users can manually refresh using the refresh button
  // useEffect(() => {
  //   fetchPreview?.(phase, mode);
  // }, [phase, mode, fetchPreview]);
 
  const handleDeviceChange = (_: React.MouseEvent<HTMLElement>, newDevice: DeviceType | null) => {
    Eif (newDevice !== null) {
      setDevice(newDevice);
      setDeviceAnnouncement(t('livePreview.switchedTo', { device: newDevice }));
      // Clear announcement after brief delay
      setTimeout(() => setDeviceAnnouncement(''), 100);
    }
  };
 
  const handleRefresh = async () => {
    setIsRefreshing(true);
    Eif (iframeRef.current?.contentWindow && typeof window !== 'undefined') {
      // Reload iframe (only in browser environment)
      try {
        iframeRef.current.contentWindow.location.reload();
      } catch (error) {
        // Ignore errors in test environment
        console.warn('Failed to reload iframe:', error);
      }
    }
    // Simulate refresh delay
    await new Promise((resolve) => setTimeout(resolve, 500));
    setIsRefreshing(false);
  };
 
  const handleRetry = () => {
    fetchPreview?.(phase);
  };
 
  const getPreviewUrl = () => {
    Eif (preview?.previewUrl) {
      return preview.previewUrl;
    }
    // Generate preview URL - use actual public event page with preview mode
    // This allows previewing how the event will look on the public site
    const baseUrl = `/events/${eventCode}`;
    const params = new URLSearchParams({ preview: 'true' });
    if (phase) {
      params.append('phase', phase);
    }
    return `${baseUrl}?${params.toString()}`;
  };
 
  const dimensions = deviceDimensions[device];
 
  return (
    <Paper sx={{ p: 2 }}>
      {/* Screen reader announcement for device changes */}
      {deviceAnnouncement && (
        <div role="status" aria-live="polite" style={{ position: 'absolute', left: '-10000px' }}>
          {deviceAnnouncement}
        </div>
      )}
 
      {/* Controls */}
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
        {/* Device Toggle */}
        <ToggleButtonGroup
          value={device}
          exclusive
          onChange={handleDeviceChange}
          aria-label={t('livePreview.devicePreviewMode')}
        >
          <ToggleButton
            value="desktop"
            aria-label={t('livePreview.desktopPreview')}
            aria-pressed={device === 'desktop'}
          >
            <DesktopIcon sx={{ mr: { xs: 0, md: 1 } }} />
            <Box component="span" sx={{ display: { xs: 'none', md: 'inline' } }}>
              {t('livePreview.desktop')}
            </Box>
          </ToggleButton>
          <ToggleButton
            value="mobile"
            aria-label={t('livePreview.mobilePreview')}
            aria-pressed={device === 'mobile'}
          >
            <MobileIcon sx={{ mr: { xs: 0, md: 1 } }} />
            <Box component="span" sx={{ display: { xs: 'none', md: 'inline' } }}>
              {t('livePreview.mobile')}
            </Box>
          </ToggleButton>
          <ToggleButton
            value="print"
            aria-label={t('livePreview.printPreview')}
            aria-pressed={device === 'print'}
          >
            <PrintIcon sx={{ mr: { xs: 0, md: 1 } }} />
            <Box component="span" sx={{ display: { xs: 'none', md: 'inline' } }}>
              {t('livePreview.print')}
            </Box>
          </ToggleButton>
        </ToggleButtonGroup>
 
        {/* Refresh Button */}
        <IconButton
          onClick={handleRefresh}
          disabled={isRefreshing || isLoadingPreview}
          aria-label={t('livePreview.refreshPreview')}
          title={t('livePreview.refreshPreview')}
        >
          <RefreshIcon sx={{ animation: isRefreshing ? 'spin 1s linear infinite' : 'none' }} />
        </IconButton>
      </Box>
 
      {/* Preview Content */}
      <Box
        sx={{
          position: 'relative',
          display: 'flex',
          justifyContent: 'center',
          minHeight: '400px',
          bgcolor: 'grey.100',
          borderRadius: 1,
          overflow: 'hidden',
        }}
      >
        {/* Loading State */}
        {(isLoadingPreview || isRefreshing) && (
          <Box
            sx={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              justifyContent: 'center',
              bgcolor: 'rgba(255, 255, 255, 0.9)',
              zIndex: 2,
              gap: 2,
            }}
          >
            <BATbernLoader size={96} data-testid="preview-loading-spinner" />
            <Typography variant="body2" color="text.secondary">
              {t('livePreview.refreshingPreview')}
            </Typography>
          </Box>
        )}
 
        {/* Error State */}
        {previewError && !isLoadingPreview && (
          <Box
            sx={{
              position: 'absolute',
              top: '50%',
              left: '50%',
              transform: 'translate(-50%, -50%)',
              width: '80%',
              maxWidth: '500px',
            }}
          >
            <Alert
              severity="error"
              action={
                <Button color="inherit" size="small" onClick={handleRetry}>
                  {t('common:actions.retry')}
                </Button>
              }
            >
              {t('livePreview.failedToLoad')}
            </Alert>
          </Box>
        )}
 
        {/* Preview Iframe */}
        {!previewError && !isLoadingPreview && (
          <iframe
            ref={iframeRef}
            data-testid="preview-iframe"
            src={getPreviewUrl()}
            title={t('livePreview.iframeTitle')}
            aria-label={t('livePreview.iframeAriaLabel')}
            className={device}
            style={{
              width: dimensions.width,
              height: dimensions.height,
              border: '1px solid #ccc',
              borderRadius: '4px',
              display: isRefreshing ? 'none' : 'block',
            }}
            onLoad={() => setIsRefreshing(false)}
          />
        )}
      </Box>
 
      {/* Preview Info */}
      <Box sx={{ mt: 2, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Typography variant="caption" color="text.secondary">
          {t('livePreview.previewPhaseCaption', {
            phase: phase || 'Topic',
          })}
        </Typography>
        <Typography variant="caption" color="text.secondary">
          {t('livePreview.deviceCaption', {
            device: device.charAt(0).toUpperCase() + device.slice(1),
            width: dimensions.width,
            height: dimensions.height,
          })}
        </Typography>
      </Box>
 
      {/* CSS for refresh animation */}
      <style>
        {`
          @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
          }
        `}
      </style>
    </Paper>
  );
};