Guest User

yahoomail

a guest
Nov 14th, 2026
15
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 62.74 KB | None | 0 0
  1. // ==UserScript==
  2. // @name Yahoo Mail Comfort
  3. // @namespace yahoo-fix
  4. // @version 20261114_0.8.0
  5. // @author DarkAuditor
  6. // @description Pagination instead of infinite scroll, denser rows and a compact, always-visible folder list for the new Yahoo Mail.
  7. // @match https://mail.yahoo.com/*
  8. // @run-at document-start
  9. // @grant none
  10. // ==/UserScript==
  11.  
  12. (() => {
  13. 'use strict';
  14. if (window.__yfxLoaded) return;
  15. window.__yfxLoaded = true;
  16.  
  17. // ---------------------------------------------------------------- settings
  18. const DEFAULTS = {
  19. pagination: true,
  20. pageSize: 50,
  21. density: 0.85, // CSS zoom applied to the message list (1 = Yahoo default)
  22. rowLines: 1, // with a reading pane: 1 = one line, 2 = subject over preview, 0 = Yahoo's rows
  23. rowHeight: 30, // height of a one-line row, px (two-line rows add LINE2 to it)
  24. listWidth: 530, // width of the list beside the reading pane, px (0 = Yahoo's own)
  25. compactFolders: true,
  26. hidePromoCards: true,
  27. collapseAdRows: true, // close the gaps left by ad rows inside the message list
  28. rightPanel: 1, // right-hand panel while it only shows ads: 0 = leave it, 1 = icon strip, 2 = hidden
  29. newTabClick: true, // Ctrl/Cmd+click and middle-click open a message in a new tab
  30. hintDismissed: false, // the "previews are off" notice was closed by the user
  31. collapsed: [], // folder paths whose children are hidden
  32. };
  33. const KEY = 'yfx.settings';
  34. const settings = { ...DEFAULTS };
  35. try { Object.assign(settings, JSON.parse(localStorage.getItem(KEY) || '{}')); } catch { /* keep defaults */ }
  36. if (settings.singleLine === false && !/"rowLines"/.test(localStorage.getItem(KEY) || '')) settings.rowLines = 0;
  37. delete settings.singleLine; // replaced by rowLines in 0.4.0
  38. if (settings.hideRightAds === false && !/"rightPanel"/.test(localStorage.getItem(KEY) || '')) settings.rightPanel = 0;
  39. delete settings.hideRightAds; // replaced by rightPanel in 0.6.1
  40. const LINE2 = 18; // extra height the preview line adds to a row
  41. // Two-line rows need Yahoo's "Message preview"; while that is off they fall back to one
  42. // line. The saved choice is kept, so they return as soon as previews are back on.
  43. let noPreview = false;
  44. const rowLines = () => (settings.rowLines === 2 && noPreview ? 1 : settings.rowLines);
  45. const rowPitch = () => settings.rowHeight + (rowLines() === 2 ? LINE2 : 0);
  46. const save = () => { try { localStorage.setItem(KEY, JSON.stringify(settings)); } catch { /* private mode */ } };
  47.  
  48. // Every selector that depends on Yahoo's markup lives here.
  49. const SEL = {
  50. appRoot: '#mail-app-container',
  51. main: '[data-test-id="novation-main-content"]',
  52. toolbar: '[data-test-id="message-list-toolbar"]',
  53. list: '[data-test-id="virtual-list"]',
  54. listContainer: '[data-test-id="virtual-list-container"]',
  55. listPane: '[data-test-id="resizable-view-left-pane"]',
  56. row: '[data-test-id="message-list-item"]',
  57. rail: '[data-test-id="novation-left-rail"]',
  58. railList: '[data-test-id="navigable-list"]',
  59. railToggle: '[data-test-id="toggle-divider-button"]',
  60. folderItem: '[data-test-id="menu-list-item"][data-folder-id]',
  61. badge: '[data-test-id="badge"]',
  62. inboxTabs: '[data-test-id="inbox-tabs-list"]',
  63. promoCard: '[data-test-id="tldr-inbox-list-opt-in-card"]',
  64. rightRail: '[data-test-id="novation-right-rail"]',
  65. rightRailBox: '#right-rail-container',
  66. };
  67.  
  68. const warn = (...a) => console.warn('[Yahoo Mail Comfort]', ...a);
  69. const guard = (name, fn) => (...a) => { try { return fn(...a); } catch (e) { warn(name, e); } };
  70. const $ = (s, root = document) => root.querySelector(s);
  71.  
  72. // ---------------------------------------------------------------- styles
  73. const CSS = `
  74. html.yfx-promo ${SEL.promoCard} { display: none !important; }
  75.  
  76. /* --- pagination --- */
  77. /* Yahoo decides how many rows to draw from the list's height at the moment it creates the
  78. list, and does not look again. So the list must be a full page tall from the very start,
  79. in the stylesheet; setting it from script afterwards is too late for a folder Yahoo
  80. already has in memory. (The per-page height set later, inline, overrides this.) */
  81. html.yfx-pg ${SEL.main} ${SEL.list} { height: var(--yfx-list-h) !important; flex: none !important; }
  82. .yfx-paged { flex: none !important; overflow: hidden !important; }
  83. .yfx-scroller { overflow-y: auto !important; overflow-x: hidden !important; }
  84. ${SEL.main} { position: relative; }
  85. #yfx-pager {
  86. position: absolute; top: 6px; right: 56px; z-index: 5;
  87. display: flex; align-items: center; gap: 4px;
  88. font: 13px/1 system-ui, sans-serif; color: #444; background: inherit;
  89. }
  90. #yfx-pager button {
  91. all: unset; cursor: pointer; min-width: 26px; height: 30px; text-align: center;
  92. border-radius: 4px; font-size: 16px; color: #333;
  93. }
  94. #yfx-pager button:hover:not(:disabled) { background: rgba(0,0,0,.08); }
  95. #yfx-pager button:focus-visible { outline: 2px solid #7d2eff; }
  96. #yfx-pager button:disabled { opacity: .3; cursor: default; }
  97. #yfx-pager .yfx-range { padding: 0 6px; white-space: nowrap; font-variant-numeric: tabular-nums; }
  98. #yfx-pager button[data-act="cfg"] {
  99. min-width: 32px; height: 32px; margin-left: 6px; font-size: 22px; line-height: 32px;
  100. color: #7d2eff; border-radius: 50%;
  101. }
  102. #yfx-pager button[data-act="cfg"]:hover { background: rgba(125,46,255,.14); color: #5b21d6; }
  103. /* numbered pages along the bottom of the list */
  104. #yfx-pages {
  105. position: absolute; left: 0; right: 0; bottom: 0; height: 34px; z-index: 4;
  106. display: flex; align-items: center; justify-content: center; gap: 2px;
  107. background: #fff; border-top: 1px solid #e6e6ed; font: 13px/1 system-ui, sans-serif; color: #333;
  108. }
  109. #yfx-pages button {
  110. all: unset; box-sizing: border-box; min-width: 26px; height: 26px; padding: 0 5px; text-align: center;
  111. border-radius: 4px; cursor: pointer; font-variant-numeric: tabular-nums;
  112. }
  113. #yfx-pages button:hover:not([aria-current]):not(:disabled) { background: rgba(0,0,0,.08); }
  114. #yfx-pages button:focus-visible { outline: 2px solid #7d2eff; }
  115. #yfx-pages button[aria-current] { background: #7d2eff; color: #fff; font-weight: 600; cursor: default; }
  116. #yfx-pages button:disabled { opacity: .3; cursor: default; }
  117. #yfx-pages .yfx-gap { padding: 0 4px; color: #888; }
  118. #yfx-pages .yfx-nav { font-size: 16px; }
  119. .yfx-busy { opacity: .35 !important; pointer-events: none !important; }
  120. #yfx-hint {
  121. display: flex; align-items: center; gap: 6px; margin-right: 8px; padding: 0 4px 0 10px; height: 28px;
  122. border-radius: 14px; background: rgba(125,46,255,.12); color: #4a1bb3; white-space: nowrap; font-size: 12.5px;
  123. }
  124. #yfx-hint[hidden] { display: none; }
  125. #yfx-hint a { color: inherit; font-weight: 600; text-decoration: underline; cursor: pointer; }
  126. #yfx-pager #yfx-hint button { min-width: 22px; height: 22px; font-size: 14px; color: inherit; border-radius: 50%; }
  127. #yfx-panel .yfx-warn { font-size: 12px; color: #4a1bb3; background: rgba(125,46,255,.10); padding: 6px 8px; border-radius: 4px; }
  128. #yfx-panel label.yfx-off { opacity: .45; }
  129. #yfx-panel .yfx-note { font-size: 12px; color: #666; margin: -2px 0 2px; }
  130. #yfx-panel {
  131. position: absolute; top: 40px; right: 0; width: 260px; padding: 10px 12px;
  132. background: #fff; color: #222; border: 1px solid #ccc; border-radius: 6px;
  133. box-shadow: 0 4px 16px rgba(0,0,0,.18); display: grid; gap: 8px;
  134. }
  135. #yfx-panel label { display: flex; justify-content: space-between; align-items: center; gap: 8px; }
  136. #yfx-panel select { font: inherit; }
  137. @media (prefers-color-scheme: dark) {
  138. html[data-color-scheme="dark"] #yfx-pager, html[data-color-scheme="dark"] #yfx-pager button { color: #ddd; }
  139. html[data-color-scheme="dark"] #yfx-panel { background: #222; color: #eee; border-color: #555; }
  140. html[data-color-scheme="dark"] #yfx-pager button[data-act="cfg"] { color: #b79bff; }
  141. html[data-color-scheme="dark"] #yfx-pages { background: #1d1d1f; color: #ddd; border-color: #444; }
  142. html[data-color-scheme="dark"] #yfx-panel .yfx-note { color: #aaa; }
  143. html[data-color-scheme="dark"] #yfx-hint, html[data-color-scheme="dark"] #yfx-panel .yfx-warn { color: #d6c8ff; background: rgba(160,120,255,.22); }
  144. }
  145.  
  146. /* --- one-line rows (reading pane layouts) --- */
  147. /* Yahoo's row is: [dot + avatar] [column: (sender | date) / (subject / snippet)] [icons].
  148. Flatten the column into a single line: sender, subject, snippet, icons, date. */
  149. .yfx-clip { flex: none !important; overflow: hidden !important; }
  150. html.yfx-1line.yfx-wide ${SEL.listPane} { width: var(--yfx-list-w) !important; max-width: 75% !important; }
  151. html.yfx-1line .yfx-paged ${SEL.row} {
  152. height: var(--yfx-row-h) !important; min-height: 0 !important; box-sizing: border-box !important;
  153. padding-top: 0 !important; padding-bottom: 0 !important; align-items: center !important;
  154. }
  155. html.yfx-1line .yfx-paged ${SEL.row} > div { margin-top: 0 !important; margin-bottom: 0 !important; }
  156. html.yfx-1line .yfx-paged ${SEL.row} > div:has([id^="email-sender-"]) {
  157. flex-direction: row !important; align-items: center !important; gap: 8px !important;
  158. min-width: 0 !important; height: auto !important;
  159. }
  160. html.yfx-1line .yfx-paged ${SEL.row} > div > div:has([id^="email-sender-"]) { display: contents !important; }
  161. html.yfx-1line .yfx-paged ${SEL.row} > div > div > div:has([id^="email-sender-"]) {
  162. order: 1; flex: 0 0 var(--yfx-sender-w) !important; width: auto !important; min-width: 0 !important;
  163. }
  164. html.yfx-1line .yfx-paged ${SEL.row} > div > div > div:has([id^="email-date-"]) { order: 4; flex: none !important; }
  165. html.yfx-1line .yfx-paged ${SEL.row} > div > div:has([id^="email-subject-"]) {
  166. order: 2; flex: 1 1 0 !important; min-width: 0 !important; height: auto !important;
  167. flex-direction: row !important; align-items: center !important; gap: 8px !important;
  168. }
  169. html.yfx-1line .yfx-paged ${SEL.row} [id^="email-subject-"]:not([id^="email-subject-snippet-"]) {
  170. display: block !important; flex: 0 1 auto !important; min-width: 0 !important; max-width: 100% !important;
  171. white-space: nowrap !important; overflow: hidden !important; text-overflow: ellipsis !important;
  172. }
  173. html.yfx-1line .yfx-paged ${SEL.row} > div > div > div:has([id^="email-snippet-"]) {
  174. flex: 1 1 0 !important; width: auto !important; min-width: 0 !important; opacity: .8;
  175. }
  176. html.yfx-1line .yfx-paged ${SEL.row} > div:has([id^="email-sender-"]) > div:not(:has([id^="email-"])) {
  177. position: static !important; order: 3; flex: none !important; padding-left: 0 !important;
  178. }
  179. /* Two-line variant: subject on the first line, message preview under it. Sender and date
  180. stay in their columns, level with the subject. */
  181. html.yfx-2line .yfx-paged ${SEL.row} > div:has([id^="email-sender-"]) { align-items: flex-start !important; }
  182. html.yfx-2line .yfx-paged ${SEL.row} > div > div:has([id^="email-subject-"]) {
  183. flex-direction: column !important; align-items: stretch !important; gap: 0 !important;
  184. }
  185. html.yfx-2line .yfx-paged ${SEL.row} [id^="email-sender-"],
  186. html.yfx-2line .yfx-paged ${SEL.row} [id^="email-date-"],
  187. html.yfx-2line .yfx-paged ${SEL.row} [id^="email-subject-"]:not([id^="email-subject-snippet-"]) {
  188. line-height: 19px !important; height: 19px !important;
  189. }
  190. html.yfx-2line .yfx-paged ${SEL.row} > div > div > div:has([id^="email-snippet-"]) {
  191. flex: none !important; width: 100% !important; height: 17px !important;
  192. }
  193. html.yfx-2line .yfx-paged ${SEL.row} [id^="email-snippet-"] {
  194. font-size: 12.5px !important; line-height: 17px !important;
  195. white-space: nowrap !important; overflow: hidden !important; text-overflow: ellipsis !important;
  196. }
  197.  
  198. /* --- right-hand panel --- */
  199. /* The panel is a row of icons (Calendar, Starred, Contacts, Settings, More) above a body that
  200. shows ads until one of those icons opens a real pane. While it only shows ads, keep just
  201. the icons, stacked in a slim strip, and give the freed width to the mail. */
  202. html.yfx-rr-min .yfx-grid, html.yfx-rr-none .yfx-grid { grid-template-columns: auto minmax(0, 1fr) auto !important; }
  203. /* "Hidden": take the whole panel out of the layout. It is only hidden, never deleted: the
  204. page is drawn by React, which breaks if nodes it owns disappear from under it. */
  205. html.yfx-rr-none ${SEL.rightRail} { display: none !important; }
  206. html.yfx-rr-none ${SEL.main} { margin-right: 16px !important; }
  207. html.yfx-rr-min ${SEL.rightRail} {
  208. width: auto !important; min-width: 0 !important; margin: 16px 8px 0 8px !important;
  209. height: auto !important; align-self: start !important;
  210. }
  211. html.yfx-rr-min ${SEL.rightRail} > div, html.yfx-rr-min ${SEL.rightRail} > div > div { width: auto !important; height: auto !important; }
  212. html.yfx-rr-min ${SEL.rightRailBox} { height: auto !important; }
  213. html.yfx-rr-min ${SEL.rightRailBox} > div:not(:first-of-type) { display: none !important; }
  214. html.yfx-rr-min ${SEL.rightRailBox} > div:first-of-type {
  215. flex-direction: column !important; align-items: center !important; gap: 2px !important;
  216. width: 44px !important; height: auto !important; padding: 6px 0 !important;
  217. }
  218. html.yfx-rr-min ${SEL.rightRailBox} [role="tablist"] { flex-direction: column !important; gap: 2px !important; }
  219. html.yfx-rr-min ${SEL.rightRailBox} [role="tablist"] > li { height: 34px !important; }
  220. html.yfx-rr-min ${SEL.rightRailBox} [data-test-id="popover-container"] button {
  221. font-size: 0 !important; width: 32px !important; min-width: 0 !important; padding: 0 !important; justify-content: center !important;
  222. }
  223.  
  224. /* --- folder rail --- */
  225. /* One tight line per folder: small icon, name, unread count on the right. */
  226. html.yfx-folders ${SEL.rail} [data-test-id="menu-list-item"],
  227. html.yfx-folders ${SEL.rail} [data-test-id="left-rail-Folder-icon"] {
  228. height: 22px !important; min-height: 0 !important; margin: 0 !important;
  229. padding-left: 8px !important; border-radius: 3px !important;
  230. }
  231. html.yfx-folders ${SEL.railList} { overflow-y: auto !important; padding: 0 !important; gap: 0 !important; }
  232. html.yfx-folders ${SEL.railList} > li { margin: 0 !important; min-height: 0 !important; }
  233. html.yfx-folders ${SEL.railList} > li > div:only-child:empty { margin: 3px 8px !important; }
  234. html.yfx-folders ${SEL.railList} [data-test-id="menu-list-item-link"] { gap: 6px !important; align-items: center !important; height: 22px !important; }
  235. html.yfx-folders ${SEL.railList} [data-test-id="menu-list-item-link"] > div { padding: 0 !important; }
  236. html.yfx-folders ${SEL.railList} [data-test-id="menu-list-item-link"] > span { height: 16px !important; }
  237. html.yfx-folders ${SEL.railList} svg { width: 16px !important; height: 16px !important; }
  238. /* Custom folders have no icon of their own: give them a small folder glyph. */
  239. html.yfx-folders ${SEL.railList} ${SEL.folderItem} [data-test-id="menu-list-item-link"]:not(:has(svg))::before {
  240. content: ""; flex: none; width: 16px; height: 16px; opacity: .65;
  241. background: no-repeat center / 16px url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23555' stroke-width='2' stroke-linejoin='round'%3E%3Cpath d='M3 6.5h6l2 2.5h10v10.500H3z'/%3E%3C/svg%3E");
  242. }
  243. html.yfx-folders [data-test-id="expanded-left-rail"] { gap: 6px !important; }
  244. /* Yahoo fades out the bottom of the folder list with a gradient overlay. With the compact
  245. list the last rows ("More") sit right under it and look washed out, so drop the fade. */
  246. html.yfx-folders [data-test-id="expanded-left-rail"] [data-test-id="focus-group"]::after { content: none !important; }
  247. html.yfx-folders [data-test-id="expanded-left-rail"] [data-test-id="left-rail-Compose-icon"] {
  248. height: 32px !important; min-height: 0 !important; margin-bottom: 4px !important;
  249. border-radius: 6px !important; font-size: 14px !important;
  250. }
  251. html.yfx-folders ${SEL.folderItem} ${SEL.badge} { display: none !important; }
  252. ${SEL.folderItem}[data-yfx-unread] { position: relative; }
  253. ${SEL.folderItem}[data-yfx-unread]::after {
  254. content: attr(data-yfx-unread); position: absolute; right: 8px; top: 50%; transform: translateY(-50%);
  255. font: 700 12px/1 system-ui, sans-serif; color: #5b21d6; pointer-events: none;
  256. }
  257. li[data-yfx-hidden] { display: none !important; }
  258. li[data-yfx-depth="1"] [data-test-id="menu-list-item-link"] { margin-left: 14px !important; }
  259. li[data-yfx-depth="2"] [data-test-id="menu-list-item-link"] { margin-left: 28px !important; }
  260. li[data-yfx-depth="3"] [data-test-id="menu-list-item-link"] { margin-left: 42px !important; }
  261. li[data-yfx-depth="4"] [data-test-id="menu-list-item-link"] { margin-left: 56px !important; }
  262. li[data-yfx-parent] { position: relative; }
  263. .yfx-caret {
  264. all: unset; position: absolute; left: 0; top: 0; bottom: 0; width: 16px; z-index: 2;
  265. cursor: pointer; text-align: center; font-size: 10px; line-height: 22px; color: #666;
  266. }
  267. .yfx-caret:hover { color: #000; }
  268. `;
  269.  
  270. function injectStyle() {
  271. if (document.getElementById('yfx-style')) return;
  272. const style = document.createElement('style');
  273. style.id = 'yfx-style';
  274. style.textContent = CSS;
  275. (document.head || document.documentElement).append(style);
  276. }
  277. function applyRootClasses() {
  278. const c = document.documentElement.classList;
  279. c.toggle('yfx-promo', settings.hidePromoCards);
  280. c.toggle('yfx-folders', settings.compactFolders);
  281. c.toggle('yfx-wide', settings.listWidth > 0);
  282. c.toggle('yfx-pg', settings.pagination);
  283. const st = document.documentElement.style;
  284. st.setProperty('--yfx-row-h', rowPitch() + 'px');
  285. // a page of Yahoo's tallest rows (84px), plus a quarter for ad slots
  286. st.setProperty('--yfx-list-h', Math.ceil(settings.pageSize * 1.25) * 84 + 'px');
  287. st.setProperty('--yfx-list-w', settings.listWidth + 'px');
  288. st.setProperty('--yfx-sender-w', Math.round(Math.max(110, Math.min(190, (settings.listWidth || 480) * 0.27))) + 'px');
  289. }
  290.  
  291. // ---------------------------------------------------------------- app store
  292. // Yahoo keeps folder names, paths and unread/total counts in a Redux store that is
  293. // handed to the React root. Reading it is far sturdier than scraping the rail.
  294. let store = null;
  295. function findStore() {
  296. const root = $(SEL.appRoot);
  297. if (!root) return null;
  298. const key = Object.keys(root).find(k => k.startsWith('__reactContainer$') || k.startsWith('__reactFiber$'));
  299. if (!key) return null;
  300. const stack = [root[key]];
  301. for (let n = 0; stack.length && n < 3000; n++) {
  302. const f = stack.pop();
  303. if (!f) continue;
  304. const p = f.memoizedProps;
  305. const s = p?.store ?? p?.value?.store;
  306. if (s && typeof s.getState === 'function' && typeof s.subscribe === 'function') return s;
  307. stack.push(f.sibling, f.child);
  308. }
  309. return null;
  310. }
  311. const getFolders = () => store?.getState()?.folders ?? {};
  312.  
  313. // Two of Yahoo's own Appearance settings, surfaced in our panel. Yahoo keeps them in the
  314. // store's feature map and changes them with one plain action, which also saves them.
  315. // previewpane: 0 = List, 1 = Right, 2 = Bottom snippets: Message preview on/off
  316. const yahooSetting = name => store?.getState()?.features?.[name];
  317. function setYahooSetting(name, value) {
  318. if (!store) return;
  319. store.dispatch({ type: 'SETTINGS_CHANGE_REQUESTED', name, value });
  320. schedule();
  321. }
  322.  
  323. // ---------------------------------------------------------------- right-hand panel
  324. // Yahoo records which pane (if any) is open in the right-hand panel; with none open the
  325. // panel's body is ads.
  326. const syncRightRail = guard('rightRail', () => {
  327. const rail = $(SEL.rightRail);
  328. let adsOnly = false;
  329. if (rail && settings.rightPanel > 0) {
  330. const view = yahooSetting('actionableRightRailContent');
  331. adsOnly = view ? view.currentView == null
  332. : !!rail.querySelector(`${SEL.rightRailBox} > div:last-of-type iframe`);
  333. }
  334. // Both modes apply only while the panel shows ads: if Yahoo opens a real pane in it
  335. // (contacts, starred list), the panel comes back at full size.
  336. document.documentElement.classList.toggle('yfx-rr-min', adsOnly && settings.rightPanel === 1);
  337. document.documentElement.classList.toggle('yfx-rr-none', adsOnly && settings.rightPanel === 2);
  338. rail?.parentElement?.classList.toggle('yfx-grid', true); // the page's column grid
  339. });
  340.  
  341. // Close whichever pane is open in the right-hand panel, the way a user would: by clicking
  342. // its (selected) icon again. Yahoo then goes back to showing ads there.
  343. const closeRightPane = guard('closeRightPane', () => {
  344. const tab = $(`${SEL.rightRailBox} > div:first-of-type [role="tab"][aria-selected="true"]`);
  345. if (!tab) return;
  346. (tab.querySelector('button, a, [role="button"]') ?? tab).click();
  347. setTimeout(schedule, 300);
  348. });
  349.  
  350. // ---------------------------------------------------------------- open in a new tab
  351. // Every message has its own address: the list's address plus /messages/<id>. The id is
  352. // the one Yahoo puts on the row's elements.
  353. function messageUrl(row) {
  354. const id = row?.querySelector('[id^="email-sender-"]')?.id.slice('email-sender-'.length);
  355. if (!id) return null;
  356. const base = location.pathname.replace(/\/messages\/.*$/, '').replace(/\/+$/, '');
  357. return location.origin + base + '/messages/' + encodeURIComponent(id);
  358. }
  359. function openInNewTab(row) {
  360. const url = messageUrl(row);
  361. if (url) window.open(url, '_blank', 'noopener');
  362. return !!url;
  363. }
  364. // Ctrl/Cmd+click and middle-click on a message row. Yahoo would otherwise treat these as
  365. // an ordinary click, so they are caught first; the checkbox, star and other buttons in
  366. // the row keep their normal behaviour.
  367. const isNewTabClick = ev => settings.newTabClick && !ev.shiftKey && !ev.altKey
  368. && ((ev.button === 0 && (ev.ctrlKey || ev.metaKey)) || ev.button === 1);
  369. const rowFor = ev => {
  370. const t = ev.target instanceof Element ? ev.target : null;
  371. if (!t || t.closest('button, [role="checkbox"], a[href]')) return null;
  372. const row = t.closest(SEL.row);
  373. return row && row.closest(SEL.list) ? row : null;
  374. };
  375. for (const type of ['pointerdown', 'mousedown', 'mouseup', 'pointerup']) {
  376. document.addEventListener(type, ev => {
  377. if (!isNewTabClick(ev) || !rowFor(ev)) return;
  378. ev.stopImmediatePropagation();
  379. if (ev.button === 1) ev.preventDefault(); // no middle-button autoscroll
  380. }, true);
  381. }
  382. for (const type of ['click', 'auxclick']) {
  383. document.addEventListener(type, guard('newTab', ev => {
  384. if (!isNewTabClick(ev)) return;
  385. const row = rowFor(ev);
  386. if (!row) return;
  387. ev.preventDefault();
  388. ev.stopImmediatePropagation();
  389. openInNewTab(row);
  390. }), true);
  391. }
  392.  
  393. // Right-click: add "Open in new tab" to the top of Yahoo's own message menu.
  394. const ctx = { row: null, at: 0 };
  395. document.addEventListener('contextmenu', ev => {
  396. const t = ev.target instanceof Element ? ev.target : null;
  397. const row = t?.closest(SEL.row);
  398. ctx.row = row && row.closest(SEL.list) ? row : null;
  399. ctx.at = Date.now();
  400. }, true);
  401. const syncContextMenu = guard('contextMenu', () => {
  402. if (!ctx.row || Date.now() - ctx.at > 5000) return;
  403. const menu = $('[data-test-id="popover-content"] ul[role="menu"]');
  404. const firstLi = menu?.querySelector('[role="menuitem"]')?.closest('li');
  405. if (!firstLi || menu.querySelector('.yfx-newtab')) return;
  406. const item = firstLi.cloneNode(true); // inherits Yahoo's menu styling
  407. item.classList.add('yfx-newtab');
  408. const label = 'Open in new tab';
  409. const link = item.querySelector('[role="menuitem"]');
  410. link?.setAttribute('aria-label', label);
  411. item.querySelectorAll('[title]').forEach(e => e.setAttribute('title', label));
  412. item.querySelectorAll('[data-folder-id]').forEach(e => e.removeAttribute('data-folder-id'));
  413. const text = [...item.querySelectorAll('span')].find(e => e.childElementCount === 0 && e.textContent.trim());
  414. if (text) text.textContent = label;
  415. const icon = item.querySelector('svg');
  416. if (icon) icon.innerHTML = '<path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M14 4h6v6M20 4l-9 9M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5"/>';
  417. const row = ctx.row;
  418. item.addEventListener('click', guard('newTabItem', ev => {
  419. ev.preventDefault();
  420. ev.stopImmediatePropagation();
  421. openInNewTab(row);
  422. // close Yahoo's menu the way a click elsewhere would
  423. menu.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', code: 'Escape', keyCode: 27, bubbles: true }));
  424. document.body.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
  425. document.body.click();
  426. }), true);
  427. firstLi.before(item);
  428. });
  429.  
  430. // ---------------------------------------------------------------- folders
  431. const isUserFolder = f => f?.types?.includes('USER') && !f.types.includes('INVISIBLE');
  432.  
  433. const syncFolders = guard('folders', () => {
  434. const rail = $(SEL.rail);
  435. if (!rail) return;
  436. const folders = getFolders();
  437. const paths = Object.values(folders).filter(isUserFolder).map(f => f.path);
  438. const collapsed = new Set(settings.collapsed);
  439.  
  440. for (const item of rail.querySelectorAll(SEL.folderItem)) {
  441. const f = folders[item.getAttribute('data-folder-id')];
  442. const li = item.closest('li');
  443.  
  444. // Unread count: only add ours where Yahoo's own badge is empty.
  445. const native = item.querySelector(SEL.badge)?.textContent.trim();
  446. // With the compact rail we replace Yahoo's rounded badge ("6.8K") by the exact count.
  447. const want = f && f.unread > 0 && (settings.compactFolders || !native) ? String(f.unread) : null;
  448. if (want !== item.getAttribute('data-yfx-unread')) {
  449. want ? item.setAttribute('data-yfx-unread', want) : item.removeAttribute('data-yfx-unread');
  450. }
  451.  
  452. if (!li || !isUserFolder(f)) continue;
  453. const parts = f.path.split('/');
  454. const depth = parts.length - 1;
  455. setAttr(li, 'data-yfx-depth', depth > 0 ? String(Math.min(depth, 4)) : null);
  456.  
  457. const hidden = parts.slice(0, -1).some((_, i) => collapsed.has(parts.slice(0, i + 1).join('/')));
  458. setAttr(li, 'data-yfx-hidden', hidden ? '' : null);
  459.  
  460. const hasChildren = paths.some(p => p.startsWith(f.path + '/'));
  461. setAttr(li, 'data-yfx-parent', hasChildren ? '' : null);
  462. let caret = li.querySelector(':scope > .yfx-caret');
  463. if (hasChildren) {
  464. if (!caret) {
  465. caret = document.createElement('button');
  466. caret.className = 'yfx-caret';
  467. caret.type = 'button';
  468. caret.addEventListener('click', ev => {
  469. ev.preventDefault();
  470. ev.stopPropagation();
  471. const p = caret.dataset.path;
  472. const set = new Set(settings.collapsed);
  473. set.has(p) ? set.delete(p) : set.add(p);
  474. settings.collapsed = [...set];
  475. save();
  476. syncFolders();
  477. });
  478. li.append(caret);
  479. }
  480. const isCollapsed = collapsed.has(f.path);
  481. caret.dataset.path = f.path;
  482. caret.style.marginLeft = depth * 14 + 'px';
  483. caret.textContent = isCollapsed ? '▸' : '▾';
  484. caret.setAttribute('aria-expanded', String(!isCollapsed));
  485. caret.setAttribute('aria-label', (isCollapsed ? 'Expand ' : 'Collapse ') + f.name);
  486. } else {
  487. caret?.remove();
  488. }
  489. }
  490. });
  491. // Yahoo can show the rail as an icon strip ("compact navigation"). Switch it back to the
  492. // full list of folder names using Yahoo's own toggle.
  493. let expandTriedAt = 0;
  494. const expandRail = guard('expandRail', () => {
  495. if (!settings.compactFolders) return;
  496. const btn = $(SEL.railToggle);
  497. if (!btn || btn.getAttribute('aria-expanded') !== 'false') return;
  498. if (Date.now() - expandTriedAt < 5000) return;
  499. expandTriedAt = Date.now();
  500. btn.click();
  501. });
  502. function setAttr(el, name, value) {
  503. if (value === null) { if (el.hasAttribute(name)) el.removeAttribute(name); }
  504. else if (el.getAttribute(name) !== value) el.setAttribute(name, value);
  505. }
  506.  
  507. // ---------------------------------------------------------------- pagination
  508. // Yahoo's list is virtualised: rows are absolutely positioned at slot * rowHeight inside
  509. // a scroller, and some slots hold ads instead of messages. We clip that scroller to the
  510. // slots holding one page of messages, move it a page at a time, and let its container
  511. // scroll normally within the page. Because ad slots vary, a page's starting offset is
  512. // not a fixed multiple: it is learned when the page before it is laid out, or, for a
  513. // jump, by finding that page's first message in the list (see jumpTo).
  514. const pg = {
  515. list: null, page: 0, starts: [0], end: 0, route: '', rowH: 44, mo: null, saved: null,
  516. faking: false, askedAt: 0, askedTotal: -1,
  517. jump: 0, // bumped to cancel a jump in progress
  518. locating: false, // a jump is moving the list around; leave it alone
  519. busy: false, status: '', boost: 0, listKey: null, lastMore: false, lastEmpty: false,
  520. };
  521. const FOOT = 36; // room kept under the rows for the numbered page bar
  522. const sleep = ms => new Promise(r => setTimeout(r, ms));
  523.  
  524. // While a jump is loading ahead, ask Yahoo for much bigger batches than its usual 100, by
  525. // editing the size in its own message-list request. Everything else about the request,
  526. // and how Yahoo handles the answer, is untouched.
  527. const xhrSend = XMLHttpRequest.prototype.send;
  528. XMLHttpRequest.prototype.send = function (body) {
  529. try {
  530. if (pg.boost && body instanceof FormData) {
  531. const json = body.get('batchJson');
  532. if (typeof json === 'string' && json.includes('/messages/@.select==q') && json.includes('count%3A100%20offset')) {
  533. body.set('batchJson', json.replace('count%3A100%20offset', `count%3A${pg.boost}%20offset`));
  534. }
  535. }
  536. } catch (e) { warn('boost', e); }
  537. return xhrSend.apply(this, arguments);
  538. };
  539.  
  540. function measureRowHeight(ul) {
  541. const tops = [...ul.children].slice(0, 6).map(li => parseFloat(li.style.top)).filter(Number.isFinite);
  542. for (let i = 1; i < tops.length; i++) {
  543. const d = tops[i] - tops[i - 1];
  544. if (d > 10) return d;
  545. }
  546. return pg.rowH;
  547. }
  548.  
  549. function attachList(list) {
  550. detachList();
  551. pg.list = list;
  552. // Coming back from an open message returns to the page it was opened from.
  553. const returning = pg.saved?.route === location.pathname && pg.route.startsWith(location.pathname + '/');
  554. pg.page = returning ? pg.saved.page : 0;
  555. pg.starts = returning ? [...pg.saved.starts] : [0];
  556. pg.jump++;
  557. pg.locating = false;
  558. pg.listKey = null;
  559. setBusy(false);
  560. list.addEventListener('scroll', onListScroll, { passive: true });
  561. const ul = list.firstElementChild;
  562. if (ul) {
  563. // Rows are recycled and ads fill in late, so watch the whole list.
  564. pg.mo = new MutationObserver(() => {
  565. if (pg.pending) return;
  566. pg.pending = true;
  567. setTimeout(() => { pg.pending = false; layoutPage(); }, 0);
  568. });
  569. pg.mo.observe(ul, { childList: true, subtree: true, attributes: true, attributeFilter: ['style'] });
  570. }
  571. layoutPage();
  572. }
  573. function detachList() {
  574. const list = pg.list;
  575. if (!list) return;
  576. list.removeEventListener('scroll', onListScroll);
  577. pg.mo?.disconnect();
  578. pg.mo = null;
  579. list.classList.remove('yfx-paged');
  580. list.style.removeProperty('height');
  581. list.style.removeProperty('zoom');
  582. for (const li of list.firstElementChild?.children ?? []) clearShift(li);
  583. list.closest(SEL.listContainer)?.classList.remove('yfx-scroller');
  584. list.parentElement?.classList.remove('yfx-clip');
  585. list.parentElement?.style.removeProperty('height');
  586. list.classList.remove('yfx-busy');
  587. document.getElementById('yfx-pages')?.remove();
  588. document.documentElement.classList.remove('yfx-1line', 'yfx-2line');
  589. pg.list = null;
  590. }
  591.  
  592. const onListScroll = guard('scroll', () => {
  593. if (!pg.list || pg.faking || pg.locating) return;
  594. // The app moved the list itself (keyboard navigation, jump to a message):
  595. // follow it to the neighbouring page instead of fighting it.
  596. const start = pg.starts[pg.page] ?? 0;
  597. const st = pg.list.scrollTop;
  598. if (Math.abs(st - start) <= 1.5) return;
  599. if (st >= pg.end - 1.5 && pg.starts[pg.page + 1] !== undefined) pg.page++;
  600. else if (st < start && pg.page > 0) pg.page--;
  601. layoutPage();
  602. });
  603.  
  604. const layoutPage = guard('pagination', () => {
  605. const list = pg.list;
  606. if (!list?.isConnected || pg.locating) return;
  607. const ul = list.firstElementChild;
  608. if (!ul) return;
  609. pg.rowH = measureRowHeight(ul);
  610. const total = parseFloat(ul.style.height) || ul.scrollHeight;
  611. if (pg.starts[pg.page] === undefined) { pg.page = 0; pg.starts = [0]; }
  612. const start = pg.starts[pg.page];
  613. const more = currentList()?.hasMoreItems === true;
  614.  
  615. // Tall multi-line rows mean a reading-pane layout: there we draw each message on one
  616. // line at our own pitch. Yahoo's single-line List layout is only zoomed.
  617. // Is Yahoo's Message preview off? Ask the store; failing that, look at the rows, which
  618. // carry no preview element at all when it is.
  619. const snippets = yahooSetting('snippets');
  620. noPreview = typeof snippets === 'boolean' ? !snippets
  621. : ul.querySelectorAll(MESSAGE).length >= 5 && !ul.querySelector('[id^="email-snippet-"]');
  622. const oneLine = settings.rowLines > 0 && pg.rowH > 50; // "our own rows", one or two lines
  623. document.documentElement.classList.toggle('yfx-1line', oneLine);
  624. document.documentElement.classList.toggle('yfx-2line', oneLine && rowLines() === 2);
  625. const pitch = oneLine ? rowPitch() : pg.rowH;
  626. const pitchPx = rowPitch() + 'px';
  627. if (document.documentElement.style.getPropertyValue('--yfx-row-h') !== pitchPx) {
  628. document.documentElement.style.setProperty('--yfx-row-h', pitchPx);
  629. }
  630. const zoom = oneLine ? 1 : settings.density;
  631.  
  632. const built = buildPage(ul, start, total, more, pitch);
  633. pg.end = built.end;
  634. // The user asked for two-line rows but is getting one line: say why, in the toolbar.
  635. pg.previewOff = oneLine && settings.rowLines === 2 && noPreview;
  636. if (built.complete && built.end < total - 0.5) pg.starts[pg.page + 1] = built.end;
  637. else delete pg.starts[pg.page + 1];
  638.  
  639. // If the page is short only because rows further down are not rendered yet, give the
  640. // list a little more room so Yahoo renders them; the next pass trims it again.
  641. const room = !built.complete && built.end < total - 0.5 ? 8 * pg.rowH : 0;
  642.  
  643. // The list keeps the height Yahoo expects for these slots (so it renders them all);
  644. // its parent clips that down to the rows as we have actually drawn them.
  645. const span = Math.max(pg.rowH, built.end - start + room);
  646. const shown = Math.max(pitch, built.visual + room) * zoom + FOOT;
  647. const clip = list.parentElement;
  648. list.classList.add('yfx-paged');
  649. clip.classList.add('yfx-clip');
  650. list.closest(SEL.listContainer)?.classList.add('yfx-scroller');
  651. if (list.style.height !== span + 'px') list.style.setProperty('height', span + 'px', 'important');
  652. if (clip.style.height !== shown + 'px') clip.style.setProperty('height', shown + 'px', 'important');
  653. if (list.style.zoom !== String(zoom)) list.style.zoom = String(zoom);
  654. if (!pg.faking && Math.abs(list.scrollTop - start) > 1.5) list.scrollTop = start;
  655.  
  656. // Keep about a page ahead loaded so "Next" is ready and pages are never half empty.
  657. if (more && total < built.end + settings.pageSize * pg.rowH * 1.3) {
  658. const now = Date.now();
  659. if (pg.askedTotal !== total || now - pg.askedAt > 4000) {
  660. pg.askedTotal = total;
  661. pg.askedAt = now;
  662. requestMore(list);
  663. }
  664. }
  665. pg.saved = { route: location.pathname, page: pg.page, starts: [...pg.starts] };
  666. pg.lastMore = more;
  667. pg.lastEmpty = built.count === 0 && !more;
  668. renderPager();
  669. });
  670.  
  671. // Ad rows keep their slot in the list even when an ad blocker empties them. Within the
  672. // visible page, hide those rows and slide the following messages up. Returns the height
  673. // reclaimed so the page can be shortened to match.
  674. const MESSAGE = '[data-test-id="message-list-item"]';
  675. function isGapRow(li) {
  676. if (li.querySelector(MESSAGE)) return false;
  677. if (li.childElementCount === 0) return true; // emptied by a blocker
  678. if ([...li.children].every(c => c.offsetHeight === 0)) return true; // hidden by a cosmetic filter
  679. if (!settings.collapseAdRows) return false;
  680. return hasAdLabel(li); // Yahoo's own "Ad" label
  681. }
  682. function clearShift(li) {
  683. if (li.style.transform) li.style.transform = '';
  684. if (li.style.visibility) li.style.visibility = '';
  685. }
  686. function hasAdLabel(li) {
  687. for (const el of li.querySelectorAll('span, div')) {
  688. if (el.childElementCount === 0 && /^(Ad|Sponsored)$/.test(el.textContent.trim())) return true;
  689. }
  690. return false;
  691. }
  692. // Lay out the page that begins at slot offset `start`: walk the rendered rows in order,
  693. // hide ad gaps, and move every remaining row to its place in a gap-free column where a
  694. // message takes `pitch` px. Stops once the page holds pageSize messages. Returns where
  695. // the page ends in Yahoo's coordinates, the height of the column as drawn, the number of
  696. // messages, and whether that boundary is final (false while rows are still loading).
  697. function buildPage(ul, start, total, more, pitch) {
  698. const rows = [];
  699. for (const li of ul.children) {
  700. const top = parseFloat(li.style.top);
  701. if (top >= start - 0.5) rows.push([top, li]);
  702. else clearShift(li);
  703. }
  704. rows.sort((a, b) => a[0] - b[0]);
  705. const size = settings.pageSize;
  706. let y = 0, count = 0, end = start, pending = false, full = false;
  707. for (const [top, li] of rows) {
  708. if (full || top > end + 0.5) { clearShift(li); continue; } // past the page, or a hole
  709. const isMessage = !!li.querySelector(MESSAGE);
  710. if (!isMessage && isGapRow(li)) {
  711. if (li.style.visibility !== 'hidden') li.style.visibility = 'hidden';
  712. } else {
  713. const dy = y - (top - start);
  714. const want = Math.abs(dy) > 0.01 ? `translateY(${dy}px)` : '';
  715. if (li.style.transform !== want) li.style.transform = want;
  716. if (li.style.visibility) li.style.visibility = '';
  717. y += isMessage ? pitch : pg.rowH;
  718. if (isMessage) count++;
  719. else if (!hasAdLabel(li)) { count++; pending = true; } // loading placeholder or footer
  720. }
  721. end = Math.min(total, top + pg.rowH);
  722. if (count >= size) full = true;
  723. }
  724. const atEnd = end >= total - 0.5 && !more;
  725. if (atEnd) end = total;
  726. return { end, visual: y, count, complete: (full && !pending) || atEnd };
  727. }
  728.  
  729. // Yahoo fetches the next batch of messages when its list is scrolled near the end. Our
  730. // clipped list never scrolls, so report an end-of-list position for one scroll event,
  731. // then let the list re-read its real position.
  732. const scrollTopProp = Object.getOwnPropertyDescriptor(Element.prototype, 'scrollTop');
  733. function requestMore(list) {
  734. if (pg.faking || !scrollTopProp) return;
  735. pg.faking = true;
  736. Object.defineProperty(list, 'scrollTop', {
  737. configurable: true,
  738. get: () => list.scrollHeight,
  739. set: v => scrollTopProp.set.call(list, v),
  740. });
  741. // Restore the real position in the same tick, before anything is painted: holding the
  742. // fake one any longer makes Yahoo render the rows at the bottom instead of this page.
  743. try {
  744. list.dispatchEvent(new Event('scroll', { bubbles: true }));
  745. } finally {
  746. delete list.scrollTop;
  747. pg.faking = false;
  748. }
  749. list.dispatchEvent(new Event('scroll', { bubbles: true }));
  750. }
  751.  
  752. // Go to page n (0-based; Infinity = the last page). A page whose start is already known
  753. // is shown at once; any other page is reached by a jump.
  754. function gotoPage(n) {
  755. n = Math.max(0, n);
  756. pg.jump++; // cancels a jump in progress
  757. if (pg.starts[n] === undefined) { jumpTo(n); return; }
  758. pg.locating = false;
  759. pg.boost = 0;
  760. setBusy(false);
  761. pg.page = n;
  762. layoutPage();
  763. pg.list?.closest(SEL.listContainer)?.scrollTo({ top: 0 });
  764. }
  765.  
  766. function setBusy(busy, status = '') {
  767. pg.busy = busy;
  768. pg.status = busy ? status : '';
  769. pg.list?.classList.toggle('yfx-busy', busy);
  770. if (pager?.isConnected) renderPager();
  771. }
  772.  
  773. // Jump straight to a page: load ahead until its first message has arrived (in big
  774. // batches), find where that message sits in Yahoo's list, and start the page there.
  775. const jumpTo = async n => {
  776. const token = pg.jump, list = pg.list, size = settings.pageSize;
  777. if (!list) return;
  778. const live = () => token === pg.jump && list === pg.list && list.isConnected;
  779. let page = null, top = null;
  780. try {
  781. setBusy(true, 'Loading…');
  782. pg.boost = 1000;
  783. for (let fails = 0; live() && fails < 3;) {
  784. const l = currentList();
  785. if (!l) { await sleep(200); fails++; continue; }
  786. if (!l.hasMoreItems || l.itemIds.length > n * size) break;
  787. const total = knownTotal(), have = l.itemIds.length;
  788. setBusy(true, `Loading ${have.toLocaleString()}${total ? ' of ' + total.toLocaleString() : ''}…`);
  789. requestMore(list);
  790. for (let t = Date.now(); live() && (currentList()?.itemIds.length ?? have) === have && Date.now() - t < 20000;) await sleep(80);
  791. fails = (currentList()?.itemIds.length ?? have) === have ? fails + 1 : 0;
  792. }
  793. pg.boost = 0;
  794. const l = currentList();
  795. if (!live() || !l) return;
  796. page = Math.min(n, Math.max(0, Math.ceil(l.itemIds.length / size) - 1));
  797. setBusy(true, `Opening page ${(page + 1).toLocaleString()}…`);
  798. top = page === 0 ? 0 : await locate(l.itemIds[page * size], page * size, live);
  799. } catch (e) {
  800. warn('jump', e);
  801. } finally {
  802. if (token === pg.jump) {
  803. pg.boost = 0;
  804. pg.locating = false;
  805. if (top !== null && page !== null) { pg.starts[page] = top; pg.page = page; }
  806. setBusy(false);
  807. layoutPage();
  808. pg.list?.closest(SEL.listContainer)?.scrollTo({ top: 0 });
  809. }
  810. }
  811. };
  812.  
  813. // Find the slot offset of a message in Yahoo's list. Only rows near the scroll position
  814. // exist, so scroll to an estimate, look, and correct the estimate from whichever
  815. // messages did get rendered there.
  816. async function locate(id, index, live) {
  817. const list = pg.list, ul = list.firstElementChild;
  818. pg.locating = true;
  819. let guess = index * pg.rowH * 1.1;
  820. for (let attempt = 0; attempt < 8 && live(); attempt++) {
  821. const max = Math.max(0, list.scrollHeight - list.clientHeight);
  822. list.scrollTop = Math.max(0, Math.min(guess - 10 * pg.rowH, max));
  823. for (let w = 0; w < 30 && live(); w++) {
  824. await sleep(60);
  825. if (document.getElementById('email-sender-' + id)) break;
  826. }
  827. const li = document.getElementById('email-sender-' + id)?.closest('li');
  828. if (li && li.parentElement === ul) return parseFloat(li.style.top);
  829. const ids = currentList()?.itemIds ?? [];
  830. let best = null;
  831. for (const el of ul.querySelectorAll('[id^="email-sender-"]')) {
  832. const j = ids.indexOf(el.id.slice('email-sender-'.length));
  833. const t = parseFloat(el.closest('li')?.style.top);
  834. if (j >= 0 && Number.isFinite(t) && (!best || Math.abs(j - index) < Math.abs(best.j - index))) best = { j, t };
  835. }
  836. if (best) guess = best.t + (index - best.j) * (best.j > 0 ? best.t / best.j : pg.rowH * 1.1);
  837. }
  838. return null;
  839. }
  840.  
  841. // How many pages the open list has: exact once everything is loaded, otherwise estimated
  842. // from the folder's message count, otherwise unknown (null).
  843. function pageCount() {
  844. const l = currentList(), size = settings.pageSize;
  845. if (l && !l.hasMoreItems) return { n: Math.max(1, Math.ceil(l.itemIds.length / size)), exact: true };
  846. const total = knownTotal();
  847. return total !== null ? { n: Math.max(1, Math.ceil(total / size)), exact: false } : { n: null, exact: false };
  848. }
  849.  
  850. // Total messages in the open folder, when the store can tell us reliably.
  851. function knownTotal() {
  852. const folders = getFolders();
  853. const id = location.pathname.match(/\/folders\/([^/]+)/)?.[1];
  854. const f = id ? folders[id]
  855. : /\/inbox(\/|$)/.test(location.pathname) ? Object.values(folders).find(x => x.types?.includes('INBOX'))
  856. : null;
  857. if (!f || typeof f.total !== 'number') return null;
  858. const tab = $(`${SEL.inboxTabs} [role="tab"][aria-selected="true"]`);
  859. if (tab && tab.getAttribute('data-category') !== 'all') return null; // tab shows a subset
  860. if (/\/search\//.test(location.pathname)) return null;
  861. return f.total;
  862. }
  863.  
  864. // The store's record of the list on screen. It is identified by a rendered message id
  865. // and remembered by key, since during a jump there may briefly be no rendered rows. Yahoo
  866. // can hold several lists that begin with the same messages (an early short copy next to
  867. // the live one), so of those containing the message, the longest is the one on screen.
  868. function currentList() {
  869. const lists = store?.getState()?.lists;
  870. if (!lists) return null;
  871. const id = pg.list?.querySelector('[id^="email-sender-"]')?.id.slice('email-sender-'.length);
  872. if (id) {
  873. let best = null;
  874. for (const k of Object.keys(lists)) {
  875. const ids = lists[k].itemIds;
  876. if (ids?.includes(id) && (!best || ids.length > lists[best].itemIds.length)) best = k;
  877. }
  878. if (best) pg.listKey = best;
  879. }
  880. return lists[pg.listKey] ?? null;
  881. }
  882.  
  883. let pager = null;
  884. function renderPager() {
  885. const more = pg.lastMore, empty = pg.lastEmpty;
  886. const main = $(SEL.main);
  887. if (!main) return;
  888. if (!pager || !pager.isConnected) {
  889. pager = document.createElement('div');
  890. pager.id = 'yfx-pager';
  891. pager.innerHTML = `
  892. <span id="yfx-hint" role="status" hidden>Two-line rows need previews ·
  893. <a data-act="enable-preview" title="Subject + preview rows show Yahoo's message preview on the second line. It is off, so rows are shown on one line. Click to turn Yahoo's Message preview on.">turn on Message preview</a>
  894. <button type="button" data-act="hint-close" aria-label="Dismiss" title="Dismiss">×</button></span>
  895. <button type="button" data-act="first" aria-label="First page" title="First page">«</button>
  896. <button type="button" data-act="prev" aria-label="Previous page" title="Previous page">‹</button>
  897. <span class="yfx-range" aria-live="polite"></span>
  898. <button type="button" data-act="next" aria-label="Next page" title="Next page">›</button>
  899. <button type="button" data-act="last" aria-label="Last page" title="Last page">»</button>
  900. <button type="button" data-act="cfg" aria-label="Yahoo Mail Comfort settings" title="Yahoo Mail Comfort settings">⚙</button>`;
  901. pager.addEventListener('click', guard('pager', ev => {
  902. const act = ev.target.closest('button, a')?.dataset.act;
  903. if (act === 'first') gotoPage(0);
  904. else if (act === 'prev') gotoPage(pg.page - 1);
  905. else if (act === 'next') gotoPage(pg.page + 1);
  906. else if (act === 'last') gotoPage(Infinity);
  907. else if (act === 'cfg') togglePanel();
  908. else if (act === 'hint-close') { settings.hintDismissed = true; save(); layoutPage(); }
  909. else if (act === 'enable-preview') { setYahooSetting('snippets', true); refreshPanelSoon(); }
  910. }));
  911. main.append(pager);
  912. }
  913. const hasNext = pg.starts[pg.page + 1] !== undefined;
  914. const total = knownTotal();
  915. const n = pg.page + 1;
  916. const count = pageCount();
  917. const atEnd = !hasNext && !more;
  918. const label = pg.status ? pg.status
  919. : empty ? 'No messages'
  920. : atEnd ? `Page ${n} of ${n}`
  921. : count.n !== null ? `Page ${n} of ${count.exact ? '' : '~'}${Math.max(n, count.n).toLocaleString()}`
  922. : `Page ${n}`;
  923. const range = pager.querySelector('.yfx-range');
  924. if (range.textContent !== label) range.textContent = label;
  925. range.title = total !== null ? `${total.toLocaleString()} messages in this folder` : '';
  926. pager.querySelector('[data-act="first"]').disabled = pg.page === 0 && !pg.busy;
  927. pager.querySelector('[data-act="prev"]').disabled = pg.page === 0;
  928. pager.querySelector('[data-act="next"]').disabled = !hasNext;
  929. pager.querySelector('[data-act="last"]').disabled = atEnd && !pg.busy;
  930. pager.querySelector('#yfx-hint').hidden = !(pg.previewOff && !settings.hintDismissed);
  931. renderPageBar(n, atEnd ? n : count.n, empty);
  932. }
  933.  
  934. // Which page numbers to offer: the first few, the ones around the current page, and the
  935. // last two, with gaps marked. `count` is null when the number of pages is unknown.
  936. function pageNumbers(cur, count) {
  937. const want = new Set([1, 2, cur - 2, cur - 1, cur, cur + 1, cur + 2]);
  938. if (cur <= 3) { want.add(3); want.add(4); want.add(5); }
  939. if (count) { want.add(count - 1); want.add(count); }
  940. const top = count ?? cur + 2;
  941. const nums = [...want].filter(p => p >= 1 && p <= top).sort((a, b) => a - b);
  942. const out = [];
  943. for (let i = 0; i < nums.length; i++) {
  944. if (i && nums[i] !== nums[i - 1] + 1) out.push(null);
  945. out.push(nums[i]);
  946. }
  947. if (!count) out.push(null); // more pages, number unknown
  948. return out;
  949. }
  950.  
  951. let pageBarKey = '';
  952. function renderPageBar(cur, count, empty) {
  953. const scroller = pg.list?.closest(SEL.listContainer);
  954. // The fixed frame around the scrolling list: the bar sits at its bottom edge.
  955. const frame = scroller?.parentElement?.closest(SEL.listContainer) ?? scroller?.parentElement;
  956. let bar = document.getElementById('yfx-pages');
  957. if (!frame || empty) { bar?.remove(); pageBarKey = ''; return; }
  958. if (!bar || bar.parentElement !== frame) {
  959. bar?.remove();
  960. bar = document.createElement('nav');
  961. bar.id = 'yfx-pages';
  962. bar.setAttribute('aria-label', 'Pages');
  963. bar.addEventListener('click', guard('pages', ev => {
  964. const b = ev.target.closest('button');
  965. if (!b || b.hasAttribute('aria-current')) return;
  966. if (b.dataset.page) gotoPage(Number(b.dataset.page) - 1);
  967. else if (b.dataset.act === 'prev') gotoPage(pg.page - 1);
  968. else if (b.dataset.act === 'next') gotoPage(pg.page + 1);
  969. else if (b.dataset.act === 'last') gotoPage(Infinity);
  970. }));
  971. frame.append(bar);
  972. pageBarKey = '';
  973. }
  974. const nums = pageNumbers(cur, count);
  975. const lastKnown = count !== null && cur >= count;
  976. const key = nums.join(',') + '|' + cur + '|' + lastKnown + '|' + pg.busy;
  977. if (key === pageBarKey) return;
  978. pageBarKey = key;
  979. bar.innerHTML = `<button type="button" class="yfx-nav" data-act="prev" aria-label="Previous page" title="Previous page"${cur === 1 ? ' disabled' : ''}>‹</button>`
  980. + nums.map(p => p === null ? '<span class="yfx-gap">…</span>'
  981. : `<button type="button" data-page="${p}"${p === cur ? ' aria-current="page"' : ''} aria-label="Page ${p}">${p.toLocaleString()}</button>`).join('')
  982. + `<button type="button" class="yfx-nav" data-act="next" aria-label="Next page" title="Next page"${lastKnown ? ' disabled' : ''}>›</button>`
  983. + `<button type="button" class="yfx-nav" data-act="last" aria-label="Last page" title="Last page"${lastKnown ? ' disabled' : ''}>»</button>`;
  984. }
  985.  
  986. // ---------------------------------------------------------------- settings panel
  987. function togglePanel() {
  988. const open = document.getElementById('yfx-panel');
  989. if (open) { open.remove(); return; }
  990. const panel = document.createElement('div');
  991. panel.id = 'yfx-panel';
  992. const opt = (v, label, cur, disabled) => `<option value="${v}"${String(v) === String(cur) ? ' selected' : ''}${disabled ? ' disabled' : ''}>${label}</option>`;
  993. // Some options only act in one of Yahoo's layouts; grey out the ones that do nothing now.
  994. const tall = pg.rowH > 50; // Yahoo's multi-line rows (Right layout)
  995. const layout = yahooSetting('previewpane');
  996. const preview = yahooSetting('snippets');
  997. const known = v => v !== undefined;
  998. const oneLine = tall && settings.rowLines > 0;
  999. const off = on => on ? '' : ' class="yfx-off"';
  1000. const dis = on => on ? '' : ' disabled';
  1001. panel.innerHTML = `
  1002. <div class="yfx-note">Yahoo's own settings</div>
  1003. <label${off(known(layout))}>Message layout <select data-y="previewpane"${dis(known(layout))}>${opt(0, 'List', layout)}${opt(1, 'Right', layout)}${opt(2, 'Bottom', layout)}</select></label>
  1004. <label${off(known(preview))}>Message preview <input type="checkbox" data-y="snippets"${preview ? ' checked' : ''}${dis(known(preview))}></label>
  1005. <div class="yfx-note">Everywhere</div>
  1006. <label>Messages per page <select data-k="pageSize">${[25, 50, 100, 200].map(n => opt(n, n, settings.pageSize)).join('')}</select></label>
  1007. <div class="yfx-note">With the Right layout</div>
  1008. <label${off(tall)}>Rows <select data-k="rowLines"${dis(tall)}>${opt(1, 'One line', rowLines())}${opt(2, noPreview ? 'Subject + preview (unavailable)' : 'Subject + preview', rowLines(), noPreview)}${opt(0, "Yahoo's own", rowLines())}</select></label>
  1009. ${tall && noPreview ? '<div class="yfx-warn">Subject + preview needs Yahoo\'s Message preview, which is off. <a data-act="enable-preview" style="text-decoration:underline;cursor:pointer;font-weight:600">Turn it on</a>.</div>' : ''}
  1010. <label${off(oneLine)}>Row height <select data-k="rowHeight"${dis(oneLine)}>${[26, 30, 34, 40].map(n => opt(n, n + ' px', settings.rowHeight)).join('')}</select></label>
  1011. <label${off(oneLine)}>List width <select data-k="listWidth"${dis(oneLine)}>${opt(0, "Yahoo's own", settings.listWidth)}${[420, 480, 530, 600, 700].map(n => opt(n, n + ' px', settings.listWidth)).join('')}</select></label>
  1012. <div class="yfx-note">With Yahoo's own rows (List or Bottom layout)</div>
  1013. <label${off(!oneLine)}>Row density <select data-k="density"${dis(!oneLine)}>
  1014. ${opt(1, 'Yahoo default', settings.density)}${opt(0.92, 'Cosy', settings.density)}
  1015. ${opt(0.85, 'Compact', settings.density)}${opt(0.75, 'Dense', settings.density)}</select></label>
  1016. <div class="yfx-note">Extras</div>
  1017. <label>Compact folder list <input type="checkbox" data-k="compactFolders"${settings.compactFolders ? ' checked' : ''}></label>
  1018. <label>Hide promo cards <input type="checkbox" data-k="hidePromoCards"${settings.hidePromoCards ? ' checked' : ''}></label>
  1019. <label title="Hold Ctrl (Cmd on Mac) and click a message, or middle-click it. Right-click also offers Open in new tab.">Ctrl+click opens in new tab <input type="checkbox" data-k="newTabClick"${settings.newTabClick ? ' checked' : ''}></label>
  1020. <label>Collapse ad rows <input type="checkbox" data-k="collapseAdRows"${settings.collapseAdRows ? ' checked' : ''}></label>
  1021. <label title="Applies while the panel shows only ads. Hidden also removes its Calendar and Contacts icons.">Right-hand ad panel <select data-k="rightPanel">${opt(1, 'Icons only', settings.rightPanel)}${opt(2, 'Hidden', settings.rightPanel)}${opt(0, 'Show', settings.rightPanel)}</select></label>
  1022. ${settings.rightPanel === 2 ? '<div class="yfx-note">Hidden also removes the Calendar and Contacts icons. Choose "Icons only" to get them back.</div>' : ''}`;
  1023. panel.addEventListener('change', guard('settings', ev => {
  1024. const el = ev.target, k = el.dataset.k;
  1025. if (el.dataset.y) { // one of Yahoo's settings: Yahoo applies and saves it
  1026. setYahooSetting(el.dataset.y, el.type === 'checkbox' ? el.checked : Number(el.value));
  1027. refreshPanelSoon();
  1028. return;
  1029. }
  1030. if (!k) return;
  1031. settings[k] = el.type === 'checkbox' ? el.checked : Number(el.value);
  1032. save();
  1033. applyRootClasses();
  1034. // Icons only / Hidden act while the panel shows ads; if a pane (contacts, starred)
  1035. // is open when one of them is chosen, close it so the choice takes effect at once.
  1036. if (k === 'rightPanel' && settings.rightPanel > 0) closeRightPane();
  1037. syncRightRail();
  1038. if (k === 'pageSize' || k === 'collapseAdRows') { pg.jump++; pg.locating = false; setBusy(false); pg.page = 0; pg.starts = [0]; }
  1039. if (k === 'rowLines') settings.hintDismissed = false;
  1040. layoutPage();
  1041. if (k === 'rowLines' || k === 'rightPanel') { panel.remove(); togglePanel(); } // refresh notes and which options apply
  1042. }));
  1043. pager.append(panel);
  1044. }
  1045. // Changing a Yahoo setting can rebuild the message list (and our pager with it). Once that
  1046. // has settled, redraw the panel so it shows the new state and which options now apply.
  1047. function refreshPanelSoon() {
  1048. if (!document.getElementById('yfx-panel')) return;
  1049. setTimeout(() => {
  1050. document.getElementById('yfx-panel')?.remove();
  1051. layoutPage();
  1052. if (pager?.isConnected) togglePanel();
  1053. }, 1200);
  1054. }
  1055. document.addEventListener('click', ev => {
  1056. const panel = document.getElementById('yfx-panel');
  1057. if (panel && !ev.target.closest('#yfx-pager')) panel.remove();
  1058. }, true);
  1059.  
  1060. // ---------------------------------------------------------------- wiring
  1061. let scheduled = false;
  1062. const tick = guard('tick', () => {
  1063. scheduled = false;
  1064. injectStyle();
  1065. if (!store) {
  1066. store = findStore();
  1067. if (store) store.subscribe(schedule);
  1068. }
  1069. syncFolders();
  1070. expandRail();
  1071. syncRightRail();
  1072. syncContextMenu();
  1073.  
  1074. if (!settings.pagination) { detachList(); pager?.remove(); return; }
  1075. if (pg.busy) { pg.route = location.pathname; return; } // a jump is rearranging the list
  1076. const list = $(`${SEL.main} ${SEL.list}`);
  1077. const route = location.pathname;
  1078. if (list !== pg.list) {
  1079. list ? attachList(list) : (detachList(), pager?.remove());
  1080. } else if (list && route !== pg.route) {
  1081. pg.jump++;
  1082. pg.locating = false;
  1083. pg.listKey = null;
  1084. setBusy(false);
  1085. pg.page = 0;
  1086. pg.starts = [0];
  1087. layoutPage();
  1088. }
  1089. pg.route = route;
  1090. });
  1091. function schedule() {
  1092. if (scheduled) return;
  1093. scheduled = true;
  1094. setTimeout(tick, 30); // not requestAnimationFrame: that never fires in a background tab
  1095. }
  1096.  
  1097. // At document-start the page may not have its <html> element yet (Chrome in particular),
  1098. // and everything below hangs off it, so wait for it to appear.
  1099. function boot() {
  1100. if (!document.documentElement) {
  1101. new MutationObserver((_, obs) => {
  1102. if (document.documentElement) { obs.disconnect(); boot(); }
  1103. }).observe(document, { childList: true });
  1104. return;
  1105. }
  1106. injectStyle();
  1107. applyRootClasses();
  1108. new MutationObserver(schedule).observe(document.documentElement, { childList: true, subtree: true });
  1109. document.addEventListener('DOMContentLoaded', schedule);
  1110. schedule();
  1111. }
  1112. boot();
  1113.  
  1114. // Small hook for debugging from the console.
  1115. window.__yfx = { settings, save, gotoPage, layoutPage, get store() { return store; } };
  1116. })();
  1117.  
Add Comment
Please, Sign In to add comment