Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions eslint-rules/select-dom.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,31 @@ const rule = {
create(context) {
const {sourceCode} = context;
return {
// X.closest(sel) → $closest(sel, x) or $closestOptional(sel, x)
'CallExpression[callee.type=MemberExpression][callee.property.name=closest]'(node) {
const {object} = node.callee;

// Determine parent, skipping over ChainExpression wrappers
const parent = node.parent?.type === 'ChainExpression' ? node.parent.parent : node.parent;

const isNonNull = parent?.type === 'TSNonNullExpression';
const replacement = isNonNull ? '$closest' : '$closestOptional';

// The node to replace: for non-null, replace the whole `x.closest(sel)!`; otherwise just the call
const nodeToReplace = isNonNull ? parent : node;

context.report({
node,
messageId: 'useSelectDom',
data: {replacement, method: 'closest'},
fix(fixer) {
const selector = sourceCode.getText(node.arguments[0]);
const objectText = sourceCode.getText(object);
return fixer.replaceText(nodeToReplace, `${replacement}(${selector}, ${objectText})`);
},
});
},

// X.querySelector(sel) with a simple receiver → $(sel, x)
'CallExpression[callee.type=MemberExpression]:matches([callee.property.name=querySelector], [callee.property.name=querySelectorAll])'(node) {
const {object} = node.callee;
Expand Down
11 changes: 3 additions & 8 deletions eslint-suppressions.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@
},
"source/features/conversation-activity-filter.tsx": {
"refined-github/no-optional-chaining": {
"count": 2
"count": 1
}
},
"source/features/cross-deleted-pr-branches.tsx": {
"refined-github/no-optional-chaining": {
"count": 2
"count": 1
}
},
"source/features/easy-toggle-commit-messages.tsx": {
Expand All @@ -49,11 +49,6 @@
"count": 1
}
},
"source/features/hide-low-quality-comments.tsx": {
"refined-github/no-optional-chaining": {
"count": 1
}
},
"source/features/highest-rated-comment.tsx": {
"refined-github/no-optional-chaining": {
"count": 2
Expand Down Expand Up @@ -169,4 +164,4 @@
"count": 1
}
}
}
}
8 changes: 6 additions & 2 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,12 +91,12 @@
'error',
{
selector:
':matches([callee.name=delegate], [callee.name=$], [callee.name=$$], [callee.name=$optional], [callee.name=observe], [callee.property.name=querySelector], [callee.property.name=querySelectorAll], [callee.property.name=closest])[arguments.0.value=/,/][arguments.0.value.length>=20]:not([arguments.0.value=/:has|:is/])',
':matches([callee.name=delegate], [callee.name=$], [callee.name=$$], [callee.name=$optional], [callee.name=$closest], [callee.name=$closestOptional], [callee.name=observe], [callee.property.name=querySelector], [callee.property.name=querySelectorAll])[arguments.0.value=/,/][arguments.0.value.length>=20]:not([arguments.0.value=/:has|:is/])',

Check warning on line 94 in eslint.config.js

View workflow job for this annotation

GitHub Actions / Lint

This line has a length of 374. Maximum allowed is 200
message: 'Instead of a single string, pass an array of selectors and add comments to each selector',
},
{
selector:
':matches([callee.name=delegate], [callee.name=$], [callee.name=$$], [callee.name=$optional], [callee.name=observe], [callee.property.name=querySelector], [callee.property.name=querySelectorAll], [callee.property.name=closest])[arguments.0.type=ArrayExpression][arguments.0.elements.length=1]:not([arguments.0.value=/:has|:is/])',
':matches([callee.name=delegate], [callee.name=$], [callee.name=$$], [callee.name=$optional], [callee.name=$closest], [callee.name=$closestOptional], [callee.name=observe], [callee.property.name=querySelector], [callee.property.name=querySelectorAll])[arguments.0.type=ArrayExpression][arguments.0.elements.length=1]:not([arguments.0.value=/:has|:is/])',

Check warning on line 99 in eslint.config.js

View workflow job for this annotation

GitHub Actions / Lint

This line has a length of 386. Maximum allowed is 200
message: 'If it\'s a single selector, use a single string instead of an array',
},
{
Expand All @@ -107,6 +107,10 @@
selector: 'TSNonNullExpression > CallExpression > [name=$]',
message: 'Unused null expression: !',
},
{
selector: 'TSNonNullExpression > CallExpression > [name=$closest]',
message: 'Unused null expression: ! — $closest() already throws when the element is not found',
},
{
message: 'Init functions wrapped with onetime() must have a name ending with "Once"',
selector: 'ObjectExpression > Property[key.name=init] > CallExpression[callee.name=onetime]:not([arguments.0.name=/Once$/])',
Expand Down Expand Up @@ -298,7 +302,7 @@
},
},

