diff --git a/src/index.js b/src/index.js index 1524e68e1..79ae2febf 100644 --- a/src/index.js +++ b/src/index.js @@ -186,6 +186,59 @@ VirtualMachine.prototype.addBackdrop = function (backdropObject) { stage.setCostume(stage.sprite.costumes.length - 1); }; +/** + * Rename a sprite. + * @param {string} targetId ID of a target whose sprite to rename. + * @param {string} newName New name of the sprite. + */ +VirtualMachine.prototype.renameSprite = function (targetId, newName) { + var target = this.runtime.getTargetById(targetId); + if (target) { + if (!target.isSprite()) { + throw new Error('Cannot rename non-sprite targets.'); + } + var sprite = target.sprite; + if (!sprite) { + throw new Error('No sprite associated with this target.'); + } + sprite.name = newName; + this.emitTargetsUpdate(); + } else { + throw new Error('No target with the provided id.'); + } +}; + +/** + * Delete a sprite and all its clones. + * @param {string} targetId ID of a target whose sprite to delete. + */ +VirtualMachine.prototype.deleteSprite = function (targetId) { + var target = this.runtime.getTargetById(targetId); + if (target) { + if (!target.isSprite()) { + throw new Error('Cannot delete non-sprite targets.'); + } + var sprite = target.sprite; + if (!sprite) { + throw new Error('No sprite associated with this target.'); + } + var currentEditingTarget = this.editingTarget; + for (var i = 0; i < sprite.clones.length; i++) { + var clone = sprite.clones[i]; + this.runtime.stopForTarget(sprite.clones[i]); + this.runtime.disposeTarget(sprite.clones[i]); + // Ensure editing target is switched if we are deleting it. + if (clone === currentEditingTarget) { + this.setEditingTarget(this.runtime.targets[0].id); + } + } + // Sprite object should be deleted by GC. + this.emitTargetsUpdate(); + } else { + throw new Error('No target with the provided id.'); + } +}; + /** * Temporary way to make an empty project, in case the desired project * cannot be loaded from the online server. diff --git a/src/sprites/rendered-target.js b/src/sprites/rendered-target.js index 80cd79aa3..89270397a 100644 --- a/src/sprites/rendered-target.js +++ b/src/sprites/rendered-target.js @@ -397,6 +397,14 @@ RenderedTarget.prototype.getName = function () { return this.sprite.name; }; +/** + * Return whether this rendered target is a sprite (not a clone, not the stage). + * @return {boolean} True if not a clone and not the stage. + */ +RenderedTarget.prototype.isSprite = function () { + return !this.isStage && this.isOriginal; +}; + /** * Return the rendered target's tight bounding box. * Includes top, left, bottom, right attributes in Scratch coordinates. diff --git a/src/sprites/sprite.js b/src/sprites/sprite.js index 1a9554bc2..0f189206a 100644 --- a/src/sprites/sprite.js +++ b/src/sprites/sprite.js @@ -35,7 +35,7 @@ var Sprite = function (blocks, runtime) { this.costumes = []; /** * List of clones for this sprite, including the original. - * @type {Array.} + * @type {Array.} */ this.clones = []; };