User:Cephalon Scientia/common.js

// Automating display of active Nightwave acts using an API // For use in Warframe Wikia, particular in the following page: // https://warframe.fandom.com/wiki/Nightwave/Acts_Currently_Available // Created by User:Cephalon Scientia // Made in JavaScript + jQuery 3.3.1 // Fork code at https://jsfiddle.net/chao_/j4yhe0vg/

// Wikia's JS parser doesn't support string interpolation nor let keyword

/* Cephalon Scientia Nightwave Current Acts */ const WIKI_IMG_URL = 'https://vignette.wikia.nocookie.net/warframe/images/'; const API_URL = 'https://api.warframestat.us/pc/nightwave'; const REP_IMG_URL = WIKI_IMG_URL + '9/92/ReputationLargeBlack.png/revision/latest/scale-to-width-down/20?cb=20141029201703'; // scaled down image

const ActTypeEnum = { 'DAILY': 1, 'WEEKLY': 2, 'ELITE_WEEKLY': 3 }; Object.freeze(ActTypeEnum); // for immutability

// Fetching act image maps from a page outside of MediaWiki namespace // so won't have to update this code everytime new Nightwave acts are added // or if they need to be modified // equivalent to https://warframe.fandom.com/api.php?action=parse&page=Module:NightwaveActs&format=xml var api = new mw.Api; var jsonMap;   // for storing act image map in json format

