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

Convert `with-gsap`, `with-mqtt-js`, `with-mux-video` examples to Typescript (#43874)

Converted three more examples to TypeScript.

Changes to individual examples pushed as separate commits.

## Documentation / Examples

- [X] Make sure the linting passes by running `pnpm build && pnpm lint`
- [X] The "examples guidelines" are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent 6cfebfb0
import { useEffect, useRef } from 'react' import { useEffect, useRef } from 'react'
import { gsap } from 'gsap' import { gsap } from 'gsap'
const Content = () => { export default function Content() {
let line1 = useRef(null) let line1 = useRef(null)
useEffect(() => { useEffect(() => {
gsap.from([line1], 0.6, { gsap.from([line1.current], 0.6, {
delay: 0.9, delay: 0.9,
ease: 'power3.out', ease: 'power3.out',
y: 24, y: 24,
...@@ -15,7 +16,7 @@ const Content = () => { ...@@ -15,7 +16,7 @@ const Content = () => {
}, [line1]) }, [line1])
return ( return (
<p ref={(el) => (line1 = el)} className="line"> <p ref={line1} className="line">
A Simple example using{' '} A Simple example using{' '}
<a <a
href="https://greensock.com/gsap/" href="https://greensock.com/gsap/"
...@@ -33,5 +34,3 @@ const Content = () => { ...@@ -33,5 +34,3 @@ const Content = () => {
</p> </p>
) )
} }
export default Content
import Title from './Title' import Title from './Title'
import Content from './Content' import Content from './Content'
const Home = () => { export default function Home() {
return ( return (
<div className="inner"> <div className="inner">
<Title lineContent="With-GSAP" lineContent2="Using NEXT" /> <Title lineContent="With-GSAP" lineContent2="Using NEXT" />
...@@ -15,5 +15,3 @@ const Home = () => { ...@@ -15,5 +15,3 @@ const Home = () => {
</div> </div>
) )
} }
export default Home
import { useEffect, useRef } from 'react' import { useEffect, useRef } from 'react'
import { gsap } from 'gsap' import { gsap } from 'gsap'
const Title = ({ lineContent, lineContent2 }) => { type TitleProps = {
lineContent: string
lineContent2: string
}
export default function Title({ lineContent, lineContent2 }: TitleProps) {
let line1 = useRef(null) let line1 = useRef(null)
let line2 = useRef(null) let line2 = useRef(null)
useEffect(() => { useEffect(() => {
gsap.from([line1, line2], 0.8, { gsap.from([line1.current, line2.current], 0.8, {
delay: 0.8, delay: 0.8,
ease: 'power3.out', ease: 'power3.out',
y: 64, y: 64,
...@@ -14,20 +20,19 @@ const Title = ({ lineContent, lineContent2 }) => { ...@@ -14,20 +20,19 @@ const Title = ({ lineContent, lineContent2 }) => {
}, },
}) })
}, [line1, line2]) }, [line1, line2])
return ( return (
<h1 className="page-title"> <h1 className="page-title">
<div className="line-wrap"> <div className="line-wrap">
<div ref={(el) => (line1 = el)} className="line"> <div ref={line1} className="line">
{lineContent} {lineContent}
</div> </div>
</div> </div>
<div className="line-wrap"> <div className="line-wrap">
<div ref={(el) => (line2 = el)} className="line"> <div ref={line2} className="line">
{lineContent2} {lineContent2}
</div> </div>
</div> </div>
</h1> </h1>
) )
} }
export default Title
...@@ -6,11 +6,19 @@ ...@@ -6,11 +6,19 @@
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"gsap": "^3.0.1", "gsap": "^3.11.3",
"next": "latest", "next": "latest",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"react-transition-group": "^4.3.0", "react-transition-group": "^4.4.5",
"sass": "1.29.0" "sass": "^1.56.2"
},
"devDependencies": {
"@types/gsap": "^3.0.0",
"@types/node": "^18.11.12",
"@types/react": "^18.0.26",
"@types/react-dom": "^18.0.9",
"@types/react-transition-group": "^4.4.5",
"typescript": "^4.9.4"
} }
} }
import type { AppProps } from 'next/app'
import '../App.scss' import '../App.scss'
function MyApp({ Component, pageProps }) { function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} /> return <Component {...pageProps} />
} }
......
import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
<Html>
<Head>
<link
href="https://fonts.googleapis.com/css?family=Bebas+Neue|Poppins:300,400&display=swap"
rel="stylesheet"
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
export default function handler(req, res) {
res.status(200).json({ name: 'John Doe' })
}
...@@ -2,8 +2,8 @@ import { CSSTransition } from 'react-transition-group' ...@@ -2,8 +2,8 @@ import { CSSTransition } from 'react-transition-group'
import { gsap } from 'gsap' import { gsap } from 'gsap'
import Home from '../components/Home' import Home from '../components/Home'
function App() { export default function HomePage() {
const onEnter = (node) => { const onEnter = (node: any) => {
gsap.from( gsap.from(
[node.children[0].firstElementChild, node.children[0].lastElementChild], [node.children[0].firstElementChild, node.children[0].lastElementChild],
0.6, 0.6,
...@@ -18,7 +18,7 @@ function App() { ...@@ -18,7 +18,7 @@ function App() {
} }
) )
} }
const onExit = (node) => { const onExit = (node: any) => {
gsap.to( gsap.to(
[node.children[0].firstElementChild, node.children[0].lastElementChild], [node.children[0].firstElementChild, node.children[0].lastElementChild],
0.6, 0.6,
...@@ -51,5 +51,3 @@ function App() { ...@@ -51,5 +51,3 @@ function App() {
</> </>
) )
} }
export default App
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
declare namespace NodeJS {
export interface ProcessEnv {
readonly NEXT_PUBLIC_MQTT_URI: string
readonly NEXT_PUBLIC_MQTT_USERNAME: string
readonly NEXT_PUBLIC_MQTT_PASSWORD: string
readonly NEXT_PUBLIC_MQTT_CLIENTID: string
}
}
import type { MqttClient, IClientOptions } from 'mqtt'
import MQTT from 'mqtt' import MQTT from 'mqtt'
import { useEffect, useRef } from 'react' import { useEffect, useRef } from 'react'
interface useMqttProps {
uri: string
options?: IClientOptions
topicHandlers?: { topic: string; handler: (payload: any) => void }[]
onConnectedHandler?: (client: MqttClient) => void
}
function useMqtt({ function useMqtt({
uri, uri,
options = {}, options = {},
topicHandlers = [{ topic: '', handler: ({ topic, payload, packet }) => {} }], topicHandlers = [{ topic: '', handler: ({ topic, payload, packet }) => {} }],
onConnectedHandler = (client) => {}, onConnectedHandler = (client) => {},
}) { }: useMqttProps) {
const clientRef = useRef(null) const clientRef = useRef<MqttClient | null>(null)
useEffect(() => { useEffect(() => {
if (clientRef.current) return if (clientRef.current) return
...@@ -23,9 +31,9 @@ function useMqtt({ ...@@ -23,9 +31,9 @@ function useMqtt({
const client = clientRef.current const client = clientRef.current
topicHandlers.forEach((th) => { topicHandlers.forEach((th) => {
client.subscribe(th.topic) client?.subscribe(th.topic)
}) })
client.on('message', (topic, rawPayload, packet) => { client?.on('message', (topic: string, rawPayload: any, packet: any) => {
const th = topicHandlers.find((t) => t.topic === topic) const th = topicHandlers.find((t) => t.topic === topic)
let payload let payload
try { try {
...@@ -36,7 +44,7 @@ function useMqtt({ ...@@ -36,7 +44,7 @@ function useMqtt({
if (th) th.handler({ topic, payload, packet }) if (th) th.handler({ topic, payload, packet })
}) })
client.on('connect', () => { client?.on('connect', () => {
if (onConnectedHandler) onConnectedHandler(client) if (onConnectedHandler) onConnectedHandler(client)
}) })
......
...@@ -6,9 +6,15 @@ ...@@ -6,9 +6,15 @@
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"mqtt": "4.2.6", "mqtt": "^4.3.7",
"next": "latest", "next": "latest",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0" "react-dom": "^18.2.0"
},
"devDependencies": {
"@types/node": "^18.11.12",
"@types/react": "^18.0.26",
"@types/react-dom": "^18.0.9",
"typescript": "^4.9.4"
} }
} }
import { useState, useRef } from 'react' import { useState, useRef } from 'react'
import type { MqttClient } from 'mqtt'
import useMqtt from '../lib/useMqtt' import useMqtt from '../lib/useMqtt'
export default function Home() { export default function Home() {
const [incommingMessages, setIncommingMessages] = useState([]) const [incommingMessages, setIncommingMessages] = useState<any[]>([])
const addMessage = (message) => { const addMessage = (message: any) => {
setIncommingMessages((incommingMessages) => [...incommingMessages, message]) setIncommingMessages((incommingMessages) => [...incommingMessages, message])
} }
const clearMessages = () => { const clearMessages = () => {
...@@ -13,14 +14,14 @@ export default function Home() { ...@@ -13,14 +14,14 @@ export default function Home() {
const incommingMessageHandlers = useRef([ const incommingMessageHandlers = useRef([
{ {
topic: 'topic1', topic: 'topic1',
handler: (msg) => { handler: (msg: string) => {
addMessage(msg) addMessage(msg)
}, },
}, },
]) ])
const mqttClientRef = useRef(null) const mqttClientRef = useRef<MqttClient | null>(null)
const setMqttClient = (client) => { const setMqttClient = (client: MqttClient) => {
mqttClientRef.current = client mqttClientRef.current = client
} }
useMqtt({ useMqtt({
...@@ -34,7 +35,7 @@ export default function Home() { ...@@ -34,7 +35,7 @@ export default function Home() {
onConnectedHandler: (client) => setMqttClient(client), onConnectedHandler: (client) => setMqttClient(client),
}) })
const publishMessages = (client) => { const publishMessages = (client: any) => {
if (!client) { if (!client) {
console.log('(publishMessages) Cannot publish, mqttClient: ', client) console.log('(publishMessages) Cannot publish, mqttClient: ', client)
return return
......
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
export default function Button({ children, ...otherProps }) { type ButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement> & {
children: React.ReactNode
}
export default function Button({ children, ...otherProps }: ButtonProps) {
return ( return (
<> <>
<button {...otherProps}>{children}</button> <button {...otherProps}>{children}</button>
......
export default function ErrorMessage({ message }) { interface ErrorMessageProps {
message?: string
}
export default function ErrorMessage({ message }: ErrorMessageProps) {
return ( return (
<> <>
<div className="message">{message || 'Unknown error'}</div> <div className="message">{message || 'Unknown error'}</div>
......
import Head from 'next/head' import Head from 'next/head'
import { MUX_HOME_PAGE_URL } from '../constants' import { MUX_HOME_PAGE_URL } from '../constants'
interface LayoutProps {
title?: string
description?: string
metaTitle?: string
metaDescription?: string
image?: string
children: React.ReactNode
loadTwitterWidget?: boolean
}
export default function Layout({ export default function Layout({
title, title,
description, description,
...@@ -9,7 +19,7 @@ export default function Layout({ ...@@ -9,7 +19,7 @@ export default function Layout({
image = 'https://with-mux-video.vercel.app/mux-nextjs-og-image.png', image = 'https://with-mux-video.vercel.app/mux-nextjs-og-image.png',
children, children,
loadTwitterWidget, loadTwitterWidget,
}) { }: LayoutProps) {
return ( return (
<div className="container"> <div className="container">
<Head> <Head>
......
export default function Spinner({ size = 6, color = '#999' }) { interface SpinnerProps {
size?: Number
color?: string
}
export default function Spinner({ size = 6, color = '#999' }: SpinnerProps) {
return ( return (
<> <>
<div className="spinner" /> <div className="spinner" />
......
...@@ -6,7 +6,7 @@ import Button from './button' ...@@ -6,7 +6,7 @@ import Button from './button'
import Spinner from './spinner' import Spinner from './spinner'
import ErrorMessage from './error-message' import ErrorMessage from './error-message'
const fetcher = (url) => { const fetcher = (url: string) => {
return fetch(url).then((res) => res.json()) return fetch(url).then((res) => res.json())
} }
...@@ -14,9 +14,9 @@ const UploadForm = () => { ...@@ -14,9 +14,9 @@ const UploadForm = () => {
const [isUploading, setIsUploading] = useState(false) const [isUploading, setIsUploading] = useState(false)
const [isPreparing, setIsPreparing] = useState(false) const [isPreparing, setIsPreparing] = useState(false)
const [uploadId, setUploadId] = useState(null) const [uploadId, setUploadId] = useState(null)
const [progress, setProgress] = useState(null) const [progress, setProgress] = useState<Number | null>(null)
const [errorMessage, setErrorMessage] = useState('') const [errorMessage, setErrorMessage] = useState('')
const inputRef = useRef(null) const inputRef = useRef<HTMLInputElement>(null)
const { data, error } = useSwr( const { data, error } = useSwr(
() => (isPreparing ? `/api/upload/${uploadId}` : null), () => (isPreparing ? `/api/upload/${uploadId}` : null),
...@@ -30,7 +30,6 @@ const UploadForm = () => { ...@@ -30,7 +30,6 @@ const UploadForm = () => {
if (upload && upload.asset_id) { if (upload && upload.asset_id) {
Router.push({ Router.push({
pathname: `/asset/${upload.asset_id}`, pathname: `/asset/${upload.asset_id}`,
scroll: false,
}) })
} }
}, [upload]) }, [upload])
...@@ -54,18 +53,25 @@ const UploadForm = () => { ...@@ -54,18 +53,25 @@ const UploadForm = () => {
} }
} }
const startUpload = (evt) => { const startUpload = () => {
setIsUploading(true) setIsUploading(true)
const files = inputRef.current?.files
if (!files) {
setErrorMessage('An unexpected issue occurred')
return
}
const upload = UpChunk.createUpload({ const upload = UpChunk.createUpload({
endpoint: createUpload, endpoint: createUpload,
file: inputRef.current.files[0], file: files[0],
}) })
upload.on('error', (err) => { upload.on('error', (err: any) => {
setErrorMessage(err.detail.message) setErrorMessage(err.detail.message)
}) })
upload.on('progress', (progress) => { upload.on('progress', (progress: any) => {
setProgress(Math.floor(progress.detail)) setProgress(Math.floor(progress.detail))
}) })
...@@ -90,7 +96,7 @@ const UploadForm = () => { ...@@ -90,7 +96,7 @@ const UploadForm = () => {
</> </>
) : ( ) : (
<label> <label>
<Button type="button" onClick={() => inputRef.current.click()}> <Button type="button" onClick={() => inputRef.current?.click()}>
Select a video file Select a video file
</Button> </Button>
<input type="file" onChange={startUpload} ref={inputRef} /> <input type="file" onChange={startUpload} ref={inputRef} />
......
import Layout from './layout' import Layout from './layout'
import { MUX_HOME_PAGE_URL } from '../constants' import { MUX_HOME_PAGE_URL } from '../constants'
export default function UploadPage({ children }) { interface UploadPageProps {
children: React.ReactNode
}
export default function UploadPage({ children }: UploadPageProps) {
return ( return (
<Layout <Layout
title="Welcome to Mux + Next.js" title="Welcome to Mux + Next.js"
......
...@@ -6,12 +6,18 @@ ...@@ -6,12 +6,18 @@
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"@mux/mux-node": "^2.8.0", "@mux/mux-node": "^7.0.0",
"@mux/mux-player-react": "latest", "@mux/mux-player-react": "^1.4.0",
"@mux/upchunk": "^2.3.1", "@mux/upchunk": "^3.0.0",
"next": "latest", "next": "latest",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"swr": "^0.2.0" "swr": "^1.3.0"
},
"devDependencies": {
"@types/node": "^18.11.10",
"@types/react": "^18.0.26",
"@types/react-dom": "^18.0.9",
"typescript": "^4.9.3"
} }
} }
import type { NextApiRequest, NextApiResponse } from 'next'
import Mux from '@mux/mux-node' import Mux from '@mux/mux-node'
const { Video } = new Mux() const { Video } = new Mux()
export default async function assetHandler(req, res) { export default async function assetHandler(
req: NextApiRequest,
res: NextApiResponse
) {
const { method } = req const { method } = req
switch (method) { switch (method) {
case 'GET': case 'GET':
try { try {
const asset = await Video.Assets.get(req.query.id) const asset = await Video.Assets.get(req.query.id as string)
res.json({ res.json({
asset: { asset: {
id: asset.id, id: asset.id,
status: asset.status, status: asset.status,
errors: asset.errors, errors: asset.errors,
playback_id: asset.playback_ids[0].id, playback_id: asset.playback_ids![0].id,
}, },
}) })
} catch (e) { } catch (e) {
......
import type { NextApiRequest, NextApiResponse } from 'next'
import Mux from '@mux/mux-node' import Mux from '@mux/mux-node'
const { Video } = new Mux() const { Video } = new Mux()
export default async function uploadHandler(req, res) { export default async function uploadHandler(
req: NextApiRequest,
res: NextApiResponse
) {
const { method } = req const { method } = req
switch (method) { switch (method) {
......
import type { NextApiRequest, NextApiResponse } from 'next'
import Mux from '@mux/mux-node' import Mux from '@mux/mux-node'
const { Video } = new Mux() const { Video } = new Mux()
export default async function uploadHandler(req, res) { export default async function uploadHandler(
req: NextApiRequest,
res: NextApiResponse
) {
const { method } = req const { method } = req
switch (method) { switch (method) {
case 'GET': case 'GET':
try { try {
const upload = await Video.Uploads.get(req.query.id) const upload = await Video.Uploads.get(req.query.id as string)
res.json({ res.json({
upload: { upload: {
status: upload.status, status: upload.status,
......
...@@ -6,7 +6,7 @@ import Spinner from '../../components/spinner' ...@@ -6,7 +6,7 @@ import Spinner from '../../components/spinner'
import ErrorMessage from '../../components/error-message' import ErrorMessage from '../../components/error-message'
import UploadPage from '../../components/upload-page' import UploadPage from '../../components/upload-page'
const fetcher = (url) => { const fetcher = (url: string) => {
return fetch(url).then((res) => res.json()) return fetch(url).then((res) => res.json())
} }
...@@ -27,7 +27,7 @@ export default function Asset() { ...@@ -27,7 +27,7 @@ export default function Asset() {
} }
}, [asset]) }, [asset])
let errorMessage let errorMessage: string = ''
if (error) { if (error) {
errorMessage = 'Error fetching api' errorMessage = 'Error fetching api'
......
import type {
InferGetStaticPropsType,
GetStaticProps,
GetStaticPaths,
} from 'next'
import MuxPlayer from '@mux/mux-player-react' import MuxPlayer from '@mux/mux-player-react'
import Link from 'next/link' import Link from 'next/link'
import Layout from '../../components/layout' import Layout from '../../components/layout'
...@@ -5,20 +10,29 @@ import Spinner from '../../components/spinner' ...@@ -5,20 +10,29 @@ import Spinner from '../../components/spinner'
import { MUX_HOME_PAGE_URL } from '../../constants' import { MUX_HOME_PAGE_URL } from '../../constants'
import { useRouter } from 'next/router' import { useRouter } from 'next/router'
export function getStaticProps({ params: { id: playbackId } }) { type Params = {
id?: string
}
export const getStaticProps: GetStaticProps = async ({ params }) => {
const { id: playbackId } = params as Params
const poster = `https://image.mux.com/${playbackId}/thumbnail.png` const poster = `https://image.mux.com/${playbackId}/thumbnail.png`
return { props: { playbackId, poster } } return { props: { playbackId, poster } }
} }
export function getStaticPaths() { export const getStaticPaths: GetStaticPaths = () => {
return { return {
paths: [], paths: [],
fallback: true, fallback: true,
} }
} }
const Code = ({ children }) => ( type CodeProps = {
children: React.ReactNode
}
const Code = ({ children }: CodeProps) => (
<> <>
<span className="code">{children}</span> <span className="code">{children}</span>
<style jsx>{` <style jsx>{`
...@@ -32,7 +46,10 @@ const Code = ({ children }) => ( ...@@ -32,7 +46,10 @@ const Code = ({ children }) => (
</> </>
) )
export default function Playback({ playbackId, poster }) { export default function Playback({
playbackId,
poster,
}: InferGetStaticPropsType<typeof getStaticProps>) {
const router = useRouter() const router = useRouter()
if (router.isFallback) { if (router.isFallback) {
......
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true
},
"include": ["next-env.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