a11y

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 6 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package a11y adds game accessibility primitives built on NSGo's public API: live captions for dialogue and sound effects, color-blind-safe palettes with CVD simulation and WCAG contrast helpers, persistent assist options, and screen-reader-ready native menus.

Index

Examples

Constants

View Source
const (
	// MinGameSpeed is the slowest allowed Assist.GameSpeed multiplier.
	MinGameSpeed = 0.25
	// MaxGameSpeed is the fastest allowed Assist.GameSpeed multiplier.
	MaxGameSpeed = 1.0
	// MinTextScale is the minimum allowed Assist.TextScale multiplier.
	MinTextScale float32 = 1.0
	// MaxTextScale is the maximum allowed Assist.TextScale multiplier.
	MaxTextScale float32 = 2.0
)
View Source
const (
	// DefaultMaxVisibleCaptions is the default cap on simultaneously visible captions.
	DefaultMaxVisibleCaptions = 4
	// DefaultCaptionDuration is used when a Caption is shown without a positive Duration.
	DefaultCaptionDuration = 3 * time.Second
)

Variables

This section is empty.

Functions

func AccessibleMenu

func AccessibleMenu(cx *core.Scope, props MenuProps) core.Node

AccessibleMenu renders a screen-reader- and keyboard-accessible native NSGo menu with RoleMenu / RoleMenuItem (or RoleMenuItemCheckbox), full ARIA/a11y metadata, keyboard navigation (Up/Down/Home/End/Return/Space/Escape via OnKeyDown), and live screen-reader announcements via cx.Announce on open, focus change, toggle, and close.

func CaptionsView

func CaptionsView(cx *core.Scope, track *CaptionTrack, opts CaptionStyle) core.Node

CaptionsView renders high-contrast live captions from track as native NSGo views with LiveRegionPolite on standard cues and LiveRegionAssertive on CaptionImportant cues.

func ContrastRatio

func ContrastRatio(fg, bg core.Color) float64

ContrastRatio returns the WCAG 2.1 relative luminance contrast ratio between fg and bg in [1.0, 21.0]. Semi-transparent foregrounds are composited over bg.

func EnsureContrast

func EnsureContrast(fg, bg core.Color, minRatio float64) core.Color

EnsureContrast adjusts fg's lightness until ContrastRatio(result, bg) meets minRatio while preserving fg's hue as closely as possible and keeping its alpha channel. If fg already meets minRatio (or minRatio <= 1), fg is returned unchanged. If minRatio exceeds the maximum contrast achievable against bg, the higher-contrast extreme (white or black) is returned.

Example

ContrastRatio measures text against its background, and EnsureContrast moves a color that falls short of WCAG AA (4.5:1) until it meets it.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/a11y"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	bg := core.RGB(0x202020)
	fg := core.RGB(0x505050)
	fmt.Printf("before: %.2f\n", a11y.ContrastRatio(fg, bg))
	fixed := a11y.EnsureContrast(fg, bg, 4.5)
	fmt.Println("meets AA:", a11y.ContrastRatio(fixed, bg) >= 4.5)
}
Output:
before: 2.02
meets AA: true

func Simulate

func Simulate(c core.Color, mode ColorVision) core.Color

Simulate approximates how c appears under color-vision mode using linear-RGB Viénot/Brettel/Machado dichromacy matrices. Alpha is preserved. VisionNormal and VisionHighContrast return c unchanged.

Example

Simulate shows how a color reads under a color-vision deficiency, so a game can check that two of its colors stay apart.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/a11y"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	red, green := core.RGB(0xd03030), core.RGB(0x30a030)
	mode, ok := a11y.ParseColorVision("deuteranopia")
	fmt.Println(mode, ok)
	fmt.Printf("%08x %08x\n", uint32(a11y.Simulate(red, mode)), uint32(a11y.Simulate(green, mode)))
}
Output:
deuteranopia true
897b29ff 96883bff

Types

type Assist

type Assist struct {
	// contains filtered or unexported fields
}

