1
1
/* eslint-disable jsx-a11y/alt-text */
2
2
/* eslint-disable @next/next/no-img-element */
3
3
import { type ReactNode } from "react" ;
4
- import slugify from "slugify" ;
5
- import { extractTextFromNode , incrementID } from "./util/heading-id" ;
4
+ import GithubSlugger from 'github-slugger'
5
+ import { extractTextFromNode } from "./util/heading-id" ;
6
6
7
7
/**
8
8
* TODOs
@@ -221,18 +221,13 @@ export type RichTextProps<
221
221
> ;
222
222
} ;
223
223
224
- type GeneratedIDsRecord = Record <
225
- number , // level
226
- Array < string >
227
- > ;
228
-
229
224
export const RichText = <
230
225
CustomBlocks extends CustomBlocksBase = readonly any [ ] ,
231
226
> (
232
227
props : RichTextProps < CustomBlocks >
233
228
) : ReactNode => {
234
229
const value = props . children as Node [ ] | undefined ;
235
- const generatedIDs : GeneratedIDsRecord = [ ] ;
230
+ const slugger = new GithubSlugger ( )
236
231
237
232
return (
238
233
< >
@@ -244,7 +239,7 @@ export const RichText = <
244
239
components = { props . components }
245
240
blocks = { props . blocks }
246
241
level = { 0 }
247
- generatedIDs = { generatedIDs }
242
+ slugger = { slugger }
248
243
/>
249
244
) ;
250
245
} ) }
@@ -337,14 +332,14 @@ const Node = ({
337
332
blocks,
338
333
parent,
339
334
level,
340
- generatedIDs ,
335
+ slugger ,
341
336
} : {
342
337
node : Node ;
343
338
components ?: Partial < Handlers > ;
344
339
blocks ?: readonly CustomBlockBase [ ] ;
345
340
parent ?: Node ;
346
341
level : number ;
347
- generatedIDs : GeneratedIDsRecord ;
342
+ slugger : GithubSlugger ;
348
343
} ) => {
349
344
const children = node . content ?. map ( ( childNode , index ) => {
350
345
return (
@@ -355,7 +350,7 @@ const Node = ({
355
350
components = { components }
356
351
blocks = { blocks }
357
352
level = { level + 1 }
358
- generatedIDs = { generatedIDs }
353
+ slugger = { slugger }
359
354
/>
360
355
) ;
361
356
} ) ;
@@ -415,32 +410,7 @@ const Node = ({
415
410
case "heading" :
416
411
const handlerTag = `h${ node . attrs . level } ` as keyof Handlers ;
417
412
handler = components ?. [ handlerTag ] ?? defaultHandlers [ handlerTag ] ;
418
-
419
- // initialize the array for this level
420
- generatedIDs [ level ] = generatedIDs [ level ] ?? [ ] ;
421
-
422
- function getUniqueID ( id : string ) : string {
423
- // make sure there are no collisions
424
- if ( id ) {
425
- if ( generatedIDs [ level ] ?. includes ( id ) ) {
426
- return getUniqueID ( incrementID ( id ) ) ;
427
- }
428
- }
429
-
430
- return id ;
431
- }
432
-
433
- const id = getUniqueID (
434
- slugify ( extractTextFromNode ( node ) , {
435
- strict : true ,
436
- lower : true ,
437
- trim : true ,
438
- } )
439
- ) ;
440
-
441
- if ( id ) {
442
- generatedIDs [ level ] ?. push ( id ) ;
443
- }
413
+ const id = slugger . slug ( extractTextFromNode ( node ) )
444
414
445
415
props = { children, id } satisfies ExtractPropsForHandler < Handlers [ "h1" ] > ;
446
416
break ;
0 commit comments