PlatformSDKで自作のAlteryxツールを作ってみる

Alteryx

AlteryxACEのAkimasaKajitaniです。

Alteryx Communityにて「Beyond the Tool Palette: Building Custom Alteryx Connectors and Tools」という興味深い記事が掲載されました。この記事では、PlatformSDKを使うことで、複雑な認証やロジックを隠ぺいし、カスタムコネクタやカスタムツールを作りこんで安定的に動かすことができる、ということが解説されていました。

確かにカスタムコネクタを作るのはかなりハードルが高いようにも思いますが、最近は生成AIのプログラミング能力が飛躍的に高度化しているため、AIを使えばかなりこのアプローチは現実的になっているのでは?ということで、今回試してみました。

これまでHTML GUI ToolKitなどを使って作ったことはありますが、このPlatformSDKを使ってツールを作ったのは初めてです。

ちなみに、結論として、いきなりClaudeやGeminiに尋ねて作ろうとするとうまくいきませんでした。最終的には動くものができましたが、新旧のSDKが入り混じることとなり、かなり混乱したものができあがりました(結局、古いSDKベースで動くようになってしまいました。LLMは新旧のSDKどちらも中途半端に学習しているように見えます)。

このような状況なので、ちゃんとSkills作るなり、最低限の下準備は自分で整えていくのがスムーズで、無駄なLLMコストや時間を使わなくてすむのではないか、ということで今回環境整備を中心に記事を書いてみました。

PlatformSDKを使うための準備

さて、PlatformSDKを使うためには何をすればよいのでしょうか?基本的には以下の公式ページが頼りです。

PlatformSDKのページ:

Platform SDK

まず、事前に最低限行う必要のある作業が二つあります。PythonのインストールとNode.jsのインストールです。

Pythonのインストール

PlatformSDKのページによると、RequirementsのPythonバージョンが最低3.8.5と記載されていますが、これを真に受けてはいけません。基本的に使用しているDesignerのバージョンに合わせて環境を構築する必要があります。すなわち、各Designerに応じた組み込みPythonは、「Alteryx Embedded Python」というページに記載されているので、ここを参考にしてください。

ちなみに、2026.1や2026.2であれば、Pythonは3.13.11となっています。

すでに別のバージョンのPythonがコンピュータにインストールされていてどうしましょう?というときは、仮想環境を使って指定したバージョンを使うことができます。これは後程紹介します。直接仮想環境にインストールする方法もあるので、必ずしも先にPythonをインストールしなければならないわけではありません。

Node.jsのインストール

次に、UI SDKを使うために必要な Node.jsをインストールします。Node.jsも必要なバージョンを入れる必要があります。バージョンによってはうまく動かないことがあります。

実際、私はNode.jsもすでにコンピュータにインストールしてあったのですが、今回の作業を行う上でバージョン違いによるエラーが発生していました。結局複数のバージョンのNode.jsを切り替えて動作するようにする必要がありました。普通にインストールする場合は、そのままインストーラーを入手しインストールしてください。ここでは複数バージョンを切り替えて利用する方法を紹介したいと思います。

ここでは、WindowsPCを利用している前提となりますが、この切り替えには「NVM for Windows」というソフトを使います。なお、すでにNode.jsがインストールされている場合、このソフトのインストール前に、アンインストールをしておいてください。インストーラーはこちらから入手できるはずです(どれを入れたらいいのか少しわかりにくいかもしれません)。

「NVM for Windows」をインストールできたら、Node.jsをインストールしますが、これもNVM for Windows経由でインストールを行います。以下のようなコマンドでインストールできますが、Node.jsのいくつかのバージョンは、パッケージのフォルダ構成が変わっているせいか、うまくインストールできないので注意が必要です。

nvm install 24.20.0

