PluginProbe
Code Block Pro – Beautiful Syntax Highlighting / 1.13.0
Code Block Pro – Beautiful Syntax Highlighting v1.13.0
1.27.1 1.27.2 1.27.3 1.27.4 1.27.5 1.27.6 1.27.7 1.28.0 1.3.0 1.4.0 1.5.0 1.5.1 1.5.2 1.6.0 1.7.0 1.8.0 1.9.0 1.9.1 1.9.2 1.9.3 trunk 1.1.0 1.10.0 1.11.0 1.11.1 All 63 releases
code-block-pro / src / state / settings.ts

settings.ts in Code Block Pro – Beautiful Syntax Highlighting 1.13.0, at src/state/settings.ts

86 lines 3.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 import apiFetch from '@wordpress/api-fetch';
2 import { useEffect, useState } from '@wordpress/element';
3 import create from 'zustand';
4 import { devtools, persist } from 'zustand/middleware';
5
6 type Settings = {
7 seenNotices: string[];
8 hiddenThemes: string[];
9 setSeenNotice: (notice: string) => void;
10 toggleHiddenTheme: (theme: string) => void;
11 };
12 const path = '/wp/v2/settings';
13 const getSettings = async (name: string) => {
14 const allSettings = await apiFetch({ path });
15 // eslint-disable-next-line @typescript-eslint/ban-ts-comment
16 // @ts-ignore-next-line
17 return allSettings?.[name];
18 };
19 export const useSettingsStore = create<Settings>()(
20 persist(
21 devtools(
22 (set) => ({
23 seenNotices: [],
24 hiddenThemes: [],
25 setSeenNotice(notice: string) {
26 set((state) => {
27 if (state.seenNotices.includes(notice)) return state;
28 return { seenNotices: [...state.seenNotices, notice] };
29 });
30 },
31 toggleHiddenTheme(theme: string) {
32 set((state) => ({
33 hiddenThemes: state.hiddenThemes.includes(theme)
34 ? state.hiddenThemes.filter((t) => t !== theme)
35 : [...state.hiddenThemes, theme],
36 }));
37 },
38 }),
39 { name: 'Code Block Pro Settings' },
40 ),
41 {
42 name: 'code_block_pro_settings_2',
43 getStorage: () => ({
44 getItem: async (name: string) => {
45 const settings = await getSettings(name);
46 return JSON.stringify({
47 version: settings?.version ?? 0,
48 state: settings,
49 });
50 },
51 setItem: async (name: string, value: string) => {
52 const { state, version } = JSON.parse(value);
53 const data = {
54 [name]: Object.assign(
55 (await getSettings(name)) ?? {},
56 state,
57 version,
58 ),
59 };
60 await apiFetch({ path, method: 'POST', data });
61 },
62 removeItem: async (name: string) => {
63 const data = { [name]: null };
64 return await apiFetch({ path, method: 'POST', data });
65 },
66 }),
67 },
68 ),
69 );
70
71 /* Hook useful for when you need to wait on the async state to hydrate */
72 export const useSettingsStoreReady = () => {
73 const [hydrated, setHydrated] = useState(
74 useSettingsStore.persist.hasHydrated,
75 );
76 useEffect(() => {
77 const unsubFinishHydration = useSettingsStore.persist.onFinishHydration(
78 () => setHydrated(true),
79 );
80 return () => {
81 unsubFinishHydration();
82 };
83 }, []);
84 return hydrated;
85 };
86