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/9 add use resize observer hook #18

Open
wants to merge 2 commits into
base: main
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
2 changes: 1 addition & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ module.exports = {
// setupFilesAfterEnv: ['<rootDir>/test-utils/setupTests.js'],
// added "(?<!types.)" as a negative lookbehind to the default pattern
// to exclude .types.test.ts patterns fro being picked up by jest
testRegex: '(/__tests__/.*|(\\.|/)(?<!types.)(test|spec))\\.[jt]sx?$'
testRegex: '(/__tests__/.*|(\\.|/)(?<!types.)(test|spec))\\.[jt]sx?$',
};
67 changes: 51 additions & 16 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
"@types/jest": "^26.0.15",
"babel-jest": "^26.6.3",
"jest": "^26.3.0",
"jsdom-testing-mocks": "^1.2.2",
"nanoid": "^3.1.30",
"npm-run-all": "^4.1.5",
"plop": "^3.0.6",
Expand All @@ -83,5 +84,9 @@
},
"engines": {
"npm": ">= 7.0.0"
},
"dependencies": {
"@types/lodash-es": "^4.17.6",
"lodash-es": "^4.17.21"
}
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/* PLOP_ADD_EXPORT */
export * from './useResizeObserver/useResizeObserver';
export * from './useToggle/useToggle';
export * from './useEventListener/useEventListener';
export * from './useKeyboardEvent/useKeyboardEvent';
Expand Down
60 changes: 60 additions & 0 deletions src/useResizeObserver/useResizeObserver.stories.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { Meta } from '@storybook/addon-docs';

<Meta
title="useResizeObserver/docs"
/>

# useResizeObserver

Please add a description about the `useResizeObserver` hook.

## Reference

```ts
function useResizeObserver(
source: DomElementOrRef,
callback: KeyDownCallback,
debounceTime?: number,
): void
```

### Parameters

* `source` - The DOM Element or Ref that you want to observe for resizes.
* `callback` - The function to invoke when the source is resized.
* `debounceTime` - The amount of debounce you want to apply to the callback function.

### Returns

* `void`

## Usage

```ts
useResizeObserver(refs.someRef, () => {
console.log('someRef was resized!')
}, 100);
````

```ts
const Demo = defineComponent({
name: 'demo',
refs: {
someRef: 'some-ref',
},
setup({ refs }) {

// The most basic implementation of watching an element for resizes.
useResizeObserver(refs.someRef, () => {
console.log('someRef was resized')
});

// The callback method can easily be debounced to reduce the amount of triggers.
useResizeObserver(refs.someRef, () => {
console.log('someRef was resized.')
}, 500);

return [];
}
})
```
68 changes: 68 additions & 0 deletions src/useResizeObserver/useResizeObserver.stories.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/* eslint-disable import/no-extraneous-dependencies */
import { bind, computed, defineComponent, ref } from '@muban/muban';
import type { Story } from '@muban/storybook/types-6-0';
import { html } from '@muban/template';
import { useResizeObserver } from './useResizeObserver';
import { useStorybookLog } from '../hooks/useStorybookLog';

export default {
title: 'useResizeObserver',
};

export const Demo: Story = () => ({
component: defineComponent({
name: 'story',
refs: {
testArea: 'test-area',
label: 'label',
resizeButton: 'resize-button',
},
setup({ refs }) {
const [logBinding, log] = useStorybookLog(refs.label);
const width = ref(100);

function onResizeObserverUpdate(): void {
log('resize observer triggered');
}

useResizeObserver(refs.testArea, onResizeObserverUpdate, 100);

return [
logBinding,
bind(refs.testArea, {
style: {
width: computed(() => `${width.value}%`),
},
}),
bind(refs.resizeButton, {
click() {
const newWidth = width.value - 25;
width.value = newWidth > 0 ? newWidth : 100;
},
}),
];
},
}),
template: () => html`<div data-component="story">
<div class="alert alert-primary">
<h4 class="alert-heading">Instructions!</h4>
<p>Resize the window or click on the resize button to see the events being triggered.</p>
<p class="mb-0">
Note: The <code>callback</code> is debounced by <u>100ms</u> to avoid it from being called
way too much for the sake of the demo.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

too often

</p>
</div>
<div data-ref="label" />
<div class="card border-dark" data-ref="test-area">
<div class="card-header">Test Area</div>
<div class="card-body">
<p>
The resize observer is attached to this element, so it will trigger the callback method if
it's resized.
</p>
<button type="button" data-ref="resize-button" class="btn btn-success">Resize</button>
</div>
</div>
</div>`,
});
Demo.storyName = 'demo';
52 changes: 52 additions & 0 deletions src/useResizeObserver/useResizeObserver.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { createMockElementRef, runComponentSetup } from '@muban/test-utils';
import { mockResizeObserver } from 'jsdom-testing-mocks';
import { useResizeObserver } from './useResizeObserver';
import { timeout } from './useResizeObserver.test.utils';

jest.mock('@muban/muban', () => jest.requireActual('@muban/test-utils').getMubanLifecycleMock());

const resizeObserver = mockResizeObserver();

describe('useResizeObserver', () => {
it('should not crash', () => {
const { ref } = createMockElementRef();

runComponentSetup(() => {
useResizeObserver(ref, () => undefined);
});
});

it('should attach a resize observer to a ref', async () => {
const mockHandler = jest.fn();
const { ref, target } = createMockElementRef();

await runComponentSetup(
() => {
useResizeObserver(ref, mockHandler);
},
async () => {
resizeObserver.resize(target);
await timeout(0);
},
);

expect(mockHandler).toBeCalledTimes(1);
});

it('should attach a resize observer to a HTML element', async () => {
const mockHandler = jest.fn();
const { target } = createMockElementRef();

await runComponentSetup(
() => {
useResizeObserver(target, mockHandler);
},
async () => {
resizeObserver.resize(target);
await timeout(0);
},
);

expect(mockHandler).toBeCalledTimes(1);
});
});
17 changes: 17 additions & 0 deletions src/useResizeObserver/useResizeObserver.test.utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* A helper method that allows you to easily create a timeout with the async/await notation
*
* ```ts
* async function someFunction(){
* await timeout(100);
* console.log('This is delayed by 100ms');
* }
* ```
*
* @param duration The duration that you want to create the timeout for.
*/
export async function timeout(duration: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, duration);
});
}
Loading