Skip to content

Commit

Permalink
Merge remote-tracking branch 'upstream/canary' into update/adding-bas…
Browse files Browse the repository at this point in the history
…ePath
  • Loading branch information
ijjk committed Feb 8, 2020
2 parents efa2899 + 0183a13 commit 4cc5241
Show file tree
Hide file tree
Showing 71 changed files with 1,022 additions and 354 deletions.
2 changes: 0 additions & 2 deletions examples/blog-starter/now.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
{
"version": 2,
"name": "nextjs-blog-starter",
"alias": ["nextjs-blog-starter.now.sh"],
"builds": [{ "src": "package.json", "use": "@now/next" }],
"routes": [
{ "src": "/feed.json", "dest": "/_next/static/feed.json" },
{ "src": "/blog/(?<page>[^/]+)$", "dest": "/blog?page=$page" }
Expand Down
64 changes: 43 additions & 21 deletions examples/with-apollo/lib/apollo.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React from 'react'
import App from 'next/app'
import Head from 'next/head'
import { ApolloProvider } from '@apollo/react-hooks'
import { ApolloClient } from 'apollo-client'
Expand All @@ -12,11 +13,8 @@ let globalApolloClient = null
* Creates and provides the apolloContext
* to a next.js PageTree. Use it by wrapping
* your PageComponent via HOC pattern.
* @param {Function|Class} PageComponent
* @param {Object} [config]
* @param {Boolean} [config.ssr=true]
*/
export function withApollo(PageComponent, { ssr = true } = {}) {
export const withApollo = ({ ssr = true } = {}) => PageComponent => {
const WithApollo = ({ apolloClient, apolloState, ...pageProps }) => {
const client = apolloClient || initApolloClient(apolloState)
return (
Expand All @@ -31,25 +29,44 @@ export function withApollo(PageComponent, { ssr = true } = {}) {
const displayName =
PageComponent.displayName || PageComponent.name || 'Component'

if (displayName === 'App') {
console.warn('This withApollo HOC only works with PageComponents.')
}

WithApollo.displayName = `withApollo(${displayName})`
}

if (ssr || PageComponent.getInitialProps) {
WithApollo.getInitialProps = async ctx => {
const { AppTree } = ctx
const inAppContext = Boolean(ctx.ctx)

if (process.env.NODE_ENV === 'development') {
if (inAppContext) {
console.warn(
'Warning: You have opted-out of Automatic Static Optimization due to `withApollo` in `pages/_app`.\n' +
'Read more: https://err.sh/next.js/opt-out-auto-static-optimization\n'
)
}
}

// Initialize ApolloClient, add it to the ctx object so
// we can use it in `PageComponent.getInitialProp`.
const apolloClient = (ctx.apolloClient = initApolloClient())
if (ctx.apolloClient) {
throw new Error('Multiple instances of withApollo found.')
}

// Initialize ApolloClient
const apolloClient = initApolloClient()

// Add apolloClient to NextPageContext & NextAppContext
// This allows us to consume the apolloClient inside our
// custom `getInitialProps({ apolloClient })`.
ctx.apolloClient = apolloClient
if (inAppContext) {
ctx.ctx.apolloClient = apolloClient
}

// Run wrapped getInitialProps methods
let pageProps = {}
if (PageComponent.getInitialProps) {
pageProps = await PageComponent.getInitialProps(ctx)
} else if (inAppContext) {
pageProps = await App.getInitialProps(ctx)
}

// Only on the server:
Expand All @@ -65,14 +82,19 @@ export function withApollo(PageComponent, { ssr = true } = {}) {
try {
// Run all GraphQL queries
const { getDataFromTree } = await import('@apollo/react-ssr')
await getDataFromTree(
<AppTree
pageProps={{
...pageProps,
apolloClient,
}}
/>
)

// Since AppComponents and PageComponents have different context types
// we need to modify their props a little.
let props
if (inAppContext) {
props = { ...pageProps, apolloClient }
} else {
props = { pageProps: { ...pageProps, apolloClient } }
}

// Takes React AppTree, determine which queries are needed to render,
// then fetche them all.
await getDataFromTree(<AppTree {...props} />)
} catch (error) {
// Prevent Apollo Client GraphQL errors from crashing SSR.
// Handle them in components via the data.error prop:
Expand Down Expand Up @@ -104,7 +126,7 @@ export function withApollo(PageComponent, { ssr = true } = {}) {
* Creates or reuses apollo client in the browser.
* @param {Object} initialState
*/
function initApolloClient(initialState) {
const initApolloClient = initialState => {
// Make sure to create a new client for every server-side request so that data
// isn't shared between connections (which would be bad)
if (typeof window === 'undefined') {
Expand All @@ -123,7 +145,7 @@ function initApolloClient(initialState) {
* Creates and configures the ApolloClient
* @param {Object} [initialState={}]
*/
function createApolloClient(initialState = {}) {
const createApolloClient = (initialState = {}) => {
// Check out https://github.com/zeit/next.js/pull/4611 if you want to use the AWSAppSyncClient
return new ApolloClient({
ssrMode: typeof window === 'undefined', // Disables forceFetch on the server (so queries are only run once)
Expand Down
6 changes: 2 additions & 4 deletions examples/with-apollo/pages/client-only.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,5 @@ const ClientOnlyPage = props => (
</App>
)

export default withApollo(ClientOnlyPage, {
// Disable apollo ssr fetching in favour of automatic static optimization
ssr: false,
})
// Disable apollo ssr fetching in favour of automatic static optimization
export default withApollo({ ssr: false })(ClientOnlyPage)
2 changes: 1 addition & 1 deletion examples/with-apollo/pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,4 @@ const IndexPage = props => (
</App>
)

export default withApollo(IndexPage)
export default withApollo()(IndexPage)
7 changes: 0 additions & 7 deletions examples/with-now-env/now.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,4 @@
{
"version": 2,
"builds": [
{
"src": "package.json",
"use": "@now/next"
}
],
"build": {
"env": {
"SECRET": "@my-secret-key",
Expand Down
2 changes: 2 additions & 0 deletions examples/with-stencil/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.
now
```

> Choose `packages/web-app` as root directory when deploying.
## The idea behind the example

Stencil is a compiler that generates Web Components (more specifically, Custom Elements). Stencil combines the best concepts of the most popular frameworks into a simple build-time tool.
Expand Down
5 changes: 0 additions & 5 deletions examples/with-stencil/now.json

This file was deleted.

49 changes: 49 additions & 0 deletions examples/with-three-js/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# With Three js

This example uses:

`threejs`: A lightweight, 3D library with a default WebGL renderer. The library also provides Canvas 2D, SVG and CSS3D renderers in the examples.
`react-three-fiber`: A React renderer for Threejs on the web and react-native.

## Deploy your own

Deploy the example using [ZEIT Now](https://zeit.co/now):

[![Deploy with ZEIT Now](https://zeit.co/button)](https://zeit.co/new/project?template=https://github.com/zeit/next.js/tree/canary/examples/with-three-js)

## How to use

### Using `create-next-app`

Execute [`create-next-app`](https://github.com/zeit/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:

```bash
npx create-next-app --example with-three-js
# or
yarn create next-app --example with-three-js
```

### Download manually

Download the example:

```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-three-js
cd with-three-js
```

Install it and run:

```bash
npm install
npm run dev
# or
yarn
yarn dev
```

Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download)):

```bash
now
```
18 changes: 18 additions & 0 deletions examples/with-three-js/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "with-three-js",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "9.2.1",
"react": "16.12.0",
"react-dom": "16.12.0",
"react-three-fiber": "4.0.12",
"three": "0.112.1"
},
"devDependencies": {}
}
8 changes: 8 additions & 0 deletions examples/with-three-js/pages/_app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import React from 'react'
import './index.css'

function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}

export default MyApp
84 changes: 84 additions & 0 deletions examples/with-three-js/pages/birds.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import React, { useRef, useState, useEffect, Suspense } from 'react'
import * as THREE from 'three'
import { Canvas, useFrame, useLoader } from 'react-three-fiber'

let GLTFLoader

const Bird = ({ speed, factor, url, ...props }) => {
const gltf = useLoader(GLTFLoader, url)
const group = useRef()
const [mixer] = useState(() => new THREE.AnimationMixer())
useEffect(
() => void mixer.clipAction(gltf.animations[0], group.current).play(),
[gltf.animations, mixer]
)
useFrame((state, delta) => {
group.current.rotation.y +=
Math.sin((delta * factor) / 2) * Math.cos((delta * factor) / 2) * 1.5
mixer.update(delta * speed)
})
return (
<group ref={group}>
<scene name="Scene" {...props}>
<mesh
name="Object_0"
morphTargetDictionary={gltf.__$[1].morphTargetDictionary}
morphTargetInfluences={gltf.__$[1].morphTargetInfluences}
rotation={[1.5707964611537577, 0, 0]}
>
<bufferGeometry attach="geometry" {...gltf.__$[1].geometry} />
<meshStandardMaterial
attach="material"
{...gltf.__$[1].material}
name="Material_0_COLOR_0"
/>
</mesh>
</scene>
</group>
)
}

const Birds = () => {
return new Array(5).fill().map((_, i) => {
const x = (15 + Math.random() * 30) * (Math.round(Math.random()) ? -1 : 1)
const y = -10 + Math.random() * 20
const z = -5 + Math.random() * 10
const bird = ['stork', 'parrot', 'flamingo'][Math.round(Math.random() * 2)]
let speed = bird === 'stork' ? 0.5 : bird === 'flamingo' ? 2 : 5
let factor =
bird === 'stork'
? 0.5 + Math.random()
: bird === 'flamingo'
? 0.25 + Math.random()
: 1 + Math.random() - 0.5
return (
<Bird
key={i}
position={[x, y, z]}
rotation={[0, x > 0 ? Math.PI : 0, 0]}
speed={speed}
factor={factor}
url={`/glb/${bird}.glb`}
/>
)
})
}

const BirdsPage = props => {
useEffect(() => {
GLTFLoader = require('three/examples/jsm/loaders/GLTFLoader').GLTFLoader
}, [])
return (
<>
<Canvas camera={{ position: [0, 0, 35] }}>
<ambientLight intensity={2} />
<pointLight position={[40, 40, 40]} />
<Suspense fallback={null}>
<Birds />
</Suspense>
</Canvas>
</>
)
}

export default BirdsPage
46 changes: 46 additions & 0 deletions examples/with-three-js/pages/boxes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import React, { useRef, useState, Suspense } from 'react'
import { Canvas, useFrame } from 'react-three-fiber'

const Box = props => {
const mesh = useRef()

const [hovered, setHover] = useState(false)
const [active, setActive] = useState(false)

useFrame(() => (mesh.current.rotation.x = mesh.current.rotation.y += 0.01))

return (
<mesh
{...props}
ref={mesh}
scale={active ? [6, 6, 6] : [5, 5, 5]}
onClick={e => setActive(!active)}
onPointerOver={e => setHover(true)}
onPointerOut={e => setHover(false)}
>
<boxBufferGeometry attach="geometry" args={[1, 1, 1]} />
<meshStandardMaterial
attach="material"
color={hovered ? '#2b6c76' : '#720b23'}
/>
</mesh>
)
}

const BirdsPage = () => {
return [
<h1>Click on me - Hover me :)</h1>,
<Canvas camera={{ position: [0, 0, 35] }}>
<ambientLight intensity={2} />
<pointLight position={[40, 40, 40]} />
<Suspense fallback={null}>
<Box position={[10, 0, 0]} />
<Box position={[-10, 0, 0]} />
<Box position={[0, 10, 0]} />
<Box position={[0, -10, 0]} />
</Suspense>
</Canvas>,
]
}

export default BirdsPage
Loading

0 comments on commit 4cc5241

Please sign in to comment.