diff --git a/.eslintrc.json b/.eslintrc.json index 4f3c9e2164f1fbc..b2508a20109dade 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -71,6 +71,7 @@ "functions": false, "classes": false, "variables": false, + "enums": false, "typedefs": false } ], @@ -106,6 +107,16 @@ { "files": ["examples/**/*"], "rules": { + "@typescript-eslint/no-use-before-define": [ + "error", + { + "functions": true, + "classes": true, + "variables": true, + "enums": true, + "typedefs": true + } + ], "import/no-anonymous-default-export": [ "error", { diff --git a/examples/amp-first/components/amp/AmpCustomElement.tsx b/examples/amp-first/components/amp/AmpCustomElement.tsx index 1a14221ea49260e..0c02ae55668c41d 100644 --- a/examples/amp-first/components/amp/AmpCustomElement.tsx +++ b/examples/amp-first/components/amp/AmpCustomElement.tsx @@ -319,6 +319,10 @@ export function AmpIncludeAmpLinkRewriter() { return } +export function AmpIncludeAmpMustache() { + return +} + export function AmpIncludeAmpList() { return ( <> @@ -350,10 +354,6 @@ export function AmpIncludeAmpMowplayer() { return } -export function AmpIncludeAmpMustache() { - return -} - export function AmpIncludeAmpNextPage() { return } diff --git a/examples/amp-first/components/amp/AmpScript.tsx b/examples/amp-first/components/amp/AmpScript.tsx index d8b2b4d2e00b913..c884ec5ae83fca7 100644 --- a/examples/amp-first/components/amp/AmpScript.tsx +++ b/examples/amp-first/components/amp/AmpScript.tsx @@ -10,6 +10,13 @@ type AmpScriptProps = { src?: string } +const generateInlineScript = (script: Function | string) => { + if (typeof script === 'function') { + return `${script.toString()}()` + } + return String(script) +} + /** * Embeds an AMP Script by either linking to a TS `src` file or embedding inline * AMP Script via the `script` property. The inline script hash will automatically @@ -42,10 +49,3 @@ const AmpScript: React.FC = ({ } export default AmpScript - -const generateInlineScript = (script: Function | string) => { - if (typeof script === 'function') { - return `${script.toString()}()` - } - return String(script) -} diff --git a/examples/cms-agilitycms/lib/components/rich-text-area.tsx b/examples/cms-agilitycms/lib/components/rich-text-area.tsx index f747cf0076534ea..7ff6f6f456dbfa2 100644 --- a/examples/cms-agilitycms/lib/components/rich-text-area.tsx +++ b/examples/cms-agilitycms/lib/components/rich-text-area.tsx @@ -1,3 +1,7 @@ +const setHTML = (textblob) => { + return { __html: textblob } +} + export default function RichTextArea({ fields }) { const { textblob } = fields return ( @@ -7,7 +11,3 @@ export default function RichTextArea({ fields }) { /> ) } - -const setHTML = (textblob) => { - return { __html: textblob } -} diff --git a/examples/cms-agilitycms/lib/dependancies.ts b/examples/cms-agilitycms/lib/dependancies.ts index 44ccead1baeef74..183fceba8ac3bba 100644 --- a/examples/cms-agilitycms/lib/dependancies.ts +++ b/examples/cms-agilitycms/lib/dependancies.ts @@ -3,6 +3,23 @@ const path = require('path') const userComponentsPath = path.resolve('./components') const libComponentsPath = path.resolve('./lib/components') +const requireComponent = (name) => { + let Component = null + + try { + //check the user path first (must be relative paths) + Component = require(`../components/${name}.tsx`).default + } catch {} + + if (!Component) + try { + //fallback to lib path (must be relative paths) + Component = require(`./components/${name}.tsx`).default + } catch {} + + return Component +} + //Bug: when dynamic imports are used within the module, it doest not get outputted server-side //let AgilityModule = dynamic(() => import ('../components/' + m.moduleName)); @@ -32,20 +49,3 @@ export const requireComponentDependancyByName = (name) => { return Component } - -const requireComponent = (name) => { - let Component = null - - try { - //check the user path first (must be relative paths) - Component = require(`../components/${name}.tsx`).default - } catch {} - - if (!Component) - try { - //fallback to lib path (must be relative paths) - Component = require(`./components/${name}.tsx`).default - } catch {} - - return Component -} diff --git a/examples/cms-agilitycms/lib/preview.ts b/examples/cms-agilitycms/lib/preview.ts index 7189f4ca398d13a..42e456df04b6730 100644 --- a/examples/cms-agilitycms/lib/preview.ts +++ b/examples/cms-agilitycms/lib/preview.ts @@ -2,45 +2,27 @@ import crypto from 'crypto' import { getClient } from './api' import { CMS_LANG, CMS_CHANNEL } from './constants' -//Validates whether the incoming preview request is valid -export async function validatePreview({ agilityPreviewKey, slug, contentID }) { - //Validate the preview key - if (!agilityPreviewKey) { - return { - error: true, - message: `Missing agilitypreviewkey.`, - } - } - - //sanitize incoming key (replace spaces with '+') - if (agilityPreviewKey.indexOf(` `) > -1) { - agilityPreviewKey = agilityPreviewKey.split(` `).join(`+`) - } - - //compare the preview key being used - const correctPreviewKey = generatePreviewKey() +//Generates a preview key to compare against +export function generatePreviewKey() { + //the string we want to encode + const str = `-1_${process.env.AGILITY_CMS_SECURITY_KEY}_Preview` - if (agilityPreviewKey !== correctPreviewKey) { - return { - error: true, - message: `Invalid agilitypreviewkey.`, - //message: `Invalid agilitypreviewkey. Incoming key is=${agilityPreviewKey} compared to=${correctPreviewKey}...` - } + //build our byte array + let data = [] + for (var i = 0; i < str.length; ++i) { + data.push(str.charCodeAt(i)) + data.push(0) } - const validateSlugResponse = await validateSlugForPreview({ slug, contentID }) - - if (validateSlugResponse.error) { - //kickout - return validateSlugResponse - } + //convert byte array to buffer + const strBuffer = Buffer.from(data) + //encode it! + const previewKey = crypto + .createHash('sha512') + .update(strBuffer) + .digest('base64') - //return success - return { - error: false, - message: null, - slug: validateSlugResponse.slug, - } + return previewKey } //Checks that the requested page exists, if not return a 401 @@ -95,25 +77,43 @@ export async function validateSlugForPreview({ slug, contentID }) { } } -//Generates a preview key to compare against -export function generatePreviewKey() { - //the string we want to encode - const str = `-1_${process.env.AGILITY_CMS_SECURITY_KEY}_Preview` +//Validates whether the incoming preview request is valid +export async function validatePreview({ agilityPreviewKey, slug, contentID }) { + //Validate the preview key + if (!agilityPreviewKey) { + return { + error: true, + message: `Missing agilitypreviewkey.`, + } + } - //build our byte array - let data = [] - for (var i = 0; i < str.length; ++i) { - data.push(str.charCodeAt(i)) - data.push(0) + //sanitize incoming key (replace spaces with '+') + if (agilityPreviewKey.indexOf(` `) > -1) { + agilityPreviewKey = agilityPreviewKey.split(` `).join(`+`) } - //convert byte array to buffer - const strBuffer = Buffer.from(data) - //encode it! - const previewKey = crypto - .createHash('sha512') - .update(strBuffer) - .digest('base64') + //compare the preview key being used + const correctPreviewKey = generatePreviewKey() - return previewKey + if (agilityPreviewKey !== correctPreviewKey) { + return { + error: true, + message: `Invalid agilitypreviewkey.`, + //message: `Invalid agilitypreviewkey. Incoming key is=${agilityPreviewKey} compared to=${correctPreviewKey}...` + } + } + + const validateSlugResponse = await validateSlugForPreview({ slug, contentID }) + + if (validateSlugResponse.error) { + //kickout + return validateSlugResponse + } + + //return success + return { + error: false, + message: null, + slug: validateSlugResponse.slug, + } } diff --git a/examples/cms-builder-io/lib/api.js b/examples/cms-builder-io/lib/api.js index 6b80cf062d97b63..14b287ab1fb0b28 100644 --- a/examples/cms-builder-io/lib/api.js +++ b/examples/cms-builder-io/lib/api.js @@ -11,13 +11,6 @@ export function getAllPostsWithSlug() { }) } -export function getAllPostsForHome(preview) { - return searchPosts( - { 'data.slug': { $exists: true }, 'data.author': { $exists: true } }, - preview - ) -} - export function getDraftPost(id) { return fetch( `https://builder.io/api/v2/content/${BUILDER_CONFIG.postsModel}/${id}?apiKey=${BUILDER_CONFIG.apiKey}&preview=true&noCache=true&cachebust=tru&includeRefs=true` @@ -26,25 +19,6 @@ export function getDraftPost(id) { .then((res) => res || null) } -export async function getPost(mongoQuery, preview) { - let post = preview - ? (await searchPosts(mongoQuery, true))?.[0] - : await builder - .get(BUILDER_CONFIG.postsModel, { - includeRefs: true, - staleCacheSeconds: 20, - apiKey: BUILDER_CONFIG.apiKey, - preview: BUILDER_CONFIG.postsModel, - options: { - noTargeting: true, - }, - query: mongoQuery, - }) - .toPromise() - - return post || null -} - export async function searchPosts(query, preview, limit = 20, offset = 0) { let posts = await builder.getAll(BUILDER_CONFIG.postsModel, { limit, @@ -67,6 +41,32 @@ export async function searchPosts(query, preview, limit = 20, offset = 0) { return posts } +export function getAllPostsForHome(preview) { + return searchPosts( + { 'data.slug': { $exists: true }, 'data.author': { $exists: true } }, + preview + ) +} + +export async function getPost(mongoQuery, preview) { + let post = preview + ? (await searchPosts(mongoQuery, true))?.[0] + : await builder + .get(BUILDER_CONFIG.postsModel, { + includeRefs: true, + staleCacheSeconds: 20, + apiKey: BUILDER_CONFIG.apiKey, + preview: BUILDER_CONFIG.postsModel, + options: { + noTargeting: true, + }, + query: mongoQuery, + }) + .toPromise() + + return post || null +} + export async function getPostAndMorePosts(slug, preview, previewData) { const post = preview && previewData diff --git a/examples/cms-buttercms/lib/api.js b/examples/cms-buttercms/lib/api.js index 5913ae1277efd1b..b4a07b946fdf01f 100644 --- a/examples/cms-buttercms/lib/api.js +++ b/examples/cms-buttercms/lib/api.js @@ -16,6 +16,24 @@ try { const defaultPageSize = 100 const defaultPostCount = 10 +async function getLandingPagesData(page, pageSize = defaultPageSize) { + try { + const params = { + page, + page_size: pageSize, + } + const response = await butter.page.list('landing-page', params) + + return { + pages: response?.data?.data, + prevPage: response?.data?.meta.previous_page, + nextPage: response?.data?.meta.next_page, + } + } catch (e) { + throw e.response.data.detail + } +} + export async function getLandingPage(slug) { try { const page = await butter.page.retrieve('landing-page', slug) @@ -38,24 +56,6 @@ export async function getLandingPages() { return paginatedLandingPages } -async function getLandingPagesData(page, pageSize = defaultPageSize) { - try { - const params = { - page, - page_size: pageSize, - } - const response = await butter.page.list('landing-page', params) - - return { - pages: response?.data?.data, - prevPage: response?.data?.meta.previous_page, - nextPage: response?.data?.meta.next_page, - } - } catch (e) { - throw e.response.data.detail - } -} - export async function getPostsData( { page, pageSize, tag, category } = { page: 1, pageSize: defaultPostCount } ) { diff --git a/examples/cms-kontent/components/image.js b/examples/cms-kontent/components/image.js index 7b47e9176ad06aa..bbf5694d9330d2a 100644 --- a/examples/cms-kontent/components/image.js +++ b/examples/cms-kontent/components/image.js @@ -1,10 +1,6 @@ import NextImage from 'next/image' import { transformImageUrl } from '@kentico/kontent-delivery' -const getLoader = (src) => { - return srcIsKontentAsset(src) ? kontentImageLoader : undefined -} - const srcIsKontentAsset = (src) => { try { const { hostname } = new URL(src) @@ -23,6 +19,10 @@ const kontentImageLoader = ({ src, width, quality = 75 }) => { .getUrl() } +const getLoader = (src) => { + return srcIsKontentAsset(src) ? kontentImageLoader : undefined +} + export default function Image(props) { const loader = getLoader(props.src) diff --git a/examples/with-aphrodite/pages/index.js b/examples/with-aphrodite/pages/index.js index 165a20546656c6d..e13f3adddf11a5a 100644 --- a/examples/with-aphrodite/pages/index.js +++ b/examples/with-aphrodite/pages/index.js @@ -7,14 +7,6 @@ if (typeof window !== 'undefined') { StyleSheet.rehydrate(window.__REHYDRATE_IDS) } -export default function Home() { - return ( -
-

My page

-
- ) -} - const styles = StyleSheet.create({ root: { width: 80, @@ -34,3 +26,11 @@ const styles = StyleSheet.create({ }, }, }) + +export default function Home() { + return ( +
+

My page

+
+ ) +} diff --git a/examples/with-apivideo-upload/components/Card/index.tsx b/examples/with-apivideo-upload/components/Card/index.tsx index 287da46ff84b62a..6f9d3a61f9e0272 100644 --- a/examples/with-apivideo-upload/components/Card/index.tsx +++ b/examples/with-apivideo-upload/components/Card/index.tsx @@ -8,19 +8,6 @@ interface ICardProps { method: 'get' | 'post' } -const Card: React.FC = ({ content, url, method }): JSX.Element => ( - - {method.toUpperCase()} - {content} - - Sketch arrow -

Try it out with our API!

-
-
-) - -export default Card - const Container = styled.a` border: 1px solid rgb(215, 219, 236); border-radius: 0.25rem; @@ -59,3 +46,16 @@ const ImageContainer = styled.div` font-size: 0.5rem; } ` + +const Card: React.FC = ({ content, url, method }): JSX.Element => ( + + {method.toUpperCase()} + {content} + + Sketch arrow +

Try it out with our API!

+
+
+) + +export default Card diff --git a/examples/with-apivideo-upload/components/Loader/index.tsx b/examples/with-apivideo-upload/components/Loader/index.tsx index 0b0bd14a8f1f007..9abbffdb189aa29 100644 --- a/examples/with-apivideo-upload/components/Loader/index.tsx +++ b/examples/with-apivideo-upload/components/Loader/index.tsx @@ -5,10 +5,6 @@ import styled, { keyframes } from 'styled-components' interface ILoaderProps { done: boolean } -const Loader: React.FC = ({ done }): JSX.Element => - done ? : - -export default Loader const spin = keyframes` 0% { @@ -18,6 +14,7 @@ const spin = keyframes` transform: rotate(360deg); } ` + const Spinner = styled.div` border: 3px solid #f3f3f3; border-top: 3px solid rgb(235, 137, 82); @@ -26,3 +23,8 @@ const Spinner = styled.div` height: 25px; animation: ${spin} 1s linear infinite; ` + +const Loader: React.FC = ({ done }): JSX.Element => + done ? : + +export default Loader diff --git a/examples/with-apivideo-upload/components/Status/index.tsx b/examples/with-apivideo-upload/components/Status/index.tsx index 90d494863c0fcfe..d83f8fc123545d2 100644 --- a/examples/with-apivideo-upload/components/Status/index.tsx +++ b/examples/with-apivideo-upload/components/Status/index.tsx @@ -6,6 +6,13 @@ interface IStatusProps { done: boolean title: string } + +const Container = styled.div` + display: flex; + flex-direction: column; + align-items: center; + gap: 5px; +` const Status: React.FC = ({ done, title }): JSX.Element => (

{title}

@@ -14,10 +21,3 @@ const Status: React.FC = ({ done, title }): JSX.Element => ( ) export default Status - -const Container = styled.div` - display: flex; - flex-direction: column; - align-items: center; - gap: 5px; -` diff --git a/examples/with-apivideo-upload/pages/index.tsx b/examples/with-apivideo-upload/pages/index.tsx index 24ec5d4edf99d90..63bb34361dff10d 100644 --- a/examples/with-apivideo-upload/pages/index.tsx +++ b/examples/with-apivideo-upload/pages/index.tsx @@ -42,6 +42,30 @@ const Home: NextPage = () => { fetcher ) + const fetchVideoStatus = async (videoId: string): Promise => { + const { status } = await fetcher(`/api/${videoId}`) + const { encoding, ingest } = status + setStatus({ + ingested: ingest.status === 'uploaded', + encoded: encoding.playable, + }) + if (ingest.status === 'uploaded' && encoding.playable) { + setSize({ + width: encoding.metadata.width, + height: encoding.metadata.height, + }) + setReady(true) + } + } + + const clearState = (): void => { + setReady(false) + setStatus({ ingested: false, encoded: false }) + setVideo(undefined) + setUploadProgress(undefined) + setSize(undefined) + } + useEffect(() => { if (video) { const intervalId = window.setInterval(() => { @@ -72,35 +96,11 @@ const Home: NextPage = () => { setVideo(video) } - const fetchVideoStatus = async (videoId: string): Promise => { - const { status } = await fetcher(`/api/${videoId}`) - const { encoding, ingest } = status - setStatus({ - ingested: ingest.status === 'uploaded', - encoded: encoding.playable, - }) - if (ingest.status === 'uploaded' && encoding.playable) { - setSize({ - width: encoding.metadata.width, - height: encoding.metadata.height, - }) - setReady(true) - } - } - const handleNavigate = (): void => { if (!video) return router.push(`/${video.videoId}?w=${size?.width}&h=${size?.height}`) } - const clearState = (): void => { - setReady(false) - setStatus({ ingested: false, encoded: false }) - setVideo(undefined) - setUploadProgress(undefined) - setSize(undefined) - } - return ( diff --git a/examples/with-apollo-and-redux/components/PostList.js b/examples/with-apollo-and-redux/components/PostList.js index d9b01d3ef1e6abd..a0eee23090ab88c 100644 --- a/examples/with-apollo-and-redux/components/PostList.js +++ b/examples/with-apollo-and-redux/components/PostList.js @@ -35,6 +35,8 @@ export default function PostList() { const loadingMorePosts = networkStatus === NetworkStatus.fetchMore + const { allPosts, _allPostsMeta } = data + const loadMorePosts = () => { fetchMore({ variables: { @@ -46,7 +48,6 @@ export default function PostList() { if (error) return if (loading && !loadingMorePosts) return
Loading
- const { allPosts, _allPostsMeta } = data const areMorePosts = allPosts.length < _allPostsMeta.count return ( diff --git a/examples/with-apollo/components/PostList.js b/examples/with-apollo/components/PostList.js index 4748ac8f35a6aa8..381c156e8189b85 100644 --- a/examples/with-apollo/components/PostList.js +++ b/examples/with-apollo/components/PostList.js @@ -35,6 +35,7 @@ export default function PostList() { ) const loadingMorePosts = networkStatus === NetworkStatus.fetchMore + const { allPosts, _allPostsMeta } = data const loadMorePosts = () => { fetchMore({ @@ -47,7 +48,6 @@ export default function PostList() { if (error) return if (loading && !loadingMorePosts) return
Loading
- const { allPosts, _allPostsMeta } = data const areMorePosts = allPosts.length < _allPostsMeta.count return ( diff --git a/examples/with-babel-macros/pages/index.js b/examples/with-babel-macros/pages/index.js index dea28155a3da0d8..0a0b2d5d6de90c7 100644 --- a/examples/with-babel-macros/pages/index.js +++ b/examples/with-babel-macros/pages/index.js @@ -5,9 +5,7 @@ const whoami = preval` module.exports = userInfo.username ` -export default WhoAmI - -function WhoAmI() { +export default function WhoAmI() { return (

diff --git a/examples/with-cerebral/components/Clock.js b/examples/with-cerebral/components/Clock.js index cfbddeae67ab19e..e2f4fcc8a3c31e3 100644 --- a/examples/with-cerebral/components/Clock.js +++ b/examples/with-cerebral/components/Clock.js @@ -1,3 +1,7 @@ +const pad = (n) => (n < 10 ? `0${n}` : n) +const format = (t) => + `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}` + export default function Clock(props) { return (
@@ -18,8 +22,3 @@ export default function Clock(props) {
) } - -const format = (t) => - `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}` - -const pad = (n) => (n < 10 ? `0${n}` : n) diff --git a/examples/with-cxs/pages/index.js b/examples/with-cxs/pages/index.js index bc7e660e5b2383e..fe092135537374c 100644 --- a/examples/with-cxs/pages/index.js +++ b/examples/with-cxs/pages/index.js @@ -8,14 +8,6 @@ if (typeof window !== 'undefined') { cxs.rehydrate(serverCss) } -export default function Home() { - return ( -
-

My page

-
- ) -} - const cx = { root: cxs({ width: 80, @@ -35,3 +27,11 @@ const cx = { }, }), } + +export default function Home() { + return ( +
+

My page

+
+ ) +} diff --git a/examples/with-draft-js/pages/index.js b/examples/with-draft-js/pages/index.js index 950f5b4aceaa731..3185ad29e701f55 100644 --- a/examples/with-draft-js/pages/index.js +++ b/examples/with-draft-js/pages/index.js @@ -7,6 +7,81 @@ import { convertFromRaw, } from 'draft-js' +const initialData = { + blocks: [ + { + key: '16d0k', + text: 'You can edit this text.', + type: 'unstyled', + depth: 0, + inlineStyleRanges: [{ offset: 0, length: 23, style: 'BOLD' }], + entityRanges: [], + data: {}, + }, + { + key: '98peq', + text: '', + type: 'unstyled', + depth: 0, + inlineStyleRanges: [], + entityRanges: [], + data: {}, + }, + { + key: 'ecmnc', + text: 'Luke Skywalker has vanished. In his absence, the sinister FIRST ORDER has risen from the ashes of the Empire and will not rest until Skywalker, the last Jedi, has been destroyed.', + type: 'unstyled', + depth: 0, + inlineStyleRanges: [ + { offset: 0, length: 14, style: 'BOLD' }, + { offset: 133, length: 9, style: 'BOLD' }, + ], + entityRanges: [], + data: {}, + }, + { + key: 'fe2gn', + text: '', + type: 'unstyled', + depth: 0, + inlineStyleRanges: [], + entityRanges: [], + data: {}, + }, + { + key: '4481k', + text: 'With the support of the REPUBLIC, General Leia Organa leads a brave RESISTANCE. She is desperate to find her brother Luke and gain his help in restoring peace and justice to the galaxy.', + type: 'unstyled', + depth: 0, + inlineStyleRanges: [ + { offset: 34, length: 19, style: 'BOLD' }, + { offset: 117, length: 4, style: 'BOLD' }, + { offset: 68, length: 10, style: 'ANYCUSTOMSTYLE' }, + ], + entityRanges: [], + data: {}, + }, + ], + entityMap: {}, +} + +// Custom overrides for each style +const styleMap = { + CODE: { + backgroundColor: 'rgba(0, 0, 0, 0.05)', + fontFamily: '"Inconsolata", "Menlo", "Consolas", monospace', + fontSize: 16, + padding: 4, + }, + BOLD: { + color: '#395296', + fontWeight: 'bold', + }, + ANYCUSTOMSTYLE: { + color: '#00e400', + }, +} + export default class App extends Component { constructor(props) { super(props) @@ -223,23 +298,6 @@ export default class App extends Component { } } -// Custom overrides for each style -const styleMap = { - CODE: { - backgroundColor: 'rgba(0, 0, 0, 0.05)', - fontFamily: '"Inconsolata", "Menlo", "Consolas", monospace', - fontSize: 16, - padding: 4, - }, - BOLD: { - color: '#395296', - fontWeight: 'bold', - }, - ANYCUSTOMSTYLE: { - color: '#00e400', - }, -} - class ToolbarButton extends Component { constructor() { super() @@ -285,61 +343,3 @@ const ToolBar = (props) => {

) } - -const initialData = { - blocks: [ - { - key: '16d0k', - text: 'You can edit this text.', - type: 'unstyled', - depth: 0, - inlineStyleRanges: [{ offset: 0, length: 23, style: 'BOLD' }], - entityRanges: [], - data: {}, - }, - { - key: '98peq', - text: '', - type: 'unstyled', - depth: 0, - inlineStyleRanges: [], - entityRanges: [], - data: {}, - }, - { - key: 'ecmnc', - text: 'Luke Skywalker has vanished. In his absence, the sinister FIRST ORDER has risen from the ashes of the Empire and will not rest until Skywalker, the last Jedi, has been destroyed.', - type: 'unstyled', - depth: 0, - inlineStyleRanges: [ - { offset: 0, length: 14, style: 'BOLD' }, - { offset: 133, length: 9, style: 'BOLD' }, - ], - entityRanges: [], - data: {}, - }, - { - key: 'fe2gn', - text: '', - type: 'unstyled', - depth: 0, - inlineStyleRanges: [], - entityRanges: [], - data: {}, - }, - { - key: '4481k', - text: 'With the support of the REPUBLIC, General Leia Organa leads a brave RESISTANCE. She is desperate to find her brother Luke and gain his help in restoring peace and justice to the galaxy.', - type: 'unstyled', - depth: 0, - inlineStyleRanges: [ - { offset: 34, length: 19, style: 'BOLD' }, - { offset: 117, length: 4, style: 'BOLD' }, - { offset: 68, length: 10, style: 'ANYCUSTOMSTYLE' }, - ], - entityRanges: [], - data: {}, - }, - ], - entityMap: {}, -} diff --git a/examples/with-edgedb/pages/api/post/[id].ts b/examples/with-edgedb/pages/api/post/[id].ts index 32aa946615b929f..a1971a52bc0e3ef 100644 --- a/examples/with-edgedb/pages/api/post/[id].ts +++ b/examples/with-edgedb/pages/api/post/[id].ts @@ -1,23 +1,6 @@ import type { NextApiRequest, NextApiResponse } from 'next' import { client, e } from '../../../client' -export default async function handle( - req: NextApiRequest, - res: NextApiResponse -) { - const postId = req.query.id as string - - if (req.method === 'DELETE') { - res.json(await deletePost(postId)) - } else if (req.method === 'PATCH') { - res.json(await updatePost(postId, req.body)) - } else { - throw new Error( - `The HTTP ${req.method} method is not supported at this route.` - ) - } -} - // PATCH /api/post/:id async function updatePost( postId: string, @@ -42,3 +25,20 @@ async function deletePost(postId: string) { })) .run(client) } + +export default async function handle( + req: NextApiRequest, + res: NextApiResponse +) { + const postId = req.query.id as string + + if (req.method === 'DELETE') { + res.json(await deletePost(postId)) + } else if (req.method === 'PATCH') { + res.json(await updatePost(postId, req.body)) + } else { + throw new Error( + `The HTTP ${req.method} method is not supported at this route.` + ) + } +} diff --git a/examples/with-expo-typescript/pages/index.tsx b/examples/with-expo-typescript/pages/index.tsx index a833b7b6d98ae3f..61d3eba5202f577 100644 --- a/examples/with-expo-typescript/pages/index.tsx +++ b/examples/with-expo-typescript/pages/index.tsx @@ -2,14 +2,6 @@ import React from 'react' import { StyleSheet, Text, View } from 'react-native' -export default function App() { - return ( - - Welcome to Expo + Next.js 👋 - - ) -} - const styles = StyleSheet.create({ container: { flex: 1, @@ -20,3 +12,11 @@ const styles = StyleSheet.create({ fontSize: 16, }, }) + +export default function App() { + return ( + + Welcome to Expo + Next.js 👋 + + ) +} diff --git a/examples/with-expo/pages/index.js b/examples/with-expo/pages/index.js index 7bf300c94990fe3..90b9d18c7086f56 100644 --- a/examples/with-expo/pages/index.js +++ b/examples/with-expo/pages/index.js @@ -1,14 +1,6 @@ // @generated: @expo/next-adapter@2.1.5 import { StyleSheet, Text, View } from 'react-native' -export default function App() { - return ( - - Welcome to Expo + Next.js 👋 - - ) -} - const styles = StyleSheet.create({ container: { flex: 1, @@ -19,3 +11,11 @@ const styles = StyleSheet.create({ fontSize: 16, }, }) + +export default function App() { + return ( + + Welcome to Expo + Next.js 👋 + + ) +} diff --git a/examples/with-fingerprintjs-pro/components/Nav.tsx b/examples/with-fingerprintjs-pro/components/Nav.tsx index 3315c84c36a0edc..0e8ff28a3d78e05 100644 --- a/examples/with-fingerprintjs-pro/components/Nav.tsx +++ b/examples/with-fingerprintjs-pro/components/Nav.tsx @@ -3,15 +3,6 @@ import { useRouter } from 'next/router' import Link from 'next/link' import { RouterProps } from './types' -export const Nav: React.FC = () => { - return ( - - ) -} - const CustomLink: React.FC> = ({ to, children, @@ -35,3 +26,12 @@ const CustomLink: React.FC> = ({ ) } + +export const Nav: React.FC = () => { + return ( + + ) +} diff --git a/examples/with-fingerprintjs-pro/pages/home/[cacheStrategy].tsx b/examples/with-fingerprintjs-pro/pages/home/[cacheStrategy].tsx index 5f67e8eef36b4b8..c9a786a6bcef334 100644 --- a/examples/with-fingerprintjs-pro/pages/home/[cacheStrategy].tsx +++ b/examples/with-fingerprintjs-pro/pages/home/[cacheStrategy].tsx @@ -6,6 +6,14 @@ import { useVisitorData, } from '@fingerprintjs/fingerprintjs-pro-react' +function VisitorDataComponent() { + const { data, isLoading, error } = useVisitorData({ extendedResult: true }) + + return ( + + ) +} + function HomePage() { const { clearCache } = useContext(FpjsContext) @@ -27,12 +35,4 @@ function HomePage() { ) } -function VisitorDataComponent() { - const { data, isLoading, error } = useVisitorData({ extendedResult: true }) - - return ( - - ) -} - export default HomePage diff --git a/examples/with-graphql-hooks/components/submit.js b/examples/with-graphql-hooks/components/submit.js index 71e7fb8395a5ec6..ca69203795bdf11 100644 --- a/examples/with-graphql-hooks/components/submit.js +++ b/examples/with-graphql-hooks/components/submit.js @@ -12,6 +12,22 @@ mutation createPost($title: String!, $url: String!) { } }` +async function handleSubmit(event, onSubmission, createPost) { + event.preventDefault() + const form = event.target + const formData = new window.FormData(form) + const title = formData.get('title') + const url = formData.get('url') + form.reset() + const result = await createPost({ + variables: { + title, + url, + }, + }) + onSubmission && onSubmission(result) +} + export default function Submit({ onSubmission }) { const [createPost, state] = useMutation(CREATE_POST) @@ -38,19 +54,3 @@ export default function Submit({ onSubmission }) { ) } - -async function handleSubmit(event, onSubmission, createPost) { - event.preventDefault() - const form = event.target - const formData = new window.FormData(form) - const title = formData.get('title') - const url = formData.get('url') - form.reset() - const result = await createPost({ - variables: { - title, - url, - }, - }) - onSubmission && onSubmission(result) -} diff --git a/examples/with-iron-session/lib/fetchJson.ts b/examples/with-iron-session/lib/fetchJson.ts index d8402eb865742e1..7165e84b92d3dd5 100644 --- a/examples/with-iron-session/lib/fetchJson.ts +++ b/examples/with-iron-session/lib/fetchJson.ts @@ -1,26 +1,3 @@ -export default async function fetchJson( - input: RequestInfo, - init?: RequestInit -): Promise { - const response = await fetch(input, init) - - // if the server replies, there's always some data in json - // if there's a network error, it will throw at the previous line - const data = await response.json() - - // response.ok is true when res.status is 2xx - // https://developer.mozilla.org/en-US/docs/Web/API/Response/ok - if (response.ok) { - return data - } - - throw new FetchError({ - message: response.statusText, - response, - data, - }) -} - export class FetchError extends Error { response: Response data: { @@ -50,3 +27,26 @@ export class FetchError extends Error { this.data = data ?? { message: message } } } + +export default async function fetchJson( + input: RequestInfo, + init?: RequestInit +): Promise { + const response = await fetch(input, init) + + // if the server replies, there's always some data in json + // if there's a network error, it will throw at the previous line + const data = await response.json() + + // response.ok is true when res.status is 2xx + // https://developer.mozilla.org/en-US/docs/Web/API/Response/ok + if (response.ok) { + return data + } + + throw new FetchError({ + message: response.statusText, + response, + data, + }) +} diff --git a/examples/with-iron-session/pages/api/events.ts b/examples/with-iron-session/pages/api/events.ts index d946088e9277af1..91ed59a494713e2 100644 --- a/examples/with-iron-session/pages/api/events.ts +++ b/examples/with-iron-session/pages/api/events.ts @@ -10,8 +10,6 @@ export type Events = const octokit = new Octokit() -export default withIronSessionApiRoute(eventsRoute, sessionOptions) - async function eventsRoute(req: NextApiRequest, res: NextApiResponse) { const user = req.session.user @@ -31,3 +29,5 @@ async function eventsRoute(req: NextApiRequest, res: NextApiResponse) { res.status(200).json([]) } } + +export default withIronSessionApiRoute(eventsRoute, sessionOptions) diff --git a/examples/with-iron-session/pages/api/login.ts b/examples/with-iron-session/pages/api/login.ts index 9fa2e84cf3e1e0d..c9f094ae429d782 100644 --- a/examples/with-iron-session/pages/api/login.ts +++ b/examples/with-iron-session/pages/api/login.ts @@ -6,8 +6,6 @@ import { sessionOptions } from 'lib/session' import { NextApiRequest, NextApiResponse } from 'next' const octokit = new Octokit() -export default withIronSessionApiRoute(loginRoute, sessionOptions) - async function loginRoute(req: NextApiRequest, res: NextApiResponse) { const { username } = await req.body @@ -24,3 +22,5 @@ async function loginRoute(req: NextApiRequest, res: NextApiResponse) { res.status(500).json({ message: (error as Error).message }) } } + +export default withIronSessionApiRoute(loginRoute, sessionOptions) diff --git a/examples/with-iron-session/pages/api/logout.ts b/examples/with-iron-session/pages/api/logout.ts index cbbfb6a9ee210d8..e081136289bca1a 100644 --- a/examples/with-iron-session/pages/api/logout.ts +++ b/examples/with-iron-session/pages/api/logout.ts @@ -3,9 +3,9 @@ import { sessionOptions } from 'lib/session' import { NextApiRequest, NextApiResponse } from 'next' import type { User } from 'pages/api/user' -export default withIronSessionApiRoute(logoutRoute, sessionOptions) - function logoutRoute(req: NextApiRequest, res: NextApiResponse) { req.session.destroy() res.json({ isLoggedIn: false, login: '', avatarUrl: '' }) } + +export default withIronSessionApiRoute(logoutRoute, sessionOptions) diff --git a/examples/with-iron-session/pages/api/user.ts b/examples/with-iron-session/pages/api/user.ts index 7de3d3b2199942b..e7249a427e02282 100644 --- a/examples/with-iron-session/pages/api/user.ts +++ b/examples/with-iron-session/pages/api/user.ts @@ -8,8 +8,6 @@ export type User = { avatarUrl: string } -export default withIronSessionApiRoute(userRoute, sessionOptions) - async function userRoute(req: NextApiRequest, res: NextApiResponse) { if (req.session.user) { // in a real world application you might read the user id from the session and then do a database request @@ -26,3 +24,5 @@ async function userRoute(req: NextApiRequest, res: NextApiResponse) { }) } } + +export default withIronSessionApiRoute(userRoute, sessionOptions) diff --git a/examples/with-mobx-react-lite/components/StoreProvider.js b/examples/with-mobx-react-lite/components/StoreProvider.js index 9f8cdd1be49249f..8484b5a3eb9147d 100644 --- a/examples/with-mobx-react-lite/components/StoreProvider.js +++ b/examples/with-mobx-react-lite/components/StoreProvider.js @@ -13,12 +13,6 @@ export function useStore() { return context } -export function StoreProvider({ children, initialState: initialData }) { - const store = initializeStore(initialData) - - return {children} -} - function initializeStore(initialData = null) { const _store = store ?? new Store() @@ -34,3 +28,9 @@ function initializeStore(initialData = null) { return _store } + +export function StoreProvider({ children, initialState: initialData }) { + const store = initializeStore(initialData) + + return {children} +} diff --git a/examples/with-mobx-state-tree-typescript/components/Clock.tsx b/examples/with-mobx-state-tree-typescript/components/Clock.tsx index ddf2dd6c51878f9..19ea8d84f6681e4 100644 --- a/examples/with-mobx-state-tree-typescript/components/Clock.tsx +++ b/examples/with-mobx-state-tree-typescript/components/Clock.tsx @@ -1,6 +1,6 @@ +const pad = (n) => (n < 10 ? `0${n}` : n) const format = (t) => `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}` -const pad = (n) => (n < 10 ? `0${n}` : n) const Clock = (props) => { const divStyle = { diff --git a/examples/with-mongodb-mongoose/components/Form.js b/examples/with-mongodb-mongoose/components/Form.js index 968df84a86ba6df..03b754e7934c4c3 100644 --- a/examples/with-mongodb-mongoose/components/Form.js +++ b/examples/with-mongodb-mongoose/components/Form.js @@ -83,16 +83,6 @@ const Form = ({ formId, petForm, forNewPet = true }) => { }) } - const handleSubmit = (e) => { - e.preventDefault() - const errs = formValidate() - if (Object.keys(errs).length === 0) { - forNewPet ? postData(form) : putData(form) - } else { - setErrors({ errs }) - } - } - /* Makes sure pet info is filled for pet name, owner name, species, and image url*/ const formValidate = () => { let err = {} @@ -103,6 +93,16 @@ const Form = ({ formId, petForm, forNewPet = true }) => { return err } + const handleSubmit = (e) => { + e.preventDefault() + const errs = formValidate() + if (Object.keys(errs).length === 0) { + forNewPet ? postData(form) : putData(form) + } else { + setErrors({ errs }) + } + } + return ( <>
diff --git a/examples/with-react-native-web/pages/alternate.js b/examples/with-react-native-web/pages/alternate.js index e8fc16ec8b693da..1184ce94f2e6c92 100644 --- a/examples/with-react-native-web/pages/alternate.js +++ b/examples/with-react-native-web/pages/alternate.js @@ -1,19 +1,5 @@ import { StyleSheet, Text, View } from 'react-native' -export default function Alternate() { - return ( - - - Alternate Page - - - - Go Back - - - ) -} - const styles = StyleSheet.create({ container: { alignItems: 'center', @@ -29,3 +15,17 @@ const styles = StyleSheet.create({ color: 'blue', }, }) + +export default function Alternate() { + return ( + + + Alternate Page + + + + Go Back + + + ) +} diff --git a/examples/with-react-native-web/pages/index.js b/examples/with-react-native-web/pages/index.js index cac53ebcd5e7469..3fa857406993522 100644 --- a/examples/with-react-native-web/pages/index.js +++ b/examples/with-react-native-web/pages/index.js @@ -1,25 +1,5 @@ import { StyleSheet, Text, View } from 'react-native' -export default function App(props) { - return ( - - - React Native for Web & Next.js - - - - A universal link - - - - - Subheader - - - - ) -} - const styles = StyleSheet.create({ container: { alignItems: 'center', @@ -39,3 +19,23 @@ const styles = StyleSheet.create({ marginBottom: 24, }, }) + +export default function App(props) { + return ( + + + React Native for Web & Next.js + + + + A universal link + + + + + Subheader + + + + ) +} diff --git a/examples/with-redis/pages/api/subscribe.ts b/examples/with-redis/pages/api/subscribe.ts index 544558c36df309f..6f3bac267bd78fb 100644 --- a/examples/with-redis/pages/api/subscribe.ts +++ b/examples/with-redis/pages/api/subscribe.ts @@ -2,6 +2,12 @@ import type { NextApiRequest, NextApiResponse } from 'next' import redis from '../../lib/redis' +function validateEmail(email: string) { + const re = + /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ + return re.test(String(email).toLowerCase()) +} + export default async function subscribe( req: NextApiRequest, res: NextApiResponse @@ -19,9 +25,3 @@ export default async function subscribe( }) } } - -function validateEmail(email: string) { - const re = - /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ - return re.test(String(email).toLowerCase()) -} diff --git a/examples/with-redux-wrapper/components/Clock.js b/examples/with-redux-wrapper/components/Clock.js index 6b13e9ebb4d65ab..57523ec179271c6 100644 --- a/examples/with-redux-wrapper/components/Clock.js +++ b/examples/with-redux-wrapper/components/Clock.js @@ -1,3 +1,7 @@ +const pad = (n) => (n < 10 ? `0${n}` : n) +const format = (t) => + `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}` + export default function Clock({ lastUpdate, light }) { return (
@@ -18,8 +22,3 @@ export default function Clock({ lastUpdate, light }) {
) } - -const format = (t) => - `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}` - -const pad = (n) => (n < 10 ? `0${n}` : n)