Set window width in jsDom? - node.js

Should be a simple question. How do I set the width in a jsDom object?
jsdom.env({
url:'http://testdatalocation',
scripts: ['http://code.jquery.com/jquery.js'],
done: function(errors, tstWindow) {
console.log(tstWindow.innerWidth);
};
}
});
I can't figure out how to get the "innerWidth" to be anything but 1024

The resizeTo and resizeBy methods are not implemented. You can see that by searching through the code base of jsdom:
$ grep -P 'resize(To|By)' `find . -type f`
./lib/jsdom/browser/index.js: resizeBy: NOT_IMPLEMENTED(null, 'window.resizeBy'),
./lib/jsdom/browser/index.js: resizeTo: NOT_IMPLEMENTED(null, 'window.resizeTo'),
If you just want to set the window size once and for all at initialization time, you could just set the innerWidth value to whatever you want. In a real browser, this is not the right way to do it, but in jsdom it would work.
However, if you have code that depends on resizeTo being present, you can add your own polyfill to the constructor that builds windows:
var jsdom = require("jsdom");
var document = jsdom.env({
html: "<html></html>",
done: function (error, w) {
console.log(w.innerWidth, w.innerHeight);
w.constructor.prototype.resizeTo = function (width, height) {
this.innerWidth = this.outerWidth = width;
this.innerHeight = this.outerHeight = height;
};
w.resizeTo(100, 200);
console.log(w.innerWidth, w.innerHeight);
}
});
This displays:
1024 768
100 200
The code above is for illustration purposes. I've not thought about all the ins and outs of writing a polyfill for resizeTo. resizeBy would be handled similarly but would add deltas to the size of the window.

There isn't currently a formal option or API for doing so.
The values of innerWidth and similar properties are simply set to literal values:
DOMWindow.prototype = createFrom(dom || null, {
// ...
name: 'nodejs',
innerWidth: 1024,
innerHeight: 768,
outerWidth: 1024,
outerHeight: 768,
// ...
});
Beyond test cases and documentation, outerWidth isn't referenced elsewhere else in jsdom, so you could probably assign a new value within the created event, updating outerWidth as well.
The primary use-case for created is to modify the window object (e.g. add new functions on built-in prototypes) before any scripts execute.
created: function (errors, tstWindow) {
tstWindow.outerWidth = tstWindow.innerWidth = 1440;
},
done: function(errors, tstWindow) {
console.log(tstWindow.innerWidth);
}

Related

PhaserJS: After Rotation of camera dragging a Sprite gives strange coords

Basically the problem is that after you rotate the camera, the points that are given as arguments in the callback for dragging are not what I expected. I'm guessing I have to Rotate the given points also but I just couldn't.
Can Someone explain what is going on, is this some kind of bug or what should I do in order the sprite to follow the mouse cursor?
Easiest way to explain the problem is to reproduce it:
1) Go to Phaser Example Runner
2) Copy- Paste this code:
var config = {
type: Phaser.WEBGL,
parent: 'phaser-example',
scene: {
preload: preload,
create: create
}
};
var game = new Phaser.Game(config);
function preload ()
{
this.load.image('eye', 'assets/pics/lance-overdose-loader-eye.png');
}
function create ()
{
var image = this.add.sprite(200, 300, 'eye').setInteractive();
this.cameras.main.setRotation(Math.PI);
image.on('pointerover', function () {
this.setTint(0x00ff00);
});
image.on('pointerout', function () {
this.clearTint();
});
this.input.setDraggable(image);
this.input.on('dragstart', function (pointer, gameObject) {
gameObject.setTint(0xff0000);
});
this.input.on('drag', function (pointer, gameObject, dragX, dragY) {
console.log(`x: ${dragX}, y: ${dragY}`);
gameObject.x = dragX;
gameObject.y = dragY;
});
this.input.on('dragend', function (pointer, gameObject) {
gameObject.clearTint();
});
}
3) Open the console, drag around the Eye and look at what coordinates are given.
4) If you remove line 24 (the rotation of the camera) Everything works as expected.
(The example is taken from Phaser 3 Official examples and a bit changed for the bug)
According to Phaser's API Documentation on the setRotation() method, the rotation given in radians applies to everything rendered by the camera. Unfortunately, your pointer isn't rendered by the camera so it doesn't get the same rotated coordinates. Not sure if this is a bug with the library or just a poorly documented exception, but I believe there is a workaround.
Create 2 variables to hold an initial position and a final position:
var image = this.add.sprite(200, 300, 'eye').setInteractive();
var initial = [];
var final = [];
Populate the initial position in your .on('dragstart') method:
this.input.on('dragstart', function (pointer, gameObject) {
initial = [
gameObject.x,
gameObject.y,
pointer.x,
pointer.y
];
gameObject.setTint(0xff0000);
});
Then, populate the final variable in your .on('drag') method:
this.input.on('drag', function (pointer, gameObject, dragX, dragY) {
final = [
gameObject.x, // not necessary but keeping for variable shape consistency
gameObject.y, // not necessary but keeping for variable shape consistency
pointer.x,
pointer.y
];
gameObject.x = initial[0] + (initial[2] - final[2]);
gameObject.y = initial[1] + (initial[3] - final[3]);
});
All we're doing here is keeping track of the change in pointer position and mimicking that change in our gameObject.