Assist stores and persists a player's accessibility and gameplay-assist preferences in core.Storage under a key prefix. Every getter reads through core.Storage (and core.Env where appropriate), so calling a getter inside a reactive NSGo computation automatically subscribes to updates.

Example

Assist keeps a player's assist options in the app's storage; ScaleDT applies the slow-motion setting to a fixed step.

package main

import (
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/a11y"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	root := core.NewRoot(core.RootOptions{})
	defer root.Dispose()

	assist := a11y.NewAssist(root, "assist")
	if err := assist.Apply(a11y.AssistOptions{GameSpeed: 0.5, CaptionsEnabled: true, TextScale: 1.5, ColorVision: a11y.VisionProtanopia}); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(assist.ScaleDT(time.Second / 60))
	fmt.Println(assist.CaptionsEnabled(), assist.TextScale(), assist.ColorVision())

	// A fresh Assist on the same storage reads the saved options back.
	again := a11y.NewAssist(root, "assist")
	fmt.Println(again.GameSpeed())
}
Output:
8.333333ms
true 1.5 protanopia
0.5

func NewAssist

func NewAssist(cx *core.Scope, key string) *Assist

NewAssist returns an Assist controller backed by cx's core.Storage under keys prefixed with key (defaulting to "a11y.assist" when empty).

func (*Assist) Apply

func (a *Assist) Apply(opts AssistOptions) error

Apply persists every option in opts.

func (*Assist) AutoAim

func (a *Assist) AutoAim() bool

AutoAim reports whether aim assistance is enabled.

func (*Assist) CaptionsEnabled

func (a *Assist) CaptionsEnabled() bool

CaptionsEnabled reports whether dialogue and music captions are enabled.

func (*Assist) ColorVision

func (a *Assist) ColorVision() ColorVision

ColorVision returns the selected color-vision mode, defaulting to VisionNormal.

func (*Assist) GameSpeed

func (a *Assist) GameSpeed() float64

GameSpeed returns the slow-motion multiplier in [0.25, 1.0], defaulting to 1.0.

func (*Assist) HighContrast

func (a *Assist) HighContrast() bool

HighContrast reports whether high-contrast visuals are requested. When unset in storage, it follows cx.Env().IncreaseContrast().

func (*Assist) HoldToToggle

func (a *Assist) HoldToToggle() bool

HoldToToggle reports whether held inputs should act as toggles.

func (*Assist) Invincibility

func (a *Assist) Invincibility() bool

Invincibility reports whether player damage is disabled.

func (*Assist) Palette

func (a *Assist) Palette() Palette

Palette returns the active Palette for the player's current settings, preferring VisionHighContrast when HighContrast is enabled.

func (*Assist) ReduceMotion

func (a *Assist) ReduceMotion() bool

ReduceMotion reports whether screen shake, flashes, and non-essential motion should be disabled. When unset in storage, it follows cx.Env().ReduceMotion().

func (*Assist) Reset

func (a *Assist) Reset()

Reset removes all stored assist preferences so defaults and OS environment settings take effect again.

func (*Assist) SFXCaptionsEnabled

func (a *Assist) SFXCaptionsEnabled() bool

SFXCaptionsEnabled reports whether sound-effect captions are enabled.

func (*Assist) ScaleDT

func (a *Assist) ScaleDT(dt time.Duration) time.Duration

ScaleDT scales a simulation step dt by GameSpeed. Non-positive durations return 0, and a speed of 1.0 returns dt unchanged.

func (*Assist) SetAutoAim

func (a *Assist) SetAutoAim(v bool) error

SetAutoAim persists the auto-aim assist option.

func (*Assist) SetCaptionsEnabled

func (a *Assist) SetCaptionsEnabled(v bool) error

SetCaptionsEnabled persists whether captions are enabled.

func (*Assist) SetColorVision

func (a *Assist) SetColorVision(v ColorVision) error

SetColorVision persists the selected color-vision mode.

func (*Assist) SetGameSpeed

func (a *Assist) SetGameSpeed(v float64) error

SetGameSpeed clamps v to [0.25, 1.0] and persists it.

