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