Do you suggest a script that shows a random comment of my blog, created with bloggers? - comments

good evening.
Do you suggest a script that shows a random comment of my blog, created with bloggers?
thank you

That should be possible to generate using the global comment feed provided by Blogger -
http://blogname.blogspot.com/feeds/comments/default
A working snippet for the same would look like -
<div id='stylify_random_comments'></div>
<script style='text/javascript'>
//<![CDATA[
var commentTitleOriginal, myLink, myDiv, myImage;
var main;
function getcomment(json) {
var s;
var entry = json.feed.entry[0];
var commentTitle = entry.title.$t;
commentTitleOriginal = commentTitle;
if (isNaN(titleLength) || titleLength == 0) {
commentTitle = '';
} else if (commentTitle.length > titleLength) commentTitle = commentTitle.substring(0, titleLength) + "...";
var commentUrl;
for (var k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'replies' && entry.link[k].type == 'text/html') {
var commentText = entry.link[k].title;
var commentUrl = entry.link[k].href;
}
if (entry.link[k].rel == 'alternate') {
commentUrl = entry.link[k].href;
break;
}
}
if (showThumbs == true) {
var thumbUrl = "";
try {
thumbUrl = entry.author["0"].gd$image.src;
if (imgDim == "80" || imgDim == "85" || imgDim == "90" || imgDim == "95" || imgDim == "100") thumbUrl = thumbUrl.replace("/s72-c/", "/s104-c/");
} catch (error) {
if ("content" in entry) s = entry.content.$t;
else s = "";
if (thumbUrl == "" && mediaThumbsOnly == false) {
a = s.indexOf("<img");
b = s.indexOf("src=\"", a);
c = s.indexOf("\"", b + 5);
d = s.substr(b + 5, c - b - 5);
if ((a != -1) && (b != -1) && (c != -1) && (d != "")) thumbUrl = d;
}
}
if (thumbUrl == "" && showNoImage == true) thumbUrl = 'http://1.bp.blogspot.com/_u4gySN2ZgqE/SosvnavWq0I/AAAAAAAAArk/yL95WlyTqr0/s400/noimage.png';
} //end ifcommenthumbs
if (showcommentDate == true) {
var commentdate = entry.published.$t;
var cdyear = commentdate.substring(0, 4);
var cdmonth = commentdate.substring(5, 7);
var cdday = commentdate.substring(8, 10);
var monthnames = new Array();
monthnames[1] = "Jan";
monthnames[2] = "Feb";
monthnames[3] = "Mar";
monthnames[4] = "Apr";
monthnames[5] = "May";
monthnames[6] = "Jun";
monthnames[7] = "Jul";
monthnames[8] = "Aug";
monthnames[9] = "Sep";
monthnames[10] = "Oct";
monthnames[11] = "Nov";
monthnames[12] = "Dec";
} //end if date
code = "";
main = document.getElementById('stylify_random_comments');
myDiv = document.createElement('div');
myDiv.setAttribute("class", "stylify_item_title");
myDiv.style.clear = "both";
myDiv.style.marginTop = "4px";
myLink = createLink(commentUrl, "_top", commentTitleOriginal)
if (commentTitle != '') myDiv.appendChild(myLink);
main.appendChild(myDiv);
if (commentTitle != '') myLink.innerHTML = commentTitle;
if (showThumbs == true && thumbUrl != "") {
myImage = document.createElement('img');
myImage.style.border = "0px solid transparent";
myImage.style.margin = "5px";
myImage.style.boxShadow = "0 0 0px rgba(0, 0, 0, 0.3)";
myImage.setAttribute("src", thumbUrl);
myImage.style.cssFloat = imgFloat;
myImage.style.styleFloat = imgFloat;
//myImage.setAttribute("alt", commentTitleOriginal);
myImage.setAttribute("width", imgDim);
//myImage.setAttribute("align", imgFloat);
myImage.setAttribute("height", imgDim);
myLink = document.createElement('a');
myLink.setAttribute("href", commentUrl + "?utm_source=blog&utm_medium=gadget&utm_campaign=stylify_random_comments");
myLink.setAttribute("target", "_top");
myLink.setAttribute("title", commentTitleOriginal);
myLink.appendChild(myImage);
myDiv = document.createElement('div');
myDiv.setAttribute("class", "stylify_item_thumb");
myDiv.appendChild(myLink);
main.appendChild(myDiv);
}
try {
if ("content" in entry) {
var commentContent = entry.content.$t;
} else if ("summary" in entry) {
var commentContent = entry.summary.$t;
} else var commentContent = "";
var re = /<\S[^>]*>/g;
commentContent = commentContent.replace(re, "");
if (showSummary == true) {
myDiv = createDiv("stylify_item_summary");
if (commentContent.length < summaryLength) {
myDiv.innerHTML = commentContent;
} else {
commentContent = commentContent.substring(0, summaryLength);
var quoteEnd = commentContent.lastIndexOf(" ");
commentContent = commentContent.substring(0, quoteEnd);
myDiv.innerHTML = commentContent + '...';
}
main.appendChild(myDiv);
}
} //end try
catch (error) {}
myDiv = createDiv("stylify_item_meta");
myDiv.style.clear = "both";
myDiv.style.marginBottom = "4px";
var flag = 0;
if (showcommentDate == true) {
myDiv.appendChild(document.createTextNode(monthnames[parseInt(cdmonth, 10)] + '-' + cdday + '-' + cdyear));
flag = 1;
}
if (showCommentCount == true) {
if (flag == 1) {
myDiv.appendChild(document.createTextNode(" | "));
}
if (commentText == '1 Comments') commentText = '1 Comment';
if (commentText == '0 Comments') commentText = 'No Comments';
var myLink = createLink(commentUrl, "_top", commentText + " on " + commentTitleOriginal)
myDiv.appendChild(myLink);
myLink.innerHTML = commentText;
flag = 1;;
}
if (showReadMore == true) {
if (flag == 1) {
myDiv.appendChild(document.createTextNode(" | "));
}
var myLink = createLink(commentUrl, "_top", commentTitleOriginal)
myDiv.appendChild(myLink);
myLink.innerHTML = readMore + " ยป";
flag = 1;;
}
if (flag == 1 || showSummary || commentTitle != "") main.appendChild(myDiv);
}
function getRandom(json) {
var feedUrl = '/feeds/comments/default';
if (mediaThumbsOnly || !showThumbs) feedUrl = feedUrl.replace("comments/default", "comments/summary");
totalcomments = parseInt(json.feed.openSearch$totalResults.$t);
var rand = [];
if (numberOfcomments > totalcomments) numberOfcomments = totalcomments;
if (numberOfcomments > 15) numberOfcomments = 15;
while (rand.length < numberOfcomments) {
var randomNumber = Math.ceil(Math.random() * totalcomments);
var found = false;
for (var i = 0; i < rand.length; i++) {
if (rand[i] == randomNumber) {
found = true;
break;
}
}
if (!found) rand[rand.length] = randomNumber;
}
var head = document.getElementsByTagName("head")[0] || document.documentElement;
for (var i = 0; i < rand.length; i++) {
script = document.createElement("script");
script.src = feedUrl + "?start-index=" + rand[i] + "&max-results=1&alt=json-in-script&callback=getcomment";
script.charSet = "utf-8";
head.appendChild(script);
}
}
function createDiv(className) {
var myDiv = document.createElement('div');
myDiv.setAttribute("class", className);
return myDiv;
}
function createLink(href, target, title) {
var myLink = document.createElement('a');
if (href.indexOf("?utm_source=") == -1) href = href + "?utm_source=blog&utm_medium=gadget&utm_campaign=stylify_random_comments";
myLink.setAttribute("href", href);
myLink.setAttribute("target", target);
myLink.setAttribute("title", title);
return myLink;
}
//]]>
</script>
<script style='text/javascript'>
var numberOfcomments = 5;
var showcommentDate = false;
var showSummary = true;
var summaryLength = 200;
var titleLength = 100;
var showCommentCount = false;
var showThumbs = true;
var showNoImage = false;
var imgDim = 50;
var imgFloat = 'left';
var myMargin = 0;
var mediaThumbsOnly = true;
var showReadMore = false;
var readMore = 'More';
</script>
<script src='/feeds/comments/default?max-results=1&alt=json-in-script&callback=getRandom'></script>

