Kanka Atomic Entity Editor

Provides keyboard shortcuts for simple edits from the entity view page on Kanka.

  1. // ==UserScript==
  2. // @name Kanka Atomic Entity Editor
  3. // @namespace https://greatest.deepsurf.us/en/users/1029479-infinitegeek
  4. // @version 1.0.0
  5. // @description Provides keyboard shortcuts for simple edits from the entity view page on Kanka.
  6. // @author InfiniteGeek
  7. // @supportURL Infinite @ https://discord.gg/rhsyZJ4
  8. // @license MIT
  9. // @match https://app.kanka.io/w/*/entities/*
  10. // @icon https://www.google.com/s2/favicons?domain=kanka.io
  11. // @keywords kanka,keybind,keyboard,shortcut,hotkey,tag,location,entity,edit
  12. // @run-at document-idle
  13. // @grant none
  14. // @require https://craig.global.ssl.fastly.net/js/mousetrap/mousetrap.min.js?a4098
  15. // ==/UserScript==
  16.  
  17. /******/ (() => { // webpackBootstrap
  18. /******/ "use strict";
  19. /******/ var __webpack_modules__ = ({
  20.  
  21. /***/ 519:
  22. /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
  23.  
  24.  
  25. var __importDefault = (this && this.__importDefault) || function (mod) {
  26. return (mod && mod.__esModule) ? mod : { "default": mod };
  27. };
  28. var _a, _b, _c, _d, _e, _f;
  29. Object.defineProperty(exports, "__esModule", ({ value: true }));
  30. /* ====================================
  31. You can change these keybinds
  32. ====================================
  33. */
  34. const keybinds = {
  35. LABEL: 'l',
  36. MOVE: 'm',
  37. HELP: '?',
  38. };
  39. /*
  40.  
  41. ## Combination of keys - generic mod helper sets cross platform shortcuts
  42. 'mod+s' => command+s / ctrl+s
  43.  
  44. ## Sequence of keys - keys separated by a space will be considered a sequence
  45. 'g i'
  46.  
  47. ## Shift key - handled magically
  48. '?' instead of 'shift+/'
  49.  
  50. ## Text fields - keyboard events will not fire in textarea, input, or select
  51. enable on an element with [class='mousetrap']
  52.  
  53. */
  54. /* =======================================================
  55. You probably shouldn't edit below... probably.
  56. Here there be `Dragons : Reptile<Mythical>[]`
  57. ======================================================= */
  58. const mousetrap_1 = __importDefault(__webpack_require__(802));
  59. // import tippy from 'tippy';
  60. const emit_debug = console.log;
  61. // this is a jQuery 'plugin' to make an element blink
  62. $.prototype.blink = function (times, duration) {
  63. for (let i = 0; i < times; i++) {
  64. this.animate({ opacity: 0 }, duration)
  65. .animate({ opacity: 1 }, duration);
  66. }
  67. return this;
  68. };
  69. /**
  70. * Extract metadata from the classes on the <body>
  71. */
  72. function parseBodyClasses(body) {
  73. const classes = Array.from(body.classList);
  74. const entity = { id: '', entityType: 'default', type: '' };
  75. const tags = [];
  76. const regex = /^kanka-(\w+)-(\w+)$/;
  77. let tempTag = null;
  78. classes.forEach(className => {
  79. const match = className.match(regex);
  80. if (match) {
  81. const [, key, value] = match;
  82. const isValueNumeric = !isNaN(Number(value));
  83. switch (key) {
  84. case 'entity':
  85. entity[isValueNumeric ? 'id' : 'entityType'] = value;
  86. break;
  87. case 'type':
  88. entity.type = value;
  89. break;
  90. case 'tag':
  91. if (isValueNumeric) {
  92. tempTag = value;
  93. }
  94. else {
  95. tags.push({
  96. id: tempTag,
  97. entityType: value,
  98. });
  99. tempTag = null;
  100. }
  101. break;
  102. default:
  103. emit_debug("what's this?", match);
  104. break;
  105. }
  106. }
  107. });
  108. return { entity, tags };
  109. }
  110. const route = window.location.pathname;
  111. // using the edit button is necessary to get the typedID and the plural :\
  112. const editButtonLink = (_a = $('div#entity-submenu a[href$="edit"]').attr('href')) !== null && _a !== void 0 ? _a : $('div.header-buttons a[href$="edit"]').attr('href');
  113. /**
  114. * This contains "all" the Kanka-specific data
  115. */
  116. const kanka = {
  117. rootUri: 'https://app.kanka.io',
  118. getUri: (...segments) => [kanka.rootUri, 'w', kanka.campaignID, ...segments].join('/'),
  119. /**
  120. * Ye olde CSRF token
  121. */
  122. csrfToken: (_b = document.head.querySelector('meta[name="csrf-token"]')) === null || _b === void 0 ? void 0 : _b.getAttribute('content'),
  123. route,
  124. campaignID: ((_c = route.match(/w\/(\d+)\//)) !== null && _c !== void 0 ? _c : [null, '0'])[1],
  125. /**
  126. * this is the plural, not values from EntityType
  127. */
  128. entityType: ((_d = editButtonLink === null || editButtonLink === void 0 ? void 0 : editButtonLink.match(/\/(\w+)\/\d+\/edit$/)) !== null && _d !== void 0 ? _d : [null, '0'])[1],
  129. /**
  130. * this is the 'larger' ID: entities/__[5328807]__ === characters/1357612
  131. */
  132. entityID: ((_e = route.match(/w\/\d+\/entities\/(\d+)/)) !== null && _e !== void 0 ? _e : [null, '0'])[1],
  133. /**
  134. * this is the 'smaller' ID: entities/5328807 === characters/__[1357612]__
  135. */
  136. typedID: ((_f = editButtonLink === null || editButtonLink === void 0 ? void 0 : editButtonLink.match(/\/(\d+)\/edit$/)) !== null && _f !== void 0 ? _f : [null, '0'])[1],
  137. meta: parseBodyClasses(document.body),
  138. /**
  139. * this encapsulates the definitions from the system
  140. * - some entities have a location, some don't
  141. * - some entities have a link in the header, some use the sidebar
  142. * - some entities can have multiple locations, some can't
  143. */
  144. entityTypeHasLocation: ({
  145. default: {},
  146. character: { headerLink: true },
  147. location: { headerLink: true },
  148. map: { headerLink: true },
  149. organisation: { sidebarLink: true },
  150. family: { headerLink: true },
  151. creature: { sidebarLink: true, multiple: true },
  152. race: { sidebarLink: true, multiple: true },
  153. event: { sidebarLink: true },
  154. journal: { sidebarLink: true },
  155. item: { sidebarLink: true },
  156. tag: {},
  157. note: {},
  158. quest: {},
  159. }),
  160. };
  161. const identifiers = {
  162. Sidebar: {
  163. Class: '.entity-sidebar',
  164. ProfileClass: '.sidebar-section-profile',
  165. ProfileElementsID: '#sidebar-profile-elements',
  166. },
  167. };
  168. const templates = {
  169. SIDEBAR_PROFILE: () => `
  170. <div class="sidebar-section-box ${identifiers.Sidebar.ProfileClass.slice(1)} overflow-hidden flex flex-col gap-2">
  171. <div class="sidebar-section-title cursor-pointer text-lg user-select border-b element-toggle" data-animate="collapse" data-target="#sidebar-profile-elements">
  172. <i class="fa-solid fa-chevron-up icon-show"></i>
  173. <i class="fa-solid fa-chevron-down icon-hide"></i>
  174. Profile
  175. </div>
  176.  
  177. <div class="sidebar-elements grid overflow-hidden" id="${identifiers.Sidebar.ProfileElementsID.slice(1)}">
  178. </div>
  179. </div>`.trim(),
  180. SELECT_ELEMENT: (dataUrl, placeholder) => `
  181. <select class="form-tags select2"
  182. style="width: 100%"
  183. data-url="${dataUrl}"
  184. data-allow-new="false"
  185. data-allow-clear="true"
  186. data-placeholder="${placeholder}"
  187. data-dropdown-parent="#app"
  188. </select>`.trim(),
  189. SELECT_ITEM: (text, image) => {
  190. if (!!image) {
  191. return $(`
  192. <span class="flex gap-2 items-center text-left">
  193. <img src="${image}" class="rounded-full flex-none w-6 h-6" />
  194. <span class="grow">${text}</span>
  195. </span>`.trim());
  196. }
  197. return $(`<span>${text}</span>`);
  198. },
  199. TAG_SELECT: () => templates.SELECT_ELEMENT(kanka.getUri('search/tags'), 'Apply Tag'),
  200. TAG_URL: (tagID) => kanka.getUri('tags', tagID),
  201. TAG_LINK: (tagID, text) => `
  202. <a href="${templates.TAG_URL(tagID)}" title="Refresh to get full tooltip functionality">
  203. <span class="badge color-tag rounded-sm px-2 py-1">${text}</span>
  204. </a>`.trim(),
  205. LOCATION_SELECT: () => templates.SELECT_ELEMENT(kanka.getUri('search/locations'), 'Move to...'),
  206. LOCATION_URL: (locationID) => kanka.getUri('entities', locationID),
  207. LOCATION_LINK: (locationID, text) => `<a class="name" href="${templates.LOCATION_URL(locationID)}" title="Refresh to get full tooltip functionality">${text}</a>`,
  208. // TODO - get popper/tippy working to enable preview tooltips
  209. // data-toggle="tooltip-ajax" data-id="${locationID}" data-url="${templates.LOCATION_URL(locationID)}/tooltip">
  210. };
  211. /// making my own container for the select to avoid any interference
  212. function createFloatingElement(template) {
  213. const divID = 'infinite-select2';
  214. let floatingDiv = document.getElementById(divID)
  215. || document.createElement('div');
  216. if (!floatingDiv.id) {
  217. floatingDiv.id = divID;
  218. // Add styles to make it float and position it as needed
  219. floatingDiv.style.position = 'absolute';
  220. floatingDiv.style.top = '5%';
  221. floatingDiv.style.left = '41%';
  222. floatingDiv.style.minWidth = '200px';
  223. floatingDiv.style.width = '18%';
  224. floatingDiv.style.maxWidth = '400px';
  225. }
  226. floatingDiv.innerHTML = '';
  227. $(template()).appendTo(floatingDiv);
  228. document.body.appendChild(floatingDiv);
  229. return floatingDiv;
  230. }
  231. function createPostParams() {
  232. const params = new URLSearchParams();
  233. params.append('_token', kanka.csrfToken);
  234. params.append('datagrid-action', 'batch');
  235. // this needs the plural
  236. params.append('entity', kanka.entityType);
  237. params.append('mode', 'table');
  238. // typedID is different from entityID
  239. params.append('models', kanka.typedID);
  240. params.append('undefined', '');
  241. return params;
  242. }
  243. async function fetch_success(response) {
  244. var _a;
  245. emit_debug('Success:', response);
  246. return { ok: response.ok, document: (_a = $.parseHTML(await response.text())) !== null && _a !== void 0 ? _a : [] };
  247. }
  248. function post(url, body) {
  249. return fetch(url, {
  250. method: 'POST',
  251. redirect: 'follow',
  252. headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  253. body,
  254. })
  255. .then(fetch_success)
  256. .catch((error) => {
  257. console.error('Error:', error);
  258. return { ok: false, document: [], error };
  259. });
  260. }
  261. async function edit(body) {
  262. // wat da faq
  263. emit_debug({ edit_data: [...body.entries()] });
  264. var xhr = new XMLHttpRequest();
  265. xhr.withCredentials = true;
  266. xhr.open('POST', kanka.getUri(kanka.entityType, kanka.typedID), false);
  267. xhr.setRequestHeader('x-csrf-token', kanka.csrfToken);
  268. xhr.setRequestHeader('x-requested-with', 'XMLHttpRequest');
  269. xhr.send(body);
  270. emit_debug({ req: xhr });
  271. return {
  272. ok: xhr.status == 200,
  273. document: $.parseHTML(xhr.responseText),
  274. };
  275. return fetch(kanka.getUri(kanka.entityType, kanka.typedID), {
  276. method: 'POST',
  277. headers: {
  278. "x-csrf-token": kanka.csrfToken,
  279. "x-requested-with": "XMLHttpRequest"
  280. },
  281. redirect: 'follow',
  282. body,
  283. })
  284. .then(fetch_success)
  285. .catch((error) => {
  286. console.error('Error:', error);
  287. return { ok: false, document: [], error };
  288. });
  289. }
  290. /**
  291. * Reacts when Location is selected via floaty dropdown. Sets the Location of the entity.
  292. *
  293. * @param event - The Select2 event object.
  294. * @returns A promise that resolves to a boolean indicating whether the processing was successful.
  295. */
  296. async function processLocationSelection(event) {
  297. const { id: locationID, text } = event.params.data;
  298. const thisEntityTypeHasLocation = kanka.entityTypeHasLocation[kanka.meta.entity.entityType];
  299. if (thisEntityTypeHasLocation.multiple) {
  300. alert('This entity type can have multiple locations. This feature is not yet implemented.');
  301. /**
  302. * For the curious, it's because the edit endpoint needs:
  303. * - the list of typed IDs (which we don't have)
  304. * - some weird voodoo with XHR that I can't replicate (I get a 405 Method Not Allowed)
  305. */
  306. return false;
  307. const data = new FormData();
  308. data.append('_token', kanka.csrfToken);
  309. // this is kinda BS, but it's the cleanest way to get
  310. // - the list of typed IDs
  311. // - the other stuff
  312. const editable = await fetch(kanka.getUri('creatures', kanka.typedID, 'edit'), {
  313. method: 'GET',
  314. headers: { 'Content-Type': 'text/html' }
  315. })
  316. .then(fetch_success);
  317. if (!editable.ok) {
  318. emit_debug('Error:', editable);
  319. return false;
  320. }
  321. $(editable.document)
  322. .find('form#entity-form')
  323. .serializeArray()
  324. // .filter(kvp => {
  325. // if (kvp.value == '') return false;
  326. // if (kvp.value == '0') return false;
  327. // if (kvp.value == 'inherit') return false;
  328. // })
  329. .forEach(kvp => data.append(kvp.name, kvp.value));
  330. data.append('locations[]', locationID);
  331. const response = await edit(data);
  332. if (response.ok) {
  333. const doc = $(response.document);
  334. emit_debug({
  335. header: doc.find('.entity-header'),
  336. sidebar: doc.find('#sidebar-profile-elements'),
  337. });
  338. }
  339. return response.ok;
  340. }
  341. const params = createPostParams();
  342. params.append('location_id', locationID);
  343. const response = await post(kanka.getUri('bulk/process'), params);
  344. if (!response.ok) {
  345. emit_debug('Error:', response);
  346. return false;
  347. }
  348. const sub = (selector) => {
  349. $(selector).replaceWith($(response.document).find(selector));
  350. return $(selector);
  351. };
  352. const ensure = (parent, selector, defaultValue) => {
  353. if ($(selector).length == 0) {
  354. emit_debug(`adding ${selector} to ${parent}`);
  355. parent.append(defaultValue);
  356. }
  357. };
  358. if (thisEntityTypeHasLocation.headerLink) {
  359. // TODO [2024-03-06] - reduce the replacement scope to keep more functionality
  360. sub('.entity-header')
  361. .find('.entity-header-sub')
  362. .blink(3, 125);
  363. }
  364. if (thisEntityTypeHasLocation.sidebarLink) {
  365. const sidebar = $(identifiers.Sidebar.Class);
  366. // make sure the sidebar has the relevant childrens
  367. ensure(sidebar, identifiers.Sidebar.ProfileClass, templates.SIDEBAR_PROFILE());
  368. // an entity might have the sidebar, but not the Profile block
  369. ensure(sidebar, identifiers.Sidebar.ProfileElementsID, `<div id="${identifiers.Sidebar.ProfileElementsID.slice(1)}"></div>`);
  370. // and the Profile block may or may not have the Location
  371. ensure(sidebar.find(identifiers.Sidebar.ProfileElementsID), '.profile-location', `<div class="profile-location"></div>`);
  372. sub(identifiers.Sidebar.ProfileElementsID)
  373. .find('.profile-location')
  374. .blink(3, 125);
  375. }
  376. return true;
  377. }
  378. /**
  379. * Reacts when a Tag is selected via floaty dropdown. Toggles the presence of the tag on the entity.
  380. *
  381. * @param event - The Select2 event object.
  382. * @returns A promise that resolves to a boolean indicating whether the processing was successful.
  383. */
  384. async function processTagSelection(event) {
  385. const { id: tagID, text } = event.params.data;
  386. const params = createPostParams();
  387. params.append('save-tags', '1');
  388. params.append('tags[]', tagID);
  389. const header = $('.entity-header .entity-header-text');
  390. if (header.has('.entity-tags').length == 0) {
  391. $('<div class="entity-tags entity-header-line text-xs flex flex-wrap gap-2"></div>')
  392. .insertBefore(header.find('.header-buttons'));
  393. }
  394. const hasTag = !!kanka.meta.tags.find(tag => tag.id == tagID);
  395. params.append('bulk-tagging', hasTag ? 'remove' : 'add');
  396. const result = await post(`/w/${kanka.campaignID}/bulk/process`, params);
  397. const tagBar = header.find('.entity-tags');
  398. if (result.ok) {
  399. (hasTag
  400. ? tagBar.children().remove(`[href="${templates.TAG_URL(tagID)}"]`)
  401. : tagBar.append($(templates.TAG_LINK(tagID, text))))
  402. .blink(3, 125);
  403. }
  404. return result.ok;
  405. /*
  406. // was doing it using the simple 'add entity under tag' API
  407. // but why not consolidate?
  408. params.append('entities[]', kanka.meta.entity.id);
  409. params.append('tag_id', tagID);
  410. post(kanka.getUri('tags', tagID, 'entity-add'), params)
  411. .then((ok) => ok && tagBar.append($(templates.TAG_LINK(tagID, text))));
  412. */
  413. }
  414. function initSelector(template, processSelection) {
  415. const floatingDiv = createFloatingElement(template);
  416. $(floatingDiv).find('select.select2')
  417. .each(function () {
  418. const me = $(this);
  419. me.select2({
  420. tags: false,
  421. placeholder: me.data('placeholder'),
  422. allowClear: me.data('allowClear') || true,
  423. language: me.data('language'),
  424. minimumInputLength: 0,
  425. dropdownParent: $(me.data('dropdownParent')) || '',
  426. width: '100%',
  427. sorter: (data) => {
  428. const term = $('input.select2-search__field').val().toLowerCase();
  429. return data.sort(byMatchiness(term));
  430. },
  431. ajax: {
  432. delay: 500, // quiet ms
  433. url: me.data('url'),
  434. dataType: 'json',
  435. data: (params) => { var _a; return ({ q: (_a = params.term) === null || _a === void 0 ? void 0 : _a.trim() }); },
  436. processResults: (data) => ({ results: data }),
  437. error: function (jqXHR, textStatus, errorThrown) {
  438. if (textStatus === 'abort') {
  439. // it does this for the empty field, I think?
  440. return;
  441. }
  442. if (jqXHR.status === 503) {
  443. window.showToast(jqXHR.responseJSON.message, 'error');
  444. }
  445. emit_debug('error', jqXHR, textStatus, errorThrown);
  446. return { results: [] };
  447. },
  448. cache: true
  449. },
  450. templateResult: (item) => templates.SELECT_ITEM(item.text, item.image),
  451. })
  452. .on('select2:select', processSelection)
  453. .on('select2:close', () => {
  454. setTimeout(() => { $(floatingDiv).remove(); }, 100);
  455. });
  456. setTimeout(() => { me.select2('open'); }, 0);
  457. });
  458. }
  459. function byMatchiness(term) {
  460. return (a, b) => {
  461. const textA = a.text.toLowerCase();
  462. const textB = b.text.toLowerCase();
  463. // Assign a score based on how well the option matches the search term
  464. const scoreA = textA === term ? 3 : textA.startsWith(term) ? 2 : textA.includes(term) ? 1 : 0;
  465. const scoreB = textB === term ? 3 : textB.startsWith(term) ? 2 : textB.includes(term) ? 1 : 0;
  466. // Sort by score. If the scores are equal, sort alphabetically
  467. return scoreB - scoreA || textA.localeCompare(textB);
  468. };
  469. }
  470. /**
  471. * Map the keybinds to the handlers
  472. */
  473. const handlers = {
  474. [keybinds.LABEL]: function (evt, combo) {
  475. initSelector(templates.TAG_SELECT, processTagSelection);
  476. },
  477. [keybinds.MOVE]: function (evt, combo) {
  478. initSelector(templates.LOCATION_SELECT, processLocationSelection);
  479. },
  480. [keybinds.HELP]: function (evt, combo) {
  481. // TODO show a modal describing the keybinds
  482. },
  483. };
  484. (function () {
  485. if (!document.body.className.includes('kanka-entity-')) {
  486. return;
  487. }
  488. for (const key in handlers) {
  489. mousetrap_1.default.bind(key, handlers[key]);
  490. }
  491. emit_debug({ kanka });
  492. })();
  493.  
  494.  
  495. /***/ }),
  496.  
  497. /***/ 802:
  498. /***/ ((module) => {
  499.  
  500. module.exports = Mousetrap;
  501.  
  502. /***/ })
  503.  
  504. /******/ });
  505. /************************************************************************/
  506. /******/ // The module cache
  507. /******/ var __webpack_module_cache__ = {};
  508. /******/
  509. /******/ // The require function
  510. /******/ function __webpack_require__(moduleId) {
  511. /******/ // Check if module is in cache
  512. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  513. /******/ if (cachedModule !== undefined) {
  514. /******/ return cachedModule.exports;
  515. /******/ }
  516. /******/ // Create a new module (and put it into the cache)
  517. /******/ var module = __webpack_module_cache__[moduleId] = {
  518. /******/ // no module.id needed
  519. /******/ // no module.loaded needed
  520. /******/ exports: {}
  521. /******/ };
  522. /******/
  523. /******/ // Execute the module function
  524. /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  525. /******/
  526. /******/ // Return the exports of the module
  527. /******/ return module.exports;
  528. /******/ }
  529. /******/
  530. /************************************************************************/
  531. /******/
  532. /******/ // startup
  533. /******/ // Load entry module and return exports
  534. /******/ // This entry module is referenced by other modules so it can't be inlined
  535. /******/ var __webpack_exports__ = __webpack_require__(519);
  536. /******/
  537. /******/ })()
  538. ;