|
| 1 | +import { createContext, createMemo, createSignal, useContext } from 'solid-js' |
| 2 | +import { createStore } from 'solid-js/store' |
| 3 | + |
| 4 | +import { runAudit } from '../scanner/audit' |
| 5 | +import { DEFAULT_CONFIG } from '../config' |
| 6 | + |
| 7 | +import type { |
| 8 | + A11yAuditResult, |
| 9 | + A11yPluginOptions, |
| 10 | + SeverityThreshold, |
| 11 | +} from '../types' |
| 12 | +import type { ParentComponent } from 'solid-js' |
| 13 | + |
| 14 | +type UseAllyValueProps = { |
| 15 | + options?: A11yPluginOptions |
| 16 | +} |
| 17 | + |
| 18 | +function useAllyValue(props: UseAllyValueProps) { |
| 19 | + const [config, setConfig] = createStore<A11yPluginOptions>({ |
| 20 | + ...DEFAULT_CONFIG, |
| 21 | + ...(props.options ?? {}), |
| 22 | + }) |
| 23 | + |
| 24 | + const [allyResult, setAllyResult] = createStore<{ |
| 25 | + audit?: A11yAuditResult |
| 26 | + state: 'init' | 'scanning' | 'done' |
| 27 | + }>({ state: 'init' }) |
| 28 | + const [impactKey, setImpactKey] = createSignal<SeverityThreshold | 'all'>( |
| 29 | + 'all', |
| 30 | + ) |
| 31 | + |
| 32 | + const triggerAllyScan = async () => { |
| 33 | + const results = await runAudit(config) |
| 34 | + setAllyResult({ audit: results, state: 'done' }) |
| 35 | + } |
| 36 | + |
| 37 | + const filteredIssues = createMemo(() => { |
| 38 | + if (allyResult.state !== 'done' || !allyResult.audit?.issues) return [] |
| 39 | + if (impactKey() === 'all') return allyResult.audit.issues |
| 40 | + |
| 41 | + return allyResult.audit.issues.filter((val) => val.impact === impactKey()) |
| 42 | + }) |
| 43 | + |
| 44 | + return { |
| 45 | + impactKey, |
| 46 | + setImpactKey, |
| 47 | + |
| 48 | + filteredIssues, |
| 49 | + |
| 50 | + triggerAllyScan, |
| 51 | + |
| 52 | + setConfig, |
| 53 | + |
| 54 | + audit: allyResult.audit, |
| 55 | + state: allyResult.state, |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +type ContextType = ReturnType<typeof useAllyValue> |
| 60 | + |
| 61 | +const AllyContext = createContext<ContextType | null>(null) |
| 62 | + |
| 63 | +type AllyProviderProps = { options?: A11yPluginOptions } |
| 64 | + |
| 65 | +export const AllyProvider: ParentComponent<AllyProviderProps> = (props) => { |
| 66 | + const value = useAllyValue({ options: props.options }) |
| 67 | + |
| 68 | + return ( |
| 69 | + <AllyContext.Provider value={value}>{props.children}</AllyContext.Provider> |
| 70 | + ) |
| 71 | +} |
| 72 | + |
| 73 | +export function useAllyContext() { |
| 74 | + const context = useContext(AllyContext) |
| 75 | + |
| 76 | + if (context === null) { |
| 77 | + throw new Error('useAllyContext must be used within an AllyProvider') |
| 78 | + } |
| 79 | + |
| 80 | + return context |
| 81 | +} |
0 commit comments