2020
2121const MASK_SVG = `url("data:image/svg+xml,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20viewBox%3D'0%200%2024%2024'%20fill%3D'none'%20stroke%3D'black'%20stroke-width%3D'1.75'%3E%3Cpath%20d%3D'M15%203h6v6'%2F%3E%3Cpath%20d%3D'M10%2014%2021%203'%2F%3E%3Cpath%20d%3D'M18%2013v6a2%202%200%200%201-2%202H5a2%202%200%200%201-2-2V8a2%202%200%200%201%202-2h6'%2F%3E%3C%2Fsvg%3E")`
2222const DEFAULT_PLAYGROUND_HTML = '<div id="root"></div>'
23+ const GET_ELEMENT_BY_ID_RE = / d o c u m e n t \. g e t E l e m e n t B y I d \( \s * ( [ ' " ` ] ) ( [ ^ ' " ` ] + ) \1\s * \) /
2324
2425function h ( tag , props , children = [ ] ) {
2526 return {
@@ -78,6 +79,11 @@ function indentBlock(code, spaces) {
7879 . join ( '\n' )
7980}
8081
82+ function inferPlaygroundHtml ( tsx ) {
83+ const mountId = tsx . match ( GET_ELEMENT_BY_ID_RE ) ?. [ 2 ]
84+ return mountId ? `<div id="${ mountId } "></div>` : DEFAULT_PLAYGROUND_HTML
85+ }
86+
8187function wrapTsxForPlayground ( tsx ) {
8288 const code = tsx . trim ( )
8389 if ( ! code ) return code
@@ -92,10 +98,13 @@ function wrapTsxForPlayground(tsx) {
9298 }
9399
94100 const blocks = code . split ( / \n \s * \n / )
95- const jsxBlock = blocks . at ( - 1 ) ?. trim ( )
96- if ( ! jsxBlock || ! looksLikeJsxExpression ( jsxBlock ) ) return code
101+ const jsxIndex = blocks . findIndex ( block => looksLikeJsxExpression ( block . trim ( ) ) )
102+ if ( jsxIndex < 0 ) return code
103+
104+ const jsxBlock = blocks . slice ( jsxIndex ) . join ( '\n\n' ) . trim ( )
105+ if ( ! jsxBlock ) return code
97106
98- const prelude = blocks . slice ( 0 , - 1 ) . join ( '\n\n' ) . trim ( )
107+ const prelude = blocks . slice ( 0 , jsxIndex ) . join ( '\n\n' ) . trim ( )
99108
100109 let wrapped = ''
101110 if ( prelude ) wrapped += `${ prelude } \n\n`
@@ -138,7 +147,7 @@ function addHtmlPlaygroundButton(blockAst, html, js) {
138147}
139148
140149function addTsxButton ( blockAst , tsx ) {
141- insertPlaygroundButton ( blockAst , DEFAULT_PLAYGROUND_HTML , wrapTsxForPlayground ( tsx ) )
150+ insertPlaygroundButton ( blockAst , inferPlaygroundHtml ( tsx ) , wrapTsxForPlayground ( tsx ) )
142151}
143152
144153export function pluginPlaygroundButton ( ) {
0 commit comments