NativeScript Plugins

repository·main·Indexed 42 days ago

https://github.com/nativescript/plugins

A monorepo managing a suite of NativeScript plugins, including @nativescript/animated-circle for circular progress bars, @nativescript/appavailability for checking installed apps on iOS and Android, and @nativescript/apple-sign-in for Apple authentication.

Tokens
111.6K
Snippets
441
Records
512
Agent score
49%

What's inside NativeScript Plugins

  1. Overview of @nativescript/datetimepicker components

    main

    The @nativescript/datetimepicker plugin provides UI elements for selecting dates and times. It offers two primary ways to interact with pickers:

    1. Field Components: UI elements that can be embedded directly into your layouts.

      • DatePickerField: Extends the TextField view for date selection.
      • TimePickerField: Extends the TextField view for time selection.
      • DateTimePickerFields: A GridLayout container that holds both DatePickerField and TimePickerField components.
    2. Dialog Pickers: A programmatic way to show pickers as modal dialogs.

      • Use the DateTimePicker class and its static methods pickDate() and pickTime() to trigger the native dialog pickers.
  2. Detect fingerprint database changes (iOS Security++)

    main

    To protect against attacks where a new fingerprint is added to the device, use didFingerprintDatabaseChange().

    Recommended Workflow:

    1. Check if biometrics are available().
    2. Call didFingerprintDatabaseChange().
    3. If it returns true, the list of enrolled fingerprints has changed. You should force the user to re-authenticate using their primary credentials (e.g., username/password) before allowing biometric access again.
    4. If false, proceed with the standard fingerprint scan.
    fingerprintAuth.available().then((avail) => {
    	if (!avail) {
    		return;
    	}
    	fingerprintAuth.didFingerprintDatabaseChange().then((changed) => {
    		if (changed) {
    			// re-auth the user by asking for his credentials before allowing a fingerprint scan again
    		} else {
    			// call the fingerprint scanner
    		}
    	});
    });
  3. Configure data filtering in PickerField

    main

    The picker supports a search/filter bar.

    • Set showFilter="true" to enable it.
    • Use filterKeyName to specify which property of your data objects should be used for the search (e.g., if your objects have a title property, set filterKeyName="title").
    • Use focusOnShow="true" to automatically focus the search bar when the modal opens.
    <picker:PickerField 
        showFilter="true" 
        filterKeyName="title" 
        focusOnShow="true" 
        items="{{ pickerItems }}" />
  4. How to use SharedNotificationDelegate with Observers

    main

    The SharedNotificationDelegate allows you to register multiple observers to handle iOS notification events, bypassing the iOS limitation of a single delegate.

    Key Concepts

    • Observer Chain: Methods are called asynchronously in a chain.
    • Handling Notifications: If an observer handles a notification, it calls the provided completionHandler (or stop()) to end the chain.
    • Passing Control: If an observer does NOT want to handle the event, it must call next() to allow the next observer in the chain to process it.
    • Uniqueness: Use delegateUniqueKey to ensure that only one instance of an observer exists (useful for preventing duplicates during Hot Module Replacement/HMR).
    import { SharedNotificationDelegate } from '@nativescript/shared-notification-delegate';
    
    SharedNotificationDelegate.addObserver({
        delegateUniqueKey: "myUniqueKey",
        userNotificationCenterWillPresentNotificationWithCompletionHandler: (notificationCenter, notification, handler, stop, next) => {
            if (shouldHandleThis) {
                // Intercept and handle
                handler(UNNotificationPresentationOptions.Alert);
                return;
            }
            // Pass to the next observer
            next();
        }
    });
  5. Manage contact groups

    main

    The plugin allows you to manage groups of contacts:

    • Get groups: Contacts.getGroups([name]) returns all groups or a specific group by name.
    • Create a group: Instantiate Group, set the name, and call .save(useDefaultContainer: boolean). Note: On iOS, false uses the Local Container, true uses the Default Container. On Android, it always uses the default.
    • Delete a group: Retrieve the group via getGroups() and call .delete() on the group instance.
    • Add a member: Call group.addMember(contact).
    • Remove a member: Call group.removeMember(contact).
    • Get contacts in a group: Use Contacts.getContactsInGroup(group).
    // Create a group
    import { Group } from '@nativescript/contacts/models';
    const groupModel = new Group();
    groupModel.name = 'Test Group';
    groupModel.save(false);
    
    // Add a member
    Contacts.getGroups('Test Group').then(a => {
        if (a.data !== null) {
            const group = a.data[0];
            group.addMember(contact);
        }
    });
  6. How @nativescript/keyboard-toolbar works

    main

    The plugin attaches a custom layout (the toolbar) to the top of the soft keyboard.

    Mechanism:

    1. The plugin takes your declared toolbar layout and moves it off-screen initially.
    2. When a related TextField or TextView receives focus, the plugin animates the toolbar to the top of the keyboard.
    3. The toolbar stays visible until the field loses focus.

    Layout Requirement: To ensure the toolbar stacks correctly, you must wrap your main page layout in a GridLayout. This allows the toolbar to stack on top of your existing content without displacing it.

    Example Structure Change: From:

    <ActionBar/>
    <StackLayout/>

    To:

    <ActionBar/>
    <GridLayout>
        <StackLayout/>
        <Toolbar/>
    </GridLayout>
  7. Configure default language and application name

    main

    Setting the default language

    To set a default language, append the .default extension to the filename (e.g., fr.default.json). This ensures the app has a fallback language. Android will automatically use the locale file matching the device's language (e.g., es.json for Spanish).

    Localizing the application name

    Use the reserved app.name key in your translation files to localize the application name:

    {
    	"app.name": "My app"
    }
  8. Compatibility with IQKeyboardManager

    main

    If you are using IQKeyboardManager for iOS keyboard behavior, @nativescript/keyboard-toolbar will automatically detect it and adjust the scroll offset by the height of your custom toolbar.

    Note: To avoid showing two toolbars on iOS, you may want to suppress the IQKeyboardManager toolbar when using this plugin.

  9. Use HapticsFallback for unsupported devices

    main

    If Haptics.isSupported() returns false, you can use HapticsFallback to attempt to trigger vibrations using undocumented features.

    Warning: Using HapticsFallback utilizes undocumented features that may lead to app rejection during Apple's review process, though some developers have used it without issues.

    Usage Pattern:

    if (!Haptics.isSupported()) {
      // use HapticsFallback
    }
  10. How multiple theme switchers work together

    main

    If your application needs to switch different parts of the UI independently (e.g., one switcher for button styles and another for font styles), you can instantiate multiple ThemeSwitcher objects. Each instance manages its own set of themes and its own persistence state.

    import { ThemeSwitcher } from '@nativescript/theme-switcher'
    
    const switcher1 = new ThemeSwitcher('switcher1');
    const switcher2 = new ThemeSwitcher('switcher2');
    
    switcher1.initThemes({ /* ... */})
    switcher2.initThemes({ /* ... */})
    
    switcher1.switchTheme( /* ... */ )
    switcher2.switchTheme( /* ... */ )