@ui5/webcomponents-tools 0.0.0-9c26e8e4f → 0.0.0-9ed6f23c6

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 (34) hide show
  1. package/CHANGELOG.md +348 -0
  2. package/components-package/eslint.js +34 -0
  3. package/components-package/nps.js +54 -23
  4. package/components-package/postcss.components.js +13 -13
  5. package/components-package/postcss.themes.js +39 -15
  6. package/components-package/vite.config.js +6 -5
  7. package/components-package/wdio.js +400 -386
  8. package/components-package/wdio.sync.js +9 -1
  9. package/icons-collection/nps.js +8 -5
  10. package/lib/copy-list/index.js +2 -2
  11. package/lib/create-icons/index.js +52 -10
  12. package/lib/create-new-component/index.js +71 -104
  13. package/lib/create-new-component/jsFileContentTemplate.js +73 -0
  14. package/lib/create-new-component/tsFileContentTemplate.js +80 -0
  15. package/lib/dev-server/virtual-index-html-plugin.js +2 -2
  16. package/lib/esm-abs-to-rel/index.js +1 -1
  17. package/lib/generate-custom-elements-manifest/index.js +327 -0
  18. package/lib/generate-js-imports/illustrations.js +72 -0
  19. package/lib/hbs2lit/src/compiler.js +16 -5
  20. package/lib/hbs2lit/src/litVisitor2.js +85 -22
  21. package/lib/hbs2lit/src/svgProcessor.js +12 -5
  22. package/lib/hbs2ui5/RenderTemplates/LitRenderer.js +32 -4
  23. package/lib/hbs2ui5/index.js +21 -4
  24. package/lib/i18n/defaults.js +18 -2
  25. package/lib/i18n/toJSON.js +1 -1
  26. package/lib/jsdoc/configTypescript.json +29 -0
  27. package/lib/jsdoc/plugin.js +32 -0
  28. package/lib/jsdoc/preprocess.js +146 -0
  29. package/lib/jsdoc/template/publish.js +9 -1
  30. package/lib/postcss-css-to-esm/index.js +40 -7
  31. package/lib/replace-global-core/index.js +1 -1
  32. package/lib/scoping/get-all-tags.js +1 -8
  33. package/lib/test-runner/test-runner.js +10 -2
  34. package/package.json +14 -5
