---
title: "ペイウォールにインタラクティブな体重目標チャートを表示する"
description: "ペイウォールフローで各ユーザーの予測体重をチャートとして表示します。ユーザーはチャート上をドラッグして任意の週の体重を確認できます。"
---

> **AI agents**: to search Adapty docs faster and with fewer tokens, install the Adapty skills: `npx adapty skills install --yes`

レシピに従って、ペイウォールフローでユーザーの予測体重をチャートとして表示しましょう。ユーザーはオンボーディングフローで現在の体重と目標体重を入力します。アプリは両方の値を収集します。チャートは、アプリを使用することでユーザーが期待できる週ごとの進捗を、現在値から目標値まで表示します。アプリはチャートを[カスタム要素](flow-custom-elements)のネイティブビューとしてレンダリングします。iOS では Swift Charts を使用し、Android ではチャートライブラリなしで直接描画します。

## 始める前に \{#before-you-start\}

- Adapty React Native SDK 4.4 以降にアプリを更新してください。それより古いバージョンの SDK では、すべてのカスタム要素に[フォールバックコンテンツ](flow-custom-elements#set-fallback-content)が表示されます。
- アプリでフローを[取得](react-native-get-pb-paywalls)および[表示](react-native-present-paywalls)できるよう設定してください。
- [React Native ガイド](react-native-flow-custom-elements#before-you-start)に従い、カスタム要素用にアプリのネイティブコードをセットアップしてください。
- iOS では、チャート上のドラッグ操作に iOS 17 以降が必要です。iOS 16 では線は表示されますが、ドラッグ操作はできません。
- Android では、アプリモジュールに [Jetpack Compose をセットアップ](react-native-flow-custom-elements#set-up-jetpack-compose)してください。このレシピのチャートはコンポーザブルです。`androidx.compose.foundation:foundation` から Gradle を使ってアプリに Compose Foundation を追加してください。

2つの別々のフローを作成します。1つはオンボーディング用、もう1つはペイウォール用です。それぞれを[プレースメント](placements)に追加してください。このレシピのコードは、ID `weight_paywall` のプレースメントからペイウォールフローを取得します。

## 1. オンボーディングフローで現在の体重と目標体重を入力してもらう \{#1-ask-for-the-current-and-goal-weight-in-the-onboarding-flow\}

フロー & ペイウォールビルダーで、オンボーディングフローに2つの[**Number** 入力](builder-inputs-and-forms)を追加してください：

- 現在の体重（キログラム）用（**Element ID** は `weight`）
- 目標体重（キログラム）用（**Element ID** は `goal_weight`）

すべてのロケールで体重を同じように読み取れるようにするには、両方の入力の **Format** ドロップダウンから **Integer** を選択してください。入力はユーザーが入力した通りのテキストとして値をアプリに送信します。このレシピのコードでは "70.5" と "70,5" は異なる値として扱われます。整数には小数点区切り文字がありません。

アプリが両方の値を確実に受け取れるようにするには、オンボーディングフローの最後に入力のない画面を配置してください。その画面に [**Close flow**](onboarding-actions#close-flow) アクションを持つボタンを追加します。入力はフォーカスが外れたとき、またはユーザーが別の画面に移動したときに値を送信します。

## 2. ペイウォール画面にカスタム要素を追加する \{#2-add-the-custom-element-to-the-paywall-screen\}

ペイウォールフローで、画面に[カスタム要素を追加](flow-custom-elements#add-and-configure)して、チャート用に設定します：

- **Type**: `line_chart`
- **ID**: `weight_goal`
- **Height**: デフォルトの **Fixed** 高さを維持します。チャートはカスタム要素全体に広がります。

カスタム要素は、カルーセルなどのタッチに反応するコンテナの外に配置してください。これにより、ドラッグ操作にはチャートのみが反応します。

カスタム要素の内部に、サンプルの体重チャートを含む[**Image**](custom-media#image)を追加します。お使いのアプリのバージョンがチャートを表示できない場合、ユーザーにはこれが[フォールバック](flow-custom-elements#set-fallback-content)として表示されます。

## 3. アプリに現在の体重と目標体重を保存する \{#3-save-the-current-and-goal-weight-in-your-app\}

オンボーディングフローの `flow_user_input` イベントから現在の体重と目標体重を収集します。方法は[フローからのデータ処理](react-native-flow-input)を参照してください。ユーザーが最後の画面に到達したことを確認するには、`is_last_screen` が `true` に設定された `flow_screen_showed` イベントを監視します。その画面の後にオンボーディングフローが閉じたら、両方の体重を `showWeightPaywall`（[チャート付きのペイウォールフローを開く](#6-send-the-weights-from-your-javascript-code)関数）に渡します。

以下の関数は、オンボーディングフローの `onAnalytics` ハンドラーと `onDisappeared` ハンドラーを返します。

```typescript showLineNumbers title="weightOnboardingHandlers.ts"

// the event handlers of the onboarding flow view
export function weightOnboardingHandlers(): Partial<FlowEventHandlers> {
  const enteredWeights: Record<string, string> = {};
  let reachedLastScreen = false;

  return {
    onAnalytics(name, params) {
      if (name === 'flow_screen_showed' && params.is_last_screen === true) {
        reachedLastScreen = true;
      } else if (
        name === 'flow_user_input' &&
        typeof params.element_id === 'string' &&
        typeof params.value === 'string'
      ) {
        enteredWeights[params.element_id] = params.value;
      }
      return false; // keep the flow open
    },
    onDisappeared() {
      // number inputs send their values as strings
      const currentWeight = Number.parseFloat(enteredWeights.weight ?? '');
      const goalWeight = Number.parseFloat(enteredWeights.goal_weight ?? '');
      if (reachedLastScreen && !Number.isNaN(currentWeight) && !Number.isNaN(goalWeight)) {
        showWeightPaywall(currentWeight, goalWeight);
      }
      return false;
    },
  };
}
```

オンボーディングフローを表示する前に、そのビューにハンドラーを渡してください：

```typescript showLineNumbers title="React Native"
const view = await createFlowView(flow);
view.setEventHandlers(weightOnboardingHandlers());
await view.present();
```

アプリがすでにオンボーディングフローに `onAnalytics` または `onDisappeared` を設定している場合は、`weightOnboardingHandlers` のコードを既存のハンドラーに追加してください。`setEventHandlers` に渡した各ハンドラーは、同じ名前の以前のハンドラーを上書きします。

## 4. チャートビューを作成する \{#create-the-chart-view\}

体重プランのモデルと、チャートを含むビューを作成します。このプランは現在の体重から目標体重まで、1週間ごとのエントリーを持ちます。ユーザーがチャート上をドラッグすると、タッチ位置の週がマークされ、その週の予測体重が表示されます：

<Tabs groupId="platform" queryString>
<TabItem value="ios" label="iOS (Swift)" default>

```swift showLineNumbers title="Swift"

struct WeightPlan {
    let entries: [WeightEntry]

    // One entry per week, from the current weight to the goal weight
    init(currentWeight: Double, goalWeight: Double) {
        let weeklyChange = 0.5 // kg per week
        let startDate = Date.now
        let weeks = Int((abs(goalWeight - currentWeight) / weeklyChange).rounded(.up))
        let step = goalWeight < currentWeight ? -weeklyChange : weeklyChange
        entries = (0...weeks).map { week in
            WeightEntry(
                date: startDate.addingTimeInterval(Double(week) * 7 * 24 * 60 * 60),
                kilograms: week == weeks ? goalWeight : currentWeight + step * Double(week)
            )
        }
    }
}

struct WeightEntry: Identifiable {
    let date: Date
    let kilograms: Double
    var id: Date { date }
}

@available(iOS 16.0, *) // Swift Charts needs iOS 16
struct WeightGoalChart: View {
    let entries: [WeightEntry]
    @State private var selectedDate: Date?

    // The entry closest to the date that the user drags to
    private var selectedEntry: WeightEntry? {
        guard let selectedDate else { return nil }
        return entries.min {
            abs($0.date.timeIntervalSince(selectedDate)) < abs($1.date.timeIntervalSince(selectedDate))
        }
    }

    var body: some View {
        if #available(iOS 17.0, *) {
            chart.chartXSelection(value: $selectedDate)
        } else {
            chart // iOS 16: no drag selection
        }
    }

    private var chart: some View {
        Chart {
            ForEach(entries) { entry in
                LineMark(
                    x: .value("Date", entry.date),
                    y: .value("Weight", entry.kilograms)
                )
            }
            if let selectedEntry {
                RuleMark(x: .value("Date", selectedEntry.date))
                    .foregroundStyle(.gray.opacity(0.3))
                PointMark(
                    x: .value("Date", selectedEntry.date),
                    y: .value("Weight", selectedEntry.kilograms)
                )
                .annotation(position: .top) {
                    Text("\(selectedEntry.kilograms, specifier: "%.1f") kg")
                        .font(.caption.bold())
                }
            }
        }
        .chartYScale(domain: .automatic(includesZero: false))
    }
}
```

チャートに沿ったドラッグ操作はiOS 17以降が必要です。iOS 16では、ラインは表示されますがドラッグはできません。

</TabItem>
<TabItem value="android" label="Android (Kotlin)">

```kotlin showLineNumbers title="Kotlin"

class WeightPlan(currentWeight: Double, goalWeight: Double) {
    // one entry per week, from the current weight to the goal weight
    val entries: List<WeightEntry> = run {
        val weeklyChange = 0.5 // kg per week
        val start = System.currentTimeMillis()
        val weekMillis = 7L * 24 * 60 * 60 * 1000
        val weeks = ceil(abs(goalWeight - currentWeight) / weeklyChange).toInt()
        val step = if (goalWeight < currentWeight) -weeklyChange else weeklyChange
        (0..weeks).map { week ->
            val kilograms = if (week == weeks) goalWeight else currentWeight + step * week
            WeightEntry(Date(start + week * weekMillis), kilograms)
        }
    }
}

data class WeightEntry(val date: Date, val kilograms: Double)

@Composable
fun WeightGoalChart(entries: List<WeightEntry>) {
    // the week under the finger, or null when the user isn't dragging
    var selectedIndex by remember { mutableStateOf<Int?>(null) }
    val textMeasurer = rememberTextMeasurer()
    val dateFormat = remember { DateFormat.getDateInstance(DateFormat.MEDIUM) }
    val color = Color(0xFFAF52DE)
    val textStyle = TextStyle(color = Color.Gray, fontSize = 12.sp)
    val minKg = entries.minOf { it.kilograms }
    val kgRange = (entries.maxOf { it.kilograms } - minKg).coerceAtLeast(1.0)

    Canvas(
        Modifier
            .fillMaxSize()
            .pointerInput(entries) {
                // horizontal drags select a week; vertical drags scroll the screen
                detectHorizontalDragGestures(
                    onDragEnd = { selectedIndex = null },
                    onDragCancel = { selectedIndex = null },
                ) { change, _ ->
                    val index = (change.position.x / size.width * entries.lastIndex).roundToInt()
                    selectedIndex = index.coerceIn(0, entries.lastIndex)
                }
            }
    ) {
        val startDate = textMeasurer.measure(dateFormat.format(entries.first().date), textStyle)
        val endDate = textMeasurer.measure(dateFormat.format(entries.last().date), textStyle)
        val dateY = size.height - startDate.size.height
        val top = 24.dp.toPx() // room for the projected weight above the line
        val bottom = dateY - 8.dp.toPx()
        fun pointOf(index: Int) = Offset(
            x = size.width * index / entries.lastIndex.coerceAtLeast(1),
            y = bottom - ((entries[index].kilograms - minKg) / kgRange * (bottom - top)).toFloat(),
        )

        // the line from the current weight to the goal weight
        for (index in 1..entries.lastIndex) {
            drawLine(color, pointOf(index - 1), pointOf(index), strokeWidth = 2.dp.toPx())
        }
        // the dates of the first and the last week
        drawText(startDate, topLeft = Offset(0f, dateY))
        drawText(endDate, topLeft = Offset(size.width - endDate.size.width, dateY))

        // the selected week: a point, and the projected weight above it
        selectedIndex?.let { index ->
            val point = pointOf(index)
            drawCircle(color, radius = 5.dp.toPx(), center = point)
            val weight = String.format(Locale.getDefault(), "%.1f kg", entries[index].kilograms)
            val label = textMeasurer.measure(weight, textStyle.copy(color = color))
            val x = (point.x - label.size.width / 2)
                .coerceAtMost(size.width - label.size.width)
                .coerceAtLeast(0f)
            drawText(label, topLeft = Offset(x, point.y - label.size.height - 8.dp.toPx()))
        }
    }
}
```

</TabItem>
</Tabs>

このプランでは、体重が1週間に0.5 kgずつ変化することを前提としています。別の変化率を使用するには、`weeklyChange` を編集してください。

## 5. カスタム要素へのチャートの紐付け \{#match-the-chart-to-the-custom-element\}

[アプリ全体のリゾルバー](react-native-flow-custom-elements#pass-the-resolver-to-the-sdk)に `WeightPlanStore` プロパティを追加します。次に、Type が `line_chart`、ID が `weight_goal` のチャートビューを返します。ハイライトされた行が追加・変更箇所です。アプリにまだアプリ全体の[リゾルバー](react-native-flow-custom-elements#write-a-resolver-to-match-custom-elements-and-views)がない場合は、コード全体をコピーしてください。

<Tabs groupId="platform" queryString>
<TabItem value="ios" label="iOS (Swift)" default>

```swift showLineNumbers title="Swift" {4-8,11,19-23}

// the weight plan that your JavaScript code sends before the paywall flow opens
@MainActor
final class WeightPlanStore {
    var plan: WeightPlan?
}

struct CustomElementsResolver: AdaptyUICustomElementsResolver {
    let weightPlanStore: WeightPlanStore

    func view(
        forType type: String,
        id: String,
        context: AdaptyUICustomElementContext
    ) -> AnyView? {
        switch type {
        case "line_chart" where id == "weight_goal":
            guard #available(iOS 16.0, *), let plan = weightPlanStore.plan else {
                return nil // no weight plan: show the fallback
            }
            return AnyView(WeightGoalChart(entries: plan.entries))
        // the other cases of your resolver
        default:
            return nil
        }
    }
}
```

</TabItem>
<TabItem value="android" label="Android (Kotlin)">

```kotlin showLineNumbers title="Kotlin" {4-7,10,15-22}

// the weight plan that your JavaScript code sends before the paywall flow opens
class WeightPlanStore {
    var plan: WeightPlan? = null
}

class CustomElementsResolver(
    private val weightPlanStore: WeightPlanStore,
) : AdaptyCustomElementsResolver {

    override fun resolve(type: String, id: String): AdaptyCustomElementContent? =
        when (type) {
            "line_chart" -> {
                val plan = weightPlanStore.plan
                if (id == "weight_goal" && plan != null) {
                    AdaptyCustomElementContent.compose { WeightGoalChart(plan.entries) }
                } else {
                    null // no weight plan: show the fallback
                }
            }
            // the other Types of your resolver
            else -> null
        }
}
```

</TabItem>
</Tabs>

JavaScriptコードからネイティブコードにウェイトを送信するまで、リゾルバーはビューを返さず、ユーザーにはフォールバックが表示されます。

## 6. JavaScriptコードからウェイトを送信する \{#6-send-the-weights-from-your-javascript-code\}

アプリ起動時にリゾルバーを設定し、[Turbo Native Module](https://reactnative.dev/docs/turbo-native-modules-introduction)を通じてJavaScriptコードからストアにデータを渡します。このモジュールにはJavaScriptのスペックと各プラットフォーム向けの実装が含まれています。

プロジェクトのルートにある`specs`フォルダ内に、モジュールのスペックを作成します。

```typescript showLineNumbers title="specs/NativeWeightPlanStore.ts"

export interface Spec extends TurboModule {
  setWeights(currentWeight: number, goalWeight: number): void;
}

export default TurboModuleRegistry.getEnforcing<Spec>('NativeWeightPlanStore');
```

ネイティブコードの仕様を生成するには、`package.json` に `codegenConfig` を追加します。`package.json` とモジュールの Kotlin 実装の両方で、`com.example.app` をご自身の Android アプリのパッケージ名に置き換えてください。`package.json` にすでに `codegenConfig` がある場合は、`NativeWeightPlanStore` を `modulesProvider` オブジェクトに追加するだけです：

```json showLineNumbers title="package.json"
"codegenConfig": {
  "name": "AppSpecs",
  "type": "modules",
  "jsSrcsDir": "specs",
  "android": {
    "javaPackageName": "com.example.app.specs"
  },
  "ios": {
    "modulesProvider": {
      "NativeWeightPlanStore": "RCTNativeWeightPlanStore"
    }
  }
}
```

各プラットフォーム向けにモジュールを実装します：

<Tabs groupId="platform" queryString>
<TabItem value="ios" label="iOS (Swift)" default>

Xcode のアプリターゲットで Objective-C++ モジュールを作成します。このモジュールは `NotificationCenter` を通じて Swift コードにウェイトを送信します：

```objectivec showLineNumbers title="RCTNativeWeightPlanStore.h"
#import <AppSpecs/AppSpecs.h>

@interface RCTNativeWeightPlanStore : NSObject <NativeWeightPlanStoreSpec>
@end
```

```objectivec showLineNumbers title="RCTNativeWeightPlanStore.mm"
#import "RCTNativeWeightPlanStore.h"

@implementation RCTNativeWeightPlanStore

+ (NSString *)moduleName {
  return @"NativeWeightPlanStore";
}

- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:
    (const facebook::react::ObjCTurboModule::InitParams &)params {
  return std::make_shared<facebook::react::NativeWeightPlanStoreSpecJSI>(params);
}

- (void)setWeights:(double)currentWeight goalWeight:(double)goalWeight {
  // the AppDelegate updates the weight plan when it receives this notification
  [[NSNotificationCenter defaultCenter] postNotificationName:@"WeightsDidChange"
                                                      object:nil
                                                    userInfo:@{@"current": @(currentWeight),
                                                               @"goal": @(goalWeight)}];
}

@end
```

`AppDelegate.swift` に、体重プランのプロパティを追加します。`application(_:didFinishLaunchingWithOptions:)` メソッドでリゾルバーを設定し、`NotificationCenter` を監視して各体重ペアでプランを更新します。ハイライトされた行が追加箇所です。`AppDelegate` クラスの残りの部分はそのまま維持してください：

```swift showLineNumbers title="ios/YourApp/AppDelegate.swift" {1,6-7,13-26}

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
  // the weight plan that your JavaScript code sends
  let weightPlanStore = WeightPlanStore()

  func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
  ) -> Bool {
    AdaptyUI.setCustomElementsResolver(CustomElementsResolver(weightPlanStore: weightPlanStore))
    // the weights that your JavaScript code sends through the native module
    NotificationCenter.default.addObserver(
      forName: Notification.Name("WeightsDidChange"),
      object: nil,
      queue: .main
    ) { [weightPlanStore] notification in
      guard let currentWeight = notification.userInfo?["current"] as? Double,
            let goalWeight = notification.userInfo?["goal"] as? Double
      else { return }
      MainActor.assumeIsolated {
        weightPlanStore.plan = WeightPlan(currentWeight: currentWeight, goalWeight: goalWeight)
      }
    }
    // the rest of your launch code
    return true
  }
}
```

ネイティブコードのスペックを生成するには、`ios` フォルダ内で `pod install` を実行してください。

</TabItem>
<TabItem value="android" label="Android (Kotlin)">

モジュールと、それを React Native に登録するパッケージを作成します。

```kotlin showLineNumbers title="NativeWeightPlanStoreModule.kt"
package com.example.app

class NativeWeightPlanStoreModule(reactContext: ReactApplicationContext) :
    NativeWeightPlanStoreSpec(reactContext) {

    override fun getName() = NAME

    override fun setWeights(currentWeight: Double, goalWeight: Double) {
        val app = reactApplicationContext.applicationContext as MainApplication
        // the resolver reads the weight plan on the main thread
        UiThreadUtil.runOnUiThread {
            app.weightPlanStore.plan = WeightPlan(currentWeight, goalWeight)
        }
    }

    companion object {
        const val NAME = "NativeWeightPlanStore"
    }
}
```

```kotlin showLineNumbers title="NativeWeightPlanStorePackage.kt"

class NativeWeightPlanStorePackage : BaseReactPackage() {
    override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? =
        if (name == NativeWeightPlanStoreModule.NAME) NativeWeightPlanStoreModule(reactContext) else null

    override fun getReactModuleInfoProvider() = ReactModuleInfoProvider {
        mapOf(
            NativeWeightPlanStoreModule.NAME to ReactModuleInfo(
                name = NativeWeightPlanStoreModule.NAME,
                className = NativeWeightPlanStoreModule.NAME,
                canOverrideExistingModule = false,
                needsEagerInit = false,
                isCxxModule = false,
                isTurboModule = true,
            )
        )
    }
}
```

`MainApplication.kt` に体重プランのプロパティを追加し、`onCreate` メソッドでリゾルバーを設定します。ハイライトされた行が追加箇所です。`MainApplication` クラスの残りの部分はそのままにしてください：

```kotlin showLineNumbers title="MainApplication.kt" {1,4-5,11}

class MainApplication : Application(), ReactApplication {
  // the weight plan that your JavaScript code sends
  val weightPlanStore = WeightPlanStore()

  // the other members of your MainApplication class

  override fun onCreate() {
    super.onCreate()
    AdaptyUI.setCustomElementsResolver(CustomElementsResolver(weightPlanStore))
    // the rest of your onCreate code
  }
}
```

`MainApplication.kt` で、パッケージリストに `NativeWeightPlanStorePackage` を追加します：

```kotlin showLineNumbers title="MainApplication.kt" {2}
PackageList(this).packages.apply {
  add(NativeWeightPlanStorePackage())
}
```

</TabItem>
</Tabs>

JavaScriptコードで、ペイウォールフローが開く前にウェイトをストアに送信します。

```typescript showLineNumbers title="showWeightPaywall.ts"

export async function showWeightPaywall(currentWeight: number, goalWeight: number) {
  try {
    // the native resolver builds the chart from these weights
    NativeWeightPlanStore.setWeights(currentWeight, goalWeight);
    const flow = await adapty.getFlow('weight_paywall');
    const view = await createFlowView(flow);
    await view.present();
  } catch (error) {
    // handle the error
  }
}
```

## 7. デバイスでテストする \{#7-test-on-a-device\}

Flow & Paywall Builder はアプリのコードを実行できないため、キャンバスにはフォールバックのみが表示されます。チャートをプレビューするには:

1. [両方のフローを公開します](builder-save-publish)。キャッシュではなく最新の公開バージョンを確認するには、デバイスを[テストデバイス](test-devices)として登録してください。
2. リゾルバーを含むアプリのビルドを実行します。iOS の場合は iOS 17 以降のデバイスを使用してください。現在の体重と目標体重を入力してオンボーディングフローを完了し、チャートの線が現在の体重から始まり目標体重で終わることを確認してください。
3. チャート上をドラッグして、指の下にある週の予測体重が線の上に表示されることを確認してください。

フォールバックをテストするには、`line_chart` タイプのビューを返さないようにして、ペイウォールフローを再度開いてください。

チャートの代わりにフォールバックが表示される理由を調べるには、React Native ガイドの[デバイスでテストする](react-native-flow-custom-elements#test-on-a-device)セクションの手順を参照してください。