Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

react-query for blocklist fetching and caching #128

Merged
merged 8 commits into from
Nov 24, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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
47 changes: 47 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,17 @@
"keywords": [],
"author": "",
"license": "ISC",
"prettier": {
"singleQuote": true
},
"dependencies": {
"@atproto/api": "^0.10.4",
"@emotion/react": "^11.11.1",
"@emotion/styled": "^11.11.0",
"@mui/icons-material": "^5.14.16",
"@mui/material": "^5.14.20",
"@mui/styles": "^5.14.20",
"@tanstack/react-query": "^4.36.1",
"ag-grid-community": "^31.0.2",
"ag-grid-react": "^31.0.3",
"esbuild": "^0.20.0",
Expand Down
126 changes: 35 additions & 91 deletions src/api/blocklist.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,84 +3,47 @@
import { unwrapShortHandle, v1APIPrefix, xAPIKey } from '.';
import { parseNumberWithCommas, unwrapClearSkyURL } from './core';
import { resolveHandleOrDID } from './resolve-handle-or-did';

const blocklistFetchQueued = new Map();
let blocklistDebounce = 0;
import { useInfiniteQuery } from '@tanstack/react-query';

/**
* @param {string} handleOrDID
*/
export function blocklist(handleOrDID) {
if (blocklistFetchQueued.has(handleOrDID)) return blocklistFetchQueued.get(handleOrDID);

let generator = blocklistCall(handleOrDID, 'blocklist');
blocklistFetchQueued.set(handleOrDID, generator);

clearTimeout(blocklistDebounce);
blocklistDebounce = setTimeout(() => blocklistFetchQueued.delete(handleOrDID), 1000);

return generator;
export function useBlocklist(handleOrDID) {
return useInfiniteQuery({
queryKey: ['blocklist', handleOrDID],
queryFn: ({ pageParam = 1 }) =>
blocklistCall(handleOrDID, 'blocklist', pageParam),
getNextPageParam: (lastPage, pages) => lastPage.nextPage,
});
}

const singleBlocklistFetchQueued = new Map();
let singleBlocklistDebounce = 0;

/**
* @param {string} handleOrDID
*/
export function singleBlocklist(handleOrDID) {
if (singleBlocklistFetchQueued.has(handleOrDID)) return singleBlocklistFetchQueued.get(handleOrDID);

let generator = blocklistCall(handleOrDID, 'single-blocklist');

singleBlocklistFetchQueued.set(handleOrDID, generator);

clearTimeout(singleBlocklistDebounce);
singleBlocklistDebounce = setTimeout(() => singleBlocklistFetchQueued.delete(handleOrDID), 1000);

return generator;
export function useSingleBlocklist(handleOrDID) {
return useInfiniteQuery({
queryKey: ['single-blocklist', handleOrDID],
queryFn: ({ pageParam = 1 }) =>
blocklistCall(handleOrDID, 'single-blocklist', pageParam),
getNextPageParam: (lastPage, pages) => lastPage.nextPage,
});
}

/**
* @typedef {{
* shortDID: string,
* api: string,
* count: number,
* nextPage: number,
* blocklist: BlockedByRecord[]
* }} BlockCacheEntry
*/

/**
* @type {{ [key: string]: BlockCacheEntry }}
*/
const blockApiResultCache = {};

/**
* @param {string} handleOrDID
* @param {string} api
* @returns {AsyncGenerator<{
* @param {"blocklist" | "single-blocklist"} api
* @param {number} currentPage
* @returns {Promise<{
* count: number,
* nextPage: number,
* nextPage: number | null,
* blocklist: BlockedByRecord[]
* }>}
*/
async function* blocklistCall(handleOrDID, api) {
export async function blocklistCall(handleOrDID, api, currentPage = 1) {
const resolved = await resolveHandleOrDID(handleOrDID);

if (!resolved) throw new Error('Could not resolve handle or DID: ' + handleOrDID);

const key = resolved.shortDID + '/' + api;
let cacheEntry = blockApiResultCache[key];
if (cacheEntry) {
yield {
count: cacheEntry.count,
nextPage: cacheEntry.nextPage,
blocklist: cacheEntry.blocklist
};

if (!cacheEntry.nextPage) return;
}
if (!resolved)
throw new Error('Could not resolve handle or DID: ' + handleOrDID);

/**
* @typedef {{
Expand All @@ -96,40 +59,21 @@ async function* blocklistCall(handleOrDID, api) {
const handleURL =
unwrapClearSkyURL(v1APIPrefix + api + '/') +
unwrapShortHandle(resolved.shortHandle);

let nextPageNumber = cacheEntry?.nextPage || 1;
while (true) {

/** @type {SingleBlocklistResponse} */
const pageResponse = await fetch(
nextPageNumber === 1 ? handleURL : handleURL + '/' + nextPageNumber,
{ headers: { 'X-API-Key': xAPIKey } }).then(x => x.json());

let pages = parseNumberWithCommas(pageResponse.data.pages) || 1;
let count = parseNumberWithCommas(pageResponse.data.count) || 0;

const chunk = pageResponse.data.blocklist;
/** @type {SingleBlocklistResponse} */
const pageResponse = await fetch(
currentPage === 1 ? handleURL : handleURL + '/' + currentPage,
{ headers: { 'X-API-Key': xAPIKey } }
).then((x) => x.json());

if (cacheEntry) {
cacheEntry.blocklist = cacheEntry.blocklist.concat(chunk);
} else {
blockApiResultCache[key] = cacheEntry = {
shortDID: resolved.shortDID,
api,
count,
nextPage: 0,
blocklist: chunk
};
}
cacheEntry.count = count;
cacheEntry.nextPage = nextPageNumber = nextPageNumber >= pages ? 0 : nextPageNumber + 1;
let pages = parseNumberWithCommas(pageResponse.data.pages) || 1;
let count = parseNumberWithCommas(pageResponse.data.count) || 0;

yield {
count,
nextPage: cacheEntry.nextPage,
blocklist: cacheEntry.blocklist
};
const chunk = pageResponse.data.blocklist;

if (!cacheEntry.nextPage) break;
}
return {
count,
nextPage: pages === currentPage ? null : currentPage + 1,
blocklist: chunk,
};
}
2 changes: 1 addition & 1 deletion src/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export { dashboardStats } from './dashboard-stats';
export { postHistory } from './post-history';
export { resolveHandleOrDID } from './resolve-handle-or-did';
export { searchHandle } from './search';
export { singleBlocklist, blocklist } from './blocklist';
export { useSingleBlocklist, useBlocklist } from './blocklist';

export const xAPIKey = '';

Expand Down
7 changes: 5 additions & 2 deletions src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
RouterProvider,
} from "react-router-dom";
import { createTheme, ThemeProvider } from '@mui/material';
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"

import { AgGridReact } from 'ag-grid-react'; // React Grid Logic
import "ag-grid-community/styles/ag-grid.css"; // Core CSS
Expand Down Expand Up @@ -89,16 +90,18 @@ function showApp() {
},
});

