diff --git a/templates/ecommerce/.editorconfig b/templates/ecommerce/.editorconfig deleted file mode 100644 index d8e085abcb2..00000000000 --- a/templates/ecommerce/.editorconfig +++ /dev/null @@ -1,10 +0,0 @@ -root = true - -[*] -indent_style = space -indent_size = 2 -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true -end_of_line = lf -max_line_length = null diff --git a/templates/ecommerce/.env.example b/templates/ecommerce/.env.example deleted file mode 100644 index 6803b5ad261..00000000000 --- a/templates/ecommerce/.env.example +++ /dev/null @@ -1,31 +0,0 @@ -# Run on a specific port -PORT=3000 - -# Database connection string -DATABASE_URI=mongodb://127.0.0.1/payload-template-ecommerce - -# Used to encrypt JWT tokens -PAYLOAD_SECRET=YOUR_SECRET_HERE - -# Used to format links and URLs -PAYLOAD_PUBLIC_SERVER_URL=http://localhost:3000 -NEXT_PUBLIC_SERVER_URL=http://localhost:3000 - -# Enable Stripe integration -STRIPE_SECRET_KEY= -PAYLOAD_PUBLIC_STRIPE_IS_TEST_KEY=true -NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY= - -# Enable Stripe webhooks (optional) -STRIPE_WEBHOOKS_SIGNING_SECRET= - -# Allow robots to index the site (optional) -NEXT_PUBLIC_IS_LIVE= - -# Used to preview drafts -PAYLOAD_PUBLIC_DRAFT_SECRET=demo-draft-secret -NEXT_PRIVATE_DRAFT_SECRET=demo-draft-secret - -# Used to revalidate static pages -REVALIDATION_KEY=demo-revalation-key -NEXT_PRIVATE_REVALIDATION_KEY=demo-revalation-key diff --git a/templates/ecommerce/.eslintrc.cjs b/templates/ecommerce/.eslintrc.cjs deleted file mode 100644 index cbb655ef53a..00000000000 --- a/templates/ecommerce/.eslintrc.cjs +++ /dev/null @@ -1,38 +0,0 @@ -/** @type {import('eslint').Linter.Config} */ -module.exports = { - extends: ['plugin:@next/next/recommended', '@payloadcms'], - ignorePatterns: ['**/payload-types.ts'], - overrides: [ - { - extends: ['plugin:@typescript-eslint/disable-type-checked'], - files: ['*.js', '*.cjs', '*.json', '*.md', '*.yml', '*.yaml'], - }, - { - files: ['package.json', 'tsconfig.json'], - rules: { - 'perfectionist/sort-array-includes': 'off', - 'perfectionist/sort-astro-attributes': 'off', - 'perfectionist/sort-classes': 'off', - 'perfectionist/sort-enums': 'off', - 'perfectionist/sort-exports': 'off', - 'perfectionist/sort-imports': 'off', - 'perfectionist/sort-interfaces': 'off', - 'perfectionist/sort-jsx-props': 'off', - 'perfectionist/sort-keys': 'off', - 'perfectionist/sort-maps': 'off', - 'perfectionist/sort-named-exports': 'off', - 'perfectionist/sort-named-imports': 'off', - 'perfectionist/sort-object-types': 'off', - 'perfectionist/sort-objects': 'off', - 'perfectionist/sort-svelte-attributes': 'off', - 'perfectionist/sort-union-types': 'off', - 'perfectionist/sort-vue-attributes': 'off', - }, - }, - ], - parserOptions: { - project: ['./tsconfig.json'], - tsconfigRootDir: __dirname, - }, - root: true, -} diff --git a/templates/ecommerce/.gitignore b/templates/ecommerce/.gitignore deleted file mode 100644 index 1bbe951cc3e..00000000000 --- a/templates/ecommerce/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -build -dist -/media -node_modules -.DS_Store -.env -.next -.vercel diff --git a/templates/ecommerce/.prettierignore b/templates/ecommerce/.prettierignore deleted file mode 100644 index 996b10e1585..00000000000 --- a/templates/ecommerce/.prettierignore +++ /dev/null @@ -1,14 +0,0 @@ -**/payload-types.ts -.tmp -**/.git -**/.hg -**/.pnp.* -**/.svn -**/.yarn/** -**/build -**/dist/** -**/node_modules -**/temp -**/docs/** -tsconfig.json - diff --git a/templates/ecommerce/.prettierrc.json b/templates/ecommerce/.prettierrc.json deleted file mode 100644 index cb8ee2671df..00000000000 --- a/templates/ecommerce/.prettierrc.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "singleQuote": true, - "trailingComma": "all", - "printWidth": 100, - "semi": false -} diff --git a/templates/ecommerce/.vscode/launch.json b/templates/ecommerce/.vscode/launch.json deleted file mode 100644 index 35316d56d8d..00000000000 --- a/templates/ecommerce/.vscode/launch.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - // Use IntelliSense to learn about possible attributes. - // Hover to view descriptions of existing attributes. - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", - "configurations": [ - { - "command": "yarn dev", - "name": "Debug Ecommerce", - "request": "launch", - "type": "node-terminal" - } - ] -} diff --git a/templates/ecommerce/Dockerfile b/templates/ecommerce/Dockerfile deleted file mode 100644 index 27ace7fb4ca..00000000000 --- a/templates/ecommerce/Dockerfile +++ /dev/null @@ -1,27 +0,0 @@ -FROM node:18.8-alpine as base - -FROM base as builder - -WORKDIR /home/node/app -COPY package*.json ./ - -COPY . . -RUN yarn install -RUN yarn build - -FROM base as runtime - -ENV NODE_ENV=production -ENV PAYLOAD_CONFIG_PATH=dist/payload.config.js - -WORKDIR /home/node/app -COPY package*.json ./ -COPY yarn.lock ./ - -RUN yarn install --production -COPY --from=builder /home/node/app/dist ./dist -COPY --from=builder /home/node/app/build ./build - -EXPOSE 3000 - -CMD ["node", "dist/server.js"] diff --git a/templates/ecommerce/README.md b/templates/ecommerce/README.md deleted file mode 100644 index 9fb2481aab7..00000000000 --- a/templates/ecommerce/README.md +++ /dev/null @@ -1,329 +0,0 @@ -# Payload E-Commerce Template - -This is the official [Payload E-Commerce Template](https://github.com/payloadcms/payload/blob/main/templates/ecommerce). Use it to power e-commerce businesses and online stores of all sizes. This repo includes a fully-working backend, enterprise-grade admin panel, and a beautifully designed, production-ready website. - -This template is right for you if you are selling: - -- Physical products like clothing or merchandise -- Digital assets like ebooks or videos -- Access to content like courses or premium articles - -Core features: - -- [Pre-configured Payload Config](#how-it-works) -- [Authentication](#users-authentication) -- [Access Control](#access-control) -- [Shopping Cart](#shopping-cart) -- [Checkout](#checkout) -- [Paywall](#paywall) -- [Layout Builder](#layout-builder) -- [SEO](#seo) -- [Website](#website) - -## Quick Start - -To spin up this example locally, follow these steps: - -### Clone - -If you have not done so already, you need to have standalone copy of this repo on your machine. If you've already cloned this repo, skip to [Development](#development). - -#### Method 1 (recommended) - -Go to Payload Cloud and [clone this template](https://payloadcms.com/new/clone/ecommerce). This will create a new repository on your GitHub account with this template's code which you can then clone to your own machine. - -#### Method 2 - -Use the `create-payload-app` CLI to clone this template directly to your machine: - - npx create-payload-app@latest my-project -t ecommerce - -#### Method 3 - -Use the `git` CLI to clone this template directly to your machine: - - git clone -n --depth=1 --filter=tree:0 https://github.com/payloadcms/payload my-project && cd my-project && git sparse-checkout set --no-cone templates/ecommerce && git checkout && rm -rf .git && git init && git add . && git mv -f templates/ecommerce/{.,}* . && git add . && git commit -m "Initial commit" - -### Development - -1. First [clone the repo](#clone) if you have not done so already -1. `cd my-project && cp .env.example .env` to copy the example environment variables -1. `yarn && yarn dev` to install dependencies and start the dev server -1. `open http://localhost:3000` to open the app in your browser - -That's it! Changes made in `./src` will be reflected in your app. Follow the on-screen instructions to login and create your first admin user. To begin accepting payment, follow the [Stripe](#stripe) guide. Then check out [Production](#production) once you're ready to build and serve your app, and [Deployment](#deployment) when you're ready to go live. - -## How it works - -The Payload config is tailored specifically to the needs of most e-commerce businesses. It is pre-configured in the following ways: - -### Collections - -See the [Collections](https://payloadcms.com/docs/configuration/collections) docs for details on how to extend this functionality. - -- #### Users (Authentication) - - Users are auth-enabled and encompass both admins and customers based on the value of their `roles` field. Only `admin` users can access your admin panel to manage your store whereas `customer` can authenticate on your front-end to create [shopping carts](#shopping-cart) and place [orders](#orders) but have limited access to the platform. See [Access Control](#access-control) for more details. - - For additional help, see the official [Auth Example](https://github.com/payloadcms/payload/tree/main/examples/auth) or the [Authentication](https://payloadcms.com/docs/authentication/overview#authentication-overview) docs. - -- #### Products - - Products are linked to Stripe via a custom select field that is dynamically populated in the sidebar of each product. This field fetches all available products in the background and displays them as options. Once a product has been selected, prices get automatically synced between Stripe and Payload through [Payload Hooks](https://payloadcms.com/docs/hooks) and [Stripe Webhooks](https://stripe.com/docs/webhooks). See [Stripe](#stripe) for more details. - - All products are layout builder enabled so you can generate unique pages for each product using layout building blocks, see [Layout Builder](#layout-builder) for more details. - - Products can also restrict access to content or digital assets behind a paywall (gated content), see [Paywall](#paywall) for more details. - -- #### Orders - - Orders are created when a user successfully completes a checkout. They contain all the data about the order including the products purchased, the total price, and the user who placed the order. See [Checkout](#checkout) for more details. - -- #### Pages - - All pages are layout builder enabled so you can generate unique layouts for each page using layout-building blocks, see [Layout Builder](#layout-builder) for more details. - -- #### Media - - This is the uploads enabled collection used by products and pages to contain media like images, videos, downloads, and other assets. - -- #### Categories - - A taxonomy used to group products together. Categories can be nested inside of one another, for example "Courses > Technology". See the official [Payload Nested Docs Plugin](https://github.com/payloadcms/plugin-nested-docs) for more details. - -### Globals - -See the [Globals](https://payloadcms.com/docs/configuration/globals) docs for details on how to extend this functionality. - -- `Header` - - The data required by the header on your front-end like nav links. - -- `Footer` - - Same as above but for the footer of your site. - -## Access control - -Basic role-based access control is setup to determine what users can and cannot do based on their roles, which are: - -- `admin`: They can access the Payload admin panel to manage your store. They can see all data and make all operations. -- `customer`: They cannot access the Payload admin panel and can perform limited operations based on their user (see below). - -This applies to each collection in the following ways: - -- `users`: Only admins and the user themselves can access their profile. Anyone can create a user but only admins can delete users. -- `products`: Everyone can access products, but only admins can create, update, or delete them. Paywall-enabled products may also have content that is only accessible to only users who have purchased the product. See [Paywall](#paywall) for more details. - -For more details on how to extend this functionality, see the [Payload Access Control](https://payloadcms.com/docs/access-control/overview#access-control) docs. - -## Shopping cart - -Logged-in users can have their shopping carts saved to their profiles as they shop. This way they can continue shopping at a later date or on another device. When not logged in, the cart can be saved to local storage and synced to Payload on the next login. This works by maintaining a `cart` field on the `user`: - -```ts -{ - name: 'cart', - label: 'Shopping Cart', - type: 'object', - fields: [ - { - name: 'items', - label: 'Items', - type: 'array', - fields: [ - // product, quantity, etc - ] - }, - // other metadata like `createdOn`, etc - ] -} -``` - -## Stripe - -Payload itself handles no currency exchange. All payments are processed and billed using [Stripe](https://stripe.com). This means you must have access to a Stripe account via an API key, see [Connect Stripe](#connect-stripe) for how to get one. When you create a product in Payload that you wish to sell, it must be connected to a Stripe product by selecting one from the field in the product's sidebar, see [Products](#products) for more details. Once set, data is automatically synced between the two platforms in the following ways: - -1. Stripe to Payload using [Stripe Webhooks](https://stripe.com/docs/webhooks): - - - `product.created` - - `product.updated` - - `price.updated` - -1. Payload to Stripe using [Payload Hooks](https://payloadcms.com/docs/hooks/overview): - - `user.create` - -For more details on how to extend this functionality, see the the official [Payload Stripe Plugin](https://github.com/payloadcms/plugin-stripe). - -### Connect Stripe - -To integrate with Stripe, follow these steps: - -1. You will first need to create a [Stripe](https://stripe.com) account if you do not already have one. -1. Retrieve your [Stripe API keys](https://dashboard.stripe.com/test/apikeys) and paste them into your `env`: - ```bash - STRIPE_SECRET_KEY= - NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY= - ``` -1. In another terminal, listen for webhooks (optional): - ```bash - stripe login # follow the prompts - yarn stripe:webhooks - ``` -1. Paste the given webhook signing secret into your `env`: - ```bash - STRIPE_WEBHOOKS_SIGNING_SECRET= - ``` -1. Reboot Payload to ensure that Stripe connects and the webhooks are registered. - -## Checkout - -A custom endpoint is opened at `POST /api/create-payment-intent` which initiates the checkout process. This endpoint totals your cart and creates a [Stripe Payment Intent](https://stripe.com/docs/payments/payment-intents). The total price is recalculated on the server to ensure accuracy and security, and once completed, passes the `client_secret` back in the response for your front-end to finalize the payment. Once the payment has succeeded, an [Order](#orders) will be created in Payload with a `stripePaymentIntentID`. Each purchased product will be recorded to the user's profile, and the user's cart will be automatically cleared. - -## Paywall - -Products can optionally restrict access to content or digital assets behind a paywall. This will require the product to be purchased before it's data and resources are accessible. To do this, a `purchases` field is maintained on each user to track their purchase history: - -```ts -{ - name: 'purchases', - label: 'Purchases', - type: 'array', - fields: [ - { - name: 'product', - label: 'Product', - type: 'relationship', - relationTo: 'products', - }, - // other metadata like `createdOn`, etc - ] -} -``` - -Then, a `paywall` field is added to the `product` with `read` access control set to check for associated purchases. Every time a user requests a product, this will only return data to those who have purchased it: - -```ts -{ - name: 'paywall', - label: 'Paywall', - type: 'blocks', - access: { - read: checkUserPurchases, - }, - fields: [ - // assets - ] -} -``` - -## Layout Builder - -Create unique product and page layouts for any type fo content using a powerful layout builder. This template comes pre-configured with the following layout building blocks: - -- Hero -- Content -- Media -- Call To Action -- Archive - -Each block is fully designed and built into the front-end website that comes with this template. See [Website](#website) for more details. - -## Draft Preview - -All pages and products are draft-enabled so you can preview them before publishing them to your website. To do this, these collections use [Versions](https://payloadcms.com/docs/configuration/collections#versions) with `drafts` set to `true`. This means that when you create a new page or product, it will be saved as a draft and will not be visible on your website until you publish it. This also means that you can preview your draft before publishing it to your website. To do this, we automatically format a custom URL which redirects to your front-end to securely fetch the draft version of your content. - -Since the front-end of this template is statically generated, this also means that pages and products will need to be regenerated as changes are made to published documents. To do this, we use an `afterChange` hook to regenerate the front-end when a document has changed and its `_status` is `published`. - -For more details on how to extend this functionality, see the official [Draft Preview Example](https://github.com/payloadcms/payload/tree/main/examples/draft-preview). - -## SEO - -This template comes pre-configured with the official [Payload SEO Plugin](https://github.com/payloadcms/plugin-seo) for complete SEO control from the admin panel. All SEO data is fully integrated into the front-end website that comes with this template. See [Website](#website) for more details. - -## Redirects - -If you are migrating an existing site or moving content to a new URL, you can use the `redirects` collection to create a proper redirect from old URLs to new ones. This will ensure that proper request status codes are returned to search engines and that your users are not left with a broken link. This template comes pre-configured with the official [Payload Redirects Plugin](https://github.com/payloadcms/plugin-redirects) for complete redirect control from the admin panel. All redirects are fully integrated into the front-end website that comes with this template. See [Website](#website) for more details. - -## Website - -This template includes a beautifully designed, production-ready front-end built with the [Next.js App Router](https://nextjs.org), served right alongside your Payload app in a single Express server. This makes is so that you can deploy both apps simultaneously and host them together. If you prefer a different front-end framework, this pattern works for any framework that supports a custom server. If you prefer to host your website separately from Payload, you can easily [Eject](#eject) the front-end out from this template to swap in your own, or to use it as a standalone CMS. For more details, see the official [Custom Server Example](https://github.com/payloadcms/payload/tree/main/examples/custom-server). - -Core features: - -- [Next.js App Router](https://nextjs.org) -- [Stripe](https://stripe.com) -- [GraphQL](https://graphql.org) -- [TypeScript](https://www.typescriptlang.org) -- [React Hook Form](https://react-hook-form.com) -- [Payload Admin Bar](https://github.com/payloadcms/payload-admin-bar) -- Authentication -- Publication workflow -- Shopping cart -- Checkout -- Customer accounts -- Dark mode -- Pre-made layout building blocks -- SEO -- Redirects -- Paywall - -### Cache - -Although Next.js includes a robust set of caching strategies out of the box, Payload Cloud proxies and caches all files through Cloudflare using the [Official Cloud Plugin](https://github.com/payloadcms/plugin-cloud). This means that Next.js caching is not needed and is disabled by default. If you are hosting your app outside of Payload Cloud, you can easily reenable the Next.js caching mechanisms by removing the `no-store` directive from all fetch requests in `./src/app/_api` and then removing all instances of `export const dynamic = 'force-dynamic'` from pages files, such as `./src/app/(pages)/[slug]/page.tsx`. For more details, see the official [Next.js Caching Docs](https://nextjs.org/docs/app/building-your-application/caching). - -### Eject - -If you prefer another front-end framework or would like to use Payload as a standalone CMS, you can easily eject the front-end from this template. To eject, simply run `yarn eject`. This will uninstall all Next.js related dependencies and delete all files and folders related to the Next.js front-end. It also removes all custom routing from your `server.ts` file and updates your `eslintrc.js`. - -> Note: Your eject script may not work as expected if you've made significant modifications to your project. If you run into any issues, compare your project's dependencies and file structure with this template. See [./src/eject](./src/eject) for full details. - -For more details on how setup a custom server, see the official [Custom Server Example](https://github.com/payloadcms/payload/tree/main/examples/custom-server). - -## Development - -To spin up this example locally, follow the [Quick Start](#quick-start). Then [Connect Stripe](#connect-stripe) to enable payments, and [Seed](#seed) the database with a few products and pages. - -### Docker - -Alternatively, you can use [Docker](https://www.docker.com) to spin up this template locally. To do so, follow these steps: - -1. Follow [steps 1 and 2 from above](#development), the docker-compose file will automatically use the `.env` file in your project root -1. Next run `docker-compose up` -1. Follow [steps 4 and 5 from above](#development) to login and create your first admin user - -That's it! The Docker instance will help you get up and running quickly while also standardizing the development environment across your teams. - -### Seed - -To seed the database with a few products and pages you can run `yarn seed`. This template also comes with a `GET /api/seed` endpoint you can use to seed the database from the admin panel. - -> NOTICE: seeding the database is destructive because it drops your current database to populate a fresh one from the seed template. Only run this command if you are starting a new project or can afford to lose your current data. - -### Conflicting routes - -> In a monorepo when routes are bootstrapped to the same host, they can conflict with Payload's own routes if they have the same name. In our template we've named the Nextjs API routes to `next` to avoid this conflict. -> -> This can happen with any other routes conflicting with Payload such as `admin` and we recommend using different names for custom routes. -> Alternatively you can also rename Payload's own routes via the [configuration](https://payloadcms.com/docs/configuration/overview). - -## Production - -To run Payload in production, you need to build and serve the Admin panel. To do so, follow these steps: - -1. Invoke the `payload build` script by running `yarn build` or `npm run build` in your project root. This creates a `./build` directory with a production-ready admin bundle. -1. Finally run `yarn serve` or `npm run serve` to run Node in production and serve Payload from the `./build` directory. -1. When you're ready to go live, see [Deployment](#deployment) for more details. - -### Deployment - -Before deploying your app, you need to: - -1. Switch [your Stripe account to live mode](https://stripe.com/docs/test-mode) and update your [Stripe API keys](https://dashboard.stripe.com/test/apikeys). See [Connect Stripe](#connect-stripe) for more details. -1. Ensure your app builds and serves in production. See [Production](#production) for more details. - -The easiest way to deploy your project is to use [Payload Cloud](https://payloadcms.com/new/import), a one-click hosting solution to deploy production-ready instances of your Payload apps directly from your GitHub repo. You can also deploy your app manually, check out the [deployment documentation](https://payloadcms.com/docs/production/deployment) for full details. - -## Questions - -If you have any issues or questions, reach out to us on [Discord](https://discord.com/invite/payload) or start a [GitHub discussion](https://github.com/payloadcms/payload/discussions). diff --git a/templates/ecommerce/csp.js b/templates/ecommerce/csp.js deleted file mode 100644 index 84b18d17bd3..00000000000 --- a/templates/ecommerce/csp.js +++ /dev/null @@ -1,36 +0,0 @@ -const policies = { - 'child-src': ["'self'"], - 'connect-src': [ - "'self'", - 'https://checkout.stripe.com', - 'https://api.stripe.com', - 'https://maps.googleapis.com', - ], - 'default-src': ["'self'"], - 'font-src': ["'self'"], - 'frame-src': [ - "'self'", - 'https://checkout.stripe.com', - 'https://js.stripe.com', - 'https://hooks.stripe.com', - ], - 'img-src': ["'self'", 'https://*.stripe.com', 'https://raw.githubusercontent.com'], - 'script-src': [ - "'self'", - "'unsafe-inline'", - "'unsafe-eval'", - 'https://checkout.stripe.com', - 'https://js.stripe.com', - 'https://maps.googleapis.com', - ], - 'style-src': ["'self'", "'unsafe-inline'", 'https://fonts.googleapis.com'], -} - -module.exports = Object.entries(policies) - .map(([key, value]) => { - if (Array.isArray(value)) { - return `${key} ${value.join(' ')}` - } - return '' - }) - .join('; ') diff --git a/templates/ecommerce/docker-compose.yml b/templates/ecommerce/docker-compose.yml deleted file mode 100644 index 4c9fc519402..00000000000 --- a/templates/ecommerce/docker-compose.yml +++ /dev/null @@ -1,31 +0,0 @@ -version: '3' - -services: - payload: - image: node:18-alpine - ports: - - '3000:3000' - volumes: - - .:/home/node/app - - node_modules:/home/node/app/node_modules - working_dir: /home/node/app/ - command: sh -c "yarn install && yarn dev" - depends_on: - - mongo - env_file: - - .env - - mongo: - image: mongo:latest - ports: - - '27017:27017' - command: - - --storageEngine=wiredTiger - volumes: - - data:/data/db - logging: - driver: none - -volumes: - data: - node_modules: diff --git a/templates/ecommerce/eject.ts b/templates/ecommerce/eject.ts deleted file mode 100644 index f3f119dd5bd..00000000000 --- a/templates/ecommerce/eject.ts +++ /dev/null @@ -1,36 +0,0 @@ -import fs from 'fs' -import path from 'path' - -// Run this script to eject the front-end from this template -// This will remove all template-specific files and directories -// See `yarn eject` in `package.json` for the exact command -// See `./README.md#eject` for more information - -const files = ['./next.config.js', './next-env.d.ts', './redirects.js'] -const directories = ['./src/app'] - -const eject = async (): Promise => { - files.forEach((file) => { - fs.unlinkSync(path.join(__dirname, file)) - }) - - directories.forEach((directory) => { - fs.rm(path.join(__dirname, directory), { recursive: true }, (err) => { - if (err) throw err - }) - }) - - // create a new `./src/server.ts` file - // use contents from `./src/server.default.ts` - const serverFile = path.join(__dirname, './src/server.ts') - const serverDefaultFile = path.join(__dirname, './src/server.default.ts') - fs.copyFileSync(serverDefaultFile, serverFile) - - // remove `'plugin:@next/next/recommended', ` from `./.eslintrc.js` - const eslintConfigFile = path.join(__dirname, './.eslintrc.js') - const eslintConfig = fs.readFileSync(eslintConfigFile, 'utf8') - const updatedEslintConfig = eslintConfig.replace(`'plugin:@next/next/recommended', `, '') - fs.writeFileSync(eslintConfigFile, updatedEslintConfig, 'utf8') -} - -eject() diff --git a/templates/ecommerce/next-env.d.ts b/templates/ecommerce/next-env.d.ts deleted file mode 100644 index 4f11a03dc6c..00000000000 --- a/templates/ecommerce/next-env.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -/// -/// - -// NOTE: This file should not be edited -// see https://nextjs.org/docs/basic-features/typescript for more information. diff --git a/templates/ecommerce/next.config.js b/templates/ecommerce/next.config.js deleted file mode 100644 index 4f068b477ae..00000000000 --- a/templates/ecommerce/next.config.js +++ /dev/null @@ -1,50 +0,0 @@ -/** @type {import('next').NextConfig} */ -const ContentSecurityPolicy = require('./csp') -const redirects = require('./redirects') - -const nextConfig = { - async headers() { - const headers = [] - - // Prevent search engines from indexing the site if it is not live - // This is useful for staging environments before they are ready to go live - // To allow robots to crawl the site, use the `NEXT_PUBLIC_IS_LIVE` env variable - // You may want to also use this variable to conditionally render any tracking scripts - if (!process.env.NEXT_PUBLIC_IS_LIVE) { - headers.push({ - headers: [ - { - key: 'X-Robots-Tag', - value: 'noindex', - }, - ], - source: '/:path*', - }) - } - - // Set the `Content-Security-Policy` header as a security measure to prevent XSS attacks - // It works by explicitly whitelisting trusted sources of content for your website - // This will block all inline scripts and styles except for those that are allowed - headers.push({ - headers: [ - { - key: 'Content-Security-Policy', - value: ContentSecurityPolicy, - }, - ], - source: '/(.*)', - }) - - return headers - }, - images: { - domains: ['localhost', process.env.NEXT_PUBLIC_SERVER_URL] - .filter(Boolean) - .map((url) => url.replace(/https?:\/\//, '')), - }, - reactStrictMode: true, - redirects, - swcMinify: true, -} - -module.exports = nextConfig diff --git a/templates/ecommerce/nodemon.json b/templates/ecommerce/nodemon.json deleted file mode 100644 index f94c3a7eeff..00000000000 --- a/templates/ecommerce/nodemon.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/nodemon.json", - "exec": "ts-node --project tsconfig.server.json src/server.ts -- -I", - "ext": "js ts", - "ignore": ["src/app"], - "stdin": false, - "watch": ["server.ts"] -} diff --git a/templates/ecommerce/package.json b/templates/ecommerce/package.json deleted file mode 100644 index 3ff124cc289..00000000000 --- a/templates/ecommerce/package.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "name": "@payloadcms/template-ecommerce", - "version": "1.0.0", - "description": "E-commerce template for Payload", - "license": "MIT", - "main": "dist/server.js", - "scripts": { - "build": "cross-env NODE_ENV=production yarn build:payload && yarn build:server && yarn copyfiles && yarn build:next", - "build:next": "cross-env PAYLOAD_CONFIG_PATH=dist/payload/payload.config.js NEXT_BUILD=true node dist/server.js", - "build:payload": "cross-env PAYLOAD_CONFIG_PATH=src/payload/payload.config.ts payload build", - "build:server": "tsc --project tsconfig.server.json", - "copyfiles": "copyfiles -u 1 \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png,js}\" dist/", - "dev": "cross-env PAYLOAD_CONFIG_PATH=src/payload/payload.config.ts nodemon", - "eject": "yarn remove next react react-dom @next/eslint-plugin-next && ts-node eject.ts", - "generate:graphQLSchema": "PAYLOAD_CONFIG_PATH=src/payload/payload.config.ts payload generate:graphQLSchema", - "generate:types": "cross-env PAYLOAD_CONFIG_PATH=src/payload/payload.config.ts payload generate:types", - "lint": "eslint src", - "lint:fix": "eslint --fix --ext .ts,.tsx src", - "payload": "cross-env PAYLOAD_CONFIG_PATH=src/payload/payload.config.ts payload", - "seed": "rm -rf media && cross-env PAYLOAD_SEED=true PAYLOAD_DROP_DATABASE=true PAYLOAD_CONFIG_PATH=src/payload/payload.config.ts ts-node src/server.ts", - "serve": "cross-env PAYLOAD_CONFIG_PATH=dist/payload/payload.config.js NODE_ENV=production node dist/server.js", - "stripe:webhooks": "stripe listen --forward-to localhost:8000/stripe/webhooks" - }, - "dependencies": { - "@payloadcms/bundler-webpack": "^1.0.0", - "@payloadcms/db-mongodb": "^1.0.0", - "@payloadcms/plugin-cloud": "^3.0.0", - "@payloadcms/plugin-nested-docs": "^1.0.8", - "@payloadcms/plugin-redirects": "^1.0.0", - "@payloadcms/plugin-seo": "^1.0.10", - "@payloadcms/plugin-stripe": "^0.0.19", - "@payloadcms/richtext-slate": "^1.0.0", - "@stripe/react-stripe-js": "^1.16.3", - "@stripe/stripe-js": "^1.46.0", - "cross-env": "^7.0.3", - "dotenv": "^8.2.0", - "escape-html": "^1.0.3", - "express": "^4.17.1", - "next": "13.5.2", - "payload": "^2.0.7", - "payload-admin-bar": "^1.0.6", - "qs": "6.11.2", - "react": "^18.2.0", - "react-dom": "^18.2.0", - "react-hook-form": "7.45.4", - "react-router-dom": "5.3.4", - "stripe": "^10.2.0" - }, - "devDependencies": { - "@next/eslint-plugin-next": "^13.1.6", - "@payloadcms/eslint-config": "^1.1.1", - "@swc/core": "1.3.76", - "@types/escape-html": "^1.0.2", - "@types/express": "^4.17.9", - "@types/node": "18.11.3", - "@types/qs": "^6.9.8", - "@types/react": "18.0.21", - "copyfiles": "^2.4.1", - "nodemon": "^2.0.6", - "prettier": "^3.0.3", - "slate": "0.91.4", - "ts-node": "10.9.1", - "typescript": "^4.8.4" - } -} diff --git a/templates/ecommerce/public/favicon.ico b/templates/ecommerce/public/favicon.ico deleted file mode 100644 index 601b77718ca..00000000000 Binary files a/templates/ecommerce/public/favicon.ico and /dev/null differ diff --git a/templates/ecommerce/public/favicon.svg b/templates/ecommerce/public/favicon.svg deleted file mode 100644 index 86dc2defc49..00000000000 --- a/templates/ecommerce/public/favicon.svg +++ /dev/null @@ -1,15 +0,0 @@ - - - - - diff --git a/templates/ecommerce/public/static-image.jpg b/templates/ecommerce/public/static-image.jpg deleted file mode 100644 index ae614855dc6..00000000000 Binary files a/templates/ecommerce/public/static-image.jpg and /dev/null differ diff --git a/templates/ecommerce/redirects.js b/templates/ecommerce/redirects.js deleted file mode 100644 index 9e81b7095c3..00000000000 --- a/templates/ecommerce/redirects.js +++ /dev/null @@ -1,81 +0,0 @@ -// Note: This will not work in dev mode and will throw an error upon startup -// This is because the Payload APIs are not yet running when the Next.js server starts -// This is not a problem in production as Payload is booted up before building Next.js -// For this reason the errors can be silently ignored in dev mode - -module.exports = async () => { - const internetExplorerRedirect = { - destination: '/ie-incompatible.html', - has: [ - { - type: 'header', - key: 'user-agent', - value: '(.*Trident.*)', // all ie browsers - }, - ], - permanent: false, - source: '/:path((?!ie-incompatible.html$).*)', // all pages except the incompatibility page - } - - try { - const redirectsRes = await fetch( - `${process.env.NEXT_PUBLIC_SERVER_URL}/api/redirects?limit=1000&depth=1`, - ) - - const redirectsData = await redirectsRes.json() - const { docs } = redirectsData - - let dynamicRedirects = [] - - if (docs) { - docs.forEach((doc) => { - const { from, to: { type, reference, url } = {} } = doc - - let source = from - .replace(process.env.NEXT_PUBLIC_SERVER_URL, '') - .split('?')[0] - .toLowerCase() - - if (source.endsWith('/')) source = source.slice(0, -1) // a trailing slash will break this redirect - - let destination = '/' - - if (type === 'custom' && url) { - destination = url.replace(process.env.NEXT_PUBLIC_SERVER_URL, '') - } - - if ( - type === 'reference' && - typeof reference.value === 'object' && - reference?.value?._status === 'published' - ) { - destination = `${process.env.NEXT_PUBLIC_SERVER_URL}/${ - reference.relationTo !== 'pages' ? `${reference.relationTo}/` : '' - }${reference.value.slug}` - } - - const redirect = { - destination, - permanent: true, - source, - } - - if (source.startsWith('/') && destination && source !== destination) { - return dynamicRedirects.push(redirect) - } - - return - }) - } - - const redirects = [internetExplorerRedirect, ...dynamicRedirects] - - return redirects - } catch (error) { - if (process.env.NODE_ENV === 'production') { - console.error(`Error configuring redirects: ${error}`) // eslint-disable-line no-console - } - - return [] - } -} diff --git a/templates/ecommerce/src/app/(pages)/[slug]/page.tsx b/templates/ecommerce/src/app/(pages)/[slug]/page.tsx deleted file mode 100644 index 97ce360bf9d..00000000000 --- a/templates/ecommerce/src/app/(pages)/[slug]/page.tsx +++ /dev/null @@ -1,98 +0,0 @@ -import type { Metadata } from 'next' - -import { draftMode } from 'next/headers' -import { notFound } from 'next/navigation' -import React from 'react' - -import type { Page } from '../../../payload/payload-types' - -import { staticHome } from '../../../payload/seed/home-static' -import { fetchDoc } from '../../_api/fetchDoc' -import { fetchDocs } from '../../_api/fetchDocs' -import { Blocks } from '../../_components/Blocks' -import { Hero } from '../../_components/Hero' -import { generateMeta } from '../../_utilities/generateMeta' - -// Payload Cloud caches all files through Cloudflare, so we don't need Next.js to cache them as well -// This means that we can turn off Next.js data caching and instead rely solely on the Cloudflare CDN -// To do this, we include the `no-cache` header on the fetch requests used to get the data for this page -// But we also need to force Next.js to dynamically render this page on each request for preview mode to work -// See https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#dynamic -// If you are not using Payload Cloud then this line can be removed, see `../../../README.md#cache` -export const dynamic = 'force-dynamic' - -export default async function Page({ params: { slug = 'home' } }) { - const { isEnabled: isDraftMode } = draftMode() - - let page: Page | null = null - - try { - page = await fetchDoc({ - slug, - collection: 'pages', - draft: isDraftMode, - }) - } catch (error) { - // when deploying this template on Payload Cloud, this page needs to build before the APIs are live - // so swallow the error here and simply render the page with fallback data where necessary - // in production you may want to redirect to a 404 page or at least log the error somewhere - // console.error(error) - } - - // if no `home` page exists, render a static one using dummy content - // you should delete this code once you have a home page in the CMS - // this is really only useful for those who are demoing this template - if (!page && slug === 'home') { - page = staticHome - } - - if (!page) { - return notFound() - } - - const { hero, layout } = page - - return ( - - - - - ) -} - -export async function generateStaticParams() { - try { - const pages = await fetchDocs('pages') - return pages?.map(({ slug }) => slug) - } catch (error) { - return [] - } -} - -export async function generateMetadata({ params: { slug = 'home' } }): Promise { - const { isEnabled: isDraftMode } = draftMode() - - let page: Page | null = null - - try { - page = await fetchDoc({ - slug, - collection: 'pages', - draft: isDraftMode, - }) - } catch (error) { - // don't throw an error if the fetch fails - // this is so that we can render a static home page for the demo - // when deploying this template on Payload Cloud, this page needs to build before the APIs are live - // in production you may want to redirect to a 404 page or at least log the error somewhere - } - - if (!page && slug === 'home') { - page = staticHome - } - - return generateMeta({ doc: page }) -} diff --git a/templates/ecommerce/src/app/(pages)/account/AccountForm/index.module.scss b/templates/ecommerce/src/app/(pages)/account/AccountForm/index.module.scss deleted file mode 100644 index 9798e6489c2..00000000000 --- a/templates/ecommerce/src/app/(pages)/account/AccountForm/index.module.scss +++ /dev/null @@ -1,24 +0,0 @@ -@import '../../../_css/common'; - -.form { - margin-bottom: var(--base); - display: flex; - flex-direction: column; - gap: calc(var(--base) / 2); - align-items: flex-start; - width: 66.66%; - - @include mid-break { - width: 100%; - } -} - -.changePassword { - all: unset; - cursor: pointer; - text-decoration: underline; -} - -.submit { - margin-top: calc(var(--base) / 2); -} diff --git a/templates/ecommerce/src/app/(pages)/account/AccountForm/index.tsx b/templates/ecommerce/src/app/(pages)/account/AccountForm/index.tsx deleted file mode 100644 index 95c7783c5c8..00000000000 --- a/templates/ecommerce/src/app/(pages)/account/AccountForm/index.tsx +++ /dev/null @@ -1,161 +0,0 @@ -'use client' - -import { useRouter } from 'next/navigation' -import React, { Fragment, useCallback, useEffect, useRef, useState } from 'react' -import { useForm } from 'react-hook-form' - -import { Button } from '../../../_components/Button' -import { Input } from '../../../_components/Input' -import { Message } from '../../../_components/Message' -import { useAuth } from '../../../_providers/Auth' -import classes from './index.module.scss' - -type FormData = { - email: string - name: string - password: string - passwordConfirm: string -} - -const AccountForm: React.FC = () => { - const [error, setError] = useState('') - const [success, setSuccess] = useState('') - const { setUser, user } = useAuth() - const [changePassword, setChangePassword] = useState(false) - - const { - formState: { errors, isLoading }, - handleSubmit, - register, - reset, - watch, - } = useForm() - - const password = useRef({}) - password.current = watch('password', '') - - const router = useRouter() - - const onSubmit = useCallback( - async (data: FormData) => { - if (user) { - const response = await fetch(`${process.env.NEXT_PUBLIC_SERVER_URL}/api/users/${user.id}`, { - // Make sure to include cookies with fetch - body: JSON.stringify(data), - credentials: 'include', - headers: { - 'Content-Type': 'application/json', - }, - method: 'PATCH', - }) - - if (response.ok) { - const json = await response.json() - setUser(json.doc) - setSuccess('Successfully updated account.') - setError('') - setChangePassword(false) - reset({ - name: json.doc.name, - email: json.doc.email, - password: '', - passwordConfirm: '', - }) - } else { - setError('There was a problem updating your account.') - } - } - }, - [user, setUser, reset], - ) - - useEffect(() => { - if (user === null) { - router.push( - `/login?error=${encodeURIComponent( - 'You must be logged in to view this page.', - )}&redirect=${encodeURIComponent('/account')}`, - ) - } - - // Once user is loaded, reset form to have default values - if (user) { - reset({ - name: user.name, - email: user.email, - password: '', - passwordConfirm: '', - }) - } - }, [user, router, reset, changePassword]) - - return ( -
- - {!changePassword ? ( - -

- {'Change your account details below, or '} - - {' to change your password.'} -

- - -
- ) : ( - -

- {'Change your password below, or '} - - . -

- - value === password.current || 'The passwords do not match'} - /> -
- )} - -
- - Page {page} of {totalPages} - -
- - - ) -} diff --git a/templates/ecommerce/src/app/_components/PaywallBlocks/index.tsx b/templates/ecommerce/src/app/_components/PaywallBlocks/index.tsx deleted file mode 100644 index 2589464766a..00000000000 --- a/templates/ecommerce/src/app/_components/PaywallBlocks/index.tsx +++ /dev/null @@ -1,121 +0,0 @@ -'use client' - -import Link from 'next/link' -import React, { useEffect } from 'react' - -import type { Page } from '../../../payload/payload-types' - -import { PRODUCT_PAYWALL } from '../../_graphql/products' -import { useAuth } from '../../_providers/Auth' -import { Blocks } from '../Blocks' -import { Gutter } from '../Gutter' -import { LoadingShimmer } from '../LoadingShimmer' -import { Message } from '../Message' -import { VerticalPadding } from '../VerticalPadding' - -export const PaywallBlocks: React.FC<{ - disableTopPadding?: boolean - productSlug: string -}> = (props) => { - const { disableTopPadding, productSlug } = props - const { user } = useAuth() - - const [isLoading, setIsLoading] = React.useState(false) - const [blocks, setBlocks] = React.useState() - const hasInitialized = React.useRef(false) - const isRequesting = React.useRef(false) - - useEffect(() => { - if (!user || hasInitialized.current || isRequesting.current) return - hasInitialized.current = true - isRequesting.current = true - - const start = Date.now() - - const getPaywallContent = async () => { - setIsLoading(true) - - try { - const paywall = await fetch(`${process.env.NEXT_PUBLIC_SERVER_URL}/api/graphql`, { - body: JSON.stringify({ - query: PRODUCT_PAYWALL, - variables: { - slug: productSlug, - }, - }), - credentials: 'include', - headers: { - 'Content-Type': 'application/json', - }, - method: 'POST', - }) - ?.then((res) => res.json()) - ?.then((res) => res?.data?.Products.docs[0]?.paywall) - - if (paywall) { - setBlocks(paywall) - } - - // wait before setting `isLoading` to `false` to give the illusion of loading - // this is to prevent a flash of the loading shimmer on fast networks - const end = Date.now() - if (end - start < 1000) { - await new Promise((resolve) => setTimeout(resolve, 500 - (end - start))) - } - - setIsLoading(false) - } catch (error) { - console.error(error) // eslint-disable-line no-console - setIsLoading(false) - } - } - - getPaywallContent() - }, [user, productSlug]) - - if (user === undefined) { - return null - } - - if (user === null) { - return ( - - - - {`This content is gated behind a paywall. You must be `} - - logged in - - {` as an admin or have purchased this product to view this content.`} - - } - /> - - - ) - } - - if (isLoading) { - return ( - - - - - - ) - } - - if (!blocks || blocks.length === 0) { - return ( - - - - - - ) - } - - return -} diff --git a/templates/ecommerce/src/app/_components/Price/index.module.scss b/templates/ecommerce/src/app/_components/Price/index.module.scss deleted file mode 100644 index 1b31033fe76..00000000000 --- a/templates/ecommerce/src/app/_components/Price/index.module.scss +++ /dev/null @@ -1,29 +0,0 @@ -@import '../../_css/common'; - -.actions { - display: flex; - align-items: center; - flex-wrap: wrap; - gap: calc(var(--base) / 2); - - @include mid-break { - flex-direction: column; - align-items: flex-start; - } -} - -.price { - font-weight: 600; - line-height: 1; - display: flex; - flex-direction: column; - gap: 4px; - - > * { - margin: 0; - } -} - -.priceBreakdown { - color: var(--theme-elevation-500); -} diff --git a/templates/ecommerce/src/app/_components/Price/index.tsx b/templates/ecommerce/src/app/_components/Price/index.tsx deleted file mode 100644 index 5dc31f5b57c..00000000000 --- a/templates/ecommerce/src/app/_components/Price/index.tsx +++ /dev/null @@ -1,80 +0,0 @@ -'use client' - -import React, { useEffect, useState } from 'react' - -import type { Product } from '../../../payload/payload-types' - -import { AddToCartButton } from '../AddToCartButton' -import { RemoveFromCartButton } from '../RemoveFromCartButton' -import classes from './index.module.scss' - -export const priceFromJSON = (priceJSON: string, quantity: number = 1, raw?: boolean): string => { - let price = '' - - if (priceJSON) { - try { - const parsed = JSON.parse(priceJSON)?.data[0] - const priceValue = parsed.unit_amount * quantity - const priceType = parsed.type - - if (raw) return priceValue.toString() - - price = (priceValue / 100).toLocaleString('en-US', { - currency: 'USD', // TODO: use `parsed.currency` - style: 'currency', - }) - - if (priceType === 'recurring') { - price += `/${ - parsed.recurring.interval_count > 1 - ? `${parsed.recurring.interval_count} ${parsed.recurring.interval}` - : parsed.recurring.interval - }` - } - } catch (e) { - console.error(`Cannot parse priceJSON`) // eslint-disable-line no-console - } - } - - return price -} - -export const Price: React.FC<{ - button?: 'addToCart' | 'removeFromCart' | false - product: Product - quantity?: number -}> = (props) => { - const { button = 'addToCart', product, product: { priceJSON } = {}, quantity } = props - - const [price, setPrice] = useState<{ - actualPrice: string - withQuantity: string - }>(() => ({ - actualPrice: priceFromJSON(priceJSON), - withQuantity: priceFromJSON(priceJSON, quantity), - })) - - useEffect(() => { - setPrice({ - actualPrice: priceFromJSON(priceJSON), - withQuantity: priceFromJSON(priceJSON, quantity), - }) - }, [priceJSON, quantity]) - - return ( -
- {typeof price?.actualPrice !== 'undefined' && price?.withQuantity !== '' && ( -
-

{price?.withQuantity}

- {quantity > 1 && ( - {`${price.actualPrice} x ${quantity}`} - )} -
- )} - {button && button === 'addToCart' && ( - - )} - {button && button === 'removeFromCart' && } -
- ) -} diff --git a/templates/ecommerce/src/app/_components/RemoveFromCartButton/index.module.scss b/templates/ecommerce/src/app/_components/RemoveFromCartButton/index.module.scss deleted file mode 100644 index 2519bfea484..00000000000 --- a/templates/ecommerce/src/app/_components/RemoveFromCartButton/index.module.scss +++ /dev/null @@ -1,7 +0,0 @@ -@import '../../_css/common'; - -.removeFromCartButton { - all: unset; - cursor: pointer; - @extend %label; -} diff --git a/templates/ecommerce/src/app/_components/RemoveFromCartButton/index.tsx b/templates/ecommerce/src/app/_components/RemoveFromCartButton/index.tsx deleted file mode 100644 index b27e4ce4fab..00000000000 --- a/templates/ecommerce/src/app/_components/RemoveFromCartButton/index.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import React from 'react' - -import type { Product } from '../../../payload/payload-types' - -import { useCart } from '../../_providers/Cart' -import classes from './index.module.scss' - -export const RemoveFromCartButton: React.FC<{ - className?: string - product: Product -}> = (props) => { - const { className, product } = props - - const { deleteItemFromCart, isProductInCart } = useCart() - - const productIsInCart = isProductInCart(product) - - if (!productIsInCart) { - return
Item is not in the cart
- } - - return ( - - ) -} diff --git a/templates/ecommerce/src/app/_components/RenderParams/Component.tsx b/templates/ecommerce/src/app/_components/RenderParams/Component.tsx deleted file mode 100644 index f911d357869..00000000000 --- a/templates/ecommerce/src/app/_components/RenderParams/Component.tsx +++ /dev/null @@ -1,51 +0,0 @@ -'use client' - -import { useSearchParams } from 'next/navigation' -import { useEffect } from 'react' - -import { Message } from '../Message' -import classes from './index.module.scss' - -export type Props = { - className?: string - message?: string - onParams?: (paramValues: ((null | string | undefined) | string[])[]) => void - params?: string[] -} - -export const RenderParamsComponent: React.FC = ({ - className, - onParams, - params = ['error', 'warning', 'success', 'message'], -}) => { - const searchParams = useSearchParams() - const paramValues = params.map((param) => searchParams?.get(param)) - - useEffect(() => { - if (paramValues.length && onParams) { - onParams(paramValues) - } - }, [paramValues, onParams]) - - if (paramValues.length) { - return ( -
- {paramValues.map((paramValue, index) => { - if (!paramValue) return null - - return ( - - ) - })} -
- ) - } - - return null -} diff --git a/templates/ecommerce/src/app/_components/RenderParams/index.module.scss b/templates/ecommerce/src/app/_components/RenderParams/index.module.scss deleted file mode 100644 index 69f05b94908..00000000000 --- a/templates/ecommerce/src/app/_components/RenderParams/index.module.scss +++ /dev/null @@ -1,9 +0,0 @@ -@import '../../_css/common.scss'; - -.renderParams { - margin-bottom: calc(var(--base) * 2); - - @include mid-break { - margin-bottom: var(--base); - } -} diff --git a/templates/ecommerce/src/app/_components/RenderParams/index.tsx b/templates/ecommerce/src/app/_components/RenderParams/index.tsx deleted file mode 100644 index dd8b1f95175..00000000000 --- a/templates/ecommerce/src/app/_components/RenderParams/index.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { Suspense } from 'react' - -import type { Props } from './Component' - -import { RenderParamsComponent } from './Component' - -// Using `useSearchParams` from `next/navigation` causes the entire route to de-optimize into client-side rendering -// To fix this, we wrap the component in a `Suspense` component -// See https://nextjs.org/docs/messages/deopted-into-client-rendering for more info - -export const RenderParams: React.FC = (props) => { - return ( - - - - ) -} diff --git a/templates/ecommerce/src/app/_components/RichText/index.module.scss b/templates/ecommerce/src/app/_components/RichText/index.module.scss deleted file mode 100644 index ef45c8d9036..00000000000 --- a/templates/ecommerce/src/app/_components/RichText/index.module.scss +++ /dev/null @@ -1,8 +0,0 @@ -.richText { - :first-child { - margin-top: 0; - } - :last-child { - margin-bottom: 0; - } -} diff --git a/templates/ecommerce/src/app/_components/RichText/index.tsx b/templates/ecommerce/src/app/_components/RichText/index.tsx deleted file mode 100644 index b0b28080cb9..00000000000 --- a/templates/ecommerce/src/app/_components/RichText/index.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import React from 'react' - -import classes from './index.module.scss' -import serialize from './serialize' - -const RichText: React.FC<{ className?: string; content: any }> = ({ className, content }) => { - if (!content) { - return null - } - - return ( -
- {serialize(content)} -
- ) -} - -export default RichText diff --git a/templates/ecommerce/src/app/_components/RichText/serialize.tsx b/templates/ecommerce/src/app/_components/RichText/serialize.tsx deleted file mode 100644 index b071b813d9e..00000000000 --- a/templates/ecommerce/src/app/_components/RichText/serialize.tsx +++ /dev/null @@ -1,110 +0,0 @@ -import escapeHTML from 'escape-html' -import Link from 'next/link' -import React, { Fragment } from 'react' -import { Text } from 'slate' - -import { Label } from '../Label' -import { LargeBody } from '../LargeBody' -import { CMSLink } from '../Link' - -// eslint-disable-next-line no-use-before-define -type Children = Leaf[] - -type Leaf = { - [key: string]: unknown - children?: Children - type: string - url?: string - value?: { - alt: string - url: string - } -} - -const serialize = (children?: Children): React.ReactNode[] => - children?.map((node, i) => { - if (Text.isText(node)) { - let text = - - if (node.bold) { - text = {text} - } - - if (node.code) { - text = {text} - } - - if (node.italic) { - text = {text} - } - - if (node.underline) { - text = ( - - {text} - - ) - } - - if (node.strikethrough) { - text = ( - - {text} - - ) - } - - return {text} - } - - if (!node) { - return null - } - - switch (node.type) { - case 'h1': - return

{serialize(node?.children)}

- case 'h2': - return

{serialize(node?.children)}

- case 'h3': - return

{serialize(node?.children)}

- case 'h4': - return

{serialize(node?.children)}

- case 'h5': - return
{serialize(node?.children)}
- case 'h6': - return
{serialize(node?.children)}
- case 'quote': - return
{serialize(node?.children)}
- case 'ul': - return
    {serialize(node?.children)}
- case 'ol': - return
    {serialize(node.children)}
- case 'li': - return
  • {serialize(node.children)}
  • - case 'link': - return ( - - {serialize(node?.children)} - - ) - - case 'label': - return - - case 'large-body': { - return {serialize(node?.children)} - } - - default: - return

    {serialize(node?.children)}

    - } - }) || [] - -export default serialize diff --git a/templates/ecommerce/src/app/_components/VerticalPadding/index.module.scss b/templates/ecommerce/src/app/_components/VerticalPadding/index.module.scss deleted file mode 100644 index a9db566e8cf..00000000000 --- a/templates/ecommerce/src/app/_components/VerticalPadding/index.module.scss +++ /dev/null @@ -1,15 +0,0 @@ -.top-large { - padding-top: var(--block-padding); -} - -.top-medium { - padding-top: calc(var(--block-padding) / 2); -} - -.bottom-large { - padding-bottom: var(--block-padding); -} - -.bottom-medium { - padding-bottom: calc(var(--block-padding) / 2); -} diff --git a/templates/ecommerce/src/app/_components/VerticalPadding/index.tsx b/templates/ecommerce/src/app/_components/VerticalPadding/index.tsx deleted file mode 100644 index d17a341b110..00000000000 --- a/templates/ecommerce/src/app/_components/VerticalPadding/index.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import React from 'react' - -import classes from './index.module.scss' - -export type VerticalPaddingOptions = 'large' | 'medium' | 'none' - -type Props = { - bottom?: VerticalPaddingOptions - children: React.ReactNode - className?: string - top?: VerticalPaddingOptions -} - -export const VerticalPadding: React.FC = ({ - bottom = 'medium', - children, - className, - top = 'medium', -}) => { - return ( -
    - {children} -
    - ) -} diff --git a/templates/ecommerce/src/app/_components/icons/Chevron/index.tsx b/templates/ecommerce/src/app/_components/icons/Chevron/index.tsx deleted file mode 100644 index 9e07b0d94ef..00000000000 --- a/templates/ecommerce/src/app/_components/icons/Chevron/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import React from 'react' - -export const Chevron: React.FC = () => { - return ( - - - - ) -} diff --git a/templates/ecommerce/src/app/_components/icons/Menu/index.tsx b/templates/ecommerce/src/app/_components/icons/Menu/index.tsx deleted file mode 100644 index c513d7ba79c..00000000000 --- a/templates/ecommerce/src/app/_components/icons/Menu/index.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import React from 'react' - -export const MenuIcon: React.FC = () => { - return ( - - - - - - ) -} diff --git a/templates/ecommerce/src/app/_css/app.scss b/templates/ecommerce/src/app/_css/app.scss deleted file mode 100644 index da67c2347fa..00000000000 --- a/templates/ecommerce/src/app/_css/app.scss +++ /dev/null @@ -1,123 +0,0 @@ -@use './queries.scss' as *; -@use './colors.scss' as *; -@use './type.scss' as *; -@import './theme.scss'; - -:root { - --base: 24px; - --font-body: system-ui; - --font-mono: 'Roboto Mono', monospace; - - --gutter-h: 180px; - --block-padding: 120px; - - @include large-break { - --gutter-h: 144px; - --block-padding: 96px; - } - - @include mid-break { - --gutter-h: 24px; - --block-padding: 60px; - } -} - -* { - box-sizing: border-box; -} - -html { - @extend %body; - background: var(--theme-bg); - -webkit-font-smoothing: antialiased; - opacity: 0; - - &[data-theme='dark'], - &[data-theme='light'] { - opacity: initial; - } -} - -html, -body, -#app { - height: 100%; -} - -body { - font-family: var(--font-body); - margin: 0; - color: var(--theme-text); -} - -::selection { - background: var(--theme-success-500); - color: var(--color-base-800); -} - -::-moz-selection { - background: var(--theme-success-500); - color: var(--color-base-800); -} - -img { - max-width: 100%; - height: auto; - display: block; -} - -h1 { - @extend %h1; -} - -h2 { - @extend %h2; -} - -h3 { - @extend %h3; -} - -h4 { - @extend %h4; -} - -h5 { - @extend %h5; -} - -h6 { - @extend %h6; -} - -p { - margin: var(--base) 0; - - @include mid-break { - margin: calc(var(--base) * 0.75) 0; - } -} - -ul, -ol { - padding-left: var(--base); - margin: 0 0 var(--base); -} - -a { - color: currentColor; - - &:focus { - opacity: 0.8; - outline: none; - } - - &:active { - opacity: 0.7; - outline: none; - } -} - -svg { - vertical-align: middle; -} diff --git a/templates/ecommerce/src/app/_css/colors.scss b/templates/ecommerce/src/app/_css/colors.scss deleted file mode 100644 index ce7655db303..00000000000 --- a/templates/ecommerce/src/app/_css/colors.scss +++ /dev/null @@ -1,105 +0,0 @@ -// Keep these in sync with the colors exported in '../cssVariables.js' - -:root { - --color-base-0: rgb(255, 255, 255); - --color-base-50: rgb(245, 245, 245); - --color-base-100: rgb(235, 235, 235); - --color-base-150: rgb(221, 221, 221); - --color-base-200: rgb(208, 208, 208); - --color-base-250: rgb(195, 195, 195); - --color-base-300: rgb(181, 181, 181); - --color-base-350: rgb(168, 168, 168); - --color-base-400: rgb(154, 154, 154); - --color-base-450: rgb(141, 141, 141); - --color-base-500: rgb(128, 128, 128); - --color-base-550: rgb(114, 114, 114); - --color-base-600: rgb(101, 101, 101); - --color-base-650: rgb(87, 87, 87); - --color-base-700: rgb(74, 74, 74); - --color-base-750: rgb(60, 60, 60); - --color-base-800: rgb(47, 47, 47); - --color-base-850: rgb(34, 34, 34); - --color-base-900: rgb(20, 20, 20); - --color-base-950: rgb(7, 7, 7); - --color-base-1000: rgb(0, 0, 0); - - --color-success-50: rgb(237, 245, 249); - --color-success-100: rgb(218, 237, 248); - --color-success-150: rgb(188, 225, 248); - --color-success-200: rgb(156, 216, 253); - --color-success-250: rgb(125, 204, 248); - --color-success-300: rgb(97, 190, 241); - --color-success-350: rgb(65, 178, 236); - --color-success-400: rgb(36, 164, 223); - --color-success-450: rgb(18, 148, 204); - --color-success-500: rgb(21, 135, 186); - --color-success-550: rgb(12, 121, 168); - --color-success-600: rgb(11, 110, 153); - --color-success-650: rgb(11, 97, 135); - --color-success-700: rgb(17, 88, 121); - --color-success-750: rgb(17, 76, 105); - --color-success-800: rgb(18, 66, 90); - --color-success-850: rgb(18, 56, 76); - --color-success-900: rgb(19, 44, 58); - --color-success-950: rgb(22, 33, 39); - - --color-error-50: rgb(250, 241, 240); - --color-error-100: rgb(252, 229, 227); - --color-error-150: rgb(247, 208, 204); - --color-error-200: rgb(254, 193, 188); - --color-error-250: rgb(253, 177, 170); - --color-error-300: rgb(253, 154, 146); - --color-error-350: rgb(253, 131, 123); - --color-error-400: rgb(246, 109, 103); - --color-error-450: rgb(234, 90, 86); - --color-error-500: rgb(218, 75, 72); - --color-error-550: rgb(200, 62, 61); - --color-error-600: rgb(182, 54, 54); - --color-error-650: rgb(161, 47, 47); - --color-error-700: rgb(144, 44, 43); - --color-error-750: rgb(123, 41, 39); - --color-error-800: rgb(105, 39, 37); - --color-error-850: rgb(86, 36, 33); - --color-error-900: rgb(64, 32, 29); - --color-error-950: rgb(44, 26, 24); - - --color-warning-50: rgb(249, 242, 237); - --color-warning-100: rgb(248, 232, 219); - --color-warning-150: rgb(243, 212, 186); - --color-warning-200: rgb(243, 200, 162); - --color-warning-250: rgb(240, 185, 136); - --color-warning-300: rgb(238, 166, 98); - --color-warning-350: rgb(234, 148, 58); - --color-warning-400: rgb(223, 132, 17); - --color-warning-450: rgb(204, 120, 15); - --color-warning-500: rgb(185, 108, 13); - --color-warning-550: rgb(167, 97, 10); - --color-warning-600: rgb(150, 87, 11); - --color-warning-650: rgb(134, 78, 11); - --color-warning-700: rgb(120, 70, 13); - --color-warning-750: rgb(105, 61, 13); - --color-warning-800: rgb(90, 55, 19); - --color-warning-850: rgb(73, 47, 21); - --color-warning-900: rgb(56, 38, 20); - --color-warning-950: rgb(38, 29, 21); - - --color-blue-50: rgb(237, 245, 249); - --color-blue-100: rgb(218, 237, 248); - --color-blue-150: rgb(188, 225, 248); - --color-blue-200: rgb(156, 216, 253); - --color-blue-250: rgb(125, 204, 248); - --color-blue-300: rgb(97, 190, 241); - --color-blue-350: rgb(65, 178, 236); - --color-blue-400: rgb(36, 164, 223); - --color-blue-450: rgb(18, 148, 204); - --color-blue-500: rgb(21, 135, 186); - --color-blue-550: rgb(12, 121, 168); - --color-blue-600: rgb(11, 110, 153); - --color-blue-650: rgb(11, 97, 135); - --color-blue-700: rgb(17, 88, 121); - --color-blue-750: rgb(17, 76, 105); - --color-blue-800: rgb(18, 66, 90); - --color-blue-850: rgb(18, 56, 76); - --color-blue-900: rgb(19, 44, 58); - --color-blue-950: rgb(22, 33, 39); -} diff --git a/templates/ecommerce/src/app/_css/common.scss b/templates/ecommerce/src/app/_css/common.scss deleted file mode 100644 index e66be0183db..00000000000 --- a/templates/ecommerce/src/app/_css/common.scss +++ /dev/null @@ -1,2 +0,0 @@ -@forward './queries.scss'; -@forward './type.scss'; diff --git a/templates/ecommerce/src/app/_css/queries.scss b/templates/ecommerce/src/app/_css/queries.scss deleted file mode 100644 index b5f8c282cdc..00000000000 --- a/templates/ecommerce/src/app/_css/queries.scss +++ /dev/null @@ -1,30 +0,0 @@ -// Keep these in sync with the breakpoints exported in '../cssVariables.js' - -$breakpoint-xs-width: 400px; -$breakpoint-s-width: 768px; -$breakpoint-m-width: 1024px; -$breakpoint-l-width: 1440px; - -@mixin extra-small-break { - @media (max-width: #{$breakpoint-xs-width}) { - @content; - } -} - -@mixin small-break { - @media (max-width: #{$breakpoint-s-width}) { - @content; - } -} - -@mixin mid-break { - @media (max-width: #{$breakpoint-m-width}) { - @content; - } -} - -@mixin large-break { - @media (max-width: #{$breakpoint-l-width}) { - @content; - } -} diff --git a/templates/ecommerce/src/app/_css/theme.scss b/templates/ecommerce/src/app/_css/theme.scss deleted file mode 100644 index 17bd7caa9aa..00000000000 --- a/templates/ecommerce/src/app/_css/theme.scss +++ /dev/null @@ -1,237 +0,0 @@ -[data-theme='light'] { - --theme-success-50: var(--color-success-50); - --theme-success-100: var(--color-success-100); - --theme-success-150: var(--color-success-150); - --theme-success-200: var(--color-success-200); - --theme-success-250: var(--color-success-250); - --theme-success-300: var(--color-success-300); - --theme-success-350: var(--color-success-350); - --theme-success-400: var(--color-success-400); - --theme-success-450: var(--color-success-450); - --theme-success-500: var(--color-success-500); - --theme-success-550: var(--color-success-550); - --theme-success-600: var(--color-success-600); - --theme-success-650: var(--color-success-650); - --theme-success-700: var(--color-success-700); - --theme-success-750: var(--color-success-750); - --theme-success-800: var(--color-success-800); - --theme-success-850: var(--color-success-850); - --theme-success-900: var(--color-success-900); - --theme-success-950: var(--color-success-950); - - --theme-warning-50: var(--color-warning-50); - --theme-warning-100: var(--color-warning-100); - --theme-warning-150: var(--color-warning-150); - --theme-warning-200: var(--color-warning-200); - --theme-warning-250: var(--color-warning-250); - --theme-warning-300: var(--color-warning-300); - --theme-warning-350: var(--color-warning-350); - --theme-warning-400: var(--color-warning-400); - --theme-warning-450: var(--color-warning-450); - --theme-warning-500: var(--color-warning-500); - --theme-warning-550: var(--color-warning-550); - --theme-warning-600: var(--color-warning-600); - --theme-warning-650: var(--color-warning-650); - --theme-warning-700: var(--color-warning-700); - --theme-warning-750: var(--color-warning-750); - --theme-warning-800: var(--color-warning-800); - --theme-warning-850: var(--color-warning-850); - --theme-warning-900: var(--color-warning-900); - --theme-warning-950: var(--color-warning-950); - - --theme-error-50: var(--color-error-50); - --theme-error-100: var(--color-error-100); - --theme-error-150: var(--color-error-150); - --theme-error-200: var(--color-error-200); - --theme-error-250: var(--color-error-250); - --theme-error-300: var(--color-error-300); - --theme-error-350: var(--color-error-350); - --theme-error-400: var(--color-error-400); - --theme-error-450: var(--color-error-450); - --theme-error-500: var(--color-error-500); - --theme-error-550: var(--color-error-550); - --theme-error-600: var(--color-error-600); - --theme-error-650: var(--color-error-650); - --theme-error-700: var(--color-error-700); - --theme-error-750: var(--color-error-750); - --theme-error-800: var(--color-error-800); - --theme-error-850: var(--color-error-850); - --theme-error-900: var(--color-error-900); - --theme-error-950: var(--color-error-950); - - --theme-elevation-0: var(--color-base-0); - --theme-elevation-50: var(--color-base-50); - --theme-elevation-100: var(--color-base-100); - --theme-elevation-150: var(--color-base-150); - --theme-elevation-200: var(--color-base-200); - --theme-elevation-250: var(--color-base-250); - --theme-elevation-300: var(--color-base-300); - --theme-elevation-350: var(--color-base-350); - --theme-elevation-400: var(--color-base-400); - --theme-elevation-450: var(--color-base-450); - --theme-elevation-500: var(--color-base-500); - --theme-elevation-550: var(--color-base-550); - --theme-elevation-600: var(--color-base-600); - --theme-elevation-650: var(--color-base-650); - --theme-elevation-700: var(--color-base-700); - --theme-elevation-750: var(--color-base-750); - --theme-elevation-800: var(--color-base-800); - --theme-elevation-850: var(--color-base-850); - --theme-elevation-900: var(--color-base-900); - --theme-elevation-950: var(--color-base-950); - --theme-elevation-1000: var(--color-base-1000); - - --theme-bg: var(--theme-elevation-0); - --theme-input-bg: var(--theme-elevation-50); - --theme-text: var(--theme-elevation-750); - --theme-border-color: var(--theme-elevation-150); - - color-scheme: light; - color: var(--theme-text); - - --highlight-default-bg-color: var(--theme-success-400); - --highlight-default-text-color: var(--theme-text); - - --highlight-danger-bg-color: var(--theme-error-150); - --highlight-danger-text-color: var(--theme-text); - - h1 a, - h2 a, - h3 a, - h4 a, - h5 a, - h6 a { - color: var(--theme-elevation-750); - - &:hover { - color: var(--theme-elevation-800); - } - - &:visited { - color: var(--theme-elevation-750); - - &:hover { - color: var(--theme-elevation-800); - } - } - } -} - -[data-theme='dark'] { - --theme-elevation-0: var(--color-base-1000); - --theme-elevation-50: var(--color-base-950); - --theme-elevation-100: var(--color-base-900); - --theme-elevation-150: var(--color-base-850); - --theme-elevation-200: var(--color-base-800); - --theme-elevation-250: var(--color-base-750); - --theme-elevation-300: var(--color-base-700); - --theme-elevation-350: var(--color-base-650); - --theme-elevation-400: var(--color-base-600); - --theme-elevation-450: var(--color-base-550); - --theme-elevation-500: var(--color-base-500); - --theme-elevation-550: var(--color-base-450); - --theme-elevation-600: var(--color-base-400); - --theme-elevation-650: var(--color-base-350); - --theme-elevation-700: var(--color-base-300); - --theme-elevation-750: var(--color-base-250); - --theme-elevation-800: var(--color-base-200); - --theme-elevation-850: var(--color-base-150); - --theme-elevation-900: var(--color-base-100); - --theme-elevation-950: var(--color-base-50); - --theme-elevation-1000: var(--color-base-0); - - --theme-success-50: var(--color-success-950); - --theme-success-100: var(--color-success-900); - --theme-success-150: var(--color-success-850); - --theme-success-200: var(--color-success-800); - --theme-success-250: var(--color-success-750); - --theme-success-300: var(--color-success-700); - --theme-success-350: var(--color-success-650); - --theme-success-400: var(--color-success-600); - --theme-success-450: var(--color-success-550); - --theme-success-500: var(--color-success-500); - --theme-success-550: var(--color-success-450); - --theme-success-600: var(--color-success-400); - --theme-success-650: var(--color-success-350); - --theme-success-700: var(--color-success-300); - --theme-success-750: var(--color-success-250); - --theme-success-800: var(--color-success-200); - --theme-success-850: var(--color-success-150); - --theme-success-900: var(--color-success-100); - --theme-success-950: var(--color-success-50); - - --theme-warning-50: var(--color-warning-950); - --theme-warning-100: var(--color-warning-900); - --theme-warning-150: var(--color-warning-850); - --theme-warning-200: var(--color-warning-800); - --theme-warning-250: var(--color-warning-750); - --theme-warning-300: var(--color-warning-700); - --theme-warning-350: var(--color-warning-650); - --theme-warning-400: var(--color-warning-600); - --theme-warning-450: var(--color-warning-550); - --theme-warning-500: var(--color-warning-500); - --theme-warning-550: var(--color-warning-450); - --theme-warning-600: var(--color-warning-400); - --theme-warning-650: var(--color-warning-350); - --theme-warning-700: var(--color-warning-300); - --theme-warning-750: var(--color-warning-250); - --theme-warning-800: var(--color-warning-200); - --theme-warning-850: var(--color-warning-150); - --theme-warning-900: var(--color-warning-100); - --theme-warning-950: var(--color-warning-50); - - --theme-error-50: var(--color-error-950); - --theme-error-100: var(--color-error-900); - --theme-error-150: var(--color-error-850); - --theme-error-200: var(--color-error-800); - --theme-error-250: var(--color-error-750); - --theme-error-300: var(--color-error-700); - --theme-error-350: var(--color-error-650); - --theme-error-400: var(--color-error-600); - --theme-error-450: var(--color-error-550); - --theme-error-500: var(--color-error-500); - --theme-error-550: var(--color-error-450); - --theme-error-600: var(--color-error-400); - --theme-error-650: var(--color-error-350); - --theme-error-700: var(--color-error-300); - --theme-error-750: var(--color-error-250); - --theme-error-800: var(--color-error-200); - --theme-error-850: var(--color-error-150); - --theme-error-900: var(--color-error-100); - --theme-error-950: var(--color-error-50); - - --theme-bg: var(--theme-elevation-100); - --theme-text: var(--theme-elevation-900); - --theme-input-bg: var(--theme-elevation-150); - --theme-border-color: var(--theme-elevation-250); - - color-scheme: dark; - color: var(--theme-text); - - --highlight-default-bg-color: var(--theme-success-100); - --highlight-default-text-color: var(--theme-success-600); - - --highlight-danger-bg-color: var(--theme-error-100); - --highlight-danger-text-color: var(--theme-error-550); - - h1 a, - h2 a, - h3 a, - h4 a, - h5 a, - h6 a { - color: var(--theme-success-600); - - &:hover { - color: var(--theme-success-400); - } - - &:visited { - color: var(--theme-success-700); - - &:hover { - color: var(--theme-success-500); - } - } - } -} diff --git a/templates/ecommerce/src/app/_css/type.scss b/templates/ecommerce/src/app/_css/type.scss deleted file mode 100644 index f8d1d07162e..00000000000 --- a/templates/ecommerce/src/app/_css/type.scss +++ /dev/null @@ -1,110 +0,0 @@ -@use 'queries' as *; - -%h1, -%h2, -%h3, -%h4, -%h5, -%h6 { - font-weight: 700; -} - -%h1 { - margin: 40px 0; - font-size: 64px; - line-height: 70px; - font-weight: bold; - - @include mid-break { - margin: 24px 0; - font-size: 42px; - line-height: 42px; - } -} - -%h2 { - margin: 28px 0; - font-size: 48px; - line-height: 54px; - font-weight: bold; - - @include mid-break { - margin: 22px 0; - font-size: 32px; - line-height: 40px; - } -} - -%h3 { - margin: 24px 0; - font-size: 32px; - line-height: 40px; - font-weight: bold; - - @include mid-break { - margin: 20px 0; - font-size: 26px; - line-height: 32px; - } -} - -%h4 { - margin: 20px 0; - font-size: 26px; - line-height: 32px; - font-weight: bold; - - @include mid-break { - font-size: 22px; - line-height: 30px; - } -} - -%h5 { - margin: 20px 0; - font-size: 22px; - line-height: 30px; - font-weight: bold; - - @include mid-break { - font-size: 18px; - line-height: 24px; - } -} - -%h6 { - margin: 20px 0; - font-size: inherit; - line-height: inherit; - font-weight: bold; -} - -%body { - font-size: 18px; - line-height: 32px; - - @include mid-break { - font-size: 15px; - line-height: 24px; - } -} - -%large-body { - font-size: 25px; - line-height: 32px; - - @include mid-break { - font-size: 22px; - line-height: 30px; - } -} - -%label { - font-size: 16px; - line-height: 24px; - text-transform: uppercase; - - @include mid-break { - font-size: 13px; - } -} diff --git a/templates/ecommerce/src/app/_graphql/blocks.ts b/templates/ecommerce/src/app/_graphql/blocks.ts deleted file mode 100644 index 6f3aea1d7e7..00000000000 --- a/templates/ecommerce/src/app/_graphql/blocks.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { CATEGORIES } from './categories' -import { LINK_FIELDS } from './link' -import { MEDIA } from './media' -import { META } from './meta' - -export const CALL_TO_ACTION = ` -...on Cta { - blockType - invertBackground - richText - links { - link ${LINK_FIELDS()} - } -} -` - -export const CONTENT = ` -...on Content { - blockType - invertBackground - columns { - size - richText - enableLink - link ${LINK_FIELDS()} - } -} -` - -export const MEDIA_BLOCK = ` -...on MediaBlock { - blockType - invertBackground - position - ${MEDIA} -} -` - -export const ARCHIVE_BLOCK = ` -...on Archive { - blockType - introContent - populateBy - relationTo - ${CATEGORIES} - limit - selectedDocs { - relationTo - value { - ...on Product { - id - slug - title - priceJSON - ${META} - } - } - } - populatedDocs { - relationTo - value { - ...on Product { - id - slug - title - priceJSON - ${CATEGORIES} - ${META} - } - } - } - populatedDocsTotal -} -` diff --git a/templates/ecommerce/src/app/_graphql/cart.ts b/templates/ecommerce/src/app/_graphql/cart.ts deleted file mode 100644 index 84d0b131ed2..00000000000 --- a/templates/ecommerce/src/app/_graphql/cart.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { META } from './meta' - -export const CART = `cart { - items { - product { - id - slug - priceJSON - ${META} - } - quantity - } -}` diff --git a/templates/ecommerce/src/app/_graphql/categories.ts b/templates/ecommerce/src/app/_graphql/categories.ts deleted file mode 100644 index df8cbe9a154..00000000000 --- a/templates/ecommerce/src/app/_graphql/categories.ts +++ /dev/null @@ -1,8 +0,0 @@ -export const CATEGORIES = `categories { - title - id - breadcrumbs { - id - label - } -}` diff --git a/templates/ecommerce/src/app/_graphql/globals.ts b/templates/ecommerce/src/app/_graphql/globals.ts deleted file mode 100644 index d43c5978581..00000000000 --- a/templates/ecommerce/src/app/_graphql/globals.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { LINK_FIELDS } from './link' - -export const HEADER = ` - Header { - navItems { - link ${LINK_FIELDS({ disableAppearance: true })} - } - } -` - -export const HEADER_QUERY = ` -query Header { - ${HEADER} -} -` - -export const FOOTER = ` - Footer { - navItems { - link ${LINK_FIELDS({ disableAppearance: true })} - } - } -` - -export const FOOTER_QUERY = ` -query Footer { - ${FOOTER} -} -` - -export const SETTINGS = ` - Settings { - productsPage { - slug - } - } -` - -export const SETTINGS_QUERY = ` -query Settings { - ${SETTINGS} -} -` diff --git a/templates/ecommerce/src/app/_graphql/link.ts b/templates/ecommerce/src/app/_graphql/link.ts deleted file mode 100644 index 9c211b41891..00000000000 --- a/templates/ecommerce/src/app/_graphql/link.ts +++ /dev/null @@ -1,20 +0,0 @@ -interface Args { - disableAppearance?: true - disableLabel?: true -} - -export const LINK_FIELDS = ({ disableAppearance, disableLabel }: Args = {}): string => `{ - ${!disableLabel ? 'label' : ''} - ${!disableAppearance ? 'appearance' : ''} - type - newTab - url - reference { - relationTo - value { - ...on Page { - slug - } - } - } -}` diff --git a/templates/ecommerce/src/app/_graphql/me.ts b/templates/ecommerce/src/app/_graphql/me.ts deleted file mode 100644 index 8154ae2331c..00000000000 --- a/templates/ecommerce/src/app/_graphql/me.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { CART } from './cart' - -export const ME_QUERY = `query { - meUser { - user { - id - email - name - ${CART} - roles - } - exp - } -}` diff --git a/templates/ecommerce/src/app/_graphql/media.ts b/templates/ecommerce/src/app/_graphql/media.ts deleted file mode 100644 index fbf8e526b66..00000000000 --- a/templates/ecommerce/src/app/_graphql/media.ts +++ /dev/null @@ -1,12 +0,0 @@ -export const MEDIA_FIELDS = ` -mimeType -filename -width -height -alt -caption -` - -export const MEDIA = `media { - ${MEDIA_FIELDS} -}` diff --git a/templates/ecommerce/src/app/_graphql/meta.ts b/templates/ecommerce/src/app/_graphql/meta.ts deleted file mode 100644 index fc87374928e..00000000000 --- a/templates/ecommerce/src/app/_graphql/meta.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { MEDIA_FIELDS } from './media' - -export const META = `meta { - title - image { - ${MEDIA_FIELDS} - } - description -}` diff --git a/templates/ecommerce/src/app/_graphql/orders.ts b/templates/ecommerce/src/app/_graphql/orders.ts deleted file mode 100644 index da57fb5d51b..00000000000 --- a/templates/ecommerce/src/app/_graphql/orders.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { PRODUCT } from './products' - -export const ORDERS = ` - query Orders { - Orders(limit: 300) { - docs { - id - } - } - } -` - -export const ORDER = ` - query Order($id: String ) { - Orders(where: { id: { equals: $id}}) { - docs { - id - orderedBy - items { - product ${PRODUCT} - title - priceJSON - } - } - } - } -` diff --git a/templates/ecommerce/src/app/_graphql/pages.ts b/templates/ecommerce/src/app/_graphql/pages.ts deleted file mode 100644 index 67aaa7f07a1..00000000000 --- a/templates/ecommerce/src/app/_graphql/pages.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { ARCHIVE_BLOCK, CALL_TO_ACTION, CONTENT, MEDIA_BLOCK } from './blocks' -import { LINK_FIELDS } from './link' -import { MEDIA } from './media' -import { META } from './meta' - -export const PAGES = ` - query Pages { - Pages(limit: 300, where: { slug: { not_equals: "cart" } }) { - docs { - slug - } - } - } -` - -export const PAGE = ` - query Page($slug: String, $draft: Boolean) { - Pages(where: { AND: [{ slug: { equals: $slug }}] }, limit: 1, draft: $draft) { - docs { - id - title - hero { - type - richText - links { - link ${LINK_FIELDS()} - } - ${MEDIA} - } - layout { - ${CONTENT} - ${CALL_TO_ACTION} - ${CONTENT} - ${MEDIA_BLOCK} - ${ARCHIVE_BLOCK} - } - ${META} - } - } - } -` diff --git a/templates/ecommerce/src/app/_graphql/products.ts b/templates/ecommerce/src/app/_graphql/products.ts deleted file mode 100644 index 13e579811a8..00000000000 --- a/templates/ecommerce/src/app/_graphql/products.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { ARCHIVE_BLOCK, CALL_TO_ACTION, CONTENT, MEDIA_BLOCK } from './blocks' -import { CATEGORIES } from './categories' -import { META } from './meta' - -export const PRODUCTS = ` - query Products { - Products(limit: 300) { - docs { - slug - } - } - } -` - -export const PRODUCT = ` - query Product($slug: String, $draft: Boolean) { - Products(where: { slug: { equals: $slug}}, limit: 1, draft: $draft) { - docs { - id - title - stripeProductID - ${CATEGORIES} - layout { - ${CALL_TO_ACTION} - ${CONTENT} - ${MEDIA_BLOCK} - ${ARCHIVE_BLOCK} - } - priceJSON - enablePaywall - relatedProducts { - id - slug - title - ${META} - } - ${META} - } - } - } -` - -export const PRODUCT_PAYWALL = ` - query Product($slug: String, $draft: Boolean) { - Products(where: { slug: { equals: $slug}}, limit: 1, draft: $draft) { - docs { - paywall { - ${CALL_TO_ACTION} - ${CONTENT} - ${MEDIA_BLOCK} - ${ARCHIVE_BLOCK} - } - } - } - } -` diff --git a/templates/ecommerce/src/app/_heros/HighImpact/index.module.scss b/templates/ecommerce/src/app/_heros/HighImpact/index.module.scss deleted file mode 100644 index d6bffc2a230..00000000000 --- a/templates/ecommerce/src/app/_heros/HighImpact/index.module.scss +++ /dev/null @@ -1,55 +0,0 @@ -@import '../../_css/queries.scss'; - -.hero { - padding-top: calc(var(--base) * 2); - position: relative; - overflow: hidden; - - @include mid-break { - padding-top: var(--gutter-h); - } -} - -.media { - width: calc(100% + var(--gutter-h)); - left: calc(var(--gutter-h) / -2); - margin-top: calc(var(--base) * 3); - position: relative; - - @include mid-break { - left: 0; - margin-top: var(--base); - margin-left: calc(var(--gutter-h) * -1); - width: calc(100% + var(--gutter-h) * 2); - } -} - -.links { - list-style: none; - margin: 0; - padding: 0; - display: flex; - padding-top: var(--base); - flex-wrap: wrap; - margin: calc(var(--base) * -0.5); - - & > * { - margin: calc(var(--base) / 2); - } -} - -.caption { - margin-top: var(--base); - color: var(--theme-elevation-500); - left: calc(var(--gutter-h) / 2); - width: calc(100% - var(--gutter-h)); - position: relative; - - @include mid-break { - left: var(--gutter-h); - } -} - -.content { - position: relative; -} diff --git a/templates/ecommerce/src/app/_heros/HighImpact/index.tsx b/templates/ecommerce/src/app/_heros/HighImpact/index.tsx deleted file mode 100644 index 109616da9ec..00000000000 --- a/templates/ecommerce/src/app/_heros/HighImpact/index.tsx +++ /dev/null @@ -1,43 +0,0 @@ -import React, { Fragment } from 'react' - -import type { Page } from '../../../payload/payload-types' - -import { Gutter } from '../../_components/Gutter' -import { CMSLink } from '../../_components/Link' -import { Media } from '../../_components/Media' -import RichText from '../../_components/RichText' -import classes from './index.module.scss' - -export const HighImpactHero: React.FC = ({ links, media, richText }) => { - return ( - -
    - - {Array.isArray(links) && links.length > 0 && ( -
      - {links.map(({ link }, i) => { - return ( -
    • - -
    • - ) - })} -
    - )} -
    -
    - {typeof media === 'object' && ( - - - {media?.caption && } - - )} -
    -
    - ) -} diff --git a/templates/ecommerce/src/app/_heros/LowImpact/index.module.scss b/templates/ecommerce/src/app/_heros/LowImpact/index.module.scss deleted file mode 100644 index 6b6fbea13da..00000000000 --- a/templates/ecommerce/src/app/_heros/LowImpact/index.module.scss +++ /dev/null @@ -1,4 +0,0 @@ -@use '../../_css/type.scss' as *; - -.lowImpactHero { -} diff --git a/templates/ecommerce/src/app/_heros/LowImpact/index.tsx b/templates/ecommerce/src/app/_heros/LowImpact/index.tsx deleted file mode 100644 index 3b1a34c5988..00000000000 --- a/templates/ecommerce/src/app/_heros/LowImpact/index.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import React from 'react' - -import type { Page } from '../../../payload/payload-types' - -import { Gutter } from '../../_components/Gutter' -import RichText from '../../_components/RichText' -import { VerticalPadding } from '../../_components/VerticalPadding' -import classes from './index.module.scss' - -export const LowImpactHero: React.FC = ({ richText }) => { - return ( - -
    - - - -
    -
    - ) -} diff --git a/templates/ecommerce/src/app/_heros/MediumImpact/index.module.scss b/templates/ecommerce/src/app/_heros/MediumImpact/index.module.scss deleted file mode 100644 index a0b58fef569..00000000000 --- a/templates/ecommerce/src/app/_heros/MediumImpact/index.module.scss +++ /dev/null @@ -1,62 +0,0 @@ -@use '../../_css/common.scss' as *; - -.hero { - padding-top: calc(var(--base) * 3); - - @include mid-break { - padding-top: var(--base); - } -} - -.richText { - position: relative; - - &::after { - content: ''; - display: block; - position: absolute; - width: 100vw; - left: calc(var(--gutter-h) * -1); - height: 200px; - background: linear-gradient(to bottom, var(--theme-elevation-100), transparent); - top: calc(100% + (var(--base) * 2)); - right: 0; - - @include mid-break { - display: none; - } - } -} - -.links { - position: relative; - list-style: none; - margin: 0; - padding: 0; - display: flex; - margin-top: calc(var(--base) * 4); - - li { - margin-right: 12px; - } - - @include mid-break { - display: block; - margin-top: var(--base); - - li { - margin-right: 0; - } - } -} - -.link { - @include mid-break { - width: 100%; - } -} - -.media { - position: relative; - width: calc(100% + var(--gutter-h)); -} diff --git a/templates/ecommerce/src/app/_heros/MediumImpact/index.tsx b/templates/ecommerce/src/app/_heros/MediumImpact/index.tsx deleted file mode 100644 index 980844a51be..00000000000 --- a/templates/ecommerce/src/app/_heros/MediumImpact/index.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import React from 'react' - -import type { Page } from '../../../payload/payload-types' - -import { Gutter } from '../../_components/Gutter' -import { CMSLink } from '../../_components/Link' -import { Media } from '../../_components/Media' -import RichText from '../../_components/RichText' -import classes from './index.module.scss' - -export const MediumImpactHero: React.FC = (props) => { - const { links, media, richText } = props - - return ( - -
    - - {Array.isArray(links) && ( -
      - {links.map(({ link }, i) => { - return ( -
    • - -
    • - ) - })} -
    - )} -
    -
    - {typeof media === 'object' && } -
    -
    - ) -} diff --git a/templates/ecommerce/src/app/_heros/Product/index.module.scss b/templates/ecommerce/src/app/_heros/Product/index.module.scss deleted file mode 100644 index 50c9439a910..00000000000 --- a/templates/ecommerce/src/app/_heros/Product/index.module.scss +++ /dev/null @@ -1,84 +0,0 @@ -@use '../../_css/common.scss' as *; - -.productHero { - display: flex; - gap: calc(var(--base) * 2); - - @include mid-break { - flex-direction: column; - gap: var(--base); - } -} - -.content { - width: 50%; - display: flex; - flex-direction: column; - justify-content: center; - align-items: flex-start; - gap: var(--base); - - @include mid-break { - width: 100%; - gap: calc(var(--base) / 2); - } -} - -.categories { - @extend %label; -} - -.title { - margin: 0; -} - -.warning { - margin-bottom: calc(var(--base) * 1.5); -} - -.description { - margin: 0; -} - -.media { - width: 50%; - - @include mid-break { - width: 100%; - } -} - -.mediaWrapper { - text-decoration: none; - display: block; - position: relative; - aspect-ratio: 5 / 4; - margin-bottom: calc(var(--base) / 2); - width: calc(100% + calc(var(--gutter-h) / 2)); - - @include mid-break { - margin-left: calc(var(--gutter-h) * -1); - width: calc(100% + var(--gutter-h) * 2); - } -} - -.image { - object-fit: cover; -} - -.placeholder { - background-color: var(--theme-elevation-50); - width: 100%; - height: 100%; - display: flex; - align-items: center; - justify-content: center; -} - -.caption { - color: var(--theme-elevation-500); -} - -.addToCartButton { - margin-top: calc(var(--base) / 2); -} diff --git a/templates/ecommerce/src/app/_heros/Product/index.tsx b/templates/ecommerce/src/app/_heros/Product/index.tsx deleted file mode 100644 index 4a7ab2f25f7..00000000000 --- a/templates/ecommerce/src/app/_heros/Product/index.tsx +++ /dev/null @@ -1,94 +0,0 @@ -import Link from 'next/link' -import React, { Fragment } from 'react' - -import type { Product } from '../../../payload/payload-types' - -import { AddToCartButton } from '../../_components/AddToCartButton' -import { Gutter } from '../../_components/Gutter' -import { Media } from '../../_components/Media' -import { Message } from '../../_components/Message' -import { Price } from '../../_components/Price' -import RichText from '../../_components/RichText' -import classes from './index.module.scss' - -export const ProductHero: React.FC<{ - product: Product -}> = ({ product }) => { - const { - id, - categories, - meta: { description, image: metaImage } = {}, - stripeProductID, - title, - } = product - - return ( - - {!stripeProductID && ( - - - {'This product is not yet connected to Stripe. To link this product, '} - - edit this product in the admin panel - - . - - } - /> - - )} - -
    -
    - {categories?.map((category, index) => { - if (typeof category === 'object' && category !== null) { - const { title: categoryTitle } = category - - const titleToUse = categoryTitle || 'Untitled category' - - const isLast = index === categories.length - 1 - - return ( - - {titleToUse} - {!isLast && ,  } - - ) - } - - return null - })} -
    -

    {title}

    -
    -

    - {`${description ? `${description} ` : ''}To edit this product, `} - - navigate to the admin dashboard - - . -

    -
    - - -
    -
    -
    - {!metaImage &&
    No image
    } - {metaImage && typeof metaImage !== 'string' && ( - - )} -
    - {metaImage && typeof metaImage !== 'string' && metaImage?.caption && ( - - )} -
    -
    - - ) -} diff --git a/templates/ecommerce/src/app/_providers/Auth/index.tsx b/templates/ecommerce/src/app/_providers/Auth/index.tsx deleted file mode 100644 index 19dc73cf2cf..00000000000 --- a/templates/ecommerce/src/app/_providers/Auth/index.tsx +++ /dev/null @@ -1,218 +0,0 @@ -'use client' - -import React, { createContext, useCallback, useContext, useEffect, useState } from 'react' - -import type { User } from '../../../payload/payload-types' - -// eslint-disable-next-line no-unused-vars -type ResetPassword = (args: { - password: string - passwordConfirm: string - token: string -}) => Promise - -type ForgotPassword = (args: { email: string }) => Promise // eslint-disable-line no-unused-vars - -type Create = (args: { email: string; password: string; passwordConfirm: string }) => Promise // eslint-disable-line no-unused-vars - -type Login = (args: { email: string; password: string }) => Promise // eslint-disable-line no-unused-vars - -type Logout = () => Promise - -type AuthContext = { - create: Create - forgotPassword: ForgotPassword - login: Login - logout: Logout - resetPassword: ResetPassword - setUser: (user: User | null) => void // eslint-disable-line no-unused-vars - status: 'loggedIn' | 'loggedOut' | undefined - user?: User | null -} - -const Context = createContext({} as AuthContext) - -export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { - const [user, setUser] = useState() - - // used to track the single event of logging in or logging out - // useful for `useEffect` hooks that should only run once - const [status, setStatus] = useState<'loggedIn' | 'loggedOut' | undefined>() - const create = useCallback(async (args) => { - try { - const res = await fetch(`${process.env.NEXT_PUBLIC_SERVER_URL}/api/users/create`, { - body: JSON.stringify({ - email: args.email, - password: args.password, - passwordConfirm: args.passwordConfirm, - }), - credentials: 'include', - headers: { - 'Content-Type': 'application/json', - }, - method: 'POST', - }) - - if (res.ok) { - const { data, errors } = await res.json() - if (errors) throw new Error(errors[0].message) - setUser(data?.loginUser?.user) - setStatus('loggedIn') - } else { - throw new Error('Invalid login') - } - } catch (e) { - throw new Error('An error occurred while attempting to login.') - } - }, []) - - const login = useCallback(async (args) => { - try { - const res = await fetch(`${process.env.NEXT_PUBLIC_SERVER_URL}/api/users/login`, { - body: JSON.stringify({ - email: args.email, - password: args.password, - }), - credentials: 'include', - headers: { - 'Content-Type': 'application/json', - }, - method: 'POST', - }) - - if (res.ok) { - const { errors, user } = await res.json() - if (errors) throw new Error(errors[0].message) - setUser(user) - setStatus('loggedIn') - return user - } - - throw new Error('Invalid login') - } catch (e) { - throw new Error('An error occurred while attempting to login.') - } - }, []) - - const logout = useCallback(async () => { - try { - const res = await fetch(`${process.env.NEXT_PUBLIC_SERVER_URL}/api/users/logout`, { - credentials: 'include', - headers: { - 'Content-Type': 'application/json', - }, - method: 'POST', - }) - - if (res.ok) { - setUser(null) - setStatus('loggedOut') - } else { - throw new Error('An error occurred while attempting to logout.') - } - } catch (e) { - throw new Error('An error occurred while attempting to logout.') - } - }, []) - - useEffect(() => { - const fetchMe = async () => { - try { - const res = await fetch(`${process.env.NEXT_PUBLIC_SERVER_URL}/api/users/me`, { - credentials: 'include', - headers: { - 'Content-Type': 'application/json', - }, - method: 'GET', - }) - - if (res.ok) { - const { user: meUser } = await res.json() - setUser(meUser || null) - setStatus(meUser ? 'loggedIn' : undefined) - } else { - throw new Error('An error occurred while fetching your account.') - } - } catch (e) { - setUser(null) - throw new Error('An error occurred while fetching your account.') - } - } - - fetchMe() - }, []) - - const forgotPassword = useCallback(async (args) => { - try { - const res = await fetch(`${process.env.NEXT_PUBLIC_SERVER_URL}/api/users/forgot-password`, { - body: JSON.stringify({ - email: args.email, - }), - credentials: 'include', - headers: { - 'Content-Type': 'application/json', - }, - method: 'POST', - }) - - if (res.ok) { - const { data, errors } = await res.json() - if (errors) throw new Error(errors[0].message) - setUser(data?.loginUser?.user) - } else { - throw new Error('Invalid login') - } - } catch (e) { - throw new Error('An error occurred while attempting to login.') - } - }, []) - - const resetPassword = useCallback(async (args) => { - try { - const res = await fetch(`${process.env.NEXT_PUBLIC_SERVER_URL}/api/users/reset-password`, { - body: JSON.stringify({ - password: args.password, - passwordConfirm: args.passwordConfirm, - token: args.token, - }), - credentials: 'include', - headers: { - 'Content-Type': 'application/json', - }, - method: 'POST', - }) - - if (res.ok) { - const { data, errors } = await res.json() - if (errors) throw new Error(errors[0].message) - setUser(data?.loginUser?.user) - setStatus(data?.loginUser?.user ? 'loggedIn' : undefined) - } else { - throw new Error('Invalid login') - } - } catch (e) { - throw new Error('An error occurred while attempting to login.') - } - }, []) - - return ( - - {children} - - ) -} - -type UseAuth = () => AuthContext // eslint-disable-line no-unused-vars - -export const useAuth: UseAuth = () => useContext(Context) diff --git a/templates/ecommerce/src/app/_providers/Cart/index.tsx b/templates/ecommerce/src/app/_providers/Cart/index.tsx deleted file mode 100644 index 5f0a890ba2a..00000000000 --- a/templates/ecommerce/src/app/_providers/Cart/index.tsx +++ /dev/null @@ -1,278 +0,0 @@ -'use client' - -import React, { - createContext, - useCallback, - useContext, - useEffect, - useReducer, - useRef, - useState, -} from 'react' - -import type { Product, User } from '../../../payload/payload-types' -import type { CartItem } from './reducer' - -import { useAuth } from '../Auth' -import { cartReducer } from './reducer' - -export type CartContext = { - addItemToCart: (item: CartItem) => void - cart: User['cart'] - cartIsEmpty: boolean | undefined - cartTotal: { - formatted: string - raw: number - } - clearCart: () => void - deleteItemFromCart: (product: Product) => void - hasInitializedCart: boolean - isProductInCart: (product: Product) => boolean -} - -const Context = createContext({} as CartContext) - -export const useCart = () => useContext(Context) - -const arrayHasItems = (array) => Array.isArray(array) && array.length > 0 - -/** - * ensure that cart items are fully populated, filter out any items that are not - * this will prevent discontinued products from appearing in the cart - */ -const flattenCart = (cart: User['cart']): User['cart'] => ({ - ...cart, - items: cart.items - .map((item) => { - if (!item?.product || typeof item?.product !== 'object') { - return null - } - - return { - ...item, - // flatten relationship to product - product: item?.product?.id, - quantity: typeof item?.quantity === 'number' ? item?.quantity : 0, - } - }) - .filter(Boolean) as CartItem[], -}) - -// Step 1: Check local storage for a cart -// Step 2: If there is a cart, fetch the products and hydrate the cart -// Step 3: Authenticate the user -// Step 4: If the user is authenticated, merge the user's cart with the local cart -// Step 4B: Sync the cart to Payload and clear local storage -// Step 5: If the user is logged out, sync the cart to local storage only - -export const CartProvider = (props) => { - // const { setTimedNotification } = useNotifications(); - const { children } = props - const { status: authStatus, user } = useAuth() - - const [cart, dispatchCart] = useReducer(cartReducer, {}) - - const [total, setTotal] = useState<{ - formatted: string - raw: number - }>({ - formatted: '0.00', - raw: 0, - }) - - const hasInitialized = useRef(false) - const [hasInitializedCart, setHasInitialized] = useState(false) - - // Check local storage for a cart - // If there is a cart, fetch the products and hydrate the cart - useEffect(() => { - // wait for the user to be defined before initializing the cart - if (user === undefined) return - if (!hasInitialized.current) { - hasInitialized.current = true - - const syncCartFromLocalStorage = async () => { - const localCart = localStorage.getItem('cart') - - const parsedCart = JSON.parse(localCart || '{}') - - if (parsedCart?.items && parsedCart?.items?.length > 0) { - const initialCart = await Promise.all( - parsedCart.items.map(async ({ product, quantity }) => { - const res = await fetch( - `${process.env.NEXT_PUBLIC_SERVER_URL}/api/products/${product}`, - ) - const data = await res.json() - return { - product: data, - quantity, - } - }), - ) - - dispatchCart({ - type: 'SET_CART', - payload: { - items: initialCart, - }, - }) - } else { - dispatchCart({ - type: 'SET_CART', - payload: { - items: [], - }, - }) - } - } - - syncCartFromLocalStorage() - } - }, [user]) - - // authenticate the user and if logged in, merge the user's cart with local state - // only do this after we have initialized the cart to ensure we don't lose any items - useEffect(() => { - if (!hasInitialized.current) return - - if (authStatus === 'loggedIn') { - // merge the user's cart with the local state upon logging in - dispatchCart({ - type: 'MERGE_CART', - payload: user?.cart, - }) - } - - if (authStatus === 'loggedOut') { - // clear the cart from local state after logging out - dispatchCart({ - type: 'CLEAR_CART', - }) - } - }, [user, authStatus]) - - // every time the cart changes, determine whether to save to local storage or Payload based on authentication status - // upon logging in, merge and sync the existing local cart to Payload - useEffect(() => { - // wait until we have attempted authentication (the user is either an object or `null`) - if (!hasInitialized.current || user === undefined || !cart.items) return - - const flattenedCart = flattenCart(cart) - - if (user) { - // prevent updating the cart when the cart hasn't changed - if (JSON.stringify(flattenCart(user.cart)) === JSON.stringify(flattenedCart)) { - setHasInitialized(true) - return - } - - try { - const syncCartToPayload = async () => { - const req = await fetch(`${process.env.NEXT_PUBLIC_SERVER_URL}/api/users/${user.id}`, { - // Make sure to include cookies with fetch - body: JSON.stringify({ - cart: flattenedCart, - }), - credentials: 'include', - headers: { - 'Content-Type': 'application/json', - }, - method: 'PATCH', - }) - - if (req.ok) { - localStorage.setItem('cart', '[]') - } - } - - syncCartToPayload() - } catch (e) { - console.error('Error while syncing cart to Payload.') // eslint-disable-line no-console - } - } else { - localStorage.setItem('cart', JSON.stringify(flattenedCart)) - } - - setHasInitialized(true) - }, [user, cart]) - - const isProductInCart = useCallback( - (incomingProduct: Product): boolean => { - let isInCart = false - const { items: itemsInCart } = cart || {} - if (Array.isArray(itemsInCart) && itemsInCart.length > 0) { - isInCart = Boolean( - itemsInCart.find(({ product }) => - typeof product === 'string' - ? product === incomingProduct.id - : product?.id === incomingProduct.id, - ), // eslint-disable-line function-paren-newline - ) - } - return isInCart - }, - [cart], - ) - - // this method can be used to add new items AND update existing ones - const addItemToCart = useCallback((incomingItem) => { - dispatchCart({ - type: 'ADD_ITEM', - payload: incomingItem, - }) - }, []) - - const deleteItemFromCart = useCallback((incomingProduct: Product) => { - dispatchCart({ - type: 'DELETE_ITEM', - payload: incomingProduct, - }) - }, []) - - const clearCart = useCallback(() => { - dispatchCart({ - type: 'CLEAR_CART', - }) - }, []) - - // calculate the new cart total whenever the cart changes - useEffect(() => { - if (!hasInitialized) return - - const newTotal = - cart?.items?.reduce((acc, item) => { - return ( - acc + - (typeof item.product === 'object' - ? JSON.parse(item?.product?.priceJSON || '{}')?.data?.[0]?.unit_amount * - (typeof item?.quantity === 'number' ? item?.quantity : 0) - : 0) - ) - }, 0) || 0 - - setTotal({ - formatted: (newTotal / 100).toLocaleString('en-US', { - currency: 'USD', - style: 'currency', - }), - raw: newTotal, - }) - }, [cart, hasInitialized]) - - return ( - - {children && children} - - ) -} diff --git a/templates/ecommerce/src/app/_providers/Cart/reducer.ts b/templates/ecommerce/src/app/_providers/Cart/reducer.ts deleted file mode 100644 index 04171b8e427..00000000000 --- a/templates/ecommerce/src/app/_providers/Cart/reducer.ts +++ /dev/null @@ -1,122 +0,0 @@ -import type { CartItems, Product, User } from '../../../payload/payload-types' - -export type CartItem = CartItems[0] - -type CartType = User['cart'] - -type CartAction = - | { - payload: CartItem - type: 'ADD_ITEM' - } - | { - payload: CartType - type: 'MERGE_CART' - } - | { - payload: CartType - type: 'SET_CART' - } - | { - payload: Product - type: 'DELETE_ITEM' - } - | { - type: 'CLEAR_CART' - } - -export const cartReducer = (cart: CartType, action: CartAction): CartType => { - switch (action.type) { - case 'SET_CART': { - return action.payload - } - - case 'MERGE_CART': { - const { payload: incomingCart } = action - - const syncedItems: CartItem[] = [ - ...(cart?.items || []), - ...(incomingCart?.items || []), - ].reduce((acc: CartItem[], item) => { - // remove duplicates - const productId = typeof item.product === 'string' ? item.product : item?.product?.id - - const indexInAcc = acc.findIndex(({ product }) => - typeof product === 'string' ? product === productId : product?.id === productId, - ) // eslint-disable-line function-paren-newline - - if (indexInAcc > -1) { - acc[indexInAcc] = { - ...acc[indexInAcc], - // customize the merge logic here, e.g.: - // quantity: acc[indexInAcc].quantity + item.quantity - } - } else { - acc.push(item) - } - return acc - }, []) - - return { - ...cart, - items: syncedItems, - } - } - - case 'ADD_ITEM': { - // if the item is already in the cart, increase the quantity - const { payload: incomingItem } = action - const productId = - typeof incomingItem.product === 'string' ? incomingItem.product : incomingItem?.product?.id - - const indexInCart = cart?.items?.findIndex(({ product }) => - typeof product === 'string' ? product === productId : product?.id === productId, - ) // eslint-disable-line function-paren-newline - - const withAddedItem = [...(cart?.items || [])] - - if (indexInCart === -1) { - withAddedItem.push(incomingItem) - } - - if (typeof indexInCart === 'number' && indexInCart > -1) { - withAddedItem[indexInCart] = { - ...withAddedItem[indexInCart], - quantity: (incomingItem.quantity || 0) > 0 ? incomingItem.quantity : undefined, - } - } - - return { - ...cart, - items: withAddedItem, - } - } - - case 'DELETE_ITEM': { - const { payload: incomingProduct } = action - const withDeletedItem = { ...cart } - - const indexInCart = cart?.items?.findIndex(({ product }) => - typeof product === 'string' - ? product === incomingProduct.id - : product?.id === incomingProduct.id, - ) // eslint-disable-line function-paren-newline - - if (typeof indexInCart === 'number' && withDeletedItem.items && indexInCart > -1) - withDeletedItem.items.splice(indexInCart, 1) - - return withDeletedItem - } - - case 'CLEAR_CART': { - return { - ...cart, - items: [], - } - } - - default: { - return cart - } - } -} diff --git a/templates/ecommerce/src/app/_providers/Theme/InitTheme/index.tsx b/templates/ecommerce/src/app/_providers/Theme/InitTheme/index.tsx deleted file mode 100644 index 206d655ee5b..00000000000 --- a/templates/ecommerce/src/app/_providers/Theme/InitTheme/index.tsx +++ /dev/null @@ -1,49 +0,0 @@ -import Script from 'next/script' - -import { defaultTheme, themeLocalStorageKey } from '../ThemeSelector/types' - -export const InitTheme: React.FC = () => { - return ( - // eslint-disable-next-line @next/next/no-before-interactive-script-outside-document -