Repository: sveltejs/svelte (JavaScript)
Date: 2022-09-02 11:30:57+00:00
Task type: Bug Fix

Issue:
Non-Svelte imports trigger `x will be treated as an HTML element` warning
**Describe the bug**
Importing a module with the same name as a HTML element causes Svelte to issue a warning about the element being treated as HTML unless it begins with a capital.

**Logs**
Example:
```sh
<section> will be treated as an HTML element unless it begins with a capital letter
```

**To Reproduce**
Import any module with the name of an HTML element, then use that HTML element in Svelte markup.

Eg:

```svelte
<script>
  import { section } from '../styles/mixins.ts';
</script>

<section class={section}>
 ...
</section>
```

**Expected behavior**
Svelte should not issue warnings about HTML element usage if the module imported was not a Svelte component.


**Information about your Svelte project:**
 System:
    OS: macOS 11.0.1
    CPU: (4) x64 Intel(R) Core(TM) i5-7360U CPU @ 2.30GHz
    Memory: 549.42 MB / 16.00 GB
    Shell: 5.7.1 - /usr/local/bin/zsh
  Binaries:
    Node: 12.6.0 - /usr/local/bin/node
    Yarn: 1.22.4 - ~/.yarn/bin/yarn
    npm: 6.9.0 - /usr/local/bin/npm
  Browsers:
    Chrome: 86.0.4240.198
    Firefox: 74.0
    Safari: 14.0.1
  npmPackages:
    svelte: ^3.17.3 => 3.29.0 


Using Webpack

**Severity**
Merely annoying. Just adds extra console noise, no impact on usage at all.



Issue discussion:
This came up before in #5570. I don't know what would be a better option for a reasonable heuristic for this warning.
Is the warning even that necessary? If it's getting triggered by simple use-cases like this I think it's more of a hinderance than a help in DX. At least providing a way to opt-out of it would be good. Because anyone coming from a JSX-like syntax will be familiar with needing uppercased components, and Svelte can (does?) document the need for uppercase components during the starter tutorial.

I know I was surprised to see the warning at all.