例えば、私はv14はインストールしようとしましたが、このコマンドではうまくインストールできませんでした。この場合、Node.js公式からzipファイルをダウンロードし、解凍後にフォルダ名をv.14.21.3に変更し、NVM for Windowsのルートフォルダにコピーすればオッケーです。なお、NVM for Windowsのルートフォルダは、

nvm root

でわかります。切り替え可能になっていれば、以下のコマンドですべての切り替え可能バージョンがリストアップされます。

nvm list

バージョンを切りかえる場合は、以下コマンドを使います。

nvm use 14.21.3

実際にプロジェクトを作ってみる

今回はテストプロジェクトとして、INT64でも扱うことのできない大きな数の計算を行うようなツールを作ってみたいと思います。

例えば、「LargeNumberCalc」というフォルダを作ってそこに作りこんでいきたいと思います。

Python仮想環境を作成する

まず、プロジェクト用にPythonの仮想環境を作成しましょう。いくつか方法はありますが、スタンダードな方法を取りたいと思います。私はすでにPythonをインストールしていたので、改めてPython3.13.11をインストールし、仮想環境を作成する際にそのバージョンを指定して仮想環境を作りました。

つまり、先ほど作成したフォルダに移動し、コマンドラインにて、以下のようにバージョン指定(ここでは、Pythonのバージョン3.13を指定しています)をして仮想環境を作成することができます。

py -3.13 -m venv myenv

このコマンドの「myenv」というのは、自分で好きにつけられる仮想環境の名称です。

例えば、今回は以下のようなコマンドを打ち込みます。

cd LargeNumberCalc
py -3.13 -m venv alteryx_venv

これで、LargeNumberCalcフォルダ内にalteryx_venvというフォルダが作成されます。

実際にこの環境を有効化するには、以下のコマンドを打ち込みます。

.\alteryx_venv\Scripts\activate

仮想環境が有効化されると、以下のような画面になります。

必要に応じて、pipをアップデートします。

pip install --upgrade pip

Python仮想環境の環境を整える

CLIのインストール

まず、Alteryx Plugin CLIをインストールします。

pip install ayx-plugin-cli

これにより、以下のようなメッセージが最終的に表示されました。いったんうまくいってそうには見えます。

Installing collected packages: zipp, xmltodict, urllib3, typing-extensions, pygments, pluggy, packaging, MarkupSafe, iniconfig, idna, colorama, cloudpickle, click, charset_normalizer, certifi, annotated-types, typer, requests, pytest, pydantic-core, jinja2, importlib-metadata, pydantic, doit, ayx-plugin-cli
Successfully installed MarkupSafe-2.1.4 annotated-types-0.8.0 ayx-plugin-cli-1.4.0 certifi-2026.7.22 charset_normalizer-3.5.1 click-8.5.0 cloudpickle-3.1.2 colorama-0.4.6 doit-0.36.0 idna-3.19 importlib-metadata-9.0.1 iniconfig-2.3.0 jinja2-3.1.6 packaging-24.2 pluggy-1.6.0 pydantic-2.10.6 pydantic-core-2.27.2 pygments-2.21.0 pytest-9.1.1 requests-2.34.2 typer-0.9.0 typing-extensions-4.16.0 urllib3-2.7.0 xmltodict-1.0.4 zipp-4.1.

インストールが成功したかどうか確認のために、以下のコマンドを打ちます。

ayx_plugin_cli version

これを実行すると、エラーが出ました。

どうやらパッケージのバージョンがうまくいっていないようなので、以下のようにパッケージを再インストールします(これはAIを使って修復した結果です)。

python.exe -m pip install --upgrade --force-reinstall ayx_plugin_cli "click==8.1.7" "protobuf==6.33.5" "urllib3==2.5.0" "typer==0.9.0" "requests==2.32.4"

以下のようにアップデートされました。

