prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
oClient } from "@apollo/experimental-nextjs-app-support/rsc";
export const { getClient } = registerApolloClient(() => {
return new ApolloClient({
cache: new InMemoryCache(),
link: new HttpLink({
// See more information about this GraphQL endpoint at https://studio.apollographql.com/public/spacex-l4uc6p... | the default `fetchOptions` on a per query basis
// ```js
// const result = await getClient().query({
// query: MY_QUERY,
// context: {
// fetchOptions: { cache: "force-cache" },
// },
// });
// ```
| e-cache" },
// alternatively you can override | {
"filepath": "examples/with-apollo/src/lib/ApolloClient.ts",
"language": "typescript",
"file_size": 932,
"cut_index": 606,
"middle_length": 52
} |
"next/link";
import { useRouter } from "next/router";
import Layout from "../components/Layout";
import List from "../components/List";
import { User } from "../interfaces";
import { findAll } from "../utils/sample-api";
type Props = {
items: User[];
pathname: string;
};
const WithInitialProps = ({ items }: Props... | ame}</p>
<List items={items} />
<p>
<Link href="/">Go home</Link>
</p>
</Layout>
);
};
export async function getStaticProps() {
const items: User[] = await findAll();
return { props: { items } };
}
export default With | t)</h1>
<p>You are currently on: {router.pathn | {
"filepath": "examples/with-electron-typescript/renderer/pages/initial-props.tsx",
"language": "tsx",
"file_size": 851,
"cut_index": 529,
"middle_length": 52
} |
{ Table } from "@nextui-org/react";
const CustomTable = () => {
return (
<Table
aria-label="Example table with static content"
css={{
height: "auto",
minWidth: "100%",
}}
>
<Table.Header>
<Table.Column>NAME</Table.Column>
<Table.Column>ROLE</Table.Colu... | Table.Cell>
</Table.Row>
<Table.Row key="3">
<Table.Cell>Jane Fisher</Table.Cell>
<Table.Cell>Senior Developer</Table.Cell>
<Table.Cell>Active</Table.Cell>
</Table.Row>
<Table.Row key="4">
| /Table.Cell>
<Table.Cell>Active</Table.Cell>
</Table.Row>
<Table.Row key="2">
<Table.Cell>Zoey Lang</Table.Cell>
<Table.Cell>Technical Lead</Table.Cell>
<Table.Cell>Paused</ | {
"filepath": "examples/with-next-ui/components/Table.tsx",
"language": "tsx",
"file_size": 1236,
"cut_index": 518,
"middle_length": 229
} |
import Avatar from "./avatar";
import Date from "./date";
import CoverImage from "./cover-image";
import Link from "next/link";
export default function HeroPost({
title,
coverImage,
date,
excerpt,
author,
slug,
}) {
return (
<section>
<div className="mb-8 md:mb-16">
<CoverImage title={t... | ate dateString={date} />
</div>
</div>
<div>
<p className="text-lg leading-relaxed mb-4">{excerpt}</p>
<Avatar name={author.name} picture={author.content.picture} />
</div>
</div>
</section>
| text-4xl lg:text-6xl leading-tight">
<Link href={`/posts/${slug}`} className="hover:underline">
{title}
</Link>
</h3>
<div className="mb-4 md:mb-0 text-lg">
<D | {
"filepath": "examples/cms-storyblok/components/hero-post.js",
"language": "javascript",
"file_size": 1003,
"cut_index": 512,
"middle_length": 229
} |
{ NextSeo } from "next-seo";
import Link from "next/link";
export default function Home() {
return (
<div>
<NextSeo
title="Page Meta Title"
description="This will be the page meta description"
canonical="https://www.canonicalurl.ie/"
openGraph={{
url: "https://www... | ight: 800,
alt: "Og Image Alt Second",
},
{ url: "https://www.example.ie/og-image-03.jpg" },
{ url: "https://www.example.ie/og-image-04.jpg" },
],
}}
/>
<h1>SEO Added to Page</ | 01.jpg",
width: 800,
height: 600,
alt: "Og Image Alt",
},
{
url: "https://www.example.ie/og-image-02.jpg",
width: 900,
he | {
"filepath": "examples/with-next-seo/pages/index.js",
"language": "javascript",
"file_size": 1206,
"cut_index": 518,
"middle_length": 229
} |
t { User } from "../interfaces";
/** Dummy user data. */
export const dataArray: User[] = [
{ id: 101, name: "Alice" },
{ id: 102, name: "Bob" },
{ id: 103, name: "Caroline" },
{ id: 104, name: "Dave" },
];
/**
* Calls a mock API which finds a user by ID from the list above.
*
* Throws an error if not foun... | elected;
}
/** Calls a mock API which returns the above array to simulate "get all". */
export async function findAll() {
// Throw an error, just for example.
if (!Array.isArray(dataArray)) {
throw new Error("Cannot find users");
}
return dat | }
return s | {
"filepath": "examples/with-electron-typescript/renderer/utils/sample-api.ts",
"language": "typescript",
"file_size": 797,
"cut_index": 517,
"middle_length": 14
} |
string
description: string
link: string
}
const Card = (props: Props) => {
return (
<Anchor
href={props.link}
target="_blank"
sx={{
border: '1px solid #eaeaea',
margin: '1rem',
padding: '1.5rem',
borderRadius: '10px',
textAlign: 'left',
color:... | fontSize: '1.5rem',
fontWeight: 'bold',
textAlign: 'left',
}}
>
{props.title}
</Text>
<Text
component="p"
sx={{
fontSize: '1rem',
textAlign: 'left',
}}
| <Text
component="h2"
sx={{
| {
"filepath": "examples/with-mantine/components/Card.tsx",
"language": "tsx",
"file_size": 980,
"cut_index": 582,
"middle_length": 52
} |
;
import {
useReducer,
useContext,
createContext,
ReactNode,
Dispatch,
} from "react";
type CounterState = number;
type CounterAction =
| {
type: "INCREASE" | "DECREASE";
}
| {
type: "INCREASE_BY";
payload: number;
};
const CounterStateContext = createContext<CounterState>(0);... | type CounterProviderProps = {
children: ReactNode;
initialValue?: number;
};
export const CounterProvider = ({
children,
initialValue = 0,
}: CounterProviderProps) => {
const [state, dispatch] = useReducer(reducer, initialValue);
return (
| NCREASE":
return state + 1;
case "DECREASE":
return state - 1;
case "INCREASE_BY":
return state + action.payload;
default:
throw new Error(`Unknown action: ${JSON.stringify(action)}`);
}
};
| {
"filepath": "examples/with-context-api/_components/Counter.tsx",
"language": "tsx",
"file_size": 1353,
"cut_index": 524,
"middle_length": 229
} |
IClientOptions } from "mqtt";
import MQTT from "mqtt";
import { useEffect, useRef } from "react";
interface useMqttProps {
uri: string;
options?: IClientOptions;
topicHandlers?: { topic: string; handler: (payload: any) => void }[];
onConnectedHandler?: (client: MqttClient) => void;
}
function useMqtt({
uri... | : MQTT.connect(uri);
} catch (error) {
console.error("error", error);
}
const client = clientRef.current;
topicHandlers.forEach((th) => {
client?.subscribe(th.topic);
});
client?.on("message", (topic: string, rawPa | t | null>(null);
useEffect(() => {
if (clientRef.current) return;
if (!topicHandlers || topicHandlers.length === 0) return () => {};
try {
clientRef.current = options
? MQTT.connect(uri, options)
| {
"filepath": "examples/with-mqtt-js/lib/useMqtt.ts",
"language": "typescript",
"file_size": 1671,
"cut_index": 537,
"middle_length": 229
} |
t useI18n from "../hooks/use-i18n";
import Title from "../components/title";
import { contentLanguageMap } from "../lib/i18n";
import EN from "../locales/en.json";
import DE from "../locales/de.json";
const Dashboard = () => {
const i18n = useI18n();
useEffect(() => {
i18n.locale("en", EN);
// eslint-disa... | ="Peter" />
<h2>{i18n.t("intro.text")}</h2>
<h3>{i18n.t("dashboard.description")}</h3>
<div>Current locale: {i18n.activeLocale}</div>
<a
href="#"
onClick={() => {
i18n.locale("de", DE);
}}
>
| ale]}
/>
</Head>
<Title username | {
"filepath": "examples/with-i18n-rosetta/pages/dashboard.js",
"language": "javascript",
"file_size": 990,
"cut_index": 582,
"middle_length": 52
} |
defineGlobalStyles,
defineRecipe,
defineTextStyles,
} from "@pandacss/dev";
// https://panda-css.com/docs/theming/text-styles#defining-text-styles
export const textStyles = defineTextStyles({
link: {
description: "The classic link text style - used in demo links",
value: {
fontSize: "lg",
f... | },
defaultVariants: {
size: "lg",
},
});
// https://panda-css.com/docs/concepts/writing-styles#global-styles
const globalCss = defineGlobalStyles({
html: {
bg: {
_default: "white",
_osDark: "black",
},
"& .icon": {
| he link component",
base: {
color: {
_default: "gray.800",
_osDark: "gray.100",
},
fontFamily: "inter",
},
variants: {
size: {
sm: { fontSize: "sm" },
lg: { fontSize: "lg" },
},
| {
"filepath": "examples/panda-css/panda.config.ts",
"language": "typescript",
"file_size": 1703,
"cut_index": 537,
"middle_length": 229
} |
{ Meta, StoryObj } from "@storybook/react";
import { fn } from "@storybook/test";
import { Button } from "./Button";
// More on how to set up stories at: https://storybook.js.org/docs/writing-stories#default-export
const meta = {
title: "Example/Button",
component: Button,
parameters: {
// Optional parameter... | // Use `fn` to spy on the onClick arg, which will appear in the actions panel once invoked: https://storybook.js.org/docs/essentials/actions#action-args
args: { onClick: fn() },
} satisfies Meta<typeof Button>;
export default meta;
type Story = StoryObj | todocs entry: https://storybook.js.org/docs/writing-docs/autodocs
tags: ["autodocs"],
// More on argTypes: https://storybook.js.org/docs/api/argtypes
argTypes: {
backgroundColor: {
control: "color",
},
},
| {
"filepath": "examples/with-storybook/stories/Button.stories.ts",
"language": "typescript",
"file_size": 1456,
"cut_index": 524,
"middle_length": 229
} |
port type { Meta, StoryObj } from "@storybook/react";
import { fn } from "@storybook/test";
import { Header } from "./Header";
const meta = {
title: "Example/Header",
component: Header,
// This component will have an automatically generated Autodocs entry: https://storybook.js.org/docs/react/writing-docs/autodoc... | ut: fn(),
onCreateAccount: fn(),
},
} satisfies Meta<typeof Header>;
export default meta;
type Story = StoryObj<typeof meta>;
export const LoggedIn: Story = {
args: {
user: {
name: "Jane Doe",
},
},
};
export const LoggedOut: Sto | (),
onLogo | {
"filepath": "examples/with-storybook/stories/Header.stories.ts",
"language": "typescript",
"file_size": 793,
"cut_index": 514,
"middle_length": 14
} |
mport type { Meta, StoryObj } from "@storybook/react";
import { within, userEvent, expect } from "@storybook/test";
import { Page } from "./Page";
const meta = {
title: "Example/Page",
component: Page,
parameters: {
// More on how to position stories at: https://storybook.js.org/docs/configure/story-layout
... | name: /Log in/i });
await expect(loginButton).toBeInTheDocument();
await userEvent.click(loginButton);
await expect(loginButton).not.toBeInTheDocument();
const logoutButton = canvas.getByRole("button", { name: /Log out/i });
await expe | tps://storybook.js.org/docs/writing-tests/interaction-testing
export const LoggedIn: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const loginButton = canvas.getByRole("button", { | {
"filepath": "examples/with-storybook/stories/Page.stories.ts",
"language": "typescript",
"file_size": 1044,
"cut_index": 513,
"middle_length": 229
} |
"./page.module.css";
export default function Home() {
return (
<main className={styles.main}>
<div className={styles.description}>
<p>
Get started by editing
<code className={styles.code}>src/app/page.tsx</code>
</p>
<div>
<a
href="htt... | </a>
</div>
</div>
<div className={styles.center}>
<Image
className={styles.logo}
src="/next.svg"
alt="Next.js Logo"
width={180}
height={37}
priority
/>
| {" "}
<Image
src="/vercel.svg"
alt="Vercel Logo"
className={styles.vercelLogo}
width={100}
height={24}
priority
/>
| {
"filepath": "examples/with-storybook/app/page.tsx",
"language": "tsx",
"file_size": 2766,
"cut_index": 563,
"middle_length": 229
} |
, Text } from "@nextui-org/react";
const CustomCollapse = () => {
return (
<Collapse.Group>
<Collapse title="Option A">
<Text>
I have had my invitation to this world's festival, and thus my life
has been blessed.
</Text>
</Collapse>
<Collapse title="Option B"... | came out on the chariot of the first gleam of light, and pursued my
voyage through the wildernesses of worlds leaving my track on many a
star and planet.
</Text>
</Collapse>
</Collapse.Group>
);
};
export default Cu | llapse title="Option C">
<Text>
I | {
"filepath": "examples/with-next-ui/components/Collapse.tsx",
"language": "tsx",
"file_size": 851,
"cut_index": 529,
"middle_length": 52
} |
Prop } from "../common/interface";
export const Password = ({ fill, size, height, width, ...props }: SvgProp) => {
return (
<svg
width={size || width || 24}
height={size || height || 24}
viewBox="0 0 24 24"
{...props}
>
<g fill={fill}>
<path d="M18.75 8v2.1a12.984 12.984... | 0 01.21-.33 1.032 1.032 0 01.33-.21 1 1 0 011.09.21 1.155 1.155 0 01.21.33A1 1 0 019 16a1.052 1.052 0 01-.29.71zm4.21-.33a1.155 1.155 0 01-.21.33A1.052 1.052 0 0112 17a1.033 1.033 0 01-.71-.29 1.155 1.155 0 01-.21-.33A1 1 0 0111 16a1.033 1.033 0 01.29-.71 | a12.984 12.984 0 00-1.5.1C2.7 10.41 2 11.66 2 15v2c0 4 1 5 5 5h10c4 0 5-1 5-5v-2c0-3.34-.7-4.59-3.25-4.9zM8.71 16.71A1.052 1.052 0 018 17a1 1 0 01-.38-.08 1.032 1.032 0 01-.33-.21A1.052 1.052 0 017 16a1 1 0 01.08-.38 1.155 1.155 | {
"filepath": "examples/with-next-ui/components/Password.tsx",
"language": "tsx",
"file_size": 1283,
"cut_index": 524,
"middle_length": 229
} |
m "@twilio-paste/core/anchor";
import { Heading } from "@twilio-paste/core/heading";
import { Box } from "@twilio-paste/core/box";
import { Paragraph } from "@twilio-paste/core/paragraph";
import { ListItem, UnorderedList } from "@twilio-paste/core/list";
import { ArrowForwardIcon } from "@twilio-paste/icons/cjs/ArrowF... |
</Heading>
<Paragraph>
Everything you need to get started using Paste in a Production app.
Start by editing <code>pages/index.tsx</code>
</Paragraph>
<Separator orientation="horizontal" verticalSpacing="space120" | .js App</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<Heading as="h1" variant="heading10">
Welcome to the{" "}
<Anchor href="https://paste.twilio.design">Paste Next.js App!</Anchor> | {
"filepath": "examples/with-paste-typescript/pages/index.tsx",
"language": "tsx",
"file_size": 2697,
"cut_index": 563,
"middle_length": 229
} |
lint-disable @typescript-eslint/no-namespace */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { contextBridge, ipcRenderer } from "electron";
import { IpcRendererEvent } from "electron/main";
// We are using the context bridge to securely expose NodeAPIs.
// Please note that many Node APIs grant... | llo: (handler: (event: IpcRendererEvent, ...args: any[]) => void) =>
ipcRenderer.on("message", handler),
stopReceivingHello: (
handler: (event: IpcRendererEvent, ...args: any[]) => void,
) => ipcRenderer.removeListener("message", handler),
});
| enderer.send("message", "hi from next"),
receiveHe | {
"filepath": "examples/with-electron-typescript/electron-src/preload.ts",
"language": "typescript",
"file_size": 825,
"cut_index": 517,
"middle_length": 52
} |
t { Box, Code, Text } from '@mantine/core'
import Card from '../components/Card'
import Grid from '../components/Grid'
const Home: NextPage = () => {
return (
<Box
component="main"
sx={{
paddingLeft: '2rem',
paddingRight: '2rem',
}}
>
<Head>
<title>Create Next ... | ,
}}
>
<Text
sx={{
color: '#0070f3',
fontSize: '2rem',
'@media (min-width: 800px)': {
fontSize: '3rem',
},
fontWeight: 'bold',
textAlign: | sx={{
minHeight: '100vh',
display: 'flex',
paddingTop: '2rem',
paddingBottom: '2rem',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center' | {
"filepath": "examples/with-mantine/pages/index.tsx",
"language": "tsx",
"file_size": 3428,
"cut_index": 614,
"middle_length": 229
} |
seState, useRef } from "react";
import type { MqttClient } from "mqtt";
import useMqtt from "@/lib/useMqtt";
export default function Home() {
const [incomingMessages, setIncomingMessages] = useState<any[]>([]);
const addMessage = (message: any) => {
setIncomingMessages((incomingMessages) => [...incomingMessage... | s.env.NEXT_PUBLIC_MQTT_URI,
options: {
username: process.env.NEXT_PUBLIC_MQTT_USERNAME,
password: process.env.NEXT_PUBLIC_MQTT_PASSWORD,
clientId: process.env.NEXT_PUBLIC_MQTT_CLIENTID,
},
topicHandlers: incomingMessageHandler | => {
addMessage(msg);
},
},
]);
const mqttClientRef = useRef<MqttClient | null>(null);
const setMqttClient = (client: MqttClient) => {
mqttClientRef.current = client;
};
useMqtt({
uri: proces | {
"filepath": "examples/with-mqtt-js/app/page.tsx",
"language": "tsx",
"file_size": 1836,
"cut_index": 537,
"middle_length": 229
} |
ort Link from "next/link";
import Head from "next/head";
import Title from "../../components/title";
import useI18n from "../../hooks/use-i18n";
import { languages, contentLanguageMap } from "../../lib/i18n";
const HomePage = () => {
const i18n = useI18n();
return (
<div>
<Head>
<meta
... | c function getStaticProps({ params }) {
const { default: lngDict = {} } = await import(
`../../locales/${params.lng}.json`
);
return {
props: { lng: params.lng, lngDict },
};
}
export async function getStaticPaths() {
return {
paths | >{i18n.t("intro.description")}</h3>
<div>Current locale: {i18n.activeLocale}</div>
<Link href="/[lng]" as="/de">
Use client-side routing to change language to 'de'
</Link>
</div>
);
};
export asyn | {
"filepath": "examples/with-i18n-rosetta/pages/[lng]/index.js",
"language": "javascript",
"file_size": 1104,
"cut_index": 515,
"middle_length": 229
} |
import React from "react";
import "./button.css";
interface ButtonProps {
/**
* Is this the principal call to action on the page?
*/
primary?: boolean;
/**
* What background color to use
*/
backgroundColor?: string;
/**
* How large should the button be?
*/
size?: "small" | "medium" | "lar... | type="button"
className={["storybook-button", `storybook-button--${size}`, mode].join(
" ",
)}
{...props}
>
{label}
<style jsx>{`
button {
background-color: ${backgroundColor};
}
`}< | on = ({
primary = false,
size = "medium",
backgroundColor,
label,
...props
}: ButtonProps) => {
const mode = primary
? "storybook-button--primary"
: "storybook-button--secondary";
return (
<button
| {
"filepath": "examples/with-storybook/stories/Button.tsx",
"language": "tsx",
"file_size": 1027,
"cut_index": 512,
"middle_length": 229
} |
;
import { Button } from "./Button";
import "./header.css";
type User = {
name: string;
};
interface HeaderProps {
user?: User;
onLogin?: () => void;
onLogout?: () => void;
onCreateAccount?: () => void;
}
export const Header = ({
user,
onLogin,
onLogout,
onCreateAccount,
}: HeaderProps) => (
<he... | d="M5.3 10.6l10.4 6v11.1l-10.4-6v-11zm11.4-6.2l9.7 5.5-9.7 5.6V4.4z"
fill="#555AB9"
/>
<path
d="M27.2 10.6v11.2l-10.5 6V16.5l10.5-6zM15.7 4.4v11L6 10l9.7-5.5z"
fill="#91BAF8"
| >
<g fill="none" fillRule="evenodd">
<path
d="M10 0h12a10 10 0 0110 10v12a10 10 0 01-10 10H10A10 10 0 010 22V10A10 10 0 0110 0z"
fill="#FFF"
/>
<path
| {
"filepath": "examples/with-storybook/stories/Header.tsx",
"language": "tsx",
"file_size": 1644,
"cut_index": 537,
"middle_length": 229
} |
port { SvgProp } from "../common/interface";
export const Mail = ({ fill, size, height, width, ...props }: SvgProp) => {
return (
<svg
width={size || width || 24}
height={size || height || 24}
viewBox="0 0 24 24"
{...props}
>
<g
fill="none"
stroke={fill}
... | 66 3.166 0 01-3.75 0L7 9M19.21 14.77l-3.539 3.54a1.232 1.232 0 00-.3.59l-.19 1.35a.635.635 0 00.76.76l1.35-.19a1.189 1.189 0 00.59-.3l3.54-3.54a1.365 1.365 0 000-2.22 1.361 1.361 0 00-2.211.01zM18.7 15.28a3.185 3.185 0 002.22 2.22" />
</g>
</svg> | l-3.13 2.5a3.1 | {
"filepath": "examples/with-next-ui/components/Mail.tsx",
"language": "tsx",
"file_size": 793,
"cut_index": 514,
"middle_length": 14
} |
next/link";
import { gql, useQuery } from "@apollo/client";
const ViewerQuery = gql`
query ViewerQuery {
viewer {
id
email
}
}
`;
const Index = () => {
const router = useRouter();
const { data, loading, error } = useQuery(ViewerQuery);
const viewer = data?.viewer;
const shouldRedirect ... | }</p>;
}
if (viewer) {
return (
<div>
You're signed in as {viewer.email}. Go to{" "}
<Link href="/about">about</Link> page or{" "}
<Link href="/signout">signout</Link>.
</div>
);
}
return <p>Loading...< | rect]);
if (error) {
return <p>{error.message | {
"filepath": "examples/api-routes-apollo-server-and-client-auth/pages/index.tsx",
"language": "tsx",
"file_size": 945,
"cut_index": 606,
"middle_length": 52
} |
rom "next/head";
import Image from "next/image";
import styles from "../../styles/Home.module.css";
const Home: NextPage = () => {
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<li... | ttps://nextjs.org/docs" className={styles.card}>
<h2>Documentation →</h2>
<p>Find in-depth information about Next.js features and API.</p>
</a>
<a href="https://nextjs.org/learn" className={styles.card}>
| </h1>
<p className={styles.description}>
Get started by editing{" "}
<code className={styles.code}>pages/index.tsx</code>
</p>
<div className={styles.grid}>
<a href="h | {
"filepath": "examples/with-vitest/pages/home/index.tsx",
"language": "tsx",
"file_size": 2363,
"cut_index": 563,
"middle_length": 229
} |
"./Header";
import "./page.css";
type User = {
name: string;
};
export const Page: React.FC = () => {
const [user, setUser] = React.useState<User>();
return (
<article>
<Header
user={user}
onLogin={() => setUser({ name: "Jane Doe" })}
onLogout={() => setUser(undefined)}
... | ocess starting with atomic components and ending with pages.
</p>
<p>
Render pages with mock data. This makes it easy to build and review
page states without needing to navigate to them in your app. Here are
so | with a{" "}
<a
href="https://componentdriven.org"
target="_blank"
rel="noopener noreferrer"
>
<strong>component-driven</strong>
</a>{" "}
pr | {
"filepath": "examples/with-storybook/stories/Page.tsx",
"language": "tsx",
"file_size": 2790,
"cut_index": 563,
"middle_length": 229
} |
ateContext, useState, useRef, useEffect } from "react";
import rosetta from "rosetta";
// import rosetta from 'rosetta/debug';
const i18n = rosetta();
export const defaultLanguage = "en";
export const languages = ["de", "en"];
export const contentLanguageMap = { de: "de-DE", en: "en-US" };
export const I18nContext =... | activeLocaleRef.current = l;
if (dict) {
i18n.set(l, dict);
}
// force rerender to update view
setTick((tick) => tick + 1);
},
};
// for initial SSR render
if (locale && firstRender.current === true) {
firs |
const [, setTick] = useState(0);
const firstRender = useRef(true);
const i18nWrapper = {
activeLocale: activeLocaleRef.current,
t: (...args) => i18n.t(...args),
locale: (l, dict) => {
i18n.locale(l);
| {
"filepath": "examples/with-i18n-rosetta/lib/i18n.js",
"language": "javascript",
"file_size": 1379,
"cut_index": 524,
"middle_length": 229
} |
. This is useful to test the logic for rewriting
* paths to multi zones to make sure that the logic is correct before deploying the application.
*/
import { type MatchResult, compile, match } from "path-to-regexp";
import nextConfig from "../next.config.js";
function getDestination(destination: string, pathMatch: M... | st BLOG_URL = "https://with-zones-blog.vercel.app";
describe("next.config.js test", () => {
describe("rewrites", () => {
let rewrites: Awaited<ReturnType<NonNullable<typeof nextConfig.rewrites>>>;
beforeAll(async () => {
process.env.BLOG_ | mpile(destinationUrl.pathname, {
encode: encodeURIComponent,
})(pathMatch.params);
return destinationUrl.toString();
}
return compile(destination, {
encode: encodeURIComponent,
})(pathMatch.params);
}
con | {
"filepath": "examples/with-zones/home/test/next-config.test.ts",
"language": "typescript",
"file_size": 2351,
"cut_index": 563,
"middle_length": 229
} |
bles } = {} as any,
preview: boolean,
) {
const url = preview
? `${process.env.NEXT_PUBLIC_WEBINY_PREVIEW_API_URL}`
: `${process.env.NEXT_PUBLIC_WEBINY_API_UR}`;
const res = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${proc... | slug
}
}
}
`,
{},
false,
);
return data?.listPosts.data;
}
export async function getAllPostsForHome(preview) {
const data = await fetchAPI(
`
query Posts {
listPosts {
data {
| ;
throw new Error("Failed to fetch API");
}
return json.data;
}
export async function getAllPostsWithSlug() {
const data = await fetchAPI(
`
query PostSlugs {
listPosts {
data {
| {
"filepath": "examples/cms-webiny/lib/api.ts",
"language": "typescript",
"file_size": 2260,
"cut_index": 563,
"middle_length": 229
} |
es";
import Link from "next/link";
import Image from "next/image";
export type TCoverImage = {
title: string;
src: string;
slug?: string;
height: number;
width: number;
};
const CoverImage: React.FC<TCoverImage> = ({
title,
src,
slug,
height,
width,
}) => {
const image = (
<Image
src={... | eight={height}
/>
);
return (
<div className="sm:mx-0">
{slug ? (
<Link href={`/posts/${slug}`} aria-label={title}>
{image}
</Link>
) : (
image
)}
</div>
);
};
export default CoverImage; | width}
h | {
"filepath": "examples/cms-webiny/components/cover-image.tsx",
"language": "tsx",
"file_size": 807,
"cut_index": 536,
"middle_length": 14
} |
Container from "./container";
import { EXAMPLE_PATH } from "../lib/constants";
export default function Footer() {
return (
<footer className="border-t bg-accent-1 border-accent-2">
<Container>
<div className="flex flex-col items-center py-28 lg:flex-row">
<h3 className="mb-10 text-4xl fo... | on-colors duration-200 bg-black border border-black hover:bg-white hover:text-black lg:px-8 lg:mb-0"
>
Read Documentation
</a>
<a
href={`https://github.com/vercel/next.js/tree/canary/examples/ | flex flex-col items-center justify-center lg:flex-row lg:pl-4 lg:w-1/2">
<a
href="https://nextjs.org/docs/basic-features/pages"
className="px-12 py-3 mx-3 mb-6 font-bold text-white transiti | {
"filepath": "examples/cms-webiny/components/footer.tsx",
"language": "tsx",
"file_size": 1210,
"cut_index": 518,
"middle_length": 229
} |
from "next/head";
import { CMS_NAME, HOME_OG_IMAGE_URL } from "../lib/constants";
export default function Meta() {
return (
<Head>
<link
rel="apple-touch-icon"
sizes="180x180"
href="/favicons/apple-touch-icon.png"
/>
<link
rel="icon"
type="image/png"
... | vicons/favicon.ico" />
<meta name="msapplication-TileColor" content="#000000" />
<meta name="msapplication-config" content="/favicons/browserconfig.xml" />
<meta name="theme-color" content="#000" />
<link rel="alternate" type="appli | />
<link rel="manifest" href="/favicons/site.webmanifest" />
<link
rel="mask-icon"
href="/favicons/safari-pinned-tab.svg"
color="#000000"
/>
<link rel="shortcut icon" href="/fa | {
"filepath": "examples/cms-webiny/components/meta.tsx",
"language": "tsx",
"file_size": 1262,
"cut_index": 524,
"middle_length": 229
} |
vatar";
import DateFormatter from "../components/date-formatter";
import CoverImage from "./cover-image";
import Link from "next/link";
export default function PostPreview({
title,
coverImage,
date,
excerpt,
author,
slug,
}) {
return (
<div>
<div className="mb-5">
<CoverImage
... | ne">
{title}
</Link>
</h3>
<div className="mb-4 text-lg">
<DateFormatter dateString={date} />
</div>
<p className="mb-4 text-lg leading-relaxed">{excerpt}</p>
<Avatar name={author.name} picture={autho | ink href={`/posts/${slug}`} className="hover:underli | {
"filepath": "examples/cms-webiny/components/post-preview.tsx",
"language": "tsx",
"file_size": 887,
"cut_index": 547,
"middle_length": 52
} |
iner from "../components/container";
import MoreStories from "../components/more-stories";
import HeroPost from "../components/hero-post";
import Intro from "../components/intro";
import Layout from "../components/layout";
import { getAllPostsForHome } from "../lib/api";
import Head from "next/head";
import { CMS_NAME ... | itle}
coverImage={heroPost.featuredImage}
createdOn={heroPost.date}
author={heroPost.author}
slug={heroPost.slug}
excerpt={heroPost.excerpt}
/>
)}
{morePo | w={preview}>
<Head>
<title>{`Next.js Blog Example with ${CMS_NAME}`}</title>
</Head>
<Container>
<Intro />
{heroPost && (
<HeroPost
title={heroPost.t | {
"filepath": "examples/cms-webiny/pages/index.tsx",
"language": "tsx",
"file_size": 1274,
"cut_index": 524,
"middle_length": 229
} |
om "next/font/google";
import styles from "./page.module.css";
import Content from "./message.mdx";
const inter = Inter({ subsets: ["latin"] });
export default function Home() {
return (
<main className={`${styles.main} ${inter.className}`}>
<div className={styles.description}>
<p>
Get s... | ogo"
className={styles.vercelLogo}
width={100}
height={24}
priority
/>
</a>
</div>
</div>
<div className={styles.center}>
<div>
<Content /> | medium=appdir-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
By{" "}
<Image
src="/vercel.svg"
alt="Vercel L | {
"filepath": "examples/mdx/app/page.tsx",
"language": "tsx",
"file_size": 2379,
"cut_index": 563,
"middle_length": 229
} |
m "couchbase";
const COUCHBASE_USER = process.env.COUCHBASE_USER;
const COUCHBASE_PASSWORD = process.env.COUCHBASE_PASSWORD;
const COUCHBASE_ENDPOINT = process.env.COUCHBASE_ENDPOINT || "localhost";
const COUCHBASE_BUCKET = process.env.COUCHBASE_BUCKET || "travel-sample";
let IS_CLOUD_INSTANCE = process.env.IS_CLOUD_I... | onentially
* during API Route usage.
*/
let cached = global.couchbase;
if (!cached) {
cached = global.couchbase = { conn: null };
}
async function createCouchbaseCluster() {
if (cached.conn) {
return cached.conn;
}
cached.conn = await couc | or(
"Please define the COUCHBASE_PASSWORD environment variable inside .env.local",
);
}
/**
* Global is used here to maintain a cached connection across hot reloads
* in development. This prevents connections growing exp | {
"filepath": "examples/with-couchbase/util/couchbase.js",
"language": "javascript",
"file_size": 1586,
"cut_index": 537,
"middle_length": 229
} |
xt.js on <span className="text-blue-600">Docker</span>!
</h1>
<p className="text-xl text-zinc-600 max-w-2xl mx-auto">
A production-ready example demonstrating how to Dockerize Next.js
applications using standalone mode.
</p>
</header>
<main className="container mx... | showcases Next.js standalone output mode, which
creates a minimal production build optimized for Docker
containers.
</p>
<ul className="list-disc list-inside space-y-2 text-zinc-600">
<li>Mu | p-8 shadow-lg border border-zinc-200">
<h2 className="text-2xl font-semibold mb-4 text-black">
Standalone Mode
</h2>
<p className="text-zinc-600 mb-4">
This example | {
"filepath": "examples/with-docker/app/page.tsx",
"language": "tsx",
"file_size": 10248,
"cut_index": 921,
"middle_length": 229
} |
reateOvermindSSR } from "overmind";
import { config } from "../overmind";
import Header from "../components/Header";
import Items from "../components/Items";
export async function getStaticProps() {
// If we want to produce some mutations we do so by instantiating
// an Overmind SSR instance, do whatever datafetch... | = [
{
id: 0,
title: "foo",
},
{
id: 1,
title: "bar",
},
];
return {
props: { mutations: overmind.hydrate() },
};
}
export default function IndexPage() {
return (
<div>
<Header />
<Items | nd.state.items | {
"filepath": "examples/with-overmind/pages/index.js",
"language": "javascript",
"file_size": 814,
"cut_index": 522,
"middle_length": 14
} |
import { useState, useEffect } from "react";
import PropTypes from "prop-types";
import Link from "next/link";
const About = (props) => {
const [loaded, setLoaded] = useState(false);
const { pageTransitionReadyToEnter } = props;
useEffect(() => {
const timeoutId = setTimeout(() => {
pageTransitionRead... | light">
Go back home
</Link>
</div>
);
};
About.propTypes = {
pageTransitionReadyToEnter: PropTypes.func,
};
About.defaultProps = {
pageTransitionReadyToEnter: () => {},
};
About.pageTransitionDelayEnter = true;
export default A | className="container bg-success page">
<h1>About us</h1>
<p>
Notice how a loading spinner showed up while my content was "loading"?
Pretty neat, huh?
</p>
<Link href="/" className="btn btn- | {
"filepath": "examples/with-next-page-transitions/pages/about.js",
"language": "javascript",
"file_size": 1003,
"cut_index": 512,
"middle_length": 229
} |
* @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {
colors: {
"accent-1": "#FAFAFA",
"accent-2": "#EAEAEA",
"accent-7": "#333",
success: "#0070f3",
... | "5xl": "2.5rem",
"6xl": "2.75rem",
"7xl": "4.5rem",
"8xl": "6.25rem",
},
boxShadow: {
small: "0 5px 10px rgba(0, 0, 0, 0.12)",
medium: "0 8px 30px rgba(0, 0, 0, 0.12)",
},
},
},
plugins: | tSize: {
| {
"filepath": "examples/cms-storyblok/tailwind.config.js",
"language": "javascript",
"file_size": 791,
"cut_index": 514,
"middle_length": 14
} |
Container from "./container";
import { EXAMPLE_PATH } from "@/lib/constants";
export default function Footer() {
return (
<footer className="bg-accent-1 border-t border-accent-2">
<Container>
<div className="py-28 flex flex-col lg:flex-row items-center">
<h3 className="text-4xl lg:text-5... | r border-black text-white font-bold py-3 px-12 lg:px-8 duration-200 transition-colors mb-6 lg:mb-0"
>
Read Documentation
</a>
<a
href={`https://github.com/vercel/next.js/tree/canary/examples/$ | lex flex-col lg:flex-row justify-center items-center lg:pl-4 lg:w-1/2">
<a
href="https://nextjs.org/docs/basic-features/pages"
className="mx-3 bg-black hover:bg-white hover:text-black borde | {
"filepath": "examples/cms-storyblok/components/footer.js",
"language": "javascript",
"file_size": 1209,
"cut_index": 518,
"middle_length": 229
} |
=> {
const props = { style: {}, className: "" };
if (block.data.textAlign) {
props.style["textAlign"] = block.data.textAlign;
}
if (block.data.className) {
props.className = block.data.className;
}
return (
<p
{...props}
className={classNames("rte-block-paragraph", props.className)}... | lock.data.level) {
case 1:
return (
<h1
{...props}
className={classNames(
props.className,
"rte-block-heading rte-block-heading--h1",
)}
dangerouslySetInnerHTML={{ __html: bl | => {
const props = { style: {}, className: "" };
if (block.data.textAlign) {
props.style["textAlign"] = block.data.textAlign;
}
if (block.data.className) {
props.className = block.data.className;
}
switch (b | {
"filepath": "examples/cms-webiny/lib/rich-text-renderer.tsx",
"language": "tsx",
"file_size": 4100,
"cut_index": 614,
"middle_length": 229
} |
Container from "./container";
import cn from "classnames";
import { EXAMPLE_PATH } from "../lib/constants";
export default function Alert({ preview }) {
return (
<div
className={cn("border-b", {
"bg-accent-7 border-accent-7 text-white": preview,
"bg-accent-1 border-accent-2": !preview,
... | </>
) : (
<>
The source code for this blog is{" "}
<a
href={`https://github.com/vercel/next.js/tree/canary/examples/${EXAMPLE_PATH}`}
className="underline transition-colors d | href="/api/exit-preview"
className="underline transition-colors duration-200 hover:text-cyan"
>
Click here
</a>{" "}
to exit preview mode.
| {
"filepath": "examples/cms-webiny/components/alert.tsx",
"language": "tsx",
"file_size": 1203,
"cut_index": 518,
"middle_length": 229
} |
URL } from "../lib/constants";
export default function Intro() {
return (
<section className="flex flex-col items-center mt-16 mb-16 md:flex-row md:justify-between md:mb-12">
<h1 className="text-6xl font-bold leading-tight tracking-tighter md:text-8xl md:pr-8">
Blog.
</h1>
<h4 className... |
Next.js
</a>{" "}
and{" "}
<a
href={CMS_URL}
className="underline transition-colors duration-200 hover:text-success"
>
{CMS_NAME}
</a>
.
</h4>
</section>
) | on-colors duration-200 hover:text-success"
> | {
"filepath": "examples/cms-webiny/components/intro.tsx",
"language": "tsx",
"file_size": 847,
"cut_index": 535,
"middle_length": 52
} |
) {
// Check the secret and next parameters
// This secret should only be known to this API route and the CMS
if (req.query.secret !== process.env.PREVIEW_API_SECRET || !req.query.slug) {
return res.status(401).json({ message: "Invalid token" });
}
// Fetch the headless CMS to check if the provided `slug... | ode by setting the cookie
res.setDraftMode({ enable: true });
// Redirect to the path from the fetched post
// We don't redirect to req.query.slug as that might lead to open redirect vulnerabilities
res.writeHead(307, { Location: `/posts/${post.da | message: "Invalid slug" });
}
// Enable Draft M | {
"filepath": "examples/cms-webiny/pages/api/preview.ts",
"language": "typescript",
"file_size": 943,
"cut_index": 606,
"middle_length": 52
} |
./styles/Home.module.css";
import { connectToDatabase } from "../util/couchbase";
export default function Home({ isConnected }) {
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={s... | Couchbase. Try refreshing the page, and
if this error persists check the <code>README.md</code> for
instructions.
</h2>
<em className={styles.center}>
Note: if the database was recently sta | ={`${styles.subtitle} ${styles.green}`}>
You are connected to Couchbase
</h2>
) : (
<>
<h2 className={`${styles.subtitle} ${styles.red}`}>
You are NOT connected to | {
"filepath": "examples/with-couchbase/pages/index.js",
"language": "javascript",
"file_size": 2533,
"cut_index": 563,
"middle_length": 229
} |
from "react";
import App from "next/app";
import { createOvermind, createOvermindSSR, rehydrate } from "overmind";
import { Provider } from "overmind-react";
import { config } from "../overmind";
class MyApp extends App {
// CLIENT: On initial route
// SERVER: On initial route
constructor(props) {
super(pro... | t want to run any additional logic here
this.overmind = createOvermindSSR(config);
rehydrate(this.overmind.state, mutations);
}
}
// CLIENT: After initial route, on page change
// SERVER: never
componentDidUpdate() {
// This run | angePage" action
this.overmind = createOvermind(config);
this.overmind.actions.changePage(mutations);
} else {
// On the server we rehydrate the mutations to an SSR instance of Overmind,
// as we do no | {
"filepath": "examples/with-overmind/pages/_app.js",
"language": "javascript",
"file_size": 1376,
"cut_index": 524,
"middle_length": 229
} |
} = {}) {
const res = await fetch("https://gapi.storyblok.com/v1/api", {
method: "POST",
headers: {
"Content-Type": "application/json",
Token: process.env.STORYBLOK_API_KEY,
Version: preview ? "draft" : "published",
},
body: JSON.stringify({
query,
variables,
}),
}... | },
);
return post;
}
export async function getAllPostsWithSlug() {
const data = await fetchAPI(`
{
PostItems {
items {
slug
}
}
}
`);
return data?.PostItems.items;
}
export async function getAll | ewPostBySlug(slug) {
const post = await fetchAPI(
`
query PostBySlug($slug: ID!) {
PostItem(id: $slug) {
slug
}
}
`,
{
preview: true,
variables: {
slug: `posts/${slug}`,
},
| {
"filepath": "examples/cms-storyblok/lib/api.js",
"language": "javascript",
"file_size": 2465,
"cut_index": 563,
"middle_length": 229
} |
ad";
import Image from "next/image";
import styles from "../styles/Home.module.css";
import dynamic from "next/dynamic";
import { Avatar, Pagination } from "@nextui-org/react";
const CustomCheckbox = dynamic(() => import("../components/Checkbox"));
const CustomTable = dynamic(() => import("../components/Table"));
cons... | or="gradient" textColor={"white"} size={"xl"} />
</h1>
<h1 className={styles.title}>
Welcome to use <a href="https://nextui.org/">NextUI!</a>
</h1>
{/* checkout */}
<h2>Checkbox:</h2>
<CustomCheckbo | le</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<h1>
<Avatar text="Hi" col | {
"filepath": "examples/with-next-ui/pages/index.tsx",
"language": "tsx",
"file_size": 1793,
"cut_index": 537,
"middle_length": 229
} |
Avatar from "../components/avatar";
import DateFormatter from "../components/date-formatter";
import CoverImage from "../components/cover-image";
import Link from "next/link";
export default function HeroPost({
title,
coverImage,
createdOn,
excerpt,
author,
slug,
}) {
return (
<section>
<div c... | ne">
{title}
</Link>
</h3>
<div className="mb-4 text-lg md:mb-0">
<DateFormatter dateString={createdOn} />
</div>
</div>
<div>
<p className="mb-4 text-lg leading- | <div className="mb-20 md:grid md:grid-cols-2 md:gap-x-16 lg:gap-x-8 md:mb-28">
<div>
<h3 className="mb-4 text-4xl leading-tight lg:text-6xl">
<Link href={`/posts/${slug}`} className="hover:underli | {
"filepath": "examples/cms-webiny/components/hero-post.tsx",
"language": "tsx",
"file_size": 1141,
"cut_index": 518,
"middle_length": 229
} |
orPage from "next/error";
import Container from "../../components/container";
import PostBody from "../../components/post-body";
import Header from "../../components/header";
import PostHeader from "../../components/post-header";
import MoreStories from "../../components/more-stories";
import SectionSeparator from "../... | urn <ErrorPage statusCode={404} />;
}
return (
<Layout preview={preview}>
<Container>
<Header />
{router.isFallback ? (
<PostTitle>Loading…</PostTitle>
) : (
<>
<article className="mb-32 | -title";
import Head from "next/head";
import { CMS_NAME } from "../../lib/constants";
export default function Post({ post, morePosts, preview }) {
const router = useRouter();
if (!router.isFallback && !post?.slug) {
ret | {
"filepath": "examples/cms-webiny/pages/posts/[slug].tsx",
"language": "tsx",
"file_size": 2327,
"cut_index": 563,
"middle_length": 229
} |
ad";
import { PageTransition } from "next-page-transitions";
import Loader from "../components/Loader";
const TIMEOUT = 400;
function MyApp({ Component, pageProps }) {
return (
<>
<Head>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
</Head>
<PageTransition
... | form: translate3d(0, 20px, 0);
}
.page-transition-enter-active {
opacity: 1;
transform: translate3d(0, 0, 0);
transition:
opacity ${TIMEOUT}ms,
transform ${TIMEOUT}ms;
}
| t: 0,
}}
loadingClassNames="loading-indicator"
>
<Component {...pageProps} />
</PageTransition>
<style jsx global>{`
.page-transition-enter {
opacity: 0;
trans | {
"filepath": "examples/with-next-page-transitions/pages/_app.js",
"language": "javascript",
"file_size": 1510,
"cut_index": 537,
"middle_length": 229
} |
nk";
import camelcaseKeys from "camelcase-keys";
import PostsList from "@/components/blog/posts-list";
import { getCategories, searchPosts } from "@/lib/api";
import CategoriesWidget from "@/components/blog/categories-widget";
import SearchWidget from "@/components/blog/search-widget";
export default function Searc... | <Link href="/">Home</Link>
</li>
<li>
<Link href="/blog">Blog</Link>
</li>
<li>Search: "{query}"</li>
</ul>
</div>
| enter">
<div className="col-12">
<div className="section-title text-center">
<h2>Search Results</h2>
<ul className="breadcrumb-nav">
<li>
| {
"filepath": "examples/cms-buttercms/pages/blog/search.js",
"language": "javascript",
"file_size": 1736,
"cut_index": 537,
"middle_length": 229
} |
Container from "./container";
import cn from "classnames";
import { EXAMPLE_PATH } from "@/lib/constants";
export default function Alert({ preview }) {
return (
<div
className={cn("border-b", {
"bg-accent-7 border-accent-7 text-white": preview,
"bg-accent-1 border-accent-2": !preview,
... | </>
) : (
<>
The source code for this blog is{" "}
<a
href={`https://github.com/vercel/next.js/tree/canary/examples/${EXAMPLE_PATH}`}
className="underline hover:text-succes | href="/api/exit-preview"
className="underline hover:text-cyan duration-200 transition-colors"
>
Click here
</a>{" "}
to exit preview mode.
| {
"filepath": "examples/cms-storyblok/components/alert.js",
"language": "javascript",
"file_size": 1205,
"cut_index": 518,
"middle_length": 229
} |
vatar";
import DateFormatter from "../components/date-formatter";
import CoverImage from "../components/cover-image";
import PostTitle from "../components/post-title";
export default function PostHeader({ title, coverImage, date, author }) {
return (
<>
<PostTitle>{title}</PostTitle>
<div className="... | <div className="max-w-2xl mx-auto">
<div className="block mb-6 md:hidden">
<Avatar name={author.name} picture={author.picture} />
</div>
<div className="mb-6 text-lg">
<DateFormatter dateString={date} />
| rImage} height={620} width={1240} />
</div>
| {
"filepath": "examples/cms-webiny/components/post-header.tsx",
"language": "tsx",
"file_size": 894,
"cut_index": 547,
"middle_length": 52
} |
m "../components/avatar";
import Date from "../components/date";
import CoverImage from "../components/cover-image";
import PostTitle from "../components/post-title";
export default function PostHeader({ title, coverImage, date, author }) {
return (
<>
<PostTitle>{title}</PostTitle>
<div className="h... | "max-w-2xl mx-auto">
<div className="block md:hidden mb-6">
<Avatar name={author.name} picture={author.content.picture} />
</div>
<div className="mb-6 text-lg">
<Date dateString={date} />
</div>
</d | l={coverImage} />
</div>
<div className= | {
"filepath": "examples/cms-storyblok/components/post-header.js",
"language": "javascript",
"file_size": 856,
"cut_index": 529,
"middle_length": 52
} |
iner from "@/components/container";
import MoreStories from "@/components/more-stories";
import HeroPost from "@/components/hero-post";
import Intro from "@/components/intro";
import Layout from "@/components/layout";
import { getAllPostsForHome } from "@/lib/api";
import Head from "next/head";
import { CMS_NAME } from... | title}
coverImage={heroPost.content.image}
date={heroPost.first_published_at || heroPost.published_at}
author={heroPost.content.author}
slug={heroPost.slug}
excerpt={heroPost.content.int | iew}>
<Head>
<title>{`Next.js Blog Example with ${CMS_NAME}`}</title>
</Head>
<Container>
<Intro />
{heroPost && (
<HeroPost
title={heroPost.content. | {
"filepath": "examples/cms-storyblok/pages/index.js",
"language": "javascript",
"file_size": 1337,
"cut_index": 524,
"middle_length": 229
} |
t React, { ReactElement, AnchorHTMLAttributes } from "react";
import Link, { LinkProps } from "next/link";
export interface LinkUnstyledProps
extends Omit<LinkProps, "children" | "onError">,
Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "onError" | "href"> {}
export default function LinkUnstyled({
as,
href,... | ps} href={href} rel="noopener noreferrer">
{children}
</a>
);
}
return (
<Link
shallow={shallow}
scroll={scroll}
replace={replace}
href={href}
as={as}
{...props}
>
{children}
</Li | <a {...pro | {
"filepath": "examples/with-react-md-typescript/components/LinkUnstyled.tsx",
"language": "tsx",
"file_size": 798,
"cut_index": 517,
"middle_length": 14
} |
{ Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
... | monstrating how to Dockerize Next.js applications using standalone mode.",
type: "website",
},
twitter: {
card: "summary_large_image",
title: "Next.js Docker Example - Standalone Mode",
description:
"A production-ready example dem | "Next.js",
"Docker",
"standalone mode",
"containerization",
"React",
"Node.js",
],
openGraph: {
title: "Next.js Docker Example - Standalone Mode",
description:
"A production-ready example de | {
"filepath": "examples/with-docker/app/layout.tsx",
"language": "tsx",
"file_size": 1372,
"cut_index": 524,
"middle_length": 229
} |
t {
LayoutNavigationTree,
LayoutNavigationItem,
HomeSVGIcon,
TvSVGIcon,
} from "react-md";
/**
* Note: The `parentId` **must** be defaulted to `null` for the navigation tree
* to render correctly since this uses the @react-md/tree package behind the
* scenes. Each item that has a `parentId` set to `null` wi... | hname,
parentId,
href: pathname,
children,
leftAddon,
};
}
const navItems: LayoutNavigationTree = {
"/": createRoute("/", "Home", <HomeSVGIcon />),
"/route-1": createRoute("/route-1", "Route 1", <TvSVGIcon />),
};
export default nav | ): LayoutNavigationItem {
return {
itemId: pat | {
"filepath": "examples/with-react-md-typescript/components/Layout/navItems.tsx",
"language": "tsx",
"file_size": 874,
"cut_index": 559,
"middle_length": 52
} |
from "next/head";
import { CMS_NAME, HOME_OG_IMAGE_URL } from "@/lib/constants";
export default function Meta() {
return (
<Head>
<link
rel="apple-touch-icon"
sizes="180x180"
href="/favicon/apple-touch-icon.png"
/>
<link
rel="icon"
type="image/png"
... | favicon.ico" />
<meta name="msapplication-TileColor" content="#000000" />
<meta name="msapplication-config" content="/favicon/browserconfig.xml" />
<meta name="theme-color" content="#000" />
<link rel="alternate" type="application/r | />
<link rel="manifest" href="/favicon/site.webmanifest" />
<link
rel="mask-icon"
href="/favicon/safari-pinned-tab.svg"
color="#000000"
/>
<link rel="shortcut icon" href="/favicon/ | {
"filepath": "examples/cms-storyblok/components/meta.js",
"language": "javascript",
"file_size": 1254,
"cut_index": 524,
"middle_length": 229
} |
c function preview(req, res) {
// Check the secret and next parameters
// This secret should only be known to this API route and the CMS
if (
req.query.secret !== process.env.STORYBLOK_PREVIEW_SECRET ||
!req.query.slug
) {
return res.status(401).json({ message: "Invalid token" });
}
// Fetch th... | Invalid slug" });
}
// Enable Draft Mode by setting the cookie
res.setDraftMode({ enable: true });
// Redirect to the path from the fetched post
// We don't redirect to req.query.slug as that might lead to open redirect vulnerabilities
res.wr | post) {
return res.status(401).json({ message: " | {
"filepath": "examples/cms-storyblok/pages/api/preview.js",
"language": "javascript",
"file_size": 967,
"cut_index": 582,
"middle_length": 52
} |
URL } from "@/lib/constants";
export default function Intro() {
return (
<section className="flex-col md:flex-row flex items-center md:justify-between mt-16 mb-16 md:mb-12">
<h1 className="text-6xl md:text-8xl font-bold tracking-tighter leading-tight md:pr-8">
Blog.
</h1>
<h4 className=... | Next.js
</a>{" "}
and{" "}
<a
href={CMS_URL}
className="underline hover:text-success duration-200 transition-colors"
>
{CMS_NAME}
</a>
.
</h4>
</section>
); | t-success duration-200 transition-colors"
>
| {
"filepath": "examples/cms-storyblok/components/intro.js",
"language": "javascript",
"file_size": 846,
"cut_index": 535,
"middle_length": 52
} |
orPage from "next/error";
import Container from "@/components/container";
import PostBody from "@/components/post-body";
import MoreStories from "@/components/more-stories";
import Header from "@/components/header";
import PostHeader from "@/components/post-header";
import SectionSeparator from "@/components/section-se... | ter.isFallback && !post?.slug) {
return <ErrorPage statusCode={404} />;
}
return (
<Layout preview={preview}>
<Container>
<Header />
{router.isFallback ? (
<PostTitle>Loading…</PostTitle>
) : (
| t/head";
import { CMS_NAME } from "@/lib/constants";
import RichTextResolver from "storyblok-js-client/dist/richTextResolver";
export default function Post({ post, morePosts, preview }) {
const router = useRouter();
if (!rou | {
"filepath": "examples/cms-storyblok/pages/posts/[slug].js",
"language": "javascript",
"file_size": 2396,
"cut_index": 563,
"middle_length": 229
} |
ent, ReactNode } from "react";
import { useRouter } from "next/router";
import {
Layout as RMDLayout,
Configuration,
ConfigurableIcons,
useLayoutNavigation,
ArrowDropDownSVGIcon,
CheckBoxSVGIcon,
FileDownloadSVGIcon,
KeyboardArrowDownSVGIcon,
KeyboardArrowLeftSVGIcon,
KeyboardArrowRightSVGIcon,
Me... | yboardArrowDownSVGIcon />,
forward: <KeyboardArrowRightSVGIcon />,
menu: <MenuSVGIcon />,
notification: <NotificationsSVGIcon />,
radio: <RadioButtonCheckedSVGIcon />,
password: <RemoveRedEyeSVGIcon />,
selected: <CheckSVGIcon />,
sort: <Arro | ort navItems from "./navItems";
const icons: ConfigurableIcons = {
back: <KeyboardArrowLeftSVGIcon />,
checkbox: <CheckBoxSVGIcon />,
dropdown: <ArrowDropDownSVGIcon />,
download: <FileDownloadSVGIcon />,
expander: <Ke | {
"filepath": "examples/with-react-md-typescript/components/Layout/Layout.tsx",
"language": "tsx",
"file_size": 1778,
"cut_index": 537,
"middle_length": 229
} |
;
export const MAX_AGE = 60 * 60 * 8; // 8 hours
export function setTokenCookie(res, token) {
const cookie = serialize(TOKEN_NAME, token, {
maxAge: MAX_AGE,
expires: new Date(Date.now() + MAX_AGE * 1000),
httpOnly: true,
secure: process.env.NODE_ENV === "production",
path: "/",
sameSite: "la... | ies(req) {
// For API Routes we don't need to parse the cookies.
if (req.cookies) return req.cookies;
// For pages we do need to parse the cookies.
const cookie = req.headers?.cookie;
return parse(cookie || "");
}
export function getTokenCookie | ("Set-Cookie", cookie);
}
export function parseCook | {
"filepath": "examples/with-magic/lib/auth-cookies.js",
"language": "javascript",
"file_size": 967,
"cut_index": 582,
"middle_length": 52
} |
import Router from "next/router";
import useSWR from "swr";
const fetcher = (url) =>
fetch(url)
.then((r) => r.json())
.then((data) => {
return { user: data?.user || null };
});
export function useUser({ redirectTo, redirectIfFound } = {}) {
const { data, error } = useSWR("/api/user", fetcher);
... | rectTo && !redirectIfFound && !hasUser) ||
// If redirectIfFound is also set, redirect if the user was found
(redirectIfFound && hasUser)
) {
Router.push(redirectTo);
}
}, [redirectTo, redirectIfFound, finished, hasUser]);
re | set, redirect if the user was not found.
(redi | {
"filepath": "examples/with-magic/lib/hooks.js",
"language": "javascript",
"file_size": 883,
"cut_index": 547,
"middle_length": 52
} |
Link from "next/link";
import { useUser } from "../lib/hooks";
const Header = () => {
const user = useUser();
return (
<header>
<nav>
<ul>
<li>
<Link href="/">Home</Link>
</li>
{user ? (
<>
<li>
<Link href="/pro... | ul {
display: flex;
list-style: none;
margin-left: 0;
padding-left: 0;
}
li {
margin-right: 1rem;
}
li:first-child {
margin-left: auto;
}
a {
| <Link href="/login">Login</Link>
</li>
)}
</ul>
</nav>
<style jsx>{`
nav {
max-width: 42rem;
margin: 0 auto;
padding: 0.2rem 1.25rem;
}
| {
"filepath": "examples/with-magic/components/header.js",
"language": "javascript",
"file_size": 1213,
"cut_index": 518,
"middle_length": 229
} |
{ useUser } from "../lib/hooks";
import Layout from "../components/layout";
const Home = () => {
const user = useUser();
return (
<Layout>
<h1>Magic Example</h1>
<p>Steps to test this authentication example:</p>
<ol>
<li>Click Login and enter an email.</li>
<li>
... | k"
rel="noopener noreferrer"
>
documentation
</a>
.
</p>
{user && (
<>
<p>Currently logged in as:</p>
<pre>{JSON.stringify(user, null, 2)}</pre>
</>
)}
| go to Profile again. You'll get redirected to
Login.
</li>
</ol>
<p>
To learn more about Magic, visit their{" "}
<a
href="https://docs.magic.link/"
target="_blan | {
"filepath": "examples/with-magic/pages/index.js",
"language": "javascript",
"file_size": 1226,
"cut_index": 518,
"middle_length": 229
} |
"react";
import Router from "next/router";
import { useUser } from "../lib/hooks";
import Layout from "../components/layout";
import Form from "../components/form";
import { Magic } from "magic-sdk";
const Login = () => {
useUser({ redirectTo: "/", redirectIfFound: true });
const [errorMsg, setErrorMsg] = useSta... | "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + didToken,
},
body: JSON.stringify(body),
});
if (res.status === 200) {
Router.push("/");
} else {
| nst magic = new Magic(process.env.NEXT_PUBLIC_MAGIC_PUBLISHABLE_KEY);
const didToken = await magic.auth.loginWithMagicLink({
email: body.email,
});
const res = await fetch("/api/login", {
method: | {
"filepath": "examples/with-magic/pages/login.js",
"language": "javascript",
"file_size": 1589,
"cut_index": 537,
"middle_length": 229
} |
ort type { GetStaticPropsContext } from "next";
import { FormattedMessage, FormattedNumber, useIntl } from "react-intl";
import loadIntlMessages from "../helper/loadIntlMessages";
import Layout from "../components/Layout";
export async function getStaticProps({
defaultLocale,
locale,
}: GetStaticPropsContext) {
... | eact Intl with Next.js",
description: "Index Page: Meta Description",
})}
>
<p>
<FormattedMessage
defaultMessage="Hello, World!"
description="Index Page: Content"
/>
</p>
<p>
< | <Layout
title={intl.formatMessage({
defaultMessage: "Home",
description: "Index Page: document title",
})}
description={intl.formatMessage({
defaultMessage: "An example app integrating R | {
"filepath": "examples/with-react-intl/pages/index.tsx",
"language": "tsx",
"file_size": 1064,
"cut_index": 515,
"middle_length": 229
} |
xt.js on <span className="text-blue-600">Docker</span>!
</h1>
<p className="text-xl text-zinc-600 max-w-2xl mx-auto">
A production-ready example demonstrating how to Dockerize Next.js
applications using static export mode with Nginx.
</p>
</header>
<main className... | This example showcases Next.js static export mode, which creates a
fully static site served by Nginx. Perfect for blogs, docs, and
marketing sites.
</p>
<ul className="list-disc list-inside space-y-2 | te rounded-lg p-8 shadow-lg border border-zinc-200">
<h2 className="text-2xl font-semibold mb-4 text-black">
Static Export Mode
</h2>
<p className="text-zinc-600 mb-4">
| {
"filepath": "examples/with-docker-export-output/app/page.tsx",
"language": "tsx",
"file_size": 10404,
"cut_index": 921,
"middle_length": 229
} |
g} */
module.exports = {
reactStrictMode: true,
async rewrites() {
return [
{
source: "/",
destination: "/landing-page/landing-page-with-components",
},
];
},
redirects() {
const sourcesRequiringAuthToken = [
"/",
"/landing-page/:slug*",
"/blog/:path*",
... | source) => ({
source: source,
destination: "/missing-token",
permanent: false,
}));
},
images: {
remotePatterns: [
{
protocol: "https",
hostname: "cdn.buttercms.com",
port: "",
| },
]
: sourcesRequiringAuthToken.map(( | {
"filepath": "examples/cms-buttercms/next.config.js",
"language": "javascript",
"file_size": 912,
"cut_index": 547,
"middle_length": 52
} |
Effect, useState, useRef } from "react";
import Image from "next/image";
import MainMenu from "./main-menu/main-menu";
export default function HeaderSection({ mainMenu }) {
const [isNavbarSticky, setIsNavbarSticky] = useState(false);
const navbarAreaEl = useRef(null);
function fixNavBar() {
if (navbarArea... | >
<div className="container">
<div className="row align-items-center">
<div className="col-lg-12">
<nav className="navbar navbar-expand-lg">
<a className="navbar-brand" href="https://buttercms.com |
window.removeEventListener("scroll", fixNavBar);
};
}, []);
return (
<header className="header">
<div
ref={navbarAreaEl}
className={`navbar-area ${isNavbarSticky ? "sticky" : ""}`}
| {
"filepath": "examples/cms-buttercms/components/header-section.js",
"language": "javascript",
"file_size": 1407,
"cut_index": 524,
"middle_length": 229
} |
from "next/link";
import PostPreviewCondensed from "./post-preview-condensed";
export default function Blog({ posts }) {
return (
<section id="blog" className="blog-section">
<div className="container">
<div className="row justify-content-center">
<div className="col-lg-6 col-md-10">
... | </p>
</div>
</div>
</div>
<div className="row justify-content-center">
{posts.map((post) => (
<PostPreviewCondensed
key={post.slug}
title={post.title}
| simple to launch a new company blog.
</p>
<p>
<Link href={`/blog`} className="main-btn btn-hover mt-5">
View All Blog Posts
</Link>
| {
"filepath": "examples/cms-buttercms/components/blog/blog.js",
"language": "javascript",
"file_size": 1314,
"cut_index": 524,
"middle_length": 229
} |
mage";
import Link from "next/link";
import HumanDate from "@/components/human-date";
import AuthorCard from "@/components/author-card";
export default function PostsPreview({
title,
coverImage,
coverImageAlt,
date,
author,
tags,
excerpt,
slug,
}) {
return (
<div className="col-12 col-lg-6">
... | <HumanDate dateString={date} />
</li>
{tags.map((tag) => (
<li key={tag.slug}>
<Link href={`/blog/tag/${tag.slug}`}>
<i className="lni lni-tag"></i> {tag.name}
</Link> | </h2>
<ul className="blog-roll-card-meta-info">
<li>
<AuthorCard author={author} />
</li>
<li>
<i className="lni lni-calendar"></i>{" "}
| {
"filepath": "examples/cms-buttercms/components/blog/post-preview.js",
"language": "javascript",
"file_size": 1702,
"cut_index": 537,
"middle_length": 229
} |
Image from "next/image";
export default function Hero({
headline,
subheadline,
image,
buttonLabel,
buttonUrl,
scrollAnchorId,
}) {
return (
<section id={scrollAnchorId} className="hero-section">
<div className="container">
<div className="row align-items-center">
<div classNa... | col-xxl-6 col-xl-6 col-lg-6">
<div className="hero-image text-center text-lg-end">
<Image
src={image}
layout="responsive"
height="400px"
width="400px"
| main-btn btn-hover">
{buttonLabel}
</a>
<a href="https://buttercms.com/join/">Need an account?</a>
</div>
</div>
{image && (
<div className=" | {
"filepath": "examples/cms-buttercms/components/landing-page-sections/hero.js",
"language": "javascript",
"file_size": 1147,
"cut_index": 518,
"middle_length": 229
} |
Effect } from "react";
import { tns } from "tiny-slider";
import Testimonial from "./testimonial";
export default function Testimonials({
headline,
testimonial: testimonials,
scrollAnchorId,
}) {
useEffect(() => {
tns({
container: ".testimonial-active",
autoplay: true,
autoplayTimeout: ... | ner">
<div className="row justify-content-center">
<div className="col-xl-7 col-lg-9">
<div className="testimonial-active-wrapper">
<div className="section-title text-center">
<h2 className="mb-20 | ni lni-chevron-left"></i>',
'<i class="lni lni-chevron-right"></i>',
],
items: 1,
});
});
return (
<section id={scrollAnchorId} className="testimonial-section mt-100">
<div className="contai | {
"filepath": "examples/cms-buttercms/components/landing-page-sections/testimonials.js",
"language": "javascript",
"file_size": 1507,
"cut_index": 524,
"middle_length": 229
} |
mage";
export default function TwoColumnWithImage({
headline,
subheadline,
buttonLabel,
buttonUrl,
image,
imagePosition,
scrollAnchorId,
}) {
return (
<section id={scrollAnchorId} className="cta-section">
<div className="container">
<div className="row">
{image && imagePosit... | -lg-6">
<div className="cta-content-wrapper">
<div className="section-title">
<h2 className="mb-20">{headline}</h2>
<div dangerouslySetInnerHTML={{ __html: subheadline }} />
</div>
| layout="responsive"
height="400px"
width="600px"
alt=""
/>
</div>
</div>
)}
<div className="col | {
"filepath": "examples/cms-buttercms/components/landing-page-sections/two-column-with-image.js",
"language": "javascript",
"file_size": 1693,
"cut_index": 537,
"middle_length": 229
} |
t Router from "next/router";
import App from "next/app";
import Head from "next/head";
import { useRouter } from "next/router";
import { getMainMenu } from "@/lib/api";
import FooterSection from "@/components/footer-section";
import HeaderSection from "@/components/header-section";
import ScrollToButtonButton from "@... | useEffect(() => {
import("bootstrap/dist/js/bootstrap.js");
const showLoader = () => {
setIsLoading(true);
};
const removeLoader = () => {
setIsLoading(false);
};
Router.events.on("routeChangeStart", showLoader);
| ;
import "@/css/main.css";
function MyApp({ Component, pageProps, mainMenu }) {
const [isLoading, setIsLoading] = useState(false);
const router = useRouter();
const authToken = process.env.NEXT_PUBLIC_BUTTER_CMS_API_KEY;
| {
"filepath": "examples/cms-buttercms/pages/_app.js",
"language": "javascript",
"file_size": 2757,
"cut_index": 563,
"middle_length": 229
} |
"@hapi/iron";
import { MAX_AGE, setTokenCookie, getTokenCookie } from "./auth-cookies";
const TOKEN_SECRET = process.env.TOKEN_SECRET;
export async function setLoginSession(res, session) {
const createdAt = Date.now();
// Create a session object with a max age that we can validate later
const obj = { ...session... | st session = await Iron.unseal(token, TOKEN_SECRET, Iron.defaults);
const expiresAt = session.createdAt + session.maxAge * 1000;
// Validate the expiration date of the session
if (Date.now() > expiresAt) {
throw new Error("Session expired");
} | = getTokenCookie(req);
if (!token) return;
con | {
"filepath": "examples/with-magic/lib/auth.js",
"language": "javascript",
"file_size": 859,
"cut_index": 529,
"middle_length": 52
} |
from "next/head";
import Header from "./header";
const Layout = (props) => (
<>
<Head>
<title>Magic</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<Header />
<main>
<div className="container">{props.children}</div>
</main>
<footer>
<a
href="https://... | ont-family:
-apple-system,
BlinkMacSystemFont,
"Segoe UI",
Roboto,
"Helvetica Neue",
Arial,
Noto Sans,
sans-serif,
"Apple Color Emoji",
"Segoe UI Emoji",
| vercel.svg" alt="Vercel Logo" />
</a>
</footer>
<style jsx global>{`
*,
*::before,
*::after {
box-sizing: border-box;
}
body {
margin: 0;
color: #333;
f | {
"filepath": "examples/with-magic/components/layout.js",
"language": "javascript",
"file_size": 1421,
"cut_index": 524,
"middle_length": 229
} |
port { ReactNode } from "react";
import { useIntl } from "react-intl";
import Head from "next/head";
import Nav from "./Nav";
interface LayoutProps {
title?: string;
description?: string;
children: ReactNode;
}
export default function Layout({ title, description, children }: LayoutProps) {
const intl = useInt... | tion: "Default document description",
});
return (
<>
<Head>
<title>{title}</title>
<meta name="description" content={description} />
</Head>
<header>
<Nav />
</header>
{children}
</>
);
| sage: "This page is powered by Next.js",
descrip | {
"filepath": "examples/with-react-intl/components/Layout.tsx",
"language": "tsx",
"file_size": 824,
"cut_index": 514,
"middle_length": 52
} |
{ Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
... | ne & Static Export",
description:
"A production-ready example demonstrating how to Dockerize Next.js applications using standalone mode and static export.",
type: "website",
},
twitter: {
card: "summary_large_image",
title: "Next. | c export.",
keywords: [
"Next.js",
"Docker",
"standalone mode",
"static export",
"containerization",
"React",
"Node.js",
"Nginx",
],
openGraph: {
title: "Next.js Docker Example - Standalo | {
"filepath": "examples/with-docker-export-output/app/layout.tsx",
"language": "tsx",
"file_size": 1493,
"cut_index": 524,
"middle_length": 229
} |
ction FooterSection({ mainMenu }) {
const links = mainMenu.map((link) => ({
...link,
url: link.url[0] === "#" ? `/${link.url}` : link.url,
}));
return (
<footer className="footer pt-120">
<div className="container">
<div className="row">
<div className="col-xl-3 col-lg-4 col-m... | assName="desc">
ButterCMS is your content backend. Build better with Butter.
</p>
<ul className="social-links">
<li>
<a href="#0">
<i className="lni lni-faceb | idth={200}
height={50}
src="https://cdn.buttercms.com/PBral0NQGmmFzV0uG7Q6"
alt="logo"
/>
</a>
</div>
<p cl | {
"filepath": "examples/cms-buttercms/components/footer-section.js",
"language": "javascript",
"file_size": 2476,
"cut_index": 563,
"middle_length": 229
} |
t Image from "next/image";
export default function PostPreviewCondensed({
title,
coverImage,
coverImageAlt,
excerpt,
slug,
}) {
return (
<div className="col-lg-4 col-md-8 col-sm-10">
<div className="single-blog">
{coverImage && (
<div className="blog-header">
<Image
... | <Link href={`/blog/${slug}`}>{title}</Link>
</h5>
<p>{excerpt}</p>
</div>
<div className="blog-footer">
<Link href={`/blog/${slug}`} className="main-btn btn-hover">
Read More
< | blog-body">
<h5 className="package-name">
| {
"filepath": "examples/cms-buttercms/components/blog/post-preview-condensed.js",
"language": "javascript",
"file_size": 908,
"cut_index": 547,
"middle_length": 52
} |
ic from "next/dynamic";
import camelcaseKeys from "camelcase-keys";
import Preloader from "@/components/preloader";
import MissingSection from "./missing-section";
export default function LandingPageSection({ type, sectionData }) {
const sectionsComponentPaths = () => ({
hero: dynamic(
() =>
impo... | import("@/components/landing-page-sections/features").catch(
() => () => MissingSection,
),
{
loading: Preloader,
},
),
testimonials: dynamic(
() =>
import("@/components/landing-page-section | () =>
import(
"@/components/landing-page-sections/two-column-with-image"
).catch(() => () => MissingSection),
{
loading: Preloader,
},
),
features: dynamic(
() =>
| {
"filepath": "examples/cms-buttercms/components/landing-page-sections/landing-page-section.js",
"language": "javascript",
"file_size": 1295,
"cut_index": 524,
"middle_length": 229
} |
nk";
import camelcaseKeys from "camelcase-keys";
import PostsList from "@/components/blog/posts-list";
import { getPostsData, getCategories } from "@/lib/api";
import CategoriesWidget from "@/components/blog/categories-widget";
import SearchWidget from "@/components/blog/search-widget";
export default function Blog... | nk href="/">Home</Link>
</li>
<li>All blog posts</li>
</ul>
</div>
</div>
</div>
</div>
</section>
<section className="blog-posts">
<div cl | <div className="col-12">
<div className="section-title text-center">
<h2>All Blog Posts</h2>
<ul className="breadcrumb-nav">
<li>
<Li | {
"filepath": "examples/cms-buttercms/pages/blog.js",
"language": "javascript",
"file_size": 1875,
"cut_index": 537,
"middle_length": 229
} |
Form = ({ errorMessage, onSubmit }) => (
<form onSubmit={onSubmit}>
<label>
<span>Email</span>
<input type="email" name="email" required />
</label>
<div className="submit">
<button type="submit">Sign Up / Login</button>
</div>
{errorMessage && <p className="error">{errorMessag... | ontent: space-between;
}
.submit > a {
text-decoration: none;
}
.submit > button {
padding: 0.5rem 1rem;
cursor: pointer;
background: #fff;
border: 1px solid #ccc;
border-radius: 4px;
| ing: 8px;
margin: 0.3rem 0 1rem;
border: 1px solid #ccc;
border-radius: 4px;
}
.submit {
display: flex;
justify-content: flex-end;
align-items: center;
justify-c | {
"filepath": "examples/with-magic/components/form.js",
"language": "javascript",
"file_size": 1199,
"cut_index": 518,
"middle_length": 229
} |
from "camelcase-keys";
import PostsList from "@/components/blog/posts-list";
import { getPostsData, getCategories } from "@/lib/api";
import CategoriesWidget from "@/components/blog/categories-widget";
import SearchWidget from "@/components/blog/search-widget";
export default function Category({ posts, categories, ... | "/">Home</Link>
</li>
<li>
<Link href="/blog">Blog</Link>
</li>
<li>Category: {slug}</li>
</ul>
</div>
</div>
</ | className="col-12">
<div className="section-title text-center">
<h2>Blog Posts by Category</h2>
<ul className="breadcrumb-nav">
<li>
<Link href= | {
"filepath": "examples/cms-buttercms/pages/blog/category/[slug].js",
"language": "javascript",
"file_size": 2373,
"cut_index": 563,
"middle_length": 229
} |
from "next/router";
import ErrorPage from "next/error";
import camelcaseKeys from "camelcase-keys";
import { getLandingPage, getLandingPages, getPostsData } from "@/lib/api";
import LandingPageSection from "@/components/landing-page-sections/landing-page-section";
import Blog from "@/components/blog/blog";
import Pr... | e>
<meta name="description" content={page.fields.seo.description} />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
rel="shortcut icon"
type="image/x-icon"
href="https://bu | (!page) {
return <ErrorPage statusCode={404} />;
}
return (
<>
<Head>
<meta charSet="utf-8" />
<meta httpEquiv="x-ua-compatible" content="ie=edge" />
<title>{page.fields.seo.title}</titl | {
"filepath": "examples/cms-buttercms/pages/landing-page/[slug].js",
"language": "javascript",
"file_size": 2235,
"cut_index": 563,
"middle_length": 229
} |
**
* As this file is reused in several other files, try to keep it lean and small.
* Importing other npm packages here could lead to needlessly increasing the client bundle size, or end up in a server-only function that don't need it.
*/
function assertValue<T>(v: T | undefined, errorMessage: string): T {
if (v =... | or how versioning works
*/
export const apiVersion =
process.env.NEXT_PUBLIC_SANITY_API_VERSION || "2024-02-28";
/**
* Used to configure edit intent links, for Presentation Mode, as well as to configure where the Studio is mounted in the router.
*/
e | C_SANITY_DATASET",
);
export const projectId = assertValue(
process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
"Missing environment variable: NEXT_PUBLIC_SANITY_PROJECT_ID",
);
/**
* see https://www.sanity.io/docs/api-versioning f | {
"filepath": "examples/cms-sanity/sanity/lib/api.ts",
"language": "typescript",
"file_size": 1033,
"cut_index": 513,
"middle_length": 229
} |
"next-sanity";
import { draftMode } from "next/headers";
import { client } from "@/sanity/lib/client";
import { token } from "@/sanity/lib/token";
/**
* Used to fetch data in Server Components, it has built in support for handling Draft Mode and perspectives.
* When using the "published" perspective then time-base... | *
* Stega embedded Content Source Maps are used by Visual Editing by both the Sanity Presentation Tool and Vercel Visual Editing.
* The Sanity Presentation Tool will enable Draft Mode when loading up the live preview, and we use it as a signal for wh | ed from the live API and isn't cached, it will also fetch draft content that isn't published yet.
*/
export async function sanityFetch<const QueryString extends string>({
query,
params = {},
perspective: _perspective,
/* | {
"filepath": "examples/cms-sanity/sanity/lib/fetch.ts",
"language": "typescript",
"file_size": 2538,
"cut_index": 563,
"middle_length": 229
} |
import createImageUrlBuilder from "@sanity/image-url";
import { dataset, projectId } from "@/sanity/lib/api";
const imageBuilder = createImageUrlBuilder({
projectId: projectId || "",
dataset: dataset || "",
});
export const urlForImage = (source: any) => {
// Ensure that source image contains a valid reference... | cumentType?: string,
slug?: string,
): string | undefined {
switch (documentType) {
case "post":
return slug ? `/posts/${slug}` : undefined;
default:
console.warn("Invalid document type:", documentType);
return undefined;
}
| ight = 627) {
if (!image) return;
const url = urlForImage(image)?.width(1200).height(627).fit("crop").url();
if (!url) return;
return { url, alt: image?.alt as string, width, height };
}
export function resolveHref(
do | {
"filepath": "examples/cms-sanity/sanity/lib/utils.ts",
"language": "typescript",
"file_size": 999,
"cut_index": 512,
"middle_length": 229
} |
mport { format, parseISO } from "date-fns";
import { defineField, defineType } from "sanity";
import authorType from "./author";
/**
* This file is the schema definition for a post.
*
* Here you'll be able to edit the different fields that appear when you
* create or edit a post in the studio.
*
* Here you ca... | type: "slug",
description: "A slug is required for the post to show up in the preview",
options: {
source: "title",
maxLength: 96,
isUnique: (value, context) => context.defaultIsUnique(value, context),
},
va | ype: "document",
fields: [
defineField({
name: "title",
title: "Title",
type: "string",
validation: (rule) => rule.required(),
}),
defineField({
name: "slug",
title: "Slug",
| {
"filepath": "examples/cms-sanity/sanity/schemas/documents/post.ts",
"language": "typescript",
"file_size": 2732,
"cut_index": 563,
"middle_length": 229
} |
anity";
import * as demo from "@/sanity/lib/demo";
export default defineType({
name: "settings",
title: "Settings",
type: "document",
icon: CogIcon,
fields: [
defineField({
name: "title",
description: "This field is the title of your blog.",
title: "Title",
type: "string",
... | [],
lists: [],
marks: {
decorators: [],
annotations: [
defineField({
type: "object",
name: "link",
fields: [
{
t | for SEO, and the blog subheader.",
title: "Description",
type: "array",
initialValue: demo.description,
of: [
defineArrayMember({
type: "block",
options: {},
styles: | {
"filepath": "examples/cms-sanity/sanity/schemas/singletons/settings.tsx",
"language": "tsx",
"file_size": 3254,
"cut_index": 614,
"middle_length": 229
} |
ng up the singletons
*/
import { definePlugin, type DocumentDefinition } from "sanity";
import { type StructureResolver } from "sanity/structure";
export const singletonPlugin = definePlugin((types: string[]) => {
return {
name: "singletonPlugin",
document: {
// Hide 'Singletons (such as Settings)' f... | s the "duplicate" action on the Singletons (such as Home)
actions: (prev, { schemaType }) => {
if (types.includes(schemaType)) {
return prev.filter(({ action }) => action !== "duplicate");
}
return prev;
},
| }) => {
if (creationContext.type === "global") {
return prev.filter(
(templateItem) => !types.includes(templateItem.templateId),
);
}
return prev;
},
// Remove | {
"filepath": "examples/cms-sanity/sanity/plugins/settings.tsx",
"language": "tsx",
"file_size": 2111,
"cut_index": 563,
"middle_length": 229
} |
rt { urlForImage } from "@/sanity/lib/utils";
interface Props {
name: string;
picture: Exclude<Author["picture"], undefined> | null;
}
export default function Avatar({ name, picture }: Props) {
return (
<div className="flex items-center text-xl">
{picture?.asset?._ref ? (
<div className="mr-4 ... | ght(96)
.width(96)
.fit("crop")
.url() as string
}
/>
</div>
) : (
<div className="mr-1">By </div>
)}
<div className="text-pretty text-xl font-bold">{na | urlForImage(picture)
?.hei | {
"filepath": "examples/cms-sanity/app/(blog)/avatar.tsx",
"language": "tsx",
"file_size": 942,
"cut_index": 606,
"middle_length": 52
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.