Skip to content

[LiveComponents] Stop polling if data-poll disappears #385

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

Merged
merged 1 commit into from
Jul 8, 2022
Merged
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
38 changes: 27 additions & 11 deletions src/LiveComponent/assets/src/live_controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,9 +108,7 @@ export default class extends Controller implements LiveController {
throw new Error('Invalid Element Type');
}

if (this.element.dataset.poll !== undefined) {
this._initiatePolling(this.element.dataset.poll);
}
this._initiatePolling();

window.addEventListener('beforeunload', this.markAsWindowUnloaded);
this._startAttributesMutationObserver();
Expand All @@ -123,9 +121,7 @@ export default class extends Controller implements LiveController {
}

disconnect() {
this.pollingIntervals.forEach((interval) => {
clearInterval(interval);
});
this._stopAllPolling();

window.removeEventListener('beforeunload', this.markAsWindowUnloaded);
this.element.removeEventListener('live:update-model', this.handleUpdateModelEvent);
Expand Down Expand Up @@ -794,7 +790,14 @@ export default class extends Controller implements LiveController {
this._updateModelFromElement(target, 'change')
}

_initiatePolling(rawPollConfig: string) {
_initiatePolling() {
this._stopAllPolling();

if ((this.element as HTMLElement).dataset.poll === undefined) {
return;
}

const rawPollConfig = (this.element as HTMLElement).dataset.poll;
const directives = parseDirectives(rawPollConfig || '$render');

directives.forEach((directive) => {
Expand Down Expand Up @@ -959,7 +962,10 @@ export default class extends Controller implements LiveController {
}

/**
* Re-establishes the data-original-data attribute if missing.
* Helps "re-normalize" certain root element attributes after a re-render.
*
* 1) Re-establishes the data-original-data attribute if missing.
* 2) Stops or re-initializes data-poll
*
* This happens if a parent component re-renders a child component
* and morphdom *updates* child. This commonly happens if a parent
Expand All @@ -979,9 +985,13 @@ export default class extends Controller implements LiveController {

this.mutationObserver = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === 'attributes' && !element.dataset.originalData) {
this.originalDataJSON = this.valueStore.asJson();
this._exposeOriginalData();
if (mutation.type === 'attributes') {
if (!element.dataset.originalData) {
this.originalDataJSON = this.valueStore.asJson();
this._exposeOriginalData();
}

this._initiatePolling();
}
});
});
Expand All @@ -994,6 +1004,12 @@ export default class extends Controller implements LiveController {
private getDefaultDebounce(): number {
return this.hasDebounceValue ? this.debounceValue : DEFAULT_DEBOUNCE;
}

private _stopAllPolling() {
this.pollingIntervals.forEach((interval) => {
clearInterval(interval);
});
}
}

/**
Expand Down
188 changes: 188 additions & 0 deletions src/LiveComponent/assets/test/controller/poll.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

'use strict';

import { shutdownTest, createTest, initComponent } from '../tools';
import { waitFor } from '@testing-library/dom';

describe('LiveController polling Tests', () => {
afterEach(() => {
shutdownTest();
})

it('starts a poll', async () => {
const test = await createTest({ renderCount: 0 }, (data: any) => `
<div ${initComponent(data)} data-poll>
<span>Render count: ${data.renderCount}</span>
</div>
`);

// poll 1
test.expectsAjaxCall('get')
.expectSentData(test.initialData)
.serverWillChangeData((data: any) => {
data.renderCount = 1;
})
.init();
// poll 2
test.expectsAjaxCall('get')
.expectSentData({renderCount: 1})
.serverWillChangeData((data: any) => {
data.renderCount = 2;
})
.init();

await waitFor(() => expect(test.element).toHaveTextContent('Render count: 1'), {
timeout: 2100
});
await waitFor(() => expect(test.element).toHaveTextContent('Render count: 2'), {
timeout: 2100
});
});

it('is controllable via modifiers', async () => {
const test = await createTest({ renderCount: 0 }, (data: any) => `
<div ${initComponent(data)} data-poll="delay(500)|$render">
<span>Render count: ${data.renderCount}</span>
</div>
`);

// poll 1
test.expectsAjaxCall('get')
.expectSentData(test.initialData)
.serverWillChangeData((data: any) => {
data.renderCount = 1;
})
.init();
// poll 2
test.expectsAjaxCall('get')
.expectSentData({renderCount: 1})
.serverWillChangeData((data: any) => {
data.renderCount = 2;
})
.init();

// only wait for about 500ms this time
await waitFor(() => expect(test.element).toHaveTextContent('Render count: 1'), {
timeout: 600
});
await waitFor(() => expect(test.element).toHaveTextContent('Render count: 2'), {
timeout: 600
});
});

it('can also call a live action', async () => {
const test = await createTest({ renderCount: 0 }, (data: any) => `
<div ${initComponent(data)} data-poll="delay(500)|saveAction">
<span>Render count: ${data.renderCount}</span>
</div>
`);

// poll 1
test.expectsAjaxCall('post')
.expectSentData(test.initialData)
.expectActionCalled('saveAction')
.serverWillChangeData((data: any) => {
data.renderCount = 1;
})
.init();
// poll 2
test.expectsAjaxCall('post')
.expectSentData({renderCount: 1})
.expectActionCalled('saveAction')
.serverWillChangeData((data: any) => {
data.renderCount = 2;
})
.init();

// only wait for about 500ms this time
await waitFor(() => expect(test.element).toHaveTextContent('Render count: 1'), {
timeout: 600
});
await waitFor(() => expect(test.element).toHaveTextContent('Render count: 2'), {
timeout: 600
});
});

// check polling stops after disconnect

it('polling should stop if data-poll is removed', async () => {
const test = await createTest({ keepPolling: true, renderCount: 0 }, (data: any) => `
<div ${initComponent(data)} ${data.keepPolling ? 'data-poll="delay(500)|$render"' : ''}>
<span>Render count: ${data.renderCount}</span>
</div>
`);

// poll 1
test.expectsAjaxCall('get')
.expectSentData(test.initialData)
.serverWillChangeData((data: any) => {
data.renderCount = 1;
})
.init();
// poll 2
test.expectsAjaxCall('get')
.expectSentData({keepPolling: true, renderCount: 1})
.serverWillChangeData((data: any) => {
data.renderCount = 2;
data.keepPolling = false;
})
.init();

// only wait for about 500ms this time
await waitFor(() => expect(test.element).toHaveTextContent('Render count: 1'), {
timeout: 600
});
await waitFor(() => expect(test.element).toHaveTextContent('Render count: 2'), {
timeout: 600
});
// wait 1 more second... no more Ajax calls should be made
const timeoutPromise = new Promise((resolve) => {
setTimeout(() => {
resolve(true);
}, 1000);
});
await waitFor(() => timeoutPromise, {
timeout: 1500
});
});

it('stops polling after it disconnects', async () => {
const test = await createTest({ renderCount: 0 }, (data: any) => `
<div ${initComponent(data)} data-poll="delay(500)|$render">
<span>Render count: ${data.renderCount}</span>
</div>
`);

// poll 1
test.expectsAjaxCall('get')
.expectSentData(test.initialData)
.serverWillChangeData((data: any) => {
data.renderCount = 1;
})
.init();

// only wait for about 500ms this time
await waitFor(() => expect(test.element).toHaveTextContent('Render count: 1'), {
timeout: 600
});
// "remove" our controller from the page
document.body.innerHTML = '<div>something else</div>';
// wait 1 more second... no more Ajax calls should be made
const timeoutPromise = new Promise((resolve) => {
setTimeout(() => {
resolve(true);
}, 1000);
});
await waitFor(() => timeoutPromise, {
timeout: 1500
});
});
});