Skip to main content
Image
Integrating SDC With Storybook OpenSense Labs

SDC: Integrating Storybook & Single Directory Component

Drupal

Today, we will talk about about Drupal Single Directory Components or SDC and Storybook. Single Directory Components in Drupal allows you to arrange your UI components, while Storybook enables you to engage with them. Integrating them changes your development process, creating a groundbreaking way to build and test UI components. 

And the release of Drupal 11 brings a stabilized version of Drupal Single Directory Components.  

Think about this for a second - 

Imagine a solution that can keep website UI components tidy, reusable for various projects, uniform across all web pages, and offer even more benefits.

SDC (Single Directory Components) is a key feature in Drupal 10.1 and Drupal 11, enabling all of this to happen.

In this blog, we will discuss how integrating SDC and Storybook can help you build faster and work more efficiently. 

If you're looking to switch from your current content management system to Drupal, take a look at our migration services before we proceed.

Migrate To Drupal Now! 

Let's dive in! 

What Is SDC? 

SDC was once a contributed module, but it has now become part of the Core and is more stable since the release of Drupal version 11. SDC or Single Directory Components offers a new way to structure and organize components. SDC is how Drupal uses components. 

SDC enhances your Drupal themes for a more contemporary style. These components include HTML, CSS, and JavaScript code, making it simple to customize and use on different pages or apps. 

All the files needed to make a component are in one single directory. 

But what exactly are components? 

In the context of Single Directory Components (SDC) in Drupal, components refer to modular, reusable building blocks that encapsulate all the resources required to render a specific UI element. SDC organizes templates, styles, scripts, and metadata into a single directory for each component, providing a more cohesive and maintainable development experience. 

With SDC developers can design components that are interchangeable and modular, making their code more flexible and reusable. Components help with organizing, reusing, keeping things consistent, scaling, testing, and collaborating. This configuration helps in easily integrating with tools such as Storybook.

The directory of an SDC contains these files:

  1. A YAML file containing metadata that assists Drupal in identifying the component. 

  1. A Twig file containing the templates. 

  1. A CSS file containing the styles. 

  1. A JavaScript file containing the scripts. 

A component can also include a screenshot, a PHP file (with hooks and alters), media (like images, audio, or video), or any other related items, but this is optional. 

More reliable and simpler front-ends that are easy to update?

Yes, please! 

Also Check Out: 

  1. Drupal 11: Eleven Changes & Updates In Drupal 11 

  1. DrupalCon Barcelona: 2024 Wrap-Up From Europe 

  1. Drupal 7 End Of Life: Top Reasons You Should Migrate To Drupal 10 

  1. RFP: How To Create An RFP For Open Source Solutions? 

What Is Storybook? 

Storybook is a tool that helps developers and designers view and test all their components in one place before using them on the actual website. It's fantastic because it's open-source, widely used, and has a user-friendly interface, which makes it ideal for modern development workflows!

You can make and test components individually. This confirms they run independently prior to integration. It provides a visual guide to the components, making it simple to see and grasp how each component works.  

Storybook offers a simpler file layout than various alternatives, makes use of webpack, and is compatible with a wide range of front-end technologies. It can easily adapt to fit individual needs. Storybook is one of the top design systems in use with Drupal today.

In Storybook, atoms, molecules, and organisms are components that make up the atomic design system. 

  • Atoms: Basic UI elements like buttons, input boxes, labels, and headings. 
  • Molecules: They are more advanced UI components formed from atoms, like a search box combined with a submit button. 
  • Organisms: These are bigger UI components formed from molecules, like a product list, a header, or forms. 

OpenSense Labs is among only 100 organizations worldwide that are recognized as a Drupal Association Certified Partner. If you're looking to migrate your Drupal 7 site, check out our services today.

Migrate To Drupal 10 Now! 

Why Should You Integrate SDC With Storybook In Drupal? 

