diff --git a/astro-portabletext/components/PortableText.astro b/astro-portabletext/components/PortableText.astro index 99f1fdb..f7ebee4 100644 --- a/astro-portabletext/components/PortableText.astro +++ b/astro-portabletext/components/PortableText.astro @@ -237,8 +237,10 @@ const blocks = Array.isArray(value) ? value : [value]; // Using a generator to avoid creating a new array function* renderBlocks() { + let index = 0; + for (const it of nestLists(blocks, listNestingMode)) { - yield asComponentProps(it, 0, false); + yield asComponentProps(it, index++, false); } } --- diff --git a/lab/src/components/BlockIndex.astro b/lab/src/components/BlockIndex.astro new file mode 100644 index 0000000..98fc515 --- /dev/null +++ b/lab/src/components/BlockIndex.astro @@ -0,0 +1,16 @@ +--- +import type { Block, Props as $ } from "astro-portabletext/types"; +import { usePortableText } from "astro-portabletext/utils"; + +export type Props = $; + +const props = Astro.props; +const { getDefaultComponent } = usePortableText(props.node); +const Default = getDefaultComponent(); +--- + +
+ + + +
diff --git a/lab/src/pages/block/block-index.astro b/lab/src/pages/block/block-index.astro new file mode 100644 index 0000000..e7ca2f5 --- /dev/null +++ b/lab/src/pages/block/block-index.astro @@ -0,0 +1,42 @@ +--- +import Layout from "../../layouts/Default.astro"; +import { PortableText } from "astro-portabletext"; +import Block from "../../components/BlockIndex.astro"; + +const blocks = [ + { + _type: "block", + style: "normal", + children: [ + { + _type: "span", + text: "Paragraph 1", + }, + ], + }, + { + _type: "block", + style: "normal", + children: [ + { + _type: "span", + text: "Paragraph 2", + }, + ], + }, + { + _type: "block", + style: "normal", + children: [ + { + _type: "span", + text: "Paragraph 3", + }, + ], + }, +]; +--- + + + + diff --git a/lab/src/test/block.test.js b/lab/src/test/block.test.js index 22ad79d..d5edf1d 100644 --- a/lab/src/test/block.test.js +++ b/lab/src/test/block.test.js @@ -126,4 +126,14 @@ block("merge", async () => { assert.is($el.length, 1); }); +block("block index", async () => { + const $ = await fetchContent("block/block-index"); + const $el = $("[data-block-index]"); + + assert.is($el.length, 3); + assert.is($el.eq(0).attr("data-block-index"), "0"); + assert.is($el.eq(1).attr("data-block-index"), "1"); + assert.is($el.eq(2).attr("data-block-index"), "2"); +}); + block.run();