IdlePixel+

Idle-Pixel plugin framework

当前为 2022-09-03 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/441206/1089174/IdlePixel%2B.js

  1. // ==UserScript==
  2. // @name IdlePixel+
  3. // @namespace com.anwinity.idlepixel
  4. // @version 1.0.5
  5. // @description Idle-Pixel plugin framework
  6. // @author Anwinity
  7. // @match *://idle-pixel.com/login/play*
  8. // @grant none
  9. // ==/UserScript==
  10.  
  11. (function() {
  12. 'use strict';
  13.  
  14. const VERSION = "1.0.5";
  15.  
  16. if(window.IdlePixelPlus) {
  17. // already loaded
  18. return;
  19. }
  20.  
  21. const LOCAL_STORAGE_KEY_DEBUG = "IdlePixelPlus:debug";
  22.  
  23. const CONFIG_TYPES_LABEL = ["label"];
  24. const CONFIG_TYPES_BOOLEAN = ["boolean", "bool", "checkbox"];
  25. const CONFIG_TYPES_INTEGER = ["integer", "int"];
  26. const CONFIG_TYPES_FLOAT = ["number", "num", "float"];
  27. const CONFIG_TYPES_STRING = ["string", "text"];
  28. const CONFIG_TYPES_SELECT = ["select"];
  29. const CONFIG_TYPES_COLOR = ["color"];
  30.  
  31. const CHAT_COMMAND_NO_OVERRIDE = ["help", "mute", "ban", "pm"];
  32.  
  33. function createCombatZoneObjects() {
  34. const fallback = {
  35. field: {
  36. id: "field",
  37. commonMonsters: [
  38. "Chickens",
  39. "Rats",
  40. "Spiders"
  41. ],
  42. rareMonsters: [
  43. "Lizards",
  44. "Bees"
  45. ],
  46. energyCost: 50,
  47. fightPointCost: 300
  48. },
  49. forest: {
  50. id: "forest",
  51. commonMonsters: [
  52. "Snakes",
  53. "Ants",
  54. "Wolves"
  55. ],
  56. rareMonsters: [
  57. "Ents",
  58. "Thief"
  59. ],
  60. energyCost: 200,
  61. fightPointCost: 600
  62. },
  63. cave: {
  64. id: "cave",
  65. commonMonsters: [
  66. "Bears",
  67. "Goblins",
  68. "Bats"
  69. ],
  70. rareMonsters: [
  71. "Skeletons"
  72. ],
  73. energyCost: 500,
  74. fightPointCost: 900
  75. },
  76. volcano: {
  77. id: "volcano",
  78. commonMonsters: [
  79. "Fire Hawk",
  80. "Fire Snake",
  81. "Fire Golem"
  82. ],
  83. rareMonsters: [
  84. "Fire Witch"
  85. ],
  86. energyCost: 1000,
  87. fightPointCost: 1500
  88. },
  89. northern_field: {
  90. id: "northern_field",
  91. commonMonsters: [
  92. "Ice Hawk",
  93. "Ice Witch",
  94. "Golem"
  95. ],
  96. rareMonsters: [
  97. "Yeti"
  98. ],
  99. energyCost: 3000,
  100. fightPointCost: 2000
  101. }
  102. };
  103. try {
  104. const code = Combat._modal_load_area_data.toString().split(/\r?\n/g);
  105. const zones = {};
  106. let foundSwitch = false;
  107. let endSwitch = false;
  108. let current = null;
  109. code.forEach(line => {
  110. if(endSwitch) {
  111. return;
  112. }
  113. if(!foundSwitch) {
  114. if(line.includes("switch(area)")) {
  115. foundSwitch = true;
  116. }
  117. }
  118. else {
  119. line = line.trim();
  120. if(foundSwitch && !endSwitch && !current && line=='}') {
  121. endSwitch = true;
  122. }
  123. else if(/case /.test(line)) {
  124. // start of zone data
  125. let zoneId = line.replace(/^case\s+"/, "").replace(/":.*$/, "");
  126. current = zones[zoneId] = {id: zoneId};
  127. }
  128. else if(line.startsWith("break;")) {
  129. // end of zone data
  130. current = null;
  131. }
  132. else if(current) {
  133. if(line.startsWith("common_monsters_array")) {
  134. current.commonMonsters = line
  135. .replace("common_monsters_array = [", "")
  136. .replace("];", "")
  137. .split(/\s*,\s*/g)
  138. .map(s => s.substring(1, s.length-1));
  139. }
  140. else if(line.startsWith("rare_monsters_array")) {
  141. current.rareMonsters = line
  142. .replace("rare_monsters_array = [", "")
  143. .replace("];", "")
  144. .split(/\s*,\s*/g)
  145. .map(s => s.substring(1, s.length-1));
  146. }
  147. else if(line.startsWith("energy")) {
  148. current.energyCost = parseInt(line.match(/\d+/)[0]);
  149. }
  150. else if(line.startsWith("fightpoints")) {
  151. current.fightPointCost = parseInt(line.match(/\d+/)[0]);
  152. }
  153. }
  154. }
  155. });
  156. if(!zones || !Object.keys(zones).length) {
  157. console.error("IdlePixelPlus: Could not parse combat zone data, using fallback.");
  158. return fallback;
  159. }
  160. return zones;
  161. }
  162. catch(err) {
  163. console.error("IdlePixelPlus: Could not parse combat zone data, using fallback.", err);
  164. return fallback;
  165. }
  166. }
  167.  
  168. function createOreObjects() {
  169. const ores = {
  170. stone: { smeltable:false, bar: null },
  171. copper: { smeltable:true, bar: "bronze_bar" },
  172. iron: { smeltable:true, bar: "iron_bar" },
  173. silver: { smeltable:true, bar: "silver_bar" },
  174. gold: { smeltable:true, bar: "gold_bar" },
  175. promethium: { smeltable:true, bar: "promethium_bar" }
  176. };
  177. try {
  178. Object.keys(ores).forEach(id => {
  179. const obj = ores[id];
  180. obj.id = id;
  181. obj.oil = Crafting.getOilPerBar(id);
  182. obj.charcoal = Crafting.getCharcoalPerBar(id);
  183. });
  184. }
  185. catch(err) {
  186. console.error("IdlePixelPlus: Could not create ore data. This could adversely affect related functionality.", err);
  187. }
  188. return ores;
  189. }
  190.  
  191. function createSeedObjects() {
  192. // hardcoded for now.
  193. return {
  194. dotted_green_leaf_seeds: {
  195. id: "dotted_green_leaf_seeds",
  196. level: 1,
  197. stopsDying: 15,
  198. time: 15,
  199. bonemealCost: 0
  200. },
  201. stardust_seeds: {
  202. id: "stardust_seeds",
  203. level: 8,
  204. stopsDying: 0,
  205. time: 20,
  206. bonemealCost: 0
  207. },
  208. green_leaf_seeds: {
  209. id: "green_leaf_seeds",
  210. level: 10,
  211. stopsDying: 25,
  212. time: 30,
  213. bonemealCost: 0
  214. },
  215. lime_leaf_seeds: {
  216. id: "lime_leaf_seeds",
  217. level: 25,
  218. stopsDying: 40,
  219. time: 1*60,
  220. bonemealCost: 1
  221. },
  222. gold_leaf_seeds: {
  223. id: "gold_leaf_seeds",
  224. level: 50,
  225. stopsDying: 60,
  226. time: 2*60,
  227. bonemealCost: 10
  228. },
  229. crystal_leaf_seeds: {
  230. id: "crystal_leaf_seeds",
  231. level: 70,
  232. stopsDying: 80,
  233. time: 5*60,
  234. bonemealCost: 25
  235. },
  236. red_mushroom_seeds: {
  237. id: "red_mushroom_seeds",
  238. level: 1,
  239. stopsDying: 0,
  240. time: 5,
  241. bonemealCost: 0
  242. },
  243. tree_seeds: {
  244. id: "tree_seeds",
  245. level: 10,
  246. stopsDying: 25,
  247. time: 5*60,
  248. bonemealCost: 10
  249. },
  250. oak_tree_seeds: {
  251. id: "oak_tree_seeds",
  252. level: 25,
  253. stopsDying: 40,
  254. time: 4*60,
  255. bonemealCost: 25
  256. },
  257. willow_tree_seeds: {
  258. id: "willow_tree_seeds",
  259. level: 37,
  260. stopsDying: 55,
  261. time: 8*60,
  262. bonemealCost: 50
  263. },
  264. maple_tree_seeds: {
  265. id: "maple_tree_seeds",
  266. level: 50,
  267. stopsDying: 65,
  268. time: 12*60,
  269. bonemealCost: 120
  270. },
  271. stardust_tree_seeds: {
  272. id: "stardust_tree_seeds",
  273. level: 65,
  274. stopsDying: 80,
  275. time: 15*60,
  276. bonemealCost: 150
  277. },
  278. pine_tree_seeds: {
  279. id: "pine_tree_seeds",
  280. level: 70,
  281. stopsDying: 85,
  282. time: 17*60,
  283. bonemealCost: 180
  284. }
  285. };
  286. }
  287.  
  288. function createSpellObjects() {
  289. const spells = {};
  290. Object.keys(Magic.spell_info).forEach(id => {
  291. const info = Magic.spell_info[id];
  292. spells[id] = {
  293. id: id,
  294. manaCost: info.mana_cost,
  295. magicBonusRequired: info.magic_bonus
  296. };
  297. });
  298. return spells;
  299. }
  300.  
  301. const INFO = {
  302. ores: createOreObjects(),
  303. seeds: createSeedObjects(),
  304. combatZones: createCombatZoneObjects(),
  305. spells: createSpellObjects()
  306. };
  307.  
  308. function logFancy(s, color="#00f7ff") {
  309. console.log("%cIdlePixelPlus: %c"+s, `color: ${color}; font-weight: bold; font-size: 12pt;`, "color: black; font-weight: normal; font-size: 10pt;");
  310. }
  311.  
  312. class IdlePixelPlusPlugin {
  313.  
  314. constructor(id, opts) {
  315. if(typeof id !== "string") {
  316. throw new TypeError("IdlePixelPlusPlugin constructor takes the following arguments: (id:string, opts?:object)");
  317. }
  318. this.id = id;
  319. this.opts = opts || {};
  320. this.config = null;
  321. }
  322.  
  323. getConfig(name) {
  324. if(!this.config) {
  325. IdlePixelPlus.loadPluginConfigs(this.id);
  326. }
  327. if(this.config) {
  328. return this.config[name];
  329. }
  330. }
  331.  
  332. /*
  333. onConfigsChanged() { }
  334. onLogin() { }
  335. onMessageReceived(data) { }
  336. onVariableSet(key, valueBefore, valueAfter) { }
  337. onChat(data) { }
  338. onPanelChanged(panelBefore, panelAfter) { }
  339. onCombatStart() { }
  340. onCombatEnd() { }
  341. onCustomMessageReceived(player, content, callbackId) { }
  342. onCustomMessagePlayerOffline(player, content) { }
  343. */
  344.  
  345. }
  346.  
  347. const internal = {
  348. init() {
  349. const self = this;
  350.  
  351. $("body").prepend(`
  352. <style>
  353. .ipp-chat-command-help {
  354. padding: 0.5em 0;
  355. }
  356. .ipp-chat-command-help:first-child {
  357. padding-top: 0;
  358. }
  359. .ipp-chat-command-help:last-child {
  360. padding-bottom: 0;
  361. }
  362. dialog.ipp-dialog {
  363. background-color: white;
  364. border: 1px solid rgba(0, 0, 0, 0.2);
  365. width: 500px;
  366. max-width: 800px;
  367. border-radius: 5px;
  368. display: flex;
  369. flex-direction: column;
  370. justify-content: flex-start;
  371. }
  372. dialog.ipp-dialog > div {
  373. width: 100%;
  374. }
  375. dialog.ipp-dialog > .ipp-dialog-header > h4 {
  376. margin-bottom: 0;
  377. }
  378. dialog.ipp-dialog > .ipp-dialog-header {
  379. border-bottom: 1px solid rgba(0, 0, 0, 0.2);
  380. padding-bottom: 0.25em;
  381. }
  382. dialog.ipp-dialog > .ipp-dialog-actions {
  383. padding-top: 0.25em;
  384. padding-bottom: 0.25em;
  385. }
  386. dialog.ipp-dialog > .ipp-dialog-actions {
  387. border-top: 1px solid rgba(0, 0, 0, 0.2);
  388. padding-top: 0.25em;
  389. text-align: right;
  390. }
  391. dialog.ipp-dialog > .ipp-dialog-actions > button {
  392. margin: 4px;
  393. }
  394. </style>
  395. `);
  396.  
  397. // hook into websocket messages
  398. const hookIntoOnMessage = () => {
  399. try {
  400. const original_onmessage = window.websocket.connected_socket.onmessage;
  401. if(typeof original_onmessage === "function") {
  402. window.websocket.connected_socket.onmessage = function(event) {
  403. original_onmessage.apply(window.websocket.connected_socket, arguments);
  404. self.onMessageReceived(event.data);
  405. }
  406. return true;
  407. }
  408. else {
  409. return false;
  410. }
  411. }
  412. catch(err) {
  413. console.error("Had trouble hooking into websocket...");
  414. return false;
  415. }
  416. };
  417. $(function() {
  418. if(!hookIntoOnMessage()) {
  419. // try once more
  420. setTimeout(hookIntoOnMessage, 40);
  421. }
  422. });
  423.  
  424. // hook into Chat.send
  425. const original_chat_send = Chat.send;
  426. Chat.send = function() {
  427. const input = $("#chat-area-input");
  428. let message = input.val();
  429. if(message.length == 0) {
  430. return;
  431. }
  432. if(message.startsWith("/")) {
  433. const space = message.indexOf(" ");
  434. let command;
  435. let data;
  436. if(space <= 0) {
  437. command = message.substring(1);
  438. data = "";
  439. }
  440. else {
  441. command = message.substring(1, space);
  442. data = message.substring(space+1);
  443. }
  444. if(window.IdlePixelPlus.handleCustomChatCommand(command, data)) {
  445. input.val("");
  446. }
  447. else {
  448. original_chat_send();
  449. }
  450. }
  451. else {
  452. original_chat_send();
  453. }
  454. };
  455.  
  456. // hook into Items.set, which is where var_ values are set
  457. const original_items_set = Items.set;
  458. Items.set = function(key, value) {
  459. let valueBefore = window["var_"+key];
  460. original_items_set.apply(this, arguments);
  461. let valueAfter = window["var_"+key];
  462. self.onVariableSet(key, valueBefore, valueAfter);
  463. }
  464.  
  465. // hook into switch_panels, which is called when the main panel is changed. This is also used for custom panels.
  466. const original_switch_panels = window.switch_panels;
  467. window.switch_panels = function(id) {
  468. let panelBefore = Globals.currentPanel;
  469. if(panelBefore && panelBefore.startsWith("panel-")) {
  470. panelBefore = panelBefore.substring("panel-".length);
  471. }
  472. self.hideCustomPanels();
  473. original_switch_panels.apply(this, arguments);
  474. let panelAfter = Globals.currentPanel;
  475. if(panelAfter && panelAfter.startsWith("panel-")) {
  476. panelAfter = panelAfter.substring("panel-".length);
  477. }
  478. self.onPanelChanged(panelBefore, panelAfter);
  479. }
  480.  
  481. // create plugin menu item and panel
  482. const lastMenuItem = $("#menu-bar-buttons > .hover-menu-bar-item").last();
  483. lastMenuItem.after(`
  484. <div onclick="IdlePixelPlus.setPanel('idlepixelplus')" class="hover hover-menu-bar-item">
  485. <img id="menu-bar-idlepixelplus-icon" src="https://anwinity.com/idlepixelplus/plugins.png"> PLUGINS
  486. </div>
  487. `);
  488. self.addPanel("idlepixelplus", "IdlePixel+ Plugins", function() {
  489. let content = `
  490. <style>
  491. .idlepixelplus-plugin-box {
  492. display: block;
  493. position: relative;
  494. padding: 0.25em;
  495. color: white;
  496. background-color: rgb(107, 107, 107);
  497. border: 1px solid black;
  498. border-radius: 6px;
  499. margin-bottom: 0.5em;
  500. }
  501. .idlepixelplus-plugin-box .idlepixelplus-plugin-settings-button {
  502. position: absolute;
  503. right: 2px;
  504. top: 2px;
  505. cursor: pointer;
  506. }
  507. .idlepixelplus-plugin-box .idlepixelplus-plugin-config-section {
  508. display: grid;
  509. grid-template-columns: minmax(100px, min-content) 1fr;
  510. row-gap: 0.5em;
  511. column-gap: 0.5em;
  512. white-space: nowrap;
  513. }
  514. </style>
  515. `;
  516. self.forEachPlugin(plugin => {
  517. let id = plugin.id;
  518. let name = "An IdlePixel+ Plugin!";
  519. let description = "";
  520. let author = "unknown";
  521. if(plugin.opts.about) {
  522. let about = plugin.opts.about;
  523. name = about.name || name;
  524. description = about.description || description;
  525. author = about.author || author;
  526. }
  527. content += `
  528. <div id="idlepixelplus-plugin-box-${id}" class="idlepixelplus-plugin-box">
  529. <strong><u>${name||id}</u></strong> (by ${author})<br />
  530. <span>${description}</span><br />
  531. <div class="idlepixelplus-plugin-config-section" style="display: none">
  532. <hr style="grid-column: span 2">
  533. `;
  534. if(plugin.opts.config && Array.isArray(plugin.opts.config)) {
  535. plugin.opts.config.forEach(cfg => {
  536. if(CONFIG_TYPES_LABEL.includes(cfg.type)) {
  537. content += `<h5 style="grid-column: span 2; margin-bottom: 0; font-weight: 600">${cfg.label}</h5>`;
  538. }
  539. else if(CONFIG_TYPES_BOOLEAN.includes(cfg.type)) {
  540. content += `
  541. <div>
  542. <label for="idlepixelplus-config-${plugin.id}-${cfg.id}">${cfg.label || cfg.id}</label>
  543. </div>
  544. <div>
  545. <input id="idlepixelplus-config-${plugin.id}-${cfg.id}" type="checkbox" onchange="IdlePixelPlus.setPluginConfigUIDirty('${id}', true)" />
  546. </div>
  547. `;
  548. }
  549. else if(CONFIG_TYPES_INTEGER.includes(cfg.type)) {
  550. content += `
  551. <div>
  552. <label for="idlepixelplus-config-${plugin.id}-${cfg.id}">${cfg.label || cfg.id}</label>
  553. </div>
  554. <div>
  555. <input id="idlepixelplus-config-${plugin.id}-${cfg.id}" type="number" step="1" min="${cfg.min || ''}" max="${cfg.max || ''}" onchange="IdlePixelPlus.setPluginConfigUIDirty('${id}', true)" />
  556. </div>
  557. `;
  558. }
  559. else if(CONFIG_TYPES_FLOAT.includes(cfg.type)) {
  560. content += `
  561. <div>
  562. <label for="idlepixelplus-config-${plugin.id}-${cfg.id}">${cfg.label || cfg.id}</label>
  563. </div>
  564. <div>
  565. <input id="idlepixelplus-config-${plugin.id}-${cfg.id}" type="number" step="${cfg.step || ''}" min="${cfg.min || ''}" max="${cfg.max || ''}" onchange="IdlePixelPlus.setPluginConfigUIDirty('${id}', true)" />
  566. </div>
  567. `;
  568. }
  569. else if(CONFIG_TYPES_STRING.includes(cfg.type)) {
  570. content += `
  571. <div>
  572. <label for="idlepixelplus-config-${plugin.id}-${cfg.id}">${cfg.label || cfg.id}</label>
  573. </div>
  574. <div>
  575. <input id="idlepixelplus-config-${plugin.id}-${cfg.id}" type="text" maxlength="${cfg.max || ''}" onchange="IdlePixelPlus.setPluginConfigUIDirty('${id}', true)" />
  576. </div>
  577. `;
  578. }
  579. else if(CONFIG_TYPES_COLOR.includes(cfg.type)) {
  580. content += `
  581. <div>
  582. <label for="idlepixelplus-config-${plugin.id}-${cfg.id}">${cfg.label || cfg.id}</label>
  583. </div>
  584. <div>
  585. <input id="idlepixelplus-config-${plugin.id}-${cfg.id}" type="color" onchange="IdlePixelPlus.setPluginConfigUIDirty('${id}', true)" />
  586. </div>
  587. `;
  588. }
  589. else if(CONFIG_TYPES_SELECT.includes(cfg.type)) {
  590. content += `
  591. <div>
  592. <label for="idlepixelplus-config-${plugin.id}-${cfg.id}">${cfg.label || cfg.id}</label>
  593. </div>
  594. <div>
  595. <select id="idlepixelplus-config-${plugin.id}-${cfg.id}" onchange="IdlePixelPlus.setPluginConfigUIDirty('${id}', true)">
  596. `;
  597. if(cfg.options && Array.isArray(cfg.options)) {
  598. cfg.options.forEach(option => {
  599. if(typeof option === "string") {
  600. content += `<option value="${option}">${option}</option>`;
  601. }
  602. else {
  603. content += `<option value="${option.value}">${option.label || option.value}</option>`;
  604. }
  605. });
  606. }
  607. content += `
  608. </select>
  609. </div>
  610. `;
  611. }
  612. });
  613. content += `
  614. <div style="grid-column: span 2">
  615. <button id="idlepixelplus-configbutton-${plugin.id}-reload" onclick="IdlePixelPlus.loadPluginConfigs('${id}')">Reload</button>
  616. <button id="idlepixelplus-configbutton-${plugin.id}-apply" onclick="IdlePixelPlus.savePluginConfigs('${id}')">Apply</button>
  617. </div>
  618. `;
  619. }
  620. content += "</div>";
  621. if(plugin.opts.config) {
  622. content += `
  623. <div class="idlepixelplus-plugin-settings-button">
  624. <button onclick="$('#idlepixelplus-plugin-box-${id} .idlepixelplus-plugin-config-section').toggle()">Settings</button>
  625. </div>`;
  626. }
  627. content += "</div>";
  628. });
  629.  
  630. return content;
  631. });
  632.  
  633. logFancy(`(v${self.version}) initialized.`);
  634. }
  635. };
  636.  
  637. class IdlePixelPlus {
  638.  
  639. constructor() {
  640. this.version = VERSION;
  641. this.plugins = {};
  642. this.panels = {};
  643. this.debug = false;
  644. this.info = INFO;
  645. this.nextUniqueId = 1;
  646. this.customMessageCallbacks = {};
  647. this.customChatCommands = {
  648. help: (command, data) => {
  649. console.log("help", command, data);
  650. }
  651. };
  652. this.customChatHelp = {};
  653. this.customDialogOptions = {};
  654.  
  655. if(localStorage.getItem(LOCAL_STORAGE_KEY_DEBUG) == "1") {
  656. this.debug = true;
  657. }
  658. }
  659.  
  660. getCustomDialogData(id) {
  661. const el = document.querySelector(`dialog#${id}.ipp-dialog`);
  662. if(el) {
  663. const result = {};
  664. $(el).find("[data-key]").each(function() {
  665. const dataElement = $(this);
  666. const dataKey = dataElement.attr("data-key");
  667. if(["INPUT", "SELECT", "TEXTAREA"].includes(dataElement.prop("tagName"))) {
  668. result[dataKey] = dataElement.val();
  669. }
  670. else {
  671. result[dataKey] = dataElement.text();
  672. }
  673. });
  674. return result;
  675. }
  676. }
  677.  
  678. openCustomDialog(id, noEvent=false) {
  679. this.closeCustomDialog(id, true);
  680. const el = document.querySelector(`dialog#${id}.ipp-dialog`);
  681. if(el) {
  682. el.style.display = "";
  683. el.showModal();
  684. const opts = this.customDialogOptions[id];
  685. if(!noEvent && opts && typeof opts.onOpen === "function") {
  686. opts.onOpen(opts);
  687. }
  688. }
  689. }
  690.  
  691. closeCustomDialog(id, noEvent=false) {
  692. const el = document.querySelector(`dialog#${id}.ipp-dialog`);
  693. if(el) {
  694. el.close();
  695. el.style.display = "none";
  696. const opts = this.customDialogOptions[id];
  697. if(!noEvent && opts && typeof opts.onClose === "function") {
  698. opts.onClose(opts);
  699. }
  700. }
  701. }
  702.  
  703. destroyCustomDialog(id, noEvent=false) {
  704. const el = document.querySelector(`dialog#${id}.ipp-dialog`);
  705. if(el) {
  706. el.remove();
  707. const opts = this.customDialogOptions[id];
  708. if(!noEvent && opts && typeof opts.onDestroy === "function") {
  709. opts.onDestroy(opts);
  710. }
  711. }
  712. delete this.customDialogOptions[id];
  713. }
  714.  
  715. createCustomDialog(id, opts={}) {
  716. const self = this;
  717. this.destroyCustomDialog(id);
  718. this.customDialogOptions[id] = opts;
  719. const el = $("body").append(`
  720. <dialog id="${id}" class="ipp-dialog" style="display: none">
  721. <div class="ipp-dialog-header">
  722. <h4>${opts.title||''}</h4>
  723. </div>
  724. <div class="ipp-dialog-content"></div>
  725. <div class="ipp-dialog-actions"></div>
  726. </dialog>
  727. `);
  728. const headerElement = el.find(".ipp-dialog-header");
  729. const contentElement = el.find(".ipp-dialog-content");
  730. const actionsElement = el.find(".ipp-dialog-actions");
  731.  
  732. if(!opts.title) {
  733. headerElement.hide();
  734. }
  735.  
  736. if(typeof opts.content === "string") {
  737. contentElement.append(opts.content);
  738. }
  739.  
  740. let actions = opts.actions;
  741. if(actions) {
  742. if(!Array.isArray(actions)) {
  743. actions = [actions];
  744. }
  745. actions.forEach(action => {
  746. let label;
  747. let primary = false;
  748. if(typeof action === "string") {
  749. label = action;
  750. }
  751. else {
  752. label = action.label || action.action;
  753. primary = action.primary===true;
  754. action = action.action;
  755. }
  756. actionsElement.append(`<button data-action="${action}" class="${primary?'background-primary':''}">${label}</button>`);
  757. });
  758. actionsElement.find("button").on("click", function(e) {
  759. if(typeof opts.onAction === "function") {
  760. e.stopPropagation();
  761. const button = $(this);
  762. const buttonAction = button.attr("data-action");
  763. const data = self.getCustomDialogData(id);
  764. const actionReturn = opts.onAction(buttonAction, data);
  765. if(actionReturn) {
  766. self.closeCustomDialog(id);
  767. }
  768. }
  769. });
  770. }
  771. else {
  772. el.find(".ipp-dialog-actions").hide();
  773. }
  774.  
  775. el.click(function(e) {
  776. const rect = e.target.getBoundingClientRect();
  777. const inside =
  778. rect.top <= e.clientY &&
  779. rect.left <= e.clientX &&
  780. e.clientX <= rect.left + rect.width &&
  781. e.clientY <= rect.top + rect.height;
  782. if(!inside) {
  783. self.closeCustomDialog(id);
  784. e.stopPropagation();
  785. }
  786. });
  787.  
  788. if(typeof opts.onCreate === "function") {
  789. opts.onCreate();
  790. }
  791. if(opts.openImmediately === true) {
  792. this.openCustomDialog(id);
  793. }
  794. }
  795.  
  796.  
  797. registerCustomChatCommand(command, f, help) {
  798. if(Array.isArray(command)) {
  799. command.forEach(cmd => this.registerCustomChatCommand(cmd, f, help));
  800. return;
  801. }
  802. if(typeof command !== "string" || typeof f !== "function") {
  803. throw new TypeError("IdlePixelPlus.registerCustomChatCommand takes the following arguments: (command:string, f:function)");
  804. }
  805. if(CHAT_COMMAND_NO_OVERRIDE.includes(command)) {
  806. throw new Error(`Cannot override the following chat commands: ${CHAT_COMMAND_NO_OVERRIDE.join(", ")}`);
  807. }
  808. if(command in this.customChatCommands) {
  809. console.warn(`IdlePixelPlus: re-registering custom chat command "${command}" which already exists.`);
  810. }
  811. this.customChatCommands[command] = f;
  812. if(help && typeof help === "string") {
  813. this.customChatHelp[command] = help.replace(/%COMMAND%/g, command);
  814. }
  815. else {
  816. delete this.customChatHelp[command];
  817. }
  818. }
  819.  
  820. handleCustomChatCommand(command, message) {
  821. // return true if command handler exists, false otherwise
  822. const f = this.customChatCommands[command];
  823. if(typeof f === "function") {
  824. try {
  825. f(command, message);
  826. }
  827. catch(err) {
  828. console.error(`Error executing custom command "${command}"`, err);
  829. }
  830. return true;
  831. }
  832. return false;
  833. }
  834.  
  835. uniqueId() {
  836. return this.nextUniqueId++;
  837. }
  838.  
  839. setDebug(debug) {
  840. if(debug) {
  841. this.debug = true;
  842. localStorage.setItem(LOCAL_STORAGE_KEY_DEBUG, "1");
  843. }
  844. else {
  845. this.debug = false;
  846. localStorage.removeItem(LOCAL_STORAGE_KEY_DEBUG);
  847. }
  848. }
  849.  
  850. getVar(name, type) {
  851. let s = window[`var_${name}`];
  852. if(type) {
  853. switch(type) {
  854. case "int":
  855. case "integer":
  856. return parseInt(s);
  857. case "number":
  858. case "float":
  859. return parseFloat(s);
  860. case "boolean":
  861. case "bool":
  862. if(s=="true") return true;
  863. if(s=="false") return false;
  864. return undefined;
  865. }
  866. }
  867. return s;
  868. }
  869.  
  870. getVarOrDefault(name, defaultValue, type) {
  871. let s = window[`var_${name}`];
  872. if(s==null || typeof s === "undefined") {
  873. return defaultValue;
  874. }
  875. if(type) {
  876. let value;
  877. switch(type) {
  878. case "int":
  879. case "integer":
  880. value = parseInt(s);
  881. return isNaN(value) ? defaultValue : value;
  882. case "number":
  883. case "float":
  884. value = parseFloat(s);
  885. return isNaN(value) ? defaultValue : value;
  886. case "boolean":
  887. case "bool":
  888. if(s=="true") return true;
  889. if(s=="false") return false;
  890. return defaultValue;
  891. }
  892. }
  893. return s;
  894. }
  895.  
  896. setPluginConfigUIDirty(id, dirty) {
  897. if(typeof id !== "string" || typeof dirty !== "boolean") {
  898. throw new TypeError("IdlePixelPlus.setPluginConfigUIDirty takes the following arguments: (id:string, dirty:boolean)");
  899. }
  900. const plugin = this.plugins[id];
  901. const button = $(`#idlepixelplus-configbutton-${plugin.id}-apply`);
  902. if(button) {
  903. button.prop("disabled", !(dirty));
  904. }
  905. }
  906.  
  907. loadPluginConfigs(id) {
  908. if(typeof id !== "string") {
  909. throw new TypeError("IdlePixelPlus.reloadPluginConfigs takes the following arguments: (id:string)");
  910. }
  911. const plugin = this.plugins[id];
  912. const config = {};
  913. let stored;
  914. try {
  915. stored = JSON.parse(localStorage.getItem(`idlepixelplus.${id}.config`) || "{}");
  916. }
  917. catch(err) {
  918. console.error(`Failed to load configs for plugin with id "${id} - will use defaults instead."`);
  919. stored = {};
  920. }
  921. if(plugin.opts.config && Array.isArray(plugin.opts.config)) {
  922. plugin.opts.config.forEach(cfg => {
  923. const el = $(`#idlepixelplus-config-${plugin.id}-${cfg.id}`);
  924. let value = stored[cfg.id];
  925. if(value==null || typeof value === "undefined") {
  926. value = cfg.default;
  927. }
  928. config[cfg.id] = value;
  929.  
  930. if(el) {
  931. if(CONFIG_TYPES_BOOLEAN.includes(cfg.type) && typeof value === "boolean") {
  932. el.prop("checked", value);
  933. }
  934. else if(CONFIG_TYPES_INTEGER.includes(cfg.type) && typeof value === "number") {
  935. el.val(value);
  936. }
  937. else if(CONFIG_TYPES_FLOAT.includes(cfg.type) && typeof value === "number") {
  938. el.val(value);
  939. }
  940. else if(CONFIG_TYPES_STRING.includes(cfg.type) && typeof value === "string") {
  941. el.val(value);
  942. }
  943. else if(CONFIG_TYPES_SELECT.includes(cfg.type) && typeof value === "string") {
  944. el.val(value);
  945. }
  946. else if(CONFIG_TYPES_COLOR.includes(cfg.type) && typeof value === "string") {
  947. el.val(value);
  948. }
  949. }
  950. });
  951. }
  952. plugin.config = config;
  953. this.setPluginConfigUIDirty(id, false);
  954. if(typeof plugin.onConfigsChanged === "function") {
  955. plugin.onConfigsChanged();
  956. }
  957. }
  958.  
  959. savePluginConfigs(id) {
  960. if(typeof id !== "string") {
  961. throw new TypeError("IdlePixelPlus.savePluginConfigs takes the following arguments: (id:string)");
  962. }
  963. const plugin = this.plugins[id];
  964. const config = {};
  965. if(plugin.opts.config && Array.isArray(plugin.opts.config)) {
  966. plugin.opts.config.forEach(cfg => {
  967. const el = $(`#idlepixelplus-config-${plugin.id}-${cfg.id}`);
  968. let value;
  969. if(CONFIG_TYPES_BOOLEAN.includes(cfg.type)) {
  970. config[cfg.id] = el.is(":checked");
  971. }
  972. else if(CONFIG_TYPES_INTEGER.includes(cfg.type)) {
  973. config[cfg.id] = parseInt(el.val());
  974. }
  975. else if(CONFIG_TYPES_FLOAT.includes(cfg.type)) {
  976. config[cfg.id] = parseFloat(el.val());
  977. }
  978. else if(CONFIG_TYPES_STRING.includes(cfg.type)) {
  979. config[cfg.id] = el.val();
  980. }
  981. else if(CONFIG_TYPES_SELECT.includes(cfg.type)) {
  982. config[cfg.id] = el.val();
  983. }
  984. else if(CONFIG_TYPES_COLOR.includes(cfg.type)) {
  985. config[cfg.id] = el.val();
  986. }
  987. });
  988. }
  989. plugin.config = config;
  990. localStorage.setItem(`idlepixelplus.${id}.config`, JSON.stringify(config));
  991. this.setPluginConfigUIDirty(id, false);
  992. if(typeof plugin.onConfigsChanged === "function") {
  993. plugin.onConfigsChanged();
  994. }
  995. }
  996.  
  997. addPanel(id, title, content) {
  998. if(typeof id !== "string" || typeof title !== "string" || (typeof content !== "string" && typeof content !== "function") ) {
  999. throw new TypeError("IdlePixelPlus.addPanel takes the following arguments: (id:string, title:string, content:string|function)");
  1000. }
  1001. const panels = $("#panels");
  1002. panels.append(`
  1003. <div id="panel-${id}" style="display: none">
  1004. <h1>${title}</h1>
  1005. <hr>
  1006. <div class="idlepixelplus-panel-content"></div>
  1007. </div>
  1008. `);
  1009. this.panels[id] = {
  1010. id: id,
  1011. title: title,
  1012. content: content
  1013. };
  1014. this.refreshPanel(id);
  1015. }
  1016.  
  1017. refreshPanel(id) {
  1018. if(typeof id !== "string") {
  1019. throw new TypeError("IdlePixelPlus.refreshPanel takes the following arguments: (id:string)");
  1020. }
  1021. const panel = this.panels[id];
  1022. if(!panel) {
  1023. throw new TypeError(`Error rendering panel with id="${id}" - panel has not be added.`);
  1024. }
  1025. let content = panel.content;
  1026. if(!["string", "function"].includes(typeof content)) {
  1027. throw new TypeError(`Error rendering panel with id="${id}" - panel.content must be a string or a function returning a string.`);
  1028. }
  1029. if(typeof content === "function") {
  1030. content = content();
  1031. if(typeof content !== "string") {
  1032. throw new TypeError(`Error rendering panel with id="${id}" - panel.content must be a string or a function returning a string.`);
  1033. }
  1034. }
  1035. const panelContent = $(`#panel-${id} .idlepixelplus-panel-content`);
  1036. panelContent.html(content);
  1037. if(id === "idlepixelplus") {
  1038. this.forEachPlugin(plugin => {
  1039. this.loadPluginConfigs(plugin.id);
  1040. });
  1041. }
  1042. }
  1043.  
  1044. registerPlugin(plugin) {
  1045. if(!(plugin instanceof IdlePixelPlusPlugin)) {
  1046. throw new TypeError("IdlePixelPlus.registerPlugin takes the following arguments: (plugin:IdlePixelPlusPlugin)");
  1047. }
  1048. if(plugin.id in this.plugins) {
  1049. throw new Error(`IdlePixelPlusPlugin with id "${plugin.id}" is already registered. Make sure your plugin id is unique!`);
  1050. }
  1051.  
  1052. this.plugins[plugin.id] = plugin;
  1053. this.loadPluginConfigs(plugin.id);
  1054. let versionString = plugin.opts&&plugin.opts.about&&plugin.opts.about.version ? ` (v${plugin.opts.about.version})` : "";
  1055. logFancy(`registered plugin "${plugin.id}"${versionString}`);
  1056. }
  1057.  
  1058. forEachPlugin(f) {
  1059. if(typeof f !== "function") {
  1060. throw new TypeError("IdlePixelPlus.forEachPlugin takes the following arguments: (f:function)");
  1061. }
  1062. Object.values(this.plugins).forEach(plugin => {
  1063. try {
  1064. f(plugin);
  1065. }
  1066. catch(err) {
  1067. console.error(`Error occurred while executing function for plugin "${plugin.id}."`);
  1068. console.error(err);
  1069. }
  1070. });
  1071. }
  1072.  
  1073. setPanel(panel) {
  1074. if(typeof panel !== "string") {
  1075. throw new TypeError("IdlePixelPlus.setPanel takes the following arguments: (panel:string)");
  1076. }
  1077. window.switch_panels(`panel-${panel}`);
  1078. }
  1079.  
  1080. sendMessage(message) {
  1081. if(typeof message !== "string") {
  1082. throw new TypeError("IdlePixelPlus.sendMessage takes the following arguments: (message:string)");
  1083. }
  1084. if(window.websocket && window.websocket.connected_socket && window.websocket.connected_socket.readyState==1) {
  1085. window.websocket.connected_socket.send(message);
  1086. }
  1087. }
  1088.  
  1089. showToast(title, content) {
  1090. show_toast(title, content);
  1091. }
  1092.  
  1093. hideCustomPanels() {
  1094. Object.values(this.panels).forEach((panel) => {
  1095. const el = $(`#panel-${panel.id}`);
  1096. if(el) {
  1097. el.css("display", "none");
  1098. }
  1099. });
  1100. }
  1101.  
  1102. onMessageReceived(data) {
  1103. if(this.debug) {
  1104. console.log(`IP+ onMessageReceived: ${data}`);
  1105. }
  1106. if(data) {
  1107. this.forEachPlugin((plugin) => {
  1108. if(typeof plugin.onMessageReceived === "function") {
  1109. plugin.onMessageReceived(data);
  1110. }
  1111. });
  1112. if(data.startsWith("VALID_LOGIN")) {
  1113. this.onLogin();
  1114. }
  1115. else if(data.startsWith("CHAT=")) {
  1116. const split = data.substring("CHAT=".length).split("~");
  1117. const chatData = {
  1118. username: split[0],
  1119. sigil: split[1],
  1120. tag: split[2],
  1121. level: parseInt(split[3]),
  1122. message: split[4]
  1123. };
  1124. this.onChat(chatData);
  1125. // CHAT=anwinity~none~none~1565~test
  1126. }
  1127. else if(data.startsWith("CUSTOM=")) {
  1128. const customData = data.substring("CUSTOM=".length);
  1129. const tilde = customData.indexOf("~");
  1130. if(tilde > 0) {
  1131. const fromPlayer = customData.substring(0, tilde);
  1132. const content = customData.substring(tilde+1);
  1133. this.onCustomMessageReceived(fromPlayer, content);
  1134. }
  1135. }
  1136. }
  1137. }
  1138.  
  1139. deleteCustomMessageCallback(callbackId) {
  1140. if(this.debug) {
  1141. console.log(`IP+ deleteCustomMessageCallback`, callbackId);
  1142. }
  1143. delete this.customMessageCallbacks[callbackId];
  1144. }
  1145.  
  1146. requestPluginManifest(player, callback, pluginId) {
  1147. if(typeof pluginId === "string") {
  1148. pluginId = [pluginId];
  1149. }
  1150. if(Array.isArray(pluginId)) {
  1151. pluginId = JSON.stringify(pluginId);
  1152. }
  1153. this.sendCustomMessage(player, {
  1154. content: "PLUGIN_MANIFEST" + (pluginId ? `:${pluginId}` : ''),
  1155. onResponse: function(respPlayer, content) {
  1156. if(typeof callback === "function") {
  1157. callback(respPlayer, JSON.parse(content));
  1158. }
  1159. else {
  1160. console.log(`Plugin Manifest: ${respPlayer}`, content);
  1161. }
  1162. },
  1163. onOffline: function(respPlayer, content) {
  1164. if(typeof callback === "function") {
  1165. callback(respPlayer, false);
  1166. }
  1167. },
  1168. timeout: 10000
  1169. });
  1170. }
  1171.  
  1172. sendCustomMessage(toPlayer, opts) {
  1173. if(this.debug) {
  1174. console.log(`IP+ sendCustomMessage`, toPlayer, opts);
  1175. }
  1176. const reply = !!(opts.callbackId);
  1177. const content = typeof opts.content === "string" ? opts.content : JSON.stringify(opts.content);
  1178. const callbackId = reply ? opts.callbackId : this.uniqueId();
  1179. const responseHandler = typeof opts.onResponse === "function" ? opts.onResponse : null;
  1180. const offlineHandler = opts.onOffline===true ? () => { this.deleteCustomMessageCallback(callbackId); } : (typeof opts.onOffline === "function" ? opts.onOffline : null);
  1181. const timeout = typeof opts.timeout === "number" ? opts.timeout : -1;
  1182.  
  1183. if(responseHandler || offlineHandler) {
  1184. const handler = {
  1185. id: callbackId,
  1186. player: toPlayer,
  1187. responseHandler: responseHandler,
  1188. offlineHandler: offlineHandler,
  1189. timeout: typeof timeout === "number" ? timeout : -1,
  1190. };
  1191. if(callbackId) {
  1192. this.customMessageCallbacks[callbackId] = handler;
  1193. if(handler.timeout > 0) {
  1194. setTimeout(() => {
  1195. this.deleteCustomMessageCallback(callbackId);
  1196. }, handler.timeout);
  1197. }
  1198. }
  1199. }
  1200. const message = `CUSTOM=${toPlayer}~IPP${reply?'R':''}${callbackId}:${content}`;
  1201. if(message.length > 255) {
  1202. console.warn("The resulting websocket message from IdlePixelPlus.sendCustomMessage has a length limit of 255 characters. Recipients may not receive the full message!");
  1203. }
  1204. this.sendMessage(message);
  1205. }
  1206.  
  1207. onCustomMessageReceived(fromPlayer, content) {
  1208. if(this.debug) {
  1209. console.log(`IP+ onCustomMessageReceived`, fromPlayer, content);
  1210. }
  1211. const offline = content == "PLAYER_OFFLINE";
  1212. let callbackId = null;
  1213. let originalCallbackId = null;
  1214. let reply = false;
  1215. const ippMatcher = content.match(/^IPP(\w+):/);
  1216. if(ippMatcher) {
  1217. originalCallbackId = callbackId = ippMatcher[1];
  1218. let colon = content.indexOf(":");
  1219. content = content.substring(colon+1);
  1220. if(callbackId.startsWith("R")) {
  1221. callbackId = callbackId.substring(1);
  1222. reply = true;
  1223. }
  1224. }
  1225.  
  1226. // special built-in messages
  1227. if(content.startsWith("PLUGIN_MANIFEST")) {
  1228. const manifest = {};
  1229. let filterPluginIds = null;
  1230. if(content.includes(":")) {
  1231. content = content.substring("PLUGIN_MANIFEST:".length);
  1232. filterPluginIds = JSON.parse(content).map(s => s.replace("~", ""));
  1233. }
  1234. this.forEachPlugin(plugin => {
  1235. let id = plugin.id.replace("~", "");
  1236. if(filterPluginIds && !filterPluginIds.includes(id)) {
  1237. return;
  1238. }
  1239. let version = "unknown";
  1240. if(plugin.opts && plugin.opts.about && plugin.opts.about.version) {
  1241. version = plugin.opts.about.version.replace("~", "");
  1242. }
  1243. manifest[id] = version;
  1244. });
  1245. manifest.IdlePixelPlus = IdlePixelPlus.version;
  1246. this.sendCustomMessage(fromPlayer, {
  1247. content: manifest,
  1248. callbackId: callbackId
  1249. });
  1250. return;
  1251. }
  1252.  
  1253. const callbacks = this.customMessageCallbacks;
  1254. if(reply) {
  1255. const handler = callbacks[callbackId];
  1256. if(handler && typeof handler.responseHandler === "function") {
  1257. try {
  1258. if(handler.responseHandler(fromPlayer, content, originalCallbackId)) {
  1259. this.deleteCustomMessageCallback(callbackId);
  1260. }
  1261. }
  1262. catch(err) {
  1263. console.error("Error executing custom message response handler.", {player: fromPlayer, content: content, handler: handler});
  1264. }
  1265. }
  1266. }
  1267. else if(offline) {
  1268. Object.values(callbacks).forEach(handler => {
  1269. try {
  1270. if(handler.player.toLowerCase()==fromPlayer.toLowerCase() && typeof handler.offlineHandler === "function" && handler.offlineHandler(fromPlayer, content)) {
  1271. this.deleteCustomMessageCallback(handler.id);
  1272. }
  1273. }
  1274. catch(err) {
  1275. console.error("Error executing custom message offline handler.", {player: fromPlayer, content: content, handler: handler});
  1276. }
  1277. });
  1278. }
  1279.  
  1280. if(offline) {
  1281. this.onCustomMessagePlayerOffline(fromPlayer, content);
  1282. }
  1283. else {
  1284. this.forEachPlugin((plugin) => {
  1285. if(typeof plugin.onCustomMessageReceived === "function") {
  1286. plugin.onCustomMessageReceived(fromPlayer, content, originalCallbackId);
  1287. }
  1288. });
  1289. }
  1290. }
  1291.  
  1292. onCustomMessagePlayerOffline(fromPlayer, content) {
  1293. if(this.debug) {
  1294. console.log(`IP+ onCustomMessagePlayerOffline`, fromPlayer, content);
  1295. }
  1296. this.forEachPlugin((plugin) => {
  1297. if(typeof plugin.onCustomMessagePlayerOffline === "function") {
  1298. plugin.onCustomMessagePlayerOffline(fromPlayer, content);
  1299. }
  1300. });
  1301. }
  1302.  
  1303. onCombatStart() {
  1304. if(this.debug) {
  1305. console.log(`IP+ onCombatStart`);
  1306. }
  1307. this.forEachPlugin((plugin) => {
  1308. if(typeof plugin.onCombatStart === "function") {
  1309. plugin.onCombatStart();
  1310. }
  1311. });
  1312. }
  1313.  
  1314. onCombatEnd() {
  1315. if(this.debug) {
  1316. console.log(`IP+ onCombatEnd`);
  1317. }
  1318. this.forEachPlugin((plugin) => {
  1319. if(typeof plugin.onCombatEnd === "function") {
  1320. plugin.onCombatEnd();
  1321. }
  1322. });
  1323. }
  1324.  
  1325. onLogin() {
  1326. if(this.debug) {
  1327. console.log(`IP+ onLogin`);
  1328. }
  1329. logFancy("login detected");
  1330. this.forEachPlugin((plugin) => {
  1331. if(typeof plugin.onLogin === "function") {
  1332. plugin.onLogin();
  1333. }
  1334. });
  1335. $("#chat-area").append(`
  1336. <div class="ipp-chat-command-help">
  1337. <span><strong>FYI: </strong> Use the /help command to see information on available chat commands.</span>
  1338. </div>
  1339. `);
  1340. if(Chat._auto_scroll) {
  1341. $("#chat-area").scrollTop($("#chat-area")[0].scrollHeight);
  1342. }
  1343.  
  1344. }
  1345.  
  1346. onVariableSet(key, valueBefore, valueAfter) {
  1347. if(this.debug) {
  1348. console.log(`IP+ onVariableSet "${key}": "${valueBefore}" -> "${valueAfter}"`);
  1349. }
  1350. this.forEachPlugin((plugin) => {
  1351. if(typeof plugin.onVariableSet === "function") {
  1352. plugin.onVariableSet(key, valueBefore, valueAfter);
  1353. }
  1354. });
  1355. if(key == "monster_name") {
  1356. const combatBefore = !!(valueBefore && valueBefore!="none");
  1357. const combatAfter = !!(valueAfter && valueAfter!="none");
  1358. if(!combatBefore && combatAfter) {
  1359. this.onCombatStart();
  1360. }
  1361. else if(combatBefore && !combatAfter) {
  1362. this.onCombatEnd();
  1363. }
  1364. }
  1365. }
  1366.  
  1367. onChat(data) {
  1368. if(this.debug) {
  1369. console.log(`IP+ onChat`, data);
  1370. }
  1371. this.forEachPlugin((plugin) => {
  1372. if(typeof plugin.onChat === "function") {
  1373. plugin.onChat(data);
  1374. }
  1375. });
  1376. }
  1377.  
  1378. onPanelChanged(panelBefore, panelAfter) {
  1379. if(this.debug) {
  1380. console.log(`IP+ onPanelChanged "${panelBefore}" -> "${panelAfter}"`);
  1381. }
  1382. if(panelAfter === "idlepixelplus") {
  1383. this.refreshPanel("idlepixelplus");
  1384. }
  1385. this.forEachPlugin((plugin) => {
  1386. if(typeof plugin.onPanelChanged === "function") {
  1387. plugin.onPanelChanged(panelBefore, panelAfter);
  1388. }
  1389. });
  1390. }
  1391.  
  1392. }
  1393.  
  1394. // Add to window and init
  1395. window.IdlePixelPlusPlugin = IdlePixelPlusPlugin;
  1396. window.IdlePixelPlus = new IdlePixelPlus();
  1397.  
  1398. window.IdlePixelPlus.customChatCommands["help"] = (command, data='') => {
  1399. let help;
  1400. if(data && data!="help") {
  1401. let helpContent = window.IdlePixelPlus.customChatHelp[data.trim()] || "No help content was found for this command.";
  1402. help = `
  1403. <div class="ipp-chat-command-help">
  1404. <strong><u>Command Help:</u></strong><br />
  1405. <strong>/${data}:</strong> <span>${helpContent}</span>
  1406. </div>
  1407. `;
  1408. }
  1409. else {
  1410. help = `
  1411. <div class="ipp-chat-command-help">
  1412. <strong><u>Command Help:</u></strong><br />
  1413. <strong>Available Commands:</strong> <span>${Object.keys(window.IdlePixelPlus.customChatCommands).sort().map(s => "/"+s).join(" ")}</span><br />
  1414. <span>Use the /help command for more information about a specific command: /help &lt;command&gt;</span>
  1415. </div>
  1416. `;
  1417. }
  1418. $("#chat-area").append(help);
  1419. if(Chat._auto_scroll) {
  1420. $("#chat-area").scrollTop($("#chat-area")[0].scrollHeight);
  1421. }
  1422. };
  1423.  
  1424. const SHRUG = "¯\\_(ツ)_/¯";
  1425. window.IdlePixelPlus.registerCustomChatCommand(["shrug", "rshrug"], (command, data='') => {
  1426. data=data.replace(/~/g, " ");
  1427. const margin = SHRUG.length + 1;
  1428. data = data.substring(0, 250-margin);
  1429. window.IdlePixelPlus.sendMessage(`CHAT=${data} ${SHRUG}`);
  1430. }, `Adds a ${SHRUG} to the end of your chat message.<br /><strong>Usage:</strong> /%COMMAND% &lt;message&gt;`);
  1431.  
  1432. window.IdlePixelPlus.registerCustomChatCommand("lshrug", (command, data='') => {
  1433. data=data.replace(/~/g, " ");
  1434. const margin = SHRUG.length + 1;
  1435. data = data.substring(0, 250-margin);
  1436. window.IdlePixelPlus.sendMessage(`CHAT=${SHRUG} ${data}`);
  1437. }, `Adds a ${SHRUG} to the beginning of your chat message.<br /><strong>Usage:</strong> /%COMMAND% &lt;message&gt;`);
  1438.  
  1439. window.IdlePixelPlus.registerCustomChatCommand("clear", (command, data='') => {
  1440. $("#chat-area").empty();
  1441. }, `Clears all messages in chat.`);
  1442.  
  1443.  
  1444. internal.init.call(window.IdlePixelPlus);
  1445.  
  1446. })();