LinkedIn Tool

Minor enhancements to LinkedIn. Mostly just hotkeys.

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

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