Related

Multiple People Picker Columns (fields) on one form

SharePoint Online: I have multiple people picker columns and enter in a number of places people. I get the people OK but it won't update. It says it the entry is undefined. I thought maybe separating each out would work but obviously not. I hope I get some help on this one. What I want to do is to allow users to enter names into where the div entries are and as a people picker. I accomplished that but when you submit the form it says that any entry other than the first is undefined.
<script type = "text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js" > < /script>
<script type="text/javascript" src="/_layouts/15/sp.core.js"></script>
<script type="text/javascript" src="/_layouts/15/clienttemplates.js"></script>
<script type="text/javascript" src="/_layouts/15/clientforms.js"></script>
<script type="text/javascript" src="/_layouts/15/clientpeoplepicker.js"></script>
<script type="text/javascript" src="/_layouts/15/autofill.js"></script>
<script type="text/javascript" src="/_layouts/15/1033/sts_strings.js"></script>
<script type="text/javascript">
var prim5 = 0;var sec4 = 0;var auth5 = 0;
var EorB25 = "";var BorE25 = "";var BorE35 = "";var siteUrl = "https://sp-cloud.kp.org/sites/MedicaidRepository";var cat25 = "";var regimpact = "";var regimpact1 = "";var prim25="";var sec25="";
var auth25="";var s1 = "";var soxD1 = "";var k1 = 'No';var com2 = "";var sDate1 = "";var sSever = "";var kDate1 = "";var finalusersP = [];var finalusers22 = [];var finalusersK = [];var user22 = [];var userK = [];var userP = [];var users22 = [];var usersK = [];var usersP = [];var userPemail = "";var userKemail = "";var user22email = "";
var tDay = new Date();
var dd = tDay.getDate();
var mm = tDay.getMonth()+1;
var yy = tDay.getFullYear();
var sDate = mm+ '/' +dd+ '/' +yy;
$(document).ready(function() {
prim5 = 1;
initializePeoplePickerP('peoplePickerDivP');
registerPPOnChangeEventP($('#peoplePickerDivP'));
});
$(document).ready(function() {
sec5 = 1;
initializePeoplePickerS('peoplePickerDivS');
registerPPOnChangeEventS($('#peoplePickerDivS'));
});
$(document).ready(function() {
auth5 = 1;
initializePeoplePickerK('peoplePickerDivK');
registerPPOnChangeEventK($('#peoplePickerDivK'));
});
function initializePeoplePickerP(peoplePickerElementIdP, UsersP) {
if (typeof(UsersP) == 'undefined') UsersP = null;
console.log('UsersP: ' +UsersP);
// Create a schema to store picker properties, and set the properties.
var schema = {};
schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
schema['SearchPrincipalSource'] = 15;
schema['ResolvePrincipalSource'] = 15;
schema['AllowMultipleValues'] = true;
schema['MaximumEntitySuggestions'] = 50;
schema['Width'] = '280px';
this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementIdP, null, schema);
}
function initializePeoplePickerS(peoplePickerElementIdS, Users22) {
if (typeof(Users22) == 'undefined') Users22 = null;
console.log('Users22: ' +Users22);
// Create a schema to store picker properties, and set the properties.
var schema = {};
schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
schema['SearchPrincipalSource'] = 15;
schema['ResolvePrincipalSource'] = 15;
schema['AllowMultipleValues'] = true;
schema['MaximumEntitySuggestions'] = 50;
schema['Width'] = '280px';
this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementIdS, null, schema);
}
function initializePeoplePickerK(peoplePickerElementIdK, UsersK) {
if (typeof(UsersK) == 'undefined') UsersK = null;
// Create a schema to store picker properties, and set the properties.
var schema = {};
schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
schema['SearchPrincipalSource'] = 15;
schema['ResolvePrincipalSource'] = 15;
schema['AllowMultipleValues'] = true;
schema['MaximumEntitySuggestions'] = 50;
schema['Width'] = '280px';
this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementIdK, null, schema);
}
function registerPPOnChangeEventP(ppElement) {
var ppId = ppElement.attr('id') + "_TopSpan";
console.log('ppID: ' +ppId);
//var addOnChanged = function(ctx) {
if (SPClientPeoplePicker &&
SPClientPeoplePicker.SPClientPeoplePickerDict &&
SPClientPeoplePicker.SPClientPeoplePickerDict[ppId]) {
console.log("In registerPPOnChangeEvent if");
var picker = SPClientPeoplePicker.SPClientPeoplePickerDict[ppId];
picker.oldChanged = picker.OnControlResolvedUserChanged;
//var ppidTest = picker.toString();
console.log("picker: " +picker);
//OnControlResolvedUserChanged
picker.OnControlResolvedUserChanged = function () {
if (picker.TotalUserCount == 0) {
$('#resolvedUsers').html("");
$('#userKeys').html("");
$('#userProfileProperties').html("");
$('#userID').html("");
} else {
setTimeout(function () {
getUserInfoP();
},
100);
}
picker.oldChanged();
}
} else {
// setTimeout(function () { addOnChanged(ctx); }, 100);
console.log("In registerPPOnChangeEvent else");
}
//}
}
function registerPPOnChangeEventS(ppElement) {
var ppId = ppElement.attr('id') + "_TopSpan";
console.log('ppID: ' +ppId);
//var addOnChanged = function(ctx) {
if (SPClientPeoplePicker &&
SPClientPeoplePicker.SPClientPeoplePickerDict &&
SPClientPeoplePicker.SPClientPeoplePickerDict[ppId]) {
console.log("In registerPPOnChangeEvent if");
var picker = SPClientPeoplePicker.SPClientPeoplePickerDict[ppId];
picker.oldChanged = picker.OnControlResolvedUserChanged;
var ppidTest = picker.toString();
console.log("picker: " +ppidTest);
//OnControlResolvedUserChanged
picker.OnControlResolvedUserChanged = function () {
if (picker.TotalUserCount == 0) {
$('#resolvedUsers22').html("");
$('#user22Keys').html("");
$('#user22ProfileProperties').html("");
$('#user22ID').html("");
} else {
setTimeout(function () {
getUserInfoS();
},
100);
}
picker.oldChanged();
}
} else {
//setTimeout(function () { addOnChanged(ctx); }, 100);
console.log("In registerPPOnChangeEvent else");
}
//}
}
function registerPPOnChangeEventK(ppElement) {
var ppId = ppElement.attr('id') + "_TopSpan";
console.log('ppID: ' +ppId);
//var addOnChanged = function(ctx) {
if (SPClientPeoplePicker &&
SPClientPeoplePicker.SPClientPeoplePickerDict &&
SPClientPeoplePicker.SPClientPeoplePickerDict[ppId]) {
console.log("In registerPPOnChangeEvent if");
var picker = SPClientPeoplePicker.SPClientPeoplePickerDict[ppId];
picker.oldChanged = picker.OnControlResolvedUserChanged;
var ppidTest = picker.toString();
console.log("picker: " +ppidTest);
//OnControlResolvedUserChanged
picker.OnControlResolvedUserChanged = function () {
if (picker.TotalUserCount == 0) {
$('#resolvedUsers').html("");
$('#userKeys').html("");
$('#userProfileProperties').html("");
$('#userID').html("");
} else {
setTimeout(function () {
getUserInfoK();
},
100);
}
picker.oldChanged();
}
} else {
// setTimeout(function () { addOnChanged(ctx); }, 100);
console.log("In registerPPOnChangeEvent else");
}
//}
}
// Query the picker for user information.
var userPropertyP = "";
var userPropertyS = "";
var userPropertyK ="";
var userPemail = "";
var i = 0;
var j = 0;
var m = 0;
var keysP = "";
var keysS = "";
var keysK = "";
function getUserInfoP() {
// Get the people picker object from the page.
var peoplePickerP = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDivP_TopSpan;
// Get information about all users.
var usersP = peoplePickerP.GetAllUserInfo();
//var keysP = peoplePickerP.GetAllUserKeys();
//finalusersP = new Array();
console.log('Users: ' +usersP);
var ownerP = usersP[0];
for(i = 0; i < usersP.length; i++){
userPemail = usersP[i];
}
console.log('Owner: ' +ownerP);
$("#siteOwenerEmail").val(ownerP.AutoFillSubDisplayText);
$("#siteOwenerClaim").val(ownerP.Key);
$("#siteOwnerName").val(ownerP.DisplayText);
$("#siteOwnerLogin").val(ownerP.Description);console.log('Get People Picker NameP: ' +ownerP.DisplayText);
var userInfo = '';
if(prim5 > 0){
for (var i = 0; i < usersP.length; i++) {
userP = usersP[i];
if(userP !== null){
//userPemail = userP.EntityData.Email;
userPemail = ownerP.DisplayText;
}
console.log("userPemail: " +userPemail);
return userPemail;
console.log('i= ' +i+ 'User= ' +userP);
for (userPropertyP in userP) {
prim25 += userPropertyP + ': ' + userP[userPropertyP] + '<br>';
}
}
$('#resolvedUsers').html(prim25);
// Get user keys.
keysP = peoplePickerP.GetAllUserKeys();
$('#userKeys').html(keysP);
// Get the first user's ID by using the login name.
getUserIdP(usersP[0].Key);
console.log('Initial: ' +prim25);
}
}
function getUserInfoS() {
// Get the people picker object from the page.
var peoplePickerS = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDivS_TopSpan;
// Get information about all users.
users22 = peoplePickerS.GetAllUserInfo();
//var keysP = peoplePickerP.GetAllUserKeys();
//finalusersS = new Array();
console.log('Users: ' + users22);
var ownerS = users22[0];
/*for(i = 0; i < usersS.length; j++){
userSemail = usersS[i];
}*/
console.log('Owner: ' +ownerS);
$("#siteOwenerEmail").val(ownerS.AutoFillSubDisplayText);
$("#siteOwenerClaim").val(ownerS.Key);
$("#siteOwnerName").val(ownerS.DisplayText);
$("#siteOwnerLogin").val(ownerS.Description);console.log('Get People Picker NameS: ' +ownerS.DisplayText);
var userInfo = '';
if(sec4 > 0){
for (j = 0; j < users22.length; j++) {
user22 = users22[j];
if(user22 !== null){
//userPemail = userP.EntityData.Email;
user22email = ownerS.DisplayText;
}
for (userPropertyS in user22) {
sec25 += userPropertyS + ': ' + user22[userPropertyS] + '<br>';
}
}
$('#resolvedUsers').html(sec25);
// Get user keys.
keysS = peoplePickerS.GetAllUserKeys();
$('#user22Keys').html(keysS);
// Get the first user's ID by using the login name.
getUserIdS( users22[0].Key);
}
}
function getUserInfoK() {
// Get the people picker object from the page.
var peoplePickerK = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDivK_TopSpan;
// Get information about all users.
usersK = peoplePickerK.GetAllUserInfo();
//var keysP = peoplePickerP.GetAllUserKeys();
//finalusersK = new Array();
console.log('Users: ' +usersK);
var ownerK = usersK[0];
/*for(i = 0; i < usersK.length; i++){
userKemail = usersK[i];
}*/
console.log('Owner: ' +ownerK);
$("#siteOwenerEmail").val(ownerK.AutoFillSubDisplayText);
$("#siteOwenerClaim").val(ownerK.Key);
$("#siteOwnerName").val(ownerK.DisplayText);
$("#siteOwnerLogin").val(ownerK.Description);console.log('Get People Picker NameK: ' +ownerK.DisplayText);
var userInfo = '';
if(auth5 > 0){
for (m = 0; m < usersK.length; m++) {
userK = usersK[m];
if(userK !== null){
//userPemail = userP.EntityData.Email;
userKemail = ownerK.DisplayText;
}
for (userPropertyK in userK) {
auth25 += userPropertyK + ': ' + userK[userPropertyK] + '<br>';
}
}
$('#resolvedUsers').html(auth25);
// Get user keys.
keysK = peoplePickerK.GetAllUserKeys();
$('#userKeys').html(keysK);
// Get the first user's ID by using the login name.
getUserIdK(usersK[0].Key);
}
}
// Get the user ID.
function getUserIdP(loginName) {
console.log('Get User ID-P');
var context = new SP.ClientContext.get_current();
this.userP = context.get_web().ensureUser(loginName);
context.load(this.userP);
context.executeQueryAsync(
Function.createDelegate(null, ensureUserSuccessP),
Function.createDelegate(null, onFail)
);
}
function ensureUserSuccessP() {
$('#userId').html(this.userP.get_id());
$("#siteOwenerId").val(this.userP.get_id());
userP = $("#siteOwenerId").val(this.userP.get_id());
}
function getUserIdS(loginName) {
console.log("Get User ID-S");
var context = new SP.ClientContext.get_current();
this.user22 = context.get_web().ensureUser(loginName);
context.load(this.user22);
context.executeQueryAsync(
Function.createDelegate(null, ensureUserSuccessS),
Function.createDelegate(null, onFail)
);
}
function ensureUserSuccessS() {
$('#userId').html(this.user22.get_id());
$("#siteOwenerId").val(this.user22.get_id());
userS = $("#siteOwenerId").val(this.user22.get_id());
}
function getUserIdK(loginName) {
console.log('Get User ID-K');
var context = new SP.ClientContext.get_current();
this.userK = context.get_web().ensureUser(loginName);
context.load(this.userK);
context.executeQueryAsync(
Function.createDelegate(null, ensureUserSuccessK),
Function.createDelegate(null, onFail)
);
}
function ensureUserSuccessK() {
$('#userId').html(this.userK.get_id());
$("#siteOwenerId").val(this.userK.get_id());
userK = $("#siteOwenerId").val(this.userK.get_id());
}
function onFail(sender, args) {
alert('Query failed. Error: ' + args.get_message());
}
function addNewIntake(){
SP.SOD.executeFunc('sp.js', 'SP.ClientContext',updateListItem1);
}
function updateListItem1() {
finalusersP.push(SP.FieldUserValue.fromUser(userP.Key));
finalusers22.push(SP.FieldUserValue.fromUser(user22.Key));
finalusersK.push(SP.FieldUserValue.fromUser(userK.Key));
var clientContext = new SP.ClientContext(siteUrl);
var oList =
clientContext.get_web().get_lists().getByTitle('Issue_Tracker_List');
this.oListItem = oList.addItem();
//console.log('primary person info: ' + finalusersP);
oListItem.set_item('MainContact2',finalusersP);
if(finalusers22 !== ""){
//console.log('secondary person info: ' +finalusers22);
oListItem.set_item('AdditionalContact_x0028_s_x0029_',finalusersS);
}
if(finalusersK !== ""){
oListItem.set_item('ITSupportOwner',finalusersK);
}
oListItem.update();
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded() {
document.getElementById('main12').style.display="none";
document.getElementById('main22').style.display="block";
setTimeout(CloseDlg, 2000);
}
function CloseDlg() {
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.Cancel);
}
function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>

