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 { gsap } from 'gsap'
const Content = () => {
export default function Content() {
let line1 = useRef(null)
useEffect(() => {
gsap.from([line1], 0.6, {
gsap.from([line1.current], 0.6, {
delay: 0.9,
ease: 'power3.out',
y: 24,
......@@ -15,7 +16,7 @@ const Content = () => {
}, [line1])
return (
<p ref={(el) => (line1 = el)} className="line">
<p ref={line1} className="line">
A Simple example using{' '}
<a
href="https://greensock.com/gsap/"
......@@ -33,5 +34,3 @@ const Content = () => {
</p>
)
}
export default Content
import Title from './Title'
import Content from './Content'
const Home = () => {
export default function Home() {
return (
<div className="inner">
<Title lineContent="With-GSAP" lineContent2="Using NEXT" />
......@@ -15,5 +15,3 @@ const Home = () => {
</div>
)
}
export default Home
import { useEffect, useRef } from 'react'
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 line2 = useRef(null)
useEffect(() => {
gsap.from([line1, line2], 0.8, {
gsap.from([line1.current, line2.current], 0.8, {
delay: 0.8,
ease: 'power3.out',
y: 64,
......@@ -14,20 +20,19 @@ const Title = ({ lineContent, lineContent2 }) => {
},
})
}, [line1, line2])
return (
<h1 className="page-title">
<div className="line-wrap">
<div ref={(el) => (line1 = el)} className="line">
<div ref={line1} className="line">
{lineContent}
</div>
</div>
<div className="line-wrap">
<div ref={(el) => (line2 = el)} className="line">
<div ref={line2} className="line">
{lineContent2}
</div>
</div>
</h1>
)
}
export default Title
......@@ -6,11 +6,19 @@
"start": "next start"
},
"dependencies": {
"gsap": "^3.0.1",
"gsap": "^3.11.3",
"next": "latest",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-transition-group": "^4.3.0",
"sass": "1.29.0"
"react-transition-group": "^4.4.5",
"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'
function MyApp({ Component, pageProps }) {
function MyApp({ Component, pageProps }: AppProps) {
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'
import { gsap } from 'gsap'
import Home from '../components/Home'
function App() {
const onEnter = (node) => {
export default function HomePage() {
const onEnter = (node: any) => {
gsap.from(
[node.children[0].firstElementChild, node.children[0].lastElementChild],
0.6,
......@@ -18,7 +18,7 @@ function App() {
}
)
}
const onExit = (node) => {
const onExit = (node: any) => {
gsap.to(
[node.children[0].firstElementChild, node.children[0].lastElementChild],
0.6,
......@@ -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 { useEffect, useRef } from 'react'
interface useMqttProps {
uri: string
options?: IClientOptions
topicHandlers?: { topic: string; handler: (payload: any) => void }[]
onConnectedHandler?: (client: MqttClient) => void
}
function useMqtt({
uri,
options = {},
topicHandlers = [{ topic: '', handler: ({ topic, payload, packet }) => {} }],
onConnectedHandler = (client) => {},
}) {
const clientRef = useRef(null)
}: useMqttProps) {
const clientRef = useRef<MqttClient | null>(null)
useEffect(() => {
if (clientRef.current) return
......@@ -23,9 +31,9 @@ function useMqtt({
const client = clientRef.current
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)
let payload
try {
......@@ -36,7 +44,7 @@ function useMqtt({
if (th) th.handler({ topic, payload, packet })
})
client.on('connect', () => {
client?.on('connect', () => {
if (onConnectedHandler) onConnectedHandler(client)
})
......
......@@ -6,9 +6,15 @@
"start": "next start"
},
"dependencies": {
"mqtt": "4.2.6",
"mqtt": "^4.3.7",
"next": "latest",
"react": "^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 type { MqttClient } from 'mqtt'
import useMqtt from '../lib/useMqtt'
export default function Home() {
const [incommingMessages, setIncommingMessages] = useState([])
const addMessage = (message) => {
const [incommingMessages, setIncommingMessages] = useState<any[]>([])
const addMessage = (message: any) => {
setIncommingMessages((incommingMessages) => [...incommingMessages, message])
}
const clearMessages = () => {
......@@ -13,14 +14,14 @@ export default function Home() {
const incommingMessageHandlers = useRef([
{
topic: 'topic1',
handler: (msg) => {
handler: (msg: string) => {
addMessage(msg)
},
},
])
const mqttClientRef = useRef(null)
const setMqttClient = (client) => {
const mqttClientRef = useRef<MqttClient | null>(null)
const setMqttClient = (client: MqttClient) => {
mqttClientRef.current = client
}
useMqtt({
......@@ -34,7 +35,7 @@ export default function Home() {
onConnectedHandler: (client) => setMqttClient(client),
})
const publishMessages = (client) => {
const publishMessages = (client: any) => {
if (!client) {
console.log('(publishMessages) Cannot publish, mqttClient: ', client)
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 (
<>
<button {...otherProps}>{children}</button>
......
export default function ErrorMessage({ message }) {
interface ErrorMessageProps {
message?: string
}
export default function ErrorMessage({ message }: ErrorMessageProps) {
return (
<>
<div className="message">{message || 'Unknown error'}</div>
......
import Head from 'next/head'
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({
title,
description,
......@@ -9,7 +19,7 @@ export default function Layout({
image = 'https://with-mux-video.vercel.app/mux-nextjs-og-image.png',
children,
loadTwitterWidget,
}) {
}: LayoutProps) {
return (
<div className="container">
<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 (
<>
<div className="spinner" />
......
......@@ -6,7 +6,7 @@ import Button from './button'
import Spinner from './spinner'
import ErrorMessage from './error-message'
const fetcher = (url) => {
const fetcher = (url: string) => {
return fetch(url).then((res) => res.json())
}
......@@ -14,9 +14,9 @@ const UploadForm = () => {
const [isUploading, setIsUploading] = useState(false)
const [isPreparing, setIsPreparing] = useState(false)
const [uploadId, setUploadId] = useState(null)
const [progress, setProgress] = useState(null)
const [progress, setProgress] = useState<Number | null>(null)
const [errorMessage, setErrorMessage] = useState('')
const inputRef = useRef(null)
const inputRef = useRef<HTMLInputElement>(null)
const { data, error } = useSwr(
() => (isPreparing ? `/api/upload/${uploadId}` : null),
......@@ -30,7 +30,6 @@ const UploadForm = () => {
if (upload && upload.asset_id) {
Router.push({
pathname: `/asset/${upload.asset_id}`,
scroll: false,
})
}
}, [upload])
......@@ -54,18 +53,25 @@ const UploadForm = () => {
}
}
const startUpload = (evt) => {
const startUpload = () => {
setIsUploading(true)
const files = inputRef.current?.files
if (!files) {
setErrorMessage('An unexpected issue occurred')
return
}
const upload = UpChunk.createUpload({
endpoint: createUpload,
file: inputRef.current.files[0],
file: files[0],
})
upload.on('error', (err) => {
upload.on('error', (err: any) => {
setErrorMessage(err.detail.message)
})
upload.on('progress', (progress) => {
upload.on('progress', (progress: any) => {
setProgress(Math.floor(progress.detail))
})
......@@ -90,7 +96,7 @@ const UploadForm = () => {
</>
) : (
<label>
<Button type="button" onClick={() => inputRef.current.click()}>
<Button type="button" onClick={() => inputRef.current?.click()}>
Select a video file
</Button>
<input type="file" onChange={startUpload} ref={inputRef} />
......
import Layout from './layout'
import { MUX_HOME_PAGE_URL } from '../constants'
export default function UploadPage({ children }) {
interface UploadPageProps {
children: React.ReactNode
}
export default function UploadPage({ children }: UploadPageProps) {
return (
<Layout
title="Welcome to Mux + Next.js"
......
......@@ -6,12 +6,18 @@
"start": "next start"
},
"dependencies": {
"@mux/mux-node": "^2.8.0",
"@mux/mux-player-react": "latest",
"@mux/upchunk": "^2.3.1",
"@mux/mux-node": "^7.0.0",
"@mux/mux-player-react": "^1.4.0",
"@mux/upchunk": "^3.0.0",
"next": "latest",
"react": "^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'
const { Video } = new Mux()
export default async function assetHandler(req, res) {
export default async function assetHandler(
req: NextApiRequest,
res: NextApiResponse
) {
const { method } = req
switch (method) {
case 'GET':
try {
const asset = await Video.Assets.get(req.query.id)
const asset = await Video.Assets.get(req.query.id as string)
res.json({
asset: {
id: asset.id,
status: asset.status,
errors: asset.errors,
playback_id: asset.playback_ids[0].id,
playback_id: asset.playback_ids![0].id,
},
})
} catch (e) {
......
import type { NextApiRequest, NextApiResponse } from 'next'
import Mux from '@mux/mux-node'
const { Video } = new Mux()
export default async function uploadHandler(req, res) {
export default async function uploadHandler(
req: NextApiRequest,
res: NextApiResponse
) {
const { method } = req
switch (method) {
......
import type { NextApiRequest, NextApiResponse } from 'next'
import Mux from '@mux/mux-node'
const { Video } = new Mux()
export default async function uploadHandler(req, res) {
export default async function uploadHandler(
req: NextApiRequest,
res: NextApiResponse
) {
const { method } = req
switch (method) {
case 'GET':
try {
const upload = await Video.Uploads.get(req.query.id)
const upload = await Video.Uploads.get(req.query.id as string)
res.json({
upload: {
status: upload.status,
......
......@@ -6,7 +6,7 @@ import Spinner from '../../components/spinner'
import ErrorMessage from '../../components/error-message'
import UploadPage from '../../components/upload-page'
const fetcher = (url) => {
const fetcher = (url: string) => {
return fetch(url).then((res) => res.json())
}
......@@ -27,7 +27,7 @@ export default function Asset() {
}
}, [asset])
let errorMessage
let errorMessage: string = ''
if (error) {
errorMessage = 'Error fetching api'
......
import type {
InferGetStaticPropsType,
GetStaticProps,
GetStaticPaths,
} from 'next'
import MuxPlayer from '@mux/mux-player-react'
import Link from 'next/link'
import Layout from '../../components/layout'
......@@ -5,20 +10,29 @@ import Spinner from '../../components/spinner'
import { MUX_HOME_PAGE_URL } from '../../constants'
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`
return { props: { playbackId, poster } }
}
export function getStaticPaths() {
export const getStaticPaths: GetStaticPaths = () => {
return {
paths: [],
fallback: true,
}
}
const Code = ({ children }) => (
type CodeProps = {
children: React.ReactNode
}
const Code = ({ children }: CodeProps) => (
<>
<span className="code">{children}</span>
<style jsx>{`
......@@ -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()
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