From 5006933295258780321321ed3bdfe2a727509b91 Mon Sep 17 00:00:00 2001 From: Anton Medvedev Date: Thu, 12 Dec 2024 15:44:31 +0100 Subject: [PATCH] wip --- finder.js | 27 +++++++++++++++++++-------- finder.ts | 16 ++++++++++++++-- 2 files changed, 33 insertions(+), 10 deletions(-) diff --git a/finder.js b/finder.js index 9c0dc3e..6a68f32 100644 --- a/finder.js +++ b/finder.js @@ -11,10 +11,10 @@ export function finder(input, options) { } const defaults = { root: document.body, - idName: (name) => false, - attr: (name, value) => false, - className: (name) => wordLike(name), + idName: wordLike, + className: wordLike, tagName: (name) => true, + attr: (name, value) => false, timeoutMs: undefined, }; const config = { ...defaults, ...options }; @@ -32,7 +32,6 @@ export function finder(input, options) { i++; const paths = sort(combinations(stack)); for (const candidate of paths) { - console.log(selector(candidate)); if (unique(candidate, rootDocument)) { return selector(candidate); } @@ -40,6 +39,21 @@ export function finder(input, options) { } throw new Error(`Selector was not found.`); } +function wordLike(name) { + if (/^[a-z0-9\-]{3,}$/i.test(name)) { + const words = name.split(/-|[A-Z]/); + for (const word of words) { + if (word.length <= 2) { // No short words. + return false; + } + if (/[^aeiou]{3,}/i.test(word)) { // 3 or more consonants in a row. + return false; + } + } + return true; + } + return false; +} function tie(element, config) { const level = []; const elementId = element.getAttribute('id'); @@ -85,14 +99,11 @@ function tie(element, config) { if (nth !== undefined) { level.push({ name: `*:nth-child(${nth})`, - penalty: 5, + penalty: 9, }); } return level; } -function wordLike(name) { - return /^[a-zA-Z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(name); -} function selector(path) { let node = path[0]; let query = node.name; diff --git a/finder.ts b/finder.ts index 6442d7d..8055d06 100644 --- a/finder.ts +++ b/finder.ts @@ -63,7 +63,19 @@ export function finder(input: Element, options?: Partial): string { } function wordLike(name: string) { - return /^[a-z0-9\-]{3,}$/i.test(name) + if (/^[a-z0-9\-]{3,}$/i.test(name)) { + const words = name.split(/-|[A-Z]/) + for (const word of words) { + if (word.length <= 2) { // No short words. + return false + } + if (/[^aeiou]{3,}/i.test(word)) { // 3 or more consonants in a row. + return false + } + } + return true + } + return false } function tie(element: Element, config: Options): Knot[] { @@ -117,7 +129,7 @@ function tie(element: Element, config: Options): Knot[] { if (nth !== undefined) { level.push({ name: `*:nth-child(${nth})`, - penalty: 5, + penalty: 9, }) }