// TODO: Use global `/flat` config. Currently limited to svelte files because dprint is applied to their JS

Check warning on line 305 in eslint.config.js

View workflow job for this annotation

GitHub Actions / Lint

Unexpected 'todo' comment: 'TODO: Use global `/flat` config....'
rules: eslintConfigPrettier.rules,
},
{
Expand Down
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
"one-mutation": "^3.0.1",
"pretty-bytes": "^7.1.0",
"regex-join": "^2.1.0",
"select-dom": "^10.0.0-0",
"select-dom": "^10.0.0",
"shorten-repo-url": "^6.0.0",
"strip-indent": "^4.0.0",
"text-field-edit": "^4.1.1",
Expand Down
3 changes: 2 additions & 1 deletion source/features/action-pr-link.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as pageDetect from 'github-url-detection';
import {$, $closest} from 'select-dom';

import features from '../feature-manager.js';
import {getConversationNumber} from '../github-helpers/index.js';
Expand All @@ -13,7 +14,7 @@ function setSearchParameter(anchorElement: HTMLAnchorElement, name: string, valu
async function addForRepositoryActions(prLink: HTMLAnchorElement): Promise<void> {
const prNumber = prLink.textContent.slice(1);

const runLink = prLink.closest('.Box-row')!.querySelector('a:has(.Link--primary)')!;
const runLink = $('a:has(.Link--primary)', $closest('.Box-row', prLink));
setSearchParameter(runLink, 'pr', prNumber);
}

Expand Down
8 changes: 5 additions & 3 deletions source/features/actionable-pr-view-file.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import delegate, {type DelegateEvent} from 'delegate-it';
import * as pageDetect from 'github-url-detection';
import {$, $optional, elementExists} from 'select-dom';
import {
$, $closest, $optional, elementExists,
} from 'select-dom';

import features from '../feature-manager.js';
import {getBranches} from '../github-helpers/pr-branches.js';
Expand Down Expand Up @@ -40,7 +42,7 @@ async function handleMenuOpening({delegateTarget: menuButton}: DelegateEvent): P
return;
}

const fileHeader = menuButton.closest('[class*="diff-file-header"]')!;
const fileHeader = $closest('[class*="diff-file-header"]', menuButton);
if (isDeletedFile(fileHeader)) {
return;
}
Expand All @@ -56,7 +58,7 @@ async function handleMenuOpening({delegateTarget: menuButton}: DelegateEvent): P

// Legacy PR files view -- TODO: Drop after it is removed
function alter(viewFileLink: HTMLAnchorElement): void {
const filePath = viewFileLink.closest('[data-path]')!.getAttribute('data-path')!;
const filePath = $closest('[data-path]', viewFileLink).getAttribute('data-path')!;
rebuildFileLink(viewFileLink, filePath);
}

Expand Down
4 changes: 2 additions & 2 deletions source/features/actions-run-removal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import React from 'dom-chef';
import * as pageDetect from 'github-url-detection';
import SquareCircleIcon from 'octicons-plain-react/SquareCircle';
import TrashIcon from 'octicons-plain-react/Trash';
import {$, $optional} from 'select-dom';
import {$, $closest, $optional} from 'select-dom';

import features from '../feature-manager.js';
import observe from '../helpers/selector-observer.js';

function addQuickButtons(contextMenuIcon: HTMLElement): void {
const contextMenuDetails = contextMenuIcon.closest('details')!;
const contextMenuDetails = $closest('details', contextMenuIcon);

// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-arguments -- Wrong
const menuItem = $optional<HTMLElement>([
Expand Down
10 changes: 6 additions & 4 deletions source/features/batch-mark-files-as-viewed.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import {onAbort} from 'abort-utils';
import delegate, {type DelegateEvent} from 'delegate-it';
import * as pageDetect from 'github-url-detection';
import {$, $$, elementExists} from 'select-dom';
import {
$, $$, $closest, elementExists,
} from 'select-dom';

import features from '../feature-manager.js';
import showToast from '../github-helpers/toast.js';
Expand All @@ -28,7 +30,7 @@ const checkedSelector = is(
let previousFile: HTMLElement | undefined;

function remember(event: DelegateEvent<MouseEvent, HTMLElement>): void {
previousFile = event.delegateTarget.closest(fileSelector)!;
previousFile = $closest(fileSelector, event.delegateTarget);
}

function isChecked(file: HTMLElement): boolean {
Expand All @@ -43,7 +45,7 @@ function batchToggle(event: DelegateEvent<MouseEvent, HTMLElement>): void {
event.stopImmediatePropagation();

const files = $$(fileSelector);
const thisFile = event.delegateTarget.closest(fileSelector)!;
const thisFile = $closest(fileSelector, event.delegateTarget);
const isThisBeingFileChecked = isChecked(thisFile);

const selectedFiles = getItemsBetween(files, previousFile, thisFile);
Expand All @@ -70,7 +72,7 @@ function markAsViewedSelector(file: HTMLElement): string {
const markAsViewed = clickAll(markAsViewedSelector);

function onAltClick(event: DelegateEvent<MouseEvent, HTMLElement>): void {
const file = event.delegateTarget.closest(fileSelector)!;
const file = $closest(fileSelector, event.delegateTarget);
const newState = isChecked(file) ? 'viewed' : 'unviewed';

void showToast(async () => {
Expand Down
5 changes: 3 additions & 2 deletions source/features/ci-link.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import './ci-link.css';

import React from 'dom-chef';
import * as pageDetect from 'github-url-detection';
import {$closest, $closestOptional} from 'select-dom';

import features from '../feature-manager.js';
import api from '../github-helpers/api.js';
Expand Down Expand Up @@ -33,7 +34,7 @@ async function add(anchor: HTMLElement): Promise<void> {
}

if (!anchor.classList.contains('AppHeader-context-item')) {
anchor.closest('li')!.classList.add('d-flex');
$closest('li', anchor).classList.add('d-flex');
}

const endpoint = buildRepoUrl('commits/checks-statuses-rollups');
Expand All @@ -54,7 +55,7 @@ async function add(anchor: HTMLElement): Promise<void> {
);

// A parent is clipping the popup
anchor.closest('.AppHeader-context-full')?.style.setProperty('overflow', 'visible');
$closestOptional('.AppHeader-context-full', anchor)?.style.setProperty('overflow', 'visible');
}

async function init(signal: AbortSignal): Promise<void> {
Expand Down
6 changes: 3 additions & 3 deletions source/features/clean-conversation-headers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import React from 'dom-chef';
import elementReady from 'element-ready';
import * as pageDetect from 'github-url-detection';
import ArrowLeftIcon from 'octicons-plain-react/ArrowLeft';
import {$, $optional} from 'select-dom';
import {$, $closestOptional, $optional} from 'select-dom';

import features from '../feature-manager.js';
import getDefaultBranch from '../github-helpers/get-default-branch.js';
Expand Down Expand Up @@ -33,12 +33,12 @@ async function cleanPrHeader(summaryRow: HTMLElement): Promise<void> {
// Hide if it's the same as the opener (always) or merger
const shouldHideAuthor = pageDetect.isPRConversation()
// #7802
&& !summaryRow.closest([
&& !$closestOptional([
'div[class*="stickyHeader"]',
// TODO: Remove after July 2026
'.sticky-content',
'.gh-header-sticky',
])
], summaryRow)
// First link in the summary row is always the author
&& $('a', summaryRow).textContent === (await elementReady(prCreatorSelector))!.textContent;

Expand Down
12 changes: 7 additions & 5 deletions source/features/clean-conversation-sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import './clean-conversation-sidebar.css';

import React from 'dom-chef';
import * as pageDetect from 'github-url-detection';
import {$, $optional, elementExists} from 'select-dom';
import {
$, $closest, $optional, elementExists,
} from 'select-dom';

import features from '../feature-manager.js';
import {removeTextNodeContaining} from '../helpers/dom-utils.js';
Expand Down Expand Up @@ -64,11 +66,11 @@ function cleanSection(selector: string): boolean {
'details:has(> .discussion-sidebar-heading)', // Can edit sidebar, has a dropdown
'.discussion-sidebar-heading', // Cannot editor sidebar, has a plain heading
], container);
if (heading.closest(['form', '.discussion-sidebar-item'])!.querySelector(identifiers)) {
if ($closest(['form', '.discussion-sidebar-item'], heading).querySelector(identifiers)) {
return false;
}

const section = container.closest('.discussion-sidebar-item')!;
const section = $closest('.discussion-sidebar-item', container);
if (canEditSidebar()) {
getNodesAfter(heading).deleteContents();
section.classList.add('rgh-clean-sidebar');
Expand All @@ -85,15 +87,15 @@ async function cleanSidebarLegacy(sidebar: HTMLElement): Promise<void> {
// Assignees
const assignees = $('.js-issue-assignees');
if (assignees.children.length === 0) {
assignees.closest('.discussion-sidebar-item')!.remove();
$closest('.discussion-sidebar-item', assignees).remove();
} else {
const assignYourself = $optional('.js-issue-assign-self');
if (assignYourself) {
removeTextNodeContaining(assignYourself.previousSibling!, 'No one—');
$('[aria-label="Select assignees"] summary').append(
<span style={{fontWeight: 'normal'}}> – {assignYourself}</span>,
);
assignees.closest('.discussion-sidebar-item')!.classList.add('rgh-clean-sidebar');
$closest('.discussion-sidebar-item', assignees).classList.add('rgh-clean-sidebar');
}
}

Expand Down
8 changes: 5 additions & 3 deletions source/features/clean-repo-sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import './clean-repo-sidebar.css';
import domLoaded from 'dom-loaded';
import elementReady from 'element-ready';
import * as pageDetect from 'github-url-detection';
import {$, $optional, elementExists} from 'select-dom';
import {
$, $closest, $optional, elementExists,
} from 'select-dom';

import features from '../feature-manager.js';
import {buildRepoUrl} from '../github-helpers/index.js';
Expand All @@ -16,7 +18,7 @@ async function cleanReleases(): Promise<void> {
return;
}

const releasesSection = sidebarReleases.closest('.BorderGrid-cell')!;
const releasesSection = $closest('.BorderGrid-cell', sidebarReleases);
if (!elementExists('.octicon-tag', releasesSection)) {
// Hide the whole section if there's no releases
releasesSection.hidden = true;
Expand All @@ -25,7 +27,7 @@ async function cleanReleases(): Promise<void> {

// Collapse "Releases" section into previous section
releasesSection.classList.add('border-0', 'pt-md-0');
sidebarReleases.closest('.BorderGrid-row')!
$closest('.BorderGrid-row', sidebarReleases)
.previousElementSibling! // About’s .BorderGrid-row
.firstElementChild! // About’s .BorderGrid-cell
.classList
Expand Down
6 changes: 4 additions & 2 deletions source/features/clean-repo-tabs.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import React from 'dom-chef';
import elementReady from 'element-ready';
import * as pageDetect from 'github-url-detection';
import {$, $optional, countElements} from 'select-dom';
import {
$, $closest, $optional, countElements,
} from 'select-dom';
import {CachedFunction} from 'webext-storage-cache';

import features from '../feature-manager.js';
Expand Down Expand Up @@ -44,7 +46,7 @@ function onlyShowInDropdown(id: string): void {
return;
}

tabItem.closest('li')!.hidden = true;
$closest('li', tabItem).hidden = true;

const menuItem = $(`[data-menu-item$="${id}"]`);
menuItem.removeAttribute('data-menu-item');
Expand Down
4 changes: 2 additions & 2 deletions source/features/clear-pr-merge-commit-message.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'dom-chef';
import * as pageDetect from 'github-url-detection';
import {countElements} from 'select-dom';
import {$closest, countElements} from 'select-dom';

import features from '../feature-manager.js';
import getDefaultBranch from '../github-helpers/get-default-branch.js';
Expand All @@ -27,7 +27,7 @@ async function clear(messageField: HTMLTextAreaElement): Promise<void> {
// Trigger `fit-textareas` if enabled
messageField.dispatchEvent(new Event('input', {bubbles: true}));

const anchor = messageField.closest('div[data-has-label]')!;
const anchor = $closest('div[data-has-label]', messageField);

attachElement(anchor, {
after: () => (
Expand Down
4 changes: 2 additions & 2 deletions source/features/close-as-unplanned.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import delegate, {type DelegateEvent} from 'delegate-it';
import * as pageDetect from 'github-url-detection';
import {$} from 'select-dom';
import {$, $closest} from 'select-dom';

import features from '../feature-manager.js';
import {getFeatureId} from '../helpers/feature-helpers.js';
Expand All @@ -11,7 +11,7 @@ const id = getFeatureId(import.meta.url);
const unplannedCheckbox = 'input[name="state_reason"][value="not_planned"]';

function update(dropdown: HTMLElement): void {
const form = dropdown.closest('form')!;
const form = $closest('form', dropdown);
const radio = $(unplannedCheckbox, dropdown);
const mainButton = $('[name="comment_and_close"]', form);
const icon = $('.octicon-skip', dropdown);
Expand Down
Loading
Loading