@@ -28,6 +28,8 @@ export interface MarkdownDataChild extends Node {
2828 lang : string ;
2929 meta : string ;
3030 value : string ;
31+ depth ?: number ;
32+ children ?: Array < MarkdownDataChild > ;
3133}
3234
3335export interface MarkdownParseData extends Parent < MarkdownDataChild > { }
@@ -125,3 +127,75 @@ export const mdCodeModulesLoader = (
125127 } ) ;
126128 return config ;
127129} ;
130+
131+ export interface HeadingListType {
132+ depth : number ;
133+ value : string ;
134+ }
135+
136+ export interface HeadingItem extends HeadingListType {
137+ /**嵌套子标题*/
138+ children ?: HeadingItem [ ] ;
139+ }
140+
141+ /**进行获取同级别标题数据*/
142+ export const getSameLevelHeading = ( list : HeadingListType [ ] ) => {
143+ const newList : { start : number ; end : number } [ ] = [ ] ;
144+ let level : number = 0 ;
145+ let satrtIndex = 0 ;
146+ let lg = list . length ;
147+
148+ // 对同级别数据进行区分
149+ for ( let index = 0 ; index < lg ; index ++ ) {
150+ const element = list [ index ] ;
151+ if ( index === 0 ) {
152+ satrtIndex = 0 ;
153+ /**默认第一个数据的层级进行查找*/
154+ level = element . depth ;
155+ } else if ( element . depth === level ) {
156+ // 层级相同则进行赋值
157+ // 这个位置相等,说明这些数据是一组数据
158+ newList . push ( { start : satrtIndex , end : index } ) ;
159+ /**重新赋值开始下标数据*/
160+ satrtIndex = index ;
161+ }
162+ }
163+ // 如果最后位置没找到
164+ if ( satrtIndex <= lg - 1 ) {
165+ newList . push ( { start : satrtIndex , end : lg } ) ;
166+ }
167+
168+ const saveList : HeadingItem [ ] = [ ] ;
169+
170+ /**对标题数据进行处理*/
171+ newList . forEach ( ( item ) => {
172+ const { start, end } = item ;
173+ const [ firstItem , ...lastItems ] = list . slice ( start , end ) ;
174+ const newItem : HeadingItem = { ...firstItem } ;
175+ if ( Array . isArray ( lastItems ) && lastItems . length ) {
176+ newItem . children = getSameLevelHeading ( lastItems ) ;
177+ }
178+ saveList . push ( newItem ) ;
179+ } ) ;
180+
181+ return saveList ;
182+ } ;
183+
184+ /**获取标题*/
185+ export const getHeadings = ( child : MarkdownParseData [ 'children' ] ) => {
186+ const headingList : HeadingListType [ ] = [ ] ;
187+
188+ child . forEach ( ( item ) => {
189+ if ( item && item . type === 'heading' ) {
190+ const { depth, children } = item ;
191+ if ( Array . isArray ( children ) && children . length && depth ) {
192+ const [ firstItem ] = children || [ ] ;
193+ if ( firstItem && firstItem ?. value ) {
194+ headingList . push ( { depth, value : firstItem ?. value } ) ;
195+ }
196+ }
197+ }
198+ } ) ;
199+
200+ return getSameLevelHeading ( headingList ) ;
201+ } ;
0 commit comments