Mới v1.2.2 Exact Dynamic Hit Layer, Native Chronometer Countdown, Swift 6 Ready & Chuẩn hoá UI IR Xem chi tiết →
react-native-live-widgets
v1.2.2
100% Declarative UI • Không viết Swift / Kotlin • Expo CNG Ready

Live Activities & Dynamic Island Chỉ với TypeScript & JSX

Giải pháp toàn diện All-in-One cho Live Activities, Dynamic Island và Interactive Home Screen Widgets trên cả iOS & Android. Tích hợp sẵn bộ mô phỏng <WidgetPreview> và chuẩn dữ liệu mở cho AI Agent.

$ npm install react-native-live-widgets
Tương tác trực tiếp trên trình duyệt

Live Simulator: Trải Nghiệm Widget & Dynamic Island

Nhấp chuột vào các chế độ bên dưới để xem Dynamic Island co dãn, sóng âm Equalizer chuyển động và nút bấm Home Widget phản hồi tức thì!

Nhấn vào các nút bên trong widget để thấy phản hồi tương tác!

Mã TypeScript Declarative
// Mã nguồn tương ứng
              

Tại sao chọn `react-native-live-widgets`?

Kiến trúc đột phá giúp phát triển Widget Native nhanh gấp 10 lần mà vẫn bảo toàn hiệu năng tối đa.

100% Không Viết Swift / Kotlin

Viết giao diện hoàn toàn bằng JavaScript/TypeScript hoặc cú pháp JSX. Thư viện tự động chuyển đổi thành cây Native AST cho WidgetKit và RemoteViews.

Tương Tác 2 Chiều (AppIntents)

Nút bấm trên Home Widget kích hoạt trực tiếp hàm JavaScript trong React Native qua React Hook useWidgetAction() mà không cần mở toàn màn hình ứng dụng.

Timer Phần Cứng (0% Tiêu Hao Pin)

UI.Timer tự động đếm giây mượt mà trên Dynamic Island dựa vào chip hệ thống của iOS/Android mà không làm thức giấc CPU hay hao tổn pin thiết bị.

Sóng Nhạc Động (Equalizer)

Duy nhất trên thị trường hỗ trợ hiệu ứng sóng âm thanh chuyển động liên tục cho ứng dụng nghe nhạc, podcast, radio trực tiếp trên Dynamic Island & Notification.

Đồng Bộ Ngầm Khi Kill App

Hàm Widget.setRemoteConfig() cho phép cấu hình URL API ngầm để hệ điều hành iOS/Android tự động fetch dữ liệu mới cho Widget kể cả khi ứng dụng đã bị tắt.

Chuẩn AI Agent (llms.txt)

Sẵn sàng 100% cho ChatGPT, Claude Code, Cursor, Antigravity thông qua llms.txt và SKILL.md. Agent của bạn có thể tự lập trình widget không lỗi.

Sẵn sàng 100% cho ChatGPT, Claude Code, Cursor, Antigravity thông qua llms.txt và SKILL.md. Agent của bạn có thể tự lập trình widget không lỗi.

Cài đặt & Thiết lập Tự động

Thư viện tích hợp sẵn bộ All-in-One CLI Scaffolder giúp cấu hình Xcode Widget Extension, App Groups và Android permissions chỉ với 1 câu lệnh duy nhất.

1. Quy trình dành cho Expo (SDK 50, 51, 52, 58+ CNG) Config Plugin

Thư viện tương thích 100% với Continuous Native Generation (CNG) và EAS Build:

# Bước 1: Cài đặt thư viện
npx expo install react-native-live-widgets

# Bước 2: Thiết lập tự động 1 lệnh (tự cấu hình app.json, tạo widgets.config.ts, sync icons & Swift)
npx react-native-live-widgets init

# Bước 3: Chạy ứng dụng trên máy ảo / thiết bị thật
npx expo run:ios
npx expo run:android

Cấu hình Config Plugin được tự động thêm vào tập tin app.json:

{
  "expo": {
    "name": "MyAwesomeApp",
    "slug": "my-awesome-app",
    "plugins": [
      [
        "react-native-live-widgets",
        {
          "appGroup": "group.com.yourcompany.app",
          "enableLiveActivities": true,
          "frequentUpdates": true
        }
      ]
    ]
  }
}
2. Quy trình dành cho Bare React Native CLI CLI Auto-Link
# Bước 1: Cài đặt package
npm install react-native-live-widgets
# hoặc: yarn add react-native-live-widgets

# Bước 2: Tự động cấu hình Xcode Target, Entitlements, Podfile, pod install, Android permissions và Swift bundle
npx react-native-live-widgets init

# Bước 3: Khởi chạy dự án
npx react-native run-ios
npx react-native run-android
3. Lệnh đồng bộ Codegen & Đa ngôn ngữ (i18n) Codegen Engine

Mỗi khi bạn thêm widget mới hoặc chỉnh sửa nội dung trong tập tin widgets.config.ts, chỉ cần chạy 1 câu lệnh để tự động cập nhật toàn bộ:

npx react-native-live-widgets codegen
JSX / TSX

Cú pháp JSX / TSX & UI.StyleSheet

Bạn có thể viết giao diện Widget theo 2 phong cách tương đương 100%: thẻ JSX tự nhiên (<VStack>, <HStack>, <Text>...) với style / mảng conditional style, hoặc bộ hàm UI.* kết hợp UI.StyleSheet.create(...). Cả Widget.setLayout() và LiveActivity.start() tự động biên dịch JSX sang JSON AST gốc.

Phong cách 1: JSX Components & StyleSheet

