Tuesday, June 27, 2023

Serving Up Cut-Out Text Like a Master Chef: A Delectable CSS & React Recipe


Greetings to all connoisseurs of the code, patrons of programming, and gastronomes of the grid! Chef Gourmet here, and today I have a special treat on the menu. We are going to learn how to cook up an exquisite web dish – Cut-Out Text with a CSS & React sauce.

Imagine you’re dining in the mystique ambiance of the *Restaurant of Mistaken Orders*, and a plate is placed before you with text that looks like it has been delicately carved out, revealing a succulent video playing right underneath. That, my dear friends, is the deliciousness we are about to create.

Ingredients:

  • Fresh React app
  • Ripe Rnd component for draggable and resizable delights
  • A pinch of CSS properties
  • A dash of creativity

Preparation:

First, let’s prepare the base. We have an application where users can overlay text boxes on videos. These text boxes are resizable and draggable, much like the flexibility of our menu where patrons never know what they’re going to get.

Our guests have made a peculiar request - they want to see through the letters as if the text itself were made of windows to the video underneath. It's called a cut-out text effect.

Method:

Step 1: The Div Layering Technique

In our kitchen, stacking is an art. It’s like the fine layering of a Ratatouille, but for this dish, we are stacking `div` elements. The `video` layer needs to be directly underneath the `div` which is responsible for the cut-out text effect. We don’t want the cheese (video) too far from the pasta (div) - they must melt together.

Step 2: Marinate with CSS

Now, let’s marinate our `div` with the right blend of CSS to achieve that melt-in-your-mouth cut-out effect. Here’s our secret sauce:

{
background-color: white; /* The color you want around your text */
-webkit-background-clip: text;
background-clip: text;
color: transparent; /* This makes the text transparent, while the background stays */
}

This is the alchemy that transforms plain text into cut-out text!

Step 3: Mix with React

In React, we have this sumptuous component that uses the `Rnd` library, allowing text boxes to be draggable and resizable like the ever-changing dishes in our restaurant.

Here’s how you mix it:


<Rnd { /* ...all your Rnd props... */ }>
<div style={{ /* ...background styles... */ }}>
<div style={{
WebkitBackgroundClip: 'text',
backgroundClip: 'text',
color: 'transparent'
}}
dangerouslySetInnerHTML={{ __html: content }}
/>
</div>
</Rnd>

This structure lets the `Rnd` component do its magic, while the inner `div` reveals the delectable video underneath.

Step 4: Serve Immediately

Now that we’ve cooked up our dish, serve it hot and fresh! Invite your guests to interact with the text boxes, dragging them across the screen to savor different parts of the video through the cut-out text.

Closing Notes:

In the *Restaurant of Mistaken Orders*, our dishes are as unpredictable as they are delicious. Today, you learned how to create a Cut-Out Text delicacy with CSS and React, and like a true master chef, you’ve seen how important it is to layer your ingredients properly. Keep your video close to your

Sunday, June 18, 2023

Debugging React Components in Vite for Sitecore Content Hub: The Secret Sauce

Welcome back, chefs! Having prepared our first dish in the previous blog post, now it's time to add some secret sauce: Debugging. Debugging is the taste test of the digital kitchen. It helps ensure the quality of our dish, i.e., our React components, before we serve them up to our diners.

So, grab your apron, and let's add this flavor booster to our dish!

The Culinary Twist: Debugging

In our previous blog post, we learned how to set up a Vite project for Sitecore Content Hub and create our first React component. Now, let's understand how to debug these components.

The twist in our digital kitchen? We'll be using the source TypeScript (*.ts/*.tsx) files instead of the transpiled JavaScript (*.js) files for debugging.

