summaryrefslogtreecommitdiffstats
path: root/testing/web-platform/tests/css/support/interpolation-testcommon.js
blob: 211018ca053adfe4f03ad70bf31c060b8bfdb0b1 (plain)
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
'use strict';
(function() {
  var interpolationTests = [];
  var compositionTests = [];
  var cssAnimationsData = {
    sharedStyle: null,
    nextID: 0,
  };
  var expectNoInterpolation = {};
  var expectNotAnimatable = {};
  var neutralKeyframe = {};
  function isNeutralKeyframe(keyframe) {
    return keyframe === neutralKeyframe;
  }

  // For the CSS interpolation methods set the delay to be negative half the
  // duration, so we are immediately at the halfway point of the animation.
  // We then use an easing function that maps halfway to whatever progress
  // we actually want.

  var cssAnimationsInterpolation = {
    name: 'CSS Animations',
    isSupported: function() {return true;},
    supportsProperty: function() {return true;},
    supportsValue: function() {return true;},
    setup: function() {},
    nonInterpolationExpectations: function(from, to) {
      return expectFlip(from, to, 0.5);
    },
    notAnimatableExpectations: function(from, to, underlying) {
      return expectFlip(underlying, underlying, -Infinity);
    },
    interpolate: function(property, from, to, at, target) {
      var id = cssAnimationsData.nextID++;
      if (!cssAnimationsData.sharedStyle) {
        cssAnimationsData.sharedStyle = createElement(document.body, 'style');
      }
      cssAnimationsData.sharedStyle.textContent += '' +
        '@keyframes animation' + id + ' {' +
          (isNeutralKeyframe(from) ? '' : `from {${property}:${from};}`) +
          (isNeutralKeyframe(to) ? '' : `to {${property}:${to};}`) +
        '}';
      target.style.animationName = 'animation' + id;
      target.style.animationDuration = '100s';
      target.style.animationDelay = '-50s';
      target.style.animationTimingFunction = createEasing(at);
    },
  };

  var cssTransitionsInterpolation = {
    name: 'CSS Transitions',
    isSupported: function() {return true;},
    supportsProperty: function() {return true;},
    supportsValue: function() {return true;},
    setup: function(property, from, target) {
      target.style.setProperty(property, isNeutralKeyframe(from) ? '' : from);
    },
    nonInterpolationExpectations: function(from, to) {
      return expectFlip(from, to, -Infinity);
    },
    notAnimatableExpectations: function(from, to, underlying) {
      return expectFlip(from, to, -Infinity);
    },
    interpolate: function(property, from, to, at, target, behavior) {
      // Force a style recalc on target to set the 'from' value.
      getComputedStyle(target).getPropertyValue(property);
      target.style.transitionDuration = '100s';
      target.style.transitionDelay = '-50s';
      target.style.transitionTimingFunction = createEasing(at);
      target.style.transitionProperty = property;
      if (behavior) {
        target.style.transitionBehavior = behavior;
      }
      target.style.setProperty(property, isNeutralKeyframe(to) ? '' : to);
    },
  };

  var cssTransitionAllInterpolation = {
    name: 'CSS Transitions with transition: all',
    isSupported: function() {return true;},
    // The 'all' value doesn't cover custom properties.
    supportsProperty: function(property) {return property.indexOf('--') !== 0;},
    supportsValue: function() {return true;},
    setup: function(property, from, target) {
      target.style.setProperty(property, isNeutralKeyframe(from) ? '' : from);
    },
    nonInterpolationExpectations: function(from, to) {
      return expectFlip(from, to, -Infinity);
    },
    notAnimatableExpectations: function(from, to, underlying) {
      return expectFlip(from, to, -Infinity);
    },
    interpolate: function(property, from, to, at, target, behavior) {
      // Force a style recalc on target to set the 'from' value.
      getComputedStyle(target).getPropertyValue(property);
      target.style.transitionDuration = '100s';
      target.style.transitionDelay = '-50s';
      target.style.transitionTimingFunction = createEasing(at);
      target.style.transitionProperty = 'all';
      if (behavior) {
        target.style.transitionBehavior = behavior;
      }
      target.style.setProperty(property, isNeutralKeyframe(to) ? '' : to);
    },
  };

  var cssTransitionsInterpolationAllowDiscrete = {
    name: 'CSS Transitions with transition-behavior:allow-discrete',
    isSupported: function() {return true;},
    supportsProperty: function() {return true;},
    supportsValue: function() {return true;},
    setup: function(property, from, target) {
      target.style.setProperty(property, isNeutralKeyframe(from) ? '' : from);
    },
    nonInterpolationExpectations: function(from, to) {
      return expectFlip(from, to, 0.5);
    },
    notAnimatableExpectations: function(from, to, underlying) {
      return expectFlip(from, to, -Infinity);
    },
    interpolate: function(property, from, to, at, target, behavior) {
      // Force a style recalc on target to set the 'from' value.
      getComputedStyle(target).getPropertyValue(property);
      target.style.transitionDuration = '100s';
      target.style.transitionDelay = '-50s';
      target.style.transitionTimingFunction = createEasing(at);
      target.style.transitionProperty = property;
      target.style.transitionBehavior = 'allow-discrete';
      target.style.setProperty(property, isNeutralKeyframe(to) ? '' : to);
    },
  };

  var cssTransitionAllInterpolationAllowDiscrete = {
    name: 'CSS Transitions with transition-property:all and transition-behavor:allow-discrete',
    isSupported: function() {return true;},
    // The 'all' value doesn't cover custom properties.
    supportsProperty: function(property) {return property.indexOf('--') !== 0;},
    supportsValue: function() {return true;},
    setup: function(property, from, target) {
      target.style.setProperty(property, isNeutralKeyframe(from) ? '' : from);
    },
    nonInterpolationExpectations: function(from, to) {
      return expectFlip(from, to, 0.5);
    },
    notAnimatableExpectations: function(from, to, underlying) {
      return expectFlip(from, to, -Infinity);
    },
    interpolate: function(property, from, to, at, target, behavior) {
      // Force a style recalc on target to set the 'from' value.
      getComputedStyle(target).getPropertyValue(property);
      target.style.transitionDuration = '100s';
      target.style.transitionDelay = '-50s';
      target.style.transitionTimingFunction = createEasing(at);
      target.style.transitionProperty = 'all';
      target.style.transitionBehavior = 'allow-discrete';
      target.style.setProperty(property, isNeutralKeyframe(to) ? '' : to);
    },
  };

  var webAnimationsInterpolation = {
    name: 'Web Animations',
    isSupported: function() {return 'animate' in Element.prototype;},
    supportsProperty: function(property) {return true;},
    supportsValue: function(value) {return value !== '';},
    setup: function() {},
    nonInterpolationExpectations: function(from, to) {
      return expectFlip(from, to, 0.5);
    },
    notAnimatableExpectations: function(from, to, underlying) {
      return expectFlip(underlying, underlying, -Infinity);
    },
    interpolate: function(property, from, to, at, target) {
      this.interpolateComposite(property, from, 'replace', to, 'replace', at, target);
    },
    interpolateComposite: function(property, from, fromComposite, to, toComposite, at, target) {
      // This case turns into a test error later on.
      if (!this.isSupported())
        return;

      // Convert standard properties to camelCase.
      if (!property.startsWith('--')) {
        for (var i = property.length - 2; i > 0; --i) {
          if (property[i] === '-') {
            property = property.substring(0, i) + property[i + 1].toUpperCase() + property.substring(i + 2);
          }
        }
        if (property === 'offset') {
          property = 'cssOffset';
        } else if (property === 'float') {
          property = 'cssFloat';
        }
      }
      var keyframes = [];
      if (!isNeutralKeyframe(from)) {
        keyframes.push({
          offset: 0,
          composite: fromComposite,
          [property]: from,
        });
      }
      if (!isNeutralKeyframe(to)) {
        keyframes.push({
          offset: 1,
          composite: toComposite,
          [property]: to,
        });
      }
      var animation = target.animate(keyframes, {
        fill: 'forwards',
        duration: 100 * 1000,
        easing: createEasing(at),
      });
      animation.pause();
      animation.currentTime = 50 * 1000;
    },
  };

  function expectFlip(from, to, flipAt) {
    return [-0.3, 0, 0.3, 0.5, 0.6, 1, 1.5].map(function(at) {
      return {
        at: at,
        expect: at < flipAt ? from : to
      };
    });
  }

  // Constructs a timing function which produces 'y' at x = 0.5
  function createEasing(y) {
    if (y == 0) {
      return 'steps(1, end)';
    }
    if (y == 1) {
      return 'steps(1, start)';
    }
    if (y == 0.5) {
      return 'linear';
    }
    // Approximate using a bezier.
    var b = (8 * y - 1) / 6;
    return 'cubic-bezier(0, ' + b + ', 1, ' + b + ')';
  }

  function createElement(parent, tag, text) {
    var element = document.createElement(tag || 'div');
    element.textContent = text || '';
    parent.appendChild(element);
    return element;
  }

  function createTargetContainer(parent, className) {
    var targetContainer = createElement(parent);
    targetContainer.classList.add('container');
    var template = document.querySelector('#target-template');
    if (template) {
      targetContainer.appendChild(template.content.cloneNode(true));
    }
    var target = targetContainer.querySelector('.target') || targetContainer;
    target.classList.add('target', className);
    target.parentElement.classList.add('parent');
    targetContainer.target = target;
    return targetContainer;
  }

  function roundNumbers(value) {
    return value.
        // Round numbers to two decimal places.
        replace(/-?\d*\.\d+(e-?\d+)?/g, function(n) {
          return (parseFloat(n).toFixed(2)).
              replace(/\.\d+/, function(m) {
                return m.replace(/0+$/, '');
              }).
              replace(/\.$/, '').
              replace(/^-0$/, '0');
        });
  }

  var anchor = document.createElement('a');
  function sanitizeUrls(value) {
    var matches = value.match(/url\("([^#][^\)]*)"\)/g);
    if (matches !== null) {
      for (var i = 0; i < matches.length; ++i) {
        var url = /url\("([^#][^\)]*)"\)/g.exec(matches[i])[1];
        anchor.href = url;
        anchor.pathname = '...' + anchor.pathname.substring(anchor.pathname.lastIndexOf('/'));
        value = value.replace(matches[i], 'url(' + anchor.href + ')');
      }
    }
    return value;
  }

  function normalizeValue(value) {
    return roundNumbers(sanitizeUrls(value)).
        // Place whitespace between tokens.
        replace(/([\w\d.]+|[^\s])/g, '$1 ').
        replace(/\s+/g, ' ');
  }

  function stringify(text) {
    if (!text.includes("'")) {
      return `'${text}'`;
    }
    return `"${text.replace('"', '\\"')}"`;
  }

  function keyframeText(keyframe) {
    return isNeutralKeyframe(keyframe) ? 'neutral' : `[${keyframe}]`;
  }

  function keyframeCode(keyframe) {
    return isNeutralKeyframe(keyframe) ? 'neutralKeyframe' : `${stringify(keyframe)}`;
  }

  function createInterpolationTestTargets(interpolationMethod, interpolationMethodContainer, interpolationTest) {
    var property = interpolationTest.options.property;
    var from = interpolationTest.options.from;
    var to = interpolationTest.options.to;
    var comparisonFunction = interpolationTest.options.comparisonFunction;
    var behavior = interpolationTest.options.behavior;

    if ((interpolationTest.options.method && interpolationTest.options.method != interpolationMethod.name)
      || !interpolationMethod.supportsProperty(property)
      || !interpolationMethod.supportsValue(from)
      || !interpolationMethod.supportsValue(to)) {
      return;
    }

    var testText = `${interpolationMethod.name}: property <${property}> from ${keyframeText(from)} to ${keyframeText(to)}`;
    var testContainer = createElement(interpolationMethodContainer, 'div');
    createElement(testContainer);
    var expectations = interpolationTest.expectations;
    var applyUnderlying = false;
    if (expectations === expectNoInterpolation) {
      expectations = interpolationMethod.nonInterpolationExpectations(from, to);
    } else if (expectations === expectNotAnimatable) {
      expectations = interpolationMethod.notAnimatableExpectations(from, to, interpolationTest.options.underlying);
      applyUnderlying = true;
    } else if (interpolationTest.options[interpolationMethod.name]) {
      expectations = interpolationTest.options[interpolationMethod.name];
    }

    // Setup a standard equality function if an override is not provided.
    if (!comparisonFunction) {
      comparisonFunction = (actual, expected) => {
        assert_equals(normalizeValue(actual), normalizeValue(expected));
      };
    }

    return expectations.map(function(expectation) {
      var actualTargetContainer = createTargetContainer(testContainer, 'actual');
      var expectedTargetContainer = createTargetContainer(testContainer, 'expected');
      var expectedProperties = expectation.option || expectation.expect;
      if (typeof expectedProperties !== "object") {
        expectedProperties = {[property]: expectedProperties};
      }
      var target = actualTargetContainer.target;
      if (applyUnderlying) {
        let underlying = interpolationTest.options.underlying;
        assert_true(typeof underlying !== 'undefined', '\'underlying\' value must be provided');
        assert_true(CSS.supports(property, underlying), '\'underlying\' value must be supported');
        target.style.setProperty(property, underlying);
      }
      interpolationMethod.setup(property, from, target);
      target.interpolate = function() {
        interpolationMethod.interpolate(property, from, to, expectation.at, target, behavior);
      };
      target.measure = function() {
        for (var [expectedProp, expectedStr] of Object.entries(expectedProperties)) {
          if (!isNeutralKeyframe(expectedStr)) {
            expectedTargetContainer.target.style.setProperty(expectedProp, expectedStr);
          }
          var expectedValue = getComputedStyle(expectedTargetContainer.target).getPropertyValue(expectedProp);
          let testName = `${testText} at (${expectation.at}) should be [${sanitizeUrls(expectedStr)}]`;
          if (property !== expectedProp) {
            testName += ` for <${expectedProp}>`;
          }
          test(function() {
            assert_true(interpolationMethod.isSupported(), `${interpolationMethod.name} should be supported`);

            if (from && from !== neutralKeyframe) {
              assert_true(CSS.supports(property, from), '\'from\' value should be supported');
            }
            if (to && to !== neutralKeyframe) {
              assert_true(CSS.supports(property, to), '\'to\' value should be supported');
            }
            if (typeof underlying !== 'undefined') {
              assert_true(CSS.supports(property, underlying), '\'underlying\' value should be supported');
            }

            comparisonFunction(
                getComputedStyle(target).getPropertyValue(expectedProp),
                expectedValue);
          }, testName);
        }
      };
      return target;
    });
  }

  function createCompositionTestTargets(compositionContainer, compositionTest) {
    var options = compositionTest.options;
    var property = options.property;
    var underlying = options.underlying;
    var comparisonFunction = options.comparisonFunction;
    var from = options.accumulateFrom || options.addFrom || options.replaceFrom;
    var to = options.accumulateTo || options.addTo || options.replaceTo;
    var fromComposite = 'accumulateFrom' in options ? 'accumulate' : 'addFrom' in options ? 'add' : 'replace';
    var toComposite = 'accumulateTo' in options ? 'accumulate' : 'addTo' in options ? 'add' : 'replace';
    const invalidFrom = 'addFrom' in options === 'replaceFrom' in options
        && 'addFrom' in options === 'accumulateFrom' in options;
    const invalidTo = 'addTo' in options === 'replaceTo' in options
        && 'addTo' in options === 'accumulateTo' in options;
    if (invalidFrom || invalidTo) {
      test(function() {
        assert_false(invalidFrom, 'Exactly one of accumulateFrom, addFrom, or replaceFrom must be specified');
        assert_false(invalidTo, 'Exactly one of accumulateTo, addTo, or replaceTo must be specified');
      }, `Composition tests must have valid setup`);
    }

    var testText = `Compositing: property <${property}> underlying [${underlying}] from ${fromComposite} [${from}] to ${toComposite} [${to}]`;
    var testContainer = createElement(compositionContainer, 'div');
    createElement(testContainer);

    // Setup a standard equality function if an override is not provided.
    if (!comparisonFunction) {
      comparisonFunction = (actual, expected) => {
        assert_equals(normalizeValue(actual), normalizeValue(expected));
      };
    }

    return compositionTest.expectations.map(function(expectation) {
      var actualTargetContainer = createTargetContainer(testContainer, 'actual');
      var expectedTargetContainer = createTargetContainer(testContainer, 'expected');
      var expectedStr = expectation.option || expectation.expect;
      if (!isNeutralKeyframe(expectedStr)) {
        expectedTargetContainer.target.style.setProperty(property, expectedStr);
      }
      var target = actualTargetContainer.target;
      target.style.setProperty(property, underlying);
      target.interpolate = function() {
        webAnimationsInterpolation.interpolateComposite(property, from, fromComposite, to, toComposite, expectation.at, target);
      };
      target.measure = function() {
        var expectedValue = getComputedStyle(expectedTargetContainer.target).getPropertyValue(property);
        test(function() {

          if (from && from !== neutralKeyframe) {
            assert_true(CSS.supports(property, from), '\'from\' value should be supported');
          }
          if (to && to !== neutralKeyframe) {
            assert_true(CSS.supports(property, to), '\'to\' value should be supported');
          }
          if (typeof underlying !== 'undefined') {
            assert_true(CSS.supports(property, underlying), '\'underlying\' value should be supported');
          }

          comparisonFunction(
              getComputedStyle(target).getPropertyValue(property),
              expectedValue);
        }, `${testText} at (${expectation.at}) should be [${sanitizeUrls(expectedStr)}]`);
      };
      return target;
    });
  }



  function createTestTargets(interpolationMethods, interpolationTests, compositionTests, container) {
    var targets = [];
    for (var interpolationMethod of interpolationMethods) {
      var interpolationMethodContainer = createElement(container);
      for (var interpolationTest of interpolationTests) {
        if(!interpolationTest.options.target_names ||
           interpolationTest.options.target_names.includes(interpolationMethod.name)) {
            [].push.apply(targets, createInterpolationTestTargets(interpolationMethod, interpolationMethodContainer, interpolationTest));
          }
      }
    }
    var compositionContainer = createElement(container);
    for (var compositionTest of compositionTests) {
      [].push.apply(targets, createCompositionTestTargets(compositionContainer, compositionTest));
    }
    return targets;
  }

  function test_no_interpolation(options) {
    test_interpolation(options, expectNoInterpolation);
  }
  function test_not_animatable(options) {
    test_interpolation(options, expectNotAnimatable);
  }
  function create_tests(addAllowDiscreteTests) {
    var interpolationMethods = [
      cssTransitionsInterpolation,
      cssTransitionAllInterpolation,
      cssAnimationsInterpolation,
      webAnimationsInterpolation,
    ];
    if (addAllowDiscreteTests) {
      interpolationMethods = [
        cssTransitionsInterpolationAllowDiscrete,
        cssTransitionAllInterpolationAllowDiscrete,
      ].concat(interpolationMethods);
    }
    var container = createElement(document.body);
    var targets = createTestTargets(interpolationMethods, interpolationTests, compositionTests, container);
    // Separate interpolation and measurement into different phases to avoid O(n^2) of the number of targets.
    for (var target of targets) {
      target.interpolate();
    }
    for (var target of targets) {
      target.measure();
    }
    container.remove();
  }

  function test_interpolation(options, expectations) {
    interpolationTests.push({options, expectations});
    create_tests(expectations === expectNoInterpolation || expectations === expectNotAnimatable);
    interpolationTests = [];
  }
  function test_composition(options, expectations) {
    compositionTests.push({options, expectations});
    create_tests();
    compositionTests = [];
  }
  window.test_interpolation = test_interpolation;
  window.test_no_interpolation = test_no_interpolation;
  window.test_not_animatable = test_not_animatable;
  window.test_composition = test_composition;
  window.neutralKeyframe = neutralKeyframe;
  window.roundNumbers = roundNumbers;
  window.normalizeValue = normalizeValue;
})();