Phone-hit guard: no blind spots for aliased, namespace and non-tsx IconButton; scope-aware PhoneHit check #156
4 changed files with 342 additions and 53 deletions
|
|
@ -1,40 +1,62 @@
|
|||
import { readdirSync, readFileSync } from 'fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { classLists, emitted, expectPhoneHitClasses, phoneHitClasses } from './phoneHitTestKit';
|
||||
import {
|
||||
classLists,
|
||||
emitted,
|
||||
expectPhoneHitClasses,
|
||||
uncoveredIconButtons,
|
||||
} from './phoneHitTestKit';
|
||||
|
||||
// Every IconButton under src carries a PhoneHit class, or is named here with the reason it has none. The per-group
|
||||
// suites pin which variant a listed file's buttons carry; this one sees files no group lists, so a new bare
|
||||
// IconButton fails here instead of shipping with a sub-44px phone hit area.
|
||||
const EXEMPT: Record<string, { indices: number[]; why: string }> = {
|
||||
'features/estate/EstateNavigator.tsx': {
|
||||
'app/features/estate/EstateNavigator.tsx': {
|
||||
indices: [0],
|
||||
why: 'Find a room sits in a css.Targets row that already gives it a 44 px phone target',
|
||||
},
|
||||
'features/lobby/LobbyHeader.tsx': {
|
||||
'app/features/lobby/LobbyHeader.tsx': {
|
||||
indices: [1],
|
||||
why: 'Members button, hidden on mobile',
|
||||
},
|
||||
};
|
||||
|
||||
const tsxFiles = (dir: string): string[] =>
|
||||
readdirSync(`${process.cwd()}/src/app/${dir}`, { withFileTypes: true }).flatMap((e) => {
|
||||
if (e.isDirectory()) return tsxFiles(`${dir}${e.name}/`);
|
||||
return e.name.endsWith('.tsx') ? [`${dir}${e.name}`] : [];
|
||||
// Every script file, not only .tsx: an IconButton can be rendered from a .ts or .js module too. A file that never
|
||||
// says IconButton is skipped; one that does is parsed and every mention of it must be a tag the guard can check.
|
||||
const SCRIPT = /\.(?:[cm]?[jt]s|[jt]sx)$/;
|
||||
const sourceFiles = (dir: string): string[] =>
|
||||
readdirSync(`${process.cwd()}/src/${dir}`, { withFileTypes: true }).flatMap((e) => {
|
||||
if (e.isDirectory()) return sourceFiles(`${dir}${e.name}/`);
|
||||
return SCRIPT.test(e.name) ? [`${dir}${e.name}`] : [];
|
||||
});
|
||||
|
||||
describe('phone hit areas: every IconButton is covered or named', () => {
|
||||
const scanned = sourceFiles('').flatMap((file) => {
|
||||
const src = readFileSync(`${process.cwd()}/src/${file}`, 'utf8');
|
||||
return src.includes('IconButton') ? [{ file, ...uncoveredIconButtons(src, file) }] : [];
|
||||
});
|
||||
|
||||
it('lists exactly the IconButtons without a PhoneHit class', () => {
|
||||
expect(scanned.length).toBeGreaterThan(0);
|
||||
const bare: Record<string, number[]> = {};
|
||||
tsxFiles('').forEach((file) => {
|
||||
const src = readFileSync(`${process.cwd()}/src/app/${file}`, 'utf8');
|
||||
if (!src.includes('<IconButton')) return;
|
||||
const missing = phoneHitClasses(src).flatMap((c, i) => (c === null ? [i] : []));
|
||||
scanned.forEach(({ file, bare: missing }) => {
|
||||
if (missing.length > 0) bare[file] = missing;
|
||||
});
|
||||
expect(bare).toEqual(
|
||||
Object.fromEntries(Object.entries(EXEMPT).map(([f, e]) => [f, e.indices]))
|
||||
);
|
||||
});
|
||||
|
||||
// An IconButton passed as a value (as={IconButton}), re-bound, re-exported or destructured cannot be tied to a
|
||||
// PhoneHit class, so the guard names it instead of passing over it. Render it as a <IconButton> tag, or extend the
|
||||
// guard to read the new form.
|
||||
it('finds no IconButton the guard cannot check', () => {
|
||||
const unhandled: Record<string, string[]> = {};
|
||||
scanned.forEach(({ file, unhandled: found }) => {
|
||||
if (found.length > 0) unhandled[file] = found;
|
||||
});
|
||||
expect(unhandled).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
// UrlPreviewCard's arrows are absolutely positioned by their own class; PhoneHit would set position: relative on them
|
||||
|
|
|
|||
|
|
@ -104,4 +104,16 @@ describe('what the PhoneHit class relies on', () => {
|
|||
expect(stack).toMatch(/direction="Column"/);
|
||||
expect(stack).toMatch(/gap="100"/);
|
||||
});
|
||||
|
||||
// The same column rhythm in the scrolling Sidebar: its 40 px buttons sit in a Column of Box gap="100" (4 px).
|
||||
it('the emoji sidebar column keeps its 4 px gap', () => {
|
||||
const src = readSource('components/emoji-board/components/Sidebar.tsx');
|
||||
const column = src.slice(
|
||||
src.indexOf('export function Sidebar('),
|
||||
src.indexOf('export const SidebarStack')
|
||||
);
|
||||
expect(column).toMatch(
|
||||
/<Box className=\{css\.SidebarContent\} direction="Column"[^>]*gap="100"/
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import {
|
|||
expectSizeTie,
|
||||
iconButtons,
|
||||
phoneHitOf,
|
||||
uncoveredIconButtons,
|
||||
} from './phoneHitTestKit';
|
||||
|
||||
describe('phone hit test kit', () => {
|
||||
|
|
@ -151,4 +152,125 @@ describe('phone hit test kit', () => {
|
|||
expect(() => check(wrongModule, ['PhoneHit'])).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('uncoveredIconButtons: the coverage guard is not blind to a spelling of IconButton', () => {
|
||||
const imp = "import { PhoneHit } from '../styles/PhoneHit.css';\n";
|
||||
const none = { bare: [], unhandled: [] };
|
||||
|
||||
it('sees an IconButton imported under an alias, as a tag', () => {
|
||||
const bare = "import { IconButton as IB } from 'folds';\nconst A = () => <IB />;";
|
||||
expect(uncoveredIconButtons(bare)).toEqual({ bare: [0], unhandled: [] });
|
||||
const ok = `${imp}import { IconButton as IB } from 'folds';\nconst A = () => <IB className={PhoneHit} />;`;
|
||||
expect(uncoveredIconButtons(ok)).toEqual(none);
|
||||
});
|
||||
|
||||
it('sees a namespace member tag', () => {
|
||||
const bare = "import * as F from 'folds';\nconst A = () => <F.IconButton />;";
|
||||
expect(uncoveredIconButtons(bare)).toEqual({ bare: [0], unhandled: [] });
|
||||
const ok = `${imp}import * as F from 'folds';\nconst A = () => <F.IconButton className={PhoneHit}></F.IconButton>;`;
|
||||
expect(uncoveredIconButtons(ok)).toEqual(none);
|
||||
});
|
||||
|
||||
it('fails loudly on an IconButton passed or bound as a value, and on a re-export', () => {
|
||||
const asProp =
|
||||
"import { IconButton } from 'folds';\nconst A = () => <Box as={IconButton} />;";
|
||||
expect(uncoveredIconButtons(asProp).unhandled).toEqual(['2:26']);
|
||||
const aliasValue =
|
||||
"import { IconButton as IB } from 'folds';\nconst A = () => <Box as={IB} />;";
|
||||
expect(uncoveredIconButtons(aliasValue).unhandled).toEqual(['2:26']);
|
||||
const rebound = "import { IconButton } from 'folds';\nconst B = IconButton;";
|
||||
expect(uncoveredIconButtons(rebound).unhandled).toEqual(['2:11']);
|
||||
const destructured = "import * as F from 'folds';\nconst { IconButton: IB } = F;";
|
||||
expect(uncoveredIconButtons(destructured).unhandled).toEqual(['2:9']);
|
||||
const member = "import * as F from 'folds';\nconst B = F.IconButton;";
|
||||
expect(uncoveredIconButtons(member).unhandled).toEqual(['2:13']);
|
||||
const indexed = "import * as F from 'folds';\nconst B = F['IconButton'];";
|
||||
expect(uncoveredIconButtons(indexed).unhandled).toEqual(['2:13']);
|
||||
expect(uncoveredIconButtons("export { IconButton } from 'folds';").unhandled).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('reads a non-.tsx file by its extension', () => {
|
||||
const ts =
|
||||
"import { IconButton } from 'folds';\nexport const x = <T,>(v: T) => <IconButton />;";
|
||||
expect(uncoveredIconButtons(ts, 'x.tsx').bare).toEqual([0]);
|
||||
const js = "import { IconButton } from 'folds';\nexport const B = IconButton;";
|
||||
expect(uncoveredIconButtons(js, 'x.ts').unhandled).toEqual(['2:18']);
|
||||
expect(uncoveredIconButtons(js, 'x.js').unhandled).toEqual(['2:18']);
|
||||
const jsx = "import { IconButton } from 'folds';\nexport const A = () => <IconButton />;";
|
||||
expect(uncoveredIconButtons(jsx, 'x.jsx').bare).toEqual([0]);
|
||||
});
|
||||
|
||||
it('does not count IconButtonX, a comment or a string as an IconButton', () => {
|
||||
const src =
|
||||
"import { IconButtonGroup } from 'folds';\n// IconButton\nconst a = 'IconButton';\nconst A = () => <IconButtonGroup />;";
|
||||
expect(uncoveredIconButtons(src)).toEqual(none);
|
||||
});
|
||||
|
||||
it('does not count a PhoneHit that an inner scope rebinds', () => {
|
||||
const tag = '<IconButton className={PhoneHit} />';
|
||||
const cases = [
|
||||
`const A = (PhoneHit) => ${tag};`,
|
||||
`const A = ({ PhoneHit }) => ${tag};`,
|
||||
`const A = ([a, PhoneHit]) => ${tag};`,
|
||||
`function A() { const PhoneHit = 'x'; return ${tag}; }`,
|
||||
`function A() { return ${tag}; var PhoneHit; }`,
|
||||
`function A() { if (a) { var PhoneHit = 'x'; } return ${tag}; }`,
|
||||
`function A() { { let { PhoneHit } = o; return ${tag}; } }`,
|
||||
`function A() { function PhoneHit() {} return ${tag}; }`,
|
||||
`function A() { for (const PhoneHit of xs) { return ${tag}; } }`,
|
||||
`function A() { try { f(); } catch (PhoneHit) { return ${tag}; } }`,
|
||||
`const A = function PhoneHit() { return ${tag}; };`,
|
||||
`function A() { switch (x) { case 1: const PhoneHit = 'x'; return ${tag}; } }`,
|
||||
];
|
||||
cases.forEach((c) => expect(uncoveredIconButtons(`${imp}${c}`).bare, c).toEqual([0]));
|
||||
// the same shapes without the rebinding count, and a rebinding that is not in scope does not hide it
|
||||
expect(uncoveredIconButtons(`${imp}const A = () => ${tag};`).bare).toEqual([]);
|
||||
expect(
|
||||
uncoveredIconButtons(`${imp}const f = (PhoneHit) => 1;\nconst A = () => ${tag};`).bare
|
||||
).toEqual([]);
|
||||
expect(uncoveredIconButtons(`${imp}function A() { return ${tag}; }`).bare).toEqual([]);
|
||||
});
|
||||
|
||||
it('does not count an import type of PhoneHit', () => {
|
||||
const tag = 'const A = () => <IconButton className={PhoneHit} />;';
|
||||
const typeOnly = `import type { PhoneHit } from '../styles/PhoneHit.css';\n${tag}`;
|
||||
expect(uncoveredIconButtons(typeOnly).bare).toEqual([0]);
|
||||
const typeSpecifier = `import { type PhoneHit } from '../styles/PhoneHit.css';\n${tag}`;
|
||||
expect(uncoveredIconButtons(typeSpecifier).bare).toEqual([0]);
|
||||
expect(uncoveredIconButtons(`${imp}${tag}`).bare).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('drawnPx reads the parsed tag, not its text', () => {
|
||||
it('ignores a size in a string, comment or other prop name', () => {
|
||||
expect(drawnPx('<IconButton title=" size=\'500\'">', '<Icon />')).toEqual({ px: 40 });
|
||||
expect(drawnPx('<IconButton data-size="600" iconSize="500">', '<Icon />')).toEqual({
|
||||
px: 40,
|
||||
});
|
||||
expect(
|
||||
drawnPx('<IconButton size="300">', '{/* <Icon size="500" /> */}<Icon size="50" />')
|
||||
).toEqual({
|
||||
px: 24,
|
||||
});
|
||||
expect(drawnPx('<IconButton size="300">', '{"<Icon size=\'500\' />"}')).toHaveProperty(
|
||||
'undetermined'
|
||||
);
|
||||
});
|
||||
|
||||
it('reads a size from a braced string, and the last size wins', () => {
|
||||
expect(drawnPx("<IconButton size={'300'}>", '<Icon size={"50"} />')).toEqual({ px: 24 });
|
||||
expect(drawnPx('<IconButton size="300" size="500">', '<Icon size="50" />')).toEqual({
|
||||
px: 40,
|
||||
});
|
||||
});
|
||||
|
||||
it('reads an Icon spread after a size, and a size past a braced prop with a > inside', () => {
|
||||
expect(drawnPx('<IconButton onClick={() => a > b} size="300">', '<Icon />')).toEqual({
|
||||
px: 32,
|
||||
});
|
||||
expect(drawnPx('<IconButton size="300">', '<Icon size="50" {...p} />')).toHaveProperty(
|
||||
'undetermined'
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -61,39 +61,78 @@ export const rulesFor = (css: string, selector: RegExp, media: string | undefine
|
|||
export const readSource = (file: string) =>
|
||||
readFileSync(`${process.cwd()}/src/app/${file}`, 'utf8');
|
||||
|
||||
/** The end of a JSX opening tag starting at `from`: its closing > outside any {} expression. */
|
||||
const tagEnd = (src: string, from: number) => {
|
||||
let depth = 0;
|
||||
let j = from;
|
||||
for (; j < src.length; j += 1) {
|
||||
if (src[j] === '{') depth += 1;
|
||||
else if (src[j] === '}') depth -= 1;
|
||||
else if (src[j] === '>' && depth === 0) break;
|
||||
}
|
||||
return j;
|
||||
};
|
||||
|
||||
const tsx = (src: string) =>
|
||||
ts.createSourceFile('source.tsx', src, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
|
||||
// The extension picks the script kind (.ts reads `<T>x` as an assertion, .tsx and .jsx read it as JSX).
|
||||
const tsx = (src: string, fileName = 'source.tsx') =>
|
||||
ts.createSourceFile(fileName, src, ts.ScriptTarget.Latest, true);
|
||||
|
||||
type Opening = ts.JsxOpeningElement | ts.JsxSelfClosingElement;
|
||||
|
||||
/** Every IconButton element (not IconButtonX) of a parsed source, in source order. */
|
||||
const isTag = (n: ts.Node): n is Opening =>
|
||||
ts.isJsxOpeningElement(n) || ts.isJsxSelfClosingElement(n);
|
||||
|
||||
/** Local names the source binds IconButton to by import: IconButton itself and any alias (IconButton as IB). */
|
||||
const iconButtonNames = (sf: ts.SourceFile) => {
|
||||
const names = new Set(['IconButton']);
|
||||
sf.statements.forEach((st) => {
|
||||
const nb = ts.isImportDeclaration(st) ? st.importClause?.namedBindings : undefined;
|
||||
if (nb && ts.isNamedImports(nb))
|
||||
nb.elements.forEach((e) => {
|
||||
if ((e.propertyName ?? e.name).text === 'IconButton') names.add(e.name.text);
|
||||
});
|
||||
});
|
||||
return names;
|
||||
};
|
||||
|
||||
/** Whether a JSX tag name is an IconButton: the plain or aliased identifier, or a namespace member (<F.IconButton>). */
|
||||
const isIconButtonTag = (tag: ts.JsxTagNameExpression, names: Set<string>) =>
|
||||
(ts.isIdentifier(tag) && names.has(tag.text)) ||
|
||||
(ts.isPropertyAccessExpression(tag) && tag.name.text === 'IconButton');
|
||||
|
||||
/** Every IconButton element (not IconButtonX) of a parsed source, in source order, however its tag is spelled. */
|
||||
const elements = (sf: ts.SourceFile) => {
|
||||
const names = iconButtonNames(sf);
|
||||
const found: Opening[] = [];
|
||||
const walk = (n: ts.Node) => {
|
||||
if (
|
||||
(ts.isJsxOpeningElement(n) || ts.isJsxSelfClosingElement(n)) &&
|
||||
ts.isIdentifier(n.tagName) &&
|
||||
n.tagName.text === 'IconButton'
|
||||
)
|
||||
found.push(n);
|
||||
if (isTag(n) && isIconButtonTag(n.tagName, names)) found.push(n);
|
||||
ts.forEachChild(n, walk);
|
||||
};
|
||||
walk(sf);
|
||||
return found;
|
||||
};
|
||||
|
||||
/** Every mention of IconButton that is not a JSX tag or the import itself: passed as a value (as={IconButton}),
|
||||
* re-bound, re-exported, reached by destructuring or by an element access. Such a render cannot be tied to a
|
||||
* PhoneHit class, so each is reported ("line:col") and the guard fails on it. */
|
||||
const unhandledMentions = (sf: ts.SourceFile) => {
|
||||
const names = iconButtonNames(sf);
|
||||
const out: string[] = [];
|
||||
const at = (n: ts.Node) => {
|
||||
const { line, character } = sf.getLineAndCharacterOfPosition(n.getStart());
|
||||
out.push(`${line + 1}:${character + 1}`);
|
||||
};
|
||||
const walk = (n: ts.Node) => {
|
||||
if (ts.isIdentifier(n) && names.has(n.text)) {
|
||||
const p = n.parent;
|
||||
const tagged = (x: ts.Node) =>
|
||||
(isTag(x) || ts.isJsxClosingElement(x)) && x.tagName === (n as ts.Node);
|
||||
const member =
|
||||
ts.isPropertyAccessExpression(p) &&
|
||||
p.name === n &&
|
||||
(isTag(p.parent) || ts.isJsxClosingElement(p.parent)) &&
|
||||
p.parent.tagName === p;
|
||||
if (!ts.isImportSpecifier(p) && !tagged(p) && !member) at(n);
|
||||
} else if (
|
||||
ts.isStringLiteralLike(n) &&
|
||||
n.text === 'IconButton' &&
|
||||
ts.isElementAccessExpression(n.parent)
|
||||
)
|
||||
at(n);
|
||||
ts.forEachChild(n, walk);
|
||||
};
|
||||
walk(sf);
|
||||
return out;
|
||||
};
|
||||
|
||||
const bodyOf = (el: Opening) =>
|
||||
ts.isJsxOpeningElement(el) && ts.isJsxElement(el.parent)
|
||||
? el.getSourceFile().text.slice(el.end, el.parent.closingElement.getStart())
|
||||
|
|
@ -105,29 +144,94 @@ export const iconButtons = (src: string) =>
|
|||
|
||||
export const iconButtonTags = (src: string) => iconButtons(src).map((b) => b.tag);
|
||||
|
||||
/** Local names the source imports from the PhoneHit.css module (as written, not aliased). */
|
||||
/** Local names the source imports as values from the PhoneHit.css module (as written, not aliased). An
|
||||
* `import type`, or a `type` specifier, binds no value and is not read. */
|
||||
const importedHits = (sf: ts.SourceFile) =>
|
||||
new Set(
|
||||
sf.statements.flatMap((st) => {
|
||||
const nb = ts.isImportDeclaration(st) ? st.importClause?.namedBindings : undefined;
|
||||
if (!ts.isImportDeclaration(st) || !ts.isStringLiteral(st.moduleSpecifier)) return [];
|
||||
const nb = st.importClause?.namedBindings;
|
||||
return nb &&
|
||||
!st.importClause?.isTypeOnly &&
|
||||
ts.isNamedImports(nb) &&
|
||||
ts.isStringLiteral((st as ts.ImportDeclaration).moduleSpecifier) &&
|
||||
/^(\.\.\/)+styles\/PhoneHit\.css$/.test(
|
||||
((st as ts.ImportDeclaration).moduleSpecifier as ts.StringLiteral).text
|
||||
)
|
||||
? nb.elements.filter((e) => !e.propertyName).map((e) => e.name.text)
|
||||
/^(\.\.\/)+styles\/PhoneHit\.css$/.test(st.moduleSpecifier.text)
|
||||
? nb.elements.filter((e) => !e.propertyName && !e.isTypeOnly).map((e) => e.name.text)
|
||||
: [];
|
||||
})
|
||||
);
|
||||
|
||||
const bindingNames = (b: ts.BindingName): string[] =>
|
||||
ts.isIdentifier(b)
|
||||
? [b.text]
|
||||
: b.elements.flatMap((e) => (ts.isOmittedExpression(e) ? [] : bindingNames(e.name)));
|
||||
|
||||
const declaresVar = (list: ts.VariableDeclarationList, name: string) =>
|
||||
list.declarations.some((d) => bindingNames(d.name).includes(name));
|
||||
|
||||
/** Whether `var name` is declared anywhere in a function body, outside nested functions (var hoists to the function). */
|
||||
const hoistsVar = (fn: ts.Node, name: string) => {
|
||||
let found = false;
|
||||
const walk = (n: ts.Node) => {
|
||||
if (found || (n !== fn && ts.isFunctionLike(n))) return;
|
||||
if (
|
||||
ts.isVariableDeclarationList(n) &&
|
||||
// eslint-disable-next-line no-bitwise -- NodeFlags is a bit set; var is the one declaration kind with neither flag
|
||||
(n.flags & ts.NodeFlags.BlockScoped) === 0 &&
|
||||
declaresVar(n, name)
|
||||
)
|
||||
found = true;
|
||||
ts.forEachChild(n, walk);
|
||||
};
|
||||
walk(fn);
|
||||
return found;
|
||||
};
|
||||
|
||||
/** Whether one scope node declares `name` of its own: parameters, a function expression's own name, block-level
|
||||
* let/const/function/class, a for-loop head or a catch variable. */
|
||||
const scopeDeclares = (scope: ts.Node, name: string): boolean => {
|
||||
const inStatements = (sts: readonly ts.Statement[]) =>
|
||||
sts.some(
|
||||
(st) =>
|
||||
(ts.isVariableStatement(st) && declaresVar(st.declarationList, name)) ||
|
||||
((ts.isFunctionDeclaration(st) || ts.isClassDeclaration(st)) && st.name?.text === name)
|
||||
);
|
||||
if (ts.isBlock(scope) || ts.isModuleBlock(scope)) return inStatements(scope.statements);
|
||||
if (ts.isCaseBlock(scope)) return inStatements(scope.clauses.flatMap((c) => [...c.statements]));
|
||||
if (ts.isFunctionLike(scope))
|
||||
return (
|
||||
scope.parameters.some((p) => bindingNames(p.name).includes(name)) ||
|
||||
((ts.isFunctionExpression(scope) || ts.isClassExpression(scope)) &&
|
||||
scope.name?.text === name) ||
|
||||
hoistsVar(scope, name)
|
||||
);
|
||||
if (ts.isForStatement(scope) || ts.isForInStatement(scope) || ts.isForOfStatement(scope))
|
||||
return (
|
||||
!!scope.initializer &&
|
||||
ts.isVariableDeclarationList(scope.initializer) &&
|
||||
declaresVar(scope.initializer, name)
|
||||
);
|
||||
if (ts.isCatchClause(scope))
|
||||
return (
|
||||
!!scope.variableDeclaration && bindingNames(scope.variableDeclaration.name).includes(name)
|
||||
);
|
||||
return false;
|
||||
};
|
||||
|
||||
/** Whether an inner scope between the identifier and the module rebinds its name, so it is not the import. */
|
||||
const shadowed = (id: ts.Identifier) => {
|
||||
for (let n: ts.Node | undefined = id.parent; n && !ts.isSourceFile(n); n = n.parent)
|
||||
if (scopeDeclares(n, id.text)) return true;
|
||||
return false;
|
||||
};
|
||||
|
||||
const MERGERS = new Set(['classNames', 'clsx', 'cx']);
|
||||
|
||||
/** The PhoneHit* class an IconButton carries, or null. className must appear exactly once, with no props spread
|
||||
* after it (a spread can override it at runtime), and its expression must be: the bare identifier; a classNames /
|
||||
* clsx / cx call with it as a direct argument; or a template with it as a direct span. The identifier must occur
|
||||
* nowhere else in the expression, so a key, a member, a closure, a conditional or a comma can never carry it. When
|
||||
* `imported` is given, the identifier must also be a binding imported from the PhoneHit.css module. */
|
||||
* `imported` is given, the identifier must also resolve to a value binding imported from the PhoneHit.css module
|
||||
* (not an `import type`, not rebound by an inner scope). */
|
||||
const hitOf = (el: Opening, imported?: Set<string>): string | null => {
|
||||
const props = el.attributes.properties;
|
||||
const at = props.flatMap((p, i) =>
|
||||
|
|
@ -139,7 +243,9 @@ const hitOf = (el: Opening, imported?: Set<string>): string | null => {
|
|||
attr.initializer && ts.isJsxExpression(attr.initializer) && attr.initializer.expression;
|
||||
if (!expr) return null;
|
||||
const isHit = (n: ts.Node): n is ts.Identifier =>
|
||||
ts.isIdentifier(n) && /^PhoneHit\w*$/.test(n.text) && (!imported || imported.has(n.text));
|
||||
ts.isIdentifier(n) &&
|
||||
/^PhoneHit\w*$/.test(n.text) &&
|
||||
(!imported || (imported.has(n.text) && !shadowed(n)));
|
||||
let direct: ts.Node[] = [];
|
||||
if (ts.isIdentifier(expr)) direct = [expr];
|
||||
else if (
|
||||
|
|
@ -174,6 +280,18 @@ export const phoneHitClasses = (src: string) => {
|
|||
return elements(sf).map((el) => hitOf(el, imported));
|
||||
};
|
||||
|
||||
/** What a source file leaves uncovered: the indices (source order) of its IconButton elements without a PhoneHit
|
||||
* class, and the "line:col" of every mention of IconButton that is not a tag and so cannot be checked at all. The
|
||||
* fileName picks the parser (.ts, .tsx, .js, ...). */
|
||||
export const uncoveredIconButtons = (src: string, fileName = 'source.tsx') => {
|
||||
const sf = tsx(src, fileName);
|
||||
const imported = importedHits(sf);
|
||||
return {
|
||||
bare: elements(sf).flatMap((el, i) => (hitOf(el, imported) === null ? [i] : [])),
|
||||
unhandled: unhandledMentions(sf),
|
||||
};
|
||||
};
|
||||
|
||||
/** The class each IconButton must carry, in source order (null = must carry none): the variant is chosen by the
|
||||
* button's drawn size and whether a clipping container or neighbours surround it, so a swapped variant is a wrong
|
||||
* hit area. The name must also be the one PhoneHit.css exports, not a local of the same name. */
|
||||
|
|
@ -192,29 +310,44 @@ const ICON_PX: Record<string, number> = {
|
|||
};
|
||||
|
||||
/** The size prop of a tag: its literal value, the default when absent, or undefined when it is an expression. */
|
||||
const sizeProp = (tag: string) => {
|
||||
const sizeProp = (el: Opening) => {
|
||||
const props = el.attributes.properties;
|
||||
// props spread in may carry a size of their own
|
||||
if (tag.includes('{...')) return undefined;
|
||||
const m = tag.match(/\ssize=(?:"(\w+)"|\{([^}]*)\})/);
|
||||
if (!m) return '400';
|
||||
return m[1] ?? m[2].match(/^'(\w+)'$/)?.[1];
|
||||
if (props.some(ts.isJsxSpreadAttribute)) return undefined;
|
||||
const sizes = props.filter(
|
||||
(p): p is ts.JsxAttribute =>
|
||||
ts.isJsxAttribute(p) && ts.isIdentifier(p.name) && p.name.text === 'size'
|
||||
);
|
||||
if (sizes.length === 0) return '400';
|
||||
const init = sizes[sizes.length - 1].initializer;
|
||||
const lit = init && ts.isJsxExpression(init) ? init.expression : init;
|
||||
return lit && ts.isStringLiteralLike(lit) ? lit.text : undefined;
|
||||
};
|
||||
|
||||
/** The px an IconButton draws, from its size prop and the Icon inside; undefined with a reason when the source
|
||||
* does not say (a variable size, no Icon, Icons of different sizes). */
|
||||
* does not say (a variable size, no Icon, Icons of different sizes). Both are read off the parsed tag and body. */
|
||||
export const drawnPx = (tag: string, body: string): { px: number } | { undetermined: string } => {
|
||||
const pad = BUTTON_PAD[sizeProp(tag) ?? ''];
|
||||
let button: Opening | undefined;
|
||||
const first = (n: ts.Node) => {
|
||||
if (!button && isTag(n)) button = n;
|
||||
else if (!button) ts.forEachChild(n, first);
|
||||
};
|
||||
first(tsx(tag.endsWith('/>') ? tag : `${tag}</x>`));
|
||||
const pad = BUTTON_PAD[(button && sizeProp(button)) ?? ''];
|
||||
if (pad === undefined)
|
||||
return { undetermined: 'size of the IconButton is not a literal (or props are spread in)' };
|
||||
const icons = [...body.matchAll(/<Icon(?=[\s>/])/g)].map((m) => {
|
||||
const t = body.slice(m.index, tagEnd(body, m.index ?? 0) + 1);
|
||||
return ICON_PX[sizeProp(t) ?? ''];
|
||||
});
|
||||
const icons: (number | undefined)[] = [];
|
||||
const find = (n: ts.Node) => {
|
||||
if (isTag(n) && ts.isIdentifier(n.tagName) && n.tagName.text === 'Icon')
|
||||
icons.push(ICON_PX[sizeProp(n) ?? '']);
|
||||
ts.forEachChild(n, find);
|
||||
};
|
||||
find(tsx(`<>${body}</>`));
|
||||
if (icons.length === 0) return { undetermined: 'no <Icon> inside' };
|
||||
if (icons.some((p) => p === undefined))
|
||||
return { undetermined: 'size of an Icon is not a literal (or props are spread in)' };
|
||||
if (new Set(icons).size > 1) return { undetermined: 'Icons of different sizes inside' };
|
||||
return { px: icons[0] + 2 * pad };
|
||||
return { px: (icons[0] as number) + 2 * pad };
|
||||
};
|
||||
|
||||
/** Per file, per IconButton index (source order): why its drawn size cannot be derived from the source. */
|
||||
|
|
|
|||
Loading…
Reference in a new issue