Javascript Get Selected Text: Incorrect number of lines - javascript

I am using the following code
(function(e, t) {
"use strict";
var n = t.selection;
var i = t.getSelection;
var o = i || n;
var r = function(e) {
var t = Object.prototype.toString.call(e);
return typeof e === "object" && /^\[object (HTMLCollection|NodeList|Object)\]$/.test(t) && e.hasOwnProperty("length") && (e.length === 0 || typeof e[0] === "object" && e[0].nodeType > 0)
};
var c = function(e, t) {
var n;
return function() {
var i = this,
o = arguments;
var r = function() {
n = null;
e.apply(i, o)
};
clearTimeout(n);
n = setTimeout(r, t)
}
};
var s = function(t, n) {
this.element = t;
this.callback = n || function() {};
this.isTouch = "ontouchstart" in e;
this.hasLib = e.jQuery && t instanceof e.jQuery || e.Zepto && t instanceof e.Zepto
};
s.prototype = {
events: function() {
var e = this.callback;
var t = this.getText;
this[this.isTouch ? "bindTouch" : "bindMouseUp"](function() {
e(t())
})
},
getText: function() {
var n = "";
if (i) {
n = e.getSelection().toString()
} else if (t.selection && t.selection.type !== "Control") {
n = t.selection.createRange().text
}
return n
},
checkForSelections: function(e, t, n) {
var i;
var o = function(e) {
var n = t();
var i = setInterval(function() {
if (t() !== n) {
e(t());
n = t()
} else if (t() === "") {
clearInterval(i)
}
}, 100)
};
var r = function() {
e.removeEventListener("touchend", c, false);
e.addEventListener("touchend", c, false);
if (i) {
clearInterval(i)
}
i = setInterval(function() {
var e = t();
if (e !== "") {
n(e);
c();
o(n)
}
}, 100)
};
var c = function() {
clearInterval(i);
e.removeEventListener("touchend", c, false)
};
e.addEventListener("touchstart", r, false)
},
bindTouch: function(e) {
var t = this.checkForSelections;
var n = this.getText;
if (this.hasLib) {
this.element.each(function() {
t(this, n, e)
});
return
}
var i = function(i) {
t(i, n, e)
};
if (!r(this.element)) {
i(this.element);
return
} [].forEach.call(this.element, function(e) {
i(e)
})
},
bindMouseUp: function(e) {
if (this.hasLib) {
this.element.on("mouseup", c(e, 150));
return
}
var t = function(t) {
t.addEventListener("mouseup", c(e, 150), false)
};
if (!r(this.element)) {
t(this.element);
return
} [].forEach.call(this.element, function(e) {
t(e)
})
}
};
e.selecting = function(e, t) {
if (!o) {
return
}
new s(e, t).events()
}
})(window, document);
And :
var myElement = document.body;
window.selecting(myElement, function(selector) {
var text = selector;
instance.publishState("text", text);
});
to basically get the selected/highlighted text by the user in the browser. I then use the selected text to work with it, make API calls etc.
Getting the selected text is fine, but unfortunately the number of lines in the returned text is usually incorrect which makes it impossible for me to work with.
Let me give you an example:
The user highlights the following text on the page:
Hello this is a test
Hello this is another test
The returned value from my code however than displays this text but with more line breaks in between. So for example I get returned:
Hello this is a test
Hello this is another test
This completely breaks my functionality, as I have to exactly know how many line breaks there actually are in order to work with the text. Any ideas what could be wrong or how I can access the browsers selected text with the correct number of line breaks?

The code
window.getSelection().toString()
will return the correct selection, which will produce in your case
Hello this is a test\n\nHello this is another test
Notice how you have two \n corresponding to the 2 newlines you have.
So if you do anything like this to display what the user has selected:
console.dir(window.getSelection().toString());
You will see correctly what the user has selected
Hello this is a test
Hello this is another test

Related

I can't insert a footnote into the copied text

