Verified Commit 8496c2c3 authored by Théodore Biadala's avatar Théodore Biadala
Browse files

Issue #3110517 by gapple, andypost, nod_, Wim Leers, smustgrave: Improve...

Issue #3110517 by gapple, andypost, nod_, Wim Leers, smustgrave: Improve Drupal\Core\Ajax\AddCssCommand to accept an array of CSS assets
parent 9e5aef92
Loading
Loading
Loading
Loading
+9 −9
Original line number Diff line number Diff line
@@ -15,30 +15,30 @@
class AddCssCommand implements CommandInterface {

  /**
   * A string that contains the styles to be added to the page.
   * Arrays containing attributes of the stylesheets to be added to the page.
   *
   * It should include the wrapping style tag.
   *
   * @var string
   * @var string[][]|string
   */
  protected $styles;

  /**
   * Constructs an AddCssCommand.
   *
   * @param string $styles
   *   A string that contains the styles to be added to the page, including the
   *   wrapping <style> tag.
   * @param string[][]|string $styles
   *   Arrays containing attributes of the stylesheets to be added to the page.
   *   i.e. `['href' => 'someURL']` becomes `<link href="someURL">`.
   */
  public function __construct($styles) {
    if (is_string($styles)) {
      @trigger_error('The ' . __NAMESPACE__ . '\AddCssCommand with a string argument is deprecated in drupal:10.1.0 and is removed from drupal:11.0.0. See http://www.drupal.org/node/3154948', E_USER_DEPRECATED);
    }
    $this->styles = $styles;
  }

  /**
   * Implements Drupal\Core\Ajax\CommandInterface:render().
   * {@inheritdoc}
   */
  public function render() {

    return [
      'command' => 'add_css',
      'data' => $this->styles,
+1 −1
Original line number Diff line number Diff line
@@ -174,7 +174,7 @@ protected function buildAttachmentsCommands(AjaxResponse $response, Request $req
    $resource_commands = [];
    if ($css_assets) {
      $css_render_array = $this->cssCollectionRenderer->render($css_assets);
      $resource_commands[] = new AddCssCommand($this->renderer->renderPlain($css_render_array));
      $resource_commands[] = new AddCssCommand(array_column($css_render_array, '#attributes'));
    }
    if ($js_assets_header) {
      $js_header_render_array = $this->jsCollectionRenderer->render($js_assets_header);
+42 −3
Original line number Diff line number Diff line
@@ -1659,13 +1659,52 @@
     *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
     * @param {object} response
     *   The response from the Ajax request.
     * @param {string} response.data
     *   A string that contains the styles to be added.
     * @param {object[]|string} response.data
     *   An array of styles to be added.
     * @param {number} [status]
     *   The XMLHttpRequest status.
     */
    add_css(ajax, response, status) {
      if (typeof response.data === 'string') {
        Drupal.deprecationError({
          message:
            'Passing a string to the Drupal.ajax.add_css() method is deprecated in 10.1.0 and is removed from drupal:11.0.0. See https://www.drupal.org/node/3154948.',
        });
        $('head').prepend(response.data);
        return;
      }

      const allUniqueBundleIds = response.data.map(function (style) {
        const uniqueBundleId = style.href + ajax.instanceIndex;
        loadjs(style.href, uniqueBundleId, {
          before(path, styleEl) {
            // This allows all attributes to be added, like media.
            Object.keys(style).forEach((attributeKey) => {
              styleEl.setAttribute(attributeKey, style[attributeKey]);
            });
          },
        });
        return uniqueBundleId;
      });
      // Returns the promise so that the next AJAX command waits on the
      // completion of this one to execute, ensuring the CSS is loaded before
      // executing.
      return new Promise((resolve, reject) => {
        loadjs.ready(allUniqueBundleIds, {
          success() {
            // All CSS files were loaded. Resolve the promise and let the
            // remaining commands execute.
            resolve();
          },
          error(depsNotFound) {
            const message = Drupal.t(
              `The following files could not be loaded: @dependencies`,
              { '@dependencies': depsNotFound.join(', ') },
            );
            reject(message);
          },
        });
      });
    },

    /**
+17 −1
Original line number Diff line number Diff line
@@ -202,7 +202,23 @@ function ajax_forms_test_advanced_commands_settings_callback($form, FormStateInt
 */
function ajax_forms_test_advanced_commands_add_css_callback($form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $response->addCommand(new AddCssCommand('my/file.css'));
  $response->addCommand(new AddCssCommand([
    [
      'href' => 'my/file.css',
      'media' => 'all',
    ],
  ]));
  return $response;
}

/**
 * Ajax callback for 'add_css' that uses legacy string parameter.
 *
 * @todo Remove in Drupal 11.0.0 https://www.drupal.org/i/3339374
 */
function ajax_forms_test_advanced_commands_add_css_legacy_callback($form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $response->addCommand(new AddCssCommand("<link rel='stylesheet' href='my/file.css' media='all' />"));
  return $response;
}

+10 −0
Original line number Diff line number Diff line
@@ -224,6 +224,16 @@ public function buildForm(array $form, FormStateInterface $form_state) {
      ],
    ];

    // Shows the Ajax 'add_css' command with legacy string parameter.
    // @todo Remove in Drupal 11.0.0 https://www.drupal.org/i/3339374
    $form['add_css_legacy_command_example'] = [
      '#type' => 'submit',
      '#value' => $this->t("AJAX 'add_css' legacy command"),
      '#ajax' => [
        'callback' => 'ajax_forms_test_advanced_commands_add_css_legacy_callback',
      ],
    ];

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
Loading