How to save a custom draft from the panel (using the API)

Greetings,

I’m working on a custom plugin to save an already-published page as a draft (while keeping it published but not changing the published page). My motivation is a “drafts for published content” implementation. I’m using Kirby as a headless CMS and have created preview buttons for content editors to preview their changes before saving them. When clicking one of these buttons, the idea is to create a draft entry of the page (even though it’s technically published) and build a preview pulling draft content from the API (and then open that page in a new tab). I’m currently stuck on the “create a draft entry of the page” step, but close.

Here’s where I’m currently at:

Kirby::plugin('namespace/myPlugin', [
   'api' => [
      'routes' => function ($kirby) {
         return [
            [
               'pattern' => 'save-custom-draft',
               'method' => 'POST',
               'action'  => function () use ($kirby) {
                  $bodyRaw = file_get_contents('php://input');
                  $bodyJson = json_decode($bodyRaw);

                  // Create the temporary draft instance.
                  $tempDraft = new Page([
                     "isDraft" => true,
                     "slug" => $bodyJson->pageId
                  ]);
                  
                  // Write the temporary draft instance to disk
                  $tempDraft->writeContent([
                     'data' => json_encode($bodyJson->fileContent)
                  ]);
               }
            ]
         ];
      }
   ]
])

That works, except that the format of the file created does not follow the format of the published file. It’s missing the Title, and all the data that’s stored is inside of a data property. I think I need to pass a template option when creating the page, but so far haven’t been able to get that to work.

Grateful for any feedback!