1
0
mirror of https://github.com/uetchy/namae.git synced 2025-08-20 09:58:13 +09:00

chore: split app into api and web

This commit is contained in:
2019-07-31 13:11:00 +09:00
parent 44c46f329d
commit 11e7f0e9e0
50 changed files with 10730 additions and 472 deletions

125
web/src/App.js Normal file
View File

@@ -0,0 +1,125 @@
import React from 'react'
import styled from 'styled-components'
import { useDeferredState } from './hooks/state'
import { mobile } from './util/css'
import GithubCard from './components/cards/GithubCard'
import DomainCard from './components/cards/DomainCard'
import HomebrewCard from './components/cards/HomebrewCard'
import TwitterCard from './components/cards/TwitterCard'
import SlackCard from './components/cards/SlackCard'
import NpmCard from './components/cards/NpmCard'
import JsOrgCard from './components/cards/JsOrgCard'
import PypiCard from './components/cards/PypiCard'
import S3Card from './components/cards/S3Card'
import CratesioCard from './components/cards/CratesioCard'
import Footer from './components/Footer'
export default function App() {
const [query, setQuery] = useDeferredState(1000)
function onChange(e) {
setQuery(e.target.value)
}
return (
<>
<Header>
<Logo>namæ</Logo>
<SubHeader>name your new project</SubHeader>
<Input onChange={onChange} />
</Header>
{query && query.length > 0 ? (
<Cards>
<CardHeader>Result for {query}</CardHeader>
<CardContainer>
<GithubCard name={query} />
<DomainCard name={query} />
<TwitterCard name={query} />
<HomebrewCard name={query} />
<NpmCard name={query} />
<PypiCard name={query} />
<CratesioCard name={query} />
<JsOrgCard name={query} />
<SlackCard name={query} />
<S3Card name={query} />
</CardContainer>
</Cards>
) : null}
<Footer />
</>
)
}
const Header = styled.header`
margin-top: 30px;
text-align: center;
`
const Logo = styled.div`
margin-bottom: 5px;
font-family: sans-serif;
font-weight: bold;
`
const SubHeader = styled.div`
font-size: 0.8em;
font-style: italic;
`
const Input = styled.input.attrs({
type: 'text',
placeholder: 'awesome-package',
autocomplete: 'off',
autocorrect: 'off',
autocapitalize: 'off',
spellcheck: 'false',
})`
width: 100%;
margin-top: 20px;
padding: 20px;
outline: none;
text-align: center;
font-size: 4rem;
font-family: monospace;
border: none;
transition: box-shadow 0.5s ease-out;
&:hover {
box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
}
${mobile} {
font-size: 2rem;
}
`
const Cards = styled.div`
margin-top: 40px;
`
const CardHeader = styled.div`
margin-bottom: 20px;
font-size: 1.2rem;
font-weight: bold;
text-align: center;
${mobile} {
padding-left: 20px;
text-align: left;
}
`
const CardContainer = styled.div`
display: flex;
flex-direction: row;
justify-content: center;
flex-wrap: wrap;
${mobile} {
flex-direction: column;
}
`

9
web/src/App.test.js Normal file
View File

@@ -0,0 +1,9 @@
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)
})

View File

@@ -0,0 +1,103 @@
import React from 'react'
import styled from 'styled-components'
import useFetch from 'fetch-suspense'
import { BarLoader } from 'react-spinners'
function AvailabilityCell({
name,
availability,
url,
prefix = '',
suffix = '',
icon,
}) {
return (
<ItemContainer>
{icon}
<Item>
<a href={url} target="_blank" rel="noopener noreferrer">
{prefix}
{availability ? (
<span style={{ color: 'green' }}>{name}</span>
) : (
<span style={{ color: 'red' }}>{name}</span>
)}
{suffix}
</a>
</Item>
</ItemContainer>
)
}
export const Fallback = () => (
<ItemContainer>
<BarLoader />
</ItemContainer>
)
export function DedicatedAvailability({
name,
provider,
url,
prefix = '',
suffix = '',
icon,
}) {
const response = useFetch(`/availability/${provider}/${name}`)
if (response.error) {
throw new Error(`${provider}: ${response.error}`)
}
return (
<AvailabilityCell
availability={response.availability}
name={name}
url={url}
prefix={prefix}
suffix={suffix}
icon={icon}
/>
)
}
export function ExistentialAvailability({
name,
target,
prefix = '',
suffix = '',
icon,
}) {
const response = useFetch(target, null, { metadata: true })
if (response.status !== 404 && response.status !== 200) {
throw new Error(`${name}: ${response.status}`)
}
const availability = response.status === 404
return (
<AvailabilityCell
name={name}
availability={availability}
url={`https://formulae.brew.sh/formula/${name}`}
prefix={prefix}
suffix={suffix}
icon={icon}
/>
)
}
const ItemContainer = styled.div`
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;
}
`

View File

