New "browse" UI

Also, separated out browse, ?meta, and ?module request handlers.

Fixes #82
This commit is contained in:
Michael Jackson
2019-07-24 17:55:13 -07:00
parent ea35b3c4b0
commit 34baab07ab
57 changed files with 2431 additions and 686 deletions

View File

@ -2,12 +2,12 @@
"env": {
"browser": true
},
"plugins": [
"react"
],
"plugins": ["react", "react-hooks"],
"rules": {
"react/jsx-uses-react": "error",
"react/jsx-uses-vars": "error"
"react/jsx-uses-vars": "error",
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn"
},
"settings": {
"react": {

View File

@ -1,91 +0,0 @@
/** @jsx jsx */
import PropTypes from 'prop-types';
import { Global, css, jsx } from '@emotion/core';
import DirectoryListing from './DirectoryListing.js';
const globalStyles = css`
body {
font-size: 14px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
Helvetica, Arial, sans-serif;
line-height: 1.7;
padding: 0px 10px 5px;
color: #000000;
}
`;
export default function App({
packageName,
packageVersion,
availableVersions = [],
filename,
entry,
entries
}) {
function handleChange(event) {
window.location.href = window.location.href.replace(
'@' + packageVersion,
'@' + event.target.value
);
}
return (
<div css={{ maxWidth: 900, margin: '0 auto' }}>
<Global styles={globalStyles} />
<header
css={{
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between'
}}
>
<h1>
Index of /{packageName}@{packageVersion}
{filename}
</h1>
<div css={{ float: 'right', lineHeight: '2.25em' }}>
Version:{' '}
<select
id="version"
defaultValue={packageVersion}
onChange={handleChange}
css={{ fontSize: '1em' }}
>
{availableVersions.map(v => (
<option key={v} value={v}>
{v}
</option>
))}
</select>
</div>
</header>
<hr />
<DirectoryListing filename={filename} entry={entry} entries={entries} />
<hr />
<address css={{ textAlign: 'right' }}>
{packageName}@{packageVersion}
</address>
</div>
);
}
if (process.env.NODE_ENV !== 'production') {
const entryType = PropTypes.object;
App.propTypes = {
packageName: PropTypes.string.isRequired,
packageVersion: PropTypes.string.isRequired,
availableVersions: PropTypes.arrayOf(PropTypes.string),
filename: PropTypes.string.isRequired,
entry: entryType.isRequired,
entries: PropTypes.objectOf(entryType).isRequired
};
}

View File

@ -1,142 +0,0 @@
/** @jsx jsx */
import React from 'react';
import PropTypes from 'prop-types';
import { jsx } from '@emotion/core';
import formatBytes from 'pretty-bytes';
import sortBy from 'sort-by';
function getDirname(name) {
return (
name
.split('/')
.slice(0, -1)
.join('/') || '.'
);
}
function getMatchingEntries(entry, entries) {
const dirname = entry.name || '.';
return Object.keys(entries)
.filter(name => entry.name !== name && getDirname(name) === dirname)
.map(name => entries[name]);
}
function getRelativeName(base, name) {
return base.length ? name.substr(base.length + 1) : name;
}
const styles = {
tableHead: {
textAlign: 'left',
padding: '0.5em 1em'
},
tableCell: {
padding: '0.5em 1em'
},
evenRow: {
backgroundColor: '#eee'
}
};
export default function DirectoryListing({ filename, entry, entries }) {
const rows = [];
if (filename !== '/') {
rows.push(
<tr key="..">
<td css={styles.tableCell}>
<a title="Parent directory" href="../">
..
</a>
</td>
<td css={styles.tableCell}>-</td>
<td css={styles.tableCell}>-</td>
<td css={styles.tableCell}>-</td>
</tr>
);
}
const matchingEntries = getMatchingEntries(entry, entries);
matchingEntries
.filter(({ type }) => type === 'directory')
.sort(sortBy('name'))
.forEach(({ name }) => {
const relName = getRelativeName(entry.name, name);
const href = relName + '/';
rows.push(
<tr key={name}>
<td css={styles.tableCell}>
<a title={relName} href={href}>
{href}
</a>
</td>
<td css={styles.tableCell}>-</td>
<td css={styles.tableCell}>-</td>
<td css={styles.tableCell}>-</td>
</tr>
);
});
matchingEntries
.filter(({ type }) => type === 'file')
.sort(sortBy('name'))
.forEach(({ name, size, contentType, lastModified }) => {
const relName = getRelativeName(entry.name, name);
rows.push(
<tr key={name}>
<td css={styles.tableCell}>
<a title={relName} href={relName}>
{relName}
</a>
</td>
<td css={styles.tableCell}>{contentType}</td>
<td css={styles.tableCell}>{formatBytes(size)}</td>
<td css={styles.tableCell}>{lastModified}</td>
</tr>
);
});
return (
<div>
<table
css={{
width: '100%',
borderCollapse: 'collapse',
font: '0.85em Monaco, monospace'
}}
>
<thead>
<tr>
<th css={styles.tableHead}>Name</th>
<th css={styles.tableHead}>Type</th>
<th css={styles.tableHead}>Size</th>
<th css={styles.tableHead}>Last Modified</th>
</tr>
</thead>
<tbody>
{rows.map((row, index) =>
React.cloneElement(row, {
style: index % 2 ? undefined : styles.evenRow
})
)}
</tbody>
</table>
</div>
);
}
if (process.env.NODE_ENV !== 'production') {
const entryType = PropTypes.shape({
name: PropTypes.string.isRequired
});
DirectoryListing.propTypes = {
filename: PropTypes.string.isRequired,
entry: entryType.isRequired,
entries: PropTypes.objectOf(entryType).isRequired
};
}

View File

@ -1,7 +1,7 @@
import React from 'react';
import ReactDOM from 'react-dom';
import App from './autoIndex/App.js';
import App from './browse/App.js';
const props = window.__DATA__ || {};

View File

@ -0,0 +1,356 @@
/** @jsx jsx */
import { Global, css, jsx } from '@emotion/core';
import { Fragment } from 'react';
import PropTypes from 'prop-types';
import { fontSans, fontMono } from '../utils/style.js';
import { PackageInfoProvider } from './PackageInfo.js';
import DirectoryViewer from './DirectoryViewer.js';
import FileViewer from './FileViewer.js';
import { TwitterIcon, GitHubIcon } from './Icons.js';
import SelectDownArrow from './images/SelectDownArrow.png';
const globalStyles = css`
html {
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
html,
body,
#root {
height: 100%;
margin: 0;
}
body {
${fontSans}
font-size: 16px;
line-height: 1.5;
background: white;
color: black;
}
code {
${fontMono}
}
th,
td {
padding: 0;
}
select {
font-size: inherit;
}
#root {
display: flex;
flex-direction: column;
}
`;
// Adapted from https://github.com/highlightjs/highlight.js/blob/master/src/styles/atom-one-light.css
const lightCodeStyles = css`
.code-listing {
background: #fbfdff;
color: #383a42;
}
.code-comment,
.code-quote {
color: #a0a1a7;
font-style: italic;
}
.code-doctag,
.code-keyword,
.code-link,
.code-formula {
color: #a626a4;
}
.code-section,
.code-name,
.code-selector-tag,
.code-deletion,
.code-subst {
color: #e45649;
}
.code-literal {
color: #0184bb;
}
.code-string,
.code-regexp,
.code-addition,
.code-attribute,
.code-meta-string {
color: #50a14f;
}
.code-built_in,
.code-class .code-title {
color: #c18401;
}
.code-attr,
.code-variable,
.code-template-variable,
.code-type,
.code-selector-class,
.code-selector-attr,
.code-selector-pseudo,
.code-number {
color: #986801;
}
.code-symbol,
.code-bullet,
.code-meta,
.code-selector-id,
.code-title {
color: #4078f2;
}
.code-emphasis {
font-style: italic;
}
.code-strong {
font-weight: bold;
}
`;
const linkStyle = {
color: '#0076ff',
textDecoration: 'none',
':hover': {
textDecoration: 'underline'
}
};
export default function App({
packageName,
packageVersion,
availableVersions = [],
filename,
target
}) {
function handleChange(event) {
window.location.href = window.location.href.replace(
'@' + packageVersion,
'@' + event.target.value
);
}
const breadcrumbs = [];
if (filename === '/') {
breadcrumbs.push(packageName);
} else {
let url = `/browse/${packageName}@${packageVersion}`;
breadcrumbs.push(
<a href={`${url}/`} css={linkStyle}>
{packageName}
</a>
);
const segments = filename
.replace(/^\/+/, '')
.replace(/\/+$/, '')
.split('/');
const lastSegment = segments.pop();
segments.forEach(segment => {
url += `/${segment}`;
breadcrumbs.push(
<a href={`${url}/`} css={linkStyle}>
{segment}
</a>
);
});
breadcrumbs.push(lastSegment);
}
// TODO: Provide a user pref to go full width?
const maxContentWidth = 940;
return (
<PackageInfoProvider
packageName={packageName}
packageVersion={packageVersion}
>
<Fragment>
<Global styles={globalStyles} />
<Global styles={lightCodeStyles} />
<div css={{ flex: '1 0 auto' }}>
<div
css={{
maxWidth: maxContentWidth,
padding: '0 20px',
margin: '0 auto'
}}
>
<header css={{ textAlign: 'center' }}>
<h1 css={{ fontSize: '3rem', marginTop: '2rem' }}>
<a href="/" css={{ color: '#000', textDecoration: 'none' }}>
UNPKG
</a>
</h1>
{/*
<nav>
<a href="#" css={{ ...linkStyle, color: '#c400ff' }}>
Become a Sponsor
</a>
</nav>
*/}
</header>
<header
css={{
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between'
}}
>
<h1 css={{ fontSize: '1.5rem' }}>
<nav>
{breadcrumbs.map((link, index) => (
<span key={index}>
{index !== 0 && (
<span css={{ paddingLeft: 5, paddingRight: 5 }}>/</span>
)}
{link}
</span>
))}
</nav>
</h1>
<div>
<label htmlFor="version">Version:</label>{' '}
<select
name="version"
defaultValue={packageVersion}
onChange={handleChange}
css={{
appearance: 'none',
cursor: 'pointer',
padding: '4px 24px 4px 8px',
fontWeight: 600,
fontSize: '0.9em',
color: '#24292e',
border: '1px solid rgba(27,31,35,.2)',
borderRadius: 3,
backgroundColor: '#eff3f6',
backgroundImage: `url(${SelectDownArrow})`,
backgroundPosition: 'right 8px center',
backgroundRepeat: 'no-repeat',
backgroundSize: 'auto 25%',
':hover': {
backgroundColor: '#e6ebf1',
borderColor: 'rgba(27,31,35,.35)'
},
':active': {
backgroundColor: '#e9ecef',
borderColor: 'rgba(27,31,35,.35)',
boxShadow: 'inset 0 0.15em 0.3em rgba(27,31,35,.15)'
}
}}
>
{availableVersions.map(v => (
<option key={v} value={v}>
{v}
</option>
))}
</select>
</div>
</header>
</div>
<div
css={{
maxWidth: maxContentWidth,
padding: '0 20px',
margin: '0 auto',
'@media (max-width: 700px)': {
padding: 0,
margin: 0
}
}}
>
{target.type === 'directory' ? (
<DirectoryViewer path={target.path} details={target.details} />
) : target.type === 'file' ? (
<FileViewer path={target.path} details={target.details} />
) : null}
</div>
</div>
<footer
css={{
marginTop: '5rem',
background: 'black',
color: '#aaa'
}}
>
<div
css={{
maxWidth: maxContentWidth,
padding: '10px 20px',
margin: '0 auto',
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between'
}}
>
<p>&copy; {new Date().getFullYear()} UNPKG</p>
<p css={{ fontSize: '1.5rem' }}>
<a
title="Twitter"
href="https://twitter.com/unpkg"
css={{
color: '#aaa',
display: 'inline-block',
':hover': { color: 'white' }
}}
>
<TwitterIcon />
</a>
<a
title="GitHub"
href="https://github.com/mjackson/unpkg"
css={{
color: '#aaa',
display: 'inline-block',
marginLeft: '1rem',
':hover': { color: 'white' }
}}
>
<GitHubIcon />
</a>
</p>
</div>
</footer>
</Fragment>
</PackageInfoProvider>
);
}
if (process.env.NODE_ENV !== 'production') {
const targetType = PropTypes.shape({
path: PropTypes.string.isRequired,
type: PropTypes.oneOf(['directory', 'file']).isRequired,
details: PropTypes.object.isRequired
});
App.propTypes = {
packageName: PropTypes.string.isRequired,
packageVersion: PropTypes.string.isRequired,
availableVersions: PropTypes.arrayOf(PropTypes.string),
filename: PropTypes.string.isRequired,
target: targetType.isRequired
};
}

View File

@ -0,0 +1,182 @@
/** @jsx jsx */
import { jsx } from '@emotion/core';
import PropTypes from 'prop-types';
import VisuallyHidden from '@reach/visually-hidden';
import sortBy from 'sort-by';
import { formatBytes } from '../utils/format.js';
import { DirectoryIcon, CodeFileIcon } from './Icons.js';
const linkStyle = {
color: '#0076ff',
textDecoration: 'none',
':hover': {
textDecoration: 'underline'
}
};
const tableCellStyle = {
paddingTop: 6,
paddingRight: 3,
paddingBottom: 6,
paddingLeft: 3,
borderTop: '1px solid #eaecef'
};
const iconCellStyle = {
...tableCellStyle,
color: '#424242',
width: 17,
paddingRight: 2,
paddingLeft: 10,
'@media (max-width: 700px)': {
paddingLeft: 20
}
};
const typeCellStyle = {
...tableCellStyle,
textAlign: 'right',
paddingRight: 10,
'@media (max-width: 700px)': {
paddingRight: 20
}
};
function getRelName(path, base) {
return path.substr(base.length > 1 ? base.length + 1 : 1);
}
export default function DirectoryViewer({ path, details: entries }) {
const rows = [];
if (path !== '/') {
rows.push(
<tr key="..">
<td css={iconCellStyle} />
<td css={tableCellStyle}>
<a title="Parent directory" href="../" css={linkStyle}>
..
</a>
</td>
<td css={tableCellStyle}></td>
<td css={typeCellStyle}></td>
</tr>
);
}
const { subdirs, files } = Object.keys(entries).reduce(
(memo, key) => {
const { subdirs, files } = memo;
const entry = entries[key];
if (entry.type === 'directory') {
subdirs.push(entry);
} else if (entry.type === 'file') {
files.push(entry);
}
return memo;
},
{ subdirs: [], files: [] }
);
subdirs.sort(sortBy('path')).forEach(({ path: dirname }) => {
const relName = getRelName(dirname, path);
const href = relName + '/';
rows.push(
<tr key={relName}>
<td css={iconCellStyle}>
<DirectoryIcon />
</td>
<td css={tableCellStyle}>
<a title={relName} href={href} css={linkStyle}>
{relName}
</a>
</td>
<td css={tableCellStyle}>-</td>
<td css={typeCellStyle}>-</td>
</tr>
);
});
files
.sort(sortBy('path'))
.forEach(({ path: filename, size, contentType }) => {
const relName = getRelName(filename, path);
const href = relName;
rows.push(
<tr key={relName}>
<td css={iconCellStyle}>
<CodeFileIcon />
</td>
<td css={tableCellStyle}>
<a title={relName} href={href} css={linkStyle}>
{relName}
</a>
</td>
<td css={tableCellStyle}>{formatBytes(size)}</td>
<td css={typeCellStyle}>{contentType}</td>
</tr>
);
});
return (
<div
css={{
border: '1px solid #dfe2e5',
borderRadius: 3,
borderTopWidth: 0,
'@media (max-width: 700px)': {
borderRightWidth: 0,
borderLeftWidth: 0
}
}}
>
<table
css={{
width: '100%',
borderCollapse: 'collapse',
borderRadius: 2,
background: '#fff'
}}
>
<thead>
<tr>
<th>
<VisuallyHidden>Icon</VisuallyHidden>
</th>
<th>
<VisuallyHidden>Name</VisuallyHidden>
</th>
<th>
<VisuallyHidden>Size</VisuallyHidden>
</th>
<th>
<VisuallyHidden>Content Type</VisuallyHidden>
</th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
</div>
);
}
if (process.env.NODE_ENV !== 'production') {
DirectoryViewer.propTypes = {
path: PropTypes.string.isRequired,
details: PropTypes.objectOf(
PropTypes.shape({
path: PropTypes.string.isRequired,
type: PropTypes.oneOf(['directory', 'file']).isRequired,
contentType: PropTypes.string, // file only
integrity: PropTypes.string, // file only
size: PropTypes.number // file only
})
).isRequired
};
}

View File

@ -0,0 +1,212 @@
/** @jsx jsx */
import { jsx } from '@emotion/core';
import PropTypes from 'prop-types';
import { formatBytes } from '../utils/format.js';
import { createHTML } from '../utils/markup.js';
import { usePackageInfo } from './PackageInfo.js';
function getBasename(path) {
const segments = path.split('/');
return segments[segments.length - 1];
}
function ImageViewer({ path, uri }) {
return (
<div css={{ padding: 20, textAlign: 'center' }}>
<img title={getBasename(path)} src={uri} />
</div>
);
}
function CodeListing({ highlights }) {
const lines = highlights.slice(0);
const hasTrailingNewline = lines.length && lines[lines.length - 1] === '';
if (hasTrailingNewline) {
lines.pop();
}
return (
<div
className="code-listing"
css={{
overflowX: 'auto',
overflowY: 'hidden',
paddingTop: 5,
paddingBottom: 5
}}
>
<table
css={{
border: 'none',
borderCollapse: 'collapse',
borderSpacing: 0
}}
>
<tbody>
{lines.map((line, index) => {
const lineNumber = index + 1;
return (
<tr key={index}>
<td
id={`L${lineNumber}`}
css={{
paddingLeft: 10,
paddingRight: 10,
color: 'rgba(27,31,35,.3)',
textAlign: 'right',
verticalAlign: 'top',
width: '1%',
minWidth: 50,
userSelect: 'none'
}}
>
<span>{lineNumber}</span>
</td>
<td
id={`LC${lineNumber}`}
css={{
paddingLeft: 10,
paddingRight: 10,
color: '#24292e',
whiteSpace: 'pre'
}}
>
<code dangerouslySetInnerHTML={createHTML(line)} />
</td>
</tr>
);
})}
{!hasTrailingNewline && (
<tr key="no-newline">
<td
css={{
paddingLeft: 10,
paddingRight: 10,
color: 'rgba(27,31,35,.3)',
textAlign: 'right',
verticalAlign: 'top',
width: '1%',
minWidth: 50,
userSelect: 'none'
}}
>
\
</td>
<td
css={{
paddingLeft: 10,
color: 'rgba(27,31,35,.3)',
userSelect: 'none'
}}
>
No newline at end of file
</td>
</tr>
)}
</tbody>
</table>
</div>
);
}
function BinaryViewer() {
return (
<div css={{ padding: 20 }}>
<p css={{ textAlign: 'center' }}>No preview available.</p>
</div>
);
}
export default function FileViewer({ path, details }) {
const { packageName, packageVersion } = usePackageInfo();
const { highlights, uri, language, size } = details;
const segments = path.split('/');
const filename = segments[segments.length - 1];
return (
<div
css={{
border: '1px solid #dfe2e5',
borderRadius: 3,
'@media (max-width: 700px)': {
borderRightWidth: 0,
borderLeftWidth: 0
}
}}
>
<div
css={{
padding: 10,
background: '#f6f8fa',
color: '#424242',
border: '1px solid #d1d5da',
borderTopLeftRadius: 3,
borderTopRightRadius: 3,
margin: '-1px -1px 0',
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
'@media (max-width: 700px)': {
paddingRight: 20,
paddingLeft: 20
}
}}
>
<span>{formatBytes(size)}</span> <span>{language}</span>{' '}
<a
title={filename}
href={`/${packageName}@${packageVersion}${path}`}
css={{
display: 'inline-block',
textDecoration: 'none',
padding: '2px 8px',
fontWeight: 600,
fontSize: '0.9rem',
color: '#24292e',
backgroundColor: '#eff3f6',
border: '1px solid rgba(27,31,35,.2)',
borderRadius: 3,
':hover': {
backgroundColor: '#e6ebf1',
borderColor: 'rgba(27,31,35,.35)'
},
':active': {
backgroundColor: '#e9ecef',
borderColor: 'rgba(27,31,35,.35)',
boxShadow: 'inset 0 0.15em 0.3em rgba(27,31,35,.15)'
}
}}
>
View Raw
</a>
</div>
{highlights ? (
<CodeListing highlights={highlights} />
) : uri ? (
<ImageViewer path={path} uri={uri} />
) : (
<BinaryViewer />
)}
</div>
);
}
if (process.env.NODE_ENV !== 'production') {
FileViewer.propTypes = {
path: PropTypes.string.isRequired,
details: PropTypes.shape({
contentType: PropTypes.string.isRequired,
highlights: PropTypes.arrayOf(PropTypes.string), // code
uri: PropTypes.string, // images
integrity: PropTypes.string.isRequired,
language: PropTypes.string.isRequired,
size: PropTypes.number.isRequired
}).isRequired
};
}

View File

@ -0,0 +1,24 @@
/** @jsx jsx */
import { jsx } from '@emotion/core';
import { GoFileDirectory, GoFile } from 'react-icons/go';
import { FaTwitter, FaGithub } from 'react-icons/fa';
function createIcon(Type, { css, ...rest }) {
return <Type css={{ ...css, verticalAlign: 'text-bottom' }} {...rest} />;
}
export function DirectoryIcon(props) {
return createIcon(GoFileDirectory, props);
}
export function CodeFileIcon(props) {
return createIcon(GoFile, props);
}
export function TwitterIcon(props) {
return createIcon(FaTwitter, props);
}
export function GitHubIcon(props) {
return createIcon(FaGithub, props);
}

View File

@ -0,0 +1,11 @@
import React, { createContext, useContext } from 'react';
const Context = createContext();
export function PackageInfoProvider({ children, ...rest }) {
return <Context.Provider children={children} value={rest} />;
}
export function usePackageInfo() {
return useContext(Context);
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 307 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 343 B

View File

@ -1,40 +1,45 @@
/** @jsx jsx */
import React from 'react';
import PropTypes from 'prop-types';
import { Global, css, jsx } from '@emotion/core';
import { Fragment, useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import formatBytes from 'pretty-bytes';
import formatDate from 'date-fns/format';
import parseDate from 'date-fns/parse';
import formatNumber from '../utils/formatNumber.js';
import formatPercent from '../utils/formatPercent.js';
import { formatNumber, formatPercent } from '../utils/format.js';
import { fontSans, fontMono } from '../utils/style.js';
import cloudflareLogo from './CloudflareLogo.png';
import angularLogo from './AngularLogo.png';
import googleCloudLogo from './GoogleCloudLogo.png';
import { TwitterIcon, GitHubIcon } from './Icons.js';
import CloudflareLogo from './images/CloudflareLogo.png';
import AngularLogo from './images/AngularLogo.png';
const globalStyles = css`
html {
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
html,
body,
#root {
height: 100%;
margin: 0;
}
body {
font-size: 14px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
Helvetica, Arial, sans-serif;
line-height: 1.7;
padding: 5px 20px;
${fontSans}
font-size: 16px;
line-height: 1.5;
background: white;
color: black;
}
@media (min-width: 800px) {
body {
padding: 40px 20px 120px;
}
}
a:link {
color: blue;
text-decoration: none;
}
a:visited {
color: rebeccapurple;
code {
${fontMono}
}
dd,
@ -42,23 +47,18 @@ const globalStyles = css`
margin-left: 0;
padding-left: 25px;
}
#root {
display: flex;
flex-direction: column;
}
`;
const styles = {
heading: {
margin: '0.8em 0',
textTransform: 'uppercase',
textAlign: 'center',
fontSize: '5em'
},
subheading: {
fontSize: '1.6em'
},
example: {
textAlign: 'center',
backgroundColor: '#eee',
margin: '2em 0',
padding: '5px 0'
const linkStyle = {
color: '#0076ff',
textDecoration: 'none',
':hover': {
textDecoration: 'underline'
}
};
@ -90,59 +90,73 @@ function Stats({ data }) {
);
}
export default class App extends React.Component {
constructor(props) {
super(props);
export default function App() {
const [stats, setStats] = useState(
typeof window === 'object' &&
window.localStorage &&
window.localStorage.savedStats
? JSON.parse(window.localStorage.savedStats)
: null
);
const hasStats = !!(stats && !stats.error);
const stringStats = JSON.stringify(stats);
this.state = { stats: null };
useEffect(() => {
window.localStorage.savedStats = stringStats;
}, [stringStats]);
if (typeof window === 'object' && window.localStorage) {
const savedStats = window.localStorage.savedStats;
if (savedStats) {
this.state.stats = JSON.parse(savedStats);
}
window.onbeforeunload = () => {
window.localStorage.savedStats = JSON.stringify(this.state.stats);
};
}
}
componentDidMount() {
// Refresh latest stats.
useEffect(() => {
fetch('/api/stats?period=last-month')
.then(res => res.json())
.then(stats => this.setState({ stats }));
}
.then(setStats);
}, []);
render() {
const { stats } = this.state;
const hasStats = !!(stats && !stats.error);
return (
<div css={{ maxWidth: 700, margin: '0 auto' }}>
return (
<Fragment>
<div
css={{
maxWidth: 740,
margin: '0 auto',
padding: '0 20px'
}}
>
<Global styles={globalStyles} />
<header>
<h1 css={styles.heading}>unpkg</h1>
<h1
css={{
textTransform: 'uppercase',
textAlign: 'center',
fontSize: '5em'
}}
>
unpkg
</h1>
<p>
unpkg is a fast, global{' '}
<a href="https://en.wikipedia.org/wiki/Content_delivery_network">
content delivery network
</a>{' '}
for everything on <a href="https://www.npmjs.com/">npm</a>. Use it
to quickly and easily load any file from any package using a URL
like:
unpkg is a fast, global content delivery network for everything on{' '}
<a href="https://www.npmjs.com/" css={linkStyle}>
npm
</a>
. Use it to quickly and easily load any file from any package using
a URL like:
</p>
<div css={styles.example}>unpkg.com/:package@:version/:file</div>
<div
css={{
textAlign: 'center',
backgroundColor: '#eee',
margin: '2em 0',
padding: '5px 0'
}}
>
unpkg.com/:package@:version/:file
</div>
{hasStats && <Stats data={stats} />}
</header>
<h3 css={styles.subheading} id="examples">
<h3 css={{ fontSize: '1.6em' }} id="examples">
Examples
</h3>
@ -150,12 +164,20 @@ export default class App extends React.Component {
<ul>
<li>
<a href="/react@16.7.0/umd/react.production.min.js">
<a
title="react.production.min.js"
href="/react@16.7.0/umd/react.production.min.js"
css={linkStyle}
>
unpkg.com/react@16.7.0/umd/react.production.min.js
</a>
</li>
<li>
<a href="/react-dom@16.7.0/umd/react-dom.production.min.js">
<a
title="react-dom.production.min.js"
href="/react-dom@16.7.0/umd/react-dom.production.min.js"
css={linkStyle}
>
unpkg.com/react-dom@16.7.0/umd/react-dom.production.min.js
</a>
</li>
@ -163,20 +185,41 @@ export default class App extends React.Component {
<p>
You may also use a{' '}
<a href="https://docs.npmjs.com/misc/semver">semver range</a> or a{' '}
<a href="https://docs.npmjs.com/cli/dist-tag">tag</a> instead of a
fixed version number, or omit the version/tag entirely to use the{' '}
<code>latest</code> tag.
<a
title="semver"
href="https://docs.npmjs.com/misc/semver"
css={linkStyle}
>
semver range
</a>{' '}
or a{' '}
<a
title="tags"
href="https://docs.npmjs.com/cli/dist-tag"
css={linkStyle}
>
tag
</a>{' '}
instead of a fixed version number, or omit the version/tag entirely to
use the <code>latest</code> tag.
</p>
<ul>
<li>
<a href="/react@^16/umd/react.production.min.js">
<a
title="react.production.min.js"
href="/react@^16/umd/react.production.min.js"
css={linkStyle}
>
unpkg.com/react@^16/umd/react.production.min.js
</a>
</li>
<li>
<a href="/react/umd/react.production.min.js">
<a
title="react.production.min.js"
href="/react/umd/react.production.min.js"
css={linkStyle}
>
unpkg.com/react/umd/react.production.min.js
</a>
</li>
@ -190,10 +233,14 @@ export default class App extends React.Component {
<ul>
<li>
<a href="/jquery">unpkg.com/jquery</a>
<a title="jQuery" href="/jquery" css={linkStyle}>
unpkg.com/jquery
</a>
</li>
<li>
<a href="/three">unpkg.com/three</a>
<a title="Three.js" href="/three" css={linkStyle}>
unpkg.com/three
</a>
</li>
</ul>
@ -204,14 +251,26 @@ export default class App extends React.Component {
<ul>
<li>
<a href="/react/">unpkg.com/react/</a>
<a
title="Index of the react package"
href="/react/"
css={linkStyle}
>
unpkg.com/react/
</a>
</li>
<li>
<a href="/lodash/">unpkg.com/lodash/</a>
<a
title="Index of the react-router package"
href="/react-router/"
css={linkStyle}
>
unpkg.com/react-router/
</a>
</li>
</ul>
<h3 css={styles.subheading} id="query-params">
<h3 css={{ fontSize: '1.6em' }} id="query-params">
Query Parameters
</h3>
@ -229,7 +288,11 @@ export default class App extends React.Component {
</dt>
<dd>
Expands all{' '}
<a href="https://html.spec.whatwg.org/multipage/webappapis.html#resolve-a-module-specifier">
<a
title="bare import specifiers"
href="https://html.spec.whatwg.org/multipage/webappapis.html#resolve-a-module-specifier"
css={linkStyle}
>
&ldquo;bare&rdquo; <code>import</code> specifiers
</a>{' '}
in JavaScript modules to unpkg URLs. This feature is{' '}
@ -237,7 +300,7 @@ export default class App extends React.Component {
</dd>
</dl>
<h3 css={styles.subheading} id="cache-behavior">
<h3 css={{ fontSize: '1.6em' }} id="cache-behavior">
Cache Behavior
</h3>
@ -255,8 +318,14 @@ export default class App extends React.Component {
URLs that do not specify a package version number redirect to one that
does. This is the <code>latest</code> version when no version is
specified, or the <code>maxSatisfying</code> version when a{' '}
<a href="https://github.com/npm/node-semver">semver version</a> is
given. Redirects are cached for 10 minutes at the CDN, 1 minute in
<a
title="semver"
href="https://github.com/npm/node-semver"
css={linkStyle}
>
semver version
</a>{' '}
is given. Redirects are cached for 10 minutes at the CDN, 1 minute in
browsers.
</p>
<p>
@ -267,15 +336,18 @@ export default class App extends React.Component {
latest version and redirect them.
</p>
<h3 css={styles.subheading} id="workflow">
<h3 css={{ fontSize: '1.6em' }} id="workflow">
Workflow
</h3>
<p>
For npm package authors, unpkg relieves the burden of publishing your
code to a CDN in addition to the npm registry. All you need to do is
include your <a href="https://github.com/umdjs/umd">UMD</a> build in
your npm package (not your repo, that&apos;s different!).
include your{' '}
<a title="UMD" href="https://github.com/umdjs/umd" css={linkStyle}>
UMD
</a>{' '}
build in your npm package (not your repo, that&apos;s different!).
</p>
<p>You can do this easily using the following setup:</p>
@ -287,7 +359,11 @@ export default class App extends React.Component {
</li>
<li>
Add the <code>umd</code> directory to your{' '}
<a href="https://docs.npmjs.com/files/package.json#files">
<a
title="package.json files array"
href="https://docs.npmjs.com/files/package.json#files"
css={linkStyle}
>
files array
</a>{' '}
in <code>package.json</code>
@ -303,24 +379,50 @@ export default class App extends React.Component {
a version available on unpkg as well.
</p>
<h3 css={styles.subheading} id="about">
<h3 css={{ fontSize: '1.6em' }} id="about">
About
</h3>
<p>
unpkg is an <a href="https://github.com/unpkg">open source</a> project
built and maintained by{' '}
<a href="https://twitter.com/mjackson">Michael Jackson</a>. unpkg is
not affiliated with or supported by npm, Inc. in any way. Please do
not contact npm for help with unpkg. Instead, please reach out to{' '}
<a href="https://twitter.com/unpkg">@unpkg</a> with any questions or
concerns.
unpkg is an{' '}
<a
title="unpkg on GitHub"
href="https://github.com/unpkg"
css={linkStyle}
>
open source
</a>{' '}
project built and maintained by{' '}
<a
title="mjackson on Twitter"
href="https://twitter.com/mjackson"
css={linkStyle}
>
Michael Jackson
</a>
. unpkg is not affiliated with or supported by npm, Inc. in any way.
Please do not contact npm for help with unpkg. Instead, please reach
out to{' '}
<a
title="unpkg on Twitter"
href="https://twitter.com/unpkg"
css={linkStyle}
>
@unpkg
</a>{' '}
with any questions or concerns.
</p>
<p>
The unpkg CDN is powered by{' '}
<a href="https://www.cloudflare.com">Cloudflare</a>, one of the
world&apos;s largest and fastest cloud network platforms.{' '}
<a
title="Cloudflare"
href="https://www.cloudflare.com"
css={linkStyle}
>
Cloudflare
</a>
, one of the world&apos;s largest and fastest cloud network platforms.{' '}
{hasStats && (
<span>
In the past month, Cloudflare served over{' '}
@ -339,19 +441,27 @@ export default class App extends React.Component {
}}
>
<AboutLogo>
<a href="https://www.cloudflare.com">
<AboutLogoImage src={cloudflareLogo} height="100" />
<a title="Cloudflare" href="https://www.cloudflare.com">
<AboutLogoImage src={CloudflareLogo} height="100" />
</a>
</AboutLogo>
</div>
<p>
The origin servers for unpkg are powered by{' '}
<a href="https://cloud.google.com/">Google Cloud</a> and made possible
by a generous donation from the{' '}
<a href="https://angular.io">Angular web framework</a>, one of the
world&apos;s most popular libraries for building incredible user
experiences on both desktop and mobile.
<a
title="Google Cloud"
href="https://cloud.google.com/"
css={linkStyle}
>
Google Cloud
</a>{' '}
and made possible by a generous donation from the{' '}
<a title="Angular" href="https://angular.io" css={linkStyle}>
Angular web framework
</a>
, one of the world&apos;s most popular libraries for building
incredible user experiences on both desktop and mobile.
</p>
<div
@ -362,37 +472,61 @@ export default class App extends React.Component {
}}
>
<AboutLogo>
<a href="https://angular.io">
<AboutLogoImage src={angularLogo} width="200" />
<a title="Angular" href="https://angular.io">
<AboutLogoImage src={AngularLogo} width="200" />
</a>
</AboutLogo>
</div>
</div>
<footer
<footer
css={{
marginTop: '5rem',
background: 'black',
color: '#aaa'
}}
>
<div
css={{
marginTop: '10em',
color: '#aaa'
maxWidth: 740,
padding: '10px 20px',
margin: '0 auto',
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between'
}}
>
<p css={{ textAlign: 'center' }}>
&copy; {new Date().getFullYear()} unpkg &nbsp;&mdash;&nbsp; powered
by{' '}
<a href="https://cloud.google.com/">
<img
src={googleCloudLogo}
height="32"
css={{
verticalAlign: 'middle',
marginTop: -2,
marginLeft: -10
}}
/>
<p>&copy; {new Date().getFullYear()} UNPKG</p>
<p css={{ fontSize: '1.5rem' }}>
<a
title="Twitter"
href="https://twitter.com/unpkg"
css={{
color: '#aaa',
display: 'inline-block',
':hover': { color: 'white' }
}}
>
<TwitterIcon />
</a>
<a
title="GitHub"
href="https://github.com/mjackson/unpkg"
css={{
color: '#aaa',
display: 'inline-block',
marginLeft: '1rem',
':hover': { color: 'white' }
}}
>
<GitHubIcon />
</a>
</p>
</footer>
</div>
);
}
</div>
</footer>
</Fragment>
);
}
if (process.env.NODE_ENV !== 'production') {

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

View File

@ -0,0 +1,15 @@
/** @jsx jsx */
import { jsx } from '@emotion/core';
import { FaTwitter, FaGithub } from 'react-icons/fa';
function createIcon(Type, { css, ...rest }) {
return <Type css={{ ...css, verticalAlign: 'text-bottom' }} {...rest} />;
}
export function TwitterIcon(props) {
return createIcon(FaTwitter, props);
}
export function GitHubIcon(props) {
return createIcon(FaGithub, props);
}

View File

Before

Width:  |  Height:  |  Size: 2.3 KiB

After

Width:  |  Height:  |  Size: 2.3 KiB

View File

Before

Width:  |  Height:  |  Size: 9.1 KiB

After

Width:  |  Height:  |  Size: 9.1 KiB

View File

@ -0,0 +1,18 @@
import formatBytes from 'pretty-bytes';
export { formatBytes };
export function formatNumber(n) {
const digits = String(n).split('');
const groups = [];
while (digits.length) {
groups.unshift(digits.splice(-3).join(''));
}
return groups.join(',');
}
export function formatPercent(n, decimals = 1) {
return (n * 100).toPrecision(decimals + 2);
}

View File

@ -1,10 +0,0 @@
export default function formatNumber(n) {
const digits = String(n).split('');
const groups = [];
while (digits.length) {
groups.unshift(digits.splice(-3).join(''));
}
return groups.join(',');
}

View File

@ -1,3 +0,0 @@
export default function formatPercent(n, decimals = 1) {
return (n * 100).toPrecision(decimals + 2);
}

View File

@ -0,0 +1,3 @@
export function createHTML(content) {
return { __html: content };
}

View File

@ -0,0 +1,24 @@
export const fontSans = `
font-family: -apple-system,
BlinkMacSystemFont,
"Segoe UI",
"Roboto",
"Oxygen",
"Ubuntu",
"Cantarell",
"Fira Sans",
"Droid Sans",
"Helvetica Neue",
sans-serif;
`;
export const fontMono = `
font-family: Menlo,
Monaco,
Lucida Console,
Liberation Mono,
DejaVu Sans Mono,
Bitstream Vera Sans Mono,
Courier New,
monospace;
`;