Make updateContent persist specified classNames

Wrap the code that updates the HTML with changes
from the server with code that stores and
re-applies specified classes.

This is to allow other JS to add classes which
change the visual state of the HTML without them
being considered by the code that diffs our
in-page HTML against that from the server.

They are called classesToPersist because this
should make the visual state they create persist
between updates.

Includes the addition of tests for updateContent
that cover the addition/deletion of elements so we
can write a test for classNames persisting through
updates. The existing tests only cover updates
that change the content of elements. Just adding
the test for these changes to those would simulate
a scenario that doesn't exist in the app. Writing
extra tests for the kind of updates these changes
act on keeps them in line with the app code.
This commit is contained in:
Tom Byers
2022-02-08 11:33:13 +00:00
parent 73cc034676
commit 3fa2650ffa
2 changed files with 464 additions and 190 deletions

View File

@@ -11,10 +11,37 @@
1000
));
var getRenderer = $component => response => morphdom(
$component.get(0),
$(response[$component.data('key')]).get(0)
);
// Methods to ensure the DOM fragment is clean of classes added by JS before diffing
// and that they are replaced afterwards.
var classesToPersist = {
classNames: [],
$els: [],
remove: function () {
this.classNames.forEach(className => {
var $elsWithClassName = $('.' + className).removeClass(className);
// store elements for that className at the same index
this.$els.push($elsWithClassName);
});
},
replace: function () {
this.classNames.forEach((className, index) => {
this.$els[index].addClass(className);
});
// remove references to elements
this.$els = [];
}
};
var getRenderer = $component => response => {
classesToPersist.remove();
morphdom(
$component.get(0),
$(response[$component.data('key')]).get(0)
);
classesToPersist.replace();
};
var getQueue = resource => (
queues[resource] = queues[resource] || []
@@ -55,15 +82,26 @@
global.GOVUK.Modules.UpdateContent = function() {
this.start = component => setTimeout(
() => poll(
getRenderer($(component)),
$(component).data('resource'),
getQueue($(component).data('resource')),
$(component).data('form')
),
defaultInterval
);
this.start = component => {
var $component = $(component);
// store any classes that should persist through updates
if ($contents.data('classesToPersist') !== undefined) {
$contents.data('classesToPersist')
.split(' ')
.forEach(className => classesToPersist.classNames.push(className));
}
setTimeout(
() => poll(
getRenderer($component),
$component.data('resource'),
getQueue($component.data('resource')),
$component.data('form')
),
defaultInterval
);
};
};