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
const isContainClass = (element, className) => { if (!element) throw Error('element could not be empty!'); if (!className) throw Error('className could not be empty!'); if (Array.isArray(className)) return className.some(currify( isContainClass, element, )); const {classList} = element; return classList.contains(className); };
check class of element @param element @param className
isContainClass
javascript
coderaiser/cloudcmd
client/dom/dom-tree.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/dom-tree.js
MIT
module.exports.getByTag = (tag, element = document) => { return element.getElementsByTagName(tag); };
Function search element by tag @param tag - className @param element - element
module.exports.getByTag
javascript
coderaiser/cloudcmd
client/dom/dom-tree.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/dom-tree.js
MIT
module.exports.getById = (id, element = document) => { return element.querySelector(`#${id}`); };
Function search element by id @param Id - id
module.exports.getById
javascript
coderaiser/cloudcmd
client/dom/dom-tree.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/dom-tree.js
MIT
module.exports.getByClass = (className, element = document) => DOM.getByClassAll(className, element)[0];
Function search first element by class name @param className - className @param element - element
module.exports.getByClass
javascript
coderaiser/cloudcmd
client/dom/dom-tree.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/dom-tree.js
MIT
module.exports.getByClassAll = (className, element) => { return (element || document).getElementsByClassName(className); };
Function search element by class name @param pClass - className @param element - element
module.exports.getByClassAll
javascript
coderaiser/cloudcmd
client/dom/dom-tree.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/dom-tree.js
MIT
module.exports.hide = (element) => { element.classList.add('hidden'); return DOM; };
add class=hidden to element @param element
module.exports.hide
javascript
coderaiser/cloudcmd
client/dom/dom-tree.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/dom-tree.js
MIT
function getIdBySrc(src) { const isStr = itype.string(src); if (!isStr) return; if (src.includes(':')) src += '-join'; const num = src.lastIndexOf('/') + 1; const sub = src.substr(src, num); const id = src .replace(sub, '') .replace(/\./g, '-'); return id; }
Function gets id by src @param src Example: http://domain.com/1.js -> 1_js
getIdBySrc ( src )
javascript
coderaiser/cloudcmd
client/dom/load.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/load.js
MIT
function show(position, panel) { const image = Images.loading(); const parent = image.parentElement; const refreshButton = DOM.getRefreshButton(panel); let current; if (position === 'top') { current = refreshButton.parentElement; } else { current = DOM.getCurrentFile(); if (current) current = DOM.getByDataName('js-name', current); else current = refreshButton.parentElement; } if (!parent || parent && parent !== current) current.appendChild(image); DOM.show(image); return image; }
Function shows loading spinner position = {top: true};
show ( position , panel )
javascript
coderaiser/cloudcmd
client/dom/images.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/images.js
MIT
module.exports.setCurrentName = (name, current) => { const Info = DOM.CurrentInfo; const {link} = Info; const {prefix} = CloudCmd; const dir = prefix + FS + Info.dirPath; const encoded = encode(name); link.title = encoded; link.href = dir + encoded; link.innerHTML = encoded; current.setAttribute('data-name', createNameAttribute(name)); CloudCmd.emit('current-file', current); return link; };
set name from current (or param) file @param name @param current
module.exports.setCurrentName
javascript
coderaiser/cloudcmd
client/dom/current-file.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/current-file.js
MIT
module.exports.getCurrentName = (currentFile) => { const current = currentFile || DOM.getCurrentFile(); if (!current) return ''; return parseNameAttribute(current.getAttribute('data-name')); };
get name from current (or param) file @param currentFile
module.exports.getCurrentName
javascript
coderaiser/cloudcmd
client/dom/current-file.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/current-file.js
MIT
const createNameAttribute = (name) => { const encoded = btoa(encodeURI(name)); return `js-file-${encoded}`; };
Generate a `data-name` attribute for the given filename @param name The string name to encode
createNameAttribute
javascript
coderaiser/cloudcmd
client/dom/current-file.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/current-file.js
MIT
const parseNameAttribute = (attribute) => { attribute = attribute.replace('js-file-', ''); return decodeNBSP(decodeURI(atob(attribute))); };
Parse a `data-name` attribute string back into the original filename @param attribute The string we wish to decode
parseNameAttribute
javascript
coderaiser/cloudcmd
client/dom/current-file.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/current-file.js
MIT
module.exports.getCurrentPath = (currentFile) => { const current = currentFile || DOM.getCurrentFile(); const [element] = DOM.getByTag('a', current); const {prefix} = CloudCmd; return parseHrefAttribute(prefix, element.getAttribute('href')); };
get link from current (or param) file @param currentFile - current file by default
module.exports.getCurrentPath
javascript
coderaiser/cloudcmd
client/dom/current-file.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/current-file.js
MIT
module.exports.getCurrentFile = () => { return DOM.getByClass(CURRENT_FILE); };
unified way to get current file @currentFile
module.exports.getCurrentFile
javascript
coderaiser/cloudcmd
client/dom/current-file.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/current-file.js
MIT
function unsetCurrentFile(currentFile) { const is = DOM.isCurrentFile(currentFile); if (!is) return; currentFile.classList.remove(CURRENT_FILE); }
private function thet unset currentfile @currentFile
unsetCurrentFile ( currentFile )
javascript
coderaiser/cloudcmd
client/dom/current-file.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/current-file.js
MIT
module.exports.isCurrentFile = (currentFile) => { if (!currentFile) return false; return DOM.isContainClass(currentFile, CURRENT_FILE); };
current file check @param currentFile
module.exports.isCurrentFile
javascript
coderaiser/cloudcmd
client/dom/current-file.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/current-file.js
MIT
module.exports.setTitle = (name) => { if (!Title) Title = DOM.getByTag('title')[0] || createElement('title', { innerHTML: name, parent: document.head, }); Title.textContent = name; return DOM; };
set title or create title element @param name
module.exports.setTitle
javascript
coderaiser/cloudcmd
client/dom/current-file.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/current-file.js
MIT
module.exports.isCurrentIsDir = (currentFile) => { const current = currentFile || DOM.getCurrentFile(); const path = DOM.getCurrentPath(current); const fileType = DOM.getCurrentType(current); const isZip = /\.zip$/.test(path); const isDir = /^directory(-link)?/.test(fileType); return isDir || isZip; };
check is current file is a directory @param currentFile
module.exports.isCurrentIsDir
javascript
coderaiser/cloudcmd
client/dom/current-file.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/current-file.js
MIT
module.exports.getSelectedFiles = () => { const panel = DOM.getPanel(); const selected = DOM.getByClassAll(SELECTED_FILE, panel); return Array.from(selected); };
unified way to get selected files @currentFile
module.exports.getSelectedFiles
javascript
coderaiser/cloudcmd
client/dom/index.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/index.js
MIT
module.exports.getActiveFiles = () => { const current = DOM.getCurrentFile(); const files = DOM.getSelectedFiles(); const name = DOM.getCurrentName(current); if (!files.length && name !== '..') return [current]; return files; };
get all selected files or current when none selected @currentFile
module.exports.getActiveFiles
javascript
coderaiser/cloudcmd
client/dom/index.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/index.js
MIT
module.exports.getCurrentData = async (currentFile) => { const {Dialog} = DOM; const Info = DOM.CurrentInfo; const current = currentFile || DOM.getCurrentFile(); const path = DOM.getCurrentPath(current); const isDir = DOM.isCurrentIsDir(current); if (Info.name === '..') { Dialog.alert.noFiles(); return [ Error('No Files'), ]; } if (isDir) return await RESTful.read(path); const [hashNew, hash] = await DOM.checkStorageHash(path); if (!hashNew) return [ Error(`Can't get hash of a file`), ]; if (hash === hashNew) return [null, await Storage.get(`${path}-data`)]; const [e, data] = await RESTful.read(path); if (e) return [ e, null, ]; const ONE_MEGABYTE = 1024 ** 2 * 1024; const {length} = data; if (hash && length < ONE_MEGABYTE) await DOM.saveDataToStorage(path, data, hashNew); return [null, data]; };
unified way to get current file content @param currentFile
module.exports.getCurrentData
javascript
coderaiser/cloudcmd
client/dom/index.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/index.js
MIT
module.exports.selectFile = (currentFile) => { const current = currentFile || DOM.getCurrentFile(); current.classList.add(SELECTED_FILE); return Cmd; };
select current file @param currentFile
module.exports.selectFile
javascript
coderaiser/cloudcmd
client/dom/index.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/index.js
MIT
module.exports.isSelected = (selected) => { if (!selected) return false; return DOM.isContainClass(selected, SELECTED_FILE); };
selected file check @param currentFile
module.exports.isSelected
javascript
coderaiser/cloudcmd
client/dom/index.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/index.js
MIT
module.exports.saveDataToStorage = async (name, data, hash) => { const isDir = DOM.isCurrentIsDir(); if (isDir) return; hash = hash || await DOM.loadCurrentHash(); const nameHash = `${name}-hash`; const nameData = `${name}-data`; await Storage.set(nameHash, hash); await Storage.set(nameData, data); return hash; };
save data to storage @param name @param data @param hash @param callback
module.exports.saveDataToStorage
javascript
coderaiser/cloudcmd
client/dom/index.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/index.js
MIT
module.exports.getPanel = (options) => { let files; let panel; let isLeft; let dataName = 'js-'; const current = DOM.getCurrentFile(); if (!current) { panel = DOM.getByDataName('js-left'); } else { files = current.parentElement; panel = files.parentElement; isLeft = panel.getAttribute('data-name') === 'js-left'; } /* if {active : false} getting passive panel */ if (options && !options.active) { dataName += isLeft ? 'right' : 'left'; panel = DOM.getByDataName(dataName); } /* if two panels showed * then always work with passive * panel */ if (window.innerWidth < CloudCmd.MIN_ONE_PANEL_WIDTH) panel = DOM.getByDataName('js-left'); if (!panel) throw Error('can not find Active Panel!'); return panel; };
function getting panel active, or passive @param options = {active: true}
module.exports.getPanel
javascript
coderaiser/cloudcmd
client/dom/index.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/index.js
MIT
module.exports.showPanel = (active) => { const panel = DOM.getPanel({ active, }); if (!panel) return false; DOM.show(panel); return true; };
shows panel right or left (or active)
module.exports.showPanel
javascript
coderaiser/cloudcmd
client/dom/index.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/index.js
MIT
module.exports.hidePanel = (active) => { const panel = DOM.getPanel({ active, }); if (!panel) return false; return DOM.hide(panel); };
hides panel right or left (or active)
module.exports.hidePanel
javascript
coderaiser/cloudcmd
client/dom/index.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/index.js
MIT
module.exports.remove = (child, element) => { const parent = element || document.body; parent.removeChild(child); return DOM; };
remove child of element @param pChild @param element
module.exports.remove
javascript
coderaiser/cloudcmd
client/dom/index.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/index.js
MIT
module.exports.deleteCurrent = (current) => { if (!current) DOM.getCurrentFile(); const parent = current?.parentElement; const name = DOM.getCurrentName(current); if (current && name !== '..') { const next = current.nextSibling; const prev = current.previousSibling; DOM.setCurrentFile(next || prev); parent.removeChild(current); } };
remove current file from file table @param current
module.exports.deleteCurrent
javascript
coderaiser/cloudcmd
client/dom/index.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/index.js
MIT
module.exports.deleteSelected = (selected) => { selected = selected || DOM.getSelectedFiles(); if (!selected) return; selected.map(DOM.deleteCurrent); };
remove selected files from file table @Selected
module.exports.deleteSelected
javascript
coderaiser/cloudcmd
client/dom/index.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/index.js
MIT
module.exports.scrollIntoViewIfNeeded = (element, center = false) => { if (!element || !element.scrollIntoViewIfNeeded) return; element.scrollIntoViewIfNeeded(center); };
unified way to scrollIntoViewIfNeeded (native suporte by webkit only) @param element @param center - to scroll as small as possible param should be false
module.exports.scrollIntoViewIfNeeded
javascript
coderaiser/cloudcmd
client/dom/index.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/index.js
MIT
this.add = (type, element, listener) => { checkType(type); parseArgs(type, element, listener, (element, args) => { const [name, fn, options] = args; element.addEventListener(name, fn, options); EventStore.add(element, name, fn); }); return Events; };
safe add event listener @param type @param element {document by default} @param listener
this.add
javascript
coderaiser/cloudcmd
client/dom/events/index.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/events/index.js
MIT
this.remove = (type, element, listener) => { checkType(type); parseArgs(type, element, listener, (element, args) => { element.removeEventListener(...args); }); return Events; };
safe remove event listener @param type @param listener @param element {document by default}
this.remove
javascript
coderaiser/cloudcmd
client/dom/events/index.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/events/index.js
MIT
this.removeAll = () => { const events = EventStore.get(); for (const [el, name, fn] of events) el.removeEventListener(name, fn); EventStore.clear(); };
remove all added event listeners @param listener
this.removeAll
javascript
coderaiser/cloudcmd
client/dom/events/index.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/events/index.js
MIT
this.addKey = function(...argsArr) { const name = 'keydown'; const args = [ name, ...argsArr, ]; return Events.add(...args); };
safe add event keydown listener @param listener
this.addKey ( ... argsArr )
javascript
coderaiser/cloudcmd
client/dom/events/index.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/events/index.js
MIT
this.rmKey = function(...argsArr) { const name = 'keydown'; const args = [ name, ...argsArr, ]; return Events.remove(...args); };
safe remove event click listener @param listener
this.rmKey ( ... argsArr )
javascript
coderaiser/cloudcmd
client/dom/events/index.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/events/index.js
MIT
this.addClick = function(...argsArr) { const name = 'click'; const args = [ name, ...argsArr, ]; return Events.add(...args); };
safe add event click listener @param listener
this.addClick ( ... argsArr )
javascript
coderaiser/cloudcmd
client/dom/events/index.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/events/index.js
MIT
this.addLoad = function(...argsArr) { const name = 'load'; const args = [ name, ...argsArr, ]; return Events.add(...args); };
safe add load click listener @param listener
this.addLoad ( ... argsArr )
javascript
coderaiser/cloudcmd
client/dom/events/index.js
https://github.com/coderaiser/cloudcmd/blob/master/client/dom/events/index.js
MIT
function getPathLink(url, prefix, template) { if (!url) throw Error('url could not be empty!'); if (!template) throw Error('template could not be empty!'); const names = url .split('/') .slice(1, -1); const allNames = [ '/', ...names, ]; const lines = []; const n = allNames.length; let path = '/'; for (let i = 0; i < n; i++) { const name = allNames[i]; const isLast = i === n - 1; if (i) path += `${name}/`; if (i && isLast) { lines.push(`${name}/`); continue; } const slash = i ? '/' : ''; lines.push(rendy(template, { path, name, slash, prefix, })); } return lines.join(''); }
Функция получает адреса каждого каталога в пути возвращаеться массив каталогов @param url - адрес каталога
getPathLink ( url , prefix , template )
javascript
coderaiser/cloudcmd
common/cloudfunc.js
https://github.com/coderaiser/cloudcmd/blob/master/common/cloudfunc.js
MIT
function MapboxLanguage(options) { options = Object.assign({}, options); if (!(this instanceof MapboxLanguage)) { throw new Error('MapboxLanguage needs to be called with the new keyword'); } this.setLanguage = this.setLanguage.bind(this); this._initialStyleUpdate = this._initialStyleUpdate.bind(this); this._defaultLanguage = options.defaultLanguage; this._isLanguageField = options.languageField || /^name_/; this._getLanguageField = options.getLanguageField || function nameField(language) { return language === 'mul' ? 'name' : `name_${language}`; }; this._languageSource = options.languageSource || null; this._languageTransform = options.languageTransform; this._excludedLayerIds = options.excludedLayerIds || []; this.supportedLanguages = options.supportedLanguages || ['ar', 'de', 'en', 'es', 'fr', 'it', 'ja', 'ko', 'mul', 'pt', 'ru', 'vi', 'zh-Hans', 'zh-Hant']; }
Create a new [Mapbox GL JS plugin](https://www.mapbox.com/blog/build-mapbox-gl-js-plugins/) that modifies the layers of the map style to use the `text-field` that matches the browser language. As of Mapbox GL Language v1.0.0, this plugin no longer supports token values (e.g. `{name}`). v1.0+ expects the `text-field` property of a style to use an [expression](https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions/) of the form `['get', 'name_en']` or `['get', 'name']`; these expressions can be nested. Note that `get` expressions used as inputs to other expressions may not be handled by this plugin. For example: ``` ["match", ["get", "name"], "California", "Golden State", ["coalesce", ["get", "name_en"], ["get", "name"] ] ] ``` Only styles based on [Mapbox v8 styles](https://docs.mapbox.com/help/troubleshooting/streets-v8-migration-guide/) are supported. @constructor @param {object} options - Options to configure the plugin. @param {string[]} [options.supportedLanguages] - List of supported languages @param {Function} [options.languageTransform] - Custom style transformation to apply @param {RegExp} [options.languageField=/^name_/] - RegExp to match if a text-field is a language field @param {Function} [options.getLanguageField] - Given a language choose the field in the vector tiles @param {string} [options.languageSource] - Name of the source that contains the different languages. @param {string} [options.defaultLanguage] - Name of the default language to initialize style after loading. @param {string[]} [options.excludedLayerIds] - Name of the layers that should be excluded from translation.
MapboxLanguage ( options )
javascript
dillonzq/LoveIt
assets/lib/mapbox-gl/mapbox-gl-language.js
https://github.com/dillonzq/LoveIt/blob/master/assets/lib/mapbox-gl/mapbox-gl-language.js
MIT
MapboxLanguage.prototype.setLanguage = function (style, language) { if (this.supportedLanguages.indexOf(language) < 0) throw new Error(`Language ${ language } is not supported`); const streetsSource = this._languageSource || findStreetsSource(style); if (!streetsSource) return style; const field = this._getLanguageField(language); const isLangField = this._isLanguageField; const excludedLayerIds = this._excludedLayerIds; const changedLayers = style.layers.map((layer) => { if (layer.source === streetsSource) return changeLayerTextProperty(isLangField, layer, field, excludedLayerIds); return layer; }); const languageStyle = Object.assign({}, style, { layers: changedLayers }); return this._languageTransform ? this._languageTransform(languageStyle, language) : languageStyle; };
Explicitly change the language for a style. @param {object} style - Mapbox GL style to modify @param {string} language - The language iso code @returns {object} the modified style
MapboxLanguage.prototype.setLanguage ( style , language )
javascript
dillonzq/LoveIt
assets/lib/mapbox-gl/mapbox-gl-language.js
https://github.com/dillonzq/LoveIt/blob/master/assets/lib/mapbox-gl/mapbox-gl-language.js
MIT
function OutBatch() { this.content = []; // buf, flags, buf, flags, ... this.cbs = []; // callbacks this.isClosed = false; // true if the last message does not have SNDMORE in its flags, false otherwise this.next = null; // next batch (for linked list of batches) }
A batch consists of 1 or more message parts with their flags that need to be sent as one unit
OutBatch ( )
javascript
JustinTulloss/zeromq.node
lib/index.js
https://github.com/JustinTulloss/zeromq.node/blob/master/lib/index.js
MIT
Socket.prototype.pause = function() { this._paused = true; }
Set socket to pause mode no data will be emit until resume() is called all send() calls will be queued @api public
Socket.prototype.pause ( )
javascript
JustinTulloss/zeromq.node
lib/index.js
https://github.com/JustinTulloss/zeromq.node/blob/master/lib/index.js
MIT
Socket.prototype.resume = function() { this._paused = false; this._flushReads(); this._flushWrites(); }
Set a socket back to normal work mode @api public
Socket.prototype.resume ( )
javascript
JustinTulloss/zeromq.node
lib/index.js
https://github.com/JustinTulloss/zeromq.node/blob/master/lib/index.js
MIT
Socket.prototype.setsockopt = function(opt, val){ this._zmq.setsockopt(opts[opt] || opt, val); return this; };
Set `opt` to `val`. @param {String|Number} opt @param {Mixed} val @return {Socket} for chaining @api public
Socket.prototype.setsockopt ( opt , val )
javascript
JustinTulloss/zeromq.node
lib/index.js
https://github.com/JustinTulloss/zeromq.node/blob/master/lib/index.js
MIT
Socket.prototype.getsockopt = function(opt){ return this._zmq.getsockopt(opts[opt] || opt); };
Get socket `opt`. @param {String|Number} opt @return {Mixed} @api public
Socket.prototype.getsockopt ( opt )
javascript
JustinTulloss/zeromq.node
lib/index.js
https://github.com/JustinTulloss/zeromq.node/blob/master/lib/index.js
MIT
Object.keys(opts).forEach(function(name){ Socket.prototype.__defineGetter__(name, function() { return this._zmq.getsockopt(opts[name]); }); Socket.prototype.__defineSetter__(name, function(val) { if ('string' == typeof val) val = new Buffer(val, 'utf8'); return this._zmq.setsockopt(opts[name], val); }); });
Socket opt accessors allowing `sock.backlog = val` instead of `sock.setsockopt('backlog', val)`.
(anonymous) ( name )
javascript
JustinTulloss/zeromq.node
lib/index.js
https://github.com/JustinTulloss/zeromq.node/blob/master/lib/index.js
MIT
Socket.prototype.bind = function(addr, cb) { var self = this; this._zmq.bind(addr, function(err) { if (err) { return cb && cb(err); } self._flushReads(); self._flushWrites(); self.emit('bind', addr); cb && cb(); }); return this; };
Async bind. Emits the "bind" event. @param {String} addr @param {Function} cb @return {Socket} for chaining @api public
Socket.prototype.bind ( addr , cb )
javascript
JustinTulloss/zeromq.node
lib/index.js
https://github.com/JustinTulloss/zeromq.node/blob/master/lib/index.js
MIT
Socket.prototype.bindSync = function(addr) { this._zmq.bindSync(addr); return this; };
Sync bind. @param {String} addr @return {Socket} for chaining @api public
Socket.prototype.bindSync ( addr )
javascript
JustinTulloss/zeromq.node
lib/index.js
https://github.com/JustinTulloss/zeromq.node/blob/master/lib/index.js
MIT
Socket.prototype.unbind = function(addr, cb) { if (zmq.ZMQ_CAN_UNBIND) { var self = this; this._zmq.unbind(addr, function(err) { if (err) { return cb && cb(err); } self.emit('unbind', addr); self._flushReads(); self._flushWrites(); cb && cb(); }); } else { cb && cb(); } return this; };
Async unbind. Emits the "unbind" event. @param {String} addr @param {Function} cb @return {Socket} for chaining @api public
Socket.prototype.unbind ( addr , cb )
javascript
JustinTulloss/zeromq.node
lib/index.js
https://github.com/JustinTulloss/zeromq.node/blob/master/lib/index.js
MIT
Socket.prototype.unbindSync = function(addr) { if (zmq.ZMQ_CAN_UNBIND) { this._zmq.unbindSync(addr); } return this; }
Sync unbind. @param {String} addr @return {Socket} for chaining @api public
Socket.prototype.unbindSync ( addr )
javascript
JustinTulloss/zeromq.node
lib/index.js
https://github.com/JustinTulloss/zeromq.node/blob/master/lib/index.js
MIT
Socket.prototype.connect = function(addr) { this._zmq.connect(addr); return this; };
Connect to `addr`. @param {String} addr @return {Socket} for chaining @api public
Socket.prototype.connect ( addr )
javascript
JustinTulloss/zeromq.node
lib/index.js
https://github.com/JustinTulloss/zeromq.node/blob/master/lib/index.js
MIT
Socket.prototype.disconnect = function(addr) { if (zmq.ZMQ_CAN_DISCONNECT) { this._zmq.disconnect(addr); } return this; };
Disconnect from `addr`. @param {String} addr @return {Socket} for chaining @api public
Socket.prototype.disconnect ( addr )
javascript
JustinTulloss/zeromq.node
lib/index.js
https://github.com/JustinTulloss/zeromq.node/blob/master/lib/index.js
MIT
Socket.prototype.monitor = function(interval, numOfEvents) { if (zmq.ZMQ_CAN_MONITOR) { var self = this; self._zmq.onMonitorEvent = function(event_id, event_value, event_endpoint_addr, ex) { self.emit(events[event_id], event_value, event_endpoint_addr, ex); } self._zmq.onMonitorError = function(error) { self.emit('monitor_error', error); } this._zmq.monitor(interval, numOfEvents); } else { throw new Error('Monitoring support disabled check zmq version is > 3.2.1 and recompile this addon'); } return this; };
Enable monitoring of a Socket @param {Number} timer interval in ms > 0 or Undefined for default @param {Number} The maximum number of events to read on each interval, default is 1, use 0 for reading all events @return {Socket} for chaining @api public
Socket.prototype.monitor ( interval , numOfEvents )
javascript
JustinTulloss/zeromq.node
lib/index.js
https://github.com/JustinTulloss/zeromq.node/blob/master/lib/index.js
MIT
Socket.prototype.unmonitor = function() { if (zmq.ZMQ_CAN_MONITOR) { this._zmq.unmonitor(); } return this; };
Disable monitoring of a Socket release idle handler and close the socket @return {Socket} for chaining @api public
Socket.prototype.unmonitor ( )
javascript
JustinTulloss/zeromq.node
lib/index.js
https://github.com/JustinTulloss/zeromq.node/blob/master/lib/index.js
MIT
Socket.prototype.subscribe = function(filter) { this._subscribe = filter; return this; };
Subscribe with the given `filter`. @param {String} filter @return {Socket} for chaining @api public
Socket.prototype.subscribe ( filter )
javascript
JustinTulloss/zeromq.node
lib/index.js
https://github.com/JustinTulloss/zeromq.node/blob/master/lib/index.js
MIT
Socket.prototype.unsubscribe = function(filter) { this._unsubscribe = filter; return this; };
Unsubscribe with the given `filter`. @param {String} filter @return {Socket} for chaining @api public
Socket.prototype.unsubscribe ( filter )
javascript
JustinTulloss/zeromq.node
lib/index.js
https://github.com/JustinTulloss/zeromq.node/blob/master/lib/index.js
MIT
Socket.prototype.send = function(msg, flags, cb) { flags = flags | 0; if (Array.isArray(msg)) { for (var i = 0, len = msg.length; i < len; i++) { var isLast = i === len - 1; var msgFlags = isLast ? flags : flags | zmq.ZMQ_SNDMORE; var callback = isLast ? cb : undefined; this._outgoing.append(msg[i], msgFlags, callback); } } else { this._outgoing.append(msg, flags, cb); } if (this._outgoing.canSend()) { this._zmq.pending = true; this._flushWrites(); } else { this._zmq.pending = false; } return this; };
Send the given `msg`. @param {String|Buffer|Array} msg @param {Number} [flags] @param {Function} [cb] @return {Socket} for chaining @api public
Socket.prototype.send ( msg , flags , cb )
javascript
JustinTulloss/zeromq.node
lib/index.js
https://github.com/JustinTulloss/zeromq.node/blob/master/lib/index.js
MIT
Socket.prototype.close = function() { this._zmq.close(); return this; };
Close the socket. @return {Socket} for chaining @api public
Socket.prototype.close ( )
javascript
JustinTulloss/zeromq.node
lib/index.js
https://github.com/JustinTulloss/zeromq.node/blob/master/lib/index.js
MIT
function proxy (frontend, backend, capture){ switch(frontend.type+'/'+backend.type){ case 'push/pull': case 'pull/push': case 'xpub/xsub': if(capture){ frontend.on('message',function (){ backend.send([].slice.call(arguments)); }); backend.on('message',function (){ frontend.send([].slice.call(arguments)); //forwarding messages over capture socket capture.send([].slice.call(arguments)); }); } else { //no capture socket provided, just forwarding msgs to respective sockets frontend.on('message',function (){ backend.send([].slice.call(arguments)); }); backend.on('message',function (){ frontend.send([].slice.call(arguments)); }); } break; case 'router/dealer': case 'xrep/xreq': if(capture){ //forwarding router/dealer pack signature: id, delimiter, msg frontend.on('message',function (id,delimiter,msg){ backend.send([id,delimiter,msg]); }); backend.on('message',function (id,delimiter,msg){ frontend.send([id,delimiter,msg]); //forwarding message to the capture socket capture.send(msg); }); } else {
JS based on API characteristics of the native zmq_proxy()
proxy ( frontend , backend , capture )
javascript
JustinTulloss/zeromq.node
lib/index.js
https://github.com/JustinTulloss/zeromq.node/blob/master/lib/index.js
MIT
a.on('message', function(msg){ msg.should.be.an.instanceof(Buffer); msg.toString().should.equal('hello'); this.close(); b.close(); clearTimeout(timeout); done(); });
We create 2 dealer sockets. One of them (`a`) is not referenced explicitly after the main loop finishes so it's a pretender for garbage collection. This test performs gc() explicitly and then tries to send a message to a dealer socket that could be destroyed and collected. If a message is delivered, than everything is ok. Otherwise the guard timeout will make the test fail.
(anonymous) ( msg )
javascript
JustinTulloss/zeromq.node
test/gc.js
https://github.com/JustinTulloss/zeromq.node/blob/master/test/gc.js
MIT
function requestMicToggle() { debugLog('Requested microphone toggle'); mainWindow.webContents.send('request-mic-toggle'); }
Toggles the assistant microphone in the renderer process.
requestMicToggle ( )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app.js
Apache-2.0
function displayNotification(opts) { const icon = nativeImage.createFromPath( path.join(__dirname, 'app', 'res', 'icons', 'icon.png'), ); if (process.platform === 'win32') { tray.displayBalloon({ title: opts.title, content: opts.body, icon, }); tray.on('balloon-click', () => { opts.onNotificationClick?.(); }); }
Displays Notifications. On Windows, a balloon is displayed instead of using the Notification API. @param {object} opts @param {string} opts.title @param {string} opts.body @param {{type: string, text: string, onClick: Function}[]?} opts.actions @param {Function?} opts.onNotificationClick
displayNotification ( opts )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app.js
Apache-2.0
function launchAssistant(args = { shouldStartMic: false, }) { if (!readyForLaunch) return; // Set assistant window launch args assistantWindowLaunchArgs = args; mainWindow.webContents.executeJavaScript( 'document.querySelector("body").innerHTML = "";', ); mainWindow.reload(); mainWindow.show(); }
Launches the assistant renderer process. @param {object} args Arguments to be processed when assistant window launches @param {boolean} args.shouldStartMic Should the assistant start mic when relaunched
launchAssistant ( args = { shouldStartMic : false , } )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app.js
Apache-2.0
function shouldAutoInstallUpdate() { return !didLaunchWindow && assistantConfig.autoDownloadUpdates && updater._isDownloadCached; }
Checks for criterion for auto-installing downloaded update
shouldAutoInstallUpdate ( )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app.js
Apache-2.0
function setAssistantWindowPosition() { const displayList = electron.screen.getAllDisplays(); const displayIndex = getDisplayIndex(displayList); const { x, width, height } = displayList[displayIndex].workArea; const windowSize = mainWindow.getSize(); mainWindow.setPosition( Math.floor(width / 2 - windowSize[0] / 2 + x), Math.floor(height - windowSize[1] - 10), ); }
Sets the assistant window position at the bottom-center position of the given display.
setAssistantWindowPosition ( )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app.js
Apache-2.0
function getDisplayIndex(displayList) { let displayIndex = 0; try { displayIndex = parseInt(assistantConfig['displayPreference']) - 1; if (displayIndex > displayList.length - 1 || displayIndex < 0) { debugLog(`Resetting Display Preference: ${displayIndex + 1} -> 1`); displayIndex = 0; } else { displayIndex = 0; } } catch { displayIndex = 0; } return displayIndex; }
Returns display index based on `assistantConfig.displayPreference`. If the value of `displayPreference` is invalid or is unavailable, a default value is returned. @param {Electron.Display[]} displayList The list of all available displays.
getDisplayIndex ( displayList )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app.js
Apache-2.0
function registerAssistantHotkey(hotkey) { electron.globalShortcut.register(hotkey, () => { const { hotkeyBehavior } = assistantConfig; const isContentsVisible = mainWindow.isVisible(); if (hotkeyBehavior === 'launch' || !isContentsVisible) { launchAssistant(); } else if (hotkeyBehavior === 'launch+close' && isContentsVisible) { // Prevents change in size and position of window when opening assistant the next time mainWindow.restore(); mainWindow.webContents.send('window-will-close'); if (process.platform !== 'darwin') { mainWindow.close(); } else { mainWindow.webContents.executeJavaScript( 'document.querySelector("body").innerHTML = "";', ); setTimeout(() => mainWindow.hide(), 100); } } else { requestMicToggle(); } }); }
Registers global shortcut for Assistant. @param {string} hotkey Accelerator for assistant hotkey
registerAssistantHotkey ( hotkey )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app.js
Apache-2.0
function updateHotkey(newHotkey) { electron.globalShortcut.unregisterAll(); registerAssistantHotkey(newHotkey); setTrayContextMenu(newHotkey); }
Re-registers global shortcut and rebuilds tray context menu based on newly assigned assistant hotkey. @param {string} newHotkey Newly assigned assistant hotkey
updateHotkey ( newHotkey )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app.js
Apache-2.0
function isSnap() { return app.getAppPath().startsWith('/snap'); }
Checks if the user is currently using the `snap` build.
isSnap ( )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app.js
Apache-2.0
function isLinux() { return ['win32', 'darwin'].indexOf(process.platform) === -1; }
Checks if the assistant is running in any linux platform.
isLinux ( )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app.js
Apache-2.0
function isDevMode(execPath) { const executablePath = execPath ?? process.argv0; return /[\\/]electron.*$/.test(executablePath); }
Checks if the application is running in Development mode. @param {string?} execPath Path of the executable. Typically `argv[0]`. If left blank, current executable path will be used.
isDevMode ( execPath )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app.js
Apache-2.0
function isFallbackMode() { return argv.includes('--fallback'); }
Checks if the application is running in fallback mode. Typically enabled when user requests the session to start with settings set to default.
isFallbackMode ( )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app.js
Apache-2.0
function assistantTextQuery(query) { if (query.trim()) { audPlayer.stop(); config.conversation['textQuery'] = query; assistant.start(config.conversation); setQueryTitle(query); assistantInput.value = ''; currentTypedQuery = ''; stopMic(); } }
Ask a `query` from assistant in text. @param {string} query
assistantTextQuery ( query )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/main.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/main.js
Apache-2.0
function setQueryTitle(query) { const init = document.querySelector('.init'); if (init != null) { init.innerHTML = ` <center id="assistant-logo-main-parent" style="margin-top: 80px;"> <img id="assistant-logo-main" src="../res/Google_Assistant_logo.svg" alt=""> </center>`; } document.querySelector('.app-title').innerHTML = ` <span class="fade-in-from-bottom"> ${query} </span>`; activateLoader(); }
Set the `query` in titlebar @param {string} query
setQueryTitle ( query )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/main.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/main.js
Apache-2.0
function getCurrentQuery() { return document.querySelector('.app-title').innerText; }
Returns the title displayed in the 'titlebar' @returns {string} Title
getCurrentQuery ( )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/main.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/main.js
Apache-2.0
function retryRecent(popHistory = true) { if (popHistory) history.pop(); assistantTextQuery(getCurrentQuery()); }
Retry/Refresh result for the query displayed in the titlebar @param {boolean} popHistory Remove the recent result from history and replace it with the refreshed one. _(Defaults to `true`)_
retryRecent ( popHistory = true )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/main.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/main.js
Apache-2.0
function activateLoader() { const loaderArea = document.querySelector('#loader-area'); loaderArea.classList.value = 'loader'; }
Display a preloader near the titlebar to notify user that a task is being performed.
activateLoader ( )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/main.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/main.js
Apache-2.0
function deactivateLoader() { const loaderArea = document.querySelector('#loader-area'); loaderArea.classList.value = ''; }
Make the preloader near the titlebar disappear once the task is completed.
deactivateLoader ( )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/main.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/main.js
Apache-2.0
function stopAudioAndMic() { mic.stop(); audPlayer.stop(); }
Turns off mic and stops output stream of the audio player. Typically called before the window is closed.
stopAudioAndMic ( )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/main.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/main.js
Apache-2.0
function getEffectiveTheme(theme = null) { // eslint-disable-next-line no-underscore-dangle const _theme = theme || assistantConfig.theme; if (['light', 'dark'].includes(_theme)) { return _theme; } if (_theme === 'system') { if (window.matchMedia('(prefers-color-scheme: light)').matches) { return 'light'; } } return 'dark'; }
Returns effective theme based on `assistantConfig.theme`. If the theme is set to `"system"`, it returns the system theme. @param {"dark" | "light" | "system"} theme Get the effective theme for given theme explicitly. Leave it blank to infer from `assistantConfig.theme` @returns {string} Effective theme based on config and system preferences
getEffectiveTheme ( theme = null )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/main.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/main.js
Apache-2.0
function setTheme(theme = null, forceAssistantResponseThemeChange = true) { const effectiveTheme = getEffectiveTheme(theme || assistantConfig.theme); const themeLabel = effectiveTheme === 'light' ? 'light-theme' : 'dark-theme'; Object.keys(themes[themeLabel]).forEach((cssVariable) => { document.documentElement.style.setProperty( cssVariable, themes[themeLabel][cssVariable], ); }); console.log(...consoleMessage( `Setting theme: ${effectiveTheme} (${assistantConfig.theme})`, )); if ( forceAssistantResponseThemeChange && document.querySelector('.assistant-markup-response') ) { displayScreenData(history[historyHead]['screen-data']); } document .querySelector('#master-bg') .setAttribute('data-theme', effectiveTheme); }
Sets the theme based on the given `theme`. @param {"dark" | "light" | "system"} theme The theme which you want to switch to. Ignore this parameter, if you want to set the theme based on `assistantConfig.theme` @param {boolean} forceAssistantResponseThemeChange Change theme for Assistant Response screen. _(Defaults to `true`)_
setTheme ( theme = null , forceAssistantResponseThemeChange = true )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/main.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/main.js
Apache-2.0
function getAboutBoxContent() { const { commitHash, commitDate } = getCommitInfo(); const appVersion = app.getVersion(); const nodeVersion = process.versions.node; const v8Version = process.versions.v8; const electronVersion = process.versions.electron; const chromeVersion = process.versions.chrome; const osInfo = [ `${os.type()}`, `${os.arch()}`, `${os.release()} ${isSnap() ? 'snap' : ''}`, ].join(' '); const commitInfo = commitHash != null ? `Commit ID: ${commitHash}\nCommit Date: ${commitDate}\n` : ''; const content = [ `Version: ${appVersion}`, `${commitInfo}Electron: ${electronVersion}`, `Chrome: ${chromeVersion}`, `Node.js: ${nodeVersion}`, `V8: ${v8Version}`, `OS: ${osInfo.trimEnd()}`, ].join('\n'); return content; }
Returns the string content to display inside About Box
getAboutBoxContent ( )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/main.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/main.js
Apache-2.0
function showArgsDialog() { const content = process.argv.join('\n '); displayAsyncDialog({ type: 'info', title: 'Google Assistant Unofficial Desktop Client', message: 'Command Line Arguments', detail: content, buttons: ['OK', 'Copy'], }) .then((result) => { if (result.response === 1) { // If "Copy" is pressed electron.clipboard.writeText(content); } }); }
Display "Command Line Arguments" Dialog Box.
showArgsDialog ( )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/main.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/main.js
Apache-2.0
function startMic() { if (assistantConfig['respondToHotword']) { // Disable hotword detection when assistant is listening hotwordDetector?.stop(); } if (canAccessMicrophone) { if (!mic) mic = new Microphone(); } else { audPlayer.playPingStop(); stopMic(); displayQuickMessage('Microphone is not accessible', true); return; } if (config.conversation['textQuery'] !== undefined) { delete config.conversation['textQuery']; } // Prevent triggering microphone when assistant // has not been initialized. if (!isAssistantReady) return; mic.start(); assistant.start(config.conversation); }
Start the microphone for transcription and visualization.
startMic ( )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/main.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/main.js
Apache-2.0
function stopMic() { if (assistantConfig['respondToHotword']) { // Enable hotword detection when assistant has done listening hotwordDetector?.start(); } console.log('STOPPING MICROPHONE...'); if (mic) mic.stop(); p5jsMic.stop(); if (initHeadline) { initHeadline.innerText = supportedLanguages[assistantConfig['language']].welcomeMessage; } // Set the `Assistant Mic` icon const assistantMicrophoneParent = document.querySelector('#assistant-mic-parent'); assistantMicrophoneParent.outerHTML = ` <div id="assistant-mic-parent" class="fade-scale"> <img id="assistant-mic" src="../res/Google_mic.svg" type="icon" alt="Speak"> </div> `; // Add Event Listener to the `Assistant Mic` assistantMicrophone = document.querySelector('#assistant-mic'); assistantMicrophone.onclick = startMic; }
Stops the microphone for transcription and visualization.
stopMic ( )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/main.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/main.js
Apache-2.0
function closeOnBlurCallback() { const isDevToolsFocused = assistantWindow.webContents.isDevToolsFocused(); const isCloseOnBlurAllowed = ipcRenderer.sendSync('get-allow-close-on-blur'); // Only close when not focusing DevTools and // the application is initialized properly if (!isDevToolsFocused && initScreenFlag && isCloseOnBlurAllowed) { stopAudioAndMic(); close(); } // Reset `allowCloseOnBlur` if already set to `false` ipcRenderer.sendSync('set-allow-close-on-blur', true); }
Callback function called when the application requests to close the window when out of focus.
closeOnBlurCallback ( )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/main.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/main.js
Apache-2.0
function isFallbackMode() { return process.env.FALLBACK_MODE === 'true'; }
Checks if the application is running in fallback mode. Typically enabled when user requests the app to start with settings set to default.
isFallbackMode ( )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/main.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/main.js
Apache-2.0
function getCommitInfo() { let commitHash; let commitDate; try { commitHash = execSync('git rev-parse HEAD').toString().trim(); commitDate = execSync('git log -1 --format=%cd').toString().trim(); } catch (err) { console.error(err); if (app.getAppPath().endsWith('.asar')) { // User is running the release version commitHash = null; commitDate = null; } else { // Either git is not installed or is not found in the path commitHash = '[Git not found in the path]'; commitDate = 'Unknown'; } } return { commitHash, commitDate, }; }
Returns an object containing `commitHash` and `commitDate` of the latest commit. (**Requires GIT**)
getCommitInfo ( )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/main.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/main.js
Apache-2.0
function getVersion(version) { const appVersion = version || app.getVersion(); const ver = `v${appVersion.replace(/^v*/, '')}`; return ver; }
Returns a version string with a `v` prefixed. If the `version` provided is empty, current version of the application is returned. @param {string} version Version
getVersion ( version )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/main.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/main.js
Apache-2.0
function getMicPermEnableHelp() { const defaultMsg = 'Manually enable the microphone permissions for "Google Assistant" in the system settings'; if (process.platform === 'darwin') { // If platform is "MacOS" return ` You can follow either of the steps: <br /> <ul> <li>${defaultMsg}</li> <li> Click this button <button style="margin-left: 10px;" onclick="electron.remote.systemPreferences.askForMediaAccess('microphone')" > Request microphone permission </button> </li> </ul> `; } if (process.platform !== 'win32' && isSnap()) { // If platform is any type of linux distro and application is a snap package. return ` You can follow either of the steps: <br /> <ul> <li>${defaultMsg}</li> <li> Type the following command in the <strong>terminal</strong>: <code class="codeblock">sudo snap connect g-assist:audio-record</code> </li> </ul> `; } // If platform is "Windows" or any linux distro (application not a snap package) return `You can ${defaultMsg.replace(/^M/, 'm')}`; }
Returns help for granting microphone permission as an HTML string.
getMicPermEnableHelp ( )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/main.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/main.js
Apache-2.0
function consoleMessage(message, type = 'info') { let labelColor = ''; switch (type) { case 'error': labelColor = '#EA4335'; break; case 'warn': labelColor = '#E1A804'; break; default: labelColor = '#4285F4'; break; } return [ `%c[${type.toUpperCase()}]%c ${message}`, `color: ${labelColor}`, 'color: unset', ]; }
Returns a formatted message to be logged in console prefixed with a type. @param {string} message The message to be logged in the console @param {"info" | "error" | "warn"} type Type of the message @returns {string[]} List of strings with formatting to be printed in console. Use `...` operator to unpack the list as parameters to the console function. @example <caption>Passing to `console.log`</caption> console.log(...consoleMessage('This is an info', 'info')); @example <caption>Passing to `console.group`</caption> console.group(...consoleMessage('This is an error', 'error')); console.error(error); console.groupEnd();
consoleMessage ( message , type = 'info' )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/main.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/main.js
Apache-2.0
function map(n, start1, stop1, start2, stop2) { return ((n - start1) / (stop1 - start1)) * (stop2 - start2) + start2; }
Maps the value `n` which ranges between `start1` and `stop1` to `start2` and `stop2`. @param {number} n @param {number} start1 @param {number} stop1 @param {number} start2 @param {number} stop2
map ( n , start1 , stop1 , start2 , stop2 )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/main.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/main.js
Apache-2.0
function constrain(n, low, high) { if (n < low) return low; if (n > high) return high; return n; }
Constrain `n` between `high` and `low` @param {number} n @param {number} low @param {number} high
constrain ( n , low , high )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/main.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/main.js
Apache-2.0
assistantInput.oninput = (e) => { // Stop listening when user starts typing if (mic.isActive) stopMic(); queryHistoryHead = history.length; currentTypedQuery = e.target.value; };
Remember user's currently typed query and stops mic when user inputs some characters in the assistant input box. @param {InputEvent} e
assistantInput.oninput
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/main.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/main.js
Apache-2.0
keyDownListener(e, stopListeningAfterKeyCombination, escapeToCancel) { e.preventDefault(); if (e.key === 'Escape' && escapeToCancel) { this.stopListening(); this.emit('cancel'); return; } if (!this.blacklistedKeys.includes(e.key)) { const keyList = []; if (e.metaKey) keyList.push('Super'); if (e.ctrlKey) keyList.push('Ctrl'); if (e.altKey) keyList.push('Alt'); if (e.shiftKey) keyList.push('Shift'); keyList.push(getNormalizedKeyName(e.key)); if (keyList.length >= 2) { this.emit('key-combination', keyList); if (stopListeningAfterKeyCombination) this.stopListening(); } } }
Event listener for `keydown` event @param {KeyboardEvent} e @param {boolean} stopListeningAfterKeyCombination @param {boolean} escapeToCancel
keyDownListener ( e , stopListeningAfterKeyCombination , escapeToCancel )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/keybinding.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/keybinding.js
Apache-2.0
function getNormalizedKeyName(keyboardKey) { const key = keyboardKey.trim(); const keyMap = { ArrowUp: 'Up', ArrowDown: 'Down', ArrowLeft: 'Left', ArrowRight: 'Right', }; if (key.length === 1) { return key.toUpperCase(); } if (Object.keys(keyMap).includes(key)) { return keyMap[key]; } return key; }
Returns normalized key name compliant with Electron Accelerator API. @param {string} keyboardKey Name of the key
getNormalizedKeyName ( keyboardKey )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/keybinding.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/keybinding.js
Apache-2.0
function getNativeKeyName(keyboardKey) { const key = keyboardKey.trim(); const keyMap = { Ctrl: { mac: 'Control', win: 'Ctrl', linux: 'Ctrl', }, Super: { mac: 'Command', win: 'Windows', linux: 'Super', }, Alt: { mac: 'Option', win: 'Alt', linux: 'Alt', }, }; let platform = ''; switch (process.platform) { case 'win32': platform = 'win'; break; case 'darwin': platform = 'mac'; break; default: platform = 'linux'; } if (Object.keys(keyMap).includes(key)) { return keyMap[key][platform]; } return key; }
Returns the platform-specific key name for given key. @param {string} keyboardKey Name of the key
getNativeKeyName ( keyboardKey )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/keybinding.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/keybinding.js
Apache-2.0
function getHotwordDetectorInstance(onHotword) { // Create instance of Bumblebee /** * @type {Bumblebee & { setMicrophone?: (id: string) => void }} */ const bumblebee = new Bumblebee(); // set path to worker files bumblebee.setWorkersPath('./lib/pv_workers'); // add hotword bumblebee.addHotword('hey_google'); bumblebee.addHotword('ok_google'); // set sensitivity (from 0.0 to 1.0) bumblebee.setSensitivity(1); // Call `onHotword` when hotword is detected bumblebee.on('hotword', (hotword) => onHotword(hotword)); // Return Hotword Detection Instance return bumblebee; }
Returns an instance of hotword detector @param {(hotword: string) => void} onHotword Function called when hotword is detected.
getHotwordDetectorInstance ( onHotword )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/hotword.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/hotword.js
Apache-2.0
setup() { this.audioPlayer.addEventListener('waiting', () => { console.log('[Audio Player] Player is waiting on data...'); this.emit('waiting'); }); this.audioPlayer.preload = 'none'; this.audioPlayer.autoplay = true; this.audioPlayer.src = URL.createObjectURL(this.mediaSource); }
Setups the player with the given buffer as source.
setup ( )
javascript
Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client
app/src/lib/audio_player.js
https://github.com/Melvin-Abraham/Google-Assistant-Unofficial-Desktop-Client/blob/master/app/src/lib/audio_player.js
Apache-2.0