Infovis not Iterating over Root Node - javascript

I'm facing weird behaviour of Jit Infovis i'm using. I have two different html files that include a load json function from a Javascript file. The function is using infovis library to display a hypertree map from a json file. Both two html files load the same json file.
One html file has been succeeded rendering the map properly. But another one has not. It renders the map almost properly, but after i debugged it, i got it not iterating over the root node. Then, the root node becames inactive without label and clickability.
This is the js function i'm using.
var labelType, useGradients, nativeTextSupport, animate;
(function () {
var ua = navigator.userAgent,
iStuff = ua.match(/iPhone/i) || ua.match(/iPad/i),
typeOfCanvas = typeof HTMLCanvasElement,
nativeCanvasSupport = (typeOfCanvas == 'object' || typeOfCanvas == 'function'),
textSupport = nativeCanvasSupport
&& (typeof document.createElement('canvas').getContext('2d').fillText == 'function');
//I'm setting this based on the fact that ExCanvas provides text support for IE
//and that as of today iPhone/iPad current text support is lame
labelType = (!nativeCanvasSupport || (textSupport && !iStuff)) ? 'Native' : 'HTML';
nativeTextSupport = labelType == 'Native';
useGradients = nativeCanvasSupport;
animate = !(iStuff || !nativeCanvasSupport);
})();
var Log = {
elem: false,
write: function (text) {
if (!this.elem)
this.elem = document.getElementById('log');
this.elem.innerHTML = text;
this.elem.style.left = (350 - this.elem.offsetWidth / 2) + 'px';
}
};
function init(slugParam, pageParam) {
var isFirst = true;
var isSetAsRoot = false;
// alert(slugParam+ " | "+pageParam);
var url = Routing.generate('trade_map_buyer_json', { slug : slugParam, page : pageParam });
//init data
$.getJSON(url, function (json) {
var type = 'Buyer';
//end
var infovis = document.getElementById('infovis');
infovis.style.align = "center";
infovis.innerHTML = '';
// infovis.innerHTML = '<img align="center" id="gifloader" style="margin-left:50%; margin-top:50%" src="{{ asset('/bundles/jariffproject/frontend/images/preloader.gif') }}" width="30px" height="30px"/>'
var w = infovis.offsetWidth - 50, h = infovis.offsetHeight - 50;
url = url.replace("/json/", "/");
window.history.pushState("object or string", "Title", url);
//init Hypertree
var ht = new $jit.Hypertree({
//id of the visualization container
injectInto: 'infovis',
Navigation: {
enable: false,
panning: 'avoid nodes',
},
//canvas width and height
width: w,
height
: h,
//Change node and edge styles such as
//color, width and dimensions.
Node: {
dim: 9,
overridable: true,
color: "#66FF33"
},
Tips: {
enable: true,
type: 'HTML',
offsetX: 0,
offsetY: 0,
onShow: function(tip, node) {
// dump(tip);
tip.innerHTML = "<div style='background-color:#F8FFC9;text-align:center;border-radius:5px; padding:10px 10px;' class='node-tip'><p style='font-size:100%;font-weight:bold;'>"+node.name+"</p><p style='font-size:50%pt'>"+node.data.address+"</p></div>";
}
},
Events: {
enable: true,
type: 'HTML',
onMouseEnter: function(node, eventInfo, e){
var nodeId = node.id;
var menu1 = [
{'set as Root':function(menuItem,menu) {
menu.hide();
isSetAsRoot = true;
console.log(nodeId);
init(nodeId, 0);
}},
$.contextMenu.separator,
{'View details':function(menuItem,menu) {
}}
];
$('.node').contextMenu(menu1,{theme:'vista'});
}
},
Edge: {
lineWidth: 1,
color: "#52D5DE",
overridable: true,
},
onBeforePlotNode: function(node)
{
if (isFirst) {
console.log(node._depth);
var odd = isOdd(node._depth);
if (odd) {
node.setData('color', "#66FF33"); // hijau (supplier)
} else {
node.setData('color', "#FF3300"); // merah (buyer)
}
isFirst = false;
}
},
onPlotNode: function(node)
{
if (isSetAsRoot) {
var nodeInstance = node.getNode();
var nodeId = nodeInstance.id;
init(nodeId, 0);
isSetAsRoot = false;
}
},
onBeforeCompute: function (domElement, node) {
var dot = ht.graph.getClosestNodeToOrigin("current");
type = isOdd(dot._depth) ? 'Supplier' : 'Buyer';
},
//Attach event handlers and add text to the
//labels. This method is only triggered on label
//creation
onCreateLabel: function (domElement, node) {
var odd = isOdd(node._depth);
if (odd) {
node.setData('color', "#66FF33"); // hijau (supplier)
} else {
node.setData('color', "#FF3300"); // merah (buyer)
}
domElement.innerHTML = node.name;
// if (node._depth == 1) {
console.log("|"+node.name+"|"+node._depth+"|");
// }
$jit.util.addEvent(domElement, 'click', function () {
ht.onClick(node.id, {
onComplete: function () {
console.log(node.id);
ht.controller.onComplete(node);
}
});
});
},
onPlaceLabel: function (domElement, node) {
var style = domElement.style;
style.display = '';
style.cursor = 'pointer';
if (node._depth <= 1) {
style.fontSize = "0.8em";
style.color = "#000";
style.fontWeight = "normal";
} else if (node._depth == 2) {
style.fontSize = "0.7em";
style.color = "#555";
} else {
style.display = 'none';
}
var left = parseInt(style.left);
var w = domElement.offsetWidth;
style.left = (left - w / 2) + 'px';
},
onComplete: function (node) {
var dot = ht.graph.getClosestNodeToOrigin("current");
console.log(dot._depth);
var connCount = dot.data.size;
var showingCount = '';
if (connCount != undefined) {
var pageParamInt = (parseInt(pageParam)+1) * 10;
var modulus = connCount%10;
showingCount = (pageParamInt - 9) + " - " + pageParamInt;
if (connCount - (pageParamInt - 9) < 10) {
showingCount = (pageParamInt - 10) + " - " + ((pageParamInt - 10) + modulus);
}
} else {
connCount = '0';
showingCount = 'No Connections Shown'
}
}
});
//load JSON data.
ht.loadJSON(json);
//compute positions and plot.
ht.refresh();
//end
ht.controller.onComplete();
});
}
function isEven(n)
{
return isNumber(n) && (n % 2 == 0);
}
function isOdd(n)
{
return isNumber(n) && (n % 2 == 1);
}
function isNumber(n)
{
return n === parseFloat(n);
}
function processAjaxData(response, urlPath){
}
function dump(obj) {
var out = '';
for (var i in obj) {
out += i + ": " + obj[i] + "\n";
}
out = out + "\n\n"
console.log(out);
// or, if you wanted to avoid alerts...
var pre = document.createElement('pre');
pre.innerHTML = out;
document.body.appendChild(pre)
}
What's probably causing this?

Please check whether there is conflict id. Basically infovis render each nodes by the id.
And if there is an DOM element that has the same id with one DOM element of a node. It would conflict and won't render
you can check it by duming dom element iterating over the nodes.

Related

Loading two similar scripts twice dosn't work

