0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Scriptable + PokeAPIでiPhoneに表示するウィジェットを作った

0
Last updated at Posted at 2026-07-25

Scriptableを使って、iPhoneのホーム画面とロック画面に表示できるポケモンウィジェットを作りました。
PokeAPIから取得した画像や日本語名、図鑑番号、種族値などをそのままウィジェットに表示します。
特定のポケモンを固定したり、複数候補からランダム表示したりできます。

表示できる主な情報は次のとおりです。

  • ポケモンの画像
  • 日本語名
  • 図鑑番号
  • タイプ
  • 種族値
  • 高さと重さ
  • 分類
  • 図鑑説明

ウィジェットのパラメータを変更することで、特定のポケモンを固定表示したり、複数の候補からランダムに表示したりできます。

完成イメージ

実際に配置したウィジェットのスクリーンショットを掲載します。
image.png
image.png

使用するもの

  • iPhoneまたはiPad
  • Scriptable
  • PokeAPI

Scriptableは、JavaScriptでiOSのウィジェットを作成できるアプリです。
今回はScriptableからPokeAPIへアクセスし、ポケモンの情報と画像を取得します。

このウィジェットでできること

特定のポケモンを表示する

ウィジェットパラメータに、PokeAPIで使用できる図鑑番号を指定します。
英語名(pikachu)による指定も可能です。
image.png
対応している主な指定例は次のとおりです。

  • pikachu
  • 25
  • 25,133,448
  • pikachu,eevee,lucario
  • pokemon=pikachu
  • id=25
  • name=eevee
  • pokemonPool=pikachu,eevee,lucario
  • pool=25,133,448
  • list=pikachu,eevee,lucario
  • {"pokemon":"eevee"}

単体指定だけでなく、候補リスト、キー名付き形式、JSON形式にも対応しています。

複数候補からランダムに表示する

カンマ区切りで複数のポケモンを指定すると、その中から1匹をランダムに選びます。
25,133,448
pikachu,eevee,lucario 英語名でも指定できます。

全ポケモンからランダムに表示する

ウィジェットパラメータを空欄にすると、取得可能なポケモンからランダムに1匹を表示します。

Scriptableへの登録方法

  1. Scriptableをインストールする
    AppStoreからScriptableをインストールします。
  2. 新しいスクリプトを作成する
    Scriptableを開き、右上の追加ボタンから新しいスクリプトを作成します。
  3. コードを貼り付ける
    作成したスクリプトへ、記事末尾に掲載したコードを貼り付けます。
  4. スクリプトを実行する
    Scriptable上でスクリプトを実行し、ポケモンのウィジェットが表示されることを確認します。

ホーム画面への追加方法

  1. iPhone(またはiPad)のホーム画面を長押しする
  2. ウィジェット追加画面を開く
  3. Scriptableを選択する
  4. 使用したいサイズを選択する
  5. 追加したウィジェットを長押しする
  6. 「ウィジェットを編集」を開く
  7. 作成したスクリプトを選択する
  8. Parameterへポケモン名や図鑑番号を入力する
    Parameterを空欄にした場合は、ランダム表示になります。

対応しているウィジェットサイズ

このスクリプトでは、次のウィジェットサイズを判定して表示内容を切り替えています。

  • Small
  • Medium
  • Large
  • Extra Large
  • Accessory Circular
  • Accessory Rectangular
  • Accessory Inline

Smallでは画像と基本情報を中心に表示し、Mediumでは種族値を含めた情報をコンパクトに配置しています。

LargeとExtra Largeでは、分類や図鑑説明も表示します。

ロック画面用のAccessoryウィジェットでは、限られた表示領域に合わせて画像や名称だけを表示します。

処理の流れ

スクリプト全体は、主に次の流れで動作します。

  1. ウィジェットサイズを取得する
  2. ウィジェットパラメータを解析する
  3. 表示するポケモンを決定する
  4. PokeAPIからデータを取得する
  5. 日本語名や種族値を表示用データへ変換する
  6. ウィジェットサイズごとのレイアウトを作る
  7. 取得結果をキャッシュする
  8. ウィジェットを表示する

ウィジェットパラメータの解析

パラメータの形式によって処理を分けています。

  • 空欄:全体からランダム
  • JSON:JSONとして解析
  • =を含む:キーバリュー形式として解析
  • ,を含む:候補リストとして解析
  • それ以外:単体の名前またはID

これにより、単純な指定と詳細な設定の両方に対応できます。

ただし、ポケモン名を指定する場合は、PokeAPIで使用できる英語名が必要です。
日本語の「ピカチュウ」を直接指定する形式には対応していません。

PokeAPIから取得するデータ

ポケモンの表示には、主に2つのエンドポイントを使用します。

Pokémon

ポケモン本体の情報を取得します。

ここから次の情報を使用します。

  • 図鑑番号
  • タイプ
  • 種族値
  • 高さ
  • 重さ
  • 画像URL

Pokémon Species

言語別の名称や図鑑情報を取得します。

ここから次の情報を使用します。

  • 日本語名
  • 日本語の分類
  • 日本語の図鑑説明

本体情報と種族情報を組み合わせ、ウィジェットで扱いやすいオブジェクトへ変換しています。

日本語名の取得

PokeAPIの名称データには、言語情報が含まれています。

