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