Kanka.io Keybinds

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

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

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