Successfully installed MarkupSafe-2.1.4 annotated-types-0.8.0 ayx_plugin_cli-1.4.0 certifi-2026.7.22 charset_normalizer-3.5.1 click-8.1.7 cloudpickle-3.1.2 colorama-0.4.6 doit-0.36.0 idna-3.19 importlib-metadata-9.0.1 iniconfig-2.3.0 jinja2-3.1.6 packaging-24.2 pluggy-1.6.0 protobuf-6.33.5 pydantic-2.10.6 pydantic-core-2.27.2 pygments-2.21.0 pytest-9.1.1 requests-2.32.4 typer-0.9.0 typing-extensions-4.16.0 urllib3-2.5.0 xmltodict-1.0.4 zipp-4.1.0

これでもう一度、「ayx_plugin_cli version」を実行します。

完璧です!

次は、PythonSDKをインストールします。

pip install ayx-python-sdk

インストール完了すると、以下のように成功メッセージが出ます。

Successfully installed PyPAC-0.16.5 ayx-python-sdk-2.6.1 deprecation-2.1.0 dukpy-0.6.0 filelock-3.32.5 grpcio-fips-1.81.1 numpy-2.5.2 pandas-2.3.3 psutil-7.0.0 pyarrow-23.0.1 python-dateutil-2.8.2 pytz-2023.3.post1 requests-file-3.0.1 six-1.16.0 tldextract-5.3.2 tzdata-2026.3 wincertstore-0.2

ここまで行けばいったんこのまま使いまわせる状態になっているので、このままzipなどに保存しておき、他のプロジェクトで使いまわすのも良いかと思います。

プロジェクトの作成

ここから本格的にプロジェクトを作成してきます。

ここからはプロジェクト作成のコマンドを実行していきます。

ayx_plugin_cli sdk-workspace-init

コマンドライン上で以下の情報を入れていきます。

  • Package Name
  • Tool Category
  • Description
  • Author
  • Company
  • Backend Language:python

入力が終わると、以下のように進みます。

次に、ツール情報をもう少し具体的に設定していきます。以下コマンドを実行します。

ayx_plugin_cli create-ayx-plugin

コマンドライン上で以下の情報を入れていきます。

  • Tool Name
  • Tool Type:input, multiple-inputs, multiple-outputs, optional, output, single-input-single-output, multi-connection-inputo-anchor
  • Will this tool write output data?:[y/N]
  • Description
  • Tool Version
  • DCM Namespace
  • Do you want to skip generationg UI component?[Default: No]:[y/N]

Tool Typeは、アンカーの数やタイプなどが変わるので、自分が作りたいタイプのものを選択して入力します。

最後の「Do you want to skip generationg UI component?」はUIが必要になる場合は基本「N」にする必要があるため、デフォルトのまま「N」で問題ありません。

入力が終わると、以下のように進みます。

これで基本的な準備はできました。プロジェクトのフォルダは以下のような構成になりました。README.mdなどもできていますが、中身は空っぽなので、自分で書く必要があります。

これらのフォルダ構成は以下のようになっています。

  • backend・・・ツールの実際の処理を記述します。
  • configuration・・・ツールの設定を行います。
  • DcmSchema・・・DCMを使う場合に利用します。
  • ui・・・ツールの設定画面のUIを記述します

また、ツールの直下のフォルダにある「ayx_workspace.json」は、「ayx_plugin_cli sdk-workspace-init」や「ayx_plugin_cli sdk-workspace-init」実行時にコマンドラインで入力していった内容が記載されています。CLIコマンドで管理・更新するので、公式ドキュメントでは、手動更新はやめてくれ、と記載されています。

実際にツールを作りこむ前に・・・

いったん本格的にツールを作りこむ前に、Designerにインストールまでできるかどうか試してみましょう。

カスタムツールをDesignerにインストールする

Designerにインストールするには以下のコマンドを打ち込みます。

ayx_plugin_cli designer-install

もし、上のコマンドでエラーが出る場合は、以下のようにgrpcioを再インストールしてみてください。

pip install --force-reinstall grpcio

さて、「ayx_plugin_cli designer-install」を起動すると、うまくいけば、以下のように処理が走ります。途中、Install Typeを聞かれます。がそのままリターンキーで問題ありません(デフォルトはUser)。さらに、パスを消すかどうか聞かれますが、Y/Nどちらでも問題なさそうですが、どちらかを入力する必要があることに注意してください。

以下のようにエラーが出ることもあるようですが、いったんうまく動いているので、今回はこのままにしておきます。

実際にDesignerを開いてみましょう。今回は、以下のように表示されました。

無事にインストールできたようです。

ツールをキャンバスにドラッグ&ドロップして設定画面を開いてると、UIが未設定なので、以下のような画面になっています。

これで準備はほぼできたように思います。

UI作りこみのために・・・

ちなみに、UIの作りこみ時は、ブラウザで画面を確認しながら進めることができます。プロジェクトにはuiフォルダがあると思いますが、その中のツール名のフォルダ、例えば今回は「NumberCalculator」というフォルダがありますが、さらにその中に入り、コマンドプロンプトで以下のコマンドを実行します。

npm run start

このコマンドを実行する際に、uiフォルダ内のツール名のフォルダ内にある「package.json」を見に行くようになっています。成功すると以下のようにコマンドプロンプトの画面が流れていきます。

これと同時に、ブラウザが「http://localhost:8080/」を開き、以下のような画面が出てきます(以下は全くUIを作りこんでいない場合の画面です)。UIのソースファイルを編集すると、リアルタイムで以下の画面も変更されます。

この画面を止めたい場合は、起動中のコマンドプロンプトにて「Ctrl+C」で止めることができます。

実際にツールを作りこんでみる

実際にツールを作りこむためには、どこをいじればよいのでしょうか?場所としては、実際の処理の内容と、設定画面のUIのところの二か所です。

処理部分

実際の処理については、プロジェクトフォルダ内の「backend」フォルダ内の、「build」の中の「lib\axyplugins」内のツール名のpyファイルです。

これを開くと、ツール名でclassができているので、これを編集していきます。

"""Example pass through tool."""
from typing import TYPE_CHECKING

from ayx_python_sdk.core import (
    Anchor,
    PluginV2,
)
from ayx_python_sdk.providers.amp_provider.amp_provider_v2 import AMPProviderV2

if TYPE_CHECKING:
    import pyarrow as pa


class LargeNumberCalculator(PluginV2):
    """A sample Plugin that passes data from an input connection to an output connection."""

    def __init__(self, provider: AMPProviderV2):
        """Construct the plugin."""
        self.name = "LargeNumberCalculator"
        self.provider = provider
        self.provider.io.info(f"{self.name} tool started")

チュートリアルとしては、一度こちらを読んでおくことをお勧めします。

Getting Started Guide — AyxPythonSdk 2.0.0 documentation

また、上の実際にコードを書く部分は以下のページが参考になるかと思います。

Plugin Tool Execution Framework — AyxPythonSdk 2.0.0 documentation

これ以外に、SDKを入れたときにサンプルも一緒にインストールされています。仮想環境のフォルダ(今回は、alteryx_venvとしています)内の、Lib¥site-packagesのayx_python_sdk内のexamplsというフォルダがあるので、ここにいくつかあるmain.pyを見てみてください。かなり単純なサンプルなので、理解の助けになると思います。

いずれにしても、alteryx-python-sdkの公式ページをよく読んでおくのが良いと思います。

Welcome to ayx_python_sdk’s documentation! — AyxPythonSdk 2.0.0 documentation

UI部分

UIについては、プロジェクトフォルダ直下の「ui」フォルダ内のプロジェクト名のフォルダ内の「src」内の「index.tsx」を変更していきます。

UI部分は説明が少なくてわかりにくいのですが、UIそのものと、バックエンド処理とUIをつなぐ中間に位置するReact Commsの二つがあります。いずれにしても、index.tsxを編集していくことになります。