Is it possible to morph SVG's paths using Velocity.js?

Is it possible to morph SVG's paths using Velocity.js?
FROM
"M292,129c55.2,0,193,125.8,193,181S365.7,506,310.5,506S136,355.2,136,300S236.8,129,292,129z"
TO
"M230,38c55.2,0,348,57.8,348,113S391.2,569,336,569S55,456.2,55,401S174.8,38,230,38z"
var path = document.querySelectorAll('svg path');
Velocity(path[0], {
tween: 1000
}, {
duration: 6000,
easing: 'easeOutBounce',
progress: function (el, c, r, s, t) {
el[0].setAttribute('d', ??????);
}
});
EDIT: Please note I am the author of the code that enabled this in 2016, so it is the official supported way to do it!
Almost, should be something like this:
var path = document.querySelectorAll('svg path'),
from = "M292,129c55.2,0,193,125.8,193,181S365.7,506,310.5,506S136,355.2,136,300S236.8,129,292,129z",
to = "M230,38c55.2,0,348,57.8,348,113S391.2,569,336,569S55,456.2,55,401S174.8,38,230,38z";
Velocity(path[0], {
tween: [to, from]
}, {
duration: 6000,
easing: 'easeOutBounce',
progress: function(elements, complete, remaining, start, tweenValue) {
elements[0].setAttribute('d', tweenValue);
}
});
Edit: Velocity has some string animation support built in, see Rycochets answer below.
If not you could try doing that yourself, by breaking down the path string into an array.
One way could be to use the path data polyfill (as Chrome has deprecated that feature to give easy access to the array points) at polyfill. Then you could loop similar to below through the path points and interpolate.
You could also try using some regex to split and then build back up, a quick example could be something like the following. It's probably not complete (I haven't really tested the regex, and you may get varying number of elements if there are some characters that I haven't thought of).
$velocity=$("#mypath");
var fromPath = "M292,129c55.2,0,193,125.8,193,181S365.7,506,310.5,506S136,355.2,136,300S236.8,129,292,129z";
var toPath = "M230,38c55.2,0,348,57.8,348,113S391.2,569,336,569S55,456.2,55,401S174.8,38,230,38z";
var re = /(([+-]?[0-9\.]+)|[a-z]|\s+)([eE][-+]?[0-9]+)?/gi
var fromMatch = fromPath.match(re)
var toMatch = toPath.match(re)
$velocity.velocity(
{ opacity: 0.5, tween: [0,1] },
{ progress: function( el, complete, remaining, start, tweenValue) {
var interpPath = '';
for( c=0; c<fromMatch.length; c++) {
if( !isNaN( fromMatch[c]) ) {
interpPath += ( toMatch[c] - fromMatch[c] ) * tweenValue + +fromMatch[c]
} else {
interpPath += toMatch[c]
}
}
el[0].setAttribute('d', interpPath)
} }
)
jsfiddle

How to keep previous data in Leaflet Realtime

