|
| 1 | +package checked_requires_onchange_or_readonly |
| 2 | + |
| 3 | +import ( |
| 4 | + "github.com/microsoft/typescript-go/shim/ast" |
| 5 | + "github.com/web-infra-dev/rslint/internal/plugins/react/reactutil" |
| 6 | + "github.com/web-infra-dev/rslint/internal/rule" |
| 7 | + "github.com/web-infra-dev/rslint/internal/utils" |
| 8 | +) |
| 9 | + |
| 10 | +const ( |
| 11 | + msgMissingProperty = "`checked` should be used with either `onChange` or `readOnly`." |
| 12 | + msgExclusiveCheckedAttribute = "Use either `checked` or `defaultChecked`, but not both." |
| 13 | +) |
| 14 | + |
| 15 | +// targetProps mirrors upstream's `targetPropSet`. Only these four names are |
| 16 | +// tracked; every other attribute / property is ignored. Note the rule does |
| 17 | +// NOT inspect the `type` attribute — any `<input>` (or `createElement('input')`) |
| 18 | +// carrying `checked` is checked, regardless of `type="checkbox"` vs `"radio"` |
| 19 | +// vs anything else. |
| 20 | +var targetProps = map[string]struct{}{ |
| 21 | + "checked": {}, |
| 22 | + "onChange": {}, |
| 23 | + "readOnly": {}, |
| 24 | + "defaultChecked": {}, |
| 25 | +} |
| 26 | + |
| 27 | +type options struct { |
| 28 | + ignoreMissingProperties bool |
| 29 | + ignoreExclusiveCheckedAttribute bool |
| 30 | +} |
| 31 | + |
| 32 | +func parseOptions(opts any) options { |
| 33 | + o := options{} |
| 34 | + optsMap := utils.GetOptionsMap(opts) |
| 35 | + if optsMap == nil { |
| 36 | + return o |
| 37 | + } |
| 38 | + if v, ok := optsMap["ignoreMissingProperties"].(bool); ok { |
| 39 | + o.ignoreMissingProperties = v |
| 40 | + } |
| 41 | + if v, ok := optsMap["ignoreExclusiveCheckedAttribute"].(bool); ok { |
| 42 | + o.ignoreExclusiveCheckedAttribute = v |
| 43 | + } |
| 44 | + return o |
| 45 | +} |
| 46 | + |
| 47 | +var CheckedRequiresOnchangeOrReadonlyRule = rule.Rule{ |
| 48 | + Name: "react/checked-requires-onchange-or-readonly", |
| 49 | + Run: func(ctx rule.RuleContext, opts any) rule.RuleListeners { |
| 50 | + o := parseOptions(opts) |
| 51 | + pragma := reactutil.GetReactPragma(ctx.Settings) |
| 52 | + |
| 53 | + // checkAndReport mirrors upstream's `checkAttributesAndReport`: report |
| 54 | + // only when `checked` is present, then emit the exclusive-attribute and |
| 55 | + // missing-property diagnostics in that order (so a node carrying both |
| 56 | + // `checked` and `defaultChecked` reports exclusiveCheckedAttribute first). |
| 57 | + checkAndReport := func(node *ast.Node, propSet map[string]struct{}) { |
| 58 | + if _, hasChecked := propSet["checked"]; !hasChecked { |
| 59 | + return |
| 60 | + } |
| 61 | + if _, hasDefaultChecked := propSet["defaultChecked"]; !o.ignoreExclusiveCheckedAttribute && hasDefaultChecked { |
| 62 | + ctx.ReportNode(node, rule.RuleMessage{ |
| 63 | + Id: "exclusiveCheckedAttribute", |
| 64 | + Description: msgExclusiveCheckedAttribute, |
| 65 | + }) |
| 66 | + } |
| 67 | + _, hasOnChange := propSet["onChange"] |
| 68 | + _, hasReadOnly := propSet["readOnly"] |
| 69 | + if !o.ignoreMissingProperties && !hasOnChange && !hasReadOnly { |
| 70 | + ctx.ReportNode(node, rule.RuleMessage{ |
| 71 | + Id: "missingProperty", |
| 72 | + Description: msgMissingProperty, |
| 73 | + }) |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + // checkJsxElement handles the upstream `JSXOpeningElement` listener. In |
| 78 | + // tsgo a self-closing `<input/>` is a JsxSelfClosingElement and a paired |
| 79 | + // `<input></input>` produces a JsxOpeningElement, so both kinds route |
| 80 | + // here. The element node itself is the report target, matching upstream's |
| 81 | + // `report(..., { node })` on the JSXOpeningElement (whose loc is the |
| 82 | + // opening tag, not the whole element). |
| 83 | + checkJsxElement := func(node *ast.Node) { |
| 84 | + if reactutil.GetJsxElementTypeString(node) != "input" { |
| 85 | + return |
| 86 | + } |
| 87 | + checkAndReport(node, jsxPropSet(reactutil.GetJsxElementAttributes(node))) |
| 88 | + } |
| 89 | + |
| 90 | + return rule.RuleListeners{ |
| 91 | + ast.KindJsxOpeningElement: checkJsxElement, |
| 92 | + ast.KindJsxSelfClosingElement: checkJsxElement, |
| 93 | + ast.KindCallExpression: func(node *ast.Node) { |
| 94 | + call := node.AsCallExpression() |
| 95 | + if !reactutil.IsCreateElementCall(call.Expression, pragma) { |
| 96 | + return |
| 97 | + } |
| 98 | + // Upstream requires `arguments[0]` to be a string Literal "input" |
| 99 | + // and `arguments[1]` to be an ObjectExpression; anything else |
| 100 | + // (missing args, non-literal tag, non-object props) bails out. |
| 101 | + if call.Arguments == nil || len(call.Arguments.Nodes) < 2 { |
| 102 | + return |
| 103 | + } |
| 104 | + firstArg := ast.SkipParentheses(call.Arguments.Nodes[0]) |
| 105 | + if firstArg.Kind != ast.KindStringLiteral || firstArg.AsStringLiteral().Text != "input" { |
| 106 | + return |
| 107 | + } |
| 108 | + secondArg := ast.SkipParentheses(call.Arguments.Nodes[1]) |
| 109 | + if secondArg.Kind != ast.KindObjectLiteralExpression { |
| 110 | + return |
| 111 | + } |
| 112 | + checkAndReport(node, objectPropSet(secondArg.AsObjectLiteralExpression())) |
| 113 | + }, |
| 114 | + } |
| 115 | + }, |
| 116 | +} |
| 117 | + |
| 118 | +// jsxPropSet collects the subset of `targetProps` present as JSX attributes, |
| 119 | +// mirroring upstream `extractTargetProps(node.attributes, 'name')`. |
| 120 | +// reactutil.GetJsxPropName returns the plain attribute name for an identifier |
| 121 | +// attribute, "ns:name" for a namespaced one, and "spread" for a spread |
| 122 | +// attribute — none of which (besides a plain identifier) can land in |
| 123 | +// targetProps, exactly like upstream's `attr.name.name` access where a |
| 124 | +// spread has no `.name` and a namespaced `.name` is a node, not a string. |
| 125 | +func jsxPropSet(attrs []*ast.Node) map[string]struct{} { |
| 126 | + set := make(map[string]struct{}) |
| 127 | + for _, attr := range attrs { |
| 128 | + name := reactutil.GetJsxPropName(attr) |
| 129 | + if _, ok := targetProps[name]; ok { |
| 130 | + set[name] = struct{}{} |
| 131 | + } |
| 132 | + } |
| 133 | + return set |
| 134 | +} |
| 135 | + |
| 136 | +// objectPropSet collects the subset of `targetProps` present as object keys, |
| 137 | +// mirroring upstream `extractTargetProps(secondArg.properties, 'key')`. |
| 138 | +func objectPropSet(obj *ast.ObjectLiteralExpression) map[string]struct{} { |
| 139 | + set := make(map[string]struct{}) |
| 140 | + if obj.Properties == nil { |
| 141 | + return set |
| 142 | + } |
| 143 | + for _, prop := range obj.Properties.Nodes { |
| 144 | + name, ok := objectKeyName(prop) |
| 145 | + if !ok { |
| 146 | + continue |
| 147 | + } |
| 148 | + if _, isTarget := targetProps[name]; isTarget { |
| 149 | + set[name] = struct{}{} |
| 150 | + } |
| 151 | + } |
| 152 | + return set |
| 153 | +} |
| 154 | + |
| 155 | +// objectKeyName reproduces upstream's `prop.key.name` access on an object |
| 156 | +// property. Upstream reads `.name` without gating on `computed`, so: |
| 157 | +// - `{ checked: … }` → "checked" (Identifier key) |
| 158 | +// - `{ checked }` → "checked" (shorthand) |
| 159 | +// - `{ [checked]: … }` → "checked" (computed Identifier — `.name` exists) |
| 160 | +// - `{ "checked": … }` → not matched (string Literal key has `.value`, not `.name`) |
| 161 | +// - `{ ["checked"]: … }` → not matched (computed string Literal key) |
| 162 | +// - `{ ...rest }` → not matched (SpreadAssignment has no `.key`) |
| 163 | +func objectKeyName(prop *ast.Node) (string, bool) { |
| 164 | + var nameNode *ast.Node |
| 165 | + switch prop.Kind { |
| 166 | + case ast.KindPropertyAssignment: |
| 167 | + nameNode = prop.AsPropertyAssignment().Name() |
| 168 | + case ast.KindShorthandPropertyAssignment: |
| 169 | + nameNode = prop.AsShorthandPropertyAssignment().Name() |
| 170 | + default: |
| 171 | + return "", false |
| 172 | + } |
| 173 | + if nameNode == nil { |
| 174 | + return "", false |
| 175 | + } |
| 176 | + switch nameNode.Kind { |
| 177 | + case ast.KindIdentifier: |
| 178 | + return nameNode.AsIdentifier().Text, true |
| 179 | + case ast.KindComputedPropertyName: |
| 180 | + inner := ast.SkipParentheses(nameNode.AsComputedPropertyName().Expression) |
| 181 | + if inner != nil && inner.Kind == ast.KindIdentifier { |
| 182 | + return inner.AsIdentifier().Text, true |
| 183 | + } |
| 184 | + } |
| 185 | + return "", false |
| 186 | +} |
0 commit comments