Skip to content
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

feat: add remix-infinite-scroll example #564

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions remix-infinite-scroll/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/**
* This is intended to be a basic starting point for linting in your app.
* It relies on recommended configs out of the box for simplicity, but you can
* and should modify this configuration to best suit your team's needs.
*/

/** @type {import('eslint').Linter.Config} */
module.exports = {
root: true,
parserOptions: {
ecmaVersion: "latest",
sourceType: "module",
ecmaFeatures: {
jsx: true,
},
},
env: {
browser: true,
commonjs: true,
es6: true,
},
ignorePatterns: ["!**/.server", "!**/.client"],

// Base config
extends: ["eslint:recommended"],

overrides: [
// React
{
files: ["**/*.{js,jsx,ts,tsx}"],
plugins: ["react", "jsx-a11y"],
extends: [
"plugin:react/recommended",
"plugin:react/jsx-runtime",
"plugin:react-hooks/recommended",
"plugin:jsx-a11y/recommended",
],
settings: {
react: {
version: "detect",
},
formComponents: ["Form"],
linkComponents: [
{ name: "Link", linkAttribute: "to" },
{ name: "NavLink", linkAttribute: "to" },
],
"import/resolver": {
typescript: {},
},
},
},

// Typescript
{
files: ["**/*.{ts,tsx}"],
plugins: ["@typescript-eslint", "import"],
parser: "@typescript-eslint/parser",
settings: {
"import/internal-regex": "^~/",
"import/resolver": {
node: {
extensions: [".ts", ".tsx"],
},
typescript: {
alwaysTryTypes: true,
},
},
},
extends: [
"plugin:@typescript-eslint/recommended",
"plugin:import/recommended",
"plugin:import/typescript",
],
},

// Node
{
files: [".eslintrc.cjs"],
env: {
node: true,
},
},
],
};
5 changes: 5 additions & 0 deletions remix-infinite-scroll/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules

/.cache
/build
.env
38 changes: 38 additions & 0 deletions remix-infinite-scroll/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Remix Infinite Query Example

A demonstration of infinite scroll implementation in Remix using React Query, Loaders, and Defer for optimal performance and user experience.

## Preview

Open this example on [CodeSandbox](https://codesandbox.com):

<!-- TODO: update this li nk to the path for your example: -->

[![Open in CodeSandbox](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/github/remix-run/examples/tree/main/remix-infinite-scroll)

## Example

A demonstration of infinite scroll implementation in Remix using React Query, Loaders, and Defer for optimal performance and user experience.

📁 Project Structure

```
app/
├── components/ # React components
│ ├── LoadingState.tsx
│ ├── PostCard.tsx
│ ├── PostSkeleton.tsx
│ └── PostsList.tsx
├── hooks/ # Custom hooks
│ ├── useIntersectionObserver.ts
│ └── usePosts.ts
├── routes/ # Remix routes
│ ├── _index.tsx
│ └── api.posts.ts
└── types/ # TypeScript types
└── post.ts
```

## Related Links

[remix-loader-infinite-useQuery-bestpractice](https://github.com/Amateur0x1/remix-loader-infinite-useQuery-bestpractice)
24 changes: 24 additions & 0 deletions remix-infinite-scroll/app/components/LoadingState.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { PostSkeleton } from './PostSkeleton';

export function LoadingState() {
return (
<div className="space-y-4" role="status" aria-label="Loading posts">
<div className="flex items-center justify-center">首次加载中...</div>
{Array.from({ length: 3 }).map((_, i) => (
<PostSkeleton key={i} />
))}
</div>
);
}


export function LoadingState2() {
return (
<div className="space-y-4" role="status" aria-label="Loading posts">
<div className="flex items-center justify-center">之后的加载...</div>
{Array.from({ length: 3 }).map((_, i) => (
<PostSkeleton key={i} />
))}
</div>
);
}
11 changes: 11 additions & 0 deletions remix-infinite-scroll/app/components/PostCard.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { Post } from '~/types/post';

export function PostCard({ post }: { post: Post }) {
return (
<div className="p-4 border rounded-lg mb-4 shadow-sm">
<h2 className="text-xl font-bold mb-2">{post.title}</h2>
<p className="text-gray-600 mb-2">{post.content}</p>
<p className="text-sm text-gray-500">By {post.author}</p>
</div>
);
}
9 changes: 9 additions & 0 deletions remix-infinite-scroll/app/components/PostSkeleton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export function PostSkeleton() {
return (
<div className="p-4 border rounded-lg mb-4 shadow-sm animate-pulse">
<div className="h-6 bg-gray-200 rounded w-3/4 mb-2"></div>
<div className="h-4 bg-gray-200 rounded w-full mb-2"></div>
<div className="h-4 bg-gray-200 rounded w-1/2"></div>
</div>
);
}
18 changes: 18 additions & 0 deletions remix-infinite-scroll/app/components/PostsList.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import type { Post } from '~/types/post';

interface PostsListProps {
posts: Post[];
}

export function PostsList({ posts }: PostsListProps) {
return (
<div className="space-y-4">
{posts.map((post) => (
<div key={post.id} className="border p-4 rounded">
<h2 className="text-xl font-bold">{post.title}</h2>
<p>{post.content}</p>
</div>
))}
</div>
);
}
18 changes: 18 additions & 0 deletions remix-infinite-scroll/app/entry.client.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* By default, Remix will handle hydrating your app on the client for you.
* You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨
* For more information, see https://remix.run/file-conventions/entry.client
*/

import { RemixBrowser } from "@remix-run/react";
import { startTransition, StrictMode } from "react";
import { hydrateRoot } from "react-dom/client";

startTransition(() => {
hydrateRoot(
document,
<StrictMode>
<RemixBrowser />
</StrictMode>
);
});
140 changes: 140 additions & 0 deletions remix-infinite-scroll/app/entry.server.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
/**
* By default, Remix will handle generating the HTTP Response for you.
* You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨
* For more information, see https://remix.run/file-conventions/entry.server
*/

import { PassThrough } from "node:stream";

import type { AppLoadContext, EntryContext } from "@remix-run/node";
import { createReadableStreamFromReadable } from "@remix-run/node";
import { RemixServer } from "@remix-run/react";
import { isbot } from "isbot";
import { renderToPipeableStream } from "react-dom/server";

const ABORT_DELAY = 5_000;

export default function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext,
// This is ignored so we can keep it in the template for visibility. Feel
// free to delete this parameter in your app if you're not using it!
// eslint-disable-next-line @typescript-eslint/no-unused-vars
loadContext: AppLoadContext
) {
return isbot(request.headers.get("user-agent") || "")
? handleBotRequest(
request,
responseStatusCode,
responseHeaders,
remixContext
)
: handleBrowserRequest(
request,
responseStatusCode,
responseHeaders,
remixContext
);
}

function handleBotRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext
) {
return new Promise((resolve, reject) => {
let shellRendered = false;
const { pipe, abort } = renderToPipeableStream(
<RemixServer
context={remixContext}
url={request.url}
abortDelay={ABORT_DELAY}
/>,
{
onAllReady() {
shellRendered = true;
const body = new PassThrough();
const stream = createReadableStreamFromReadable(body);

responseHeaders.set("Content-Type", "text/html");

resolve(
new Response(stream, {
headers: responseHeaders,
status: responseStatusCode,
})
);

pipe(body);
},
onShellError(error: unknown) {
reject(error);
},
onError(error: unknown) {
responseStatusCode = 500;
// Log streaming rendering errors from inside the shell. Don't log
// errors encountered during initial shell rendering since they'll
// reject and get logged in handleDocumentRequest.
if (shellRendered) {
console.error(error);
}
},
}
);

setTimeout(abort, ABORT_DELAY);
});
}

function handleBrowserRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext
) {
return new Promise((resolve, reject) => {
let shellRendered = false;
const { pipe, abort } = renderToPipeableStream(
<RemixServer
context={remixContext}
url={request.url}
abortDelay={ABORT_DELAY}
/>,
{
onShellReady() {
shellRendered = true;
const body = new PassThrough();
const stream = createReadableStreamFromReadable(body);

responseHeaders.set("Content-Type", "text/html");

resolve(
new Response(stream, {
headers: responseHeaders,
status: responseStatusCode,
})
);

pipe(body);
},
onShellError(error: unknown) {
reject(error);
},
onError(error: unknown) {
responseStatusCode = 500;
// Log streaming rendering errors from inside the shell. Don't log
// errors encountered during initial shell rendering since they'll
// reject and get logged in handleDocumentRequest.
if (shellRendered) {
console.error(error);
}
},
}
);

setTimeout(abort, ABORT_DELAY);
});
}
Loading