code
stringlengths
10
343k
docstring
stringlengths
36
21.9k
func_name
stringlengths
1
3.35k
language
stringclasses
1 value
repo
stringlengths
7
58
path
stringlengths
4
131
url
stringlengths
44
195
license
stringclasses
5 values
function _enableMarkdown(sQuery){ var waTarget = $(sQuery || "[markdown]"); // TODO: markdown=true waTarget.each(function(nIndex, elTarget){ _isEditableElement(elTarget) ? _setEditor($(elTarget)) : _setViewer($(elTarget)); }); }
enableMarkdown on target elements @param {String} sQuery Selector string for targets
_enableMarkdown ( sQuery )
javascript
yona-projects/yona
public/javascripts/common/yobi.Markdown.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yobi.Markdown.js
Apache-2.0
function _isEditableElement(elTarget){ var sTagName = elTarget.tagName.toUpperCase(); return (sTagName === "TEXTAREA" || sTagName === "INPUT" || elTarget.contentEditable == "true"); }
Returns that specified element is editable @param {HTMLElement} elTarget @return {Boolean}
_isEditableElement ( elTarget )
javascript
yona-projects/yona
public/javascripts/common/yobi.Markdown.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yobi.Markdown.js
Apache-2.0
function getProjectLabels(){ var allLabels = {}; $("#labelIds > optgroup").each(function(){ var allLabelsOfTheCategory = []; var categoryId; $(this).children().each(function(){ $this = $(this); allLabelsOfTheCategory.push($this.val()); categoryId = $this.data("categoryId") }); allLabels[categoryId] = allLabelsOfTheCategory; }); return allLabels; }
It gather all project labels. Category id is used for the key. Label ids are used for the value. { 31: [130, 120, ...], 70: [200, 201, 320, ...] }
getProjectLabels ( )
javascript
yona-projects/yona
public/javascripts/common/yona.TitleHeadAutoCompletion.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yona.TitleHeadAutoCompletion.js
Apache-2.0
function _init(htOptions){ htOptions = htOptions || {}; htVar.sListURL = htOptions.sListURL; htVar.sUploadURL = htOptions.sUploadURL; htVar.htUploadOpts = htOptions.htUploadOpts || {"dataType": "json"}; // XMLHttpRequest2 file upload // The FileReader API is not actually used, but works as feature detection. // Check for window.ProgressEvent instead to detect XHR2 file upload capability // ref: http://blueimp.github.io/jQuery-File-Upload htVar.bXHR2 = !!(window.ProgressEvent && window.FileReader) && !!window.FormData; // HTTPS connection is required for XHR upload on MSIE Browsers // even if FormData feature available. if(navigator.userAgent.toLowerCase().indexOf("trident") > -1){ htVar.bXHR2 = htVar.bXHR2 && (location.protocol.toLowerCase().indexOf("https") > -1); } // HTML5 FileAPI required htVar.bDroppable = (typeof window.File != "undefined") && htVar.bXHR2; // onpaste & XHR2 required htVar.bPastable = (typeof document.onpaste != "undefined") && htVar.bXHR2 && (navigator.userAgent.indexOf("FireFox") === -1); // and not FireFox // maximum filesize (<= 2,147,483,454 bytes = 2Gb) htVar.nMaxFileSize = htOptions.maxFileSize || 2147483454; }
initialize fileUploader @param {Hash Table} htOptions @param {String} htOptions.sListURL @param {String} htOptions.sUploadURL
_init ( htOptions )
javascript
yona-projects/yona
public/javascripts/common/yobi.Files.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yobi.Files.js
Apache-2.0
function _getEnv(){ return htVar; }
Returns Environment information @return {Hash Table}
_getEnv ( )
javascript
yona-projects/yona
public/javascripts/common/yobi.Files.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yobi.Files.js
Apache-2.0
function _uploadFile(oFiles, sNamespace){ if(oFiles && oFiles.length){ for(var i = 0; i < oFiles.length; i++){ _uploadSingleFile(oFiles[i], _getSubmitId(), sNamespace); } } else { _uploadSingleFile(oFiles, _getSubmitId(), sNamespace); } }
Upload files @param {Variant} oFiles FileList or File Object, HTMLInputElement(IE) @param {String} sNamespace (Optional)
_uploadFile ( oFiles , sNamespace )
javascript
yona-projects/yona
public/javascripts/common/yobi.Files.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yobi.Files.js
Apache-2.0
function _uploadSingleFile(oFile, nSubmitId, sNamespace){ // append file on list if(oFile){ oFile.nSubmitId = nSubmitId || _getSubmitId(); } // fireEvent: beforeUpload var bEventResult = _fireEvent("beforeUpload", { "oFile": oFile, "nSubmitId": oFile ? oFile.nSubmitId : nSubmitId }, sNamespace); if(bEventResult === false){ // upload cancel by event handler return false; } return htVar.bXHR2 ? _uploadFileXHR(nSubmitId, oFile, sNamespace) : _uploadFileForm(nSubmitId, oFile, sNamespace); }
Upload single file with specified submitId @param {File} oFile @param {Number} nSubmitId @param {String} sNamespace (Optional)
_uploadSingleFile ( oFile , nSubmitId , sNamespace )
javascript
yona-projects/yona
public/javascripts/common/yobi.Files.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yobi.Files.js
Apache-2.0
function _uploadFileForm(nSubmitId, elFile, sNamespace){ var htElement = htElements[sNamespace]; if(!htElement.welInputFile && !elFile){ return false; } var welInputFile = htElement.welInputFile || $(elFile); var welInputFileClone = welInputFile.clone(); var welForm = $('<form method="post" enctype="multipart/form-data" style="display:none">'); welInputFileClone.insertAfter(welInputFile); welInputFileClone.on("change", $.proxy(_onChangeFile, this, sNamespace)); htElement.welInputFile = welInputFileClone; welForm.attr('action', htVar.sUploadURL); welForm.append(welInputFile).appendTo(document.body); // free memory finally var fClear = function(){ welInputFile.remove(); welForm.remove(); welForm = welInputFile = null; }; var htUploadOpts = htVar.htUploadOpts; htUploadOpts.success = function(oRes){ _onSuccessSubmit(nSubmitId, oRes, sNamespace); fClear(); fClear = null; }; htUploadOpts.uploadProgress = function(oEvent, nPos, nTotal, nPercentComplete){ _onUploadProgress(nSubmitId, nPercentComplete, sNamespace); fClear(); fClear = null; }; htUploadOpts.error = function(oRes){ _onErrorSubmit(nSubmitId, oRes, sNamespace); fClear(); fClear = null; }; welForm.ajaxForm(htUploadOpts); welForm.submit(); }
Upload file with $.ajaxForm available in almost browsers, except Safari on OSX. Reference: http://malsup.com/jquery/form/ @param {Number} nSubmitId @param {HTMLElement} elFile @param {String} sNamespace
_uploadFileForm ( nSubmitId , elFile , sNamespace )
javascript
yona-projects/yona
public/javascripts/common/yobi.Files.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yobi.Files.js
Apache-2.0
function _onUploadProgress(nSubmitId, nPercentComplete, sNamespace){ _fireEvent("uploadProgress", { "nSubmitId": nSubmitId, "nPercentComplete": nPercentComplete }, sNamespace); }
uploadProgress event handler @param {Object} oEvent @param {Number} nPercentComplete
_onUploadProgress ( nSubmitId , nPercentComplete , sNamespace )
javascript
yona-projects/yona
public/javascripts/common/yobi.Files.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yobi.Files.js
Apache-2.0
function _onSuccessSubmit(nSubmitId, oRes, sNamespace){ // Validate server response if(!(oRes instanceof Object) || !oRes.name || !oRes.url){ return _onErrorSubmit(nSubmitId, oRes); } // clear inputFile if(sNamespace && htElements[sNamespace] && htElements[sNamespace].welInputFile){ htElements[sNamespace].welInputFile.val(""); } // fireEvent: onSuccessSubmit _fireEvent("successUpload", { "nSubmitId": nSubmitId, "oRes": oRes }, sNamespace); }
On success to submit temporary form created in onChangeFile() @param {Hash Table} htData @return
_onSuccessSubmit ( nSubmitId , oRes , sNamespace )
javascript
yona-projects/yona
public/javascripts/common/yobi.Files.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yobi.Files.js
Apache-2.0
function _onErrorSubmit(nSubmitId, oRes, sNamespace){ // fireEvent: onError _fireEvent("errorUpload", { "nSubmitId": nSubmitId, "oRes": oRes }, sNamespace); }
On error to submit temporary form created in onChangeFile(). @param {Number} nSubmitId @param {Object} oRes
_onErrorSubmit ( nSubmitId , oRes , sNamespace )
javascript
yona-projects/yona
public/javascripts/common/yobi.Files.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yobi.Files.js
Apache-2.0
function _deleteFile(htOptions){ $yobi.sendForm({ "sURL" : htOptions.sURL, "fOnLoad" : htOptions.fOnLoad, "fOnError" : htOptions.fOnError, "htData" : {"_method":"delete"}, "htOptForm": { "method" :"post", "enctype":"multipart/form-data" } }); }
delete specified file @param {Hash Table} htOptions @param {String} htOptions.sURL @param {Function} htOptions.fOnLoad @param {Function} htOptions.fOnError
_deleteFile ( htOptions )
javascript
yona-projects/yona
public/javascripts/common/yobi.Files.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yobi.Files.js
Apache-2.0
function _getFileList(htOptions){ $.ajax({ "type" : "get", "url" : htVar.sListURL, "success": htOptions.fOnLoad, "error" : htOptions.fOnError, "data" : { "containerType": htOptions.sResourceType, "containerId" : htOptions.sResourceId } }); }
request attached file list @param {Hash Table} htOptions @param {String} htOptions.sResourceType @param {String} htOptions.sResourceId @param {Function} htOptions.fOnLoad @param {Function} htOptions.fOnError
_getFileList ( htOptions )
javascript
yona-projects/yona
public/javascripts/common/yobi.Files.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yobi.Files.js
Apache-2.0
function _getUploader(elContainer, elTextarea, sNamespace){ sNamespace = sNamespace || _getSubmitId(); // only single uploader can be attached on single Container/Textarea if($(elContainer).data("isYobiUploader") || $(elTextarea).data("isYobiUploader")){ return false; } _initElement({ "elContainer": elContainer, "elTextarea" : elTextarea, "sNamespace" : sNamespace }); _attachEvent(sNamespace); return htElements[sNamespace].welContainer; }
@param {HTMLElement} elContainer @param {HTMLTextareaElement} elTextarea (Optional) @param {String} sNamespace @return {Wrapped Element}
_getUploader ( elContainer , elTextarea , sNamespace )
javascript
yona-projects/yona
public/javascripts/common/yobi.Files.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yobi.Files.js
Apache-2.0
function _initElement(htOptions){ var sNamespace = htOptions.sNamespace; htElements[sNamespace] = {}; htElements[sNamespace].welContainer = $(htOptions.elContainer); htElements[sNamespace].welTextarea = $(htOptions.elTextarea); htElements[sNamespace].welInputFile = htElements[sNamespace].welContainer.find("input[type=file]"); htElements[sNamespace].welContainer.attr("data-namespace", sNamespace); if(!htVar.bXHR2){ htElements[sNamespace].welInputFile.attr("multiple", null); } }
@param {Hash Table} htOptions @param {HTMLElement} htOptions.elContainer @param {HTMLTextareaElement} htOptions.elTextarea (Optional) @param {String} sNamespace
_initElement ( htOptions )
javascript
yona-projects/yona
public/javascripts/common/yobi.Files.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yobi.Files.js
Apache-2.0
function _onDragOver(sNamespace, weEvt){ _showDropper(); weEvt.stopPropagation(); weEvt.preventDefault(); return false; }
@param sNamespace @param weEvt @returns {boolean} @private
_onDragOver ( sNamespace , weEvt )
javascript
yona-projects/yona
public/javascripts/common/yobi.Files.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yobi.Files.js
Apache-2.0
function _onDragEnter(sNamespace, weEvt){ _showDropper(); weEvt.originalEvent.dataTransfer.dropEffect = _getDropEffect(weEvt); weEvt.stopPropagation(); weEvt.preventDefault(); }
@param sNamespace @param weEvt @private
_onDragEnter ( sNamespace , weEvt )
javascript
yona-projects/yona
public/javascripts/common/yobi.Files.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yobi.Files.js
Apache-2.0
function _getDropEffect(weEvt){ var oData = weEvt.originalEvent.dataTransfer; if(!oData.types){ return "none"; } if(oData.types.indexOf("text/uri-list") > -1){ return "link"; } else if((oData.types.indexOf("Files") > -1) || (oData.types.indexOf("text/plain") > -1)){ return "copy"; } return "none"; }
@param weEvt @returns {string} @private
_getDropEffect ( weEvt )
javascript
yona-projects/yona
public/javascripts/common/yobi.Files.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yobi.Files.js
Apache-2.0
function _onChangeFile(sNamespace){ var htElement = htElements[sNamespace]; var sFileName = _getBasename(htElement.welInputFile.val()); if(!sFileName || sFileName === ""){ return; } _uploadFile(htElement.welInputFile[0].files || htElement.welInputFile[0], sNamespace); }
change event handler on input[type="file"] @param {String} sNamespace
_onChangeFile ( sNamespace )
javascript
yona-projects/yona
public/javascripts/common/yobi.Files.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yobi.Files.js
Apache-2.0
function _onDropFile(sNamespace, weEvt){ _hideDropper(); var oFiles = weEvt.originalEvent.dataTransfer.files; if(!oFiles || oFiles.length === 0){ return; } _uploadFile(oFiles, sNamespace); _fireEvent("dropFile", { "weEvt" : weEvt, "oFiles": oFiles }, sNamespace); weEvt.stopPropagation(); weEvt.preventDefault(); return false; }
@param {String} sNamespace @param {Wrapped Event} weEvt
_onDropFile ( sNamespace , weEvt )
javascript
yona-projects/yona
public/javascripts/common/yobi.Files.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yobi.Files.js
Apache-2.0
function _getSubmitId(){ var now = new Date(); return now.getSeconds() + "" + now.getMilliseconds() + '-' + now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate() + '-' + now.getHours() + '-' + now.getMinutes(); }
Get submitId for each upload @return {Number}
_getSubmitId ( )
javascript
yona-projects/yona
public/javascripts/common/yobi.Files.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yobi.Files.js
Apache-2.0
function _getBasename(sPath){ var sSeparator = 'fakepath'; var nPos = sPath.indexOf(sSeparator); return (nPos > -1) ? sPath.substring(nPos + sSeparator.length + 1) : sPath; }
return trailing name component of path @param {String} sPath @return {String}
_getBasename ( sPath )
javascript
yona-projects/yona
public/javascripts/common/yobi.Files.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yobi.Files.js
Apache-2.0
function _attachCustomEvent(sEventName, fHandler, sNamespace){ if(typeof sEventName === "object"){ sNamespace = fHandler ? (fHandler+".") : ""; for(var sKey in sEventName){ htHandlers[sNamespace + sKey] = htHandlers[sNamespace + sKey] || []; htHandlers[sNamespace + sKey].push(sEventName[sKey]); } } else { sNamespace = sNamespace ? (sNamespace+".") : ""; htHandlers[sNamespace + sEventName] = htHandlers[sNamespace + sEventName] || []; htHandlers[sNamespace + sEventName].push(fHandler); } }
Attach custom event handler @param {String} sEventName @param {Function} fHandler @param {String} sNamespace @example yobi.Files.attach("eventName", function(){}, "namespace"); // or yobi.Files.attach({ "event1st": function(){}, "event2nd": function(){} }, "namespace");
_attachCustomEvent ( sEventName , fHandler , sNamespace )
javascript
yona-projects/yona
public/javascripts/common/yobi.Files.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yobi.Files.js
Apache-2.0
function _detachCustomEvent(sEventName, fHandler, sNamespace){ sNamespace = sNamespace ? (sNamespace+".") : ""; if(!fHandler){ htHandlers[sNamespace + sEventName] = []; return; } var aHandlers = htHandlers[sNamespace + sEventName]; var nIndex = aHandlers ? aHandlers.indexOf(fHandler) : -1; if(nIndex > -1){ htHandlers[sNamespace + sEventName].splice(nIndex, 1); } }
Detach custom event handler clears all handler of sEventName when fHandler is empty @param {String} sEventName @param {Function} fHandler @param {String} sNamespace
_detachCustomEvent ( sEventName , fHandler , sNamespace )
javascript
yona-projects/yona
public/javascripts/common/yobi.Files.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yobi.Files.js
Apache-2.0
function _fireEvent(sEventName, oData, sNamespace){ sNamespace = sNamespace ? (sNamespace+".") : ""; var aGlobalHandlers = htHandlers[sEventName] || []; var aLocalHandlers = htHandlers[sNamespace + sEventName] || []; var aHandlers = aGlobalHandlers.concat(aLocalHandlers); if((aHandlers instanceof Array) === false){ return; } var bResult; aHandlers.forEach(function(fHandler){ bResult = bResult || fHandler(oData); }); return bResult; }
Run specified custom event handlers @param {String} sEventName @param {Object} oData @param {String} sNamespace
_fireEvent ( sEventName , oData , sNamespace )
javascript
yona-projects/yona
public/javascripts/common/yobi.Files.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yobi.Files.js
Apache-2.0
(function(ns){ var oNS = $yobi.createNamespace(ns); oNS.container[oNS.name] = function(htOptions){ var htVar = {"sValue":""}; var htElement = {}; function _init(htOptions){ _initElement(htOptions); _attachEvent(); htVar.fOnChange = htOptions.fOnChange; _selectDefault(); } function _initElement(htOptions){ htElement.welContainer = $(htOptions.elContainer); htElement.welSelectedLabel = htElement.welContainer.find(".d-label"); htElement.welList = htElement.welContainer.find(".dropdown-menu"); htElement.waItems = htElement.welList.find("li"); } function _attachEvent(){ htElement.welList.on("click", "li", _onClickItem); htElement.welList.on("mousewheel", _onScrollList); } /** * @param weEvt * @returns {boolean} * @private */ function _onScrollList(weEvt){ if((weEvt.originalEvent.deltaY > 0 && _isScrollEndOfList()) || (weEvt.originalEvent.deltaY < 0 && _isScrollTopOfList())){ weEvt.preventDefault(); weEvt.stopPropagation(); return false; } } /** * @returns {boolean} * @private */ function _isScrollTopOfList(){ return (htElement.welList.scrollTop() === 0); } /** * @returns {boolean} * @private */ function _isScrollEndOfList(){ return (htElement.welList.scrollTop() + htElement.welList.height() === htElement.welList.get(0).scrollHeight); } /** * @param {Wrapped Event} weEvt */ function _onClickItem(weEvt){ // set welTarget to <li> item var welCurrent = $(weEvt.target); var welTarget = (weEvt.target.tagName === "LI") ? welCurrent : $(welCurrent.parents("li")[0]); // ignore click event if item doesn't have data-value attribute if(welTarget.length === 0 || typeof welTarget.attr("data-value") === "undefined"){ weEvt.stopPropagation(); weEvt.preventDefault(); return false; } _setItemSelected(welTarget); // display _setFormValue(welTarget); // set form value _onChange(); // fireEvent } /** * @param {Wrapped Element} welTarget */ function _setItemSelected(welTarget){ htElement.welSelectedLabel.html(welTarget.html()); htElement.waItems.removeClass("active"); welTarget.addClass("active"); } /** * @param {Wrapped Element} welTarget */ function _setFormValue(welTarget){ var sFieldValue = welTarget.attr("data-value"); var sFieldName = htElement.welContainer.attr("data-name"); htVar.sName = sFieldName; htVar.sValue = sFieldValue; if(typeof sFieldName === "undefined"){ return; } var welInput = htElement.welContainer.find("input[name='" + sFieldName +"']"); if(welInput.length === 0){ welInput = $('<input type="hidden" name="' + sFieldName + '">'); htElement.welContainer.append(welInput); } welInput.val(sFieldValue); } function _onChange(){ if(typeof htVar.fOnChange == "function"){ setTimeout(function(){ htVar.fOnChange(_getValue()); }, 0); } } /** * @param {Function} fOnChange */ function _setOnChange(fOnChange){ htVar.fOnChange = fOnChange; return true; } /** * @return {String} */ function _getValue(){ return htVar.sValue; } function _selectDefault(){ return _selectItem("li[data-selected=true]"); } /** * @param {String} sValue */ function _selectByValue(sValue){ return _selectItem("li[data-value='" + sValue + "']"); } /** * @param {String} sQuery */ function _selectItem(sQuery){ var waFind = htElement.welContainer.find(sQuery); if(waFind.length <= 0){ return false; // no item matches } var welTarget = $(waFind[0]); _setItemSelected(welTarget); _setFormValue(welTarget); return true; } _init(htOptions); return { "getValue": _getValue, "onChange": _setOnChange, "selectByValue": _selectByValue, "selectItem" : _selectItem }; }; })("yobi.ui.Dropdown");
@example var oSelect = new yobi.Dropdown({ "elContainer": ".btn-group", "fOnChange" : function(){}, " }); @require bootstrap-dropdown.js
(anonymous) ( ns )
javascript
yona-projects/yona
public/javascripts/common/yobi.ui.Dropdown.js
https://github.com/yona-projects/yona/blob/master/public/javascripts/common/yobi.ui.Dropdown.js
Apache-2.0
exports.navigate = (url) => ({ type: 'NAVIGATE', payload: { url } })
Copyright 2020 - Offen Authors <[email protected]> SPDX-License-Identifier: Apache-2.0
exports.navigate
javascript
offen/offen
auditorium/src/action-creators/navigation.js
https://github.com/offen/offen/blob/master/auditorium/src/action-creators/navigation.js
Apache-2.0
module.exports = (state = {}, action) => { switch (action.type) { case 'UDPATE_QUERY_PARAMS': return action.payload default: return state } }
Copyright 2021 - Offen Authors <[email protected]> SPDX-License-Identifier: Apache-2.0
module.exports
javascript
offen/offen
auditorium/src/reducers/query-params.js
https://github.com/offen/offen/blob/master/auditorium/src/reducers/query-params.js
Apache-2.0
function makeSourceObj(sourceName, sourceFn) { var results = { url: undefined, isStarted: false, isComplete: false, color: "black" } return { results: results, name: sourceName, isComplete: function(){ return results.isComplete }, isStarted: function(){ return results.isStarted }, run: function(){ results.isStarted = true sourceFn(results) }, getUrl: function(){ return results.url }, isGold: function(){ return results.color == "gold" }, isGreen: function(){ return results.color == "green" }, isBronze: function(){ return results.color == "bronze" } } }
********************************************************************************* Sources ***********************************************************************************
makeSourceObj ( sourceName , sourceFn )
javascript
ourresearch/unpaywall-extension
extension/unpaywall.js
https://github.com/ourresearch/unpaywall-extension/blob/master/extension/unpaywall.js
MIT
function runRegexOnDoc(re, host){ // @re regex that has a submatch in it that we're searching for, like /foo(.+?)bar/ // @host optional. only work on this host. if (!host || host == myHost){ var m = re.exec(docAsStr) if (m && m.length > 1){ return m[1] } } return false }
********************************************************************************* Page scraping functions, for DOIs and PDF links ***********************************************************************************
runRegexOnDoc ( re , host )
javascript
ourresearch/unpaywall-extension
extension/unpaywall.js
https://github.com/ourresearch/unpaywall-extension/blob/master/extension/unpaywall.js
MIT
function insertIframe(name, url){ var iframe = document.createElement('iframe'); // make sure we are not inserting iframe again and again if (iframeIsInserted){ return false } iframe.src = browser.runtime.getURL('unpaywall.html'); iframe.style.height = "50px"; iframe.style.width = '50px'; iframe.style.position = 'fixed'; iframe.style.right = '0'; iframe.style.top = '33%'; iframe.scrolling = 'no'; iframe.style.border = '0'; iframe.style.zIndex = '9999999999'; iframe.style.display = 'none;' iframe.id = "unpaywall"; // set a custom name and URL iframe.name = name + "#" + encodeURI(url) document.documentElement.appendChild(iframe); iframeIsInserted = true
********************************************************************************* utility and UX functions ***********************************************************************************
insertIframe ( name , url )
javascript
ourresearch/unpaywall-extension
extension/unpaywall.js
https://github.com/ourresearch/unpaywall-extension/blob/master/extension/unpaywall.js
MIT
function run() { reportInstallation() // Setting globally. Used when we search the doc with regex for DOI. docAsStr = document.documentElement.innerHTML; doi = findDoi() // setting this globally. // the meat of the extension does not run unless we find a DOI if (!doi){ return } devLog("we have a doi!", doi) startSearches() // poll, waiting for all our data to be collected. once it is, // make a call and inject the iframe, then quit. var resultsChecker = setInterval(function(){ var searchResults = getSearchResults() if (searchResults){ insertIframe(searchResults.color, searchResults.url) clearInterval(resultsChecker) // stop polling } }, 250)
********************************************************************************* main method ***********************************************************************************
run ( )
javascript
ourresearch/unpaywall-extension
extension/unpaywall.js
https://github.com/ourresearch/unpaywall-extension/blob/master/extension/unpaywall.js
MIT
send (chunk) { if (this.destroying) return if (this.destroyed) throw errCode(new Error('cannot send after peer is destroyed'), 'ERR_DESTROYED') this._channel.send(chunk) }
Send text/binary data to the remote peer. @param {ArrayBufferView|ArrayBuffer|Buffer|string|Blob} chunk
send ( chunk )
javascript
feross/simple-peer
index.js
https://github.com/feross/simple-peer/blob/master/index.js
MIT
addTransceiver (kind, init) { if (this.destroying) return if (this.destroyed) throw errCode(new Error('cannot addTransceiver after peer is destroyed'), 'ERR_DESTROYED') this._debug('addTransceiver()') if (this.initiator) { try { this._pc.addTransceiver(kind, init) this._needsNegotiation() } catch (err) { this.destroy(errCode(err, 'ERR_ADD_TRANSCEIVER')) } } else { this.emit('signal', { // request initiator to renegotiate type: 'transceiverRequest', transceiverRequest: { kind, init } }) } }
Add a Transceiver to the connection. @param {String} kind @param {Object} init
addTransceiver ( kind , init )
javascript
feross/simple-peer
index.js
https://github.com/feross/simple-peer/blob/master/index.js
MIT
addStream (stream) { if (this.destroying) return if (this.destroyed) throw errCode(new Error('cannot addStream after peer is destroyed'), 'ERR_DESTROYED') this._debug('addStream()') stream.getTracks().forEach(track => { this.addTrack(track, stream) }) }
Add a MediaStream to the connection. @param {MediaStream} stream
addStream ( stream )
javascript
feross/simple-peer
index.js
https://github.com/feross/simple-peer/blob/master/index.js
MIT
addTrack (track, stream) { if (this.destroying) return if (this.destroyed) throw errCode(new Error('cannot addTrack after peer is destroyed'), 'ERR_DESTROYED') this._debug('addTrack()') const submap = this._senderMap.get(track) || new Map() // nested Maps map [track, stream] to sender let sender = submap.get(stream) if (!sender) { sender = this._pc.addTrack(track, stream) submap.set(stream, sender) this._senderMap.set(track, submap) this._needsNegotiation() } else if (sender.removed) { throw errCode(new Error('Track has been removed. You should enable/disable tracks that you want to re-add.'), 'ERR_SENDER_REMOVED') } else { throw errCode(new Error('Track has already been added to that stream.'), 'ERR_SENDER_ALREADY_ADDED') } }
Add a MediaStreamTrack to the connection. @param {MediaStreamTrack} track @param {MediaStream} stream
addTrack ( track , stream )
javascript
feross/simple-peer
index.js
https://github.com/feross/simple-peer/blob/master/index.js
MIT
var Typed = (function () { function Typed(elementId, options) { _classCallCheck(this, Typed); // Initialize it up _initializerJs.initializer.load(this, options, elementId); // All systems go! this.begin(); } /** * Toggle start() and stop() of the Typed instance * @public */ _createClass(Typed, [{ key: 'toggle', value: function toggle() { this.pause.status ? this.start() : this.stop(); } /** * Stop typing / backspacing and enable cursor blinking * @public */ }, { key: 'stop', value: function stop() { if (this.typingComplete) return; if (this.pause.status) return; this.toggleBlinking(true); this.pause.status = true; this.options.onStop(this.arrayPos, this); } /** * Start typing / backspacing after being stopped * @public */ }, { key: 'start', value: function start() { if (this.typingComplete) return; if (!this.pause.status) return; this.pause.status = false; if (this.pause.typewrite) { this.typewrite(this.pause.curString, this.pause.curStrPos); } else { this.backspace(this.pause.curString, this.pause.curStrPos); } this.options.onStart(this.arrayPos, this); } /** * Destroy this instance of Typed * @public */ }, { key: 'destroy', value: function destroy() { this.reset(false); this.options.onDestroy(this); } /** * Reset Typed and optionally restarts * @param {boolean} restart * @public */ }, { key: 'reset', value: function reset() { var restart = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0]; clearInterval(this.timeout); this.replaceText(''); if (this.cursor && this.cursor.parentNode) { this.cursor.parentNode.removeChild(this.cursor); this.cursor = null; } this.strPos = 0; this.arrayPos = 0; this.curLoop = 0; if (restart) { this.insertCursor(); this.options.onReset(this); this.begin(); } } /** * Begins the typing animation * @private */ }, { key: 'begin', value: function begin() { var _this = this; this.options.onBegin(this); this.typingComplete = false; this.shuffleStringsIfNeeded(this); this.insertCursor(); if (this.bindInputFocusEvents) this.bindFocusEvents(); this.timeout = setTimeout(function () { // Check if there is some text in the element, if yes start by backspacing the default message if (!_this.currentElContent || _this.currentElContent.length === 0) { _this.typewrite(_this.strings[_this.sequence[_this.arrayPos]], _this.strPos); } else { // Start typing _this.backspace(_this.currentElContent, _this.currentElContent.length); } }, this.startDelay); } /** * Called for each character typed * @param {string} curString the current string in the strings array * @param {number} curStrPos the current position in the curString * @private */ }, { key: 'typewrite', value: function typewrite(curString, curStrPos) { var _this2 = this; if (this.fadeOut && this.el.classList.contains(this.fadeOutClass)) { this.el.classList.remove(this.fadeOutClass); if (this.cursor) this.cursor.classList.remove(this.fadeOutClass); } var humanize = this.humanizer(this.typeSpeed); var numChars = 1; if (this.pause.status === true) { this.setPauseStatus(curString, curStrPos, true); return; } // contain typing function in a timeout humanize'd delay this.timeout = setTimeout(function () { // skip over any HTML chars curStrPos = _htmlParserJs.htmlParser.typeHtmlChars(curString, curStrPos, _this2); var pauseTime = 0; var substr = curString.substr(curStrPos); // check for an escape character before a pause value // format: \^\d+ .. eg: ^1000 .. should be able to print the ^ too using ^^ // single ^ are removed from string if (substr.charAt(0) === '^') { if (/^\^\d+/.test(substr)) { var skip = 1; // skip at least 1 substr = /\d+/.exec(substr)[0]; skip += substr.length; pauseTime = parseInt(substr); _this2.temporaryPause = true; _this2.options.onTypingPaused(_this2.arrayPos, _this2); // strip out the escape character and pause value so they're not printed curString = curString.substring(0, curStrPos) + curString.substring(curStrPos + skip); _this2.toggleBlinking(true); } } // check for skip characters formatted as // "this is a `string to print NOW` ..." if (substr.charAt(0) === '`') { while (curString.substr(curStrPos + numChars).charAt(0) !== '`') { numChars++; if (curStrPos + numChars > curString.length) break; } // strip out the escape characters and append all the string in between var stringBeforeSkip = curString.substring(0, curStrPos); var stringSkipped = curString.substring(stringBeforeSkip.length + 1, curStrPos + numChars); var stringAfterSkip = curString.substring(curStrPos + numChars + 1); curString = stringBeforeSkip + stringSkipped + stringAfterSkip; numChars--; } // timeout for any pause after a character _this2.timeout = setTimeout(function () { // Accounts for blinking while paused _this2.toggleBlinking(false); // We're done with this sentence! if (curStrPos >= curString.length) { _this2.doneTyping(curString, curStrPos); } else { _this2.keepTyping(curString, curStrPos, numChars); } // end of character pause if (_this2.temporaryPause) { _this2.temporaryPause = false; _this2.options.onTypingResumed(_this2.arrayPos, _this2); } }, pauseTime); // humanized value for typing }, humanize); } /** * Continue to the next string & begin typing * @param {string} curString the current string in the strings array * @param {number} curStrPos the current position in the curString * @private */ }, { key: 'keepTyping', value: function keepTyping(curString, curStrPos, numChars) { // call before functions if applicable if (curStrPos === 0) { this.toggleBlinking(false); this.options.preStringTyped(this.arrayPos, this); } // start typing each new char into existing string // curString: arg, this.el.html: original text inside element curStrPos += numChars; var nextString = curString.substr(0, curStrPos); this.replaceText(nextString); // loop the function this.typewrite(curString, curStrPos); } /** * We're done typing the current string * @param {string} curString the current string in the strings array * @param {number} curStrPos the current position in the curString * @private */ }, { key: 'doneTyping', value: function doneTyping(curString, curStrPos) { var _this3 = this; // fires callback function this.options.onStringTyped(this.arrayPos, this); this.toggleBlinking(true); // is this the final string if (this.arrayPos === this.strings.length - 1) { // callback that occurs on the last typed string this.complete(); // quit if we wont loop back if (this.loop === false || this.curLoop === this.loopCount) { return; } } this.timeout = setTimeout(function () { _this3.backspace(curString, curStrPos); }, this.backDelay); } /** * Backspaces 1 character at a time * @param {string} curString the current string in the strings array * @param {number} curStrPos the current position in the curString * @private */ }, { key: 'backspace', value: function backspace(curString, curStrPos) { var _this4 = this; if (this.pause.status === true) { this.setPauseStatus(curString, curStrPos, true); return; } if (this.fadeOut) return this.initFadeOut(); this.toggleBlinking(false); var humanize = this.humanizer(this.backSpeed); this.timeout = setTimeout(function () { curStrPos = _htmlParserJs.htmlParser.backSpaceHtmlChars(curString, curStrPos, _this4); // replace text with base text + typed characters var curStringAtPosition = curString.substr(0, curStrPos); _this4.replaceText(curStringAtPosition); // if smartBack is enabled if (_this4.smartBackspace) { // the remaining part of the current string is equal of the same part of the new string var nextString = _this4.strings[_this4.arrayPos + 1]; if (nextString && curStringAtPosition === nextString.substr(0, curStrPos)) { _this4.stopNum = curStrPos; } else { _this4.stopNum = 0; } } // if the number (id of character in current string) is // less than the stop number, keep going if (curStrPos > _this4.stopNum) { // subtract characters one by one curStrPos--; // loop the function _this4.backspace(curString, curStrPos); } else if (curStrPos <= _this4.stopNum) { // if the stop number has been reached, increase // array position to next string _this4.arrayPos++; // When looping, begin at the beginning after backspace complete if (_this4.arrayPos === _this4.strings.length) { _this4.arrayPos = 0; _this4.options.onLastStringBackspaced(); _this4.shuffleStringsIfNeeded(); _this4.begin(); } else { _this4.typewrite(_this4.strings[_this4.sequence[_this4.arrayPos]], curStrPos); } } // humanized value for typing }, humanize); } /** * Full animation is complete * @private */ }, { key: 'complete', value: function complete() { this.options.onComplete(this); if (this.loop) { this.curLoop++; } else { this.typingComplete = true; } } /** * Has the typing been stopped * @param {string} curString the current string in the strings array * @param {number} curStrPos the current position in the curString * @param {boolean} isTyping * @private */ }, { key: 'setPauseStatus', value: function setPauseStatus(curString, curStrPos, isTyping) { this.pause.typewrite = isTyping; this.pause.curString = curString; this.pause.curStrPos = curStrPos; } /** * Toggle the blinking cursor * @param {boolean} isBlinking * @private */ }, { key: 'toggleBlinking', value: function toggleBlinking(isBlinking) { if (!this.cursor) return; // if in paused state, don't toggle blinking a 2nd time if (this.pause.status) return; if (this.cursorBlinking === isBlinking) return; this.cursorBlinking = isBlinking; if (isBlinking) { this.cursor.classList.add('typed-cursor--blink'); } else { this.cursor.classList.remove('typed-cursor--blink'); } } /** * Speed in MS to type * @param {number} speed * @private */ }, { key: 'humanizer', value: function humanizer(speed) { return Math.round(Math.random() * speed / 2) + speed; } /** * Shuffle the sequence of the strings array * @private */ }, { key: 'shuffleStringsIfNeeded', value: function shuffleStringsIfNeeded() { if (!this.shuffle) return; this.sequence = this.sequence.sort(function () { return Math.random() - 0.5; }); } /** * Adds a CSS class to fade out current string * @private */ }, { key: 'initFadeOut', value: function initFadeOut() { var _this5 = this; this.el.className += ' ' + this.fadeOutClass; if (this.cursor) this.cursor.className += ' ' + this.fadeOutClass; return setTimeout(function () { _this5.arrayPos++; _this5.replaceText(''); // Resets current string if end of loop reached if (_this5.strings.length > _this5.arrayPos) { _this5.typewrite(_this5.strings[_this5.sequence[_this5.arrayPos]], 0); } else { _this5.typewrite(_this5.strings[0], 0); _this5.arrayPos = 0; } }, this.fadeOutDelay); } /** * Replaces current text in the HTML element * depending on element type * @param {string} str * @private */ }, { key: 'replaceText', value: function replaceText(str) { if (this.attr) { this.el.setAttribute(this.attr, str); } else { if (this.isInput) { this.el.value = str; } else if (this.contentType === 'html') { this.el.innerHTML = str; } else { this.el.textContent = str; } } } /** * If using input elements, bind focus in order to * start and stop the animation * @private */ }, { key: 'bindFocusEvents', value: function bindFocusEvents() { var _this6 = this; if (!this.isInput) return; this.el.addEventListener('focus', function (e) { _this6.stop(); }); this.el.addEventListener('blur', function (e) { if (_this6.el.value && _this6.el.value.length !== 0) { return; } _this6.start(); }); } /** * On init, insert the cursor element * @private */ }, { key: 'insertCursor', value: function insertCursor() { if (!this.showCursor) return; if (this.cursor) return; this.cursor = document.createElement('span'); this.cursor.className = 'typed-cursor'; this.cursor.innerHTML = this.cursorChar; this.el.parentNode && this.el.parentNode.insertBefore(this.cursor, this.el.nextSibling); } }]); return Typed; })();
Welcome to Typed.js! @param {string} elementId HTML element ID _OR_ HTML element @param {object} options options object @returns {object} a new Typed object
(anonymous) ( )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/typed.js/typed.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/typed.js/typed.js
MIT
value: function load(self, options, elementId) { // chosen element to manipulate text if (typeof elementId === 'string') { self.el = document.querySelector(elementId); } else { self.el = elementId; } self.options = _extends({}, _defaultsJs2['default'], options); // attribute to type into self.isInput = self.el.tagName.toLowerCase() === 'input'; self.attr = self.options.attr; self.bindInputFocusEvents = self.options.bindInputFocusEvents; // show cursor self.showCursor = self.isInput ? false : self.options.showCursor; // custom cursor self.cursorChar = self.options.cursorChar; // Is the cursor blinking self.cursorBlinking = true; // text content of element self.elContent = self.attr ? self.el.getAttribute(self.attr) : self.el.textContent; // html or plain text self.contentType = self.options.contentType; // typing speed self.typeSpeed = self.options.typeSpeed; // add a delay before typing starts self.startDelay = self.options.startDelay; // backspacing speed self.backSpeed = self.options.backSpeed; // only backspace what doesn't match the previous string self.smartBackspace = self.options.smartBackspace; // amount of time to wait before backspacing self.backDelay = self.options.backDelay; // Fade out instead of backspace self.fadeOut = self.options.fadeOut; self.fadeOutClass = self.options.fadeOutClass; self.fadeOutDelay = self.options.fadeOutDelay; // variable to check whether typing is currently paused self.isPaused = false; // input strings of text self.strings = self.options.strings.map(function (s) { return s.trim(); }); // div containing strings if (typeof self.options.stringsElement === 'string') { self.stringsElement = document.querySelector(self.options.stringsElement); } else { self.stringsElement = self.options.stringsElement; } if (self.stringsElement) { self.strings = []; self.stringsElement.style.display = 'none'; var strings = Array.prototype.slice.apply(self.stringsElement.children); var stringsLength = strings.length; if (stringsLength) { for (var i = 0; i < stringsLength; i += 1) { var stringEl = strings[i]; self.strings.push(stringEl.innerHTML.trim()); } } } // character number position of current string self.strPos = 0; // current array position self.arrayPos = 0; // index of string to stop backspacing on self.stopNum = 0; // Looping logic self.loop = self.options.loop; self.loopCount = self.options.loopCount; self.curLoop = 0; // shuffle the strings self.shuffle = self.options.shuffle; // the order of strings self.sequence = []; self.pause = { status: false, typewrite: true, curString: '', curStrPos: 0 }; // When the typing is complete (when not looped) self.typingComplete = false; // Set the order in which the strings are typed for (var i in self.strings) { self.sequence[i] = i; } // If there is some text in the element self.currentElContent = this.getCurrentElContent(self); self.autoInsertCss = self.options.autoInsertCss; this.appendAnimationCss(self); }
Load up defaults & options on the Typed instance @param {Typed} self instance of Typed @param {object} options options object @param {string} elementId HTML element ID _OR_ instance of HTML element @private
load ( self , options , elementId )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/typed.js/typed.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/typed.js/typed.js
MIT
onBegin: function onBegin(self) {},
Before it begins typing @param {Typed} self
onBegin ( self )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/typed.js/typed.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/typed.js/typed.js
MIT
onComplete: function onComplete(self) {},
All typing is complete @param {Typed} self
onComplete ( self )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/typed.js/typed.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/typed.js/typed.js
MIT
preStringTyped: function preStringTyped(arrayPos, self) {},
Before each string is typed @param {number} arrayPos @param {Typed} self
preStringTyped ( arrayPos , self )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/typed.js/typed.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/typed.js/typed.js
MIT
onStringTyped: function onStringTyped(arrayPos, self) {},
After each string is typed @param {number} arrayPos @param {Typed} self
onStringTyped ( arrayPos , self )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/typed.js/typed.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/typed.js/typed.js
MIT
onLastStringBackspaced: function onLastStringBackspaced(self) {},
During looping, after last string is typed @param {Typed} self
onLastStringBackspaced ( self )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/typed.js/typed.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/typed.js/typed.js
MIT
onTypingPaused: function onTypingPaused(arrayPos, self) {},
Typing has been stopped @param {number} arrayPos @param {Typed} self
onTypingPaused ( arrayPos , self )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/typed.js/typed.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/typed.js/typed.js
MIT
onTypingResumed: function onTypingResumed(arrayPos, self) {},
Typing has been started after being stopped @param {number} arrayPos @param {Typed} self
onTypingResumed ( arrayPos , self )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/typed.js/typed.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/typed.js/typed.js
MIT
onStop: function onStop(arrayPos, self) {},
After stop @param {number} arrayPos @param {Typed} self
onStop ( arrayPos , self )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/typed.js/typed.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/typed.js/typed.js
MIT
onStart: function onStart(arrayPos, self) {},
After start @param {number} arrayPos @param {Typed} self
onStart ( arrayPos , self )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/typed.js/typed.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/typed.js/typed.js
MIT
value: function typeHtmlChars(curString, curStrPos, self) { if (self.contentType !== 'html') return curStrPos; var curChar = curString.substr(curStrPos).charAt(0); if (curChar === '<' || curChar === '&') { var endTag = ''; if (curChar === '<') { endTag = '>'; } else { endTag = ';'; } while (curString.substr(curStrPos + 1).charAt(0) !== endTag) { curStrPos++; if (curStrPos + 1 > curString.length) { break; } } curStrPos++; } return curStrPos; }
Type HTML tags & HTML Characters @param {string} curString Current string @param {number} curStrPos Position in current string @param {Typed} self instance of Typed @returns {number} a new string position @private
typeHtmlChars ( curString , curStrPos , self )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/typed.js/typed.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/typed.js/typed.js
MIT
trigger: function(typ, opt_evt) { if (!typ) { throw "INVALID EVENT TYPE " + typ; } var obj = this.handlers || (this.handlers = {}), arr = [].concat(obj[typ] || []), //Use copy evt = opt_evt || {}, len, i, fnc; evt.type || (evt.type = typ); // handle specified event type for (i = 0, len = arr.length; i < len; ++i) { (fnc = arr[i][0]) && fnc.call(arr[i][1] || this, this, evt); } // handle wildcard "*" event arr = obj["*"] || []; for (i = 0, len = arr.length; i < len; ++i) { (fnc = arr[i][0]) && fnc.call(arr[i][1] || this, this, evt); } },
@param {string} typ @param {?Object=} opt_evt @return {void}
trigger ( typ , opt_evt )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/rubiks_cube.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/rubiks_cube.js
MIT
on: function(typ, fnc, context) { if (!typ) { throw "addEventListener:INVALID EVENT TYPE " + typ + " " + fnc; } var obj = this.handlers || (this.handlers = {}); (obj[typ] || (obj[typ] = [])).push([fnc, context]); },
@param {string} typ @param {function(evt:Object):void} fnc @param {Object} [context] if would like to be called context is set this param. @return {void}
on ( typ , fnc , context )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/rubiks_cube.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/rubiks_cube.js
MIT
off: function(typ, fnc) { if (!typ) { throw "removeEventListener:INVALID EVENT TYPE " + typ + " " + fn; } var obj = this.handlers || (this.handlers = {}), arr = obj[typ] || [], i = arr.length; while (i) { arr[--i][0] === fnc && arr.splice(i, 1); } },
@param {string} typ @param {function(evt:object):void} fnc
off ( typ , fnc )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/rubiks_cube.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/rubiks_cube.js
MIT
add: function(object) { if (this === object) { return null; } if (object.parent != null) { object.parent.remove(object); } this.children.push(object); object.parent = this; this.el.appendChild(object.el); },
Add object. @param {Object3D} object
add ( object )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/rubiks_cube.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/rubiks_cube.js
MIT
remove: function(object) { var index, ret; if (this === object) { return null; } index = this.children.indexOf(object); if (index === -1) { return null; } ret = this.children.splice(index, 1); return ret; },
Remove object. @param {Object3D} object @return {Object3D}
remove ( object )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/rubiks_cube.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/rubiks_cube.js
MIT
getAt: function(index) { var type = this.history[index]; return this._decodeHistory(type); },
Get history data using index. @param {number} index history index number. @return {Object} a history data.
getAt ( index )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/rubiks_cube.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/rubiks_cube.js
MIT
add: function(data) { var history = this._encodeHistory(data); this.history.push(history); },
Add a new history. @param {Object} data a history data.
add ( data )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/rubiks_cube.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/rubiks_cube.js
MIT
length: function() { return this.history.length; },
Return history length. @return {number} History length.
length ( )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/rubiks_cube.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/rubiks_cube.js
MIT
_encodeHistory: function(data) { var dir = (data.direction > 0) ? 'left' : 'right'; return history_type_map[data.type][dir]; }
Encode a history from an object. @param {Object} data an object as history that contains `type` and `direction`. @return {string} a charactor as history type.
_encodeHistory ( data )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/rubiks_cube.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/rubiks_cube.js
MIT
_decodeHistory: function(data) { for (var key in history_type_map) { for (var type in history_type_map[key]) { if (history_type_map[key][type] === data) { return { type: key, direction: (type === 'left') ? 1 : -1 }; } } } }, /** * Encode a history from an object. * @param {Object} data an object as history that contains `type` and `direction`. * @return {string} a charactor as history type. */ _encodeHistory: function(data) { var dir = (data.direction > 0) ? 'left' : 'right'; return history_type_map[data.type][dir]; } }); (win.CSS3D || (win.CSS3D = {})).History = History; }(window, window.document, window.CSS3D, window.Class));;
Decode history from a charactor. @param {string} data a charactor. @return {Object} an object contains `type` and `direction`.
_decodeHistory ( data )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/rubiks_cube.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/rubiks_cube.js
MIT
init: function(size, n, index) { this.pseudoMatrixWorld = Matrix4.createMatrix(); this._super(); size = size || 50; var _2n = n * 2; var _n2 = n * n; var _2n2 = (n * n) * 2; var opt = {}; var noOpt = { color: 'black' }; //var top = new CSS3D.Face(size, size, 'blue', 'http://placekitten.com/' + size + '/' + size); //For TOP. if (index % _n2 < n) { opt = { color: 'white', useController: true }; } else { opt = noOpt; } var top = new CSS3D.Face(size, size, opt); top.rotateX(90); top.translate([0, -size / 2, 0]); this.add(top); //For BOTTOM. if (index % _n2 >= _2n) { opt = { color: 'blue', useController: true }; } else { opt = noOpt; } var bottom = new CSS3D.Face(size, size, opt); bottom.rotateX(-90); bottom.translate([0, size / 2, 0]); this.add(bottom); //For FRONT. if (_2n2 <= index) { opt = { color: 'orange', useController: true }; } else { opt = noOpt; } var front = new CSS3D.Face(size, size, opt); front.translate([0, 0, size / 2]); this.add(front); //For BACK. if (_n2 > index) { opt = { color: 'red', useController: true }; } else { opt = noOpt; } var back = new CSS3D.Face(size, size, opt); back.rotateY(180); back.translate([0, 0, -size / 2]); this.add(back); //For LEFT. if (index % n === 0) { opt = { color: 'yellow', useController: true }; } else { opt = noOpt; } var left = new CSS3D.Face(size, size, opt); left.rotateY(-90); left.translate([-size / 2, 0, 0]); this.add(left); //For RIGHT. if (index % n === (n - 1)) { opt = { color: 'green', useController: true }; } else { opt = noOpt; } var right = new CSS3D.Face(size, size, opt); right.rotateY(90); right.translate([size / 2, 0, 0]); this.add(right); this.el.style.width = this.el.style.height = size + 'px'; this.el.style.marginTop = this.el.style.marginLeft = -(size / 2) + 'px'; },
@param {number} size width and height size. @param {number} n RubikCube count. @param {number} index current index number.
init ( size , n , index )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/rubiks_cube.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/rubiks_cube.js
MIT
calc: function(object) { if (!(object instanceof CSS3D.Face)) { var children = object.children; for (var i = 0, l = children.length; i < l; i++) { this.calc(children[i]); } } else { if (!object.useController) { return; } var normal = object.getNormal(); var strength = normal.dot(this.directorn); if (strength < 0) { strength = 0; } object.setOpacity(strength); } }
Calucrate light strength. @param {CSS3D.Object3D} object
calc ( object )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/rubiks_cube.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/rubiks_cube.js
MIT
function getCurAxisDir(axis) { if (Math.abs(axis.x) > 0.00001) { return 'x'; } else if (Math.abs(axis.y) > 0.00001) { return 'y'; } else { return 'z'; } }
Get current axis direction. @param {CSS3D.Vector3} axis @return {string} current axis direction.
getCurAxisDir ( axis )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/rubiks_cube.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/rubiks_cube.js
MIT
setOpacity: function(alpha) { this.faceEl.style.opacity = 0.8 * alpha + 0.3; },
Set opacity. set opacity as alpha. max alpha is 0.8 + 0.3. 0.3 is ambent light as opacity. @param {number} alpha 0.0 ~ 1.0
setOpacity ( alpha )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/rubiks_cube.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/rubiks_cube.js
MIT
updateLight: function(cubes) { var light = this.light; cubes = cubes || this.cubes; for (var i = 0, l = cubes.length; i < l; i++) { light.calc(cubes[i]); } },
Update light strength. if this method will be invoked with an argument, it calculates only `cubes`. @param {Array.<CSS3D.Cube>} cubes.
updateLight ( cubes )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/rubiks_cube.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/rubiks_cube.js
MIT
const createMap = ({ lat, lng }) => { return new google.maps.Map(document.getElementById('map'), { center: { lat, lng }, zoom: 15 }); };
Create google maps Map instance. @param {number} lat @param {number} lng @return {Object}
createMap
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/deviceInfo.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/deviceInfo.js
MIT
const createMarker = ({ map, position }) => { return new google.maps.Marker({ map, position }); };
Create google maps Marker instance. @param {Object} map @param {Object} position @return {Object}
createMarker
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/deviceInfo.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/deviceInfo.js
MIT
const trackLocation = ({ onSuccess, onError = () => { } }) => {
Track the user location. @param {Object} onSuccess @param {Object} [onError] @return {number}
=
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/deviceInfo.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/deviceInfo.js
MIT
const getPositionErrorMessage = code => { switch (code) { case 1: return 'Permission denied.'; case 2: return 'Position unavailable.'; case 3: return 'Timeout reached.'; } }
Get position error message from the given error code. @param {number} code @return {String}
getPositionErrorMessage
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/deviceInfo.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/deviceInfo.js
MIT
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Matter = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(_dereq_,module,exports){
The MIT License (MIT) Copyright (c) Liam Brummitt and contributors. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
(anonymous) ( f )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/physics-matter.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/physics-matter.js
MIT
Constraint.create = function(options) { var constraint = options; // if bodies defined but no points, use body centre if (constraint.bodyA && !constraint.pointA) constraint.pointA = { x: 0, y: 0 }; if (constraint.bodyB && !constraint.pointB) constraint.pointB = { x: 0, y: 0 }; // calculate static length using initial world space points var initialPointA = constraint.bodyA ? Vector.add(constraint.bodyA.position, constraint.pointA) : constraint.pointA, initialPointB = constraint.bodyB ? Vector.add(constraint.bodyB.position, constraint.pointB) : constraint.pointB, length = Vector.magnitude(Vector.sub(initialPointA, initialPointB)); constraint.length = typeof constraint.length !== 'undefined' ? constraint.length : length; // option defaults constraint.id = constraint.id || Common.nextId(); constraint.label = constraint.label || 'Constraint'; constraint.type = 'constraint'; constraint.stiffness = constraint.stiffness || (constraint.length > 0 ? 1 : 0.7); constraint.damping = constraint.damping || 0; constraint.angularStiffness = constraint.angularStiffness || 0; constraint.angleA = constraint.bodyA ? constraint.bodyA.angle : constraint.angleA; constraint.angleB = constraint.bodyB ? constraint.bodyB.angle : constraint.angleB; constraint.plugin = {}; // render var render = { visible: true, lineWidth: 2, strokeStyle: '#ffffff', type: 'line', anchors: true }; if (constraint.length === 0 && constraint.stiffness > 0.1) { render.type = 'pin'; render.anchors = false; } else if (constraint.stiffness < 0.9) { render.type = 'spring'; } constraint.render = Common.extend(render, constraint.render); return constraint; }; /** * Prepares for solving by constraint warming. * @private * @method preSolveAll * @param {body[]} bodies */ Constraint.preSolveAll = function(bodies) { for (var i = 0; i < bodies.length; i += 1) { var body = bodies[i], impulse = body.constraintImpulse; if (body.isStatic || (impulse.x === 0 && impulse.y === 0 && impulse.angle === 0)) { continue; } body.position.x += impulse.x; body.position.y += impulse.y; body.angle += impulse.angle; } }; /** * Solves all constraints in a list of collisions. * @private * @method solveAll * @param {constraint[]} constraints * @param {number} timeScale */ Constraint.solveAll = function(constraints, timeScale) { // Solve fixed constraints first. for (var i = 0; i < constraints.length; i += 1) { var constraint = constraints[i], fixedA = !constraint.bodyA || (constraint.bodyA && constraint.bodyA.isStatic), fixedB = !constraint.bodyB || (constraint.bodyB && constraint.bodyB.isStatic); if (fixedA || fixedB) { Constraint.solve(constraints[i], timeScale); } } // Solve free constraints last. for (i = 0; i < constraints.length; i += 1) { constraint = constraints[i]; fixedA = !constraint.bodyA || (constraint.bodyA && constraint.bodyA.isStatic); fixedB = !constraint.bodyB || (constraint.bodyB && constraint.bodyB.isStatic); if (!fixedA && !fixedB) { Constraint.solve(constraints[i], timeScale); } } }; /** * Solves a distance constraint with Gauss-Siedel method. * @private * @method solve * @param {constraint} constraint * @param {number} timeScale */ Constraint.solve = function(constraint, timeScale) { var bodyA = constraint.bodyA, bodyB = constraint.bodyB, pointA = constraint.pointA, pointB = constraint.pointB; if (!bodyA && !bodyB) return; // update reference angle if (bodyA && !bodyA.isStatic) { Vector.rotate(pointA, bodyA.angle - constraint.angleA, pointA); constraint.angleA = bodyA.angle; } // update reference angle if (bodyB && !bodyB.isStatic) { Vector.rotate(pointB, bodyB.angle - constraint.angleB, pointB); constraint.angleB = bodyB.angle; } var pointAWorld = pointA, pointBWorld = pointB; if (bodyA) pointAWorld = Vector.add(bodyA.position, pointA); if (bodyB) pointBWorld = Vector.add(bodyB.position, pointB); if (!pointAWorld || !pointBWorld) return; var delta = Vector.sub(pointAWorld, pointBWorld), currentLength = Vector.magnitude(delta); // prevent singularity if (currentLength < Constraint._minLength) { currentLength = Constraint._minLength; } // solve distance constraint with Gauss-Siedel method var difference = (currentLength - constraint.length) / currentLength, stiffness = constraint.stiffness < 1 ? constraint.stiffness * timeScale : constraint.stiffness, force = Vector.mult(delta, difference * stiffness), massTotal = (bodyA ? bodyA.inverseMass : 0) + (bodyB ? bodyB.inverseMass : 0), inertiaTotal = (bodyA ? bodyA.inverseInertia : 0) + (bodyB ? bodyB.inverseInertia : 0), resistanceTotal = massTotal + inertiaTotal, torque, share, normal, normalVelocity, relativeVelocity; if (constraint.damping) { var zero = Vector.create(); normal = Vector.div(delta, currentLength); relativeVelocity = Vector.sub( bodyB && Vector.sub(bodyB.position, bodyB.positionPrev) || zero, bodyA && Vector.sub(bodyA.position, bodyA.positionPrev) || zero ); normalVelocity = Vector.dot(normal, relativeVelocity); } if (bodyA && !bodyA.isStatic) { share = bodyA.inverseMass / massTotal; // keep track of applied impulses for post solving bodyA.constraintImpulse.x -= force.x * share; bodyA.constraintImpulse.y -= force.y * share; // apply forces bodyA.position.x -= force.x * share; bodyA.position.y -= force.y * share; // apply damping if (constraint.damping) { bodyA.positionPrev.x -= constraint.damping * normal.x * normalVelocity * share; bodyA.positionPrev.y -= constraint.damping * normal.y * normalVelocity * share; } // apply torque torque = (Vector.cross(pointA, force) / resistanceTotal) * Constraint._torqueDampen * bodyA.inverseInertia * (1 - constraint.angularStiffness); bodyA.constraintImpulse.angle -= torque; bodyA.angle -= torque; } if (bodyB && !bodyB.isStatic) { share = bodyB.inverseMass / massTotal; // keep track of applied impulses for post solving bodyB.constraintImpulse.x += force.x * share; bodyB.constraintImpulse.y += force.y * share; // apply forces bodyB.position.x += force.x * share; bodyB.position.y += force.y * share; // apply damping if (constraint.damping) { bodyB.positionPrev.x += constraint.damping * normal.x * normalVelocity * share; bodyB.positionPrev.y += constraint.damping * normal.y * normalVelocity * share; } // apply torque torque = (Vector.cross(pointB, force) / resistanceTotal) * Constraint._torqueDampen * bodyB.inverseInertia * (1 - constraint.angularStiffness); bodyB.constraintImpulse.angle += torque; bodyB.angle += torque; } }; /** * Performs body updates required after solving constraints. * @private * @method postSolveAll * @param {body[]} bodies */ Constraint.postSolveAll = function(bodies) { for (var i = 0; i < bodies.length; i++) { var body = bodies[i], impulse = body.constraintImpulse; if (body.isStatic || (impulse.x === 0 && impulse.y === 0 && impulse.angle === 0)) { continue; } Sleeping.set(body, false); // update geometry and reset for (var j = 0; j < body.parts.length; j++) { var part = body.parts[j]; Vertices.translate(part.vertices, impulse); if (j > 0) { part.position.x += impulse.x; part.position.y += impulse.y; } if (impulse.angle !== 0) { Vertices.rotate(part.vertices, impulse.angle, body.position); Axes.rotate(part.axes, impulse.angle); if (j > 0) { Vector.rotateAbout(part.position, impulse.angle, body.position, part.position); } } Bounds.update(part.bounds, part.vertices, body.velocity); } // dampen the cached impulse for warming next step impulse.angle *= Constraint._warming; impulse.x *= Constraint._warming; impulse.y *= Constraint._warming; } }; /* * * Properties Documentation * */ /** * An integer `Number` uniquely identifying number generated in `Composite.create` by `Common.nextId`. * * @property id * @type number */ /** * A `String` denoting the type of object. * * @property type * @type string * @default "constraint" * @readOnly */ /** * An arbitrary `String` name to help the user identify and manage bodies. * * @property label * @type string * @default "Constraint" */ /** * An `Object` that defines the rendering properties to be consumed by the module `Matter.Render`. * * @property render * @type object */ /** * A flag that indicates if the constraint should be rendered. * * @property render.visible * @type boolean * @default true */ /** * A `Number` that defines the line width to use when rendering the constraint outline. * A value of `0` means no outline will be rendered. * * @property render.lineWidth * @type number * @default 2 */ /** * A `String` that defines the stroke style to use when rendering the constraint outline. * It is the same as when using a canvas, so it accepts CSS style property values. * * @property render.strokeStyle * @type string * @default a random colour */ /** * A `String` that defines the constraint rendering type. * The possible values are 'line', 'pin', 'spring'. * An appropriate render type will be automatically chosen unless one is given in options. * * @property render.type * @type string * @default 'line' */ /** * A `Boolean` that defines if the constraint's anchor points should be rendered. * * @property render.anchors * @type boolean * @default true */ /** * The first possible `Body` that this constraint is attached to. * * @property bodyA * @type body * @default null */ /** * The second possible `Body` that this constraint is attached to. * * @property bodyB * @type body * @default null */ /** * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyA` if defined, otherwise a world-space position. * * @property pointA * @type vector * @default { x: 0, y: 0 } */ /** * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyB` if defined, otherwise a world-space position. * * @property pointB * @type vector * @default { x: 0, y: 0 } */ /** * A `Number` that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`. * A value of `1` means the constraint should be very stiff. * A value of `0.2` means the constraint acts like a soft spring. * * @property stiffness * @type number * @default 1 */ /** * A `Number` that specifies the damping of the constraint, * i.e. the amount of resistance applied to each body based on their velocities to limit the amount of oscillation. * Damping will only be apparent when the constraint also has a very low `stiffness`. * A value of `0.1` means the constraint will apply heavy damping, resulting in little to no oscillation. * A value of `0` means the constraint will apply no damping. * * @property damping * @type number * @default 0 */ /** * A `Number` that specifies the target resting length of the constraint. * It is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`. * * @property length * @type number */ /** * An object reserved for storing plugin-specific properties. * * @property plugin * @type {} */ })(); },{"../core/Common":14,"../core/Sleeping":22,"../geometry/Axes":25,"../geometry/Bounds":26,"../geometry/Vector":28,"../geometry/Vertices":29}],13:[function(_dereq_,module,exports){
Creates a new constraint. All properties have default values, and many are pre-calculated automatically based on other properties. To simulate a revolute constraint (or pin joint) set `length: 0` and a high `stiffness` value (e.g. `0.7` or above). If the constraint is unstable, try lowering the `stiffness` value and / or increasing `engine.constraintIterations`. For compound bodies, constraints must be applied to the parent body (not one of its parts). See the properties section below for detailed information on what you can pass via the `options` object. @method create @param {} options @return {constraint} constraint
Constraint.create ( options )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/physics-matter.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/physics-matter.js
MIT
Common._requireGlobal = function(globalName, moduleName) { var obj = (typeof window !== 'undefined' ? window[globalName] : typeof global !== 'undefined' ? global[globalName] : null); return obj || _dereq_(moduleName); }; })();
Used to require external libraries outside of the bundle. It first looks for the `globalName` on the environment's global namespace. If the global is not found, it will fall back to using the standard `require` using the `moduleName`. @private @method _requireGlobal @param {string} globalName The global module name @param {string} moduleName The fallback CommonJS module name @return {} The loaded module
Common._requireGlobal ( globalName , moduleName )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/physics-matter.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/physics-matter.js
MIT
function fallDown(apple) { if (!(IsPlaying && apple instanceof HTMLElement)) { return; } //store the current top position for future refrence. apple.setAttribute('data-top', apple.style.top); //change the top position, this is animated using transition property in CSS apple.style.top = "380px"; //increase score score = score + 5; //show the score by calling this function renderScore(); //hide the apple after it reaches the ground by calling this function hideFallenApple(apple); }
Makes the provided element fall down by changing the top property. @param {HTMLElement} apple
fallDown ( apple )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/AppleGameController.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/AppleGameController.js
MIT
function hideFallenApple(apple) { //we need to wait until the apple has fallen down //so we will use this setTimeout function to wait and the hide the apple setTimeout(function () { apple.style.display = 'none'; //call the function that will move the apple to top //and display it again restoreFallenApple(apple); }, 501); }
Hides the provided element by changing the display property. @param {HTMLElement} apple
hideFallenApple ( apple )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/AppleGameController.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/AppleGameController.js
MIT
function restoreFallenApple(apple) { //as in hideFallenApple we need to wait and the make the html element visible //restore the top value apple.style.top = apple.getAttribute('data-top'); setTimeout(function () { apple.style.display = 'inline-block'; }, 501); }
Shows the provided element by changing the display property and restores top position. @param {HTMLElement} apple
restoreFallenApple ( apple )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/AppleGameController.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/AppleGameController.js
MIT
function renderScore() { scoreBoard.innerText = score; if (score > highScore) { highScore = score; document.getElementById('high').innerText = highScore; } }
Shows the score in the HTMLElement and checks for High Score.
renderScore ( )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/AppleGameController.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/AppleGameController.js
MIT
function startGame() { //disable the button to make it unclickable btnStart.disabled = "disabled"; IsPlaying = true; renderScore(); //start countDown function and call it every second //1000 is in millisecond = 1 second //timer variable stores refrence to the current setInterval //which will be used to clearInterval later. timer = setInterval(countDown, 1000); }
Makes the game playable by setting IsPlaying flag to true.
startGame ( )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/AppleGameController.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/AppleGameController.js
MIT
function countDown() { time = time - 1; timeBoard.innerText = time; if (time == 0) { //clear the interval by using the timer refrence clearInterval(timer); //call end game endGame(); } }
Performs countDown and the displays the time left. if the time has end it will end the game
countDown ( )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/AppleGameController.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/AppleGameController.js
MIT
function endGame() { IsPlaying = false; alert("Your score is " + score); //reset score and time for next game. score = 0; time = 30; //enable the button to make it clickable btnStart.removeAttribute('disabled'); }
Ends the game by setting IsPlaying to false, finally resets the score, time and enables btnStart.
endGame ( )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/AppleGameController.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/AppleGameController.js
MIT
Trie.prototype.get = function (codePoint) { var ix; if (codePoint >= 0) { if (codePoint < 0x0d800 || (codePoint > 0x0dbff && codePoint <= 0x0ffff)) { // Ordinary BMP code point, excluding leading surrogates. // BMP uses a single level lookup. BMP index starts at offset 0 in the Trie2 index. // 16 bit data is stored in the index array itself. ix = this.index[codePoint >> UTRIE2_SHIFT_2]; ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK); return this.data[ix]; } if (codePoint <= 0xffff) { // Lead Surrogate Code Point. A Separate index section is stored for // lead surrogate code units and code points. // The main index has the code unit data. // For this function, we need the code point data. // Note: this expression could be refactored for slightly improved efficiency, but // surrogate code points will be so rare in practice that it's not worth it. ix = this.index[UTRIE2_LSCP_INDEX_2_OFFSET + ((codePoint - 0xd800) >> UTRIE2_SHIFT_2)]; ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK); return this.data[ix]; } if (codePoint < this.highStart) { // Supplemental code point, use two-level lookup. ix = UTRIE2_INDEX_1_OFFSET - UTRIE2_OMITTED_BMP_INDEX_1_LENGTH + (codePoint >> UTRIE2_SHIFT_1); ix = this.index[ix]; ix += (codePoint >> UTRIE2_SHIFT_2) & UTRIE2_INDEX_2_MASK; ix = this.index[ix]; ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK); return this.data[ix]; } if (codePoint <= 0x10ffff) { return this.data[this.highValueIndex]; } } // Fall through. The code point is outside of the legal range of 0..0x10ffff. return this.errorValue; };
Get the value for a code point as stored in the Trie. @param codePoint the code point @return the value
Trie.prototype.get ( codePoint )
javascript
Vishal-raj-1/Awesome-JavaScript-Projects
assets/js/avatarMaker_js/html2canvas.js
https://github.com/Vishal-raj-1/Awesome-JavaScript-Projects/blob/master/assets/js/avatarMaker_js/html2canvas.js
MIT
const applyAPItoObject = (object) => { let alreadySetted = true // attach to itself if not provided for (const method in api) { if (Object.prototype.hasOwnProperty.call(api, method)) { const alias = api[method] // be kind rewind, or better not touch anything already existing if (!object[alias]) { alreadySetted = false object[alias] = i18n[method].bind(object) } } } // set initial locale if not set if (!object.locale) { object.locale = defaultLocale } // escape recursion if (alreadySetted) { return } // attach to response if present (ie. in express) if (object.res) { applyAPItoObject(object.res) } // attach to locals if present (ie. in express) if (object.locals) { applyAPItoObject(object.locals) } }
registers all public API methods to a given response object when not already declared
(
javascript
mashpie/i18n-node
i18n.js
https://github.com/mashpie/i18n-node/blob/master/i18n.js
MIT
const guessLocaleFromFile = (filename) => { const extensionRegex = new RegExp(extension + '$', 'g') const prefixRegex = new RegExp('^' + prefix, 'g') if (!filename) return false if (prefix && !filename.match(prefixRegex)) return false if (extension && !filename.match(extensionRegex)) return false return filename.replace(prefix, '').replace(extensionRegex, '') }
tries to guess locales from a given filename
guessLocaleFromFile
javascript
mashpie/i18n-node
i18n.js
https://github.com/mashpie/i18n-node/blob/master/i18n.js
MIT
const extractQueryLanguage = (queryLanguage) => { if (Array.isArray(queryLanguage)) { return queryLanguage.find((lang) => lang !== '' && lang) } return typeof queryLanguage === 'string' && queryLanguage }
@param queryLanguage - language query parameter, either an array or a string. @return the first non-empty language query parameter found, null otherwise.
extractQueryLanguage
javascript
mashpie/i18n-node
i18n.js
https://github.com/mashpie/i18n-node/blob/master/i18n.js
MIT
const guessLanguage = (request) => { if (typeof request === 'object') { const languageHeader = request.headers ? request.headers[languageHeaderName] : undefined const languages = [] const regions = [] request.languages = [defaultLocale] request.regions = [defaultLocale] request.language = defaultLocale request.region = defaultLocale // a query parameter overwrites all if (queryParameter && request.url) { const urlAsString = typeof request.url === 'string' ? request.url : request.url.toString() /** * @todo WHATWG new URL() requires full URL including hostname - that might change * @see https://github.com/nodejs/node/issues/12682 */ // eslint-disable-next-line node/no-deprecated-api const urlObj = url.parse(urlAsString, true) const languageQueryParameter = urlObj.query[queryParameter] if (languageQueryParameter) { let queryLanguage = extractQueryLanguage(languageQueryParameter) if (queryLanguage) { logDebug('Overriding locale from query: ' + queryLanguage) if (preserveLegacyCase) { queryLanguage = queryLanguage.toLowerCase() } return i18n.setLocale(request, queryLanguage) } } } // a cookie overwrites headers if (cookiename && request.cookies && request.cookies[cookiename]) { request.language = request.cookies[cookiename] return i18n.setLocale(request, request.language) } // 'accept-language' is the most common source if (languageHeader) { const acceptedLanguages = getAcceptedLanguagesFromHeader(languageHeader) let match let fallbackMatch let fallback for (let i = 0; i < acceptedLanguages.length; i++) { const lang = acceptedLanguages[i] const lr = lang.split('-', 2) const parentLang = lr[0] const region = lr[1] // Check if we have a configured fallback set for this language. const fallbackLang = getFallback(lang, fallbacks) if (fallbackLang) { fallback = fallbackLang // Fallbacks for languages should be inserted // where the original, unsupported language existed. const acceptedLanguageIndex = acceptedLanguages.indexOf(lang) const fallbackIndex = acceptedLanguages.indexOf(fallback) if (fallbackIndex > -1) { acceptedLanguages.splice(fallbackIndex, 1) } acceptedLanguages.splice(acceptedLanguageIndex + 1, 0, fallback) } // Check if we have a configured fallback set for the parent language of the locale. const fallbackParentLang = getFallback(parentLang, fallbacks) if (fallbackParentLang) { fallback = fallbackParentLang // Fallbacks for a parent language should be inserted // to the end of the list, so they're only picked // if there is no better match. if (acceptedLanguages.indexOf(fallback) < 0) { acceptedLanguages.push(fallback) } } if (languages.indexOf(parentLang) < 0) { languages.push(parentLang.toLowerCase()) } if (region) { regions.push(region.toLowerCase()) } if (!match && locales[lang]) { match = lang break } if (!fallbackMatch && locales[parentLang]) { fallbackMatch = parentLang } } request.language = match || fallbackMatch || request.language request.region = regions[0] || request.region return i18n.setLocale(request, request.language) } } // last resort: defaultLocale return i18n.setLocale(request, defaultLocale) }
guess language setting based on http headers
guessLanguage
javascript
mashpie/i18n-node
i18n.js
https://github.com/mashpie/i18n-node/blob/master/i18n.js
MIT
const getAcceptedLanguagesFromHeader = (header) => { const languages = header.split(',') const preferences = {} return languages .map((item) => { const preferenceParts = item.trim().split(';q=') if (preferenceParts.length < 2) { preferenceParts[1] = 1.0 } else { const quality = parseFloat(preferenceParts[1]) preferenceParts[1] = quality || 0.0 } preferences[preferenceParts[0]] = preferenceParts[1] return preferenceParts[0] }) .filter((lang) => preferences[lang] > 0) .sort((a, b) => preferences[b] - preferences[a]) }
Get a sorted list of accepted languages from the HTTP Accept-Language header
getAcceptedLanguagesFromHeader
javascript
mashpie/i18n-node
i18n.js
https://github.com/mashpie/i18n-node/blob/master/i18n.js
MIT
const matchInterval = (number, interval) => { interval = parseInterval(interval) if (interval && typeof number === 'number') { if (interval.from.value === number) { return interval.from.included } if (interval.to.value === number) { return interval.to.included } return ( Math.min(interval.from.value, number) === interval.from.value && Math.max(interval.to.value, number) === interval.to.value ) } return false }
test a number to match mathematical interval expressions [0,2] - 0 to 2 (including, matches: 0, 1, 2) ]0,3[ - 0 to 3 (excluding, matches: 1, 2) [1] - 1 (matches: 1) [20,] - all numbers ≥20 (matches: 20, 21, 22, ...) [,20] - all numbers ≤20 (matches: 20, 21, 22, ...)
matchInterval
javascript
mashpie/i18n-node
i18n.js
https://github.com/mashpie/i18n-node/blob/master/i18n.js
MIT
const translate = (locale, singular, plural, skipSyncToAllFiles) => { // add same key to all translations if (!skipSyncToAllFiles && syncFiles) { syncToAllFiles(singular, plural) } if (locale === undefined) { logWarn( 'WARN: No locale found - check the context of the call to __(). Using ' + defaultLocale + ' as current locale' ) locale = defaultLocale } // try to get a fallback if (!locales[locale]) { locale = getFallback(locale, fallbacks) || locale } // attempt to read when defined as valid locale if (!locales[locale]) { read(locale) } // fallback to default when missed if (!locales[locale]) { logWarn( 'WARN: Locale ' + locale + " couldn't be read - check the context of the call to $__. Using " + defaultLocale + ' (default) as current locale' ) locale = defaultLocale read(locale) } // dotnotaction add on, @todo: factor out let defaultSingular = singular let defaultPlural = plural if (objectNotation) { let indexOfColon = singular.indexOf(':') // We compare against 0 instead of -1 because // we don't really expect the string to start with ':'. if (indexOfColon > 0) { defaultSingular = singular.substring(indexOfColon + 1) singular = singular.substring(0, indexOfColon) } if (plural && typeof plural !== 'number') { indexOfColon = plural.indexOf(':') if (indexOfColon > 0) { defaultPlural = plural.substring(indexOfColon + 1) plural = plural.substring(0, indexOfColon) } } } const accessor = localeAccessor(locale, singular) const mutator = localeMutator(locale, singular) // if (plural) { // if (accessor() == null) { // mutator({ // 'one': defaultSingular || singular, // 'other': defaultPlural || plural // }); // write(locale); // } // } // if (accessor() == null) { // mutator(defaultSingular || singular); // write(locale); // } if (plural) { if (accessor() == null) { // when retryInDefaultLocale is true - try to set default value from defaultLocale if (retryInDefaultLocale && locale !== defaultLocale) { logDebug( 'Missing ' + singular + ' in ' + locale + ' retrying in ' + defaultLocale ) mutator(translate(defaultLocale, singular, plural, true)) } else { mutator({ one: defaultSingular || singular, other: defaultPlural || plural }) } write(locale) } } if (accessor() == null) { // when retryInDefaultLocale is true - try to set default value from defaultLocale if (retryInDefaultLocale && locale !== defaultLocale) { logDebug( 'Missing ' + singular + ' in ' + locale + ' retrying in ' + defaultLocale ) mutator(translate(defaultLocale, singular, plural, true)) } else { mutator(defaultSingular || singular) } write(locale) } return accessor() }
read locale file, translate a msg and write to fs if new
translate
javascript
mashpie/i18n-node
i18n.js
https://github.com/mashpie/i18n-node/blob/master/i18n.js
MIT
const syncToAllFiles = (singular, plural) => { // iterate over locales and translate again // this will implicitly write/sync missing keys // to the rest of locales for (const l in locales) { translate(l, singular, plural, true) } }
initialize the same key in all locales when not already existing, checked via translate
syncToAllFiles
javascript
mashpie/i18n-node
i18n.js
https://github.com/mashpie/i18n-node/blob/master/i18n.js
MIT
const write = (locale) => { let stats, target, tmp // don't write new locale information to disk if updateFiles isn't true if (!updateFiles) { return } // creating directory if necessary try { stats = fs.lstatSync(directory) } catch (e) { logDebug('creating locales dir in: ' + directory) try { fs.mkdirSync(directory, directoryPermissions) } catch (e) { // in case of parallel tasks utilizing in same dir if (e.code !== 'EEXIST') throw e } } // first time init has an empty file if (!locales[locale]) { locales[locale] = {} } // writing to tmp and rename on success try { target = getStorageFilePath(locale) tmp = target + '.tmp' fs.writeFileSync( tmp, parser.stringify(locales[locale], null, indent), 'utf8' ) stats = fs.statSync(tmp) if (stats.isFile()) { fs.renameSync(tmp, target) } else { logError( 'unable to write locales to file (either ' + tmp + ' or ' + target + ' are not writeable?): ' ) } } catch (e) { logError( 'unexpected error writing files (either ' + tmp + ' or ' + target + ' are not writeable?): ', e ) } }
try writing a file in a created directory
write
javascript
mashpie/i18n-node
i18n.js
https://github.com/mashpie/i18n-node/blob/master/i18n.js
MIT
describe('autoreload configuration', () => { const testScope = {} const directory = path.join(__dirname, '..', 'testlocalesauto') fs.mkdirSync(directory) fs.writeFileSync(directory + '/de.json', '{}') fs.writeFileSync(directory + '/en.json', '{}') const i18n = new I18n({ directory: directory, register: testScope, autoReload: true }) it('will start with empty catalogs', (done) => { should.deepEqual(i18n.getCatalog(), { de: {}, en: {} }) setTimeout(done, timeout) }) it('reloads when a catalog is altered', (done) => { fs.writeFileSync(directory + '/de.json', '{"Hello":"Hallo"}') setTimeout(done, timeout) }) it('has added new string to catalog and translates correctly', (done) => { i18n.setLocale(testScope, 'de') should.equal('Hallo', testScope.__('Hello')) should.deepEqual(i18n.getCatalog(), { de: { Hello: 'Hallo' }, en: {} }) done() }) it('will add new string to catalog and files from __()', (done) => { should.equal('Hallo', testScope.__('Hello')) should.deepEqual(i18n.getCatalog(), { de: { Hello: 'Hallo' }, en: {} }) done() }) it('will remove testlocalesauto after tests', (done) => { fs.unlinkSync(directory + '/de.json') fs.unlinkSync(directory + '/en.json') fs.rmdirSync(directory) done() }) })
@todo autoreload... by fs.watch never stops test may timeout when run without --exit. Still this works: $ mocha --exit test/i18n.configureAutoreload.js ...needs a proper shutdown as of https://github.com/mashpie/i18n-node/issues/359
(anonymous)
javascript
mashpie/i18n-node
test/i18n.configureAutoreload.js
https://github.com/mashpie/i18n-node/blob/master/test/i18n.configureAutoreload.js
MIT
(function(a){ var isMobile = /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4));
Detect mobile devices (optional) Based on http://detectmobilebrowsers.com/ @value: navigator.isMobile @return: true | false Detect if this plugin is enabled: ('isMobile' in navigator)
(anonymous) ( a )
javascript
yuche/vue-strap
dist/isMobileBrowser.js
https://github.com/yuche/vue-strap/blob/master/dist/isMobileBrowser.js
MIT
insertBefore: function (inside, before, insert, root) { root = root || _.languages; var grammar = root[inside]; if (arguments.length == 2) { insert = arguments[1]; for (var newToken in insert) { if (insert.hasOwnProperty(newToken)) { grammar[newToken] = insert[newToken]; } } return grammar; } var ret = {}; for (var token in grammar) { if (grammar.hasOwnProperty(token)) { if (token == before) { for (var newToken in insert) { if (insert.hasOwnProperty(newToken)) { ret[newToken] = insert[newToken]; } } } ret[token] = grammar[token]; } } // Update references in other language definitions _.languages.DFS(_.languages, function(key, value) { if (value === root[inside] && key != inside) { this[key] = ret; } }); return root[inside] = ret; },
Insert a token before another token in a language literal As this needs to recreate the object (we cannot actually insert before keys in object literals), we cannot just provide an object, we need anobject and a key. @param inside The key (or language id) of the parent @param before The key to insert before. If not provided, the function appends instead. @param insert Object with the key/value pairs to insert @param root The object that contains `inside`. If equal to Prism.languages, it can be omitted.
insertBefore ( inside , before , insert , root )
javascript
yuche/vue-strap
build/build-docs.js
https://github.com/yuche/vue-strap/blob/master/build/build-docs.js
MIT
const RowsComponent = Wrapped((args, selection) => selection .append('div') .attr('class', 'ds--rows') )(ContainerComponent({
Useful for grouping elements in a vertical layout. Similar to RootComponent, but doesn't alter the `<title>` tag. @module components/rows @param args Component arguments @param args.tagName HTML tag name (i.e. div, p, h1, h2, etc.) @returns {function} @example <caption>YAML format</caption> rows: ... @example <caption>JSON format</caption> { "component": "rows", "data": [...] } @example <caption>JavaScript format</caption> import RowsComponent from 'components/rows' RowsComponent({'tagName': 'p'})(d3.selection())(...)
(anonymous)
javascript
kantord/just-dashboard
src/components/rows/Rows.js
https://github.com/kantord/just-dashboard/blob/master/src/components/rows/Rows.js
MIT
const parse = (component_loader) => (input, file_loader) => { if (!(typeof input === 'object')) throw new Error('An object is required') validators.required('component')(input) validators.regexp('component', /^[A-z]\w*$/)(input) const component = component_loader(input.component) const args = Object.assign({}, input.args) if (input.component === 'root') { args.state_handler = create_state_handler() args.file_loader = file_loader } const bind = component(args) return (selection) => { const update = bind(selection) update(input.data) return update } }
Creates a function that parses a JSON component and compiles it into a Javascript component * @param {Function} component_loader - A function that can load components
parse
javascript
kantord/just-dashboard
src/parser/parser.js
https://github.com/kantord/just-dashboard/blob/master/src/parser/parser.js
MIT
exports.isTag = function(node, tagName) { return node.type === TYPES.ELEMENT && getTagName(node) === tagName; };
Test if this is a custom JSX element with the given name. @param {object} node - Current node to test @param {string} tagName - Name of element @returns {boolean} whether the searched for element was found
exports.isTag ( node , tagName )
javascript
AlexGilleran/jsx-control-statements
src/util/ast.js
https://github.com/AlexGilleran/jsx-control-statements/blob/master/src/util/ast.js
MIT
exports.isExpressionContainer = function(attribute) { return attribute && attribute.value.type === TYPES.EXPRESSION_CONTAINER; };
Tests whether this is an JSXExpressionContainer and returns it if true. @param {object} attribute - The attribute the value of which is tested @returns {boolean}
exports.isExpressionContainer ( attribute )
javascript
AlexGilleran/jsx-control-statements
src/util/ast.js
https://github.com/AlexGilleran/jsx-control-statements/blob/master/src/util/ast.js
MIT
exports.getExpression = function(attribute) { return attribute.value.expression; };
Get expression from given attribute. @param {JSXAttribute} attribute @returns {Expression}
exports.getExpression ( attribute )
javascript
AlexGilleran/jsx-control-statements
src/util/ast.js
https://github.com/AlexGilleran/jsx-control-statements/blob/master/src/util/ast.js
MIT
exports.isStringLiteral = function(attribute) { return attribute && attribute.value.type === TYPES.STRING_LITERAL; };
Tests whether this is an StringLiteral and returns it if true. @param {object} attribute - The attribute the value of which is tested @returns {boolean}
exports.isStringLiteral ( attribute )
javascript
AlexGilleran/jsx-control-statements
src/util/ast.js
https://github.com/AlexGilleran/jsx-control-statements/blob/master/src/util/ast.js
MIT
exports.getAttributeMap = function(node) { return node.openingElement.attributes.reduce(function(result, attr) { result[attr.name.name] = attr; return result; }, {}); };
Get all attributes from given element. @param {JSXElement} node - Current node from which attributes are gathered @returns {object} Map of all attributes with their name as key
exports.getAttributeMap ( node )
javascript
AlexGilleran/jsx-control-statements
src/util/ast.js
https://github.com/AlexGilleran/jsx-control-statements/blob/master/src/util/ast.js
MIT
exports.getKey = function(node) { var key = exports.getAttributeMap(node).key; return key ? key.value.value : undefined; };
Get the string value of a node's key attribute if present. @param {JSXElement} node - Node to get attributes from @returns {object} The string value of the key attribute of this node if present, otherwise undefined.
exports.getKey ( node )
javascript
AlexGilleran/jsx-control-statements
src/util/ast.js
https://github.com/AlexGilleran/jsx-control-statements/blob/master/src/util/ast.js
MIT
exports.getChildren = function(babelTypes, node) { return babelTypes.react.buildChildren(node); };
Get all children from given element. Normalizes JSXText and JSXExpressionContainer to expressions. @param {object} babelTypes - Babel lib @param {JSXElement} node - Current node from which children are gathered @returns {array} List of all children
exports.getChildren ( babelTypes , node )
javascript
AlexGilleran/jsx-control-statements
src/util/ast.js
https://github.com/AlexGilleran/jsx-control-statements/blob/master/src/util/ast.js
MIT
var addKeyAttribute = function(babelTypes, node, keyValue) { var keyFound = false; node.openingElement.attributes.forEach(function(attrib) { if (babelTypes.isJSXAttribute(attrib) && attrib.name.name === "key") { keyFound = true; return false; } }); if (!keyFound) { var keyAttrib = babelTypes.jSXAttribute(babelTypes.jSXIdentifier("key"), babelTypes.stringLiteral("" + keyValue)); node.openingElement.attributes.push(keyAttrib); } };
Adds attribute "key" to given node, if not already preesent. @param {object} babelTypes - Babel lib @param {JSXElement} node - Current node to which the new attribute is added @param {string} keyValue - Value of the key
addKeyAttribute ( babelTypes , node , keyValue )
javascript
AlexGilleran/jsx-control-statements
src/util/ast.js
https://github.com/AlexGilleran/jsx-control-statements/blob/master/src/util/ast.js
MIT