I'm making a way for users to insert a footnote in the text (as implemented in scientific articles). I'm using tinymce for this, and it functions as a plugin. It works fine when I type the text itself. But as soon as I try to insert a footnote with it into the copied text (that is, I copied text from another site and want to insert a footnote), it gives me an error - Uncaught ReferenceError: $node is not defined
I've already tried many attempts, but I can't get it to work. Can you please tell me what I am doing wrong?
footnote.min.js
! function () {
"use strict";
var t, e = tinymce.util.Tools.resolve("tinymce.PluginManager");
"function" != typeof Array.prototype.forEach && (Array.prototype.forEach = function (t) {
for (var e = 0; e < this.length; e++) t.apply(this, [this[e], e, this])
}), Object.defineProperty && Object.getOwnPropertyDescriptor && Object.getOwnPropertyDescriptor(Element.prototype, "textContent") && !Object.getOwnPropertyDescriptor(Element.prototype, "textContent").get && (t = Object.getOwnPropertyDescriptor(Element.prototype, "innerText"), Object.defineProperty(Element.prototype, "textContent", {
get: function () {
return t.get.call(this)
},
set: function (e) {
return t.set.call(this, e)
}
}));
var n = function (t, e) {
var n = t;
for (var o in e) n = n.replace(/\{(\/?[^\}]+)\}/gm, e[o]);
return n
},
o = function (t) {
var e = t.selection.getNode(),
o = "",
r = "SPAN" == e.tagName && "fnoteWrap" === t.dom.getAttrib(e, "class"),
i = "fnoteWrap" == e.className ? e.childNodes[0].firstChild.nodeValue.replace(/[^0-9]/g, "") : e.childNodes[0];
r && (o = e.name || decodeURIComponent(e.childNodes[0].getAttribute("data-content")) || ""), t.windowManager.open({
title: "Insert Contents",
size: "normal",
body: {
type: "panel",
items: [{
type: "textarea",
name: "name",
multiline: !0,
minWidth: 520,
minHeight: 100
}]
},
buttons: [{
type: "cancel",
name: "cancel",
text: "Cancel"
}, {
type: "submit",
name: "save",
text: "Save",
primary: !0
}],
initialData: {
name: o
},
onSubmit: function (e) {
var o, r, a, c, l = e.getData().name,
s = '<span class="fnoteWrap" id="#wk_ft{FOOTNOTE_INDEX}" contenteditable="false"><button type="button" class="fnoteBtn" data-content="' + l + '">{FOOTNOTE_INDEX}</button></span>',
f = t.getDoc().querySelectorAll(".fnoteBtn"),
u = f.length,
p = (r = t.selection.getNode(), a = function (t) {
var e = !1;
return (e = [].filter.call(t.parentNode.children, function (n) {
return n.previousElementSibling === t ? e = !0 : e
})).map(e => Array.from(e.querySelectorAll("fnoteBtn").length) > 0 ? $node.nextElementSibling.classList.contains("fnoteBtn") ? $node.nextElementSibling.children.children : e.querySelectorAll(".fnoteBtn") : "BODY" === t.nodeName ? [] : a(t.parentNode))
}, c = function (t, e) {
if (!e) return !1;
if (e) return $node;
var n = null;
return e.children.forEach(function () {
e && (n = c(t, this))
}), n
}, function (t, e) {
for (var n = a(e); 0 !== n.length;) {
var o = c(t, n);
if (null !== o) return o;
n = a(n)
}
return n
}(".fnoteBtn", r));
if (p.length) {
var d;
for (p = p[0], d = 0; d < u && p != f[d]; d++);
i < u ? o = n(s, {
FOOTNOTE_INDEX: $(f[i - 1]).html()
}) : (o = n(s, {
FOOTNOTE_INDEX: $(f[d]).html()
}), t.selection.collapse(0))
} else o = n(s, {
FOOTNOTE_INDEX: u + 1
}), t.selection.collapse(0);
t.execCommand("mceInsertContent", !1, o), e.close(), Array.from(t.getDoc().querySelectorAll(".fnoteBtn")).forEach(function (t, e) {
t.textContent = e + 1, t.parentNode.setAttribute("id", "#wk_ft" + (e + 1))
})
}
})
},
r = {
register: function (t) {
t.addCommand("footnotes", function () {
o(t)
})
}
},
i = {
register: function (t) {
t.ui.registry.addToggleButton("footnotes", {
icon: "fnote",
tooltip: "Footnote",
onAction: function () {
return t.execCommand("footnotes")
},
onSetup: function (e) {
return t.selection.selectorChangedWithUnbind("span.fnoteWrap", e.setActive).unbind
}
}), t.ui.registry.addMenuItem("footnotes", {
icon: "fnote",
onAction: function () {
return t.execCommand("footnotes")
}
})
}
};
e.add("footnotes", function (t) {
t.ui.registry.addIcon("fnote", '<img src="' + tinyMCE.baseURL + '/plugins/footnotes/img/fn.png">'), r.register(t), i.register(t)
})
}();
footnote.js
(function(){
'use strict';
var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
if (typeof Array.prototype.forEach !== 'function') {
Array.prototype.forEach = function(cb){
for (var i = 0; i < this.length; i++){
cb.apply(this, [this[i], i, this]);
}
};
}
if (Object.defineProperty
&& Object.getOwnPropertyDescriptor
&& Object.getOwnPropertyDescriptor(Element.prototype, "textContent")
&& !Object.getOwnPropertyDescriptor(Element.prototype, "textContent").get) {
(function() {
var innerText = Object.getOwnPropertyDescriptor(Element.prototype, "innerText");
Object.defineProperty(Element.prototype, "textContent",
{
get: function() {
return innerText.get.call(this);
},
set: function(s) {
return innerText.set.call(this, s);
}
}
);
})();
}
/**
*
* #param str
* #param data
* #returns {*}
*/
var replaceTmpl = function(str, data) {
var result = str;
for (var key in data) {
result = result.replace(/\{(\/?[^\}]+)\}/gm,data[key]);
}
return result;
};
/**
*
* #param editor
*/
var open = function (editor) {
var selectedNode = editor.selection.getNode(), name = '',
isFootNotes = selectedNode.tagName == 'SPAN' && editor.dom.getAttrib(selectedNode, 'class') === 'fnoteWrap';
var selectIndex = (function(){
if (selectedNode.className == 'fnoteWrap') {
var num = selectedNode.childNodes[0].firstChild.nodeValue.replace(/[^0-9]/g,'');
return num;
}
else {
return selectedNode.childNodes[0];
}
}());
if (isFootNotes) {
name = selectedNode.name || decodeURIComponent(selectedNode.childNodes[0].getAttribute('data-content')) || '';
}
editor.windowManager.open({
title: 'Insert Contents',
size: 'normal',
body: {
type: 'panel',
items : [
{
type:'textarea',
name: 'name',
multiline: true,
minWidth: 520,
minHeight: 100,
}
],
},
buttons: [
{
type: 'cancel',
name: 'cancel',
text: 'Cancel'
},
{
type: 'submit',
name: 'save',
text: 'Save',
primary: true
}
],
initialData: { name: name },
onSubmit: function (e) {
var newfootnoteContent = e.getData().name,
fixFootnoteContent = (function () {
return encodeURIComponent(newfootnoteContent);
}()),
htmlTemplate = '<span class="fnoteWrap" id="#wk_ft{FOOTNOTE_INDEX}" contenteditable="false"><button type="button" class="fnoteBtn" data-content="'+fixFootnoteContent+'">{FOOTNOTE_INDEX}</button></span>',
totalFootNote = editor.getDoc().querySelectorAll('.fnoteBtn'),
totalCount = totalFootNote.length,
html;
function findNextFD(node) {
var getNext = function(el) {
var nextAll = false,
elements;
nextAll = [].filter.call(el.parentNode.children, function (htmlElement) {
return (htmlElement.previousElementSibling === el) ? nextAll = true : nextAll;
});
return nextAll.map(v => {
if (Array.from(v.querySelectorAll('fnoteBtn').length) > 0) {
$node.nextElementSibling.classList.contains('fnoteBtn') ?
elements = $node.nextElementSibling.children.children :
elements = v.querySelectorAll('.fnoteBtn');
return elements
}
else {
if (el.nodeName === 'BODY') return [];
return getNext(el.parentNode);
}
})
}
var nextInDOM = function(_selector, el) {
var next = getNext(el);
while(next.length !== 0) {
var found = searchFor(_selector, next);
if(found !== null) {
return found;
}
next = getNext(next);
}
return next;
}
var searchFor = function(_selector, el) {
if (!el) {return false};
if(el) {
return $node;
}
else {
var found = null;
el.children.forEach(function() {
if (el)
found = searchFor(_selector, this);
});
return found;
}
return null;
}
var currentClassNot_NextClass = nextInDOM('.fnoteBtn', node);
return currentClassNot_NextClass;
}
var nextFD = findNextFD(editor.selection.getNode());
if(nextFD.length) {
nextFD = nextFD[0];
var foundIdx;
for(foundIdx = 0; foundIdx < totalCount; foundIdx++) {
if(nextFD == totalFootNote[foundIdx]) {
break;
}
}
if (selectIndex < totalCount) {
// modify
html = replaceTmpl(htmlTemplate,{FOOTNOTE_INDEX : $(totalFootNote[selectIndex-1]).html()});
}
else {
// anywhere add
html = replaceTmpl(htmlTemplate,{FOOTNOTE_INDEX : $(totalFootNote[foundIdx]).html()});
editor.selection.collapse(0);
}
} else {
// last add
html = replaceTmpl(htmlTemplate,{FOOTNOTE_INDEX : totalCount + 1});
editor.selection.collapse(0);
}
editor.execCommand('mceInsertContent', false, html);
e.close()
// index realignment
var fnoteBtn = Array.from(editor.getDoc().querySelectorAll('.fnoteBtn'));
fnoteBtn.forEach(function(value,idx){
value.textContent = idx+1;
value.parentNode.setAttribute('id','#wk_ft' + (idx +1))
})
}
});
};
var Dialog = { open: open };
var register$1 = function (editor) {
editor.ui.registry.addToggleButton('footnotes', {
icon : 'fnote',
tooltip : 'Footnote',
onAction: function () {
return editor.execCommand('footnotes');
},
onSetup: function (buttonApi) {
return editor.selection.selectorChangedWithUnbind('span.fnoteWrap', buttonApi.setActive).unbind;
}
});
editor.ui.registry.addMenuItem('footnotes', {
icon: 'fnote',
onAction: function () {
return editor.execCommand('footnotes');
}
});
};
var register = function (editor) {
editor.addCommand('footnotes', function () {
Dialog.open(editor);
});
};
var Commands = { register: register };
var Buttons = { register: register$1 };
function Plugin () {
global.add('footnotes', function (editor) {
editor.ui.registry.addIcon('fnote','<img src="'+ tinyMCE.baseURL + '/plugins/footnotes/img/fn.png' +'">')
Commands.register(editor);
Buttons.register(editor);
});
}
Plugin();
})()
You are passing in findNextFD(node) there is no variable named $node inside that function. Try it without the $ in front of node, and add some logic to make sure node !== null at the beginning of the function for debugging.
If you are trying to use the jQuery function $ make sure it is imported properly and that the $ is defined.
Some examples:
// Select all "p" elements and write "Hello"
$( "p" ).text( "Hello" );
// Change the color of all "p" elements to red
$( "p" ).css( "color", "red" );
// Hide all elements with the ".shy" class
$( ".shy" ).hide();
// Show the element with the "#nav" id
$( "#nav" ).show();

