diff --git a/e2e/reactComponentTemplates.spec.ts b/e2e/reactComponentTemplates.spec.ts new file mode 100644 index 0000000000..d405ea6dbd --- /dev/null +++ b/e2e/reactComponentTemplates.spec.ts @@ -0,0 +1,34 @@ +import { expect, test } from "./fixtures"; +import type { Page } from "@playwright/test"; + +/** Opens an empty file, types `abbrev` + Tab and returns the text with `|` at the caret. */ +async function expand(page: Page, path: string, abbrev: string) { + await page.evaluate(async (p) => { + const backendPath = "/src/editor/core/backend.ts"; + const contributionsPath = "/src/workbench/contributions.ts"; + const { docBackend } = await import(backendPath); + const { editorService } = await import(contributionsPath); + docBackend().files.set(p, ""); + await editorService().openFile(p); + }, path); + const content = page.locator(".cm-editor .cm-content").last(); + await content.click(); + await page.keyboard.type(abbrev); + await page.keyboard.press("Tab"); + return content.evaluate((element) => { + const view = (element as HTMLElement & { cmTile: { view: import("@codemirror/view").EditorView } }).cmTile.view; + const text = view.state.doc.toString(); + const at = view.state.selection.main.head; + return `${text.slice(0, at)}|${text.slice(at)}`; + }); +} + +test("React component templates expand in TSX / JSX, named after the file", async ({ workbench: page }) => { + expect(await expand(page, "/dev/acme-api/src/user-card.tsx", "rafce")).toBe( + "type Props = {};\n\nconst UserCard = ({}: Props) => {\n return (\n
\n |\n
\n );\n};\n\nexport default UserCard;", + ); + expect(await expand(page, "/dev/acme-api/src/Profile.jsx", "rcc")).toContain( + "export default class Profile extends React.Component {", + ); + expect(await expand(page, "/dev/acme-api/src/util.ts", "rfc")).not.toContain("function"); +}); diff --git a/src/features/templates/__tests__/live.test.ts b/src/features/templates/__tests__/live.test.ts index fca67033f8..5bad7552e5 100644 --- a/src/features/templates/__tests__/live.test.ts +++ b/src/features/templates/__tests__/live.test.ts @@ -158,6 +158,44 @@ describe("expansion", () => { expect(has("java", "fore")).toBe(false); }); + it("offers React component templates only in JSX / TSX, named after the file", () => { + const abbrevs = ["rfc", "rfce", "rafce", "rcc"]; + const pick = (lang: string) => + applicableTemplates(BUILTIN_TEMPLATES, lang).filter((t) => abbrevs.includes(t.abbrev)); + for (const lang of ["javascript", "typescript"]) expect(pick(lang)).toEqual([]); + for (const lang of ["javascriptreact", "typescriptreact"]) expect(pick(lang).map((t) => t.abbrev)).toEqual(abbrevs); + // Listed in Settings with the useState / useEffect templates. + expect(new Set(pick("typescriptreact").map((t) => t.group))).toEqual(new Set(["JavaScript / TypeScript"])); + + const fns = { fileNameWithoutExtension: () => "user-card" }; + const expand = (lang: string, abbrev: string) => { + const t = pick(lang).find((x) => x.abbrev === abbrev)!; + const r = apply("", expandTemplate(t, { fns }).snippet, 0); + const [[from, to]] = r.sel as [[number, number]]; + return `${r.text.slice(0, from)}|${r.text.slice(to)}`; + }; + expect(expand("javascriptreact", "rfc")).toBe( + "export default function UserCard() {\n return (\n
\n |\n
\n );\n}", + ); + expect(expand("typescriptreact", "rafce")).toBe( + "type Props = {};\n\nconst UserCard = ({}: Props) => {\n return (\n
\n |\n
\n );\n};\n\nexport default UserCard;", + ); + expect(expand("typescriptreact", "rfce")).toContain("function UserCard({}: Props) {"); + expect(expand("javascriptreact", "rcc")).toBe( + 'import React from "react";\n\nexport default class UserCard extends React.Component {\n render() {\n return (\n
\n |\n
\n );\n }\n}', + ); + expect(expand("typescriptreact", "rcc")).toContain("class UserCard extends React.Component {"); + + const nameFrom = (file: string) => + evaluateExpression("componentName(fileNameWithoutExtension())", { fileNameWithoutExtension: () => file }); + expect(nameFrom("APIClient")).toBe("APIClient"); + expect(nameFrom("UIButton")).toBe("UIButton"); + expect(nameFrom("user_card")).toBe("UserCard"); + expect(nameFrom("404")).toBe("Component404"); + expect(nameFrom("2fa-form")).toBe("Component2faForm"); + expect(nameFrom("")).toBe(""); + }); + it("writes PHP variables with their $", () => { const php = (abbrev: string) => BUILTIN_TEMPLATES.find((t) => t.id === `php.${abbrev}`)!; const fore = apply("", expandTemplate(php("fore")).snippet, 0); diff --git a/src/features/templates/live/builtins.ts b/src/features/templates/live/builtins.ts index 3f55877338..88af3ad132 100644 --- a/src/features/templates/live/builtins.ts +++ b/src/features/templates/live/builtins.ts @@ -116,6 +116,47 @@ const ts = group("JavaScript / TypeScript", "ts", TS_LANGS, [ { abbrev: "useEffect", description: "React useEffect hook", body: "useEffect(() => {\n\t$END$\n}, [$DEPS$]);" }, ]); +/** React components named after the file; the TSX variants declare a `Props` type. */ +function reactComponents(tsx: boolean): LiveTemplate[] { + const ext = tsx ? "tsx" : "jsx"; + const props = tsx ? "type Props = {};\n\n" : ""; + const param = tsx ? "{}: Props" : ""; + const render = (t: string) => `${t}return (\n${t}\t
\n${t}\t\t$END$\n${t}\t
\n${t});\n`; + const variables = [v("NAME", "componentName(fileNameWithoutExtension())", '"Component"', true)]; + const defs: Def[] = [ + { + abbrev: "rfc", + description: tsx ? "React function component with Props" : "React function component", + body: `${props}export default function $NAME$(${param}) {\n${render("\t")}}`, + }, + { + abbrev: "rfce", + description: tsx + ? "React function component with Props and export default" + : "React function component with export default", + body: `${props}function $NAME$(${param}) {\n${render("\t")}}\n\nexport default $NAME$;`, + }, + { + abbrev: "rafce", + description: tsx + ? "React arrow function component with Props and export default" + : "React arrow function component with export default", + body: `${props}const $NAME$ = (${param}) => {\n${render("\t")}};\n\nexport default $NAME$;`, + }, + { + abbrev: "rcc", + description: tsx ? "React class component with Props" : "React class component", + body: `import React from "react";\n\n${props}export default class $NAME$ extends React.Component${tsx ? "" : ""} {\n\trender() {\n${render("\t\t")}\t}\n}`, + }, + ]; + return group( + "JavaScript / TypeScript", + "ts", + [tsx ? "typescriptreact" : "javascriptreact"], + defs.map((d) => ({ ...d, id: `${d.abbrev}.${ext}`, variables })), + ); +} + const python = group( "Python", "py", @@ -545,6 +586,8 @@ const sqlCode = group( export const BUILTIN_TEMPLATES: readonly LiveTemplate[] = [ ...rust, ...ts, + ...reactComponents(false), + ...reactComponents(true), ...python, ...go, ...zig, diff --git a/src/features/templates/live/model.ts b/src/features/templates/live/model.ts index 8dd021204f..ce6ee7b02d 100644 --- a/src/features/templates/live/model.ts +++ b/src/features/templates/live/model.ts @@ -162,6 +162,11 @@ export const camelCase = (s: string) => .map((w, i) => (i ? capitalize(w.toLowerCase()) : w.toLowerCase())) .join(""); export const pascalCase = (s: string) => capitalize(camelCase(s)); +/** A component / class name from a file name: kept when already PascalCase (`APIClient`), prefixed when it starts with a digit. */ +export const componentName = (s: string) => { + const name = /^[A-Z][A-Za-z0-9]*$/.test(s) ? s : pascalCase(s); + return /^[0-9]/.test(name) ? `Component${name}` : name; +}; export const snakeCase = (s: string) => words(s) .map((w) => w.toLowerCase()) @@ -204,6 +209,7 @@ const PURE_FUNCTIONS: TemplateFunctions = { decapitalize, camelCase, pascalCase, + componentName, snakeCase, lowercaseAndDash: kebabCase, kebabCase, diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 0d8a14f317..86ffbd6266 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -2922,6 +2922,14 @@ "Re-check installed tools": "重新检查已安装的工具", "Re-reads the effective POMs and dependency trees with Maven": "使用 Maven 重新读取有效 POM 和依赖树", "Re-reads the task list with Gradle": "使用 Gradle 重新读取任务列表", + "React arrow function component with export default": "带 export default 的 React 箭头函数组件", + "React arrow function component with Props and export default": "带 Props 和 export default 的 React 箭头函数组件", + "React class component": "React 类组件", + "React class component with Props": "带 Props 的 React 类组件", + "React function component": "React 函数组件", + "React function component with Props": "带 Props 的 React 函数组件", + "React function component with Props and export default": "带 Props 和 export default 的 React 函数组件", + "React function component with export default": "带 export default 的 React 函数组件", "React useEffect hook": "React useEffect Hook", "React useState hook": "React useState Hook", "Read-only": "只读",