statamic / v2-hub

Statamic 2 - Feature Requests and Bug Reports
https://statamic.com
95 stars 5 forks source link

Add a tree sort option for pages, which respects the tree structure #2198

Open FrittenKeeZ opened 5 years ago

FrittenKeeZ commented 5 years ago

Is your feature request related to a problem? Please describe. Sometimes you want to output pages in the order they have in the tree, but currently sort done by order is flattened, so hierarchy isn't respected.

Describe the solution you'd like A simple option like sort="tree:asc/desc".

Describe alternatives you've considered I added a custom filter to handle the sort, using sort="false" to combat the default sort.

Additional context I'm a little teapot...

Would you be willing to sponsor this feature? This is my current implementation in a custom addon (PHP 7.2).

<?php

namespace Statamic\Addons\PagesExtended;

use Statamic\Data\Pages\Page;
use Statamic\Extend\Filter;

class PagesExtendedFilter extends Filter
{
    /**
     * Perform filtering on a collection
     *
     * @return \Illuminate\Support\Collection
     */
    public function filter()
    {
        return $this->collection->sort(function (Page $a, Page $b) {
            return $this->getTreeOrder($a) <=> $this->getTreeOrder($b);
        });
    }

    /**
     * Get tree order.
     *
     * @param  \Statamic\Data\Pages\Page  $page
     * @return string
     */
    private function getTreeOrder(Page $page)
    {
        $order = [];
        do {
            $order[] = $page->order() ?: 0;
        } while ($page = $page->parent());

        return implode('-', array_reverse($order));
    }
}
jackmcdade commented 5 years ago

Couldn't you use the Nav tag for that, technically?