commit
stringlengths 40
40
| subject
stringlengths 1
3.25k
| old_file
stringlengths 4
311
| new_file
stringlengths 4
311
| old_contents
stringlengths 0
26.3k
| lang
stringclasses 3
values | proba
float64 0
1
| diff
stringlengths 0
7.82k
|
---|---|---|---|---|---|---|---|
876547b1ea81a7cfc4afdb032acfa1d6ef4a78cc
|
Fix saving comments
|
js/id/ui/commit.js
|
js/id/ui/commit.js
|
iD.ui.Commit = function(context) {
var event = d3.dispatch('cancel', 'save', 'fix'),
presets = context.presets();
function zipSame(d) {
var c = {}, n = -1;
for (var i = 0; i < d.length; i++) {
var desc = {
name: d[i].tags.name || presets.match(d[i], context.graph()).name(),
geometry: d[i].geometry(context.graph()),
count: 1,
tagText: iD.util.tagText(d[i])
};
var fingerprint = desc.name + desc.tagText;
if (c[fingerprint]) {
c[fingerprint].count++;
} else {
c[fingerprint] = desc;
}
}
return _.values(c);
}
function commit(selection) {
var changes = context.history().changes();
function changesLength(d) { return changes[d].length; }
var header = selection.append('div')
.attr('class', 'header fillL');
header.append('button')
.attr('class', 'fr')
.on('click', event.cancel)
.append('span')
.attr('class', 'icon close');
header.append('h3')
.text(t('commit.title'));
var body = selection.append('div')
.attr('class', 'body');
// Comment Section
var commentSection = body.append('div')
.attr('class', 'modal-section form-field commit-form');
commentSection.append('label')
.attr('class', 'form-label')
.text(t('commit.message_label'));
var commentField = commentSection.append('textarea')
.attr('placeholder', t('commit.description_placeholder'))
.property('value', context.storage('comment') || '')
.on('blur.save', function () {
context.storage('comment', this.value);
});
commentField.node().select();
// Save Section
var saveSection = body.append('div')
.attr('class','modal-section fillL cf');
var prose = saveSection.append('p')
.attr('class', 'commit-info')
.html(t('commit.upload_explanation'));
context.connection().userDetails(function(err, user) {
if (err) return;
var userLink = d3.select(document.createElement('div'));
if (user.image_url) {
userLink.append('img')
.attr('src', user.image_url)
.attr('class', 'icon icon-pre-text user-icon');
}
userLink.append('a')
.attr('class','user-info')
.text(user.display_name)
.attr('href', context.connection().userURL(user.display_name))
.attr('tabindex', -1)
.attr('target', '_blank');
prose.html(t('commit.upload_explanation_with_user', {user: userLink.html()}));
});
// Confirm Button
var saveButton = saveSection.append('button')
.attr('class', 'action col3 button');
saveButton.append('span')
.attr('class', 'label')
.text(t('commit.save'));
var warnings = body.selectAll('div.warning-section')
.data(iD.validate(changes, context.graph()))
.enter()
.append('div')
.attr('class', 'modal-section warning-section fillL2');
warnings.append('h3')
.text(t('commit.warnings'));
var warningLi = warnings.append('ul')
.attr('class', 'changeset-list')
.selectAll('li')
.data(function(d) { return d; })
.enter()
.append('li');
// only show the fix icon when an entity is given
warningLi.filter(function(d) { return d.entity; })
.append('button')
.attr('class', 'minor')
.on('click', event.fix)
.append('span')
.attr('class', 'icon warning');
warningLi.append('strong').text(function(d) {
return d.message;
});
var section = body.selectAll('div.commit-section')
.data(['modified', 'deleted', 'created'].filter(changesLength))
.enter()
.append('div')
.attr('class', 'commit-section modal-section fillL2');
section.append('h3')
.text(function(d) { return t('commit.' + d); })
.append('small')
.attr('class', 'count')
.text(changesLength);
var li = section.append('ul')
.attr('class', 'changeset-list')
.selectAll('li')
.data(function(d) { return zipSame(changes[d]); })
.enter()
.append('li');
li.append('strong')
.text(function(d) {
return d.geometry + ' ';
});
li.append('span')
.text(function(d) { return d.name; })
.attr('title', function(d) { return d.tagText; });
li.filter(function(d) { return d.count > 1; })
.append('span')
.attr('class', 'count')
.text(function(d) { return d.count; });
}
return d3.rebind(commit, event, 'on');
};
|
JavaScript
| 0 |
@@ -3048,16 +3048,178 @@
button')
+%0A .on('click.save', function() %7B%0A event.save(%7B%0A comment: commentField.node().value%0A %7D);%0A %7D)
;%0A%0A
|
970de9ffa183ad8c9dbd306aadd5c651c738bb0d
|
Please keep indentation simple: 4 spaces always
|
js/id/ui/commit.js
|
js/id/ui/commit.js
|
iD.ui.commit = function(map) {
var event = d3.dispatch('cancel', 'save', 'fix');
function zipSame(d) {
var c = [], n = -1;
for (var i = 0; i < d.length; i++) {
var desc = {
name: d[i].friendlyName(),
type: d[i].type,
count: 1,
tagText: iD.util.tagText(d[i])
};
if (c[n] &&
c[n].name == desc.name &&
c[n].tagText == desc.tagText) {
c[n].count++;
} else {
c[++n] = desc;
}
}
return c;
}
function commit(selection) {
function changesLength(d) { return changes[d].length; }
var changes = selection.datum(),
connection = changes.connection,
user = connection.user(),
header = selection.append('div').attr('class', 'header modal-section fillL'),
body = selection.append('div').attr('class', 'body');
var user_details = header
.append('div')
.attr('class', 'user-details');
var user_link = user_details
.append('div')
.append('a')
.attr('href', connection.url() + '/user/' +
user.display_name)
.attr('target', '_blank');
if (user.image_url) {
user_link
.append('img')
.attr('src', user.image_url)
.attr('class', 'user-icon');
}
user_link
.append('div')
.text(user.display_name);
header.append('h2').text('Save Changes');
header.append('p').text('The changes you upload will be visible on all maps that use OpenStreetMap data.');
// Comment Box
var comment_section = body.append('div').attr('class','modal-section fillD');
comment_section.append('textarea')
.attr('class', 'changeset-comment')
.attr('placeholder', 'Brief Description of your contributions');
// Confirm / Cancel Buttons
var buttonwrap = comment_section.append('div')
.attr('class', 'buttons cf')
.append('div')
.attr('class', 'button-wrap joined col4');
var savebutton = buttonwrap
.append('button')
.attr('class', 'save action col6 button')
.on('click.save', function() {
event.save({
comment: d3.select('textarea.changeset-comment').node().value
});
});
savebutton.append('span').attr('class','label').text('Save');
var cancelbutton = buttonwrap.append('button')
.attr('class', 'cancel col6 button')
.on('click.cancel', function() {
event.cancel();
});
cancelbutton.append('span').attr('class','icon close icon-pre-text');
cancelbutton.append('span').attr('class','label').text('Cancel');
var warnings = body.selectAll('div.warning-section')
.data(iD.validate(changes, map.history().graph()))
.enter()
.append('div').attr('class', 'modal-section warning-section fillL');
warnings.append('h3')
.text('Warnings');
var warning_li = warnings.append('ul')
.attr('class', 'changeset-list')
.selectAll('li')
.data(function(d) { return d; })
.enter()
.append('li');
warning_li.append('button')
.attr('class', 'minor')
.on('click', event.fix)
.append('span')
.attr('class', 'icon inspect');
warning_li.append('strong').text(function(d) {
return d.message;
});
var section = body.selectAll('div.commit-section')
.data(['modified', 'deleted', 'created'].filter(changesLength))
.enter()
.append('div').attr('class', 'commit-section modal-section fillL2');
section.append('h3').text(function(d) {
return d.charAt(0).toUpperCase() + d.slice(1);
})
.append('small')
.attr('class', 'count')
.text(changesLength);
var li = section.append('ul')
.attr('class','changeset-list')
.selectAll('li')
.data(function(d) { return zipSame(changes[d]); })
.enter()
.append('li');
li.append('strong').text(function(d) {
return (d.count > 1) ? d.type + 's ' : d.type + ' ';
});
li.append('span')
.text(function(d) { return d.name; })
.attr('title', function(d) { return d.tagText; });
li.filter(function(d) { return d.count > 1; })
.append('span')
.attr('class', 'count')
.text(function(d) { return d.count; });
}
return d3.rebind(commit, event, 'on');
};
|
JavaScript
| 0.999652 |
@@ -2146,32 +2146,24 @@
-
.attr('class
@@ -2191,32 +2191,24 @@
-
.append('div
@@ -2222,32 +2222,24 @@
-
-
.attr('class
@@ -2310,36 +2310,32 @@
rap%0A
-
.append('button'
@@ -2340,36 +2340,32 @@
n')%0A
-
-
.attr('class', '
@@ -2394,36 +2394,32 @@
n')%0A
-
.on('click.save'
@@ -2425,36 +2425,32 @@
', function() %7B%0A
-
@@ -2478,28 +2478,24 @@
-
comment: d3.
@@ -2556,36 +2556,28 @@
- %7D);%0A
+%7D);%0A
@@ -2572,36 +2572,32 @@
%7D);%0A
-
save
@@ -2702,36 +2702,32 @@
ppend('button')%0A
-
.att
@@ -2763,36 +2763,32 @@
n')%0A
-
.on('click.cance
@@ -2816,28 +2816,24 @@
-
event.cancel
@@ -2844,36 +2844,28 @@
-
-
%7D);%0A
-
@@ -2930,28 +2930,24 @@
pre-text');%0A
-
|
18521835638591ea234a48fb9bf2dd03f89b5ee7
|
Update textbox text to hash
|
js/imgur-viewer.js
|
js/imgur-viewer.js
|
var imgurClient = {
$: null,
base_url: null,
client_id: null,
init: function($, base_url, client_id){
this.$ = $;
this.base_url = base_url;
this.client_id = client_id;
},
accountImages: function(account, page, done, fail, always){
this._ajaxRequest("account/" + account + "/images/" + page.toString(),
{},
done, fail, always);
},
_ajaxRequest: function(endpoint, data, done, fail, always){
this.$.ajax({
url: this.base_url + endpoint,
dataType: "json",
headers: {
"Authorization": "Client-ID " + this.client_id
}
}).
done(done || function(){}).
fail(fail || function(){}).
always(always || function(){});
}
}
var imgurViewer = {
client: imgurClient,
$: null,
$images: null,
$accountText: null,
$accountSubmit: null,
$navigation: null,
init: function($, base_url, client_id,
imagesId, accountTextId, accountSubmitId, navigationId){
this.$ = $;
this.client.init($, base_url, client_id);
this.$images = this.$("#" + imagesId);
this.$accountSubmit = this.$("#" + accountSubmitId);
this.$accountText = this.$("#" + accountTextId);
this.$navigation = this.$("#" + navigationId);
if (! this.$images) {
// TODO: Notify dom Error
return;
}
this.$(window).bind("hashchange", this.onHashChange.bind(this));
this.onHashChange();
this.$accountText.bind("keypress", (function(e){
if (e.keyCode === 13) {
this.changeHash(this.$accountText.val());
return;
}
}).bind(this));
this.$accountSubmit.bind("click", (function(){
this.changeHash(this.$accountText.val());
return;
}).bind(this));
},
changeHash: function(text){
window.location.hash = text;
return;
},
onHashChange: function(){
this.$images.empty();
this.$navigation.empty();
var hash = this.$.param.fragment();
//var hash = (window.content.location.hash || "").replace(/^#/, "");
if (! hash) {
return;
}
var splittedHash = hash.split("/");
var account = splittedHash[0];
var page = parseInt(splittedHash[1]);
if (isNaN(page)) {
page = 0;
}
this.client.accountImages(account, page, (function(data, textStatus, jqXHR){
var result = data.data;
for (var i = 0; i < result.length; i++) {
this.$images.append(
$("<div />", {
class: "col-1-4 mobile-col-1-3 imgur-viewer-image"
}).append(
$("<a />", {
href: result[i].link
}).append(
$("<img />", {
src: this.makeThumbnailLink(result[i].link, "b"),
alt: result[i].id,
width: "100%"
})
)
)
);
}
if (page === 1) {
this.$navigation.append($("<a />", {
href: "#" + account
}).text("<-"));
} else if (page >= 1) {
this.$navigation.append($("<a />", {
href: "#" + account + "/" + (page - 1).toString(),
}).text("<-"));
}
this.$navigation.append($("<a />", {
href: "#" + account + "/" + (page + 1).toString(),
}).text("->"));
}).bind(this));
},
makeThumbnailLink: function(url, suffix){
return url.replace(/\/([^.]+)(\.[^\/]*)$/, "/$1" + suffix + "$2");
}
};
|
JavaScript
| 0.000001 |
@@ -2032,24 +2032,57 @@
(/%5E#/, %22%22);%0A
+ this.$accountText.val(hash);%0A
if (! ha
|
3e2e6e6d8adeafe30caa97e8baa20df25874d2ee
|
choice two 4 digit primes
|
js/presentation.js
|
js/presentation.js
|
/*global Reveal, RSA, Sieve, document*/
(function (Reveal, RSA, Sieve) {
'use strict';
var p = new RSA.Number('3');
var q = new RSA.Number('5');
var N = new RSA.Product(p, q);
var model = new Sieve.Model(20);
Reveal.addEventListener('pq', function () {
var pInput = document.getElementById('p_input');
var qInput = document.getElementById('q_input');
new RSA.EditableNumberView(pInput, p);
new RSA.EditableNumberView(qInput, q);
});
Reveal.addEventListener('sieve', function () {
var container = document.getElementById('prime-sieve');
new Sieve.ControlView(container, model);
});
Reveal.addEventListener('n', function () {
var nView = document.getElementById('n_view');
new RSA.EditableNumberView(nView, N);
});
Reveal.addEventListener('factor', function () {
var s = new RSA.Number(37);
var t = new RSA.Number(53);
var factor = new RSA.Product(s, t);
var factorView = document.getElementById('factor_view');
new RSA.NumberView(factorView, factor);
});
})(Reveal, RSA, Sieve);
|
JavaScript
| 0.999999 |
@@ -903,10 +903,14 @@
ber(
-37
+'3491'
);%0A%09
@@ -936,10 +936,14 @@
ber(
-53
+'6397'
);%0A%09
|
bb2230298742f47207fe8bb2bdfa907da6575409
|
add moleculeViewer function and actually use width/height parameters.
|
js/schemeViewer.js
|
js/schemeViewer.js
|
function schemeViewer(rxn, height, width) {
var viewerName = 'viewer' + Math.round(Math.random() * 10000);
this[viewerName] = new ChemDoodle.ViewerCanvas(viewerName, 600, 200);
debugger;
this[viewerName].specs.atoms_displayTerminalCarbonLabels_2D = true;
// sets atom labels to be colored by JMol colors, which are easy to recognize
this[viewerName].specs.atoms_useJMOLColors = true;
// enables overlap clear widths, so that some depth is introduced to overlapping bonds
this[viewerName].specs.bonds_clearOverlaps_2D = true;
// sets the shape color to improve contrast when drawing figures
this[viewerName].specs.shapes_color = 'c10000';
this[viewerName].emptyMessage = "No reaction defined";
// because we do not load any content, we need to repaint the sketcher, otherwise we would just see an empty area with the toolbar
// however, you can instead use one of the Canvas.load... functions to pre-populate the canvas with content, then you don't need to call repaint
if(rxn !== "") {
var reaction_cd = ChemDoodle.readRXN(rxn);
this[viewerName].loadContent(reaction_cd.molecules, reaction_cd.shapes);
}
}
|
JavaScript
| 0 |
@@ -33,24 +33,114 @@
t, width) %7B%0A
+ if(!height) %7B%0A height = 200;%0A %7D%0A if(!width) %7B%0A width = 600;%0A %7D%0A
var view
@@ -261,31 +261,22 @@
me,
-600, 200);%0A debugger
+width, height)
;%0A
@@ -1263,7 +1263,950 @@
%7D%0A
-%0A
%7D%0A
+%0Afunction moleculeViewer(molecule, height, width) %7B%0A if(!height) %7B%0A height = 200;%0A %7D%0A if(!width) %7B%0A width = 200;%0A %7D%0A var viewerName = 'viewer' + Math.round(Math.random() * 10000);%0A this%5BviewerName%5D = new ChemDoodle.ViewerCanvas(viewerName, width, height);%0A this%5BviewerName%5D.specs.atoms_displayTerminalCarbonLabels_2D = true;%0A // sets atom labels to be colored by JMol colors, which are easy to recognize%0A this%5BviewerName%5D.specs.atoms_useJMOLColors = true;%0A // enables overlap clear widths, so that some depth is introduced to overlapping bonds%0A this%5BviewerName%5D.specs.bonds_clearOverlaps_2D = true;%0A // sets the shape color to improve contrast when drawing figures%0A this%5BviewerName%5D.specs.shapes_color = 'c10000';%0A %0A this%5BviewerName%5D.emptyMessage = %22No molecule defined%22;%0A%0A debugger;%0A if(molecule) %7B%0A this%5BviewerName%5D.loadMolecule(ChemDoodle.readMOL(molecule));%0A %7D%0A%7D
|
6833d8012708df73a874ba348bfc5138f54cc2e5
|
fix for https
|
js/viewport.min.js
|
js/viewport.min.js
|
/*! Viewport.info 12-04-2015 */
var ViewPortInfo={init:function(){$(window).on("beforeunload",function(){$(window).scrollTop(0)}),$("body").on("resize,orientationchange",function(){ViewPortInfo.updateViewportProperties(),ViewPortInfo.generateTextBox()}),$("#copyButton").on("click",function(a){ViewPortInfo.copyToClipboard()}),this.testBrowser()},testBrowser:function(){var a="undefined"!=typeof navigator.plugins&&"object"==typeof navigator.plugins["Shockwave Flash"]||window.ActiveXObject&&new ActiveXObject("ShockwaveFlash.ShockwaveFlash")!==!1;$("#UserAgent").text(navigator.userAgent),$.getJSON("http://api.ipify.org?format=json",function(a){$("#IpAddress").text(a.ip),$("body").removeClass("initial")}).fail(function(){$("#IpAddress").text("UNAVAILABLE"),$("body").removeClass("initial")}),$("#Geolocation").addClass(""+Modernizr.geolocation).text(Modernizr.geolocation),$("#LocalStorage").addClass(""+Modernizr.localstorage).text(Modernizr.localstorage),$("#SessionStorage").addClass(""+Modernizr.sessionstorage).text(Modernizr.sessionstorage),$("#HtmlAudio").addClass(""+Modernizr.audio).text(Modernizr.audio),$("#HtmlVideo").addClass(""+Modernizr.video).text(Modernizr.video),$("#Flexbox").addClass(""+Modernizr.flexbox).text(Modernizr.flexbox),$("#TouchEvents").addClass(""+Modernizr.touch).text(Modernizr.touch),$("#CanvasSupport").addClass(""+Modernizr.canvas).text(Modernizr.canvas),$("#WebGL").addClass(""+Modernizr.webgl).text(Modernizr.webgl),$("#SVG").addClass(""+Modernizr.svg).text(Modernizr.svg),$("#Flash").addClass(""+a).text(a),$("#HistoryAPI").addClass(""+Modernizr.history).text(Modernizr.history),this.updateViewportProperties(),this.generateTextBox()},updateViewportProperties:function(){$("#ScreenDimensions").text(screen.width+"px x "+screen.height+"px"),$("#DocumentDimensions").text($(document).width()+"px x "+$(document).height()+"px"),$("#WindowDimensions").text($(window).width()+"px x "+$(window).height()+"px"),$("#BodyDimensions").text($("body").width()+"px x "+$("body").height()+"px"),Modernizr.deviceorientation?$("#WindowOrientation").addClass("true").text(window.orientation):$("#WindowOrientation").addClass("false").text("false")},copyToClipboard:function(){window.prompt("To copy, press Ctrl+C",this.generateTextBox())},generateTextBox:function(){var a="";return a+="Client report (http://viewport.info) \n",a+="============================================\n\n\n",$("table").each(function(){var b=$(this);a+="--------------------------------------------\n\n",a+=b.find("caption").text()+"\n",a+="\n--------------------------------------------\n",$(b).find("tr").each(function(){var b=$(this),c="";c=b.find("th span").text()+": "+b.find("td").text().toUpperCase()+"\n",a+=c}),a+="\n\n"}),a}};ViewPortInfo.init();
|
JavaScript
| 0 |
@@ -594,21 +594,16 @@
etJSON(%22
-http:
//api.ip
@@ -2745,8 +2745,9 @@
.init();
+%0A
|
03c6cdb5ac49606a2ead460257081e75848b6210
|
Update UDPefef
|
nga.js
|
nga.js
|
var dgram = require('dgram');
var structer = {
'v1' : {
"30" : {
'des' : 'Tìm xem vị trí hiện tại của xe trong chỉ định',
'type' : 'server',
'res' : '81',
'pro': 'udp/tcp'
},
"3D" : {
'des' : 'Tìm kiếm phiên bản tin của chiếc xe chỉ định',
'type' : 'server',
'res' : '2B',
'pro' : 'udp/tcp',
'hex' : ''
},
'28' : {
'des' : 'thu thập hình ảnh',
'type': 'server',
'res' : '85',
'pro' : 'udp/tcp',
'hex' : ''
},
'2A' : {
'des' : 'Chup anh lien tiep 10s',
'type': 'server',
'res' : '85',
'pro' : 'udp/tcp',
'hex' : ''
},
'21': {
'des' : 'Server gui xac nhan menh lenh',
'type': 'server',
'pro' : 'udp',
'hex' : ''
},
'80': {
'des': 'Du lieu vi tri',
'type': 'client',
'res' : '21',
'pro' : 'udp',
'func': function(str){
return {
'goidai' : str.slice(6,10),
'ip' : str.slice(10,18),
'vitri': str.slice(18,68),
'morong': str.slice(),
'sum': str.slice(str.length - 4, str.length - 2)
}
}
},
'B1': {
'des': 'Du lieu nhay',
'type': 'client',
'res': '21',
'pro': 'udp',
'hex' : '',
'func': function(str){
return {
'goidai' : str.slice(6,10),
'ip' : str.slice(10,18),
'vitri': str.slice(18,68),
'morong': str.slice(),
'sum': str.slice(str.length - 4, str.length - 2)
}
}
},
'E0': {
'des': 'Nguoi dang ky lai xe thoat',
'type': 'client',
'res' : '21',
'pro' : 'udp',
'hex' : ''
}
}
};
var client = dgram.createSocket('udp4', function(data){
var data = data.toString('hex');
console.log('data',data);
var menhlenh = data.slice(4,6);
console.log("Menh lenh:", menhlenh);
var obj = structer.v1[menhlenh].func(data);
console.log("Du lieu cuoi:", obj);
console.log(data);
console.log("----------------------------------------------");
});
client.on('message', function(data, ip) {
console.log(ip.port, ip.address);
/* client.send(logdata, 0, logdata.length, ip.port, ip.address, function(err) {
if(!err) {
//console.log('send success');
}else {
//console.log(err);
}
});*/
//console.log(util.inspect(ip, {depth: null}));
})
client.bind(3333);
|
JavaScript
| 0 |
@@ -2282,24 +2282,25 @@
ata',data);%0A
+%0A
var menh
@@ -2362,24 +2362,53 @@
menhlenh);%0A%0A
+ if(menhlenh === 80)%7B%0A
var obj
@@ -2439,32 +2439,36 @@
func(data);%0A
+
+
console.log(%22Du
@@ -2486,16 +2486,23 @@
, obj);%0A
+ %7D%0A%0A
%0A con
|
1cfa902e313e848732976ac6e538f3f72c135d90
|
refactor scrollspy refresh method
|
js/scrollspy.js
|
js/scrollspy.js
|
/* ========================================================================
* Bootstrap: scrollspy.js v3.1.1
* http://getbootstrap.com/javascript/#scrollspy
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// SCROLLSPY CLASS DEFINITION
// ==========================
function ScrollSpy(element, options) {
var process = $.proxy(this.process, this)
this.$body = $('body')
this.$scrollElement = $(element).is('body') ? $(window) : $(element)
this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
this.selector = (this.options.target || '') + ' .nav li > a'
this.offsets = []
this.targets = []
this.activeTarget = null
this.$scrollElement.on('scroll.bs.scrollspy', process)
this.refresh()
this.process()
}
ScrollSpy.VERSION = '3.1.1'
ScrollSpy.DEFAULTS = {
offset: 10
}
ScrollSpy.prototype.refresh = function () {
var offsetMethod = this.$scrollElement[0] == window ? 'offset' : 'position'
this.offsets = []
this.targets = []
var self = this
this.$body
.find(this.selector)
.filter(':visible')
.map(function () {
var $el = $(this)
var href = $el.data('target') || $el.attr('href')
var $href = /^#./.test(href) && $(href)
return ($href
&& $href.length
&& $href.is(':visible')
&& [[$href[offsetMethod]().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href]]) || null
})
.sort(function (a, b) { return a[0] - b[0] })
.each(function () {
self.offsets.push(this[0])
self.targets.push(this[1])
})
}
ScrollSpy.prototype.process = function () {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
var scrollHeight = this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height()
var offsets = this.offsets
var targets = this.targets
var activeTarget = this.activeTarget
var i
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets[targets.length - 1]) && this.activate(i)
}
if (activeTarget && scrollTop <= offsets[0]) {
return activeTarget != (i = targets[0]) && this.activate(i)
}
for (i = offsets.length; i--;) {
activeTarget != targets[i]
&& scrollTop >= offsets[i]
&& (!offsets[i + 1] || scrollTop <= offsets[i + 1])
&& this.activate(targets[i])
}
}
ScrollSpy.prototype.activate = function (target) {
this.activeTarget = target
$(this.selector)
.parentsUntil(this.options.target, '.active')
.removeClass('active')
var selector = this.selector +
'[data-target="' + target + '"],' +
this.selector + '[href="' + target + '"]'
var active = $(selector)
.parents('li')
.addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active
.closest('li.dropdown')
.addClass('active')
}
active.trigger('activate.bs.scrollspy')
}
// SCROLLSPY PLUGIN DEFINITION
// ===========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.scrollspy')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.scrollspy
$.fn.scrollspy = Plugin
$.fn.scrollspy.Constructor = ScrollSpy
// SCROLLSPY NO CONFLICT
// =====================
$.fn.scrollspy.noConflict = function () {
$.fn.scrollspy = old
return this
}
// SCROLLSPY DATA-API
// ==================
$(window).on('load.bs.scrollspy.data-api', function () {
$('[data-spy="scroll"]').each(function () {
var $spy = $(this)
Plugin.call($spy, $spy.data())
})
})
}(jQuery);
|
JavaScript
| 0 |
@@ -1201,64 +1201,180 @@
d =
-this.$scrollElement%5B0%5D == window ? 'offset' : 'position'
+'offset'%0A var offsetBase = 0%0A%0A if (!$.isWindow(this.$scrollElement%5B0%5D)) %7B%0A offsetMethod = 'position'%0A offsetBase = this.$scrollElement.scrollTop()%0A %7D
%0A%0A
@@ -1799,84 +1799,18 @@
p +
-(!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop())
+offsetBase
, hr
|
30907490166ebc07f5eefbb6da7ef2dfee36aba4
|
Update scrollspy.js
|
js/scrollspy.js
|
js/scrollspy.js
|
$(document).ready(function(){
// Add smooth scrolling to all links in navbar + footer link
$(".navbar a, footer a[href='#myPage']").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (900) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 900, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
$(window).scroll(function() {
$(".slideanim").each(function(){
var pos = $(this).offset().top;
var winTop = $(window).scrollTop();
if (pos < winTop + 600) {
$(this).addClass("slide");
}
});
});
})
// Problem: user when clicking on image goes to dead end
// Solution: Create overlay with the large image
var $XyzSummon = $('<div id="overlay"></div>');
var $image = $('<img class="img-responsice">');
var $caption = $("<p></p>");
$XyzSummon.append($image);
// Add overlay
$("body").append($XyzSummon);
// An image
// A caption
$XyzSummon.append($caption);
// capture click event on a to an image
$(".imageGallery a").click(function(event){
event.preventDefault();
var imageLocation = $(this).attr("href");
// Update overlay with the image linked in the link
$image.attr("src", imageLocation);
// Show the overlay
$XyzSummon.show();
// Get child's alt atribute and set caption
var captionText = $(this).children("img").attr("alt");
$caption.text(captionText);
});
// When overlay is clicked
$XyzSummon.click(function(){
// Hide the overlay
$XyzSummon.hide();
});
|
JavaScript
| 0.000001 |
@@ -1263,17 +1263,17 @@
responsi
-c
+v
e%22%3E');%0Av
|
7081838f9ea2b336919ea4bdecce3e876b61b6fa
|
Update updatetab.js
|
js/updatetab.js
|
js/updatetab.js
|
function updatetab(url, pane) {
// http://docs.mathjax.org/en/latest/tex.html
// From http://stackoverflow.com/a/651735
var ext = url.split('.').pop().toLowerCase();
var ismd = true;
if ($.inArray(ext, ['md', 'markdown', 'mdown', 'mkdn', 'mkd', 'mdtxt', 'mdtext']) == -1) {
ismd = false;
}
$.get(url, function(data) {
if (ismd) {
data= data.replace(/(?<=\\[)(\_)(?=\\])/gi,'\\\_'); // Handle underscore by \_
// only change if _ is within math symbols http://stackoverflow.com/a/1454936
$('#my-pagination-content').html(marked(data));
MathJax.Hub.Queue(["Typeset", MathJax.Hub, "my-pagination-content"]);
} else {
$('#my-pagination-content').html(data);
MathJax.Hub.Queue(["Typeset", MathJax.Hub, "my-pagination-content"]);
}
console.log('makerbutton');
makerbutton(); //Update buttons.
pane.tab('show');
});
}
|
JavaScript
| 0.000001 |
@@ -549,16 +549,45 @@
1454936%0A
+ console.log(data);%0A
|
2b1bb3fa45dda2c71287da0cb10b6eaf96e24d50
|
Update updatetab.js
|
js/updatetab.js
|
js/updatetab.js
|
var Latexdown={
delay: 150, // delay after keystroke before updating
previewid: null,
eventtapid: null,
preview: null, // filled in by Init below
timeout: null, // store setTimout id
mjRunning: false, // true when MathJax is processing
oldText: null, // used to check if an update is needed
Init: function (pid,eid) {
this.previewid=pid;
this.eventtabid=eid;
this.preview=document.getElementById(this.previewid);
},
Update: function () {
if (this.timeout) {clearTimeout(this.timeout)}
this.timeout = setTimeout(this.callback,this.delay);
},
PreviewHtml: function () {
this.mjRunning = false;
},
PreviewMark: function () {
this.mjRunning = false;
text = this.preview.innerHTML;
text = text.replace(/^>/mg, '>');
this.preview.innerHTML = marked (text);
},
IsMarkdown: function(url){
ext = url.split('.').pop().toLowerCase();
if ($.inArray(ext, ['md', 'markdown', 'mdown', 'mkdn', 'mkd', 'mdtxt', 'mdtext']) == -1) {
return false;
}
else{
return true;
}
},
UpdateTab: function(url , pane){
var _this=this;
$.get(url, function(data) {
//this.timeout = null;
if (_this.mjRunning) return;
var text = data;
if (text === _this.oldtext) return;
_this.preview.innerHTML = _this.oldtext = text;
_this.mjRunning = true;
console.log(url);
if(_this.IsMarkdown(url) || true){
MathJax.Hub.Queue(["Typeset",MathJax.Hub,_this.preview],["PreviewMark",_this]);
}
else{
MathJax.Hub.Queue(["Typeset",MathJax.Hub,_this.preview],["PreviewHTML",_this]);
}
makerbutton();
pane.tab('show');
});
}
};
/*
Latexdown.callback=MathJax.Callback(["UpdateTab",Latexdown]);
Latexdown.callback.autoReset = true;
*/
|
JavaScript
| 0.000001 |
@@ -1463,14 +1463,15 @@
rl)
-%7C%7C tru
+&& fals
e)%7B%0A
|
bf8734a775396d1d9d5542efcb55de27aedb4d0f
|
Update updatetab.js
|
js/updatetab.js
|
js/updatetab.js
|
var Latexdown={
delay: 150, // delay after keystroke before updating
previewid: null,
eventtapid: null,
preview: null, // filled in by Init below
timeout: null, // store setTimout id
mjRunning: false, // true when MathJax is processing
oldText: null, // used to check if an update is needed
Init: function (pid,eid) {
this.previewid=pid;
this.eventtabid=eid;
this.preview=document.getElementById(this.previewid);
var id='#'+this.preivewid+' a .active';
var initial=$(id);
console.log("initial:"+initial);
this.UpdateTab(initial.attr("data-url"),initial);
},
Update: function () {
if (this.timeout) {clearTimeout(this.timeout)}
this.timeout = setTimeout(this.callback,this.delay);
},
PreviewHtml: function () {
this.mjRunning = false;
},
PreviewMark: function () {
this.mjRunning = false;
text = this.preview.innerHTML;
text = text.replace(/^>/mg, '>');
this.preview.innerHTML = marked (text);
},
IsMarkdown: function(url){
ext = url.split('.').pop().toLowerCase();
if ($.inArray(ext, ['md', 'markdown', 'mdown', 'mkdn', 'mkd', 'mdtxt', 'mdtext']) == -1) {
return false;
}
else{
return true;
}
},
UpdateTab: function(url , pane){
var _this=this;
$.get(url, function(data) {
//this.timeout = null;
if (_this.mjRunning) return;
var text = data;
if (text === _this.oldtext) return;
_this.preview.innerHTML = _this.oldtext = text;
_this.mjRunning = true;
console.log(url);
if(_this.IsMarkdown(url)){
MathJax.Hub.Queue(["Typeset",MathJax.Hub,_this.preview],["PreviewMark",_this]);
}
else{
MathJax.Hub.Queue(["Typeset",MathJax.Hub,_this.preview],["PreviewHTML",_this]);
}
makerbutton();
pane.tab('show');
});
}
};
Latexdown.callback=MathJax.Callback(["UpdateTab",Latexdown]);
Latexdown.callback.autoReset = true;
|
JavaScript
| 0.000001 |
@@ -546,19 +546,8 @@
log(
-%22initial:%22+
init
|
35965e55b589f3bea84f5fc397d75d5794ee842d
|
Add on error method to exec node... (should have been there before :-)
|
nodes/core/core/75-exec.js
|
nodes/core/core/75-exec.js
|
/**
* Copyright 2013 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
module.exports = function(RED) {
"use strict";
var spawn = require('child_process').spawn;
var exec = require('child_process').exec;
function ExecNode(n) {
RED.nodes.createNode(this,n);
this.cmd = n.command.trim();
this.append = n.append.trim() || "";
this.useSpawn = n.useSpawn;
var node = this;
this.on("input", function(msg) {
if (msg != null) {
node.status({fill:"blue",shape:"dot"});
if (this.useSpawn === true) {
// make the extra args into an array
// then prepend with the msg.payload
if (typeof(msg.payload !== "string")) { msg.payload = msg.payload.toString(); }
var arg = [];
if (node.append.length > 0) { arg = node.append.split(","); }
if (msg.payload.trim() !== "") { arg.unshift(msg.payload); }
node.log(node.cmd+" ["+arg+"]");
if (node.cmd.indexOf(" ") == -1) {
var ex = spawn(node.cmd,arg);
ex.stdout.on('data', function (data) {
//console.log('[exec] stdout: ' + data);
msg.payload = data.toString();
node.send([msg,null,null]);
});
ex.stderr.on('data', function (data) {
//console.log('[exec] stderr: ' + data);
msg.payload = data.toString();
node.send([null,msg,null]);
});
ex.on('close', function (code) {
//console.log('[exec] result: ' + code);
msg.payload = code;
node.status({});
node.send([null,null,msg]);
});
}
else { node.error("Spawn command must be just the command - no spaces or extra parameters"); }
}
else {
var cl = node.cmd+" "+msg.payload+" "+node.append;
node.log(cl);
var child = exec(cl, function (error, stdout, stderr) {
msg.payload = stdout;
var msg2 = {payload:stderr};
var msg3 = null;
//console.log('[exec] stdout: ' + stdout);
//console.log('[exec] stderr: ' + stderr);
if (error !== null) {
msg3 = {payload:error};
//console.log('[exec] error: ' + error);
}
node.status({});
node.send([msg,msg2,msg3]);
});
}
}
});
}
RED.nodes.registerType("exec",ExecNode);
}
|
JavaScript
| 0 |
@@ -2532,32 +2532,162 @@
%7D);%0A
+ ex.on('error', function (code) %7B%0A node.warn(code);%0A %7D);%0A
|
21dda652e66136db024ebf86e1c80ace13536552
|
fix line comment bug.
|
s4l.js
|
s4l.js
|
/*
* Sort the CSS properties for LESS
* 2013/12/19
*/
var properties = require("./properties.js");
module.exports = (function(){
var s4l = function(str){
return restore(blocks(str));
};
var styles = s4l.styles = [];
var stack = s4l.stack = function(str, semicolon){
styles.push(str);
return "<" + (styles.length - 1) + ">" + (semicolon ? ";" : "");
};
var rblock = /\{([^\}]+)\}/;
var findBlock = s4l.findBlock = function(str){
return str.replace(rblock, function(a, b){
if(~b.indexOf("{")){
return "{" + findBlock(b + "}");
}
// @{hoge}
else if(/\S/.test(b) && !~b.indexOf(":")){
return stack(b);
}
else{
return stack(sort(b), true);
}
});
};
var blocks = s4l.blocks = function(str){
var re = findBlock(str);
if(rblock.test(re)){
return s4l(re);
}
return re;
};
var rstyle = /<(\d+)>;?/g;
var restore = s4l.restore = function(str){
var re = str.replace(rstyle, function(a, i){
return "{" + styles[i] + "}";
});
if(rstyle.test(re)){
return restore(re);
}
return re;
};
var sort = s4l.sort = function(str){
var line = str.split(";");
var count = 1;
var len = properties.length;
var end = line.pop();
var getPos = function(prop){
var index = properties.indexOf(prop);
return ~index ? index : (len + count++);
};
return line.map(function(style){
var pos;
var prop = style.split(":")[0].trim();
// Variable
if(prop[0] === "@"){
pos = -1;
}
// IE7
else if(prop[0] === "*"){
pos = getPos(prop.slice(1)) + 0.1;
}
else {
pos = getPos(prop);
}
return [
style, pos
];
})
.sort(function(a, b){
return a[1] > b[1] ? 1 : -1;
}).map(function(a){
return a[0] + ";";
}).join("") + end;
};
return s4l;
})();
|
JavaScript
| 0 |
@@ -47,10 +47,10 @@
/12/
+2
1
-9
%0A */
@@ -708,16 +708,20 @@
n stack(
+s4l.
sort(b),
@@ -1145,19 +1145,8 @@
;%0A%0A
- var sort =
s4l
@@ -1408,16 +1408,394 @@
%0A %7D;%0A
+%0A /* %22prop: value; // hoge%22 */%0A var rlc = /%5C/%5C/(.*)%5Cn.+:/;%0A%0A // Line Comment Only%0A var rlcOnly = /%5Cn%5C/%5C/(.*)%5Cn.+:/;%0A%0A for(var i = 0,l = line.length;i %3C l;i++)%7B%0A if(!rlcOnly.test(line%5Bi%5D) && rlc.test(line%5Bi%5D))%7B%0A var sp = line%5Bi%5D.split(%22%5Cn%22);%0A line%5Bi-1%5D += sp.shift();%0A line%5Bi%5D = %22%5Cn%22 + sp.join(%22%5Cn%22);%0A %7D%0A line%5Bi%5D += %22;%22;%0A %7D%0A%0A
retu
@@ -1848,19 +1848,17 @@
var
-pro
+s
p = styl
@@ -1873,37 +1873,99 @@
%22:%22)
-%5B0%5D.trim();%0A // Variable
+;%0A var prop = sp%5B0%5D.trim();%0A var value = sp%5B1%5D;%0A // Variable (@prop: value;)
%0A
@@ -2026,16 +2026,32 @@
// IE7
+ (*prop: value;)
%0A e
@@ -2118,32 +2118,62 @@
+ 0.1;%0A %7D%0A
+ // Style (prop: value;)%0A
else %7B%0A
@@ -2219,25 +2219,16 @@
return %5B
-%0A
style, p
@@ -2229,23 +2229,16 @@
yle, pos
-%0A
%5D;%0A %7D
@@ -2345,14 +2345,8 @@
a%5B0%5D
- + %22;%22
;%0A
|
14c82b3af12a8ab3851182492df39e65df7b4bc1
|
fix sao error
|
sao.js
|
sao.js
|
module.exports = {
template: 'handlebars',
templateOptions: {
helpers: {
if_eq: function(a, b, opts) {
return a === b
? opts.fn(this)
: opts.inverse(this);
}
}
},
prompts: {
name: {
message: 'Project name',
role: 'folder:name'
},
description: {
message: 'Project description',
default: 'A React project'
},
author: {
message: 'Author',
role: 'git:name'
},
router: {
message: 'Install react-router?',
type: 'confirm'
},
routerVersion: {
when: 'router',
message: 'Pick the version of router',
type: 'list',
choices: [
{
name: 'v4',
value: 'v4',
short: 'v4'
},
{
name: 'v3',
value: 'v3',
short: 'v3'
}
]
},
history: {
when: 'router',
type: 'list',
message: 'Pick the type of router',
choices: [
{
name: 'html5 history api',
value: function(obj) {
return obj.data.root.routerVersion === 'v3'
? 'browserHistory' : 'BrowserRouter';
},
short: 'html5'
},
{
name: 'hash router',
value: function(obj) {
return obj.data.root.routerVersion === 'v3'
? 'hashHistory' : 'HashRouter';
},
short: 'hash'
}
]
},
redux: {
type: 'confirm',
message: 'Install redux?'
},
devtools: {
type: 'list',
when: 'redux',
message: 'Pick the type of DevTools',
choices: [
{
name: 'Browser Extension',
value: 'browser',
short: 'Browser'
},
{
name: 'Customized DevTools',
value: 'normal',
short: 'Normal'
}
]
},
lint: {
type: 'confirm',
message: 'Use ESLint to lint your code?',
short: 'Standard'
}
},
filters: {
'src/routes/**/*': 'router',
'src/views/**/*': 'router',
'src/redux/**/*': 'redux',
'src/components/Counter.jsx': 'redux',
'src/components/Counter.css': 'redux',
'src/components/DevTools/**/*': 'devtools === "normal"',
'.eslintrc.js': 'lint',
'.eslintignore': 'lint'
},
post({isNewFolder, folderName, chalk, install, init, answers}) {
console.log(chalk.cyan('\n To get started:\n'));
if (isNewFolder) {
console.log(` cd ${folderName}`);
}
console.log(' npm install');
console.log(' npm run dev');
if (answers.devtools === 'browser') {
console.log(chalk.cyan('\n To make redux-devtools-extension work:\n'));
console.log(' https://github.com/zalmoxisus/redux-devtools-extension');
}
console.log(chalk.cyan('\n To build for production:\n'));
console.log(' npm run build');
console.log(chalk.cyan('\n Documentation:\n'));
console.log(' https://github.com/SidKwok/react-webpack-boilerplate\n');
}
};
|
JavaScript
| 0.000001 |
@@ -2913,16 +2913,25 @@
**/*': '
+redux &&
devtools
|
5eba0823aee7f1a96c278f49a553b61fe4ecbe2d
|
Update seed
|
migrations/seed.js
|
migrations/seed.js
|
var db = require('../helpers/models');
var settings = require('./data/settings.json');
var persist = function(list, model) {
for (var r in list){
if(list.hasOwnProperty(r)){
model.Insert(list[r]);
}
}
};
db.roles.DropDB(function(){
persist(settings, db.settings);
});
|
JavaScript
| 0.000001 |
@@ -81,19 +81,24 @@
son');%0A%0A
-var
+function
persist
@@ -102,18 +102,8 @@
ist
-= function
(lis
@@ -216,34 +216,35 @@
%7D;%0A%0A
-db.roles.DropDB(function
+function updateSettings
()
+
%7B%0A
@@ -276,11 +276,55 @@
ings);%0A%7D
+%0A%0Adb.settings.DropCollection(updateSettings
);%0A
+%0A
|
b9ff523977fb123315edb4668bb2c99921a4fb26
|
improve widgetsPath resolution
|
src/scripts/widget-content.js
|
src/scripts/widget-content.js
|
/*
* The MIT License
*
* Copyright (c) 2015, Sebastian Sdorra
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
'use strict';
angular.module('adf')
.directive('adfWidgetContent', function($log, $q, $sce, $http, $templateCache, $compile, $controller, $injector, dashboard) {
function parseUrl(url){
return url.replace('{widgetsPath}', dashboard.widgetsPath);
}
function getTemplate(widget){
var deferred = $q.defer();
if ( widget.template ){
deferred.resolve(widget.template);
} else if (widget.templateUrl) {
// try to fetch template from cache
var tpl = $templateCache.get(widget.templateUrl);
if (tpl){
deferred.resolve(tpl);
} else {
var url = $sce.getTrustedResourceUrl(parseUrl(widget.templateUrl));
$http.get(url)
.success(function(response){
// put response to cache, with unmodified url as key
$templateCache.put(widget.templateUrl, response);
deferred.resolve(response);
})
.error(function(){
deferred.reject('could not load template');
});
}
}
return deferred.promise;
}
function compileWidget($scope, $element) {
var model = $scope.model;
var content = $scope.content;
// display loading template
$element.html(dashboard.loadingTemplate);
// create new scope
var templateScope = $scope.$new();
// pass config object to scope
if (!model.config) {
model.config = {};
}
templateScope.config = model.config;
// local injections
var base = {
$scope: templateScope,
widget: model,
config: model.config
};
// get resolve promises from content object
var resolvers = {};
resolvers.$tpl = getTemplate(content);
if (content.resolve) {
angular.forEach(content.resolve, function(promise, key) {
if (angular.isString(promise)) {
resolvers[key] = $injector.get(promise);
} else {
resolvers[key] = $injector.invoke(promise, promise, base);
}
});
}
// resolve all resolvers
$q.all(resolvers).then(function(locals) {
angular.extend(locals, base);
// compile & render template
var template = locals.$tpl;
$element.html(template);
if (content.controller) {
var templateCtrl = $controller(content.controller, locals);
if (content.controllerAs){
templateScope[content.controllerAs] = templateCtrl;
}
$element.children().data('$ngControllerController', templateCtrl);
}
$compile($element.contents())(templateScope);
}, function(reason) {
// handle promise rejection
var msg = 'Could not resolve all promises';
if (reason) {
msg += ': ' + reason;
}
$log.warn(msg);
$element.html(dashboard.messageTemplate.replace(/{}/g, msg));
});
}
return {
replace: true,
restrict: 'EA',
transclude: false,
scope: {
model: '=',
content: '='
},
link: function($scope, $element, $attr) {
compileWidget($scope, $element);
$scope.$on('widgetConfigChanged', function(){
compileWidget($scope, $element);
});
$scope.$on('widgetReload', function(){
compileWidget($scope, $element);
});
}
};
});
|
JavaScript
| 0.000001 |
@@ -1255,16 +1255,20 @@
teCache,
+%0A
$compil
@@ -1346,66 +1346,321 @@
-return url.replace('%7BwidgetsPath%7D', dashboard.widgetsPath)
+var parsedUrl = url;%0A if ( url.indexOf('%7BwidgetsPath%7D') %3E= 0 )%7B%0A parsedUrl = url.replace('%7BwidgetsPath%7D', dashboard.widgetsPath)%0A .replace('//', '/');%0A if (parsedUrl.indexOf('/') == 0)%7B%0A parsedUrl = parsedUrl.substring(1);%0A %7D%0A %7D%0A return parsedUrl
;%0A
|
4f5dda7cb0581ed41e19d69a7182df55778683d2
|
remove arbitrary 20 sermon limit
|
src/services/SermonService.js
|
src/services/SermonService.js
|
class SermonService {
static findById(sermons, id) {
return sermons.find((sermon) => (
sermon.key === id
))
}
static getUnpublishedSermons(sermons, selectedCongregationBucketId) {
if (selectedCongregationBucketId === 'all') {
selectedCongregationBucketId = null;
}
var filteredSermons = sermons.filter((sermon) => (sermon.published === false))
if (selectedCongregationBucketId) {
filteredSermons = filteredSermons.filter((sermon) => (
(sermon.bucketID === selectedCongregationBucketId)
))
}
// always sort by date in decsending order
return filteredSermons.sort((a, b) => (
new Date(b.date) - new Date(a.date)
)).slice(0, 20);
}
static filter(sermons, searchTerm, selectedCongregationBucketId) {
if (selectedCongregationBucketId === 'all') {
selectedCongregationBucketId = null;
}
var filteredSermons = sermons.filter((sermon) => (sermon.published === true))
if (searchTerm) {
searchTerm = searchTerm.toLowerCase()
}
if (searchTerm && selectedCongregationBucketId) {
filteredSermons = filteredSermons.filter((sermon) => (
(
(sermon.bucketID === selectedCongregationBucketId) &&
(
(sermon.comments.toLowerCase().search(searchTerm) !== -1) ||
(sermon.minister.toLowerCase().search(searchTerm) !== -1) ||
(sermon.bibleText.toLowerCase().search(searchTerm) !== -1)
)
)
))
}
// searching all sermons
else if (searchTerm) {
filteredSermons = filteredSermons.filter((sermon) => (
(
(sermon.comments.toLowerCase().search(searchTerm) !== -1) ||
(sermon.minister.toLowerCase().search(searchTerm) !== -1) ||
(sermon.bibleText.toLowerCase().search(searchTerm) !== -1)
)
))
}
else if (selectedCongregationBucketId) {
filteredSermons = filteredSermons.filter((sermon) => (
(sermon.bucketID === selectedCongregationBucketId)
))
}
// always sort by date in decsending order
return filteredSermons.sort((a, b) => (
new Date(b.date) - new Date(a.date)
)).slice(0, 20);
}
}
export default SermonService
|
JavaScript
| 0.029353 |
@@ -720,37 +720,24 @@
te)%0A ))
-.slice(0, 20)
;%0A %7D%0A%0A
@@ -2277,21 +2277,8 @@
))
-.slice(0, 20)
;%0A
|
0f11146e80080e300bd018fd18c47eec66dfbaf0
|
Add languages
|
packages/request-maxdome/src/Asset.js
|
packages/request-maxdome/src/Asset.js
|
class Asset {
constructor(
data,
{ hostname: hostname = 'maxdome.de', protocol: protocol = 'http' } = {}
) {
this.id = data.id;
const types = {
assetvideofilm: 'movie',
assetvideofilmtvseries: 'episode',
multiassettvseriesseason: 'season',
multiassetbundletvseries: 'series',
};
this.type = types[data['@class'].toLowerCase()];
this.title = data.title;
if (this.type === 'season') {
this.title += ` (Staffel ${data.number})`;
}
this.searchTitle = data.title
.replace(' (Hot From the UK)', '')
.replace(' (Hot from the US)', '');
this.hotFromTheUK = data.title.includes(' (Hot From the UK)');
this.hotFromTheUS = data.title.includes(' (Hot from the US)');
this.episodeTitle = data.episodeTitle;
this.episodeNumber = data.episodeNumber;
this.seasonNumber = data.seasonNumber || data.number;
this.description = data.descriptionShort;
if (data.coverList) {
const poster = data.coverList.filter(
cover => cover.usageType === 'poster'
)[0];
if (poster) {
this.image = poster.url;
}
}
this.areas = [];
if (data.fullMarkingList.includes('inPremiumIncluded')) {
this.areas.push('package');
}
if (
data.mediaUsageList.includes('DTO') ||
data.mediaUsageList.includes('TVOD')
) {
this.areas.push('store');
}
this.countries = data.countryList;
this.duration = data.duration;
this.fskLevels = data.fskLevelList;
this.genres = data.genreList
.filter(genre => genre.genreType === 'genre')
.map(genre => genre.value);
this.link = `${protocol}://${hostname}/${data.id}`;
this.productionYear = data.productionYear;
this.rating = data.userrating;
}
getImage(width = 204, height = 295) {
if (this.image) {
return this.image
.replace('__WIDTH__', width)
.replace('__HEIGHT__', height);
}
}
}
module.exports = Asset;
|
JavaScript
| 0.999964 |
@@ -1634,16 +1634,56 @@
value);%0A
+ this.languages = data.languageList;%0A
this
|
63da0825361e125722fb2f62dd5af3a23d437712
|
Rename pullData->labelData in models/db_label.js
|
models/db_label.js
|
models/db_label.js
|
var _ = require('underscore'),
config = require('../config'),
db = require('../lib/db'),
Promise = require('promise');
// Builds an object representation of a row in the DB `pull_labels` table
// from the data returned by GitHub's API.
function DBLabel(label) {
this.data = {
number: label.data.number,
title: label.data.title,
repo_name: config.repo.name,
};
}
DBLabel.prototype.save = function() {
var pullData = this.data;
var q_update = 'REPLACE INTO pull_labels SET ?';
return new Promise(function(resolve, reject) {
db.query(q_update, pullData, function(err, rows) {
if (err) { return reject(err); }
resolve();
});
});
};
DBLabel.prototype.delete = function() {
var pullData = this.data;
var q_update = 'DELETE FROM pull_labels WHERE ' +
'number = ? AND title = ? AND repo_name = ?';
return new Promise(function(resolve, reject) {
db.query(q_update, [pullData.number, pullData.title, pullData.repo_name],
function(err, rows) {
if (err) { return reject(err); }
resolve();
});
});
};
module.exports = DBLabel;
|
JavaScript
| 0 |
@@ -431,35 +431,36 @@
tion() %7B%0A var
-pul
+labe
lData = this.dat
@@ -590,19 +590,20 @@
update,
-pul
+labe
lData, f
@@ -753,19 +753,20 @@
%0A var
-pul
+labe
lData =
@@ -956,19 +956,20 @@
pdate, %5B
-pul
+labe
lData.nu
@@ -974,19 +974,20 @@
number,
-pul
+labe
lData.ti
@@ -991,19 +991,20 @@
.title,
-pul
+labe
lData.re
|
dc6836b028d87e91427533e668ae7b8e9e2f0daa
|
Update table-report.js (#172)
|
src/bcf/report/js/table-report.js
|
src/bcf/report/js/table-report.js
|
// customize column_values to display the attributes of your choice to the sidebar
let column_values = ['id', 'position', 'reference', 'alternatives', 'type'];
// customize which parts of the annotation field to display at the sidebar
let ann_values = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27]
$(document).ready(function () {
$('html').on('click', '.variant-row', function () {
$(this).siblings().children().removeClass("active-row");
$(this).children().addClass("active-row");
let vis_len = $(this).data('vislen');
for (let t = 1; t <= vis_len; t++) {
$(this).data('index');
let compressed_specs = plots[0][$(this).data('idx') + "_" + t.toString()];
let decompressed = LZString.decompressFromUTF16(compressed_specs);
let unpacker = new jsonm.Unpacker();
unpacker.setMaxDictSize(100000);
$(this).data('vis' + t.toString(), unpacker.unpack(JSON.parse(decompressed)));
}
let d = $(this).data('description')
d = d.replace(/, /g,"\",\"");
d = d.replace("[","[\"");
d = d.replace("]","\"]")
let description = JSON.parse(d);
for (let t = 1; t <= vis_len; t++) {
let specs = $(this).data('vis' + t.toString());
specs.data[1].values.forEach(function(a) {
if (a.row > 0 && Array.isArray(a.flags)) {
let flags = {};
a.flags.forEach(function(b) {
if (b === 1) {
flags[b] = "template having multiple segments in sequencing";
} else if (b === 2) {
flags[b] = "each segment properly aligned according to the aligner";
} else if (b === 4) {
flags[b] = "segment unmapped";
} else if (b === 8) {
flags[b] = "next segment in the template unmapped";
} else if (b === 16) {
flags[b] = "SEQ being reverse complemented";
} else if (b === 32) {
flags[b] = "SEQ of the next segment in the template being reverse complemented";
} else if (b === 64) {
flags[b] = "the first segment in the template";
} else if (b === 128) {
flags[b] = "the last segment in the template";
} else if (b === 256) {
flags[b] = "secondary alignment";
} else if (b === 512) {
flags[b] = "not passing filters, such as platform/vendor quality controls";
} else if (b === 1024) {
flags[b] = "PCR or optical duplicate";
} else if (b === 2048) {
flags[b] = "vega lite lines";
}
});
a.flags = flags;
}
});
specs.title = 'Sample: ' + $(this).data('vis-sample' + t.toString());
specs.width = $('#vis1').width() - 40;
vegaEmbed('#vis' + t.toString(), specs);
}
$('.spinner-border').hide();
$("#sidebar").empty();
$.each($(this).data(), function(i, v) {
if (i !== 'index' && !i.includes("ann") && column_values.includes(i)) {
$('#sidebar').append('<tr><th class="thead-dark">' + i + '</th><td>' + v + '</td></tr>');
}
});
$("#ann-sidebar").empty();
let ann_length = $(this).data('annlen');
let that = this;
ann_values.forEach(function (x) {
let name = description[x];
$('#ann-sidebar').append('<tr>');
$('#ann-sidebar').append('<th class="thead-dark" style="position: sticky; left:-1px;">' + name + '</th>');
for (let j = 1; j <= ann_length; j++) {
let ix = x + 1;
let field = 'ann[' + j + '][' + ix + ']';
let vl = $(that).data(field);
if (vl) {
if (name === "Existing_variation") {
let fields = vl.split('&');
let result = "";
for (var o = 0; o < fields.length; o++) {
let val = fields[o];
if (val.startsWith("rs")) {
result = result + "<a href='https://www.ncbi.nlm.nih.gov/snp/" + val + "'>" + val + "</a>";
} else if (val.startsWith("COSM")) {
let num = val.replace( /^\D+/g, '');
result = result + "<a href='https://cancer.sanger.ac.uk/cosmic/mutation/overview?id=" + num + "'>" + val + "</a>";
} else if (val.startsWith("COSN")) {
let num = val.replace( /^\D+/g, '');
result = result + "<a href='https://cancer.sanger.ac.uk/cosmic/ncv/overview?id=" + num + "'>" + val + "</a>";
} else if (val.startsWith("COSV")) {
let num = val.replace( /^\D+/g, '');
result = result + "<a href='https://cancer.sanger.ac.uk/cosmic/search?q=" + num + "'>" + val + "</a>";
} else {
result = result + val;
}
if (!(o === fields.length - 1)) {
result = result + ", ";
}
}
vl = result;
}
$('#ann-sidebar').append('<td>' + vl + '</td>');
} else {
$('#ann-sidebar').append('<td></td>');
}
}
$('#ann-sidebar').append('</tr>');
});
})
})
|
JavaScript
| 0 |
@@ -5312,77 +5312,8 @@
) %7B%0A
- let num = val.replace( /%5E%5CD+/g, '');%0A
@@ -5412,27 +5412,27 @@
earch?q=%22 +
-num
+val
+ %22'%3E%22 + va
|
23b8e178ffc15ca75db4860805d5144464d30476
|
Remove a word from 0.9.1 upgrader
|
tools/upgraders.js
|
tools/upgraders.js
|
var _ = require('underscore');
var fs = require('fs');
var path = require('path');
var project = require('./project.js');
// This file implements "upgraders" --- functions which upgrade a Meteor app to
// a new version. Each upgrader has a name (registered in upgradersByName).
//
// You can test upgraders by running "meteor run-upgrader myupgradername".
//
// Upgraders are run automatically by "meteor update". It looks at the
// .meteor/.finished-upgraders file in the app and runs every upgrader listed
// here that is not in that file; then it appends their names to that file.
// Upgraders are run in the order they are listed in upgradersByName below.
var printedNoticeHeaderThisProcess = false;
var maybePrintNoticeHeader = function () {
if (printedNoticeHeaderThisProcess)
return;
console.log();
console.log("-- Notice --");
console.log();
printedNoticeHeaderThisProcess = true;
};
var upgradersByName = {
"notices-for-0.9.0": function () {
maybePrintNoticeHeader();
if (fs.existsSync(path.join(project.project.rootDir, 'smart.json'))) {
// Meteorite apps:
console.log(
"0.9.0: Welcome to the new Meteor package system! You can now add any Meteor\n" +
" package to your app (from more than 1800 packages available on the\n" +
" Meteor Package Server) just by typing 'meteor add <packagename>', no\n" +
" Meteorite required.\n" +
"\n" +
" It looks like you have been using Meteorite with this project. To\n" +
" migrate your project automatically to the new system:\n" +
" (1) upgrade your Meteorite with 'npm install -g meteorite', then\n" +
" (2) run 'mrt migrate-app' inside the project.\n" +
" Having done this, you no longer need 'mrt' and can just use 'meteor'.\n");
} else {
// Non-Meteorite apps:
console.log(
"0.9.0: Welcome to the new Meteor package system! You can now add any Meteor\n" +
" package to your app (from more than 1800 packages available on the\n" +
" Meteor Package Server) just by typing 'meteor add <packagename>'. Check\n" +
" out the available packages by typing 'meteor search <term>' or by\n" +
" visiting atmospherejs.com.\n");
}
// How to do package-specific notices:
// if (_.has(project.project.getConstraints(), 'accounts-ui')) {
// console.log(
// "\n" +
// " Accounts UI has totally changed, yo.");
// }
console.log();
},
"notices-for-0.9.1": function () {
maybePrintNoticeHeader();
console.log(
"Meteor 0.9.1 includes many changes to the Blaze API, in preparation for 1.0.\n" +
"Many previously undocumented APIs are now public and documented. Most changes\n" +
"are backwards compatible, except that templates can no longer be named \"body\"\n" +
"or \"instance\".\n");
console.log();
}
};
exports.runUpgrader = function (upgraderName) {
// This should only be called from the hidden run-upgrader command or by
// "meteor update" with an upgrader from one of our releases, so it's OK if
// error handling is just an exception.
if (! _.has(upgradersByName, upgraderName))
throw new Error("Unknown upgrader: " + upgraderName);
upgradersByName[upgraderName]();
};
exports.upgradersToRun = function () {
var ret = [];
var finishedUpgraders = project.project.getFinishedUpgraders();
// This relies on the fact that Node guarantees object iteration ordering.
_.each(upgradersByName, function (func, name) {
if (!_.contains(finishedUpgraders, name)) {
ret.push(name);
}
});
return ret;
};
exports.allUpgraders = function () {
return _.keys(upgradersByName);
};
|
JavaScript
| 0.999999 |
@@ -2549,13 +2549,8 @@
des
-many
chan
|
ef03d25859ecc117ce653e153a40ad4a3de934ec
|
Remove unused reference
|
src/botPage/view/Dialogs/Chart.js
|
src/botPage/view/Dialogs/Chart.js
|
import {
SmartChart,
setSmartChartsPublicPath,
ChartTypes,
StudyLegend,
Views,
Timeperiod,
DrawTools,
Share,
CrosshairToggle,
ChartSize,
} from '@binary-com/smartcharts';
import React, { PureComponent } from 'react';
import { translate } from '../../../common/i18n';
import Dialog from './Dialog';
import ChartTicksService from '../../common/ChartTicksService';
import { observer as globalObserver } from '../../../common/utils/observer';
import { getLanguage } from '../../../common/lang';
import { fieldGeneratorMapping } from '../blockly/blocks/shared';
setSmartChartsPublicPath('./js/');
export const BarrierTypes = {
CALL : 'ABOVE',
PUT : 'BELOW',
EXPIRYRANGE: 'BETWEEN',
EXPIRYMISS : 'OUTSIDE',
RANGE : 'BETWEEN',
UPORDOWN : 'OUTSIDE',
ONETOUCH : 'NONE_SINGLE',
NOTOUCH : 'NONE_SINGLE',
};
const chartWidth = 600;
const chartHeight = 600;
class ChartContent extends PureComponent {
constructor(props) {
super(props);
const { api } = props;
this.settings = { language: getLanguage() };
this.ticksService = new ChartTicksService(api);
this.listeners = [];
this.chartId = 'binary-bot-chart';
this.state = {
chartType : 'mountain',
granularity: 0,
symbol : 'R_100',
barrierType: undefined,
high : undefined,
low : undefined,
};
this.shouldBarrierDisplay = false;
}
componentDidMount() {
globalObserver.register('bot.init', s => {
if (s && this.state.symbol !== s) {
this.setState({ symbol: s });
}
});
globalObserver.register('bot.contract', c => {
if (c) {
if (c.is_sold) {
this.shouldBarrierDisplay = false;
this.setState({ barrierType: null });
} else {
this.setState({ barrierType: BarrierTypes[c.contract_type] });
if (c.barrier) this.setState({ high: c.barrier });
if (c.high_barrier) this.setState({ high: c.high_barrier, low: c.low_barrier });
this.shouldBarrierDisplay = true;
}
}
});
}
getKey = request => {
const key = `${request.ticks_history}-${request.granularity}`;
return key;
};
requestAPI(data) {
return this.ticksService.api.send(data);
}
requestSubscribe(request, callback) {
const { ticks_history: symbol, style: dataType, granularity } = request;
if (dataType === 'candles') {
this.listeners[this.getKey(request)] = this.ticksService.monitor({
symbol,
granularity,
callback,
});
} else {
this.listeners[this.getKey(request)] = this.ticksService.monitor({
symbol,
callback,
});
}
}
requestForget(request) {
const { ticks_history: symbol, style: dataType, granularity } = request;
const requsestKey = this.getKey(request);
if (dataType === 'candles') {
this.ticksService.stopMonitor({
symbol,
granularity,
key: this.listeners[requsestKey],
});
} else {
this.ticksService.stopMonitor({
symbol,
key: this.listeners[requsestKey],
});
}
delete this.listeners[requsestKey];
}
renderTopWidgets = () => <span />;
renderControls = () => (
<React.Fragment>
<CrosshairToggle />
<ChartTypes enabled={true} onChange={chartType => this.setState({ chartType })} />
<Timeperiod enabled={true} onChange={granularity => this.setState({ granularity })} />
<StudyLegend />
<DrawTools />
<Views />
<Share />
<ChartSize />
</React.Fragment>
);
render() {
const barriers = this.shouldBarrierDisplay
? [
{
shade : this.state.barrierType,
shadeColor : '#0000ff',
color : '#c03',
relative : false,
draggable : false,
lineStyle : 'dotted',
hidePriceLines: false,
high : parseFloat(this.state.high),
low : parseFloat(this.state.low),
},
]
: [];
return (
<SmartChart
id={this.chartId}
chartType={this.state.chartType}
granularity={this.state.granularity}
symbol={this.state.symbol}
isMobile={true}
topWidgets={this.renderTopWidgets}
chartControlsWidgets={this.renderControls}
requestAPI={this.requestAPI.bind(this)}
requestSubscribe={this.requestSubscribe.bind(this)}
requestForget={this.requestForget.bind(this)}
barriers={barriers}
settings={this.settings}
/>
);
}
}
export default class Chart extends Dialog {
constructor(api) {
super('chart-dialog', translate('Chart'), <ChartContent api={api} />, {
width : chartWidth,
height : chartHeight,
resizable: false,
});
}
}
|
JavaScript
| 0.000001 |
@@ -527,74 +527,8 @@
ng';
-%0Aimport %7B fieldGeneratorMapping %7D from '../blockly/blocks/shared';
%0A%0Ase
|
38c631e791da795b11584c69a5e4eebb86e50bce
|
fix comment deletion detection when using html format (and ckeditor)
|
src/cm/media/js/site/text_edit.js
|
src/cm/media/js/site/text_edit.js
|
function check_save(){
var newVersion = $('#id_new_version').attr('checked') ;
var commentsKept = $('#id_keep_comments').attr('checked') ;
var new_content = $('#id_content').val() ;
var new_format = $('#id_format').val() ;
var mess = gettext( 'Should these comments be detached (i.e. kept with no scope) or removed from new version?') ;
if (commentsKept) {
var pre_edit_url = tb_conf['pre_edit_url'] ;
$.ajax({
url: pre_edit_url,
type:'POST',
dataType:"json",
data: { "new_content": new_content, "new_format": new_format},
success: function(obj){
nb_removed = obj['nb_removed'];
if (newVersion) {
if (nb_removed == 0) {
submit_edit_form();
}
else {
var message = ngettext(
'%(nb_comments)s comment applies to text that was modified.',
'%(nb_comments)s comments apply to text that was modified.',
nb_removed) ;
message += '<br />' ;
message += mess ;
message = interpolate(message,{'nb_comments':nb_removed}, true) ;
$('#remove_scope_choice_dlg').html(message) ;
$('#remove_scope_choice_dlg').dialog('open') ;
}
}
else {
if (nb_removed == 0) {
submit_edit_form();
}
else {
var message = ngettext(
'%(nb_comments)s comment applies to text that was modified.',
'%(nb_comments)s comments apply to text that was modified.',
nb_removed) ;
message += '<br />' ;
message += gettext( '(We suggest you create a new version)') ;
message += '<br />' ;
message += mess ;
message = interpolate(message,{'nb_comments':nb_removed}, true) ;
$('#remove_scope_choice_dlg').html(message) ;
$('#remove_scope_choice_dlg').dialog('open') ;
}
}
},
error: function(msg){
alert("error: " + msg);
}
});
}
else {
if (!newVersion) {
var message = gettext("You chose not to create a new version all comments will be deleted") ;
message += '<br />' ;
message += gettext( 'Do you want to continue?') ;
$('#confirm_all_removed_dlg').html(message) ;
$('#confirm_all_removed_dlg').dialog('open') ;
}
else {
submit_edit_form() ;
}
}
}
function submit_edit_form() {
needToConfirm = false;
$('#edit_form').submit();
}
$(function() {
var buttons = {};
buttons[gettext('No')] = function() {
$(this).dialog('close');
} ;
buttons[gettext('Yes')] = function() {
$(this).dialog('close');submit_edit_form();
} ;
$('#confirm_all_removed_dlg').dialog({
bgiframe: true,
autoOpen: false,
title :gettext('Warning'),
modal: true,
buttons:buttons
}) ;
var buttons0 = {};
buttons0[gettext('Detach')] = function() {$(this).dialog('close');$('#cancel_modified_scopes').val("1");submit_edit_form();} ;
buttons0[gettext('Remove')] = function() {$(this).dialog('close');$('#cancel_modified_scopes').val("0");submit_edit_form();} ;
buttons0[gettext('Cancel')] = function() {$(this).dialog('close');} ;
$('#remove_scope_choice_dlg').dialog({
bgiframe: true,
autoOpen: false,
title :gettext('Warning'),
modal: true,
buttons:buttons0
}) ;
$("#save").click(function() { check_save() ;}) ;
}) ;
|
JavaScript
| 0 |
@@ -180,32 +180,122 @@
ntent').val() ;%0A
+ %0A var o=CKEDITOR.instances%5B'id_content'%5D;%0A if (o) new_content=o.getData();%0A %0A
var new_form
|
4a044e42ac7fea7f8efea4da7e90b4b4183b0fb7
|
make restyle connector visible (true|false) work
|
src/traces/waterfall/style.js
|
src/traces/waterfall/style.js
|
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var d3 = require('d3');
var lineGroupStyle = require('../../components/drawing').lineGroupStyle;
var barStyle = require('../bar/style').style;
var barStyleOnSelect = require('../bar/style').styleOnSelect;
function style(gd, cd) {
barStyle(gd, cd);
var s = cd ? cd[0].node3 : d3.select(gd).selectAll('g.trace.bars');
s.selectAll('g.lines').each(function(d) {
var sel = d3.select(this);
var connector = d[0].trace.connector;
lineGroupStyle(sel.selectAll('path'),
connector.line.width,
connector.line.color,
connector.line.dash
);
});
}
function styleOnSelect(gd, cd) {
barStyleOnSelect(gd, cd);
}
module.exports = {
style: style,
styleOnSelect: styleOnSelect
};
|
JavaScript
| 0.000019 |
@@ -630,19 +630,24 @@
onnector
+Line
=
+(
d%5B0%5D.tra
@@ -658,18 +658,31 @@
onnector
+.line %7C%7C %7B%7D)
;%0A
+%0A
@@ -736,26 +736,25 @@
connector
-.l
+L
ine.width,%0A
@@ -769,26 +769,25 @@
connector
-.l
+L
ine.color,%0A
@@ -806,18 +806,17 @@
onnector
-.l
+L
ine.dash
|
138ff97d04d37e8a83b72c55567b4f1be4586032
|
update platform to inherit all platforms
|
src/commands/Settings/Platform.js
|
src/commands/Settings/Platform.js
|
'use strict';
const Command = require('../../models/Command.js');
const { getChannel, captures, platforms } = require('../../CommonFunctions');
class Platform extends Command {
constructor(bot) {
super(bot, 'settings.platform', 'platform', 'Change a channel\'s platform');
this.usages = [
{ description: 'Change this channel\'s platform', parameters: ['platform'] },
];
this.regex = new RegExp(`^${this.call}(?:\\s+(pc|ps4|xb1|swi))?(?:\\s+in\\s+(${captures.channel}|here))?$`, 'i');
this.requiresAuth = true;
}
async run(message, ctx) {
const platform = message.strippedContent.match(this.regex)[1];
if (!platform || !platforms.includes(platform.toLowerCase())) {
return this.sendToggleUsage(message, ctx, platforms);
}
const channelParam = message.strippedContent.match(this.regex)[2] ? message.strippedContent.match(this.regex)[2].trim().replace(/<|>|#/ig, '') : undefined;
const channel = getChannel(channelParam, message);
await this.settings.setChannelSetting(channel, 'platform', platform.toLowerCase());
this.messageManager.notifySettingsChange(message, true, true);
return this.messageManager.statuses.SUCCESS;
}
}
module.exports = Platform;
|
JavaScript
| 0.000001 |
@@ -439,22 +439,30 @@
%5Cs+(
-pc%7Cps4%7Cxb1%7Cswi
+$%7Bplatforms.join('%7C')%7D
))?(
|
37a9eb79d3c1a4ebc4b64cecbdec39e6067df4f7
|
add private channel setting
|
src/commands/Settings/Settings.js
|
src/commands/Settings/Settings.js
|
'use strict';
const Command = require('../../Command.js');
const SettingsEmbed = require('../../embeds/SettingsEmbed.js');
function createGroupedArray(arr, chunkSize) {
const groups = [];
for (let i = 0; i < arr.length; i += chunkSize) {
groups.push(arr.slice(i, i + chunkSize));
}
return groups;
}
class Settings extends Command {
constructor(bot) {
super(bot, 'settings.settings', 'settings', 'Get settings');
this.regex = new RegExp(`^${this.call}$`, 'i');
this.requiresAuth = true;
}
run(message) {
const settings = [];
const tracked = [];
let perms = [];
let finalPingIndex = 3;
this.bot.settings.getChannelLanguage(message.channel)
.then((language) => {
settings.push({ name: 'Language', value: language, inline: true });
return this.bot.settings.getChannelPlatform(message.channel);
})
.then((platform) => {
settings.push({ name: 'Platform', value: platform, inline: true });
return this.bot.settings.getChannelResponseToSettings(message.channel);
})
.then((respond) => {
settings.push({ name: 'Respond to Settings', value: respond === '1' ? 'yes' : 'no', inline: true });
return this.bot.settings.getChannelDeleteAfterResponse(message.channel);
})
.then((deleteAfterRespond) => {
settings.push({ name: 'Delete Message After Responding', value: deleteAfterRespond === '1' ? 'yes' : 'no', inline: true });
return this.bot.settings.getChannelPrefix(message.channel);
})
.then((prefix) => {
settings.push({ name: 'Command Prefix', value: prefix, inline: true });
const embed = new SettingsEmbed(this.bot, message.channel, settings, 1);
this.messageManager.embed(message, embed, false, false);
return this.bot.settings.getTrackedItems(message.channel);
})
.then((items) => {
tracked.push({
name: 'Tracked Items',
value: items.length > 0 ? `\n${items.join(' ')}` : 'No Tracked Items',
inline: true,
});
return this.bot.settings.getTrackedEventTypes(message.channel);
})
.then((types) => {
tracked.push({
name: 'Tracked Events',
value: types.length > 0 ? `\n${types.join(' ')}` : 'No Tracked Event Types',
inline: true,
});
const embed = new SettingsEmbed(this.bot, message.channel, tracked, 2);
this.messageManager.embed(message, embed, false, false);
return this.bot.settings.getPingsForGuild(message.guild);
})
.then((pingsArray) => {
if (pingsArray.length > 0) {
const pingParts = pingsArray
.filter(obj => obj.thing && obj.text)
.map(obj => `**${obj.thing}**: ${obj.text}`);
const pingSections = createGroupedArray(pingParts, 10);
pingSections.forEach((item, index) => {
const val = [{
name: 'Pings per Item',
value: item.length > 0 ? `\n\t${item.join('\n\t')}` : 'No Configured Pings',
inline: false,
}];
const embed = new SettingsEmbed(this.bot, message.channel, val, 3 + index);
finalPingIndex += 1;
this.messageManager.embed(message, embed, false, false);
});
}
})
.then(() => this.bot.settings.permissionsForGuild(message.guild))
.then((permissions) => {
perms = perms.concat(permissions);
return this.bot.settings.permissionsForChannel(message.channel);
})
.then((permissions) => {
const channelParts = permissions
.map(obj => `**${obj.command}** ${obj.isAllowed ? 'allowed' : 'denied'} for ${this.evalAppliesTo(obj.type, obj.appliesToId, message)}`);
const guildParts = perms
.map(obj => `**${obj.command}** ${obj.isAllowed ? 'allowed' : 'denied'} for ${this.evalAppliesTo(obj.type, obj.appliesToId, message)}`);
const channelSections = createGroupedArray(channelParts, 20);
const guildSections = createGroupedArray(guildParts, 20);
let finalGuildIndex = finalPingIndex;
guildSections.forEach((item, index) => {
const val = [{
name: 'Guild Permissions',
value: item.length > 0 ? `\n\t${item.join('\n\t')}` : 'No Configured Guild Permission',
inline: false,
}];
const embed = new SettingsEmbed(this.bot, message.channel, val, finalPingIndex + index);
finalGuildIndex += 1;
this.messageManager.embed(message, embed, false, false);
});
channelSections.forEach((item, index) => {
const val = [{
name: 'Channel Permissions',
value: item.length > 0 ? `\n\t${item.join('\n\t')}` : 'No Configured Channel Permission',
inline: false,
}];
const embed = new SettingsEmbed(this.bot, message.channel, val, finalGuildIndex + index);
this.messageManager.embed(message, embed, false, false);
});
})
.catch(this.logger.error);
}
evalAppliesTo(type, id, message) {
if (type === 'role') {
return message.guild.roles.get(id);
}
if (id === message.guild.id) {
return 'everyone';
}
return this.bot.client.users.get(id);
}
}
module.exports = Settings;
|
JavaScript
| 0 |
@@ -1632,32 +1632,287 @@
nline: true %7D);%0A
+ return this.bot.settings.getChannelSetting(message.channel, 'createPrivateChannel');%0A %7D)%0A .then((privChan) =%3E %7B%0A settings.push(%7B name: 'Allow creation of private channels', value: privChan === '1' ? 'yes' : 'no', inline: true %7D);%0A
const em
|
f127906a92615ddc6e207905662b58aab068d87a
|
add keepAlive
|
src/util/PubChemConnection.js
|
src/util/PubChemConnection.js
|
'use strict';
const delay = require('delay');
const MongoClient = require('mongodb').MongoClient;
const config = require('./config');
function PubChemConnection() {}
PubChemConnection.prototype.close = function close() {
if (this.connection) return this.connection.close();
return undefined;
};
PubChemConnection.prototype.getMoleculesCollection = async function getDatabase() {
return (await this.getDatabase()).collection('molecules');
};
PubChemConnection.prototype.getAdminCollection = async function getDatabase() {
return (await this.getDatabase()).collection('admin');
};
PubChemConnection.prototype.getMfsCollection = async function getDatabase() {
return (await this.getDatabase()).collection('mfs');
};
PubChemConnection.prototype.getMfStatsCollection = async function getDatabase() {
return (await this.getDatabase()).collection('mfstats');
};
PubChemConnection.prototype.getDatabase = async function getDatabase() {
while (true) {
try {
await this.init();
break;
} catch (e) {
console.log('Connection to mongo failed, waiting 5s');
await delay(5000);
}
}
return this.connection.db(config.databaseName);
};
PubChemConnection.prototype.getCollection = async function getCollection(
collectionName
) {
return (await this.getDatabase()).collection(collectionName);
};
PubChemConnection.prototype.init = async function init() {
if (this.connection) return;
this.connection = await MongoClient.connect(
config.mongodbUrl,
{
autoReconnect: true,
connectTimeoutMS: 60 * 60 * 1000,
socketTimeoutMS: 60 * 60 * 1000
}
);
};
module.exports = PubChemConnection;
|
JavaScript
| 0.000002 |
@@ -1532,16 +1532,39 @@
: true,%0A
+ keepAlive: true,%0A
co
|
786ff41eb0c7e26ea396e4cde7ec3d3f9155f63f
|
Add escape listener to main activity input
|
src/components/AddActivityForm.js
|
src/components/AddActivityForm.js
|
import React, { Component, PropTypes } from 'react';
import { getDescriptionAndTags } from '../helpers';
class AddActivityForm extends Component {
createActivity(e) {
e.preventDefault();
const { description, tags } = getDescriptionAndTags(this.description.value);
const activity = {
description,
tags,
}
this.props.addActivity(activity);
this.activityForm.reset();
}
render() {
return (
<form
onSubmit={(e) => this.createActivity(e)}
ref={(input) => this.activityForm = input}
className="row row--middle stretch"
>
<input
type="text"
ref={(node) => this.description = node}
placeholder="went to the park"
className="pv- ph- col--9"
/>
<div
onClick={(e) => this.createActivity(e)}
className="pv-- ph- bg--peter-river bg--belize-hole--hover text--white transition--3-10 pointer col--3 flex align-items--center justify-content--center"
>
Add activity
</div>
</form>
);
}
}
AddActivityForm.propTypes = {
addActivity: PropTypes.func.isRequired,
};
export default AddActivityForm;
|
JavaScript
| 0.000001 |
@@ -142,16 +142,325 @@
onent %7B%0A
+%0A componentDidMount() %7B%0A this.description.addEventListener('keydown', this.escapeListener.bind(this));%0A %7D%0A%0A componentWillUnmount() %7B%0A this.description.removeEventListener('keydown', this.escapeListener)%0A %7D%0A%0A escapeListener(e) %7B%0A if (e.keyCode === 27) %7B%0A this.description.blur();%0A %7D%0A %7D%0A%0A
create
@@ -1072,16 +1072,36 @@
col--9%22%0A
+ autoFocus%0A
|
1c2b59f5c2206ffb2e8aafac6ddcb63f8c2de86c
|
Update text
|
src/components/CoRiskScoreForm.js
|
src/components/CoRiskScoreForm.js
|
import React, {Component} from 'react';
import {validateAge, validateNihssPoints, validateCopeptinLevel} from '../core/coRiskScore';
const INITIAL = Number.MAX_SAFE_INTEGER;
const checkSubmittable = (state) => {
if (state.ageFormHint || state.nihssFormHint || state.copeptinFormHint || state.age === INITIAL || state.nihss === INITIAL || state.copeptin === INITIAL) {
return false;
}
return true;
}
const getFormHint = (value, validator) => {
const validationResult = validator(value);
if (!validationResult.isValid) {
return validationResult.reason;
}
return '';
};
const updateState = (newState) => {
if (newState.age !== INITIAL) {
newState.ageFormHint = getFormHint(newState.age, validateAge);
}
if (newState.nihss !== INITIAL) {
newState.nihssFormHint = getFormHint(newState.nihss, validateNihssPoints);
}
if (newState.copeptin !== INITIAL) {
newState.copeptinFormHint = getFormHint(newState.copeptin, validateCopeptinLevel);
}
newState.isSubmittable = checkSubmittable(newState);
return newState;
}
/**
* Note that the default values are undefined
*/
class CoRiskScoreForm extends Component {
constructor(props) {
super(props);
const {
age = INITIAL,
nihss = INITIAL,
copeptin = INITIAL
} = props;
const state = {
age: age,
ageFormHint: '',
nihss: nihss,
nihssFormHint: '',
copeptin: copeptin,
copeptinFormHint: '',
isSubmittable: false
};
const newState = updateState(state);
this.state = newState;
}
setLocalState(newState) {
newState = updateState(newState);
this.setState(newState);
}
handleAgeChange = (event) => {
const newState = {
...this.state,
age: event.target.value
};
this.setLocalState(newState);
}
handleNihssChange = (event) => {
const newState = {
...this.state,
nihss: event.target.value
};
this.setLocalState(newState);
}
handleCopeptinChange = (event) => {
const newState = {
...this.state,
copeptin: event.target.value
}
this.setLocalState(newState);
}
handleSubmit = (event) => {
event.preventDefault();
const state = this.state;
this
.props
.onCalculate({age: state.age, nihss: state.nihss, copeptin: state.copeptin});
}
render() {
return (
<div className="container grid-480">
<div className="">
<h1 className="app-title text-center">The CoRisk Score</h1>
<p className="info ">
The CoRisk score is the probability of an unfavorable 3-month outcome for
patients using Copeptin.
</p>
<p className="info">
Use the form below to calculate your patient's score. All fields are required.
</p>
<form
className="form-horizontal"
action=""
type="GET"
onSubmit={this.handleSubmit}>
<div className="form-group">
<div className="col-6">
<label className="form-label">Age</label>
</div>
<div className="col-6">
<input
className="form-input"
name="age"
type="number"
min="0"
max="200"
value={this.state.age === INITIAL
? ''
: this.state.age}
onChange={this
.handleAgeChange}/>
</div>
</div>
<div
className={"form-group form-input-hint fade-in " + (this.state.ageFormHint
? ''
: 'hide')}>
<div className="col-12 text-right">
{this.state.ageFormHint}
</div>
</div>
<div className="form-group">
<div className="col-6">
<label className="form-label">NIHSS points</label>
</div>
<div className="col-6">
<input
className="form-input"
name="nihss"
type="number"
min="0"
max="42"
value={this.state.nihss === INITIAL
? ''
: this.state.nihss}
onChange={this
.handleNihssChange}/>
</div>
</div>
<div
className={"form-group form-input-hint fade-in " + (this.state.nihssFormHint
? ''
: 'hide')}>
<div className="col-12 text-right">
{this.state.nihssFormHint}
</div>
</div>
<div className="form-group">
<div className="col-6">
<label className="form-label">Copeptin blood level (pmol/L)</label>
</div>
<div className="col-6">
<input
className="form-input"
name="copeptin"
value={this.state.copeptin === INITIAL
? ''
: this.state.copeptin}
onChange={this
.handleCopeptinChange}/>
</div>
</div>
<div
className={"form-group form-input-hint fade-in " + (this.state.copeptinFormHint
? ''
: 'hide')}>
<div className="col-12 text-right">
{this.state.copeptinFormHint}
</div>
</div>
<div className="form-group mt-30">
<div className="col-12 text-center">
<button
className="btn btn-primary btn-lg"
disabled={this.state.isSubmittable
? ''
: 'disabled'}>
Calculate
</button>
</div>
</div>
</form>
</div>
</div>
);
}
}
export default CoRiskScoreForm;
|
JavaScript
| 0.000001 |
@@ -2559,15 +2559,23 @@
isk
-s
+S
core
-i
+calculate
s th
|
8f379505895f14f9c2ffd0135f0d57616b046db7
|
remove autosize plugin
|
src/components/Tinymce/plugins.js
|
src/components/Tinymce/plugins.js
|
// Any plugins you want to use has to be imported
// Detail plugins list see https://www.tinymce.com/docs/plugins/
// Custom builds see https://www.tinymce.com/download/custom-builds/
const plugins = ['advlist anchor autolink autoresize autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime legacyoutput link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount']
export default plugins
|
JavaScript
| 0 |
@@ -224,19 +224,8 @@
ink
-autoresize
auto
|
10be646783800e7d0d8fcde1c0c9a7d2cba70d0e
|
fix for #591
|
src/components/forms/TextField.js
|
src/components/forms/TextField.js
|
import Input from '../../mixins/input'
export default {
name: 'text-field',
mixins: [Input],
data () {
return {
hasFocused: false,
inputHeight: null
}
},
props: {
autofocus: Boolean,
autoGrow: Boolean,
counter: Boolean,
fullWidth: Boolean,
id: String,
name: String,
maxlength: [Number, String],
max: {
type: [Number, String],
default: 25
},
min: {
type: [Number, String],
default: 0
},
multiLine: Boolean,
prefix: String,
readonly: Boolean,
rows: {
default: 5
},
singleLine: Boolean,
suffix: String,
type: {
type: String,
default: 'text'
}
},
computed: {
classes () {
return {
'input-group--text-field': true,
'input-group--single-line': this.singleLine,
'input-group--multi-line': this.multiLine,
'input-group--full-width': this.fullWidth
}
},
hasError () {
return this.errors.length !== 0 ||
!this.counterIsValid() ||
!this.validateIsValid()
},
count () {
const inputLength = (this.inputValue && this.inputValue.toString() || '').length
let min = inputLength
if (this.min !== 0 && inputLength < this.min) {
min = this.min
}
return `${min} / ${this.max}`
},
inputValue: {
get () {
return this.value
},
set (val) {
if (this.modifiers.trim) {
val = val.trim()
}
if (this.modifiers.number) {
val = Number(val)
}
if (!this.modifiers.lazy) {
this.$emit('input', val)
}
this.lazyValue = val
}
},
isDirty () {
return this.lazyValue !== null &&
typeof this.lazyValue !== 'undefined' &&
this.lazyValue.toString().length > 0
}
},
watch: {
focused () {
this.hasFocused = true
if (!this.focused) {
this.$emit('blur')
this.$emit('change', this.lazyValue)
} else {
this.$emit('focus')
}
},
value () {
this.lazyValue = this.value
this.validate()
this.multiLine && this.autoGrow && this.calculateInputHeight()
}
},
mounted () {
this.$vuetify.load(() => {
this.multiLine && this.autoGrow && this.calculateInputHeight()
this.autofocus && this.focus()
})
},
methods: {
calculateInputHeight () {
const height = this.$refs.input.scrollHeight
const minHeight = this.rows * 24
this.inputHeight = height < minHeight ? minHeight : height
},
onInput (e) {
this.inputValue = e.target.value
this.multiLine && this.autoGrow && this.calculateInputHeight()
},
blur () {
this.validate()
this.$nextTick(() => (this.focused = false))
},
focus () {
this.focused = true
this.$refs.input.focus()
},
genCounter () {
return this.$createElement('div', {
'class': {
'input-group__counter': true,
'input-group__counter--error': !this.counterIsValid()
}
}, this.count)
},
genInput () {
const tag = this.multiLine ? 'textarea' : 'input'
const data = {
style: {
'height': this.inputHeight && `${this.inputHeight}px`
},
domProps: {
disabled: this.disabled,
required: this.required,
value: this.lazyValue,
autofucus: this.autofocus
},
attrs: {
tabindex: this.tabindex,
readonly: this.readonly
},
on: {
blur: this.blur,
input: this.onInput,
focus: this.focus
},
ref: 'input'
}
if (this.placeholder) data.domProps.placeholder = this.placeholder
if (this.autocomplete) data.domProps.autocomplete = true
if (this.name) data.attrs.name = this.name
if (this.maxlength) data.attrs.maxlength = this.maxlength
if (this.id) data.domProps.id = this.id
if (this.multiLine) {
data.domProps.rows = this.rows
} else {
data.domProps.type = this.type
}
const children = [this.$createElement(tag, data)]
this.prefix && children.unshift(this.genFix('prefix'))
this.suffix && children.push(this.genFix('suffix'))
return children
},
genFix (type) {
return this.$createElement('span', {
'class': `input-group--text-field__${type}`
}, this[type])
},
counterIsValid: function counterIsValid () {
const val = (this.inputValue && this.inputValue.toString() || '')
return (!this.counter ||
(val.length >= this.min && val.length <= this.max)
)
},
validateIsValid () {
return (!this.required ||
(this.required &&
this.inputValue) ||
!this.hasFocused ||
(this.hasFocused && this.focused))
}
},
render () {
return this.genInputGroup(this.genInput(), { attrs: { tabindex: -1 }})
}
}
|
JavaScript
| 0 |
@@ -4829,25 +4829,22 @@
this.i
-nputValue
+sDirty
) %7C%7C%0A
|
ac04b878519bd9163727fca5827cf8d12b093a20
|
fix invalid paths
|
karma-docs.conf.js
|
karma-docs.conf.js
|
var sharedConfig = require('./karma-shared.conf');
module.exports = function(config) {
sharedConfig(config);
config.set({
files: [
'build/docs/components/jquery.js',
'test/jquery_remove.js',
'build/angular.js',
'build/angular-cookies.js',
'build/angular-mocks.js',
'build/angular-resource.js',
'build/angular-mobile.js',
'build/angular-sanitize.js',
'build/angular-route.js',
'build/docs/components/lib/lunr.js/lunr.js',
'build/docs/components/lib/google-code-prettify/src/prettify.js',
'build/docs/components/showdown.js',
'build/docs/components/angular-bootstrap.js',
'build/docs/components/angular-bootstrap-prettify.js',
'build/docs/js/docs.js',
'build/docs/docs-data.js',
'docs/component-spec/*.js'
],
junitReporter: {
outputFile: 'test_out/docs.xml',
suite: 'Docs'
}
});
config.sauceLabs.testName = 'AngularJS: docs';
};
|
JavaScript
| 0.000001 |
@@ -468,20 +468,8 @@
nts/
-lib/lunr.js/
lunr
@@ -507,12 +507,8 @@
nts/
-lib/
goog
@@ -527,21 +527,8 @@
tify
-/src/prettify
.js'
|
551a8a44b3bf86501a0fbed88c3d7130c51c9a4c
|
Use published date or created date for URL params
|
src/web_modules/urlHelpers.js
|
src/web_modules/urlHelpers.js
|
const Immutable = require('immutable');
const moment = require('moment');
const padStart = require('lodash/padStart');
const rpath = require('ramda/src/path');
const utils = require('../scripts/utils.js');
function assemblePath(_obj) {
if (!Array.isArray(_obj.path) || !Array.isArray(_obj.filename)) {
throw new Error('invalid object');
}
const obj = Object.assign({}, _obj);
obj.path.pop();
if (obj.path[0]) {
obj.path.unshift('');
}
obj.filename = obj.filename.filter(Boolean);
return [obj.path.join('/'), obj.filename.join('.')].join('/');
}
function getUserPath(userId) {
return userId ? `/users/${utils.getUserId(userId)}` : '';
}
function setUserInArray(_arr, userId) {
const i = _arr.indexOf('users');
let arr = _arr.slice(0);
if (i !== -1) {
arr.splice(i, 0, userId);
}
else {
if (!arr[0]) {
arr.unshift('');
}
arr = ['users', userId].concat(arr);
}
return arr;
}
function addLangToArray(_arr, lang) {
let arr = _arr;
if (lang) {
arr = arr.slice(0);
arr[arr.length] = lang;
}
return arr;
}
const encodeMaybe = utils.maybe(encodeURIComponent);
function getPath(params) {
const dateKeys = ['year', 'month', 'day'];
const keys = dateKeys.concat(['slug', 'view']);
let path = keys.map(k => {
let param;
if (params[k] && dateKeys.indexOf[k] !== -1) {
param = padStart(params[k], 2, '0');
}
else {
param = params[k];
}
return encodeMaybe(param);
});
path = path.filter(Boolean);
if (params.userId) {
path = setUserInArray(path, params.userId);
}
let filename = [path[path.length - 1]];
filename = addLangToArray(filename, params.lang);
return assemblePath({ path, filename });
}
function getArticleParams(article) {
const created = moment(rpath(['created', 'utc'], article) || new Date());
return {
year: created.year(),
month: created.month() + 1,
day: created.date(),
slug: article.slug,
};
}
function getServerUrl() {
return `${location.protocol}//${location.host}`;
}
function getNextParams({ currentParams, langParam, params, slug }) {
return Immutable.Map(currentParams || {})
.filter(utils.keyIn('userId', 'lang'))
.set('slug', slug)
.merge(params || {})
.update('lang', v => langParam || v)
.toJS();
}
module.exports = {
getArticleParams, getNextParams, getPath, getServerUrl, getUserPath,
};
|
JavaScript
| 0 |
@@ -1,12 +1,52 @@
+const find = require('ramda/src/find');%0A
const Immuta
@@ -155,49 +155,8 @@
t');
-%0Aconst rpath = require('ramda/src/path');
%0A%0Aco
@@ -1768,62 +1768,202 @@
nst
-created = moment(rpath(%5B'created', 'utc'%5D, article) %7C%7C
+dateFields = %5B'published', 'created'%5D;%0A const dateField = find(%0A Object.prototype.hasOwnProperty.bind(article),%0A dateFields%0A );%0A const date = moment(dateField ? article%5BdateField%5D.utc :
new
@@ -1993,23 +1993,20 @@
year:
-cre
+d
ate
-d
.year(),
@@ -2017,23 +2017,20 @@
month:
-cre
+d
ate
-d
.month()
@@ -2044,23 +2044,20 @@
day:
-cre
+d
ate
-d
.date(),
|
6cd520166b6472680ad4ecf26cb86fd030b2cd87
|
allow config file overrides
|
plugins/data.rfc5322_header_checks.js
|
plugins/data.rfc5322_header_checks.js
|
// Enforce RFC 5322 Section 3.6
var required_headers = ['Date', 'From'];
var singular_headers = ['Date', 'From', 'Sender', 'Reply-To', 'To', 'Cc',
'Bcc', 'Message-Id', 'In-Reply-To', 'References',
'Subject'];
exports.hook_data_post = function (next, connection) {
var header = connection.transaction.header;
// Headers that MUST be present
for (var i=0,l=required_headers.length; i < l; i++) {
if (header.get_all(required_headers[i]).length === 0)
{
return next(DENY, "Required header '" + required_headers[i] +
"' missing");
}
}
// Headers that MUST be unique if present
for (var i=0,l=singular_headers.length; i < l; i++) {
if (header.get_all(singular_headers[i]).length > 1) {
return next(DENY, "Message contains non-unique '" +
singular_headers[i] + "' header");
}
}
return next();
}
|
JavaScript
| 0.000001 |
@@ -1,8 +1,9 @@
+%0A
// Enfor
@@ -25,17 +25,16 @@
tion 3.6
-
%0Avar req
@@ -89,17 +89,16 @@
eaders =
-
%5B'Date'
@@ -252,16 +252,568 @@
bject'%5D;
+%0Avar date_future_days = 2;%0Avar date_past_days = 15;%0A%0Aexports.register = function() %7B%0A var config = this.config.get('data.headers.ini');%0A%0A if ( config.main.required ) %7B%0A required_headers = config.main.required.split(',');%0A %7D;%0A if ( config.main.singular ) %7B%0A singular_headers = config.main.singular.split(',');%0A %7D;%0A%0A if ( config.main.date_future_days ) %7B%0A date_future_days = config.main.date_future_days;%0A %7D%0A if ( config.main.date_past_days ) %7B%0A date_past_days = config.main.date_past_days;%0A %7D%0A%7D
%0A%0Aexport
@@ -1148,17 +1148,16 @@
ers%5Bi%5D +
-
%0A
@@ -1414,72 +1414,20 @@
Y, %22
-Message contains non-uniqu
+Only on
e
-'
%22 +
-%0A
sin
@@ -1448,18 +1448,68 @@
i%5D +
+%0A
%22
-'
header
+ allowed. See RFC 5322, Section 3.6
%22);%0A
|
1730984364bf5397f0c014042a0ada0f6a72c9ec
|
Move throttling management to resize utility
|
src/components/popover/Popover.js
|
src/components/popover/Popover.js
|
import React, { PureComponent } from 'react';
import { createPortal } from 'react-dom';
import PropTypes from 'prop-types';
import cx from 'classnames';
import throttle from 'lodash.throttle';
import InjectOverlay from '../overlay';
import Transition from 'react-transition-group/Transition';
import ReactResizeDetector from 'react-resize-detector';
import { events } from '../utils';
import { calculatePositions } from './positionCalculation';
import ScrollContainer from '../scrollContainer';
import theme from './theme.css';
const MAX_HEIGHT_DEFAULT = 240;
class Popover extends PureComponent {
popoverRoot = document.createElement('div');
state = { positioning: { left: 0, top: 0, arrowLeft: 0, arrowTop: 0, maxHeight: 'initial' } };
componentDidMount() {
document.body.appendChild(this.popoverRoot);
events.addEventsToWindow({ resize: this.setPlacementThrottled, scroll: this.setPlacementThrottled });
}
componentWillUnmount() {
events.removeEventsFromWindow({ resize: this.setPlacementThrottled, scroll: this.setPlacementThrottled });
document.body.removeChild(this.popoverRoot);
}
componentDidUpdate(prevProps) {
if (this.props.active && prevProps !== this.props) {
this.setPlacement();
}
}
setPlacement = () => {
const { anchorEl, direction, position, offsetCorrection } = this.props;
if (this.popoverNode) {
this.setState({
positioning: calculatePositions(anchorEl, this.popoverNode, direction, position, offsetCorrection),
});
}
};
getMaxHeight = () => {
const { fullHeight } = this.props;
const { maxHeight } = this.state.positioning;
if (!fullHeight && maxHeight > MAX_HEIGHT_DEFAULT) {
return MAX_HEIGHT_DEFAULT;
}
return maxHeight;
};
setPlacementThrottled = throttle(this.setPlacement, 250);
render() {
const { left, top, arrowLeft, arrowTop } = this.state.positioning;
const {
active,
backdrop,
children,
className,
color,
footer,
header,
lockScroll,
onOverlayClick,
onEscKeyDown,
onOverlayMouseDown,
onOverlayMouseMove,
onOverlayMouseUp,
tint,
} = this.props;
if (!active) {
return null;
}
const popover = (
<Transition timeout={0} in={active} appear>
{state => {
return (
<div
className={cx(theme['wrapper'], theme[color], theme[tint], {
[theme['is-entering']]: state === 'entering',
[theme['is-entered']]: state === 'entered',
})}
>
<InjectOverlay
active={active}
backdrop={backdrop}
className={theme['overlay']}
lockScroll={lockScroll}
onClick={onOverlayClick}
onEscKeyDown={onEscKeyDown}
onMouseDown={onOverlayMouseDown}
onMouseMove={onOverlayMouseMove}
onMouseUp={onOverlayMouseUp}
/>
<div
data-teamleader-ui={'popover'}
className={cx(theme['popover'], className)}
style={{ left: `${left}px`, top: `${top}px` }}
ref={node => {
this.popoverNode = node;
}}
>
<div className={theme['arrow']} style={{ left: `${arrowLeft}px`, top: `${arrowTop}px` }} />
<ScrollContainer
className={theme['inner']}
header={header}
body={children}
footer={footer}
style={{ maxHeight: this.getMaxHeight() }}
/>
<ReactResizeDetector handleHeight handleWidth onResize={this.setPlacementThrottled} />
</div>
</div>
);
}}
</Transition>
);
return createPortal(popover, this.popoverRoot);
}
}
Popover.propTypes = {
/** The state of the Popover, when true the Popover is rendered otherwise it is not. */
active: PropTypes.bool,
/** The Popovers anchor element. */
anchorEl: PropTypes.object,
/** The background colour of the Overlay. */
backdrop: PropTypes.string,
/** The component wrapped by the Popover. */
children: PropTypes.node,
/** The class names for the wrapper to apply custom styling. */
className: PropTypes.string,
/** The background colour of the Popover. */
color: PropTypes.oneOf(['aqua', 'gold', 'mint', 'neutral', 'ruby', 'teal', 'violet']),
/** The direction in which the Popover is rendered, is overridden with the opposite direction if the Popover cannot be entirely displayed in the current direction. */
direction: PropTypes.oneOf(['north', 'south', 'east', 'west']),
/** Node to render as the footer */
footer: PropTypes.node,
/** Node to render as the header */
header: PropTypes.node,
/** If true, the Popover stretches to fit its content vertically */
fullHeight: PropTypes.bool,
/** The scroll state of the body, if true it will not be scrollable. */
lockScroll: PropTypes.bool,
/** The amount of extra translation on the Popover (has no effect if position is "middle" or "center"). */
offsetCorrection: PropTypes.number,
/** The function executed, when the "ESC" key is down. */
onEscKeyDown: PropTypes.func,
/** The function executed, when the Overlay is clicked. */
onOverlayClick: PropTypes.func,
/** The function executed, when the mouse is down on the Overlay. */
onOverlayMouseDown: PropTypes.func,
/** The function executed, when the mouse is being moved over the Overlay. */
onOverlayMouseMove: PropTypes.func,
/** The function executed, when the mouse is up on the Overlay. */
onOverlayMouseUp: PropTypes.func,
/** The position in which the Popover is rendered, is overridden with the another position if the Popover cannot be entirely displayed in the current position. */
position: PropTypes.oneOf(['start', 'center', 'end']),
/** The tint of the background colour of the Popover. */
tint: PropTypes.oneOf(['lightest', 'light', 'normal', 'dark', 'darkest']),
};
Popover.defaultProps = {
active: true,
backdrop: 'dark',
direction: 'south',
fullHeight: true,
color: 'neutral',
lockScroll: true,
offsetCorrection: 0,
position: 'center',
tint: 'lightest',
};
export default Popover;
|
JavaScript
| 0 |
@@ -812,17 +812,16 @@
rRoot);%0A
-%0A
even
@@ -846,44 +846,8 @@
ow(%7B
- resize: this.setPlacementThrottled,
scr
@@ -953,44 +953,8 @@
ow(%7B
- resize: this.setPlacementThrottled,
scr
@@ -989,17 +989,16 @@
led %7D);%0A
-%0A
docu
@@ -3660,71 +3660,256 @@
ctor
- handleHeight handleWidth onResize=%7Bthis.setPlacementThrottled%7D
+%0A handleHeight%0A handleWidth%0A onResize=%7Bthis.setPlacement%7D%0A onScroll=%7Bthis.setPlacement%7D%0A refreshMode=%22throttle%22%0A refreshRate=%7B250%7D%0A
/%3E%0A
|
7a08cdfcbacafa50a7db8c0e8939d9c16a8140ce
|
Use SCSS CI color in log
|
kaba/shelf/scss.js
|
kaba/shelf/scss.js
|
/**
* @typedef {{
* input: string,
* output: string,
* browsers: string[],
* ignoreLintFor: Array.<(string|RegExp)>,
* outputFileName: function(string, string):string,
* debug: boolean,
* watch: boolean,
* lint: boolean,
* verbose: boolean,
* }} ScssTaskConfig
*/
const Logger = require("../lib/Logger");
const ScssTask = require("./scss/ScssTask");
const _ = require("lodash");
const defaultEnvironment = require("./app-environment");
const logger = new Logger("SCSS", "blue");
/**
* Main task for Sass
*
* @param {ScssTaskConfig} config
*
* @returns {Function}
*/
module.exports = function (config = {})
{
// parse user config
config = _.assign({
// input directory (can be a glob to multiple directories)
input: "src/**/Resources/assets/scss/",
// output directory (relative to input directory)
output: "../../public/css",
// browsers to support
browsers: ["last 2 versions", "IE 10"],
// list of file path paths (string or regex). If the file path matches one of these entries, the file won't be linted
ignoreLintFor: ["/node_modules/", "/vendor/"],
// Transforms the file name before writing the out file
outputFileName: (outputFileName, inputFileName) => outputFileName,
}, config);
// build internal config
config.input = config.input.replace(/\/+$/, "") + "/";
return function (done, env)
{
// keep the user defined parameters
config = _.assign({}, defaultEnvironment, env, config);
const task = new ScssTask(config, logger);
switch (config.mode)
{
case "compile":
task.compile(done);
break;
case "lint":
task.lint(done);
break;
default:
logger.error(`Unsupported mode: ${config.mode}`);
done();
break;
}
};
};
|
JavaScript
| 0 |
@@ -527,12 +527,15 @@
%22, %22
-blue
+magenta
%22);%0A
|
2ccef43614b8d77b42c1118db00eba4f98febd45
|
update view primitive
|
src/components/primitives/View.js
|
src/components/primitives/View.js
|
// ─────────────────────────────────────────────────────────────────────────────
// import
// ─────────────────────────────────────────────────────────────────────────────
import styled from 'styled-components';
import { mediaQuerise } from '~utils';
// ─────────────────────────────────────────────────────────────────────────────
// component
// ─────────────────────────────────────────────────────────────────────────────
export const View = styled.div(
({
display,
position,
gridArea,
gridTemplate,
gridTemplateColumns,
gridTemplateRows,
gridColumn,
gridGap,
alignItems,
justifyContent,
alignSelf,
margin,
padding,
top,
right,
bottom,
left,
width,
minWidth,
minHeight,
maxWidth,
boxShadow,
borderRadius,
backgroundColor,
backgroundImage,
backgroundPosition,
backgroundRepeat,
cursor,
transition,
before,
after,
}) => ({
...mediaQuerise({
display,
position,
gridArea,
gridTemplate,
gridTemplateColumns,
gridTemplateRows,
gridColumn,
gridGap,
alignItems,
justifyContent,
alignSelf,
margin,
padding,
top,
right,
bottom,
left,
width,
minWidth,
minHeight,
maxWidth,
boxShadow,
borderRadius,
backgroundColor,
backgroundImage,
backgroundPosition,
backgroundRepeat,
cursor,
transition,
}),
'&::before': {
...before,
},
'&::after': {
...after,
},
}),
);
|
JavaScript
| 0 |
@@ -562,24 +562,42 @@
mplateRows,%0A
+ gridAutoRows,%0A
gridColu
@@ -1104,24 +1104,44 @@
mplateRows,%0A
+ gridAutoRows,%0A
gridCo
|
cf89995f9416c3f9341fe216f52da5cf81fc4958
|
Improve std{out,err} handling
|
src/components/routes/terminal.js
|
src/components/routes/terminal.js
|
import React from 'react';
import BaseWindow from '../BaseWindow';
import io from 'socket.io-client';
export default class TerminalPage extends React.Component {
constructor(props) {
super(props);
this.state = { bufferList: [], command: [] };
}
componentDidMount() {
this.socket = io.connect('http://localhost:3000');
this.socket.on('stdout', (message) => {
this.setState({bufferList: this.state.bufferList.concat([message])});
});
}
execute = (e) => {
console.log(`Executing: ${this.input.value}`);
this.setState({bufferList: this.state.bufferList.concat(["$ " + this.input.value])});
this.socket.emit('execute', { command: this.input.value });
this.input.value = "";
e.preventDefault();
}
autocomplete = (e) => {
console.log(`Autocomplete: ${e.target.value}`);
}
render() {
return (
<BaseWindow title="terminal">
<pre className="buffer">{this.state.bufferList.join("\n")}</pre>
<form className="prompt" onSubmit={this.execute}>
$ <input autoFocus type="text" ref={input => this.input = input} onChange={this.autocomplete} />
</form>
</BaseWindow>
);
}
}
|
JavaScript
| 0.000028 |
@@ -413,65 +413,351 @@
-this.setState(%7BbufferList: this.state.bufferList.concat(%5B
+if (!message %7C%7C message.length === 0) message = %22%5Cn%22;%0A this.setState(%7BbufferList: this.state.bufferList.concat(%5Bmessage%5D)%7D);%0A %7D);%0A this.socket.on('stderr', (message) =%3E %7B%0A if (!message %7C%7C message.length === 0) message = %22%5Cn%22;%0A this.setState(%7BbufferList: this.state.bufferList.concat(%5B%22ERROR: %22 +
mess
|
a455fbb809ed439c7009aae2bd221a772606c2e2
|
Fix function names
|
client/app/services/materialService.js
|
client/app/services/materialService.js
|
import 'whatwg-fetch';
import h from '../helpers.js';
let services = {
};
function getAllPieces() {
return fetch('/a/materials')
.then(h.checkStatus)
.then(h.parseJSON)
.then(data => data.materials)
.catch(error => {
console.log('Error fetching materials: ', error);
throw error;
});
}
function getPiece(id) {
return fetch('/a/materials/' + id)
.then(h.checkStatus)
.then(h.parseJSON)
.then(data => data.material)
.catch(error => {
console.log('Error fetching material: ', error);
throw error;
});
}
function getTypes() {
return fetch('/a/types/materials')
.then(h.checkStatus)
.then(h.parseJSON)
.then(data => data.types)
.catch(error => {
console.log('Error fetching material types: ', error);
throw error;
});
}
function modifyPiece(id, field, value) {
return fetch('/a/materials/' + id, {
method: 'put',
headers: h.headers,
body: JSON.stringify({
[field]: value
})
}).then(h.checkStatus)
.then(h.parseJSON)
.then(data => data.material)
.catch(error => {
console.log('Error modifying material: ', error);
throw error;
});
}
export default services;
|
JavaScript
| 0.999963 |
@@ -65,16 +65,79 @@
ces = %7B%0A
+ getAllMaterials,%0A getMaterial,%0A getTypes,%0A modifyMaterial%0A
%7D;%0A%0Afunc
@@ -147,21 +147,24 @@
n getAll
-Piece
+Material
s() %7B%0A
@@ -394,21 +394,24 @@
tion get
-Piece
+Material
(id) %7B%0A
@@ -903,13 +903,16 @@
dify
-Piece
+Material
(id,
|
9d971a89eb4c067cf015f33015de9b888ff14194
|
reorder components alphabetically
|
client/assets/components/components.js
|
client/assets/components/components.js
|
angular.module('lucidworksView.components', [
'lucidworksView.components.document',
'lucidworksView.components.document_file',
'lucidworksView.components.document_jira',
'lucidworksView.components.document_slack',
'lucidworksView.components.document_twitter',
'lucidworksView.components.document_web',
'lucidworksView.components.documentList',
'lucidworksView.components.facetField',
'lucidworksView.components.facetList',
'lucidworksView.components.field',
'lucidworksView.components.login',
'lucidworksView.components.paginate',
'lucidworksView.components.searchbox',
'lucidworksView.components.landingpage',
'lucidworksView.components.sort'
]);
|
JavaScript
| 0.002848 |
@@ -467,24 +467,67 @@
nts.field',%0A
+ 'lucidworksView.components.landingpage',%0A
'lucidwork
@@ -636,51 +636,8 @@
x',%0A
- 'lucidworksView.components.landingpage',%0A
'l
|
c52b76399468e11a2a718a2b774de5489161771b
|
fix bug show message
|
client/scripts/controllers/userCtrl.js
|
client/scripts/controllers/userCtrl.js
|
(function () {
var UserCtrl;
UserCtrl = (function () {
function UserCtrl($scope, $rootScope, $log, $location, UserService, RoleService, toaster) {
this.$scope = $scope;
this.$rootScope = $rootScope;
this.$log = $log;
this.$location = $location;
this.UserService = UserService;
this.RoleService = RoleService;
this.toaster = toaster;
this.$log.debug("constructing UserCtrl");
this.users = [];
this.user = this.$rootScope.user || {};
this.$rootScope.user = {};
this.pager = {};
this.roles = [];
this.selectedRoleIds = [];
$scope.gridOptions = {
data: 'pager.list',
enablePaging: true,
showFooter: true,
multiSelect: false,
totalServerItems: 'pager.count',
pagingOptions: {
pageSizes: [5, 10, 15],
pageSize: 10,
currentPage: 1
},
columnDefs: [
{
field: 'username',
displayName: '用户名'
},
{
field: 'zhName',
displayName: '中文名'
},
{
field: 'email',
displayName: '邮箱'
},
{
field: 'telephone',
displayName: '手机'
},
{
field: 'status',
displayName: '状态',
cellTemplate: "<div class='ngCellText' ng-class='col.colIndex()'><span>{{row.entity.status == 'Y' ? '启用' : '禁用'}}</span></div>"
},
{
field: "createTime",
displayName: '创建时间',
cellFilter: 'date:"yyyy-MM-dd HH:mm"'
},
{
field: "updateTime",
displayName: '创建时间',
cellFilter: 'date:"yyyy-MM-dd HH:mm"'
},
{
field: "deleted",
displayName: '有效',
cellTemplate: "<div class='ngCellText' ng-class='col.colIndex()'><span>{{row.entity.deleted ? '否' : '是'}}</span></div>"
},
{
field: null,
displayName: '操作',
cellTemplate: 'views/authority/user/operation.html'
}
]
};
}
UserCtrl.prototype.initSave = function () {
this.$log.debug("initSave()");
return this.findRoles();
};
UserCtrl.prototype.findRoles = function () {
this.$log.debug("findRoles()");
return this.RoleService.findRoles({}).then((function (_this) {
return function (data) {
_this.$log.debug("Promise returned " + data.value.list.length + " Roles");
return _this.roles = data.value.list;
};
})(this), (function (_this) {
return function (error) {
_this.$log.error("Unable to get Roles: " + error);
return _this.error = error;
};
})(this));
};
UserCtrl.prototype.findUsers = function () {
this.$log.debug("findUsers()");
this.pager.pageSize = this.$scope.gridOptions.pagingOptions.pageSize;
this.pager.pageNum = this.$scope.gridOptions.pagingOptions.currentPage;
return this.UserService.findUsers(this.pager).then((function (_this) {
return function (data) {
_this.$log.debug("Promise returned " + data.value.list.length + " Users");
return _this.$scope.pager = data.value;
};
})(this), (function (_this) {
return function (error) {
_this.$log.error("Unable to get Users: " + error);
return _this.error = error;
};
})(this));
};
UserCtrl.prototype.findCurrentUser = function () {
this.$log.debug("find Current User()");
return this.UserService.findCurrentUser().then((function (_this) {
return function (data) {
return _this.user = data.value;
};
})(this), (function (_this) {
return function (error) {
_this.$log.error("Unable to get Users: " + error);
return _this.error = error;
};
})(this));
};
UserCtrl.prototype.saveUser = function () {
this.$log.debug("saveUser()");
this.user.deleted = !this.user.deleted;
return this.UserService.saveUser(this.user).then((function (_this) {
return function (data) {
_this.$log.debug("save user successfully");
_this.toaster.pop('success', data.message.summary, data.message.detail);
return _this.$location.path("/dashboard/user");
};
})(this), (function (_this) {
return function (error) {
_this.$log.error("Unable to save user: " + error);
_this.toaster.pop('error', data.message.summary, data.message.detail);
return _this.error = error;
};
})(this));
};
UserCtrl.prototype.SettingUser = function () {
this.$log.debug("SettingUser()");
return this.UserService.saveUser(this.user).then((function (_this) {
return function (data) {
_this.$log.debug("save user successfully");
return _this.$location.path("/dashboard/home");
};
})(this), (function (_this) {
return function (error) {
_this.$log.error("Unable to save user: " + error);
return _this.error = error;
};
})(this));
};
UserCtrl.prototype.createUser = function () {
this.$log.debug("createUser()");
this.$rootScope.user.deleted = true;
return this.$location.path("/dashboard/user/save");
};
UserCtrl.prototype.updateUser = function (row) {
this.$log.debug("updateUser()");
this.user = row.entity;
this.$rootScope.user = this.user;
this.$rootScope.user.deleted = !this.user.deleted;
return this.$location.path("/dashboard/user/save");
};
UserCtrl.prototype.deleteUser = function (row) {
this.$log.debug("deleteUser()");
this.user = row.entity;
this.user.deleted = true;
return this.UserService.saveUser(this.user).then((function (_this) {
return function (data) {
_this.$log.debug("successfully delete user");
_this.toaster.pop('success', data.message.summary, data.message.detail);
return _this.findUsers();
};
})(this), (function (_this) {
return function (error) {
_this.$log.error("Unable to delete user: " + error);
_this.toaster.pop('error', error.message.summary, error.message.detail);
return _this.error = error;
};
})(this));
};
return UserCtrl;
})();
angular.module('sbAdminApp').controller('UserCtrl', UserCtrl);
}).call(this);
|
JavaScript
| 0 |
@@ -4607,20 +4607,21 @@
error',
-data
+error
.message
@@ -4622,36 +4622,37 @@
essage.summary,
-data
+error
.message.detail)
|
91f601b695c89fbab3d5655966d06ef4a4a85b9c
|
Remove duplicate App.Payment model.
|
static/global/js/app/order.js
|
static/global/js/app/order.js
|
/*
Models
*/
App.OrderItem = DS.Model.extend({
url: 'fund/orders/:order_id/items',
// Model fields
// FIXME Make the drf2 serializer use the id (or slug) to serialize DS.belongsTo.
// This will enable us to remove the project_slug field.
project: DS.belongsTo('App.Project'),
project_slug: DS.attr('string'),
amount: DS.attr('number'),
status: DS.attr('string'),
type: DS.attr('string')
});
App.CurrentOrderItem = DS.Model.extend({
url: 'fund/orders/current/items'
});
App.LatestDonation = App.OrderItem.extend({
url: 'fund/orders/latest/donations'
});
App.CurrentDonation = App.OrderItem.extend({
url: 'fund/orders/current/donations'
});
App.CurrentVoucher = App.OrderItem.extend({
url: 'fund/orders/current/vouchers'
});
App.PaymentInfo = DS.Model.extend({
url: 'fund/paymentinfo',
payment_method: DS.attr('number'),
amount: DS.attr('number'),
firstName: DS.attr('string'),
lastName: DS.attr('string'),
address: DS.attr('string'),
city: DS.attr('string'),
country: DS.attr('string'),
zipCode: DS.attr('string'),
payment_url: DS.attr('string')
});
App.Payment = DS.Model.extend({
url: 'fund/payments',
payment_method: DS.attr('number'),
amount: DS.attr('number'),
status: DS.attr('string')
});
/*
Controllers
*/
App.CurrentOrderItemListController = Em.ArrayController.extend({
updateOrderItem: function(orderItem, newAmount) {
var transaction = App.store.transaction();
transaction.add(orderItem);
orderItem.set('amount', newAmount);
transaction.commit();
},
deleteOrderItem: function(orderItem) {
var transaction = App.store.transaction();
transaction.add(orderItem);
orderItem.deleteRecord();
transaction.commit();
}
});
// TODO: Do we want to use this?
App.CurrentOrderController = Em.ObjectController.extend({
});
// TODO: Do we want to use this?
App.PaymentInfoController = Em.ObjectController.extend({
});
App.FinalOrderItemListController = Em.ArrayController.extend({
});
// TODO: Do we want to use this?
App.OrderPaymentController = Em.ObjectController.extend({
});
/*
Views
*/
App.CurrentOrderView = Em.View.extend({
templateName: 'currentorder'
});
App.CurrentOrderItemListView = Em.View.extend({
templateName: 'currentorderitem_form',
tagName: 'form'
});
App.FinalOrderItemListView = Em.View.extend({
templateName: 'final_order_item_list',
tagName: 'div'
});
App.CurrentOrderItemView = Em.View.extend({
templateName: 'currentorderitem',
tagName: 'li',
classNames: 'donation-project',
neededAfterDonation: function(){
return this.get('content.project.money_needed_natural') - this.get('content.amount');
}.property('content.amount', 'content.project.money_needed_natural'),
change: function(e){
this.get('controller').updateOrderItem(this.get('content'), Em.get(e, 'target.value'));
}
});
App.Payment = DS.Model.extend({
url: 'fund/payments',
payment_method: DS.attr('number'),
amount: DS.attr('number'),
status: DS.attr('string')
});
App.OrderPaymentView = Em.View.extend({
tagName: 'form',
templateName: 'order_payment'
});
App.PaymentInfoView = Em.View.extend({
tagName: 'form',
templateName: 'payment_info'
});
|
JavaScript
| 0 |
@@ -3001,172 +3001,8 @@
;%0A%0A%0A
-App.Payment = DS.Model.extend(%7B%0A url: 'fund/payments',%0A payment_method: DS.attr('number'),%0A amount: DS.attr('number'),%0A status: DS.attr('string')%0A%7D);%0A%0A%0A
App.
|
372235826aa724a812552e13ea45fe516d8da423
|
Update dnevnik.operator.js
|
static/js/dnevnik.operator.js
|
static/js/dnevnik.operator.js
|
$(document).ready(function() {
$("#dnevnik-login").on("submit", function(a) {
a.preventDefault();
$.ajax({
headers: {
"X-CSRFToken": Cookies.get("csrftoken")
},
url: "/login",
type: "POST",
dataType: "json",
data: $("#dnevnik-login").serialize(),
timeout: 10000,
})
.done(function(data) {
if (data !== null) {
$("#error").show();
$("#error").html(data);
} else {
location.reload();
}
})
.fail(function() {
location.reload();
});
});
$("#dnevnik-date").on("submit", function(a) {
a.preventDefault();
$.ajax({
headers: {
"X-CSRFToken": Cookies.get("csrftoken")
},
url: "/dnevnik",
type: "POST",
dataType: "json",
data: $("#dnevnik-date").serialize(),
timeout: 10000,
})
.done(function(data) {
$("#dnevnik-out").html(data);
})
.fail(function() {
location.reload();
});
});
});
|
JavaScript
| 0 |
@@ -404,33 +404,33 @@
timeout:
-1
+3
0000,%0D%0A
@@ -1186,9 +1186,9 @@
ut:
-1
+3
0000
@@ -1404,8 +1404,10 @@
;%0D%0A%0D%0A%7D);
+%0D%0A
|
d46171ba5adcddf80b6fffed9f055cd0713165d0
|
add depth to torus
|
components/famous-demos/torus/torus.js
|
components/famous-demos/torus/torus.js
|
BEST.component('famous-demos:torus', {
tree: 'torus.html',
behaviors: {
'.my-mesh-container': {
'mount-point': function() {
return [0.5, 0.5]
},
'size': function(canvasSize) {
return canvasSize;
},
'position': function() {
var xPosition = window.innerWidth * 0.25;
var yPosition = window.innerHeight * 0.85;
return [xPosition, yPosition];
},
'rotation': function($time) {
return [$time / 1000, $time / 1000, $time / 1000];
},
},
'.my-webgl-mesh': {
'geometry': function(geometry) {
return geometry;
},
'color': function(color) {
return color;
},
}
},
events: {},
states: {
color: '#3cf',
geometry: 'Torus',
canvasSize: [200, 200],
}
});
|
JavaScript
| 0 |
@@ -965,16 +965,21 @@
e: %5B200,
+ 200,
200%5D,%0A
|
77d7912cac21558cc36523d35f19b7966d139e90
|
add __UNI_ROUTER_BASE__
|
src/core/service/plugins/index.js
|
src/core/service/plugins/index.js
|
import VueRouter from 'vue-router'
import {
isPage
} from 'uni-helpers/index'
import {
createAppMixin
} from './app'
import {
createPageMixin
} from './page'
import {
lifecycleMixin
} from './lifecycle'
import {
initPolyfill
} from './polyfill'
import {
getTabBarScrollPosition
} from './app/router-guard'
function getMinId (routes) {
let minId = 0
routes.forEach(route => {
if (route.meta.id) {
minId++
}
})
return minId
}
function getHash () {
const href = window.location.href
const index = href.indexOf('#')
return index === -1 ? '' : decodeURI(href.slice(index + 1))
}
function getLocation (base = '/') {
let path = decodeURI(window.location.pathname)
if (base && path.indexOf(base) === 0) {
path = path.slice(base.length)
}
return (path || '/') + window.location.search + window.location.hash
}
/**
* Service 层 Vue 插件
* 1.init keepAliveInclude?
* 2.init router
* 3.init entryRoute
* 4.hack vue _init (app)
* 5.use router
*/
export default {
install (Vue, {
routes
} = {}) {
if (
__PLATFORM__ === 'h5' &&
Vue.config.devtools &&
typeof window !== 'undefined' &&
window.navigator.userAgent.toLowerCase().indexOf('hbuilderx') !== -1
) {
// HBuilderX 内置浏览器禁用 devtools 提示
Vue.config.devtools = false
}
initPolyfill(Vue)
lifecycleMixin(Vue)
const minId = getMinId(routes)
const router = new VueRouter({
id: minId,
mode: __uniConfig.router.mode,
base: __uniConfig.router.base,
routes,
scrollBehavior (to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else {
if (
to &&
from &&
to.meta.isTabBar &&
from.meta.isTabBar
) { // tabbar 跳 tabbar
const position = getTabBarScrollPosition(to.params.__id__)
if (position) {
return position
}
}
return {
x: 0,
y: 0
}
}
}
})
const keepAliveInclude = []
// 需跨平台,根据用户配置 hash 或 history 来调用
const entryRoute = router.match(__uniConfig.router.mode === 'history' ? getLocation(__uniConfig.router.base)
: getHash())
if (entryRoute.meta.name) {
if (entryRoute.meta.id) {
keepAliveInclude.push(entryRoute.meta.name + '-' + entryRoute.meta.id)
} else {
keepAliveInclude.push(entryRoute.meta.name + '-' + (minId + 1))
}
}
/* eslint-disable no-undef */
if (__PLATFORM__ === 'h5') {
if (entryRoute.meta && entryRoute.meta.name) {
document.body.className = 'uni-body ' + entryRoute.meta.name
if (entryRoute.meta.isNVue) {
const nvueDirKey = 'nvue-dir-' + __uniConfig.nvue['flex-direction']
document.body.setAttribute('nvue', '')
document.body.setAttribute(nvueDirKey, '')
}
}
}
Vue.mixin({
beforeCreate () {
const options = this.$options
if (options.mpType === 'app') {
options.data = function () {
return {
keepAliveInclude
}
}
const appMixin = createAppMixin(routes, entryRoute)
// mixin app hooks
Object.keys(appMixin).forEach(hook => {
options[hook] = options[hook] ? [].concat(appMixin[hook], options[hook]) : [
appMixin[hook]
]
})
// router
options.router = router
// onError
if (!Array.isArray(options.onError) || options.onError.length === 0) {
options.onError = [function (err) {
console.error(err)
}]
}
} else if (isPage(this)) {
const pageMixin = createPageMixin()
// mixin page hooks
Object.keys(pageMixin).forEach(hook => {
if (options.mpOptions) { // 小程序适配出来的 vue 组件(保证先调用小程序适配里的 created,再触发 onLoad)
options[hook] = options[hook] ? [].concat(options[hook], pageMixin[hook]) : [
pageMixin[hook]
]
} else {
options[hook] = options[hook] ? [].concat(pageMixin[hook], options[hook]) : [
pageMixin[hook]
]
}
})
} else {
if (this.$parent && this.$parent.__page__) {
this.__page__ = this.$parent.__page__
}
}
}
})
Object.defineProperty(Vue.prototype, '$page', {
get () {
return this.__page__
}
})
Vue.prototype.createSelectorQuery = function createSelectorQuery () {
return uni.createSelectorQuery().in(this)
}
Vue.prototype.createIntersectionObserver = function createIntersectionObserver (args) {
return uni.createIntersectionObserver(this, args)
}
Vue.use(VueRouter)
}
}
|
JavaScript
| 0 |
@@ -1110,16 +1110,17 @@
= %7B%7D) %7B
+%0D
%0A if
@@ -1439,24 +1439,173 @@
Mixin(Vue)%0D%0A
+%0A /* eslint-disable no-undef */%0D%0A if (typeof __UNI_ROUTER_BASE__ !== 'undefined') %7B%0D%0A __uniConfig.router.base = __UNI_ROUTER_BASE__%0D%0A %7D
%0D%0A const
@@ -2522,24 +2522,26 @@
getHash())%0D%0A
+%0D%0A
if (entr
|
f9f873b6645cc312188025f9d64513c4020a04e7
|
delete checkbox scope changign
|
src/directives/schema-validate.js
|
src/directives/schema-validate.js
|
angular.module('schemaForm').directive('schemaValidate', ['sfValidator', function(sfValidator) {
return {
restrict: 'A',
scope: false,
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
var error = null;
if (attrs.type === 'radio' || attrs.type === 'checkbox') {
scope = scope.$parent;
}
//Since we have scope false this is the same scope
//as the decorator
if (!scope.ngModelHolder) {
scope.ngModelHolder = ngModel;
}
var error = null;
var form = scope.$eval(attrs.schemaValidate);
// Validate against the schema.
var validate = function(viewValue) {
if (!form) {
form = scope.$eval(attrs.schemaValidate);
}
//Still might be undefined
if (!form) {
return viewValue;
}
// Is required is handled by ng-required?
if (angular.isDefined(attrs.ngRequired) && angular.isUndefined(viewValue)) {
return undefined;
}
// An empty field gives us the an empty string, which JSON schema
// happily accepts as a proper defined string, but an empty field
// for the user should trigger "required". So we set it to undefined.
if (viewValue === '') {
viewValue = undefined;
}
var result = sfValidator.validate(form, viewValue);
if (result.valid) {
// it is valid
scope.ngModelHolder.$setValidity('schema', true);
return viewValue;
} else {
// it is invalid, return undefined (no model update)
scope.ngModelHolder.$setValidity('schema', false);
error = result.error;
return undefined;
}
};
// Unshift onto parsers of the ng-model.
ngModel.$parsers.unshift(validate);
// Listen to an event so we can validate the input on request
scope.$on('schemaFormValidate', function() {
if (scope.ngModelHolder.$commitViewValue) {
scope.ngModelHolder.$commitViewValue(true);
} else {
scope.ngModelHolder.$setViewValue(scope.ngModelHolder.$viewValue);
}
});
//This works since we now we're inside a decorator and that this is the decorators scope.
//If $pristine and empty don't show success (even if it's valid)
scope.hasSuccess = function() {
return scope.ngModelHolder.$valid && (!scope.ngModelHolder.$pristine || !scope.ngModelHolder.$isEmpty(scope.ngModelHolder.$modelValue));
};
scope.hasError = function() {
return scope.ngModelHolder.$invalid && !scope.ngModelHolder.$pristine;
};
scope.schemaError = function() {
return error;
};
}
};
}]);
|
JavaScript
| 0.000001 |
@@ -277,37 +277,8 @@
dio'
- %7C%7C attrs.type === 'checkbox'
) %7B%0A
|
5c39648d8093e5f2cae99aaea7b5189e90f20f06
|
FIX typo
|
cordova-device.js
|
cordova-device.js
|
'use strict';
Polymer(
{
is: 'cordova-device',
properties: {
/**
* Return the version of Cordova running on the device.
*/
cordova: {
notify: true,
readOnly: true,
type: String
},
/**
* Return the device's manufacturer.
*/
manufacturer: {
notify: true,
readOnly: true,
type: String
},
/**
* Return the name of the device's model or product. (Nexus One returns
* "Passion").
*/
model: {
notify: true,
readOnly: true,
type: String
},
/**
* Return the device's operating system name. ("iOS").
*/
platform: {
notify: true,
readOnly: true,
type: String
},
/**
* Return if cordova deviceready event has been fired.
*/
ready: {
computed: '_computeReady(_ready_, _paused_)',
notify: true,
observer: '_observeReady',
type: Boolean
},
/**
* Return the device hardware serial number.
*/
serial: {
notify: true,
readOnly: true,
type: String
},
/**
* Return the device's Universally Unique Identifier.
*/
uuid: {
notify: true,
readOnly: true,
type: String
},
/**
* Return the operating system version.
*/
version: {
notify: true,
readOnly: true,
type: String
},
/**
* Return whether the device is running on a simulator.
*/
virtua: {
notify: true,
readOnly: true,
type: Boolean
}
},
_computeReady(ready, paused) {
return ready && !paused;
},
_observeReady() {
const device = window.device;
this._setCordova(device.cordova);
this._setManufacturer(device.manufacturer);
this._setModel(device.model);
this._setPlatform(device.platform);
this._setSerial(device.serial);
this._setUuid(device.uuid);
this._setVersion(device.version);
this._setVirtual(device.virtual);
}
}
);
|
JavaScript
| 0.000695 |
@@ -1619,16 +1619,17 @@
virtua
+l
: %7B%0A
@@ -1800,20 +1800,46 @@
veReady(
-) %7B%0A
+ready) %7B%0A if (ready) %7B%0A
co
@@ -1869,24 +1869,26 @@
ice;%0A%0A
+
+
this._setCor
@@ -1909,16 +1909,18 @@
rdova);%0A
+
th
@@ -1959,32 +1959,34 @@
acturer);%0A
+
+
this._setModel(d
@@ -1995,24 +1995,26 @@
ice.model);%0A
+
this._
@@ -2041,32 +2041,34 @@
latform);%0A
+
this._setSerial(
@@ -2079,24 +2079,26 @@
ce.serial);%0A
+
this._
@@ -2117,32 +2117,34 @@
ce.uuid);%0A
+
this._setVersion
@@ -2163,24 +2163,26 @@
ion);%0A
+
+
this._setVir
@@ -2193,17 +2193,19 @@
(device.
-v
+isV
irtual);
@@ -2201,24 +2201,32 @@
isVirtual);%0A
+ %7D%0A
%7D%0A %7D%0A);
|
88ebfb5e7c4bab8ef1307dedf256b35df18e2eba
|
Fix for empty selection prevents rewind.
|
d3-transrewind.js
|
d3-transrewind.js
|
/*
*
* By Spencer Hedger ([email protected])
* http://www.spencerhedger.com
* https://github.com/SpencerHedger/d3-transrewind
*/
var transRewind = function() {
function _handlestyle(scriptstep, d, rewinding) {
var step = scriptstep;
d = d.style(step.property, function(d, i) {
if(!rewinding) {
step._origval = d3.select(this).style(step.property);
return step.value;
}
else {
var orig = step._origval;
step._origval = null;
return orig;
}
});
return d;
}
function _handletransition(trans, d, onBegin, onEnd, rewinding, prevdelay) {
var o = trans;
o._transitionCount = 0;
d = d.transition();
if(o.duration != undefined) d = d.duration(o.duration);
if(o.ease != undefined) d = d.ease(o.ease);
if(!rewinding) {
if(o.delay != undefined) d = d.delay(o.delay);
}
else if(prevdelay != undefined && prevdelay != null) d = d.delay(prevdelay);
d = d.each('start', function() {
if(o._transitionCount == 0 && onBegin != undefined && onBegin != null) onBegin(o);
o._transitionCount++;
});
d = d.each('end', function() {
o._transitionCount--;
if(o._transitionCount == 0 && onEnd != undefined && onEnd != null) onEnd(o);
});
if(o.style != undefined) {
if(!rewinding) {
for(var j=0; j < o.style.length; j++) {
d = _handlestyle(o.style[j], d, false);
}
}
else {
for(var j=o.style.length-1; j >= 0; j--) {
d = _handlestyle(o.style[j], d, true);
}
}
}
return d;
}
function _handlescript(script, onBegin, onEnd, rewinding) {
var o = script;
var d = d3.select(o.select);
o._scriptCount = 0;
onBegin(o);
if(!rewinding) {
for(var j=0; j < o.transitions.length; j++) {
d = _handletransition(o.transitions[j], d,
function() { o._scriptCount++; },
function() { o._scriptCount--; if(o._scriptCount == 0) onEnd(o); }, false);
}
}
else {
for(var j=o.transitions.length-1; j >= 0; j--) {
var prevdelay = null;
if(j < o.transitions.length-1) prevdelay = o.transitions[j+1].delay;
d = _handletransition(o.transitions[j], d,
function() { o._scriptCount++; },
function() { o._scriptCount--; if(o._scriptCount == 0) onEnd(o); }, true, prevdelay);
}
}
}
function played(s) {
return (s._played == true);
}
function play(s, onBegin, onEnd) {
if(s._sCount > 0 || s._played == true) return; // Still busy or already played
s._sCount = 0;
s._played = true;
for(var i=0; i < s.script.length; i++) _handlescript(s.script[i], function() {
if(s._sCount == 0 && onBegin != undefined && onBegin != null) onBegin(s);
s._sCount++;
},
function() {
s._sCount--;
if(s._sCount == 0 && onEnd != undefined && onEnd != null) onEnd(s);
}, false);
}
function rewind(s, onBegin, onEnd) {
if(s._sCount > 0 || s._played != true) return; // Still busy or not played
s._sCount = 0;
s._played = false;
for(var i=s.script.length-1; i >= 0; i--) _handlescript(s.script[i], function() {
if(s._sCount == 0 && onBegin != undefined && onBegin != null) onBegin(s);
s._sCount++
},
function() {
s._sCount--;
if(s._sCount == 0 && onEnd != undefined && onEnd != null) onEnd(s);
}, true);
}
return {
played: played,
play: play,
rewind: rewind
};
}();
|
JavaScript
| 0 |
@@ -1645,24 +1645,143 @@
egin(o);%0A%09%09%0A
+%09%09var count = 0;%0A%09%09d.each(function() %7B count++; %7D);%0A%09%09%0A%09%09// Empty selection?%0A%09%09if(count == 0) %7B onEnd(o); return; %7D%0A%09%09%0A
%09%09if(!rewind
@@ -3226,16 +3226,17 @@
sCount++
+;
%0A%09%09%09%7D,%0A%09
|
0f7fc33023d5da4eb76c9c0c44d3e6a4164bc46b
|
Add tests for update method
|
package/reactive-obj-tests.js
|
package/reactive-obj-tests.js
|
Tinytest.add('Initialize a given object and get the root node', function (test) {
var obj = {a: 1};
var x = new ReactiveObj(obj);
test.equal(x.get(), obj);
test.equal(x.get([]), obj);
});
Tinytest.add('Get nested nodes', function (test) {
var obj = {a: 1, b: {c: 2}, d: [0, 42, {e: 13}]};
var x = new ReactiveObj(obj);
test.equal(x.get('a'), 1);
test.equal(x.get(['a']), 1);
test.equal(x.get(['b', 'c']), 2);
test.equal(x.get(['d', 1]), 42);
test.equal(x.get(['d', 2, 'e']), 13);
});
Tinytest.add('Replace root node', function (test) {
var obj = {a: 1};
var x = new ReactiveObj(obj);
x.set([], {b: 1});
test.equal(x.get().b, 1);
});
Tinytest.add('Replace nested nodes', function (test) {
var obj = {a: 1, b: {c: 2}, d: [0, 42, {e: 13}]};
var x = new ReactiveObj(obj);
x.set('a', {aa: 1});
x.set(['aa'], 11);
x.set(['b', 'c'], 20);
x.set(['d', 1], 'forty-two');
x.set(['d', 2, 'e'], {f: 'thirteen'});
test.equal(x.get(['a', 'aa']), 1);
test.equal(x.get('aa'), 11);
test.equal(x.get(['b', 'c']), 20);
test.equal(x.get(['d', 1]), 'forty-two');
test.equal(x.get(['d', 2, 'e', 'f']), 'thirteen');
});
Tinytest.add('Root node getter is reactive', function (test) {
var obj = {a: 1};
var num = 1;
var count = 0;
var x = new ReactiveObj(obj);
var c = Tracker.autorun(function () {
test.equal(x.get().a, num);
count += 1;
});
x.set(['a'], 2);
num = 2;
Tracker.flush();
x.set([], {a: 3});
num = 3;
Tracker.flush();
test.equal(count, num);
c.stop();
});
Tinytest.add('Nested node getter is reactive', function (test) {
var obj = {a: {b: 1}};
var num = 1;
var count = 0;
var x = new ReactiveObj(obj);
var c = Tracker.autorun(function () {
test.equal(x.get('a').b, num);
count += 1;
});
x.set(['a'], {b: 2});
num = 2;
Tracker.flush();
x.set([], {a: {b: 3}});
num = 3;
Tracker.flush();
x.set(['a', 'b'], 4);
num = 4;
Tracker.flush();
test.equal(count, num);
c.stop();
});
Tinytest.add('Reactivity is isolated between sibling nodes', function (test) {
var obj = {a: {b: 1}, z: 0};
var count = 1;
var x = new ReactiveObj(obj);
var c = Tracker.autorun(function () {
test.equal(x.get('z'), 0);
count += 1;
});
x.set(['a', 'b'], 2);
Tracker.flush();
x.set(['a'], {b: 3});
Tracker.flush();
test.equal(count, 2);
c.stop();
});
Tinytest.add('Reactivity is triggered only upon flush', function (test) {
var x = new ReactiveObj({a: 1});
var num = 1;
var count = 1;
var c = Tracker.autorun(function () {
test.equal(x.get('a'), num);
count += 1;
});
x.set('a', 2);
x.set('a', 1);
test.equal(count, 2);
});
Tinytest.add('Empty nodes in deps are cleaned up when removed', function (test) {
var x = new ReactiveObj({a: 1});
var depState = JSON.stringify(x._deps);
var c = Tracker.autorun(function () {
for (var i=0; i<10; i+=1) {
x.get(i + '');
for (var j=0; j<10; j+=1) {
x.get([i+'', j+'']);
}
}
});
c.stop();
Tracker.flush();
test.equal(JSON.stringify(x._deps), depState);
});
|
JavaScript
| 0 |
@@ -3103,12 +3103,439 @@
State);%0A%7D);%0A
+%0ATinytest.add('Update value if not set', function (test) %7B%0A var x = new ReactiveObj(%7Ba: 1%7D);%0A%0A x.update('b', 2, function () %7B%7D);%0A test.equal(x.get('b'), 2);%0A%7D);%0A%0ATinytest.add('Update existing value', function (test) %7B%0A var x = new ReactiveObj(%7Ba: 1%7D);%0A%0A x.update('a', function (v) %7B return v + 10; %7D);%0A test.equal(x.get('a'), 11);%0A%0A x.update('a', 13, function (v) %7B return v + 10; %7D);%0A test.equal(x.get('a'), 21);%0A%7D);%0A%0A
|
685d3c15d6b6b8175a297285dd32eccc190387c6
|
Remove console logs
|
packages/bemlinter/bin/cli.js
|
packages/bemlinter/bin/cli.js
|
#!/usr/bin/env node
const _ = require('lodash');
const fs = require('mz/fs');
const path = require('path');
const minimist = require('minimist');
const {lint, format} = require('./../src/bemlinter');
// Main
const argv = minimist(process.argv.slice(2));
new Promise(resolve => {
if (!argv.config) {
return resolve({sources: argv._});
}
fs.readFile(argv.config, {encoding:'utf8'})
.then(data => JSON.parse(data))
.then(config => {
const basePath = path.dirname(argv.config);
config.excludePath = (config.excludePath || [])
.map(filePath => `!${path.resolve(basePath, filePath)}`);
config.sources = config.sources
.map(filePath => path.resolve(basePath, filePath))
.concat(config.excludePath);
console.log(config.sources);
resolve({
sources: config.sources,
options: _.omit(config, 'sources', 'excludePath')
});
})
.catch(console.error);
})
.then(params => {
if (params.sources.length < 1) {
console.log('Usage: ./index.js <scss-file> [<scss-file> ...]');
process.exit(1);
}
return lint(params.sources, params.options);
})
.then(lintResult => {
console.log(format(lintResult));
process.exit(lintResult.getStatus() ? 0 : 1);
})
.catch(console.error);
|
JavaScript
| 0.000002 |
@@ -752,43 +752,8 @@
h);%0A
- console.log(config.sources);%0A
|
655fe4595fd8ab5fd426036dea4d0fe61e6e33bf
|
update error in user-task
|
gulpy/user-tasks/example-task.js
|
gulpy/user-tasks/example-task.js
|
// This is example of task function
var gulp = require('gulp'),
gulpif = require('gulp-if'),
notify = require('gulp-notify'),
projectConfig = require('../../projectConfig'),
notifyConfig = projectConfig.notifyConfig,
modifyDate = require('../helpers/modifyDateFormatter');
// Include browserSync, if you need to reload browser
// browserSync = require('browser-sync');
// require('./ path to task file, which have to be done before current task');
// Task description
module.exports = function(cb) {
return gulp.task(/* task name, String in quotes */, [/* tasks names, which have to be done before current task */], function(cb) {
return gulp.src(/* path-string or array of path-strings to files */)
// Do stuff here
.on('error', notify.onError(function (error) {
return 'Something is wrong.\nLook in console.\n' + error;
}))
.pipe(gulp.dest(/* path-string to destanation directory. Only directory, not a file! */))
// If you need to reload browser, uncomment the row below
// .pipe(browserSync.reload({stream:true}))
.pipe(
gulpif(notifyConfig.useNotify,
notify({
onLast: true, // Use this, if you need notify only after last file will be processed
sound: notifyConfig.sounds.onSuccess,
title: notifyConfig.title,
// You can change text of success message
message: 'Example task is finished \n'+ notifyConfig.taskFinishedText +'<%= options.date %>',
templateOptions: {
date: modifyDate.getTimeOfModify()
}
})
)
);
// You can return callback, if you can't return pipe
// cb(null);
});
};
|
JavaScript
| 0.000001 |
@@ -853,24 +853,41 @@
rn '
-Something is wro
+%5CnAn error occurred while somethi
ng.%5C
@@ -899,15 +899,31 @@
in
+the
console
+ for details
.%5Cn'
|
d6aae730d4f063bd7cb3342a35baa7244b2a40d6
|
Handle searchNodeEverywhere returning null (#583)
|
packages/core/src/components/HotKey/Decorator.js
|
packages/core/src/components/HotKey/Decorator.js
|
/*
* This file is part of ORY Editor.
*
* ORY Editor is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ORY Editor is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ORY Editor. If not, see <http://www.gnu.org/licenses/>.
*
* @license LGPL-3.0
* @copyright 2016-2018 Aeneas Rekkas
* @author Aeneas Rekkas <[email protected]>
*
*/
// @flow
/* eslint-disable no-empty-function */
import { Component } from 'react'
import { connect } from 'react-redux'
import { createStructuredSelector } from 'reselect'
import pathOr from 'ramda/src/pathOr'
import Mousetrap from 'mousetrap'
import { undo, redo } from '../../actions/undo'
import { removeCell, focusCell, blurAllCells } from '../../actions/cell'
import { isEditMode } from '../../selector/display'
import { focus } from '../../selector/focus'
import {
node,
editable,
editables,
searchNodeEverywhere
} from '../../selector/editable'
import type { Editable, ComponetizedCell } from '../../types/editable'
type Props = {
children: any,
id: string,
undo(id: string): void,
redo(id: string): void,
removeCell(id: string): void,
focus: string,
focusCell(id: string): void,
blurAllCells(): void,
updateCellContent(): any,
updateCellLayout(): any,
isEditMode: boolean,
node(cell: string, editable: string): Object,
editable: Editable,
searchNodeEverywhere(
id: string
): { editable: Editable, node: ComponetizedCell }
}
const hotKeyHandler = (n: Object, key: string) =>
pathOr(
pathOr(() => Promise.resolve(), ['content', 'plugin', key], n),
['layout', 'plugin', key],
n
)
const nextLeaf = (order: Array<any> = [], current: string) => {
let last
return order.find((c: { id: string, isLeaf: boolean }) => {
if (last === current) {
return c.isLeaf
}
last = c.id
return false
})
}
const previousLeaf = (order: Array<any>, current: string) =>
nextLeaf([...order].reverse(), current)
const falser = (err: Error) => {
if (err) {
console.log(err)
}
}
if (Mousetrap && Mousetrap.prototype) {
Mousetrap.prototype.stopCallback = () => false
}
let wasInitialized = false
class Decorator extends Component {
componentDidMount() {
if (!wasInitialized) {
if (!Mousetrap) {
return
}
Mousetrap.bind(['ctrl+z', 'command+z'], this.handlers.undo)
Mousetrap.bind(
['ctrl+shift+z', 'ctrl+y', 'command+shift+z', 'command+y'],
this.handlers.redo
)
Mousetrap.bind(['del', 'backspace'], this.handlers.remove)
Mousetrap.bind(['down', 'right'], this.handlers.focusNext)
Mousetrap.bind(['up', 'left'], this.handlers.focusPrev)
wasInitialized = true
}
}
props: Props
handlers = {
undo: () => {
const { id, undo } = this.props
undo(id)
},
redo: () => {
const { id, redo } = this.props
redo(id)
},
// remove cells
remove: (e: Event) => {
const { focus, removeCell, isEditMode } = this.props
if (!isEditMode) {
return
}
const { node: n } = this.props.searchNodeEverywhere(focus)
hotKeyHandler(n, 'handleRemoveHotKey')(e, n)
.then(() => removeCell(focus))
.catch(falser)
},
// focus next cell
focusNext: (e: Event) => {
const { focus, focusCell, blurAllCells, isEditMode } = this.props
if (!isEditMode) {
return
}
const { node: n, editable } = this.props.searchNodeEverywhere(focus)
hotKeyHandler(n, 'handleFocusNextHotKey')(e, n)
.then(() => {
const found = nextLeaf(editable.cellOrder, focus)
if (found) {
blurAllCells()
focusCell(found.id)
}
})
.catch(falser)
},
// focus previous cell
focusPrev: (e: Event) => {
const { focus, focusCell, blurAllCells, isEditMode } = this.props
if (!isEditMode) {
return
}
const { node: n, editable } = this.props.searchNodeEverywhere(focus)
hotKeyHandler(n, 'handleFocusPreviousHotKey')(e, n)
.then(() => {
const found = previousLeaf(editable.cellOrder, focus)
if (found) {
blurAllCells()
focusCell(found.id)
}
})
.catch(falser)
}
}
render() {
const { children } = this.props
return children
}
}
const mapStateToProps = createStructuredSelector({
isEditMode,
focus,
node: (state: any) => (id: string, editable: string) =>
node(state, { id, editable }),
searchNodeEverywhere: (state: any) => (id: string) =>
searchNodeEverywhere(state, id),
editable: (state: any, props: any) => (id?: string) =>
editable(state, id ? { id } : props),
editables
})
const mapDispatchToProps = {
undo,
redo,
removeCell,
focusCell: (id: string) => focusCell(id)(),
blurAllCells
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(Decorator)
|
JavaScript
| 0 |
@@ -3491,32 +3491,38 @@
return%0A %7D%0A
+
%0A const %7B n
@@ -3522,19 +3522,17 @@
nst
-%7B node: n %7D
+maybeNode
= t
@@ -3561,32 +3561,116 @@
erywhere(focus)%0A
+ if (!maybeNode) %7B %0A return%0A %7D%0A const %7B node: n %7D = maybeNode%0A
hotKeyHand
|
2b9691a0387c124a3661404c3f68cfc0054e32b0
|
Update HeaderBar tests
|
project/frontend/src/components/HeaderBar/HeaderBar.test.js
|
project/frontend/src/components/HeaderBar/HeaderBar.test.js
|
import React from "react";
import { configure, shallow } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import HeaderBar from "./HeaderBar";
import LoginButtonSet from "../UI/LoginButtonSet/LoginButtonSet";
import SignOutButton from "./SignOutButton/SignOutButton";
import { NavLink } from "react-router-dom";
configure({ adapter: new Adapter() });
describe("<HeaderBar />", () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<HeaderBar />);
});
it('should render "What is sGonks?" and "Sign in" buttins if not authenticated', () => {
expect(wrapper.find(LoginButtonSet));
});
it('should render "Select competition" and "Sign out" buttins if authenticated', () => {
wrapper.setProps({ loggedIn: true });
expect(wrapper.find(SignOutButton));
expect(wrapper.find(NavLink).text()).toEqual("Select Competition");
});
it('should render inner navigation items if "innerNav" is true', () => {
wrapper.setProps({ innerNav: true });
expect(wrapper.find(NavLink)).toHaveLength(3);
});
});
|
JavaScript
| 0 |
@@ -605,16 +605,100 @@
ttonSet)
+.exists()).toBeTruthy();%0A expect(wrapper.find(SignOutButton).exists()).toBeFalsy(
);%0A %7D);
@@ -870,16 +870,101 @@
tButton)
+.exists()).toBeTruthy();%0A expect(wrapper.find(LoginButtonSet).exists()).toBeFalsy(
);%0A e
|
9bf39d2bc8349efee80277e9e31a014eec01e9fc
|
fix require capitalization.
|
polyball/client/hudbehaviors/LandingPageRenderer.js
|
polyball/client/hudbehaviors/LandingPageRenderer.js
|
/**
* Created by kdban on 4/8/2016.
*/
var $ = require('jquery');
var Logger = require('polyball/shared/logger');
var throttle = require('physicsjs').util.throttle;
/**
*
* @param {Object} config
* @property {string} config.prependTo - css selector for the element to prepend the renderer to
* @property {function} config.onNameChange
* @property {function} config.onWatchClick
* @property {function} config.onQueueClick
* @constructor
*/
var LandingPageRenderer = function (config) {
var landingModal;
var self = this;
$.get('hudcomponents/landingModal.html', function (data) {
Logger.debug('Injecting Landing Modal.');
$(config.prependTo).prepend(data);
landingModal = $('.landingModal');
var changeName = throttle(function () {
if (!config.onNameChange) {
Logger.warn("LandingPageRenderer: no onNameChange listener.");
return;
}
config.onNameChange($('.landingNameChooser input').val());
}, 100);
$('.landingNameChooser input').keypress(changeName);
$('.landingNameChooser input').change(changeName);
$('.landingSpectateButton').click(function () {
if (config.onWatchClick) {
config.onWatchClick();
}
self.remove();
});
$('.landingQueueButton').click(function () {
if (config.onQueueClick) {
config.onQueueClick();
}
self.remove();
});
});
this.render = function (name) {
if (landingModal != null) {
$('.localUsername').text(name);
if (!$('.landingNameChooser input').is(":focus")) {
$('.landingNameChooser input').val(name);
}
}
};
this.remove = function () {
if (landingModal != null) {
landingModal.remove();
}
};
};
module.exports = LandingPageRenderer;
|
JavaScript
| 0.00022 |
@@ -100,17 +100,17 @@
/shared/
-l
+L
ogger');
|
3eabc966e5566baf930ed1aaac61e470089d98f1
|
Update script.js
|
developer/script.js
|
developer/script.js
|
//todo write angular scripts for developer page.
var forumModule = angular.module('app', []).
controller("forumCtrl", function forumCtrl($scope, $window){
$scope.forum = {
threads: [{subject: "blah blah blah", posts: [{user: "user1", message: "hi how u doing"}, {user: "user2", message: "lol wassup"}]},
{subject: "how to add your own functions", posts: [{user: "user1", message: "hi how u doing"}, {user: "user2", message: "lol wassup"}]}]
};
$scope.currentThread = {};
$scope.setThread = function(thread){
$scope.currentThread = thread;
}
});
|
JavaScript
| 0.000002 |
@@ -385,38 +385,32 @@
, message: %22
-hi how u doing
+asdfasdf
%22%7D, %7Buser: %22
@@ -423,34 +423,38 @@
, message: %22
-lol wassup
+j jajajajajajh
%22%7D%5D%7D%5D%0A%09%09%7D;%0A%09
|
491e5e10e04c58040f5f72ddf889b3872941e7f3
|
Scale logo
|
layouts/Page.js
|
layouts/Page.js
|
import { Component } from 'react';
import NProgress from 'nprogress';
import Head from 'next/head';
import Link from 'next/link';
import Router from 'next/router';
import animatedAbakus from '../animatedAbakus';
import Content from '../components/Content';
import WideBackground from '../components/WideBackground';
import Navigation from '../components/Navigation';
import Footer from '../components/Footer';
Router.onRouteChangeStart = () => NProgress.start();
Router.onRouteChangeComplete = () => NProgress.done();
Router.onRouteChangeError = () => NProgress.done();
export default class extends Component {
componentDidMount() {
//animatedAbakus(this.canvas, {});
}
render() {
return (
<div className="container">
<Head>
<meta charSet="utf-8" />
<title>{this.props.title} · Abakus 40 år</title>
<link href="https://fonts.googleapis.com/css?family=Lato|Ubuntu:700" rel="stylesheet" />
<link rel="stylesheet" href="/static/nprogress.css" />
<script src="https://use.fontawesome.com/f3b8128270.js"></script>
</Head>
<WideBackground height={460}>
<Content alignItems="center" justifyContent="flex-end">
<img src="/static/logo.svg" style={{ marginLeft: -20 }} />
<div className="date">
<time>13.–19. mars 2017</time>
</div>
</Content>
</WideBackground>
<Content>
{this.props.children}
</Content>
<Footer />
<style jsx>{`
:global(*) {
margin: 0;
padding: 0;
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
}
:global(body) {
font-family: Lato, 'Open Sans', sans-serif;
background: #f4f4f4;
font-size: 18px;
line-height: 1.6;
}
:global(a) {
text-decoration: none;
color: #333;
cursor: pointer;
}
:global(h2) {
font-weight: 400;
}
.title {
font-size: 85px;
letter-spacing: 10px;
text-transform: uppercase;
font-weight: 700;
text-shadow: 4px 2px 0 #444;
padding-bottom: 10px;
text-align: center;
}
.title::selection {
background: #b11b11;
}
.date {
font-size: 24px;
letter-spacing: 2px;
text-transform: uppercase;
padding: 20px;
}
.canvas {
transform: translateX(-30px)
}
`}</style>
</div>
);
}
}
|
JavaScript
| 0.000001 |
@@ -1275,16 +1275,44 @@
eft: -20
+, width: '100%25', padding: 20
%7D%7D /%3E%0A
|
accd39339f9aa4a3911b13795be5bbb6e1378909
|
Fix import
|
powerauth-webflow/src/main/js/components/consent.js
|
powerauth-webflow/src/main/js/components/consent.js
|
/*
* Copyright 2019 Wultra s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from "react";
import {connect} from "react-redux";
// Actions
import {authenticate, cancel, init} from "../actions/consentActions";
// Components
import {FormGroup, Panel} from "react-bootstrap";
import Spinner from 'react-tiny-spin';
// i18n
import {FormattedMessage} from "react-intl";
import sanitizeHTML from 'sanitize-html';
/**
* OAuth 2.0 consent form.
*/
@connect((store) => {
return {
context: store.dispatching.context
}
})
export default class Consent extends React.Component {
constructor() {
super();
this.init = this.init.bind(this);
this.handleCheckboxChange = this.handleCheckboxChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleCancel = this.handleCancel.bind(this);
this.createHtml = this.createHtml.bind(this);
this.initConsent = this.initConsent.bind(this);
this.state = {
consentHtml: null,
options: null,
validationErrorMessage: null,
optionValidationErrors: new Map()
};
}
componentWillMount() {
this.init();
}
componentWillReceiveProps(props) {
this.initConsent(props);
}
init() {
this.props.dispatch(init());
}
initConsent(props) {
// Store consent HTML in local state, switching language or refresh will receive new consent HTML
if (props.context.consentHtml) {
this.setState({consentHtml: props.context.consentHtml});
}
if (props.context.options) {
// Update default values in context when options are received for the first time
if (!props.context.consent) {
props.context.consent = {};
props.context.consent.checkedOptions = new Map();
props.context.options.map(option => {
if (option.defaultValue === 'CHECKED') {
option.value = 'CHECKED';
props.context.consent.checkedOptions.set(option.id, true);
}
});
} else if (props.context.consent && props.context.consent.checkedOptions) {
// Update option values from context when consent data is already present in context (e.g. language change)
props.context.options.map(option => {
if (props.context.consent.checkedOptions.get(option.id)) {
option.value = 'CHECKED';
}
});
}
// Store consent options in local state
this.setState({options: props.context.options});
}
// Store validation error message only in local state, language change will require new validation error message
if (props.context.consentValidationPassed === false && props.context.validationErrorMessage) {
this.setState({validationErrorMessage: props.context.validationErrorMessage});
}
// Store validation results only in local store, language change will require new option validation error messages
if (props.context.optionValidationResults) {
// At first, clean existing errors
const validationErrors = new Map();
props.context.optionValidationResults.map((result) => {
if (!result.validationPassed) {
// Store validation errors only in local state, language change will require new option validation error messages
validationErrors.set(result.id, result.errorMessage);
}
});
this.setState({optionValidationErrors: validationErrors});
}
}
handleCheckboxChange(event) {
// Update map of checked checkboxes in context
const optionId = event.target.id;
const checked = event.target.checked;
this.props.context.consent.checkedOptions.set(optionId, checked);
// Update options in local state, the values are used later in handleSubmit()
const localOptions = this.state.options;
localOptions.map(option => {
if (option.id === optionId) {
if (checked) {
option.value = 'CHECKED';
} else {
option.value = 'NOT_CHECKED';
}
}
});
this.setState({options: localOptions});
}
handleSubmit(event) {
event.preventDefault();
// Local state stores up-to-date consent options state
this.props.dispatch(authenticate(this.state.options));
}
handleCancel(event) {
event.preventDefault();
this.props.dispatch(cancel());
}
createHtml(html) {
let updatedAttributes = sanitizeHTML.defaults.allowedAttributes;
updatedAttributes.img.concat(['alt']);
return {
__html: sanitizeHTML(html, {
allowedTags: sanitizeHTML.defaults.allowedTags.concat(['img']),
allowedAttributes: updatedAttributes
})
};
}
render() {
return (
<div id="operation">
{(this.props.context.loading) ? (
<Spinner/>
) : (
<form onSubmit={this.handleSubmit}>
<Panel>
<div className="auth-actions">
{(this.state.consentHtml) ? (
<div dangerouslySetInnerHTML={this.createHtml(this.state.consentHtml)} className="consent-text"/>
) : (
undefined
)}
{(this.state.validationErrorMessage) ? (
<div dangerouslySetInnerHTML={this.createHtml(this.state.validationErrorMessage)} className="consent-error"/>
) : (
undefined
)}
{(this.state.options) ? (
<div>
{this.state.options.map((option) => {
const required = option.required;
const validationError = this.state.optionValidationErrors.get(option.id);
let optionPrefixClassName = "consent-option-prefix";
if (validationError) {
optionPrefixClassName += " consent-option-error";
}
let checked = false;
if (option.value === 'CHECKED') {
checked = true;
}
return (
<div className="row attribute" key={option.id}>
<div className="col-xs-2 text-nowrap consent-nopadding">
{(required) ? (
<span className={optionPrefixClassName}>* </span>
) : (
<span className={optionPrefixClassName}> </span>
)}
<input id={option.id} type="checkbox" className="consent-checkbox" checked={checked} onChange={this.handleCheckboxChange}/>
</div>
<div className="col-xs-10 text-left consent-nopadding">
<label htmlFor={option.id} className="consent-option-text" dangerouslySetInnerHTML={this.createHtml(option.descriptionHtml)}/>
{(validationError) ? (
<div dangerouslySetInnerHTML={this.createHtml(validationError)} className="consent-option-error"/>
) : (
undefined
)}
</div>
</div>
)
})}
</div>
) : (
undefined
)}
{(this.props.context.message) ? (
<FormGroup
className={(this.props.context.error ? "message-error" : "message-information")}>
<FormattedMessage id={this.props.context.message}/>
{(this.props.context.remainingAttempts > 0) ? (
<div>
<FormattedMessage
id="authentication.attemptsRemaining"/> {this.props.context.remainingAttempts}
</div>
) : (
undefined
)}
</FormGroup>
) : (
undefined
)}
<div className="buttons">
<div className="attribute row">
<div className="col-xs-12">
<Button bsSize="lg" type="submit" bsStyle="success" block>
<FormattedMessage id="operation.confirm"/>
</Button>
</div>
</div>
<div className="attribute row">
<div className="col-xs-12">
<a href="#" onClick={this.handleCancel} className="btn btn-lg btn-default">
<FormattedMessage id="operation.cancel"/>
</a>
</div>
</div>
</div>
</div>
</Panel>
</form>
)}
</div>
)
}
}
|
JavaScript
| 0.000002 |
@@ -749,24 +749,32 @@
nts%0Aimport %7B
+Button,
FormGroup, P
|
ad4fcd7c34bec45ec23d4b9872c7fe776972c8eb
|
Add margin
|
layouts/main.js
|
layouts/main.js
|
import React, { Component } from 'react'
import { connect } from 'react-redux'
import Link from 'next/link'
import Router from 'next/router'
import { withRouter } from 'next/router'
import NoSSR from 'react-no-ssr'
import fetch from 'isomorphic-fetch'
import debounce from 'lodash/debounce'
import Meta from '../components/meta'
import { loggedOut } from '../lib/authActions'
import { initGA, logPageView } from '../lib/analytics'
import Colors from '../utils/Colors'
import { PLATONOS_API_ENDPOINT } from '../constants'
class MainLayout extends Component {
constructor(props) {
super(props)
this.updateUserLastActive = debounce(this.updateUserLastActive, 1000)
}
componentDidMount() {
if (!window.GA_INITIALIZED) {
initGA()
window.GA_INITIALIZED = true
}
logPageView()
}
onClickLogout = (e) => {
e.preventDefault()
if (confirm('Do you want to logout?')) {
this.props.onLoggedout()
Router.push({
pathname: '/'
})
}
}
updateUserLastActive = async () => {
if (!process.browser) return
if (!this.props.currentUserId) return
const currentUserId = this.props.currentUserId
try {
await fetch(`${PLATONOS_API_ENDPOINT}/updateUserLastActiveAt/${currentUserId}`)
} catch (err) {
console.error('Cannot update user last active: ', err)
}
}
render() {
this.updateUserLastActive()
const isLoggedIn = this.props.isLoggedIn
const { pathname } = this.props.router
return (
<div className="main">
{ /* global styles and meta tags */ }
<Meta />
{/* Site content */}
<div className="sidebar">
<Link prefetch href="/">
<a className="logo">
<img src="/static/plato-red.jpg" className="logo-img"/>
<h1 className="logo-text">Platonos</h1>
</a>
</Link>
<div className="button-wrapper">
<div className="upper-pane">
<Link prefetch href="/"><a className={pathname === '/' && 'active'}>Read</a></Link>
<Link prefetch href="/talk"><a className={pathname === '/talk' && 'active'}>Talk</a></Link>
{isLoggedIn ?
// Fix the wrong reuse component ssr problems (without this, profile won't get highlighted when you go to the page directly.)
<NoSSR>
<Link prefetch href="/profile"><a className={pathname === '/profile' && 'active'}>Profile</a></Link>
<a onClick={this.onClickLogout}>Logout</a>
</NoSSR>
:
<Link prefetch href="/join"><a className={pathname === '/join' && 'active'}>Join</a></Link>
}
</div>
<div className="flex-space"></div>
<Link prefetch href="/about"><a className={pathname === '/about' && 'active'}>About</a></Link>
</div>
</div>
<div className="world">
{ this.props.children }
</div>
{/* <div className="logo">
<Link prefetch href="/"><a>Platonos</a></Link>
</div> */}
{ /* local styles */ }
<style jsx>{`
.main {
display: flex;
flex-direction: row;
height: 100vh;
}
.sidebar {
min-width: 98px;
border-right: 1px solid #ddd;
display: flex;
flex-direction: column;
}
.logo {
pointer: cursor;
}
.logo-img {
margin: 15px 25px 7px;
width: 48px;
}
.logo-text {
font-size: 14px;
font-weight: bold;
text-align: center;
margin: 0 0 15px;
color: ${Colors.main};
}
.button-wrapper {
margin-top: 20px;
display: flex;
flex-direction: column;
flex-grow: 1;
overflow-y: auto;
}
.button-wrapper .upper-pane {
display: flex;
flex-direction: column;
min-height: 200px;
}
.button-wrapper a {
height: 50px;
color: #000;
display: block;
text-align: center;
padding: 15px 0;
cursor: pointer;
outline: none;
}
.button-wrapper a:hover {
background-color: ${Colors.lightGrey};
}
.button-wrapper a.active {
font-weight: bold;
background-color: ${Colors.lightGrey};
border-top: 1px solid #ddd;
border-bottom: 1px solid #ddd;
}
.flex-space {
flex: 1;
min-height: 1px;
}
.world {
flex: 1 1 auto;
}
`}</style>
</div>
)
}
}
const MainLayoutWithRedux = connect(
(state) => {
return {
isLoggedIn: state.authReducers.isLoggedIn,
currentUserId: state.authReducers.authData && state.authReducers.authData.currentUserId,
}
},
(dispatch) => ({
onLoggedout() {
dispatch(loggedOut())
}
}),
)(MainLayout)
const MainLayoutWithRouter = withRouter(MainLayoutWithRedux)
export default MainLayoutWithRouter
|
JavaScript
| 0.000004 |
@@ -3988,24 +3988,58 @@
ow-y: auto;%0A
+ padding-bottom: 30px;%0A
%7D%0A
|
d4f17eb62e733b213200c0f09d2c3798035ab1bd
|
Modify current test data.
|
placeholders.js
|
placeholders.js
|
var placeholderProfile = {
user: {
name: 'Gordon Ramsay',
email: '[email protected]',
date: 'September 20, 2015',
image: 'http://www.trbimg.com/img-53c59dde/turbine/la-dd-jacques-pepin-gordon-ramsay-20140715 (376KB)',
other: 'BANANA'
},
recipes: [
{
name: "Filet Mignon",
sourceID: "Austin Riedel"
},
{
name: "Foie Gras",
sourceID: "Emeril Lagasse"
},
{
name: "FlavorTown Nachos",
sourceID: "Guy Fieri"
}
],
recipeTemplate: {
name:{
value: ''
},
servings: {
value: ''
},
skillLevel: {
value: 'Junior Dev'
},
description: {
value: 'This is your basic recipe description'
}
}
}
module.exports = placeholderProfile;
|
JavaScript
| 0 |
@@ -556,16 +556,59 @@
'%0A %7D, %0A
+ cookTime: %7B%0A value: '60 minutes'%0A %7D,%0A
skillL
@@ -718,16 +718,327 @@
'%0A %7D%0A %7D
+, %0A followingList: %5B%0A %7B%0A username: 'Gordon Ramsay', %0A recipes: 2, %0A skillLevel: 98,%0A totalForks: 1214%0A %7D, %0A %7B%0A username: 'Bobby Flay', %0A recipes: 5, %0A skillLevel: 89,%0A totalForks: 1348%0A %7D, %0A %7B%0A username: 'Guy Fieri', %0A recipes: 3, %0A skillLevel: 27,%0A totalForks: 0%0A %7D%0A %5D
%0A%7D%0A%0A%0Amod
|
f3ebb21f4785cc05093967ac43e285873c035367
|
Add console.log on build
|
hooks/beforePluginInstallHook.js
|
hooks/beforePluginInstallHook.js
|
/**
Hook is executed when plugin is added to the project.
It will check all necessary module dependencies and install the missing ones locally.
*/
var path = require('path');
var fs = require('fs');
var spawnSync = require('child_process').spawnSync;
var pluginNpmDependencies = require('../package.json').dependencies;
var INSTALLATION_FLAG_FILE_NAME = '.npmInstalled';
// region mark that we installed npm packages
/**
* Check if we already executed this hook.
*
* @param {Object} ctx - cordova context
* @return {Boolean} true if already executed; otherwise - false
*/
function isInstallationAlreadyPerformed(ctx) {
var pathToInstallFlag = path.join(ctx.opts.projectRoot, 'plugins', ctx.opts.plugin.id, INSTALLATION_FLAG_FILE_NAME);
try {
fs.accessSync(pathToInstallFlag, fs.F_OK);
return true;
} catch (err) {
return false;
}
}
/**
* Create empty file - indicator, that we tried to install dependency modules after installation.
* We have to do that, or this hook is gonna be called on any plugin installation.
*/
function createPluginInstalledFlag(ctx) {
var pathToInstallFlag = path.join(ctx.opts.projectRoot, 'plugins', ctx.opts.plugin.id, INSTALLATION_FLAG_FILE_NAME);
fs.closeSync(fs.openSync(pathToInstallFlag, 'w'));
}
// endregion
module.exports = function(ctx) {
if (isInstallationAlreadyPerformed(ctx)) {
return;
}
console.log('Installing dependency packages: ');
console.log(JSON.stringify(pluginNpmDependencies, null, 2));
var npm = (process.platform === "win32" ? "npm.cmd" : "/usr/local/bin/npm");
var result = spawnSync(npm, ['--version'], { });
console.log(result);
var result = spawnSync(npm, ['install', '--production'], { cwd: './plugins/' + ctx.opts.plugin.id });
if (result.error) {
throw result.error;
}
createPluginInstalledFlag(ctx);
};
|
JavaScript
| 0 |
@@ -1559,24 +1559,99 @@
bin/npm%22);%0A%0A
+ console.log(npm);%0A console.log(%22spawnSync%22);%0A console.log(spawnSync);%0A%0A
var result
|
8f01f37070614ceeed74ae94ef7eecbd89f8c56b
|
Add base test for containing any value
|
koans/AboutMaps.js
|
koans/AboutMaps.js
|
describe("About Maps", function () {
describe("Basic Usage", function () {
it("should understand they are key, value stores", function () {
var trooper = new Map();
trooper.set('name', 'Stormtrooper');
trooper.set('Droid you are looking for?', false);
trooper.set('hits target', function() {
return false;
})
expect(trooper.size).toEqual(FILL_ME_IN);
expect(trooper.get('name')).toEqual(FILL_ME_IN);
expect(trooper.get('hits target')()).toEqual(FILL_ME_IN);
});
it("should understand they are mutable values", function() {
var trooper = new Map();
trooper.set('name', 'Stormtrooper');
expect(trooper.get('name')).toEqual(FILL_ME_IN);
trooper.set('name', 'Iron Maiden');
expect(trooper.get('name')).toEqual(FILL_ME_IN);
})
});
});
|
JavaScript
| 0 |
@@ -826,20 +826,99 @@
%0A %7D)%0A
+%0A
+it(%22should understand they can contain any value%22, function() %7B%0A %0A %7D)%0A
%0A %7D);%0A%7D
|
5f470b7dc5a1b399c143da348b3642a4a228578f
|
Add og:article to Post
|
layouts/post.js
|
layouts/post.js
|
import Page from "./page";
import PropTypes from "prop-types";
const Post = ({ title, children }) => (
<Page title={`writing about ${title}`}>
{children}
{/* TODO: Social media buttons */}
{/*<span>If you enjoyed this article, please share it below! If you have your own reasons for using one style over another <i>please drop me a line or mention me on Twitter!</i></span>*/}
<style>{`
/*
Monokai style - ported by Luigi Maselli - http://grigio.org
*/
.hljs {
display: block;
overflow-x: auto;
padding: 0.5em;
background: black;
color: #ddd;
}
.hljs-tag,
.hljs-keyword,
.hljs-selector-tag,
.hljs-literal,
.hljs-strong,
.hljs-name {
color: #f92672;
}
.hljs-code {
color: #66d9ef;
}
.hljs-class .hljs-title {
color: white;
}
.hljs-attribute,
.hljs-symbol,
.hljs-regexp,
.hljs-link {
color: #bf79db;
}
.hljs-string,
.hljs-bullet,
.hljs-subst,
.hljs-title,
.hljs-section,
.hljs-emphasis,
.hljs-type,
.hljs-built_in,
.hljs-builtin-name,
.hljs-selector-attr,
.hljs-selector-pseudo,
.hljs-addition,
.hljs-variable,
.hljs-template-tag,
.hljs-template-variable {
color: #a6e22e;
}
.hljs-comment,
.hljs-quote,
.hljs-deletion,
.hljs-meta {
color: #75715e;
}
.hljs-keyword,
.hljs-selector-tag,
.hljs-literal,
.hljs-doctag,
.hljs-title,
.hljs-section,
.hljs-type,
.hljs-selector-id {
font-weight: bold;
}
`}</style>
</Page>
);
Post.propTypes = {
title: PropTypes.string.isRequired,
children: PropTypes.node.isRequired
};
export default Post;
|
JavaScript
| 0 |
@@ -4,25 +4,28 @@
ort
-Page
+Head
from %22
-./page
+next/head
%22;%0Ai
@@ -58,16 +58,43 @@
-types%22;
+%0Aimport Page from %22./page%22;
%0A%0Aconst
@@ -118,16 +118,31 @@
children
+, date, summary
%7D) =%3E (
@@ -184,16 +184,539 @@
tle%7D%60%7D%3E%0A
+ %3CHead%3E%0A %3Cmeta property=%22og:description%22 content=%7Bsummary%7D /%3E%0A %3Cmeta property=%22og:type%22 content=%22article%22 /%3E%0A %3Cmeta%0A property=%22og:article:published_time%22%0A content=%7Bdate.replace(%22/%22, %22-%22)%7D%0A /%3E%0A %3Cmeta property=%22og:article:author:first_name%22 content=%22Josh%22 /%3E%0A %3Cmeta property=%22og:article:author:last_name%22 content=%22Hawkins%22 /%3E%0A %3Cmeta property=%22og:article:author:username%22 content=%22@hawkinjs%22 /%3E%0A %3Cmeta property=%22og:article:author:gender%22 content=%22male%22 /%3E%0A %3C/Head%3E%0A%0A
%7Bchi
@@ -2370,16 +2370,93 @@
quired,%0A
+ date: PropTypes.string.isRequired,%0A summary: PropTypes.string.isRequired,%0A
childr
|
2d6a964b661ca36f83e418aef66cd7f4ec823e52
|
store hot search keywords within 7 days
|
src/models/search_keywords.js
|
src/models/search_keywords.js
|
import getDatabase from './database';
const saveSearchInfo = async (type, keyword) => {
const db = await getDatabase();
await db
.collection('search_keywords')
.update(
{ type, keyword },
{ $inc: { count: 1 }, $set: { updated_at: new Date() } },
{ upsert: true }
);
};
export default saveSearchInfo;
|
JavaScript
| 0 |
@@ -115,16 +115,42 @@
abase();
+%0A const now = new Date();
%0A%0A awai
@@ -276,25 +276,18 @@
ed_at: n
-ew Date()
+ow
%7D %7D,%0A
@@ -313,16 +313,124 @@
%7D%0A );
+%0A%0A await db.collection('hot_search_keywords').insertOne(%7B%0A keyword,%0A type,%0A created_at: now,%0A %7D);
%0A%7D;%0A%0Aexp
|
354b64051c1388ac57ca4060b30cedbb6db69a0b
|
Use copy of config
|
play.js
|
play.js
|
var _ = require('lodash')
var EventEmitter = require('eventemitter2').EventEmitter2
var State = require('./state.js')
var formatEvent = require('./util/events.js').formatEvent
module.exports = function (id, level, opts) {
opts = opts || {size: 700}
function load (level) {
var tmp
var maps = []
level.maps.forEach(function (map) {
map.start.forEach(function (start) {
tmp = _.cloneDeep(map)
tmp.start = [start]
maps.push(tmp)
})
})
var config = level.config
config.stages = maps.length
return {maps: maps, config: config}
}
level = load(level)
var container = document.getElementById(id)
var main = require('./ui/main.js')(container, opts)
var score = require('./ui/score.js')(container)
var stages = require('./ui/stages.js')(container)
var moves = require('./ui/moves.js')(container)
var lives = require('./ui/lives.js')(container)
var message = require('./ui/message.js')(container)
var state = new State(level.config)
var events = new EventEmitter()
var game = require('./game.js')(main.canvas, level.maps[0])
game.events.on(['player', 'collect'], function (event) {
state.score.current += 10
score.update(state.score)
})
game.events.on(['player', 'exit'], function (event) {
state.moves.current -= 1
moves.update(state.moves)
})
game.events.on(['player', 'enter'], function (event) {
if (_.isEqual(event.tile, level.maps[state.stages.current].target)) {
completed()
} else {
failed()
}
})
game.events.onAny(function (event) {
events.emit(this.event, event)
})
function completed () {
events.emit(['map', 'completed'], formatEvent({ map: state.stages.current }))
if (state.stages.current === state.stages.total - 1) {
game.flash()
events.emit(['level', 'completed'], formatEvent({ level: level.config.name }))
setTimeout(function () {
main.hide()
message.show('LEVEL COMPLETE')
}, 1000)
} else {
game.flash()
state.stages.current += 1
stages.update(state.stages)
state.score.current += 1000
state.moves.current = state.moves.total
score.update(state.score)
moves.update(state.moves)
setTimeout(function () {
main.hide()
message.show('YOU DID IT!')
setTimeout(function () {
game.reload(level.maps[state.stages.current])
message.hide()
main.show()
}, 1000)
}, 600)
}
}
function failed () {
if (state.moves.current === 0 & state.lives.current === 1) {
events.emit(['level', 'failed'], formatEvent({ level: level.config.name }))
state.lives.current -= 1
lives.update(state.lives)
main.hide()
message.show('GAME OVER')
}
if (state.moves.current === 0 & state.lives.current > 1) {
main.hide()
message.show('OUT OF STEPS TRY AGAIN')
events.emit(['map', 'failed'], formatEvent({ map: state.stages.current }))
state.lives.current -= 1
lives.update(state.lives)
setTimeout(function () {
state.moves.current = state.moves.total
moves.update(state.moves)
game.moveto(level.maps[state.stages.current].start[0])
message.hide()
main.show()
}, 1000)
}
}
function start () {
if (state.stages.current === 0 && state.lives.current === state.lives.total) {
events.emit(['level', 'started'], formatEvent({ level: level.config.name }))
}
score.update(state.score)
stages.update(state.stages)
moves.update(state.moves)
lives.update(state.lives)
score.show()
stages.show()
moves.show()
lives.show()
main.hide()
message.show('GET READY!')
events.emit(['map', 'started'], formatEvent({ map: state.stages.current }))
setTimeout(function () {
message.hide()
main.show()
}, 1000)
game.start()
}
return {
pause: function () {
game.pause()
},
resume: function () {
game.resume()
},
reload: function (updated) {
level = load(updated)
state.reload(level.config)
game.reload(level.maps[state.stages.current])
start()
},
start: start,
events: events
}
}
|
JavaScript
| 0 |
@@ -500,16 +500,28 @@
onfig =
+_.cloneDeep(
level.co
@@ -524,16 +524,17 @@
l.config
+)
%0A con
|
592c75c538adb74b322547bc889d10e5d935b4ee
|
use meld instead of replaceMethod in Rollover Blurbs
|
src/modules/RolloverBlurbs.js
|
src/modules/RolloverBlurbs.js
|
define('extplug/modules/rollover-blurbs/main', function (require, exports, module) {
var Module = require('extplug/Module'),
fnUtils = require('extplug/util/function'),
rolloverView = require('plug/views/users/userRolloverView'),
UserFindAction = require('plug/actions/users/UserFindAction'),
$ = require('jquery');
var emoji = $('<span />').addClass('emoji-glow')
.append($('<span />').addClass('emoji emoji-1f4dd'));
module.exports = Module.extend({
name: 'Rollover Blurb (Experimental)',
description: 'Show user "Blurb" / bio in rollover popups.',
enable: function () {
this._super();
this.Style({
'.extplug-blurb': {
padding: '10px',
position: 'absolute',
top: '3px',
background: '#282c35',
width: '100%',
'box-sizing': 'border-box',
display: 'none'
},
'.expand .extplug-blurb': {
display: 'block'
}
});
fnUtils.replaceMethod(rolloverView, 'showModal', this.addBlurb);
fnUtils.replaceMethod(rolloverView, 'hide', this.removeBlurb);
},
disable: function () {
this._super();
fnUtils.unreplaceMethod(rolloverView, 'showModal', this.addBlurb);
fnUtils.unreplaceMethod(rolloverView, 'hide', this.removeBlurb);
},
addBlurb: function (showModal, _arg) {
var self = this;
this.$('.extplug-blurb-wrap').remove();
var span = $('<span />').addClass('extplug-blurb');
var div = $('<div />').addClass('info extplug-blurb-wrap').append(span);
if (this.user.get('blurb')) {
show(this.user.get('blurb'));
}
else {
new UserFindAction(this.user.get('id')).on('success', function (user) {
self.user.set('blurb', user.blurb);
show(user.blurb);
});
}
showModal(_arg);
function show(blurb) {
if (blurb) {
self.$('.actions').before(div);
span.append(emoji, ' ' + blurb);
div.height(span[0].offsetHeight + 6);
self.$el.css('top', (parseInt(self.$el.css('top'), 10) - div.height()) + 'px');
}
}
},
removeBlurb: function (hide, _arg) {
this.$('.extplug-blurb-wrap').remove();
hide(_arg);
}
});
});
(extp = window.extp || []).push('extplug/modules/rollover-blurbs/main');
|
JavaScript
| 0 |
@@ -326,16 +326,44 @@
jquery')
+,%0A meld = require('meld')
;%0A%0A var
@@ -1008,36 +1008,44 @@
%0A%0A
-fnUtils.replaceMetho
+this.showAdvice = meld.aroun
d(rollov
@@ -1091,29 +1091,37 @@
-fnUtils.replaceMethod
+this.hideAdivce = meld.before
(rol
@@ -1224,143 +1224,63 @@
-fnUtils.unreplaceMethod(rolloverView, 'showModal', this.addBlurb);%0A fnUtils.unreplaceMethod(rolloverView, 'hide', this
+this.showAdvice.remove();%0A this.hideAdvice
.remove
-Blurb
+(
);%0A
@@ -1302,61 +1302,21 @@
lurb
-: function (showModal, _arg) %7B%0A var self = this;
+(joinpoint) %7B
%0A
@@ -1354,24 +1354,47 @@
).remove();%0A
+ var self = this;%0A
var sp
@@ -1660,16 +1660,27 @@
t('id'))
+%0A
.on('suc
@@ -1690,26 +1690,52 @@
s',
-function (user) %7B%0A
+user =%3E %7B%0A if (user.blurb) %7B%0A
@@ -1782,24 +1782,28 @@
;%0A
+
+
show(user.bl
@@ -1800,32 +1800,48 @@
ow(user.blurb);%0A
+ %7D%0A
%7D);%0A
@@ -1854,22 +1854,33 @@
-showModal(_arg
+return joinpoint.proceed(
);%0A%0A
@@ -2004,19 +2004,19 @@
ji,
-' ' +
+%60 $%7B
blurb
+%7D%60
);%0A
@@ -2196,30 +2196,9 @@
lurb
-: function (hide, _arg
+(
) %7B%0A
@@ -2247,26 +2247,8 @@
();%0A
- hide(_arg);%0A
|
02021354d7a05d8bbbf83b9efd63fc2eb41dae29
|
bump MINIFIED distribution dist/snuggsi.min.js
|
dist/snuggsi.min.js
|
dist/snuggsi.min.js
|
var HTMLElement=function(t){function e(){}return e.prototype=window.HTMLElement.prototype,e}(),DOMTokenList=function(t){for(var e=this,n=function(t){return/{(\w+|#)}/.test(t.textContent)&&(t.text=t.textContent).match(/[^{]+(?=})/g).map(function(n){return(e[n]||(e[n]=[])).push(t)})},r=document.createNodeIterator(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,function(t){return t.attributes&&[].slice.call(t.attributes).map(n)||n(t)},null);r.nextNode(););};DOMTokenList.prototype.bind=function(t){var e=this;Object.keys(this).map(function(t){return e[t].map(function(t){return t.textContent=t.text})&&t}).map(function(n){return e[n].map(function(e){return e.textContent=e.textContent.split("{"+n+"}").join(t[n])})})},function(t){function e(t){var e=new XMLHttpRequest;e.link=t,e.onload=n,e.open("GET",t.href),e.responseType="document",e.send()}function n(t){t=this.link;for(var e=this.response,n=t.nextChild,i=t.content=e.querySelector("template"),c=0,l=document.querySelectorAll(t.id);c<l.length;c+=1){var s=l[c];i&&o.call(s,i)}for(var a=0,u=e.querySelectorAll("style,link,script");a<u.length;a+=1)r(t,u[a],n)}function r(t,e,n){var r=e.getAttribute("as"),o=document.createElement("script"==r?r:e.localName);["id","rel","href","src","textContent","as","defer","crossOrigin"].map(function(t){return e[t]&&t in o&&(o[t]=e[t])}),"style"==r&&(o.rel="stylesheet"),"script"==r&&(o.src=o.href),t.parentNode.insertBefore(o,n)}function o(t){var e=this;t=document.importNode(t,!0);var n;[].slice.call(t.attributes).map(function(t){return!e.attributes[t.name]&&e.setAttribute(t.name,t.value)});for(var r=0,o=e.querySelectorAll("[slot]");r<o.length;r+=1){var i=o[r];(n=(t.content||t).querySelector("slot[name="+i.getAttribute("slot")+"]"))&&n.parentNode.replaceChild(i,n)}return this.innerHTML=t.innerHTML}new MutationObserver(function(t){for(var n=0,r=t;n<r.length;n+=1)for(var i=0,c=r[n].addedNodes;i<c.length;i+=1){var l=c[i];/^p/.test(l.rel)&&/\-/.test(l.id)&&e(l),!!/\-/.test(l.localName)&&(link=document.querySelector("#"+l.localName))&&link.content&&o.call(l,link.content)&&customElements.upgrade(l)}}).observe(document.documentElement,{childList:!0,subtree:!0}),[].slice.call(document.querySelectorAll('[rel^=pre][id~="-"]')).map(e)}();var Template=function(t){t.length&&(t=document.querySelector("template[name="+t+"]"));var e=t.innerHTML,n=t.nextSibling;return t.innerHTML="",t.bind=function(t){for(var r=this,o=document.createElement("section"),i=0,c=r.dependents||[];i<c.length;i+=1){var l=c[i];l.parentNode.removeChild(l)}o.innerHTML=[].concat(t).reduce(function(t,n,r){var o=e;"object"!=typeof n&&(n={self:n}),n["#"]=r;for(var i in n)o=o.split("{"+i+"}").join(n[i]);return t+o},"");for(var s=0,a=r.dependents=[].slice.call(o.childNodes);s<a.length;s+=1){var u=a[s];r.parentNode.insertBefore(u,n)}}.bind(t),t};new(function(){function t(){window.customElements=window.customElements||{},customElements.define=this.define.bind(this),customElements.upgrade=this.upgrade.bind(this)}return t.prototype.define=function(t,e){this[t]=e,[].slice.call(document.getElementsByTagName(t)).map(this.upgrade,this)},t.prototype.upgrade=function(t){this[t.localName]&&Object.setPrototypeOf(t,this[t.localName].prototype).connectedCallback()},t}());var ParentNode=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.select=function(){return(t=this).selectAll.apply(t,arguments)[0];var t},e.prototype.selectAll=function(t){for(var e=[],n=arguments.length-1;n-- >0;)e[n]=arguments[n+1];return t=[].concat(t),[].slice.call(this.querySelectorAll(e.reduce(function(e,n){return e+n+t.shift()},t.shift())))},e}(t)},EventTarget=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.on=function(t,e){this.addEventListener(t,this.renderable(e))},e.prototype.renderable=function(t){var e=this;return function(n){return!1!==t.call(e,n)&&n.defaultPrevented||e.render()}},e}(t)},GlobalEventHandlers=function(t){return function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.onconnect=function(){this.templates=this.selectAll("template[name]").map(Template),this.tokens=new DOMTokenList(this),t.prototype.onconnect&&t.prototype.onconnect.call(this)},e.prototype.reflect=function(t){/^on/.test(t)&&t in HTMLElement.prototype&&this.on(t.substr(2),this[t])},e.prototype.register=function(t,e,n){for(var r=this,o=0,i=[].slice.call(t.attributes);o<i.length;o+=1){var c=i[o];/^on/.test(n=c.name)&&(e=(/{\s*(\w+)/.exec(t[n])||[])[1])&&(t[n]=r.renderable(r[e]))}},e}(t)},Custom=function(t){return function(e){function n(){e.apply(this,arguments)}return e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n,n.prototype.connectedCallback=function(){this.context={},e.prototype.initialize&&e.prototype.initialize.call(this),Object.getOwnPropertyNames(t.prototype).map(this.reflect,this),this.onconnect(),this.render()},n.prototype.render=function(){for(var t=this,n=0,r=t.templates;n<r.length;n+=1){var o=r[n];o.bind(t[o.getAttribute("name")])}this.tokens.bind(this),[this].concat(this.selectAll("*")).map(this.register,this),e.prototype.onidle&&e.prototype.onidle.call(this)},n}(ParentNode(EventTarget(GlobalEventHandlers(t))))},Element=function(t){return function(e){return customElements.define(t+"",Custom(e))}};
|
JavaScript
| 0 |
@@ -2833,23 +2833,16 @@
ion t()%7B
-window.
customEl
|
aa3b2e850299fcddf35683e77cde1efdfc4abee1
|
Make ids unique between buttons
|
spark/components/buttons/vanilla/button.stories.js
|
spark/components/buttons/vanilla/button.stories.js
|
export default {
title: 'Components|Buttons',
};
export const primary = () => (
`
<button class="sprk-c-Button" data-id="button-1">
Button
</button>
`
);
export const secondary = () => (
`
<button class="sprk-c-Button sprk-c-Button--secondary" type="button" data-id="button-1">
Button
</button>
`
);
export const tertiary = () => (
`
<button class="sprk-c-Button sprk-c-Button--tertiary" type="button" data-id="button-2">
Button
</button>
`
);
export const disabled = () => (
`
<button class="sprk-c-Button sprk-is-Disabled" data-id="button-1" disabled>
Button
</button>
`
);
export const spinner = () => (
`
<button class="sprk-c-Button" data-sprk-spinner="click" data-id="button-spinner-1">
<div class="sprk-c-Spinner sprk-c-Spinner--circle"></div>
</button>
`
);
spinner.story = {
name: 'Spinner',
};
export const fullWidthAtSmallViewport = () => (
`
<button class="sprk-c-Button sprk-c-Button--full@s" type="button" data-id="button-1">
Button
</button>
`
);
fullWidthAtSmallViewport.story = {
name: 'Full Width at Small Viewport',
};
export const fullWidthAtExtraSmallViewport = () => (
`
<button class="sprk-c-Button sprk-c-Button--full@xs" type="button" data-id="button-90">
Button
</button>
`
);
fullWidthAtExtraSmallViewport.story = {
name: 'Full Width at Extra Small Viewport',
};
|
JavaScript
| 0.000587 |
@@ -127,25 +127,31 @@
-id=%22button-
-1
+primary
%22%3E%0A But
@@ -294,33 +294,41 @@
data-id=%22button-
-1
+secondary
%22%3E%0A Button%0A
@@ -475,9 +475,16 @@
ton-
-2
+tertiary
%22%3E%0A
@@ -616,17 +616,24 @@
%22button-
-1
+disabled
%22 disabl
@@ -783,18 +783,16 @@
-spinner
--1
%22%3E%0A %3C
@@ -1048,9 +1048,16 @@
ton-
-1
+full-smv
%22%3E%0A
@@ -1310,10 +1310,17 @@
ton-
-90
+full-xsmv
%22%3E%0A
|
0fdc1140dd3956e72c38b1bcee517eff7ff5de6c
|
Add `Database.getCount` function
|
js/modules/database.js
|
js/modules/database.js
|
/* global indexedDB */
// Module for interacting with IndexedDB without Backbone IndexedDB adapter
// and using promises. Revisit use of `idb` dependency as it might cover
// this functionality.
exports.open = (name, version) => {
const request = indexedDB.open(name, version);
return new Promise((resolve, reject) => {
request.onblocked = () =>
reject(new Error('Database blocked'));
request.onupgradeneeded = event =>
reject(new Error('Unexpected database upgrade required:' +
`oldVersion: ${event.oldVersion}, newVersion: ${event.newVersion}`));
request.onerror = event =>
reject(event.target.error);
request.onsuccess = (event) => {
const connection = event.target.result;
resolve(connection);
};
});
};
exports.completeTransaction = transaction =>
new Promise((resolve, reject) => {
transaction.addEventListener('abort', event => reject(event.target.error));
transaction.addEventListener('error', event => reject(event.target.error));
transaction.addEventListener('complete', () => resolve());
});
exports.getVersion = async (name) => {
const connection = await exports.open(name);
const { version } = connection;
connection.close();
return version;
};
|
JavaScript
| 0.000004 |
@@ -190,16 +190,63 @@
ality.%0A%0A
+const isObject = require('lodash/isObject');%0A%0A%0A
exports.
@@ -1289,12 +1289,359 @@
version;%0A%7D;%0A
+%0Aexports.getCount = async (%7B store %7D = %7B%7D) =%3E %7B%0A if (!isObject(store)) %7B%0A throw new TypeError('%22store%22 is required');%0A %7D%0A%0A const request = store.count();%0A return new Promise((resolve, reject) =%3E %7B%0A request.onerror = event =%3E%0A reject(event.target.error);%0A request.onsuccess = event =%3E%0A resolve(event.target.result);%0A %7D);%0A%7D;%0A
|
a7555b30a25b63157b30fc80656e55813d307c68
|
Fix eslint
|
js/views/screenview.js
|
js/views/screenview.js
|
/* global Marionette */
/**
*
* @copyright Copyright (c) 2019, Daniel Calviño Sánchez ([email protected])
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
(function(OCA, Marionette) {
'use strict';
OCA.SpreedMe = OCA.SpreedMe || {};
OCA.Talk = OCA.Talk || {};
OCA.SpreedMe.Views = OCA.SpreedMe.Views || {};
OCA.Talk.Views = OCA.Talk.Views || {};
var ScreenView = Marionette.View.extend({
tagName: 'div',
className: 'screenContainer',
id: function() {
return this.options.peerId? 'container_' + this.options.peerId + '_screen_incoming': 'localScreenContainer';
},
template: function(context) {
// OCA.Talk.Views.Templates may not have been initialized when this
// view is initialized, so the template can not be directly
// assigned.
return OCA.Talk.Views.Templates['screenview'](context);
},
ui: {
'video': 'video',
'nameIndicator': '.nameIndicator',
},
initialize: function(options) {
this.render();
if (!options.peerId) {
this.getUI('nameIndicator').text(t('spreed', 'Your screen'));
}
},
setParticipantName: function(participantName) {
if (!this.options.peerId) {
return;
}
var nameIndicator;
if (participantName) {
nameIndicator = t('spreed', "{participantName}'s screen", {participantName: participantName});
} else {
nameIndicator = t('spreed', "Guest's screen")
}
this.getUI('nameIndicator').text(nameIndicator);
},
/**
* Sets the element with the video stream.
*
* @param HTMLVideoElement|null videoElement the element to set, or null
* to remove the current one.
*/
setVideoElement: function(videoElement) {
this.getUI('video').remove();
if (videoElement) {
this.$el.prepend(videoElement);
videoElement.oncontextmenu = function() {
return false;
};
}
this.bindUIElements();
},
});
OCA.Talk.Views.ScreenView = ScreenView;
})(OCA, Marionette);
|
JavaScript
| 0.000001 |
@@ -2050,16 +2050,17 @@
screen%22)
+;
%0A%09%09%09%7D%0A%0A%09
@@ -2184,16 +2184,17 @@
@param
+%7B
HTMLVide
@@ -2206,16 +2206,17 @@
ent%7Cnull
+%7D
videoEl
|
fdcca2d52ff0e105100856875f8e2338a97f221c
|
Add text input for all user attributes, working
|
simul/app/components/register.js
|
simul/app/components/register.js
|
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TextInput,
TouchableHighlight,
} from 'react-native';
class Register extends Component{
constructor() {
super();
this.state = {
name: "",
username: "",
location: "",
bio: "",
preferred_contact: "",
skills: "",
seeking: "",
}
}
render() {
return (
<View style={styles.container}>
<Text>Register with Simul today</Text>
<TextInput
onChangeText={ (val)=> this.setState({name: val}) }
style={styles.input} placeholder="Name"
/>
<Text>
{this.state.name}
</Text>
</View>
);
}
};
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
title: {
fontSize: 20,
alignSelf: 'center',
margin: 40
},
input: {
height: 50,
marginTop: 10,
padding: 4,
fontSize: 15,
borderWidth: 1,
borderColor: '#48bbec'
},
});
module.exports = Register;
|
JavaScript
| 0 |
@@ -616,16 +616,165 @@
Name%22%0A
+ /%3E%0A%0A %3CTextInput%0A onChangeText=%7B (val)=%3E this.setState(%7Busername: val%7D) %7D%0A style=%7Bstyles.input%7D placeholder=%22Username%22%0A
@@ -776,16 +776,17 @@
/%3E%0A
+%0A
@@ -794,54 +794,957 @@
Text
-%3E%0A %7B
+Input%0A onChangeText=%7B (val)=%3E this.setState(%7Blocation: val%7D) %7D%0A style=%7Bstyles.input%7D placeholder=%22Location%22%0A /%3E%0A%0A %3CTextInput%0A onChangeText=%7B (val)=%3E
this.s
+etS
tate
-.name%7D%0A %3C/Text%3E%0A
+(%7Bbio: val%7D) %7D%0A style=%7Bstyles.input%7D placeholder=%22Bio%22%0A /%3E%0A%0A %3CTextInput%0A onChangeText=%7B (val)=%3E this.setState(%7Bpreferred_contact: val%7D) %7D%0A style=%7Bstyles.input%7D placeholder=%22Preferred_contact%22%0A /%3E%0A%0A %3CTextInput%0A onChangeText=%7B (val)=%3E this.setState(%7Bskills: val%7D) %7D%0A style=%7Bstyles.input%7D placeholder=%22Skills%22%0A /%3E%0A%0A%0A %3CTextInput%0A onChangeText=%7B (val)=%3E this.setState(%7Bseeking: val%7D) %7D%0A style=%7Bstyles.input%7D placeholder=%22Seeking%22%0A /%3E%0A%0A %3CTouchableHighlight onPress=%7Bthis.onRegisterPressed.bind(this)%7D style=%7Bstyles.button%7D%3E%0A %3CText style=%7Bstyles.buttonText%7D%3E%0A Register%0A %3C/Text%3E%0A %3C/TouchableHighlight%3E
%0A%0A
|
2c96699aed5e10fb3bb31b152c4fc3ae8443f268
|
convert timestamps to ISO 8601 date string (#2099)
|
packages/gatsby-source-medium/src/gatsby-node.js
|
packages/gatsby-source-medium/src/gatsby-node.js
|
const axios = require(`axios`)
const crypto = require(`crypto`)
const fetch = username => {
const url = `https://medium.com/${username}/latest?format=json`
return axios.get(url)
}
const prefix = `])}while(1);</x>`
const strip = payload => payload.replace(prefix, ``)
exports.sourceNodes = async ({ boundActionCreators }, { username }) => {
const { createNode } = boundActionCreators
try {
const result = await fetch(username)
const json = JSON.parse(strip(result.data))
const { posts } = json.payload
const collectionKeys = Object.keys(json.payload.references.Collection)
const userKeys = Object.keys(json.payload.references.User)
const importableResources = [
userKeys.map(key => json.payload.references.User[key]),
posts,
collectionKeys.map(key => json.payload.references.Collection[key]),
]
const resources = Array.prototype.concat(...importableResources)
resources.map(resource => {
const digest = crypto
.createHash(`md5`)
.update(JSON.stringify(resource))
.digest(`hex`)
const links =
resource.type === `Post`
? {
author___NODE: resource.creatorId,
}
: resource.type === `User`
? {
posts___NODE: posts
.filter(post => post.creatorId === resource.userId)
.map(post => post.id),
}
: {}
const node = Object.assign(
resource,
{
id: resource.id ? resource.id : resource.userId,
parent: `__SOURCE__`,
children: [],
internal: {
type: `Medium${resource.type}`,
contentDigest: digest,
},
},
links
)
createNode(node)
})
} catch (error) {
console.error(error)
process.exit(1)
}
}
|
JavaScript
| 0.000037 |
@@ -214,16 +214,433 @@
;%3C/x%3E%60%0A%0A
+const convertTimestamps = (nextObj, prevObj, prevKey) =%3E %7B%0A if (typeof nextObj === 'object') %7B%0A Object.keys(nextObj).map(key =%3E convertTimestamps(nextObj%5Bkey%5D, nextObj, key));%0A %7D else %7B%0A if (typeof nextObj === 'number' && nextObj %3E%3E 0 !== nextObj) %7B%0A const date = new Date(nextObj);%0A if (date.getTime() === nextObj) %7B%0A prevObj%5BprevKey%5D = date.toISOString().slice(0, 10);%0A %7D%0A %7D%0A %7D%0A%7D%0A%0A
const st
@@ -1367,16 +1367,51 @@
ce =%3E %7B%0A
+ convertTimestamps(resource)%0A%0A
co
|
2e454a9363b01cff1ee6e4ac59e17e473295e645
|
fix language dropdown
|
imports/api/languages/service.js
|
imports/api/languages/service.js
|
import { Meteor } from 'meteor/meteor';
import Users from '/imports/api/users/Users';
import SystemLanguages from '/imports/framework/Constants/SystemLanguages';
Meteor.methods({
'language.get': () => {
return Meteor.user().profile.language;
},
'language.update': ({}, {}, language) => {
const profileLanguage = Meteor.user().profile.language;
const isSystemLanguage = SystemLanguages.allowedValues.indexOf(language) > -1;
if (profileLanguage && isSystemLanguage) {
const userId = Meteor.userId();
Users.persistence.update(userId, 'profile.language', language);
}
}
});
|
JavaScript
| 0.000072 |
@@ -210,16 +210,34 @@
return
+ %7B%0A language:
Meteor.
@@ -255,24 +255,30 @@
ile.language
+%0A %7D
;%0A %7D,%0A 'la
|
ccde4a5a69aef61655b830d043bc553c3a718c4b
|
Fix key warning
|
redef/patron-client/src/frontend/components/Publications.js
|
redef/patron-client/src/frontend/components/Publications.js
|
import React, { PropTypes } from 'react'
import { defineMessages, FormattedMessage } from 'react-intl'
import Publication from './Publication'
import PublicationInfo from './PublicationInfo'
import { getId } from '../utils/uriParser'
export default React.createClass({
propTypes: {
publications: PropTypes.array.isRequired,
expandSubResource: PropTypes.func.isRequired,
locationQuery: PropTypes.object.isRequired
},
contextTypes: {
router: React.PropTypes.object
},
componentWillMount () {
if (this.props.publications.length === 1) {
this.props.expandSubResource(this.props.publications[ 0 ].id, this.context.router)
}
},
renderEmpty () {
return (
<h2 data-automation-id='no_publications'>
<FormattedMessage {...messages.noPublications} />
</h2>
)
},
getArrow (column) {
return [ 0, 1, 2 ].map(number =>
<div className='col col-1-3'>{number === column ? <div className='triangle-up'/> : ''} </div>
)
},
renderPublications () {
let publications = [ ...this.props.publications ]
let threeAndThreePublications = []
while (publications.length > 0) {
threeAndThreePublications.push(publications.splice(0, 3))
}
let showMore
return (
<div>
{threeAndThreePublications.map((publications, row) => {
let output = [ <div className='row'>{publications.map(publication => <Publication
key={publication.id}
expandSubResource={this.props.expandSubResource}
publication={publication}/>)}</div> ]
let showMorePublication = publications.find(publication => getId(publication.uri) === this.props.locationQuery.showMore)
if (showMorePublication) {
showMore = {
publication: showMorePublication,
row: row,
column: publications.indexOf(showMorePublication)
}
}
if (showMore && row === showMore.row) {
output.push(<div className='row'>
{this.getArrow(showMore.column)}
<div className='col'>
<PublicationInfo expandSubResource={this.props.expandSubResource}
publication={showMore.publication}/>
</div>
</div>
)
}
return output
})
}
</div>
)
},
render () {
return (
<div id='publications' className='panel row'>
<div className='panel-header'>
<span><strong><FormattedMessage {...messages.numberOfPublications}
values={{numberOfPublications: this.props.publications.length}}/></strong></span>
<div className='panel-arrow panel-open'></div>
</div>
<div className='col'>
{this.props.publications.length > 0 ? this.renderPublications() : this.renderEmpty()}
</div>
</div>
)
}
})
const messages = defineMessages({
title: {
id: 'Publications.title', description: 'Title of the publication', defaultMessage: 'title'
},
publicationYear: {
id: 'Publications.publicationYear',
description: 'Publication year of the publication',
defaultMessage: 'publication year'
},
language: {
id: 'Publications.language', description: 'Language of the publication', defaultMessage: 'language'
},
format: {
id: 'Publications.format', description: 'Format of the publication', defaultMessage: 'format'
},
copies: {
id: 'Publications.copies', description: 'Copies of the publication', defaultMessage: 'copies'
},
noPublications: {
id: 'Publications.noPublications',
description: 'Text displayed when no publications',
defaultMessage: 'We have no publications'
},
numberOfPublications: {
id: 'Publications.numberOfPublications',
description: 'The number of publications',
defaultMessage: 'Publications ({numberOfPublications})'
}
})
|
JavaScript
| 0.000004 |
@@ -881,32 +881,57 @@
er =%3E%0A %3Cdiv
+ key=%7B%60column-$%7Bnumber%7D%60%7D
className='col
@@ -939,16 +939,25 @@
ol-1-3'%3E
+%0A
%7Bnumber
@@ -1387,24 +1387,43 @@
put = %5B %3Cdiv
+ key=%7B%60row-$%7Brow%7D%60%7D
className='
@@ -2062,24 +2062,54 @@
ssName='row'
+ key=%7BshowMore.publication.id%7D
%3E%0A
|
2108a85301d981b4e5131af9554212f64cc0b5cd
|
Add a mount test
|
web/src/js/components/Dashboard/__tests__/NewUserTourComponent.test.js
|
web/src/js/components/Dashboard/__tests__/NewUserTourComponent.test.js
|
/* eslint-env jest */
import React from 'react'
import {
shallow
} from 'enzyme'
import { cloneDeep } from 'lodash/lang'
import Joyride from 'react-joyride'
import Dialog from '@material-ui/core/Dialog'
import DialogTitle from '@material-ui/core/DialogTitle'
import localStorageMgr from 'js/utils/localstorage-mgr'
import { STORAGE_NEW_USER_HAS_COMPLETED_TOUR } from 'js/constants'
jest.mock('js/utils/localstorage-mgr')
const mockProps = {
user: {}
}
const mockJoyrideCallbackData = {
action: 'next',
controlled: false,
index: 1, // current step in the tour
lifecycle: 'tooltip',
size: 3,
status: 'running',
step: {
// step data here
},
type: 'step:before'
}
describe('New user tour component', () => {
it('renders without error', () => {
const NewUserTourComponent = require('js/components/Dashboard/NewUserTourComponent').default
shallow(
<NewUserTourComponent {...mockProps} />
)
})
it('shows the intro dialog', () => {
const NewUserTourComponent = require('js/components/Dashboard/NewUserTourComponent').default
const wrapper = shallow(
<NewUserTourComponent {...mockProps} />
).dive()
const introModal = wrapper.find(Dialog).first()
expect(introModal.prop('open')).toBe(true)
expect(introModal
.find(DialogTitle).render().text())
.toBe('Your tabs are changing the world!')
})
it('does not run the Joyride tour until clicking through the first modal', () => {
const NewUserTourComponent = require('js/components/Dashboard/NewUserTourComponent').default
const wrapper = shallow(
<NewUserTourComponent {...mockProps} />
).dive()
expect(wrapper.find(Joyride).first().prop('run')).toBe(false)
// Mock a button click on the intro modal
// It would be better to simulate a click on the button,
// but that's difficult with the old Material UI dialog.
// @material-ui-1-todo: find the dialog button and simulate a
// click instead of calling the method directly.
wrapper.instance().introModalButtonClick()
wrapper.update()
expect(wrapper.find(Joyride).first().prop('run')).toBe(true)
})
it('does not initially show the final dialog', () => {
const NewUserTourComponent = require('js/components/Dashboard/NewUserTourComponent').default
const wrapper = shallow(
<NewUserTourComponent {...mockProps} />
).dive()
const finalModal = wrapper.find(Dialog).last()
expect(finalModal.prop('open')).toBe(false)
expect(finalModal
.find(DialogTitle).render().text())
.toBe("We're thrilled to have you!")
})
it('calls localStorage to mark that the user has completed the tour', () => {
const NewUserTourComponent = require('js/components/Dashboard/NewUserTourComponent').default
const wrapper = shallow(
<NewUserTourComponent {...mockProps} />
).dive()
const joyrideComponent = wrapper.find(Joyride).first()
const joyrideCallbackFn = joyrideComponent.prop('callback')
// Mock that Joyride calls its callback to indicate the
// tour is complete.
const callbackData = cloneDeep(mockJoyrideCallbackData)
callbackData.status = 'finished'
joyrideCallbackFn(callbackData)
expect(localStorageMgr.setItem)
.toHaveBeenCalledWith(STORAGE_NEW_USER_HAS_COMPLETED_TOUR, 'true')
})
})
|
JavaScript
| 0.000001 |
@@ -51,16 +51,25 @@
mport %7B%0A
+ mount,%0A
shallo
@@ -938,24 +938,227 @@
)%0A %7D)%0A%0A
+ it('mounts without error', () =%3E %7B%0A const NewUserTourComponent = require('js/components/Dashboard/NewUserTourComponent').default%0A mount(%0A %3CNewUserTourComponent %7B...mockProps%7D /%3E%0A )%0A %7D)%0A%0A
it('shows
|
b5267a0713ef57854be5f5999593d96119da7016
|
verify permissions with dictybase resource
|
src/utils/apiClasses.js
|
src/utils/apiClasses.js
|
// @flow
export class JsonAPI {
json: Object
links: Object
relationships: Object
constructor(json: Object) {
this.json = json
}
getAttributes() {
return this.json.data.attributes
}
getId() {
return this.json.data.id
}
getRelationships() {
return this.json.data.relationships
}
}
export class AuthAPI extends JsonAPI {
json: Object
// checks if user is currently authenticated
isAuthenticated() {
if (this.json.isAuthenticated === true) {
return true
}
return false
}
// gets JWT from currently logged in user
getToken() {
return this.json.token
}
// gets provider (i.e. google) from logged in user
getProvider() {
return this.json.provider
}
// gets user data
getUser() {
return this.json.user
}
}
export class AuthenticatedUser extends JsonAPI {
json: Object
// gets the first and last name of logged in user
getFullName() {
return `${this.json.data.attributes.first_name} ${
this.json.data.attributes.last_name
}`
}
// gets capitalized version of user's role
getRoles() {
if (this.json.roles) {
const rolesArr = this.json.roles
// return the role and capitalize the first letter
const role = rolesArr[0].attributes.role
return role.charAt(0).toUpperCase() + role.substr(1)
} else {
return ""
}
}
// checks if user can overwrite current content
canOverwrite = (id: string) => {
if (id === this.json.data.id || this.getRoles() === "Superuser") {
return true
} else {
return null
}
}
}
export class PermissionAPI extends JsonAPI {
json: Object
// gets lists of all resources from user's permissions
getResources() {
if (this.json.permissions) {
this.json.permissions.forEach(item => {
return item.attributes.resource
})
} else {
return
}
}
// gets full list of user's permissions
getPermissions() {
if (this.json.permissions) {
this.json.permissions.forEach(item => {
return item.attributes.permission
})
} else {
return
}
}
// this verifies that the user has the right resource
// and permission to edit content
verifyPermissions = (perm: string, resource: string) => {
if (this.json.permissions > 0) {
return this.json.permissions.filter(
item =>
item.attributes.permission === "admin" ||
(item.attributes.permission === perm &&
item.attributes.resource === resource)
)
} else {
return null
}
}
}
export class RoleAPI extends JsonAPI {
json: Object
// get full list of user's roles
getRoles() {
if (this.json.roles) {
this.json.roles.forEach(item => {
return item.attributes.role
})
} else {
return
}
}
// checks if user has specified role
checkRoles = (role: string) => {
if (this.json.roles) {
return this.json.roles.filter(item => item.attributes.role === role)
} else {
return
}
}
}
export class ContentAPI extends AuthenticatedUser {
json: Object
// gets the user ID for person who last updated this content
getUser() {
if (this.json.data) {
return this.json.data.attributes.updated_by
} else {
return
}
}
}
|
JavaScript
| 0 |
@@ -2,16 +2,69 @@
/ @flow%0A
+import %7B MAIN_RESOURCE %7D from %22constants/resources%22%0A%0A
export c
@@ -2348,16 +2348,23 @@
missions
+.length
%3E 0) %7B%0A
@@ -2409,27 +2409,18 @@
ter(
-%0A
item =%3E
-%0A
+ %7B%0A
@@ -2565,23 +2565,133 @@
esource)
+ %7C%7C
%0A
+ (item.attributes.permission === perm &&%0A item.attributes.resource === MAIN_RESOURCE)%0A %7D
)%0A %7D
|
4f988130a0dca156e0438c0c65c59d7e58e6690e
|
Add TODOs
|
web/src/js/components/Settings/__tests__/SettingsPageComponent.test.js
|
web/src/js/components/Settings/__tests__/SettingsPageComponent.test.js
|
/* eslint-env jest */
import React from 'react'
import { shallow } from 'enzyme'
import { Route, Switch } from 'react-router-dom'
import SettingsPage from 'js/components/Settings/SettingsPageComponent'
// import AccountView from 'js/components/Settings/Account/AccountView'
// import BackgroundSettingsView from 'js/components/Settings/Background/BackgroundSettingsView'
// import ErrorMessage from 'js/components/General/ErrorMessage'
// import Logo from 'js/components/Logo/Logo'
// import ProfileStatsView from 'js/components/Settings/Profile/ProfileStatsView'
// import ProfileDonateHearts from 'js/components/Settings/Profile/ProfileDonateHeartsView'
// import ProfileInviteFriend from 'js/components/Settings/Profile/ProfileInviteFriendView'
import SettingsMenuItem from 'js/components/Settings/SettingsMenuItem'
import WidgetsSettingsView from 'js/components/Settings/Widgets/WidgetsSettingsView'
jest.mock('react-router-dom')
jest.mock('js/components/Settings/Account/AccountView')
jest.mock('js/components/Settings/Background/BackgroundSettingsView')
jest.mock('js/components/General/ErrorMessage')
jest.mock('js/components/Logo/Logo')
jest.mock('js/components/Settings/Profile/ProfileStatsView')
jest.mock('js/components/Settings/Profile/ProfileDonateHeartsView')
jest.mock('js/components/Settings/Profile/ProfileInviteFriendView')
jest.mock('js/components/Settings/SettingsMenuItem')
jest.mock('js/components/Settings/Widgets/WidgetsSettingsView')
jest.mock('js/components/General/withUser')
afterEach(() => {
jest.clearAllMocks()
})
const getMockProps = () => ({})
describe('withUser HOC in SettingsPage', () => {
beforeEach(() => {
jest.resetModules()
})
it('is called with the expected options', () => {
const withUser = require('js/components/General/withUser').default
/* eslint-disable-next-line no-unused-expressions */
require('js/components/Settings/SettingsPageComponent').default
expect(withUser).toHaveBeenCalledWith()
})
it('wraps the SettingsPage component', () => {
const {
__mockWithUserWrappedFunction,
} = require('js/components/General/withUser')
/* eslint-disable-next-line no-unused-expressions */
require('js/components/Settings/SettingsPageComponent').default
const wrappedComponent = __mockWithUserWrappedFunction.mock.calls[0][0]
expect(wrappedComponent.name).toEqual('SettingsPage')
})
})
describe('SettingsPage', () => {
it('renders without error', () => {
const mockProps = getMockProps()
shallow(<SettingsPage {...mockProps} />)
.dive()
.dive()
})
it('renders the expected side menu items', () => {
const mockProps = getMockProps()
const wrapper = shallow(<SettingsPage {...mockProps} />)
.dive()
.dive()
const menuItems = wrapper.find(SettingsMenuItem)
const expectedMenuItems = [
'Widgets',
'Background',
'Your Stats',
'Donate Hearts',
'Invite Friends',
'Account',
]
menuItems.forEach((menuItem, index) => {
expect(menuItem.prop('children')).toEqual(expectedMenuItems[index])
})
})
it('includes a WidgetsSettingsView route', () => {
const mockProps = getMockProps()
const wrapper = shallow(<SettingsPage {...mockProps} />)
.dive()
.dive()
const routeElem = wrapper
.find(Switch)
.find(Route)
.filterWhere(elem => elem.prop('path') === '/newtab/settings/widgets/')
expect(routeElem.exists()).toBe(true)
})
it('renders the expected WidgetsSettingsView component with the expected props', () => {
const mockProps = getMockProps()
const wrapper = shallow(<SettingsPage {...mockProps} />)
.dive()
.dive()
const routeElem = wrapper
.find(Switch)
.find(Route)
.filterWhere(elem => elem.prop('path') === '/newtab/settings/widgets/')
expect(routeElem.exists()).toBe(true)
const ThisRouteComponent = routeElem.prop('render')
const ThisRouteComponentElem = shallow(
<ThisRouteComponent fakeProp={'abc'} />
)
expect(ThisRouteComponentElem.type()).toEqual(WidgetsSettingsView)
expect(ThisRouteComponentElem.prop('fakeProp')).toEqual('abc')
expect(ThisRouteComponentElem.prop('showError')).toEqual(
expect.any(Function)
)
})
})
|
JavaScript
| 0.000001 |
@@ -4268,16 +4268,317 @@
)%0A )%0A %7D)
+%0A%0A // TODO:%0A // - add tests for remaining route components%0A // - add tests for existence of the Redirect components%0A // - add tests for the showError prop functionality%0A // - pass authUser to WidgetsSettingsView and test for that prop; remove%0A // the withUser HOC from WidgetsSettingsView
%0A%7D)%0A
|
215fe3375442f81c74d76f345f5ddb30de0d793e
|
Use config option for footer
|
core/src/main/public/static/js/find/app/page/search/filters/parametric/parametric-field-view.js
|
core/src/main/public/static/js/find/app/page/search/filters/parametric/parametric-field-view.js
|
define([
'backbone',
'underscore',
'jquery',
'i18n!find/nls/bundle',
'js-whatever/js/list-view',
'find/app/util/collapsible',
'find/app/page/search/filters/parametric/parametric-select-modal',
'find/app/page/search/filters/parametric/parametric-value-view'
], function(Backbone, _, $, i18n, ListView, Collapsible, ParametricModal, ValueView) {
'use strict';
var MAX_SIZE = 5;
var ValuesView = Backbone.View.extend({
className: 'table parametric-fields-table',
tagName: 'table',
seeAllButtonTemplate: _.template('<tr class="show-all clickable"><td></td><td> <span class="toggle-more-text text-muted"><%-i18n["app.seeAll"]%></span></td></tr>'),
events: {
'click .show-all': function() {
new ParametricModal({
collection: this.model.fieldValues,
currentFieldGroup: this.model.id,
parametricCollection: this.parametricCollection,
parametricDisplayCollection: this.parametricDisplayCollection,
selectedParametricValues: this.selectedParametricValues
});
}
},
initialize: function(options) {
this.parametricDisplayCollection = options.parametricDisplayCollection;
this.selectedParametricValues = options.selectedParametricValues;
this.parametricCollection = options.parametricCollection;
this.listView = new ListView({
collection: this.collection,
ItemView: ValueView,
maxSize: MAX_SIZE,
tagName: 'tbody',
collectionChangeEvents: {
count: 'updateCount',
selected: 'updateSelected'
}
});
},
render: function() {
this.$el.empty().append(this.listView.render().$el);
this.$('tbody').append(this.seeAllButtonTemplate({i18n:i18n}));
},
remove: function() {
this.listView.remove();
Backbone.View.prototype.remove.call(this);
}
});
return Backbone.View.extend({
className: 'animated fadeIn',
subtitleTemplate: _.template('<span class="selection-length"><%-length%></span> <%-i18n["app.selected"]%> <i class="hp-icon hp-warning selected-warning hidden"></i>'),
initialize: function(options) {
this.$el.attr('data-field', this.model.id);
this.$el.attr('data-field-display-name', this.model.get('displayName'));
this.parametricDisplayCollection = options.parametricDisplayCollection;
this.selectedParametricValues = options.selectedParametricValues;
this.parametricCollection = options.parametricCollection;
var collapsed;
if (_.isFunction(options.collapsed)) {
collapsed = options.collapsed(options.model);
}
else {
collapsed = options.collapsed;
}
this.collapsible = new Collapsible({
collapsed: collapsed,
title: this.model.get('displayName') + ' (' + this.model.fieldValues.length +')',
subtitle: this.subtitleTemplate({
i18n: i18n,
length: this.getFieldSelectedValuesLength()
}),
view: new ValuesView({
collection: this.model.fieldValues,
model: this.model,
parametricCollection:this.parametricCollection,
parametricDisplayCollection: this.parametricDisplayCollection,
selectedParametricValues: this.selectedParametricValues
})
});
this.listenTo(this.selectedParametricValues, 'update', function() {
this.collapsible.$('.selection-length').text(this.getFieldSelectedValuesLength());
this.toggleWarning();
});
this.listenTo(this.collapsible, 'show', function() {
this.collapsible.toggleSubtitle(true);
});
this.listenTo(this.collapsible, 'hide', function() {
this.toggleSubtitle();
});
this.listenTo(this.collapsible, 'toggle', function(newState) {
this.trigger('toggle', this.model, newState)
})
},
render: function() {
this.$el.empty().append(this.collapsible.$el);
this.collapsible.render();
this.$warning = this.collapsible.$('.selected-warning');
this.$warning.tooltip({
title: i18n['search.parametric.selected.notAllVisible']
});
this.toggleSubtitle();
this.toggleWarning();
},
toggleSubtitle: function() {
this.collapsible.toggleSubtitle(this.getFieldSelectedValuesLength() !== 0);
},
toggleWarning: function() {
var currentValues = this.selectedParametricValues.where({field: this.model.id});
var toggle = true;
if(currentValues.length > 0) {
var firstFiveValues = this.model.fieldValues.chain()
.first(MAX_SIZE)
.pluck('id')
.value();
var fieldsArray = _.invoke(currentValues, 'get', 'value');
toggle = !_.difference(fieldsArray, firstFiveValues).length;
}
this.$warning.toggleClass('hidden', toggle);
},
getFieldSelectedValuesLength: function() {
return this.selectedParametricValues.where({field: this.model.id}).length;
},
remove: function() {
this.$warning.tooltip('destroy');
this.collapsible.remove();
Backbone.View.prototype.remove.call(this);
}
});
});
|
JavaScript
| 0 |
@@ -1544,32 +1544,100 @@
his.collection,%0A
+ footerHtml: this.seeAllButtonTemplate(%7Bi18n:i18n%7D),%0A
@@ -2000,85 +2000,8 @@
el);
-%0A%0A this.$('tbody').append(this.seeAllButtonTemplate(%7Bi18n:i18n%7D));
%0A
|
97652be6a9a2c06391dd1afaf240abc7ce5c419d
|
Fix module resolving in eslint for vue + more attr per element
|
packages/eslint-config/vue.js
|
packages/eslint-config/vue.js
|
// extra settings for Vue components
module.exports = {
extends: [
'@wearegenki/eslint-config',
'plugin:vue/recommended',
],
plugins: [
'vue',
],
parser: 'vue-eslint-parser',
parserOptions: {
parser: 'babel-eslint',
ecmaVersion: 8,
sourceType: 'module',
ecmaFeatures: {
experimentalObjectRestSpread: true,
},
},
env: {
es6: true,
browser: true,
},
rules: {
'vue/max-attributes-per-line': ['error', {
singleline: 5, // length of the line is more important than # attributes
multiline: {
max: 1,
allowFirstLine: false,
},
}],
},
};
|
JavaScript
| 0 |
@@ -406,16 +406,139 @@
e,%0A %7D,%0A
+ settings: %7B%0A 'import/resolver': %7B%0A webpack: %7B%0A config: 'build/webpack.base.conf.js',%0A %7D,%0A %7D,%0A %7D,%0A
rules:
@@ -609,9 +609,9 @@
ne:
-5
+6
, //
|
a519b52819bb802b74eef817aec4d75ff516e90e
|
make lint free
|
src/grunt-alias-npm-submodules.js
|
src/grunt-alias-npm-submodules.js
|
'use strict';
var
cwd = process.cwd(),
path = require('path'),
DIRECTORY_SEPARATOR = path.sep;
module.exports = function ( $grunt ) {
function _writeAliasFile ( $data ) {
var
_fileDest = $data.dir,
_fileSrc = $data.full,
_index,
_nesting = _fileDest.length,
_prefix = '.'
+ DIRECTORY_SEPARATOR;
_fileDest.push( $data.base ),
_fileDest = _prefix
+ _fileDest.join( DIRECTORY_SEPARATOR );
if( _nesting > 0 ) {
_prefix = '.'
+ _prefix;
for( _index = 1; _index < _nesting; _index ++ ) {
_prefix += _prefix;
}
}
$grunt.log.writeln(
'Create forwarding from '
+ _fileDest['cyan']
+ ' to '
+ (
'./'
+ _fileSrc
)['cyan']
+ ' ...'
),
$grunt.file.write(
_fileDest,
"module.exports = require('"
+ _prefix
+ _fileSrc.replace(
$data.ext,
''
)
+ "');"
);
}
return $grunt.registerMultiTask(
'alias',
'Create forwardings to submodules that are not located in the topmost directory',
function aliasNpmSubmodules () {
var
_count = 0,
_filesSrc = this.filesSrc,
_options = this.options(
{
'levels': 1
}
),
_levels = Number( _options.levels );
if(
isNaN( _levels )
|| _levels < 1
) {
_levels = 1;
}
if( Array.isArray(_filesSrc) && _filesSrc.length > 0 ) {
_filesSrc.forEach(
function ( $file, $index, $files ) {
var
_dir,
_parsedPath;
$file = path.normalize( $file );
if( path.isAbsolute($file) ) {
$file = path.relative(
cwd,
$file
);
}
_parsedPath = path.parse( $file );
if(
typeof _parsedPath !== 'object'
|| _parsedPath === null
||
typeof _parsedPath.dir !== 'string'
) {
return;
}
_parsedPath.dir = _parsedPath.dir.split( DIRECTORY_SEPARATOR );
if(
!Array.isArray( _dir = _parsedPath.dir )
|| _dir.length < 1
) {
return;
}
_parsedPath.dir = _dir.slice(
_levels > _dir.length ?
_dir.length : _levels
),
_parsedPath.full = $file,
_writeAliasFile( _parsedPath ),
_count ++;
}
),
$grunt.log.writeln(),
$grunt.log.ok(
'Successfully aliased '
+ String( _count )['green']
+ ' npm module'
+ (
_count === 1 ?
'' : 's'
)
+ '.'
);
} else {
$grunt.log.error('No files were aliased');
}
}
);
};
|
JavaScript
| 0 |
@@ -730,24 +730,21 @@
fileDest
-%5B'
+.
cyan
-'%5D
%0A
@@ -832,16 +832,13 @@
)
-%5B'
+.
cyan
-'%5D
%0A
@@ -3117,17 +3117,14 @@
nt )
-%5B'
+.
green
-'%5D
%0A
|
4d8e1767972c6097429042a51ed25ef756e70588
|
change isFetching to consistently be boolean (#1570)
|
packages/netlify-cms-core/src/reducers/search.js
|
packages/netlify-cms-core/src/reducers/search.js
|
import { Map, List } from 'immutable';
import {
SEARCH_ENTRIES_REQUEST,
SEARCH_ENTRIES_SUCCESS,
QUERY_REQUEST,
QUERY_SUCCESS,
SEARCH_CLEAR,
} from 'Actions/search';
let loadedEntries;
let response;
let page;
let searchTerm;
const defaultState = Map({ isFetching: false, term: null, page: 0, entryIds: List([]), queryHits: Map({}) });
const entries = (state = defaultState, action) => {
switch (action.type) {
case SEARCH_CLEAR:
return defaultState;
case SEARCH_ENTRIES_REQUEST:
if (action.payload.searchTerm !== state.get('term')) {
return state.withMutations((map) => {
map.set('isFetching', true);
map.set('term', action.payload.searchTerm);
});
}
return state;
case SEARCH_ENTRIES_SUCCESS:
loadedEntries = action.payload.entries;
page = action.payload.page;
searchTerm = action.payload.searchTerm;
return state.withMutations((map) => {
const entryIds = List(loadedEntries.map(entry => ({ collection: entry.collection, slug: entry.slug })));
map.set('isFetching', false);
map.set('page', page);
map.set('term', searchTerm);
map.set('entryIds', (!page || isNaN(page) || page === 0) ? entryIds : map.get('entryIds', List()).concat(entryIds));
});
case QUERY_REQUEST:
if (action.payload.searchTerm !== state.get('term')) {
return state.withMutations((map) => {
map.set('isFetching', action.payload.namespace);
map.set('term', action.payload.searchTerm);
});
}
return state;
case QUERY_SUCCESS:
searchTerm = action.payload.searchTerm;
response = action.payload.response;
return state.withMutations((map) => {
map.set('isFetching', false);
map.set('term', searchTerm);
map.mergeIn(['queryHits'], Map({ [action.payload.namespace]: response.hits }));
});
default:
return state;
}
};
export default entries;
|
JavaScript
| 0 |
@@ -1488,16 +1488,31 @@
amespace
+ ? true : false
);%0A
|
39209dc5b5fbbc514c63d8f53e2aabc0536bcba8
|
Update react-devtools-inline to embed react-debug-tools since it's not published yet
|
packages/react-devtools-inline/webpack.config.js
|
packages/react-devtools-inline/webpack.config.js
|
const {resolve} = require('path');
const {DefinePlugin} = require('webpack');
const {
getGitHubURL,
getVersionString,
} = require('react-devtools-extensions/utils');
const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
console.error('NODE_ENV not set');
process.exit(1);
}
const __DEV__ = true; // NODE_ENV === 'development';
const GITHUB_URL = getGitHubURL();
const DEVTOOLS_VERSION = getVersionString();
module.exports = {
mode: __DEV__ ? 'development' : 'production',
devtool: false,
entry: {
backend: './src/backend.js',
frontend: './src/frontend.js',
},
output: {
path: __dirname + '/dist',
filename: '[name].js',
library: '[name]',
libraryTarget: 'commonjs2',
},
externals: {
react: 'react',
'react-debug-tools': 'react-debug-tools',
'react-dom': 'react-dom',
'react-is': 'react-is',
scheduler: 'scheduler',
},
plugins: [
new DefinePlugin({
__DEV__,
__TEST__: false,
'process.env.DEVTOOLS_VERSION': `"${DEVTOOLS_VERSION}"`,
'process.env.GITHUB_URL': `"${GITHUB_URL}"`,
'process.env.NODE_ENV': `"${NODE_ENV}"`,
}),
],
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
options: {
configFile: resolve(
__dirname,
'..',
'react-devtools-shared',
'babel.config.js',
),
},
},
{
test: /\.css$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
sourceMap: true,
modules: true,
localIdentName: '[local]___[hash:base64:5]',
},
},
],
},
],
},
};
|
JavaScript
| 0 |
@@ -747,24 +747,92 @@
'react',%0A
+ // TODO: Once this package is published, remove the external%0A //
'react-debu
|
d0b604010569beb5cd2204faab44782b166062b5
|
add display name for radiobutton in form story (#4588)
|
packages/react/src/components/Form/Form-story.js
|
packages/react/src/components/Form/Form-story.js
|
/**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { withKnobs, boolean, text } from '@storybook/addon-knobs';
import Checkbox from '../Checkbox';
import Form from '../Form';
import FormGroup from '../FormGroup';
import FileUploader from '../FileUploader';
import NumberInput from '../NumberInput';
import RadioButton from '../RadioButton';
import RadioButtonGroup from '../RadioButtonGroup';
import Button from '../Button';
import Search from '../Search';
import Select from '../Select';
import SelectItem from '../SelectItem';
import TextArea from '../TextArea';
import TextInput from '../TextInput';
import Toggle from '../Toggle';
const additionalProps = {
className: 'some-class',
onSubmit: e => {
e.preventDefault();
action('FormSubmitted')(e);
},
};
const checkboxEvents = {
className: 'some-class',
labelText: 'Checkbox label',
};
const fieldsetCheckboxProps = () => ({
className: 'some-class',
legendText: text('Text in <legend> (legendText)', 'Checkbox heading'),
message: boolean('Show form requirement (message)', false),
messageText: text('Form requirement text (messageText)', ''),
invalid: boolean('Mark as invalid (invalid)', false),
});
const numberInputProps = {
className: 'some-class',
id: 'number-input-1',
label: 'Number Input',
min: 0,
max: 100,
value: 50,
step: 10,
};
const toggleProps = {
className: 'some-class',
};
const fieldsetToggleProps = {
className: 'some-class',
legendText: 'Toggle heading',
};
const fileUploaderEvents = {
buttonLabel: 'Add files',
className: 'some-class',
};
const fieldsetFileUploaderProps = {
className: 'some-class',
legendText: 'File Uploader',
};
const radioProps = {
className: 'some-class',
};
const fieldsetRadioProps = {
className: 'some-class',
legendText: 'Radio Button heading',
};
const searchProps = {
className: 'some-class',
};
const fieldsetSearchProps = {
className: 'some-class',
legendText: 'Search',
};
const selectProps = {
className: 'some-class',
};
const TextInputProps = {
className: 'some-class',
id: 'test2',
labelText: 'Text Input label',
placeholder: 'Placeholder text',
};
const PasswordProps = {
className: 'some-class',
id: 'test3',
labelText: 'Password',
};
const InvalidPasswordProps = {
className: 'some-class',
id: 'test4',
labelText: 'Password',
invalid: true,
invalidText:
'Your password must be at least 6 characters as well as contain at least one uppercase, one lowercase, and one number.',
};
const textareaProps = {
labelText: 'Text Area label',
className: 'some-class',
placeholder: 'Placeholder text',
id: 'test5',
cols: 50,
rows: 4,
};
const buttonEvents = {
className: 'some-class',
};
storiesOf('Form', module)
.addDecorator(withKnobs)
.add(
'Default',
() => (
<Form {...additionalProps}>
<FormGroup {...fieldsetCheckboxProps()}>
<Checkbox defaultChecked {...checkboxEvents} id="checkbox-0" />
<Checkbox {...checkboxEvents} id="checkbox-1" />
<Checkbox disabled {...checkboxEvents} id="checkbox-2" />
</FormGroup>
<NumberInput {...numberInputProps} />
<FormGroup {...fieldsetToggleProps}>
<Toggle {...toggleProps} id="toggle-1" />
<Toggle disabled {...toggleProps} id="toggle-2" />
</FormGroup>
<FormGroup {...fieldsetFileUploaderProps}>
<FileUploader
{...fileUploaderEvents}
id="file-1"
labelDescription="Choose Files..."
/>
</FormGroup>
<FormGroup {...fieldsetRadioProps}>
<RadioButtonGroup
onChange={action('onChange')}
name="radio-button-group"
defaultSelected="default-selected">
<RadioButton
value="standard"
id="radio-1"
labelText="Standard Radio Button"
{...radioProps}
/>
<RadioButton
value="default-selected"
labelText="Default Selected Radio Button"
id="radio-2"
{...radioProps}
/>
<RadioButton
value="blue"
labelText="Standard Radio Button"
id="radio-3"
{...radioProps}
/>
<RadioButton
value="disabled"
labelText="Disabled Radio Button"
id="radio-4"
disabled
{...radioProps}
/>
</RadioButtonGroup>
</FormGroup>
<FormGroup {...fieldsetSearchProps}>
<Search
{...searchProps}
id="search-1"
labelText="Search"
placeHolderText="Search"
/>
</FormGroup>
<Select {...selectProps} id="select-1" defaultValue="placeholder-item">
<SelectItem
disabled
hidden
value="placeholder-item"
text="Choose an option"
/>
<SelectItem value="option-1" text="Option 1" />
<SelectItem value="option-2" text="Option 2" />
<SelectItem value="option-3" text="Option 3" />
</Select>
<TextInput {...TextInputProps} />
<TextInput
type="password"
required
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}"
{...PasswordProps}
/>
<TextInput
type="password"
required
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}"
{...InvalidPasswordProps}
/>
<TextArea {...textareaProps} />
<Button type="submit" className="some-class" {...buttonEvents}>
Submit
</Button>
</Form>
),
{
info: {
text: `
Forms are widely used to collect user input.
Form can have any number of react components enclosed within FormGroup component. FormGroup component
is a wrapper for legend and fieldset component.
`,
},
}
);
|
JavaScript
| 0 |
@@ -2973,16 +2973,58 @@
s',%0A%7D;%0A%0A
+RadioButton.displayName = 'RadioButton';%0A%0A
storiesO
|
e7d48d62032a4a6afc2ddc5027ae78dba1689415
|
Fix TM compat
|
dry.js
|
dry.js
|
const dry = (function() {
"use strict";
const unique = function(a, key) {
if (key) {
return a.filter(function(e) {
e = key(e);
return !!e && (!this.has(e) && !!this.add(e));
}, new Set());
}
return a.filter(function(e) {
return !!e && (!this.has(e) && !!this.add(e));
}, new Set());
};
const EventKeys = Symbol();
class EventEmitter {
constructor() {
this[EventKeys] = new Map();
}
on(event, cb) {
let handlers = this[EventKeys].get(event);
if (!handlers) {
this[EventKeys].set(event, handlers = new Set());
}
handlers.add(cb);
}
off(event, cb) {
const keys = this[EventKeys];
const handlers = keys.get(event);
if (!handlers) {
return;
}
handlers.delete(cb);
if (!handlers.size) {
keys.delete(event);
}
}
once(event, cb, ...args) {
let wrapped = (...args) => {
try {
return cb(...args);
}
finally {
this.off(event, wrapped);
}
};
return this.on(event, wrapped, ...args);
}
emit(event, ...args) {
const handlers = this[EventKeys].get(event);
if (!handlers) {
return;
}
for (let e of Array.from(handlers)) {
try {
e(...args);
}
catch (ex) {
console.error(`Event handler ${e} for ${event} failed`, ex);
}
}
}
emitSoon(event, ...args) {
setTimeout(() => this.emit(event, ...args));
}
}
const bus = new EventEmitter();
if (document.readyState === "interactive" || document.readyState === "complete" ) {
bus.emitSoon("dom", null, false);
}
else {
addEventListener("DOMContentLoaded", function dom(evt) {
removeEventListener("DOMContentLoaded", dom, true);
bus.emit("dom", evt, true);
}, true);
}
if (document.readyState === "complete") {
bus.emitSoon("load", null, false);
}
else {
addEventListener("load", function load(evt) {
removeEventListener("load", load, true);
bus.emit("load", evt, true);
}, true);
}
let exts = null;
try {
exts = (window.Room || unsafeWindow.Room).prototype._extensions.connection.prototype.room.extensions;
}
catch (ex) {
bus.on("load", () => {
exts = (window.Room || unsafeWindow.Room).prototype._extensions.connection.prototype.room.extensions;
});
}
let exportObject = function(o) {
return unsafeWindow.JSON.parse(JSON.stringify(o));
};
let exportFunction = this.exportFunction;
if (!exportFunction) {
exportFunction = (fn, o) => fn;
exportObject = o => o;
}
const replace = function(proto, where, what, newfn) {
let ext = this[where];
if (!ext) {
throw new Error("Binding not available");
}
if (proto) {
if (ext.prototype && document.readyState !== "complete") {
ext = ext.prototype;
}
else {
console.warn("binding late, skipping prototype, this might not work", where, what);
return replace.call(exts, false, where, what, newfn);
}
if (!ext) {
throw new Error("Binding prototype not available");
}
}
let origfn = ext[what];
if (!origfn) {
throw new Error("Target not available");
}
ext[what] = exportFunction(function(...args) {
return newfn.call(this, origfn.bind(this), ...args);
}, unsafeWindow);
return ext[what].bind(ext);
};
const replaceEarly = (...args) => {
return replace.call((window.Room || unsafeWindow.Room).prototype._extensions, true, ...args);
};
class Commands {
constructor() {
replaceEarly("chat", "onCommand", (orig, command, e, ...args) => {
let fn = this[command];
if (fn && fn.call(this, e, args) !== false) {
return;
}
args.unshift(e);
args.unshift(command);
return orig(...exportObject(args));
});
}
}
const appendMessage = (user, message, options) => {
let o = {
dontsave: true,
staff: true,
highlight: true
};
if (options) {
Object.assign(o, options);
}
if (message.trim) {
message = [{type: "text", value: message}];
}
return exts.chat.showMessage(user, exportObject(message), exportObject(o));
};
let config = window.config || unsafeWindow.config;
if (!config) {
bus.once("load", () => {
config = window.config || unsafeWindow.config;
});
}
return {
on: bus.on.bind(bus),
off: bus.off.bind(bus),
once: bus.once.bind(bus),
emit: bus.emit.bind(bus),
get config() {
return config;
},
get exts() {
return exts;
},
replaceEarly,
replaceLate(...args) {
return replace.call(this.exts, false, ...args);
},
appendMessage,
exportFunction,
exportObject,
unique,
EventEmitter,
Commands,
version: "0.2",
};
}).call(this);
|
JavaScript
| 0 |
@@ -37,16 +37,76 @@
trict%22;%0A
+ const unsafeWindow = this.unsafeWindow %7C%7C this.window;%0A%0A
cons
@@ -2956,33 +2956,32 @@
%7D);%0A %7D%0A
-%0A
let exportOb
@@ -5603,32 +5603,54 @@
xts;%0A %7D,%0A
+ unsafeWindow,%0A
replaceE
|
e0a2982875a38b3601e019ee1e3ec4b9d0303d6d
|
fix config
|
dry.js
|
dry.js
|
const dry = (function() {
"use strict";
const unique = function(a, key) {
if (key) {
return a.filter(function(e) {
e = key(e);
return !!e && (!this.has(e) && !!this.add(e));
}, new Set());
}
return a.filter(function(e) {
return !!e && (!this.has(e) && !!this.add(e));
}, new Set());
};
const EventKeys = Symbol();
class EventEmitter {
constructor() {
this[EventKeys] = new Map();
}
on(event, cb) {
let handlers = this[EventKeys].get(event);
if (!handlers) {
this[EventKeys].set(event, handlers = new Set());
}
handlers.add(cb);
}
off(event, cb) {
const keys = this[EventKeys];
const handlers = keys.get(event);
if (!handlers) {
return;
}
handlers.delete(cb);
if (!handlers.size) {
keys.delete(event);
}
}
once(event, cb, ...args) {
let wrapped = (...args) => {
try {
return cb(...args);
}
finally {
this.off(event, wrapped);
}
};
return this.on(event, wrapped, ...args);
}
emit(event, ...args) {
const handlers = this[EventKeys].get(event);
if (!handlers) {
return;
}
for (let e of Array.from(handlers)) {
try {
e(...args);
}
catch (ex) {
console.error(`Event handler ${e} for ${event} failed`, ex);
}
}
}
emitSoon(event, ...args) {
setTimeout(() => this.emit(event, ...args));
}
}
const bus = new EventEmitter();
if (document.readyState === "interactive" || document.readyState === "complete" ) {
bus.emitSoon("dom", null, false);
}
else {
addEventListener("DOMContentLoaded", function dom(evt) {
removeEventListener("DOMContentLoaded", dom, true);
bus.emit("dom", evt, true);
}, true);
}
if (document.readyState === "complete") {
bus.emitSoon("load", null, false);
}
else {
addEventListener("load", function load(evt) {
removeEventListener("load", load, true);
bus.emit("load", evt, true);
}, true);
}
let exts = null;
try {
exts = (window.Room || unsafeWindow.Room).prototype._extensions.connection.prototype.room.extensions;
}
catch (ex) {
bus.on("load", () => {
exts = (window.Room || unsafeWindow.Room).prototype._extensions.connection.prototype.room.extensions;
});
}
let exportObject = function(o) {
return unsafeWindow.JSON.parse(JSON.stringify(o));
};
let exportFunction = this.exportFunction;
if (!exportFunction) {
exportFunction = (fn, o) => fn;
exportObject = o => o;
}
const replace = function(proto, where, what, newfn) {
let ext = this[where];
if (!ext) {
throw new Error("Binding not available");
}
if (proto) {
if (ext.prototype && document.readyState !== "complete") {
ext = ext.prototype;
}
else {
console.warn("binding late, skipping prototype, this might not work", where, what);
return replace.call(exts, false, where, what, newfn);
}
if (!ext) {
throw new Error("Binding prototype not available");
}
}
let origfn = ext[what];
if (!origfn) {
throw new Error("Target not available");
}
ext[what] = exportFunction(function(...args) {
return newfn.call(this, origfn.bind(this), ...args);
}, unsafeWindow);
return ext[what].bind(ext);
};
const replaceEarly = (...args) => {
return replace.call((window.Room || unsafeWindow.Room).prototype._extensions, true, ...args);
};
class Commands {
constructor() {
replaceEarly("chat", "onCommand", (orig, command, e, ...args) => {
let fn = this[command];
if (fn && fn.call(this, e, args) !== false) {
return;
}
args.unshift(e);
args.unshift(command);
return orig(...exportObject(args));
});
}
}
const appendMessage = (user, message, options) => {
let o = {
dontsave: true,
staff: true,
highlight: true
};
if (options) {
Object.assign(o, options);
}
if (message.trim) {
message = [{type: "text", value: message}];
}
return exts.chat.showMessage(user, exportObject(message), exportObject(o));
};
const config = window.config || unsafeWindow.config;
return {
on: bus.on.bind(bus),
off: bus.off.bind(bus),
once: bus.once.bind(bus),
emit: bus.emit.bind(bus),
config,
get exts() {
return exts;
},
replaceEarly,
replaceLate(...args) {
return replace.call(this.exts, false, ...args);
},
appendMessage,
exportFunction,
exportObject,
unique,
EventEmitter,
Commands,
version: "0.2",
};
}).call(this);
|
JavaScript
| 0.000006 |
@@ -5110,21 +5110,130 @@
%7D;%0A%0A
-const
+let config = window.config %7C%7C unsafeWindow.config;%0A if (!config) %7B%0A bus.once(%22load%22, () =%3E %7B%0A
config
@@ -5271,16 +5271,34 @@
.config;
+%0A %7D);%0A %7D
%0A%0A re
@@ -5442,22 +5442,67 @@
+get
config
+() %7B%0A return config;%0A %7D
,%0A
|
dcee1a3b8899e13381bb116783c1e873e564e079
|
remove fb copyright, because the code is modified a lot
|
src/utils/deepFreeze.js
|
src/utils/deepFreeze.js
|
/**
* Based on deepFreezeAndThrowOnMutationInDev from react-native package.
*/
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule deepFreezeAndThrowOnMutationInDev
* @flow
*/
declare var __DEV__: boolean
const identity = value => value
const throwOnMutation = (objectName, key, value) => {
throw Error(`
You attempted to set the key ${key} with the value
${JSON.stringify(value)} on the object ${objectName} that is meant to be immutable
and has been frozen.
`)
}
/**
* If your application is accepting different values for the same field over
* time and is doing a diff on them, you can either (1) create a copy or
* (2) ensure that those values are not mutated behind two passes.
* This function helps you with (2) by freezing the object and throwing if
* the user subsequently modifies the value.
*
* There are two caveats with this function:
* - If the call site is not in strict mode, it will only throw when
* mutating existing fields, adding a new one
* will unfortunately fail silently :(
* - If the object is already frozen or sealed, it will not continue the
* deep traversal and will leave leaf nodes unfrozen.
*
* Freezing the object and adding the throw mechanism is expensive and will
* only be used in DEV.
*/
export default function deepFreeze(object: Object, objectName?: string = '') {
if (!__DEV__) return
if (
typeof object !== 'object' ||
object === null ||
Object.isFrozen(object) ||
Object.isSealed(object)
) return
const keys = Object.keys(object)
keys.forEach((key) => {
if (!Object.prototype.hasOwnProperty.call(object, key)) return
Object.defineProperty(object, key, {
enumerable: true,
get: identity.bind(null, object[key]),
set: throwOnMutation.bind(null, objectName, key)
})
})
Object.freeze(object)
Object.seal(object)
keys.forEach((key) => {
if (!Object.prototype.hasOwnProperty.call(object, key)) return
deepFreeze(object[key])
})
}
|
JavaScript
| 0 |
@@ -79,383 +79,8 @@
*/%0A%0A
-/**%0A * Copyright (c) 2015-present, Facebook, Inc.%0A * All rights reserved.%0A *%0A * This source code is licensed under the BSD-style license found in the%0A * LICENSE file in the root directory of this source tree. An additional grant%0A * of patent rights can be found in the PATENTS file in the same directory.%0A *%0A * @providesModule deepFreezeAndThrowOnMutationInDev%0A * @flow%0A */%0A%0A
decl
|
e65b827ef7e8263211b83756482048c9dc24ce56
|
Use less confusing names for `for in`
|
lib/Proclass.js
|
lib/Proclass.js
|
// Avoids running `_init()` unnecessarily
var _initializing = false;
// Empty constructor (overwritten in `extend()`)
var Proclass = function() { };
// Make it possible to extend the class
// Save function (as `Extend`) to inject protected variables later
Proclass.extend = function Extend(_self, _parent) {
// If `_parent` doesn't exist, define it (to avoid errors later)
if (typeof _parent === "undefined") {
_parent = {};
}
// Create base prototype for new class
var prototype = function() {};
// Loop through `_parent` and add to saved prototype
for (var name in _parent) {
prototype[name] = _parent[name];
}
// Loop through `_self` and add to saved prototype
for (var name in _self) {
prototype[name] = _self[name];
}
// Create constructor
function Proclass() {
// If initializing, don't run constructor
if (_initializing) {
return;
}
// Store protected variables
var _protected = {};
// Copy prototype onto `this`
for (var name in prototype) {
// If variable begins with `_`, consider it protected
var isProtected = false;
if (/^_/.test(name)) {
isProtected = true;
}
// If we're overwriting a function with a function, add `_parent` method
var addParent = false;
if (typeof _self[name] === "function" && typeof _parent[name] === "function") {
addParent = true;
}
// If a function, add protected variables and `_parent` method to scope
// Else, simply use the value
var isFunction = (typeof prototype[name] === "function");
var toCall = !isFunction ? prototype[name] : (function(name, fnc, addParent){
return function() {
// Create temp object to store previous values for protected variables
var temp = {};
// Save previous value of `_parent` if `addParent` is `true` and
// overwrite `this._parent` with `_parent[name]`
if (addParent) {
temp._parent = this._parent
this._parent = _parent[name];
}
// Save previous value of all protected variables and overwrite
// `this[x]` with `_protected[x]`
for (var allNames in _protected) {
temp[allNames] = this[allNames];
this[allNames] = _protected[allNames];
}
// Bind actual function with the newly created scope
var appliedFunction = fnc.apply(this, arguments);
// Remove protected variables from `this`
for (var nonPublic in _protected) {
// Save new value if it changed
if (this[nonPublic] !== _protected[nonPublic]) {
_protected[nonPublic] = this[nonPublic];
}
// Set this value back to previous
this[nonPublic] = temp[nonPublic];
}
// Set `this._parent` to saved `temp._parent`
if (addParent) {
this._parent = temp._parent;
}
// Return applied function
return appliedFunction;
};
})(name, prototype[name], addParent);
// If protected, add to `_protected` and set to `undefined`
// Else, add to `this`
if (isProtected) {
_protected[name] = toCall;
this[name] = undefined;
} else {
this[name] = toCall;
}
}
// Run constructor function (`_init()`)
if (_protected._init) {
_protected._init.apply(this, arguments);
}
}
// Make sure this function's `_protected` gets passed to children
Proclass.extend = (function(fnc, protectedVariables){
return function() {
return fnc.call(this, arguments[0], protectedVariables);
};
})(Extend, prototype);
// Save prototype
Proclass.prototype = prototype;
// Save constructor
Proclass.prototype.constructor = Proclass;
return Proclass;
};
// Export Proclass
module.exports = Proclass;
|
JavaScript
| 0.000002 |
@@ -2062,24 +2062,23 @@
or (var
-all
+pro
Name
-s
in _pro
@@ -2098,24 +2098,23 @@
%09%09%09temp%5B
-all
+pro
Name
-s
%5D = this
@@ -2114,24 +2114,23 @@
= this%5B
-all
+pro
Name
-s
%5D;%0A%09%09%09%09%09
@@ -2135,24 +2135,23 @@
%09%09%09this%5B
-all
+pro
Name
-s
%5D = _pro
@@ -2161,16 +2161,15 @@
ted%5B
-all
+pro
Name
-s
%5D;%0A%09
@@ -2350,25 +2350,23 @@
or (var
-nonPublic
+proName
in _pro
@@ -2428,25 +2428,23 @@
f (this%5B
-nonPublic
+proName
%5D !== _p
@@ -2452,25 +2452,23 @@
otected%5B
-nonPublic
+proName
%5D) %7B%0A%09%09%09
@@ -2486,35 +2486,31 @@
ted%5B
-nonPublic%5D = this%5BnonPublic
+proName%5D = this%5BproName
%5D;%0A%09
@@ -2572,35 +2572,31 @@
his%5B
-nonPublic%5D = temp%5BnonPublic
+proName%5D = temp%5BproName
%5D;%0A%09
|
80a92d75a35644f95f0c18b3d711a64b043cf381
|
Response.setState and setView are fluent
|
lib/Response.js
|
lib/Response.js
|
var inherits = require('inherits');
var EventEmitter = require('EventEmitter2').EventEmitter2;
var Renderer = require('./Renderer');
var React = require('react');
/**
* The Response is used as the `this` value for route functions. It hosts
* methods for manipulating the server response and application state.
*/
function Response(request, router) {
this.request = request;
this.router = router;
this.state = router.state;
}
inherits(Response, EventEmitter);
//
//
// The main methods for manipulating the application state.
//
//
Response.prototype.setState = function(state) {
this.router.setState(state);
this.state = this.router.state;
};
Response.prototype.setView = function(view) {
this.router.setView(view);
this.view = this.router.view;
};
//
//
// Ending
//
//
/**
* Indicates that a response was ended.
*/
Response.prototype.ended = false;
Response.prototype.initialEnded = false;
/**
* Call to indicate that router is in the "initial" state—the state that the
* server will send and the browser app will begin in.
*/
Response.prototype.endInitial = function() {
if (this.initialEnded) {
return;
}
this.initialEnded = true;
this.emit('initialReady');
if (this.request.initialOnly) {
this.end();
}
};
Response.prototype.end = function() {
if (!this.ended) {
this.endInitial();
this.ended = true;
this.emit('end');
}
};
//
//
// Metadata methods.
//
//
/**
* Indicate that no view was found for the corresponding request. This has no
* effect in the browser, but causes a 404 response to be sent on the server.
* Note that this is different from `unhandled` as it indicates that the UI has
* been updated.
*/
Response.prototype.notFound = function() {
// TODO: Should this work as a getter too? Or should we make it chainable?
this._notFound = true;
};
Response.prototype.doctype = function() {
return ''; // TODO: THIS!
};
Response.prototype.contentType = function() {
return ''; // TODO: THIS, ALSO!
};
//
//
// Rendering shortcuts.
//
//
/**
* A function decorator that creates a new view from the provided one and the
* (optional) remaining arguments.
*
* @param {function} fn The function whose arguments to transform.
*/
function renderer(fn) {
return function(view) {
if (arguments.length > 1) {
var oldView = view;
var args = Array.prototype.slice.call(arguments, 1);
view = function() {
return oldView.apply(this, args);
};
}
return fn.call(this, view);
};
}
//
// Shortcut methods for rendering a view with props and (optionally) ending the
// request.
//
/**
* Render the provided view and end the request.
*/
Response.prototype.render = renderer(function(view) {
this.setView(view);
this.end();
return this;
});
/**
* Render the provided view and mark the current state as the initial one.
*/
Response.prototype.renderInitial = renderer(function(view) {
this.setView(view);
this.request.endInitial();
return this;
});
/**
* Render the provided view.
*/
Response.prototype.renderIntermediate = renderer(function(view) {
this.setView(view);
return this;
});
Response.prototype.renderDocumentToString = function() {
var renderer = Renderer({view: this.view, routerState: this.state});
var markup = React.renderComponentToString(renderer);
var doctype = res.doctype(); // Guess from contentType if not present.
return (doctype || '') + markup;
};
module.exports = Response;
|
JavaScript
| 0.998771 |
@@ -650,16 +650,31 @@
.state;%0A
+ return this;%0A
%7D;%0A%0AResp
@@ -776,16 +776,31 @@
r.view;%0A
+ return this;%0A
%7D;%0A%0A//%0A/
|
d34200b26515aed65c72cfc9b85d879111fa10d5
|
Address ember 2.6 SafeString deprecation warnings (#321)
|
addon/components/md-loader.js
|
addon/components/md-loader.js
|
import Ember from 'ember';
import UsesSettings from '../mixins/uses-settings';
import layout from '../templates/components/md-loader';
const { Component, computed, computed: { oneWay } } = Ember;
export default Component.extend(UsesSettings, {
layout,
classNameBindings: ['isBarType:progress:preloader-wrapper', 'active:active', 'size'],
mode: oneWay('_mdSettings.loaderMode'),
percent: 0,
size: oneWay('_mdSettings.loaderSize'),
active: true,
color: null,
isBarType: computed('mode', function() {
return ['determinate', 'indeterminate'].indexOf(this.get('mode')) >= 0;
}),
isDeterminate: computed('mode', function() {
return ['determinate'].indexOf(this.get('mode'));
}),
barStyle: computed('mode', 'percent', function() {
if (this.get('mode') === 'determinate') {
return new Ember.Handlebars.SafeString(`width: ${parseInt(this.get('percent'), 10)}%`);
} else {
return new Ember.Handlebars.SafeString('');
}
}),
barClassName: computed('isBarType', 'mode', function() {
return this.get('isBarType') ? this.get('mode') : null;
}),
spinnerClassNames: computed('color', 'isBarType', function() {
if (!this.get('isBarType')) {
const color = this.get('color');
if (!color) {
return Ember.A(['blue', 'red', 'green', 'yellow']
.map(c => (`spinner-layer spinner-${c}`)));
} else {
return Ember.A([`spinner-layer spinner-${color}-only`]);
}
} else {
return Ember.A();
}
})
});
|
JavaScript
| 0 |
@@ -825,37 +825,31 @@
w Ember.
-Handlebars.SafeString
+String.htmlSafe
(%60width:
@@ -930,29 +930,23 @@
ber.
-Handlebars.SafeString
+String.htmlSafe
('')
|
9ebd92b1153fd03b48002afffc40a535a15b9c34
|
use set
|
addon/components/wrap-urls.js
|
addon/components/wrap-urls.js
|
/* eslint-disable no-cond-assign */
import Component from '@ember/component';
import layout from '../templates/components/wrap-urls';
const WrapUrlsComponent = Component.extend({
layout,
tagName: '',
parts: null,
didReceiveAttrs() {
this._super(...arguments);
this.set('parts', this._textToParts(this.text));
this.set('urlComponent', this.component || 'wrap-urls/url');
},
_textToParts(text) {
text = text || '';
text = text.toString();
const parts = [];
let lastIndex = 0;
let match;
let string;
while ((match = WrapUrlsComponent.regex.exec(text))) {
const [url] = match;
const { index: start } = match;
string = text.slice(lastIndex, start);
lastIndex = start + url.length;
if (string) {
parts.push({
text: string
});
}
parts.push({
url,
start,
end: lastIndex
});
}
string = text.slice(lastIndex);
if (string) {
parts.push({
text: string
});
}
return parts;
}
});
WrapUrlsComponent.reopenClass({
regex: /(https?|file|ftp):\/\/([a-zA-Z0-9~!@#$%^&*()_\-=+/?.:;',]*)?/g
});
export default WrapUrlsComponent;
|
JavaScript
| 0.000002 |
@@ -1,41 +1,4 @@
-/* eslint-disable no-cond-assign */%0A%0A
impo
@@ -90,16 +90,53 @@
p-urls';
+%0Aimport %7B set %7D from '@ember/object';
%0A%0Aconst
@@ -272,25 +272,26 @@
s);%0A
-this.set(
+set(this,
'parts',
@@ -330,17 +330,18 @@
-this.set(
+set(this,
'url
|
c4672774b45e6124cf26b15e7e02b7740738bc0f
|
Rename readOnlyCopy to serialize
|
lib/argument.js
|
lib/argument.js
|
var B = require("buster-core");
var when = require("when");
function validate(validator) {
try {
var val = validator(this.readOnlyCopy());
return when.isPromise(val) ? val : when(val);
} catch (e) {
var deferred = when.defer();
deferred.reject(e);
return deferred.promise;
}
}
module.exports = {
create: function () {
return B.extend(B.create(this), { validators: [] });
},
addValidator: function (validator) {
this.validators.push(validator);
},
validatorPromise: function () {
var deferred = when.defer();
when.all(this.validators.map(B.bind(this, validate))).then(function () {
deferred.resolve();
}, function (errors) {
deferred.reject(errors);
});
return deferred.promise;
},
readOnlyCopy: function () {
return {
value: this.value,
isSet: this.isSet,
timesSet: this.timesSet,
hasValue: this.hasValue,
signature: this.signature
};
}
};
|
JavaScript
| 0 |
@@ -128,28 +128,25 @@
or(this.
-readOnlyCopy
+serialize
());%0A
@@ -573,45 +573,14 @@
-var deferred = when.defer();%0A%0A
+return
whe
@@ -633,198 +633,31 @@
e)))
-.then(function () %7B%0A deferred.resolve()
;%0A
-
- %7D, function (errors) %7B%0A deferred.reject(errors);%0A %7D);%0A%0A return deferred.promise;%0A %7D,%0A%0A readOnlyCopy
+%7D,%0A%0A serialize
: fu
|
5332b6d22c81cf0701b175735970651c1af9807e
|
Add trim to japanese check
|
modules/japanese.js
|
modules/japanese.js
|
/**
* The original intention of this module was to translate
* using the Google Translate API, but it's a paid service.
* Hence, this pale imitation.
*/
var jp = require( 'japanese' );
module.exports = {
events: {
message: function ( bot, nick, to, text ) {
// http://stackoverflow.com/a/15034560/1875784
if ( text.match( /[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\uff00-\uff9f\u4e00-\u9faf\u3400-\u4dbf]/ ) ) {
var romaji = jp.romanize( text );
if ( romaji ) {
bot.shout( to, '\u000314' + romaji );
}
}
}
}
};
|
JavaScript
| 0 |
@@ -471,16 +471,24 @@
( romaji
+.trim()
) %7B%0A%09%09%09
|
e158a96b8e64b91e0f4e5c30d0c354e92cbea629
|
Improve interceptor with correct redirect URL
|
lib/assets/javascripts/builder/data/backbone/network-interceptors/interceptors/forbidden-403.js
|
lib/assets/javascripts/builder/data/backbone/network-interceptors/interceptors/forbidden-403.js
|
/**
* 403 Forbidden Network Error Interceptor
*
* This interceptor redirects to login page when
* any 403 session expired error is returned in any of the
* network requests
*/
var LOGIN_ROUTE = '/login';
var SESSION_EXPIRED = 'session_expired';
module.exports = function (xhr, textStatus, errorThrown) {
if (xhr.status !== 403) return;
var error = xhr.responseJSON && xhr.responseJSON.error;
if (error === SESSION_EXPIRED) {
console.warn('Redirect to password change', xhr);
// window.location = LOGIN_ROUTE;
}
};
|
JavaScript
| 0.000001 |
@@ -184,71 +184,190 @@
var
-LOGIN_ROUTE = '/login';%0Avar SESSION_EXPIRED = 'session_expired'
+PASSWORD_CHANGE_ROUTE = '/password_change/';%0Avar SESSION_EXPIRED = 'session_expired';%0A%0Avar organizationUsernameMatch = /%5C/(u%7Cuser)%5C/(.*)%5C//;%0Avar subdomainMatch = /https?:%5C/%5C/(%5B%5E.%5D+)/
;%0A%0Am
@@ -561,99 +561,772 @@
-console.warn('Redirect to password change', xhr
+window.location.href = getRedirectURL();%0A %7D%0A%7D;%0A%0Afunction getRedirectURL () %7B%0A // We cannot get accountHost and username from configModel%0A // and userModel because of static pages. God save static pages.%0A var username = getUsernameFromURL(location.href
);%0A
+%0A
- // window.location = LOGIN_ROUTE;%0A %7D%0A%7D;
+if (!username) %7B%0A return '';%0A %7D%0A%0A var newURL = location.origin.replace(subdomainMatch, function () %7B%0A return username;%0A %7D);%0A%0A return %60$%7Blocation.protocol%7D//$%7BnewURL%7D$%7BPASSWORD_CHANGE_ROUTE%7D$%7Busername%7D%60;%0A%7D%0A%0Afunction getUsernameFromURL (url) %7B%0A var usernameMatches = url.match(organizationUsernameMatch);%0A%0A if (usernameMatches) %7B%0A return usernameMatches%5B2%5D;%0A %7D%0A%0A var subdomainMatches = url.match(subdomainMatch);%0A%0A if (subdomainMatches) %7B%0A return subdomainMatches%5B1%5D;%0A %7D%0A%0A return '';%0A%7D
%0A
|
d9c3d2baa531c5f06272c3ad00104cc449a98135
|
Fix doc for Behalter#exec
|
lib/behalter.js
|
lib/behalter.js
|
'use strict';
var _ = require('lodash');
/**
* Create a new behalter.
* @param {Behalter=} parent
* @constructor
*/
function Behalter(parent) {
this.__parent = parent;
this.__values = {};
this.__factories = {};
}
/**
* Set or get value.
*
* @param {(string|Object)} name
* @param {Object=} value
* @returns {*} value for name or this
*/
Behalter.prototype.value = function(name, value) {
var self = this;
if (reserved(name)) {
throw new Error(name + ' is a reserved word');
}
// setter(bulk)
if (_.isObject(name)) {
_.each(name, function(v, k) {
self.value(k, v);
});
return self;
}
// setter
if (arguments.length === 2 && _.isString(name)) {
self.__values[name] = value;
self.__defineGetter__(name, function() {
return this.value(name);
});
self.__defineSetter__(name, function() {
});
return self;
}
// getter
if (arguments.length === 1 && _.isString(name)) {
var val = self.__values[name];
if (val) {
return val;
} else if (self.__parent) {
return self.__parent.value(name);
} else {
return undefined;
}
}
throw new Error('invalid arguments');
};
/**
* Alias of Behalter#value.
*
* @param {string} name
* @returns {*} value for name
*/
Behalter.prototype.get = function(name) {
return this.value(name);
};
/**
* Alias of Behalter#value.
*
* @param {(string|Object)} name
* @param {Object} value
* @returns {Behalter} this
*/
Behalter.prototype.set = function(name, value) {
return this.value(name, value);
};
/**
* Set factory function or get returned value.
*
* @param {(string|Object)} name
* @param {function=} factory
* @returns {*} created value for name or this
*/
Behalter.prototype.factory = function(name, factory) {
var self = this;
if (reserved(name)) {
throw new Error(name + ' is a reserved word');
}
// setter(bulk)
if (_.isObject(name)) {
_.each(name, function(v, k) {
self.factory(k, v);
});
return self;
}
// setter
if (arguments.length === 2 && _.isString(name)) {
self.__factories[name] = factory;
self.__defineGetter__(name, function() {
return this.factory(name);
});
self.__defineSetter__(name, function() {
});
return self;
}
// getter
if (arguments.length === 1 && _.isString(name)) {
var fact = self.__factories[name];
if (_.isFunction(fact)) {
return fact();
} else if (self.__parent) {
return self.__parent.factory(name);
} else {
return undefined;
}
}
throw new Error('invalid arguments');
};
/**
* Get parent behalter.
*
* @returns {Behalter} parent behalter
*/
Behalter.prototype.parent = function() {
return this.__parent;
};
/**
* Get root behalter.
*
* @returns {Behalter} root behalter
*/
Behalter.prototype.root = function() {
if (this.__parent) {
return this.__parent.root();
} else {
return this;
}
};
/**
* Create and get a new child behalter.
*
* @param {string=} name
* @returns {Behalter} child behalter
*/
Behalter.prototype.child = function(name) {
var self = this;
if (arguments.length === 0) {
return new Behalter(self);
}
if (!_.isString(name)) {
throw new Error('invalid arguments');
}
if (reserved(name)) {
throw new Error(name + ' is reserved word');
}
var val = self.value(name);
if (val instanceof Behalter) {
return val;
} else if (val) {
throw new Error('value for name ' + name + ' is already defined');
}
self.value(name, new Behalter(self));
return self.value(name);
};
/**
* Create a new independent behalter.
*
* @returns {Behalter} new behalter
*/
Behalter.prototype.forge = function() {
return new Behalter();
};
/**
* Execute a function with Behalter as `this`.
*
* @param {function} fn
* @param {*...} params
* @return {*} return value of fn
*/
Behalter.prototype.exec = function(fn, params) { // jshint ignore:line
var self = this;
if (!_.isFunction(fn)) {
throw new Error('invalid arguments');
}
var matched = /function +[^\(]*\(([^\)]*)\).*/.exec(fn.toString());
var names = _.map(matched[1].split(',') || [], function(name) {
return name.replace(/\s+/g, '');
});
var runtime = Array.prototype.slice.call(arguments, 1);
var merged = _.map(names, function(name) {
return self.value(name) || self.factory(name) || runtime.shift();
});
return fn.apply(self, merged);
};
/**
* Execute a function with Behalter as `this`.
*
* @param {function} fn
* @param {*...} props
* @return {*} return value of fn
*/
Behalter.prototype.execp = function(fn, props) {
var self = this;
if (!_.isFunction(fn) || !_.isObject(props)) {
throw new Error('invalid arguments');
}
var matched = /function +[^\(]*\(([^\)]*)\).*/.exec(fn.toString());
var names = _.map(matched[1].split(',') || [], function(name) {
return name.replace(/\s+/g, '');
});
var merged = _.map(names, function(name) {
return props[name] || self.value(name) || self.factory(name);
});
return fn.apply(self, merged);
};
/**
* Install module into behalter.
*
* @param {function|Object} mod
* @param {*...=} params
* @return {Behalter} this
*/
Behalter.prototype.install = function(mod, params) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
if (_.isFunction(mod)) {
mod.apply(self, args);
} else if (_.isFunction(mod.install)) {
mod.install.apply(self, args);
}
return self;
};
// =====================================
// Helpers
// =====================================
var RESERVED = _.keys(Behalter.prototype);
/**
* Judge if name is reserved word or not.
*
* @param {string} name
* @returns {boolean} true if reserved
*/
function reserved(name) {
if (!_.isString(name)) {
return false;
}
return _.contains(RESERVED, name);
}
module.exports = Behalter;
|
JavaScript
| 0 |
@@ -3843,16 +3843,17 @@
am %7B*...
+=
%7D params
@@ -3943,30 +3943,8 @@
s) %7B
- // jshint ignore:line
%0A%0A
@@ -4525,16 +4525,17 @@
am %7B*...
+=
%7D props%0A
|
e53f35c09aeeb9588479a054440f207c38e825a7
|
Remove listener before
|
ejs.js
|
ejs.js
|
/**
* ejs
*
* @category ejs
* @author Vaibhav Mehta <[email protected]>
* @copyright Copyright (c) 2016 Vaibhav Mehta <https://github.com/i-break-codes>
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 1.0.0 Beta
*/
'use strict';
var Error = function() {
function init(userConfig = {}) {
// Default configuration
var config = {
detailedErrors: true,
remoteLogging: false,
remoteSettings: {
url: null,
additionalParams: null,
successCallback: null,
errorCallback: null
}
}
// Override with user config
var setConfig = Object.assign(config, userConfig);
// Listen to errors
window.addEventListener('error', function(e) {
if(setConfig.detailedErrors) {
_detailedErrors(e);
}
if(setConfig.remoteLogging) {
_remoteLogging(e, setConfig.remoteSettings);
}
});
}
// NOTE: Private
function _detailedErrors(e) {
_formatError(e);
}
function _formatError(e) {
var i = _errorData(e);
var helpPath = encodeURI("https://stackoverflow.com/search?q=" + i.error.split(' ').join('+'));
var str = [
"%cType: %c" + i.type,
"%cError: %c" + i.error,
"%cStackTrace: %c" + i.stackTrace,
"%cFile Name: %c" + i.filename,
"%cPath: %c" + i.path,
"%cLine: %c" + i.line,
"%cColumn: %c" + i.column,
"%cDate: %c" + i.datetime,
"%cDebug : %c" + i.path + ':' + i.line,
"%cGet Help: " + "%c" + helpPath
].join("\n");
console.log(str, "font-weight: bold;", "color: #e74c3c;", "font-weight: bold;", "font-weight: normal; color: #e74c3c;","font-weight: bold;", "font-weight: normal; color: #e74c3c;", "font-weight: bold;", "font-weight: normal;", "font-weight: bold;", "font-weight: normal;", "font-weight: bold;", "font-weight: normal;", "font-weight: bold;", "font-weight: normal;", "font-weight: bold;", "font-weight: normal;", "font-weight: bold;", "font-weight: normal;", "font-weight: bold;", "font-weight: normal; color: #3498db;");
}
function _remoteLogging(e, remoteSettings) {
if(!remoteSettings.url) {
throw 'Provide remote URL to log errors remotely';
return false;
} else if(remoteSettings.additionalParams && typeof remoteSettings.additionalParams !== 'object') {
throw 'Invalid data type, additionalParams should be a valid object';
return false;
}
var http = new XMLHttpRequest();
var url = remoteSettings.url;
var data = _errorData(e);
var setData = Object.assign(data, remoteSettings.additionalParams);
var params = _serializeData(setData);
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
if (http.readyState == XMLHttpRequest.DONE) {
if(remoteSettings.successCallback) {
remoteSettings.successCallback();
}
} else {
if(remoteSettings.errorCallback) {
remoteSettings.errorCallback();
} else {
throw 'Remote error logging failed!';
}
}
}
}
}
function _serializeData(params) {
return Object.keys(params).map(function(k) {
return encodeURIComponent(k) + "=" + encodeURIComponent(params[k]);
}).join('&');
}
function _errorData(e) {
var filename = e.filename.lastIndexOf('/');
var datetime = new Date().toString();
return {
type: e.type,
path: e.filename,
filename: e.filename.substring(++filename),
line: e.lineno,
column: e.colno,
error: e.message,
stackTrace: e.error.stack.toString().replace(/(\r\n|\n|\r)/gm,""),
datetime: datetime
}
}
return {
init: init
}
}();
|
JavaScript
| 0 |
@@ -315,24 +315,42 @@
tion() %7B%0A %0A
+ var setConfig;%0A%0A
function i
@@ -376,16 +376,19 @@
) %7B%0A
+%0A
// Defau
@@ -404,18 +404,16 @@
uration%0A
-
var co
@@ -621,28 +621,24 @@
%7D%0A %7D%0A
-
%0A // Over
@@ -663,20 +663,16 @@
fig%0A
-var
setConfi
@@ -725,71 +725,205 @@
//
- Listen to errors%0A window.addEventListener('error', function
+Remove current listener%0A window.removeEventListener('error', _listener );%0A // Listen to errors%0A window.addEventListener('error', _listener );%0A %7D%0A %0A // NOTE: Private%0A function _listener
(e)
@@ -1110,36 +1110,9 @@
%7D
-);%0A %7D%0A %0A // NOTE: Private
+%0A
%0A f
|
2250426ddf26e966864a4d0e7963152a3634c359
|
Fix 'add cordova platforms' test
|
tools/tests/cordova-platforms.js
|
tools/tests/cordova-platforms.js
|
var selftest = require('../selftest.js');
var Sandbox = selftest.Sandbox;
var files = require('../files.js');
selftest.define("add cordova platforms", function () {
var s = new Sandbox();
var run;
// Starting a run
s.createApp("myapp", "package-tests");
s.cd("myapp");
s.set("METEOR_TEST_TMP", files.mkdtemp());
run = s.run("run", "android");
run.matchErr("Platform is not added");
run.match("meteor add-platform android");
run.expectExit(1);
// XXX: This prints the Android EULA.
// We should move this to a once-per-machine agreement.
/*
run = s.run("add-platform", "android");
run.matchErr("Platform is not installed");
run.expectExit(2);
*/
run = s.run("install-sdk", "android");
run.extraTime = 90; // Big downloads
run.expectExit(0);
run = s.run("add-platform", "android");
run.match("Do you agree");
run.write("Y\n");
run.extraTime = 90; // Huge download
run.match("added");
run = s.run("remove-platform", "foo");
run.match("foo: platform is not");
run = s.run("remove-platform", "android");
run.match("removed");
run = s.run("run", "android");
run.matchErr("Platform is not added");
run.match("meteor add-platform android");
run.expectExit(1);
});
|
JavaScript
| 0.000082 |
@@ -371,35 +371,67 @@
hErr(%22Pl
-atform is not added
+ease add the Android platform to your project first
%22);%0A ru
@@ -487,17 +487,17 @@
ectExit(
-1
+2
);%0A%0A //
@@ -1167,27 +1167,59 @@
(%22Pl
-atform is not added
+ease add the Android platform to your project first
%22);%0A
@@ -1283,9 +1283,9 @@
xit(
-1
+2
);%0A%7D
|
b00fc0523f72031fdf3baafe50fda99b01e85c3f
|
Fix Typo in reporting when Cookie has been found
|
plugins/GUID.js
|
plugins/GUID.js
|
/*
Tag users with a unique GUID
*/
(function(w) {
var impl = {
expires: 604800,
cookieName: "GUID",
generate: function() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
};
return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}
};
BOOMR.plugins.GUID = {
init: function(config) {
var properties = ["cookieName", "expires"];
BOOMR.utils.pluginConfig(impl, config, "GUID", properties);
BOOMR.info("Initializing plugin GUID " + impl.cookieName , "GUID");
if( BOOMR.utils.getCookie(impl.cookieName) == null ) {
BOOMR.info("Could not find a cookie for " + impl.cookieName, "GUID");
var guid = impl.generate();
BOOMR.utils.setCookie(impl.cookieName,guid, impl.expires);
BOOMR.info("Setting GUID Cookie value to: " + guid + " expiring in: " + impl.expires + "s", "GUID");
} else {
BOOMR.info("Found a cookie named: " + impl.cookieName + " value: " + BOOMR.getCookie(impl.cookieName) , "GUID");
}
return this;
},
is_complete: function() {
return true;
}
};
}(this));
|
JavaScript
| 0 |
@@ -997,16 +997,22 @@
+ BOOMR.
+utils.
getCooki
|
452bddcbb7e93071bb8a2926743b26817ccfc80b
|
Fix typo in observable name.
|
public/app/models/ListModeSwitcher.js
|
public/app/models/ListModeSwitcher.js
|
(function () {
'use strict';
define(
[
'lodash',
'knockout'
],
function (_, ko) {
var AVAILABLE_MODES = [ 'List', 'Thumbnails', 'Table' ];
return function (mode) {
this.mode = ko.observable(mode || AVAILABLE_MODES[0]);
this.availableModes = ko.pureComputed(function () {
return AVAILABLE_MODES;
});
this.resultsContainerClassName = ko.pureComputed(function () {
return 'results-container-' + this.resultsMode().toLowerCase();
}.bind(this));
};
}
);
}());
|
JavaScript
| 0.000055 |
@@ -582,16 +582,9 @@
his.
-resultsM
+m
ode(
|
75d850f133b3497221c63d4139ab8bc960b5bc01
|
Update disabled prop based on zero states for mobile.
|
assets/js/modules/analytics/components/dashboard/DashboardAllTrafficWidget/DimensionTabs.js
|
assets/js/modules/analytics/components/dashboard/DashboardAllTrafficWidget/DimensionTabs.js
|
/**
* DimensionTabs component
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import PropTypes from 'prop-types';
import Tab from '@material/react-tab';
import TabBar from '@material/react-tab-bar';
/**
* WordPress dependencies
*/
import { Fragment, useCallback, useContext } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import Data from 'googlesitekit-data';
import ViewContextContext from '../../../../../components/Root/ViewContextContext';
import { CORE_UI } from '../../../../../googlesitekit/datastore/ui/constants';
import {
UI_DIMENSION_COLOR,
UI_DIMENSION_NAME,
UI_DIMENSION_VALUE,
UI_ACTIVE_ROW_INDEX,
} from '../../../datastore/constants';
import PreviewBlock from '../../../../../components/PreviewBlock';
import { Select, Option } from '../../../../../material-components';
import { trackEvent } from '../../../../../util';
import { useFeature } from '../../../../../hooks/useFeature';
const { useDispatch } = Data;
const tabs = [
{
tabText: __( 'Channels', 'google-site-kit' ),
dimensionName: 'ga:channelGrouping',
},
{
tabText: __( 'Locations', 'google-site-kit' ),
dimensionName: 'ga:country',
},
{
tabText: __( 'Devices', 'google-site-kit' ),
dimensionName: 'ga:deviceCategory',
},
];
export default function DimensionTabs( {
dimensionName,
gatheringData,
loaded,
isZeroData,
} ) {
const viewContext = useContext( ViewContextContext );
const { setValues } = useDispatch( CORE_UI );
const zeroDataStatesEnabled = useFeature( 'zeroDataStates' );
const activeTab = tabs.findIndex(
( v ) => v.dimensionName === dimensionName
);
const handleTabUpdate = useCallback(
( index ) => {
const { dimensionName: name } = tabs[ index ] || {};
setValues( {
[ UI_DIMENSION_NAME ]: name,
[ UI_DIMENSION_VALUE ]: '',
[ UI_DIMENSION_COLOR ]: '',
[ UI_ACTIVE_ROW_INDEX ]: null,
} );
trackEvent(
`${ viewContext }_all-traffic-widget`,
'tab_select',
name
);
},
[ setValues, viewContext ]
);
if ( ! loaded ) {
return (
<div className="googlesitekit-widget--analyticsAllTraffic__tabs--loading">
<PreviewBlock width="100px" height="40px" shape="square" />
<PreviewBlock width="100px" height="40px" shape="square" />
<PreviewBlock width="100px" height="40px" shape="square" />
</div>
);
}
return (
<Fragment>
<div className="googlesitekit-widget--analyticsAllTraffic__tabs hidden-on-mobile">
<TabBar
activeIndex={ activeTab }
handleActiveIndexUpdate={ handleTabUpdate }
>
{ tabs.map( ( tab ) => (
<Tab
key={ tab.dimensionName }
className="mdc-tab--min-width"
focusOnActivate={ false }
disabled={
gatheringData ||
( zeroDataStatesEnabled && isZeroData )
}
>
<span className="mdc-tab__text-label">
{ tab.tabText }
</span>
</Tab>
) ) }
</TabBar>
</div>
<div className="googlesitekit-widget--analyticsAllTraffic__tabs--small">
<Select
enhanced
onEnhancedChange={ handleTabUpdate }
outlined
value={ `dimension-name-${ activeTab }` }
disabled={ gatheringData }
>
{ tabs.map( ( tab, index ) => (
<Option
key={ index }
value={ `dimension-name-${ index }` }
>
{ tab.tabText }
</Option>
) ) }
</Select>
</div>
</Fragment>
);
}
DimensionTabs.propTypes = {
dimensionName: PropTypes.string.isRequired,
gatheringData: PropTypes.bool,
isZeroData: PropTypes.bool,
loaded: PropTypes.bool,
};
|
JavaScript
| 0 |
@@ -3763,17 +3763,23 @@
sabled=%7B
-
+%0A%09%09%09%09%09%09
gatherin
@@ -3784,16 +3784,64 @@
ingData
+%7C%7C ( zeroDataStatesEnabled && isZeroData )%0A%09%09%09%09%09
%7D%0A%09%09%09%09%3E%0A
|
f553051867776b517d8c7d1871d2a763001bcc70
|
Fix basic view click handling
|
inspector/views/containerView.js
|
inspector/views/containerView.js
|
'use strict';
import * as helper from '../helper.js';
export default class ContainerView {
constructor(inspectorContent, originalParent, originalElements, hierarchyLevel=undefined) {
this._inspectorContent = inspectorContent;
this._showedLevel = 0;
this._maxNestedLevel = 0;
this._create(originalParent, originalElements);
// Show defined hierarchy level if specified
if (hierarchyLevel !== undefined) {
this.showHierarchyLevel(hierarchyLevel);
}
}
getShowedLevel() {
return this._showedLevel;
}
getMaxNestedLevel() {
return this._maxNestedLevel;
}
showHierarchyLevel(level) {
if (level > this._maxNestedLevel || level < 0) {
return;
}
if (level > this._showedLevel) {
// Find all elements with desired level
let allElements = this._getAllCreatedElements();
let elements = [];
for(let i = 1; i <= level; i++) {
elements = jQuery.merge(elements, jQuery(allElements).find('.nested_' + i));
}
// Show them
if(elements.length > 0) {
this._showElements(elements);
}
} else if(level < this._showedLevel) {
// Find all elements with desired level
let allElements = this._getAllCreatedElements();
let elements = [];
for(let i = this._maxNestedLevel; i > level; i--) {
elements = jQuery.merge(elements, jQuery(allElements).find('.nested_' + i));
}
// Hide them
if(elements.length > 0) {
this._hideElements(elements);
}
} else {
return;
}
this._showedLevel = level;
}
deleteElements() {
this._inspectorContent.querySelector('#' + helper.getCreatedRootSelector()).remove();
this._showedLevel = 0;
this._maxNestedLevel = 0;
}
_create(originalParent, originalElements) {
// Create a new div with the position and size of the original container.
// This div will be used as new root and is absolutely positioned. Thus it
// is easier to position the actual elements correctly.
var newParent = document.createElement('div');
newParent.id = helper.getCreatedRootSelector();
helper.copySpacing(newParent, originalParent);
helper.copySize(newParent, originalParent);
// newParent.style.top = this._inspectorContent.querySelector('#inspector-content').shadowRoot.querySelector('#container-root').getBoundingClientRect().top + 'px';
// newParent.style.left = this._inspectorContent.querySelector('#inspector-content').shadowRoot.querySelector('#container-root').getBoundingClientRect().left + 'px';
this._inspectorContent.appendChild(newParent);
for (let i = 0; i < originalElements.length; i++) {
if (originalElements[i].tagName != 'SCRIPT' && originalElements[i].tagName != 'LINK') {
this._copyElement(newParent, originalElements[i]);
}
}
}
_copyElement(parentElement, element, nested = false, nestingLevel = 0, fixedPosition = false) {
let newElement = document.createElement('div');
// Set style information for the new element
helper.copySpacing(newElement, element);
newElement.style.borderColor = helper.getColourFromInt(nestingLevel);
newElement.style.display = window.getComputedStyle(element, null).display;
newElement.classList.add('created');
// Child elements are hidden by default --> only first hierarchy level is shown
if(nested) {
newElement.style.visibility = 'hidden';
newElement.classList.add('nested_' + nestingLevel);
}
if(element.id === "") {
element.id = helper.getRandomId();
}
newElement.dataset.id = element.id;
// This is a really ugly hack to get only the text of the actual element
let text = jQuery(element).clone().children().remove().end().text().trim();
newElement.dataset.content = (text.length > 0) ? text : element.tagName;
parentElement.appendChild(newElement);
// Only the last children of the hierarchy and element with text inside need an actual sizement.
// All other elements are sized by their children
if(element.children.length === 0 || text.length !== 0 ) {
helper.copySize(newElement, element);
}
// Elements whose parent has some text inside need a concrete positioning.
// Because we do not copy the text the position gets lost.
if(fixedPosition) {
helper.copyPosition(newElement, element, parentElement);
}
// Keep hierarchy information by adding child elements recursively
if(element.children.length > 0) {
nestingLevel += 1;
for(let j = 0; j < element.children.length; j++) {
this._copyElement(newElement, element.children[j], true, nestingLevel, text.length !== 0);
}
}
if (nestingLevel > this._maxNestedLevel) {
this._maxNestedLevel = nestingLevel;
}
// Add click handler
newElement.onclick = (e) => this._handleOnClick(e, newElement, element);
}
_showElements(elements) {
for(let i = 0; i < elements.length; i++) {
elements[i].style.visibility = 'visible';
}
}
_hideElements(elements) {
for(let i = 0; i < elements.length; i++) {
elements[i].style.visibility = 'hidden';
}
}
_getAllCreatedElements() {
return this._inspectorContent.getElementsByClassName('created');
}
_showAllHierarchyLevels() {
let elements = this._getAllCreatedElements();
this._showElements(elements);
this._showedLevel = this._maxNestedLevel;
}
//
// Click handlers
//
_handleOnClick(e, newElement, originalElement) {
// Pass click event
originalElement.click();
// Highlight original element
originalElement.style.backgroundColor = 'red';
window.setTimeout(() => {
originalElement.style.backgroundColor = 'initial';
}, 1000);
}
}
|
JavaScript
| 0.000348 |
@@ -3617,16 +3617,49 @@
nt.id;%0A%0A
+ // Set elements content data%0A
// T
@@ -3884,16 +3884,21 @@
agName;%0A
+ %0A
pare
@@ -5560,24 +5560,48 @@
lElement) %7B%0A
+ e.stopPropagation()%0A
// Pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.