-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Fix CustomCode scriptsClientOnly not re-running scripts after hydration #4848
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
Open
Manish-Builder-io
wants to merge
6
commits into
main
Choose a base branch
from
ai_main_11d532f23f2448839fcf
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+185
−6
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
b3be005
fix[react]: restore Custom Code scripts after hydration
builderio-bot 8b5a961
Merge remote-tracking branch 'refs/remotes/origin/main' into ai_main_…
builderio-bot 274496e
Move CustomCode tests and simplify hydration rendering
builderio-bot 967f200
Merge branch 'main' into ai_main_11d532f23f2448839fcf
sanyamkamat 13f418b
chore: update version to 9.4.7-0 in package.json
sanyamkamat 80f6050
fix[react][custom-code]: restore scripts after async hydration
builderio-bot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| '@builder.io/react': patch | ||
| --- | ||
|
|
||
| Fix: Custom Code blocks with `scriptsClientOnly` now re-insert and run their `<script>` tags after hydration. Two things blocked it: the first client render only matched the script-stripped server render when the SSR'd node happened to be captured at module-evaluation time (not guaranteed with async chunk loading, e.g. Next.js), and `shouldComponentUpdate` only compared `props.code`, suppressing the one-time re-render scheduled by `componentDidMount`. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,157 @@ | ||
| /** | ||
| * @jest-environment jsdom | ||
| */ | ||
|
|
||
| import * as React from 'react'; | ||
| import { renderToString } from 'react-dom/server'; | ||
| import { act, render } from '@testing-library/react'; | ||
| import type { BuilderElement } from '@builder.io/sdk'; | ||
| import type { CustomCode as CustomCodeComponent } from './CustomCode'; | ||
|
|
||
| declare global { | ||
| interface Window { | ||
| __ccRuns?: number; | ||
| } | ||
| } | ||
|
|
||
| // jsdom does not implement innerText, which is what CustomCode reads to eval inline scripts. | ||
| if (!Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'innerText')) { | ||
| Object.defineProperty(HTMLElement.prototype, 'innerText', { | ||
| configurable: true, | ||
| get(this: HTMLElement) { | ||
| return this.textContent; | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| const BLOCK_ID = 'builder-custom-code-hydration'; | ||
| const REMOTE_SCRIPT_SRC = 'https://example.com/custom-code.js'; | ||
|
|
||
| const builderBlock: BuilderElement = { | ||
| '@type': '@builder.io/sdk:Element', | ||
| id: BLOCK_ID, | ||
| }; | ||
|
|
||
| const CODE = [ | ||
| '<div class="cc-body">hello</div>', | ||
| '<script>window.__ccRuns = (window.__ccRuns || 0) + 1;</script>', | ||
| `<script src="${REMOTE_SCRIPT_SRC}"></script>`, | ||
| ].join(''); | ||
|
|
||
| /** | ||
| * CustomCode collects the SSR'd nodes at module scope, so it has to be loaded after the markup | ||
| * it is meant to hydrate is already in the document. | ||
| */ | ||
| function loadCustomCode() { | ||
| jest.resetModules(); | ||
| const sdk = require('@builder.io/sdk') as typeof import('@builder.io/sdk'); | ||
| const blockModule = require('./CustomCode') as { | ||
| CustomCode: typeof CustomCodeComponent; | ||
| }; | ||
| return { Builder: sdk.Builder, CustomCode: blockModule.CustomCode }; | ||
| } | ||
|
|
||
| function customCodeTree(CustomCode: typeof CustomCodeComponent) { | ||
| return ( | ||
| <div builder-id={BLOCK_ID} className={BLOCK_ID}> | ||
| <CustomCode code={CODE} scriptsClientOnly builderBlock={builderBlock} /> | ||
| </div> | ||
| ); | ||
| } | ||
|
|
||
| function renderSsrMarkup() { | ||
| const { Builder, CustomCode } = loadCustomCode(); | ||
| Builder.isServer = true; | ||
| try { | ||
| return { markup: renderToString(customCodeTree(CustomCode)), CustomCode }; | ||
| } finally { | ||
| Builder.isServer = false; | ||
| } | ||
| } | ||
|
|
||
| function mountSsrMarkup(markup: string): HTMLElement { | ||
| const container = document.createElement('div'); | ||
| container.innerHTML = markup; | ||
| document.body.appendChild(container); | ||
| return container; | ||
| } | ||
|
|
||
| async function flushNextTick() { | ||
| await act(async () => { | ||
| await new Promise(resolve => setTimeout(resolve, 0)); | ||
| }); | ||
| } | ||
|
|
||
| describe('CustomCode scriptsClientOnly hydration', () => { | ||
| beforeEach(() => { | ||
| delete window.__ccRuns; | ||
| document.body.innerHTML = ''; | ||
| document.head.querySelectorAll(`script[src="${REMOTE_SCRIPT_SRC}"]`).forEach(el => el.remove()); | ||
| }); | ||
|
|
||
| it('strips scripts from the server render', () => { | ||
| const { markup } = renderSsrMarkup(); | ||
| expect(markup).toContain('cc-body'); | ||
| expect(markup).not.toContain('__ccRuns'); | ||
| expect(markup).not.toContain(REMOTE_SCRIPT_SRC); | ||
| }); | ||
|
|
||
| it('restores and runs the stripped scripts after hydration', async () => { | ||
| const { markup } = renderSsrMarkup(); | ||
| const container = mountSsrMarkup(markup); | ||
|
|
||
| const { CustomCode } = loadCustomCode(); | ||
| render(customCodeTree(CustomCode), { container, hydrate: true }); | ||
| await flushNextTick(); | ||
|
|
||
| const customCodeEl = container.querySelector('.builder-custom-code'); | ||
| expect(customCodeEl).toBeTruthy(); | ||
|
|
||
| // The re-render triggered by `hydrated` must put the stripped <script> tags back in the DOM. | ||
| expect(customCodeEl!.querySelector('script')).toBeTruthy(); | ||
| // ...and findAndRunScripts must then pick them up. | ||
| expect(window.__ccRuns).toBe(1); | ||
| expect(document.head.querySelector(`script[src="${REMOTE_SCRIPT_SRC}"]`)).toBeTruthy(); | ||
| }); | ||
|
|
||
| // Bundlers load the SDK chunk asynchronously, so the module-scope `.builder-custom-code` scan | ||
| // can run before the SSR'd markup is in the document. `originalRef` then stays null and the | ||
| // block must still recover, which is the reported Next.js App Router failure. | ||
| it('restores and runs the scripts when the module loads before the SSR markup exists', async () => { | ||
| const { markup, CustomCode } = renderSsrMarkup(); | ||
| const container = mountSsrMarkup(markup); | ||
|
|
||
| render(customCodeTree(CustomCode), { container, hydrate: true }); | ||
| await flushNextTick(); | ||
|
|
||
| const customCodeEl = container.querySelector('.builder-custom-code'); | ||
| expect(customCodeEl!.querySelector('script')).toBeTruthy(); | ||
| expect(window.__ccRuns).toBe(1); | ||
| expect(document.head.querySelector(`script[src="${REMOTE_SCRIPT_SRC}"]`)).toBeTruthy(); | ||
| }); | ||
|
|
||
| it('still skips re-renders when neither code nor hydration state change', async () => { | ||
| const { CustomCode } = loadCustomCode(); | ||
| const renderSpy = jest.spyOn(CustomCode.prototype, 'render'); | ||
|
|
||
| function Parent({ label }: { label: string }) { | ||
| return ( | ||
| <div> | ||
| <span>{label}</span> | ||
| <CustomCode code={CODE} scriptsClientOnly builderBlock={builderBlock} /> | ||
| </div> | ||
| ); | ||
| } | ||
|
|
||
| const { rerender } = render(<Parent label="a" />); | ||
| await flushNextTick(); | ||
|
|
||
| const rendersAfterMount = renderSpy.mock.calls.length; | ||
|
|
||
| rerender(<Parent label="b" />); | ||
| await flushNextTick(); | ||
|
|
||
| expect(renderSpy.mock.calls.length).toBe(rendersAfterMount); | ||
| renderSpy.mockRestore(); | ||
| }); | ||
| }); |
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. why was this needed? |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Will do a dev release first
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@sanyamkamat can we do the dev release?