import { useState } from 'react'; import { Viewer, DocumentGate } from '@embedpdf/react/runtime'; import type { OpenInput } from '@embedpdf/react/runtime'; import { outlinePlugin, useOutline, useOutlineState } from '@embedpdf/react/outline'; import type { OutlineItem, OutlineItemRef } from '@embedpdf/react/outline'; import { cloudEngine } from '@cloudpdf/engine'; import './nesting.css'; const engine = cloudEngine(); const plugins = [outlinePlugin()]; const welcome: OpenInput = { kind: 'grant', grant: 'shr_gvpJcG1ULUMon19C0D1wODSY' }; const same = (left: OutlineItemRef | null, right: OutlineItemRef | null) => left?.objectNumber === right?.objectNumber; /** The picked item, the one before it among its parent's children, and its parent. */ const neighboursOf = (items: readonly OutlineItem[], picked: OutlineItemRef | undefined) => { const item = items.find((each) => same(each.ref, picked ?? null)) ?? null; if (!item) return { item, previous: null, parent: null }; const siblings = items.filter((each) => same(each.parent, item.parent)); const previous = siblings[siblings.indexOf(item) - 1] ?? null; const parent = items.find((each) => same(each.ref, item.parent)) ?? null; return { item, previous, parent }; }; // An outline being built: add items, nest them, fold them, rename and delete them. function OutlineEditor() { const outline = useOutline(); const { items, rows, selected, canEdit } = useOutlineState(); const [title, setTitle] = useState('Chapter'); const [picked] = selected; const { item, previous, parent } = neighboursOf(items, picked); // After the picked item, or at the end. const add = (inside: boolean) => outline.create( inside && item ? { title, parent: item.ref } : { title, parent: item?.parent ?? null, position: item ? { after: item.ref } : 'end' }, { select: true }, ); const indent = () => { if (!item || !previous) return; outline.move([item.ref], previous.ref, 'end'); outline.expand(previous.ref); }; const outdent = () => { if (item && parent) outline.move([item.ref], parent.parent, { after: parent.ref }); }; return (
This document has no outline yet. Add an item.
) : (