Extend Tumult Hype with JavaScript: hypeDocument.extensions

↑ extension index


hypeDocument.stopAllCustomBehaviourTicker

Hype Pro Extension: Stops all active ticker broadcasting custom behaviour.


/**
* hypeDocument.stopAllCustomBehaviourTicker
* @require stopCustomBehaviourTicker
*/
hypeDocument.stopAllCustomBehaviourTicker = function(){
    if (this.hasOwnProperty('_ticker')) {
        for (var behaviour in this._ticker) {
            this.stopCustomBehaviourTicker (behaviour);
        }
    }
}

Usage:

hypeDocument.stopAllCustomBehaviourTicker();

Updates:
1.0 initial release
1.1 code cleanup

1 Like

↑ extension index


hypeDocument.setCurrentSceneHeight

Sets the current scene height. Beware to do this it need to set the hypeDocument height as well so you should reset scene height on scene changes if you wish to the restore initial state.


/**
* hypeDocument.setCurrentSceneHeight v1.0
* @param {Number} height to set the scene element to
*/  
hypeDocument.setCurrentSceneHeight = function ( height) {
    var sceneElm = document.getElementById(this.currentSceneId());
    sceneElm.parentElement.style.height = height;
    sceneElm.style.height = height;
}

Usage:

hypeDocument.setCurrentSceneHeight( '1000px' );

setCurrentSceneHeight.hype.zip (272,0 KB)

Update: This was updated on 11. September 2020

1 Like

↑ extension index


hypeDocument.getCurrentSceneHeight

Gets the current scene height.


/**
* hypeDocument.getCurrentSceneHeight 1.0
* @return {Number} height of the scene element
* @require currentSceneElement
*/  
hypeDocument.getCurrentSceneHeight = function () {
    var cS = hypeDocument.currentSceneElement();
    return cS.style.height;
}

Usage:

var height = hypeDocument.getCurrentSceneHeight();

Requires:
hypeDocument.currentSceneElement

1 Like

↑ extension index


hypeDocument.setElementProperties

Sets multiple properties in one go (with the optional possibility to animate them)


20180412-dj7ka

/**
* setElementProperties v1.1
* @param {Element} target to be animated
* @param {Object} object with properties to be animated
* @param {Number} time in seconds for no animation (optional)
* @param {String} easing function (optional)
*/  
hypeDocument.setElementProperties = function ( target, obj, duration, ease) {
    for (var prop in obj) {
        var val = (typeof(obj[prop]) == 'string') ? this.getElementProperty(target, prop) + parseInt(obj[prop]) : parseInt(obj[prop]);
        this.setElementProperty(target, prop, val , duration, ease);
    }
}

Usage:
Given we have element in scene with the id “circle” we can animate it.

var target = hypeDocument.getElementById('someId');
hypeDocument.setElementProperties( target , {top:500, left:267, rotateZ:180}, 1, 'easeinout');

Given we have element in scene with the id “slider” we can slide it relativ to it’s position

var target = hypeDocument.getElementById('slider');
hypeDocument.setElementProperties( target , { left:"-500"}, 1, 'easeinout');

setElementProperties.hype.zip (55,7 KB)

Updates:
1.0 Initial release with multiple property animation
1.1 Added relativ motion if value is String

2 Likes

↑ extension index


hypeDocument.currentSceneIndex

Returns the current scene index (Number).


/**
* hypeDocument.currentSceneIndex 1.0
* @return {Number} gives you the current scene index
*/
hypeDocument.currentSceneIndex = function(){
    var hc = document.getElementById(hypeDocument.documentId());
    var sa = hc.getElementsByClassName("HYPE_scene");
    for (i = 0; i < sa.length; i++) {
        if (sa[i].style.display === "block") return parseInt(sa[i].getAttribute("hype_scene_index"));
    }
}

Usage:
The scene index can also be obtained through element.getAttribute(“hype_scene_index”) in an scene load function but this implementation is agnostic to it’s location and can be used in any Hype function.

