Tag: Recreating

Recreating the CodePen Gutenberg Embed Block for Sanity.io

Chris recently put out a neat CodePen Embed Block for the Gutenberg editor in WordPress. It allows you to embed a Pen just by dropping in its URL. From there, you get access to control the size, theme, and the default tabs that render on initial load. Super neat!

Having a live preview of the embedded Pen while writing is so handy!

But it got me thinking: How difficult would it be to recreate it with Sanity Studio’s Portable Text editor? (Spoiler: Not that difficult). Since I already knew how to do it, it took me under seven minutes from start to finish. This tutorial takes you through how to get up and running with a studio, and how to add the schemas and the custom preview component for a CodePen embed.

That felt so cool that I want to teach you how to do it as well. Let’s dive right into it.

Getting Sanity Studio up and running locally

First, you’ll need to install Sanity Studio locally on your machine. In this tutorial we will be using the blog studio that you can initiate from the command line, but you can also check out the different starters on sanity.io/create. You should be able to tag along with one of those too.

This tutorial assumes that you have a bit of knowledge of JavaScript. It will use a bit of React, but only a small part. You should have installed node and npm if you haven’t already.

Oh, and you’ll want the Sanity CLI, which you can snag with the command line:

npm install --global @sanity/cli

Once the installation is done, you can initiate a new Sanity Studio with a new project by running the command sanity init. It will let you log in with your Google or GitHub account (or make a new account with an email/password). Give your project a name and follow the instructions. When given the options for a project template, choose the blog one:

? Select project template   Movie project (schema + sample data)   E-commerce (schema + sample data) ❯ Blog (schema)   Clean project with no predefined schemas

After completing the steps, change directory (cd) into the new project folder and open it in your favorite code editor. To start the developer server that will also hot reload your studio when you make changes, run sanity start. To stop this server, you press ctrl + C in most command line tools.

Adding the schemas for a CodePen embed

Schemas define which document types that are available in the Studio, and which input fields they have. These schemas are defined in JavaScript objects that you import into the schemas.js file, where they are exported as a function that the Studio translates into its UI. There’s a lot you can do with these schemas, but in this tutorial, we will keep it reasonably simple.

Start with adding a new file inside /yourproject/schemas called codepen.js. Then type in this code:

export default {   name: "codepen",   type: "object",   title: "CodePen Embed",   fields: [     {       name: "url",       type: "url",       title: "CodePen URL"     }   ] };

Then you can go to /yourproject/schemas/schema.js and add the following two lines of code to it:

import createSchema from "part:@sanity/base/schema-creator"; import schemaTypes from "all:part:@sanity/base/schema-type";  import blockContent from "./blockContent"; import category from "./category"; import post from "./post"; import author from "./author"; import codepen from "/codepen.js"; // <= first import the object  export default createSchema({   name: "default",   types: schemaTypes.concat([     post,     author,     category,     blockContent,     codepen // <= add it to the schema types array   ]) });

So what did we just do? Well, we have now made this CodePen object available as a type in other schemas in the Studio. In other words, you can now add type: 'codepen' to get those fields anywhere else in the schema code where you add fields. Adding this type to the rich text field is also our next step. Hang on!

Adding the CodePen field to the rich text editor

Before diving into the code bit, let us take a step back and look at what is going on in terms of the data formats we operate with, and how WordPress and Sanity differ slightly.

While Gutenberg stores rich text as JSON in its runtime (which is great!), what developers end up dealing with is mostly this content as HTML and JSON objects inside of HTML comments.

Sanity stores and distributes rich text content as Portable Text, which developers then serializes in their frontends. That means that you get fine-grained control over how rich text content is rendered by letting you use custom components for your favorite framework, either it's ReactVueSvelte, or .NETPHP, or even Markdown.

In other words, you store your content as structured data in Sanity’s backend, and then decide how you want to use the data inside your frontend components. But enough exposition, let's get back to the code!