@@ -0,0 +1,84 @@
import React, { Suspense, useState } from 'react'
import styled from 'styled-components'
import { Fallback } from './Availability'
import { mobile } from '../util/css'
export function Card({ title, nameList, alternativeList = [], children }) {
const [show, setShow] = useState(false)
function onClick() {
setShow(true)
}
return (
<CardWrapper>
<CardTitle>{title}</CardTitle>
<>
{nameList.map((name) => (
<ErrorBoundary>
<Suspense fallback={<Fallback />}>{children(name)}</Suspense>
</ErrorBoundary>
))}
{show
? alternativeList.map((name) => (
<ErrorBoundary>
<Suspense fallback={<Fallback />}>{children(name)}</Suspense>
</ErrorBoundary>
))
: null}
</>
{alternativeList.length > 0 && !show ? (
<ShowAlternativesButton onClick={onClick}>
show alternatives
</ShowAlternativesButton>
) : null}
</CardWrapper>
)
}
export const CardTitle = styled.div`
font-size: 0.8rem;
font-weight: bold;
margin-bottom: 15px;
`
const CardWrapper = styled.div`
margin-bottom: 20px;
padding: 40px;
border-radius: 2px;
${mobile} {
padding: 20px;
box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.1);
border-radius: 0;
}
`
const ShowAlternativesButton = styled.div`
display: inline-block;
margin-top: 10px;
padding: 5px 0;
border: none;
border-bottom: 1px dashed black;
cursor: pointer;
font-family: monospace;
font-size: 1rem;
`
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
}
}

View File

@@ -0,0 +1,35 @@
import React from 'react'
import styled from 'styled-components'
import { FaTwitter, FaGlobe } from 'react-icons/fa'
export default function Footer() {
return (
<Container>
<p>
Made by U with{' '}
<span role="img" aria-label="love">
🐤
</span>
<br />
<br />
<a
href="https://twitter.com/uetschy"
target="_blank"
rel="noopener noreferrer">
<FaTwitter />
</a>{' '}
<a href="https://uechi.io" target="_blank" rel="noopener noreferrer">
<FaGlobe />
</a>
</p>
</Container>
)
}
const Container = styled.footer`
margin: 40px 0;
text-align: center;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
font-size: 0.8em;
`

View File

@@ -0,0 +1,21 @@
import React from 'react'
import { DiRust } from 'react-icons/di'
import { Card } from '../Card'
import { DedicatedAvailability } from '../Availability'
export default function CratesioCard({ name }) {
const lowerCase = name.toLowerCase()
return (
<Card title="crates.io (Rust)" key={lowerCase} nameList={[lowerCase]}>
{(name) => (
<DedicatedAvailability
name={name}
provider="cratesio"
url={`https://crates.io/crates/${name}`}
icon={<DiRust />}
/>
)}
</Card>
)
}

View File

@@ -0,0 +1,29 @@
import React from 'react'
import { FaMapSigns } from 'react-icons/fa'
import { Card } from '../Card'
import { DedicatedAvailability } from '../Availability'
export default function DomainCard({ name }) {
const lowerCase = name.toLowerCase()
return (
<Card
title="Domain"
key={lowerCase}
nameList={[`${lowerCase}.app`, `${lowerCase}.dev`, `${lowerCase}.org`]}
alternativeList={[
`${lowerCase}app.com`,
`${lowerCase}.build`,
`${lowerCase}.ai`,
]}>
{(name) => (
<DedicatedAvailability
name={name}
provider="domain"
url={`https://domainr.com/?q=${name}`}
icon={<FaMapSigns />}
/>
)}
</Card>
)
}

View File

@@ -0,0 +1,30 @@
import React from 'react'
import { FaGithub } from 'react-icons/fa'
import { Card } from '../Card'
import { DedicatedAvailability } from '../Availability'
import { capitalize } from '../../util/text'
export default function GithubCard({ name }) {
return (
<Card
title="GitHub"
key={name}
nameList={[name]}
alternativeList={[
`${name.toLowerCase()}hq`,
`${name.toLowerCase()}-team`,
`${capitalize(name)}Team`,
`${name.toLowerCase()}-org`,
]}>
{(name) => (
<DedicatedAvailability
name={name}
provider="github"
url={`https://github.com/${name}`}
prefix="github.com/"
icon={<FaGithub />}
/>
)}
</Card>
)
}

View File

@@ -0,0 +1,30 @@
import React from 'react'
import { IoIosBeer } from 'react-icons/io'
import { Card } from '../Card'
import { ExistentialAvailability } from '../Availability'
export default function HomebrewCard({ name }) {
const lowerCase = name.toLowerCase()
return (
<Card title="Homebrew" key={lowerCase} nameList={[lowerCase]}>
{(name) => (
<>
<ExistentialAvailability
name={name}
target={`https://formulae.brew.sh/api/formula/${name}.json`}
url={`https://formulae.brew.sh/formula/${name}`}
icon={<IoIosBeer />}
/>
<ExistentialAvailability
name={name}
target={`https://formulae.brew.sh/api/cask/${name}.json`}
url={`https://formulae.brew.sh/cask/${name}`}
suffix=" (Cask)"
icon={<IoIosBeer />}
/>
</>
)}
</Card>
)
}

View File

@@ -0,0 +1,21 @@
import React from 'react'
import { FaJsSquare } from 'react-icons/fa'
import { Card } from '../Card'
import { DedicatedAvailability } from '../Availability'
export default function JsOrgCard({ name }) {
const lowerCase = name.toLowerCase()
return (
<Card title="js.org" key={lowerCase} nameList={[lowerCase]}>
{(name) => (
<DedicatedAvailability
name={`${name}.js.org`}
provider="dns"
url={`https://${name}.js.org`}
icon={<FaJsSquare />}
/>
)}
</Card>
)
}

View File

@@ -0,0 +1,32 @@
import React from 'react'
import { FaNpm } from 'react-icons/fa'
import { Card } from '../Card'
import { DedicatedAvailability } from '../Availability'
export default function NpmCard({ name }) {
const lowerCase = name.toLowerCase()
return (
<Card title="npm" key={lowerCase} nameList={[lowerCase]}>
{(name) => (
<>
<DedicatedAvailability
name={name}
provider="npm"
url={`https://www.npmjs.com/package/${name}`}
prefix="npmjs.com/"
icon={<FaNpm />}
/>
<DedicatedAvailability
name={name}
provider="npm-org"
url={`https://www.npmjs.com/org/${name}`}
prefix="npmjs.com/~"
suffix=" (Org)"
icon={<FaNpm />}
/>
</>
)}
</Card>
)
}

View File

@@ -0,0 +1,19 @@
import React from 'react'
import { FaPython } from 'react-icons/fa'
import { Card } from '../Card'
import { DedicatedAvailability } from '../Availability'
export default function PypiCard({ name }) {
return (
<Card title="PyPI" key={name} nameList={[name]}>
{(name) => (
<DedicatedAvailability
name={name}
provider="pypi"
url={`https://pypi.org/project/${name}`}
icon={<FaPython />}
/>
)}
</Card>
)
}

View File

@@ -0,0 +1,22 @@
import React from 'react'
import { FaAws } from 'react-icons/fa'
import { Card } from '../Card'
import { DedicatedAvailability } from '../Availability'
export default function S3Card({ name }) {
const lowerCase = name.toLowerCase()
return (
<Card title="AWS S3" key={lowerCase} nameList={[lowerCase]}>
{(name) => (
<DedicatedAvailability
name={name}
provider="s3"
url={`https://${name}.s3.amazonaws.com`}
suffix=".s3.amazonaws.com"
icon={<FaAws />}
/>
)}
</Card>
)
}

View File

@@ -0,0 +1,22 @@
import React from 'react'
import { FaSlack } from 'react-icons/fa'
import { Card } from '../Card'
import { DedicatedAvailability } from '../Availability'
export default function SlackCard({ name }) {
const lowerCase = name.toLowerCase()
return (
<Card title="Slack" key={lowerCase} nameList={[lowerCase]}>
{(name) => (
<DedicatedAvailability
name={name}
provider="slack"
url={`https://${name}.slack.com`}
suffix=".slack.com"
icon={<FaSlack />}
/>
)}
</Card>
)
}

View File

@@ -0,0 +1,30 @@
import React from 'react'
import { FaTwitter } from 'react-icons/fa'
import { Card } from '../Card'
import { DedicatedAvailability } from '../Availability'
import { capitalize } from '../../util/text'
export default function TwitterCard({ name }) {
return (
<Card
title="Twitter"
key={name}
nameList={[name]}
alternativeList={[
`${capitalize(name)}HQ`,
`${name.toLowerCase()}app`,
`${name.toLowerCase()}-support`,
`${capitalize(name)}Team`,
]}>
{(name) => (
<DedicatedAvailability
name={name}
provider="twitter"
url={`https://twitter.com/${name}`}
prefix="twitter.com/"
icon={<FaTwitter />}
/>
)}
</Card>
)
}

18
web/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]
}

19
web/src/index.css Normal file
View File

@@ -0,0 +1,19 @@
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}

9
web/src/index.js Normal file
View File

@@ -0,0 +1,9 @@
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'))
serviceWorker.unregister()

135
web/src/serviceWorker.js Normal file
View File

@@ -0,0 +1,135 @@
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
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)
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
}
window.addEventListener('load', () => {
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)
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
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)
}
})
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then((registration) => {
registration.onupdatefound = () => {
const installingWorker = registration.installing
if (installingWorker == null) {
return
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
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)
}
} 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.')
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration)
}
}
}
}
}
})
.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) => {
// Ensure service worker exists, and that we really are getting a JS file.
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) => {
registration.unregister().then(() => {
window.location.reload()
})
})
} else {
// Service worker found. Proceed as normal.
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()
})
}
}

1
web/src/util/css.js Normal file
View File

@@ -0,0 +1 @@
export const mobile = '@media screen and (max-width: 800px)'

3
web/src/util/text.js Normal file
View File

@@ -0,0 +1,3 @@
export function capitalize(text) {
return text[0].toUpperCase() + text.slice(1).toLowerCase()
}