var nr = hypeDocument.currentSceneIndex();
1 Like

↑ extension index


hypeDocument.currentSceneElement

Returns the current scene element (HTMLDivElement).


/**
* hypeDocument.currentSceneElement 1.1
* @return {HTMLDivElement} gives you the current scene element
*/
hypeDocument.currentSceneElement = function(){
    return document.querySelector('#'+this.documentId()+' > .HYPE_scene[style*="block"]');
}

As of Hype 4.0.2 (build 656) this new version is the way to go:

/**
* hypeDocument.currentSceneElement 1.2
* @return {HTMLDivElement} gives you the current scene element
*/
hypeDocument.currentSceneElement = function(){
    return document.getElementById(this.currentSceneId());
}

Usage:
Given one would like to share a button function across multiple scenes one could get the current scene element and search for the affected elements using a querySelector contained in the scene. This way you can reuse classes in every scene instead of having different ID’s that would have to be unique across the whole HTML page. This is just one example as I am sure there are more use cases.

var elm = hypeDocument.currentSceneElement();
var someButton = elm.querySelector('.someButton');

Update:
1.0 initial release using getElementById ( :pencil2: see edit history to recall)
1.1 updated version with only one function call

1 Like

↑ extension index


hypeDocument.loadSound

Load soundfiles from the library and plays them back.


/**
* hypeDocument.loadSound 1.0
* @param {String} soundname without extention (mp3/ogg/wav)
* @param {String} uniqueId to load the same sound multiple times (optional)
* @require getPrivateContainer 
* @return {HTMLAudioElement}
*/
hypeDocument.loadSound = function(soundname, uniqueId){
    var soundId = soundname+'_-_'+( (uniqueId===undefined)?'':uniqueId);
    if (!hypeDocument.hasOwnProperty('_sounds')) {
        hypeDocument._sounds={};
    }
    if (!hypeDocument._sounds.hasOwnProperty(soundId)) {
        var pc = hypeDocument.getPrivateContainer('sounds');
        var sndElm = document.createElement('audio');
        if (!!(sndElm.canPlayType && sndElm.canPlayType('audio/mpeg;').replace(/no/, ''))) {
            sndElm.setAttribute('src','${resourcesFolderName}/'+soundname+'.mp3');
        } else {
            sndElm.setAttribute('src','${resourcesFolderName}/'+soundname+'.ogg');
        }
        pc.appendChild(sndElm);
        hypeDocument._sounds[soundId]=sndElm;
        
    }
    return hypeDocument._sounds[soundId];
}

Usage:
Given you have a file called “soundfile.mp3” in your library this function attaches it to your document for further use. The return value is a regular HTMLAudioElement with all it’s functions. Also this functions supports a built in ogg fallback given you supply the file in the library. Wav is currently unsupported (but easy to hack).

var snd = hypeDocument.loadSound('soundfile');
snd.play();

Requires:
hypeDocument.getPrivateContainer

1 Like

↑ extension index


hypeDocument.stopAllSounds

Stops all playing soundfiles that have been loaded with hypeDocument.loadSound


/**
* hypeDocument.stopAllSounds 1.0
*/
hypeDocument.stopAllSounds = function(){
    if (!hypeDocument.hasOwnProperty('_sounds')) {
        return;
    }
    for(var id in hypeDocument._sounds) {
        var snd = hypeDocument._sounds[id];
        snd.pause();
        snd.currentTime = 0;
    }
}

Usage:
Given you have have sounds running that go attached through hypeDocument.loadSound this function will stop them and rewind them to their beginning.

hypeDocument.stopAllSounds();

1 Like

↑ extension index


##hypeDocument.getPrivateContainer
This function creates a kind of “shadow DOM” to hold the audio elements. It’s required by loadSound but also works on it’s own to assist in any other extension.


