language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function partition(array, funck){
// make a for loop to run through each element
var newArray=[];
var otherArr = [];
var collection = [];
for (var i =0; i <= array.length -1; i++ ){
if (funck(array[i], i, array)){
newArray.push(array[i]);
} else if (funck(array[i], i, array)!== true){
otherArr.push(array[i]);
}
}
collection.push(newArray);
collection.push(otherArr);
return collection;
} | function partition(array, funck){
// make a for loop to run through each element
var newArray=[];
var otherArr = [];
var collection = [];
for (var i =0; i <= array.length -1; i++ ){
if (funck(array[i], i, array)){
newArray.push(array[i]);
} else if (funck(array[i], i, array)!== true){
otherArr.push(array[i]);
}
}
collection.push(newArray);
collection.push(otherArr);
return collection;
} |
JavaScript | function map(array,callback) {
// create container for return value of function
var newArr = [];
// create if statement condition true array type is an array
if(Array.isArray(array)) {
// create for loop
for(var i = 0; i < array.length; i++) {
// push function results into array container
newArr.push(callback(array[i],i, array));
// else statement if this is false
}
} else {
// for in loop for object
for(var key in array) {
// push function action results into newAr container
newArr.push(callback(array[key], key, array));
}
}
// return newArr
return newArr;
} | function map(array,callback) {
// create container for return value of function
var newArr = [];
// create if statement condition true array type is an array
if(Array.isArray(array)) {
// create for loop
for(var i = 0; i < array.length; i++) {
// push function results into array container
newArr.push(callback(array[i],i, array));
// else statement if this is false
}
} else {
// for in loop for object
for(var key in array) {
// push function action results into newAr container
newArr.push(callback(array[key], key, array));
}
}
// return newArr
return newArr;
} |
JavaScript | function pluck(array,key){
return map(array,(object, i, a )=>{
return object[key];
});
} | function pluck(array,key){
return map(array,(object, i, a )=>{
return object[key];
});
} |
JavaScript | function every(collection,action) {
if(action === undefined) {
action = function (collectstuff) {
if(!!collectstuff == true) {
return true;
} else {
return false;
}
};
}
if(Array.isArray(collection)) {
for(var i =0; i < collection.length; i++) {
if(action(collection[i], i, collection) === false) {
return false;
}
}
return true;
} else if(typeof(collection) === "object"){
for (var key in collection) {
if(action(collection[key], key, collection) === false) {
return false;
}
}
return true;
}
} | function every(collection,action) {
if(action === undefined) {
action = function (collectstuff) {
if(!!collectstuff == true) {
return true;
} else {
return false;
}
};
}
if(Array.isArray(collection)) {
for(var i =0; i < collection.length; i++) {
if(action(collection[i], i, collection) === false) {
return false;
}
}
return true;
} else if(typeof(collection) === "object"){
for (var key in collection) {
if(action(collection[key], key, collection) === false) {
return false;
}
}
return true;
}
} |
JavaScript | function some(collection,action) {
if(action === undefined) {
action = function (collect) {
if(!!collect == true) {
return true;
} else {
return false;
}
};
}
if(Array.isArray(collection)) {
for(var i =0; i < collection.length; i++) {
if(action(collection[i], i, collection) === true) {
return true;
}
}
return false;
} else if(typeof(collection) === "object"){
for (var key in collection) {
if(action(collection[key], key, collection) === true) {
return true;
}
}
return false;
}
} | function some(collection,action) {
if(action === undefined) {
action = function (collect) {
if(!!collect == true) {
return true;
} else {
return false;
}
};
}
if(Array.isArray(collection)) {
for(var i =0; i < collection.length; i++) {
if(action(collection[i], i, collection) === true) {
return true;
}
}
return false;
} else if(typeof(collection) === "object"){
for (var key in collection) {
if(action(collection[key], key, collection) === true) {
return true;
}
}
return false;
}
} |
JavaScript | function reduce(array,action,seed) {
if(seed === undefined) {
for (var i = 0;i <= array.length - 1; i++) {
// if the first iteration ends and there is no seed, we use the first array element
// if its not the first iteration call action on previous result, element ,index
if(i === 0) {
seed = array[0];
// implement action
} else {
seed = action(seed,array[i],i);
}
}
// if there is a seed, then
} else {
for(var i = 0; i < array.length; i++) {
seed = action(seed,array[i],i)
}
}
return seed;
} | function reduce(array,action,seed) {
if(seed === undefined) {
for (var i = 0;i <= array.length - 1; i++) {
// if the first iteration ends and there is no seed, we use the first array element
// if its not the first iteration call action on previous result, element ,index
if(i === 0) {
seed = array[0];
// implement action
} else {
seed = action(seed,array[i],i);
}
}
// if there is a seed, then
} else {
for(var i = 0; i < array.length; i++) {
seed = action(seed,array[i],i)
}
}
return seed;
} |
JavaScript | function extend(object1, ...restOfObjects){
// 1 working with an array of objects, grab all properties/values of every object pass in
for (let i = 0; i < restOfObjects.length; i++){
// 2 iterate over rest of objects
for (var key in restOfObjects[i]){
// 3 inside that for loop, iterate through every object's properties
object1[key] = restOfObjects[i][key];
}
// 4 while iterating through those, assign all of the propeties and their values onto object1
} return object1;
} | function extend(object1, ...restOfObjects){
// 1 working with an array of objects, grab all properties/values of every object pass in
for (let i = 0; i < restOfObjects.length; i++){
// 2 iterate over rest of objects
for (var key in restOfObjects[i]){
// 3 inside that for loop, iterate through every object's properties
object1[key] = restOfObjects[i][key];
}
// 4 while iterating through those, assign all of the propeties and their values onto object1
} return object1;
} |
JavaScript | function calcMaxExtent() {
let maxExtent = 0.0;
for (i = 0; i < 3; i++) {
if (globalExtent[i] > maxExtent)
maxExtent = globalExtent[i];
}
return maxExtent;
} | function calcMaxExtent() {
let maxExtent = 0.0;
for (i = 0; i < 3; i++) {
if (globalExtent[i] > maxExtent)
maxExtent = globalExtent[i];
}
return maxExtent;
} |
JavaScript | redraw() {
// init root container
let containerDiv = this.domHelper.initRootContainer();
// add note if filter is empty
if (this.containers.length < 1) {
containerDiv.appendChild(this.domHelper.buildEmptyFilterNote());
}
// create container elements
for (let currentContainer of this.containers) {
// build container
let container = this.domHelper.buildContainer(currentContainer);
container.appendChild(this.domHelper.buildContainerHeader(currentContainer));
container.appendChild(this.domHelper.buildLayerContainer(currentContainer));
containerDiv.appendChild(container);
// calculate suggestions
for (let currentLayer of currentContainer.layers)
this.setSuggestionsEngine(this, currentContainer, currentLayer);
}
// set general widget properties
this.domHelper.setContainerHeaderProperties(this.containers);
// set special widget properties
for (let currentContainer of this.containers) {
this.domHelper.setContainerProperties(currentContainer);
}
} | redraw() {
// init root container
let containerDiv = this.domHelper.initRootContainer();
// add note if filter is empty
if (this.containers.length < 1) {
containerDiv.appendChild(this.domHelper.buildEmptyFilterNote());
}
// create container elements
for (let currentContainer of this.containers) {
// build container
let container = this.domHelper.buildContainer(currentContainer);
container.appendChild(this.domHelper.buildContainerHeader(currentContainer));
container.appendChild(this.domHelper.buildLayerContainer(currentContainer));
containerDiv.appendChild(container);
// calculate suggestions
for (let currentLayer of currentContainer.layers)
this.setSuggestionsEngine(this, currentContainer, currentLayer);
}
// set general widget properties
this.domHelper.setContainerHeaderProperties(this.containers);
// set special widget properties
for (let currentContainer of this.containers) {
this.domHelper.setContainerProperties(currentContainer);
}
} |
JavaScript | deactivateContainer(event) {
let container = event.target.container;
let filter = event.target.filter;
container.switchActivated();
filter.apply(event);
filter.redraw();
} | deactivateContainer(event) {
let container = event.target.container;
let filter = event.target.filter;
container.switchActivated();
filter.apply(event);
filter.redraw();
} |
JavaScript | moveContainer(event) {
event.stopPropagation();
let filter = event.target.filter;
let containers = filter.containers;
let container = event.target.container;
let source = containers.indexOf(container);
let target = event.target.isDirectionUp ? source - 1 : source + 1;
if (source >= 0 && target >= 0 && target <= containers.length - 1) {
let swap = containers[target];
containers[target] = containers[source];
containers[source] = swap;
filter.apply(event);
filter.redraw();
}
} | moveContainer(event) {
event.stopPropagation();
let filter = event.target.filter;
let containers = filter.containers;
let container = event.target.container;
let source = containers.indexOf(container);
let target = event.target.isDirectionUp ? source - 1 : source + 1;
if (source >= 0 && target >= 0 && target <= containers.length - 1) {
let swap = containers[target];
containers[target] = containers[source];
containers[source] = swap;
filter.apply(event);
filter.redraw();
}
} |
JavaScript | addLayer(event) {
let filter = event.target.filter;
let container = event.target.container;
let l = new Layer(++filter.layerCounter);
container.addLayer(l);
// console.log("added layer:", filter.layerCounter);
filter.apply(event);
filter.redraw();
} | addLayer(event) {
let filter = event.target.filter;
let container = event.target.container;
let l = new Layer(++filter.layerCounter);
container.addLayer(l);
// console.log("added layer:", filter.layerCounter);
filter.apply(event);
filter.redraw();
} |
JavaScript | removeLayer(event) {
let filter = event.target.filter;
event.target.container.removeLayer(event.target.layer);
filter.apply(event);
filter.redraw();
} | removeLayer(event) {
let filter = event.target.filter;
event.target.container.removeLayer(event.target.layer);
filter.apply(event);
filter.redraw();
} |
JavaScript | moveLayer(event) {
let filter = event.target.filter;
let layers = event.target.layers;
let source = layers.indexOf(event.target.layer);
let target = event.target.isDirectionUp ? source - 1 : source + 1;
if (source >= 0 && target >= 0 && target <= layers.length - 1) {
let swap = layers[target];
layers[target] = layers[source];
layers[source] = swap;
filter.apply(event);
filter.redraw();
}
} | moveLayer(event) {
let filter = event.target.filter;
let layers = event.target.layers;
let source = layers.indexOf(event.target.layer);
let target = event.target.isDirectionUp ? source - 1 : source + 1;
if (source >= 0 && target >= 0 && target <= layers.length - 1) {
let swap = layers[target];
layers[target] = layers[source];
layers[source] = swap;
filter.apply(event);
filter.redraw();
}
} |
JavaScript | apply(event) {
let filter = event ? event.target.filter : this;
// associate arrays with transformation strings
let tMap = new Map([
[Constants.transformations.visible, []],
[Constants.transformations.invisible, []],
[Constants.transformations.opaque, []],
[Constants.transformations.transparent, []],
[Constants.transformations.selected, []],
[Constants.transformations.connected, []]
]);
// reset transformations
TransformationHelper.resetTransformations(filter);
// handle one container after the other
for (let container of filter.containers) {
// skip deactivated containers
if (!container.activated) continue;
// calculate suggestions
filter.calculateSuggestions(filter, container);
// get selected transformation as key
let tKey = container.transformations[container.transformation];
// get isolated container selection
let selection = filter.handleContainer(filter, container);
// make relations visible
if (container.relations) TransformationHelper.makeEntitiesVisible(selection);
// selections of containers add up
let union = tMap.get(tKey).concat(selection);
// remove duplicates of selection
union = union.filter((entity, index) => {
return union.indexOf(entity) === index;
});
tMap.set(tKey, union);
// apply transformations
if (container.layers.every(layer => layer.faulty == false)) {
// console.table(Array.from(tMap).map(entry => [entry[0], entry[1].length]));
if (tKey == Constants.transformations.visible)
TransformationHelper.makeEntitiesVisible(tMap.get(Constants.transformations.visible));
else if (tKey == Constants.transformations.invisible)
TransformationHelper.makeEntitiesInvisible(tMap.get(Constants.transformations.invisible));
else if (tKey == Constants.transformations.transparent) {
TransformationHelper.makeEntitiesTransparent(
tMap.get(Constants.transformations.transparent)
);
} else if (tKey == Constants.transformations.opaque)
TransformationHelper.makeEntitiesOpaque(tMap.get(Constants.transformations.opaque));
else if (tKey == Constants.transformations.selected)
TransformationHelper.selectEntities(tMap.get(Constants.transformations.selected));
else if (tKey == Constants.transformations.connected) {
TransformationHelper.connectEntities(
tMap.get(Constants.transformations.connected),
filter.loadedPositions
);
}
} else {
// reset transformations
TransformationHelper.resetTransformations(filter);
console.info(Constants.strings.invalidFilter);
}
}
// update filter UI
filter.redraw();
} | apply(event) {
let filter = event ? event.target.filter : this;
// associate arrays with transformation strings
let tMap = new Map([
[Constants.transformations.visible, []],
[Constants.transformations.invisible, []],
[Constants.transformations.opaque, []],
[Constants.transformations.transparent, []],
[Constants.transformations.selected, []],
[Constants.transformations.connected, []]
]);
// reset transformations
TransformationHelper.resetTransformations(filter);
// handle one container after the other
for (let container of filter.containers) {
// skip deactivated containers
if (!container.activated) continue;
// calculate suggestions
filter.calculateSuggestions(filter, container);
// get selected transformation as key
let tKey = container.transformations[container.transformation];
// get isolated container selection
let selection = filter.handleContainer(filter, container);
// make relations visible
if (container.relations) TransformationHelper.makeEntitiesVisible(selection);
// selections of containers add up
let union = tMap.get(tKey).concat(selection);
// remove duplicates of selection
union = union.filter((entity, index) => {
return union.indexOf(entity) === index;
});
tMap.set(tKey, union);
// apply transformations
if (container.layers.every(layer => layer.faulty == false)) {
// console.table(Array.from(tMap).map(entry => [entry[0], entry[1].length]));
if (tKey == Constants.transformations.visible)
TransformationHelper.makeEntitiesVisible(tMap.get(Constants.transformations.visible));
else if (tKey == Constants.transformations.invisible)
TransformationHelper.makeEntitiesInvisible(tMap.get(Constants.transformations.invisible));
else if (tKey == Constants.transformations.transparent) {
TransformationHelper.makeEntitiesTransparent(
tMap.get(Constants.transformations.transparent)
);
} else if (tKey == Constants.transformations.opaque)
TransformationHelper.makeEntitiesOpaque(tMap.get(Constants.transformations.opaque));
else if (tKey == Constants.transformations.selected)
TransformationHelper.selectEntities(tMap.get(Constants.transformations.selected));
else if (tKey == Constants.transformations.connected) {
TransformationHelper.connectEntities(
tMap.get(Constants.transformations.connected),
filter.loadedPositions
);
}
} else {
// reset transformations
TransformationHelper.resetTransformations(filter);
console.info(Constants.strings.invalidFilter);
}
}
// update filter UI
filter.redraw();
} |
JavaScript | handleContainer(filter, container) {
let selection = [];
for (let layer of container.layers) {
if (!layer.activated) continue;
if (layer.query == null || layer.query == '') {
// first container treats all entities as visible, although they are invisible by default
if (filter.containers.indexOf(container) == 0) {
selection = filter.visualizedEntities;
} else {
selection = filter.visualizedEntities.filter(entity => !entity.filtered);
}
layer.entity = null;
layer.faulty = false;
} else {
// get entity with (query == entity.qualifiedName) test
let entity = FilterHelper.getEntityFromQN(layer.query);
layer.entity = entity ? entity : null;
// set error indicator for current layer
layer.faulty = layer.entity == null;
if (layer.entity) {
// add parent
selection.push(layer.entity);
// add all children and children of children
if (layer.includeChilds) {
let allChildren = [];
FilterHelper.getAllChildren(layer.entity, allChildren);
selection = selection.concat(allChildren);
}
}
}
}
// subtract selected entities from all entities
if (container.relations) {
let relations = [];
let fields = ['subTypes', 'superTypes', 'accessedBy', 'accesses', 'calls', 'calledBy'];
for (let entity of selection) {
for (let field of fields) {
if (entity[field]) {
relations = relations.concat(entity[field]);
// console.log(field, entity[field], entity);
}
}
}
// remove duplicates
relations = relations.filter((entity, index) => {
return relations.indexOf(entity) === index;
});
selection = selection.concat(relations);
}
// subtract selected entities from all entities
if (container.inverted)
selection = filter.visualizedEntities.filter(ent => selection.indexOf(ent) == -1);
// console.log(container.id, 'selection final', selection);
return selection.map(entity => entity.id);
} | handleContainer(filter, container) {
let selection = [];
for (let layer of container.layers) {
if (!layer.activated) continue;
if (layer.query == null || layer.query == '') {
// first container treats all entities as visible, although they are invisible by default
if (filter.containers.indexOf(container) == 0) {
selection = filter.visualizedEntities;
} else {
selection = filter.visualizedEntities.filter(entity => !entity.filtered);
}
layer.entity = null;
layer.faulty = false;
} else {
// get entity with (query == entity.qualifiedName) test
let entity = FilterHelper.getEntityFromQN(layer.query);
layer.entity = entity ? entity : null;
// set error indicator for current layer
layer.faulty = layer.entity == null;
if (layer.entity) {
// add parent
selection.push(layer.entity);
// add all children and children of children
if (layer.includeChilds) {
let allChildren = [];
FilterHelper.getAllChildren(layer.entity, allChildren);
selection = selection.concat(allChildren);
}
}
}
}
// subtract selected entities from all entities
if (container.relations) {
let relations = [];
let fields = ['subTypes', 'superTypes', 'accessedBy', 'accesses', 'calls', 'calledBy'];
for (let entity of selection) {
for (let field of fields) {
if (entity[field]) {
relations = relations.concat(entity[field]);
// console.log(field, entity[field], entity);
}
}
}
// remove duplicates
relations = relations.filter((entity, index) => {
return relations.indexOf(entity) === index;
});
selection = selection.concat(relations);
}
// subtract selected entities from all entities
if (container.inverted)
selection = filter.visualizedEntities.filter(ent => selection.indexOf(ent) == -1);
// console.log(container.id, 'selection final', selection);
return selection.map(entity => entity.id);
} |
JavaScript | function executeFunctionByName(functionName, context /*, args */) {
var args = [].slice.call(arguments).splice(2);
var namespaces = functionName.split(".");
var func = namespaces.pop();
for(var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return context[func].apply(context, args);
} | function executeFunctionByName(functionName, context /*, args */) {
var args = [].slice.call(arguments).splice(2);
var namespaces = functionName.split(".");
var func = namespaces.pop();
for(var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return context[func].apply(context, args);
} |
JavaScript | function obfuscateUserLinks() {
const userLoginName = getUserLoginName();
function obfuscateLink(anchorElement) {
const href = anchorElement.getAttribute('href');
if (
anchorElement.dataset.biasedHref ||
href.startsWith(`/${userLoginName}`) ||
href.startsWith(`${location.origin}/${userLoginName}`)
) {
return;
}
const unbiasedHref = href.replace(
/\/([\w-_]+)$/,
(_, name) => `/@unbiased-github/?unbiased-name=${encryptUserName(name)}`
);
anchorElement.dataset.biasedHref = href;
anchorElement.setAttribute('href', unbiasedHref);
}
const unobserve = observe(
'a[data-hovercard-type="user"]:not([data-biased-href]), [data-hovercard-type="user"] a:not([data-biased-href])',
obfuscateLink
);
return () => {
unobserve();
document.querySelectorAll('[data-biased-href]').forEach(element => {
element.setAttribute('href', element.dataset.biasedHref);
delete element.dataset.biasedHref;
});
};
} | function obfuscateUserLinks() {
const userLoginName = getUserLoginName();
function obfuscateLink(anchorElement) {
const href = anchorElement.getAttribute('href');
if (
anchorElement.dataset.biasedHref ||
href.startsWith(`/${userLoginName}`) ||
href.startsWith(`${location.origin}/${userLoginName}`)
) {
return;
}
const unbiasedHref = href.replace(
/\/([\w-_]+)$/,
(_, name) => `/@unbiased-github/?unbiased-name=${encryptUserName(name)}`
);
anchorElement.dataset.biasedHref = href;
anchorElement.setAttribute('href', unbiasedHref);
}
const unobserve = observe(
'a[data-hovercard-type="user"]:not([data-biased-href]), [data-hovercard-type="user"] a:not([data-biased-href])',
obfuscateLink
);
return () => {
unobserve();
document.querySelectorAll('[data-biased-href]').forEach(element => {
element.setAttribute('href', element.dataset.biasedHref);
delete element.dataset.biasedHref;
});
};
} |
JavaScript | function handleMouseOver(e) {
// Stop when itself has hovercard, or it's inside a hovercard element
const hovercard = e.target.closest('[data-hovercard-type="user"]');
if (hovercard) {
if (
userLoginName &&
hovercard.dataset.hovercardUrl === `/users/${userLoginName}/hovercard`
) {
return;
}
e.stopImmediatePropagation();
}
} | function handleMouseOver(e) {
// Stop when itself has hovercard, or it's inside a hovercard element
const hovercard = e.target.closest('[data-hovercard-type="user"]');
if (hovercard) {
if (
userLoginName &&
hovercard.dataset.hovercardUrl === `/users/${userLoginName}/hovercard`
) {
return;
}
e.stopImmediatePropagation();
}
} |
JavaScript | function rainbow(num, step) {
var r, g, b;
var h = step / num;
var i = ~~(h * 6);
var f = h * 6 - i;
var q = 1 - f;
switch(i % 6){
case 0: r = 0.9; g = f; b = 0.1; break;
case 1: r = q; g = 0.9; b = 0.1; break;
case 2: r = 0.1; g = 0.9; b = f; break;
case 3: r = 0.1; g = q; b = 0.9; break;
case 4: r = f; g = 0.1; b = 0.9; break;
case 5: r = 0.9; g = 0.1; b = q; break;
}
var c = "#" + ("00" + (~ ~(r * 255)).toString(16)).slice(-2) + ("00" + (~ ~(g * 255)).toString(16)).slice(-2) + ("00" + (~ ~(b * 255)).toString(16)).slice(-2);
return (c);
} | function rainbow(num, step) {
var r, g, b;
var h = step / num;
var i = ~~(h * 6);
var f = h * 6 - i;
var q = 1 - f;
switch(i % 6){
case 0: r = 0.9; g = f; b = 0.1; break;
case 1: r = q; g = 0.9; b = 0.1; break;
case 2: r = 0.1; g = 0.9; b = f; break;
case 3: r = 0.1; g = q; b = 0.9; break;
case 4: r = f; g = 0.1; b = 0.9; break;
case 5: r = 0.9; g = 0.1; b = q; break;
}
var c = "#" + ("00" + (~ ~(r * 255)).toString(16)).slice(-2) + ("00" + (~ ~(g * 255)).toString(16)).slice(-2) + ("00" + (~ ~(b * 255)).toString(16)).slice(-2);
return (c);
} |
JavaScript | function lighten(color, amount) {
var usePound = false;
if (color[0] == "#") {
color = color.slice(1);
usePound = true;
}
var num = parseInt(color, 16);
var r = (num >> 16) + amount;
if (r > 255) r = 255;
else if (r < 0) r = 0;
var b = ((num >> 8) & 0x00FF) + amount;
if (b > 255) b = 255;
else if (b < 0) b = 0;
var g = (num & 0x0000FF) + amount;
if (g > 255) g = 255;
else if (g < 0) g = 0;
return (usePound ? "#" : "") + (g | (b << 8) | (r << 16)).toString(16);
} | function lighten(color, amount) {
var usePound = false;
if (color[0] == "#") {
color = color.slice(1);
usePound = true;
}
var num = parseInt(color, 16);
var r = (num >> 16) + amount;
if (r > 255) r = 255;
else if (r < 0) r = 0;
var b = ((num >> 8) & 0x00FF) + amount;
if (b > 255) b = 255;
else if (b < 0) b = 0;
var g = (num & 0x0000FF) + amount;
if (g > 255) g = 255;
else if (g < 0) g = 0;
return (usePound ? "#" : "") + (g | (b << 8) | (r << 16)).toString(16);
} |
JavaScript | function array_to_int(items) {
var ints = [];
for (let i=0; i<items.length; i++)
ints.push(parseInt(items[i], 10));
return ints;
} | function array_to_int(items) {
var ints = [];
for (let i=0; i<items.length; i++)
ints.push(parseInt(items[i], 10));
return ints;
} |
JavaScript | function stringToIntegerOrBoolean(parameter){
var param = parameter.toLowerCase().trim();
if(!isNaN(param)){
console.log("retrn a number");
return +param;
}
switch(param){
case "true": return true;
case "false": case null: return false;
default: return param;
}
} | function stringToIntegerOrBoolean(parameter){
var param = parameter.toLowerCase().trim();
if(!isNaN(param)){
console.log("retrn a number");
return +param;
}
switch(param){
case "true": return true;
case "false": case null: return false;
default: return param;
}
} |
JavaScript | function identify_language(file_type) {
if (config.languages.hasOwnProperty(file_type))
return config.languages[file_type].value;
return "plain_text";
} | function identify_language(file_type) {
if (config.languages.hasOwnProperty(file_type))
return config.languages[file_type].value;
return "plain_text";
} |
JavaScript | function is_editable(file_type) {
if (config.languages.hasOwnProperty(file_type) || file_type.match('text.*'))
return true;
return false;
} | function is_editable(file_type) {
if (config.languages.hasOwnProperty(file_type) || file_type.match('text.*'))
return true;
return false;
} |
JavaScript | function version_compare(a, b){
if (a == null || b == null)
return b;
return Date.parse(b["upload_time"]) - Date.parse(a["upload_time"]);
} | function version_compare(a, b){
if (a == null || b == null)
return b;
return Date.parse(b["upload_time"]) - Date.parse(a["upload_time"]);
} |
JavaScript | function XmlElement(tag) {
this.name = tag.name;
this.attr = tag.attributes || {};
this.val = "";
this.children = [];
} | function XmlElement(tag) {
this.name = tag.name;
this.attr = tag.attributes || {};
this.val = "";
this.children = [];
} |
JavaScript | function XmlDocument(xml) {
xml && (xml = xml.toString().trim());
if (!xml)
throw new Error("No XML to parse!")
var parser = sax.parser(true) // strict
addParserEvents(parser);
// We'll use the file-scoped "delegates" var to remember what elements we're currently
// parsing; they will push and pop off the stack as we get deeper into the XML hierarchy.
// It's safe to use a global because JS is single-threaded.
delegates = [this];
parser.write(xml);
} | function XmlDocument(xml) {
xml && (xml = xml.toString().trim());
if (!xml)
throw new Error("No XML to parse!")
var parser = sax.parser(true) // strict
addParserEvents(parser);
// We'll use the file-scoped "delegates" var to remember what elements we're currently
// parsing; they will push and pop off the stack as we get deeper into the XML hierarchy.
// It's safe to use a global because JS is single-threaded.
delegates = [this];
parser.write(xml);
} |
JavaScript | function _cartesianProductOf(args) {
if (arguments.length > 1) args = _.toArray(arguments);
// strings to arrays of letters
args = _.map(args, opt => (typeof opt === "string" ? _.toArray(opt) : opt));
return _.reduce(
args,
function(a, b) {
return _.flatten(
_.map(a, function(x) {
return _.map(b, function(y) {
return _.concat(x, [y]);
});
}),
true
);
},
[[]]
);
} | function _cartesianProductOf(args) {
if (arguments.length > 1) args = _.toArray(arguments);
// strings to arrays of letters
args = _.map(args, opt => (typeof opt === "string" ? _.toArray(opt) : opt));
return _.reduce(
args,
function(a, b) {
return _.flatten(
_.map(a, function(x) {
return _.map(b, function(y) {
return _.concat(x, [y]);
});
}),
true
);
},
[[]]
);
} |
JavaScript | function combinations(obj, n) {
/* filter out keys out of order, e.g. [0,1] is ok but [1,0] isn't */
function isSorted(arr) {
return _.every(arr, function(value, index, array) {
return index === 0 || String(array[index - 1]) <= String(value);
});
}
// array with n copies of the keys of obj
return _(permutations(_.keys(obj), n))
.filter(isSorted)
.map(indices => _.map(indices, i => obj[i]))
.value();
} | function combinations(obj, n) {
/* filter out keys out of order, e.g. [0,1] is ok but [1,0] isn't */
function isSorted(arr) {
return _.every(arr, function(value, index, array) {
return index === 0 || String(array[index - 1]) <= String(value);
});
}
// array with n copies of the keys of obj
return _(permutations(_.keys(obj), n))
.filter(isSorted)
.map(indices => _.map(indices, i => obj[i]))
.value();
} |
JavaScript | function combinations_with_replacement(obj, n) {
if (typeof obj == "string") obj = _.toArray(obj);
n = n ? n : obj.length;
// make n copies of keys/indices
for (var j = 0, nInds = []; j < n; j++) {
nInds.push(_.keys(obj));
}
// get product of the indices, then filter to keep elements in order
var arrangements = product(nInds).filter(pair => pair[0] <= pair[1]);
return _.map(arrangements, indices => _.map(indices, i => obj[i]));
} | function combinations_with_replacement(obj, n) {
if (typeof obj == "string") obj = _.toArray(obj);
n = n ? n : obj.length;
// make n copies of keys/indices
for (var j = 0, nInds = []; j < n; j++) {
nInds.push(_.keys(obj));
}
// get product of the indices, then filter to keep elements in order
var arrangements = product(nInds).filter(pair => pair[0] <= pair[1]);
return _.map(arrangements, indices => _.map(indices, i => obj[i]));
} |
JavaScript | addPost(req, res, next) {
Post.create({
listItem: req.body.listItem,
dateCompleted: req.body.dateCompleted,
postDescription: req.body.postDescription,
location: req.body.location,
youtubeLink: req.body.youtubeLink,
images: req.body.images,
}, (err, newPost) => {
if (err) {
next({
log: 'Error creating post. Please check middleware syntax.',
});
} else {
res.status(200).json(newPost);
}
});
} | addPost(req, res, next) {
Post.create({
listItem: req.body.listItem,
dateCompleted: req.body.dateCompleted,
postDescription: req.body.postDescription,
location: req.body.location,
youtubeLink: req.body.youtubeLink,
images: req.body.images,
}, (err, newPost) => {
if (err) {
next({
log: 'Error creating post. Please check middleware syntax.',
});
} else {
res.status(200).json(newPost);
}
});
} |
JavaScript | updatePost(req, res, next) {
const postTitle = req.params.title;
const update = {
listItem: req.body.listItem,
dateCompleted: req.body.dateCompleted,
postDescription: req.body.postDescription,
location: req.body.location,
youtubeLink: req.body.youtubeLink,
images: req.body.images,
};
Post.findOneAndUpdate({ listItem: postTitle }, update,
(err, updatedPost) => {
if (err) {
next({
log: 'Error updating post. Please check middleware syntax.',
});
} else {
res.status(200).json(updatedPost);
}
});
} | updatePost(req, res, next) {
const postTitle = req.params.title;
const update = {
listItem: req.body.listItem,
dateCompleted: req.body.dateCompleted,
postDescription: req.body.postDescription,
location: req.body.location,
youtubeLink: req.body.youtubeLink,
images: req.body.images,
};
Post.findOneAndUpdate({ listItem: postTitle }, update,
(err, updatedPost) => {
if (err) {
next({
log: 'Error updating post. Please check middleware syntax.',
});
} else {
res.status(200).json(updatedPost);
}
});
} |
JavaScript | function useDelayedState(initialState) {
const [state, setState] = useState(initialState);
const timeoutId = useRef(null);
// We use `useCallback` to match the signature of React's `useState` which will
// always return the same reference for the `setState` updater
const setStateWithDelay = useCallback((stateToSet, delayMs = 0) => {
clearTimeout(timeoutId.current);
timeoutId.current = null;
if (delayMs === 0) {
setState(stateToSet);
return;
}
timeoutId.current = setTimeout(() => {
setState(stateToSet);
timeoutId.current = null;
}, delayMs);
}, []);
useEffect(() => {
return () => {
clearTimeout(timeoutId.current);
};
}, []);
return [state, setStateWithDelay];
} | function useDelayedState(initialState) {
const [state, setState] = useState(initialState);
const timeoutId = useRef(null);
// We use `useCallback` to match the signature of React's `useState` which will
// always return the same reference for the `setState` updater
const setStateWithDelay = useCallback((stateToSet, delayMs = 0) => {
clearTimeout(timeoutId.current);
timeoutId.current = null;
if (delayMs === 0) {
setState(stateToSet);
return;
}
timeoutId.current = setTimeout(() => {
setState(stateToSet);
timeoutId.current = null;
}, delayMs);
}, []);
useEffect(() => {
return () => {
clearTimeout(timeoutId.current);
};
}, []);
return [state, setStateWithDelay];
} |
JavaScript | static get options() {
const { prefix } = settings;
return {
selectorInit: '[data-slider]',
selectorTrack: `.${prefix}--slider__track`,
selectorFilledTrack: `.${prefix}--slider__filled-track`,
selectorThumb: `.${prefix}--slider__thumb`,
selectorInput: `.${prefix}--slider__input`,
classDisabled: `${prefix}--slider--disabled`,
classThumbClicked: `${prefix}--slider__thumb--clicked`,
eventBeforeSliderValueChange: 'slider-before-value-change',
eventAfterSliderValueChange: 'slider-after-value-change',
stepMultiplier: 4,
};
} | static get options() {
const { prefix } = settings;
return {
selectorInit: '[data-slider]',
selectorTrack: `.${prefix}--slider__track`,
selectorFilledTrack: `.${prefix}--slider__filled-track`,
selectorThumb: `.${prefix}--slider__thumb`,
selectorInput: `.${prefix}--slider__input`,
classDisabled: `${prefix}--slider--disabled`,
classThumbClicked: `${prefix}--slider__thumb--clicked`,
eventBeforeSliderValueChange: 'slider-before-value-change',
eventAfterSliderValueChange: 'slider-after-value-change',
stepMultiplier: 4,
};
} |
JavaScript | static get options() {
const { prefix } = settings;
return Object.assign(Object.create(NavigationMenuPanel.options), {
selectorInit: '[data-navigation-menu]',
attribInitTarget: 'data-navigation-menu-target',
selectorShellNavSubmenu: `.${prefix}--navigation__category-toggle`,
selectorShellNavLink: `.${prefix}--navigation-link`,
selectorShellNestedNavLink: `.${prefix}--navigation__category-item > a.${prefix}--navigation-link`,
selectorShellNavLinkCurrent: `.${prefix}--navigation-item--active,.${prefix}--navigation__category-item--active`,
selectorFocusableNavItems: `
.${prefix}--navigation__category-toggle,
.${prefix}--navigation-item > .${prefix}--navigation-link,
.${prefix}--navigation-link[tabindex="0"]
`,
selectorShellNavItem: `.${prefix}--navigation-item`,
selectorShellNavCategory: `.${prefix}--navigation__category`,
selectorShellNavNestedCategory: `.${prefix}--navigation__category-item`,
classShellNavItemActive: `${prefix}--navigation-item--active`,
classShellNavLinkCurrent: `${prefix}--navigation__category-item--active`,
classShellNavCategoryExpanded: `${prefix}--navigation__category--expanded`,
});
} | static get options() {
const { prefix } = settings;
return Object.assign(Object.create(NavigationMenuPanel.options), {
selectorInit: '[data-navigation-menu]',
attribInitTarget: 'data-navigation-menu-target',
selectorShellNavSubmenu: `.${prefix}--navigation__category-toggle`,
selectorShellNavLink: `.${prefix}--navigation-link`,
selectorShellNestedNavLink: `.${prefix}--navigation__category-item > a.${prefix}--navigation-link`,
selectorShellNavLinkCurrent: `.${prefix}--navigation-item--active,.${prefix}--navigation__category-item--active`,
selectorFocusableNavItems: `
.${prefix}--navigation__category-toggle,
.${prefix}--navigation-item > .${prefix}--navigation-link,
.${prefix}--navigation-link[tabindex="0"]
`,
selectorShellNavItem: `.${prefix}--navigation-item`,
selectorShellNavCategory: `.${prefix}--navigation__category`,
selectorShellNavNestedCategory: `.${prefix}--navigation__category-item`,
classShellNavItemActive: `${prefix}--navigation-item--active`,
classShellNavLinkCurrent: `${prefix}--navigation__category-item--active`,
classShellNavCategoryExpanded: `${prefix}--navigation__category--expanded`,
});
} |
JavaScript | end() {
this.set(false);
let handleAnimationEnd = this.manage(
on(this.element, 'animationend', (evt) => {
if (handleAnimationEnd) {
handleAnimationEnd = this.unmanage(handleAnimationEnd).release();
}
if (evt.animationName === 'rotate-end-p2') {
this._deleteElement();
}
})
);
} | end() {
this.set(false);
let handleAnimationEnd = this.manage(
on(this.element, 'animationend', (evt) => {
if (handleAnimationEnd) {
handleAnimationEnd = this.unmanage(handleAnimationEnd).release();
}
if (evt.animationName === 'rotate-end-p2') {
this._deleteElement();
}
})
);
} |
JavaScript | _deleteElement() {
const { parentNode } = this.element;
parentNode.removeChild(this.element);
if (parentNode.classList.contains(this.options.selectorLoadingOverlay)) {
parentNode.remove();
}
} | _deleteElement() {
const { parentNode } = this.element;
parentNode.removeChild(this.element);
if (parentNode.classList.contains(this.options.selectorLoadingOverlay)) {
parentNode.remove();
}
} |
JavaScript | _handleClick(event) {
const numberInput = this.element.querySelector(this.options.selectorInput);
const target = event.currentTarget.getAttribute('class').split(' ');
const min = Number(numberInput.min);
const max = Number(numberInput.max);
const step = Number(numberInput.step) || 1;
if (target.indexOf('up-icon') >= 0) {
const nextValue = Number(numberInput.value) + step;
if (numberInput.max === '') {
numberInput.value = nextValue;
} else if (numberInput.value < max) {
if (nextValue > max) {
numberInput.value = max;
} else if (nextValue < min) {
numberInput.value = min;
} else {
numberInput.value = nextValue;
}
}
} else if (target.indexOf('down-icon') >= 0) {
const nextValue = Number(numberInput.value) - step;
if (numberInput.min === '') {
numberInput.value = nextValue;
} else if (numberInput.value > min) {
if (nextValue < min) {
numberInput.value = min;
} else if (nextValue > max) {
numberInput.value = max;
} else {
numberInput.value = nextValue;
}
}
}
// Programmatic change in value (including `stepUp()`/`stepDown()`) won't fire change event
numberInput.dispatchEvent(
new CustomEvent('change', {
bubbles: true,
cancelable: false,
})
);
} | _handleClick(event) {
const numberInput = this.element.querySelector(this.options.selectorInput);
const target = event.currentTarget.getAttribute('class').split(' ');
const min = Number(numberInput.min);
const max = Number(numberInput.max);
const step = Number(numberInput.step) || 1;
if (target.indexOf('up-icon') >= 0) {
const nextValue = Number(numberInput.value) + step;
if (numberInput.max === '') {
numberInput.value = nextValue;
} else if (numberInput.value < max) {
if (nextValue > max) {
numberInput.value = max;
} else if (nextValue < min) {
numberInput.value = min;
} else {
numberInput.value = nextValue;
}
}
} else if (target.indexOf('down-icon') >= 0) {
const nextValue = Number(numberInput.value) - step;
if (numberInput.min === '') {
numberInput.value = nextValue;
} else if (numberInput.value > min) {
if (nextValue < min) {
numberInput.value = min;
} else if (nextValue > max) {
numberInput.value = max;
} else {
numberInput.value = nextValue;
}
}
}
// Programmatic change in value (including `stepUp()`/`stepDown()`) won't fire change event
numberInput.dispatchEvent(
new CustomEvent('change', {
bubbles: true,
cancelable: false,
})
);
} |
JavaScript | function FeatureFlags({ children, flags = {} }) {
const parentScope = useContext(FeatureFlagContext);
const [prevParentScope, setPrevParentScope] = useState(parentScope);
const [scope, updateScope] = useState(() => {
const scope = createScope(flags);
scope.mergeWithScope(parentScope);
return scope;
});
if (parentScope !== prevParentScope) {
const scope = createScope(flags);
scope.mergeWithScope(parentScope);
updateScope(scope);
setPrevParentScope(parentScope);
}
// We use a custom hook to detect if any of the keys or their values change
// for flags that are passed in. If they have changed, then we re-create the
// FeatureFlagScope using the new flags
useChangedValue(flags, isEqual, (changedFlags) => {
const scope = createScope(changedFlags);
scope.mergeWithScope(parentScope);
updateScope(scope);
});
return (
<FeatureFlagContext.Provider value={scope}>
{children}
</FeatureFlagContext.Provider>
);
} | function FeatureFlags({ children, flags = {} }) {
const parentScope = useContext(FeatureFlagContext);
const [prevParentScope, setPrevParentScope] = useState(parentScope);
const [scope, updateScope] = useState(() => {
const scope = createScope(flags);
scope.mergeWithScope(parentScope);
return scope;
});
if (parentScope !== prevParentScope) {
const scope = createScope(flags);
scope.mergeWithScope(parentScope);
updateScope(scope);
setPrevParentScope(parentScope);
}
// We use a custom hook to detect if any of the keys or their values change
// for flags that are passed in. If they have changed, then we re-create the
// FeatureFlagScope using the new flags
useChangedValue(flags, isEqual, (changedFlags) => {
const scope = createScope(changedFlags);
scope.mergeWithScope(parentScope);
updateScope(scope);
});
return (
<FeatureFlagContext.Provider value={scope}>
{children}
</FeatureFlagContext.Provider>
);
} |
JavaScript | function useChangedValue(value, compare, callback) {
const initialRender = useRef(false);
const savedCallback = useRef(callback);
const [prevValue, setPrevValue] = useState(value);
if (!compare(prevValue, value)) {
setPrevValue(value);
}
useEffect(() => {
savedCallback.current = callback;
});
useEffect(() => {
// We only want the callback triggered after the first render
if (initialRender.current) {
savedCallback.current(prevValue);
}
}, [prevValue]);
useEffect(() => {
initialRender.current = true;
}, []);
} | function useChangedValue(value, compare, callback) {
const initialRender = useRef(false);
const savedCallback = useRef(callback);
const [prevValue, setPrevValue] = useState(value);
if (!compare(prevValue, value)) {
setPrevValue(value);
}
useEffect(() => {
savedCallback.current = callback;
});
useEffect(() => {
// We only want the callback triggered after the first render
if (initialRender.current) {
savedCallback.current(prevValue);
}
}, [prevValue]);
useEffect(() => {
initialRender.current = true;
}, []);
} |
JavaScript | function isEqual(a, b) {
if (a === b) {
return true;
}
for (const key of Object.keys(a)) {
if (a[key] !== b[key]) {
return false;
}
}
for (const key of Object.keys(b)) {
if (b[key] !== a[key]) {
return false;
}
}
return true;
} | function isEqual(a, b) {
if (a === b) {
return true;
}
for (const key of Object.keys(a)) {
if (a[key] !== b[key]) {
return false;
}
}
for (const key of Object.keys(b)) {
if (b[key] !== a[key]) {
return false;
}
}
return true;
} |
JavaScript | function testSyncSharedStyles() {
command('commands/test/sync-shared-styles', () => {
const document = Document.getSelectedDocument();
const { selectedPage: page } = document;
// Clear the current document and page
function clear() {
document.sharedLayerStyles = [];
document.sharedTextStyles = [];
page.layers = [];
}
clear();
/**
* Testing shared layer styles
*/
const sharedStyle = syncColorStyle({
document,
name: 'black',
value: '#000000',
});
if (document.sharedLayerStyles.length !== 1) {
throw new Error('Expected sync command to generate a shared layer style');
}
syncColorStyle({ document, name: 'black', value: '#000000' });
if (document.sharedLayerStyles.length !== 1) {
throw new Error(
'Expected sync command to generate only one shared layer style for ' +
'the given name'
);
}
const layer = new ShapePath({
name: 'Rectangle',
shapeType: ShapePath.ShapeType.Rectangle,
frame: new Rectangle(0, 0, 100, 100),
style: {
fills: [
{
fillType: Style.FillType.Color,
color: '#d8d8d8ff',
},
],
},
points: [
{
type: 'CurvePoint',
cornerRadius: 0,
curveFrom: { x: 0, y: 0 },
curveTo: { x: 0, y: 0 },
point: { x: 0, y: 0 },
pointType: 'Straight',
},
{
type: 'CurvePoint',
cornerRadius: 0,
curveFrom: { x: 1, y: 0 },
curveTo: { x: 1, y: 0 },
point: { x: 1, y: 0 },
pointType: 'Straight',
},
{
type: 'CurvePoint',
cornerRadius: 0,
curveFrom: { x: 1, y: 1 },
curveTo: { x: 1, y: 1 },
point: { x: 1, y: 1 },
pointType: 'Straight',
},
{
type: 'CurvePoint',
cornerRadius: 0,
curveFrom: { x: 0, y: 1 },
curveTo: { x: 0, y: 1 },
point: { x: 0, y: 1 },
pointType: 'Straight',
},
],
closed: true,
});
layer.sharedStyleId = sharedStyle.id;
layer.style.syncWithSharedStyle(sharedStyle);
page.layers.push(layer);
function getLayerFillColor() {
return layer.style.fills[0].color;
}
if (getLayerFillColor() !== '#000000ff') {
throw new Error('The layer is not in sync with the shared style');
}
syncColorStyle({ document, name: 'black', value: '#dedede' });
if (getLayerFillColor() !== '#dededeff') {
throw new Error('The layer did not update to the new shared style');
}
/**
* Testing shared text styles
*/
clear();
const textSharedStyle = syncSharedStyle({
document,
name: 'test-shared-text-style',
style: {
textColor: '#000000ff',
fontSize: 16,
textTransform: 'none',
fontFamily: 'IBM Plex Sans',
fontWeight: 5,
paragraphSpacing: 0,
lineHeight: null,
kerning: 0.16,
verticalAlignment: 'top',
alignment: 'left',
styleType: SharedStyle.StyleType.Text,
},
styleType: SharedStyle.StyleType.Text,
});
if (document.sharedTextStyles.length !== 1) {
throw new Error('Expected sync command to generate a shared text style');
}
syncSharedStyle({
document,
name: 'test-shared-text-style',
style: {},
styleType: SharedStyle.StyleType.Text,
});
if (document.sharedTextStyles.length !== 1) {
throw new Error(
'Expected sync command to generate only one shared text style for ' +
'the given name'
);
}
const textLayer = new Text({
name: 'Text',
frame: new Rectangle(0, 0),
style: textSharedStyle.style,
text: 'Text sample',
fixedWidth: false,
sharedStyleId: textSharedStyle.id,
});
page.layers.push(textLayer);
function getTextFillColor() {
return textLayer.style.textColor;
}
if (getTextFillColor() !== '#000000ff') {
throw new Error('Inserted layer is out of sync with shared text style');
}
syncSharedStyle({
document,
name: 'test-shared-text-style',
style: {
textColor: '#343434ff',
},
styleType: SharedStyle.StyleType.Text,
});
if (getTextFillColor() !== '#343434ff') {
throw new Error('Shared text style textColor was not updated');
}
});
} | function testSyncSharedStyles() {
command('commands/test/sync-shared-styles', () => {
const document = Document.getSelectedDocument();
const { selectedPage: page } = document;
// Clear the current document and page
function clear() {
document.sharedLayerStyles = [];
document.sharedTextStyles = [];
page.layers = [];
}
clear();
/**
* Testing shared layer styles
*/
const sharedStyle = syncColorStyle({
document,
name: 'black',
value: '#000000',
});
if (document.sharedLayerStyles.length !== 1) {
throw new Error('Expected sync command to generate a shared layer style');
}
syncColorStyle({ document, name: 'black', value: '#000000' });
if (document.sharedLayerStyles.length !== 1) {
throw new Error(
'Expected sync command to generate only one shared layer style for ' +
'the given name'
);
}
const layer = new ShapePath({
name: 'Rectangle',
shapeType: ShapePath.ShapeType.Rectangle,
frame: new Rectangle(0, 0, 100, 100),
style: {
fills: [
{
fillType: Style.FillType.Color,
color: '#d8d8d8ff',
},
],
},
points: [
{
type: 'CurvePoint',
cornerRadius: 0,
curveFrom: { x: 0, y: 0 },
curveTo: { x: 0, y: 0 },
point: { x: 0, y: 0 },
pointType: 'Straight',
},
{
type: 'CurvePoint',
cornerRadius: 0,
curveFrom: { x: 1, y: 0 },
curveTo: { x: 1, y: 0 },
point: { x: 1, y: 0 },
pointType: 'Straight',
},
{
type: 'CurvePoint',
cornerRadius: 0,
curveFrom: { x: 1, y: 1 },
curveTo: { x: 1, y: 1 },
point: { x: 1, y: 1 },
pointType: 'Straight',
},
{
type: 'CurvePoint',
cornerRadius: 0,
curveFrom: { x: 0, y: 1 },
curveTo: { x: 0, y: 1 },
point: { x: 0, y: 1 },
pointType: 'Straight',
},
],
closed: true,
});
layer.sharedStyleId = sharedStyle.id;
layer.style.syncWithSharedStyle(sharedStyle);
page.layers.push(layer);
function getLayerFillColor() {
return layer.style.fills[0].color;
}
if (getLayerFillColor() !== '#000000ff') {
throw new Error('The layer is not in sync with the shared style');
}
syncColorStyle({ document, name: 'black', value: '#dedede' });
if (getLayerFillColor() !== '#dededeff') {
throw new Error('The layer did not update to the new shared style');
}
/**
* Testing shared text styles
*/
clear();
const textSharedStyle = syncSharedStyle({
document,
name: 'test-shared-text-style',
style: {
textColor: '#000000ff',
fontSize: 16,
textTransform: 'none',
fontFamily: 'IBM Plex Sans',
fontWeight: 5,
paragraphSpacing: 0,
lineHeight: null,
kerning: 0.16,
verticalAlignment: 'top',
alignment: 'left',
styleType: SharedStyle.StyleType.Text,
},
styleType: SharedStyle.StyleType.Text,
});
if (document.sharedTextStyles.length !== 1) {
throw new Error('Expected sync command to generate a shared text style');
}
syncSharedStyle({
document,
name: 'test-shared-text-style',
style: {},
styleType: SharedStyle.StyleType.Text,
});
if (document.sharedTextStyles.length !== 1) {
throw new Error(
'Expected sync command to generate only one shared text style for ' +
'the given name'
);
}
const textLayer = new Text({
name: 'Text',
frame: new Rectangle(0, 0),
style: textSharedStyle.style,
text: 'Text sample',
fixedWidth: false,
sharedStyleId: textSharedStyle.id,
});
page.layers.push(textLayer);
function getTextFillColor() {
return textLayer.style.textColor;
}
if (getTextFillColor() !== '#000000ff') {
throw new Error('Inserted layer is out of sync with shared text style');
}
syncSharedStyle({
document,
name: 'test-shared-text-style',
style: {
textColor: '#343434ff',
},
styleType: SharedStyle.StyleType.Text,
});
if (getTextFillColor() !== '#343434ff') {
throw new Error('Shared text style textColor was not updated');
}
});
} |
JavaScript | function clear() {
document.sharedLayerStyles = [];
document.sharedTextStyles = [];
page.layers = [];
} | function clear() {
document.sharedLayerStyles = [];
document.sharedTextStyles = [];
page.layers = [];
} |
JavaScript | function transformMetadata(metadata) {
const namesRegEx = new RegExp(
metadata.tokens.map((token) => token.name).join('|'),
'g'
);
const replaceMap = {};
metadata.tokens.map((token) => {
replaceMap[token.name] = formatTokenName(token.name);
});
metadata.tokens.forEach((token, i) => {
// interactive01 to `$interactive-01`
if (token.role) {
token.role.forEach((role, j) => {
metadata.tokens[i].role[j] = role.replace(namesRegEx, (match) => {
return '`$' + replaceMap[match] + '`';
});
});
}
// brand01 to brand-01
if (token.alias) {
token.alias = formatTokenName(token.alias);
}
});
return metadata;
} | function transformMetadata(metadata) {
const namesRegEx = new RegExp(
metadata.tokens.map((token) => token.name).join('|'),
'g'
);
const replaceMap = {};
metadata.tokens.map((token) => {
replaceMap[token.name] = formatTokenName(token.name);
});
metadata.tokens.forEach((token, i) => {
// interactive01 to `$interactive-01`
if (token.role) {
token.role.forEach((role, j) => {
metadata.tokens[i].role[j] = role.replace(namesRegEx, (match) => {
return '`$' + replaceMap[match] + '`';
});
});
}
// brand01 to brand-01
if (token.alias) {
token.alias = formatTokenName(token.alias);
}
});
return metadata;
} |
JavaScript | _changeState(state, detail, callback) {
let handleTransitionEnd;
const transitionEnd = () => {
if (handleTransitionEnd) {
handleTransitionEnd = this.unmanage(handleTransitionEnd).release();
}
if (
state === 'shown' &&
this.element.offsetWidth > 0 &&
this.element.offsetHeight > 0
) {
this.previouslyFocusedNode = this.element.ownerDocument.activeElement;
const focusableItem =
this.element.querySelector(this.options.selectorPrimaryFocus) ||
this.element.querySelector(settings.selectorTabbable);
focusableItem.focus();
if (__DEV__) {
warning(
focusableItem,
`Modals need to contain a focusable element by either using ` +
`\`${this.options.selectorPrimaryFocus}\` or settings.selectorTabbable.`
);
}
}
callback();
};
if (this._handleFocusinListener) {
this._handleFocusinListener = this.unmanage(
this._handleFocusinListener
).release();
}
if (state === 'shown') {
const hasFocusin = 'onfocusin' in this.element.ownerDocument.defaultView;
const focusinEventName = hasFocusin ? 'focusin' : 'focus';
this._handleFocusinListener = this.manage(
on(
this.element.ownerDocument,
focusinEventName,
this._handleFocusin,
!hasFocusin
)
);
}
if (state === 'hidden') {
this.element.classList.toggle(this.options.classVisible, false);
this.element.ownerDocument.body.classList.toggle(
this.options.classBody,
false
);
if (this.options.selectorFocusOnClose || this.previouslyFocusedNode) {
(
this.element.ownerDocument.querySelector(
this.options.selectorFocusOnClose
) || this.previouslyFocusedNode
).focus();
}
} else if (state === 'shown') {
this.element.classList.toggle(this.options.classVisible, true);
this.element.ownerDocument.body.classList.toggle(
this.options.classBody,
true
);
}
handleTransitionEnd = this.manage(
on(this.element, 'transitionend', transitionEnd)
);
} | _changeState(state, detail, callback) {
let handleTransitionEnd;
const transitionEnd = () => {
if (handleTransitionEnd) {
handleTransitionEnd = this.unmanage(handleTransitionEnd).release();
}
if (
state === 'shown' &&
this.element.offsetWidth > 0 &&
this.element.offsetHeight > 0
) {
this.previouslyFocusedNode = this.element.ownerDocument.activeElement;
const focusableItem =
this.element.querySelector(this.options.selectorPrimaryFocus) ||
this.element.querySelector(settings.selectorTabbable);
focusableItem.focus();
if (__DEV__) {
warning(
focusableItem,
`Modals need to contain a focusable element by either using ` +
`\`${this.options.selectorPrimaryFocus}\` or settings.selectorTabbable.`
);
}
}
callback();
};
if (this._handleFocusinListener) {
this._handleFocusinListener = this.unmanage(
this._handleFocusinListener
).release();
}
if (state === 'shown') {
const hasFocusin = 'onfocusin' in this.element.ownerDocument.defaultView;
const focusinEventName = hasFocusin ? 'focusin' : 'focus';
this._handleFocusinListener = this.manage(
on(
this.element.ownerDocument,
focusinEventName,
this._handleFocusin,
!hasFocusin
)
);
}
if (state === 'hidden') {
this.element.classList.toggle(this.options.classVisible, false);
this.element.ownerDocument.body.classList.toggle(
this.options.classBody,
false
);
if (this.options.selectorFocusOnClose || this.previouslyFocusedNode) {
(
this.element.ownerDocument.querySelector(
this.options.selectorFocusOnClose
) || this.previouslyFocusedNode
).focus();
}
} else if (state === 'shown') {
this.element.classList.toggle(this.options.classVisible, true);
this.element.ownerDocument.body.classList.toggle(
this.options.classBody,
true
);
}
handleTransitionEnd = this.manage(
on(this.element, 'transitionend', transitionEnd)
);
} |
JavaScript | static get options() {
const { prefix } = settings;
return {
selectorInit: '[data-modal]',
selectorModalClose: '[data-modal-close]',
selectorPrimaryFocus: '[data-modal-primary-focus]',
selectorsFloatingMenus: [
`.${prefix}--overflow-menu-options`,
`.${prefix}--tooltip`,
'.flatpickr-calendar',
],
selectorModalContainer: `.${prefix}--modal-container`,
classVisible: 'is-visible',
classBody: `${prefix}--body--with-modal-open`,
attribInitTarget: 'data-modal-target',
initEventNames: ['click'],
eventBeforeShown: 'modal-beingshown',
eventAfterShown: 'modal-shown',
eventBeforeHidden: 'modal-beinghidden',
eventAfterHidden: 'modal-hidden',
};
} | static get options() {
const { prefix } = settings;
return {
selectorInit: '[data-modal]',
selectorModalClose: '[data-modal-close]',
selectorPrimaryFocus: '[data-modal-primary-focus]',
selectorsFloatingMenus: [
`.${prefix}--overflow-menu-options`,
`.${prefix}--tooltip`,
'.flatpickr-calendar',
],
selectorModalContainer: `.${prefix}--modal-container`,
classVisible: 'is-visible',
classBody: `${prefix}--body--with-modal-open`,
attribInitTarget: 'data-modal-target',
initEventNames: ['click'],
eventBeforeShown: 'modal-beingshown',
eventAfterShown: 'modal-shown',
eventBeforeHidden: 'modal-beinghidden',
eventAfterHidden: 'modal-hidden',
};
} |
JavaScript | function flattenOptions(options) {
const o = {};
// eslint-disable-next-line guard-for-in, no-restricted-syntax
for (const key in options) {
o[key] = options[key];
}
return o;
} | function flattenOptions(options) {
const o = {};
// eslint-disable-next-line guard-for-in, no-restricted-syntax
for (const key in options) {
o[key] = options[key];
}
return o;
} |
JavaScript | static get options() {
const { prefix } = settings;
return {
selectorInit: '[data-date-picker]',
selectorDatePickerInput: '[data-date-picker-input]',
selectorDatePickerInputFrom: '[data-date-picker-input-from]',
selectorDatePickerInputTo: '[data-date-picker-input-to]',
selectorDatePickerIcon: '[data-date-picker-icon]',
selectorFlatpickrMonthYearContainer: '.flatpickr-current-month',
selectorFlatpickrYearContainer: '.numInputWrapper',
selectorFlatpickrCurrentMonth: '.cur-month',
classCalendarContainer: `${prefix}--date-picker__calendar`,
classMonth: `${prefix}--date-picker__month`,
classWeekdays: `${prefix}--date-picker__weekdays`,
classDays: `${prefix}--date-picker__days`,
classWeekday: `${prefix}--date-picker__weekday`,
classDay: `${prefix}--date-picker__day`,
classFocused: `${prefix}--focused`,
classVisuallyHidden: `${prefix}--visually-hidden`,
classFlatpickrCurrentMonth: 'cur-month',
attribType: 'data-date-picker-type',
dateFormat: 'm/d/Y',
};
} | static get options() {
const { prefix } = settings;
return {
selectorInit: '[data-date-picker]',
selectorDatePickerInput: '[data-date-picker-input]',
selectorDatePickerInputFrom: '[data-date-picker-input-from]',
selectorDatePickerInputTo: '[data-date-picker-input-to]',
selectorDatePickerIcon: '[data-date-picker-icon]',
selectorFlatpickrMonthYearContainer: '.flatpickr-current-month',
selectorFlatpickrYearContainer: '.numInputWrapper',
selectorFlatpickrCurrentMonth: '.cur-month',
classCalendarContainer: `${prefix}--date-picker__calendar`,
classMonth: `${prefix}--date-picker__month`,
classWeekdays: `${prefix}--date-picker__weekdays`,
classDays: `${prefix}--date-picker__days`,
classWeekday: `${prefix}--date-picker__weekday`,
classDay: `${prefix}--date-picker__day`,
classFocused: `${prefix}--focused`,
classVisuallyHidden: `${prefix}--visually-hidden`,
classFlatpickrCurrentMonth: 'cur-month',
attribType: 'data-date-picker-type',
dateFormat: 'm/d/Y',
};
} |
JavaScript | function wrapFocus({
bodyNode,
startTrapNode,
endTrapNode,
currentActiveNode,
oldActiveNode,
selectorsFloatingMenus,
}) {
if (
bodyNode &&
currentActiveNode &&
oldActiveNode &&
!bodyNode.contains(currentActiveNode) &&
!elementOrParentIsFloatingMenu(currentActiveNode, selectorsFloatingMenus)
) {
const comparisonResult = oldActiveNode.compareDocumentPosition(
currentActiveNode
);
if (
currentActiveNode === startTrapNode ||
comparisonResult & DOCUMENT_POSITION_BROAD_PRECEDING
) {
const tabbable = findLast(
bodyNode.querySelectorAll(selectorTabbable),
(elem) => Boolean(elem.offsetParent)
);
if (tabbable) {
tabbable.focus();
} else if (bodyNode !== oldActiveNode) {
bodyNode.focus();
}
} else if (
currentActiveNode === endTrapNode ||
comparisonResult & DOCUMENT_POSITION_BROAD_FOLLOWING
) {
const tabbable = Array.prototype.find.call(
bodyNode.querySelectorAll(selectorTabbable),
(elem) => Boolean(elem.offsetParent)
);
if (tabbable) {
tabbable.focus();
} else if (bodyNode !== oldActiveNode) {
bodyNode.focus();
}
}
}
} | function wrapFocus({
bodyNode,
startTrapNode,
endTrapNode,
currentActiveNode,
oldActiveNode,
selectorsFloatingMenus,
}) {
if (
bodyNode &&
currentActiveNode &&
oldActiveNode &&
!bodyNode.contains(currentActiveNode) &&
!elementOrParentIsFloatingMenu(currentActiveNode, selectorsFloatingMenus)
) {
const comparisonResult = oldActiveNode.compareDocumentPosition(
currentActiveNode
);
if (
currentActiveNode === startTrapNode ||
comparisonResult & DOCUMENT_POSITION_BROAD_PRECEDING
) {
const tabbable = findLast(
bodyNode.querySelectorAll(selectorTabbable),
(elem) => Boolean(elem.offsetParent)
);
if (tabbable) {
tabbable.focus();
} else if (bodyNode !== oldActiveNode) {
bodyNode.focus();
}
} else if (
currentActiveNode === endTrapNode ||
comparisonResult & DOCUMENT_POSITION_BROAD_FOLLOWING
) {
const tabbable = Array.prototype.find.call(
bodyNode.querySelectorAll(selectorTabbable),
(elem) => Boolean(elem.offsetParent)
);
if (tabbable) {
tabbable.focus();
} else if (bodyNode !== oldActiveNode) {
bodyNode.focus();
}
}
}
} |
JavaScript | function Theme({
as: BaseComponent = 'div',
children,
className: customClassName,
theme,
...rest
}) {
const prefix = usePrefix();
const className = cx(customClassName, {
[`${prefix}--white`]: theme === 'white',
[`${prefix}--g10`]: theme === 'g10',
[`${prefix}--g90`]: theme === 'g90',
[`${prefix}--g100`]: theme === 'g100',
[`${prefix}--layer-one`]: true,
});
const value = React.useMemo(() => {
return {
theme,
};
}, [theme]);
return (
<ThemeContext.Provider value={value}>
<LayerContext.Provider value={1}>
<BaseComponent {...rest} className={className}>
{children}
</BaseComponent>
</LayerContext.Provider>
</ThemeContext.Provider>
);
} | function Theme({
as: BaseComponent = 'div',
children,
className: customClassName,
theme,
...rest
}) {
const prefix = usePrefix();
const className = cx(customClassName, {
[`${prefix}--white`]: theme === 'white',
[`${prefix}--g10`]: theme === 'g10',
[`${prefix}--g90`]: theme === 'g90',
[`${prefix}--g100`]: theme === 'g100',
[`${prefix}--layer-one`]: true,
});
const value = React.useMemo(() => {
return {
theme,
};
}, [theme]);
return (
<ThemeContext.Provider value={value}>
<LayerContext.Provider value={1}>
<BaseComponent {...rest} className={className}>
{children}
</BaseComponent>
</LayerContext.Provider>
</ThemeContext.Provider>
);
} |
JavaScript | function buildModulesTokenFile(tokenScale, group) {
const FILE_BANNER = t.Comment(` Code generated by @carbon/layout. DO NOT EDIT.
Copyright IBM Corp. 2018, 2019
This source code is licensed under the Apache-2.0 license found in the
LICENSE file in the root directory of this source tree.
`);
const values = tokenScale.map((value, index) => {
const name = formatStep(`${group}`, index + 1);
const shorthand = formatStep(group, index + 1);
const id = t.Identifier(name);
return [
name,
shorthand,
id,
t.Assignment({
id,
init: t.SassValue(value),
default: true,
}),
];
});
const variables = values.flatMap(([_name, _shorthand, _id, assignment]) => {
const comment = t.Comment(`/ @type Number
/ @access public
/ @group @carbon/layout`);
return [comment, assignment, t.Newline()];
});
const map = [
t.Comment(`/ @type Map
/ @access public
/ @group @carbon/layout`),
t.Assignment({
id: t.Identifier(group),
init: t.SassMap({
properties: values.map(([name, _shorthand, id]) => {
return t.SassMapProperty({
key: id,
value: t.SassValue(`$${name}`),
});
}),
}),
}),
];
return t.StyleSheet([
FILE_BANNER,
t.Newline(),
...variables,
...map,
t.Newline(),
]);
} | function buildModulesTokenFile(tokenScale, group) {
const FILE_BANNER = t.Comment(` Code generated by @carbon/layout. DO NOT EDIT.
Copyright IBM Corp. 2018, 2019
This source code is licensed under the Apache-2.0 license found in the
LICENSE file in the root directory of this source tree.
`);
const values = tokenScale.map((value, index) => {
const name = formatStep(`${group}`, index + 1);
const shorthand = formatStep(group, index + 1);
const id = t.Identifier(name);
return [
name,
shorthand,
id,
t.Assignment({
id,
init: t.SassValue(value),
default: true,
}),
];
});
const variables = values.flatMap(([_name, _shorthand, _id, assignment]) => {
const comment = t.Comment(`/ @type Number
/ @access public
/ @group @carbon/layout`);
return [comment, assignment, t.Newline()];
});
const map = [
t.Comment(`/ @type Map
/ @access public
/ @group @carbon/layout`),
t.Assignment({
id: t.Identifier(group),
init: t.SassMap({
properties: values.map(([name, _shorthand, id]) => {
return t.SassMapProperty({
key: id,
value: t.SassValue(`$${name}`),
});
}),
}),
}),
];
return t.StyleSheet([
FILE_BANNER,
t.Newline(),
...variables,
...map,
t.Newline(),
]);
} |
JavaScript | function validateFiles(event) {
const transferredFiles =
event.type === 'drop'
? [...event.dataTransfer.files]
: [...event.target.files];
if (!accept.length) {
return transferredFiles;
}
const acceptedTypes = new Set(accept);
return transferredFiles.reduce((acc, curr) => {
const { name, type: mimeType = '' } = curr;
const fileExtensionRegExp = new RegExp(pattern, 'i');
const hasFileExtension = fileExtensionRegExp.test(name);
if (!hasFileExtension) {
return acc;
}
const [fileExtension] = name.match(fileExtensionRegExp);
if (acceptedTypes.has(mimeType) || acceptedTypes.has(fileExtension)) {
return acc.concat([curr]);
}
curr.invalidFileType = true;
return acc.concat([curr]);
}, []);
} | function validateFiles(event) {
const transferredFiles =
event.type === 'drop'
? [...event.dataTransfer.files]
: [...event.target.files];
if (!accept.length) {
return transferredFiles;
}
const acceptedTypes = new Set(accept);
return transferredFiles.reduce((acc, curr) => {
const { name, type: mimeType = '' } = curr;
const fileExtensionRegExp = new RegExp(pattern, 'i');
const hasFileExtension = fileExtensionRegExp.test(name);
if (!hasFileExtension) {
return acc;
}
const [fileExtension] = name.match(fileExtensionRegExp);
if (acceptedTypes.has(mimeType) || acceptedTypes.has(fileExtension)) {
return acc.concat([curr]);
}
curr.invalidFileType = true;
return acc.concat([curr]);
}, []);
} |
JavaScript | componentDidMount() {
if (this.element) {
const { value, left } = this.calcValue({
useRawValue: true,
});
this.setState({ value, left });
}
} | componentDidMount() {
if (this.element) {
const { value, left } = this.calcValue({
useRawValue: true,
});
this.setState({ value, left });
}
} |
JavaScript | _handleClick(event) {
const button = eventMatches(event, this.options.selectorButton);
const trigger = eventMatches(event, this.options.selectorTrigger);
if (
button &&
!button.classList.contains(this.options.classButtonDisabled)
) {
super._handleClick(event);
this._updateMenuState(false);
}
if (trigger) {
this._updateMenuState();
}
} | _handleClick(event) {
const button = eventMatches(event, this.options.selectorButton);
const trigger = eventMatches(event, this.options.selectorTrigger);
if (
button &&
!button.classList.contains(this.options.classButtonDisabled)
) {
super._handleClick(event);
this._updateMenuState(false);
}
if (trigger) {
this._updateMenuState();
}
} |
JavaScript | _handleKeyDown(event) {
const triggerNode = eventMatches(event, this.options.selectorTrigger);
if (triggerNode) {
if (event.which === 13) {
this._updateMenuState();
}
return;
}
const direction = {
37: this.constructor.NAVIGATE.BACKWARD,
39: this.constructor.NAVIGATE.FORWARD,
}[event.which];
if (direction) {
const buttons = toArray(
this.element.querySelectorAll(this.options.selectorButtonEnabled)
);
const button = this.element.querySelector(
this.options.selectorButtonSelected
);
const nextIndex = Math.max(
buttons.indexOf(button) + direction,
-1 /* For `button` not found in `buttons` */
);
const nextIndexLooped =
nextIndex >= 0 && nextIndex < buttons.length
? nextIndex
: nextIndex - Math.sign(nextIndex) * buttons.length;
this.setActive(buttons[nextIndexLooped], (error, item) => {
if (item) {
const link = item.querySelector(this.options.selectorLink);
if (link) {
link.focus();
}
}
});
event.preventDefault();
}
} | _handleKeyDown(event) {
const triggerNode = eventMatches(event, this.options.selectorTrigger);
if (triggerNode) {
if (event.which === 13) {
this._updateMenuState();
}
return;
}
const direction = {
37: this.constructor.NAVIGATE.BACKWARD,
39: this.constructor.NAVIGATE.FORWARD,
}[event.which];
if (direction) {
const buttons = toArray(
this.element.querySelectorAll(this.options.selectorButtonEnabled)
);
const button = this.element.querySelector(
this.options.selectorButtonSelected
);
const nextIndex = Math.max(
buttons.indexOf(button) + direction,
-1 /* For `button` not found in `buttons` */
);
const nextIndexLooped =
nextIndex >= 0 && nextIndex < buttons.length
? nextIndex
: nextIndex - Math.sign(nextIndex) * buttons.length;
this.setActive(buttons[nextIndexLooped], (error, item) => {
if (item) {
const link = item.querySelector(this.options.selectorLink);
if (link) {
link.focus();
}
}
});
event.preventDefault();
}
} |
JavaScript | _updateTriggerText(target) {
const triggerText = this.element.querySelector(
this.options.selectorTriggerText
);
if (triggerText) {
triggerText.textContent = target.textContent;
}
} | _updateTriggerText(target) {
const triggerText = this.element.querySelector(
this.options.selectorTriggerText
);
if (triggerText) {
triggerText.textContent = target.textContent;
}
} |
JavaScript | static get options() {
const { prefix } = settings;
return Object.assign(Object.create(ContentSwitcher.options), {
selectorInit: '[data-tabs]',
selectorMenu: `.${prefix}--tabs__nav`,
selectorTrigger: `.${prefix}--tabs-trigger`,
selectorTriggerText: `.${prefix}--tabs-trigger-text`,
selectorButton: `.${prefix}--tabs__nav-item`,
selectorButtonEnabled: `.${prefix}--tabs__nav-item:not(.${prefix}--tabs__nav-item--disabled)`,
selectorButtonSelected: `.${prefix}--tabs__nav-item--selected`,
selectorLink: `.${prefix}--tabs__nav-link`,
classActive: `${prefix}--tabs__nav-item--selected`,
classHidden: `${prefix}--tabs__nav--hidden`,
classOpen: `${prefix}--tabs-trigger--open`,
classButtonDisabled: `${prefix}--tabs__nav-item--disabled`,
eventBeforeSelected: 'tab-beingselected',
eventAfterSelected: 'tab-selected',
});
} | static get options() {
const { prefix } = settings;
return Object.assign(Object.create(ContentSwitcher.options), {
selectorInit: '[data-tabs]',
selectorMenu: `.${prefix}--tabs__nav`,
selectorTrigger: `.${prefix}--tabs-trigger`,
selectorTriggerText: `.${prefix}--tabs-trigger-text`,
selectorButton: `.${prefix}--tabs__nav-item`,
selectorButtonEnabled: `.${prefix}--tabs__nav-item:not(.${prefix}--tabs__nav-item--disabled)`,
selectorButtonSelected: `.${prefix}--tabs__nav-item--selected`,
selectorLink: `.${prefix}--tabs__nav-link`,
classActive: `${prefix}--tabs__nav-item--selected`,
classHidden: `${prefix}--tabs__nav--hidden`,
classOpen: `${prefix}--tabs-trigger--open`,
classButtonDisabled: `${prefix}--tabs__nav-item--disabled`,
eventBeforeSelected: 'tab-beingselected',
eventAfterSelected: 'tab-selected',
});
} |
JavaScript | function useSavedCallback(callback) {
const savedCallback = useRef(callback);
useEffect(() => {
savedCallback.current = callback;
});
return useCallback(() => {
if (savedCallback.current) {
return savedCallback.current();
}
}, []);
} | function useSavedCallback(callback) {
const savedCallback = useRef(callback);
useEffect(() => {
savedCallback.current = callback;
});
return useCallback(() => {
if (savedCallback.current) {
return savedCallback.current();
}
}, []);
} |
JavaScript | static get options() {
const { prefix } = settings;
return {
selectorInit: '[data-pagination-nav]',
selectorPageElement: '[data-page]',
selectorPageButton: '[data-page-button]',
selectorPagePrevious: '[data-page-previous]',
selectorPageNext: '[data-page-next]',
selectorPageSelect: '[data-page-select]',
selectorPageActive: '[data-page-active="true"]',
attribPage: 'data-page',
attribActive: 'data-page-active',
classActive: `${prefix}--pagination-nav__page--active`,
classDisabled: `${prefix}--pagination-nav__page--disabled`,
};
} | static get options() {
const { prefix } = settings;
return {
selectorInit: '[data-pagination-nav]',
selectorPageElement: '[data-page]',
selectorPageButton: '[data-page-button]',
selectorPagePrevious: '[data-page-previous]',
selectorPageNext: '[data-page-next]',
selectorPageSelect: '[data-page-select]',
selectorPageActive: '[data-page-active="true"]',
attribPage: 'data-page',
attribActive: 'data-page-active',
classActive: `${prefix}--pagination-nav__page--active`,
classDisabled: `${prefix}--pagination-nav__page--disabled`,
};
} |
JavaScript | toggleLayout(element) {
toArray(element.querySelectorAll(this.options.selectorSearchView)).forEach(
(item) => {
item.classList.toggle(this.options.classLayoutHidden);
}
);
} | toggleLayout(element) {
toArray(element.querySelectorAll(this.options.selectorSearchView)).forEach(
(item) => {
item.classList.toggle(this.options.classLayoutHidden);
}
);
} |
JavaScript | async function publish({ tag, ...flags }) {
const { gitRemote, noGitTagVersion, noPush, registry, skipReset } = flags;
const lastTag = await getLastGitTag();
const packages = await getPackages();
displayBanner();
logger.start(`Validating the tag: ${tag}`);
if (tag[0] !== 'v') {
throw new Error(
`Expected tag name to match vX.Y.Z, instead received: ${tag}`
);
}
if (!semver.valid(tag.slice(1))) {
throw new Error(
`Given tag is not a semantically valid version, received: ${tag}`
);
}
logger.stop();
logger.start('Resetting the project to a known state');
if (!skipReset) {
const type = semver.diff(lastTag, tag);
if (type !== 'patch' && type !== 'prepatch') {
logger.info('Fetching latest from upstream master');
await fetchLatestFromUpstream();
}
logger.info('Cleaning any local artifacts or node_modules');
// Make sure that our tooling is defined before running clean
await execa('yarn', ['install', '--offline']);
await execa('yarn', ['clean']);
logger.info('Installing known dependencies from offline mirror');
await execa('yarn', ['install', '--offline']);
logger.info('Building packages from source');
await execa('yarn', ['build']);
}
logger.stop();
logger.start('Checking project for out-of-sync generated files');
const { stdout } = await execa('git', ['status', '--porcelain']);
if (stdout !== '') {
throw new Error(
'There are generated files that are out-of-sync. Please wait for ' +
'these changes to be committed upstream or commit manually'
);
}
logger.stop();
logger.start('Publishing packages');
logger.info('Logging into npm');
try {
// This command will fail if the user is unauthenticated
await execa('npm', ['whoami', '--registry', registry]);
} catch {
await execa('npm', ['login'], {
stdio: 'inherit',
});
}
logger.info(`Setting the npm registry to ${registry}`);
const { stdout: originalRegistryUrl } = await execa('npm', [
'get',
'registry',
]);
if (originalRegistryUrl !== registry) {
await execa('npm', ['set', 'registry', registry]);
defer(() => execa('npm', ['set', 'registry', originalRegistryUrl]));
}
// Publish packages using `lerna`, we default to placing these under the
// `next` tag instead of `latest` so that we can verify the release.
await execa(
'yarn',
[
'lerna',
'publish',
'from-package',
'--dist-tag',
'next',
'--registry',
registry,
],
{
stdio: 'inherit',
}
);
logger.stop();
// We specify a stopping point so that the operator can verify the packages
// published as intended before setting the `latest` dist-tag
const answers = await prompt([
{
type: 'confirm',
name: 'tags',
message: 'Would you like to update the package tags from next to latest?',
},
]);
if (answers.tags) {
logger.start('Setting npm dist tags to latest');
for (const { name, version } of packages) {
logger.info(`Setting npm dist-tag for ${name}@${version} to latest`);
await execa('npm', ['dist-tag', 'add', `${name}@${version}`, 'latest']);
}
logger.stop();
}
if (!noGitTagVersion) {
logger.start(`Generating the git tag ${tag}`);
await execa('git', ['tag', '-a', tag, '-m', tag]);
logger.stop();
}
if (!noPush) {
const { remote } = await prompt([
{
type: 'confirm',
name: 'remote',
message: `Should we push the tag ${tag} to the ${gitRemote} remote?`,
},
]);
if (remote) {
logger.start(`Pushing the tag ${tag} to the ${gitRemote} remote`);
await execa('git', ['push', gitRemote, tag]);
logger.stop();
}
}
logger.start('Generating the changelog');
logger.info(`Using commits from ${lastTag}...${tag}`);
const changelog = await generate(packages, lastTag, tag);
logger.stop();
const { display } = await prompt([
{
type: 'confirm',
name: 'display',
message: 'Display contents of generated changelog for release?',
},
]);
if (display) {
// eslint-disable-next-line no-console
console.log(changelog);
}
} | async function publish({ tag, ...flags }) {
const { gitRemote, noGitTagVersion, noPush, registry, skipReset } = flags;
const lastTag = await getLastGitTag();
const packages = await getPackages();
displayBanner();
logger.start(`Validating the tag: ${tag}`);
if (tag[0] !== 'v') {
throw new Error(
`Expected tag name to match vX.Y.Z, instead received: ${tag}`
);
}
if (!semver.valid(tag.slice(1))) {
throw new Error(
`Given tag is not a semantically valid version, received: ${tag}`
);
}
logger.stop();
logger.start('Resetting the project to a known state');
if (!skipReset) {
const type = semver.diff(lastTag, tag);
if (type !== 'patch' && type !== 'prepatch') {
logger.info('Fetching latest from upstream master');
await fetchLatestFromUpstream();
}
logger.info('Cleaning any local artifacts or node_modules');
// Make sure that our tooling is defined before running clean
await execa('yarn', ['install', '--offline']);
await execa('yarn', ['clean']);
logger.info('Installing known dependencies from offline mirror');
await execa('yarn', ['install', '--offline']);
logger.info('Building packages from source');
await execa('yarn', ['build']);
}
logger.stop();
logger.start('Checking project for out-of-sync generated files');
const { stdout } = await execa('git', ['status', '--porcelain']);
if (stdout !== '') {
throw new Error(
'There are generated files that are out-of-sync. Please wait for ' +
'these changes to be committed upstream or commit manually'
);
}
logger.stop();
logger.start('Publishing packages');
logger.info('Logging into npm');
try {
// This command will fail if the user is unauthenticated
await execa('npm', ['whoami', '--registry', registry]);
} catch {
await execa('npm', ['login'], {
stdio: 'inherit',
});
}
logger.info(`Setting the npm registry to ${registry}`);
const { stdout: originalRegistryUrl } = await execa('npm', [
'get',
'registry',
]);
if (originalRegistryUrl !== registry) {
await execa('npm', ['set', 'registry', registry]);
defer(() => execa('npm', ['set', 'registry', originalRegistryUrl]));
}
// Publish packages using `lerna`, we default to placing these under the
// `next` tag instead of `latest` so that we can verify the release.
await execa(
'yarn',
[
'lerna',
'publish',
'from-package',
'--dist-tag',
'next',
'--registry',
registry,
],
{
stdio: 'inherit',
}
);
logger.stop();
// We specify a stopping point so that the operator can verify the packages
// published as intended before setting the `latest` dist-tag
const answers = await prompt([
{
type: 'confirm',
name: 'tags',
message: 'Would you like to update the package tags from next to latest?',
},
]);
if (answers.tags) {
logger.start('Setting npm dist tags to latest');
for (const { name, version } of packages) {
logger.info(`Setting npm dist-tag for ${name}@${version} to latest`);
await execa('npm', ['dist-tag', 'add', `${name}@${version}`, 'latest']);
}
logger.stop();
}
if (!noGitTagVersion) {
logger.start(`Generating the git tag ${tag}`);
await execa('git', ['tag', '-a', tag, '-m', tag]);
logger.stop();
}
if (!noPush) {
const { remote } = await prompt([
{
type: 'confirm',
name: 'remote',
message: `Should we push the tag ${tag} to the ${gitRemote} remote?`,
},
]);
if (remote) {
logger.start(`Pushing the tag ${tag} to the ${gitRemote} remote`);
await execa('git', ['push', gitRemote, tag]);
logger.stop();
}
}
logger.start('Generating the changelog');
logger.info(`Using commits from ${lastTag}...${tag}`);
const changelog = await generate(packages, lastTag, tag);
logger.stop();
const { display } = await prompt([
{
type: 'confirm',
name: 'display',
message: 'Display contents of generated changelog for release?',
},
]);
if (display) {
// eslint-disable-next-line no-console
console.log(changelog);
}
} |
JavaScript | function AspectRatio({
as: BaseComponent = 'div',
className: containerClassName,
children,
ratio = '1x1',
...rest
}) {
const prefix = usePrefix();
const className = cx(
containerClassName,
`${prefix}--aspect-ratio`,
`${prefix}--aspect-ratio--${ratio}`
);
return (
<BaseComponent className={className} {...rest}>
{children}
</BaseComponent>
);
} | function AspectRatio({
as: BaseComponent = 'div',
className: containerClassName,
children,
ratio = '1x1',
...rest
}) {
const prefix = usePrefix();
const className = cx(
containerClassName,
`${prefix}--aspect-ratio`,
`${prefix}--aspect-ratio--${ratio}`
);
return (
<BaseComponent className={className} {...rest}>
{children}
</BaseComponent>
);
} |
JavaScript | toggle() {
if (this.target) {
this.state = {
[InlineLoading.states.ACTIVE]: InlineLoading.states.FINISHED,
[InlineLoading.states.FINISHED]: InlineLoading.states.ERROR,
[InlineLoading.states.ERROR]: InlineLoading.states.ACTIVE,
}[this.state];
this.target.setState(this.state);
}
} | toggle() {
if (this.target) {
this.state = {
[InlineLoading.states.ACTIVE]: InlineLoading.states.FINISHED,
[InlineLoading.states.FINISHED]: InlineLoading.states.ERROR,
[InlineLoading.states.ERROR]: InlineLoading.states.ACTIVE,
}[this.state];
this.target.setState(this.state);
}
} |
JavaScript | function syncSymbol({ symbols, name, config }) {
const symbol = symbols.find((symbol) => symbol.name === name);
if (!symbol) {
return new SymbolMaster({
name,
...config,
});
}
Object.keys(config).forEach((key) => {
if (key === 'frame') {
// prefer x and y positioning of existing artboard #8569
symbol[key] = symbol[key] ?? config[key];
} else {
symbol[key] = config[key];
}
});
return symbol;
} | function syncSymbol({ symbols, name, config }) {
const symbol = symbols.find((symbol) => symbol.name === name);
if (!symbol) {
return new SymbolMaster({
name,
...config,
});
}
Object.keys(config).forEach((key) => {
if (key === 'frame') {
// prefer x and y positioning of existing artboard #8569
symbol[key] = symbol[key] ?? config[key];
} else {
symbol[key] = config[key];
}
});
return symbol;
} |
JavaScript | function removeDeprecatedSymbolArtboards({ icons, sizes, symbolsPage }) {
const deprecatedIcons = icons.reduce((deprecatedIconsMap, currentIcon) => {
if (currentIcon.deprecated) {
sizes.forEach((size) => {
const symbolName = getSymbolName({ icon: currentIcon, size });
deprecatedIconsMap.set(symbolName, currentIcon);
});
}
return deprecatedIconsMap;
}, new Map());
symbolsPage.layers.forEach((symbol) => {
if (deprecatedIcons.get(symbol.name)) {
symbol.remove();
}
});
} | function removeDeprecatedSymbolArtboards({ icons, sizes, symbolsPage }) {
const deprecatedIcons = icons.reduce((deprecatedIconsMap, currentIcon) => {
if (currentIcon.deprecated) {
sizes.forEach((size) => {
const symbolName = getSymbolName({ icon: currentIcon, size });
deprecatedIconsMap.set(symbolName, currentIcon);
});
}
return deprecatedIconsMap;
}, new Map());
symbolsPage.layers.forEach((symbol) => {
if (deprecatedIcons.get(symbol.name)) {
symbol.remove();
}
});
} |
JavaScript | function createSVGArtboards(
page,
sharedStyle,
icons,
sizes = [32, 24, 20, 16]
) {
// We keep track of the current X and Y offsets at the top-level, each
// iteration of an icon set should reset the X_OFFSET and update the
// Y_OFFSET with the maximum size in the icon set.
const ARTBOARD_MARGIN = 32;
let X_OFFSET = 0;
let Y_OFFSET = getInitialPageOffset(page) + ARTBOARD_MARGIN;
return icons
.filter((icon) => !icon.deprecated)
.flatMap((icon) => {
X_OFFSET = 0;
const artboards = sizes.map((size) => {
const asset =
icon.assets.find((asset) => asset.size === 32) ?? icon.assets[0];
const svgString = NSString.stringWithString(asset.source);
const svgData = svgString.dataUsingEncoding(NSUTF8StringEncoding);
const svgImporter = MSSVGImporter.svgImporter();
svgImporter.prepareToImportFromData(svgData);
const svgLayer = svgImporter.importAsLayer();
svgLayer.rect = {
origin: {
x: 0,
y: 0,
},
size: {
width: size,
height: size,
},
};
const symbolName = getSymbolName({ icon, size });
const artboard = new Artboard({
name: symbolName,
frame: new Rectangle(X_OFFSET, Y_OFFSET, size, size),
layers: [svgLayer],
});
const [group] = artboard.layers;
const paths = group.layers.map((layer) => layer.duplicate());
/**
* There are several different types of layers that we might run into.
* These include:
* 1. Fill paths, used to specify the fill for the majority of the icon
* 2. Inner paths, used to specify the fill for a part of an icon
* 3. Transparent, used as the bounding box for icon artboards
* 4. Cutouts, leftover assets or ones used to cut out certain parts of
* an icon. They should have no fill associated with them
*/
const {
fillPaths = [],
innerPaths = [],
transparent = [],
cutouts = [],
} = groupByKey(paths, (layer) => {
if (layer.name === 'Rectangle') {
if (layer.frame.width === size && layer.frame.height === size) {
return 'transparent';
}
}
// workspace
if (layer.name.includes('_Rectangle_')) {
return 'transparent';
}
if (layer.name.includes('Transparent_Rectangle')) {
return 'transparent';
}
if (layer.name === 'inner-path') {
return 'innerPaths';
}
if (layer.style.fills.length > 0) {
return 'fillPaths';
}
return 'cutouts';
});
let shape;
if (fillPaths.length === 1) {
shape = fillPaths[0];
shape.name = 'Fill';
shape.style = sharedStyle.style;
shape.sharedStyleId = sharedStyle.id;
} else {
// If we have multiple fill paths, we need to consolidate them into a
// single Shape so that we can style the icon with one override in the
// symbol
shape = new Shape({
name: 'Fill',
frame: new Rectangle(0, 0, size, size),
layers: fillPaths,
style: sharedStyle.style,
sharedStyleId: sharedStyle.id,
});
}
for (const layer of transparent) {
layer.remove();
}
for (const innerPath of innerPaths) {
innerPath.name = 'Inner Fill';
innerPath.style = sharedStyle.style;
innerPath.style.opacity = 0;
innerPath.sharedStyleId = sharedStyle.id;
}
artboard.layers.push(shape, ...innerPaths, ...cutouts);
group.remove();
X_OFFSET += size + ARTBOARD_MARGIN;
return artboard;
});
Y_OFFSET += 32 + ARTBOARD_MARGIN;
return artboards;
});
} | function createSVGArtboards(
page,
sharedStyle,
icons,
sizes = [32, 24, 20, 16]
) {
// We keep track of the current X and Y offsets at the top-level, each
// iteration of an icon set should reset the X_OFFSET and update the
// Y_OFFSET with the maximum size in the icon set.
const ARTBOARD_MARGIN = 32;
let X_OFFSET = 0;
let Y_OFFSET = getInitialPageOffset(page) + ARTBOARD_MARGIN;
return icons
.filter((icon) => !icon.deprecated)
.flatMap((icon) => {
X_OFFSET = 0;
const artboards = sizes.map((size) => {
const asset =
icon.assets.find((asset) => asset.size === 32) ?? icon.assets[0];
const svgString = NSString.stringWithString(asset.source);
const svgData = svgString.dataUsingEncoding(NSUTF8StringEncoding);
const svgImporter = MSSVGImporter.svgImporter();
svgImporter.prepareToImportFromData(svgData);
const svgLayer = svgImporter.importAsLayer();
svgLayer.rect = {
origin: {
x: 0,
y: 0,
},
size: {
width: size,
height: size,
},
};
const symbolName = getSymbolName({ icon, size });
const artboard = new Artboard({
name: symbolName,
frame: new Rectangle(X_OFFSET, Y_OFFSET, size, size),
layers: [svgLayer],
});
const [group] = artboard.layers;
const paths = group.layers.map((layer) => layer.duplicate());
/**
* There are several different types of layers that we might run into.
* These include:
* 1. Fill paths, used to specify the fill for the majority of the icon
* 2. Inner paths, used to specify the fill for a part of an icon
* 3. Transparent, used as the bounding box for icon artboards
* 4. Cutouts, leftover assets or ones used to cut out certain parts of
* an icon. They should have no fill associated with them
*/
const {
fillPaths = [],
innerPaths = [],
transparent = [],
cutouts = [],
} = groupByKey(paths, (layer) => {
if (layer.name === 'Rectangle') {
if (layer.frame.width === size && layer.frame.height === size) {
return 'transparent';
}
}
// workspace
if (layer.name.includes('_Rectangle_')) {
return 'transparent';
}
if (layer.name.includes('Transparent_Rectangle')) {
return 'transparent';
}
if (layer.name === 'inner-path') {
return 'innerPaths';
}
if (layer.style.fills.length > 0) {
return 'fillPaths';
}
return 'cutouts';
});
let shape;
if (fillPaths.length === 1) {
shape = fillPaths[0];
shape.name = 'Fill';
shape.style = sharedStyle.style;
shape.sharedStyleId = sharedStyle.id;
} else {
// If we have multiple fill paths, we need to consolidate them into a
// single Shape so that we can style the icon with one override in the
// symbol
shape = new Shape({
name: 'Fill',
frame: new Rectangle(0, 0, size, size),
layers: fillPaths,
style: sharedStyle.style,
sharedStyleId: sharedStyle.id,
});
}
for (const layer of transparent) {
layer.remove();
}
for (const innerPath of innerPaths) {
innerPath.name = 'Inner Fill';
innerPath.style = sharedStyle.style;
innerPath.style.opacity = 0;
innerPath.sharedStyleId = sharedStyle.id;
}
artboard.layers.push(shape, ...innerPaths, ...cutouts);
group.remove();
X_OFFSET += size + ARTBOARD_MARGIN;
return artboard;
});
Y_OFFSET += 32 + ARTBOARD_MARGIN;
return artboards;
});
} |
JavaScript | function convert(value) {
const { types } = sass;
if (value instanceof types.Boolean) {
return value.getValue();
}
if (value instanceof types.Number) {
const unit = value.getUnit();
if (unit === '') {
return value.getValue();
}
return `${value.getValue()}${unit}`;
}
if (value instanceof types.String) {
return value.getValue();
}
if (value instanceof types.Color) {
return value.toString();
}
if (value instanceof types.List) {
const length = value.getLength();
const result = Array(length);
for (let i = 0; i < length; i++) {
result[i] = convert(value.getValue(i));
}
return result;
}
if (value instanceof types.Map) {
const length = value.getLength();
const result = {};
for (let i = 0; i < length; i++) {
const key = convert(value.getKey(i));
result[key] = convert(value.getValue(i));
}
return result;
}
if (value instanceof types.Null) {
return null;
}
return value;
} | function convert(value) {
const { types } = sass;
if (value instanceof types.Boolean) {
return value.getValue();
}
if (value instanceof types.Number) {
const unit = value.getUnit();
if (unit === '') {
return value.getValue();
}
return `${value.getValue()}${unit}`;
}
if (value instanceof types.String) {
return value.getValue();
}
if (value instanceof types.Color) {
return value.toString();
}
if (value instanceof types.List) {
const length = value.getLength();
const result = Array(length);
for (let i = 0; i < length; i++) {
result[i] = convert(value.getValue(i));
}
return result;
}
if (value instanceof types.Map) {
const length = value.getLength();
const result = {};
for (let i = 0; i < length; i++) {
const key = convert(value.getKey(i));
result[key] = convert(value.getValue(i));
}
return result;
}
if (value instanceof types.Null) {
return null;
}
return value;
} |
JavaScript | function formatColorName({ name, grade, formatFor }) {
const formattedName = name.split('-').join(' ');
const folderName = name.includes('hover') ? hoverFolderName : coreFolderName;
switch (formatFor) {
case 'sharedLayerStyle':
return ['color', folderName, formattedName, grade]
.filter(Boolean)
.join(' / ');
case 'colorVariable':
return [
grade
? `${folderName}/${formattedName}/${formattedName}`
: `${folderName}/${formattedName}`,
grade,
]
.filter(Boolean)
.join(' ');
default:
return '';
}
} | function formatColorName({ name, grade, formatFor }) {
const formattedName = name.split('-').join(' ');
const folderName = name.includes('hover') ? hoverFolderName : coreFolderName;
switch (formatFor) {
case 'sharedLayerStyle':
return ['color', folderName, formattedName, grade]
.filter(Boolean)
.join(' / ');
case 'colorVariable':
return [
grade
? `${folderName}/${formattedName}/${formattedName}`
: `${folderName}/${formattedName}`,
grade,
]
.filter(Boolean)
.join(' ');
default:
return '';
}
} |
JavaScript | function syncColorStyles({ document }) {
const sharedCoreStyles = Object.keys(swatches).flatMap((swatchName) => {
const name = formatTokenName(swatchName);
const result = Object.keys(swatches[swatchName]).map((grade) => {
return syncColorStyle({
document,
name: formatColorName({ name, grade, formatFor: 'sharedLayerStyle' }),
value: swatches[swatchName][grade],
});
});
return result;
});
const sharedHoverStyles = Object.keys(hoverSwatches).flatMap((swatchName) => {
const name = formatTokenName(swatchName);
const result = Object.keys(hoverSwatches[swatchName]).map((grade) => {
return syncColorStyle({
document,
name: formatColorName({
name,
grade,
formatFor: 'sharedLayerStyle',
}),
value: hoverSwatches[swatchName][grade],
});
});
return result;
});
const singleColors = [
['black', black['100']],
['white', white['0']],
['orange', orange['40']],
['yellow', yellow['30']],
].map(([name, value]) => {
return syncColorStyle({
document,
name: formatColorName({ name, formatFor: 'sharedLayerStyle' }),
value,
});
});
const singleHoverColors = [
['black hover', blackHover],
['white hover', whiteHover],
].map(([name, value]) => {
return syncColorStyle({
document,
name: formatColorName({ name, formatFor: 'sharedLayerStyle' }),
value,
});
});
return sharedCoreStyles.concat(
singleColors,
singleHoverColors,
sharedHoverStyles
);
} | function syncColorStyles({ document }) {
const sharedCoreStyles = Object.keys(swatches).flatMap((swatchName) => {
const name = formatTokenName(swatchName);
const result = Object.keys(swatches[swatchName]).map((grade) => {
return syncColorStyle({
document,
name: formatColorName({ name, grade, formatFor: 'sharedLayerStyle' }),
value: swatches[swatchName][grade],
});
});
return result;
});
const sharedHoverStyles = Object.keys(hoverSwatches).flatMap((swatchName) => {
const name = formatTokenName(swatchName);
const result = Object.keys(hoverSwatches[swatchName]).map((grade) => {
return syncColorStyle({
document,
name: formatColorName({
name,
grade,
formatFor: 'sharedLayerStyle',
}),
value: hoverSwatches[swatchName][grade],
});
});
return result;
});
const singleColors = [
['black', black['100']],
['white', white['0']],
['orange', orange['40']],
['yellow', yellow['30']],
].map(([name, value]) => {
return syncColorStyle({
document,
name: formatColorName({ name, formatFor: 'sharedLayerStyle' }),
value,
});
});
const singleHoverColors = [
['black hover', blackHover],
['white hover', whiteHover],
].map(([name, value]) => {
return syncColorStyle({
document,
name: formatColorName({ name, formatFor: 'sharedLayerStyle' }),
value,
});
});
return sharedCoreStyles.concat(
singleColors,
singleHoverColors,
sharedHoverStyles
);
} |
JavaScript | function useEscapeToClose(ref, callback, override = true) {
const handleKeyDown = (event) => {
// The callback should only be called when focus is on or within the container
const elementContainsFocus =
(ref.current && document.activeElement === ref.current) ||
ref.current.contains(document.activeElement);
if (matches(event, [keys.Escape]) && override && elementContainsFocus) {
callback(event);
}
};
useIsomorphicEffect(() => {
document.addEventListener('keydown', handleKeyDown, false);
return () => document.removeEventListener('keydown', handleKeyDown, false);
});
} | function useEscapeToClose(ref, callback, override = true) {
const handleKeyDown = (event) => {
// The callback should only be called when focus is on or within the container
const elementContainsFocus =
(ref.current && document.activeElement === ref.current) ||
ref.current.contains(document.activeElement);
if (matches(event, [keys.Escape]) && override && elementContainsFocus) {
callback(event);
}
};
useIsomorphicEffect(() => {
document.addEventListener('keydown', handleKeyDown, false);
return () => document.removeEventListener('keydown', handleKeyDown, false);
});
} |
JavaScript | _getSVGComplete() {
return `<svg width="24px" height="24px" viewBox="0 0 24 24">
<circle cx="12" cy="12" r="12"></circle>
<polygon points="10.3 13.6 7.7 11 6.3 12.4 10.3 16.4 17.8 9 16.4 7.6"></polygon>
</svg>`;
} | _getSVGComplete() {
return `<svg width="24px" height="24px" viewBox="0 0 24 24">
<circle cx="12" cy="12" r="12"></circle>
<polygon points="10.3 13.6 7.7 11 6.3 12.4 10.3 16.4 17.8 9 16.4 7.6"></polygon>
</svg>`;
} |
JavaScript | _getCurrentSVG() {
return `<svg>
<circle cx="12" cy="12" r="12"></circle>
<circle cx="12" cy="12" r="6"></circle>
</svg>`;
} | _getCurrentSVG() {
return `<svg>
<circle cx="12" cy="12" r="12"></circle>
<circle cx="12" cy="12" r="6"></circle>
</svg>`;
} |
JavaScript | _getIncompleteSVG() {
return `<svg>
<circle cx="12" cy="12" r="12"></circle>
</svg>`;
} | _getIncompleteSVG() {
return `<svg>
<circle cx="12" cy="12" r="12"></circle>
</svg>`;
} |
JavaScript | static get options() {
const { prefix } = settings;
return {
selectorInit: '[data-progress]',
selectorStepElement: `.${prefix}--progress-step`,
selectorCurrent: `.${prefix}--progress-step--current`,
selectorIncomplete: `.${prefix}--progress-step--incomplete`,
selectorComplete: `.${prefix}--progress-step--complete`,
selectorLabel: `.${prefix}--progress-label`,
selectorTooltip: `.${prefix}--tooltip`,
selectorTooltipText: `.${prefix}--tooltip__text`,
classStep: `${prefix}--progress-step`,
classComplete: `${prefix}--progress-step--complete`,
classCurrent: `${prefix}--progress-step--current`,
classIncomplete: `${prefix}--progress-step--incomplete`,
classOverflowLabel: `${prefix}--progress-label-overflow`,
classTooltipMulti: `${prefix}--tooltip_multi`,
maxWidth: 87,
tooltipMaxHeight: 21,
};
} | static get options() {
const { prefix } = settings;
return {
selectorInit: '[data-progress]',
selectorStepElement: `.${prefix}--progress-step`,
selectorCurrent: `.${prefix}--progress-step--current`,
selectorIncomplete: `.${prefix}--progress-step--incomplete`,
selectorComplete: `.${prefix}--progress-step--complete`,
selectorLabel: `.${prefix}--progress-label`,
selectorTooltip: `.${prefix}--tooltip`,
selectorTooltipText: `.${prefix}--tooltip__text`,
classStep: `${prefix}--progress-step`,
classComplete: `${prefix}--progress-step--complete`,
classCurrent: `${prefix}--progress-step--current`,
classIncomplete: `${prefix}--progress-step--incomplete`,
classOverflowLabel: `${prefix}--progress-label-overflow`,
classTooltipMulti: `${prefix}--tooltip_multi`,
maxWidth: 87,
tooltipMaxHeight: 21,
};
} |
JavaScript | static get options() {
const { prefix } = settings;
return {
selectorInit: `.${prefix}--checkbox`,
selectorContainedCheckboxState: '[data-contained-checkbox-state]',
selectorContainedCheckboxDisabled: '[data-contained-checkbox-disabled]',
classLabel: `${prefix}--checkbox-label`,
classLabelFocused: `${prefix}--checkbox-label__focus`,
attribContainedCheckboxState: 'data-contained-checkbox-state',
attribContainedCheckboxDisabled: 'data-contained-checkbox-disabled',
};
} | static get options() {
const { prefix } = settings;
return {
selectorInit: `.${prefix}--checkbox`,
selectorContainedCheckboxState: '[data-contained-checkbox-state]',
selectorContainedCheckboxDisabled: '[data-contained-checkbox-disabled]',
classLabel: `${prefix}--checkbox-label`,
classLabelFocused: `${prefix}--checkbox-label__focus`,
attribContainedCheckboxState: 'data-contained-checkbox-state',
attribContainedCheckboxDisabled: 'data-contained-checkbox-disabled',
};
} |
JavaScript | changeState(state) {
this.element.classList.toggle(
this.options.classSideNavExpanded,
state === this.constructor.state.EXPANDED
);
} | changeState(state) {
this.element.classList.toggle(
this.options.classSideNavExpanded,
state === this.constructor.state.EXPANDED
);
} |
JavaScript | static get options() {
const { prefix } = settings;
return {
initEventNames: ['click'],
eventBeforeExpanded: 'navigation-menu-being-expanded',
eventAfterExpanded: 'navigation-menu-expanded',
eventBeforeCollapsed: 'navigation-menu-being-collapsed',
eventAfterCollapsed: 'navigation-menu-collapsed',
selectorFocusableMenuItem: `.${prefix}--navigation__category-toggle, .${prefix}--navigation-link`,
classNavigationMenuPanelHeaderActionActive: `${prefix}--header__action--active`,
attribLabelExpand: 'data-navigation-menu-panel-label-expand',
attribLabelCollapse: 'data-navigation-menu-panel-label-collapse',
};
} | static get options() {
const { prefix } = settings;
return {
initEventNames: ['click'],
eventBeforeExpanded: 'navigation-menu-being-expanded',
eventAfterExpanded: 'navigation-menu-expanded',
eventBeforeCollapsed: 'navigation-menu-being-collapsed',
eventAfterCollapsed: 'navigation-menu-collapsed',
selectorFocusableMenuItem: `.${prefix}--navigation__category-toggle, .${prefix}--navigation-link`,
classNavigationMenuPanelHeaderActionActive: `${prefix}--header__action--active`,
attribLabelExpand: 'data-navigation-menu-panel-label-expand',
attribLabelCollapse: 'data-navigation-menu-panel-label-collapse',
};
} |
JavaScript | function syncSharedStyle({
document,
name,
style,
styleType = SharedStyle.StyleType.Layer,
}) {
// Figure out the type of shared style and try and find if we have already
// created a shared style with the given name
const documentSharedStyles =
styleType === SharedStyle.StyleType.Layer
? document.sharedLayerStyles
: document.sharedTextStyles;
const [sharedStyle] = Array.from(documentSharedStyles).filter(
(sharedStyle) => {
/**
* TODO: remove the following block after next Sketch plugin release
* backwards compatibility to avoid breaking changes from #5664, #5744
* we search for style names with the following format
* `color/teal/60`
* and reformat it to
* `color / teal / 60`
* this search and replace will not be needed after the plugin has been
* published with renamed style layers
*/
// start removal
if (sharedStyle.name.split('/').join(' / ') === name) {
sharedStyle.name = name;
}
// end removal
return sharedStyle.name === name;
}
);
// If none exists, we can create one from scratch
if (!sharedStyle) {
const generatedSharedStyle = SharedStyle.fromStyle({
name,
style,
styleType,
document,
});
generatedSharedStyle.style.borders = [];
return generatedSharedStyle;
}
// Otherwise, we'll go and update values of the sharedStyle with the given
// style if the values are different
Object.keys(style).forEach((key) => {
if (sharedStyle.style[key] !== style[key]) {
sharedStyle.style[key] = style[key];
}
});
for (const layer of Array.from(sharedStyle.getAllInstancesLayers())) {
layer.style.syncWithSharedStyle(sharedStyle);
}
return sharedStyle;
} | function syncSharedStyle({
document,
name,
style,
styleType = SharedStyle.StyleType.Layer,
}) {
// Figure out the type of shared style and try and find if we have already
// created a shared style with the given name
const documentSharedStyles =
styleType === SharedStyle.StyleType.Layer
? document.sharedLayerStyles
: document.sharedTextStyles;
const [sharedStyle] = Array.from(documentSharedStyles).filter(
(sharedStyle) => {
/**
* TODO: remove the following block after next Sketch plugin release
* backwards compatibility to avoid breaking changes from #5664, #5744
* we search for style names with the following format
* `color/teal/60`
* and reformat it to
* `color / teal / 60`
* this search and replace will not be needed after the plugin has been
* published with renamed style layers
*/
// start removal
if (sharedStyle.name.split('/').join(' / ') === name) {
sharedStyle.name = name;
}
// end removal
return sharedStyle.name === name;
}
);
// If none exists, we can create one from scratch
if (!sharedStyle) {
const generatedSharedStyle = SharedStyle.fromStyle({
name,
style,
styleType,
document,
});
generatedSharedStyle.style.borders = [];
return generatedSharedStyle;
}
// Otherwise, we'll go and update values of the sharedStyle with the given
// style if the values are different
Object.keys(style).forEach((key) => {
if (sharedStyle.style[key] !== style[key]) {
sharedStyle.style[key] = style[key];
}
});
for (const layer of Array.from(sharedStyle.getAllInstancesLayers())) {
layer.style.syncWithSharedStyle(sharedStyle);
}
return sharedStyle;
} |
JavaScript | static get options() {
const { prefix } = settings;
return {
selectorInit: '[data-tile]',
selectorAboveTheFold: '[data-tile-atf]',
selectorTileInput: '[data-tile-input]',
classExpandedTile: `${prefix}--tile--is-expanded`,
classClickableTile: `${prefix}--tile--is-clicked`,
classSelectableTile: `${prefix}--tile--is-selected`,
};
} | static get options() {
const { prefix } = settings;
return {
selectorInit: '[data-tile]',
selectorAboveTheFold: '[data-tile-atf]',
selectorTileInput: '[data-tile-input]',
classExpandedTile: `${prefix}--tile--is-expanded`,
classClickableTile: `${prefix}--tile--is-clicked`,
classSelectableTile: `${prefix}--tile--is-selected`,
};
} |
JavaScript | _handleClick(event) {
const button = eventMatches(event, this.options.selectorButton);
if (button) {
this.changeState({
group: 'selected',
item: button,
launchingEvent: event,
});
}
} | _handleClick(event) {
const button = eventMatches(event, this.options.selectorButton);
if (button) {
this.changeState({
group: 'selected',
item: button,
launchingEvent: event,
});
}
} |
JavaScript | _changeState({ item }, callback) {
// `options.selectorLink` is not defined in this class itself, code here primary is for inherited classes
const itemLink = item.querySelector(this.options.selectorLink);
if (itemLink) {
toArray(this.element.querySelectorAll(this.options.selectorLink)).forEach(
(link) => {
if (link !== itemLink) {
link.setAttribute('aria-selected', 'false');
}
}
);
itemLink.setAttribute('aria-selected', 'true');
}
const selectorButtons = toArray(
this.element.querySelectorAll(this.options.selectorButton)
);
selectorButtons.forEach((button) => {
if (button !== item) {
button.setAttribute('aria-selected', false);
button.classList.toggle(this.options.classActive, false);
toArray(
button.ownerDocument.querySelectorAll(button.dataset.target)
).forEach((element) => {
element.setAttribute('hidden', '');
element.setAttribute('aria-hidden', 'true');
});
}
});
item.classList.toggle(this.options.classActive, true);
item.setAttribute('aria-selected', true);
toArray(item.ownerDocument.querySelectorAll(item.dataset.target)).forEach(
(element) => {
element.removeAttribute('hidden');
element.setAttribute('aria-hidden', 'false');
}
);
if (callback) {
callback();
}
} | _changeState({ item }, callback) {
// `options.selectorLink` is not defined in this class itself, code here primary is for inherited classes
const itemLink = item.querySelector(this.options.selectorLink);
if (itemLink) {
toArray(this.element.querySelectorAll(this.options.selectorLink)).forEach(
(link) => {
if (link !== itemLink) {
link.setAttribute('aria-selected', 'false');
}
}
);
itemLink.setAttribute('aria-selected', 'true');
}
const selectorButtons = toArray(
this.element.querySelectorAll(this.options.selectorButton)
);
selectorButtons.forEach((button) => {
if (button !== item) {
button.setAttribute('aria-selected', false);
button.classList.toggle(this.options.classActive, false);
toArray(
button.ownerDocument.querySelectorAll(button.dataset.target)
).forEach((element) => {
element.setAttribute('hidden', '');
element.setAttribute('aria-hidden', 'true');
});
}
});
item.classList.toggle(this.options.classActive, true);
item.setAttribute('aria-selected', true);
toArray(item.ownerDocument.querySelectorAll(item.dataset.target)).forEach(
(element) => {
element.removeAttribute('hidden');
element.setAttribute('aria-hidden', 'false');
}
);
if (callback) {
callback();
}
} |
JavaScript | static get options() {
const { prefix } = settings;
return {
selectorInit: '[data-content-switcher]',
selectorButton: `input[type="radio"], .${prefix}--content-switcher-btn`,
classActive: `${prefix}--content-switcher--selected`,
eventBeforeSelected: 'content-switcher-beingselected',
eventAfterSelected: 'content-switcher-selected',
};
} | static get options() {
const { prefix } = settings;
return {
selectorInit: '[data-content-switcher]',
selectorButton: `input[type="radio"], .${prefix}--content-switcher-btn`,
classActive: `${prefix}--content-switcher--selected`,
eventBeforeSelected: 'content-switcher-beingselected',
eventAfterSelected: 'content-switcher-selected',
};
} |
JavaScript | async function builder(metadata, { output }) {
const modules = metadata.icons.map((icon) => {
const { moduleInfo } = icon;
const localPreamble = [];
const globalPreamble = [];
if (icon.deprecated) {
localPreamble.push(
templates.deprecatedBlock({
check: t.identifier('didWarnAboutDeprecation'),
warning: t.stringLiteral(
formatDeprecationWarning(moduleInfo.local, icon.reason)
),
})
);
globalPreamble.push(
templates.deprecatedBlock({
check: t.memberExpression(
t.identifier('didWarnAboutDeprecation'),
t.stringLiteral(moduleInfo.global),
true
),
warning: t.stringLiteral(
formatDeprecationWarning(moduleInfo.global, icon.reason)
),
})
);
}
const localSource = createIconSource(
moduleInfo.local,
moduleInfo.sizes,
localPreamble
);
const globalSource = createIconSource(
moduleInfo.global,
moduleInfo.sizes,
globalPreamble
);
return {
filepath: moduleInfo.filepath,
entrypoint: createIconEntrypoint(
moduleInfo.local,
localSource,
icon.deprecated
),
name: moduleInfo.global,
source: globalSource,
};
});
// Rollup allows us to define multiple "entrypoints" instead of only one when
// creating a bundle. This allows us to map different input paths in the
// `input` object to files that we're generating for each icon component in
// the `files` object
const files = {
'index.js': template.ast(`
import React from 'react';
import Icon from './Icon.js';
import { iconPropTypes } from './iconPropTypes.js';
export { Icon };
const didWarnAboutDeprecation = {};
`),
};
const input = {
'index.js': 'index.js',
};
for (const m of modules) {
files[m.filepath] = m.entrypoint;
input[m.filepath] = m.filepath;
files['index.js'].push(...m.source);
files['index.js'].push(template.ast(`export { ${m.name} };`));
}
files['index.js'] = t.file(t.program(files['index.js']));
files['index.js'] = generate(files['index.js']).code;
const defaultVirtualOptions = {
// Each of our Icon modules use the "./Icon.js" path to import this base
// componnet
'./Icon.js': await fs.readFile(
path.resolve(__dirname, './components/Icon.js'),
'utf8'
),
'./iconPropTypes.js': `
import PropTypes from 'prop-types';
export const iconPropTypes = {
size: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string,
]),
};
`,
};
const bundle = await rollup({
input,
external: ['@carbon/icon-helpers', 'react', 'prop-types'],
plugins: [
// We use a "virtual" plugin to pass all of our components that we
// created from our metadata to rollup instead of rollup trying to read
// these files from disk
virtual({
...defaultVirtualOptions,
...files,
}),
babel(babelConfig),
// Add a custom plugin to emit a `package.json` file. This includes the
// settings for the "main" and "module" entrypoints for packages, along
// with the new "exports" field for Node.js v14+
//
// When this bundle becomes the default, this logic will live in
// icons-react/package.json
{
name: 'generate-package-json',
generateBundle() {
const packageJson = {
main: 'index.js',
module: 'index.esm.js',
exports: {
import: 'index.esm.js',
require: 'index.js',
},
};
this.emitFile({
type: 'asset',
name: 'package.json',
fileName: 'package.json',
source: JSON.stringify(packageJson, null, 2),
});
},
},
],
});
await bundle.write({
dir: path.join(output, 'next'),
format: 'commonjs',
entryFileNames: '[name]',
banner: templates.banner,
exports: 'auto',
});
// We create a separate rollup for our ESM bundle since this will only emit
// one file: `index.esm.js`
const esmBundle = await rollup({
input: 'index.js',
external: ['@carbon/icon-helpers', 'react', 'prop-types'],
plugins: [
virtual({
...defaultVirtualOptions,
'index.js': files['index.js'],
}),
babel(babelConfig),
],
});
await esmBundle.write({
file: path.join(output, 'next', 'index.esm.js'),
format: 'esm',
banner: templates.banner,
exports: 'auto',
});
} | async function builder(metadata, { output }) {
const modules = metadata.icons.map((icon) => {
const { moduleInfo } = icon;
const localPreamble = [];
const globalPreamble = [];
if (icon.deprecated) {
localPreamble.push(
templates.deprecatedBlock({
check: t.identifier('didWarnAboutDeprecation'),
warning: t.stringLiteral(
formatDeprecationWarning(moduleInfo.local, icon.reason)
),
})
);
globalPreamble.push(
templates.deprecatedBlock({
check: t.memberExpression(
t.identifier('didWarnAboutDeprecation'),
t.stringLiteral(moduleInfo.global),
true
),
warning: t.stringLiteral(
formatDeprecationWarning(moduleInfo.global, icon.reason)
),
})
);
}
const localSource = createIconSource(
moduleInfo.local,
moduleInfo.sizes,
localPreamble
);
const globalSource = createIconSource(
moduleInfo.global,
moduleInfo.sizes,
globalPreamble
);
return {
filepath: moduleInfo.filepath,
entrypoint: createIconEntrypoint(
moduleInfo.local,
localSource,
icon.deprecated
),
name: moduleInfo.global,
source: globalSource,
};
});
// Rollup allows us to define multiple "entrypoints" instead of only one when
// creating a bundle. This allows us to map different input paths in the
// `input` object to files that we're generating for each icon component in
// the `files` object
const files = {
'index.js': template.ast(`
import React from 'react';
import Icon from './Icon.js';
import { iconPropTypes } from './iconPropTypes.js';
export { Icon };
const didWarnAboutDeprecation = {};
`),
};
const input = {
'index.js': 'index.js',
};
for (const m of modules) {
files[m.filepath] = m.entrypoint;
input[m.filepath] = m.filepath;
files['index.js'].push(...m.source);
files['index.js'].push(template.ast(`export { ${m.name} };`));
}
files['index.js'] = t.file(t.program(files['index.js']));
files['index.js'] = generate(files['index.js']).code;
const defaultVirtualOptions = {
// Each of our Icon modules use the "./Icon.js" path to import this base
// componnet
'./Icon.js': await fs.readFile(
path.resolve(__dirname, './components/Icon.js'),
'utf8'
),
'./iconPropTypes.js': `
import PropTypes from 'prop-types';
export const iconPropTypes = {
size: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string,
]),
};
`,
};
const bundle = await rollup({
input,
external: ['@carbon/icon-helpers', 'react', 'prop-types'],
plugins: [
// We use a "virtual" plugin to pass all of our components that we
// created from our metadata to rollup instead of rollup trying to read
// these files from disk
virtual({
...defaultVirtualOptions,
...files,
}),
babel(babelConfig),
// Add a custom plugin to emit a `package.json` file. This includes the
// settings for the "main" and "module" entrypoints for packages, along
// with the new "exports" field for Node.js v14+
//
// When this bundle becomes the default, this logic will live in
// icons-react/package.json
{
name: 'generate-package-json',
generateBundle() {
const packageJson = {
main: 'index.js',
module: 'index.esm.js',
exports: {
import: 'index.esm.js',
require: 'index.js',
},
};
this.emitFile({
type: 'asset',
name: 'package.json',
fileName: 'package.json',
source: JSON.stringify(packageJson, null, 2),
});
},
},
],
});
await bundle.write({
dir: path.join(output, 'next'),
format: 'commonjs',
entryFileNames: '[name]',
banner: templates.banner,
exports: 'auto',
});
// We create a separate rollup for our ESM bundle since this will only emit
// one file: `index.esm.js`
const esmBundle = await rollup({
input: 'index.js',
external: ['@carbon/icon-helpers', 'react', 'prop-types'],
plugins: [
virtual({
...defaultVirtualOptions,
'index.js': files['index.js'],
}),
babel(babelConfig),
],
});
await esmBundle.write({
file: path.join(output, 'next', 'index.esm.js'),
format: 'esm',
banner: templates.banner,
exports: 'auto',
});
} |
JavaScript | function createIconSource(moduleName, sizes, preamble = []) {
// We map over all of our different asset sizes to generate the JSX needed to
// render the asset
const sizeVariants = sizes.map(({ size, ast }) => {
const { svgProps, children } = svgToJSX(ast);
const source = templates.jsx({
props: t.objectExpression([
t.objectProperty(t.identifier('width'), t.identifier('size')),
t.objectProperty(t.identifier('height'), t.identifier('size')),
t.objectProperty(t.identifier('ref'), t.identifier('ref')),
...Object.entries(svgProps).map(([key, value]) => {
return t.objectProperty(t.identifier(key), jsToAST(value));
}),
t.spreadElement(t.identifier('rest')),
]),
children,
});
return {
source,
size: size || 'glyph',
};
});
// Find our max size from all of our asset sizes. The max size will be our
// "default" icon, meaning that it will be used if no matches come in for a
// specific size
const maxSize = sizeVariants.reduce((maxSize, { size }) => {
if (size > maxSize) {
return size;
}
return maxSize;
}, -Infinity);
// Each asset that is not used for our "default" icon will conditionally
// render from an if statement in our component
const ifStatements = sizeVariants.filter(({ size }) => {
return size !== maxSize;
});
// The "default" icon that will be rendered, based on the max size
const returnStatement =
sizeVariants.find(({ size }) => {
return size === maxSize;
}) ?? sizeVariants[0];
// We build up our component source by adding in any necessary deprecation
// blocks along with conditionally rendering all asset sizes. We also use a
// return statement for the "default" icon
const source = templates.component({
moduleName: t.identifier(moduleName),
defaultSize: t.numericLiteral(16),
statements: [
...preamble,
...ifStatements.map(({ size, source }) => {
// Generate if (size === 16 || size === '16' || size === '16px') {}
// block statements to match on numbers or strings
return t.ifStatement(
t.logicalExpression(
'||',
t.logicalExpression(
'||',
t.binaryExpression('===', t.identifier('size'), jsToAST(size)),
t.binaryExpression(
'===',
t.identifier('size'),
jsToAST('' + size)
)
),
t.binaryExpression(
'===',
t.identifier('size'),
jsToAST(`${size}px`)
)
),
t.blockStatement([t.returnStatement(source)])
);
}),
t.returnStatement(returnStatement.source),
].filter(Boolean),
});
return source;
} | function createIconSource(moduleName, sizes, preamble = []) {
// We map over all of our different asset sizes to generate the JSX needed to
// render the asset
const sizeVariants = sizes.map(({ size, ast }) => {
const { svgProps, children } = svgToJSX(ast);
const source = templates.jsx({
props: t.objectExpression([
t.objectProperty(t.identifier('width'), t.identifier('size')),
t.objectProperty(t.identifier('height'), t.identifier('size')),
t.objectProperty(t.identifier('ref'), t.identifier('ref')),
...Object.entries(svgProps).map(([key, value]) => {
return t.objectProperty(t.identifier(key), jsToAST(value));
}),
t.spreadElement(t.identifier('rest')),
]),
children,
});
return {
source,
size: size || 'glyph',
};
});
// Find our max size from all of our asset sizes. The max size will be our
// "default" icon, meaning that it will be used if no matches come in for a
// specific size
const maxSize = sizeVariants.reduce((maxSize, { size }) => {
if (size > maxSize) {
return size;
}
return maxSize;
}, -Infinity);
// Each asset that is not used for our "default" icon will conditionally
// render from an if statement in our component
const ifStatements = sizeVariants.filter(({ size }) => {
return size !== maxSize;
});
// The "default" icon that will be rendered, based on the max size
const returnStatement =
sizeVariants.find(({ size }) => {
return size === maxSize;
}) ?? sizeVariants[0];
// We build up our component source by adding in any necessary deprecation
// blocks along with conditionally rendering all asset sizes. We also use a
// return statement for the "default" icon
const source = templates.component({
moduleName: t.identifier(moduleName),
defaultSize: t.numericLiteral(16),
statements: [
...preamble,
...ifStatements.map(({ size, source }) => {
// Generate if (size === 16 || size === '16' || size === '16px') {}
// block statements to match on numbers or strings
return t.ifStatement(
t.logicalExpression(
'||',
t.logicalExpression(
'||',
t.binaryExpression('===', t.identifier('size'), jsToAST(size)),
t.binaryExpression(
'===',
t.identifier('size'),
jsToAST('' + size)
)
),
t.binaryExpression(
'===',
t.identifier('size'),
jsToAST(`${size}px`)
)
),
t.blockStatement([t.returnStatement(source)])
);
}),
t.returnStatement(returnStatement.source),
].filter(Boolean),
});
return source;
} |
JavaScript | function useNormalizedInputProps({
id,
readOnly,
disabled,
invalid,
invalidText,
warn,
warnText,
}) {
const normalizedProps = {
disabled: !readOnly && disabled,
invalid: !readOnly && invalid,
invalidId: `${id}-error-msg`,
warn: !readOnly && !invalid && warn,
warnId: `${id}-warn-msg`,
validation: null,
icon: null,
helperId: `${id}-helper-text`,
};
if (readOnly) {
normalizedProps.icon = EditOff16;
} else {
if (normalizedProps.invalid) {
normalizedProps.icon = WarningFilled16;
normalizedProps.validation = (
<div
className={`${prefix}--form-requirement`}
id={normalizedProps.invalidId}>
{invalidText}
</div>
);
} else if (normalizedProps.warn) {
normalizedProps.icon = WarningAltFilled16;
normalizedProps.validation = (
<div
className={`${prefix}--form-requirement`}
id={normalizedProps.warnId}>
{warnText}
</div>
);
}
}
return normalizedProps;
} | function useNormalizedInputProps({
id,
readOnly,
disabled,
invalid,
invalidText,
warn,
warnText,
}) {
const normalizedProps = {
disabled: !readOnly && disabled,
invalid: !readOnly && invalid,
invalidId: `${id}-error-msg`,
warn: !readOnly && !invalid && warn,
warnId: `${id}-warn-msg`,
validation: null,
icon: null,
helperId: `${id}-helper-text`,
};
if (readOnly) {
normalizedProps.icon = EditOff16;
} else {
if (normalizedProps.invalid) {
normalizedProps.icon = WarningFilled16;
normalizedProps.validation = (
<div
className={`${prefix}--form-requirement`}
id={normalizedProps.invalidId}>
{invalidText}
</div>
);
} else if (normalizedProps.warn) {
normalizedProps.icon = WarningAltFilled16;
normalizedProps.validation = (
<div
className={`${prefix}--form-requirement`}
id={normalizedProps.warnId}>
{warnText}
</div>
);
}
}
return normalizedProps;
} |
JavaScript | async function main() {
reporter.info('Building examples...');
await fs.remove(BUILD_DIR);
await fs.ensureDir(BUILD_DIR);
const packageNames = await fs.readdir(PACKAGES_DIR);
const packages = await Promise.all(
packageNames
.filter((name) => PACKAGES_TO_BUILD.has(name))
.map(async (name) => {
// Verify that each file that we read from the packages directory is
// actually a folder. Typically used to catch `.DS_store` files that
// accidentally appear when opening with MacOS Finder
const filepath = path.join(PACKAGES_DIR, name);
const stat = await fs.lstat(filepath);
const descriptor = {
filepath,
name,
};
if (!stat.isDirectory()) {
throw new Error(`Unexpected file: ${name} at ${filepath}`);
}
// Try and figure out if the package has an examples directory, if not
// then we can skip it
const examplesDir = path.join(filepath, 'examples');
if (!(await fs.pathExists(examplesDir))) {
return descriptor;
}
const examples = (await fs.readdir(examplesDir)).filter((example) => {
return (
example !== '.yarnrc' &&
example !== '.yarnrc.yml' &&
!IGNORE_EXAMPLE_DIRS.has(example) &&
example !== '.DS_Store'
);
});
return {
...descriptor,
examples: examples.map((name) => ({
filepath: path.join(examplesDir, name),
name,
})),
};
})
);
const packagesWithExamples = packages.filter(
(pkg) => Array.isArray(pkg.examples) && pkg.examples.length !== 0
);
await Promise.all(
packagesWithExamples.map(async (pkg) => {
reporter.info(`Building examples in package \`${pkg.name}\``);
const { examples, name } = pkg;
const packageDir = path.join(BUILD_DIR, name, 'examples');
await fs.ensureDir(packageDir);
await Promise.all(
examples.map(async (example) => {
reporter.info(
`Building example \`${example.name}\` in package \`${pkg.name}\``
);
const exampleDir = path.join(packageDir, example.name);
const exampleBuildDir = path.join(example.filepath, 'build');
const packageJsonPath = path.join(example.filepath, 'package.json');
const packageJson = await fs.readJson(packageJsonPath);
await fs.ensureDir(exampleDir);
if (packageJson.scripts.build) {
const installResult = spawn.sync('yarn', ['install'], {
stdio: 'inherit',
cwd: example.filepath,
});
if (installResult.status !== 0) {
throw new Error(
`Error installing dependencies for ${pkg.name}:${example.name}`
);
}
const buildResult = spawn.sync('yarn', ['build'], {
stdio: 'inherit',
cwd: example.filepath,
});
if (buildResult.status !== 0) {
throw new Error(
`Error building example ${example.name} for ${pkg.name}`
);
}
}
if (await fs.pathExists(exampleBuildDir)) {
await fs.copy(exampleBuildDir, exampleDir);
return;
}
await fs.copy(example.filepath, exampleDir, {
filter(src) {
const relativePath = path.relative(example.filepath, src);
if (relativePath.includes('node_modules')) {
return false;
}
if (relativePath[0] === '.') {
return false;
}
return true;
},
});
reporter.success(
`Built example \`${example.name}\` in package \`${pkg.name}\``
);
})
);
reporter.success(`Built examples in package \`${pkg.name}\``);
})
);
const links = packagesWithExamples.reduce((html, pkg) => {
const links = pkg.examples.reduce((acc, example) => {
const href = `./${pkg.name}/examples/${example.name}/`;
return acc + `<li><a href="${href}">${example.name}</a></li>`;
}, '');
return (
html +
'\n' +
`<section>
<header>
<h2><pre style="display:inline;"><code>@carbon/${pkg.name}</code></pre></h2>
</header>
<ul>
${links}
</ul>
</section>`
);
}, '');
const indexFile = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=IBM+Plex+Mono" rel="stylesheet">
<title>Carbon Elements</title>
<style>body { font-family: 'IBM Plex Mono', monospaces; }</style>
</head>
<body>${links}</body>
</html>
`;
await fs.writeFile(path.join(BUILD_DIR, 'index.html'), indexFile);
// Copy icons over, useful for adding download links
await fs.copy(
path.resolve(__dirname, '../packages/icons/svg'),
path.join(BUILD_DIR, 'icons/svg')
);
} | async function main() {
reporter.info('Building examples...');
await fs.remove(BUILD_DIR);
await fs.ensureDir(BUILD_DIR);
const packageNames = await fs.readdir(PACKAGES_DIR);
const packages = await Promise.all(
packageNames
.filter((name) => PACKAGES_TO_BUILD.has(name))
.map(async (name) => {
// Verify that each file that we read from the packages directory is
// actually a folder. Typically used to catch `.DS_store` files that
// accidentally appear when opening with MacOS Finder
const filepath = path.join(PACKAGES_DIR, name);
const stat = await fs.lstat(filepath);
const descriptor = {
filepath,
name,
};
if (!stat.isDirectory()) {
throw new Error(`Unexpected file: ${name} at ${filepath}`);
}
// Try and figure out if the package has an examples directory, if not
// then we can skip it
const examplesDir = path.join(filepath, 'examples');
if (!(await fs.pathExists(examplesDir))) {
return descriptor;
}
const examples = (await fs.readdir(examplesDir)).filter((example) => {
return (
example !== '.yarnrc' &&
example !== '.yarnrc.yml' &&
!IGNORE_EXAMPLE_DIRS.has(example) &&
example !== '.DS_Store'
);
});
return {
...descriptor,
examples: examples.map((name) => ({
filepath: path.join(examplesDir, name),
name,
})),
};
})
);
const packagesWithExamples = packages.filter(
(pkg) => Array.isArray(pkg.examples) && pkg.examples.length !== 0
);
await Promise.all(
packagesWithExamples.map(async (pkg) => {
reporter.info(`Building examples in package \`${pkg.name}\``);
const { examples, name } = pkg;
const packageDir = path.join(BUILD_DIR, name, 'examples');
await fs.ensureDir(packageDir);
await Promise.all(
examples.map(async (example) => {
reporter.info(
`Building example \`${example.name}\` in package \`${pkg.name}\``
);
const exampleDir = path.join(packageDir, example.name);
const exampleBuildDir = path.join(example.filepath, 'build');
const packageJsonPath = path.join(example.filepath, 'package.json');
const packageJson = await fs.readJson(packageJsonPath);
await fs.ensureDir(exampleDir);
if (packageJson.scripts.build) {
const installResult = spawn.sync('yarn', ['install'], {
stdio: 'inherit',
cwd: example.filepath,
});
if (installResult.status !== 0) {
throw new Error(
`Error installing dependencies for ${pkg.name}:${example.name}`
);
}
const buildResult = spawn.sync('yarn', ['build'], {
stdio: 'inherit',
cwd: example.filepath,
});
if (buildResult.status !== 0) {
throw new Error(
`Error building example ${example.name} for ${pkg.name}`
);
}
}
if (await fs.pathExists(exampleBuildDir)) {
await fs.copy(exampleBuildDir, exampleDir);
return;
}
await fs.copy(example.filepath, exampleDir, {
filter(src) {
const relativePath = path.relative(example.filepath, src);
if (relativePath.includes('node_modules')) {
return false;
}
if (relativePath[0] === '.') {
return false;
}
return true;
},
});
reporter.success(
`Built example \`${example.name}\` in package \`${pkg.name}\``
);
})
);
reporter.success(`Built examples in package \`${pkg.name}\``);
})
);
const links = packagesWithExamples.reduce((html, pkg) => {
const links = pkg.examples.reduce((acc, example) => {
const href = `./${pkg.name}/examples/${example.name}/`;
return acc + `<li><a href="${href}">${example.name}</a></li>`;
}, '');
return (
html +
'\n' +
`<section>
<header>
<h2><pre style="display:inline;"><code>@carbon/${pkg.name}</code></pre></h2>
</header>
<ul>
${links}
</ul>
</section>`
);
}, '');
const indexFile = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=IBM+Plex+Mono" rel="stylesheet">
<title>Carbon Elements</title>
<style>body { font-family: 'IBM Plex Mono', monospaces; }</style>
</head>
<body>${links}</body>
</html>
`;
await fs.writeFile(path.join(BUILD_DIR, 'index.html'), indexFile);
// Copy icons over, useful for adding download links
await fs.copy(
path.resolve(__dirname, '../packages/icons/svg'),
path.join(BUILD_DIR, 'icons/svg')
);
} |
JavaScript | function Portal({ container, children }) {
const [mountNode, setMountNode] = useState(null);
useEffect(() => {
setMountNode(container ? container.current : document.body);
}, [container]);
if (mountNode) {
return ReactDOM.createPortal(children, mountNode);
}
return null;
} | function Portal({ container, children }) {
const [mountNode, setMountNode] = useState(null);
useEffect(() => {
setMountNode(container ? container.current : document.body);
}, [container]);
if (mountNode) {
return ReactDOM.createPortal(children, mountNode);
}
return null;
} |
JavaScript | static get options() {
const { prefix } = settings;
return {
selectorInit: '[data-accordion]',
selectorAccordionItem: `.${prefix}--accordion__item`,
selectorAccordionItemHeading: `.${prefix}--accordion__heading`,
selectorAccordionContent: `.${prefix}--accordion__content`,
classActive: `${prefix}--accordion__item--active`,
};
} | static get options() {
const { prefix } = settings;
return {
selectorInit: '[data-accordion]',
selectorAccordionItem: `.${prefix}--accordion__item`,
selectorAccordionItemHeading: `.${prefix}--accordion__heading`,
selectorAccordionContent: `.${prefix}--accordion__content`,
classActive: `${prefix}--accordion__item--active`,
};
} |
JavaScript | _handleDocumentClick(event) {
const searchInput = eventMatches(event, this.options.selectorSearch);
const isOfSelfSearchInput =
searchInput && this.element.contains(searchInput);
if (isOfSelfSearchInput) {
const shouldBeOpen =
isOfSelfSearchInput &&
!this.element.classList.contains(this.options.classSearchActive);
searchInput.classList.toggle(
this.options.classSearchActive,
shouldBeOpen
);
if (shouldBeOpen) {
searchInput.querySelector('input').focus();
}
}
const targetComponentElement = eventMatches(
event,
this.options.selectorInit
);
toArray(
this.element.ownerDocument.querySelectorAll(this.options.selectorSearch)
).forEach((item) => {
if (!targetComponentElement || !targetComponentElement.contains(item)) {
item.classList.remove(this.options.classSearchActive);
}
});
} | _handleDocumentClick(event) {
const searchInput = eventMatches(event, this.options.selectorSearch);
const isOfSelfSearchInput =
searchInput && this.element.contains(searchInput);
if (isOfSelfSearchInput) {
const shouldBeOpen =
isOfSelfSearchInput &&
!this.element.classList.contains(this.options.classSearchActive);
searchInput.classList.toggle(
this.options.classSearchActive,
shouldBeOpen
);
if (shouldBeOpen) {
searchInput.querySelector('input').focus();
}
}
const targetComponentElement = eventMatches(
event,
this.options.selectorInit
);
toArray(
this.element.ownerDocument.querySelectorAll(this.options.selectorSearch)
).forEach((item) => {
if (!targetComponentElement || !targetComponentElement.contains(item)) {
item.classList.remove(this.options.classSearchActive);
}
});
} |
JavaScript | _handleKeyDown(event) {
const searchInput = eventMatches(event, this.options.selectorSearch);
if (searchInput && event.which === 27) {
searchInput.classList.remove(this.options.classSearchActive);
}
} | _handleKeyDown(event) {
const searchInput = eventMatches(event, this.options.selectorSearch);
if (searchInput && event.which === 27) {
searchInput.classList.remove(this.options.classSearchActive);
}
} |
JavaScript | _handleRowHeightChange(event, boundTable) {
const { value } = event.currentTarget.querySelector('input:checked');
if (value === 'tall') {
boundTable.classList.add(this.options.classTallRows);
} else {
boundTable.classList.remove(this.options.classTallRows);
}
} | _handleRowHeightChange(event, boundTable) {
const { value } = event.currentTarget.querySelector('input:checked');
if (value === 'tall') {
boundTable.classList.add(this.options.classTallRows);
} else {
boundTable.classList.remove(this.options.classTallRows);
}
} |
JavaScript | static get options() {
const { prefix } = settings;
return {
selectorInit: '[data-toolbar]',
selectorSearch: '[data-toolbar-search]',
selectorRowHeight: '[data-row-height]',
classTallRows: `${prefix}--responsive-table--tall`,
classSearchActive: `${prefix}--toolbar-search--active`,
};
} | static get options() {
const { prefix } = settings;
return {
selectorInit: '[data-toolbar]',
selectorSearch: '[data-toolbar-search]',
selectorRowHeight: '[data-row-height]',
classTallRows: `${prefix}--responsive-table--tall`,
classSearchActive: `${prefix}--toolbar-search--active`,
};
} |
JavaScript | _changeState() {
throw new Error(
'_changeState() should be overridden to perform actual change in state.'
);
} | _changeState() {
throw new Error(
'_changeState() should be overridden to perform actual change in state.'
);
} |
JavaScript | changeState(...args) {
const state = typeof args[0] === 'string' ? args.shift() : undefined;
const detail =
Object(args[0]) === args[0] && typeof args[0] !== 'function'
? args.shift()
: undefined;
const callback = typeof args[0] === 'function' ? args.shift() : undefined;
if (
typeof this.shouldStateBeChanged === 'function' &&
!this.shouldStateBeChanged(state, detail)
) {
if (callback) {
callback(null, true);
}
return;
}
const data = {
group: detail && detail.group,
state,
};
const eventNameSuffix = [data.group, state]
.filter(Boolean)
.join('-')
.split('-') // Group or state may contain hyphen
.map((item) => item[0].toUpperCase() + item.substr(1))
.join('');
const eventStart = new CustomEvent(
this.options[`eventBefore${eventNameSuffix}`],
{
bubbles: true,
cancelable: true,
detail,
}
);
const fireOnNode = (detail && detail.delegatorNode) || this.element;
const canceled = !fireOnNode.dispatchEvent(eventStart);
if (canceled) {
if (callback) {
const error = new Error(
`Changing state (${JSON.stringify(data)}) has been canceled.`
);
error.canceled = true;
callback(error);
}
} else {
const changeStateArgs = [state, detail].filter(Boolean);
this._changeState(...changeStateArgs, () => {
fireOnNode.dispatchEvent(
new CustomEvent(this.options[`eventAfter${eventNameSuffix}`], {
bubbles: true,
cancelable: true,
detail,
})
);
if (callback) {
callback();
}
});
}
} | changeState(...args) {
const state = typeof args[0] === 'string' ? args.shift() : undefined;
const detail =
Object(args[0]) === args[0] && typeof args[0] !== 'function'
? args.shift()
: undefined;
const callback = typeof args[0] === 'function' ? args.shift() : undefined;
if (
typeof this.shouldStateBeChanged === 'function' &&
!this.shouldStateBeChanged(state, detail)
) {
if (callback) {
callback(null, true);
}
return;
}
const data = {
group: detail && detail.group,
state,
};
const eventNameSuffix = [data.group, state]
.filter(Boolean)
.join('-')
.split('-') // Group or state may contain hyphen
.map((item) => item[0].toUpperCase() + item.substr(1))
.join('');
const eventStart = new CustomEvent(
this.options[`eventBefore${eventNameSuffix}`],
{
bubbles: true,
cancelable: true,
detail,
}
);
const fireOnNode = (detail && detail.delegatorNode) || this.element;
const canceled = !fireOnNode.dispatchEvent(eventStart);
if (canceled) {
if (callback) {
const error = new Error(
`Changing state (${JSON.stringify(data)}) has been canceled.`
);
error.canceled = true;
callback(error);
}
} else {
const changeStateArgs = [state, detail].filter(Boolean);
this._changeState(...changeStateArgs, () => {
fireOnNode.dispatchEvent(
new CustomEvent(this.options[`eventAfter${eventNameSuffix}`], {
bubbles: true,
cancelable: true,
detail,
})
);
if (callback) {
callback();
}
});
}
} |
JavaScript | function safe(name) {
if (!isNaN(name[0])) {
return '_' + name;
}
return name;
} | function safe(name) {
if (!isNaN(name[0])) {
return '_' + name;
}
return name;
} |
JavaScript | function createIconComponent(moduleName, { attrs, content }) {
return `import createSVGComponent from './utils.js';
const attrs = ${JSON.stringify(attrs)};
const content = ${JSON.stringify(content)};
const ${moduleName} = createSVGComponent(${moduleName}, ${JSON.stringify(
attrs
)}, ${JSON.stringify(content)});
export default ${moduleName};
`;
} | function createIconComponent(moduleName, { attrs, content }) {
return `import createSVGComponent from './utils.js';
const attrs = ${JSON.stringify(attrs)};
const content = ${JSON.stringify(content)};
const ${moduleName} = createSVGComponent(${moduleName}, ${JSON.stringify(
attrs
)}, ${JSON.stringify(content)});
export default ${moduleName};
`;
} |
JavaScript | function syncTextStyles(document) {
return Object.keys(styles)
.filter((token) => {
for (const pattern of expressiveTokens) {
if (token.includes(pattern)) {
return false;
}
}
return true;
})
.map((token) => {
const name = formatSharedStyleName(token);
const style = convertTypeStyle(token, styles[token]);
const sharedTextStyle = syncSharedStyle({
document,
name,
style,
styleType: SharedStyle.StyleType.Text,
});
sharedTextStyle.style.textColor = '#000000ff';
sharedTextStyle.style.borders = [];
return sharedTextStyle;
});
} | function syncTextStyles(document) {
return Object.keys(styles)
.filter((token) => {
for (const pattern of expressiveTokens) {
if (token.includes(pattern)) {
return false;
}
}
return true;
})
.map((token) => {
const name = formatSharedStyleName(token);
const style = convertTypeStyle(token, styles[token]);
const sharedTextStyle = syncSharedStyle({
document,
name,
style,
styleType: SharedStyle.StyleType.Text,
});
sharedTextStyle.style.textColor = '#000000ff';
sharedTextStyle.style.borders = [];
return sharedTextStyle;
});
} |
JavaScript | function formatSharedStyleName(token) {
const parts = formatTokenName(token).split('-');
if (parts.length === 2) {
return parts.join('-');
}
const [category, name, grade] = parts;
if (category !== 'productive') {
return parts.join('-');
}
return `${category}/${name}-${grade}`;
} | function formatSharedStyleName(token) {
const parts = formatTokenName(token).split('-');
if (parts.length === 2) {
return parts.join('-');
}
const [category, name, grade] = parts;
if (category !== 'productive') {
return parts.join('-');
}
return `${category}/${name}-${grade}`;
} |
JavaScript | createdByEvent(evt) {
if (evt.type === 'change') {
this._handleChange(evt);
} else {
this._handleDrop(evt);
}
} | createdByEvent(evt) {
if (evt.type === 'change') {
this._handleChange(evt);
} else {
this._handleDrop(evt);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.