Scrapboard.org client
1"use client";
2import { useEffect } from "react";
3import { useAuth } from "./useAuth";
4import { useModerationOptsStore } from "../stores/moderationOpts";
5import { DEFAULT_LABEL_SETTINGS } from "@atproto/api";
6
7/**
8 * From {@link https://github.com/bluesky-social/social-app/blob/2a6172cbaf2db0eda2a7cd2afaeef4b60aadf3ba/src/state/queries/preferences/moderation.ts#L15}
9 */
10export const DEFAULT_LOGGED_OUT_LABEL_PREFERENCES: typeof DEFAULT_LABEL_SETTINGS =
11 Object.fromEntries(
12 Object.entries(DEFAULT_LABEL_SETTINGS).map(([key, _pref]) => [key, "hide"])
13 );
14
15export function useModerationOpts() {
16 const { agent } = useAuth();
17 const {
18 moderationPrefs,
19 labelDefs,
20 isLoading,
21 error,
22 setModerationOpts,
23 setLoading,
24 setError,
25 isStale,
26 shouldRefetch,
27 } = useModerationOptsStore();
28
29 useEffect(() => {
30 if (!agent || agent?.did == null) return;
31
32 const fetchModerationOpts = async () => {
33 try {
34 setLoading(true);
35 const prefs = await agent.getPreferences();
36 const labelDefs = await agent.getLabelDefinitions(prefs);
37 setModerationOpts(prefs.moderationPrefs, labelDefs);
38 } catch (err) {
39 console.error("Error fetching moderation opts:", err);
40 setError(err instanceof Error ? err.message : String(err));
41 } finally {
42 setLoading(false);
43 }
44 };
45
46 // If we have stale data, return it immediately but fetch fresh data in background
47 if (moderationPrefs && labelDefs && isStale()) {
48 fetchModerationOpts(); // Background refresh
49 }
50 // If we have no data or data is expired, fetch immediately
51 else if (!moderationPrefs || !labelDefs || shouldRefetch()) {
52 fetchModerationOpts();
53 }
54 }, [
55 agent,
56 moderationPrefs,
57 labelDefs,
58 isStale,
59 shouldRefetch,
60 setModerationOpts,
61 setLoading,
62 setError,
63 ]);
64
65 return {
66 moderationPrefs,
67 labelDefs,
68 isLoading,
69 error,
70 };
71}