@@ -6,33 +6,51 @@ import {
66 resolveBlockCategory ,
77} from "../utils/blockCategories" ;
88
9- export type CatalogItem = RegistryItem & {
9+ type CatalogItem = RegistryItem & {
1010 category : BlockCategory ;
1111} ;
1212
13+ let catalogCache : CatalogItem [ ] | null = null ;
14+ let catalogRequest : Promise < CatalogItem [ ] > | null = null ;
15+
16+ function loadCatalog ( ) : Promise < CatalogItem [ ] > {
17+ catalogRequest ??= fetch ( "/api/registry/blocks" )
18+ . then ( ( response ) => {
19+ if ( ! response . ok ) throw new Error ( "Failed to load catalog" ) ;
20+ return response . json ( ) as Promise < RegistryItem [ ] > ;
21+ } )
22+ . then ( ( items ) => {
23+ catalogCache = items
24+ . map ( ( item ) => ( { ...item , category : resolveBlockCategory ( item . tags ) } ) )
25+ . sort ( ( a , b ) => {
26+ const aIndex = BLOCK_CATEGORIES . findIndex ( ( category ) => category . id === a . category ) ;
27+ const bIndex = BLOCK_CATEGORIES . findIndex ( ( category ) => category . id === b . category ) ;
28+ return ( aIndex === - 1 ? 99 : aIndex ) - ( bIndex === - 1 ? 99 : bIndex ) ;
29+ } ) ;
30+ return catalogCache ;
31+ } )
32+ . catch ( ( error : unknown ) => {
33+ catalogRequest = null ;
34+ throw error ;
35+ } ) ;
36+ return catalogRequest ;
37+ }
38+
1339export function useBlockCatalog ( ) {
14- const [ blocks , setBlocks ] = useState < CatalogItem [ ] > ( [ ] ) ;
15- const [ loading , setLoading ] = useState ( true ) ;
40+ const [ blocks , setBlocks ] = useState < CatalogItem [ ] > ( ( ) => catalogCache ?? [ ] ) ;
41+ const [ loading , setLoading ] = useState ( catalogCache === null ) ;
1642 const [ error , setError ] = useState < string | null > ( null ) ;
1743 const [ search , setSearch ] = useState ( "" ) ;
1844 const [ category , setCategory ] = useState < BlockCategory | null > ( null ) ;
1945
2046 // fallow-ignore-next-line complexity
2147 useEffect ( ( ) => {
48+ if ( catalogCache ) return ;
2249 let cancelled = false ;
2350 ( async ( ) => {
2451 try {
25- const res = await fetch ( "/api/registry/blocks" ) ;
26- if ( ! res . ok ) throw new Error ( "Failed to load catalog" ) ;
27- const data = ( await res . json ( ) ) as RegistryItem [ ] ;
52+ const items = await loadCatalog ( ) ;
2853 if ( cancelled ) return ;
29- const items = data
30- . map ( ( b ) => ( { ...b , category : resolveBlockCategory ( b . tags ) } ) )
31- . sort ( ( a , b ) => {
32- const ia = BLOCK_CATEGORIES . findIndex ( ( c ) => c . id === a . category ) ;
33- const ib = BLOCK_CATEGORIES . findIndex ( ( c ) => c . id === b . category ) ;
34- return ( ia === - 1 ? 99 : ia ) - ( ib === - 1 ? 99 : ib ) ;
35- } ) ;
3654 setBlocks ( items ) ;
3755 } catch ( err ) {
3856 if ( cancelled ) return ;
0 commit comments