Skip to content

Commit

Permalink
handle new themes that match the previous one
Browse files Browse the repository at this point in the history
  • Loading branch information
stipsan committed Nov 21, 2024
1 parent a9dc228 commit 9e5dc37
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 22 deletions.
11 changes: 10 additions & 1 deletion api/api/random-color-theme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import {createClient} from '@sanity/client'
import {lch} from 'd3-color'
import {defineQuery} from 'groq'

export const config = {runtime: 'edge'}

Expand Down Expand Up @@ -68,8 +69,16 @@ export default async function handler(request: Request) {
useCdn: false,
token: process.env.SANITY_API_WRITE_TOKEN,
})
const THEME_QUERY = defineQuery(`*[_id == "theme"][0]{background,text}`)
const prevTheme = await client.fetch(THEME_QUERY, {}, {perspective: 'published'})
const _id = 'theme'
const patch = client.patch(_id).set(generateThemeColors())
const nextTheme = generateThemeColors()
const patch = client.patch(_id).set(
// If the new theme is the same as the previous theme, swap the background and text colors
prevTheme?.background === nextTheme.background && prevTheme?.text === nextTheme.text
? {background: nextTheme.text, text: nextTheme.background}
: nextTheme,
)
client.transaction().createIfNotExists({_id, _type: _id}).patch(patch).commit()

return new Response(JSON.stringify({patch}), {status: 200, headers})
Expand Down
6 changes: 5 additions & 1 deletion api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@
"name": "api",
"version": "0.0.0",
"private": true,
"scripts": {
"typegen:generate": "sanity typegen generate"
},
"dependencies": {
"@sanity/client": "^6.22.5",
"d3-color": "^3.1.0"
"d3-color": "^3.1.0",
"groq": "^3.64.2"
},
"devDependencies": {
"@edge-runtime/types": "^3.0.3",
Expand Down
3 changes: 3 additions & 0 deletions api/sanity-typegen.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"schema": "../studio/schema.json"
}
47 changes: 27 additions & 20 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 9e5dc37

Please sign in to comment.