Hỗ trợ <VStack>, <HStack>, <ZStack>, <Grid>, <Text>, <Button>, <Toggle>, <Switch>, <Checkbox>, <Badge>, <Progress>, <Timer>, <Equalizer>, <Image>, <Gauge>, <Chart>, <Link>, <Spacer>, <Divider>.

import {
  Widget, VStack, HStack, Text, Badge, Button, Spacer, UI
} from 'react-native-live-widgets';

const styles = UI.StyleSheet.create({
  card: { padding: 16, backgroundColor: '#0F172A', borderRadius: 18 },
  title: { fontSize: 15, fontWeight: 'bold', color: '#FFFFFF' },
});

await Widget.setLayout('main', {
  medium: (
    <VStack style={styles.card} spacing={8}>
      <HStack alignment="center">
        <Text style={styles.title}>Ca Làm Việc Hôm Nay</Text>
        <Spacer />
        <Badge text="08:00 - 17:30" backgroundColor="#064E3B" textColor="#6EE7B7" />
      </HStack>
      <Text fontSize={13} color="#94A3B8">Văn phòng Fastdo Đà Nẵng</Text>
      <Button
        title="⚡ Check-in Ngay"
        actionId="FASTDO_CHECKIN"
        backgroundColor="#0284C7"
        textColor="#FFFFFF"
        fullWidth
      />
    </VStack>
  ),
});

Phong cách 2: Functional DSL & Conditional Styles

Viết thuần TypeScript với UI.* và truyền mảng style có điều kiện tương tự React Native StyleSheet ([styles.base, isAlert && styles.alert]). Tương thích mọi bundler không dùng JSX transform.

import { UI, Widget } from 'react-native-live-widgets';

const styles = UI.StyleSheet.create({
  card: { padding: 14, backgroundColor: '#111827', borderRadius: 16, spacing: 6 },
  label: { fontSize: 13, fontWeight: 'medium', color: '#E2E8F0' },
  errorText: { color: '#F87171', fontWeight: 'bold' },
});

const isLate = true;

await Widget.setLayout('shift', {
  medium: UI.VStack(
    styles.card,
    UI.Text('TIÊU ĐỀ BÁO CÁO', { typography: 'caption1', color: '#94A3B8' }),
    UI.Text('Trạng thái ca làm', [styles.label, isLate && styles.errorText])
  ),
});

Mô phỏng trực tiếp trong App: <WidgetPreview> (alias <VoltraWidgetPreview>)

Multi-page & Timer Preview

Nhúng thẳng giao diện Widget vào màn hình React Native để xem trước chính xác tỉ lệ chuẩn iOS/Android, tự động chuyển đổi trang (page:*), bật/tắt công tắc toggle:*, và chạy đồng hồ đếm ngược PreviewTimerText 1 giây/lần trước khi ghim ra màn hình chính.

Prop Kiểu Mô tả
size 'small' | 'medium' | 'large' | 'extraLarge' | 'standBy' | 'lockScreen' | 'dynamicIsland' | 'control' Kích thước khung xem trước (mặc định 'medium' 338×158dp). Hỗ trợ StandBy, ExtraLarge & Control Tile (170×76dp).
layout / controlConfig / children LayoutNode | WidgetSinglePageConfig | ControlWidgetConfig | ReactNode Nhận cây JSON DSL, object đa kích cỡ, cấu hình ControlWidget (kèm size="control"), hoặc thẻ JSX lồng trực tiếp.
showBadge boolean (true) Hiển thị nhãn kích thước chuẩn ở góc trên.
interactiveSizeSwitch boolean (false) Hiển thị thanh chuyển nhanh giữa Small / Medium / Large / Lock Screen.
onAction (actionId: string) => void Nhận sự kiện khi bấm nút hoặc toggle bên trong khung xem trước.
import React from 'react';
import { View } from 'react-native';
import { WidgetPreview, VStack, HStack, Text, Badge, Button } from 'react-native-live-widgets';

export default function PreviewScreen() {
  return (
    <View style={{ flex: 1, padding: 16 }}>
      <WidgetPreview
        size="medium"
        showBadge
        interactiveSizeSwitch
        onAction={(actionId) => console.log('Action clicked in preview:', actionId)}
      >
        <VStack padding={16} backgroundColor="#0F172A" borderRadius={18} spacing={8}>
          <HStack justifyContent="spaceBetween" alignment="center">
            <Text fontSize={15} fontWeight="bold" color="#FFFFFF">Ca Làm Việc Hôm Nay</Text>
            <Badge text="08:00 - 17:30" backgroundColor="#064E3B" textColor="#6EE7B7" />
          </HStack>
          <Text fontSize={13} color="#94A3B8">Vị trí: Văn phòng Fastdo Đà Nẵng</Text>
          <Button
            title="⚡ Check-in Ngay"
            actionId="FASTDO_CHECKIN"
            backgroundColor="#0284C7"
            textColor="#FFFFFF"
          />
        </VStack>
      </WidgetPreview>
    </View>
  );
}
v1.2.2 Mới

Vùng Bấm Động Từng Pixel, Chronometer & Swift 6 Ready

Bản phát hành v1.2.2 tái cấu trúc toàn diện hệ thống tương tác cảm ứng trên Android Home Screen Widgets, tích hợp đồng hồ đếm ngược phần cứng native và tương thích hoàn toàn Swift 6 Language Mode trên Xcode mới.

1. Exact Dynamic Hit Layer (rn_hit_layer)

Thay thế hoàn toàn lưới cố định cũ bằng FrameLayout động (rn_live_widget_hit_zone.xml). Giải thuật computeCanvasMapping ánh xạ chính xác toạ độ từ Bitmap Canvas sang khung Launcher thật (xử lý bù viền fitCenter letterboxing). Bấm vào nút/checkbox nào ăn đúng 100% nút đó, vùng trống hoàn toàn không kích hoạt nhầm.

