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, _g;
  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. console.log({
  96. editButton: (_a = $('div#entity-submenu a[href$="edit"]').attr('href')) === null || _a === void 0 ? void 0 : _a.match(/\/(\d+)\/edit$/),
  97. headerEditButton: (_b = $('div.header-buttons a[href$="edit"]').attr('href')) === null || _b === void 0 ? void 0 : _b.match(/\/(\d+)\/edit$/),
  98. });
  99. const route = window.location.pathname;
  100. const kanka = {
  101. csrfToken: (_c = document.head.querySelector('meta[name="csrf-token"]')) === null || _c === void 0 ? void 0 : _c.getAttribute('content'),
  102. route,
  103. campaignID: ((_d = route.match(/w\/(\d+)\//)) !== null && _d !== void 0 ? _d : [null, '0'])[1],
  104. entityID: ((_e = route.match(/w\/\d+\/entities\/(\d+)/)) !== null && _e !== void 0 ? _e : [null, '0'])[1],
  105. typedID: ((_g = (_f = $('div#entity-submenu a[href$="edit"]').attr('href')) === null || _f === void 0 ? void 0 : _f.match(/\/(\d+)\/edit$/)) !== null && _g !== void 0 ? _g : [null, '0'])[1],
  106. meta: parseBodyClasses(document.body),
  107. entityTypeHasLocation: ({
  108. default: {},
  109. character: { headerLink: true },
  110. location: { headerLink: true },
  111. map: { headerLink: true },
  112. organisation: { sidebarLink: true },
  113. family: { headerLink: true },
  114. creature: { sidebarLink: true, multiple: true },
  115. race: { sidebarLink: true, multiple: true },
  116. event: { sidebarLink: true },
  117. journal: { sidebarLink: true },
  118. item: { sidebarLink: true },
  119. tag: {},
  120. note: {},
  121. quest: {},
  122. }),
  123. };
  124. const handlers = {
  125. [keybinds.LABEL]: function (evt, combo) {
  126. initSelector(templates.TAG_SELECT, processTagSelection);
  127. },
  128. [keybinds.MOVE]: function (evt, combo) {
  129. initSelector(templates.LOCATION_SELECT, processLocationSelection);
  130. },
  131. [keybinds.HELP]: function (evt, combo) {
  132. // TODO show a modal describing the keybinds
  133. },
  134. };
  135. const templates = {
  136. SELECT_ELEMENT: (dataUrl, placeholder) => `
  137. <select class="form-tags select2"
  138. style="width: 100%"
  139. data-url="${dataUrl}"
  140. data-allow-new="false"
  141. data-allow-clear="true"
  142. data-placeholder="${placeholder}"
  143. data-dropdown-parent="#app"
  144. </select>`.trim(),
  145. SELECT_ITEM: (text, image) => {
  146. if (!!image) {
  147. return $(`
  148. <span class="flex gap-2 items-center text-left">
  149. <img src="${image}" class="rounded-full flex-none w-6 h-6" />
  150. <span class="grow">${text}</span>
  151. </span>`.trim());
  152. }
  153. return $(`<span>${text}</span>`);
  154. },
  155. TAG_SELECT: () => templates.SELECT_ELEMENT(`https://app.kanka.io/w/${kanka.campaignID}/search/tags`, 'Apply Tag'),
  156. TAG_URL: (tagID) => `https://app.kanka.io/w/${kanka.campaignID}/tags/${tagID}`,
  157. TAG_LINK: (tagID, text) => `
  158. <a href="${templates.TAG_URL(tagID)}" title="Refresh to get full tooltip functionality">
  159. <span class="badge color-tag rounded-sm px-2 py-1">${text}</span>
  160. </a>`.trim(),
  161. LOCATION_SELECT: () => templates.SELECT_ELEMENT(`https://app.kanka.io/w/${kanka.campaignID}/search/locations`, 'Move to...'),
  162. LOCATION_URL: (locationID) => `https://app.kanka.io/w/${kanka.campaignID}/entities/${locationID}`,
  163. LOCATION_LINK: (locationID, text) => `<a class="name" href="${templates.LOCATION_URL(locationID)}" title="Refresh to get full tooltip functionality">${text}</a>`,
  164. // TODO - get popper/tippy working to enable preview tooltips
  165. // data-toggle="tooltip-ajax" data-id="${locationID}" data-url="${templates.LOCATION_URL(locationID)}/tooltip">
  166. };
  167. /// making my own container for the select to avoid any interference
  168. function createFloatingElement(template) {
  169. let floatingDiv = document.getElementById('#infinite-select2');
  170. if (!floatingDiv) {
  171. floatingDiv = document.createElement('div');
  172. floatingDiv.id = 'infinite-select2';
  173. // Add styles to make it float and position it as needed
  174. floatingDiv.style.position = 'absolute';
  175. floatingDiv.style.top = '5%';
  176. floatingDiv.style.left = '41%';
  177. floatingDiv.style.minWidth = '200px';
  178. floatingDiv.style.width = '18%';
  179. floatingDiv.style.maxWidth = '400px';
  180. }
  181. floatingDiv.innerHTML = '';
  182. $(template()).appendTo(floatingDiv);
  183. document.body.appendChild(floatingDiv);
  184. return floatingDiv;
  185. }
  186. function createPostParams() {
  187. const params = new URLSearchParams();
  188. params.append('_token', kanka.csrfToken);
  189. params.append('datagrid-action', 'batch');
  190. params.append('entity', kanka.meta.entity.entityType);
  191. params.append('mode', 'table');
  192. // typedID is different from entityID >:(
  193. params.append('models', kanka.typedID);
  194. params.append('undefined', '');
  195. return params;
  196. }
  197. function post(url, body) {
  198. return fetch(url, {
  199. method: 'POST',
  200. redirect: 'follow',
  201. headers: {
  202. 'Content-Type': 'application/x-www-form-urlencoded',
  203. },
  204. body,
  205. })
  206. .then((response) => {
  207. var _a;
  208. console.log('Success:', response);
  209. (_a = response.body) === null || _a === void 0 ? void 0 : _a.getReader().read().then(content => {
  210. const responseText = new TextDecoder().decode(content.value);
  211. const body = responseText.match(/\<body[^\>]*?\>/);
  212. if (body) {
  213. console.log({ resp: body[0] });
  214. }
  215. });
  216. return response.ok;
  217. })
  218. .catch((error) => {
  219. console.error('Error:', error);
  220. return error.ok;
  221. });
  222. }
  223. function processLocationSelection(event) {
  224. const { id: locationID, text } = event.params.data;
  225. const params = createPostParams();
  226. params.append('location_id', locationID);
  227. post(`/w/${kanka.campaignID}/bulk/process`, params)
  228. .then(() => {
  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. if (thisEntityLocation.sidebarLink) {
  237. const sidebar = $('#sidebar-profile-elements > div').first();
  238. let sidebar_Location = sidebar.find('.profile-location');
  239. if (!sidebar_Location) {
  240. sidebar_Location = $('<div class="element profile-location">');
  241. sidebar_Location.append($('<div class="title text-uppercase text-xs">Location</div>'));
  242. sidebar.prepend(sidebar_Location);
  243. }
  244. const link = templates.LOCATION_LINK(locationID, text);
  245. if (thisEntityLocation.multiple) {
  246. sidebar_Location.append(link);
  247. }
  248. else {
  249. sidebar_Location.find('a').replaceWith(link);
  250. }
  251. }
  252. });
  253. }
  254. function processTagSelection(event) {
  255. const { id: tagID, text } = event.params.data;
  256. const params = createPostParams();
  257. params.append('save-tags', '1');
  258. params.append('tags[]', tagID);
  259. const header = $('.entity-header .entity-header-text');
  260. if (header.has('.entity-tags').length == 0) {
  261. $('<div class="entity-tags entity-header-line text-xs flex flex-wrap gap-2"></div>')
  262. .insertBefore(header.find('.header-buttons'));
  263. }
  264. const tagBar = header.find('.entity-tags');
  265. const hasTag = !!kanka.meta.tags.find(tag => tag.id == tagID);
  266. const existingTag = tagBar.children(`[href="${templates.TAG_URL(tagID)}"]`)[0];
  267. params.append('bulk-tagging', hasTag ? 'remove' : 'add');
  268. return post(`/w/${kanka.campaignID}/bulk/process`, params)
  269. .then((ok) => {
  270. ok && hasTag
  271. ? existingTag.remove()
  272. : tagBar.append($(templates.TAG_LINK(tagID, text)));
  273. });
  274. if (hasTag) {
  275. const existingTag = tagBar.children(`[href="${templates.TAG_URL(tagID)}"]`)[0];
  276. if (!!existingTag) {
  277. params.append('bulk-tagging', 'remove');
  278. post(`/w/${kanka.campaignID}/bulk/process`, params)
  279. .then(() => {
  280. existingTag.remove();
  281. });
  282. return;
  283. }
  284. }
  285. params.append('bulk-tagging', 'add');
  286. params.append('entities[]', kanka.meta.entity.id);
  287. params.append('tag_id', tagID);
  288. post(`/w/${kanka.campaignID}/tags/${tagID}/entity-add/`, params)
  289. .then((ok) => {
  290. ok && tagBar.append($(templates.TAG_LINK(tagID, text)));
  291. });
  292. }
  293. function initSelector(template, processSelection) {
  294. const floatingDiv = createFloatingElement(template);
  295. $(floatingDiv).find('select.select2')
  296. .each(function () {
  297. const me = $(this);
  298. me.select2({
  299. tags: false,
  300. placeholder: me.data('placeholder'),
  301. allowClear: me.data('allowClear') || true,
  302. language: me.data('language'),
  303. minimumInputLength: 0,
  304. dropdownParent: $(me.data('dropdownParent')) || '',
  305. width: '100%',
  306. sorter: (data) => {
  307. const term = $('input.select2-search__field').val().toLowerCase();
  308. return data.sort(byMatchiness(term));
  309. },
  310. ajax: {
  311. delay: 500, // quiet ms
  312. url: me.data('url'),
  313. dataType: 'json',
  314. data: (params) => { var _a; return ({ q: (_a = params.term) === null || _a === void 0 ? void 0 : _a.trim() }); },
  315. processResults: (data) => ({ results: data }),
  316. error: function (jqXHR, textStatus, errorThrown) {
  317. if (textStatus === 'abort') {
  318. // it does this for the empty field, I think?
  319. return;
  320. }
  321. if (jqXHR.status === 503) {
  322. window.showToast(jqXHR.responseJSON.message, 'error');
  323. }
  324. console.log('error', jqXHR, textStatus, errorThrown);
  325. return { results: [] };
  326. },
  327. cache: true
  328. },
  329. templateResult: (item) => templates.SELECT_ITEM(item.text, item.image),
  330. })
  331. .on('select2:select', processSelection)
  332. .on('select2:close', () => {
  333. setTimeout(() => { $(floatingDiv).remove(); }, 100);
  334. });
  335. setTimeout(() => { me.select2('open'); }, 0);
  336. });
  337. }
  338. function byMatchiness(term) {
  339. return (a, b) => {
  340. const textA = a.text.toLowerCase();
  341. const textB = b.text.toLowerCase();
  342. // Assign a score based on how well the option matches the search term
  343. const scoreA = textA === term ? 3 : textA.startsWith(term) ? 2 : textA.includes(term) ? 1 : 0;
  344. const scoreB = textB === term ? 3 : textB.startsWith(term) ? 2 : textB.includes(term) ? 1 : 0;
  345. // Sort by score. If the scores are equal, sort alphabetically
  346. return scoreB - scoreA || textA.localeCompare(textB);
  347. };
  348. }
  349. (function () {
  350. if (!document.body.className.includes('kanka-entity-')) {
  351. return;
  352. }
  353. for (const key in handlers) {
  354. mousetrap_1.default.bind(key, handlers[key]);
  355. }
  356. console.log(kanka.meta);
  357. })();
  358.  
  359.  
  360. /***/ }),
  361.  
  362. /***/ 802:
  363. /***/ ((module) => {
  364.  
  365. module.exports = Mousetrap;
  366.  
  367. /***/ })
  368.  
  369. /******/ });
  370. /************************************************************************/
  371. /******/ // The module cache
  372. /******/ var __webpack_module_cache__ = {};
  373. /******/
  374. /******/ // The require function
  375. /******/ function __webpack_require__(moduleId) {
  376. /******/ // Check if module is in cache
  377. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  378. /******/ if (cachedModule !== undefined) {
  379. /******/ return cachedModule.exports;
  380. /******/ }
  381. /******/ // Create a new module (and put it into the cache)
  382. /******/ var module = __webpack_module_cache__[moduleId] = {
  383. /******/ // no module.id needed
  384. /******/ // no module.loaded needed
  385. /******/ exports: {}
  386. /******/ };
  387. /******/
  388. /******/ // Execute the module function
  389. /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  390. /******/
  391. /******/ // Return the exports of the module
  392. /******/ return module.exports;
  393. /******/ }
  394. /******/
  395. /************************************************************************/
  396. /******/
  397. /******/ // startup
  398. /******/ // Load entry module and return exports
  399. /******/ // This entry module is referenced by other modules so it can't be inlined
  400. /******/ var __webpack_exports__ = __webpack_require__(519);
  401. /******/
  402. /******/ })()
  403. ;