Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ downloads/
eggs/
.eggs/
lib/
# Python build-artifact rule above — the frontend API client lives in app/src/lib/
!app/src/lib/
lib64/
parts/
sdist/
Expand Down
31 changes: 11 additions & 20 deletions app/src/components/FeedbackWidget.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ import ToggleButton from '@mui/material/ToggleButton';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import Tooltip from '@mui/material/Tooltip';

import { API_URL } from 'src/constants';
import { useAnalytics } from 'src/hooks';
import { useLocalStorage } from 'src/hooks/useLocalStorage';
import { apiPost, endpoints } from 'src/lib/api';
import { RESERVED_TOP_LEVEL } from 'src/utils/paths';

const MAX_MESSAGE_LENGTH = 500;
Expand Down Expand Up @@ -224,12 +224,10 @@ export function FeedbackWidget() {
// the row was never written.
setMode('closed');
try {
const response = await fetch(`${API_URL}/feedback`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(buildPayload({ message: null, reaction: r, contact: null })),
});
if (!response.ok) return;
await apiPost<unknown>(
endpoints.feedback,
buildPayload({ message: null, reaction: r, contact: null })
);
setThanksVisible(true);
trackEvent('feedback_submitted', {
path: getCurrentPath() || undefined,
Expand All @@ -239,8 +237,8 @@ export function FeedbackWidget() {
mode: 'quick',
});
} catch {
// Network failure — drop silently. The quick interaction has no error UI
// surface (we closed the FAB optimistically); the user can retry.
// Non-2xx or network failure — drop silently. The quick interaction has
// no error UI surface (we closed the FAB optimistically); the user can retry.
}
};