/**
* hypeDocument.getPrivateContainer 1.0
* @param {String} name for container
* @return {HTMLDivElement}
*/
hypeDocument.getPrivateContainer = function(name){
    var hypeId = hypeDocument.documentId();             
    var hypeElm = document.querySelector('#'+hypeId);
    var pcId = hypeId+'_'+name;
    var pcElm = hypeElm.querySelector('#'+pcId);
    if (pcElm === null){
        pcElm = document.createElement('div');
        pcElm.setAttribute('id', pcId);
        pcElm.style.visibility='none';
        hypeElm.appendChild(pcElm);
    }
    return pcElm;
}

Usage:
Given you need a “shadow DOM” of sorts. This will create a HTMLDivElement inside your HypeDocument and hide it. The return value is a regular HTMLDivElement and can be manipulated as regular. Used for loadSound but should come in handy for other extensions as well. The name parameter is a must to keep each generated container ID unique.

var shadowDom = getPrivateContainer('uniqueName');

1 Like

↑ extension index


hypeDocument.unloadSound

resets the audio element and removes it from the DOM given a HTMLAudioElement to kill.
You will only need this if you are concerned with garbage collection.


/**
* hypeDocument.unloadSound 1.0
* @param soundname
*/
hypeDocument.unloadSound = function(audioRef){
    if (!hypeDocument.hasOwnProperty('_sounds')) return false;
    for(var id in hypeDocument._sounds) {
        if (audioRef === hypeDocument._sounds[id]) {
            var elm = hypeDocument._sounds[id];
            elm.src=''; elm.load();
            elm.parentNode.removeChild(elm);
            delete hypeDocument._sounds[id];
        }
    }
}

Usage:
Given you have a “soundfile.mp3” in your library and loaded it using HypeDocument.loadSound this function will remove the instances by reference. You need to store the reference todo so.

var snd = hypeDocument.loadSound('soundfile');
//makes no sense but let's unload it directly again :-)
hypeDocument.unloadSound(snd);

2 Likes

↑ extension index


hypeDocument.unloadAllSoundsByName

resets all the audio element and removes them from the DOM given the library name (without mp3/ogg)
You will only need this if you are concerned with garbage collection.


/**
* hypeDocument.unloadAllSoundsByName 1.0
* @param soundname
*/
hypeDocument.unloadAllSoundsByName = function(soundname){
    if (!hypeDocument.hasOwnProperty('_sounds')) return false;
    var success = false;
    for(var id in hypeDocument._sounds) {
        if(id.indexOf(soundname+'_-_') == 0){
            var elm = hypeDocument._sounds[id];
            elm.src=''; elm.load();
            elm.parentNode.removeChild(elm);
            delete hypeDocument._sounds[id];
            success = true;
        }
   }
   return success; 
}


Usage:
Given you have a “soundfile.mp3” in your library and are using it multiple times (see loadSound for details) this function will remove all instances by name.

hypeDocument.unloadAllSoundsByName('soundfile');

1 Like

↑ extension index

hypeDocument.cloneElement

This Extension allows you to clone elements and append them to the scene or within a Group.
You will specify the Element to clone, where to append the clone, it’s ID, Class Name, Top, Left and z-Index.
The clones HYPE_element_container class name, Child Nodes ID and HYPE_element classes are removed from the clones to avoid clashes with the Hype runtime.

/**
    * cloneElement, can be single Element or Group
    * @param {element} Hype Element to  clone
     * @param {element} Hype Element to append the clone
    * @param {String} The clone's id
    * @param {String} The clone's class name
    * @param {numnber} The clone's Top placement
    * @param {numnber} The clone's Left placement
    * @param {numnber} The clone's z-index
    * @return the specified element is cloned and appended to the specified element. The clones HYPE_element_container class name, Child Nodes ID and HYPE_element classes are removed from the clones to avoid clashes with the Hype runtime.
    */	  
    	hypeDocument.cloneElement = function(elementToClone,clonTo,elementID,elementClassName,elementTop,elementLeft,elementZIndex){
    	var elementClone =   elementToClone.cloneNode(true, true);
      
    	elementClone.id = elementID ;
    	elementClone.className = elementClassName;

    	elementClone.style.top = elementTop.toString() +'px';
    	elementClone.style.left = elementLeft.toString() +'px';
    	elementClone.style.zIndex = elementZIndex.toString();  
    		  
    	clonTo.appendChild(elementClone);
    	
    	
    	var clonedChildren = elementClone.childNodes

    for (i = 0; i < clonedChildren.length; i++) { 
     
    clonedChildren[i].classList.remove("HYPE_element_container");
     
      	var thisChild = clonedChildren[i].childNodes[0];
      	thisChild.classList.remove("HYPE_element");
     	thisChild.id  = "" ;

 } 
	
	return elementClone;
    	
    	
    	}

