Content Generator & CKEditor

Created on 17 February 2023, about 2 years ago

Problem/Motivation

New content created by the OpenAI Content Generator initially renders OK at the node level, but after editing and/or saving with CKEditor new lines get stripped and styling/rendering/editing gets wonky. This makes all line breaks and bulleted items in the copy look like one 'big blob'.

Steps to reproduce

Create a node under Admin > Configuration > OpenAI > Content Generator > Subject:

"List of 5 states"

Going directly to the database to see what gets saved with the following SQL:

select entity_id,body_value,body_format from node__body;

Notice body_format is empty and body_value contains REAL new lines. Those new lines are removed as soon as CKEditor has a chance to render it, and body_value then automatically gets wrapped in a <p> tag too.

Initial node level copy looks alright, but simply edit/resave with CKEditor and it becomes one big text blob wrapped with a single <p>.

Proposed resolution

In GenerationController.php, around line 190, amend the generateArticle() code:

    $body = [
        'value' => "<p>" . str_replace(array("\r\n","\r","\n","\\r","\\n","\\r\\n"),"<br>",$body) . "</p>",
        'format' => 'ckeditor5', // Machine Name of the text_format
    ];
    $article->set($body_field, $body);

With this, the value that Content Generator writes to body_value matches what CKEditor wants, and setting the body_format takes care of rendering/editing quirks.

I looked at using PHP's nl2br() instead of the str_replace() approach above, but that only adds <br /> - replacing the newlines altogether with <br> matches what CKEditor expects; won't rewrite it again upon subsequent node > edit re-saves.

Remaining tasks

Better handle different machine names of the text format, set under Admin > Configuration > Content Authoring > Text formats and editors. It is statically set in my code example above

User interface changes

Maybe make the target text_format a configuration option in OpenAI > Settings, or in the Content Generator UI itself.

Note: This seems to be a common problem with lots of other ChatGPT integrations I've come across too (beyond your Drupal OpenAI Module). Most of them cannot format the response well at all!

πŸ› Bug report
Status

Fixed

Version

1.0

Component

Code

Created by

πŸ‡ΊπŸ‡ΈUnited States d0t101101

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024