|
| 1 | +import { useEffect, useState, useCallback } from 'react'; |
| 2 | +import { useBuildInfo, useSaveCanvas } from './api/hooks'; |
| 3 | +import { saveCurrentCanvas } from './utils/canvasUtils'; |
| 4 | + |
| 5 | +/** |
| 6 | + * Component that checks for application version changes and refreshes the page when needed. |
| 7 | + * This component doesn't render anything visible. |
| 8 | + */ |
| 9 | +export function BuildVersionCheck() { |
| 10 | + // Store the initial build hash when the component first loads |
| 11 | + const [initialBuildHash, setInitialBuildHash] = useState<string | null>(null); |
| 12 | + |
| 13 | + // Query for the current build info from the server |
| 14 | + const { data: buildInfo } = useBuildInfo(); |
| 15 | + |
| 16 | + // Get the saveCanvas mutation |
| 17 | + const { mutate: saveCanvas } = useSaveCanvas({ |
| 18 | + onSuccess: () => { |
| 19 | + console.debug("[pad.ws] Canvas saved before refresh"); |
| 20 | + // Refresh the page immediately after saving |
| 21 | + window.location.reload(); |
| 22 | + }, |
| 23 | + onError: (error) => { |
| 24 | + console.error("[pad.ws] Failed to save canvas before refresh:", error); |
| 25 | + // Refresh anyway even if save fails |
| 26 | + window.location.reload(); |
| 27 | + } |
| 28 | + }); |
| 29 | + |
| 30 | + // Function to handle version update |
| 31 | + const handleVersionUpdate = useCallback(() => { |
| 32 | + // Save the canvas and then refresh |
| 33 | + saveCurrentCanvas( |
| 34 | + saveCanvas, |
| 35 | + undefined, // No success callback needed as it's handled in the useSaveCanvas hook |
| 36 | + () => window.location.reload() // On error, just refresh |
| 37 | + ); |
| 38 | + }, [saveCanvas]); |
| 39 | + |
| 40 | + useEffect(() => { |
| 41 | + // On first load, store the initial build hash |
| 42 | + if (buildInfo?.buildHash && initialBuildHash === null) { |
| 43 | + console.log('Initial build hash:', buildInfo.buildHash); |
| 44 | + setInitialBuildHash(buildInfo.buildHash); |
| 45 | + } |
| 46 | + |
| 47 | + // If we have both values and they don't match, a new version is available |
| 48 | + if (initialBuildHash !== null && |
| 49 | + buildInfo?.buildHash && |
| 50 | + initialBuildHash !== buildInfo.buildHash) { |
| 51 | + |
| 52 | + console.log('New version detected. Current:', initialBuildHash, 'New:', buildInfo.buildHash); |
| 53 | + |
| 54 | + // Save the canvas and then refresh |
| 55 | + handleVersionUpdate(); |
| 56 | + } |
| 57 | + }, [buildInfo, initialBuildHash, handleVersionUpdate]); |
| 58 | + |
| 59 | + // This component doesn't render anything |
| 60 | + return null; |
| 61 | +} |
0 commit comments