-
Notifications
You must be signed in to change notification settings - Fork 0
/
conditional-classes.js
432 lines (319 loc) · 11.3 KB
/
conditional-classes.js
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
// conditional-classes.js
//
// by Eric Portis
// TODO
// - needs more and better comments
// - code order/organization is a mess
( function() {
// the shoddiest little mustard-cutting test
if ( !( 'Set' in window ) ) { return; }
// prevent --if from cascading
if ( 'CSS' in window && 'registerProperty' in CSS ) {
// new, fancy
CSS.registerProperty( {
name: '--if',
syntax: '*',
inherits: false
} );
} else {
// old, tired
const sheet = document.createElement( 'style' );
sheet.innerHTML = '* { --if: initial; }';
document.head.appendChild( sheet );
}
// get computed CSS props from elements
function getProperty( node, property ) {
if ( 'computedStyleMap' in Element.prototype ) {
// new and ¡fancy!
const p = node.computedStyleMap().get( property )
if ( p ) {
return p[ 0 ]; // TODO why do I need the [ 0 ] and why do I get the feeling that's going to bite me in the ass somehow
} else {
return null;
}
} else {
// older and ¿slower?
return window.getComputedStyle( node ).getPropertyValue( property );
}
}
// data we're storing about DOM nodes goes here
const conditionalClasses = new WeakMap();
// as elements come into the DOM, check to see if they have `--if` custom props
// if an element does have an `--if`,
// 1. parse the prop and put the resulting query functions in the conditionalClasses WeakMap
// 2. start ResizeObserving the element
// TODO get this to work on element updates, not just when elements are inserted
const mo = new MutationObserver( ( mutations ) => {
for ( const mutation of mutations ) {
for ( const newNode of mutation.addedNodes ) {
if ( newNode.nodeType === 1 ) { // elements only, no text!
const theProp = getProperty( newNode, '--if' );
if ( theProp ) {
conditionalClasses.set(
newNode,
parseConditionalClasses( theProp, newNode )
);
ro.observe( newNode );
}
}
}
}
} );
// use the stored queries to check-and-possibly-toggle classes whenever the element is resized
const ro = new ResizeObserver( entries => {
for ( const entry of entries ) {
const ccs = conditionalClasses.get( entry.target );
// `classes` here is the returned object which will look like
// {
// toAdd: Set { 'medium' },
// toRemove: Set { 'small', 'large' }
// }
// `queries` is an array of functions, which take the RO entry as input and return true or false depending on whether the query matches or not
let classes = [ ...ccs.keys() ].reduce( ( classes, queries ) => {
querysClassNames = ccs.get( queries );
// all queries must return true (they're all joined by ANDs...)
if ( queries.every( query => { return query( entry ) } ) ) {
classes.toAdd = union( classes.toAdd, querysClassNames );
} else {
classes.toRemove = union( classes.toRemove, querysClassNames );
}
return classes;
}, {
toAdd: new Set(),
toRemove: new Set()
} );
// a class may be attached to both a true & false query
// this is an author error, really - but - what should we do? first wins? last wins? but I've made everything sets...
// how about, truth wins. the world needs a little more truth.
classes.toRemove = difference( classes.toRemove, classes.toAdd );
entry.target.classList.remove( ...classes.toRemove );
entry.target.classList.add( ...classes.toAdd );
}
} );
/*
* input: single condititons/classes pair
* e.g.'( 200px < content-width < 400px ) .medium'
* output: split conditions and classes strings
* e.g.[ '( 200px < content-width < 400px )', '.medium' ]
*/
const splitPair = function( pair ) {
const trimmed = pair.trim();
const match = trimmed.match( /\(.+\)/ );
if ( !match ) { return null; } //error?
const query = match[ 0 ];
const classNames = trimmed
.slice( query.length, pair.length )
.trim();
return [ query, classNames ];
}
/* input: classes string
* e.g., '.medium.border'
* output: set of classes
* e.g., Set { 'medium', 'border' }
*/
const classStringToSet = function( string ) {
return new Set( string
.split( '.' )
.map( c => { return c.trim(); } )
.filter( c => { return c !== '' } )
);
}
/* input: full `--if` attribute string
* e.g.,
'( 200px < content-inline <= 400px ) .medium,
( content-inline > 400px ) .large'
* output: object with query-testing-functions as keys and sets of classes as values
* e.g.,
Map {
[ ( entry ) => { entry.contentBoxSize.inlineSize > 200 },
( entry ) => { entry.contentBoxSize.inlineSize <= 400 } ]
=> Set { 'medium' },
[ ( entry ) => { entry.contentBoxSize.inlineSize > 400 } ]
=> Set { 'large' }
}
*/
const parseConditionalClasses = ( function( conditionalClassesString, element ) { // need the element to calculate ems based on context
return conditionalClassesString.split( ',' ).reduce( ( accumulator, conditionalClassString ) => {
const [ queryString, classesString ] = splitPair( conditionalClassString );
const queryTestFunctions = parseQuery( queryString, element );
const setOfClasses = classStringToSet( classesString );
accumulator.set( queryTestFunctions, setOfClasses );
return accumulator;
}, new Map() );
} );
const flipped = {
'<': '>',
'>': '<',
'<=': '>=',
'>=': '<=',
'=': '='
}
/*
* input: single conditional query string (just the query part, not the class)
! also the element, so that we can parse cascade-relative units like em
* output: array of functions that test that query
* depends on:
* constructQuery function
* flipped object (for flipping </>/etc)
*/
function parseQuery( string, el ) {
const numberOfSigns = string.match( /\>=|\<=|\>|\<|=/g ).length;
if ( numberOfSigns === 1 ) {
const captured = string.match( /^\(\s*([\w\d\-\.]+)\s*(\>=|\<=|\>|\<|=)\s*([\w\d\-\.]+)\s*\)$/ );
if ( !captured ) { throw 'invalid media query'; }
return [
constructQuery( captured[1], captured[2], getComputedLength( captured[3], el ) )
];
} else if ( numberOfSigns === 2 ) {
const captured = string.match( /^\(\s*([\w\d\-\.]+)\s*(\>=|\<=|\>|\<|=)\s*([\w\d\-\.]+)\s*(\>=|\<=|\>|\<|=)\s*([\w\d\-\.]+)\s*\)$/ );
if ( !captured ) { throw 'invalid media query' }
return [
constructQuery( captured[ 3 ], flipped[ captured[ 2 ] ], getComputedLength( captured[ 1 ], el ) ),
constructQuery( captured[ 3 ], captured[ 4 ], getComputedLength( captured[ 5 ], el ) )
];
} else {
throw `invalid media query (expected one or two signs, got ${ numberOfSigns })`;
}
}
// query parsing stuff
const operators = {
'<': function(a, b) { return a < b },
'<=': function(a, b) { return a <= b },
'>': function(a, b) { return a > b },
'>=': function(a, b) { return a >= b },
'=': function(a, b) { return a === b }
};
logicalToPhysical = {
'inline': 'width',
'block': 'height'
};
// returns a *function* that will test whether an element's
// query target ([content{default}|border]-[inline|block] size, which is measured from layout and may change over time)
// is greater than, less than, equal to, etc
// a given length (constant)
function constructQuery( queryTarget, relationalOperator, someNumber ) {
let box = 'content', // optional, can be 'content' or 'border'; content is default
queriedProperty; // can be 'height', 'width', 'inline', 'block', or 'aspect-ratio'
const remainingTokens = queryTarget.split('-');
let currentToken = remainingTokens.shift();
if ( currentToken === 'content' || currentToken === 'border' ) {
box = currentToken;
currentToken = remainingTokens.shift();
}
if ( currentToken === 'aspect' && remainingTokens.shift() === 'ratio' ) {
queriedProperty = 'aspect-ratio';
} else {
queriedProperty = currentToken;
}
if ( remainingTokens.length > 0 ) {
throw `"${ queryTarget }" is not a valid query target.`
}
// if we support new and improved ResizeObserver
let fancyResizeObserver = false;
if ( 'contentBoxSize' in ResizeObserverEntry.prototype &&
'borderBoxSize' in ResizeObserverEntry.prototype ) {
fancyResizeObserver = true;
}
return function( entry ) {
let queriedQuantity;
if ( queriedProperty === 'aspect-ratio' ) {
if ( fancyResizeObserver ) {
queriedQuantity = entry[ `${ box }BoxSize` ].inlineSize /
entry[ `${ box }BoxSize` ].blockSize;
} else {
queriedQuantity = entry.contentRect.width /
entry.contentRect.height;
}
} else if ( queriedProperty === 'inline' || queriedProperty === 'block' ) {
if ( fancyResizeObserver ) {
queriedQuantity = entry[ `${ box }BoxSize` ][ `${ queriedProperty }Size` ];
} else {
// TODO alerts about querying border-box size when fancy=false
queriedQuantity = entry.contentRect[ logicalToPhysical[ queriedProperty ] ];
console.warn( `Conditional class query asked for an ${ queriedProperty } size, but this browser only supports querying height and width. So I queried ${ logicalToPhysical[ queriedProperty ] } instead.` );
}
} else if ( queriedProperty === 'height' || queriedProperty === 'width' ) {
// TODO alerts about querying border-box size when fancy=false
// TODO what to do about border-height and border-width queries? (instead of content-)
queriedQuantity = entry.contentRect[ logicalToPhysical[ queriedProperty ] ];
}
return operators[ relationalOperator ](
queriedQuantity,
someNumber
);
}
}
/*
* Get the computed length in pixels of a CSS length value
// e.g. getComputedLength( '10em', el ) → 160
*
* @param {string} value
* @param {Element} element
* @return {number}
*/
// someday this will be as easy as CSSUnitValue.parse('5em').to('px')
// (wait, how will it know the em context? will it?)
// but for now, using a function copied from Martin Auswöger
// https://github.com/ausi/cq-prolyfill/blob/master/cq-prolyfill.js#L1037
// under MIT license:
// https://github.com/ausi/cq-prolyfill/blob/master/LICENSE
//
function getComputedLength(value, element) {
var LENGTH_REGEXP = /^(-?(?:\d*\.)?\d+)(em|ex|ch|rem|vh|vw|vmin|vmax|px|mm|cm|in|pt|pc)$/i;
var FIXED_UNIT_MAP = {
'px': 1,
'pt': 16 / 12,
'pc': 16,
'in': 96,
'cm': 96 / 2.54,
'mm': 96 / 25.4,
};
var length = value.match(LENGTH_REGEXP);
if (!length) {
return parseFloat(value);
}
value = parseFloat(length[1]);
var unit = length[2].toLowerCase();
if (FIXED_UNIT_MAP[unit]) {
return value * FIXED_UNIT_MAP[unit];
}
if (unit === 'vw') {
return value * window.innerWidth / 100;
}
if (unit === 'vh') {
return value * window.innerHeight / 100;
}
if (unit === 'vmin') {
return value * Math.min(window.innerWidth, window.innerHeight) / 100;
}
if (unit === 'vmax') {
return value * Math.max(window.innerWidth, window.innerHeight) / 100;
}
// em units
if (unit === 'rem') {
element = document.documentElement;
}
if (unit === 'ex') {
value /= 2;
}
return parseFloat(getComputedStyle(element).fontSize) * value;
}
// basic set operations
// from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
const union = function( setA, setB ) {
let result = new Set( setA );
for ( const element of setB ) {
result.add( element );
}
return result;
}
const difference = function( setA, setB ) {
let result = new Set( setA );
for ( const element of setB ) {
result.delete( element );
}
return result;
}
// start MutationObserving the document
mo.observe( document, { childList: true, subtree: true } );
} )();