Usage:
You may have a form that you want to dynamically add elements to it’s list.

Constructor:
hypeDocument.cloneElement(original_to_clone,append_the_clone_To, id,className,top,left,z-index)

In Use:

if (!window.start_Top) { window.start_Top = 0 }; //-- This will be the space between the new clones and we will also use this number in the new ids.
    		
    		if ( window.start_Top < 200 ){ //-- Limit to 2 new clones
    		
    		window.start_Top +=100
    			
    		var original_to_clone  = hypeDocument.getElementById('infoBoxGroup'); 
     
     		/* We use the Scene element here to append the clones but we could use any Div/Group in the scene i.e  hypeDocument.getElementById('clonToFoo'); */
     		var append_the_clone_To = hypeDocument.currentSceneElement(); //-  @REQUIERS  currentSceneElement  Extension.

     //-- clone
    hypeDocument.cloneElement(original_to_clone,append_the_clone_To,'infoBoxGroupClone'+ window.start_Top,'infoBoxGroupClone',window.start_Top,0,2000)

     
    }

In this example we want a couple of clones so we also use the top’s number as an index to limit the cloning to two and also we use it in the new ids to keep them original.

Note: This example also uses currentSceneElement Extension.


Version update 1.1

Added a return of the clone element. You will now be able to add the returned clone element to a var or send it instructions.

clone Extension_Example_v1_MH.hype.zip (27.9 KB)

3 Likes

Awesome Max

I added relativ motion to hypeDocument.setElementProperties (if value is given as string)

1 Like

↑ extension index


hypeDocument.goToTimeIndexInTimelineNamed

Jump to timeIndex as seen in the Hype frontend.


/**
* hypeDocument.goToTimeIndexInTimelineNamed 1.0
* @param {String, Object, Number} timeIndex as seen in Hype GUI
* @param {String} time line to adress
* @param {Boolean} convert overbound values
*/
hypeDocument.goToTimeIndexInTimelineNamed = function (timeIndex, timelineName, convert) {
    this.goToTimeInTimelineNamed( this.timeIndexToSeconds(timeIndex, convert), timelineName);
}

/**
* hypeDocument.timeIndexToSeconds 1.2
* @param {String, Object, Number} timeIndex in various formats
* @param {Boolean} convert overbound values 
*/
hypeDocument.timeIndexToSeconds = function (tidx, convert) {
	var min=0, sec=0, frm=0, FPS=30;
	switch (typeof(tidx)) {
		case 'object':
		 min = tidx.minutes ? tidx.minutes : 0;
		 sec = tidx.seconds ? tidx.seconds : 0;
		 frm = tidx.frames ? tidx.frames : 0;
		 FPS = tidx.FPS ? tidx.FPS : FPS;
		 break;
		case 'number':
		 sec = Math.floor(tidx);
		 frm = Math.floor((tidx-sec)*100);
		 break;	
		case 'string':
		 var temp = tidx.split(':');
		 min = temp.length > 1 ? temp[0] : 0;
		 temp = (temp.length > 1) ? temp[1] : temp[0];
		 temp = temp.split(temp.indexOf('.') > -1 ? '.' : ',');
		 sec = temp[0] ? temp[0] : 0;
		 frm = temp.length > 1 ? temp[1] : 0;
		 break;
	}
	sec = (convert) ? sec : sec %60;
	min = (convert) ? min : min %60;
	frm = (convert) ? frm : frm %FPS;
	return min*60+sec+frm/FPS;
}