Integrating SDC with Storybook in Drupal provides many benefits. It automatically loads components, which simplifies the process of creating and managing stories with minimal setup. The SDC Storybook integrations provide unique benefits, that tools like the SDC Styleguide and Drupal Storybook can’t provide alone.  

Let’s have a look at some of these advantages:  

1. Components work separately and can be integrated easily 

A component can function on its own in different environments, using the BEM (Block Element Modifier) method. A component can function on its own, regardless of the Drupal version or the theme in use. It is compatible with all systems. 

2. Simple Drupal setup needed 

You can develop components without needing to install or set up Drupal dependencies. You can create frontend components in Storybook to make your work faster, without having to run a large Drupal setup. This accelerates development and makes sure everything functions smoothly. 

3. Makes DevOps and CI/CD pipelines easier 

Separate components simplify testing and deployment. You can skip Drupal-specific integration in CI pipelines, you can streamline your workflows and make them easier to manage. It keeps components organized and makes it easy to manage JavaScript and CSS files, templates, and data flow within components.

4. Using Faker.js and JSON Schema for scalability and adaptability 

With tools such as Faker.js, you can make test data for components without using actual content. JSON Schema clearly and consistently defines component data, which helps keep data integrity intact. You can test and view components individually which helps make UI components easier to manage and expand.

5. Tool used widely for frontend development 

Storybook is commonly used in front-end development, making it easier for new developers to get started, even if they are not familiar with Drupal. With JSON Schema, developers can build components without having to know a lot about Drupal, making it easier for more developers to participate in the project.

6. Drupal-related functions built into components 

Integrate Drupal behaviours, such as [Drupal.attachBehaviors()], directly into Storybook previews. This ensures that the components work consistently in both Storybook and the live environment. Integrates drupalSettings and once.js to make sure that Storybook components work like those in Drupal.

6 Benefits Of Integrating SDC With Storybook OpenSense Labs

Requirements For Integrating SDC With Storybook 

You must have at least Drupal version 10.1 or the latest Drupal 11 to use SDC. Some initial steps are needed before you can start creating components and integrating them with Storybook.  

  1. Make sure you have a recent version of Node.js on your computer. We recommend using the nvm tool for managing node versions, but you can use any method you usually prefer to install a node.

  1. Set up a local environment for your Drupal site. Storybook connects to Drupal to show the individual components, so Drupal needs to be running and accessible.

Also Check Out: 

  1. 7 Quick Steps to Create API Documentation Using Postman 

  1. What is Product Engineering Life Cycle? 

  1. Drupal's Omnichannel Capabilities: Enhancing Customer Engagement and Experience 

  1. The Importance of Learning Soft Skills: A Journey of Self-Discovery 

How To Integrate SDC With Storybook In Drupal 11? 

Setting up Storybook with Drupal 11 is simple. You just need to create SDC enable them, and install the required dependencies. Developers can easily connect SDC with Storybook by following specific steps. They can use tools such as Twig and Webpack5 to improve how their components are templated and rendered. 

Step 1: Set Up SDC 

Enable the SDC core module. It is included by default in Drupal 10.1 and later versions. 

Setting Up SDC OpenSense Labs

Step 2: CORS Settings To Configure Storybook 
 

Create a .storybook folder inside of Project root 

Create two files main.js and preview.js file

Install and Enable the Storybook module or CL Server module

After installing this module, connect this module with Drupal using the development.services.yml file

Setting up development.service.yml 

parameters:
  http.response.debug_cacheability_headers: true
  cl_server.development: true
  cors.config:
    enabled: true
    allowedHeaders:
      ["Origin", "X-Requested-With", "Content-Type", "Accept", "*"]
    allowedMethods: ["*"]
    allowedOrigins: ["*"]
    exposedHeaders: false
    maxAge: false
    supportsCredentials: false
services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory

After this in settings.php File, uncomment this code 

if (file_exists($app_root . '/' . $site_path . '/settings.local.php')) {
  include $app_root . '/' . $site_path . '/settings.local.php';
}

