| 1 |
import { useCallback, useState } from 'react' |
| 2 |
import { DEFAULT_SNIPPET_VIEW } from '../types/SnippetView' |
| 3 |
import { handleUnknownError } from '../utils/errors' |
| 4 |
import { REST_BASES } from '../utils/restAPI' |
| 5 |
import { useRestAPI } from './useRestAPI' |
| 6 |
import type { SnippetView } from '../types/SnippetView' |
| 7 |
|
| 8 |
export interface UseSnippetView { |
| 9 |
snippetView: SnippetView |
| 10 |
setSnippetView: (view: SnippetView) => void |
| 11 |
} |
| 12 |
|
| 13 |
/** |
| 14 |
* Plugin-wide snippet view preference (cards or table). |
| 15 |
* |
| 16 |
* The initial value is localized into the page, and updates are persisted |
| 17 |
* through the preferences REST endpoint so the choice survives page loads |
| 18 |
* everywhere snippet lists are displayed. The UI updates optimistically |
| 19 |
* rather than waiting for the save to complete. |
| 20 |
*/ |
| 21 |
export const useSnippetView = (): UseSnippetView => { |
| 22 |
const { api } = useRestAPI() |
| 23 |
const [snippetView, setViewState] = useState<SnippetView>( |
| 24 |
() => window.CODE_SNIPPETS?.snippetView ?? DEFAULT_SNIPPET_VIEW |
| 25 |
) |
| 26 |
|
| 27 |
const setSnippetView = useCallback((view: SnippetView) => { |
| 28 |
setViewState(view) |
| 29 |
api.post<{ view: SnippetView }, { view: SnippetView }>(`${REST_BASES.preferences}/snippet-view`, { view }) |
| 30 |
.catch(handleUnknownError) |
| 31 |
}, [api]) |
| 32 |
|
| 33 |
return { snippetView, setSnippetView } |
| 34 |
} |
| 35 |
|