スクリプトでは、次の言語を順番に検索しています。

  1. ja
  2. ja-Hrkt

日本語名が見つからない場合は、PokeAPIの英語名を先頭大文字にして表示します。

分類や図鑑説明についても、同様に日本語データを検索しています。

タイプに応じた背景色

タイプごとに、表示名と背景色を定義しています。

たとえば、ほのおタイプではオレンジ系、みずタイプでは青系、くさタイプでは緑系のグラデーションを使用します。

複合タイプの場合、背景には第1タイプの色を使用し、すべてのタイプを画面上部のラベルとして表示します。

PokeAPIから未知のタイプが返された場合でも表示が止まらないように、デフォルト色も用意しています。

種族値の表示

PokeAPIから取得した種族値は、次の日本語ラベルへ変換しています。

API上の名称 表示
hp HP
attack 攻撃
defense 防御
special-attack 特攻
special-defense 特防
speed 素早

Mediumサイズでは2項目ずつ横並びにし、Largeサイズでは3列のグリッドとして表示しています。

画像の取得

画像には、PokeAPIのOfficial Artworkを優先して使用します。

Official Artworkが存在しない場合は、通常の正面画像へフォールバックします。

画像取得に失敗した場合は、保存済みの画像キャッシュを読み込みます。

これにより、一時的に通信できない状態でも、以前表示したポケモンであれば画像を表示できる可能性があります。

キャッシュ処理

PokeAPIへ毎回アクセスするだけでは、通信状態によってウィジェットが表示できないことがあります。

そこで、取得したデータと画像をScriptableのローカル領域へ保存しています。

保存対象は次の2種類です。

  • ポケモン情報のJSON
  • ポケモン画像のPNG

APIへのアクセスに失敗した場合は、同じポケモンのキャッシュを読み込みます。

ランダム表示の場合は、指定したIDのキャッシュが存在しなくても、最後に正常取得できたランダムポケモンを表示します。

キャッシュには保存期間とファイル数の上限を設定しています。

  • 保存期間:30日
  • キャッシュ上限:JSONとPNGを合わせて160ファイル

スクリプト実行時に古いファイルを削除し、上限を超えた場合は更新日時が古いものから削除します。

エラー表示

JSON形式やキー付き形式のパラメータが不正な場合は、入力値を含むエラーメッセージを表示します。
また、pokemon、id、name に、日本語名や使用できない記号を含む値を指定した場合は、ランダム表示へ切り替えずエラーを表示します。

これは、指定方法を間違えたときに、意図しないポケモンが表示されることを防ぐためです。

実装してみて

Scriptableでは、APIから取得したデータを使って比較的自由にウィジェットを構成できます。

一方で、ウィジェットサイズごとに利用できる領域が大きく異なるため、単純に文字サイズを変更するだけでは収まりません。

今回は、サイズごとに表示する情報そのものを変更しました。

  • Small:画像と名前を重視
  • Medium:画像と種族値を両立
  • Large:図鑑情報まで表示
  • ロック画面:最低限の情報だけ表示

また、PokeAPIへの通信に失敗した場合を考慮し、データと画像のキャッシュも実装しました。

見た目だけでなく、通信状態が不安定な場合にも可能な限り表示を維持できるウィジェットになりました。

今後追加したいこと

今後は次の機能も追加できそうです。

  • 色違い画像の表示
  • ポケモンをタップしたときの画面遷移
  • 日本語名によるパラメータ指定
  • 世代やタイプを指定したランダム表示
  • ポケモンの定期的な自動切り替え
  • キャッシュ表示中であることの明示
  • 表示項目や配色のカスタマイズ

ソースコード

ソースコード全文は、以下へ掲載します。

// ======================================
// Pokemon Widget for Scriptable
// ======================================
//
// widgetParameter 例:
//   未指定 -> ランダム
//   pikachu
//   25
//   25,133,448
//   pikachu,eevee,lucario
//   pokemon=pikachu
//   pokemonPool=pikachu,eevee,lucario
//   pool=25,133,448
//   {"pokemon":"eevee"}
//
// PokeAPI から直接取得する。
// 表示するのは日本語名・タイプ・種族値。

