Unverified Commit ed81a149 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Enable @typescript-eslint/no-use-before-define for examples dir (#39469)



Found that this rule was added but all options are set to `false` so it doesn't do anything. Started with enabling it for examples to ensure minimal breaking of existing PRs.

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
parent 01888dcb
......@@ -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",
{
......
......@@ -319,6 +319,10 @@ export function AmpIncludeAmpLinkRewriter() {
return <AmpIncludeCustomElement name="amp-link-rewriter" version="0.1" />
}
export function AmpIncludeAmpMustache() {
return <AmpIncludeCustomTemplate name="amp-mustache" version="0.2" />
}
export function AmpIncludeAmpList() {
return (
<>
......@@ -350,10 +354,6 @@ export function AmpIncludeAmpMowplayer() {
return <AmpIncludeCustomElement name="amp-mowplayer" version="0.1" />
}
export function AmpIncludeAmpMustache() {
return <AmpIncludeCustomTemplate name="amp-mustache" version="0.2" />
}
export function AmpIncludeAmpNextPage() {
return <AmpIncludeCustomElement name="amp-next-page" version="0.1" />
}
......
......@@ -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<AmpScriptProps> = ({
}
export default AmpScript
const generateInlineScript = (script: Function | string) => {
if (typeof script === 'function') {
return `${script.toString()}()`
}
return String(script)
}
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 }
}
......@@ -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
}
......@@ -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,
}
}
......@@ -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
......
......@@ -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 }
) {
......
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)
......
......@@ -7,14 +7,6 @@ if (typeof window !== 'undefined') {
StyleSheet.rehydrate(window.__REHYDRATE_IDS)
}
export default function Home() {
return (
<div className={css(styles.root)}>
<h1 className={css(styles.title)}>My page</h1>
</div>
)
}
const styles = StyleSheet.create({
root: {
width: 80,
......@@ -34,3 +26,11 @@ const styles = StyleSheet.create({
},
},
})
export default function Home() {
return (
<div className={css(styles.root)}>
<h1 className={css(styles.title)}>My page</h1>
</div>
)
}
......@@ -8,19 +8,6 @@ interface ICardProps {
method: 'get' | 'post'
}
const Card: React.FC<ICardProps> = ({ content, url, method }): JSX.Element => (
<Container target="_blank" href={url}>
<Method $method={method}>{method.toUpperCase()}</Method>
<Content>{content}</Content>
<ImageContainer>
<Image src="/arrow.png" alt="Sketch arrow" width={20} height={20} />
<p>Try it out with our API!</p>
</ImageContainer>
</Container>
)
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<ICardProps> = ({ content, url, method }): JSX.Element => (
<Container target="_blank" href={url}>
<Method $method={method}>{method.toUpperCase()}</Method>
<Content>{content}</Content>
<ImageContainer>
<Image src="/arrow.png" alt="Sketch arrow" width={20} height={20} />
<p>Try it out with our API!</p>
</ImageContainer>
</Container>
)
export default Card
......@@ -5,10 +5,6 @@ import styled, { keyframes } from 'styled-components'
interface ILoaderProps {
done: boolean
}
const Loader: React.FC<ILoaderProps> = ({ done }): JSX.Element =>
done ? <Image src="/check.png" width={30} height={30} /> : <Spinner />
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<ILoaderProps> = ({ done }): JSX.Element =>
done ? <Image src="/check.png" width={30} height={30} /> : <Spinner />
export default Loader
......@@ -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<IStatusProps> = ({ done, title }): JSX.Element => (
<Container>
<p>{title}</p>
......@@ -14,10 +21,3 @@ const Status: React.FC<IStatusProps> = ({ done, title }): JSX.Element => (
)
export default Status
const Container = styled.div`
display: flex;
flex-direction: column;
align-items: center;
gap: 5px;
`
......@@ -42,6 +42,30 @@ const Home: NextPage = () => {
fetcher
)
const fetchVideoStatus = async (videoId: string): Promise<void> => {
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<void> => {
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 (
<GlobalContainer>
<Head>
......
......@@ -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 <ErrorMessage message="Error loading posts." />
if (loading && !loadingMorePosts) return <div>Loading</div>
const { allPosts, _allPostsMeta } = data
const areMorePosts = allPosts.length < _allPostsMeta.count
return (
......
......@@ -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 <ErrorMessage message="Error loading posts." />
if (loading && !loadingMorePosts) return <div>Loading</div>
const { allPosts, _allPostsMeta } = data
const areMorePosts = allPosts.length < _allPostsMeta.count
return (
......
......@@ -5,9 +5,7 @@ const whoami = preval`
module.exports = userInfo.username
`
export default WhoAmI
function WhoAmI() {
export default function WhoAmI() {
return (
<div style={{ display: 'flex', justifyContent: 'center' }}>
<h1>
......
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 (
<div className={props.light ? 'light' : ''}>
......@@ -18,8 +22,3 @@ export default function Clock(props) {
</div>
)
}
const format = (t) =>
`${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`
const pad = (n) => (n < 10 ? `0${n}` : n)
......@@ -8,14 +8,6 @@ if (typeof window !== 'undefined') {
cxs.rehydrate(serverCss)
}
export default function Home() {
return (
<div className={cx.root}>
<h1 className={cx.title}>My page</h1>
</div>
)
}
const cx = {
root: cxs({
width: 80,
......@@ -35,3 +27,11 @@ const cx = {
},
}),
}
export default function Home() {
return (
<div className={cx.root}>
<h1 className={cx.title}>My page</h1>
</div>
)
}
......@@ -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) => {
</div>
)
}
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: {},
}
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.`
)
}
}
......@@ -2,14 +2,6 @@
import React from 'react'
import { StyleSheet, Text, View } from 'react-native'
export default function App() {
return (
<View style={styles.container}>
<Text style={styles.text}>Welcome to Expo + Next.js 👋</Text>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
......@@ -20,3 +12,11 @@ const styles = StyleSheet.create({
fontSize: 16,
},
})
export default function App() {
return (
<View style={styles.container}>
<Text style={styles.text}>Welcome to Expo + Next.js 👋</Text>
</View>
)
}
// @generated: @expo/next-adapter@2.1.5
import { StyleSheet, Text, View } from 'react-native'
export default function App() {
return (
<View style={styles.container}>
<Text style={styles.text}>Welcome to Expo + Next.js 👋</Text>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
......@@ -19,3 +11,11 @@ const styles = StyleSheet.create({
fontSize: 16,
},
})
export default function App() {
return (
<View style={styles.container}>
<Text style={styles.text}>Welcome to Expo + Next.js 👋</Text>
</View>
)
}
......@@ -3,15 +3,6 @@ import { useRouter } from 'next/router'
import Link from 'next/link'
import { RouterProps } from './types'
export const Nav: React.FC = () => {
return (
<nav className="nav">
<CustomLink to="home">Home</CustomLink>
<CustomLink to="signin">Sign in</CustomLink>
</nav>
)
}
const CustomLink: React.FC<PropsWithChildren<{ to: string }>> = ({
to,
children,
......@@ -35,3 +26,12 @@ const CustomLink: React.FC<PropsWithChildren<{ to: string }>> = ({
</div>
)
}
export const Nav: React.FC = () => {
return (
<nav className="nav">
<CustomLink to="home">Home</CustomLink>
<CustomLink to="signin">Sign in</CustomLink>
</nav>
)
}
......@@ -6,6 +6,14 @@ import {
useVisitorData,
} from '@fingerprintjs/fingerprintjs-pro-react'
function VisitorDataComponent() {
const { data, isLoading, error } = useVisitorData({ extendedResult: true })
return (
<VisitorDataPresenter data={data} isLoading={isLoading} error={error} />
)
}
function HomePage() {
const { clearCache } = useContext(FpjsContext)
......@@ -27,12 +35,4 @@ function HomePage() {
)
}
function VisitorDataComponent() {
const { data, isLoading, error } = useVisitorData({ extendedResult: true })
return (
<VisitorDataPresenter data={data} isLoading={isLoading} error={error} />
)
}
export default HomePage
......@@ -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 }) {
</form>
)
}
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 async function fetchJson<JSON = unknown>(
input: RequestInfo,
init?: RequestInit
): Promise<JSON> {
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<JSON = unknown>(
input: RequestInfo,
init?: RequestInit
): Promise<JSON> {
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,
})
}
......@@ -10,8 +10,6 @@ export type Events =
const octokit = new Octokit()
export default withIronSessionApiRoute(eventsRoute, sessionOptions)
async function eventsRoute(req: NextApiRequest, res: NextApiResponse<Events>) {
const user = req.session.user
......@@ -31,3 +29,5 @@ async function eventsRoute(req: NextApiRequest, res: NextApiResponse<Events>) {
res.status(200).json([])
}
}
export default withIronSessionApiRoute(eventsRoute, sessionOptions)
......@@ -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)
......@@ -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<User>) {
req.session.destroy()
res.json({ isLoggedIn: false, login: '', avatarUrl: '' })
}
export default withIronSessionApiRoute(logoutRoute, sessionOptions)
......@@ -8,8 +8,6 @@ export type User = {
avatarUrl: string
}
export default withIronSessionApiRoute(userRoute, sessionOptions)
async function userRoute(req: NextApiRequest, res: NextApiResponse<User>) {
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<User>) {
})
}
}
export default withIronSessionApiRoute(userRoute, sessionOptions)
......@@ -13,12 +13,6 @@ export function useStore() {
return context
}
export function StoreProvider({ children, initialState: initialData }) {
const store = initializeStore(initialData)
return <StoreContext.Provider value={store}>{children}</StoreContext.Provider>
}
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 <StoreContext.Provider value={store}>{children}</StoreContext.Provider>
}
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 = {
......
......@@ -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 (
<>
<form id={formId} onSubmit={handleSubmit}>
......
import { StyleSheet, Text, View } from 'react-native'
export default function Alternate() {
return (
<View style={styles.container}>
<Text accessibilityRole="header" style={styles.text}>
Alternate Page
</Text>
<Text style={styles.link} accessibilityRole="link" href={`/`}>
Go Back
</Text>
</View>
)
}
const styles = StyleSheet.create({
container: {
alignItems: 'center',
......@@ -29,3 +15,17 @@ const styles = StyleSheet.create({
color: 'blue',
},
})
export default function Alternate() {
return (
<View style={styles.container}>
<Text accessibilityRole="header" style={styles.text}>
Alternate Page
</Text>
<Text style={styles.link} accessibilityRole="link" href={`/`}>
Go Back
</Text>
</View>
)
}
import { StyleSheet, Text, View } from 'react-native'
export default function App(props) {
return (
<View style={styles.container}>
<Text accessibilityRole="header" style={styles.text}>
React Native for Web & Next.js
</Text>
<Text style={styles.link} accessibilityRole="link" href={`/alternate`}>
A universal link
</Text>
<View style={styles.textContainer}>
<Text accessibilityRole="header" aria-level="2" style={styles.text}>
Subheader
</Text>
</View>
</View>
)
}
const styles = StyleSheet.create({
container: {
alignItems: 'center',
......@@ -39,3 +19,23 @@ const styles = StyleSheet.create({
marginBottom: 24,
},
})
export default function App(props) {
return (
<View style={styles.container}>
<Text accessibilityRole="header" style={styles.text}>
React Native for Web & Next.js
</Text>
<Text style={styles.link} accessibilityRole="link" href={`/alternate`}>
A universal link
</Text>
<View style={styles.textContainer}>
<Text accessibilityRole="header" aria-level="2" style={styles.text}>
Subheader
</Text>
</View>
</View>
)
}
......@@ -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())
}
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 (
<div className={light ? 'light' : ''}>
......@@ -18,8 +22,3 @@ export default function Clock({ lastUpdate, light }) {
</div>
)
}
const format = (t) =>
`${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`
const pad = (n) => (n < 10 ? `0${n}` : n)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment