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