+
= T | undefined | null;
const registryStore = useRegistryStore();
diff --git a/src/components/address/AddressHeader.vue b/src/components/address/AddressHeader.vue
index 3b8a452..a156dc1 100644
--- a/src/components/address/AddressHeader.vue
+++ b/src/components/address/AddressHeader.vue
@@ -68,7 +68,7 @@ onBeforeUnmount(() => {
const qrAddress = computed(() =>
normalizeDisplayAddress(props.address, {
removePrefix: false,
- }),
+ }) || "",
);
const displayAddress = computed(() => normalizeDisplayAddress(props.address));
const addressType = computed(() => getAddressType(qrAddress.value));
diff --git a/src/components/address/AddressTransaction.vue b/src/components/address/AddressTransaction.vue
index 01c3c90..c0e28c2 100644
--- a/src/components/address/AddressTransaction.vue
+++ b/src/components/address/AddressTransaction.vue
@@ -25,29 +25,24 @@
diff --git a/src/components/Transaction/TransactionList.vue b/src/components/Transaction/TransactionList.vue
index 90a16c2..4b3335a 100644
--- a/src/components/Transaction/TransactionList.vue
+++ b/src/components/Transaction/TransactionList.vue
@@ -106,7 +106,7 @@ export type Transactions = Array<{
diff --git a/src/components/token/Address.vue b/src/components/token/Address.vue
index 303bcef..2a003e8 100644
--- a/src/components/token/Address.vue
+++ b/src/components/token/Address.vue
@@ -66,6 +66,7 @@ const addressList = computed(() => {
([lockingBytecode, amount]) => {
const address = formatLockingBytecodeAddress(
lockingBytecode.substring(2),
+ { tokenCategory: `\\x${props.category}` },
);
if (typeof address !== "string") {
return [];
diff --git a/src/components/token/Child.vue b/src/components/token/Child.vue
index 8c0eb39..de2555c 100644
--- a/src/components/token/Child.vue
+++ b/src/components/token/Child.vue
@@ -81,6 +81,7 @@ const childNfts = computed(() => {
const commitment = output.nonfungible_token_commitment?.substring(2) || "";
const address = formatLockingBytecodeAddress(
output.locking_bytecode.substring(2),
+ { tokenCategory: `\\x${props.category}` },
);
return {
@@ -112,6 +113,7 @@ const outputs = computed(() => {
// Convert locking bytecode to cash address
const address = formatLockingBytecodeAddress(
output.locking_bytecode.substring(2),
+ { tokenCategory: `\\x${props.category}` },
);
// Get nonfungible token commitment
const commitment = output.nonfungible_token_commitment?.substring(2);
diff --git a/src/hooks/addressDisplay.ts b/src/hooks/addressDisplay.ts
index 7c979cc..d66f86d 100644
--- a/src/hooks/addressDisplay.ts
+++ b/src/hooks/addressDisplay.ts
@@ -1,62 +1,107 @@
+import {
+ Base58AddressFormatVersion,
+ base58AddressToLockingBytecode,
+ cashAddressToLockingBytecode,
+ lockingBytecodeToCashAddress,
+} from "@bitauth/libauth";
+import { type InferOutput, picklist, safeParse } from "valibot";
import { useStorage } from "~/hooks/storage";
import {
addPrefixToAddress,
- addressToLockingBytecodeHex,
+ getAddressType,
removeAddressPrefix,
} from "~/module/bitcoin";
-import { useStateStore } from "~/store";
+import { useStateStore } from "~/store/state";
+import type { Utxo } from "~/types";
+
+const addressDisplayModeSchema = picklist(["auto", "token", "regular"]);
+export type AddressDisplayMode = InferOutput;
-export type AddressDisplayMode = "token" | "regular";
+export function useAddressDisplayPreference() {
+ const mode = useStorage("addressDisplayMode", "auto");
+ // Older versions also stored raw strings. useStorage reads both forms;
+ // validate here before a persisted value can control address encoding.
+ const saved = safeParse(addressDisplayModeSchema, mode.value);
+ mode.value = saved.success ? saved.output : "auto";
+ return mode;
+}
-export const addressDisplayMode = useStorage(
- "addressDisplayMode",
- "token",
-);
+export const addressDisplayMode = useAddressDisplayPreference();
type AddressFormatOptions = {
removePrefix?: boolean;
+ tokenCategory?: Utxo["token_category"];
};
-const withDefaultOptions = (opts?: AddressFormatOptions) => ({
- removePrefix: opts?.removePrefix ?? true,
-});
-
-export const formatLockingBytecodeAddress = (
+export function formatLockingBytecodeAddress(
lockingBytecodeHex: string,
opts?: AddressFormatOptions,
-) => {
- const stateStore = useStateStore();
- const tokenSupport = addressDisplayMode.value === "token";
- const address = stateStore.lockingBytecodeHexToCashAddress(
+) {
+ const tokenSupport = {
+ auto: Boolean(opts?.tokenCategory),
+ token: true,
+ regular: false,
+ }[addressDisplayMode.value];
+ const address = useStateStore().lockingBytecodeHexToCashAddress(
lockingBytecodeHex,
tokenSupport,
);
- if (typeof address !== "string") return;
- const options = withDefaultOptions(opts);
- return options.removePrefix ? removeAddressPrefix(address) : address;
-};
+ if (!address) return;
+ return opts?.removePrefix === false ? address : removeAddressPrefix(address);
+}
-export const normalizeDisplayAddress = (
+// The input is a previous output (outpoint) for "from", or a new output for
+// "to". Never infer token presence from the FT amount or address history.
+export function formatUtxoAddress(
+ utxo: Pick,
+) {
+ const bytecode = utxo.locking_bytecode.startsWith("\\x")
+ ? utxo.locking_bytecode.substring(2)
+ : utxo.locking_bytecode;
+ const fullAddress = formatLockingBytecodeAddress(bytecode, {
+ removePrefix: false,
+ tokenCategory: utxo.token_category,
+ });
+ if (!fullAddress) return;
+ const address = removeAddressPrefix(fullAddress);
+ return {
+ fullAddress,
+ address,
+ addressType: getAddressType(fullAddress),
+ url: `/address/${address}`,
+ };
+}
+
+export function normalizeDisplayAddress(
address: string,
- opts?: AddressFormatOptions,
-) => {
- const options = withDefaultOptions(opts);
- const lockingBytecodeHex = addressToLockingBytecodeHex(address);
-
- if (lockingBytecodeHex) {
- const convertedAddress = formatLockingBytecodeAddress(
- lockingBytecodeHex,
- options,
- );
- if (typeof convertedAddress === "string") {
- return convertedAddress;
- }
- }
-
- if (options.removePrefix) {
- return removeAddressPrefix(address);
- }
-
- return addPrefixToAddress(address);
-};
+ opts?: Pick,
+) {
+ const legacy = base58AddressToLockingBytecode(address);
+ const decoded =
+ typeof legacy === "string"
+ ? cashAddressToLockingBytecode(addPrefixToAddress(address))
+ : {
+ bytecode: legacy.bytecode,
+ prefix:
+ legacy.version === Base58AddressFormatVersion.p2pkhTestnet ||
+ legacy.version === Base58AddressFormatVersion.p2sh20Testnet
+ ? ("bchtest" as const)
+ : ("bitcoincash" as const),
+ tokenSupport: false,
+ };
+ if (typeof decoded === "string") return address;
+
+ // An address page has no single UTXO. In auto mode preserve the incoming
+ // encoding (including its network) so following a link retains QR semantics.
+ const tokenSupport = {
+ auto: decoded.tokenSupport,
+ token: true,
+ regular: false,
+ }[addressDisplayMode.value];
+ const encoded = lockingBytecodeToCashAddress({ ...decoded, tokenSupport });
+ if (typeof encoded === "string") return address;
+ return opts?.removePrefix === false
+ ? encoded.address
+ : removeAddressPrefix(encoded.address);
+}
diff --git a/src/pages/settings/index.vue b/src/pages/settings/index.vue
index 47d5a0e..88c300a 100644
--- a/src/pages/settings/index.vue
+++ b/src/pages/settings/index.vue
@@ -72,66 +72,7 @@
{{ $t("address_display_format") }}
-
-
-
-
-
+
@@ -145,6 +86,5 @@
diff --git a/src/pages/token/[category].vue b/src/pages/token/[category].vue
index 2004223..a412c99 100644
--- a/src/pages/token/[category].vue
+++ b/src/pages/token/[category].vue
@@ -188,7 +188,9 @@ const tokenInfo = computed(() => {
? null
: Number(reservedSupply.value);
const ownerAddress =
- lockingBytecode && formatLockingBytecodeAddress(lockingBytecode);
+ lockingBytecode && formatLockingBytecodeAddress(lockingBytecode, {
+ tokenCategory: `\\x${category.value}`,
+ });
const items: contentWarpItem[] = [
{
diff --git a/tests/address-components.test.ts b/tests/address-components.test.ts
new file mode 100644
index 0000000..0a32844
--- /dev/null
+++ b/tests/address-components.test.ts
@@ -0,0 +1,26 @@
+import { expect, test } from "bun:test";
+import { fileURLToPath } from "node:url";
+
+test("Vue address integration regressions", async () => {
+ // Nuxt composables are process globals in these Bun tests. Isolate the Vue
+ // compiler and network stubs from the existing store and USD-price tests.
+ const fixture = fileURLToPath(
+ new URL("./fixtures/address-components.ts", import.meta.url),
+ );
+ const child = Bun.spawn([process.execPath, "test", fixture], {
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ const [stdout, stderr, exitCode] = await Promise.all([
+ new Response(child.stdout).text(),
+ new Response(child.stderr).text(),
+ child.exited,
+ ]);
+ expect({
+ exitCode,
+ output: exitCode === 0 ? "passed" : stdout + stderr,
+ }).toEqual({
+ exitCode: 0,
+ output: "passed",
+ });
+});
diff --git a/tests/address-display.test.ts b/tests/address-display.test.ts
new file mode 100644
index 0000000..df20807
--- /dev/null
+++ b/tests/address-display.test.ts
@@ -0,0 +1,237 @@
+import { afterAll, beforeEach, describe, expect, test } from "bun:test";
+import {
+ binToHex,
+ cashAddressToLockingBytecode,
+ encodeBase58Address,
+ hexToBin,
+} from "@bitauth/libauth";
+import { createPinia, setActivePinia } from "pinia";
+import { computed, effectScope, nextTick, ref, watch } from "vue";
+
+Object.assign(globalThis, {
+ computed,
+ ref,
+ watch,
+ gql: (source: string) => source,
+ useSubscription: () => ({ result: ref() }),
+});
+const {
+ addressDisplayMode,
+ formatLockingBytecodeAddress,
+ formatUtxoAddress,
+ normalizeDisplayAddress,
+ useAddressDisplayPreference,
+} = await import("../src/hooks/addressDisplay");
+const { useStateStore } = await import("../src/store/state");
+
+const scripts = [
+ { bytecode: `76a914${"12".repeat(20)}88ac`, label: "P2PKH" },
+ { bytecode: `a914${"12".repeat(20)}87`, label: "P2SH" },
+ { bytecode: `aa20${"12".repeat(32)}87`, label: "P2SH" },
+] as const;
+const category = `\\x${"34".repeat(32)}` as const;
+const holdings = [
+ { name: "BCH only", token_category: null, fungible_token_amount: "0" },
+ { name: "missing category", fungible_token_amount: "500" },
+ { name: "FT", token_category: category, fungible_token_amount: "100" },
+ {
+ name: "NFT without FTs",
+ token_category: category,
+ fungible_token_amount: "0",
+ nonfungible_token_capability: "none",
+ nonfungible_token_commitment: "\\x",
+ },
+];
+
+beforeEach(() => {
+ setActivePinia(createPinia());
+ addressDisplayMode.value = "auto";
+});
+
+for (const mode of ["auto", "token", "regular"] as const) {
+ for (const network of ["mainnet", "chipnet"] as const) {
+ for (const { bytecode, label } of scripts) {
+ for (const holding of holdings) {
+ test(`${mode} ${network} ${bytecode.slice(0, 6)} ${holding.name}`, () => {
+ addressDisplayMode.value = mode;
+ useStateStore().network = network;
+ const output = { ...holding, locking_bytecode: `\\x${bytecode}` };
+ const result = formatUtxoAddress(output);
+ expect(result).toBeDefined();
+ if (!result) throw new Error("Expected a supported address");
+ const decoded = cashAddressToLockingBytecode(result.fullAddress);
+ if (typeof decoded === "string") throw new Error(decoded);
+ expect(binToHex(decoded.bytecode)).toBe(bytecode);
+ expect(decoded.prefix).toBe(
+ network === "mainnet" ? "bitcoincash" : "bchtest",
+ );
+ expect(decoded.tokenSupport).toBe(
+ mode === "token" ||
+ (mode === "auto" && Boolean(output.token_category)),
+ );
+ // Script labels must never imply token holdings, even under override.
+ expect(result.addressType).toBe(label);
+ expect(
+ formatUtxoAddress({ ...output, locking_bytecode: bytecode }),
+ ).toEqual(result);
+
+ // Copy text and the link destination lead to the same full QR payload.
+ const destination = result.url.slice("/address/".length);
+ expect(destination).toBe(result.address);
+ expect(
+ normalizeDisplayAddress(destination, { removePrefix: false }),
+ ).toBe(result.fullAddress);
+ expect(normalizeDisplayAddress(destination)).toBe(result.address);
+ });
+ }
+ }
+ }
+}
+
+test("the same address can have independent BCH-only and token UTXOs", () => {
+ const locking_bytecode = scripts[0].bytecode;
+ const token = formatUtxoAddress({
+ locking_bytecode,
+ token_category: category,
+ });
+ const regular = formatUtxoAddress({ locking_bytecode });
+ expect(regular?.address).not.toBe(token?.address);
+ expect(formatUtxoAddress({ locking_bytecode })).toEqual(regular);
+ expect(formatLockingBytecodeAddress(locking_bytecode)).toBe(regular?.address);
+ const reactiveAddress = computed(() =>
+ formatUtxoAddress({ locking_bytecode }),
+ );
+ expect(reactiveAddress.value).toEqual(regular);
+ addressDisplayMode.value = "token";
+ expect(reactiveAddress.value).toEqual(token);
+ addressDisplayMode.value = "auto";
+ expect(reactiveAddress.value).toEqual(regular);
+});
+
+test("address pages retain the incoming network and encoding independently of selected network", () => {
+ useStateStore().network = "chipnet";
+ const source = formatUtxoAddress({
+ locking_bytecode: scripts[2].bytecode,
+ token_category: category,
+ });
+ if (!source) throw new Error("Expected P2SH32 address");
+ useStateStore().network = "mainnet";
+ expect(normalizeDisplayAddress(source.address, { removePrefix: false })).toBe(
+ source.fullAddress,
+ );
+ addressDisplayMode.value = "regular";
+ const regular = cashAddressToLockingBytecode(
+ normalizeDisplayAddress(source.address, { removePrefix: false }),
+ );
+ if (typeof regular === "string") throw new Error(regular);
+ expect(regular.prefix).toBe("bchtest");
+ expect(regular.tokenSupport).toBe(false);
+ expect(binToHex(regular.bytecode)).toBe(scripts[2].bytecode);
+});
+
+for (const type of [
+ "p2pkh",
+ "p2pkhTestnet",
+ "p2sh20",
+ "p2sh20Testnet",
+] as const) {
+ test(`legacy ${type} becomes regular CashAddr on its original network`, () => {
+ const legacy = encodeBase58Address(type, hexToBin("12".repeat(20)));
+ const fullAddress = normalizeDisplayAddress(legacy, {
+ removePrefix: false,
+ });
+ const decoded = cashAddressToLockingBytecode(fullAddress);
+ if (typeof decoded === "string") throw new Error(decoded);
+ expect(decoded.prefix).toBe(
+ type.endsWith("Testnet") ? "bchtest" : "bitcoincash",
+ );
+ expect(decoded.tokenSupport).toBe(false);
+ addressDisplayMode.value = "token";
+ const token = cashAddressToLockingBytecode(
+ normalizeDisplayAddress(legacy, { removePrefix: false }),
+ );
+ if (typeof token === "string") throw new Error(token);
+ expect(binToHex(token.bytecode)).toBe(binToHex(decoded.bytecode));
+ expect(token.prefix).toBe(decoded.prefix);
+ expect(token.tokenSupport).toBe(true);
+ });
+}
+
+test("unsupported locking bytecode never becomes an address or link", () => {
+ for (const locking_bytecode of ["", "6a", "\\x6a", "51"]) {
+ expect(formatUtxoAddress({ locking_bytecode })).toBeUndefined();
+ }
+});
+
+describe("browser preference migration", () => {
+ const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
+ const previousStorage = Object.getOwnPropertyDescriptor(
+ globalThis,
+ "localStorage",
+ );
+ const values = new Map
();
+ const storage = {
+ getItem: (key: string) => values.get(key) ?? null,
+ setItem: (key: string, value: string) => values.set(key, value),
+ };
+
+ afterAll(() => {
+ for (const [key, descriptor] of [
+ ["window", previousWindow],
+ ["localStorage", previousStorage],
+ ] as const) {
+ if (descriptor) Object.defineProperty(globalThis, key, descriptor);
+ else Reflect.deleteProperty(globalThis, key);
+ }
+ });
+
+ for (const saved of [
+ undefined,
+ '"auto"',
+ '"token"',
+ '"regular"',
+ "token",
+ "regular",
+ '"invalid"',
+ "broken-json{",
+ "null",
+ "false",
+ "42",
+ "{}",
+ "[]",
+ ]) {
+ test(`validates and persists saved value ${saved}`, async () => {
+ values.clear();
+ Object.assign(globalThis, {
+ window: { localStorage: storage },
+ localStorage: storage,
+ });
+ if (saved !== undefined) values.set("addressDisplayMode", saved);
+ const scope = effectScope();
+ try {
+ const preference = scope.run(useAddressDisplayPreference);
+ if (!preference) throw new Error("Expected a preference ref");
+ const expected =
+ saved === '"token"' || saved === "token"
+ ? "token"
+ : saved === '"regular"' || saved === "regular"
+ ? "regular"
+ : "auto";
+ expect(preference.value).toBe(expected);
+ await nextTick();
+ if (saved !== undefined && expected === "auto" && saved !== '"auto"') {
+ expect(values.get("addressDisplayMode")).toBe('"auto"');
+ }
+ preference.value = expected === "token" ? "regular" : "token";
+ await nextTick();
+ expect(values.get("addressDisplayMode")).toBe(
+ JSON.stringify(preference.value),
+ );
+ const reloaded = scope.run(useAddressDisplayPreference);
+ expect(reloaded?.value).toBe(preference.value);
+ } finally {
+ scope.stop();
+ }
+ });
+ }
+});
diff --git a/tests/fixtures/address-components.ts b/tests/fixtures/address-components.ts
new file mode 100644
index 0000000..5a4131d
--- /dev/null
+++ b/tests/fixtures/address-components.ts
@@ -0,0 +1,180 @@
+import { beforeEach, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { cashAddressToLockingBytecode } from "@bitauth/libauth";
+import { compileScript, parse } from "@vue/compiler-sfc";
+import { renderToString } from "@vue/server-renderer";
+import { plugin } from "bun";
+import { createPinia, setActivePinia } from "pinia";
+import {
+ computed,
+ createSSRApp,
+ defineComponent,
+ h,
+ onBeforeUnmount,
+ onMounted,
+ reactive,
+ ref,
+ shallowReactive,
+ useId,
+ watch,
+} from "vue";
+
+// Compile the actual Vue components, rather than duplicating their mapping logic.
+plugin({
+ name: "vue-address-regressions",
+ setup(build) {
+ build.onLoad({ filter: /\.vue$/ }, ({ path }) => {
+ const { descriptor } = parse(readFileSync(path, "utf8"), {
+ filename: path,
+ });
+ const script = compileScript(descriptor, {
+ id: path,
+ inlineTemplate: true,
+ });
+ return { contents: script.content, loader: "ts" };
+ });
+ },
+});
+Object.assign(globalThis, {
+ computed,
+ ref,
+ reactive,
+ shallowReactive,
+ watch,
+ onMounted,
+ onBeforeUnmount,
+ useId,
+ gql: (source: string) => source,
+ useSubscription: () => ({ result: ref() }),
+ useQuery: () => ({ onResult: () => undefined }),
+ useFetch: () => ({ data: ref() }),
+});
+const { addressDisplayMode } = await import("../../src/hooks/addressDisplay");
+const { default: TransactionList } = await import(
+ "../../src/components/Transaction/TransactionList.vue"
+);
+const { default: TransactionListOperation } = await import(
+ "../../src/components/Transaction/TransactionListOperation.vue"
+);
+const { default: AddressHeader } = await import(
+ "../../src/components/address/AddressHeader.vue"
+);
+const { default: AddressFormatSettings } = await import(
+ "../../src/components/AddressFormatSettings.vue"
+);
+
+const locking_bytecode = `\\x76a914${"12".repeat(20)}88ac`;
+const category = `\\x${"34".repeat(32)}` as const;
+const bch = { locking_bytecode, value_satoshis: "1000", token_category: null };
+const nft = {
+ ...bch,
+ token_category: category,
+ fungible_token_amount: "0",
+ nonfungible_token_capability: "none" as const,
+ nonfungible_token_commitment: "\\x" as const,
+};
+
+beforeEach(() => {
+ setActivePinia(createPinia());
+ addressDisplayMode.value = "auto";
+});
+
+for (const mode of ["auto", "token", "regular"] as const) {
+ for (const direction of ["spend NFT", "receive FT"] as const) {
+ test(`actual transaction copy, link and destination QR stay consistent: ${mode}, ${direction}`, async () => {
+ addressDisplayMode.value = mode;
+ const copies: { text: string; url?: string; copy: boolean }[] = [];
+ const qrPayloads: string[] = [];
+ const app = createSSRApp(TransactionList, {
+ transactions: [
+ {
+ hash: `\\x${"56".repeat(32)}`,
+ is_coinbase: false,
+ // Same script, different token data on the spent and created output.
+ inputs: [{ outpoint: direction === "spend NFT" ? nft : bch }],
+ outputs: [
+ direction === "spend NFT"
+ ? bch
+ : { ...nft, fungible_token_amount: "100" },
+ { locking_bytecode: "\\x6a0161", value_satoshis: "0" },
+ ],
+ },
+ ],
+ });
+ app.config.globalProperties.$t = (key: string) => key;
+ app.component("TransactionListOperation", TransactionListOperation);
+ app.component(
+ "SliderUpDown",
+ defineComponent({
+ props: { active: Boolean },
+ setup:
+ (_, { slots }) =>
+ () =>
+ slots.default?.(),
+ }),
+ );
+ app.component(
+ "TransactionOperationToken",
+ defineComponent({ setup: () => () => null }),
+ );
+ const Copy = defineComponent({
+ props: {
+ text: { type: String, default: "" },
+ url: String,
+ copy: Boolean,
+ },
+ setup(props) {
+ copies.push({ text: props.text, url: props.url, copy: props.copy });
+ return () => h("span", props.text);
+ },
+ });
+ app.component("BaseCopy", Copy);
+ await renderToString(app);
+ const addresses = copies.filter(({ url }) =>
+ url?.startsWith("/address/"),
+ );
+ expect(addresses).toHaveLength(4); // two summaries and two expanded rows
+ const inputSupport =
+ mode === "token" || (mode === "auto" && direction === "spend NFT");
+ const outputSupport =
+ mode === "token" || (mode === "auto" && direction === "receive FT");
+ const expectedSupport = [
+ inputSupport,
+ outputSupport,
+ inputSupport,
+ outputSupport,
+ ];
+ for (const [index, copy] of addresses.entries()) {
+ expect(copy.url).toBe(`/address/${copy.text}`);
+ const destination = createSSRApp(AddressHeader, { address: copy.text });
+ destination.component("BaseCopy", Copy);
+ destination.component(
+ "VueQrCode",
+ defineComponent({
+ props: { content: { type: String, required: true } },
+ setup(props) {
+ qrPayloads.push(props.content);
+ return () => null;
+ },
+ }),
+ );
+ await renderToString(destination);
+ const decoded = cashAddressToLockingBytecode(qrPayloads[index] || "");
+ if (typeof decoded === "string") throw new Error(decoded);
+ expect(decoded.tokenSupport).toBe(expectedSupport[index] === true);
+ expect(copies.at(-1)?.text).toBe(copy.text);
+ }
+ expect(addresses.slice(2).every(({ copy }) => copy)).toBe(true);
+ });
+ }
+}
+
+test("settings render three native radio choices with the effective preference selected", async () => {
+ for (const mode of ["auto", "token", "regular"] as const) {
+ addressDisplayMode.value = mode;
+ const html = await renderToString(createSSRApp(AddressFormatSettings));
+ expect(html.match(/type="radio"/g)).toHaveLength(3);
+ expect(html.match(/ checked/g)).toHaveLength(1);
+ expect(html.match(/]+checked>/)?.[0]).toContain(`value="${mode}"`);
+ }
+});
From a9bb934b996b8f7fe508f12013f9d0ffe51b7fc2 Mon Sep 17 00:00:00 2001
From: Salem Mohammed Shamakh <58360393+salemkode@users.noreply.github.com>
Date: Sat, 14 Nov 2026 23:10:32 +0300
Subject: [PATCH 4/4] fix: complete NFT galleries for collections and addresses
---
docs/nft-gallery.md | 65 ++++
src/components/NavPills.vue | 3 +-
src/components/address/AddressNFTs.vue | 88 +++--
src/components/token/Child.vue | 67 ++--
src/components/token/NFTGallery.vue | 126 ++++---
src/components/token/NFTImage.vue | 83 +++++
src/hooks/nftPagination.ts | 36 ++
src/module/chaingraph.ts | 6 +
tests/fixtures/nft-gallery.ts | 475 +++++++++++++++++++++++++
tests/nft-gallery.test.ts | 26 ++
tests/vue-fixture.ts | 119 +++++++
11 files changed, 969 insertions(+), 125 deletions(-)
create mode 100644 docs/nft-gallery.md
create mode 100644 src/components/token/NFTImage.vue
create mode 100644 src/hooks/nftPagination.ts
create mode 100644 tests/fixtures/nft-gallery.ts
create mode 100644 tests/nft-gallery.test.ts
create mode 100644 tests/vue-fixture.ts
diff --git a/docs/nft-gallery.md b/docs/nft-gallery.md
new file mode 100644
index 0000000..31742a8
--- /dev/null
+++ b/docs/nft-gallery.md
@@ -0,0 +1,65 @@
+# NFT gallery
+
+On a token collection page, choose **Grid View** above the child NFT list. On an
+address page, open **Cash token**, then choose **Grid View** above **Address NFTs**.
+**Table View** remains available in both contexts. The collection view preference
+continues to be saved by the token page; the address view starts as a table.
+
+The gallery shows up to 24 unspent NFT outputs per page. Previous/next buttons
+load adjacent pages; switching views, addresses, collections, or networks returns
+to the first page. Queries use a transaction-hash/output-index ordering and fetch
+one extra output to detect another page. Holdings can change between requests;
+this is offset pagination over current holdings, not a historical snapshot.
+The existing child collection query excludes minting outputs; address NFTs include
+them. This change does not alter those filters or token totals.
+
+Each card shows its category, exact hexadecimal commitment, capability, owner
+when the locking script can be represented as a CashAddr, and output outpoint.
+Category, owner, and output link to their explorer pages. Two NFTs with the same
+commitment are separate cards because their outpoints differ. An empty commitment
+is a valid NFT state and is labeled **Empty commitment**.
+
+Collection names and artwork follow the selected registry. Artwork uses the registered full image, then the token icon, then a generated
+category placeholder. Image and metadata loading are labeled separately. Missing
+metadata does not remove the NFT or hide its on-chain details. A generated
+placeholder is labeled **Image unavailable** and cannot open an image preview.
+
+Activate **View token image** with a pointer, Enter, or Space after artwork loads.
+The full image opens in a native modal dialog. Close it using **Close**, Escape,
+or the backdrop. The browser confines focus to the dialog and restores it to the
+trigger on dismissal. No animation is required. The card layout uses the existing
+slate/zinc surfaces, emerald focus/link colors, and responsive grid.
+
+## Regression checks
+
+Run from the repository root:
+
+```bash
+bun install --frozen-lockfile
+bun run lint
+bun run test
+bun run lint:type
+bun run build
+```
+
+`tests/nft-gallery.test.ts` compiles the actual Vue components using the Vue
+compiler and runs them through a small Vue host fixture without adding a browser
+test dependency. It checks duplicate-commitment reconciliation, missing metadata,
+empty commitments, query binding and retry, first/last pages and lookahead,
+context/view/network resets, disabled loading navigation, image fallback/reset,
+and image-dialog open/close event handlers.
+
+These fixtures do not verify browser focus management or CSS layout. For browser
+QA, use an allowed built-in browser session and verify:
+
+- A collection and an address with NFTs switch between both views. Navigate
+ forward/back, including the final partial page; no lookahead card is rendered.
+- Distinct outputs with identical commitments stay separate, including after
+ pagination. Confirm full commitments and owner/category/output destinations.
+- A metadata-free NFT remains visible with on-chain details. Check a failed image,
+ an icon-only NFT, and a fully missing image; the placeholder does not loop.
+- Query loading hides stale cards, an empty result is explained, and a failed
+ query offers **Try again** and a previous-page action when applicable.
+- At narrow and desktop widths in light/dark themes, long commitments and names
+ stay within cards. Keyboard focus remains visible; Enter/Space opens artwork,
+ Tab stays within the dialog, Escape closes it, and focus returns to the trigger.
diff --git a/src/components/NavPills.vue b/src/components/NavPills.vue
index d9a7263..55e4b0c 100644
--- a/src/components/NavPills.vue
+++ b/src/components/NavPills.vue
@@ -4,7 +4,8 @@
v-for="(item, index) in props.items"
:key="index"
type="button"
- class="flex-1 py-2 px-3 sm:px-4 rounded-xl text-xs sm:text-sm font-semibold text-center transition-all cursor-pointer select-none"
+ :aria-pressed="navItem === index"
+ class="flex-1 py-2 px-3 sm:px-4 rounded-xl text-xs sm:text-sm font-semibold text-center transition-all motion-reduce:transition-none cursor-pointer select-none focus-visible:outline-2 focus-visible:outline-emerald-500"
:class="
navItem === index
? 'bg-white dark:bg-zinc-800 text-slate-900 dark:text-white shadow-xs border border-slate-200/60 dark:border-zinc-700/60'
diff --git a/src/components/address/AddressNFTs.vue b/src/components/address/AddressNFTs.vue
index 38c5084..ebb0da7 100644
--- a/src/components/address/AddressNFTs.vue
+++ b/src/components/address/AddressNFTs.vue
@@ -1,30 +1,62 @@
-
+
+
+
+
+
diff --git a/src/components/token/Child.vue b/src/components/token/Child.vue
index de2555c..dadb19a 100644
--- a/src/components/token/Child.vue
+++ b/src/components/token/Child.vue
@@ -8,18 +8,20 @@
:has-next-page="!!hasNextPage"
:loading="loading"
:error="error?.message"
- @next="offset += pageSize"
- @previous="offset -= pageSize"
+ @next="next(loading, hasNextPage && !error)"
+ @previous="previous(loading)"
/>
@@ -27,29 +29,31 @@
import type { GetTokenChildQuery } from "@/module/chaingraph";
import { GetTokenChild } from "@/module/chaingraph";
import { formatLockingBytecodeAddress } from "~/hooks/addressDisplay";
+import { nftPage, useNftPagination } from "~/hooks/nftPagination";
import { useStateStore } from "~/store";
import type { IdentitySnapshot, tableColumn } from "~/types/index.js";
import NFTGallery, { type ChildNftItem } from "./NFTGallery.vue";
const stateStore = useStateStore();
-const offset = ref(0);
const props = defineProps<{
category: string;
- identitySnapshot?: IdentitySnapshot;
+ identitySnapshot?: IdentitySnapshot | null;
viewMode?: "table" | "grid";
}>();
const effectiveViewMode = computed(() =>
props.viewMode === "grid" ? "grid" : "table",
);
-const pageSize = computed(() => (effectiveViewMode.value === "grid" ? 24 : 8));
-const limit = computed(() => pageSize.value + 1);
+const { offset, pageSize, limit, next, previous } = useNftPagination(
+ () => `${stateStore.network}:${props.category}`,
+ () => effectiveViewMode.value,
+);
const variable = computed(() => ({
network: stateStore.network,
tokenCategory: `\\x${props.category}` as const,
offset: offset.value,
limit: limit.value,
}));
-const { result, loading, error } = useQuery(GetTokenChild, variable);
+const { result, loading, error, refetch } = useQuery(GetTokenChild, variable);
const types = computed(() => props.identitySnapshot?.token?.nfts?.parse.types);
const showTokenColumn = computed(() => {
@@ -64,52 +68,37 @@ const column = computed(() => {
}
return result;
});
-const hasNextPage = computed(() => {
- if (result.value) {
- return result.value.output.length === limit.value;
- }
- return false;
-});
+const page = computed(() => nftPage(result.value?.output || [], pageSize.value));
+const hasNextPage = computed(() => page.value.hasNextPage);
type ChildOutput = GetTokenChildQuery["output"][number];
-const childNfts = computed(() => {
- if (!result.value) {
- return [];
- }
+const childNfts = computed(() =>
+ page.value.items.flatMap((output) => {
+ if (!output.nonfungible_token_capability) return [];
- let items = result.value.output.map((output: ChildOutput) => {
const commitment = output.nonfungible_token_commitment?.substring(2) || "";
const address = formatLockingBytecodeAddress(
output.locking_bytecode.substring(2),
{ tokenCategory: `\\x${props.category}` },
);
- return {
+
+ return [{
+ id: `${output.transaction_hash.substring(2)}:${output.output_index}`,
category: props.category,
capability: output.nonfungible_token_capability,
commitment,
- address: typeof address === "string" ? address : undefined,
- name: types.value?.[commitment]?.name || "N/A",
- };
- });
-
- if (items.length === limit.value) {
- items = items.slice(0, -1);
- }
-
- return items;
-});
-
-watch(effectiveViewMode, () => {
- offset.value = 0;
-});
+ address,
+ }];
+ }),
+);
const outputs = computed(() => {
if (!result.value) {
return [];
}
- let items = result.value?.output.map((output: ChildOutput) => {
+ const items = page.value.items.map((output: ChildOutput) => {
// Convert locking bytecode to cash address
const address = formatLockingBytecodeAddress(
output.locking_bytecode.substring(2),
@@ -155,10 +144,6 @@ const outputs = computed(() => {
return item;
});
- // Remove last item if it reaches the limit
- if (items.length === limit.value) {
- items = items.slice(0, -1);
- }
return items;
});
diff --git a/src/components/token/NFTGallery.vue b/src/components/token/NFTGallery.vue
index 5beeb8d..0e430f6 100644
--- a/src/components/token/NFTGallery.vue
+++ b/src/components/token/NFTGallery.vue
@@ -1,90 +1,98 @@
-
-
-
-
- {{ $t("nft_gallery") }}
-
+
+
+
{{ $t("nft_gallery") }}
-
- {{ error }}
+
+
Could not load NFTs. Try again.
+
{{ error }}
+
-
-
-
-
-
-
+
+
+ Loading NFTs…
+
+
No NFTs found on this page.
+
+
+
+
+
+ {{ item.name }}
+ Loading metadata…
+ Metadata unavailable
+
+
+
- {{ $t("category") }}
+
-
-
- {{ item.name }}
+
+
- {{ $t("commitment") }}
+
+ - Empty commitment
-
-
-
- {{ $t("category") }}
-
-
-
-
- {{ $t("commitment") }}
-
-
+
+
- {{ $t("capability") }}
+ - {{ item.capability }}
-
-
+
+
- {{ $t("tokenstats_nft_owner") }}
+
+
+
+
- Output
+
+
+
+
-
-
-
+
diff --git a/src/components/token/NFTImage.vue b/src/components/token/NFTImage.vue
new file mode 100644
index 0000000..b06fbeb
--- /dev/null
+++ b/src/components/token/NFTImage.vue
@@ -0,0 +1,83 @@
+
+
+
+
Loading image…
+
Image unavailable
+
+
+
+
+
+
diff --git a/src/hooks/nftPagination.ts b/src/hooks/nftPagination.ts
new file mode 100644
index 0000000..13d8ffb
--- /dev/null
+++ b/src/hooks/nftPagination.ts
@@ -0,0 +1,36 @@
+import { computed, ref, watch } from "vue";
+
+// Fetch one extra output to detect the next page without a separate count query.
+export function useNftPagination(
+ context: () => string,
+ viewMode: () => string,
+) {
+ const offset = ref(0);
+ const pageSize = computed(() => (viewMode() === "grid" ? 24 : 8));
+ const limit = computed(() => pageSize.value + 1);
+
+ watch(
+ [context, viewMode],
+ () => {
+ offset.value = 0;
+ },
+ { flush: "sync" },
+ );
+
+ function next(loading: boolean, hasNextPage: boolean) {
+ if (!loading && hasNextPage) offset.value += pageSize.value;
+ }
+
+ function previous(loading: boolean) {
+ if (!loading) offset.value = Math.max(0, offset.value - pageSize.value);
+ }
+
+ return { offset, pageSize, limit, next, previous };
+}
+
+export function nftPage
(outputs: readonly T[], pageSize: number) {
+ return {
+ items: outputs.slice(0, pageSize),
+ hasNextPage: outputs.length > pageSize,
+ };
+}
diff --git a/src/module/chaingraph.ts b/src/module/chaingraph.ts
index a9c118a..ce0cbfc 100644
--- a/src/module/chaingraph.ts
+++ b/src/module/chaingraph.ts
@@ -406,6 +406,7 @@ export const GetTokenChild = gql(`
output(
limit: $limit
offset: $offset
+ order_by: [{ transaction_hash: asc }, { output_index: asc }]
where: {
transaction: {
block_inclusions: {
@@ -417,6 +418,8 @@ export const GetTokenChild = gql(`
_not: { spent_by: { transaction: { hash: { _gt: "" } } } }
}
) {
+ transaction_hash
+ output_index
locking_bytecode
nonfungible_token_capability
nonfungible_token_commitment
@@ -434,6 +437,7 @@ export const GetAddressNFTs = gql(`
search_output(
limit: $limit
offset: $offset
+ order_by: [{ transaction_hash: asc }, { output_index: asc }]
args: { locking_bytecode_hex: $lockingBytecode }
where: {
token_category: { _is_null: false }
@@ -446,6 +450,8 @@ export const GetAddressNFTs = gql(`
_not: { spent_by: { transaction: { hash: { _gt: "" } } } }
}
) {
+ transaction_hash
+ output_index
token_category
nonfungible_token_capability
nonfungible_token_commitment
diff --git a/tests/fixtures/nft-gallery.ts b/tests/fixtures/nft-gallery.ts
new file mode 100644
index 0000000..3b2e4b2
--- /dev/null
+++ b/tests/fixtures/nft-gallery.ts
@@ -0,0 +1,475 @@
+import { afterEach, describe, expect, mock, test } from "bun:test";
+import {
+ computed,
+ defineComponent,
+ effectScope,
+ h,
+ nextTick,
+ reactive,
+ ref,
+ toRef,
+ watchEffect,
+} from "vue";
+import { nftPage, useNftPagination } from "../../src/hooks/nftPagination";
+import type { IdentitySnapshot } from "../../src/types";
+import { dispatch, mountFixture, nodes, text } from "../vue-fixture";
+
+const network = reactive({ network: "mainnet" });
+const metadata = reactive({ loading: false, available: false });
+mock.module("../../src/store/index.ts", () => ({
+ useStateStore: () => network,
+ useRegistryStore: () => ({
+ getToken: () =>
+ metadata.available
+ ? {
+ loading: false,
+ token: {
+ name: "Fixture NFT",
+ icon: "https://example.com/icon.png",
+ image: "https://example.com/full.png",
+ },
+ }
+ : { loading: metadata.loading },
+ }),
+}));
+mock.module("../../src/module/utils.ts", () => ({
+ getHttpsUrl: (url: string) => url,
+ svgToBase64: (svg: string) => `data:image/svg+xml;base64,${btoa(svg)}`,
+}));
+
+mock.module("../../src/hooks/addressDisplay.ts", () => ({
+ formatLockingBytecodeAddress: (
+ _bytecode: string,
+ context?: { tokenCategory?: string },
+ ) => (context?.tokenCategory ? "zowner" : "qowner"),
+}));
+mock.module("../../src/hooks/authchains.ts", () => ({
+ useAuthChains: () => undefined,
+}));
+const fixtureOutputs = Array.from({ length: 25 }, (_, index) => ({
+ transaction_hash: `\\x${"01".repeat(32)}`,
+ output_index: String(index),
+ token_category: `\\x${"ab".repeat(32)}`,
+ nonfungible_token_commitment: "\\x00ff",
+ nonfungible_token_capability: "none",
+ locking_bytecode: "\\x76a914fixture88ac",
+}));
+const query = {
+ result: ref({ output: fixtureOutputs, search_output: fixtureOutputs }),
+ loading: ref(false),
+ error: ref(),
+ refetch: mock(),
+};
+const queryVariables = ref({ offset: 0, limit: 0 });
+Object.assign(globalThis, {
+ computed,
+ ref,
+ toRef,
+ gql: (source: string) => source,
+ useQuery: (
+ _document: unknown,
+ variables: { value: { offset: number; limit: number } },
+ ) => {
+ watchEffect(() => {
+ queryVariables.value = variables.value;
+ });
+ return query;
+ },
+});
+
+const { default: NFTGallery } = await import(
+ "../../src/components/token/NFTGallery.vue"
+);
+const { default: NFTImage } = await import(
+ "../../src/components/token/NFTImage.vue"
+);
+const { default: BasePagination } = await import(
+ "../../src/components/BasePagination.vue"
+);
+const { default: TokenChild } = await import(
+ "../../src/components/token/Child.vue"
+);
+const { default: AddressNFTs } = await import(
+ "../../src/components/address/AddressNFTs.vue"
+);
+const CopyFixture = defineComponent({
+ props: { text: String, url: String },
+ setup: (props) => () => h("a", { href: props.url }, props.text),
+});
+const cleanup = new Set<() => void>();
+afterEach(() => {
+ for (const unmount of cleanup) unmount();
+ cleanup.clear();
+ metadata.loading = false;
+ metadata.available = false;
+});
+
+function mountGallery(items = [nft("01", "0"), nft("01", "1")]) {
+ const events = { next: mock(), previous: mock(), retry: mock() };
+ const props = reactive({
+ identitySnapshot: undefined as IdentitySnapshot | null | undefined,
+ items,
+ loading: false,
+ error: "",
+ hasPrevPage: false,
+ hasNextPage: true,
+ onNext: events.next,
+ onPrevious: events.previous,
+ onRetry: events.retry,
+ });
+ const mounted = mountFixture(NFTGallery, props, {
+ BasePagination,
+ LoadingSpinner: { render: () => h("span", "spinner") },
+ BaseCopy: CopyFixture,
+ });
+ cleanup.add(mounted.unmount);
+ return { ...mounted, props, events };
+}
+
+function nft(hash: string, index: string) {
+ return {
+ id: `${hash.repeat(32)}:${index}`,
+ category: "ab".repeat(32),
+ commitment: "00ff",
+ capability: "none" as const,
+ address: "qowner",
+ };
+}
+
+describe("NFT gallery fixtures", () => {
+ test("identical commitments retain separate card and image state during a page update", async () => {
+ metadata.available = true;
+ const { root, props } = mountGallery();
+ const articles = nodes(root, "article");
+ expect(articles).toHaveLength(2);
+ props.items = [nft("01", "1"), nft("02", "0")];
+ await nextTick();
+ expect(nodes(root, "article")[0]).toBe(articles[1]);
+ expect(nodes(root, "article")[1]).not.toBe(articles[0]);
+ expect(nodes(root, "a").map((link) => link.props.href)).toContain(
+ `/token/${"ab".repeat(32)}`,
+ );
+ expect(nodes(root, "a").map((link) => link.props.href)).toContain(
+ "/address/qowner",
+ );
+ expect(text(root)).toContain("00ff");
+ expect(text(root)).toContain("none");
+ });
+
+ test("metadata unavailable and empty commitments do not hide NFTs", async () => {
+ const { root, props } = mountGallery([
+ { ...nft("01", "0"), commitment: "" },
+ ]);
+ expect(text(root)).toContain("Unnamed NFT");
+ expect(text(root)).toContain("Metadata unavailable");
+ expect(text(root)).toContain("Empty commitment");
+ metadata.loading = true;
+ await nextTick();
+ expect(text(root)).toContain("Loading metadata…");
+ expect(nodes(root, "article")).toHaveLength(1);
+ props.items = [];
+ await nextTick();
+ expect(text(root)).toContain("No NFTs found on this page.");
+ });
+
+ test("loading hides stale cards and blocks page actions; errors offer retry and previous", async () => {
+ const { root, props, events } = mountGallery();
+ props.loading = true;
+ await nextTick();
+ expect(nodes(root, "article")).toHaveLength(0);
+ expect(text(root)).toContain("Loading NFTs…");
+ expect(
+ nodes(root, "button").find(
+ (node) => node.props["aria-label"] === "Next page",
+ )?.props.disabled,
+ ).toBe(true);
+ props.loading = false;
+ props.error = "Indexer offline";
+ props.hasPrevPage = true;
+ await nextTick();
+ expect(text(root)).toContain("Indexer offline");
+ dispatch(
+ nodes(root, "button").find((node) => node.text === "Try again"),
+ "onClick",
+ );
+ expect(events.retry).toHaveBeenCalledTimes(1);
+ dispatch(
+ nodes(root, "button").find(
+ (node) => node.props["aria-label"] === "Previous page",
+ ),
+ "onClick",
+ );
+ expect(events.previous).toHaveBeenCalledTimes(1);
+ });
+ test("explicit missing selected metadata never falls back to an unrelated registry", async () => {
+ metadata.available = true;
+ const { root, props } = mountGallery();
+ expect(text(root)).toContain("Fixture NFT");
+ props.identitySnapshot = {
+ name: "Selected revision",
+ uris: { image: "https://example.com/selected.png" },
+ };
+ await nextTick();
+ expect(text(root)).toContain("Selected revision");
+ props.identitySnapshot = null;
+ await nextTick();
+ expect(text(root)).toContain("Metadata unavailable");
+ expect(text(root)).not.toContain("Fixture NFT");
+ expect(text(root)).not.toContain("Selected revision");
+ expect(nodes(root, "img")[0]?.props.src).toStartWith(
+ "data:image/svg+xml;base64,",
+ );
+ props.identitySnapshot = undefined;
+ await nextTick();
+ expect(text(root)).toContain("Fixture NFT");
+ });
+});
+
+describe("NFT image behavior", () => {
+ function mountImage() {
+ const props = reactive({
+ category: "ab".repeat(32),
+ name: "Fixture NFT",
+ image: "https://example.com/full.png",
+ icon: "https://example.com/icon.png",
+ });
+ const mounted = mountFixture(NFTImage, props);
+ cleanup.add(mounted.unmount);
+ return { ...mounted, props };
+ }
+
+ test("full artwork opens after load and closes by button or Escape", async () => {
+ const { root } = mountImage();
+ const trigger = nodes(root, "button")[0];
+ expect(trigger?.props.disabled).toBe(true);
+ dispatch(nodes(root, "img")[0], "onLoad");
+ await nextTick();
+ expect(trigger?.props.disabled).toBe(false);
+ dispatch(trigger, "onClick");
+ const dialog = nodes(root, "dialog")[0];
+ expect(dialog?.open).toBe(true);
+ expect(nodes(root, "img")[1]?.props.src).toBe(
+ "https://example.com/full.png",
+ );
+ dispatch(dialog, "onKeydown", { key: "Escape" });
+ expect(dialog?.open).toBe(false);
+ dispatch(trigger, "onClick");
+ dispatch(nodes(root, "button")[1], "onClick");
+ expect(dialog?.open).toBe(false);
+ });
+
+ test("changing only an inactive icon preserves loaded artwork and dialog readiness", async () => {
+ const { root, props } = mountImage();
+ dispatch(nodes(root, "img")[0], "onLoad");
+ await nextTick();
+ const image = nodes(root, "img")[0];
+ props.icon = "https://example.com/new-icon.png";
+ await nextTick();
+ expect(nodes(root, "img")[0]).toBe(image);
+ expect(nodes(root, "button")[0]?.props.disabled).toBe(false);
+ dispatch(nodes(root, "button")[0], "onClick");
+ expect(nodes(root, "dialog")[0]?.open).toBe(true);
+ dispatch(image, "onError");
+ await nextTick();
+ expect(nodes(root, "img")[0]?.props.src).toBe(props.icon);
+ expect(nodes(root, "button")[0]?.props.disabled).toBe(true);
+ expect(nodes(root, "dialog")[0]?.open).toBe(false);
+ dispatch(nodes(root, "img")[0], "onLoad");
+ await nextTick();
+ expect(nodes(root, "button")[0]?.props.disabled).toBe(false);
+ });
+
+ test("failed artwork falls back to icon, then a bounded generated placeholder; new URLs reset", async () => {
+ const { root, props } = mountImage();
+ dispatch(nodes(root, "img")[0], "onError");
+ await nextTick();
+ expect(nodes(root, "img")[0]?.props.src).toBe(
+ "https://example.com/icon.png",
+ );
+ dispatch(nodes(root, "img")[0], "onError");
+ await nextTick();
+ expect(nodes(root, "img")[0]?.props.src).toStartWith(
+ "data:image/svg+xml;base64,",
+ );
+ dispatch(nodes(root, "img")[0], "onError");
+ await nextTick();
+ expect(text(root)).toContain("Image unavailable");
+ expect(nodes(root, "button")[0]?.props.disabled).toBe(true);
+ props.image = "https://example.com/recovered.png";
+ await nextTick();
+ expect(nodes(root, "img")[0]?.props.src).toBe(props.image);
+ expect(text(root)).toContain("Loading image…");
+ });
+});
+
+describe("NFT page navigation", () => {
+ test("lookahead is not rendered and adjacent pages preserve repeated commitments", () => {
+ const outputs = Array.from({ length: 49 }, (_, index) =>
+ nft("01", String(index)),
+ );
+ const first = nftPage(outputs.slice(0, 25), 24);
+ const second = nftPage(outputs.slice(24, 49), 24);
+ const last = nftPage(outputs.slice(48), 24);
+ expect(first.items).toHaveLength(24);
+ expect(first.hasNextPage).toBe(true);
+ expect(second.hasNextPage).toBe(true);
+ expect(last.hasNextPage).toBe(false);
+ expect(
+ new Set(
+ [...first.items, ...second.items, ...last.items].map((item) => item.id),
+ ).size,
+ ).toBe(49);
+ expect(nftPage(outputs.slice(0, 24), 24).hasNextPage).toBe(false);
+ expect(nftPage([], 24).items).toEqual([]);
+ });
+
+ test("mode, address/category and network changes reset offset; loading blocks navigation", () => {
+ const scope = effectScope();
+ scope.run(() => {
+ const context = reactive({
+ network: "mainnet",
+ identity: "collection-a",
+ mode: "grid",
+ });
+ const pager = useNftPagination(
+ () => `${context.network}:${context.identity}`,
+ () => context.mode,
+ );
+ expect(pager.limit.value).toBe(25);
+ pager.next(false, true);
+ expect(pager.offset.value).toBe(24);
+ pager.next(true, true);
+ pager.previous(true);
+ expect(pager.offset.value).toBe(24);
+ context.mode = "table";
+ expect(pager.offset.value).toBe(0);
+ expect(pager.limit.value).toBe(9);
+ pager.next(false, false);
+ expect(pager.offset.value).toBe(0);
+ pager.next(false, true);
+ context.identity = "address-b";
+ expect(pager.offset.value).toBe(0);
+ pager.next(false, true);
+ context.network = "chipnet";
+ expect(pager.offset.value).toBe(0);
+ pager.previous(false);
+ expect(pager.offset.value).toBe(0);
+ });
+ scope.stop();
+ });
+});
+
+describe("address and collection gallery integration", () => {
+ const components = {
+ BasePagination,
+ LoadingSpinner: { render: () => h("span", "spinner") },
+ BaseCopy: CopyFixture,
+ TableView: { render: () => h("div", "NFT table") },
+ };
+
+ test("address NFTs switch from table to gallery, paginate and retry using the real query bindings", async () => {
+ const props = reactive({ lockingBytecode: "76a914fixture88ac" });
+ const { root, unmount } = mountFixture(AddressNFTs, props, components);
+ cleanup.add(unmount);
+ expect(text(root)).toContain("NFT table");
+ expect(queryVariables.value.limit).toBe(9);
+ dispatch(
+ nodes(root, "button").find((node) => node.text === "grid_view"),
+ "onClick",
+ );
+ await nextTick();
+ expect(queryVariables.value.limit).toBe(25);
+ expect(nodes(root, "article")).toHaveLength(24);
+ expect(
+ nodes(root, "a").filter((node) => node.props.href === "/address/zowner"),
+ ).toHaveLength(24);
+ dispatch(
+ nodes(root, "button").find(
+ (node) => node.props["aria-label"] === "Next page",
+ ),
+ "onClick",
+ );
+ await nextTick();
+ expect(queryVariables.value.offset).toBe(24);
+ query.result.value = {
+ output: fixtureOutputs.slice(24),
+ search_output: fixtureOutputs.slice(24),
+ };
+ await nextTick();
+ expect(nodes(root, "article")).toHaveLength(1);
+ expect(
+ nodes(root, "button").find(
+ (node) => node.props["aria-label"] === "Next page",
+ )?.props.disabled,
+ ).toBe(true);
+ query.error.value = new Error("Indexer offline");
+ await nextTick();
+ dispatch(
+ nodes(root, "button").find((node) => node.text === "Try again"),
+ "onClick",
+ );
+ expect(query.refetch).toHaveBeenCalledTimes(1);
+ query.error.value = undefined;
+ props.lockingBytecode = "other-address";
+ await nextTick();
+ expect(queryVariables.value.offset).toBe(0);
+ });
+
+ test("collection outputs become distinct outpoints and reset pages on category or view changes", async () => {
+ query.result.value = {
+ output: fixtureOutputs,
+ search_output: fixtureOutputs,
+ };
+ const props = reactive({
+ category: "ab".repeat(32),
+ viewMode: "grid",
+ identitySnapshot: {
+ name: "Selected collection",
+ token: {
+ category: "ab".repeat(32),
+ symbol: "NFT",
+ nfts: {
+ parse: {
+ types: {
+ "00ff": {
+ name: "Selected NFT",
+ uris: { image: "https://example.com/selected.png" },
+ },
+ },
+ },
+ },
+ },
+ },
+ });
+ const { root, unmount } = mountFixture(TokenChild, props, components);
+ cleanup.add(unmount);
+ expect(nodes(root, "article")).toHaveLength(24);
+ expect(
+ nodes(root, "a").filter((node) => node.props.href === "/address/zowner"),
+ ).toHaveLength(24);
+ expect(text(root)).toContain("Selected NFT");
+ expect(text(root)).not.toContain("Metadata unavailable");
+ expect(nodes(root, "img")[0]?.props.src).toBe(
+ "https://example.com/selected.png",
+ );
+ const outputLinks = nodes(root, "a").filter((node) =>
+ String(node.props.href).startsWith("/tx/"),
+ );
+ expect(new Set(outputLinks.map((node) => node.text)).size).toBe(24);
+ dispatch(
+ nodes(root, "button").find(
+ (node) => node.props["aria-label"] === "Next page",
+ ),
+ "onClick",
+ );
+ await nextTick();
+ expect(queryVariables.value.offset).toBe(24);
+ props.category = "cd".repeat(32);
+ await nextTick();
+ expect(queryVariables.value.offset).toBe(0);
+ props.viewMode = "table";
+ await nextTick();
+ expect(queryVariables.value.limit).toBe(9);
+ expect(text(root)).toContain("NFT table");
+ });
+});
diff --git a/tests/nft-gallery.test.ts b/tests/nft-gallery.test.ts
new file mode 100644
index 0000000..0750474
--- /dev/null
+++ b/tests/nft-gallery.test.ts
@@ -0,0 +1,26 @@
+import { expect, test } from "bun:test";
+import { fileURLToPath } from "node:url";
+
+test("Vue NFT gallery integration regressions", async () => {
+ // Nuxt composables are process globals in these Bun tests. Isolate the Vue
+ // compiler and network stubs from the existing store and USD-price tests.
+ const fixture = fileURLToPath(
+ new URL("./fixtures/nft-gallery.ts", import.meta.url),
+ );
+ const child = Bun.spawn([process.execPath, "test", fixture], {
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ const [stdout, stderr, exitCode] = await Promise.all([
+ new Response(child.stdout).text(),
+ new Response(child.stderr).text(),
+ child.exited,
+ ]);
+ expect({
+ exitCode,
+ output: exitCode === 0 ? "passed" : stdout + stderr,
+ }).toEqual({
+ exitCode: 0,
+ output: "passed",
+ });
+});
diff --git a/tests/vue-fixture.ts b/tests/vue-fixture.ts
new file mode 100644
index 0000000..49fccff
--- /dev/null
+++ b/tests/vue-fixture.ts
@@ -0,0 +1,119 @@
+import { readFile } from "node:fs/promises";
+import { resolve } from "node:path";
+import { compileScript, parse } from "@vue/compiler-sfc";
+import { plugin } from "bun";
+import { type Component, createRenderer, h, markRaw } from "vue";
+
+// Compile the actual SFCs; exercise Vue updates without a browser or a test-only UI copy.
+plugin({
+ name: "vue-fixture",
+ setup(build) {
+ build.onResolve({ filter: /^[~@]\// }, ({ path }) => ({
+ path: Bun.resolveSync(
+ resolve(import.meta.dir, "../src", path.slice(2)),
+ import.meta.dir,
+ ),
+ }));
+ build.onLoad({ filter: /\.vue$/ }, async ({ path }) => {
+ const { descriptor } = parse(await readFile(path, "utf8"), {
+ filename: path,
+ });
+ return {
+ contents: compileScript(descriptor, { id: path, inlineTemplate: true })
+ .content,
+ loader: "ts",
+ };
+ });
+ },
+});
+
+// Only the host boundary is simulated. Component setup, templates, event handlers,
+// computed state, keyed reconciliation, and watchers are Vue's real implementation.
+class FixtureNode {
+ children: FixtureNode[] = [];
+ parent: FixtureNode | null = null;
+ props: Record = {};
+ text = "";
+ open = false;
+ constructor(public tag: string) {}
+ showModal() {
+ this.open = true;
+ }
+ close() {
+ this.open = false;
+ }
+}
+
+const renderer = createRenderer({
+ createElement: (tag) => markRaw(new FixtureNode(tag)),
+ createText: (text) => Object.assign(new FixtureNode("#text"), { text }),
+ createComment: () => new FixtureNode("#comment"),
+ setText: (node, text) => {
+ node.text = text;
+ },
+ setElementText: (node, text) => {
+ node.text = text;
+ node.children = [];
+ },
+ parentNode: (node) => node.parent,
+ nextSibling: (node) =>
+ node.parent?.children[node.parent.children.indexOf(node) + 1] || null,
+ patchProp: (node, key, _previous, value) => {
+ node.props[key] = value;
+ },
+ insert(node, parent, anchor) {
+ if (node.parent)
+ node.parent.children.splice(node.parent.children.indexOf(node), 1);
+ node.parent = parent;
+ const index = anchor ? parent.children.indexOf(anchor) : -1;
+ parent.children.splice(index < 0 ? parent.children.length : index, 0, node);
+ },
+ remove(node) {
+ if (node.parent)
+ node.parent.children.splice(node.parent.children.indexOf(node), 1);
+ node.parent = null;
+ },
+});
+
+export function nodes(root: FixtureNode, tag?: string) {
+ const found = [root];
+ for (const node of found) found.push(...node.children);
+ return tag ? found.filter((node) => node.tag === tag) : found;
+}
+
+export function text(root: FixtureNode) {
+ return nodes(root)
+ .map((node) => node.text)
+ .join(" ");
+}
+
+export function dispatch(
+ node: FixtureNode | undefined,
+ event: string,
+ value = {},
+) {
+ const handler = node?.props[event];
+ if (typeof handler !== "function")
+ throw new Error(`Missing ${event} handler`);
+ handler({
+ target: node,
+ currentTarget: node,
+ stopPropagation() {},
+ preventDefault() {},
+ ...value,
+ });
+}
+
+export function mountFixture(
+ component: Component,
+ props: object,
+ components: Record = {},
+) {
+ const root = new FixtureNode("root");
+ const app = renderer.createApp({ render: () => h(component, props) });
+ app.config.globalProperties.$t = (key: string) => key;
+ for (const [name, value] of Object.entries(components))
+ app.component(name, value);
+ app.mount(root);
+ return { root, unmount: () => app.unmount() };
+}