Why Use TypeScript Files for Debugging?

  1. Readability: TypeScript files are easier to read and understand than their transpiled JavaScript counterparts. This makes it easier to identify and resolve issues in your code.
  2. Superior Development Tools Support: Development tools such as VS Code offer excellent support for TypeScript, including advanced features like IntelliSense, which provides code suggestions, type checking, and autocompletion. This makes the development and debugging process a lot smoother. To further enhance your debugging experience, you might want to consider installing VS Code extensions like:
    • TypeScript Hero: TypeScript Hero provides advanced TypeScript functionality, including the ability to automatically import required modules and organize your imports.

    • Debugger for Chrome: This extension lets you launch a development server and debug your React apps directly in the VS Code editor. You can set breakpoints, step through your code, inspect variables, and navigate the call stack.

    • ESLint: ESLint is a pluggable and configurable linter tool for identifying and reporting on patterns in JavaScript. Its TypeScript support helps to enforce code style, catch bugs, and generally maintain a consistent code quality. If you're using TypeScript with React, you'll likely want to use the typescript-eslint parser.

    • Prettier - Code formatter: Prettier is an opinionated code formatter that supports many languages, including TypeScript. It helps to maintain a consistent style in your code by automatically formatting it on save.

    • Code Spell Checker: This extension is particularly helpful when you're new to a language like TypeScript. It can help to catch common spelling errors in variable declarations and comments.

    • Visual Studio IntelliCode: IntelliCode enhances your software development efforts by providing AI-assisted IntelliSense. The suggestions you get are based on your own coding practices and those of thousands of other TypeScript developers.

    • GitLens: GitLens supercharges the Git capabilities built into VS Code. It helps you to visualize code authorship at a glance via Git blame annotations and code lens, seamlessly navigate and explore Git repositories, and much more.

Getting Ready for Debugging

Remember the component we cooked up in the previous blog post? Let's consider its code for debugging. In the index.html file where we attached our component to the DOM, instead of pointing to the compiled JavaScript file in the dist folder, we point to the TypeScript source file directly:

<script type="module">
import createExternalRoot from '/src/components/example-component/index.tsx';
const rootElement = document.querySelector("#app");
const component = createExternalRoot(rootElement);
const mockContext = {
theme: {
palette: {
primary: {
main: "#000000"
}
}
}
};
component.render(mockContext);
</script>

In the TypeScript file index.tsx, we include console log statements, which will output valuable information to the browser console while debugging.

export default function createExternalRoot(container) {
return {
render(context) {
console.log('Rendering with context:', context); // Added for debugging
ReactDOM.render(
<OptionsContext.Provider value={context.options}>
<OptionsContext.Consumer>
{options => (
<>
<h2 style={{ color: context.theme.palette.primary.main }}>
Example Component
</h2>
<p>
Example Component, Sitecore Content Hub
</p>
</>
)}
</OptionsContext.Consumer>
</OptionsContext.Provider>,
container
);
},
unmount() {
console.log('Unmounting the component'); // Added for debugging
ReactDOM.unmountComponentAtNode(container);
},
};
}

Taste Test (Debugging)

Open the index.html in a browser to see the component in action. One of the powerful tools at our disposal here are the browser's developer tools. These tools not only allow us to observe logs and catch any bugs in the component, but they also provide capabilities like setting breakpoints, a critical part of the debugging process.

Breakpoints are markers that you can set at specific lines in your code. When your browser executes your code and encounters a breakpoint, it'll pause execution. This pause allows you to examine the current state of your code, including the values of variables, the call stack, and more.

To use breakpoints:

Open the Developer Tools (For instance, in Chrome, you can press F12 or Ctrl + Shift + I).

Navigate to the 'Source' tab (this might be named differently in browsers other than Chrome).

Locate your TypeScript file in the file navigator. It should be under the 'localhost' section.

Click on the line number beside the code where you want to set a breakpoint. A marker will appear, indicating that a breakpoint has been set.

When you reload your page, execution will pause at your breakpoint, allowing you to examine the state of your code at that point.

Setting breakpoints in our TypeScript files gives us the advantage of being able to debug our code in the same form that we write it. We don't need to navigate through minified or transpiled JavaScript, making our debugging process much more straightforward and efficient.

In the Network tab, ensure 'Disable cache' is selected. This forces the browser to get the latest versions of all files from the server, helping you avoid potential confusion caused by caching.

Summary

We've added a robust flavor to our dish - debugging. It's an integral part of the cooking process in our digital kitchen. Just like in a culinary kitchen where chefs taste their dishes before serving, in our digital kitchen, we debug our code before deploying. This helps us catch and rectify any bugs, ensuring that we're delivering a high-quality, delicious dish to our diners.


That's it for today's culinary-tech adventure! In the next blog post, we'll dive deeper into converting an Existing Sitecore Content Hub 4.1 external component to a React component. Until then, keep cooking and debugging!