id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
|---|---|---|---|---|---|---|---|---|---|---|---|
13,500
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/phonegap1/plugins/cordova-plugin-camera/src/blackberry10/index.js
|
saveImage
|
function saveImage(data, success, fail) {
var name = savePath + imgName();
require('lib/webview').setSandbox(false);
window.webkitRequestFileSystem(window.PERSISTENT, 0, function (fs) {
fs.root.getFile(name, { create: true }, function (entry) {
entry.createWriter(function (writer) {
writer.onwriteend = function () {
success(name);
};
writer.onerror = fail;
writer.write(dataURItoBlob(data));
});
}, fail);
}, fail);
}
|
javascript
|
function saveImage(data, success, fail) {
var name = savePath + imgName();
require('lib/webview').setSandbox(false);
window.webkitRequestFileSystem(window.PERSISTENT, 0, function (fs) {
fs.root.getFile(name, { create: true }, function (entry) {
entry.createWriter(function (writer) {
writer.onwriteend = function () {
success(name);
};
writer.onerror = fail;
writer.write(dataURItoBlob(data));
});
}, fail);
}, fail);
}
|
[
"function",
"saveImage",
"(",
"data",
",",
"success",
",",
"fail",
")",
"{",
"var",
"name",
"=",
"savePath",
"+",
"imgName",
"(",
")",
";",
"require",
"(",
"'lib/webview'",
")",
".",
"setSandbox",
"(",
"false",
")",
";",
"window",
".",
"webkitRequestFileSystem",
"(",
"window",
".",
"PERSISTENT",
",",
"0",
",",
"function",
"(",
"fs",
")",
"{",
"fs",
".",
"root",
".",
"getFile",
"(",
"name",
",",
"{",
"create",
":",
"true",
"}",
",",
"function",
"(",
"entry",
")",
"{",
"entry",
".",
"createWriter",
"(",
"function",
"(",
"writer",
")",
"{",
"writer",
".",
"onwriteend",
"=",
"function",
"(",
")",
"{",
"success",
"(",
"name",
")",
";",
"}",
";",
"writer",
".",
"onerror",
"=",
"fail",
";",
"writer",
".",
"write",
"(",
"dataURItoBlob",
"(",
"data",
")",
")",
";",
"}",
")",
";",
"}",
",",
"fail",
")",
";",
"}",
",",
"fail",
")",
";",
"}"
] |
save dataURI to file system and call success with path
|
[
"save",
"dataURI",
"to",
"file",
"system",
"and",
"call",
"success",
"with",
"path"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/phonegap1/plugins/cordova-plugin-camera/src/blackberry10/index.js#L110-L124
|
13,501
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/scripts/ios/updateAssociatedDomains.js
|
addAssociatedDomains
|
function addAssociatedDomains(preferences) {
const files = getEntitlementFiles(preferences);
for (let i = 0; i < files.length; i++) {
const file = files[i];
let entitlements = getEntitlements(file);
entitlements = updateEntitlements(entitlements, preferences);
setEntitlements(file, entitlements);
}
}
|
javascript
|
function addAssociatedDomains(preferences) {
const files = getEntitlementFiles(preferences);
for (let i = 0; i < files.length; i++) {
const file = files[i];
let entitlements = getEntitlements(file);
entitlements = updateEntitlements(entitlements, preferences);
setEntitlements(file, entitlements);
}
}
|
[
"function",
"addAssociatedDomains",
"(",
"preferences",
")",
"{",
"const",
"files",
"=",
"getEntitlementFiles",
"(",
"preferences",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"files",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"file",
"=",
"files",
"[",
"i",
"]",
";",
"let",
"entitlements",
"=",
"getEntitlements",
"(",
"file",
")",
";",
"entitlements",
"=",
"updateEntitlements",
"(",
"entitlements",
",",
"preferences",
")",
";",
"setEntitlements",
"(",
"file",
",",
"entitlements",
")",
";",
"}",
"}"
] |
updates the associated domains from the link-domain field of the app's config.xml
|
[
"updates",
"the",
"associated",
"domains",
"from",
"the",
"link",
"-",
"domain",
"field",
"of",
"the",
"app",
"s",
"config",
".",
"xml"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/scripts/ios/updateAssociatedDomains.js#L17-L27
|
13,502
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/scripts/ios/updateAssociatedDomains.js
|
getEntitlementFiles
|
function getEntitlementFiles(preferences) {
const files = [];
const entitlements = path.join(
preferences.projectRoot,
"platforms",
"ios",
preferences.projectName,
"Resources",
`${preferences.projectName}.entitlements`
);
files.push(
path.join(
preferences.projectRoot,
"platforms",
"ios",
preferences.projectName,
`${preferences.projectName}.entitlements`
)
);
files.push(entitlements);
for (let i = 0; i < BUILD_TYPES.length; i++) {
const buildType = BUILD_TYPES[i];
const plist = path.join(
preferences.projectRoot,
"platforms",
"ios",
preferences.projectName,
`Entitlements-${buildType}.plist`
);
files.push(plist);
}
return files;
}
|
javascript
|
function getEntitlementFiles(preferences) {
const files = [];
const entitlements = path.join(
preferences.projectRoot,
"platforms",
"ios",
preferences.projectName,
"Resources",
`${preferences.projectName}.entitlements`
);
files.push(
path.join(
preferences.projectRoot,
"platforms",
"ios",
preferences.projectName,
`${preferences.projectName}.entitlements`
)
);
files.push(entitlements);
for (let i = 0; i < BUILD_TYPES.length; i++) {
const buildType = BUILD_TYPES[i];
const plist = path.join(
preferences.projectRoot,
"platforms",
"ios",
preferences.projectName,
`Entitlements-${buildType}.plist`
);
files.push(plist);
}
return files;
}
|
[
"function",
"getEntitlementFiles",
"(",
"preferences",
")",
"{",
"const",
"files",
"=",
"[",
"]",
";",
"const",
"entitlements",
"=",
"path",
".",
"join",
"(",
"preferences",
".",
"projectRoot",
",",
"\"platforms\"",
",",
"\"ios\"",
",",
"preferences",
".",
"projectName",
",",
"\"Resources\"",
",",
"`",
"${",
"preferences",
".",
"projectName",
"}",
"`",
")",
";",
"files",
".",
"push",
"(",
"path",
".",
"join",
"(",
"preferences",
".",
"projectRoot",
",",
"\"platforms\"",
",",
"\"ios\"",
",",
"preferences",
".",
"projectName",
",",
"`",
"${",
"preferences",
".",
"projectName",
"}",
"`",
")",
")",
";",
"files",
".",
"push",
"(",
"entitlements",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"BUILD_TYPES",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"buildType",
"=",
"BUILD_TYPES",
"[",
"i",
"]",
";",
"const",
"plist",
"=",
"path",
".",
"join",
"(",
"preferences",
".",
"projectRoot",
",",
"\"platforms\"",
",",
"\"ios\"",
",",
"preferences",
".",
"projectName",
",",
"`",
"${",
"buildType",
"}",
"`",
")",
";",
"files",
".",
"push",
"(",
"plist",
")",
";",
"}",
"return",
"files",
";",
"}"
] |
get the xcode .entitlements and provisioning profile .plist
|
[
"get",
"the",
"xcode",
".",
"entitlements",
"and",
"provisioning",
"profile",
".",
"plist"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/scripts/ios/updateAssociatedDomains.js#L30-L64
|
13,503
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/scripts/ios/updateAssociatedDomains.js
|
updateAssociatedDomains
|
function updateAssociatedDomains(preferences) {
const domainList = [];
const prefix = "applinks:";
const linkDomains = preferences.linkDomain;
for (let i = 0; i < linkDomains.length; i++) {
const linkDomain = linkDomains[i];
// add link domain to associated domain
domainList.push(prefix + linkDomain);
// app.link link domains need -alternate associated domains as well (for Deep Views)
if (linkDomain.indexOf("app.link") !== -1) {
const first = linkDomain.split(".")[0];
const second = linkDomain.split(".")[1];
const rest = linkDomain
.split(".")
.slice(2)
.join(".");
const alternate = `${first}-alternate`;
domainList.push(`${prefix + alternate}.${second}.${rest}`);
}
}
return domainList;
}
|
javascript
|
function updateAssociatedDomains(preferences) {
const domainList = [];
const prefix = "applinks:";
const linkDomains = preferences.linkDomain;
for (let i = 0; i < linkDomains.length; i++) {
const linkDomain = linkDomains[i];
// add link domain to associated domain
domainList.push(prefix + linkDomain);
// app.link link domains need -alternate associated domains as well (for Deep Views)
if (linkDomain.indexOf("app.link") !== -1) {
const first = linkDomain.split(".")[0];
const second = linkDomain.split(".")[1];
const rest = linkDomain
.split(".")
.slice(2)
.join(".");
const alternate = `${first}-alternate`;
domainList.push(`${prefix + alternate}.${second}.${rest}`);
}
}
return domainList;
}
|
[
"function",
"updateAssociatedDomains",
"(",
"preferences",
")",
"{",
"const",
"domainList",
"=",
"[",
"]",
";",
"const",
"prefix",
"=",
"\"applinks:\"",
";",
"const",
"linkDomains",
"=",
"preferences",
".",
"linkDomain",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"linkDomains",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"linkDomain",
"=",
"linkDomains",
"[",
"i",
"]",
";",
"// add link domain to associated domain",
"domainList",
".",
"push",
"(",
"prefix",
"+",
"linkDomain",
")",
";",
"// app.link link domains need -alternate associated domains as well (for Deep Views)",
"if",
"(",
"linkDomain",
".",
"indexOf",
"(",
"\"app.link\"",
")",
"!==",
"-",
"1",
")",
"{",
"const",
"first",
"=",
"linkDomain",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]",
";",
"const",
"second",
"=",
"linkDomain",
".",
"split",
"(",
"\".\"",
")",
"[",
"1",
"]",
";",
"const",
"rest",
"=",
"linkDomain",
".",
"split",
"(",
"\".\"",
")",
".",
"slice",
"(",
"2",
")",
".",
"join",
"(",
"\".\"",
")",
";",
"const",
"alternate",
"=",
"`",
"${",
"first",
"}",
"`",
";",
"domainList",
".",
"push",
"(",
"`",
"${",
"prefix",
"+",
"alternate",
"}",
"${",
"second",
"}",
"${",
"rest",
"}",
"`",
")",
";",
"}",
"}",
"return",
"domainList",
";",
"}"
] |
determine which Branch Link Domains to append
|
[
"determine",
"which",
"Branch",
"Link",
"Domains",
"to",
"append"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/scripts/ios/updateAssociatedDomains.js#L138-L164
|
13,504
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/phonegap1/plugins/cordova-plugin-camera/src/windows/CameraProxy.js
|
function () {
window.removeEventListener("focus", savePhotoOnFocus);
// call only when the app is in focus again
savePhoto(cameraPicture, {
destinationType: destinationType,
targetHeight: targetHeight,
targetWidth: targetWidth,
encodingType: encodingType,
saveToPhotoAlbum: saveToPhotoAlbum
}, successCallback, errorCallback);
}
|
javascript
|
function () {
window.removeEventListener("focus", savePhotoOnFocus);
// call only when the app is in focus again
savePhoto(cameraPicture, {
destinationType: destinationType,
targetHeight: targetHeight,
targetWidth: targetWidth,
encodingType: encodingType,
saveToPhotoAlbum: saveToPhotoAlbum
}, successCallback, errorCallback);
}
|
[
"function",
"(",
")",
"{",
"window",
".",
"removeEventListener",
"(",
"\"focus\"",
",",
"savePhotoOnFocus",
")",
";",
"// call only when the app is in focus again",
"savePhoto",
"(",
"cameraPicture",
",",
"{",
"destinationType",
":",
"destinationType",
",",
"targetHeight",
":",
"targetHeight",
",",
"targetWidth",
":",
"targetWidth",
",",
"encodingType",
":",
"encodingType",
",",
"saveToPhotoAlbum",
":",
"saveToPhotoAlbum",
"}",
",",
"successCallback",
",",
"errorCallback",
")",
";",
"}"
] |
define focus handler for windows phone 10.0
|
[
"define",
"focus",
"handler",
"for",
"windows",
"phone",
"10",
".",
"0"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/phonegap1/plugins/cordova-plugin-camera/src/windows/CameraProxy.js#L754-L764
|
|
13,505
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/platforms/android/cordova/lib/check_reqs.js
|
function (id, name, version, installed) {
this.id = id;
this.name = name;
this.installed = installed || false;
this.metadata = {
version: version
};
}
|
javascript
|
function (id, name, version, installed) {
this.id = id;
this.name = name;
this.installed = installed || false;
this.metadata = {
version: version
};
}
|
[
"function",
"(",
"id",
",",
"name",
",",
"version",
",",
"installed",
")",
"{",
"this",
".",
"id",
"=",
"id",
";",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"installed",
"=",
"installed",
"||",
"false",
";",
"this",
".",
"metadata",
"=",
"{",
"version",
":",
"version",
"}",
";",
"}"
] |
Object thar represents one of requirements for current platform.
@param {String} id The unique identifier for this requirements.
@param {String} name The name of requirements. Human-readable field.
@param {String} version The version of requirement installed. In some cases could be an array of strings
(for example, check_android_target returns an array of android targets installed)
@param {Boolean} installed Indicates whether the requirement is installed or not
|
[
"Object",
"thar",
"represents",
"one",
"of",
"requirements",
"for",
"current",
"platform",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/platforms/android/cordova/lib/check_reqs.js#L387-L394
|
|
13,506
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/platforms/android/platform_www/cordova.js
|
function (type, data, bNoDetach) {
var evt = createEvent(type, data);
if (typeof documentEventHandlers[type] !== 'undefined') {
if (bNoDetach) {
documentEventHandlers[type].fire(evt);
} else {
setTimeout(function () {
// Fire deviceready on listeners that were registered before cordova.js was loaded.
if (type === 'deviceready') {
document.dispatchEvent(evt);
}
documentEventHandlers[type].fire(evt);
}, 0);
}
} else {
document.dispatchEvent(evt);
}
}
|
javascript
|
function (type, data, bNoDetach) {
var evt = createEvent(type, data);
if (typeof documentEventHandlers[type] !== 'undefined') {
if (bNoDetach) {
documentEventHandlers[type].fire(evt);
} else {
setTimeout(function () {
// Fire deviceready on listeners that were registered before cordova.js was loaded.
if (type === 'deviceready') {
document.dispatchEvent(evt);
}
documentEventHandlers[type].fire(evt);
}, 0);
}
} else {
document.dispatchEvent(evt);
}
}
|
[
"function",
"(",
"type",
",",
"data",
",",
"bNoDetach",
")",
"{",
"var",
"evt",
"=",
"createEvent",
"(",
"type",
",",
"data",
")",
";",
"if",
"(",
"typeof",
"documentEventHandlers",
"[",
"type",
"]",
"!==",
"'undefined'",
")",
"{",
"if",
"(",
"bNoDetach",
")",
"{",
"documentEventHandlers",
"[",
"type",
"]",
".",
"fire",
"(",
"evt",
")",
";",
"}",
"else",
"{",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"// Fire deviceready on listeners that were registered before cordova.js was loaded.",
"if",
"(",
"type",
"===",
"'deviceready'",
")",
"{",
"document",
".",
"dispatchEvent",
"(",
"evt",
")",
";",
"}",
"documentEventHandlers",
"[",
"type",
"]",
".",
"fire",
"(",
"evt",
")",
";",
"}",
",",
"0",
")",
";",
"}",
"}",
"else",
"{",
"document",
".",
"dispatchEvent",
"(",
"evt",
")",
";",
"}",
"}"
] |
Method to fire event from native code
bNoDetach is required for events which cause an exception which needs to be caught in native code
|
[
"Method",
"to",
"fire",
"event",
"from",
"native",
"code",
"bNoDetach",
"is",
"required",
"for",
"events",
"which",
"cause",
"an",
"exception",
"which",
"needs",
"to",
"be",
"caught",
"in",
"native",
"code"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/platforms/android/platform_www/cordova.js#L218-L235
|
|
13,507
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/platforms/android/platform_www/cordova.js
|
function (callbackId, args) {
cordova.callbackFromNative(callbackId, true, args.status, [args.message], args.keepCallback);
}
|
javascript
|
function (callbackId, args) {
cordova.callbackFromNative(callbackId, true, args.status, [args.message], args.keepCallback);
}
|
[
"function",
"(",
"callbackId",
",",
"args",
")",
"{",
"cordova",
".",
"callbackFromNative",
"(",
"callbackId",
",",
"true",
",",
"args",
".",
"status",
",",
"[",
"args",
".",
"message",
"]",
",",
"args",
".",
"keepCallback",
")",
";",
"}"
] |
Called by native code when returning successful result from an action.
|
[
"Called",
"by",
"native",
"code",
"when",
"returning",
"successful",
"result",
"from",
"an",
"action",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/platforms/android/platform_www/cordova.js#L270-L272
|
|
13,508
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/platforms/android/platform_www/cordova.js
|
function (callbackId, args) {
// TODO: Deprecate callbackSuccess and callbackError in favour of callbackFromNative.
// Derive success from status.
cordova.callbackFromNative(callbackId, false, args.status, [args.message], args.keepCallback);
}
|
javascript
|
function (callbackId, args) {
// TODO: Deprecate callbackSuccess and callbackError in favour of callbackFromNative.
// Derive success from status.
cordova.callbackFromNative(callbackId, false, args.status, [args.message], args.keepCallback);
}
|
[
"function",
"(",
"callbackId",
",",
"args",
")",
"{",
"// TODO: Deprecate callbackSuccess and callbackError in favour of callbackFromNative.",
"// Derive success from status.",
"cordova",
".",
"callbackFromNative",
"(",
"callbackId",
",",
"false",
",",
"args",
".",
"status",
",",
"[",
"args",
".",
"message",
"]",
",",
"args",
".",
"keepCallback",
")",
";",
"}"
] |
Called by native code when returning error result from an action.
|
[
"Called",
"by",
"native",
"code",
"when",
"returning",
"error",
"result",
"from",
"an",
"action",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/platforms/android/platform_www/cordova.js#L277-L281
|
|
13,509
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/platforms/android/platform_www/cordova.js
|
recursiveMerge
|
function recursiveMerge (target, src) {
for (var prop in src) {
if (src.hasOwnProperty(prop)) {
if (target.prototype && target.prototype.constructor === target) {
// If the target object is a constructor override off prototype.
clobber(target.prototype, prop, src[prop]);
} else {
if (typeof src[prop] === 'object' && typeof target[prop] === 'object') {
recursiveMerge(target[prop], src[prop]);
} else {
clobber(target, prop, src[prop]);
}
}
}
}
}
|
javascript
|
function recursiveMerge (target, src) {
for (var prop in src) {
if (src.hasOwnProperty(prop)) {
if (target.prototype && target.prototype.constructor === target) {
// If the target object is a constructor override off prototype.
clobber(target.prototype, prop, src[prop]);
} else {
if (typeof src[prop] === 'object' && typeof target[prop] === 'object') {
recursiveMerge(target[prop], src[prop]);
} else {
clobber(target, prop, src[prop]);
}
}
}
}
}
|
[
"function",
"recursiveMerge",
"(",
"target",
",",
"src",
")",
"{",
"for",
"(",
"var",
"prop",
"in",
"src",
")",
"{",
"if",
"(",
"src",
".",
"hasOwnProperty",
"(",
"prop",
")",
")",
"{",
"if",
"(",
"target",
".",
"prototype",
"&&",
"target",
".",
"prototype",
".",
"constructor",
"===",
"target",
")",
"{",
"// If the target object is a constructor override off prototype.",
"clobber",
"(",
"target",
".",
"prototype",
",",
"prop",
",",
"src",
"[",
"prop",
"]",
")",
";",
"}",
"else",
"{",
"if",
"(",
"typeof",
"src",
"[",
"prop",
"]",
"===",
"'object'",
"&&",
"typeof",
"target",
"[",
"prop",
"]",
"===",
"'object'",
")",
"{",
"recursiveMerge",
"(",
"target",
"[",
"prop",
"]",
",",
"src",
"[",
"prop",
"]",
")",
";",
"}",
"else",
"{",
"clobber",
"(",
"target",
",",
"prop",
",",
"src",
"[",
"prop",
"]",
")",
";",
"}",
"}",
"}",
"}",
"}"
] |
Merge properties from one object onto another recursively. Properties from
the src object will overwrite existing target property.
@param target Object to merge properties into.
@param src Object to merge properties from.
|
[
"Merge",
"properties",
"from",
"one",
"object",
"onto",
"another",
"recursively",
".",
"Properties",
"from",
"the",
"src",
"object",
"will",
"overwrite",
"existing",
"target",
"property",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/platforms/android/platform_www/cordova.js#L590-L605
|
13,510
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/platforms/android/platform_www/cordova.js
|
function (type, sticky) {
this.type = type;
// Map of guid -> function.
this.handlers = {};
// 0 = Non-sticky, 1 = Sticky non-fired, 2 = Sticky fired.
this.state = sticky ? 1 : 0;
// Used in sticky mode to remember args passed to fire().
this.fireArgs = null;
// Used by onHasSubscribersChange to know if there are any listeners.
this.numHandlers = 0;
// Function that is called when the first listener is subscribed, or when
// the last listener is unsubscribed.
this.onHasSubscribersChange = null;
}
|
javascript
|
function (type, sticky) {
this.type = type;
// Map of guid -> function.
this.handlers = {};
// 0 = Non-sticky, 1 = Sticky non-fired, 2 = Sticky fired.
this.state = sticky ? 1 : 0;
// Used in sticky mode to remember args passed to fire().
this.fireArgs = null;
// Used by onHasSubscribersChange to know if there are any listeners.
this.numHandlers = 0;
// Function that is called when the first listener is subscribed, or when
// the last listener is unsubscribed.
this.onHasSubscribersChange = null;
}
|
[
"function",
"(",
"type",
",",
"sticky",
")",
"{",
"this",
".",
"type",
"=",
"type",
";",
"// Map of guid -> function.",
"this",
".",
"handlers",
"=",
"{",
"}",
";",
"// 0 = Non-sticky, 1 = Sticky non-fired, 2 = Sticky fired.",
"this",
".",
"state",
"=",
"sticky",
"?",
"1",
":",
"0",
";",
"// Used in sticky mode to remember args passed to fire().",
"this",
".",
"fireArgs",
"=",
"null",
";",
"// Used by onHasSubscribersChange to know if there are any listeners.",
"this",
".",
"numHandlers",
"=",
"0",
";",
"// Function that is called when the first listener is subscribed, or when",
"// the last listener is unsubscribed.",
"this",
".",
"onHasSubscribersChange",
"=",
"null",
";",
"}"
] |
Custom pub-sub "channel" that can have functions subscribed to it
This object is used to define and control firing of events for
cordova initialization, as well as for custom events thereafter.
The order of events during page load and Cordova startup is as follows:
onDOMContentLoaded* Internal event that is received when the web page is loaded and parsed.
onNativeReady* Internal event that indicates the Cordova native side is ready.
onCordovaReady* Internal event fired when all Cordova JavaScript objects have been created.
onDeviceReady* User event fired to indicate that Cordova is ready
onResume User event fired to indicate a start/resume lifecycle event
onPause User event fired to indicate a pause lifecycle event
The events marked with an * are sticky. Once they have fired, they will stay in the fired state.
All listeners that subscribe after the event is fired will be executed right away.
The only Cordova events that user code should register for are:
deviceready Cordova native code is initialized and Cordova APIs can be called from JavaScript
pause App has moved to background
resume App has returned to foreground
Listeners can be registered as:
document.addEventListener("deviceready", myDeviceReadyListener, false);
document.addEventListener("resume", myResumeListener, false);
document.addEventListener("pause", myPauseListener, false);
The DOM lifecycle events should be used for saving and restoring state
window.onload
window.onunload
Channel
@constructor
@param type String the channel name
|
[
"Custom",
"pub",
"-",
"sub",
"channel",
"that",
"can",
"have",
"functions",
"subscribed",
"to",
"it",
"This",
"object",
"is",
"used",
"to",
"define",
"and",
"control",
"firing",
"of",
"events",
"for",
"cordova",
"initialization",
"as",
"well",
"as",
"for",
"custom",
"events",
"thereafter",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/platforms/android/platform_www/cordova.js#L666-L679
|
|
13,511
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/platforms/android/platform_www/cordova.js
|
function (h, c) {
var len = c.length;
var i = len;
var f = function () {
if (!(--i)) h();
};
for (var j = 0; j < len; j++) {
if (c[j].state === 0) {
throw Error('Can only use join with sticky channels.');
}
c[j].subscribe(f);
}
if (!len) h();
}
|
javascript
|
function (h, c) {
var len = c.length;
var i = len;
var f = function () {
if (!(--i)) h();
};
for (var j = 0; j < len; j++) {
if (c[j].state === 0) {
throw Error('Can only use join with sticky channels.');
}
c[j].subscribe(f);
}
if (!len) h();
}
|
[
"function",
"(",
"h",
",",
"c",
")",
"{",
"var",
"len",
"=",
"c",
".",
"length",
";",
"var",
"i",
"=",
"len",
";",
"var",
"f",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"(",
"--",
"i",
")",
")",
"h",
"(",
")",
";",
"}",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"len",
";",
"j",
"++",
")",
"{",
"if",
"(",
"c",
"[",
"j",
"]",
".",
"state",
"===",
"0",
")",
"{",
"throw",
"Error",
"(",
"'Can only use join with sticky channels.'",
")",
";",
"}",
"c",
"[",
"j",
"]",
".",
"subscribe",
"(",
"f",
")",
";",
"}",
"if",
"(",
"!",
"len",
")",
"h",
"(",
")",
";",
"}"
] |
Calls the provided function only after all of the channels specified
have been fired. All channels must be sticky channels.
|
[
"Calls",
"the",
"provided",
"function",
"only",
"after",
"all",
"of",
"the",
"channels",
"specified",
"have",
"been",
"fired",
".",
"All",
"channels",
"must",
"be",
"sticky",
"channels",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/platforms/android/platform_www/cordova.js#L685-L698
|
|
13,512
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/platforms/android/platform_www/cordova.js
|
handlePluginsObject
|
function handlePluginsObject (moduleList) {
// if moduleList is not defined or empty, we've nothing to do
if (!moduleList || !moduleList.length) {
return;
}
// Loop through all the modules and then through their clobbers and merges.
for (var i = 0, module; module = moduleList[i]; i++) { // eslint-disable-line no-cond-assign
if (module.clobbers && module.clobbers.length) {
for (var j = 0; j < module.clobbers.length; j++) {
modulemapper.clobbers(module.id, module.clobbers[j]);
}
}
if (module.merges && module.merges.length) {
for (var k = 0; k < module.merges.length; k++) {
modulemapper.merges(module.id, module.merges[k]);
}
}
// Finally, if runs is truthy we want to simply require() the module.
if (module.runs) {
modulemapper.runs(module.id);
}
}
}
|
javascript
|
function handlePluginsObject (moduleList) {
// if moduleList is not defined or empty, we've nothing to do
if (!moduleList || !moduleList.length) {
return;
}
// Loop through all the modules and then through their clobbers and merges.
for (var i = 0, module; module = moduleList[i]; i++) { // eslint-disable-line no-cond-assign
if (module.clobbers && module.clobbers.length) {
for (var j = 0; j < module.clobbers.length; j++) {
modulemapper.clobbers(module.id, module.clobbers[j]);
}
}
if (module.merges && module.merges.length) {
for (var k = 0; k < module.merges.length; k++) {
modulemapper.merges(module.id, module.merges[k]);
}
}
// Finally, if runs is truthy we want to simply require() the module.
if (module.runs) {
modulemapper.runs(module.id);
}
}
}
|
[
"function",
"handlePluginsObject",
"(",
"moduleList",
")",
"{",
"// if moduleList is not defined or empty, we've nothing to do",
"if",
"(",
"!",
"moduleList",
"||",
"!",
"moduleList",
".",
"length",
")",
"{",
"return",
";",
"}",
"// Loop through all the modules and then through their clobbers and merges.",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"module",
";",
"module",
"=",
"moduleList",
"[",
"i",
"]",
";",
"i",
"++",
")",
"{",
"// eslint-disable-line no-cond-assign",
"if",
"(",
"module",
".",
"clobbers",
"&&",
"module",
".",
"clobbers",
".",
"length",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"module",
".",
"clobbers",
".",
"length",
";",
"j",
"++",
")",
"{",
"modulemapper",
".",
"clobbers",
"(",
"module",
".",
"id",
",",
"module",
".",
"clobbers",
"[",
"j",
"]",
")",
";",
"}",
"}",
"if",
"(",
"module",
".",
"merges",
"&&",
"module",
".",
"merges",
".",
"length",
")",
"{",
"for",
"(",
"var",
"k",
"=",
"0",
";",
"k",
"<",
"module",
".",
"merges",
".",
"length",
";",
"k",
"++",
")",
"{",
"modulemapper",
".",
"merges",
"(",
"module",
".",
"id",
",",
"module",
".",
"merges",
"[",
"k",
"]",
")",
";",
"}",
"}",
"// Finally, if runs is truthy we want to simply require() the module.",
"if",
"(",
"module",
".",
"runs",
")",
"{",
"modulemapper",
".",
"runs",
"(",
"module",
".",
"id",
")",
";",
"}",
"}",
"}"
] |
Handler for the cordova_plugins.js content. See plugman's plugin_loader.js for the details of this object.
|
[
"Handler",
"for",
"the",
"cordova_plugins",
".",
"js",
"content",
".",
"See",
"plugman",
"s",
"plugin_loader",
".",
"js",
"for",
"the",
"details",
"of",
"this",
"object",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/platforms/android/platform_www/cordova.js#L1962-L1987
|
13,513
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/phonegap1/plugins/cordova-plugin-dialogs/src/windows/NotificationProxy.js
|
createPromptDialog
|
function createPromptDialog (title, message, buttons, defaultText, callback) {
var isPhone = cordova.platformId === 'windows' && WinJS.Utilities.isPhone;
var isWindows = !!cordova.platformId.match(/windows/);
createCSSElem('notification.css');
var dlgWrap = document.createElement('div');
dlgWrap.className = 'dlgWrap';
var dlg = document.createElement('div');
dlg.className = 'dlgContainer';
if (isWindows) {
dlg.className += ' dlgContainer-windows';
} else if (isPhone) {
dlg.className += ' dlgContainer-phone';
}
// dialog layout template
dlg.innerHTML = _cleanHtml("<span id='lbl-title'></span><br/>" + // title
"<span id='lbl-message'></span><br/>" + // message
"<input id='prompt-input'/><br/>"); // input fields
dlg.querySelector('#lbl-title').appendChild(document.createTextNode(title));
dlg.querySelector('#lbl-message').appendChild(document.createTextNode(message));
dlg.querySelector('#prompt-input').setAttribute('placeholder', defaultText);
dlg.querySelector('#prompt-input').setAttribute('value', defaultText);
function makeButtonCallback (idx) {
return function () {
var value = dlg.querySelector('#prompt-input').value || defaultText;
dlgWrap.parentNode.removeChild(dlgWrap);
if (callback) {
callback({ input1: value, buttonIndex: idx }); // eslint-disable-line standard/no-callback-literal
}
};
}
function addButton (idx, label) {
var button = document.createElement('button');
button.className = 'dlgButton';
button.tabIndex = idx;
button.onclick = makeButtonCallback(idx + 1);
if (idx === 0) {
button.className += ' dlgButtonFirst';
}
button.appendChild(document.createTextNode(label));
dlg.appendChild(button);
}
// reverse order is used since we align buttons to the right
for (var idx = buttons.length - 1; idx >= 0; idx--) {
addButton(idx, buttons[idx]);
}
dlgWrap.appendChild(dlg);
document.body.appendChild(dlgWrap);
// make sure input field is under focus
dlg.querySelector('#prompt-input').select();
// add Enter/Return key handling
var defaultButton = dlg.querySelector('.dlgButtonFirst');
dlg.addEventListener('keypress', function (e) {
if (e.keyCode === 13) { // enter key
if (defaultButton) {
defaultButton.click();
}
}
});
return dlgWrap;
}
|
javascript
|
function createPromptDialog (title, message, buttons, defaultText, callback) {
var isPhone = cordova.platformId === 'windows' && WinJS.Utilities.isPhone;
var isWindows = !!cordova.platformId.match(/windows/);
createCSSElem('notification.css');
var dlgWrap = document.createElement('div');
dlgWrap.className = 'dlgWrap';
var dlg = document.createElement('div');
dlg.className = 'dlgContainer';
if (isWindows) {
dlg.className += ' dlgContainer-windows';
} else if (isPhone) {
dlg.className += ' dlgContainer-phone';
}
// dialog layout template
dlg.innerHTML = _cleanHtml("<span id='lbl-title'></span><br/>" + // title
"<span id='lbl-message'></span><br/>" + // message
"<input id='prompt-input'/><br/>"); // input fields
dlg.querySelector('#lbl-title').appendChild(document.createTextNode(title));
dlg.querySelector('#lbl-message').appendChild(document.createTextNode(message));
dlg.querySelector('#prompt-input').setAttribute('placeholder', defaultText);
dlg.querySelector('#prompt-input').setAttribute('value', defaultText);
function makeButtonCallback (idx) {
return function () {
var value = dlg.querySelector('#prompt-input').value || defaultText;
dlgWrap.parentNode.removeChild(dlgWrap);
if (callback) {
callback({ input1: value, buttonIndex: idx }); // eslint-disable-line standard/no-callback-literal
}
};
}
function addButton (idx, label) {
var button = document.createElement('button');
button.className = 'dlgButton';
button.tabIndex = idx;
button.onclick = makeButtonCallback(idx + 1);
if (idx === 0) {
button.className += ' dlgButtonFirst';
}
button.appendChild(document.createTextNode(label));
dlg.appendChild(button);
}
// reverse order is used since we align buttons to the right
for (var idx = buttons.length - 1; idx >= 0; idx--) {
addButton(idx, buttons[idx]);
}
dlgWrap.appendChild(dlg);
document.body.appendChild(dlgWrap);
// make sure input field is under focus
dlg.querySelector('#prompt-input').select();
// add Enter/Return key handling
var defaultButton = dlg.querySelector('.dlgButtonFirst');
dlg.addEventListener('keypress', function (e) {
if (e.keyCode === 13) { // enter key
if (defaultButton) {
defaultButton.click();
}
}
});
return dlgWrap;
}
|
[
"function",
"createPromptDialog",
"(",
"title",
",",
"message",
",",
"buttons",
",",
"defaultText",
",",
"callback",
")",
"{",
"var",
"isPhone",
"=",
"cordova",
".",
"platformId",
"===",
"'windows'",
"&&",
"WinJS",
".",
"Utilities",
".",
"isPhone",
";",
"var",
"isWindows",
"=",
"!",
"!",
"cordova",
".",
"platformId",
".",
"match",
"(",
"/",
"windows",
"/",
")",
";",
"createCSSElem",
"(",
"'notification.css'",
")",
";",
"var",
"dlgWrap",
"=",
"document",
".",
"createElement",
"(",
"'div'",
")",
";",
"dlgWrap",
".",
"className",
"=",
"'dlgWrap'",
";",
"var",
"dlg",
"=",
"document",
".",
"createElement",
"(",
"'div'",
")",
";",
"dlg",
".",
"className",
"=",
"'dlgContainer'",
";",
"if",
"(",
"isWindows",
")",
"{",
"dlg",
".",
"className",
"+=",
"' dlgContainer-windows'",
";",
"}",
"else",
"if",
"(",
"isPhone",
")",
"{",
"dlg",
".",
"className",
"+=",
"' dlgContainer-phone'",
";",
"}",
"// dialog layout template",
"dlg",
".",
"innerHTML",
"=",
"_cleanHtml",
"(",
"\"<span id='lbl-title'></span><br/>\"",
"+",
"// title",
"\"<span id='lbl-message'></span><br/>\"",
"+",
"// message",
"\"<input id='prompt-input'/><br/>\"",
")",
";",
"// input fields",
"dlg",
".",
"querySelector",
"(",
"'#lbl-title'",
")",
".",
"appendChild",
"(",
"document",
".",
"createTextNode",
"(",
"title",
")",
")",
";",
"dlg",
".",
"querySelector",
"(",
"'#lbl-message'",
")",
".",
"appendChild",
"(",
"document",
".",
"createTextNode",
"(",
"message",
")",
")",
";",
"dlg",
".",
"querySelector",
"(",
"'#prompt-input'",
")",
".",
"setAttribute",
"(",
"'placeholder'",
",",
"defaultText",
")",
";",
"dlg",
".",
"querySelector",
"(",
"'#prompt-input'",
")",
".",
"setAttribute",
"(",
"'value'",
",",
"defaultText",
")",
";",
"function",
"makeButtonCallback",
"(",
"idx",
")",
"{",
"return",
"function",
"(",
")",
"{",
"var",
"value",
"=",
"dlg",
".",
"querySelector",
"(",
"'#prompt-input'",
")",
".",
"value",
"||",
"defaultText",
";",
"dlgWrap",
".",
"parentNode",
".",
"removeChild",
"(",
"dlgWrap",
")",
";",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
"{",
"input1",
":",
"value",
",",
"buttonIndex",
":",
"idx",
"}",
")",
";",
"// eslint-disable-line standard/no-callback-literal",
"}",
"}",
";",
"}",
"function",
"addButton",
"(",
"idx",
",",
"label",
")",
"{",
"var",
"button",
"=",
"document",
".",
"createElement",
"(",
"'button'",
")",
";",
"button",
".",
"className",
"=",
"'dlgButton'",
";",
"button",
".",
"tabIndex",
"=",
"idx",
";",
"button",
".",
"onclick",
"=",
"makeButtonCallback",
"(",
"idx",
"+",
"1",
")",
";",
"if",
"(",
"idx",
"===",
"0",
")",
"{",
"button",
".",
"className",
"+=",
"' dlgButtonFirst'",
";",
"}",
"button",
".",
"appendChild",
"(",
"document",
".",
"createTextNode",
"(",
"label",
")",
")",
";",
"dlg",
".",
"appendChild",
"(",
"button",
")",
";",
"}",
"// reverse order is used since we align buttons to the right",
"for",
"(",
"var",
"idx",
"=",
"buttons",
".",
"length",
"-",
"1",
";",
"idx",
">=",
"0",
";",
"idx",
"--",
")",
"{",
"addButton",
"(",
"idx",
",",
"buttons",
"[",
"idx",
"]",
")",
";",
"}",
"dlgWrap",
".",
"appendChild",
"(",
"dlg",
")",
";",
"document",
".",
"body",
".",
"appendChild",
"(",
"dlgWrap",
")",
";",
"// make sure input field is under focus",
"dlg",
".",
"querySelector",
"(",
"'#prompt-input'",
")",
".",
"select",
"(",
")",
";",
"// add Enter/Return key handling",
"var",
"defaultButton",
"=",
"dlg",
".",
"querySelector",
"(",
"'.dlgButtonFirst'",
")",
";",
"dlg",
".",
"addEventListener",
"(",
"'keypress'",
",",
"function",
"(",
"e",
")",
"{",
"if",
"(",
"e",
".",
"keyCode",
"===",
"13",
")",
"{",
"// enter key",
"if",
"(",
"defaultButton",
")",
"{",
"defaultButton",
".",
"click",
"(",
")",
";",
"}",
"}",
"}",
")",
";",
"return",
"dlgWrap",
";",
"}"
] |
Windows does not provide native UI for promp dialog so we use some simple html-based implementation until it is available
|
[
"Windows",
"does",
"not",
"provide",
"native",
"UI",
"for",
"promp",
"dialog",
"so",
"we",
"use",
"some",
"simple",
"html",
"-",
"based",
"implementation",
"until",
"it",
"is",
"available"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/phonegap1/plugins/cordova-plugin-dialogs/src/windows/NotificationProxy.js#L56-L129
|
13,514
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/scripts/lib/xmlHelper.js
|
readXmlAsJson
|
function readXmlAsJson(file) {
let xmlData;
let xmlParser;
let parsedData;
try {
xmlData = fs.readFileSync(file);
xmlParser = new xml2js.Parser();
xmlParser.parseString(xmlData, (err, data) => {
if (!err && data) {
parsedData = data;
}
});
} catch (err) {
throw new Error(`BRANCH SDK: Cannot write file ${file}`);
}
return parsedData;
}
|
javascript
|
function readXmlAsJson(file) {
let xmlData;
let xmlParser;
let parsedData;
try {
xmlData = fs.readFileSync(file);
xmlParser = new xml2js.Parser();
xmlParser.parseString(xmlData, (err, data) => {
if (!err && data) {
parsedData = data;
}
});
} catch (err) {
throw new Error(`BRANCH SDK: Cannot write file ${file}`);
}
return parsedData;
}
|
[
"function",
"readXmlAsJson",
"(",
"file",
")",
"{",
"let",
"xmlData",
";",
"let",
"xmlParser",
";",
"let",
"parsedData",
";",
"try",
"{",
"xmlData",
"=",
"fs",
".",
"readFileSync",
"(",
"file",
")",
";",
"xmlParser",
"=",
"new",
"xml2js",
".",
"Parser",
"(",
")",
";",
"xmlParser",
".",
"parseString",
"(",
"xmlData",
",",
"(",
"err",
",",
"data",
")",
"=>",
"{",
"if",
"(",
"!",
"err",
"&&",
"data",
")",
"{",
"parsedData",
"=",
"data",
";",
"}",
"}",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"file",
"}",
"`",
")",
";",
"}",
"return",
"parsedData",
";",
"}"
] |
read from xml file
|
[
"read",
"from",
"xml",
"file"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/scripts/lib/xmlHelper.js#L14-L32
|
13,515
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/scripts/lib/xmlHelper.js
|
writeJsonAsXml
|
function writeJsonAsXml(file, content, options) {
const xmlBuilder = new xml2js.Builder(options);
const changedXmlData = xmlBuilder.buildObject(content);
let isSaved = true;
try {
fs.writeFileSync(file, changedXmlData);
} catch (err) {
isSaved = false;
throw new Error(`BRANCH SDK: Cannot write file ${file}`);
}
return isSaved;
}
|
javascript
|
function writeJsonAsXml(file, content, options) {
const xmlBuilder = new xml2js.Builder(options);
const changedXmlData = xmlBuilder.buildObject(content);
let isSaved = true;
try {
fs.writeFileSync(file, changedXmlData);
} catch (err) {
isSaved = false;
throw new Error(`BRANCH SDK: Cannot write file ${file}`);
}
return isSaved;
}
|
[
"function",
"writeJsonAsXml",
"(",
"file",
",",
"content",
",",
"options",
")",
"{",
"const",
"xmlBuilder",
"=",
"new",
"xml2js",
".",
"Builder",
"(",
"options",
")",
";",
"const",
"changedXmlData",
"=",
"xmlBuilder",
".",
"buildObject",
"(",
"content",
")",
";",
"let",
"isSaved",
"=",
"true",
";",
"try",
"{",
"fs",
".",
"writeFileSync",
"(",
"file",
",",
"changedXmlData",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"isSaved",
"=",
"false",
";",
"throw",
"new",
"Error",
"(",
"`",
"${",
"file",
"}",
"`",
")",
";",
"}",
"return",
"isSaved",
";",
"}"
] |
write to xml file
|
[
"write",
"to",
"xml",
"file"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/scripts/lib/xmlHelper.js#L35-L48
|
13,516
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/phonegap1/plugins/cordova-plugin-globalization/www/firefoxos/l10n_date.js
|
relativeParts
|
function relativeParts (seconds) {
seconds = Math.abs(seconds);
var descriptors = {};
var units = [
'years', 86400 * 365,
'months', 86400 * 30,
'weeks', 86400 * 7,
'days', 86400,
'hours', 3600,
'minutes', 60
];
if (seconds < 60) {
return {
minutes: Math.round(seconds / 60)
};
}
for (var i = 0, uLen = units.length; i < uLen; i += 2) {
var value = units[i + 1];
if (seconds >= value) {
descriptors[units[i]] = Math.floor(seconds / value);
seconds -= descriptors[units[i]] * value;
}
}
return descriptors;
}
|
javascript
|
function relativeParts (seconds) {
seconds = Math.abs(seconds);
var descriptors = {};
var units = [
'years', 86400 * 365,
'months', 86400 * 30,
'weeks', 86400 * 7,
'days', 86400,
'hours', 3600,
'minutes', 60
];
if (seconds < 60) {
return {
minutes: Math.round(seconds / 60)
};
}
for (var i = 0, uLen = units.length; i < uLen; i += 2) {
var value = units[i + 1];
if (seconds >= value) {
descriptors[units[i]] = Math.floor(seconds / value);
seconds -= descriptors[units[i]] * value;
}
}
return descriptors;
}
|
[
"function",
"relativeParts",
"(",
"seconds",
")",
"{",
"seconds",
"=",
"Math",
".",
"abs",
"(",
"seconds",
")",
";",
"var",
"descriptors",
"=",
"{",
"}",
";",
"var",
"units",
"=",
"[",
"'years'",
",",
"86400",
"*",
"365",
",",
"'months'",
",",
"86400",
"*",
"30",
",",
"'weeks'",
",",
"86400",
"*",
"7",
",",
"'days'",
",",
"86400",
",",
"'hours'",
",",
"3600",
",",
"'minutes'",
",",
"60",
"]",
";",
"if",
"(",
"seconds",
"<",
"60",
")",
"{",
"return",
"{",
"minutes",
":",
"Math",
".",
"round",
"(",
"seconds",
"/",
"60",
")",
"}",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"uLen",
"=",
"units",
".",
"length",
";",
"i",
"<",
"uLen",
";",
"i",
"+=",
"2",
")",
"{",
"var",
"value",
"=",
"units",
"[",
"i",
"+",
"1",
"]",
";",
"if",
"(",
"seconds",
">=",
"value",
")",
"{",
"descriptors",
"[",
"units",
"[",
"i",
"]",
"]",
"=",
"Math",
".",
"floor",
"(",
"seconds",
"/",
"value",
")",
";",
"seconds",
"-=",
"descriptors",
"[",
"units",
"[",
"i",
"]",
"]",
"*",
"value",
";",
"}",
"}",
"return",
"descriptors",
";",
"}"
] |
Returns the parts of a number of seconds
|
[
"Returns",
"the",
"parts",
"of",
"a",
"number",
"of",
"seconds"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/phonegap1/plugins/cordova-plugin-globalization/www/firefoxos/l10n_date.js#L110-L136
|
13,517
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/phonegap1/plugins/cordova-plugin-globalization/www/firefoxos/l10n_date.js
|
prettyDate
|
function prettyDate (time, useCompactFormat, maxDiff) {
maxDiff = maxDiff || 86400 * 10; // default = 10 days
switch (time.constructor) {
case String: // timestamp
time = parseInt(time);
break;
case Date:
time = time.getTime();
break;
}
var secDiff = (Date.now() - time) / 1000;
if (isNaN(secDiff)) {
return _('incorrectDate');
}
if (Math.abs(secDiff) > 60) {
// round milliseconds up if difference is over 1 minute so the result is
// closer to what the user would expect (1h59m59s300ms diff should return
// "in 2 hours" instead of "in an hour")
secDiff = secDiff > 0 ? Math.ceil(secDiff) : Math.floor(secDiff);
}
if (secDiff > maxDiff) {
return localeFormat(new Date(time), '%x');
}
var f = useCompactFormat ? '-short' : '-long';
var parts = relativeParts(secDiff);
var affix = secDiff >= 0 ? '-ago' : '-until';
for (var i in parts) {
return _(i + affix + f, { value: parts[i] });
}
}
|
javascript
|
function prettyDate (time, useCompactFormat, maxDiff) {
maxDiff = maxDiff || 86400 * 10; // default = 10 days
switch (time.constructor) {
case String: // timestamp
time = parseInt(time);
break;
case Date:
time = time.getTime();
break;
}
var secDiff = (Date.now() - time) / 1000;
if (isNaN(secDiff)) {
return _('incorrectDate');
}
if (Math.abs(secDiff) > 60) {
// round milliseconds up if difference is over 1 minute so the result is
// closer to what the user would expect (1h59m59s300ms diff should return
// "in 2 hours" instead of "in an hour")
secDiff = secDiff > 0 ? Math.ceil(secDiff) : Math.floor(secDiff);
}
if (secDiff > maxDiff) {
return localeFormat(new Date(time), '%x');
}
var f = useCompactFormat ? '-short' : '-long';
var parts = relativeParts(secDiff);
var affix = secDiff >= 0 ? '-ago' : '-until';
for (var i in parts) {
return _(i + affix + f, { value: parts[i] });
}
}
|
[
"function",
"prettyDate",
"(",
"time",
",",
"useCompactFormat",
",",
"maxDiff",
")",
"{",
"maxDiff",
"=",
"maxDiff",
"||",
"86400",
"*",
"10",
";",
"// default = 10 days",
"switch",
"(",
"time",
".",
"constructor",
")",
"{",
"case",
"String",
":",
"// timestamp",
"time",
"=",
"parseInt",
"(",
"time",
")",
";",
"break",
";",
"case",
"Date",
":",
"time",
"=",
"time",
".",
"getTime",
"(",
")",
";",
"break",
";",
"}",
"var",
"secDiff",
"=",
"(",
"Date",
".",
"now",
"(",
")",
"-",
"time",
")",
"/",
"1000",
";",
"if",
"(",
"isNaN",
"(",
"secDiff",
")",
")",
"{",
"return",
"_",
"(",
"'incorrectDate'",
")",
";",
"}",
"if",
"(",
"Math",
".",
"abs",
"(",
"secDiff",
")",
">",
"60",
")",
"{",
"// round milliseconds up if difference is over 1 minute so the result is",
"// closer to what the user would expect (1h59m59s300ms diff should return",
"// \"in 2 hours\" instead of \"in an hour\")",
"secDiff",
"=",
"secDiff",
">",
"0",
"?",
"Math",
".",
"ceil",
"(",
"secDiff",
")",
":",
"Math",
".",
"floor",
"(",
"secDiff",
")",
";",
"}",
"if",
"(",
"secDiff",
">",
"maxDiff",
")",
"{",
"return",
"localeFormat",
"(",
"new",
"Date",
"(",
"time",
")",
",",
"'%x'",
")",
";",
"}",
"var",
"f",
"=",
"useCompactFormat",
"?",
"'-short'",
":",
"'-long'",
";",
"var",
"parts",
"=",
"relativeParts",
"(",
"secDiff",
")",
";",
"var",
"affix",
"=",
"secDiff",
">=",
"0",
"?",
"'-ago'",
":",
"'-until'",
";",
"for",
"(",
"var",
"i",
"in",
"parts",
")",
"{",
"return",
"_",
"(",
"i",
"+",
"affix",
"+",
"f",
",",
"{",
"value",
":",
"parts",
"[",
"i",
"]",
"}",
")",
";",
"}",
"}"
] |
Returns a translated string which respresents the
relative time before or after a date.
@param {String|Date} time before/after the currentDate.
@param {String} useCompactFormat whether to use a compact display format.
@param {Number} maxDiff returns a formatted date if the diff is greater.
|
[
"Returns",
"a",
"translated",
"string",
"which",
"respresents",
"the",
"relative",
"time",
"before",
"or",
"after",
"a",
"date",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/phonegap1/plugins/cordova-plugin-globalization/www/firefoxos/l10n_date.js#L145-L180
|
13,518
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/phonegap1/plugins/cordova-plugin-file/www/blackberry10/resolveLocalFileSystemURI.js
|
resolve
|
function resolve(success, fail, path, fsType, sandbox, options, size) {
options = options || { create: false };
size = size || info.MAX_SIZE;
if (size > info.MAX_SIZE) {
//bb10 does not respect quota; fail at unreasonably large size
fail(FileError.QUOTA_EXCEEDED_ERR);
} else if (path.indexOf(':') > -1) {
//files with : character are not valid in Cordova apps
fail(FileError.ENCODING_ERR);
} else {
requestAnimationFrame(function () {
cordova.exec(function () {
requestAnimationFrame(function () {
resolveNative(success, fail, path, fsType, options, size);
});
}, fail, 'File', 'setSandbox', [sandbox], false);
});
}
}
|
javascript
|
function resolve(success, fail, path, fsType, sandbox, options, size) {
options = options || { create: false };
size = size || info.MAX_SIZE;
if (size > info.MAX_SIZE) {
//bb10 does not respect quota; fail at unreasonably large size
fail(FileError.QUOTA_EXCEEDED_ERR);
} else if (path.indexOf(':') > -1) {
//files with : character are not valid in Cordova apps
fail(FileError.ENCODING_ERR);
} else {
requestAnimationFrame(function () {
cordova.exec(function () {
requestAnimationFrame(function () {
resolveNative(success, fail, path, fsType, options, size);
});
}, fail, 'File', 'setSandbox', [sandbox], false);
});
}
}
|
[
"function",
"resolve",
"(",
"success",
",",
"fail",
",",
"path",
",",
"fsType",
",",
"sandbox",
",",
"options",
",",
"size",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"create",
":",
"false",
"}",
";",
"size",
"=",
"size",
"||",
"info",
".",
"MAX_SIZE",
";",
"if",
"(",
"size",
">",
"info",
".",
"MAX_SIZE",
")",
"{",
"//bb10 does not respect quota; fail at unreasonably large size",
"fail",
"(",
"FileError",
".",
"QUOTA_EXCEEDED_ERR",
")",
";",
"}",
"else",
"if",
"(",
"path",
".",
"indexOf",
"(",
"':'",
")",
">",
"-",
"1",
")",
"{",
"//files with : character are not valid in Cordova apps ",
"fail",
"(",
"FileError",
".",
"ENCODING_ERR",
")",
";",
"}",
"else",
"{",
"requestAnimationFrame",
"(",
"function",
"(",
")",
"{",
"cordova",
".",
"exec",
"(",
"function",
"(",
")",
"{",
"requestAnimationFrame",
"(",
"function",
"(",
")",
"{",
"resolveNative",
"(",
"success",
",",
"fail",
",",
"path",
",",
"fsType",
",",
"options",
",",
"size",
")",
";",
"}",
")",
";",
"}",
",",
"fail",
",",
"'File'",
",",
"'setSandbox'",
",",
"[",
"sandbox",
"]",
",",
"false",
")",
";",
"}",
")",
";",
"}",
"}"
] |
validate parameters and set sandbox
|
[
"validate",
"parameters",
"and",
"set",
"sandbox"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/phonegap1/plugins/cordova-plugin-file/www/blackberry10/resolveLocalFileSystemURI.js#L111-L129
|
13,519
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/phonegap1/plugins/cordova-plugin-file/www/blackberry10/resolveLocalFileSystemURI.js
|
resolveNative
|
function resolveNative(success, fail, path, fsType, options, size) {
window.webkitRequestFileSystem(
fsType,
size,
function (fs) {
if (path === '') {
//no path provided, call success with root file system
success(createEntryFromNative(fs.root));
} else {
//otherwise attempt to resolve as file
fs.root.getFile(
path,
options,
function (entry) {
success(createEntryFromNative(entry));
},
function (fileError) {
//file not found, attempt to resolve as directory
fs.root.getDirectory(
path,
options,
function (entry) {
success(createEntryFromNative(entry));
},
function (dirError) {
//path cannot be resolved
if (fileError.code === FileError.INVALID_MODIFICATION_ERR &&
options.exclusive) {
//mobile-spec expects this error code
fail(FileError.PATH_EXISTS_ERR);
} else {
fail(FileError.NOT_FOUND_ERR);
}
}
);
}
);
}
}
);
}
|
javascript
|
function resolveNative(success, fail, path, fsType, options, size) {
window.webkitRequestFileSystem(
fsType,
size,
function (fs) {
if (path === '') {
//no path provided, call success with root file system
success(createEntryFromNative(fs.root));
} else {
//otherwise attempt to resolve as file
fs.root.getFile(
path,
options,
function (entry) {
success(createEntryFromNative(entry));
},
function (fileError) {
//file not found, attempt to resolve as directory
fs.root.getDirectory(
path,
options,
function (entry) {
success(createEntryFromNative(entry));
},
function (dirError) {
//path cannot be resolved
if (fileError.code === FileError.INVALID_MODIFICATION_ERR &&
options.exclusive) {
//mobile-spec expects this error code
fail(FileError.PATH_EXISTS_ERR);
} else {
fail(FileError.NOT_FOUND_ERR);
}
}
);
}
);
}
}
);
}
|
[
"function",
"resolveNative",
"(",
"success",
",",
"fail",
",",
"path",
",",
"fsType",
",",
"options",
",",
"size",
")",
"{",
"window",
".",
"webkitRequestFileSystem",
"(",
"fsType",
",",
"size",
",",
"function",
"(",
"fs",
")",
"{",
"if",
"(",
"path",
"===",
"''",
")",
"{",
"//no path provided, call success with root file system",
"success",
"(",
"createEntryFromNative",
"(",
"fs",
".",
"root",
")",
")",
";",
"}",
"else",
"{",
"//otherwise attempt to resolve as file",
"fs",
".",
"root",
".",
"getFile",
"(",
"path",
",",
"options",
",",
"function",
"(",
"entry",
")",
"{",
"success",
"(",
"createEntryFromNative",
"(",
"entry",
")",
")",
";",
"}",
",",
"function",
"(",
"fileError",
")",
"{",
"//file not found, attempt to resolve as directory",
"fs",
".",
"root",
".",
"getDirectory",
"(",
"path",
",",
"options",
",",
"function",
"(",
"entry",
")",
"{",
"success",
"(",
"createEntryFromNative",
"(",
"entry",
")",
")",
";",
"}",
",",
"function",
"(",
"dirError",
")",
"{",
"//path cannot be resolved",
"if",
"(",
"fileError",
".",
"code",
"===",
"FileError",
".",
"INVALID_MODIFICATION_ERR",
"&&",
"options",
".",
"exclusive",
")",
"{",
"//mobile-spec expects this error code",
"fail",
"(",
"FileError",
".",
"PATH_EXISTS_ERR",
")",
";",
"}",
"else",
"{",
"fail",
"(",
"FileError",
".",
"NOT_FOUND_ERR",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] |
find path using webkit file system
|
[
"find",
"path",
"using",
"webkit",
"file",
"system"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/phonegap1/plugins/cordova-plugin-file/www/blackberry10/resolveLocalFileSystemURI.js#L132-L172
|
13,520
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/phonegap1/platforms/ios/www/plugins/cordova-plugin-vibration/www/vibration.js
|
function (pattern, repeat) {
repeat = (typeof repeat !== 'undefined') ? repeat : -1;
pattern = pattern.unshift(0); // add a 0 at beginning for backwards compatibility from w3c spec
exec(null, null, 'Vibration', 'vibrateWithPattern', [pattern, repeat]);
}
|
javascript
|
function (pattern, repeat) {
repeat = (typeof repeat !== 'undefined') ? repeat : -1;
pattern = pattern.unshift(0); // add a 0 at beginning for backwards compatibility from w3c spec
exec(null, null, 'Vibration', 'vibrateWithPattern', [pattern, repeat]);
}
|
[
"function",
"(",
"pattern",
",",
"repeat",
")",
"{",
"repeat",
"=",
"(",
"typeof",
"repeat",
"!==",
"'undefined'",
")",
"?",
"repeat",
":",
"-",
"1",
";",
"pattern",
"=",
"pattern",
".",
"unshift",
"(",
"0",
")",
";",
"// add a 0 at beginning for backwards compatibility from w3c spec",
"exec",
"(",
"null",
",",
"null",
",",
"'Vibration'",
",",
"'vibrateWithPattern'",
",",
"[",
"pattern",
",",
"repeat",
"]",
")",
";",
"}"
] |
Vibrates the device with a given pattern.
@param {Array of Integer} pattern Pattern with which to vibrate the device.
Pass in an array of integers that
are the durations for which to
turn on or off the vibrator in
milliseconds. The first value
indicates the number of milliseconds
to wait before turning the vibrator
on. The next value indicates the
number of milliseconds for which
to keep the vibrator on before
turning it off. Subsequent values
alternate between durations in
milliseconds to turn the vibrator
off or to turn the vibrator on.
@param {Integer} repeat Optional index into the pattern array at which
to start repeating (will repeat until canceled),
or -1 for no repetition (default).
|
[
"Vibrates",
"the",
"device",
"with",
"a",
"given",
"pattern",
"."
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/phonegap1/platforms/ios/www/plugins/cordova-plugin-vibration/www/vibration.js#L105-L109
|
|
13,521
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/scripts/npm/processConfigXml.js
|
read
|
function read(context) {
const projectRoot = getProjectRoot(context);
const configXml = getConfigXml(projectRoot);
const branchXml = getBranchXml(configXml);
const branchPreferences = getBranchPreferences(
context,
configXml,
branchXml
);
validateBranchPreferences(branchPreferences);
return branchPreferences;
}
|
javascript
|
function read(context) {
const projectRoot = getProjectRoot(context);
const configXml = getConfigXml(projectRoot);
const branchXml = getBranchXml(configXml);
const branchPreferences = getBranchPreferences(
context,
configXml,
branchXml
);
validateBranchPreferences(branchPreferences);
return branchPreferences;
}
|
[
"function",
"read",
"(",
"context",
")",
"{",
"const",
"projectRoot",
"=",
"getProjectRoot",
"(",
"context",
")",
";",
"const",
"configXml",
"=",
"getConfigXml",
"(",
"projectRoot",
")",
";",
"const",
"branchXml",
"=",
"getBranchXml",
"(",
"configXml",
")",
";",
"const",
"branchPreferences",
"=",
"getBranchPreferences",
"(",
"context",
",",
"configXml",
",",
"branchXml",
")",
";",
"validateBranchPreferences",
"(",
"branchPreferences",
")",
";",
"return",
"branchPreferences",
";",
"}"
] |
read branch config from config.xml
|
[
"read",
"branch",
"config",
"from",
"config",
".",
"xml"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/scripts/npm/processConfigXml.js#L13-L26
|
13,522
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/scripts/npm/processConfigXml.js
|
getConfigXml
|
function getConfigXml(projectRoot) {
const pathToConfigXml = path.join(projectRoot, "config.xml");
const configXml = xmlHelper.readXmlAsJson(pathToConfigXml);
if (configXml == null) {
throw new Error(
"BRANCH SDK: A config.xml is not found in project's root directory. Docs https://goo.gl/GijGKP"
);
}
return configXml;
}
|
javascript
|
function getConfigXml(projectRoot) {
const pathToConfigXml = path.join(projectRoot, "config.xml");
const configXml = xmlHelper.readXmlAsJson(pathToConfigXml);
if (configXml == null) {
throw new Error(
"BRANCH SDK: A config.xml is not found in project's root directory. Docs https://goo.gl/GijGKP"
);
}
return configXml;
}
|
[
"function",
"getConfigXml",
"(",
"projectRoot",
")",
"{",
"const",
"pathToConfigXml",
"=",
"path",
".",
"join",
"(",
"projectRoot",
",",
"\"config.xml\"",
")",
";",
"const",
"configXml",
"=",
"xmlHelper",
".",
"readXmlAsJson",
"(",
"pathToConfigXml",
")",
";",
"if",
"(",
"configXml",
"==",
"null",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"BRANCH SDK: A config.xml is not found in project's root directory. Docs https://goo.gl/GijGKP\"",
")",
";",
"}",
"return",
"configXml",
";",
"}"
] |
read config.xml
|
[
"read",
"config",
".",
"xml"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/scripts/npm/processConfigXml.js#L29-L40
|
13,523
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/scripts/npm/processConfigXml.js
|
getProjectName
|
function getProjectName(configXml) {
let output = null;
if (configXml.widget.hasOwnProperty("name")) {
const name = configXml.widget.name[0];
if (typeof name === "string") {
// handle <name>Branch Cordova</name>
output = configXml.widget.name[0];
} else {
// handle <name short="Branch">Branch Cordova</name>
output = configXml.widget.name[0]._;
}
}
return output;
}
|
javascript
|
function getProjectName(configXml) {
let output = null;
if (configXml.widget.hasOwnProperty("name")) {
const name = configXml.widget.name[0];
if (typeof name === "string") {
// handle <name>Branch Cordova</name>
output = configXml.widget.name[0];
} else {
// handle <name short="Branch">Branch Cordova</name>
output = configXml.widget.name[0]._;
}
}
return output;
}
|
[
"function",
"getProjectName",
"(",
"configXml",
")",
"{",
"let",
"output",
"=",
"null",
";",
"if",
"(",
"configXml",
".",
"widget",
".",
"hasOwnProperty",
"(",
"\"name\"",
")",
")",
"{",
"const",
"name",
"=",
"configXml",
".",
"widget",
".",
"name",
"[",
"0",
"]",
";",
"if",
"(",
"typeof",
"name",
"===",
"\"string\"",
")",
"{",
"// handle <name>Branch Cordova</name>",
"output",
"=",
"configXml",
".",
"widget",
".",
"name",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"// handle <name short=\"Branch\">Branch Cordova</name>",
"output",
"=",
"configXml",
".",
"widget",
".",
"name",
"[",
"0",
"]",
".",
"_",
";",
"}",
"}",
"return",
"output",
";",
"}"
] |
read project name from config.xml
|
[
"read",
"project",
"name",
"from",
"config",
".",
"xml"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/scripts/npm/processConfigXml.js#L79-L93
|
13,524
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/scripts/npm/processConfigXml.js
|
getProjectModule
|
function getProjectModule(context) {
const projectRoot = getProjectRoot(context);
const projectPath = path.join(projectRoot, "platforms", "ios");
try {
// pre 5.0 cordova structure
return context
.requireCordovaModule("cordova-lib/src/plugman/platforms")
.ios.parseProjectFile(projectPath);
} catch (e) {
try {
// pre 7.0 cordova structure
return context
.requireCordovaModule("cordova-lib/src/plugman/platforms/ios")
.parseProjectFile(projectPath);
} catch (e) {
// post 7.0 cordova structure
return getProjectModuleGlob(context);
}
}
}
|
javascript
|
function getProjectModule(context) {
const projectRoot = getProjectRoot(context);
const projectPath = path.join(projectRoot, "platforms", "ios");
try {
// pre 5.0 cordova structure
return context
.requireCordovaModule("cordova-lib/src/plugman/platforms")
.ios.parseProjectFile(projectPath);
} catch (e) {
try {
// pre 7.0 cordova structure
return context
.requireCordovaModule("cordova-lib/src/plugman/platforms/ios")
.parseProjectFile(projectPath);
} catch (e) {
// post 7.0 cordova structure
return getProjectModuleGlob(context);
}
}
}
|
[
"function",
"getProjectModule",
"(",
"context",
")",
"{",
"const",
"projectRoot",
"=",
"getProjectRoot",
"(",
"context",
")",
";",
"const",
"projectPath",
"=",
"path",
".",
"join",
"(",
"projectRoot",
",",
"\"platforms\"",
",",
"\"ios\"",
")",
";",
"try",
"{",
"// pre 5.0 cordova structure",
"return",
"context",
".",
"requireCordovaModule",
"(",
"\"cordova-lib/src/plugman/platforms\"",
")",
".",
"ios",
".",
"parseProjectFile",
"(",
"projectPath",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"try",
"{",
"// pre 7.0 cordova structure",
"return",
"context",
".",
"requireCordovaModule",
"(",
"\"cordova-lib/src/plugman/platforms/ios\"",
")",
".",
"parseProjectFile",
"(",
"projectPath",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// post 7.0 cordova structure",
"return",
"getProjectModuleGlob",
"(",
"context",
")",
";",
"}",
"}",
"}"
] |
read iOS project module from cordova context
|
[
"read",
"iOS",
"project",
"module",
"from",
"cordova",
"context"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/scripts/npm/processConfigXml.js#L128-L148
|
13,525
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/scripts/npm/updateNpmVersion.js
|
updateNpmVersion
|
function updateNpmVersion(pluginConfig, config, callback) {
const files = readFilePaths(FILES);
const version = config.nextRelease.version;
let git = "";
for (let i = 0; i < files.length; i++) {
// update
const file = files[i];
const content = readContent(file);
const updated = updateVersion(file, content, version);
// save
git += `git add ${file} && `;
saveContent(file, updated);
}
// publish
isChange && commitChanges(git, version);
}
|
javascript
|
function updateNpmVersion(pluginConfig, config, callback) {
const files = readFilePaths(FILES);
const version = config.nextRelease.version;
let git = "";
for (let i = 0; i < files.length; i++) {
// update
const file = files[i];
const content = readContent(file);
const updated = updateVersion(file, content, version);
// save
git += `git add ${file} && `;
saveContent(file, updated);
}
// publish
isChange && commitChanges(git, version);
}
|
[
"function",
"updateNpmVersion",
"(",
"pluginConfig",
",",
"config",
",",
"callback",
")",
"{",
"const",
"files",
"=",
"readFilePaths",
"(",
"FILES",
")",
";",
"const",
"version",
"=",
"config",
".",
"nextRelease",
".",
"version",
";",
"let",
"git",
"=",
"\"\"",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"files",
".",
"length",
";",
"i",
"++",
")",
"{",
"// update",
"const",
"file",
"=",
"files",
"[",
"i",
"]",
";",
"const",
"content",
"=",
"readContent",
"(",
"file",
")",
";",
"const",
"updated",
"=",
"updateVersion",
"(",
"file",
",",
"content",
",",
"version",
")",
";",
"// save",
"git",
"+=",
"`",
"${",
"file",
"}",
"`",
";",
"saveContent",
"(",
"file",
",",
"updated",
")",
";",
"}",
"// publish",
"isChange",
"&&",
"commitChanges",
"(",
"git",
",",
"version",
")",
";",
"}"
] |
updates the npm version in semantic-release pre
|
[
"updates",
"the",
"npm",
"version",
"in",
"semantic",
"-",
"release",
"pre"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/scripts/npm/updateNpmVersion.js#L14-L31
|
13,526
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/scripts/npm/updateNpmVersion.js
|
updateVersion
|
function updateVersion(file, content, version) {
const prev = /id="branch-cordova-sdk"[\s]*version="\d+\.\d+\.\d+"/gim;
const next = `id="branch-cordova-sdk"\n version="${version}"`;
try {
if (isFileXml(file)) {
content = content.replace(prev, next);
} else {
isChange = content.version !== version;
content.version = version;
}
} catch (e) {
throw new Error(
`BRANCH SDK: update to update npm version with file ${file}`
);
}
return content;
}
|
javascript
|
function updateVersion(file, content, version) {
const prev = /id="branch-cordova-sdk"[\s]*version="\d+\.\d+\.\d+"/gim;
const next = `id="branch-cordova-sdk"\n version="${version}"`;
try {
if (isFileXml(file)) {
content = content.replace(prev, next);
} else {
isChange = content.version !== version;
content.version = version;
}
} catch (e) {
throw new Error(
`BRANCH SDK: update to update npm version with file ${file}`
);
}
return content;
}
|
[
"function",
"updateVersion",
"(",
"file",
",",
"content",
",",
"version",
")",
"{",
"const",
"prev",
"=",
"/",
"id=\"branch-cordova-sdk\"[\\s]*version=\"\\d+\\.\\d+\\.\\d+\"",
"/",
"gim",
";",
"const",
"next",
"=",
"`",
"\\n",
"${",
"version",
"}",
"`",
";",
"try",
"{",
"if",
"(",
"isFileXml",
"(",
"file",
")",
")",
"{",
"content",
"=",
"content",
".",
"replace",
"(",
"prev",
",",
"next",
")",
";",
"}",
"else",
"{",
"isChange",
"=",
"content",
".",
"version",
"!==",
"version",
";",
"content",
".",
"version",
"=",
"version",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"file",
"}",
"`",
")",
";",
"}",
"return",
"content",
";",
"}"
] |
update content based on xml or json
|
[
"update",
"content",
"based",
"on",
"xml",
"or",
"json"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/scripts/npm/updateNpmVersion.js#L51-L68
|
13,527
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/scripts/npm/updateNpmVersion.js
|
readFilePaths
|
function readFilePaths(files) {
const locations = [];
for (let i = 0; i < files.length; i++) {
const file = files[i];
const location = path.join(__dirname, "../../../", file);
locations.push(location);
}
return locations;
}
|
javascript
|
function readFilePaths(files) {
const locations = [];
for (let i = 0; i < files.length; i++) {
const file = files[i];
const location = path.join(__dirname, "../../../", file);
locations.push(location);
}
return locations;
}
|
[
"function",
"readFilePaths",
"(",
"files",
")",
"{",
"const",
"locations",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"files",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"file",
"=",
"files",
"[",
"i",
"]",
";",
"const",
"location",
"=",
"path",
".",
"join",
"(",
"__dirname",
",",
"\"../../../\"",
",",
"file",
")",
";",
"locations",
".",
"push",
"(",
"location",
")",
";",
"}",
"return",
"locations",
";",
"}"
] |
get the absolute path of the files within the root directory
|
[
"get",
"the",
"absolute",
"path",
"of",
"the",
"files",
"within",
"the",
"root",
"directory"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/scripts/npm/updateNpmVersion.js#L71-L79
|
13,528
|
BranchMetrics/cordova-ionic-phonegap-branch-deep-linking
|
examples/cordova1/plugins/branch-cordova-sdk/src/scripts/npm/updateNpmVersion.js
|
commitChanges
|
function commitChanges(git, version) {
git += `git commit -m "chore: updated npm version to ${version}" && git push`;
exec(git, (err, stdout, stderr) => {
if (err) {
throw new Error(
"BRANCH SDK: Failed to commit git changes for the npm version. Docs https://goo.gl/GijGKP"
);
}
});
}
|
javascript
|
function commitChanges(git, version) {
git += `git commit -m "chore: updated npm version to ${version}" && git push`;
exec(git, (err, stdout, stderr) => {
if (err) {
throw new Error(
"BRANCH SDK: Failed to commit git changes for the npm version. Docs https://goo.gl/GijGKP"
);
}
});
}
|
[
"function",
"commitChanges",
"(",
"git",
",",
"version",
")",
"{",
"git",
"+=",
"`",
"${",
"version",
"}",
"`",
";",
"exec",
"(",
"git",
",",
"(",
"err",
",",
"stdout",
",",
"stderr",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"BRANCH SDK: Failed to commit git changes for the npm version. Docs https://goo.gl/GijGKP\"",
")",
";",
"}",
"}",
")",
";",
"}"
] |
push file code changes to github
|
[
"push",
"file",
"code",
"changes",
"to",
"github"
] |
252f591fcc833ac9fe7fb0f535d351e0879a873c
|
https://github.com/BranchMetrics/cordova-ionic-phonegap-branch-deep-linking/blob/252f591fcc833ac9fe7fb0f535d351e0879a873c/examples/cordova1/plugins/branch-cordova-sdk/src/scripts/npm/updateNpmVersion.js#L82-L91
|
13,529
|
DesignRevision/shards-vue
|
dist/shards-vue.umd.js
|
registerComponent
|
function registerComponent(Vue, name, definition) {
Vue._shards_vue_components_ = Vue._shards_vue_components_ || {};
var loaded = Vue._shards_vue_components_[name];
if (!loaded && definition && name) {
Vue._shards_vue_components_[name] = true;
Vue.component(name, definition);
}
return loaded
}
|
javascript
|
function registerComponent(Vue, name, definition) {
Vue._shards_vue_components_ = Vue._shards_vue_components_ || {};
var loaded = Vue._shards_vue_components_[name];
if (!loaded && definition && name) {
Vue._shards_vue_components_[name] = true;
Vue.component(name, definition);
}
return loaded
}
|
[
"function",
"registerComponent",
"(",
"Vue",
",",
"name",
",",
"definition",
")",
"{",
"Vue",
".",
"_shards_vue_components_",
"=",
"Vue",
".",
"_shards_vue_components_",
"||",
"{",
"}",
";",
"var",
"loaded",
"=",
"Vue",
".",
"_shards_vue_components_",
"[",
"name",
"]",
";",
"if",
"(",
"!",
"loaded",
"&&",
"definition",
"&&",
"name",
")",
"{",
"Vue",
".",
"_shards_vue_components_",
"[",
"name",
"]",
"=",
"true",
";",
"Vue",
".",
"component",
"(",
"name",
",",
"definition",
")",
";",
"}",
"return",
"loaded",
"}"
] |
Register a component plugin.
|
[
"Register",
"a",
"component",
"plugin",
"."
] |
b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3
|
https://github.com/DesignRevision/shards-vue/blob/b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3/dist/shards-vue.umd.js#L29-L39
|
13,530
|
DesignRevision/shards-vue
|
dist/shards-vue.umd.js
|
registerComponents
|
function registerComponents(Vue, components) {
for (var component in components) {
registerComponent(Vue, component, components[component]);
}
}
|
javascript
|
function registerComponents(Vue, components) {
for (var component in components) {
registerComponent(Vue, component, components[component]);
}
}
|
[
"function",
"registerComponents",
"(",
"Vue",
",",
"components",
")",
"{",
"for",
"(",
"var",
"component",
"in",
"components",
")",
"{",
"registerComponent",
"(",
"Vue",
",",
"component",
",",
"components",
"[",
"component",
"]",
")",
";",
"}",
"}"
] |
Register a group of components.
|
[
"Register",
"a",
"group",
"of",
"components",
"."
] |
b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3
|
https://github.com/DesignRevision/shards-vue/blob/b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3/dist/shards-vue.umd.js#L42-L46
|
13,531
|
DesignRevision/shards-vue
|
dist/shards-vue.umd.js
|
registerDirective
|
function registerDirective(Vue, name, definition) {
Vue._shards_vue_directives_ = Vue._shards_vue_directives_ || {};
var loaded = Vue._shards_vue_directives_[name];
if (!loaded && definition && name) {
Vue._shards_vue_directives_[name] = true;
Vue.directive(name, definition);
}
return loaded
}
|
javascript
|
function registerDirective(Vue, name, definition) {
Vue._shards_vue_directives_ = Vue._shards_vue_directives_ || {};
var loaded = Vue._shards_vue_directives_[name];
if (!loaded && definition && name) {
Vue._shards_vue_directives_[name] = true;
Vue.directive(name, definition);
}
return loaded
}
|
[
"function",
"registerDirective",
"(",
"Vue",
",",
"name",
",",
"definition",
")",
"{",
"Vue",
".",
"_shards_vue_directives_",
"=",
"Vue",
".",
"_shards_vue_directives_",
"||",
"{",
"}",
";",
"var",
"loaded",
"=",
"Vue",
".",
"_shards_vue_directives_",
"[",
"name",
"]",
";",
"if",
"(",
"!",
"loaded",
"&&",
"definition",
"&&",
"name",
")",
"{",
"Vue",
".",
"_shards_vue_directives_",
"[",
"name",
"]",
"=",
"true",
";",
"Vue",
".",
"directive",
"(",
"name",
",",
"definition",
")",
";",
"}",
"return",
"loaded",
"}"
] |
Register a directive as being loaded. returns true if directive plugin already registered
|
[
"Register",
"a",
"directive",
"as",
"being",
"loaded",
".",
"returns",
"true",
"if",
"directive",
"plugin",
"already",
"registered"
] |
b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3
|
https://github.com/DesignRevision/shards-vue/blob/b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3/dist/shards-vue.umd.js#L49-L59
|
13,532
|
DesignRevision/shards-vue
|
dist/shards-vue.umd.js
|
registerDirectives
|
function registerDirectives(Vue, directives) {
for (var directive in directives) {
registerDirective(Vue, directive, directives[directive]);
}
}
|
javascript
|
function registerDirectives(Vue, directives) {
for (var directive in directives) {
registerDirective(Vue, directive, directives[directive]);
}
}
|
[
"function",
"registerDirectives",
"(",
"Vue",
",",
"directives",
")",
"{",
"for",
"(",
"var",
"directive",
"in",
"directives",
")",
"{",
"registerDirective",
"(",
"Vue",
",",
"directive",
",",
"directives",
"[",
"directive",
"]",
")",
";",
"}",
"}"
] |
Register a group of directives as being loaded.
|
[
"Register",
"a",
"group",
"of",
"directives",
"as",
"being",
"loaded",
"."
] |
b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3
|
https://github.com/DesignRevision/shards-vue/blob/b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3/dist/shards-vue.umd.js#L62-L66
|
13,533
|
DesignRevision/shards-vue
|
dist/shards-vue.umd.js
|
function (el, className) {
if (className && isElement(el)) {
return el.classList.contains(className)
}
return false
}
|
javascript
|
function (el, className) {
if (className && isElement(el)) {
return el.classList.contains(className)
}
return false
}
|
[
"function",
"(",
"el",
",",
"className",
")",
"{",
"if",
"(",
"className",
"&&",
"isElement",
"(",
"el",
")",
")",
"{",
"return",
"el",
".",
"classList",
".",
"contains",
"(",
"className",
")",
"}",
"return",
"false",
"}"
] |
Checks whether an element has a particular class name, or not.
|
[
"Checks",
"whether",
"an",
"element",
"has",
"a",
"particular",
"class",
"name",
"or",
"not",
"."
] |
b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3
|
https://github.com/DesignRevision/shards-vue/blob/b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3/dist/shards-vue.umd.js#L141-L147
|
|
13,534
|
DesignRevision/shards-vue
|
dist/shards-vue.umd.js
|
function (el, attr, value) {
if (attr && isElement(el)) {
el.setAttribute(attr, value);
}
}
|
javascript
|
function (el, attr, value) {
if (attr && isElement(el)) {
el.setAttribute(attr, value);
}
}
|
[
"function",
"(",
"el",
",",
"attr",
",",
"value",
")",
"{",
"if",
"(",
"attr",
"&&",
"isElement",
"(",
"el",
")",
")",
"{",
"el",
".",
"setAttribute",
"(",
"attr",
",",
"value",
")",
";",
"}",
"}"
] |
Sets an attribute on an element
|
[
"Sets",
"an",
"attribute",
"on",
"an",
"element"
] |
b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3
|
https://github.com/DesignRevision/shards-vue/blob/b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3/dist/shards-vue.umd.js#L189-L193
|
|
13,535
|
DesignRevision/shards-vue
|
dist/shards-vue.umd.js
|
function (el) {
return !isElement(el)
|| el.disabled
|| el.classList.contains('disabled')
|| Boolean(el.getAttribute('disabled'))
}
|
javascript
|
function (el) {
return !isElement(el)
|| el.disabled
|| el.classList.contains('disabled')
|| Boolean(el.getAttribute('disabled'))
}
|
[
"function",
"(",
"el",
")",
"{",
"return",
"!",
"isElement",
"(",
"el",
")",
"||",
"el",
".",
"disabled",
"||",
"el",
".",
"classList",
".",
"contains",
"(",
"'disabled'",
")",
"||",
"Boolean",
"(",
"el",
".",
"getAttribute",
"(",
"'disabled'",
")",
")",
"}"
] |
Checks whether an element is disabled, or not.
|
[
"Checks",
"whether",
"an",
"element",
"is",
"disabled",
"or",
"not",
"."
] |
b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3
|
https://github.com/DesignRevision/shards-vue/blob/b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3/dist/shards-vue.umd.js#L212-L217
|
|
13,536
|
DesignRevision/shards-vue
|
dist/shards-vue.umd.js
|
function (el) {
return isElement(el)
&& document.body.contains(el)
&& el.getBoundingClientRect().height > 0
&& el.getBoundingClientRect().width > 0
}
|
javascript
|
function (el) {
return isElement(el)
&& document.body.contains(el)
&& el.getBoundingClientRect().height > 0
&& el.getBoundingClientRect().width > 0
}
|
[
"function",
"(",
"el",
")",
"{",
"return",
"isElement",
"(",
"el",
")",
"&&",
"document",
".",
"body",
".",
"contains",
"(",
"el",
")",
"&&",
"el",
".",
"getBoundingClientRect",
"(",
")",
".",
"height",
">",
"0",
"&&",
"el",
".",
"getBoundingClientRect",
"(",
")",
".",
"width",
">",
"0",
"}"
] |
Determines if an HTML element is visible - Faster than CSS check
|
[
"Determines",
"if",
"an",
"HTML",
"element",
"is",
"visible",
"-",
"Faster",
"than",
"CSS",
"check"
] |
b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3
|
https://github.com/DesignRevision/shards-vue/blob/b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3/dist/shards-vue.umd.js#L220-L225
|
|
13,537
|
DesignRevision/shards-vue
|
dist/shards-vue.umd.js
|
function (selector, root) {
if (!isElement(root)) {
root = document;
}
return root.querySelector(selector) || null
}
|
javascript
|
function (selector, root) {
if (!isElement(root)) {
root = document;
}
return root.querySelector(selector) || null
}
|
[
"function",
"(",
"selector",
",",
"root",
")",
"{",
"if",
"(",
"!",
"isElement",
"(",
"root",
")",
")",
"{",
"root",
"=",
"document",
";",
"}",
"return",
"root",
".",
"querySelector",
"(",
"selector",
")",
"||",
"null",
"}"
] |
Selects an element.
|
[
"Selects",
"an",
"element",
"."
] |
b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3
|
https://github.com/DesignRevision/shards-vue/blob/b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3/dist/shards-vue.umd.js#L228-L234
|
|
13,538
|
DesignRevision/shards-vue
|
dist/shards-vue.umd.js
|
function (selector, root) {
if (!isElement(root)) {
return null
}
var Closest = Element.prototype.closest ||
function (sel) {
var element = this;
if (!document.documentElement.contains(element)) {
return null
}
do {
if (element.matches(sel)) {
return element
}
element = element.parentElement;
} while (element !== null)
return null
};
var el = Closest.call(root, selector);
return el === root ? null : el
}
|
javascript
|
function (selector, root) {
if (!isElement(root)) {
return null
}
var Closest = Element.prototype.closest ||
function (sel) {
var element = this;
if (!document.documentElement.contains(element)) {
return null
}
do {
if (element.matches(sel)) {
return element
}
element = element.parentElement;
} while (element !== null)
return null
};
var el = Closest.call(root, selector);
return el === root ? null : el
}
|
[
"function",
"(",
"selector",
",",
"root",
")",
"{",
"if",
"(",
"!",
"isElement",
"(",
"root",
")",
")",
"{",
"return",
"null",
"}",
"var",
"Closest",
"=",
"Element",
".",
"prototype",
".",
"closest",
"||",
"function",
"(",
"sel",
")",
"{",
"var",
"element",
"=",
"this",
";",
"if",
"(",
"!",
"document",
".",
"documentElement",
".",
"contains",
"(",
"element",
")",
")",
"{",
"return",
"null",
"}",
"do",
"{",
"if",
"(",
"element",
".",
"matches",
"(",
"sel",
")",
")",
"{",
"return",
"element",
"}",
"element",
"=",
"element",
".",
"parentElement",
";",
"}",
"while",
"(",
"element",
"!==",
"null",
")",
"return",
"null",
"}",
";",
"var",
"el",
"=",
"Closest",
".",
"call",
"(",
"root",
",",
"selector",
")",
";",
"return",
"el",
"===",
"root",
"?",
"null",
":",
"el",
"}"
] |
Finds closest element matching selector.
|
[
"Finds",
"closest",
"element",
"matching",
"selector",
"."
] |
b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3
|
https://github.com/DesignRevision/shards-vue/blob/b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3/dist/shards-vue.umd.js#L237-L263
|
|
13,539
|
DesignRevision/shards-vue
|
dist/shards-vue.umd.js
|
function (type, breakpoint, val) {
if (!!val === false) {
return false
}
var className = type;
if (breakpoint) {
className += "-" + (breakpoint.replace(type, '')); // -md ?
}
if (type === 'col' && (val === '' || val === true)) {
return className.toLowerCase() // .col-md
}
return (className + "-" + val).toLowerCase()
}
|
javascript
|
function (type, breakpoint, val) {
if (!!val === false) {
return false
}
var className = type;
if (breakpoint) {
className += "-" + (breakpoint.replace(type, '')); // -md ?
}
if (type === 'col' && (val === '' || val === true)) {
return className.toLowerCase() // .col-md
}
return (className + "-" + val).toLowerCase()
}
|
[
"function",
"(",
"type",
",",
"breakpoint",
",",
"val",
")",
"{",
"if",
"(",
"!",
"!",
"val",
"===",
"false",
")",
"{",
"return",
"false",
"}",
"var",
"className",
"=",
"type",
";",
"if",
"(",
"breakpoint",
")",
"{",
"className",
"+=",
"\"-\"",
"+",
"(",
"breakpoint",
".",
"replace",
"(",
"type",
",",
"''",
")",
")",
";",
"// -md ?",
"}",
"if",
"(",
"type",
"===",
"'col'",
"&&",
"(",
"val",
"===",
"''",
"||",
"val",
"===",
"true",
")",
")",
"{",
"return",
"className",
".",
"toLowerCase",
"(",
")",
"// .col-md",
"}",
"return",
"(",
"className",
"+",
"\"-\"",
"+",
"val",
")",
".",
"toLowerCase",
"(",
")",
"}"
] |
Creates Bootstrap specific breakpoint classes.
|
[
"Creates",
"Bootstrap",
"specific",
"breakpoint",
"classes",
"."
] |
b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3
|
https://github.com/DesignRevision/shards-vue/blob/b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3/dist/shards-vue.umd.js#L4573-L4589
|
|
13,540
|
DesignRevision/shards-vue
|
dist/shards-vue.umd.js
|
generateProp
|
function generateProp(type, defaultVal) {
if ( type === void 0 ) type = [Boolean, String, Number];
if ( defaultVal === void 0 ) defaultVal = null;
return {
default: defaultVal,
type: type
}
}
|
javascript
|
function generateProp(type, defaultVal) {
if ( type === void 0 ) type = [Boolean, String, Number];
if ( defaultVal === void 0 ) defaultVal = null;
return {
default: defaultVal,
type: type
}
}
|
[
"function",
"generateProp",
"(",
"type",
",",
"defaultVal",
")",
"{",
"if",
"(",
"type",
"===",
"void",
"0",
")",
"type",
"=",
"[",
"Boolean",
",",
"String",
",",
"Number",
"]",
";",
"if",
"(",
"defaultVal",
"===",
"void",
"0",
")",
"defaultVal",
"=",
"null",
";",
"return",
"{",
"default",
":",
"defaultVal",
",",
"type",
":",
"type",
"}",
"}"
] |
Generates component properties.
|
[
"Generates",
"component",
"properties",
"."
] |
b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3
|
https://github.com/DesignRevision/shards-vue/blob/b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3/dist/shards-vue.umd.js#L4592-L4600
|
13,541
|
DesignRevision/shards-vue
|
dist/shards-vue.umd.js
|
createBreakpointMap
|
function createBreakpointMap(propGenArgs, defaultValue, breakpointWrapper) {
if ( propGenArgs === void 0 ) propGenArgs = null;
if ( breakpointWrapper === void 0 ) breakpointWrapper = null;
var breakpointWrapperArgs = [], len = arguments.length - 3;
while ( len-- > 0 ) breakpointWrapperArgs[ len ] = arguments[ len + 3 ];
breakpointWrapper = breakpointWrapper === null ? function (v) { return v; } : breakpointWrapper;
return BREAKPOINTS.reduce(function (map, breakpoint) {
map[breakpointWrapper.apply(void 0, [ breakpoint ].concat( breakpointWrapperArgs ))] = generateProp(propGenArgs, defaultValue);
return map
}, {})
}
|
javascript
|
function createBreakpointMap(propGenArgs, defaultValue, breakpointWrapper) {
if ( propGenArgs === void 0 ) propGenArgs = null;
if ( breakpointWrapper === void 0 ) breakpointWrapper = null;
var breakpointWrapperArgs = [], len = arguments.length - 3;
while ( len-- > 0 ) breakpointWrapperArgs[ len ] = arguments[ len + 3 ];
breakpointWrapper = breakpointWrapper === null ? function (v) { return v; } : breakpointWrapper;
return BREAKPOINTS.reduce(function (map, breakpoint) {
map[breakpointWrapper.apply(void 0, [ breakpoint ].concat( breakpointWrapperArgs ))] = generateProp(propGenArgs, defaultValue);
return map
}, {})
}
|
[
"function",
"createBreakpointMap",
"(",
"propGenArgs",
",",
"defaultValue",
",",
"breakpointWrapper",
")",
"{",
"if",
"(",
"propGenArgs",
"===",
"void",
"0",
")",
"propGenArgs",
"=",
"null",
";",
"if",
"(",
"breakpointWrapper",
"===",
"void",
"0",
")",
"breakpointWrapper",
"=",
"null",
";",
"var",
"breakpointWrapperArgs",
"=",
"[",
"]",
",",
"len",
"=",
"arguments",
".",
"length",
"-",
"3",
";",
"while",
"(",
"len",
"--",
">",
"0",
")",
"breakpointWrapperArgs",
"[",
"len",
"]",
"=",
"arguments",
"[",
"len",
"+",
"3",
"]",
";",
"breakpointWrapper",
"=",
"breakpointWrapper",
"===",
"null",
"?",
"function",
"(",
"v",
")",
"{",
"return",
"v",
";",
"}",
":",
"breakpointWrapper",
";",
"return",
"BREAKPOINTS",
".",
"reduce",
"(",
"function",
"(",
"map",
",",
"breakpoint",
")",
"{",
"map",
"[",
"breakpointWrapper",
".",
"apply",
"(",
"void",
"0",
",",
"[",
"breakpoint",
"]",
".",
"concat",
"(",
"breakpointWrapperArgs",
")",
")",
"]",
"=",
"generateProp",
"(",
"propGenArgs",
",",
"defaultValue",
")",
";",
"return",
"map",
"}",
",",
"{",
"}",
")",
"}"
] |
Creates breakpoint maps
|
[
"Creates",
"breakpoint",
"maps"
] |
b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3
|
https://github.com/DesignRevision/shards-vue/blob/b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3/dist/shards-vue.umd.js#L4611-L4622
|
13,542
|
DesignRevision/shards-vue
|
dist/shards-vue.umd.js
|
CancelableEvent
|
function CancelableEvent (type, eventInit) {
if ( eventInit === void 0 ) eventInit = {};
Object.assign(this, CancelableEvent.defaults(), eventInit, { type: type });
Object.defineProperties(this, {
type: _makeCancelableEventProps(),
cancelable: _makeCancelableEventProps(),
nativeEvent: _makeCancelableEventProps(),
target: _makeCancelableEventProps(),
relatedTarget: _makeCancelableEventProps(),
vueTarget: _makeCancelableEventProps()
});
var defaultPrevented = false;
this.preventDefault = function preventDefault() {
if (this.cancelable) {
defaultPrevented = true;
}
};
Object.defineProperty(this, 'defaultPrevented', {
enumerable: true,
get: function get() {
return defaultPrevented
}
});
}
|
javascript
|
function CancelableEvent (type, eventInit) {
if ( eventInit === void 0 ) eventInit = {};
Object.assign(this, CancelableEvent.defaults(), eventInit, { type: type });
Object.defineProperties(this, {
type: _makeCancelableEventProps(),
cancelable: _makeCancelableEventProps(),
nativeEvent: _makeCancelableEventProps(),
target: _makeCancelableEventProps(),
relatedTarget: _makeCancelableEventProps(),
vueTarget: _makeCancelableEventProps()
});
var defaultPrevented = false;
this.preventDefault = function preventDefault() {
if (this.cancelable) {
defaultPrevented = true;
}
};
Object.defineProperty(this, 'defaultPrevented', {
enumerable: true,
get: function get() {
return defaultPrevented
}
});
}
|
[
"function",
"CancelableEvent",
"(",
"type",
",",
"eventInit",
")",
"{",
"if",
"(",
"eventInit",
"===",
"void",
"0",
")",
"eventInit",
"=",
"{",
"}",
";",
"Object",
".",
"assign",
"(",
"this",
",",
"CancelableEvent",
".",
"defaults",
"(",
")",
",",
"eventInit",
",",
"{",
"type",
":",
"type",
"}",
")",
";",
"Object",
".",
"defineProperties",
"(",
"this",
",",
"{",
"type",
":",
"_makeCancelableEventProps",
"(",
")",
",",
"cancelable",
":",
"_makeCancelableEventProps",
"(",
")",
",",
"nativeEvent",
":",
"_makeCancelableEventProps",
"(",
")",
",",
"target",
":",
"_makeCancelableEventProps",
"(",
")",
",",
"relatedTarget",
":",
"_makeCancelableEventProps",
"(",
")",
",",
"vueTarget",
":",
"_makeCancelableEventProps",
"(",
")",
"}",
")",
";",
"var",
"defaultPrevented",
"=",
"false",
";",
"this",
".",
"preventDefault",
"=",
"function",
"preventDefault",
"(",
")",
"{",
"if",
"(",
"this",
".",
"cancelable",
")",
"{",
"defaultPrevented",
"=",
"true",
";",
"}",
"}",
";",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"'defaultPrevented'",
",",
"{",
"enumerable",
":",
"true",
",",
"get",
":",
"function",
"get",
"(",
")",
"{",
"return",
"defaultPrevented",
"}",
"}",
")",
";",
"}"
] |
Custom cancelable event.
|
[
"Custom",
"cancelable",
"event",
"."
] |
b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3
|
https://github.com/DesignRevision/shards-vue/blob/b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3/dist/shards-vue.umd.js#L7744-L7772
|
13,543
|
DesignRevision/shards-vue
|
dist/shards-vue.umd.js
|
function () {
if (this$1._config.animation) {
var initConfigAnimation = this$1._config.animation || false;
if (getAttr(TPElement, 'x-placement') !== null) {
return
}
removeClass(TPElement, TP_STATE_CLASSES.FADE);
this$1._config.animation = false;
this$1.hide();
this$1.show();
this$1._config.animation = initConfigAnimation;
}
var prevHoverState = this$1._hoverState;
this$1._hoverState = null;
if (prevHoverState === TOOLTIP_HOVER_STATE_CLASSES.OUT) {
this$1._handleLeave(null);
}
var shownEvt = new CancelableEvent('shown', {
cancelable: false,
target: this$1._targetElement,
relatedTarget: TPElement
});
this$1._emitCustomEvent(shownEvt);
}
|
javascript
|
function () {
if (this$1._config.animation) {
var initConfigAnimation = this$1._config.animation || false;
if (getAttr(TPElement, 'x-placement') !== null) {
return
}
removeClass(TPElement, TP_STATE_CLASSES.FADE);
this$1._config.animation = false;
this$1.hide();
this$1.show();
this$1._config.animation = initConfigAnimation;
}
var prevHoverState = this$1._hoverState;
this$1._hoverState = null;
if (prevHoverState === TOOLTIP_HOVER_STATE_CLASSES.OUT) {
this$1._handleLeave(null);
}
var shownEvt = new CancelableEvent('shown', {
cancelable: false,
target: this$1._targetElement,
relatedTarget: TPElement
});
this$1._emitCustomEvent(shownEvt);
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"this$1",
".",
"_config",
".",
"animation",
")",
"{",
"var",
"initConfigAnimation",
"=",
"this$1",
".",
"_config",
".",
"animation",
"||",
"false",
";",
"if",
"(",
"getAttr",
"(",
"TPElement",
",",
"'x-placement'",
")",
"!==",
"null",
")",
"{",
"return",
"}",
"removeClass",
"(",
"TPElement",
",",
"TP_STATE_CLASSES",
".",
"FADE",
")",
";",
"this$1",
".",
"_config",
".",
"animation",
"=",
"false",
";",
"this$1",
".",
"hide",
"(",
")",
";",
"this$1",
".",
"show",
"(",
")",
";",
"this$1",
".",
"_config",
".",
"animation",
"=",
"initConfigAnimation",
";",
"}",
"var",
"prevHoverState",
"=",
"this$1",
".",
"_hoverState",
";",
"this$1",
".",
"_hoverState",
"=",
"null",
";",
"if",
"(",
"prevHoverState",
"===",
"TOOLTIP_HOVER_STATE_CLASSES",
".",
"OUT",
")",
"{",
"this$1",
".",
"_handleLeave",
"(",
"null",
")",
";",
"}",
"var",
"shownEvt",
"=",
"new",
"CancelableEvent",
"(",
"'shown'",
",",
"{",
"cancelable",
":",
"false",
",",
"target",
":",
"this$1",
".",
"_targetElement",
",",
"relatedTarget",
":",
"TPElement",
"}",
")",
";",
"this$1",
".",
"_emitCustomEvent",
"(",
"shownEvt",
")",
";",
"}"
] |
Prep the transition complete handler
|
[
"Prep",
"the",
"transition",
"complete",
"handler"
] |
b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3
|
https://github.com/DesignRevision/shards-vue/blob/b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3/dist/shards-vue.umd.js#L15128-L15157
|
|
13,544
|
DesignRevision/shards-vue
|
dist/shards-vue.umd.js
|
DOMObserver
|
function DOMObserver (el, callback, opts) {
if ( opts === void 0 ) opts = null;
if (opts === null) {
opts = {
subtree: true,
childList: true,
characterData: true,
attributes: true,
attributeFilter: ['class', 'style']
};
}
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
var eventListenerSupported = window.addEventListener;
el = el ? (el.$el || el) : null;
if (!isElement(el)) {
return null
}
var obs = null;
if (MutationObserver) {
obs = new MutationObserver(function (mutations) {
var changed = false;
for (var i = 0; i < mutations.length && !changed; i++) {
var mutation = mutations[i];
var type = mutation.type;
var target = mutation.target;
if (type === 'characterData' && target.nodeType === Node.TEXT_NODE) {
changed = true;
} else if (type === 'attributes') {
changed = true;
} else if (type === 'childList' && (mutation.addedNodes.length > 0 || mutation.removedNodes.length > 0)) {
changed = true;
}
}
if (changed) {
callback();
}
});
obs.observe(el, Object.assign({}, { childList: true, subtree: true }, opts));
} else if (eventListenerSupported) {
el.addEventListener('DOMNodeInserted', callback, false);
el.addEventListener('DOMNodeRemoved', callback, false);
}
return obs
}
|
javascript
|
function DOMObserver (el, callback, opts) {
if ( opts === void 0 ) opts = null;
if (opts === null) {
opts = {
subtree: true,
childList: true,
characterData: true,
attributes: true,
attributeFilter: ['class', 'style']
};
}
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
var eventListenerSupported = window.addEventListener;
el = el ? (el.$el || el) : null;
if (!isElement(el)) {
return null
}
var obs = null;
if (MutationObserver) {
obs = new MutationObserver(function (mutations) {
var changed = false;
for (var i = 0; i < mutations.length && !changed; i++) {
var mutation = mutations[i];
var type = mutation.type;
var target = mutation.target;
if (type === 'characterData' && target.nodeType === Node.TEXT_NODE) {
changed = true;
} else if (type === 'attributes') {
changed = true;
} else if (type === 'childList' && (mutation.addedNodes.length > 0 || mutation.removedNodes.length > 0)) {
changed = true;
}
}
if (changed) {
callback();
}
});
obs.observe(el, Object.assign({}, { childList: true, subtree: true }, opts));
} else if (eventListenerSupported) {
el.addEventListener('DOMNodeInserted', callback, false);
el.addEventListener('DOMNodeRemoved', callback, false);
}
return obs
}
|
[
"function",
"DOMObserver",
"(",
"el",
",",
"callback",
",",
"opts",
")",
"{",
"if",
"(",
"opts",
"===",
"void",
"0",
")",
"opts",
"=",
"null",
";",
"if",
"(",
"opts",
"===",
"null",
")",
"{",
"opts",
"=",
"{",
"subtree",
":",
"true",
",",
"childList",
":",
"true",
",",
"characterData",
":",
"true",
",",
"attributes",
":",
"true",
",",
"attributeFilter",
":",
"[",
"'class'",
",",
"'style'",
"]",
"}",
";",
"}",
"var",
"MutationObserver",
"=",
"window",
".",
"MutationObserver",
"||",
"window",
".",
"WebKitMutationObserver",
"||",
"window",
".",
"MozMutationObserver",
";",
"var",
"eventListenerSupported",
"=",
"window",
".",
"addEventListener",
";",
"el",
"=",
"el",
"?",
"(",
"el",
".",
"$el",
"||",
"el",
")",
":",
"null",
";",
"if",
"(",
"!",
"isElement",
"(",
"el",
")",
")",
"{",
"return",
"null",
"}",
"var",
"obs",
"=",
"null",
";",
"if",
"(",
"MutationObserver",
")",
"{",
"obs",
"=",
"new",
"MutationObserver",
"(",
"function",
"(",
"mutations",
")",
"{",
"var",
"changed",
"=",
"false",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"mutations",
".",
"length",
"&&",
"!",
"changed",
";",
"i",
"++",
")",
"{",
"var",
"mutation",
"=",
"mutations",
"[",
"i",
"]",
";",
"var",
"type",
"=",
"mutation",
".",
"type",
";",
"var",
"target",
"=",
"mutation",
".",
"target",
";",
"if",
"(",
"type",
"===",
"'characterData'",
"&&",
"target",
".",
"nodeType",
"===",
"Node",
".",
"TEXT_NODE",
")",
"{",
"changed",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"type",
"===",
"'attributes'",
")",
"{",
"changed",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"type",
"===",
"'childList'",
"&&",
"(",
"mutation",
".",
"addedNodes",
".",
"length",
">",
"0",
"||",
"mutation",
".",
"removedNodes",
".",
"length",
">",
"0",
")",
")",
"{",
"changed",
"=",
"true",
";",
"}",
"}",
"if",
"(",
"changed",
")",
"{",
"callback",
"(",
")",
";",
"}",
"}",
")",
";",
"obs",
".",
"observe",
"(",
"el",
",",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"{",
"childList",
":",
"true",
",",
"subtree",
":",
"true",
"}",
",",
"opts",
")",
")",
";",
"}",
"else",
"if",
"(",
"eventListenerSupported",
")",
"{",
"el",
".",
"addEventListener",
"(",
"'DOMNodeInserted'",
",",
"callback",
",",
"false",
")",
";",
"el",
".",
"addEventListener",
"(",
"'DOMNodeRemoved'",
",",
"callback",
",",
"false",
")",
";",
"}",
"return",
"obs",
"}"
] |
Observes DOM changes.
@see http://stackoverflow.com/questions/3219758
|
[
"Observes",
"DOM",
"changes",
"."
] |
b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3
|
https://github.com/DesignRevision/shards-vue/blob/b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3/dist/shards-vue.umd.js#L15838-L15889
|
13,545
|
DesignRevision/shards-vue
|
dist/shards-vue.umd.js
|
getUpdatedConfig
|
function getUpdatedConfig() {
var updatedConfig = Object.assign({}, this.baseConfig);
// override title if slot is used
if (this.$refs.title) {
updatedConfig.title = this.$refs.title;
updatedConfig.html = true;
}
// override content if slot is used
if (this.$refs.content) {
updatedConfig.content = this.$refs.content;
updatedConfig.html = true;
}
return updatedConfig
}
|
javascript
|
function getUpdatedConfig() {
var updatedConfig = Object.assign({}, this.baseConfig);
// override title if slot is used
if (this.$refs.title) {
updatedConfig.title = this.$refs.title;
updatedConfig.html = true;
}
// override content if slot is used
if (this.$refs.content) {
updatedConfig.content = this.$refs.content;
updatedConfig.html = true;
}
return updatedConfig
}
|
[
"function",
"getUpdatedConfig",
"(",
")",
"{",
"var",
"updatedConfig",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"this",
".",
"baseConfig",
")",
";",
"// override title if slot is used",
"if",
"(",
"this",
".",
"$refs",
".",
"title",
")",
"{",
"updatedConfig",
".",
"title",
"=",
"this",
".",
"$refs",
".",
"title",
";",
"updatedConfig",
".",
"html",
"=",
"true",
";",
"}",
"// override content if slot is used",
"if",
"(",
"this",
".",
"$refs",
".",
"content",
")",
"{",
"updatedConfig",
".",
"content",
"=",
"this",
".",
"$refs",
".",
"content",
";",
"updatedConfig",
".",
"html",
"=",
"true",
";",
"}",
"return",
"updatedConfig",
"}"
] |
Returns the updated config.
|
[
"Returns",
"the",
"updated",
"config",
"."
] |
b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3
|
https://github.com/DesignRevision/shards-vue/blob/b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3/dist/shards-vue.umd.js#L16058-L16074
|
13,546
|
DesignRevision/shards-vue
|
dist/shards-vue.umd.js
|
parseBindings
|
function parseBindings(bindings) {
var config = {};
switch (typeof bindings.value) {
case 'string':
case 'function':
config.title = bindings.value;
break
case 'object':
config = Object.assign({}, bindings.value);
}
// Parse args (eg: v-d-tooltip:my-container)
if (bindings.arg) {
config.container = "#" + (bindings.arg); // #my-container
}
// Parse modifiers. eg: v-d-tooltip.my-modifier
Object.keys(bindings.modifiers).forEach(function (mod) {
// Parse if the title allows HTML
if (/^html$/.test(mod)) {
config.html = true;
// Parse animation
} else if (/^nofade$/.test(mod)) {
config.animation = false;
// Parse placement
} else if (/^(auto|top(left|right)?|bottom(left|right)?|left(top|bottom)?|right(top|bottom)?)$/.test(mod)) {
config.placement = mod;
// Parse boundary
} else if (/^(window|viewport)$/.test(mod)) {
config.boundary = mod;
// Parse delay
} else if (/^d\d+$/.test(mod)) {
var delay = parseInt(mod.slice(1), 10) || 0;
if (delay) {
config.delay = delay;
}
// Parse offset
} else if (/^o-?\d+$/.test(mod)) {
var offset = parseInt(mod.slice(1), 10) || 0;
if (offset) {
config.offset = offset;
}
}
});
// Parse selected triggers.
var selectedTriggers = {};
var triggers = typeof config.trigger === 'string' ? config.trigger.trim().split(/\s+/) : [];
triggers.forEach(function (trigger) {
if (validTriggers[trigger]) {
selectedTriggers[trigger] = true;
}
});
// Parse trigger modifiers. eg: v-d-tooltip.click
Object.keys(validTriggers).forEach(function (trigger) {
if (bindings.modifiers[trigger]) {
selectedTriggers[trigger] = true;
}
});
config.trigger = Object.keys(selectedTriggers).join(' ');
// Convert `blur` to `focus`
if (config.trigger === 'blur') {
config.trigger = 'focus';
}
// If there's no trigger assigned, just delete the key.
if (!config.trigger) {
delete config.trigger;
}
return config
}
|
javascript
|
function parseBindings(bindings) {
var config = {};
switch (typeof bindings.value) {
case 'string':
case 'function':
config.title = bindings.value;
break
case 'object':
config = Object.assign({}, bindings.value);
}
// Parse args (eg: v-d-tooltip:my-container)
if (bindings.arg) {
config.container = "#" + (bindings.arg); // #my-container
}
// Parse modifiers. eg: v-d-tooltip.my-modifier
Object.keys(bindings.modifiers).forEach(function (mod) {
// Parse if the title allows HTML
if (/^html$/.test(mod)) {
config.html = true;
// Parse animation
} else if (/^nofade$/.test(mod)) {
config.animation = false;
// Parse placement
} else if (/^(auto|top(left|right)?|bottom(left|right)?|left(top|bottom)?|right(top|bottom)?)$/.test(mod)) {
config.placement = mod;
// Parse boundary
} else if (/^(window|viewport)$/.test(mod)) {
config.boundary = mod;
// Parse delay
} else if (/^d\d+$/.test(mod)) {
var delay = parseInt(mod.slice(1), 10) || 0;
if (delay) {
config.delay = delay;
}
// Parse offset
} else if (/^o-?\d+$/.test(mod)) {
var offset = parseInt(mod.slice(1), 10) || 0;
if (offset) {
config.offset = offset;
}
}
});
// Parse selected triggers.
var selectedTriggers = {};
var triggers = typeof config.trigger === 'string' ? config.trigger.trim().split(/\s+/) : [];
triggers.forEach(function (trigger) {
if (validTriggers[trigger]) {
selectedTriggers[trigger] = true;
}
});
// Parse trigger modifiers. eg: v-d-tooltip.click
Object.keys(validTriggers).forEach(function (trigger) {
if (bindings.modifiers[trigger]) {
selectedTriggers[trigger] = true;
}
});
config.trigger = Object.keys(selectedTriggers).join(' ');
// Convert `blur` to `focus`
if (config.trigger === 'blur') {
config.trigger = 'focus';
}
// If there's no trigger assigned, just delete the key.
if (!config.trigger) {
delete config.trigger;
}
return config
}
|
[
"function",
"parseBindings",
"(",
"bindings",
")",
"{",
"var",
"config",
"=",
"{",
"}",
";",
"switch",
"(",
"typeof",
"bindings",
".",
"value",
")",
"{",
"case",
"'string'",
":",
"case",
"'function'",
":",
"config",
".",
"title",
"=",
"bindings",
".",
"value",
";",
"break",
"case",
"'object'",
":",
"config",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"bindings",
".",
"value",
")",
";",
"}",
"// Parse args (eg: v-d-tooltip:my-container)",
"if",
"(",
"bindings",
".",
"arg",
")",
"{",
"config",
".",
"container",
"=",
"\"#\"",
"+",
"(",
"bindings",
".",
"arg",
")",
";",
"// #my-container",
"}",
"// Parse modifiers. eg: v-d-tooltip.my-modifier",
"Object",
".",
"keys",
"(",
"bindings",
".",
"modifiers",
")",
".",
"forEach",
"(",
"function",
"(",
"mod",
")",
"{",
"// Parse if the title allows HTML",
"if",
"(",
"/",
"^html$",
"/",
".",
"test",
"(",
"mod",
")",
")",
"{",
"config",
".",
"html",
"=",
"true",
";",
"// Parse animation",
"}",
"else",
"if",
"(",
"/",
"^nofade$",
"/",
".",
"test",
"(",
"mod",
")",
")",
"{",
"config",
".",
"animation",
"=",
"false",
";",
"// Parse placement",
"}",
"else",
"if",
"(",
"/",
"^(auto|top(left|right)?|bottom(left|right)?|left(top|bottom)?|right(top|bottom)?)$",
"/",
".",
"test",
"(",
"mod",
")",
")",
"{",
"config",
".",
"placement",
"=",
"mod",
";",
"// Parse boundary",
"}",
"else",
"if",
"(",
"/",
"^(window|viewport)$",
"/",
".",
"test",
"(",
"mod",
")",
")",
"{",
"config",
".",
"boundary",
"=",
"mod",
";",
"// Parse delay",
"}",
"else",
"if",
"(",
"/",
"^d\\d+$",
"/",
".",
"test",
"(",
"mod",
")",
")",
"{",
"var",
"delay",
"=",
"parseInt",
"(",
"mod",
".",
"slice",
"(",
"1",
")",
",",
"10",
")",
"||",
"0",
";",
"if",
"(",
"delay",
")",
"{",
"config",
".",
"delay",
"=",
"delay",
";",
"}",
"// Parse offset",
"}",
"else",
"if",
"(",
"/",
"^o-?\\d+$",
"/",
".",
"test",
"(",
"mod",
")",
")",
"{",
"var",
"offset",
"=",
"parseInt",
"(",
"mod",
".",
"slice",
"(",
"1",
")",
",",
"10",
")",
"||",
"0",
";",
"if",
"(",
"offset",
")",
"{",
"config",
".",
"offset",
"=",
"offset",
";",
"}",
"}",
"}",
")",
";",
"// Parse selected triggers.",
"var",
"selectedTriggers",
"=",
"{",
"}",
";",
"var",
"triggers",
"=",
"typeof",
"config",
".",
"trigger",
"===",
"'string'",
"?",
"config",
".",
"trigger",
".",
"trim",
"(",
")",
".",
"split",
"(",
"/",
"\\s+",
"/",
")",
":",
"[",
"]",
";",
"triggers",
".",
"forEach",
"(",
"function",
"(",
"trigger",
")",
"{",
"if",
"(",
"validTriggers",
"[",
"trigger",
"]",
")",
"{",
"selectedTriggers",
"[",
"trigger",
"]",
"=",
"true",
";",
"}",
"}",
")",
";",
"// Parse trigger modifiers. eg: v-d-tooltip.click",
"Object",
".",
"keys",
"(",
"validTriggers",
")",
".",
"forEach",
"(",
"function",
"(",
"trigger",
")",
"{",
"if",
"(",
"bindings",
".",
"modifiers",
"[",
"trigger",
"]",
")",
"{",
"selectedTriggers",
"[",
"trigger",
"]",
"=",
"true",
";",
"}",
"}",
")",
";",
"config",
".",
"trigger",
"=",
"Object",
".",
"keys",
"(",
"selectedTriggers",
")",
".",
"join",
"(",
"' '",
")",
";",
"// Convert `blur` to `focus`",
"if",
"(",
"config",
".",
"trigger",
"===",
"'blur'",
")",
"{",
"config",
".",
"trigger",
"=",
"'focus'",
";",
"}",
"// If there's no trigger assigned, just delete the key.",
"if",
"(",
"!",
"config",
".",
"trigger",
")",
"{",
"delete",
"config",
".",
"trigger",
";",
"}",
"return",
"config",
"}"
] |
Bindings parser.
|
[
"Bindings",
"parser",
"."
] |
b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3
|
https://github.com/DesignRevision/shards-vue/blob/b10a2489d7a5b544b3e1ba46e6b1c673046cc3c3/dist/shards-vue.umd.js#L18677-L18758
|
13,547
|
atmist/snazzy-info-window
|
src/snazzy-info-window.js
|
mergeDefaultOptions
|
function mergeDefaultOptions(opts) {
const copy = {};
copyKeys(copy, _defaultOptions);
copyKeys(copy, opts);
Object.keys(_defaultOptions).forEach((key) => {
const obj = _defaultOptions[key];
if (typeof obj === 'object') {
const objCopy = {};
copyKeys(objCopy, obj);
copyKeys(objCopy, copy[key]);
copy[key] = objCopy;
}
});
return copy;
}
|
javascript
|
function mergeDefaultOptions(opts) {
const copy = {};
copyKeys(copy, _defaultOptions);
copyKeys(copy, opts);
Object.keys(_defaultOptions).forEach((key) => {
const obj = _defaultOptions[key];
if (typeof obj === 'object') {
const objCopy = {};
copyKeys(objCopy, obj);
copyKeys(objCopy, copy[key]);
copy[key] = objCopy;
}
});
return copy;
}
|
[
"function",
"mergeDefaultOptions",
"(",
"opts",
")",
"{",
"const",
"copy",
"=",
"{",
"}",
";",
"copyKeys",
"(",
"copy",
",",
"_defaultOptions",
")",
";",
"copyKeys",
"(",
"copy",
",",
"opts",
")",
";",
"Object",
".",
"keys",
"(",
"_defaultOptions",
")",
".",
"forEach",
"(",
"(",
"key",
")",
"=>",
"{",
"const",
"obj",
"=",
"_defaultOptions",
"[",
"key",
"]",
";",
"if",
"(",
"typeof",
"obj",
"===",
"'object'",
")",
"{",
"const",
"objCopy",
"=",
"{",
"}",
";",
"copyKeys",
"(",
"objCopy",
",",
"obj",
")",
";",
"copyKeys",
"(",
"objCopy",
",",
"copy",
"[",
"key",
"]",
")",
";",
"copy",
"[",
"key",
"]",
"=",
"objCopy",
";",
"}",
"}",
")",
";",
"return",
"copy",
";",
"}"
] |
We need to safely merge options from the defaults. This will make sure settings like edgeOffset are properly assigned.
|
[
"We",
"need",
"to",
"safely",
"merge",
"options",
"from",
"the",
"defaults",
".",
"This",
"will",
"make",
"sure",
"settings",
"like",
"edgeOffset",
"are",
"properly",
"assigned",
"."
] |
dd49636d356f204d15008c8190aefbe2f743364f
|
https://github.com/atmist/snazzy-info-window/blob/dd49636d356f204d15008c8190aefbe2f743364f/src/snazzy-info-window.js#L40-L54
|
13,548
|
atmist/snazzy-info-window
|
src/snazzy-info-window.js
|
parseAttribute
|
function parseAttribute(attribute, defaultValue) {
// 1em, 1.0em, 0.1em, .1em, 1. em
const re = /^(-{0,1}\.{0,1}\d+(\.\d+)?)[\s|\.]*(\w*)$/;
if (attribute && re.test(attribute)) {
const match = re.exec(attribute);
const number = match[1];
const units = match[3] || 'px';
return { value: number * 1, units, original: attribute };
}
if (defaultValue) {
return parseAttribute(defaultValue);
}
return { original: defaultValue };
}
|
javascript
|
function parseAttribute(attribute, defaultValue) {
// 1em, 1.0em, 0.1em, .1em, 1. em
const re = /^(-{0,1}\.{0,1}\d+(\.\d+)?)[\s|\.]*(\w*)$/;
if (attribute && re.test(attribute)) {
const match = re.exec(attribute);
const number = match[1];
const units = match[3] || 'px';
return { value: number * 1, units, original: attribute };
}
if (defaultValue) {
return parseAttribute(defaultValue);
}
return { original: defaultValue };
}
|
[
"function",
"parseAttribute",
"(",
"attribute",
",",
"defaultValue",
")",
"{",
"// 1em, 1.0em, 0.1em, .1em, 1. em",
"const",
"re",
"=",
"/",
"^(-{0,1}\\.{0,1}\\d+(\\.\\d+)?)[\\s|\\.]*(\\w*)$",
"/",
";",
"if",
"(",
"attribute",
"&&",
"re",
".",
"test",
"(",
"attribute",
")",
")",
"{",
"const",
"match",
"=",
"re",
".",
"exec",
"(",
"attribute",
")",
";",
"const",
"number",
"=",
"match",
"[",
"1",
"]",
";",
"const",
"units",
"=",
"match",
"[",
"3",
"]",
"||",
"'px'",
";",
"return",
"{",
"value",
":",
"number",
"*",
"1",
",",
"units",
",",
"original",
":",
"attribute",
"}",
";",
"}",
"if",
"(",
"defaultValue",
")",
"{",
"return",
"parseAttribute",
"(",
"defaultValue",
")",
";",
"}",
"return",
"{",
"original",
":",
"defaultValue",
"}",
";",
"}"
] |
Parse a css attribute into the numeric portion and the units
|
[
"Parse",
"a",
"css",
"attribute",
"into",
"the",
"numeric",
"portion",
"and",
"the",
"units"
] |
dd49636d356f204d15008c8190aefbe2f743364f
|
https://github.com/atmist/snazzy-info-window/blob/dd49636d356f204d15008c8190aefbe2f743364f/src/snazzy-info-window.js#L57-L70
|
13,549
|
atmist/snazzy-info-window
|
src/snazzy-info-window.js
|
setHTML
|
function setHTML(container, content) {
if (container) {
// Clear out everything in the container
while (container.firstChild) {
container.removeChild(container.firstChild);
}
if (content) {
if (typeof content === 'string') {
container.innerHTML = content;
} else {
container.appendChild(content);
}
}
}
}
|
javascript
|
function setHTML(container, content) {
if (container) {
// Clear out everything in the container
while (container.firstChild) {
container.removeChild(container.firstChild);
}
if (content) {
if (typeof content === 'string') {
container.innerHTML = content;
} else {
container.appendChild(content);
}
}
}
}
|
[
"function",
"setHTML",
"(",
"container",
",",
"content",
")",
"{",
"if",
"(",
"container",
")",
"{",
"// Clear out everything in the container",
"while",
"(",
"container",
".",
"firstChild",
")",
"{",
"container",
".",
"removeChild",
"(",
"container",
".",
"firstChild",
")",
";",
"}",
"if",
"(",
"content",
")",
"{",
"if",
"(",
"typeof",
"content",
"===",
"'string'",
")",
"{",
"container",
".",
"innerHTML",
"=",
"content",
";",
"}",
"else",
"{",
"container",
".",
"appendChild",
"(",
"content",
")",
";",
"}",
"}",
"}",
"}"
] |
Set the html of a container. Should support both raw text and a single DOM Element.
|
[
"Set",
"the",
"html",
"of",
"a",
"container",
".",
"Should",
"support",
"both",
"raw",
"text",
"and",
"a",
"single",
"DOM",
"Element",
"."
] |
dd49636d356f204d15008c8190aefbe2f743364f
|
https://github.com/atmist/snazzy-info-window/blob/dd49636d356f204d15008c8190aefbe2f743364f/src/snazzy-info-window.js#L74-L88
|
13,550
|
atmist/snazzy-info-window
|
src/snazzy-info-window.js
|
toLatLng
|
function toLatLng(v) {
if (v !== undefined && v !== null) {
if (v instanceof google.maps.LatLng) {
return v;
} else if (v.lat !== undefined && v.lng !== undefined) {
return new google.maps.LatLng(v);
}
}
return null;
}
|
javascript
|
function toLatLng(v) {
if (v !== undefined && v !== null) {
if (v instanceof google.maps.LatLng) {
return v;
} else if (v.lat !== undefined && v.lng !== undefined) {
return new google.maps.LatLng(v);
}
}
return null;
}
|
[
"function",
"toLatLng",
"(",
"v",
")",
"{",
"if",
"(",
"v",
"!==",
"undefined",
"&&",
"v",
"!==",
"null",
")",
"{",
"if",
"(",
"v",
"instanceof",
"google",
".",
"maps",
".",
"LatLng",
")",
"{",
"return",
"v",
";",
"}",
"else",
"if",
"(",
"v",
".",
"lat",
"!==",
"undefined",
"&&",
"v",
".",
"lng",
"!==",
"undefined",
")",
"{",
"return",
"new",
"google",
".",
"maps",
".",
"LatLng",
"(",
"v",
")",
";",
"}",
"}",
"return",
"null",
";",
"}"
] |
Convert the value into a Google Map LatLng
|
[
"Convert",
"the",
"value",
"into",
"a",
"Google",
"Map",
"LatLng"
] |
dd49636d356f204d15008c8190aefbe2f743364f
|
https://github.com/atmist/snazzy-info-window/blob/dd49636d356f204d15008c8190aefbe2f743364f/src/snazzy-info-window.js#L110-L119
|
13,551
|
atmist/snazzy-info-window
|
dist/snazzy-info-window.js
|
applyCss
|
function applyCss(element, args) {
if (element && args) {
for (var i = 0; i < args.length; i++) {
var className = args[i];
if (className) {
if (element.className) {
element.className += ' ';
}
element.className += _classPrefix + className;
}
}
}
}
|
javascript
|
function applyCss(element, args) {
if (element && args) {
for (var i = 0; i < args.length; i++) {
var className = args[i];
if (className) {
if (element.className) {
element.className += ' ';
}
element.className += _classPrefix + className;
}
}
}
}
|
[
"function",
"applyCss",
"(",
"element",
",",
"args",
")",
"{",
"if",
"(",
"element",
"&&",
"args",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"args",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"className",
"=",
"args",
"[",
"i",
"]",
";",
"if",
"(",
"className",
")",
"{",
"if",
"(",
"element",
".",
"className",
")",
"{",
"element",
".",
"className",
"+=",
"' '",
";",
"}",
"element",
".",
"className",
"+=",
"_classPrefix",
"+",
"className",
";",
"}",
"}",
"}",
"}"
] |
Used for creating new elements
|
[
"Used",
"for",
"creating",
"new",
"elements"
] |
dd49636d356f204d15008c8190aefbe2f743364f
|
https://github.com/atmist/snazzy-info-window/blob/dd49636d356f204d15008c8190aefbe2f743364f/dist/snazzy-info-window.js#L527-L539
|
13,552
|
securing/gattacker
|
standalone/blueRadiosCmd.js
|
blueRadiosAT
|
function blueRadiosAT(command){
if (! wsclient.listeners('notification').length) {
console.log('subscribe to RX notification');
//listen for notification response
wsclient.on('notification', function(peripheralId, serviceUuid, characteristicUuid, data) {
// console.log("NOTIFICATION: " + data.toString('hex') + ' : ' + data.toString('ascii').yellow);
console.log(data.toString('ascii').trim().yellow);
});
}
//convert command to hex, add CR (0x0d = \r) at the end
var hexCommand = new Buffer(command + '\r','ascii');
wsclient.notify(peripheralId, blueRadiosService,blueRadiosRxCharacteristic,true, function() {
wsclient.write(peripheralId, blueRadiosService,blueRadiosCmdCharacteristic, new Buffer('02','hex'), false, function(error) {
console.log('Switch to CMD mode');
wsclient.write(peripheralId, blueRadiosService, blueRadiosTxCharacteristic, hexCommand, false, function(){
console.log('sent CMD: ' + command.cyan);
})
})
});
}
|
javascript
|
function blueRadiosAT(command){
if (! wsclient.listeners('notification').length) {
console.log('subscribe to RX notification');
//listen for notification response
wsclient.on('notification', function(peripheralId, serviceUuid, characteristicUuid, data) {
// console.log("NOTIFICATION: " + data.toString('hex') + ' : ' + data.toString('ascii').yellow);
console.log(data.toString('ascii').trim().yellow);
});
}
//convert command to hex, add CR (0x0d = \r) at the end
var hexCommand = new Buffer(command + '\r','ascii');
wsclient.notify(peripheralId, blueRadiosService,blueRadiosRxCharacteristic,true, function() {
wsclient.write(peripheralId, blueRadiosService,blueRadiosCmdCharacteristic, new Buffer('02','hex'), false, function(error) {
console.log('Switch to CMD mode');
wsclient.write(peripheralId, blueRadiosService, blueRadiosTxCharacteristic, hexCommand, false, function(){
console.log('sent CMD: ' + command.cyan);
})
})
});
}
|
[
"function",
"blueRadiosAT",
"(",
"command",
")",
"{",
"if",
"(",
"!",
"wsclient",
".",
"listeners",
"(",
"'notification'",
")",
".",
"length",
")",
"{",
"console",
".",
"log",
"(",
"'subscribe to RX notification'",
")",
";",
"//listen for notification response",
"wsclient",
".",
"on",
"(",
"'notification'",
",",
"function",
"(",
"peripheralId",
",",
"serviceUuid",
",",
"characteristicUuid",
",",
"data",
")",
"{",
"//\t\tconsole.log(\"NOTIFICATION: \" + data.toString('hex') + ' : ' + data.toString('ascii').yellow);",
"console",
".",
"log",
"(",
"data",
".",
"toString",
"(",
"'ascii'",
")",
".",
"trim",
"(",
")",
".",
"yellow",
")",
";",
"}",
")",
";",
"}",
"//convert command to hex, add CR (0x0d = \\r) at the end",
"var",
"hexCommand",
"=",
"new",
"Buffer",
"(",
"command",
"+",
"'\\r'",
",",
"'ascii'",
")",
";",
"wsclient",
".",
"notify",
"(",
"peripheralId",
",",
"blueRadiosService",
",",
"blueRadiosRxCharacteristic",
",",
"true",
",",
"function",
"(",
")",
"{",
"wsclient",
".",
"write",
"(",
"peripheralId",
",",
"blueRadiosService",
",",
"blueRadiosCmdCharacteristic",
",",
"new",
"Buffer",
"(",
"'02'",
",",
"'hex'",
")",
",",
"false",
",",
"function",
"(",
"error",
")",
"{",
"console",
".",
"log",
"(",
"'Switch to CMD mode'",
")",
";",
"wsclient",
".",
"write",
"(",
"peripheralId",
",",
"blueRadiosService",
",",
"blueRadiosTxCharacteristic",
",",
"hexCommand",
",",
"false",
",",
"function",
"(",
")",
"{",
"console",
".",
"log",
"(",
"'sent CMD: '",
"+",
"command",
".",
"cyan",
")",
";",
"}",
")",
"}",
")",
"}",
")",
";",
"}"
] |
command - string
|
[
"command",
"-",
"string"
] |
a8dd58cc10b1804cd1bc3c9f71a639a8bcfeee68
|
https://github.com/securing/gattacker/blob/a8dd58cc10b1804cd1bc3c9f71a639a8bcfeee68/standalone/blueRadiosCmd.js#L82-L103
|
13,553
|
securing/gattacker
|
advertise.js
|
dumpLog
|
function dumpLog(type, peripheralId, serviceUuid, uuid, data ){
var dumpFile=dumpPath + '/' + peripheralId + '.log';
if (servicesLookup[serviceUuid]) {
var serviceName = servicesLookup[serviceUuid].name;
var characteristicName = servicesLookup[serviceUuid].characteristics[uuid].name;
}
var toSave = getDateTime() + ' | ' + type + ' | ' + serviceUuid;
if (serviceName) { toSave += ' (' + serviceName + ')'; };
toSave += ' | ' + uuid;
if (characteristicName) { toSave += ' (' + characteristicName + ')'; };
toSave += ' | ' + data.toString('hex') + ' (' + utils.hex2a(data.toString('hex'))+ ')\n';
fs.appendFile(dumpFile, toSave, function(err) {
if(err) {
return console.log(err);
}
})
}
|
javascript
|
function dumpLog(type, peripheralId, serviceUuid, uuid, data ){
var dumpFile=dumpPath + '/' + peripheralId + '.log';
if (servicesLookup[serviceUuid]) {
var serviceName = servicesLookup[serviceUuid].name;
var characteristicName = servicesLookup[serviceUuid].characteristics[uuid].name;
}
var toSave = getDateTime() + ' | ' + type + ' | ' + serviceUuid;
if (serviceName) { toSave += ' (' + serviceName + ')'; };
toSave += ' | ' + uuid;
if (characteristicName) { toSave += ' (' + characteristicName + ')'; };
toSave += ' | ' + data.toString('hex') + ' (' + utils.hex2a(data.toString('hex'))+ ')\n';
fs.appendFile(dumpFile, toSave, function(err) {
if(err) {
return console.log(err);
}
})
}
|
[
"function",
"dumpLog",
"(",
"type",
",",
"peripheralId",
",",
"serviceUuid",
",",
"uuid",
",",
"data",
")",
"{",
"var",
"dumpFile",
"=",
"dumpPath",
"+",
"'/'",
"+",
"peripheralId",
"+",
"'.log'",
";",
"if",
"(",
"servicesLookup",
"[",
"serviceUuid",
"]",
")",
"{",
"var",
"serviceName",
"=",
"servicesLookup",
"[",
"serviceUuid",
"]",
".",
"name",
";",
"var",
"characteristicName",
"=",
"servicesLookup",
"[",
"serviceUuid",
"]",
".",
"characteristics",
"[",
"uuid",
"]",
".",
"name",
";",
"}",
"var",
"toSave",
"=",
"getDateTime",
"(",
")",
"+",
"' | '",
"+",
"type",
"+",
"' | '",
"+",
"serviceUuid",
";",
"if",
"(",
"serviceName",
")",
"{",
"toSave",
"+=",
"' ('",
"+",
"serviceName",
"+",
"')'",
";",
"}",
";",
"toSave",
"+=",
"' | '",
"+",
"uuid",
";",
"if",
"(",
"characteristicName",
")",
"{",
"toSave",
"+=",
"' ('",
"+",
"characteristicName",
"+",
"')'",
";",
"}",
";",
"toSave",
"+=",
"' | '",
"+",
"data",
".",
"toString",
"(",
"'hex'",
")",
"+",
"' ('",
"+",
"utils",
".",
"hex2a",
"(",
"data",
".",
"toString",
"(",
"'hex'",
")",
")",
"+",
"')\\n'",
";",
"fs",
".",
"appendFile",
"(",
"dumpFile",
",",
"toSave",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"console",
".",
"log",
"(",
"err",
")",
";",
"}",
"}",
")",
"}"
] |
dump transmission log to file
|
[
"dump",
"transmission",
"log",
"to",
"file"
] |
a8dd58cc10b1804cd1bc3c9f71a639a8bcfeee68
|
https://github.com/securing/gattacker/blob/a8dd58cc10b1804cd1bc3c9f71a639a8bcfeee68/advertise.js#L185-L205
|
13,554
|
securing/gattacker
|
gattacker2nrf.js
|
formatUuid
|
function formatUuid(Uuid) {
var formatted='';
//expand short service/characteristic UUID
if (Uuid.length == 4) {
formatted='0000' + Uuid + '-0000-1000-8000-00805f9b34fb';
}
else { //just add dashes
formatted = Uuid.slice(0,8)+'-'+Uuid.slice(8,12)+'-'+Uuid.slice(12,16)+'-'+Uuid.slice(16,20)+'-'+Uuid.slice(20,32);
}
return formatted;
}
|
javascript
|
function formatUuid(Uuid) {
var formatted='';
//expand short service/characteristic UUID
if (Uuid.length == 4) {
formatted='0000' + Uuid + '-0000-1000-8000-00805f9b34fb';
}
else { //just add dashes
formatted = Uuid.slice(0,8)+'-'+Uuid.slice(8,12)+'-'+Uuid.slice(12,16)+'-'+Uuid.slice(16,20)+'-'+Uuid.slice(20,32);
}
return formatted;
}
|
[
"function",
"formatUuid",
"(",
"Uuid",
")",
"{",
"var",
"formatted",
"=",
"''",
";",
"//expand short service/characteristic UUID",
"if",
"(",
"Uuid",
".",
"length",
"==",
"4",
")",
"{",
"formatted",
"=",
"'0000'",
"+",
"Uuid",
"+",
"'-0000-1000-8000-00805f9b34fb'",
";",
"}",
"else",
"{",
"//just add dashes ",
"formatted",
"=",
"Uuid",
".",
"slice",
"(",
"0",
",",
"8",
")",
"+",
"'-'",
"+",
"Uuid",
".",
"slice",
"(",
"8",
",",
"12",
")",
"+",
"'-'",
"+",
"Uuid",
".",
"slice",
"(",
"12",
",",
"16",
")",
"+",
"'-'",
"+",
"Uuid",
".",
"slice",
"(",
"16",
",",
"20",
")",
"+",
"'-'",
"+",
"Uuid",
".",
"slice",
"(",
"20",
",",
"32",
")",
";",
"}",
"return",
"formatted",
";",
"}"
] |
nrf requires strict UUID format
|
[
"nrf",
"requires",
"strict",
"UUID",
"format"
] |
a8dd58cc10b1804cd1bc3c9f71a639a8bcfeee68
|
https://github.com/securing/gattacker/blob/a8dd58cc10b1804cd1bc3c9f71a639a8bcfeee68/gattacker2nrf.js#L30-L40
|
13,555
|
securing/gattacker
|
hookFunctions/lock.js
|
lockCrc
|
function lockCrc(inputStr){
res = 0xff;
inputHex = new Buffer(inputStr,'hex');
//start from the second byte
for (i = 1; i<= inputHex.length; i++) {
res = res ^ inputHex[i];
}
//add padding
reshex = (res+0x100).toString(16).substr(-2);
// console.log(reshex);
return(inputStr+reshex);
}
|
javascript
|
function lockCrc(inputStr){
res = 0xff;
inputHex = new Buffer(inputStr,'hex');
//start from the second byte
for (i = 1; i<= inputHex.length; i++) {
res = res ^ inputHex[i];
}
//add padding
reshex = (res+0x100).toString(16).substr(-2);
// console.log(reshex);
return(inputStr+reshex);
}
|
[
"function",
"lockCrc",
"(",
"inputStr",
")",
"{",
"res",
"=",
"0xff",
";",
"inputHex",
"=",
"new",
"Buffer",
"(",
"inputStr",
",",
"'hex'",
")",
";",
"//start from the second byte ",
"for",
"(",
"i",
"=",
"1",
";",
"i",
"<=",
"inputHex",
".",
"length",
";",
"i",
"++",
")",
"{",
"res",
"=",
"res",
"^",
"inputHex",
"[",
"i",
"]",
";",
"}",
"//add padding",
"reshex",
"=",
"(",
"res",
"+",
"0x100",
")",
".",
"toString",
"(",
"16",
")",
".",
"substr",
"(",
"-",
"2",
")",
";",
"//\t\tconsole.log(reshex);",
"return",
"(",
"inputStr",
"+",
"reshex",
")",
";",
"}"
] |
returns string with calculated CRC attached
|
[
"returns",
"string",
"with",
"calculated",
"CRC",
"attached"
] |
a8dd58cc10b1804cd1bc3c9f71a639a8bcfeee68
|
https://github.com/securing/gattacker/blob/a8dd58cc10b1804cd1bc3c9f71a639a8bcfeee68/hookFunctions/lock.js#L99-L113
|
13,556
|
securing/gattacker
|
scan.js
|
checkFile
|
function checkFile(peripheralId, callback) {
if (overWriteServices) {
callback(false);
} else {
fs.stat(devicesPath + '/' + peripheralId + '.srv.json', function(err, stat) {
if(err == null) {
callback(true);
// console.log('File exists');
} else {
callback(false)
}
});
}
}
|
javascript
|
function checkFile(peripheralId, callback) {
if (overWriteServices) {
callback(false);
} else {
fs.stat(devicesPath + '/' + peripheralId + '.srv.json', function(err, stat) {
if(err == null) {
callback(true);
// console.log('File exists');
} else {
callback(false)
}
});
}
}
|
[
"function",
"checkFile",
"(",
"peripheralId",
",",
"callback",
")",
"{",
"if",
"(",
"overWriteServices",
")",
"{",
"callback",
"(",
"false",
")",
";",
"}",
"else",
"{",
"fs",
".",
"stat",
"(",
"devicesPath",
"+",
"'/'",
"+",
"peripheralId",
"+",
"'.srv.json'",
",",
"function",
"(",
"err",
",",
"stat",
")",
"{",
"if",
"(",
"err",
"==",
"null",
")",
"{",
"callback",
"(",
"true",
")",
";",
"// console.log('File exists');",
"}",
"else",
"{",
"callback",
"(",
"false",
")",
"}",
"}",
")",
";",
"}",
"}"
] |
check if the services file exists
|
[
"check",
"if",
"the",
"services",
"file",
"exists"
] |
a8dd58cc10b1804cd1bc3c9f71a639a8bcfeee68
|
https://github.com/securing/gattacker/blob/a8dd58cc10b1804cd1bc3c9f71a639a8bcfeee68/scan.js#L77-L90
|
13,557
|
securing/gattacker
|
ws-slave.js
|
readRaw
|
function readRaw(peripheralId, serviceUuid, uuid, callback){
//todo catch exceptions
var handle = servicesCache[peripheralId].services[serviceUuid].characteristics[uuid].handle;
var peripheral = peripherals[peripheralId];
//if not connected, connect
checkConnected(peripheral, function(){
peripheral.readHandle(handle, function(error, data){
if (error) {
debug('readHandle error : '.red + error)
}
debug('read handle data :' + data.toString('hex'));
sendEvent({
type: 'read',
peripheralId: peripheralId,
serviceUuid: serviceUuid,
characteristicUuid: uuid,
data: data.toString('hex'),
isNotification: false
});
if (callback) { callback(error, data); }
});
})
}
|
javascript
|
function readRaw(peripheralId, serviceUuid, uuid, callback){
//todo catch exceptions
var handle = servicesCache[peripheralId].services[serviceUuid].characteristics[uuid].handle;
var peripheral = peripherals[peripheralId];
//if not connected, connect
checkConnected(peripheral, function(){
peripheral.readHandle(handle, function(error, data){
if (error) {
debug('readHandle error : '.red + error)
}
debug('read handle data :' + data.toString('hex'));
sendEvent({
type: 'read',
peripheralId: peripheralId,
serviceUuid: serviceUuid,
characteristicUuid: uuid,
data: data.toString('hex'),
isNotification: false
});
if (callback) { callback(error, data); }
});
})
}
|
[
"function",
"readRaw",
"(",
"peripheralId",
",",
"serviceUuid",
",",
"uuid",
",",
"callback",
")",
"{",
"//todo catch exceptions",
"var",
"handle",
"=",
"servicesCache",
"[",
"peripheralId",
"]",
".",
"services",
"[",
"serviceUuid",
"]",
".",
"characteristics",
"[",
"uuid",
"]",
".",
"handle",
";",
"var",
"peripheral",
"=",
"peripherals",
"[",
"peripheralId",
"]",
";",
"//if not connected, connect",
"checkConnected",
"(",
"peripheral",
",",
"function",
"(",
")",
"{",
"peripheral",
".",
"readHandle",
"(",
"handle",
",",
"function",
"(",
"error",
",",
"data",
")",
"{",
"if",
"(",
"error",
")",
"{",
"debug",
"(",
"'readHandle error : '",
".",
"red",
"+",
"error",
")",
"}",
"debug",
"(",
"'read handle data :'",
"+",
"data",
".",
"toString",
"(",
"'hex'",
")",
")",
";",
"sendEvent",
"(",
"{",
"type",
":",
"'read'",
",",
"peripheralId",
":",
"peripheralId",
",",
"serviceUuid",
":",
"serviceUuid",
",",
"characteristicUuid",
":",
"uuid",
",",
"data",
":",
"data",
".",
"toString",
"(",
"'hex'",
")",
",",
"isNotification",
":",
"false",
"}",
")",
";",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
"error",
",",
"data",
")",
";",
"}",
"}",
")",
";",
"}",
")",
"}"
] |
read by handle
|
[
"read",
"by",
"handle"
] |
a8dd58cc10b1804cd1bc3c9f71a639a8bcfeee68
|
https://github.com/securing/gattacker/blob/a8dd58cc10b1804cd1bc3c9f71a639a8bcfeee68/ws-slave.js#L352-L377
|
13,558
|
securing/gattacker
|
ws-slave.js
|
writeRaw
|
function writeRaw(peripheralId, serviceUuid, uuid, data, withoutResponse, callback){
//todo catch exceptions
var handle = servicesCache[peripheralId].services[serviceUuid].characteristics[uuid].handle;
var peripheral = peripherals[peripheralId];
//if not connected, connect
checkConnected(peripheral, function(){
peripheral.writeHandle(handle, new Buffer(data,'hex'), withoutResponse, function(error){
if (error) {
debug('Write handle error! '. red + error);
}
debug('write handle sent ' + peripheralId + ' : ' + serviceUuid + ' : ' + uuid )
sendEvent({
type: 'write',
peripheralId: peripheralId,
serviceUuid: serviceUuid,
characteristicUuid: uuid
});
});
})
}
|
javascript
|
function writeRaw(peripheralId, serviceUuid, uuid, data, withoutResponse, callback){
//todo catch exceptions
var handle = servicesCache[peripheralId].services[serviceUuid].characteristics[uuid].handle;
var peripheral = peripherals[peripheralId];
//if not connected, connect
checkConnected(peripheral, function(){
peripheral.writeHandle(handle, new Buffer(data,'hex'), withoutResponse, function(error){
if (error) {
debug('Write handle error! '. red + error);
}
debug('write handle sent ' + peripheralId + ' : ' + serviceUuid + ' : ' + uuid )
sendEvent({
type: 'write',
peripheralId: peripheralId,
serviceUuid: serviceUuid,
characteristicUuid: uuid
});
});
})
}
|
[
"function",
"writeRaw",
"(",
"peripheralId",
",",
"serviceUuid",
",",
"uuid",
",",
"data",
",",
"withoutResponse",
",",
"callback",
")",
"{",
"//todo catch exceptions",
"var",
"handle",
"=",
"servicesCache",
"[",
"peripheralId",
"]",
".",
"services",
"[",
"serviceUuid",
"]",
".",
"characteristics",
"[",
"uuid",
"]",
".",
"handle",
";",
"var",
"peripheral",
"=",
"peripherals",
"[",
"peripheralId",
"]",
";",
"//if not connected, connect",
"checkConnected",
"(",
"peripheral",
",",
"function",
"(",
")",
"{",
"peripheral",
".",
"writeHandle",
"(",
"handle",
",",
"new",
"Buffer",
"(",
"data",
",",
"'hex'",
")",
",",
"withoutResponse",
",",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"error",
")",
"{",
"debug",
"(",
"'Write handle error! '",
".",
"red",
"+",
"error",
")",
";",
"}",
"debug",
"(",
"'write handle sent '",
"+",
"peripheralId",
"+",
"' : '",
"+",
"serviceUuid",
"+",
"' : '",
"+",
"uuid",
")",
"sendEvent",
"(",
"{",
"type",
":",
"'write'",
",",
"peripheralId",
":",
"peripheralId",
",",
"serviceUuid",
":",
"serviceUuid",
",",
"characteristicUuid",
":",
"uuid",
"}",
")",
";",
"}",
")",
";",
"}",
")",
"}"
] |
write by handle
|
[
"write",
"by",
"handle"
] |
a8dd58cc10b1804cd1bc3c9f71a639a8bcfeee68
|
https://github.com/securing/gattacker/blob/a8dd58cc10b1804cd1bc3c9f71a639a8bcfeee68/ws-slave.js#L380-L401
|
13,559
|
securing/gattacker
|
ws-slave.js
|
checkConnected
|
function checkConnected(peripheral, callback){
if (peripheral.state === 'connected') {
debug(' - connected');
if (callback) { callback(); }
} else if (peripheral.state === 'connecting'){
debug(' - connecting....');
//wait until the connection completes, invoke callback
peripheral.once('connect', function(){
if (callback){
callback();
}
})
}
else { //not connected
debug(' - not connected');
//if peripheral is lost by noble
if (! noble._peripherals[peripheral.id]) {
console.log('No such peripheral! This should not happen, restart manually...');
return
}
peripheral.connect( function(error) {
if (error) {
debug('checkconnected -> reconnect error !'.red + error)
} else {
debug('checkconnected -> reconnect');
}
if (callback) { callback(error); };
});
}
}
|
javascript
|
function checkConnected(peripheral, callback){
if (peripheral.state === 'connected') {
debug(' - connected');
if (callback) { callback(); }
} else if (peripheral.state === 'connecting'){
debug(' - connecting....');
//wait until the connection completes, invoke callback
peripheral.once('connect', function(){
if (callback){
callback();
}
})
}
else { //not connected
debug(' - not connected');
//if peripheral is lost by noble
if (! noble._peripherals[peripheral.id]) {
console.log('No such peripheral! This should not happen, restart manually...');
return
}
peripheral.connect( function(error) {
if (error) {
debug('checkconnected -> reconnect error !'.red + error)
} else {
debug('checkconnected -> reconnect');
}
if (callback) { callback(error); };
});
}
}
|
[
"function",
"checkConnected",
"(",
"peripheral",
",",
"callback",
")",
"{",
"if",
"(",
"peripheral",
".",
"state",
"===",
"'connected'",
")",
"{",
"debug",
"(",
"' - connected'",
")",
";",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
")",
";",
"}",
"}",
"else",
"if",
"(",
"peripheral",
".",
"state",
"===",
"'connecting'",
")",
"{",
"debug",
"(",
"' - connecting....'",
")",
";",
"//wait until the connection completes, invoke callback ",
"peripheral",
".",
"once",
"(",
"'connect'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
")",
";",
"}",
"}",
")",
"}",
"else",
"{",
"//not connected",
"debug",
"(",
"' - not connected'",
")",
";",
"//if peripheral is lost by noble",
"if",
"(",
"!",
"noble",
".",
"_peripherals",
"[",
"peripheral",
".",
"id",
"]",
")",
"{",
"console",
".",
"log",
"(",
"'No such peripheral! This should not happen, restart manually...'",
")",
";",
"return",
"}",
"peripheral",
".",
"connect",
"(",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"error",
")",
"{",
"debug",
"(",
"'checkconnected -> reconnect error !'",
".",
"red",
"+",
"error",
")",
"}",
"else",
"{",
"debug",
"(",
"'checkconnected -> reconnect'",
")",
";",
"}",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
"error",
")",
";",
"}",
";",
"}",
")",
";",
"}",
"}"
] |
check whether connected to peripheral, if not - reconnect, and then invoke peripheral function
|
[
"check",
"whether",
"connected",
"to",
"peripheral",
"if",
"not",
"-",
"reconnect",
"and",
"then",
"invoke",
"peripheral",
"function"
] |
a8dd58cc10b1804cd1bc3c9f71a639a8bcfeee68
|
https://github.com/securing/gattacker/blob/a8dd58cc10b1804cd1bc3c9f71a639a8bcfeee68/ws-slave.js#L498-L528
|
13,560
|
Yomguithereal/baobab
|
src/helpers.js
|
index
|
function index(a, fn) {
let i, l;
for (i = 0, l = a.length; i < l; i++) {
if (fn(a[i]))
return i;
}
return -1;
}
|
javascript
|
function index(a, fn) {
let i, l;
for (i = 0, l = a.length; i < l; i++) {
if (fn(a[i]))
return i;
}
return -1;
}
|
[
"function",
"index",
"(",
"a",
",",
"fn",
")",
"{",
"let",
"i",
",",
"l",
";",
"for",
"(",
"i",
"=",
"0",
",",
"l",
"=",
"a",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"if",
"(",
"fn",
"(",
"a",
"[",
"i",
"]",
")",
")",
"return",
"i",
";",
"}",
"return",
"-",
"1",
";",
"}"
] |
Function returning the index of the first element of a list matching the
given predicate.
@param {array} a - The target array.
@param {function} fn - The predicate function.
@return {mixed} - The index of the first matching item or -1.
|
[
"Function",
"returning",
"the",
"index",
"of",
"the",
"first",
"element",
"of",
"a",
"list",
"matching",
"the",
"given",
"predicate",
"."
] |
d0b7319117d929efb585b031ccebd01c13310f6e
|
https://github.com/Yomguithereal/baobab/blob/d0b7319117d929efb585b031ccebd01c13310f6e/src/helpers.js#L22-L29
|
13,561
|
Yomguithereal/baobab
|
src/helpers.js
|
slice
|
function slice(array) {
const newArray = new Array(array.length);
let i,
l;
for (i = 0, l = array.length; i < l; i++)
newArray[i] = array[i];
return newArray;
}
|
javascript
|
function slice(array) {
const newArray = new Array(array.length);
let i,
l;
for (i = 0, l = array.length; i < l; i++)
newArray[i] = array[i];
return newArray;
}
|
[
"function",
"slice",
"(",
"array",
")",
"{",
"const",
"newArray",
"=",
"new",
"Array",
"(",
"array",
".",
"length",
")",
";",
"let",
"i",
",",
"l",
";",
"for",
"(",
"i",
"=",
"0",
",",
"l",
"=",
"array",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"newArray",
"[",
"i",
"]",
"=",
"array",
"[",
"i",
"]",
";",
"return",
"newArray",
";",
"}"
] |
Efficient slice function used to clone arrays or parts of them.
@param {array} array - The array to slice.
@return {array} - The sliced array.
|
[
"Efficient",
"slice",
"function",
"used",
"to",
"clone",
"arrays",
"or",
"parts",
"of",
"them",
"."
] |
d0b7319117d929efb585b031ccebd01c13310f6e
|
https://github.com/Yomguithereal/baobab/blob/d0b7319117d929efb585b031ccebd01c13310f6e/src/helpers.js#L37-L47
|
13,562
|
Yomguithereal/baobab
|
src/helpers.js
|
cloneRegexp
|
function cloneRegexp(re) {
const pattern = re.source;
let flags = '';
if (re.global) flags += 'g';
if (re.multiline) flags += 'm';
if (re.ignoreCase) flags += 'i';
if (re.sticky) flags += 'y';
if (re.unicode) flags += 'u';
return new RegExp(pattern, flags);
}
|
javascript
|
function cloneRegexp(re) {
const pattern = re.source;
let flags = '';
if (re.global) flags += 'g';
if (re.multiline) flags += 'm';
if (re.ignoreCase) flags += 'i';
if (re.sticky) flags += 'y';
if (re.unicode) flags += 'u';
return new RegExp(pattern, flags);
}
|
[
"function",
"cloneRegexp",
"(",
"re",
")",
"{",
"const",
"pattern",
"=",
"re",
".",
"source",
";",
"let",
"flags",
"=",
"''",
";",
"if",
"(",
"re",
".",
"global",
")",
"flags",
"+=",
"'g'",
";",
"if",
"(",
"re",
".",
"multiline",
")",
"flags",
"+=",
"'m'",
";",
"if",
"(",
"re",
".",
"ignoreCase",
")",
"flags",
"+=",
"'i'",
";",
"if",
"(",
"re",
".",
"sticky",
")",
"flags",
"+=",
"'y'",
";",
"if",
"(",
"re",
".",
"unicode",
")",
"flags",
"+=",
"'u'",
";",
"return",
"new",
"RegExp",
"(",
"pattern",
",",
"flags",
")",
";",
"}"
] |
Function cloning the given regular expression. Supports `y` and `u` flags
already.
@param {RegExp} re - The target regular expression.
@return {RegExp} - The cloned regular expression.
|
[
"Function",
"cloning",
"the",
"given",
"regular",
"expression",
".",
"Supports",
"y",
"and",
"u",
"flags",
"already",
"."
] |
d0b7319117d929efb585b031ccebd01c13310f6e
|
https://github.com/Yomguithereal/baobab/blob/d0b7319117d929efb585b031ccebd01c13310f6e/src/helpers.js#L144-L156
|
13,563
|
Yomguithereal/baobab
|
src/helpers.js
|
cloner
|
function cloner(deep, item) {
if (!item ||
typeof item !== 'object' ||
item instanceof Error ||
item instanceof MonkeyDefinition ||
item instanceof Monkey ||
('ArrayBuffer' in global && item instanceof ArrayBuffer))
return item;
// Array
if (type.array(item)) {
if (deep) {
const a = new Array(item.length);
for (let i = 0, l = item.length; i < l; i++)
a[i] = cloner(true, item[i]);
return a;
}
return slice(item);
}
// Date
if (item instanceof Date)
return new Date(item.getTime());
// RegExp
if (item instanceof RegExp)
return cloneRegexp(item);
// Object
if (type.object(item)) {
const o = {};
// NOTE: could be possible to erase computed properties through `null`.
const props = Object.getOwnPropertyNames(item);
for (let i = 0, l = props.length; i < l; i++) {
const name = props[i];
const k = Object.getOwnPropertyDescriptor(item, name);
if (k.enumerable === true) {
if (k.get && k.get.isLazyGetter) {
Object.defineProperty(o, name, {
get: k.get,
enumerable: true,
configurable: true
});
}
else {
o[name] = deep ? cloner(true, item[name]) : item[name];
}
}
else if (k.enumerable === false) {
Object.defineProperty(o, name, {
value: deep ? cloner(true, k.value) : k.value,
enumerable: false,
writable: true,
configurable: true
});
}
}
return o;
}
return item;
}
|
javascript
|
function cloner(deep, item) {
if (!item ||
typeof item !== 'object' ||
item instanceof Error ||
item instanceof MonkeyDefinition ||
item instanceof Monkey ||
('ArrayBuffer' in global && item instanceof ArrayBuffer))
return item;
// Array
if (type.array(item)) {
if (deep) {
const a = new Array(item.length);
for (let i = 0, l = item.length; i < l; i++)
a[i] = cloner(true, item[i]);
return a;
}
return slice(item);
}
// Date
if (item instanceof Date)
return new Date(item.getTime());
// RegExp
if (item instanceof RegExp)
return cloneRegexp(item);
// Object
if (type.object(item)) {
const o = {};
// NOTE: could be possible to erase computed properties through `null`.
const props = Object.getOwnPropertyNames(item);
for (let i = 0, l = props.length; i < l; i++) {
const name = props[i];
const k = Object.getOwnPropertyDescriptor(item, name);
if (k.enumerable === true) {
if (k.get && k.get.isLazyGetter) {
Object.defineProperty(o, name, {
get: k.get,
enumerable: true,
configurable: true
});
}
else {
o[name] = deep ? cloner(true, item[name]) : item[name];
}
}
else if (k.enumerable === false) {
Object.defineProperty(o, name, {
value: deep ? cloner(true, k.value) : k.value,
enumerable: false,
writable: true,
configurable: true
});
}
}
return o;
}
return item;
}
|
[
"function",
"cloner",
"(",
"deep",
",",
"item",
")",
"{",
"if",
"(",
"!",
"item",
"||",
"typeof",
"item",
"!==",
"'object'",
"||",
"item",
"instanceof",
"Error",
"||",
"item",
"instanceof",
"MonkeyDefinition",
"||",
"item",
"instanceof",
"Monkey",
"||",
"(",
"'ArrayBuffer'",
"in",
"global",
"&&",
"item",
"instanceof",
"ArrayBuffer",
")",
")",
"return",
"item",
";",
"// Array",
"if",
"(",
"type",
".",
"array",
"(",
"item",
")",
")",
"{",
"if",
"(",
"deep",
")",
"{",
"const",
"a",
"=",
"new",
"Array",
"(",
"item",
".",
"length",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"l",
"=",
"item",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"a",
"[",
"i",
"]",
"=",
"cloner",
"(",
"true",
",",
"item",
"[",
"i",
"]",
")",
";",
"return",
"a",
";",
"}",
"return",
"slice",
"(",
"item",
")",
";",
"}",
"// Date",
"if",
"(",
"item",
"instanceof",
"Date",
")",
"return",
"new",
"Date",
"(",
"item",
".",
"getTime",
"(",
")",
")",
";",
"// RegExp",
"if",
"(",
"item",
"instanceof",
"RegExp",
")",
"return",
"cloneRegexp",
"(",
"item",
")",
";",
"// Object",
"if",
"(",
"type",
".",
"object",
"(",
"item",
")",
")",
"{",
"const",
"o",
"=",
"{",
"}",
";",
"// NOTE: could be possible to erase computed properties through `null`.",
"const",
"props",
"=",
"Object",
".",
"getOwnPropertyNames",
"(",
"item",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"l",
"=",
"props",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"const",
"name",
"=",
"props",
"[",
"i",
"]",
";",
"const",
"k",
"=",
"Object",
".",
"getOwnPropertyDescriptor",
"(",
"item",
",",
"name",
")",
";",
"if",
"(",
"k",
".",
"enumerable",
"===",
"true",
")",
"{",
"if",
"(",
"k",
".",
"get",
"&&",
"k",
".",
"get",
".",
"isLazyGetter",
")",
"{",
"Object",
".",
"defineProperty",
"(",
"o",
",",
"name",
",",
"{",
"get",
":",
"k",
".",
"get",
",",
"enumerable",
":",
"true",
",",
"configurable",
":",
"true",
"}",
")",
";",
"}",
"else",
"{",
"o",
"[",
"name",
"]",
"=",
"deep",
"?",
"cloner",
"(",
"true",
",",
"item",
"[",
"name",
"]",
")",
":",
"item",
"[",
"name",
"]",
";",
"}",
"}",
"else",
"if",
"(",
"k",
".",
"enumerable",
"===",
"false",
")",
"{",
"Object",
".",
"defineProperty",
"(",
"o",
",",
"name",
",",
"{",
"value",
":",
"deep",
"?",
"cloner",
"(",
"true",
",",
"k",
".",
"value",
")",
":",
"k",
".",
"value",
",",
"enumerable",
":",
"false",
",",
"writable",
":",
"true",
",",
"configurable",
":",
"true",
"}",
")",
";",
"}",
"}",
"return",
"o",
";",
"}",
"return",
"item",
";",
"}"
] |
Function cloning the given variable.
@todo: implement a faster way to clone an array.
@param {boolean} deep - Should we deep clone the variable.
@param {mixed} item - The variable to clone
@return {mixed} - The cloned variable.
|
[
"Function",
"cloning",
"the",
"given",
"variable",
"."
] |
d0b7319117d929efb585b031ccebd01c13310f6e
|
https://github.com/Yomguithereal/baobab/blob/d0b7319117d929efb585b031ccebd01c13310f6e/src/helpers.js#L167-L231
|
13,564
|
Yomguithereal/baobab
|
src/helpers.js
|
compare
|
function compare(object, description) {
let ok = true,
k;
// If we reached here via a recursive call, object may be undefined because
// not all items in a collection will have the same deep nesting structure.
if (!object)
return false;
for (k in description) {
if (type.object(description[k])) {
ok = ok && compare(object[k], description[k]);
}
else if (type.array(description[k])) {
ok = ok && !!~description[k].indexOf(object[k]);
}
else {
if (object[k] !== description[k])
return false;
}
}
return ok;
}
|
javascript
|
function compare(object, description) {
let ok = true,
k;
// If we reached here via a recursive call, object may be undefined because
// not all items in a collection will have the same deep nesting structure.
if (!object)
return false;
for (k in description) {
if (type.object(description[k])) {
ok = ok && compare(object[k], description[k]);
}
else if (type.array(description[k])) {
ok = ok && !!~description[k].indexOf(object[k]);
}
else {
if (object[k] !== description[k])
return false;
}
}
return ok;
}
|
[
"function",
"compare",
"(",
"object",
",",
"description",
")",
"{",
"let",
"ok",
"=",
"true",
",",
"k",
";",
"// If we reached here via a recursive call, object may be undefined because",
"// not all items in a collection will have the same deep nesting structure.",
"if",
"(",
"!",
"object",
")",
"return",
"false",
";",
"for",
"(",
"k",
"in",
"description",
")",
"{",
"if",
"(",
"type",
".",
"object",
"(",
"description",
"[",
"k",
"]",
")",
")",
"{",
"ok",
"=",
"ok",
"&&",
"compare",
"(",
"object",
"[",
"k",
"]",
",",
"description",
"[",
"k",
"]",
")",
";",
"}",
"else",
"if",
"(",
"type",
".",
"array",
"(",
"description",
"[",
"k",
"]",
")",
")",
"{",
"ok",
"=",
"ok",
"&&",
"!",
"!",
"~",
"description",
"[",
"k",
"]",
".",
"indexOf",
"(",
"object",
"[",
"k",
"]",
")",
";",
"}",
"else",
"{",
"if",
"(",
"object",
"[",
"k",
"]",
"!==",
"description",
"[",
"k",
"]",
")",
"return",
"false",
";",
"}",
"}",
"return",
"ok",
";",
"}"
] |
Function comparing an object's properties to a given descriptive
object.
@param {object} object - The object to compare.
@param {object} description - The description's mapping.
@return {boolean} - Whether the object matches the description.
|
[
"Function",
"comparing",
"an",
"object",
"s",
"properties",
"to",
"a",
"given",
"descriptive",
"object",
"."
] |
d0b7319117d929efb585b031ccebd01c13310f6e
|
https://github.com/Yomguithereal/baobab/blob/d0b7319117d929efb585b031ccebd01c13310f6e/src/helpers.js#L261-L284
|
13,565
|
Yomguithereal/baobab
|
src/helpers.js
|
freezer
|
function freezer(deep, o) {
if (typeof o !== 'object' ||
o === null ||
o instanceof Monkey)
return;
Object.freeze(o);
if (!deep)
return;
if (Array.isArray(o)) {
// Iterating through the elements
let i,
l;
for (i = 0, l = o.length; i < l; i++)
deepFreeze(o[i]);
}
else {
let p,
k;
for (k in o) {
if (type.lazyGetter(o, k))
continue;
p = o[k];
if (!p ||
!hasOwnProp.call(o, k) ||
typeof p !== 'object' ||
Object.isFrozen(p))
continue;
deepFreeze(p);
}
}
}
|
javascript
|
function freezer(deep, o) {
if (typeof o !== 'object' ||
o === null ||
o instanceof Monkey)
return;
Object.freeze(o);
if (!deep)
return;
if (Array.isArray(o)) {
// Iterating through the elements
let i,
l;
for (i = 0, l = o.length; i < l; i++)
deepFreeze(o[i]);
}
else {
let p,
k;
for (k in o) {
if (type.lazyGetter(o, k))
continue;
p = o[k];
if (!p ||
!hasOwnProp.call(o, k) ||
typeof p !== 'object' ||
Object.isFrozen(p))
continue;
deepFreeze(p);
}
}
}
|
[
"function",
"freezer",
"(",
"deep",
",",
"o",
")",
"{",
"if",
"(",
"typeof",
"o",
"!==",
"'object'",
"||",
"o",
"===",
"null",
"||",
"o",
"instanceof",
"Monkey",
")",
"return",
";",
"Object",
".",
"freeze",
"(",
"o",
")",
";",
"if",
"(",
"!",
"deep",
")",
"return",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"o",
")",
")",
"{",
"// Iterating through the elements",
"let",
"i",
",",
"l",
";",
"for",
"(",
"i",
"=",
"0",
",",
"l",
"=",
"o",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"deepFreeze",
"(",
"o",
"[",
"i",
"]",
")",
";",
"}",
"else",
"{",
"let",
"p",
",",
"k",
";",
"for",
"(",
"k",
"in",
"o",
")",
"{",
"if",
"(",
"type",
".",
"lazyGetter",
"(",
"o",
",",
"k",
")",
")",
"continue",
";",
"p",
"=",
"o",
"[",
"k",
"]",
";",
"if",
"(",
"!",
"p",
"||",
"!",
"hasOwnProp",
".",
"call",
"(",
"o",
",",
"k",
")",
"||",
"typeof",
"p",
"!==",
"'object'",
"||",
"Object",
".",
"isFrozen",
"(",
"p",
")",
")",
"continue",
";",
"deepFreeze",
"(",
"p",
")",
";",
"}",
"}",
"}"
] |
Function freezing the given variable if possible.
@param {boolean} deep - Should we recursively freeze the given objects?
@param {object} o - The variable to freeze.
@return {object} - The merged object.
|
[
"Function",
"freezing",
"the",
"given",
"variable",
"if",
"possible",
"."
] |
d0b7319117d929efb585b031ccebd01c13310f6e
|
https://github.com/Yomguithereal/baobab/blob/d0b7319117d929efb585b031ccebd01c13310f6e/src/helpers.js#L293-L332
|
13,566
|
Yomguithereal/baobab
|
src/cursor.js
|
makeSetter
|
function makeSetter(name, typeChecker) {
/**
* Binding a setter method to the Cursor class and having the following
* definition.
*
* Note: this is not really possible to make those setters variadic because
* it would create an impossible polymorphism with path.
*
* @todo: perform value validation elsewhere so that tree.update can
* beneficiate from it.
*
* Arity (1):
* @param {mixed} value - New value to set at cursor's path.
*
* Arity (2):
* @param {path} path - Subpath to update starting from cursor's.
* @param {mixed} value - New value to set.
*
* @return {mixed} - Data at path.
*/
Cursor.prototype[name] = function(path, value) {
// We should warn the user if he applies to many arguments to the function
if (arguments.length > 2)
throw makeError(`Baobab.Cursor.${name}: too many arguments.`);
// Handling arities
if (arguments.length === 1 && !INTRANSITIVE_SETTERS[name]) {
value = path;
path = [];
}
// Coerce path
path = coercePath(path);
// Checking the path's validity
if (!type.path(path))
throw makeError(`Baobab.Cursor.${name}: invalid path.`, {path});
// Checking the value's validity
if (typeChecker && !typeChecker(value))
throw makeError(`Baobab.Cursor.${name}: invalid value.`, {path, value});
// Checking the solvability of the cursor's dynamic path
if (!this.solvedPath)
throw makeError(
`Baobab.Cursor.${name}: the dynamic path of the cursor cannot be solved.`,
{path: this.path}
);
const fullPath = this.solvedPath.concat(path);
// Filing the update to the tree
return this.tree.update(
fullPath,
{
type: name,
value
}
);
};
}
|
javascript
|
function makeSetter(name, typeChecker) {
/**
* Binding a setter method to the Cursor class and having the following
* definition.
*
* Note: this is not really possible to make those setters variadic because
* it would create an impossible polymorphism with path.
*
* @todo: perform value validation elsewhere so that tree.update can
* beneficiate from it.
*
* Arity (1):
* @param {mixed} value - New value to set at cursor's path.
*
* Arity (2):
* @param {path} path - Subpath to update starting from cursor's.
* @param {mixed} value - New value to set.
*
* @return {mixed} - Data at path.
*/
Cursor.prototype[name] = function(path, value) {
// We should warn the user if he applies to many arguments to the function
if (arguments.length > 2)
throw makeError(`Baobab.Cursor.${name}: too many arguments.`);
// Handling arities
if (arguments.length === 1 && !INTRANSITIVE_SETTERS[name]) {
value = path;
path = [];
}
// Coerce path
path = coercePath(path);
// Checking the path's validity
if (!type.path(path))
throw makeError(`Baobab.Cursor.${name}: invalid path.`, {path});
// Checking the value's validity
if (typeChecker && !typeChecker(value))
throw makeError(`Baobab.Cursor.${name}: invalid value.`, {path, value});
// Checking the solvability of the cursor's dynamic path
if (!this.solvedPath)
throw makeError(
`Baobab.Cursor.${name}: the dynamic path of the cursor cannot be solved.`,
{path: this.path}
);
const fullPath = this.solvedPath.concat(path);
// Filing the update to the tree
return this.tree.update(
fullPath,
{
type: name,
value
}
);
};
}
|
[
"function",
"makeSetter",
"(",
"name",
",",
"typeChecker",
")",
"{",
"/**\n * Binding a setter method to the Cursor class and having the following\n * definition.\n *\n * Note: this is not really possible to make those setters variadic because\n * it would create an impossible polymorphism with path.\n *\n * @todo: perform value validation elsewhere so that tree.update can\n * beneficiate from it.\n *\n * Arity (1):\n * @param {mixed} value - New value to set at cursor's path.\n *\n * Arity (2):\n * @param {path} path - Subpath to update starting from cursor's.\n * @param {mixed} value - New value to set.\n *\n * @return {mixed} - Data at path.\n */",
"Cursor",
".",
"prototype",
"[",
"name",
"]",
"=",
"function",
"(",
"path",
",",
"value",
")",
"{",
"// We should warn the user if he applies to many arguments to the function",
"if",
"(",
"arguments",
".",
"length",
">",
"2",
")",
"throw",
"makeError",
"(",
"`",
"${",
"name",
"}",
"`",
")",
";",
"// Handling arities",
"if",
"(",
"arguments",
".",
"length",
"===",
"1",
"&&",
"!",
"INTRANSITIVE_SETTERS",
"[",
"name",
"]",
")",
"{",
"value",
"=",
"path",
";",
"path",
"=",
"[",
"]",
";",
"}",
"// Coerce path",
"path",
"=",
"coercePath",
"(",
"path",
")",
";",
"// Checking the path's validity",
"if",
"(",
"!",
"type",
".",
"path",
"(",
"path",
")",
")",
"throw",
"makeError",
"(",
"`",
"${",
"name",
"}",
"`",
",",
"{",
"path",
"}",
")",
";",
"// Checking the value's validity",
"if",
"(",
"typeChecker",
"&&",
"!",
"typeChecker",
"(",
"value",
")",
")",
"throw",
"makeError",
"(",
"`",
"${",
"name",
"}",
"`",
",",
"{",
"path",
",",
"value",
"}",
")",
";",
"// Checking the solvability of the cursor's dynamic path",
"if",
"(",
"!",
"this",
".",
"solvedPath",
")",
"throw",
"makeError",
"(",
"`",
"${",
"name",
"}",
"`",
",",
"{",
"path",
":",
"this",
".",
"path",
"}",
")",
";",
"const",
"fullPath",
"=",
"this",
".",
"solvedPath",
".",
"concat",
"(",
"path",
")",
";",
"// Filing the update to the tree",
"return",
"this",
".",
"tree",
".",
"update",
"(",
"fullPath",
",",
"{",
"type",
":",
"name",
",",
"value",
"}",
")",
";",
"}",
";",
"}"
] |
Function creating a setter method for the Cursor class.
@param {string} name - the method's name.
@param {function} [typeChecker] - a function checking that the given value is
valid for the given operation.
|
[
"Function",
"creating",
"a",
"setter",
"method",
"for",
"the",
"Cursor",
"class",
"."
] |
d0b7319117d929efb585b031ccebd01c13310f6e
|
https://github.com/Yomguithereal/baobab/blob/d0b7319117d929efb585b031ccebd01c13310f6e/src/cursor.js#L777-L839
|
13,567
|
toomuchdesign/react-minimal-pie-chart
|
src/ReactMinimalPieChart.js
|
extendData
|
function extendData({
data,
lengthAngle: totalAngle,
totalValue,
paddingAngle,
}) {
const total = totalValue || sumValues(data);
const normalizedTotalAngle = valueBetween(totalAngle, -360, 360);
const numberOfPaddings =
Math.abs(normalizedTotalAngle) === 360 ? data.length : data.length - 1;
const degreesTakenByPadding =
Math.abs(paddingAngle) * numberOfPaddings * Math.sign(normalizedTotalAngle);
const singlePaddingDegrees = degreesTakenByPadding / numberOfPaddings;
const degreesTakenByPaths = normalizedTotalAngle - degreesTakenByPadding;
let lastSegmentEnd = 0;
return data.map(dataEntry => {
const valueInPercentage = (dataEntry.value / total) * 100;
const degrees = extractPercentage(degreesTakenByPaths, valueInPercentage);
const startOffset = lastSegmentEnd;
lastSegmentEnd = lastSegmentEnd + degrees + singlePaddingDegrees;
return {
percentage: valueInPercentage,
degrees,
startOffset,
...dataEntry,
};
});
}
|
javascript
|
function extendData({
data,
lengthAngle: totalAngle,
totalValue,
paddingAngle,
}) {
const total = totalValue || sumValues(data);
const normalizedTotalAngle = valueBetween(totalAngle, -360, 360);
const numberOfPaddings =
Math.abs(normalizedTotalAngle) === 360 ? data.length : data.length - 1;
const degreesTakenByPadding =
Math.abs(paddingAngle) * numberOfPaddings * Math.sign(normalizedTotalAngle);
const singlePaddingDegrees = degreesTakenByPadding / numberOfPaddings;
const degreesTakenByPaths = normalizedTotalAngle - degreesTakenByPadding;
let lastSegmentEnd = 0;
return data.map(dataEntry => {
const valueInPercentage = (dataEntry.value / total) * 100;
const degrees = extractPercentage(degreesTakenByPaths, valueInPercentage);
const startOffset = lastSegmentEnd;
lastSegmentEnd = lastSegmentEnd + degrees + singlePaddingDegrees;
return {
percentage: valueInPercentage,
degrees,
startOffset,
...dataEntry,
};
});
}
|
[
"function",
"extendData",
"(",
"{",
"data",
",",
"lengthAngle",
":",
"totalAngle",
",",
"totalValue",
",",
"paddingAngle",
",",
"}",
")",
"{",
"const",
"total",
"=",
"totalValue",
"||",
"sumValues",
"(",
"data",
")",
";",
"const",
"normalizedTotalAngle",
"=",
"valueBetween",
"(",
"totalAngle",
",",
"-",
"360",
",",
"360",
")",
";",
"const",
"numberOfPaddings",
"=",
"Math",
".",
"abs",
"(",
"normalizedTotalAngle",
")",
"===",
"360",
"?",
"data",
".",
"length",
":",
"data",
".",
"length",
"-",
"1",
";",
"const",
"degreesTakenByPadding",
"=",
"Math",
".",
"abs",
"(",
"paddingAngle",
")",
"*",
"numberOfPaddings",
"*",
"Math",
".",
"sign",
"(",
"normalizedTotalAngle",
")",
";",
"const",
"singlePaddingDegrees",
"=",
"degreesTakenByPadding",
"/",
"numberOfPaddings",
";",
"const",
"degreesTakenByPaths",
"=",
"normalizedTotalAngle",
"-",
"degreesTakenByPadding",
";",
"let",
"lastSegmentEnd",
"=",
"0",
";",
"return",
"data",
".",
"map",
"(",
"dataEntry",
"=>",
"{",
"const",
"valueInPercentage",
"=",
"(",
"dataEntry",
".",
"value",
"/",
"total",
")",
"*",
"100",
";",
"const",
"degrees",
"=",
"extractPercentage",
"(",
"degreesTakenByPaths",
",",
"valueInPercentage",
")",
";",
"const",
"startOffset",
"=",
"lastSegmentEnd",
";",
"lastSegmentEnd",
"=",
"lastSegmentEnd",
"+",
"degrees",
"+",
"singlePaddingDegrees",
";",
"return",
"{",
"percentage",
":",
"valueInPercentage",
",",
"degrees",
",",
"startOffset",
",",
"...",
"dataEntry",
",",
"}",
";",
"}",
")",
";",
"}"
] |
Append "percentage", "degrees" and "startOffset" into each data entry
|
[
"Append",
"percentage",
"degrees",
"and",
"startOffset",
"into",
"each",
"data",
"entry"
] |
03158af5ddecde83361909ccd185ae8b5064bdf5
|
https://github.com/toomuchdesign/react-minimal-pie-chart/blob/03158af5ddecde83361909ccd185ae8b5064bdf5/src/ReactMinimalPieChart.js#L22-L51
|
13,568
|
HubSpot/Singularity
|
SingularityUI/gulpfile.js
|
function(req, res, next) {
if (req.headers.accept && req.headers.accept.startsWith('text/html')) {
req.url = '/index.html'; // eslint-disable-line no-param-reassign
}
next();
}
|
javascript
|
function(req, res, next) {
if (req.headers.accept && req.headers.accept.startsWith('text/html')) {
req.url = '/index.html'; // eslint-disable-line no-param-reassign
}
next();
}
|
[
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"if",
"(",
"req",
".",
"headers",
".",
"accept",
"&&",
"req",
".",
"headers",
".",
"accept",
".",
"startsWith",
"(",
"'text/html'",
")",
")",
"{",
"req",
".",
"url",
"=",
"'/index.html'",
";",
"// eslint-disable-line no-param-reassign",
"}",
"next",
"(",
")",
";",
"}"
] |
Serve index.html for all unknown requests
|
[
"Serve",
"index",
".",
"html",
"for",
"all",
"unknown",
"requests"
] |
2402934c40c8f86670c703d87e3016de3bab5a26
|
https://github.com/HubSpot/Singularity/blob/2402934c40c8f86670c703d87e3016de3bab5a26/SingularityUI/gulpfile.js#L130-L135
|
|
13,569
|
AndiDittrich/Node.CLI-Progress
|
examples/example-align.js
|
showPreset
|
function showPreset(name, pos){
console.log(_colors.magenta('Preset: ' + name));
// create a new progress bar with preset
var bar = new _progress.Bar({
align: pos
}, _progress.Presets[name] || _progress.Presets.legacy);
bar.start(200, 0);
// random value 1..200
bar.update(Math.floor((Math.random() * 200) + 1));
bar.stop();
console.log('');
}
|
javascript
|
function showPreset(name, pos){
console.log(_colors.magenta('Preset: ' + name));
// create a new progress bar with preset
var bar = new _progress.Bar({
align: pos
}, _progress.Presets[name] || _progress.Presets.legacy);
bar.start(200, 0);
// random value 1..200
bar.update(Math.floor((Math.random() * 200) + 1));
bar.stop();
console.log('');
}
|
[
"function",
"showPreset",
"(",
"name",
",",
"pos",
")",
"{",
"console",
".",
"log",
"(",
"_colors",
".",
"magenta",
"(",
"'Preset: '",
"+",
"name",
")",
")",
";",
"// create a new progress bar with preset",
"var",
"bar",
"=",
"new",
"_progress",
".",
"Bar",
"(",
"{",
"align",
":",
"pos",
"}",
",",
"_progress",
".",
"Presets",
"[",
"name",
"]",
"||",
"_progress",
".",
"Presets",
".",
"legacy",
")",
";",
"bar",
".",
"start",
"(",
"200",
",",
"0",
")",
";",
"// random value 1..200",
"bar",
".",
"update",
"(",
"Math",
".",
"floor",
"(",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"200",
")",
"+",
"1",
")",
")",
";",
"bar",
".",
"stop",
"(",
")",
";",
"console",
".",
"log",
"(",
"''",
")",
";",
"}"
] |
helper function to display preset
|
[
"helper",
"function",
"to",
"display",
"preset"
] |
5cb2a261a604d272e7a4019e66c2954547bea696
|
https://github.com/AndiDittrich/Node.CLI-Progress/blob/5cb2a261a604d272e7a4019e66c2954547bea696/examples/example-align.js#L5-L18
|
13,570
|
IonicaBizau/github-contributions
|
lib/contributions/calendar.js
|
getDateTime
|
function getDateTime(obj) {
// get date, hour, minute, second, year, month and day
var date = new Date()
, hour = date.getHours()
, min = date.getMinutes()
, sec = date.getSeconds()
, year = date.getFullYear()
, month = date.getMonth() + 1
, day = date.getDate()
;
// add `0` if needed
hour = padWithZero(hour);
min = padWithZero(min);
sec = padWithZero(sec);
month = padWithZero(month);
day = padWithZero(day);
// obj is true, return an object
if (obj) {
return {
year: year,
month: parseInt(month),
day: parseInt(day),
cDay: date.getDay()
}
}
// return a string
return year + "-" + month + "-" + day;
}
|
javascript
|
function getDateTime(obj) {
// get date, hour, minute, second, year, month and day
var date = new Date()
, hour = date.getHours()
, min = date.getMinutes()
, sec = date.getSeconds()
, year = date.getFullYear()
, month = date.getMonth() + 1
, day = date.getDate()
;
// add `0` if needed
hour = padWithZero(hour);
min = padWithZero(min);
sec = padWithZero(sec);
month = padWithZero(month);
day = padWithZero(day);
// obj is true, return an object
if (obj) {
return {
year: year,
month: parseInt(month),
day: parseInt(day),
cDay: date.getDay()
}
}
// return a string
return year + "-" + month + "-" + day;
}
|
[
"function",
"getDateTime",
"(",
"obj",
")",
"{",
"// get date, hour, minute, second, year, month and day",
"var",
"date",
"=",
"new",
"Date",
"(",
")",
",",
"hour",
"=",
"date",
".",
"getHours",
"(",
")",
",",
"min",
"=",
"date",
".",
"getMinutes",
"(",
")",
",",
"sec",
"=",
"date",
".",
"getSeconds",
"(",
")",
",",
"year",
"=",
"date",
".",
"getFullYear",
"(",
")",
",",
"month",
"=",
"date",
".",
"getMonth",
"(",
")",
"+",
"1",
",",
"day",
"=",
"date",
".",
"getDate",
"(",
")",
";",
"// add `0` if needed",
"hour",
"=",
"padWithZero",
"(",
"hour",
")",
";",
"min",
"=",
"padWithZero",
"(",
"min",
")",
";",
"sec",
"=",
"padWithZero",
"(",
"sec",
")",
";",
"month",
"=",
"padWithZero",
"(",
"month",
")",
";",
"day",
"=",
"padWithZero",
"(",
"day",
")",
";",
"// obj is true, return an object",
"if",
"(",
"obj",
")",
"{",
"return",
"{",
"year",
":",
"year",
",",
"month",
":",
"parseInt",
"(",
"month",
")",
",",
"day",
":",
"parseInt",
"(",
"day",
")",
",",
"cDay",
":",
"date",
".",
"getDay",
"(",
")",
"}",
"}",
"// return a string",
"return",
"year",
"+",
"\"-\"",
"+",
"month",
"+",
"\"-\"",
"+",
"day",
";",
"}"
] |
Returns the time in the moment when it's called
If `obj` is true an object is returned
|
[
"Returns",
"the",
"time",
"in",
"the",
"moment",
"when",
"it",
"s",
"called",
"If",
"obj",
"is",
"true",
"an",
"object",
"is",
"returned"
] |
6c3eeb7613f779603b911d35ac4ffb6b0d52b514
|
https://github.com/IonicaBizau/github-contributions/blob/6c3eeb7613f779603b911d35ac4ffb6b0d52b514/lib/contributions/calendar.js#L6-L37
|
13,571
|
IonicaBizau/github-contributions
|
lib/client_handler/index.js
|
Openfile
|
function Openfile(i, path) {
// !Optimized: use child_process module to open local file with local path
(function() {
var cmdArr = [
'nautilus ' + path
, 'start "" "' + path + '"'
, 'konqueror ' + path
, 'open ' + path
]
;
if (i >= cmdArr.length) {
client.emit("complete", {
error: null
, output: path
, mannual: true
});
}
// recursive calling
exec(cmdArr[i], function (err, stdout, stderr) {
if (err == null) {
// Success
client.emit("complete", {
error: null
, output: path
, mannual: false
});
} else {
Openfile(++i, path);
}
});
})();
}
|
javascript
|
function Openfile(i, path) {
// !Optimized: use child_process module to open local file with local path
(function() {
var cmdArr = [
'nautilus ' + path
, 'start "" "' + path + '"'
, 'konqueror ' + path
, 'open ' + path
]
;
if (i >= cmdArr.length) {
client.emit("complete", {
error: null
, output: path
, mannual: true
});
}
// recursive calling
exec(cmdArr[i], function (err, stdout, stderr) {
if (err == null) {
// Success
client.emit("complete", {
error: null
, output: path
, mannual: false
});
} else {
Openfile(++i, path);
}
});
})();
}
|
[
"function",
"Openfile",
"(",
"i",
",",
"path",
")",
"{",
"// !Optimized: use child_process module to open local file with local path",
"(",
"function",
"(",
")",
"{",
"var",
"cmdArr",
"=",
"[",
"'nautilus '",
"+",
"path",
",",
"'start \"\" \"'",
"+",
"path",
"+",
"'\"'",
",",
"'konqueror '",
"+",
"path",
",",
"'open '",
"+",
"path",
"]",
";",
"if",
"(",
"i",
">=",
"cmdArr",
".",
"length",
")",
"{",
"client",
".",
"emit",
"(",
"\"complete\"",
",",
"{",
"error",
":",
"null",
",",
"output",
":",
"path",
",",
"mannual",
":",
"true",
"}",
")",
";",
"}",
"// recursive calling",
"exec",
"(",
"cmdArr",
"[",
"i",
"]",
",",
"function",
"(",
"err",
",",
"stdout",
",",
"stderr",
")",
"{",
"if",
"(",
"err",
"==",
"null",
")",
"{",
"// Success",
"client",
".",
"emit",
"(",
"\"complete\"",
",",
"{",
"error",
":",
"null",
",",
"output",
":",
"path",
",",
"mannual",
":",
"false",
"}",
")",
";",
"}",
"else",
"{",
"Openfile",
"(",
"++",
"i",
",",
"path",
")",
";",
"}",
"}",
")",
";",
"}",
")",
"(",
")",
";",
"}"
] |
Use Script to open local file with local path
|
[
"Use",
"Script",
"to",
"open",
"local",
"file",
"with",
"local",
"path"
] |
6c3eeb7613f779603b911d35ac4ffb6b0d52b514
|
https://github.com/IonicaBizau/github-contributions/blob/6c3eeb7613f779603b911d35ac4ffb6b0d52b514/lib/client_handler/index.js#L37-L70
|
13,572
|
gdsestimating/dxf-parser
|
src/DxfArrayScanner.js
|
parseGroupValue
|
function parseGroupValue(code, value) {
if(code <= 9) return value;
if(code >= 10 && code <= 59) return parseFloat(value);
if(code >= 60 && code <= 99) return parseInt(value);
if(code >= 100 && code <= 109) return value;
if(code >= 110 && code <= 149) return parseFloat(value);
if(code >= 160 && code <= 179) return parseInt(value);
if(code >= 210 && code <= 239) return parseFloat(value);
if(code >= 270 && code <= 289) return parseInt(value);
if(code >= 290 && code <= 299) return parseBoolean(value);
if(code >= 300 && code <= 369) return value;
if(code >= 370 && code <= 389) return parseInt(value);
if(code >= 390 && code <= 399) return value;
if(code >= 400 && code <= 409) return parseInt(value);
if(code >= 410 && code <= 419) return value;
if(code >= 420 && code <= 429) return parseInt(value);
if(code >= 430 && code <= 439) return value;
if(code >= 440 && code <= 459) return parseInt(value);
if(code >= 460 && code <= 469) return parseFloat(value);
if(code >= 470 && code <= 481) return value;
if(code === 999) return value;
if(code >= 1000 && code <= 1009) return value;
if(code >= 1010 && code <= 1059) return parseFloat(value);
if(code >= 1060 && code <= 1071) return parseInt(value);
console.log('WARNING: Group code does not have a defined type: %j', { code: code, value: value });
return value;
}
|
javascript
|
function parseGroupValue(code, value) {
if(code <= 9) return value;
if(code >= 10 && code <= 59) return parseFloat(value);
if(code >= 60 && code <= 99) return parseInt(value);
if(code >= 100 && code <= 109) return value;
if(code >= 110 && code <= 149) return parseFloat(value);
if(code >= 160 && code <= 179) return parseInt(value);
if(code >= 210 && code <= 239) return parseFloat(value);
if(code >= 270 && code <= 289) return parseInt(value);
if(code >= 290 && code <= 299) return parseBoolean(value);
if(code >= 300 && code <= 369) return value;
if(code >= 370 && code <= 389) return parseInt(value);
if(code >= 390 && code <= 399) return value;
if(code >= 400 && code <= 409) return parseInt(value);
if(code >= 410 && code <= 419) return value;
if(code >= 420 && code <= 429) return parseInt(value);
if(code >= 430 && code <= 439) return value;
if(code >= 440 && code <= 459) return parseInt(value);
if(code >= 460 && code <= 469) return parseFloat(value);
if(code >= 470 && code <= 481) return value;
if(code === 999) return value;
if(code >= 1000 && code <= 1009) return value;
if(code >= 1010 && code <= 1059) return parseFloat(value);
if(code >= 1060 && code <= 1071) return parseInt(value);
console.log('WARNING: Group code does not have a defined type: %j', { code: code, value: value });
return value;
}
|
[
"function",
"parseGroupValue",
"(",
"code",
",",
"value",
")",
"{",
"if",
"(",
"code",
"<=",
"9",
")",
"return",
"value",
";",
"if",
"(",
"code",
">=",
"10",
"&&",
"code",
"<=",
"59",
")",
"return",
"parseFloat",
"(",
"value",
")",
";",
"if",
"(",
"code",
">=",
"60",
"&&",
"code",
"<=",
"99",
")",
"return",
"parseInt",
"(",
"value",
")",
";",
"if",
"(",
"code",
">=",
"100",
"&&",
"code",
"<=",
"109",
")",
"return",
"value",
";",
"if",
"(",
"code",
">=",
"110",
"&&",
"code",
"<=",
"149",
")",
"return",
"parseFloat",
"(",
"value",
")",
";",
"if",
"(",
"code",
">=",
"160",
"&&",
"code",
"<=",
"179",
")",
"return",
"parseInt",
"(",
"value",
")",
";",
"if",
"(",
"code",
">=",
"210",
"&&",
"code",
"<=",
"239",
")",
"return",
"parseFloat",
"(",
"value",
")",
";",
"if",
"(",
"code",
">=",
"270",
"&&",
"code",
"<=",
"289",
")",
"return",
"parseInt",
"(",
"value",
")",
";",
"if",
"(",
"code",
">=",
"290",
"&&",
"code",
"<=",
"299",
")",
"return",
"parseBoolean",
"(",
"value",
")",
";",
"if",
"(",
"code",
">=",
"300",
"&&",
"code",
"<=",
"369",
")",
"return",
"value",
";",
"if",
"(",
"code",
">=",
"370",
"&&",
"code",
"<=",
"389",
")",
"return",
"parseInt",
"(",
"value",
")",
";",
"if",
"(",
"code",
">=",
"390",
"&&",
"code",
"<=",
"399",
")",
"return",
"value",
";",
"if",
"(",
"code",
">=",
"400",
"&&",
"code",
"<=",
"409",
")",
"return",
"parseInt",
"(",
"value",
")",
";",
"if",
"(",
"code",
">=",
"410",
"&&",
"code",
"<=",
"419",
")",
"return",
"value",
";",
"if",
"(",
"code",
">=",
"420",
"&&",
"code",
"<=",
"429",
")",
"return",
"parseInt",
"(",
"value",
")",
";",
"if",
"(",
"code",
">=",
"430",
"&&",
"code",
"<=",
"439",
")",
"return",
"value",
";",
"if",
"(",
"code",
">=",
"440",
"&&",
"code",
"<=",
"459",
")",
"return",
"parseInt",
"(",
"value",
")",
";",
"if",
"(",
"code",
">=",
"460",
"&&",
"code",
"<=",
"469",
")",
"return",
"parseFloat",
"(",
"value",
")",
";",
"if",
"(",
"code",
">=",
"470",
"&&",
"code",
"<=",
"481",
")",
"return",
"value",
";",
"if",
"(",
"code",
"===",
"999",
")",
"return",
"value",
";",
"if",
"(",
"code",
">=",
"1000",
"&&",
"code",
"<=",
"1009",
")",
"return",
"value",
";",
"if",
"(",
"code",
">=",
"1010",
"&&",
"code",
"<=",
"1059",
")",
"return",
"parseFloat",
"(",
"value",
")",
";",
"if",
"(",
"code",
">=",
"1060",
"&&",
"code",
"<=",
"1071",
")",
"return",
"parseInt",
"(",
"value",
")",
";",
"console",
".",
"log",
"(",
"'WARNING: Group code does not have a defined type: %j'",
",",
"{",
"code",
":",
"code",
",",
"value",
":",
"value",
"}",
")",
";",
"return",
"value",
";",
"}"
] |
Parse a value to its proper type.
See pages 3 - 10 of the AutoCad DXF 2012 reference given at the top of this file
@param code
@param value
@returns {*}
|
[
"Parse",
"a",
"value",
"to",
"its",
"proper",
"type",
".",
"See",
"pages",
"3",
"-",
"10",
"of",
"the",
"AutoCad",
"DXF",
"2012",
"reference",
"given",
"at",
"the",
"top",
"of",
"this",
"file"
] |
887a26af9181c62bb5d016b606882d9897f5b7d7
|
https://github.com/gdsestimating/dxf-parser/blob/887a26af9181c62bb5d016b606882d9897f5b7d7/src/DxfArrayScanner.js#L105-L132
|
13,573
|
bolt-design-system/bolt
|
packages/build-tools/tasks/task-collections.js
|
getExtraTasks
|
async function getExtraTasks() {
config = config || (await getConfig());
switch (config.env) {
case 'pl':
extraTasks.patternLab = require('./pattern-lab-tasks');
break;
case 'static':
extraTasks.static = require('./static-tasks');
break;
case 'pwa':
delete require.cache[require.resolve('./api-tasks')];
extraTasks.api = require('./api-tasks');
extraTasks.patternLab = require('./pattern-lab-tasks');
extraTasks.static = require('./static-tasks');
break;
}
if (config.wwwDir) {
extraTasks.server = require('./server-tasks');
}
return extraTasks;
}
|
javascript
|
async function getExtraTasks() {
config = config || (await getConfig());
switch (config.env) {
case 'pl':
extraTasks.patternLab = require('./pattern-lab-tasks');
break;
case 'static':
extraTasks.static = require('./static-tasks');
break;
case 'pwa':
delete require.cache[require.resolve('./api-tasks')];
extraTasks.api = require('./api-tasks');
extraTasks.patternLab = require('./pattern-lab-tasks');
extraTasks.static = require('./static-tasks');
break;
}
if (config.wwwDir) {
extraTasks.server = require('./server-tasks');
}
return extraTasks;
}
|
[
"async",
"function",
"getExtraTasks",
"(",
")",
"{",
"config",
"=",
"config",
"||",
"(",
"await",
"getConfig",
"(",
")",
")",
";",
"switch",
"(",
"config",
".",
"env",
")",
"{",
"case",
"'pl'",
":",
"extraTasks",
".",
"patternLab",
"=",
"require",
"(",
"'./pattern-lab-tasks'",
")",
";",
"break",
";",
"case",
"'static'",
":",
"extraTasks",
".",
"static",
"=",
"require",
"(",
"'./static-tasks'",
")",
";",
"break",
";",
"case",
"'pwa'",
":",
"delete",
"require",
".",
"cache",
"[",
"require",
".",
"resolve",
"(",
"'./api-tasks'",
")",
"]",
";",
"extraTasks",
".",
"api",
"=",
"require",
"(",
"'./api-tasks'",
")",
";",
"extraTasks",
".",
"patternLab",
"=",
"require",
"(",
"'./pattern-lab-tasks'",
")",
";",
"extraTasks",
".",
"static",
"=",
"require",
"(",
"'./static-tasks'",
")",
";",
"break",
";",
"}",
"if",
"(",
"config",
".",
"wwwDir",
")",
"{",
"extraTasks",
".",
"server",
"=",
"require",
"(",
"'./server-tasks'",
")",
";",
"}",
"return",
"extraTasks",
";",
"}"
] |
These tasks are present based on optional conditions like `config.env` and should only be `require`-ed when it's the right env due to each file's setup where it tries to grab specific files - and of course the tasks should only run in the correct `env` as well.
|
[
"These",
"tasks",
"are",
"present",
"based",
"on",
"optional",
"conditions",
"like",
"config",
".",
"env",
"and",
"should",
"only",
"be",
"require",
"-",
"ed",
"when",
"it",
"s",
"the",
"right",
"env",
"due",
"to",
"each",
"file",
"s",
"setup",
"where",
"it",
"tries",
"to",
"grab",
"specific",
"files",
"-",
"and",
"of",
"course",
"the",
"tasks",
"should",
"only",
"run",
"in",
"the",
"correct",
"env",
"as",
"well",
"."
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/build-tools/tasks/task-collections.js#L17-L40
|
13,574
|
bolt-design-system/bolt
|
packages/build-tools/utils/cache.js
|
getFileHash
|
function getFileHash(filePath, callback) {
var stream = fs.ReadStream(filePath);
var md5sum = crypto.createHash('md5');
stream.on('data', function(data) {
md5sum.update(data);
});
stream.on('end', function() {
callback(md5sum.digest('hex'));
});
}
|
javascript
|
function getFileHash(filePath, callback) {
var stream = fs.ReadStream(filePath);
var md5sum = crypto.createHash('md5');
stream.on('data', function(data) {
md5sum.update(data);
});
stream.on('end', function() {
callback(md5sum.digest('hex'));
});
}
|
[
"function",
"getFileHash",
"(",
"filePath",
",",
"callback",
")",
"{",
"var",
"stream",
"=",
"fs",
".",
"ReadStream",
"(",
"filePath",
")",
";",
"var",
"md5sum",
"=",
"crypto",
".",
"createHash",
"(",
"'md5'",
")",
";",
"stream",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"data",
")",
"{",
"md5sum",
".",
"update",
"(",
"data",
")",
";",
"}",
")",
";",
"stream",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"callback",
"(",
"md5sum",
".",
"digest",
"(",
"'hex'",
")",
")",
";",
"}",
")",
";",
"}"
] |
given the path to a local file being streamed, returns back the MD5 hash to quickly check if a file's contents have changed.
|
[
"given",
"the",
"path",
"to",
"a",
"local",
"file",
"being",
"streamed",
"returns",
"back",
"the",
"MD5",
"hash",
"to",
"quickly",
"check",
"if",
"a",
"file",
"s",
"contents",
"have",
"changed",
"."
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/build-tools/utils/cache.js#L8-L19
|
13,575
|
bolt-design-system/bolt
|
packages/build-tools/tasks/internal-tasks.js
|
mkDirs
|
async function mkDirs() {
config = config || (await getConfig());
try {
return Promise.all([
config.wwwDir ? mkdirp(config.wwwDir) : null,
config.dataDir ? mkdirp(config.dataDir) : null,
config.buildDir ? mkdirp(config.buildDir) : null,
]);
} catch (error) {
log.errorAndExit('Could not make all directories necessary.', error);
}
}
|
javascript
|
async function mkDirs() {
config = config || (await getConfig());
try {
return Promise.all([
config.wwwDir ? mkdirp(config.wwwDir) : null,
config.dataDir ? mkdirp(config.dataDir) : null,
config.buildDir ? mkdirp(config.buildDir) : null,
]);
} catch (error) {
log.errorAndExit('Could not make all directories necessary.', error);
}
}
|
[
"async",
"function",
"mkDirs",
"(",
")",
"{",
"config",
"=",
"config",
"||",
"(",
"await",
"getConfig",
"(",
")",
")",
";",
"try",
"{",
"return",
"Promise",
".",
"all",
"(",
"[",
"config",
".",
"wwwDir",
"?",
"mkdirp",
"(",
"config",
".",
"wwwDir",
")",
":",
"null",
",",
"config",
".",
"dataDir",
"?",
"mkdirp",
"(",
"config",
".",
"dataDir",
")",
":",
"null",
",",
"config",
".",
"buildDir",
"?",
"mkdirp",
"(",
"config",
".",
"buildDir",
")",
":",
"null",
",",
"]",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"log",
".",
"errorAndExit",
"(",
"'Could not make all directories necessary.'",
",",
"error",
")",
";",
"}",
"}"
] |
Makes all directories in config
@async
@returns {Promise}
|
[
"Makes",
"all",
"directories",
"in",
"config"
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/build-tools/tasks/internal-tasks.js#L16-L28
|
13,576
|
bolt-design-system/bolt
|
packages/servers/ssr-server/index.js
|
setupServer
|
async function setupServer() {
return new Promise(async (resolve, reject) => {
config = config || (await getConfig());
config.components.individual = [];
config.prod = true;
config.enableCache = true;
config.mode = 'server';
config.env = 'pwa';
config.sourceMaps = false;
config.copy = [];
config.webpackDevServer = false;
config.buildDir = path.join(config.wwwDir, 'build-ssr');
config.dataDir = path.join(config.wwwDir, 'build-ssr', 'data');
app.use(express.static(path.relative(process.cwd(), config.wwwDir)));
// generate a fresh webpack build + pass along asset data to dynamic HTML template rendered
server = await app.listen(port);
app.get('/ssr', function(req, res) {
res.send(template(html || '', port, webpackStatsGenerated || []));
});
// handle cleaning up + shutting down the server instance
process.on('SIGTERM', shutDownSSRServer);
process.on('SIGINT', shutDownSSRServer);
server.on('connection', connection => {
connections.push(connection);
connection.on(
'close',
// eslint-disable-next-line no-return-assign
() => (connections = connections.filter(curr => curr !== connection)),
);
});
resolve();
});
}
|
javascript
|
async function setupServer() {
return new Promise(async (resolve, reject) => {
config = config || (await getConfig());
config.components.individual = [];
config.prod = true;
config.enableCache = true;
config.mode = 'server';
config.env = 'pwa';
config.sourceMaps = false;
config.copy = [];
config.webpackDevServer = false;
config.buildDir = path.join(config.wwwDir, 'build-ssr');
config.dataDir = path.join(config.wwwDir, 'build-ssr', 'data');
app.use(express.static(path.relative(process.cwd(), config.wwwDir)));
// generate a fresh webpack build + pass along asset data to dynamic HTML template rendered
server = await app.listen(port);
app.get('/ssr', function(req, res) {
res.send(template(html || '', port, webpackStatsGenerated || []));
});
// handle cleaning up + shutting down the server instance
process.on('SIGTERM', shutDownSSRServer);
process.on('SIGINT', shutDownSSRServer);
server.on('connection', connection => {
connections.push(connection);
connection.on(
'close',
// eslint-disable-next-line no-return-assign
() => (connections = connections.filter(curr => curr !== connection)),
);
});
resolve();
});
}
|
[
"async",
"function",
"setupServer",
"(",
")",
"{",
"return",
"new",
"Promise",
"(",
"async",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"config",
"=",
"config",
"||",
"(",
"await",
"getConfig",
"(",
")",
")",
";",
"config",
".",
"components",
".",
"individual",
"=",
"[",
"]",
";",
"config",
".",
"prod",
"=",
"true",
";",
"config",
".",
"enableCache",
"=",
"true",
";",
"config",
".",
"mode",
"=",
"'server'",
";",
"config",
".",
"env",
"=",
"'pwa'",
";",
"config",
".",
"sourceMaps",
"=",
"false",
";",
"config",
".",
"copy",
"=",
"[",
"]",
";",
"config",
".",
"webpackDevServer",
"=",
"false",
";",
"config",
".",
"buildDir",
"=",
"path",
".",
"join",
"(",
"config",
".",
"wwwDir",
",",
"'build-ssr'",
")",
";",
"config",
".",
"dataDir",
"=",
"path",
".",
"join",
"(",
"config",
".",
"wwwDir",
",",
"'build-ssr'",
",",
"'data'",
")",
";",
"app",
".",
"use",
"(",
"express",
".",
"static",
"(",
"path",
".",
"relative",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"config",
".",
"wwwDir",
")",
")",
")",
";",
"// generate a fresh webpack build + pass along asset data to dynamic HTML template rendered",
"server",
"=",
"await",
"app",
".",
"listen",
"(",
"port",
")",
";",
"app",
".",
"get",
"(",
"'/ssr'",
",",
"function",
"(",
"req",
",",
"res",
")",
"{",
"res",
".",
"send",
"(",
"template",
"(",
"html",
"||",
"''",
",",
"port",
",",
"webpackStatsGenerated",
"||",
"[",
"]",
")",
")",
";",
"}",
")",
";",
"// handle cleaning up + shutting down the server instance",
"process",
".",
"on",
"(",
"'SIGTERM'",
",",
"shutDownSSRServer",
")",
";",
"process",
".",
"on",
"(",
"'SIGINT'",
",",
"shutDownSSRServer",
")",
";",
"server",
".",
"on",
"(",
"'connection'",
",",
"connection",
"=>",
"{",
"connections",
".",
"push",
"(",
"connection",
")",
";",
"connection",
".",
"on",
"(",
"'close'",
",",
"// eslint-disable-next-line no-return-assign",
"(",
")",
"=>",
"(",
"connections",
"=",
"connections",
".",
"filter",
"(",
"curr",
"=>",
"curr",
"!==",
"connection",
")",
")",
",",
")",
";",
"}",
")",
";",
"resolve",
"(",
")",
";",
"}",
")",
";",
"}"
] |
listen for when we need to auto-shut down + track open server connections
|
[
"listen",
"for",
"when",
"we",
"need",
"to",
"auto",
"-",
"shut",
"down",
"+",
"track",
"open",
"server",
"connections"
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/servers/ssr-server/index.js#L110-L148
|
13,577
|
bolt-design-system/bolt
|
packages/uikit-workshop/src/scripts/utils/postmessage.js
|
receiveIframeMessage
|
function receiveIframeMessage(event) {
// does the origin sending the message match the current host? if not dev/null the request
if (
window.location.protocol !== 'file:' &&
event.origin !== window.location.protocol + '//' + window.location.host
) {
return;
}
let path;
let data = {};
try {
data = typeof event.data !== 'string' ? event.data : JSON.parse(event.data);
} catch (e) {
// @todo: how do we want to handle exceptions like these?
}
if (data.event !== undefined && data.event === 'patternLab.updatePath') {
if (window.patternData.patternPartial !== undefined) {
// handle patterns and the view all page
const re = /(patterns|snapshots)\/(.*)$/;
path =
window.location.protocol +
'//' +
window.location.host +
window.location.pathname.replace(re, '') +
data.path +
'?' +
Date.now();
window.location.replace(path);
} else {
// handle the style guide
path =
window.location.protocol +
'//' +
window.location.host +
window.location.pathname.replace(
'styleguide/html/styleguide.html',
''
) +
data.path +
'?' +
Date.now();
window.location.replace(path);
}
} else if (data.event !== undefined && data.event === 'patternLab.reload') {
// reload the location if there was a message to do so
window.location.reload();
}
}
|
javascript
|
function receiveIframeMessage(event) {
// does the origin sending the message match the current host? if not dev/null the request
if (
window.location.protocol !== 'file:' &&
event.origin !== window.location.protocol + '//' + window.location.host
) {
return;
}
let path;
let data = {};
try {
data = typeof event.data !== 'string' ? event.data : JSON.parse(event.data);
} catch (e) {
// @todo: how do we want to handle exceptions like these?
}
if (data.event !== undefined && data.event === 'patternLab.updatePath') {
if (window.patternData.patternPartial !== undefined) {
// handle patterns and the view all page
const re = /(patterns|snapshots)\/(.*)$/;
path =
window.location.protocol +
'//' +
window.location.host +
window.location.pathname.replace(re, '') +
data.path +
'?' +
Date.now();
window.location.replace(path);
} else {
// handle the style guide
path =
window.location.protocol +
'//' +
window.location.host +
window.location.pathname.replace(
'styleguide/html/styleguide.html',
''
) +
data.path +
'?' +
Date.now();
window.location.replace(path);
}
} else if (data.event !== undefined && data.event === 'patternLab.reload') {
// reload the location if there was a message to do so
window.location.reload();
}
}
|
[
"function",
"receiveIframeMessage",
"(",
"event",
")",
"{",
"// does the origin sending the message match the current host? if not dev/null the request",
"if",
"(",
"window",
".",
"location",
".",
"protocol",
"!==",
"'file:'",
"&&",
"event",
".",
"origin",
"!==",
"window",
".",
"location",
".",
"protocol",
"+",
"'//'",
"+",
"window",
".",
"location",
".",
"host",
")",
"{",
"return",
";",
"}",
"let",
"path",
";",
"let",
"data",
"=",
"{",
"}",
";",
"try",
"{",
"data",
"=",
"typeof",
"event",
".",
"data",
"!==",
"'string'",
"?",
"event",
".",
"data",
":",
"JSON",
".",
"parse",
"(",
"event",
".",
"data",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// @todo: how do we want to handle exceptions like these?",
"}",
"if",
"(",
"data",
".",
"event",
"!==",
"undefined",
"&&",
"data",
".",
"event",
"===",
"'patternLab.updatePath'",
")",
"{",
"if",
"(",
"window",
".",
"patternData",
".",
"patternPartial",
"!==",
"undefined",
")",
"{",
"// handle patterns and the view all page",
"const",
"re",
"=",
"/",
"(patterns|snapshots)\\/(.*)$",
"/",
";",
"path",
"=",
"window",
".",
"location",
".",
"protocol",
"+",
"'//'",
"+",
"window",
".",
"location",
".",
"host",
"+",
"window",
".",
"location",
".",
"pathname",
".",
"replace",
"(",
"re",
",",
"''",
")",
"+",
"data",
".",
"path",
"+",
"'?'",
"+",
"Date",
".",
"now",
"(",
")",
";",
"window",
".",
"location",
".",
"replace",
"(",
"path",
")",
";",
"}",
"else",
"{",
"// handle the style guide",
"path",
"=",
"window",
".",
"location",
".",
"protocol",
"+",
"'//'",
"+",
"window",
".",
"location",
".",
"host",
"+",
"window",
".",
"location",
".",
"pathname",
".",
"replace",
"(",
"'styleguide/html/styleguide.html'",
",",
"''",
")",
"+",
"data",
".",
"path",
"+",
"'?'",
"+",
"Date",
".",
"now",
"(",
")",
";",
"window",
".",
"location",
".",
"replace",
"(",
"path",
")",
";",
"}",
"}",
"else",
"if",
"(",
"data",
".",
"event",
"!==",
"undefined",
"&&",
"data",
".",
"event",
"===",
"'patternLab.reload'",
")",
"{",
"// reload the location if there was a message to do so",
"window",
".",
"location",
".",
"reload",
"(",
")",
";",
"}",
"}"
] |
watch the iframe source so that it can be sent back to everyone else.
|
[
"watch",
"the",
"iframe",
"source",
"so",
"that",
"it",
"can",
"be",
"sent",
"back",
"to",
"everyone",
"else",
"."
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/uikit-workshop/src/scripts/utils/postmessage.js#L37-L86
|
13,578
|
bolt-design-system/bolt
|
packages/build-tools/create-webpack-config.js
|
buildWebpackEntry
|
async function buildWebpackEntry() {
const { components } = await getBoltManifest();
const entry = {};
const globalEntryName = 'bolt-global';
if (components.global) {
entry[globalEntryName] = [];
components.global.forEach(component => {
if (component.assets.style) {
entry[globalEntryName].push(component.assets.style);
}
if (component.assets.main) {
entry[globalEntryName].push(component.assets.main);
}
});
const useHotMiddleware =
Array.isArray(fullBuildConfig.lang) && fullBuildConfig.lang.length > 1
? false
: true;
if (!config.prod && config.webpackDevServer && useHotMiddleware) {
entry[globalEntryName].push(
`webpack-hot-middleware/client?name=${
config.lang
}&noInfo=true&quiet=true&logLevel=silent&reload=true`,
);
}
}
if (components.individual) {
components.individual.forEach(component => {
const files = [];
if (component.assets.style) files.push(component.assets.style);
if (component.assets.main) files.push(component.assets.main);
if (files) {
entry[component.basicName] = files;
}
});
}
if (config.verbosity > 4) {
log.info('WebPack `entry`:');
console.log(entry);
}
return entry;
}
|
javascript
|
async function buildWebpackEntry() {
const { components } = await getBoltManifest();
const entry = {};
const globalEntryName = 'bolt-global';
if (components.global) {
entry[globalEntryName] = [];
components.global.forEach(component => {
if (component.assets.style) {
entry[globalEntryName].push(component.assets.style);
}
if (component.assets.main) {
entry[globalEntryName].push(component.assets.main);
}
});
const useHotMiddleware =
Array.isArray(fullBuildConfig.lang) && fullBuildConfig.lang.length > 1
? false
: true;
if (!config.prod && config.webpackDevServer && useHotMiddleware) {
entry[globalEntryName].push(
`webpack-hot-middleware/client?name=${
config.lang
}&noInfo=true&quiet=true&logLevel=silent&reload=true`,
);
}
}
if (components.individual) {
components.individual.forEach(component => {
const files = [];
if (component.assets.style) files.push(component.assets.style);
if (component.assets.main) files.push(component.assets.main);
if (files) {
entry[component.basicName] = files;
}
});
}
if (config.verbosity > 4) {
log.info('WebPack `entry`:');
console.log(entry);
}
return entry;
}
|
[
"async",
"function",
"buildWebpackEntry",
"(",
")",
"{",
"const",
"{",
"components",
"}",
"=",
"await",
"getBoltManifest",
"(",
")",
";",
"const",
"entry",
"=",
"{",
"}",
";",
"const",
"globalEntryName",
"=",
"'bolt-global'",
";",
"if",
"(",
"components",
".",
"global",
")",
"{",
"entry",
"[",
"globalEntryName",
"]",
"=",
"[",
"]",
";",
"components",
".",
"global",
".",
"forEach",
"(",
"component",
"=>",
"{",
"if",
"(",
"component",
".",
"assets",
".",
"style",
")",
"{",
"entry",
"[",
"globalEntryName",
"]",
".",
"push",
"(",
"component",
".",
"assets",
".",
"style",
")",
";",
"}",
"if",
"(",
"component",
".",
"assets",
".",
"main",
")",
"{",
"entry",
"[",
"globalEntryName",
"]",
".",
"push",
"(",
"component",
".",
"assets",
".",
"main",
")",
";",
"}",
"}",
")",
";",
"const",
"useHotMiddleware",
"=",
"Array",
".",
"isArray",
"(",
"fullBuildConfig",
".",
"lang",
")",
"&&",
"fullBuildConfig",
".",
"lang",
".",
"length",
">",
"1",
"?",
"false",
":",
"true",
";",
"if",
"(",
"!",
"config",
".",
"prod",
"&&",
"config",
".",
"webpackDevServer",
"&&",
"useHotMiddleware",
")",
"{",
"entry",
"[",
"globalEntryName",
"]",
".",
"push",
"(",
"`",
"${",
"config",
".",
"lang",
"}",
"`",
",",
")",
";",
"}",
"}",
"if",
"(",
"components",
".",
"individual",
")",
"{",
"components",
".",
"individual",
".",
"forEach",
"(",
"component",
"=>",
"{",
"const",
"files",
"=",
"[",
"]",
";",
"if",
"(",
"component",
".",
"assets",
".",
"style",
")",
"files",
".",
"push",
"(",
"component",
".",
"assets",
".",
"style",
")",
";",
"if",
"(",
"component",
".",
"assets",
".",
"main",
")",
"files",
".",
"push",
"(",
"component",
".",
"assets",
".",
"main",
")",
";",
"if",
"(",
"files",
")",
"{",
"entry",
"[",
"component",
".",
"basicName",
"]",
"=",
"files",
";",
"}",
"}",
")",
";",
"}",
"if",
"(",
"config",
".",
"verbosity",
">",
"4",
")",
"{",
"log",
".",
"info",
"(",
"'WebPack `entry`:'",
")",
";",
"console",
".",
"log",
"(",
"entry",
")",
";",
"}",
"return",
"entry",
";",
"}"
] |
Build WebPack config's `entry` object
@link https://webpack.js.org/configuration/entry-context/#entry
@returns {object} entry - WebPack config `entry`
|
[
"Build",
"WebPack",
"config",
"s",
"entry",
"object"
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/build-tools/create-webpack-config.js#L147-L193
|
13,579
|
bolt-design-system/bolt
|
packages/build-tools/utils/yaml.js
|
readYamlFile
|
function readYamlFile(file) {
return new Promise((resolve, reject) => {
readFile(file, 'utf8')
.then(data => resolve(fromYaml(data)))
.catch(reject);
});
}
|
javascript
|
function readYamlFile(file) {
return new Promise((resolve, reject) => {
readFile(file, 'utf8')
.then(data => resolve(fromYaml(data)))
.catch(reject);
});
}
|
[
"function",
"readYamlFile",
"(",
"file",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"readFile",
"(",
"file",
",",
"'utf8'",
")",
".",
"then",
"(",
"data",
"=>",
"resolve",
"(",
"fromYaml",
"(",
"data",
")",
")",
")",
".",
"catch",
"(",
"reject",
")",
";",
"}",
")",
";",
"}"
] |
Read Yaml File into Object
@param {string} file - File path
@returns {Promise<object>} Promise resolves with yaml file as object
@see fromYaml
@see writeYamlFile
|
[
"Read",
"Yaml",
"File",
"into",
"Object"
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/build-tools/utils/yaml.js#L37-L43
|
13,580
|
bolt-design-system/bolt
|
packages/build-tools/utils/yaml.js
|
writeYamlFile
|
function writeYamlFile(file, data) {
return new Promise((resolve, reject) => {
writeFile(file, toYaml(data))
.then(resolve)
.catch(reject);
});
}
|
javascript
|
function writeYamlFile(file, data) {
return new Promise((resolve, reject) => {
writeFile(file, toYaml(data))
.then(resolve)
.catch(reject);
});
}
|
[
"function",
"writeYamlFile",
"(",
"file",
",",
"data",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"writeFile",
"(",
"file",
",",
"toYaml",
"(",
"data",
")",
")",
".",
"then",
"(",
"resolve",
")",
".",
"catch",
"(",
"reject",
")",
";",
"}",
")",
";",
"}"
] |
Write Yaml string to File
@param {string} file - File path
@param {object} data - Object to turn into Yaml
@returns {Promise}
@see readYamlFile
@see toYaml
|
[
"Write",
"Yaml",
"string",
"to",
"File"
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/build-tools/utils/yaml.js#L69-L75
|
13,581
|
bolt-design-system/bolt
|
packages/build-tools/tasks/api-tasks/bolt-pkg-versions.js
|
generatePackageData
|
async function generatePackageData() {
boltPackages.forEach(async pkg => {
if (pkg.version !== '0.0.0' && pkg.private !== true) {
const name = pkg.name;
try {
const pkgInfo = await packageJson(name, {
allVersions: true,
});
processedPackages.push(pkgInfo);
numberOfPackagesProcessed += 1;
} catch (err) {
console.log(err);
}
} else {
numberOfPackagesProcessed += 1;
}
if (numberOfPackagesProcessed === totalNumberOfPackages) {
const config = await getConfig();
const unformattedJSON = JSON.stringify(processedPackages);
const formattedJSON = prettier.format(unformattedJSON, {
parser: 'json',
});
fs.writeFile(
path.join(config.dataDir, 'bolt-pkg-versions.json'),
formattedJSON,
'utf8',
function(err) {
if (err) {
console.log('An error occured while writing JSON Object to File.');
return console.log(err);
}
console.log('Bolt NPM pkg Data has been saved.');
},
);
}
});
}
|
javascript
|
async function generatePackageData() {
boltPackages.forEach(async pkg => {
if (pkg.version !== '0.0.0' && pkg.private !== true) {
const name = pkg.name;
try {
const pkgInfo = await packageJson(name, {
allVersions: true,
});
processedPackages.push(pkgInfo);
numberOfPackagesProcessed += 1;
} catch (err) {
console.log(err);
}
} else {
numberOfPackagesProcessed += 1;
}
if (numberOfPackagesProcessed === totalNumberOfPackages) {
const config = await getConfig();
const unformattedJSON = JSON.stringify(processedPackages);
const formattedJSON = prettier.format(unformattedJSON, {
parser: 'json',
});
fs.writeFile(
path.join(config.dataDir, 'bolt-pkg-versions.json'),
formattedJSON,
'utf8',
function(err) {
if (err) {
console.log('An error occured while writing JSON Object to File.');
return console.log(err);
}
console.log('Bolt NPM pkg Data has been saved.');
},
);
}
});
}
|
[
"async",
"function",
"generatePackageData",
"(",
")",
"{",
"boltPackages",
".",
"forEach",
"(",
"async",
"pkg",
"=>",
"{",
"if",
"(",
"pkg",
".",
"version",
"!==",
"'0.0.0'",
"&&",
"pkg",
".",
"private",
"!==",
"true",
")",
"{",
"const",
"name",
"=",
"pkg",
".",
"name",
";",
"try",
"{",
"const",
"pkgInfo",
"=",
"await",
"packageJson",
"(",
"name",
",",
"{",
"allVersions",
":",
"true",
",",
"}",
")",
";",
"processedPackages",
".",
"push",
"(",
"pkgInfo",
")",
";",
"numberOfPackagesProcessed",
"+=",
"1",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"err",
")",
";",
"}",
"}",
"else",
"{",
"numberOfPackagesProcessed",
"+=",
"1",
";",
"}",
"if",
"(",
"numberOfPackagesProcessed",
"===",
"totalNumberOfPackages",
")",
"{",
"const",
"config",
"=",
"await",
"getConfig",
"(",
")",
";",
"const",
"unformattedJSON",
"=",
"JSON",
".",
"stringify",
"(",
"processedPackages",
")",
";",
"const",
"formattedJSON",
"=",
"prettier",
".",
"format",
"(",
"unformattedJSON",
",",
"{",
"parser",
":",
"'json'",
",",
"}",
")",
";",
"fs",
".",
"writeFile",
"(",
"path",
".",
"join",
"(",
"config",
".",
"dataDir",
",",
"'bolt-pkg-versions.json'",
")",
",",
"formattedJSON",
",",
"'utf8'",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"'An error occured while writing JSON Object to File.'",
")",
";",
"return",
"console",
".",
"log",
"(",
"err",
")",
";",
"}",
"console",
".",
"log",
"(",
"'Bolt NPM pkg Data has been saved.'",
")",
";",
"}",
",",
")",
";",
"}",
"}",
")",
";",
"}"
] |
iterator for forEach loop so we know when we're done
|
[
"iterator",
"for",
"forEach",
"loop",
"so",
"we",
"know",
"when",
"we",
"re",
"done"
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/build-tools/tasks/api-tasks/bolt-pkg-versions.js#L16-L56
|
13,582
|
bolt-design-system/bolt
|
packages/build-tools/tasks/static-tasks.js
|
getPage
|
async function getPage(file) {
config = config || (await asyncConfig());
if (config.verbosity > 3) {
log.dim(`Getting info for: ${file}`);
}
const url = path
.relative(config.srcDir, file)
.replace('.md', '.html')
.split('/')
.map(x => x.replace(/^[0-9]*-/, '')) // Removing number prefix `05-item` => `item`
.join('/');
const fileContents = await readFile(file, 'utf8');
// https://www.npmjs.com/package/front-matter
const { attributes, body, frontmatter } = fm(fileContents);
const dirTree = url.split('/');
let depth = url.split('/').filter(x => x !== 'index.html').length;
let parent = dirTree[depth - 2];
// Don't do it for homepage
if (url === 'index.html') depth = 1;
const page = {
srcPath: file,
url,
depth,
parent,
meta: attributes,
body: file.endsWith('.md') ? marked(body) : body,
};
return page;
}
|
javascript
|
async function getPage(file) {
config = config || (await asyncConfig());
if (config.verbosity > 3) {
log.dim(`Getting info for: ${file}`);
}
const url = path
.relative(config.srcDir, file)
.replace('.md', '.html')
.split('/')
.map(x => x.replace(/^[0-9]*-/, '')) // Removing number prefix `05-item` => `item`
.join('/');
const fileContents = await readFile(file, 'utf8');
// https://www.npmjs.com/package/front-matter
const { attributes, body, frontmatter } = fm(fileContents);
const dirTree = url.split('/');
let depth = url.split('/').filter(x => x !== 'index.html').length;
let parent = dirTree[depth - 2];
// Don't do it for homepage
if (url === 'index.html') depth = 1;
const page = {
srcPath: file,
url,
depth,
parent,
meta: attributes,
body: file.endsWith('.md') ? marked(body) : body,
};
return page;
}
|
[
"async",
"function",
"getPage",
"(",
"file",
")",
"{",
"config",
"=",
"config",
"||",
"(",
"await",
"asyncConfig",
"(",
")",
")",
";",
"if",
"(",
"config",
".",
"verbosity",
">",
"3",
")",
"{",
"log",
".",
"dim",
"(",
"`",
"${",
"file",
"}",
"`",
")",
";",
"}",
"const",
"url",
"=",
"path",
".",
"relative",
"(",
"config",
".",
"srcDir",
",",
"file",
")",
".",
"replace",
"(",
"'.md'",
",",
"'.html'",
")",
".",
"split",
"(",
"'/'",
")",
".",
"map",
"(",
"x",
"=>",
"x",
".",
"replace",
"(",
"/",
"^[0-9]*-",
"/",
",",
"''",
")",
")",
"// Removing number prefix `05-item` => `item`",
".",
"join",
"(",
"'/'",
")",
";",
"const",
"fileContents",
"=",
"await",
"readFile",
"(",
"file",
",",
"'utf8'",
")",
";",
"// https://www.npmjs.com/package/front-matter",
"const",
"{",
"attributes",
",",
"body",
",",
"frontmatter",
"}",
"=",
"fm",
"(",
"fileContents",
")",
";",
"const",
"dirTree",
"=",
"url",
".",
"split",
"(",
"'/'",
")",
";",
"let",
"depth",
"=",
"url",
".",
"split",
"(",
"'/'",
")",
".",
"filter",
"(",
"x",
"=>",
"x",
"!==",
"'index.html'",
")",
".",
"length",
";",
"let",
"parent",
"=",
"dirTree",
"[",
"depth",
"-",
"2",
"]",
";",
"// Don't do it for homepage",
"if",
"(",
"url",
"===",
"'index.html'",
")",
"depth",
"=",
"1",
";",
"const",
"page",
"=",
"{",
"srcPath",
":",
"file",
",",
"url",
",",
"depth",
",",
"parent",
",",
"meta",
":",
"attributes",
",",
"body",
":",
"file",
".",
"endsWith",
"(",
"'.md'",
")",
"?",
"marked",
"(",
"body",
")",
":",
"body",
",",
"}",
";",
"return",
"page",
";",
"}"
] |
Get data for a single page that is Markdown or HTML with Yaml front matter
@param {string} file - Path to source file
@returns {Promise<{srcPath: string, distPath: string, meta: object, body: string}>} page - Page Data
|
[
"Get",
"data",
"for",
"a",
"single",
"page",
"that",
"is",
"Markdown",
"or",
"HTML",
"with",
"Yaml",
"front",
"matter"
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/build-tools/tasks/static-tasks.js#L55-L91
|
13,583
|
bolt-design-system/bolt
|
packages/build-tools/tasks/static-tasks.js
|
getPages
|
async function getPages(srcDir) {
config = config || (await asyncConfig());
/** @type Array<String> */
const allPaths = await globby([
path.join(srcDir, '**/*.{md,html}'),
'!**/_*/**/*.{md,html}',
'!**/pattern-lab/**/*',
'!**/_*.{md,html}',
]);
return Promise.all(allPaths.map(getPage)).then(pages => {
if (config.verbosity > 4) {
log.dim('All data for Static pages:');
console.log(pages);
log.dim('END: All data for Static pages.');
}
return pages;
});
}
|
javascript
|
async function getPages(srcDir) {
config = config || (await asyncConfig());
/** @type Array<String> */
const allPaths = await globby([
path.join(srcDir, '**/*.{md,html}'),
'!**/_*/**/*.{md,html}',
'!**/pattern-lab/**/*',
'!**/_*.{md,html}',
]);
return Promise.all(allPaths.map(getPage)).then(pages => {
if (config.verbosity > 4) {
log.dim('All data for Static pages:');
console.log(pages);
log.dim('END: All data for Static pages.');
}
return pages;
});
}
|
[
"async",
"function",
"getPages",
"(",
"srcDir",
")",
"{",
"config",
"=",
"config",
"||",
"(",
"await",
"asyncConfig",
"(",
")",
")",
";",
"/** @type Array<String> */",
"const",
"allPaths",
"=",
"await",
"globby",
"(",
"[",
"path",
".",
"join",
"(",
"srcDir",
",",
"'**/*.{md,html}'",
")",
",",
"'!**/_*/**/*.{md,html}'",
",",
"'!**/pattern-lab/**/*'",
",",
"'!**/_*.{md,html}'",
",",
"]",
")",
";",
"return",
"Promise",
".",
"all",
"(",
"allPaths",
".",
"map",
"(",
"getPage",
")",
")",
".",
"then",
"(",
"pages",
"=>",
"{",
"if",
"(",
"config",
".",
"verbosity",
">",
"4",
")",
"{",
"log",
".",
"dim",
"(",
"'All data for Static pages:'",
")",
";",
"console",
".",
"log",
"(",
"pages",
")",
";",
"log",
".",
"dim",
"(",
"'END: All data for Static pages.'",
")",
";",
"}",
"return",
"pages",
";",
"}",
")",
";",
"}"
] |
Get data for all pages
@param {string} files - Source directory
@see getPage
@returns {Promise<object[]>} - An array of page data objects
|
[
"Get",
"data",
"for",
"all",
"pages"
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/build-tools/tasks/static-tasks.js#L99-L117
|
13,584
|
bolt-design-system/bolt
|
packages/build-tools/tasks/static-tasks.js
|
getSiteData
|
async function getSiteData(pages) {
config = config || (await asyncConfig());
const nestedPages = await getNestedPages(config.srcDir);
const site = {
nestedPages,
pages: pages.map(page => ({
url: page.url,
meta: page.meta,
// choosing not to have `page.body` in here on purpose
})),
};
return site;
}
|
javascript
|
async function getSiteData(pages) {
config = config || (await asyncConfig());
const nestedPages = await getNestedPages(config.srcDir);
const site = {
nestedPages,
pages: pages.map(page => ({
url: page.url,
meta: page.meta,
// choosing not to have `page.body` in here on purpose
})),
};
return site;
}
|
[
"async",
"function",
"getSiteData",
"(",
"pages",
")",
"{",
"config",
"=",
"config",
"||",
"(",
"await",
"asyncConfig",
"(",
")",
")",
";",
"const",
"nestedPages",
"=",
"await",
"getNestedPages",
"(",
"config",
".",
"srcDir",
")",
";",
"const",
"site",
"=",
"{",
"nestedPages",
",",
"pages",
":",
"pages",
".",
"map",
"(",
"page",
"=>",
"(",
"{",
"url",
":",
"page",
".",
"url",
",",
"meta",
":",
"page",
".",
"meta",
",",
"// choosing not to have `page.body` in here on purpose",
"}",
")",
")",
",",
"}",
";",
"return",
"site",
";",
"}"
] |
Get the site data based on the pages
@param {object} pages
@returns {{pages}}
|
[
"Get",
"the",
"site",
"data",
"based",
"on",
"the",
"pages"
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/build-tools/tasks/static-tasks.js#L173-L186
|
13,585
|
bolt-design-system/bolt
|
packages/build-tools/tasks/static-tasks.js
|
compile
|
async function compile(exitOnError = true) {
config = config || (await asyncConfig());
const startMessage = chalk.blue('Compiling Static Site...');
const startTime = timer.start();
let spinner;
if (config.verbosity > 2) {
console.log(startMessage);
} else {
spinner = ora(startMessage).start();
}
const pages = await getPages(config.srcDir);
const renderPages = pages.map(async page => {
const site = await getSiteData(pages);
const layout = page.meta.layout ? page.meta.layout : 'default';
const { ok, html, message } = await render(`@bolt/${layout}.twig`, {
page,
site,
});
if (!ok) {
if (exitOnError) {
log.errorAndExit(message);
} else {
log.error(message);
}
}
const htmlFilePath = path.join(config.wwwDir, page.url);
await mkdirp(path.dirname(htmlFilePath));
await writeFile(htmlFilePath, html);
if (config.verbosity > 3) {
log.dim(`Wrote: ${htmlFilePath}`);
}
return true;
});
Promise.all(renderPages)
.then(() => {
const endMessage = chalk.green(
`Compiled Static Site in ${timer.end(startTime)}`,
);
if (config.verbosity > 2) {
console.log(endMessage);
} else {
spinner.succeed(endMessage);
}
})
.catch(error => {
console.log(error);
const endMessage = chalk.red(
`Compiling Static Site failed in ${timer.end(startTime)}`,
);
spinner.fail(endMessage);
});
}
|
javascript
|
async function compile(exitOnError = true) {
config = config || (await asyncConfig());
const startMessage = chalk.blue('Compiling Static Site...');
const startTime = timer.start();
let spinner;
if (config.verbosity > 2) {
console.log(startMessage);
} else {
spinner = ora(startMessage).start();
}
const pages = await getPages(config.srcDir);
const renderPages = pages.map(async page => {
const site = await getSiteData(pages);
const layout = page.meta.layout ? page.meta.layout : 'default';
const { ok, html, message } = await render(`@bolt/${layout}.twig`, {
page,
site,
});
if (!ok) {
if (exitOnError) {
log.errorAndExit(message);
} else {
log.error(message);
}
}
const htmlFilePath = path.join(config.wwwDir, page.url);
await mkdirp(path.dirname(htmlFilePath));
await writeFile(htmlFilePath, html);
if (config.verbosity > 3) {
log.dim(`Wrote: ${htmlFilePath}`);
}
return true;
});
Promise.all(renderPages)
.then(() => {
const endMessage = chalk.green(
`Compiled Static Site in ${timer.end(startTime)}`,
);
if (config.verbosity > 2) {
console.log(endMessage);
} else {
spinner.succeed(endMessage);
}
})
.catch(error => {
console.log(error);
const endMessage = chalk.red(
`Compiling Static Site failed in ${timer.end(startTime)}`,
);
spinner.fail(endMessage);
});
}
|
[
"async",
"function",
"compile",
"(",
"exitOnError",
"=",
"true",
")",
"{",
"config",
"=",
"config",
"||",
"(",
"await",
"asyncConfig",
"(",
")",
")",
";",
"const",
"startMessage",
"=",
"chalk",
".",
"blue",
"(",
"'Compiling Static Site...'",
")",
";",
"const",
"startTime",
"=",
"timer",
".",
"start",
"(",
")",
";",
"let",
"spinner",
";",
"if",
"(",
"config",
".",
"verbosity",
">",
"2",
")",
"{",
"console",
".",
"log",
"(",
"startMessage",
")",
";",
"}",
"else",
"{",
"spinner",
"=",
"ora",
"(",
"startMessage",
")",
".",
"start",
"(",
")",
";",
"}",
"const",
"pages",
"=",
"await",
"getPages",
"(",
"config",
".",
"srcDir",
")",
";",
"const",
"renderPages",
"=",
"pages",
".",
"map",
"(",
"async",
"page",
"=>",
"{",
"const",
"site",
"=",
"await",
"getSiteData",
"(",
"pages",
")",
";",
"const",
"layout",
"=",
"page",
".",
"meta",
".",
"layout",
"?",
"page",
".",
"meta",
".",
"layout",
":",
"'default'",
";",
"const",
"{",
"ok",
",",
"html",
",",
"message",
"}",
"=",
"await",
"render",
"(",
"`",
"${",
"layout",
"}",
"`",
",",
"{",
"page",
",",
"site",
",",
"}",
")",
";",
"if",
"(",
"!",
"ok",
")",
"{",
"if",
"(",
"exitOnError",
")",
"{",
"log",
".",
"errorAndExit",
"(",
"message",
")",
";",
"}",
"else",
"{",
"log",
".",
"error",
"(",
"message",
")",
";",
"}",
"}",
"const",
"htmlFilePath",
"=",
"path",
".",
"join",
"(",
"config",
".",
"wwwDir",
",",
"page",
".",
"url",
")",
";",
"await",
"mkdirp",
"(",
"path",
".",
"dirname",
"(",
"htmlFilePath",
")",
")",
";",
"await",
"writeFile",
"(",
"htmlFilePath",
",",
"html",
")",
";",
"if",
"(",
"config",
".",
"verbosity",
">",
"3",
")",
"{",
"log",
".",
"dim",
"(",
"`",
"${",
"htmlFilePath",
"}",
"`",
")",
";",
"}",
"return",
"true",
";",
"}",
")",
";",
"Promise",
".",
"all",
"(",
"renderPages",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"const",
"endMessage",
"=",
"chalk",
".",
"green",
"(",
"`",
"${",
"timer",
".",
"end",
"(",
"startTime",
")",
"}",
"`",
",",
")",
";",
"if",
"(",
"config",
".",
"verbosity",
">",
"2",
")",
"{",
"console",
".",
"log",
"(",
"endMessage",
")",
";",
"}",
"else",
"{",
"spinner",
".",
"succeed",
"(",
"endMessage",
")",
";",
"}",
"}",
")",
".",
"catch",
"(",
"error",
"=>",
"{",
"console",
".",
"log",
"(",
"error",
")",
";",
"const",
"endMessage",
"=",
"chalk",
".",
"red",
"(",
"`",
"${",
"timer",
".",
"end",
"(",
"startTime",
")",
"}",
"`",
",",
")",
";",
"spinner",
".",
"fail",
"(",
"endMessage",
")",
";",
"}",
")",
";",
"}"
] |
The main event - compile the whole site
@returns {Promise<any[]>}
|
[
"The",
"main",
"event",
"-",
"compile",
"the",
"whole",
"site"
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/build-tools/tasks/static-tasks.js#L192-L250
|
13,586
|
bolt-design-system/bolt
|
packages/twig-renderer/twig-renderer.js
|
init
|
async function init(keepAlive = false) {
state = STATES.STARTING;
const config = await getConfig();
const relativeFrom = path.dirname(config.configFileUsed);
// console.log({ config });
twigNamespaces = await getTwigNamespaceConfig(
relativeFrom,
config.extraTwigNamespaces,
);
twigRenderer = new TwigRenderer({
relativeFrom,
src: {
roots: [relativeFrom],
namespaces: TwigRenderer.convertLegacyNamespacesConfig(twigNamespaces),
},
debug: true,
alterTwigEnv: config.alterTwigEnv,
hasExtraInfoInResponses: false, // Will add `info` onto results with a lot of info about Twig Env
maxConcurrency: 50,
keepAlive, // only set this to be true when doing in-browser requests to avoid issues with this process not exiting when complete
});
state = STATES.READY;
}
|
javascript
|
async function init(keepAlive = false) {
state = STATES.STARTING;
const config = await getConfig();
const relativeFrom = path.dirname(config.configFileUsed);
// console.log({ config });
twigNamespaces = await getTwigNamespaceConfig(
relativeFrom,
config.extraTwigNamespaces,
);
twigRenderer = new TwigRenderer({
relativeFrom,
src: {
roots: [relativeFrom],
namespaces: TwigRenderer.convertLegacyNamespacesConfig(twigNamespaces),
},
debug: true,
alterTwigEnv: config.alterTwigEnv,
hasExtraInfoInResponses: false, // Will add `info` onto results with a lot of info about Twig Env
maxConcurrency: 50,
keepAlive, // only set this to be true when doing in-browser requests to avoid issues with this process not exiting when complete
});
state = STATES.READY;
}
|
[
"async",
"function",
"init",
"(",
"keepAlive",
"=",
"false",
")",
"{",
"state",
"=",
"STATES",
".",
"STARTING",
";",
"const",
"config",
"=",
"await",
"getConfig",
"(",
")",
";",
"const",
"relativeFrom",
"=",
"path",
".",
"dirname",
"(",
"config",
".",
"configFileUsed",
")",
";",
"// console.log({ config });",
"twigNamespaces",
"=",
"await",
"getTwigNamespaceConfig",
"(",
"relativeFrom",
",",
"config",
".",
"extraTwigNamespaces",
",",
")",
";",
"twigRenderer",
"=",
"new",
"TwigRenderer",
"(",
"{",
"relativeFrom",
",",
"src",
":",
"{",
"roots",
":",
"[",
"relativeFrom",
"]",
",",
"namespaces",
":",
"TwigRenderer",
".",
"convertLegacyNamespacesConfig",
"(",
"twigNamespaces",
")",
",",
"}",
",",
"debug",
":",
"true",
",",
"alterTwigEnv",
":",
"config",
".",
"alterTwigEnv",
",",
"hasExtraInfoInResponses",
":",
"false",
",",
"// Will add `info` onto results with a lot of info about Twig Env",
"maxConcurrency",
":",
"50",
",",
"keepAlive",
",",
"// only set this to be true when doing in-browser requests to avoid issues with this process not exiting when complete",
"}",
")",
";",
"state",
"=",
"STATES",
".",
"READY",
";",
"}"
] |
Initialize Twig Renderer instance
@param {Boolean} keepAlive - Optionally tell the Twig renderer service to keep alive to help speed up requests
|
[
"Initialize",
"Twig",
"Renderer",
"instance"
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/twig-renderer/twig-renderer.js#L21-L43
|
13,587
|
bolt-design-system/bolt
|
packages/twig-renderer/twig-renderer.js
|
render
|
async function render(template, data = {}, keepAlive = false) {
await prep(keepAlive);
const results = await twigRenderer.render(template, data);
return results;
}
|
javascript
|
async function render(template, data = {}, keepAlive = false) {
await prep(keepAlive);
const results = await twigRenderer.render(template, data);
return results;
}
|
[
"async",
"function",
"render",
"(",
"template",
",",
"data",
"=",
"{",
"}",
",",
"keepAlive",
"=",
"false",
")",
"{",
"await",
"prep",
"(",
"keepAlive",
")",
";",
"const",
"results",
"=",
"await",
"twigRenderer",
".",
"render",
"(",
"template",
",",
"data",
")",
";",
"return",
"results",
";",
"}"
] |
Render Twig Template
@param {string} template - Template name (i.e. `@bolt/button.twig`)
@param {Object} data - Optional data to pass to template
@param {Boolean} keepAlive - Optionally tell the Twig renderer service to keep alive to help speed up requests
@return {Promise<{{ ok: boolean, html: string, message: string}}>} - Results of render
|
[
"Render",
"Twig",
"Template"
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/twig-renderer/twig-renderer.js#L72-L76
|
13,588
|
bolt-design-system/bolt
|
packages/twig-renderer/twig-renderer.js
|
renderString
|
async function renderString(templateString, data = {}, keepAlive = false) {
await prep(keepAlive);
const results = await twigRenderer.renderString(templateString, data);
// console.log({ results });
return results;
}
|
javascript
|
async function renderString(templateString, data = {}, keepAlive = false) {
await prep(keepAlive);
const results = await twigRenderer.renderString(templateString, data);
// console.log({ results });
return results;
}
|
[
"async",
"function",
"renderString",
"(",
"templateString",
",",
"data",
"=",
"{",
"}",
",",
"keepAlive",
"=",
"false",
")",
"{",
"await",
"prep",
"(",
"keepAlive",
")",
";",
"const",
"results",
"=",
"await",
"twigRenderer",
".",
"renderString",
"(",
"templateString",
",",
"data",
")",
";",
"// console.log({ results });",
"return",
"results",
";",
"}"
] |
Render Twig String
@param {string} templateString - String that is a Twig template (i.e. `<p>{{ text }}</p>`)
@param {Object} data - Optional data to pass to template
@param {Boolean} keepAlive - Optionally tell the Twig renderer service to keep alive to help speed up requests
@return {Promise<{{ ok: boolean, html: string, message: string}}>} - Results of render
|
[
"Render",
"Twig",
"String"
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/twig-renderer/twig-renderer.js#L85-L90
|
13,589
|
bolt-design-system/bolt
|
packages/build-tools/utils/general.js
|
uniqueArray
|
function uniqueArray(item) {
const u = {};
const newArray = [];
for (let i = 0, l = item.length; i < l; ++i) {
if (!{}.hasOwnProperty.call(u, item[i])) {
newArray.push(item[i]);
u[item[i]] = 1;
}
}
return newArray;
}
|
javascript
|
function uniqueArray(item) {
const u = {};
const newArray = [];
for (let i = 0, l = item.length; i < l; ++i) {
if (!{}.hasOwnProperty.call(u, item[i])) {
newArray.push(item[i]);
u[item[i]] = 1;
}
}
return newArray;
}
|
[
"function",
"uniqueArray",
"(",
"item",
")",
"{",
"const",
"u",
"=",
"{",
"}",
";",
"const",
"newArray",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"l",
"=",
"item",
".",
"length",
";",
"i",
"<",
"l",
";",
"++",
"i",
")",
"{",
"if",
"(",
"!",
"{",
"}",
".",
"hasOwnProperty",
".",
"call",
"(",
"u",
",",
"item",
"[",
"i",
"]",
")",
")",
"{",
"newArray",
".",
"push",
"(",
"item",
"[",
"i",
"]",
")",
";",
"u",
"[",
"item",
"[",
"i",
"]",
"]",
"=",
"1",
";",
"}",
"}",
"return",
"newArray",
";",
"}"
] |
Make an array unique by removing duplicate entries.
@param item {Array}
@returns {Array}
|
[
"Make",
"an",
"array",
"unique",
"by",
"removing",
"duplicate",
"entries",
"."
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/build-tools/utils/general.js#L30-L40
|
13,590
|
bolt-design-system/bolt
|
packages/build-tools/utils/general.js
|
ensureFileExists
|
function ensureFileExists(filePath) {
fs.access(filePath, err => {
if (err) {
log.errorAndExit(
'This file ^^^ does not exist and it was referenced in package.json for that component, please make sure the file path is correct.',
filePath,
);
}
});
}
|
javascript
|
function ensureFileExists(filePath) {
fs.access(filePath, err => {
if (err) {
log.errorAndExit(
'This file ^^^ does not exist and it was referenced in package.json for that component, please make sure the file path is correct.',
filePath,
);
}
});
}
|
[
"function",
"ensureFileExists",
"(",
"filePath",
")",
"{",
"fs",
".",
"access",
"(",
"filePath",
",",
"err",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"log",
".",
"errorAndExit",
"(",
"'This file ^^^ does not exist and it was referenced in package.json for that component, please make sure the file path is correct.'",
",",
"filePath",
",",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Ensure a file exists
We don't want to do anything with the file now, we just want to provide an early error if a path is wrong.
This is called async and by the time an error is thrown, we may be several steps ahead with WebPack probably already trying to start - that's ok, we don't want to hold up the process everytime things are correct.
@param filePath {string} - Path to file to ensure exists
|
[
"Ensure",
"a",
"file",
"exists",
"We",
"don",
"t",
"want",
"to",
"do",
"anything",
"with",
"the",
"file",
"now",
"we",
"just",
"want",
"to",
"provide",
"an",
"early",
"error",
"if",
"a",
"path",
"is",
"wrong",
".",
"This",
"is",
"called",
"async",
"and",
"by",
"the",
"time",
"an",
"error",
"is",
"thrown",
"we",
"may",
"be",
"several",
"steps",
"ahead",
"with",
"WebPack",
"probably",
"already",
"trying",
"to",
"start",
"-",
"that",
"s",
"ok",
"we",
"don",
"t",
"want",
"to",
"hold",
"up",
"the",
"process",
"everytime",
"things",
"are",
"correct",
"."
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/build-tools/utils/general.js#L48-L57
|
13,591
|
bolt-design-system/bolt
|
packages/build-tools/utils/general.js
|
dirExists
|
async function dirExists(path) {
try {
const stats = await stat(path);
return stats.isDirectory() ? true : false;
} catch (err) {
return false;
}
}
|
javascript
|
async function dirExists(path) {
try {
const stats = await stat(path);
return stats.isDirectory() ? true : false;
} catch (err) {
return false;
}
}
|
[
"async",
"function",
"dirExists",
"(",
"path",
")",
"{",
"try",
"{",
"const",
"stats",
"=",
"await",
"stat",
"(",
"path",
")",
";",
"return",
"stats",
".",
"isDirectory",
"(",
")",
"?",
"true",
":",
"false",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"false",
";",
"}",
"}"
] |
Check if a directory exists
@param path {string} - Path to the directory to check
|
[
"Check",
"if",
"a",
"directory",
"exists"
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/build-tools/utils/general.js#L76-L83
|
13,592
|
bolt-design-system/bolt
|
scripts/check-run.js
|
execAndReport
|
async function execAndReport({ cmd, name }) {
try {
const {
failed,
// code,
// timedOut,
stdout,
stderr,
// message,
} = await execa.shell(cmd);
process.stdout.write(stdout);
process.stderr.write(stderr);
await setCheckRun({
name,
status: 'completed',
conclusion: 'success',
output: {
title: name,
summary: `Ran ${cmd}`,
},
});
return failed;
} catch (err) {
const {
failed,
// code,
// timedOut,
stdout,
stderr,
message,
} = err;
process.stdout.write(stdout);
process.stderr.write(stderr);
await setCheckRun({
name,
status: 'completed',
conclusion: 'failure',
output: {
title: name,
summary: `Ran ${cmd}`,
text: `
<pre><code>
${message}
</code></pre>
`.trim(),
},
});
return failed;
}
}
|
javascript
|
async function execAndReport({ cmd, name }) {
try {
const {
failed,
// code,
// timedOut,
stdout,
stderr,
// message,
} = await execa.shell(cmd);
process.stdout.write(stdout);
process.stderr.write(stderr);
await setCheckRun({
name,
status: 'completed',
conclusion: 'success',
output: {
title: name,
summary: `Ran ${cmd}`,
},
});
return failed;
} catch (err) {
const {
failed,
// code,
// timedOut,
stdout,
stderr,
message,
} = err;
process.stdout.write(stdout);
process.stderr.write(stderr);
await setCheckRun({
name,
status: 'completed',
conclusion: 'failure',
output: {
title: name,
summary: `Ran ${cmd}`,
text: `
<pre><code>
${message}
</code></pre>
`.trim(),
},
});
return failed;
}
}
|
[
"async",
"function",
"execAndReport",
"(",
"{",
"cmd",
",",
"name",
"}",
")",
"{",
"try",
"{",
"const",
"{",
"failed",
",",
"// code,",
"// timedOut,",
"stdout",
",",
"stderr",
",",
"// message,",
"}",
"=",
"await",
"execa",
".",
"shell",
"(",
"cmd",
")",
";",
"process",
".",
"stdout",
".",
"write",
"(",
"stdout",
")",
";",
"process",
".",
"stderr",
".",
"write",
"(",
"stderr",
")",
";",
"await",
"setCheckRun",
"(",
"{",
"name",
",",
"status",
":",
"'completed'",
",",
"conclusion",
":",
"'success'",
",",
"output",
":",
"{",
"title",
":",
"name",
",",
"summary",
":",
"`",
"${",
"cmd",
"}",
"`",
",",
"}",
",",
"}",
")",
";",
"return",
"failed",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"const",
"{",
"failed",
",",
"// code,",
"// timedOut,",
"stdout",
",",
"stderr",
",",
"message",
",",
"}",
"=",
"err",
";",
"process",
".",
"stdout",
".",
"write",
"(",
"stdout",
")",
";",
"process",
".",
"stderr",
".",
"write",
"(",
"stderr",
")",
";",
"await",
"setCheckRun",
"(",
"{",
"name",
",",
"status",
":",
"'completed'",
",",
"conclusion",
":",
"'failure'",
",",
"output",
":",
"{",
"title",
":",
"name",
",",
"summary",
":",
"`",
"${",
"cmd",
"}",
"`",
",",
"text",
":",
"`",
"${",
"message",
"}",
"`",
".",
"trim",
"(",
")",
",",
"}",
",",
"}",
")",
";",
"return",
"failed",
";",
"}",
"}"
] |
Exec Shell Command and Report Results to GitHub Checks
@param {Object} opt
@param {string} opt.cmd - Shell command to execute from CWD
@param {string} opt.name - GitHub Checks Name
@return {Promise<boolean>} Did cmd fail?
|
[
"Exec",
"Shell",
"Command",
"and",
"Report",
"Results",
"to",
"GitHub",
"Checks"
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/scripts/check-run.js#L86-L136
|
13,593
|
bolt-design-system/bolt
|
packages/build-tools/utils/sh.js
|
sh
|
async function sh(
cmd,
args,
exitOnError,
streamOutput,
showCmdOnError = true,
exitImmediately = false,
) {
return new Promise((resolve, reject) => {
const child = execa(cmd, args);
let output = '';
if (streamOutput) {
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
}
child.stdout.on('data', data => {
output += data;
if (streamOutput) {
process.stdout.write(data);
}
});
child.stderr.on('data', data => {
output += data;
if (streamOutput) {
process.stdout.write(data);
}
});
child.on('close', code => {
if (code > 0) {
const errorMsg = chalk.red(`
Error with code ${code}${
showCmdOnError ? ` after running: ${cmd}` : ''
}:
`);
if (exitOnError) {
if (exitImmediately) {
console.error(errorMsg + output);
process.exit(1);
}
process.exitCode = 1;
reject(new Error(errorMsg + output));
} else {
notifier.notify({
title: cmd,
message: output,
sound: true,
});
// eslint-disable-next-line prefer-promise-reject-errors
reject(errorMsg + output);
}
}
resolve(output);
});
});
}
|
javascript
|
async function sh(
cmd,
args,
exitOnError,
streamOutput,
showCmdOnError = true,
exitImmediately = false,
) {
return new Promise((resolve, reject) => {
const child = execa(cmd, args);
let output = '';
if (streamOutput) {
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
}
child.stdout.on('data', data => {
output += data;
if (streamOutput) {
process.stdout.write(data);
}
});
child.stderr.on('data', data => {
output += data;
if (streamOutput) {
process.stdout.write(data);
}
});
child.on('close', code => {
if (code > 0) {
const errorMsg = chalk.red(`
Error with code ${code}${
showCmdOnError ? ` after running: ${cmd}` : ''
}:
`);
if (exitOnError) {
if (exitImmediately) {
console.error(errorMsg + output);
process.exit(1);
}
process.exitCode = 1;
reject(new Error(errorMsg + output));
} else {
notifier.notify({
title: cmd,
message: output,
sound: true,
});
// eslint-disable-next-line prefer-promise-reject-errors
reject(errorMsg + output);
}
}
resolve(output);
});
});
}
|
[
"async",
"function",
"sh",
"(",
"cmd",
",",
"args",
",",
"exitOnError",
",",
"streamOutput",
",",
"showCmdOnError",
"=",
"true",
",",
"exitImmediately",
"=",
"false",
",",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"child",
"=",
"execa",
"(",
"cmd",
",",
"args",
")",
";",
"let",
"output",
"=",
"''",
";",
"if",
"(",
"streamOutput",
")",
"{",
"child",
".",
"stdout",
".",
"pipe",
"(",
"process",
".",
"stdout",
")",
";",
"child",
".",
"stderr",
".",
"pipe",
"(",
"process",
".",
"stderr",
")",
";",
"}",
"child",
".",
"stdout",
".",
"on",
"(",
"'data'",
",",
"data",
"=>",
"{",
"output",
"+=",
"data",
";",
"if",
"(",
"streamOutput",
")",
"{",
"process",
".",
"stdout",
".",
"write",
"(",
"data",
")",
";",
"}",
"}",
")",
";",
"child",
".",
"stderr",
".",
"on",
"(",
"'data'",
",",
"data",
"=>",
"{",
"output",
"+=",
"data",
";",
"if",
"(",
"streamOutput",
")",
"{",
"process",
".",
"stdout",
".",
"write",
"(",
"data",
")",
";",
"}",
"}",
")",
";",
"child",
".",
"on",
"(",
"'close'",
",",
"code",
"=>",
"{",
"if",
"(",
"code",
">",
"0",
")",
"{",
"const",
"errorMsg",
"=",
"chalk",
".",
"red",
"(",
"`",
"${",
"code",
"}",
"${",
"showCmdOnError",
"?",
"`",
"${",
"cmd",
"}",
"`",
":",
"''",
"}",
"`",
")",
";",
"if",
"(",
"exitOnError",
")",
"{",
"if",
"(",
"exitImmediately",
")",
"{",
"console",
".",
"error",
"(",
"errorMsg",
"+",
"output",
")",
";",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}",
"process",
".",
"exitCode",
"=",
"1",
";",
"reject",
"(",
"new",
"Error",
"(",
"errorMsg",
"+",
"output",
")",
")",
";",
"}",
"else",
"{",
"notifier",
".",
"notify",
"(",
"{",
"title",
":",
"cmd",
",",
"message",
":",
"output",
",",
"sound",
":",
"true",
",",
"}",
")",
";",
"// eslint-disable-next-line prefer-promise-reject-errors",
"reject",
"(",
"errorMsg",
"+",
"output",
")",
";",
"}",
"}",
"resolve",
"(",
"output",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Run shell command
@param cmd {string} - Command to run
@param args {string[]} - args to pass to `cmd`
@param exitOnError {boolean} - If that should exit non-zero or carry one.
@param streamOutput {boolean} - Should output be sent to stdout as it happens? It always gets passed to resolve at end.
@param showCmdOnError {boolean} - If error, should `cmd` be shown?
@param exitImmediately {boolean} - If an exit is about to happen, should it happen immediately or at the end of the call stack at next tick?
|
[
"Run",
"shell",
"command"
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/build-tools/utils/sh.js#L14-L75
|
13,594
|
bolt-design-system/bolt
|
packages/components/bolt-ul/src/ul.js
|
addNestedLevelProps
|
function addNestedLevelProps(childNode, level) {
let currentLevel = level;
if (childNode.tagName) {
childNode.level = currentLevel;
}
return currentLevel;
}
|
javascript
|
function addNestedLevelProps(childNode, level) {
let currentLevel = level;
if (childNode.tagName) {
childNode.level = currentLevel;
}
return currentLevel;
}
|
[
"function",
"addNestedLevelProps",
"(",
"childNode",
",",
"level",
")",
"{",
"let",
"currentLevel",
"=",
"level",
";",
"if",
"(",
"childNode",
".",
"tagName",
")",
"{",
"childNode",
".",
"level",
"=",
"currentLevel",
";",
"}",
"return",
"currentLevel",
";",
"}"
] |
list-specific helper function to set nested children's `level` prop automatically
|
[
"list",
"-",
"specific",
"helper",
"function",
"to",
"set",
"nested",
"children",
"s",
"level",
"prop",
"automatically"
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/components/bolt-ul/src/ul.js#L10-L18
|
13,595
|
bolt-design-system/bolt
|
packages/build-tools/cli.js
|
updateConfig
|
async function updateConfig(options, programInstance) {
await configStore.updateConfig(config => {
originalConfig = config;
config.verbosity =
typeof program.verbosity === 'undefined'
? config.verbosity
: program.verbosity;
config.openServerAtStart =
typeof options.open === 'undefined'
? config.openServerAtStart
: options.open;
config.renderingService =
typeof options.renderingService === 'undefined'
? process.env.TRAVIS
? false
: config.renderingService
: options.renderingService;
config.env = process.env.NODE_ENV
? process.env.NODE_ENV
: typeof options.env === 'undefined'
? config.env
: options.env;
config.webpackStats =
typeof options.webpackStats === 'undefined'
? config.webpackStats
: options.webpackStats;
config.webpackDevServer =
typeof options.webpackDevServer === 'undefined'
? config.webpackDevServer
: options.webpackDevServer;
config.mode =
typeof options.mode === 'undefined' ? config.mode : options.mode;
config.quick =
typeof options.quick === 'undefined' ? config.quick : options.quick;
config.watch =
typeof options.watch === 'undefined' ? config.watch : options.watch;
config.prod =
typeof program.prod === 'undefined' ? config.prod : program.prod;
// automatically set enableSSR to true in prod mode and false in dev mode, unless manually set.
config.enableSSR = false;
config.i18n =
typeof options.i18n === 'undefined'
? config.prod
? true
: false
: options.i18n;
// If i18n is disabled, ignore and remove lang config settings
if (config.lang && config.i18n === false) {
// Remove any lang-specific settings for local dev to speed things up.
delete config['lang'];
}
return config;
});
const config = await configStore.getConfig();
log.dim(`Verbosity: ${config.verbosity}`);
log.dim(`Prod: ${config.prod}`);
log.dim(`i18n: ${config.i18n}`);
log.dim(
`enableSSR: ${config.enableSSR} ${
originalConfig.enableSSR ? '(manually set)' : '(auto set)'
}`,
);
log.dim(`Rendering Mode: ${config.mode}`);
if (config.verbosity > 2) {
log.dim(`Opening browser: ${config.openServerAtStart}`);
log.dim(`Quick mode: ${config.quick}`);
log.dim(`buildDir: ${config.buildDir}`);
log.dim(`dataDir: ${config.dataDir}`);
log.dim(`wwwDir: ${config.wwwDir}`);
}
// Basically at this point, the cli is bootstrapped and ready to go.
// Let's build the core bolt manifest
await buildBoltManifest();
return config;
}
|
javascript
|
async function updateConfig(options, programInstance) {
await configStore.updateConfig(config => {
originalConfig = config;
config.verbosity =
typeof program.verbosity === 'undefined'
? config.verbosity
: program.verbosity;
config.openServerAtStart =
typeof options.open === 'undefined'
? config.openServerAtStart
: options.open;
config.renderingService =
typeof options.renderingService === 'undefined'
? process.env.TRAVIS
? false
: config.renderingService
: options.renderingService;
config.env = process.env.NODE_ENV
? process.env.NODE_ENV
: typeof options.env === 'undefined'
? config.env
: options.env;
config.webpackStats =
typeof options.webpackStats === 'undefined'
? config.webpackStats
: options.webpackStats;
config.webpackDevServer =
typeof options.webpackDevServer === 'undefined'
? config.webpackDevServer
: options.webpackDevServer;
config.mode =
typeof options.mode === 'undefined' ? config.mode : options.mode;
config.quick =
typeof options.quick === 'undefined' ? config.quick : options.quick;
config.watch =
typeof options.watch === 'undefined' ? config.watch : options.watch;
config.prod =
typeof program.prod === 'undefined' ? config.prod : program.prod;
// automatically set enableSSR to true in prod mode and false in dev mode, unless manually set.
config.enableSSR = false;
config.i18n =
typeof options.i18n === 'undefined'
? config.prod
? true
: false
: options.i18n;
// If i18n is disabled, ignore and remove lang config settings
if (config.lang && config.i18n === false) {
// Remove any lang-specific settings for local dev to speed things up.
delete config['lang'];
}
return config;
});
const config = await configStore.getConfig();
log.dim(`Verbosity: ${config.verbosity}`);
log.dim(`Prod: ${config.prod}`);
log.dim(`i18n: ${config.i18n}`);
log.dim(
`enableSSR: ${config.enableSSR} ${
originalConfig.enableSSR ? '(manually set)' : '(auto set)'
}`,
);
log.dim(`Rendering Mode: ${config.mode}`);
if (config.verbosity > 2) {
log.dim(`Opening browser: ${config.openServerAtStart}`);
log.dim(`Quick mode: ${config.quick}`);
log.dim(`buildDir: ${config.buildDir}`);
log.dim(`dataDir: ${config.dataDir}`);
log.dim(`wwwDir: ${config.wwwDir}`);
}
// Basically at this point, the cli is bootstrapped and ready to go.
// Let's build the core bolt manifest
await buildBoltManifest();
return config;
}
|
[
"async",
"function",
"updateConfig",
"(",
"options",
",",
"programInstance",
")",
"{",
"await",
"configStore",
".",
"updateConfig",
"(",
"config",
"=>",
"{",
"originalConfig",
"=",
"config",
";",
"config",
".",
"verbosity",
"=",
"typeof",
"program",
".",
"verbosity",
"===",
"'undefined'",
"?",
"config",
".",
"verbosity",
":",
"program",
".",
"verbosity",
";",
"config",
".",
"openServerAtStart",
"=",
"typeof",
"options",
".",
"open",
"===",
"'undefined'",
"?",
"config",
".",
"openServerAtStart",
":",
"options",
".",
"open",
";",
"config",
".",
"renderingService",
"=",
"typeof",
"options",
".",
"renderingService",
"===",
"'undefined'",
"?",
"process",
".",
"env",
".",
"TRAVIS",
"?",
"false",
":",
"config",
".",
"renderingService",
":",
"options",
".",
"renderingService",
";",
"config",
".",
"env",
"=",
"process",
".",
"env",
".",
"NODE_ENV",
"?",
"process",
".",
"env",
".",
"NODE_ENV",
":",
"typeof",
"options",
".",
"env",
"===",
"'undefined'",
"?",
"config",
".",
"env",
":",
"options",
".",
"env",
";",
"config",
".",
"webpackStats",
"=",
"typeof",
"options",
".",
"webpackStats",
"===",
"'undefined'",
"?",
"config",
".",
"webpackStats",
":",
"options",
".",
"webpackStats",
";",
"config",
".",
"webpackDevServer",
"=",
"typeof",
"options",
".",
"webpackDevServer",
"===",
"'undefined'",
"?",
"config",
".",
"webpackDevServer",
":",
"options",
".",
"webpackDevServer",
";",
"config",
".",
"mode",
"=",
"typeof",
"options",
".",
"mode",
"===",
"'undefined'",
"?",
"config",
".",
"mode",
":",
"options",
".",
"mode",
";",
"config",
".",
"quick",
"=",
"typeof",
"options",
".",
"quick",
"===",
"'undefined'",
"?",
"config",
".",
"quick",
":",
"options",
".",
"quick",
";",
"config",
".",
"watch",
"=",
"typeof",
"options",
".",
"watch",
"===",
"'undefined'",
"?",
"config",
".",
"watch",
":",
"options",
".",
"watch",
";",
"config",
".",
"prod",
"=",
"typeof",
"program",
".",
"prod",
"===",
"'undefined'",
"?",
"config",
".",
"prod",
":",
"program",
".",
"prod",
";",
"// automatically set enableSSR to true in prod mode and false in dev mode, unless manually set.",
"config",
".",
"enableSSR",
"=",
"false",
";",
"config",
".",
"i18n",
"=",
"typeof",
"options",
".",
"i18n",
"===",
"'undefined'",
"?",
"config",
".",
"prod",
"?",
"true",
":",
"false",
":",
"options",
".",
"i18n",
";",
"// If i18n is disabled, ignore and remove lang config settings",
"if",
"(",
"config",
".",
"lang",
"&&",
"config",
".",
"i18n",
"===",
"false",
")",
"{",
"// Remove any lang-specific settings for local dev to speed things up.",
"delete",
"config",
"[",
"'lang'",
"]",
";",
"}",
"return",
"config",
";",
"}",
")",
";",
"const",
"config",
"=",
"await",
"configStore",
".",
"getConfig",
"(",
")",
";",
"log",
".",
"dim",
"(",
"`",
"${",
"config",
".",
"verbosity",
"}",
"`",
")",
";",
"log",
".",
"dim",
"(",
"`",
"${",
"config",
".",
"prod",
"}",
"`",
")",
";",
"log",
".",
"dim",
"(",
"`",
"${",
"config",
".",
"i18n",
"}",
"`",
")",
";",
"log",
".",
"dim",
"(",
"`",
"${",
"config",
".",
"enableSSR",
"}",
"${",
"originalConfig",
".",
"enableSSR",
"?",
"'(manually set)'",
":",
"'(auto set)'",
"}",
"`",
",",
")",
";",
"log",
".",
"dim",
"(",
"`",
"${",
"config",
".",
"mode",
"}",
"`",
")",
";",
"if",
"(",
"config",
".",
"verbosity",
">",
"2",
")",
"{",
"log",
".",
"dim",
"(",
"`",
"${",
"config",
".",
"openServerAtStart",
"}",
"`",
")",
";",
"log",
".",
"dim",
"(",
"`",
"${",
"config",
".",
"quick",
"}",
"`",
")",
";",
"log",
".",
"dim",
"(",
"`",
"${",
"config",
".",
"buildDir",
"}",
"`",
")",
";",
"log",
".",
"dim",
"(",
"`",
"${",
"config",
".",
"dataDir",
"}",
"`",
")",
";",
"log",
".",
"dim",
"(",
"`",
"${",
"config",
".",
"wwwDir",
"}",
"`",
")",
";",
"}",
"// Basically at this point, the cli is bootstrapped and ready to go.",
"// Let's build the core bolt manifest",
"await",
"buildBoltManifest",
"(",
")",
";",
"return",
"config",
";",
"}"
] |
Update config with all options flags
@param {Object} options
@param programInstance - The commander `program`
@returns {Object} config - Final updated config
|
[
"Update",
"config",
"with",
"all",
"options",
"flags"
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/build-tools/cli.js#L66-L156
|
13,596
|
bolt-design-system/bolt
|
packages/build-tools/plugins/postcss-themify/src/index.js
|
translateColor
|
function translateColor(colorArr, variationName, execMode) {
const [colorVar, alpha] = colorArr;
// returns the real color representation
if (!options.palette) {
options.palette = getColorPalette();
}
const underlineColor = options.palette[variationName][colorVar];
if (!underlineColor) {
// variable is not mandatory in non-default variations
if (variationName !== defaultVariation) {
return null;
}
throw new Error(
`The variable name '${colorVar}' doesn't exists in your palette.`,
);
}
switch (execMode) {
case ExecutionMode.CSS_COLOR:
// with default alpha - just returns the color
if (alpha === '1') {
return rgb2hex(underlineColor).hex;
}
// with custom alpha, convert it to rgba
const rgbaColor = hexToRgba(rgb2hex(underlineColor).hex, alpha);
return rgbaColor;
default:
if (alpha === 1) {
return `rgba(var(--bolt-theme-${colorVar}), ${alpha})`;
//return `var(--bolt-theme-${colorVar})`; // @todo: re-evaluate if hex values should ever get outputted here
} else {
return `rgba(var(--bolt-theme-${colorVar}), ${alpha})`;
}
}
}
|
javascript
|
function translateColor(colorArr, variationName, execMode) {
const [colorVar, alpha] = colorArr;
// returns the real color representation
if (!options.palette) {
options.palette = getColorPalette();
}
const underlineColor = options.palette[variationName][colorVar];
if (!underlineColor) {
// variable is not mandatory in non-default variations
if (variationName !== defaultVariation) {
return null;
}
throw new Error(
`The variable name '${colorVar}' doesn't exists in your palette.`,
);
}
switch (execMode) {
case ExecutionMode.CSS_COLOR:
// with default alpha - just returns the color
if (alpha === '1') {
return rgb2hex(underlineColor).hex;
}
// with custom alpha, convert it to rgba
const rgbaColor = hexToRgba(rgb2hex(underlineColor).hex, alpha);
return rgbaColor;
default:
if (alpha === 1) {
return `rgba(var(--bolt-theme-${colorVar}), ${alpha})`;
//return `var(--bolt-theme-${colorVar})`; // @todo: re-evaluate if hex values should ever get outputted here
} else {
return `rgba(var(--bolt-theme-${colorVar}), ${alpha})`;
}
}
}
|
[
"function",
"translateColor",
"(",
"colorArr",
",",
"variationName",
",",
"execMode",
")",
"{",
"const",
"[",
"colorVar",
",",
"alpha",
"]",
"=",
"colorArr",
";",
"// returns the real color representation",
"if",
"(",
"!",
"options",
".",
"palette",
")",
"{",
"options",
".",
"palette",
"=",
"getColorPalette",
"(",
")",
";",
"}",
"const",
"underlineColor",
"=",
"options",
".",
"palette",
"[",
"variationName",
"]",
"[",
"colorVar",
"]",
";",
"if",
"(",
"!",
"underlineColor",
")",
"{",
"// variable is not mandatory in non-default variations",
"if",
"(",
"variationName",
"!==",
"defaultVariation",
")",
"{",
"return",
"null",
";",
"}",
"throw",
"new",
"Error",
"(",
"`",
"${",
"colorVar",
"}",
"`",
",",
")",
";",
"}",
"switch",
"(",
"execMode",
")",
"{",
"case",
"ExecutionMode",
".",
"CSS_COLOR",
":",
"// with default alpha - just returns the color",
"if",
"(",
"alpha",
"===",
"'1'",
")",
"{",
"return",
"rgb2hex",
"(",
"underlineColor",
")",
".",
"hex",
";",
"}",
"// with custom alpha, convert it to rgba",
"const",
"rgbaColor",
"=",
"hexToRgba",
"(",
"rgb2hex",
"(",
"underlineColor",
")",
".",
"hex",
",",
"alpha",
")",
";",
"return",
"rgbaColor",
";",
"default",
":",
"if",
"(",
"alpha",
"===",
"1",
")",
"{",
"return",
"`",
"${",
"colorVar",
"}",
"${",
"alpha",
"}",
"`",
";",
"//return `var(--bolt-theme-${colorVar})`; // @todo: re-evaluate if hex values should ever get outputted here",
"}",
"else",
"{",
"return",
"`",
"${",
"colorVar",
"}",
"${",
"alpha",
"}",
"`",
";",
"}",
"}",
"}"
] |
Get the underline color, according to the execution mode
@param colorArr two sized array with the color and the alpha
@param variationName the name of the variation. e.g. light / dark
@param execMode
|
[
"Get",
"the",
"underline",
"color",
"according",
"to",
"the",
"execution",
"mode"
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/build-tools/plugins/postcss-themify/src/index.js#L200-L237
|
13,597
|
bolt-design-system/bolt
|
packages/build-tools/plugins/postcss-themify/src/index.js
|
processRules
|
function processRules(root) {
root.walkRules(rule => {
if (!hasThemify(rule.toString())) {
return;
}
let aggragatedSelectorsMap = {};
let aggragatedSelectors = [];
let createdRules = [];
const variationRules = {
[defaultVariation]: rule,
};
rule.walkDecls(decl => {
const propertyValue = decl.value;
if (!hasThemify(propertyValue)) return;
const property = decl.prop;
const variationValueMap = getThemifyValue(
propertyValue,
ExecutionMode.CSS_VAR,
);
const defaultVariationValue = variationValueMap[defaultVariation];
decl.value = defaultVariationValue;
// indicate if we have a global rule, that cannot be nested
const createNonDefaultVariationRules = isAtRule(rule);
// don't create extra CSS for global rules
if (createNonDefaultVariationRules) {
return;
}
// create a new declaration and append it to each rule
nonDefaultVariations.forEach(variationName => {
const currentValue = variationValueMap[variationName];
// variable for non-default variation is optional
if (!currentValue || currentValue === 'null') {
return;
}
// when the declaration is the same as the default variation,
// we just need to concatenate our selector to the default rule
if (currentValue === defaultVariationValue) {
const selector = getSelectorName(rule, variationName);
// append the selector once
if (!aggragatedSelectorsMap[variationName]) {
aggragatedSelectorsMap[variationName] = true;
aggragatedSelectors.push(selector);
}
} else {
// creating the rule for the first time
if (!variationRules[variationName]) {
const clonedRule = createRuleWithVariation(rule, variationName);
variationRules[variationName] = clonedRule;
// append the new rule to the array, so we can append it later
createdRules.push(clonedRule);
}
const variationDecl = createDecl(
property,
variationValueMap[variationName],
);
variationRules[variationName].append(variationDecl);
}
});
});
if (aggragatedSelectors.length) {
rule.selectors = [...rule.selectors];
// Don't add extra redundant CSS selectors to every component using CSS vars
// rule.selectors = [...rule.selectors, ...aggragatedSelectors];
}
// append each created rule
if (createdRules.length) {
createdRules.forEach(r => root.append(r));
}
});
}
|
javascript
|
function processRules(root) {
root.walkRules(rule => {
if (!hasThemify(rule.toString())) {
return;
}
let aggragatedSelectorsMap = {};
let aggragatedSelectors = [];
let createdRules = [];
const variationRules = {
[defaultVariation]: rule,
};
rule.walkDecls(decl => {
const propertyValue = decl.value;
if (!hasThemify(propertyValue)) return;
const property = decl.prop;
const variationValueMap = getThemifyValue(
propertyValue,
ExecutionMode.CSS_VAR,
);
const defaultVariationValue = variationValueMap[defaultVariation];
decl.value = defaultVariationValue;
// indicate if we have a global rule, that cannot be nested
const createNonDefaultVariationRules = isAtRule(rule);
// don't create extra CSS for global rules
if (createNonDefaultVariationRules) {
return;
}
// create a new declaration and append it to each rule
nonDefaultVariations.forEach(variationName => {
const currentValue = variationValueMap[variationName];
// variable for non-default variation is optional
if (!currentValue || currentValue === 'null') {
return;
}
// when the declaration is the same as the default variation,
// we just need to concatenate our selector to the default rule
if (currentValue === defaultVariationValue) {
const selector = getSelectorName(rule, variationName);
// append the selector once
if (!aggragatedSelectorsMap[variationName]) {
aggragatedSelectorsMap[variationName] = true;
aggragatedSelectors.push(selector);
}
} else {
// creating the rule for the first time
if (!variationRules[variationName]) {
const clonedRule = createRuleWithVariation(rule, variationName);
variationRules[variationName] = clonedRule;
// append the new rule to the array, so we can append it later
createdRules.push(clonedRule);
}
const variationDecl = createDecl(
property,
variationValueMap[variationName],
);
variationRules[variationName].append(variationDecl);
}
});
});
if (aggragatedSelectors.length) {
rule.selectors = [...rule.selectors];
// Don't add extra redundant CSS selectors to every component using CSS vars
// rule.selectors = [...rule.selectors, ...aggragatedSelectors];
}
// append each created rule
if (createdRules.length) {
createdRules.forEach(r => root.append(r));
}
});
}
|
[
"function",
"processRules",
"(",
"root",
")",
"{",
"root",
".",
"walkRules",
"(",
"rule",
"=>",
"{",
"if",
"(",
"!",
"hasThemify",
"(",
"rule",
".",
"toString",
"(",
")",
")",
")",
"{",
"return",
";",
"}",
"let",
"aggragatedSelectorsMap",
"=",
"{",
"}",
";",
"let",
"aggragatedSelectors",
"=",
"[",
"]",
";",
"let",
"createdRules",
"=",
"[",
"]",
";",
"const",
"variationRules",
"=",
"{",
"[",
"defaultVariation",
"]",
":",
"rule",
",",
"}",
";",
"rule",
".",
"walkDecls",
"(",
"decl",
"=>",
"{",
"const",
"propertyValue",
"=",
"decl",
".",
"value",
";",
"if",
"(",
"!",
"hasThemify",
"(",
"propertyValue",
")",
")",
"return",
";",
"const",
"property",
"=",
"decl",
".",
"prop",
";",
"const",
"variationValueMap",
"=",
"getThemifyValue",
"(",
"propertyValue",
",",
"ExecutionMode",
".",
"CSS_VAR",
",",
")",
";",
"const",
"defaultVariationValue",
"=",
"variationValueMap",
"[",
"defaultVariation",
"]",
";",
"decl",
".",
"value",
"=",
"defaultVariationValue",
";",
"// indicate if we have a global rule, that cannot be nested",
"const",
"createNonDefaultVariationRules",
"=",
"isAtRule",
"(",
"rule",
")",
";",
"// don't create extra CSS for global rules",
"if",
"(",
"createNonDefaultVariationRules",
")",
"{",
"return",
";",
"}",
"// create a new declaration and append it to each rule",
"nonDefaultVariations",
".",
"forEach",
"(",
"variationName",
"=>",
"{",
"const",
"currentValue",
"=",
"variationValueMap",
"[",
"variationName",
"]",
";",
"// variable for non-default variation is optional",
"if",
"(",
"!",
"currentValue",
"||",
"currentValue",
"===",
"'null'",
")",
"{",
"return",
";",
"}",
"// when the declaration is the same as the default variation,",
"// we just need to concatenate our selector to the default rule",
"if",
"(",
"currentValue",
"===",
"defaultVariationValue",
")",
"{",
"const",
"selector",
"=",
"getSelectorName",
"(",
"rule",
",",
"variationName",
")",
";",
"// append the selector once",
"if",
"(",
"!",
"aggragatedSelectorsMap",
"[",
"variationName",
"]",
")",
"{",
"aggragatedSelectorsMap",
"[",
"variationName",
"]",
"=",
"true",
";",
"aggragatedSelectors",
".",
"push",
"(",
"selector",
")",
";",
"}",
"}",
"else",
"{",
"// creating the rule for the first time",
"if",
"(",
"!",
"variationRules",
"[",
"variationName",
"]",
")",
"{",
"const",
"clonedRule",
"=",
"createRuleWithVariation",
"(",
"rule",
",",
"variationName",
")",
";",
"variationRules",
"[",
"variationName",
"]",
"=",
"clonedRule",
";",
"// append the new rule to the array, so we can append it later",
"createdRules",
".",
"push",
"(",
"clonedRule",
")",
";",
"}",
"const",
"variationDecl",
"=",
"createDecl",
"(",
"property",
",",
"variationValueMap",
"[",
"variationName",
"]",
",",
")",
";",
"variationRules",
"[",
"variationName",
"]",
".",
"append",
"(",
"variationDecl",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"if",
"(",
"aggragatedSelectors",
".",
"length",
")",
"{",
"rule",
".",
"selectors",
"=",
"[",
"...",
"rule",
".",
"selectors",
"]",
";",
"// Don't add extra redundant CSS selectors to every component using CSS vars",
"// rule.selectors = [...rule.selectors, ...aggragatedSelectors];",
"}",
"// append each created rule",
"if",
"(",
"createdRules",
".",
"length",
")",
"{",
"createdRules",
".",
"forEach",
"(",
"r",
"=>",
"root",
".",
"append",
"(",
"r",
")",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Walk through all rules, and replace each themify occurrence with the corresponding CSS variable.
@example background-color: themify(primary-300, 0.5) => background-color: rgba(var(--primary-300),0.6)
@param root
|
[
"Walk",
"through",
"all",
"rules",
"and",
"replace",
"each",
"themify",
"occurrence",
"with",
"the",
"corresponding",
"CSS",
"variable",
"."
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/build-tools/plugins/postcss-themify/src/index.js#L244-L328
|
13,598
|
bolt-design-system/bolt
|
packages/build-tools/plugins/postcss-themify/src/index.js
|
createRuleWithVariation
|
function createRuleWithVariation(rule, variationName) {
const selector = getSelectorName(rule, variationName);
return postcss.rule({
selector,
});
}
|
javascript
|
function createRuleWithVariation(rule, variationName) {
const selector = getSelectorName(rule, variationName);
return postcss.rule({
selector,
});
}
|
[
"function",
"createRuleWithVariation",
"(",
"rule",
",",
"variationName",
")",
"{",
"const",
"selector",
"=",
"getSelectorName",
"(",
"rule",
",",
"variationName",
")",
";",
"return",
"postcss",
".",
"rule",
"(",
"{",
"selector",
",",
"}",
")",
";",
"}"
] |
Create a new rule for the given variation, out of the original rule
@param rule
@param variationName
|
[
"Create",
"a",
"new",
"rule",
"for",
"the",
"given",
"variation",
"out",
"of",
"the",
"original",
"rule"
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/build-tools/plugins/postcss-themify/src/index.js#L477-L482
|
13,599
|
bolt-design-system/bolt
|
packages/build-tools/plugins/postcss-themify/src/index.js
|
createFallbackRuleWithVariation
|
function createFallbackRuleWithVariation(rule, variationName) {
const selector = getSelectorName(rule, variationName, true);
return postcss.rule({
selector,
});
}
|
javascript
|
function createFallbackRuleWithVariation(rule, variationName) {
const selector = getSelectorName(rule, variationName, true);
return postcss.rule({
selector,
});
}
|
[
"function",
"createFallbackRuleWithVariation",
"(",
"rule",
",",
"variationName",
")",
"{",
"const",
"selector",
"=",
"getSelectorName",
"(",
"rule",
",",
"variationName",
",",
"true",
")",
";",
"return",
"postcss",
".",
"rule",
"(",
"{",
"selector",
",",
"}",
")",
";",
"}"
] |
Create a new fallback-specific rule for the given variation, out of the original
@param rule
@param variationName
|
[
"Create",
"a",
"new",
"fallback",
"-",
"specific",
"rule",
"for",
"the",
"given",
"variation",
"out",
"of",
"the",
"original"
] |
c63ab37dbee8f35aa5472be2d9688f989b20fd21
|
https://github.com/bolt-design-system/bolt/blob/c63ab37dbee8f35aa5472be2d9688f989b20fd21/packages/build-tools/plugins/postcss-themify/src/index.js#L489-L494
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.