### Query Multiple Topics and Code Samples Examples (JavaScript)
Source: https://github.com/appt-org/appt-samples/blob/main/lib/README.md
Examples demonstrating how to use the `querySamples` function with different filtering options. These examples show how to retrieve all samples, filter by frameworks, or filter by techniques for a given locale.
```javascript
// Get all code topics with all platforms for the 'en' locale
const allSamples = await querySamples(loader, { locale: ['en'] });
// Get all topics with code samples for Android and iOS, for the 'en' locale
const frameworkSamples = await querySamples(
loader,
{ locale: ['en'], frameworks: ['android', 'ios'] }
);
// Get the accessibility role topic with all frameworks, in 'en' locale
const techniqueSamples = await querySamples(
loader,
{ locale: ['en'], techniques: ['accessibility-role'] }
);
```
--------------------------------
### Install Appt Samples Package
Source: https://context7.com/appt-org/appt-samples/llms.txt
Installs the @appt.org/samples package using npm. This package provides the library and code samples for mobile accessibility.
```bash
npm i @appt.org/samples
```
--------------------------------
### Retrieve Single Topic and Code Samples Examples (JavaScript)
Source: https://github.com/appt-org/appt-samples/blob/main/lib/README.md
Examples illustrating the usage of the `getTopic` function. These demonstrate how to fetch a specific topic by its technique and locale, with and without framework filtering.
```javascript
// Get the 'accessibility-role' topic with all available frameworks in 'en' locale
const topic = await getTopic(loader, { locale: ['en'], technique: 'accessibility-role' });
// Get the 'accessibility-role' topic, but only for the 'android' and 'ios' frameworks
const topic = await getTopic({
locale: ['en'],
technique: 'accessibility-role',
frameworks: ['android', 'ios'],
});
```
--------------------------------
### Implement Custom Appt Loader
Source: https://github.com/appt-org/appt-samples/blob/main/lib/README.md
Provides an example of creating a custom loader that implements the `Loader` interface. This allows integration with different bundlers or custom file loading mechanisms.
```typescript
import { Loader } from '@appt.org/samples';
// Create a custom loader
const customLoader: Loader = {
loadSample: async (path, locale, technique, framework) => {
// Example of what the values might be
// path: @appt/samples/samples/en.accessibility-label.android.md
// locale: en
// technique: accessibility-role
// framework: android
// Your custom implementation to load sample introductions
return await (path);
},
loadIntroduction: async (path, locale, technique) => {
// Example of what the values might be
// path: @appt/samples/samples/en.accessibility-label.README.md
// locale: en
// technique: accessibility-role
// Your custom implementation to load sample introductions
return await (path);
}
};
// Use your custom loader with getTopic
import { getTopic } from '@appt.org/samples';
const topic = await getTopic(customLoader, {
locale: ['en'],
technique: 'accessibility-role'
});
```
--------------------------------
### Jetpack Compose TextField onValueChange Example
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/input-predictable/jetpack-compose.md
An example of a Jetpack Compose `TextField` demonstrating the `onValueChange` lambda. It highlights the importance of not triggering context changes within this callback to maintain predictable UI behavior.
```kotlin
TextField(
value = "",
onValueChange = {
// Do not trigger change of context here
},
)
```
--------------------------------
### Display Input Instructions in React Native
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/input-instructions/react-native.md
Demonstrates how to display input instructions in React Native. This example combines Text and TextInput components, and also shows the usage of HelperText from React Native Paper for informational messages.
```jsx
Your password should be at least 8 characters.
Your password should be at least 8 characters.
```
--------------------------------
### Set Audio Attributes and Media Controls for MediaPlayer in Kotlin
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/media-audio-control/android.md
This snippet shows how to configure audio attributes for a MediaPlayer, specifying usage, content type, and legacy stream type. It also includes an example of setting up a click listener for a button to control the player's start and pause states. This requires the Android Media and AudioManager libraries.
```kotlin
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.MediaPlayer
// Set audio attributes
val player = MediaPlayer()
player.setAudioAttributes(
AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ASSISTANCE_ACCESSIBILITY)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.setLegacyStreamType(AudioManager.STREAM_ACCESSIBILITY)
.build()
)
// Provide media controls
button.setOnClickListener {
if (player.isPlaying()) {
player.pause()
} else {
player.start()
}
}
```
--------------------------------
### Get Topic API
Source: https://github.com/appt-org/appt-samples/blob/main/lib/README.md
Retrieves a single topic and its code samples based on specified query parameters. Allows filtering by locale, technique, and frameworks.
```APIDOC
## POST /getTopic
### Description
Retrieves a single topic and its code samples based on specified query parameters. This function fetches a topic by locale, technique, and optionally filters code samples by frameworks.
### Method
POST
### Endpoint
/getTopic
### Parameters
#### Request Body
- **locale** (Locale[]) - Required - The locale to get the topic from. If a topic or sample is not available in the first selected locale, we fall back to the second, then the third etc.
- **technique** (Technique) - Required - The technique to retrieve.
- **frameworks** (Framework[]) - Optional - An array of frameworks to filter code samples by. If omitted, code samples for all available frameworks are included.
### Request Example
```json
{
"locale": ["en"],
"technique": "accessibility-role",
"frameworks": ["android", "ios"]
}
```
### Response
#### Success Response (200)
- **topic** (Topic | null) - A Topic object containing the topic's introduction and code samples for the specified frameworks, or null if the technique or locale does not exist.
#### Response Example
```json
{
"topic": {
"introduction": "Introduction to the accessibility role technique.",
"codeSamples": [
{
"framework": "android",
"language": "kotlin",
"code": "// Android code sample for accessibility role"
},
{
"framework": "ios",
"language": "swift",
"code": "// Swift code sample for accessibility role"
}
]
}
}
```
#### Error Response (404)
- **topic** (null) - Returned if the requested technique or locale does not exist.
#### Error Response Example
```json
{
"topic": null
}
```
```
--------------------------------
### Display Input Instructions in Flutter TextField
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/input-instructions/flutter.md
This snippet shows how to use the `InputDecoration` class to provide helper text for a `TextField` in Flutter. The `helperText` property accepts a string that will be displayed to guide the user on input requirements.
```dart
TextField(
decoration: InputDecoration(
helperText: 'Your password should be at least 8 characters.',
),
);
```
--------------------------------
### SwiftUI Universal Link Handling for Authentication
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/input-authentication/swiftui.md
This example shows how to configure and handle universal links in a SwiftUI application for email-based authentication. It involves setting up associated domains in Xcode, creating an apple-app-site-association file, and processing the incoming URL within the app's lifecycle.
```swift
@main
struct ApptApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.onOpenURL { url in
// Authenticate based on parameters of incoming URL
}
}
}
}
```
--------------------------------
### Control Accelerometer Monitoring in .NET MAUI
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/input-motion/net-maui.md
This C# code demonstrates how to toggle the accelerometer monitoring in a .NET MAUI application. It checks if the accelerometer is supported and available, then either starts or stops monitoring, attaching or detaching an event handler for reading changes. Ensure platform-specific setup is completed for the accelerometer to function correctly.
```csharp
public void UpdateAccelerometer()
{
if (Accelerometer.Default.IsSupported)
{
if (Accelerometer.Default.IsMonitoring)
{
// Turn off
Accelerometer.Default.Stop();
Accelerometer.Default.ReadingChanged -= Accelerometer_ReadingChanged;
}
else
{
// Turn on
Accelerometer.Default.ReadingChanged += Accelerometer_ReadingChanged;
Accelerometer.Default.Start(SensorSpeed.UI);
}
}
}
private void Accelerometer_ReadingChanged(object? sender, AccelerometerChangedEventArgs e)
{
//Apply any logic
}
```
--------------------------------
### Usage of Custom Autofill Composable with TextField in Kotlin
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/input-content-type/jetpack-compose.md
This example demonstrates how to use the custom `Autofill` composable to wrap an `OutlinedTextField`. It shows how to pass multiple `AutofillType` values and handle the autofill callback to update the `TextFieldValue`. This pattern is useful for fields like name or address.
```kotlin
// AutoFill composable usage
var name by
rememberSaveable(stateSaver = TextFieldValue.Saver) { mutableStateOf(TextFieldValue("")) }
Autofill(
// We can pass here multiple AutofillTypes
autofillTypes = listOf(AutofillType.PersonFullName, AutofillType.PersonLastName),
onFill = { name = TextFieldValue(it) }
) {
OutlinedTextField(
value = name,
onValueChange = { name = it },
label = { Text("Name") },
)
}
```
--------------------------------
### Adaptive Layouts with WindowSizeClass in Jetpack Compose
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/screen-orientation/jetpack-compose.md
This code example illustrates using the WindowSizeClass library in Jetpack Compose to create adaptive layouts. It allows developers to tailor the UI for various screen sizes and states, including different device types and foldable scenarios. This approach is more comprehensive than simple orientation checks.
```kotlin
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable
@Composable
fun WindowSizeExample(widthSizeClass: WindowWidthSizeClass) {
when(widthSizeClass) {
WindowWidthSizeClass.Expanded -> // orientation is landscape in most devices including foldables (width 840dp+)
WindowWidthSizeClass.Medium -> // Most tablets are in landscape, larger unfolded inner displays in portrait (width 600dp+)
WindowWidthSizeClass.Compact -> // Most phones in portrait
}
}
```
--------------------------------
### Request Focus (Jetpack Compose)
Source: https://context7.com/appt-org/appt-samples/llms.txt
Shows how to programmatically request focus for a composable element in Jetpack Compose using `FocusRequester`. This is useful for guiding user interaction, such as focusing on an input field when a screen loads.
```kotlin
// Jetpack Compose - Focus Request
val focusRequester = remember { FocusRequester() }
TextField(
modifier = Modifier.focusRequester(focusRequester)
)
LaunchedEffect(Unit) {
focusRequester.requestFocus()
}
```
--------------------------------
### Implement iOS Help Button in Swift
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/screen-help/ios.md
This snippet demonstrates creating a custom UIButton subclass for help functionality in iOS. It configures the button with a system image and accessibility label. The example also shows how to instantiate and potentially add this button to a view controller, with a note on constraint management.
```swift
class HelpButton: UIButton {
private func configure() {
let config = UIImage.SymbolConfiguration(pointSize: 20, weight: .regular)
let image = UIImage(systemName: "questionmark.circle", withConfiguration: config)
setImage(image, for: .normal)
accessibilityLabel = "Help"
}
}
class ApptViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let helpButton = HelpButton()
// Set constraints consistently across screens
}
}
```
--------------------------------
### Usage of Input Content Type Behavior in .NET MAUI (C#)
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/input-content-type/net-maui.md
This C# code example shows how to instantiate and add the InputContentTypeBehavior to an Entry control programmatically. It illustrates setting platform-specific input types for Android and iOS.
```csharp
var entry = new Entry();
entry.Behaviors.Add(new InputContentTypeBehavior
{
FieldTypeAndroid = FieldTypeAndroid.CreditCardExpirationDate,
FieldTypeiOS = FieldTypeiOS.AddressCity
});
```
--------------------------------
### Custom Loader Implementation - TypeScript
Source: https://context7.com/appt-org/appt-samples/llms.txt
Create custom loaders for environments other than Webpack by implementing the Loader interface. This allows integration with Vite, Rollup, or any custom build system. Examples are provided for Vite and Node.js environments.
```typescript
import { Loader, getTopic, querySamples } from '@appt.org/samples';
import type { Locale, Technique, Framework } from '@appt.org/samples';
// Custom loader for Vite using import.meta.glob
const viteModules = import.meta.glob('/node_modules/@appt.org/samples/samples/*.md', {
as: 'raw'
});
const viteLoader: Loader = {
loadSample: async (
path: string, // @appt.org/samples/samples/en.accessibility-label.android.md
locale: Locale, // en
technique: Technique, // accessibility-label
framework: Framework // android
) => {
const modulePath = `/node_modules/${path}`;
const loadModule = viteModules[modulePath];
return loadModule ? await loadModule() : null;
},
loadIntroduction: async (
path: string, // @appt.org/samples/samples/en.accessibility-label.README.md
locale: Locale, // en
technique: Technique // accessibility-label
) => {
const modulePath = `/node_modules/${path}`;
const loadModule = viteModules[modulePath];
return loadModule ? await loadModule() : null;
}
};
// Use custom loader with retrieval functions
const topic = await getTopic(viteLoader, {
locale: ['en'],
technique: 'screen-dark-mode'
});
// Custom loader for server-side/Node.js using fs
import { readFile } from 'fs/promises';
import { join } from 'path';
const nodeLoader: Loader = {
loadSample: async (path, locale, technique, framework) => {
const filePath = join(
'node_modules/@appt.org/samples/dist/samples',
`${locale}.${technique}.${framework}.md`
);
return await readFile(filePath, 'utf-8');
},
loadIntroduction: async (path, locale, technique) => {
const filePath = join(
'node_modules/@appt.org/samples/dist/samples',
`${locale}.${technique}.README.md`
);
return await readFile(filePath, 'utf-8');
}
};
```
--------------------------------
### Set Android Accessibility Live Region (Kotlin)
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/accessibility-live-region/android.md
Demonstrates how to set the accessibility live region for a view in Android using Kotlin. It includes examples for both interrupting ongoing speech (ASSERTIVE) and waiting for ongoing speech (POLITE). This functionality relies on the androidx.core.view.ViewCompat library.
```kotlin
import androidx.core.view.ViewCompat
// Assuming 'view' is a valid Android View object
// Interrupt ongoing speech
ViewCompat.setAccessibilityLiveRegion(view, ViewCompat.ACCESSIBILITY_LIVE_REGION_ASSERTIVE)
// Wait for ongoing speech
ViewCompat.setAccessibilityLiveRegion(view, ViewCompat.ACCESSIBILITY_LIVE_REGION_POLITE)
```
--------------------------------
### Load Localized String in Jetpack Compose (Kotlin)
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/text-localization/jetpack-compose.md
This snippet demonstrates how to create a localized context in Jetpack Compose to fetch a string resource for a specific locale ('nl-NL'). It uses `createConfigurationContext` to apply the locale to the application's resources, making `R.string.appt` available in the specified language. This is crucial for internationalization and accessibility.
```kotlin
val context = LocalContext.current
val localizedContext = remember {
val locales = LocaleList.forLanguageTags("nl-NL")
val configuration = context.resources.configuration
configuration.setLocales(locales)
context.createConfigurationContext(configuration)
}
val localizedString = localizedContext.resources.getString(R.string.appt)
Text(text = localizedString)
```
--------------------------------
### Select Audio Description Track with MediaPlayer in Jetpack Compose
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/media-audio-description/jetpack-compose.md
This code snippet initializes a MediaPlayer, iterates through its available tracks, and selects the audio description track if found. It then starts playback or logs an error. Dependencies include Jetpack Compose state management and Android's MediaPlayer API. It handles potential exceptions during track selection and playback.
```kotlin
var mediaPlayer: MediaPlayer? by remember { mutableStateOf(null) }
var error by remember { mutableStateOf(null) }
val currentContext = LocalContext.current
DisposableEffect(Unit) {
val player = MediaPlayer.create(currentContext, R.raw.video)
mediaPlayer = player
try {
player.trackInfo.forEachIndexed {
index,
trackInfo ->
if (trackInfo.trackType == MediaPlayer.TrackInfo.MEDIA_TRACK_TYPE_AUDIO) {
player.selectTrack(index)
return@forEachIndexed
}
}
player.start()
} catch (e: Exception) {
e.printStackTrace()
error = e.message
}
onDispose {
player.release()
mediaPlayer = null
}
}
```
--------------------------------
### C# Usage of Accessibility Custom Action Behavior in .NET MAUI
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/accessibility-action/net-maui.md
This C# code example illustrates how to add the `AccessibilityCustomActionBehavior` to an Image object programmatically in .NET MAUI. It shows the instantiation of the behavior and the setting of its `Name` and `Action` properties, including a placeholder for the custom action logic.
```csharp
var image = new Image();
image.Behaviors.Add(new AccessibilityCustomActionBehavior
{
Name = "",
Action = () =>
{
// Custom action logic
return true;
}
});
```
--------------------------------
### Create and Use Webpack Loader with Appt Samples
Source: https://github.com/appt-org/appt-samples/blob/main/lib/README.md
Demonstrates how to create a webpack context for Markdown files and use it with the createWebpackLoader function. It then shows how to use this loader with the getTopic function to retrieve samples.
```javascript
// In your application code
import { createWebpackLoader } from '@appt.org/samples';
// Create a webpack context that includes all markdown files
const webpackContext = require.context(
'@appt.org/samples/samples',
true, // Include subdirectories
/\.md$/,
'lazy' // Only load a sample when it is requested in retrieval
);
// Create a loader using the webpack context
const loader = createWebpackLoader(webpackContext);
// Now you can use the loader with the getTopic function
import { getTopic } from '@appt.org/samples';
const topic = await getTopic(loader, {
locale: ['en'],
technique: 'accessibility-role'
});
// The imported markdown file is available under topic.samples[number].content.
// The value of `content` depends on your own Webpack configuration.
```
--------------------------------
### Display Scrollable Text in React Native
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/media-transcript/react-native.md
This snippet shows how to display text within a ScrollView in React Native. The ScrollView component enables scrolling for content that exceeds the screen's visible area. The Text component is used for rendering the actual text content. Ensure you have React Native installed and configured.
```jsx
Appt transcript
```
--------------------------------
### Display Input Instructions in SwiftUI
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/input-instructions/swiftui.md
This snippet shows how to use SwiftUI's Text and Button views to display and toggle input instructions. It also demonstrates setting a state variable to control the visibility and content of the help message. No external dependencies are required beyond SwiftUI.
```swift
import SwiftUI
struct ContentView: View {
@State private var showHelp = false
@State private var helpMessage = ""
var body: some View {
VStack {
// Other UI elements here such as a TextField ...
Button(action: {
// Example action to display input instructions
showHelp.toggle()
helpMessage = "Provide a date in form DD/MM/YYYY, for example, 01/01/2000"
}) {
Text(showHelp ? "Hide Help" : "Help")
}
if showHelp {
Text(helpMessage)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
```
--------------------------------
### Indicate State with accessibilityValue in SwiftUI
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/accessibility-state/swiftui.md
This example demonstrates how to use the accessibilityValue modifier in SwiftUI to provide a textual representation of a view's state, such as 'Expanded' or 'Collapsed'. This is useful when a standard trait like .isSelected does not accurately describe the state.
```swift
import SwiftUI
struct ExpandableView: View {
@State private var isExpanded = false
var body: some View {
VStack {
Text("Expandable Content")
.padding()
if isExpanded {
Text("This is the expanded content.")
.padding()
}
}
.background(Color.gray.opacity(0.2))
.cornerRadius(8)
.onTapGesture {
isExpanded.toggle()
}
// Accessibility value indicates the state
.accessibilityValue(isExpanded ? "Expanded": "Collapsed")
.accessibilityHint("Tap to expand or collapse")
}
}
struct ExpandableView_Previews: PreviewProvider {
static var previews: some View {
ExpandableView()
}
}
```
--------------------------------
### Handle Universal Links in AppDelegate for Authentication (Swift)
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/input-authentication/ios.md
Implement the `application(_:continue:restorationHandler:)` method in your `AppDelegate` to process incoming Universal Links. This method is called when your app is launched or brought to the foreground via a universal link, allowing you to extract URL parameters for authentication.
```swift
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(
_ application: UIApplication,
continue userActivity: NSUserActivity,
restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void
) -> Bool {
if let url = userActivity.webpageURL {
// Authenticate based on parameters of incoming URL
}
}
}
```
--------------------------------
### Display Transcript with UILabel in UIScrollView (Swift)
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/media-transcript/ios.md
This option demonstrates embedding a UILabel within a UIView, which is then added to a UIScrollView. This setup allows for custom layouts and scrolling behavior for the transcript text.
```swift
let transcript = UILabel()
transcript.text = "Appt transcript"
let view = UIView()
view.addSubview(transcript)
let scrollView = UIScrollView()
scrollView.addSubview(view)
```
--------------------------------
### Implement Keyboard Shortcuts in iOS using UIKeyCommand
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/keyboard-shortcuts/ios.md
This Swift code demonstrates how to add keyboard shortcuts to an iOS application using UIKeyCommand. It shows the creation of a UIKeyCommand with specific input and modifier flags, and how to return it in the keyCommands property. The associated action method is also included.
```swift
let find = UIKeyCommand(
input: "f",
modifierFlags: .command,
action: #selector(findContent),
discoverabilityTitle: "Find"
)
override var keyCommands: [UIKeyCommand]? {
return [find]
}
@objc private func find() {
// Logic
}
```
--------------------------------
### Input Keyboard Types in Xamarin.Forms
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/input-keyboard-type/xamarin.md
This section explains how to use the `Keyboard` property in Xamarin.Forms to customize the on-screen keyboard for input fields. It lists the available keyboard types and provides an example.
```APIDOC
## Input Keyboard Types - Xamarin.Forms
### Description
In Xamarin.Forms, you can set a specific keyboard type for input fields by utilizing the `Keyboard` property of input controls like `Entry` or `Editor`. This allows you to tailor the keyboard to the expected input, improving user experience.
### Method
Set the `Keyboard` property on the input control.
### Endpoint
N/A (This is a UI property, not an API endpoint)
### Parameters
#### Keyboard Properties
- **Chat** - Keyboard optimized for chatting, includes emoji characters.
- **Default** - The standard system keyboard.
- **Email** - Keyboard suitable for email addresses, includes the '@' symbol.
- **Numeric** - Keyboard for entering numerical values, includes ',' and '.' for decimal points.
- **Plain** - Keyboard for entering general plain text.
- **Telephone** - Keyboard designed for phone numbers, includes '+' and '#' symbols.
- **Text** - Standard text input keyboard, includes an 'enter' key.
- **Url** - Keyboard optimized for URL input, includes '/' symbol.
### Request Example
```xml
```
### Response
N/A (This is a UI configuration, not an API request/response)
#### Success Response (UI Update)
- The input field will display the keyboard corresponding to the selected `Keyboard` type.
```
--------------------------------
### Configure Webpack for Markdown Loading
Source: https://github.com/appt-org/appt-samples/blob/main/lib/README.md
Configures Webpack to handle .md files as 'asset/source'. This allows the library to import Markdown files directly. This rule can be customized based on your project's needs.
```javascript
module.exports = {
module: {
rules: [
{
test: /\.md$/,
type: 'asset/source'
}
]
}
};
```
--------------------------------
### Set Attributed Accessibility Label - Swift
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/accessibility-label/ios.md
Shows how to set an attributed accessibility label in Swift, allowing for custom pronunciation. This example specifically sets the language to Dutch using NSAttributedString attributes.
```swift
element.attributedAccessibilityLabel = NSAttributedString(
string: "Appt",
attributes: [.accessibilitySpeechLanguage: "nl-NL"]
)
```
--------------------------------
### Set Accessibility Role (React Native)
Source: https://context7.com/appt-org/appt-samples/llms.txt
Provides an example of setting the accessibility role for interactive elements in React Native. The `accessibilityRole` prop helps define the purpose of the element to assistive technologies.
```jsx
// React Native - Accessibility Role
```
--------------------------------
### Create Webpack Loader for Appt Samples
Source: https://context7.com/appt-org/appt-samples/llms.txt
Creates a Webpack loader instance to dynamically load accessibility topic introductions and samples using Webpack's require.context. This function adapts Webpack's module loading to the Appt Samples Loader interface, facilitating integration with build systems.
```typescript
import { createWebpackLoader, getTopic } from '@appt.org/samples';
// Webpack configuration to handle markdown files
// webpack.config.js
// module.exports = {
// module: {
// rules: [
// {
// test: /\.md$/,
// type: 'asset/source'
// }
// ]
// }
// };
// Create a webpack context for all markdown files (lazy loaded)
const webpackContext = require.context(
'@appt.org/samples/samples',
true,
/\.md$/,
'lazy'
);
// Create loader using the webpack context
const loader = createWebpackLoader(webpackContext);
// Example usage with getTopic:
// const topic = await getTopic(loader, {
// locale: ['en'],
// technique: 'accessibility-role'
// });
// console.log(topic.introduction.content);
// console.log(topic.samples[0].framework.label);
```
--------------------------------
### Initialize MediaElement in C# for MAUI Audio Control
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/media-audio-control/net-maui.md
This C# code demonstrates how to create and configure a MediaElement instance programmatically. It sets the audio source and enables autoplay. This is useful for dynamic audio loading within your MAUI application.
```csharp
var mediaElement = new MediaElement
{
ShouldAutoPlay = true,
Source = "TheUrlOrPathForYouAudio.mp3"
};
```
--------------------------------
### Display Input Instructions with Label in Xamarin.Forms
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/input-instructions/xamarin.md
This snippet shows how to use the Xamarin.Forms Label control to display text instructions to the user. It's a simple way to provide guidance for input fields. No external dependencies are required beyond the Xamarin.Forms framework.
```xml
```
--------------------------------
### Indicate Selection State with AccessibilityTraits in SwiftUI
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/accessibility-state/swiftui.md
This snippet shows how to use the .isSelected AccessibilityTrait to indicate a selection state for a custom view in SwiftUI. It relies on a @State variable to manage the selection status and applies the trait conditionally.
```swift
import SwiftUI
struct CustomCheckbox: View {
@Binding var isSelected: Bool
var body: some View {
Image(systemName: isSelected ? "checkmark.square.fill" : "square")
.resizable()
.frame(width: 24, height: 24)
.onTapGesture {
isSelected.toggle()
}
}
}
struct ContentView: View {
@State private var isSelected: Bool = false
var body: some View {
CustomCheckbox(isSelected: $isSelected)
.accessibilityLabel("Toggle selection")
.accessibilityAddTraits(isSelected ? [.isSelected] : [])
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
```
--------------------------------
### Detect Pinch Gestures in Swift (iOS)
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/input-gestures/ios.md
This Swift code snippet demonstrates how to create and add a UIPinchGestureRecognizer to a view in iOS. It includes a target-action setup to handle the pinch event and a placeholder for providing an alternative action.
```swift
let gesture = UIPinchGestureRecognizer(
target: self,
action: #selector(onPinch(_:))
)
addGestureRecognizer(gesture)
@objc private func onPinch(_ sender: UIPinchGestureRecognizer) {
// Provide alternative
}
```
--------------------------------
### Query Samples API
Source: https://github.com/appt-org/appt-samples/blob/main/lib/README.md
Retrieves multiple topics and their code samples based on specified query parameters. Supports filtering by locale, techniques, and frameworks.
```APIDOC
## POST /querySamples
### Description
Retrieves multiple topics and their code samples based on specified query parameters. This function filters topics and code samples by locale, techniques, and frameworks.
### Method
POST
### Endpoint
/querySamples
### Parameters
#### Request Body
- **locale** (Locale[]) - Required - The locale to get samples from. If a sample is not available in the first selected locale, we fall back to the second, then the third etc.
- **techniques** (Technique[]) - Optional - An array of techniques to filter by.
- **frameworks** (Framework[]) - Optional - An array of frameworks to filter by.
### Request Example
```json
{
"locale": ["en"],
"frameworks": ["android", "ios"]
}
```
### Response
#### Success Response (200)
- **topics** (Topic[]) - An array of Topic objects, each containing topic introduction and code samples.
#### Response Example
```json
{
"topics": [
{
"introduction": "Sample introduction for a topic.",
"codeSamples": [
{
"framework": "android",
"language": "kotlin",
"code": "// Kotlin code sample"
}
]
}
]
}
```
```
--------------------------------
### Configure ExoPlayer for Live Captions in Jetpack Compose (Kotlin)
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/media-captions-live/jetpack-compose.md
This snippet demonstrates how to initialize and configure an ExoPlayer instance within a Jetpack Compose UI. It sets up a `DefaultTrackSelector` to prefer Dutch subtitles and prepares an HLS media source for live streaming. The player is managed using `DisposableEffect` for proper lifecycle handling.
```kotlin
val context = LocalContext.current
var exoPlayer by remember { mutableStateOf(null) }
DisposableEffect(Unit) {
// Create a track selector with preferred text language
val trackSelector = DefaultTrackSelector(context).apply {
setParameters(buildUponParameters().setPreferredTextLanguage("nl"))
}
val player = ExoPlayer.Builder(context)
.setTrackSelector(trackSelector)
.build()
val dataSourceFactory = DefaultHttpDataSource.Factory()
.setUserAgent(Util.getUserAgent(context, "Appt"))
.setAllowCrossProtocolRedirects(true)
// Prepare the media source
val mediaUri = Uri.parse("https://appt.org/live-video")
val mediaSource = HlsMediaSource.Factory(dataSourceFactory)
.createMediaSource(MediaItem.fromUri(mediaUri))
player.setMediaSource(mediaSource)
player.prepare()
player.playWhenReady = true
exoPlayer = player
onDispose {
player.release()
exoPlayer = null
}
}
```
--------------------------------
### Displaying Instructions with TextField in Jetpack Compose
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/input-instructions/jetpack-compose.md
Shows how to use the `supportingText` parameter of the `TextField` composable in Jetpack Compose to display instructional text to the user. This is commonly used for input validation or guidance, such as password length requirements. It requires the `androidx.compose.material` library.
```kotlin
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
@Composable
fun InstructionTextField() {
TextField(
value = "",
onValueChange = { /* State update logic */ },
supportingText = {
Text("Your password should be at least 8 characters.")
}
)
}
```
--------------------------------
### Jetpack Compose Audio Control with MediaPlayer and AudioAttributes
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/media-audio-control/jetpack-compose.md
This snippet demonstrates how to initialize a MediaPlayer with specific AudioAttributes for accessibility and speech content in a Jetpack Compose UI. It also includes a button to toggle playback between start and pause states.
```kotlin
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.MediaPlayer
import androidx.compose.material3.Button
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
@Composable
fun AudioControlScreen() {
// Set audio attributes
val player = remember {
MediaPlayer().apply {
setAudioAttributes(
AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ASSISTANCE_ACCESSIBILITY)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.setLegacyStreamType(AudioManager.STREAM_ACCESSIBILITY)
.build()
)
}
}
// Provide media controls
Button(
onClick = {
if (player.isPlaying) {
player.pause()
} else {
player.start()
}
}
) {
// Button content...
}
}
```
--------------------------------
### Query Multiple Topics and Code Samples (TypeScript)
Source: https://github.com/appt-org/appt-samples/blob/main/lib/README.md
The `querySamples` function retrieves multiple topics and their code samples based on specified query parameters. It filters by locale, and optionally by techniques and frameworks. If a sample is not available in the primary locale, it falls back to secondary locales.
```typescript
async function querySamples(
loader: Loader,
query: {
locale: Locale[];
techniques?: Technique[];
frameworks?: Framework[];
}
): Promise
```
--------------------------------
### Suppressing Lint Warnings in Kotlin
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/linting/android.md
Demonstrates how to suppress specific Android Lint warnings in Kotlin code using the @SuppressLint annotation. This is useful when a lint check is not applicable or when the desired behavior requires bypassing the check. The example suppresses the 'SetJavaScriptEnabled' warning for a WebView.
```kotlin
import android.webkit.WebView
import android.annotation.SuppressLint
// Suppressing java script enabled warning
val webView: WebView
@SuppressLint("SetJavaScriptEnabled")
webView.settings.javaScriptEnabled = true
```
--------------------------------
### Display Text with React Native Text Component
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/text-element/react-native.md
Use the `Text` component from React Native to render text content. This is the standard way to display strings within a React Native application. Ensure you have React Native installed and configured.
```jsx
Appt
```
--------------------------------
### Set Input Instructions using SemanticProperties.Description in .NET MAUI
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/input-instructions/net-maui.md
Demonstrates how to set the input instructions for a UI element in .NET MAUI. This is achieved using the SemanticProperties.Description attached property, which is crucial for accessibility. The property takes a string describing the expected input.
```csharp
var entry = new Entry();
SemanticProperties.SetDescription(entry, "Your password should be at least 8 characters.");
```
```xml
```
--------------------------------
### Run SwiftLint for Code Quality in SwiftUI
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/linting/swiftui.md
This command executes SwiftLint to analyze and lint your SwiftUI project's code. It helps identify potential issues and enforce coding standards, ensuring higher code quality and maintainability.
```shell
swiftlint lint
```
--------------------------------
### Set up Localization in React Native
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/text-localization/react-native.md
This snippet shows how to initialize localization in a React Native app. It uses expo-localization to detect the device's locale and i18n-js to manage translation files. Ensure you have `expo-localization` and `i18n-js` installed.
```jsx
import * as Localization from 'expo-localization';
import i18n from 'i18n-js';
// Set the key-value pairs for the different languages you want to support.
i18n.translations = {
en: { welcome: 'Appt accessibility' },
nl: { welcome: 'Appt toegankelijkheid' },
};
// Set the locale once at the beginning of your app.
i18n.locale = Localization.locale;
```
--------------------------------
### Set Keyboard Type to Number Pad in SwiftUI
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/input-keyboard-type/swiftui.md
This code snippet demonstrates how to set the keyboard type for a SwiftUI TextField to a number pad. It uses the `.keyboardType(.numberPad)` modifier. This is useful for inputs that should only accept numeric characters, such as phone numbers or PINs.
```swift
import SwiftUI
struct ContentView: View {
@State private var phoneNumber: String = ""
var body: some View {
TextField("Phone Number", text: $phoneNumber)
// Set keyboard type
.keyboardType(.numberPad)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
```
--------------------------------
### Display Text with UILabel in Swift
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/text-element/ios.md
Demonstrates how to create and configure a UILabel to display text on iOS. This involves initializing a UILabel object and setting its text property. No external dependencies are required beyond the UIKit framework.
```swift
let label = UILabel()
label.text = "Appt"
```
--------------------------------
### Implement Input Gestures in .NET MAUI using C#
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/input-gestures/net-maui.md
This snippet demonstrates how to add various gesture recognizers (Drag, Drop, Pan, Pinch, Pointer, Swipe, Tap) to a Label UI element in .NET MAUI using C# code. It shows the instantiation of each gesture recognizer and the attachment of event handlers for different gesture events.
```csharp
var label = new Label();
var dragGestureRecognizer = new DragGestureRecognizer();
dragGestureRecognizer.CanDrag = true;
dragGestureRecognizer.DropCompleted += DragGestureRecognizer_DropCompleted;
dragGestureRecognizer.DragStarting += DragGestureRecognizer_DragStarting;
label.GestureRecognizers.Add(dragGestureRecognizer);
var dropGestureRecognizer = new DropGestureRecognizer();
dropGestureRecognizer.AllowDrop = true;
dropGestureRecognizer.DragLeave += DropGestureRecognizer_DragLeave;
dropGestureRecognizer.DragOver += DropGestureRecognizer_DragOver;
label.GestureRecognizers.Add(dropGestureRecognizer);
var panGestureRecognizer = new PanGestureRecognizer();
panGestureRecognizer.PanUpdated += PanGestureRecognizer_PanUpdated;
label.GestureRecognizers.Add(panGestureRecognizer);
var pinchGestureRecognizer = new PinchGestureRecognizer();
pinchGestureRecognizer.PinchUpdated += PinchGestureRecognizer_PinchUpdated;
label.GestureRecognizers.Add(pinchGestureRecognizer);
var pointerGestureRecognizer = new PointerGestureRecognizer();
pointerGestureRecognizer.PointerEntered += PointerGestureRecognizer_PointerEntered;
pointerGestureRecognizer.PointerExited += PointerGestureRecognizer_PointerExited;
pointerGestureRecognizer.PointerMoved += PointerGestureRecognizer_PointerMoved;
pointerGestureRecognizer.PointerPressed += PointerGestureRecognizer_PointerPressed;
label.GestureRecognizers.Add(pointerGestureRecognizer);
var swipeGestureRecognizer = new SwipeGestureRecognizer();
swipeGestureRecognizer.Direction = SwipeDirection.Left;
swipeGestureRecognizer.Swiped += SwipeGestureRecognizer_Swiped;
label.GestureRecognizers.Add(swipeGestureRecognizer);
var tapGestureRecognizer = new TapGestureRecognizer();
tapGestureRecognizer.NumberOfTapsRequired = 2;
tapGestureRecognizer.Tapped += TapGestureRecognizer_Tapped;
label.GestureRecognizers.Add(tapGestureRecognizer);
```
--------------------------------
### Add Accessibility Hint to SwiftUI Button
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/accessibility-hint/swiftui.md
This snippet shows how to apply the accessibilityHint modifier to a SwiftUI Button. The hint provides extra context for VoiceOver users, read after the label and value. Essential information should not be placed solely in the hint as users can disable them.
```swift
Button(action: {}, label: {
Text("Search")
})
.accessibilityHint("Searches for accessibility articles")
```
--------------------------------
### Retrieve Single Topic and Code Samples (TypeScript)
Source: https://github.com/appt-org/appt-samples/blob/main/lib/README.md
The `getTopic` function retrieves a single topic and its code samples based on specified query parameters. It requires a locale and a technique, and can optionally filter code samples by frameworks. It returns `null` if the technique or locale does not exist.
```typescript
async function getTopic(
loader: Loader,
query: {
locale: Locale[];
technique: Technique;
frameworks?: Framework[];
}
): Promise
```
--------------------------------
### Add Captions to React Native Video
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/media-captions/react-native.md
This snippet shows how to configure text tracks for captions in a React Native Video component. It utilizes the react-native-video package and supports VTT and SRT formats. Ensure the react-native-video package is installed and imported correctly.
```jsx
import { TextTrackType, Video } from 'react-native-video';
```
--------------------------------
### Apple App Site Association File Configuration
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/input-authentication/swiftui.md
This JSON configuration file is used to define the paths within a domain that should be handled by a specific iOS application via Universal Links. It requires a valid TEAM_ID and the app's bundle identifier.
```json
{
"applinks": {
"details": [
{
"appID": "TEAM_ID.com.example.bundle",
"paths": ["/auth/*"]
}
]
}
}
```
--------------------------------
### Set Accessibility Role - Swift
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/accessibility-role/ios.md
This snippet demonstrates how to set the accessibility role for an element in Swift. It utilizes the `accessibilityTraits` attribute and shows examples of assigning single roles like `.button`, `.header`, `.link`, and `.image`, as well as combining multiple roles such as `.button` and `.selected`.
```swift
element.accessibilityTraits = .button
element.accessibilityTraits = .header
element.accessibilityTraits = .link
element.accessibilityTraits = .image
element.accessibilityTraits = [.button, .selected]
```
--------------------------------
### Set Accessibility Language for UI Elements in Swift
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/accessibility-language/ios.md
Shows how to set the accessibility language for UI elements like UIApplication and UIView using the accessibilityLanguage attribute. This ensures that accessibility features, including spoken content, adhere to the specified language, for example, Dutch ('nl_NL').
```swift
application.accessibilityLanguage = "nl_NL"
view.accessibilityLanguage = "nl_NL"
```
--------------------------------
### Listen to Orientation Changes - C#
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/screen-orientation/xamarin.md
This C# code snippet demonstrates how to subscribe to and handle screen orientation changes using the DeviceDisplay class from Xamarin.Essentials. It shows the constructor for subscribing and a method for processing the display information when a change occurs. No external dependencies beyond Xamarin.Essentials are required.
```csharp
public class OrientationChanges
{
public OrientationChanges()
{
// Subscribe to changes of screen metrics
DeviceDisplay.MainDisplayInfoChanged += OnMainDisplayInfoChanged;
}
void OnMainDisplayInfoChanged(object sender, DisplayInfoChangedEventArgs e)
{
// Process changes
var displayInfo = e.DisplayInfo;
}
}
```
--------------------------------
### Configure ExoPlayer for Live Captions in Android (Kotlin)
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/media-captions-live/android.md
This Kotlin code configures an ExoPlayer instance for live captions on Android. It sets preferred text language, user agent for data source, and prepares an HLS media source. Dependencies include Media3 libraries.
```kotlin
val trackSelector = DefaultTrackSelector(baseContext).apply {
setParameters(buildUponParameters().setPreferredTextLanguage("nl"))
}
val player = ExoPlayer.Builder(context)
.setTrackSelector(trackSelector)
.build()
val dataSourceFactory = DefaultHttpDataSource.Factory()
.setUserAgent(Util.getUserAgent(context, "Appt"))
.setAllowCrossProtocolRedirects(true)
val mediaUri = Uri.parse("https://appt.org/live-video")
val mediaSource = HlsMediaSource.Factory(dataSourceFactory)
.createMediaSource(MediaItem.fromUri(mediaUri))
player.setMediaSource(mediaSource)
player.prepare()
player.playWhenReady = true
```
--------------------------------
### Implement Pinch Gesture Handling in React Native
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/input-gestures/react-native.md
This snippet demonstrates how to use the `PinchGestureHandler` from `react-native-gesture-handler` to detect pinch gestures. It includes event handling for gesture updates and state changes, and utilizes `Animated` for smooth transformations. Ensure `react-native-gesture-handler` is installed and configured.
```jsx
import { PinchGestureHandler, State } from 'react-native-gesture-handler'
import { Animated, View } from 'react-native'
const PinchableView = () => {
const scale = new Animated.Value(1)
const onPinchEvent = Animated.event([
{
nativeEvent: { scale: this.scale }
}
], {
useNativeDriver: true
})
const onPinchStateChange = event => {
if (event.nativeEvent.oldState === State.ACTIVE) {
// Provide alternative
Animated.spring(this.scale, {
toValue: 1,
useNativeDriver: true
}).start()
}
}
return (
)
}
```
--------------------------------
### Retrieve Topic and Samples with getTopic
Source: https://context7.com/appt-org/appt-samples/llms.txt
Retrieves a specific accessibility topic and its associated code samples based on locale, technique, and optional framework filters. It supports locale fallback and returns null if the technique or locale is not found. The function returns a detailed structure including introduction and samples for each framework.
```typescript
import { getTopic } from '@appt.org/samples';
// Assume 'loader' is an instance created by createWebpackLoader
// const loader = ...
// Get accessibility-label topic with all frameworks for 'en' locale
// const topic = await getTopic(loader, {
// locale: ['en'],
// technique: 'accessibility-label'
// });
// Get topic filtered to specific frameworks (android and ios) for 'en' locale
// const mobileTopic = await getTopic(loader, {
// locale: ['en'],
// technique: 'accessibility-role',
// frameworks: ['android', 'ios']
// });
// console.log(mobileTopic.samples.length); // Expected: 2
// console.log(mobileTopic.samples[0].framework.label); // Expected: "Android"
// console.log(mobileTopic.samples[1].framework.label); // Expected: "iOS"
```
--------------------------------
### Assign Accessibility Roles with Semantics in Flutter
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/accessibility-role/flutter.md
This code snippet demonstrates how to use the Semantics widget in Flutter to manually assign accessibility roles to a child widget. It shows examples of setting roles such as 'button', 'header', 'link', and 'image'. This is useful when roles are not automatically assigned by Flutter.
```dart
Semantics(
button: true,
header: true,
link: true,
image: true,
child: Widget(...)
);
```
--------------------------------
### Access and Set Locale in SwiftUI
Source: https://github.com/appt-org/appt-samples/blob/main/data/en/text-localization/swiftui.md
Demonstrates how to access the current locale using the @Environment property wrapper and how to dynamically set the locale for a SwiftUI view hierarchy. This is useful for testing or providing user-selectable languages.
```swift
// Get current locale
@Environment(\.locale) var locale: Locale
// Set the locale dynamically
WindowGroup {
ContentView()
.environment(\.locale, .init(identifier: "en"))
}
```