Historically, much of the UI used title case. This PR adds a lint check
that reports title case UI text so it can be converted to sentence case,
and converts the existing text.
- `site/scripts/check-sentence-case.mjs` runs as `pnpm
lint:sentence-case` and is part of `pnpm lint`. It reads JSX text and
string/template literals from the TypeScript AST and skips literals that
are code rather than UI text (imports, types, property names, tagged
templates, values of JSX attributes that are not displayed such as
`className` or `style`, and operands of `===`/`case` comparisons). JSX
text across inline elements and conditional JSX is checked as one
phrase. `--fix` lowercases the reported words. The checker is a
heuristic: it is not meant to model every code shape, so use a
`sentence-case-expect` comment where it guesses wrong.
- Proper nouns (Coder products, role names, third-party products,
protocols, font names) live in `PROPER_NOUNS`. For other deliberate
exceptions, a `sentence-case-expect` comment on the line above
suppresses the report and fails when that line no longer needs it.
- Existing UI text is converted to sentence case, and tests that assert
on it are updated.
- Deployment option lookups (`useDeploymentOptions`) now use CLI flags
instead of display names, so they do not depend on UI wording.
## Performance
`pnpm lint:sentence-case` takes **1.6 s** and is 2% to 4.5% of `pnpm
lint`. Measured on 82317c925e in a dev workspace (Xeon Platinum 8375C,
16 vCPUs, Node 22.23.4, TypeScript 6.0.2, warm file cache). CI buffers
the output of the lint steps, so its log has no per-step times to
compare against.
| Measurement (20 runs) | Result |
|---|---|
| Wall time | 1.64 s mean, 0.03 s standard deviation, 1.62 s to 1.71 s |
| CPU time | 3.0 s |
| Peak memory (RSS) | 154 MB, of which 116 MB is Node with `typescript`
loaded |
| Input | 1,301 of the 2,199 `.ts` and `.tsx` files in `site/src` (the
rest are excluded), 210,684 lines, 6.1 MB |
| Throughput | About 130,000 lines per second |
| Time per file | 0.5 ms median, 3 ms at the 95th percentile, 76 ms
maximum (`src/api/api.ts`, 121 KB) |
Each step of `pnpm lint`, median wall time of 5 runs:
| Step | Wall time |
|---|---|
| `lint:check` (Biome) | 0.96 s |
| `lint:oxlint` | 0.32 s |
| `lint:types` (`tsc`) | 5.8 s with its incremental cache, 45 s without
|
| `lint:circular-deps` | 5.7 s |
| `lint:compiler` | 15.6 s |
| `lint:sentence-case` | 1.6 s |
| `knip` | 6.6 s |
| All of `pnpm lint` | 37 s with the `tsc` cache, 76 s without |
<details>
<summary>Where the time goes, scaling, and limits</summary>
Phases of one run, from in-process timers. The split between parsing and
checking is approximate.
| Phase | Time | Share |
|---|---|---|
| Node startup | 0.03 s | 2% |
| Load the `typescript` module | 0.32 s | 20% |
| Find and read the files | 0.04 s | 2% |
| Parse (`ts.createSourceFile`) | 0.83 s | 52% |
| Check logic | 0.38 s | 24% |
Scaling, from synthetic inputs passed to `checkSource` (median of 3 to 5
warm runs):
- Clean input is linear in size: 0.2 ms to 0.35 ms per KB for one file
from 54 KB to 7 MB. 100,000 string literals take 0.3 s, 100,000 sibling
JSX elements take 0.8 s, and JSX nested 800 levels deep takes 10 ms.
- Conditional JSX stays bounded by the 64-variant cap: 1 to 48
conditional children in one element take at most 3.4 ms.
- Reporting and fixing add no measurable time. On the merge base with
`main` (378 reports in 175 files), a check, `--fix`, and a second
`--fix` each take 1.6 s to 1.7 s.
- The 21 unit tests run in about 30 ms, 1.7 s including Vitest startup.
Two limits, neither reachable with the current source:
- Time is quadratic in the reports for one file, because the fixed text
is rebuilt once per report. A 3.5 MB file takes 0.7 s clean and 18.0 s
with 12,800 reports. The most reports in one file on the merge base is
16.
- One JSX element with more than about 120,000 text phrases fails with
`RangeError: Maximum call stack size exceeded`, because the phrases are
spread into `push`.
</details>
---------
Co-authored-by: Jake Howell <jake@hwll.me>
796 lines
23 KiB
JavaScript
796 lines
23 KiB
JavaScript
/**
|
||
* Sentence case checker.
|
||
*
|
||
* The UI uses sentence case: capitalize the first word of a phrase and
|
||
* proper nouns only ("Create workspace", not "Create Workspace"). This
|
||
* script reports user-facing text in src/ that uses title case instead.
|
||
*
|
||
* Text is read from the TypeScript AST: JSX text plus string and template
|
||
* literals. Literals that are not displayed text are skipped: module
|
||
* specifiers, type positions, property names, tagged templates, values
|
||
* of JSX attributes that are not displayed (className, style, href), and
|
||
* operands of equality checks or `case` clauses (those usually compare
|
||
* against API values).
|
||
*
|
||
* A phrase starts at a capitalized word and runs until sentence or list
|
||
* punctuation, or an opening bracket or quote. A word is reported when it
|
||
* is not the first word of its phrase, looks like a regular capitalized
|
||
* word ("Workspace"), and is not part of a proper noun from PROPER_NOUNS.
|
||
* Lowercase words do not end a phrase, so both "Create a Template" and
|
||
* "Browse other Templates" are reported. Acronyms ("SSH") and mixed-case
|
||
* names ("GitHub") are never reported.
|
||
*
|
||
* For deliberate exceptions, put a comment containing
|
||
* "sentence-case-expect" on the line above the text. Above a template
|
||
* literal that spans several lines, the comment applies to the whole
|
||
* literal. Like @ts-expect-error, the check fails when the comment has
|
||
* nothing to report, so stale exceptions do not accumulate.
|
||
*
|
||
* Usage: node scripts/check-sentence-case.mjs [--fix]
|
||
*/
|
||
import { readdirSync, readFileSync, writeFileSync } from "node:fs";
|
||
import { join, relative } from "node:path";
|
||
import { fileURLToPath } from "node:url";
|
||
import ts from "typescript";
|
||
|
||
const EXPECT_COMMENT = "sentence-case-expect";
|
||
|
||
// Names that keep their capitalization. Single words only need listing
|
||
// when they look like regular words; acronyms and mixed-case names such
|
||
// as "SSH" or "GitHub" are already allowed.
|
||
const PROPER_NOUNS = [
|
||
// Coder products, features, and built-in role names.
|
||
"Agent Hours",
|
||
"AI Gateway",
|
||
"AI Gateway Proxy",
|
||
"AI Governance",
|
||
"Coder",
|
||
"Coder Agents",
|
||
"Coder Agents User",
|
||
"Codernauts",
|
||
"Coder Desktop",
|
||
"Coder Privacy Policy",
|
||
"Coder Registry",
|
||
"Coder Technologies",
|
||
"Coder Workspaces",
|
||
"Community",
|
||
"Dynamic Parameters",
|
||
"Open in Coder",
|
||
"Organization Workspace Access",
|
||
"Premium",
|
||
"Template Admin",
|
||
"Terms of Service",
|
||
"Web Terminal",
|
||
"Workspace Proxy",
|
||
|
||
// Days of the week.
|
||
"Monday",
|
||
"Tuesday",
|
||
"Wednesday",
|
||
"Thursday",
|
||
"Friday",
|
||
"Saturday",
|
||
"Sunday",
|
||
|
||
// Third-party products and companies.
|
||
"Splunk",
|
||
"Anthropic",
|
||
"Azure Repos",
|
||
"Bedrock",
|
||
"Claude Platform",
|
||
"Copilot",
|
||
"Discord",
|
||
"Git",
|
||
"Google Cloud",
|
||
"Inc",
|
||
"JetBrains Gateway",
|
||
"JetBrains Toolbox",
|
||
"Markdown",
|
||
"Mermaid",
|
||
"React",
|
||
"Terraform",
|
||
"Unicode",
|
||
"Unix",
|
||
"VS Code",
|
||
"VS Code Desktop",
|
||
"VS Code Insiders",
|
||
"VS Code Remote SSH",
|
||
"VSCode Insiders",
|
||
"Visual Studio Code",
|
||
|
||
// Standards and protocols.
|
||
"Cross-Origin Resource Sharing",
|
||
"Dynamic Client Registration",
|
||
"NAT Port Mapping Protocol",
|
||
"OpenID Connect",
|
||
"Port Control Protocol",
|
||
"Universal Plug and Play",
|
||
|
||
// Font names, shown in the terminal font picker.
|
||
"Courier New",
|
||
"Fira Code",
|
||
"Geist Mono",
|
||
"Geist Mono Variable",
|
||
"Geist Variable",
|
||
"IBM Plex Mono",
|
||
"JetBrains Mono",
|
||
"Liberation Mono",
|
||
"Lucida Console",
|
||
"Lucida Sans Typewriter",
|
||
"Source Code Pro",
|
||
"Terminal Symbols",
|
||
];
|
||
|
||
// Generated code, tests, and fixture data, plus files whose text is
|
||
// mostly names (people and job titles).
|
||
const EXCLUDED_FILE_PATTERNS = [
|
||
/Generated\.ts$/,
|
||
/\.(stories|test|jest)\.tsx?$/,
|
||
/(^|\/)(mocks|storybookData|storybookUtils)\.tsx?$/,
|
||
/(^|\/)(testHelpers|storybookData)\//,
|
||
/[fF]ixtures(\.tsx?$|\/)/,
|
||
/^src\/pages\/CoderCupPage\/roster\.ts$/,
|
||
];
|
||
|
||
// Proper nouns as lists of words, keyed by their first word, so a token is
|
||
// compared only with the nouns that can start at it.
|
||
const properNounsByFirstWord = new Map();
|
||
for (const noun of PROPER_NOUNS) {
|
||
const words = noun.split(" ");
|
||
const nouns = properNounsByFirstWord.get(words[0]) ?? [];
|
||
nouns.push(words);
|
||
properNounsByFirstWord.set(words[0], nouns);
|
||
}
|
||
|
||
/**
|
||
* Returns true when `word` is `nounWord`, a hyphenated compound of it like
|
||
* "Anthropic-compatible", or its possessive like "Coder's".
|
||
*/
|
||
function matchesNounWord(word, nounWord) {
|
||
return (
|
||
word === nounWord ||
|
||
word.startsWith(`${nounWord}-`) ||
|
||
word === `${nounWord}'s` ||
|
||
word === `${nounWord}’s`
|
||
);
|
||
}
|
||
|
||
/**
|
||
* Returns the proper nouns whose first word matches `word`, looked up by
|
||
* each first word that matchesNounWord accepts for it.
|
||
*/
|
||
function properNounsStartingAt(word) {
|
||
const firstWords = [word];
|
||
if (word.endsWith("'s") || word.endsWith("’s")) {
|
||
firstWords.push(word.slice(0, -2));
|
||
}
|
||
for (let i = word.indexOf("-"); i !== -1; i = word.indexOf("-", i + 1)) {
|
||
firstWords.push(word.slice(0, i));
|
||
}
|
||
return firstWords.flatMap(
|
||
(firstWord) => properNounsByFirstWord.get(firstWord) ?? [],
|
||
);
|
||
}
|
||
|
||
// Surrounding punctuation that is not part of a word, such as quotes,
|
||
// brackets, and sentence punctuation.
|
||
const LEADING_PUNCTUATION = /^[^\p{L}\p{N}]+/u;
|
||
const TRAILING_PUNCTUATION = /[^\p{L}\p{N}]+$/u;
|
||
|
||
// A regular capitalized word, like "Workspace" or "Don't".
|
||
const CAPITALIZED_WORD = /^[A-Z][a-z]+(?:['’-][a-z]+)*$/;
|
||
|
||
// Punctuation that ends a sentence, label, or list item, so the next
|
||
// word starts a new phrase and may be capitalized ("GitHub, GitLab").
|
||
const PHRASE_END = /[.!?:;,]["'’)\]]*$/;
|
||
|
||
/**
|
||
* Returns the title case words in `text`. Each result has the word's
|
||
* offset in `text` and the word itself.
|
||
*/
|
||
export function findTitleCaseWords(text) {
|
||
const tokens = [];
|
||
for (const match of text.matchAll(/\S+/g)) {
|
||
const leading = match[0].match(LEADING_PUNCTUATION)?.[0] ?? "";
|
||
const word = match[0]
|
||
.slice(leading.length)
|
||
.replace(TRAILING_PUNCTUATION, "");
|
||
tokens.push({
|
||
offset: match.index + leading.length,
|
||
raw: match[0],
|
||
word,
|
||
// A leading bracket or quote starts a new phrase, e.g.
|
||
// "Use (Recommended)" is a label followed by a note.
|
||
startsPhrase: leading.length > 0,
|
||
});
|
||
}
|
||
|
||
// Indexes of tokens that belong to a proper noun.
|
||
const properNounTokens = new Set();
|
||
for (let i = 0; i < tokens.length; i++) {
|
||
for (const nounWords of properNounsStartingAt(tokens[i].word)) {
|
||
const matches =
|
||
i + nounWords.length <= tokens.length &&
|
||
nounWords.every((w, j) => matchesNounWord(tokens[i + j].word, w));
|
||
if (matches) {
|
||
for (let j = 0; j < nounWords.length; j++) {
|
||
properNounTokens.add(i + j);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
const results = [];
|
||
let inPhrase = false;
|
||
for (let i = 0; i < tokens.length; i++) {
|
||
const token = tokens[i];
|
||
const capitalized = /^[A-Z]/.test(token.word);
|
||
if (token.raw.includes(SUBSTITUTION)) {
|
||
// Unknown text; keep the current phrase, if any, going.
|
||
} else if (!inPhrase || token.startsPhrase) {
|
||
// A lowercase word outside a phrase may continue text from
|
||
// elsewhere, so only a capitalized word starts a phrase.
|
||
inPhrase = capitalized;
|
||
} else if (
|
||
capitalized &&
|
||
CAPITALIZED_WORD.test(token.word) &&
|
||
!properNounTokens.has(i)
|
||
) {
|
||
results.push({ offset: token.offset, word: token.word });
|
||
}
|
||
if (PHRASE_END.test(token.raw)) {
|
||
inPhrase = false;
|
||
}
|
||
}
|
||
return results;
|
||
}
|
||
|
||
// JSX attributes whose values are displayed. Values of other attributes,
|
||
// such as className, style, or href, are code and are never checked.
|
||
const DISPLAY_ATTRIBUTES = new Set([
|
||
"alt",
|
||
"aria-description",
|
||
"aria-label",
|
||
"aria-placeholder",
|
||
"aria-roledescription",
|
||
"aria-valuetext",
|
||
"caption",
|
||
"children",
|
||
"description",
|
||
"detail",
|
||
// PremiumPaywall bullet points.
|
||
"features",
|
||
// Shown as the title of TextPreviewDialog.
|
||
"fileName",
|
||
"heading",
|
||
"hint",
|
||
"label",
|
||
"legend",
|
||
"message",
|
||
"placeholder",
|
||
"subtitle",
|
||
"summary",
|
||
"text",
|
||
"title",
|
||
"tooltip",
|
||
]);
|
||
// Component props named like confirmText or emptyMessage.
|
||
const DISPLAY_ATTRIBUTE_SUFFIX =
|
||
/(Caption|Content|Description|Detail|Heading|Hint|Label|Message|Placeholder|Summary|Text|Title|Tooltip)$/;
|
||
|
||
/**
|
||
* Returns true when the node is part of the value of a JSX attribute that
|
||
* is not displayed. Function bodies end the search, so a toast message in
|
||
* an onClick handler is still checked.
|
||
*/
|
||
function isInCodeAttribute(node) {
|
||
for (let current = node.parent; current; current = current.parent) {
|
||
if (ts.isFunctionLike(current) || ts.isJsxElement(current)) {
|
||
return false;
|
||
}
|
||
if (ts.isJsxAttribute(current)) {
|
||
const name = current.name.getText();
|
||
return !(
|
||
DISPLAY_ATTRIBUTES.has(name) || DISPLAY_ATTRIBUTE_SUFFIX.test(name)
|
||
);
|
||
}
|
||
}
|
||
return false;
|
||
}
|
||
|
||
/** Returns true when the literal is code rather than displayed text. */
|
||
function isNonDisplayLiteral(node) {
|
||
if (isInCodeAttribute(node)) {
|
||
return true;
|
||
}
|
||
const parent = node.parent;
|
||
if (
|
||
ts.isImportDeclaration(parent) ||
|
||
ts.isExportDeclaration(parent) ||
|
||
ts.isExternalModuleReference(parent) ||
|
||
ts.isLiteralTypeNode(parent) ||
|
||
ts.isCaseClause(parent) ||
|
||
ts.isElementAccessExpression(parent) ||
|
||
ts.isTaggedTemplateExpression(parent)
|
||
) {
|
||
return true;
|
||
}
|
||
if (
|
||
ts.isCallExpression(parent) &&
|
||
parent.expression.kind === ts.SyntaxKind.ImportKeyword
|
||
) {
|
||
return true;
|
||
}
|
||
if ("name" in parent && parent.name === node) {
|
||
return true;
|
||
}
|
||
if (ts.isBinaryExpression(parent)) {
|
||
const kind = parent.operatorToken.kind;
|
||
return (
|
||
kind === ts.SyntaxKind.EqualsEqualsEqualsToken ||
|
||
kind === ts.SyntaxKind.ExclamationEqualsEqualsToken ||
|
||
kind === ts.SyntaxKind.EqualsEqualsToken ||
|
||
kind === ts.SyntaxKind.ExclamationEqualsToken
|
||
);
|
||
}
|
||
return false;
|
||
}
|
||
|
||
// Stands in for a template substitution. A substitution continues a
|
||
// phrase but does not start one, so `New ${name} Provider` is reported
|
||
// while `${message} To continue` is not, because the substitution may
|
||
// end a sentence.
|
||
const SUBSTITUTION = "\uE000";
|
||
|
||
/**
|
||
* Returns true when JSX renders the whitespace at one edge of a text
|
||
* piece. JSX drops leading and trailing whitespace that contains a line
|
||
* break.
|
||
*/
|
||
function rendersSpace(whitespace) {
|
||
return whitespace.length > 0 && !whitespace.includes("\n");
|
||
}
|
||
|
||
// Caps the rendered variants checked for one JSX element. Past the cap,
|
||
// further conditional children are treated as substitutions and their
|
||
// JSX is checked on its own.
|
||
const MAX_JSX_VARIANTS = 64;
|
||
|
||
/**
|
||
* Returns what an inline JSX expression may render: a JSX node or string
|
||
* literal to read as text, null for nothing, or "substitution" for an
|
||
* unknown value. `cond && <b>Text</b>` renders the element or nothing,
|
||
* and a conditional renders either branch.
|
||
*/
|
||
function renderedOptions(expression) {
|
||
let node = expression;
|
||
while (ts.isParenthesizedExpression(node)) {
|
||
node = node.expression;
|
||
}
|
||
if (
|
||
ts.isJsxElement(node) ||
|
||
ts.isJsxFragment(node) ||
|
||
ts.isJsxSelfClosingElement(node) ||
|
||
ts.isStringLiteral(node) ||
|
||
ts.isNoSubstitutionTemplateLiteral(node)
|
||
) {
|
||
return [node];
|
||
}
|
||
if (
|
||
ts.isBinaryExpression(node) &&
|
||
node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken
|
||
) {
|
||
return [...renderedOptions(node.right), null];
|
||
}
|
||
if (ts.isConditionalExpression(node)) {
|
||
return [
|
||
...renderedOptions(node.whenTrue),
|
||
...renderedOptions(node.whenFalse),
|
||
];
|
||
}
|
||
if (
|
||
node.kind === ts.SyntaxKind.NullKeyword ||
|
||
node.kind === ts.SyntaxKind.FalseKeyword ||
|
||
(ts.isIdentifier(node) && node.text === "undefined")
|
||
) {
|
||
return [null];
|
||
}
|
||
return ["substitution"];
|
||
}
|
||
|
||
/**
|
||
* Collects the rendered text of a JSX element or fragment, including the
|
||
* text of nested elements, so a phrase that crosses inline markup is
|
||
* checked as one phrase: `Create <strong>New Workspace</strong>` reads as
|
||
* "Create New Workspace". JSX that a child expression renders
|
||
* conditionally is read in place too, once per rendered variant, so
|
||
* `Create {show && <b>Workspace</b>}` reads as "Create Workspace" and as
|
||
* "Create".
|
||
*
|
||
* The edge of a nested element joins the text on either side only when
|
||
* JSX renders a space there; otherwise it ends the phrase, because
|
||
* adjacent elements are usually separate labels. Nested nodes that are
|
||
* read here are added to `consumed` so they are not checked again on
|
||
* their own.
|
||
*/
|
||
function collectJsxTexts(container, sourceFile, consumed) {
|
||
const sourceText = sourceFile.text;
|
||
let variants = 1;
|
||
|
||
// Appends the rendered pieces of `node` to `pieces`: text ranges,
|
||
// substitutions for unknown values, boundaries at the edges of nested
|
||
// elements, breaks for self-closing elements, and choices between the
|
||
// pieces of each variant a conditional expression renders.
|
||
const addNode = (node, pieces) => {
|
||
if (node === null) {
|
||
return;
|
||
}
|
||
if (node === "substitution") {
|
||
pieces.push({ kind: "substitution" });
|
||
} else if (ts.isJsxText(node)) {
|
||
consumed.add(node);
|
||
const text = sourceText.slice(node.pos, node.end);
|
||
// Whitespace with a line break between tags renders nothing.
|
||
if (!/^\s*$/.test(text) || rendersSpace(text)) {
|
||
pieces.push({ kind: "text", start: node.pos, end: node.end });
|
||
}
|
||
} else if (
|
||
ts.isStringLiteral(node) ||
|
||
ts.isNoSubstitutionTemplateLiteral(node)
|
||
) {
|
||
consumed.add(node);
|
||
pieces.push({
|
||
kind: "text",
|
||
start: node.getStart(sourceFile) + 1,
|
||
end: node.end - 1,
|
||
});
|
||
} else if (ts.isJsxExpression(node)) {
|
||
// An empty expression, such as {/* note */}, renders nothing.
|
||
if (node.expression) {
|
||
addExpression(node.expression, pieces);
|
||
}
|
||
} else if (ts.isJsxElement(node) || ts.isJsxFragment(node)) {
|
||
consumed.add(node);
|
||
pieces.push({ kind: "boundary", edge: "open" });
|
||
for (const child of node.children) {
|
||
addNode(child, pieces);
|
||
}
|
||
pieces.push({ kind: "boundary", edge: "close" });
|
||
} else {
|
||
// A self-closing element, such as an icon, sits between
|
||
// separate labels more often than inside a phrase.
|
||
pieces.push({ kind: "break" });
|
||
}
|
||
};
|
||
|
||
const addExpression = (expression, pieces) => {
|
||
const options = renderedOptions(expression);
|
||
if (options.length === 1) {
|
||
addNode(options[0], pieces);
|
||
} else if (
|
||
options.every((option) => option === "substitution") ||
|
||
variants * options.length > MAX_JSX_VARIANTS
|
||
) {
|
||
pieces.push({ kind: "substitution" });
|
||
} else {
|
||
variants *= options.length;
|
||
pieces.push({
|
||
kind: "choice",
|
||
options: options.map((option) => {
|
||
const optionPieces = [];
|
||
addNode(option, optionPieces);
|
||
return optionPieces;
|
||
}),
|
||
});
|
||
}
|
||
};
|
||
|
||
const rootPieces = [];
|
||
for (const child of container.children) {
|
||
addNode(child, rootPieces);
|
||
}
|
||
|
||
const texts = [];
|
||
for (const pieces of expandChoices(rootPieces)) {
|
||
texts.push(...joinJsxPieces(pieces, sourceText));
|
||
}
|
||
return texts;
|
||
}
|
||
|
||
/** Expands choice pieces into every linear sequence of pieces. */
|
||
function expandChoices(pieces) {
|
||
let sequences = [[]];
|
||
for (const piece of pieces) {
|
||
if (piece.kind !== "choice") {
|
||
for (const sequence of sequences) {
|
||
sequence.push(piece);
|
||
}
|
||
continue;
|
||
}
|
||
const next = [];
|
||
for (const option of piece.options) {
|
||
for (const tail of expandChoices(option)) {
|
||
for (const sequence of sequences) {
|
||
next.push([...sequence, ...tail]);
|
||
}
|
||
}
|
||
}
|
||
sequences = next;
|
||
}
|
||
return sequences;
|
||
}
|
||
|
||
/**
|
||
* Joins a linear sequence of JSX pieces into phrases, each with its text
|
||
* and the source position of each character.
|
||
*/
|
||
function joinJsxPieces(pieces, sourceText) {
|
||
const edgeRendersSpace = (piece, edge) => {
|
||
if (piece?.kind !== "text") {
|
||
return false;
|
||
}
|
||
const text = sourceText.slice(piece.start, piece.end);
|
||
const whitespace = text.match(edge === "end" ? /\s*$/ : /^\s*/)[0];
|
||
return rendersSpace(whitespace);
|
||
};
|
||
|
||
const texts = [];
|
||
let current = { text: "", positions: [] };
|
||
const endPhrase = () => {
|
||
if (current.text.trim()) {
|
||
texts.push(current);
|
||
}
|
||
current = { text: "", positions: [] };
|
||
};
|
||
for (let i = 0; i < pieces.length; i++) {
|
||
const piece = pieces[i];
|
||
if (
|
||
piece.kind === "boundary" &&
|
||
piece.edge === "open" &&
|
||
pieces[i - 1]?.edge === "close"
|
||
) {
|
||
// Sibling elements with nothing rendered between them are
|
||
// separate labels, whatever whitespace they hold inside.
|
||
endPhrase();
|
||
} else if (piece.kind === "boundary") {
|
||
let before = i - 1;
|
||
while (pieces[before]?.kind === "boundary") {
|
||
before--;
|
||
}
|
||
let after = i + 1;
|
||
while (pieces[after]?.kind === "boundary") {
|
||
after++;
|
||
}
|
||
if (
|
||
!edgeRendersSpace(pieces[before], "end") &&
|
||
!edgeRendersSpace(pieces[after], "start")
|
||
) {
|
||
endPhrase();
|
||
}
|
||
} else if (piece.kind === "break") {
|
||
endPhrase();
|
||
} else if (piece.kind === "substitution") {
|
||
// Pad with spaces so the substitution is a token of its own.
|
||
current.text += ` ${SUBSTITUTION} `;
|
||
current.positions.push(-1, -1, -1);
|
||
} else {
|
||
current.text += sourceText.slice(piece.start, piece.end);
|
||
for (let position = piece.start; position < piece.end; position++) {
|
||
current.positions.push(position);
|
||
}
|
||
}
|
||
}
|
||
endPhrase();
|
||
return texts;
|
||
}
|
||
|
||
/**
|
||
* Collects every displayed text node as its text plus the source position
|
||
* of each character. Substitutions in template literals and JSX map to -1.
|
||
* Text from a string or template literal also has `start`, the position
|
||
* where the literal starts.
|
||
*/
|
||
function collectTexts(sourceFile) {
|
||
const sourceText = sourceFile.text;
|
||
const texts = [];
|
||
// JSX nodes already read as part of an enclosing element's text.
|
||
const consumed = new Set();
|
||
const addRange = (start, end) => {
|
||
texts.push({
|
||
text: sourceText.slice(start, end),
|
||
positions: Array.from({ length: end - start }, (_, i) => start + i),
|
||
start,
|
||
});
|
||
};
|
||
const visit = (node) => {
|
||
switch (node.kind) {
|
||
case ts.SyntaxKind.JsxElement:
|
||
case ts.SyntaxKind.JsxFragment:
|
||
if (!consumed.has(node)) {
|
||
texts.push(...collectJsxTexts(node, sourceFile, consumed));
|
||
}
|
||
break;
|
||
case ts.SyntaxKind.StringLiteral:
|
||
case ts.SyntaxKind.NoSubstitutionTemplateLiteral:
|
||
if (!consumed.has(node) && !isNonDisplayLiteral(node)) {
|
||
addRange(node.getStart(sourceFile), node.end);
|
||
}
|
||
break;
|
||
case ts.SyntaxKind.TemplateExpression: {
|
||
if (isNonDisplayLiteral(node)) {
|
||
break;
|
||
}
|
||
// Join the literal parts without their `, ${, and } delimiters.
|
||
let text = "";
|
||
const positions = [];
|
||
const addPart = (start, end) => {
|
||
text += sourceText.slice(start, end);
|
||
for (let i = start; i < end; i++) {
|
||
positions.push(i);
|
||
}
|
||
};
|
||
const head = node.head;
|
||
addPart(head.getStart(sourceFile) + 1, head.end - 2);
|
||
for (const span of node.templateSpans) {
|
||
text += SUBSTITUTION;
|
||
positions.push(-1);
|
||
const literal = span.literal;
|
||
const isTail = literal.kind === ts.SyntaxKind.TemplateTail;
|
||
addPart(
|
||
literal.getStart(sourceFile) + 1,
|
||
literal.end - (isTail ? 1 : 2),
|
||
);
|
||
}
|
||
texts.push({ text, positions, start: node.getStart(sourceFile) });
|
||
break;
|
||
}
|
||
}
|
||
ts.forEachChild(node, visit);
|
||
};
|
||
visit(sourceFile);
|
||
return texts;
|
||
}
|
||
|
||
/**
|
||
* Checks one file's source text. Returns the reported words, the
|
||
* line numbers of unused expect comments, and the source with every
|
||
* reported word lowercased.
|
||
*/
|
||
export function checkSource(fileName, sourceText) {
|
||
const sourceFile = ts.createSourceFile(
|
||
fileName,
|
||
sourceText,
|
||
ts.ScriptTarget.Latest,
|
||
true,
|
||
fileName.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS,
|
||
);
|
||
|
||
// Expect comments apply to the line after the comment, and to every
|
||
// line of a template literal that starts on that line. Line numbers
|
||
// from the TypeScript API are zero-based; results are one-based.
|
||
const expectedLines = new Set();
|
||
sourceText.split("\n").forEach((line, index) => {
|
||
if (line.includes(EXPECT_COMMENT)) {
|
||
expectedLines.add(index + 1);
|
||
}
|
||
});
|
||
|
||
const issues = [];
|
||
const usedExpectations = new Set();
|
||
// Conditional JSX is checked once per rendered variant, so the same
|
||
// word can be reported more than once.
|
||
const reportedPositions = new Set();
|
||
for (const { text, positions, start } of collectTexts(sourceFile)) {
|
||
const words = findTitleCaseWords(text);
|
||
if (words.length === 0) {
|
||
continue;
|
||
}
|
||
const startLine =
|
||
start === undefined
|
||
? undefined
|
||
: sourceFile.getLineAndCharacterOfPosition(start).line;
|
||
for (const { offset, word } of words) {
|
||
const position = positions[offset];
|
||
if (reportedPositions.has(position)) {
|
||
continue;
|
||
}
|
||
reportedPositions.add(position);
|
||
const { line, character } =
|
||
sourceFile.getLineAndCharacterOfPosition(position);
|
||
const expectedLine = [line, startLine].find((candidate) =>
|
||
expectedLines.has(candidate),
|
||
);
|
||
if (expectedLine !== undefined) {
|
||
usedExpectations.add(expectedLine);
|
||
continue;
|
||
}
|
||
issues.push({ position, line: line + 1, column: character + 1, word });
|
||
}
|
||
}
|
||
issues.sort((a, b) => a.position - b.position);
|
||
|
||
let fixedText = sourceText;
|
||
for (const { position } of [...issues].reverse()) {
|
||
fixedText =
|
||
fixedText.slice(0, position) +
|
||
fixedText[position].toLowerCase() +
|
||
fixedText.slice(position + 1);
|
||
}
|
||
|
||
// A zero-based expected line is also the one-based line of its
|
||
// comment, which is the line to report.
|
||
const unusedExpectations = [...expectedLines].filter(
|
||
(line) => !usedExpectations.has(line),
|
||
);
|
||
|
||
return { issues, unusedExpectations, fixedText };
|
||
}
|
||
|
||
function collectFiles(dir) {
|
||
const files = [];
|
||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||
const path = join(dir, entry.name);
|
||
if (entry.isDirectory()) {
|
||
files.push(...collectFiles(path));
|
||
} else if (/\.tsx?$/.test(entry.name)) {
|
||
files.push(path);
|
||
}
|
||
}
|
||
return files;
|
||
}
|
||
|
||
function isExcluded(path) {
|
||
return EXCLUDED_FILE_PATTERNS.some((pattern) => pattern.test(path));
|
||
}
|
||
|
||
// Only run the main block when executed directly, not when imported by
|
||
// tests for the exported functions.
|
||
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||
const siteDir = fileURLToPath(new URL("..", import.meta.url));
|
||
const fix = process.argv.includes("--fix");
|
||
const files = collectFiles(join(siteDir, "src"))
|
||
.map((path) => relative(siteDir, path))
|
||
.filter((path) => !isExcluded(path));
|
||
|
||
let issueCount = 0;
|
||
let unusedCount = 0;
|
||
for (const file of files) {
|
||
const sourceText = readFileSync(join(siteDir, file), "utf8");
|
||
const { issues, unusedExpectations, fixedText } = checkSource(
|
||
file,
|
||
sourceText,
|
||
);
|
||
for (const { line, column, word } of issues) {
|
||
console.log(
|
||
`${file}:${line}:${column}: "${word}" should be lowercase in sentence case`,
|
||
);
|
||
}
|
||
for (const line of unusedExpectations) {
|
||
console.log(
|
||
`${file}:${line}: unused "${EXPECT_COMMENT}" comment, the next line has no title case text`,
|
||
);
|
||
}
|
||
issueCount += issues.length;
|
||
unusedCount += unusedExpectations.length;
|
||
if (fix && issues.length > 0) {
|
||
writeFileSync(join(siteDir, file), fixedText);
|
||
}
|
||
}
|
||
|
||
if (fix && issueCount > 0) {
|
||
console.log(`\nLowercased ${issueCount} word(s). Review the changes.`);
|
||
}
|
||
if ((!fix && issueCount > 0) || unusedCount > 0) {
|
||
console.log(
|
||
[
|
||
"",
|
||
"Use sentence case for UI text: capitalize only the first word and proper nouns.",
|
||
"To fix automatically: pnpm run lint:sentence-case --fix",
|
||
"For proper nouns: add them to PROPER_NOUNS in scripts/check-sentence-case.mjs.",
|
||
`For other exceptions: add a "${EXPECT_COMMENT}" comment on the line above.`,
|
||
].join("\n"),
|
||
);
|
||
process.exitCode = 1;
|
||
}
|
||
}
|