-
Notifications
You must be signed in to change notification settings - Fork 151
/
Block.ts
502 lines (459 loc) · 16.2 KB
/
Block.ts
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
import * as postcss from 'postcss';
import { ObjectDictionary, MultiMap, assertNever } from "@opticss/util";
import selectorParser = require('postcss-selector-parser');
import { FileIdentifier } from "../importing";
import { LocalScopedContext } from "../util/LocalScope";
import { CssBlockError } from "../errors";
import { OptionsReader } from "../OptionsReader";
import { CLASS_NAME_IDENT, ROOT_CLASS } from "../BlockSyntax";
import { Source } from "./BlockTree";
import { BlockClass } from "./BlockClass";
import { State } from "./State";
import { BlockPath } from "../BlockSyntax";
import {
SelectorFactory,
parseSelector,
ParsedSelector,
CompoundSelector
} from "opticss";
import {
stateParser,
isClassNode,
isStateNode,
NodeAndType,
BlockType
} from "../BlockParser";
export type Style = BlockClass | State;
export const OBJ_REF_SPLITTER = (s: string): [string, string] | undefined => {
let index = s.indexOf('.');
if (index < 0) index = s.indexOf('[');
if (index >= 0) {
return [s.substr(0, index), s.substring(index)];
}
return;
};
export class Block
extends Source<Block, BlockClass>
implements SelectorFactory {
private _rootClass: BlockClass;
private _blockReferences: ObjectDictionary<Block> = {};
private _identifier: FileIdentifier;
private _implements: Block[] = [];
private _localScope: LocalScopedContext<Block, Style>;
private hasHadNameReset = false;
/**
* array of paths that this block depends on and, if changed, would
* invalidate the compiled css of this block. This is usually only useful in
* preprocessed blocks.
*/
private _dependencies: Set<string>;
public stylesheet?: postcss.Root;
public readonly parsedRuleSelectors: WeakMap<postcss.Rule, ParsedSelector[]>;
constructor(name: string, identifier: FileIdentifier) {
super(name);
this._identifier = identifier;
this.parsedRuleSelectors = new WeakMap();
this._localScope = new LocalScopedContext<Block, Style>(OBJ_REF_SPLITTER, this);
this._dependencies = new Set<string>();
this._rootClass = new BlockClass(ROOT_CLASS, this, this);
this.addClass(this._rootClass);
}
get name() { return this._name; }
set name(name: string) {
if (this.hasHadNameReset) {
throw new CssBlockError('Can not set block name more than once.');
}
this._name = name;
this.hasHadNameReset = true;
}
get rootClass(): BlockClass {
return this._rootClass;
}
/// Start of methods to implement LocalScope<Block, Style>
subScope(name: string): LocalScopedContext<Block, Style> | undefined {
let block = this._blockReferences[name];
if (block) {
return block._localScope;
} else {
return;
}
}
lookupLocal(name: string): Style | undefined {
let blockRef = this._blockReferences[name];
if (blockRef) {
return blockRef.rootClass;
} else {
return this.all(false).find(o => o.asSource() === name);
}
}
/**
* Lookup a sub-block either locally, or on a referenced foreign block.
* @param reference
* A reference to a block object adhering to the following grammar:
* reference -> <ident> '.' <sub-reference> // reference through sub-block <ident>
* | <ident> // reference to sub-block <ident>
* | '.' <class-selector> // reference to class in this block
* | <state-selector> // reference to state in this block
* | '.' // reference to this block
* sub-reference -> <ident> '.' <sub-reference> // reference through sub-sub-block
* | <object-selector> // reference to object in sub-block
* object-selector -> <block-selector> // reference to this sub-block
* | <class-selector> // reference to class in sub-block
* | <state-selector> // reference to state in this sub-block
* block-selector -> 'root'
* class-selector -> <ident>
* state-selector -> '[state|' <ident> ']'
* ident -> regex:[a-zA-Z_-][a-zA-Z0-9]*
* A single dot by itself returns the current block.
* @returns The Style referenced at the supplied path.
*/
public lookup(path: string | BlockPath): Style | undefined {
path = new BlockPath(path);
let block = this.getReferencedBlock(path.block);
if (!block) return undefined;
let klass = block.resolveClass(path.class);
if (!klass) return undefined;
let state;
if (path.state) {
let groupName = path.state.group ? path.state.group : path.state.name;
let stateName = path.state.group ? path.state.name : undefined;
state = klass.resolveState(groupName, stateName);
if (!state) return undefined;
}
return state || klass;
// for (let part of path.tokens()) {
// res = res.resolveChild(part);
// if (!res) { break; }
// }
}
/// End of methods to implement LocalScope<Block, Style>
/**
* Add an absolute, normalized path as a compilation dependency. This is used
* to invalidate caches and trigger watchers when those files change.
*
* It is not necessary or helpful to add css-block files.
*/
addDependency(filepath: string) {
this._dependencies.add(filepath);
}
get dependencies(): string[] {
return new Array(...this._dependencies);
}
get identifier(): FileIdentifier {
return this._identifier;
}
getClass(name: string): BlockClass | null { return name ? this.getChild(name) : this.getChild(ROOT_CLASS); }
resolveClass(name: string): BlockClass | null { return name ? this.resolveChild(name) : this.resolveChild(ROOT_CLASS); }
newChild(name: string): BlockClass { return new BlockClass(name, this, this); }
// Alias protected methods from `Inheritable` to Block-specific names, and expose them as a public API.
get classes(): BlockClass[] { return this.children(); }
addClass(blockClass: BlockClass) { this.setChild(blockClass.name, blockClass); }
ensureClass(name: string): BlockClass { return this.ensureChild(name); }
getImplementedBlocks(): Block[] {
return this._implements.slice();
}
addImplementation(b: Block) {
return this._implements.push(b);
}
/**
* Validate that this block implements all foreign selectors from blocks it implements.
* @param b The block to check implementation against.
* @returns The Styles from b that are missing in the block.
*/
checkImplementation(b: Block): Style[] {
let missing: Style[] = [];
for (let o of b.all()) {
if (!this.find(o.asSource())) {
missing.push(o);
}
}
return missing;
}
/**
* Validate that all foreign blocks this block implements are fully...implemented.
*/
checkImplementations(): void {
for (let b of this.getImplementedBlocks()) {
let missing: Style[] = this.checkImplementation(b);
let paths = missing.map(o => o.asSource()).join(", ");
if (missing.length > 0) {
let s = missing.length > 1 ? 's' : '';
throw new CssBlockError(`Missing implementation${s} for: ${paths} from ${b.identifier}`);
}
}
}
// This is a really dumb impl
find(sourceName: string): Style | undefined {
let blockRefName: string | undefined;
let md = sourceName.match(CLASS_NAME_IDENT);
if (md && md.index === 0) {
blockRefName = md[0];
let blockRef: Block | undefined;
this.eachBlockReference((name, block) => {
if (blockRefName === name) {
blockRef = block;
}
});
if (blockRef) {
if (md[0].length === sourceName.length) {
return blockRef.rootClass;
}
return blockRef.find(sourceName.slice(md[0].length));
} else {
return undefined;
}
}
return this.all().find(e => e.asSource() === sourceName);
}
eachBlockReference(callback: (name: string, block: Block) => any) {
for (let name of Object.keys(this._blockReferences)) {
callback(name, this._blockReferences[name]);
}
}
addBlockReference(localName: string, other: Block) {
this._blockReferences[localName] = other;
}
getReferencedBlock(localName: string): Block | null {
if (localName === "") { return this; }
return this._blockReferences[localName] || null;
}
transitiveBlockDependencies(): Set<Block> {
let deps = new Set<Block>();
this.eachBlockReference((_name, block) => {
deps.add(block);
let moreDeps = block.transitiveBlockDependencies();
if (moreDeps.size > 0) {
deps = new Set([...deps, ...moreDeps]);
}
});
return deps;
}
/**
* Returns a new array of ancestors in order of inheritance
* with the first one being the immediate super block.
*
* If this block doesn't inherit, the array is empty.
**/
getAncestors(): Array<Block> {
let inherited = new Array<Block>();
let base = this.base;
while (base) {
inherited.push(base);
base = base.base;
}
return inherited;
}
/**
* Return array self and all children.
* @param shallow Pass true to not include inherited objects.
* @returns Array of Styles.
*/
all(shallow?: boolean): Style[] {
let result = new Array<Style>();
for (let blockClass of this.classes) {
result.push(...blockClass.all());
}
if (!shallow && this.base) {
result.push(...this.base.all(shallow));
}
return result;
}
merged(): MultiMap<string, Style> {
let map = new MultiMap<string, Style>(false);
for (let obj of this.all()) {
map.set(obj.asSource(), obj);
}
return map;
}
/**
* Fetch a the cached `Style` from `Block` given `NodeAndType`.
* @param obj The `NodeAndType` object to use for `Style` lookup.
*/
nodeAndTypeToStyle(obj: NodeAndType): Style | null {
switch (obj.blockType) {
case BlockType.root:
return this.rootClass;
case BlockType.state:
return this.rootClass._getState(stateParser(<selectorParser.Attribute>obj.node));
case BlockType.class:
return this.getClass(obj.node.value!);
case BlockType.classState:
let classNode = obj.node.prev();
let classObj = this.getClass(classNode.value!);
if (classObj) {
return classObj._getState(stateParser(<selectorParser.Attribute>obj.node));
}
return null;
default:
return assertNever(obj.blockType);
}
}
nodeAsStyle(node: selectorParser.Node): [Style, number] | null {
if (node.type === selectorParser.CLASS && node.value === ROOT_CLASS) {
return [this.rootClass, 0];
} else if (node.type === selectorParser.TAG) {
let otherBlock = this.getReferencedBlock(node.value!);
if (otherBlock) {
let next = node.next();
if (next && isClassNode(next)) {
let klass = otherBlock.getClass(next.value!);
if (klass) {
let another = next.next();
if (another && isStateNode(another)) {
let info = stateParser(<selectorParser.Attribute>another);
let state = klass._getState(info);
if (state) {
return [state, 2];
} else {
return null; // this is invalid and should never happen.
}
} else {
// we don't allow scoped classes not part of a state
return null; // this is invalid and should never happen.
}
} else {
return null;
}
} else if (next && isStateNode(next)) {
let info = stateParser(<selectorParser.Attribute>next);
let state = otherBlock.rootClass._getState(info);
if (state) {
return [state, 1];
} else {
return null;
}
} else {
return null;
}
} else {
return null;
}
} else if (node.type === selectorParser.CLASS) {
let klass = this.getClass(node.value!);
if (klass === null) {
return null;
}
let next = node.next();
if (next && isStateNode(next)) {
let info = stateParser(<selectorParser.Attribute>next);
let state = klass._getState(info);
if (state === null) {
return null;
} else {
return [state, 1];
}
} else {
return [klass, 0];
}
} else if (isStateNode(node)) {
let info = stateParser(<selectorParser.Attribute>node);
let state = this.rootClass._ensureState(info);
if (state) {
return [state, 0];
} else {
return null;
}
}
return null;
}
rewriteSelectorNodes(nodes: selectorParser.Node[], opts: OptionsReader): selectorParser.Node[] {
let newNodes: selectorParser.Node[] = [];
for (let i = 0; i < nodes.length; i++) {
let node = nodes[i];
let result = this.nodeAsStyle(node);
if (result === null) {
newNodes.push(node);
} else {
newNodes.push(selectorParser.className({ value: result[0].cssClass(opts) }));
i += result[1];
}
}
return newNodes;
}
rewriteSelectorToString(selector: ParsedSelector, opts: OptionsReader): string {
let firstNewSelector = new CompoundSelector();
let newSelector = firstNewSelector;
let newCurrentSelector = newSelector;
let currentSelector: CompoundSelector | undefined = selector.selector;
do {
newCurrentSelector.nodes = this.rewriteSelectorNodes(currentSelector.nodes, opts);
newCurrentSelector.pseudoelement = currentSelector.pseudoelement;
if (currentSelector.next !== undefined) {
let tempSel = newCurrentSelector;
newCurrentSelector = new CompoundSelector();
tempSel.setNext(currentSelector.next.combinator, newCurrentSelector);
currentSelector = currentSelector.next.selector;
} else {
currentSelector = undefined;
}
} while (currentSelector !== undefined);
return firstNewSelector.toString();
}
rewriteSelector(selector: ParsedSelector, opts: OptionsReader): ParsedSelector {
// generating a string and re-parsing ensures the internal structure is consistent
// otherwise the parent/next/prev relationships will be wonky with the new nodes.
let s = this.rewriteSelectorToString(selector, opts);
return parseSelector(s)[0];
}
debug(opts: OptionsReader): string[] {
let result: string[] = [`Source: ${this.identifier}`, this.rootClass.asDebug(opts)];
let sourceNames = new Set<string>(this.all().map(s => s.asSource()));
let sortedNames = [...sourceNames].sort();
for (let n of sortedNames) {
if (n !== `.${ROOT_CLASS}`) {
let o = this.find(n) as Style;
result.push(o.asDebug(opts));
}
}
return result;
}
/**
* Test if the supplied block is the same block object.
* @param other The other Block to test against.
* @return True or False if self and `other` are equal.
*/
equal(other: Block | undefined | null) {
return other && this.identifier === other.identifier;
}
isAncestorOf(other: Block | undefined | null): boolean {
let base: Block | undefined | null = other && other.base;
while (base) {
if (this.equal(base)) {
return true;
} else {
base = base.base;
}
}
return false;
}
/**
* TODO: Move selector cache into `parseSelector` and have consumers of this
* method interface with the parseSelector utility directly.
* Given a PostCSS Rule, ensure it is present in this Block's parsed rule
* selectors cache, and return the ParsedSelector array.
* @param rule PostCSS Rule
* @return ParsedSelector array
*/
getParsedSelectors(rule: postcss.Rule): ParsedSelector[] {
let sels = this.parsedRuleSelectors.get(rule);
if (!sels) {
sels = parseSelector(rule);
this.parsedRuleSelectors.set(rule, sels);
}
return sels;
}
/**
* Objects that contain Blocks are often passed into assorted libraries' options
* hashes. Some libraries like to `JSON.stringify()` their options to create
* unique identifiers for re-run caching. (ex: Webpack, awesome-typescript-loader)
* Blocks contain circular dependencies, so we need to override their `toJSON`
* method so these libraries don't implode.
* @return The name of the block.
*/
toJSON() {
return this._name;
}
}
export function isBlock(o?: object): o is Block {
return o instanceof Block;
}