1
0
mirror of https://github.com/uetchy/namae.git synced 2025-10-14 23:22:19 +09:00

feat: add MVP

This commit is contained in:
2019-07-30 23:27:28 +09:00
parent f84667b2d6
commit d7872f9872
19 changed files with 770 additions and 194 deletions

View File

@@ -1,86 +1,71 @@
import React from 'react'
import styled, { createGlobalStyle } from 'styled-components'
import { useDeferredState } from './hooks/state'
import { CardHolder } from './components/Card'
import GithubCard from './components/GithubCard'
import TwitterCard from './components/TwitterCard'
import NpmCard from './components/NpmCard'
import './App.css'
function useDeferredState(duration) {
const [response, setResponse] = React.useState()
const [innerValue, setInnerValue] = React.useState()
const GlobalStyle = createGlobalStyle`
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
`
React.useEffect(() => {
const fn = setTimeout(() => {
setResponse(innerValue)
}, duration)
return () => {
clearTimeout(fn)
}
}, [duration, innerValue])
return [response, setInnerValue]
}
async function githubAvailability(name) {
const response = await fetch(`/availability/github/${name}`)
const json = await response.json()
return json.availability
}
async function npmAvailability(name) {
const response = await fetch(`/availability/npm/${name}`)
const json = await response.json()
return json.availability
}
function App() {
const [query, setQuery] = useDeferredState(1000) // 1sec 遅延
const [githubOrg, setGithubOrg] = React.useState()
const [npmOrg, setNpmOrg] = React.useState()
export default function App() {
const [query, setQuery] = useDeferredState(1000)
function onChange(e) {
setQuery(e.target.value)
}
React.useEffect(() => {
const fn = async () => {
if (!query) return
const github = await githubAvailability(query)
const npm = await npmAvailability(query)
setGithubOrg(github)
setNpmOrg(npm)
}
fn()
}, [query])
return (
<div>
<>
<GlobalStyle />
<header>
<input onChange={onChange} />
<Input
onChange={onChange}
placeholder="awesome-package"
autoComplete="off"
autoCorrect="off"
autoCapitalize="off"
spellCheck="false"
/>
</header>
<div>
{githubOrg !== undefined && (
<div>
github.com/
{githubOrg ? (
<span style={{ color: 'blue' }}>{query}</span>
) : (
<span style={{ color: 'red' }}>{query}</span>
)}
</div>
)}
</div>
<div>
{npmOrg !== undefined && (
<div>
npmjs.com/~
{npmOrg ? (
<span style={{ color: 'blue' }}>{query}</span>
) : (
<span style={{ color: 'red' }}>{query}</span>
)}
</div>
)}
</div>
</div>
{query && query.length > 0 ? (
<SearchResult>
<ResultHeader>Result for {query}</ResultHeader>
<CardHolder>
<GithubCard name={query} />
<TwitterCard name={query} />
<NpmCard name={query} />
</CardHolder>
</SearchResult>
) : null}
</>
)
}
export default App
const Input = styled.input`
width: 100%;
padding: 20px;
outline: none;
font-size: 4rem;
font-family: monospace;
@media screen and (max-width: 800px) {
font-size: 2rem;
}
`
const SearchResult = styled.div`
margin-top: 40px;
`
const ResultHeader = styled.h4`
padding-left: 20px;
margin-bottom: 20px;
`

View File

@@ -1,9 +1,9 @@
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});
const div = document.createElement('div')
ReactDOM.render(<App />, div)
ReactDOM.unmountComponentAtNode(div)
})

83
src/components/Card.js Normal file
View File

@@ -0,0 +1,83 @@
import React, { Suspense } from 'react'
import styled from 'styled-components'
import { BarLoader } from 'react-spinners'
class ErrorBoundary extends React.Component {
constructor(props) {
super(props)
this.state = { hasError: false }
}
static getDerivedStateFromError(error) {
return { hasError: true, message: error.message }
}
componentDidCatch(error, info) {}
render() {
if (this.state.hasError) {
return <h4>{this.state.message}</h4>
}
return this.props.children
}
}
export function Card({ children }) {
return (
<CardWrapper>
<ErrorBoundary>
<Suspense fallback={<BarLoader />}>{children}</Suspense>
</ErrorBoundary>
</CardWrapper>
)
}
export const CardHolder = styled.div`
display: flex;
flex-direction: column;
`
export const CardWrapper = styled.div`
margin-bottom: 40px;
padding: 20px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
border-radius: 2px;
`
const ItemContainer = styled.span`
display: flex;
flex-direction: row;
align-items: flex-start;
margin-top: 8px;
word-break: break-all;
`
const Item = styled.span`
margin-left: 6px;
font-family: monospace;
font-size: 1rem;
a {
text-decoration: none;
color: inherit;
}
`
export function AvailabilityCell({ name, availability, url, prefix, icon }) {
return (
<ItemContainer>
{icon}
<Item>
<a href={url + name} target="_blank" rel="noopener noreferrer">
{prefix}
{availability ? (
<span style={{ color: 'green' }}>{name}</span>
) : (
<span style={{ color: 'red' }}>{name}</span>
)}
</a>
</Item>
</ItemContainer>
)
}

View File

