Skip to content

Commit

Permalink
fix: block index (#138)
Browse files Browse the repository at this point in the history
  • Loading branch information
theisel committed Apr 21, 2024
1 parent 7582c73 commit d0f4ed8
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 1 deletion.
4 changes: 3 additions & 1 deletion astro-portabletext/components/PortableText.astro
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
---
Expand Down
16 changes: 16 additions & 0 deletions lab/src/components/BlockIndex.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
import type { Block, Props as $ } from "astro-portabletext/types";
import { usePortableText } from "astro-portabletext/utils";
export type Props = $<Block>;
const props = Astro.props;
const { getDefaultComponent } = usePortableText(props.node);
const Default = getDefaultComponent();
---

<div data-block-index={props.index}>
<Default {...props}>
<slot />
</Default>
</div>
42 changes: 42 additions & 0 deletions lab/src/pages/block/block-index.astro
Original file line number Diff line number Diff line change
@@ -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",
},
],
},
];
---

<Layout>
<PortableText value={blocks} components={{ block: Block }} />
</Layout>
10 changes: 10 additions & 0 deletions lab/src/test/block.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();

0 comments on commit d0f4ed8

Please sign in to comment.