const RANDOM_POKEMON_FALLBACK_MAX_ID = 1025;
const POKE_API_DOMAIN = "https://pokeapi.co/api/v2";
const CACHE_DIR = "pokemon_widget_cache";
const CACHE_MAX_AGE_DAYS = 30;
const CACHE_MAX_CACHE_FILE_COUNT = 160;
const RANDOM_FALLBACK_CACHE_KEY = "__last_random_pokemon__";
const TYPE_INFO = Object.freeze({
  normal: { label: "ノーマル", colors: ["#94A3B8", "#111111"], pill: "#CBD5E1" },
  fire: { label: "ほのお", colors: ["#F97316", "#111111"], pill: "#FCA5A5" },
  water: { label: "みず", colors: ["#38BDF8", "#111111"], pill: "#93C5FD" },
  electric: { label: "でんき", colors: ["#FACC15", "#111111"], pill: "#FDE68A" },
  grass: { label: "くさ", colors: ["#4ADE80", "#111111"], pill: "#86EFAC" },
  ice: { label: "こおり", colors: ["#7DD3FC", "#111111"], pill: "#93C5FD" },
  fighting: { label: "かくとう", colors: ["#DC2626", "#111111"], pill: "#FCA5A5" },
  poison: { label: "どく", colors: ["#A855F7", "#111111"], pill: "#C4B5FD" },
  ground: { label: "じめん", colors: ["#D97706", "#111111"], pill: "#FDBA74" },
  flying: { label: "ひこう", colors: ["#60A5FA", "#111111"], pill: "#93C5FD" },
  psychic: { label: "エスパー", colors: ["#F472B6", "#111111"], pill: "#F9A8D4" },
  bug: { label: "むし", colors: ["#84CC16", "#111111"], pill: "#86EFAC" },
  rock: { label: "いわ", colors: ["#A16207", "#111111"], pill: "#FDBA74" },
  ghost: { label: "ゴースト", colors: ["#7C3AED", "#111111"], pill: "#C4B5FD" },
  dragon: { label: "ドラゴン", colors: ["#4F46E5", "#111111"], pill: "#C4B5FD" },
  dark: { label: "あく", colors: ["#334155", "#111111"], pill: "#CBD5E1" },
  steel: { label: "はがね", colors: ["#94A3B8", "#111111"], pill: "#CBD5E1" },
  fairy: { label: "フェアリー", colors: ["#F9A8D4", "#111111"], pill: "#F9A8D4" },
});
const STAT_LABELS = Object.freeze({
  hp: "HP",
  attack: "攻撃",
  defense: "防御",
  "special-attack": "特攻",
  "special-defense": "特防",
  speed: "素早",
});
const COLORS = Object.freeze({
  white: "#FFFFFF",
  light: "#D1D5DB",
  subtle: "#CBD5E1",
  dark: "#111111",
  pillText: "#111111",
});
const DEFAULT_OPTIONS = Object.freeze({
  pokemon: "",
  isRandomSelection: false,
});

async function main() {
  const family = config.widgetFamily || "medium";
  prunePokemonCache_();
  const widgetOptions = await resolveWidgetOptions(args.widgetParameter);
  const identifier = widgetOptions.pokemon;
  const pokemon = await fetchPokemonModel(identifier, widgetOptions);
  const widget = await buildPokemonWidget(pokemon, family);

  Script.setWidget(widget);

  if (!config.runsInWidget) {
    await presentWidgetForFamily_(widget, family);
  }

  Script.complete();
}

/**
 * family ごとの preview 表示を共通化します。
 *
 * @param {ListWidget} widget 表示対象
 * @param {string} family Widget family
 * @returns {Promise<void>} 表示完了
 */
async function presentWidgetForFamily_(widget, family) {
  if (family === "small") {
    await widget.presentSmall();
    return;
  }

  if (family === "accessoryCircular") {
    await widget.presentAccessoryCircular();
    return;
  }

  if (family === "accessoryRectangular") {
    await widget.presentAccessoryRectangular();
    return;
  }

  if (family === "accessoryInline") {
    await widget.presentAccessoryInline();
    return;
  }

  if (family === "large") {
    await widget.presentLarge();
    return;
  }

  if (family === "extraLarge") {
    await widget.presentExtraLarge();
    return;
  }

  await widget.presentMedium();
}

async function resolveWidgetOptions(rawValue) {
  const raw = String(rawValue || "").trim();
  if (!raw) {
    return {
      ...DEFAULT_OPTIONS,
      pokemon: String(await generateRandomPokemonId()),
      isRandomSelection: true,
    };
  }

  if (raw.startsWith("{")) {
    try {
      const parsed = JSON.parse(raw);
      return normalizeWidgetOptions(parsed);
    } catch (error) {
      throw new Error(`widgetParameter の JSON が不正です: ${raw}`);
    }
  }

  if (raw.includes("=")) {
    return normalizeWidgetOptions(parseKeyValueConfig(raw));
  }

  if (raw.includes(",")) {
    return normalizeWidgetOptions({ pokemonPool: raw });
  }

  return normalizeWidgetOptions({ pokemon: raw.toLowerCase() });
}

async function normalizeWidgetOptions(partial) {
  const explicitValue = partial && (partial.pokemon || partial.id || partial.name);
  const normalizedExplicitValue = normalizePokemonIdentifier_(explicitValue);
  const pokemonPool = normalizePokemonPool_(partial && (partial.pokemonPool || partial.pool || partial.list));
  if (explicitValue !== undefined && explicitValue !== null && String(explicitValue).trim() && !normalizedExplicitValue) {
    throw new Error(
      "pokemon/id/name は図鑑番号の数値、または英小文字・数字・ハイフンの名前を指定してください。例: 25, pikachu, mr-mime"
    );
  }
  const pokemon = await resolvePokemonIdentifier_(
    normalizedExplicitValue,
    pokemonPool
  );

  return {
    pokemon: pokemon,
    isRandomSelection: !normalizedExplicitValue,
  };
}

function parseKeyValueConfig(raw) {
  try {
    return raw
      .split("&")
      .filter(Boolean)
      .reduce((acc, pair) => {
        const parts = pair.split("=");
        const key = decodeURIComponent(parts[0] || "").trim();
        const value = decodeURIComponent(parts.slice(1).join("=") || "").trim();

        if (key) {
          acc[key] = value;
        }

        return acc;
      }, {});
  } catch (error) {
    throw new Error(`widgetParameter の key=value 形式が不正です: ${raw}`);
  }
}

