芝麻web文件管理V1.00
编辑当前文件:/home/freeclou/optimyar/wp-content/plugins/code-snippets/js/hooks/useSnippetForm.tsx
import { isAxiosError } from 'axios' import React, { useCallback, useMemo, useState } from 'react' import { createContextHook } from '../utils/hooks' import { isLicensed } from '../utils/screen' import { isProSnippet } from '../utils/snippets/snippets' import type { Dispatch, PropsWithChildren, SetStateAction } from 'react' import type { ScreenNotice } from '../types/ScreenNotice' import type { Snippet } from '../types/Snippet' import type { CodeEditorInstance } from '../types/WordPressCodeEditor' export interface SnippetFormContext { snippet: Snippet isWorking: boolean isReadOnly: boolean setSnippet: Dispatch
> updateSnippet: Dispatch
> setIsWorking: Dispatch
> currentNotice: ScreenNotice | undefined setCurrentNotice: Dispatch
> codeEditorInstance: CodeEditorInstance | undefined handleRequestError: (error: unknown, message?: string) => void setCodeEditorInstance: Dispatch
> } export const [SnippetFormContext, useSnippetForm] = createContextHook
('SnippetForm') export interface WithSnippetFormContextProps extends PropsWithChildren { initialSnippet: () => Snippet } export const WithSnippetFormContext: React.FC
= ({ children, initialSnippet }) => { const [snippet, setSnippet] = useState
(initialSnippet) const [isWorking, setIsWorking] = useState(false) const [currentNotice, setCurrentNotice] = useState
() const [codeEditorInstance, setCodeEditorInstance] = useState
() const isReadOnly = useMemo(() => !isLicensed() && isProSnippet({ scope: snippet.scope }), [snippet.scope]) const handleRequestError = useCallback((error: unknown, message?: string) => { console.error('Request failed', error) setIsWorking(false) setCurrentNotice(['error', [message, isAxiosError(error) ? error.message : ''].filter(Boolean).join(' ')]) }, [setIsWorking, setCurrentNotice]) const updateSnippet: Dispatch
> = useCallback((value: SetStateAction
) => { setSnippet(previous => { const updated = 'object' === typeof value ? value : value(previous) codeEditorInstance?.codemirror.setValue(updated.code) window.tinymce?.activeEditor.setContent(updated.desc) return updated }) }, [codeEditorInstance?.codemirror]) const value: SnippetFormContext = { snippet, isWorking, isReadOnly, setSnippet, setIsWorking, updateSnippet, currentNotice, setCurrentNotice, codeEditorInstance, handleRequestError, setCodeEditorInstance } return
{children}
}