Skip to content

Commit

Permalink
Add function to convert string to colors to better distinguish the tags
Browse files Browse the repository at this point in the history
  • Loading branch information
sroertgen committed Nov 8, 2023
1 parent 9b92615 commit d57e3f7
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 3 deletions.
13 changes: 13 additions & 0 deletions src/common.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@

export function stringToColor(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
let color = '#';
for (let i = 0; i < 3; i++) {
let value = (hash >> (i * 8)) & 0xFF;
color += ('00' + value.toString(16)).substr(-2);
}
return color;
}
3 changes: 2 additions & 1 deletion src/pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Link, graphql } from "gatsby"
import Bio from "../components/bio"
import Layout from "../components/layout"
import SEO from "../components/seo"
import { stringToColor } from "../common"

const BlogIndex = ({ data, location }) => {
const siteTitle = data.site.siteMetadata?.title || `Title`
Expand Down Expand Up @@ -67,7 +68,7 @@ const BlogIndex = ({ data, location }) => {
{` | `}
{post.frontmatter.tags.map((tag, index) => {
return (
<small className="chip" key={"tag" + index}>
<small style={{ backgroundColor: stringToColor(tag) }} className="chip" key={"tag" + index}>
{tag}
</small>
)
Expand Down
1 change: 0 additions & 1 deletion src/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,6 @@ a:focus {
height: 1.5rem;
line-height: 1.5rem;
border-radius: 25px;
background-color: #fff017;
}

.gatsby-highlight {
Expand Down
3 changes: 2 additions & 1 deletion src/templates/blog-post.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Link, graphql } from "gatsby"
import Bio from "../components/bio"
import Layout from "../components/layout"
import SEO from "../components/seo"
import { stringToColor } from "../common"

const BlogPostTemplate = ({ data, location }) => {
const post = data.markdownRemark
Expand Down Expand Up @@ -47,7 +48,7 @@ const BlogPostTemplate = ({ data, location }) => {
{` | `}
{post.frontmatter.tags.map((tag, index) => {
return (
<span className="chip" key={"tag" + index}>
<span style={{ backgroundColor: stringToColor(tag) }} className="chip" key={"tag" + index}>
{tag}
</span>
)
Expand Down

0 comments on commit d57e3f7

Please sign in to comment.