i have this javascript that I called cookiebar.js, it shows a sticky bar message for cookies, (source code)
(function (context) {
"use strict";
var win = context,
doc = win.document;
var global_instance_name = "cbinstance";
function contentLoaded(win, fn) {
var done = false,
top = true,
doc = win.document,
root = doc.documentElement,
add = doc.addEventListener ? "addEventListener" : "attachEvent",
rem = doc.addEventListener ? "removeEventListener" : "detachEvent",
pre = doc.addEventListener ? "" : "on",
init = function (e) {
if (e.type == "readystatechange" && doc.readyState != "complete") return;
(e.type == "load" ? win : doc)[rem](pre + e.type, init, false);
if (!done && (done = true)) fn.call(win, e.type || e);
},
poll = function () {
try {
root.doScroll("left");
} catch (e) {
setTimeout(poll, 50);
return;
}
init("poll");
};
if (doc.readyState == "complete") fn.call(win, "lazy");
else {
if (doc.createEventObject && root.doScroll) {
try {
top = !win.frameElement;
} catch (e) {}
if (top) poll();
}
doc[add](pre + "DOMContentLoaded", init, false);
doc[add](pre + "readystatechange", init, false);
win[add](pre + "load", init, false);
}
}
var Cookies = {
get: function (key) {
return decodeURIComponent(doc.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
set: function (key, val, end, path, domain, secure) {
if (!key || /^(?:expires|max\-age|path|domain|secure)$/i.test(key)) {
return false;
}
var expires = "";
if (end) {
switch (end.constructor) {
case Number:
expires = end === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + end;
break;
case String:
expires = "; expires=" + end;
break;
case Date:
expires = "; expires=" + end.toUTCString();
break;
}
}
doc.cookie = encodeURIComponent(key) + "=" + encodeURIComponent(val) + expires + (domain ? "; domain=" + domain : "") + (path ? "; path=" + path : "") + (secure ? "; secure" : "");
return true;
},
has: function (key) {
return new RegExp("(?:^|;\\s*)" + encodeURIComponent(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=").test(doc.cookie);
},
remove: function (key, path, domain) {
if (!key || !this.has(key)) {
return false;
}
doc.cookie = encodeURIComponent(key) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (domain ? "; domain=" + domain : "") + (path ? "; path=" + path : "");
return true;
},
};
var Utils = {
merge: function () {
var obj = {},
i = 0,
al = arguments.length,
key;
if (0 === al) {
return obj;
}
for (; i < al; i++) {
for (key in arguments[i]) {
if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
obj[key] = arguments[i][key];
}
}
}
return obj;
},
str2bool: function (str) {
str = "" + str;
switch (str.toLowerCase()) {
case "false":
case "no":
case "0":
case "":
return false;
default:
return true;
}
},
fade_in: function (el) {
if (el.style.opacity < 1) {
el.style.opacity = (parseFloat(el.style.opacity) + 0.05).toFixed(2);
win.setTimeout(function () {
Utils.fade_in(el);
}, 50);
}
},
get_data_attribs: function (script) {
var data = {};
if (Object.prototype.hasOwnProperty.call(script, "dataset")) {
data = script.dataset;
} else {
var attribs = script.attributes;
var key;
for (key in attribs) {
if (Object.prototype.hasOwnProperty.call(attribs, key)) {
var attr = attribs[key];
if (/^data-/.test(attr.name)) {
var camelized = Utils.camelize(attr.name.substr(5));
data[camelized] = attr.value;
}
}
}
}
return data;
},
normalize_keys: function (options_object) {
var camelized = {};
for (var key in options_object) {
if (Object.prototype.hasOwnProperty.call(options_object, key)) {
var camelized_key = Utils.camelize(key);
camelized[camelized_key] = options_object[camelized_key] ? options_object[camelized_key] : options_object[key];
}
}
return camelized;
},
camelize: function (str) {
var separator = "-",
match = str.indexOf(separator);
while (match != -1) {
var last = match === str.length - 1,
next = last ? "" : str[match + 1],
upnext = next.toUpperCase(),
sep_substr = last ? separator : separator + next;
str = str.replace(sep_substr, upnext);
match = str.indexOf(separator);
}
return str;
},
find_script_by_id: function (id) {
var scripts = doc.getElementsByTagName("script");
for (var i = 0, l = scripts.length; i < l; i++) {
if (id === scripts[i].id) {
return scripts[i];
}
}
return null;
},
};
var script_el_invoker = Utils.find_script_by_id("cookiebanner");
var Cookiebanner = (context.Cookiebanner = function (opts) {
this.init(opts);
});
Cookiebanner.prototype = {
cookiejar: Cookies,
init: function (opts) {
this.inserted = false;
this.closed = false;
this.test_mode = false;
var default_text = "This site uses cookies.";
var default_link = "Detail";
this.default_options = {
cookie: "cookiebanner-accepted",
closeText: "✖",
cookiePath: "/",
debug: false,
expires: Infinity,
zindex: 255,
mask: false,
maskOpacity: 0.5,
maskBackground: "#000",
height: "auto",
minHeight: "21px",
bg: "#000",
fg: "#ddd",
link: "#aaa",
position: "bottom",
message: default_text,
linkmsg: default_link,
moreinfo: "http://www.examplesite123.com/cookie-policy/",
effect: null,
fontSize: "14px",
fontFamily: "arial, sans-serif",
instance: global_instance_name,
textAlign: "center",
acceptOnScroll: true,
};
this.options = this.default_options;
this.script_el = script_el_invoker;
if (this.script_el) {
var data_options = Utils.get_data_attribs(this.script_el);
this.options = Utils.merge(this.options, data_options);
}
if (opts) {
opts = Utils.normalize_keys(opts);
this.options = Utils.merge(this.options, opts);
}
global_instance_name = this.options.instance;
this.options.zindex = parseInt(this.options.zindex, 10);
this.options.mask = Utils.str2bool(this.options.mask);
if ("string" === typeof this.options.expires) {
if ("function" === typeof context[this.options.expires]) {
this.options.expires = context[this.options.expires];
}
}
if ("function" === typeof this.options.expires) {
this.options.expires = this.options.expires();
}
if (this.script_el) {
this.run();
}
},
log: function () {
if ("undefined" !== typeof console) {
console.log.apply(console, arguments);
}
},
run: function () {
if (!this.agreed()) {
var self = this;
contentLoaded(win, function () {
self.insert();
});
}
},
build_viewport_mask: function () {
var mask = null;
if (true === this.options.mask) {
var mask_opacity = this.options.maskOpacity;
var bg = this.options.maskBackground;
var mask_markup =
'<div id="cookiebanner-mask" style="' +
"position:fixed;top:0;left:0;width:100%;height:100%;" +
"background:" +
bg +
";zoom:1;filter:alpha(opacity=" +
mask_opacity * 100 +
");opacity:" +
mask_opacity +
";" +
"z-index:" +
this.options.zindex +
';"></div>';
var el = doc.createElement("div");
el.innerHTML = mask_markup;
mask = el.firstChild;
}
return mask;
},
agree: function () {
this.cookiejar.set(this.options.cookie, 1, this.options.expires, this.options.cookiePath);
return true;
},
agreed: function () {
return this.cookiejar.has(this.options.cookie);
},
close: function () {
if (this.inserted) {
if (!this.closed) {
if (this.element) {
this.element.parentNode.removeChild(this.element);
}
if (this.element_mask) {
this.element_mask.parentNode.removeChild(this.element_mask);
}
this.closed = true;
}
}
return this.closed;
},
agree_and_close: function () {
this.agree();
return this.close();
},
cleanup: function () {
this.close();
return this.unload();
},
unload: function () {
if (this.script_el) {
this.script_el.parentNode.removeChild(this.script_el);
}
context[global_instance_name] = undefined;
return true;
},
insert: function () {
this.element_mask = this.build_viewport_mask();
var zidx = this.options.zindex;
if (this.element_mask) {
zidx += 1;
}
var el = doc.createElement("div");
el.className = "cookiebanner";
el.style.position = "fixed";
el.style.left = 0;
el.style.right = 0;
el.style.height = this.options.height;
el.style.minHeight = this.options.minHeight;
el.style.zIndex = zidx;
el.style.background = this.options.bg;
el.style.color = this.options.fg;
el.style.lineHeight = el.style.minHeight;
el.style.padding = "5px 16px";
el.style.fontFamily = this.options.fontFamily;
el.style.fontSize = this.options.fontSize;
el.style.textAlign = this.options.textAlign;
if ("top" === this.options.position) {
el.style.top = 0;
} else {
el.style.bottom = 0;
}
el.innerHTML = '<div class="cookiebanner-close" style="float:right;padding-left:5px;">' + this.options.closeText + "</div>" + "<span>" + this.options.message + " <a>" + this.options.linkmsg + "</a></span>";
this.element = el;
var el_a = el.getElementsByTagName("a")[0];
el_a.href = this.options.moreinfo;
el_a.target = "_blank";
el_a.style.textDecoration = "none";
el_a.style.color = this.options.link;
var el_x = el.getElementsByTagName("div")[0];
el_x.style.cursor = "pointer";
function on(el, ev, fn) {
var add = el.addEventListener ? "addEventListener" : "attachEvent",
pre = el.addEventListener ? "" : "on";
el[add](pre + ev, fn, false);
}
var self = this;
on(el_x, "click", function () {
self.agree_and_close();
});
if (this.element_mask) {
on(this.element_mask, "click", function () {
self.agree_and_close();
});
doc.body.appendChild(this.element_mask);
}
if (this.options.acceptOnScroll) {
on(window, "scroll", function () {
self.agree_and_close();
});
}
doc.body.appendChild(this.element);
this.inserted = true;
if ("fade" === this.options.effect) {
this.element.style.opacity = 0;
Utils.fade_in(this.element);
} else {
this.element.style.opacity = 1;
}
},
};
if (script_el_invoker) {
if (!context[global_instance_name]) {
context[global_instance_name] = new Cookiebanner();
}
}
})(window);
I load it in this way in functions.php in Wordpress:
function wpb_hook_javascript() {
?>
<script defer type="text/javascript" id="cookiebanner" src="https://www.examplesite123.com/cookiebar.js"></script>
<?php
}
add_action('wp_head', 'wpb_hook_javascript');
It works fine.
Now i duplicate the same javascript code and i called it stickybar.js. I add some modifications, also change class with name "stickybar":
The code of the stickybar.js is here (i pasted it in jsfiddle because there is too much text for stackoverflow)
Then i show this second bar (stickybar.js) only on mobile device and after 8 second with this CSS:
.stickybar { display: none; }
#media only screen and (max-device-width:480px) {
.stickybar {
display: block;
animation: cssAnimation 0s 8s forwards;
visibility: hidden;
}
#keyframes cssAnimation {
to { visibility: visible; }
}
}
I load it in Wordpress with this code in functions.php:
function wpb_hook_javascript() {
?>
<script defer type="text/javascript" id="cookiebanner" src="https://www.examplesite123.com/stickybar.js"></script>
<?php
}
add_action('wp_head', 'wpb_hook_javascript');
It works fine.
If i load one by one of this codes, they work fine.
The problem is that when i load the two scripts together in this way in functions.php, only the first works:
function wpb_hook_javascript() {
?>
<script defer type="text/javascript" id="cookiebanner" src="https://www.examplesite123.com/cookiebar.js"></script>
<script defer type="text/javascript" id="cookiebanner" src="https://www.examplesite123.com/stickybar.js"></script>
<?php
}
add_action('wp_head', 'wpb_hook_javascript');
How can i load the two scripts together?
The comment thread on this question is semantically correct, you can only have one instance of each html id attribute, they must be unique, and your find_script_by_id methods are both searching for the same thing.
However, you're doing what's generally called "baking in" the scripts into your header which is at best, a faux pas, at least as far as WordPress is concerned. Properly Enqueueing Scripts (and styles) is very easy in WordPress, and your future self, web clients, and other people who look at your code will thank you for doing it.
It's not unlike how you're "baking in" the scripts now:
function wpb_hook_javascript() {
?>
<script defer type="text/javascript" id="cookiebanner" src="https://www.examplesite123.com/cookiebar.js"></script>
<script defer type="text/javascript" id="cookiebanner" src="https://www.examplesite123.com/stickybar.js"></script>
<?php
}
add_action('wp_head', 'wpb_hook_javascript');
But with a few things changed:
function enqueue_my_scripts(){
wp_enqueue_script( 'cookie-bar', 'https://www.examplesite123.com/cookiebar.js', array(), '1.0', true );
wp_enqueue_script( 'sticky-bar', 'https://www.examplesite123.com/stickybar.js', array(), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'enqueue_my_scripts' );
Namely, it uses the wp_enqueue_script() function on the wp_enqueue_scripts hook. This lets you defer the script to the footer, load in the header, add version numbers to prevent caching issues, add dependencies, allows you to dynamically add/remove them programatically,gives them unique ID's based on the handle, and much more. (You do still need to update your find_script_by_id functions to use these new handles instead cookie-bar, sticky-bar, change the global_instance_name, etc. (more on that in a second)
With that said, if the .js files are on your server, you'll want to use site_url(), plugins_url(), get_stylesheet_directory_uri(), or similar functions to grab the URL of the file instead of typing it out. If you're using a remote resource, don't worry about it, but if they're on you're site, you should swap out the baked in version for that so you don't have issues if you ever move your site, and it allows you easier methods to edit the version to prevent caching problems if you change them.
Back to your variables, you may also want to replace your find_script_by_id type functions with document.currentScript instead, to allow them to be more abstract and not rely on typo/duplicate prone element IDs, and instead reference the currently running <script> tag.

Change the rangeslider's starting point videojs

I am using videojs in my react application. I have added rangeslider to it. There is a button near my video player which triggers the rangeslider to show up on the video player. Every thing works fine, but the rangeslider's start arrow is not at the point (time) where I clicked the button. The starting button is always at time 0:0. What I want is: say the video is playing at the current time 30:00 seconds and I clicked the show button, then rangeslider should show it's starting arrow at 30 sec only and not at o sec. I can get my current time of videojs player and pass it to rangeslider.js plugin, but I don't know where to pass it.
This is my rangeslider.js (I know it's a long code but i don't know which part of it to use to achieve the result)
//----------------Load Plugin----------------//
(function () {
var videojsAddClass = function (element, className) {
element.classList.add(className);
};
var videojsRemoveClass = function (element, className) {
element.classList.remove(className);
};
var videojsFindPosition = function (element) {
return element.getBoundingClientRect();
};
var videojsRound = function (n, precision) {
return parseFloat(n.toFixed(precision));
};
var videojsFormatTime = function (totalSeconds) {
var minutes = Math.floor(totalSeconds / 60).toFixed(0);
var seconds = (totalSeconds % 60).toFixed(0);
if (seconds.length === 1) {
seconds = "0" + seconds;
}
return minutes + ':' + seconds;
};
var videojsBlockTextSelection = function () {
// TODO
};
//-- Load RangeSlider plugin in videojs
function RangeSlider_(options) {
var player = this;
player.rangeslider = new RangeSlider(player, options);
//When the DOM and the video media is loaded
function initialVideoFinished(event) {
var plugin = player.rangeslider;
//All components will be initialize after they have been loaded by videojs
for (var index in plugin.components) {
plugin.components[index].init_();
}
if (plugin.options.hidden)
plugin.hide(); //Hide the Range Slider
if (plugin.options.locked)
plugin.lock(); //Lock the Range Slider
if (plugin.options.panel == false)
plugin.hidePanel(); //Hide the second Panel
if (plugin.options.controlTime == false)
plugin.hidecontrolTime(); //Hide the control time panel
plugin._reset();
player.trigger('loadedRangeSlider'); //Let know if the Range Slider DOM is ready
}
if (player.techName == 'Youtube') {
//Detect youtube problems
player.one('error', function (e) {
switch (player.error) {
case 2:
alert("The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.");
case 5:
alert("The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.");
case 100:
alert("The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.");
break;
case 101:
alert("The owner of the requested video does not allow it to be played in embedded players.");
break;
case 150:
alert("The owner of the requested video does not allow it to be played in embedded players.");
break;
default:
alert("Unknown Error");
break;
}
});
player.on('firstplay', initialVideoFinished);
} else {
player.one('playing', initialVideoFinished);
}
}
videojs.plugin('rangeslider', RangeSlider_);
//-- Plugin
function RangeSlider(player, options) {
var player = player || this;
this.player = player;
this.components = {}; // holds any custom components we add to the player
options = options || {}; // plugin options
if (!options.hasOwnProperty('locked'))
options.locked = false; // lock slider handles
if (!options.hasOwnProperty('hidden'))
options.hidden = true; // hide slider handles
if (!options.hasOwnProperty('panel'))
options.panel = true; // Show Second Panel
if (!options.hasOwnProperty('controlTime'))
options.controlTime = true; // Show Control Time to set the arrows in the edition
this.options = options;
this.init();
}
//-- Methods
RangeSlider.prototype = {
/*Constructor*/
init: function () {
var player = this.player || {};
this.updatePrecision = 3;
//position in second of the arrows
this.start = 0;
this.end = 0;
//components of the plugin
var controlBar = player.controlBar;
var seekBar = controlBar.progressControl.seekBar;
this.components.RSTimeBar = seekBar.RSTimeBar;
this.components.ControlTimePanel = controlBar.ControlTimePanel;
//Save local component
this.rstb = this.components.RSTimeBar;
this.box = this.components.SeekRSBar = this.rstb.SeekRSBar;
this.bar = this.components.SelectionBar = this.box.SelectionBar;
this.left = this.components.SelectionBarLeft = this.box.SelectionBarLeft;
this.right = this.components.SelectionBarRight = this.box.SelectionBarRight;
this.tp = this.components.TimePanel = this.box.TimePanel;
this.tpl = this.components.TimePanelLeft = this.tp.TimePanelLeft;
this.tpr = this.components.TimePanelRight = this.tp.TimePanelRight;
this.ctp = this.components.ControlTimePanel;
this.ctpl = this.components.ControlTimePanelLeft = this.ctp.ControlTimePanelLeft;
this.ctpr = this.components.ControlTimePanelRight = this.ctp.ControlTimePanelRight;
},
show: function () {
this.options.hidden = false;
if (typeof this.rstb != 'undefined') {
this.rstb.show();
if (this.options.controlTime)
this.showcontrolTime();
}
},
hide: function () {
this.options.hidden = true;
if (typeof this.rstb != 'undefined') {
this.rstb.hide();
this.ctp.hide();
}
},
showPanel: function () {
this.options.panel = true;
if (typeof this.tp != 'undefined')
videojsRemoveClass(this.tp.el_, 'disable');
},
showcontrolTime: function () {
this.options.controlTime = true;
if (typeof this.ctp != 'undefined')
this.ctp.show();
},
hidecontrolTime: function () {
this.options.controlTime = false;
if (typeof this.ctp != 'undefined')
this.ctp.hide();
},
setValue: function (index, seconds, writeControlTime) {
//index = 0 for the left Arrow and 1 for the right Arrow. Value in seconds
var writeControlTime = typeof writeControlTime != 'undefined' ? writeControlTime : true;
var percent = this._percent(seconds);
var isValidIndex = (index === 0 || index === 1);
var isChangeable = !this.locked;
if (isChangeable && isValidIndex)
this.box.setPosition(index, percent, writeControlTime);
},
setValues: function (start, end, writeControlTime) {
//index = 0 for the left Arrow and 1 for the right Arrow. Value in seconds
var writeControlTime = typeof writeControlTime != 'undefined' ? writeControlTime : true;
this._reset();
this._setValuesLocked(start, end, writeControlTime);
},
getValues: function () { //get values in seconds
var values = {}, start, end;
start = this.start || this._getArrowValue(0);
end = this.end || this._getArrowValue(1);
return {start: start, end: end};
},
_getArrowValue: function (index) {
var index = index || 0;
var duration = this.player.duration();
duration = typeof duration == 'undefined' ? 0 : duration;
var percentage = this[index === 0 ? "left" : "right"].el_.style.left.replace("%", "");
if (percentage == "")
percentage = index === 0 ? 0 : 100;
return videojsRound(this._seconds(percentage / 100), this.updatePrecision - 1);
},
_percent: function (seconds) {
var duration = this.player.duration();
if (isNaN(duration)) {
return 0;
}
return Math.min(1, Math.max(0, seconds / duration));
},
_seconds: function (percent) {
var duration = this.player.duration();
if (isNaN(duration)) {
return 0;
}
return Math.min(duration, Math.max(0, percent * duration));
},
_reset: function () {
var duration = this.player.duration();
this.tpl.el_.style.left = '0%';
this.tpr.el_.style.left = '100%';
this._setValuesLocked(0, duration);
},
_setValuesLocked: function (start, end, writeControlTime) {
var triggerSliderChange = typeof writeControlTime != 'undefined';
var writeControlTime = typeof writeControlTime != 'undefined' ? writeControlTime : true;
if (this.options.locked) {
this.unlock();//It is unlocked to change the bar position. In the end it will return the value.
this.setValue(0, start, writeControlTime);
this.setValue(1, end, writeControlTime);
this.lock();
} else {
this.setValue(0, start, writeControlTime);
this.setValue(1, end, writeControlTime);
}
// Trigger slider change
if (triggerSliderChange) {
this._triggerSliderChange();
}
},
_checkControlTime: function (index, TextInput, timeOld) {
var h = TextInput[0],
m = TextInput[1],
s = TextInput[2],
newHour = h.value,
newMin = m.value,
newSec = s.value,
obj, objNew, objOld;
index = index || 0;
if (newHour != timeOld[0]) {
obj = h;
objNew = newHour;
objOld = timeOld[0];
} else if (newMin != timeOld[1]) {
obj = m;
objNew = newMin;
objOld = timeOld[1];
} else if (newSec != timeOld[2]) {
obj = s;
objNew = newSec;
objOld = timeOld[2];
} else {
return false;
}
var duration = this.player.duration() || 0,
durationSel;
var intRegex = /^\d+$/;//check if the objNew is an integer
if (!intRegex.test(objNew) || objNew > 60) {
objNew = objNew == "" ? "" : objOld;
}
newHour = newHour == "" ? 0 : newHour;
newMin = newMin == "" ? 0 : newMin;
newSec = newSec == "" ? 0 : newSec;
durationSel = videojs.TextTrack.prototype.parseCueTime(newHour + ":" + newMin + ":" + newSec);
if (durationSel > duration) {
obj.value = objOld;
obj.style.border = "1px solid red";
} else {
obj.value = objNew;
h.style.border = m.style.border = s.style.border = "1px solid transparent";
this.setValue(index, durationSel, false);
// Trigger slider change
this._triggerSliderChange();
}
if (index === 1) {
var oldTimeLeft = this.ctpl.el_.children,
durationSelLeft = videojs.TextTrack.prototype.parseCueTime(oldTimeLeft[0].value + ":" + oldTimeLeft[1].value + ":" + oldTimeLeft[2].value);
if (durationSel < durationSelLeft) {
obj.style.border = "1px solid red";
}
} else {
var oldTimeRight = this.ctpr.el_.children,
durationSelRight = videojs.TextTrack.prototype.parseCueTime(oldTimeRight[0].value + ":" + oldTimeRight[1].value + ":" + oldTimeRight[2].value);
if (durationSel > durationSelRight) {
obj.style.border = "1px solid red";
}
}
},
_triggerSliderChange: function () {
this.player.trigger("sliderchange");
}
};
//----------------Public Functions----------------//
//-- Public Functions added to video-js
var videojsPlayer = videojs.getComponent('Player');
//Lock the Slider bar and it will not be possible to change the arrow positions
videojsPlayer.prototype.lockSlider = function () {
return this.rangeslider.lock();
};
//Unlock the Slider bar and it will be possible to change the arrow positions
videojsPlayer.prototype.unlockSlider = function () {
return this.rangeslider.unlock();
};
//Show the Slider Bar Component
videojsPlayer.prototype.showSlider = function () {
return this.rangeslider.show();
};
//Hide the Slider Bar Component
videojsPlayer.prototype.hideSlider = function () {
return this.rangeslider.hide();
};
//Show the Panel with the seconds of the selection
videojsPlayer.prototype.showSliderPanel = function () {
return this.rangeslider.showPanel();
};
//Hide the Panel with the seconds of the selection
videojsPlayer.prototype.hideSliderPanel = function () {
return this.rangeslider.hidePanel();
};
//Show the control Time to edit the position of the arrows
videojsPlayer.prototype.showControlTime = function () {
return this.rangeslider.showcontrolTime();
};
//Hide the control Time to edit the position of the arrows
videojsPlayer.prototype.hideControlTime = function () {
return this.rangeslider.hidecontrolTime();
};
//Set a Value in second for both arrows
videojsPlayer.prototype.setValueSlider = function (start, end) {
return this.rangeslider.setValues(start, end);
};
//The video will be played in a selected section
videojsPlayer.prototype.playBetween = function (start, end) {
return this.rangeslider.playBetween(start, end);
};
//The video will loop between to values
videojsPlayer.prototype.loopBetween = function (start, end) {
return this.rangeslider.loop(start, end);
};
//Set a Value in second for the arrows
videojsPlayer.prototype.getValueSlider = function () {
return this.rangeslider.getValues();
};
//----------------Create new Components----------------//
//--Charge the new Component into videojs
var videojsSeekBar = videojs.getComponent('SeekBar');
videojsSeekBar.prototype.options_.children.push('RSTimeBar'); //Range Slider Time Bar
var videojsControlBar = videojs.getComponent('ControlBar');
videojsControlBar.prototype.options_.children.push('ControlTimePanel'); //Panel with the time of the range slider
//-- Design the new components
var videojsComponent = videojs.getComponent('Component');
/**
* Range Slider Time Bar
* #param {videojs.Player|Object} player
* #param {Object=} options
* #constructor
*/
var videojsRSTimeBar = videojs.extend(videojsComponent, {
/** #constructor */
constructor: function (player, options) {
videojsComponent.call(this, player, options);
}
});
videojsRSTimeBar.prototype.init_ = function () {
this.rs = this.player_.rangeslider;
};
videojsRSTimeBar.prototype.options_ = {
children: {
'SeekRSBar': {}
}
};
videojsRSTimeBar.prototype.createEl = function () {
return videojsComponent.prototype.createEl.call(this, 'div', {
className: 'vjs-timebar-RS',
innerHTML: ''
});
};
videojs.registerComponent('RSTimeBar', videojsRSTimeBar);
/**
* Seek Range Slider Bar and holder for the selection bars
* #param {videojs.Player|Object} player
* #param {Object=} options
* #constructor
*/
var videojsSeekRSBar = videojs.extend(videojsSeekBar, {
/** #constructor */
constructor: function (player, options) {
videojsComponent.call(this, player, options);
this.on('mousedown', this.onMouseDown);
this.on('touchstart', this.onMouseDown);
}
});
videojsSeekRSBar.prototype.init_ = function () {
this.rs = this.player_.rangeslider;
};
videojsSeekRSBar.prototype.options_ = {
children: {
'SelectionBar': {},
'SelectionBarLeft': {},
'SelectionBarRight': {},
'TimePanel': {},
}
};
videojsSeekRSBar.prototype.createEl = function () {
return videojsComponent.prototype.createEl.call(this, 'div', {
className: 'vjs-rangeslider-holder'
});
};
videojsSeekRSBar.prototype.onMouseDown = function (event) {
event.preventDefault();
videojsBlockTextSelection();
if (!this.rs.options.locked) {
this.on(document, "mousemove", videojs.bind(this, this.onMouseMove));
this.on(document, "mouseup", videojs.bind(this, this.onMouseUp));
this.on(document, "touchmove", videojs.bind(this, this.onMouseMove));
this.on(document, "touchend", videojs.bind(this, this.onMouseUp));
}
};
videojsSeekRSBar.prototype.onMouseUp = function (event) {
this.off(document, "mousemove", videojs.bind(this, this.onMouseMove), false);
this.off(document, "mouseup", videojs.bind(this, this.onMouseUp), false);
this.off(document, "touchmove", videojs.bind(this, this.onMouseMove), false);
this.off(document, "touchend", videojs.bind(this, this.onMouseUp), false);
};
videojsSeekRSBar.prototype.onMouseMove = function (event) {
var left = this.calculateDistance(event);
if (this.rs.left.pressed)
this.setPosition(0, left);
else if (this.rs.right.pressed)
this.setPosition(1, left);
//Fix a problem with the presition in the display time
var ctd = this.player_.controlBar.currentTimeDisplay;
ctd.contentEl_.innerHTML = '<span class="vjs-control-text">' + ctd.localize('Current Time') + '</span>' + videojsFormatTime(this.rs._seconds(left), this.player_.duration());
// Trigger slider change
if (this.rs.left.pressed || this.rs.right.pressed) {
this.rs._triggerSliderChange();
}
};
videojsSeekRSBar.prototype.setPosition = function (index, left, writeControlTime) {
var writeControlTime = typeof writeControlTime != 'undefined' ? writeControlTime : true;
//index = 0 for left side, index = 1 for right side
var index = index || 0;
// Position shouldn't change when handle is locked
if (this.rs.options.locked)
return false;
// Check for invalid position
if (isNaN(left))
return false;
// Check index between 0 and 1
if (!(index === 0 || index === 1))
return false;
// Alias
var ObjLeft = this.rs.left.el_,
ObjRight = this.rs.right.el_,
Obj = this.rs[index === 0 ? 'left' : 'right'].el_,
tpr = this.rs.tpr.el_,
tpl = this.rs.tpl.el_,
bar = this.rs.bar,
ctp = this.rs[index === 0 ? 'ctpl' : 'ctpr'].el_;
//Check if left arrow is passing the right arrow
if ((index === 0 ? bar.updateLeft(left) : bar.updateRight(left))) {
Obj.style.left = (left * 100) + '%';
index === 0 ? bar.updateLeft(left) : bar.updateRight(left);
this.rs[index === 0 ? 'start' : 'end'] = this.rs._seconds(left);
//Fix the problem when you press the button and the two arrow are underhand
//left.zIndex = 10 and right.zIndex=20. This is always less in this case:
if (index === 0) {
if ((left) >= 0.9)
ObjLeft.style.zIndex = 25;
else
ObjLeft.style.zIndex = 10;
}
//-- Panel
var TimeText = videojsFormatTime(this.rs._seconds(left)),
tplTextLegth = tpl.children[0].innerHTML.length;
var MaxP, MinP, MaxDisP;
if (tplTextLegth <= 4) //0:00
MaxDisP = this.player_.isFullScreen ? 3.25 : 6.5;
else if (tplTextLegth <= 5)//00:00
MaxDisP = this.player_.isFullScreen ? 4 : 8;
else//0:00:00
MaxDisP = this.player_.isFullScreen ? 5 : 10;
if (TimeText.length <= 4) { //0:00
MaxP = this.player_.isFullScreen ? 97 : 93;
MinP = this.player_.isFullScreen ? 0.1 : 0.5;
} else if (TimeText.length <= 5) {//00:00
MaxP = this.player_.isFullScreen ? 96 : 92;
MinP = this.player_.isFullScreen ? 0.1 : 0.5;
} else {//0:00:00
MaxP = this.player_.isFullScreen ? 95 : 91;
MinP = this.player_.isFullScreen ? 0.1 : 0.5;
}
if (index === 0) {
tpl.style.left = Math.max(MinP, Math.min(MaxP, (left * 100 - MaxDisP / 2))) + '%';
if ((tpr.style.left.replace("%", "") - tpl.style.left.replace("%", "")) <= MaxDisP)
tpl.style.left = Math.max(MinP, Math.min(MaxP, tpr.style.left.replace("%", "") - MaxDisP)) + '%';
tpl.children[0].innerHTML = TimeText;
} else {
tpr.style.left = Math.max(MinP, Math.min(MaxP, (left * 100 - MaxDisP / 2))) + '%';
if (((tpr.style.left.replace("%", "") || 100) - tpl.style.left.replace("%", "")) <= MaxDisP)
tpr.style.left = Math.max(MinP, Math.min(MaxP, tpl.style.left.replace("%", "") - 0 + MaxDisP)) + '%';
tpr.children[0].innerHTML = TimeText;
}
//-- Control Time
if (writeControlTime) {
var time = TimeText.split(":"),
h, m, s;
if (time.length == 2) {
h = 0;
m = time[0];
s = time[1];
} else {
h = time[0];
m = time[1];
s = time[2];
}
ctp.children[0].value = h;
ctp.children[1].value = m;
ctp.children[2].value = s;
}
}
return true;
};
videojs.registerComponent('SeekRSBar', videojsSeekRSBar);
/**
* This is the bar with the selection of the RangeSlider
* #param {videojs.Player|Object} player
* #param {Object=} options
* #constructor
*/
var videojsSelectionBar = videojs.extend(videojsComponent, {
/** #constructor */
constructor: function (player, options) {
videojsComponent.call(this, player, options);
this.on('mouseup', this.onMouseUp);
this.on('touchend', this.onMouseUp);
this.fired = false;
}
});
videojsSelectionBar.prototype.init_ = function () {
this.rs = this.player_.rangeslider;
};
videojsSelectionBar.prototype.createEl = function () {
return videojsComponent.prototype.createEl.call(this, 'div', {
className: 'vjs-selectionbar-RS'
});
};
videojsControlTimePanelRight.prototype.init_ = function () {
this.rs = this.player_.rangeslider;
this.timeOld = {};
};
videojsControlTimePanelRight.prototype.createEl = function () {
return videojsComponent.prototype.createEl.call(this, 'div', {
className: 'vjs-controltimepanel-right-RS',
innerHTML: 'End: <input type="text" id="controltimepanel" maxlength="2" value="00"/>:<input type="text" id="controltimepanel" maxlength="2" value="00"/>:<input type="text" id="controltimepanel" maxlength="2" value="00"/>'
});
};
videojsControlTimePanelRight.prototype.onKeyDown = function (event) {
this.timeOld[0] = this.el_.children[0].value;
this.timeOld[1] = this.el_.children[1].value;
this.timeOld[2] = this.el_.children[2].value;
};
videojsControlTimePanelRight.prototype.onKeyUp = function (event) {
this.rs._checkControlTime(1, this.el_.children, this.timeOld);
};
videojs.registerComponent('ControlTimePanelRight', videojsControlTimePanelRight);
})();
And this is how rangeslider looks everytime it shows up
I use
video.currentTime
But it looks like rangeslider is using
e.currentPoint

How to "dump" points selected with the LinkedBrush plugin for mpld3?

I am trying to implement a plugin that allows the user to dump relevant information about points selected by the LinkedBrush plugin. I think my question is sort of related to this example. I have meta information tied to each point via the HTMLTooltip plugin. Ideally, I would somehow be able to dump this too. In the example I linked to, the information is outputted via a prompt. I wish to be able to save this information to a text file of some kind.
Put slightly differently: How do I determine which points in a scatter plot have been selected by the LinkedBrush tool so that I can save the information?
To solves this, I ended up just editing the LinkedBrush plugin code. I added a button that, when clicked, outputs the extent of the brush window by using brush.extent(). This prints the minimum and maximum x and y coordinates. I will basically use these coordinates to trace back to the input data set and determine which points fell within the bounds of the brush. If anyone has a better idea of how to solve this, I would welcome it.
class LinkedBrush(plugins.PluginBase):
JAVASCRIPT="""
mpld3.LinkedBrushPlugin = mpld3_LinkedBrushPlugin;
mpld3.register_plugin("linkedbrush", mpld3_LinkedBrushPlugin);
mpld3_LinkedBrushPlugin.prototype = Object.create(mpld3.Plugin.prototype);
mpld3_LinkedBrushPlugin.prototype.constructor = mpld3_LinkedBrushPlugin;
mpld3_LinkedBrushPlugin.prototype.requiredProps = [ "id" ];
mpld3_LinkedBrushPlugin.prototype.defaultProps = {
button: true,
enabled: null
};
function mpld3_LinkedBrushPlugin(fig, props) {
mpld3.Plugin.call(this, fig, props);
if (this.props.enabled === null) {
this.props.enabled = !this.props.button;
}
var enabled = this.props.enabled;
if (this.props.button) {
var BrushButton = mpld3.ButtonFactory({
buttonID: "linkedbrush",
sticky: true,
actions: [ "drag" ],
onActivate: this.activate.bind(this),
onDeactivate: this.deactivate.bind(this),
onDraw: function() {
this.setState(enabled);
},
icon: function() {
return mpld3.icons["brush"];
}
});
this.fig.buttons.push(BrushButton);
var my_icon = "data:image/png;base64,longstring_that_I_redacted";
var SaveButton = mpld3.ButtonFactory({
buttonID: "save",
sticky: false,
onActivate: this.get_selected.bind(this),
icon: function(){return my_icon;},
});
this.fig.buttons.push(SaveButton);
}
this.extentClass = "linkedbrush";
}
mpld3_LinkedBrushPlugin.prototype.activate = function() {
if (this.enable) this.enable();
};
mpld3_LinkedBrushPlugin.prototype.deactivate = function() {
if (this.disable) this.disable();
};
mpld3_LinkedBrushPlugin.prototype.get_selected = function() {
if (this.get_selected) this.get_selected();
};
mpld3_LinkedBrushPlugin.prototype.draw = function() {
var obj = mpld3.get_element(this.props.id);
if (obj === null) {
throw "LinkedBrush: no object with id='" + this.props.id + "' was found";
}
var fig = this.fig;
if (!("offsets" in obj.props)) {
throw "Plot object with id='" + this.props.id + "' is not a scatter plot";
}
var dataKey = "offsets" in obj.props ? "offsets" : "data";
mpld3.insert_css("#" + fig.figid + " rect.extent." + this.extentClass, {
fill: "#000",
"fill-opacity": .125,
stroke: "#fff"
});
mpld3.insert_css("#" + fig.figid + " path.mpld3-hidden", {
stroke: "#ccc !important",
fill: "#ccc !important"
});
var dataClass = "mpld3data-" + obj.props[dataKey];
var brush = fig.getBrush();
var dataByAx = [];
fig.axes.forEach(function(ax) {
var axData = [];
ax.elements.forEach(function(el) {
if (el.props[dataKey] === obj.props[dataKey]) {
el.group.classed(dataClass, true);
axData.push(el);
}
});
dataByAx.push(axData);
});
var allData = [];
var dataToBrush = fig.canvas.selectAll("." + dataClass);
var currentAxes;
function brushstart(d) {
if (currentAxes != this) {
d3.select(currentAxes).call(brush.clear());
currentAxes = this;
brush.x(d.xdom).y(d.ydom);
}
}
function brushmove(d) {
var data = dataByAx[d.axnum];
if (data.length > 0) {
var ix = data[0].props.xindex;
var iy = data[0].props.yindex;
var e = brush.extent();
if (brush.empty()) {
dataToBrush.selectAll("path").classed("mpld3-hidden", false);
} else {
dataToBrush.selectAll("path").classed("mpld3-hidden", function(p) {
return e[0][0] > p[ix] || e[1][0] < p[ix] || e[0][1] > p[iy] || e[1][1] < p[iy];
});
}
}
}
function brushend(d) {
if (brush.empty()) {
dataToBrush.selectAll("path").classed("mpld3-hidden", false);
}
}
this.get_selected = function(d) {
var brush = fig.getBrush();
var extent = brush.extent();
alert(extent);
}
this.enable = function() {
this.fig.showBrush(this.extentClass);
brush.on("brushstart", brushstart).on("brush", brushmove).on("brushend", brushend);
this.enabled = true;
};
this.disable = function() {
d3.select(currentAxes).call(brush.clear());
this.fig.hideBrush(this.extentClass);
this.enabled = false;
};
this.disable();
};
"""
def __init__(self, points, button=True, enabled=True):
if isinstance(points, mpl.lines.Line2D):
suffix = "pts"
else:
suffix = None
self.dict_ = {"type": "linkedbrush",
"button": button,
"enabled": False,
"id": utils.get_id(points, suffix)}

jquery auto complete load when type somthing in search box

I use jquery auto complete on my site I have many keywords in auto complete script so my site load slow please tell me any method to load jquery auto complete when user type something on search box this will help to load page fast.
check my site: www.playorplays.com
$(document).ready(function() {
var availableTags = ["", ""];
var otherTags = [
"Video",
"Song",
"Full",
"Movie",
"HD",
"1080p",
""];
var faux = $("#faux");
var offsets;
var arrayused;
var calcfaux;
var retresult;
var checkspace;
var contents = $('#s')[0];
var carpos;
var fauxpos;
var tier;
var startss;
var endss;
function getCaret(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
function split(val) {
return val.split(/ \s*/);
}
function extractLast(term) {
return split(term).pop();
}
$("#s").on("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {
event.preventDefault();
}
}).click(function(event) {
carpos = getCaret(contents);
fauxpos = faux.text().length;
if (carpos < fauxpos) {
tier = "close";
$(this).autocomplete("close");
startss = this.selectionStart;
endss = this.selectionEnd;
$(this).val($(this).val().replace(/ *$/, ''));
this.setSelectionRange(startss, endss);
} else {
tier = "open";
}
}).on("keyup", function(event) {
calcfaux = faux.text($(this).val());
fauxpos = faux.text().length;
if (/ $/.test(faux.text()) || tier === "close") {
checkspace = "space";
} else {
checkspace = "nospace";
} if (fauxpos <= 1) {
offsets = 0;
tier = "open";
}
carpos = getCaret(contents);
if (carpos < fauxpos) {
tier = "close";
$(this).autocomplete("close");
startss = this.selectionStart;
endss = this.selectionEnd;
$(this).val($(this).val().replace(/ *$/, ''));
this.setSelectionRange(startss, endss);
} else {
tier = "open";
}
}).autocomplete({
minLength: 1,
search: function(event, ui) {
var input = $(event.target);
if (checkspace === "space") {
input.autocomplete("close");
return false;
}
},
source: function(request, response) {
var terme = $.ui.autocomplete.escapeRegex(extractLast(request.term)),
startsWithMatchere = new RegExp("^" + terme, "i"),
startsWithe = $.grep(availableTags, function(value) {
return startsWithMatchere.test(value.label || value.value || value);
}),
containsMatchere = new RegExp(terme, "i"),
containse = $.grep(availableTags, function(value) {
return $.inArray(value, startsWithe) < 0 && containsMatchere.test(value.label || value.value || value);
});
var term = $.ui.autocomplete.escapeRegex(extractLast(request.term)),
startsWithMatcher = new RegExp("^" + term, "i"),
startsWith = $.grep(otherTags, function(value) {
return startsWithMatcher.test(value.label || value.value || value);
}),
containsMatcher = new RegExp(term, "i"),
contains = $.grep(otherTags, function(value) {
return $.inArray(value, startsWith) < 0 && containsMatcher.test(value.label || value.value || value);
});
if (offsets == 0) {
retresult = startsWithe.concat(containse);
arrayused = "availableTags";
response(startsWithe.concat(containse));
}
if (retresult == "" || offsets != 0) {
arrayused = "otherTags";
response(startsWith.concat(contains));
}
},
open: function(event, ui) {
var input = $(event.target),
widget = input.autocomplete("widget"),
style = $.extend(input.css(["font", "border-left", "padding-left"]), {
position: "absolute",
visibility: "hidden",
"padding-right": 0,
"border-right": 0,
"white-space": "pre",
"font-size": "16px",
"font-weight": "bold"
}),
div = $("<div/>"),
pos = {
my: "left top",
collision: "none"
},
offset = 0;
div.text(input.val().replace(/\S*$/, "")).css(style).insertAfter(input);
offset = Math.min(Math.max(offset + div.width(), 0), input.width() - widget.width());
if (arrayused === "otherTags") {
widget.css("width", "");
offset = Math.min(Math.max(offset + div.width(), 0), input.width() - widget.width());
}
div.remove();
pos.at = "left+" + offset + " bottom";
input.autocomplete("option", "position", pos);
widget.position($.extend({
of: input
}, pos));
offsets = offset;
},
focus: function() {
return false;
},
select: function(event, ui) {
var terms = split(this.value);
terms.pop();
terms.push(ui.item.value);
terms.push("");
this.value = terms.join(" ");
calcfaux = faux.text($(this).val());
if (/ $/.test(faux.text())) {
checkspace = "space";
} else {
checkspace = "nospace";
}
carpos = getCaret(contents);
fauxpos = faux.text().length;
return false;
}
});
});
Try to avoid triggering auto completing for the single key entry;Wait at least user enter three key board inputs.
And if your keep your key words in a static array it wont be affect to the speed of the page load.
But the size of your images, .css files, .js files will directly affect to speed of the page load.
try to compress those files and use light weight images.
And try to reduce the round trip time. In order to do that use your basic styling in your html page.
and do research in how to reduce the page load time.
and check your site with google developer page speed insights (https://developers.google.com/speed/pagespeed/insights/)
and read the tips.....

How to create a plugin to add attachment or file in rich text editor of Adobe CQ 5?

I need help in creating a plugin for rich text editor in Adobe cq 5 to add an image, pdf, video, ppt or any file into rich text editor.
The existing rte plugins that are available are findreplace, undo, spellcheck, table etc
How to create a plugin to add a file to rich text editor?
The plugins are an ext js files. Appreciate if any one can suggest answer. It will be of great help.
Thanks
I added a custom drop down into my RTE. It was used to add values to the editor on selecting values from it. I think this might help you solve your issue because similarly you can create your required plugin.
Please refer comments next to the methods for your reference.
/**
* Placeholder Plugin
*/
var keyvalueEnteries = [];
var newText;
var doc;
var range
CUI.rte.plugins.PlaceholderPlugin = new Class({
toString: "PlaceholderPlugin",
extend: CUI.rte.plugins.Plugin,
/**
* #private
*/
cachedFormats: null,
/**
* #private
*/
formatUI: null,
getFeatures: function() {
return [ "Myparaformat" ];
},
/**
* #private
*
*/
getKeys: function() {
var com = CUI.rte.Common;
if (this.cachedFormats == null) {
this.cachedFormats = this.config.formats || { };
com.removeJcrData(this.cachedFormats);
this.cachedFormats = com.toArray(this.cachedFormats, "tag", "description");
}
return this.cachedFormats;
},
initializeUI: function(tbGenerator) {
var plg = CUI.rte.plugins;
var ui = CUI.rte.ui;
if (this.isFeatureEnabled("placeHolder")) {
this.formatUI = tbGenerator.createParaFormatter("placeHolder", this,null,this.getKeys());
tbGenerator.addElement("placeHolder", plg.Plugin.SORT_PARAFORMAT, this.formatUI,
10);
}
},
notifyPluginConfig: function(pluginConfig) { //This function gets executed once on load of RTE for the first time
var url = pluginConfig.sourceURL;
keyvalueEnteries = CQ.HTTP.eval(url);
keyvalueEnteries = JSON.stringify(keyvalueEnteries);
if(keyvalueEnteries == undefined){
keyvalueEnteries = '[{"key":"","value":"None"}]';
}
pluginConfig = pluginConfig || { };
//creating JSON sttructure
var placeholderJSON = '{"formats":' + keyvalueEnteries + '}';
var placeHolderVals = eval('(' + placeholderJSON + ')');
var defaults = placeHolderVals;
if (pluginConfig.formats) {
delete defaults.formats;
}
CUI.rte.Utils.applyDefaults(pluginConfig, defaults);
this.config = pluginConfig;
},
execute: function(cmd) { // This function gets executed when there is change in the state of custom plugin/drop down
if (this.formatUI) {
var formatId = this.formatUI.getSelectedFormat();
if (formatId && range != undefined) {
var placeholderElement = "";
if(formatId == 'none' && range.collapsed == false){//checks if None is selected in placeholder and the text is selected
range.deleteContents();
}else if(formatId != 'none'){
placeholderElement = document.createTextNode(" ${" + formatId + "} ");
range.insertNode(placeholderElement); //INSERTS PLACEHOLDER AT CURRENT CARET LOCATION
range.setStartAfter(placeholderElement);//INSERTS CURSOR AT THE END OF CURRENT PLACEHOLDER IF PLACEHOLDER IS SELECTED AGAIN
}
}
}
},
updateState: function(selDef) { // This function gets executed on click on the editor space in RTE
doc = selDef.editContext.doc; //GET THE DOCUMENT INSIDE THE IFRAME
range = doc.getSelection().getRangeAt(0); //GETS CURRENT CARET POSITION
}
});
//register plugin
CUI.rte.plugins.PluginRegistry.register("placeholder",
CUI.rte.plugins.PlaceholderPlugin);
CUI.rte.ui.ext.ParaFormatterImpl = new Class({
toString: "ParaFormatterImpl",
extend: CUI.rte.ui.TbParaFormatter,
// Interface implementation ------------------------------------------------------------
addToToolbar: function(toolbar) {
var com = CUI.rte.Common;
this.toolbar = toolbar;
if (com.ua.isIE) {
// the regular way doesn't work for IE anymore with Ext 3.1.1, hence working
// around
var helperDom = document.createElement("span");
helperDom.innerHTML = "<select class=\"x-placeholder-select\">"
+ this.createFormatOptions() + "</select>";
this.formatSelector = CQ.Ext.get(helperDom.childNodes[0]);
} else {
this.formatSelector = CQ.Ext.get(CQ.Ext.DomHelper.createDom({
tag: "select",
cls: "x-placeholder-select",
html: this.createFormatOptions()
}));
}
this.initializeSelector();
toolbar.add(
CQ.I18n.getMessage("Placeholder"), // Type the name you want to appear in RTE for the custom plugin /drop down
" ",
this.formatSelector.dom);
},
/**
* Creates HTML code for rendering the options of the format selector.
* #return {String} HTML code containing the options of the format selector
* #private
*/
createFormatOptions: function() {
var htmlCode = "";
if (this.formats) {
var formatCnt = this.formats.length;
htmlCode += "<option value='none'>None</option>";
for (var f = 0; f < formatCnt; f++) {
var text = this.formats[f].text;
htmlCode += "<option value=\"" + this.formats[f].value + "\">" + text
+ "</option>";
}
}
return htmlCode;
},
createToolbarDef: function() {
return {
"xtype": "panel",
"itemId": this.id,
"html": "<select class=\"x-placeholder-select\">"
+ this.createFormatOptions() + "</select>",
"listeners": {
"afterrender": function() {
var item = this.toolbar.items.get(this.id);
if (item && item.body) {
this.formatSelector = CQ.Ext.get(item.body.dom.childNodes[0]);
this.initializeSelector();
}
},
"scope": this
}
};
},
initializeSelector: function() {
this.formatSelector.on('change', function() {
var format = this.formatSelector.dom.value;
if (format.length > 0) {
this.plugin.execute(this.id);
}
}, this);
this.formatSelector.on('focus', function() {
this.plugin.editorKernel.isTemporaryBlur = true;
}, this);
// fix for a Firefox problem that adjusts the combobox' height to the height
// of the largest entry
this.formatSelector.setHeight(20);
},
getSelectorDom: function() {
return this.formatSelector.dom;
},
getSelectedFormat: function() {
var format;
if (this.formatSelector) {
format = this.formatSelector.dom.value;
if (format.length > 0) {
return format;
}
} else {
var item = this.toolbar.items.get(this.id);
if (item.getValue()) {
return item;
}
}
return null;
},
selectFormat: function(formatToSelect, auxRoot, formatCnt, noFormatCnt) {
var indexToSelect = -1;
var selectorDom = this.formatSelector.dom;
if ((formatToSelect != null) && (formatCnt == 1) && (noFormatCnt == 0)) {
var options = selectorDom.options;
for (var optIndex = 0; optIndex < options.length; optIndex++) {
var optionToCheck = options[optIndex];
if (optionToCheck.value == formatToSelect) {
indexToSelect = optIndex;
break;
}
}
}
selectorDom.disabled = (noFormatCnt > 0) && (auxRoot == null);
selectorDom.selectedIndex = indexToSelect;
}
});

Categories