const queryClient = new QueryClient();

console.log('React createRoot/render');
ReactDOM.createRoot(root).render(
<React.StrictMode>
<ThemeProvider theme={theme}>
<>
<QueryClientProvider client={queryClient}>
<RouterProvider router={router}/>
<div className='bluethernal-llc-watermark'>
© 2024 Bluethernal LLC
</div>
</>
</QueryClientProvider>
</ThemeProvider>
</React.StrictMode>

Expand Down
86 changes: 69 additions & 17 deletions src/common-components/visible.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,30 @@
// @ts-check
import React from 'react';
import { useEffect, useRef, useState } from 'react';
import { useEffect, useRef, useState, useCallback } from 'react';

/**
* @param {{
/** @typedef {{
* Component?: React.ElementType,
* onVisible?: () => void,
* onObscured?: () => void,
* rootMargin?: string;
* threshold?: number | number[];
* children?: React.ReactNode,
* className?: string
* }} _
* }} VisibleProps */

/**
* Notifies when it becomes visible or obscured (by scrolling, usually)
* @param {VisibleProps} _
*/
export function Visible({ Component = 'div', onVisible, onObscured, rootMargin, threshold, children, ...rest }) {
export function Visible({
Component = 'div',
onVisible,
onObscured,
rootMargin,
threshold,
children,
...rest
}) {
let [visible, setVisible] = useState(false);
const ref = useRef(null);

Expand All @@ -22,18 +33,19 @@ export function Visible({ Component = 'div', onVisible, onObscured, rootMargin,
return;
}

const observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting !== visible) {
setVisible(visible = entry.isIntersecting);
if (entry.isIntersecting)
onVisible?.();
else
onObscured?.();
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting !== visible) {
setVisible((visible = entry.isIntersecting));
if (entry.isIntersecting) onVisible?.();
else onObscured?.();
}
},
{
rootMargin,
threshold,
}
}, {
rootMargin,
threshold
});
);

observer.observe(ref.current);
return () => observer.disconnect();
Expand All @@ -44,4 +56,44 @@ export function Visible({ Component = 'div', onVisible, onObscured, rootMargin,
{children}
</Component>
);
}
}

/**
* Notifies when it becomes visible, but only after a given delay,
* and notifications are cancelled if obscured during the delay.
* @param {VisibleProps & { delayMs: number }} _
*/
export function VisibleWithDelay({
delayMs,
onVisible: onVisibleAfterDelay,
onObscured: onObscuredOriginal,
...rest
}) {
/** @type {React.MutableRefObject<number | undefined>} */
const nextPageTimeout = useRef();
useEffect(() => {
return () => {
if (nextPageTimeout.current) {
clearTimeout(nextPageTimeout.current);
}
};
}, []);

const onVisible = useCallback(() => {
if (nextPageTimeout.current) return;
nextPageTimeout.current = setTimeout(() => {
onVisibleAfterDelay?.();
nextPageTimeout.current = undefined;
}, delayMs);
}, [delayMs, onVisibleAfterDelay]);

const onObscured = useCallback(() => {
onObscuredOriginal?.();
if (nextPageTimeout.current) {
clearTimeout(nextPageTimeout.current);
nextPageTimeout.current = undefined;
}
}, [onObscuredOriginal]);

return <Visible {...rest} onVisible={onVisible} onObscured={onObscured} />;
}
Loading