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 @@ ...@@ -71,6 +71,7 @@
"functions": false, "functions": false,
"classes": false, "classes": false,
"variables": false, "variables": false,
"enums": false,
"typedefs": false "typedefs": false
} }
], ],
...@@ -106,6 +107,16 @@ ...@@ -106,6 +107,16 @@
{ {
"files": ["examples/**/*"], "files": ["examples/**/*"],
"rules": { "rules": {
"@typescript-eslint/no-use-before-define": [
"error",
{
"functions": true,
"classes": true,
"variables": true,
"enums": true,
"typedefs": true
}
],
"import/no-anonymous-default-export": [ "import/no-anonymous-default-export": [
"error", "error",
{ {
......
...@@ -319,6 +319,10 @@ export function AmpIncludeAmpLinkRewriter() { ...@@ -319,6 +319,10 @@ export function AmpIncludeAmpLinkRewriter() {
return <AmpIncludeCustomElement name="amp-link-rewriter" version="0.1" /> return <AmpIncludeCustomElement name="amp-link-rewriter" version="0.1" />
} }
export function AmpIncludeAmpMustache() {
return <AmpIncludeCustomTemplate name="amp-mustache" version="0.2" />
}
export function AmpIncludeAmpList() { export function AmpIncludeAmpList() {
return ( return (
<> <>
...@@ -350,10 +354,6 @@ export function AmpIncludeAmpMowplayer() { ...@@ -350,10 +354,6 @@ export function AmpIncludeAmpMowplayer() {
return <AmpIncludeCustomElement name="amp-mowplayer" version="0.1" /> return <AmpIncludeCustomElement name="amp-mowplayer" version="0.1" />
} }
export function AmpIncludeAmpMustache() {
return <AmpIncludeCustomTemplate name="amp-mustache" version="0.2" />
}
export function AmpIncludeAmpNextPage() { export function AmpIncludeAmpNextPage() {
return <AmpIncludeCustomElement name="amp-next-page" version="0.1" /> return <AmpIncludeCustomElement name="amp-next-page" version="0.1" />
} }
......
...@@ -10,6 +10,13 @@ type AmpScriptProps = { ...@@ -10,6 +10,13 @@ type AmpScriptProps = {
src?: string 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 * 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 * AMP Script via the `script` property. The inline script hash will automatically
...@@ -42,10 +49,3 @@ const AmpScript: React.FC<AmpScriptProps> = ({ ...@@ -42,10 +49,3 @@ const AmpScript: React.FC<AmpScriptProps> = ({
} }
export default AmpScript 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 }) { export default function RichTextArea({ fields }) {
const { textblob } = fields const { textblob } = fields
return ( return (
...@@ -7,7 +11,3 @@ export default function RichTextArea({ fields }) { ...@@ -7,7 +11,3 @@ export default function RichTextArea({ fields }) {
/> />
) )
} }
const setHTML = (textblob) => {
return { __html: textblob }
}
...@@ -3,6 +3,23 @@ const path = require('path') ...@@ -3,6 +3,23 @@ const path = require('path')
const userComponentsPath = path.resolve('./components') const userComponentsPath = path.resolve('./components')
const libComponentsPath = path.resolve('./lib/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 //Bug: when dynamic imports are used within the module, it doest not get outputted server-side
//let AgilityModule = dynamic(() => import ('../components/' + m.moduleName)); //let AgilityModule = dynamic(() => import ('../components/' + m.moduleName));
...@@ -32,20 +49,3 @@ export const requireComponentDependancyByName = (name) => { ...@@ -32,20 +49,3 @@ export const requireComponentDependancyByName = (name) => {
return Component 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' ...@@ -2,45 +2,27 @@ import crypto from 'crypto'
import { getClient } from './api' import { getClient } from './api'
import { CMS_LANG, CMS_CHANNEL } from './constants' import { CMS_LANG, CMS_CHANNEL } from './constants'
//Validates whether the incoming preview request is valid //Generates a preview key to compare against
export async function validatePreview({ agilityPreviewKey, slug, contentID }) { export function generatePreviewKey() {
//Validate the preview key //the string we want to encode
if (!agilityPreviewKey) { const str = `-1_${process.env.AGILITY_CMS_SECURITY_KEY}_Preview`
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()
if (agilityPreviewKey !== correctPreviewKey) { //build our byte array
return { let data = []
error: true, for (var i = 0; i < str.length; ++i) {
message: `Invalid agilitypreviewkey.`, data.push(str.charCodeAt(i))
//message: `Invalid agilitypreviewkey. Incoming key is=${agilityPreviewKey} compared to=${correctPreviewKey}...` data.push(0)
}
} }
const validateSlugResponse = await validateSlugForPreview({ slug, contentID }) //convert byte array to buffer
const strBuffer = Buffer.from(data)
if (validateSlugResponse.error) { //encode it!
//kickout const previewKey = crypto
return validateSlugResponse .createHash('sha512')
} .update(strBuffer)
.digest('base64')
//return success return previewKey
return {
error: false,
message: null,
slug: validateSlugResponse.slug,
}
} }
//Checks that the requested page exists, if not return a 401 //Checks that the requested page exists, if not return a 401
...@@ -95,25 +77,43 @@ export async function validateSlugForPreview({ slug, contentID }) { ...@@ -95,25 +77,43 @@ export async function validateSlugForPreview({ slug, contentID }) {
} }
} }
//Generates a preview key to compare against //Validates whether the incoming preview request is valid
export function generatePreviewKey() { export async function validatePreview({ agilityPreviewKey, slug, contentID }) {
//the string we want to encode //Validate the preview key
const str = `-1_${process.env.AGILITY_CMS_SECURITY_KEY}_Preview` if (!agilityPreviewKey) {
return {
error: true,
message: `Missing agilitypreviewkey.`,
}
}
//build our byte array //sanitize incoming key (replace spaces with '+')
let data = [] if (agilityPreviewKey.indexOf(` `) > -1) {
for (var i = 0; i < str.length; ++i) { agilityPreviewKey = agilityPreviewKey.split(` `).join(`+`)
data.push(str.charCodeAt(i))
data.push(0)
} }
//convert byte array to buffer //compare the preview key being used
const strBuffer = Buffer.from(data) const correctPreviewKey = generatePreviewKey()
//encode it!
const previewKey = crypto
.createHash('sha512')
.update(strBuffer)
.digest('base64')
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() { ...@@ -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) { export function getDraftPost(id) {
return fetch( return fetch(
`https://builder.io/api/v2/content/${BUILDER_CONFIG.postsModel}/${id}?apiKey=${BUILDER_CONFIG.apiKey}&preview=true&noCache=true&cachebust=tru&includeRefs=true` `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) { ...@@ -26,25 +19,6 @@ export function getDraftPost(id) {
.then((res) => res || null) .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) { export async function searchPosts(query, preview, limit = 20, offset = 0) {
let posts = await builder.getAll(BUILDER_CONFIG.postsModel, { let posts = await builder.getAll(BUILDER_CONFIG.postsModel, {
limit, limit,
...@@ -67,6 +41,32 @@ export async function searchPosts(query, preview, limit = 20, offset = 0) { ...@@ -67,6 +41,32 @@ export async function searchPosts(query, preview, limit = 20, offset = 0) {
return posts 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) { export async function getPostAndMorePosts(slug, preview, previewData) {
const post = const post =
preview && previewData preview && previewData
......
...@@ -16,6 +16,24 @@ try { ...@@ -16,6 +16,24 @@ try {
const defaultPageSize = 100 const defaultPageSize = 100
const defaultPostCount = 10 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) { export async function getLandingPage(slug) {
try { try {
const page = await butter.page.retrieve('landing-page', slug) const page = await butter.page.retrieve('landing-page', slug)
...@@ -38,24 +56,6 @@ export async function getLandingPages() { ...@@ -38,24 +56,6 @@ export async function getLandingPages() {
return paginatedLandingPages 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( export async function getPostsData(
{ page, pageSize, tag, category } = { page: 1, pageSize: defaultPostCount } { page, pageSize, tag, category } = { page: 1, pageSize: defaultPostCount }
) { ) {
......
import NextImage from 'next/image' import NextImage from 'next/image'
import { transformImageUrl } from '@kentico/kontent-delivery' import { transformImageUrl } from '@kentico/kontent-delivery'
const getLoader = (src) => {
return srcIsKontentAsset(src) ? kontentImageLoader : undefined
}
const srcIsKontentAsset = (src) => { const srcIsKontentAsset = (src) => {
try { try {
const { hostname } = new URL(src) const { hostname } = new URL(src)
...@@ -23,6 +19,10 @@ const kontentImageLoader = ({ src, width, quality = 75 }) => { ...@@ -23,6 +19,10 @@ const kontentImageLoader = ({ src, width, quality = 75 }) => {
.getUrl() .getUrl()
} }
const getLoader = (src) => {
return srcIsKontentAsset(src) ? kontentImageLoader : undefined
}
export default function Image(props) { export default function Image(props) {
const loader = getLoader(props.src) const loader = getLoader(props.src)
......
...@@ -7,14 +7,6 @@ if (typeof window !== 'undefined') { ...@@ -7,14 +7,6 @@ if (typeof window !== 'undefined') {
StyleSheet.rehydrate(window.__REHYDRATE_IDS) 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({ const styles = StyleSheet.create({
root: { root: {
width: 80, width: 80,
...@@ -34,3 +26,11 @@ const styles = StyleSheet.create({ ...@@ -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 { ...@@ -8,19 +8,6 @@ interface ICardProps {
method: 'get' | 'post' 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` const Container = styled.a`
border: 1px solid rgb(215, 219, 236); border: 1px solid rgb(215, 219, 236);
border-radius: 0.25rem; border-radius: 0.25rem;
...@@ -59,3 +46,16 @@ const ImageContainer = styled.div` ...@@ -59,3 +46,16 @@ const ImageContainer = styled.div`
font-size: 0.5rem; 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' ...@@ -5,10 +5,6 @@ import styled, { keyframes } from 'styled-components'
interface ILoaderProps { interface ILoaderProps {
done: boolean 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` const spin = keyframes`
0% { 0% {
...@@ -18,6 +14,7 @@ const spin = keyframes` ...@@ -18,6 +14,7 @@ const spin = keyframes`
transform: rotate(360deg); transform: rotate(360deg);
} }
` `
const Spinner = styled.div` const Spinner = styled.div`
border: 3px solid #f3f3f3; border: 3px solid #f3f3f3;
border-top: 3px solid rgb(235, 137, 82); border-top: 3px solid rgb(235, 137, 82);
...@@ -26,3 +23,8 @@ const Spinner = styled.div` ...@@ -26,3 +23,8 @@ const Spinner = styled.div`
height: 25px; height: 25px;
animation: ${spin} 1s linear infinite; 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 { ...@@ -6,6 +6,13 @@ interface IStatusProps {
done: boolean done: boolean
title: string 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 => ( const Status: React.FC<IStatusProps> = ({ done, title }): JSX.Element => (
<Container> <Container>
<p>{title}</p> <p>{title}</p>
...@@ -14,10 +21,3 @@ const Status: React.FC<IStatusProps> = ({ done, title }): JSX.Element => ( ...@@ -14,10 +21,3 @@ const Status: React.FC<IStatusProps> = ({ done, title }): JSX.Element => (
) )
export default Status export default Status
const Container = styled.div`
display: flex;
flex-direction: column;
align-items: center;
gap: 5px;
`
...@@ -42,6 +42,30 @@ const Home: NextPage = () => { ...@@ -42,6 +42,30 @@ const Home: NextPage = () => {
fetcher 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(() => { useEffect(() => {
if (video) { if (video) {
const intervalId = window.setInterval(() => { const intervalId = window.setInterval(() => {
...@@ -72,35 +96,11 @@ const Home: NextPage = () => { ...@@ -72,35 +96,11 @@ const Home: NextPage = () => {
setVideo(video) 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 => { const handleNavigate = (): void => {
if (!video) return if (!video) return
router.push(`/${video.videoId}?w=${size?.width}&h=${size?.height}`) 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 ( return (
<GlobalContainer> <GlobalContainer>
<Head> <Head>
......
...@@ -35,6 +35,8 @@ export default function PostList() { ...@@ -35,6 +35,8 @@ export default function PostList() {
const loadingMorePosts = networkStatus === NetworkStatus.fetchMore const loadingMorePosts = networkStatus === NetworkStatus.fetchMore
const { allPosts, _allPostsMeta } = data
const loadMorePosts = () => { const loadMorePosts = () => {
fetchMore({ fetchMore({
variables: { variables: {
...@@ -46,7 +48,6 @@ export default function PostList() { ...@@ -46,7 +48,6 @@ export default function PostList() {
if (error) return <ErrorMessage message="Error loading posts." /> if (error) return <ErrorMessage message="Error loading posts." />
if (loading && !loadingMorePosts) return <div>Loading</div> if (loading && !loadingMorePosts) return <div>Loading</div>
const { allPosts, _allPostsMeta } = data
const areMorePosts = allPosts.length < _allPostsMeta.count const areMorePosts = allPosts.length < _allPostsMeta.count
return ( return (
......
...@@ -35,6 +35,7 @@ export default function PostList() { ...@@ -35,6 +35,7 @@ export default function PostList() {
) )
const loadingMorePosts = networkStatus === NetworkStatus.fetchMore const loadingMorePosts = networkStatus === NetworkStatus.fetchMore
const { allPosts, _allPostsMeta } = data
const loadMorePosts = () => { const loadMorePosts = () => {
fetchMore({ fetchMore({
...@@ -47,7 +48,6 @@ export default function PostList() { ...@@ -47,7 +48,6 @@ export default function PostList() {
if (error) return <ErrorMessage message="Error loading posts." /> if (error) return <ErrorMessage message="Error loading posts." />
if (loading && !loadingMorePosts) return <div>Loading</div> if (loading && !loadingMorePosts) return <div>Loading</div>
const { allPosts, _allPostsMeta } = data
const areMorePosts = allPosts.length < _allPostsMeta.count const areMorePosts = allPosts.length < _allPostsMeta.count
return ( return (
......
...@@ -5,9 +5,7 @@ const whoami = preval` ...@@ -5,9 +5,7 @@ const whoami = preval`
module.exports = userInfo.username module.exports = userInfo.username
` `
export default WhoAmI export default function WhoAmI() {
function WhoAmI() {
return ( return (
<div style={{ display: 'flex', justifyContent: 'center' }}> <div style={{ display: 'flex', justifyContent: 'center' }}>
<h1> <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) { export default function Clock(props) {
return ( return (
<div className={props.light ? 'light' : ''}> <div className={props.light ? 'light' : ''}>
...@@ -18,8 +22,3 @@ export default function Clock(props) { ...@@ -18,8 +22,3 @@ export default function Clock(props) {
</div> </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') { ...@@ -8,14 +8,6 @@ if (typeof window !== 'undefined') {
cxs.rehydrate(serverCss) cxs.rehydrate(serverCss)
} }
export default function Home() {
return (
<div className={cx.root}>
<h1 className={cx.title}>My page</h1>
</div>
)
}
const cx = { const cx = {
root: cxs({ root: cxs({
width: 80, width: 80,
...@@ -35,3 +27,11 @@ const cx = { ...@@ -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 { ...@@ -7,6 +7,81 @@ import {
convertFromRaw, convertFromRaw,
} from 'draft-js' } 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 { export default class App extends Component {
constructor(props) { constructor(props) {
super(props) super(props)
...@@ -223,23 +298,6 @@ export default class App extends Component { ...@@ -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 { class ToolbarButton extends Component {
constructor() { constructor() {
super() super()
...@@ -285,61 +343,3 @@ const ToolBar = (props) => { ...@@ -285,61 +343,3 @@ const ToolBar = (props) => {
</div> </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 type { NextApiRequest, NextApiResponse } from 'next'
import { client, e } from '../../../client' 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 // PATCH /api/post/:id
async function updatePost( async function updatePost(
postId: string, postId: string,
...@@ -42,3 +25,20 @@ async function deletePost(postId: string) { ...@@ -42,3 +25,20 @@ async function deletePost(postId: string) {
})) }))
.run(client) .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 @@ ...@@ -2,14 +2,6 @@
import React from 'react' import React from 'react'
import { StyleSheet, Text, View } from 'react-native' 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({ const styles = StyleSheet.create({
container: { container: {
flex: 1, flex: 1,
...@@ -20,3 +12,11 @@ const styles = StyleSheet.create({ ...@@ -20,3 +12,11 @@ const styles = StyleSheet.create({
fontSize: 16, 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 // @generated: @expo/next-adapter@2.1.5
import { StyleSheet, Text, View } from 'react-native' 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({ const styles = StyleSheet.create({
container: { container: {
flex: 1, flex: 1,
...@@ -19,3 +11,11 @@ const styles = StyleSheet.create({ ...@@ -19,3 +11,11 @@ const styles = StyleSheet.create({
fontSize: 16, 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' ...@@ -3,15 +3,6 @@ import { useRouter } from 'next/router'
import Link from 'next/link' import Link from 'next/link'
import { RouterProps } from './types' 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 }>> = ({ const CustomLink: React.FC<PropsWithChildren<{ to: string }>> = ({
to, to,
children, children,
...@@ -35,3 +26,12 @@ const CustomLink: React.FC<PropsWithChildren<{ to: string }>> = ({ ...@@ -35,3 +26,12 @@ const CustomLink: React.FC<PropsWithChildren<{ to: string }>> = ({
</div> </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 { ...@@ -6,6 +6,14 @@ import {
useVisitorData, useVisitorData,
} from '@fingerprintjs/fingerprintjs-pro-react' } from '@fingerprintjs/fingerprintjs-pro-react'
function VisitorDataComponent() {
const { data, isLoading, error } = useVisitorData({ extendedResult: true })
return (
<VisitorDataPresenter data={data} isLoading={isLoading} error={error} />
)
}
function HomePage() { function HomePage() {
const { clearCache } = useContext(FpjsContext) const { clearCache } = useContext(FpjsContext)
...@@ -27,12 +35,4 @@ function HomePage() { ...@@ -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 export default HomePage
...@@ -12,6 +12,22 @@ mutation createPost($title: String!, $url: String!) { ...@@ -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 }) { export default function Submit({ onSubmission }) {
const [createPost, state] = useMutation(CREATE_POST) const [createPost, state] = useMutation(CREATE_POST)
...@@ -38,19 +54,3 @@ export default function Submit({ onSubmission }) { ...@@ -38,19 +54,3 @@ export default function Submit({ onSubmission }) {
</form> </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 { export class FetchError extends Error {
response: Response response: Response
data: { data: {
...@@ -50,3 +27,26 @@ export class FetchError extends Error { ...@@ -50,3 +27,26 @@ export class FetchError extends Error {
this.data = data ?? { message: message } 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 = ...@@ -10,8 +10,6 @@ export type Events =
const octokit = new Octokit() const octokit = new Octokit()
export default withIronSessionApiRoute(eventsRoute, sessionOptions)
async function eventsRoute(req: NextApiRequest, res: NextApiResponse<Events>) { async function eventsRoute(req: NextApiRequest, res: NextApiResponse<Events>) {
const user = req.session.user const user = req.session.user
...@@ -31,3 +29,5 @@ async function eventsRoute(req: NextApiRequest, res: NextApiResponse<Events>) { ...@@ -31,3 +29,5 @@ async function eventsRoute(req: NextApiRequest, res: NextApiResponse<Events>) {
res.status(200).json([]) res.status(200).json([])
} }
} }
export default withIronSessionApiRoute(eventsRoute, sessionOptions)
...@@ -6,8 +6,6 @@ import { sessionOptions } from 'lib/session' ...@@ -6,8 +6,6 @@ import { sessionOptions } from 'lib/session'
import { NextApiRequest, NextApiResponse } from 'next' import { NextApiRequest, NextApiResponse } from 'next'
const octokit = new Octokit() const octokit = new Octokit()
export default withIronSessionApiRoute(loginRoute, sessionOptions)
async function loginRoute(req: NextApiRequest, res: NextApiResponse) { async function loginRoute(req: NextApiRequest, res: NextApiResponse) {
const { username } = await req.body const { username } = await req.body
...@@ -24,3 +22,5 @@ async function loginRoute(req: NextApiRequest, res: NextApiResponse) { ...@@ -24,3 +22,5 @@ async function loginRoute(req: NextApiRequest, res: NextApiResponse) {
res.status(500).json({ message: (error as Error).message }) res.status(500).json({ message: (error as Error).message })
} }
} }
export default withIronSessionApiRoute(loginRoute, sessionOptions)
...@@ -3,9 +3,9 @@ import { sessionOptions } from 'lib/session' ...@@ -3,9 +3,9 @@ import { sessionOptions } from 'lib/session'
import { NextApiRequest, NextApiResponse } from 'next' import { NextApiRequest, NextApiResponse } from 'next'
import type { User } from 'pages/api/user' import type { User } from 'pages/api/user'
export default withIronSessionApiRoute(logoutRoute, sessionOptions)
function logoutRoute(req: NextApiRequest, res: NextApiResponse<User>) { function logoutRoute(req: NextApiRequest, res: NextApiResponse<User>) {
req.session.destroy() req.session.destroy()
res.json({ isLoggedIn: false, login: '', avatarUrl: '' }) res.json({ isLoggedIn: false, login: '', avatarUrl: '' })
} }
export default withIronSessionApiRoute(logoutRoute, sessionOptions)
...@@ -8,8 +8,6 @@ export type User = { ...@@ -8,8 +8,6 @@ export type User = {
avatarUrl: string avatarUrl: string
} }
export default withIronSessionApiRoute(userRoute, sessionOptions)
async function userRoute(req: NextApiRequest, res: NextApiResponse<User>) { async function userRoute(req: NextApiRequest, res: NextApiResponse<User>) {
if (req.session.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 // 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>) { ...@@ -26,3 +24,5 @@ async function userRoute(req: NextApiRequest, res: NextApiResponse<User>) {
}) })
} }
} }
export default withIronSessionApiRoute(userRoute, sessionOptions)
...@@ -13,12 +13,6 @@ export function useStore() { ...@@ -13,12 +13,6 @@ export function useStore() {
return context return context
} }
export function StoreProvider({ children, initialState: initialData }) {
const store = initializeStore(initialData)
return <StoreContext.Provider value={store}>{children}</StoreContext.Provider>
}
function initializeStore(initialData = null) { function initializeStore(initialData = null) {
const _store = store ?? new Store() const _store = store ?? new Store()
...@@ -34,3 +28,9 @@ function initializeStore(initialData = null) { ...@@ -34,3 +28,9 @@ function initializeStore(initialData = null) {
return _store 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) => const format = (t) =>
`${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}` `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`
const pad = (n) => (n < 10 ? `0${n}` : n)
const Clock = (props) => { const Clock = (props) => {
const divStyle = { const divStyle = {
......
...@@ -83,16 +83,6 @@ const Form = ({ formId, petForm, forNewPet = true }) => { ...@@ -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*/ /* Makes sure pet info is filled for pet name, owner name, species, and image url*/
const formValidate = () => { const formValidate = () => {
let err = {} let err = {}
...@@ -103,6 +93,16 @@ const Form = ({ formId, petForm, forNewPet = true }) => { ...@@ -103,6 +93,16 @@ const Form = ({ formId, petForm, forNewPet = true }) => {
return err 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 ( return (
<> <>
<form id={formId} onSubmit={handleSubmit}> <form id={formId} onSubmit={handleSubmit}>
......
import { StyleSheet, Text, View } from 'react-native' 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({ const styles = StyleSheet.create({
container: { container: {
alignItems: 'center', alignItems: 'center',
...@@ -29,3 +15,17 @@ const styles = StyleSheet.create({ ...@@ -29,3 +15,17 @@ const styles = StyleSheet.create({
color: 'blue', 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' 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({ const styles = StyleSheet.create({
container: { container: {
alignItems: 'center', alignItems: 'center',
...@@ -39,3 +19,23 @@ const styles = StyleSheet.create({ ...@@ -39,3 +19,23 @@ const styles = StyleSheet.create({
marginBottom: 24, 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' ...@@ -2,6 +2,12 @@ import type { NextApiRequest, NextApiResponse } from 'next'
import redis from '../../lib/redis' 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( export default async function subscribe(
req: NextApiRequest, req: NextApiRequest,
res: NextApiResponse res: NextApiResponse
...@@ -19,9 +25,3 @@ export default async function subscribe( ...@@ -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 }) { export default function Clock({ lastUpdate, light }) {
return ( return (
<div className={light ? 'light' : ''}> <div className={light ? 'light' : ''}>
...@@ -18,8 +22,3 @@ export default function Clock({ lastUpdate, light }) { ...@@ -18,8 +22,3 @@ export default function Clock({ lastUpdate, light }) {
</div> </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