Advertisement
NecromancerCoding

Monomer Switcheroo Traducido ESP

May 11th, 2024
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.19 KB | None | 0 0
  1. const DEFAULT_LANG = {
  2. button: {
  3. add: "Añadir personaje"
  4. },
  5. msg: {
  6. error: "Ha ocurrido un error, inténtalo de nuevo.",
  7. confirm: "¿Confirmar acción?"
  8. },
  9. modal: {
  10. password_placeholder: "",
  11. password_label: "Contraseña",
  12. username_label: "Nombre de usuario",
  13. username_placholder: "",
  14. login_button: "Añade la cuenta"
  15. }
  16. };
  17.  
  18. const DEFAULT_OPT = {
  19. logo: '',
  20. enableReorder: true,
  21. confirm: true,
  22. updateAvatar: true,
  23. customButtons: [],
  24. blockClass: 'switcheroo',
  25. deleteIcon: `×`,
  26. addIcon: `+`,
  27. errorMsg: 'Ha ocurrido un error, inténtalo de nuevo.',
  28. confirmMsg: '¿Confirmar acción?',
  29. modal: {}
  30. };
  31.  
  32. function extend(obj1, obj2) {
  33. var keys = Object.keys(obj2);
  34. for (var i = 0; i < keys.length; i += 1) {
  35. var val = obj2[keys[i]];
  36. obj1[keys[i]] = ['string', 'number', 'array', 'boolean'].indexOf(typeof val) === -1 ? extend(obj1[keys[i]] || {}, val) : val;
  37. }
  38. return obj1;
  39. }
  40.  
  41. (function (global) {
  42. 'use strict';
  43.  
  44. global.monomer = global.monomer || new MONOMER();
  45.  
  46. function Switcheroo(selector = '#switcheroo', options = {}, lang = {}) {
  47. this.component = document.querySelector(selector);
  48.  
  49.  
  50. this.options = extend(DEFAULT_OPT, options);
  51. this.lang = extend(DEFAULT_LANG, lang);
  52.  
  53. this.createFormModal(this.options.modal);
  54.  
  55. this.elements = {
  56. loginButton: document.querySelector('[data-action="open-login"]'),
  57. loginFormID: 'fa-login-form',
  58. classPrefix: '.' + this.options.blockClass,
  59. deleteButtonClass: '.' + this.options.blockClass + '__delete'
  60. };
  61.  
  62. if (!localStorage.hasOwnProperty('switcheroo')) {
  63. localStorage.setItem('switcheroo', "[]");
  64. }
  65.  
  66. this.buildSwitcheroo();
  67.  
  68. this.bindEvents();
  69. }
  70.  
  71. Switcheroo.prototype.bindEvents = function () {
  72. let t = this;
  73.  
  74. document.delegateEventListener('click', '[data-action="open-login"]', e => {
  75. this.loginModal.open();
  76. });
  77.  
  78. document.delegateEventListener('click', '[data-action="switcheroo"]', function (e) {
  79. if (t.isCloseButton(e)) {
  80. t.deleteRecord(this.dataset.id);
  81. }
  82. });
  83.  
  84. if (t.options.updateAvatar) {
  85. document.delegateEventListener('contextmenu', '[data-action="switcheroo"].active', function (e) {
  86. t.updateAvatar(this, e);
  87. });
  88. }
  89.  
  90. document.delegateEventListener('click', '[data-action="switcheroo"]:not(.active)', function (e) {
  91. if (!t.isCloseButton(e)) {
  92. if (t.options.confirm) {
  93. var r = confirm(t.lang.msg.confirm);
  94. if (r == true) {
  95. t.switch(this);
  96. }
  97. } else {
  98. t.switch(this);
  99. }
  100. }
  101. });
  102.  
  103. };
  104.  
  105. Switcheroo.prototype.isUserLoggedIn = function () {
  106. return monomer.user().logged();
  107. };
  108.  
  109. Switcheroo.prototype.add = async function (form) {
  110. let fields = monomer.getFormData(form);
  111. let credentials = (({ username, password }) => ({ username, password: monomer.cipher(password) }))(fields);
  112.  
  113. /* new async/await way */
  114. if (this.isUserLoggedIn()) await this.logout();
  115.  
  116. await this.login(credentials, (data) => {
  117. credentials = Object.assign({}, credentials, this.updateCredentials(data));
  118. this.update(credentials);
  119. monomer.reload();
  120. }, () => {
  121. this.errorAlert();
  122. });
  123. /* end */
  124. }
  125.  
  126. Switcheroo.prototype.switch = async function (user) {
  127. let id = user.dataset.id;
  128. let switcheroo = this.findSwitcheroo(id);
  129. if (!switcheroo) return this.errorAlert();
  130.  
  131. if (this.isUserLoggedIn()) await this.logout();
  132. await this.login(switcheroo, monomer.reload, () => {
  133. this.errorAlert();
  134. });
  135. }
  136.  
  137. Switcheroo.prototype.login = function (credentials, success, error) {
  138. return monomer.login(credentials['username'], monomer.decipher(credentials['password']))
  139. .then(res => {
  140. this.statusCallbacks(res, success, error);
  141. });
  142. };
  143.  
  144. Switcheroo.prototype.logout = function (success, error) {
  145. let t = this;
  146. return monomer.logout().then(res => {
  147. this.statusCallbacks(res, success, error);
  148. });
  149. };
  150.  
  151. Switcheroo.prototype.statusCallbacks = function (res, success, error) {
  152. if (res.status) {
  153. if (success) success(res.data);
  154. } else {
  155. if (error) error(res.data);
  156. }
  157. };
  158.  
  159. Switcheroo.prototype.errorAlert = function () {
  160. alert(this.lang.msg.error);
  161. };
  162.  
  163. Switcheroo.prototype.update = function (credentials) {
  164. if (!this.credentialsExists(credentials['id'])) {
  165. this.switcherooCredentials.push(credentials);
  166. this.updateStorage();
  167. }
  168. };
  169.  
  170. Switcheroo.prototype.findSwitcheroo = function (id) {
  171. return this.switcherooCredentials.find(x => x.id === id);
  172. }
  173.  
  174. Switcheroo.prototype.deleteSwitcheroo = function (id) {
  175. this.switcherooCredentials = this.switcherooCredentials.filter(function (obj) {
  176. return obj.id !== id;
  177. });
  178. };
  179.  
  180. Switcheroo.prototype.updateCredentials = function (data) {
  181. // make sure everything is formatted for localstorage
  182. return {
  183. id: this.catchID(data),
  184. avatar: this.catchAvatar(data),
  185. username: this.catchUsername(data)
  186. }
  187. };
  188.  
  189. Switcheroo.prototype.credentialsExists = function (id) {
  190. return this.switcherooCredentials.some(function (el) {
  191. return el.id === id;
  192. });
  193. };
  194.  
  195. Switcheroo.prototype.updateAvatar = function (user, e) {
  196. e.preventDefault();
  197. let user_id = user.dataset.id;
  198. let toUpdate = this.findSwitcheroo(user_id);
  199. let currentAvatar = monomer.user().avatar();
  200. if (toUpdate['avatar'] == currentAvatar) return;
  201. toUpdate['avatar'] = currentAvatar;
  202. this.updateRecord();
  203. };
  204.  
  205. Switcheroo.prototype.updateRecord = function () {
  206. this.updateStorage();
  207. monomer.reload();
  208. };
  209.  
  210. Switcheroo.prototype.deleteRecord = function (id) {
  211. this.deleteSwitcheroo(id);
  212. this.updateStorage();
  213. monomer.reload();
  214. };
  215.  
  216. Switcheroo.prototype.updateStorage = function (obj) {
  217. localStorage.setItem('switcheroo', JSON.stringify(obj || this.switcherooCredentials));
  218. };
  219.  
  220. Switcheroo.prototype.isCloseButton = function (e) {
  221. var el = e.target;
  222. return el.matches(this.elements.deleteButtonClass);
  223. };
  224.  
  225. Switcheroo.prototype.catchAvatar = function (data) {
  226. let pattern = new RegExp(/_userdata\["avatar"\] = "(.+)";/, "gm");
  227. return pattern.exec(data)[1];
  228. }
  229.  
  230. Switcheroo.prototype.catchID = function (data) {
  231. let pattern = new RegExp(/_userdata\["user_id"\] = (\d+);/, "gm");
  232. return pattern.exec(data)[1];
  233. };
  234.  
  235. Switcheroo.prototype.catchUsername = function (data) {
  236. let pattern = new RegExp(/_userdata\["username"\] = "(.+)";/, "gm");
  237. return pattern.exec(data)[1];
  238. };
  239.  
  240. Switcheroo.prototype.buildSwitcheroo = function () {
  241. var c = this.options.blockClass;
  242. this.component.style.userSelect = 'none';
  243. this.switcherooCredentials = JSON.parse(localStorage.getItem('switcheroo'));
  244.  
  245. let docFrag = document.createDocumentFragment();
  246.  
  247. let wrapper = document.createElement('ul');
  248. wrapper.classList.add(c + '__squircles');
  249.  
  250. if (this.options.logo) {
  251. this.createLogoElement(wrapper);
  252. }
  253.  
  254. this.switcherooCredentials.forEach(el => {
  255. this.createSwitcherooUser(el, wrapper);
  256. });
  257.  
  258. /* options */
  259. const login = document.createElement('li');
  260. login.classList.add(c + '__squircle', c + '__squircle--button');
  261. login.dataset.action = 'open-login';
  262. login.innerHTML = this.options.addIcon;
  263. login.appendChild(this.createTooltip(this.lang.button.add))
  264. wrapper.appendChild(login);
  265.  
  266. this.createCustomButtons(wrapper);
  267.  
  268. docFrag.appendChild(wrapper);
  269. this.component.appendChild(docFrag);
  270.  
  271. };
  272.  
  273. Switcheroo.prototype.createSwitcherooUser = function (user, wrapper) {
  274. let c = this.options.blockClass;
  275. let list = document.createElement("li");
  276.  
  277. list.classList.add(c + '__squircle');
  278. list.dataset.id = user.id;
  279. list.classList.toggle('active', (user.id == monomer.user().id()));
  280. /* draggable */
  281. if (this.options.enableReorder) {
  282. list.draggable = true;
  283. list.addEventListener('dragstart', this.dragStart.bind(this));
  284. list.addEventListener('dragover', this.dragOver.bind(this));
  285. list.addEventListener('dragend', this.dragEnd.bind(this));
  286. }
  287. list.dataset.action = 'switcheroo';
  288.  
  289.  
  290. // create avatar
  291. let avatar = document.createElement("div")
  292. avatar.classList.add(c + '__avatar');
  293. avatar.innerHTML = user.avatar.replace(/\\"/g, '"');
  294. if (this.options.enableReorder) {
  295. avatar.draggable = false;
  296. avatar.querySelector('img').draggable = false;
  297. }
  298. list.appendChild(avatar);
  299.  
  300. // create popper
  301. list.appendChild(this.createTooltip(user.username));
  302.  
  303. // create delete
  304. let del = document.createElement('div');
  305. del.classList.add(c + '__delete');
  306. if (this.options.enableReorder) {
  307. del.draggable = false;
  308. }
  309. del.innerHTML = this.options.deleteIcon;
  310. list.appendChild(del);
  311.  
  312. wrapper.appendChild(list);
  313. };
  314.  
  315. Switcheroo.prototype.createLogoElement = function (wrapper) {
  316. let c = this.options.blockClass;
  317. let logo = document.createElement('a');
  318. logo.classList.add(c + '__squircle', c + '__logo');
  319. logo.href = '/';
  320. logo.innerHTML = this.options.logo;
  321. logo.appendChild(this.createTooltip('Accueil'));
  322. wrapper.appendChild(logo);
  323. this.createDividerLine(wrapper);
  324. };
  325.  
  326. Switcheroo.prototype.createDividerLine = function (wrapper) {
  327. const divider = document.createElement('li');
  328. divider.classList.add(this.options.blockClass + '__divider');
  329. wrapper.appendChild(divider);
  330. };
  331.  
  332. Switcheroo.prototype.createCustomButtons = function (wrapper) {
  333. const t = this;
  334. const buttons = this.options.customButtons;
  335. const c = this.options.blockClass;
  336. if (buttons.length > 0) {
  337. buttons.forEach(el => {
  338. if (!el) return;
  339. let button;
  340. const isValidLink = (monomer.isValidURL(el.action) || (typeof el.action === 'string' && el.action.indexOf('/') === 0));
  341. if (isValidLink) {
  342. button = document.createElement('a');
  343. button.href = el.action;
  344. } else if (typeof el.action === 'function') {
  345. button = document.createElement('div');
  346. button.addEventListener('click', function (e) {
  347. el.action.call(t, e, this);
  348. });
  349. }
  350. if (!button) return false;
  351. if (Array.isArray(el.classes)) button.classList.add(...el.classes.map(x => `${c}__button--${x}`));
  352. if (typeof el.before === "boolean" && el.before) button.style.order = "-1";
  353. button.classList.add(c + '__squircle', c + '__button');
  354. button.innerHTML = el.html;
  355. if (el.tooltip && typeof el.tooltip === "string") button.appendChild(this.createTooltip(el.tooltip));
  356. wrapper.appendChild(button);
  357. });
  358. }
  359. };
  360.  
  361. Switcheroo.prototype.createTooltip = function (tooltip) {
  362. let c = this.options.blockClass;
  363. // create popper
  364. let popper = document.createElement("div");
  365. if (this.options.enableReorder) {
  366. popper.draggable = false;
  367. }
  368. popper.classList.add(c + '__popper');
  369. // create popper text
  370. let textNode = document.createElement("div");
  371. textNode.classList.add(c + '__popper-text');
  372. if (this.options.enableReorder) {
  373. textNode.draggable = false;
  374. }
  375. textNode.innerHTML = tooltip;
  376. popper.appendChild(textNode);
  377. return popper;
  378. };
  379.  
  380. Switcheroo.prototype.createFormModal = function (options) {
  381. let t = this;
  382. const form = document.createDocumentFragment();
  383. const c = 'switcheroo';
  384.  
  385. const vdom = VD.h('form', {
  386. className: c + '__form',
  387. name: 'form_login',
  388. method: 'post',
  389. action: '/login',
  390. onSubmit: (e) => {
  391. e.preventDefault();
  392. this.add(e.target);
  393. }
  394. },
  395. VD.h('div', {
  396. className: c + '__form-row'
  397. },
  398. VD.h('label', {
  399. for: c + '-username',
  400. className: c + '__form-label'
  401. }, t.lang.modal.username_label),
  402. VD.h('input', {
  403. type: 'text',
  404. className: c + '__form-input',
  405. id: c + '-username',
  406. name: 'username',
  407. required: true,
  408. maxlength: '40'
  409. }),
  410. ),
  411. VD.h('div', {
  412. className: c + '__form-row'
  413. },
  414. VD.h('label', {
  415. for: c + '-password',
  416. className: c + '__form-label'
  417. }, t.lang.modal.password_label),
  418. VD.h('input', {
  419. className: c + '__form-input',
  420. type: 'password',
  421. id: c + '-password',
  422. name: 'password',
  423. required: true,
  424. maxlength: '32'
  425. })
  426. ),
  427. VD.h('input', {
  428. type: 'checkbox',
  429. style: 'display: none;',
  430. name: 'autologin',
  431. checked: true
  432. }),
  433. VD.h('div', {
  434. className: c + '__form-row'
  435. },
  436. VD.h('button', {
  437. name: 'login',
  438. className: c + '__form-button'
  439. }, t.lang.modal.login_button)
  440. )
  441. );
  442.  
  443. form.appendChild(VD.createElement(vdom));
  444.  
  445. this.loginModal = monomer.modal({
  446. content: VD.createElement(vdom),
  447. maxWidth: 400
  448. });
  449. };
  450.  
  451. Switcheroo.prototype.isBefore = function (el1, el2) {
  452. let cur;
  453. if (el2.parentNode === el1.parentNode) {
  454. for (cur = el1.previousSibling; cur; cur = cur.previousSibling) {
  455. if (cur === el2) return true;
  456. }
  457. }
  458. return false;
  459. };
  460.  
  461. Switcheroo.prototype.dragStart = function (e) {
  462. e.stopPropagation();
  463. let target = e.target;
  464. target.closest('.' + this.options.blockClass).classList.add('dragged');
  465. e.dataTransfer.effectAllowed = 'move';
  466. e.dataTransfer.setData('text/html', this.innerHTML);
  467. this.draggedElement = target;
  468. };
  469.  
  470. Switcheroo.prototype.dragOver = function (e) {
  471. e.stopPropagation();
  472. let target = e.target.closest('li');
  473. if (this.isBefore(this.draggedElement, target)) {
  474. this.insertDraggedBefore(this.draggedElement, target);
  475. } else {
  476. this.insertDraggedBefore(this.draggedElement, target.nextSibling);
  477. }
  478. };
  479.  
  480. Switcheroo.prototype.insertDraggedBefore = function (el1, el2) {
  481. el2.parentNode.insertBefore(el1, el2);
  482. };
  483.  
  484. Switcheroo.prototype.dragEnd = function (e) {
  485. e.stopPropagation();
  486. e.target.closest('.' + this.options.blockClass).classList.remove('dragged');
  487. this.draggedElement = null;
  488. this.sortSwitcheroo();
  489. };
  490.  
  491. Switcheroo.prototype.sortSwitcheroo = function () {
  492. let els = document.querySelectorAll('#switcheroo [data-id]');
  493. /* get new order */
  494. let newOrder = [];
  495. els.forEach(el => {
  496. newOrder.push(el.dataset.id);
  497. });
  498.  
  499.  
  500. let result = [];
  501. newOrder.forEach((key) => {
  502. /* go through each id added in new order */
  503. var found = false;
  504. this.switcherooCredentials.filter(function (item) {
  505. if (!found && item.id == key) {
  506. result.push(item);
  507. found = true;
  508. return false;
  509. }
  510. return true;
  511. })
  512. });
  513. this.updateStorage(result);
  514. };
  515.  
  516. global.Switcheroo = Switcheroo;
  517. })(window);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement