@teleporthq/teleport-project-generator-next 0.44.14 → 0.44.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,192 @@
1
+ import generate from '@babel/generator'
2
+ import { parse } from '@babel/parser'
3
+ import * as types from '@babel/types'
4
+ import {
5
+ GeneratedFolder,
6
+ ProjectUIDL,
7
+ UIDLConditionalNode,
8
+ UIDLElementNode,
9
+ } from '@teleporthq/teleport-types'
10
+ import uidlSample from '../../../../examples/uidl-samples/component-variants.json'
11
+ import template from './template-definition.json'
12
+ import { createNextProjectGenerator } from '../../src'
13
+
14
+ /**
15
+ * A button component with four looks: `btn` always, plus `btn-<look>` while
16
+ * the `buttonType` prop (default "primary") names it, and `btn-full` while the
17
+ * boolean `fullWidth` prop is true. The Next.js export decides at runtime, so
18
+ * the test reads the generated component's `className` and `defaultProps`,
19
+ * then evaluates the class list each placed instance renders with.
20
+ */
21
+ const nodesOfType = <T extends types.Node>(root: types.Node, type: T['type']): T[] => {
22
+ const found: T[] = []
23
+ const visit = (value: unknown) => {
24
+ if (Array.isArray(value)) {
25
+ value.forEach(visit)
26
+ return
27
+ }
28
+ if (!value || typeof value !== 'object' || typeof (value as types.Node).type !== 'string') {
29
+ return
30
+ }
31
+ if ((value as types.Node).type === type) {
32
+ found.push(value as T)
33
+ }
34
+ Object.entries(value).forEach(([key, child]) => {
35
+ if (key !== 'loc' && !key.endsWith('Comments')) {
36
+ visit(child)
37
+ }
38
+ })
39
+ }
40
+ visit(root)
41
+ return found
42
+ }
43
+
44
+ // tslint:disable-next-line function-constructor
45
+ const evaluate = (code: string, props: Record<string, unknown> = {}) =>
46
+ new Function('props', `return (${code})`)(props)
47
+
48
+ const sourceOf = (folder: GeneratedFolder, folderName: string, fileName: string) => {
49
+ const file = folder.subFolders
50
+ .find((subFolder) => subFolder.name === folderName)
51
+ ?.files.find((candidate) => candidate.name === fileName && candidate.fileType === 'js')
52
+ if (!file) {
53
+ throw new Error(`${folderName}/${fileName}.js was not generated`)
54
+ }
55
+ return parse(file.content, { sourceType: 'module', plugins: ['jsx'] })
56
+ }
57
+
58
+ const classesByLabel = async (uidl: ProjectUIDL): Promise<Record<string, string>> => {
59
+ const output = await createNextProjectGenerator().generateProject(uidl, template)
60
+ const component = sourceOf(output, 'components', 'action-button')
61
+ const page = sourceOf(output, 'pages', 'index')
62
+
63
+ const className = nodesOfType<types.JSXAttribute>(component, 'JSXAttribute').find(
64
+ (attribute) => attribute.name.name === 'className'
65
+ )
66
+ const classExpression = generate(
67
+ (className.value as types.JSXExpressionContainer).expression as types.Expression
68
+ ).code
69
+ const defaultProps = nodesOfType<types.AssignmentExpression>(
70
+ component,
71
+ 'AssignmentExpression'
72
+ ).find((assignment) => generate(assignment.left).code === 'ActionButton.defaultProps')
73
+ const defaults = evaluate(generate(defaultProps.right).code)
74
+
75
+ const instances = nodesOfType<types.JSXOpeningElement>(page, 'JSXOpeningElement').filter(
76
+ (element) => generate(element.name).code === 'ActionButton'
77
+ )
78
+ return Object.fromEntries(
79
+ instances.map((instance) => {
80
+ const props: Record<string, unknown> = { ...defaults }
81
+ instance.attributes.forEach((attribute) => {
82
+ if (attribute.type !== 'JSXAttribute') {
83
+ return
84
+ }
85
+ const { value } = attribute
86
+ props[String(attribute.name.name)] =
87
+ value === null
88
+ ? true
89
+ : value.type === 'StringLiteral'
90
+ ? value.value
91
+ : evaluate(generate((value as types.JSXExpressionContainer).expression).code)
92
+ })
93
+ const classes = String(evaluate(classExpression, props)).split(/\s+/).filter(Boolean)
94
+ return [String(props.label), classes.join(' ')]
95
+ })
96
+ )
97
+ }
98
+
99
+ const fixture = () => JSON.parse(JSON.stringify(uidlSample)) as ProjectUIDL
100
+
101
+ const homeOf = (uidl: ProjectUIDL) => {
102
+ const home = (uidl.root.node.content.children[0] as UIDLConditionalNode).content.node
103
+ if (home.type !== 'element') {
104
+ throw new Error('fixture drifted: Home is not an element')
105
+ }
106
+ return home
107
+ }
108
+
109
+ const placeButton = (uidl: ProjectUIDL, key: string, attrs: Record<string, unknown>) =>
110
+ homeOf(uidl).content.children.push({
111
+ type: 'element',
112
+ content: {
113
+ elementType: 'ActionButton',
114
+ semanticType: 'ActionButton',
115
+ key,
116
+ name: key,
117
+ dependency: { type: 'local' },
118
+ attrs: Object.fromEntries(
119
+ Object.entries(attrs).map(([name, content]) => [name, { type: 'static', content }])
120
+ ),
121
+ children: [],
122
+ },
123
+ } as UIDLElementNode)
124
+
125
+ const classWhen = (referenceId: string, propId: string, operands: string[]) => ({
126
+ type: 'style-map' as const,
127
+ content: {
128
+ mapType: 'project-referenced' as const,
129
+ referenceId,
130
+ condition: {
131
+ reference: {
132
+ type: 'dynamic' as const,
133
+ content: { referenceType: 'prop' as const, id: propId },
134
+ },
135
+ expression: { conditions: operands.map((operand) => ({ operation: '===', operand })) },
136
+ },
137
+ },
138
+ })
139
+
140
+ describe('Component variants in the Next.js export', () => {
141
+ it('renders every instance with the base class and exactly its own look', async () => {
142
+ expect(await classesByLabel(fixture())).toEqual({
143
+ Primary: 'btn btn-primary',
144
+ Secondary: 'btn btn-secondary',
145
+ Outline: 'btn btn-outline',
146
+ Link: 'btn btn-link',
147
+ Unset: 'btn btn-primary',
148
+ 'Full width': 'btn btn-outline btn-full',
149
+ 'Not full width': 'btn btn-primary',
150
+ })
151
+ })
152
+
153
+ it('still generates, with the class left off, when a class condition is dangling', async () => {
154
+ const uidl = fixture()
155
+ const button = uidl.components.ActionButton.node.content
156
+ const dangling = (referenceId: string, propId: string, operands: string[]) => ({
157
+ type: 'style-map' as const,
158
+ content: {
159
+ mapType: 'project-referenced' as const,
160
+ referenceId,
161
+ condition: {
162
+ reference: {
163
+ type: 'dynamic' as const,
164
+ content: { referenceType: 'prop' as const, id: propId },
165
+ },
166
+ expression: { conditions: operands.map((operand) => ({ operation: '===', operand })) },
167
+ },
168
+ },
169
+ })
170
+ button.referencedStyles.deletedProp = dangling('btn-link', 'removedProp', ['x'])
171
+ button.referencedStyles.noRule = dangling('btn-full', 'buttonType', [])
172
+
173
+ const classes = await classesByLabel(uidl)
174
+
175
+ expect(classes.Outline).toBe('btn btn-outline')
176
+ expect(classes['Full width']).toBe('btn btn-outline btn-full')
177
+ expect(classes.Unset).toBe('btn btn-primary')
178
+ })
179
+
180
+ it('applies a class on a number prop whose default and rule both store the number as text', async () => {
181
+ const uidl = fixture()
182
+ uidl.root.styleSetDefinitions['btn-size-two'] = uidl.root.styleSetDefinitions['btn-full']
183
+ const actionButton = uidl.components.ActionButton
184
+ actionButton.propDefinitions.size = { type: 'number', defaultValue: '2' }
185
+ actionButton.node.content.referencedStyles.sizeTwo = classWhen('btn-size-two', 'size', ['2'])
186
+ placeButton(uidl, 'sizeThreeButton', { size: 3, label: 'Size three' })
187
+
188
+ const classes = await classesByLabel(uidl)
189
+ expect(classes.Primary).toBe('btn btn-primary btn-size-two')
190
+ expect(classes['Size three']).toBe('btn btn-primary')
191
+ })
192
+ })