Double-Page and Single-Page Navigation with Prev Next between "cousins" instead of siblings

Hey there,

I was just about to post this as a question, just when I got it to work. This is just such a nice example of the flexibility of this system so I thought I just post it anyway just in case anybody will someday look for something similar.

I’am building a site for a webcomic where the user should be able to decide if he/she wants to view single pages or double pages. (and navigate between them)

I achieved this by setting up the content folder in such a way, that two single pages are alway children of a double page.

This solved most of what I wanted:
I can always show both corresponding pages together, I can navigate between the double pages, and I can also klick on a single page and have just the single page larger.

But from the Single-Page I was obviously only able to navigate back and forth between the two pages that are children of the current double page … with the normal “hasPrev” navigation.
So I had to say: link to the next sibling if there is one, else link to the next “cousin” if there is one (and the same with prev of course)

This worked perfectly fine for what I was trying to do:

<?php if ($page->hasPrevListed()): ?>
<a href="<?= $page->prevListed()->url() ?>">previous page</a>
<?php elseif ($page->parent()->hasPrevListed() ): ?>
<a href="<?= $page->parent()->prevListed()->children()->listed()->last()->url() ?>">prev page</a>
<?php endif ?>

<?php if ($page->hasNextListed()): ?>
<a href="<?= $page->nextListed()->url() ?>">next page</a>
<?php elseif ($page->parent()->hasNextListed() ): ?>
<a href="<?= $page->parent()->nextListed()->children()->listed()->first()->url() ?>">next page</a>
<?php endif ?>

I feel like there might be a more elegant way of doing this hiding somewhere here, but for now I am quite happy that it works. Feel free to let me know, if you know a way to improve this.