javascript decoding webpackJsonp to readable code

there is a way to change this code into a clear and readable code ?
(window.webpackJsonp=window.webpackJsonp||[]).push([[7],{"2wwy":function(n,t,e){n.exports=e("nhzr")},E8gZ:function(n,t,e){var o=e("jmDH"),i=e("w6GO"),r=e("NsO/"),u=e("NV0k").f;n.exports=function(n){return function(t){for(var e,c=r(t),a=i(c),f=a.length,s=0,l=[];f>s;)e=a[s++],o&&!u.call(c,e)||l.push(n?[e,c[e]]:c[e]);return l}}},f0Zw:function(n,t,e){"use strict";e.r(t);var o=e("q1tI"),i=e.n(o),r=e("/MKj"),u=e("2wwy"),c=e.n(u),a=e("G4qV"),f=Object(a.a)((function(n){return n.g_notifications}),(function(n){return c()(n)})),s=e("F7NL"),l=e("kOwS"),p=e("qNsG"),v=e("CnBM"),w=e.n(v)()({loader:function(){return Promise.all([e.e(0),e.e(6)]).then(e.bind(null,"OyQA"))},loading:function(){return null},modules:["Notification"]}),b=i.a.createElement,d=function(n){var t=n.notifications,e=n.onRemove;return b(i.a.Fragment,null,t.map((function(n){var t=n.id,o=Object(p.a)(n,["id"]);return b(w,Object(l.a)({onRemove:e},o,{key:t,id:t}))})))},O=i.a.createElement,m=Object(r.b)((function(n){return{notifications:f(n)}})),j=function(n){var t=n.dataset.id;Object(s.b)(t)},g=m((function(n){var t=n.notifications;return O(d,{onRemove:j,notifications:t})}));t.default=g},fW1p:function(n,t,e){var o=e("Y7ZC"),i=e("E8gZ")(!1);o(o.S,"Object",{values:function(n){return i(n)}})},nhzr:function(n,t,e){e("fW1p"),n.exports=e("WEpk").Object.values}}]);
This looks like output from Webpack 4.
If the site you're looking at exposes source maps, you will see a section under sources in your browser's dev tools labelled "Webpack", which will contain the source for the scripts bundled using Webpack.
If the site doesn't expose source maps, the first step is to format the code. You can then start manually renaming variables as you figure out what they do. In this case, there must be more scripts on the site because there seem to be references to modules not defined in the file.
Passing this code through Prettier gives:
(window.webpackJsonp = window.webpackJsonp || []).push([
[7],
{
"2wwy": function(n, t, e) {
n.exports = e("nhzr");
},
E8gZ: function(n, t, e) {
var o = e("jmDH"),
i = e("w6GO"),
r = e("NsO/"),
u = e("NV0k").f;
n.exports = function(n) {
return function(t) {
for (var e, c = r(t), a = i(c), f = a.length, s = 0, l = []; f > s; )
(e = a[s++]), (o && !u.call(c, e)) || l.push(n ? [e, c[e]] : c[e]);
return l;
};
};
},
f0Zw: function(n, t, e) {
"use strict";
e.r(t);
var o = e("q1tI"),
i = e.n(o),
r = e("/MKj"),
u = e("2wwy"),
c = e.n(u),
a = e("G4qV"),
f = Object(a.a)(
function(n) {
return n.g_notifications;
},
function(n) {
return c()(n);
}
),
s = e("F7NL"),
l = e("kOwS"),
p = e("qNsG"),
v = e("CnBM"),
w = e.n(v)()({
loader: function() {
return Promise.all([e.e(0), e.e(6)]).then(e.bind(null, "OyQA"));
},
loading: function() {
return null;
},
modules: ["Notification"]
}),
b = i.a.createElement,
d = function(n) {
var t = n.notifications,
e = n.onRemove;
return b(
i.a.Fragment,
null,
t.map(function(n) {
var t = n.id,
o = Object(p.a)(n, ["id"]);
return b(w, Object(l.a)({ onRemove: e }, o, { key: t, id: t }));
})
);
},
O = i.a.createElement,
m = Object(r.b)(function(n) {
return { notifications: f(n) };
}),
j = function(n) {
var t = n.dataset.id;
Object(s.b)(t);
},
g = m(function(n) {
var t = n.notifications;
return O(d, { onRemove: j, notifications: t });
});
t.default = g;
},
fW1p: function(n, t, e) {
var o = e("Y7ZC"),
i = e("E8gZ")(!1);
o(o.S, "Object", {
values: function(n) {
return i(n);
}
});
},
nhzr: function(n, t, e) {
e("fW1p"), (n.exports = e("WEpk").Object.values);
}
}
]);
finding yourself in this is almost impossible, I mean that the result of decoding was on this principle:
var func = {
init: function() {
console.log('test');
this.set();
},
set: function(){
$('.body .test').innerHTML = 'test';
}
}
func.init();
easy and legible

