Skip to content

Add cache for tailwind-variants #13018

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion MODULE.bazel.lock

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

Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as aria from '#/components/aria'
import * as ariaComponents from '#/components/AriaComponents'
import Portal from '#/components/Portal'
import * as eventCallback from '#/hooks/eventCallbackHooks'
import { unsafeWriteValue } from '#/utilities/write'
import * as React from 'react'

/** Props for {@link useVisualTooltip}. */
Expand Down Expand Up @@ -101,8 +102,13 @@ export function useVisualTooltip(props: VisualTooltipOptions): VisualTooltipRetu
onHoverChange: handleHoverChange,
})

unsafeWriteValue(targetHoverProps, 'id', id)

return {
targetProps: aria.mergeProps<React.HTMLAttributes<HTMLElement>>()(targetHoverProps, { id }),
// This is SAFE because we are writing the value to the targetHoverProps object
// above.
// eslint-disable-next-line no-restricted-syntax
targetProps: targetHoverProps as VisualTooltipReturn['targetProps'],
tooltip:
state.isOpen ?
<TooltipInner
Expand All @@ -122,7 +128,7 @@ export function useVisualTooltip(props: VisualTooltipOptions): VisualTooltipRetu
handleHoverChange={handleHoverChange}
/>
: null,
} as const
}
}

/** Props for {@link TooltipInner}. */
Expand Down
2 changes: 1 addition & 1 deletion app/gui/src/dashboard/components/dashboard/AssetRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@ export function RealAssetRow(props: RealAssetRowProps) {
}
}}
className={tailwindMerge.twMerge(
'h-table-row rounded-full transition-all ease-in-out rounded-rows-child [contain-intrinsic-size:44px] [content-visibility:auto]',
'h-table-row rounded-full transition-all ease-in-out rounded-rows-child',
visibility,
(isDraggedOver || isSelected) && 'selected',
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export default function SharedWithColumn(props: SharedWithColumnPropsInternal) {
const assetPermissions = item.permissions ?? []

return (
<div className="group flex items-center gap-column-items [content-visibility:auto]">
<div className="group flex items-center gap-column-items">
{(category.type === 'trash' ?
assetPermissions.filter((permission) => permission.permission === PermissionAction.own)
: assetPermissions
Expand Down
69 changes: 69 additions & 0 deletions app/gui/src/dashboard/utilities/LruCache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/** @file A simple LRU cache. */
/**
* A simple LRU cache.
*
* Implementation based on https://github.com/dominictarr/hashlru#algorithm
*/
export class LRUCache<K, V> {
private oldCache: Map<K, V>
private cache: Map<K, V>

/**
* Create a new LRU cache.
*/
constructor(private readonly maxSize: number) {
this.cache = new Map()
this.oldCache = new Map()
}

/**
* Get a value from the cache.
*/
get(key: K): V | undefined {
const newCacheValue = this.cache.get(key)

if (newCacheValue != null) {
return newCacheValue
}

const oldCacheValue = this.oldCache.get(key)

if (oldCacheValue != null) {
this.cache.set(key, oldCacheValue)
this.evictIfNecessary()
}

return oldCacheValue
}

/**
* Set a value in the cache.
*/
set(key: K, value: V) {
const isValueInNewCache = this.cache.has(key)

this.cache.set(key, value)

if (isValueInNewCache) {
this.evictIfNecessary()
}
}

/**
* Clear the cache.
*/
clear() {
this.cache.clear()
this.oldCache.clear()
}

/**
* Evict the oldest value from the cache.
*/
private evictIfNecessary() {
if (this.cache.size > this.maxSize) {
this.oldCache = this.cache
this.cache = new Map()
}
}
}
75 changes: 74 additions & 1 deletion app/gui/src/dashboard/utilities/tailwindVariants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,85 @@ import type { OmitUndefined } from 'tailwind-variants'
import { createTV } from 'tailwind-variants'

import { TAILWIND_MERGE_CONFIG } from '#/utilities/tailwindMerge'
import { LRUCache } from './LruCache'

export * from 'tailwind-variants'

const MAX_CACHE_SIZE = 256

// eslint-disable-next-line no-restricted-syntax
const tvConstructor = createTV({ twMergeConfig: TAILWIND_MERGE_CONFIG })

// This is a function, even though it does not contain function syntax.
// eslint-disable-next-line no-restricted-syntax
export const tv = createTV({ twMergeConfig: TAILWIND_MERGE_CONFIG })
export const tv: typeof tvConstructor = function tvWithLRU(
construct: Parameters<typeof tvConstructor>[0],
) {
const cache = new LRUCache<string, unknown>(MAX_CACHE_SIZE)
/**
* Get a cache key for a given set of arguments.
*/
function getCacheKey(props: Parameters<typeof baseVariants>[0]) {
return JSON.stringify(props)
}

const baseVariants = tvConstructor(construct)

/**
* Variants constructor with LRU cache.
*/
function variantsWithLRU(args: Parameters<typeof baseVariants>[0]) {
const cacheKey = getCacheKey(args)
const cached = cache.get(cacheKey)

if (cached != null) {
return cached
}

const result: unknown = baseVariants(args)

if (typeof result === 'object' && result != null) {
for (const slot in result) {
// eslint-disable-next-line no-restricted-syntax
const value = result[slot as keyof typeof result]

if (typeof value === 'function') {
const slotCachePrefix = slot + cacheKey
/**
* Wrap a slot function with a cache.
*/
// @ts-expect-error - This is a valid assignment.
result[slot] = function withSlotCache(props: Parameters<typeof value>[0]) {
const slotCacheKey = slotCachePrefix + getCacheKey(props)
const slotCache = cache.get(slotCacheKey)

if (slotCache != null) {
return slotCache
}

// @ts-expect-error - This is a valid assignment.
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const classes = value(props)

cache.set(slotCacheKey, classes)

// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return classes
}
}
}
}

cache.set(cacheKey, result)
return result
}
// Extend the prototype of the `variantsWithLRU` function with the `baseVariants` function.
// This is done to preserve the extra properties of the `baseVariants` function.
variantsWithLRU.__proto__ = baseVariants

// eslint-disable-next-line no-restricted-syntax
return variantsWithLRU as unknown as typeof tvConstructor
} as unknown as typeof tvConstructor

/** Extract function signatures from a type. */
export type ExtractFunction<T> =
Expand Down
Loading