Kanka.io Keybinds

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

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

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