import * as dom from "./dom" ; const SELECTOR_LIST = "ol, ul" ; const SELECTOR_LINK = "> a, p > a" ; const SELECTOR_PART = "h2, h3, h4" ; param { cheerio . Node } return { cheerio . Node } function findList ( $parent ) { const $container = $parent . children ( ".olist" ) ; if ( $container . length > 0 ) $parent = $container . first ( ) ; return $parent . children ( SELECTOR_LIST ) ; } param { cheerio . Node } param { cheerio . DOM } return { Array } function parseList ( $ul , $ ) { const articles = [ ] ; $ul . children ( "li" ) . each ( function ( ) { const article = { } ; const $li = $ ( this ) ; const $p = $li . children ( "p" ) ; article . title = ( $p . text ( ) || dom . textNode ( $li . get ( 0 ) ) ) . trim ( ) ; const $a = $li . find ( SELECTOR_LINK ) ; if ( $a . length > 0 ) { article . title = $a . first ( ) . text ( ) ; article . ref = $a . attr ( "href" ) . replace ( /\\/g , "/" ) . replace ( /^\/+/ , "" ) ; } const $sub = findList ( $li ) ; article . articles = parseList ( $sub , $ ) ; if ( ! article . title ) return ; articles . push ( article ) ; } ) ; return articles ; } param { cheerio . Node } param { cheerio . DOM } return { Array < { title : String , list : cheerio . Node } > } function findParts ( $parent , $ ) { const partsAndLists = $parent . children ( `${ SELECTOR_LIST }, ${ SELECTOR_PART }` ) ; const parts = [ ] ; let previousPart = null ; partsAndLists . each ( ( i , el ) => { if ( isPartNode ( el ) ) { if ( previousPart !== null ) { parts . push ( previousPart ) ; } previousPart = { title : getPartTitle ( el , $ ) , list : null , } ; } else { if ( previousPart !== null ) { previousPart . list = el ; } else { previousPart = { title : "" , list : el , } ; } parts . push ( previousPart ) ; previousPart = null ; } } ) ; if ( previousPart !== null ) { parts . push ( previousPart ) ; } return parts ; } param el return { boolean } function isPartNode ( el ) { return SELECTOR_PART . indexOf ( el . name ) !== - 1 ; } param el param { cheerio . DOM } $ return { string } function getPartTitle ( el , $ ) { return $ ( el ) . text ( ) . trim ( ) ; } param { string } html return { Object } function parseSummary ( html ) { const $ = dom . parse ( html ) ; const $root = dom . cleanup ( dom . root ( $ ) , $ ) ; const parts = findParts ( $root , $ ) ; const parsedParts = [ ] ; let part ; for ( let i = 0 ; i < parts . length ; ++ i ) { part = parts [ i ] ; parsedParts . push ( { title : part . title , articles : parseList ( $ ( part . list ) , $ ) , } ) ; } return { parts : parsedParts , } ; } export default parseSummary ;