language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
searchGithub() { var displayCount = 10; var searchTerm = this.state.searchTerm; console.log(searchTerm); fetch("https://api.github.com/search/repositories?q=" + searchTerm, { headers: { Authorization: github_api_token } }) .then(res => res.json()) .then(function(response) { var records = []; for (var i = 0; i < displayCount; i++) { console.log(response.items); var row = {}; row["id"] = response.items[i].full_name; row["name"] = response.items[i].full_name; row["language"] = response.items[i].language; row["version"] = "-"; row["url"] = response.items[i].html_url; records.push(row); } return records; }) .then( //Get tags from {user} / {repo} function(records) { records.forEach(function(item, i) { fetch("https://api.github.com/repos/" + records[i].name + "/tags", { headers: { Authorization: github_api_token } }) .then(res => res.json()) .then(function(response) { records[i]["version"] = response[0].name; }) .catch(function(err) { records[i]["version"] = "-"; }); }); this.setState({ table: records }); this.forceUpdate(); return records; }.bind(this) ); }
searchGithub() { var displayCount = 10; var searchTerm = this.state.searchTerm; console.log(searchTerm); fetch("https://api.github.com/search/repositories?q=" + searchTerm, { headers: { Authorization: github_api_token } }) .then(res => res.json()) .then(function(response) { var records = []; for (var i = 0; i < displayCount; i++) { console.log(response.items); var row = {}; row["id"] = response.items[i].full_name; row["name"] = response.items[i].full_name; row["language"] = response.items[i].language; row["version"] = "-"; row["url"] = response.items[i].html_url; records.push(row); } return records; }) .then( //Get tags from {user} / {repo} function(records) { records.forEach(function(item, i) { fetch("https://api.github.com/repos/" + records[i].name + "/tags", { headers: { Authorization: github_api_token } }) .then(res => res.json()) .then(function(response) { records[i]["version"] = response[0].name; }) .catch(function(err) { records[i]["version"] = "-"; }); }); this.setState({ table: records }); this.forceUpdate(); return records; }.bind(this) ); }
JavaScript
handleTableClicked (event) { if (event.target.tagName.toLowerCase() !== 'td') { return } const rowElement = event.target.parentElement this.applyRow(rowElement) }
handleTableClicked (event) { if (event.target.tagName.toLowerCase() !== 'td') { return } const rowElement = event.target.parentElement this.applyRow(rowElement) }
JavaScript
handleTorsionMarkerClicked (pickingProxy) { if (!pickingProxy || !pickingProxy.cylinder) { return } const id = pickingProxy.cylinder.name.split(' ').pop() const rows = this.element.getElementsByTagName('tr') for (let i = 0; i < rows.length; i++) { if (rows[i].children[0].textContent === id) { this.applyRow(rows[i]) break } } }
handleTorsionMarkerClicked (pickingProxy) { if (!pickingProxy || !pickingProxy.cylinder) { return } const id = pickingProxy.cylinder.name.split(' ').pop() const rows = this.element.getElementsByTagName('tr') for (let i = 0; i < rows.length; i++) { if (rows[i].children[0].textContent === id) { this.applyRow(rows[i]) break } } }
JavaScript
applyRow (element) { const highlightedElements = this.element.getElementsByClassName('highlight') if (highlightedElements.length > 0) { for (let i = highlightedElements.length - 1; i >= 0; i--) { highlightedElements[i].classList.remove('highlight') } } if (this.highlightedBond) { this.highlightedBond.setHighlight(false) } const rowText = element.getElementsByTagName('td')[0].innerText if (rowText === 'No data available in table') { this.torsionPlot.setTorsionResult(undefined) return } const resultId = parseInt(rowText) element.classList.add('highlight') const result = this.resultComponentMap.get(this.molecule.id).get(resultId) this.highlightedBond = result.torsionMarker this.highlightedBond.setHighlight(true) this.torsionPlot.setTorsionResult(result) }
applyRow (element) { const highlightedElements = this.element.getElementsByClassName('highlight') if (highlightedElements.length > 0) { for (let i = highlightedElements.length - 1; i >= 0; i--) { highlightedElements[i].classList.remove('highlight') } } if (this.highlightedBond) { this.highlightedBond.setHighlight(false) } const rowText = element.getElementsByTagName('td')[0].innerText if (rowText === 'No data available in table') { this.torsionPlot.setTorsionResult(undefined) return } const resultId = parseInt(rowText) element.classList.add('highlight') const result = this.resultComponentMap.get(this.molecule.id).get(resultId) this.highlightedBond = result.torsionMarker this.highlightedBond.setHighlight(true) this.torsionPlot.setTorsionResult(result) }
JavaScript
resize (availableHeight = undefined) { if (availableHeight) { this.availableHeight = availableHeight } const torsionResultsScrollElement = this.element.getElementsByClassName('dataTables_scrollBody') if (torsionResultsScrollElement.length === 1) { torsionResultsScrollElement[0].style.height = this.availableHeight / 3 + 'px' } if (this.table) { this.table.draw() } this.torsionPlot.resize(this.availableHeight * 2 / 3) }
resize (availableHeight = undefined) { if (availableHeight) { this.availableHeight = availableHeight } const torsionResultsScrollElement = this.element.getElementsByClassName('dataTables_scrollBody') if (torsionResultsScrollElement.length === 1) { torsionResultsScrollElement[0].style.height = this.availableHeight / 3 + 'px' } if (this.table) { this.table.draw() } this.torsionPlot.resize(this.availableHeight * 2 / 3) }
JavaScript
handleTabClicked (event) { event.preventDefault() if (event.target.classList.contains('active')) { return } const id = event.target.getAttribute('target') if (id && id !== '_blank') { this.switchTab(id) } }
handleTabClicked (event) { event.preventDefault() if (event.target.classList.contains('active')) { return } const id = event.target.getAttribute('target') if (id && id !== '_blank') { this.switchTab(id) } }
JavaScript
switchTab (id) { if (id === 'help') { return } this.currentTab = id const tabId = id + '-tab' this.tabs.getElementsByClassName('active')[0].classList.remove('active') this.content.getElementsByClassName('active')[0].classList.remove('active') document.getElementById(tabId).classList.add('active') document.getElementById(id).classList.add('active') this.callRenderFunctions(id) }
switchTab (id) { if (id === 'help') { return } this.currentTab = id const tabId = id + '-tab' this.tabs.getElementsByClassName('active')[0].classList.remove('active') this.content.getElementsByClassName('active')[0].classList.remove('active') document.getElementById(tabId).classList.add('active') document.getElementById(id).classList.add('active') this.callRenderFunctions(id) }
JavaScript
addRenderFunction (id, callback) { if (!this.renderFunctions.has(id)) { this.renderFunctions.set(id, []) } this.renderFunctions.get(id).push(callback) }
addRenderFunction (id, callback) { if (!this.renderFunctions.has(id)) { this.renderFunctions.set(id, []) } this.renderFunctions.get(id).push(callback) }
JavaScript
callRenderFunctions (id) { if (!this.renderFunctions.has(id)) { return } this.renderFunctions.get(id).forEach((callback) => callback()) }
callRenderFunctions (id) { if (!this.renderFunctions.has(id)) { return } this.renderFunctions.get(id).forEach((callback) => callback()) }
JavaScript
async fetchPlot (url, plotElement, angle) { if (!this.plotCallback) { plotElement.innerHTML = 'No plot available' return } const plot = await this.plotCallback(url) if (!plot) { plotElement.innerHTML = 'No plot available' } else { this.loadPlot(plotElement, plot, angle) } }
async fetchPlot (url, plotElement, angle) { if (!this.plotCallback) { plotElement.innerHTML = 'No plot available' return } const plot = await this.plotCallback(url) if (!plot) { plotElement.innerHTML = 'No plot available' } else { this.loadPlot(plotElement, plot, angle) } }
JavaScript
loadPlot (plotElement, plot, angle) { plot = plot.replaceAll('id="patch_', 'class="patch_') .replaceAll('id="xtick_', 'class="xtick_') plotElement.innerHTML = plot TorsionPlot.makeAngleLine(plotElement, angle) this.resize() }
loadPlot (plotElement, plot, angle) { plot = plot.replaceAll('id="patch_', 'class="patch_') .replaceAll('id="xtick_', 'class="xtick_') plotElement.innerHTML = plot TorsionPlot.makeAngleLine(plotElement, angle) this.resize() }
JavaScript
resize (availableHeight = undefined) { if (availableHeight) { this.availableHeight = availableHeight } const pill = this.element.getElementsByTagName('a')[0] const svgs = this.element.getElementsByTagName('svg') for (let i = 0; i < svgs.length; i++) { svgs[i].style.width = this.element.clientWidth + 'px' svgs[i].style.height = (this.availableHeight - pill.clientHeight) + 'px' } }
resize (availableHeight = undefined) { if (availableHeight) { this.availableHeight = availableHeight } const pill = this.element.getElementsByTagName('a')[0] const svgs = this.element.getElementsByTagName('svg') for (let i = 0; i < svgs.length; i++) { svgs[i].style.width = this.element.clientWidth + 'px' svgs[i].style.height = (this.availableHeight - pill.clientHeight) + 'px' } }
JavaScript
generateTabs () { const uploadFormId = 'upload-form' const uploadFormElement = ElementBuilder.generate('div') .createChild('h1', 'Upload') .appendChild(ElementBuilder.generate('div') .setAttribute('id', uploadFormId)) .addClass('container').element this.tabPane.addTab('Upload', uploadFormElement) const moleculeTableId = 'molecule-table-element' const moleculeTableElement = ElementBuilder.generate('div') .createChild('h1', 'Molecules') .appendChild(ElementBuilder.generate('div') .setAttribute('id', moleculeTableId)) .addClass('container').element this.tabPane.addTab('Molecules', moleculeTableElement) const torsionResultTableId = 'torsion-result-table-element' const torsionResultTableElement = ElementBuilder.generate('div') .createChild('h1', 'Torsion Results') .appendChild(ElementBuilder.generate('div') .setAttribute('id', torsionResultTableId)) .addClass('container').element this.tabPane.addTab('Torsion Results', torsionResultTableElement) // help tab with link to help.html this.tabPane.addTab('Help') const helpTab = document.getElementById('help-tab') helpTab.addEventListener('click', (_event) => { window.open(this.baseUrl + '/help.html') }) this.uploadForm = new MoleculeUploadForm(uploadFormId) this.uploadForm.uploadForm.addEventListener('submit', (event) => { this.handleUploadedFile(event) }) const torsionResultsAvailableHeight = this.tabPane.element.clientHeight - this.TABPANE_HEIGHT this.torsionResultTable = new TorsionResultsTable( torsionResultTableId, this.stage, undefined, torsionResultsAvailableHeight, (url) => this.handleDownloadPlot(url)) this.tabPane.addRenderFunction('torsion-results', () => { this.torsionResultTable.resize(this.tabPane.element.clientHeight - this.TABPANE_HEIGHT) }) const moleculeTableAvailableHeight = this.tabPane.element.clientHeight - this.TABPANE_HEIGHT this.moleculeTable = new MoleculeTable( moleculeTableId, this.stage, this.torsionResultTable, [], moleculeTableAvailableHeight, (event) => this.handleDownloadFile(event)) this.tabPane.addRenderFunction('molecules', () => { this.moleculeTable.resize(this.tabPane.element.clientHeight - this.TABPANE_HEIGHT) }) }
generateTabs () { const uploadFormId = 'upload-form' const uploadFormElement = ElementBuilder.generate('div') .createChild('h1', 'Upload') .appendChild(ElementBuilder.generate('div') .setAttribute('id', uploadFormId)) .addClass('container').element this.tabPane.addTab('Upload', uploadFormElement) const moleculeTableId = 'molecule-table-element' const moleculeTableElement = ElementBuilder.generate('div') .createChild('h1', 'Molecules') .appendChild(ElementBuilder.generate('div') .setAttribute('id', moleculeTableId)) .addClass('container').element this.tabPane.addTab('Molecules', moleculeTableElement) const torsionResultTableId = 'torsion-result-table-element' const torsionResultTableElement = ElementBuilder.generate('div') .createChild('h1', 'Torsion Results') .appendChild(ElementBuilder.generate('div') .setAttribute('id', torsionResultTableId)) .addClass('container').element this.tabPane.addTab('Torsion Results', torsionResultTableElement) // help tab with link to help.html this.tabPane.addTab('Help') const helpTab = document.getElementById('help-tab') helpTab.addEventListener('click', (_event) => { window.open(this.baseUrl + '/help.html') }) this.uploadForm = new MoleculeUploadForm(uploadFormId) this.uploadForm.uploadForm.addEventListener('submit', (event) => { this.handleUploadedFile(event) }) const torsionResultsAvailableHeight = this.tabPane.element.clientHeight - this.TABPANE_HEIGHT this.torsionResultTable = new TorsionResultsTable( torsionResultTableId, this.stage, undefined, torsionResultsAvailableHeight, (url) => this.handleDownloadPlot(url)) this.tabPane.addRenderFunction('torsion-results', () => { this.torsionResultTable.resize(this.tabPane.element.clientHeight - this.TABPANE_HEIGHT) }) const moleculeTableAvailableHeight = this.tabPane.element.clientHeight - this.TABPANE_HEIGHT this.moleculeTable = new MoleculeTable( moleculeTableId, this.stage, this.torsionResultTable, [], moleculeTableAvailableHeight, (event) => this.handleDownloadFile(event)) this.tabPane.addRenderFunction('molecules', () => { this.moleculeTable.resize(this.tabPane.element.clientHeight - this.TABPANE_HEIGHT) }) }
JavaScript
onKeydown (event) { if (event.keyCode !== 32) { return } if (this.moleculeTable.highlightedMolecule && this.moleculeTable.highlightedMolecule.component) { this.moleculeTable.highlightedMolecule.component.autoView() } }
onKeydown (event) { if (event.keyCode !== 32) { return } if (this.moleculeTable.highlightedMolecule && this.moleculeTable.highlightedMolecule.component) { this.moleculeTable.highlightedMolecule.component.autoView() } }
JavaScript
handleUploadedFile (event) { event.preventDefault() $('#tab-pane').loading() const file = this.uploadForm.fileField.files[0] const formData = new FormData() formData.append('molFile', file) this.upload(formData) }
handleUploadedFile (event) { event.preventDefault() $('#tab-pane').loading() const file = this.uploadForm.fileField.files[0] const formData = new FormData() formData.append('molFile', file) this.upload(formData) }
JavaScript
upload (formData) { const tabPane = $('#tab-pane') fetch(this.baseUrl + '/torsion_analysis', { method: this.uploadForm.uploadForm.getAttribute('method'), body: formData }).then((response) => { if (response.status >= 500) { alert('Encountered an internal server error.') tabPane.loading('stop') return } response.json().then((json) => { if (response.status >= 400) { alert(json.error) tabPane.loading('stop') return } this.poll(json.id, (data) => { this.torsionAnalysis = data this.moleculeTable.setMolecules(this.torsionAnalysis.molecules) this.tabPane.switchTab('molecules') }) }) }) }
upload (formData) { const tabPane = $('#tab-pane') fetch(this.baseUrl + '/torsion_analysis', { method: this.uploadForm.uploadForm.getAttribute('method'), body: formData }).then((response) => { if (response.status >= 500) { alert('Encountered an internal server error.') tabPane.loading('stop') return } response.json().then((json) => { if (response.status >= 400) { alert(json.error) tabPane.loading('stop') return } this.poll(json.id, (data) => { this.torsionAnalysis = data this.moleculeTable.setMolecules(this.torsionAnalysis.molecules) this.tabPane.switchTab('molecules') }) }) }) }
JavaScript
poll (id, callback) { const tabPane = $('#tab-pane') fetch(this.baseUrl + '/torsion_analysis/' + id, { method: 'get' }) .then((response) => { if (response.status >= 500) { alert('Encountered an internal server error.') tabPane.loading('stop') return } response.json().then((json) => { if (response.status >= 400) { alert(json.error) tabPane.loading('stop') return } if (json.status === 'pending' || json.status === 'running') { setTimeout(() => { this.poll(id, callback) }, 3000) } else if (json.status === 'failure') { alert('Torsion analysis failed') tabPane.loading('stop') } else if (json.status === 'success') { tabPane.loading('stop') callback(json) } }) }) }
poll (id, callback) { const tabPane = $('#tab-pane') fetch(this.baseUrl + '/torsion_analysis/' + id, { method: 'get' }) .then((response) => { if (response.status >= 500) { alert('Encountered an internal server error.') tabPane.loading('stop') return } response.json().then((json) => { if (response.status >= 400) { alert(json.error) tabPane.loading('stop') return } if (json.status === 'pending' || json.status === 'running') { setTimeout(() => { this.poll(id, callback) }, 3000) } else if (json.status === 'failure') { alert('Torsion analysis failed') tabPane.loading('stop') } else if (json.status === 'success') { tabPane.loading('stop') callback(json) } }) }) }
JavaScript
handleDownloadFile (event) { event.stopImmediatePropagation() if (this.torsionAnalysis.id) { window.open(this.baseUrl + '/torsion_analysis/' + this.torsionAnalysis.id + '/download') } else { alert('No torsion analysis to download') } }
handleDownloadFile (event) { event.stopImmediatePropagation() if (this.torsionAnalysis.id) { window.open(this.baseUrl + '/torsion_analysis/' + this.torsionAnalysis.id + '/download') } else { alert('No torsion analysis to download') } }
JavaScript
async handleDownloadPlot (url) { const response = await fetch(this.baseUrl + url) if (response.status !== 200) { return undefined } return await response.text() }
async handleDownloadPlot (url) { const response = await fetch(this.baseUrl + url) if (response.status !== 200) { return undefined } return await response.text() }
JavaScript
handleTorsionMarkerClicked (pickingProxy) { if (!pickingProxy || !pickingProxy.cylinder) { return } if (this.tabPane.currentTab !== 'torsion-results') { this.tabPane.switchTab('torsion-results') } }
handleTorsionMarkerClicked (pickingProxy) { if (!pickingProxy || !pickingProxy.cylinder) { return } if (this.tabPane.currentTab !== 'torsion-results') { this.tabPane.switchTab('torsion-results') } }
JavaScript
applyRow (element) { const highlightedElements = this.element.getElementsByClassName('highlight') if (highlightedElements.length > 0) { for (let i = highlightedElements.length - 1; i >= 0; i--) { highlightedElements[i].classList.remove('highlight') } } this.highlightedElement = element this.highlightedElement.classList.add('highlight') const data = this.table.row(this.highlightedElement).data() const entryId = parseInt(this.highlightedElement.children[0].textContent) this.loadMolecule(entryId, data) }
applyRow (element) { const highlightedElements = this.element.getElementsByClassName('highlight') if (highlightedElements.length > 0) { for (let i = highlightedElements.length - 1; i >= 0; i--) { highlightedElements[i].classList.remove('highlight') } } this.highlightedElement = element this.highlightedElement.classList.add('highlight') const data = this.table.row(this.highlightedElement).data() const entryId = parseInt(this.highlightedElement.children[0].textContent) this.loadMolecule(entryId, data) }
JavaScript
initMolecule () { if (this.molecules.length > 0) { this.highlightedElement = this.element.querySelector('tr.odd, tr.even') this.highlightedElement.classList.add('highlight') this.loadMolecule(this.molecules[0].entryId, this.molecules[0]) } }
initMolecule () { if (this.molecules.length > 0) { this.highlightedElement = this.element.querySelector('tr.odd, tr.even') this.highlightedElement.classList.add('highlight') this.loadMolecule(this.molecules[0].entryId, this.molecules[0]) } }
JavaScript
loadMolecule (entryId, molecule) { this.highlightedMolecule = molecule for (const [, molecule] of this.componentMap.entries()) { molecule.component.setVisibility(false) } if (this.componentMap.has(entryId)) { this.componentMap.get(entryId).component.setVisibility(true) this.torsionResultsTable.setMolecule(molecule) molecule.component.autoView() } else { Utils.addStructure(this.stage, molecule).then((component) => { molecule.component = component component.addRepresentation('licorice', { multipleBond: true }) component.autoView() this.componentMap.set(entryId, molecule) molecule.component.autoView() this.torsionResultsTable.setMolecule(molecule) }) } }
loadMolecule (entryId, molecule) { this.highlightedMolecule = molecule for (const [, molecule] of this.componentMap.entries()) { molecule.component.setVisibility(false) } if (this.componentMap.has(entryId)) { this.componentMap.get(entryId).component.setVisibility(true) this.torsionResultsTable.setMolecule(molecule) molecule.component.autoView() } else { Utils.addStructure(this.stage, molecule).then((component) => { molecule.component = component component.addRepresentation('licorice', { multipleBond: true }) component.autoView() this.componentMap.set(entryId, molecule) molecule.component.autoView() this.torsionResultsTable.setMolecule(molecule) }) } }
JavaScript
resize (availableHeight = undefined) { if (availableHeight) { this.availableHeight = availableHeight - this.downloadButton.clientHeight } const moleculeTableScrollElement = this.element.getElementsByClassName('dataTables_scrollBody') if (moleculeTableScrollElement.length === 1) { moleculeTableScrollElement[0].style.height = this.availableHeight + 'px' } if (this.table) { this.table.draw() } }
resize (availableHeight = undefined) { if (availableHeight) { this.availableHeight = availableHeight - this.downloadButton.clientHeight } const moleculeTableScrollElement = this.element.getElementsByClassName('dataTables_scrollBody') if (moleculeTableScrollElement.length === 1) { moleculeTableScrollElement[0].style.height = this.availableHeight + 'px' } if (this.table) { this.table.draw() } }
JavaScript
fileCheck (event) { const file = event.target.files[0] if (file.size > this.maxFileSize) { alert('Maximum file size is 10 MB') this.disableUpload() return } const splitFileName = file.name.split('.') if (splitFileName[splitFileName.length - 1] !== 'sdf') { alert('File with unsupported extension. (Supported: ".sdf")') this.disableUpload() return } this.enableUpload() }
fileCheck (event) { const file = event.target.files[0] if (file.size > this.maxFileSize) { alert('Maximum file size is 10 MB') this.disableUpload() return } const splitFileName = file.name.split('.') if (splitFileName[splitFileName.length - 1] !== 'sdf') { alert('File with unsupported extension. (Supported: ".sdf")') this.disableUpload() return } this.enableUpload() }
JavaScript
function seed(doc, options) { var Category = mongoose.model('Category'); return new Promise(function (resolve, reject) { skipDocument() .then(findAdminUser) .then(add) .then(function (response) { return resolve(response); }) .catch(function (err) { return reject(err); }); function findAdminUser(skip) { var User = mongoose.model('User'); return new Promise(function (resolve, reject) { if (skip) { return resolve(true); } User .findOne({ roles: { $in: ['admin'] } }) .exec(function (err, admin) { if (err) { return reject(err); } doc.user = admin; return resolve(); }); }); } function skipDocument() { return new Promise(function (resolve, reject) { Category .findOne({ title: doc.title }) .exec(function (err, existing) { if (err) { return reject(err); } if (!existing) { return resolve(false); } if (existing && !options.overwrite) { return resolve(true); } // Remove Category (overwrite) existing.remove(function (err) { if (err) { return reject(err); } return resolve(false); }); }); }); } function add(skip) { return new Promise(function (resolve, reject) { if (skip) { return resolve({ message: chalk.yellow('Database Seeding: Category\t' + doc.title + ' skipped') }); } var category = new Category(doc); category.save(function (err) { if (err) { return reject(err); } return resolve({ message: 'Database Seeding: Category\t' + category.title + ' added' }); }); }); } }); }
function seed(doc, options) { var Category = mongoose.model('Category'); return new Promise(function (resolve, reject) { skipDocument() .then(findAdminUser) .then(add) .then(function (response) { return resolve(response); }) .catch(function (err) { return reject(err); }); function findAdminUser(skip) { var User = mongoose.model('User'); return new Promise(function (resolve, reject) { if (skip) { return resolve(true); } User .findOne({ roles: { $in: ['admin'] } }) .exec(function (err, admin) { if (err) { return reject(err); } doc.user = admin; return resolve(); }); }); } function skipDocument() { return new Promise(function (resolve, reject) { Category .findOne({ title: doc.title }) .exec(function (err, existing) { if (err) { return reject(err); } if (!existing) { return resolve(false); } if (existing && !options.overwrite) { return resolve(true); } // Remove Category (overwrite) existing.remove(function (err) { if (err) { return reject(err); } return resolve(false); }); }); }); } function add(skip) { return new Promise(function (resolve, reject) { if (skip) { return resolve({ message: chalk.yellow('Database Seeding: Category\t' + doc.title + ' skipped') }); } var category = new Category(doc); category.save(function (err) { if (err) { return reject(err); } return resolve({ message: 'Database Seeding: Category\t' + category.title + ' added' }); }); }); } }); }
JavaScript
function parseComment (comment) { const body = j('[' + comment + ']').nodes()[0].program.body const array = body[0].expression return array.elements }
function parseComment (comment) { const body = j('[' + comment + ']').nodes()[0].program.body const array = body[0].expression return array.elements }
JavaScript
static observeValidation(...validationObservers) { return combineLatest( validationObservers, (...errors) => [].concat(...errors)) .pipe( map(errors => errors.length === 0), startWith(false), share()); }
static observeValidation(...validationObservers) { return combineLatest( validationObservers, (...errors) => [].concat(...errors)) .pipe( map(errors => errors.length === 0), startWith(false), share()); }
JavaScript
length(min, max) { return this.addValidator( (value) => value.length >= min && value.length <= max, `Must be at least ${min} and at most ${max} characters long` ); }
length(min, max) { return this.addValidator( (value) => value.length >= min && value.length <= max, `Must be at least ${min} and at most ${max} characters long` ); }
JavaScript
isEmpty() { return this.addValidator( (value) => value === null || value.length === 0, `Is empty` ); }
isEmpty() { return this.addValidator( (value) => value === null || value.length === 0, `Is empty` ); }
JavaScript
flatten(constraint) { return this.addValidator( (value) => constraint.validate(value).length === 0, flatttenValidatorDescription(constraint) ); }
flatten(constraint) { return this.addValidator( (value) => constraint.validate(value).length === 0, flatttenValidatorDescription(constraint) ); }
JavaScript
isEmail() { return this.addValidator( (value) => isEmail(value), `Provide a valid email` ) }
isEmail() { return this.addValidator( (value) => isEmail(value), `Provide a valid email` ) }
JavaScript
async markRead() { if (this._markingRead) return; this._markReadIcon.controller.displayAlternate(this._loadingMarkedRead); this._markingRead = true; const NotificationStatus = await Notification.getStatuses(); const markNotificationStatus = new MarkNotificationStatus(this.notificationGroup, NotificationStatus.read); await markNotificationStatus.run(); this._markingRead = false; // Switch the checkmark to a loading icon this.markedRead(); }
async markRead() { if (this._markingRead) return; this._markReadIcon.controller.displayAlternate(this._loadingMarkedRead); this._markingRead = true; const NotificationStatus = await Notification.getStatuses(); const markNotificationStatus = new MarkNotificationStatus(this.notificationGroup, NotificationStatus.read); await markNotificationStatus.run(); this._markingRead = false; // Switch the checkmark to a loading icon this.markedRead(); }
JavaScript
markedRead() { // Switch from blue -> gray icon this._unreadIconWrapper.classList.remove('notification__detail--state-unread'); this._unreadIconWrapper.classList.add('notification__detail--state-read'); // Remove the read button if (this._markReadWrapper.parentNode) { this._markReadWrapper.parentNode.removeChild(this._markReadWrapper); } }
markedRead() { // Switch from blue -> gray icon this._unreadIconWrapper.classList.remove('notification__detail--state-unread'); this._unreadIconWrapper.classList.add('notification__detail--state-read'); // Remove the read button if (this._markReadWrapper.parentNode) { this._markReadWrapper.parentNode.removeChild(this._markReadWrapper); } }
JavaScript
async loginJWT(authData) { await axios.post( '/auth/login/jwt', authData.json ); }
async loginJWT(authData) { await axios.post( '/auth/login/jwt', authData.json ); }
JavaScript
bindLabelGroup(labelGroup) { labelGroup.validationDelegate.didSetStateTo = (labelGroup, isValid) => { if (isValid) { this.state = CheckState.Done; } else { this.state = CheckState.Error; } }; }
bindLabelGroup(labelGroup) { labelGroup.validationDelegate.didSetStateTo = (labelGroup, isValid) => { if (isValid) { this.state = CheckState.Done; } else { this.state = CheckState.Error; } }; }
JavaScript
observeFocus() { return merge( fromEvent(this.underlyingNode, 'focus') .pipe(mapTo(true)), fromEvent(this.underlyingNode, 'blur') .pipe(mapTo(false)) ); }
observeFocus() { return merge( fromEvent(this.underlyingNode, 'focus') .pipe(mapTo(true)), fromEvent(this.underlyingNode, 'blur') .pipe(mapTo(false)) ); }
JavaScript
clone() { return new Answer({ id: this._id, code: this._code, encoding: this._encoding, commentary: this._commentary, length: this._length, language: this._language, user: this._user }); }
clone() { return new Answer({ id: this._id, code: this._code, encoding: this._encoding, commentary: this._commentary, length: this._length, language: this._language, user: this._user }); }
JavaScript
static fromIndexJSON(json) { return new Answer({ id: json.id, code: json.code, deleted: false, length: json.byte_count, language: Language.fromJSON(json.language), user: User.fromIndexJSON(json.author), dateCreated: new Date(json.date_created), dateModified: new Date(json.last_modified), post: new Post({ postId: json.post.id, title: json.post.name, slug: json.post.slug }) }); }
static fromIndexJSON(json) { return new Answer({ id: json.id, code: json.code, deleted: false, length: json.byte_count, language: Language.fromJSON(json.language), user: User.fromIndexJSON(json.author), dateCreated: new Date(json.date_created), dateModified: new Date(json.last_modified), post: new Post({ postId: json.post.id, title: json.post.name, slug: json.post.slug }) }); }
JavaScript
foreignSynchronize(text, time = 50) { let interactor = new ForeignInteractor(`/post/preview`); let interactionTargets = this._form.getElementsByClassName('foreign-synchronize'); for (let i = 0; i < interactionTargets.length; i++) { let target = interactionTargets[i]; let name = target.name; interactor.sendKey(name, ""); interactionTargets[i].addEventListener('input', () => { interactor.queueKey(name, time, target.value); }); } return <a href={interactor.link} target="_blank">{text}</a>; }
foreignSynchronize(text, time = 50) { let interactor = new ForeignInteractor(`/post/preview`); let interactionTargets = this._form.getElementsByClassName('foreign-synchronize'); for (let i = 0; i < interactionTargets.length; i++) { let target = interactionTargets[i]; let name = target.name; interactor.sendKey(name, ""); interactionTargets[i].addEventListener('input', () => { interactor.queueKey(name, time, target.value); }); } return <a href={interactor.link} target="_blank">{text}</a>; }
JavaScript
addConstraints(constraints) { for (let i = 0; i < constraints.length; i++) { this.addConstraint(constraints[i]); } }
addConstraints(constraints) { for (let i = 0; i < constraints.length; i++) { this.addConstraint(constraints[i]); } }
JavaScript
get request() { return new Request({ path: this.path, method: this.method, data: this.formData }); }
get request() { return new Request({ path: this.path, method: this.method, data: this.formData }); }
JavaScript
get locationHash() { if (this.navigation.length === 0) return ''; return `/${this.navigation.join("/")}`; }
get locationHash() { if (this.navigation.length === 0) return ''; return `/${this.navigation.join("/")}`; }
JavaScript
get hash() { const hash = this.locationHash + this.valueHash; if (hash === '') return ''; return '!' + hash; }
get hash() { const hash = this.locationHash + this.valueHash; if (hash === '') return ''; return '!' + hash; }
JavaScript
async nextPage(animated = true) { const users = await this.request.nextPage(); if (users.length === 0) return false; const subList = <ul class="user-item__sublist" />; // Load all items into a temporary list await Promise.all( users.map(async user => { const template = await new UserTemplate(user); template.loadInContext(subList); }) ); const newSublist = <li class="user-item__sublist_wrap">{ subList }</li>; this.userList.appendChild(newSublist); if (animated) { const animationController = new AnimationController( newSublist, [ Animation.expand.height ] ); animationController.triggerAnimation(); } // Create & style the load more button if (this.request.areMore) { const loadMore = new ProgressButtonTemplate({ icon: await SVG.load('down'), color: ButtonColor.plain, text: 'Load More' }); loadMore.isWide = true; loadMore.hasPaddedTop = true; loadMore.loadInContext(this.userList); loadMore.delegate.didSetStateTo = async (button, state) => { await this.nextPage(true); button.removeFromContext(); } } return true; }
async nextPage(animated = true) { const users = await this.request.nextPage(); if (users.length === 0) return false; const subList = <ul class="user-item__sublist" />; // Load all items into a temporary list await Promise.all( users.map(async user => { const template = await new UserTemplate(user); template.loadInContext(subList); }) ); const newSublist = <li class="user-item__sublist_wrap">{ subList }</li>; this.userList.appendChild(newSublist); if (animated) { const animationController = new AnimationController( newSublist, [ Animation.expand.height ] ); animationController.triggerAnimation(); } // Create & style the load more button if (this.request.areMore) { const loadMore = new ProgressButtonTemplate({ icon: await SVG.load('down'), color: ButtonColor.plain, text: 'Load More' }); loadMore.isWide = true; loadMore.hasPaddedTop = true; loadMore.loadInContext(this.userList); loadMore.delegate.didSetStateTo = async (button, state) => { await this.nextPage(true); button.removeFromContext(); } } return true; }
JavaScript
untrigger(changesUpdated = false) { if (!this.isEditing) return; this.isEditing = false; this.isDisabled = false; this.editor.restoreOriginal(); if (changesUpdated) { Analytics.shared.report(EventType.answerEdited(this.answerController.answer)); } else { Analytics.shared.report(EventType.answerNotEdited(this.answerController.answer)); } EditAnswerViewController.activeEditInstance = null; }
untrigger(changesUpdated = false) { if (!this.isEditing) return; this.isEditing = false; this.isDisabled = false; this.editor.restoreOriginal(); if (changesUpdated) { Analytics.shared.report(EventType.answerEdited(this.answerController.answer)); } else { Analytics.shared.report(EventType.answerNotEdited(this.answerController.answer)); } EditAnswerViewController.activeEditInstance = null; }
JavaScript
registerObservable(key) { let removeHandler; return fromEventPattern( (listener) => { removeHandler = this.register(key, listener); }, () => { removeHandler() } ); }
registerObservable(key) { let removeHandler; return fromEventPattern( (listener) => { removeHandler = this.register(key, listener); }, () => { removeHandler() } ); }
JavaScript
toJSON() { const json = { id: this.id, text: this.text, parent: null, date: this.date, owner: this.owner, children: this.children && this.children.map(child => child.toJSON()) } return json; }
toJSON() { const json = { id: this.id, text: this.text, parent: null, date: this.date, owner: this.owner, children: this.children && this.children.map(child => child.toJSON()) } return json; }
JavaScript
present(modal) { if (this._context === null) this._createContext(); if (this._presenting) return false; this._setPresentee(modal); return true; }
present(modal) { if (this._context === null) this._createContext(); if (this._presenting) return false; this._setPresentee(modal); return true; }
JavaScript
function addSchema(schema) { const script = <script type="application/ld+json"/> script.text = JSON.stringify(schema); document.head.appendChild(script); }
function addSchema(schema) { const script = <script type="application/ld+json"/> script.text = JSON.stringify(schema); document.head.appendChild(script); }
JavaScript
async showCount(count) { this._countText.data = String(count); if (this._showingCount) return; this._showingCount = true; const anime = await import('animejs'); anime.timeline() .add({ targets: this._overlay, width: ['0%', '100%'], height: ['0%', '100%'], easing: 'easeOutElastic', elasticity: 300, duration: 700 }) .add({ targets: this._overlayText, fontSize: ['0em', '1em'], easing: 'easeOutElastic', elasticity: 600, duration: 1200, offset: 100 }); }
async showCount(count) { this._countText.data = String(count); if (this._showingCount) return; this._showingCount = true; const anime = await import('animejs'); anime.timeline() .add({ targets: this._overlay, width: ['0%', '100%'], height: ['0%', '100%'], easing: 'easeOutElastic', elasticity: 300, duration: 700 }) .add({ targets: this._overlayText, fontSize: ['0em', '1em'], easing: 'easeOutElastic', elasticity: 600, duration: 1200, offset: 100 }); }
JavaScript
async hideCount() { this._showingCount = false; const anime = await import('animejs'); anime.timeline() .add({ targets: this._overlayText, fontSize: 0, easing: 'easeInElastic', elasticity: 300, duration: 700 }) .add({ targets: this._overlay, width: 0, height: 0, easing: 'easeInElastic', elasticity: 600, duration: 900, offset: 0 }); }
async hideCount() { this._showingCount = false; const anime = await import('animejs'); anime.timeline() .add({ targets: this._overlayText, fontSize: 0, easing: 'easeInElastic', elasticity: 300, duration: 700 }) .add({ targets: this._overlay, width: 0, height: 0, easing: 'easeInElastic', elasticity: 600, duration: 900, offset: 0 }); }
JavaScript
static of(id) { let elem; if (elem = document.getElementById(id)) { return elem.controller || null; } else { return null; } }
static of(id) { let elem; if (elem = document.getElementById(id)) { return elem.controller || null; } else { return null; } }
JavaScript
serializer() { let serializer = new TIOSerializer(); serializer.addVariable('lang', this.language.tioId); serializer.addFile('.code.tio', this.code); serializer.addFile('.input.tio', ''); serializer.addVariable('args', []); serializer.addRun(); return serializer; }
serializer() { let serializer = new TIOSerializer(); serializer.addVariable('lang', this.language.tioId); serializer.addFile('.code.tio', this.code); serializer.addFile('.input.tio', ''); serializer.addVariable('args', []); serializer.addRun(); return serializer; }
JavaScript
async createCommentInstance(comment, type = InstanceType.prepend) { const commentContent = await new CommentTemplate(comment); const commentHTML = <li/>; commentContent.loadInContext(commentHTML); this.addInstance(commentHTML, type); return commentHTML; }
async createCommentInstance(comment, type = InstanceType.prepend) { const commentContent = await new CommentTemplate(comment); const commentHTML = <li/>; commentContent.loadInContext(commentHTML); this.addInstance(commentHTML, type); return commentHTML; }
JavaScript
addInstance(html, type) { const ref = InstanceType.getReference(type, this); this._node.insertBefore(html, ref); html.style.opacity = 0; // Wait for transition to finish, then change setTimeout(() => { html.style.opacity = 1 }, OPACITY_TRANSITION_DURATION); }
addInstance(html, type) { const ref = InstanceType.getReference(type, this); this._node.insertBefore(html, ref); html.style.opacity = 0; // Wait for transition to finish, then change setTimeout(() => { html.style.opacity = 1 }, OPACITY_TRANSITION_DURATION); }
JavaScript
imageForTheme(name, type = 'svg') { if (this.isDark) { return `${THEME_IMG_ROOT}/${name}-white.${type}`; } else { return `${THEME_IMG_ROOT}/${name}.${type}`; } }
imageForTheme(name, type = 'svg') { if (this.isDark) { return `${THEME_IMG_ROOT}/${name}-white.${type}`; } else { return `${THEME_IMG_ROOT}/${name}.${type}`; } }
JavaScript
toggleSection(section, isOpen) { this.animationQueue.add({ targets: section, easing: 'easeOutCubic', elasticity: 0, height: isOpen ? (section.scrollHeight || '100%') : '0', offset: 0, duration: 200, begin: () => section.classList.add(ACTIVE_SECTION_CLASS_NAME) }); }
toggleSection(section, isOpen) { this.animationQueue.add({ targets: section, easing: 'easeOutCubic', elasticity: 0, height: isOpen ? (section.scrollHeight || '100%') : '0', offset: 0, duration: 200, begin: () => section.classList.add(ACTIVE_SECTION_CLASS_NAME) }); }
JavaScript
addSubheader(template) { this._lastSubheader.classList.add('header--transparent'); this._lastSubheader.classList.remove('header--shadow'); const instance = template.loadBeforeContext(this._lastSubheader.nextSibling); instance.classList.add('header--shadow'); }
addSubheader(template) { this._lastSubheader.classList.add('header--transparent'); this._lastSubheader.classList.remove('header--shadow'); const instance = template.loadBeforeContext(this._lastSubheader.nextSibling); instance.classList.add('header--shadow'); }
JavaScript
async displayResults(results) { if (results === null) { this.resultContainer.restoreOriginal(); return; } const parent = <div class="search-list"/>, templates = []; let isAtLeastOneResult = false; for (const category of results.categories()) { if (!results.categoryHasResultsForCategory(category)) { continue; } isAtLeastOneResult = true; const template = new SearchCategoryTemplate(category, results); templates.push(...template.results); template.loadInContext(parent); } this.results = templates; this.resultIndex = -1; if (!isAtLeastOneResult) { parent.appendChild( <div class="search-overlay-base search-result__empty"> No results found </div> ); } this.resultContainer.displayAlternate(parent); }
async displayResults(results) { if (results === null) { this.resultContainer.restoreOriginal(); return; } const parent = <div class="search-list"/>, templates = []; let isAtLeastOneResult = false; for (const category of results.categories()) { if (!results.categoryHasResultsForCategory(category)) { continue; } isAtLeastOneResult = true; const template = new SearchCategoryTemplate(category, results); templates.push(...template.results); template.loadInContext(parent); } this.results = templates; this.resultIndex = -1; if (!isAtLeastOneResult) { parent.appendChild( <div class="search-overlay-base search-result__empty"> No results found </div> ); } this.resultContainer.displayAlternate(parent); }
JavaScript
report(...args) { ErrorList.push(this); console.error(`%c${this.idString}:%c ${this.message}`, 'font-weight: 700', '', ...args); console.log( `This error has been reported, your instance id is %c${Data.shared.dataId}%c.`, 'font-family: Menlo, "Fira Mono", monospace;', '' ); }
report(...args) { ErrorList.push(this); console.error(`%c${this.idString}:%c ${this.message}`, 'font-weight: 700', '', ...args); console.log( `This error has been reported, your instance id is %c${Data.shared.dataId}%c.`, 'font-family: Menlo, "Fira Mono", monospace;', '' ); }
JavaScript
report(error) { if (error instanceof AnyError) { Analytics.shared.reportError('error', error); error.report(); } else { this.unhandled(error); } }
report(error) { if (error instanceof AnyError) { Analytics.shared.reportError('error', error); error.report(); } else { this.unhandled(error); } }
JavaScript
dumpConsole() { console.log( `%cError Dump%c for instance (%c${Data.shared.dataId}%c):%c\n` + ErrorList.map( (error, indexNum) => { let index = String(indexNum); return `%c${indexNum + 1}. %c${error.idString}%c\n` + `%c${" ".repeat(index.length)} ${error.message}%c`; } ).join('\n'), 'font-size: 24px; font-weight: bold;', 'font-size: 24px;', 'font-size: 24px; font-weight: bold; text-decoration: underline', 'font-size: 24px;', '', ...[].concat(...ErrorList.map(_ => [ 'font-size: 16px;', 'color: red; font-weight: bold; font-size: 16px;', '', 'font-size: 14px;', '' ])) ); }
dumpConsole() { console.log( `%cError Dump%c for instance (%c${Data.shared.dataId}%c):%c\n` + ErrorList.map( (error, indexNum) => { let index = String(indexNum); return `%c${indexNum + 1}. %c${error.idString}%c\n` + `%c${" ".repeat(index.length)} ${error.message}%c`; } ).join('\n'), 'font-size: 24px; font-weight: bold;', 'font-size: 24px;', 'font-size: 24px; font-weight: bold; text-decoration: underline', 'font-size: 24px;', '', ...[].concat(...ErrorList.map(_ => [ 'font-size: 16px;', 'color: red; font-weight: bold; font-size: 16px;', '', 'font-size: 14px;', '' ])) ); }
JavaScript
report(eventType, label = null, id = null) { const eventObject = {}; if (eventType.value) { eventObject.value = eventType.value; } if (typeof label == 'number' || id) { eventObject.value = id || label; } if (typeof label == 'string') { eventObject.event_label = label; } Bugsnag?.leaveBreadcrumb(eventType.name, eventType.info || {}); eventObject.event_category = eventType.category; this.gtag?.('event', eventType.name, eventObject); }
report(eventType, label = null, id = null) { const eventObject = {}; if (eventType.value) { eventObject.value = eventType.value; } if (typeof label == 'number' || id) { eventObject.value = id || label; } if (typeof label == 'string') { eventObject.event_label = label; } Bugsnag?.leaveBreadcrumb(eventType.name, eventType.info || {}); eventObject.event_category = eventType.category; this.gtag?.('event', eventType.name, eventObject); }
JavaScript
reportTime(timingType, id) { let timingObject = Object.create(timingType); timingObject.value = id; this.gtag?.('event', 'timing_complete', timingObject); }
reportTime(timingType, id) { let timingObject = Object.create(timingType); timingObject.value = id; this.gtag?.('event', 'timing_complete', timingObject); }
JavaScript
static fromIndexJSON(json) { return new Post({ postId: json.id, title: json.title, body: json.body, slug: json.slug, owner: User.fromIndexJSON(json.author), dateCreated: new Date(json.date_created) }); }
static fromIndexJSON(json) { return new Post({ postId: json.id, title: json.title, body: json.body, slug: json.slug, owner: User.fromIndexJSON(json.author), dateCreated: new Date(json.date_created) }); }
JavaScript
checkIsDisabled(value) { if (this.answer.code === value) { this.saveButton.setIsDisabled(true, 'No changes to save.'); } else { this.saveButton.setIsDisabled(false); } }
checkIsDisabled(value) { if (this.answer.code === value) { this.saveButton.setIsDisabled(true, 'No changes to save.'); } else { this.saveButton.setIsDisabled(false); } }
JavaScript
async nuke() { this.isLoading = true; const request = new PublishNuke(this.item); const finalResult = await request.run(); await this.delegate.didSetStateTo(this, finalResult); this.isLoading = false; }
async nuke() { this.isLoading = true; const request = new PublishNuke(this.item); const finalResult = await request.run(); await this.delegate.didSetStateTo(this, finalResult); this.isLoading = false; }
JavaScript
addTag(name) { if (this._managedTags.has(name)) return; let close = CLOSE_ICON(); let label = <span class="input-list-item">{name}{close}</span> let input = <input type="hidden" name="post-categories" value={name} />; close.addEventListener('click', () => this.removeTag(name)); this._managingContext.insertBefore(label, this._typingContext); this._inputContext.appendChild(input); this._managedTags.set(name, { label, input, position: this._managingStack.length }); this._managingStack.push(name); }
addTag(name) { if (this._managedTags.has(name)) return; let close = CLOSE_ICON(); let label = <span class="input-list-item">{name}{close}</span> let input = <input type="hidden" name="post-categories" value={name} />; close.addEventListener('click', () => this.removeTag(name)); this._managingContext.insertBefore(label, this._typingContext); this._inputContext.appendChild(input); this._managedTags.set(name, { label, input, position: this._managingStack.length }); this._managingStack.push(name); }
JavaScript
removeTag(name) { let tag; if (tag = this._managedTags.get(name)) { let { label, input, position } = tag; // Remove from DOM this._managingContext.removeChild(label); // Remove from input list this._inputContext.removeChild(input); // Remove from managedTags this._managedTags.delete(name); // Remove from stack this._managingStack.splice(position, 1); } }
removeTag(name) { let tag; if (tag = this._managedTags.get(name)) { let { label, input, position } = tag; // Remove from DOM this._managingContext.removeChild(label); // Remove from input list this._inputContext.removeChild(input); // Remove from managedTags this._managedTags.delete(name); // Remove from stack this._managingStack.splice(position, 1); } }
JavaScript
static fromId(id, type = TemplateType.none) { return new Template( document.getElementById(id), type ); }
static fromId(id, type = TemplateType.none) { return new Template( document.getElementById(id), type ); }
JavaScript
unique() { switch (this._type) { case TemplateType.move: this._root.parentNode.removeChild(this._root); this._root.classList.remove('template'); this._type = TemplateType.none; return this._root; case TemplateType.clone: return this._root.cloneNode(true); default: return this._root; } }
unique() { switch (this._type) { case TemplateType.move: this._root.parentNode.removeChild(this._root); this._root.classList.remove('template'); this._type = TemplateType.none; return this._root; case TemplateType.clone: return this._root.cloneNode(true); default: return this._root; } }
JavaScript
removeFromContext() { this.willUnload(); this.underlyingNode.parentNode.removeChild(this.underlyingNode); this.didUnload(); }
removeFromContext() { this.willUnload(); this.underlyingNode.parentNode.removeChild(this.underlyingNode); this.didUnload(); }
JavaScript
didLoad() { if (this._hasLoaded === false) { this.didInitialLoad() .catch(HandleUnhandledPromise); } this._hasLoaded = true; }
didLoad() { if (this._hasLoaded === false) { this.didInitialLoad() .catch(HandleUnhandledPromise); } this._hasLoaded = true; }
JavaScript
willLoad() { if (this._hasLoaded === false) { this.willInitialLoad() .catch(HandleUnhandledPromise); } }
willLoad() { if (this._hasLoaded === false) { this.willInitialLoad() .catch(HandleUnhandledPromise); } }
JavaScript
loadInContext(parent, allowDuplicate = true) { if (!allowDuplicate && this._hasLoaded) return; let elem = this.unique(); this.willLoad(); parent.appendChild(elem); this.didLoad(); return elem; }
loadInContext(parent, allowDuplicate = true) { if (!allowDuplicate && this._hasLoaded) return; let elem = this.unique(); this.willLoad(); parent.appendChild(elem); this.didLoad(); return elem; }
JavaScript
prependInContext(parent, allowDuplicate = true) { if (!allowDuplicate && this._hasLoaded) return; let elem = this.unique(); this.willLoad(); parent.insertBefore(elem, parent.firstChild); this.didLoad(); return elem; }
prependInContext(parent, allowDuplicate = true) { if (!allowDuplicate && this._hasLoaded) return; let elem = this.unique(); this.willLoad(); parent.insertBefore(elem, parent.firstChild); this.didLoad(); return elem; }
JavaScript
loadBeforeContext(elem) { let instance = this.unique(); this.willLoad(); elem.parentNode.insertBefore(instance, elem); this.didLoad(); return instance; }
loadBeforeContext(elem) { let instance = this.unique(); this.willLoad(); elem.parentNode.insertBefore(instance, elem); this.didLoad(); return instance; }
JavaScript
bind(node, template) { if (typeof node === 'string') { node = document.getElementById(node); } if (node) { node.addEventListener('click', () => { this.present(template) .catch(HandleUnhandledPromise); }); } }
bind(node, template) { if (typeof node === 'string') { node = document.getElementById(node); } if (node) { node.addEventListener('click', () => { this.present(template) .catch(HandleUnhandledPromise); }); } }
JavaScript
async hide({ bumpAnimation = this._bumpAnimation } = {}) { if (!this._activeTemplate) return; this._activeTemplateModel.willUnload(); this._removeKeyHandler?.(); // Avoids race condition const instance = this._activeTemplate, template = this._activeTemplateModel; this._activeTemplate = null; this._activeTemplateModel = null; this._dim.removeEventListener('click', this._eventListener); const anime = await import('animejs'); this._dim.style.pointerEvents = 'none' const timeline = anime.timeline() .add({ targets: this._dim, opacity: [1, 0], backdropFilter: [`blur(${MODAL_BLUR_RADIUS})`, 'blur(0px)'], webkitBackdropFilter: [`blur(${MODAL_BLUR_RADIUS})`, 'blur(0px)'], elasticity: 0, duration: 300, offset: bumpAnimation ? 400 : 0 }); if (bumpAnimation) { timeline.add({ targets: instance, opacity: [1, 0], top: ['50%', '60%'], easing: 'easeInBack', offset: 0, duration: 500, elasticity: 0 }) } await timeline.finished; template.didUnload(); this.context.removeChild(this._dim); this._dim = null; }
async hide({ bumpAnimation = this._bumpAnimation } = {}) { if (!this._activeTemplate) return; this._activeTemplateModel.willUnload(); this._removeKeyHandler?.(); // Avoids race condition const instance = this._activeTemplate, template = this._activeTemplateModel; this._activeTemplate = null; this._activeTemplateModel = null; this._dim.removeEventListener('click', this._eventListener); const anime = await import('animejs'); this._dim.style.pointerEvents = 'none' const timeline = anime.timeline() .add({ targets: this._dim, opacity: [1, 0], backdropFilter: [`blur(${MODAL_BLUR_RADIUS})`, 'blur(0px)'], webkitBackdropFilter: [`blur(${MODAL_BLUR_RADIUS})`, 'blur(0px)'], elasticity: 0, duration: 300, offset: bumpAnimation ? 400 : 0 }); if (bumpAnimation) { timeline.add({ targets: instance, opacity: [1, 0], top: ['50%', '60%'], easing: 'easeInBack', offset: 0, duration: 500, elasticity: 0 }) } await timeline.finished; template.didUnload(); this.context.removeChild(this._dim); this._dim = null; }
JavaScript
set isDeleted(isDeleted) { if (this._deleted === isDeleted) return; this._deleted = isDeleted; // TODO: improve + add undo if (isDeleted) { this._body.parentNode.removeChild(this._body); } }
set isDeleted(isDeleted) { if (this._deleted === isDeleted) return; this._deleted = isDeleted; // TODO: improve + add undo if (isDeleted) { this._body.parentNode.removeChild(this._body); } }
JavaScript
triggerAnimation() { setTimeout(() => { this.delegate.didStartAnimation(this); if (this.untriggerTimeout) clearTimeout(this.untriggerTimeout); this.element.classList.add('template--active'); this.styles.forEach((value, style) => { this.element.style[style] = value(this.element); }); this.triggerTimeout = setTimeout(() => { this.triggerTimeout = null; this.styles.forEach((_, style) => { this.element.style[style] = ''; }); this.element.classList.add('template--finished'); this.delegate.didFinishAnimation(this); }, this.animationTime); }); }
triggerAnimation() { setTimeout(() => { this.delegate.didStartAnimation(this); if (this.untriggerTimeout) clearTimeout(this.untriggerTimeout); this.element.classList.add('template--active'); this.styles.forEach((value, style) => { this.element.style[style] = value(this.element); }); this.triggerTimeout = setTimeout(() => { this.triggerTimeout = null; this.styles.forEach((_, style) => { this.element.style[style] = ''; }); this.element.classList.add('template--finished'); this.delegate.didFinishAnimation(this); }, this.animationTime); }); }
JavaScript
addWidget(template, { id }) { const generatedId = this._widgetId(id, template.state); this._editor.replaceSelection(generatedId, "around"); var from = this._editor.getCursor("from"); var to = this._editor.getCursor("to"); const marker = this._editor.markText(from, to, { replacedWith: template.unique(), clearWhenEmpty: false }); const updateId = (newId, value) => { const pos = marker.find(); if (pos) { pos.from.ch += 1; pos.to.ch -= 1; this._editor.replaceRange(this._widgetId(newId, value), pos.from, pos.to); } } // Support values on ActionControllerDelegate if (template.delegate instanceof ActionControllerDelegate) { template.delegate.didSetStateTo = (template, state) => { this._editor.refresh(); updateId(id, state); }; } return { exists: () => { return !!marker.find(); }, updateId }; }
addWidget(template, { id }) { const generatedId = this._widgetId(id, template.state); this._editor.replaceSelection(generatedId, "around"); var from = this._editor.getCursor("from"); var to = this._editor.getCursor("to"); const marker = this._editor.markText(from, to, { replacedWith: template.unique(), clearWhenEmpty: false }); const updateId = (newId, value) => { const pos = marker.find(); if (pos) { pos.from.ch += 1; pos.to.ch -= 1; this._editor.replaceRange(this._widgetId(newId, value), pos.from, pos.to); } } // Support values on ActionControllerDelegate if (template.delegate instanceof ActionControllerDelegate) { template.delegate.didSetStateTo = (template, state) => { this._editor.refresh(); updateId(id, state); }; } return { exists: () => { return !!marker.find(); }, updateId }; }
JavaScript
nameForType(type) { let theme = this.themes[type]; if (typeof theme === 'undefined') ErrorManager.raise(`Invalid theme`, BadCodeEditorThemeType); return theme; }
nameForType(type) { let theme = this.themes[type]; if (typeof theme === 'undefined') ErrorManager.raise(`Invalid theme`, BadCodeEditorThemeType); return theme; }
JavaScript
static pipeValueTo(func) { return (controller, state) => { func(state); }; }
static pipeValueTo(func) { return (controller, state) => { func(state); }; }
JavaScript
async toggleState() { if (this._displayingWritingBox) { // Hide writing box Analytics.shared.report(EventType.commentWriteClose(this.owner)); this._writingBox.parentNode.replaceChild(this._node, this._writingBox); this._displayingWritingBox = false; // Remove Escape handler this._keyBinding?.(); this._keyBinding = null; // Removes the Ctrl+Enter handler this._submitHandler?.(); } else { // When we try to display box const auth = Auth.shared; if (!await auth.ensureLoggedIn()) return; Analytics.shared.report(EventType.commentWriteOpen(this.owner)); this._node.parentNode.replaceChild(this._writingBox, this._node); this._displayingWritingBox = true; this.commentText.input.userInput?.focus(); this._keyBinding = KeyManager.shared.register('Escape', () => { this.toggleState(); }); // Remove previous Ctrl+Enter handler.f this._submitHandler?.(); this._submitHandler = KeyManager.shared.registerMeta('Enter', () => { this.submitButton.trigger(); }); } }
async toggleState() { if (this._displayingWritingBox) { // Hide writing box Analytics.shared.report(EventType.commentWriteClose(this.owner)); this._writingBox.parentNode.replaceChild(this._node, this._writingBox); this._displayingWritingBox = false; // Remove Escape handler this._keyBinding?.(); this._keyBinding = null; // Removes the Ctrl+Enter handler this._submitHandler?.(); } else { // When we try to display box const auth = Auth.shared; if (!await auth.ensureLoggedIn()) return; Analytics.shared.report(EventType.commentWriteOpen(this.owner)); this._node.parentNode.replaceChild(this._writingBox, this._node); this._displayingWritingBox = true; this.commentText.input.userInput?.focus(); this._keyBinding = KeyManager.shared.register('Escape', () => { this.toggleState(); }); // Remove previous Ctrl+Enter handler.f this._submitHandler?.(); this._submitHandler = KeyManager.shared.registerMeta('Enter', () => { this.submitButton.trigger(); }); } }
JavaScript
formatResults(response) { const results = response.results; const resultMap = new Map(); let areMore = false; for (let i = 0; i < results.length; i++) { const indexName = results[i].index; const category = this.search.getCategoryFromFullName(indexName); let categoryHasMore = false; if (results[i].page < results[i].nbPages - 1) { areMore = true; categoryHasMore = true; } let formattedResults = []; for (let j = 0; j < results[i].hits.length; j++) { const formattedResult = this.search.formatResult(category, results[i].hits[j]); if (formattedResult !== null) { formattedResults.push(formattedResult); } } resultMap.set(category, { areMore: categoryHasMore, results: formattedResults }); } return new SearchResults(this.search, resultMap, areMore); }
formatResults(response) { const results = response.results; const resultMap = new Map(); let areMore = false; for (let i = 0; i < results.length; i++) { const indexName = results[i].index; const category = this.search.getCategoryFromFullName(indexName); let categoryHasMore = false; if (results[i].page < results[i].nbPages - 1) { areMore = true; categoryHasMore = true; } let formattedResults = []; for (let j = 0; j < results[i].hits.length; j++) { const formattedResult = this.search.formatResult(category, results[i].hits[j]); if (formattedResult !== null) { formattedResults.push(formattedResult); } } resultMap.set(category, { areMore: categoryHasMore, results: formattedResults }); } return new SearchResults(this.search, resultMap, areMore); }
JavaScript
get hasPermissions() { if (this.useAPN) { return global.safari.pushNotification.permission(this.webAPNId).permission === "granted"; } else if (this.usePush) { return Notification.permission === 'granted'; } else { return false; } }
get hasPermissions() { if (this.useAPN) { return global.safari.pushNotification.permission(this.webAPNId).permission === "granted"; } else if (this.usePush) { return Notification.permission === 'granted'; } else { return false; } }
JavaScript
requestPriviledge() { return new Promise(async (resolve, reject) => { // If we don't have permission then ¯\_(ツ)_/¯ if (this.denied) { return resolve(false) } if (this.useAPN) { if (!this.backendSupportsAPN) { alert("Axtell instance is not configured for APN"); return resolve(false); } const authorizationToken = await new WebAPNToken().run(); safari.pushNotification.requestPermission( this.apnURL, this.webAPNId, { token: authorizationToken }, ({ deviceToken, permission }) => { if (this.hasPermissions) { resolve(true); } else { resolve(false) }; } ) } else if (this.usePush) { const key = await new WebPushKey().run(); const serviceWorker = await ServiceWorker.global(); const registration = serviceWorker.registration; // Request permission const permission = await new Promise((resolve, reject) => { const promise = Notification.requestPermission(resolve); if (promise) promise.then(resolve, reject); }); if (!this.hasPermissions) resolve(false); const pushSubscription = await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: key }); // Submit to server const deviceId = await new WebPushNewDevice(pushSubscription).run(); resolve(true); } else { resolve(false); } }); }
requestPriviledge() { return new Promise(async (resolve, reject) => { // If we don't have permission then ¯\_(ツ)_/¯ if (this.denied) { return resolve(false) } if (this.useAPN) { if (!this.backendSupportsAPN) { alert("Axtell instance is not configured for APN"); return resolve(false); } const authorizationToken = await new WebAPNToken().run(); safari.pushNotification.requestPermission( this.apnURL, this.webAPNId, { token: authorizationToken }, ({ deviceToken, permission }) => { if (this.hasPermissions) { resolve(true); } else { resolve(false) }; } ) } else if (this.usePush) { const key = await new WebPushKey().run(); const serviceWorker = await ServiceWorker.global(); const registration = serviceWorker.registration; // Request permission const permission = await new Promise((resolve, reject) => { const promise = Notification.requestPermission(resolve); if (promise) promise.then(resolve, reject); }); if (!this.hasPermissions) resolve(false); const pushSubscription = await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: key }); // Submit to server const deviceId = await new WebPushNewDevice(pushSubscription).run(); resolve(true); } else { resolve(false); } }); }
JavaScript
async markRead() { if (this.markingRead) return; this.checkAll.controller.displayAlternate(this.loadingSign); this.markingRead = true; const NotificationStatus = await Notification.getStatuses(); const markNotificationStatus = new MarkNotificationStatus(this.notificationCategory, NotificationStatus.read); await markNotificationStatus.run(); for (const group of this.notificationGroupTemplates) { group.markedRead(); } this.markingRead = false; if (this.checkWrapper.parentNode) { this.checkWrapper.parentNode.removeChild(this.checkWrapper); } }
async markRead() { if (this.markingRead) return; this.checkAll.controller.displayAlternate(this.loadingSign); this.markingRead = true; const NotificationStatus = await Notification.getStatuses(); const markNotificationStatus = new MarkNotificationStatus(this.notificationCategory, NotificationStatus.read); await markNotificationStatus.run(); for (const group of this.notificationGroupTemplates) { group.markedRead(); } this.markingRead = false; if (this.checkWrapper.parentNode) { this.checkWrapper.parentNode.removeChild(this.checkWrapper); } }
JavaScript
appendLanguage(language) { let lang = new LanguageTemplate(language).loadInContext(this._list); this._langs.push(lang); return lang; }
appendLanguage(language) { let lang = new LanguageTemplate(language).loadInContext(this._list); this._langs.push(lang); return lang; }
JavaScript
clearList() { while (this._langs.length > 0) { let lang = this._langs.pop(); lang.parentNode.removeChild(lang); } }
clearList() { while (this._langs.length > 0) { let lang = this._langs.pop(); lang.parentNode.removeChild(lang); } }
JavaScript
watch(key, callback) { let lastDelta = localStorage.getItem(this._writeDelta(key)), keyValue; if (keyValue = this._watchingKeys.get(key)) { keyValue.lastDelta = lastDelta; keyValue.callbacks.push(callback); } else { this._watchingKeys.set(key, { lastDelta: lastDelta, callbacks: [callback], }); } let value = localStorage.getItem(this._writeKey(key)); if (value !== null) callback(value); }
watch(key, callback) { let lastDelta = localStorage.getItem(this._writeDelta(key)), keyValue; if (keyValue = this._watchingKeys.get(key)) { keyValue.lastDelta = lastDelta; keyValue.callbacks.push(callback); } else { this._watchingKeys.set(key, { lastDelta: lastDelta, callbacks: [callback], }); } let value = localStorage.getItem(this._writeKey(key)); if (value !== null) callback(value); }
JavaScript
tick() { let hasChangedKey = null; for (let [key, keyData] of this._watchingKeys) { let { lastDelta, callbacks } = keyData; let latestDelta = this.getDelta(key); // If the write time has elapsed they are relevant changes if (latestDelta - lastDelta > 0) { keyData.lastDelta = latestDelta; hasChangedKey = true; let value = localStorage.getItem(this._writeKey(key)); for (let i = 0; i < callbacks.length; i++) { callbacks[i](value); } } } if (hasChangedKey) { for (let i = 0; i < this._tickWatchers.length; i++) { this._tickWatchers[i](); } } }
tick() { let hasChangedKey = null; for (let [key, keyData] of this._watchingKeys) { let { lastDelta, callbacks } = keyData; let latestDelta = this.getDelta(key); // If the write time has elapsed they are relevant changes if (latestDelta - lastDelta > 0) { keyData.lastDelta = latestDelta; hasChangedKey = true; let value = localStorage.getItem(this._writeKey(key)); for (let i = 0; i < callbacks.length; i++) { callbacks[i](value); } } } if (hasChangedKey) { for (let i = 0; i < this._tickWatchers.length; i++) { this._tickWatchers[i](); } } }
JavaScript
validate(errors) { const erroredConstraints = errors .map(error => error.sourceValidator); for (const { template, constraintValidator } of this._constraints) { if (erroredConstraints.includes(constraintValidator)) { template.state = ConstraintState.Error; } else { template.state = ConstraintState.Done; } } this.validationDelegate.didSetStateTo(this, erroredConstraints.length === 0); }
validate(errors) { const erroredConstraints = errors .map(error => error.sourceValidator); for (const { template, constraintValidator } of this._constraints) { if (erroredConstraints.includes(constraintValidator)) { template.state = ConstraintState.Error; } else { template.state = ConstraintState.Done; } } this.validationDelegate.didSetStateTo(this, erroredConstraints.length === 0); }
JavaScript
foreignSynchronize(interactor, key, time = 70) { this.input.userInput.addEventListener('input', (event) => { interactor.queueKey(key, time, this.input.value); }); }
foreignSynchronize(interactor, key, time = 70) { this.input.userInput.addEventListener('input', (event) => { interactor.queueKey(key, time, this.input.value); }); }
JavaScript
didInvalidateState(event) { this._list.clearList(); let results = Language.query.find(this._input.value, 5); results.forEach(lang => { let langBox = this._list.appendLanguage(lang) langBox.addEventListener("click", () => { this.setLanguage(lang); }); }) }
didInvalidateState(event) { this._list.clearList(); let results = Language.query.find(this._input.value, 5); results.forEach(lang => { let langBox = this._list.appendLanguage(lang) langBox.addEventListener("click", () => { this.setLanguage(lang); }); }) }
JavaScript
bindTrigger(trigger) { if (typeof trigger === 'string') { trigger = document.getElementById(trigger); } trigger.addEventListener("click", () => { this.trigger(); }, false); }
bindTrigger(trigger) { if (typeof trigger === 'string') { trigger = document.getElementById(trigger); } trigger.addEventListener("click", () => { this.trigger(); }, false); }
JavaScript
bindUntrigger(untrigger) { if (typeof untrigger === 'string') { untrigger = document.getElementById(untrigger); } untrigger.addEventListener("click", () => { this.untrigger(); }, false); }
bindUntrigger(untrigger) { if (typeof untrigger === 'string') { untrigger = document.getElementById(untrigger); } untrigger.addEventListener("click", () => { this.untrigger(); }, false); }
JavaScript
static async all() { if (Encoding._codepages !== null) return Encoding._codepages; const encodingNames = await new Encodings().run(); let encodings = new Set(); for (const encodingName of encodingNames) { encodings.add(Encoding.fromName(encodingName)); } Encoding._codepages = new Set() return encodings; }
static async all() { if (Encoding._codepages !== null) return Encoding._codepages; const encodingNames = await new Encodings().run(); let encodings = new Set(); for (const encodingName of encodingNames) { encodings.add(Encoding.fromName(encodingName)); } Encoding._codepages = new Set() return encodings; }