Kanka.io Keybinds

Set your own keyboard shortcuts for entity view page on Kanka.

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

  1. // ==UserScript==
  2. // @name Kanka.io Keybinds
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.8.3-4
  5. // @description Set your own keyboard shortcuts for entity view page on Kanka.
  6. // @author Infinite
  7. // @license MIT
  8. // @match https://app.kanka.io/w/*/entities/*
  9. // @icon https://www.google.com/s2/favicons?domain=kanka.io
  10. // @run-at document-idle
  11. // @grant none
  12. // @require https://craig.global.ssl.fastly.net/js/mousetrap/mousetrap.min.js?a4098
  13. // @require https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js
  14. // ==/UserScript==
  15.  
  16. /******/ (() => { // webpackBootstrap
  17. /******/ "use strict";
  18. /******/ var __webpack_modules__ = ({
  19.  
  20. /***/ 519:
  21. /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
  22.  
  23.  
  24. var __importDefault = (this && this.__importDefault) || function (mod) {
  25. return (mod && mod.__esModule) ? mod : { "default": mod };
  26. };
  27. var _a, _b, _c, _d, _e, _f;
  28. Object.defineProperty(exports, "__esModule", ({ value: true }));
  29. /* ====================================
  30. You can change these keybinds
  31. ====================================
  32. */
  33. const keybinds = {
  34. LABEL: 'l',
  35. MOVE: 'm',
  36. HELP: '?',
  37. };
  38. /*
  39.  
  40. ## Combination of keys - generic mod helper sets cross platform shortcuts
  41. 'mod+s' => command+s / ctrl+s
  42.  
  43. ## Sequence of keys - keys separated by a space will be considered a sequence
  44. 'g i'
  45.  
  46. ## Shift key - handled magically
  47. '?' instead of 'shift+/'
  48.  
  49. ## Text fields - keyboard events will not fire in textarea, input, or select
  50. enable with [class='mousetrap']
  51.  
  52. */
  53. /* =======================================
  54. You probably shouldn't edit below
  55. ======================================= */
  56. const mousetrap_1 = __importDefault(__webpack_require__(802));
  57. function parseBodyClasses(body) {
  58. const classes = Array.from(body.classList);
  59. const entity = { id: '', entityType: 'default', type: '' };
  60. const tags = [];
  61. const regex = /^kanka-(\w+)-(\w+)$/;
  62. let tempTag = null;
  63. classes.forEach(className => {
  64. const match = className.match(regex);
  65. if (match) {
  66. const [, key, value] = match;
  67. const isValueNumeric = !isNaN(Number(value));
  68. switch (key) {
  69. case 'entity':
  70. entity[isValueNumeric ? 'id' : 'entityType'] = value;
  71. break;
  72. case 'type':
  73. entity.type = value;
  74. break;
  75. case 'tag':
  76. if (isValueNumeric) {
  77. tempTag = value;
  78. }
  79. else {
  80. tags.push({
  81. id: tempTag,
  82. entityType: value,
  83. });
  84. tempTag = null;
  85. }
  86. break;
  87. default:
  88. console.warn("what's this?", match);
  89. break;
  90. }
  91. }
  92. });
  93. return { tags, entity };
  94. }
  95. const editButtonLink = (_a = $('div#entity-submenu a[href$="edit"]').attr('href')) !== null && _a !== void 0 ? _a : $('div.header-buttons a[href$="edit"]').attr('href');
  96. const route = window.location.pathname;
  97. const kanka = {
  98. csrfToken: (_b = document.head.querySelector('meta[name="csrf-token"]')) === null || _b === void 0 ? void 0 : _b.getAttribute('content'),
  99. route,
  100. campaignID: ((_c = route.match(/w\/(\d+)\//)) !== null && _c !== void 0 ? _c : [null, '0'])[1],
  101. // this is the plural, not values from EntityType
  102. entityType: ((_d = editButtonLink === null || editButtonLink === void 0 ? void 0 : editButtonLink.match(/\/(\w+)\/\d+\/edit$/)) !== null && _d !== void 0 ? _d : [null, '0'])[1],
  103. // this is the 'larger' ID: entities/*5328807* === characters/1357612
  104. entityID: ((_e = route.match(/w\/\d+\/entities\/(\d+)/)) !== null && _e !== void 0 ? _e : [null, '0'])[1],
  105. // this is the 'smaller' ID: entities/5328807 === characters/*1357612*
  106. typedID: ((_f = editButtonLink === null || editButtonLink === void 0 ? void 0 : editButtonLink.match(/\/(\d+)\/edit$/)) !== null && _f !== void 0 ? _f : [null, '0'])[1],
  107. meta: parseBodyClasses(document.body),
  108. entityTypeHasLocation: ({
  109. default: {},
  110. character: { headerLink: true },
  111. location: { headerLink: true },
  112. map: { headerLink: true },
  113. organisation: { sidebarLink: true },
  114. family: { headerLink: true },
  115. creature: { sidebarLink: true, multiple: true },
  116. race: { sidebarLink: true, multiple: true },
  117. event: { sidebarLink: true },
  118. journal: { sidebarLink: true },
  119. item: { sidebarLink: true },
  120. tag: {},
  121. note: {},
  122. quest: {},
  123. }),
  124. };
  125. const handlers = {
  126. [keybinds.LABEL]: function (evt, combo) {
  127. initSelector(templates.TAG_SELECT, processTagSelection);
  128. },
  129. [keybinds.MOVE]: function (evt, combo) {
  130. initSelector(templates.LOCATION_SELECT, processLocationSelection);
  131. },
  132. [keybinds.HELP]: function (evt, combo) {
  133. // TODO show a modal describing the keybinds
  134. },
  135. };
  136. const templates = {
  137. SELECT_ELEMENT: (dataUrl, placeholder) => `
  138. <select class="form-tags select2"
  139. style="width: 100%"
  140. data-url="${dataUrl}"
  141. data-allow-new="false"
  142. data-allow-clear="true"
  143. data-placeholder="${placeholder}"
  144. data-dropdown-parent="#app"
  145. </select>`.trim(),
  146. SELECT_ITEM: (text, image) => {
  147. if (!!image) {
  148. return $(`
  149. <span class="flex gap-2 items-center text-left">
  150. <img src="${image}" class="rounded-full flex-none w-6 h-6" />
  151. <span class="grow">${text}</span>
  152. </span>`.trim());
  153. }
  154. return $(`<span>${text}</span>`);
  155. },
  156. TAG_SELECT: () => templates.SELECT_ELEMENT(`https://app.kanka.io/w/${kanka.campaignID}/search/tags`, 'Apply Tag'),
  157. TAG_URL: (tagID) => `https://app.kanka.io/w/${kanka.campaignID}/tags/${tagID}`,
  158. TAG_LINK: (tagID, text) => `
  159. <a href="${templates.TAG_URL(tagID)}" title="Refresh to get full tooltip functionality">
  160. <span class="badge color-tag rounded-sm px-2 py-1">${text}</span>
  161. </a>`.trim(),
  162. LOCATION_SELECT: () => templates.SELECT_ELEMENT(`https://app.kanka.io/w/${kanka.campaignID}/search/locations`, 'Move to...'),
  163. LOCATION_URL: (locationID) => `https://app.kanka.io/w/${kanka.campaignID}/entities/${locationID}`,
  164. LOCATION_LINK: (locationID, text) => `<a class="name" href="${templates.LOCATION_URL(locationID)}" title="Refresh to get full tooltip functionality">${text}</a>`,
  165. // TODO - get popper/tippy working to enable preview tooltips
  166. // data-toggle="tooltip-ajax" data-id="${locationID}" data-url="${templates.LOCATION_URL(locationID)}/tooltip">
  167. };
  168. /// making my own container for the select to avoid any interference
  169. function createFloatingElement(template) {
  170. let floatingDiv = document.getElementById('#infinite-select2');
  171. if (!floatingDiv) {
  172. floatingDiv = document.createElement('div');
  173. floatingDiv.id = 'infinite-select2';
  174. // Add styles to make it float and position it as needed
  175. floatingDiv.style.position = 'absolute';
  176. floatingDiv.style.top = '5%';
  177. floatingDiv.style.left = '41%';
  178. floatingDiv.style.minWidth = '200px';
  179. floatingDiv.style.width = '18%';
  180. floatingDiv.style.maxWidth = '400px';
  181. }
  182. floatingDiv.innerHTML = '';
  183. $(template()).appendTo(floatingDiv);
  184. document.body.appendChild(floatingDiv);
  185. return floatingDiv;
  186. }
  187. function createPostParams() {
  188. const params = new URLSearchParams();
  189. params.append('_token', kanka.csrfToken);
  190. params.append('datagrid-action', 'batch');
  191. // this needs the plural
  192. params.append('entity', kanka.entityType);
  193. params.append('mode', 'table');
  194. // typedID is different from entityID
  195. params.append('models', kanka.typedID);
  196. params.append('undefined', '');
  197. return params;
  198. }
  199. function post(url, body) {
  200. return fetch(url, {
  201. method: 'POST',
  202. redirect: 'follow',
  203. headers: {
  204. 'Content-Type': 'application/x-www-form-urlencoded',
  205. },
  206. body,
  207. })
  208. .then(async (response) => {
  209. var _a;
  210. console.log('Success:', response);
  211. const document = await ((_a = response.body) === null || _a === void 0 ? void 0 : _a.getReader().read().then(content => {
  212. const responseHtml = new TextDecoder().decode(content.value);
  213. return $.parseHTML(responseHtml);
  214. }));
  215. return { ok: response.ok, document: document !== null && document !== void 0 ? document : [] };
  216. })
  217. .catch((error) => {
  218. console.error('Error:', error);
  219. return { ok: error.ok, document: [] };
  220. });
  221. }
  222. function processLocationSelection(event) {
  223. const { id: locationID, text } = event.params.data;
  224. const params = createPostParams();
  225. params.append('location_id', locationID);
  226. post(`/w/${kanka.campaignID}/bulk/process`, params)
  227. .then(response => {
  228. return response.ok && $('.entity-header').replaceWith($(response.document).find('.entity-header'));
  229. const thisEntityLocation = kanka.entityTypeHasLocation[kanka.meta.entity.entityType];
  230. if (thisEntityLocation.headerLink) {
  231. const headerLink_Location = $($('[title="Location"]').next().next());
  232. if (!!headerLink_Location) {
  233. headerLink_Location.replaceWith(templates.LOCATION_LINK(locationID, text));
  234. }
  235. }
  236. /*
  237. <div class="entity-tags entity-header-line text-xs flex flex-wrap gap-2">
  238. <a href="https://app.kanka.io/w/9070/tags/240570" data-toggle="tooltip-ajax"
  239. data-id="3607547" data-url="https://app.kanka.io/w/9070/entities/3607547/tooltip"
  240. data-tag-slug="spider">
  241. <span class="badge color-tag rounded-sm px-2 py-1">Spider</span>
  242. </a>
  243. </div>
  244. <div class="entity-header-sub entity-header-line">
  245. <div class="entity-header-sub-element">
  246. <i class="fa-duotone fa-circle-location-arrow " aria-hidden="true"
  247. title="Location" ></i>
  248. <a class="name" data-toggle="tooltip-ajax" data-id="3566987" data-url="https://app.kanka.io/w/9070/entities/3566987/tooltip" href="https://app.kanka.io/w/9070/entities/3566987">Valley of Ghosts and Spiders</a>
  249. in
  250. <a class="name" data-toggle="tooltip-ajax" data-id="3566949" data-url="https://app.kanka.io/w/9070/entities/3566949/tooltip" href="https://app.kanka.io/w/9070/entities/3566949">Crane Lands</a>
  251. </div>
  252. </div>
  253. */
  254. if (thisEntityLocation.sidebarLink) {
  255. const sidebar = $('#sidebar-profile-elements > div').first();
  256. let sidebar_Location = sidebar.find('.profile-location');
  257. if (!sidebar_Location) {
  258. sidebar_Location = $('<div class="element profile-location">');
  259. sidebar_Location.append($('<div class="title text-uppercase text-xs">Location</div>'));
  260. sidebar.prepend(sidebar_Location);
  261. }
  262. const link = templates.LOCATION_LINK(locationID, text);
  263. if (thisEntityLocation.multiple) {
  264. sidebar_Location.append(link);
  265. }
  266. else {
  267. sidebar_Location.find('a').replaceWith(link);
  268. }
  269. }
  270. });
  271. }
  272. function processTagSelection(event) {
  273. const { id: tagID, text } = event.params.data;
  274. const params = createPostParams();
  275. params.append('save-tags', '1');
  276. params.append('tags[]', tagID);
  277. const header = $('.entity-header .entity-header-text');
  278. if (header.has('.entity-tags').length == 0) {
  279. $('<div class="entity-tags entity-header-line text-xs flex flex-wrap gap-2"></div>')
  280. .insertBefore(header.find('.header-buttons'));
  281. }
  282. const hasTag = !!kanka.meta.tags.find(tag => tag.id == tagID);
  283. params.append('bulk-tagging', hasTag ? 'remove' : 'add');
  284. return post(`/w/${kanka.campaignID}/bulk/process`, params)
  285. .then((ok) => {
  286. const tagBar = header.find('.entity-tags');
  287. ok && hasTag
  288. ? tagBar.children().remove(`[href="${templates.TAG_URL(tagID)}"]`)
  289. : tagBar.append($(templates.TAG_LINK(tagID, text)));
  290. });
  291. /*
  292. // was doing it using the simple 'add entity under tag' API
  293. // but why not consolidate?
  294. params.append('entities[]', kanka.meta.entity.id);
  295. params.append('tag_id', tagID);
  296. post(`/w/${kanka.campaignID}/tags/${tagID}/entity-add/`, params)
  297. .then((ok) => ok && tagBar.append($(templates.TAG_LINK(tagID, text))));
  298. */
  299. }
  300. function initSelector(template, processSelection) {
  301. const floatingDiv = createFloatingElement(template);
  302. $(floatingDiv).find('select.select2')
  303. .each(function () {
  304. const me = $(this);
  305. me.select2({
  306. tags: false,
  307. placeholder: me.data('placeholder'),
  308. allowClear: me.data('allowClear') || true,
  309. language: me.data('language'),
  310. minimumInputLength: 0,
  311. dropdownParent: $(me.data('dropdownParent')) || '',
  312. width: '100%',
  313. sorter: (data) => {
  314. const term = $('input.select2-search__field').val().toLowerCase();
  315. return data.sort(byMatchiness(term));
  316. },
  317. ajax: {
  318. delay: 500, // quiet ms
  319. url: me.data('url'),
  320. dataType: 'json',
  321. data: (params) => { var _a; return ({ q: (_a = params.term) === null || _a === void 0 ? void 0 : _a.trim() }); },
  322. processResults: (data) => ({ results: data }),
  323. error: function (jqXHR, textStatus, errorThrown) {
  324. if (textStatus === 'abort') {
  325. // it does this for the empty field, I think?
  326. return;
  327. }
  328. if (jqXHR.status === 503) {
  329. window.showToast(jqXHR.responseJSON.message, 'error');
  330. }
  331. console.log('error', jqXHR, textStatus, errorThrown);
  332. return { results: [] };
  333. },
  334. cache: true
  335. },
  336. templateResult: (item) => templates.SELECT_ITEM(item.text, item.image),
  337. })
  338. .on('select2:select', processSelection)
  339. .on('select2:close', () => {
  340. setTimeout(() => { $(floatingDiv).remove(); }, 100);
  341. });
  342. setTimeout(() => { me.select2('open'); }, 0);
  343. });
  344. }
  345. function byMatchiness(term) {
  346. return (a, b) => {
  347. const textA = a.text.toLowerCase();
  348. const textB = b.text.toLowerCase();
  349. // Assign a score based on how well the option matches the search term
  350. const scoreA = textA === term ? 3 : textA.startsWith(term) ? 2 : textA.includes(term) ? 1 : 0;
  351. const scoreB = textB === term ? 3 : textB.startsWith(term) ? 2 : textB.includes(term) ? 1 : 0;
  352. // Sort by score. If the scores are equal, sort alphabetically
  353. return scoreB - scoreA || textA.localeCompare(textB);
  354. };
  355. }
  356. (function () {
  357. if (!document.body.className.includes('kanka-entity-')) {
  358. return;
  359. }
  360. for (const key in handlers) {
  361. mousetrap_1.default.bind(key, handlers[key]);
  362. }
  363. console.log(kanka.meta);
  364. })();
  365.  
  366.  
  367. /***/ }),
  368.  
  369. /***/ 802:
  370. /***/ ((module) => {
  371.  
  372. module.exports = Mousetrap;
  373.  
  374. /***/ })
  375.  
  376. /******/ });
  377. /************************************************************************/
  378. /******/ // The module cache
  379. /******/ var __webpack_module_cache__ = {};
  380. /******/
  381. /******/ // The require function
  382. /******/ function __webpack_require__(moduleId) {
  383. /******/ // Check if module is in cache
  384. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  385. /******/ if (cachedModule !== undefined) {
  386. /******/ return cachedModule.exports;
  387. /******/ }
  388. /******/ // Create a new module (and put it into the cache)
  389. /******/ var module = __webpack_module_cache__[moduleId] = {
  390. /******/ // no module.id needed
  391. /******/ // no module.loaded needed
  392. /******/ exports: {}
  393. /******/ };
  394. /******/
  395. /******/ // Execute the module function
  396. /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  397. /******/
  398. /******/ // Return the exports of the module
  399. /******/ return module.exports;
  400. /******/ }
  401. /******/
  402. /************************************************************************/
  403. /******/
  404. /******/ // startup
  405. /******/ // Load entry module and return exports
  406. /******/ // This entry module is referenced by other modules so it can't be inlined
  407. /******/ var __webpack_exports__ = __webpack_require__(519);
  408. /******/
  409. /******/ })()
  410. ;