How to cancel or abort image download in Three.js TextureLoader

I have an image gallery project where the user can move around the 3D space and the images start downloading as he gets near them. Since he can be moving around all the time, getting away from those images which already started downloading, I'd need to cancel these downloads (they no longer need to download as they are not to be seen anymore).
I download them with Three.TextureLoader and was hoping to find some method to stop/cancel/abort the download, but looks like it doesn't exist. I found these threads related to the topic:
https://github.com/mrdoob/three.js/pull/6649
https://github.com/mrdoob/three.js/issues/6641
But I didn't find where to add the suggested "return request" in the Three code in my version of Three. I think this is the section where it should be found, but I don't quite get exactly where should I add such return statement:
Object.assign(Ja.prototype, {
load: function(a, b, c, d) {
void 0 === a && (a = "");
void 0 !== this.path && (a = this.path + a);
a = this.manager.resolveURL(a);
var e = this
, f = jd.get(a);
if (void 0 !== f)
return e.manager.itemStart(a),
setTimeout(function() {
b && b(f);
e.manager.itemEnd(a)
}, 0),
f;
if (void 0 !== Ta[a])
Ta[a].push({
onLoad: b,
onProgress: c,
onError: d
});
else {
var g = a.match(/^data:(.*?)(;base64)?,(.*)$/);
if (g) {
c = g[1];
var h = !!g[2]
, g = g[3]
, g = window.decodeURIComponent(g);
h && (g = window.atob(g));
try {
var k = (this.responseType || "").toLowerCase();
switch (k) {
case "arraybuffer":
case "blob":
for (var l = new Uint8Array(g.length), h = 0; h < g.length; h++)
l[h] = g.charCodeAt(h);
var m = "blob" === k ? new Blob([l.buffer],{
type: c
}) : l.buffer;
break;
case "document":
m = (new DOMParser).parseFromString(g, c);
break;
case "json":
m = JSON.parse(g);
break;
default:
m = g
}
window.setTimeout(function() {
b && b(m);
e.manager.itemEnd(a)
}, 0)
} catch (t) {
window.setTimeout(function() {
d && d(t);
e.manager.itemEnd(a);
e.manager.itemError(a)
}, 0)
}
} else {
Ta[a] = [];
Ta[a].push({
onLoad: b,
onProgress: c,
onError: d
});
var n = new XMLHttpRequest;
n.open("GET", a, !0);
n.addEventListener("load", function(b) {
var c = b.target.response;
jd.add(a, c);
var d = Ta[a];
delete Ta[a];
if (200 === this.status) {
for (var f = 0, g = d.length; f < g; f++) {
var h = d[f];
if (h.onLoad)
h.onLoad(c)
}
e.manager.itemEnd(a)
} else if (0 === this.status) {
console.warn("THREE.FileLoader: HTTP Status 0 received.");
f = 0;
for (g = d.length; f < g; f++)
if (h = d[f],
h.onLoad)
h.onLoad(c);
e.manager.itemEnd(a)
} else {
f = 0;
for (g = d.length; f < g; f++)
if (h = d[f],
h.onError)
h.onError(b);
e.manager.itemEnd(a);
e.manager.itemError(a)
}
}, !1);
n.addEventListener("progress", function(b) {
for (var c = Ta[a], d = 0, e = c.length; d < e; d++) {
var f = c[d];
if (f.onProgress)
f.onProgress(b)
}
}, !1);
n.addEventListener("error", function(b) {
var c = Ta[a];
delete Ta[a];
for (var d = 0, f = c.length; d < f; d++) {
var g = c[d];
if (g.onError)
g.onError(b)
}
e.manager.itemEnd(a);
e.manager.itemError(a)
}, !1);
void 0 !== this.responseType && (n.responseType = this.responseType);
void 0 !== this.withCredentials && (n.withCredentials = this.withCredentials);
n.overrideMimeType && n.overrideMimeType(void 0 !== this.mimeType ? this.mimeType : "text/plain");
for (h in this.requestHeader)
n.setRequestHeader(h, this.requestHeader[h]);
n.send(null)
}
e.manager.itemStart(a);
return n
}
return n
},
setPath: function(a) {
this.path = a;
return this
},
setResponseType: function(a) {
this.responseType = a;
return this
},
setWithCredentials: function(a) {
this.withCredentials = a;
return this
},
setMimeType: function(a) {
this.mimeType = a;
return this
},
setRequestHeader: function(a) {
this.requestHeader = a;
return this
}
});
Can anybody point me in the right direction? Or perhaps another solution such as loading the image in another way (jQuery, perhaps?) and then pass the texture to my material somehow? This is my current callback for TextureLaoder:
obj.handleTexture = function (size, texture) {
obj.mesh.material.map = texture;
obj.mesh.material.needsUpdate = true;
};
Many thanks
If you need to abort the image loader, check out the source code: https://github.com/mrdoob/three.js/blob/dev/src/loaders/ImageLoader.js
The new ImageLoader().load(...) function returns an XHTML image element (<img />). But this element is not accessible externally. Therefore you can easily write your own function to load textures, and override the existing one.
The function below is mostly copied from: https://github.com/mrdoob/three.js/blob/dev/src/loaders/TextureLoader.js Make sure that in the latest version of ThreeJS, you check if the source code below is the same (except for the additional abort function).
THREE.TextureLoader.prototype.load = function(url, onLoad, onProgress, onError)
{
var texture = new THREE.Texture();
var loader = new THREE.ImageLoader(this.manager);
loader.setCrossOrigin(this.crossOrigin);
loader.setPath(this.path);
var image = loader.load(url, function(image)
{
texture.image = image;
// JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
var isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
texture.format = isJPEG ? THREE.RGBFormat : THREE.RGBAFormat;
texture.needsUpdate = true;
if(onLoad !== undefined)
{
onLoad( texture );
}
}, onProgress, onError);
// add this function to the texture
texture.abort = function()
{
if(image && typeof image.hasAttribute === 'function')
{
image.src = '';
}
};
return texture;
};
Usage:
var texLoader = new THREE.TextureLoader();
var texRequest = texLoader.load('https://example.com/image.jpg', function(texture)
{
clearTimeout(texTimer);
// use loaded texture
...
});
// For example, abort after 200ms if still loading:
var texTimer = setTimeout(function()
{
texRequest.abort();
}, 200);

