prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
ing when you don't have any posts yet and are using the template for the first time.
* Once you have content, and know where to go to access the Sanity Studio and create content, you can delete this file.
*/
import Link from "next/link";
import { useSyncExternalStore } from "react";
const emptySubscribe = () => () ... | 512"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<rect width="512" height="512" fill="#F03E2F" rx="30" />
<path
d="M161.527 136.723C161.527 179.76 187.738 205.443 240.388 219.095L296 232.283C345.687 243 | return (
<div className="grid grid-flow-row gap-6 py-60 text-center">
<svg
className="mx-auto h-10 w-10 text-gray-400"
aria-hidden="true"
width="512"
height="512"
viewBox="0 0 512 | {
"filepath": "examples/cms-sanity/app/(blog)/onboarding.tsx",
"language": "tsx",
"file_size": 2982,
"cut_index": 563,
"middle_length": 229
} |
CoverImage from "./cover-image";
import DateComponent from "./date";
import MoreStories from "./more-stories";
import Onboarding from "./onboarding";
import PortableText from "./portable-text";
import type { HeroQueryResult } from "@/sanity.types";
import * as demo from "@/sanity/lib/demo";
import { sanityFetch } fro... | n">
<h1 className="text-balance text-6xl font-bold leading-tight tracking-tighter lg:pr-8 lg:text-8xl">
{title || demo.title}
</h1>
<h2 className="text-pretty mt-5 text-center text-lg lg:pl-8 lg:text-left">
<PortableText
| title || demo.title;
const description = props.description?.length
? props.description
: demo.description;
return (
<section className="mt-16 mb-16 flex flex-col items-center lg:mb-12 lg:flex-row lg:justify-betwee | {
"filepath": "examples/cms-sanity/app/(blog)/page.tsx",
"language": "tsx",
"file_size": 3279,
"cut_index": 614,
"middle_length": 229
} |
iew mode by default
const preview =
previewSetting === "true" || previewSetting === undefined ? 1 : 0;
try {
butter = Butter(process.env.NEXT_PUBLIC_BUTTER_CMS_API_KEY, preview);
} catch (e) {
console.log(e);
}
const defaultPageSize = 100;
const defaultPostCount = 10;
async function getLandingPagesData(page, p... | e(slug) {
try {
const page = await butter.page.retrieve("landing-page", slug);
return page?.data?.data;
} catch (e) {
throw e.response.data.detail;
}
}
export async function getLandingPages() {
let paginatedLandingPages = [];
let cu | pages: response?.data?.data,
prevPage: response?.data?.meta.previous_page,
nextPage: response?.data?.meta.next_page,
};
} catch (e) {
throw e.response.data.detail;
}
}
export async function getLandingPag | {
"filepath": "examples/cms-buttercms/lib/api.js",
"language": "javascript",
"file_size": 3136,
"cut_index": 614,
"middle_length": 229
} |
,
features,
scrollAnchorId,
}) {
return (
<section id={scrollAnchorId} className="feature-section">
<div className="container">
<div className="row">
<div className="col-lg-5 col-md-10">
<div className="section-title mb-60">
<h2 className="mb-20">{headline}</h... | index}
headline={feature.headline}
description={feature.description}
icon={feature.icon}
/>
))}
</div>
</div>
</div>
</div>
</sectio | > (
<Feature
key={ | {
"filepath": "examples/cms-buttercms/components/landing-page-sections/features.js",
"language": "javascript",
"file_size": 924,
"cut_index": 606,
"middle_length": 52
} |
e-keys";
import { getPost, getPostsData, getCategories } from "@/lib/api";
import HumanDate from "@/components/human-date";
import CategoriesWidget from "@/components/blog/categories-widget";
import SearchWidget from "@/components/blog/search-widget";
import AuthorCard from "@/components/author-card";
import Preloade... | name="description" content={post.metaDescription} />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
rel="shortcut icon"
type="image/x-icon"
href="https://buttercms.com/static/v2/i | {
return <ErrorPage statusCode={404} />;
}
return (
<>
<Head>
<meta charSet="utf-8" />
<meta httpEquiv="x-ua-compatible" content="ie=edge" />
<title>{post.seoTitle}</title>
<meta | {
"filepath": "examples/cms-buttercms/pages/blog/[slug].js",
"language": "javascript",
"file_size": 5165,
"cut_index": 716,
"middle_length": 229
} |
from "camelcase-keys";
import PostsList from "@/components/blog/posts-list";
import { getPostsData, getCategories, getTags } from "@/lib/api";
import CategoriesWidget from "@/components/blog/categories-widget";
import SearchWidget from "@/components/blog/search-widget";
export default function Tag({ posts, categori... | /">Home</Link>
</li>
<li>
<Link href="/blog">Blog</Link>
</li>
<li>Tag: {slug}</li>
</ul>
</div>
</div>
</div>
| <div className="col-12">
<div className="section-title text-center">
<h2>Blog Posts by Tag</h2>
<ul className="breadcrumb-nav">
<li>
<Link href=" | {
"filepath": "examples/cms-buttercms/pages/blog/tag/[slug].js",
"language": "javascript",
"file_size": 2322,
"cut_index": 563,
"middle_length": 229
} |
Sanity Studio that's mounted on the `app/(sanity)/studio/[[...tool]]/page.tsx` route
*/
import { visionTool } from "@sanity/vision";
import { PluginOptions, defineConfig } from "sanity";
import { unsplashImageAsset } from "sanity-plugin-asset-source-unsplash";
import {
presentationTool,
defineDocuments,
defineLo... | documents/post";
import settings from "@/sanity/schemas/singletons/settings";
import { resolveHref } from "@/sanity/lib/utils";
const homeLocation = {
title: "Home",
href: "/",
} satisfies DocumentLocation;
export default defineConfig({
basePath: s |
import { pageStructure, singletonPlugin } from "@/sanity/plugins/settings";
import { assistWithPresets } from "@/sanity/plugins/assist";
import author from "@/sanity/schemas/documents/author";
import post from "@/sanity/schemas/ | {
"filepath": "examples/cms-sanity/sanity.config.ts",
"language": "typescript",
"file_size": 2810,
"cut_index": 563,
"middle_length": 229
} |
== "settings"][0]`);
const postFields = /* groq */ `
_id,
"status": select(_originalId in path("drafts.**") => "draft", "published"),
"title": coalesce(title, "Untitled"),
"slug": slug.current,
excerpt,
coverImage,
"date": coalesce(date, _updatedAt),
"author": author->{"name": coalesce(name, "Anonymous... | "post" && _id != $skip && defined(slug.current)] | order(date desc, _updatedAt desc) [0...$limit] {
${postFields}
}
`);
export const postQuery = defineQuery(`
*[_type == "post" && slug.current == $slug] [0] {
content,
${postFields}
}
`); | const moreStoriesQuery = defineQuery(`
*[_type == | {
"filepath": "examples/cms-sanity/sanity/lib/queries.ts",
"language": "typescript",
"file_size": 915,
"cut_index": 606,
"middle_length": 52
} |
path: "content",
instructions: [
{
_key: "preset-instruction-1",
title: "Generate sample content",
icon: "block-content",
prompt: [
{
_key: "86e70087d4d5",
markDef... | _key: "0132742d463b",
},
{
_type: "span",
marks: [],
text: " of a blog post, generate a comprehensive and engaging sample content that spans |
_key: "6b5d5d6a63cf0",
},
{
path: "title",
_type: "sanity.assist.instruction.fieldRef",
| {
"filepath": "examples/cms-sanity/sanity/plugins/assist.ts",
"language": "typescript",
"file_size": 10645,
"cut_index": 921,
"middle_length": 229
} |
etadata } from "next";
import {
VisualEditing,
toPlainText,
type PortableTextBlock,
} from "next-sanity";
import { Inter } from "next/font/google";
import { draftMode } from "next/headers";
import AlertBanner from "./alert-banner";
import PortableText from "./portable-text";
import * as demo from "@/sanity/lib/... | description = settings?.description || demo.description;
const ogImage = resolveOpenGraphImage(settings?.ogImage);
let metadataBase: URL | undefined = undefined;
try {
metadataBase = settings?.ogImage?.metadataBase
? new URL(settings.ogIma | n generateMetadata(): Promise<Metadata> {
const settings = await sanityFetch({
query: settingsQuery,
// Metadata should never contain stega
stega: false,
});
const title = settings?.title || demo.title;
const | {
"filepath": "examples/cms-sanity/app/(blog)/layout.tsx",
"language": "tsx",
"file_size": 3585,
"cut_index": 614,
"middle_length": 229
} |
Link from "next/link";
import { useRouter } from "next/router";
import { FormattedMessage } from "react-intl";
import styles from "./Nav.module.css";
export default function Nav() {
const { locale, locales, asPath } = useRouter();
return (
<nav className={styles.nav}>
<li className={styles.li}>
... | locales?.map((availableLocale) => (
<li key={availableLocale} className={styles.li}>
<Link
href={asPath}
locale={availableLocale}
prefetch={false}
className={availableLocale === locale ? sty | >
<Link href="/about">
<FormattedMessage
defaultMessage="About"
description="Nav: About item"
/>
</Link>
</li>
<li className={styles.divider}></li>
{ | {
"filepath": "examples/with-react-intl/components/Nav.tsx",
"language": "tsx",
"file_size": 1129,
"cut_index": 518,
"middle_length": 229
} |
Image from "next/image";
export default function MissingTokenSection() {
return (
<section id="home" className="hero-section">
<div className="container">
<div className="row align-items-center">
<div className="col-xl-6 col-lg-6 col-md-10">
<div className="hero-content">
... | >
Get your free API token
</a>
</div>
</div>
<div className="col-xxl-6 col-xl-6 col-lg-6">
<Image
width={300}
height={300}
src="https://cd | S_API_KEY</code>.
</p>
<a
target="_blank"
rel="noreferrer"
href="https://buttercms.com/join/"
className="main-btn btn-hover"
| {
"filepath": "examples/cms-buttercms/components/missing-token-section.js",
"language": "javascript",
"file_size": 1215,
"cut_index": 518,
"middle_length": 229
} |
Demo data used as placeholders and initial values for the blog
*/
export const title = "Blog.";
export const description = [
{
_key: "9f1a629887fd",
_type: "block",
children: [
{
_key: "4a58edd077880",
_type: "span",
marks: [],
text: "A statically generated blog e... | 8edd077884",
_type: "span",
marks: [],
text: ".",
},
],
markDefs: [
{
_key: "ec5b66c9b1e0",
_type: "link",
href: "https://nextjs.org/",
},
{
_key: "1f8991913ea8",
|
_type: "span",
marks: [],
text: " and ",
},
{
_key: "4a58edd077883",
_type: "span",
marks: ["1f8991913ea8"],
text: "Sanity",
},
{
_key: "4a5 | {
"filepath": "examples/cms-sanity/sanity/lib/demo.ts",
"language": "typescript",
"file_size": 1184,
"cut_index": 518,
"middle_length": 229
} |
ort { UserIcon } from "@sanity/icons";
import { defineField, defineType } from "sanity";
export default defineType({
name: "author",
title: "Author",
icon: UserIcon,
type: "document",
fields: [
defineField({
name: "name",
title: "Name",
type: "string",
validation: (rule) => rule.r... | set?._ref && !alt) {
return "Required";
}
return true;
});
},
},
],
options: {
hotspot: true,
aiAssist: {
imageDescriptionField: "alt",
| tle: "Alternative text",
description: "Important for SEO and accessibility.",
validation: (rule) => {
return rule.custom((alt, context) => {
if ((context.document?.picture as any)?.as | {
"filepath": "examples/cms-sanity/sanity/schemas/documents/author.ts",
"language": "typescript",
"file_size": 1074,
"cut_index": 515,
"middle_length": 229
} |
;
import MainMenuLink from "./main-menu-link";
export default function ManiMenu({ mainMenuLinks }) {
const [activeMenuLink, setActiveMenuLink] = useState(
mainMenuLinks.length ? mainMenuLinks[0].url : "",
);
function highlightLinks() {
const sections = document.querySelectorAll(".page-scroll");
con... | if (
refElement.offsetTop <= scrollTopMinus &&
refElement.offsetTop + refElement.offsetHeight > scrollTopMinus
) {
setActiveMenuLink(val);
}
});
}
useEffect(() => {
window.addEventListener("scroll", highli | ute("href").slice(1);
if (val[0] !== "#") {
return;
}
const refElement = document.querySelector(val);
if (!refElement) {
return;
}
const scrollTopMinus = scrollPos + 73;
| {
"filepath": "examples/cms-buttercms/components/main-menu/main-menu.js",
"language": "javascript",
"file_size": 2547,
"cut_index": 563,
"middle_length": 229
} |
;
import { useRouter } from "next/navigation";
import { useSyncExternalStore, useTransition } from "react";
import { disableDraftMode } from "./actions";
const emptySubscribe = () => () => {};
export default function AlertBanner() {
const router = useRouter();
const [pending, startTransition] = useTransition();... | ft mode..."
) : (
<>
{"Previewing drafts. "}
<button
type="button"
onClick={() =>
startTransition(() =>
disableDraftMode().then(() => {
| ${
pending ? "animate-pulse" : ""
} fixed top-0 left-0 z-50 w-full border-b bg-white/95 text-black backdrop-blur`}
>
<div className="py-2 text-center text-sm">
{pending ? (
"Disabling dra | {
"filepath": "examples/cms-sanity/app/(blog)/alert-banner.tsx",
"language": "tsx",
"file_size": 1294,
"cut_index": 524,
"middle_length": 229
} |
functions.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* Generated by convex@1.12.0.
* To regenerate, run `npx convex dev`.
* @module
*/
import {
actionGeneric,
httpActionGeneric,
queryGeneric,
mutationGeneric,
internalActionGeneric,
internalMutationGeneric,
internalQueryGeneric,
} from "convex/s... | at is only accessible from other Convex functions (but not from the client).
*
* This function will be allowed to read from your Convex database. It will not be accessible from the client.
*
* @param func - The query function. It receives a {@link Quer | query function. It receives a {@link QueryCtx} as its first argument.
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
*/
export const query = queryGeneric;
/**
* Define a query th | {
"filepath": "examples/convex/convex/_generated/server.js",
"language": "javascript",
"file_size": 3484,
"cut_index": 614,
"middle_length": 229
} |
nk";
import Avatar from "./avatar";
import CoverImage from "./cover-image";
import DateComponent from "./date";
import { sanityFetch } from "@/sanity/lib/fetch";
import { moreStoriesQuery } from "@/sanity/lib/queries";
export default async function MoreStories(params: {
skip: string;
limit: number;
}) {
const ... | <CoverImage image={coverImage} priority={false} />
</Link>
<h3 className="text-balance mb-3 text-3xl leading-snug">
<Link href={`/posts/${slug}`} className="hover:underline">
{titl | {data?.map((post) => {
const { _id, title, slug, coverImage, excerpt, author } = post;
return (
<article key={_id}>
<Link href={`/posts/${slug}`} className="group mb-5 block">
| {
"filepath": "examples/cms-sanity/app/(blog)/more-stories.tsx",
"language": "tsx",
"file_size": 1516,
"cut_index": 537,
"middle_length": 229
} |
* This component uses Portable Text to render a post body.
*
* You can learn more about Portable Text on:
* https://www.sanity.io/docs/block-content
* https://github.com/portabletext/react-portabletext
* https://portabletext.org/
*
*/
import {
PortableText,
type PortableTextComponents,
type PortableText... |
),
},
marks: {
link: ({ children, value }) => {
return (
<a href={value?.href} rel="noreferrer noopener">
{children}
</a>
);
},
},
};
return (
<div className={["prose", | omponents = {
block: {
h5: ({ children }) => (
<h5 className="mb-2 text-sm font-semibold">{children}</h5>
),
h6: ({ children }) => (
<h6 className="mb-1 text-xs font-semibold">{children}</h6> | {
"filepath": "examples/cms-sanity/app/(blog)/portable-text.tsx",
"language": "tsx",
"file_size": 1119,
"cut_index": 515,
"middle_length": 229
} |
port { type PortableTextBlock } from "next-sanity";
import Link from "next/link";
import { notFound } from "next/navigation";
import { Suspense } from "react";
import Avatar from "../../avatar";
import CoverImage from "../../cover-image";
import DateComponent from "../../date";
import MoreStories from "../../more-stor... | current}`,
);
export async function generateStaticParams() {
return await sanityFetch({
query: postSlugs,
perspective: "published",
stega: false,
});
}
export async function generateMetadata(
{ params }: Props,
parent: ResolvingMetada | sanity/lib/queries";
import { resolveOpenGraphImage } from "@/sanity/lib/utils";
type Props = {
params: Promise<{ slug: string }>;
};
const postSlugs = defineQuery(
`*[_type == "post" && defined(slug.current)]{"slug": slug. | {
"filepath": "examples/cms-sanity/app/(blog)/posts/[slug]/page.tsx",
"language": "tsx",
"file_size": 3587,
"cut_index": 614,
"middle_length": 229
} |
e { Stripe } from "stripe";
import { headers } from "next/headers";
import { CURRENCY } from "@/config";
import { formatAmountForStripe } from "@/utils/stripe-helpers";
import { stripe } from "@/lib/stripe";
export async function createCheckoutSession(
data: FormData,
): Promise<{ client_secret: string | null; url... | CURRENCY,
product_data: {
name: "Custom amount donation",
},
unit_amount: formatAmountForStripe(
Number(data.get("customDonation") as string),
CURRENCY,
),
| Session: Stripe.Checkout.Session =
await stripe.checkout.sessions.create({
mode: "payment",
submit_type: "donate",
line_items: [
{
quantity: 1,
price_data: {
currency: | {
"filepath": "examples/with-stripe-typescript/app/actions/stripe.ts",
"language": "typescript",
"file_size": 1977,
"cut_index": 537,
"middle_length": 229
} |
tResponse } from "next/server";
import { stripe } from "@/lib/stripe";
export async function POST(req: Request) {
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(
await (await req.blob()).text(),
req.headers.get("stripe-signature") as string,
process.env.STRIPE_WEBHOOK... | cted event.
console.log("✅ Success:", event.id);
const permittedEvents: string[] = [
"checkout.session.completed",
"payment_intent.succeeded",
"payment_intent.payment_failed",
];
if (permittedEvents.includes(event.type)) {
let dat | anceof Error)) console.log(err);
console.log(`❌ Error message: ${errorMessage}`);
return NextResponse.json(
{ message: `Webhook Error: ${errorMessage}` },
{ status: 400 },
);
}
// Successfully constru | {
"filepath": "examples/with-stripe-typescript/app/api/webhooks/route.ts",
"language": "typescript",
"file_size": 2075,
"cut_index": 563,
"middle_length": 229
} |
se types.
*
* For more information on how to use Sanity TypeGen, visit the official documentation:
* https://www.sanity.io/docs/sanity-typegen
* ---------------------------------------------------------------------------------
*/
// Source: schema.json
export type SanityImagePaletteSwatch = {
_type: "sanity.ima... | muted?: SanityImagePaletteSwatch;
};
export type SanityImageDimensions = {
_type: "sanity.imageDimensions";
height?: number;
width?: number;
aspectRatio?: number;
};
export type SanityFileAsset = {
_id: string;
_type: "sanity.fileAsset";
_c | nityImagePaletteSwatch;
lightVibrant?: SanityImagePaletteSwatch;
darkVibrant?: SanityImagePaletteSwatch;
vibrant?: SanityImagePaletteSwatch;
dominant?: SanityImagePaletteSwatch;
lightMuted?: SanityImagePaletteSwatch;
| {
"filepath": "examples/cms-sanity/sanity.types.ts",
"language": "typescript",
"file_size": 16775,
"cut_index": 921,
"middle_length": 229
} |
ort type { Metadata } from "next";
import Link from "next/link";
export const metadata: Metadata = {
title: "Home | Next.js + TypeScript Example",
};
export default function IndexPage(): JSX.Element {
return (
<ul className="card-list">
<li>
<Link
href="/donate-with-embedded-checkout"... | mg src="/checkout-one-time-payments.svg" />
</Link>
</li>
<li>
<Link
href="/donate-with-elements"
className="card elements-style-background"
>
<h2 className="bottom">Donate with Elements</h2 | </Link>
</li>
<li>
<Link
href="/donate-with-checkout"
className="card checkout-style-background"
>
<h2 className="bottom">Donate with hosted Checkout</h2>
<i | {
"filepath": "examples/with-stripe-typescript/app/page.tsx",
"language": "tsx",
"file_size": 1098,
"cut_index": 515,
"middle_length": 229
} |
mport React, { useState } from "react";
import CustomDonationInput from "@/components/CustomDonationInput";
import StripeTestCards from "@/components/StripeTestCards";
import { formatAmountForDisplay } from "@/utils/stripe-helpers";
import * as config from "@/config";
import { createCheckoutSession } from "@/actions/... | >({
customDonation: Math.round(config.MAX_AMOUNT / config.AMOUNT_STEP),
});
const [clientSecret, setClientSecret] = useState<string | null>(null);
const handleInputChange: React.ChangeEventHandler<HTMLInputElement> = (
e,
): void =>
se | e.Checkout.SessionCreateParams.UiMode;
}
export default function CheckoutForm(props: CheckoutFormProps): JSX.Element {
const [loading] = useState<boolean>(false);
const [input, setInput] = useState<{ customDonation: number } | {
"filepath": "examples/with-stripe-typescript/app/components/CheckoutForm.tsx",
"language": "tsx",
"file_size": 2436,
"cut_index": 563,
"middle_length": 229
} |
from "next";
import Link from "next/link";
import "../styles.css";
interface LayoutProps {
children: React.ReactNode;
}
export const metadata: Metadata = {
title: {
default: "TypeScript Next.js Stripe Example",
template: "%s | Next.js + TypeScript Example",
},
twitter: {
card: "summary_large_ima... | >
<div className="container">
<header>
<div className="header-content">
<Link href="/" className="logo">
<img src="/logo.png" />
</Link>
<h1>
<span clas | el.app/social_card.png",
},
],
site: "@StripeDev",
title: "TypeScript Next.js Stripe Example",
},
};
export default function RootLayout({ children }: LayoutProps) {
return (
<html lang="en">
<body | {
"filepath": "examples/with-stripe-typescript/app/layout.tsx",
"language": "tsx",
"file_size": 1856,
"cut_index": 537,
"middle_length": 229
} |
t type { Stripe } from "stripe";
import PrintObject from "@/components/PrintObject";
import { stripe } from "@/lib/stripe";
export default async function ResultPage({
searchParams,
}: {
searchParams: { session_id: string };
}): Promise<JSX.Element> {
if (!searchParams.session_id)
throw new Error("Please pro... | tent"],
});
const paymentIntent = checkoutSession.payment_intent as Stripe.PaymentIntent;
return (
<>
<h2>Status: {paymentIntent.status}</h2>
<h3>Checkout Session response:</h3>
<PrintObject content={checkoutSession} />
| ", "payment_in | {
"filepath": "examples/with-stripe-typescript/app/donate-with-checkout/result/page.tsx",
"language": "tsx",
"file_size": 798,
"cut_index": 517,
"middle_length": 14
} |
import CustomDonationInput from "./CustomDonationInput";
import StripeTestCards from "./StripeTestCards";
import { formatAmountForDisplay } from "@/utils/stripe-helpers";
import * as config from "@/config";
import getStripe from "@/utils/get-stripejs";
import { createPaymentIntent } from "@/actions/stripe";
function ... | initial" });
const [errorMessage, setErrorMessage] = React.useState<string>("");
const stripe = useStripe();
const elements = useElements();
const PaymentStatus = ({ status }: { status: string }) => {
switch (status) {
case "processing" | fig.AMOUNT_STEP),
cardholderName: "",
});
const [paymentType, setPaymentType] = React.useState<string>("");
const [payment, setPayment] = React.useState<{
status: "initial" | "processing" | "error";
}>({ status: " | {
"filepath": "examples/with-stripe-typescript/app/components/ElementsForm.tsx",
"language": "tsx",
"file_size": 5319,
"cut_index": 716,
"middle_length": 229
} |
{ Action, ThunkAction } from "@reduxjs/toolkit";
import { combineSlices, configureStore } from "@reduxjs/toolkit";
import { counterSlice } from "./features/counter/counterSlice";
import { quotesApiSlice } from "./features/quotes/quotesApiSlice";
// `combineSlices` automatically combines the reducers using
// their `re... | SR, separate store instances
// are needed for each request to prevent cross-request state pollution.
export const makeStore = () => {
return configureStore({
reducer: rootReducer,
// Adding the api middleware enables caching, invalidation, polli | type RootState = ReturnType<typeof rootReducer>;
// `makeStore` encapsulates the store configuration to allow
// creating unique store instances, which is particularly important for
// server-side rendering (SSR) scenarios. In S | {
"filepath": "examples/with-redux/lib/store.ts",
"language": "typescript",
"file_size": 1504,
"cut_index": 524,
"middle_length": 229
} |
keStore } from "@/lib/store";
import { setupListeners } from "@reduxjs/toolkit/query";
import type { ReactNode } from "react";
import { useEffect, useRef } from "react";
import { Provider } from "react-redux";
interface Props {
readonly children: ReactNode;
}
export const StoreProvider = ({ children }: Props) => {
... | configure listeners using the provided defaults
// optional, but required for `refetchOnFocus`/`refetchOnReconnect` behaviors
const unsubscribe = setupListeners(storeRef.current.dispatch);
return unsubscribe;
}
}, []);
return <P | () => {
if (storeRef.current != null) {
// | {
"filepath": "examples/with-redux/app/StoreProvider.tsx",
"language": "tsx",
"file_size": 949,
"cut_index": 582,
"middle_length": 52
} |
mport {
decrement,
increment,
incrementAsync,
incrementByAmount,
incrementIfOdd,
selectCount,
selectStatus,
} from "@/lib/features/counter/counterSlice";
import { useAppDispatch, useAppSelector } from "@/lib/hooks";
import styles from "./Counter.module.css";
export const Counter = () => {
const dispat... | ment())}
>
-
</button>
<span aria-label="Count" className={styles.value}>
{count}
</span>
<button
className={styles.button}
aria-label="Increment value"
onClick={() = | mentValue = Number(incrementAmount) || 0;
return (
<div>
<div className={styles.row}>
<button
className={styles.button}
aria-label="Decrement value"
onClick={() => dispatch(decre | {
"filepath": "examples/with-redux/app/components/counter/Counter.tsx",
"language": "tsx",
"file_size": 2025,
"cut_index": 563,
"middle_length": 229
} |
;
import { useGetQuotesQuery } from "@/lib/features/quotes/quotesApiSlice";
import { useState } from "react";
import styles from "./Quotes.module.css";
const options = [5, 10, 20, 30];
export const Quotes = () => {
const [numberOfQuotes, setNumberOfQuotes] = useState(10);
// Using a query hook automatically fetch... | Quantity of Quotes to Fetch:</h3>
<select
className={styles.select}
value={numberOfQuotes}
onChange={(e) => {
setNumberOfQuotes(Number(e.target.value));
}}
>
{options.map((optio | ror!!!</h1>
</div>
);
}
if (isLoading) {
return (
<div>
<h1>Loading...</h1>
</div>
);
}
if (isSuccess) {
return (
<div className={styles.container}>
<h3>Select the | {
"filepath": "examples/with-redux/app/components/quotes/Quotes.tsx",
"language": "tsx",
"file_size": 1421,
"cut_index": 524,
"middle_length": 229
} |
smosdb";
export type Props = {
isConnected: boolean;
database?: {
name?: string;
isConnected: boolean;
numOfContainers?: number;
};
container?: {
isConnected: boolean;
name?: string;
};
};
const Home = (props: Props) => {
return (
<div className="container">
<Head>
<t... | README.md</code>{" "}
for instructions.
</h2>
)}
<p className="description">
Get started by editing <code>pages/index.js</code>
</p>
{props.isConnected ? (
<div className="main">
<div cl | osmosDB!</a>
</h1>
{props.isConnected ? (
<h2 className="subtitle">You are connected to CosmosDB</h2>
) : (
<h2 className="subtitle">
You are NOT connected to CosmosDB. Check the <code> | {
"filepath": "examples/with-azure-cosmos/pages/index.tsx",
"language": "tsx",
"file_size": 4752,
"cut_index": 614,
"middle_length": 229
} |
nngest } from "inngest";
// TypeScript schema for the events
export type Events = {
"test/hello.world": {
name: "test/hello.world";
data: {
message: string;
};
};
};
// Inngest client to send and receive events
export const inngest = new Inngest({
id: "demo-app",
schemas: new EventSchemas().... | nc ({ event, step }) => {
await step.sleep("sleep for a second", "1s");
return { event, body: event.data.message };
},
);
// configuration for the Inngest api router
export const inngestConfig = {
client: inngest,
functions: [helloWorld],
}; | orld" },
asy | {
"filepath": "examples/inngest/src/inngest/inngest.config.ts",
"language": "typescript",
"file_size": 807,
"cut_index": 536,
"middle_length": 14
} |
import passport from "passport";
import LocalStrategy from "passport-local";
import { findUserByUsername, validatePassword } from "./db";
passport.serializeUser(function (user, done) {
// serialize the username into session
done(null, user.username);
});
passport.deserializeUser(function (req, id, done) {
// de... | , you must verify it
// if (!user || await argon2.verify(user.password, password))
if (!user || !validatePassword(user, password)) {
done(null, null);
} else {
done(null, user);
}
},
),
);
export default passp | username, password, done) => {
// Here you lookup the user in your DB and compare the password/hashed password
const user = findUserByUsername(req, username);
// Security-wise, if you hashed the password earlier | {
"filepath": "examples/with-passport-and-next-connect/lib/passport.js",
"language": "javascript",
"file_size": 1002,
"cut_index": 512,
"middle_length": 229
} |
nk";
import { useUser } from "../lib/hooks";
export default function Navbar() {
const [user, { mutate }] = useUser();
async function handleLogout() {
await fetch("/api/logout");
mutate({ user: null });
}
return (
<header>
<nav>
<ul>
<li>
<Link href="/">Home</Li... | </li>
<li>
<Link href="/login">Login</Link>
</li>
</>
)}
</ul>
</nav>
<style jsx>{`
nav {
max-width: 42rem;
margin: 0 auto;
padding: | utton" onClick={handleLogout}>
Logout
</a>
</li>
</>
) : (
<>
<li>
<Link href="/signup">Sign up</Link>
| {
"filepath": "examples/with-passport-and-next-connect/components/Navbar.js",
"language": "javascript",
"file_size": 1522,
"cut_index": 537,
"middle_length": 229
} |
port useSWR from "swr";
function UserList() {
const { data: { users } = {} } = useSWR("/api/users", fetcher);
return (
<>
<h2>All users</h2>
{!!users?.length && (
<ul>
{users.map((user) => (
<li key={user.username}>
<pre>{JSON.stringify(user, null, 2)}</p... | com/hoangvvo/next-connect">next-connect</a>{" "}
Example
</h1>
<h2>Steps to test the example:</h2>
<h3>Sign up</h3>
<ol>
<li>Click Sign up and enter a username and password.</li>
<li>You will be logged in and | </ul>
)}
</>
);
}
export default function HomePage() {
const [user] = useUser();
return (
<>
<h1>
<a href="http://www.passportjs.org/">Passport.js</a> +{" "}
<a href="https://github. | {
"filepath": "examples/with-passport-and-next-connect/pages/index.js",
"language": "javascript",
"file_size": 2235,
"cut_index": 563,
"middle_length": 229
} |
ect } from "react";
import Router from "next/router";
import Link from "next/link";
import { useUser } from "../lib/hooks";
export default function SignupPage() {
const [user, { mutate }] = useUser();
const [errorMsg, setErrorMsg] = useState("");
async function onSubmit(e) {
e.preventDefault();
const b... | tringify(body),
});
if (res.status === 201) {
const userObj = await res.json();
// set user to useSWR state
mutate(userObj);
} else {
setErrorMsg(await res.text());
}
}
useEffect(() => {
// redirect to home | t.rpassword.value) {
setErrorMsg(`The passwords don't match`);
return;
}
const res = await fetch("/api/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.s | {
"filepath": "examples/with-passport-and-next-connect/pages/signup.js",
"language": "javascript",
"file_size": 2017,
"cut_index": 537,
"middle_length": 229
} |
nextConnect from "next-connect";
import auth from "../../middleware/auth";
import { getAllUsers, createUser, findUserByUsername } from "../../lib/db";
const handler = nextConnect();
handler
.use(auth)
.get((req, res) => {
// For demo purpose only. You will never have an endpoint which returns all users.
... | s.status(409).send("The username has already been used");
}
const user = { username, password, name };
// Security-wise, you must hash the password before saving it
// const hashedPass = await argon2.hash(password);
// const user = { us | {
return res.status(400).send("Missing fields");
}
// Here you check if the username has already been used
const usernameExisted = !!findUserByUsername(req, username);
if (usernameExisted) {
return re | {
"filepath": "examples/with-passport-and-next-connect/pages/api/users.js",
"language": "javascript",
"file_size": 1251,
"cut_index": 518,
"middle_length": 229
} |
mport { useEffect } from "react";
import { useRouter } from "next/router";
import Modal from "react-modal";
import Article from "../../components/Article";
import { data } from "../../components/Grid";
Modal.setAppElement("#__next");
const ArticlePage = ({ articleId }) => {
const router = useRouter();
useEffect(... | lt ArticlePage;
export function getStaticProps({ params: { articleId } }) {
return { props: { articleId: articleId } };
}
export function getStaticPaths() {
return {
paths: data.map((articleId) => ({
params: { articleId: articleId.toString( | n on page load, it is the 'page'
onRequestClose={() => router.push("/")}
contentLabel="Post modal"
>
<Article id={articleId} pathname={router.pathname} />
</Modal>
</>
);
};
export defau | {
"filepath": "examples/with-route-as-modal/pages/article/[articleId].js",
"language": "javascript",
"file_size": 1040,
"cut_index": 513,
"middle_length": 229
} |
async 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.PLASMIC_PREVIEW_SECRET ||
!req.query.slug
) {
return res.status(401).json({ message: "Invalid token" });
}
// Check ... | a) {
return res.status(401).json({ message: "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 mig | event preview mode from being enabled
if (!pageMet | {
"filepath": "examples/cms-plasmic/pages/api/preview.ts",
"language": "typescript",
"file_size": 964,
"cut_index": 582,
"middle_length": 52
} |
* Generated data model types.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* Generated by convex@1.12.0.
* To regenerate, run `npx convex dev`.
* @module
*/
import type {
DataModelFromSchemaDefinition,
DocumentByName,
TableNamesInDataModel,
SystemTableNames,
} from "convex/server";
import type { Generic... | ier for a document in Convex.
*
* Convex documents are uniquely identified by their `Id`, which is accessible
* on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).
*
* Documents can be loaded using `db.ge | a document stored in Convex.
*
* @typeParam TableName - A string literal type of the table name (like "users").
*/
export type Doc<TableName extends TableNames> = DocumentByName<
DataModel,
TableName
>;
/**
* An identif | {
"filepath": "examples/convex/convex/_generated/dataModel.d.ts",
"language": "typescript",
"file_size": 1756,
"cut_index": 537,
"middle_length": 229
} |
mEvent, useEffect, useState } from "react";
import { useMutation, useQuery } from "convex/react";
import { api } from "../convex/_generated/api";
export default function App() {
const messages = useQuery(api.messages.list);
const sendMessage = useMutation(api.messages.send);
const [newMessageText, setNewMessage... | an>{name}</span>
</p>
<ul>
{messages?.map((message) => (
<li key={message._id.toString()}>
<span>{message.author}:</span>
<span>{message.body}</span>
<span>{new Date(message._creationTime).t | vent: FormEvent) {
event.preventDefault();
setNewMessageText("");
await sendMessage({ body: newMessageText, author: name });
}
return (
<main>
<h1>Convex Chat</h1>
<p className="badge">
<sp | {
"filepath": "examples/convex/pages/index.tsx",
"language": "tsx",
"file_size": 1396,
"cut_index": 524,
"middle_length": 229
} |
port type { PayloadAction } from "@reduxjs/toolkit";
import { fetchCount } from "./counterAPI";
export interface CounterSliceState {
value: number;
status: "idle" | "loading" | "failed";
}
const initialState: CounterSliceState = {
value: 0,
status: "idle",
};
// If you are not using async thunks you can use ... | // doesn't actually mutate the state because it uses the Immer library,
// which detects changes to a "draft state" and produces a brand new
// immutable state based off those changes
state.value += 1;
}),
decrement: create.reduce | The `reducers` field lets us define reducers and generate associated actions
reducers: (create) => ({
increment: create.reducer((state) => {
// Redux Toolkit allows us to write "mutating" logic in reducers. It
| {
"filepath": "examples/with-redux/lib/features/counter/counterSlice.ts",
"language": "typescript",
"file_size": 3265,
"cut_index": 614,
"middle_length": 229
} |
Node } from "react";
import { StoreProvider } from "./StoreProvider";
import { Nav } from "./components/Nav";
import "./styles/globals.css";
import styles from "./styles/layout.module.css";
interface Props {
readonly children: ReactNode;
}
export default function RootLayout({ children }: Props) {
return (
<S... | .main}>{children}</main>
<footer className={styles.footer}>
<span>Learn </span>
<a
className={styles.link}
href="https://reactjs.org"
target="_blank"
r | src="/logo.svg"
className={styles.logo}
alt="logo"
width={100}
height={100}
/>
</header>
<main className={styles | {
"filepath": "examples/with-redux/app/layout.tsx",
"language": "tsx",
"file_size": 2317,
"cut_index": 563,
"middle_length": 229
} |
tainer, CosmosClient, Database } from "@azure/cosmos";
export type Cosmos = {
connected: boolean;
client?: CosmosClient;
database?: Database;
container?: Container;
};
if (!process.env.COSMOSDB_CONNECTION_STRING) {
throw new Error(
'Invalid/Missing environment variable: "COSMOSDB_CONNECTION_STRING"',
... | inerName = process.env.COSMOSDB_CONTAINER_NAME;
let client;
let database;
let container;
const cosmos: Cosmos = {
connected: true,
client,
database,
container,
};
try {
client = new CosmosClient(connectionString);
database = client.database( | throw new Error(
'Invalid/Missing environment variable: "COSMOSDB_CONTAINER_NAME"',
);
}
const connectionString = process.env.COSMOSDB_CONNECTION_STRING;
const databaseName = process.env.COSMOSDB_DATABASE_NAME;
const conta | {
"filepath": "examples/with-azure-cosmos/lib/cosmosdb.ts",
"language": "typescript",
"file_size": 1279,
"cut_index": 524,
"middle_length": 229
} |
o";
export function getAllUsers(req) {
// For demo purpose only. You are not likely to have to return all users.
return req.session.users;
}
export function createUser(req, { username, password, name }) {
// Here you should create the user and save the salt and hashed password (some dbs may have
// authentica... | ateUser(user)
req.session.users.push(user);
}
export function findUserByUsername(req, username) {
// Here you find the user based on id/username in the database
// const user = await db.findUserById(id)
return req.session.users.find((user) => user | , "sha512")
.toString("hex");
const user = {
id: crypto.randomUUID(),
createdAt: Date.now(),
username,
name,
hash,
salt,
};
// Here you should insert the user into the database
// await db.cre | {
"filepath": "examples/with-passport-and-next-connect/lib/db.js",
"language": "javascript",
"file_size": 1966,
"cut_index": 537,
"middle_length": 229
} |
ect } from "react";
import Router from "next/router";
import Link from "next/link";
import { useUser } from "../lib/hooks";
export default function LoginPage() {
const [user, { mutate }] = useUser();
const [errorMsg, setErrorMsg] = useState("");
async function onSubmit(e) {
e.preventDefault();
const bo... | etErrorMsg("Incorrect username or password. Try better!");
}
}
useEffect(() => {
// redirect to home if user is authenticated
if (user) Router.push("/");
}, [user]);
return (
<>
<h1>Login to Example</h1>
{errorMsg && < | "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (res.status === 200) {
const userObj = await res.json();
// set user to useSWR state
mutate(userObj);
} else {
s | {
"filepath": "examples/with-passport-and-next-connect/pages/login.js",
"language": "javascript",
"file_size": 1605,
"cut_index": 537,
"middle_length": 229
} |
outer from "next/router";
import { useUser } from "../lib/hooks";
function ProfileEdit() {
const [user, { mutate }] = useUser();
const nameRef = useRef();
useEffect(() => {
if (!user) return;
nameRef.current.value = user.name;
}, [user]);
async function handleEditProfile(e) {
e.preventDefault()... | (res.status === 204) {
mutate({ user: null });
Router.replace("/");
}
}
return (
<>
<div className="form-container">
<form onSubmit={handleEditProfile}>
<label>
<span>Name</span>
<in | y: JSON.stringify(body),
});
const updatedUser = await res.json();
mutate(updatedUser);
}
async function handleDeleteProfile() {
const res = await fetch(`/api/user`, {
method: "DELETE",
});
if | {
"filepath": "examples/with-passport-and-next-connect/pages/profile.js",
"language": "javascript",
"file_size": 2141,
"cut_index": 563,
"middle_length": 229
} |
PlasmicRootProvider,
extractPlasmicQueryData,
} from "@plasmicapp/loader-nextjs";
import type { GetStaticPaths, GetStaticProps } from "next";
import Error from "next/error";
import { PLASMIC, PREVIEW_PLASMIC } from "../plasmic-init";
/**
* Use fetchPages() to fetch list of pages that have been created in Plasmic... | ext.params ?? {};
// Convert the catchall param into a path string
const plasmicPath =
typeof catchall === "string"
? catchall
: Array.isArray(catchall)
? `/${catchall.join("/")}`
: "/";
const plasmicData = await PLAS | bstring(1).split("/") },
})),
fallback: "blocking",
};
};
/**
* For each page, pre-fetch the data we need to render it
*/
export const getStaticProps: GetStaticProps = async (context) => {
const { catchall } = cont | {
"filepath": "examples/cms-plasmic/pages/[[...catchall]].tsx",
"language": "tsx",
"file_size": 2699,
"cut_index": 563,
"middle_length": 229
} |
t type { Stripe } from "stripe";
import PrintObject from "@/components/PrintObject";
import { stripe } from "@/lib/stripe";
export default async function ResultPage({
searchParams,
}: {
searchParams: { session_id: string };
}): Promise<JSX.Element> {
if (!searchParams.session_id)
throw new Error("Please pro... | tent"],
});
const paymentIntent = checkoutSession.payment_intent as Stripe.PaymentIntent;
return (
<>
<h2>Status: {paymentIntent.status}</h2>
<h3>Checkout Session response:</h3>
<PrintObject content={checkoutSession} />
| ", "payment_in | {
"filepath": "examples/with-stripe-typescript/app/donate-with-embedded-checkout/result/page.tsx",
"language": "tsx",
"file_size": 798,
"cut_index": 517,
"middle_length": 14
} |
ext");
const http2 = require("node:http2");
const { parse } = require("node:url");
const fs = require("node:fs");
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== "production";
// Init the Next app:
const app = next({ dev });
// Create the secure HTTPS server:
// Don't forget... | (() => {
server.on("error", (err) => console.error(err));
server.on("request", (req, res) => {
const parsedUrl = parse(req.url, true);
handler(req, res, parsedUrl);
});
server.listen(port);
console.log(`Listening on HTTPS port ${port}`); | ndler = app.getRequestHandler();
app.prepare().then | {
"filepath": "examples/with-http2/server.js",
"language": "javascript",
"file_size": 848,
"cut_index": 535,
"middle_length": 52
} |
se, serialize } from "cookie";
import { createLoginSession, getLoginSession } from "./auth";
function parseCookies(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(... | is invalid
}
}
req.session = unsealed;
// We are proxying res.end to commit the session cookie
const oldEnd = res.end;
res.end = async function resEndProxy(...args) {
if (res.finished || res.writableEnded || res.headersSe | name];
let unsealed = {};
if (token) {
try {
// the cookie needs to be unsealed using the password `secret`
unsealed = await getLoginSession(token, secret);
} catch (e) {
// The cookie | {
"filepath": "examples/with-passport-and-next-connect/lib/session.js",
"language": "javascript",
"file_size": 1307,
"cut_index": 524,
"middle_length": 229
} |
;
export const data = [1, 2, 3, 4, 5, 6, 7, 8, 9];
export default function PostCardGrid() {
return (
<div className={styles.postCardGridWrapper}>
<h2>With QueryString Routing, and a reload won't use the modal</h2>
<div className={styles.postCardGrid}>
{data.map((id, index) => (
<Li... | eloads will keep the modal</h2>
<div className={styles.postCardGrid}>
{data.map((id, index) => (
<Link
key={index}
href="/article/[articleId]"
as={`/article/${id}`}
className={styles.p |
</div>
<h2>With Dynamic Routing, and r | {
"filepath": "examples/with-route-as-modal/components/Grid.js",
"language": "javascript",
"file_size": 989,
"cut_index": 582,
"middle_length": 52
} |
ckageDefinition,
} from "./templates/component-factory";
import { getItems, watchItems } from "./utils";
/*
COMPONENT FACTORY GENERATION
Generates the `/src/temp/componentFactory.ts` file, which maps JSS React components
to Sitecore renderings.
The component factory is a mapping between a string name and a Re... | ponents/ComponentName.ts` would map to component `ComponentName`.
This can be customized in writeComponentFactory().
This script supports two modes. In default mode, the component factory file is written once.
In watch mode, the component factory so |
Generating the componentFactory is optional, and it can be maintained manually if preferred.
The default convention uses the component's filename (without the extension) as the component
name. For example, the file `/com | {
"filepath": "examples/cms-sitecore-xmcloud/scripts/generate-component-factory.ts",
"language": "typescript",
"file_size": 3692,
"cut_index": 614,
"middle_length": 229
} |
TION
NOTE: pluginName: the name of the plugin in the src/lib folder
Generates the `/src/temp/{pluginName}-plugins.ts` file, which exports list of plugins
Generating the plugins is optional, and it can be maintained manually if preferred.
The default convention uses the plugin's filename (without the extension... | [
{
listPath: "scripts/temp/config-plugins.ts",
rootPath: "scripts/config/plugins",
moduleType: ModuleType.ESM,
},
{
listPath: "src/temp/sitemap-fetcher-plugins.ts",
rootPath: "src/lib/sitemap-fetcher/plugins",
moduleType: Mo | ugins().
*/
enum ModuleType {
CJS,
ESM,
}
interface PluginDefinition {
listPath: string;
rootPath: string;
moduleType: ModuleType;
}
interface PluginFile {
path: string;
name: string;
}
const pluginDefinitions = | {
"filepath": "examples/cms-sitecore-xmcloud/scripts/generate-plugins.ts",
"language": "typescript",
"file_size": 3757,
"cut_index": 614,
"middle_length": 229
} |
rt chokidar from "chokidar";
/**
* Run watch mode, watching on @var rootPath
*/
export function watchItems(rootPath: string, cb: () => void): void {
chokidar
.watch(rootPath, { ignoreInitial: true, awaitWriteFinish: true })
.on("add", cb)
.on("unlink", cb);
}
/**
* Using @var path find all files recu... | : string) => void;
fileFormat?: RegExp;
}): Item[] {
const {
path,
resolveItem,
cb,
fileFormat = new RegExp(/(.+)(?<!\.d)\.[jt]sx?$/),
} = settings;
const items: Item[] = [];
const folders: fs.Dirent[] = [];
if (!fs.existsSync( | called when new item is found
* @param fileFormat Matches specific files
* @returns {Item[]} items
*/
export function getItems<Item>(settings: {
path: string;
resolveItem: (path: string, name: string) => Item;
cb?: (name | {
"filepath": "examples/cms-sitecore-xmcloud/scripts/utils.ts",
"language": "typescript",
"file_size": 1624,
"cut_index": 537,
"middle_length": 229
} |
onfigPlugin, JssConfig } from "..";
/**
* This plugin will set config props based on scjssconfig.json.
* scjssconfig.json may not exist if you've never run `jss setup` (development)
* or are depending on environment variables instead (production).
*/
class ScJssConfigPlugin implements ConfigPlugin {
order = 1;
... | rn Object.assign({}, config, {
sitecoreApiKey: config.sitecoreApiKey || scJssConfig.sitecore?.apiKey,
sitecoreApiHost:
config.sitecoreApiHost || scJssConfig.sitecore?.layoutServiceHost,
});
}
}
export const scjssconfigPlugin = ne | fig;
retu | {
"filepath": "examples/cms-sitecore-xmcloud/scripts/config/plugins/scjssconfig.ts",
"language": "typescript",
"file_size": 815,
"cut_index": 522,
"middle_length": 14
} |
ictionaryService,
RestDictionaryService,
GraphQLDictionaryService,
constants,
} from "@sitecore-jss/sitecore-jss-nextjs";
import config from "temp/config";
/**
* Factory responsible for creating a DictionaryService instance
*/
export class DictionaryServiceFactory {
/**
* @param {string} siteName site nam... | es for the current
app. If your Sitecore instance only has 1 JSS App, you can specify the root item ID here;
otherwise, the service will attempt to figure out the root item for the current JSS App using GraphQL and app name.
| LDictionaryService({
endpoint: config.graphQLEndpoint,
apiKey: config.sitecoreApiKey,
siteName,
/*
The Dictionary Service needs a root item ID in order to fetch dictionary phras | {
"filepath": "examples/cms-sitecore-xmcloud/src/lib/dictionary-service-factory.ts",
"language": "typescript",
"file_size": 1332,
"cut_index": 524,
"middle_length": 229
} |
nt, NextRequest } from "next/server";
import * as plugins from "temp/middleware-plugins";
export interface MiddlewarePlugin {
/**
* Detect order when the plugin should be called, e.g. 0 - will be called first (can be a plugin which data is required for other plugins)
*/
order: number;
/**
* A middleware... | q: NextRequest,
ev: NextFetchEvent,
): Promise<NextResponse> {
const response = NextResponse.next();
return (Object.values(plugins) as MiddlewarePlugin[])
.sort((p1, p2) => p1.order - p2.order)
.reduce(
(p, plugin) => p.then((res) => p | >;
}
export default async function middleware(
re | {
"filepath": "examples/cms-sitecore-xmcloud/src/lib/middleware/index.ts",
"language": "typescript",
"file_size": 959,
"cut_index": 582,
"middle_length": 52
} |
psContext, GetStaticPropsContext } from "next";
import { SitecorePageProps } from "lib/page-props";
import * as plugins from "temp/page-props-factory-plugins";
/**
* Determines whether context is GetServerSidePropsContext (SSR) or GetStaticPropsContext (SSG)
* @param {GetServerSidePropsContext | GetStaticPropsContex... | order: number;
/**
* A function which will be called during page props generation
*/
exec(
props: SitecorePageProps,
context: GetServerSidePropsContext | GetStaticPropsContext,
): Promise<SitecorePageProps>;
}
export class SitecorePag | etServerSidePropsContext).req !== undefined;
};
export interface Plugin {
/**
* Detect order when the plugin should be called, e.g. 0 - will be called first (can be a plugin which data is required for other plugins)
*/
| {
"filepath": "examples/cms-sitecore-xmcloud/src/lib/page-props-factory/index.ts",
"language": "typescript",
"file_size": 1852,
"cut_index": 537,
"middle_length": 229
} |
ponentPropsService } from "@sitecore-jss/sitecore-jss-nextjs";
import { SitecorePageProps } from "lib/page-props";
import { GetServerSidePropsContext, GetStaticPropsContext } from "next";
import { componentModule } from "temp/componentFactory";
import { Plugin, isServerSidePropsContext } from "..";
class ComponentProp... | onents level
if (isServerSidePropsContext(context)) {
props.componentProps =
await this.componentPropsService.fetchServerSideComponentProps({
layoutData: props.layoutData,
context,
componentModule,
}) | exec(
props: SitecorePageProps,
context: GetServerSidePropsContext | GetStaticPropsContext,
) {
if (!props.layoutData.sitecore.route) return props;
// Retrieve component props using side-effects defined on comp | {
"filepath": "examples/cms-sitecore-xmcloud/src/lib/page-props-factory/plugins/component-props.ts",
"language": "typescript",
"file_size": 1316,
"cut_index": 524,
"middle_length": 229
} |
om "@sitecore-jss/sitecore-jss-nextjs";
import * as plugins from "temp/sitemap-fetcher-plugins";
export interface SitemapFetcherPlugin {
/**
* A function which will be called during page props generation
*/
exec(context?: GetStaticPathsContext): Promise<StaticPath[]>;
}
export class SitecoreSitemapFetcher {... | alues(plugins) as SitemapFetcherPlugin[];
const pluginsResults = await Promise.all(
pluginsList.map((plugin) => plugin.exec(context)),
);
const results = pluginsResults.reduce((acc, cur) => [...acc, ...cur], []);
return results;
}
} | ise<StaticPath[]> {
const pluginsList = Object.v | {
"filepath": "examples/cms-sitecore-xmcloud/src/lib/sitemap-fetcher/index.ts",
"language": "typescript",
"file_size": 952,
"cut_index": 582,
"middle_length": 52
} |
rate, run `npx convex dev`.
* @module
*/
import {
ActionBuilder,
HttpActionBuilder,
MutationBuilder,
QueryBuilder,
GenericActionCtx,
GenericMutationCtx,
GenericQueryCtx,
GenericDatabaseReader,
GenericDatabaseWriter,
} from "convex/server";
import type { DataModel } from "./dataModel.js";
/**
* De... | a query that is only accessible from other Convex functions (but not from the client).
*
* This function will be allowed to read from your Convex database. It will not be accessible from the client.
*
* @param func - The query function. It receives a { | t receives a {@link QueryCtx} as its first argument.
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
*/
export declare const query: QueryBuilder<DataModel, "public">;
/**
* Define | {
"filepath": "examples/convex/convex/_generated/server.d.ts",
"language": "typescript",
"file_size": 5570,
"cut_index": 716,
"middle_length": 229
} |
se the React-specific entry point to import `createApi`
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
interface Quote {
id: number;
quote: string;
author: string;
}
interface QuotesApiResponse {
quotes: Quote[];
total: number;
skip: number;
limit: number;
}
// Define a servi... | no argument, use `void`
// for the argument type instead.
getQuotes: build.query<QuotesApiResponse, number>({
query: (limit = 10) => `?limit=${limit}`,
// `providesTags` determines which 'tag' is attached to the
// cached data re | Tag types are used for caching and invalidation.
tagTypes: ["Quotes"],
endpoints: (build) => ({
// Supply generics for the return type (in this case `QuotesApiResponse`)
// and the expected query argument. If there is | {
"filepath": "examples/with-redux/lib/features/quotes/quotesApiSlice.ts",
"language": "typescript",
"file_size": 1269,
"cut_index": 524,
"middle_length": 229
} |
st { getPublicUrl } = require("@sitecore-jss/sitecore-jss-nextjs");
const plugins = require("./src/temp/next-config-plugins") || {};
const publicUrl = getPublicUrl();
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
// Set assetPrefix to our public URL
assetPrefix: publicUrl,
// Allow specifyi... | locales: ["en"],
// This is the locale that will be used when visiting a non-locale
// prefixed path e.g. `/styleguide`.
defaultLocale: jssConfig.defaultLanguage,
},
// Enable React Strict Mode
reactStrictMode: true,
async rewrites() | client bundle
env: {
PUBLIC_URL: publicUrl,
},
i18n: {
// These are all the locales you want to support in your application.
// These should generally match (or at least be a subset of) those in Sitecore.
| {
"filepath": "examples/cms-sitecore-xmcloud/next.config.js",
"language": "javascript",
"file_size": 2071,
"cut_index": 563,
"middle_length": 229
} |
mage,
Link as JssLink,
RichText as JssRichText,
ImageField,
Field,
LinkField,
Text,
} from "@sitecore-jss/sitecore-jss-nextjs";
interface Fields {
PromoIcon: ImageField;
PromoText: Field<string>;
PromoLink: LinkField;
PromoText2: Field<string>;
}
type PromoProps = {
params: { [key: string]: stri... | <div
className={`component promo ${props.params.styles}`}
id={id ? id : undefined}
>
<div className="component-content">
<div className="field-promoicon">
<JssImage field={props.fields.PromoIcon} />
| nt">
<span className="is-empty-hint">Promo</span>
</div>
</div>
);
export const Default = (props: PromoProps): JSX.Element => {
const id = props.params.RenderingIdentifier;
if (props.fields) {
return (
| {
"filepath": "examples/cms-sitecore-xmcloud/src/components/Promo.tsx",
"language": "tsx",
"file_size": 2390,
"cut_index": 563,
"middle_length": 229
} |
onfig} nextConfig
*/
const graphqlPlugin = (nextConfig = {}) => {
return Object.assign({}, nextConfig, {
webpack: (config, options) => {
config.module.rules.push({
test: /\.graphql$/,
exclude: /node_modules/,
use: [options.defaultLoaders.babel, { loader: "graphql-let/loader" }],
... | use: "yaml-loader",
});
// Overload the Webpack config if it was already overloaded
if (typeof nextConfig.webpack === "function") {
return nextConfig.webpack(config, options);
}
return config;
},
});
};
mod | test: /\.ya?ml$/,
type: "json",
| {
"filepath": "examples/cms-sitecore-xmcloud/src/lib/next-config/plugins/graphql.js",
"language": "javascript",
"file_size": 884,
"cut_index": 547,
"middle_length": 52
} |
LayoutService,
} from "@sitecore-jss/sitecore-jss-nextjs";
import { dictionaryServiceFactory } from "lib/dictionary-service-factory";
import { layoutServiceFactory } from "lib/layout-service-factory";
import { SitecorePageProps } from "lib/page-props";
import { pathExtractor } from "lib/extract-path";
import { Plugi... | t: GetServerSidePropsContext | GetStaticPropsContext,
) {
if (context.preview) return props;
// Get normalized Sitecore item path
const path = pathExtractor.extract(context.params);
// Use context locale if Next.js i18n is configured, o | ervice>;
order = 1;
constructor() {
this.dictionaryServices = new Map<string, DictionaryService>();
this.layoutServices = new Map<string, LayoutService>();
}
async exec(
props: SitecorePageProps,
contex | {
"filepath": "examples/cms-sitecore-xmcloud/src/lib/page-props-factory/plugins/normal-mode.ts",
"language": "typescript",
"file_size": 3116,
"cut_index": 614,
"middle_length": 229
} |
(() => import("react-quill"), {
ssr: false,
loading: () => <p>Loading ...</p>,
});
const modules = {
toolbar: [
[{ header: "1" }, { header: "2" }, { font: [] }],
[{ size: [] }],
["bold", "italic", "underline", "strike", "blockquote"],
[
{ list: "ordered" },
{ list: "bullet" },
{... | ://quilljs.com/docs/formats/
*/
const formats = [
"header",
"font",
"size",
"bold",
"italic",
"underline",
"strike",
"blockquote",
"list",
"bullet",
"indent",
"link",
"image",
"video",
];
export default function Home() {
ret | lse,
},
};
/*
* Quill editor formats
* See https | {
"filepath": "examples/with-quill-js/pages/index.js",
"language": "javascript",
"file_size": 968,
"cut_index": 582,
"middle_length": 52
} |
path from "path";
import { constantCase } from "constant-case";
import { JssConfig, jssConfigFactory } from "./config";
/*
CONFIG GENERATION
Generates the /src/temp/config.js file which contains runtime configuration
that the app can import and use.
*/
const defaultConfig: JssConfig = {
sitecoreApiKey: proce... | object to disk with support for environment variables.
* @param {JssConfig} config JSS configuration to write.
*/
function writeConfig(config: JssConfig): void {
let configText = `/* eslint-disable */
// Do not edit this file, it is auto-generated at | Path: process.env[`${constantCase("graphQLEndpointPath")}`],
defaultLanguage: process.env[`${constantCase("defaultLanguage")}`],
graphQLEndpoint: process.env[`${constantCase("graphQLEndpoint")}`],
};
/**
* Writes the config | {
"filepath": "examples/cms-sitecore-xmcloud/scripts/generate-config.ts",
"language": "typescript",
"file_size": 2114,
"cut_index": 563,
"middle_length": 229
} |
g `jss scaffold <ComponentName>`.
The default convention is that component names must start with a capital letter, and can contain
letters, number, underscores, or dashes.
If the <ComponentName> parameter includes a path, it must be relative to the src/components folder.
For example, `jss scaffold search/Sea... | tSrc from "./templates/component-src";
const componentRootPath = "src/components";
// Matches component names that start with a capital letter, and contain only letters, number,
// underscores, or dashes. Optionally, the component name can be preceded by | if you wish to use your own conventions for component storage in your JSS app.
*/
/* eslint-disable no-throw-literal,no-console */
import fs from "fs";
import path from "path";
import chalk from "chalk";
import generateComponen | {
"filepath": "examples/cms-sitecore-xmcloud/scripts/scaffold-component.ts",
"language": "typescript",
"file_size": 3141,
"cut_index": 614,
"middle_length": 229
} |
int-disable-next-line @typescript-eslint/no-var-requires
const plugins = require("scripts/temp/config-plugins");
/**
* JSS configuration object
*/
export interface JssConfig extends Record<string, string | undefined> {
sitecoreApiKey?: string;
sitecoreApiHost?: string;
jssAppName?: string;
graphQLEndpointPat... | JssConfig): Promise<JssConfig>;
}
export class JssConfigFactory {
public async create(defaultConfig: JssConfig = {}): Promise<JssConfig> {
return (Object.values(plugins) as ConfigPlugin[])
.sort((p1, p2) => p1.order - p2.order)
.reduce( | can be a plugin which data is required for other plugins)
*/
order: number;
/**
* A function which will be called during config generation
* @param {JssConfig} config Current (accumulated) config
*/
exec(config: | {
"filepath": "examples/cms-sitecore-xmcloud/scripts/config/index.ts",
"language": "typescript",
"file_size": 1192,
"cut_index": 518,
"middle_length": 229
} |
rystring";
import * as plugins from "temp/extract-path-plugins";
export interface Plugin {
/**
* A function which will be called during path extraction
*/
exec(path: string): string;
}
export class PathExtractor {
/**
* Extract normalized Sitecore item path
* @param {ParsedUrlQuery} [params]
*/
... | /'
if (!path.startsWith("/")) {
path = "/" + path;
}
const extractedPath = (Object.values(plugins) as Plugin[]).reduce(
(resultPath, plugin) => plugin.exec(resultPath),
path,
);
return extractedPath;
}
}
export co | : (params.path ?? "/");
// Ensure leading ' | {
"filepath": "examples/cms-sitecore-xmcloud/src/lib/extract-path/index.ts",
"language": "typescript",
"file_size": 896,
"cut_index": 547,
"middle_length": 52
} |
;
import {
ComponentParams,
ComponentRendering,
Placeholder,
useSitecoreContext,
} from "@sitecore-jss/sitecore-jss-nextjs";
const BACKGROUND_REG_EXP = new RegExp(
/[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/gi,
);
interface ComponentProps {
rendering: ComponentRendering & { p... | t id = props.params.RenderingIdentifier;
let backgroundImage = props.params.BackgroundImage as string;
let backgroundStyle: { [key: string]: string } = {};
if (backgroundImage) {
const prefix = `${
sitecoreContext.pageState !== "normal" ? | Styles =
props.params && props.params.Styles ? props.params.Styles : "";
const styles = `${props.params.GridParameters} ${containerStyles}`.trimEnd();
const phKey = `container-${props.params.DynamicPlaceholderId}`;
cons | {
"filepath": "examples/cms-sitecore-xmcloud/src/components/Container.tsx",
"language": "tsx",
"file_size": 1949,
"cut_index": 537,
"middle_length": 229
} |
mage,
Link as JssLink,
ImageField,
Field,
LinkField,
Text,
useSitecoreContext,
} from "@sitecore-jss/sitecore-jss-nextjs";
interface Fields {
Image: ImageField;
ImageCaption: Field<string>;
TargetUrl: LinkField;
}
type ImageProps = {
params: { [key: string]: string };
fields: Fields;
};
const I... | .Image?.value?.src}')`,
};
const modifyImageProps = {
...props.fields.Image,
editable: props?.fields?.Image?.editable
?.replace(`width="${props?.fields?.Image?.value?.width}"`, 'width="100%"')
.replace(
`height="${props?.fie | ty-hint">Image</span>
</div>
</div>
);
export const Banner = (props: ImageProps): JSX.Element => {
const { sitecoreContext } = useSitecoreContext();
const backgroundStyle = {
backgroundImage: `url('${props?.fields? | {
"filepath": "examples/cms-sitecore-xmcloud/src/components/Image.tsx",
"language": "tsx",
"file_size": 2421,
"cut_index": 563,
"middle_length": 229
} |
nk,
Text,
LinkField,
TextField,
} from "@sitecore-jss/sitecore-jss-nextjs";
type ResultsFieldLink = {
field: {
link: LinkField;
};
};
interface Fields {
data: {
datasource: {
children: {
results: ResultsFieldLink[];
};
field: {
title: TextField;
};
};
... | 1 === props.total) {
className += " last";
}
return (
<li className={className}>
<div className="field-link">
<JssLink field={props.field} />
</div>
</li>
);
};
export const Default = (props: LinkListProps): JSX.Elem | t LinkListItem = (props: LinkListItemProps) => {
let className = `item${props.index}`;
className += (props.index + 1) % 2 === 0 ? " even" : " odd";
if (props.index === 0) {
className += " first";
}
if (props.index + | {
"filepath": "examples/cms-sitecore-xmcloud/src/components/LinkList.tsx",
"language": "tsx",
"file_size": 2028,
"cut_index": 563,
"middle_length": 229
} |
;
import {
RichText as JssRichText,
useSitecoreContext,
RichTextField,
} from "@sitecore-jss/sitecore-jss-nextjs";
interface Fields {
Content: RichTextField;
}
type PageContentProps = {
params: { [key: string]: string };
fields: Fields;
};
type ComponentContentProps = {
id: string;
styles: string;
... | => {
const { sitecoreContext } = useSitecoreContext();
const id = props.params.RenderingIdentifier;
if (
!(props.fields && props.fields.Content) &&
!sitecoreContext?.route?.fields?.Content
) {
return (
<div
className={`co | d={id ? id : undefined}
>
<div className="component-content">
<div className="field-content">{props.children}</div>
</div>
</div>
);
};
export const Default = (props: PageContentProps): JSX.Element | {
"filepath": "examples/cms-sitecore-xmcloud/src/components/PageContent.tsx",
"language": "tsx",
"file_size": 1543,
"cut_index": 537,
"middle_length": 229
} |
itecore-jss/sitecore-jss-nextjs";
import config from "temp/config";
/**
* Factory responsible for creating a LayoutService instance
*/
export class LayoutServiceFactory {
/**
* @param {string} siteName site name
* @returns {LayoutService} service instance
*/
create(siteName: string): LayoutService {
... | ({
apiHost: config.sitecoreApiHost,
apiKey: config.sitecoreApiKey,
siteName,
configurationName: "default",
});
}
}
/** LayoutServiceFactory singleton */
export const layoutServiceFactory = new LayoutServic | siteName,
})
: new RestLayoutService | {
"filepath": "examples/cms-sitecore-xmcloud/src/lib/layout-service-factory.ts",
"language": "typescript",
"file_size": 926,
"cut_index": 606,
"middle_length": 52
} |
ort { SiteInfo } from "@sitecore-jss/sitecore-jss-nextjs";
import { editingDataService } from "@sitecore-jss/sitecore-jss-nextjs/editing";
import { SitecorePageProps } from "lib/page-props";
import { GetServerSidePropsContext, GetStaticPropsContext } from "next";
import { Plugin } from "..";
class PreviewModePlugin im... | get editing data for preview ${JSON.stringify(
context.previewData,
)}`,
);
}
props.site = data.layoutData.sitecore.context.site as SiteInfo;
props.locale = data.language;
props.layoutData = data.layoutData;
prop | / If we're in preview (editing) mode, use data already sent along with the editing request
const data = await editingDataService.getEditingData(context.previewData);
if (!data) {
throw new Error(
`Unable to | {
"filepath": "examples/cms-sitecore-xmcloud/src/lib/page-props-factory/plugins/preview-mode.ts",
"language": "typescript",
"file_size": 1116,
"cut_index": 515,
"middle_length": 229
} |
name: string;
components: {
moduleName: string;
componentName: string;
}[];
}
const isLazyLoadingModule = (componentPath: string) =>
componentPath.includes(".dynamic");
const removeDynamicModuleNameEnding = (moduleName: string) =>
moduleName.replace(/\.?dynamic$/i, "");
/**
* Generates the contents... | ponents.filter(
(component) => (component as PackageDefinition).components,
) as PackageDefinition[];
const hasLazyModules = componentFiles.find((component) =>
isLazyLoadingModule(component.path),
);
return `/* eslint-disable */
// Do not | teComponentFactory(
components: (PackageDefinition | ComponentFile)[],
): string {
const componentFiles = components.filter(
(component) => (component as ComponentFile).path,
) as ComponentFile[];
const packages = com | {
"filepath": "examples/cms-sitecore-xmcloud/scripts/templates/component-factory.ts",
"language": "typescript",
"file_size": 5100,
"cut_index": 716,
"middle_length": 229
} |
t {
SiteInfo,
SiteResolver,
} from "@sitecore-jss/sitecore-jss-nextjs/middleware";
import * as plugins from "temp/site-resolver-plugins";
/*
The site resolver stores site information and is used in the app
whenever site lookup is required (e.g. by name in page props factory
or by host in Next.js middleware).... | which will be called during sites collection
*/
exec(sites: SiteInfo[]): SiteInfo[];
}
const sites = (Object.values(plugins) as SiteResolverPlugin[]).reduce(
(sites, plugin) => plugin.exec(sites),
[],
);
export const siteResolver = new SiteReso | * A function | {
"filepath": "examples/cms-sitecore-xmcloud/src/lib/site-resolver/index.ts",
"language": "typescript",
"file_size": 800,
"cut_index": 517,
"middle_length": 14
} |
t {
Text,
RichText,
Field,
withDatasourceCheck,
} from "@sitecore-jss/sitecore-jss-nextjs";
import { ComponentProps } from "lib/component-props";
type ContentBlockProps = ComponentProps & {
fields: {
heading: Field<string>;
content: Field<string>;
};
};
/**
* A simple Content Block component, wit... | Element => (
<div className="contentBlock">
<Text tag="h2" className="contentTitle" field={fields.heading} />
<RichText className="contentDescription" field={fields.content} />
</div>
);
export default withDatasourceCheck()<ContentBlockProps> | ckProps): JSX. | {
"filepath": "examples/cms-sitecore-xmcloud/src/components/ContentBlock.tsx",
"language": "tsx",
"file_size": 803,
"cut_index": 517,
"middle_length": 14
} |
ded for Starter Kit.
*/
import React from "react";
import Head from "next/head";
import {
Placeholder,
getPublicUrl,
LayoutServiceData,
Field,
} from "@sitecore-jss/sitecore-jss-nextjs";
import Scripts from "src/Scripts";
// Prefix public assets with a public URL to enable compatibility with Sitecore Experien... | = layoutData.sitecore.context.pageEditing;
const mainClassPageEditing = isPageEditing ? "editing-mode" : "prod-mode";
return (
<>
<Scripts />
<Head>
<title>{fields?.Title?.value?.toString() || "Page"}</title>
<link rel= | eFields {
[key: string]: unknown;
Title?: Field;
}
const Layout = ({ layoutData }: LayoutProps): JSX.Element => {
const { route } = layoutData.sitecore;
const fields = route?.fields as RouteFields;
const isPageEditing | {
"filepath": "examples/cms-sitecore-xmcloud/src/Layout.tsx",
"language": "tsx",
"file_size": 1742,
"cut_index": 537,
"middle_length": 229
} |
onnect from "next-connect";
import auth from "../../middleware/auth";
import { deleteUser, createUser, updateUserByUsername } from "../../lib/db";
const handler = nextConnect();
handler
.use(auth)
.get((req, res) => {
// You do not generally want to return the whole user object
// because it may contain s... |
})
.use((req, res, next) => {
// handlers after this (PUT, DELETE) all require an authenticated user
// This middleware to check if user is authenticated before continuing
if (!req.user) {
res.status(401).send("unauthenticated");
| son({ user: req.user });
})
.post((req, res) => {
const { username, password, name } = req.body;
createUser(req, { username, password, name });
res.status(200).json({ success: true, message: "created new user" }); | {
"filepath": "examples/with-passport-and-next-connect/pages/api/user.js",
"language": "javascript",
"file_size": 1323,
"cut_index": 524,
"middle_length": 229
} |
phQLRequestClient } from "@sitecore-jss/sitecore-jss-nextjs";
import fs from "fs";
import { getIntrospectionQuery } from "graphql";
// This script load graphql introspection data in order to use graphql code generator and generate typescript types
// The `jss graphql:update` command should be executed when Sitecore te... | int}...`,
);
const client = new GraphQLRequestClient(jssConfig.graphQLEndpoint, {
apiKey: jssConfig.sitecoreApiKey,
});
client
.request(getIntrospectionQuery())
.then((result) => {
fs.writeFile(
"./src/temp/GraphQLIntrospectionResult.json | JSS config. Ensure `jss setup` has been run, and the app has been started at least once after setup.",
);
console.error(e);
process.exit(1);
}
console.log(
`Fetch graphql introspection data from ${jssConfig.graphQLEndpo | {
"filepath": "examples/cms-sitecore-xmcloud/scripts/fetch-graphql-introspection-data.ts",
"language": "typescript",
"file_size": 1356,
"cut_index": 524,
"middle_length": 229
} |
oreContext,
} from "@sitecore-jss/sitecore-jss-nextjs";
interface Fields {
Id: string;
DisplayName: string;
Title: TextField;
NavigationTitle: TextField;
Href: string;
Querystring: string;
Children: Array<Fields>;
Styles: string[];
}
type NavigationProps = {
params?: { [key: string]: string };
fie... | .DisplayName;
}
return text;
};
const getLinkTitle = (props: NavigationProps): string | undefined => {
let title;
if (props.fields.NavigationTitle?.value) {
title = props.fields.NavigationTitle.value.toString();
} else if (props.fields.Titl | {
let text;
if (props.fields.NavigationTitle) {
text = <Text field={props.fields.NavigationTitle} />;
} else if (props.fields.Title) {
text = <Text field={props.fields.Title} />;
} else {
text = props.fields | {
"filepath": "examples/cms-sitecore-xmcloud/src/components/Navigation.tsx",
"language": "tsx",
"file_size": 4280,
"cut_index": 614,
"middle_length": 229
} |
sitecore-jss/sitecore-jss-nextjs";
import config from "temp/config";
import { SitemapFetcherPlugin } from "..";
import { GetStaticPathsContext } from "next";
class GraphqlSitemapServicePlugin implements SitemapFetcherPlugin {
_graphqlSitemapService: GraphQLSitemapService;
constructor() {
this._graphqlSitemapS... | cess.env.JSS_MODE === constants.JSS_MODE.DISCONNECTED) {
return [];
}
return process.env.EXPORT_MODE
? this._graphqlSitemapService.fetchExportSitemap(config.defaultLanguage)
: this._graphqlSitemapService.fetchSSGSitemap(context?.l | icPathsContext): Promise<StaticPath[]> {
if (pro | {
"filepath": "examples/cms-sitecore-xmcloud/src/lib/sitemap-fetcher/plugins/graphql-sitemap-service.ts",
"language": "typescript",
"file_size": 990,
"cut_index": 582,
"middle_length": 52
} |
;
import {
ComponentParams,
ComponentRendering,
Placeholder,
} from "@sitecore-jss/sitecore-jss-nextjs";
interface ComponentProps {
rendering: ComponentRendering & { params: ComponentParams };
params: ComponentParams;
}
export const Default = (props: ComponentProps): JSX.Element => {
const styles = `${pro... | arams.Styles2,
props.params.Styles3,
props.params.Styles4,
props.params.Styles5,
props.params.Styles6,
props.params.Styles7,
props.params.Styles8,
];
const enabledPlaceholders = props.params.EnabledPlaceholders.split(",");
con | idth3,
props.params.ColumnWidth4,
props.params.ColumnWidth5,
props.params.ColumnWidth6,
props.params.ColumnWidth7,
props.params.ColumnWidth8,
];
const columnStyles = [
props.params.Styles1,
props.p | {
"filepath": "examples/cms-sitecore-xmcloud/src/components/ColumnSplitter.tsx",
"language": "tsx",
"file_size": 1720,
"cut_index": 537,
"middle_length": 229
} |
le,
MDBCol,
MDBContainer,
MDBFooter,
MDBRow,
} from "mdbreact";
export default function Home() {
return (
<>
<Head>
<title>Next.js with Material Design Bootstrap for React</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<MDBContainer className="text-center mt-5">... | <MDBCardText>
Find in-depth information about Next.js features and API.
</MDBCardText>
<MDBBtn
color="primary"
size="sm"
className="text-cap | iting <code>pages/index.js</code>
</p>
<MDBRow>
<MDBCol sm="6">
<MDBCard className="my-3">
<MDBCardBody>
<MDBCardTitle tag="h5">Documentation</MDBCardTitle>
| {
"filepath": "examples/with-mdbreact/pages/index.js",
"language": "javascript",
"file_size": 3787,
"cut_index": 614,
"middle_length": 229
} |
port type { Types } from "ably";
import type { ProxyMessage, TextMessage } from "../types";
import Head from "next/head";
import Image from "next/image";
import styles from "../styles/Home.module.css";
export default function Home() {
const [messages, setMessages] = useState<TextMessage[]>([]);
const [channel, a... | = presenceData.map((msg, index) => (
<li key={index}>
{msg.clientId}: {msg.data}
</li>
));
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<meta name="description" content="Gene | ata]);
},
);
const [presenceData, updateStatus] = usePresence("your-channel-name");
const messageList = messages.map((message, index) => {
return <li key={index}>{message.text}</li>;
});
const presentClients | {
"filepath": "examples/with-ably/pages/index.tsx",
"language": "tsx",
"file_size": 3158,
"cut_index": 614,
"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-umbraco-heartcore/tailwind.config.js",
"language": "javascript",
"file_size": 791,
"cut_index": 514,
"middle_length": 14
} |
ql.umbraco.io", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Api-Key": process.env.UMBRACO_API_KEY,
"Umb-Project-Alias": process.env.UMBRACO_PROJECT_ALIAS,
},
body: JSON.stringify({
query,
variables,
}),
});
const json = await res.json();
if ... | }
export async function getAllPostsWithSlug() {
const data = await fetchAPI(`
{
allPost {
edges {
node {
slug:url
}
}
}
}
`);
return data.allPost.edges.map((x) => x.node);
}
export | fetchAPI(
`
query PostBySlug($slug: String!) {
post(url: $slug, preview: true) {
slug:url
}
}`,
{
preview: true,
variables: {
slug,
},
},
);
return data.post;
| {
"filepath": "examples/cms-umbraco-heartcore/lib/umbraco-heartcore.js",
"language": "javascript",
"file_size": 3408,
"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 hover:text-success | href="/api/exit-preview"
className="underline hover:text-cyan duration-200 transition-colors"
>
Click here
</a>{" "}
to exit preview mode.
| {
"filepath": "examples/cms-umbraco-heartcore/components/alert.js",
"language": "javascript",
"file_size": 1203,
"cut_index": 518,
"middle_length": 229
} |
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-... | er 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/ | flex 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 bord | {
"filepath": "examples/cms-umbraco-heartcore/components/footer.js",
"language": "javascript",
"file_size": 1210,
"cut_index": 518,
"middle_length": 229
} |
import Avatar from "../components/avatar";
import Date from "../components/date";
import CoverImage from "../components/cover-image";
import Link from "next/link";
export default function HeroPost({
title,
coverImage,
date,
excerpt,
author,
slug,
}) {
return (
<section>
<div className="mb-8 md:... | >
<Date dateString={date} />
</div>
</div>
<div>
<p className="mb-4 text-lg leading-relaxed">{excerpt}</p>
<Avatar name={author.name} picture={author.picture.url} />
</div>
</div>
| <h3 className="mb-4 text-4xl leading-tight lg:text-6xl">
<Link href={slug} className="hover:underline">
{title}
</Link>
</h3>
<div className="mb-4 text-lg md:mb-0" | {
"filepath": "examples/cms-umbraco-heartcore/components/hero-post.js",
"language": "javascript",
"file_size": 1015,
"cut_index": 512,
"middle_length": 229
} |
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>
) | xt-success duration-200 transition-colors"
> | {
"filepath": "examples/cms-umbraco-heartcore/components/intro.js",
"language": "javascript",
"file_size": 847,
"cut_index": 535,
"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/ | />
<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-umbraco-heartcore/components/meta.js",
"language": "javascript",
"file_size": 1255,
"cut_index": 524,
"middle_length": 229
} |
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... | sName="max-w-2xl mx-auto">
<div className="block mb-6 md:hidden">
<Avatar name={author.name} picture={author.picture.url} />
</div>
<div className="mb-6 text-lg">
<Date dateString={date} />
</div>
< | url={coverImage.url} />
</div>
<div clas | {
"filepath": "examples/cms-umbraco-heartcore/components/post-header.js",
"language": "javascript",
"file_size": 858,
"cut_index": 529,
"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-separator";
im... | ;
}
return (
<Layout preview={preview}>
<Container>
<Header />
{router.isFallback ? (
<PostTitle>Loading…</PostTitle>
) : (
<>
<article>
<Head>
<title>
| xt/head";
import { CMS_NAME } from "lib/constants";
export default function Post({ post, morePosts, preview }) {
const router = useRouter();
if (!router.isFallback && !post?.slug) {
return <ErrorPage statusCode={404} /> | {
"filepath": "examples/cms-umbraco-heartcore/pages/[...slug].js",
"language": "javascript",
"file_size": 2095,
"cut_index": 563,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.