@@ -5,20 +5,30 @@ const markdownItYouTubeEmbed: PluginWithOptions<void> = (md) => {
5
5
const youtubeEmbedRule : RuleCore = ( state ) => {
6
6
const tokens = state . tokens ;
7
7
8
- for ( let i = 0 ; i < tokens . length ; i ++ ) {
8
+ for ( let i = 0 ; i < tokens . length - 2 ; i ++ ) {
9
9
const token = tokens [ i ] ;
10
+ const next = tokens [ i + 1 ] ;
11
+ const nextNext = tokens [ i + 2 ] ;
10
12
13
+ // Look for paragraph_open → inline → paragraph_close
11
14
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 '
16
19
) {
17
- const linkToken = token . children [ 0 ] ;
18
- const href = linkToken . attrGet ( 'href' ) ;
20
+ const firstChild = next . children [ 0 ] ;
19
21
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' ) ! ;
21
30
const videoId = href . split ( 'v=' ) [ 1 ] ;
31
+
22
32
const iframeHtml = `
23
33
<div class="responsive-video">
24
34
<iframe
@@ -27,13 +37,13 @@ const markdownItYouTubeEmbed: PluginWithOptions<void> = (md) => {
27
37
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
28
38
allowfullscreen>
29
39
</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 ;
32
45
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 ) ;
37
47
}
38
48
}
39
49
}
0 commit comments