api.get({   action: 'parse',    page: 'Module:NightwaveActs',    format: 'json' }).done(function(data) {    console.log('Inside done function');    console.log(data);    console.log(data.parse.text['*']);    jsonMap = data.parse.text['*'];    // type string    // actual data is encapsulated between two block comment symbols in Lua    jsonMap = jsonMap.substring(jsonMap.indexOf('--') + 4, jsonMap.indexOf('--'));    console.log(jsonMap);    // removing any trace or tags so string can be converted to JSON    jsonMap = jsonMap.replace(/(<.+>)/g, '');    console.log(jsonMap);    jsonMap = JSON.parse(jsonMap);    console.log(jsonMap); });

console.log('Outside of api.get');

// To map out act name to associated image in wiki // Keys are in alphabetical order, values are hexidecimal values with image name // to be concatenated to https://vignette.wikia.nocookie.net/warframe/images/ // Some acts don't have image so their values are links to a placeholder image const DAILY_ACT_IMG_MAP = new Map([   ['Accelerator', '3/38/KillEnemiesWhileSliding.png'],    ['Agent', '1/14/CompleteAnyMission.png/'],    ['Air It Out', '4/47/Placeholder.png'],    ['Arsonist', 'f/fe/KillEnemiesDamageTypeFire.png'],    ['Attractive', '4/47/KillEnemiesDamageTypeMagnetic.png'],    ['Biohazard', '7/7e/KillEnemiesDamageTypeGas.png'],    ['Communicator', '5/5d/PlaceWaypoint.png'],    ['Deep Freeze', '4/4b/KillEnemiesDamageTypeCold.png'],    ['Detonator', 'c/c3/KillEnemiesDamageTypeBlast.png'],    ['Energizing', 'a/ac/EnergyOrbs.png'],    ['Everything Old is New Again', ''],    ['Executioner', 'c/ca/KillEnemiesFinishingMoves.png'],    ['Expressive', 'f/f2/PerformEmote.png'],    ['Glider', '1/1d/AimGlide.png'],    ['Grafitti', '8/87/PlaceGlyph.png'],    ['Hacker', '7/75/SolveCipher.png'],    ['Kleptomaniac', '0/0d/OpenLootLocker.png'],    ['Loyalty', '4/47/Placeholder.png'], ['Marksman', '3/3a/GetHeadshots.png'], ['Meltdown', 'e/e0/KillEnemiesDamageTypeCorrosive.png'], ['Mow Them Down', '9/9a/KillEnemiesWithPrimary.png'], ['Poisoner', '5/5a/KillEnemiesDamageTypePoison.png'], ['Power Trip', '9/93/KillEnemiesWithAbilities.png'], ['Reactor', '4/4b/KillEnemiesDamageTypeRadiation.png'], ['Researcher', '0/01/CodexScan.png'], ['Saver', '3/30/CollectCredits.png'], ['Sharing is Caring', '4/4e/KillEnemiesDamageTypeViral.png'], ['Shiny', 'a/a2/FindMod.png'], ['Short Circuit', '8/8a/KillEnemiesDamageTypeElectricty.png'], ['Smaller Is Bigger', 'f/f4/KillEnemiesWithSecondary.png'], ['Sword Dance', 'd/df/KillEnemiesWithMelee.png'], ['The Hunt is On', '4/47/Placeholder.png'], ['Trampoline', 'a/aa/BulletJump.png'], ['Warning Shot', 'a/a7/KillEnemies.png'], ]);

const WEEKLY_ACT_IMG_MAP = new Map([   ['Animator', 'a/a4/AyatanSculptures.png'],    ['Assassin', '6/66/CompleteMissionTypesAssassination.png'],    ['Cache Hunter', 'c/ce/SabotageCaches.png'],    ['Conservationist', '5/53/PerfectConservations.png'],    ['Don\'t Blow It', '4/47/Placeholder.png'],    ['Don\'t Fear The Reaper', '4/47/Placeholder.png'],    ['Earth Bounty Hunter', 'f/f9/BountiesPoE.png'],    ['Earth Fisher', '2/29/RareFishPoE.png'],    ['Earth Miner', 'f/f3/MineGemsPoE.png'],    ['Eliminator', '1/1f/MissionsOfXType.png'],    ['Enhance!', '7/79/AcquireRareMods.png'],    ['Eximus Eliminator', '2/22/KillEnemiesWeekly.png'],    ['Good Friend', '7/77/HelpClem.png'],    ['Invader', '9/9a/InvasionMissions.png'],    ['Jailer', '8/8a/CompleteMissionTypesCapture.png'],    ['Not a Warning Shot', '2/22/KillEnemiesWeekly.png'],    ['Now Boarding', '4/47/Placeholder.png'],    ['Operative', 'e/ec/CompleteMissionTypesSpy.png'], ['Polarized', 'b/b8/FormaWeapons.png'], ['Protector', '3/3f/CompleteMissionTypeDefense.png'], ['Rescuer', 'f/fd/CompleteMissionTypesRescue.png'], ['Saboteur', '2/20/CompleteMissionTypesSabotage.png'], ['Sanctuary Researcher', 'a/a0/SynthesizeSimarisTargets.png'], ['Sound Sleeper', 'f/f4/NightmareMissions.png'], ['Sortie Specialist', '1/1e/SortieWarframe.png'], ['Supporter', '0/0c/SyndicateDailies.png'], ['Test Subject', 'a/a0/Weekly_EliteSanctuaryOnslaught.png'], ['Tusk Thumpin\'', '4/47/Placeholder.png'], ['Unlock Relics', '5/53/UnlockRelics.png'], ['Vault Looter', '0/01/UnlockDragonVaults.png'], ['Venus Bounty Hunter', 'b/b3/BountiesOrbVallis.png'], ['Venus Fisher', 'd/d2/RareFishOrbVallis.png'], ['Venus Miner', '8/86/MineGemsOrbVallis.png'], ]);

const ELITE_ACT_IMG_MAP = new Map([   ['Ascendant', '2/2b/HallsOfAscension.png'],    ['Day Trader', '3/39/IndexRounds.png'],    ['Defense', '3/31/DefenseMissionWaveXWithFriendsClan.png'],    ['Elite Test Subject', 'd/db/EliteSanctuaryOnslaught.png'],    ['Eximus Executioner', '5/5d/KillEnemiesHardcore.png'],    ['Flying High', '4/47/Placeholder.png'],    ['Grove Guardian', '5/5d/KillEnemiesHardcore.png'],    ['Hold Your Breath', '1/11/KuvaSurvival.png'], // typo in description in API    ['Hydrolyst Hunter', 'c/c0/Hydrolists.png'],    ['Kill Profit-Taker', '7/71/OrbHeistFullParty.png'],    ['Kill Shot', '5/5d/KillEnemiesHardcore.png'],    ['Night Terror', 'a/ac/NightmareMissionsHardcore.png'],    ['Silent Eliminator', 'c/c6/ExterminationWithoutAlarms.png'],    ['Sortie Expert', '9/9e/Hardcore_Sortie.png'],    ['Survival', 'a/ab/HighLevelSurvivalWithFriendsClan.png'],    ['Unlock Relics', '5/59/UnlockRelicsHardcore.png'], ['Walk Without Rhythm', '4/47/Placeholder.png'], ]);

$(document).ready(function { var $resultElem = $(document.getElementById('nightwave_acts'));

// Adding tabber navigation and starting div tags for tabber // Styling based on: // https://stackoverflow.com/questions/9760328/clearest-way-to-build-html-elements-in-jquery // Code block can be collapsed in this styling $resultElem.append($([ ' ',   ' ',    '', '♦ Daily', ' ', '', '♦♦ Weekly', ' ', '', '♦♦♦ Elite Weekly', ' ', '' ].join('\n')).prop('outerHTML'));

// Using Fetch API to get JSON on current Nightwave acts fetch(API_URL) .then(function(response) {     return response.json;    }) // response is a Body object .then(function(data) {     // Work with data here      data.activeChallenges.forEach(function(actJSON) { var actType; var actImgURL; var idAttr; var titleAttr;

if (actJSON.isDaily) { actType = ActTypeEnum.DAILY; } else if (!actJSON.isElite) { actType = ActTypeEnum.WEEKLY; } else { actType = ActTypeEnum.ELITE_WEEKLY; }

// Initializing idAttr, titleAttr, and actImgURL switch (actType) { case ActTypeEnum.DAILY: idAttr = 'daily_acts'; titleAttr = '♦ Daily'; actImgURL = WIKI_IMG_URL + DAILY_ACT_IMG_MAP.get(actJSON.title); break;

case ActTypeEnum.WEEKLY: idAttr = 'weekly_acts'; titleAttr = '♦♦ Weekly'; actImgURL = WIKI_IMG_URL + WEEKLY_ACT_IMG_MAP.get(actJSON.title); break;

case ActTypeEnum.ELITE_WEEKLY: idAttr = 'elite_acts'; titleAttr = '♦♦♦ Elite Weekly'; actImgURL = WIKI_IMG_URL + ELITE_ACT_IMG_MAP.get(actJSON.title); break; }

// Adding table // Add table if a div element with id associated with act type is not found // One table per act type if ($resultElem.find('#' + idAttr).length === 0) { /* HTML of jQuery statements ``, ' ',          	' ',          	' ',          	' ',          		' Icon ', ' Description ', ' Reward ', ' End Time ', ' '         */          $resultElem.find('.tabber, .tabberlive').append($(' ', { id: idAttr, class: 'tabbertab', title: titleAttr, style: 'display: block;', append: [ $(' '),             $(' ', {                class: 'emodtable',                style: 'width:100%;',                append: [                  $(' ', { append: [ $(' ', {                       append: [                          $(' ').text('Icon'),                          $(' ').text('Description'),                          $(' ').text('Reward'),                          (actType === ActTypeEnum.DAILY) ? $(' ').text('End Time') : null,                        ]                      }) ]                 })                ]              })            ]          }));        }

// Adding table row /* HTML of jQuery statements ' ',       		'  ',        			``, ``, '</a>', '  ',        		' ',        			`${actName} `, `${actDesc}`, ' ',       		' ',        			` ${actRep} `, '', `<img src="${REP_IMG_URL}" width="20" height="20">`, '</a>', `${actRep.toLocaleString}`, ' ',       		`  `,        	' '        */        $resultElem.find('#' + idAttr).find('.emodtable').append($(' ', { append: [ $(' ', {             append: [                $(' ', { class: 'center floatnone', append: [ $('', {                     href: actImgURL,                      class: 'image image-thumbnail',                      append: [                        $(' ', { src: actImgURL, width: "75", height: "75" })                     ]                    })                  ]                })              ]            }),            $(' ', {              append: [                $('<b>').text(actJSON.title),                $(' '),                $('<i>').text(actJSON.desc)              ]            }), $(' ', {             append: [                $(' ', { style: 'display:none', class: 'sortkey' }).text(actJSON.reputation),               $('', { href: '/wiki/Syndicates', class: 'image image-thumbnail link-internal', title: 'Syndicates', append: [ $(' ', {                     src: REP_IMG_URL,                      width: "20",                      height: "20"                    }) ]               }),                $('<b>').text(actJSON.reputation.toLocaleString)              ]            }), // add end time for daily acts only (actType === ActTypeEnum.DAILY) ? $(' ').text(parseISOString(actJSON.expiry)) : null ]       }));      });    }); });

// Assume s is in ISO Date format // Source: https://stackoverflow.com/questions/27012854/change-iso-date-string-to-date-object-javascript function parseISOString(s) { var b = s.split(/\D+/); return new Date(Date.UTC(b[0], --b[1], b[2], b[3], b[4], b[5], b[6])); } /* END Cephalon Scientia Nightwave Current Acts */