func (*Assist) SetHighContrast

func (a *Assist) SetHighContrast(v bool) error

SetHighContrast persists an explicit high-contrast preference.

func (*Assist) SetHoldToToggle

func (a *Assist) SetHoldToToggle(v bool) error

SetHoldToToggle persists the hold-to-toggle assist option.

func (*Assist) SetInvincibility

func (a *Assist) SetInvincibility(v bool) error

SetInvincibility persists the invincibility assist option.

func (*Assist) SetReduceMotion

func (a *Assist) SetReduceMotion(v bool) error

SetReduceMotion persists an explicit reduced-motion preference.

func (*Assist) SetSFXCaptionsEnabled

func (a *Assist) SetSFXCaptionsEnabled(v bool) error

SetSFXCaptionsEnabled persists whether sound-effect captions are enabled.

func (*Assist) SetTextScale

func (a *Assist) SetTextScale(v float32) error

SetTextScale clamps v to [1.0, 2.0] and persists it.

func (*Assist) Snapshot

func (a *Assist) Snapshot() AssistOptions

Snapshot returns all current assist option values.

func (*Assist) TextScale

func (a *Assist) TextScale() float32

TextScale returns the UI/caption text scale multiplier in [1.0, 2.0]. When unset in storage, it adopts cx.Env().FontScale() clamped to [1.0, 2.0].

type AssistOptions

type AssistOptions struct {
	GameSpeed          float64
	ReduceMotion       bool
	Invincibility      bool
	AutoAim            bool
	HoldToToggle       bool
	HighContrast       bool
	CaptionsEnabled    bool
	SFXCaptionsEnabled bool
	ColorVision        ColorVision
	TextScale          float32
}

AssistOptions is a plain snapshot of every assist option managed by Assist.

type Caption

type Caption struct {
	// ID uniquely identifies the caption within its track.
	ID uint64
	// Speaker is the optional speaker name (e.g. "Ada").
	Speaker string
	// Text is the caption body.
	Text string
	// Kind classifies the cue for formatting, filtering, and LiveRegion priority.
	Kind CaptionKind
	// Direction is an optional stereo pan hint in [-1, +1] (-1 left, +1 right).
	Direction float32
	// Duration is the total lifetime of the caption.
	Duration time.Duration
	// Remaining is the time left before the caption expires.
	Remaining time.Duration
}

Caption represents one active timed caption on a CaptionTrack.

func (Caption) Format

func (c Caption) Format() string

Format renders c as human- and screen-reader-friendly text with speaker and directional stereo indicators ([<] for left, [>] for right).

type CaptionKind

type CaptionKind int

CaptionKind classifies a live caption entry for styling, filtering, and screen-reader politeness.

const (
	// CaptionDialogue is spoken character dialogue.
	CaptionDialogue CaptionKind = iota
	// CaptionSFX is a non-speech sound effect cue (footsteps, explosion, door).
	CaptionSFX
	// CaptionMusic is a musical cue or track mood indicator.
	CaptionMusic
	// CaptionImportant is a critical gameplay or hazard audio cue announced assertively.
	CaptionImportant
)

func (CaptionKind) String

func (k CaptionKind) String() string

String returns the canonical name of k.

type CaptionStyle

type CaptionStyle struct {
	// Background is the caption pill backdrop color (default high-contrast near-black).
	Background core.Color
	// TextColor is the dialogue/music text color (default white).
	TextColor core.Color
	// SFXColor is the sound-effect caption text color (default soft cyan).
	SFXColor core.Color
	// ImportantColor is the text color for CaptionImportant cues (default high-contrast yellow).
	ImportantColor core.Color
	// FontSize is the base font size in points (default 16).
	FontSize core.Points
	// TextScale multiplies FontSize when > 0 (overridden by Assist.TextScale when Assist is set).
	TextScale float32
	// MaxWidth caps the caption overlay width in points (default 640).
	MaxWidth core.Points
	// Assist, when non-nil, automatically scales caption text, respects
	// HighContrast, and filters captions by CaptionsEnabled/SFXCaptionsEnabled.
	Assist *Assist
	// TestID overrides the root view's TestID (default "a11y-captions").
	TestID string
	// Style merges additional layout/positioning style onto the container.
	Style core.Style
}

