@figma/code-connect 1.0.6 → 1.1.1

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.
Files changed (167) hide show
  1. package/README.md +48 -541
  2. package/dist/client/figma_client.d.ts +1 -1
  3. package/dist/client/figma_client.js +9 -7
  4. package/dist/client/figma_client.js.map +1 -1
  5. package/dist/commands/connect.d.ts +4 -2
  6. package/dist/commands/connect.d.ts.map +1 -1
  7. package/dist/commands/connect.js +97 -49
  8. package/dist/commands/connect.js.map +1 -1
  9. package/dist/{common → connect}/api.d.ts +6 -87
  10. package/dist/connect/api.d.ts.map +1 -0
  11. package/dist/{common → connect}/api.js.map +1 -1
  12. package/dist/connect/create.d.ts.map +1 -1
  13. package/dist/connect/create.js +4 -0
  14. package/dist/connect/create.js.map +1 -1
  15. package/dist/connect/create_common.d.ts +7 -0
  16. package/dist/connect/create_common.d.ts.map +1 -0
  17. package/dist/connect/create_common.js +19 -0
  18. package/dist/connect/create_common.js.map +1 -0
  19. package/dist/connect/external_types.d.ts +8 -0
  20. package/dist/connect/external_types.d.ts.map +1 -0
  21. package/dist/connect/external_types.js +31 -0
  22. package/dist/connect/external_types.js.map +1 -0
  23. package/dist/connect/figma_connect.d.ts.map +1 -0
  24. package/dist/connect/figma_connect.js.map +1 -0
  25. package/dist/connect/figma_rest_api.d.ts +7 -0
  26. package/dist/connect/figma_rest_api.d.ts.map +1 -1
  27. package/dist/connect/figma_rest_api.js.map +1 -1
  28. package/dist/connect/index_common.d.ts +3 -0
  29. package/dist/connect/index_common.d.ts.map +1 -0
  30. package/dist/connect/index_common.js +23 -0
  31. package/dist/connect/index_common.js.map +1 -0
  32. package/dist/{common → connect}/intrinsics.d.ts +4 -3
  33. package/dist/connect/intrinsics.d.ts.map +1 -0
  34. package/dist/{common → connect}/intrinsics.js +48 -24
  35. package/dist/connect/intrinsics.js.map +1 -0
  36. package/dist/connect/parser_common.d.ts +144 -0
  37. package/dist/connect/parser_common.d.ts.map +1 -0
  38. package/dist/connect/parser_common.js +297 -0
  39. package/dist/connect/parser_common.js.map +1 -0
  40. package/dist/connect/parser_executable_types.d.ts +20 -23
  41. package/dist/connect/parser_executable_types.d.ts.map +1 -1
  42. package/dist/connect/parser_executable_types.js.map +1 -1
  43. package/dist/connect/parser_executables.js +1 -1
  44. package/dist/connect/parser_executables.js.map +1 -1
  45. package/dist/connect/project.d.ts +20 -5
  46. package/dist/connect/project.d.ts.map +1 -1
  47. package/dist/connect/project.js +79 -16
  48. package/dist/connect/project.js.map +1 -1
  49. package/dist/connect/upload.d.ts +1 -1
  50. package/dist/connect/upload.d.ts.map +1 -1
  51. package/dist/connect/validation.d.ts +1 -1
  52. package/dist/connect/validation.d.ts.map +1 -1
  53. package/dist/connect/wizard/helpers.d.ts.map +1 -1
  54. package/dist/connect/wizard/helpers.js +18 -14
  55. package/dist/connect/wizard/helpers.js.map +1 -1
  56. package/dist/connect/wizard/prop_mapping.d.ts +12 -7
  57. package/dist/connect/wizard/prop_mapping.d.ts.map +1 -1
  58. package/dist/connect/wizard/prop_mapping.js +88 -89
  59. package/dist/connect/wizard/prop_mapping.js.map +1 -1
  60. package/dist/connect/wizard/run_wizard.d.ts.map +1 -1
  61. package/dist/connect/wizard/run_wizard.js +8 -3
  62. package/dist/connect/wizard/run_wizard.js.map +1 -1
  63. package/dist/connect/wizard/signature_extraction.d.ts +7 -0
  64. package/dist/connect/wizard/signature_extraction.d.ts.map +1 -0
  65. package/dist/connect/wizard/signature_extraction.js +46 -0
  66. package/dist/connect/wizard/signature_extraction.js.map +1 -0
  67. package/dist/html/__test__/parser/examples/NoConfigObject.figma.d.ts +2 -0
  68. package/dist/html/__test__/parser/examples/NoConfigObject.figma.d.ts.map +1 -0
  69. package/dist/html/__test__/parser/examples/NoConfigObject.figma.js +9 -0
  70. package/dist/html/__test__/parser/examples/NoConfigObject.figma.js.map +1 -0
  71. package/dist/html/__test__/parser/examples/NoExample.figma.d.ts +2 -0
  72. package/dist/html/__test__/parser/examples/NoExample.figma.d.ts.map +1 -0
  73. package/dist/html/__test__/parser/examples/NoExample.figma.js +9 -0
  74. package/dist/html/__test__/parser/examples/NoExample.figma.js.map +1 -0
  75. package/dist/html/__test__/parser/examples/RegularFunctionExampleWithExtraCode.figma.d.ts +2 -0
  76. package/dist/html/__test__/parser/examples/RegularFunctionExampleWithExtraCode.figma.d.ts.map +1 -0
  77. package/dist/html/__test__/parser/examples/RegularFunctionExampleWithExtraCode.figma.js +33 -0
  78. package/dist/html/__test__/parser/examples/RegularFunctionExampleWithExtraCode.figma.js.map +1 -0
  79. package/dist/html/__test__/parser/examples/WrongSignatureJsx.figma.d.ts +2 -0
  80. package/dist/html/__test__/parser/examples/WrongSignatureJsx.figma.d.ts.map +1 -0
  81. package/dist/html/__test__/parser/examples/WrongSignatureJsx.figma.js +15 -0
  82. package/dist/html/__test__/parser/examples/WrongSignatureJsx.figma.js.map +1 -0
  83. package/dist/html/__test__/parser/examples/WrongSignatureNoHtmlTag.figma.d.ts +2 -0
  84. package/dist/html/__test__/parser/examples/WrongSignatureNoHtmlTag.figma.d.ts.map +1 -0
  85. package/dist/html/__test__/parser/examples/WrongSignatureNoHtmlTag.figma.js +15 -0
  86. package/dist/html/__test__/parser/examples/WrongSignatureNoHtmlTag.figma.js.map +1 -0
  87. package/dist/html/__test__/parser/parser.test.d.ts +2 -0
  88. package/dist/html/__test__/parser/parser.test.d.ts.map +1 -0
  89. package/dist/html/__test__/parser/parser.test.js +50 -0
  90. package/dist/html/__test__/parser/parser.test.js.map +1 -0
  91. package/dist/html/create.d.ts +4 -0
  92. package/dist/html/create.d.ts.map +1 -0
  93. package/dist/html/create.js +81 -0
  94. package/dist/html/create.js.map +1 -0
  95. package/dist/html/external.d.ts +8 -0
  96. package/dist/html/external.d.ts.map +1 -0
  97. package/dist/html/external.js +25 -0
  98. package/dist/html/external.js.map +1 -0
  99. package/dist/html/index_html.d.ts +77 -0
  100. package/dist/html/index_html.d.ts.map +1 -0
  101. package/dist/html/index_html.js +42 -0
  102. package/dist/html/index_html.js.map +1 -0
  103. package/dist/html/parser.d.ts +19 -0
  104. package/dist/html/parser.d.ts.map +1 -0
  105. package/dist/html/parser.js +487 -0
  106. package/dist/html/parser.js.map +1 -0
  107. package/dist/html/parser_template_helpers.d.ts +2 -0
  108. package/dist/html/parser_template_helpers.d.ts.map +1 -0
  109. package/dist/html/parser_template_helpers.js +68 -0
  110. package/dist/html/parser_template_helpers.js.map +1 -0
  111. package/dist/html/template_literal.d.ts +5 -0
  112. package/dist/html/template_literal.d.ts.map +1 -0
  113. package/dist/html/template_literal.js +8 -0
  114. package/dist/html/template_literal.js.map +1 -0
  115. package/dist/parser_scripts/get_swift_parser_dir.d.ts +1 -1
  116. package/dist/parser_scripts/get_swift_parser_dir.d.ts.map +1 -1
  117. package/dist/parser_scripts/get_swift_parser_dir.js +38 -10
  118. package/dist/parser_scripts/get_swift_parser_dir.js.map +1 -1
  119. package/dist/react/create.d.ts +5 -0
  120. package/dist/react/create.d.ts.map +1 -1
  121. package/dist/react/create.js +144 -42
  122. package/dist/react/create.js.map +1 -1
  123. package/dist/react/external.d.ts +9 -0
  124. package/dist/react/external.d.ts.map +1 -0
  125. package/dist/{common → react}/external.js +8 -28
  126. package/dist/react/external.js.map +1 -0
  127. package/dist/react/index_react.d.ts +94 -0
  128. package/dist/react/index_react.d.ts.map +1 -0
  129. package/dist/{index.js → react/index_react.js} +5 -19
  130. package/dist/react/index_react.js.map +1 -0
  131. package/dist/react/parser.d.ts +6 -38
  132. package/dist/react/parser.d.ts.map +1 -1
  133. package/dist/react/parser.js +137 -295
  134. package/dist/react/parser.js.map +1 -1
  135. package/dist/react/parser_template_helpers.d.ts +15 -15
  136. package/dist/react/parser_template_helpers.d.ts.map +1 -1
  137. package/dist/react/parser_template_helpers.js +51 -35
  138. package/dist/react/parser_template_helpers.js.map +1 -1
  139. package/dist/storybook/convert.d.ts +1 -1
  140. package/dist/storybook/convert.d.ts.map +1 -1
  141. package/dist/storybook/convert.js +6 -4
  142. package/dist/storybook/convert.js.map +1 -1
  143. package/dist/storybook/external.d.ts +1 -1
  144. package/dist/storybook/external.d.ts.map +1 -1
  145. package/dist/typescript/compiler.d.ts +2 -2
  146. package/dist/typescript/compiler.d.ts.map +1 -1
  147. package/dist/typescript/compiler.js +50 -23
  148. package/dist/typescript/compiler.js.map +1 -1
  149. package/package.json +28 -8
  150. package/dist/common/__test__/project.test.d.ts +0 -2
  151. package/dist/common/__test__/project.test.d.ts.map +0 -1
  152. package/dist/common/__test__/project.test.js +0 -14
  153. package/dist/common/__test__/project.test.js.map +0 -1
  154. package/dist/common/api.d.ts.map +0 -1
  155. package/dist/common/external.d.ts +0 -14
  156. package/dist/common/external.d.ts.map +0 -1
  157. package/dist/common/external.js.map +0 -1
  158. package/dist/common/figma_connect.d.ts.map +0 -1
  159. package/dist/common/figma_connect.js.map +0 -1
  160. package/dist/common/intrinsics.d.ts.map +0 -1
  161. package/dist/common/intrinsics.js.map +0 -1
  162. package/dist/index.d.ts +0 -9
  163. package/dist/index.d.ts.map +0 -1
  164. package/dist/index.js.map +0 -1
  165. /package/dist/{common → connect}/api.js +0 -0
  166. /package/dist/{common → connect}/figma_connect.d.ts +0 -0
  167. /package/dist/{common → connect}/figma_connect.js +0 -0