@@ -0,0 +1,327 @@
1
+ const fs = require("fs").promises;
2
+ const path = require("path");
3
+ // https://github.com/webcomponents/custom-elements-manifest/blob/main/schema.json
4
+
5
+ const inputDir = process.argv[2];
6
+ const outputDir = process.argv[3];
7
+
8
+ const camelToKebabMap = new Map();
9
+ const apiIndex = new Map();
10
+ const forbiddenAttributeTypes = ["object", "array"];
11
+
12
+ const camelToKebabCase = string => {
13
+ if (!camelToKebabMap.has(string)) {
14
+ const result = string.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
15
+ camelToKebabMap.set(string, result);
16
+ }
17
+ return camelToKebabMap.get(string);
18
+ };
19
+
20
+ const generateJavaScriptExport = entity => {
21
+ return {
22
+ declaration: generateRefenrece(entity.name),
23
+ deprecated: !!entity.deprecated,
24
+ kind: "js",
25
+ name: "default",
26
+ };
27
+ };
28
+
29
+ const generateCustomElementExport = entity => {
30
+ return {
31
+ declaration: {
32
+ name: entity.basename,
33
+ module: `${entity.module}.js`,
34
+ },
35
+ deprecated: !!entity.deprecated,
36
+ kind: "custom-element-definition",
37
+ name: entity.tagname,
38
+ };
39
+ };
40
+
41
+ const generateJavaScriptModule = entity => {
42
+ return {
43
+ kind: "javascript-module",
44
+ path: `${entity.basename}.js`,
45
+ declarations: [
46
+ generateCustomElementDeclaration(entity),
47
+ ],
48
+ exports: [
49
+ generateJavaScriptExport(entity),
50
+ generateCustomElementExport(entity),
51
+ ],
52
+ };
53
+ };
54
+
55
+ const generateSingleClassField = classField => {
56
+ let generatedClassField = {
57
+ deprecated: !!classField.deprecated,
58
+ kind: "field",
59
+ name: classField.name,
60
+ privacy: classField.visibility,
61
+ static: !!classField.static,
62
+ type: generateType(classField.type),
63
+ };
64
+
65
+ if (classField.defaultValue) {
66
+ generatedClassField.default = classField.defaultValue;
67
+ }
68
+
69
+ if (classField.description) {
70
+ generatedClassField.description = classField.description;
71
+ }
72
+
73
+ return generatedClassField;
74
+ };
75
+
76
+ const generateSingleParameter = parameter => {
77
+ let generatedParameter = {
78
+ deprecated: !!parameter.deprecated,
79
+ name: parameter.name,
80
+ type: generateType(parameter.type),
81
+ };
82
+
83
+ if (parameter.description) {
84
+ generatedParameter.description = parameter.description;
85
+ }
86
+
87
+ if (parameter.optional) {
88
+ generatedParameter.optional = parameter.optional;
89
+ }
90
+
91
+ return generatedParameter;
92
+ };
93
+
94
+ const generateParameters = (parameters) => {
95
+ return parameters.reduce((newParametersArray, parameter) => {
96
+ newParametersArray.push(generateSingleParameter(parameter));
97
+
98
+ return newParametersArray;
99
+ }, []);
100
+ };
101
+
102
+ const generateSingleClassMethod = classMethod => {
103
+ let generatedClassMethod = {
104
+ deprecated: !!classMethod.deprecated,
105
+ kind: "method",
106
+ name: classMethod.name,
107
+ privacy: classMethod.visibility,
108
+ static: classMethod.static,
109
+ };
110
+
111
+ if (classMethod.description) {
112
+ generatedClassMethod.description = classMethod.description;
113
+ }
114
+
115
+ if (classMethod.parameters && classMethod.parameters.length) {
116
+ generatedClassMethod.parameters = generateParameters(classMethod.parameters);
117
+ }
118
+
119
+ if (classMethod.returnValue) {
120
+ generatedClassMethod.return = {
121
+ type: generateType(classMethod.returnValue.type),
122
+ };
123
+
124
+ if (classMethod.returnValue.description) {
125
+ generatedClassMethod.return.description = classMethod.returnValue.type;
126
+ }
127
+ }
128
+
129
+ return generatedClassMethod;
130
+ };
131
+
132
+ const generateClassFields = classFields => {
133
+ return classFields.reduce((newClassFieldsArray, classField) => {
134
+ newClassFieldsArray.push(generateSingleClassField(classField));
135
+
136
+ return newClassFieldsArray;
137
+ }, []);
138
+ };
139
+
140
+ const generateClassMethods = classMethods => {
141
+ return classMethods.reduce((newClassMethodsArray, classMethod) => {
142
+ newClassMethodsArray.push(generateSingleClassMethod(classMethod));
143
+
144
+ return newClassMethodsArray;
145
+ }, []);
146
+ };
147
+
148
+ const generateMembers = (classFields, classMethods) => {
149
+ return [...generateClassFields(classFields), ...generateClassMethods(classMethods)];
150
+ };
151
+
152
+ const generateType = type => {
153
+ const dataType = apiIndex.get(type);
154
+
155
+ return {
156
+ text: dataType && dataType.name.includes(".types.") ?
157
+ filterPublicApi(dataType.properties)
158
+ .map(prop => `"${prop.name}"`)
159
+ .join(" | ") : type,
160
+ };
161
+ };
162
+
163
+ const generateSingleAttribute = attribute => {
164
+ let generatedAttribute = {
165
+ default: attribute.defaultValue,
166
+ deprecated: !!attribute.deprecated,
167
+ fieldName: attribute.name,
168
+ name: camelToKebabCase(attribute.name),
169
+ type: generateType(attribute.type),
170
+ };
171
+
172
+ if (attribute.description) {
173
+ generatedAttribute.description = attribute.description;
174
+ }
175
+
176
+ return generatedAttribute;
177
+ };
178
+
179
+ const generateAttributes = attributes => {
180
+ attributes = attributes.reduce((newAttributesArray, attribute) => {
181
+ newAttributesArray.push(generateSingleAttribute(attribute));
182
+
183
+ return newAttributesArray;
184
+ }, []);
185
+
186
+ return attributes;
187
+ };
188
+
189
+ const generateSingleEvent = event => {
190
+ let generatedEvent = {
191
+ deprecated: !!event.deprecated,
192
+ name: event.name,
193
+ type: event.native === "true" ? "NativeEvent" : "CustomEvent",
194
+ };
195
+
196
+ if (event.description) {
197
+ generatedEvent.description = event.description;
198
+ }
199
+
200
+ return generatedEvent;
201
+ };
202
+
203
+ const generateEvents = events => {
204
+ events = events.reduce((newEventsArray, event) => {
205
+ newEventsArray.push(generateSingleEvent(event));
206
+
207
+ return newEventsArray;
208
+ }, []);
209
+
210
+ return events;
211
+ };
212
+
213
+ const generateSingleSlot = slot => {
214
+ return {
215
+ deprecated: !!slot.deprecated,
216
+ description: slot.description,
217
+ name: slot.name,
218
+ };
219
+ };
220
+
221
+ const generateSlots = slots => {
222
+ slots = slots.reduce((newSlotsArray, event) => {
223
+ newSlotsArray.push(generateSingleSlot(event));
224
+
225
+ return newSlotsArray;
226
+ }, []);
227
+
228
+ return slots;
229
+ };
230
+
231
+ const generateCustomElementDeclaration = entity => {
232
+ let generatedCustomElementDeclaration = {
233
+ deprecated: !!entity.deprecated,
234
+ customElement: true,
235
+ kind: entity.basename,
236
+ name: entity.basename,
237
+ tagName: entity.tagname,
238
+ };
239
+
240
+ const slots = filterPublicApi(entity.slots);
241
+ const events = filterPublicApi(entity.events);
242
+ const classFields = filterPublicApi(entity.properties);
243
+ const classMethods = filterPublicApi(entity.methods);
244
+ const attributes = classFields.filter(property => {
245
+ return property.noattribute !== "true" && property.readonly !== "true" && !forbiddenAttributeTypes.includes(property.type.toLowerCase());
246
+ });
247
+
248
+ if (slots.length) {
249
+ generatedCustomElementDeclaration.slots = generateSlots(slots);
250
+ }
251
+
252
+ if (events.length) {
253
+ generatedCustomElementDeclaration.events = generateEvents(events);
254
+ }
255
+
256
+ if (attributes.length) {
257
+ generatedCustomElementDeclaration.attributes = generateAttributes(attributes);
258
+ }
259
+
260
+ if (entity.description) {
261
+ generatedCustomElementDeclaration.description = entity.description;
262
+ }
263
+
264
+ if (classFields.length || classMethods.length) {
265
+ generatedCustomElementDeclaration.members = generateMembers(classFields, classMethods);
266
+ }
267
+
268
+ if (entity.extends && entity.extends !== "HTMLElement") {
269
+ generatedCustomElementDeclaration.superclass = generateRefenrece(entity.extends);
270
+ }
271
+
272
+ return generatedCustomElementDeclaration;
273
+ };
274
+
275
+ const generateRefenrece = (entityName) => {
276
+ let packageName;
277
+ let basename;
278
+
279
+ if (!entityName) {
280
+ throw new Error("JSDoc error: entity not found in api.json.");
281
+ }
282
+
283
+ if (entityName.includes(".")) {
284
+ basename = entityName.split(".").pop();
285
+ } else {
286
+ basename = entityName
287
+ }
288
+
289
+ if (entityName.includes("sap.ui.webc.main")) {
290
+ packageName = "@ui5/webcomponents";
291
+ } else if (entityName.includes("sap.ui.webc.fiori")) {
292
+ packageName = "@ui5/webcomponents-fiori";
293
+ } else if (entityName.includes("sap.ui.webc.base")) {
294
+ packageName = "@ui5/webcomponents-base";
295
+ }
296
+
297
+ return {
298
+ module: `${basename}.js`,
299
+ name: `${basename}`,
300
+ package: packageName,
301
+ };
302
+ };
303
+
304
+ const filterPublicApi = array => {
305
+ return (array || []).filter(el => el.visibility === "public");
306
+ };
307
+
308
+ const generate = async () => {
309
+ const file = JSON.parse(await fs.readFile(path.join(inputDir, "api.json")));
310
+ let customElementsManifest = {
311
+ schemaVersion: "1.0.0",
312
+ readme: "",
313
+ modules: [],
314
+ };
315
+
316
+ file.symbols.forEach(entity => {
317
+ if (entity.tagname) {
318
+ customElementsManifest.modules.push(generateJavaScriptModule(entity));
319
+ }
320
+ });
321
+
322
+ await fs.writeFile(path.join(outputDir, "custom-elements.json"), JSON.stringify(customElementsManifest));
323
+ };
324
+
325
+ generate().then(() => {
326
+ console.log("Custom elements manifest generated.");
327
+ });
@@ -0,0 +1,72 @@
1
+ const fs = require("fs").promises;
2
+ const path = require('path');
3
+
4
+ const generate = async () => {
5
+ const fioriInputFolder = path.normalize(process.argv[2]);
6
+ const tntInputFolder = path.normalize(process.argv[3]);
7
+ const outputFile = path.normalize(`${process.argv[4]}/Illustrations.js`);
8
+
9
+ const dir = await fs.readdir(fioriInputFolder);
10
+ const fioriIllustrationsOnFileSystem = dir.map(illustrationName => {
11
+ const fioriMatches = illustrationName.match(/.*\.js$/);
12
+ return fioriMatches ? illustrationName : undefined;
13
+ }).filter(key => !!key);
14
+
15
+ const tntDir = await fs.readdir(tntInputFolder);
16
+ const tntIllustrationsOnFileSystem = tntDir.map(illustrationName => {
17
+ const tntMatches = illustrationName.match(/.*\.js$/);
18
+ return tntMatches ? illustrationName : undefined;
19
+ }).filter(key => !!key);
20
+
21
+ // dynamic imports for Fiori illustrations
22
+ const fioriAvailableIllustrationsArray = `[${fioriIllustrationsOnFileSystem.filter(
23
+ // skipping the items starting with sapIllus-Dialog, sapIllus-Scene, sapIllus-Spot since they are included in the illustration's js file
24
+ line => !line.startsWith("sapIllus-Dialog") && !line.startsWith("sapIllus-Scene") && !line.startsWith("sapIllus-Spot") && !line.startsWith("AllIllustrations")).map(illustrationName => `"${illustrationName.replace('.js', '')}"`).join(", ")}]`;
25
+
26
+ const fioriDynamicImportLines = fioriIllustrationsOnFileSystem.map(illustrationName =>
27
+ `\t\tcase "${illustrationName.replace('.js', '')}": return (await import("../../illustrations/${illustrationName}")).default;`).filter(
28
+ // skipping the items starting with sapIllus-Dialog, sapIllus-Scene, sapIllus-Spot since they are included in the illustration's js file
29
+ line => !line.startsWith("\t\tcase \"sapIllus-Dialog") && !line.startsWith("\t\tcase \"sapIllus-Scene") && !line.startsWith("\t\tcase \"sapIllus-Spot") && !line.startsWith("\t\tcase \"AllIllustrations")).join("\n");
30
+
31
+ // dynamic imports for Tnt illustrations
32
+ const tntAvailableIllustrationsArray = `[${tntIllustrationsOnFileSystem.filter(
33
+ // skipping the items starting with tnt-Dialog, tnt-Scene, tnt-Spot since they are included in the illustration's js file
34
+ line => !line.startsWith("tnt-Dialog") && !line.startsWith("tnt-Scene") && !line.startsWith("tnt-Spot")).map(illustrationName => `"Tnt${illustrationName.replace('.js', '')}"`).join(", ")}]`;
35
+
36
+ const tntDynamicImportLines = tntIllustrationsOnFileSystem.map(illustrationName =>
37
+ `\t\tcase "Tnt${illustrationName.replace('.js', '')}": return (await import("../../illustrations/tnt/${illustrationName}")).default;`).filter(
38
+ // skipping the items starting with tnt-Dialog, tnt-Scene, tnt-Spot since they are included in the illustration's js file
39
+ line => !line.startsWith("\t\tcase \"Tnttnt-Dialog") && !line.startsWith("\t\tcase \"Tnttnt-Scene") && !line.startsWith("\t\tcase \"Tnttnt-Spot")).join("\n");
40
+
41
+
42
+ // dynamic imports file content
43
+ const contentDynamic = `import { registerIllustrationLoader } from "@ui5/webcomponents-base/dist/asset-registries/Illustrations.js";
44
+
45
+ const loadIllustration = async (illustrationName) => {
46
+ switch (illustrationName) {
47
+ ${fioriDynamicImportLines}
48
+ ${tntDynamicImportLines}
49
+ default: throw new Error("[Illustrations] Illustration not found: " + illustrationName);
50
+ }
51
+ };
52
+ const loadAndCheck = async (illustrationName) => {
53
+ const data = await loadIllustration(illustrationName);
54
+ return data;
55
+ }
56
+
57
+
58
+ ${fioriAvailableIllustrationsArray}.forEach(illustrationName => registerIllustrationLoader(illustrationName, loadAndCheck));
59
+ ${tntAvailableIllustrationsArray}.forEach(illustrationName => registerIllustrationLoader(illustrationName, loadAndCheck));`;
60
+
61
+
62
+ await fs.mkdir(path.dirname(outputFile), { recursive: true });
63
+ return Promise.all([fs.writeFile(outputFile, contentDynamic)]);
64
+ };
65
+
66
+ generate().then(() => {
67
+ console.log("Generated Illustrations.js");
68
+ })
69
+ .catch(err => {
70
+ console.error(err);
71
+ process.exit(1);
72
+ });
@@ -12,15 +12,25 @@ const removeWhiteSpaces = (source) => {
12
12
  .replace(/}}\s+{{/g, "}}{{"); // Remove whitespace between }} and {{
13
13
  };