React Commsについてもう少し説明を加えると、これが行うのは「設定値の同期」と「初期状態の受け取り」そして「状態通知」の三つです。「設定値の同期」は、ユーザーがUIで入力したものをAlteryxに送ります。次に、「初期状態の受け取り」は、保存されている既存の設定データをAlteryxから読み取り、画面に反映します。「状態通知」は、データの読み込み状態やエラーメッセージなど、Alteryx側の動作を画面上に表示させます。

特に編集が必要な部分は、以下の部分となります。サンプルでは、「To get started, edit src/index.tsx」の部分が表示されているかと思います。

const App = () => {
  const classes = useStyles();
  const [model, handleUpdateModel] = useContext(UiSdkContext);

  // Dev Harness Specific Code ---------- Start
  // The following code is specifically a dev harness functionality.
  // If you're developing a tool for Designer, you'll want to remove this
  // and check out our docs for guidance 
  useEffect(() => {
    handleUpdateModel(model)
  }, []);
  // Dev Harness Specific Code ---------- End

  return (
    <Box p={4}>
      <Grid container spacing={4} direction="column" alignItems="center">
        <Grid item>
          <Alteryx className={classes.alteryx} />
        </Grid>
        <Grid item>
          <Typography variant="h3">
            To get started, edit src/index.tsx
          </Typography>
        </Grid>
      </Grid>
    </Box>
  )
}

それ以外にも、各コンポーネントを読み込むための宣言文(import~from@alteryx/ui)など、いろいろと変更箇所は多いです。

ここで生きてくるのがUI作りこみのためのDev Harnessです。すでに一度紹介しましたが、事前準備で確かめたブラウザでUIを確認する機能を使います。これを使えば、「index.tsx」を更新するたびに都度リアルタイムに結果を確認できます。

配置できるコンポーネント(部品)は、Alteryx UIのページに掲載されています。各コンポーネントを閲覧すると、「VIEW CODE」というのがあるので、ここでサンプルコードを見ることができます。

処理部分、UI部分、いずれにしても、ここはもう完全にコーディングの世界になるので、LLMが生きてきます。VS CodeのCopilotに指示するなり、Geminiにソースを読ませるなり、Claude CodeやAntigravityなど、様々なAIコーディングの方法はありますので、ここからはAIで作りこんだ方が早いのが正直なところです。

アイコンについて

ツールアイコンは、いくつかの場所に点在しています。基本的には、プロジェクトフォルダ直下に配置されている「ayx_workspace.json」に各アイコンのPathが書かれているのでこれをたどると良いと思います。

一つ目、プロジェクトフォルダ直下に「configuration」フォルダがあります。この直下にある「default_package_icon.png」は、YXIにパッケージングした際のインストール時に表示されるアイコンです。

さらに、プロジェクトフォルダ直下にあるツール名のフォルダ内の「icon.png」がメインのアイコンになります。

まとめ

本記事では、AlteryxのPlartformSDKを使ったカスタムツール作成の環境づくりをメインにお届けしました。環境さえできてしまえば、あとはAIでなんとでもなるといえばなんとでもなります。環境作りからAIにもちろんやらせることもできますが、古い環境と混じらないように慎重に進めていく必要があります。その際、このブログの内容など読ませれば勝手にやってくれるように思います。

改めて、手順をまとめておきます。

  1. 環境整備
    1. Python環境の整備
    2. Node.jsの整備
  2. Python依存パッケージのセットアップ
    1. ayx-plugin-cliのインストール
    2. ayx-python-sdkのインストール
  3. プロジェクトおよびツールの初期化
    1. ayx_plugin_cli sdk-workspace-init
    2. ayx_plugin_cli create-ayx-plugin
  4. 動作確認(ayx_plugin_cli designer-install)
  5. ツール本体の実装
    1. バックエンド(処理ロジック)の実装
    2. UIの実装
    3. アイコン設定