AND, Copy example.settings.local.php and paste it into the sites/default Folder and rename it to settings.local.php

 

<?php

$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';

/**
* Show all error messages, with backtrace information.
*
* In case the error level could not be fetched from the database, as for
* example the database connection failed, we rely only on this value.
*/
$config['system.logging']['error_level'] = 'verbose';

/**
* Disable CSS and JS aggregation.
*/
$config['system.performance']['css']['preprocess'] = FALSE;
$config['system.performance']['js']['preprocess'] = FALSE;


$settings['rebuild_access'] = TRUE;


$settings['skip_permissions_hardening'] = TRUE;

Step 3: Create Package.json File In The Lando Root Folder For Storybook And Install Storybook 

Create package.json folder in Root Folder and add this code

  

{
"name": "drupalstorybook",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "storybook": "storybook dev -p 6006",
  "build-storybook": "storybook build"
},
"author": "Opensense",
"license": "ISC",
"devDependencies": {
  "@lullabot/storybook-drupal-addon": "^2.0.1",
  "@storybook/addon-essentials": "^7.4.1",
  "@storybook/addon-links": "^7.4.1",
  "@storybook/blocks": "^7.4.1",
  "@storybook/server": "^7.4.1",
  "@storybook/server-webpack5": "^7.4.1",
  "react": "^18.2.0",
  "react-dom": "^18.2.0",
  "storybook": "^7.4.1"
}
}

After this run npm install or if you are using yarn run yarn install [use node version 20] 

Now for the storybook, run the command 

yarn storybook or if you are using npm then run npm run storybook 

Note: For the latest Storybook, please check the latest version of the Storybook, add in package.json and run npm or yarn Install 

For generating stories without automatically JSON format: 

drush storybook:generate-all-stories 

watch --color drush storybook:generate-all-stories 

If on Mac (brew using watch) 

Step 4: Create Stories For Components  
 
Create stories for every SDC component to demonstrate its features and variations. Use Twig files to set up the layout and details of each component story. Also, make sure each story clearly shows how the component looks and acts. 

Let’s check out an example:

Below is a sample file structure for developing an SDC component that includes Storybook integration.  The component here is 'hero'.

 SDC Create Stories For Components OpenSense Labs

Here, we have opted for a method that focuses on atomic components. We have added the hero component below the atoms.  

Note: It’s important to keep SDC components under the components/folder. 

Here are the coding examples for the component above:  

1. hero.component.yml

$schema: https://git.drupalcode.org/project/drupal/-/raw/10.1.x/core/modules/sdc/src/metadata.schema.json
name: Hero
description: Hero with title, text, and image
status: experimental
slots:
  body: {}
  media_image: {}
props:
  type: object
  properties:
    heading:
      title: Heading
      description: The title for the hero text.
      examples:
        - You Are My Hero
      type: string
    bodyText:
      title: Hero body text
      type: string
      examples:
        - hello lorum ipsum
    Image_Inverse:
      label: "inverse"
      type: boolean
    mediaImage:
      title: Media Image
      description: Media image for the hero.
      type: string
  1. hero.css 

We can create an SCSS file and then compile it into a CSS file. Here’s the method to do this in a gulp.js file:  

gulp.src([‘.components/**/*.scss’]).pipe(gulpSass()).pipe(gulp.dest([‘./components’])) 

 

.c-hero {
  background-color:var(--black);
  margin:0 -50vw;
  width:100vw;
  position:relative;
  left:50%;
  right:50%;
  overflow:hidden;
}

@media (width >= 1024px) {
  .c-hero__wrap {
    display:flex;
    align-items:center
  }
}

.c-hero__content-wrap {
  padding:1.25rem 1.875rem 1.25rem 1.25rem;
}

@media (width >= 1024px) {
  .c-hero__content-wrap {
    padding:1.875rem 2.5rem 1.875rem 3.125rem;
    width:40%
  }
}

