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

> For the complete documentation index, see [llms.txt](https://adapty.io/docs/ja/llms.txt).

> **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 Capacitor SDK 4.4 以降にアップデートしてください。それより古い SDK バージョンでは、すべてのカスタム要素に[フォールバックコンテンツ](flow-custom-elements#set-fallback-content)が表示されます。
- アプリでフローを[取得](capacitor-get-pb-paywalls)および[表示](capacitor-present-paywalls)できるよう設定してください。
- [Capacitor ガイド](capacitor-flow-custom-elements#before-you-start)に従って、カスタム要素用のアプリのネイティブコードを設定してください。
- iOS では、チャート上のドラッグ操作に iOS 17 以降が必要です。iOS 16 では、ラインは表示されますがドラッグはできません。
- Android では、Jetpack Compose を含む[Android プロジェクトの設定](capacitor-flow-custom-elements#set-up-your-android-project)を行ってください。このレシピのチャートはコンポーザブルです。Gradle で `androidx.compose.foundation:foundation` から Compose Foundation をアプリに追加してください（バージョン指定なし）。バージョンは `io.adapty:android-ui` の Compose BOM で設定されます。

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` イベントから現在の体重と目標体重を収集します。方法は[フローからのデータ処理](capacitor-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="Capacitor"
const view = await createFlowView(flow);
await view.setEventHandlers(weightOnboardingHandlers());
await view.present();
```

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

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

体重プランのモデルと、チャートを含むビューを作成します。このプランには、現在の体重から目標体重まで、1週間ごとに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\}

[アプリ全体のリゾルバー](capacitor-flow-custom-elements#pass-the-resolver-to-the-sdk)に `WeightPlanStore` プロパティを追加します。次に、`line_chart` Type と `weight_goal` ID に対してチャートビューを返します。ハイライトされた行が追加または変更する箇所です。アプリにまだアプリ全体の[リゾルバー](capacitor-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\}

アプリ起動時にリゾルバーを設定し、<InlineTooltip tooltip="ローカルCapacitorプラグイン">[iOS](https://capacitorjs.com/docs/ios/custom-code)、[Android](https://capacitorjs.com/docs/android/custom-code)</InlineTooltip>を通じてJavaScriptコードからストアにデータを渡します。プラグインは各プラットフォームの実装とJavaScriptインターフェースを持ちます。

各プラットフォーム向けにプラグインを実装します：

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

`App` ターゲットの Xcode で、プラグインを作成します。`AppDelegate` クラスのウェイトプランを更新します。

```swift showLineNumbers title="WeightPlanStorePlugin.swift"

@objc(WeightPlanStorePlugin)
public class WeightPlanStorePlugin: CAPPlugin, CAPBridgedPlugin {
    public let identifier = "WeightPlanStorePlugin"
    public let jsName = "WeightPlanStore"
    public let pluginMethods: [CAPPluginMethod] = [
        CAPPluginMethod(name: "setWeights", returnType: CAPPluginReturnPromise)
    ]

    @objc func setWeights(_ call: CAPPluginCall) {
        guard let currentWeight = call.getDouble("currentWeight"),
              let goalWeight = call.getDouble("goalWeight")
        else {
            call.reject("Missing currentWeight or goalWeight")
            return
        }
        // the resolver reads the weight plan on the main thread
        Task { @MainActor in
            (UIApplication.shared.delegate as? AppDelegate)?.weightPlanStore.plan =
                WeightPlan(currentWeight: currentWeight, goalWeight: goalWeight)
        }
        call.resolve()
    }
}
```

`CAPBridgeViewController` のサブクラスを作成し、`capacitorDidLoad` メソッドでプラグインを登録します。すでに `CAPBridgeViewController` のサブクラスがある場合は、そちらでプラグインを登録してください：

```swift showLineNumbers title="MyViewController.swift"

class MyViewController: CAPBridgeViewController {
    override open func capacitorDidLoad() {
        bridge?.registerPluginInstance(WeightPlanStorePlugin())
    }
}
```

このサブクラスをアプリで使用するには、`SceneDelegate.swift` 内の `CAPBridgeViewController()` を `MyViewController()` に置き換えてください。プロジェクトに `SceneDelegate.swift` がない場合は、[Custom ViewController](https://capacitorjs.com/docs/ios/viewcontroller) の説明に従って、`Main.storyboard` の **Bridge View Controller** のカスタムクラスに `MyViewController` を設定してください。

`AppDelegate.swift` では、ウェイトプランのプロパティを追加し、`application(_:didFinishLaunchingWithOptions:)` メソッド内でリゾルバを設定します。ハイライトされた行が追加箇所です。`AppDelegate` クラスのそれ以外の部分はそのまま残してください：

```swift showLineNumbers title="ios/App/App/AppDelegate.swift" {1,9-10,13}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    // the weight plan that your JavaScript code sends
    let weightPlanStore = WeightPlanStore()

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        AdaptyUI.setCustomElementsResolver(CustomElementsResolver(weightPlanStore: weightPlanStore))
        // the rest of your launch code
        return true
    }
}
```

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

`MainActivity.java` のフォルダ内にプラグインを作成します。`MainApplication` クラスのウェイトプランを更新します：

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

@CapacitorPlugin(name = "WeightPlanStore")
class WeightPlanStorePlugin : Plugin() {
    @PluginMethod
    fun setWeights(call: PluginCall) {
        val currentWeight = call.getDouble("currentWeight") ?: return call.reject("Missing currentWeight")
        val goalWeight = call.getDouble("goalWeight") ?: return call.reject("Missing goalWeight")
        val app = context.applicationContext as MainApplication
        // the resolver reads the weight plan on the main thread
        activity.runOnUiThread {
            app.weightPlanStore.plan = WeightPlan(currentWeight, goalWeight)
        }
        call.resolve()
    }
}
```

プラグインを登録するには、`MainActivity.java`で`super.onCreate`の前に`registerPlugin`を呼び出します。追加が必要な箇所はハイライト行で示しています：

```java showLineNumbers title="MainActivity.java" {3,7-11}
package com.example.app;

public class MainActivity extends BridgeActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        registerPlugin(WeightPlanStorePlugin.class);
        super.onCreate(savedInstanceState);
    }
}
```

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

```kotlin showLineNumbers title="MainApplication.kt" {7-8,12}
package com.example.app

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

    override fun onCreate() {
        super.onCreate()
        AdaptyUI.setCustomElementsResolver(CustomElementsResolver(weightPlanStore))
    }
}
```

</TabItem>
</Tabs>

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

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

interface WeightPlanStorePlugin {
  setWeights(options: { currentWeight: number; goalWeight: number }): Promise<void>;
}

// the name matches the jsName on iOS and the plugin name on Android
const WeightPlanStore = registerPlugin<WeightPlanStorePlugin>('WeightPlanStore');

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

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

フローとペイウォールビルダーはアプリのコードを実行できないため、キャンバスにはフォールバックのみ表示されます。チャートをプレビューするには、次の手順を行います。

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

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

チャートの代わりにフォールバックが表示される理由を確認するには、Capacitor ガイドの[デバイスでテストする](capacitor-flow-custom-elements#test-on-a-device)セクションの手順に従ってください。