SDC ComponentElement: Transform slots scalar values to #plain_text instead of throwing an exception

Created on 4 October 2023, about 1 year ago
Updated 18 June 2024, 5 months ago

Problem/Motivation

We are planning to rewrite UI Patterns upon SDC. To achieve this, we are proposing a few changes and additions:

Today, #slots property of ComponentElement accepts only render arrays.

If something else is send, there is a fatal error:

Unable to render component "%s". A render array is expected for the slot "%s" when using the render element with the "#slots" property

We believe such a strong behaviour and expected verbosity don't fit with developers expectations and may hurt SDC adoption.

Steps to reproduce

When using component render element, instead of doing this:

[
     '#type' => 'component',
    '#component' => 'ui_patterns_test:close_button',
    '#slots' => [
       "foo" => [
           "#plain_text" => "Bar",
       ]
   ],
    '#props' => []
];

Do that:

[
    '#type' => 'component',
    '#component' => 'ui_patterns_test:close_button',
    '#slots' => [
      'foo' => "Bar",
    ],
    '#props' => []
];

Proposed resolution

More or less something like that:

@@ -105,13 +105,10 @@ class ComponentElement extends RenderElement {
     $template .= sprintf('{%% embed \'%s\' %%}', $id);
     $template .= PHP_EOL;
     foreach ($slots as $slot_name => $slot_value) {
-      if (!Utilities::isRenderArray($slot_value)) {
-        $message = sprintf(
-          'Unable to render component "%s". A render array is expected for the slot "%s" when using the render element with the "#slots" property',
-          $id,
-          $slot_name
-        );
-        throw new InvalidComponentDataException($message);
+      if (!Utilities::isRenderArray($slot_value) && \is_scalar($slot_value)) {
+        $slot_value = [
+          "#plain_text" => (string) $slot_value,
+        ];
       }
       $context[$slot_name] = array_reduce(
         $slots_alter_callbacks,

With update of related tests.

Remaining tasks

If there is a chance for this change to be accepted, we (UI Patterns team) can propose a merge request soon.

We have one month before the release of Drupal 10.2.0-alpha1.

API changes

It seems safe. Nothing breaking.

🐛 Bug report
Status

Fixed

Version

10.1

Component
single-directory components 

Last updated 2 days ago

Created by

🇫🇷France pdureau Paris

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

Comments & Activities

Production build 0.71.5 2024