Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ==UserScript==
- // @name Yahoo Mail Comfort
- // @namespace yahoo-fix
- // @version 20261114_0.8.0
- // @author DarkAuditor
- // @description Pagination instead of infinite scroll, denser rows and a compact, always-visible folder list for the new Yahoo Mail.
- // @match https://mail.yahoo.com/*
- // @run-at document-start
- // @grant none
- // ==/UserScript==
- (() => {
- 'use strict';
- if (window.__yfxLoaded) return;
- window.__yfxLoaded = true;
- // ---------------------------------------------------------------- settings
- const DEFAULTS = {
- pagination: true,
- pageSize: 50,
- density: 0.85, // CSS zoom applied to the message list (1 = Yahoo default)
- rowLines: 1, // with a reading pane: 1 = one line, 2 = subject over preview, 0 = Yahoo's rows
- rowHeight: 30, // height of a one-line row, px (two-line rows add LINE2 to it)
- listWidth: 530, // width of the list beside the reading pane, px (0 = Yahoo's own)
- compactFolders: true,
- hidePromoCards: true,
- collapseAdRows: true, // close the gaps left by ad rows inside the message list
- rightPanel: 1, // right-hand panel while it only shows ads: 0 = leave it, 1 = icon strip, 2 = hidden
- newTabClick: true, // Ctrl/Cmd+click and middle-click open a message in a new tab
- hintDismissed: false, // the "previews are off" notice was closed by the user
- collapsed: [], // folder paths whose children are hidden
- };
- const KEY = 'yfx.settings';
- const settings = { ...DEFAULTS };
- try { Object.assign(settings, JSON.parse(localStorage.getItem(KEY) || '{}')); } catch { /* keep defaults */ }
- if (settings.singleLine === false && !/"rowLines"/.test(localStorage.getItem(KEY) || '')) settings.rowLines = 0;
- delete settings.singleLine; // replaced by rowLines in 0.4.0
- if (settings.hideRightAds === false && !/"rightPanel"/.test(localStorage.getItem(KEY) || '')) settings.rightPanel = 0;
- delete settings.hideRightAds; // replaced by rightPanel in 0.6.1
- const LINE2 = 18; // extra height the preview line adds to a row
- // Two-line rows need Yahoo's "Message preview"; while that is off they fall back to one
- // line. The saved choice is kept, so they return as soon as previews are back on.
- let noPreview = false;
- const rowLines = () => (settings.rowLines === 2 && noPreview ? 1 : settings.rowLines);
- const rowPitch = () => settings.rowHeight + (rowLines() === 2 ? LINE2 : 0);
- const save = () => { try { localStorage.setItem(KEY, JSON.stringify(settings)); } catch { /* private mode */ } };
- // Every selector that depends on Yahoo's markup lives here.
- const SEL = {
- appRoot: '#mail-app-container',
- main: '[data-test-id="novation-main-content"]',
- toolbar: '[data-test-id="message-list-toolbar"]',
- list: '[data-test-id="virtual-list"]',
- listContainer: '[data-test-id="virtual-list-container"]',
- listPane: '[data-test-id="resizable-view-left-pane"]',
- row: '[data-test-id="message-list-item"]',
- rail: '[data-test-id="novation-left-rail"]',
- railList: '[data-test-id="navigable-list"]',
- railToggle: '[data-test-id="toggle-divider-button"]',
- folderItem: '[data-test-id="menu-list-item"][data-folder-id]',
- badge: '[data-test-id="badge"]',
- inboxTabs: '[data-test-id="inbox-tabs-list"]',
- promoCard: '[data-test-id="tldr-inbox-list-opt-in-card"]',
- rightRail: '[data-test-id="novation-right-rail"]',
- rightRailBox: '#right-rail-container',
- };
- const warn = (...a) => console.warn('[Yahoo Mail Comfort]', ...a);
- const guard = (name, fn) => (...a) => { try { return fn(...a); } catch (e) { warn(name, e); } };
- const $ = (s, root = document) => root.querySelector(s);
- // ---------------------------------------------------------------- styles
- const CSS = `
- html.yfx-promo ${SEL.promoCard} { display: none !important; }
- /* --- pagination --- */
- /* Yahoo decides how many rows to draw from the list's height at the moment it creates the
- list, and does not look again. So the list must be a full page tall from the very start,
- in the stylesheet; setting it from script afterwards is too late for a folder Yahoo
- already has in memory. (The per-page height set later, inline, overrides this.) */
- html.yfx-pg ${SEL.main} ${SEL.list} { height: var(--yfx-list-h) !important; flex: none !important; }
- .yfx-paged { flex: none !important; overflow: hidden !important; }
- .yfx-scroller { overflow-y: auto !important; overflow-x: hidden !important; }
- ${SEL.main} { position: relative; }
- #yfx-pager {
- position: absolute; top: 6px; right: 56px; z-index: 5;
- display: flex; align-items: center; gap: 4px;
- font: 13px/1 system-ui, sans-serif; color: #444; background: inherit;
- }
- #yfx-pager button {
- all: unset; cursor: pointer; min-width: 26px; height: 30px; text-align: center;
- border-radius: 4px; font-size: 16px; color: #333;
- }
- #yfx-pager button:hover:not(:disabled) { background: rgba(0,0,0,.08); }
- #yfx-pager button:focus-visible { outline: 2px solid #7d2eff; }
- #yfx-pager button:disabled { opacity: .3; cursor: default; }
- #yfx-pager .yfx-range { padding: 0 6px; white-space: nowrap; font-variant-numeric: tabular-nums; }
- #yfx-pager button[data-act="cfg"] {
- min-width: 32px; height: 32px; margin-left: 6px; font-size: 22px; line-height: 32px;
- color: #7d2eff; border-radius: 50%;
- }
- #yfx-pager button[data-act="cfg"]:hover { background: rgba(125,46,255,.14); color: #5b21d6; }
- /* numbered pages along the bottom of the list */
- #yfx-pages {
- position: absolute; left: 0; right: 0; bottom: 0; height: 34px; z-index: 4;
- display: flex; align-items: center; justify-content: center; gap: 2px;
- background: #fff; border-top: 1px solid #e6e6ed; font: 13px/1 system-ui, sans-serif; color: #333;
- }
- #yfx-pages button {
- all: unset; box-sizing: border-box; min-width: 26px; height: 26px; padding: 0 5px; text-align: center;
- border-radius: 4px; cursor: pointer; font-variant-numeric: tabular-nums;
- }
- #yfx-pages button:hover:not([aria-current]):not(:disabled) { background: rgba(0,0,0,.08); }
- #yfx-pages button:focus-visible { outline: 2px solid #7d2eff; }
- #yfx-pages button[aria-current] { background: #7d2eff; color: #fff; font-weight: 600; cursor: default; }
- #yfx-pages button:disabled { opacity: .3; cursor: default; }
- #yfx-pages .yfx-gap { padding: 0 4px; color: #888; }
- #yfx-pages .yfx-nav { font-size: 16px; }
- .yfx-busy { opacity: .35 !important; pointer-events: none !important; }
- #yfx-hint {
- display: flex; align-items: center; gap: 6px; margin-right: 8px; padding: 0 4px 0 10px; height: 28px;
- border-radius: 14px; background: rgba(125,46,255,.12); color: #4a1bb3; white-space: nowrap; font-size: 12.5px;
- }
- #yfx-hint[hidden] { display: none; }
- #yfx-hint a { color: inherit; font-weight: 600; text-decoration: underline; cursor: pointer; }
- #yfx-pager #yfx-hint button { min-width: 22px; height: 22px; font-size: 14px; color: inherit; border-radius: 50%; }
- #yfx-panel .yfx-warn { font-size: 12px; color: #4a1bb3; background: rgba(125,46,255,.10); padding: 6px 8px; border-radius: 4px; }
- #yfx-panel label.yfx-off { opacity: .45; }
- #yfx-panel .yfx-note { font-size: 12px; color: #666; margin: -2px 0 2px; }
- #yfx-panel {
- position: absolute; top: 40px; right: 0; width: 260px; padding: 10px 12px;
- background: #fff; color: #222; border: 1px solid #ccc; border-radius: 6px;
- box-shadow: 0 4px 16px rgba(0,0,0,.18); display: grid; gap: 8px;
- }
- #yfx-panel label { display: flex; justify-content: space-between; align-items: center; gap: 8px; }
- #yfx-panel select { font: inherit; }
- @media (prefers-color-scheme: dark) {
- html[data-color-scheme="dark"] #yfx-pager, html[data-color-scheme="dark"] #yfx-pager button { color: #ddd; }
- html[data-color-scheme="dark"] #yfx-panel { background: #222; color: #eee; border-color: #555; }
- html[data-color-scheme="dark"] #yfx-pager button[data-act="cfg"] { color: #b79bff; }
- html[data-color-scheme="dark"] #yfx-pages { background: #1d1d1f; color: #ddd; border-color: #444; }
- html[data-color-scheme="dark"] #yfx-panel .yfx-note { color: #aaa; }
- html[data-color-scheme="dark"] #yfx-hint, html[data-color-scheme="dark"] #yfx-panel .yfx-warn { color: #d6c8ff; background: rgba(160,120,255,.22); }
- }
- /* --- one-line rows (reading pane layouts) --- */
- /* Yahoo's row is: [dot + avatar] [column: (sender | date) / (subject / snippet)] [icons].
- Flatten the column into a single line: sender, subject, snippet, icons, date. */
- .yfx-clip { flex: none !important; overflow: hidden !important; }
- html.yfx-1line.yfx-wide ${SEL.listPane} { width: var(--yfx-list-w) !important; max-width: 75% !important; }
- html.yfx-1line .yfx-paged ${SEL.row} {
- height: var(--yfx-row-h) !important; min-height: 0 !important; box-sizing: border-box !important;
- padding-top: 0 !important; padding-bottom: 0 !important; align-items: center !important;
- }
- html.yfx-1line .yfx-paged ${SEL.row} > div { margin-top: 0 !important; margin-bottom: 0 !important; }
- html.yfx-1line .yfx-paged ${SEL.row} > div:has([id^="email-sender-"]) {
- flex-direction: row !important; align-items: center !important; gap: 8px !important;
- min-width: 0 !important; height: auto !important;
- }
- html.yfx-1line .yfx-paged ${SEL.row} > div > div:has([id^="email-sender-"]) { display: contents !important; }
- html.yfx-1line .yfx-paged ${SEL.row} > div > div > div:has([id^="email-sender-"]) {
- order: 1; flex: 0 0 var(--yfx-sender-w) !important; width: auto !important; min-width: 0 !important;
- }
- html.yfx-1line .yfx-paged ${SEL.row} > div > div > div:has([id^="email-date-"]) { order: 4; flex: none !important; }
- html.yfx-1line .yfx-paged ${SEL.row} > div > div:has([id^="email-subject-"]) {
- order: 2; flex: 1 1 0 !important; min-width: 0 !important; height: auto !important;
- flex-direction: row !important; align-items: center !important; gap: 8px !important;
- }
- html.yfx-1line .yfx-paged ${SEL.row} [id^="email-subject-"]:not([id^="email-subject-snippet-"]) {
- display: block !important; flex: 0 1 auto !important; min-width: 0 !important; max-width: 100% !important;
- white-space: nowrap !important; overflow: hidden !important; text-overflow: ellipsis !important;
- }
- html.yfx-1line .yfx-paged ${SEL.row} > div > div > div:has([id^="email-snippet-"]) {
- flex: 1 1 0 !important; width: auto !important; min-width: 0 !important; opacity: .8;
- }
- html.yfx-1line .yfx-paged ${SEL.row} > div:has([id^="email-sender-"]) > div:not(:has([id^="email-"])) {
- position: static !important; order: 3; flex: none !important; padding-left: 0 !important;
- }
- /* Two-line variant: subject on the first line, message preview under it. Sender and date
- stay in their columns, level with the subject. */
- html.yfx-2line .yfx-paged ${SEL.row} > div:has([id^="email-sender-"]) { align-items: flex-start !important; }
- html.yfx-2line .yfx-paged ${SEL.row} > div > div:has([id^="email-subject-"]) {
- flex-direction: column !important; align-items: stretch !important; gap: 0 !important;
- }
- html.yfx-2line .yfx-paged ${SEL.row} [id^="email-sender-"],
- html.yfx-2line .yfx-paged ${SEL.row} [id^="email-date-"],
- html.yfx-2line .yfx-paged ${SEL.row} [id^="email-subject-"]:not([id^="email-subject-snippet-"]) {
- line-height: 19px !important; height: 19px !important;
- }
- html.yfx-2line .yfx-paged ${SEL.row} > div > div > div:has([id^="email-snippet-"]) {
- flex: none !important; width: 100% !important; height: 17px !important;
- }
- html.yfx-2line .yfx-paged ${SEL.row} [id^="email-snippet-"] {
- font-size: 12.5px !important; line-height: 17px !important;
- white-space: nowrap !important; overflow: hidden !important; text-overflow: ellipsis !important;
- }
- /* --- right-hand panel --- */
- /* The panel is a row of icons (Calendar, Starred, Contacts, Settings, More) above a body that
- shows ads until one of those icons opens a real pane. While it only shows ads, keep just
- the icons, stacked in a slim strip, and give the freed width to the mail. */
- html.yfx-rr-min .yfx-grid, html.yfx-rr-none .yfx-grid { grid-template-columns: auto minmax(0, 1fr) auto !important; }
- /* "Hidden": take the whole panel out of the layout. It is only hidden, never deleted: the
- page is drawn by React, which breaks if nodes it owns disappear from under it. */
- html.yfx-rr-none ${SEL.rightRail} { display: none !important; }
- html.yfx-rr-none ${SEL.main} { margin-right: 16px !important; }
- html.yfx-rr-min ${SEL.rightRail} {
- width: auto !important; min-width: 0 !important; margin: 16px 8px 0 8px !important;
- height: auto !important; align-self: start !important;
- }
- html.yfx-rr-min ${SEL.rightRail} > div, html.yfx-rr-min ${SEL.rightRail} > div > div { width: auto !important; height: auto !important; }
- html.yfx-rr-min ${SEL.rightRailBox} { height: auto !important; }
- html.yfx-rr-min ${SEL.rightRailBox} > div:not(:first-of-type) { display: none !important; }
- html.yfx-rr-min ${SEL.rightRailBox} > div:first-of-type {
- flex-direction: column !important; align-items: center !important; gap: 2px !important;
- width: 44px !important; height: auto !important; padding: 6px 0 !important;
- }
- html.yfx-rr-min ${SEL.rightRailBox} [role="tablist"] { flex-direction: column !important; gap: 2px !important; }
- html.yfx-rr-min ${SEL.rightRailBox} [role="tablist"] > li { height: 34px !important; }
- html.yfx-rr-min ${SEL.rightRailBox} [data-test-id="popover-container"] button {
- font-size: 0 !important; width: 32px !important; min-width: 0 !important; padding: 0 !important; justify-content: center !important;
- }
- /* --- folder rail --- */
- /* One tight line per folder: small icon, name, unread count on the right. */
- html.yfx-folders ${SEL.rail} [data-test-id="menu-list-item"],
- html.yfx-folders ${SEL.rail} [data-test-id="left-rail-Folder-icon"] {
- height: 22px !important; min-height: 0 !important; margin: 0 !important;
- padding-left: 8px !important; border-radius: 3px !important;
- }
- html.yfx-folders ${SEL.railList} { overflow-y: auto !important; padding: 0 !important; gap: 0 !important; }
- html.yfx-folders ${SEL.railList} > li { margin: 0 !important; min-height: 0 !important; }
- html.yfx-folders ${SEL.railList} > li > div:only-child:empty { margin: 3px 8px !important; }
- html.yfx-folders ${SEL.railList} [data-test-id="menu-list-item-link"] { gap: 6px !important; align-items: center !important; height: 22px !important; }
- html.yfx-folders ${SEL.railList} [data-test-id="menu-list-item-link"] > div { padding: 0 !important; }
- html.yfx-folders ${SEL.railList} [data-test-id="menu-list-item-link"] > span { height: 16px !important; }
- html.yfx-folders ${SEL.railList} svg { width: 16px !important; height: 16px !important; }
- /* Custom folders have no icon of their own: give them a small folder glyph. */
- html.yfx-folders ${SEL.railList} ${SEL.folderItem} [data-test-id="menu-list-item-link"]:not(:has(svg))::before {
- content: ""; flex: none; width: 16px; height: 16px; opacity: .65;
- 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");
- }
- html.yfx-folders [data-test-id="expanded-left-rail"] { gap: 6px !important; }
- /* Yahoo fades out the bottom of the folder list with a gradient overlay. With the compact
- list the last rows ("More") sit right under it and look washed out, so drop the fade. */
- html.yfx-folders [data-test-id="expanded-left-rail"] [data-test-id="focus-group"]::after { content: none !important; }
- html.yfx-folders [data-test-id="expanded-left-rail"] [data-test-id="left-rail-Compose-icon"] {
- height: 32px !important; min-height: 0 !important; margin-bottom: 4px !important;
- border-radius: 6px !important; font-size: 14px !important;
- }
- html.yfx-folders ${SEL.folderItem} ${SEL.badge} { display: none !important; }
- ${SEL.folderItem}[data-yfx-unread] { position: relative; }
- ${SEL.folderItem}[data-yfx-unread]::after {
- content: attr(data-yfx-unread); position: absolute; right: 8px; top: 50%; transform: translateY(-50%);
- font: 700 12px/1 system-ui, sans-serif; color: #5b21d6; pointer-events: none;
- }
- li[data-yfx-hidden] { display: none !important; }
- li[data-yfx-depth="1"] [data-test-id="menu-list-item-link"] { margin-left: 14px !important; }
- li[data-yfx-depth="2"] [data-test-id="menu-list-item-link"] { margin-left: 28px !important; }
- li[data-yfx-depth="3"] [data-test-id="menu-list-item-link"] { margin-left: 42px !important; }
- li[data-yfx-depth="4"] [data-test-id="menu-list-item-link"] { margin-left: 56px !important; }
- li[data-yfx-parent] { position: relative; }
- .yfx-caret {
- all: unset; position: absolute; left: 0; top: 0; bottom: 0; width: 16px; z-index: 2;
- cursor: pointer; text-align: center; font-size: 10px; line-height: 22px; color: #666;
- }
- .yfx-caret:hover { color: #000; }
- `;
- function injectStyle() {
- if (document.getElementById('yfx-style')) return;
- const style = document.createElement('style');
- style.id = 'yfx-style';
- style.textContent = CSS;
- (document.head || document.documentElement).append(style);
- }
- function applyRootClasses() {
- const c = document.documentElement.classList;
- c.toggle('yfx-promo', settings.hidePromoCards);
- c.toggle('yfx-folders', settings.compactFolders);
- c.toggle('yfx-wide', settings.listWidth > 0);
- c.toggle('yfx-pg', settings.pagination);
- const st = document.documentElement.style;
- st.setProperty('--yfx-row-h', rowPitch() + 'px');
- // a page of Yahoo's tallest rows (84px), plus a quarter for ad slots
- st.setProperty('--yfx-list-h', Math.ceil(settings.pageSize * 1.25) * 84 + 'px');
- st.setProperty('--yfx-list-w', settings.listWidth + 'px');
- st.setProperty('--yfx-sender-w', Math.round(Math.max(110, Math.min(190, (settings.listWidth || 480) * 0.27))) + 'px');
- }
- // ---------------------------------------------------------------- app store
- // Yahoo keeps folder names, paths and unread/total counts in a Redux store that is
- // handed to the React root. Reading it is far sturdier than scraping the rail.
- let store = null;
- function findStore() {
- const root = $(SEL.appRoot);
- if (!root) return null;
- const key = Object.keys(root).find(k => k.startsWith('__reactContainer$') || k.startsWith('__reactFiber$'));
- if (!key) return null;
- const stack = [root[key]];
- for (let n = 0; stack.length && n < 3000; n++) {
- const f = stack.pop();
- if (!f) continue;
- const p = f.memoizedProps;
- const s = p?.store ?? p?.value?.store;
- if (s && typeof s.getState === 'function' && typeof s.subscribe === 'function') return s;
- stack.push(f.sibling, f.child);
- }
- return null;
- }
- const getFolders = () => store?.getState()?.folders ?? {};
- // Two of Yahoo's own Appearance settings, surfaced in our panel. Yahoo keeps them in the
- // store's feature map and changes them with one plain action, which also saves them.
- // previewpane: 0 = List, 1 = Right, 2 = Bottom snippets: Message preview on/off
- const yahooSetting = name => store?.getState()?.features?.[name];
- function setYahooSetting(name, value) {
- if (!store) return;
- store.dispatch({ type: 'SETTINGS_CHANGE_REQUESTED', name, value });
- schedule();
- }
- // ---------------------------------------------------------------- right-hand panel
- // Yahoo records which pane (if any) is open in the right-hand panel; with none open the
- // panel's body is ads.
- const syncRightRail = guard('rightRail', () => {
- const rail = $(SEL.rightRail);
- let adsOnly = false;
- if (rail && settings.rightPanel > 0) {
- const view = yahooSetting('actionableRightRailContent');
- adsOnly = view ? view.currentView == null
- : !!rail.querySelector(`${SEL.rightRailBox} > div:last-of-type iframe`);
- }
- // Both modes apply only while the panel shows ads: if Yahoo opens a real pane in it
- // (contacts, starred list), the panel comes back at full size.
- document.documentElement.classList.toggle('yfx-rr-min', adsOnly && settings.rightPanel === 1);
- document.documentElement.classList.toggle('yfx-rr-none', adsOnly && settings.rightPanel === 2);
- rail?.parentElement?.classList.toggle('yfx-grid', true); // the page's column grid
- });
- // Close whichever pane is open in the right-hand panel, the way a user would: by clicking
- // its (selected) icon again. Yahoo then goes back to showing ads there.
- const closeRightPane = guard('closeRightPane', () => {
- const tab = $(`${SEL.rightRailBox} > div:first-of-type [role="tab"][aria-selected="true"]`);
- if (!tab) return;
- (tab.querySelector('button, a, [role="button"]') ?? tab).click();
- setTimeout(schedule, 300);
- });
- // ---------------------------------------------------------------- open in a new tab
- // Every message has its own address: the list's address plus /messages/<id>. The id is
- // the one Yahoo puts on the row's elements.
- function messageUrl(row) {
- const id = row?.querySelector('[id^="email-sender-"]')?.id.slice('email-sender-'.length);
- if (!id) return null;
- const base = location.pathname.replace(/\/messages\/.*$/, '').replace(/\/+$/, '');
- return location.origin + base + '/messages/' + encodeURIComponent(id);
- }
- function openInNewTab(row) {
- const url = messageUrl(row);
- if (url) window.open(url, '_blank', 'noopener');
- return !!url;
- }
- // Ctrl/Cmd+click and middle-click on a message row. Yahoo would otherwise treat these as
- // an ordinary click, so they are caught first; the checkbox, star and other buttons in
- // the row keep their normal behaviour.
- const isNewTabClick = ev => settings.newTabClick && !ev.shiftKey && !ev.altKey
- && ((ev.button === 0 && (ev.ctrlKey || ev.metaKey)) || ev.button === 1);
- const rowFor = ev => {
- const t = ev.target instanceof Element ? ev.target : null;
- if (!t || t.closest('button, [role="checkbox"], a[href]')) return null;
- const row = t.closest(SEL.row);
- return row && row.closest(SEL.list) ? row : null;
- };
- for (const type of ['pointerdown', 'mousedown', 'mouseup', 'pointerup']) {
- document.addEventListener(type, ev => {
- if (!isNewTabClick(ev) || !rowFor(ev)) return;
- ev.stopImmediatePropagation();
- if (ev.button === 1) ev.preventDefault(); // no middle-button autoscroll
- }, true);
- }
- for (const type of ['click', 'auxclick']) {
- document.addEventListener(type, guard('newTab', ev => {
- if (!isNewTabClick(ev)) return;
- const row = rowFor(ev);
- if (!row) return;
- ev.preventDefault();
- ev.stopImmediatePropagation();
- openInNewTab(row);
- }), true);
- }
- // Right-click: add "Open in new tab" to the top of Yahoo's own message menu.
- const ctx = { row: null, at: 0 };
- document.addEventListener('contextmenu', ev => {
- const t = ev.target instanceof Element ? ev.target : null;
- const row = t?.closest(SEL.row);
- ctx.row = row && row.closest(SEL.list) ? row : null;
- ctx.at = Date.now();
- }, true);
- const syncContextMenu = guard('contextMenu', () => {
- if (!ctx.row || Date.now() - ctx.at > 5000) return;
- const menu = $('[data-test-id="popover-content"] ul[role="menu"]');
- const firstLi = menu?.querySelector('[role="menuitem"]')?.closest('li');
- if (!firstLi || menu.querySelector('.yfx-newtab')) return;
- const item = firstLi.cloneNode(true); // inherits Yahoo's menu styling
- item.classList.add('yfx-newtab');
- const label = 'Open in new tab';
- const link = item.querySelector('[role="menuitem"]');
- link?.setAttribute('aria-label', label);
- item.querySelectorAll('[title]').forEach(e => e.setAttribute('title', label));
- item.querySelectorAll('[data-folder-id]').forEach(e => e.removeAttribute('data-folder-id'));
- const text = [...item.querySelectorAll('span')].find(e => e.childElementCount === 0 && e.textContent.trim());
- if (text) text.textContent = label;
- const icon = item.querySelector('svg');
- 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"/>';
- const row = ctx.row;
- item.addEventListener('click', guard('newTabItem', ev => {
- ev.preventDefault();
- ev.stopImmediatePropagation();
- openInNewTab(row);
- // close Yahoo's menu the way a click elsewhere would
- menu.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', code: 'Escape', keyCode: 27, bubbles: true }));
- document.body.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
- document.body.click();
- }), true);
- firstLi.before(item);
- });
- // ---------------------------------------------------------------- folders
- const isUserFolder = f => f?.types?.includes('USER') && !f.types.includes('INVISIBLE');
- const syncFolders = guard('folders', () => {
- const rail = $(SEL.rail);
- if (!rail) return;
- const folders = getFolders();
- const paths = Object.values(folders).filter(isUserFolder).map(f => f.path);
- const collapsed = new Set(settings.collapsed);
- for (const item of rail.querySelectorAll(SEL.folderItem)) {
- const f = folders[item.getAttribute('data-folder-id')];
- const li = item.closest('li');
- // Unread count: only add ours where Yahoo's own badge is empty.
- const native = item.querySelector(SEL.badge)?.textContent.trim();
- // With the compact rail we replace Yahoo's rounded badge ("6.8K") by the exact count.
- const want = f && f.unread > 0 && (settings.compactFolders || !native) ? String(f.unread) : null;
- if (want !== item.getAttribute('data-yfx-unread')) {
- want ? item.setAttribute('data-yfx-unread', want) : item.removeAttribute('data-yfx-unread');
- }
- if (!li || !isUserFolder(f)) continue;
- const parts = f.path.split('/');
- const depth = parts.length - 1;
- setAttr(li, 'data-yfx-depth', depth > 0 ? String(Math.min(depth, 4)) : null);
- const hidden = parts.slice(0, -1).some((_, i) => collapsed.has(parts.slice(0, i + 1).join('/')));
- setAttr(li, 'data-yfx-hidden', hidden ? '' : null);
- const hasChildren = paths.some(p => p.startsWith(f.path + '/'));
- setAttr(li, 'data-yfx-parent', hasChildren ? '' : null);
- let caret = li.querySelector(':scope > .yfx-caret');
- if (hasChildren) {
- if (!caret) {
- caret = document.createElement('button');
- caret.className = 'yfx-caret';
- caret.type = 'button';
- caret.addEventListener('click', ev => {
- ev.preventDefault();
- ev.stopPropagation();
- const p = caret.dataset.path;
- const set = new Set(settings.collapsed);
- set.has(p) ? set.delete(p) : set.add(p);
- settings.collapsed = [...set];
- save();
- syncFolders();
- });
- li.append(caret);
- }
- const isCollapsed = collapsed.has(f.path);
- caret.dataset.path = f.path;
- caret.style.marginLeft = depth * 14 + 'px';
- caret.textContent = isCollapsed ? '▸' : '▾';
- caret.setAttribute('aria-expanded', String(!isCollapsed));
- caret.setAttribute('aria-label', (isCollapsed ? 'Expand ' : 'Collapse ') + f.name);
- } else {
- caret?.remove();
- }
- }
- });
- // Yahoo can show the rail as an icon strip ("compact navigation"). Switch it back to the
- // full list of folder names using Yahoo's own toggle.
- let expandTriedAt = 0;
- const expandRail = guard('expandRail', () => {
- if (!settings.compactFolders) return;
- const btn = $(SEL.railToggle);
- if (!btn || btn.getAttribute('aria-expanded') !== 'false') return;
- if (Date.now() - expandTriedAt < 5000) return;
- expandTriedAt = Date.now();
- btn.click();
- });
- function setAttr(el, name, value) {
- if (value === null) { if (el.hasAttribute(name)) el.removeAttribute(name); }
- else if (el.getAttribute(name) !== value) el.setAttribute(name, value);
- }
- // ---------------------------------------------------------------- pagination
- // Yahoo's list is virtualised: rows are absolutely positioned at slot * rowHeight inside
- // a scroller, and some slots hold ads instead of messages. We clip that scroller to the
- // slots holding one page of messages, move it a page at a time, and let its container
- // scroll normally within the page. Because ad slots vary, a page's starting offset is
- // not a fixed multiple: it is learned when the page before it is laid out, or, for a
- // jump, by finding that page's first message in the list (see jumpTo).
- const pg = {
- list: null, page: 0, starts: [0], end: 0, route: '', rowH: 44, mo: null, saved: null,
- faking: false, askedAt: 0, askedTotal: -1,
- jump: 0, // bumped to cancel a jump in progress
- locating: false, // a jump is moving the list around; leave it alone
- busy: false, status: '', boost: 0, listKey: null, lastMore: false, lastEmpty: false,
- };
- const FOOT = 36; // room kept under the rows for the numbered page bar
- const sleep = ms => new Promise(r => setTimeout(r, ms));
- // While a jump is loading ahead, ask Yahoo for much bigger batches than its usual 100, by
- // editing the size in its own message-list request. Everything else about the request,
- // and how Yahoo handles the answer, is untouched.
- const xhrSend = XMLHttpRequest.prototype.send;
- XMLHttpRequest.prototype.send = function (body) {
- try {
- if (pg.boost && body instanceof FormData) {
- const json = body.get('batchJson');
- if (typeof json === 'string' && json.includes('/messages/@.select==q') && json.includes('count%3A100%20offset')) {
- body.set('batchJson', json.replace('count%3A100%20offset', `count%3A${pg.boost}%20offset`));
- }
- }
- } catch (e) { warn('boost', e); }
- return xhrSend.apply(this, arguments);
- };
- function measureRowHeight(ul) {
- const tops = [...ul.children].slice(0, 6).map(li => parseFloat(li.style.top)).filter(Number.isFinite);
- for (let i = 1; i < tops.length; i++) {
- const d = tops[i] - tops[i - 1];
- if (d > 10) return d;
- }
- return pg.rowH;
- }
- function attachList(list) {
- detachList();
- pg.list = list;
- // Coming back from an open message returns to the page it was opened from.
- const returning = pg.saved?.route === location.pathname && pg.route.startsWith(location.pathname + '/');
- pg.page = returning ? pg.saved.page : 0;
- pg.starts = returning ? [...pg.saved.starts] : [0];
- pg.jump++;
- pg.locating = false;
- pg.listKey = null;
- setBusy(false);
- list.addEventListener('scroll', onListScroll, { passive: true });
- const ul = list.firstElementChild;
- if (ul) {
- // Rows are recycled and ads fill in late, so watch the whole list.
- pg.mo = new MutationObserver(() => {
- if (pg.pending) return;
- pg.pending = true;
- setTimeout(() => { pg.pending = false; layoutPage(); }, 0);
- });
- pg.mo.observe(ul, { childList: true, subtree: true, attributes: true, attributeFilter: ['style'] });
- }
- layoutPage();
- }
- function detachList() {
- const list = pg.list;
- if (!list) return;
- list.removeEventListener('scroll', onListScroll);
- pg.mo?.disconnect();
- pg.mo = null;
- list.classList.remove('yfx-paged');
- list.style.removeProperty('height');
- list.style.removeProperty('zoom');
- for (const li of list.firstElementChild?.children ?? []) clearShift(li);
- list.closest(SEL.listContainer)?.classList.remove('yfx-scroller');
- list.parentElement?.classList.remove('yfx-clip');
- list.parentElement?.style.removeProperty('height');
- list.classList.remove('yfx-busy');
- document.getElementById('yfx-pages')?.remove();
- document.documentElement.classList.remove('yfx-1line', 'yfx-2line');
- pg.list = null;
- }
- const onListScroll = guard('scroll', () => {
- if (!pg.list || pg.faking || pg.locating) return;
- // The app moved the list itself (keyboard navigation, jump to a message):
- // follow it to the neighbouring page instead of fighting it.
- const start = pg.starts[pg.page] ?? 0;
- const st = pg.list.scrollTop;
- if (Math.abs(st - start) <= 1.5) return;
- if (st >= pg.end - 1.5 && pg.starts[pg.page + 1] !== undefined) pg.page++;
- else if (st < start && pg.page > 0) pg.page--;
- layoutPage();
- });
- const layoutPage = guard('pagination', () => {
- const list = pg.list;
- if (!list?.isConnected || pg.locating) return;
- const ul = list.firstElementChild;
- if (!ul) return;
- pg.rowH = measureRowHeight(ul);
- const total = parseFloat(ul.style.height) || ul.scrollHeight;
- if (pg.starts[pg.page] === undefined) { pg.page = 0; pg.starts = [0]; }
- const start = pg.starts[pg.page];
- const more = currentList()?.hasMoreItems === true;
- // Tall multi-line rows mean a reading-pane layout: there we draw each message on one
- // line at our own pitch. Yahoo's single-line List layout is only zoomed.
- // Is Yahoo's Message preview off? Ask the store; failing that, look at the rows, which
- // carry no preview element at all when it is.
- const snippets = yahooSetting('snippets');
- noPreview = typeof snippets === 'boolean' ? !snippets
- : ul.querySelectorAll(MESSAGE).length >= 5 && !ul.querySelector('[id^="email-snippet-"]');
- const oneLine = settings.rowLines > 0 && pg.rowH > 50; // "our own rows", one or two lines
- document.documentElement.classList.toggle('yfx-1line', oneLine);
- document.documentElement.classList.toggle('yfx-2line', oneLine && rowLines() === 2);
- const pitch = oneLine ? rowPitch() : pg.rowH;
- const pitchPx = rowPitch() + 'px';
- if (document.documentElement.style.getPropertyValue('--yfx-row-h') !== pitchPx) {
- document.documentElement.style.setProperty('--yfx-row-h', pitchPx);
- }
- const zoom = oneLine ? 1 : settings.density;
- const built = buildPage(ul, start, total, more, pitch);
- pg.end = built.end;
- // The user asked for two-line rows but is getting one line: say why, in the toolbar.
- pg.previewOff = oneLine && settings.rowLines === 2 && noPreview;
- if (built.complete && built.end < total - 0.5) pg.starts[pg.page + 1] = built.end;
- else delete pg.starts[pg.page + 1];
- // If the page is short only because rows further down are not rendered yet, give the
- // list a little more room so Yahoo renders them; the next pass trims it again.
- const room = !built.complete && built.end < total - 0.5 ? 8 * pg.rowH : 0;
- // The list keeps the height Yahoo expects for these slots (so it renders them all);
- // its parent clips that down to the rows as we have actually drawn them.
- const span = Math.max(pg.rowH, built.end - start + room);
- const shown = Math.max(pitch, built.visual + room) * zoom + FOOT;
- const clip = list.parentElement;
- list.classList.add('yfx-paged');
- clip.classList.add('yfx-clip');
- list.closest(SEL.listContainer)?.classList.add('yfx-scroller');
- if (list.style.height !== span + 'px') list.style.setProperty('height', span + 'px', 'important');
- if (clip.style.height !== shown + 'px') clip.style.setProperty('height', shown + 'px', 'important');
- if (list.style.zoom !== String(zoom)) list.style.zoom = String(zoom);
- if (!pg.faking && Math.abs(list.scrollTop - start) > 1.5) list.scrollTop = start;
- // Keep about a page ahead loaded so "Next" is ready and pages are never half empty.
- if (more && total < built.end + settings.pageSize * pg.rowH * 1.3) {
- const now = Date.now();
- if (pg.askedTotal !== total || now - pg.askedAt > 4000) {
- pg.askedTotal = total;
- pg.askedAt = now;
- requestMore(list);
- }
- }
- pg.saved = { route: location.pathname, page: pg.page, starts: [...pg.starts] };
- pg.lastMore = more;
- pg.lastEmpty = built.count === 0 && !more;
- renderPager();
- });
- // Ad rows keep their slot in the list even when an ad blocker empties them. Within the
- // visible page, hide those rows and slide the following messages up. Returns the height
- // reclaimed so the page can be shortened to match.
- const MESSAGE = '[data-test-id="message-list-item"]';
- function isGapRow(li) {
- if (li.querySelector(MESSAGE)) return false;
- if (li.childElementCount === 0) return true; // emptied by a blocker
- if ([...li.children].every(c => c.offsetHeight === 0)) return true; // hidden by a cosmetic filter
- if (!settings.collapseAdRows) return false;
- return hasAdLabel(li); // Yahoo's own "Ad" label
- }
- function clearShift(li) {
- if (li.style.transform) li.style.transform = '';
- if (li.style.visibility) li.style.visibility = '';
- }
- function hasAdLabel(li) {
- for (const el of li.querySelectorAll('span, div')) {
- if (el.childElementCount === 0 && /^(Ad|Sponsored)$/.test(el.textContent.trim())) return true;
- }
- return false;
- }
- // Lay out the page that begins at slot offset `start`: walk the rendered rows in order,
- // hide ad gaps, and move every remaining row to its place in a gap-free column where a
- // message takes `pitch` px. Stops once the page holds pageSize messages. Returns where
- // the page ends in Yahoo's coordinates, the height of the column as drawn, the number of
- // messages, and whether that boundary is final (false while rows are still loading).
- function buildPage(ul, start, total, more, pitch) {
- const rows = [];
- for (const li of ul.children) {
- const top = parseFloat(li.style.top);
- if (top >= start - 0.5) rows.push([top, li]);
- else clearShift(li);
- }
- rows.sort((a, b) => a[0] - b[0]);
- const size = settings.pageSize;
- let y = 0, count = 0, end = start, pending = false, full = false;
- for (const [top, li] of rows) {
- if (full || top > end + 0.5) { clearShift(li); continue; } // past the page, or a hole
- const isMessage = !!li.querySelector(MESSAGE);
- if (!isMessage && isGapRow(li)) {
- if (li.style.visibility !== 'hidden') li.style.visibility = 'hidden';
- } else {
- const dy = y - (top - start);
- const want = Math.abs(dy) > 0.01 ? `translateY(${dy}px)` : '';
- if (li.style.transform !== want) li.style.transform = want;
- if (li.style.visibility) li.style.visibility = '';
- y += isMessage ? pitch : pg.rowH;
- if (isMessage) count++;
- else if (!hasAdLabel(li)) { count++; pending = true; } // loading placeholder or footer
- }
- end = Math.min(total, top + pg.rowH);
- if (count >= size) full = true;
- }
- const atEnd = end >= total - 0.5 && !more;
- if (atEnd) end = total;
- return { end, visual: y, count, complete: (full && !pending) || atEnd };
- }
- // Yahoo fetches the next batch of messages when its list is scrolled near the end. Our
- // clipped list never scrolls, so report an end-of-list position for one scroll event,
- // then let the list re-read its real position.
- const scrollTopProp = Object.getOwnPropertyDescriptor(Element.prototype, 'scrollTop');
- function requestMore(list) {
- if (pg.faking || !scrollTopProp) return;
- pg.faking = true;
- Object.defineProperty(list, 'scrollTop', {
- configurable: true,
- get: () => list.scrollHeight,
- set: v => scrollTopProp.set.call(list, v),
- });
- // Restore the real position in the same tick, before anything is painted: holding the
- // fake one any longer makes Yahoo render the rows at the bottom instead of this page.
- try {
- list.dispatchEvent(new Event('scroll', { bubbles: true }));
- } finally {
- delete list.scrollTop;
- pg.faking = false;
- }
- list.dispatchEvent(new Event('scroll', { bubbles: true }));
- }
- // Go to page n (0-based; Infinity = the last page). A page whose start is already known
- // is shown at once; any other page is reached by a jump.
- function gotoPage(n) {
- n = Math.max(0, n);
- pg.jump++; // cancels a jump in progress
- if (pg.starts[n] === undefined) { jumpTo(n); return; }
- pg.locating = false;
- pg.boost = 0;
- setBusy(false);
- pg.page = n;
- layoutPage();
- pg.list?.closest(SEL.listContainer)?.scrollTo({ top: 0 });
- }
- function setBusy(busy, status = '') {
- pg.busy = busy;
- pg.status = busy ? status : '';
- pg.list?.classList.toggle('yfx-busy', busy);
- if (pager?.isConnected) renderPager();
- }
- // Jump straight to a page: load ahead until its first message has arrived (in big
- // batches), find where that message sits in Yahoo's list, and start the page there.
- const jumpTo = async n => {
- const token = pg.jump, list = pg.list, size = settings.pageSize;
- if (!list) return;
- const live = () => token === pg.jump && list === pg.list && list.isConnected;
- let page = null, top = null;
- try {
- setBusy(true, 'Loading…');
- pg.boost = 1000;
- for (let fails = 0; live() && fails < 3;) {
- const l = currentList();
- if (!l) { await sleep(200); fails++; continue; }
- if (!l.hasMoreItems || l.itemIds.length > n * size) break;
- const total = knownTotal(), have = l.itemIds.length;
- setBusy(true, `Loading ${have.toLocaleString()}${total ? ' of ' + total.toLocaleString() : ''}…`);
- requestMore(list);
- for (let t = Date.now(); live() && (currentList()?.itemIds.length ?? have) === have && Date.now() - t < 20000;) await sleep(80);
- fails = (currentList()?.itemIds.length ?? have) === have ? fails + 1 : 0;
- }
- pg.boost = 0;
- const l = currentList();
- if (!live() || !l) return;
- page = Math.min(n, Math.max(0, Math.ceil(l.itemIds.length / size) - 1));
- setBusy(true, `Opening page ${(page + 1).toLocaleString()}…`);
- top = page === 0 ? 0 : await locate(l.itemIds[page * size], page * size, live);
- } catch (e) {
- warn('jump', e);
- } finally {
- if (token === pg.jump) {
- pg.boost = 0;
- pg.locating = false;
- if (top !== null && page !== null) { pg.starts[page] = top; pg.page = page; }
- setBusy(false);
- layoutPage();
- pg.list?.closest(SEL.listContainer)?.scrollTo({ top: 0 });
- }
- }
- };
- // Find the slot offset of a message in Yahoo's list. Only rows near the scroll position
- // exist, so scroll to an estimate, look, and correct the estimate from whichever
- // messages did get rendered there.
- async function locate(id, index, live) {
- const list = pg.list, ul = list.firstElementChild;
- pg.locating = true;
- let guess = index * pg.rowH * 1.1;
- for (let attempt = 0; attempt < 8 && live(); attempt++) {
- const max = Math.max(0, list.scrollHeight - list.clientHeight);
- list.scrollTop = Math.max(0, Math.min(guess - 10 * pg.rowH, max));
- for (let w = 0; w < 30 && live(); w++) {
- await sleep(60);
- if (document.getElementById('email-sender-' + id)) break;
- }
- const li = document.getElementById('email-sender-' + id)?.closest('li');
- if (li && li.parentElement === ul) return parseFloat(li.style.top);
- const ids = currentList()?.itemIds ?? [];
- let best = null;
- for (const el of ul.querySelectorAll('[id^="email-sender-"]')) {
- const j = ids.indexOf(el.id.slice('email-sender-'.length));
- const t = parseFloat(el.closest('li')?.style.top);
- if (j >= 0 && Number.isFinite(t) && (!best || Math.abs(j - index) < Math.abs(best.j - index))) best = { j, t };
- }
- if (best) guess = best.t + (index - best.j) * (best.j > 0 ? best.t / best.j : pg.rowH * 1.1);
- }
- return null;
- }
- // How many pages the open list has: exact once everything is loaded, otherwise estimated
- // from the folder's message count, otherwise unknown (null).
- function pageCount() {
- const l = currentList(), size = settings.pageSize;
- if (l && !l.hasMoreItems) return { n: Math.max(1, Math.ceil(l.itemIds.length / size)), exact: true };
- const total = knownTotal();
- return total !== null ? { n: Math.max(1, Math.ceil(total / size)), exact: false } : { n: null, exact: false };
- }
- // Total messages in the open folder, when the store can tell us reliably.
- function knownTotal() {
- const folders = getFolders();
- const id = location.pathname.match(/\/folders\/([^/]+)/)?.[1];
- const f = id ? folders[id]
- : /\/inbox(\/|$)/.test(location.pathname) ? Object.values(folders).find(x => x.types?.includes('INBOX'))
- : null;
- if (!f || typeof f.total !== 'number') return null;
- const tab = $(`${SEL.inboxTabs} [role="tab"][aria-selected="true"]`);
- if (tab && tab.getAttribute('data-category') !== 'all') return null; // tab shows a subset
- if (/\/search\//.test(location.pathname)) return null;
- return f.total;
- }
- // The store's record of the list on screen. It is identified by a rendered message id
- // and remembered by key, since during a jump there may briefly be no rendered rows. Yahoo
- // can hold several lists that begin with the same messages (an early short copy next to
- // the live one), so of those containing the message, the longest is the one on screen.
- function currentList() {
- const lists = store?.getState()?.lists;
- if (!lists) return null;
- const id = pg.list?.querySelector('[id^="email-sender-"]')?.id.slice('email-sender-'.length);
- if (id) {
- let best = null;
- for (const k of Object.keys(lists)) {
- const ids = lists[k].itemIds;
- if (ids?.includes(id) && (!best || ids.length > lists[best].itemIds.length)) best = k;
- }
- if (best) pg.listKey = best;
- }
- return lists[pg.listKey] ?? null;
- }
- let pager = null;
- function renderPager() {
- const more = pg.lastMore, empty = pg.lastEmpty;
- const main = $(SEL.main);
- if (!main) return;
- if (!pager || !pager.isConnected) {
- pager = document.createElement('div');
- pager.id = 'yfx-pager';
- pager.innerHTML = `
- <span id="yfx-hint" role="status" hidden>Two-line rows need previews ·
- <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>
- <button type="button" data-act="hint-close" aria-label="Dismiss" title="Dismiss">×</button></span>
- <button type="button" data-act="first" aria-label="First page" title="First page">«</button>
- <button type="button" data-act="prev" aria-label="Previous page" title="Previous page">‹</button>
- <span class="yfx-range" aria-live="polite"></span>
- <button type="button" data-act="next" aria-label="Next page" title="Next page">›</button>
- <button type="button" data-act="last" aria-label="Last page" title="Last page">»</button>
- <button type="button" data-act="cfg" aria-label="Yahoo Mail Comfort settings" title="Yahoo Mail Comfort settings">⚙</button>`;
- pager.addEventListener('click', guard('pager', ev => {
- const act = ev.target.closest('button, a')?.dataset.act;
- if (act === 'first') gotoPage(0);
- else if (act === 'prev') gotoPage(pg.page - 1);
- else if (act === 'next') gotoPage(pg.page + 1);
- else if (act === 'last') gotoPage(Infinity);
- else if (act === 'cfg') togglePanel();
- else if (act === 'hint-close') { settings.hintDismissed = true; save(); layoutPage(); }
- else if (act === 'enable-preview') { setYahooSetting('snippets', true); refreshPanelSoon(); }
- }));
- main.append(pager);
- }
- const hasNext = pg.starts[pg.page + 1] !== undefined;
- const total = knownTotal();
- const n = pg.page + 1;
- const count = pageCount();
- const atEnd = !hasNext && !more;
- const label = pg.status ? pg.status
- : empty ? 'No messages'
- : atEnd ? `Page ${n} of ${n}`
- : count.n !== null ? `Page ${n} of ${count.exact ? '' : '~'}${Math.max(n, count.n).toLocaleString()}`
- : `Page ${n}`;
- const range = pager.querySelector('.yfx-range');
- if (range.textContent !== label) range.textContent = label;
- range.title = total !== null ? `${total.toLocaleString()} messages in this folder` : '';
- pager.querySelector('[data-act="first"]').disabled = pg.page === 0 && !pg.busy;
- pager.querySelector('[data-act="prev"]').disabled = pg.page === 0;
- pager.querySelector('[data-act="next"]').disabled = !hasNext;
- pager.querySelector('[data-act="last"]').disabled = atEnd && !pg.busy;
- pager.querySelector('#yfx-hint').hidden = !(pg.previewOff && !settings.hintDismissed);
- renderPageBar(n, atEnd ? n : count.n, empty);
- }
- // Which page numbers to offer: the first few, the ones around the current page, and the
- // last two, with gaps marked. `count` is null when the number of pages is unknown.
- function pageNumbers(cur, count) {
- const want = new Set([1, 2, cur - 2, cur - 1, cur, cur + 1, cur + 2]);
- if (cur <= 3) { want.add(3); want.add(4); want.add(5); }
- if (count) { want.add(count - 1); want.add(count); }
- const top = count ?? cur + 2;
- const nums = [...want].filter(p => p >= 1 && p <= top).sort((a, b) => a - b);
- const out = [];
- for (let i = 0; i < nums.length; i++) {
- if (i && nums[i] !== nums[i - 1] + 1) out.push(null);
- out.push(nums[i]);
- }
- if (!count) out.push(null); // more pages, number unknown
- return out;
- }
- let pageBarKey = '';
- function renderPageBar(cur, count, empty) {
- const scroller = pg.list?.closest(SEL.listContainer);
- // The fixed frame around the scrolling list: the bar sits at its bottom edge.
- const frame = scroller?.parentElement?.closest(SEL.listContainer) ?? scroller?.parentElement;
- let bar = document.getElementById('yfx-pages');
- if (!frame || empty) { bar?.remove(); pageBarKey = ''; return; }
- if (!bar || bar.parentElement !== frame) {
- bar?.remove();
- bar = document.createElement('nav');
- bar.id = 'yfx-pages';
- bar.setAttribute('aria-label', 'Pages');
- bar.addEventListener('click', guard('pages', ev => {
- const b = ev.target.closest('button');
- if (!b || b.hasAttribute('aria-current')) return;
- if (b.dataset.page) gotoPage(Number(b.dataset.page) - 1);
- else if (b.dataset.act === 'prev') gotoPage(pg.page - 1);
- else if (b.dataset.act === 'next') gotoPage(pg.page + 1);
- else if (b.dataset.act === 'last') gotoPage(Infinity);
- }));
- frame.append(bar);
- pageBarKey = '';
- }
- const nums = pageNumbers(cur, count);
- const lastKnown = count !== null && cur >= count;
- const key = nums.join(',') + '|' + cur + '|' + lastKnown + '|' + pg.busy;
- if (key === pageBarKey) return;
- pageBarKey = key;
- bar.innerHTML = `<button type="button" class="yfx-nav" data-act="prev" aria-label="Previous page" title="Previous page"${cur === 1 ? ' disabled' : ''}>‹</button>`
- + nums.map(p => p === null ? '<span class="yfx-gap">…</span>'
- : `<button type="button" data-page="${p}"${p === cur ? ' aria-current="page"' : ''} aria-label="Page ${p}">${p.toLocaleString()}</button>`).join('')
- + `<button type="button" class="yfx-nav" data-act="next" aria-label="Next page" title="Next page"${lastKnown ? ' disabled' : ''}>›</button>`
- + `<button type="button" class="yfx-nav" data-act="last" aria-label="Last page" title="Last page"${lastKnown ? ' disabled' : ''}>»</button>`;
- }
- // ---------------------------------------------------------------- settings panel
- function togglePanel() {
- const open = document.getElementById('yfx-panel');
- if (open) { open.remove(); return; }
- const panel = document.createElement('div');
- panel.id = 'yfx-panel';
- const opt = (v, label, cur, disabled) => `<option value="${v}"${String(v) === String(cur) ? ' selected' : ''}${disabled ? ' disabled' : ''}>${label}</option>`;
- // Some options only act in one of Yahoo's layouts; grey out the ones that do nothing now.
- const tall = pg.rowH > 50; // Yahoo's multi-line rows (Right layout)
- const layout = yahooSetting('previewpane');
- const preview = yahooSetting('snippets');
- const known = v => v !== undefined;
- const oneLine = tall && settings.rowLines > 0;
- const off = on => on ? '' : ' class="yfx-off"';
- const dis = on => on ? '' : ' disabled';
- panel.innerHTML = `
- <div class="yfx-note">Yahoo's own settings</div>
- <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>
- <label${off(known(preview))}>Message preview <input type="checkbox" data-y="snippets"${preview ? ' checked' : ''}${dis(known(preview))}></label>
- <div class="yfx-note">Everywhere</div>
- <label>Messages per page <select data-k="pageSize">${[25, 50, 100, 200].map(n => opt(n, n, settings.pageSize)).join('')}</select></label>
- <div class="yfx-note">With the Right layout</div>
- <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>
- ${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>' : ''}
- <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>
- <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>
- <div class="yfx-note">With Yahoo's own rows (List or Bottom layout)</div>
- <label${off(!oneLine)}>Row density <select data-k="density"${dis(!oneLine)}>
- ${opt(1, 'Yahoo default', settings.density)}${opt(0.92, 'Cosy', settings.density)}
- ${opt(0.85, 'Compact', settings.density)}${opt(0.75, 'Dense', settings.density)}</select></label>
- <div class="yfx-note">Extras</div>
- <label>Compact folder list <input type="checkbox" data-k="compactFolders"${settings.compactFolders ? ' checked' : ''}></label>
- <label>Hide promo cards <input type="checkbox" data-k="hidePromoCards"${settings.hidePromoCards ? ' checked' : ''}></label>
- <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>
- <label>Collapse ad rows <input type="checkbox" data-k="collapseAdRows"${settings.collapseAdRows ? ' checked' : ''}></label>
- <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>
- ${settings.rightPanel === 2 ? '<div class="yfx-note">Hidden also removes the Calendar and Contacts icons. Choose "Icons only" to get them back.</div>' : ''}`;
- panel.addEventListener('change', guard('settings', ev => {
- const el = ev.target, k = el.dataset.k;
- if (el.dataset.y) { // one of Yahoo's settings: Yahoo applies and saves it
- setYahooSetting(el.dataset.y, el.type === 'checkbox' ? el.checked : Number(el.value));
- refreshPanelSoon();
- return;
- }
- if (!k) return;
- settings[k] = el.type === 'checkbox' ? el.checked : Number(el.value);
- save();
- applyRootClasses();
- // Icons only / Hidden act while the panel shows ads; if a pane (contacts, starred)
- // is open when one of them is chosen, close it so the choice takes effect at once.
- if (k === 'rightPanel' && settings.rightPanel > 0) closeRightPane();
- syncRightRail();
- if (k === 'pageSize' || k === 'collapseAdRows') { pg.jump++; pg.locating = false; setBusy(false); pg.page = 0; pg.starts = [0]; }
- if (k === 'rowLines') settings.hintDismissed = false;
- layoutPage();
- if (k === 'rowLines' || k === 'rightPanel') { panel.remove(); togglePanel(); } // refresh notes and which options apply
- }));
- pager.append(panel);
- }
- // Changing a Yahoo setting can rebuild the message list (and our pager with it). Once that
- // has settled, redraw the panel so it shows the new state and which options now apply.
- function refreshPanelSoon() {
- if (!document.getElementById('yfx-panel')) return;
- setTimeout(() => {
- document.getElementById('yfx-panel')?.remove();
- layoutPage();
- if (pager?.isConnected) togglePanel();
- }, 1200);
- }
- document.addEventListener('click', ev => {
- const panel = document.getElementById('yfx-panel');
- if (panel && !ev.target.closest('#yfx-pager')) panel.remove();
- }, true);
- // ---------------------------------------------------------------- wiring
- let scheduled = false;
- const tick = guard('tick', () => {
- scheduled = false;
- injectStyle();
- if (!store) {
- store = findStore();
- if (store) store.subscribe(schedule);
- }
- syncFolders();
- expandRail();
- syncRightRail();
- syncContextMenu();
- if (!settings.pagination) { detachList(); pager?.remove(); return; }
- if (pg.busy) { pg.route = location.pathname; return; } // a jump is rearranging the list
- const list = $(`${SEL.main} ${SEL.list}`);
- const route = location.pathname;
- if (list !== pg.list) {
- list ? attachList(list) : (detachList(), pager?.remove());
- } else if (list && route !== pg.route) {
- pg.jump++;
- pg.locating = false;
- pg.listKey = null;
- setBusy(false);
- pg.page = 0;
- pg.starts = [0];
- layoutPage();
- }
- pg.route = route;
- });
- function schedule() {
- if (scheduled) return;
- scheduled = true;
- setTimeout(tick, 30); // not requestAnimationFrame: that never fires in a background tab
- }
- // At document-start the page may not have its <html> element yet (Chrome in particular),
- // and everything below hangs off it, so wait for it to appear.
- function boot() {
- if (!document.documentElement) {
- new MutationObserver((_, obs) => {
- if (document.documentElement) { obs.disconnect(); boot(); }
- }).observe(document, { childList: true });
- return;
- }
- injectStyle();
- applyRootClasses();
- new MutationObserver(schedule).observe(document.documentElement, { childList: true, subtree: true });
- document.addEventListener('DOMContentLoaded', schedule);
- schedule();
- }
- boot();
- // Small hook for debugging from the console.
- window.__yfx = { settings, save, gotoPage, layoutPage, get store() { return store; } };
- })();
Add Comment
Please, Sign In to add comment