CaptionStyle configures the appearance and optional Assist integration of CaptionsView.

type CaptionTrack

type CaptionTrack struct {
	// MaxVisible caps how many captions remain active at once; 4 when <= 0.
	MaxVisible int
	// contains filtered or unexported fields
}

CaptionTrack manages timed captions stepped deterministically by Update(dt) inside game.Loop.Update, exposing a reactive signal revision for CaptionsView.

Example

A CaptionTrack holds timed captions that Update steps from the game loop; Format adds the speaker and the direction a sound came from.

package main

import (
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/a11y"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	root := core.NewRoot(core.RootOptions{})
	defer root.Dispose()

	track := a11y.NewCaptionTrack(root)
	track.ShowDialogue("Ada", "Over here!", 2*time.Second)
	track.ShowSFXAt("Footsteps", -1, time.Second)
	for _, c := range track.Active() {
		fmt.Printf("%v: %s\n", c.Kind, c.Format())
	}
	track.Update(1500 * time.Millisecond)
	fmt.Println("after 1.5 s:", len(track.Active()))
}
Output:
dialogue: Ada: Over here!
sfx: [<] [Footsteps]
after 1.5 s: 1

func NewCaptionTrack

func NewCaptionTrack(cx *core.Scope) *CaptionTrack

NewCaptionTrack returns a CaptionTrack bound to cx's reactive graph with MaxVisible set to DefaultMaxVisibleCaptions (4).

func (*CaptionTrack) Active

func (t *CaptionTrack) Active() []Caption

Active returns a snapshot of the currently active captions in display order (oldest to newest). Calling Active inside a reactive computation subscribes it to caption additions, expirations, and clears.

func (*CaptionTrack) Clear

func (t *CaptionTrack) Clear()

Clear removes all active captions.

func (*CaptionTrack) Dismiss

func (t *CaptionTrack) Dismiss(id uint64) bool

Dismiss removes the caption with id if present and reports whether one was removed.

func (*CaptionTrack) Show

func (t *CaptionTrack) Show(c Caption) uint64

Show adds c to the track, assigning an ID and defaults if unset, enforcing MaxVisible, and notifying reactive subscribers. It returns the caption's ID.

func (*CaptionTrack) ShowDialogue

func (t *CaptionTrack) ShowDialogue(speaker, text string, duration time.Duration) uint64

ShowDialogue appends a spoken dialogue caption attributed to speaker.

func (*CaptionTrack) ShowImportant

func (t *CaptionTrack) ShowImportant(text string, duration time.Duration) uint64

ShowImportant appends a high-priority gameplay cue announced assertively.

func (*CaptionTrack) ShowSFX

func (t *CaptionTrack) ShowSFX(label string, duration time.Duration) uint64

ShowSFX appends a sound-effect caption for label lasting duration.

func (*CaptionTrack) ShowSFXAt

func (t *CaptionTrack) ShowSFXAt(label string, direction float32, duration time.Duration) uint64

ShowSFXAt appends a directional sound-effect caption with stereo direction in [-1, +1].

func (*CaptionTrack) Update

func (t *CaptionTrack) Update(dt time.Duration)

Update advances all active captions by dt and expires any whose Remaining time reaches zero. Intended to be called on each game.Loop.Update step.

type ColorVision

type ColorVision int

ColorVision selects a color-vision mode for palettes and CVD simulation.

const (
	// VisionNormal is standard trichromatic vision with a color-blind-aware
	// Okabe-Ito inspired base palette.
	VisionNormal ColorVision = iota
	// VisionProtanopia adapts colors for red-blind (L-cone deficient) vision.
	VisionProtanopia
	// VisionDeuteranopia adapts colors for green-blind (M-cone deficient) vision.
	VisionDeuteranopia
	// VisionTritanopia adapts colors for blue-blind (S-cone deficient) vision.
	VisionTritanopia
	// VisionHighContrast provides maximum luminance separation (WCAG AAA).
	VisionHighContrast
)