@@ -0,0 +1,30 @@
import React from 'react'
import useFetch from 'fetch-suspense'
import { Card, AvailabilityCell } from './Card'
import { FaGithub } from 'react-icons/fa'
function GithubPanel({ name }) {
const response = useFetch(`/availability/github/${name}`)
if (response.error) {
throw new Error(`GitHub: ${response.error}`)
}
return (
<AvailabilityCell
name={name}
availability={response.availability}
icon={<FaGithub />}
url="https://github.com/"
prefix="github.com/"
/>
)
}
export default function GithubCard({ name }) {
return (
<Card key={name}>
<GithubPanel name={name} />
</Card>
)
}

39
src/components/NpmCard.js Normal file
View File

@@ -0,0 +1,39 @@
import React from 'react'
import useFetch from 'fetch-suspense'
import { Card, AvailabilityCell } from './Card'
import { FaNpm } from 'react-icons/fa'
function NpmPanel({ name }) {
const response = useFetch(`/availability/npm/${name}`)
if (response.error) {
throw new Error(`npm: ${response.error}`)
}
return (
<>
<AvailabilityCell
name={name}
availability={response.packageAvailability}
icon={<FaNpm />}
url="https://www.npmjs.com/package/"
prefix="npmjs.com/package/"
/>
<AvailabilityCell
name={name}
availability={response.orgAvailability}
icon={<FaNpm />}
url="https://www.npmjs.com/org/"
prefix="npmjs.com/org/"
/>
</>
)
}
export default function NpmCard({ name }) {
return (
<Card key={name.toLowerCase()}>
<NpmPanel name={name.toLowerCase()} />
</Card>
)
}

View File

@@ -0,0 +1,30 @@
import React from 'react'
import useFetch from 'fetch-suspense'
import { Card, AvailabilityCell } from './Card'
import { FaTwitter } from 'react-icons/fa'
function TwitterPanel({ name }) {
const response = useFetch(`/availability/twitter/${name}`)
if (response.error) {
throw new Error(`Twitter: ${response.error}`)
}
return (
<AvailabilityCell
name={name}
availability={response.availability}
icon={<FaTwitter />}
url="https://twitter.com/"
prefix="twitter.com/"
/>
)
}
export default function TwitterCard({ name }) {
return (
<Card key={name}>
<TwitterPanel name={name} />
</Card>
)
}

18
src/hooks/state.js Normal file
View File

@@ -0,0 +1,18 @@
import { useState, useEffect } from 'react'
export function useDeferredState(duration) {
const [response, setResponse] = useState()
const [innerValue, setInnerValue] = useState()
useEffect(() => {
const fn = setTimeout(() => {
setResponse(innerValue)
}, duration)
return () => {
clearTimeout(fn)
}
}, [duration, innerValue])
return [response, setInnerValue]
}

View File

@@ -1,12 +1,12 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import * as serviceWorker from './serviceWorker'
ReactDOM.render(<App />, document.getElementById('root'));
ReactDOM.render(<App />, document.getElementById('root'))
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
serviceWorker.unregister()

View File

@@ -18,25 +18,25 @@ const isLocalhost = Boolean(
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
)
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href)
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
return
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
checkValidServiceWorker(swUrl, config)
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
@@ -44,24 +44,24 @@ export function register(config) {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
);
});
)
})
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
registerValidSW(swUrl, config)
}
});
})
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
.then((registration) => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
const installingWorker = registration.installing
if (installingWorker == null) {
return;
return
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
@@ -72,64 +72,64 @@ function registerValidSW(swUrl, config) {
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
);
)
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
config.onUpdate(registration)
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
console.log('Content is cached for offline use.')
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
config.onSuccess(registration)
}
}
}
};
};
}
}
})
.catch((error) => {
console.error('Error during service worker registration:', error)
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
.then((response) => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
const contentType = response.headers.get('content-type')
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
navigator.serviceWorker.ready.then((registration) => {
registration.unregister().then(() => {
window.location.reload();
});
});
window.location.reload()
})
})
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
registerValidSW(swUrl, config)
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
)
})
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
navigator.serviceWorker.ready.then((registration) => {
registration.unregister()
})
}
}

22
src/services/github.js Normal file
View File

@@ -0,0 +1,22 @@
const fetch = require('isomorphic-unfetch')
async function getGitHubAvailability(name) {
const githubURL = 'https://github.com'
const response = await fetch(`${githubURL}/${encodeURIComponent(name)}`)
return response.status === 404
}
module.exports = async (req, res) => {
const name = req.query.name
if (!name) {
return res.status(400).json({ error: 'no query given' })
}
try {
const availability = await getGitHubAvailability(name)
res.json({ availability })
} catch (err) {
res.status(400).json({ error: err.message })
}
}

17
src/services/npm.js Normal file
View File

@@ -0,0 +1,17 @@
const npmName = require('npm-name')
module.exports = async (req, res) => {
const name = req.query.name
if (!name) {
return res.status(400).json({ error: 'no query given' })
}
try {
const packageAvailability = await npmName(name)
const orgAvailability = await npmName(`@${name}`)
res.json({ packageAvailability, orgAvailability })
} catch (err) {
res.status(400).json({ error: err.message })
}
}

22
src/services/twitter.js Normal file
View File

@@ -0,0 +1,22 @@
const fetch = require('isomorphic-unfetch')
async function getTwitterAvailability(name) {
const twitterURL = 'https://twitter.com'
const response = await fetch(`${twitterURL}/${encodeURIComponent(name)}`)
return response.status === 404
}
module.exports = async (req, res) => {
const name = req.query.name
if (!name) {
return res.status(400).json({ error: 'no query given' })
}
try {
const availability = await getTwitterAvailability(name)
res.json({ availability })
} catch (err) {
res.status(400).json({ error: err.message })
}
}