Open /schemas/blockContent.js and notice that it's of the type array. Yes, rich text is an array of different types, where one of them has to be of the block type (in which text paragraphs are stored). So the simplest way of making rich text is the following schema definition:

export default {   name: "body",   type: "array",   title: "Body",   of: [     {       type: "block"     }   ] };

Now, blockContent.js has a bunch of more stuff. You can see styles, lists, marks, and so on. All defining which properties should be available for the author. In the top array, there are two types block and image. We are going to add the third one, codepen:

export default {   title: "Block Content",   name: "blockContent",   type: "array",   of: [     {       type: "block"       // ...     },     {       type: "image",       options: { hotspot: true }     },     {       type: "codepen"     }   ] };

Save the file, and that's it! If you now run sanity start in your command line (assuming you haven't already), and open the Studio on https://localhost:3333, you should be able to find your new field in the rich text editor under the "post" type:

Sanity Studio with a CodePen button in the Rich Text editor.

If you try out the new button, you'll get a modal with the URL field that you defined in the previous section. Feel free to add the URL from a cool CodePen that you have found. We will use this one from the legendary Sara Drasner; it's pretty cool.

Just showing the URL value in the editor isn't especially inspiring, though. So let's go ahead and add the actual CodePen embed so we can interact with it directly in the editor!

Adding the CodePen embed as a preview

Open /yourproject/schemas/codepen.js again. Now we are going to make a small React component for our preview. Start by importing React in the top, and the boilerplate for the React component that we will turn into the embed:

import React from "react";  const CodePenPreview = ({ value }) => {   return <pre>{JSON.stringify(value, null, 2)}</pre>; };  export default {   name: "codepen",   type: "object",   title: "CodePen Embed",   fields: [     {       name: "url",       type: "url",       title: "CodePen URL"     }   ] };

The JSON.stringify stuff is a temporary little way of outputting the incoming data in a readable manner. You could also use console.log(value), but who has time to open the developer console?

Now you must tell Sanity how to use this component for the preview. As well as which of the fields in the object it should select for the value in the preview component.

import React from "react";  const CodePenPreview = ({ value }) => {   return <pre>{JSON.stringify(value, null, 2)}</pre>; };  export default {   name: "codepen",   type: "object",   title: "CodePen Embed",   preview: {     select: {       url: "url"     },     component: CodePenPreview   },   fields: [     {       name: "url",       type: "url",       title: "CodePen URL"     }   ] };

The editor should look something like this after you saved your changes:

Cool! Now we want to take the url value and somehow integrate it with a CodePen embed. The easiest way to go about this is to fit the markup for CodePen’s iFrame embed, and fit into our preview component in React.

The original iFrame element will look like this:

<iframe height="265" style="width: 100%;" scrolling="no" title="React Animated Page Transitions" src="https://codepen.io/sdras/embed/gWWQgb?height=265&theme-id=dark&default-tab=js,result" frameborder="no" allowtransparency="true" allowfullscreen="true">   See the Pen <a href='https://codepen.io/sdras/pen/gWWQgb'>React Animated Page Transitions</a> by Sarah Drasner   (<a href='https://codepen.io/sdras'>@sdras</a>) on <a href='https://codepen.io'>CodePen</a>. </iframe>

If we paste this snippet into our preview component, it will almost work. In order to make it JSX-compatible you'll have to some few changes to some of the HTML-attributes. Make sure that you change:

  • style="width: 100%;" to style={{width: "100%"}}
  • frameborder="no" to frameBorder="no"
  • allow-transparency="true" to allowTransparency
  • allow-fullscreen="true" to allowFullScreen

You can remove the content (links, etc.) inside of the iframe, because it isn't particularly useful inside the studio. What we should end up with is something like this:

import React from "react"; import Codepen from "react-codepen-embed";  const CodePenPreview = ({ value }) => {   return (     <iframe       height="265"       style={{ width: '100%' }}       scrolling="no"       title="React Animated Page Transitions"       src="https://codepen.io/sdras/embed/gWWQgb?height=370&theme-id=dark&default-tab=js,result"       frameBorder="no"       allowTransparency       allowFullScreen     />); };  // ...

When saved, we should be able to see the CodePen embed inside the rich text editor:

Notice that the iFrame has an embed URL with some parameters for how it should be displayed. Of course, we could've asked someone to dive into CodePen to obtain this URL, but it's probably better for to use the regular one. We'll take the effort to reassemble into what we need:

The last part is to take the URL from the field, and get the hash and user out of it.

We split the URL string on forward slashes into an array. Then we use array destructuring to assign the different array elements to a variable. Since we only need the user and the hash we leave the other positions empty. This method isn't bulletproof, as it assumed a specific format for the URL, but it works for this example. Then we reassemble the embedUrl by using template literals.

import React from "react";  const CodePenPreview = ({ value }) => {   const { url } = value;   const splitURL = url.split("/");   // [ 'https:', '', 'codepen.io', 'sdras', 'pen', 'gWWQgb' ]   const [, , , user, , hash] = splitURL;   const embedUrl = `https://codepen.io/$ {user}/embed/$ {hash}?height=370&theme-id=dark&default-tab=result`;   return (     <iframe       height="370"       style={{ width: '100%' }}       scrolling="no"       title="CodePen Embed"       src={embedUrl}       frameBorder="no"       allowTransparency       allowFullScreen     />   ); }; // ...

Save the changes and voilá; we're pretty much done with the custom CodePen block!

Taking it further

Now, you probably noticed that Chris had put more settings into his custom block. Nothing is stopping us from doing the same! If we look up the documentation for the React CodePen embed component that we installed, we'll find a table of properties that it can take. We can add these as fields in the schema definition. For example, if we wanted to add the themeId, we could do it as follows:

import React from "react"; import Codepen from "react-codepen-embed";  const CodePenPreview = ({ value }) => {   const { url, themeId = "dark" } = value; // <= add themeId here, default it to "dark"   const splitURL = url.split("/");   // [ 'https:', '', 'codepen.io', 'sdras', 'pen', 'gWWQgb' ]   const [, , , user, , hash] = splitURL;   const embedUrl = `https://codepen.io/$ {user}/embed/$ {hash}?height=370&theme-id=$ {themeId}&default-tab=result`; // <= add themeId here   return (     <iframe       height="370"       style={{ width: '100%' }}       scrolling="no"       title="CodePen Embed"       src={embedUrl}       frameBorder="no"       allowTransparency       allowFullScreen     />   ); };  export default {   name: "codepen",   type: "object",   title: "CodePen Embed",   preview: {     select: {       url: "url",       themeId: "themeId" // <= add themeId here     },     component: CodePenPreview   },   fields: [     {       name: "url",       type: "url",       title: "CodePen URL"     },     // Add the new field below     {       name: "themeId",       type: "string",       title: "Theme ID",       description: 'You can use "light" and "dark" also.'     }   ] };

Conclusion

We just looked at how schemas for Sanity Studio work, and learned how to make previews for custom components to boot! Hopefully, you now know enough to make pretty much any custom component with a preview using these same principles. If you do, I would love to know about it either on Twitter or in the comments.

The post Recreating the CodePen Gutenberg Embed Block for Sanity.io appeared first on CSS-Tricks.

CSS-Tricks

, , , , ,

Recreating the Facebook Messenger Gradient Effect with CSS

One Sunday morning, I woke up a little earlier than I would’ve liked to, thanks to the persistent buzzing of my phone. I reached out, tapped into Facebook Messenger, and joined the conversation. Pretty soon my attention went from the actual conversations to the funky gradient effect of the message bubbles containing them. Let me show you what I mean:

This is a new feature of Messenger, which allows you to choose a gradient instead of a plain color for the background of the chat messages. It’s currently available on the mobile application as well as Facebook’s site, but not yet on Messenger’s site. The gradient appears “fixed” so that chat bubbles appear to change background color as they scroll vertically.

I thought this looked like something that could be done in CSS, so… challenge accepted!

Let’s walk through my thought process as I attempted to recreate it and explain the CSS features that were used to make it work. Also, we’ll see how Facebook actually implemented it (spoiler alert: not the way I did) and how the two approaches compare.

Getting our hands dirty

First, let’s look at the example again to see what exactly it is that we’re trying to achieve here.

In general, we have a pretty standard messaging layout: messages are divided into bubbles going from top to bottom, ours on the right and the other people in the chat on the left. The ones on the left all have a gray background color, but the ones on the right look like they’re sharing the same fixed background gradient. That’s pretty much it!

Step 1: Set up the layout

This part is pretty simple: let’s arrange the messages in an ordered list and apply some basic CSS to make it look more like an actual messaging application:

<ol class="messages">   <li class="ours">Hi, babe!</li>   <li class="ours">I have something for you.</li>   <li>What is it?</li>   <li class="ours">Just a little something.</li>   <li>Johnny, it’s beautiful. Thank you. Can I try it on now?</li>   <li class="ours">Sure, it’s yours.</li>   <li>Wait right here.</li>   <li>I’ll try it on right now.</li> </ol>

When it comes to dividing the messages to the left and the right, my knee-jerk reaction was to use floats. We could use float: left for messages on the left and float: right for messages on the right to have them stick to different edges. Then, we’d apply clear: both to on each message so they stack. But there’s a much more modern approach — flexbox!

We can use flexbox to stack the list items vertically with flex-direction: column and tell all the children to stick to the left edge (or “align the cross-start margin edges of the flex children with cross-start margin edges of the lines,” if you prefer the technical terms) with align-items: flex-start. Then, we can overwrite the align-items value for individual flex items by setting align-self: flex-end on them.

What, you mean you couldn’t visualize the code based on that? Fine, here’s how that looks:

.messages {   /* Flexbox-specific styles */   display: flex;   flex-direction: column;   align-items: flex-start;    /* General styling */   font: 16px/1.3 sans-serif;   height: 300px;   list-style-type: none;   margin: 0 auto;   padding: 8px;   overflow: auto;   width: 200px; }  /* Default styles for chat bubbles */ .messages li {   background: #eee;   border-radius: 8px;   padding: 8px;   margin: 2px 8px 2px 0; }  /* Styles specific to our chat bubbles */ .messages li.ours {   align-self: flex-end; /* Stick to the right side, please! */   margin: 2px 0 2px 8px; }

Some padding and colors here and there and this already looks similar enough to move on to the fun part.

Step 2: Let’s color things in!

The initial idea for the gradient actually came to me from this tweet by Matthias Ott (that Chris recreated in another post):

The key clue here is mix-blend-mode, which is a CSS property that allows us to control how the content of an element blends in with what’s behind it. It’s a feature that has been present in Photoshop and other similar tools for a while, but is fairly new to the web. There’s an almanac entry for the property that explains all of its many possible values.

One of the values is screen: it takes the values of the pixels of the background and foreground, inverts them, multiplies them, and inverts them once more. This results in a color that is brighter than the original background color.

The description can seem a little confusing, but what it essentially means is that if the background is monochrome, wherever the background is black, the foreground pixels are shown fully and wherever it is white, white remains.

With mix-blend-mode: screen;</code on the foreground, we'll see more of the foreground as the background is darker.</figcaption></figure>

So, for our purposes, the background will be the chat window itself and the foreground will contain an element with the desired gradient set as the background that’s positioned over the background. Then, we apply the appropriate blend mode to the foreground element and restyle the background. We want the background to be black in places where we want the gradient to be shown and white in other places, so we’ll style the bubbles by giving them a plain black background and white text. Oh, and let’s remember to add <code>pointer-events: none to the foreground element so the user can interact with the underlying text.

At this point, I also changed the original HTML a little. The entire chat is a wrapper in an additional container that allows the gradient to stay “fixed” over the scrollable part of the chat:

.messages-container:after {   content: '';   background: linear-gradient(rgb(255, 143, 178) 0%, rgb(167, 151, 255) 50%, rgb(0, 229, 255) 100%);   position: absolute;   left: 0;   top: 0;   height: 100%;   width: 100%;   mix-blend-mode: screen;   pointer-events: none; }  .messages li {   background: black;   color: white;   /* rest of styles */ }

The result looks something like this:

The gradient applied to the chat bubbles

Step 3: Exclude some messages from the gradient

Now the gradient is being shown where the text bubbles are under it! However, we only want it to be shown over our bubbles — the ones along the right edge. A hint to how that can be achieved is hidden in MDN’s description of the mix-blend-mode property:

The mix-blend-mode CSS property sets how an element’s content should blend with the content of the element’s parent and the element’s background.

That’s right! The background. Of course, the effect only takes into account the HTML elements that are behind the current element and have a lower stack order. Fortunately, the stacking order of elements can easily be changed with the z-index property. So all we have to do is to give the chat bubbles on the left a higher z-index than that of the foreground element and they will be raised above it, outside of the influence of mix-blend-mode! Then we can style them however we want.

The gradient applied to the chat bubbles.

Let’s talk browser support

At the time of writing, mix-blend-mode is not supported at all in Internet Explorer and Edge. In those browsers, the gradient is laid over the whole chat and others’ bubbles appear on top of it, which is not an ideal solution.

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

Chrome Opera Firefox IE Edge Safari
41 29 32 No No TP

Mobile / Tablet

iOS Safari Opera Mobile Opera Mini Android Android Chrome Android Firefox
12.2 46 No 67 71 64

So, this is what we get in unsupported browsers:

How browsers that don’t support mix-blend-mode render the chat.

Fortunately, all the browsers that support mix-blend-mode also support CSS Feature Queries. Using them allows us to write fallback styles for unsupported browsers first and include the fancy effects for the browsers that support them. This way, even if a user can’t see the full effect, they can still see the whole chat and interact with it:

A simplified UI for older browsers, falling back to a plain cyan background color.

Here’s the final Pen with the full effect and fallback styles:

See the Pen
Facebook Messenger-like gradient coloring in CSS
by Stepan Bolotnikov (@Stopa)
on CodePen.

Now let’s see how Facebook did it

Turns out that Facebook’s solution is almost the opposite of what we’ve covered here. Instead of laying the gradient over the chat and cutting holes in it, they apply the gradient as a fixed background image to the whole chat. The chat itself is filled with a whole bunch of empty elements with white backgrounds and borders, except where the gradient should be visible.

The final HTML rendered by the Facebook Messenger React app is pretty verbose and hard to navigate, so I recreated a minimal example to demonstrate it. A lot of the empty HTML elements can be switched for pseudo-elements instead:

See the Pen
Facebook Messenger-like gradient coloring in CSS: The Facebook Way
by Stepan Bolotnikov (@Stopa)
on CodePen.

As you can see, the end result looks similar to the mix-blend-mode solution, but with a little bit of extra markup. Additionally, their approach provides more flexibility for rich content, like images and emojis . The mix-blend-mode approach doesn’t really work if the background is anything but monochrome and I haven’t been able to come up with a way to “raise” inner content above the gradient or get around this limitation in another way.

Because of this limitation, it’s wiser to use Facebook’s approach in an actual chat application. Still, our solution using mix-blend-mode showcases an interesting way to use one of the most under-appreciated CSS properties in modern web design and hopefully it has given you some ideas on what you could do with it!

The post Recreating the Facebook Messenger Gradient Effect with CSS appeared first on CSS-Tricks.

CSS-Tricks

, , , ,
[Top]