I am trying to use Leaflet realtime plugin (https://github.com/perliedman/leaflet-realtime), they mentioned in the documentation that we can keep previous updates by adding start:false in the constructor.
var map = L.map('map'),
realtime = L.realtime({
url: 'https://wanderdrone.appspot.com/',
crossOrigin: true,
type: 'json'
}, {
interval: 3 * 1000, start:false
}).addTo(map);
Anyone have better idea on how to do that ?
plnkr has a good demo:
http://plnkr.co/edit/NmtcUa?p=preview
If you set start: false, automatic updates will be disabled. This means you will have to call the layer's update method yourself, providing any GeoJSON data you want to add or update; you can also remove added features with the remove method. These methods can be used if you want to use something other than server polling.
You can use the following code that I copied from plnkr while changed a little bit, because L.realtime inherit L.geoJson. And L.geoJson have 'layeradd'.
realtime.on('layeradd', function(e) {
var coordPart = function(v, dirs) {
return dirs.charAt(v >= 0 ? 0 : 1) +
(Math.round(Math.abs(v) * 100) / 100).toString();
},
popupContent = function(fId) {
var feature = e.features[fId],
c = feature.geometry.coordinates;
return 'Wander drone at ' +
coordPart(c[1], 'NS') + ', ' + coordPart(c[0], 'EW');
},
bindFeaturePopup = function(fId) {
realtime.getLayer(fId).bindPopup(popupContent(fId));
},
updateFeaturePopup = function(fId) {
realtime.getLayer(fId).getPopup().setContent(popupContent(fId));
};
map.fitBounds(realtime.getBounds(), {maxZoom: 3});
Object.keys(e.enter).forEach(bindFeaturePopup);
Object.keys(e.update).forEach(updateFeaturePopup);
});

YUI3 autocomplete has images on top - How to get autocomplete to the top

My auto YUI autocomplete zindex is off. How can I force the autocomplete DIV to the top.
Below I am using a standard template for YUI:
YAHOO.util.Event.onDOMReady(function(){
YUI().use("autocomplete", "autocomplete-filters", "autocomplete-highlighters", function (Y) {
var inputNode = Y.one('#name'),
tags = [
'css',
'css3',
'douglas crockford',
'ecmascript',
'html',
'html5',
'java',
'javascript',
'json',
'node.js',
'pie',
'yui'
],
lastValue = '';
inputNode.plug(Y.Plugin.AutoComplete, {
activateFirstItem: true,
minQueryLength: 0,
queryDelay: 0,
source: tags,
resultHighlighter: 'startsWith',
resultFilters: ['startsWith']
});
// When the input node receives focus, send an empty query to display the full
// list of tag suggestions.
inputNode.on('focus', function () {
inputNode.ac.sendRequest('');
});
// When there are new AutoComplete results, check the length of the result
// list. A length of zero means the value isn't in the list, so reset it to
// the last known good value.
inputNode.ac.on('results', function (e) {
if (e.results.length) {
lastValue = inputNode.ac.get('value');
} else {
inputNode.set('value', lastValue);
}
});
// Update the last known good value after a selection is made.
inputNode.ac.after('select', function (e) {
lastValue = e.result.text;
});
});
});
Simply to put the z-index in the css. Setting via JS used to be allowed, but as of YUI 3.4.0 it's a css-only flag (https://github.com/yui/yui3/blob/master/src/autocomplete/HISTORY.md).
The relevant CSS is (adjust your z-index as necessary):
.yui3-aclist { z-index: 100; }
PS., your YAHOO. line is from YUI2, so that is quite peculiar and definitely not a standard template.
By the time your callback in the YUI().use(...) section is called, the dom should be ready. No ondomready required.

When I close a window and then open a different one, the selected tab is recreated by Chrome

I am writing a Chrome extension that saves/restores your browsers window state - So, I save the state of a given window:
var properties = [ "top",
"left",
"width",
"height",
"incognito",
"focused",
"type"
];
var json = {};
var cache = chrome_window_object;
// copy only the keys we care about:
_.each(properties,function(key,value) {
json[key] = cache[key];
});
// then copy the URLs of the tabs, if they exist:
if(cache.tabs) {
json.url = [];
_.each(cache.tabs,function(tab) {
json.url.push(tab.url);
});
}
return json;
At some point in the future, I remove all windows:
closeAllWindows: function(done_callback) {
function got_all(windows) {
var index = 0;
// use a closure to only close one window at a time:
function close_next() {
if(windows.length <= index) return;
var window = windows[index++];
chrome.windows.remove(window,close_next);
}
// start closing windows:
close_next();
}
chrome.windows.getAll(got_all);
}
and then I restore the window using:
chrome.windows.create(json_from_before);
The window that is created has an extra tab in it, whatever was in the window that I just closed... I am completely floored, and I assume the problem is something that I am doing in the code that I haven't posted (it's a big extension). I've spent a few hours checking code line by line and making sure I'm not explicitly asking for this tab to be created. So - has anybody seen anything like this before?

Resources