mirror of
https://github.com/arsvendg/Stirling-PDF.git
synced 2026-07-16 11:23:10 +02:00
Add frontend autoformatting and set CI to require formatted code for all languages (#6052)
# Description of Changes Changes the strategy for autoformatting to reject PRs if they are not formatted correctly instead of allowing them to merge and then spawning a new PR to fix the formatting. The old strategy just caused more work for us because we'd have to manually approve the followup PR and get it merged, which required 2 reviewers so in practice it rarely got done and just meant everyone's PRs ended up containing reformatting for unrelated files, which makes code review unnecessarily difficult. If the PR's code is not formatted correctly after this PR, a comment will be added automatically to tell the author how to run the formatter script to fix their code so it can go in. This also enables autoformatting for the frontend code, using Prettier. I've enabled it for pretty much everything in the frontend folder, other than 3rd party files and files it doesn't make sense for. I also excluded Markdown because it sounds likely to be more annoying to have to autoformat the Markdown in the frontend folder but nowhere else. Open to changing this though if people disagree. > [!note] > > Advice to reviewers: The first commit contains all of the actual logic I've introduced (CI changes, Prettier config, etc.) > The second commit is just the reformatting of the entire frontend folder. > The first commit needs proper review, the second one just give it a spot-check that it's doing what you'd expect.
This commit is contained in:
@@ -1,14 +1,14 @@
|
||||
import React, { createContext, useContext, useState, useEffect, ReactNode, useCallback } from 'react';
|
||||
import apiClient from '@app/services/apiClient';
|
||||
import { getSimulatedAppConfig } from '@app/testing/serverExperienceSimulations';
|
||||
import type { AppConfig, AppConfigBootstrapMode } from '@app/types/appConfig';
|
||||
import { useJwtConfigSync } from '@app/hooks/useJwtConfigSync';
|
||||
import React, { createContext, useContext, useState, useEffect, ReactNode, useCallback } from "react";
|
||||
import apiClient from "@app/services/apiClient";
|
||||
import { getSimulatedAppConfig } from "@app/testing/serverExperienceSimulations";
|
||||
import type { AppConfig, AppConfigBootstrapMode } from "@app/types/appConfig";
|
||||
import { useJwtConfigSync } from "@app/hooks/useJwtConfigSync";
|
||||
|
||||
/**
|
||||
* Sleep utility for delays
|
||||
*/
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
export interface AppConfigRetryOptions {
|
||||
@@ -49,11 +49,11 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
|
||||
children,
|
||||
retryOptions,
|
||||
initialConfig = null,
|
||||
bootstrapMode = 'blocking',
|
||||
bootstrapMode = "blocking",
|
||||
autoFetch = true,
|
||||
onConfigLoaded,
|
||||
}) => {
|
||||
const isBlockingMode = bootstrapMode === 'blocking';
|
||||
const isBlockingMode = bootstrapMode === "blocking";
|
||||
const [config, setConfig] = useState<AppConfig | null>(initialConfig);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
// Track how many times we've attempted to fetch. useRef avoids re-renders that can trigger loops.
|
||||
@@ -67,102 +67,106 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
|
||||
const maxRetries = retryOptions?.maxRetries ?? 0;
|
||||
const initialDelay = retryOptions?.initialDelay ?? 1000;
|
||||
|
||||
const fetchConfig = useCallback(async (force = false) => {
|
||||
// Prevent duplicate fetches unless forced
|
||||
if (!force && fetchCountRef.current > 0) {
|
||||
console.debug('[AppConfig] Already fetched, skipping');
|
||||
return;
|
||||
}
|
||||
const fetchConfig = useCallback(
|
||||
async (force = false) => {
|
||||
// Prevent duplicate fetches unless forced
|
||||
if (!force && fetchCountRef.current > 0) {
|
||||
console.debug("[AppConfig] Already fetched, skipping");
|
||||
return;
|
||||
}
|
||||
|
||||
// Mark that we've attempted a fetch to prevent repeated auto-fetch loops
|
||||
fetchCountRef.current += 1;
|
||||
// Mark that we've attempted a fetch to prevent repeated auto-fetch loops
|
||||
fetchCountRef.current += 1;
|
||||
|
||||
const shouldBlockUI = !hasResolvedConfig || isBlockingMode;
|
||||
if (shouldBlockUI) {
|
||||
setLoading(true);
|
||||
}
|
||||
setError(null);
|
||||
const shouldBlockUI = !hasResolvedConfig || isBlockingMode;
|
||||
if (shouldBlockUI) {
|
||||
setLoading(true);
|
||||
}
|
||||
setError(null);
|
||||
|
||||
const startTime = performance.now();
|
||||
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
||||
try {
|
||||
const testConfig = getSimulatedAppConfig();
|
||||
if (testConfig) {
|
||||
setConfig(testConfig);
|
||||
setHasResolvedConfig(true);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
const startTime = performance.now();
|
||||
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
||||
try {
|
||||
const testConfig = getSimulatedAppConfig();
|
||||
if (testConfig) {
|
||||
setConfig(testConfig);
|
||||
setHasResolvedConfig(true);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (attempt > 0) {
|
||||
const delay = initialDelay * Math.pow(2, attempt - 1);
|
||||
console.log(`[AppConfig] Retry attempt ${attempt}/${maxRetries} after ${delay}ms delay...`);
|
||||
await sleep(delay);
|
||||
} else {
|
||||
console.log('[AppConfig] Fetching app config...');
|
||||
}
|
||||
if (attempt > 0) {
|
||||
const delay = initialDelay * Math.pow(2, attempt - 1);
|
||||
console.log(`[AppConfig] Retry attempt ${attempt}/${maxRetries} after ${delay}ms delay...`);
|
||||
await sleep(delay);
|
||||
} else {
|
||||
console.log("[AppConfig] Fetching app config...");
|
||||
}
|
||||
|
||||
// apiClient automatically adds JWT header if available via interceptors
|
||||
// Always suppress error toast - we handle 401 errors locally
|
||||
console.debug('[AppConfig] Fetching app config', { attempt, force, path: window.location.pathname });
|
||||
const response = await apiClient.get<AppConfig>(
|
||||
'/api/v1/config/app-config',
|
||||
{
|
||||
// apiClient automatically adds JWT header if available via interceptors
|
||||
// Always suppress error toast - we handle 401 errors locally
|
||||
console.debug("[AppConfig] Fetching app config", { attempt, force, path: window.location.pathname });
|
||||
const response = await apiClient.get<AppConfig>("/api/v1/config/app-config", {
|
||||
suppressErrorToast: true,
|
||||
skipAuthRedirect: true,
|
||||
} as any,
|
||||
);
|
||||
const data = response.data;
|
||||
} as any);
|
||||
const data = response.data;
|
||||
|
||||
console.debug('[AppConfig] Config fetched successfully:', data);
|
||||
console.debug('[AppConfig] Fetch duration ms:', (performance.now() - startTime).toFixed(2));
|
||||
setConfig(data);
|
||||
setHasResolvedConfig(true);
|
||||
setLoading(false);
|
||||
onConfigLoadedRef.current?.(data);
|
||||
return; // Success - exit function
|
||||
} catch (err: any) {
|
||||
const status = err?.response?.status;
|
||||
|
||||
// On 401 (not authenticated), use default config with login enabled
|
||||
// This allows the app to work even without authentication
|
||||
if (status === 401) {
|
||||
console.debug('[AppConfig] 401 error - using default config (login enabled)');
|
||||
console.debug('[AppConfig] Fetch duration ms:', (performance.now() - startTime).toFixed(2));
|
||||
setConfig({ enableLogin: true });
|
||||
console.debug("[AppConfig] Config fetched successfully:", data);
|
||||
console.debug("[AppConfig] Fetch duration ms:", (performance.now() - startTime).toFixed(2));
|
||||
setConfig(data);
|
||||
setHasResolvedConfig(true);
|
||||
setLoading(false);
|
||||
return;
|
||||
onConfigLoadedRef.current?.(data);
|
||||
return; // Success - exit function
|
||||
} catch (err: any) {
|
||||
const status = err?.response?.status;
|
||||
|
||||
// On 401 (not authenticated), use default config with login enabled
|
||||
// This allows the app to work even without authentication
|
||||
if (status === 401) {
|
||||
console.debug("[AppConfig] 401 error - using default config (login enabled)");
|
||||
console.debug("[AppConfig] Fetch duration ms:", (performance.now() - startTime).toFixed(2));
|
||||
setConfig({ enableLogin: true });
|
||||
setHasResolvedConfig(true);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if we should retry (network errors or 5xx errors)
|
||||
const shouldRetry = (!status || status >= 500) && attempt < maxRetries;
|
||||
|
||||
if (shouldRetry) {
|
||||
console.warn(
|
||||
`[AppConfig] Attempt ${attempt + 1} failed (status ${status || "network error"}):`,
|
||||
err.message,
|
||||
"- will retry...",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Final attempt failed or non-retryable error (4xx)
|
||||
const errorMessage = err?.response?.data?.message || err?.message || "Unknown error occurred";
|
||||
setError(errorMessage);
|
||||
console.error(`[AppConfig] Failed to fetch app config after ${attempt + 1} attempts:`, err);
|
||||
console.debug("[AppConfig] Fetch duration ms:", (performance.now() - startTime).toFixed(2));
|
||||
// Preserve existing config (initial default or previous fetch). If nothing is set, assume login enabled.
|
||||
setConfig((current) => current ?? { enableLogin: true });
|
||||
setHasResolvedConfig(true);
|
||||
break;
|
||||
}
|
||||
|
||||
// Check if we should retry (network errors or 5xx errors)
|
||||
const shouldRetry = (!status || status >= 500) && attempt < maxRetries;
|
||||
|
||||
if (shouldRetry) {
|
||||
console.warn(`[AppConfig] Attempt ${attempt + 1} failed (status ${status || 'network error'}):`, err.message, '- will retry...');
|
||||
continue;
|
||||
}
|
||||
|
||||
// Final attempt failed or non-retryable error (4xx)
|
||||
const errorMessage = err?.response?.data?.message || err?.message || 'Unknown error occurred';
|
||||
setError(errorMessage);
|
||||
console.error(`[AppConfig] Failed to fetch app config after ${attempt + 1} attempts:`, err);
|
||||
console.debug('[AppConfig] Fetch duration ms:', (performance.now() - startTime).toFixed(2));
|
||||
// Preserve existing config (initial default or previous fetch). If nothing is set, assume login enabled.
|
||||
setConfig((current) => current ?? { enableLogin: true });
|
||||
setHasResolvedConfig(true);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
setLoading(false);
|
||||
}, [hasResolvedConfig, isBlockingMode, maxRetries, initialDelay]);
|
||||
setLoading(false);
|
||||
},
|
||||
[hasResolvedConfig, isBlockingMode, maxRetries, initialDelay],
|
||||
);
|
||||
|
||||
const { isAuthPage } = useJwtConfigSync(fetchConfig);
|
||||
|
||||
useEffect(() => {
|
||||
if (isAuthPage) {
|
||||
console.debug('[AppConfig] On auth page - using default config, skipping fetch', { path: window.location.pathname });
|
||||
console.debug("[AppConfig] On auth page - using default config, skipping fetch", { path: window.location.pathname });
|
||||
setConfig({ enableLogin: true });
|
||||
setHasResolvedConfig(true);
|
||||
setLoading(false);
|
||||
@@ -183,11 +187,7 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
|
||||
refetch,
|
||||
};
|
||||
|
||||
return (
|
||||
<AppConfigContext.Provider value={value}>
|
||||
{children}
|
||||
</AppConfigContext.Provider>
|
||||
);
|
||||
return <AppConfigContext.Provider value={value}>{children}</AppConfigContext.Provider>;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -198,7 +198,7 @@ export function useAppConfig(): AppConfigContextValue {
|
||||
const context = useContext(AppConfigContext);
|
||||
|
||||
if (context === undefined) {
|
||||
throw new Error('useAppConfig must be used within AppConfigProvider');
|
||||
throw new Error("useAppConfig must be used within AppConfigProvider");
|
||||
}
|
||||
|
||||
return context;
|
||||
|
||||
Reference in New Issue
Block a user