async function generateRandomPokemonId() {
  const maxId = await fetchPokemonMaxId();
  return Math.floor(Math.random() * maxId) + 1;
}

async function resolvePokemonIdentifier_(explicitPokemon, pokemonPool) {
  if (explicitPokemon) {
    return explicitPokemon;
  }

  if (pokemonPool.length > 0) {
    const randomIndex = Math.floor(Math.random() * pokemonPool.length);
    return pokemonPool[randomIndex];
  }

  return String(await generateRandomPokemonId()).trim().toLowerCase();
}

async function fetchPokemonMaxId() {
  try {
    const response = await loadJson(`${POKE_API_DOMAIN}/pokemon-species?limit=1`);
    const count = Number(response && response.count);
    return count > 0 ? count : RANDOM_POKEMON_FALLBACK_MAX_ID;
  } catch (error) {
    console.warn("pokemon count fetch failed, use fallback max id");
    return RANDOM_POKEMON_FALLBACK_MAX_ID;
  }
}

async function fetchPokemonModel(identifier, widgetOptions) {
  const cacheKey = sanitizeCacheKey(identifier);

  try {
    const pokemonResponse = await loadJson(`${POKE_API_DOMAIN}/pokemon/${identifier}`);
    const speciesResponse = await loadJson(`${POKE_API_DOMAIN}/pokemon-species/${pokemonResponse.id}`);
    const model = buildPokemonModel_(pokemonResponse, speciesResponse);
    try {
      writePokemonCache_(cacheKey, model);
      if (widgetOptions && widgetOptions.isRandomSelection) {
        writePokemonCache_(RANDOM_FALLBACK_CACHE_KEY, model);
      }
    } catch (error) {
      console.warn(`pokemon cache write failed: ${error.message}`);
    }
    return model;
  } catch (error) {
    const cached = readPokemonCache_(cacheKey);
    if (cached) {
      return cached;
    }

    if (widgetOptions && widgetOptions.isRandomSelection) {
      const randomFallback = readPokemonCache_(RANDOM_FALLBACK_CACHE_KEY);
      if (randomFallback) {
        return randomFallback;
      }
    }

    throw error;
  }
}

function buildPokemonModel_(pokemonResponse, speciesResponse) {
  return {
    id: Number(pokemonResponse.id),
    nameJa: resolveLocalizedName(speciesResponse.names, ["ja", "ja-Hrkt"]) ||
      capitalizeText(pokemonResponse.name),
    genusJa: resolveLocalizedField(speciesResponse.genera, ["ja", "ja-Hrkt"], "genus"),
    flavorJa: resolveFlavorText(speciesResponse.flavor_text_entries),
    imageUrl: resolveArtworkUrl(pokemonResponse),
    types: normalizeTypes(pokemonResponse.types || []),
    stats: normalizeStats(pokemonResponse.stats || []),
    heightMeters: Number(pokemonResponse.height || 0) / 10,
    weightKg: Number(pokemonResponse.weight || 0) / 10,
    syncedAt: new Date(),
  };
}

async function loadJson(url) {
  const request = new Request(url);
  request.timeoutInterval = 20;
  return await request.loadJSON();
}

function resolveArtworkUrl(pokemonResponse) {
  const officialArtwork = pokemonResponse &&
    pokemonResponse.sprites &&
    pokemonResponse.sprites.other &&
    pokemonResponse.sprites.other["official-artwork"] &&
    pokemonResponse.sprites.other["official-artwork"].front_default;

  return officialArtwork || (pokemonResponse.sprites && pokemonResponse.sprites.front_default) || "";
}

function resolveLocalizedName(entries, languages) {
  return resolveLocalizedField(entries, languages, "name");
}

function resolveLocalizedField(entries, languages, fieldName) {
  if (!Array.isArray(entries)) {
    return "";
  }

  for (let index = 0; index < languages.length; index += 1) {
    const language = languages[index];
    const found = entries.find(function(entry) {
      return entry && entry.language && entry.language.name === language;
    });
    if (found && found[fieldName]) {
      return sanitizeText(found[fieldName]);
    }
  }

  return "";
}

function resolveFlavorText(entries) {
  if (!Array.isArray(entries)) {
    return "";
  }

  const found = entries.find(function(entry) {
    return entry &&
      entry.language &&
      ["ja", "ja-Hrkt"].indexOf(entry.language.name) >= 0 &&
      entry.flavor_text;
  });

  return sanitizeText(found && found.flavor_text);
}

function normalizeTypes(typeEntries) {
  return typeEntries.slice().sort(function(a, b) {
    return Number(a.slot) - Number(b.slot);
  }).map(function(typeEntry) {
    const key = String(typeEntry.type.name || "");
    const info = TYPE_INFO[key] || {
      label: key,
      colors: ["#0F766E", "#111111"],
      pill: "#CBD5E1",
    };

    return {
      key: key,
      label: info.label,
      colors: info.colors,
      pill: info.pill,
    };
  });
}

function normalizeStats(statEntries) {
  return statEntries.map(function(statEntry) {
    const key = String(statEntry.stat.name || "");
    return {
      key: key,
      label: STAT_LABELS[key] || key,
      value: Number(statEntry.base_stat || 0),
    };
  });
}

