Skip to content

Commit 3cb2ac2

Browse files
authored
perf(core): cache media query matches between device changes (#11512)
[skip ci]
1 parent e58b67f commit 3cb2ac2

8 files changed

Lines changed: 297 additions & 18 deletions

File tree

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { setToggleApplicationEventListenersCallback, toggleApplicationEventListeners } from './helpers-common';
2+
3+
describe('toggleApplicationEventListeners', () => {
4+
it('replays listeners requested before the platform handler is installed', () => {
5+
const handled: Array<[boolean, (args: any) => void]> = [];
6+
const early = () => {};
7+
const withdrawn = () => {};
8+
9+
toggleApplicationEventListeners(true, early);
10+
toggleApplicationEventListeners(true, withdrawn);
11+
toggleApplicationEventListeners(false, withdrawn);
12+
13+
setToggleApplicationEventListenersCallback((toAdd, callback) => handled.push([toAdd, callback]));
14+
15+
expect(handled).toEqual([[true, early]]);
16+
17+
const late = () => {};
18+
toggleApplicationEventListeners(true, late);
19+
20+
expect(handled).toEqual([
21+
[true, early],
22+
[true, late],
23+
]);
24+
});
25+
});

‎packages/core/application/helpers-common.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,13 +144,24 @@ export function setAppMainEntry(entry: any /* NavigationEntry */) {
144144

145145
// Aids avoiding circular dependencies by allowing the application event listeners to be toggled
146146
let _toggleApplicationEventListenersHandler: (toAdd: boolean, callback: (args: any) => void) => void;
147+
// Listeners requested before the platform installs its handler
148+
const _pendingApplicationEventListeners = new Set<(args: any) => void>();
147149
export function toggleApplicationEventListeners(toAdd: boolean, callback: (args: any) => void) {
148150
if (_toggleApplicationEventListenersHandler) {
149151
_toggleApplicationEventListenersHandler(toAdd, callback);
152+
} else if (toAdd) {
153+
_pendingApplicationEventListeners.add(callback);
154+
} else {
155+
_pendingApplicationEventListeners.delete(callback);
150156
}
151157
}
152158
export function setToggleApplicationEventListenersCallback(callback: (toAdd: boolean, callback: (args: any) => void) => void) {
153159
_toggleApplicationEventListenersHandler = callback;
160+
161+
for (const listener of _pendingApplicationEventListeners) {
162+
callback(true, listener);
163+
}
164+
_pendingApplicationEventListeners.clear();
154165
}
155166

156167
// Aids avoiding circular dependencies by allowing the application properties to be retrieved

‎packages/core/css-mediaquery/index.spec.ts‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,26 @@
1-
import { MediaQueryType, matchQuery, parseQuery } from '.';
1+
import { MediaQueryType, isEvaluableMediaQuery, matchQuery, parseQuery } from '.';
22

33
describe('css-mediaquery', () => {
4+
describe('isEvaluableMediaQuery', () => {
5+
it('accepts queries built only from evaluable features', () => {
6+
expect(isEvaluableMediaQuery('(orientation: landscape)')).toBe(true);
7+
expect(isEvaluableMediaQuery('only screen and (min-width: 100) and (max-height: 200)')).toBe(true);
8+
expect(isEvaluableMediaQuery('(prefers-color-scheme: dark), (device-width: 1024)')).toBe(true);
9+
expect(isEvaluableMediaQuery('screen')).toBe(true);
10+
});
11+
12+
it('rejects queries with a feature the runtime cannot evaluate', () => {
13+
expect(isEvaluableMediaQuery('(color-gamut: p3)')).toBe(false);
14+
expect(isEvaluableMediaQuery('(orientation: landscape) and (hover: hover)')).toBe(false);
15+
expect(isEvaluableMediaQuery('(orientation: landscape), (prefers-reduced-motion: reduce)')).toBe(false);
16+
});
17+
18+
it('rejects invalid queries', () => {
19+
expect(isEvaluableMediaQuery('some crap')).toBe(false);
20+
expect(isEvaluableMediaQuery('48em')).toBe(false);
21+
});
22+
});
23+
424
describe('parseQuery', () => {
525
it('should parse media queries without expressions', () => {
626
expect(parseQuery('screen')).toEqual([

‎packages/core/css-mediaquery/index.ts‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,38 @@ export interface MediaQueryFeature {
4949
value: string;
5050
}
5151

52+
const EVALUABLE_FEATURES = new Set<string>(['width', 'height', 'device-width', 'device-height', 'orientation', 'prefers-color-scheme']);
53+
54+
const parsedQueryCache = new Map<string, MediaQueryExpression[]>();
55+
56+
function getParsedQuery(mediaQuery: string): MediaQueryExpression[] {
57+
let expressions = parsedQueryCache.get(mediaQuery);
58+
if (!expressions) {
59+
expressions = parseQuery(mediaQuery);
60+
parsedQueryCache.set(mediaQuery, expressions);
61+
}
62+
63+
return expressions;
64+
}
65+
66+
/**
67+
* Whether a media query is valid and uses only features the runtime can evaluate.
68+
* @param mediaQuery The media query string.
69+
*/
70+
export function isEvaluableMediaQuery(mediaQuery: string): boolean {
71+
let expressions: MediaQueryExpression[];
72+
73+
try {
74+
expressions = getParsedQuery(mediaQuery);
75+
} catch {
76+
return false;
77+
}
78+
79+
return expressions.every((query) => query.features.every((feature) => EVALUABLE_FEATURES.has(feature.property)));
80+
}
81+
5282
export function matchQuery(mediaQuery: string, values: MediaQueryEnvironmentParams): boolean {
53-
const expressions = parseQuery(mediaQuery);
83+
const expressions = getParsedQuery(mediaQuery);
5484

5585
return expressions.some((query) => {
5686
const { type, inverse, features } = query;

‎packages/core/media-query-list/index.ts‎

Lines changed: 64 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,35 @@ import { EventData, Observable } from '../data/observable';
22
import { Screen } from '../platform/screen';
33
import { getApplicationProperties, toggleApplicationEventListeners } from '../application/helpers-common';
44
import type { ApplicationEventData } from '../application/application-interfaces';
5-
import { matchQuery, MediaQueryType } from '../css-mediaquery';
5+
import { isEvaluableMediaQuery, matchQuery, MediaQueryType } from '../css-mediaquery';
66
import { Trace } from '../trace';
77

88
const mediaQueryLists: MediaQueryListImpl[] = [];
99

1010
// In browser, developers cannot create MediaQueryList instances without calling matchMedia
1111
let isMediaInitializationEnabled: boolean = false;
1212

13+
// Query results only change with orientation, appearance or screen metrics.
14+
const matchResultCache = new Map<string, boolean>();
15+
let isCacheInvalidationRegistered = false;
16+
17+
function clearMatchResultCache() {
18+
matchResultCache.clear();
19+
}
20+
21+
function registerCacheInvalidation() {
22+
if (isCacheInvalidationRegistered) {
23+
return;
24+
}
25+
26+
isCacheInvalidationRegistered = true;
27+
toggleApplicationEventListeners(true, clearMatchResultCache);
28+
}
29+
1330
function onDeviceChange(args: ApplicationEventData) {
31+
// Listener order is not guaranteed, so never re-evaluate against stale results
32+
clearMatchResultCache();
33+
1434
for (const mql of mediaQueryLists) {
1535
const matches = checkIfMediaQueryMatches(mql.media);
1636
if (mql.matches !== matches) {
@@ -27,26 +47,55 @@ function onDeviceChange(args: ApplicationEventData) {
2747
}
2848

2949
function checkIfMediaQueryMatches(mediaQueryString: string): boolean {
30-
const { widthPixels, heightPixels } = Screen.mainScreen;
50+
const cachedResult = matchResultCache.get(mediaQueryString);
51+
if (cachedResult !== undefined) {
52+
return cachedResult;
53+
}
3154

3255
let matches: boolean;
3356

34-
try {
35-
const appProperties = getApplicationProperties();
36-
matches = matchQuery(mediaQueryString, {
37-
type: MediaQueryType.screen,
38-
width: widthPixels,
39-
height: heightPixels,
40-
'device-width': widthPixels,
41-
'device-height': heightPixels,
42-
orientation: appProperties.orientation,
43-
'prefers-color-scheme': appProperties.systemAppearance,
44-
});
45-
} catch (err) {
57+
if (isEvaluableMediaQuery(mediaQueryString)) {
58+
registerCacheInvalidation();
59+
60+
// Native reads are deferred until a feature in the query asks for them
61+
let screenPixels: { width: number; height: number };
62+
let appProperties: ReturnType<typeof getApplicationProperties>;
63+
const getScreenPixels = () => (screenPixels ??= { width: Screen.mainScreen.widthPixels, height: Screen.mainScreen.heightPixels });
64+
const getAppProperties = () => (appProperties ??= getApplicationProperties());
65+
66+
try {
67+
matches = matchQuery(mediaQueryString, {
68+
type: MediaQueryType.screen,
69+
get width() {
70+
return getScreenPixels().width;
71+
},
72+
get height() {
73+
return getScreenPixels().height;
74+
},
75+
get 'device-width'() {
76+
return getScreenPixels().width;
77+
},
78+
get 'device-height'() {
79+
return getScreenPixels().height;
80+
},
81+
get orientation() {
82+
return getAppProperties().orientation;
83+
},
84+
get 'prefers-color-scheme'() {
85+
return getAppProperties().systemAppearance;
86+
},
87+
});
88+
} catch (err) {
89+
matches = false;
90+
Trace.write(err, Trace.categories.MediaQuery, Trace.messageType.error);
91+
}
92+
} else {
4693
matches = false;
47-
Trace.write(err, Trace.categories.MediaQuery, Trace.messageType.error);
94+
Trace.write(`Media query '${mediaQueryString}' cannot be evaluated and will never match`, Trace.categories.MediaQuery, Trace.messageType.warn);
4895
}
4996

97+
matchResultCache.set(mediaQueryString, matches);
98+
5099
return matches;
51100
}
52101

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
import { vi } from 'vitest';
2+
3+
const device = vi.hoisted(() => ({
4+
orientation: 'portrait',
5+
listeners: new Set<(args: any) => void>(),
6+
propertyReads: 0,
7+
}));
8+
9+
vi.mock('../application/helpers-common', async (importOriginal) => ({
10+
...(await importOriginal<typeof import('../application/helpers-common')>()),
11+
getApplicationProperties: () => {
12+
device.propertyReads++;
13+
14+
return { orientation: device.orientation, systemAppearance: 'light' };
15+
},
16+
toggleApplicationEventListeners: (toAdd: boolean, callback: (args: any) => void) => {
17+
if (toAdd) {
18+
device.listeners.add(callback);
19+
} else {
20+
device.listeners.delete(callback);
21+
}
22+
},
23+
}));
24+
25+
import { checkIfMediaQueryMatches, matchMedia } from '.';
26+
import { Screen } from '../platform/screen';
27+
28+
function notifyDeviceChange() {
29+
for (const listener of [...device.listeners]) {
30+
listener({ eventName: 'orientationChanged' });
31+
}
32+
}
33+
34+
describe('media-query-list match cache', () => {
35+
const portraitQuery = '(orientation: portrait)';
36+
37+
beforeEach(() => {
38+
device.orientation = 'portrait';
39+
notifyDeviceChange();
40+
});
41+
42+
it('reuses a result until the device changes', () => {
43+
expect(checkIfMediaQueryMatches(portraitQuery)).toBe(true);
44+
45+
const readsAfterFirstCheck = device.propertyReads;
46+
device.orientation = 'landscape';
47+
48+
expect(checkIfMediaQueryMatches(portraitQuery)).toBe(true);
49+
expect(device.propertyReads).toBe(readsAfterFirstCheck);
50+
51+
notifyDeviceChange();
52+
53+
expect(checkIfMediaQueryMatches(portraitQuery)).toBe(false);
54+
expect(device.propertyReads).toBe(readsAfterFirstCheck + 1);
55+
});
56+
57+
it('reads no device state for a query it cannot evaluate', () => {
58+
const unsupportedQuery = '(color-gamut: p3)';
59+
const screenReads = vi.spyOn(Screen.mainScreen, 'widthPixels', 'get');
60+
const readsBefore = device.propertyReads;
61+
62+
expect(checkIfMediaQueryMatches(unsupportedQuery)).toBe(false);
63+
expect(checkIfMediaQueryMatches(unsupportedQuery)).toBe(false);
64+
expect(device.propertyReads).toBe(readsBefore);
65+
expect(screenReads).not.toHaveBeenCalled();
66+
67+
screenReads.mockRestore();
68+
});
69+
70+
it('reads only the device state the query names', () => {
71+
const widthQuery = `(max-width: ${Screen.mainScreen.widthDIPs})`;
72+
const screenReads = vi.spyOn(Screen.mainScreen, 'widthPixels', 'get');
73+
const readsBefore = device.propertyReads;
74+
75+
expect(checkIfMediaQueryMatches(widthQuery)).toBe(true);
76+
expect(device.propertyReads).toBe(readsBefore);
77+
expect(screenReads).toHaveBeenCalled();
78+
79+
screenReads.mockClear();
80+
81+
expect(checkIfMediaQueryMatches('(orientation: portrait)')).toBe(true);
82+
expect(device.propertyReads).toBe(readsBefore + 1);
83+
expect(screenReads).not.toHaveBeenCalled();
84+
85+
screenReads.mockRestore();
86+
});
87+
88+
it('keeps MediaQueryList change notifications in sync with the cache', () => {
89+
expect(checkIfMediaQueryMatches(portraitQuery)).toBe(true);
90+
91+
const mql = matchMedia(portraitQuery);
92+
let notifiedMatches: boolean | undefined;
93+
mql.addEventListener('change', (data: any) => {
94+
notifiedMatches = data.matches;
95+
});
96+
97+
device.orientation = 'landscape';
98+
notifyDeviceChange();
99+
100+
expect(mql.matches).toBe(false);
101+
expect(notifiedMatches).toBe(false);
102+
expect(checkIfMediaQueryMatches(portraitQuery)).toBe(false);
103+
});
104+
});

‎packages/core/ui/styling/style-scope.spec.ts‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { describe, it, expect, beforeAll } from 'vitest';
22

3-
import { StyleScope, applyInlineStyle, addTaggedAdditionalCSS, removeTaggedAdditionalCSS } from './style-scope';
3+
import { StyleScope, _populateRules, applyInlineStyle, addTaggedAdditionalCSS, removeTaggedAdditionalCSS } from './style-scope';
4+
import { parse } from '../../css/reworkcss.js';
5+
import type { RuleSet } from './css-selector';
46
import { StackLayout } from '../layouts/stack-layout';
57
import { Label } from '../label';
68

@@ -475,3 +477,34 @@ describe('CssState.onChange subscriptions', () => {
475477
expect(view.style.color.toString()).toBe('#0000FF');
476478
});
477479
});
480+
481+
describe('_populateRules media scopes', () => {
482+
function rulesetsOf(css: string): RuleSet[] {
483+
const rulesets: RuleSet[] = [];
484+
_populateRules(parse(css, { source: 'style-scope.spec.ts' }).stylesheet.rules, rulesets, []);
485+
486+
return rulesets;
487+
}
488+
489+
it('drops media blocks the runtime cannot evaluate and keeps the rest', () => {
490+
const rulesets = rulesetsOf(`
491+
label { color: red; }
492+
@media (color-gamut: p3) { label { color: blue; } }
493+
@media (orientation: landscape) { label { color: green; } }
494+
`);
495+
496+
expect(rulesets.map((ruleset) => ruleset.mediaQueryString)).toEqual([undefined, '(orientation: landscape)']);
497+
});
498+
499+
it('drops an unevaluable block nested inside an evaluable one', () => {
500+
const rulesets = rulesetsOf(`
501+
@media (orientation: landscape) {
502+
label { color: red; }
503+
@media (hover: hover) { label { color: blue; } }
504+
}
505+
`);
506+
507+
expect(rulesets).toHaveLength(1);
508+
expect(rulesets[0].mediaQueryString).toBe('(orientation: landscape)');
509+
});
510+
});

‎packages/core/ui/styling/style-scope.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import * as ReworkCSS from '../../css';
77

88
import { RuleSet, StyleSheetSelectorScope, SelectorCore, SelectorTier, SelectorsMatch, ChangeMap, Changes, fromAstNode, Node, matchMediaQueryString, matchSelectorCandidates } from './css-selector';
99
import { Trace } from './styling-shared';
10+
import { isEvaluableMediaQuery } from '../../css-mediaquery';
1011
import { File, knownFolders, path } from '../../file-system';
1112
import { Application, CssChangedEventData, LoadAppCSSEventData } from '../../application';
1213
import { profile } from './styling-profile';
@@ -518,6 +519,12 @@ export function _populateRules(nodes: ReworkCSS.Node[], rulesets: RuleSet[], key
518519

519520
keyframes.push(keyframeRule);
520521
} else if (isMedia(node)) {
522+
// A query the runtime cannot evaluate never matches, so its rules are dead weight
523+
if (!isEvaluableMediaQuery(node.media)) {
524+
Trace.write(`Dropping '@media ${node.media}': the runtime cannot evaluate it`, Trace.categories.MediaQuery, Trace.messageType.warn);
525+
continue;
526+
}
527+
521528
// Media query can be an array of strings in case of nested queries
522529
let compositeMediaQuery: string | string[];
523530

0 commit comments

Comments
 (0)