From d3fd3ff806db8d32ef1571dad37087234e89e761 Mon Sep 17 00:00:00 2001 From: Paul Kaplan Date: Tue, 5 Jun 2018 11:49:51 -0400 Subject: [PATCH] Add reorderSound and unit test to rendered-target --- src/sprites/rendered-target.js | 18 ++++++++++++ test/unit/sprites_rendered-target.js | 42 ++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/src/sprites/rendered-target.js b/src/sprites/rendered-target.js index 8010cec9..3e27f5fa 100644 --- a/src/sprites/rendered-target.js +++ b/src/sprites/rendered-target.js @@ -662,6 +662,24 @@ class RenderedTarget extends Target { this.setCostume(this.getCostumeIndexByName(currentCostume.name)); } + /** + * Reorder sound list by moving sound at soundIndex to newIndex. + * @param {!number} soundIndex Index of the sound to move. + * @param {!number} newIndex New index for that sound. + */ + reorderSound (soundIndex, newIndex) { + const clampedNewIndex = + Math.max(0, Math.min(this.sprite.sounds.length - 1, newIndex)); + const clampedSoundIndex = + Math.max(0, Math.min(this.sprite.sounds.length - 1, soundIndex)); + + if (clampedNewIndex === clampedSoundIndex) return; + + const sound = this.sprite.sounds[clampedSoundIndex]; + this.deleteSound(clampedSoundIndex); + this.addSound(sound, clampedNewIndex); + } + /** * Get full sound list * @return {object[]} list of sounds diff --git a/test/unit/sprites_rendered-target.js b/test/unit/sprites_rendered-target.js index 7f0ba354..ff1a24b4 100644 --- a/test/unit/sprites_rendered-target.js +++ b/test/unit/sprites_rendered-target.js @@ -476,3 +476,45 @@ test('#reorderCostume', t => { t.end(); }); + +test('#reorderSound', t => { + const o1 = {id: 0, name: 'name0'}; + const o2 = {id: 1, name: 'name1'}; + const o3 = {id: 2, name: 'name2'}; + const o4 = {id: 3, name: 'name3'}; + const o5 = {id: 4, name: 'name4'}; + const s = new Sprite(); + const r = new Runtime(); + s.sounds = [o1, o2, o3, o4, o5]; + const a = new RenderedTarget(s, r); + const renderer = new FakeRenderer(); + a.renderer = renderer; + + const resetSounds = () => { + s.sounds = [o1, o2, o3, o4, o5]; + }; + const soundIds = () => a.sprite.sounds.map(c => c.id); + + resetSounds(); + t.deepEquals(soundIds(), [0, 1, 2, 3, 4]); + + // Make sure reordering up and down works and current sound follows + resetSounds(); + a.reorderSound(0, 3); + t.deepEquals(soundIds(), [1, 2, 3, 0, 4]); + + resetSounds(); + a.reorderSound(3, 1); + t.deepEquals(soundIds(), [0, 3, 1, 2, 4]); + + // Out of bounds indices get clamped + resetSounds(); + a.reorderSound(10, 0); + t.deepEquals(soundIds(), [4, 0, 1, 2, 3]); + + resetSounds(); + a.reorderSound(2, -1000); + t.deepEquals(soundIds(), [2, 0, 1, 3, 4]); + + t.end(); +});