@@ -5,20 +5,30 @@ const markdownItYouTubeEmbed: PluginWithOptions<void> = (md) => {
55 const youtubeEmbedRule : RuleCore = ( state ) => {
66 const tokens = state . tokens ;
77
8- for ( let i = 0 ; i < tokens . length ; i ++ ) {
8+ for ( let i = 0 ; i < tokens . length - 2 ; i ++ ) {
99 const token = tokens [ i ] ;
10+ const next = tokens [ i + 1 ] ;
11+ const nextNext = tokens [ i + 2 ] ;
1012
13+ // Look for paragraph_open → inline → paragraph_close
1114 if (
12- token . type === 'inline ' &&
13- token . children &&
14- token . children . length >= 1 &&
15- token . children [ 0 ] . type === 'link_open '
15+ token . type === 'paragraph_open ' &&
16+ next . type === 'inline' &&
17+ next . children &&
18+ nextNext . type === 'paragraph_close '
1619 ) {
17- const linkToken = token . children [ 0 ] ;
18- const href = linkToken . attrGet ( 'href' ) ;
20+ const firstChild = next . children [ 0 ] ;
1921
20- if ( href && href . startsWith ( 'https://www.youtube.com/watch?v=' ) ) {
22+ if (
23+ firstChild &&
24+ firstChild . type === 'link_open' &&
25+ firstChild
26+ . attrGet ( 'href' )
27+ ?. startsWith ( 'https://www.youtube.com/watch?v=' )
28+ ) {
29+ const href = firstChild . attrGet ( 'href' ) ! ;
2130 const videoId = href . split ( 'v=' ) [ 1 ] ;
31+
2232 const iframeHtml = `
2333 <div class="responsive-video">
2434 <iframe
@@ -27,13 +37,13 @@ const markdownItYouTubeEmbed: PluginWithOptions<void> = (md) => {
2737 allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
2838 allowfullscreen>
2939 </iframe>
30- </div>
31- ` ;
40+ </div>` . trim ( ) ;
41+
42+ // Replace the 3 tokens (paragraph_open, inline, paragraph_close)
43+ const htmlToken = new state . Token ( 'html_block' , '' , 0 ) ;
44+ htmlToken . content = iframeHtml ;
3245
33- // Replace current token with a new HTML block token
34- const newToken = new state . Token ( 'html_block' , '' , 0 ) ;
35- newToken . content = iframeHtml ;
36- tokens [ i ] = newToken ;
46+ tokens . splice ( i , 3 , htmlToken ) ;
3747 }
3848 }
3949 }
0 commit comments