language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | async clickSelectorId(selector, id) {
if (this.autoLog) log(`Clicking for a ${selector} matching ${id}`)
await this.page.evaluate(
(selector, id) => {
let matches = Array.from(document.querySelectorAll(selector))
let singleMatch = matches.find((button) => button.id === id)
let result
if (singleMatch && singleMatch.click) {
log('normal click')
result = singleMatch.click()
}
if (singleMatch && !singleMatch.click) {
log('on click')
result = singleMatch.dispatchEvent(new MouseEvent('click', { bubbles: true }))
}
if (!singleMatch) {
log('event click', matches.length)
if (matches.length > 0) {
const m = matches[0]
result = m.dispatchEvent(new MouseEvent('click', { bubbles: true }))
}
}
},
selector,
id
)
} | async clickSelectorId(selector, id) {
if (this.autoLog) log(`Clicking for a ${selector} matching ${id}`)
await this.page.evaluate(
(selector, id) => {
let matches = Array.from(document.querySelectorAll(selector))
let singleMatch = matches.find((button) => button.id === id)
let result
if (singleMatch && singleMatch.click) {
log('normal click')
result = singleMatch.click()
}
if (singleMatch && !singleMatch.click) {
log('on click')
result = singleMatch.dispatchEvent(new MouseEvent('click', { bubbles: true }))
}
if (!singleMatch) {
log('event click', matches.length)
if (matches.length > 0) {
const m = matches[0]
result = m.dispatchEvent(new MouseEvent('click', { bubbles: true }))
}
}
},
selector,
id
)
} |
JavaScript | async clickSelectorByAlt(selector, title) {
if (this.autoLog) log(`Clicking for a ${selector} matching ${title}`)
await this.page.evaluate((selector, title) => {
let matches = Array.from(document.querySelectorAll(selector))
let singleMatch = matches.find((btn) => btn.alt === title)
let result
if (singleMatch && singleMatch.click) {
log('normal click')
result = singleMatch.click()
}
if (singleMatch && !singleMatch.click) {
log('on click')
result = singleMatch.dispatchEvent(new MouseEvent('click', { bubbles: true }))
}
if (!singleMatch) {
log('event click', matches.length)
if (matches.length > 0) {
const m = matches[0]
result = m.dispatchEvent(new MouseEvent('click', { bubbles: true }))
}
}
}, selector, title)
} | async clickSelectorByAlt(selector, title) {
if (this.autoLog) log(`Clicking for a ${selector} matching ${title}`)
await this.page.evaluate((selector, title) => {
let matches = Array.from(document.querySelectorAll(selector))
let singleMatch = matches.find((btn) => btn.alt === title)
let result
if (singleMatch && singleMatch.click) {
log('normal click')
result = singleMatch.click()
}
if (singleMatch && !singleMatch.click) {
log('on click')
result = singleMatch.dispatchEvent(new MouseEvent('click', { bubbles: true }))
}
if (!singleMatch) {
log('event click', matches.length)
if (matches.length > 0) {
const m = matches[0]
result = m.dispatchEvent(new MouseEvent('click', { bubbles: true }))
}
}
}, selector, title)
} |
JavaScript | async clickSelectorFirstMatch(selector) {
if (this.autoLog)
log(`Clicking for first ${selector}`);
await this.page.evaluate((selector) => {
let matches = Array.from(document.querySelectorAll(selector));
let singleMatch = matches[0];
if (singleMatch)
singleMatch.click();
}, selector);
} | async clickSelectorFirstMatch(selector) {
if (this.autoLog)
log(`Clicking for first ${selector}`);
await this.page.evaluate((selector) => {
let matches = Array.from(document.querySelectorAll(selector));
let singleMatch = matches[0];
if (singleMatch)
singleMatch.click();
}, selector);
} |
JavaScript | async function initProfanityFilter() {
// TODO: remove punctuation from phrases and words before testing
badWords = (await database.instance.getBadWords()).toString().split("\n");
sensitiveWords = (await database.instance.getSensitiveWords()).toString().trim().split("\r\n");
sensitivePhrases = (await database.instance.getSensitivePhrases()).toString().split("\n");
leadingStatements = (await database.instance.getLeadingStatements()).toString().split("\n");
profanity.addWords(badWords);
} | async function initProfanityFilter() {
// TODO: remove punctuation from phrases and words before testing
badWords = (await database.instance.getBadWords()).toString().split("\n");
sensitiveWords = (await database.instance.getSensitiveWords()).toString().trim().split("\r\n");
sensitivePhrases = (await database.instance.getSensitivePhrases()).toString().split("\n");
leadingStatements = (await database.instance.getLeadingStatements()).toString().split("\n");
profanity.addWords(badWords);
} |
JavaScript | async function testIfIsToxic(text, threshold) {
if (customConfig.instance.get('hf_api_token')) {
const result = await makeModelRequest(text, "unitary/toxic-bert");
log(result);
result[0].forEach((sentence) => {
if (sentence.score > threshold) {
return true;
}
});
} else return false;
} | async function testIfIsToxic(text, threshold) {
if (customConfig.instance.get('hf_api_token')) {
const result = await makeModelRequest(text, "unitary/toxic-bert");
log(result);
result[0].forEach((sentence) => {
if (sentence.score > threshold) {
return true;
}
});
} else return false;
} |
JavaScript | async function validateESRB(agent, text, checkIfForEveryone) {
const { contentRating } = JSON.parse((await database.instance.getAgentsConfig(agent)).toString());
const ratings =
{
everyone: /(?:everyone|pending|rp|10)/i,
pending: /(?:everyone|pending|10)|/i,
teen: /(?:everyone|teen|pending|10)/i,
mature: /(?:everyone|teen|mature|pending|17|10)/i,
adult: /(?:everyone|teen|mature|adult|nr|pending|18|17|10)/i,
}
const ratingsShort =
{
everyone: /\b(?:e|e10|rp)\b/i,
pending: /\b(?:e|e10|e10|rp)|\b/i,
teen: /\b(?:e|e10|t|rp)\b/i,
mature: /\b(?:e|e10|t|m|p|rp)\b/i,
adult: /\b(?:e|e10|t|m|a|nr|rp|ao)\b/i,
}
var regex = ratings[checkIfForEveryone ? "everyone" : contentRating.toLowerCase()];
const matchedEasy = regex.test(text);
if (matchedEasy) {
return !matchedEasy;
}
var regexShort = ratingsShort[checkIfForEveryone ? "everyone" : contentRating.toLowerCase()];
return !regexShort.test(text.substring(0, 3));
} | async function validateESRB(agent, text, checkIfForEveryone) {
const { contentRating } = JSON.parse((await database.instance.getAgentsConfig(agent)).toString());
const ratings =
{
everyone: /(?:everyone|pending|rp|10)/i,
pending: /(?:everyone|pending|10)|/i,
teen: /(?:everyone|teen|pending|10)/i,
mature: /(?:everyone|teen|mature|pending|17|10)/i,
adult: /(?:everyone|teen|mature|adult|nr|pending|18|17|10)/i,
}
const ratingsShort =
{
everyone: /\b(?:e|e10|rp)\b/i,
pending: /\b(?:e|e10|e10|rp)|\b/i,
teen: /\b(?:e|e10|t|rp)\b/i,
mature: /\b(?:e|e10|t|m|p|rp)\b/i,
adult: /\b(?:e|e10|t|m|a|nr|rp|ao)\b/i,
}
var regex = ratings[checkIfForEveryone ? "everyone" : contentRating.toLowerCase()];
const matchedEasy = regex.test(text);
if (matchedEasy) {
return !matchedEasy;
}
var regexShort = ratingsShort[checkIfForEveryone ? "everyone" : contentRating.toLowerCase()];
return !regexShort.test(text.substring(0, 3));
} |
JavaScript | async function keywordExtractor(input, agent) {
const keywords = []
const res = keyword_extractor.extract(input, {
language: "english",
remove_digits: true,
return_changed_case: true,
remove_duplicates: true
});
if (keywords.length == []) {
return [];
}
const result = await makeModelRequest(input, "flair/pos-english");
const skw = await database.instance.getIgnoredKeywords(agent);
for (let i = 0; i < res.length; i++) {
for (let j = 0; j < result.length; j++) {
if (result[j].word === res[i]) {
if (skw.includes(res[i])) {
continue;
}
if (result[j].entity_group === 'NN' || result[j].entity_group === 'NNS') {
keywords.push(res[i]);
break;
}
}
}
}
if (keywords.length === 0) {
return [];
}
let totalLength = 0;
const respp = [];
for(let i = 0; i < keywords.length; i++) {
const weaviateResponse = await makeWeaviateRequest(keywords[i]);
if (weaviateResponse.Paragraph.length > 0) {
const sum = await makeModelRequest(weaviateResponse.Paragraph[0].content, "facebook/bart-large-cnn");
if (sum && sum.length > 0) {
totalLength += sum[0].summary_text.length;
if (totalLength > 1000) {
return keywords;
}
respp.push({ word: keywords[i], info: sum[0].summary_text });
}
}
}
return respp;
} | async function keywordExtractor(input, agent) {
const keywords = []
const res = keyword_extractor.extract(input, {
language: "english",
remove_digits: true,
return_changed_case: true,
remove_duplicates: true
});
if (keywords.length == []) {
return [];
}
const result = await makeModelRequest(input, "flair/pos-english");
const skw = await database.instance.getIgnoredKeywords(agent);
for (let i = 0; i < res.length; i++) {
for (let j = 0; j < result.length; j++) {
if (result[j].word === res[i]) {
if (skw.includes(res[i])) {
continue;
}
if (result[j].entity_group === 'NN' || result[j].entity_group === 'NNS') {
keywords.push(res[i]);
break;
}
}
}
}
if (keywords.length === 0) {
return [];
}
let totalLength = 0;
const respp = [];
for(let i = 0; i < keywords.length; i++) {
const weaviateResponse = await makeWeaviateRequest(keywords[i]);
if (weaviateResponse.Paragraph.length > 0) {
const sum = await makeModelRequest(weaviateResponse.Paragraph[0].content, "facebook/bart-large-cnn");
if (sum && sum.length > 0) {
totalLength += sum[0].summary_text.length;
if (totalLength > 1000) {
return keywords;
}
respp.push({ word: keywords[i], info: sum[0].summary_text });
}
}
}
return respp;
} |
JavaScript | function detectOsOption() {
const os = getOS();
const options = {executablePath: null};
let chromePath = '';
switch (os) {
case 'Mac OS':
chromePath = '/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome';
break;
case 'Windows':
chromePath = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe';
break;
case 'Linux':
chromePath = '/usr/bin/google-chrome';
break;
default:
break;
}
if (chromePath) {
if (existsSync(chromePath)) {
options.executablePath = chromePath;
}
else {
warn("Warning! Please install Google Chrome to make bot workiing correctly in headless mode.\n");
}
}
return options;
} | function detectOsOption() {
const os = getOS();
const options = {executablePath: null};
let chromePath = '';
switch (os) {
case 'Mac OS':
chromePath = '/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome';
break;
case 'Windows':
chromePath = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe';
break;
case 'Linux':
chromePath = '/usr/bin/google-chrome';
break;
default:
break;
}
if (chromePath) {
if (existsSync(chromePath)) {
options.executablePath = chromePath;
}
else {
warn("Warning! Please install Google Chrome to make bot workiing correctly in headless mode.\n");
}
}
return options;
} |
JavaScript | async function createWikipediaAgent(speaker, name, personality, facts) {
try {
let start = Date.now()
//gets the info from the wikipedia article, if the agent name can't be found it returns null, in order to send the default agent
let out = null;
try {
out = await searchWikipedia(name);
} catch (e) {
error(e);
return null;
}
let stop = Date.now()
log(`Time Taken to execute loaded data from wikipedia = ${(stop - start)/1000} seconds`);
start = Date.now()
//const type = await namedEntityRecognition(out.result.title);
// create a constant called name which uses the value of nameRaw but removes all punctuation
// const name = nameRaw.replace(/[^\w\s]/gi, '');
log("out is ", out);
if (out.result.extract == "" || out.result.extract == null) {
return log("Error, couldn't find anything on wikiedia about " + name);
}
const factSourcePrompt = `The following are facts about ${name}\n`;
const factPrompt = factSourcePrompt + out.result.extract + "\n" + facts;
const personalitySourcePrompt = `Based on the above facts, the following is a description of the personality of an anthropomorphized ${name}:`;
database.instance.setDefaultEthics(name);
database.instance.setDefaultNeedsAndMotivations(name);
stop = Date.now()
log(`Time Taken to execute save data = ${(stop - start)/1000} seconds`);
start = Date.now()
let data = {
"prompt": factPrompt + "\n" + personalitySourcePrompt,
"temperature": 0.9,
"max_tokens": 300,
"top_p": 1,
"frequency_penalty": 0.0,
"presence_penalty": 0.0,
"stop": ["\"\"\"", `${speaker}:`, '\n']
};
let res = await makeCompletionRequest(data, speaker, name, "personality_generation", "davinci", false);
stop = Date.now()
log(`Time Taken to execute openai request = ${(stop - start)/1000} seconds`);
start = Date.now()
if (!res.success) {
log("Error: Failed to generate personality, check GPT3 keys");
return undefined;
}
log("res.choice.text")
log(res);
database.instance.setPersonality(name, personalitySourcePrompt + '\n' + personality + '\n' + res.choice.text);
const dialogPrompt = `The following is a conversation with ${name}. ${name} is helpful, knowledgeable and very friendly\n${speaker}: Hi there, ${name}! Can you tell me a little bit about yourself?\n${name}:`;
data = {
"prompt": factPrompt + "\n" + personalitySourcePrompt + "\n" + res + "\n" + dialogPrompt,
"temperature": 0.9,
"max_tokens": 300,
"top_p": 1,
"frequency_penalty": 0.0,
"presence_penalty": 0.0,
"stop": ["\"\"\"", `${speaker}:`, '\n']
};
res = makeCompletionRequest(data, speaker, name, "dialog_generation", "davinci", false);
stop = Date.now()
log(`Time Taken to execute openai request 2 = ${(stop - start)/1000} seconds`);
start = Date.now()
log("res.choice.text (2)")
log(res);
database.instance.setDialogue(name, dialogPrompt + (await res).choice?.text);
database.instance.setAgentFacts(name, factPrompt);
database.instance.setAgentExists(name);
stop = Date.now()
log(`Time Taken to execute save data = ${(stop - start)/1000} seconds`);
start = Date.now()
return out;
} catch (err) {
error(err);
}
return {}
} | async function createWikipediaAgent(speaker, name, personality, facts) {
try {
let start = Date.now()
//gets the info from the wikipedia article, if the agent name can't be found it returns null, in order to send the default agent
let out = null;
try {
out = await searchWikipedia(name);
} catch (e) {
error(e);
return null;
}
let stop = Date.now()
log(`Time Taken to execute loaded data from wikipedia = ${(stop - start)/1000} seconds`);
start = Date.now()
//const type = await namedEntityRecognition(out.result.title);
// create a constant called name which uses the value of nameRaw but removes all punctuation
// const name = nameRaw.replace(/[^\w\s]/gi, '');
log("out is ", out);
if (out.result.extract == "" || out.result.extract == null) {
return log("Error, couldn't find anything on wikiedia about " + name);
}
const factSourcePrompt = `The following are facts about ${name}\n`;
const factPrompt = factSourcePrompt + out.result.extract + "\n" + facts;
const personalitySourcePrompt = `Based on the above facts, the following is a description of the personality of an anthropomorphized ${name}:`;
database.instance.setDefaultEthics(name);
database.instance.setDefaultNeedsAndMotivations(name);
stop = Date.now()
log(`Time Taken to execute save data = ${(stop - start)/1000} seconds`);
start = Date.now()
let data = {
"prompt": factPrompt + "\n" + personalitySourcePrompt,
"temperature": 0.9,
"max_tokens": 300,
"top_p": 1,
"frequency_penalty": 0.0,
"presence_penalty": 0.0,
"stop": ["\"\"\"", `${speaker}:`, '\n']
};
let res = await makeCompletionRequest(data, speaker, name, "personality_generation", "davinci", false);
stop = Date.now()
log(`Time Taken to execute openai request = ${(stop - start)/1000} seconds`);
start = Date.now()
if (!res.success) {
log("Error: Failed to generate personality, check GPT3 keys");
return undefined;
}
log("res.choice.text")
log(res);
database.instance.setPersonality(name, personalitySourcePrompt + '\n' + personality + '\n' + res.choice.text);
const dialogPrompt = `The following is a conversation with ${name}. ${name} is helpful, knowledgeable and very friendly\n${speaker}: Hi there, ${name}! Can you tell me a little bit about yourself?\n${name}:`;
data = {
"prompt": factPrompt + "\n" + personalitySourcePrompt + "\n" + res + "\n" + dialogPrompt,
"temperature": 0.9,
"max_tokens": 300,
"top_p": 1,
"frequency_penalty": 0.0,
"presence_penalty": 0.0,
"stop": ["\"\"\"", `${speaker}:`, '\n']
};
res = makeCompletionRequest(data, speaker, name, "dialog_generation", "davinci", false);
stop = Date.now()
log(`Time Taken to execute openai request 2 = ${(stop - start)/1000} seconds`);
start = Date.now()
log("res.choice.text (2)")
log(res);
database.instance.setDialogue(name, dialogPrompt + (await res).choice?.text);
database.instance.setAgentFacts(name, factPrompt);
database.instance.setAgentExists(name);
stop = Date.now()
log(`Time Taken to execute save data = ${(stop - start)/1000} seconds`);
start = Date.now()
return out;
} catch (err) {
error(err);
}
return {}
} |
JavaScript | isUserBanned(user_id, client) {
for(let x in this.bannedUsers) {
log(x + ' - ' + this.bannedUsers[x].user_id + ' - ' + user_id + ' - ' + (this.bannedUsers[x].user_id === user_id))
if (this.bannedUsers[x].user_id === user_id && this.bannedUsers[x].client === client) {
return true
}
}
return false
} | isUserBanned(user_id, client) {
for(let x in this.bannedUsers) {
log(x + ' - ' + this.bannedUsers[x].user_id + ' - ' + user_id + ' - ' + (this.bannedUsers[x].user_id === user_id))
if (this.bannedUsers[x].user_id === user_id && this.bannedUsers[x].client === client) {
return true
}
}
return false
} |
JavaScript | async readConfig() {
const configs = {}
const query = 'SELECT * FROM config';
const rows = await this.client.query(query);
if (rows && rows.rows && rows.rows.length > 0) {
for (let i = 0; i < rows.rows.length; i++) {
configs[rows.rows[i]._key] = rows.rows[i]._value;
}
}
new customConfig(configs);
} | async readConfig() {
const configs = {}
const query = 'SELECT * FROM config';
const rows = await this.client.query(query);
if (rows && rows.rows && rows.rows.length > 0) {
for (let i = 0; i < rows.rows.length; i++) {
configs[rows.rows[i]._key] = rows.rows[i]._value;
}
}
new customConfig(configs);
} |
JavaScript | async catchAndScreenShot(fn, path = "botError.png") {
try {
await fn()
}
catch (e) {
if (this.page) {
warn("Caught error. Trying to screenshot")
this.page.screenshot({ path })
}
error(e);
}
} | async catchAndScreenShot(fn, path = "botError.png") {
try {
await fn()
}
catch (e) {
if (this.page) {
warn("Caught error. Trying to screenshot")
this.page.screenshot({ path })
}
error(e);
}
} |
JavaScript | exec(fn) {
this.catchAndScreenShot(() => fn(this)).catch((e) => {
error("Failed to run. Check botError.png if it exists. Error:", e)
})
} | exec(fn) {
this.catchAndScreenShot(() => fn(this)).catch((e) => {
error("Failed to run. Check botError.png if it exists. Error:", e)
})
} |
JavaScript | async launchBrowser() {
log('Launching browser');
const options = {
headless: this.headless,
ignoreHTTPSErrors: true,
args: [
"--disable-gpu",
"--use-fake-ui-for-media-stream=1",
"--use-fake-device-for-media-stream=1",
`--use-file-for-fake-video-capture=${this.fakeMediaPath}/video.y4m`,
`--use-file-for-fake-audio-capture=${this.fakeMediaPath}/audio.wav`,
'--disable-web-security=1',
// '--use-fake-device-for-media-stream',
// '--use-file-for-fake-video-capture=/Users/apple/Downloads/football_qcif_15fps.y4m',
// // '--use-file-for-fake-audio-capture=/Users/apple/Downloads/BabyElephantWalk60.wav',
'--allow-file-access=1',
],
ignoreDefaultArgs: ['--mute-audio'],
...detectOsOption()
};
this.browser = await browserWindow(options);
this.page = await this.browser.newPage();
this.page.on('console', message => {
if (message.text().startsWith('scene_metadata')) {
const data = message.text().split('|', 2)
if (data.length === 2) {
const _data = data[1]
log(`Scene Metadata: Data:${_data}`)
// TODO: Replace me with metadata handler
// MessageClient.instance.sendMetadata('xr-engine', 'xr-engine', 'xr-engine', data || 'none')
}
else
log(`invalid scene metadata length (${data.length}): ${data}`)
}
else if (message.text().startsWith('metadata')) {
const data = message.text().split('|', 3)
if (data.length === 3) {
const xyz = data[1]
const _data = data[2]
log(`Metadata: Position: ${xyz}, Data: ${_data}`)
}
else
log(`invalid metadata length ${data.length}: ${data}`)
}
else if (message.text().startsWith('players|')) {
const cmd = message.text().split('|')[0]
const data = message.text().substring(cmd.length + 1)
log(`Players: ${data}`)
}
else if (message.text().startsWith('messages|')) {
const cmd = message.text().split('|')[0]
const data = message.text().substring(cmd.length + 1)
log(`Messages: ${data}`)
}
else if (message.text().startsWith('proximity|')) {
const data = message.text().split('|')
//log('Proximity Data: ' + data)
if (data.length === 4) {
const mode = data[1]
const player = data[2]
const value = data[3]
if (value === 'left') {
if (mode == 'inRange') {
UsersInRange[player] = undefined
} else if (mode == 'intimate') {
UsersInIntimateRange[player] = undefined
} else if (mode == 'harassment') {
UsersInHarassmentRange[player] = undefined
} else if (mode == 'lookAt') {
UsersLookingAt[player] = undefined
}
} else {
if (mode == 'inRange') {
UsersInRange[player] = value
} else if (mode == 'intimate') {
UsersInIntimateRange[player] = value
} else if (mode == 'harassment') {
UsersInHarassmentRange[player] = value
} else if (mode == 'lookAt') {
UsersLookingAt[player] = value
}
}
}
}
else if (message.text().startsWith('localId|')) {
const cmd = message.text().split('|')[0]
const data = message.text().substring(cmd.length + 1)
log('local user id: ' + data)
if (data !== undefined && data !== '') {
this.userId = data
}
}
else if (message.text().startsWith('emotions|')) {
}
if (this.autoLog)
log(">> ", message.text())
})
this.page.setViewport({ width: 0, height: 0 });
await this.page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36')
this.pu = new PageUtils(this);
} | async launchBrowser() {
log('Launching browser');
const options = {
headless: this.headless,
ignoreHTTPSErrors: true,
args: [
"--disable-gpu",
"--use-fake-ui-for-media-stream=1",
"--use-fake-device-for-media-stream=1",
`--use-file-for-fake-video-capture=${this.fakeMediaPath}/video.y4m`,
`--use-file-for-fake-audio-capture=${this.fakeMediaPath}/audio.wav`,
'--disable-web-security=1',
// '--use-fake-device-for-media-stream',
// '--use-file-for-fake-video-capture=/Users/apple/Downloads/football_qcif_15fps.y4m',
// // '--use-file-for-fake-audio-capture=/Users/apple/Downloads/BabyElephantWalk60.wav',
'--allow-file-access=1',
],
ignoreDefaultArgs: ['--mute-audio'],
...detectOsOption()
};
this.browser = await browserWindow(options);
this.page = await this.browser.newPage();
this.page.on('console', message => {
if (message.text().startsWith('scene_metadata')) {
const data = message.text().split('|', 2)
if (data.length === 2) {
const _data = data[1]
log(`Scene Metadata: Data:${_data}`)
// TODO: Replace me with metadata handler
// MessageClient.instance.sendMetadata('xr-engine', 'xr-engine', 'xr-engine', data || 'none')
}
else
log(`invalid scene metadata length (${data.length}): ${data}`)
}
else if (message.text().startsWith('metadata')) {
const data = message.text().split('|', 3)
if (data.length === 3) {
const xyz = data[1]
const _data = data[2]
log(`Metadata: Position: ${xyz}, Data: ${_data}`)
}
else
log(`invalid metadata length ${data.length}: ${data}`)
}
else if (message.text().startsWith('players|')) {
const cmd = message.text().split('|')[0]
const data = message.text().substring(cmd.length + 1)
log(`Players: ${data}`)
}
else if (message.text().startsWith('messages|')) {
const cmd = message.text().split('|')[0]
const data = message.text().substring(cmd.length + 1)
log(`Messages: ${data}`)
}
else if (message.text().startsWith('proximity|')) {
const data = message.text().split('|')
//log('Proximity Data: ' + data)
if (data.length === 4) {
const mode = data[1]
const player = data[2]
const value = data[3]
if (value === 'left') {
if (mode == 'inRange') {
UsersInRange[player] = undefined
} else if (mode == 'intimate') {
UsersInIntimateRange[player] = undefined
} else if (mode == 'harassment') {
UsersInHarassmentRange[player] = undefined
} else if (mode == 'lookAt') {
UsersLookingAt[player] = undefined
}
} else {
if (mode == 'inRange') {
UsersInRange[player] = value
} else if (mode == 'intimate') {
UsersInIntimateRange[player] = value
} else if (mode == 'harassment') {
UsersInHarassmentRange[player] = value
} else if (mode == 'lookAt') {
UsersLookingAt[player] = value
}
}
}
}
else if (message.text().startsWith('localId|')) {
const cmd = message.text().split('|')[0]
const data = message.text().substring(cmd.length + 1)
log('local user id: ' + data)
if (data !== undefined && data !== '') {
this.userId = data
}
}
else if (message.text().startsWith('emotions|')) {
}
if (this.autoLog)
log(">> ", message.text())
})
this.page.setViewport({ width: 0, height: 0 });
await this.page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36')
this.pu = new PageUtils(this);
} |
JavaScript | async enterRoom(roomUrl, { name = 'bot' } = {}) {
await this.navigate(roomUrl);
await this.page.waitForSelector("div[class*=\"instance-chat-container\"]", { timeout: 100000 });
if (name) {
this.name = name
}
else {
name = this.name
}
this.username_regex = new RegExp(customConfig.instance.get('botName'), 'ig')
if (this.headless) {
// Disable rendering for headless, otherwise chromium uses a LOT of CPU
}
//@ts-ignore
if (this.setName != null) this.setName(name)
await this.page.mouse.click(0, 0);
await this.delay(10000)
await this.getUser()
await this.updateChannelState()
await this.updateUsername(name)
await this.delay(10000)
const index = this.getRandomNumber(0, this.avatars.length - 1)
log(`avatar index: ${index}`)
await this.updateAvatar(this.avatars[index])
await this.requestPlayers()
await this.getUser()
await setInterval(() => this.getUser(), 1000)
} | async enterRoom(roomUrl, { name = 'bot' } = {}) {
await this.navigate(roomUrl);
await this.page.waitForSelector("div[class*=\"instance-chat-container\"]", { timeout: 100000 });
if (name) {
this.name = name
}
else {
name = this.name
}
this.username_regex = new RegExp(customConfig.instance.get('botName'), 'ig')
if (this.headless) {
// Disable rendering for headless, otherwise chromium uses a LOT of CPU
}
//@ts-ignore
if (this.setName != null) this.setName(name)
await this.page.mouse.click(0, 0);
await this.delay(10000)
await this.getUser()
await this.updateChannelState()
await this.updateUsername(name)
await this.delay(10000)
const index = this.getRandomNumber(0, this.avatars.length - 1)
log(`avatar index: ${index}`)
await this.updateAvatar(this.avatars[index])
await this.requestPlayers()
await this.getUser()
await setInterval(() => this.getUser(), 1000)
} |
JavaScript | async function handleRequest(request) {
if (request.url.endsWith("/links")) {
return new Response(JSON.stringify(links_arr), {
headers: { 'content-type': 'application/json' },
})}
else{
const staticLink = "https://static-links-page.signalnerve.workers.dev"
const response = await fetch(staticLink, {
headers: { 'content-type': 'text/html' },
})
return htmlrewriter.transform(response)
}
} | async function handleRequest(request) {
if (request.url.endsWith("/links")) {
return new Response(JSON.stringify(links_arr), {
headers: { 'content-type': 'application/json' },
})}
else{
const staticLink = "https://static-links-page.signalnerve.workers.dev"
const response = await fetch(staticLink, {
headers: { 'content-type': 'text/html' },
})
return htmlrewriter.transform(response)
}
} |
JavaScript | function createCol(key, title = toTitle(key), width = 80, proj, format=true) {
return {
key: key,
title: title,
createCell: ({ rowData }) => ({
type: "text",
value: valueFunction(rowData, key, proj, format)
}),
sortable: true,
width: width,
weight: 0,
alignment: "left"
};
} | function createCol(key, title = toTitle(key), width = 80, proj, format=true) {
return {
key: key,
title: title,
createCell: ({ rowData }) => ({
type: "text",
value: valueFunction(rowData, key, proj, format)
}),
sortable: true,
width: width,
weight: 0,
alignment: "left"
};
} |
JavaScript | function Result(processor, root, opts) {
/**
* The Processor instance used for this transformation.
*
* @type {Processor}
*
* @example
* for (const plugin of result.processor.plugins) {
* if (plugin.postcssPlugin === 'postcss-bad') {
* throw 'postcss-good is incompatible with postcss-bad'
* }
* })
*/
this.processor = processor;
/**
* Contains messages from plugins (e.g., warnings or custom messages).
* Each message should have type and plugin properties.
*
* @type {Message[]}
*
* @example
* postcss.plugin('postcss-min-browser', () => {
* return (root, result) => {
* const browsers = detectMinBrowsersByCanIUse(root)
* result.messages.push({
* type: 'min-browser',
* plugin: 'postcss-min-browser',
* browsers
* })
* }
* })
*/
this.messages = [];
/**
* Root node after all transformations.
*
* @type {Root}
*
* @example
* root.toResult().root === root
*/
this.root = root;
/**
* Options from the {@link Processor#process} or {@link Root#toResult} call
* that produced this Result instance.
*
* @type {processOptions}
*
* @example
* root.toResult(opts).opts === opts
*/
this.opts = opts;
/**
* A CSS string representing of {@link Result#root}.
*
* @type {string}
*
* @example
* postcss.parse('a{}').toResult().css //=> "a{}"
*/
this.css = undefined;
/**
* An instance of `SourceMapGenerator` class from the `source-map` library,
* representing changes to the {@link Result#root} instance.
*
* @type {SourceMapGenerator}
*
* @example
* result.map.toJSON() //=> { version: 3, file: 'a.css', … }
*
* @example
* if (result.map) {
* fs.writeFileSync(result.opts.to + '.map', result.map.toString())
* }
*/
this.map = undefined;
} | function Result(processor, root, opts) {
/**
* The Processor instance used for this transformation.
*
* @type {Processor}
*
* @example
* for (const plugin of result.processor.plugins) {
* if (plugin.postcssPlugin === 'postcss-bad') {
* throw 'postcss-good is incompatible with postcss-bad'
* }
* })
*/
this.processor = processor;
/**
* Contains messages from plugins (e.g., warnings or custom messages).
* Each message should have type and plugin properties.
*
* @type {Message[]}
*
* @example
* postcss.plugin('postcss-min-browser', () => {
* return (root, result) => {
* const browsers = detectMinBrowsersByCanIUse(root)
* result.messages.push({
* type: 'min-browser',
* plugin: 'postcss-min-browser',
* browsers
* })
* }
* })
*/
this.messages = [];
/**
* Root node after all transformations.
*
* @type {Root}
*
* @example
* root.toResult().root === root
*/
this.root = root;
/**
* Options from the {@link Processor#process} or {@link Root#toResult} call
* that produced this Result instance.
*
* @type {processOptions}
*
* @example
* root.toResult(opts).opts === opts
*/
this.opts = opts;
/**
* A CSS string representing of {@link Result#root}.
*
* @type {string}
*
* @example
* postcss.parse('a{}').toResult().css //=> "a{}"
*/
this.css = undefined;
/**
* An instance of `SourceMapGenerator` class from the `source-map` library,
* representing changes to the {@link Result#root} instance.
*
* @type {SourceMapGenerator}
*
* @example
* result.map.toJSON() //=> { version: 3, file: 'a.css', … }
*
* @example
* if (result.map) {
* fs.writeFileSync(result.opts.to + '.map', result.map.toString())
* }
*/
this.map = undefined;
} |
JavaScript | function prefix(prop) {
var match = prop.match(/^(-\w+-)/);
if (match) {
return match[0];
}
return '';
} | function prefix(prop) {
var match = prop.match(/^(-\w+-)/);
if (match) {
return match[0];
}
return '';
} |
JavaScript | function updateData(timePassed) {
const newData = data.get('data')
const index = newData.length - 1
// Mutate the object
newData[index] = {
day: ISODate,
value: newData[index].value + timePassed,
streak: newData[index].streak + 1
}
// Save it
data.set('data', newData)
} | function updateData(timePassed) {
const newData = data.get('data')
const index = newData.length - 1
// Mutate the object
newData[index] = {
day: ISODate,
value: newData[index].value + timePassed,
streak: newData[index].streak + 1
}
// Save it
data.set('data', newData)
} |
JavaScript | function fillEmptyDates(entries) {
// Check for potential empty dates
const lastEntry = entries[entries.length - 2].day
// Yesterday because today already exists with `setNewKey()`
const date = new Date()
date.setDate(date.getDate() - 1)
const [yesterday] = date.toISOString().split('T')
// Cancel if no empty dates
if (yesterday === lastEntry) return
const firstDate = entries[0].day
const lastDate = entries[entries.length - 1].day
const dates = [
...Array(
Date.parse(lastDate) / 86400000 - Date.parse(firstDate) / 86400000 + 1
).keys()
].map(
k =>
new Date(86400000 * k + Date.parse(firstDate)).toISOString().split('T')[0]
)
const result = []
for (let i = 0, j = 0; i < dates.length; i++) {
let hasSameKey = false
if (dates[i] === entries[j].day) hasSameKey = true
result[i] = {
day: dates[i],
value: hasSameKey ? entries[j].value : 0,
streak: hasSameKey ? entries[j].streak : 0
}
if (hasSameKey) j++
}
data.set('data', result)
// Update the last index
const newIndex = result.length - 1
config.set('lastTimeUpdated.index', newIndex)
} | function fillEmptyDates(entries) {
// Check for potential empty dates
const lastEntry = entries[entries.length - 2].day
// Yesterday because today already exists with `setNewKey()`
const date = new Date()
date.setDate(date.getDate() - 1)
const [yesterday] = date.toISOString().split('T')
// Cancel if no empty dates
if (yesterday === lastEntry) return
const firstDate = entries[0].day
const lastDate = entries[entries.length - 1].day
const dates = [
...Array(
Date.parse(lastDate) / 86400000 - Date.parse(firstDate) / 86400000 + 1
).keys()
].map(
k =>
new Date(86400000 * k + Date.parse(firstDate)).toISOString().split('T')[0]
)
const result = []
for (let i = 0, j = 0; i < dates.length; i++) {
let hasSameKey = false
if (dates[i] === entries[j].day) hasSameKey = true
result[i] = {
day: dates[i],
value: hasSameKey ? entries[j].value : 0,
streak: hasSameKey ? entries[j].streak : 0
}
if (hasSameKey) j++
}
data.set('data', result)
// Update the last index
const newIndex = result.length - 1
config.set('lastTimeUpdated.index', newIndex)
} |
JavaScript | function mapStateToProps(state) {
return {
diagramWidth: window.innerWidth * (1 - state.draw.artboard.width),
artboardWidth: window.innerWidth * state.draw.artboard.width,
editId: state.draw.diagram.editObject.id,
mode: state.draw.diagram.mode,
};
} | function mapStateToProps(state) {
return {
diagramWidth: window.innerWidth * (1 - state.draw.artboard.width),
artboardWidth: window.innerWidth * state.draw.artboard.width,
editId: state.draw.diagram.editObject.id,
mode: state.draw.diagram.mode,
};
} |
JavaScript | function mapDispatchToProps(dispatch) {
return bindActionCreators({
setEditObject,
setLabel,
}, dispatch);
} | function mapDispatchToProps(dispatch) {
return bindActionCreators({
setEditObject,
setLabel,
}, dispatch);
} |
JavaScript | function mapStateToProps(state) {
return {
location: state.routing.locationBeforeTransitions.pathname.split('/').pop(),
};
} | function mapStateToProps(state) {
return {
location: state.routing.locationBeforeTransitions.pathname.split('/').pop(),
};
} |
JavaScript | function mapDispatchToProps(dispatch) {
return bindActionCreators({
setUser,
setDevice,
}, dispatch);
} | function mapDispatchToProps(dispatch) {
return bindActionCreators({
setUser,
setDevice,
}, dispatch);
} |
JavaScript | function mapStateToProps(state) {
console.log(state);
return {
imageUrl: state.train.imageUrl,
};
} | function mapStateToProps(state) {
console.log(state);
return {
imageUrl: state.train.imageUrl,
};
} |
JavaScript | function mapDispatchToProps(dispatch) {
return bindActionCreators({
submitAction,
}, dispatch);
} | function mapDispatchToProps(dispatch) {
return bindActionCreators({
submitAction,
}, dispatch);
} |
JavaScript | function mapStateToProps(state) {
return {
username: state.main.user.NIBR521,
};
} | function mapStateToProps(state) {
return {
username: state.main.user.NIBR521,
};
} |
JavaScript | function mapDispatchToProps(dispatch) {
return bindActionCreators({
}, dispatch);
} | function mapDispatchToProps(dispatch) {
return bindActionCreators({
}, dispatch);
} |
JavaScript | redraw() {
const context = this.state.drawContext;
context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clears the canvas
if (!this.props.clear) {
context.strokeStyle = 'black';
context.lineJoin = 'round';
context.lineWidth = 5;
context.closePath();
let lineNumber = 0;
let dotNumber = 0;
this.state.lines.forEach(() => {
this.state.lines[lineNumber].forEach((dot) => {
if (dotNumber === 0) {
context.beginPath();
context.moveTo(dot.x / dot.scale, dot.y / dot.scale);
context.lineTo(dot.x / dot.scale, dot.y / dot.scale);
context.closePath();
context.stroke();
} else {
context.lineTo(dot.x / dot.scale, dot.y / dot.scale);
context.closePath();
context.stroke();
context.beginPath();
}
context.moveTo(dot.x / dot.scale, dot.y / dot.scale);
dotNumber += 1;
});
dotNumber = 0;
lineNumber += 1;
});
}
this.updatePaintCanvas();
} | redraw() {
const context = this.state.drawContext;
context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clears the canvas
if (!this.props.clear) {
context.strokeStyle = 'black';
context.lineJoin = 'round';
context.lineWidth = 5;
context.closePath();
let lineNumber = 0;
let dotNumber = 0;
this.state.lines.forEach(() => {
this.state.lines[lineNumber].forEach((dot) => {
if (dotNumber === 0) {
context.beginPath();
context.moveTo(dot.x / dot.scale, dot.y / dot.scale);
context.lineTo(dot.x / dot.scale, dot.y / dot.scale);
context.closePath();
context.stroke();
} else {
context.lineTo(dot.x / dot.scale, dot.y / dot.scale);
context.closePath();
context.stroke();
context.beginPath();
}
context.moveTo(dot.x / dot.scale, dot.y / dot.scale);
dotNumber += 1;
});
dotNumber = 0;
lineNumber += 1;
});
}
this.updatePaintCanvas();
} |
JavaScript | addClick(x, y, dragging) {
const { lines } = this.state;
const scale = this.props.scale;
const dot = {
x,
y,
scale,
};
const lastIndex = lines.length - 1;
if (this.props.enabled) {
if (dragging) {
this.setState({
lines: [...lines.slice(0, lastIndex), [...lines[lastIndex], dot]],
drawing: true,
}, () => this.redraw());
} else {
this.setState({
lines: [...this.state.lines, [dot]],
drawing: true,
}, () => this.redraw());
}
}
} | addClick(x, y, dragging) {
const { lines } = this.state;
const scale = this.props.scale;
const dot = {
x,
y,
scale,
};
const lastIndex = lines.length - 1;
if (this.props.enabled) {
if (dragging) {
this.setState({
lines: [...lines.slice(0, lastIndex), [...lines[lastIndex], dot]],
drawing: true,
}, () => this.redraw());
} else {
this.setState({
lines: [...this.state.lines, [dot]],
drawing: true,
}, () => this.redraw());
}
}
} |
JavaScript | handleMouseMove(e) {
const positionX = e.pageX === undefined ? (e.changedTouches[0].pageX) : e.pageX;
const positionY = e.pageX === undefined ? (e.changedTouches[0].pageY) : e.pageY;
if (this.state.drawing) {
const rect = this.state.canvas.getBoundingClientRect();
const x = positionX - rect.left;
const y = positionY - rect.top;
this.addClick(x, y, true);
}
} | handleMouseMove(e) {
const positionX = e.pageX === undefined ? (e.changedTouches[0].pageX) : e.pageX;
const positionY = e.pageX === undefined ? (e.changedTouches[0].pageY) : e.pageY;
if (this.state.drawing) {
const rect = this.state.canvas.getBoundingClientRect();
const x = positionX - rect.left;
const y = positionY - rect.top;
this.addClick(x, y, true);
}
} |
JavaScript | function mapStateToProps(state) {
return {
};
} | function mapStateToProps(state) {
return {
};
} |
JavaScript | function mapDispatchToProps(dispatch) {
return bindActionCreators({
requestImage,
clearArtboard,
}, dispatch);
} | function mapDispatchToProps(dispatch) {
return bindActionCreators({
requestImage,
clearArtboard,
}, dispatch);
} |
JavaScript | function mapStateToProps(state) {
return {
resizing: state.draw.artboard.resizing,
width: state.draw.artboard.width,
};
} | function mapStateToProps(state) {
return {
resizing: state.draw.artboard.resizing,
width: state.draw.artboard.width,
};
} |
JavaScript | function mapDispatchToProps(dispatch) {
return bindActionCreators({
resize,
setWidth,
stopResize,
}, dispatch);
} | function mapDispatchToProps(dispatch) {
return bindActionCreators({
resize,
setWidth,
stopResize,
}, dispatch);
} |
JavaScript | function mapStateToProps(state) {
return {
resizing: state.draw.artboard.resizing,
width: 100 * (1 - state.draw.artboard.width),
objects: state.draw.diagram.objects,
zoom: state.draw.diagram.zoom,
x: state.draw.diagram.x,
y: state.draw.diagram.y,
};
} | function mapStateToProps(state) {
return {
resizing: state.draw.artboard.resizing,
width: 100 * (1 - state.draw.artboard.width),
objects: state.draw.diagram.objects,
zoom: state.draw.diagram.zoom,
x: state.draw.diagram.x,
y: state.draw.diagram.y,
};
} |
JavaScript | function mapDispatchToProps(dispatch) {
return bindActionCreators({
finishEditing,
}, dispatch);
} | function mapDispatchToProps(dispatch) {
return bindActionCreators({
finishEditing,
}, dispatch);
} |
JavaScript | function mapStateToProps(state) {
return {
//////////// Artboard ////////////
loading: state.draw.artboard.loading,
width: state.draw.artboard.width,
clearArtboard: state.draw.artboard.clear,
resizing: state.draw.artboard.resizing,
//////////// Diagram ////////////
diagramMode: state.draw.diagram.mode,
editing: state.draw.diagram.editObject.editing,
objectId: state.draw.diagram.editObject.id,
dragging: state.draw.diagram.dragging,
zoom: state.draw.diagram.zoom,
x: state.draw.diagram.x,
y: state.draw.diagram.y,
};
} | function mapStateToProps(state) {
return {
//////////// Artboard ////////////
loading: state.draw.artboard.loading,
width: state.draw.artboard.width,
clearArtboard: state.draw.artboard.clear,
resizing: state.draw.artboard.resizing,
//////////// Diagram ////////////
diagramMode: state.draw.diagram.mode,
editing: state.draw.diagram.editObject.editing,
objectId: state.draw.diagram.editObject.id,
dragging: state.draw.diagram.dragging,
zoom: state.draw.diagram.zoom,
x: state.draw.diagram.x,
y: state.draw.diagram.y,
};
} |
JavaScript | function mapDispatchToProps(dispatch) {
return bindActionCreators({
//////////// Artboard ////////////
setWidth,
resize,
stopResize,
//////////// Diagram ////////////
scrollDiagram,
stopEditing,
finishEditing,
//////////// Object ////////////
moveObject,
resizeObject,
rotateObject,
}, dispatch);
} | function mapDispatchToProps(dispatch) {
return bindActionCreators({
//////////// Artboard ////////////
setWidth,
resize,
stopResize,
//////////// Diagram ////////////
scrollDiagram,
stopEditing,
finishEditing,
//////////// Object ////////////
moveObject,
resizeObject,
rotateObject,
}, dispatch);
} |
JavaScript | function trainReducer(state = initialState, action) {
const { payload } = action;
switch (action.type) {
case SET_USER:
return {
...state,
user: payload.user,
};
case SET_DEVICE:
return {
...state,
isMobile: payload.isMobile,
};
default:
return state;
}
} | function trainReducer(state = initialState, action) {
const { payload } = action;
switch (action.type) {
case SET_USER:
return {
...state,
user: payload.user,
};
case SET_DEVICE:
return {
...state,
isMobile: payload.isMobile,
};
default:
return state;
}
} |
JavaScript | function trainReducer(state = initialState, action) {
const { payload } = action;
switch (action.type) {
case REQUESTING:
return {
...state,
loading: true,
playing: false,
};
case SUBMIT:
return {
...state,
loading: true,
submitted: true,
playing: false,
};
case GETIMAGE:
return {
...state,
loading: false,
submitted: false,
imageData: payload.data,
imageLabel: payload.label,
playing: true,
};
case TOGGLE_TIMER:
return {
...state,
playing: !state.playing,
};
case ERROR:
return {
...state,
playing: false,
error: payload.error,
};
default:
return state;
}
} | function trainReducer(state = initialState, action) {
const { payload } = action;
switch (action.type) {
case REQUESTING:
return {
...state,
loading: true,
playing: false,
};
case SUBMIT:
return {
...state,
loading: true,
submitted: true,
playing: false,
};
case GETIMAGE:
return {
...state,
loading: false,
submitted: false,
imageData: payload.data,
imageLabel: payload.label,
playing: true,
};
case TOGGLE_TIMER:
return {
...state,
playing: !state.playing,
};
case ERROR:
return {
...state,
playing: false,
error: payload.error,
};
default:
return state;
}
} |
JavaScript | function mapStateToProps(state) {
return {
loading: state.train.loading,
submitted: state.train.submitted,
imageData: state.train.imageData,
imageLabel: state.train.imageLabel,
playing: state.train.playing,
error: state.train.error,
username: state.main.user.NIBR521,
};
} | function mapStateToProps(state) {
return {
loading: state.train.loading,
submitted: state.train.submitted,
imageData: state.train.imageData,
imageLabel: state.train.imageLabel,
playing: state.train.playing,
error: state.train.error,
username: state.main.user.NIBR521,
};
} |
JavaScript | function mapDispatchToProps(dispatch) {
return bindActionCreators({
submitAction,
sendImage,
toggleTimerAction,
}, dispatch);
} | function mapDispatchToProps(dispatch) {
return bindActionCreators({
submitAction,
sendImage,
toggleTimerAction,
}, dispatch);
} |
JavaScript | function makeView(str) {
console.log('starting server');
http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(str);
res.end();
}).listen(8080);
} | function makeView(str) {
console.log('starting server');
http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(str);
res.end();
}).listen(8080);
} |
JavaScript | async fetch(URI, method, data) {
let params = {
method: method,
headers: MoulinetteClient.HEADERS
}
if( data ) { params.body = JSON.stringify(data) }
const response = await fetch(`${MoulinetteClient.SERVER_URL}${URI}`, params).catch(function(e) {
console.log(`Moulinette | Cannot establish connection to server ${MoulinetteClient.SERVER_URL}`, e)
});
return response
} | async fetch(URI, method, data) {
let params = {
method: method,
headers: MoulinetteClient.HEADERS
}
if( data ) { params.body = JSON.stringify(data) }
const response = await fetch(`${MoulinetteClient.SERVER_URL}${URI}`, params).catch(function(e) {
console.log(`Moulinette | Cannot establish connection to server ${MoulinetteClient.SERVER_URL}`, e)
});
return response
} |
JavaScript | static async upload(file, name, folderSrc, folderPath, overwrite = false) {
const source = Moulinette.getSource()
Moulinette.createFolderIfMissing(folderSrc, folderPath)
// check if file already exist
let base = await FilePicker.browse(source, folderPath);
let exist = base.files.filter(f => f == `${folderPath}/${name}`)
if(exist.length > 0 && !overwrite) return;
try {
let response = await FilePicker.upload(source, folderPath, file, {bucket: null});
} catch (e) {
console.log(`Moulinette | Not able to upload file ${name}`)
console.log(e)
}
} | static async upload(file, name, folderSrc, folderPath, overwrite = false) {
const source = Moulinette.getSource()
Moulinette.createFolderIfMissing(folderSrc, folderPath)
// check if file already exist
let base = await FilePicker.browse(source, folderPath);
let exist = base.files.filter(f => f == `${folderPath}/${name}`)
if(exist.length > 0 && !overwrite) return;
try {
let response = await FilePicker.upload(source, folderPath, file, {bucket: null});
} catch (e) {
console.log(`Moulinette | Not able to upload file ${name}`)
console.log(e)
}
} |
JavaScript | _onSoundVolume(event) {
event.preventDefault();
const slider = event.currentTarget;
const path = slider.closest(".pack").dataset.path;
// retrieve sound in play list
const playlist = game.playlists.find( pl => pl.data.name == Moulinette.MOULINETTE_SOUNDBOARD )
if(!playlist) return;
const sound = playlist.sounds.find( s => s.path == path )
if(!sound) return
// Only push the update if the user is a GM
const volume = AudioHelper.inputToVolume(slider.value);
if (game.user.isGM) playlist.updateEmbeddedEntity("PlaylistSound", {_id: sound._id, volume: volume});
// Otherwise simply apply a local override
else {
let sound = playlist.audio[sound._id];
if (!sound.howl) return;
sound.howl.volume(volume, sound._id);
}
} | _onSoundVolume(event) {
event.preventDefault();
const slider = event.currentTarget;
const path = slider.closest(".pack").dataset.path;
// retrieve sound in play list
const playlist = game.playlists.find( pl => pl.data.name == Moulinette.MOULINETTE_SOUNDBOARD )
if(!playlist) return;
const sound = playlist.sounds.find( s => s.path == path )
if(!sound) return
// Only push the update if the user is a GM
const volume = AudioHelper.inputToVolume(slider.value);
if (game.user.isGM) playlist.updateEmbeddedEntity("PlaylistSound", {_id: sound._id, volume: volume});
// Otherwise simply apply a local override
else {
let sound = playlist.audio[sound._id];
if (!sound.howl) return;
sound.howl.volume(volume, sound._id);
}
} |
JavaScript | static async _scanFolder(path, filter) {
let list = []
const base = await FilePicker.browse(Moulinette.getSource(), path);
let baseFiles = filter ? base.files.filter(f => filter.includes(f.split(".").pop().toLowerCase())) : base.files
list.push(...baseFiles)
for(const d of base.dirs) {
const files = await MoulinetteForge._scanFolder(d, filter)
list.push(...files)
}
return list
} | static async _scanFolder(path, filter) {
let list = []
const base = await FilePicker.browse(Moulinette.getSource(), path);
let baseFiles = filter ? base.files.filter(f => filter.includes(f.split(".").pop().toLowerCase())) : base.files
list.push(...baseFiles)
for(const d of base.dirs) {
const files = await MoulinetteForge._scanFolder(d, filter)
list.push(...files)
}
return list
} |
JavaScript | async _installPacks(selected) {
this.inProgress = true
let client = new MoulinetteClient()
let babeleInstalled = false
let coreInstalled = false
try {
// installed packs
let packInstalled = JSON.parse(game.settings.get("moulinette", "packInstalled"))
// iterate on each desired request
for( const r of selected ) {
const response = await fetch(`${MoulinetteClient.GITHUB_SRC}/main${r.url}`).catch(function(e) {
console.log(`Moulinette | Not able to fetch JSON for pack ${r.name}`, e)
});
if(!response) continue;
const pack = await response.json()
if(r.type == "babele-translation" && (!"babele" in game.modules.keys() || !game.modules.get("babele").active)) {
ui.notifications.error(game.i18n.localize("ERROR.mtteNoBabele"));
continue;
}
// initialize progressbar
SceneNavigation._onLoadProgress(r.name,0);
// retrieve all translations from pack
let idx = 0
for( const ts of pack.list ) {
idx++;
// retrieve transl JSON
const filename = ts.url.split('/').pop()
let response = await fetch(`${ts.url}`).catch(function(e) {
console.log(`Moulinette | Not able to fetch translation of pack ${pack.name}`, e)
});
if(!response) {
console.log("Moulinette | Direct download not working. Using proxy...")
response = await client.fetch(`/bundler/fvtt/transl/${pack.id}/${idx-1}`)
if(!response) {
console.log("Moulinette | Proxy download not working. Skip.")
continue;
}
}
const blob = await response.blob()
// Babele translations
if(r.type == "babele-translation") {
const folder = `moulinette/transl/babele/${r["lang"]}`
await Moulinette.upload(new File([blob], filename, { type: blob.type, lastModified: new Date() }), filename, "moulinette/transl/babele", folder, true)
babeleInstalled = true
if(!packInstalled.includes(r.filename)) packInstalled.push(r.filename)
}
// Core/system translation
else if(r.type == "core-translation") {
const folder = `moulinette/transl/core/${r["lang"]}`
const transFilename = `${r["filename"]}-${filename}`
await Moulinette.upload(new File([blob], transFilename, { type: blob.type, lastModified: new Date() }), transFilename, "moulinette/transl/core", folder, true)
coreInstalled = true
if(!packInstalled.includes(r.filename)) packInstalled.push(r.filename)
}
// update progressbar
SceneNavigation._onLoadProgress(r.name, Math.round((idx / pack.list.length)*100));
}
}
// cleanup installed packages (avoid two conflicting translations)
let core = []
let modules = []
let systems = []
let packInstalledClean = []
packInstalled.slice().reverse().forEach( installed => {
const pack = this.lists.transl.find( tr => tr.filename == installed )
if(!pack) return
if(pack.system && !systems.includes(`${pack.type}-${pack.lang}-${pack.system}`)) {
systems.push(`${pack.type}-${pack.lang}-${pack.system}`)
packInstalledClean.push(installed)
}
else if(pack.module && !modules.includes(`${pack.type}-${pack.lang}-${pack.module}`)) {
modules.push(`${pack.lang}-${pack.module}`)
packInstalledClean.push(installed)
} else if(!pack.module && !pack.system && !core.includes(pack.lang)) {
core.push(pack.lang)
packInstalledClean.push(installed)
} else {
console.log(`Moulinette | Translation ${installed} removed from list because in conflict with another`)
}
});
// store settings (installed packs)
game.settings.set("moulinette", "packInstalled", JSON.stringify(packInstalledClean))
if(babeleInstalled) {
game.settings.set('babele', 'directory', "moulinette/transl/babele")
this._displayMessage(game.i18n.localize("mtte.downloadSuccess"), 'success')
}
if(coreInstalled) {
let languages = []
let browse = await FilePicker.browse(Moulinette.getSource(), "moulinette/transl/core");
for( const d of browse.dirs ) {
const lang = d.split('/').pop()
const data = await FilePicker.browse(Moulinette.getSource(), d, {'extensions': ['.json']});
data.files.forEach( f => {
languages.push( {
"lang": lang,
"name": game.i18n.localize("mtte.lang." + lang),
"path": f
})
});
}
game.settings.set("moulinette", "coreLanguages", JSON.stringify(languages))
this._displayMessage(game.i18n.localize("mtte.downloadCoreSuccess"), 'success')
}
} catch(e) {
console.log(`Moulinette | Unhandled exception`, e)
this._displayMessage(game.i18n.localize("mtte.downloadFailure"), 'error')
}
// hide progressbar
SceneNavigation._onLoadProgress(game.i18n.localize("mtte.installingPacks"), 100);
} | async _installPacks(selected) {
this.inProgress = true
let client = new MoulinetteClient()
let babeleInstalled = false
let coreInstalled = false
try {
// installed packs
let packInstalled = JSON.parse(game.settings.get("moulinette", "packInstalled"))
// iterate on each desired request
for( const r of selected ) {
const response = await fetch(`${MoulinetteClient.GITHUB_SRC}/main${r.url}`).catch(function(e) {
console.log(`Moulinette | Not able to fetch JSON for pack ${r.name}`, e)
});
if(!response) continue;
const pack = await response.json()
if(r.type == "babele-translation" && (!"babele" in game.modules.keys() || !game.modules.get("babele").active)) {
ui.notifications.error(game.i18n.localize("ERROR.mtteNoBabele"));
continue;
}
// initialize progressbar
SceneNavigation._onLoadProgress(r.name,0);
// retrieve all translations from pack
let idx = 0
for( const ts of pack.list ) {
idx++;
// retrieve transl JSON
const filename = ts.url.split('/').pop()
let response = await fetch(`${ts.url}`).catch(function(e) {
console.log(`Moulinette | Not able to fetch translation of pack ${pack.name}`, e)
});
if(!response) {
console.log("Moulinette | Direct download not working. Using proxy...")
response = await client.fetch(`/bundler/fvtt/transl/${pack.id}/${idx-1}`)
if(!response) {
console.log("Moulinette | Proxy download not working. Skip.")
continue;
}
}
const blob = await response.blob()
// Babele translations
if(r.type == "babele-translation") {
const folder = `moulinette/transl/babele/${r["lang"]}`
await Moulinette.upload(new File([blob], filename, { type: blob.type, lastModified: new Date() }), filename, "moulinette/transl/babele", folder, true)
babeleInstalled = true
if(!packInstalled.includes(r.filename)) packInstalled.push(r.filename)
}
// Core/system translation
else if(r.type == "core-translation") {
const folder = `moulinette/transl/core/${r["lang"]}`
const transFilename = `${r["filename"]}-${filename}`
await Moulinette.upload(new File([blob], transFilename, { type: blob.type, lastModified: new Date() }), transFilename, "moulinette/transl/core", folder, true)
coreInstalled = true
if(!packInstalled.includes(r.filename)) packInstalled.push(r.filename)
}
// update progressbar
SceneNavigation._onLoadProgress(r.name, Math.round((idx / pack.list.length)*100));
}
}
// cleanup installed packages (avoid two conflicting translations)
let core = []
let modules = []
let systems = []
let packInstalledClean = []
packInstalled.slice().reverse().forEach( installed => {
const pack = this.lists.transl.find( tr => tr.filename == installed )
if(!pack) return
if(pack.system && !systems.includes(`${pack.type}-${pack.lang}-${pack.system}`)) {
systems.push(`${pack.type}-${pack.lang}-${pack.system}`)
packInstalledClean.push(installed)
}
else if(pack.module && !modules.includes(`${pack.type}-${pack.lang}-${pack.module}`)) {
modules.push(`${pack.lang}-${pack.module}`)
packInstalledClean.push(installed)
} else if(!pack.module && !pack.system && !core.includes(pack.lang)) {
core.push(pack.lang)
packInstalledClean.push(installed)
} else {
console.log(`Moulinette | Translation ${installed} removed from list because in conflict with another`)
}
});
// store settings (installed packs)
game.settings.set("moulinette", "packInstalled", JSON.stringify(packInstalledClean))
if(babeleInstalled) {
game.settings.set('babele', 'directory', "moulinette/transl/babele")
this._displayMessage(game.i18n.localize("mtte.downloadSuccess"), 'success')
}
if(coreInstalled) {
let languages = []
let browse = await FilePicker.browse(Moulinette.getSource(), "moulinette/transl/core");
for( const d of browse.dirs ) {
const lang = d.split('/').pop()
const data = await FilePicker.browse(Moulinette.getSource(), d, {'extensions': ['.json']});
data.files.forEach( f => {
languages.push( {
"lang": lang,
"name": game.i18n.localize("mtte.lang." + lang),
"path": f
})
});
}
game.settings.set("moulinette", "coreLanguages", JSON.stringify(languages))
this._displayMessage(game.i18n.localize("mtte.downloadCoreSuccess"), 'success')
}
} catch(e) {
console.log(`Moulinette | Unhandled exception`, e)
this._displayMessage(game.i18n.localize("mtte.downloadFailure"), 'error')
}
// hide progressbar
SceneNavigation._onLoadProgress(game.i18n.localize("mtte.installingPacks"), 100);
} |
JavaScript | function ExpectationError(message) {
this.name = 'ExpectationError';
this.message = 'ExpectationError: ' + (message || 'Unknown expectation failed.');
this.stack = new Error().stack;
} | function ExpectationError(message) {
this.name = 'ExpectationError';
this.message = 'ExpectationError: ' + (message || 'Unknown expectation failed.');
this.stack = new Error().stack;
} |
JavaScript | function activate() {
__log("Activating global mock '{0}:{1}'", _propertyName, _id);
_context[_propertyName] = _mock;
} | function activate() {
__log("Activating global mock '{0}:{1}'", _propertyName, _id);
_context[_propertyName] = _mock;
} |
JavaScript | function mock(mockName, objectToBeMocked) {
if (typeof mockName !== "string" || !mockName) {
throw new TypeError("The first argument must be a string");
}
var objType = _typeof(objectToBeMocked);
if (objType === "function" || objType === "object" && objectToBeMocked !== null) {
return __createObjectOrFunctionMock(mockName, objectToBeMocked, objType);
}
return __createSimpleMock(mockName);
} | function mock(mockName, objectToBeMocked) {
if (typeof mockName !== "string" || !mockName) {
throw new TypeError("The first argument must be a string");
}
var objType = _typeof(objectToBeMocked);
if (objType === "function" || objType === "object" && objectToBeMocked !== null) {
return __createObjectOrFunctionMock(mockName, objectToBeMocked, objType);
}
return __createSimpleMock(mockName);
} |
JavaScript | function mockGlobal(globalObjectName) {
if (typeof globalObjectName !== "string" || !globalObjectName) {
throw new TypeError("The first argument must be a string");
}
return __mockGlobal(globalObjectName);
} | function mockGlobal(globalObjectName) {
if (typeof globalObjectName !== "string" || !globalObjectName) {
throw new TypeError("The first argument must be a string");
}
return __mockGlobal(globalObjectName);
} |
JavaScript | function ExpectationError(message) {
this.name = 'ExpectationError';
this.message = 'ExpectationError: ' + (message || 'Unknown expectation failed.');
this.stack = (new Error()).stack;
} | function ExpectationError(message) {
this.name = 'ExpectationError';
this.message = 'ExpectationError: ' + (message || 'Unknown expectation failed.');
this.stack = (new Error()).stack;
} |
JavaScript | addFileList (fileList) {
for (let i = 0; i < fileList.length; i++) {
const file = fileList[i]
const uuid = nanoid()
const removeFile = function () {
this.removeFile(uuid)
}
this.files.push({
progress: false,
error: false,
complete: false,
justFinished: false,
name: file.name || 'file-upload',
file,
uuid,
path: false,
removeFile: removeFile.bind(this),
previewData: file.previewData || false
})
}
} | addFileList (fileList) {
for (let i = 0; i < fileList.length; i++) {
const file = fileList[i]
const uuid = nanoid()
const removeFile = function () {
this.removeFile(uuid)
}
this.files.push({
progress: false,
error: false,
complete: false,
justFinished: false,
name: file.name || 'file-upload',
file,
uuid,
path: false,
removeFile: removeFile.bind(this),
previewData: file.previewData || false
})
}
} |
JavaScript | uploaderIsAxios () {
if (
this.hasUploader() &&
typeof this.context.uploader.request === 'function' &&
typeof this.context.uploader.get === 'function' &&
typeof this.context.uploader.delete === 'function' &&
typeof this.context.uploader.post === 'function'
) {
return true
}
return false
} | uploaderIsAxios () {
if (
this.hasUploader() &&
typeof this.context.uploader.request === 'function' &&
typeof this.context.uploader.get === 'function' &&
typeof this.context.uploader.delete === 'function' &&
typeof this.context.uploader.post === 'function'
) {
return true
}
return false
} |
JavaScript | __performUpload () {
return new Promise((resolve, reject) => {
if (!this.hasUploader()) {
return reject(new Error('No uploader has been defined'))
}
Promise.all(this.files.map(file => {
file.error = false
file.complete = !!file.path
return file.path ? Promise.resolve(file.path) : this.getUploader(
file.file,
(progress) => {
file.progress = progress
this.context.rootEmit('file-upload-progress', progress)
if (progress >= 100) {
if (!file.complete) {
file.justFinished = true
setTimeout(() => { file.justFinished = false }, this.options.uploadJustCompleteDuration)
}
file.complete = true
this.context.rootEmit('file-upload-complete', file)
}
},
(error) => {
file.progress = 0
file.error = error
file.complete = true
this.context.rootEmit('file-upload-error', error)
reject(error)
},
this.options
)
}))
.then(results => {
this.results = this.mapUUID(results)
resolve(results)
})
.catch(err => {
throw new Error(err)
})
})
} | __performUpload () {
return new Promise((resolve, reject) => {
if (!this.hasUploader()) {
return reject(new Error('No uploader has been defined'))
}
Promise.all(this.files.map(file => {
file.error = false
file.complete = !!file.path
return file.path ? Promise.resolve(file.path) : this.getUploader(
file.file,
(progress) => {
file.progress = progress
this.context.rootEmit('file-upload-progress', progress)
if (progress >= 100) {
if (!file.complete) {
file.justFinished = true
setTimeout(() => { file.justFinished = false }, this.options.uploadJustCompleteDuration)
}
file.complete = true
this.context.rootEmit('file-upload-complete', file)
}
},
(error) => {
file.progress = 0
file.error = error
file.complete = true
this.context.rootEmit('file-upload-error', error)
reject(error)
},
this.options
)
}))
.then(results => {
this.results = this.mapUUID(results)
resolve(results)
})
.catch(err => {
throw new Error(err)
})
})
} |
JavaScript | removeFile (uuid) {
const originalLength = this.files.length
this.files = this.files.filter(file => file && file.uuid !== uuid)
if (Array.isArray(this.results)) {
this.results = this.results.filter(file => file && file.__id !== uuid)
}
this.context.performValidation()
if (window && this.fileList instanceof FileList && this.supportsDataTransfers) {
const transfer = new DataTransfer()
this.files.forEach(file => transfer.items.add(file.file))
this.fileList = transfer.files
this.input.files = this.fileList
} else {
this.fileList = this.fileList.filter(file => file && file.__id !== uuid)
}
if (originalLength > this.files.length) {
this.context.rootEmit('file-removed', this.files)
}
} | removeFile (uuid) {
const originalLength = this.files.length
this.files = this.files.filter(file => file && file.uuid !== uuid)
if (Array.isArray(this.results)) {
this.results = this.results.filter(file => file && file.__id !== uuid)
}
this.context.performValidation()
if (window && this.fileList instanceof FileList && this.supportsDataTransfers) {
const transfer = new DataTransfer()
this.files.forEach(file => transfer.items.add(file.file))
this.fileList = transfer.files
this.input.files = this.fileList
} else {
this.fileList = this.fileList.filter(file => file && file.__id !== uuid)
}
if (originalLength > this.files.length) {
this.context.rootEmit('file-removed', this.files)
}
} |
JavaScript | mergeFileList (input) {
this.addFileList(input.files)
// Create a new mutable FileList
if (this.supportsDataTransfers) {
const transfer = new DataTransfer()
this.files.forEach(file => {
if (file.file instanceof File) {
transfer.items.add(file.file)
}
})
this.fileList = transfer.files
this.input.files = this.fileList
// Reset the merged FileList to empty
input.files = (new DataTransfer()).files
}
this.context.performValidation()
this.loadPreviews()
if (this.context.uploadBehavior !== 'delayed') {
this.upload()
}
} | mergeFileList (input) {
this.addFileList(input.files)
// Create a new mutable FileList
if (this.supportsDataTransfers) {
const transfer = new DataTransfer()
this.files.forEach(file => {
if (file.file instanceof File) {
transfer.items.add(file.file)
}
})
this.fileList = transfer.files
this.input.files = this.fileList
// Reset the merged FileList to empty
input.files = (new DataTransfer()).files
}
this.context.performValidation()
this.loadPreviews()
if (this.context.uploadBehavior !== 'delayed') {
this.upload()
}
} |
JavaScript | loadPreviews () {
this.files.map(file => {
if (!file.previewData && window && window.FileReader && /^image\//.test(file.file.type)) {
const reader = new FileReader()
reader.onload = e => Object.assign(file, { previewData: e.target.result })
reader.readAsDataURL(file.file)
}
})
} | loadPreviews () {
this.files.map(file => {
if (!file.previewData && window && window.FileReader && /^image\//.test(file.file.type)) {
const reader = new FileReader()
reader.onload = e => Object.assign(file, { previewData: e.target.result })
reader.readAsDataURL(file.file)
}
})
} |
JavaScript | dataTransferCheck () {
try {
new DataTransfer() // eslint-disable-line
this.supportsDataTransfers = true
} catch (err) {
this.supportsDataTransfers = false
}
} | dataTransferCheck () {
try {
new DataTransfer() // eslint-disable-line
this.supportsDataTransfers = true
} catch (err) {
this.supportsDataTransfers = false
}
} |
JavaScript | function useRegistryComputed (options = {}) {
return {
hasInitialValue () {
return (
(this.formulateValue && typeof this.formulateValue === 'object') ||
(this.values && typeof this.values === 'object') ||
(this.isGrouping && typeof this.context.model[this.index] === 'object')
)
},
isVmodeled () {
return !!(this.$options.propsData.hasOwnProperty('formulateValue') &&
this._events &&
Array.isArray(this._events.input) &&
this._events.input.length)
},
initialValues () {
if (
has(this.$options.propsData, 'formulateValue') &&
typeof this.formulateValue === 'object'
) {
// If there is a v-model on the form/group, use those values as first priority
return { ...this.formulateValue } // @todo - use a deep clone to detach reference types?
} else if (
has(this.$options.propsData, 'values') &&
typeof this.values === 'object'
) {
// If there are values, use them as secondary priority
return { ...this.values }
} else if (
this.isGrouping && typeof this.context.model[this.index] === 'object'
) {
return this.context.model[this.index]
}
return {}
},
mergedGroupErrors () {
const hasSubFields = /^([^.\d+].*?)\.(\d+\..+)$/
return Object.keys(this.mergedFieldErrors)
.filter(k => hasSubFields.test(k))
.reduce((groupErrorsByRoot, k) => {
let [, rootField, groupKey] = k.match(hasSubFields)
if (!groupErrorsByRoot[rootField]) {
groupErrorsByRoot[rootField] = {}
}
Object.assign(groupErrorsByRoot[rootField], { [groupKey]: this.mergedFieldErrors[k] })
return groupErrorsByRoot
}, {})
}
}
} | function useRegistryComputed (options = {}) {
return {
hasInitialValue () {
return (
(this.formulateValue && typeof this.formulateValue === 'object') ||
(this.values && typeof this.values === 'object') ||
(this.isGrouping && typeof this.context.model[this.index] === 'object')
)
},
isVmodeled () {
return !!(this.$options.propsData.hasOwnProperty('formulateValue') &&
this._events &&
Array.isArray(this._events.input) &&
this._events.input.length)
},
initialValues () {
if (
has(this.$options.propsData, 'formulateValue') &&
typeof this.formulateValue === 'object'
) {
// If there is a v-model on the form/group, use those values as first priority
return { ...this.formulateValue } // @todo - use a deep clone to detach reference types?
} else if (
has(this.$options.propsData, 'values') &&
typeof this.values === 'object'
) {
// If there are values, use them as secondary priority
return { ...this.values }
} else if (
this.isGrouping && typeof this.context.model[this.index] === 'object'
) {
return this.context.model[this.index]
}
return {}
},
mergedGroupErrors () {
const hasSubFields = /^([^.\d+].*?)\.(\d+\..+)$/
return Object.keys(this.mergedFieldErrors)
.filter(k => hasSubFields.test(k))
.reduce((groupErrorsByRoot, k) => {
let [, rootField, groupKey] = k.match(hasSubFields)
if (!groupErrorsByRoot[rootField]) {
groupErrorsByRoot[rootField] = {}
}
Object.assign(groupErrorsByRoot[rootField], { [groupKey]: this.mergedFieldErrors[k] })
return groupErrorsByRoot
}, {})
}
}
} |
JavaScript | function useRegistryMethods (without = []) {
const methods = {
applyInitialValues () {
if (this.hasInitialValue) {
this.proxy = { ...this.initialValues }
}
},
setFieldValue (field, value) {
if (value === undefined) {
// undefined values should be removed from the form model
const { [field]: value, ...proxy } = this.proxy
this.proxy = proxy
} else {
Object.assign(this.proxy, { [field]: value })
}
this.$emit('input', { ...this.proxy })
},
valueDeps (callerCmp) {
return Object.keys(this.proxy)
.reduce((o, k) => Object.defineProperty(o, k, {
enumerable: true,
get: () => {
const callee = this.registry.get(k)
this.deps.set(callerCmp, this.deps.get(callerCmp) || new Set())
if (callee) {
this.deps.set(callee, this.deps.get(callee) || new Set())
this.deps.get(callee).add(callerCmp.name)
}
this.deps.get(callerCmp).add(k)
return this.proxy[k]
}
}), Object.create(null))
},
validateDeps (callerCmp) {
if (this.deps.has(callerCmp)) {
this.deps.get(callerCmp).forEach(field => this.registry.has(field) && this.registry.get(field).performValidation())
}
},
hasValidationErrors () {
return Promise.all(this.registry.reduce((resolvers, cmp, name) => {
resolvers.push(cmp.performValidation() && cmp.getValidationErrors())
return resolvers
}, [])).then(errorObjects => errorObjects.some(item => item.hasErrors))
},
showErrors () {
this.childrenShouldShowErrors = true
this.registry.map(input => {
input.formShouldShowErrors = true
})
},
hideErrors () {
this.childrenShouldShowErrors = false
this.registry.map(input => {
input.formShouldShowErrors = false
input.behavioralErrorVisibility = false
})
},
setValues (values) {
// Collect all keys, existing and incoming
const keys = Array.from(new Set(Object.keys(values || {}).concat(Object.keys(this.proxy))))
keys.forEach(field => {
const input = this.registry.has(field) && this.registry.get(field)
let value = values ? values[field] : undefined
if (input && !equals(input.proxy, value, true)) {
input.context.model = value
}
if (!equals(value, this.proxy[field], true)) {
this.setFieldValue(field, value)
}
})
},
updateValidation (errorObject) {
if (has(this.registry.errors, errorObject.name)) {
this.registry.errors[errorObject.name] = errorObject.hasErrors
}
this.$emit('validation', errorObject)
},
addErrorObserver (observer) {
if (!this.errorObservers.find(obs => observer.callback === obs.callback)) {
this.errorObservers.push(observer)
if (observer.type === 'form') {
observer.callback(this.mergedFormErrors)
} else if (observer.type === 'group' && has(this.mergedGroupErrors, observer.field)) {
observer.callback(this.mergedGroupErrors[observer.field])
} else if (has(this.mergedFieldErrors, observer.field)) {
observer.callback(this.mergedFieldErrors[observer.field])
}
}
},
removeErrorObserver (observer) {
this.errorObservers = this.errorObservers.filter(obs => obs.callback !== observer)
}
}
return Object.keys(methods).reduce((withMethods, key) => {
return without.includes(key) ? withMethods : { ...withMethods, [key]: methods[key] }
}, {})
} | function useRegistryMethods (without = []) {
const methods = {
applyInitialValues () {
if (this.hasInitialValue) {
this.proxy = { ...this.initialValues }
}
},
setFieldValue (field, value) {
if (value === undefined) {
// undefined values should be removed from the form model
const { [field]: value, ...proxy } = this.proxy
this.proxy = proxy
} else {
Object.assign(this.proxy, { [field]: value })
}
this.$emit('input', { ...this.proxy })
},
valueDeps (callerCmp) {
return Object.keys(this.proxy)
.reduce((o, k) => Object.defineProperty(o, k, {
enumerable: true,
get: () => {
const callee = this.registry.get(k)
this.deps.set(callerCmp, this.deps.get(callerCmp) || new Set())
if (callee) {
this.deps.set(callee, this.deps.get(callee) || new Set())
this.deps.get(callee).add(callerCmp.name)
}
this.deps.get(callerCmp).add(k)
return this.proxy[k]
}
}), Object.create(null))
},
validateDeps (callerCmp) {
if (this.deps.has(callerCmp)) {
this.deps.get(callerCmp).forEach(field => this.registry.has(field) && this.registry.get(field).performValidation())
}
},
hasValidationErrors () {
return Promise.all(this.registry.reduce((resolvers, cmp, name) => {
resolvers.push(cmp.performValidation() && cmp.getValidationErrors())
return resolvers
}, [])).then(errorObjects => errorObjects.some(item => item.hasErrors))
},
showErrors () {
this.childrenShouldShowErrors = true
this.registry.map(input => {
input.formShouldShowErrors = true
})
},
hideErrors () {
this.childrenShouldShowErrors = false
this.registry.map(input => {
input.formShouldShowErrors = false
input.behavioralErrorVisibility = false
})
},
setValues (values) {
// Collect all keys, existing and incoming
const keys = Array.from(new Set(Object.keys(values || {}).concat(Object.keys(this.proxy))))
keys.forEach(field => {
const input = this.registry.has(field) && this.registry.get(field)
let value = values ? values[field] : undefined
if (input && !equals(input.proxy, value, true)) {
input.context.model = value
}
if (!equals(value, this.proxy[field], true)) {
this.setFieldValue(field, value)
}
})
},
updateValidation (errorObject) {
if (has(this.registry.errors, errorObject.name)) {
this.registry.errors[errorObject.name] = errorObject.hasErrors
}
this.$emit('validation', errorObject)
},
addErrorObserver (observer) {
if (!this.errorObservers.find(obs => observer.callback === obs.callback)) {
this.errorObservers.push(observer)
if (observer.type === 'form') {
observer.callback(this.mergedFormErrors)
} else if (observer.type === 'group' && has(this.mergedGroupErrors, observer.field)) {
observer.callback(this.mergedGroupErrors[observer.field])
} else if (has(this.mergedFieldErrors, observer.field)) {
observer.callback(this.mergedFieldErrors[observer.field])
}
}
},
removeErrorObserver (observer) {
this.errorObservers = this.errorObservers.filter(obs => obs.callback !== observer)
}
}
return Object.keys(methods).reduce((withMethods, key) => {
return without.includes(key) ? withMethods : { ...withMethods, [key]: methods[key] }
}, {})
} |
JavaScript | function useRegistryProviders (ctx, without = []) {
const providers = {
formulateSetter: ctx.setFieldValue,
formulateRegister: ctx.register,
formulateDeregister: ctx.deregister,
formulateFieldValidation: ctx.updateValidation,
// Provided on forms only to let getFormValues to fall back to form
getFormValues: ctx.valueDeps,
// Provided on groups only to expose group-level items
getGroupValues: ctx.valueDeps,
validateDependents: ctx.validateDeps,
observeErrors: ctx.addErrorObserver,
removeErrorObserver: ctx.removeErrorObserver
}
const p = Object.keys(providers)
.filter(provider => !without.includes(provider))
.reduce((useProviders, provider) => Object.assign(useProviders, { [provider]: providers[provider] }), {})
return p
} | function useRegistryProviders (ctx, without = []) {
const providers = {
formulateSetter: ctx.setFieldValue,
formulateRegister: ctx.register,
formulateDeregister: ctx.deregister,
formulateFieldValidation: ctx.updateValidation,
// Provided on forms only to let getFormValues to fall back to form
getFormValues: ctx.valueDeps,
// Provided on groups only to expose group-level items
getGroupValues: ctx.valueDeps,
validateDependents: ctx.validateDeps,
observeErrors: ctx.addErrorObserver,
removeErrorObserver: ctx.removeErrorObserver
}
const p = Object.keys(providers)
.filter(provider => !without.includes(provider))
.reduce((useProviders, provider) => Object.assign(useProviders, { [provider]: providers[provider] }), {})
return p
} |
JavaScript | function camel (string) {
if (typeof string === 'string') {
return string.replace(/([_-][a-z0-9])/ig, ($1) => {
if (string.indexOf($1) !== 0 && !/[_-]/.test(string[string.indexOf($1) - 1])) {
return $1.toUpperCase().replace(/[_-]/, '')
}
return $1
})
}
return string
} | function camel (string) {
if (typeof string === 'string') {
return string.replace(/([_-][a-z0-9])/ig, ($1) => {
if (string.indexOf($1) !== 0 && !/[_-]/.test(string[string.indexOf($1) - 1])) {
return $1.toUpperCase().replace(/[_-]/, '')
}
return $1
})
}
return string
} |
JavaScript | function parseRules (validation, rules) {
if (typeof validation === 'string') {
return parseRules(validation.split('|'), rules)
}
if (!Array.isArray(validation)) {
return []
}
return validation.map(rule => parseRule(rule, rules)).filter(f => !!f)
} | function parseRules (validation, rules) {
if (typeof validation === 'string') {
return parseRules(validation.split('|'), rules)
}
if (!Array.isArray(validation)) {
return []
}
return validation.map(rule => parseRule(rule, rules)).filter(f => !!f)
} |
JavaScript | function regexForFormat (format) {
let escaped = `^${escapeRegExp(format)}$`
const formats = {
MM: '(0[1-9]|1[012])',
M: '([1-9]|1[012])',
DD: '([012][0-9]|3[01])',
D: '([012]?[0-9]|3[01])',
YYYY: '\\d{4}',
YY: '\\d{2}'
}
return new RegExp(Object.keys(formats).reduce((regex, format) => {
return regex.replace(format, formats[format])
}, escaped))
} | function regexForFormat (format) {
let escaped = `^${escapeRegExp(format)}$`
const formats = {
MM: '(0[1-9]|1[012])',
M: '([1-9]|1[012])',
DD: '([012][0-9]|3[01])',
D: '([012]?[0-9]|3[01])',
YYYY: '\\d{4}',
YY: '\\d{2}'
}
return new RegExp(Object.keys(formats).reduce((regex, format) => {
return regex.replace(format, formats[format])
}, escaped))
} |
JavaScript | function cloneDeep (obj) {
if (typeof obj !== 'object') {
return obj
}
const isArr = Array.isArray(obj)
const newObj = isArr ? [] : {}
for (const key in obj) {
if (obj[key] instanceof FileUpload || isValueType(obj[key])) {
newObj[key] = obj[key]
} else {
newObj[key] = cloneDeep(obj[key])
}
}
return newObj
} | function cloneDeep (obj) {
if (typeof obj !== 'object') {
return obj
}
const isArr = Array.isArray(obj)
const newObj = isArr ? [] : {}
for (const key in obj) {
if (obj[key] instanceof FileUpload || isValueType(obj[key])) {
newObj[key] = obj[key]
} else {
newObj[key] = cloneDeep(obj[key])
}
}
return newObj
} |
JavaScript | function extractAttributes (obj, keys) {
return Object.keys(obj).reduce((props, key) => {
const propKey = camel(key)
if (keys.includes(propKey)) {
props[propKey] = obj[key]
}
return props
}, {})
} | function extractAttributes (obj, keys) {
return Object.keys(obj).reduce((props, key) => {
const propKey = camel(key)
if (keys.includes(propKey)) {
props[propKey] = obj[key]
}
return props
}, {})
} |
JavaScript | values () {
return new Promise((resolve, reject) => {
const pending = []
const values = cloneDeep(this.form.proxy)
for (const key in values) {
if (typeof this.form.proxy[key] === 'object' && this.form.proxy[key] instanceof FileUpload) {
pending.push(
this.form.proxy[key].upload().then(data => Object.assign(values, { [key]: data }))
)
}
}
Promise.all(pending)
.then(() => resolve(values))
.catch(err => reject(err))
})
} | values () {
return new Promise((resolve, reject) => {
const pending = []
const values = cloneDeep(this.form.proxy)
for (const key in values) {
if (typeof this.form.proxy[key] === 'object' && this.form.proxy[key] instanceof FileUpload) {
pending.push(
this.form.proxy[key].upload().then(data => Object.assign(values, { [key]: data }))
)
}
}
Promise.all(pending)
.then(() => resolve(values))
.catch(err => reject(err))
})
} |
JavaScript | function logicalAddLabel () {
if (this.classification === 'file') {
return this.addLabel === true ? `+ Add ${cap(this.type)}` : this.addLabel
}
if (typeof this.addLabel === 'boolean') {
const label = this.label || this.name
return `+ ${typeof label === 'string' ? label + ' ' : ''} Add`
}
return this.addLabel
} | function logicalAddLabel () {
if (this.classification === 'file') {
return this.addLabel === true ? `+ Add ${cap(this.type)}` : this.addLabel
}
if (typeof this.addLabel === 'boolean') {
const label = this.label || this.name
return `+ ${typeof label === 'string' ? label + ' ' : ''} Add`
}
return this.addLabel
} |
JavaScript | function logicalRemoveLabel () {
if (typeof this.removeLabel === 'boolean') {
return 'Remove'
}
return this.removeLabel
} | function logicalRemoveLabel () {
if (typeof this.removeLabel === 'boolean') {
return 'Remove'
}
return this.removeLabel
} |
JavaScript | function filteredAttributes () {
const filterKeys = Object.keys(this.pseudoProps)
.concat(Object.keys(this.typeProps))
return Object.keys(this.localAttributes).reduce((props, key) => {
if (!filterKeys.includes(camel(key))) {
props[key] = this.localAttributes[key]
}
return props
}, {})
} | function filteredAttributes () {
const filterKeys = Object.keys(this.pseudoProps)
.concat(Object.keys(this.typeProps))
return Object.keys(this.localAttributes).reduce((props, key) => {
if (!filterKeys.includes(camel(key))) {
props[key] = this.localAttributes[key]
}
return props
}, {})
} |
JavaScript | function elementAttributes () {
const attrs = Object.assign({}, this.filteredAttributes)
// pass the ID prop through to the root element
if (this.id) {
attrs.id = this.id
} else {
attrs.id = this.defaultId
}
// pass an explicitly given name prop through to the root element
if (this.hasGivenName) {
attrs.name = this.name
}
// If there is help text, have this element be described by it.
if (this.help && !has(attrs, 'aria-describedby')) {
attrs['aria-describedby'] = `${attrs.id}-help`
}
// Ensure we dont have a class attribute unless we are actually applying classes.
if (this.classes.input && (!Array.isArray(this.classes.input) || this.classes.input.length)) {
attrs.class = this.classes.input
}
// @todo Filter out "local props" for custom inputs.
return attrs
} | function elementAttributes () {
const attrs = Object.assign({}, this.filteredAttributes)
// pass the ID prop through to the root element
if (this.id) {
attrs.id = this.id
} else {
attrs.id = this.defaultId
}
// pass an explicitly given name prop through to the root element
if (this.hasGivenName) {
attrs.name = this.name
}
// If there is help text, have this element be described by it.
if (this.help && !has(attrs, 'aria-describedby')) {
attrs['aria-describedby'] = `${attrs.id}-help`
}
// Ensure we dont have a class attribute unless we are actually applying classes.
if (this.classes.input && (!Array.isArray(this.classes.input) || this.classes.input.length)) {
attrs.class = this.classes.input
}
// @todo Filter out "local props" for custom inputs.
return attrs
} |
JavaScript | function classes () {
return this.$formulate.classes({
...this.$props,
...this.pseudoProps,
...{
attrs: this.filteredAttributes,
classification: this.classification,
hasErrors: this.hasVisibleErrors,
hasValue: this.hasValue,
helpPosition: this.logicalHelpPosition,
isValid: this.isValid,
labelPosition: this.logicalLabelPosition,
type: this.type,
value: this.proxy
}
})
} | function classes () {
return this.$formulate.classes({
...this.$props,
...this.pseudoProps,
...{
attrs: this.filteredAttributes,
classification: this.classification,
hasErrors: this.hasVisibleErrors,
hasValue: this.hasValue,
helpPosition: this.logicalHelpPosition,
isValid: this.isValid,
labelPosition: this.logicalLabelPosition,
type: this.type,
value: this.proxy
}
})
} |
JavaScript | function logicalHelpPosition () {
if (this.helpPosition) {
return this.helpPosition
}
switch (this.classification) {
case 'group':
return 'before'
default:
return 'after'
}
} | function logicalHelpPosition () {
if (this.helpPosition) {
return this.helpPosition
}
switch (this.classification) {
case 'group':
return 'before'
default:
return 'after'
}
} |
JavaScript | function mergedValidationName () {
const strategy = this.$formulate.options.validationNameStrategy || ['validationName', 'name', 'label', 'type']
if (Array.isArray(strategy)) {
const key = strategy.find(key => typeof this[key] === 'string')
return this[key]
}
if (typeof strategy === 'function') {
return strategy.call(this, this)
}
return this.type
} | function mergedValidationName () {
const strategy = this.$formulate.options.validationNameStrategy || ['validationName', 'name', 'label', 'type']
if (Array.isArray(strategy)) {
const key = strategy.find(key => typeof this[key] === 'string')
return this[key]
}
if (typeof strategy === 'function') {
return strategy.call(this, this)
}
return this.type
} |
JavaScript | function mergedGroupErrors () {
const keys = Object.keys(this.groupErrors).concat(Object.keys(this.localGroupErrors))
const isGroup = /^(\d+)\.(.*)$/
// Using new Set() to remove duplicates.
return Array.from(new Set(keys))
.filter(k => isGroup.test(k))
.reduce((groupErrors, fieldKey) => {
let [, index, subField] = fieldKey.match(isGroup)
if (!has(groupErrors, index)) {
groupErrors[index] = {}
}
const fieldErrors = Array.from(new Set(
arrayify(this.groupErrors[fieldKey]).concat(arrayify(this.localGroupErrors[fieldKey]))
))
groupErrors[index] = Object.assign(groupErrors[index], { [subField]: fieldErrors })
return groupErrors
}, {})
} | function mergedGroupErrors () {
const keys = Object.keys(this.groupErrors).concat(Object.keys(this.localGroupErrors))
const isGroup = /^(\d+)\.(.*)$/
// Using new Set() to remove duplicates.
return Array.from(new Set(keys))
.filter(k => isGroup.test(k))
.reduce((groupErrors, fieldKey) => {
let [, index, subField] = fieldKey.match(isGroup)
if (!has(groupErrors, index)) {
groupErrors[index] = {}
}
const fieldErrors = Array.from(new Set(
arrayify(this.groupErrors[fieldKey]).concat(arrayify(this.localGroupErrors[fieldKey]))
))
groupErrors[index] = Object.assign(groupErrors[index], { [subField]: fieldErrors })
return groupErrors
}, {})
} |
JavaScript | function hasValue () {
const value = this.proxy
if (
(this.classification === 'box' && this.isGrouped) ||
(this.classification === 'select' && has(this.filteredAttributes, 'multiple'))
) {
return Array.isArray(value) ? value.some(v => v === this.value) : this.value === value
}
return !isEmpty(value)
} | function hasValue () {
const value = this.proxy
if (
(this.classification === 'box' && this.isGrouped) ||
(this.classification === 'select' && has(this.filteredAttributes, 'multiple'))
) {
return Array.isArray(value) ? value.some(v => v === this.value) : this.value === value
}
return !isEmpty(value)
} |
JavaScript | function isVmodeled () {
return !!(this.$options.propsData.hasOwnProperty('formulateValue') &&
this._events &&
Array.isArray(this._events.input) &&
this._events.input.length)
} | function isVmodeled () {
return !!(this.$options.propsData.hasOwnProperty('formulateValue') &&
this._events &&
Array.isArray(this._events.input) &&
this._events.input.length)
} |
JavaScript | function explicitErrors () {
return arrayify(this.errors)
.concat(this.localErrors)
.concat(arrayify(this.error))
} | function explicitErrors () {
return arrayify(this.errors)
.concat(this.localErrors)
.concat(arrayify(this.error))
} |
JavaScript | function hasVisibleErrors () {
return (
(Array.isArray(this.validationErrors) && this.validationErrors.length && this.showValidationErrors) ||
!!this.explicitErrors.length
)
} | function hasVisibleErrors () {
return (
(Array.isArray(this.validationErrors) && this.validationErrors.length && this.showValidationErrors) ||
!!this.explicitErrors.length
)
} |
JavaScript | function slotComponents () {
const fn = this.$formulate.slotComponent.bind(this.$formulate)
return {
addMore: fn(this.type, 'addMore'),
buttonContent: fn(this.type, 'buttonContent'),
errors: fn(this.type, 'errors'),
file: fn(this.type, 'file'),
help: fn(this.type, 'help'),
label: fn(this.type, 'label'),
prefix: fn(this.type, 'prefix'),
remove: fn(this.type, 'remove'),
repeatable: fn(this.type, 'repeatable'),
suffix: fn(this.type, 'suffix'),
uploadAreaMask: fn(this.type, 'uploadAreaMask')
}
} | function slotComponents () {
const fn = this.$formulate.slotComponent.bind(this.$formulate)
return {
addMore: fn(this.type, 'addMore'),
buttonContent: fn(this.type, 'buttonContent'),
errors: fn(this.type, 'errors'),
file: fn(this.type, 'file'),
help: fn(this.type, 'help'),
label: fn(this.type, 'label'),
prefix: fn(this.type, 'prefix'),
remove: fn(this.type, 'remove'),
repeatable: fn(this.type, 'repeatable'),
suffix: fn(this.type, 'suffix'),
uploadAreaMask: fn(this.type, 'uploadAreaMask')
}
} |
JavaScript | function slotProps () {
const fn = this.$formulate.slotProps.bind(this.$formulate)
return {
label: fn(this.type, 'label', this.typeProps),
help: fn(this.type, 'help', this.typeProps),
errors: fn(this.type, 'errors', this.typeProps),
repeatable: fn(this.type, 'repeatable', this.typeProps),
addMore: fn(this.type, 'addMore', this.typeProps),
remove: fn(this.type, 'remove', this.typeProps),
component: fn(this.type, 'component', this.typeProps)
}
} | function slotProps () {
const fn = this.$formulate.slotProps.bind(this.$formulate)
return {
label: fn(this.type, 'label', this.typeProps),
help: fn(this.type, 'help', this.typeProps),
errors: fn(this.type, 'errors', this.typeProps),
repeatable: fn(this.type, 'repeatable', this.typeProps),
addMore: fn(this.type, 'addMore', this.typeProps),
remove: fn(this.type, 'remove', this.typeProps),
component: fn(this.type, 'component', this.typeProps)
}
} |
JavaScript | function blurHandler () {
if (this.errorBehavior === 'blur' || this.errorBehavior === 'value') {
this.behavioralErrorVisibility = true
}
this.$nextTick(() => this.$emit('blur-context', this.context))
} | function blurHandler () {
if (this.errorBehavior === 'blur' || this.errorBehavior === 'value') {
this.behavioralErrorVisibility = true
}
this.$nextTick(() => this.$emit('blur-context', this.context))
} |
JavaScript | function defineModel (context) {
return Object.defineProperty(context, 'model', {
get: modelGetter.bind(this),
set: (value) => {
if (!this.mntd || !this.debounceDelay) {
return modelSetter.call(this, value)
}
this.dSet(modelSetter, [value], this.debounceDelay)
},
enumerable: true
})
} | function defineModel (context) {
return Object.defineProperty(context, 'model', {
get: modelGetter.bind(this),
set: (value) => {
if (!this.mntd || !this.debounceDelay) {
return modelSetter.call(this, value)
}
this.dSet(modelSetter, [value], this.debounceDelay)
},
enumerable: true
})
} |
JavaScript | function modelGetter () {
const model = this.isVmodeled ? 'formulateValue' : 'proxy'
if (this.type === 'checkbox' && !Array.isArray(this[model]) && this.options) {
return []
}
if (!this[model] && this[model] !== 0) {
return ''
}
return this[model]
} | function modelGetter () {
const model = this.isVmodeled ? 'formulateValue' : 'proxy'
if (this.type === 'checkbox' && !Array.isArray(this[model]) && this.options) {
return []
}
if (!this[model] && this[model] !== 0) {
return ''
}
return this[model]
} |
JavaScript | function modelSetter (value) {
let didUpdate = false
if (!equals(value, this.proxy, this.type === 'group')) {
this.proxy = value
didUpdate = true
}
if (!this.context.ignored && this.context.name && typeof this.formulateSetter === 'function') {
this.formulateSetter(this.context.name, value)
}
if (didUpdate) {
this.$emit('input', value)
}
} | function modelSetter (value) {
let didUpdate = false
if (!equals(value, this.proxy, this.type === 'group')) {
this.proxy = value
didUpdate = true
}
if (!this.context.ignored && this.context.name && typeof this.formulateSetter === 'function') {
this.formulateSetter(this.context.name, value)
}
if (didUpdate) {
this.$emit('input', value)
}
} |
JavaScript | extend (extendWith) {
if (typeof extendWith === 'object') {
this.options = this.merge(this.options, extendWith)
return this
}
throw new Error(`Formulate.extend expects an object, was ${typeof extendWith}`)
} | extend (extendWith) {
if (typeof extendWith === 'object') {
this.options = this.merge(this.options, extendWith)
return this
}
throw new Error(`Formulate.extend expects an object, was ${typeof extendWith}`)
} |
JavaScript | classes (classContext) {
// Step 1: We get the global classes for all keys.
const coreClasses = this.options.coreClasses(classContext)
// Step 2: We extend those classes with a user defined baseClasses.
const baseClasses = this.options.baseClasses(coreClasses, classContext)
return Object.keys(baseClasses).reduce((classMap, key) => {
// Step 3: For each key, apply any global overrides for that key.
let classesForKey = applyClasses(baseClasses[key], this.options.classes[key], classContext)
// Step 4: Apply any prop-level overrides for that key.
classesForKey = applyClasses(classesForKey, classContext[`${key}Class`], classContext)
// Step 5: Add state based classes from props.
classesForKey = applyStates(key, classesForKey, this.options.classes, classContext)
// Now we have our final classes, assign to the given key.
return Object.assign(classMap, { [key]: classesForKey })
}, {})
} | classes (classContext) {
// Step 1: We get the global classes for all keys.
const coreClasses = this.options.coreClasses(classContext)
// Step 2: We extend those classes with a user defined baseClasses.
const baseClasses = this.options.baseClasses(coreClasses, classContext)
return Object.keys(baseClasses).reduce((classMap, key) => {
// Step 3: For each key, apply any global overrides for that key.
let classesForKey = applyClasses(baseClasses[key], this.options.classes[key], classContext)
// Step 4: Apply any prop-level overrides for that key.
classesForKey = applyClasses(classesForKey, classContext[`${key}Class`], classContext)
// Step 5: Add state based classes from props.
classesForKey = applyStates(key, classesForKey, this.options.classes, classContext)
// Now we have our final classes, assign to the given key.
return Object.assign(classMap, { [key]: classesForKey })
}, {})
} |
JavaScript | validationMessage (rule, validationContext, vm) {
const generators = this.options.locales[this.getLocale(vm)]
if (generators.hasOwnProperty(rule)) {
return generators[rule](validationContext)
}
if (generators.hasOwnProperty('default')) {
return generators.default(validationContext)
}
return 'Invalid field value'
} | validationMessage (rule, validationContext, vm) {
const generators = this.options.locales[this.getLocale(vm)]
if (generators.hasOwnProperty(rule)) {
return generators[rule](validationContext)
}
if (generators.hasOwnProperty('default')) {
return generators.default(validationContext)
}
return 'Invalid field value'
} |
JavaScript | function applyClasses (baseClass, modifier, context) {
switch (typeof modifier) {
case 'string':
return modifier
case 'function':
return modifier(context, arrayify(baseClass))
case 'object':
if (Array.isArray(modifier)) {
return arrayify(baseClass).concat(modifier)
}
/** allow fallthrough if object that isn’t an array */
default:
return baseClass
}
} | function applyClasses (baseClass, modifier, context) {
switch (typeof modifier) {
case 'string':
return modifier
case 'function':
return modifier(context, arrayify(baseClass))
case 'object':
if (Array.isArray(modifier)) {
return arrayify(baseClass).concat(modifier)
}
/** allow fallthrough if object that isn’t an array */
default:
return baseClass
}
} |
JavaScript | function applyStates (elementKey, baseClass, globals, context) {
return Object.keys(states).reduce((classes, stateKey) => {
// Step 1. Call the state function to determine if it has this state
if (states[stateKey](context)) {
const key = `${elementKey}${cap(stateKey)}`
const propKey = `${key}Class`
// Step 2. Apply any global state class keys
if (globals[key]) {
const modifier = (typeof globals[key] === 'string') ? arrayify(globals[key]) : globals[key]
classes = applyClasses(classes, modifier, context)
}
// Step 3. Apply any prop state class keys
if (context[propKey]) {
const modifier = (typeof context[propKey] === 'string') ? arrayify(context[propKey]) : context[`${key}Class`]
classes = applyClasses(classes, modifier, context)
}
}
return classes
}, baseClass)
} | function applyStates (elementKey, baseClass, globals, context) {
return Object.keys(states).reduce((classes, stateKey) => {
// Step 1. Call the state function to determine if it has this state
if (states[stateKey](context)) {
const key = `${elementKey}${cap(stateKey)}`
const propKey = `${key}Class`
// Step 2. Apply any global state class keys
if (globals[key]) {
const modifier = (typeof globals[key] === 'string') ? arrayify(globals[key]) : globals[key]
classes = applyClasses(classes, modifier, context)
}
// Step 3. Apply any prop state class keys
if (context[propKey]) {
const modifier = (typeof context[propKey] === 'string') ? arrayify(context[propKey]) : context[`${key}Class`]
classes = applyClasses(classes, modifier, context)
}
}
return classes
}, baseClass)
} |
JavaScript | function removeIngredient () {
//Select the value to be removed by looking at the value of the button clicked
var itemToRemove = $(this).closest("div").attr('id');
//Save a new array of items by removing the deleted item
ingredForQuery = arrayRemove(ingredientList, itemToRemove);
//Remove from ingredient list
$(this).closest("div").remove();
ingredientList = ingredForQuery;
console.log(itemToRemove);
console.log("After remove: "+ ingredForQuery);
console.log(ingredientList);
} | function removeIngredient () {
//Select the value to be removed by looking at the value of the button clicked
var itemToRemove = $(this).closest("div").attr('id');
//Save a new array of items by removing the deleted item
ingredForQuery = arrayRemove(ingredientList, itemToRemove);
//Remove from ingredient list
$(this).closest("div").remove();
ingredientList = ingredForQuery;
console.log(itemToRemove);
console.log("After remove: "+ ingredForQuery);
console.log(ingredientList);
} |
JavaScript | function arrayRemove(arr, value) {
return arr.filter(function(ele) {
return ele != value;
})
} | function arrayRemove(arr, value) {
return arr.filter(function(ele) {
return ele != value;
})
} |
JavaScript | function searchRecipes(num, arr) {
var queryURLRecipes = "https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/findByIngredients?number=" + num + "&ranking=1&ingredients=" ;
console.log(queryURLRecipes);
//Add the ingredients from the user list to the query url
for (var i=0; i<arr.length;i++) {
queryURLRecipes = queryURLRecipes + "%2C" + arr[i];
}
var row = $("<div class='row'>")
$.ajax({
url: queryURLRecipes,
method: "GET",
headers: ({"X-Mashape-Key": apiKey})
}).then(function(results) {
//Append recipes data to one column
for (var j=0; j<num; j++) {
var divCard = $('<div class="col">');
// var imageCard = $('<img class="card-img-top recipeCard" id="' + results[j].id + '">');REMOVED SHER
var imageCard = $('<img class="card-img-top recipeCard">');
var bodyCard = $('<div class="card-body">');
var titleCard = $('<h5 class="card-title">');
titleCard.text(results[j].title);
imageCard.attr("src", results[j].image);
imageCard.attr("data-recipe-id", results[j].id);
bodyCard.append(titleCard);
divCard.append(imageCard, bodyCard);
row.append(divCard)
$("#recipe-list").append(row);
}
})
} | function searchRecipes(num, arr) {
var queryURLRecipes = "https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/findByIngredients?number=" + num + "&ranking=1&ingredients=" ;
console.log(queryURLRecipes);
//Add the ingredients from the user list to the query url
for (var i=0; i<arr.length;i++) {
queryURLRecipes = queryURLRecipes + "%2C" + arr[i];
}
var row = $("<div class='row'>")
$.ajax({
url: queryURLRecipes,
method: "GET",
headers: ({"X-Mashape-Key": apiKey})
}).then(function(results) {
//Append recipes data to one column
for (var j=0; j<num; j++) {
var divCard = $('<div class="col">');
// var imageCard = $('<img class="card-img-top recipeCard" id="' + results[j].id + '">');REMOVED SHER
var imageCard = $('<img class="card-img-top recipeCard">');
var bodyCard = $('<div class="card-body">');
var titleCard = $('<h5 class="card-title">');
titleCard.text(results[j].title);
imageCard.attr("src", results[j].image);
imageCard.attr("data-recipe-id", results[j].id);
bodyCard.append(titleCard);
divCard.append(imageCard, bodyCard);
row.append(divCard)
$("#recipe-list").append(row);
}
})
} |
JavaScript | function showRecipe(num) {
$("#recipes-page").empty();
$("#restaurants").empty();
var queryURLinstr = "https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/" + num + "/information"
$.ajax({
url: queryURLinstr,
method: "GET",
headers: ({"X-Mashape-Key": apiKey})
}).then(function(result) {
var divRecipe = $('<div>');
var title = $("<h5>");
//Added heart button for favorites lists
var heartButton = $('<span id="favoritePick" style="font-size: 2em; color: white"><i class="fas fa-heart"></i></span>');
var details = $("<p class='lead'>");
var ingredList = $("<ul>");
var steps = $("<ol>");
if (result.analyzedInstructions.length != 0) {
title.text(result.title);
heartButton.attr("data-favorite", result.id);
details.text("Servings: " + result.servings + " Preparation time: " + result.readyInMinutes);
for (var i=0;i<result.extendedIngredients.length;i++) {
ingredList.append("<li>" + result.extendedIngredients[i].originalString + "</li>");
}
for (var k=0;k<result.analyzedInstructions[0].steps.length;k++) {
steps.append("<li>" + result.analyzedInstructions[0].steps[k].step + "</li>");
}
if(result.cuisines.length != 0) {
console.log("Cuisines " + result.cuisines[0]);
showRestaurants(cityForRestaurants, result.cuisines[0]);
} else if (result.diets.length != 0) {
console.log("Diets" + result.diets[0]);
showRestaurants(cityForRestaurants, result.diets[0]);
} else {
title.text("Try another recipe to see restaurants");
$(".recipes").show();
$("#recipes-page").append(title);
}
$("#recipes-page").show();
divRecipe.append(title, heartButton, details, ingredList, steps);
$("#recipes-page").append(divRecipe);
} else {
title.text("This recipe is no longer available. Try another one");
$("#recipes-page").show();
$("#recipes-page").append(title);
}
console.log(result);
});
} | function showRecipe(num) {
$("#recipes-page").empty();
$("#restaurants").empty();
var queryURLinstr = "https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/" + num + "/information"
$.ajax({
url: queryURLinstr,
method: "GET",
headers: ({"X-Mashape-Key": apiKey})
}).then(function(result) {
var divRecipe = $('<div>');
var title = $("<h5>");
//Added heart button for favorites lists
var heartButton = $('<span id="favoritePick" style="font-size: 2em; color: white"><i class="fas fa-heart"></i></span>');
var details = $("<p class='lead'>");
var ingredList = $("<ul>");
var steps = $("<ol>");
if (result.analyzedInstructions.length != 0) {
title.text(result.title);
heartButton.attr("data-favorite", result.id);
details.text("Servings: " + result.servings + " Preparation time: " + result.readyInMinutes);
for (var i=0;i<result.extendedIngredients.length;i++) {
ingredList.append("<li>" + result.extendedIngredients[i].originalString + "</li>");
}
for (var k=0;k<result.analyzedInstructions[0].steps.length;k++) {
steps.append("<li>" + result.analyzedInstructions[0].steps[k].step + "</li>");
}
if(result.cuisines.length != 0) {
console.log("Cuisines " + result.cuisines[0]);
showRestaurants(cityForRestaurants, result.cuisines[0]);
} else if (result.diets.length != 0) {
console.log("Diets" + result.diets[0]);
showRestaurants(cityForRestaurants, result.diets[0]);
} else {
title.text("Try another recipe to see restaurants");
$(".recipes").show();
$("#recipes-page").append(title);
}
$("#recipes-page").show();
divRecipe.append(title, heartButton, details, ingredList, steps);
$("#recipes-page").append(divRecipe);
} else {
title.text("This recipe is no longer available. Try another one");
$("#recipes-page").show();
$("#recipes-page").append(title);
}
console.log(result);
});
} |
JavaScript | function showRestaurants(string1, string2){
var queryURLrest = "https://ancient-ocean-97660.herokuapp.com/foursquareWrapper?city=" + string1 + "&query=" + string2;
var settings = {
"async": true,
"url": queryURLrest,
"method": "GET",
"headers": {
"Content-Type": "application/json",
"cache-control": "no-cache",
"Postman-Token": "f1aabd14-c1f5-4f45-b2e4-a88fadeddc62"
},
"processData": false,
"data": ""
}
console.log(settings);
$.ajax(settings).done(function (results) {
var restaurants = results.response.venues;
console.log(restaurants);
// Looping through each result item
for (var i = 0; i < 5; i++) {
// Creating and storing a div tag
var restaurantHead = $("<h5>");
restaurantHead.text(restaurants[i].name);
$('#restaurants').append(restaurantHead);
}
});
} | function showRestaurants(string1, string2){
var queryURLrest = "https://ancient-ocean-97660.herokuapp.com/foursquareWrapper?city=" + string1 + "&query=" + string2;
var settings = {
"async": true,
"url": queryURLrest,
"method": "GET",
"headers": {
"Content-Type": "application/json",
"cache-control": "no-cache",
"Postman-Token": "f1aabd14-c1f5-4f45-b2e4-a88fadeddc62"
},
"processData": false,
"data": ""
}
console.log(settings);
$.ajax(settings).done(function (results) {
var restaurants = results.response.venues;
console.log(restaurants);
// Looping through each result item
for (var i = 0; i < 5; i++) {
// Creating and storing a div tag
var restaurantHead = $("<h5>");
restaurantHead.text(restaurants[i].name);
$('#restaurants').append(restaurantHead);
}
});
} |
JavaScript | function showFavoriteRecipes(num) {
$("#results-page").hide();
$("#recipes-page").hide();
var queryURLfavs = "https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/" + num + "/information"
$.ajax({
url: queryURLfavs,
method: "GET",
headers: ({"X-Mashape-Key": apiKey})
}).then(function(results) {
var divCard = $('<div class="col">');
var imageCard = $('<img class="card-img-top favoriteCard">');
var bodyCard = $('<div class="card-body">');
var titleCard = $('<h5 class="card-title">');
titleCard.text(results.title);
imageCard.attr("src", results.image);
imageCard.attr("data-recipe-id", results.id);
bodyCard.append(titleCard);
divCard.append(imageCard, bodyCard);
$("#favorites-list").append(divCard);
})
} | function showFavoriteRecipes(num) {
$("#results-page").hide();
$("#recipes-page").hide();
var queryURLfavs = "https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/" + num + "/information"
$.ajax({
url: queryURLfavs,
method: "GET",
headers: ({"X-Mashape-Key": apiKey})
}).then(function(results) {
var divCard = $('<div class="col">');
var imageCard = $('<img class="card-img-top favoriteCard">');
var bodyCard = $('<div class="card-body">');
var titleCard = $('<h5 class="card-title">');
titleCard.text(results.title);
imageCard.attr("src", results.image);
imageCard.attr("data-recipe-id", results.id);
bodyCard.append(titleCard);
divCard.append(imageCard, bodyCard);
$("#favorites-list").append(divCard);
})
} |
Subsets and Splits