async function buildPokemonWidget(pokemon, family) {
  const widget = new ListWidget();

  if (family === "accessoryCircular") {
    widget.setPadding(0, 0, 0, 0);
    applyAccessoryBackground(widget);
    await renderAccessoryCircularPokemon(widget, pokemon);
    return widget;
  }

  if (family === "accessoryRectangular") {
    widget.setPadding(10, 12, 10, 12);
    applyBackground(widget, pokemon.types[0]);
    await renderAccessoryRectangularPokemon(widget, pokemon);
    return widget;
  }

  if (family === "accessoryInline") {
    widget.setPadding(0, 0, 0, 0);
    renderAccessoryInlinePokemon(widget, pokemon);
    return widget;
  }

  const expandedFamily = isExpandedFamily_(family);
  widget.setPadding(
    family === "small" ? 10 : expandedFamily ? 12 : 9,
    family === "small" ? 8 : expandedFamily ? 12 : 9,
    family === "small" ? 10 : expandedFamily ? 10 : 8,
    family === "small" ? 8 : expandedFamily ? 12 : 9
  );
  applyBackground(widget, pokemon.types[0]);

  renderHeader(widget, pokemon, family);
  widget.addSpacer(family === "small" ? 3 : 5);

  if (family === "small") {
    await renderSmallLayout(widget, pokemon);
  } else if (family === "medium") {
    await renderMediumLayout(widget, pokemon);
  } else {
    await renderHero(widget, pokemon, family);
    widget.addSpacer(family === "small" ? 3 : 5);
  }

  if (family === "small") {
    // small は種族値を出さず、名前と画像を優先する
  } else if (family === "medium") {
    renderMediumFooter(widget, pokemon);
  } else {
    renderStatGrid(widget, pokemon.stats, family);
    widget.addSpacer(6);
    renderSummary(widget, pokemon, family);
  }

  widget.addSpacer();
  renderSyncedAt(widget, pokemon.syncedAt);
  return widget;
}

async function renderAccessoryCircularPokemon(widget, pokemon) {
  const image = await loadImageSafe(pokemon.imageUrl);
  const canvas = new DrawContext();
  canvas.size = new Size(72, 72);
  canvas.opaque = false;
  canvas.respectScreenScale = true;

  if (image) {
    const imageSize = 56;
    const imageOrigin = Math.round((72 - imageSize) / 2);
    canvas.drawImageInRect(image, new Rect(imageOrigin, imageOrigin, imageSize, imageSize));
  } else {
    canvas.setTextAlignedCenter();
    canvas.setTextColor(new Color(COLORS.white));
    canvas.setFont(Font.boldSystemFont(28));
    canvas.drawTextInRect("?", new Rect(0, 18, 72, 32));
  }

  const imageView = widget.addImage(canvas.getImage());
  imageView.imageSize = new Size(72, 72);
  imageView.centerAlignImage();
}

async function renderAccessoryRectangularPokemon(widget, pokemon) {
  const row = widget.addStack();
  row.layoutHorizontally();
  row.centerAlignContent();

  const image = await loadImageSafe(pokemon.imageUrl);
  if (image) {
    const imageView = row.addImage(image);
    imageView.imageSize = new Size(42, 42);
    row.addSpacer(10);
  }

  const textColumn = row.addStack();
  textColumn.layoutVertically();

  const name = textColumn.addText(pokemon.nameJa || "Pokemon");
  name.font = Font.boldSystemFont(12);
  name.textColor = new Color(COLORS.white);
  name.lineLimit = 1;
  name.minimumScaleFactor = 0.7;

  const noText = textColumn.addText(`No.${String(pokemon.id).padStart(3, "0")}`);
  noText.font = Font.systemFont(9);
  noText.textColor = new Color(COLORS.light);
  noText.lineLimit = 1;

  const typeText = textColumn.addText(joinTypeLabels(pokemon.types));
  typeText.font = Font.systemFont(9);
  typeText.textColor = new Color(COLORS.subtle);
  typeText.lineLimit = 1;
  typeText.minimumScaleFactor = 0.7;
}

function renderAccessoryInlinePokemon(widget, pokemon) {
  const text = widget.addText(`${pokemon.nameJa || "Pokemon"} ${joinTypeLabels(pokemon.types)}`);
  text.font = Font.systemFont(12);
  text.textColor = new Color(COLORS.white);
  text.lineLimit = 1;
  text.minimumScaleFactor = 0.7;
}

async function renderSmallLayout(widget, pokemon) {
  const image = await loadImageSafe(pokemon.imageUrl);
  if (image) {
    const imageRow = widget.addStack();
    imageRow.layoutHorizontally();
    imageRow.centerAlignContent();
    imageRow.addSpacer();
    const imageView = imageRow.addImage(image);
    imageView.imageSize = new Size(84, 84);
    imageView.cornerRadius = 12;
    imageRow.addSpacer();
  }

  widget.addSpacer(2);

  const nameText = widget.addText(pokemon.nameJa || "Pokemon");
  nameText.font = Font.boldSystemFont(15);
  nameText.textColor = new Color(COLORS.white);
  nameText.lineLimit = 1;
  nameText.minimumScaleFactor = 0.7;

  const subText = widget.addText(buildHeroSubtitle(pokemon, "small"));
  subText.font = Font.systemFont(9);
  subText.textColor = new Color(COLORS.light);
  subText.lineLimit = 1;
  subText.minimumScaleFactor = 0.75;

  widget.addSpacer(2);
}