2. Native Chronometer Countdown (Android)

Tích hợp trực tiếp android.widget.Chronometer với setChronometerCountDown(true) và baseMillis = SystemClock.elapsedRealtime() + remainingMillis. Khi có timer đếm ngược, hệ thống ẩn text tĩnh trên Bitmap để đồng hồ native tự chạy giật lùi 1s/lần mà không phải vẽ lại ảnh Canvas.

3. Nội suy Biến động & defaultChecked Store

DynamicWidgetStateStore hỗ trợ nội suy chuỗi mẫu {{id}}, {{title}}, giá trị bộ đếm phẳng và tự động lưu trạng thái khởi tạo defaultChecked của công tắc checked: true ngay lần render đầu, giúp tắt công tắc mượt mà ngay lần chạm đầu tiên.

4. Tương thích Swift 6 Language Mode (iOS)

Khắc phục lỗi biên dịch type '()' cannot conform to 'View' trên Xcode mới bằng cách đóng gói closure cho Font trong renderText(), tách logic accessibility sang hàm thuần buildAccessibilityView(content:) -> AnyView, và bổ sung EmptyView() cho các nhánh ContainerStyleModifier.

Declarative UI Engine Catalog (JSX & UI.*)

Toàn bộ hệ sinh thái component khai báo có TypeScript autocompletion đầy đủ và ánh xạ tương đương sang SwiftUI (iOS) & 2D Canvas / RemoteViews (Android).

Bố cục: VStack, HStack, ZStack, Grid, Spacer & Divider

ContainerProps

Hỗ trợ xếp dọc (VStack), xếp ngang (HStack), xếp chồng lớp (ZStack), chia lưới nhiều cột đều nhau (Grid), khoảng trống co giãn (Spacer) và đường kẻ phân cách (Divider). Hỗ trợ các thuộc tính: padding, paddingHorizontal, paddingVertical, spacing (alias gap), alignment, justifyContent, backgroundColor, gradient, borderRadius (alias cornerRadius), borderWidth, borderColor, borderStyle.

UI.VStack(
  { padding: 14, backgroundColor: '#1A1D24', borderRadius: 16, spacing: 10 },
  // 1. ZStack: Xếp chồng chấm trạng thái lên góc phải dưới Avatar
  UI.HStack(
    { spacing: 10, alignment: 'center' },
    UI.ZStack(
      { zAlignment: 'bottomTrailing' },
      UI.Image({ url: 'https://example.com/avatar.jpg', width: 44, height: 44, borderRadius: 22 }),
      UI.Badge('●', { backgroundColor: '#10B981', textColor: '#FFFFFF', fontSize: 8 })
    ),
    UI.VStack(
      { spacing: 2 },
      UI.Text('Nguyễn Văn A', { fontWeight: 'bold', color: '#FFFFFF' }),
      UI.Text('Đang trực tuyến', { fontSize: 11, color: '#94A3B8' })
    ),
    UI.Spacer()
  ),
  UI.Divider({ color: '#334155', thickness: 1, marginVertical: 2 }),
  // 2. Grid: Chia lưới 2 cột đều nhau cho bảng chỉ số KPI
  UI.Grid(
    { columns: 2, columnSpacing: 8, rowSpacing: 8 },
    UI.VStack(
      { padding: 8, backgroundColor: '#1E293B', borderRadius: 8 },
      UI.Text('Doanh thu', { fontSize: 10, color: '#94A3B8' }),
      UI.Text('4.85 Tỷ', { fontSize: 14, fontWeight: 'bold', color: '#FFFFFF' })
    ),
    UI.VStack(
      { padding: 8, backgroundColor: '#1E293B', borderRadius: 8 },
      UI.Text('Đơn hàng', { fontSize: 10, color: '#94A3B8' }),
      UI.Text('1,420', { fontSize: 14, fontWeight: 'bold', color: '#34D399' })
    )
  )
)

Văn bản & Nhãn: UI.Text, UI.Badge & Nội suy {{field}}

TextStyle

UI.Text tự động thay thế biến động {{checkinTime}}, {{id}}, {{title}}, {{_lastSyncTime}} từ API ngầm/State Store, hỗ trợ typography chuẩn Apple HIG/Material (largeTitle → caption2), fontDesign (monospaced, rounded, serif), numericAnimation (cuộn số iOS 16+), strikethroughWhenToggled, và privacySensitive / redacted.

UI.HStack(
  { justifyContent: 'spaceBetween', alignment: 'center' },
  UI.Text('Mã #{{id}} • Check-in {{checkinTime}}', {
    color: { light: '#0F172A', dark: '#F8FAFC', tinted: '#38BDF8' },
    typography: 'subheadline',
    fontDesign: 'monospaced',
    numberOfLines: 1,
    strikethroughWhenToggled: 'task_1',
    privacySensitive: true,
  }),
  UI.Badge('+18% KPI', {
    systemName: 'arrow.up.right',
    backgroundColor: '#064E3B',
    textColor: '#34D399',
    fontSize: 10,
    borderRadius: 999,
  })
)

Hình ảnh & Biểu tượng Hệ thống: UI.Image & <Image>

Auto-Cache 360px 13,000+ Icons

Hỗ trợ 5 nguồn ảnh: url (tự tải ngầm, nén tối đa 360px tránh vượt ngưỡng 30MB WidgetKit và lưu vào App Group cache), base64 (QR/Barcode), systemName, assetName, và filePath. Đặc biệt hỗ trợ icon hệ thống đa nền tảng chuyên biệt: systemNameIos (Apple SF Symbols) và systemNameAndroid (Google Material Icons) với gợi ý type IntelliSense đầy đủ.

