-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathutils.ts
More file actions
281 lines (249 loc) · 8.46 KB
/
Copy pathutils.ts
File metadata and controls
281 lines (249 loc) · 8.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import { ArgTypes, Args, type StoryObj } from '@storybook/web-components';
import { type ControlType } from '@storybook/blocks';
import cem from '../../dist/cem/custom-elements.json';
/** Global theme options for components that support a `theme` attribute. */
export const GLOBAL_THEME_OPTIONS = ['primary', 'secondary', 'tertiary', 'success', 'warning', 'error', 'info'];
export const DENSITY_OPTIONS = ['small', 'medium', 'large'];
export const OVERLAY_FLIP_OPTIONS = ['auto', 'main', 'cross', 'never'];
export const OVERLAY_PLACEMENT_OPTIONS = [
'top',
'right',
'bottom',
'left',
'top-start',
'top-end',
'right-start',
'right-end',
'left-start',
'left-end',
'bottom-start',
'bottom-end'
];
/**
* Common default parameters for a standalone story.
*/
export const standaloneStoryParams: StoryObj = {
parameters: {
controls: { disable: true },
actions: { disable: true }
}
};
export const removeSourceStyleTagParams: StoryObj = {
parameters: {
docs: {
source: {
transform: (source: string) => source.replace(/=""/g, '').replace(/<style[\s\S]*<\/style>/, '')
}
}
}
};
/**
* Transforms the CSS properties of a custom element into controls for Storybook.
* @param tagName {string} - The tag name of the custom element
* @returns {object} - The controls object for Storybook
*/
export function transformCssPropsToControls(tagName: string) {
const declaration = cem.modules.flatMap((module: any) => module.declarations).find((declaration: any) => declaration.tagName === tagName);
return declaration.cssProperties.reduce((acc: object, prop: any) => {
acc[prop.name] = { control: 'text' };
return acc;
}, {});
}
/**
* Render a custom element story using the provided tag name and props.
* @param tagName {keyof HTMLElementTagNameMap} - The tag name of the component to render
* @param props {Partial<HTMLElementTagNameMap[T]>} - The props to pass to the component
* @returns {HTMLElement} - The rendered element.
*/
export function customElementStoryRenderer<T extends keyof HTMLElementTagNameMap>(
tagName: T,
props: Partial<HTMLElementTagNameMap[T]>
): HTMLElementTagNameMap[T] {
const element = document.createElement(tagName);
applyArgs(element, props);
return element;
}
/**
* Apply props to a custom element.
* @param element {HTMLElement} - The element to apply props to
* @param props {Partial<HTMLElement>} - The props to apply
*/
export function applyArgs(element: HTMLElement, props: Partial<HTMLElement>) {
Object.keys(props).forEach(key => {
if (key.startsWith('--')) {
// Set CSS custom properties via inline style
element.style.setProperty(key, props[key]);
} else if (key.includes('-')) {
// Args with dashes in the name are considered HTML attributes
element.setAttribute(key, props[key]);
} else if (key in element) {
// Everything else is considered a JavaScript property if it exists on the element
element[key] = props[key];
}
});
}
/**
* Get the CSS custom properties args from a full set of args (any arg that is prefixed with "--" is considered a CSS variable).
*/
export function getCssVariableArgs(args: Args): Args | null {
const cssVarArgs = Object.entries(args).reduce((acc, [key, value]) => {
if (key.startsWith('--') && value !== '') {
acc[key] = value;
}
return acc;
}, {});
return Object.entries(cssVarArgs).length ? cssVarArgs : null;
}
/**
* Generates Storybook `argTypes` for a custom element based on its tag name from the custom elements manifest.
*/
export function generateCustomElementArgTypes({
tagName,
exclude,
include,
controls,
category
}: {
tagName: string;
exclude?: string[] | RegExp;
include?: string[] | RegExp;
controls?: Partial<ArgTypes<Args>>;
category?: string;
}): object {
const declaration = getCustomElementsTagDeclaration(tagName);
const argTypes: ArgTypes = {};
let properties = declaration.members?.filter(member => member.kind === 'field' && member.privacy === 'public') ?? [];
let cssProperties = declaration.cssProperties ?? [];
if (exclude) {
if (exclude instanceof RegExp) {
properties = properties.filter(property => !exclude.test(property.name));
cssProperties = cssProperties.filter(property => !exclude.test(property.name));
} else {
exclude.forEach(prop => {
properties = properties.filter(property => property.name !== prop);
cssProperties = cssProperties.filter(property => property.name !== prop);
});
}
}
if (include) {
if (include instanceof RegExp) {
properties = properties.filter(property => include.test(property.name));
cssProperties = cssProperties.filter(property => include.test(property.name));
} else {
properties = properties.filter(property => include.includes(property.name));
cssProperties = cssProperties.filter(property => include.includes(property.name));
}
}
if (properties.length) {
const propertyArgTypes = generateArgTypesFrom(properties, category ? `${category} properties` : 'properties');
Object.assign(argTypes, propertyArgTypes);
}
if (cssProperties.length) {
const cssPropertyArgTypes = generateArgTypesFrom(cssProperties, category ? `${category} css custom properties` : 'css custom properties', 'text');
Object.assign(argTypes, cssPropertyArgTypes);
}
if (controls) {
Object.entries(controls).forEach(([key, value]) => {
if (argTypes[key]) {
Object.assign(argTypes[key], value);
}
});
}
return argTypes;
}
function generateArgTypesFrom(items: TagItem[], category: string, controlType?: ControlType): object {
return items.reduce((acc: object, property: any) => {
acc[property.name] = {
control: controlType ?? getControlFromType(property.type.text),
defaultValue: property.default,
table: { category }
};
return acc;
}, {});
}
/** Gets the custom elements manifest module for the declaration matching the provided tag name. */
export function getCustomElementsTagModule(tagName: string): any {
return cem.modules.find((module: any) => module.declarations.some((declaration: any) => declaration.tagName === tagName));
}
/** Gets the custom elements manifest declaration for the provided tag name. */
export function getCustomElementsTagDeclaration(tagName: string): Declaration {
return cem.modules.flatMap((module: any) => module.declarations).find(declaration => declaration.tagName === tagName);
}
/** Attempts to retrieve the Forge type information for the provided type string. */
export function getCustomElementType(type: string) {
return cem.forgeTypes[type];
}
/** Gets the branch name that the custom elements manifest was generated with. */
export function getBranchName() {
return cem.branchName;
}
export function htmlEncode(str: string): string {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
function getControlFromType(type: string): ControlType {
return CONTROL_TYPE_MAP[type] ?? 'text';
}
/** Removes inline style tags from a string of HTML. */
export function removeInlineStyleTag(source: string): string {
source = removeEmptyAttributes(source);
return source.replace(/<style>[\s\S]*?<\/style>/g, '');
}
/** Removes empty attributes from a string of HTML. */
export function removeEmptyAttributes(source: string): string {
return source.replace(/=""/g, '');
}
const CONTROL_TYPE_MAP: Record<string, ControlType> = {
boolean: 'boolean',
string: 'text',
number: 'number',
object: 'object',
function: 'object',
array: 'object',
bigint: 'number'
};
export interface TagItem {
name: string;
type: {
text?: string;
};
description: string;
default?: any;
kind?: string;
privacy?: string;
defaultValue?: any;
}
export interface Module {
kind: string;
path: string;
declarations: Declaration[];
}
export interface Declaration {
tagName: string;
name: string;
description: string;
attributes?: TagItem[];
properties?: TagItem[];
events?: TagItem[];
methods?: TagItem[];
members?: TagItem[];
slots?: TagItem[];
cssProperties?: TagItem[];
cssParts?: TagItem[];
dependencies?: DependencyItem[];
cssFilePath?: TagItem;
cssClasses?: TagItem[];
globalConfigProperties?: GlobalConfigPropertyItem[];
role?: TagItem;
aria?: TagItem[];
focusable?: TagItem;
formAssociated?: TagItem;
keyControls?: TagItem[];
}
export interface DependencyItem {
name: string;
description: string;
}
export interface GlobalConfigPropertyItem {
name: string;
description: string;
}