Usage of hypeDocument.timeIndexToSeconds:
Let’s assume we want to jump to 3 seconds and 14 frames :wink:

// EU notation
hypeDocument.goToTimeIndexInTimelineNamed ('03,14', 'Main Timeline');
// US notation
hypeDocument.goToTimeIndexInTimelineNamed ('03.14', 'Main Timeline');

Let’s assume we want to jump to frame number 75 on test timeline (Object-Interface)

hypeDocument.goToTimeIndexInTimelineNamed ({frame:75}, 'test', true);

See possible formats for the timeIndex-String in the timeIndexToSeconds usage.

 

 

Usage of hypeDocument.timeIndexToSeconds:

// New FPS option in Object-Interface since 1.2 
// Converting 120 frames at 60 FPS (works with other examples as well)
console.log(hypeDocument.timeIndexToSeconds( {frames:120, FPS:60 } , true ));

// New object interface since 1.1
console.log(hypeDocument.timeIndexToSeconds( {minutes:1, seconds:10} ));
console.log(hypeDocument.timeIndexToSeconds( {minutes:1} ));

// with conversion 45 frame equals 1.5 seconds
console.log(hypeDocument.timeIndexToSeconds( {frames:45 } , true ));

// Number interface since 1.1 (limited to sec.frames)
console.log(hypeDocument.timeIndexToSeconds( 4.15 ));

// New String interface since 1.1 (valid tests with US dot notation)
console.log(hypeDocument.timeIndexToSeconds('01:40.15'));
console.log(hypeDocument.timeIndexToSeconds('30.00'));
console.log(hypeDocument.timeIndexToSeconds('02:43.29'));

// String interface since 1.0 (valid tests)
console.log(hypeDocument.timeIndexToSeconds('01:40,15'));
console.log(hypeDocument.timeIndexToSeconds('30,00'));
console.log(hypeDocument.timeIndexToSeconds('02:43,29'));

// wrong range tests (fixed with modulor %60, %30
console.log(hypeDocument.timeIndexToSeconds('00:61,40'));

// partial format (no minutes)
console.log(hypeDocument.timeIndexToSeconds('25,02'));

// partial format (no frame)
console.log(hypeDocument.timeIndexToSeconds('1:15'));

// partial format (only one int)
console.log(hypeDocument.timeIndexToSeconds('15'));

// conversion (45 frames)
console.log(hypeDocument.timeIndexToSeconds(',45', true));

// conversion (120 minutes)
console.log(hypeDocument.timeIndexToSeconds('120:', true));

Credits:
This extension has been initialized by @MarkHunte :sparkles:
The version bump came about through input from @DBear

Update:
1.0 inital relase from MarkHunte and MaxZieb
1.1 fixed .frames (US) and ,frames (EU) + Number/Object interface
1.2 timeIndexToSeconds now supports higher FPS (for example 60)

4 Likes

Updated hypeDocument.startCustomBehaviourTicker to version 1.1:

  • it now support patterns and omitFirst options
1 Like

↑ extension index


hypeDocument.sceneInfo

This Extension returns the scene element, scene number and scene count, scene name list
.

		
	
	
	
