soundcite-1.1.2/js/soundcite-behavior.js
js/soundcite-behavior.js
/**
* @file
* Drupal behavior for Soundcite integration.
*/
(function (Drupal, once) {
"use strict";
/**
* Soundcite behavior.
*/
Drupal.behaviors.soundcite = {
attach: function (context, settings) {
// Use once to ensure elements are only processed once
var soundciteElements = once("js-soundcite", ".soundcite", context);
if (soundciteElements.length > 0) {
// Initialize new soundcite elements
this.initializeSoundcite(soundciteElements);
}
},
initializeSoundcite: function (elements) {
var self = this;
// Wait for soundcite library to be available
var waitForSoundcite = function () {
if (typeof window.soundcite !== "undefined" && window.soundcite.Clip) {
// Library is loaded, initialize new elements
self.createClips(elements);
} else {
// Retry if soundcite isn't loaded yet
setTimeout(waitForSoundcite, 100);
}
};
waitForSoundcite();
},
createClips: function (elements) {
// Create clips for new elements using the same logic as the main library
for (var i = 0; i < elements.length; i++) {
var el = elements[i];
try {
if (el.getAttribute("data-url")) {
// Create PopcornClip
new window.soundcite.PopcornClip(el);
} else if (el.getAttribute("data-id")) {
// Create SoundCloudClip
new window.soundcite.SoundCloudClip(el);
} else {
console.log(
'Unable to form Soundcite element because of missing attributes. The offending Soundcite was "' +
el.textContent +
'."'
);
console.log(el);
}
} catch (error) {
console.error("Error initializing Soundcite element:", error);
console.log(el);
}
}
},
detach: function (context, settings, trigger) {
if (trigger === "unload") {
// Pause all clips when content is being removed
if (
typeof window.soundcite !== "undefined" &&
window.soundcite.pause_all_clips
) {
window.soundcite.pause_all_clips();
}
// Remove once tracking for elements being unloaded
once.remove("js-soundcite", ".soundcite", context);
}
},
};
})(Drupal, once);