@@ -0,0 +1,77 @@
1
+ import { EnumValue, FigmaConnectAPI, FigmaConnectMeta, ValueOf } from '../connect/api';
2
+ import { FigmaConnectClient } from '../client/figma_client';
3
+ import { html, HtmlTemplateString } from './template_literal';
4
+ declare const _client: FigmaConnectClient;
5
+ declare const _figma: FigmaConnectAPI<HtmlTemplateString> & {
6
+ /**
7
+ * Defines a code snippet that displays in Figma when a component is selected.
8
+ *
9
+ * @param figmaNodeUrl A link to the node in Figma, for example:`https://www.figma.com/file/123abc/My-Component?node-id=123:456`
10
+ * @param meta {@link FigmaConnectMeta}
11
+ */
12
+ connect<P = {}>(figmaNodeUrl: string, meta: Required<Pick<FigmaConnectMeta<P, HtmlTemplateString>, 'example'>> & FigmaConnectMeta<P, HtmlTemplateString>): void;
13
+ /**
14
+ * Maps a Figma property to a boolean value for the connected component. This prop is replaced
15
+ * with values from the Figma instance when viewed in Dev Mode. For example:
16
+ * ```ts
17
+ * props: {
18
+ * disabled: figma.boolean('Disabled'),
19
+ * }
20
+ * ```
21
+ * Would show the `disabled` property if the Figma property "Disabled" is true.
22
+ *
23
+ * @param figmaPropName The name of the property on the Figma component
24
+ */
25
+ boolean(figmaPropName: string): boolean;
26
+ /**
27
+ * Maps a Figma boolean property to a set of values for the connected
28
+ * component, providing a value mapping for `true` and `false`. This prop is
29
+ * replaced with values from the Figma instance when viewed in Dev Mode.
30
+ * Example:
31
+ * ```ts
32
+ * props: {
33
+ * label: figma.boolean('Disabled', {
34
+ * true: <my-label></my-label>,
35
+ * false: <my-disabled-label></my-disabled-label>,
36
+ * }),
37
+ * }
38
+ * ```
39
+ * Would replace `label` with `<my-label></my-label>` if the Figma property
40
+ * "Disabled" is true.
41
+ *
42
+ * @param figmaPropName The name of the property on the Figma component
43
+ * @param valueMapping A mapping of values for `true` and `false`
44
+ */
45
+ boolean<TrueT extends EnumValue, FalseT extends EnumValue>(figmaPropName: string, valueMapping?: {
46
+ true?: TrueT;
47
+ false?: FalseT;
48
+ }): ValueOf<Record<'true' | 'false', TrueT | FalseT>>;
49
+ /**
50
+ * Maps nested properties from a Figma instance layer. The first argument
51
+ * should be the layer name of the nested instance. The mapping object passed
52
+ * in is in the same format as the `props` object in the `connect` function.
53
+ * For example:
54
+ * ```ts
55
+ * props: {
56
+ * nested: figma.nestedProps('Nested', {
57
+ * label: figma.string('Text'),
58
+ * icon: figma.instance('Icon'),
59
+ * }),
60
+ * }
61
+ * ```
62
+ *
63
+ * Which would then allow you to access the nested properties in the `example` function like so:
64
+ * ```ts
65
+ * (props) => html`<my-button label=${props.nested.label}>${props.nested.icon}</my-button>`
66
+ * ```
67
+ */
68
+ nestedProps<V>(layer: string, input: V): V;
69
+ /**
70
+ * A list of import statements that will render in the Code Snippet in Figma.
71
+ */
72
+ imports?: string[];
73
+ };
74
+ declare const _html: typeof html;
75
+ export { _figma as figma, _client as client, _html as html };
76
+ export default _figma;
77
+ //# sourceMappingURL=index_html.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index_html.d.ts","sourceRoot":"","sources":["../../src/html/index_html.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,gBAAgB,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAA;AAEtF,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAA;AAC3D,OAAO,EAAE,IAAI,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAA;AAG7D,QAAA,MAAM,OAAO,EAAE,kBAAgC,CAAA;AAC/C,QAAA,MAAM,MAAM,EAAE,eAAe,CAAC,kBAAkB,CAAC,GAAG;IAClD;;;;;OAKG;IACH,OAAO,CAAC,CAAC,GAAG,EAAE,EACZ,YAAY,EAAE,MAAM,EACpB,IAAI,EAAE,QAAQ,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC,EAAE,kBAAkB,CAAC,EAAE,SAAS,CAAC,CAAC,GACtE,gBAAgB,CAAC,CAAC,EAAE,kBAAkB,CAAC,GACxC,IAAI,CAAA;IAEP;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAAA;IAEvC;;;;;;;;;;;;;;;;;;OAkBG;IACH,OAAO,CAAC,KAAK,SAAS,SAAS,EAAE,MAAM,SAAS,SAAS,EACvD,aAAa,EAAE,MAAM,EACrB,YAAY,CAAC,EAAE;QACb,IAAI,CAAC,EAAE,KAAK,CAAA;QACZ,KAAK,CAAC,EAAE,MAAM,CAAA;KACf,GACA,OAAO,CAAC,MAAM,CAAC,MAAM,GAAG,OAAO,EAAE,KAAK,GAAG,MAAM,CAAC,CAAC,CAAA;IAEpD;;;;;;;;;;;;;;;;;;OAkBG;IACH,WAAW,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,CAAA;IAE1C;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;CACX,CAAA;AACT,QAAA,MAAM,KAAK,aAAO,CAAA;AAElB,OAAO,EAAE,MAAM,IAAI,KAAK,EAAE,OAAO,IAAI,MAAM,EAAE,KAAK,IAAI,IAAI,EAAE,CAAA;AAC5D,eAAe,MAAM,CAAA"}
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ // IMPORTANT: be careful to ensure you don't accidentally add code which has a
3
+ // dependency on Node.js-only modules here, as it will break co-located
4
+ // components. We don't have a test for this yet. Any such code should be
5
+ // conditionally required - see `client` for an example. Reach out in
6
+ // #feat-code-connect if you're unsure.
7
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
+ if (k2 === undefined) k2 = k;
9
+ var desc = Object.getOwnPropertyDescriptor(m, k);
10
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
+ desc = { enumerable: true, get: function() { return m[k]; } };
12
+ }
13
+ Object.defineProperty(o, k2, desc);
14
+ }) : (function(o, m, k, k2) {
15
+ if (k2 === undefined) k2 = k;
16
+ o[k2] = m[k];
17
+ }));
18
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
19
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
20
+ }) : function(o, v) {
21
+ o["default"] = v;
22
+ });
23
+ var __importStar = (this && this.__importStar) || function (mod) {
24
+ if (mod && mod.__esModule) return mod;
25
+ var result = {};
26
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
27
+ __setModuleDefault(result, mod);
28
+ return result;
29
+ };
30
+ Object.defineProperty(exports, "__esModule", { value: true });
31
+ exports.html = exports.client = exports.figma = void 0;
32
+ const figma = __importStar(require("./external"));
33
+ const template_literal_1 = require("./template_literal");
34
+ const index_common_1 = require("../connect/index_common");
35
+ const _client = (0, index_common_1.getClient)();
36
+ exports.client = _client;
37
+ const _figma = figma;
38
+ exports.figma = _figma;
39
+ const _html = template_literal_1.html;
40
+ exports.html = _html;
41
+ exports.default = _figma;
42
+ //# sourceMappingURL=index_html.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index_html.js","sourceRoot":"","sources":["../../src/html/index_html.ts"],"names":[],"mappings":";AAAA,8EAA8E;AAC9E,uEAAuE;AACvE,yEAAyE;AACzE,qEAAqE;AACrE,uCAAuC;;;;;;;;;;;;;;;;;;;;;;;;;;AAGvC,kDAAmC;AAEnC,yDAA6D;AAC7D,0DAAmD;AAEnD,MAAM,OAAO,GAAuB,IAAA,wBAAS,GAAE,CAAA;AAmFV,yBAAM;AAlF3C,MAAM,MAAM,GA+ER,KAAK,CAAA;AAGU,uBAAK;AAFxB,MAAM,KAAK,GAAG,uBAAI,CAAA;AAEoC,qBAAI;AAC1D,kBAAe,MAAM,CAAA"}
@@ -0,0 +1,19 @@
1
+ import ts from 'typescript';
2
+ import { PropMappings } from '../connect/intrinsics';
3
+ import { CodeConnectJSON } from '../connect/figma_connect';
4
+ import { ParserContext, ParseOptions } from '../connect/parser_common';
5
+ /**
6
+ * Parses the example template string passed to `figma.connect()`.
7
+ *
8
+ * @param exp A function or arrow function expression
9
+ * @param parserContext Parser context
10
+ * @param propMappings Prop mappings object as returned by parseProps
11
+ *
12
+ * @returns The code of the render function and a list of imports
13
+ */
14
+ export declare function parseExampleTemplate(exp: ts.ArrowFunction, parserContext: ParserContext, propMappings?: PropMappings): {
15
+ code: string;
16
+ nestable: boolean;
17
+ };
18
+ export declare function parseHtmlDoc(node: ts.CallExpression, parserContext: ParserContext, { repoUrl, silent }: ParseOptions): Promise<CodeConnectJSON>;
19
+ //# sourceMappingURL=parser.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parser.d.ts","sourceRoot":"","sources":["../../src/html/parser.ts"],"names":[],"mappings":"AAAA,OAAO,EAAwC,MAAM,YAAY,CAAA;AAOjE,OAAO,EAAsB,YAAY,EAAoB,MAAM,uBAAuB,CAAA;AAC1F,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAA;AAI1D,OAAO,EAEL,aAAa,EAOb,YAAY,EACb,MAAM,0BAA0B,CAAA;AAyKjC;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAClC,GAAG,EAAE,EAAE,CAAC,aAAa,EACrB,aAAa,EAAE,aAAa,EAC5B,YAAY,CAAC,EAAE,YAAY;;;EA4L5B;AAiID,wBAAsB,YAAY,CAChC,IAAI,EAAE,EAAE,CAAC,cAAc,EACvB,aAAa,EAAE,aAAa,EAC5B,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE,YAAY,GAChC,OAAO,CAAC,eAAe,CAAC,CA6D1B"}
@@ -0,0 +1,487 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.parseHtmlDoc = exports.parseExampleTemplate = void 0;
27
+ const typescript_1 = __importStar(require("typescript"));
28
+ const compiler_1 = require("../typescript/compiler");
29
+ const intrinsics_1 = require("../connect/intrinsics");
30
+ const parser_template_helpers_1 = require("./parser_template_helpers");
31
+ const jsdom_1 = require("jsdom");
32
+ const parse5_1 = require("parse5");
33
+ const parser_common_1 = require("../connect/parser_common");
34
+ const prettier_1 = require("prettier");
35
+ function getHtmlTaggedTemplateNode(node) {
36
+ if (typescript_1.default.isTaggedTemplateExpression(node)) {
37
+ const tag = node.tag;
38
+ if (typescript_1.default.isIdentifier(tag) && tag.text === 'html') {
39
+ return node;
40
+ }
41
+ }
42
+ else if (typescript_1.default.isBlock(node) &&
43
+ node.statements.length === 1 &&
44
+ typescript_1.default.isReturnStatement(node.statements[0]) &&
45
+ node.statements[0].expression &&
46
+ typescript_1.default.isTaggedTemplateExpression(node.statements[0].expression) &&
47
+ typescript_1.default.isIdentifier(node.statements[0].expression.tag) &&
48
+ node.statements[0].expression.tag.text === 'html') {
49
+ return node.statements[0].expression;
50
+ }
51
+ return undefined;
52
+ }
53
+ /**
54
+ * This function converts the HTML template literal into a DOM (using JSDOM) to
55
+ * extract information which is used in generating the template:
56
+ * 1. A dictionary of template placeholders which correspond to HTML attribute
57
+ * values. The key is the placeholder index, and the value is the attribute
58
+ * name. We use this to render attribute placeholders appropriately (either
59
+ * in quotes for strings, or as either the attribute name or nothing for
60
+ * booleans).
61
+ * 2. Whether the template is "nestable" or not. A template is considered
62
+ * nestable if it has only one top level element.
63
+ *
64
+ * For finding the attribute placeholders, the algorithm is as follows:
65
+ * 1. Build up a full string from the template literal, replacing any value
66
+ * ${placeholders} with `__FIGMA_PLACEHOLDER_0`, where 0 is the placeholder
67
+ * index. This results in a valid HTML string, with placeholders we can later
68
+ * detect.
69
+ * 2. Use JSDOM to turn this into a DOM.
70
+ * 3. Iterate over every node in the DOM, and if the node has any attributes
71
+ * starting `__FIGMA_PLACEHOLDER`, store the info of these attributes.
72
+ * This allows us to know which template literal placeholders correspond to
73
+ * HTML attributes when we construct the template.
74
+ */
75
+ function getInfoFromDom(templateExp, parserContext) {
76
+ let htmlString;
77
+ if (typescript_1.default.isTemplateExpression(templateExp)) {
78
+ // If this is a template expression, build up the HTML string with
79
+ // identifiable placeholders as described above
80
+ htmlString = templateExp.head.text;
81
+ templateExp.templateSpans.forEach((part, index) => {
82
+ htmlString += `__FIGMA_PLACEHOLDER_${index}` + part.literal.text;
83
+ });
84
+ }
85
+ else if (templateExp.template.kind === typescript_1.default.SyntaxKind.FirstTemplateToken) {
86
+ // This is just a template literal with no placeholders
87
+ htmlString = templateExp.template.text;
88
+ }
89
+ else {
90
+ // This should never happen as we check the type in the calling function
91
+ throw new Error(`Unsupported template type: ${typescript_1.SyntaxKind[templateExp.template.kind]}`);
92
+ }
93
+ // First, check for HTML which we cannot handle. JSDOM is quite forgiving,
94
+ // like a browser, but we need to be stricter
95
+ //
96
+ // Duplicate attribute names are handled gracefully by JSDOM (it just keeps
97
+ // one of the attributes), but this breaks our algorithm because some of the
98
+ // placeholders are no longer in the DOM. JSDOM has no way to detect this, but
99
+ // parse5 (which is a library JSDOM uses under the hood) can detect this. We
100
+ // just thrown an error in this case as there's no use case for doing this.
101
+ (0, parse5_1.parse)(htmlString, {
102
+ onParseError: (error) => {
103
+ if (error.code === 'duplicate-attribute') {
104
+ throw new parser_common_1.ParserError(`Duplicate attribute name in example HTML`, {
105
+ node: templateExp,
106
+ sourceFile: parserContext.sourceFile,
107
+ });
108
+ }
109
+ },
110
+ });
111
+ // Try to format the HTML with prettier, to catch any errors due to invalid
112
+ // HTML which would otherwise result in broken formatting in the UI as
113
+ // prettier is less forgiving
114
+ try {
115
+ // pluginSearchDirs: false is needed as otherwise prettier picks up other
116
+ // prettier plugins in our monorepo and fails on CI
117
+ (0, prettier_1.format)(htmlString, { parser: 'html', pluginSearchDirs: false });
118
+ }
119
+ catch (e) {
120
+ throw new parser_common_1.ParserError(`Error parsing example HTML. Check the HTML is valid.`, {
121
+ node: templateExp,
122
+ sourceFile: parserContext.sourceFile,
123
+ });
124
+ }
125
+ // Create a DOM with JSDOM.
126
+ //
127
+ // JSDOM doesn't work properly in all cases if we parse a DOM without a full
128
+ // document, e.g. Vue templates - when traversing with NodeIterator, it
129
+ // doesn't find all elements. We create a Fragment then append it to a full
130
+ // DOM to work around this. The extra wrapping elements don't matter, as we're
131
+ // only interested in the attributes.
132
+ const fragment = jsdom_1.JSDOM.fragment(htmlString);
133
+ const dom = new jsdom_1.JSDOM('<!DOCTYPE html><html><body></body></html>');
134
+ dom.window.document.body.appendChild(fragment);
135
+ const document = dom.window.document;
136
+ const NodeFilter = dom.window.NodeFilter;
137
+ const attributePlaceholders = {};
138
+ function iterateNodeIterator(nodeIterator) {
139
+ let currentNode;
140
+ while ((currentNode = nodeIterator.nextNode())) {
141
+ // I couldn't work out how to do this in a way which satisfies TypeScript,
142
+ // so using a check and a cast
143
+ if (currentNode.nodeType === dom.window.Node.ELEMENT_NODE) {
144
+ // Check for any attributes which correspond to placeholders in the
145
+ // template literal, and store their index and name
146
+ for (let attr of currentNode.attributes) {
147
+ if (attr.value.startsWith('__FIGMA_PLACEHOLDER_')) {
148
+ attributePlaceholders[parseInt(attr.value.split('__FIGMA_PLACEHOLDER_')[1])] = attr.name;
149
+ }
150
+ }
151
+ }
152
+ // <TEMPLATE> nodes are not iterated over by default, as they are a way to
153
+ // store a fragment which is not rendered immediately. These are used in
154
+ // e.g. Vue templates, so we need to iterate over them explicitly.
155
+ if (currentNode.nodeName === 'TEMPLATE') {
156
+ const templateContent = currentNode.content;
157
+ const templateNodeIterator = document.createNodeIterator(templateContent, NodeFilter.SHOW_ELEMENT, null);
158
+ iterateNodeIterator(templateNodeIterator);
159
+ }
160
+ }
161
+ }
162
+ // Iterate over all the nodes in the DOM
163
+ const nodeIterator = document.createNodeIterator(document.body, NodeFilter.SHOW_ELEMENT, null);
164
+ iterateNodeIterator(nodeIterator);
165
+ // We check if there is more than one top level child, as we use this as a
166
+ // signal that the template is not "nestable" (and so we render an instance
167
+ // pill rather than render the child's code inline in the UI)
168
+ const topLevelChildrenCount = document.body.children.length;
169
+ return {
170
+ attributePlaceholders,
171
+ nestable: topLevelChildrenCount === 1,
172
+ };
173
+ }
174
+ function escapeTemplateString(code) {
175
+ return code.replace(/`/g, '\\`').replace(/\$\{/g, '\\${');
176
+ }
177
+ /**
178
+ * Parses the example template string passed to `figma.connect()`.
179
+ *
180
+ * @param exp A function or arrow function expression
181
+ * @param parserContext Parser context
182
+ * @param propMappings Prop mappings object as returned by parseProps
183
+ *
184
+ * @returns The code of the render function and a list of imports
185
+ */
186
+ function parseExampleTemplate(exp, parserContext, propMappings) {
187
+ const { sourceFile } = parserContext;
188
+ if (exp.parameters.length > 1) {
189
+ throw new parser_common_1.ParserError(`Expected a single props parameter for the render function, got ${exp.parameters.length} parameters`, { sourceFile, node: exp });
190
+ }
191
+ const propsParameter = exp.parameters[0];
192
+ if (!exp.body) {
193
+ throw new parser_common_1.ParserError(`Expected a body for the render function`, { sourceFile, node: exp });
194
+ }
195
+ const templateNode = getHtmlTaggedTemplateNode(exp.body);
196
+ if (!templateNode) {
197
+ throw new parser_common_1.ParserError(`Expected only a tagged template literal as the body of the render function`, { sourceFile, node: templateNode });
198
+ }
199
+ // Keep track of any props which are referenced in the example so that we can
200
+ // insert the appropriate `figma.properties` call in the JS template
201
+ const referencedProps = new Set();
202
+ let exampleCode = '';
203
+ let nestable = true;
204
+ if ((0, typescript_1.isTemplateExpression)(templateNode.template)) {
205
+ // This is a template expression with placeholders
206
+ const createPropPlaceholder = (0, parser_common_1.makeCreatePropPlaceholder)({
207
+ propMappings,
208
+ referencedProps,
209
+ sourceFile,
210
+ });
211
+ // Transform the template to replace any props references with placeholder
212
+ // function calls, normalising the different types of props references
213
+ const transformedTemplate = typescript_1.default.transform(templateNode.template, [
214
+ (context) => (rootNode) => {
215
+ function visit(node) {
216
+ if (typescript_1.default.isTemplateSpan(node)) {
217
+ const visitResult = (0, parser_common_1.visitPropReferencingNode)({
218
+ propsParameter,
219
+ node: node.expression,
220
+ createPropPlaceholder,
221
+ useJsx: false,
222
+ });
223
+ if (visitResult) {
224
+ return typescript_1.default.factory.createTemplateSpan(visitResult, node.literal);
225
+ }
226
+ }
227
+ return typescript_1.default.visitEachChild(node, visit, context);
228
+ }
229
+ return typescript_1.default.visitNode(rootNode, visit);
230
+ },
231
+ ]).transformed[0];
232
+ // Iterate over the template string spans (i.e. the interleaved strings and
233
+ // placeholders) to build up our example code.
234
+ //
235
+ // Each time we encounter a placeholder (which by this point has been
236
+ // normalised to a __PROP__ placeholder function call), we check if it
237
+ // corresponds to a HTML attribute based on our previous DOM analysis (see
238
+ // getInfoFromDom).
239
+ //
240
+ // If it does, we replace it with a call to
241
+ // `_fcc_renderHtmlAttribute("attributeName", propVariableName), otherwise
242
+ // we replace it with a call to `_fcc_renderHtmlValue(propVariableName)`.
243
+ //
244
+ // We have some additional logic to handle cases where the user accidentally
245
+ // writes `attribute="${props.prop}"` rather than `attribute=${props.prop}`
246
+ // (which is what we show in the docs), as it's easy to make this mistake
247
+ // when copy/pasting.
248
+ // Keep track of whether we're inside an attribute value that is wrapped in quotes,
249
+ // so that we can strip the trailing quote if we are
250
+ let insideAttributeWithQuotes = false;
251
+ const infoFromDom = getInfoFromDom(transformedTemplate, parserContext);
252
+ const { attributePlaceholders } = infoFromDom;
253
+ nestable = infoFromDom.nestable;
254
+ // Handle a chunk of HTML, i.e. a text section of the template string. If
255
+ // the next placeholder is an attribute and this chunk ends with a HTML
256
+ // attribute (i.e. matches a regex like ` text=` or ` text="`), we remove the
257
+ // attribute name so that it's not present in the low level template before the
258
+ // call to _fcc_renderHtmlAttribute.
259
+ function handleHtmlChunk(html, nextPlaceholderIsAttribute) {
260
+ // If we were previously inside an attribute value placeholder with quotes
261
+ // surrounding it, remove the leading quote. We do it like this rather
262
+ // than always removing the leading quote to avoid situations where we
263
+ // mistakenly remove a quote that is part of the actual content.
264
+ if (insideAttributeWithQuotes) {
265
+ html = html.replace(/^"/g, '');
266
+ }
267
+ // If the next placeholder is an attribute, then match the start of the
268
+ // attribute (`attribute=`) at the end of this chunk, so that we can
269
+ // remove it from the example code
270
+ const attributeMatches = html.match(/(.*\s)([^\s]+)="?$/s);
271
+ if (nextPlaceholderIsAttribute && attributeMatches) {
272
+ // attributeMatches should always have matched here, but we check it
273
+ // anyway so we can fail gracefully if not
274
+ // Add the code up to the attribute, not including the ` attribute=`
275
+ // part, as _fcc_renderHtmlAttribute is responsible for (maybe)
276
+ // rendering that
277
+ exampleCode += escapeTemplateString(attributeMatches[1]);
278
+ // If we are in this block, we know that we've matched an attribute, so
279
+ // store whether it ends with a quote
280
+ insideAttributeWithQuotes = html.endsWith('"');
281
+ }
282
+ else {
283
+ // No attribute to remove, just add the code
284
+ exampleCode += escapeTemplateString(html);
285
+ insideAttributeWithQuotes = false;
286
+ }
287
+ }
288
+ // Process the first chunk, which is a special case as it is not in templateSpans
289
+ handleHtmlChunk(transformedTemplate.head.text, attributePlaceholders[0] !== undefined);
290
+ // For each section of the template string, check that the expression is a
291
+ // prop placeholder, then add the appropriate template function call
292
+ transformedTemplate.templateSpans.forEach((part, index) => {
293
+ if (!typescript_1.default.isCallExpression(part.expression)) {
294
+ throw new parser_common_1.ParserError(`Expected an call expression as a placeholder in the template, got ${typescript_1.SyntaxKind[part.expression.kind]}`, { sourceFile, node: part.expression });
295
+ }
296
+ const propNameArg = part.expression.arguments[0];
297
+ if (!typescript_1.default.isStringLiteral(propNameArg)) {
298
+ throw new parser_common_1.ParserError(`Expected a string literal as the argument to the placeholder call, got ${typescript_1.SyntaxKind[propNameArg.kind]}`, { sourceFile, node: propNameArg });
299
+ }
300
+ const propVariableName = propNameArg.text;
301
+ referencedProps.add(propVariableName);
302
+ if (attributePlaceholders[index]) {
303
+ exampleCode += `\${_fcc_renderHtmlAttribute('${attributePlaceholders[index]}', ${propVariableName})}`;
304
+ }
305
+ else {
306
+ exampleCode += `\${_fcc_renderHtmlValue(${propVariableName})}`;
307
+ }
308
+ // Process the next chunk
309
+ handleHtmlChunk(part.literal.text, attributePlaceholders[index + 1] !== undefined);
310
+ });
311
+ }
312
+ else if (templateNode.template.kind === typescript_1.default.SyntaxKind.FirstTemplateToken) {
313
+ // Template string with no placeholders
314
+ nestable = getInfoFromDom(templateNode, parserContext).nestable;
315
+ exampleCode = escapeTemplateString(templateNode.template.text);
316
+ }
317
+ else {
318
+ throw new parser_common_1.ParserError(`Expected a template expression as the body of the render function, got ${typescript_1.SyntaxKind[templateNode.template.kind]}`, { sourceFile, node: templateNode.template });
319
+ }
320
+ let templateCode = (0, parser_template_helpers_1.getParsedTemplateHelpersString)() + '\n\n';
321
+ templateCode += `const figma = require('figma')\n\n`;
322
+ templateCode += (0, parser_common_1.getReferencedPropsForTemplate)({
323
+ propMappings,
324
+ referencedProps,
325
+ exp,
326
+ sourceFile,
327
+ });
328
+ templateCode += `export default figma.html\`${exampleCode}\`\n`;
329
+ return {
330
+ code: templateCode,
331
+ nestable,
332
+ };
333
+ }
334
+ exports.parseExampleTemplate = parseExampleTemplate;
335
+ function parseFigmaConnectArgs(node, parserContext) {
336
+ const required = true;
337
+ const figmaNodeUrlArg = (0, compiler_1.parseFunctionArgument)(node, parserContext, 0, typescript_1.default.isStringLiteral, required, `\`${intrinsics_1.FIGMA_CONNECT_CALL}\` must be called with a Figma Component URL as the first argument. Example usage:
338
+ \`${intrinsics_1.FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {
339
+ example: () => html\`<button />\`
340
+ })\``);
341
+ const configObjArg = (0, compiler_1.parseFunctionArgument)(node, parserContext, 1, typescript_1.default.isObjectLiteralExpression, true, `The second argument to ${intrinsics_1.FIGMA_CONNECT_CALL}() must be an object literal. Example usage:
342
+ \`${intrinsics_1.FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {
343
+ example: () => html\`<button />\`
344
+ })\``);
345
+ return {
346
+ figmaNodeUrlArg,
347
+ configObjArg,
348
+ };
349
+ }
350
+ function parseConfigObjectArg(configArg, parserContext) {
351
+ if (!configArg) {
352
+ return {
353
+ propsArg: undefined,
354
+ exampleArg: undefined,
355
+ variantArg: undefined,
356
+ importsArg: undefined,
357
+ linksArg: undefined,
358
+ };
359
+ }
360
+ const propsArg = (0, compiler_1.parsePropertyOfType)({
361
+ objectLiteralNode: configArg,
362
+ propertyName: 'props',
363
+ predicate: typescript_1.default.isObjectLiteralExpression,
364
+ parserContext,
365
+ required: false,
366
+ errorMessage: `The 'props' property must be an object literal. Example usage:
367
+ \`${intrinsics_1.FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {
368
+ props: {
369
+ disabled: figma.boolean('Disabled'),
370
+ text: figma.string('TextContent'),
371
+ },
372
+ example: (props) => html\`<my-button disabled=\${props.disabled} label=\${props.text} />\`
373
+ })\``,
374
+ });
375
+ const exampleArg = (0, compiler_1.parsePropertyOfType)({
376
+ objectLiteralNode: configArg,
377
+ propertyName: 'example',
378
+ predicate: typescript_1.default.isArrowFunction,
379
+ parserContext,
380
+ required: true,
381
+ errorMessage: `The 'example' property must be an arrow function which returns a html tagged template string. Example usage:
382
+ \`${intrinsics_1.FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {
383
+ example: (props) => html\`<my-button />\`
384
+ })\``,
385
+ });
386
+ const variantArg = (0, compiler_1.parsePropertyOfType)({
387
+ objectLiteralNode: configArg,
388
+ propertyName: 'variant',
389
+ predicate: typescript_1.default.isObjectLiteralExpression,
390
+ parserContext,
391
+ required: false,
392
+ errorMessage: `The 'variant' property must be an object literal. Example usage:
393
+ \`${intrinsics_1.FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {
394
+ variant: {
395
+ "Has Icon": true
396
+ },
397
+ example: (props) => html\`<my-button />\`
398
+ })\``,
399
+ });
400
+ const linksArg = (0, compiler_1.parsePropertyOfType)({
401
+ objectLiteralNode: configArg,
402
+ propertyName: 'links',
403
+ predicate: typescript_1.default.isArrayLiteralExpression,
404
+ parserContext,
405
+ required: false,
406
+ errorMessage: `The 'links' property must be an array literal. Example usage:
407
+ \`${intrinsics_1.FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {
408
+ links: [
409
+ { name: 'Storybook', url: 'https://storybook.com' }
410
+ ],
411
+ example: (props) => html\`<my-button />\`
412
+ })\``,
413
+ });
414
+ const importsArg = (0, compiler_1.parsePropertyOfType)({
415
+ objectLiteralNode: configArg,
416
+ propertyName: 'imports',
417
+ predicate: typescript_1.default.isArrayLiteralExpression,
418
+ parserContext,
419
+ required: false,
420
+ errorMessage: `The 'imports' property must be an array literal. Example usage:
421
+ \`${intrinsics_1.FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {
422
+ imports: ['import { Button } from "./Button"']
423
+ example: (props) => html\`<my-button />\`,
424
+ })\``,
425
+ });
426
+ return {
427
+ propsArg,
428
+ exampleArg,
429
+ variantArg,
430
+ linksArg,
431
+ importsArg,
432
+ };
433
+ }
434
+ async function parseHtmlDoc(node, parserContext, { repoUrl, silent }) {
435
+ const { checker, sourceFile, config } = parserContext;
436
+ // Parse the arguments to the `Figma.connect()` call
437
+ const { figmaNodeUrlArg, configObjArg } = parseFigmaConnectArgs(node, parserContext);
438
+ const { propsArg, exampleArg, variantArg, linksArg, importsArg } = parseConfigObjectArg(configObjArg, parserContext);
439
+ let figmaNode = (0, compiler_1.stripQuotesFromNode)(figmaNodeUrlArg);
440
+ // TODO This logic is duplicated in connect.ts transformDocFromParser due to some type issues
441
+ if (config.documentUrlSubstitutions) {
442
+ Object.entries(config.documentUrlSubstitutions).forEach(([from, to]) => {
443
+ // @ts-expect-error
444
+ figmaNode = figmaNode.replace(from, to);
445
+ });
446
+ }
447
+ const metadata = undefined;
448
+ const props = propsArg ? (0, intrinsics_1.parsePropsObject)(propsArg, parserContext) : undefined;
449
+ const render = exampleArg ? parseExampleTemplate(exampleArg, parserContext, props) : undefined;
450
+ const variant = variantArg ? (0, parser_common_1.parseVariant)(variantArg, sourceFile, checker) : undefined;
451
+ const links = linksArg ? (0, parser_common_1.parseLinks)(linksArg, parserContext) : undefined;
452
+ let imports = importsArg ? (0, parser_common_1.parseImports)(importsArg, parserContext) : undefined;
453
+ let template;
454
+ if (render?.code) {
455
+ template = render.code;
456
+ }
457
+ else {
458
+ throw new parser_common_1.ParserError(`${intrinsics_1.FIGMA_CONNECT_CALL}() requires an example function`, {
459
+ sourceFile,
460
+ node,
461
+ });
462
+ }
463
+ return {
464
+ figmaNode,
465
+ label: 'Web Components',
466
+ language: 'html',
467
+ component: metadata?.component,
468
+ source: '',
469
+ sourceLocation: { line: -1 },
470
+ variant,
471
+ template,
472
+ templateData: {
473
+ // TODO: `props` here is currently only used for validation purposes,
474
+ // we should eventually remove it from the JSON payload
475
+ props,
476
+ imports,
477
+ // If there's no render function, the default example is always nestable
478
+ nestable: render ? render.nestable : true,
479
+ },
480
+ links,
481
+ metadata: {
482
+ cliVersion: require('../../package.json').version,
483
+ },
484
+ };
485
+ }
486
+ exports.parseHtmlDoc = parseHtmlDoc;
487
+ //# sourceMappingURL=parser.js.map