<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Stuart Roskelley on Medium]]></title>
        <description><![CDATA[Stories by Stuart Roskelley on Medium]]></description>
        <link>https://medium.com/@sroskelley?source=rss-704f509c290c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*UPofW_MRE6PcLLBBU1Wvfw.jpeg</url>
            <title>Stories by Stuart Roskelley on Medium</title>
            <link>https://medium.com/@sroskelley?source=rss-704f509c290c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 14:53:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sroskelley/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Why do you write code?]]></title>
            <link>https://medium.com/@sroskelley/why-do-you-write-code-af3508554a26?source=rss-704f509c290c------2</link>
            <guid isPermaLink="false">https://medium.com/p/af3508554a26</guid>
            <category><![CDATA[why]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[thoughts]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Stuart Roskelley]]></dc:creator>
            <pubDate>Tue, 17 Aug 2021 19:12:17 GMT</pubDate>
            <atom:updated>2021-08-17T19:12:17.419Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding your answer can help you improve your skills, but also find more purpose in what you do!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jCZr9EmyP6brF7lEOYpYUg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@trueagency?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">True Agency</a> on <a href="https://unsplash.com/s/photos/coder?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Do you know why you code?</h3><p>As a seasoned software engineer, I find that answering this question isn’t always clear, but also seems to change over time. Let’s talk about some reasons why you might find purpose in coding, followed by what this all means for you.</p><h3>Some reasons why you might code</h3><p><strong>Coding is fun<br></strong>The act of coding can be fun in itself because there is just so much code you can write that is completely unique. It is the same type of idea why a person might write a novel or go for a hike. You enjoy the activity for the activity itself and other benefits just seem to flow in as a result.</p><p><strong>It’s a paycheck</strong><br>Maybe you are motivated to code because it pays well and you want to live a certain lifestyle or have certain things. This motivation may be more of a means to an end, rather than the coding itself.</p><p><strong>The daily challenges</strong><br>Coding can definitely be a series of daily challenges, whether that is solving a specific bug, designing a specific element, or maybe finding some way to optimize something. Every day seemingly can bring something new, keeping every day fresh.</p><p><strong>The logical thinking</strong><br>Coding requires a way of thinking that is more logical and step by step. After all, it is giving instructions to a computer, which only operates based on logic and step driven instructions. Some people might fit right into this line of thinking with their personality.</p><p><strong>Constantly changing landscape</strong><br>Similar to the daily challenges, but at a higher scope, coding is always changing. You have new techniques, new languages, new frameworks, and more coming out constantly. Some stick around, some don’t, but each can be learned from.</p><p><strong>The teamwork, or the solo</strong><br>Some might code for the team and the sense of accomplishment that comes with the teamwork to completely a project. They might hunger for the social interaction of a close-knit group with the same purpose. On the flipside, you might code because you don’t necessarily have to work with a team. Maybe you like the fact that you write your own code and learn on your own.</p><p><strong>The design and organization</strong><br>Coding in different applications across every industry means different design challenges, not only for the end-user, but also organizing your code and architecture. This is a challenge in itself that can drive people to code.</p><p><strong>The responsibility</strong><br>When working on a project for a client, company, or some end-user, there is going to be a level of responsibility that comes with coding. You are responsible for that code doing what it is supposed to do, which can fill a need that some people might have. This responsibility could also come from some side-effect of the coding, like the responsibility of supporting a family.</p><p><strong>The end result</strong><br>Maybe your purpose is driven by the need to complete a project. Or maybe it is the need for the compensation at the end. For this, coding might not always be enjoyable in the moment, but for the satisfaction of the outcome.</p><p><strong>The praise</strong><br>Some might have the personality where they need to have praise for the work they perform. This could be compensation in a job, a number of “likes” for your github project, or some other form of praise.</p><h3>So, what does this actually mean?</h3><p>Understanding <strong>why</strong> you do something is a crucial aspect to improving your skills and knowing what is next. To know why you do something gives you a sense of purpose and higher level of happiness. Let’s look at two examples:</p><ul><li>John is a programmer in an enterprise level company. He is in charge of writing microservices for other departments. They give him the requirements, he builds it in a timeline, then moves on to the next project. John works with a team as needed, the projects are a good mix of easy and difficult, and John doesn’t have to worry about his next paycheck. However, he finds it difficult to care much about his job aside what he is paid to do. He does his job and goes home, then wakes up again and repeats the cycle. John isn’t particularly happy about his job. He doesn’t hate it, but could move on to another job without a second thought.</li><li>Sue is also a programmer with the same level of experience as John at the same company. She also does the same types of tasks as John. Sue loves her job and comes in early each day. She actively contributes to the team for new ideas. Sue finds the projects rewarding with a good mix of easy and difficult and is happy to get paid for her work. Most of all, Sue isn’t there for the money but because she loves what she does.</li></ul><p>In these examples, both of these people essentially have the same job, the same requirements, potentially the same pay, the same team, the same culture, etc. Why does Sue seem so much more involved and happy with her job?</p><p>I’m sure there’s plenty of answers to this question, but I think one that will stand out time and time again is <strong>purpose</strong>. Sue knows <em>why</em> she codes. What her motivations are for that why will be personal to her, but it is what drives her. It gives her a sense of passion that John just doesn’t have.</p><h4>How do I find my why?</h4><p>I think you first need to understand what makes you happy. Above I listed a few reasons one why people might enjoy coding, but it is deeper than that. This will be part of your personality and will carry throughout other aspects of your life, not just coding.</p><p>For example, I find I am happiest when I am actively engaged in a project that requires thinking and problem solving. I can find this type of challenge in many areas. Some might be cooking, woodworking, model building, or even playing video games. Coding is another level of complexity for the thinking and problem solving, so I can enjoy it that much more.</p><p>Once you know what makes you happy, you can begin to explore why you write code. For most, It is going to drive back to what makes you happy and fulfills your personality’s needs. Finding this answer isn’t going to be easy.</p><h4>Search yourself</h4><p>To answer the question “how do I find my why?”, you need to search yourself. Put some of that same deep thought that you put into your coding skills into an exercise of self-reflection. Here’s some steps you can take to get started!</p><ol><li>Find a quiet place and time to allow some adequate reflection. Remove any distractions (turn off your phone, not just silence it!) and give yourself a solid hour of uninterrupted time for pure thought.</li><li>Have a notebook and pencil ready. This needs to be a physical notebook to prevent any possible distraction, but something about physically writing something can help ideas flow more clearly. Eventually with practice of removing distractions, you can upgrade to typing on a physical keyboard. But to start, just have a notebook and pencil.</li><li>Reserve the first page of your thought session to be blank (we’ll write there later). Start to ask yourself questions that require deep thought. “What makes me happy?” is not sufficient here. You need to think about specific things you do and have done and analyze how they made you feel. Just like you analyze a problem for coding and how to solve it, we’re doing the same for the self-reflection.</li><li>As you think, write down everything that comes to mind on that second page after the blank page. Write about experiences you’ve had, the good and bad in them, and the feelings around them. As you write, let the ideas flow. If you get on a tangent thought thread, write about it!</li><li>Once you think you understand what makes you happy, flip back to that first blank page and clearly write a paragraph about it. Try to summarize in just one or two sentences that specific thing that makes you happy.</li><li>Also on the first page, think about the bad times. What made those things bad and why were you unhappy? Summarize this into a paragraph.</li></ol><p>Let’s do a quick example thought thread. Maybe I can start thinking about jobs I’ve had. Eventually I might land on a specific one. I’ll think about the team I worked on, the hiring process, the projects I worked on. I might start to think about other teams I interacted with, how I was rewarded (or chastised potentially), and actions I took. I might also think about other factors in my life unrelated to the job. Maybe there were family struggles at the same time, or maybe life at home was smooth sailing. I might think about things that make me happy in each space and things that make me frustrated.</p><p>I haven’t carved out a tip of the iceberg and I could keep going with a thought train here. That previous paragraph I was thinking about a specific job and some of the ups and downs. I’m sure I could have written pages and pages of the experience and feelings. As you dive more into deep thought like this, you may find you’ll do the same and that reserved hour is not enough time!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Jc6Xx6s1H-ITELs5poWsiA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@brucemars?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">bruce mars</a> on <a href="https://unsplash.com/s/photos/win?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>I know what makes me happy! Now what?</h3><p>Let’s reign it back in and look at the final piece. Now that you understand what makes you happy and why you might do things, you can start to analyze actions you can take specific to your coding!</p><p>Take your statement you wrote down on what makes you happy, and convert that to a why statement specifically for coding. For my example, my “happy” statement might be:</p><pre>I am happiest when I am actively engaged with a task that requires problem solving.</pre><p>Also taking the opposite statement, I might have something like this for what makes me unhappy:</p><pre>I am most unhappy when I do not find progress or end results in things I do.</pre><p>Now, put these into a why for your coding! Start your sentence with “I code because” and keep to no more than one or two simple sentences. For my statements above, I might have something like:</p><pre>I code because I am happy when I am challenged by solving coding problems and I can see the results of solving those problems.</pre><h4>Act on it!</h4><p>Your statement should accurately reflect a sense of who you are. But more so, this should be your purpose and feel like the <em>right</em> <strong>why</strong> for you. Once you understand your why statement, this can be so beneficial to help you progress!</p><p>For my example statement above, I now clearly know what makes me happiest, specific to my coding. So I can actively use this statement to help me make decisions when they might not always be so clear. A couple examples:</p><ul><li>I have a side project that I like the idea, but I find it is hard to constantly work on. Should I invest more time into it, or abandon it?<br> — With my why statement, I know that if the project isn’t challenging me enough I probably need to just abandon it.</li><li>I am paid well at my job and want to stick around, but I’m finding it hard to feel fulfilled.<br> — With my why statement above, I know I am probably missing the challenges that I need, so I either need to ask for more challenging work, or maybe even switch jobs if they can’t provide that.</li><li>I feel lazy all the time and don’t understand why I find it so hard to get out of bed sometimes.<br> — Thinking again about my statement, I know I need some project to give me motivating challenges to fulfill that deeper need.</li></ul><p>Obviously, your statements are going to be quite different. Maybe you are driven by compliments, or maybe you are driven by a sense of teamwork. These would provide quite different answers to the above questions, but you should clearly be able to answer them. If you can’t clearly answer them directly from your why statement, you need to re-evaluate your statement and dig deeper.</p><h3>Final thoughts</h3><p>Your why may slightly adjust over the years. This is expected because life changes! Mine definitely changed when I had kids versus when I was back in high school. The underlying <em>why </em>stays the same, but the reasons and motivations that build on that why shift. You are in control of your own life, no matter what situation you are in, and understanding your why can help drive your decisions in a clear path, even if options for the decisions are extremely limited.</p><p>If you’ve completed this exercise and have found your why, please feel free to comment it and share it! Sharing can help solidify your thoughts, but also help you understand why others might be motivated completely differently than you. If this article helped, I encourage you to help others understand their why, but also continue to occasionally self-evaluate and make sure you are still aligned with your why.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af3508554a26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Theming in React Using SASS Variables]]></title>
            <link>https://medium.com/@sroskelley/theming-in-react-using-sass-variables-26d2d3052c4?source=rss-704f509c290c------2</link>
            <guid isPermaLink="false">https://medium.com/p/26d2d3052c4</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[themes]]></category>
            <category><![CDATA[variables]]></category>
            <category><![CDATA[sass]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Stuart Roskelley]]></dc:creator>
            <pubDate>Thu, 21 Nov 2019 05:20:51 GMT</pubDate>
            <atom:updated>2019-11-21T05:20:51.800Z</atom:updated>
            <content:encoded><![CDATA[<h4>You’ve got some SASS implementation for your React app and you’re thinking about how you can re-use those variables in your React code. Let’s explore one possible solution to this problem!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rcws6K8FP4aQhTpgGz9HXQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@badashproducts?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ash Edmonds</a> on <a href="https://unsplash.com/s/photos/code-color?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>There’s a lot of ways to theme an app. So many, in fact, that it is downright overwhelming sometimes. Not to mention that the requirements for every app might require a whole new theming structure. I’d like to spend a few minutes going over some ideas on how you can utilize SASS variables within React and have your theme update on the fly.</p><p>Now, if I was building theming from scratch all over, it would probably be more efficient to store all your variables in JSON, then import to both React and SASS. However, for many developers, theming is an afterthought, so you probably already have some styling in SASS and are thinking about how you can get some of that back in the javascript side. So let’s get started!</p><p>A quick note before we dive in. If you need some ideas on setting up SASS theming, variables, etc., check out this article: <a href="https://medium.com/@sroskelley/theming-in-sass-67b8c0265e3f">Theming in SASS</a>. We’re going to copy the basics from there as a quick boilerplate.</p><h3>The SASS Setup</h3><p>Let’s define 4 scss files. The definitions file will have static references to the actual colors. The light and dark theme files will contain theme variables that grab references to those colors. Then the functions file just provides a utility function to map the theme files to the definitions file.</p><pre>// colorDefinitions.scss</pre><pre>$colors: (<br> tronLightBlue: #a1fefe,<br> tronDarkBlue: #004242,<br> white: #FFFFFF,<br> black: #000000<br>);<br></pre><pre>// functions.scss</pre><pre>@import &#39;./colorDefinitions&#39;;<br><em>//gets a color value from color map, defined in colorDefinitions<br></em>@function color($colorName) {<br>  @return map-get($colors, $colorName);<br>}<br></pre><pre>// light.scss</pre><pre>@import &#39;./functions&#39;;<br>$light: (<br>  borderDark:      color(tronDarkBlue),<br>  borderLight:     color(tronLightBlue),<br>  textDark:        color(black),<br>  textLight:       color(white),<br>  backgroundDark:  color(tronDarkBlue),<br>  backgroundLight: color(tronLightBlue)<br>);<br></pre><pre>// dark.scss</pre><pre>@import &#39;./functions&#39;;<br>$dark: (<br>  borderDark:      color(tronLightBlue),<br>  borderLight:     color(tronDarkBlue),<br>  textDark:        color(white),<br>  textLight:       color(black),<br>  backgroundDark:  color(tronLightBlue),<br>  backgroundLight: color(tronDarkBlue)<br>);</pre><p>Nothing complicated yet — just defining our theme variables via a couple themes. Okay, let’s export these themes to javascript! Now, there’s a trick we’re going to utilize here:</p><p>ICSS export. If you are using css modules, then this is built in. If not, you need to be! You may have seen the syntax for export like so:</p><pre>:export {<br>  key: value;<br>}</pre><p>This essentially will allow key to be used by javascript imports when you import this file. We’ll use this via a mixin to export our themes dynamically. Let’s do it.</p><pre>// mixins.scss</pre><pre><a href="http://twitter.com/mixin">@mixin</a> generateThemeJSExports($themeName, $newThemeMap) {<br>  //creates/adds to list of theme names<br>  $themes: append($themes, $themeName, $separator: comma) !global;<br>  <br>  //exports theme variables<br>  :export {<br>    themes: $themes;<br>    <a href="http://twitter.com/each">@each</a> $key, $value in $newThemeMap {<br>      theme_#{$themeName}_#{$key}: $value;<br>    }<br>  }<br>}</pre><pre><br>// colors.scss</pre><pre>@import &#39;mixins&#39;;</pre><pre>$themes: ();</pre><pre><a href="http://twitter.com/import">@import</a> &#39;light&#39;;<br><a href="http://twitter.com/include">@include</a> generateThemeJSExports(light, $light);</pre><pre><a href="http://twitter.com/import">@import</a> &#39;dark&#39;;<br><a href="http://twitter.com/include">@include</a> generateThemeJSExports(dark, $dark);</pre><p>That’s it on the SCSS side! Here’s what happens. When you import the colors.scss file into javascript, the mixin generateThemeJSExports runs for each theme, exporting variables to javascript. The annoying part of this is that :export only allows exporting a flat map. So, we have to export each theme variable as something unique to each theme. I’ve chosen to do theme_&lt;themeName&gt;_&lt;themeVariable&gt; for each variable.</p><h3>The React Side</h3><p>We’ve now got all the SASS setup for potential theming in javascript. We can use these variables as simple as:</p><pre>// some js file</pre><pre>import * as colors from &#39;colors.scss&#39;; //or colors.module.scss if using create-react-app<br>console.log(colors.theme_light_borderDark);<br>// output will be #004242, as defined via our light theme</pre><p>Let’s face it, while this works, it isn’t very useful without a few helper methods. Maybe let’s give a sample app react file in its entirety, then dissect the important bits.</p><pre>// app.js</pre><pre>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom&quot;;<br>import theme, { getCurrentTheme, initThemeObserver } from &quot;./themeColors&quot;;<br>import $ from &quot;jquery&quot;;</pre><pre>import &quot;./app.scss&quot;;</pre><pre>$(&quot;html&quot;).addClass(&quot;light&quot;); // sets default theme</pre><pre>class App extends React.Component {<br>  componentDidMount() {<br>    this.themeObserver = initThemeObserver(this.onThemeChange);<br>  }</pre><pre>  componentWillUnmount() {<br>    if (this.themeObserver) this.themeObserver.disconnect();<br>  }</pre><pre>  onThemeChange = () =&gt; {<br>    this.forceUpdate(); // propagates any theme color changes on the js side down through the whole app<br>  };</pre><pre>  toggleThemeType = () =&gt; {<br>    $(&quot;html&quot;)<br>      .toggleClass(&quot;light&quot;)<br>      .toggleClass(&quot;dark&quot;);<br>  };</pre><pre>  render() {<br>    return (<br>      &lt;&gt;<br>        &lt;button<br>          className=&quot;myButton&quot;<br>          style={{<br>            backgroundColor: theme(&quot;backgroundLight&quot;),<br>            borderColor: theme(&quot;borderDark&quot;),<br>            color: theme(&quot;textDark&quot;)<br>          }}<br>          onClick={this.toggleThemeType}<br>        &gt;<br>          Toggle Light/Dark Theme<br>        &lt;/button&gt;<br>        &lt;div&gt;The current theme is: {getCurrentTheme()}&lt;/div&gt;<br>      &lt;/&gt;<br>    );<br>  }<br>}</pre><pre>const rootElement = document.getElementById(&quot;root&quot;);<br>ReactDOM.render(&lt;App /&gt;, rootElement);</pre><p>Starting from the top:</p><ul><li>we import 3 things from a themeColors file. We’ll go over those in a bit.</li><li>When we mount the component, we initialize an observer. Essentially this allows us to watch for changes on the html element for class name changes so we can switch our theme dynamically. While this is NOT necessary in this example, it is completely necessary when you have a more complex app where the theming isn’t controlled in the same file. It’s overkill here for sure, but I’d rather give you the code in case you need it!</li><li>When the observer tells us a change happens, we do a forceUpdate. Without this, the component(s) don’t know to re-render the new theme colors. They’d be stuck using the colors they initialized with, until something else re-renders the components.</li><li>We have a simple button that toggles the theme in this example. Normally you’d need something more versatile to match your needs for changing themes. You can see we’re applying styles via our theme on the button. This helps demonstrate the dynamic nature of these colors.</li></ul><p>So, when this app renders, we’ll have the light theme applied by default. We’ll get those light values and apply them to the button. When the user clicks the button, the theme switches to dark and the observer will tell us the theme changed. As a result, the component re-renders, thus pulling in the new theme colors for the dark theme.</p><h3>Last code snippet, I promise!</h3><p>The only thing left is the helper functions for the above observer, and getting the theme variables into a more manageable state. Here you go:</p><pre>const _ = require(&quot;lodash&quot;);<br>const themeColors = require(&quot;./colors.module.scss&quot;); // using the .module part isn&#39;t necessary for a regular, non-create-react-app project</pre><pre>const DEFAULT_THEME = &quot;light&quot;;</pre><pre>const themes = _.map(themeColors.themes.split(&quot;,&quot;), val =&gt; _.trim(val));</pre><pre>/*<br>  For each theme variable, we pick the ones that start with &quot;theme_&quot;.<br>  These will be our theme variables as theme_themeName_variableName.<br>  This will output a flat object of variable names with their values.<br>*/<br>const themeVars = _.pickBy(themeColors, (value, key) =&gt; {<br>  if (key === &quot;themes&quot;) return false;<br>  if (key.indexOf(&quot;theme_&quot;) !== 0) return false;<br>  return true;<br>});</pre><pre>/*<br>  This transforms the flat object from above into a nested object like so:<br>  {<br>    themeName: {<br>      variableName: value,<br>      ...<br>    },<br>    ...<br>  }<br>*/<br>const byTheme = _.transform(<br>  themeVars,<br>  (result, value, key) =&gt; {<br>    const parts = key.split(&quot;_&quot;);<br>    const theme = parts[1];<br>    const variable = parts[2];<br>    result[theme] = result[theme] || {};<br>    result[theme][variable] = value;<br>  },<br>  {}<br>);</pre><pre>/*<br>  gets the current theme the user has applied, from the html el classname<br>*/<br>export function getCurrentTheme() {<br>  const htmlClasses = document.querySelector(&quot;html&quot;).className.split(/\s+/);<br>  const matches = _.intersection(themes, htmlClasses);<br>  return matches[0] || DEFAULT_THEME;<br>}</pre><pre>/*<br>  similar to the scss theme() method - returns the color for the current theme<br>*/<br>export default function theme(variableName) {<br>  const currentTheme = getCurrentTheme();<br>  const variables = byTheme[currentTheme];<br>  return variables[variableName];<br>}</pre><pre>/* *************** functions below here are not generally needed except at the root app level ***************** */</pre><pre>function onMutationChange(onThemeChange, mutationsList) {<br>  let wasUpdated = false;<br>  const currentTheme = getCurrentTheme();</pre><pre>mutationsList.forEach(mutation =&gt; {<br>    if (mutation.attributeName === &quot;class&quot;) {<br>      if (currentTheme !== window.__currentTheme) {<br>        wasUpdated = true;<br>      }<br>    }<br>  });</pre><pre>if (wasUpdated) {<br>    onThemeChange(window.__currentTheme, currentTheme);<br>    window.__currentTheme = currentTheme;<br>  }<br>}</pre><pre>/*<br>  inits a mutation observer to watch the html element for class changes.<br>  onThemeChange should be a method with optional usage of params oldTheme, newTheme.</pre><pre>This is needed for react, since react won&#39;t rerender with the new theme colors<br>  if the theme changes. We can watch the change manually, then have a callback that <br>  allows us to manually rerender as a result.<br>*/<br>export function initThemeObserver(onThemeChange) {<br>  window.__currentTheme = getCurrentTheme();<br>  const themeObserver = new MutationObserver(<br>    onMutationChange.bind(null, onThemeChange)<br>  );<br>  themeObserver.observe(document.querySelector(&quot;html&quot;), { attributes: true });<br>  return themeObserver;<br>}</pre><p>There’s a lot in here, so I added a bunch of comments. I would recommend copying into your favorite editor to get a more readable syntax highlighting and to go through the various things happening. We basically only export 3 methods: the initThemeObserver, a helper getCurrentTheme, and the default export for theme.</p><h3>That’s It!</h3><p>This looks like a lot. That’s because it is! Theming can be much simpler, but you’ll find that the more you want in the theming, the more complex it becomes and typically ends in heavy rewrites on things.</p><p>The code in this article should help give you the components to use this in a complex production app and have quite a few headaches avoided. If you’ve got everything setup correctly from these examples, you should now have a working React theming, using SASS variables!</p><p>Try it out here: <a href="https://codesandbox.io/s/sass-variables-in-react-0tumj">https://codesandbox.io/s/sass-variables-in-react-0tumj</a>. You’ll see the button switches between light and dark coloring when clicked.</p><p>I also mentioned the <a href="https://medium.com/@sroskelley/theming-in-sass-67b8c0265e3f">Theming in SASS</a> article. If you built your app to be robust and smart up front, you may never need any theming variables in React, as you typically can handle it all in SASS alone. However, rarely is theming implemented until an app is much larger, so artifacts creep their way in. If SASS and React theming are used together, you can implement complete dynamic themes from existing code effectively with reusability.</p><p>Good luck and happy theming!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26d2d3052c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is a Data Layer? Tips and Best Practices]]></title>
            <link>https://medium.com/@sroskelley/what-is-a-data-layer-tips-and-best-practices-ccb0c1bacf6f?source=rss-704f509c290c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccb0c1bacf6f</guid>
            <category><![CDATA[tealium]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[google-tag-manager]]></category>
            <category><![CDATA[adobe]]></category>
            <category><![CDATA[google-analytics]]></category>
            <dc:creator><![CDATA[Stuart Roskelley]]></dc:creator>
            <pubDate>Thu, 14 Nov 2019 20:38:41 GMT</pubDate>
            <atom:updated>2019-11-14T20:38:41.156Z</atom:updated>
            <content:encoded><![CDATA[<h4>Websites dealing with any Business Intelligence need a data layer! Here’s a few ideas to getting the most out of yours.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qgGar8xaNwHLSQN-ZwGWow.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@element5?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Element5 Digital </a>from <a href="https://www.pexels.com/photo/assorted-books-on-shelf-1370295/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>There’s lots of information out there on data layers, including what they are, and different ways to construct them. I’ll take a look at some common ones we see on most websites, then how to construct the best data layer for your needs. But first…</p><h3>What is a Data Layer?</h3><p>Every piece of software ever created has multiple layers. The larger the application, the more layers it has. Kind of like a sandwich.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NkSTk192g-6r-6rj8Wu1Sg.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@angele-j-35172?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Angele J </a>from <a href="https://www.pexels.com/photo/food-plate-sandwich-meal-139746/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>A sandwich has many layers that all support each other to make a delicious combination of perfection. Each layer by itself can serve useful benefits (certain flavors, textures, vitamins, etc), but the sandwich as a whole can be an entire meal. Such is the same with software with each layer building on top of each other until you get a useful application or product.</p><p>The data layer is kind of like one of those layers. It might not be necessary in all cases, but when you have it, it can make the whole sandwich that much better. When the data layer is incorrectly implemented, it too can also negatively affect that delicious sandwich.</p><p>So what is it? A data layer essentially is a specific layer in your application that is used for reporting and collecting data. This data will be used for analyzing later to help make business decisions. The content of the data layer is usually per user and may describe certain details about the user for various analytics, marketing purposes, etc.</p><p>While a data layer can be used in just about every software application, it is by far the most common on the web. If you have ever seen an ad on a website, or analytics, or campaigns, or those chat bubbles, or…the list goes on — then you’ve seen some form of a data layer. Nearly every third party vendor has some sort of information tracking on a user so they know how to interact with that user.</p><h3>What might a data layer contain?</h3><p>Anything you want! There’s a fine balance of what to include in a data layer. You want to include enough information about the user to make decisions, but not enough to overwhelm all your developer resources. Let’s look at an ecommerce website, since those are heavily influenced by user decisions.</p><ul><li>product information: id, name, price, sale price, category, size, color, …</li><li>order information: id, subtotal, tax, total, shipping, discounts, …</li><li>user information: id, city, state, country, preferences, first/last, …</li><li>page information: timing, promotions visible, products visible, category, region, currency, …</li><li>search information: term, num results, suggested terms, …</li><li>event information: event name, label of button clicked, …</li><li>lots and lots more…</li></ul><p>Each of these will be reported on any applicable pages where you need that information. So something like a page name and page type would appear on every page, but order information would only appear on the order confirmation page.</p><p>The data layer is going to contain all the data necessary (if possible) to provide to all your other vendors. So, this might contain all your custom dimensions for google analytics, all your recommendation information for power reviews, and just about everything else.</p><p>It will also contain events! This might be if a user clicks a certain button, then you might trigger an event. Or maybe they went through a certain flow, you could trigger another event. The idea of events is to indicate that something happened and you need to increment a counter.</p><h3>So, what does it look like?</h3><p>Each vendor will have a different data layer format, so there’s a lot of ways you can approach this. Let’s look at a couple common vendor specific layers, followed by some common tag management ones.</p><p>Google Analytics (GA)</p><pre>gtag(&#39;config&#39;, &#39;GA_MEASUREMENT_ID&#39;, {<br>  &#39;page_title&#39; : &#39;homepage&#39;,<br>  &#39;page_path&#39;: &#39;/home&#39;<br>});<br>gtag(&#39;event&#39;, &#39;timing_complete&#39;, {<br>  &#39;name&#39; : &#39;load&#39;,<br>  &#39;value&#39; : 3549,<br>  &#39;event_category&#39; : &#39;JS Dependencies&#39;,<br>  &#39;dimension1&#39;: &#39;foo&#39;<br>});</pre><p>You can see GA does each data point as a function call with attached data. Most params are going to be tied to configuration for that page, or an event (like purchase). Because everything is configured like this, each page is essentially an event. GA’s data layer is very specific for just their tag, so using their data in other vendors requires either a separate data layer, or integrations. You are also required to use their outlined variables for proper tracking.</p><p>Adobe Analytics (AA)</p><pre>s.pageName = &quot;homepage&quot;;<br>s.prop5 = &quot;homepage&quot;;<br>s.eVar5 = &quot;homepage&quot;;<br>s.events = &quot;event5,event5&quot;;<br>s.t(); //or s.tl() for events</pre><p>Unlike GA with mostly named params, Adobe mainly uses numbered variables called props, eVars, and events. There are some reserved names as well, but most are enumerated, then named within the AA product interface. Page views and events are essentially setup the same way, but the final call is distinguish by s.t() for page views and s.tl() for event calls. AA’s data layer is very specific for just their tag, so using their data in other vendors requires either a separate data layer, or integrations. However, since all the data is attached to a global s variable, any other vendor could potentially access it, as long as s isn’t cleared out. For AA, you are required to use their outlined variables for tracking (unless they are context variables, but that’s another topic).</p><p>Tealium</p><pre>utag_data = {<br>  page_name: &#39;homepage&#39;,<br>  page_type: &#39;home&#39;,<br>  currency: &#39;USD&#39;,<br>  promo_impressions: [&#39;123&#39;, &#39;234&#39;]<br>};</pre><pre>// for events<br>utag.link({<br>  ...some data like above<br>});</pre><p>Tealium’s tag manager is built for many vendors, so the data layer isn’t specific to any one vendor. They provide two separate flat tracking layers, one for the page view and one for events. Any vendor can access the utag_data object on the page, but most vendors will be implemented through the tag manager, where the data layer can be supplemented for each specific vendor as needed. The variables have an implied standard, but they can be named whatever you want, making this very flexible.</p><p>Google Tag Manager (GTM)</p><pre>dataLayer = [{<br>  pageName: &#39;homepage&#39;,<br>  pageType: &#39;home&#39;,<br>  currency: &#39;USD&#39;,<br>  promoImpressions: [&#39;123&#39;,&#39;234&#39;]<br>}];</pre><pre>// for events<br>dataLayer.push({<br>  ...some data like above<br>});</pre><p>Similar to Tealium, the variables can be named whatever you want and there is a page view and event setup that are different. However, similar to GA, GTM’s data layer is all event based, so you don’t have to have any page view code and could implement all with dataLayer.push(). For certain vendors (like GA), this data layer will have specific variable names and multiple levels of nesting, unlike the completely flat and open data layer Tealium utilizes.</p><p>W3C</p><pre>digitalData = {<br> pageInstanceID: &quot;MyHomePage-Production&quot;,<br> page:{<br>   pageInfo: {<br>     pageID: &quot;Home Page&quot;,<br>     destinationURL: &quot;<a href="http://mysite.com/index.html">http://mysite.com/index.html</a>&quot;<br>   },<br>   category:{<br>     primaryCategory: &quot;FAQ Pages&quot;,<br>     subCategory1: &quot;ProductInfo&quot;,<br>     pageType: &quot;FAQ&quot;<br>   },<br>   attributes:{<br>     country: &quot;US&quot;,<br>     language: &quot;en-US&quot;<br>   }<br> }<br>};</pre><p>Similar to Tealium and GTM, the W3C data layer can use all your own custom variable names and isn’t vendor specific generally. However, this standard is much more well defined and each data layer section is somewhat grouped into their type. This leads to a fairly nested object with specific variable names. The name and usage for pageview/event isn’t as specific as how the data is structured.</p><h3>So many options!</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FAANqYGD9LVsw8%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FAANqYGD9LVsw8%2Fsource.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FAANqYGD9LVsw8%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="343" frameborder="0" scrolling="no"><a href="https://medium.com/media/bec1bdb38c3d9b81166cdaa2612f04b7/href">https://medium.com/media/bec1bdb38c3d9b81166cdaa2612f04b7/href</a></iframe><p>I’ve only given you 5 examples. Imagine literally thousands of vendors all having their own formats on data layers! This is why it is so important to plan out your data layer instead of just tacking on bits and pieces as they come. This is also why the prevalence of tag managers have come into play so much more over the past decade or so.</p><h4>So how do I plan this out?</h4><p>I’ve known people that have whole consultancies built on this very question. I spent about 5 years doing it as well! Generally, here’s the process:</p><ol><li>Identify your vendors. This will be things like your analytics, marketing, support, etc. I find it’s useful to compile a big spreadsheet of each vendor you plan to use and include their code snippets and tracking requirements for each one.</li><li>For complex vendors (like analytics), identify your tracking needs. This includes figuring out the questions you need answered, then mapping those answers to the appropriate variables. Put those variables in another sheet for each complex vendor.</li><li>Start building a list of vendor-neutral variables. By taking another blank sheet, start making a list of all the variables that appear for each vendor and put them in a vendor neutral variable. For example, maybe I have a page type variable in AA as prop1, GA as pageType, and some other vendor as page. These are all the same page type, so maybe my vendor neutral variable becomes page_type. You’ll also want to repeat the step for events (checkout, newsletter submit, etc.)</li><li>Once you have these lists, then you can decide how to organize them. I personally like the flat approach Tealium does in their utag_data object. As a developer, this one is easiest to reference in comparison to nested data layers. However you decide to organize it, make sure it is readable, makes sense, and is flexible.</li><li>Implement it! Get it coded on the pages so you can start using it.</li></ol><h3>What else should I know?</h3><p>You have to remember that the data layer is a core piece of your software that will help drive decisions for your business. The more planning up front you can do before implementing, the more time you’ll save down the road. It is important to get it right so your data tracks correctly, so having a round of audits during the implementation is also crucial.</p><p>You also need to be consistent. Pick a variable naming scheme and stick with it. This goes for the values in the variables as well. This is by far where the most errors come from in implementations I’ve seen, sometimes to the point of completely breaking pages since developers weren’t given enough instruction. If you need hints on this, take a look at Tealium, GTM, or W3C examples, as those are very widely used and have defined standards.</p><p>Lastly, think smart about what you’re putting in the data layer. I’ve seen some outlandish requests for tracking that ended up never being used in any capacity, but took tons of dev hours to implement. Your data layer should 1) implement what is needed for your vendors, 2) implement what is needed to answer your questions. It doesn’t need more than this, but both of these absolutely need up front planning. If you don’t plan up front, it will cost a lot more later to add and maintain things that could have been avoided easily in the initial implementation.</p><h3>Final Thoughts</h3><p>Hopefully this article gives some insight on what the data layer is and how to use one. It doesn’t have to be hard, though it can be overwhelming up front. Just remember to plan up front and make it useful for you!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jrPr7OKxxd0eGw0i8l0nKA.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccb0c1bacf6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Theming in SASS]]></title>
            <link>https://medium.com/@sroskelley/theming-in-sass-67b8c0265e3f?source=rss-704f509c290c------2</link>
            <guid isPermaLink="false">https://medium.com/p/67b8c0265e3f</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[sass]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[scss]]></category>
            <category><![CDATA[themes]]></category>
            <dc:creator><![CDATA[Stuart Roskelley]]></dc:creator>
            <pubDate>Sat, 09 Nov 2019 05:20:32 GMT</pubDate>
            <atom:updated>2019-11-21T04:06:28.337Z</atom:updated>
            <content:encoded><![CDATA[<h4>Theming a web application can be a daunting task. This tutorial provides ideas and solutions to get a theme to meet your needs.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQchpy2ei8hZYtrK27YbrA.png" /><figcaption>It’s easier than it looks!</figcaption></figure><p>Theming is the bane of many developers because there’s always many variables to consider, including how those themes will get updated, implementing standards, how to make it easy to use, etc. It always seems like the more you dive into it, the more complex it becomes.</p><p>I’ve built many applications that use theming and wanted to share some insights that I’ve learned with different ways to theme. This article will focus on how I accomplished my latest theming endeavour in SASS, but the principles can be applied to other languages/tools as well.</p><p>Let’s first look at some of the requirements:</p><ul><li>The theming should be easy to understand (at least all the high level parts)</li><li>The implementation of said theming by developers should be easy to use</li><li>The theme setup should have a set of standardized colors that can be used for many theme attributes</li><li>The theming should allow multiple themes, as well as user customization on themes</li><li>For this example, we’ll just use colors, but you could apply the principles here to include other things like font sizes, standard padding sizes, etc.</li></ul><p>To further explain requirements, we’re looking for a very flexible system, but that can enforce certain usage. In my theming, I want to have each theme immediately available at the flip of a switch, so this will be bound to a class name on the document’s html element. Something like so:</p><pre>&lt;html class=&quot;light&quot;&gt;...&lt;/html&gt;</pre><h3>Toggle the Theme</h3><p>So, let’s get started! Firstly, let’s get the class part out of the way. There’s many of ways to do this, but for a super simple example, we can just say we’re toggling between a light mode and dark mode when clicking a button. We’ll just use a bit of JSX/jQuery throughout the article for readability. Keep in mind, this is way over-simplified and would normally account for other things as well.</p><pre>&lt;button<br>  className=&quot;myButton&quot;<br>  onClick={this.toggleThemeType}<br>&gt;<br>  Toggle Light/Dark Theme<br>&lt;/button&gt;</pre><pre>---</pre><pre>toggleThemeType = () =&gt; {<br>  $(&#39;html&#39;).toggleClass(&#39;light&#39;).toggleClass(&#39;dark&#39;);<br>}</pre><p>Cool, we have a webpage that will toggle between a dark and light theme via the html class.</p><p>This is an important note! You also should add the theme you want as the default on the html element. You could do this either directly in your index.html file, or when your app initializes. Something like so:</p><pre>$(&#39;html&#39;).addClass(&#39;light&#39;);</pre><h3>Implement the Theme Variable in SASS</h3><p>Now let’s start looking at the SASS setup. I’m not going to go over how to setup and process scss files — that’s a whole other discussion. Let’s assume we have it all working with a webpack setup, we’ve maybe got css-modules enabled (if not, see the comment in one of the mixins later on), and the styles are styling things on the webpage. In my scss file, let’s say I’ve styled .myButton from the previous example above and we want it to have different border color based on the html theme toggling we set up.</p><p>There’s a lot of ways to accomplish this. For this article, here’s what I’ve gone with:</p><pre>@import &#39;../colors&#39;;</pre><pre>.myButton {<br>  @include theme(border, borderDark, 1px solid);<br>  @include theme(background-color, backgroundLight);<br>  @include theme(color, textDark);</pre><pre>  ...other styling stuff<br>}</pre><p>A couple things here:</p><ul><li>we’re importing a colors file — more on that later, but that will contain the theme mixin and all the theme generating logic.</li><li>A “theme” mixin that accepts 2 arguments, with an optional third (and fourth) argument. You can gather that these three theme usages will add colors to the given attributes.</li></ul><p>Great! This is how simple our theming for any attribute will be to implement. We can apply this mixin to any type of property we want, we just need to remember the mixin call name and parameters: theme(attribute, themeVariable, extras)</p><p>One other thing we need is a mixin call that will actually generate all our theme variables. This is optional, but required if your users will customize their own theme variables. I put this in my root scss file for the whole application:</p><pre>@import &#39;./colors&#39;;</pre><pre>html {<br>  @include generateThemeVariables;<br>  height: 100%;<br>}</pre><p>Boom! After we have this, we literally have setup everything a front-end developer would need to know to get going to start using these theme variables.</p><h3>Setup for Generating the Themes</h3><p>Let’s get into the nitty gritty for generating the theme variables and the mixins we’re using above. Before we can do that, we need to define our themes!</p><p>There’s a lot of arguments on how to define theme-type variables. Some say to use specific naming for where they are used, some say to just do “primary/secondary/etc”, and much more. For my scheme, I chose to a) list out the raw theme colors as unique names, then b) create theme variables based on those colors.</p><p>For the raw theme colors, I have a file called colorDefinitions.scss that contains the colors, like so:</p><pre>$colors: (<br>  tronLightBlue: #a1fefe,<br>  tronDarkBlue: #004242,<br>  white: #FFFFFF,<br>  black: #000000<br>);</pre><p>I’m just generating unique names based on this site: <a href="http://chir.ag/projects/name-that-color/">http://chir.ag/projects/name-that-color/</a>, but you can do it however you’d like.</p><p>Next, we will have a theme definition file for each theme we want to use. Here’s my light.scss file:</p><pre>@import &#39;./functions&#39;;</pre><pre>$light: (<br>  borderDark:      color(tronDarkBlue),<br>  borderLight:     color(tronLightBlue),<br>  textDark:        color(black),<br>  textLight:       color(white),<br>  backgroundDark:  color(tronDarkBlue),<br>  backgroundLight: color(tronLightBlue)<br>);</pre><p>And my dark.scss file:</p><pre>@import &#39;./functions&#39;;</pre><pre>$dark: (<br>  borderDark:      color(tronLightBlue),<br>  borderLight:     color(tronDarkBlue),<br>  textDark:        color(white),<br>  textLight:       color(black),<br>  backgroundDark:  color(tronLightBlue),<br>  backgroundLight: color(tronDarkBlue)<br>);</pre><p>You’ll notice a couple things in these theme files:</p><ul><li>I’m importing a functions file. This will contain some useful functions (like “color”) that I’ll discuss more below.</li><li>The variable names in each theme are the same. This is crucial!</li><li>The colors are opposite in each theme. Since we are flipping between a dark and light theme, I wanted the two themes to be opposite each other. It doesn’t have to be this way if I added a third theme that is completely unique. After all, these just correlate to the html class name we set up at the very start.</li></ul><p>And let’s add that functions file now:</p><pre>@import &#39;./colorDefinitions&#39;;</pre><pre><em>//gets a color value from color map, defined in colorDefinitions<br></em>@function color($colorName) {<br>  @return map-get($colors, $colorName);<br>}</pre><pre><em>//helper function for checking if theme exists in theme colors<br></em>@function themeExists($key, $theme) {<br>  @if map-has-key($themeValues, $key) {<br>    @return map-has-key(map-get($themeValues, $key), $theme);<br>  }<br>  @return null;<br>}</pre><pre><em>//helper function for getting a theme color<br></em>@function getThemeValue($key, $theme) {<br>  @return map-get(map-get($themeValues, $key), $theme);<br>}</pre><p>You can see our color function we used previously is nothing more than something that gets the actual color from our $colors map, based on a provided color name. We also added a couple helper functions we’ll use later that help us check if a theme exists and for getting a theme’s color.</p><h3>Quick Recap So Far…</h3><p>Let’s look at what we have so far:</p><ul><li>themes on the html element via the class name, and we generate theme variables at the html level in the scss file</li><li>a button that will use the theme styles and the button also toggles the theme.</li><li>a color definition file with unique colors</li><li>two theme files that define variables and what colors they use.</li><li>a functions file with a couple helper functions</li></ul><p>At this point, you may be asking why this is so complicated already! If you remember our original goals, we wanted theming to be easy for general use and consistent. By adding all this extra complexity up front, we’ll find that actually using the theme variables is incredibly easy to the point where another developer only needs to know the theme mixin and the theme variable names in order to get fully going.</p><p>But we’re not quite there yet! We have all the groundwork laid out, so now we just need to generate the themes that sass will use.</p><h3>Generating the Themes</h3><p>Let’s make a mixins file now. This is by far the most complex thing, so I’ll put comments throughout the code below. You may want to copy/paste this into a text editor with scss highlighting for readability.</p><pre>@import &#39;./functions&#39;;</pre><pre>/*<br>  @mixin theme($property, $key, $inlineExtra:null, $postExtra:null)<br>  Assigns a property a theme value for each defined theme.</pre><pre>Example usage:<br>    .mySelector {<br>      padding: 6px;<br>      @include theme(background-color, backgroundLight);<br>      @include theme(border, borderDark, 1px solid);<br>    }</pre><pre>sass generated equivalent:<br>    .mySelector {<br>      padding: 6px;</pre><pre>      :global(.light) &amp; {<br>        border: 1px solid color(woodsmoke);<br>        border: 1px solid var(--theme-light-borderDark, color(woodsmoke));<br>      }<br>      :global(.light) &amp; {<br>        background-color: color(alabaster);<br>        background-color: var(--theme-light-backgroundLight, color(alabaster));<br>      }</pre><pre>      :global(.dark) &amp; {<br>        border: 1px solid color(alabaster);<br>        border: 1px solid var(--theme-dark-borderDark, color(alabaster));<br>      }<br>      :global(.dark) &amp; {<br>        background-color: color(woodsmoke);<br>        background-color: var(--theme-dark-backgroundLight, color(woodsmoke));<br>      }<br>    }</pre><pre>browser output:<br>    .mySelector {<br>      padding: 6px;<br>    }<br>    .light .mySelector {<br>      border: 1px solid #141519;<br>      border: 1px solid var(--theme-light-borderDark, #141519);<br>    }<br>    .light .mySelector {<br>      background-color: #FCFCFC;<br>      background-color: var(--theme-light-backgroundLight, #FCFCFC);<br>    }</pre><pre>    .dark .mySelector {<br>      border: 1px solid #FCFCFC;<br>      border: 1px solid var(--theme-dark-borderDark, #FCFCFC);<br>    }<br>    .dark .mySelector {<br>      background-color: #141519;<br>      background-color: var(--theme-dark-backgroundLight, #141519);<br>    }<br>*/<br>@mixin theme($property, $key, $inlineExtra:null, $postExtra:null) {<br>  @each $theme in $themes {<br>    @if (themeExists($key, $theme)) {<br>      $value: getThemeValue($key, $theme);</pre><pre>      :global(.#{$theme}) &amp; {<br>      // @at-root .#{$theme} #{&amp;} { // if you aren&#39;t using css-modules, use this instead of the :global line above<br>        #{$property}: #{$inlineExtra} #{$value} #{$postExtra}; //fallback for browsers that shouldn&#39;t exist anymore<br>        #{$property}: #{$inlineExtra} var(--theme-#{$theme}-#{$key}, #{$value}) #{$postExtra};<br>      }<br>    } @else {<br>      @error &quot;Property #{$key} doesn&#39;t exist in #{$theme}&quot;;<br>    }<br>  }<br>}</pre><pre>/*<br>  @mixin generateThemeMappings(themeName: string, themeMap: map)<br>  helper function for generating list of theme variables and adding to existing map.<br>  This will add a new theme to the themes array and the theme color list.<br>*/<br>@mixin generateThemeMappings($themeName, $newThemeMap) {<br>  //creates/adds to list of theme names<br>  $themes: append($themes, $themeName, $separator: comma) !global;</pre><pre>  @each $key, $value in $newThemeMap {<br>    //adds new themeKey if doesn&#39;t exist<br>    @if not map-has-key($themeValues, $key) {<br>      $themeValues: map-merge($themeValues, ($key: ( $themeName: $value ))) !global;<br>    }<br>    //adds to existing key map<br>    @else {<br>      $existingKeyMap: map-get($themeValues, $key);<br>      //if theme variable doesn&#39;t exist, add it<br>      @if not map-get($existingKeyMap, $themeName) {<br>        $newKeyMap: map-merge($existingKeyMap, ( $themeName: $value ));<br>        $themeValues: map-merge($themeValues, ( $key: $newKeyMap )) !global;<br>      }<br>    }<br>  }<br>}</pre><pre>/*<br>  @mixin generateThemeVariables<br>  Auto-generates the entire list of theme variables for use in var() statements.<br>  Really should only be called in the html selector at the app root.<br>*/<br>@mixin generateThemeVariables {<br>  @each $key, $val in $themeValues {<br>    @each $theme in $themes {<br>      @if (themeExists($key, $theme)) {<br>        --theme-#{$theme}-#{$key}: #{getThemeValue($key, $theme)};<br>      }<br>    }<br>  }<br>}</pre><p>Whew, that’s a lot. Instead of going over each method here, I’ll go through them as they are used. We’ve already used two of them, so let’s talk about those.</p><p>@mixin theme <br>This is the mixin that developers will use to reference the themes for individual attributes. Basically this does a lot of stuff. When a developer references this mixin, sass will compile it to be a theme level class. So if I had my example from above:</p><pre>.myButton {<br>  @include theme(border, borderDark, 1px solid);<br>  border-radius: 2px;<br>}</pre><p>Our mixin will convert this to ultimately be:</p><pre>.dark .myButton {<br>  border: 1px solid #a1fefe;<br>  border: 1px solid var(--theme-dark-borderDark, #a1fefe);<br>}<br>.light .myButton {<br>  border: 1px solid #004242;<br>  border: 1px solid var(--theme-light-borderDark, #004242);<br>}<br>.myButton {<br>  border-radius: 2px;<br>}</pre><p>Ah! We can now catch a glimpse into how those global themes will affect our button. This is pretty standard css, so I won’t go over it. However, it is important to note that we not only apply the basic border, we also have the attribute using css variables. While that isn’t necessary for the actual displaying of the themes, what this does allow is for custom user theming overrides for each theme. I’ll talk more about that later.</p><p>@mixin generateThemeVariables<br>This mixin was references in our html scss. Essentially, this will go through each of our themes and generate those css variables mentioned above. The format is ` — theme-&lt;themeName&gt;-&lt;themeVariable&gt;`. Again, if we weren’t using the css variables part, then we wouldn’t need this mixin at all. However, it is necessary if any future user customization is needed.</p><p><strong>Finishing the Generating</strong></p><p>Alright, now the grand finale…at least on the setup! Let’s make our colors.scss file we referenced earlier.</p><pre><a href="http://twitter.com/import">@import</a> &#39;./mixins&#39;;</pre><pre>/** this section generates a theme map for each theme **/<br>$themes: ();<br>$themeValues: ();</pre><pre><a href="http://twitter.com/import">@import</a> &#39;./light&#39;;<br><a href="http://twitter.com/include">@include</a> generateThemeMappings(light, $light);</pre><pre><a href="http://twitter.com/import">@import</a> &#39;./dark&#39;;<br><a href="http://twitter.com/include">@include</a> generateThemeMappings(dark, $dark);<br>/** end theme generation **/</pre><p>This file will actually generate all our theme colors. We setup an import to get each theme, then we actually generate the theme. This leads to the third mixin.</p><p>@mixin generateThemeMappings<br>This takes the name of the theme to generate and the map of variables from the theme. It essentially goes through each theme and each theme variable and zips them into one giant map. Remember how we had the same variable names for both the light and dark theme? This is why. The output of this mixin creates:</p><pre>$themes: (light, dark);<br>$themeValues: (<br>  borderDark: (light: #004242, dark: #a1fefe),<br>  ...<br>);</pre><p>The way the @mixin theme was written, it utilizes this final map to know what color should be output for each theme. We use our getThemeValue function that will get the appropriate value from this map.</p><h3>Got It!</h3><p>If everything was setup correctly, you should now have a button that switches styles based on the theme! We should never need to worry about these various theme files again because it is all standardized at this point. Let’s look at all the benefits we now have:</p><ul><li>we only need to utilize that theme mixin to get functioning theming.</li><li>You might also notice how incredibly easy it is to add a new theme. You only would need to add a new theme file, and generate the mappings in the colors.scss file.</li><li>If my company decides the rebrand their colors, I only have to change the definitions in the colorDefinitions file, instead of anywhere else.</li><li>We now have a standard list of variables and colors, so we can hand those off to UX/UI to use so they are using the same set as us.</li></ul><p>Here’s a final example of what we have now: <a href="https://codesandbox.io/s/scss-theming-bebm7">https://codesandbox.io/s/scss-theming-bebm7</a></p><h3>About Those CSS Variables</h3><p>Remember those css variables I mentioned? Up to this point, they are completely unnecessary. However, they are incredibly useful if we want users to customize their own theme colors for each theme.</p><p>Let’s say I wanted to keep the dark and light themes, but let the users customize each to match their preferences, or maybe branding for a client. Because each variable is added at the html level like so: ` — theme-dark-borderDark`, we can just save the user’s preference for custom colors, then define these same variables at a lower level than the html.</p><p>How you add those variables per user to the dom is up to you. Here’s a sample function I did at the root of my App.jsx file:</p><pre>setTheme() {<br>  /* This method should be called to initialize, update, or remove user custom theme variables.<br>     It essentially adds a new style script in the head of the page (thus lower than the html<br>     defaults), which in turn applies the new styles to all theme variables<br>  */</pre><pre>this.themeActive = this.hasTheming;<br>  // if doesn&#39;t have theming available and it was present before, remove it<br>  if(!this.hasTheming &amp;&amp; this.themeStylesEl) {<br>    this.themeStylesEl.remove();<br>  } else {<br>    this.currentTheme = this.themeVariables;<br>    let el = this.themeStylesEl ? this.themeStylesEl : document.createElement(&#39;style&#39;);<br>    if(!this.themeStylesEl) {<br>      this.themeStylesEl = el;<br>      document.head.appendChild(this.themeStylesEl);<br>    }<br>    let themeVars = [];<br>    Object.keys(this.themeVariables).map(theme =&gt; {<br>      Object.keys(this.themeVariables[theme]).map(variable =&gt; {<br>        let value = this.themeVariables[theme][variable];<br>        themeVars.push(`--theme-${theme}-${variable}: ${value};`);<br>      });<br>    });<br>    this.themeStylesEl.innerHTML = `<br>      html {<br>        ${themeVars.join(&#39;\n&#39;)}<br>      }<br>    `;<br>  }<br>}</pre><p>In that same code sandbox above, I added a text box that demonstrates this overriding concept. Here’s that same link again: <a href="https://codesandbox.io/s/scss-theming-bebm7">https://codesandbox.io/s/scss-theming-bebm7</a></p><h3>Final Thoughts</h3><p>Hopefully this tutorial gives you ideas for your own theming. There’s many ways to accomplish theming, but if you can make it robust enough, you can save a lot of refactoring headaches down the road.</p><p>This is just one solution that only focuses on colors, but you can expand to handle other theming variables as well. You can also expand your theme files to include new themes, like holiday based!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67b8c0265e3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>