// 1. Ảnh Avatar từ URL mạng có viền & icon dự phòng
UI.Image({
  url: 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=300&q=80',
  fallbackSystemName: 'person.crop.circle.fill',
  width: 44,
  height: 44,
  cornerRadius: 999,
  contentMode: 'fill',
  borderColor: '#60A5FA',
  borderWidth: 2,
})

// 2. Icon hệ thống đa nền tảng (Apple SF Symbols + Google Material Icons)
UI.Image({
  systemNameIos: 'bolt.horizontal.fill', // 9,500+ Apple SF Symbols
  systemNameAndroid: 'bolt',              // 3,800+ Google Material Icons
  tintColor: '#10B981',
  width: 24,
  height: 24,
})

// 3. Hoặc sử dụng dạng JSX React Component:
<Image
  systemNameIos="person.crop.circle.badge.checkmark"
  systemNameAndroid="verified_user"
  tintColor="#10B981"
  width={24}
  height={24}
/>
UI.Timer — Đếm giờ Phần cứng 0% CPU

Nhận targetTimestamp (epoch giây), tự đếm lùi (countdown) bằng SwiftUI timer trên iOS và native android.widget.Chronometer trên Android:

const targetSec = Math.floor(Date.now() / 1000) + 25 * 60;

UI.Timer(targetSec, {
  mode: 'countdown', // 'countdown' | 'countup'
  color: '#38BDF8',
  fontSize: 28,
  fontWeight: 'bold',
  prefix: 'Còn ',
  suffix: ' phút',
})
UI.Equalizer — Sóng nhạc liên tục Realtime

Hiển thị sóng âm thanh chuyển động cho audio/podcast qua phase hoặc mảng biên độ levels (0..1):

UI.Equalizer({
  isPlaying: true,
  barCount: 5,
  tintColor: '#A855F7',
  height: 20,
  barWidth: 3,
  spacing: 2,
  phase: 1, // Hoặc levels: [0.3, 0.8, 0.5, 0.9, 0.4]
})
UI.Progress — Bar, Segmented & Circular + Tracker & Smart Warning ProgressStyle

Hỗ trợ 3 kiểu dáng ('bar', 'segmented', 'circular'), tự chạy theo startTimestamp/targetTimestamp, đổi màu cảnh báo khi sắp hết hạn (warningSeconds, warningTintColor), và gắn icon di chuyển theo đầu thanh (trackerSystemName).

// 1. Thanh chia 4 chặng (Segmented) cho giao hàng / ca làm
UI.Progress({
  style: 'segmented',
  segments: 4,
  currentSegment: 3,
  segmentSpacing: 6,
  tintColor: '#10B981',
  trackColor: '#374151',
  height: 8,
})

// 2. Vòng tròn tiến độ kèm cảnh báo đổi màu
UI.Progress({
  style: 'circular',
  value: 0.75,
  tintColor: '#38BDF8',
  trackColor: '#1E293B',
  height: 56,
  showPercentage: true,
})

Đồ họa Số liệu: UI.Gauge (240°) & UI.Chart (Bar / Sparkline)

Canvas Sub-renderer

UI.Gauge vẽ đồng hồ cung tròn 240° hiển thị KPI/chỉ số sức khỏe; UI.Chart vẽ biểu đồ cột ('bar') hoặc đường xu hướng Sparkline ('line'). Trên Android, chỉ phần hộp bao đồ họa được vẽ thành Sub-Bitmap nhỏ (~40KB RAM) để không chạm trần Binder IPC.

// 1. Đồng hồ đo KPI cung tròn 240°
UI.Gauge(0.86, {
  size: 66,
  strokeWidth: 7,
  tintColor: '#38BDF8',
  trackColor: '#1E293B',
  valueText: '86%',
  label: 'KPI Quý',
})

