Documentation
¶
Overview ¶
Package a11y is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
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 ¶
- Constants
- func AccessibleMenu(cx *core.Scope, props MenuProps) core.Node
- func CaptionsView(cx *core.Scope, track *CaptionTrack, opts CaptionStyle) core.Node
- func ColorDistance(a, b core.Color) float64
- func ColorVisionFilter(settings save.AccessibilitySettings) (postfx.Effect, bool)
- func ColorVisionSimulation(mode ColorVision, severity float64) (postfx.Effect, bool)
- func ContrastRatio(fg, bg core.Color) float64
- func Daltonize(c core.Color, mode ColorVision, severity float64) core.Color
- func DefaultCatalog() *l10n.Catalog
- func DrawSoundIndicators(d *core.Drawing, width, height float32, captions []Caption, ...)
- func EnsureContrast(fg, bg core.Color, minRatio float64) core.Color
- func FormatCaptionParts(c Caption, importantPrefix, musicPrefix string) (prefix, speakerPart, body, suffix string)
- func LoadDefaultCatalog(cat *l10n.Catalog) error
- func MigrateLegacyAssist(storage core.Storage, legacyKey string, store *save.DefaultSettingsStore) (bool, error)
- func ResolveCaptionBackground(name string, opacity float64) core.Color
- func ResolveCaptionTextColor(name string) core.Color
- func Simulate(c core.Color, mode ColorVision) core.Color
- func SimulateAt(c core.Color, mode ColorVision, severity float64) core.Color
- func SoundIndicatorView(cx *core.Scope, track *CaptionTrack, opts SoundIndicatorStyle) core.Node
- func SpeakerColor(speaker string, mode ColorVision, overrides map[string]core.Color) core.Color
- func WrapCaptionLines(text string, maxChars int) []string
- type Assist
- func (a *Assist) Apply(opts AssistOptions) error
- func (a *Assist) ApplyInputAssists(s save.InputAssistSettings) error
- func (a *Assist) ApplySettings(s save.AccessibilitySettings) error
- func (a *Assist) ApplyToActions(actions *input.Actions)
- func (a *Assist) ApplyToPlayers(players *input.Players)
- func (a *Assist) AutoAim() bool
- func (a *Assist) CaptionBackground() string
- func (a *Assist) CaptionBackgroundOpacity() float64
- func (a *Assist) CaptionSettings() save.CaptionSettings
- func (a *Assist) CaptionSize() string
- func (a *Assist) CaptionSpeakerColors() bool
- func (a *Assist) CaptionTextColor() string
- func (a *Assist) CaptionsEnabled() bool
- func (a *Assist) ChatterCaptionsEnabled() bool
- func (a *Assist) ColorBlindSeverity() float64
- func (a *Assist) ColorVision() ColorVision
- func (a *Assist) ColorVisionFilter() (postfx.Effect, bool)
- func (a *Assist) DialogueCaptionsEnabled() bool
- func (a *Assist) GameSpeed() float64
- func (a *Assist) HighContrast() bool
- func (a *Assist) HoldToToggle() bool
- func (a *Assist) InputAssists() input.Assists
- func (a *Assist) Invincibility() bool
- func (a *Assist) Palette() Palette
- func (a *Assist) ReduceFlashes() bool
- func (a *Assist) ReduceMotion() bool
- func (a *Assist) Reload()
- func (a *Assist) Reset()
- func (a *Assist) SFXCaptionsEnabled() bool
- func (a *Assist) ScaleDT(dt time.Duration) time.Duration
- func (a *Assist) ScreenShake() float64
- func (a *Assist) SetAutoAim(v bool) error
- func (a *Assist) SetCaptionBackground(color string) error
- func (a *Assist) SetCaptionBackgroundOpacity(opacity float64) error
- func (a *Assist) SetCaptionSettings(cs save.CaptionSettings) error
- func (a *Assist) SetCaptionSize(size string) error
- func (a *Assist) SetCaptionSpeakerColors(v bool) error
- func (a *Assist) SetCaptionTextColor(color string) error
- func (a *Assist) SetCaptionsEnabled(v bool) error
- func (a *Assist) SetChatterCaptionsEnabled(v bool) error
- func (a *Assist) SetColorBlindSeverity(v float64) error
- func (a *Assist) SetColorVision(v ColorVision) error
- func (a *Assist) SetDialogueCaptionsEnabled(v bool) error
- func (a *Assist) SetGameSpeed(v float64) error
- func (a *Assist) SetHighContrast(v bool) error
- func (a *Assist) SetHoldToToggle(v bool) error
- func (a *Assist) SetInputAssists(assists input.Assists) error
- func (a *Assist) SetInvincibility(v bool) error
- func (a *Assist) SetReduceFlashes(v bool) error
- func (a *Assist) SetReduceMotion(v bool) error
- func (a *Assist) SetSFXCaptionsEnabled(v bool) error
- func (a *Assist) SetScreenShake(v float64) error
- func (a *Assist) SetTextScale(v float32) error
- func (a *Assist) Settings() save.AccessibilitySettings
- func (a *Assist) Snapshot() AssistOptions
- func (a *Assist) TextScale() float32
- type AssistOptions
- type Caption
- type CaptionEmitter
- type CaptionKind
- type CaptionStyle
- type CaptionTrack
- func (t *CaptionTrack) Active() []Caption
- func (t *CaptionTrack) Clear()
- func (t *CaptionTrack) Dismiss(id uint64) bool
- func (t *CaptionTrack) Show(c Caption) uint64
- func (t *CaptionTrack) ShowChatter(speaker, text string, duration time.Duration) uint64
- func (t *CaptionTrack) ShowDialogue(speaker, text string, duration time.Duration) uint64
- func (t *CaptionTrack) ShowDialogueWithQualifier(speaker, qualifier, text string, duration time.Duration) uint64
- func (t *CaptionTrack) ShowImportant(text string, duration time.Duration) uint64
- func (t *CaptionTrack) ShowSFX(label string, duration time.Duration) uint64
- func (t *CaptionTrack) ShowSFXAt(label string, direction float32, duration time.Duration) uint64
- func (t *CaptionTrack) Update(dt time.Duration)
- type ColorVision
- type DialogueCaptionBridge
- type MenuItem
- type MenuProps
- type MenuText
- type Palette
- type SoundCaptionOptions
- type SoundIndicatorStyle
Examples ¶
Constants ¶
const ( // MinGameSpeed is the slowest allowed Assist.GameSpeed multiplier. MinGameSpeed = save.MinGameSpeed // MaxGameSpeed is the fastest allowed Assist.GameSpeed multiplier. MaxGameSpeed = save.MaxGameSpeed // MinTextScale is the minimum allowed Assist.TextScale multiplier. MinTextScale float32 = save.MinCaptionScale // MaxTextScale is the maximum allowed Assist.TextScale multiplier. MaxTextScale float32 = save.MaxCaptionScale )
const ( // DefaultMaxVisibleCaptions is the default cap on simultaneously active captions in CaptionTrack. DefaultMaxVisibleCaptions = 4 // DefaultCaptionDuration is used when a Caption is shown without a positive Duration. DefaultCaptionDuration = 3 * time.Second // DefaultCaptionMaxLines is the default maximum number of wrapped lines shown at once in CaptionsView (XAG 104). DefaultCaptionMaxLines = 2 // DefaultCaptionMaxChars is the default maximum number of characters per wrapped line (XAG 104). DefaultCaptionMaxChars = 40 // DefaultSpeakerRepeatGap is the default silence gap after which ShowDialogue shows a repeated speaker's name again. DefaultSpeakerRepeatGap = 5 * time.Second )
const ( // KeyMenuDefaultLabel is the fallback accessible label when MenuProps.Label is empty. KeyMenuDefaultLabel = "a11y.menu.defaultLabel" // KeyMenuItems is a plural key formatted with {count} for the menu's item count. KeyMenuItems = "a11y.menu.items" // KeyMenuOpened formats the mount announcement when no item is enabled ({label}, {items}, {count}). KeyMenuOpened = "a11y.menu.opened" // KeyMenuOpenedWithItem formats the mount announcement with an active item ({label}, {items}, {count}, {item}). KeyMenuOpenedWithItem = "a11y.menu.openedWithItem" // KeyMenuPosition formats focus-change announcements ({item}, {index}, {count}). KeyMenuPosition = "a11y.menu.position" // KeyMenuSelected formats activation announcements for non-toggle items ({label}). KeyMenuSelected = "a11y.menu.selected" // KeyMenuClosed formats the Escape/close announcement ({label}). KeyMenuClosed = "a11y.menu.closed" // KeyMenuChecked is the spoken checked state word. KeyMenuChecked = "a11y.menu.checked" // KeyMenuUnchecked is the spoken unchecked state word. KeyMenuUnchecked = "a11y.menu.unchecked" // KeyMenuOn is the visible value shown for checked toggle items. KeyMenuOn = "a11y.menu.on" // KeyMenuOff is the visible value shown for unchecked toggle items. KeyMenuOff = "a11y.menu.off" // KeyMenuSeparator joins item status parts (label, checked state, value) in announcements. KeyMenuSeparator = "a11y.menu.separator" // KeyCaptionsRegionLabel is the accessible label of CaptionsView's live region. KeyCaptionsRegionLabel = "a11y.captions.regionLabel" // KeyCaptionsImportantPrefix is prepended to speakerless CaptionImportant cues. KeyCaptionsImportantPrefix = "a11y.captions.importantPrefix" // KeyCaptionsMusicPrefix is prepended to speakerless CaptionMusic cues. KeyCaptionsMusicPrefix = "a11y.captions.musicPrefix" // KeyCaptionsBgBlack is the localized label for the black caption background preset. KeyCaptionsBgBlack = "a11y.captions.bgBlack" // KeyCaptionsBgGray is the localized label for the gray caption background preset. KeyCaptionsBgGray = "a11y.captions.bgGray" // KeyCaptionsBgBlue is the localized label for the navy/blue caption background preset. KeyCaptionsBgBlue = "a11y.captions.bgBlue" // KeyCaptionsBgWhite is the localized label for the white caption background preset. KeyCaptionsBgWhite = "a11y.captions.bgWhite" // KeyCaptionsTextWhite is the localized label for the white caption text preset. KeyCaptionsTextWhite = "a11y.captions.textWhite" // KeyCaptionsTextYellow is the localized label for the yellow caption text preset. KeyCaptionsTextYellow = "a11y.captions.textYellow" // KeyCaptionsTextCyan is the localized label for the cyan caption text preset. KeyCaptionsTextCyan = "a11y.captions.textCyan" // KeyCaptionsTextGreen is the localized label for the green caption text preset. KeyCaptionsTextGreen = "a11y.captions.textGreen" // KeyCaptionsTextBlack is the localized label for the black caption text preset. KeyCaptionsTextBlack = "a11y.captions.textBlack" // KeyCaptionsSizeSmall is the localized label for the small caption size preset. KeyCaptionsSizeSmall = "a11y.captions.sizeSmall" // KeyCaptionsSizeMedium is the localized label for the medium caption size preset. KeyCaptionsSizeMedium = "a11y.captions.sizeMedium" // KeyCaptionsSizeLarge is the localized label for the large caption size preset. KeyCaptionsSizeLarge = "a11y.captions.sizeLarge" // KeyCaptionsSizeXLarge is the localized label for the extra-large caption size preset. KeyCaptionsSizeXLarge = "a11y.captions.sizeXLarge" // KeyCaptionsPreviewSpeaker is the sample dialogue speaker name used in settings previews. KeyCaptionsPreviewSpeaker = "a11y.captions.previewSpeaker" // KeyCaptionsPreviewQualifier is the sample dialogue qualifier used in settings previews. KeyCaptionsPreviewQualifier = "a11y.captions.previewQualifier" // KeyCaptionsPreviewDialogue is the sample dialogue line used in settings previews. KeyCaptionsPreviewDialogue = "a11y.captions.previewDialogue" // KeyCaptionsPreviewChatterSpeaker is the sample chatter speaker name used in settings previews. KeyCaptionsPreviewChatterSpeaker = "a11y.captions.previewChatterSpeaker" // KeyCaptionsPreviewChatter is the sample chatter line used in settings previews. KeyCaptionsPreviewChatter = "a11y.captions.previewChatter" // KeyCaptionsPreviewSFX is the sample sound-effect label used in settings previews. KeyCaptionsPreviewSFX = "a11y.captions.previewSFX" )
Documented localization keys read by MenuTextFromCatalog, MenuTextFromLocalizer, CaptionStyleFromCatalog, and CaptionStyleFromLocalizer.
const DefaultCaptionMinInterval = 250 * time.Millisecond
DefaultCaptionMinInterval is how long NewCaptionEmitter suppresses a repeat of the same label.
Variables ¶
This section is empty.
Functions ¶
func AccessibleMenu ¶
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, applying player caption preferences, per-kind toggles, speaker coloring, and the two-line / 40-character wrapping limit.
func ColorDistance ¶
ColorDistance returns the Euclidean sRGB distance between a and b in 8-bit channel units [0, 441.67], ignoring alpha.
func ColorVisionFilter ¶
func ColorVisionFilter(settings save.AccessibilitySettings) (postfx.Effect, bool)
ColorVisionFilter returns the daltonization / color-vision correction frame effect configured from settings.ColorBlindMode and settings.EffectiveColorBlindSeverity(). When ColorBlindMode is "none" (or unrecognized) or the effective severity is 0 or less, it returns a zero Effect and false so callers can omit the pass.
func ColorVisionSimulation ¶
func ColorVisionSimulation(mode ColorVision, severity float64) (postfx.Effect, bool)
ColorVisionSimulation returns a frame effect that simulates how a scene appears under mode at severity in [0, 1] (clamped, with NaN treated as 0). VisionNormal, VisionHighContrast, and severity <= 0 return a zero Effect and false.
func ContrastRatio ¶
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 Daltonize ¶
Daltonize transforms c to shift lost chromatic contrast into channels visible under mode at severity in [0, 1] (clamped, NaN treated as 0). Alpha is preserved. For VisionHighContrast, it boosts sRGB contrast around mid-gray. VisionNormal and severity <= 0 return c unchanged.
func DefaultCatalog ¶
DefaultCatalog returns a new localization catalog preloaded with pkg/a11y's built-in English ("en") and Simplified Chinese ("zh") string tables.
func DrawSoundIndicators ¶
func DrawSoundIndicators(d *core.Drawing, width, height float32, captions []Caption, opts SoundIndicatorStyle)
DrawSoundIndicators draws directional sound indicator arcs for captions into d for a viewport of width x height points. Important directional captions are always drawn (subject to Assist's caption toggles); SFX captions are also drawn when opts.IncludeSFX is true.
func EnsureContrast ¶
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 FormatCaptionParts ¶
func FormatCaptionParts(c Caption, importantPrefix, musicPrefix string) (prefix, speakerPart, body, suffix string)
FormatCaptionParts splits a formatted caption into its directional left prefix, speaker/qualifier prefix, body text, and directional right suffix so renderers can tint the speaker portion independently while preserving exact plain-text formatting.
func LoadDefaultCatalog ¶
LoadDefaultCatalog merges pkg/a11y's built-in English and Simplified Chinese string tables into cat. Call it before loading game-specific overrides so custom entries take precedence.
func MigrateLegacyAssist ¶
func MigrateLegacyAssist(storage core.Storage, legacyKey string, store *save.DefaultSettingsStore) (bool, error)
MigrateLegacyAssist performs a one-time migration of legacy raw core.Storage keys ("<legacyKey>.gameSpeed", "<legacyKey>.reduceMotion", etc.) into store's AccessibilitySettings, removing the old keys after store.Save succeeds. legacyKey defaults to "a11y.assist" when empty. It reports whether any legacy keys were found and migrated.
func ResolveCaptionBackground ¶
ResolveCaptionBackground converts a canonical caption background preset name ("black", "gray", "blue", "white") or "#rrggbb" hex string plus opacity in [0, 1] into a core.Color.
func ResolveCaptionTextColor ¶
ResolveCaptionTextColor converts a canonical caption text color preset name ("white", "yellow", "cyan", "green", "black") or "#rrggbb" hex string into a core.Color.
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
func SimulateAt ¶
SimulateAt approximates how c appears under color-vision mode at severity in [0, 1] (clamped, NaN treated as 0). Alpha is preserved. VisionNormal, VisionHighContrast, and severity <= 0 return c unchanged. SimulateAt(c, mode, 1.0) matches Simulate(c, mode).
func SoundIndicatorView ¶
func SoundIndicatorView(cx *core.Scope, track *CaptionTrack, opts SoundIndicatorStyle) core.Node
SoundIndicatorView renders a full-bleed non-interactive overlay drawing directional edge arcs toward recent important captioned sounds on track, scaled by loudness and honoring Assist's ReduceMotion, HighContrast, ColorVision, and caption toggles.
func SpeakerColor ¶
SpeakerColor returns a deterministic, color-vision-aware highlight color for speaker. Explicit entries in overrides take precedence (checked exact match first, then case-insensitive).
func WrapCaptionLines ¶
WrapCaptionLines wraps text into lines of at most maxChars characters (defaulting to DefaultCaptionMaxChars = 40 when maxChars <= 0). Space-separated text wraps at word boundaries; CJK ideographs and Kana/Hangul wrap by character, and oversized words break at maxChars so no line exceeds the limit.
Types ¶
type Assist ¶
type Assist struct {
// contains filtered or unexported fields
}
Assist stores and persists a player's accessibility and gameplay-assist preferences in a save.DefaultSettingsStore (specifically its Accessibility section). Every getter subscribes reactive NSGo computations to store saves, live ApplySettings updates, and core.Env changes where appropriate.
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
deprecated
NewAssist returns an Assist controller backed by a save.DefaultSettingsStore in cx's core.Storage under "<key>.settings" (defaulting key to "a11y.assist"). Any legacy raw "<key>.*" storage keys written by earlier versions are migrated once into the settings store and removed.
Deprecated: Use NewAssistFromSettings with the game's shared save.DefaultSettingsStore so SettingsMenu, CaptionsView, AccessibleMenu, and effects read the same settings.
func NewAssistFromSettings ¶
func NewAssistFromSettings(cx *core.Scope, store *save.DefaultSettingsStore) *Assist
NewAssistFromSettings returns an Assist controller backed by store so CaptionsView, AccessibleMenu, effects, and gameui.SettingsMenu share a single set of persisted preferences. Any legacy "a11y.assist.*" keys present in cx.Storage() are migrated once into store and removed.
When store is nil and cx is non-nil, a storage-backed DefaultSettingsStore under "a11y.assist.settings" is created automatically.
func (*Assist) Apply ¶
func (a *Assist) Apply(opts AssistOptions) error
Apply persists every option in opts.
func (*Assist) ApplyInputAssists ¶
func (a *Assist) ApplyInputAssists(s save.InputAssistSettings) error
ApplyInputAssists applies a live InputAssistSettings snapshot immediately without writing to disk, notifying reactive consumers. It matches save.SettingsTargets.ApplyInputAssists so SettingsMenu.Apply previews motor assist changes before Save.
func (*Assist) ApplySettings ¶
func (a *Assist) ApplySettings(s save.AccessibilitySettings) error
ApplySettings applies a live AccessibilitySettings snapshot immediately without writing to disk, notifying reactive views such as CaptionsView and AccessibleMenu. It matches save.SettingsTargets.ApplyAccessibility so SettingsMenu.Apply previews changes before Save.
func (*Assist) ApplyToActions ¶
ApplyToActions applies the player's motor assists to actions. When HoldToToggle is enabled, every action declared toggleable on actions (actions.ToggleableActions(), such as game.yaml actions with assist: {toggle: true}) is merged into Assists.Toggle, while undeclared actions (such as menu controls) are never latched.
Calling ApplyToActions inside a cx.Effect keeps actions synchronized automatically whenever settings are saved or previewed.
func (*Assist) ApplyToPlayers ¶
ApplyToPlayers applies the player's motor assists to every player's Actions in players.
func (*Assist) CaptionBackground ¶
CaptionBackground returns the normalized caption backdrop color preset or hex string.
func (*Assist) CaptionBackgroundOpacity ¶
CaptionBackgroundOpacity returns the caption backdrop opacity in [0, 1].
func (*Assist) CaptionSettings ¶
func (a *Assist) CaptionSettings() save.CaptionSettings
CaptionSettings returns the current validated save.CaptionSettings snapshot, with Sounds synchronized with EffectiveSoundCaptions.
func (*Assist) CaptionSize ¶
CaptionSize returns the normalized caption size preset ("small", "medium", "large", "xlarge").
func (*Assist) CaptionSpeakerColors ¶
CaptionSpeakerColors reports whether distinct per-speaker caption colors are enabled.
func (*Assist) CaptionTextColor ¶
CaptionTextColor returns the normalized caption text color preset or hex string.
func (*Assist) CaptionsEnabled ¶
CaptionsEnabled reports whether speech captions (dialogue and chatter) are enabled. When unset in settings, it follows the platform caption preference when exposed by cx.Env().
func (*Assist) ChatterCaptionsEnabled ¶
ChatterCaptionsEnabled reports whether ambient background chatter captions are enabled when CaptionsEnabled is true.
func (*Assist) ColorBlindSeverity ¶
ColorBlindSeverity returns the color-vision filter strength in [0, 1], defaulting to 1.0.
func (*Assist) ColorVision ¶
func (a *Assist) ColorVision() ColorVision
ColorVision returns the selected color-vision mode, defaulting to VisionNormal.
func (*Assist) ColorVisionFilter ¶
ColorVisionFilter returns the active color-vision correction frame effect for the player's current accessibility settings, or (zero, false) when ColorVision is VisionNormal or ColorBlindSeverity is 0.
func (*Assist) DialogueCaptionsEnabled ¶
DialogueCaptionsEnabled reports whether main spoken dialogue captions are enabled when CaptionsEnabled is true.
func (*Assist) GameSpeed ¶
GameSpeed returns the gameplay speed multiplier in [MinGameSpeed, MaxGameSpeed], defaulting to 1.0.
func (*Assist) HighContrast ¶
HighContrast reports whether high-contrast visuals are requested. When unset in settings, it follows cx.Env().IncreaseContrast().
func (*Assist) HoldToToggle ¶
HoldToToggle reports whether held inputs should act as toggles.
func (*Assist) InputAssists ¶
InputAssists returns the persisted per-action and timing motor assists (Toggle, MashToHold, MinPress, AcceptDelay) stored in save.Settings.InputAssists.
func (*Assist) Invincibility ¶
Invincibility reports whether player damage is disabled.
func (*Assist) Palette ¶
Palette returns the active Palette for the player's current settings, preferring VisionHighContrast when HighContrast is enabled.
func (*Assist) ReduceFlashes ¶
ReduceFlashes reports whether full-screen flash reduction is enabled.
func (*Assist) ReduceMotion ¶
ReduceMotion reports whether screen shake, flashes, and non-essential motion should be disabled. When unset in settings, it follows cx.Env().ReduceMotion().
func (*Assist) Reload ¶
func (a *Assist) Reload()
Reload discards any cached or previewed state and re-reads from the backing store, notifying reactive subscribers.
func (*Assist) Reset ¶
func (a *Assist) Reset()
Reset restores all accessibility preferences to defaults so OS environment settings take effect again, leaving other sections of the backing settings store (Audio, Display, Bindings, Locale, Custom) intact.
func (*Assist) SFXCaptionsEnabled ¶
SFXCaptionsEnabled reports whether non-speech sound and music captions are enabled.
func (*Assist) ScaleDT ¶
ScaleDT scales a simulation step dt by GameSpeed. Non-positive durations return 0, and a speed of 1.0 returns dt unchanged.
func (*Assist) ScreenShake ¶
ScreenShake returns the screen shake intensity multiplier in [0, 1].
func (*Assist) SetAutoAim ¶
SetAutoAim persists the auto-aim assist option.
func (*Assist) SetCaptionBackground ¶
SetCaptionBackground persists the caption backdrop color preset or "#rrggbb" hex string.
func (*Assist) SetCaptionBackgroundOpacity ¶
SetCaptionBackgroundOpacity clamps opacity to [0, 1] and persists it.
func (*Assist) SetCaptionSettings ¶
func (a *Assist) SetCaptionSettings(cs save.CaptionSettings) error
SetCaptionSettings persists cs into AccessibilitySettings.Caption (keeping SFXCaptions synchronized with cs.Sounds when cs.SoundsSet or cs.Sounds is set).
func (*Assist) SetCaptionSize ¶
SetCaptionSize persists the caption size preset.
func (*Assist) SetCaptionSpeakerColors ¶
SetCaptionSpeakerColors persists whether distinct per-speaker caption colors are enabled.
func (*Assist) SetCaptionTextColor ¶
SetCaptionTextColor persists the caption text color preset or "#rrggbb" hex string.
func (*Assist) SetCaptionsEnabled ¶
SetCaptionsEnabled persists an explicit captions preference.
func (*Assist) SetChatterCaptionsEnabled ¶
SetChatterCaptionsEnabled persists whether ambient background chatter captions are enabled.
func (*Assist) SetColorBlindSeverity ¶
SetColorBlindSeverity clamps v to [0, 1] and persists it.
func (*Assist) SetColorVision ¶
func (a *Assist) SetColorVision(v ColorVision) error
SetColorVision persists the selected color-vision mode.
func (*Assist) SetDialogueCaptionsEnabled ¶
SetDialogueCaptionsEnabled persists whether main spoken dialogue captions are enabled.
func (*Assist) SetGameSpeed ¶
SetGameSpeed clamps v to [MinGameSpeed, MaxGameSpeed] and persists it.
func (*Assist) SetHighContrast ¶
SetHighContrast persists an explicit high-contrast preference.
func (*Assist) SetHoldToToggle ¶
SetHoldToToggle persists the hold-to-toggle assist option.
func (*Assist) SetInputAssists ¶
SetInputAssists validates and persists motor assists into save.Settings.InputAssists.
func (*Assist) SetInvincibility ¶
SetInvincibility persists the invincibility assist option.
func (*Assist) SetReduceFlashes ¶
SetReduceFlashes persists the flash-reduction preference.
func (*Assist) SetReduceMotion ¶
SetReduceMotion persists an explicit reduced-motion preference.
func (*Assist) SetSFXCaptionsEnabled ¶
SetSFXCaptionsEnabled persists whether non-speech sound and music captions are enabled.
func (*Assist) SetScreenShake ¶
SetScreenShake clamps v to [0, 1] and persists it.
func (*Assist) SetTextScale ¶
SetTextScale clamps v to [MinTextScale, MaxTextScale] and persists it.
func (*Assist) Settings ¶
func (a *Assist) Settings() save.AccessibilitySettings
Settings returns the current AccessibilitySettings snapshot.
func (*Assist) Snapshot ¶
func (a *Assist) Snapshot() AssistOptions
Snapshot returns all current assist option values.
type AssistOptions ¶
type AssistOptions struct {
GameSpeed float64
ReduceMotion bool
ReduceFlashes 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
// Qualifier is an optional delivery qualifier shown beside Speaker (e.g. "on radio" -> "Ada (on radio): ...").
Qualifier string
// OmitSpeaker suppresses the speaker prefix when formatting consecutive lines from the same speaker.
OmitSpeaker bool
// 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
// Front is an optional 3D forward projection in [-1, +1] (+1 ahead, -1 behind), used when Has3D is true.
Front float32
// Has3D reports whether Front carries a 3D front/behind cue.
Has3D bool
// Angle is an optional screen-space bearing in radians (0 right, +pi/2 down/behind,
// pi/-pi left, -pi/2 up/ahead), used by SoundIndicatorView when HasAngle is true.
Angle float32
// HasAngle reports whether Angle carries a directional bearing for SoundIndicatorView.
HasAngle bool
// Loudness is an optional audible playback level in [0, 1] used by SoundIndicatorView
// to scale arc prominence; 0 defaults to full prominence (1).
Loudness 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 ¶
Format renders c as human- and screen-reader-friendly text with speaker, qualifier, and directional stereo indicators ([<] for left, [>] for right).
Example ¶
Caption.Format places directional indicators outside the SFX brackets at a pan magnitude of 0.25 or greater.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/a11y"
)
func main() {
for _, direction := range []float32{-0.25, 0.24, 0.25} {
caption := a11y.Caption{Text: "Explosion", Kind: a11y.CaptionSFX, Direction: direction}
fmt.Println(caption.Format())
}
}
Output: [<] [Explosion] [Explosion] [Explosion] [>]
type CaptionEmitter ¶
type CaptionEmitter struct {
// Track receives the captions; Emit and EmitSound do nothing while it is nil.
Track *CaptionTrack
// MinInterval is the shortest time between two captions with the same label or key;
// 0 or less shows every one (unless a sound.CaptionEvent sets a positive per-sound MinInterval).
MinInterval time.Duration
// Duration is the lifetime for captions created by EmitSound (0 uses DefaultCaptionDuration).
Duration time.Duration
// Localizer, when non-nil, resolves sound.Caption.Key values to localized strings using
// the active locale before falling back to the literal key. Takes precedence over Catalog.
Localizer *l10n.Localizer
// Catalog and Locale, when Catalog is non-nil and Localizer is nil, resolve sound.Caption.Key
// values to localized strings before falling back to the literal key.
Catalog *l10n.Catalog
Locale string
// contains filtered or unexported fields
}
CaptionEmitter turns gameplay audio events, such as sound.Mixer.SetCaptionHandler or sound.Effect.SetCaption reports, into CaptionTrack entries. It suppresses a label or key repeated within MinInterval so automatic sound hooks do not flood the caption area. Time is the track's own clock, which CaptionTrack.Update advances on the fixed loop step, so the debounce is deterministic and pauses with the track.
func BindSoundCaptions ¶
func BindSoundCaptions(mixer *sound.Mixer, track *CaptionTrack, opts SoundCaptionOptions) (*CaptionEmitter, func())
BindSoundCaptions attaches a CaptionEmitter to mixer via Mixer.SetCaptionHandler so every captioned Effect or Cue played through mixer automatically feeds track with listener direction, 3D front/behind cues, bearing angle, loudness, and repeat debouncing. It returns the emitter and an unbind function that removes the handler from mixer.
func NewCaptionEmitter ¶
func NewCaptionEmitter(track *CaptionTrack) *CaptionEmitter
NewCaptionEmitter returns an emitter for track with MinInterval DefaultCaptionMinInterval.
func (*CaptionEmitter) Emit ¶
func (e *CaptionEmitter) Emit(label string, kind CaptionKind, direction float32, duration time.Duration) uint64
Emit shows a caption of kind for label in direction, the same [-1, 1] pan audio uses, lasting duration (0 for DefaultCaptionDuration), and returns its ID. It returns 0, showing nothing, for a blank label or a label shown less than MinInterval ago on the track's clock.
func (*CaptionEmitter) EmitSound ¶
func (e *CaptionEmitter) EmitSound(ev sound.CaptionEvent) uint64
EmitSound converts a sound.CaptionEvent into a CaptionTrack entry, resolving Caption.Key through Localizer or Catalog when configured, applying per-sound MinInterval (falling back to e.MinInterval), and preserving stereo pan, 3D front/behind, bearing angle, and loudness. It returns 0 if the event has a blank key or is suppressed by the repeat interval.
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 // CaptionChatter is ambient or background NPC speech shown separately from main dialogue. CaptionChatter )
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 when Assist is nil (default high-contrast near-black at 90% opacity).
Background core.Color
// TextColor is the dialogue/music text color when Assist is nil (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
// ChatterColor overrides the text color for CaptionChatter cues when non-zero.
ChatterColor core.Color
// SpeakerColors supplies optional per-speaker color overrides keyed by speaker name.
SpeakerColors map[string]core.Color
// EnableSpeakerColors enables per-speaker name coloring when Assist is nil.
// When Assist is non-nil, Assist.CaptionSpeakerColors() takes precedence.
EnableSpeakerColors bool
// 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
// MaxLines caps the total number of wrapped caption lines shown simultaneously
// across all visible captions (default DefaultCaptionMaxLines = 2; older lines leave first).
MaxLines int
// MaxChars caps the number of characters per wrapped line (default DefaultCaptionMaxChars = 40).
MaxChars int
// Assist, when non-nil, automatically applies player caption settings
// (background color & opacity, text color, speaker colors, size preset, per-kind
// toggles, HighContrast, ColorVision, and TextScale).
Assist *Assist
// RegionLabel overrides the accessible label of the captions live region
// (default "Captions").
RegionLabel string
// ImportantPrefix overrides the prefix prepended to speakerless
// CaptionImportant cues (default "! ").
ImportantPrefix string
// MusicPrefix overrides the prefix prepended to speakerless CaptionMusic
// cues (default "♪ ").
MusicPrefix string
// 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.
func CaptionStyleFromCatalog ¶
func CaptionStyleFromCatalog(cat *l10n.Catalog, locale string) CaptionStyle
CaptionStyleFromCatalog returns a CaptionStyle whose RegionLabel, ImportantPrefix, and MusicPrefix are filled from cat for locale using the documented a11y.captions.* keys. Missing keys fall back to the English defaults ("Captions", "! ", "♪ ").
func CaptionStyleFromLocalizer ¶
func CaptionStyleFromLocalizer(loc *l10n.Localizer) CaptionStyle
CaptionStyleFromLocalizer returns a CaptionStyle populated from loc's active locale and catalog. If loc is nil, default English caption labels are used.
func (CaptionStyle) ColorForSpeaker ¶
func (s CaptionStyle) ColorForSpeaker(speaker string) core.Color
ColorForSpeaker returns the display color for speaker under s (and Assist.ColorVision when set).
func (CaptionStyle) FormatCaption ¶
func (s CaptionStyle) FormatCaption(c Caption) string
FormatCaption renders c using s's ImportantPrefix and MusicPrefix, falling back to "! " and "♪ " when unset.
type CaptionTrack ¶
type CaptionTrack struct {
// MaxVisible caps how many captions remain active at once; 4 when <= 0.
MaxVisible int
// SpeakerRepeatGap controls how long a silence pause must last before
// ShowDialogue repeats the same speaker's name. Zero defaults to
// DefaultSpeakerRepeatGap (5s); negative values disable suppression so
// speaker names are always shown.
SpeakerRepeatGap time.Duration
// 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 and resets speaker-repeat tracking.
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) ShowChatter ¶
func (t *CaptionTrack) ShowChatter(speaker, text string, duration time.Duration) uint64
ShowChatter appends an ambient or background character chatter caption.
func (*CaptionTrack) ShowDialogue ¶
func (t *CaptionTrack) ShowDialogue(speaker, text string, duration time.Duration) uint64
ShowDialogue appends a spoken dialogue caption attributed to speaker, suppressing the repeated speaker name if the same speaker spoke within SpeakerRepeatGap without an intervening speaker change.
func (*CaptionTrack) ShowDialogueWithQualifier ¶
func (t *CaptionTrack) ShowDialogueWithQualifier(speaker, qualifier, text string, duration time.Duration) uint64
ShowDialogueWithQualifier appends a spoken dialogue caption attributed to speaker with an optional delivery qualifier (such as "on radio"), suppressing the repeated speaker name only when both speaker and qualifier match within SpeakerRepeatGap.
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 ¶
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 the track's logical clock and all active captions by dt, expiring 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 (and accepts "none" as an alias for VisionNormal to match save.AccessibilitySettings).
func (ColorVision) String ¶
func (v ColorVision) String() string
String returns the canonical lowercase identifier for v.
type DialogueCaptionBridge ¶
type DialogueCaptionBridge struct {
Track *CaptionTrack
// contains filtered or unexported fields
}
DialogueCaptionBridge mirrors dialogue.Runner steps into a CaptionTrack so branching dialogue lines get the player's caption settings (size, contrast, speaker colors, toggles) in CaptionsView. Pass each dialogue.Step returned by Runner.Start, Runner.Continue, or Runner.Choose to ShowStep, or a single dialogue.Line to ShowLine, and call Clear when closing the dialogue UI.
func NewDialogueCaptionBridge ¶
func NewDialogueCaptionBridge(track *CaptionTrack) *DialogueCaptionBridge
NewDialogueCaptionBridge creates a bridge feeding track.
func (*DialogueCaptionBridge) Clear ¶
func (b *DialogueCaptionBridge) Clear()
Clear dismisses the currently bridged dialogue caption, if any.
func (*DialogueCaptionBridge) ShowLine ¶
func (b *DialogueCaptionBridge) ShowLine(line dialogue.Line) uint64
ShowLine replaces any previously bridged caption with line and returns its caption ID (0 for a blank line).
func (*DialogueCaptionBridge) ShowStep ¶
func (b *DialogueCaptionBridge) ShowStep(step dialogue.Step) uint64
ShowStep mirrors step onto Track: StepLine replaces the previous bridged caption with the new line and its speaker, StepChoices keeps the current line visible while choices wait, and StepEnded dismisses the active bridged caption. It returns the active caption's ID (0 when dismissed or not shown).
type MenuItem ¶
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 ¶
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
// Text customizes screen-reader announcements and visible toggle labels.
// Unset fields fall back to DefaultMenuText (English).
Text MenuText
// InitialIndex selects the starting focused item (clamped to the first enabled item).
InitialIndex int
// ScanEnabled enables one-switch scanning: the menu moves to the next enabled item every ScanInterval (1.2 s when zero) and activates the highlighted item on ScanSelectKey ("space" when empty). ScanLoops, when positive, stops scanning after that many wraps back to the first item.
ScanEnabled bool
ScanInterval time.Duration
ScanLoops int
ScanSelectKey string
// 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 MenuText ¶
type MenuText struct {
// DefaultLabel is used when MenuProps.Label is empty (default "Menu").
DefaultLabel string
// Opened formats the mount announcement when no item is enabled.
Opened string
// OpenedWithItem formats the mount announcement when an initial item is active.
OpenedWithItem string
// Items holds CLDR plural forms for the item count ({count}), selected using
// Locale (default "en"). Ignored when ItemsFunc is set.
Items l10n.PluralForms
// ItemsFunc, when non-nil, formats the item count directly (set automatically
// by MenuTextFromCatalog and MenuTextFromLocalizer).
ItemsFunc func(count int) string
// Locale is the BCP-47 tag used to select plural rules for Items (default "en").
Locale string
// Checked is spoken for checked toggle items when the platform does not
// already report the checked state (default "checked").
Checked string
// Unchecked is spoken for unchecked toggle items when the platform does not
// already report the checked state (default "unchecked").
Unchecked string
// Position formats focus-change announcements ({item}, {index}, {count}).
Position string
// Selected formats activation announcements for action items ({label}).
Selected string
// Closed formats the Escape/close announcement ({label}).
Closed string
// On is the visible toggle text when Checked returns true (default "On").
On string
// Off is the visible toggle text when Checked returns false (default "Off").
Off string
// Separator joins item status parts (label, checked state, value) in
// spoken announcements (default ", ").
Separator string
}
MenuText holds every user-visible and screen-reader string produced by AccessibleMenu so games can localize menus into any language.
Template fields use named {placeholder} interpolation:
- Opened: {label}, {items}, {count}
- OpenedWithItem: {label}, {items}, {count}, {item}
- Position: {item}, {index}, {count}
- Selected: {label}
- Closed: {label}
- Items: CLDR plural templates with {count}
Partial MenuText values passed via MenuProps.Text inherit any unset fields from DefaultMenuText.
func DefaultMenuText ¶
func DefaultMenuText() MenuText
DefaultMenuText returns the English strings used by AccessibleMenu when MenuProps.Text fields are left empty.
func MenuTextFromCatalog ¶
MenuTextFromCatalog fills a MenuText from cat for locale using the documented a11y.menu.* keys. Any key missing from cat (along locale's fallback chain) falls back to DefaultMenuText. The item count uses cat.Plural for KeyMenuItems.
func MenuTextFromLocalizer ¶
MenuTextFromLocalizer fills a MenuText from loc's active locale and catalog. If loc is nil, DefaultMenuText is returned.
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
type SoundCaptionOptions ¶
type SoundCaptionOptions struct {
// Localizer resolves sound.Caption.Key values using the active locale (takes precedence over Catalog).
Localizer *l10n.Localizer
// Catalog and Locale resolve sound.Caption.Key values when Localizer is nil.
Catalog *l10n.Catalog
Locale string
// Duration sets the lifetime for emitted sound captions (0 uses DefaultCaptionDuration).
Duration time.Duration
// MinInterval overrides the default repeat debounce interval when positive;
// 0 uses DefaultCaptionMinInterval, negative disables the default debounce
// (a sound's own positive Caption.MinInterval still applies).
MinInterval time.Duration
}
SoundCaptionOptions configures BindSoundCaptions.
type SoundIndicatorStyle ¶
type SoundIndicatorStyle struct {
// Assist, when non-nil, automatically applies HighContrast, ColorVision, ReduceMotion,
// and player caption enablement toggles.
Assist *Assist
// IncludeSFX, when true, also draws directional arcs for CaptionSFX entries in addition
// to CaptionImportant entries (default false: important cues only).
IncludeSFX bool
// ImportantColor overrides the arc color for CaptionImportant cues when non-zero
// (defaults to the active palette's Hazard color).
ImportantColor core.Color
// SFXColor overrides the arc color for CaptionSFX cues when non-zero
// (defaults to the active palette's Player / sky-blue color for clear separation from Hazard).
SFXColor core.Color
// RingFraction sets the indicator ring radius as a fraction of min(width, height),
// in (0, 0.5] (default 0.42).
RingFraction float32
// MinThickness is the stroke thickness in points at minimum loudness (default 4).
MinThickness float32
// MaxThickness is the stroke thickness in points at full loudness (default 12).
MaxThickness float32
// MinSweep is the arc span in radians at minimum loudness (default pi/10).
MinSweep float32
// MaxSweep is the arc span in radians at full loudness (default pi/3).
MaxSweep float32
// TestID overrides the root view's TestID (default "a11y-sound-indicator").
TestID string
// Label overrides the canvas accessible label (default "Sound indicator").
Label string
// Style merges additional layout/positioning style onto the overlay container.
Style core.Style
}
SoundIndicatorStyle configures the appearance and behavior of SoundIndicatorView and DrawSoundIndicators.