'use client'; import { useState, useEffect, useRef } from 'react'; import { getSpreadsheetData, SheetData } from '@/utils/sheets'; import { GalleryItem } from '@/components/gallery-item'; import { preview, Inputs } from '@/raydiant-sdk'; interface GalleryState { sheetData: SheetData[]; duration: number; showDescriptions: boolean; } interface GalleryProps { initialState: GalleryState; } export function Gallery({ initialState }: GalleryProps) { const [state, setState] = useState(initialState); const [currentIndex, setCurrentIndex] = useState(0); // Refs const previousSheetUrl = useRef(); // Effects // Increment the current index on interval. useEffect(() => { const interval = setInterval(() => { setCurrentIndex((index) => (index + 1) % state.sheetData.length); }, state.duration); return () => { clearInterval(interval); }; }, [state.duration, state.sheetData.length]); // Subscribe to for preview input value changes. This allows us to update the sheet data // from a local file blob URL instead of needing to upload the spreadsheet. Subscribing // to inputs will prevent the Dashboard preview from reloading the URL template on when // an input value changes. // // You can use the devTools API to simulate input changes in local development with: // devTools.previewInputs({ // sheet: { $file: 'spreadsheet' }, // descriptions: true, // }); useEffect(() => { return preview.subscribe('inputs', async (inputs) => { // Fetch updated sheet data. Sheet will be 'undefined' if the user has not yet selected // a local file to preview and 'null' if the user has cleared the file input. let updatedSheetData: SheetData[] | null = null; if (inputs.sheet) { updatedSheetData = await getSpreadsheetData(inputs.sheet.url); // Reset the index to 0 when the sheet URL changes. if (previousSheetUrl.current !== inputs.sheet?.url) { setCurrentIndex(0); } previousSheetUrl.current = inputs.sheet?.url; } setState((state) => ({ sheetData: updatedSheetData ?? state.sheetData, showDescriptions: inputs.descriptions, duration: state.duration, })); }); }, []); // Render const nextIndex = (currentIndex + 1) % state.sheetData.length; const prevIndex = (currentIndex - 1 + state.sheetData.length) % state.sheetData.length; const items = state.sheetData.map((data, index) => ( )); return (
{!isNaN(prevIndex) && (
{items[prevIndex]}
)}
{items[currentIndex]}
{!isNaN(nextIndex) && (
{items[nextIndex]}
)}
); }