GitHubリポジトリ:https://github.com/AkimasaKajitani/AYXTOOL_LargeNumberCalc_ja

YXIファイルダウンロード

おまけ

実際に今回作ったツールのコードをお見せします(GitHubでいつでも見れますが)。実際に以下のような感じのワークフローになります。

フォーミュラツールで計算すると、以下のようにINT64を超えていると表示されます。

一方、今回のツールであれば、以下のように結果がちゃんと表示されます。

backendのayx_pluginsのPythonコード「large_number_calculator.py」

変更前:

※コメントは消しました

from typing import TYPE_CHECKING

from ayx_python_sdk.core import (
    Anchor,
    PluginV2,
)
from ayx_python_sdk.providers.amp_provider.amp_provider_v2 import AMPProviderV2

if TYPE_CHECKING:
    import pyarrow as pa

class LargeNumberCalculator(PluginV2):

    def __init__(self, provider: AMPProviderV2):
        self.name = "LargeNumberCalculator"
        self.provider = provider
        self.provider.io.info(f"{self.name} tool started")

    def on_record_batch(self, batch: "pa.Table", anchor: Anchor) -> None:
        self.provider.write_to_anchor("Output", batch)

    def on_incoming_connection_complete(self, anchor: Anchor) -> None:
        self.provider.io.info(
            f"Received complete update from {anchor.name}:{anchor.connection}."
        )

    def on_complete(self) -> None:
        self.provider.io.info(f"{self.name} tool done.")

変更後:

from decimal import Decimal, InvalidOperation, localcontext

import pyarrow as pa
from ayx_python_sdk.core import (
    Anchor,
    PluginV2,
)
from ayx_python_sdk.providers.amp_provider.amp_provider_v2 import AMPProviderV2
from ayx_python_sdk.providers.amp_provider.builders.metadata_builder import MetadataBuilder

class LargeNumberCalculator(PluginV2):
    def __init__(self, provider: AMPProviderV2):
        self.name = "LargeNumberCalculator"
        self.provider = provider
        self.provider.io.info(f"{self.name} tool started")
        self._push_output_metadata()

    def _push_output_metadata(self, input_schema=None) -> None:
        result_field = self.provider.tool_config.get("resultField", "")
        if not result_field:
            return

        if input_schema is not None:
            fields = list(input_schema)
        else:
            input_connections = self.provider.incoming_anchors.get("Input", {})
            if not input_connections:
                return
            input_metadata = next(iter(input_connections.values())).get("metadata")
            if input_metadata is None:
                return
            metadata = MetadataBuilder.from_protobuf(input_metadata)
            fields = [field.to_arrow() for field in metadata]

        result = pa.field(result_field, pa.string())
        result_index = next((index for index, field in enumerate(fields) if field.name == result_field), None)
        if result_index is None:
            fields.append(result)
        else:
            fields[result_index] = result
        self.provider.push_outgoing_metadata("Output", pa.schema(fields))

    def on_record_batch(self, batch: "pa.Table", anchor: Anchor) -> None:
        configuration = self.provider.tool_config
        first_field = configuration.get("firstField", "")
        second_field = configuration.get("secondField", "")
        operator = configuration.get("operator", "+")
        result_field = configuration.get("resultField", "")

        if operator not in {"+", "-", "*", "/"}:
            self.provider.io.error(f"Unsupported operator: {operator}")
            return
        if not first_field or not second_field or not result_field:
            self.provider.io.error("Two input fields and a result field are required.")
            return
        if first_field not in batch.column_names or second_field not in batch.column_names:
            self.provider.io.error("Configured input field was not found in the input data.")
            return

        try:
            results = [
                self._calculate(first, second, operator)
                for first, second in zip(
                    batch[first_field].to_pylist(), batch[second_field].to_pylist()
                )
            ]
        except (InvalidOperation, ValueError, ZeroDivisionError) as error:
            self.provider.io.error(f"Could not calculate large number field: {error}")
            return

        result_array = pa.array(results, type=pa.string())
        self._push_output_metadata(batch.schema)
        if result_field in batch.column_names:
            result_index = batch.column_names.index(result_field)
            output = batch.set_column(result_index, result_field, result_array)
        else:
            output = batch.append_column(result_field, result_array)
        self.provider.write_to_anchor("Output", output)

    @staticmethod
    def _calculate(first: object, second: object, operator: str) -> str:
        if first is None or second is None:
            return None

        first_text = str(first).strip()
        second_text = str(second).strip()
        precision = max(len(first_text), len(second_text)) * 2 + 50
        with localcontext() as context:
            context.prec = max(50, precision)
            left = Decimal(first_text)
            right = Decimal(second_text)
            if operator == "+":
                result = left + right
            elif operator == "-":
                result = left - right
            elif operator == "*":
                result = left * right
            else:
                result = left / right

        result_text = format(result, "f")
        if "." in result_text:
            result_text = result_text.rstrip("0").rstrip(".")
        return result_text or "0"

    def on_incoming_connection_complete(self, anchor: Anchor) -> None: # 未編集
        self.provider.io.info(
            f"Received complete update from {anchor.name}:{anchor.connection}."
        )

    def on_complete(self) -> None: # 未編集
        self.provider.io.info(f"{self.name} tool done.")