function renderHeader(widget, pokemon, family) {
  const row = widget.addStack();
  row.layoutHorizontally();
  row.centerAlignContent();

  const title = row.addText("⚡ Pokemon");
  title.font = Font.boldSystemFont(
    family === "small" ? 9 : family === "extraLarge" ? 16 : family === "large" ? 14 : 12
  );
  title.textColor = new Color(COLORS.white);
  title.lineLimit = 1;
  title.minimumScaleFactor = 0.7;

  const types = pokemon.types || [];
  if (types.length > 0) {
    row.addSpacer();
    row.addSpacer(10);
    renderTypePills(row, types, family === "small");
  }
}

async function renderMediumLayout(widget, pokemon) {
  const row = widget.addStack();
  row.layoutHorizontally();
  row.topAlignContent();

  const image = await loadImageSafe(pokemon.imageUrl);
  if (image) {
    const leftColumn = row.addStack();
    leftColumn.layoutVertically();
    leftColumn.centerAlignContent();

    const imageView = leftColumn.addImage(image);
    imageView.imageSize = new Size(98, 98);
    imageView.cornerRadius = 12;

    row.addSpacer(12);
  }

  const rightColumn = row.addStack();
  rightColumn.layoutVertically();

  const nameText = rightColumn.addText(pokemon.nameJa || "Pokemon");
  nameText.font = Font.boldSystemFont(21);
  nameText.textColor = new Color(COLORS.white);
  nameText.lineLimit = 1;
  nameText.minimumScaleFactor = 0.7;

  const subText = rightColumn.addText(`No.${String(pokemon.id).padStart(3, "0")}`);
  subText.font = Font.systemFont(11);
  subText.textColor = new Color(COLORS.light);
  subText.lineLimit = 1;
  subText.minimumScaleFactor = 0.75;

  if (pokemon.genusJa) {
    const genusText = rightColumn.addText(pokemon.genusJa);
    genusText.font = Font.systemFont(10);
    genusText.textColor = new Color(COLORS.light);
    genusText.lineLimit = 2;
    genusText.minimumScaleFactor = 0.75;
  }

  rightColumn.addSpacer(6);
  renderInlineStatRows(rightColumn, pokemon.stats.slice(0, 6), {
    labelSize: 9,
    valueSize: 14,
    pairSpacing: 12,
    rowSpacing: 3,
  });
  widget.addSpacer(5);
}

function renderTypePills(target, types, compact) {
  types.forEach(function(type, index) {
    const chip = target.addStack();
    chip.layoutHorizontally();
    chip.centerAlignContent();
    chip.setPadding(compact ? 2 : 3, compact ? 7 : 9, compact ? 2 : 3, compact ? 7 : 9);
    chip.backgroundColor = new Color(type.pill || "#CBD5E1", 0.95);
    chip.cornerRadius = 999;

    const text = chip.addText(type.label);
    text.font = Font.boldSystemFont(compact ? 7 : 9);
    text.textColor = new Color(COLORS.pillText);
    text.lineLimit = 1;
    text.minimumScaleFactor = 0.7;

    if (index < types.length - 1) {
      target.addSpacer(compact ? 4 : 6);
    }
  });
}

async function renderHero(widget, pokemon, family) {
  const row = widget.addStack();
  row.layoutHorizontally();
  row.centerAlignContent();

  const image = await loadImageSafe(pokemon.imageUrl);
  if (image) {
    const imageView = row.addImage(image);
    const imageSize = family === "small" ? 76 : family === "extraLarge" ? 120 : family === "large" ? 96 : 76;
    imageView.imageSize = new Size(imageSize, imageSize);
    imageView.cornerRadius = 12;
    row.addSpacer(family === "small" ? 10 : 12);
  }

  const column = row.addStack();
  column.layoutVertically();

  const nameText = column.addText(pokemon.nameJa || "Pokemon");
  nameText.font = Font.boldSystemFont(
    family === "small" ? 17 : family === "extraLarge" ? 28 : family === "large" ? 22 : 20
  );
  nameText.textColor = new Color(COLORS.white);
  nameText.lineLimit = 1;
  nameText.minimumScaleFactor = 0.7;

  const subText = column.addText(buildHeroSubtitle(pokemon, family));
  subText.font = Font.systemFont(
    family === "small" ? 10 : family === "extraLarge" ? 13 : family === "large" ? 11 : 10
  );
  subText.textColor = new Color(COLORS.light);
  subText.lineLimit = family === "small" ? 1 : family === "extraLarge" ? 3 : 2;
  subText.minimumScaleFactor = 0.7;
}

function buildHeroSubtitle(pokemon, family) {
  if (family === "small") {
    if (pokemon.genusJa) {
      return `No.${String(pokemon.id).padStart(3, "0")} / ${pokemon.genusJa}`;
    }

    return `No.${String(pokemon.id).padStart(3, "0")}`;
  }

  if (pokemon.genusJa) {
    return `No.${String(pokemon.id).padStart(3, "0")} / ${pokemon.genusJa}`;
  }

  return `No.${String(pokemon.id).padStart(3, "0")}`;
}

