LinkedIn Tool

Minor enhancements to LinkedIn. Mostly just hotkeys.

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

  1. // ==UserScript==
  2. // @name LinkedIn Tool
  3. // @namespace dalgoda@gmail.com
  4. // @match https://www.linkedin.com/*
  5. // @version 1.10.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: '<', desc: 'First post or comment', func: this._firstPostOrComment},
  226. {seq: '>', desc: 'Last post or comment', func: this._lastPostOrComment},
  227. {seq: 'f', desc: 'Focus on current post or comment (causes browser to change focus)', func: this._focusBrowser},
  228. {seq: 'v p', desc: 'View the post directly', func: this._viewPost},
  229. {seq: 'v r', desc: 'View reactions on current post or comment', func: this._viewReactions},
  230. {seq: 'P', desc: 'Go to the share box to start a post or <kbd>TAB</kbd> to the other creator options', func: this._gotoShare},
  231. {seq: '=', desc: 'Open the (⋯) menu', func: this._openMeatballMenu},
  232. ];
  233.  
  234. _currentPostElement = null;
  235. _currentCommentElement = null;
  236.  
  237. _clickHandler(evt) {
  238. const post = evt.target.closest('div[data-id]');
  239. if (post) {
  240. this._post = post;
  241. }
  242. }
  243.  
  244. get _post() {
  245. return this._currentPostElement;
  246. }
  247.  
  248. set _post(val) {
  249. if (val === this._currentPostElement && this._comment) {
  250. return;
  251. }
  252. if (this._currentPostElement) {
  253. this._currentPostElement.classList.remove('tom');
  254. }
  255. this._currentPostElement = val;
  256. this._comment = null;
  257. if (val) {
  258. val.classList.add('tom');
  259. this._scrollToCurrentPost();
  260. }
  261. }
  262.  
  263. get _comment() {
  264. return this._currentCommentElement;
  265. }
  266.  
  267. set _comment(val) {
  268. if (this._currentCommentElement) {
  269. this._currentCommentElement.classList.remove('dick');
  270. }
  271. this._currentCommentElement = val;
  272. if (val) {
  273. val.classList.add('dick');
  274. this._scrollToCurrentComment();
  275. }
  276. }
  277.  
  278. _getPosts() {
  279. return Array.from(document.querySelectorAll('main div[data-id]'));
  280. }
  281.  
  282. _getComments() {
  283. if (this._post) {
  284. return Array.from(this._post.querySelectorAll('article.comments-comment-item'));
  285. } else {
  286. return [];
  287. }
  288. }
  289.  
  290. _scrollToCurrentPost() {
  291. this._post.style.scrollMarginTop = navBarHeightCss;
  292. this._post.scrollIntoView();
  293. }
  294.  
  295. _scrollToCurrentComment() {
  296. const rect = this._comment.getBoundingClientRect();
  297. this._comment.style.scrollMarginTop = navBarHeightCss;
  298. this._comment.style.scrollMarginBottom = '3em';
  299. // If both scrolling happens, that means the comment is too long
  300. // to fit on the page, so the top is preferred.
  301. if (rect.bottom > document.documentElement.clientHeight) {
  302. this._comment.scrollIntoView(false);
  303. }
  304. if (rect.top < navBarHeightPixels) {
  305. this._comment.scrollIntoView();
  306. }
  307. }
  308.  
  309. _scrollBy(n) {
  310. const posts = this._getPosts();
  311. if (posts.length) {
  312. let idx = Math.max(posts.indexOf(this._post), 0);
  313. let post = null;
  314. // Some posts are hidden (ads, suggestions). Skip over thoses.
  315. do {
  316. idx = (idx + n + posts.length) % posts.length;
  317. post = posts[idx];
  318. } while (!post.clientHeight);
  319. this._post = post;
  320. }
  321. }
  322.  
  323. _scrollCommentsBy(n) {
  324. const comments = this._getComments();
  325. if (comments.length) {
  326. let idx = comments.indexOf(this._comment);
  327. idx += n
  328. if (idx < -1) {
  329. idx = comments.length - 1
  330. }
  331. if (idx === -1 || idx >= comments.length) {
  332. // focus back to post
  333. this._comment = null;
  334. this._post = this._post;
  335. } else {
  336. this._comment = comments[idx];
  337. }
  338. }
  339. }
  340.  
  341. _nextPost() {
  342. this._scrollBy(1);
  343. }
  344.  
  345. _nextPostPlus() {
  346. const lastPost = this._post;
  347. function f() {
  348. this._togglePost();
  349. this._nextPost();
  350. }
  351. // XXX Need to remove the highlight before otrot sees it because
  352. // it affects the .clientHeight.
  353. this._post.classList.remove('tom');
  354. otrot(this._post, f.bind(this), 3000).then(() => {
  355. this._scrollToCurrentPost();
  356. }).catch(e => console.error(e));
  357. }
  358.  
  359. _prevPost() {
  360. this._scrollBy(-1);
  361. }
  362.  
  363. _prevPostPlus() {
  364. this._togglePost();
  365. this._prevPost();
  366. }
  367.  
  368. _nextComment() {
  369. this._scrollCommentsBy(1);
  370. }
  371.  
  372. _prevComment() {
  373. this._scrollCommentsBy(-1);
  374. }
  375.  
  376. _togglePost() {
  377. clickElement(this._post, ['button[aria-label^="Dismiss post"]', 'button[aria-label^="Undo and show"]']);
  378. }
  379.  
  380. _showComments() {
  381. function tryComment(comment) {
  382. if (comment) {
  383. const buttons = Array.from(comment.querySelectorAll('button'));
  384. const button = buttons.find(el => el.textContent.includes('Load previous replies'));
  385. if (button) {
  386. button.click();
  387. return true;
  388. }
  389. }
  390. return false;
  391. }
  392.  
  393. if (!tryComment(this._comment)) {
  394. clickElement(this._post, ['button[aria-label*="comment"]']);
  395. }
  396. }
  397.  
  398. _seeMore() {
  399. const el = this._comment ? this._comment : this._post;
  400. clickElement(el, ['button[aria-label^="see more"]']);
  401. }
  402.  
  403. _likePostOrComment() {
  404. const el = this._comment ? this._comment : this._post;
  405. clickElement(el, ['button[aria-label^="Open reactions menu"]']);
  406. }
  407.  
  408. _jumpToPostOrComment(first) {
  409. if (this._comment) {
  410. var comments = this._getComments();
  411. if (comments.length) {
  412. const idx = first ? 0 : (comments.length - 1);
  413. this._comment = comments[idx];
  414. }
  415. } else {
  416. const posts = this._getPosts();
  417. if (posts.length) {
  418. const idx = first ? 0 : (posts.length - 1);
  419. this._post = posts[idx];
  420. }
  421. }
  422. }
  423.  
  424. _firstPostOrComment() {
  425. this._jumpToPostOrComment(true);
  426. }
  427.  
  428. _lastPostOrComment() {
  429. this._jumpToPostOrComment(false);
  430. }
  431.  
  432. _loadMorePosts() {
  433. const posts = this._getPosts();
  434. if (clickElement(posts[0], ['div.feed-new-update-pill button'])) {
  435. this._post = posts[0];
  436. } else {
  437. clickElement(document, ['main button.scaffold-finite-scroll__load-button']);
  438. }
  439. this._scrollToCurrentPost();
  440. }
  441.  
  442. _gotoShare() {
  443. const share = document.querySelector('div.share-box-feed-entry__top-bar').parentElement;
  444. share.style.scrollMarginTop = navBarHeightCss;
  445. share.scrollIntoView();
  446. share.querySelector('button').focus();
  447. }
  448.  
  449. _openMeatballMenu() {
  450. if (this._comment) {
  451. // XXX In this case, the aria-label is on the svg element, not
  452. // the button, so use the parentElement.
  453. const button = this._comment.querySelector('[aria-label^="Open options"]').parentElement;
  454. button.click();
  455. } else if (this._post) {
  456. // Yeah, I don't get it. This one isn't the button either,
  457. // but the click works.
  458. clickElement(this._post, ['[aria-label^="Open control menu"]']);
  459. }
  460. }
  461.  
  462. _focusBrowser() {
  463. const el = this._comment ? this._comment : this._post;
  464. if (el) {
  465. const tabIndex = el.getAttribute('tabindex');
  466. el.setAttribute('tabindex', 0);
  467. el.focus();
  468. if (tabIndex) {
  469. el.setAttribute('tabindex', tabIndex);
  470. } else {
  471. el.removeAttribute('tabindex');
  472. }
  473. }
  474. }
  475.  
  476. _viewPost() {
  477. if (this._post) {
  478. const urn = this._post.dataset.id;
  479. const id = `lt-${urn.replaceAll(':', '-')}`;
  480. let a = this._post.querySelector(`#${id}`);
  481. if (!a) {
  482. a = document.createElement('a');
  483. a.href = `/feed/update/${urn}/`;
  484. a.id = id;
  485. this._post.append(a);
  486. }
  487. a.click();
  488. }
  489. }
  490.  
  491. _viewReactions() {
  492. // Bah! The queries are annoyingly different.
  493. if (this._comment) {
  494. clickElement(this._comment, ['button.comments-comment-social-bar__reactions-count']);
  495. } else if (this._post) {
  496. clickElement(this._post, ['button.social-details-social-counts__count-value']);
  497. }
  498. }
  499.  
  500. }
  501.  
  502. class Jobs extends Page {
  503. _pathname = '/jobs/';
  504. }
  505.  
  506. class JobsCollections extends Page {
  507. _pathname = '/jobs/collections/';
  508. }
  509.  
  510. class Notifications extends Page {
  511. _pathname = '/notifications/';
  512. _click_handler_selector = 'main';
  513. _auto_keys = [
  514. {seq: 'j', desc: 'Next notification', func: this._nextNotification},
  515. {seq: 'k', desc: 'Previous notification', func: this._prevNotification},
  516. {seq: 'Enter', desc: 'Activate the notification (click on it)', func: this._activateNotification},
  517. {seq: 'X', desc: 'Toggle current notification deletion', func: this._deleteNotification},
  518. {seq: 'l', desc: 'Load more notifications', func: this._loadMoreNotifications},
  519. {seq: '<', desc: 'First notification', func: this._firstNotification},
  520. {seq: '>', desc: 'Last notification', func: this._lastNotification},
  521. {seq: '=', desc: 'Open the (⋯) menu', func: this._openMeatballMenu},
  522. ];
  523.  
  524. // Ugh. When notifications are deleted, the entire element, and
  525. // parent elements, are deleted and replaced by new elements. So
  526. // the only way to track them is by array position.
  527. _currentNotificationIndex = -1;
  528.  
  529. _clickHandler(evt) {
  530. const notification = evt.target.closest('div.nt-card-list article');
  531. if (notification) {
  532. this._notification = notification;
  533. }
  534. }
  535.  
  536. get _notification() {
  537. if (this._currentNotificationIndex >= 0) {
  538. return this._getNotifications()[this._currentNotificationIndex];
  539. } else {
  540. return null;
  541. }
  542. }
  543.  
  544. set _notification(val) {
  545. if (this._notification) {
  546. this._notification.classList.remove('tom');
  547. }
  548. if (val) {
  549. const notifications = this._getNotifications();
  550. this._currentNotificationIndex = notifications.indexOf(val);
  551. val.classList.add('tom');
  552. this._scrollToCurrentNotification();
  553. }
  554. }
  555.  
  556. _getNotifications() {
  557. return Array.from(document.querySelectorAll('main section div.nt-card-list article'));
  558. }
  559.  
  560. _scrollToCurrentNotification() {
  561. const rect = this._notification.getBoundingClientRect();
  562. this._notification.style.scrollMarginTop = navBarHeightCss;
  563. this._notification.style.scrollMarginBottom = '3em';
  564. if (rect.bottom > document.documentElement.clientHeight) {
  565. this._notification.scrollIntoView(false);
  566. }
  567. if (rect.top < navBarHeightPixels) {
  568. this._notification.scrollIntoView();
  569. }
  570. }
  571.  
  572. _scrollBy(n) {
  573. const notifications = this._getNotifications();
  574. if (notifications.length) {
  575. if (this._currentNotificationIndex === -1 && n === -1) {
  576. this._currentNotificationIndex = 0;
  577. }
  578. const idx = (this._currentNotificationIndex + n + notifications.length) % notifications.length;
  579. this._notification = notifications[idx];
  580. }
  581. }
  582.  
  583. _nextNotification() {
  584. this._scrollBy(1);
  585. }
  586.  
  587. _prevNotification() {
  588. this._scrollBy(-1);
  589. }
  590.  
  591. _jumpToNotification(first) {
  592. const notifications = this._getNotifications();
  593. if (notifications.length) {
  594. const idx = first ? 0 : (notifications.length - 1);
  595. this._notification = notifications[idx];
  596. }
  597. }
  598.  
  599. _firstNotification() {
  600. this._jumpToNotification(true);
  601. }
  602.  
  603. _lastNotification() {
  604. this._jumpToNotification(false);
  605. }
  606.  
  607. _openMeatballMenu() {
  608. clickElement(this._notification, ['button[aria-label^="Settings menu"]']);
  609. }
  610.  
  611. _activateNotification() {
  612. if (this._notification) {
  613. // Every notification is different.
  614. // It may be that notifications are settling on 'a.nt-card__headline'.
  615. function matchesKnownText(el) {
  616. if (el.innerText === 'Apply early') return true;
  617. return false;
  618. }
  619.  
  620. // Debugging code.
  621. if (this._notification.querySelectorAll('a.nt-card__headline').length === 1 && this._notification.querySelector('button.message-anywhere-button')) {
  622. console.debug(this._notification);
  623. alert('Yes, can be simplified');
  624. }
  625.  
  626. if (!clickElement(this._notification, ['button.message-anywhere-button'])) {
  627. const buttons = Array.from(this._notification.querySelectorAll('button'));
  628. const button = buttons.find(matchesKnownText);
  629. if (button) {
  630. button.click();
  631. } else {
  632. const links = this._notification.querySelectorAll('a.nt-card__headline');
  633. if (links.length === 1) {
  634. links[0].click();
  635. } else {
  636. console.debug(this._notification);
  637. for (const el of this._notification.querySelectorAll('*')) {
  638. console.debug(el);
  639. }
  640. const msg = [
  641. 'You tried to activate an unsupported notification',
  642. 'element. Please file a bug. If you are comfortable',
  643. 'with using the browser\'s Developer Tools (often the',
  644. 'F12 key), consider sharing the information just logged',
  645. 'in the console / debug view.',
  646. ];
  647. alert(msg.join(' '));
  648. }
  649. }
  650. }
  651. }
  652. }
  653.  
  654. _deleteNotification() {
  655. if (this._notification) {
  656. // Hah. Unlike in other places, these buttons already exist,
  657. // just hidden under the menu.
  658. const buttons = Array.from(this._notification.querySelectorAll('button'));
  659. const button = buttons.find(el => el.textContent.includes('Delete this notification'));
  660. if (button) {
  661. button.click();
  662. } else {
  663. clickElement(this._notification, ['button[aria-label^="Undo notification deletion"]']);
  664. }
  665. }
  666. }
  667.  
  668. _loadMoreNotifications() {
  669. const buttons = Array.from(document.querySelectorAll('main section button'));
  670. const button = buttons.find(el => el.textContent.includes('Show more results'));
  671. if (button) {
  672. button.click();
  673. }
  674. }
  675.  
  676. }
  677.  
  678. class Pages {
  679. _global = null;
  680. _page = null;
  681. _pages = new Map();
  682.  
  683. _lastInputElement = null;
  684.  
  685. constructor() {
  686. this._id = crypto.randomUUID();
  687. this._installNavStyle();
  688. this._initializeHelpMenu();
  689. document.addEventListener('focus', this._onFocus.bind(this), true);
  690. document.addEventListener('href', this._onHref.bind(this), true);
  691. }
  692.  
  693. _setInputFocus(state) {
  694. const pages = Array.from(this._pages.values());
  695. pages.push(this._global);
  696. for (const page of pages) {
  697. if (page) {
  698. page.keyboard.setContext('inputFocus', state);
  699. }
  700. }
  701. }
  702.  
  703. _onFocus(evt) {
  704. if (this._lastInputElement && evt.target !== this._lastInputElement) {
  705. this._lastInputElement = null
  706. this._setInputFocus(false);
  707. }
  708. if (isInput(evt.target)) {
  709. this._setInputFocus(true);
  710. this._lastInputElement = evt.target;
  711. }
  712. }
  713.  
  714. _onHref(evt) {
  715. this.activate(evt.detail.url.pathname);
  716. }
  717.  
  718. _installNavStyle() {
  719. const style = document.createElement('style');
  720. style.textContent += '.tom { border-color: orange !important; border-style: solid !important; border-width: medium !important; }';
  721. style.textContent += '.dick { border-color: red !important; border-style: solid !important; border-width: thin !important; }';
  722. document.head.append(style);
  723. }
  724.  
  725. _initializeHelpMenu() {
  726. this._helpId = `help-${this._id}`;
  727. const style = document.createElement('style');
  728. style.textContent += `#${this._helpId} kbd {font-size: 0.85em; padding: 0.07em; border-width: 1px; border-style: solid; }`;
  729. style.textContent += `#${this._helpId} th { padding-top: 1em; text-align: left; }`;
  730. style.textContent += `#${this._helpId} td:first-child { white-space: nowrap; text-align: right; padding-right: 0.5em; }`;
  731. style.textContent += `#${this._helpId} button { border-width: 1px; border-style: solid; border-radius: 0.25em; }`;
  732. document.head.prepend(style);
  733. const dialog = document.createElement('dialog');
  734. dialog.id = this._helpId
  735. dialog.innerHTML = '<table><caption>' +
  736. '<span style="float: left">Keyboard shortcuts</span>' +
  737. '<span style="float: right">Hit <kbd>ESC</kbd> to close</span>' +
  738. '</caption><tbody></tbody></table>';
  739. document.body.prepend(dialog);
  740. }
  741.  
  742. // ThisPage -> This Page
  743. _parseHeader(text) {
  744. return text.replace(/([A-Z])/g, ' $1').trim();
  745. }
  746.  
  747. // 'a b' -> '<kbd>a</kbd> then <kbd>b</kbd>'
  748. _parseSeq(seq) {
  749. const letters = seq.split(' ').map(w => `<kbd>${w}</kbd>`);
  750. const s = letters.join(' then ');
  751. return s;
  752. }
  753.  
  754. _addHelp(page) {
  755. const help = document.querySelector(`#${this._helpId} tbody`);
  756. const section = this._parseHeader(page.helpHeader);
  757. let s = `<tr><th></th><th>${section}</th></tr>`;
  758. for (const {seq, desc} of page.helpContent) {
  759. const keys = this._parseSeq(seq);
  760. s += `<tr><td>${keys}:</td><td>${desc}</td></tr>`;
  761. }
  762. // Don't include works in progress that have no keys yet.
  763. if (page.helpContent.length) {
  764. help.innerHTML += s;
  765. }
  766. }
  767.  
  768. register(page) {
  769. page.start();
  770. this._addHelp(page);
  771. if (page.pathname === null) {
  772. page.helpId = this._helpId
  773. this._global = page;
  774. this._global.activate();
  775. } else {
  776. this._pages.set(page.pathname, page);
  777. }
  778. }
  779.  
  780. _findPage(pathname) {
  781. const pathnames = Array.from(this._pages.keys());
  782. const candidates = pathnames.filter(p => pathname.startsWith(p));
  783. const candidate = candidates.reduce((a, b) => {
  784. return a.length > b.length ? a : b;
  785. }, '');
  786. return this._pages.get(pathname) || null;
  787. }
  788.  
  789. activate(pathname) {
  790. console.debug('activating', pathname);
  791. if (this._page) {
  792. this._page.deactivate();
  793. }
  794. const page = this._findPage(pathname);
  795. this._page = page;
  796. if (page) {
  797. page.activate();
  798. }
  799. }
  800. }
  801.  
  802. const pages = new Pages();
  803. pages.register(new Global());
  804. pages.register(new Feed());
  805. pages.register(new Jobs());
  806. pages.register(new JobsCollections());
  807. pages.register(new Notifications());
  808. pages.activate(window.location.pathname);
  809.  
  810. function isInput(element) {
  811. let tagName = '';
  812. if ('tagName' in element) {
  813. tagName = element.tagName.toLowerCase();
  814. }
  815. return (element.isContentEditable || ['input', 'textarea'].includes(tagName));
  816. }
  817.  
  818. // Run querySelector to get an element, then click it.
  819. function clickElement(base, selectorArray) {
  820. if (base) {
  821. for (const selector of selectorArray) {
  822. const el = base.querySelector(selector);
  823. if (el) {
  824. el.click();
  825. return true;
  826. }
  827. }
  828. }
  829. return false;
  830. }
  831.  
  832. // One time mutation observer with timeout
  833. // base - element to observe
  834. // options - MutationObserver().observe options
  835. // monitor - function that takes [MutationRecord] and returns a {done, results} object
  836. // trigger - function to call that triggers observable results, can be null
  837. // timeout - time to wait for completion in milliseconds, 0 disables
  838. // Returns promise that will resolve with the results from monitor.
  839. function otmot(base, options, monitor, trigger, timeout) {
  840. const prom = new Promise((resolve, reject) => {
  841. let timeoutID = null;
  842. trigger = trigger || function () {};
  843. const observer = new MutationObserver((records) => {
  844. const {done, results} = monitor(records);
  845. if (done) {
  846. observer.disconnect();
  847. clearTimeout(timeoutID);
  848. resolve(results);
  849. }
  850. });
  851. if (timeout) {
  852. timeoutID = setTimeout(() => {
  853. observer.disconnect();
  854. reject('timed out');
  855. }, timeout);
  856. }
  857. observer.observe(base, options);
  858. trigger();
  859. });
  860. return prom;
  861. }
  862.  
  863. // One time resize observer with timeout
  864. // Will resolve automatically upon resize change.
  865. // base - element to observe
  866. // trigger - function to call that triggers observable events, can be null
  867. // timeout - time to wait for completion in milliseconds, 0 disables
  868. // Returns promise that will resolve with the results from monitor.
  869. function otrot(base, trigger, timeout) {
  870. const prom = new Promise((resolve, reject) => {
  871. let timeoutID = null;
  872. const initialHeight = base.clientHeight;
  873. const initialWidth = base.clientWidth;
  874. trigger = trigger || function () {};
  875. const observer = new ResizeObserver(() => {
  876. if (base.clientHeight !== initialHeight || base.clientWidth !== initialWidth) {
  877. observer.disconnect();
  878. clearTimeout(timeoutID);
  879. resolve(base);
  880. }
  881. });
  882. if (timeout) {
  883. timeoutID = setTimeout(() => {
  884. observer.disconnect();
  885. reject('timed out');
  886. }, timeout);
  887. }
  888. observer.observe(base);
  889. trigger();
  890. });
  891. return prom;
  892. }
  893.  
  894. function navBarMonitor(records) {
  895. const navbar = document.querySelector('#global-nav');
  896. if (navbar) {
  897. return {done: true, results: navbar};
  898. }
  899. return {done: false, results: null};
  900. }
  901.  
  902. let navBarHeightPixels = 0;
  903. let navBarHeightCss = '0';
  904.  
  905. // In this case, the trigger was the page load. It already happened
  906. // by the time we got here.
  907. otmot(document.body, {childList: true, subtree: true}, navBarMonitor,
  908. null, 0)
  909. .then((el) => {
  910. navBarHeightPixels = el.clientHeight + 4;
  911. navBarHeightCss = `${navBarHeightPixels}px`;
  912. });
  913.  
  914. let oldUrl = new URL(window.location);
  915. function registerUrlMonitor(element) {
  916. const observer = new MutationObserver((records) => {
  917. const newUrl = new URL(window.location);
  918. if (oldUrl.href !== newUrl.href) {
  919. const evt = new CustomEvent('href', {detail: {url: newUrl}})
  920. oldUrl = newUrl;
  921. document.dispatchEvent(evt);
  922. }
  923. });
  924. observer.observe(element, {childList: true, subtree: true});
  925. }
  926.  
  927. function authenticationOutletMonitor() {
  928. const div = document.body.querySelector('div.authentication-outlet');
  929. if (div) {
  930. return {done: true, results: div};
  931. }
  932. return {done: false, results: null};
  933. }
  934.  
  935. otmot(document.body, {childList: true, subtree: true}, authenticationOutletMonitor, null, 0)
  936. .then((el) => registerUrlMonitor(el));
  937.  
  938. })();