// 2. Biểu đồ Cột / Đường xu hướng 7 ngày
UI.Chart([42, 58, 51, 74, 68, 92, 108], {
  style: 'line', // 'bar' | 'line'
  labels: ['T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'CN'],
  tintColor: '#38BDF8',
  secondaryColor: '#1E3A8A',
  height: 52,
  showDots: true,
})

Tương tác: UI.Button, UI.Toggle (<Switch>/<Checkbox>) & UI.Link

AppIntents + Exact Hit Layer

Thư viện hỗ trợ các tiền tố actionId xử lý tự động ngay ở tầng Native mà không cần mở App: page:<id> / page:next / page:prev (lật trang Widget), toggle:<key> (đảo trạng thái tick/switch và lưu ngay vào DynamicWidgetStateStore), và refresh (kéo lại dữ liệu từ Remote API ngay lập tức).

// 1. Nút chuyển trang hoặc Tick hoàn thành kèm đổi màu
UI.Button({
  title: 'Duyệt PR chấm công',
  checkedTitle: '✓ Đã duyệt PR',
  actionId: 'toggle:task_1',
  backgroundColor: '#F8FAFC',
  checkedBackgroundColor: '#DCFCE7',
  textColor: '#1E293B',
  checkedTextColor: '#15803D',
  fullWidth: true,
})

// 2. Toggle Checkbox hoặc Switch (JSX cũng có thẻ <Checkbox />, <Switch />)
UI.Toggle('Tự động gửi cảnh báo vượt ngưỡng', {
  actionId: 'toggle:auto_alert',
  style: 'switch', // 'checkbox' | 'switch'
  checked: true,
  tintColor: '#10B981',
  strikethroughOnCheck: false,
})

// 3. Link bọc khối giao diện mở Deep Link thẳng vào màn hình trong App
UI.Link(
  { deepLink: 'fastdo://reports/q4', padding: 10, backgroundColor: '#1E293B', borderRadius: 10 },
  UI.Text('Xem chi tiết báo cáo →', { fontSize: 12, fontWeight: 'bold', color: '#38BDF8' })
)

Mở rộng Component Native: UI.Custom & DynamicNodeRegistry

SwiftUI & Kotlin Canvas

Khi cần nhúng đồ họa hoặc View Native đặc thù mà DSL chưa có sẵn, bạn đăng ký custom renderer trong LiveWidgetsBundle.swift (iOS) và MainApplication.kt (Android), rồi gọi qua UI.Custom('WeatherCard', { ... }).

// iOS (LiveWidgetsBundle.swift)
DynamicNodeRegistry.shared.registerView("WeatherCard") { node in
  let city = node.props?["city"]?.stringValue ?? "Hà Nội"
  let temp = node.props?["temp"]?.stringValue ?? "28°C"
  HStack {
    Image(systemName: "sun.max.fill").foregroundColor(.yellow)
    Text("\(city): \(temp)").font(.headline)
  }
}
// Android (MainApplication.onCreate)
DynamicNodeRegistry.register(
  componentName = "WeatherCard",
  heightDp = { 44f },
  drawer = { context, canvas, rect, props, density ->
    // Vẽ tự do lên Android 2D Canvas
  }
)

Styling Modifiers Nâng cao: Gradient, Border Nét Đứt, Shadow, Tinted & RTL

Graceful Fallback

Nếu thiết bị hoặc phiên bản OS không hỗ trợ một hiệu ứng (ví dụ Gradient trên OS cũ), engine tự động hạ cấp an toàn (lấy màu đầu tiên làm nền đơn sắc) để không bao giờ vỡ giao diện.

<VStack
  gradient={{ colors: ['#1E3A8A', '#3B82F6'], startPoint: { x: 0, y: 0 }, endPoint: { x: 1, y: 1 } }}
  borderWidth={1.5}
  borderColor="#38BDF8"
  borderStyle="dashed" // 'solid' | 'dashed' | 'dotted'
  borderRadius={14}
  shadowColor="#2563EB"
  shadowRadius={6}
  shadowOpacity={0.35}
  shadowOffset={{ x: 0, y: 3 }}
  direction="ltr" // Hỗ trợ 'rtl' (isRTL: true)
  padding={16}
>
  <Text color={{ light: '#0F172A', dark: '#F8FAFC', tinted: '#38BDF8' }} typography="headline">
    Tự động đổi màu theo Light / Dark / iOS 18 Tinted Mode
  </Text>
</VStack>

Core API Reference

Chi tiết toàn bộ API điều khiển LiveActivity, Widget, React Hooks, SharedStorage, Remote API Sync và Push Notifications.

1. LiveActivity API & Dynamic Island (iOS 16.1+ & Android 16)

ActivityKit + ProgressStyle
Hàm Tham số Mô tả
LiveActivity.start(options) StartActivityOptions Bắt đầu Live Activity (iOS Lock Screen + Dynamic Island) hoặc Promoted Live Update Notification (Android).
LiveActivity.update(options) UpdateActivityOptions Cập nhật layout, Dynamic Island, tiến trình hoặc pha theo activityId.
LiveActivity.end(id, options?) id, EndActivityOptions Kết thúc Live Activity (chính sách đóng dismissalPolicy, hiển thị trạng thái cuối trước khi ẩn).
LiveActivity.endAll() none Đóng toàn bộ các Live Activities đang hoạt động.
LiveActivity.getActiveActivities() / get(id) / isActive(id) id?: string Quản lý nhiều phiên đồng thời: trả về activityId, systemActivityId, isStale, relevanceScore, scheduledEndTimestamp, pushToken.
LiveActivity.onStateChange(listener) / cleanupExpired() LiveActivityStateEvent Lắng nghe chuyển đổi vòng đời (active, started_by_push, stale, expired, ended, dismissed) và tự động dọn dẹp phiên hết hạn.
LiveActivity.areActivitiesEnabled() / canPostPromoted() Promise<boolean> Kiểm tra quyền hiển thị Live Activity (iOS) / Promoted Notification (Android 16).
LiveActivity.registerBackgroundActionHandler(cb?) HeadlessJs (Android) Đăng ký trong index.js để xử lý sự kiện nút bấm ngay cả khi App Android đã bị tắt.
// Cấu hình Dynamic Island + Stale UI + RelevanceScore + Auto Scheduled End
await LiveActivity.start({
  activityId: 'shift_01',
  lockScreen: lockScreenCardNode,
  staleLockScreen: staleFallbackNode,
  staleTimestamp: shiftEndSec - 120,
  scheduledEndTimestamp: shiftEndSec,
  expiredLockScreen: completedSummaryNode,
  expiredDismissalPolicy: 'default',
  relevanceScore: 95,
  alertConfig: { title: 'Bắt đầu ca làm', body: 'Ca hành chính đã kích hoạt!', sound: 'default' },
  dynamicIsland: {
    compactLeading: UI.HStack({ spacing: 4 }, avatarImg, UI.Text('08:02', { fontSize: 12, color: '#60A5FA' })),
    compactTrailing: UI.Timer(shiftEndSec, { mode: 'countdown', fontSize: 12, color: '#60A5FA' }),
    minimal: UI.Image({ systemName: 'clock.fill', tintColor: '#60A5FA', width: 14, height: 14 }),
    expanded: {
      leading: UI.Text('ĐANG TRONG CA', { color: '#60A5FA', fontSize: 12, fontWeight: 'bold' }),
      trailing: UI.Timer(shiftEndSec, { mode: 'countdown', color: '#FFFFFF', fontSize: 14 }),
      bottom: UI.Progress({ style: 'segmented', segments: 4, value: 0.75, tintColor: '#3B82F6', height: 6 }),
    },
  },
  phases: [
    { id: 'warning', triggerTimestamp: shiftEndSec - 300, alertTitle: 'Sắp hết ca!', alertBody: 'Còn 5 phút nữa.' },
  ],
});

2. Widget API (Multi-Page, ExtraLarge, StandBy & Control Center)

WidgetKit + ControlWidget
Hàm Tham số Mô tả
Widget.setLayout(key, config, appGroup?) WidgetLayoutConfig (alias Widget.update) Cập nhật giao diện cho small, medium, large, extraLarge, standBy, pages đa trang và 3 kích thước Lock Screen iOS (accessoryRectangular, accessoryCircular, accessoryInline).
ControlWidget.set(id, cfg) / Widget.setControl(id, cfg) UI.ControlButton / UI.ControlToggle Cấu hình nút/công tắc nhanh trong iOS 18 Control Center, Action Button & Lock Screen (DynamicControlWidget.swift) và Android Quick Settings Tile (DynamicQuickSettingsTileService.kt). Hỗ trợ xem trước với <WidgetPreview size="control" />.
Widget.reload(kind) / Widget.reloadAll() kind: string Yêu cầu OS vẽ lại timeline / giao diện widget ngay lập tức.
Widget.isPinSupported() / requestPin() Android 8.0+ Mở hộp thoại hệ thống cho người dùng ghim Widget ra Home Screen ngay trong App.
Widget.getCapabilities() Promise<WidgetCapabilities> Kiểm tra thiết bị có hỗ trợ Dynamic Island, iOS 18 Tinted Mode, Interactive Intents...
Widget.inspectIR(layout) / compileIR(layout) LayoutNode | SinglePageConfig Phân tích cây UI Intermediate Representation, kế hoạch Native vs Canvas và tóm tắt TalkBack/VoiceOver.
// Widget đa trang (Pages) + Lock Screen iOS 16+ + Ghim nhanh Android
await Widget.setLayout('main', {
  initialPage: 'overview',
  pages: {
    overview: { small: overviewSmall, medium: overviewMedium, large: overviewLarge },
    tasks: { small: tasksSmall, medium: tasksMedium, large: tasksLarge },
  },
  accessoryRectangular: UI.Text('★ Công việc hôm nay: 3/5', { fontSize: 12, fontWeight: 'bold' }),
  accessoryCircular: UI.Gauge(0.6, { size: 44, valueText: '60%' }),
  accessoryInline: UI.Text('♪ Đang trong ca • 08:00 - 17:30'),
});

if (await Widget.isPinSupported()) {
  await Widget.requestPin();
}

3. React Hooks (Fast Refresh Resilient) & SharedStorage

Hooks & App Group

Các Hook tự động dọn dẹp listener khi unmount và đồng bộ 2 chiều qua App Group (iOS) / SharedPreferences (Android). Với các nghiệp vụ quan trọng (như Chấm công) khi App bị người dùng Force-Kill, hãy dùng mô hình Offline-First State Queue qua SharedStorage.

import {
  useWidgetAction, useLiveActivity, useWidgetState, SharedStorage
} from 'react-native-live-widgets';

// 1. Lắng nghe bấm nút từ Widget / Dynamic Island (an toàn với Fast Refresh)
useWidgetAction('INCREMENT', (actionId, payload) => {
  console.log('Clicked:', actionId, payload);
});

// 2. Quản lý vòng đời Live Activity bằng Hook
const { activityId, isActive, start, update, end } = useLiveActivity();

// 3. State đồng bộ 2 chiều với Native Store
const [counter, setCounter, resetCounter] = useWidgetState('widget_counter', 0);

// 4. Đọc / ghi trực tiếp vào App Group / SharedPreferences
await SharedStorage.set('pending_checkin', { timestamp: Date.now() }, 'group.com.yourapp');
const saved = await SharedStorage.get('pending_checkin', 'group.com.yourapp');

4. Background Data Engine 2.0 & Structured Data Binding

URLSession & AlarmManager

Hỗ trợ đầy đủ REST (GET/POST/PUT + body), headers, timeoutMs, cacheTtlSeconds, enableETag (gửi If-None-Match & xử lý HTTP 304 Not Modified), maxRetries / retryDelayMs (Exponential Backoff), đa nguồn sources, chuẩn hóa mapping & Pipe Transform, kiểm định schema, tự làm mới token authRefresh khi gặp HTTP 401, biến lỗi {{_syncStatus}} / {{_syncError}} / {{_httpStatus}} + errorFallback và Proxy gợi ý kiểu Widget.createDataBinding<T>().

⚠️ Lưu ý bắt buộc về Ngân sách Reload của OS: Không cam kết đồng bộ chính xác mỗi 15 phút khi app bị đóng. Apple WidgetKit sử dụng ngân sách reload động (thường khoảng 40–70 lần/ngày tùy hành vi người dùng; refreshIntervalMinutes chỉ là mốc thời gian sớm nhất được đề xuất). Android cũng áp dụng giới hạn Doze Mode & App Standby Buckets cho tác vụ nền.
// 1. Structured Data Binding + Pipe Transform trực tiếp trong TSX
const data = Widget.createDataBinding<{
  user: { name: string };
  attendance: { progress: number };
}>({
  defaults: { user: { name: 'Nhân viên' }, attendance: { progress: 0 } },
});

await Widget.setLayout('main', {
  medium: (
    <VStack padding={14} spacing={6}>
      <Text>{data.user.name}</Text>
      <Text>{data.attendance.progress}%</Text>
      <Progress value={data.attendance.progress.divide(100)} />
    </VStack>
  ),
});

// 2. Cấu hình Background Data Engine 2.0 (TTL, ETag, Retry, Multi-source, Schema, Auth Refresh)
await Widget.setRemoteConfig('main', {
  cacheTtlSeconds: 300,
  timeoutMs: 6000,
  enableETag: true,
  maxRetries: 2,
  retryDelayMs: 500,
  sources: {
    user: { url: 'https://api.yourcompany.com/v1/me' },
    attendance: { url: 'https://api.yourcompany.com/v1/attendance/today' },
  },
  schema: {
    requiredKeys: ['user.name', 'attendance.progress'],
    types: { 'attendance.progress': 'number' },
  },
  authRefresh: {
    url: 'https://api.yourcompany.com/v1/auth/refresh',
    method: 'POST',
    tokenPath: 'accessToken',
  },
  errorFallback: <Text color="#F87171">Lỗi {{_httpStatus}}: {{_syncError}}</Text>,
  refreshIntervalMinutes: 15, // Mốc gợi ý sớm nhất theo OS WidgetKit Budget
}, 'group.com.yourcompany.app');

5. Quản lý 3 loại Push Token & Payload Server (APNs / FCM)

Server Push

Hỗ trợ lấy và theo dõi xoay token tự động cho cả 3 loại: devicePushToken (APNs/FCM thường), pushToStartToken (iOS 17.2+ bật mới Live Activity từ xa khi App đang tắt), và activityUpdateToken (đẩy bản cập nhật/kết thúc phiên đang chạy).

// Lấy toàn bộ token & lắng nghe cập nhật từ Native
const tokens = await LiveActivity.getAllPushTokens();
console.log(tokens.devicePushToken, tokens.pushToStartToken);

LiveActivity.onPushToStartTokenChange((token) => {
  api.syncPushToStartToken(token);
});
LiveActivity.onActivityUpdateTokenChange(({ activityId, token }) => {
  api.syncActivityToken(activityId, token);
});
// Header APNs: apns-push-type: liveactivity | apns-topic: <bundle_id>.push-type.liveactivity
{
  "aps": {
    "timestamp": 1711890000,
    "event": "update",
    "content-state": {
      "layoutJson": "{\"lockScreen\":{...},\"dynamicIsland\":{...}}"
    },
    "alert": { "title": "Đơn hàng đã giao!", "body": "Chúc bạn ngon miệng." }
  }
}
Architecture v2.0

3 Trụ Cột Kiến Trúc & UI Intermediate Representation (IR)

Thay vì đi thẳng từ DSL → Bitmap thiếu ngữ nghĩa, thư viện áp dụng kiến trúc chuẩn công nghiệp với Semantic Tree độc lập khỏi Visual Renderer:

✅ Điểm 1: Native Semantic Coverage

Phù hợp giới hạn whitelist của Android RemoteViews: mọi Text/Button/Toggle quan trọng đều có Semantics; thành phần đồ họa Canvas (Gauge, Chart, Equalizer) sinh kèm Accessibility Description thay thế.

✅ Điểm 2: Native-first, Canvas-when-needed

Chronometer và FrameLayout Hit Layer chạy hoàn toàn bằng Native RemoteViews; Canvas 2D chỉ vẽ các phần thực sự cần vẽ (đồ họa phức tạp, Gauge, Sparkline), giảm RAM và pin.

✅ Điểm 3: Semantic Tree độc lập Renderer (UI IR)

Cây UI IR tách làm 3 phần: Visual Tree, Semantic Tree và State Bindings — dùng API Widget.inspectIR() và Widget.compileIR() để kiểm toán trực tiếp kế hoạch render.

import { Widget, UI } from 'react-native-live-widgets';

const layout = UI.VStack(
  { padding: 16, backgroundColor: '#0F172A' },
  UI.Text('BẢNG ĐIỀU KHIỂN CHẤM CÔNG', { typography: 'title2' }),
  UI.Progress({ value: 0.86, accessibilityLabel: 'Tiến độ hoàn thành ca' }),
  UI.Button({ title: 'Check In', actionId: 'toggle:attendance' }),
  UI.Gauge(0.92, { label: 'Hiệu suất' })
);

// Phân tích chiến lược Native vs Canvas & tóm tắt Trợ năng TalkBack/VoiceOver
console.log(Widget.inspectIR(layout));
const ir = Widget.compileIR(layout);
console.log(ir.renderStrategy, ir.semanticSummary);

Lớp Trợ năng Chuẩn hóa (VoiceOver iOS & TalkBack Android)

Mọi node hỗ trợ đầy đủ AccessibilityProps: accessible, accessibilityRole ('header' | 'button' | 'progressbar' | 'checkbox' | 'switch' | 'image' | 'summary'), accessibilityLabel, accessibilityHint, và accessibilityValue. Trên Android, engine tự động duyệt đệ quy để gán tóm tắt vào contentDescription của Canvas và từng Hit Zone.

<VStack padding={16}>
  <Text typography="title2" accessibilityRole="header" accessibilityLabel="Bảng điều khiển chấm công">
    BẢNG ĐIỀU KHIỂN CHẤM CÔNG
  </Text>
  <Progress value={0.86} accessibilityLabel="Tiến độ hoàn thành ca" accessibilityValue="86 phần trăm" />
  <Button
    title="Check-in vào ca"
    actionId="CHECK_IN"
    accessibilityRole="button"
    accessibilityHint="Chạm hai lần để gửi yêu cầu chấm công"
  />
  <Image systemName="sparkles" accessible={false} />
</VStack>

Bảng Năng lực Nền tảng & Lộ trình Phát triển 6 Phases (v1.2.2 Hoàn thiện 100%)

Tính năng iOS WidgetKit / LA Android Home Widget Graceful Fallback
Vùng bấm tương tác ✅ iOS 17+ AppIntent ✅ Exact Hit Layer (rn_hit_layer) Mở App xử lý queue qua PendingIntent
Đồng hồ đếm ngược ✅ SwiftUI Timer ✅ Native Chronometer Cập nhật theo mốc thời gian hệ điều hành
Gradient & Dashed Border ✅ SwiftUI ✅ Shader & DashPathEffect Hạ cấp về màu đầu tiên trong colors / nét liền
Accessibility & Dynamic Type ✅ Native VoiceOver ✅ A11y Summary + Hit-Zones + fontScale Tổng hợp ngữ nghĩa toàn cây cho bộ đọc màn hình
Phase Nội dung kiến trúc Trạng thái v1.2.2
Phase 1 Accessibility Fallback Layer (AccessibilityProps, TalkBack & VoiceOver) ✅ Hoàn thành
Phase 2 UI Intermediate Representation (src/ir.ts, Widget.inspectIR) ✅ Hoàn thành
Phase 3 & 4 Native-first Hybrid (Chronometer, Exact Hit Layer) & Two-way State Sync ✅ Hoàn thành
Phase 5 & 6 Canvas Sub-renderer (~40KB RAM) & Automated Test Suite (npm test) ✅ Hoàn thành

Widget Family Mở rộng (extraLarge, standBy, ControlWidget) & Vòng đời Live Activity

OS Surfaces & Lifecycle

Hỗ trợ đầy đủ giao diện riêng cho iOS 17+ StandBy Mode (tự nhận diện showsWidgetContainerBackground == false kèm .applyStandByMargins() & widgetAccentable), iPadOS / Tablet Extra Large (extraLarge), iOS 18+ Control Center / Action Button & Android Quick Settings Tile (ControlWidget DSL, DynamicControlWidget.swift, DynamicQuickSettingsTileService.kt, <WidgetPreview size="control" />), và hệ thống vòng đời Live Activity hoàn chỉnh (Stale, Relevance Score, AlertConfiguration, Scheduled End, Auto-Expiration, Push-to-Start & Multi-Activity Inspection).

// 1. Thiết lập StandBy + ExtraLarge + Control Widget (iOS 18+ / Android QS Tile)
await Widget.setLayout('main', {
  small: compactNode,
  medium: mediumNode,
  large: largeNode,
  extraLarge: tabletDashboardNode,
  standBy: standByBigClockNode,
});

const shiftCtrl = ControlWidget.toggle({
  title: 'Ca làm việc',
  subtitle: 'Chạm để chấm công',
  checkedTitle: 'Đang trong ca',
  checkedSubtitle: 'Nhấn để kết thúc',
  systemName: 'clock.badge.checkmark.fill',
  checked: true,
  actionId: 'toggle:attendance',
});
await ControlWidget.set('toggle', shiftCtrl);
// Xem trước Control Tile ngay trong App: <WidgetPreview size="control" controlConfig={shiftCtrl} />

// 2. Theo dõi toàn bộ vòng đời & kiểm tra Live Activity đồng thời
const unsubLifecycle = LiveActivity.onStateChange((event) => {
  console.log(`Activity ${event.activityId} -> ${event.state}`);
});
const active = await LiveActivity.get('shift_01');
const cleanedIds = await LiveActivity.cleanupExpired();

Xử lý Sự cố Thường gặp (Troubleshooting)

  • Widget hiện "Chọn 1 mẫu UI trong app để hiển thị": Kiểm tra App Group ID giữa Main App và Widget Extension đã trùng khớp chưa (vd group.<bundle_id>) và đảm bảo đã gọi await Widget.setLayout('main', ...).
  • Dynamic Island Compact bị tràn chiều ngang khi dùng UI.Timer: Đảm bảo đặt fontSize gọn (11–13) cho compactTrailing; thư viện đã tự tính độ rộng compactWidth tối ưu theo thời lượng còn lại.
  • Ảnh từ URL mạng (https://...) không hiện trên Widget: Đảm bảo URL là HTTPS hợp lệ; thư viện tự tải ngầm, nén xuống 360px để không vượt giới hạn 30MB của WidgetKit và reload lại Widget khi tải xong.
  • Lỗi build Swift 6 type '()' cannot conform to 'View' trên Xcode mới: Cập nhật lên phiên bản 1.2.2 trở lên (npm install react-native-live-widgets@latest).

AI Agent & LLMs Hub

Chuẩn hóa cho Claude Code, Antigravity, ChatGPT, Cursor Rules

llms.txt Standard

Tài liệu của thư viện tuân thủ 100% đặc tả llms.txt. Bất kỳ mô hình ngôn ngữ lớn hoặc coding agent nào cũng có thể đọc trực tiếp các file này qua URL để sinh mã widget chính xác, an toàn và không bị hallucination.

Tập tin llms.txt & llms-full.txt

Tóm tắt xúc tích về toàn bộ API, UI IR, cấu trúc JSON AST và quy tắc vàng giúp AI lập trình widget chính xác trên v1.2.2.

# Nạp trực tiếp vào Prompt của Agent
curl -s https://react-native-vu.github.io/react-native-live-widgets/llms.txt
curl -s https://react-native-vu.github.io/react-native-live-widgets/llms-full.txt
Agent Skill (SKILL.md) GitHub SKILL.md ↗

Tương thích trực tiếp với các framework Agent như Antigravity, Claude Code, Cursor Rules để kích hoạt theo ngữ cảnh của lập trình viên.

# Lưu vào thư mục agent trong repo của bạn:
.agents/skills/react-native-live-widgets/SKILL.md