/* hypeDocument.sceneInfo 1.0
* @return {object} gives you the current scene, Name, number and the total count of scenes.  {sceneName: currentSceneName, sceneNumber:Number,sceneElement:Element,sceneCount: Number}

* @Returned object break down
  sceneName = The current scene's name Type: String 
 sceneNumber = The current scene's display order number Type: Number 
 sceneElement = The current Scene's Div Element  Type: Hype Element 
 sceneCount = Total count of all scenes  Type: Number 
*/

 hypeDocument.sceneInfo = function(){
 
var sceneElement;
 //-- get current scene
 var hypeContainer = document.getElementById(hypeDocument.documentId());
    var scenArray = hypeContainer.getElementsByClassName("HYPE_scene");
    for (i = 0; i < scenArray.length; i++) {
        if (scenArray[i].style.display === "block")  sceneElement = scenArray[i];
    }

 


 
  	var sceneNumber = sceneElement.getAttribute('hype_scene_index');// get the index number of the current scene name. Add 1 to make the index start from 1 instead of 0.
	var currentSceneName = hypeDocument.currentSceneName(); // get the curent scene name 
	var sceneNameArray = hypeDocument.sceneNames();  // get an array of all scene names 
	  

	return {sceneName: currentSceneName, sceneNumber: Number(sceneNumber)+1 ,sceneElement: sceneElement ,sceneCount: Number(sceneNameArray.length)}
  
  }

Returned object break down
sceneName = The current scene's name, Type: String
sceneNumber = The current scene's display order number, Type: Number
sceneElement = The current Scene's Div Element, Type: Hype Element
sceneCount = Total count of all scenes, Type: Number

Usage:

var sceneInfo = hypeDocument.sceneInfo()

You may want to set a navigation label to display scene name and numbers,

fooElement.innerHTML = sceneInfo.sceneName + " - " + sceneInfo.sceneNumber + " of " + sceneInfo.sceneCount ;

--> fooSceneName - (1 of 5)


Get the current scene element so you can target a child element that shares a class name with similar elements on other scenes.

var someButton = sceneInfo.sceneElement.querySelector('.someButton’);


Example:

ScenInfo Extension.hype.zip (31.6 KB)

Extension code ( text file )

hypeDocument.sceneInfo 1.0.txt.zip (1.2 KB)

3 Likes

↑ extension index


hypeDocument.setInnerHtmlByClass

Sets all the all elements of a given class to the content one provides. Usefull to update content across scenes and layouts all at once. Elements that want to subscribe to content updates only need to be assigned the associated class


Reasons for using class based targeting over ID based targeting:

  1. Hype has a unique approach when it comes to responsive layouts. As with scenes themselves it keeps them in own HTML braches. Meaning when you have to repeat using elements per scene or layout … ID’s demand to be unique. Therefor it would be very annoying to have to choose a different ID per scene or layout for the same content.
  2. Addressing the content nodes per Class allows them to be in plentiful locations and they are all updated at once without the need to target any element specifically.
  3. One can also use persistent symbols and unique ID’s but one often needs to tweak the design beyond proportional symbol scaling and that is where this technic really helps.

/**
* hypeDocument.setInnerHtmlByClass 1.0
* @param {String} class name to overwrite (don't include dot)
* @param {String} content or HTML used to overwrite class
*/
hypeDocument.setInnerHtmlByClass = function(cl, content) {
    var hypeDiv = document.getElementById(this.documentId());
    var hypeElm = hypeDiv.getElementsByClassName(cl);
    for(var i=0; i<hypeElm.length; i++){
            hypeElm[i].innerHTML=content;
    }
}

Usage:
Presume you have a textfield with the class userName and want to update it:

hypeDocument.setInnerHtmlByClass ('userName', 'Max');

setInnerHtmlByClass.hype.zip (127,2 KB)

4 Likes

↑ extension index


hypeDocument.getSceneElementByName

Returns a scene element by name (HTMLDivElement).


/**
* hypeDocument.getSceneElementByName 1.0
* @return {HTMLDivElement} gives you the scene element by name
*/
hypeDocument.getSceneElementByName = function(name){
    var idx = this.sceneNames().indexOf(name);
    return document.querySelector('#'+this.documentId()+' > .HYPE_scene[hype_scene_index="'+idx+'"]');
}

Usage:
Lets assume you want to extract the text contained in an textfield in another scene called intro.

var elm = hypeDocument.getSceneElementByName('intro');
var txt = elm.querySelector('#mytextbox').value;

Update:
1.0 initial release

2 Likes