今回は、標準的な入力アンカー一つ、出力アンカー一つのツールです。基本的に処理部分は、どこをいじって良いかわかりやすいですが、データをPythonとAlteryxでどのようにやり取りするか、というのが初期コードでは書かれていないのでそこが最初のポイントになるかと思います。とはいえ、AI任せでできてしまいます。一応、サンプルコードが仮想環境内に保存されているので、そちらが参考になります。

今回は、「on_incoming_connection_complete」「on_complete」は特に変更する必要はありませんでした。

UIの「index.tsx」

完成したUI:

変更前:

import React, { useContext, useEffect } from 'react';
import ReactDOM from 'react-dom';
import { AyxAppWrapper, Box, Grid, Typography, makeStyles, Theme } from '@alteryx/ui';
import { Alteryx } from '@alteryx/icons';
import { Context as UiSdkContext, DesignerApi } from '@alteryx/react-comms';

const useStyles = makeStyles((theme: Theme) => ({
  alteryx: {
    color: theme.palette.brand.corporateBlue,
    height: '125px',
    width: '125px'
  }
}));

const App = () => {
  const classes = useStyles();
  const [model, handleUpdateModel] = useContext(UiSdkContext);

  // Dev Harness Specific Code ---------- Start
  // The following code is specifically a dev harness functionality.
  // If you're developing a tool for Designer, you'll want to remove this
  // and check out our docs for guidance 
  useEffect(() => {
    handleUpdateModel(model)
  }, []);
  // Dev Harness Specific Code ---------- End

  return (
    <Box p={4}>
      <Grid container spacing={4} direction="column" alignItems="center">
        <Grid item>
          <Alteryx className={classes.alteryx} />
        </Grid>
        <Grid item>
          <Typography variant="h3">
            To get started, edit src/index.tsx
          </Typography>
        </Grid>
      </Grid>
    </Box>
  )
}

const Tool = () => {
  return (
    <DesignerApi messages={{}}>
      <AyxAppWrapper>
        <App />
      </AyxAppWrapper>
    </DesignerApi>
  )
}

ReactDOM.render(
  <Tool />,
  document.getElementById('app')
);

変更後:

import React, { useContext, useEffect } from 'react';
import ReactDOM from 'react-dom';
import { AyxAppWrapper, Box, TextField } from '@alteryx/ui';
import { Context as UiSdkContext, DesignerApi } from '@alteryx/react-comms';