3. hero.stories.yml 

title: Components/SDC/Organisms/Hero
argTypes:
  Image_Inverse:
    defaultValue: ""
    control: boolean
    Inverse: "inverse"
stories:
  - name: "Hero Banner" 
    args:
      heading: Welcome to SDC
      heroImage: ''
      mediaImage: https://picsum.photos/id/29/1200/1200
      bodyText: |
        <p>Lorem ipsum generator tvinu lorem ipsum generator tvinu lorem ipsum generator tvinu</p>
 

We make stories by using the {% story <name> with { args } %} format to add them. The {% stories %} tag acts as a container for all {% story %} tags; without it, the stories lack context.

4. hero.twig

The primary template file for the SDC component.

{#
# For slots that have an optional field, we need to do a
# render check right in the componet template using twig set
# and then check with a trim / is not empty.
# A "slot" which is basically some arbitrary text
# which will be replaced by the Drupal body text field anyway.
# Thus, the usage of {% block body %}
#}
{% set body_content %}
{% block body %}
{# Hero body text. #}
{{ bodyText | raw }}
{% endblock %}
{% endset %}
{# ------------------------- #}

{% if Image_Inverse == 1 %}
{% set inverse_class = 'c-hero__wrap--inverse' %}
{% endif %}

<section class="c-hero">
  <div class="c-hero__wrap {{ inverse_class }}">

    <div class="c-hero__content-wrap">
      {# Hero heading #}
      <div class="c-hero__heading">
        <h1>{{ heading }}</h1>
      </div>

      {% if body_content|trim is not empty %}
      <div class="c-hero__body-text">
        {{ body_content }}
      </div>
      {% endif %}
    </div>

    <div class="c-hero__media-wrap">
      <div class="c-hero__media">
        {% block media_image %}
        <img src="{{ mediaImage }}" width="1200" height="1200" loading="eager"
          alt="">
        {% endblock %}
      </div>
    </div>
  </div>
</section>

 Step 5: Generate Component Stories 

The Storybook application is unable to process stories written in Twig format. The stories need to be compiled into *.stories.json files. You can achieve this by running: drush storybook:generate-all-stories 

To create stories while monitoring files, use this command: 

watch --color drush storybook:generate-all-stories 

Step 6: Test And Make Changes 

Type the below given command to start the storybook server and test the components: 

npm run storybook or if you are using yarn then run yarn storybook  

Update the design and functions of components according to feedback and testing outcomes. Constantly work on the SDC components to increase their user-friendliness and effectiveness. Here’s what your storybook page will look like:

SDC Test And Make Changes OpenSense Labs

Key Takeaways 

  1. SDC which stands for Single Directory Components, offers a new way to arrange and manage components in Drupal. 

  2. Storybook is a tool that helps developers and designers view and test all their components in one place before using them on the actual website. 

  3. Integrating SDC with Storybook in Drupal automatically loads components, simplifying the process of creating and managing stories with minimal setup. 

  1. To use SDC you need at least Drupal version 10.1 or the latest Drupal 11. 

  1. Setting up Storybook with Drupal 11 is simple, just create SDC enable them, and install the necessary dependencies. 

Subscribe

Ready to start your digital transformation journey with us?

Related Blogs

AI Chatbot: Crafting with Precision & Personality

Creating AI Chatbot OpenSense Labs

In the realm of artificial intelligence, developing an AI chatbot that not only delivers accurate information but also…

Drupal Debug: Effective Techniques And Tools 

Drupal Debugging Techniques Drupal Debug OpenSense Labs

Today, we will discuss how to do Drupal Debug. This means getting the tools and methods to turn complex issues into workable…

Drupal SDC v/s Storybook: What’s The Difference?

Drupal SDC Storybook Difference Between SDC And Storybook OpenSense Labs

One helps you set up your UI components, and the other allows you to work with them. we are exploring Single Directory…