Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / lint-rules / src / main / java / com / vayunmathur / lint / NoDeadClickDetector.kt
NoDeadClickDetector.kt249 lines · 11.8 KiBRaw
| 1 | package com.vayunmathur.lint |
| 2 | |
| 3 | import com.android.tools.lint.detector.api.Category |
| 4 | import com.android.tools.lint.detector.api.Detector |
| 5 | import com.android.tools.lint.detector.api.Implementation |
| 6 | import com.android.tools.lint.detector.api.Issue |
| 7 | import com.android.tools.lint.detector.api.JavaContext |
| 8 | import com.android.tools.lint.detector.api.Scope |
| 9 | import com.android.tools.lint.detector.api.Severity |
| 10 | import com.android.tools.lint.detector.api.SourceCodeScanner |
| 11 | import com.intellij.psi.PsiMethod |
| 12 | import org.jetbrains.kotlin.psi.KtFile |
| 13 | import org.jetbrains.uast.UCallExpression |
| 14 | import org.jetbrains.uast.UExpression |
| 15 | import org.jetbrains.uast.ULambdaExpression |
| 16 | import org.jetbrains.uast.ULiteralExpression |
| 17 | import org.jetbrains.uast.getParentOfType |
| 18 | |
| 19 | /** |
| 20 | * No dead clicks: a clickable widget whose click handler does nothing. |
| 21 | * |
| 22 | * A `Button`/`IconButton`/FAB/menu item/list row that renders as tappable |
| 23 | * but whose `onClick` lambda is empty (or comment-only) is a broken promise |
| 24 | * in the UI: the user taps, nothing happens, and nothing in review or in a |
| 25 | * screenshot shows it. This detector flags the empty handler at the call |
| 26 | * site in `src/main`. |
| 27 | * |
| 28 | * Widget set (by simple call name, resolved against Compose/library |
| 29 | * containers): `Button`, `TextButton`, `OutlinedButton`, |
| 30 | * `FilledTonalButton`, `ElevatedButton`, the FAB family, `IconButton`, |
| 31 | * `IconToggleButton`, `DropdownMenuItem`, `MenuItem`, `SegmentedButton`, |
| 32 | * and the TV row family (`TvButton`, `TvListRow`, `ListItem`). A widget |
| 33 | * call's `Modifier.clickable`/`combinedClickable` is covered the same way |
| 34 | * when it sits in that call's modifier (the list-row shape), and a bare |
| 35 | * `clickable`/`combinedClickable` call is flagged wherever it appears. |
| 36 | * |
| 37 | * Precision choices (deliberate): |
| 38 | * - `enabled = false` in the same call opts out: a disabled widget with an |
| 39 | * empty handler is honest — it does not promise a tap. (Busy-state |
| 40 | * buttons and display rows use this.) |
| 41 | * - Display-only label chips are excluded by widget type: `AssistChip`, |
| 42 | * `FilterChip`, chips generally are simply not in the widget set — the |
| 43 | * repo renders read-only labels with them and they carry no click |
| 44 | * promise this rule polices. Fix those by demoting the chip, not here. |
| 45 | * - A `clickable`/`combinedClickable` with a non-empty `onLongClick` is |
| 46 | * not dead: long-press-only rows (copy-on-long-press) work. |
| 47 | * - Only a literal empty/comment-only lambda is flagged. A handler passed |
| 48 | * as a reference (`onClick = onOpen`, `onClick = actions::save`) or a |
| 49 | * parameter default is never guessed at. |
| 50 | * |
| 51 | * Fix, in order of preference: wire the handler to the real action; |
| 52 | * disable the widget honestly (`enabled = false`); or demote it to a |
| 53 | * non-button container (a `Box`/`Icon` with the same modifier). The one |
| 54 | * legitimate shape left — a drag handle grip that must look like a button |
| 55 | * while the reorder modifier owns the gesture — opts out per file with: |
| 56 | * `// DEAD CLICK EXCEPTION: <reason>`. |
| 57 | */ |
| 58 | class NoDeadClickDetector : Detector(), SourceCodeScanner { |
| 59 | |
| 60 | override fun getApplicableMethodNames(): List<String> = APPLICABLE.toList() |
| 61 | |
| 62 | override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) { |
| 63 | val name = method.name |
| 64 | val file = context.file |
| 65 | if (!file.path.replace('\\', '/').contains("/src/main/")) return |
| 66 | val packageName = context.uastFile?.packageName ?: return |
| 67 | if (!packageName.startsWith(APP_PACKAGE_PREFIX)) return |
| 68 | |
| 69 | val ktFile = context.uastFile?.sourcePsi as? KtFile |
| 70 | if (ktFile != null && CommentOnlyMatcher.containsMarkerInComments(ktFile, EXCEPTION_MARKER)) return |
| 71 | |
| 72 | if (name in CLICKABLE_CALLS) { |
| 73 | checkClickable(context, node, method, enclosingWidgetName(node) ?: name) |
| 74 | return |
| 75 | } |
| 76 | if (name !in WIDGET_CALLS) return |
| 77 | if (!isWidgetContainer(method)) return |
| 78 | if (hasDisabledFalse(node, method)) return |
| 79 | |
| 80 | // A clickable in this widget's own modifier (the list-row shape). |
| 81 | var flagged = false |
| 82 | for (arg in node.valueArguments) { |
| 83 | val click = findNestedClickable(arg) ?: continue |
| 84 | if (isDeadClickable(click, null)) { |
| 85 | report(context, click, name) |
| 86 | flagged = true |
| 87 | } |
| 88 | } |
| 89 | if (flagged) return |
| 90 | |
| 91 | val onClick = argumentFor(node, method, "onClick") ?: return |
| 92 | if (isEmptyLambda(onClick)) { |
| 93 | report(context, node, name) |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | private fun checkClickable(context: JavaContext, node: UCallExpression, method: PsiMethod, widgetName: String) { |
| 98 | if (!isDeadClickable(node, method)) return |
| 99 | // Widget calls check their own modifier's clickable (above); do not |
| 100 | // double-report the same lambda from both visits. |
| 101 | val parentCall = node.getParentOfType<UCallExpression>(strict = true) |
| 102 | if (parentCall != null && parentCall.methodName in WIDGET_CALLS) return |
| 103 | report(context, node, widgetName) |
| 104 | } |
| 105 | |
| 106 | private fun report(context: JavaContext, node: UCallExpression, widgetName: String) { |
| 107 | context.report( |
| 108 | ISSUE, |
| 109 | node, |
| 110 | context.getLocation(node), |
| 111 | "Dead click: `$widgetName` renders as tappable but its click handler is " + |
| 112 | "empty, so tapping it does nothing. Wire it to the real action, disable " + |
| 113 | "it honestly (`enabled = false`), or demote it to a non-button " + |
| 114 | "container. A drag-handle grip whose reorder modifier owns the gesture " + |
| 115 | "opts out per file with `$EXCEPTION_MARKER <reason>`.", |
| 116 | ) |
| 117 | } |
| 118 | |
| 119 | /** True for an empty/comment-only `onClick` with no working `onLongClick` and not disabled. */ |
| 120 | private fun isDeadClickable(node: UCallExpression, method: PsiMethod?): Boolean { |
| 121 | if (method != null && hasDisabledFalse(node, method)) return false |
| 122 | val onLongClick = method?.let { argumentFor(node, it, "onLongClick") } ?: argumentByName(node, "onLongClick") |
| 123 | if (onLongClick != null && !isEmptyLambda(onLongClick) && !isNullLiteral(onLongClick)) return false |
| 124 | val onClick = (method?.let { argumentFor(node, it, "onClick") } ?: argumentByName(node, "onClick")) |
| 125 | // Trailing lambda: Modifier.clickable { … } |
| 126 | ?: node.valueArguments.lastOrNull()?.takeIf { it is ULambdaExpression } |
| 127 | ?: return false |
| 128 | return isEmptyLambda(onClick) |
| 129 | } |
| 130 | |
| 131 | /** The nearest enclosing widget call's name, for the message (list-row modifier shape). */ |
| 132 | private fun enclosingWidgetName(node: UCallExpression): String? { |
| 133 | var parent = node.getParentOfType<UCallExpression>(strict = true) |
| 134 | while (parent != null) { |
| 135 | val n = parent.methodName |
| 136 | if (n in WIDGET_CALLS) return n |
| 137 | parent = parent.getParentOfType<UCallExpression>(strict = true) |
| 138 | } |
| 139 | return null |
| 140 | } |
| 141 | |
| 142 | private fun findNestedClickable(expr: UExpression): UCallExpression? { |
| 143 | if (expr is UCallExpression && expr.methodName in CLICKABLE_CALLS) return expr |
| 144 | // Modifier chains are nested calls (`.clickable{}.then(…)` etc.): |
| 145 | // walk the UAST subtree for the first clickable call. |
| 146 | var found: UCallExpression? = null |
| 147 | expr.accept(object : org.jetbrains.uast.visitor.AbstractUastVisitor() { |
| 148 | override fun visitCallExpression(node: UCallExpression): Boolean { |
| 149 | if (found == null && node !== expr && node.methodName in CLICKABLE_CALLS) { |
| 150 | found = node |
| 151 | } |
| 152 | return super.visitCallExpression(node) |
| 153 | } |
| 154 | }) |
| 155 | return found |
| 156 | } |
| 157 | |
| 158 | private fun hasDisabledFalse(node: UCallExpression, method: PsiMethod): Boolean { |
| 159 | val enabled = argumentFor(node, method, "enabled") ?: return false |
| 160 | return enabled is ULiteralExpression && enabled.value == false |
| 161 | } |
| 162 | |
| 163 | private fun isNullLiteral(expr: UExpression): Boolean = |
| 164 | expr is ULiteralExpression && expr.isNull |
| 165 | |
| 166 | /** |
| 167 | * Empty or comment-only lambda. UAST drops comments from the lambda |
| 168 | * body, so a comment-only lambda and `{}` both have no expressions; |
| 169 | * a body holding only another lambda's braces still counts as work |
| 170 | * only if it has expressions — checked recursively by UAST shape. |
| 171 | */ |
| 172 | private fun isEmptyLambda(expr: UExpression): Boolean { |
| 173 | val lambda = expr as? ULambdaExpression ?: return false |
| 174 | val body = lambda.body as? org.jetbrains.uast.UBlockExpression ?: return false |
| 175 | return body.expressions.isEmpty() |
| 176 | } |
| 177 | |
| 178 | /** Argument by parameter name via the resolved method's parameter list. */ |
| 179 | private fun argumentFor(node: UCallExpression, method: PsiMethod, paramName: String): UExpression? { |
| 180 | val index = method.parameterList.parameters.indexOfFirst { it.name == paramName } |
| 181 | if (index < 0) return argumentByName(node, paramName) |
| 182 | return node.getArgumentForParameter(index) |
| 183 | } |
| 184 | |
| 185 | /** |
| 186 | * Argument by source-level named-argument shape: lint's UAST keeps |
| 187 | * named arguments in [org.jetbrains.uast.UNamedExpression] wrappers in |
| 188 | * some shapes and plain values in others, so match on the argument's |
| 189 | * own name when present and fall back to the last lambda (trailing). |
| 190 | */ |
| 191 | private fun argumentByName(node: UCallExpression, paramName: String): UExpression? { |
| 192 | for (arg in node.valueArguments) { |
| 193 | val named = arg as? org.jetbrains.uast.UNamedExpression |
| 194 | if (named?.name == paramName) return named.expression |
| 195 | } |
| 196 | return null |
| 197 | } |
| 198 | |
| 199 | private fun isWidgetContainer(method: PsiMethod): Boolean { |
| 200 | val containing = method.containingClass?.qualifiedName ?: return true |
| 201 | return containing.contains("compose") || |
| 202 | containing.startsWith("com.vayunmathur.library") || |
| 203 | containing.contains("androidx.tv") || |
| 204 | containing.contains("androidx.wear") |
| 205 | } |
| 206 | |
| 207 | companion object { |
| 208 | private const val APP_PACKAGE_PREFIX = "com.vayunmathur." |
| 209 | |
| 210 | const val EXCEPTION_MARKER = "// DEAD CLICK EXCEPTION:" |
| 211 | |
| 212 | private val WIDGET_CALLS = setOf( |
| 213 | "Button", "TextButton", "OutlinedButton", "FilledTonalButton", "ElevatedButton", |
| 214 | "FloatingActionButton", "SmallFloatingActionButton", "LargeFloatingActionButton", |
| 215 | "ExtendedFloatingActionButton", "SmallExtendedFloatingActionButton", |
| 216 | "IconButton", "IconToggleButton", |
| 217 | "DropdownMenuItem", "MenuItem", "SegmentedButton", |
| 218 | "TvButton", "TvListRow", "ListItem", |
| 219 | ) |
| 220 | |
| 221 | private val CLICKABLE_CALLS = setOf("clickable", "combinedClickable") |
| 222 | |
| 223 | private val APPLICABLE = WIDGET_CALLS + CLICKABLE_CALLS |
| 224 | |
| 225 | val ISSUE: Issue = Issue.create( |
| 226 | id = "NoDeadClick", |
| 227 | briefDescription = "Clickable widget with an empty click handler", |
| 228 | explanation = """ |
| 229 | A Button, IconButton, FAB, menu item, segmented button, TV row, \ |
| 230 | ListItem, or Modifier.clickable/combinedClickable whose onClick lambda \ |
| 231 | is empty (or comment-only) renders as tappable and does nothing when \ |
| 232 | tapped. Wire the handler to the real action, disable the widget \ |
| 233 | honestly with `enabled = false`, or demote it to a non-button \ |
| 234 | container. Display-only label chips are excluded by widget type, \ |
| 235 | `enabled = false` widgets are honest, and long-press-only rows with \ |
| 236 | a working onLongClick are not dead. A drag-handle grip whose reorder \ |
| 237 | modifier owns the gesture opts out per file with \ |
| 238 | `// DEAD CLICK EXCEPTION: <reason>`. |
| 239 | """.trimIndent(), |
| 240 | category = Category.CORRECTNESS, |
| 241 | priority = 6, |
| 242 | severity = Severity.ERROR, |
| 243 | implementation = Implementation( |
| 244 | NoDeadClickDetector::class.java, |
| 245 | Scope.JAVA_FILE_SCOPE, |
| 246 | ), |
| 247 | ) |
| 248 | } |
| 249 | } |