a tool for shared writing and social publishing
at feature/fonts 70 lines 2.1 kB view raw
1import { useMemo } from "react"; 2import { useSubscribe } from "src/replicache/useSubscribe"; 3import { useReplicache } from "src/replicache"; 4import { scanIndex, scanIndexLocal } from "src/replicache/utils"; 5import { getBlocksWithType, getBlocksWithTypeLocal } from "src/replicache/getBlocks"; 6 7export const useBlocks = (entityID: string | null) => { 8 let rep = useReplicache(); 9 let initialValue = useMemo( 10 () => 11 entityID === null 12 ? [] 13 : getBlocksWithTypeLocal(rep.initialFacts, entityID), 14 [rep.initialFacts, entityID], 15 ); 16 let repData = useSubscribe( 17 rep?.rep, 18 async (tx) => (entityID === null ? [] : getBlocksWithType(tx, entityID)), 19 { dependencies: [entityID] }, 20 ); 21 let data = repData || initialValue; 22 return data.flatMap((f) => (!f ? [] : [f])); 23}; 24 25export const useCanvasBlocksWithType = (entityID: string | null) => { 26 let rep = useReplicache(); 27 let initialValue = useMemo(() => { 28 if (!entityID) return []; 29 let scan = scanIndexLocal(rep.initialFacts); 30 let blocks = scan.eav(entityID, "canvas/block"); 31 return blocks 32 .map((b) => { 33 let type = scan.eav(b.data.value, "block/type"); 34 if (!type[0]) return null; 35 return { 36 ...b.data, 37 type: type[0]?.data.value || "text", 38 }; 39 }) 40 .filter((f) => f !== null); 41 }, [rep.initialFacts, entityID]); 42 let repData = useSubscribe( 43 rep?.rep, 44 async (tx) => { 45 if (!entityID) return []; 46 let scan = scanIndex(tx); 47 let blocks = await scan.eav(entityID, "canvas/block"); 48 return Promise.all( 49 blocks.map(async (b) => { 50 let type = await scan.eav(b.data.value, "block/type"); 51 return { 52 ...b.data, 53 type: type[0].data.value, 54 }; 55 }), 56 ); 57 }, 58 { dependencies: [entityID] }, 59 ); 60 let data = repData || initialValue; 61 return data 62 .flatMap((f) => (!f ? [] : [f])) 63 .sort((a, b) => { 64 if (a.position.y === b.position.y) { 65 return a.position.x - b.position.x; 66 } 67 return a.position.y - b.position.y; 68 }); 69}; 70