utils.js (2376B)
1 // Register a property, and interpolate its value to the halfway point. 2 function registerAndInterpolateProperty(options) { 3 CSS.registerProperty({ 4 name: options.name, 5 syntax: `${options.syntax} | none`, 6 initialValue: 'none', 7 inherits: false 8 }); 9 let animation = options.on.animate([ 10 { [options.name]: options.from }, 11 { [options.name]: options.to } 12 ], 1000); 13 animation.currentTime = 500; 14 animation.pause(); 15 } 16 17 // Apply a paint worklet to 'target' which verifies that the worklet-side value 18 // of a set of properties is what we expect. 19 // 20 // The 'expected' parameter is an object where each key is the name of a 21 // property to check, and each corresponding value is an array with the expected 22 // (serialized) values for that property. 23 function expectWorkletValues(target, expected) { 24 const workletName = 'registered-property-value'; 25 26 // Wrap any single values in an array. This makes it possible to omit the 27 // array if there is only one value. 28 const ensureArray = x => x.constructor === Array ? x : [x]; 29 expected = Object.entries(expected).map(([k, v]) => [k, ensureArray(v)]) 30 .map(x => ({[x[0]]: x[1]})) 31 .reduce((a, b) => Object.assign(a, b), {}); 32 33 target.style.setProperty('width', '100px'); 34 target.style.setProperty('height', '100px'); 35 target.style.setProperty('background-image', `paint(${workletName})`); 36 37 const worklet = ` 38 const expectedData = ${JSON.stringify(expected)}; 39 const expectedKeys = Object.keys(expectedData).sort(); 40 registerPaint('${workletName}', class { 41 static get inputProperties() { return expectedKeys; } 42 paint(ctx, geom, styleMap) { 43 let serialize = (v) => '[' + v.constructor.name + ' ' + v.toString() + ']'; 44 let actual = expectedKeys.map(k => styleMap.getAll(k).map(serialize).join(', ')).join(' | '); 45 let expected = expectedKeys.map(k => expectedData[k].join(', ')).join(' | '); 46 ctx.fillStyle = (actual === expected) ? 'green' : 'red'; 47 ctx.fillRect(0, 0, geom.width, geom.height); 48 } 49 });` 50 51 importWorkletAndTerminateTestAfterAsyncPaint(CSS.paintWorklet, worklet); 52 } 53 54 // Like expectWorkletValues, but can only test a single property. 55 function expectWorkletValue(target, property, expected) { 56 expectWorkletValues(target, { [property]: expected }); 57 }