LinkedIn Tool

Minor enhancements to LinkedIn. Mostly just hotkeys.

当前为 2023-08-02 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name LinkedIn Tool
  3. // @namespace dalgoda@gmail.com
  4. // @match https://www.linkedin.com/*
  5. // @version 1.0.3
  6. // @author Mike Castle
  7. // @description Minor enhancements to LinkedIn. Mostly just hotkeys.
  8. // @license GPL-3.0-or-later; https://www.gnu.org/licenses/gpl-3.0.txt
  9. // @supportURL https://github.com/nexushoratio/userscripts/blob/main/linkedin-tool.md
  10. // @require https://cdn.jsdelivr.net/npm/@violentmonkey/shortcut@1
  11. // @require https://cdn.jsdelivr.net/npm/@violentmonkey/dom@2
  12. // ==/UserScript==
  13.  
  14. /* global VM */
  15.  
  16. (function () {
  17. 'use strict';
  18.  
  19. console.debug('Parsing successful.');
  20.  
  21. // I'm lazy. The version of emacs I'm using does not support
  22. // #private variables out of the box, so using underscores until I
  23. // get a working configuration.
  24. class Page {
  25. // The immediate following can be set if derived classes
  26.  
  27. // What pathname part of the URL this page should handle. The
  28. // special case of null is used by the Pages class to represent
  29. // global keys.
  30. _pathname;
  31.  
  32. // CSS selector for capturing clicks on this page. If overridden,
  33. // then the class should also provide a _clickHandler() method.
  34. _click_handler_selector = null;
  35.  
  36. // List of keystrokes to register automatically. They are objects
  37. // with keys of `seq`, `desc`, and `func`. The `seq` is used to
  38. // define they keystroke sequence to trigger the function. The
  39. // `desc` is used to create the help screen. The `func` is a
  40. // function, usually in the form of `this.methodName`. The
  41. // function is bound to `this` before registering it with
  42. // VM.shortcut.
  43. _auto_keys = [];
  44.  
  45. // Private members.
  46.  
  47. _keyboard = new VM.shortcut.KeyboardService();
  48.  
  49. // Tracks which HTMLElement holds the `onclick` function.
  50. _click_handler_element = null;
  51.  
  52. // Magic for VM.shortcut. This disables keys when focus is on an
  53. // input type field.
  54. static _navOption = {
  55. caseSensitive: true,
  56. condition: '!inputFocus',
  57. };
  58.  
  59. constructor() {
  60. this._boundClickHandler = this._clickHandler.bind(this);
  61. }
  62.  
  63. start() {
  64. for (const {seq, func} of this._auto_keys) {
  65. this._addKey(seq, func.bind(this));
  66. }
  67. }
  68.  
  69. get pathname() {
  70. return this._pathname;
  71. }
  72.  
  73. get keyboard() {
  74. return this._keyboard;
  75. }
  76.  
  77. activate() {
  78. this._keyboard.enable();
  79. this._enableClickHandler();
  80. }
  81.  
  82. deactivate() {
  83. this._keyboard.disable();
  84. this._disableClickHandler();
  85. }
  86.  
  87. get helpHeader() {
  88. return this.constructor.name;
  89. }
  90.  
  91. get helpContent() {
  92. return this._auto_keys;
  93. }
  94.  
  95. _addKey(seq, func) {
  96. this._keyboard.register(seq, func, Page._navOption);
  97. }
  98.  
  99. _enableClickHandler() {
  100. if (this._click_handler_selector) {
  101. // Page is dynamically building, so keep watching it until the
  102. // element shows up.
  103. VM.observe(document.body, () => {
  104. const element = document.querySelector(this._click_handler_selector);
  105. if (element) {
  106. this._click_handler_element = element;
  107. this._click_handler_element.addEventListener('click', this._boundClickHandler);
  108.  
  109. return true;
  110. }
  111. });
  112. }
  113. }
  114.  
  115. _disableClickHandler() {
  116. if (this._click_handler_element) {
  117. this._click_handler_element.removeEventListener('click', this._boundClickHandler);
  118. this._click_handler_element = null
  119. }
  120. }
  121.  
  122. // Override this function in derived classes that want to react to
  123. // random clicks on a page, say to update current element in
  124. // focus.
  125. _clickHandler(evt) {
  126. alert(`Found a bug! ${this.constructor.name} wants to handle clicks, but forgot to create a handler.`);
  127. }
  128.  
  129. }
  130.  
  131. class Global extends Page {
  132. _pathname = null;
  133. _auto_keys = [
  134. {seq: '?', desc: 'Show keyboard help', func: this._help},
  135. {seq: '/', desc: 'Go to Search box', func: this._gotoSearch},
  136. {seq: 'g h', desc: 'Go Home (aka, Feed)', func: this._goHome},
  137. {seq: 'g m', desc: 'Go to My Network', func: this._gotoMyNetwork},
  138. {seq: 'g j', desc: 'Go to Jobs', func: this._gotoJobs},
  139. {seq: 'g g', desc: 'Go to Messaging', func: this._gotoMessaging},
  140. {seq: 'g n', desc: 'Go to Notifications', func: this._gotoNotifications},
  141. {seq: 'g p', desc: 'Go to Profile (aka, Me)', func: this._gotoProfile},
  142. {seq: 'g b', desc: 'Go to Business', func: this._gotoBusiness},
  143. {seq: 'g l', desc: 'Go to Learning', func: this._gotoLearning},
  144. ];
  145.  
  146. get helpId() {
  147. return this._helpId;
  148. }
  149.  
  150. set helpId(val) {
  151. this._helpId = val;
  152. }
  153.  
  154. _gotoNavLink(item) {
  155. clickElement(document, [`#global-nav a[href*="/${item}"`]);
  156. }
  157.  
  158. _gotoNavButton(item) {
  159. const buttons = Array.from(document.querySelectorAll('#global-nav button'));
  160. const button = buttons.find(el => el.textContent.includes(item));
  161. if (button) {
  162. button.click();
  163. }
  164. }
  165.  
  166. _help() {
  167. const help = document.querySelector(`#${this.helpId}`);
  168. help.showModal();
  169. help.focus();
  170. }
  171.  
  172. _gotoSearch() {
  173. clickElement(document, ['#global-nav-search button']);
  174. }
  175.  
  176. _goHome() {
  177. this._gotoNavLink('feed');
  178. }
  179.  
  180. _gotoMyNetwork() {
  181. this._gotoNavLink('mynetwork');
  182. }
  183.  
  184. _gotoJobs() {
  185. this._gotoNavLink('jobs');
  186. }
  187.  
  188. _gotoMessaging() {
  189. this._gotoNavLink('messaging');
  190. }
  191.  
  192. _gotoNotifications() {
  193. this._gotoNavLink('notifications');
  194. }
  195.  
  196. _gotoProfile() {
  197. this._gotoNavButton('Me');
  198. }
  199.  
  200. _gotoBusiness() {
  201. this._gotoNavButton('Business');
  202. }
  203.  
  204. _gotoLearning() {
  205. this._gotoNavLink('learning');
  206. }
  207.  
  208. }
  209.  
  210. class Feed extends Page {
  211. _pathname = '/feed/';
  212. _click_handler_selector = 'main';
  213. _auto_keys = [
  214. {seq: 'X', desc: 'Toggle hiding current post', func: this._togglePost},
  215. {seq: 'j', desc: 'Next post', func: this._nextPost},
  216. {seq: 'J', desc: 'Toggle hiding then next post', func: this._nextPostPlus},
  217. {seq: 'k', desc: 'Previous post', func: this._prevPost},
  218. {seq: 'K', desc: 'Toggle hiding then previous post', func: this._prevPostPlus},
  219. {seq: 'm', desc: 'Show more of the post or comment', func: this._seeMore},
  220. {seq: 'c', desc: 'Show comments', func: this._showComments},
  221. {seq: 'n', desc: 'Next comment', func: this._nextComment},
  222. {seq: 'p', desc: 'Previous comment', func: this._prevComment},
  223. {seq: 'l', desc: 'Load more posts (if the <button>New Posts</button> button is available, load those)', func: this._loadMorePosts},
  224. {seq: 'L', desc: 'Like post or comment', func: this._likePostOrComment},
  225. {seq: 'f', desc: 'Focus on current post or comment (causes browser to change focus)', func: this._focusBrowser},
  226. {seq: '=', desc: 'Open the (⋯) menu', func: this._openMeatballMenu},
  227. ];
  228.  
  229. _currentPostElement = null;
  230. _currentCommentElement = null;
  231.  
  232. _clickHandler(evt) {
  233. const post = evt.target.closest('div[data-id]');
  234. if (post) {
  235. this._post = post;
  236. }
  237. }
  238.  
  239. get _post() {
  240. return this._currentPostElement;
  241. }
  242.  
  243. set _post(val) {
  244. if (val === this._currentPostElement) {
  245. return;
  246. }
  247. if (this._currentPostElement) {
  248. this._currentPostElement.classList.remove('tom');
  249. }
  250. this._currentPostElement = val;
  251. this._comment = null;
  252. if (val) {
  253. val.classList.add('tom');
  254. this._scrollToCurrentPost();
  255. }
  256. }
  257.  
  258. get _comment() {
  259. return this._currentCommentElement;
  260. }
  261.  
  262. set _comment(val) {
  263. if (this._currentCommentElement) {
  264. this._currentCommentElement.classList.remove('dick');
  265. }
  266. this._currentCommentElement = val;
  267. if (val) {
  268. val.classList.add('dick');
  269. this._scrollToCurrentComment();
  270. }
  271. }
  272.  
  273. _getPosts() {
  274. return Array.from(document.querySelectorAll('main div[data-id]'));
  275. }
  276.  
  277. _getComments() {
  278. if (this._post) {
  279. return Array.from(this._post.querySelectorAll('article.comments-comment-item'));
  280. } else {
  281. return [];
  282. }
  283. }
  284.  
  285. _scrollToCurrentPost() {
  286. this._post.style.scrollMarginTop = navBarHeightCss;
  287. this._post.scrollIntoView();
  288. }
  289.  
  290. _scrollToCurrentComment() {
  291. const rect = this._comment.getBoundingClientRect();
  292. this._comment.style.scrollMarginTop = navBarHeightCss;
  293. this._comment.style.scrollMarginBottom = '3em';
  294. // If both scrolling happens, that means the comment is too long
  295. // to fit on the page, so the top is preferred.
  296. if (rect.bottom > document.documentElement.clientHeight) {
  297. this._comment.scrollIntoView(false);
  298. }
  299. if (rect.top < navBarHeightPixels) {
  300. this._comment.scrollIntoView();
  301. }
  302. }
  303.  
  304. _scrollBy(n) {
  305. const posts = this._getPosts();
  306. if (posts.length) {
  307. let idx = posts.indexOf(this._post);
  308. let post = null;
  309. // Some posts are hidden (ads, suggestions). Skip over thoses.
  310. do {
  311. idx = Math.max(Math.min(idx + n, posts.length - 1), 0);
  312. post = posts[idx];
  313. } while (!post.clientHeight);
  314. this._post = post;
  315. }
  316. }
  317.  
  318. _scrollCommentsBy(n) {
  319. const comments = this._getComments();
  320. if (comments.length) {
  321. let idx = comments.indexOf(this._comment);
  322. idx = Math.min(idx + n, comments.length - 1);
  323. if (idx < 0) {
  324. // focus back to post
  325. this._comment = null;
  326. this._post = this._post;
  327. } else {
  328. this._comment = comments[idx];
  329. }
  330. }
  331. }
  332.  
  333. _nextPost() {
  334. this._scrollBy(1);
  335. }
  336.  
  337. _nextPostPlus() {
  338. this._togglePost();
  339. this._nextPost();
  340. }
  341.  
  342. _prevPost() {
  343. this._scrollBy(-1);
  344. }
  345.  
  346. _prevPostPlus() {
  347. this._togglePost();
  348. this._prevPost();
  349. }
  350.  
  351. _nextComment() {
  352. this._scrollCommentsBy(1);
  353. }
  354.  
  355. _prevComment() {
  356. this._scrollCommentsBy(-1);
  357. }
  358.  
  359. _togglePost() {
  360. clickElement(this._post, ['button[aria-label^="Dismiss post"]', 'button[aria-label^="Undo and show"]']);
  361. }
  362.  
  363. _showComments() {
  364. clickElement(this._post, ['button[aria-label*="comment"]']);
  365. }
  366.  
  367. _seeMore() {
  368. const el = this._comment ? this._comment : this._post;
  369. clickElement(el, ['button[aria-label^="see more"]']);
  370. }
  371.  
  372. _likePostOrComment() {
  373. const el = this._comment ? this._comment : this._post;
  374. clickElement(el, ['button[aria-label^="Open reactions menu"]']);
  375. }
  376.  
  377. _loadMorePosts() {
  378. const posts = this._getPosts();
  379. if (clickElement(posts[0], ['div.feed-new-update-pill button'])) {
  380. this._post = posts[0];
  381. } else {
  382. clickElement(document, ['main button.scaffold-finite-scroll__load-button']);
  383. }
  384. this._scrollToCurrentPost();
  385. }
  386.  
  387. _openMeatballMenu() {
  388. if (this._comment) {
  389. // XXX In this case, the aria-label is on the svg element, not
  390. // the button, so use the parentElement.
  391. const button = this._comment.querySelector('[aria-label^="Open options"]').parentElement;
  392. button.click();
  393. } else if (this._post) {
  394. // Yeah, I don't get it. This one isn't the button either,
  395. // but the click works.
  396. clickElement(this._post, ['[aria-label^="Open control menu"]']);
  397. }
  398. }
  399.  
  400. _focusBrowser() {
  401. const el = this._comment ? this._comment : this._post;
  402. if (el) {
  403. const tabIndex = el.getAttribute('tabindex');
  404. el.setAttribute('tabindex', 0);
  405. el.focus();
  406. if (tabIndex) {
  407. el.setAttribute('tabindex', tabIndex);
  408. } else {
  409. el.removeAttribute('tabindex');
  410. }
  411. }
  412. }
  413.  
  414. }
  415.  
  416. class Jobs extends Page {
  417. _pathname = '/jobs/';
  418. }
  419.  
  420. class JobsCollections extends Page {
  421. _pathname = '/jobs/collections/';
  422. }
  423.  
  424. class Notifications extends Page {
  425. _pathname = '/notifications/';
  426. _auto_keys = [
  427. {seq: 'j', desc: 'Next notification', func: this._nextNotification},
  428. {seq: 'k', desc: 'Previous notification', func: this._prevNotification},
  429. {seq: 'a', desc: 'Activate the notification (click on it)', func: this._activateNotification},
  430. {seq: '=', desc: 'Open the (⋯) menu', func: this._openMeatballMenu},
  431. ];
  432.  
  433. // Ugh. When notifications are deleted, the entire element, and
  434. // parent elements, are deleted and replaced by new elements. So
  435. // the only way to track them is by array position.
  436. _currentNotificationIndex = -1;
  437.  
  438. get _notification() {
  439. if (this._currentNotificationIndex >= 0) {
  440. return this._getNotifications()[this._currentNotificationIndex];
  441. } else {
  442. return null;
  443. }
  444. }
  445.  
  446. set _notification(val) {
  447. if (this._notification) {
  448. this._notification.classList.remove('tom');
  449. }
  450. if (val) {
  451. const notifications = this._getNotifications();
  452. this._currentNotificationIndex = notifications.indexOf(val);
  453. val.classList.add('tom');
  454. this._scrollToCurrentNotification();
  455. }
  456. }
  457.  
  458. _getNotifications() {
  459. return Array.from(document.querySelectorAll('main section div.nt-card-list article'));
  460. }
  461.  
  462. _scrollToCurrentNotification() {
  463. const rect = this._notification.getBoundingClientRect();
  464. this._notification.style.scrollMarginTop = navBarHeightCss;
  465. this._notification.style.scrollMarginBottom = '3em';
  466. if (rect.bottom > document.documentElement.clientHeight) {
  467. this._notification.scrollIntoView(false);
  468. }
  469. if (rect.top < navBarHeightPixels) {
  470. this._notification.scrollIntoView();
  471. }
  472. }
  473.  
  474. _scrollBy(n) {
  475. const notifications = this._getNotifications();
  476. if (notifications.length) {
  477. const idx = Math.max(Math.min(this._currentNotificationIndex + n, notifications.length - 1), 0);
  478. this._notification = notifications[idx];
  479. }
  480. }
  481.  
  482. _nextNotification() {
  483. this._scrollBy(1);
  484. }
  485.  
  486. _prevNotification() {
  487. this._scrollBy(-1);
  488. }
  489.  
  490. _openMeatballMenu() {
  491. clickElement(this._notification, ['button[aria-label^="Settings menu"]', 'button[aria-label^="Undo notification deletion"]']);
  492. }
  493.  
  494. _activateNotification() {
  495. if (this._notification) {
  496. // Every notification is different.
  497. function matchesKnownText(el) {
  498. if (el.innerText === 'Apply early') return true;
  499. if (el.innerText.match(/View \d+ Job/)) return true;
  500. return false;
  501. }
  502.  
  503. if (!clickElement(this._notification, ['button.message-anywhere-button'])) {
  504. const buttons = Array.from(this._notification.querySelectorAll('button'));
  505. const button = buttons.find(matchesKnownText);
  506. if (button) {
  507. button.click();
  508. } else {
  509. const links = this._notification.querySelectorAll('a');
  510. if (links.length === 1) {
  511. links[0].click();
  512. } else {
  513. console.debug(this._notification);
  514. console.debug(this._notification.querySelectorAll('*'));
  515. const msg = [
  516. 'You tried to activate an unsupported notification',
  517. 'element. Please file a bug. If you are comfortable',
  518. 'with using the browser\'s Developer Tools (often the',
  519. 'F12 key), consider sharing the information just logged',
  520. 'in the console / debug view.',
  521. ];
  522. alert(msg.join(' '));
  523. }
  524. }
  525. }
  526. }
  527. }
  528.  
  529. }
  530.  
  531. class Pages {
  532. _global = null;
  533. _page = null;
  534. _pages = new Map();
  535.  
  536. _lastInputElement = null;
  537.  
  538. constructor() {
  539. this._id = crypto.randomUUID();
  540. this._installNavStyle();
  541. this._initializeHelpMenu();
  542. document.addEventListener('focus', this._onFocus.bind(this), true);
  543. document.addEventListener('href', this._onHref.bind(this), true);
  544. }
  545.  
  546. _setInputFocus(state) {
  547. const pages = Array.from(this._pages.values());
  548. pages.push(this._global);
  549. for (const page of pages) {
  550. if (page) {
  551. page.keyboard.setContext('inputFocus', state);
  552. }
  553. }
  554. }
  555.  
  556. _onFocus(evt) {
  557. if (this._lastInputElement && evt.target !== this._lastInputElement) {
  558. this._lastInputElement = null
  559. this._setInputFocus(false);
  560. }
  561. if (isInput(evt.target)) {
  562. this._setInputFocus(true);
  563. this._lastInputElement = evt.target;
  564. }
  565. }
  566.  
  567. _onHref(evt) {
  568. this.activate(evt.detail.url.pathname);
  569. }
  570.  
  571. _installNavStyle() {
  572. const style = document.createElement('style');
  573. style.textContent += '.tom { border-color: orange !important; border-style: solid !important; border-width: medium !important; }';
  574. style.textContent += '.dick { border-color: red !important; border-style: solid !important; border-width: thin !important; }';
  575. document.head.append(style);
  576. }
  577.  
  578. _initializeHelpMenu() {
  579. this._helpId = `help-${this._id}`;
  580. const style = document.createElement('style');
  581. style.textContent += `#${this._helpId} kbd {font-size: 0.85em; padding: 0.07em; border-width: 1px; border-style: solid; }`;
  582. style.textContent += `#${this._helpId} th { padding-top: 1em; text-align: left; }`;
  583. style.textContent += `#${this._helpId} td:first-child { white-space: nowrap; text-align: right; padding-right: 0.5em; }`;
  584. style.textContent += `#${this._helpId} button { border-width: 1px; border-style: solid; border-radius: 0.25em; }`;
  585. document.head.prepend(style);
  586. const dialog = document.createElement('dialog');
  587. dialog.id = this._helpId
  588. dialog.innerHTML = '<table><caption>' +
  589. '<span style="float: left">Keyboard shortcuts</span>' +
  590. '<span style="float: right">Hit <kbd>ESC</kbd> to close</span>' +
  591. '</caption><tbody></tbody></table>';
  592. document.body.prepend(dialog);
  593. }
  594.  
  595. // ThisPage -> This Page
  596. _parseHeader(text) {
  597. return text.replace(/([A-Z])/g, ' $1').trim();
  598. }
  599.  
  600. // 'a b' -> '<kbd>a</kbd> then <kbd>b</kbd>'
  601. _parseSeq(seq) {
  602. const letters = seq.split(' ').map(w => `<kbd>${w}</kbd>`);
  603. const s = letters.join(' then ');
  604. return s;
  605. }
  606.  
  607. _addHelp(page) {
  608. const help = document.querySelector(`#${this._helpId} tbody`);
  609. const section = this._parseHeader(page.helpHeader);
  610. let s = `<tr><th></th><th>${section}</th></tr>`;
  611. for (const {seq, desc} of page.helpContent) {
  612. const keys = this._parseSeq(seq);
  613. s += `<tr><td>${keys}:</td><td>${desc}</td></tr>`;
  614. }
  615. // Don't include works in progress that have no keys yet.
  616. if (page.helpContent.length) {
  617. help.innerHTML += s;
  618. }
  619. }
  620.  
  621. register(page) {
  622. page.start();
  623. this._addHelp(page);
  624. if (page.pathname === null) {
  625. page.helpId = this._helpId
  626. this._global = page;
  627. this._global.activate();
  628. } else {
  629. this._pages.set(page.pathname, page);
  630. }
  631. }
  632.  
  633. _findPage(pathname) {
  634. const pathnames = Array.from(this._pages.keys());
  635. const candidates = pathnames.filter(p => pathname.startsWith(p));
  636. const candidate = candidates.reduce((a, b) => {
  637. return a.length > b.length ? a : b;
  638. }, '');
  639. return this._pages.get(pathname) || null;
  640. }
  641.  
  642. activate(pathname) {
  643. if (this._page) {
  644. this._page.deactivate();
  645. }
  646. const page = this._findPage(pathname);
  647. this._page = page;
  648. if (page) {
  649. page.activate();
  650. }
  651. }
  652. }
  653.  
  654. const pages = new Pages();
  655. pages.register(new Global());
  656. pages.register(new Feed());
  657. pages.register(new Jobs());
  658. pages.register(new JobsCollections());
  659. pages.register(new Notifications());
  660. pages.activate(window.location.pathname);
  661.  
  662. function isInput(element) {
  663. let tagName = '';
  664. if ('tagName' in element) {
  665. tagName = element.tagName.toLowerCase();
  666. }
  667. return (element.isContentEditable || ['input', 'textarea'].includes(tagName));
  668. }
  669.  
  670. // Run querySelector to get an element, then click it.
  671. function clickElement(base, selectorArray) {
  672. if (base) {
  673. for (const selector of selectorArray) {
  674. const el = base.querySelector(selector);
  675. if (el) {
  676. el.click();
  677. return true;
  678. }
  679. }
  680. }
  681. return false;
  682. }
  683.  
  684. let navBarHeightPixels = 0;
  685. let navBarHeightCss = '0';
  686. VM.observe(document.body, () => {
  687. const navbar = document.querySelector('#global-nav');
  688.  
  689. if (navbar) {
  690. navBarHeightPixels = navbar.clientHeight + 4;
  691. navBarHeightCss = `${navBarHeightPixels}px`;
  692.  
  693. return true;
  694. }
  695. });
  696.  
  697. let oldUrl = new URL(window.location);
  698. VM.observe(document.body, () => {
  699. const newUrl = new URL(window.location);
  700. if (oldUrl.href !== newUrl.href) {
  701. const evt = new CustomEvent('href', {detail: {url: newUrl}})
  702. oldUrl = newUrl;
  703. document.dispatchEvent(evt);
  704. }
  705. });
  706.  
  707. })();