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-2
  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. */
  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 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. console.log({ resp: body[0] });
  208. }
  209. });
  210. return response.ok;
  211. })
  212. .catch((error) => {
  213. console.error('Error:', error);
  214. return error.ok;
  215. });
  216. }
  217. function processLocationSelection(event) {
  218. const { id: locationID, text } = event.params.data;
  219. const params = createPostParams();
  220. params.append('location_id', locationID);
  221. post(`/w/${kanka.campaignID}/bulk/process`, params)
  222. .then(() => {
  223. const thisEntityLocation = kanka.entityTypeHasLocation[kanka.meta.entity.entityType];
  224. if (thisEntityLocation.headerLink) {
  225. const headerLink_Location = $($('[title="Location"]').next().next());
  226. if (!!headerLink_Location) {
  227. headerLink_Location.replaceWith(templates.LOCATION_LINK(locationID, text));
  228. }
  229. }
  230. if (thisEntityLocation.sidebarLink) {
  231. const sidebar = $('#sidebar-profile-elements > div').first();
  232. let sidebar_Location = sidebar.find('.profile-location');
  233. if (!sidebar_Location) {
  234. sidebar_Location = $('<div class="element profile-location">');
  235. sidebar_Location.append($('<div class="title text-uppercase text-xs">Location</div>'));
  236. sidebar.prepend(sidebar_Location);
  237. }
  238. const link = templates.LOCATION_LINK(locationID, text);
  239. if (thisEntityLocation.multiple) {
  240. sidebar_Location.append(link);
  241. }
  242. else {
  243. sidebar_Location.find('a').replaceWith(link);
  244. }
  245. }
  246. });
  247. }
  248. function processTagSelection(event) {
  249. const { id: tagID, text } = event.params.data;
  250. const params = createPostParams();
  251. const header = $('.entity-header .entity-header-text');
  252. if (header.has('.entity-tags').length == 0) {
  253. $('<div class="entity-tags entity-header-line text-xs flex flex-wrap gap-2"></div>')
  254. .insertBefore(header.find('.header-buttons'));
  255. }
  256. const tagBar = header.find('.entity-tags');
  257. const hasTag = !!kanka.meta.tags.find(tag => tag.id == tagID);
  258. if (hasTag) {
  259. const existingTag = tagBar.children(`[href="${templates.TAG_URL(tagID)}"]`)[0];
  260. if (!!existingTag) {
  261. params.append('bulk-tagging', 'remove');
  262. params.append('tags[]', tagID);
  263. params.append('save-tags', '1');
  264. post(`/w/${kanka.campaignID}/bulk/process`, params)
  265. .then(() => {
  266. existingTag.remove();
  267. });
  268. return;
  269. }
  270. }
  271. params.append('entities[]', kanka.meta.entity.id);
  272. params.append('tag_id', tagID);
  273. post(`/w/${kanka.campaignID}/tags/${tagID}/entity-add/`, params)
  274. .then((ok) => {
  275. ok && tagBar.append($(templates.TAG_LINK(tagID, text)));
  276. });
  277. }
  278. function initSelector(template, processSelection) {
  279. const floatingDiv = createFloatingElement(template);
  280. $(floatingDiv).find('select.select2')
  281. .each(function () {
  282. const me = $(this);
  283. me.select2({
  284. tags: false,
  285. placeholder: me.data('placeholder'),
  286. allowClear: me.data('allowClear') || true,
  287. language: me.data('language'),
  288. minimumInputLength: 0,
  289. dropdownParent: $(me.data('dropdownParent')) || '',
  290. width: '100%',
  291. sorter: (data) => {
  292. const term = $('input.select2-search__field').val().toLowerCase();
  293. return data.sort(byMatchiness(term));
  294. },
  295. ajax: {
  296. delay: 500, // quiet ms
  297. url: me.data('url'),
  298. dataType: 'json',
  299. data: (params) => { var _a; return ({ q: (_a = params.term) === null || _a === void 0 ? void 0 : _a.trim() }); },
  300. processResults: (data) => ({ results: data }),
  301. error: function (jqXHR, textStatus, errorThrown) {
  302. if (textStatus === 'abort') {
  303. // it does this for the empty field, I think?
  304. return;
  305. }
  306. if (jqXHR.status === 503) {
  307. window.showToast(jqXHR.responseJSON.message, 'error');
  308. }
  309. console.log('error', jqXHR, textStatus, errorThrown);
  310. return { results: [] };
  311. },
  312. cache: true
  313. },
  314. templateResult: (item) => templates.SELECT_ITEM(item.text, item.image),
  315. })
  316. .on('select2:select', processSelection)
  317. .on('select2:close', () => {
  318. setTimeout(() => { $(floatingDiv).remove(); }, 100);
  319. });
  320. setTimeout(() => { me.select2('open'); }, 0);
  321. });
  322. }
  323. function byMatchiness(term) {
  324. return (a, b) => {
  325. const textA = a.text.toLowerCase();
  326. const textB = b.text.toLowerCase();
  327. // Assign a score based on how well the option matches the search term
  328. const scoreA = textA === term ? 3 : textA.startsWith(term) ? 2 : textA.includes(term) ? 1 : 0;
  329. const scoreB = textB === term ? 3 : textB.startsWith(term) ? 2 : textB.includes(term) ? 1 : 0;
  330. // Sort by score. If the scores are equal, sort alphabetically
  331. return scoreB - scoreA || textA.localeCompare(textB);
  332. };
  333. }
  334. (function () {
  335. if (!document.body.className.includes('kanka-entity-')) {
  336. return;
  337. }
  338. for (const key in handlers) {
  339. mousetrap_1.default.bind(key, handlers[key]);
  340. }
  341. console.log(kanka.meta);
  342. })();
  343.  
  344.  
  345. /***/ }),
  346.  
  347. /***/ 802:
  348. /***/ ((module) => {
  349.  
  350. module.exports = Mousetrap;
  351.  
  352. /***/ })
  353.  
  354. /******/ });
  355. /************************************************************************/
  356. /******/ // The module cache
  357. /******/ var __webpack_module_cache__ = {};
  358. /******/
  359. /******/ // The require function
  360. /******/ function __webpack_require__(moduleId) {
  361. /******/ // Check if module is in cache
  362. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  363. /******/ if (cachedModule !== undefined) {
  364. /******/ return cachedModule.exports;
  365. /******/ }
  366. /******/ // Create a new module (and put it into the cache)
  367. /******/ var module = __webpack_module_cache__[moduleId] = {
  368. /******/ // no module.id needed
  369. /******/ // no module.loaded needed
  370. /******/ exports: {}
  371. /******/ };
  372. /******/
  373. /******/ // Execute the module function
  374. /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  375. /******/
  376. /******/ // Return the exports of the module
  377. /******/ return module.exports;
  378. /******/ }
  379. /******/
  380. /************************************************************************/
  381. /******/
  382. /******/ // startup
  383. /******/ // Load entry module and return exports
  384. /******/ // This entry module is referenced by other modules so it can't be inlined
  385. /******/ var __webpack_exports__ = __webpack_require__(519);
  386. /******/
  387. /******/ })()
  388. ;