-
-
Notifications
You must be signed in to change notification settings - Fork 9k
/
Copy pathno-html-links.ts
102 lines (91 loc) · 2.71 KB
/
no-html-links.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {createRule} from '../util';
import type {TSESTree} from '@typescript-eslint/types';
const docsUrl = 'https://docusaurus.io/docs/docusaurus-core#link';
type Options = [
{
ignoreFullyResolved: boolean;
},
];
type MessageIds = 'link';
function isFullyResolvedUrl(urlString: string): boolean {
try {
// href gets coerced to a string when it gets rendered anyway
const url = new URL(String(urlString));
if (url.protocol) {
return true;
}
} catch (e) {}
return false;
}
export default createRule<Options, MessageIds>({
name: 'no-html-links',
meta: {
type: 'problem',
docs: {
description: 'enforce using Docusaurus Link component instead of <a> tag',
},
schema: [
{
type: 'object',
properties: {
ignoreFullyResolved: {
type: 'boolean',
},
},
additionalProperties: false,
},
],
messages: {
link: `Do not use an \`<a>\` element to navigate. Use the \`<Link />\` component from \`@docusaurus/Link\` instead. See: ${docsUrl}`,
},
},
defaultOptions: [
{
ignoreFullyResolved: false,
},
],
create(context, [options]) {
const {ignoreFullyResolved} = options;
return {
JSXOpeningElement(node) {
if ((node.name as TSESTree.JSXIdentifier).name !== 'a') {
return;
}
if (ignoreFullyResolved) {
const hrefAttr = node.attributes.find(
(attr): attr is TSESTree.JSXAttribute =>
attr.type === 'JSXAttribute' && attr.name.name === 'href',
);
if (hrefAttr?.value?.type === 'Literal') {
if (isFullyResolvedUrl(String(hrefAttr.value.value))) {
return;
}
}
if (hrefAttr?.value?.type === 'JSXExpressionContainer') {
const container: TSESTree.JSXExpressionContainer = hrefAttr.value;
const {expression} = container;
if (expression.type === 'TemplateLiteral') {
// Simple static string template literals
if (
expression.expressions.length === 0 &&
expression.quasis.length === 1 &&
expression.quasis[0]?.type === 'TemplateElement' &&
isFullyResolvedUrl(String(expression.quasis[0].value.raw))
) {
return;
}
// TODO add more complex TemplateLiteral cases here
}
}
}
context.report({node, messageId: 'link'});
},
};
},
});