func ParseColorVision

func ParseColorVision(s string) (ColorVision, bool)

ParseColorVision parses a ColorVision name returned by String.

func (ColorVision) String

func (v ColorVision) String() string

String returns the canonical lowercase identifier for v.

type MenuItem struct {
	// ID is an optional stable suffix used to derive a deterministic TestID.
	ID string
	// Label is the item's visible and accessible name.
	Label string
	// LabelFunc overrides Label with a reactive label.
	LabelFunc func() string
	// Hint describes what activating the item does (read after Label and Description).
	Hint string
	// Description provides additional accessible context (AccessibilityDescription).
	Description string
	// DescriptionFunc overrides Description with a reactive description.
	DescriptionFunc func() string
	// Value is an optional reactive textual value (e.g. "75%", "Deuteranopia"),
	// exposed both visually and via AccessibilityValue.
	Value func() string
	// AccessibilityValue, when non-nil, overrides Value for assistive technology.
	AccessibilityValue func() core.AccessibilityValue
	// Role overrides the default RoleMenuItem (or RoleMenuItemCheckbox when Checked != nil).
	Role core.Role
	// Checked, when non-nil, marks the item as a checkable toggle (RoleMenuItemCheckbox).
	Checked func() bool
	// Disabled, when returning true, prevents activation and skips the item during
	// keyboard navigation.
	Disabled func() bool
	// OnSelect runs when the user activates the item via keyboard, press, or
	// screen-reader activate action.
	OnSelect func()
	// TestID sets an explicit test identifier for this menu item.
	TestID string
}

MenuItem describes a single interactive entry inside an AccessibleMenu.

type MenuProps struct {
	// Label is the accessible name of the menu (e.g. "Pause Menu").
	Label string
	// Hint is an optional accessibility hint for the menu container.
	Hint string
	// Description is an optional AccessibilityDescription for the menu container.
	Description string
	// Items are the menu entries in vertical order.
	Items []MenuItem
	// Palette sets the menu's colors; when zero, Assist.Palette() (if Assist != nil)
	// or PaletteFor(VisionNormal) is used.
	Palette Palette
	// Assist optionally scales text and supplies a live reactive Palette.
	Assist *Assist
	// InitialIndex selects the starting focused item (clamped to the first enabled item).
	InitialIndex int
	// SuppressOpenAnnouncement disables the automatic cx.Announce call on menu mount.
	SuppressOpenAnnouncement bool
	// OnClose runs when Escape or screen-reader ActionEscape is triggered.
	OnClose func()
	// TestID overrides the menu container's TestID (default "a11y-menu").
	TestID string
	// Style merges additional styling onto the menu container.
	Style core.Style
}

MenuProps configures an AccessibleMenu.

type Palette

type Palette struct {
	Player     core.Color
	Ally       core.Color
	Enemy      core.Color
	Hazard     core.Color
	Pickup     core.Color
	Neutral    core.Color
	Background core.Color
	Foreground core.Color
	Highlight  core.Color
	Accent     core.Color
}

Palette holds semantic game and UI colors designed to remain distinguishable and readable together.

func PaletteFor

func PaletteFor(mode ColorVision) Palette

PaletteFor returns a color-blind-safe preset Palette for mode, grounded in the Okabe-Ito / Wong palette and tuned for WCAG contrast and post-simulation separability.

Example

PaletteFor returns semantic colors that stay distinguishable under the chosen color-vision mode.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/a11y"
)

func main() {
	for _, mode := range []a11y.ColorVision{a11y.VisionNormal, a11y.VisionHighContrast} {
		p := a11y.PaletteFor(mode)
		fmt.Printf("%v: player %08x enemy %08x\n", mode, uint32(p.Player), uint32(p.Enemy))
	}
}
Output:
normal: player 56b4e9ff enemy f06430ff
high-contrast: player 00e5ffff enemy ff5252ff

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL