Skip to content

Commit

Permalink
feat: add react fitter component
Browse files Browse the repository at this point in the history
  • Loading branch information
scriptcoded committed Nov 1, 2024
0 parents commit 7b70121
Show file tree
Hide file tree
Showing 18 changed files with 3,824 additions and 0 deletions.
24 changes: 24 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
50 changes: 50 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# React + TypeScript + Vite

This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.

Currently, two official plugins are available:

- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh

## Expanding the ESLint configuration

If you are developing a production application, we recommend updating the configuration to enable type aware lint rules:

- Configure the top-level `parserOptions` property like this:

```js
export default tseslint.config({
languageOptions: {
// other options...
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
},
})
```

- Replace `tseslint.configs.recommended` to `tseslint.configs.recommendedTypeChecked` or `tseslint.configs.strictTypeChecked`
- Optionally add `...tseslint.configs.stylisticTypeChecked`
- Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and update the config:

```js
// eslint.config.js
import react from 'eslint-plugin-react'

export default tseslint.config({
// Set the react version
settings: { react: { version: '18.3' } },
plugins: {
// Add the react plugin
react,
},
rules: {
// other rules...
// Enable its recommended rules
...react.configs.recommended.rules,
...react.configs['jsx-runtime'].rules,
},
})
```
30 changes: 30 additions & 0 deletions biome.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"$schema": "https://biomejs.dev/schemas/1.9.4/schema.json",
"vcs": {
"enabled": false,
"clientKind": "git",
"useIgnoreFile": false
},
"files": {
"ignoreUnknown": false,
"ignore": ["dist"]
},
"formatter": {
"enabled": true,
"indentStyle": "tab"
},
"organizeImports": {
"enabled": true
},
"linter": {
"enabled": true,
"rules": {
"recommended": true
}
},
"javascript": {
"formatter": {
"quoteStyle": "double"
}
}
}
13 changes: 13 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
88 changes: 88 additions & 0 deletions lib/Fitter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { type ReactNode, useEffect, useRef, useState } from "react";
import { useDebounce, useResizeObserver } from "./hooks";

export type FitterProps = {
children: ReactNode;
minSize?: number;
maxLines?: number;
settlePrecision?: number;
updateOnSizeChange?: boolean;
windowResizeDebounce?: number;
};

export const Fitter = ({
children,
minSize = 0.25,
maxLines = 1,
settlePrecision = 0.01,
updateOnSizeChange = true,
windowResizeDebounce = 100,
}: FitterProps) => {
const wrapperRef = useRef<HTMLDivElement>(null);
const textRef = useRef<HTMLSpanElement>(null);

const [size, setSize] = useState(1);
const [settled, setSettled] = useState(false);
const [targetMax, setTargetMax] = useState(1);

useEffect(() => {
if (settled) return;
if (!textRef.current) throw new Error("Could not access wrapper ref");

const lines = textRef.current.getClientRects().length;

const nextShrinkStep = (size - minSize) / 2;
const nextGrowStep = (targetMax - size) / 2;

const nextShrinkSize = size - nextShrinkStep;
const nextGrowSize = size + nextGrowStep;

const wantsToShrink = lines > maxLines;

if (wantsToShrink) {
if (nextShrinkStep < settlePrecision) {
setSettled(true);
return;
}

setTargetMax(size);
setSize(nextShrinkSize);
return;
}

if (nextGrowStep < settlePrecision) {
setSettled(true);
return;
}

setSize(nextGrowSize);
}, [size, maxLines, minSize, targetMax, settlePrecision, settled]);

const start = useDebounce(() => {
setTargetMax(1);
setSettled(false);
}, windowResizeDebounce);

useResizeObserver(wrapperRef, () => start(), updateOnSizeChange);

return (
<div
ref={wrapperRef}
className="react-fitter__wrapper"
style={{
lineHeight: 0,
}}
>
<span
ref={textRef}
style={{
fontSize: `${size * 100}%`,
lineHeight: 1,
}}
className="react-fitter__text"
>
{children}
</span>
</div>
);
};
63 changes: 63 additions & 0 deletions lib/hooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import {
type RefObject,
useEffect,
useLayoutEffect,
useMemo,
useRef,
} from "react";

const debounce = (callback: () => void, delay: number) => {
let timeout: NodeJS.Timeout;
return () => {
clearTimeout(timeout);
timeout = setTimeout(callback, delay);
};
};

export const useDebounce = <T extends unknown[], U>(
callback: (...args: T) => U,
delay: number,
) => {
const callbackRef = useRef(callback);
useLayoutEffect(() => {
callbackRef.current = callback;
});
return useMemo(
() => debounce((...args: T) => callbackRef.current(...args), delay),
[delay],
);
};

export const useResizeObserver = (
ref: RefObject<HTMLSpanElement>,
callback: () => void,
enabled: boolean,
) => {
const width = useRef(0);

// biome-ignore lint/correctness/useExhaustiveDependencies: Using a ref as a dependency doesn't work as expected.
useEffect(() => {
if (!ref.current) return;
if (!enabled) return;

const observer = new ResizeObserver((entries) => {
for (const entry of entries) {
// Some older browsers don't return contentBoxSize
const newWidth = entry.contentBoxSize
? entry.contentBoxSize[0].inlineSize
: entry.contentRect.width;

if (newWidth !== width.current) {
width.current = newWidth;
callback();
}
}
});

observer.observe(ref.current);

return () => {
observer.disconnect();
};
}, [enabled]);
};
1 change: 1 addition & 0 deletions lib/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./Fitter.js";
Loading

0 comments on commit 7b70121

Please sign in to comment.