Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
init

broken

fix

working

add remix

add selector parametrization

cleanup for publishing

k

setup changesets

f

f

docs

f

fdsa

rm

k
  • Loading branch information
samijaber committed Dec 13, 2023
0 parents commit 9545fce
Show file tree
Hide file tree
Showing 48 changed files with 10,158 additions and 0 deletions.
8 changes: 8 additions & 0 deletions .changeset/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Changesets

Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
with multi-package repos, or single-package repos to help you version and publish your code. You can
find the full documentation for it [in our repository](https://github.com/changesets/changesets)

We have a quick list of common questions to get you started engaging with this project in
[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md)
11 changes: 11 additions & 0 deletions .changeset/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"$schema": "https://unpkg.com/@changesets/[email protected]/schema.json",
"changelog": "@changesets/cli/changelog",
"commit": false,
"fixed": [],
"linked": [],
"access": "restricted",
"baseBranch": "main",
"updateInternalDependencies": "patch",
"ignore": ["@test/*"]
}
8 changes: 8 additions & 0 deletions .changeset/tough-schools-sit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@builder.io/react-hydration-overlay": patch
---

Initial Release:

- added `HydrationOverlay` component.
- added Next.js plugin at `@builder.io/react-hydration-overlay/next`
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
v20.10.0
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Builder.io

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
76 changes: 76 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Hydration Overlay 🕵️

This package displays an overlay during Hydration Errors, providing an explicit diff between the server-side and client-side renders.

![after](./imgs/after.png)

## Installation

```bash
npm install @builder.io/react-hydration-overlay
```

## Usage

### `HydrationOverlay`

First, wrap the root of your app in the `HydrationOverlay` component.

```tsx
import { HydrationOverlay } from "@builder.io/react-hydration-overlay";

const App = () => {
return (
<HydrationOverlay>
<YourApp />
</HydrationOverlay>
);
};
```

### Plugin

Second, add the plugin for your framework. Currently, we only support Next.js.

#### Next.js

in `next.config.js`:

```js
const {
withHydrationOverlay,
} = require("@builder.io/react-hydration-overlay/next");

/** @type {import('next').NextConfig} */
const nextConfig = {
/** your config here */
};

module.exports = withHydrationOverlay()(nextConfig);
```

## Notes

- This package is currently in beta. Please report any issues you find!
- This package is not intended for production use. We highly recommend you remove this package from your production builds.

## Caveats

This package works by comparing the HTML received from the server with the HTML rendered by the client, which has one improtant consequence. React re-renders the entire app when hydration fails, potentially introducing even more changes.

The biggest example is `style` attributes: React appends `;` to each one and alters the whitespace. In [more extreme examples](https://x.com/samijaber_/status/1734760349662957906?s=20), it causes enormous diffs for properties like `all: unset`.

Therefore, this tool will give you false positives for style changes.

## How It Works

- The plugin injects `hydration-overlay-initializer.js` into your app's entry point. This script reads the HTML from the server and stores it, and then listens for hydration errors and stores the resulting HTML then.
- The `HydrationOverlay` component reads both HTML strings and compares them, and renders the overlay.

## Support

To add support for other frameworks, what is needed is a plugin that injects the `hydration-overlay-initializer.js` script into the app's entry point. See [next-plugin.ts](./packages/lib/src/next-plugin.ts) for more information. PRs welcome!

- [x] Next.js
- [ ] Remix
- [ ] Vite SSR
Binary file added imgs/after.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added imgs/before.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
10 changes: 10 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"dependencies": {
"@changesets/cli": "^2.27.1"
},
"scripts": {
"change": "changeset",
"release": "changeset version",
"publish": "pnpm --filter \"@builder.io/react-hydration-overlay\" build && changeset publish"
}
}
1 change: 1 addition & 0 deletions packages/lib/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
dist
12 changes: 12 additions & 0 deletions packages/lib/module-augmentations.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export {};

declare global {
interface Window {
BUILDER_HYDRATION_OVERLAY: {
SSR_HTML: string | undefined;
CSR_HTML: string | undefined;
ERROR: boolean | undefined;
APP_ROOT_SELECTOR: string;
};
}
}
52 changes: 52 additions & 0 deletions packages/lib/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
{
"name": "@builder.io/react-hydration-overlay",
"description": "React utility for descriptive hydration mismatch errors.",
"version": "0.0.0",
"files": [
"dist"
],
"main": "./dist/HydrationOverlay.js",
"module": "./dist/HydrationOverlay.mjs",
"exports": {
".": {
"import": "./dist/HydrationOverlay.mjs",
"require": "./dist/HydrationOverlay.js"
},
"./next": {
"import": "./dist/next-plugin.mjs",
"require": "./dist/next-plugin.js"
}
},
"scripts": {
"tsc": "tsc",
"build": "tsup ./src/* --dts --format esm,cjs --external webpack --clean",
"pkg:attw": "attw --pack .",
"pkg:publint": "publint --strict",
"lint-pkg": "pnpm pkg:publint && pnpm pkg:attw"
},
"peerDependencies": {
"react": ">=16",
"react-dom": ">=16"
},
"devDependencies": {
"@arethetypeswrong/cli": "^0.13.3",
"@types/beautify": "^0.0.3",
"@types/diff": "^5.0.9",
"@types/node": "^20",
"@types/pretty": "^2.0.3",
"@types/react": "^18.2.43",
"@vitejs/plugin-react": "^4.0.4",
"next": "14.0.4",
"publint": "^0.2.6",
"react": "^18.2.0",
"rimraf": "^3.0.2",
"tsup": "^8.0.1",
"typescript": "^5.3.3",
"vite": "^4.4.9",
"webpack": "^5.89.0"
},
"dependencies": {
"beautify": "^0.0.8",
"react-diff-viewer": "^3.1.1"
}
}
11 changes: 11 additions & 0 deletions packages/lib/src/HydrationOverlay.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import React, { type PropsWithChildren } from "react";
import { Overlay } from "./Overlay";

export function HydrationOverlay(props: PropsWithChildren) {
return (
<>
{props.children}
<Overlay />
</>
);
}
122 changes: 122 additions & 0 deletions packages/lib/src/Overlay.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
"use client";
import beautify from "beautify";
import { createPortal } from "react-dom";
import React, { useEffect, useState } from "react";
import ReactDiffViewer, { DiffMethod } from "react-diff-viewer";

const DiffViewer: typeof ReactDiffViewer = (ReactDiffViewer as any).default
? (ReactDiffViewer as any).default
: ReactDiffViewer;

export function Overlay() {
const [SSRHtml, setSSRHtml] = useState("");
const [CSRHtml, setCSRHtml] = useState("");

const [showModal, setShowModal] = useState(true);
const [hasHydrationMismatch, setHasHydrationMismatch] = useState(true);

useEffect(() => {
const ssrHtml = window.BUILDER_HYDRATION_OVERLAY.SSR_HTML;
const newCSRHtml = window.BUILDER_HYDRATION_OVERLAY.CSR_HTML;

if (!ssrHtml || !newCSRHtml) return;

const newSSR = beautify(ssrHtml, { format: "html" });
setSSRHtml(newSSR);
const newCSR = beautify(newCSRHtml, { format: "html" });
setCSRHtml(newCSR);

setShowModal(true);
if (window.BUILDER_HYDRATION_OVERLAY.ERROR) {
setHasHydrationMismatch(true);
}
}, []);

const hideModal = () => {
setShowModal(false);
};

if (!showModal || !hasHydrationMismatch || typeof document === "undefined") {
return null;
}

return createPortal(
<div
style={{
position: "absolute",
top: 0,
left: 0,
right: 0,
bottom: 0,
zIndex: 999998,
background: "rgba(0,0,0,0.5)",
cursor: "pointer",
display: "flex",
flexDirection: "column",
fontFamily: "monospace",
}}
onClick={hideModal}
>
<div
style={{
zIndex: 999999,
margin: "4rem 6rem",
backgroundColor: "white",
borderRadius: "0.5rem",
overflow: "auto",
cursor: "auto",
color: "#212529",
}}
onClick={(e) => {
e.stopPropagation();
}}
>
<div style={{ display: "flex", flexDirection: "column" }}>
<div
style={{
display: "flex",
justifyContent: "space-between",
borderBottom: "1px solid black",
alignItems: "center",
}}
>
<div
style={{
fontSize: "2rem",
fontWeight: "bold",
padding: "1rem",
}}
>
Hydration Mismatch Occured
</div>

<button
style={{
all: "unset",
cursor: "pointer",
padding: "0.5rem",
marginRight: "1rem",
backgroundColor: "#212529",
borderRadius: "0.25rem",
color: "white",
}}
onClick={hideModal}
>
CLOSE
</button>
</div>
<div style={{ position: "relative", width: "100%" }}>
<DiffViewer
oldValue={SSRHtml}
newValue={CSRHtml}
leftTitle={"Server-Side Render"}
rightTitle={"Client-Side Render"}
compareMethod={DiffMethod.WORDS}
/>
</div>
</div>
</div>
</div>,
document.body
);
}
25 changes: 25 additions & 0 deletions packages/lib/src/hydration-overlay-initializer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
window.BUILDER_HYDRATION_OVERLAY = {};

window.addEventListener("error", (event) => {
const msg = event.message.toLowerCase();
const isReactDomError = event.filename.includes("react-dom");
const isHydrationMsg = msg.includes("hydration") || msg.includes("hydrating");

if (isReactDomError && isHydrationMsg) {
window.BUILDER_HYDRATION_OVERLAY.ERROR = true;
let appRootEl = document.querySelector(
window.BUILDER_HYDRATION_OVERLAY.APP_ROOT_SELECTOR
);
if (appRootEl) {
window.BUILDER_HYDRATION_OVERLAY.CSR_HTML = appRootEl.innerHTML;
}
}
});

let BUILDER_HYDRATION_OVERLAY_ELEMENT = document.querySelector(
window.BUILDER_HYDRATION_OVERLAY.APP_ROOT_SELECTOR
);
if (BUILDER_HYDRATION_OVERLAY_ELEMENT) {
window.BUILDER_HYDRATION_OVERLAY.SSR_HTML =
BUILDER_HYDRATION_OVERLAY_ELEMENT.innerHTML;
}
Loading

0 comments on commit 9545fce

Please sign in to comment.