Repository: teleporthq/teleport-code-generators
Pull request #343 (2019-08-16 14:51:24)

refactor: small fixes


Patch:
diff --git a/packages/teleport-component-generator-preact/src/index.ts b/packages/teleport-component-generator-preact/src/index.ts
index 7b848b4c..82951754 100644
--- a/packages/teleport-component-generator-preact/src/index.ts
+++ b/packages/teleport-component-generator-preact/src/index.ts
@@ -31,7 +31,7 @@ const stylePlugins = {
 }
 
 export const createPreactComponentGenerator = (
-  variation: string = 'CSS',
+  variation: string = 'CSSModules',
   mapping: Mapping = {}
 ): ComponentGenerator => {
   const generator = createComponentGenerator()
diff --git a/packages/teleport-plugin-angular-base-component/src/utils.ts b/packages/teleport-plugin-angular-base-component/src/utils.ts
index b5b305b3..0daa3ad9 100644
--- a/packages/teleport-plugin-angular-base-component/src/utils.ts
+++ b/packages/teleport-plugin-angular-base-component/src/utils.ts
@@ -45,7 +45,7 @@ export const generateExportAST = (
     )
   )
 
-  const dataDecleration = Object.keys(dataObject).map((dataKey) => {
+  const dataDeclaration = Object.keys(dataObject).map((dataKey) => {
     return t.classProperty(
       t.identifier(dataKey),
       convertValueToLiteral(dataObject[dataKey]),
@@ -57,7 +57,7 @@ export const generateExportAST = (
     return t.classBody([
       ...propDeclaration,
       ...propertyDecleration,
-      ...dataDecleration,
+      ...dataDeclaration,
       constructorAST(),
     ])
   }
diff --git a/packages/teleport-plugin-vue-base-component/src/utils.ts b/packages/teleport-plugin-vue-base-component/src/utils.ts
index f71e1749..bcac9bd3 100644
--- a/packages/teleport-plugin-vue-base-component/src/utils.ts
+++ b/packages/teleport-plugin-vue-base-component/src/utils.ts
@@ -112,7 +112,7 @@ const createVuePropsDefinition = (
 
     let defaultPropValue = null
 
-    if (defaultValue !== 'undefined') {
+    if (defaultValue !== undefined) {
       defaultPropValue =
         type === 'array' || type === 'object'
           ? new ParsedASTNode(t.arrowFunctionExpression([], convertValueToLiteral(defaultValue)))
diff --git a/packages/teleport-shared/src/builders/ast-builders.ts b/packages/teleport-shared/src/builders/ast-builders.ts
index 6ac8f696..63a0a247 100644
--- a/packages/teleport-shared/src/builders/ast-builders.ts
+++ b/packages/teleport-shared/src/builders/ast-builders.ts
@@ -48,13 +48,19 @@ export const createGenericImportStatement = (
     importASTs = [
       t.importDefaultSpecifier(t.identifier(defaultImport.identifierName)),
       ...namedImports.map((imp) =>
-        t.importSpecifier(t.identifier(imp.identifierName), t.identifier(imp.originalName))
+        t.importSpecifier(
+          t.identifier(imp.identifierName),
+          t.identifier(imp.originalName || imp.identifierName)
+        )
       ),
     ]
   } else {
     // No default import, so array order doesn't matter
     importASTs = imports.map((imp) =>
-      t.importSpecifier(t.identifier(imp.identifierName), t.identifier(imp.originalName))
+      t.importSpecifier(
+        t.identifier(imp.identifierName),
+        t.identifier(imp.originalName || imp.identifierName)
+      )
     )
   }
   return t.importDeclaration(importASTs, t.stringLiteral(path))
diff --git a/packages/teleport-shared/src/node-handlers/node-to-jsx/index.ts b/packages/teleport-shared/src/node-handlers/node-to-jsx/index.ts
index 5755cc3f..4e7c1aa7 100644
--- a/packages/teleport-shared/src/node-handlers/node-to-jsx/index.ts
+++ b/packages/teleport-shared/src/node-handlers/node-to-jsx/index.ts
@@ -28,7 +28,7 @@ import {
   addDynamicAttributeToJSXTag,
   renameJSXTag,
 } from '../../utils/ast-jsx-utils'
-import { createJSXTag } from '../../builders/ast-builders'
+import { createJSXTag, createSelfClosingJSXTag } from '../../builders/ast-builders'
 import { camelCaseToDashCase } from '../../utils/string-utils'
 
 const generateJSXSyntax = (
@@ -88,7 +88,7 @@ const generateElementNode = (
 ) => {
   const { dependencies, nodesLookup } = params
   const { elementType, children, key, attrs, dependency, events } = node.content
-  const elementTag = createJSXTag(elementType)
+  const elementTag = children ? createJSXTag(elementType) : createSelfClosingJSXTag(elementType)
 
   if (attrs) {
     Object.keys(attrs).forEach((attrKey) => {
@@ -248,7 +248,7 @@ const generateNativeSlotNode = (
   options?: JSXGenerationOptions,
   t = types
 ) => {
-  const slotNode = createJSXTag('slot')
+  const slotNode = createSelfClosingJSXTag('slot')
 
   if (node.content.name) {
     addAttributeToJSXTag(slotNode, 'name', node.content.name)
diff --git a/packages/teleport-shared/src/node-handlers/node-to-jsx/utils.ts b/packages/teleport-shared/src/node-handlers/node-to-jsx/utils.ts
index 4917e28c..209e16ea 100644
--- a/packages/teleport-shared/src/node-handlers/node-to-jsx/utils.ts
+++ b/packages/teleport-shared/src/node-handlers/node-to-jsx/utils.ts
@@ -159,17 +159,20 @@ export const createConditionIdentifier = (
 ): ConditionalIdentifier => {
   const { id, referenceType } = dynamicReference.content
 
+  // in case the id is a member expression: eg: fields.name
+  const referenceRoot = id.split('.')[0]
+
   switch (referenceType) {
     case 'prop':
       return {
         key: id,
-        type: params.propDefinitions[id].type,
+        type: params.propDefinitions[referenceRoot].type,
         prefix: options.dynamicReferencePrefixMap.prop,
       }
     case 'state':
       return {
         key: id,
-        type: params.stateDefinitions[id].type,
+        type: params.stateDefinitions[referenceRoot].type,
         prefix: options.dynamicReferencePrefixMap.state,
       }
     default:
diff --git a/packages/teleport-shared/src/utils/ast-js-utils.ts b/packages/teleport-shared/src/utils/ast-js-utils.ts
index f68d0288..22d7d4dd 100644
--- a/packages/teleport-shared/src/utils/ast-js-utils.ts
+++ b/packages/teleport-shared/src/utils/ast-js-utils.ts
@@ -60,12 +60,17 @@ type ExpressionLiteral =
   | types.Identifier
   | types.ArrayExpression
   | types.ObjectExpression
+  | types.NullLiteral
 
 export const convertValueToLiteral = (
   value: any,
   explicitType: string = '',
   t = types
 ): ExpressionLiteral => {
+  if (value === undefined || value === null) {
+    return t.nullLiteral()
+  }
+
   if (Array.isArray(value)) {
     return t.arrayExpression(value.map((val) => convertValueToLiteral(val)))
   }
diff --git a/packages/teleport-types/src/generators.ts b/packages/teleport-types/src/generators.ts
index cea34136..bffe1a76 100644
--- a/packages/teleport-types/src/generators.ts
+++ b/packages/teleport-types/src/generators.ts
@@ -87,7 +87,7 @@ export interface HastText {
 }
 
 export interface ImportIdentifier {
-  identifierName?: string
+  identifierName: string
   namedImport?: boolean
   originalName?: string
   importJustPath?: boolean
diff --git a/packages/teleport-uidl-validator/src/validator/utils.ts b/packages/teleport-uidl-validator/src/validator/utils.ts
index 3aa1589a..e172826f 100644
--- a/packages/teleport-uidl-validator/src/validator/utils.ts
+++ b/packages/teleport-uidl-validator/src/validator/utils.ts
@@ -77,7 +77,11 @@ export const checkDynamicDefinitions = (input: any) => {
         const errorMsg = `"${node.content.id}" is used but not defined. Please add it in propDefinitions`
         errors.push(errorMsg)
       }
-      usedPropKeys.push(node.content.id)
+
+      // for member expression we check the root
+      // if value has no `.` it will be checked as it is
+      const dynamicIdRoot = node.content.id.split('.')[0]
+      usedPropKeys.push(dynamicIdRoot)
     }
 
     if (node.type === 'dynamic' && node.content.referenceType === 'state') {
@@ -85,7 +89,11 @@ export const checkDynamicDefinitions = (input: any) => {
         const errorMsg = `\n"${node.content.id}" is used but not defined. Please add it in stateDefinitions`
         errors.push(errorMsg)
       }
-      usedstateKeys.push(node.content.id)
+
+      // for member expression we check the root
+      // if value has no `.` it will be checked as it is
+      const dynamicIdRoot = node.content.id.split('.')[0]
+      usedstateKeys.push(dynamicIdRoot)
     }
   })
 


Test patch:
diff --git a/packages/teleport-shared/__tests__/builders/ast-builders.ts b/packages/teleport-shared/__tests__/builders/ast-builders.ts
index 80ed4b2a..cf5dc024 100644
--- a/packages/teleport-shared/__tests__/builders/ast-builders.ts
+++ b/packages/teleport-shared/__tests__/builders/ast-builders.ts
@@ -40,6 +40,17 @@ describe('createGenericImportStatement', () => {
     expect(result.source).toHaveProperty('value')
     expect(result.source.value).toBe('../testConst')
   })
+  it('should use the identifierName as originalName if no originalName is provided', () => {
+    const imports = [{ identifierName: 'Card', namedImport: true }]
+    const result = createGenericImportStatement('some-package', imports)
+    expect(result.type).toBe('ImportDeclaration')
+    expect(result.specifiers.length).toEqual(imports.length)
+    expect(result.source).toHaveProperty('value')
+    expect(result.source.value).toBe('some-package')
+    const specifier = result.specifiers[0] as types.ImportSpecifier
+    expect(specifier.local.name).toBe('Card')
+    expect(specifier.imported.name).toBe('Card')
+  })
   it('should creat generic import statements if no import array is provided', () => {
     const result = createGenericImportStatement('../testConst', [])
     expect(result.type).toBe('ImportDeclaration')
diff --git a/packages/teleport-shared/__tests__/node-handlers/node-to-jsx/utils.ts b/packages/teleport-shared/__tests__/node-handlers/node-to-jsx/utils.ts
index a84c4715..a0df9232 100644
--- a/packages/teleport-shared/__tests__/node-handlers/node-to-jsx/utils.ts
+++ b/packages/teleport-shared/__tests__/node-handlers/node-to-jsx/utils.ts
@@ -1,4 +1,12 @@
-import { createBinaryExpression } from '../../../src/node-handlers/node-to-jsx/utils'
+import {
+  createBinaryExpression,
+  createConditionIdentifier,
+} from '../../../src/node-handlers/node-to-jsx/utils'
+import { dynamicNode } from '../../../src/builders/uidl-builders'
+import {
+  JSXGenerationParams,
+  JSXGenerationOptions,
+} from '../../../src/node-handlers/node-to-jsx/types'
 
 describe('createBinaryExpression', () => {
   it('varName === true -> varName', () => {
@@ -97,3 +105,64 @@ describe('createBinaryExpression', () => {
     })
   })
 })
+
+describe('createConditionIdentifier', () => {
+  const params: JSXGenerationParams = {
+    propDefinitions: {
+      title: {
+        type: 'string',
+      },
+      fields: {
+        type: 'object',
+      },
+    },
+    stateDefinitions: {
+      isActive: {
+        type: 'boolean',
+        defaultValue: false,
+      },
+    },
+    dependencies: {},
+    nodesLookup: {},
+  }
+
+  const options: JSXGenerationOptions = {
+    dynamicReferencePrefixMap: {
+      prop: 'this.props',
+      state: 'this',
+      local: '',
+    },
+  }
+
+  it('works with a prop reference', () => {
+    const node = dynamicNode('prop', 'title')
+    const result = createConditionIdentifier(node, params, options)
+
+    expect(result.key).toBe('title')
+    expect(result.prefix).toBe('this.props')
+    expect(result.type).toBe('string')
+  })
+
+  it('works on member expressions', () => {
+    const node = dynamicNode('prop', 'fields.title')
+    const result = createConditionIdentifier(node, params, options)
+
+    expect(result.key).toBe('fields.title')
+    expect(result.prefix).toBe('this.props')
+    expect(result.type).toBe('object')
+  })
+
+  it('works with a state reference', () => {
+    const node = dynamicNode('state', 'isActive')
+    const result = createConditionIdentifier(node, params, options)
+
+    expect(result.key).toBe('isActive')
+    expect(result.prefix).toBe('this')
+    expect(result.type).toBe('boolean')
+  })
+
+  it('throws an error for unknown reference type', () => {
+    const node = dynamicNode('local', 'title')
+    expect(() => createConditionIdentifier(node, params, options)).toThrowError()
+  })
+})
diff --git a/packages/teleport-shared/__tests__/utils/ast-utils.ts b/packages/teleport-shared/__tests__/utils/ast-utils.ts
index ffabd970..0c93eee8 100644
--- a/packages/teleport-shared/__tests__/utils/ast-utils.ts
+++ b/packages/teleport-shared/__tests__/utils/ast-utils.ts
@@ -74,6 +74,10 @@ describe('AST Utils ', () => {
       expect(result).toHaveProperty('type')
       expect(result.type).toBe('Identifier')
     })
+    it('returns a null literal for null or undefined', () => {
+      expect(convertValueToLiteral(null).type).toBe('NullLiteral')
+      expect(convertValueToLiteral(undefined).type).toBe('NullLiteral')
+    })
   })
 
   describe('objectToObjectExpression', () => {