const operators = [
  { value: '+', label: 'Add (+)' },
  { value: '-', label: 'Subtract (-)' },
  { value: '*', label: 'Multiply (*)' },
  { value: '/', label: 'Divide (/)' }
];

const getStringFields = (metaFields: any): any[] => {
  if (!Array.isArray(metaFields)) {
    return [];
  }

  return metaFields.reduce((fields, connectionGroup) => {
    const connections = Array.isArray(connectionGroup) ? connectionGroup : [connectionGroup];
    return fields.concat(connections.reduce((groupFields, connection) => {
      const connectionFields = Array.isArray(connection?.fields) ? connection.fields : [];
      return groupFields.concat(connectionFields.filter(field => {
        const type = String(field.type || '').toLowerCase();
        return type.includes('string');
      }));
    }, []));
  }, []);
};

const App = () => {
  const [model, handleUpdateModel] = useContext(UiSdkContext);
  const configuration = model.Configuration || {};
  const fields = getStringFields(model.Meta?.fields);

  const updateConfiguration = (name: string, value: string) => {
    handleUpdateModel({
      ...model,
      Configuration: {
        ...configuration,
        [name]: value
      }
    });
  };

  useEffect(() => {
    handleUpdateModel({
      ...model,
      Configuration: {
        ...configuration,
        operator: configuration.operator || '+',
        resultField: configuration.resultField || 'result'
      }
    })
  }, []);

  return (
    <Box p={4}>
      <Box style={{ display: 'flex', flexDirection: 'column', gap: 24, width: '100%' }}>
        <TextField select fullWidth SelectProps={{ native: true }} inputProps={{ style: { paddingLeft: 12, paddingRight: 12 } }} label="1つ目のフィールド" value={configuration.firstField || ''} onChange={event => updateConfiguration('firstField', event.target.value)}>
          <option value="" />
          {fields.map(field => <option key={`first-${field.name}`} value={field.name}>{field.name}</option>)}
        </TextField>
        <TextField select fullWidth SelectProps={{ native: true }} inputProps={{ style: { paddingLeft: 12, paddingRight: 12 } }} label="2つ目のフィールド" value={configuration.secondField || ''} onChange={event => updateConfiguration('secondField', event.target.value)}>
          <option value="" />
          {fields.map(field => <option key={`second-${field.name}`} value={field.name}>{field.name}</option>)}
        </TextField>
        <TextField select fullWidth SelectProps={{ native: true }} inputProps={{ style: { paddingLeft: 12, paddingRight: 12 } }} label="演算子" value={configuration.operator || '+'} onChange={event => updateConfiguration('operator', event.target.value)}>
          {operators.map(operator => <option key={operator.value} value={operator.value}>{operator.label}</option>)}
        </TextField>
        <TextField fullWidth inputProps={{ style: { paddingLeft: 12, paddingRight: 12 } }} label="結果を格納するフィールド名" value={configuration.resultField || 'result'} onChange={event => updateConfiguration('resultField', event.target.value)} />
      </Box>
    </Box>
  )
}

const Tool = () => {
  return (
    <DesignerApi messages={{}} defaultConfig={{ Configuration: { firstField: '', secondField: '', operator: '+', resultField: 'result' } }}>
      <AyxAppWrapper>
        <App />
      </AyxAppWrapper>
    </DesignerApi>
  )
}

ReactDOM.render(
  <Tool />,
  document.getElementById('app')
);

UIの方は、UI部分はデフォルト生成コードでもヒントがありますが、React Comms部分が手掛かりが少ないのでかなりAIにお任せになりました(基本的にほとんど全部AIお任せですが)。あと、デザイン的な部分(テキストボックスのPaddingなど)は、人の見た目が必要でした。といっても、修正はAI任せで良いですが、何がダメでどうしたいかをちゃんと指示していく必要はあります。

コメント

タイトルとURLをコピーしました