function renderStatGrid(widget, stats, family) {
  const columns = 3;
  const metricWidth = family === "extraLarge" ? 120 : family === "large" ? 94 : 74;
  const metricHeight = family === "extraLarge" ? 36 : 30;

  for (let index = 0; index < stats.length; index += columns) {
    const row = widget.addStack();
    row.layoutHorizontally();
    row.centerAlignContent();

    stats.slice(index, index + columns).forEach(function(stat, metricIndex, currentRow) {
      const card = row.addStack();
      card.layoutVertically();
      card.size = new Size(metricWidth, metricHeight);

      const label = card.addText(stat.label);
      label.font = Font.systemFont(metricWidth >= 120 ? 10 : metricWidth < 80 ? 8 : 9);
      label.textColor = new Color(COLORS.light);
      label.lineLimit = 1;

      const value = card.addText(String(stat.value));
      value.font = Font.boldSystemFont(metricWidth >= 120 ? 18 : metricWidth < 80 ? 13 : 14);
      value.textColor = new Color(COLORS.white);
      value.lineLimit = 1;
      value.minimumScaleFactor = 0.7;

      if (metricIndex < currentRow.length - 1) {
        row.addSpacer(8);
      }
    });
  }
}

function renderInlineStatRows(target, stats, options) {
  const labelSize = options && options.labelSize ? options.labelSize : 9;
  const valueSize = options && options.valueSize ? options.valueSize : 12;
  const pairSpacing = options && options.pairSpacing ? options.pairSpacing : 8;
  const rowSpacing = options && options.rowSpacing !== undefined ? options.rowSpacing : 2;

  for (let index = 0; index < stats.length; index += 2) {
    const row = target.addStack();
    row.layoutHorizontally();
    row.centerAlignContent();

    stats.slice(index, index + 2).forEach(function(stat, metricIndex, currentRow) {
      const label = row.addText(`${stat.label} `);
      label.font = Font.systemFont(labelSize);
      label.textColor = new Color(COLORS.light);
      label.lineLimit = 1;

      const value = row.addText(String(stat.value));
      value.font = Font.boldSystemFont(valueSize);
      value.textColor = new Color(COLORS.white);
      value.lineLimit = 1;
      value.minimumScaleFactor = 0.7;

      if (metricIndex < currentRow.length - 1) {
        row.addSpacer(pairSpacing);
      }
    });

    if (index + 2 < stats.length) {
      target.addSpacer(rowSpacing);
    }
  }
}

function renderMediumFooter(widget, pokemon) {
  const summary = widget.addText(
    `たかさ ${pokemon.heightMeters.toFixed(1)}m / おもさ ${pokemon.weightKg.toFixed(1)}kg`
  );
  summary.font = Font.systemFont(8);
  summary.textColor = new Color(COLORS.subtle);
  summary.lineLimit = 1;
  summary.minimumScaleFactor = 0.75;
}

function renderSummary(widget, pokemon, family) {
  const summary = widget.addText(
    `たかさ ${pokemon.heightMeters.toFixed(1)}m ・ おもさ ${pokemon.weightKg.toFixed(1)}kg`
  );
  summary.font = Font.systemFont(isExpandedFamily_(family) ? 9 : 8);
  summary.textColor = new Color(COLORS.subtle);
  summary.lineLimit = 2;
  summary.minimumScaleFactor = 0.75;

  if (isExpandedFamily_(family) && pokemon.flavorJa) {
    widget.addSpacer(4);
    const flavor = widget.addText(pokemon.flavorJa);
    flavor.font = Font.systemFont(family === "extraLarge" ? 11 : 9);
    flavor.textColor = new Color(COLORS.subtle);
    flavor.lineLimit = family === "extraLarge" ? 5 : 3;
    flavor.minimumScaleFactor = 0.75;
  }
}

function renderSyncedAt(widget, syncedAt) {
  const footer = widget.addText(`同期 ${formatDate(syncedAt)}`);
  footer.font = Font.systemFont(7);
  footer.textColor = new Color(COLORS.subtle);
  footer.lineLimit = 1;
}

function joinTypeLabels(types) {
  return (types || []).map(function(type) {
    return type.label;
  }).join(" / ");
}

async function loadImageSafe(url) {
  if (!url) {
    return null;
  }

  const cacheKey = sanitizeCacheKey(url);

  try {
    const request = new Request(url);
    request.timeoutInterval = 20;
    const image = await request.loadImage();
    try {
      writePokemonImageCache_(cacheKey, image);
    } catch (error) {
      console.warn(`pokemon image cache write failed: ${error.message}`);
    }
    return image;
  } catch (error) {
    console.warn(`image load failed: ${url}`);
    return readPokemonImageCache_(cacheKey);
  }
}

function applyBackground(widget, primaryType) {
  const gradient = new LinearGradient();
  const colors = primaryType && Array.isArray(primaryType.colors)
    ? primaryType.colors
    : ["#0F766E", "#111111"];

  gradient.colors = [new Color(colors[0]), new Color(colors[1])];
  gradient.locations = [0, 1];
  widget.backgroundGradient = gradient;
}

function applyAccessoryBackground(widget) {
  const gradient = new LinearGradient();
  gradient.colors = [
    new Color("#111111"),
    new Color("#111111"),
  ];
  gradient.locations = [0, 1];
  widget.backgroundGradient = gradient;
}

function sanitizeText(value) {
  return String(value || "").trim().replace(/[\n\f]/g, " ");
}

function capitalizeText(value) {
  const text = String(value || "");
  return text ? text.charAt(0).toUpperCase() + text.slice(1) : "Pokemon";
}

