green-code-initiative / ecoCode-challenge

Emboard in the hackhatons serie for improving ecoCode
3 stars 4 forks source link

[Hackathon 2024][Niobium][iOS] Use Button Instead of .onTapGesture for Clickable Views in SwiftUI #104

Open LaurentBnpp opened 1 month ago

LaurentBnpp commented 1 month ago

Rule title

Use Button Instead of .onTapGesture for Clickable Views in SwiftUI

Language and platform

Swift (5.3+), SwiftUI (iOS 13+, macOS 10.15+, tvOS 13+, watchOS 6+, visionOS 1+)

Rule description

We need to detect in the code whether tapping on a SwiftUI view uses a Button rather than the .onTapGesture modifier. This is because the modifier does not allow certain accessibility features to function correctly. For example, keyboard navigation that allows interaction components to be traversed will not work on an element that uses the gesture.

Bad example

            HStack {
                Text("View with gesture")
                Image(systemName: "hand.thumbsdown")
            }
            .onTapGesture {
                print("Pas glop")
            }

Good example

          Button(action: {
                print("Glop")
            }, label: {
                HStack {
                    Text("Regular button")
                    Image(systemName: "hand.thumbsup")
                }
            })

Rule short description

Avoid usage of .onTapGesture modifier to provide good accessibility experience.

Rule justification

Using Button instead of .onTapGesture for clickable views in SwiftUI is crucial for ensuring compatibility with accessibility tools like keyboard navigation. This is in line with the RGAA (General Accessibility Framework for Administrations) guidelines, which emphasize the importance of making digital services accessible to all users, including those with disabilities.

RGAA rule

Example The blue frame in the gif below corresponds to the selection made by user using the keyboard. It's important to note that functionality only works with components that the Button rather than relying solely on the .onTapGesture modifier.

Simulator Screen Recording - iPhone 15 - 2024-05-29 at 16 34 22

Severity / Remediation Cost

Severity: Blocker. For certains users, keyboard or selection control is only way to navigate within an application. Consequently, if this issue occurs, a user may become completely blocked on the screen or be unable to access a particular feature (and it's legal obligation).

Remediation Cost: Easy It requires a minor code adjustment to replace .onTapGesture with Button.

Implementation principle

During the static analysis of the source code, we need to detect instances where .onTapGesture is used for creating clickable views. If Button is not used in these instances, it indicates a potential issue.