14
14
 
15
- const hbs2lit = async (file) => {
15
+ const hbs2lit = async (file, componentName) => {
16
16
  let sPreprocessed = await includesReplacer.replace(file);
17
17
 
18
18
  sPreprocessed = removeWhiteSpaces(sPreprocessed);
19
19
 
20
+ const blockSignature = process.env.UI5_TS ? `this: ${componentName}` : ""
21
+
22
+ // icons hack
23
+ if (sPreprocessed.startsWith("<g ") || sPreprocessed.startsWith("<g>")) {
24
+ return `
25
+ function block0 (${blockSignature}) {
26
+ return svg\`${sPreprocessed}\`
27
+ }`;
28
+ }
29
+
20
30
  const ast = Handlebars.parse(sPreprocessed);
21
31
 
22
32
  const pv = new PartialsVisitor();
23
- const lv = new HTMLLitVisitor();
33
+ const lv = new HTMLLitVisitor(componentName);
24
34
 
25
35
  let result = "";
26
36
 
@@ -33,10 +43,11 @@ const hbs2lit = async (file) => {
33
43
  let block = lv.blocks[key];
34
44
 
35
45
  if (block.match(/scopeTag/)) {
36
- const matches = block.match(/^(.*?)( => )(.*?);$/);
37
- const scopedCode = matches[3];
46
+ // const matches = block.match(/^(.*?)( => )(.*?);$/);
47
+ const matches = block.match(/^(function .*? \{ return )(.*?);\}$/);
48
+ const scopedCode = matches[2];
38
49
  const normalCode = scopedCode.replace(/\${scopeTag\("/g, "").replace(/", tags, suffix\)}/g, "");
39
- block = `${matches[1]}${matches[2]}suffix ? ${scopedCode} : ${normalCode};`;
50
+ block = `${matches[1]}suffix ? ${scopedCode} : ${normalCode};}`;
40
51
  }
41
52
 
42
53
  result += block + "\n";
@@ -28,14 +28,18 @@ if (!String.prototype.replaceAll) {
28
28
  };
29
29
  }
30
30
 
31
- function HTMLLitVisitor(debug) {
31
+ function HTMLLitVisitor(componentName, debug) {
32
32
  this.blockCounter = 0;
33
33
  this.keys = [];
34
34
  this.blocks = {};
35
35
  this.result = "";
36
36
  this.mainBlock = "";
37
- this.blockPath = "context";
38
- this.blockParameters = ["context", "tags", "suffix"];
37
+ this.blockLevel = 0;
38
+ this.componentName = componentName
39
+ const blockParametersDefinitionTS = [`this: ${componentName}`, "context: UI5Element", "tags: string[]", "suffix: string | undefined"];
40
+ const blockParametersDefinitionJS = ["context", "tags", "suffix"];
41
+ this.blockParametersDefinition = process.env.UI5_TS ? blockParametersDefinitionTS : blockParametersDefinitionJS;
42
+ this.blockParametersUsage = ["this", "context", "tags", "suffix"];
39
43
  this.paths = []; //contains all normalized relative paths
40
44
  this.debug = debug;
41
45
  if (this.debug) {
@@ -51,18 +55,18 @@ HTMLLitVisitor.prototype.Program = function(program) {
51
55
  this.keys.push(key);
52
56
  this.debug && this.blockByNumber.push(key);
53
57
 
54
- this.blocks[this.currentKey()] = "const " + this.currentKey() + " = (" + this.blockParameters.join(", ") + ") => ";
58
+ // this.blocks[this.currentKey()] = "function " + this.currentKey() + ` (this: any, ` + this.blockParametersDefinition.join(", ") + ") { ";
59
+ this.blocks[this.currentKey()] = `function ${this.currentKey()} (${this.blockParametersDefinition.join(", ")}) { `;
55
60
 
56
61
  if (this.keys.length > 1) { //it's a nested block
57
- this.blocks[this.prevKey()] += this.currentKey() + "(" + this.blockParameters.join(", ") + ")";
62
+ this.blocks[this.prevKey()] += this.currentKey() + ".call(" + this.blockParametersUsage.join(", ") + ")";
58
63
  } else {
59
64
  this.mainBlock = this.currentKey();
60
- this.paths.push(this.blockPath);
61
65
  }
62
66
 
63
- this.blocks[this.currentKey()] += "html`";
67
+ this.blocks[this.currentKey()] += "return html`";
64
68
  Visitor.prototype.Program.call(this, program);
65
- this.blocks[this.currentKey()] += "`;";
69
+ this.blocks[this.currentKey()] += "`;}";
66
70
 
67
71
  this.keys.pop(key);
68
72
  };
@@ -99,14 +103,18 @@ HTMLLitVisitor.prototype.MustacheStatement = function(mustache) {
99
103
  this.blocks[this.currentKey()] += "${index}";
100
104
  } else {
101
105
  const path = normalizePath.call(this, mustache.path.original);
102
- const hasCalculatingClasses = path.includes("context.classes");
106
+ const hasCalculatingClasses = path.includes("this.classes");
103
107
 
104
108
  let parsedCode = "";
105
109
 
106
110
  if (isNodeValue && !mustache.escaped) {
107
111
  parsedCode = `\${unsafeHTML(${path})}`;
108
112
  } else if (hasCalculatingClasses) {
109
- parsedCode = `\${classMap(${path})}`;
113
+ if (process.env.UI5_TS) {
114
+ parsedCode = `\${classMap(${path} as ClassMapValue)}`;
115
+ } else {
116
+ parsedCode = `\${classMap(${path})}`;
117
+ }
110
118
  } else if (isStyleAttribute) {
111
119
  parsedCode = `\${styleMap(${path})}`;
112
120
  } else if (skipIfDefined){
@@ -171,22 +179,37 @@ function visitEachBlock(block) {
171
179
  var bParamAdded = false;
172
180
  visitSubExpression.call(this, block);
173
181
 
174
- this.blocks[this.currentKey()] += "${ repeat(" + normalizePath.call(this, block.params[0].original) + ", (item, index) => item._id || index, (item, index) => ";
182
+ const reapeatDirectiveParamsTS = "(item, index) => (item as typeof item & {_id?: any})._id || index, (item, index: number)";
183
+ const reapeatDirectiveParamsJS = "(item, index) => item._id || index, (item, index)";
184
+ const repleatDirectiveParams = process.env.UI5_TS ? reapeatDirectiveParamsTS : reapeatDirectiveParamsJS;
185
+ this.blocks[this.currentKey()] += "${ repeat(" + normalizePath.call(this, block.params[0].original) + ", " + repleatDirectiveParams + " => ";
175
186
  this.paths.push(normalizePath.call(this, block.params[0].original));
176
- this.blockPath = "item";
187
+ this.blockLevel++;
177
188
 
178
- if (this.blockParameters.indexOf("item") === -1) {
189
+ // block params is [this, context, tags, suffix] for top level blocks
190
+ // blcok params is [this, context, tags, suffix, item, index] for nested blocks
191
+ if (!this.blockParametersUsage.includes("index")) {
192
+ // last item is not index, but an each block is processed, add the paramters for further nested blocks
179
193
  bParamAdded = true;
180
- this.blockParameters.unshift("index");
181
- this.blockParameters.unshift("item");
194
+ if (process.env.UI5_TS) {
195
+ this.blockParametersDefinition.push("item: any");
196
+ this.blockParametersDefinition.push("index: number");
197
+ } else {
198
+ this.blockParametersDefinition.push("item");
199
+ this.blockParametersDefinition.push("index");
200
+ }
201
+ this.blockParametersUsage.push("item");
202
+ this.blockParametersUsage.push("index");
182
203
  }
183
204
  this.acceptKey(block, "program");
184
205
  if (bParamAdded) {
185
- this.blockParameters.shift("item");
186
- this.blockParameters.shift("index");
206
+ // if parameters were added at this step, remove the last two
207
+ this.blockParametersDefinition.pop();
208
+ this.blockParametersDefinition.pop();
209
+ this.blockParametersUsage.pop();
210
+ this.blockParametersUsage.pop();
187
211
  }
188
- this.blockPath = "context";
189
-
212
+ this.blockLevel--;
190
213
  this.blocks[this.currentKey()] += ") }";
191
214
  }
192
215
 
@@ -195,12 +218,52 @@ function normalizePath(sPath) {
195
218
 
196
219
  //read carefully - https://github.com/wycats/handlebars.js/issues/1028
197
220
  //kpdecker commented on May 20, 2015
198
- if (result.indexOf("../") === 0) {
199
- let absolutePath = replaceAll(this.paths[this.paths.length - 1], ".", "/") + "/" + result;
221
+
222
+ if (result.indexOf("@root") === 0) {
223
+ // Trying to access root context via the HBS "@root" variable.
224
+ // Example: {{@root.property}} compiles to "context.property" - called from anywhere within the template.
225
+ result = result.replace("@root", "this");
226
+
227
+ } else if (result.indexOf("../") === 0) {
228
+ let absolutePath;
229
+ const levelsUp = (result.match(/..\//g) || []).length;
230
+
231
+ if (this.blockLevel <= levelsUp) {
232
+ // Trying to access root context from nested loops.
233
+ // Example: {{../../property}} compiles to "context.property" - when currently in a nested level loop.
234
+ // Example: {{../../../property}} compile to "context.property" - when requested levels are not present. fallback to root context.
235
+ absolutePath = `this.${replaceAll(result,"../", "")}`;
236
+ } else {
237
+ // Trying to access upper context (one-level-up) and based on the current lelev, that could be "context" or "item".
238
+ // Example: {{../property}} compiles to "context.property" - when called in a top level loop.
239
+ // Example: {{../property}} compiles to "item.property" - when called in a nested level loop.
240
+ // TODO: the second example, although correctly generated to "item.property", "item" will point to the current object within the nested loop,
241
+ // not the upper level loop as intended. So accessing the upper loop from nested loop is currently not working.
242
+ absolutePath = replaceAll(this.paths[this.paths.length - 1 - levelsUp], ".", "/") + "/" + result;
243
+ }
244
+
200
245
  result = replaceAll(path.normalize(absolutePath), path.sep, ".");
246
+
201
247
  } else {
202
- result = result ? replaceAll(this.blockPath + "/" + result, "/", ".") : this.blockPath;
248
+ // When neither "@root", nor "../" are used, use the following contexts:
249
+ // - use "context" - for the top level of execution, e.g "this.blockLevel = 0".
250
+ // - use "item" - for any nested level, e.g "this.blockLevel > 0".
251
+ // Example:
252
+ //
253
+ // {{text}} -> compiles to "context.text"
254
+ // {{#each items}}
255
+ // Item text: {{text}}</div> -> compiles to "item.text"
256
+ // {{#each words}}
257
+ // Word text: {{text}}</div> -> compiles to "item.text"
258
+ // {{/each}}
259
+ // Item text: {{text}}</div> -> compiles to "item.text"
260
+ // {{/each}}
261
+ // {{text}} -> compiles to "context.text"
262
+
263
+ const blockPath = this.blockLevel > 0 ? "item" : "this";
264
+ result = result ? replaceAll(blockPath + "/" + result, "/", ".") : blockPath;
203
265
  }
266
+
204
267
  return result;
205
268
  }
206
269
 
@@ -2,7 +2,7 @@
2
2
  const svgrx = new RegExp(/<svg[\s\S]*?>([\s\S]*?)<\/svg>/, 'g');
3
3
  const blockrx = /block[0-9]+/g;
4
4
 
5
- function process(input) {
5
+ function processSVG(input) {
6
6
  let matches;
7
7
  let template = input;
8
8
  let blockCounter = 0;
@@ -45,9 +45,16 @@ function getSVGMatches(template) {
45
45
  }
46
46
 
47
47
  function getSVGBlock(input, blockCounter) {
48
+ const definitionTS = `\nfunction blockSVG${blockCounter} (this: any, context: UI5Element, tags: string[], suffix: string | undefined) {
49
+ return svg\`${input}\`;
50
+ };`;
51
+ const definitionJS = `\nfunction blockSVG${blockCounter} (context, tags, suffix) {
52
+ return svg\`${input}\`;
53
+ };`;
54
+
48
55
  return {
49
- usage: `\${blockSVG${blockCounter}(context, tags, suffix)}`,
50
- definition: `\nconst blockSVG${blockCounter} = (context, tags, suffix) => svg\`${input}\`;`,
56
+ usage: `\${blockSVG${blockCounter}.call(this, context, tags, suffix)}`,
57
+ definition: process.env.UI5_TS ? definitionTS : definitionJS,
51
58
  };
52
59
  }
53
60
 
@@ -55,7 +62,7 @@ function replaceInternalBlocks(template, svgContent) {
55
62
  const internalBlocks = svgContent.match(blockrx) || [];
56
63
 
57
64
  internalBlocks.forEach(blockName => {
58
- const rx = new RegExp(`const ${blockName}.*(html\`).*;`);
65
+ const rx = new RegExp(`function ${blockName}.*(html\`).*;`);
59
66
  template = template.replace(rx, (match, p1) => {
60
67
  return match.replace(p1, "svg\`");
61
68
  });
@@ -65,5 +72,5 @@ function replaceInternalBlocks(template, svgContent) {
65
72
  }
66
73
 
67
74
  module.exports = {
68
- process: process
75
+ process: processSVG,
69
76
  };