-
-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathhtml-css-id-module-builder.ts
More file actions
282 lines (248 loc) · 6.33 KB
/
html-css-id-module-builder.ts
File metadata and controls
282 lines (248 loc) · 6.33 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
282
import {
NoStyleJSXElementConfig,
StyledComponentJSXElementConfig,
} from "@web-builder/styled";
import { JSX, JSXChildLike, Snippet } from "coli";
import { StylesRepository } from "@web-builder/core/builders";
import { create_duplication_reduction_map } from "@web-builder/styled";
import { buildCSSStyleData, CSSProperties } from "@coli.codes/css";
import { ReservedKeywordPlatformPresets } from "@coli.codes/naming";
import { k, JsxWidget } from "@web-builder/core";
import {
buildJsx,
StylesConfigMapBuilder,
JSXWithStyleElementConfig,
} from "@web-builder/core/builders";
import {
JSXAttribute,
JSXElement,
JSXElementLike,
JSXOpeningElement,
ScopedVariableNamer,
stringfy,
StringLiteral,
} from "coli";
import { Framework } from "@grida/builder-platform-types";
interface CssDeclaration {
key: {
name: string;
selector: "tag" | "id" | "class";
};
style: CSSProperties;
}
export type HtmlModuleBuilderConfig = {
disable_all_optimizations?: boolean;
additional_css_declarations?: CssDeclaration[];
};
export class HtmlIdCssModuleBuilder {
private readonly entry: JsxWidget;
private readonly widgetName: string;
private readonly stylesMapper: StylesConfigMapBuilder;
private readonly stylesRepository: StylesRepository;
private readonly namer: ScopedVariableNamer;
readonly config: HtmlModuleBuilderConfig;
constructor({
entry,
config,
}: {
entry: JsxWidget;
config: HtmlModuleBuilderConfig;
}) {
this.entry = entry;
this.widgetName = entry.key.name;
this.config = config;
this.namer = new ScopedVariableNamer(
entry.key.id,
ReservedKeywordPlatformPresets.html
);
this.stylesMapper = new StylesConfigMapBuilder(
entry,
{
namer: this.namer,
rename_tag: false, // vanilla html tag will be preserved.
},
Framework.vanilla
);
this.stylesRepository = new StylesRepository(
this.stylesMapper.map,
this.config?.disable_all_optimizations
? undefined
: // ALWAYS USE EXACT OVERLAPPING STYLE REDUCTION STRATEGY FOR PREVIEW VANILLA
create_duplication_reduction_map
);
}
private styledConfig(
id: string
): StyledComponentJSXElementConfig | NoStyleJSXElementConfig {
return this.stylesRepository.get(id);
}
private jsxBuilder(widget: JsxWidget) {
return buildJsx(
widget,
{
styledConfig: (id) => this.styledConfig(id),
idTransformer: (jsx, id) => injectIdToJsx(jsx, id),
},
{
self_closing_if_possible: false, // html cannot be self closed
}
);
}
partStyles(): string {
const css_declarations: CssDeclaration[] = [];
// global vanilla default injected style
css_declarations.push({
key: {
name: "*",
selector: "tag",
},
style: k.user_agent_stylesheet_override_default,
});
// ------------------
// standard body css
css_declarations.push(
...Array.from(this.stylesRepository.uniques())
.map((k) => {
const item = this.stylesRepository.get(
k
) as JSXWithStyleElementConfig;
return <CssDeclaration>{
key: {
name: item.id,
selector: "id",
},
style: item.style,
};
})
.filter((s) => s)
);
// ------------------
// declare additional styles requested by user
this.config.additional_css_declarations?.forEach((d) => {
css_declarations.push(d);
});
const strfied_css = css_declarations
.map((css) => {
const selectors = {
id: "#",
class: ".",
tag: "",
};
const style = buildCSSStyleData(css.style);
const key = selectors[css.key.selector] + css.key.name;
// main
const main = `${key} {${formatCssBodyString(style.main)}}`;
// support pseudo-selectors
const pseudos = Object.keys(style.pseudo).map((k) => {
const body = style.pseudo[k];
const pseudo = `${key}${k} {${formatCssBodyString(body)}}`;
return pseudo;
});
const all = [main, ...pseudos].join("\n");
return all;
})
.join("\n\n");
return strfied_css;
}
partBody(): JSXChildLike {
let jsxTree = this.jsxBuilder(this.entry);
return jsxTree;
}
/**
*
* @returns merged final html file src
*/
render(): string {
const strfied_body = stringfy(this.partBody(), {
language: "jsx",
indentation: "\t",
});
const final = html_render({
css: this.partStyles(),
body: this.partBody(),
});
return final;
}
export() {
return {
code: this.render(),
name: this.widgetName,
/** TODO: add fonts as dependency */
dependencies: [],
};
}
}
/**
* injects id attribute to existing jsx for css selectors.
* @param jsx
* @param id
*/
function injectIdToJsx(jsx: JSXElementLike, id: string) {
let attr;
if (jsx instanceof JSXElement) {
attr = jsx.openingElement.attributes;
}
if (jsx instanceof JSXOpeningElement) {
attr = jsx.attributes;
}
//
if (attr) {
attr.push(new JSXAttribute("id", new StringLiteral(id)));
} else {
console.clear();
console.error(jsx);
throw new Error("unsupported jsx element");
}
}
const html_render = ({ css, body }: { css: string; body: JSXChildLike }) => {
const indenter = (s: string, tabs: number = 0) =>
s.replace(/\n/g, "\n" + "\t".repeat(tabs));
const html = JSX.html({
children: [
JSX.head(
// style
JSX.style(Snippet.fromStatic(indenter(css, 3)) as any)
),
// body
JSX.body(body),
],
});
return stringfy(html.make(), {
language: "jsx", // use jsx for html also.
});
};
/**
* from
* ```
* `
* color: white;
* width: 24px;
* `
* ```
*
* to
* ```
* `
* color: white;
* width: 24px;
* `
* ```
*/
function formatCssBodyString(styleString: string): string {
const lines: string[] = [];
let declarationLines = 0;
styleString.split("\n").map((l) => {
if (l.length <= 1) {
// this is not a style property line. ignore it
lines.push(l);
} else {
lines.push(`\t${l}`);
declarationLines += 1;
}
});
if (declarationLines == 0) {
// if no actual style declration in style string.
return "";
}
return lines.join("\n");
}