@ethlete/cdk 5.0.0-next.4 → 5.0.0-next.40

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,374 @@
1
+ import { COMPONENTS_CLASSES } from './components-classes.js';
2
+ import { LEGACY_SPINNER_COLOR_VARIABLE, LEGACY_SPINNER_TAG, lineOfIndex, PICTURE_TAG, SPINNER_TAG, } from './templates.js';
3
+ export const DOCS_BASE_URL = 'https://ethlete-sdk-docs.web.app';
4
+ export const createEmptyReport = () => ({
5
+ picturesWithoutAlt: [],
6
+ pictureClassInputs: [],
7
+ themedSpinners: [],
8
+ spinnerModeBindings: [],
9
+ judgmentSymbols: new Map(),
10
+ gatedSymbols: new Map(),
11
+ unknownStyleClasses: new Map(),
12
+ reactiveFormControls: new Map(),
13
+ });
14
+ export const isReportEmpty = (report) => report.picturesWithoutAlt.length === 0 &&
15
+ report.pictureClassInputs.length === 0 &&
16
+ report.themedSpinners.length === 0 &&
17
+ report.spinnerModeBindings.length === 0 &&
18
+ report.judgmentSymbols.size === 0 &&
19
+ report.gatedSymbols.size === 0 &&
20
+ report.unknownStyleClasses.size === 0 &&
21
+ report.reactiveFormControls.size === 0;
22
+ const FORM_CONTROL_TAGS = [
23
+ 'et-checkbox',
24
+ 'et-checkbox-group',
25
+ 'et-color-input',
26
+ 'et-combobox',
27
+ 'et-date-input',
28
+ 'et-date-time-input',
29
+ 'et-email-input',
30
+ 'et-native-select',
31
+ 'et-number-input',
32
+ 'et-password-input',
33
+ 'et-radio-group',
34
+ 'et-search-input',
35
+ 'et-segmented-button-group',
36
+ 'et-select',
37
+ 'et-slide-toggle',
38
+ 'et-slider',
39
+ 'et-tel-input',
40
+ 'et-text-input',
41
+ 'et-textarea-input',
42
+ 'et-time-input',
43
+ ];
44
+ const REACTIVE_FORM_BINDING = /\s\[?(formControl|formControlName|formGroup)\]?(?=[\s=/>])/;
45
+ const PICTURE_CLASS_INPUTS = ['imgClass', 'figureClass', 'pictureClass', 'figcaptionClass'];
46
+ const VARIANT_PREFIX = /^([\w-]+:)+/;
47
+ const INDEFINITE_SIZES = new Set(['auto', 'min', 'max', 'fit']);
48
+ export const classifyImgClass = (value) => {
49
+ if (!value)
50
+ return 'unclassified';
51
+ const tokens = value.split(/\s+/).filter(Boolean);
52
+ let definiteWidth = false;
53
+ let definiteHeight = false;
54
+ let hasAspect = false;
55
+ let hasConstraint = false;
56
+ let hasIndefiniteAxis = false;
57
+ let hasResponsiveSizing = false;
58
+ for (const rawToken of tokens) {
59
+ const hasVariant = VARIANT_PREFIX.test(rawToken);
60
+ const token = rawToken.replace(VARIANT_PREFIX, '');
61
+ const axis = /^(w|h|size)-(.+)$/.exec(token);
62
+ const constraint = /^(?:max|min)-(?:w|h)-(.+)$/.exec(token);
63
+ const aspect = /^aspect-(.+)$/.exec(token);
64
+ if (!axis && !constraint && !aspect)
65
+ continue;
66
+ // A sizing class behind a breakpoint or a state is a judgment call, not a mode.
67
+ if (hasVariant) {
68
+ hasResponsiveSizing = true;
69
+ continue;
70
+ }
71
+ if (constraint) {
72
+ hasConstraint = true;
73
+ continue;
74
+ }
75
+ if (aspect) {
76
+ hasAspect ||= aspect[1] !== 'auto';
77
+ continue;
78
+ }
79
+ const [, prefix, size] = axis;
80
+ if (INDEFINITE_SIZES.has(size)) {
81
+ hasIndefiniteAxis = true;
82
+ continue;
83
+ }
84
+ definiteWidth ||= prefix === 'w' || prefix === 'size';
85
+ definiteHeight ||= prefix === 'h' || prefix === 'size';
86
+ }
87
+ if (hasResponsiveSizing)
88
+ return 'unclassified';
89
+ if ((definiteWidth && definiteHeight) || ((definiteWidth || definiteHeight) && hasAspect))
90
+ return 'fit';
91
+ if (definiteWidth || definiteHeight || hasConstraint || hasIndefiniteAxis)
92
+ return 'element-classes';
93
+ return 'unclassified';
94
+ };
95
+ const forEachOpeningTag = (template, tagName, visit) => {
96
+ const pattern = new RegExp(`<${tagName}(?=[\\s/>])[^>]*>`, 'g');
97
+ let match = pattern.exec(template);
98
+ while (match) {
99
+ visit(match[0], match.index);
100
+ match = pattern.exec(template);
101
+ }
102
+ };
103
+ /** The class list an attribute spells out, or `null` when only an expression knows it. */
104
+ const classListOf = (quotedValue, isBound) => {
105
+ const inner = quotedValue.slice(1, -1);
106
+ if (!isBound)
107
+ return inner;
108
+ const literal = /^'([^']*)'$/.exec(inner.trim());
109
+ return literal ? literal[1] : null;
110
+ };
111
+ export const scanTemplate = (report, template, { file, startLine }) => {
112
+ const lineAt = (index) => startLine + lineOfIndex(template, index) - 1;
113
+ forEachOpeningTag(template, PICTURE_TAG, (tag, index) => {
114
+ if (!/(^|\s)\[?alt\]?\s*=/.test(tag)) {
115
+ report.picturesWithoutAlt.push({ file, line: lineAt(index) });
116
+ }
117
+ const attributePattern = new RegExp(`\\s\\[?(${PICTURE_CLASS_INPUTS.join('|')})\\]?\\s*=\\s*("[^"]*"|'[^']*')`, 'g');
118
+ let match = attributePattern.exec(tag);
119
+ while (match) {
120
+ const input = match[1];
121
+ const value = classListOf(match[2], match[0].includes('['));
122
+ report.pictureClassInputs.push({
123
+ file,
124
+ line: lineAt(index),
125
+ input,
126
+ value,
127
+ mode: input === 'imgClass' ? classifyImgClass(value) : 'unclassified',
128
+ });
129
+ match = attributePattern.exec(tag);
130
+ }
131
+ });
132
+ for (const tagName of FORM_CONTROL_TAGS) {
133
+ forEachOpeningTag(template, tagName, (tag, index) => {
134
+ const binding = REACTIVE_FORM_BINDING.exec(tag);
135
+ if (!binding)
136
+ return;
137
+ const sites = report.reactiveFormControls.get(tagName) ?? [];
138
+ sites.push({ file, line: lineAt(index), detail: `\`${binding[1]}\`` });
139
+ report.reactiveFormControls.set(tagName, sites);
140
+ });
141
+ }
142
+ for (const tagName of [SPINNER_TAG, LEGACY_SPINNER_TAG]) {
143
+ forEachOpeningTag(template, tagName, (tag, index) => {
144
+ if (/\s\[mode\]\s*=/.test(tag) && !/\s\[mode\]\s*=\s*(["'])'(in)?determinate'\1/.test(tag)) {
145
+ report.spinnerModeBindings.push({ file, line: lineAt(index) });
146
+ }
147
+ });
148
+ }
149
+ };
150
+ const blankOut = (match) => match.replace(/[^\n]/g, ' ');
151
+ export const collectEtClasses = (styles) => {
152
+ const code = styles.replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*|"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'/g, blankOut);
153
+ const pattern = /(?<![\w-])\.(et-[\w-]+)/g;
154
+ const classes = [];
155
+ let match = pattern.exec(code);
156
+ while (match) {
157
+ classes.push({ name: match[1], index: match.index });
158
+ match = pattern.exec(code);
159
+ }
160
+ return classes;
161
+ };
162
+ const KNOWN_COMPONENTS_CLASSES = new Set(COMPONENTS_CLASSES);
163
+ export const scanStyleSheet = (report, styles, { file, startLine }) => {
164
+ const lineAt = (index) => startLine + lineOfIndex(styles, index) - 1;
165
+ for (const { name, index } of collectEtClasses(styles)) {
166
+ if (KNOWN_COMPONENTS_CLASSES.has(name))
167
+ continue;
168
+ const sites = report.unknownStyleClasses.get(name) ?? [];
169
+ sites.push({ file, line: lineAt(index) });
170
+ report.unknownStyleClasses.set(name, sites);
171
+ }
172
+ const variablePattern = new RegExp(`${LEGACY_SPINNER_COLOR_VARIABLE}(-\\d+)?`, 'g');
173
+ let variableMatch = variablePattern.exec(styles);
174
+ while (variableMatch) {
175
+ report.themedSpinners.push({
176
+ file,
177
+ line: lineAt(variableMatch.index),
178
+ detail: variableMatch[1]
179
+ ? `\`${variableMatch[0]}\` belonged to \`multiColor\`, which has no successor - drop it.`
180
+ : `\`${variableMatch[0]}\` was rewritten to \`--et-spinner-color\`.`,
181
+ });
182
+ variableMatch = variablePattern.exec(styles);
183
+ }
184
+ const blockPattern = /([^{}]+)\{([^{}]*)\}/g;
185
+ let blockMatch = blockPattern.exec(styles);
186
+ while (blockMatch) {
187
+ if (blockMatch[1].includes('.et-legacy') && /(^|[\s;])(--)?[\w-]*color\s*:/.test(blockMatch[2])) {
188
+ const selectorOffset = blockMatch[1].length - blockMatch[1].trimStart().length;
189
+ report.themedSpinners.push({
190
+ file,
191
+ line: lineAt(blockMatch.index + selectorOffset),
192
+ detail: `\`${blockMatch[1].trim().replace(/\s+/g, ' ')}\` colours a legacy-themed element.`,
193
+ });
194
+ }
195
+ blockMatch = blockPattern.exec(styles);
196
+ }
197
+ };
198
+ export const addSymbolSite = (target, symbol, entry, site) => {
199
+ const existing = target.get(symbol);
200
+ if (existing) {
201
+ existing.sites.push(site);
202
+ return;
203
+ }
204
+ target.set(symbol, { entry, sites: [site] });
205
+ };
206
+ const renderSites = (sites) => sites.map((site) => `- \`${site.file}:${site.line}\`${site.detail ? ` - ${site.detail}` : ''}`);
207
+ const renderDocsLink = (entry) => (entry.docs ? ` See ${DOCS_BASE_URL}${entry.docs}.` : '');
208
+ const renderSymbolSection = (symbols, describe) => [...symbols.entries()].flatMap(([symbol, { entry, sites }]) => [
209
+ `### \`${symbol}\``,
210
+ '',
211
+ describe(entry),
212
+ ...(entry.note ? ['', entry.note] : []),
213
+ '',
214
+ ...renderSites(sites),
215
+ '',
216
+ ]);
217
+ const renderPictureClassGroup = (sites, heading, guidance) => {
218
+ if (sites.length === 0)
219
+ return [];
220
+ return [
221
+ `### ${heading}`,
222
+ '',
223
+ ...guidance,
224
+ '',
225
+ ...sites.map((site) => `- \`${site.file}:${site.line}\` - \`${site.input}\`${site.value === null ? ' (bound expression)' : `="${site.value}"`}`),
226
+ '',
227
+ ];
228
+ };
229
+ const styleClassGroup = (name) => name.replace(/^et-/, '').split(/-/)[0] ?? name;
230
+ const renderUnknownStyleClasses = (classes) => {
231
+ const groups = new Map();
232
+ for (const name of [...classes.keys()].sort()) {
233
+ const group = styleClassGroup(name);
234
+ const sites = classes.get(name).map((site) => `\`${site.file}:${site.line}\``);
235
+ groups.set(group, [...(groups.get(group) ?? []), `- \`.${name}\` - ${sites.join(', ')}`]);
236
+ }
237
+ return [...groups.entries()].flatMap(([group, lines]) => [`### \`et-${group}\``, '', ...lines, '']);
238
+ };
239
+ export const renderReport = (report, context) => {
240
+ const pictureClassSites = report.pictureClassInputs;
241
+ const fitSites = pictureClassSites.filter((site) => site.input === 'imgClass' && site.mode === 'fit');
242
+ const elementClassSites = pictureClassSites.filter((site) => site.input === 'imgClass' && site.mode === 'element-classes');
243
+ const unclassifiedSites = pictureClassSites.filter((site) => site.input === 'imgClass' && site.mode === 'unclassified');
244
+ const wrapperClassSites = pictureClassSites.filter((site) => site.input !== 'imgClass');
245
+ const versionLines = Object.entries(context.installedVersions).map(([packageName, version]) => `- \`${packageName}\`: ${version ?? 'not declared in `package.json` - version-gated rewrites were applied unverified'}`);
246
+ return [
247
+ '# Migrating off @ethlete/cdk: what is left to do',
248
+ '',
249
+ `The generator rewrote the mechanical parts (${context.rewrittenFiles} file(s)). Everything below needs a decision`,
250
+ 'it cannot make. Symbols whose contract changed keep importing from `@ethlete/cdk` on purpose - switch the',
251
+ 'import once the call site matches the successor API.',
252
+ '',
253
+ 'Installed versions the version gate compared against:',
254
+ '',
255
+ ...versionLines,
256
+ '',
257
+ ...(report.picturesWithoutAlt.length > 0
258
+ ? [
259
+ '## `<et-picture>` without `alt`',
260
+ '',
261
+ '`alt` is required on the components picture. Passing `""` is allowed and means the image is decorative -',
262
+ 'a deliberate statement that it carries no information, not a placeholder for text nobody wrote yet. Which',
263
+ 'of the two a site needs is a product decision.',
264
+ '',
265
+ ...renderSites(report.picturesWithoutAlt),
266
+ '',
267
+ ]
268
+ : []),
269
+ ...(report.themedSpinners.length > 0
270
+ ? [
271
+ '## Themed spinners',
272
+ '',
273
+ 'The cdk spinner defaulted to a themed `#1e88e5`; the components spinner defaults to `currentColor`. A',
274
+ 'spinner that should carry a theme colour needs the `color` input (`<et-spinner color="brand" />`); one',
275
+ `inside a button or a link is usually better off inheriting. See ${DOCS_BASE_URL}/components/loader.`,
276
+ '',
277
+ ...renderSites(report.themedSpinners),
278
+ '',
279
+ ]
280
+ : []),
281
+ ...(report.spinnerModeBindings.length > 0
282
+ ? [
283
+ '## Spinner `[mode]` bindings',
284
+ '',
285
+ 'A bound `mode` cannot be rewritten mechanically. The spinner is determinate while `value` is bound, so',
286
+ '`[mode]="expr" [value]="v"` becomes `[value]="expr === \'determinate\' ? v : undefined"`.',
287
+ '',
288
+ ...renderSites(report.spinnerModeBindings),
289
+ '',
290
+ ]
291
+ : []),
292
+ ...(pictureClassSites.length > 0
293
+ ? [
294
+ '## Picture class inputs',
295
+ '',
296
+ '`imgClass` / `pictureClass` / `figureClass` / `figcaptionClass` are gone. There are two replacements and',
297
+ 'they are not interchangeable: `fit` needs a definite box in both axes, so using it where the image sizes',
298
+ 'its own box collapses the layout. Each site below is grouped by what its classes actually express.',
299
+ '',
300
+ ...renderPictureClassGroup(fitSites, 'Definite in both axes - use `fit`', [
301
+ 'Move the box classes to the host (`<et-picture class="size-8" fit="cover">`) and let `fit` decide what the',
302
+ 'image does inside that box.',
303
+ ]),
304
+ ...renderPictureClassGroup(elementClassSites, 'Image sizes its own box - style `.et-picture-img`', [
305
+ 'These constrain one axis (`max-h-*`, `w-auto`, a single axis) and let the image resolve the other. `fit`',
306
+ 'cannot express that. Style the element class directly - `[&_.et-picture-img]:max-h-41` - which is',
307
+ 'documented, stable API.',
308
+ ]),
309
+ ...renderPictureClassGroup(unclassifiedSites, 'Unclassified - decide per site', [
310
+ 'The value is a bound expression, responsive, or says nothing about sizing. Either move the classes to the',
311
+ `host and add \`fit\`, or style \`.et-picture-img\` directly. See ${DOCS_BASE_URL}/components/picture.`,
312
+ ]),
313
+ ...renderPictureClassGroup(wrapperClassSites, 'Wrapper classes', [
314
+ 'The `<figure>`, `<picture>` and `<figcaption>` passthroughs have no successor input. Put layout classes on',
315
+ 'the host, or target `.et-picture-figure` / `.et-picture-picture` / `.et-picture-figcaption`.',
316
+ ]),
317
+ ]
318
+ : []),
319
+ ...(report.gatedSymbols.size > 0
320
+ ? [
321
+ '## Successors that need a newer package',
322
+ '',
323
+ 'These imports were left untouched: the successor does not exist in the version this workspace has',
324
+ 'installed. Upgrade, then re-run the generator.',
325
+ '',
326
+ ...renderSymbolSection(report.gatedSymbols, (entry) => {
327
+ const installed = context.installedVersions[entry.package ?? ''] ?? 'unknown';
328
+ return `\`${entry.to}\` requires \`${entry.package}\` ≥ ${entry.since} (installed: ${installed}).${renderDocsLink(entry)}`;
329
+ }),
330
+ ]
331
+ : []),
332
+ ...(report.judgmentSymbols.size > 0
333
+ ? [
334
+ '## Symbols whose contract changed',
335
+ '',
336
+ 'Renaming the import is not enough for these - the successor behaves differently, or several symbols',
337
+ 'replace one.',
338
+ '',
339
+ ...renderSymbolSection(report.judgmentSymbols, (entry) => {
340
+ const successor = entry.kind === 'reshape' ? `stays \`${entry.to}\`` : `becomes \`${entry.to}\``;
341
+ return `${entry.kind}: ${successor} in \`${entry.package}\`.${renderDocsLink(entry)}`;
342
+ }),
343
+ ]
344
+ : []),
345
+ ...(report.reactiveFormControls.size > 0
346
+ ? [
347
+ '## Form controls that need signal forms first',
348
+ '',
349
+ 'The components form controls bind through signal forms (`[formField]`) and have no ControlValueAccessor,',
350
+ 'so these cdk controls, still bound through reactive forms, stay on `@ethlete/cdk` until their form moves',
351
+ `to signal forms. See ${DOCS_BASE_URL}/cdk/migration.`,
352
+ '',
353
+ ...[...report.reactiveFormControls.entries()].flatMap(([tagName, sites]) => [
354
+ `### \`<${tagName}>\``,
355
+ '',
356
+ ...renderSites(sites),
357
+ '',
358
+ ]),
359
+ ]
360
+ : []),
361
+ ...(report.unknownStyleClasses.size > 0
362
+ ? [
363
+ '## Stylesheet selectors no components class matches',
364
+ '',
365
+ 'These `.et-*` selectors restyle a cdk class that no `@ethlete/components` stylesheet defines, so after the',
366
+ "move they match nothing. Restyle through the successor's tokens and CSS variables instead (each component",
367
+ `guide has a Theming section). See ${DOCS_BASE_URL}/cdk/migration#your-cdk-styles.`,
368
+ '',
369
+ ...renderUnknownStyleClasses(report.unknownStyleClasses),
370
+ ]
371
+ : []),
372
+ ].join('\n');
373
+ };
374
+ //# sourceMappingURL=report.js.map
@@ -0,0 +1,30 @@
1
+ {
2
+ "$schema": "http://json-schema.org/schema",
3
+ "$id": "migrate-from-cdk",
4
+ "title": "Migrate from @ethlete/cdk to @ethlete/components",
5
+ "type": "object",
6
+ "properties": {
7
+ "projects": {
8
+ "type": "array",
9
+ "items": { "type": "string" },
10
+ "description": "Nx projects to migrate. Defaults to every project in the workspace.",
11
+ "alias": "project"
12
+ },
13
+ "include": {
14
+ "type": "array",
15
+ "items": { "type": "string" },
16
+ "description": "Path prefixes to migrate, relative to the workspace root (e.g. 'apps/shop'). Unioned with `projects`.",
17
+ "alias": "includePath"
18
+ },
19
+ "mapPath": {
20
+ "type": "string",
21
+ "description": "Path to migration-map.json. Defaults to the copy shipped with the installed @ethlete/cdk."
22
+ },
23
+ "skipFormat": {
24
+ "type": "boolean",
25
+ "description": "Skip formatting files after migration",
26
+ "default": false
27
+ }
28
+ },
29
+ "required": []
30
+ }
@@ -0,0 +1,91 @@
1
+ import * as ts from 'typescript';
2
+ import { applyReplacements, createSourceFile } from './imports.js';
3
+ export const lineOfIndex = (content, index) => content.slice(0, index).split('\n').length;
4
+ const stringLikeSpans = (node, sourceFile, spans) => {
5
+ if (ts.isStringLiteralLike(node) || ts.isTemplateExpression(node)) {
6
+ const start = node.getStart(sourceFile) + 1;
7
+ const end = node.getEnd() - 1;
8
+ spans.push({ start, end, text: sourceFile.text.slice(start, end) });
9
+ return;
10
+ }
11
+ ts.forEachChild(node, (child) => stringLikeSpans(child, sourceFile, spans));
12
+ };
13
+ const inlineSpansFor = (content, filePath, propertyName) => {
14
+ const sourceFile = createSourceFile(content, filePath);
15
+ const spans = [];
16
+ const visit = (node) => {
17
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === propertyName) {
18
+ stringLikeSpans(node.initializer, sourceFile, spans);
19
+ }
20
+ ts.forEachChild(node, visit);
21
+ };
22
+ visit(sourceFile);
23
+ return spans;
24
+ };
25
+ export const findInlineTemplateSpans = (content, filePath) => inlineSpansFor(content, filePath, 'template');
26
+ export const findInlineStyleSpans = (content, filePath) => inlineSpansFor(content, filePath, 'styles');
27
+ /** A `@Component`'s `templateUrl`, so an external template file can be traced back to the class that owns it. */
28
+ export const readTemplateUrl = (content, filePath) => {
29
+ const sourceFile = createSourceFile(content, filePath);
30
+ let templateUrl = null;
31
+ const visit = (node) => {
32
+ if (templateUrl)
33
+ return;
34
+ if (ts.isPropertyAssignment(node) &&
35
+ ts.isIdentifier(node.name) &&
36
+ node.name.text === 'templateUrl' &&
37
+ ts.isStringLiteralLike(node.initializer)) {
38
+ templateUrl = node.initializer.text;
39
+ return;
40
+ }
41
+ ts.forEachChild(node, visit);
42
+ };
43
+ visit(sourceFile);
44
+ return templateUrl;
45
+ };
46
+ export const transformInlineSpans = (content, spans, transform) => {
47
+ const replacements = [];
48
+ for (const span of spans) {
49
+ const next = transform(span.text);
50
+ if (next !== span.text) {
51
+ replacements.push({ start: span.start, end: span.end, replacement: next });
52
+ }
53
+ }
54
+ return applyReplacements(content, replacements);
55
+ };
56
+ /** Every opening tag of `tagName`, passed through `transform`. */
57
+ export const mapOpeningTags = (template, tagName, transform) => template.replace(new RegExp(`<${tagName}(?=[\\s/>])[^>]*>`, 'g'), transform);
58
+ export const PICTURE_TAG = 'et-picture';
59
+ export const SPINNER_TAG = 'et-spinner';
60
+ export const LEGACY_SPINNER_TAG = 'et-progress-spinner';
61
+ export const SKELETON_ITEM_TAG = 'et-skeleton-item';
62
+ const HAS_SHAPE = /(^|\s)\[?shape\]?\s*=/;
63
+ /** `shape` defaults to `text` in components, so the cdk's block behaviour has to be spelled out. */
64
+ const rewriteSkeletonItems = (template) => mapOpeningTags(template, SKELETON_ITEM_TAG, (tag) => HAS_SHAPE.test(tag) ? tag : tag.replace(`<${SKELETON_ITEM_TAG}`, `<${SKELETON_ITEM_TAG} shape="rect"`));
65
+ const rewriteSpinnerTags = (template) => template
66
+ .replace(new RegExp(`<${LEGACY_SPINNER_TAG}(?=[\\s/>])`, 'g'), `<${SPINNER_TAG}`)
67
+ .replace(new RegExp(`</${LEGACY_SPINNER_TAG}\\s*>`, 'g'), `</${SPINNER_TAG}>`);
68
+ const INDETERMINATE_MODE = /\s(?:mode\s*=\s*(["'])indeterminate\1|\[mode\]\s*=\s*(["'])'indeterminate'\2)/;
69
+ const rewriteSpinnerAttributes = (template) => mapOpeningTags(template, SPINNER_TAG, (tag) => (INDETERMINATE_MODE.test(tag) ? tag.replace(/\s(?:\[value\]|bind-value|value)\s*=\s*("[^"]*"|'[^']*')/g, '') : tag)
70
+ .replace(/\smode\s*=\s*(["'])(in)?determinate\1/g, '')
71
+ .replace(/\s\[mode\]\s*=\s*(["'])'(in)?determinate'\1/g, '')
72
+ .replace(/(\s)\[renderBackground\]/g, '$1[track]')
73
+ .replace(/(\s)renderBackground(?=[\s=/>])/g, '$1track')
74
+ .replace(/\s\[?multiColor\]?\s*=\s*("[^"]*"|'[^']*')/g, '')
75
+ .replace(/\smultiColor(?=[\s/>])/g, ''));
76
+ const rewritePictureAttributes = (template) => mapOpeningTags(template, PICTURE_TAG, (tag) => tag
77
+ .replace(/(\s)\[hasPriority\]/g, '$1[priority]')
78
+ .replace(/(\s)hasPriority(?=[\s=/>])/g, '$1priority')
79
+ .replace(/(\s)\(imgLoaded\)/g, '$1(imgLoad)'));
80
+ const rewriteTooltipAttributes = (template) => template
81
+ .replace(/(\s)\[tooltipAriaDescription\]/g, '$1[etTooltipAriaDescription]')
82
+ .replace(/(\s)tooltipAriaDescription(?=[\s=/>])/g, '$1etTooltipAriaDescription');
83
+ export const rewriteTemplate = (template, options = {}) => {
84
+ const withSpinnerTags = rewriteSpinnerTags(template);
85
+ const withSkeletonAndSpinner = rewriteSpinnerAttributes(rewriteSkeletonItems(withSpinnerTags));
86
+ const withPicture = options.pictureImportMoved === false ? withSkeletonAndSpinner : rewritePictureAttributes(withSkeletonAndSpinner);
87
+ return rewriteTooltipAttributes(withPicture);
88
+ };
89
+ export const LEGACY_SPINNER_COLOR_VARIABLE = '--et-progress-spinner-color';
90
+ export const rewriteStyleSheet = (styles) => styles.replace(new RegExp(`${LEGACY_SPINNER_COLOR_VARIABLE}(?![\\w-])`, 'g'), '--et-spinner-color');
91
+ //# sourceMappingURL=templates.js.map
@@ -23,7 +23,6 @@ const ET_MENU_SYMBOLS = new Set([
23
23
  ]);
24
24
  export default async function migrateCdkMenu(tree) {
25
25
  console.log('\n🔄 Migrating from CDK menu to et menu');
26
- const files = tree.children('.');
27
26
  const warnings = new Map();
28
27
  function walkFiles(path) {
29
28
  const entries = tree.children(path);
@@ -63,7 +62,6 @@ export default async function migrateCdkMenu(tree) {
63
62
  return;
64
63
  // Process imports and build replacement
65
64
  let hasMenuSymbols = false;
66
- let hasMenuImports = false;
67
65
  const importedSymbols = new Set();
68
66
  imports.forEach((match) => {
69
67
  const importList = match[1];
@@ -76,9 +74,6 @@ export default async function migrateCdkMenu(tree) {
76
74
  if (CDK_MENU_SYMBOLS.includes(symbol)) {
77
75
  hasMenuSymbols = true;
78
76
  }
79
- if (symbol === 'MenuImports') {
80
- hasMenuImports = true;
81
- }
82
77
  });
83
78
  });
84
79
  if (!hasMenuSymbols && !Array.from(importedSymbols).some((s) => ET_MENU_SYMBOLS.has(s)))
@@ -130,7 +125,7 @@ export default async function migrateCdkMenu(tree) {
130
125
  return result;
131
126
  });
132
127
  // Replace imports
133
- content = content.replace(importRegex, (match, importList) => {
128
+ content = content.replace(importRegex, (_match, importList) => {
134
129
  const symbols = importList
135
130
  .split(',')
136
131
  .map((s) => s.trim())
@@ -223,7 +218,7 @@ export default async function migrateCdkMenu(tree) {
223
218
  // 4. Replace cdkMenuItemCheckbox with et-menu-checkbox-item
224
219
  if (content.includes('cdkMenuItemCheckbox')) {
225
220
  const checkboxRegex = /<(\w+)([^>]*?)\bcdkMenuItemCheckbox\b([^>]*)>([\s\S]*?)<\/\1>/g;
226
- content = content.replace(checkboxRegex, (match, tagName, beforeAttrs, afterAttrs, inner) => {
221
+ content = content.replace(checkboxRegex, (_match, _tagName, beforeAttrs, afterAttrs, inner) => {
227
222
  const allAttrs = (beforeAttrs + afterAttrs)
228
223
  .replace(/\s+cdkMenuItemCheckbox\s+/, ' ')
229
224
  .replace(/\bcdkMenuItemCheckbox\b/, '')
@@ -235,7 +230,7 @@ export default async function migrateCdkMenu(tree) {
235
230
  // 5. Replace cdkMenuItemRadio with et-menu-radio-item and add warning
236
231
  if (content.includes('cdkMenuItemRadio')) {
237
232
  const radioRegex = /<(\w+)([^>]*?)\bcdkMenuItemRadio\b([^>]*)>([\s\S]*?)<\/\1>/g;
238
- content = content.replace(radioRegex, (match, tagName, beforeAttrs, afterAttrs, inner) => {
233
+ content = content.replace(radioRegex, (_match, _tagName, beforeAttrs, afterAttrs, inner) => {
239
234
  const allAttrs = (beforeAttrs + afterAttrs)
240
235
  .replace(/\s+cdkMenuItemRadio\s+/, ' ')
241
236
  .replace(/\bcdkMenuItemRadio\b/, '')
@@ -1,8 +1,30 @@
1
1
  import { logger, readJson, visitNotIgnoredFiles, writeJson } from '@nx/devkit';
2
+ const TEMPLATE_REPLACEMENTS = [
3
+ ['[etProvideTheme]', '[etProvideColor]'],
4
+ ['etProvideTheme', 'etProvideColor'],
5
+ ['[etProvideAltTheme]', '[etProvideAltColor]'],
6
+ ['etProvideAltTheme', 'etProvideAltColor'],
7
+ ['[etColorThemed]', '[etColored]'],
8
+ ['etColorThemed', 'etColored'],
9
+ ['[etSurfaceThemed]', '[etSurfaced]'],
10
+ ['etSurfaceThemed', 'etSurfaced'],
11
+ ['[theme]=', '[color]='],
12
+ ['[altTheme]=', '[altColor]='],
13
+ ['et-theme-alt--', 'et-color-alt--'],
14
+ ['et-theme--', 'et-color--'],
15
+ ];
16
+ const CSS_REPLACEMENTS = [
17
+ ['.et-color-themed', '.et-colored'],
18
+ ['.et-surface-themed', '.et-surfaced'],
19
+ ['.et-theme--', '.et-color--'],
20
+ ['.et-theme-alt--', '.et-color-alt--'],
21
+ ];
2
22
  // Theming-related exports that moved from @ethlete/theming and @ethlete/cdk to @ethlete/core
3
23
  const THEMING_EXPORTS = new Set([
4
24
  'ProvideThemeDirective',
25
+ 'ProvideColorDirective',
5
26
  'THEME_PROVIDER',
27
+ 'COLOR_PROVIDER',
6
28
  'Theme',
7
29
  'ThemeSwatch',
8
30
  'OnThemeColorMap',
@@ -20,6 +42,44 @@ export default async function migrateColorThemes(tree) {
20
42
  let importsMoved = 0;
21
43
  let importsMerged = 0;
22
44
  let packagesRemoved = 0;
45
+ // Migrate HTML template files
46
+ visitNotIgnoredFiles(tree, '', (filePath) => {
47
+ if (!filePath.endsWith('.html')) {
48
+ return;
49
+ }
50
+ const content = tree.read(filePath, 'utf-8');
51
+ if (!content) {
52
+ return;
53
+ }
54
+ let modified = content;
55
+ for (const [oldStr, newStr] of TEMPLATE_REPLACEMENTS) {
56
+ modified = modified.replaceAll(oldStr, newStr);
57
+ }
58
+ if (modified !== content) {
59
+ tree.write(filePath, modified);
60
+ filesModified++;
61
+ console.log(` ✓ ${filePath}`);
62
+ }
63
+ });
64
+ // Migrate CSS/SCSS files
65
+ visitNotIgnoredFiles(tree, '', (filePath) => {
66
+ if (!filePath.endsWith('.css') && !filePath.endsWith('.scss')) {
67
+ return;
68
+ }
69
+ const content = tree.read(filePath, 'utf-8');
70
+ if (!content) {
71
+ return;
72
+ }
73
+ let modified = content;
74
+ for (const [oldStr, newStr] of CSS_REPLACEMENTS) {
75
+ modified = modified.replaceAll(oldStr, newStr);
76
+ }
77
+ if (modified !== content) {
78
+ tree.write(filePath, modified);
79
+ filesModified++;
80
+ console.log(` ✓ ${filePath}`);
81
+ }
82
+ });
23
83
  // Migrate TypeScript files
24
84
  visitNotIgnoredFiles(tree, '', (filePath) => {
25
85
  if (!filePath.endsWith('.ts')) {
@@ -29,14 +89,38 @@ export default async function migrateColorThemes(tree) {
29
89
  if (!content) {
30
90
  return;
31
91
  }
32
- // Check if file contains provideThemes or imports from @ethlete/theming or @ethlete/cdk
33
- if (!content.includes('provideThemes') &&
34
- !content.includes('@ethlete/theming') &&
35
- !content.includes('@ethlete/cdk')) {
92
+ // Check if file contains provideThemes or imports from @ethlete/theming or @ethlete/cdk,
93
+ // or any template/CSS strings that need replacing
94
+ const needsImportMigration = content.includes('provideThemes') || content.includes('@ethlete/theming') || content.includes('@ethlete/cdk');
95
+ const needsTemplateMigration = TEMPLATE_REPLACEMENTS.some(([oldStr]) => content.includes(oldStr));
96
+ const needsCssMigration = CSS_REPLACEMENTS.some(([oldStr]) => content.includes(oldStr));
97
+ if (!needsImportMigration && !needsTemplateMigration && !needsCssMigration) {
36
98
  return;
37
99
  }
38
100
  let modified = content;
39
101
  let fileChanges = 0;
102
+ // Apply template replacements (covers inline templates and class usages)
103
+ if (needsTemplateMigration) {
104
+ for (const [oldStr, newStr] of TEMPLATE_REPLACEMENTS) {
105
+ modified = modified.replaceAll(oldStr, newStr);
106
+ }
107
+ fileChanges++;
108
+ }
109
+ // Apply CSS replacements (covers inline styles)
110
+ if (needsCssMigration) {
111
+ for (const [oldStr, newStr] of CSS_REPLACEMENTS) {
112
+ modified = modified.replaceAll(oldStr, newStr);
113
+ }
114
+ fileChanges++;
115
+ }
116
+ if (!needsImportMigration) {
117
+ if (modified !== content) {
118
+ tree.write(filePath, modified);
119
+ filesModified++;
120
+ console.log(` ✓ ${filePath} (${fileChanges} change${fileChanges !== 1 ? 's' : ''})`);
121
+ }
122
+ return;
123
+ }
40
124
  // Replace provideThemes with provideColorThemes
41
125
  const beforeProvideThemesCount = (modified.match(/\bprovideThemes\b/g) || []).length;
42
126
  modified = modified.replace(/\bprovideThemes\b/g, 'provideColorThemes');
@@ -69,8 +153,6 @@ export default async function migrateColorThemes(tree) {
69
153
  imports.forEach((imp) => {
70
154
  // Extract the actual import name (without 'type' keyword and alias)
71
155
  // Handle patterns like: "type Theme as EthleteTheme", "Theme", "type Theme"
72
- const typeKeywordMatch = imp.match(/^type\s+/);
73
- const hasTypeKeyword = !!typeKeywordMatch;
74
156
  const withoutType = imp.replace(/^type\s+/, '').trim();
75
157
  const importName = withoutType.split(/\s+as\s+/)[0]?.trim() || withoutType;
76
158
  if (THEMING_EXPORTS.has(importName)) {