Why don't checkboxes in my Handsontable Custom Editor toggle?

I'm using the latest Handsontable version 9.0.0 without any framework and I'm trying to follow the Cell editor developer guide, but I'm at a loss.
My requirement is to show a couple of checkboxes and a text box in one cell (not my idea). My thought was to have the data for the cell be a little json string {"Attr1": true, "Attr2": false} and have a custom renderer/editor that would parse the cell value and set the checkboxes appropriately.
I made a fiddle of it here: http://jsfiddle.net/9k1x4z6b/2/
I created a class for the custom attributes column and a renderer function and set the renderer and editor for the column like this
class CustomAttributesEditor extends Handsontable.editors.BaseEditor {
/**
* Initializes editor instance, DOM Element and mount hooks.
*/
// constructor (props) {
// super(props)
// }
prepare(row, col, prop, td, originalValue, cellProperties) {
// Invoke the original method...
super.prepare(row, col, prop, td, originalValue, cellProperties);
td.innerHTML = '';
this.AttributeNames = ['Attr1', 'Attr2'];
this.ctrls = {};
let parsedValue = JSON.parse(Handsontable.helper.stringify(originalValue));
// Create checkbox controls
for (let i = 0; i < this.AttributeNames.length; i++) {
let AttributeName = this.AttributeNames[i];
let span = document.createElement('span');
span.style.whiteSpace = 'nowrap';
let checkbox = document.createElement('input');
this.ctrls[AttributeName] = checkbox;
checkbox.type = 'checkbox';
if (parsedValue[AttributeName] == 'yes') {
checkbox.checked = true;
}
let label = document.createElement('label');
label.innerHTML = AttributeName;
label.htmlFor = checkbox.id;
span.appendChild(checkbox);
span.appendChild(label);
td.appendChild(span);
td.appendChild(document.createElement('br'));
}
// Create a control that is shown/hidden when the "Attr2" checkbox is toggled
let CustomAttributesAttr3SubDiv = document.createElement('div');
var label = document.createElement('label');
label.innerHTML = "Attr3 supplier:";
CustomAttributesAttr3SubDiv.appendChild(label);
var CustomAttributesAttr3 = document.createElement('input');
if (parsedValue.hasOwnProperty('Attr3')) {
CustomAttributesAttr3.value = parsedValue['Attr3'];
}
this.ctrls['Attr3'] = CustomAttributesAttr3;
this.AttributeNames.push('Attr3');
CustomAttributesAttr3.setAttribute('title', 'Attr3');
CustomAttributesAttr3.style.width = '12em';
CustomAttributesAttr3SubDiv.appendChild(CustomAttributesAttr3);
CustomAttributesAttr3SubDiv.appendChild(document.createElement('br'));
td.appendChild(CustomAttributesAttr3SubDiv);
let Attr2Checkbox = this.ctrls['Attr2'];
//CustomAttributes_ShowHideValueCtrl(Attr2Checkbox);
$(Attr2Checkbox).off('change').on('change', function () {
//CustomAttributes_ShowHideValueCtrl(this); // irrelevant to checkbox problem. function shows Attr3 input when Attr2Checkbox is checked, hides otherwise
});
//preventDefault();
}
getValue(){
// This function returns the set value of the controls
let ctrls = this.ctrls;
let resultDict = {};
for (let ctrlID in ctrls){
let ctrl = ctrls[ctrlID];
let FormattedAttributeName = ctrlID.replaceAll(' ', '_');
let val = null;
if (ctrl.type == 'checkbox'){
if (ctrl.checked == true) {
val = 'yes';
} else {
val = null;
}
} else {
val = ctrl.value;
}
resultDict[FormattedAttributeName] = val;
}
return JSON.stringify(resultDict)
}
setValue(value){
// this function sets the value of the controls to match the data value
let parsedValue = {};
try {
parsedValue = JSON.parse(Handsontable.helper.stringify(value));
} catch (exc) {
for (let i = 0; i < this.AttributeNames.length; i++) {
parsedValue[this.AttributeNames[i]] = 'no';
}
}
let ctrls = this.ctrls;
let resultDict = {};
for (let ctrlID in ctrls){
let ctrl = ctrls[ctrlID];
let FormattedAttributeName = ctrlID.replaceAll(' ', '_');
let val = parsedValue[FormattedAttributeName];
if (ctrl.type == 'checkbox'){
if (val == 'yes'){
ctrl.checked = true;
} else {
ctrl.checked = false;
}
} else {
ctrl.value = val;
}
}
}
saveValue(value, ctrlDown){
super.saveValue(value, ctrlDown);
}
open(){}
close(){}
focus(){}
}
function CustomAttributesRenderer(instance, td, row, col, prop, value, cellProperties) {
// This function shows labels for the checked Attr1-3 values
let AttributeNames = ['Attr1', 'Attr2', 'Attr3'];
parsedValue = JSON.parse(Handsontable.helper.stringify(value));
Handsontable.dom.empty(td);
for (let i = 0; i < AttributeNames.length; i++) {
let AttributeName = AttributeNames[i];
let span = document.createElement('span');
span.style.whiteSpace = 'nowrap';
if (parsedValue[AttributeName] == 'yes') {
let label = document.createElement('label');
label.innerHTML = AttributeName;
span.appendChild(label);
td.appendChild(span);
}
td.appendChild(document.createElement('br'));
}
return td;
}
document.addEventListener("DOMContentLoaded", function () {
var container = document.getElementById('divBFEPartMatrix');
var hot = new Handsontable(container, {
data: [
[JSON.stringify({"Attr1": "yes", "Attr2": "yes", "Attr3": ""})],
[JSON.stringify({"Attr1": "yes", "Attr2": "yes", "Attr3": "somevalue"})],
[JSON.stringify({"Attr1": "no", "Attr2": "no", "Attr3": ""})],
],
columns: [
{renderer: CustomAttributesRenderer, editor: CustomAttributesEditor}
],
rowHeaders: true,
colHeaders: true,
filters: true,
dropdownMenu: true
});
})
The result appears properly, with the cell initially not having checkboxes visible due to the renderer not showing them, then when you click the cell the checkboxes appear. The problem is when you click the checkbox it doesn't toggle.
I presume something in handsontable is re-creating the td and blowing away the state change, but I can't figure out how to prevent that from happening. Is there a fully working custom editor fiddle or something I can reference to figure out how to prevent bubbling?
Any help you can offer would be greatly appreciated.
Well, after another couple days of fiddling around I figured out the full set of code I needed to add to make this work. Posted here in case it helps someone else trying to make a custom cell editor/renderer in handsontable.
class SubstitutePartEditor extends Handsontable.editors.BaseEditor {
init(){
// This function creates the edit div
let div = document.createElement('div');
this.div = div;
div.style.display = 'none';
div.style.position = 'absolute';
div.style.width = 'auto';
div.style.backgroundColor = 'white';
this.AttributeNames = ['The waste bin is part of the waste cart', 'This item includes SUPPLIER tapestry'];
this.ctrls = {};
let cbIsSubstitutePart = document.createElement('input');
this.ctrls['IsSubstitutePart'] = cbIsSubstitutePart;
cbIsSubstitutePart.type = 'checkbox';
div.appendChild(cbIsSubstitutePart);
div.appendChild(document.createElement('br'));
let SubstitutePartSubDiv = document.createElement('div');
SubstitutePartSubDiv.style.display = 'inline-block';
div.appendChild(SubstitutePartSubDiv);
let inputSubstitutePart = document.createElement('textarea');
this.ctrls['SubstitutePart'] = inputSubstitutePart;
inputSubstitutePart.style.width = '220px';
inputSubstitutePart.style.height = '88px';
SubstitutePartSubDiv.appendChild(inputSubstitutePart);
this.hot.rootElement.appendChild(div);
}
UpdateDependentControls(){
let RequiredCtrl = this.ctrls['IsSubstitutePart'];
let Ctrl = this.ctrls['SubstitutePart'];
if (RequiredCtrl.checked == true){
Ctrl.style.display = '';
} else {
Ctrl.style.display = 'none';
}
$(RequiredCtrl).off('change').on('change', function(){
if (RequiredCtrl.checked == true){
Ctrl.style.display = '';
} else {
Ctrl.style.display = 'none';
}
});
}
getValue(){
// This function returns the set value of the controls
let ctrls = this.ctrls;
let resultDict = {};
for (let ctrlID in ctrls){
let ctrl = ctrls[ctrlID];
let FormattedAttributeName = ctrlID.replaceAll(' ', '_');
let val = null;
if (ctrl.type == 'checkbox'){
if (ctrl.checked == true) {
val = 'yes';
} else {
val = null;
}
} else {
val = ctrl.value;
}
resultDict[FormattedAttributeName] = val;
}
return JSON.stringify(resultDict)
}
setValue(value){
// this function sets the value of the controls to match the data value
let parsedValue = {};
try {
parsedValue = JSON.parse(Handsontable.helper.stringify(value));
} catch (exc) {
parsedValue = {
IsSubstitutePart: 'no',
SubstitutePart: "This item requires a waiver from the operator's foreign regulatory agency, <FOREIGN REGULATORY AGENCY NAME>."
};
}
let ctrls = this.ctrls;
let resultDict = {};
for (let ctrlID in ctrls){
let ctrl = ctrls[ctrlID];
let FormattedAttributeName = ctrlID.replaceAll(' ', '_');
let val = parsedValue[FormattedAttributeName];
if (ctrl.type == 'checkbox'){
if (val == 'yes'){
ctrl.checked = true;
} else {
ctrl.checked = false;
}
} else {
ctrl.value = val;
}
}
}
saveValue(value, ctrlDown){
super.saveValue(value, ctrlDown);
}
open() {
this._opened = true;
this.refreshDimensions();
this.UpdateDependentControls();
this.div.style.display = '';
}
refreshDimensions() {
this.TD = this.getEditedCell();
// TD is outside of the viewport.
if (!this.TD) {
this.close();
return;
}
const { wtOverlays } = this.hot.view.wt;
const currentOffset = Handsontable.dom.offset(this.TD);
const containerOffset = Handsontable.dom.offset(this.hot.rootElement);
const scrollableContainer = wtOverlays.scrollableElement;
const editorSection = this.checkEditorSection();
let width = Handsontable.dom.outerWidth(this.TD) + 1;
let height = Handsontable.dom.outerHeight(this.TD) + 1;
let editTop = currentOffset.top - containerOffset.top - 1 - (scrollableContainer.scrollTop || 0);
let editLeft = currentOffset.left - containerOffset.left - 1 - (scrollableContainer.scrollLeft || 0);
let cssTransformOffset;
switch (editorSection) {
case 'top':
cssTransformOffset = Handsontable.dom.getCssTransform(wtOverlays.topOverlay.clone.wtTable.holder.parentNode);
break;
case 'left':
cssTransformOffset = Handsontable.dom.getCssTransform(wtOverlays.leftOverlay.clone.wtTable.holder.parentNode);
break;
case 'top-left-corner':
cssTransformOffset = Handsontable.dom.getCssTransform(wtOverlays.topLeftCornerOverlay.clone.wtTable.holder.parentNode);
break;
case 'bottom-left-corner':
cssTransformOffset = Handsontable.dom.getCssTransform(wtOverlays.bottomLeftCornerOverlay.clone.wtTable.holder.parentNode);
break;
case 'bottom':
cssTransformOffset = Handsontable.dom.getCssTransform(wtOverlays.bottomOverlay.clone.wtTable.holder.parentNode);
break;
default:
break;
}
if (this.hot.getSelectedLast()[0] === 0) {
editTop += 1;
}
if (this.hot.getSelectedLast()[1] === 0) {
editLeft += 1;
}
const selectStyle = this.div.style;
if (cssTransformOffset && cssTransformOffset !== -1) {
selectStyle[cssTransformOffset[0]] = cssTransformOffset[1];
} else {
Handsontable.dom.resetCssTransform(this.div);
}
const cellComputedStyle = Handsontable.dom.getComputedStyle(this.TD, this.hot.rootWindow);
if (parseInt(cellComputedStyle.borderTopWidth, 10) > 0) {
height -= 1;
}
if (parseInt(cellComputedStyle.borderLeftWidth, 10) > 0) {
width -= 1;
}
selectStyle.height = `${height}px`;
selectStyle.minWidth = `${width}px`;
selectStyle.top = `${editTop}px`;
selectStyle.left = `${editLeft}px`;
selectStyle.margin = '0px';
}
getEditedCell() {
const { wtOverlays } = this.hot.view.wt;
const editorSection = this.checkEditorSection();
let editedCell;
switch (editorSection) {
case 'top':
editedCell = wtOverlays.topOverlay.clone.wtTable.getCell({
row: this.row,
col: this.col
});
this.select.style.zIndex = 101;
break;
case 'corner':
editedCell = wtOverlays.topLeftCornerOverlay.clone.wtTable.getCell({
row: this.row,
col: this.col
});
this.select.style.zIndex = 103;
break;
case 'left':
editedCell = wtOverlays.leftOverlay.clone.wtTable.getCell({
row: this.row,
col: this.col
});
this.select.style.zIndex = 102;
break;
default:
editedCell = this.hot.getCell(this.row, this.col);
this.div.style.zIndex = '';
break;
}
return editedCell < 0 ? void 0 : editedCell;
}
focus() {
this.div.focus();
}
close() {
this._opened = false;
this.div.style.display = 'none';
}
}
function SubstitutePartRenderer(instance, td, row, col, prop, value, cellProperties) {
// This function draws the multi checkboxes for the SubstitutePart input field
// Note: if AttributeNames changes you must also update BFEPartMatrix_Edit.ascx line ~240 to match (<- this is where the data is saved)
//Handsontable.renderers.HtmlRenderer.apply(this, arguments);
let parsedValue = {};
try {
parsedValue = JSON.parse(Handsontable.helper.stringify(value));
} catch {
// nothing to do
}
Handsontable.dom.empty(td);
let div = document.createElement('div');
//div.style.whiteSpace = 'nowrap';
div.style.display = 'block';
td.appendChild(div);
if (parsedValue.hasOwnProperty('IsSubstitutePart')) {
if (parsedValue.IsSubstitutePart == 'yes') {
} else {
td.innerHTML = 'N/A';
return;
}
} else {
td.innerHTML = 'N/A';
return;
}
let SubstitutePartSubDiv = document.createElement('div');
SubstitutePartSubDiv.style.display = 'inline-block';
div.appendChild(SubstitutePartSubDiv);
// text area
let inputSubstitutePart = document.createElement('label');
inputSubstitutePart.innerHTML = parsedValue['SubstitutePart'].escape();
inputSubstitutePart.style.width = '220px';
inputSubstitutePart.style.height = '88px';
SubstitutePartSubDiv.appendChild(inputSubstitutePart);
return td;
}
then set the render and editor of the hot column like this
columns: [
{renderer: CustomAttributesRenderer, editor: CustomAttributesEditor}
],