What is the meaning of e.fn in this code

I am looking at this javascript code from the quojs library:
(function() {
var e;
e = function() {
var e, t, n;
t = [];
e = function(t, r) {
var i;
if (!t) {
return n()
} else if (e.toType(t) === "function") {
return e(document).ready(t)
} else {
i = e.getDOMObject(t, r);
return n(i, t)
}
};
n = function(e, r) {
e = e || t;
e.__proto__ = n.prototype;
e.selector = r || "";
return e
};
e.extend = function(e) {
Array.prototype.slice.call(arguments, 1).forEach(function(t) {
var n, r;
r = [];
for (n in t) {
r.push(e[n] = t[n])
}
return r
});
return e
};
n.prototype = e.fn = {};
return e
}();
which comes before this:
(function () {
(function (e) {
var t, n, r, i, u, a;
r = "parentNode";
t = /^\.([\w-]+)$/;
n = /^#[\w\d-]+$/;
i = /^[\w-]+$/;
e.query = function (e, r) {
var u;
r = r.trim();
if (t.test(r)) {
u = e.getElementsByClassName(r.replace(".", ""))
} else if (i.test(r)) {
u = e.getElementsByTagName(r)
} else if (n.test(r) && e === document) {
u = e.getElementById(r.replace("#", ""));
if (!u) {
u = []
}
} else {
u = e.querySelectorAll(r)
}
if (u.nodeType) {
return [u]
} else {
return Array.prototype.slice.call(u)
}
};
e.fn.find = function (t) {
I am trying to understand the meaning of e.fn.
I see that fn is not a reserved word. I think that e is just the name given to the event object passed as a parameter. So what is the meaning of e.fn? Is the code assuming that whatever is passed as e has a property called fn? Or is fn some kind of abbreviation that references the function?
Whatever is passed as e should have a property called fn. I would search the rest of the code for "fn" and see what you come up with.

Add space between numbers/digits and letters/characters

I have a code like this
(function($, window, document, undefined) {
$.fn.quicksearch = function (target, opt) {
var timeout, cache, rowcache, jq_results, val = '', e = this, options = $.extend({
delay: 100,
selector: null,
stripeRows: null,
loader: null,
noResults: '',
bind: 'keyup',
onBefore: function () {
return;
},
onAfter: function () {
return;
},
show: function () {
this.style.display = "";
},
hide: function () {
this.style.display = "none";
},
prepareQuery: function (val) {
return val.toLowerCase().split(' ');
},
testQuery: function (query, txt, _row) {
for (var i = 0; i < query.length; i += 1) {
if (txt.indexOf(query[i]) === -1) {
return false;
}
}
return true;
}
}, opt);
this.go = function () {
var i = 0,
noresults = true,
query = options.prepareQuery(val),
val_empty = (val.replace(' ', '').length === 0);
for (var i = 0, len = rowcache.length; i < len; i++) {
if (val_empty || options.testQuery(query, cache[i], rowcache[i])) {
options.show.apply(rowcache[i]);
noresults = false;
} else {
options.hide.apply(rowcache[i]);
}
}
if (noresults) {
this.results(false);
} else {
this.results(true);
this.stripe();
}
this.loader(false);
options.onAfter();
return this;
};
this.stripe = function () {
if (typeof options.stripeRows === "object" && options.stripeRows !== null)
{
var joined = options.stripeRows.join(' ');
var stripeRows_length = options.stripeRows.length;
jq_results.not(':hidden').each(function (i) {
$(this).removeClass(joined).addClass(options.stripeRows[i % stripeRows_length]);
});
}
return this;
};
this.strip_html = function (input) {
var output = input.replace(new RegExp('<[^<]+\>', 'g'), "");
output = $.trim(output.toLowerCase());
return output;
};
this.results = function (bool) {
if (typeof options.noResults === "string" && options.noResults !== "") {
if (bool) {
$(options.noResults).hide();
} else {
$(options.noResults).show();
}
}
return this;
};
this.loader = function (bool) {
if (typeof options.loader === "string" && options.loader !== "") {
(bool) ? $(options.loader).show() : $(options.loader).hide();
}
return this;
};
this.cache = function () {
jq_results = $(target);
if (typeof options.noResults === "string" && options.noResults !== "") {
jq_results = jq_results.not(options.noResults);
}
var t = (typeof options.selector === "string") ? jq_results.find(options.selector) : $(target).not(options.noResults);
cache = t.map(function () {
return e.strip_html(this.innerHTML);
});
rowcache = jq_results.map(function () {
return this;
});
return this.go();
};
this.trigger = function () {
this.loader(true);
options.onBefore();
window.clearTimeout(timeout);
timeout = window.setTimeout(function () {
e.go();
}, options.delay);
return this;
};
this.cache();
this.results(true);
this.stripe();
this.loader(false);
return this.each(function () {
$(this).bind(options.bind, function () {
val = $(this).val();
e.trigger();
});
});
};
}(jQuery, this, document));
I try to figure out where and how I can make a split/add space between numbers and letters. Cause some people type for example "ip1500" and the script cant match the input with an element that is like "ip 1500". My problem ist that Im a js beginner.
I was trying and trying but i cant get it work. I also tried this
I found this spot and I think it can be done here where the everything get splitted by an " " (space):
prepareQuery: function (val) {
return val.toLowerCase().split(' ');
},
Would be very nice if somebody can help me.
If you want "123abc345def" to "123 abc 345 def". The replace function may help. The code is like this.
var str = "123abc345def";
str = str.replace(/(\d+)/g, function (_, num){
console.log(num);
return ' ' + num + ' ';
});
str = str.trim();
The code you linked didn't work mainly because it's using a different programming language to javascript. In theory, it should work, but javascript does not support regular expression lookbehinds (at this present time)..
Instead, I have re-wrote that fragment of code:
prepareQuery: function (val) {
function isNotLetter(a){
return (/[0-9-_ ]/.test(a));
}
var val=val.toLowerCase().split("");
var tempArray=val.join("").split("");
var currentIndex=1;
for (var i=0;i<val.length-1;i++){
if (isNotLetter(val[i]) !== isNotLetter(val[i+1])){
tempArray.splice(i+currentIndex, 0, " ");
currentIndex++;
}
}
return tempArray.join("");
}
Since you're new to javascript, I'm going to explain what it does.
It declares a function in prepareQuery to check whether or not a string contains a letter [this can be moved somewhere else]
It then splits val into an array and copies the content of val into tempArray
An index is declared (explained later)
A loop is made, which goes through every single character in val
The if statement detects whether or not the current character (val[i] as set by the loop) is the same as the character next to it (val[i+1]).
IF either one are different to the other (ie the current character is a letter while the next isn't) then a space is added to the tempArray at that "index"
The index is incremented and used as an offset in #6
The loop finishes, joins the "array" into a string and outputs the result.
DEMO:
http://jsbin.com/ebitus/1/edit
(JSFiddle was down....)
EDIT:
Sorry, but I completely misinterpreted your question... You failed to mention that you were using "quicksearch" and jQuery. In that case I'm assuming that you have a list of elements that have names and you want to search through them with the plugin...
A much easier way to match the user's query (if there is no space) is to strip the space from the search table along with the query itself - though original reverse method will work (just not as efficiently) [aka: expanding the user's query]
In this case, stripping the space from both the search table and user input would be a better method
prepareQuery: function (val) {
return val.toLowerCase().replace(/ /ig,'').split(" ");
},
testQuery: function (query, txt, _row) {
txt=txt.toLowerCase().replace(/ /ig,'');
for (var i = 0; i < query.length; i += 1) {
if (txt.indexOf(query[i]) === -1) {
return false;
}
}
return true;
}
DEMO:
http://jsfiddle.net/q9k9Y/3/
Edit 2:
It seems like your real intent is to create a fully functioning search feature on your website, not to just add spaces between letters and numbers. With this, I suggest using Quicksilver. I would love to work out an algorithm to extend quickSearcher but at the current time I cannot (timezones). Instead, I suggest using Quicksilver
http://jsbin.com/oruhet/12/

Categories

Resources