diff --git a/docs/en/languages/java.mdx b/docs/en/languages/java.mdx index cd421dd7b..635d6e110 100644 --- a/docs/en/languages/java.mdx +++ b/docs/en/languages/java.mdx @@ -136,7 +136,7 @@ See [Debugging](/en/guide/debugging). - **Spring Boot run configurations** are created from `@SpringBootApplication` classes, and they are listed in the **Services** tool window by default. - **Configuration navigation**: Go to Definition on a key in `application.yml` or `.properties` opens the Java members bound to it (`@ConfigurationProperties`, `@Value`, `Environment.getProperty`). It also works the other way, from `${…}` placeholders in Java, YAML, properties or Spring XML. Keys described by `spring-configuration-metadata.json` in dependencies resolve to their source classes. **Find Usages** on a key lists configuration declarations and Java usages together. -- **Thymeleaf templates**: `.html` files in a project with `src/main/resources/templates` highlight `th:*` and `data-th-*` values as Thymeleaf expressions and complete the attribute names after `th:`. Go to Declaration on a fragment expression (`~{fragments/nav :: menu}`, or the bare form in `th:replace` / `th:insert`) opens the template or its `th:fragment`; on a message key (`#{home.title}`) it lists the key in each `messages*.properties` of the bundles set by `spring.messages.basename`. +- **Thymeleaf templates**: `.html` files in a project with `src/main/resources/templates` highlight `th:*` and `data-th-*` values as Thymeleaf expressions and complete the attribute names after `th:`. Go to Declaration on a fragment expression (`~{fragments/nav :: menu}`, or the bare form in `th:replace` / `th:insert`) opens the template or its `th:fragment`; on a message key (`#{home.title}`) it lists the key in each `messages*.properties` of the bundles set by `spring.messages.basename`. A fragment expression that names a fragment the template does not define (no `th:fragment`, `th:ref` or element of that name; an `id` of that name is tolerated too) is underlined as a warning, and so is a missing template in a single-module project; not when `application.properties` / `.yml` sets `spring.thymeleaf.prefix` or `suffix`, or for a `~{…} ?: …` fallback. - **Spring Web endpoints**: request mappings in Java and Kotlin controllers get a gutter icon, plus **Generate Request in HTTP Client** and **Generate Requests for Controller** actions that write requests to a scratch `.http` file. Search Everywhere matches request paths in its **All** tab. See [HTTP Client](/en/guide/http-client). - **Facets** in **Project Structure** (`⌘;` / `Ctrl+Alt+Shift+S`) record the frameworks a module uses (Web, Spring, JPA). A Web facet also adds its `WEB-INF/lib/*.jar` to the jdtls classpath. diff --git a/docs/zh/languages/java.mdx b/docs/zh/languages/java.mdx index d8a6b55c0..6b2c1ca1b 100644 --- a/docs/zh/languages/java.mdx +++ b/docs/zh/languages/java.mdx @@ -134,7 +134,7 @@ Java 调试使用 jdtls 内的 Microsoft java-debug,Kotlin 调试使用 Kotlin - **Spring Boot 运行配置**:根据 `@SpringBootApplication` 类创建,默认显示在 **服务** 工具窗口中。 - **配置导航**:在 `application.yml` 或 `.properties` 的键上转到定义,会打开绑定到它的 Java 成员(`@ConfigurationProperties`、`@Value`、`Environment.getProperty`);反过来,从 Java、YAML、properties 或 Spring XML 里的 `${…}` 占位符也能跳到配置键。依赖中 `spring-configuration-metadata.json` 描述的键会跳到对应的源类。对配置键执行 **查找用法**,会同时列出配置声明和 Java 中的使用处。 -- **Thymeleaf 模板**:项目中有 `src/main/resources/templates` 时,`.html` 文件里 `th:*` 和 `data-th-*` 的值按 Thymeleaf 表达式高亮,输入 `th:` 后补全属性名。在片段表达式(`~{fragments/nav :: menu}`,或 `th:replace` / `th:insert` 中不带 `~{}` 的写法)上转到声明,打开对应模板或其 `th:fragment`;在消息键(`#{home.title}`)上转到声明,列出 `spring.messages.basename` 所设消息包中每个 `messages*.properties` 里的该键。 +- **Thymeleaf 模板**:项目中有 `src/main/resources/templates` 时,`.html` 文件里 `th:*` 和 `data-th-*` 的值按 Thymeleaf 表达式高亮,输入 `th:` 后补全属性名。在片段表达式(`~{fragments/nav :: menu}`,或 `th:replace` / `th:insert` 中不带 `~{}` 的写法)上转到声明,打开对应模板或其 `th:fragment`;在消息键(`#{home.title}`)上转到声明,列出 `spring.messages.basename` 所设消息包中每个 `messages*.properties` 里的该键。片段表达式指向模板中没有的片段(没有同名的 `th:fragment`、`th:ref` 或元素;同名 `id` 也放过)时以警告标出,单模块项目中指向不存在的模板也会标出;`application.properties` / `.yml` 设置了 `spring.thymeleaf.prefix` 或 `suffix`,或写成 `~{…} ?: …` 回退时不检查。 - **Spring Web 端点**:Java 和 Kotlin 控制器中的请求映射旁有边栏图标,还有 **在 HTTP 客户端中生成请求** 和 **为控制器生成请求** 两个操作,会把请求写进一个临时 `.http` 文件。随处搜索的 **全部** 标签页可以按请求路径搜索。见 [HTTP Client](/zh/guide/http-client)。 - **Facet**:在 **项目结构**(`⌘;` / `Ctrl+Alt+Shift+S`)里记录模块使用的框架(Web、Spring、JPA)。添加 Web Facet 还会把其中的 `WEB-INF/lib/*.jar` 加入 jdtls 的类路径。 diff --git a/src/features/thymeleaf/index.ts b/src/features/thymeleaf/index.ts index 5ece13dd7..fac0e3ae6 100644 --- a/src/features/thymeleaf/index.ts +++ b/src/features/thymeleaf/index.ts @@ -1,19 +1,31 @@ /** * Thymeleaf navigation: Go to Declaration (⌘-click, ⌘B) on a fragment expression's template * name opens the template, on its selector the `th:fragment` defining it, and on a message - * expression's key that key in each of the message bundle's `.properties` files. + * expression's key that key in each of the message bundle's `.properties` files; and a warning on + * template and fragment names that resolve to nothing. */ -import { Text } from "@codemirror/state"; -import { offsetsToRange, registerNavigationProvider } from "@/editor/api"; +import { Text, type Extension } from "@codemirror/state"; +import { EditorView, ViewPlugin } from "@codemirror/view"; +import { + offsetsToRange, + registerEditorContribution, + registerNavigationProvider, + type EditorDocContext, +} from "@/editor/api"; +import { setFileDiagnostics } from "@/editor/lsp/diagnostics"; import { docOf } from "@/editor/lsp/lsp"; -import { call, commands, type Location } from "@/platform/ipc"; +import { tx } from "@/platform/i18n"; +import { call, commands, isTauri, onIdeEvent, type Location } from "@/platform/ipc"; +import { projectFolder, useProject } from "@/platform/project"; import { fragmentDefinition, inBundle, messageBasenames, propertyDefinition, + templatePath, templatesRoot, thymeleafReferenceAt, + unresolvedThymeleafReferences, } from "./references"; const TEMPLATE_FILE = /\.html?$/i; @@ -30,18 +42,18 @@ function location(path: string, text: string, from: number, to: number, name?: s return { path, range: offsetsToRange(Text.of(text.split("\n")), from, to), name }; } -function templatePath(root: string, template: string): string { - return `${root}/${template}${/\.\w+$/.test(template) ? "" : ".html"}`; +/** The Spring Boot `application.properties` / `.yml` text in the `resources` folder. */ +async function applicationConfig(resources: string): Promise { + const configs = await Promise.all( + ["application.properties", "application.yml", "application.yaml"].map((name) => read(`${resources}/${name}`)), + ); + return configs.map((text) => `${text ?? ""}\n`).join(""); } /** The definitions of `key` in the message bundles next to the templates `root`. */ async function messageTargets(root: string, key: string): Promise> { const resources = root.slice(0, root.lastIndexOf("/")); - const configs = await Promise.all( - ["application.properties", "application.yml", "application.yaml"].map((name) => read(`${resources}/${name}`)), - ); - const application = configs.map((text) => `${text ?? ""}\n`).join(""); - const bases = messageBasenames(application); + const bases = messageBasenames(await applicationConfig(resources)); const listings = await Promise.all( bases.map((base) => call( @@ -67,8 +79,74 @@ async function messageTargets(root: string, key: string): Promise { + const { path } = ctx; + const spring = path.lastIndexOf("/src/main/resources/templates/"); + if (ctx.virtual || !TEMPLATE_FILE.test(path) || spring < 0 || !isTauri()) return {}; + const resources = path.slice(0, spring + "/src/main/resources".length); + let timer: ReturnType | undefined; + let seq = 0; + const run = async () => { + const mine = ++seq; + const doc = view.state.doc; + const text = doc.toString(); + const refs = + text.includes("th:") || text.includes("data-th-") + ? await unresolvedThymeleafReferences( + path, + text, + await applicationConfig(resources), + projectFolder(useProject.getState().project, path)?.root ?? null, + read, + ) + : []; + if (mine !== seq) return; + setFileDiagnostics( + path, + SOURCE, + refs.map((r) => ({ + range: offsetsToRange(doc, r.from, r.to), + severity: "warning", + message: + r.kind === "fragment" + ? tx`Cannot resolve fragment '${r.fragment}'` + : tx`Cannot resolve template '${r.template}'`, + source: "Thymeleaf", + code: null, + })), + ); + }; + const schedule = () => { + clearTimeout(timer); + timer = setTimeout(() => void run(), INSPECT_DELAY); + }; + schedule(); + const offFs = onIdeEvent("fsChanged", (e) => { + if (e.created.length || e.removed.length || e.modified.some((p) => p !== path && p.startsWith(resources))) + schedule(); + }); + return { + update: (u) => { + if (u.docChanged) schedule(); + }, + destroy: () => { + clearTimeout(timer); + offFs(); + seq++; + setFileDiagnostics(path, SOURCE, []); + }, + }; + }); +} + export function activate(): () => void { - return registerNavigationProvider(async (view, offset) => { + const offUnresolved = registerEditorContribution({ id: "thymeleaf.unresolved", extensions: unresolvedReferences }); + const offNavigation = registerNavigationProvider(async (view, offset) => { const doc = docOf(view); if (!doc || doc.virtual || !TEMPLATE_FILE.test(doc.path)) return null; const text = view.state.doc.toString(); @@ -87,4 +165,8 @@ export function activate(): () => void { const at = fragmentDefinition(target, ref.fragment); return at < 0 ? null : match([location(path, target, at, at + ref.fragment.length)]); }); + return () => { + offUnresolved(); + offNavigation(); + }; } diff --git a/src/features/thymeleaf/references.test.ts b/src/features/thymeleaf/references.test.ts index 71e05d697..f385beb72 100644 --- a/src/features/thymeleaf/references.test.ts +++ b/src/features/thymeleaf/references.test.ts @@ -7,6 +7,7 @@ import { templatesRoot, thymeleafReferenceAt, thymeleafReferences, + unresolvedThymeleafReferences, } from "./references"; const at = (text: string, word: string, n = 0) => { @@ -83,3 +84,62 @@ describe("project layout", () => { expect(inBundle("messagesx.properties", "messages")).toBe(false); }); }); + +describe("unresolvedThymeleafReferences", () => { + const ROOT = "/p/src/main/resources/templates"; + const files: Record = { + [`${ROOT}/fragments/nav.html`]: `
x`, + [`${ROOT}/mail/order.v2.html`]: `

`, + [`${ROOT}/fragments/old.htm`]: ``, + [`${ROOT}/mail/body.txt`]: `Hi`, + [`${ROOT}/Page.HTML`]: `

`, + ["/p/app/src/main/resources/templates/fragments/nav.html"]: ``, + }; + const read = async (path: string) => files[path] ?? null; + const check = async (text: string, application = "", path = `${ROOT}/index.html`, project = "/p") => + (await unresolvedThymeleafReferences(path, text, application, project, read)).map((r) => text.slice(r.from, r.to)); + + it("reports a missing template once and a fragment the template lacks", async () => { + expect(await check(`
`)).toEqual(["fragments/navx"]); + expect(await check(`
`)).toEqual(["menux"]); + }); + + it("accepts fragments defined by th:fragment, id or tag name", async () => { + expect(await check(`
`)).toEqual([]); + expect(await check(`
`)).toEqual([]); + expect(await check(`
`)).toEqual([]); + expect(await check(`
`)).toEqual([]); + expect(await check(`
`)).toEqual([]); + expect(await check(`
`)).toEqual([]); + }); + + it("checks same-template selectors against the edited text", async () => { + const text = `

`; + expect(await check(text)).toEqual(["gone"]); + const self = `

`; + expect(await check(self, "", `${ROOT}/fragments/nav.html`)).toEqual([]); + }); + + it("skips the no-op token, expressions, relative names and comments", async () => { + expect(await check(`
`)).toEqual([]); + expect(await check(`
`)).toEqual([]); + expect(await check(`
`)).toEqual([]); + expect(await check(`
`)).toEqual([]); + expect(await check(``)).toEqual([]); + expect(await check(`
`)).toEqual([]); + expect(await check(`
`)).toEqual(["x"]); + }); + + it("reports nothing outside Spring's default template location", async () => { + const text = `
`; + expect(await check(text)).toEqual(["missing"]); + expect(await check(text, "", "/p/templates/index.html")).toEqual([]); + // A nested module may take templates from another module: only fragments of existing templates count. + const nested = `/p/app/src/main/resources/templates/index.html`; + const refs = `${text}
`; + expect(await check(refs, "", nested)).toEqual(["menux"]); + expect(await check(text, "spring.thymeleaf.prefix=classpath:/views/\n")).toEqual([]); + expect(await check(text, "spring:\n thymeleaf:\n cache: false\n suffix: .xhtml\n")).toEqual([]); + expect(await check(text, "spring.thymeleaf:\n prefix: classpath:/views/\n")).toEqual([]); + }); +}); diff --git a/src/features/thymeleaf/references.ts b/src/features/thymeleaf/references.ts index 97b5be1a6..f6a6fc37f 100644 --- a/src/features/thymeleaf/references.ts +++ b/src/features/thymeleaf/references.ts @@ -134,3 +134,77 @@ export function inBundle(file: string, base: string): boolean { const name = base.slice(base.lastIndexOf("/") + 1); return file === `${name}.properties` || (file.startsWith(`${name}_`) && file.endsWith(".properties")); } + +/** Extensions Thymeleaf's resolver adds no `.html` suffix to (`ContentTypeUtils.hasRecognizedFileExtension`). */ +const RECOGNIZED_EXTENSION = /\.(?:html?|xhtml|xml|rss|atom|js|json|css|txt)$/i; + +/** The file a template name resolves to under the templates `root`. */ +export function templatePath(root: string, template: string): string { + return `${root}/${template}${RECOGNIZED_EXTENSION.test(template) ? "" : ".html"}`; +} + +const SPRING_TEMPLATES = "/src/main/resources/templates/"; +const COMMENT = //g; +/** The rest of a `~{…}` followed by `?:`: Thymeleaf's fallback when the fragment does not exist. */ +const FALLBACK = /[^}]*\}\s*\?:/y; + +/** Whether `application.properties` / `.yml` text sets `spring.thymeleaf.prefix` or `suffix`. */ +function customTemplateLocation(application: string): boolean { + return ( + /spring\.thymeleaf\.(?:prefix|suffix)\b/.test(application) || + /thymeleaf:[ \t]*\n(?:[ \t]+.*\n)*?[ \t]+(?:prefix|suffix)[ \t]*:/m.test(application) + ); +} + +/** Whether `text` has a fragment `name` selects: `th:fragment`, `th:ref`, `id` or an element named so. */ +function definesFragment(text: string, name: string): boolean { + return ( + fragmentDefinition(text, name) >= 0 || + new RegExp(`\\b(?:th:|data-th-)ref\\s*=\\s*["']\\s*${escape(name)}\\s*["']`).test(text) || + new RegExp(`<${escape(name)}[\\s>/]`, "i").test(text) + ); +} + +/** + * The template and fragment references in the template `text` at `path` that name no template, or + * a fragment the named template lacks; `read` gives a file's text, `null` when it does not exist. + * Only where names resolve as Spring Boot's defaults resolve them (`templates/.html`, no + * `spring.thymeleaf.prefix` / `suffix` in `application`): elsewhere nothing is reported. A missing + * template is reported only in the project's own `src/main/resources/templates`: a nested module + * may get templates from another module or a jar. + */ +export async function unresolvedThymeleafReferences( + path: string, + text: string, + application: string, + projectRoot: string | null, + read: (path: string) => Promise, +): Promise>> { + const spring = path.lastIndexOf(SPRING_TEMPLATES); + if (spring < 0 || customTemplateLocation(application)) return []; + const root = path.slice(0, spring + SPRING_TEMPLATES.length - 1); + const ownModule = + projectRoot !== null && root === `${projectRoot.replace(/\/$/, "")}${SPRING_TEMPLATES.slice(0, -1)}`; + const comments = [...text.matchAll(COMMENT)].map((m) => [m.index, m.index + m[0].length] as const); + const refs = thymeleafReferences(text).filter( + (ref): ref is Exclude => + ref.kind !== "message" && + ref.template !== "_" && + !ref.template.split("/").some((s) => s === "." || s === "..") && + !comments.some(([from, to]) => from <= ref.from && ref.from < to) && + !((FALLBACK.lastIndex = ref.to), FALLBACK.test(text)), + ); + const names = [...new Set(refs.map((ref) => ref.template).filter(Boolean))]; + // The edited template itself is checked against its unsaved text. + const texts = await Promise.all( + names.map((name) => (templatePath(root, name) === path ? text : read(templatePath(root, name)))), + ); + const target = new Map(names.map((name, i) => [name, texts[i] ?? null])); + target.set("", text); + return refs.filter((ref) => { + const body = target.get(ref.template) ?? null; + return body === null + ? ref.kind === "template" && ownModule + : ref.kind === "fragment" && !definesFragment(body, ref.fragment); + }); +} diff --git a/src/platform/inspections.test.ts b/src/platform/inspections.test.ts index 38d20dffd..9b64ce086 100644 --- a/src/platform/inspections.test.ts +++ b/src/platform/inspections.test.ts @@ -51,6 +51,7 @@ describe("inspection profiles", () => { it("maps built-in producers to their inspections", () => { expect(producerInspectionId("file-references")).toBe("builtin:file-references"); + expect(producerInspectionId("thymeleaf-references")).toBe("builtin:thymeleaf-references"); expect(producerInspectionId("ruff")).toBe("lsp:ruff"); }); diff --git a/src/platform/inspections.ts b/src/platform/inspections.ts index a12c843f4..a23c0ca67 100644 --- a/src/platform/inspections.ts +++ b/src/platform/inspections.ts @@ -312,6 +312,15 @@ export const BUILTIN_INSPECTIONS: readonly BuiltinInspection[] = [ description: "Reports paths in HTML attributes, CSS url() and @import that do not name an existing file, resolved relative to the file, the project root and its resource roots.", }, + { + id: "builtin:thymeleaf-references", + producer: "thymeleaf-references", + name: "Unresolved template and fragment references", + group: "Thymeleaf", + description: + "Reports Thymeleaf fragment expressions under src/main/resources/templates that name a missing template, or a fragment the template does not define. Off when application.properties or .yml sets spring.thymeleaf.prefix or suffix.", + defaultLevel: "warning", + }, { id: "builtin:build", producer: "build", diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index dd11505db..9695b3f5d 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -669,6 +669,10 @@ "Dark gray": "Dark gray", "Magenta": "Magenta", "Editor inline blame": "Editor inline blame", + "Cannot resolve template '{template}'": "Cannot resolve template '{template}'", + "Cannot resolve fragment '{fragment}'": "Cannot resolve fragment '{fragment}'", + "Unresolved template and fragment references": "Unresolved template and fragment references", + "Reports Thymeleaf fragment expressions under src/main/resources/templates that name a missing template, or a fragment the template does not define. Off when application.properties or .yml sets spring.thymeleaf.prefix or suffix.": "Reports Thymeleaf fragment expressions under src/main/resources/templates that name a missing template, or a fragment the template does not define. Off when application.properties or .yml sets spring.thymeleaf.prefix or suffix.", "Annotations": "Annotations", "Last commit": "Last commit", "Annotations › Last commit": "Annotations › Last commit", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index bbc58e18c..96d9435a2 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -5574,6 +5574,10 @@ "No editor for “{kind}”": "没有适用于“{kind}”的编辑器", "Show usages of {name}": "显示 {name} 的用法", "Cannot resolve file '{value}'": "无法解析文件 '{value}'", + "Cannot resolve template '{template}'": "无法解析模板 '{template}'", + "Cannot resolve fragment '{fragment}'": "无法解析片段 '{fragment}'", + "Unresolved template and fragment references": "未解析的模板和片段引用", + "Reports Thymeleaf fragment expressions under src/main/resources/templates that name a missing template, or a fragment the template does not define. Off when application.properties or .yml sets spring.thymeleaf.prefix or suffix.": "报告 src/main/resources/templates 下 Thymeleaf 片段表达式中不存在的模板,或模板中未定义的片段。application.properties 或 .yml 设置了 spring.thymeleaf.prefix 或 suffix 时不检查。", "Reformat File: {name}": "重新格式化文件:{name}", "Inspection '{name}' options": "检查 '{name}' 的选项", "Choose Declaration of '{label}' ({count} found)": "选择 '{label}' 的声明(找到 {count} 个)",