import flatten from 'lodash/flatten' ; import nodeToString from 'hast-util-to-string' ; import { formatter } from './utils/format' ; import { componentName , sanitizeCode , removeTags } from './utils/jsx' ; import { getImportsVariables } from './utils/imports' ; import { getExportsVariables } from './utils/exports' ; const isPlayground = ( name ) => { return name === 'Playground' ; } ; const addComponentsProps = ( scopes ) => ( node , idx ) => { const name = componentName ( node . value ) ; const tagOpen = new RegExp ( `^\\<${ name }` ) ; const formatted = formatter ( nodeToString ( node ) ) ; const code = formatted . slice ( 1 , Infinity ) ; const scope = `{props, ${ scopes . join ( ',' ) }}` ; const child = sanitizeCode ( removeTags ( code ) ) ; const newTag = `<${ name } __position={${ idx }} code={'${ child }'} scope={${ scope }}` ; node . value = node . value . replace ( tagOpen , newTag ) ; } ; export interface PluginOpts { root : string ; } export const playgroundRegex = /<Playground\b/ ; export const injectCodeToPlayground = ( ) => ( tree , file ) => { if ( file . contents . search ( playgroundRegex ) == - 1 ) { return tree ; } const playgroundComponents = tree . children . filter ( ( node ) => node . type === 'jsx' ) . filter ( ( node ) => { const name = componentName ( node . value ) ; return isPlayground ( name ) ; } ) ; const importNodes = tree . children . filter ( ( n ) => n . type === 'import' ) ; const exportNodes = tree . children . filter ( ( n ) => n . type === 'export' ) ; const importedScopes = flatten < string > ( importNodes . map ( getImportsVariables ) ) ; const exportedScopes = flatten < string > ( exportNodes . map ( getExportsVariables ) ) ; const scopes = [ ... importedScopes , ... exportedScopes ] . filter ( Boolean ) ; playgroundComponents . forEach ( addComponentsProps ( scopes ) ) ; return tree ; } ;