Skip to content

Commit

Permalink
support preview url
Browse files Browse the repository at this point in the history
  • Loading branch information
torounit committed Nov 22, 2020
1 parent e8e0a7a commit 16066ad
Show file tree
Hide file tree
Showing 14 changed files with 3,427 additions and 232 deletions.
9 changes: 9 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
root = true

[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
17 changes: 17 additions & 0 deletions .wp-env.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"core": "https://wordpress.org/wordpress-5.6-RC1.zip",
"plugins": [
],
"mappings": {
"wp-content/mu-plugins": "./mu-plugins"
},
"config": {
"WP_ENVIRONMENT_TYPE": "local"
},
"port": 12345,
"env": {
"tests": {
"port": 23456
}
}
}
15 changes: 15 additions & 0 deletions components/Article.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
function Article( { post } ) {

return (
<article>
<h1>{ post?.title.rendered }</h1>
<div
dangerouslySetInnerHTML={
{ __html: post?.content.rendered }
}
/>
</article>
);
}

export default Article;
23 changes: 23 additions & 0 deletions lib/apiFetch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import 'cross-fetch/polyfill'
import apiFetch from '@hamworks/wordpress-api-fetch';

apiFetch.use( apiFetch.createRootURLMiddleware( `${process.env.WORDPRESS_URL}/wp-json/` ) );

export const fetcher = ( path ) => {
const user_login = globalThis?.localStorage?.getItem( 'user_login' );
const password = globalThis?.localStorage?.getItem( 'password' );
const authorization = globalThis?.localStorage?.getItem( 'authorization' );
const headers = {};
let request = path;
if ( authorization ) {
headers[ 'Authorization'] = `Basic ${ authorization }`;
}

return apiFetch( {
path: request,
credentials: 'omit',
headers: headers,
} );
};

export default apiFetch;
37 changes: 37 additions & 0 deletions mu-plugins/index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

add_action( 'wp_authorize_application_password_request_errors', function ( WP_Error $error, $request ) {
$host = wp_parse_url( $request['success_url'], PHP_URL_HOST );
if ( $host === 'localhost' ) {
$error->remove( 'invalid_redirect_scheme' );
}
}, 10, 2 );


add_action( 'send_headers', function () {
if ( ! did_action( 'rest_api_init' ) && $_SERVER['REQUEST_METHOD'] == 'HEAD' ) {
header( 'Access-Control-Allow-Origin: *' );
}
} );


add_filter( 'preview_post_link', function ( $preview_link, WP_Post $post ) {

if ( $post->post_type === 'post' ) {
return 'http://localhost:3000/archives/preview/' . $post->ID;
}

return $preview_link;
}, 10, 2 );


add_action( 'template_redirect', function () {
/**
* @var WP_Query;
*/
global $wp_query;
if ( $wp_query->is_preview ) {
wp_redirect( get_preview_post_link( $wp_query->get_queried_object() ) );
}

} );
7 changes: 7 additions & 0 deletions next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const withPWA = require('next-pwa')
const settings = {
env: {
WORDPRESS_URL: process.env.WORDPRESS_URL || 'http://localhost:12345'
}
}
module.exports = process.env.NODE_ENV !== 'production' ? settings: withPWA(settings)
12 changes: 10 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,19 @@
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
"start": "next start",
"export": "next export",
"wp-env": "wp-env start"
},
"dependencies": {
"@hamworks/wordpress-api-fetch": "^0.1.0",
"@wordpress/api-fetch": "^3.20.0",
"@wordpress/env": "^2.1.0",
"next": "10.0.2",
"next-pwa": "^3.1.5",
"react": "17.0.1",
"react-dom": "17.0.1"
"react-dom": "17.0.1",
"swr": "^0.3.9",
"wpapi": "^1.2.1"
}
}
39 changes: 39 additions & 0 deletions pages/archives/[id].js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { fetcher } from '../../lib/apiFetch';
import Article from '../../components/Article';

function Post( { post } ) {

return <Article post={post}/>
}

export default Post;

export const getStaticPaths = async () => {
const posts = await fetcher( '/wp/v2/posts?per_page=-1' );
return {
paths: posts.map( ( { id } ) => ( {
params: {
id: id + '',
}
} ) ),
fallback: true
};
};

export const getStaticProps = async ( { params } ) => {
if ( !params ) {
return {
props: {
post: null,
}
};
}
const id = parseInt( params.id, 10 );
const post = await fetcher( `/wp/v2/posts/${ id }` );
return {
props: {
post: post
}
};
};

30 changes: 30 additions & 0 deletions pages/archives/preview/[id].js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { fetcher } from '../../../lib/apiFetch';
import { useRouter } from 'next/router';
import useSWR from 'swr';
import { useState, useEffect } from 'react';
import Article from '../../../components/Article';

