Skip to content

Commit fd3e0ad

Browse files
authored
Remove unnecessary Tailwind class compilation calls (#6534)
# [Editions store](https://utopia.fish/p/2e4310b0-nostalgic-blackberry/?branch_name=fix-tailwind-fine-grained-dom-observer) ## Problem The Tailwind class generation code was running twice at the end of an interaction. Instead, we only want to re-run the tailwind compilation code when - a new element is added to the DOM or the `class` attribute of an element is updated - the Tailwind config file is updated (so tweaks to the tailwind config show up right away on the canvas) ## Fix - remove the `RequireFn` param from `useTailwindCompilation`. This param is problematic because a new `requireFn` is passed to `useTailwindCompilation` whenever `projectContents` changes, which triggers a re-compilation. Instead, the require fn is constructed in a `useRefEditorState` and used through that ref - The Tailwind config file is selected with a hook using `createSelector` for memoization - The mutation observer that runs the Tailwind class generation is only run if there were new nodes added (with potentially new Tailwind classes added to the DOM) or a `class` attribute was updated (with a potentially new Tailwind class) ### Out of scope This PR doesn't deal with the problem of generating new Tailwind classes only for the elements that have changed. This is due to how the library we use for tailwind class compilation works, finding a more fine-grained way to do this would be a more involved task ### Details - The PR also adds a test that tests tailwind style generation with Remix navigation
1 parent 06565e5 commit fd3e0ad

File tree

3 files changed

+230
-24
lines changed

3 files changed

+230
-24
lines changed

editor/src/components/canvas/ui-jsx-canvas.tsx

+1-1
Original file line numberDiff line numberDiff line change
@@ -498,7 +498,7 @@ export const UiJsxCanvas = React.memo<UiJsxCanvasPropsWithErrorCallback>((props)
498498

499499
const executionScope = scope
500500

501-
useTailwindCompilation(customRequire)
501+
useTailwindCompilation()
502502

503503
const topLevelElementsMap = useKeepReferenceEqualityIfPossible(new Map(topLevelJsxComponents))
504504

editor/src/core/tailwind/tailwind-compilation.ts

+59-23
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
import React from 'react'
22
import type { TailwindConfig, Tailwindcss } from '@mhsdesign/jit-browser-tailwindcss'
33
import { createTailwindcss } from '@mhsdesign/jit-browser-tailwindcss'
4-
import type { ProjectContentTreeRoot, TextFile, TextFileContents } from 'utopia-shared/src/types'
4+
import type { ProjectContentTreeRoot } from 'utopia-shared/src/types'
55
import { getProjectFileByFilePath, walkContentsTree } from '../../components/assets'
6-
import { interactionSessionIsActive } from '../../components/canvas/canvas-strategies/interaction-state'
76
import { CanvasContainerID } from '../../components/canvas/canvas-types'
87
import {
98
Substores,
@@ -18,6 +17,8 @@ import { ElementsToRerenderGLOBAL } from '../../components/canvas/ui-jsx-canvas'
1817
import { isFeatureEnabled } from '../../utils/feature-switches'
1918
import type { Config } from 'tailwindcss/types/config'
2019
import type { EditorState } from '../../components/editor/store/editor-state'
20+
import { createSelector } from 'reselect'
21+
import type { ProjectContentSubstate } from '../../components/editor/store/store-hook-substore-types'
2122

2223
const LatestConfig: { current: { code: string; config: Config } | null } = { current: null }
2324
export function getTailwindConfigCached(editorState: EditorState): Config | null {
@@ -87,45 +88,80 @@ function generateTailwindClasses(projectContents: ProjectContentTreeRoot, requir
8788
void generateTailwindStyles(tailwindCss, allCSSFiles)
8889
}
8990

90-
export const useTailwindCompilation = (requireFn: RequireFn) => {
91-
const projectContents = useEditorState(
92-
Substores.projectContents,
93-
(store) => store.editor.projectContents,
94-
'useTailwindCompilation projectContents',
91+
function runTailwindClassGenerationOnDOMMutation(
92+
mutations: MutationRecord[],
93+
projectContents: ProjectContentTreeRoot,
94+
isInteractionActive: boolean,
95+
requireFn: RequireFn,
96+
) {
97+
const updateHasNewTailwindData = mutations.some(
98+
(m) =>
99+
m.addedNodes.length > 0 || // new DOM element was added with potentially new classes
100+
m.attributeName === 'class', // potentially new classes were added to the class attribute of an element
101+
)
102+
if (
103+
!updateHasNewTailwindData ||
104+
isInteractionActive ||
105+
ElementsToRerenderGLOBAL.current !== 'rerender-all-elements' // implies that an interaction is in progress)
106+
) {
107+
return
108+
}
109+
generateTailwindClasses(projectContents, requireFn)
110+
}
111+
112+
const tailwindConfigSelector = createSelector(
113+
(store: ProjectContentSubstate) => store.editor.projectContents,
114+
(projectContents) => getProjectFileByFilePath(projectContents, TailwindConfigPath),
115+
)
116+
117+
export const useTailwindCompilation = () => {
118+
const requireFnRef = useRefEditorState((store) => {
119+
const requireFn = store.editor.codeResultCache.curriedRequireFn(store.editor.projectContents)
120+
return (importOrigin: string, toImport: string) => requireFn(importOrigin, toImport, false)
121+
})
122+
const projectContentsRef = useRefEditorState((store) => store.editor.projectContents)
123+
124+
const isInteractionActiveRef = useRefEditorState(
125+
(store) => store.editor.canvas.interactionSession != null,
95126
)
96127

97-
const isInteractionActiveRef = useRefEditorState((store) =>
98-
interactionSessionIsActive(store.editor.canvas.interactionSession),
128+
// this is not a ref, beacuse we want to re-compile the Tailwind classes when the tailwind config changes
129+
const tailwindConfig = useEditorState(
130+
Substores.projectContents,
131+
tailwindConfigSelector,
132+
'useTailwindCompilation tailwindConfig',
99133
)
100134

101-
const observerCallback = React.useCallback(() => {
135+
React.useEffect(() => {
136+
const canvasContainer = document.getElementById(CanvasContainerID)
102137
if (
103-
isInteractionActiveRef.current ||
104-
ElementsToRerenderGLOBAL.current !== 'rerender-all-elements' || // implies that an interaction is in progress
138+
tailwindConfig == null || // TODO: read this from the utopia key in package.json
139+
canvasContainer == null ||
105140
!isFeatureEnabled('Tailwind')
106141
) {
107142
return
108143
}
109-
generateTailwindClasses(projectContents, requireFn)
110-
}, [isInteractionActiveRef, projectContents, requireFn])
111144

112-
React.useEffect(() => {
113-
const tailwindConfigFile = getProjectFileByFilePath(projectContents, TailwindConfigPath)
114-
if (tailwindConfigFile == null || tailwindConfigFile.type !== 'TEXT_FILE') {
115-
return // we consider tailwind to be enabled if there's a tailwind config file in the project
116-
}
117-
const observer = new MutationObserver(observerCallback)
145+
const observer = new MutationObserver((mutations) => {
146+
runTailwindClassGenerationOnDOMMutation(
147+
mutations,
148+
projectContentsRef.current,
149+
isInteractionActiveRef.current,
150+
requireFnRef.current,
151+
)
152+
})
118153

119-
observer.observe(document.getElementById(CanvasContainerID)!, {
154+
observer.observe(canvasContainer, {
120155
attributes: true,
121156
childList: true,
122157
subtree: true,
123158
})
124159

125-
observerCallback()
160+
// run the initial tailwind class generation
161+
generateTailwindClasses(projectContentsRef.current, requireFnRef.current)
126162

127163
return () => {
128164
observer.disconnect()
129165
}
130-
}, [isInteractionActiveRef, observerCallback, projectContents, requireFn])
166+
}, [isInteractionActiveRef, projectContentsRef, requireFnRef, tailwindConfig])
131167
}

editor/src/core/tailwind/tailwind.spec.browser2.tsx

+170
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,13 @@
1+
import { mouseClickAtPoint } from '../../components/canvas/event-helpers.test-utils'
2+
import type { EditorRenderResult } from '../../components/canvas/ui-jsx.test-utils'
13
import { renderTestEditorWithModel } from '../../components/canvas/ui-jsx.test-utils'
4+
import { switchEditorMode } from '../../components/editor/actions/action-creators'
5+
import { EditorModes } from '../../components/editor/editor-modes'
6+
import { StoryboardFilePath } from '../../components/editor/store/editor-state'
7+
import { createModifiedProject } from '../../sample-projects/sample-project-utils.test-utils'
28
import { setFeatureForBrowserTestsUseInDescribeBlockOnly } from '../../utils/utils.test-utils'
9+
import { windowPoint } from '../shared/math-utils'
10+
import { TailwindConfigPath } from './tailwind-config'
311
import { Project } from './tailwind.test-utils'
412

513
describe('rendering tailwind projects in the editor', () => {
@@ -133,4 +141,166 @@ describe('rendering tailwind projects in the editor', () => {
133141
})
134142
}
135143
})
144+
145+
describe('Remix', () => {
146+
const projectWithMultipleRoutes = createModifiedProject({
147+
[StoryboardFilePath]: `import * as React from 'react'
148+
import { RemixScene, Storyboard } from 'utopia-api'
149+
150+
export var storyboard = (
151+
<Storyboard data-uid='storyboard'>
152+
<RemixScene
153+
className='absolute top-[100px] left-[200px] w-[700px] h-[700px]'
154+
data-label='Playground'
155+
data-uid='remix'
156+
/>
157+
</Storyboard>
158+
)
159+
`,
160+
['/app/root.js']: `import React from 'react'
161+
import { Outlet } from '@remix-run/react'
162+
163+
export default function Root() {
164+
return (
165+
<div data-testid='root' className='flex flex-col gap-10 bg-red-200 text-2xl'>
166+
I am Root!
167+
<Outlet />
168+
</div>
169+
)
170+
}
171+
`,
172+
['/app/routes/_index.js']: `import React from 'react'
173+
import { Link } from '@remix-run/react'
174+
175+
export default function Index() {
176+
return (
177+
<div data-testid='index' className='flex flex-col gap-8'>
178+
Index page
179+
<Link to='/about' data-testid='remix-link'>About</Link>
180+
</div>
181+
)
182+
}
183+
`,
184+
['/app/routes/about.js']: `import React from 'react'
185+
186+
export default function About() {
187+
return (
188+
<div data-testid='about' className='flex flex-row gap-6 p-4'>
189+
<span data-testid='about-text' className='text-shadow-md'>About page</span>
190+
</div>
191+
)
192+
}
193+
`,
194+
'/src/app.css': `
195+
@tailwind base;
196+
@tailwind components;
197+
@tailwind utilities;
198+
`,
199+
[TailwindConfigPath]: `
200+
const Tailwind = {
201+
theme: {
202+
colors: {
203+
transparent: 'transparent',
204+
current: 'currentColor',
205+
white: '#ffffff',
206+
purple: '#3f3cbb',
207+
midnight: '#121063',
208+
metal: '#565584',
209+
tahiti: '#3ab7bf',
210+
silver: '#ecebff',
211+
'bubble-gum': '#ff77e9',
212+
bermuda: '#78dcca',
213+
},
214+
},
215+
plugins: [
216+
function ({ addUtilities }) {
217+
const newUtilities = {
218+
'.text-shadow': {
219+
textShadow: '2px 2px 4px rgba(0, 0, 0, 0.1)',
220+
},
221+
'.text-shadow-md': {
222+
textShadow: '3px 3px 6px rgba(0, 0, 0, 0.2)',
223+
},
224+
'.text-shadow-lg': {
225+
textShadow: '4px 4px 8px rgba(0, 0, 0, 0.3)',
226+
},
227+
'.text-shadow-none': {
228+
textShadow: 'none',
229+
},
230+
}
231+
232+
addUtilities(newUtilities, ['responsive', 'hover'])
233+
},
234+
],
235+
}
236+
export default Tailwind`,
237+
})
238+
239+
it('can render content in a RemixScene', async () => {
240+
const editor = await renderTestEditorWithModel(
241+
projectWithMultipleRoutes,
242+
'await-first-dom-report',
243+
)
244+
{
245+
const root = editor.renderedDOM.getByTestId('root')
246+
const { backgroundColor, display, flexDirection, gap, fontSize } = getComputedStyle(root)
247+
expect({ backgroundColor, display, flexDirection, gap, fontSize }).toEqual({
248+
backgroundColor: 'rgba(0, 0, 0, 0)',
249+
display: 'flex',
250+
flexDirection: 'column',
251+
fontSize: '24px',
252+
gap: '40px',
253+
})
254+
}
255+
{
256+
const index = editor.renderedDOM.getByTestId('index')
257+
const { display, flexDirection, gap } = getComputedStyle(index)
258+
expect({ display, flexDirection, gap }).toEqual({
259+
display: 'flex',
260+
flexDirection: 'column',
261+
gap: '32px',
262+
})
263+
}
264+
})
265+
it('can render content after navigating to a different page', async () => {
266+
const editor = await renderTestEditorWithModel(
267+
projectWithMultipleRoutes,
268+
'await-first-dom-report',
269+
)
270+
await switchToLiveMode(editor)
271+
await clickRemixLink(editor)
272+
273+
{
274+
const about = editor.renderedDOM.getByTestId('about')
275+
const { display, flexDirection, gap, padding } = getComputedStyle(about)
276+
expect({ display, flexDirection, gap, padding }).toEqual({
277+
display: 'flex',
278+
flexDirection: 'row',
279+
gap: '24px',
280+
padding: '16px',
281+
})
282+
}
283+
{
284+
const aboutText = editor.renderedDOM.getByTestId('about-text')
285+
const { textShadow } = getComputedStyle(aboutText)
286+
expect(textShadow).toEqual('rgba(0, 0, 0, 0.2) 3px 3px 6px')
287+
}
288+
})
289+
})
136290
})
291+
292+
const switchToLiveMode = (editor: EditorRenderResult) =>
293+
editor.dispatch([switchEditorMode(EditorModes.liveMode())], true)
294+
295+
async function clickLinkWithTestId(editor: EditorRenderResult, testId: string) {
296+
const targetElement = editor.renderedDOM.queryAllByTestId(testId)[0]
297+
const targetElementBounds = targetElement.getBoundingClientRect()
298+
299+
const clickPoint = windowPoint({ x: targetElementBounds.x + 5, y: targetElementBounds.y + 5 })
300+
await mouseClickAtPoint(targetElement, clickPoint)
301+
}
302+
303+
async function clickRemixLink(editor: EditorRenderResult) {
304+
await clickLinkWithTestId(editor, 'remix-link')
305+
await editor.getDispatchFollowUpActionsFinished()
306+
}

0 commit comments

Comments
 (0)