Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature] Improve breakpoint performance #589

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ All notable changes to this project will be documented in this file. The format

- **withScrolledInView:** fix `scrolledInView` method not being triggered on mount ([#584](https://github.com/studiometa/js-toolkit/pull/584), [244f1c57](https://github.com/studiometa/js-toolkit/commit/244f1c57))

### Changed

- **useResize:** improve breakpoint retrieval performance ([#589](https://github.com/studiometa/js-toolkit/pull/589), [a35ee52e](https://github.com/studiometa/js-toolkit/commit/a35ee52e))

## [v3.0.0](https://github.com/studiometa/js-toolkit/compare/2.12.0..3.0.0) (2025-01-16)

After 9 months of development, v3.0 is finally here! It is packed with more stability, capabilities and without previously deprecated APIs. Make sure to read the [migration guide](https://js-toolkit.studiometa.dev/guide/migration/v2-to-v3.html) to learn more about all the changes and how to upgrade, as you will need to edit some parts of existing components.
Expand Down
6 changes: 5 additions & 1 deletion packages/docs/utils/cache.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
# cache

Cache the result of a function with a single key or a list of keys.
Cache the result of a function with a single key or a list of keys in nested maps.

::: warning
The `cache` function is global, meaning that keys are share across all `cache` calls in different files for the same runtime. Make sure to use a local context variable as the first key to avoid sharing cache between unrelated contexts.
:::

## Usage

Expand Down
6 changes: 5 additions & 1 deletion packages/js-toolkit/services/ResizeService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { AbstractService } from './AbstractService.js';
import type { Features } from '../Base/features.js';
import { features } from '../Base/features.js';
import { debounce } from '../utils/debounce.js';
import { cache } from '../utils/cache.js';

export interface ResizeServiceProps<U extends Features['breakpoints'] = Features['breakpoints']> {
width: number;
Expand Down Expand Up @@ -51,7 +52,10 @@ export class ResizeService<
for (const [name, breakpoint] of Object.entries(
this.breakpoints ?? features.get('breakpoints'),
)) {
activeBreakpoints[name] = window.matchMedia(`(min-width: ${breakpoint})`).matches;
activeBreakpoints[name] = cache(
[this, window.innerWidth, window.innerHeight, breakpoint],
() => window.matchMedia(`(min-width: ${breakpoint})`).matches,
);
}

return activeBreakpoints as Record<keyof T, boolean>;
Expand Down
10 changes: 5 additions & 5 deletions packages/tests/decorators/withBreakpointObserver.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ describe('The withBreakpointObserver decorator', () => {
it('should re-mount component when deleting both breakpoint options', async () => {
const { fooResponsive, matchMedia } = await getContext();
matchMedia.useMediaQuery('(min-width: 48rem)');
await resizeWindow({ width: 768 });
await resizeWindow({ width: 766 });

expect(fooResponsive[1].$isMounted).toBe(true);
matchMedia.useMediaQuery('(min-width: 64rem)');
Expand All @@ -103,7 +103,7 @@ describe('The withBreakpointObserver decorator', () => {
fooResponsive[1].$el.removeAttribute('data-option-active-breakpoints');
fooResponsive[1].$el.removeAttribute('data-option-inactive-breakpoints');
matchMedia.useMediaQuery('(min-width: 48rem)');
await resizeWindow({ width: 768 });
await resizeWindow({ width: 766 });

expect(fooResponsive[1].$isMounted).toBe(true);
});
Expand Down Expand Up @@ -181,7 +181,7 @@ describe('The withBreakpointObserver decorator', () => {
`;

matchMedia.useMediaQuery('(min-width: 64rem)');
await resizeWindow({ width: 1024 });
await resizeWindow({ width: 1025 });

await new App1(root).$mount();
expect(fn.mock.calls).toMatchInlineSnapshot(`
Expand All @@ -195,7 +195,7 @@ describe('The withBreakpointObserver decorator', () => {
fn.mockClear();

matchMedia.useMediaQuery('(min-width: 48rem)');
await resizeWindow({ width: 768 });
await resizeWindow({ width: 769 });

expect(fn.mock.calls).toMatchInlineSnapshot(`
[
Expand All @@ -212,7 +212,7 @@ describe('The withBreakpointObserver decorator', () => {
fn.mockClear();

matchMedia.useMediaQuery('(min-width: 64rem)');
await resizeWindow({ width: 1024 });
await resizeWindow({ width: 1025 });

expect(fn.mock.calls).toMatchInlineSnapshot(`
[
Expand Down
8 changes: 5 additions & 3 deletions packages/tests/services/ResizeService.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,18 +29,20 @@ describe('The `useResize` service', () => {
expect(fn).not.toHaveBeenCalled();
});

it('should return the current active breakpoint', () => {
const service = useResize({ s: '0px', m: '1024px', l: '2048px' });
it('should return the current active breakpoint', async () => {
const service = useResize({ s: '0px', m: '1025px', l: '2048px' });
expect(service.props().breakpoints).toEqual(['s', 'm', 'l']);

useMatchMedia('(min-width: 1024px)');
await resizeWindow({ width: 1025 });
useMatchMedia('(min-width: 1025px)');
expect(service.props().activeBreakpoints).toEqual({
s: false,
m: true,
l: false,
});
expect(service.props().breakpoint).toBe('m');

await resizeWindow({ width: 2048 });
useMatchMedia('(min-width: 2048px)');
expect(service.props().activeBreakpoints).toEqual({
s: false,
Expand Down