Stimulus - Removing Markers from a Wavesurfer Element

Use Stimulus value callbacks to interact with a wavesurfer element and remove markers.

View Solution on Patreon
Stimulus - Removing Markers from a Wavesurfer Element

Premise

In the previous challenge, we used Stimulus values to manage the adding of markers to a Wavesurfer.js element.

That’s only half the battle, though. Consequently, we should provide a means for the user to remove markers again.

Starting Point

We start from the state after adding the “Add Markers” functionality.

The list item template was enhanced by a button connected to the new removeMarker Stimulus action:

https://stackblitz.com/edit/stimulus-wavesurfer-2?file=controllers%2Fpeaks_controller.js%3AL5

This action is triggered with an action parameter containing the corresponding timestamp. Thus, every time a new list item is added, it can be removed again by handling the removeMarker action.

Challenge

First, we have to handle said Stimulus action by finding out the respective marker using its timestamp, and remove it from the markersValue array:

https://stackblitz.com/edit/stimulus-wavesurfer-2?file=controllers%2Fpeaks_controller.js%3AL111

Afterwards, we have to respond to the mutation of this array in the value callback listener. More precisely, we have to determine which markers have been removed using a similar technique as for the addition, and call #handleRemoval for each of them:

#handleRemoval takes care of actually removing the markers from the Wavesurfer object. The final step we have to take is to listen for the region-removed event and delete the corresponding list item, like we did for region-created:

https://stackblitz.com/edit/stimulus-wavesurfer-2?file=controllers%2Fpeaks_controller.js%3AL61

Below is a rendering of the result:

Waveform display with markers being removed

More from

Stimulus - Image Upload Previews with `URL.createObjectURL`
17 September 2024

Create client-side previews of files using URL.createObjectURL

Stimulus - Adding Markers to a Wavesurfer Element
02 July 2024

Use Stimulus value callbacks to interact with a wavesurfer element and add markers.

Stimulus - Picture in Picture API
04 June 2024

Use an IntersectionObserver to trigger a Picture in Picture overlay

Cookies
essential