Kanka.io Keybinds

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

目前为 2024-03-07 提交的版本。查看 最新版本

  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. SIDEBAR_PROFILE: () => `
  145. <div class="sidebar-section-box sidebar-section-profile overflow-hidden flex flex-col gap-2">
  146. <div class="sidebar-section-title cursor-pointer text-lg user-select border-b element-toggle" data-animate="collapse" data-target="#sidebar-profile-elements">
  147. <i class="fa-solid fa-chevron-up icon-show " aria-hidden="true"></i>
  148. <i class="fa-solid fa-chevron-down icon-hide " aria-hidden="true"></i>
  149. Profile
  150. </div>
  151.  
  152. <div class="sidebar-elements grid overflow-hidden" id="sidebar-profile-elements">
  153. </div>
  154. </div>`.trim(),
  155. SELECT_ELEMENT: (dataUrl, placeholder) => `
  156. <select class="form-tags select2"
  157. style="width: 100%"
  158. data-url="${dataUrl}"
  159. data-allow-new="false"
  160. data-allow-clear="true"
  161. data-placeholder="${placeholder}"
  162. data-dropdown-parent="#app"
  163. </select>`.trim(),
  164. SELECT_ITEM: (text, image) => {
  165. if (!!image) {
  166. return $(`
  167. <span class="flex gap-2 items-center text-left">
  168. <img src="${image}" class="rounded-full flex-none w-6 h-6" />
  169. <span class="grow">${text}</span>
  170. </span>`.trim());
  171. }
  172. return $(`<span>${text}</span>`);
  173. },
  174. TAG_SELECT: () => templates.SELECT_ELEMENT(`https://app.kanka.io/w/${kanka.campaignID}/search/tags`, 'Apply Tag'),
  175. TAG_URL: (tagID) => `https://app.kanka.io/w/${kanka.campaignID}/tags/${tagID}`,
  176. TAG_LINK: (tagID, text) => `
  177. <a href="${templates.TAG_URL(tagID)}" title="Refresh to get full tooltip functionality">
  178. <span class="badge color-tag rounded-sm px-2 py-1">${text}</span>
  179. </a>`.trim(),
  180. LOCATION_SELECT: () => templates.SELECT_ELEMENT(`https://app.kanka.io/w/${kanka.campaignID}/search/locations`, 'Move to...'),
  181. LOCATION_URL: (locationID) => `https://app.kanka.io/w/${kanka.campaignID}/entities/${locationID}`,
  182. LOCATION_LINK: (locationID, text) => `<a class="name" href="${templates.LOCATION_URL(locationID)}" title="Refresh to get full tooltip functionality">${text}</a>`,
  183. // TODO - get popper/tippy working to enable preview tooltips
  184. // data-toggle="tooltip-ajax" data-id="${locationID}" data-url="${templates.LOCATION_URL(locationID)}/tooltip">
  185. };
  186. /// making my own container for the select to avoid any interference
  187. function createFloatingElement(template) {
  188. let floatingDiv = document.getElementById('#infinite-select2');
  189. if (!floatingDiv) {
  190. floatingDiv = document.createElement('div');
  191. floatingDiv.id = 'infinite-select2';
  192. // Add styles to make it float and position it as needed
  193. floatingDiv.style.position = 'absolute';
  194. floatingDiv.style.top = '5%';
  195. floatingDiv.style.left = '41%';
  196. floatingDiv.style.minWidth = '200px';
  197. floatingDiv.style.width = '18%';
  198. floatingDiv.style.maxWidth = '400px';
  199. }
  200. floatingDiv.innerHTML = '';
  201. $(template()).appendTo(floatingDiv);
  202. document.body.appendChild(floatingDiv);
  203. return floatingDiv;
  204. }
  205. function createPostParams() {
  206. const params = new URLSearchParams();
  207. params.append('_token', kanka.csrfToken);
  208. params.append('datagrid-action', 'batch');
  209. // this needs the plural
  210. params.append('entity', kanka.entityType);
  211. params.append('mode', 'table');
  212. // typedID is different from entityID
  213. params.append('models', kanka.typedID);
  214. params.append('undefined', '');
  215. return params;
  216. }
  217. async function fetch_success(response) {
  218. var _a;
  219. emit_debug('Success:', response);
  220. const document = await ((_a = response.body) === null || _a === void 0 ? void 0 : _a.getReader().read().then(content => {
  221. const responseHtml = new TextDecoder().decode(content.value);
  222. return $.parseHTML(responseHtml);
  223. }));
  224. return { ok: response.ok, document: document !== null && document !== void 0 ? document : [] };
  225. }
  226. function post(url, body) {
  227. return fetch(url, {
  228. method: 'POST',
  229. redirect: 'follow',
  230. headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  231. body,
  232. })
  233. .then(fetch_success)
  234. .catch((error) => {
  235. console.error('Error:', error);
  236. return { ok: error.ok, document: [] };
  237. });
  238. }
  239. async function edit(body) {
  240. emit_debug({ edit_data: [...body.entries()] });
  241. var xhr = new XMLHttpRequest();
  242. xhr.withCredentials = true;
  243. xhr.open('POST', kanka.entityEditUrl, false);
  244. xhr.setRequestHeader('x-csrf-token', kanka.csrfToken);
  245. xhr.setRequestHeader('x-requested-with', 'XMLHttpRequest');
  246. xhr.send(body);
  247. emit_debug({ req: xhr });
  248. return {
  249. ok: xhr.status == 200,
  250. document: $.parseHTML(xhr.responseText),
  251. };
  252. return fetch(kanka.entityEditUrl, {
  253. method: 'POST',
  254. headers: {
  255. "x-csrf-token": kanka.csrfToken,
  256. "x-requested-with": "XMLHttpRequest"
  257. },
  258. "referrer": kanka.entityEditUrl + "/edit",
  259. "referrerPolicy": "strict-origin-when-cross-origin",
  260. "mode": "cors",
  261. "credentials": "include",
  262. redirect: 'follow',
  263. body,
  264. })
  265. .then(fetch_success)
  266. .catch((error) => {
  267. console.error('Error:', error);
  268. return { ok: error.ok, document: [] };
  269. });
  270. }
  271. async function processLocationSelection(event) {
  272. const { id: locationID, text } = event.params.data;
  273. const thisEntityTypeHasLocation = kanka.entityTypeHasLocation[kanka.meta.entity.entityType];
  274. if (thisEntityTypeHasLocation.multiple) {
  275. alert('This entity type can have multiple locations. This feature is not yet implemented.');
  276. return;
  277. const data = new FormData();
  278. data.append('_token', kanka.csrfToken);
  279. // this is kinda BS, but it's the cleanest way to get
  280. // - the list of typed IDs
  281. // - the other stuff
  282. await fetch(`https://app.kanka.io/w/${kanka.campaignID}/creatures/${kanka.typedID}/edit`, {
  283. method: 'GET',
  284. headers: { 'Content-Type': 'text/html' }
  285. })
  286. .then(fetch_success)
  287. .then(response => $(response.document)
  288. .find('form#entity-form')
  289. .serializeArray()
  290. // .filter(kvp => {
  291. // if (kvp.value == '') return false;
  292. // if (kvp.value == '0') return false;
  293. // if (kvp.value == 'inherit') return false;
  294. // })
  295. .forEach(kvp => data.append(kvp.name, kvp.value)));
  296. data.append('locations[]', locationID);
  297. await edit(data)
  298. .then(response => {
  299. const doc = $(response.document);
  300. emit_debug({
  301. header: doc.find('.entity-header'),
  302. sidebar: doc.find('#sidebar-profile-elements'),
  303. });
  304. });
  305. return;
  306. }
  307. const params = createPostParams();
  308. params.append('location_id', locationID);
  309. post(kanka.bulkEditUrl, params)
  310. .then(response => {
  311. if (!response.ok)
  312. return false;
  313. const sub = (selector) => {
  314. $(selector).replaceWith($(response.document).find(selector));
  315. return $(selector);
  316. };
  317. if (thisEntityTypeHasLocation.headerLink) {
  318. sub('.entity-header')
  319. .find('.entity-header-sub.entity-header-line')
  320. .animate({ opacity: 0 }, 125)
  321. .animate({ opacity: 1 }, 125)
  322. .animate({ opacity: 0 }, 125)
  323. .animate({ opacity: 1 }, 125)
  324. .animate({ opacity: 0 }, 125)
  325. .animate({ opacity: 1 }, 125);
  326. }
  327. if (thisEntityTypeHasLocation.sidebarLink) {
  328. const sidebar = $('.entity-sidebar');
  329. // add Profile section if it doesn't exist
  330. if (sidebar.find('.sidebar-section-profile').length == 0) {
  331. sidebar.find('.entity-pins').after(templates.SIDEBAR_PROFILE());
  332. }
  333. if (sidebar.find('#sidebar-profile-elements').length == 0) {
  334. sidebar.find('.sidebar-section-profile').append('<div id="sidebar-profile-elements"></div>');
  335. }
  336. sub('#sidebar-profile-elements')
  337. .find('.profile-location')
  338. .animate({ opacity: 0 }, 125)
  339. .animate({ opacity: 1 }, 125)
  340. .animate({ opacity: 0 }, 125)
  341. .animate({ opacity: 1 }, 125)
  342. .animate({ opacity: 0 }, 125)
  343. .animate({ opacity: 1 }, 125);
  344. }
  345. });
  346. }
  347. function processTagSelection(event) {
  348. const { id: tagID, text } = event.params.data;
  349. const params = createPostParams();
  350. params.append('save-tags', '1');
  351. params.append('tags[]', tagID);
  352. const header = $('.entity-header .entity-header-text');
  353. if (header.has('.entity-tags').length == 0) {
  354. $('<div class="entity-tags entity-header-line text-xs flex flex-wrap gap-2"></div>')
  355. .insertBefore(header.find('.header-buttons'));
  356. }
  357. const hasTag = !!kanka.meta.tags.find(tag => tag.id == tagID);
  358. params.append('bulk-tagging', hasTag ? 'remove' : 'add');
  359. return post(`/w/${kanka.campaignID}/bulk/process`, params)
  360. .then((ok) => {
  361. const tagBar = header.find('.entity-tags');
  362. ok && hasTag
  363. ? tagBar.children().remove(`[href="${templates.TAG_URL(tagID)}"]`)
  364. : tagBar.append($(templates.TAG_LINK(tagID, text)));
  365. });
  366. /*
  367. // was doing it using the simple 'add entity under tag' API
  368. // but why not consolidate?
  369. params.append('entities[]', kanka.meta.entity.id);
  370. params.append('tag_id', tagID);
  371. post(`/w/${kanka.campaignID}/tags/${tagID}/entity-add/`, params)
  372. .then((ok) => ok && tagBar.append($(templates.TAG_LINK(tagID, text))));
  373. */
  374. }
  375. function initSelector(template, processSelection) {
  376. const floatingDiv = createFloatingElement(template);
  377. $(floatingDiv).find('select.select2')
  378. .each(function () {
  379. const me = $(this);
  380. me.select2({
  381. tags: false,
  382. placeholder: me.data('placeholder'),
  383. allowClear: me.data('allowClear') || true,
  384. language: me.data('language'),
  385. minimumInputLength: 0,
  386. dropdownParent: $(me.data('dropdownParent')) || '',
  387. width: '100%',
  388. sorter: (data) => {
  389. const term = $('input.select2-search__field').val().toLowerCase();
  390. return data.sort(byMatchiness(term));
  391. },
  392. ajax: {
  393. delay: 500, // quiet ms
  394. url: me.data('url'),
  395. dataType: 'json',
  396. data: (params) => { var _a; return ({ q: (_a = params.term) === null || _a === void 0 ? void 0 : _a.trim() }); },
  397. processResults: (data) => ({ results: data }),
  398. error: function (jqXHR, textStatus, errorThrown) {
  399. if (textStatus === 'abort') {
  400. // it does this for the empty field, I think?
  401. return;
  402. }
  403. if (jqXHR.status === 503) {
  404. window.showToast(jqXHR.responseJSON.message, 'error');
  405. }
  406. emit_debug('error', jqXHR, textStatus, errorThrown);
  407. return { results: [] };
  408. },
  409. cache: true
  410. },
  411. templateResult: (item) => templates.SELECT_ITEM(item.text, item.image),
  412. })
  413. .on('select2:select', processSelection)
  414. .on('select2:close', () => {
  415. setTimeout(() => { $(floatingDiv).remove(); }, 100);
  416. });
  417. setTimeout(() => { me.select2('open'); }, 0);
  418. });
  419. }
  420. function byMatchiness(term) {
  421. return (a, b) => {
  422. const textA = a.text.toLowerCase();
  423. const textB = b.text.toLowerCase();
  424. // Assign a score based on how well the option matches the search term
  425. const scoreA = textA === term ? 3 : textA.startsWith(term) ? 2 : textA.includes(term) ? 1 : 0;
  426. const scoreB = textB === term ? 3 : textB.startsWith(term) ? 2 : textB.includes(term) ? 1 : 0;
  427. // Sort by score. If the scores are equal, sort alphabetically
  428. return scoreB - scoreA || textA.localeCompare(textB);
  429. };
  430. }
  431. (function () {
  432. if (!document.body.className.includes('kanka-entity-')) {
  433. return;
  434. }
  435. for (const key in handlers) {
  436. mousetrap_1.default.bind(key, handlers[key]);
  437. }
  438. emit_debug({ kanka });
  439. })();
  440.  
  441.  
  442. /***/ }),
  443.  
  444. /***/ 802:
  445. /***/ ((module) => {
  446.  
  447. module.exports = Mousetrap;
  448.  
  449. /***/ })
  450.  
  451. /******/ });
  452. /************************************************************************/
  453. /******/ // The module cache
  454. /******/ var __webpack_module_cache__ = {};
  455. /******/
  456. /******/ // The require function
  457. /******/ function __webpack_require__(moduleId) {
  458. /******/ // Check if module is in cache
  459. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  460. /******/ if (cachedModule !== undefined) {
  461. /******/ return cachedModule.exports;
  462. /******/ }
  463. /******/ // Create a new module (and put it into the cache)
  464. /******/ var module = __webpack_module_cache__[moduleId] = {
  465. /******/ // no module.id needed
  466. /******/ // no module.loaded needed
  467. /******/ exports: {}
  468. /******/ };
  469. /******/
  470. /******/ // Execute the module function
  471. /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  472. /******/
  473. /******/ // Return the exports of the module
  474. /******/ return module.exports;
  475. /******/ }
  476. /******/
  477. /************************************************************************/
  478. /******/
  479. /******/ // startup
  480. /******/ // Load entry module and return exports
  481. /******/ // This entry module is referenced by other modules so it can't be inlined
  482. /******/ var __webpack_exports__ = __webpack_require__(519);
  483. /******/
  484. /******/ })()
  485. ;