import { message } from 'antd' ; import { TocItem , TocStepItem } from '@tuture/local-server' ; import { Dispatch , RootState } from '../store' ; import { saveData } from '../utils/request' ; export type TocState = { isSaving : boolean ; activeArticle : string ; needDeleteOutdatedStepList : string [ ] ; articleStepList : TocItem [ ] ; unassignedStepList : TocStepItem [ ] ; deleteOutdatedStepList ? : TocStepItem [ ] ; } ; const initialState = { isSaving : false , activeArticle : '' , needDeleteOutdatedStepList : [ ] , articleStepList : [ ] , unassignedStepList : [ ] , } ; export const toc = { state : initialState , reducers : { setSaveStatus ( state , isSaving ) { state . isSaving = isSaving ; } , setArticleStepList ( state , payload ) { state . articleStepList = payload ; } , setActiveArticle ( state , payload ) { state . activeArticle = payload ; } , setUnassignedStepList ( state , payload ) { state . unassignedStepList = payload ; } , deleteOutdatedStepList ( state , stepId ) { state . needDeleteOutdatedStepList = state . needDeleteOutdatedStepList . concat ( stepId ) ; if ( state . unassignedStepList ) { const newUnassignedStepList = state . unassignedStepList . filter ( ( step ) => step . id !== stepId ) ; state . unassignedStepList = newUnassignedStepList ; } } , reset ( state ) { state . activeArticle = '' ; state . needDeleteOutdatedStepList = [ ] ; state . articleStepList = [ ] ; state . unassignedStepList = [ ] ; state . isSaving = false ; } , } , effects : ( dispatch ) => ( { async fetchToc ( ) { try { const response = await fetch ( '/api/toc' ) ; const data = await response . json ( ) ; dispatch . toc . setUnassignedStepList ( data . unassignedStepList ) ; dispatch . toc . setArticleStepList ( data . articleStepList ) ; } catch { message . error ( '获取目录失败！' ) ; } } , async save ( _ , rootState ) { const { articleStepList = [ ] , unassignedStepList = [ ] , needDeleteOutdatedStepList = [ ] , } = rootState . toc ; const success = await saveData ( { articleStepList , unassignedStepList , needDeleteOutdatedStepList , } , '/api/toc' ) ; if ( ! success ) { return message . error ( '目录保存失败！' ) ; } const { nowArticleId = '' } = rootState . collection ; const nowArticleIdList = articleStepList . filter ( ( item ) => item . type === 'article' ) . map ( ( item ) => item . id ) ; if ( nowArticleId && ! nowArticleIdList . includes ( nowArticleId ) ) { dispatch . collection . setNowArticle ( '' ) ; } await dispatch . collection . fetchArticles ( ) ; await dispatch . collection . fetchFragment ( ) ; message . success ( '目录保存成功' ) ; } , } ) , } ;