EDIT — I see you can disable the warning on a per-line basis with comments, but that seems clunky for something that IMO is flaky and unnecessary. Would be great if we could opt out at a global level, or just remove it entirely. Does the Svelte team have data on how common a problem it is to warn against?
![Screenshot 2020-12-19 at 9 12 52 pm](https://user-images.githubusercontent.com/2401925/102699742-00e03a80-423f-11eb-9b85-a3c744470266.png)
im being flagged for images, not too sure why
`<a><img><div>`  are the ending tags on proper order?
they are yes
Ok so i'm a dope, there was a helper function called `img` 😅 which makes a heck of a lot more sense considering the warnings! (this message is mostly for my future self)
Same bug. If the import commented out the warning dissapears.

<img width="733" alt="Screen Shot 2021-06-08 at 11 34 30 pm" src="https://user-images.githubusercontent.com/94196/121253768-2e36a880-c8b2-11eb-9da2-74a97912a921.png">

Is there a solution available? My Svelte code is full of unnecessary warnings about valid html tags.

Example:
```
<form> will be treated as an HTML element unless it begins with a capital letter
```
> Is there a solution available? My Svelte code is full of unnecessary warnings about valid html tags.
> 
> Example:
> 
> ```
> <form> will be treated as an HTML element unless it begins with a capital letter
> ```

To avoid the warning one could import the library as such:

```ts
import * as sf from "svelte-forms";
sf.form(...);
```

Solution patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,7 @@
 * Improve a11y `label-has-associated-control` check to recusively check for input control ([#5528](https://github.com/sveltejs/svelte/issues/5528))
 * Fix class directive updates after half way transition [#7764](https://github.com/sveltejs/svelte/issues/7764)
 * Improve parsing speed when encountering large blocks of whitespace [#7675](https://github.com/sveltejs/svelte/issues/7675)
+* Only show lowercase component warning for non-html/svg elements [#5712](https://github.com/sveltejs/svelte/issues/5712)
 
 ## 3.49.0
 
diff --git a/src/compiler/compile/nodes/Element.ts b/src/compiler/compile/nodes/Element.ts
--- a/src/compiler/compile/nodes/Element.ts
+++ b/src/compiler/compile/nodes/Element.ts
@@ -1,4 +1,4 @@
-import { is_void } from '../../../shared/utils/names';
+import { is_html, is_svg, is_void } from '../../../shared/utils/names';
 import Node from './shared/Node';
 import Attribute from './Attribute';
 import Binding from './Binding';
@@ -26,8 +26,6 @@ import compiler_errors from '../compiler_errors';
 import { ARIARoleDefintionKey, roles, aria, ARIAPropertyDefinition, ARIAProperty } from 'aria-query';
 import { is_interactive_element, is_non_interactive_roles, is_presentation_role } from '../utils/a11y';
 
-const svg = /^(?:altGlyph|altGlyphDef|altGlyphItem|animate|animateColor|animateMotion|animateTransform|circle|clipPath|color-profile|cursor|defs|desc|discard|ellipse|feBlend|feColorMatrix|feComponentTransfer|feComposite|feConvolveMatrix|feDiffuseLighting|feDisplacementMap|feDistantLight|feDropShadow|feFlood|feFuncA|feFuncB|feFuncG|feFuncR|feGaussianBlur|feImage|feMerge|feMergeNode|feMorphology|feOffset|fePointLight|feSpecularLighting|feSpotLight|feTile|feTurbulence|filter|font|font-face|font-face-format|font-face-name|font-face-src|font-face-uri|foreignObject|g|glyph|glyphRef|hatch|hatchpath|hkern|image|line|linearGradient|marker|mask|mesh|meshgradient|meshpatch|meshrow|metadata|missing-glyph|mpath|path|pattern|polygon|polyline|radialGradient|rect|set|solidcolor|stop|svg|switch|symbol|text|textPath|tref|tspan|unknown|use|view|vkern)$/;
-
 const aria_attributes = 'activedescendant atomic autocomplete busy checked colcount colindex colspan controls current describedby description details disabled dropeffect errormessage expanded flowto grabbed haspopup hidden invalid keyshortcuts label labelledby level live modal multiline multiselectable orientation owns placeholder posinset pressed readonly relevant required roledescription rowcount rowindex rowspan selected setsize sort valuemax valuemin valuenow valuetext'.split(' ');
 const aria_attribute_set = new Set(aria_attributes);
 
@@ -166,13 +164,13 @@ function get_namespace(parent: Element, element: Element, explicit_namespace: st
 	const parent_element = parent.find_nearest(/^Element/);
 
 	if (!parent_element) {
-		return explicit_namespace || (svg.test(element.name)
+		return explicit_namespace || (is_svg(element.name)
 			? namespaces.svg
 			: null);
 	}
 
 	if (parent_element.namespace !== namespaces.foreign) {
-		if (svg.test(element.name.toLowerCase())) return namespaces.svg;
+		if (is_svg(element.name.toLowerCase())) return namespaces.svg;
 		if (parent_element.name.toLowerCase() === 'foreignobject') return null;
 	}
 
@@ -373,7 +371,7 @@ export default class Element extends Node {
 	}
 
 	validate() {
-		if (this.component.var_lookup.has(this.name) && this.component.var_lookup.get(this.name).imported) {
+		if (this.component.var_lookup.has(this.name) && this.component.var_lookup.get(this.name).imported && !is_svg(this.name) && !is_html(this.name)) {
 			this.component.warn(this, compiler_warnings.component_name_lowercase(this.name));
 		}
 
@@ -827,7 +825,7 @@ export default class Element extends Node {
 			} else if (dimensions.test(name)) {
 				if (this.name === 'svg' && (name === 'offsetWidth' || name === 'offsetHeight')) {
 					return component.error(binding, compiler_errors.invalid_binding_on(binding.name, `<svg>. Use '${name.replace('offset', 'client')}' instead`));
-				} else if (svg.test(this.name)) {
+				} else if (is_svg(this.name)) {
 					return component.error(binding, compiler_errors.invalid_binding_on(binding.name, 'SVG elements'));
 				} else if (is_void(this.name)) {
 					return component.error(binding, compiler_errors.invalid_binding_on(binding.name, `void elements like <${this.name}>. Use a wrapper element instead`));
diff --git a/src/shared/utils/names.ts b/src/shared/utils/names.ts
--- a/src/shared/utils/names.ts
+++ b/src/shared/utils/names.ts
@@ -1,5 +1,18 @@
+/** regex of all html void element names */
 const void_element_names = /^(?:area|base|br|col|command|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)$/;
+/** regex of all html element names. svg and math are omitted because they belong to the svg elements namespace */
+const html_element_names = /^(?:a|abbr|address|area|article|aside|audio|b|base|bdi|bdo|blockquote|body|br|button|canvas|caption|cite|code|col|colgroup|data|datalist|dd|del|details|dfn|dialog|div|dl|dt|em|embed|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|head|header|hr|html|i|iframe|img|input|ins|kbd|label|legend|li|link|main|map|mark|meta|meter|nav|noscript|object|ol|optgroup|option|output|p|param|picture|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|small|source|span|strong|style|sub|summary|sup|table|tbody|td|template|textarea|tfoot|th|thead|time|title|tr|track|u|ul|var|video|wbr)$/;
+/** regex of all svg element names */
+const svg = /^(?:altGlyph|altGlyphDef|altGlyphItem|animate|animateColor|animateMotion|animateTransform|circle|clipPath|color-profile|cursor|defs|desc|discard|ellipse|feBlend|feColorMatrix|feComponentTransfer|feComposite|feConvolveMatrix|feDiffuseLighting|feDisplacementMap|feDistantLight|feDropShadow|feFlood|feFuncA|feFuncB|feFuncG|feFuncR|feGaussianBlur|feImage|feMerge|feMergeNode|feMorphology|feOffset|fePointLight|feSpecularLighting|feSpotLight|feTile|feTurbulence|filter|font|font-face|font-face-format|font-face-name|font-face-src|font-face-uri|foreignObject|g|glyph|glyphRef|hatch|hatchpath|hkern|image|line|linearGradient|marker|mask|mesh|meshgradient|meshpatch|meshrow|metadata|missing-glyph|mpath|path|pattern|polygon|polyline|radialGradient|rect|set|solidcolor|stop|svg|switch|symbol|text|textPath|tref|tspan|unknown|use|view|vkern)$/;
 
 export function is_void(name: string) {
 	return void_element_names.test(name) || name.toLowerCase() === '!doctype';
 }
+
+export function is_html(name: string) {
+	return html_element_names.test(name);
+}
+
+export function is_svg(name: string) {
+	return svg.test(name);
+}


Test patch:
diff --git a/test/validator/samples/component-name-lowercase/input.svelte b/test/validator/samples/component-name-lowercase/input.svelte
--- a/test/validator/samples/component-name-lowercase/input.svelte
+++ b/test/validator/samples/component-name-lowercase/input.svelte
@@ -1,7 +1,10 @@
 <script>
 	import thisShouldWarnMe from './MyComponent.svelte';
+	import { form } from './form';
 	let i;
+	form;
 </script>
 
 <thisShouldWarnMe />
-<i />
\ No newline at end of file
+<i />
+<form />
diff --git a/test/validator/samples/component-name-lowercase/warnings.json b/test/validator/samples/component-name-lowercase/warnings.json
--- a/test/validator/samples/component-name-lowercase/warnings.json
+++ b/test/validator/samples/component-name-lowercase/warnings.json
@@ -2,16 +2,16 @@
 	{
 		"code": "component-name-lowercase",
 		"message": "<thisShouldWarnMe> will be treated as an HTML element unless it begins with a capital letter",
-		"pos": 82,
+		"pos": 121,
 		"start": {
-			"character": 82,
+			"character": 121,
 			"column": 0,
-			"line": 6
+			"line": 8
 		},
 		"end": {
-			"character": 102,
+			"character": 141,
 			"column": 20,
-			"line": 6
+			"line": 8
 		}
 	}
 ]