Not real random function in a Blogger widget, it always shows 'neighbor' posts from the past

My blog is 12 years old, I have more than 5000 posts. I am using a widget that shows random posts from a specific label. I set it to show 2 posts in the sidebar, and I noticed that these posts are always 'neighbors', which means they are always from the same month in the past. For example, it's always 2 posts from May 2014, or June 2018. It's never something like: 1 post from May 2014 and the other from June 2018. Do you have any idea what the problem is?
Here is the part of the code which (I believe) contains the mistake:
rand=Math.floor((Math.random()*_vRiO.total_entry)+1);
if(rand+bcd140526_post_count>_vRiO.total_entry){
rand=_vRiO.total_entry-bcd140526_post_count+1;
}
if(rand<1){
rand=1;
}
var _vXsM=HOST+_s7IgU[159];
if(bcd140526_index_label){
_vXsM+=_s7IgU[160]+encodeURIComponent(bcd140526_index_label);
}
_vXsM+=_s7IgU[161]+bcd140526_post_count+_s7IgU[162]+rand+_s7IgU[163];
_fIoT(_vXsM);
}else{
_fYbP(json);
}
}
var _vXsM=HOST+_s7IgU[164];
if(bcd140526_index_label){
_vXsM+=_s7IgU[165]+encodeURIComponent(bcd140526_index_label);
}
_vXsM+=_s7IgU[166];
if(bcd140526_sort_by==_s7IgU[167]){
_vXsM+=_s7IgU[168];
}else{
_vXsM+=_s7IgU[169]+bcd140526_post_count;
}
_vXsM+=_s7IgU[170];_fIoT(_vXsM);
I can't paste the whole code, the website doesn't let me. But you can get it here: https://sneeit.com/blogger-random-recent-specific-label-posts-widget-all-in-one-post-feed-widget/
My settings:
Post Count - 2
Post Order - Random
Specific Label - Summer
Show Thumbnail - Checked
Thumbnail Size - 200
Show Label - No
Show Comment Numbers - No
Show Date - No
Show Author Name - No
Show Readmore - No
Show Snippet - No
Show Copyright - No
Design Style - List
I have painstakingly deobfuscated this extension to be able to check how you could modify it (which should be much easier for you if you still want to), and I see that getting "non-neighbor" random numbers is not what this system is designed to do. choosePost(json) chooses one post by number to be the starting post, and makeWidget (which, bizarrely, uses string concatenation and document.write to generate the widget) just uses the first post_count posts after the chosen post, so your objective is not (easily) doable.
var show_thumbnail = true;
var show_label = false;
var show_comment_numbers = false;
var show_date = false;
var show_author_name = false;
var show_readmore = false;
var show_snippet = false;
var hide_copyright = true;
var snippet_length = 150;
var post_count = 3;
var thumbnail_size = 140; // v1.5, only effect with list style
var sort_by = 'random'; // latest or random
var index_label = 'summer';
var design_style = 'list'; // list or column
var date_format = 'mm/dd/yyyy';
var lang_readmore = 'Readmore';
var HOST = '';
function sourceJSfile(url) {
document.write('<script type="text/javascript" src="' + url + '"<\/script>');
}
function generateDate(pub_date, format) {
pub_date = pub_date.split('-');
date = new Date(pub_date[0], pub_date[1] - 1, pub_date[2].substring(0, 2));
dd = date.getDate();
mm = date.getMonth() + 1;
yyyy = date.getFullYear();
format = format.replace('dd', dd);
format = format.replace('mm', mm);
format = format.replace('yyyy', yyyy);
return format;
}
function cleanContent(content) {
var tgt = '';
var imgtag = '<img ';
var srctag = 'src="';
var quote = '\"';
index0 = content.indexOf(imgtag);
if (index0 != -1) {
index1 = content.indexOf(srctag, index0);
index2 = content.indexOf(quote, index1 + srctag.length);
tgt = content.substring(index1 + srctag.length, index2);
}
if (tgt == '') {
imgtag = 'data-thumbnail-src="';
srctag = '"';
index0 = content.indexOf(imgtag);
if (index0 != -1) {
index1 = content.indexOf(srctag, index0 + imgtag.length);
if (index0 != -1) {
tgt = content.substring(index0 + imgtag.length, index1);
}
}
}
if (tgt == '') {
imgtag = '<iframe ';
srctag = 'src="';
quote = '"';
index0 = content.indexOf(imgtag);
if (index0 != -1) {
index1 = content.indexOf(srctag, index0);
if (index0 != -1) {
index2 = content.indexOf(quote, index1 + srctag.length);
if (index0 != -1) {
tgt = content.substring(index1 + srctag.length, index2);
tgt = tgt.replace("http://www.youtube.com/watch?v=", '');
tgt = tgt.replace("http://www.youtube.com/embed/", '');
tgt = tgt.replace('?rel=0', '');
tgt = 'http://img.youtube.com/vi/' + tgt + '/mqdefault.jpg';
}
}
}
}
return tgt;
}
function jsonProcessor(json) {
var data = new Object();
var regex = /<\S[^>]*>/g;
data.id = json.feed.id.$t;
key = 'blog-';
index = data.id.indexOf(key);
data.id = data.id.substring(index + key.length);
data.id = data.id.replace('.comments', '');
data.cate = new Array();
if ('category' in json.feed) {
for (let i = 0; i < json.feed.category.length; i++) {
data.cate[i] = json.feed.category[i].term;
}
}
data.title = '';
if ('title' in json.feed) {
data.title = json.feed.title.$t;
}
data.subtitle = '';
if ('subtitle' in json.feed) {
data.subtitle = json.feed.subtitle.$t;
}
data.admin = new Object();
data.admin.name = 'Anonymous';
data.admin.uri = '';
data.admin.avatar = 'http://img1.blogblog.com/img/anon36.png';
if ('name' in json.feed.author[0]) {
data.admin.name = json.feed.author[0].name.$t;
}
if ('uri' in json.feed.author[0]) {
data.admin.uri = json.feed.author[0].uri.$t;
}
if ('gd$image' in json.feed.author[0]) {
if (json.feed.author[0].gd$image.src != 'http://img1.blogblog.com/img/blank.gif') {
data.admin.avatar = json.feed.author[0].gd$image.src;
}
}
data.total_entry = Number(json.feed.openSearch$totalResults.$t);
data.start_index = Number(json.feed.openSearch$startIndex.$t);
data.item_per_page = Number(json.feed.openSearch$itemsPerPage.$t);
data.entry_number = 0;
if ('entry' in json.feed) {
data.entry_number = json.feed.entry.length;
}
data.entry = new Array();
for (let i = 0; i < data.entry_number; i++) {
data.entry[i] = new Object();
temp = new Object();
entry = json.feed.entry[i];
temp.id = entry.id.$t;
key = 'post-';
index = temp.id.indexOf(key);
temp.id = temp.id.substring(index + key.length);
temp.published = '';
if ('published' in entry) {
temp.published = entry.published.$t;
}
temp.cate = new Array();
if ('category' in entry) {
for (j = 0; j < entry.category.length; j++) {
temp.cate[j] = entry.category[j].term;
}
}
temp.title = '';
if ('title' in entry) {
temp.title = entry.title.$t;
}
temp.content = '';
if ('content' in entry) {
temp.content = entry.content.$t;
}
temp.summary = '';
if ('summary' in entry) {
temp.summary = entry.summary.$t;
}
if (temp.summary == '') {
temp.summary = temp.content.replace(regex, '');
}
if (temp.content == '') {
temp.content = temp.summary;
}
temp.link = '';
temp.reply_label = 'comments';
if ('link' in entry) {
for (j = 0; j < entry.link.length; j++) {
if (entry.link[j].rel == 'alternate') {
temp.link = entry.link[j].href;
}
if (entry.link[j].rel == 'replies') {
temp.reply_label = entry.link[j].title;
}
}
}
temp.author = new Object();
temp.author.name = 'Anonymous';
temp.author.uri = '';
temp.author.avatar = 'http://img1.blogblog.com/img/anon36.png';
a0 = entry.author[0];
if ('name' in a0) {
temp.author.name = a0.name.$t;
}
if ('uri' in a0) {
temp.author.uri = a0.uri.$t;
}
if ('gd$image' in a0) {
if (a0.gd$image.src != 'http://img1.blogblog.com/blank.gif') {
temp.author.avatar = a0.gd$image.src;
}
}
temp.thumbnail = '';
if ('media$thumbnail' in entry) {
temp.thumbnail = entry.media$thumbnail.url;
}
temp.reply_number = 0;
if ('thr$total' in entry) {
temp.reply_number = Number(entry.thr$total.$t);
}
temp.reply_label = temp.reply_label.replace(temp.reply_number + ' ', '');
temp.reply_to = '';
temp.reply_json = '';
temp.reply_title = '';
if ('thr$in-reply-to' in entry) {
temp.reply_to = entry['thr$in-reply-to'].href;
temp.reply_json = entry['thr$in-reply-to'].source;
temp.reply_json = temp.reply_json.replace('/default/', '/summary/');
temp.reply_json = temp.reply_json + '?alt=json-in-script';
}
temp.pid = '';
if ('gd$extendedProperty' in entry) {
for (j = 0; j < entry.gd$extendedProperty.length; j++) {
if (entry.gd$extendedProperty[j].name == 'blogger.itemClass') {
temp.pid = entry.gd$extendedProperty[j].value;
}
}
}
temp.pid = temp.pid.replace('pid-', '');
data.entry[i] = temp;
}
return data;
}
if (typeof(jquery_included) == 'undefined') {
jquery_included = false;
}
function jqueryLoader() {
if (typeof(jQuery) == 'undefined') {
if (!jquery_included) {
jquery_included = true;
var scriptEl = document.createElement('script');
scriptEl.setAttribute('src', 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js');
scriptEl.setAttribute('type', 'text/javascript');
document.getElementsByTagName('head')[0].appendChild(scriptEl);
}
setTimeout(jqueryLoader, 50);
} else {
if (!($('link[href*="font-awesome.css"]').length)) {
linkEl = document.createElement('link');
linkEl.setAttribute('href', 'http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css');
linkEl.setAttribute('rel', 'stylesheet');
document.head.appendChild(linkEl);
}
}
}
jqueryLoader();
function makeWidget(json) {
var div = '<div style="clear:both!important;float:none;!important;line-height:0!important"></div>';
var jsonOut = jsonProcessor(json);
var docAppend = '';
if (jsonOut.total_entry) {
docAppend += ('<div class="post_feed ' + design_style + ' ' + ((show_thumbnail) ? 'thumb' : 'no-thumb') + '"><ul>');
for (let i = 0; i < jsonOut.total_entry && i < post_count; i++) {
p = jsonOut.entry[i];
docAppend += ('<li class="item item-' + i + '">');
if (!p.thumbnail) {
p.thumbnail = cleanContent(p.content);
}
if (show_thumbnail && p.thumbnail) {
var tgt = p.thumbnail;
if (tgt.indexOf('/s72-c/') != -1){
if (design_style === 'column')
tgt = tgt.replace('/s72-c/', '/s1600/');
else
tgt = tgt.replace('/s72-c/', '/s' + thumbnail_size + '-c/');
} else if (tgt.indexOf('youtube.com') != -1 && tgt.indexOf('/default.') != -1) {
tgt = tgt.replace('/default.', '/mqdefault.');
}
p.thumbnail = tgt;
docAppend += ('<a class="thumbnail" style="width:' + thumbnail_size + 'px;height:' + thumbnail_size + 'px;" href="' + p.link + '"><img src="' + p.thumbnail + '"/></a>');
}
docAppend += '<div class="item-body">';
if (show_label && (typeof(p.cate[0]) != 'undefined')) {
docAppend += ('<a class="cate" href="' + HOST + '/search/label/' + p.cate[0] + '">' + p.cate[0] + '</a>');
}
docAppend += ('<h3 class="title">' + p.title + '</h3>');
if (show_author_name || show_comment_numbers || show_date) {
docAppend += '<div class="meta">';
if (show_author_name) {
docAppend += ('<span class="meta-item author-name"><i class="fa fa-user"></i> ' + p.author.name + '</span>');
}
if (show_comment_numbers) {
docAppend += ('<span class="meta-item comment-number"><i class="fa fa-comment"></i> ' + p.reply_number + '</span>');
}
if (show_comment_numbers) {
docAppend += ('<span class="meta-item date-time"><i class="fa fa-clock-o"></i> ' + generateDate(p.published, date_format) +'</span>');
}
docAppend += (div + '</div>' + div);
}
if (show_snippet) {
if (p.summary.length > snippet_length) {
p.summary = p.summary.substring(0, snippet_length) + '...';
}
if (show_readmore) {
p.summary += ' ' + lang_readmore + '';
}
docAppend += ('<p class="snippet">' + p.summary + '</p>');
}
docAppend += (div + '</div>' + div);
docAppend += ('</li>');
}
docAppend += ('</ul>');
if (!hide_copyright) {
docAppend += div;
docAppend += '<a target="_blank" class="copyright" href="http://www.sneeit.com/2014/05/blogger-random-recent-specific-label-posts-widget-all-in-one-post-feed-widget" style="font-size: 11px!important;text-align:right;visibility: visible;!important;text-indent:0!important;height:auto!important;width:100%!important;position:static!important;color:#999!important;display:block!important;opacity:1!important;">BloggerWidget</a>';
}
docAppend += ('</div>' + div);
} else {
docAppend += '<p><em>Have no posts</em><p>';
}
document.write(docAppend);
}
function choosePost(json) {
if (sort_by == 'random') {
var processedJSON = jsonProcessor(json);
rand = Math.floor((Math.random() * processedJSON.total_entry) + 1);
if (rand + post_count > processedJSON.total_entry) {
rand = processedJSON.total_entry - post_count + 1;
}
if (rand < 1) {
rand = 1;
}
var request = HOST + '/feeds/posts/default';
if (index_label) {
request += '/-/' + encodeURIComponent(index_label);
}
request += '?alt=json-in-script&max-result=' + post_count + '&start-index=' + rand + '&callback=makeWidget';
sourceJSfile(request);
} else {
makeWidget(json);
}
}
var request = HOST + '/feeds/posts/default';
if (index_label) {
request += '/-/' + encodeURIComponent(index_label);
}
request += '?alt=json-in-script';
if (sort_by == 'random') {
request += '&max-results=0';
} else {
request += '&max-results=' + post_count;
}
request += '&callback=choosePost';
sourceJSfile(request);
The modifications will take some work, but the deobfuscated version should be much easier to use. I'd recommend removing jqueryLoader, and to get you started: the API requests are sourceJSfile('/feeds/post/default/-/summer?alt=json-in-script&max-results=1&callback=choosePost'). You'd probably be better off rewriting the thing from scratch than trying to bodge it on top of this code, I think.
PS: This code loads the entire jquery library so it can load some random stylesheet in jqueryLoad.

How to use babel into appcelerator project?

I'm importend in my workspace, a project build in appcelerator.
So I have some error like this:
If I open any file, I have this situation:
I don't know, how to fix this.
So this is my plugin.js
"use strict";
exports.__esModule = true;
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn");
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require("babel-runtime/helpers/inherits");
var _inherits3 = _interopRequireDefault(_inherits2);
var _optionManager = require("./file/options/option-manager");
var _optionManager2 = _interopRequireDefault(_optionManager);
var _babelMessages = require("babel-messages");
var messages = _interopRequireWildcard(_babelMessages);
var _store = require("../store");
var _store2 = _interopRequireDefault(_store);
var _babelTraverse = require("babel-traverse");
var _babelTraverse2 = _interopRequireDefault(_babelTraverse);
var _assign = require("lodash/assign");
var _assign2 = _interopRequireDefault(_assign);
var _clone = require("lodash/clone");
var _clone2 = _interopRequireDefault(_clone);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint max-len: 0 */
var GLOBAL_VISITOR_PROPS = ["enter", "exit"];
var Plugin = function (_Store) {
(0, _inherits3.default)(Plugin, _Store);
function Plugin(plugin, key) {
(0, _classCallCheck3.default)(this, Plugin);
var _this = (0, _possibleConstructorReturn3.default)(this, _Store.call(this));
_this.initialized = false;
_this.raw = (0, _assign2.default)({}, plugin);
_this.key = key;
_this.manipulateOptions = _this.take("manipulateOptions");
_this.post = _this.take("post");
_this.pre = _this.take("pre");
_this.visitor = _this.normaliseVisitor((0, _clone2.default)(_this.take("visitor")) || {});
return _this;
}
Plugin.prototype.take = function take(key) {
var val = this.raw[key];
delete this.raw[key];
return val;
};
Plugin.prototype.chain = function chain(target, key) {
if (!target[key]) return this[key];
if (!this[key]) return target[key];
var fns = [target[key], this[key]];
return function () {
var val = void 0;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
for (var _iterator = fns, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var fn = _ref;
if (fn) {
var ret = fn.apply(this, args);
if (ret != null) val = ret;
}
}
return val;
};
};
Plugin.prototype.maybeInherit = function maybeInherit(loc) {
var inherits = this.take("inherits");
if (!inherits) return;
inherits = _optionManager2.default.normalisePlugin(inherits, loc, "inherits");
this.manipulateOptions = this.chain(inherits, "manipulateOptions");
this.post = this.chain(inherits, "post");
this.pre = this.chain(inherits, "pre");
this.visitor = _babelTraverse2.default.visitors.merge([inherits.visitor, this.visitor]);
};
/**
* We lazy initialise parts of a plugin that rely on contextual information such as
* position on disk and how it was specified.
*/
Plugin.prototype.init = function init(loc, i) {
if (this.initialized) return;
this.initialized = true;
this.maybeInherit(loc);
for (var key in this.raw) {
throw new Error(messages.get("pluginInvalidProperty", loc, i, key));
}
};
Plugin.prototype.normaliseVisitor = function normaliseVisitor(visitor) {
for (var _iterator2 = GLOBAL_VISITOR_PROPS, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var key = _ref2;
if (visitor[key]) {
throw new Error("Plugins aren't allowed to specify catch-all enter/exit handlers. Please target individual nodes.");
}
}
_babelTraverse2.default.explode(visitor);
return visitor;
};
return Plugin;
}(_store2.default);
exports.default = Plugin;
module.exports = exports["default"];
How can I fixed it?
import syntax is from ECMAScript 6 - which is yet to be added in the Appcelerator Studio.
https://jira.appcelerator.org/browse/TISTUD-6927

leaflet Dynamic icon with filter

I'm trying to create an map with the leaflet-simple-csv-master (i'm a beginner). It's really nice and i'd like to show different icons with my types (for exemple 1 icon for schools, one for administrations,...). I succed to show my different icons when i have the map but when i click to the filter, my icons disappear. In fact it doesn't work because it do not recognize my variable when i use the filter and i can read that my img is no more logos/type1.png but logos/undefined.png.
This is my all code.
var basemap = new L.TileLayer(baseUrl, {maxZoom: 17, attribution: baseAttribution, subdomains: subdomains, opacity: opacity});
var center = new L.LatLng(0, 0);
var map = new L.Map('map', {center: center, zoom: 2, maxZoom: maxZoom, layers: [basemap]});
var popupOpts = {
autoPanPadding: new L.Point(5, 50),
autoPan: true
};
var points = L.geoCsv (null, {
firstLineTitles: true,
fieldSeparator: fieldSeparator,
onEachFeature: function (feature, layer) {
var popup = '<div class="popup-content"><table class="table table-striped table-condensed">';
for (var clave in feature.properties) {
var title = points.getPropertyTitle(clave).strip();
var attr = feature.properties[clave];
if (title == labelColumn) {
layer.bindLabel(feature.properties[clave], {className: 'map-label'});
}
if (attr.indexOf('http') === 0) {
attr = '<a target="_blank" href="' + attr + '">'+ attr + '</a>';
}
if (attr) {
popup += '<tr><th>'+title+'</th><td>'+ attr +'</td></tr>';
}
}
popup += "</table></popup-content>";
layer.bindPopup(popup, popupOpts);
},
pointToLayer: function (feature, latlng) {
var logo = feature.properties['type'];
return L.marker(latlng, {
icon:L.icon({
iconUrl: 'logos/'+logo+'.png',
shadowUrl: 'marker-shadow.png',
iconSize: [25,41],
shadowSize: [41, 41],
shadowAnchor: [13, 20]
})
});
},
filter: function(feature, layer) {
total += 1;
if (!filterString) {
hits += 1;
return true;
}
var hit = false;
var lowerFilterString = filterString.toLowerCase().strip();
$.each(feature.properties, function(k, v) {
var value = v.toLowerCase();
if (value.indexOf(lowerFilterString) !== -1) {
hit = true;
hits += 1;
return false;
}
});
return hit;
}
});
var hits = 0;
var total = 0;
var filterString;
var markers = new L.MarkerClusterGroup();
var dataCsv;
var addCsvMarkers = function() {
hits = 0;
total = 0;
filterString = document.getElementById('filter-string').value;
if (filterString) {
$("#clear").fadeIn();
} else {
$("#clear").fadeOut();
}
map.removeLayer(markers);
points.clearLayers();
markers = new L.MarkerClusterGroup(clusterOptions);
points.addData(dataCsv);
markers.addLayer(points);
map.addLayer(markers);
try {
var bounds = markers.getBounds();
if (bounds) {
map.fitBounds(bounds);
}
} catch(err) {
// pass
}
if (total > 0) {
$('#search-results').html("Showing " + hits + " of " + total);
}
return false;
};
var typeAheadSource = [];
function ArrayToSet(a) {
var temp = {};
for (var i = 0; i < a.length; i++)
temp[a[i]] = true;
var r = [];
for (var k in temp)
r.push(k);
return r;
}
function populateTypeAhead(csv, delimiter) {
var lines = csv.split("\n");
for (var i = lines.length - 1; i >= 1; i--) {
var items = lines[i].split(delimiter);
for (var j = items.length - 1; j >= 0; j--) {
var item = items[j].strip();
item = item.replace(/"/g,'');
if (item.indexOf("http") !== 0 && isNaN(parseFloat(item))) {
typeAheadSource.push(item);
var words = item.split(/\W+/);
for (var k = words.length - 1; k >= 0; k--) {
typeAheadSource.push(words[k]);
}
}
}
}
}
if(typeof(String.prototype.strip) === "undefined") {
String.prototype.strip = function() {
return String(this).replace(/^\s+|\s+$/g, '');
};
}
map.addLayer(markers);
$(document).ready( function() {
$.ajax ({
type:'GET',
dataType:'text',
url: dataUrl,
contentType: "text/csv; charset=utf-8",
error: function() {
alert('Error retrieving csv file');
},
success: function(csv) {
dataCsv = csv;
populateTypeAhead(csv, fieldSeparator);
typeAheadSource = ArrayToSet(typeAheadSource);
$('#filter-string').typeahead({source: typeAheadSource});
addCsvMarkers();
}
});
$("#clear").click(function(evt){
evt.preventDefault();
$("#filter-string").val("").focus();
addCsvMarkers();
});
});

Resources