Expand All @@ -260,17 +258,10 @@ export function FeedbackWidget() {
setError(null);

try {
const response = await fetch(`${API_URL}/feedback`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(
buildPayload({ message: trimmed || null, reaction, contact: contact.trim() || null })
),
});

if (!response.ok) {
throw new Error(`status ${response.status}`);
}
await apiPost<unknown>(
endpoints.feedback,
buildPayload({ message: trimmed || null, reaction, contact: contact.trim() || null })
);

trackEvent('feedback_submitted', {
path: getCurrentPath() || undefined,
Expand Down
50 changes: 25 additions & 25 deletions app/src/components/Layout.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { type ReactNode, useCallback, useEffect, useRef, useState } from 'react';

import { API_URL } from 'src/constants';
import {
AppDataContext,
type HomeState,
Expand All @@ -9,6 +8,7 @@ import {
ThemeContext,
} from 'src/hooks/useLayoutContext';
import { useThemeMode } from 'src/hooks/useThemeMode';
import { ApiError, apiGet, endpoints } from 'src/lib/api';

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed and fixed — the root .gitignore's Python build-artifact rule (lib/) silently excluded app/src/lib/, so the module never made it into the commit. Added a scoped negation (!app/src/lib/) and committed the file; CI is re-running.

import type { LanguageInfo, LibraryInfo, SpecInfo } from 'src/types';

// Global provider that wraps the entire router
Expand Down Expand Up @@ -51,35 +51,35 @@ export function AppDataProvider({ children }: { children: ReactNode }) {
const signal = abortController.signal;

const load = async () => {
// Non-ok responses used to be skipped per endpoint (res.ok check) while
// the other setters still ran; map ApiError to null to keep that, and
// rethrow everything else (network errors, aborts) so the whole load
// lands in the outer catch like before.
const safeGet = async <T,>(path: string): Promise<T | null> => {
try {
return await apiGet<T>(path, { signal });
} catch (err) {
if (err instanceof ApiError) return null;
throw err;
}
};

try {
const [specsRes, libsRes, langsRes, statsRes] = await Promise.all([
fetch(`${API_URL}/specs`, { signal }),
fetch(`${API_URL}/libraries`, { signal }),
fetch(`${API_URL}/languages`, { signal }),
fetch(`${API_URL}/stats`, { signal }),
const [specsBody, libsBody, langsBody, statsBody] = await Promise.all([
safeGet<SpecInfo[] | { specs?: SpecInfo[] }>(endpoints.specs),
safeGet<{ libraries?: LibraryInfo[] }>(endpoints.libraries),
safeGet<{ languages?: LanguageInfo[] }>(endpoints.languages),
safeGet<{ specs: number; plots: number; libraries: number; lines_of_code?: number }>(
endpoints.stats
),
]);

if (signal.aborted) return;

if (specsRes.ok) {
const data = await specsRes.json();
if (!signal.aborted) setSpecsData(Array.isArray(data) ? data : data.specs || []);
}

if (libsRes.ok) {
const data = await libsRes.json();
if (!signal.aborted) setLibrariesData(data.libraries || []);
}

if (langsRes.ok) {
const data = await langsRes.json();
if (!signal.aborted) setLanguagesData(data.languages || []);
}

if (statsRes.ok) {
const data = await statsRes.json();
if (!signal.aborted) setStats(data);
}
if (specsBody) setSpecsData(Array.isArray(specsBody) ? specsBody : specsBody.specs || []);
if (libsBody) setLibrariesData(libsBody.libraries || []);
if (langsBody) setLanguagesData(langsBody.languages || []);
if (statsBody) setStats(statsBody);
} catch (err) {
if (signal.aborted) return;
console.warn('Initial data load incomplete:', err instanceof Error ? err.message : err);
Expand Down
9 changes: 3 additions & 6 deletions app/src/components/PlotOfTheDay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ import IconButton from '@mui/material/IconButton';
import Link from '@mui/material/Link';
import Typography from '@mui/material/Typography';

import { API_URL, GITHUB_URL } from 'src/constants';
import { GITHUB_URL } from 'src/constants';
import { useAnalytics } from 'src/hooks';
import { useTheme } from 'src/hooks/useLayoutContext';
import { apiGet, endpoints } from 'src/lib/api';
import { colors, fontSize, semanticColors, typography } from 'src/theme';
import { specPath } from 'src/utils/paths';
import { buildSrcSet, getFallbackSrc } from 'src/utils/responsiveImage';
Expand Down Expand Up @@ -49,11 +50,7 @@ export function PlotOfTheDay() {

useEffect(() => {
if (dismissed) return;
fetch(`${API_URL}/insights/plot-of-the-day`)
.then(r => {
if (!r.ok) throw new Error();
return r.json();
})
apiGet<PlotOfTheDayData>(endpoints.plotOfTheDay)
.then(setData)
.catch(() => {})
.finally(() => setLoading(false));
Expand Down
9 changes: 3 additions & 6 deletions app/src/components/RelatedSpecs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ import Tab from '@mui/material/Tab';
import Tabs from '@mui/material/Tabs';
import Typography from '@mui/material/Typography';

import { API_URL, LIB_ABBREV } from 'src/constants';
import { LIB_ABBREV } from 'src/constants';
import { useTheme } from 'src/hooks/useLayoutContext';
import { apiGet, endpoints } from 'src/lib/api';
import { colors, fontSize, semanticColors, typography } from 'src/theme';
import { specPath } from 'src/utils/paths';
import { buildSrcSet, getFallbackSrc } from 'src/utils/responsiveImage';
Expand Down Expand Up @@ -62,11 +63,7 @@ export function RelatedSpecs({ specId, mode = 'spec', library, onHoverTags }: Re
let cancelled = false;
const params = new URLSearchParams({ limit: '24', mode });
if (library && mode === 'full') params.set('library', library);
fetch(`${API_URL}/insights/related/${specId}?${params}`)
.then(r => {
if (!r.ok) throw new Error();
return r.json();
})
apiGet<{ related?: RelatedSpec[] }>(endpoints.relatedSpecs(specId, params.toString()))
.then(data => {
if (!cancelled) {
setRelated(data.related ?? []);
Expand Down
10 changes: 7 additions & 3 deletions app/src/components/SpecTabs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import Tooltip from '@mui/material/Tooltip';
import Typography from '@mui/material/Typography';

const CodeHighlighter = lazy(() => import('src/components/CodeHighlighter'));
import { API_URL } from 'src/constants';
import { apiGet, endpoints } from 'src/lib/api';
import { colors, fontSize, semanticColors, typography } from 'src/theme';

// Cached global tag counts — loaded once, shared across all SpecTabs instances
Expand Down Expand Up @@ -198,8 +198,12 @@ export function SpecTabs({
useEffect(() => {
if (cachedTagCounts) return;
const controller = new AbortController();
fetch(`${API_URL}/plots/filter?limit=1`, { signal: controller.signal })
.then(r => (r.ok ? r.json() : null))
// Non-ok responses previously resolved to null and were ignored; apiGet
// throws instead, so the empty catch keeps the same silent-skip behavior.
apiGet<{ globalCounts?: Record<string, Record<string, number>> }>(
endpoints.plotsFilter('limit=1'),
{ signal: controller.signal }
)
.then(data => {
if (data?.globalCounts) {
cachedTagCounts = data.globalCounts;
Expand Down
12 changes: 8 additions & 4 deletions app/src/hooks/useCodeFetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ describe('useCodeFetch', () => {

expect(code).toBe(mplCode);
expect(globalThis.fetch).toHaveBeenCalledWith(
expect.stringContaining('/specs/scatter-basic/matplotlib/code')
expect.stringContaining('/specs/scatter-basic/matplotlib/code'),
undefined
);
});

Expand Down Expand Up @@ -178,7 +179,8 @@ describe('useCodeFetch', () => {

expect(code).toBe(ggCode);
expect(globalThis.fetch).toHaveBeenCalledWith(
expect.stringContaining('/specs/scatter-basic/ggplot2/code?language=r')
expect.stringContaining('/specs/scatter-basic/ggplot2/code?language=r'),
undefined
);
});

Expand All @@ -197,7 +199,8 @@ describe('useCodeFetch', () => {

expect(code).toBe(jlCode);
expect(globalThis.fetch).toHaveBeenCalledWith(
expect.stringContaining('/specs/scatter-basic/makie/code?language=julia')
expect.stringContaining('/specs/scatter-basic/makie/code?language=julia'),
undefined
);
});

Expand All @@ -216,7 +219,8 @@ describe('useCodeFetch', () => {

expect(code).toBe(tsxCode);
expect(globalThis.fetch).toHaveBeenCalledWith(
expect.stringContaining('/specs/scatter-basic/muix/code?language=javascript')
expect.stringContaining('/specs/scatter-basic/muix/code?language=javascript'),
undefined
);
});

Expand Down
30 changes: 11 additions & 19 deletions app/src/hooks/useCodeFetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import { useCallback, useRef, useState } from 'react';

import { API_URL } from 'src/constants';
import { apiGet, endpoints } from 'src/lib/api';

interface CodeCache {
[key: string]: string | null; // key: `${spec_id}:${language}:${library}`
Expand All @@ -25,7 +25,10 @@ const cacheKey = (specId: string, library: string, language: string) =>
`${specId}:${language}:${library}`;

export function useCodeFetch(): UseCodeFetchReturn {
const [isLoading, setIsLoading] = useState(false);
// Count in-flight requests instead of a boolean: with overlapping fetches
// (different cache keys) the first completion must not clear the loading
// state while the second request is still pending.
const [pendingCount, setPendingCount] = useState(0);
const cacheRef = useRef<CodeCache>({});
const pendingRef = useRef<Map<string, Promise<string | null>>>(new Map());

Expand Down Expand Up @@ -55,23 +58,12 @@ export function useCodeFetch(): UseCodeFetchReturn {
return pending;
}

// Only append the language query param when it diverges from the API
// default — keeps URLs for the common Python case unchanged.
const url =
language === 'python'
? `${API_URL}/specs/${specId}/${library}/code`
: `${API_URL}/specs/${specId}/${library}/code?language=${encodeURIComponent(language)}`;

setIsLoading(true);
setPendingCount(count => count + 1);
const promise = (async () => {
try {
const response = await fetch(url);
if (!response.ok) {
cacheRef.current[key] = null;
return null;
}

const data = await response.json();
const data = await apiGet<{ code?: string | null }>(
endpoints.code(specId, library, language)
);
const code = data.code ?? null;
cacheRef.current[key] = code;
return code;
Expand All @@ -80,7 +72,7 @@ export function useCodeFetch(): UseCodeFetchReturn {
return null;
} finally {
pendingRef.current.delete(key);
setIsLoading(false);
setPendingCount(count => count - 1);
}
})();

Expand All @@ -90,5 +82,5 @@ export function useCodeFetch(): UseCodeFetchReturn {
[]
);

return { fetchCode, getCode, isLoading };
return { fetchCode, getCode, isLoading: pendingCount > 0 };
}
9 changes: 4 additions & 5 deletions app/src/hooks/useFeaturedSpecs.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useEffect, useMemo, useState } from 'react';

import { API_URL } from 'src/constants';
import { useAppData } from 'src/hooks/useLayoutContext';
import { apiGet, endpoints } from 'src/lib/api';
import type { PlotImage } from 'src/types';
import { shuffleArray } from 'src/utils/shuffle';

Expand Down Expand Up @@ -35,10 +35,9 @@ export function useFeaturedSpecs(count: number = 5): FeaturedImpl[] | null {

useEffect(() => {
let cancelled = false;
fetch(`${API_URL}/plots/filter`)
.then(r => (r.ok ? r.json() : null))
.then((data: { images?: PlotImage[] } | null) => {
if (cancelled || !data?.images) return;
apiGet<{ images?: PlotImage[] }>(endpoints.plotsFilter())
.then(data => {
if (cancelled || !data.images) return;
setImages(data.images);
})
.catch(() => {});
Expand Down
17 changes: 9 additions & 8 deletions app/src/hooks/useFilterFetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@

import { useEffect, useMemo, useRef, useState } from 'react';

import { API_URL, BATCH_SIZE } from 'src/constants';
import { BATCH_SIZE } from 'src/constants';
import { apiGet, endpoints } from 'src/lib/api';
import type { ActiveFilters, FilterCounts, PlotImage } from 'src/types';
import { shuffleArray } from 'src/utils/shuffle';

Expand Down Expand Up @@ -96,13 +97,13 @@ export function useFilterFetch({
}
});

const queryString = params.toString();
const url = `${API_URL}/plots/filter${queryString ? `?${queryString}` : ''}`;

const response = await fetch(url, { signal: abortController.signal });
if (!response.ok) throw new Error('Failed to fetch filtered plots');

const data = await response.json();
const data = await apiGet<{
counts: FilterCounts;
globalCounts?: FilterCounts;
orCounts?: Record<string, number>[];
specTitles?: Record<string, string>;
images?: PlotImage[];
}>(endpoints.plotsFilter(params.toString()), { signal: abortController.signal });

if (abortController.signal.aborted) return;

Comment on lines +105 to 109
Expand Down
10 changes: 3 additions & 7 deletions app/src/hooks/usePlotOfTheDay.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react';

import { API_URL } from 'src/constants';
import { apiGet, endpoints } from 'src/lib/api';

export interface PlotOfTheDayData {
spec_id: string;
Expand All @@ -26,12 +26,8 @@ export function usePlotOfTheDay(): PlotOfTheDayData | null {

useEffect(() => {
let cancelled = false;
fetch(`${API_URL}/insights/plot-of-the-day`)
.then(r => {
if (!r.ok) throw new Error(`${r.status}`);
return r.json();
})
.then((data: PlotOfTheDayData) => {
apiGet<PlotOfTheDayData>(endpoints.plotOfTheDay)
.then(data => {
if (!cancelled) setPotd(data);
})
.catch(() => {});
Expand Down
Loading
Loading