Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handling of Randomly changing dynamic element id, cookie/cache synchronization and visibility settings #1159

Open
wants to merge 8 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions togetherjs/cursor.js
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,7 @@ define(["jquery", "ui", "util", "session", "elementFinder", "tinycolor", "eventM
// really don't want to do anything at this stage of the event
// handling (since I'm catching every click), and I'll just do
// something real soon:
setTimeout(function () {
//setTimeout(function () {
if (! TogetherJS.running) {
// This can end up running right after TogetherJS has been closed, often
// because TogetherJS was closed with a click...
Expand Down Expand Up @@ -458,7 +458,7 @@ define(["jquery", "ui", "util", "session", "elementFinder", "tinycolor", "eventM
return;
}
displayClick({top: event.pageY, left: event.pageX}, peers.Self.color);
});
// });
}

var CLICK_TRANSITION_TIME = 3000;
Expand Down
44 changes: 43 additions & 1 deletion togetherjs/elementFinder.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,42 @@ define(["util", "jquery"], function (util, $) {
}
return false;
};
/*RANDOM ID fix start
Web Browsrs doesn't provide same element id for dynamically generated elements every time.It will become difficult to access same element
if the id is diffrent. To handle this we generated unique id of the elemnt which is kind of travesed path in DOM tree using jquery index
and on receiving side just inverted the same
*/
var getNodeIdentifier = function(element) {
return element.nodeName.toLowerCase() + "." + $(element).index();
};
var new_id =function( element) {
var current = element;
var xpath = getNodeIdentifier(element);

while (current.parentNode != null) {
xpath = getNodeIdentifier(current.parentNode) + "/" + xpath;
current = current.parentNode;
}

console.log(xpath);
return xpath;
};
var indexCalculator = function(str,splitcount) {
return parseInt(str[splitcount].split(".")[1]);
};

var string_to_element = function (string) {
var abc = document.body;
var str = string.split("/");

for( i= 2; i<str.length -1 ; i++)
{
abc = abc.children[indexCalculator(str,i+1)];
}
console.log(abc);
return abc;
};
/*RANDOM ID Fix End */
elementFinder.elementLocation = function elementLocation(el) {
assert(el !== null, "Got null element");
if (el instanceof $) {
Expand All @@ -30,7 +65,8 @@ define(["util", "jquery"], function (util, $) {
el = el[0];
}
if (el.id) {
return "#" + el.id;
return new_id(el);
// return "#" + el.id;
}
if (el.tagName == "BODY") {
return "body";
Expand Down Expand Up @@ -123,6 +159,8 @@ define(["util", "jquery"], function (util, $) {
} else if (loc.indexOf("#") === 0) {
var id;
loc = loc.substr(1);
/* RANDOM Id fix */
if (false){
if (loc.indexOf(":") === -1) {
id = loc;
rest = "";
Expand All @@ -131,6 +169,10 @@ define(["util", "jquery"], function (util, $) {
rest = loc.substr(loc.indexOf(":"));
}
el = document.getElementById(id);
} else {
el = string_to_element(loc);
}
/* RANDOM id fix end */
if (! el) {
throw elementFinder.CannotFind("#" + id, "No element by that id", container);
}
Expand Down
170 changes: 168 additions & 2 deletions togetherjs/session.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ define(["require", "util", "channels", "jquery", "storage"], function (require,
msg.peer.updateFromHello(msg);
}
if (msg.peer) {
msg.sameUrl = msg.peer.url == currentUrl;
msg.sameUrl = msg.peer.url == session.currentUrl();
if (!msg.peer.isSelf) {
msg.peer.updateMessageDate(msg);
}
Expand Down Expand Up @@ -177,7 +177,173 @@ define(["require", "util", "channels", "jquery", "storage"], function (require,
processFirstHello(msg);
}
});

*Cookie Library Change Start */
/*\
|*|
|*| :: cookies.js ::
|*|
|*| A complete cookies reader/writer framework with full unicode support.
|*|
|*| Revision #3 - July 13th, 2017
|*|
|*| https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*| https://developer.mozilla.org/User:fusionchess
|*| https://github.com/madmurphy/cookies.js
|*|
|*| This framework is released under the GNU Public License, version 3 or later.
|*| http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*| Syntaxes:
|*|
|*| * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*| * docCookies.getItem(name)
|*| * docCookies.removeItem(name[, path[, domain]])
|*| * docCookies.hasItem(name)
|*| * docCookies.keys()
|*|
\*/

var docCookies = {
getItem: function (sKey) {
if (!sKey) { return null; }
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
/*
Note: Despite officially defined in RFC 6265, the use of `max-age` is not compatible with any
version of Internet Explorer, Edge and some mobile browsers. Therefore passing a number to
the end parameter might not work as expected. A possible solution might be to convert the the
relative time to an absolute time. For instance, replacing the previous line with:
*/
/*
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; expires=" + (new Date(vEnd * 1e3 + Date.now())).toUTCString();
*/
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = sKey + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};
/*Cookie Library Change End */
session.hub.on("cookie-change",function(msg){
//console.warn("Gaurav Message Cookie", msg.cookie);
peers.getAllPeers().forEach(function(p) {
if(p.following)
{
var tempCookieObj=msg.cookie.split(';').map(function(c) {
var i = c.indexOf('=');
return [c.substring(0, i), c.substring(i + 1)];
});

tempCookieObj.forEach(function (arr) {
//debugger;
if(!docCookies.hasItem(arr[0]) && !arr[1].length)
{
docCookies.setItem(arr[0],arr[1],150,"/");
return;
}
//debugger;
if( (docCookies.getItem(arr[0]) != arr[1]))
{
docCookies.removeItem(arr[0]);
docCookies.setItem(arr[0],arr[1],150,"/");
}
});
var lStorObj = JSON.parse(JSON.stringify(msg.localStorage));
Object.keys(lStorObj).map(function(k){
/* Don't update "togetherjs" specific localstorage update only specific to application */
if(!(k.substr(0,"togetherjs".length) =="togetherjs"))
{
/* Check if key exists in localStorage
if not then create the key and value
If value is different then update */
if( !localStorage.hasOwnProperty( k))
{
localStorage.setItem(k,lStorObj[k]);
}
else( !(localStorage.getItem(k) == lStorObj[k]))
{
localStorage.setItem(k,lStorObj[k]);
}
}
});
}});
});
session.hub.on("cache-change",function(msg){
//console.warn("Gaurav Message Cache");
var lStorObj = JSON.parse(JSON.stringify(msg.localStorage));
Object.keys(lStorObj).map(function(k){
/* Don't update "togetherjs" specific localstorage update only specific to application */
if(!(k.substr(0,"togetherjs".length) =="togetherjs"))
{
/* Check if key exists in localStorage
if not then create the key and value
If value is different then update */
if( !localStorage.hasOwnProperty( k))
{
localStorage.setItem(k,lStorObj[k]);
}
else( !(localStorage.getItem(k) == lStorObj[k]))
{
localStorage.setItem(k,lStorObj[k]);
}
}
});
});
session.hub.on("started-following", function (msg) {
var resp = {
urlHash: location.hash,
cookie: document.cookie,
localStorage: window.localStorage,
// FIXME: titles update, we should track those changes:
title: document.title,
};
resp.type = "cookie-change";
session.send(resp);
});
session.hub.on("visibility", function (msg) {
if(msg.visibilityMsg.url != session.currentUrl())
return;
peers.getAllPeers().forEach(function(p) {
if(p.following){
var selectorObj = $(msg.visibilityMsg.selector);
Object.keys(selectorObj).forEach( function(key,index){
if( index < selectorObj.length){
console.log("Elements to be hidden",selectorObj[index])
if(util.matchElement(selectorObj[index],[":visible"]))
$(selectorObj[index]).hide();
}
});
}
});
});//first function
session.hub.on("who", function (msg) {
sendHello(true);
});
Expand Down
45 changes: 45 additions & 0 deletions togetherjs/togetherjs.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
// (e.g., 'canvas' would not show clicks on canvas elements.)
// Setting this to true will disable clicks globally.
dontShowClicks: false,
visibilitySelector: false,
// Experimental feature to echo clicks to certain elements across clients:
cloneClicks: false,
// Enable Mozilla or Google analytics on the page when TogetherJS is activated:
Expand Down Expand Up @@ -93,6 +94,49 @@
baseUrl = window.TogetherJSConfig_baseUrl;
}
defaultConfiguration.baseUrl = baseUrl;
/* Detect and trigger hash change inside url
also If we want to show/hide some element
*/
var prevHash = window.location.hash;
var prevCookie = document.cookie;
var prevCache = window.localStorage;
var visibilityChangeFromRemote = false;
window.setInterval(function () {
if (window.location.hash != prevHash) {
var event = document.createEvent("Event");
event.initEvent("hashchange", false, true);
window.dispatchEvent(event);
//$(window).trigger("hashchange");
//TogetherJS.reinitialize();
prevHash = window.location.hash;
//alert(window.location.hash);
var visibilitySelector = TogetherJS.config.get("visibilitySelector");
if( visibilitySelector){
var visibilityMsg = {
selector: visibilitySelector.join(","),
url:TogetherJS.require("session").currentUrl(),
urlHash: location.hash,
}
var isVisible = false;
TogetherJS.require("session").send({type:"visibility",visibilityMsg:visibilityMsg,isVisible:isVisible});
}
}
//if( window.localStorage !=prevCache){
var msg = {
urlHash: location.hash,
localStorage: window.localStorage,
cookie: document.cookie,
// FIXME: titles update, we should track those changes:
title: document.title
};
msg.type = "cookie-change";

if (TogetherJS.running) {
var session = TogetherJS.require("session");
session.send(msg);
}
// }
}, 100);

// True if this file should use minimized sub-resources:
var min = "__min__" == "__" + "min__" ? false : "__min__" == "yes";
Expand Down Expand Up @@ -554,6 +598,7 @@
// (e.g., 'canvas' would not show clicks on canvas elements.)
// Setting this to true will disable clicks globally.
dontShowClicks: false,
visibilitySelector: false,
// Experimental feature to echo clicks to certain elements across clients:
cloneClicks: false,
// Enable Mozilla or Google analytics on the page when TogetherJS is activated:
Expand Down
10 changes: 9 additions & 1 deletion togetherjs/ui.js
Original file line number Diff line number Diff line change
Expand Up @@ -1273,7 +1273,15 @@ define(["require", "jquery", "util", "session", "templates", "templating", "link
this.followCheckbox.change(function () {
if (! this.checked) {
this.peer.unfollow();
}
}else{
var msg = {
urlHash: location.hash,
title: document.title,
};
msg.type = "started-following";
session.send(msg);
this.peer.follow();
}
// Following doesn't happen until the window is closed
// FIXME: should we tell the user this?
});
Expand Down