Skip to content

Commit

Permalink
Merge pull request #164 from ator-dev/eslint-flat-more
Browse files Browse the repository at this point in the history
Port ESLint config, improve strictness+consistency
  • Loading branch information
ator-dev authored Jun 26, 2024
2 parents 904b40e + 5c99649 commit e27e442
Show file tree
Hide file tree
Showing 39 changed files with 274 additions and 229 deletions.
2 changes: 0 additions & 2 deletions .eslintignore

This file was deleted.

14 changes: 0 additions & 14 deletions .eslintrc.cjs

This file was deleted.

45 changes: 45 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import eslint from "@eslint/js";
import tseslint from "typescript-eslint";

export default [
...tseslint.config({
files: [ "**/*.ts", "**/*.mts" ],
extends: [
eslint.configs.recommended,
...tseslint.configs.recommendedTypeChecked,
...tseslint.configs.stylisticTypeChecked,
{
languageOptions: {
parserOptions: {
project: true,
tsconfigRootDir: import.meta.dirname,
},
},
},
],
}),
{
files: [ "**/*.ts", "**/*.mts" ],
plugins: {
tseslint: tseslint.plugin,
},
rules: {
"indent": [ "error", "tab" ],
"semi": [ "error", "always" ],
"linebreak-style": [ "error", "unix" ],
"@typescript-eslint/array-type": [ "error", { default: "generic" } ],
"@typescript-eslint/no-empty-object-type": [ "error", { allowInterfaces: "always" } ],
"@typescript-eslint/no-empty-function": "off",
"@typescript-eslint/no-unused-vars": "warn",
"@typescript-eslint/prefer-optional-chain": "off",
"@typescript-eslint/dot-notation": "off",
"@typescript-eslint/no-floating-promises": "off",
"@typescript-eslint/no-misused-promises": "off",
"@typescript-eslint/require-await": "off",
"@typescript-eslint/no-unnecessary-type-assertion": "off",
},
},
{
ignores: [ "dist/**/*" ],
},
];
11 changes: 6 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"name": "mark-my-search",
"displayName": "Mark My Search",
"type": "module",
"scripts": {
"icons-convert": "bash -c 'mkdir -p icons/dist; SIZES=(16 32 48 64 96 128 240 300); for SIZE in ${SIZES[@]}; do inkscape icons/mms.svg -w $SIZE -h $SIZE -o icons/dist/mms-${SIZE}.png; done; SIZES=(32); for SIZE in ${SIZES[@]}; do inkscape icons/mms-off.svg -w $SIZE -h $SIZE -o icons/dist/mms-off-${SIZE}.png; done'",
"scripts-build": "rm --recursive dist; tsc --project tsconfig.json",
Expand All @@ -24,12 +25,12 @@
},
"homepage": "https://github.com/searchmarkers/mark-my-search#readme",
"devDependencies": {
"inkscape": "3.1.1",
"@types/firefox-webext-browser": "120.0.0",
"@types/chrome": "0.0.253",
"@typescript-eslint/eslint-plugin": "6.13.1",
"@typescript-eslint/parser": "6.13.1",
"eslint": "8.54.0",
"@types/firefox-webext-browser": "120.0.0",
"typescript-eslint": "8.0.0-alpha.30",
"eslint": "9.5.0",
"globals": "^15.6.0",
"inkscape": "3.1.1",
"typescript": "5.3.2"
}
}
12 changes: 9 additions & 3 deletions src/background.mts
Original file line number Diff line number Diff line change
Expand Up @@ -528,7 +528,7 @@ chrome.commands.onCommand.addListener(async commandString => {
(chrome.action["openPopup"] ?? (() => undefined))();
}
const [ tab ] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
const tabId = tab.id as number; // `tab.id` is always defined for this case.
const tabId = tab.id!; // `tab.id` is always defined for this case.
const commandInfo = parseCommand(commandString);
switch (commandInfo.type) {
case "openPopup": {
Expand Down Expand Up @@ -666,8 +666,14 @@ const handleMessage = async (message: Message.Background<true>): Promise<Message

chrome.runtime.onMessage.addListener((message: Message.Background, sender, sendResponse) => {
(async () => {
message.tabId ??= sender.tab?.id ?? (await chrome.tabs.query({ active: true, lastFocusedWindow: true }))[0].id;
handleMessage(message as Message.Background<true>).then(sendResponse);
const messageWithTabId: Message.Background<true> = ("tabId" in message
? message
: {
...message,
tabId: sender.tab?.id ?? (await chrome.tabs.query({ active: true, lastFocusedWindow: true }))[0].id ?? NaN,
}
);
handleMessage(messageWithTabId).then(sendResponse);
})();
return true;
});
Expand Down
26 changes: 13 additions & 13 deletions src/content.mts
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ interface ControlsInfo {
*/
const focusReturnToDocument = (): boolean => {
const activeElement = document.activeElement;
if (activeElement && activeElement.tagName === "INPUT" && activeElement.closest(`#${EleID.BAR}`)) {
(activeElement as HTMLInputElement).blur();
if (activeElement instanceof HTMLInputElement && activeElement.closest(`#${EleID.BAR}`)) {
activeElement.blur();
return true;
}
return false;
Expand All @@ -67,7 +67,7 @@ const getTermsFromSelection = (termTokens: TermTokens): ReadonlyArray<MatchTerm>
})()
.map(phrase => phrase.replace(/\p{Other}/gu, ""))
.filter(phrase => phrase !== "").map(phrase => new MatchTerm(phrase));
const termSelectors: Set<string> = new Set();
const termSelectors = new Set<string>();
for (const term of termsAll) {
const token = termTokens.get(term);
if (!termSelectors.has(token)) {
Expand Down Expand Up @@ -150,8 +150,8 @@ const styleElementsCleanup = () => {
if (style && style.textContent !== "") {
style.textContent = "";
}
const stylePaint = document.getElementById(EleID.STYLE_PAINT) as HTMLStyleElement | null;
if (stylePaint && stylePaint.sheet) {
const stylePaint = document.getElementById(EleID.STYLE_PAINT);
if (stylePaint instanceof HTMLStyleElement && stylePaint.sheet) {
while (stylePaint.sheet.cssRules.length) {
stylePaint.sheet.deleteRule(0);
}
Expand Down Expand Up @@ -216,16 +216,16 @@ const respondToCommand_factory = (
};
};

interface TermSetter extends TermReplacer, TermAppender {
setTerms: (termsNew: ReadonlyArray<MatchTerm>) => void;
interface TermSetter<Async = true> extends TermReplacer<Async>, TermAppender<Async> {
setTerms: (termsNew: ReadonlyArray<MatchTerm>) => Async extends true ? Promise<void> : void;
}

interface TermReplacer {
replaceTerm: (term: MatchTerm | null, index: number) => void;
interface TermReplacer<Async = true> {
replaceTerm: (term: MatchTerm | null, index: number) => Async extends true ? Promise<void> : void;
}

interface TermAppender {
appendTerm: (term: MatchTerm) => void;
interface TermAppender<Async = true> {
appendTerm: (term: MatchTerm) => Async extends true ? Promise<void> : void;
}

(() => {
Expand Down Expand Up @@ -267,7 +267,7 @@ interface TermAppender {
};
const updateTermStatus = (term: MatchTerm) => getToolbar(false)?.updateTermStatus(term);
const highlighter: AbstractEngineManager = new EngineManager(updateTermStatus, termTokens, termPatterns);
const termSetterInternal: TermSetter = {
const termSetterInternal: TermSetter<false> = {
setTerms: termsNew => {
if (itemsMatch(terms, termsNew, termEquals)) {
return;
Expand All @@ -284,7 +284,7 @@ interface TermAppender {
replaceTerm: (term, termIndex) => {
const termsOld: ReadonlyArray<MatchTerm> = [ ...terms ];
if (term) {
const termsNew = terms as Array<MatchTerm>;
const termsNew = [ ...terms ];
termsNew[termIndex] = term;
terms = termsNew;
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/modules/highlight/container-blocks.mts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const containerBlockSelector = `:not(${Array.from(highlightTags.flow).join(", ")
*/
const getContainerBlock = (element: HTMLElement): HTMLElement =>
// Always returns an element since "body" is not a flow tag.
element.closest(containerBlockSelector) as HTMLElement
element.closest(containerBlockSelector)!
;

export { containerBlockSelector, getContainerBlock };
33 changes: 16 additions & 17 deletions src/modules/highlight/engines/element.mts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const canHighlightElement = (rejectSelector: string, element: Element): boolean
!element.closest(rejectSelector) && element.tagName !== HIGHLIGHT_TAG_UPPER
;

type Properties = { [ELEMENT_JUST_HIGHLIGHTED]: boolean }
interface Properties { [ELEMENT_JUST_HIGHLIGHTED]: boolean }

type PropertiesElement<HasProperties = false> = BasePropertiesElement<Element, HasProperties>

Expand Down Expand Up @@ -78,9 +78,9 @@ class FlowNodeList {
let text = "";
let current = this.first;
do {
text += (current as FlowNodeListItem).value.textContent;
text += current!.value.textContent;
// eslint-disable-next-line no-cond-assign
} while (current = (current as FlowNodeListItem).next);
} while (current = current!.next);
return text;
}

Expand All @@ -90,11 +90,11 @@ class FlowNodeList {
}

*[Symbol.iterator] () {
let current = this.first;
let current = this.first!;
do {
yield current as FlowNodeListItem;
yield current;
// eslint-disable-next-line no-cond-assign
} while (current = (current as FlowNodeListItem).next);
} while (current = current.next!);
}
}

Expand Down Expand Up @@ -242,7 +242,7 @@ ${HIGHLIGHT_TAG} {
const text = node.textContent ?? "";
if (text.length === 0) {
node.remove();
return (nodeItemPrevious ? nodeItemPrevious.next : nodeItems.first) as FlowNodeListItem;
return (nodeItemPrevious ? nodeItemPrevious.next : nodeItems.first)!;
}
const parent = node.parentElement as Element;
(parent as PropertiesElement<true>)[ELEMENT_JUST_HIGHLIGHTED] = true;
Expand Down Expand Up @@ -281,7 +281,7 @@ ${HIGHLIGHT_TAG} {
const text = textAfterNode.textContent ?? "";
if (text.length === 0) {
textAfterNode.parentElement?.removeChild(textAfterNode);
return (nodeItemPrevious ? nodeItemPrevious.next : nodeItems.first) as FlowNodeListItem;
return (nodeItemPrevious ? nodeItemPrevious.next : nodeItems.first)!;
}
const parent = textAfterNode.parentNode as Node;
const textEndNode = document.createTextNode(text.substring(start, end));
Expand Down Expand Up @@ -309,19 +309,18 @@ ${HIGHLIGHT_TAG} {
const textFlow = nodeItems.getText();
for (const term of terms) {
let nodeItemPrevious: FlowNodeListItem | null = null;
let nodeItem = nodeItems.first as FlowNodeListItem;
let nodeItem = nodeItems.first!;
let textStart = 0;
let textEnd = nodeItem.value.length;
for (const match of textFlow.matchAll(this.termPatterns.get(term))) {
let highlightStart = match.index as number;
let highlightStart = match.index!;
const highlightEnd = highlightStart + match[0].length;
while (textEnd <= highlightStart) {
nodeItemPrevious = nodeItem;
nodeItem = nodeItem.next as FlowNodeListItem;
nodeItem = nodeItem.next!;
textStart = textEnd;
textEnd += nodeItem.value.length;
}
// eslint-disable-next-line no-constant-condition
while (true) {
// TODO join together nodes where possible
// TODO investigate why, under some circumstances, new empty highlight elements keep being produced
Expand All @@ -340,7 +339,7 @@ ${HIGHLIGHT_TAG} {
break;
}
nodeItemPrevious = nodeItem;
nodeItem = nodeItem.next as FlowNodeListItem;
nodeItem = nodeItem.next!;
textStart = textEnd;
textEnd += nodeItem.value.length;
}
Expand Down Expand Up @@ -386,7 +385,7 @@ ${HIGHLIGHT_TAG} {
nodeItems.push(node as Text);
break;
}}
node = node.nextSibling as ChildNode; // May be null (checked by loop condition)
node = node.nextSibling!; // May be null (checked by loop condition)
} while (node && visitSiblings);
};

Expand All @@ -410,7 +409,7 @@ ${HIGHLIGHT_TAG} {

getMutationUpdatesObserver () {
const rejectSelector = Array.from(highlightTags.reject).join(", ");
const elements: Set<HTMLElement> = new Set();
const elements = new Set<HTMLElement>();
let periodDateLast = 0;
let periodHighlightCount = 0;
let throttling = false;
Expand Down Expand Up @@ -444,10 +443,10 @@ ${HIGHLIGHT_TAG} {
};
return new MutationObserver(mutations => {
//mutationUpdates.disconnect();
const elementsJustHighlighted: Set<HTMLElement> = new Set();
const elementsJustHighlighted = new Set<HTMLElement>();
for (const mutation of mutations) {
const element = mutation.target.nodeType === Node.TEXT_NODE
? mutation.target.parentElement as HTMLElement
? mutation.target.parentElement!
: mutation.target as HTMLElement;
if (element) {
if ((element as PropertiesHTMLElement<true>)[ELEMENT_JUST_HIGHLIGHTED]) {
Expand Down
12 changes: 6 additions & 6 deletions src/modules/highlight/engines/highlight.mts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ type Flow = BaseFlow<true, BoxInfoRange>

type BoxInfo = BaseBoxInfo<true, BoxInfoRange>

type BoxInfoRange = { range: AbstractRange }
interface BoxInfoRange { range: AbstractRange }

const getName = (termToken: string) => "markmysearch-" + termToken;

class ExtendedHighlight {
readonly highlight: Highlight;
readonly boxInfoRanges: Map<BoxInfo, AbstractRange> = new Map();
readonly boxInfoRanges = new Map<BoxInfo, AbstractRange>();

constructor (...initialRanges: Array<AbstractRange>) {
this.highlight = new Highlight(...initialRanges);
Expand Down Expand Up @@ -61,8 +61,8 @@ class ExtendedHighlight {
}

class ExtendedHighlightRegistry {
readonly registry = CSS.highlights as HighlightRegistry;
readonly map: Map<string, ExtendedHighlight> = new Map();
readonly registry = CSS.highlights!;
readonly map = new Map<string, ExtendedHighlight>();

get size () {
return this.map.size;
Expand Down Expand Up @@ -94,7 +94,7 @@ class ExtendedHighlightRegistry {
}
}

type HighlightStyle = {
interface HighlightStyle {
opacity: number
lineThickness: number
lineStyle: "dotted" | "dashed" | "solid" | "double" | "wavy"
Expand All @@ -113,7 +113,7 @@ class HighlightEngine implements AbstractTreeCacheEngine {
readonly mutationUpdates: ReturnType<typeof getMutationUpdates>;

readonly highlights = new ExtendedHighlightRegistry();
readonly highlightedElements: Set<CachingHTMLElement<Flow>> = new Set();
readonly highlightedElements = new Set<CachingHTMLElement<Flow>>();

readonly terms = createContainer<ReadonlyArray<MatchTerm>>([]);
readonly hues = createContainer<ReadonlyArray<number>>([]);
Expand Down
Loading

0 comments on commit e27e442

Please sign in to comment.