function Preview() {
const [ post, setPost ] = useState();
const [ id, setId ] = useState();
const router = useRouter();
useEffect( () => {
if ( router.asPath !== router.route ) {
setId( Number( router.query.id ) );
}
}, [ router ] );

useEffect( () => {
if ( id ) {
fetcher( `/wp/v2/posts/${ id }` ).then( result => {
setPost(result);
} );
}
}, [ id ] );

return <Article post={ post } />;
}

export default Preview;


30 changes: 30 additions & 0 deletions pages/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { useRouter } from 'next/router';
import Head from 'next/head';
import { useEffect } from 'react';

export default function Auth() {
const {
query: { user_login, password },
} = useRouter();


useEffect( () => {
localStorage.setItem( 'user_login', user_login );
localStorage.setItem( 'password', password );
localStorage.setItem( 'authorization', btoa(user_login + ":" + password ) )
}, [ user_login, password ] )

const app_id = '15891e06-cfd5-4efb-a0bf-1b90bcbb366';
const app_name = 'next';

return (
<div>
<Head>
<title>Create Auth App</title>
</Head>
<a href={ `${process.env.WORDPRESS_URL}/wp-admin/authorize-application.php?${app_id}c&app_name=${app_name}&success_url=http://localhost:3000/auth` }>
auth
</a>
</div>
);
}
93 changes: 34 additions & 59 deletions pages/index.js
Original file line number Diff line number Diff line change
@@ -1,65 +1,40 @@
import Head from 'next/head'
import styles from '../styles/Home.module.css'

export default function Home() {
import Head from 'next/head';
import useSWR from 'swr';
import { fetcher } from '../lib/apiFetch';
import Link from 'next/link';
import { useEffect } from 'react';

export default function Home( { posts: initialData } ) {
const { data: posts, error } = useSWR( '/wp/v2/posts?per_page=-1&context=edit', fetcher, { initialData } );
if ( error ) return <div>failed to load</div>;

const user = useSWR( '/wp/v2/users/me', fetcher );
useEffect( () => {
fetcher( '/wp/v2/users/me' ).then( (result) => console.log(result))
})
return (
<div className={styles.container}>
<div>
<Head>
<title>Create Next App</title>
<link rel="icon" href="/favicon.ico" />
</Head>

<main className={styles.main}>
<h1 className={styles.title}>
Welcome to <a href="https://nextjs.org">Next.js!</a>
</h1>

<p className={styles.description}>
Get started by editing{' '}
<code className={styles.code}>pages/index.js</code>
</p>

<div className={styles.grid}>
<a href="https://nextjs.org/docs" className={styles.card}>
<h3>Documentation &rarr;</h3>
<p>Find in-depth information about Next.js features and API.</p>
</a>

<a href="https://nextjs.org/learn" className={styles.card}>
<h3>Learn &rarr;</h3>
<p>Learn about Next.js in an interactive course with quizzes!</p>
</a>

<a
href="https://github.com/vercel/next.js/tree/master/examples"
className={styles.card}
>
<h3>Examples &rarr;</h3>
<p>Discover and deploy boilerplate example Next.js projects.</p>
</a>

<a
href="https://vercel.com/import?filter=next.js&utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
className={styles.card}
>
<h3>Deploy &rarr;</h3>
<p>
Instantly deploy your Next.js site to a public URL with Vercel.
</p>
</a>
</div>
</main>

<footer className={styles.footer}>
<a
href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Powered by{' '}
<img src="/vercel.svg" alt="Vercel Logo" className={styles.logo} />
</a>
</footer>
<ul>
{ posts.map( ( { id, title } ) => (
<li key={ id }>
<Link href={ `/archives/${ id }` }>
{ title?.rendered }
</Link>
</li>
) ) }
</ul>
</div>
)
);
}

export const getStaticProps = async () => {
const posts = await fetcher( '/wp/v2/posts?per_page=-1' );
return {
props: {
posts: posts || []
}
};
};
47 changes: 47 additions & 0 deletions pages/pages/[slug].js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { fetcher } from '../../lib/apiFetch';
function Page( { post } ) {

return (
<article>
<h1>{ post?.title.rendered }</h1>
<div
dangerouslySetInnerHTML={
{ __html: post?.content.rendered }
}
/>
</article>
);
}

export default Page;

export const getStaticPaths = async () => {
const posts = await fetcher( '/wp/v2/pages?per_page=-1' );
return {
paths: posts.map( ( { id, slug } ) => ( {
params: {
id: id + '',
slug: decodeURI(slug)
}
} ) ),
fallback: process.env.NODE_ENV !== 'production' ? 'blocking' : false
};
};

export const getStaticProps = async ( { params } ) => {
if ( !params ) {
return {
props: {
post: null,
}
};
}
const slug = typeof params.slug === 'string' ? params.slug : params.slug[0]
const pages = await fetcher( `/wp/v2/pages/?slug=${ slug }`);
return {
props: {
post: pages[0]
}
};
};

Loading

0 comments on commit 16066ad

Please sign in to comment.