Skip to content

Commit

Permalink
Invalidate context when CSS changes
Browse files Browse the repository at this point in the history
  • Loading branch information
thecrypticace committed Feb 25, 2022
1 parent 910b655 commit 3cfb703
Show file tree
Hide file tree
Showing 4 changed files with 85 additions and 1 deletion.
36 changes: 36 additions & 0 deletions src/lib/cacheInvalidation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import crypto from 'crypto'
import * as sharedState from './sharedState'

/**
*
* @param {string} str
*/
function getHash(str) {
try {
return crypto.createHash('md5').update(str, 'utf-8').digest('binary')
} catch (err) {
return ''
}
}

/**
* @param {string} sourcePath
* @param {import('postcss').Node} root
*/
export function hasContentChanged(sourcePath, root) {
let css = root.toString()

// We only care about files with @tailwind directives
// Other files use an existing context
if (!css.includes('@tailwind')) {
return false
}

let existingHash = sharedState.sourceHashMap.get(sourcePath)
let rootHash = getHash(css)
let didChange = existingHash !== rootHash

sharedState.sourceHashMap.set(sourcePath, rootHash)

return didChange
}
7 changes: 6 additions & 1 deletion src/lib/setupContextUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import log from '../util/log'
import negateValue from '../util/negateValue'
import isValidArbitraryValue from '../util/isValidArbitraryValue'
import { generateRules } from './generateRules'
import { hasContentChanged } from './cacheInvalidation.js'

function prefix(context, selector) {
let prefix = context.tailwindConfig.prefix
Expand Down Expand Up @@ -790,6 +791,8 @@ export function createContext(tailwindConfig, changedContent = [], root = postcs
let resolvedPlugins = resolvePlugins(context, root)
registerPlugins(resolvedPlugins, context)

sharedState.contextInvalidationCount++

return context
}

Expand Down Expand Up @@ -822,14 +825,16 @@ export function getContext(
existingContext = context
}

let cssDidChange = hasContentChanged(sourcePath, root)

// If there's already a context in the cache and we don't need to
// reset the context, return the cached context.
if (existingContext) {
let contextDependenciesChanged = trackModified(
[...contextDependencies],
getFileModifiedMap(existingContext)
)
if (!contextDependenciesChanged) {
if (!contextDependenciesChanged && !cssDidChange) {
return [existingContext, false]
}
}
Expand Down
7 changes: 7 additions & 0 deletions src/lib/sharedState.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ export const env = {
export const contextMap = new Map()
export const configContextMap = new Map()
export const contextSourcesMap = new Map()
/**
* A map of source files to their sizes / hashes
*
* @type {Map<string, string>}
*/
export const sourceHashMap = new Map()
export const contextInvalidationCount = 0
export const NOT_ON_DEMAND = new String('*')

export function resolveDebug(debug) {
Expand Down
36 changes: 36 additions & 0 deletions tests/context-reuse.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,39 @@ it('re-uses the context across multiple files with the same config', async () =>
// And none of this should have resulted in multiple contexts being created
expect(sharedState.contextSourcesMap.size).toBe(1)
})

it('passing in different css invalidates the context if it contains @tailwind directives', async () => {
sharedState.contextInvalidationCount = 0

let from = path.resolve(__filename)

// Save the file a handful of times with no changes
// This builds the context at most once
for (let n = 0; n < 5; n++) {
await run(`@tailwind utilities;`, configPath, `${from}?id=1`)
}

expect(sharedState.contextInvalidationCount).toBe(1)

// Save the file twice with a change
// This should rebuild the context again but only once
await run(`@tailwind utilities; .foo {}`, configPath, `${from}?id=1`)
await run(`@tailwind utilities; .foo {}`, configPath, `${from}?id=1`)

expect(sharedState.contextInvalidationCount).toBe(2)

// Save the file twice with a content but not length change
// This should rebuild the context two more times
await run(`@tailwind utilities; .bar {}`, configPath, `${from}?id=1`)
await run(`@tailwind utilities; .baz {}`, configPath, `${from}?id=1`)

expect(sharedState.contextInvalidationCount).toBe(4)

// Save a file with a change that does not affect the context
// No invalidation should occur
await run(`.foo { @apply mb-1; }`, configPath, `${from}?id=2`)
await run(`.foo { @apply mb-1; }`, configPath, `${from}?id=2`)
await run(`.foo { @apply mb-1; }`, configPath, `${from}?id=2`)

expect(sharedState.contextInvalidationCount).toBe(4)
})

0 comments on commit 3cfb703

Please sign in to comment.