Unverified Commit d57342a9 authored by Max Proske's avatar Max Proske Committed by GitHub

Convert amp-first example to TypeScript (#38029)

Converted AMP First Boilerplate example over to TypeScript to match the Contribution guidelines.

Note: Requires `v12.1.7-canary.41` or newer to build https://github.com/vercel/next.js/pull/37744#issuecomment-1159573754

## Documentation / Examples

- [X] Make sure the linting passes by running `pnpm lint`
- [X] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
parent 2b451ee6
// Allow AMP elements to be a property on JSX.IntrinsicElements
// Only the intrinsic elements defined here will be accepted, and only with the attributes defined here
declare namespace JSX {
interface AmpImg {
alt?: string
src?: string
width?: string
height?: string
layout?: string
}
interface AmpInstallServiceWorker {
src: string
'data-iframe-src': string
layout: string
}
interface AmpState {
id?: string
children?: any
src?: string
}
interface AmpScript {
id?: string
children?: any
layout?: string
width?: string
height?: string
script?: any
src?: string
}
interface AmpCarousel {
children: React.ReactNode
layout?:
| 'fill'
| 'fixed'
| 'fixed-height'
| 'flex-item'
| 'intrinsic'
| 'nodisplay'
| 'responsive'
width: string
height: string
type: 'slides' | 'carousel'
role?: 'region' | 'list' | 'listitem'
controls?: ''
loop?: ''
autoplay?: ''
delay?: string
id?: string
}
interface AmpList {
layout?:
| 'fill'
| 'fixed'
| 'fixed-height'
| 'flex-item'
| 'nodisplay'
| 'responsive'
temlate?: string
width?: string
height?: string
credentials?: 'omit' | 'include'
children: React.ReactNode
src?: string
binding?: string
}
interface IntrinsicElements {
'amp-img': AmpImg
'amp-install-serviceworker': AmpInstallServiceWorker
'amp-state': AmpState
'amp-script': AmpScript
'amp-carousel': AmpCarousel
'amp-list': AmpList
}
}
// Only the intrinsic elements defined here will be accepted, attributes don't matter
// declare namespace JSX {
// interface IntrinsicElements {
// 'amp-img': any
// 'amp-install-serviceworker': any
// 'amp-state': any
// 'amp-script': any
// 'amp-carousel': any
// 'amp-list': any
// }
// }
// All intrinsic elements will be accepted
// declare namespace JSX {
// interface IntrinsicElements {
// [elemName: string]: any
// }
// }
// Allow custom AMP attributes on HTML elements
declare namespace React {
interface ScriptHTMLAttributes {
target?: string
}
interface HTMLAttributes {
submitting?: string
type?: string
on?: string
}
}
import PropTypes from 'prop-types'
import NextHead from 'next/head'
import Head from 'next/head'
import { AmpIncludeAmpInstallServiceworker } from './amp/AmpCustomElement'
// Your app's theme color
const THEME_COLOR = '#005af0'
type LayoutProps = {
title: string
children?: React.ReactNode
description: string
}
/**
* A sample page layout installing the AMP Serviceworker by default.
*
* @param {Props} props
*/
const Layout = (props) => (
const Layout: React.FC<LayoutProps> = ({ title, children, description }) => (
<>
<NextHead>
<title>{props.title || ''}</title>
<meta name="description" content={props.description || ''} />
<Head>
<title>{title || ''}</title>
<meta name="description" content={description || ''} />
<meta name="theme-color" content={THEME_COLOR} />
<link rel="icon" sizes="192x192" href="/static/images/icons-192.png" />
<link rel="apple-touch-icon" href="/static/images/icons-192.png" />
<link rel="icon" href="/static/favicon.ico" />
<link rel="manifest" href="/manifest.json" />
</NextHead>
</Head>
{props.children}
{children}
<AmpIncludeAmpInstallServiceworker />
<amp-install-serviceworker
......@@ -46,9 +49,4 @@ const Layout = (props) => (
</>
)
Layout.propTypes = {
title: PropTypes.string,
description: PropTypes.string,
}
export default Layout
......@@ -2,10 +2,14 @@
* @file An AMP Component import helper. This file is auto-generated using
* https://www.npmjs.com/package/@ampproject/toolbox-validator-rules.
*/
import React from 'react'
import Head from 'next/head'
export function AmpIncludeCustomElement(props) {
interface Props {
name: string
version: string
}
export function AmpIncludeCustomElement(props: Props) {
return (
<Head>
<script
......@@ -24,7 +28,7 @@ export function AmpIncludeCustomElement(props) {
)
}
export function AmpIncludeCustomTemplate(props) {
export function AmpIncludeCustomTemplate(props: Props) {
return (
<Head>
<script
......
import PropTypes from 'prop-types'
import React from 'react'
import { AmpIncludeAmpScript } from './AmpCustomElement'
type AmpScriptProps = {
id?: string
children?: React.ReactNode
layout?: string
width?: string
height?: string
script?: Function | string
src?: string
}
/**
* Embeds an AMP Script by either linking to a JS `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
* be generated by AMP Optimizer.
*
* @param {Props} props
*/
export default function AmpScript(props) {
const AmpScript: React.FC<AmpScriptProps> = ({
id,
script,
children,
...props
}) => {
return (
<>
<AmpIncludeAmpScript />
<amp-script
layout={props.layout}
width={props.width}
height={props.height}
script={props.id}
src={props.src}
>
{props.children}
<amp-script script={id} {...props}>
{children}
</amp-script>
{props.script && (
{script && (
<script
id={props.id}
id={id}
type="text/plain"
target="amp-script"
dangerouslySetInnerHTML={{
__html: generateInlineScript(props.script),
__html: generateInlineScript(script),
}}
/>
)}
......@@ -36,19 +41,11 @@ export default function AmpScript(props) {
)
}
function generateInlineScript(script) {
export default AmpScript
const generateInlineScript = (script: Function | string) => {
if (typeof script === 'function') {
return `${script.toString()}()`
}
return String(script)
}
AmpScript.propTypes = {
id: PropTypes.string,
children: PropTypes.node.isRequired,
layout: PropTypes.string.isRequired,
width: PropTypes.string,
height: PropTypes.string,
script: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
src: PropTypes.string,
}
import PropTypes from 'prop-types'
import React from 'react'
import { AmpIncludeAmpBind } from './AmpCustomElement'
/**
* Renders an amp-state element, by either adding local state via `value`
* or remote state via the `src` property.
*
* @param {Props} props
*/
export default function AmpState(props) {
return (
<>
<AmpIncludeAmpBind />
<amp-state id={props.id} src={props.src}>
{props.children && (
<script
type="application/json"
dangerouslySetInnerHTML={{
__html: JSON.stringify(props.children),
}}
/>
)}
</amp-state>
</>
)
}
AmpState.propTypes = {
id: PropTypes.string.isRequired,
children: PropTypes.any,
src: PropTypes.string,
}
import { AmpIncludeCustomElement } from './AmpCustomElement'
type AmpStateProps = {
id?: string
src?: string
children?: React.ReactNode
}
const AmpState: React.FC<AmpStateProps> = ({ id, src, children }) => {
return (
<>
<AmpIncludeCustomElement name="amp-bind" version="0.1" />
<amp-state id={id} src={src}>
{children && (
<script
type="application/json"
dangerouslySetInnerHTML={{
__html: JSON.stringify(children),
}}
/>
)}
</amp-state>
</>
)
}
export default AmpState
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
......@@ -7,8 +7,13 @@
},
"dependencies": {
"next": "latest",
"prop-types": "^15.8.1",
"react": "^17.0.2",
"react-dom": "^17.0.2"
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/node": "^18.0.0",
"@types/react": "^18.0.14",
"@types/react-dom": "^18.0.5",
"typescript": "^4.7.4"
}
}
// _document is only rendered on the server side and not on the client side
// Event handlers like onClick can't be added to this file
import Document, { Html, Head, Main, NextScript } from 'next/document'
class MyDocument extends Document {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx)
return { ...initialProps }
}
render() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
import { NextPage, GetServerSideProps } from 'next'
import Layout from '../components/Layout'
import AmpState from '../components/amp/AmpState'
import AmpScript from '../components/amp/AmpScript'
......@@ -8,7 +9,11 @@ import {
export const config = { amp: true }
const Home = (props) => (
type HomeProps = {
host: string
}
const Home: NextPage<HomeProps> = (props) => (
<>
<Layout
title="Welcome to AMP"
......@@ -101,9 +106,11 @@ const Home = (props) => (
</p>
<AmpState id="myState">
{{
message: 'Hello World',
}}
<>
{{
message: 'Hello World',
}}
</>
</AmpState>
<button
on="tap:AMP.setState({
......@@ -233,21 +240,21 @@ const Home = (props) => (
)
// amp-script requires absolute URLs, so we create a property `host` which we can use to calculate the script URL.
export async function getServerSideProps({ req }) {
export const getServerSideProps: GetServerSideProps = async ({ req }) => {
const getProtocol = (req: any) => {
if (req.connection.encrypted) {
return 'https'
}
const forwardedProto = req.headers['x-forwarded-proto']
if (forwardedProto) {
return forwardedProto.split(/\s*,\s*/)[0]
}
return 'http'
}
// WARNING: This is a generally unsafe application unless you're deploying to a managed platform like Vercel.
// Be sure your load balancer is configured to not allow spoofed host headers.
return { props: { host: `${getProtocol(req)}://${req.headers.host}` } }
}
function getProtocol(req) {
if (req.connection.encrypted) {
return 'https'
}
const forwardedProto = req.headers['x-forwarded-proto']
if (forwardedProto) {
return forwardedProto.split(/\s*,\s*/)[0]
}
return 'http'
}
export default Home
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true
},
"include": ["next-env.d.ts", "amp.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
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