feat: 初版
This commit is contained in:
+24
@@ -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?
|
||||
@@ -0,0 +1,161 @@
|
||||
# InfiniteCanvas 无限滑动画布
|
||||
|
||||
基于 [Leafer-UI](https://www.leaferjs.com/) 的 React 无限滑动画布组件。卡片以网格平铺,支持**四向无限环绕**、**拖拽平移**、**惯性滑动**、**响应式布局**与**点击回调**。卡片内容通过 `renderCard` 插槽以 Leafer 节点形式自由绘制。
|
||||
|
||||
## 特性
|
||||
|
||||
- **四向无限环绕**:上下左右任意方向都能无限滑动,卡片通过取模循环复用,无缝衔接。
|
||||
- **拖拽 + 惯性**:鼠标/触摸拖拽平移,松手后按摩擦系数衰减惯性滑动。
|
||||
- **响应式布局**:`columns` / `cardWidth` / `cardHeight` / `gapX` / `gapY` 均可传函数,依容器尺寸动态计算;内部用 `ResizeObserver` 监听,并按布局签名去重,无变化时零开销重建。
|
||||
- **自定义渲染**:`renderCard` 返回任意 Leafer 节点(`Box` / `Image` / `Text` / `Rect` …),完全掌控卡片样式。
|
||||
- **点击命中**:基于 Leafer 的 `TAP` 事件(自带拖拽阈值),平移后不会误触发点击。
|
||||
- **泛型支持**:`InfiniteCanvas<T>` 与数据类型强绑定,类型安全。
|
||||
|
||||
## 安装
|
||||
|
||||
组件依赖 `leafer-ui` 与 `react`:
|
||||
|
||||
```bash
|
||||
pnpm add leafer-ui react react-dom
|
||||
```
|
||||
|
||||
将 `src/components/InfiniteCanvas` 目录拷贝到你的项目即可使用。
|
||||
|
||||
## 快速开始
|
||||
|
||||
```tsx
|
||||
import { useCallback } from "react";
|
||||
import { Box, Text } from "leafer-ui";
|
||||
import { InfiniteCanvas } from "./components/InfiniteCanvas";
|
||||
|
||||
interface Card {
|
||||
id: number;
|
||||
color: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
const items: Card[] = Array.from({ length: 50 }, (_, i) => ({
|
||||
id: i + 1,
|
||||
color: "#54A0FF",
|
||||
label: `Card ${i + 1}`
|
||||
}));
|
||||
|
||||
function App() {
|
||||
// 用 useCallback 保持引用稳定,避免每次渲染重建画布
|
||||
const renderCard = useCallback(
|
||||
(item: Card, _index: number, size: { width: number; height: number }) => {
|
||||
return new Box({
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
fill: item.color,
|
||||
cornerRadius: 16,
|
||||
children: [
|
||||
new Text({
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
text: item.label,
|
||||
fill: "#ffffff",
|
||||
fontSize: Math.round(size.width * 0.11),
|
||||
fontWeight: "bold",
|
||||
textAlign: "center",
|
||||
verticalAlign: "middle"
|
||||
})
|
||||
]
|
||||
});
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="w-screen h-screen">
|
||||
<InfiniteCanvas
|
||||
items={items}
|
||||
renderCard={renderCard}
|
||||
columns={3}
|
||||
cardWidth={180}
|
||||
cardHeight={250}
|
||||
gapX={32}
|
||||
gapY={32}
|
||||
friction={0.97}
|
||||
background="#171717"
|
||||
onCardClick={(item) => console.log("clicked", item)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## 响应式布局
|
||||
|
||||
布局相关 props 支持传入 `(size) => value` 函数,依容器宽高动态计算。例如按断点切换列数与卡片尺寸:
|
||||
|
||||
```tsx
|
||||
// 按容器宽度分档:手机窄、平板中、桌面宽
|
||||
const byWidth = <V,>(w: number, sm: V, md: V, lg: V): V =>
|
||||
w < 768 ? sm : w < 1440 ? md : lg;
|
||||
|
||||
<InfiniteCanvas
|
||||
items={items}
|
||||
renderCard={renderCard}
|
||||
columns={({ width }) => byWidth(width, 3, 5, 7)}
|
||||
cardWidth={({ width }) => byWidth(width, 180, 260, 340)}
|
||||
cardHeight={({ width }) => byWidth(width, 250, 360, 470)}
|
||||
/>
|
||||
```
|
||||
|
||||
> `renderCard` 的第三个参数 `size` 即当前解析后的卡片宽高,绘制时使用它可保证卡片随响应式尺寸缩放,与网格布局一致。
|
||||
|
||||
## API
|
||||
|
||||
### `InfiniteCanvas<T>` Props
|
||||
|
||||
| 属性 | 类型 | 默认值 | 说明 |
|
||||
| --------------- | ---------------------------------------------------------------------------- | ------------------- | ------------------------------------------------------------------------------------- |
|
||||
| `items` | `T[]` | — | **必填**。卡片数据数组。 |
|
||||
| `renderCard` | `(item: T, index: number, size: { width: number; height: number }) => IUI` | — | **必填**。卡片插槽,返回一个 Leafer 节点。建议用 `useCallback` 保持引用稳定。 |
|
||||
| `columns` | `Responsive<number>` | `7` | 列数。 |
|
||||
| `cardWidth` | `Responsive<number>` | `350` | 卡片宽(用于网格定位与无限环绕命中,需与`renderCard` 输出一致)。 |
|
||||
| `cardHeight` | `Responsive<number>` | `500` | 卡片高。 |
|
||||
| `gapX` | `Responsive<number>` | `40` | 横向间距。 |
|
||||
| `gapY` | `Responsive<number>` | `40` | 纵向间距。 |
|
||||
| `draggable` | `boolean` | `true` | 是否可拖拽平移。 |
|
||||
| `inertia` | `boolean` | `true` | 是否开启惯性滑动。 |
|
||||
| `friction` | `number` | `0.92` | 惯性每帧衰减系数(0~1,越大滑得越久)。 |
|
||||
| `onCardClick` | `(item: T, index: number) => void` | — | 点击卡片回调。 |
|
||||
| `background` | `string` | — | 画布背景色。 |
|
||||
| `className` | `string` | — | 容器`className`。 |
|
||||
| `style` | `CSSProperties` | 填满父级 100%×100% | 容器内联样式。 |
|
||||
|
||||
### 类型
|
||||
|
||||
```ts
|
||||
/** 响应式取值:传固定值,或根据容器尺寸动态计算的函数 */
|
||||
export type Responsive<V> =
|
||||
| V
|
||||
| ((size: { width: number; height: number }) => V);
|
||||
```
|
||||
|
||||
## 工作原理
|
||||
|
||||
`useInfiniteSlide` 钩子封装了完整的滑动引擎:
|
||||
|
||||
1. **网格平铺**:将 `columns × baseRows` 的基础瓦片平铺到比视口更大的范围,空槽循环复用 `items`,补全为完整矩形,避免出现空洞。
|
||||
2. **取模环绕**:拖拽/惯性时对每个节点坐标做 `wrap` 取模运算,将其规整到 `[-size, span - size)` 区间,使屏幕任意位置都被卡片覆盖;连续 wrap 消除阈值处的 1px 闪烁。
|
||||
3. **惯性滑动**:松手时记录最近速度,用 `requestAnimationFrame` 每帧按 `friction` 衰减,低于阈值时停止。
|
||||
4. **响应式重建**:`ResizeObserver` 监听容器尺寸,解析布局配置;仅当解析值或平铺规模变化时(签名去重)才真正重建网格。
|
||||
5. **生命周期安全**:易变的回调/配置存于 `ref`,避免触发画布重建;清理逻辑兼容 React StrictMode 的双调用。
|
||||
|
||||
## 本地运行
|
||||
|
||||
仓库内含一个使用 50 张色块卡片的示例(`src/App.tsx`),无需任何图片资源即可跑通:
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm dev # 启动开发服务器
|
||||
pnpm build # 类型检查 + 打包
|
||||
pnpm preview # 预览构建产物
|
||||
```
|
||||
|
||||
## 技术栈
|
||||
|
||||
React 19 · TypeScript · Vite · Leafer-UI · Tailwind CSS
|
||||
@@ -0,0 +1,22 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
js.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
reactHooks.configs.flat.recommended,
|
||||
reactRefresh.configs.vite,
|
||||
],
|
||||
languageOptions: {
|
||||
globals: globals.browser,
|
||||
},
|
||||
},
|
||||
])
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>infinite-slide</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"name": "my-react-app",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@leafer-ui/core": "^2.1.8",
|
||||
"@leafer-ui/draw": "^2.1.8",
|
||||
"@tailwindcss/vite": "^4.3.1",
|
||||
"leafer-ui": "^2.1.8",
|
||||
"react": "^19.2.7",
|
||||
"react-dom": "^19.2.7",
|
||||
"tailwindcss": "^4.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@types/node": "^24.13.2",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.2",
|
||||
"eslint": "^10.5.0",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.3",
|
||||
"globals": "^17.6.0",
|
||||
"typescript": "~6.0.2",
|
||||
"typescript-eslint": "^8.61.0",
|
||||
"vite": "^8.1.0"
|
||||
}
|
||||
}
|
||||
Generated
+2386
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 9.3 KiB |
@@ -0,0 +1,24 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg">
|
||||
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
||||
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
||||
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
||||
</symbol>
|
||||
<symbol id="discord-icon" viewBox="0 0 20 19">
|
||||
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
||||
</symbol>
|
||||
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
||||
</symbol>
|
||||
<symbol id="github-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
<symbol id="social-icon" viewBox="0 0 20 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
||||
</symbol>
|
||||
<symbol id="x-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.9 KiB |
+79
@@ -0,0 +1,79 @@
|
||||
import { useCallback } from "react";
|
||||
import { Box, Text } from "leafer-ui";
|
||||
import { InfiniteCanvas } from "./components/InfiniteCanvas";
|
||||
|
||||
interface Card {
|
||||
id: number;
|
||||
color: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
const PALETTE = [
|
||||
"#0F172A",
|
||||
"#111827",
|
||||
"#1E1B4B",
|
||||
"#312E81",
|
||||
"#0E7490",
|
||||
"#065F46",
|
||||
"#7F1D1D",
|
||||
"#831843",
|
||||
"#92400E",
|
||||
"#334155"
|
||||
];
|
||||
|
||||
// 50 张示例卡片,无需任何图片资源即可跑通
|
||||
const items: Card[] = Array.from({ length: 50 }, (_, i) => ({
|
||||
id: i + 1,
|
||||
color: PALETTE[i % PALETTE.length],
|
||||
label: `Card ${i + 1}`
|
||||
}));
|
||||
|
||||
// 按容器宽度分档:手机窄、平板中、桌面宽
|
||||
const byWidth = <V,>(w: number, sm: V, md: V, lg: V): V =>
|
||||
w < 768 ? sm : w < 1440 ? md : lg;
|
||||
|
||||
function App() {
|
||||
// renderCard 用第三参 size 绘制,保证卡片随响应式尺寸缩放
|
||||
const renderCard = useCallback(
|
||||
(item: Card, _index: number, size: { width: number; height: number }) => {
|
||||
return new Box({
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
fill: item.color,
|
||||
cornerRadius: 16,
|
||||
children: [
|
||||
new Text({
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
text: item.label,
|
||||
fill: "#ffffff",
|
||||
fontSize: Math.round(size.width * 0.11),
|
||||
fontWeight: "bold",
|
||||
textAlign: "center",
|
||||
verticalAlign: "middle"
|
||||
})
|
||||
]
|
||||
});
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="w-screen h-screen bg-[#171717]">
|
||||
<InfiniteCanvas
|
||||
items={items}
|
||||
renderCard={renderCard}
|
||||
columns={({ width }) => byWidth(width, 3, 5, 7)}
|
||||
cardWidth={({ width }) => byWidth(width, 180, 260, 340)}
|
||||
cardHeight={({ width }) => byWidth(width, 250, 360, 470)}
|
||||
gapX={32}
|
||||
gapY={32}
|
||||
friction={0.97}
|
||||
background="#171717"
|
||||
onCardClick={(item) => console.log("clicked", item)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
@@ -0,0 +1,28 @@
|
||||
import { useRef } from "react";
|
||||
import type { CSSProperties } from "react";
|
||||
import { useInfiniteSlide } from "./useInfiniteSlide";
|
||||
import type { InfiniteCanvasProps } from "./types";
|
||||
|
||||
const fillStyle: CSSProperties = {
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
cursor: "grab",
|
||||
touchAction: "none"
|
||||
};
|
||||
|
||||
/**
|
||||
* 通用无限滑动画布。卡片通过 renderCard 插槽以 Leafer 节点形式渲染,
|
||||
* 支持拖拽平移、惯性滑动、点击回调与四向无限环绕。
|
||||
*/
|
||||
export function InfiniteCanvas<T>(props: InfiniteCanvasProps<T>) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
useInfiniteSlide(containerRef, props);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={props.className}
|
||||
style={{ ...fillStyle, ...props.style }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { InfiniteCanvas } from "./InfiniteCanvas";
|
||||
export type { InfiniteCanvasProps, Responsive } from "./types";
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { CSSProperties } from "react";
|
||||
import type { IUI } from "leafer-ui";
|
||||
|
||||
/** 响应式取值:传固定值,或根据容器尺寸动态计算的函数 */
|
||||
export type Responsive<V> =
|
||||
| V
|
||||
| ((size: { width: number; height: number }) => V);
|
||||
|
||||
export interface InfiniteCanvasProps<T> {
|
||||
/** 卡片数据数组 */
|
||||
items: T[];
|
||||
/**
|
||||
* 卡片插槽:返回一个 Leafer 节点(Box / Image / Text / Rect …)
|
||||
* 第三个参数 size 为当前解析后的卡片宽高,响应式时用它来绘制以与布局一致
|
||||
* 建议用 useCallback 保持引用稳定,否则每次变化都会重建画布
|
||||
*/
|
||||
renderCard: (
|
||||
item: T,
|
||||
index: number,
|
||||
size: { width: number; height: number }
|
||||
) => IUI;
|
||||
|
||||
// —— 网格布局(均支持响应式:数字 或 (size) => 数字)——
|
||||
/** 列数,默认 7 */
|
||||
columns?: Responsive<number>;
|
||||
/** 卡片宽(用于网格定位与无限环绕命中,需与 renderCard 输出一致),默认 350 */
|
||||
cardWidth?: Responsive<number>;
|
||||
/** 卡片高,默认 500 */
|
||||
cardHeight?: Responsive<number>;
|
||||
/** 横向间距,默认 40 */
|
||||
gapX?: Responsive<number>;
|
||||
/** 纵向间距,默认 40 */
|
||||
gapY?: Responsive<number>;
|
||||
|
||||
// —— 交互 ——
|
||||
/** 是否可拖拽平移,默认 true */
|
||||
draggable?: boolean;
|
||||
/** 是否开启惯性滑动,默认 true */
|
||||
inertia?: boolean;
|
||||
/** 惯性每帧衰减系数(0~1,越大滑得越久),默认 0.92 */
|
||||
friction?: number;
|
||||
/** 点击卡片回调 */
|
||||
onCardClick?: (item: T, index: number) => void;
|
||||
|
||||
// —— 外观 / 容器 ——
|
||||
/** 画布背景色(可选) */
|
||||
background?: string;
|
||||
/** 容器 className */
|
||||
className?: string;
|
||||
/** 容器内联样式(默认填满父级 100% × 100%) */
|
||||
style?: CSSProperties;
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { Leafer, PointerEvent } from "leafer-ui";
|
||||
import type { IUI } from "leafer-ui";
|
||||
import type { InfiniteCanvasProps, Responsive } from "./types";
|
||||
|
||||
/**
|
||||
* 无限滑动引擎:负责 Leafer 生命周期、网格布局、拖拽平移、惯性滑动、
|
||||
* 无限取模环绕、点击命中。封装原生 demo 的 create_img_data / move_imgs / check_img
|
||||
*
|
||||
* 响应式:columns / cardWidth / cardHeight / gapX / gapY 可传函数,组件用
|
||||
* ResizeObserver 测容器尺寸并解析;解析值变化才重建网格(签名去重,无变化零开销)
|
||||
*/
|
||||
export function useInfiniteSlide<T>(
|
||||
containerRef: React.RefObject<HTMLDivElement | null>,
|
||||
props: InfiniteCanvasProps<T>
|
||||
) {
|
||||
const {
|
||||
items,
|
||||
renderCard,
|
||||
draggable = true,
|
||||
inertia = true,
|
||||
friction = 0.92,
|
||||
background
|
||||
} = props;
|
||||
|
||||
// 易变的回调/配置用 ref 存最新值,避免进入 effect 依赖导致画布重建
|
||||
// 在 passive effect 中更新(不能在 render 期间写 ref)
|
||||
const onCardClickRef = useRef(props.onCardClick);
|
||||
const draggableRef = useRef(draggable);
|
||||
const inertiaRef = useRef(inertia);
|
||||
const frictionRef = useRef(friction);
|
||||
const layoutCfgRef = useRef({
|
||||
columns: props.columns,
|
||||
cardWidth: props.cardWidth,
|
||||
cardHeight: props.cardHeight,
|
||||
gapX: props.gapX,
|
||||
gapY: props.gapY
|
||||
});
|
||||
// 指向当前画布的重新布局函数(结构性 effect 内赋值,供 props 变化时触发)
|
||||
const layoutRef = useRef<(() => void) | undefined>(undefined);
|
||||
|
||||
useEffect(() => {
|
||||
onCardClickRef.current = props.onCardClick;
|
||||
draggableRef.current = draggable;
|
||||
inertiaRef.current = inertia;
|
||||
frictionRef.current = friction;
|
||||
layoutCfgRef.current = {
|
||||
columns: props.columns,
|
||||
cardWidth: props.cardWidth,
|
||||
cardHeight: props.cardHeight,
|
||||
gapX: props.gapX,
|
||||
gapY: props.gapY
|
||||
};
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const container = containerRef.current;
|
||||
if (!container || items.length === 0) return;
|
||||
|
||||
// —— 创建画布;禁用内置平移/缩放,改用自定义拖拽以实现无限环绕 ——
|
||||
const leafer = new Leafer({
|
||||
view: container,
|
||||
fill: background,
|
||||
move: { disabled: true },
|
||||
zoom: { disabled: true },
|
||||
wheel: { disabled: true }
|
||||
});
|
||||
|
||||
// —— 当前网格状态(由 layout 重建,闭包内拖拽/环绕逻辑共享)——
|
||||
let nodes: IUI[] = [];
|
||||
let totalSpanX = 0; // 横向环绕周期
|
||||
let totalSpanY = 0; // 纵向环绕周期
|
||||
let curCardWidth = 0; // 解析后的卡片宽(环绕命中用)
|
||||
let curCardHeight = 0;
|
||||
let lastSig = ""; // 上次布局签名,用于去重避免无谓重建
|
||||
|
||||
const resolve = (
|
||||
v: Responsive<number> | undefined,
|
||||
dflt: number,
|
||||
w: number,
|
||||
h: number
|
||||
): number => {
|
||||
const r = typeof v === "function" ? v({ width: w, height: h }) : v;
|
||||
return typeof r === "number" && r > 0 ? r : dflt;
|
||||
};
|
||||
|
||||
/**
|
||||
* 按当前容器尺寸解析配置并(必要时)重建网格:把 columns×baseRows 的基础
|
||||
* 瓦片平铺到比视口更大,并补全为完整矩形(空槽循环复用 items,避免空洞)
|
||||
*/
|
||||
const layout = () => {
|
||||
const W = container.clientWidth || 0;
|
||||
const H = container.clientHeight || 0;
|
||||
if (W === 0 || H === 0) return;
|
||||
|
||||
const cfg = layoutCfgRef.current;
|
||||
const columns = Math.max(1, Math.round(resolve(cfg.columns, 7, W, H)));
|
||||
const cardWidth = resolve(cfg.cardWidth, 350, W, H);
|
||||
const cardHeight = resolve(cfg.cardHeight, 500, W, H);
|
||||
const gapX = resolve(cfg.gapX, 40, W, H);
|
||||
const gapY = resolve(cfg.gapY, 40, W, H);
|
||||
|
||||
const stepX = cardWidth + gapX;
|
||||
const stepY = cardHeight + gapY;
|
||||
const baseRows = Math.max(1, Math.ceil(items.length / columns));
|
||||
// 平铺份数:让总跨度 ≥ 视口 + 一个步距,确保环绕窗口完整覆盖屏幕
|
||||
const repX = Math.max(1, Math.ceil((W + stepX) / (columns * stepX)));
|
||||
const repY = Math.max(1, Math.ceil((H + stepY) / (baseRows * stepY)));
|
||||
const totalCols = columns * repX;
|
||||
const totalRows = baseRows * repY;
|
||||
|
||||
// 解析值 + 平铺规模都没变 → 跳过,避免无谓重建(如 resize 但未越界)
|
||||
const sig = `${columns}|${cardWidth}|${cardHeight}|${gapX}|${gapY}|${totalCols}|${totalRows}`;
|
||||
if (sig === lastSig) return;
|
||||
lastSig = sig;
|
||||
|
||||
for (const node of nodes) node.destroy();
|
||||
nodes = [];
|
||||
curCardWidth = cardWidth;
|
||||
curCardHeight = cardHeight;
|
||||
totalSpanX = totalCols * stepX;
|
||||
totalSpanY = totalRows * stepY;
|
||||
|
||||
const size = { width: cardWidth, height: cardHeight };
|
||||
for (let row = 0; row < totalRows; row++) {
|
||||
for (let col = 0; col < totalCols; col++) {
|
||||
// 基础瓦片内的槽位 → 复用 items;每份瓦片内卡片顺序一致
|
||||
const index =
|
||||
((row % baseRows) * columns + (col % columns)) % items.length;
|
||||
const item = items[index];
|
||||
const node = renderCard(item, index, size);
|
||||
node.x = col * stepX;
|
||||
node.y = row * stepY;
|
||||
// Leafer 的 TAP 自带拖拽阈值,平移后不会误触发点击
|
||||
node.on(PointerEvent.TAP, () =>
|
||||
onCardClickRef.current?.(item, index)
|
||||
);
|
||||
leafer.add(node);
|
||||
nodes.push(node);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
layout();
|
||||
layoutRef.current = layout;
|
||||
|
||||
// —— 平移 + 取模环绕(连续 wrap,消除阈值处 1px teleport 闪烁)——
|
||||
// 把 v 规整到 [-size, span - size) 区间:屏幕任意位置都被覆盖
|
||||
const wrap = (v: number, span: number, size: number) => {
|
||||
const lo = -size;
|
||||
return ((((v - lo) % span) + span) % span) + lo;
|
||||
};
|
||||
const shift = (dx: number, dy: number) => {
|
||||
for (const node of nodes) {
|
||||
node.x = wrap((node.x ?? 0) + dx, totalSpanX, curCardWidth);
|
||||
node.y = wrap((node.y ?? 0) + dy, totalSpanY, curCardHeight);
|
||||
}
|
||||
};
|
||||
|
||||
// —— 拖拽状态 ——
|
||||
let dragging = false;
|
||||
let lastX = 0;
|
||||
let lastY = 0;
|
||||
let vx = 0; // 最近一次移动的速度(像素/帧)
|
||||
let vy = 0;
|
||||
let raf = 0;
|
||||
|
||||
// — 停止惯性滑动(取消 requestAnimationFrame)——
|
||||
const stopInertia = () => {
|
||||
if (raf) {
|
||||
cancelAnimationFrame(raf);
|
||||
raf = 0;
|
||||
}
|
||||
};
|
||||
|
||||
// — 惯性滑动(每帧按 friction 衰减,低于阈值停止)——
|
||||
const startInertia = () => {
|
||||
const MIN = 0.1;
|
||||
const step = () => {
|
||||
vx *= frictionRef.current;
|
||||
vy *= frictionRef.current;
|
||||
if (Math.abs(vx) < MIN && Math.abs(vy) < MIN) {
|
||||
raf = 0;
|
||||
return;
|
||||
}
|
||||
shift(vx, vy);
|
||||
raf = requestAnimationFrame(step);
|
||||
};
|
||||
raf = requestAnimationFrame(step);
|
||||
};
|
||||
|
||||
// — 拖拽事件处理(PointerEvent)——
|
||||
const onDown = (e: PointerEvent) => {
|
||||
if (!draggableRef.current) return;
|
||||
stopInertia();
|
||||
dragging = true;
|
||||
lastX = e.x;
|
||||
lastY = e.y;
|
||||
vx = 0;
|
||||
vy = 0;
|
||||
};
|
||||
|
||||
const onMove = (e: PointerEvent) => {
|
||||
if (!dragging) return;
|
||||
const dx = e.x - lastX;
|
||||
const dy = e.y - lastY;
|
||||
lastX = e.x;
|
||||
lastY = e.y;
|
||||
vx = dx;
|
||||
vy = dy;
|
||||
shift(dx, dy);
|
||||
};
|
||||
|
||||
const onUp = () => {
|
||||
if (!dragging) return;
|
||||
dragging = false;
|
||||
if (inertiaRef.current && (Math.abs(vx) > 0.5 || Math.abs(vy) > 0.5)) {
|
||||
startInertia();
|
||||
}
|
||||
};
|
||||
|
||||
leafer.on(PointerEvent.DOWN, onDown);
|
||||
leafer.on(PointerEvent.MOVE, onMove);
|
||||
leafer.on(PointerEvent.UP, onUp);
|
||||
|
||||
// —— 容器尺寸变化时重新布局(解析值/平铺规模变了才真重建,由签名去重)——
|
||||
const ro = new ResizeObserver(() => layout());
|
||||
ro.observe(container);
|
||||
|
||||
// —— 清理(StrictMode 双调用安全)——
|
||||
return () => {
|
||||
layoutRef.current = undefined;
|
||||
ro.disconnect();
|
||||
stopInertia();
|
||||
leafer.off(PointerEvent.DOWN, onDown);
|
||||
leafer.off(PointerEvent.MOVE, onMove);
|
||||
leafer.off(PointerEvent.UP, onUp);
|
||||
leafer.destroy();
|
||||
};
|
||||
// 结构性变化时重建画布;布局/交互配置走 ref,尺寸变化走 layout
|
||||
}, [containerRef, items, renderCard, background]);
|
||||
|
||||
// props 中的布局配置变化时(含响应式函数返回值变化),触发重新布局;
|
||||
// layout 内部按签名去重,无实际变化则零开销
|
||||
useEffect(() => {
|
||||
layoutRef.current?.();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
@import "tailwindcss";
|
||||
@@ -0,0 +1,10 @@
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import "./index.css";
|
||||
import App from "./App.tsx";
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>
|
||||
);
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023", "DOM"],
|
||||
"module": "esnext",
|
||||
"types": ["vite/client"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023"],
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"module": "nodenext",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
import tailwindcss from "@tailwindcss/vite";
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()]
|
||||
});
|
||||
Reference in New Issue
Block a user