function formatDate(date) {
  return `${date.getMonth() + 1}/${date.getDate()} ${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
}

function isExpandedFamily_(family) {
  return family === "large" || family === "extraLarge";
}

function getPokemonCacheDirectory_() {
  const fileManager = FileManager.local();
  const directory = fileManager.joinPath(fileManager.libraryDirectory(), CACHE_DIR);

  if (!fileManager.fileExists(directory)) {
    fileManager.createDirectory(directory, true);
  }

  return { fileManager, directory };
}

function prunePokemonCache_() {
  const cache = getPokemonCacheDirectory_();
  const expirationMillis = CACHE_MAX_AGE_DAYS * 24 * 60 * 60 * 1000;
  const now = Date.now();
  let names = [];

  try {
    names = cache.fileManager.listContents(cache.directory) || [];
  } catch (error) {
    console.warn(`cache list failed: ${error.message}`);
    return;
  }

  const entries = names.map(function(name) {
    const path = cache.fileManager.joinPath(cache.directory, name);
    let modifiedAt = new Date(0);

    try {
      modifiedAt = cache.fileManager.modificationDate(path) || new Date(0);
    } catch (error) {
      modifiedAt = new Date(0);
    }

    return {
      path: path,
      modifiedAt: modifiedAt,
    };
  });

  entries.forEach(function(entry) {
    if (now - entry.modifiedAt.getTime() > expirationMillis) {
      removeCacheFile_(cache.fileManager, entry.path);
    }
  });

  const activeEntries = entries
    .filter(function(entry) {
      return cache.fileManager.fileExists(entry.path);
    })
    .sort(function(a, b) {
      return b.modifiedAt.getTime() - a.modifiedAt.getTime();
    });

  activeEntries.slice(CACHE_MAX_CACHE_FILE_COUNT).forEach(function(entry) {
    removeCacheFile_(cache.fileManager, entry.path);
  });
}

function removeCacheFile_(fileManager, path) {
  try {
    if (fileManager.fileExists(path)) {
      fileManager.remove(path);
    }
  } catch (error) {
    console.warn(`cache remove failed: ${error.message}`);
  }
}

function writePokemonCache_(key, model) {
  const cache = getPokemonCacheDirectory_();
  const path = cache.fileManager.joinPath(cache.directory, `${key}.json`);
  cache.fileManager.writeString(path, JSON.stringify(model));
}

function readPokemonCache_(key) {
  const cache = getPokemonCacheDirectory_();
  const path = cache.fileManager.joinPath(cache.directory, `${key}.json`);

  if (!cache.fileManager.fileExists(path)) {
    return null;
  }

  try {
    const model = JSON.parse(cache.fileManager.readString(path));
    model.syncedAt = model.syncedAt ? new Date(model.syncedAt) : new Date();
    return model;
  } catch (error) {
    return null;
  }
}

function writePokemonImageCache_(key, image) {
  const cache = getPokemonCacheDirectory_();
  const path = cache.fileManager.joinPath(cache.directory, `${key}.png`);
  cache.fileManager.writeImage(path, image);
}

function readPokemonImageCache_(key) {
  const cache = getPokemonCacheDirectory_();
  const path = cache.fileManager.joinPath(cache.directory, `${key}.png`);

  if (!cache.fileManager.fileExists(path)) {
    return null;
  }

  try {
    return cache.fileManager.readImage(path);
  } catch (error) {
    return null;
  }
}

function sanitizeCacheKey(value) {
  return String(value || "")
    .toLowerCase()
    .replace(/[^a-z0-9_-]+/g, "_");
}

function normalizePokemonPool_(value) {
  if (Array.isArray(value)) {
    return value.map(normalizePokemonIdentifier_).filter(Boolean);
  }

  return String(value || "")
    .split(",")
    .map(normalizePokemonIdentifier_)
    .filter(Boolean)
    .filter(function(item, index, array) {
      return array.indexOf(item) === index;
    });
}

function normalizePokemonIdentifier_(value) {
  const text = String(value || "").trim().toLowerCase();
  if (!text) {
    return "";
  }

  if (/^\d+$/.test(text)) {
    return text;
  }

  if (/^[a-z0-9-]+$/.test(text)) {
    return text;
  }

  return "";
}

function createErrorWidget(error) {
  const widget = new ListWidget();
  widget.setPadding(12, 12, 12, 12);
  widget.backgroundColor = new Color(COLORS.dark);

  const title = widget.addText("Pokemon API エラー");
  title.font = Font.boldSystemFont(16);
  title.textColor = new Color(COLORS.white);

  widget.addSpacer(6);

  const message = widget.addText(String(error && error.message ? error.message : error));
  message.font = Font.systemFont(10);
  message.textColor = new Color(COLORS.light);
  message.lineLimit = 6;
  message.minimumScaleFactor = 0.7;

  return widget;
}

main().catch(async (error) => {
  console.error(error);

  const widget = createErrorWidget(error);
  Script.setWidget(widget);

  if (!config.runsInWidget) {
    await presentWidgetForFamily_(widget, config.widgetFamily || "medium");
  }

  Script.complete();
});

注意事項

このウィジェットは非公式の個人制作物です。

PokeAPIの提供状況やデータ構造の変更により、動作しなくなる可能性があります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?