a tool for shared writing and social publishing
1"use client";
2import { getRSVPData } from "actions/getRSVPData";
3import { SWRConfig } from "swr";
4import { useReplicache } from "src/replicache";
5import useSWR from "swr";
6import { callRPC } from "app/api/rpc/client";
7import { getPollData } from "actions/pollActions";
8import type { GetLeafletDataReturnType } from "app/api/rpc/[command]/get_leaflet_data";
9import { createContext, useContext } from "react";
10import { getPublicationMetadataFromLeafletData } from "src/utils/getPublicationMetadataFromLeafletData";
11
12export const StaticLeafletDataContext = createContext<
13 null | GetLeafletDataReturnType["result"]["data"]
14>(null);
15export function PageSWRDataProvider(props: {
16 leaflet_id: string;
17 leaflet_data: GetLeafletDataReturnType["result"];
18 rsvp_data: Awaited<ReturnType<typeof getRSVPData>>;
19 poll_data: Awaited<ReturnType<typeof getPollData>>;
20 children: React.ReactNode;
21}) {
22 return (
23 <SWRConfig
24 value={{
25 fallback: {
26 rsvp_data: props.rsvp_data,
27 poll_data: props.poll_data,
28 [`${props.leaflet_id}-leaflet_data`]: props.leaflet_data.data,
29 },
30 }}
31 >
32 {props.children}
33 </SWRConfig>
34 );
35}
36
37export function useRSVPData() {
38 let { permission_token } = useReplicache();
39 return useSWR(`rsvp_data`, () =>
40 getRSVPData(
41 permission_token.permission_token_rights.map((pr) => pr.entity_set),
42 ),
43 );
44}
45export function usePollData() {
46 let { permission_token } = useReplicache();
47 return useSWR(`poll_data`, () =>
48 getPollData(
49 permission_token.permission_token_rights.map((pr) => pr.entity_set),
50 ),
51 );
52}
53
54let useLeafletData = () => {
55 let { permission_token } = useReplicache();
56 let staticLeafletData = useContext(StaticLeafletDataContext);
57 let res = useSWR(
58 staticLeafletData ? null : `${permission_token.id}-leaflet_data`,
59 async () =>
60 permission_token.id
61 ? (await callRPC("get_leaflet_data", { token_id: permission_token.id }))
62 ?.result.data
63 : undefined,
64 );
65 if (staticLeafletData) return { data: staticLeafletData, mutate: res.mutate };
66 return res;
67};
68export function useLeafletPublicationData() {
69 let { data, mutate } = useLeafletData();
70
71 // First check for leaflets in publications
72 let pubData = getPublicationMetadataFromLeafletData(data);
73
74 return {
75 data: pubData || null,
76 mutate,
77 };
78}
79export function useLeafletDomains() {
80 let { data, mutate } = useLeafletData();
81 return { data: data?.custom_domain_routes, mutate: mutate };
82}