Order InnerBlocks in custom Gutenberg block by date attribute

Question

I have the following custom Timeline block:

const {
    blocks: { registerBlockType },
    blockEditor: { InnerBlocks },
    element: { createElement: el },
} = (window as any).wp;

export default registerBlockType("my/timeline", {
    title: "Timeline",
    edit({ className }) {
        return (
            <div className={className}>
                <InnerBlocks allowedBlocks={["my/timeline-item"]} />
            </div>
        );
    },
    save() {
        return <InnerBlocks.Content />;
    },
});

That block contains custom Timeline Item blocks:

const {
    blocks: { registerBlockType },
    blockEditor: { InspectorControls, InnerBlocks },
    element: { createElement: el },
    components: { PanelBody, DateTimePicker },
} = (window as any).wp;

const dateFormat = new Intl.DateTimeFormat("en-US", {
    month: "short",
    day: "numeric",
    hour: "numeric",
    minute: "numeric",
    hour12: false,
});

export default registerBlockType("my/timeline-item", {
    title: "Timeline Item",
    parent: "my/timeline",
    attributes: {
        date: {
            type: "date",
        },
    },
    edit({ attributes: { date }, setAttributes, className }) {
        let dateText = "No date selected";
        let dateClass = "wp-block-oblik-timeline-item__date";

        if (date) {
            dateText = dateFormat.format(new Date(date));
        } else {
            dateClass += " is-invalid";
        }

        return (
            <div className={className}>
                <InspectorControls>
                    <PanelBody>
                        <DateTimePicker
                            currentDate={date}
                            onChange={(date) => setAttributes({ date })}
                        />
                    </PanelBody>
                </InspectorControls>

                <div>
                    <span className={dateClass}>{dateText}</span>
                    <InnerBlocks />
                </div>
            </div>
        );
    },
    save() {
        return <InnerBlocks.Content />;
    },
});

Currently, timeline item blocks are ordered manually. I want them to be ordered by their date attribute – from latest to oldest. Is there a way to do that?

If custom order is not possible, is it an option to automatically add new blocks to the beginning of the list? Otherwise, you always have to manually move them to the top.

0
dodov 4 months 0 Answers 20 views 0

Leave an answer