1
0
mirror of https://github.com/SomboChea/ui synced 2024-11-24 06:54:27 +07:00

Merge branch 'master' into juanpicado-patch-1

This commit is contained in:
Juan Picado @jotadeveloper 2019-11-23 13:48:11 +01:00 committed by GitHub
commit 45f76bfc2c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
304 changed files with 22339 additions and 5248 deletions

View File

@ -1,5 +1,4 @@
{ {
"presets": [ "presets": [["@verdaccio"]],
["@verdaccio", { "typescript": true }] "plugins": ["emotion"]
]
} }

View File

@ -5,6 +5,9 @@ aliases:
~/ui-theme ~/ui-theme
- &defaults - &defaults
working_directory: *repo_path working_directory: *repo_path
- &node_latest_browser
docker:
- image: circleci/node:latest-browsers
- &node_latest_executor - &node_latest_executor
docker: docker:
- image: circleci/node:latest - image: circleci/node:latest
@ -47,9 +50,12 @@ jobs:
- run: - run:
name: Install dependencies name: Install dependencies
command: yarn install --frozen-lockfile command: yarn install --frozen-lockfile
- run:
name: Lint code
command: yarn lint
- run: - run:
name: Build project name: Build project
command: yarn run build command: yarn build
- save_cache: - save_cache:
key: *yarn_cache_key key: *yarn_cache_key
paths: paths:
@ -61,15 +67,6 @@ jobs:
paths: paths:
- ./* - ./*
lint:
<<: *defaults
<<: *default_executor
steps:
- *restore_repo
- run:
name: Lint code
command: yarn lint
test_bundlesize: test_bundlesize:
<<: *defaults <<: *defaults
<<: *default_executor <<: *default_executor
@ -92,6 +89,15 @@ jobs:
paths: paths:
- coverage - coverage
test_e2e:
<<: *defaults
<<: *node_latest_browser
steps:
- *restore_repo
- run:
name: Test E2E Node (LTS)
command: yarn test:e2e
test_node_lts: test_node_lts:
<<: *defaults <<: *defaults
<<: *node_lts_executor <<: *node_lts_executor
@ -138,10 +144,6 @@ workflows:
jobs: jobs:
- prepare: - prepare:
<<: *ignore_non_dev_branches <<: *ignore_non_dev_branches
- lint:
requires:
- prepare
<<: *ignore_non_dev_branches
- test_bundlesize: - test_bundlesize:
requires: requires:
- prepare - prepare
@ -154,15 +156,19 @@ workflows:
requires: requires:
- prepare - prepare
<<: *ignore_non_dev_branches <<: *ignore_non_dev_branches
- test_e2e:
requires:
- prepare
<<: *ignore_non_dev_branches
- coverage: - coverage:
requires: requires:
- test_node_latest - test_node_latest
<<: *ignore_non_dev_branches <<: *ignore_non_dev_branches
- publish_package: - publish_package:
requires: requires:
- lint
- test_bundlesize - test_bundlesize
- test_node_latest - test_node_latest
- test_node_lts - test_node_lts
- test_e2e
- coverage - coverage
<<: *execute_on_release <<: *execute_on_release

View File

@ -3,6 +3,7 @@ coverage/
static/ static/
.github/ .github/
.circleci/ .circleci/
build
*.md *.md
*.lock *.lock
*.yaml *.yaml
@ -10,3 +11,4 @@ Dockerfile
*.html *.html
*.scss *.scss
*.png *.png
doc

View File

@ -5,7 +5,8 @@
"plugin:jest/recommended", "plugin:jest/recommended",
"plugin:prettier/recommended", "plugin:prettier/recommended",
"plugin:verdaccio/recommended", "plugin:verdaccio/recommended",
"plugin:jsx-a11y/recommended" "plugin:jsx-a11y/recommended",
"plugin:import/typescript"
], ],
"plugins": [ "plugins": [
"react", "react",
@ -14,19 +15,22 @@
"verdaccio", "verdaccio",
"jsx-a11y", "jsx-a11y",
"codeceptjs", "codeceptjs",
"react-hooks" "react-hooks",
"import"
], ],
"settings": { "settings": {
"react": { "react": {
"version": "detect" "version": "detect"
} }
}, },
"parser": "@typescript-eslint/parser",
"parserOptions": { "parserOptions": {
"ecmaFeatures": { "ecmaFeatures": {
"jsx": true "jsx": true
} }
}, },
"rules": { "rules": {
"import/order": ["error", {"newlines-between": "always"}],
"babel/no-invalid-this": 0, "babel/no-invalid-this": 0,
"no-invalid-this": 0, "no-invalid-this": 0,
"no-console": ["error", { "allow": ["warn", "error"] }], "no-console": ["error", { "allow": ["warn", "error"] }],

50
.github/workflows/canary.yml vendored Normal file
View File

@ -0,0 +1,50 @@
name: CI Canary
on: [pull_request]
jobs:
build_test_lint:
name: Node Smoke Test Befor Canary
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions/setup-node@v1
with:
node-version: '12.x'
registry-url: 'https://registry.verdaccio.org'
- name: Install
run: yarn install --frozen-lockfile
- name: Lint
run: yarn lint
- name: Build
run: yarn build
- name: Archive production artifacts
uses: actions/upload-artifact@v1
with:
name: static
path: static
canary:
name: Publish Canary Version of a PR
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Download math result for job 2
uses: actions/download-artifact@v1
with:
name: static
- uses: verdaccio/github-actions/canary@v0.4.0
with:
message: 'Thanks for your PR, the @verdaccio/ui package will be accessible from here for testing purposes:'
is-global: false
package-name: '@verdaccio/ui-theme'
registry: 'https://registry.verdaccio.org'
repo-token: ${{ secrets.GITHUB_TOKEN }}
bot-token: ${{ secrets.VERDACCIO_BOT_TOKEN }}
- uses: actions/setup-node@v1
with:
node-version: '12.x'
registry-url: 'https://registry.verdaccio.org'
- run: npm publish --tag canary
env:
NODE_AUTH_TOKEN: ${{ secrets.VERDACCIO_TOKEN }}
needs: build_test_lint

View File

@ -1,6 +1,6 @@
name: CI name: CI
on: push on: [push, pull_request]
jobs: jobs:
build_test_lint: build_test_lint:
@ -9,7 +9,7 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
node_version: [10, 12] node_version: [12, 13]
os: [ubuntu-latest, windows-latest, macOS-latest] os: [ubuntu-latest, windows-latest, macOS-latest]
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
@ -19,10 +19,10 @@ jobs:
- name: Use Node.js ${{ matrix.node_version }} - name: Use Node.js ${{ matrix.node_version }}
uses: actions/setup-node@v1 uses: actions/setup-node@v1
with: with:
version: ${{ matrix.node_version }} node-version: ${{ matrix.node_version }}
- name: Install - name: Install
run: yarn install --frozen-lockfile run: yarn install --frozen-lockfile
- name: Build
run: yarn build
- name: Lint - name: Lint
run: yarn lint run: yarn lint
- name: Build
run: yarn build

2
.gitignore vendored
View File

@ -2,6 +2,8 @@ npm-debug.log
verdaccio-*.tgz verdaccio-*.tgz
.DS_Store .DS_Store
build/ build/
doc
### ###
node_modules node_modules
package-lock.json package-lock.json

40
.secrets-baseline Normal file
View File

@ -0,0 +1,40 @@
{
"exclude": {
"files": null,
"lines": null
},
"generated_at": "2019-09-29T18:19:50Z",
"plugins_used": [
{
"name": "AWSKeyDetector"
},
{
"name": "ArtifactoryDetector"
},
{
"base64_limit": 4.5,
"name": "Base64HighEntropyString"
},
{
"name": "BasicAuthDetector"
},
{
"hex_limit": 3,
"name": "HexHighEntropyString"
},
{
"name": "KeywordDetector"
},
{
"name": "PrivateKeyDetector"
},
{
"name": "SlackDetector"
},
{
"name": "StripeDetector"
}
],
"results": {},
"version": "0.12.4"
}

View File

@ -5,5 +5,6 @@
"javascriptreact", "javascriptreact",
"typescript", "typescript",
"typescriptreact" "typescriptreact"
] ],
"typescript.tsdk": "node_modules/typescript/lib"
} }

View File

@ -2,6 +2,106 @@
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
### [0.3.6](https://github.com/verdaccio/ui/compare/v0.3.5...v0.3.6) (2019-11-08)
### [0.3.5](https://github.com/verdaccio/ui/compare/v0.3.4...v0.3.5) (2019-11-07)
### Bug Fixes
* adds unit tests for api service ([#235](https://github.com/verdaccio/ui/issues/235)) ([803da1c](https://github.com/verdaccio/ui/commit/803da1c))
* convert Engine component to hooks ([#233](https://github.com/verdaccio/ui/issues/233)) ([5cb47ed](https://github.com/verdaccio/ui/commit/5cb47ed))
* refactor/116 RegistryInfoContent is converted to functional component ([#229](https://github.com/verdaccio/ui/issues/229)) ([b74ca22](https://github.com/verdaccio/ui/commit/b74ca22)), closes [#116](https://github.com/verdaccio/ui/issues/116) [#116](https://github.com/verdaccio/ui/issues/116)
* rest MUI components - Introduced ForwardRef ([#224](https://github.com/verdaccio/ui/issues/224)) ([b56e438](https://github.com/verdaccio/ui/commit/b56e438))
### Features
* added download tarball button at list ([#237](https://github.com/verdaccio/ui/issues/237)) ([bdef686](https://github.com/verdaccio/ui/commit/bdef686))
* update date fns to v2 ([#232](https://github.com/verdaccio/ui/issues/232)) ([a4cdd14](https://github.com/verdaccio/ui/commit/a4cdd14))
### [0.3.4](https://github.com/verdaccio/ui/compare/v0.3.3...v0.3.4) (2019-10-26)
### Bug Fixes
* adds no uplink spec ([#213](https://github.com/verdaccio/ui/issues/213)) ([ade548a](https://github.com/verdaccio/ui/commit/ade548a))
* api typings ([#210](https://github.com/verdaccio/ui/issues/210)) ([5d6ad3d](https://github.com/verdaccio/ui/commit/5d6ad3d))
* PackageList component is converted to functional ([#219](https://github.com/verdaccio/ui/issues/219)) [#116](https://github.com/verdaccio/ui/issues/116) ([ae0222c](https://github.com/verdaccio/ui/commit/ae0222c))
* routes - Replaced class by func. comp ([#159](https://github.com/verdaccio/ui/issues/159)) ([5c06ace](https://github.com/verdaccio/ui/commit/5c06ace))
* version Page - Replaces class by func. ([#171](https://github.com/verdaccio/ui/issues/171)) ([f5c77ff](https://github.com/verdaccio/ui/commit/f5c77ff))
* **162:** added forwardRef Card ([#216](https://github.com/verdaccio/ui/issues/216)) ([2bc49f3](https://github.com/verdaccio/ui/commit/2bc49f3))
* **installlistitem:** changed the wrong icon ([#211](https://github.com/verdaccio/ui/issues/211)) ([4498aad](https://github.com/verdaccio/ui/commit/4498aad))
### [0.3.3](https://github.com/verdaccio/ui/compare/v0.3.2...v0.3.3) (2019-10-16)
### Bug Fixes
* **deps:** remove types from dependencies ([#201](https://github.com/verdaccio/ui/issues/201)) ([48c03fe](https://github.com/verdaccio/ui/commit/48c03fe))
* add new window property to interface definition ([b35baa0](https://github.com/verdaccio/ui/commit/b35baa0))
* added typings for react-autosuggest ([#200](https://github.com/verdaccio/ui/issues/200)) ([cfb29ce](https://github.com/verdaccio/ui/commit/cfb29ce))
* better type inference for MediaQuery ([#180](https://github.com/verdaccio/ui/issues/180)) ([e0e7c07](https://github.com/verdaccio/ui/commit/e0e7c07))
* changes font size for items of the register-info component ([#196](https://github.com/verdaccio/ui/issues/196)) ([6f87be6](https://github.com/verdaccio/ui/commit/6f87be6)), closes [#193](https://github.com/verdaccio/ui/issues/193)
* convert Dist component to hooks ([#156](https://github.com/verdaccio/ui/issues/156)) ([f1f8f8a](https://github.com/verdaccio/ui/commit/f1f8f8a))
* detailContainer Component - Replaced class by func. comp ([#130](https://github.com/verdaccio/ui/issues/130)) ([f84fd79](https://github.com/verdaccio/ui/commit/f84fd79))
* dist-tags attribute [#175](https://github.com/verdaccio/ui/issues/175) ([#178](https://github.com/verdaccio/ui/issues/178)) ([752e2b9](https://github.com/verdaccio/ui/commit/752e2b9))
* fix DependencyBlock props interface ([35d691c](https://github.com/verdaccio/ui/commit/35d691c))
* fixed import ([#176](https://github.com/verdaccio/ui/issues/176)) ([d0d4139](https://github.com/verdaccio/ui/commit/d0d4139))
* fixed imports & func's name ([#182](https://github.com/verdaccio/ui/issues/182)) ([3888736](https://github.com/verdaccio/ui/commit/3888736))
* Header Component - Replaced class by func. comp ([#142](https://github.com/verdaccio/ui/issues/142)) ([d1ce828](https://github.com/verdaccio/ui/commit/d1ce828))
* improve jest mock typings ([852f6ee](https://github.com/verdaccio/ui/commit/852f6ee))
* improved typing ([#174](https://github.com/verdaccio/ui/issues/174)) ([e0642a9](https://github.com/verdaccio/ui/commit/e0642a9))
* incorrect Tooltip import in avatar component ([#160](https://github.com/verdaccio/ui/issues/160)) ([43a9628](https://github.com/verdaccio/ui/commit/43a9628))
* install Component - Replaced class by func. comp ([#152](https://github.com/verdaccio/ui/issues/152)) ([9eb698f](https://github.com/verdaccio/ui/commit/9eb698f))
* introduced forwardRef ([#163](https://github.com/verdaccio/ui/issues/163)) ([626bcce](https://github.com/verdaccio/ui/commit/626bcce))
* introduced forwardRef ([#164](https://github.com/verdaccio/ui/issues/164)) ([909a8d9](https://github.com/verdaccio/ui/commit/909a8d9))
* introduced ForwardRef ([#177](https://github.com/verdaccio/ui/issues/177)) ([af8ed8b](https://github.com/verdaccio/ui/commit/af8ed8b))
* introduced forwardRef ([#181](https://github.com/verdaccio/ui/issues/181)) ([0c4fb7d](https://github.com/verdaccio/ui/commit/0c4fb7d))
* introduced forwardRef ([#185](https://github.com/verdaccio/ui/issues/185)) ([7548c89](https://github.com/verdaccio/ui/commit/7548c89))
* introduced SvgIcon ([#184](https://github.com/verdaccio/ui/issues/184)) ([8b86ded](https://github.com/verdaccio/ui/commit/8b86ded))
* linter error fixed ([#143](https://github.com/verdaccio/ui/issues/143)) ([74576bd](https://github.com/verdaccio/ui/commit/74576bd))
* listItem Component - Introduced ForwardRef ([#183](https://github.com/verdaccio/ui/issues/183)) ([82d7107](https://github.com/verdaccio/ui/commit/82d7107))
* lock file was corrupted ([7bd9eb7](https://github.com/verdaccio/ui/commit/7bd9eb7))
* media query ts ignore ([6f52838](https://github.com/verdaccio/ui/commit/6f52838))
* remove ts ignore from some components ([b1804d7](https://github.com/verdaccio/ui/commit/b1804d7))
* remove unnecessary ts ignore ([7a8b158](https://github.com/verdaccio/ui/commit/7a8b158))
* remove unnecessary ts ignore ([32f4389](https://github.com/verdaccio/ui/commit/32f4389))
* removed tsignore for AppContext ([#188](https://github.com/verdaccio/ui/issues/188)) ([d2c1130](https://github.com/verdaccio/ui/commit/d2c1130))
* typography Component - Introduced ForwardRef ([#179](https://github.com/verdaccio/ui/issues/179)) ([a8deeb9](https://github.com/verdaccio/ui/commit/a8deeb9))
* **api:** remove unnecessary ts ignore ([a8eb1f3](https://github.com/verdaccio/ui/commit/a8eb1f3))
* **App:** ts ignore ([f6eb747](https://github.com/verdaccio/ui/commit/f6eb747))
* **Developers:** remove compilation warnings ([f4da5e6](https://github.com/verdaccio/ui/commit/f4da5e6))
* **Footer:** remove unnecessary ts ignore ([1fb0bf9](https://github.com/verdaccio/ui/commit/1fb0bf9))
* some warnings in console ([#155](https://github.com/verdaccio/ui/issues/155)) ([583ddd5](https://github.com/verdaccio/ui/commit/583ddd5))
* spinner typings ([3166673](https://github.com/verdaccio/ui/commit/3166673))
* tarball download not working on Firefox and Edge ([#144](https://github.com/verdaccio/ui/issues/144)) ([f8e3013](https://github.com/verdaccio/ui/commit/f8e3013))
* warning about modules with names differing in casing ([#148](https://github.com/verdaccio/ui/issues/148)) ([e147290](https://github.com/verdaccio/ui/commit/e147290))
### Features
* new not found component ([#170](https://github.com/verdaccio/ui/issues/170)) ([fdbdb63](https://github.com/verdaccio/ui/commit/fdbdb63))
* **eslint-config:** add order rule in import ([ae73772](https://github.com/verdaccio/ui/commit/ae73772))
* upgraded typescript to 3.6.3 ([#145](https://github.com/verdaccio/ui/issues/145)) ([f8a1f2c](https://github.com/verdaccio/ui/commit/f8a1f2c))
* use React.lazy for loading components ([#158](https://github.com/verdaccio/ui/issues/158)) ([a365ec5](https://github.com/verdaccio/ui/commit/a365ec5))
* version Component - Replaced classes by func. comp ([#129](https://github.com/verdaccio/ui/issues/129)) ([1d705da](https://github.com/verdaccio/ui/commit/1d705da))
### [0.3.2](https://github.com/verdaccio/ui/compare/v0.3.1...v0.3.2) (2019-09-30)
### Bug Fixes
* sidebar view on small screens ([#136](https://github.com/verdaccio/ui/issues/136)) ([91d818c](https://github.com/verdaccio/ui/commit/91d818c))
### [0.3.1](https://github.com/verdaccio/ui/compare/v0.3.0...v0.3.1) (2019-09-29)
### Bug Fixes
* **ui:** fix the hover effect on the packageItem's author area ([#137](https://github.com/verdaccio/ui/issues/137)) ([2e50981](https://github.com/verdaccio/ui/commit/2e50981))
* correctly load font files - closes [#128](https://github.com/verdaccio/ui/issues/128) ([#134](https://github.com/verdaccio/ui/issues/134)) ([f61913c](https://github.com/verdaccio/ui/commit/f61913c))
## [0.3.0](https://github.com/verdaccio/ui/compare/v0.2.4...v0.3.0) (2019-09-01) ## [0.3.0](https://github.com/verdaccio/ui/compare/v0.2.4...v0.3.0) (2019-09-01)

View File

@ -26,21 +26,39 @@ We use `>=yarn@1.13.0`, keep on mind we use lock file.
For development run the following command, it will execute `webpack` and `verdaccio` to For development run the following command, it will execute `webpack` and `verdaccio` to
``` ```bash
yarn dev yarn dev
``` ```
The configuration file is located on `tools/_config.yaml`. The configuration file is located on `tools/_config.yaml`.
Run linting tooling and test to check your code is clean before commit. Run linting tooling and test to check your code is clean before commit.
``` > ⚠️ The development mode just emulate interaction of the UI development with a real verdaccio server, but it is not the real integration. UI is just a theme plugin dependency in the [Verdaccio project](https://github.com/verdaccio/verdaccio).
### Before commit
Don't forget run the following commands before commit and push your code, it will save you time.
```bash
yarn lint && yarn test yarn lint && yarn test
``` ```
#### Commits
Remember we follow the [the Conventional Commits specification](https://www.conventionalcommits.org/en/v1.0.0-beta.4/). Remember we follow the [the Conventional Commits specification](https://www.conventionalcommits.org/en/v1.0.0-beta.4/).
🤓 Feel free to participate in code reviews, let us know if you want to participate in this plugin. 🤓 Feel free to participate in code reviews, let us know if you want to participate in this plugin.
### End to End Testing
Additionally, we recommend run E2E testing before push and verify your changes do not break anything. These command will run in our CI anyway.
```bash
yarn build && yarn test:e2e
```
> `yarn build` will build with webpack the production files.
## Open Collective Sponsors ## Open Collective Sponsors
@ -65,7 +83,7 @@ Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com
## Contributors ## Contributors
This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)]. This project exists thanks to all the people who contribute.
[![contrubitors](https://opencollective.com/verdaccio/contributors.svg?width=890&button=true)](../../graphs/contributors) [![contrubitors](https://opencollective.com/verdaccio/contributors.svg?width=890&button=true)](../../graphs/contributors)

29
codecov.yml Normal file
View File

@ -0,0 +1,29 @@
codecov:
require_ci_to_pass: yes
coverage:
precision: 2
round: down
range: "80...85"
status:
project:
default:
target: auto
threshold: 1%
base: auto
patch: no
changes: no
parsers:
gcov:
branch_detection:
conditional: yes
loop: yes
method: no
macro: no
comment:
layout: "diff,flags,tree"
behavior: default
require_changes: no

View File

@ -11,7 +11,15 @@ module.exports = {
rootDir: '..', rootDir: '..',
setupFiles: ['<rootDir>/jest/setup.ts'], setupFiles: ['<rootDir>/jest/setup.ts'],
transformIgnorePatterns: ['<rootDir>/node_modules/(?!react-syntax-highlighter)'], transformIgnorePatterns: ['<rootDir>/node_modules/(?!react-syntax-highlighter)'],
modulePathIgnorePatterns: ['<rootDir>/coverage', '<rootDir>/scripts', '<rootDir>/.circleci', '<rootDir>/tools', '<rootDir>/build', '<rootDir>/.vscode/'], modulePathIgnorePatterns: [
'<rootDir>/coverage',
'<rootDir>/scripts',
'<rootDir>/.circleci',
'<rootDir>/tools',
'<rootDir>/build',
'<rootDir>/.vscode/',
'<rootDir>/test/e2e/',
],
snapshotSerializers: ['enzyme-to-json/serializer', 'jest-emotion'], snapshotSerializers: ['enzyme-to-json/serializer', 'jest-emotion'],
moduleNameMapper: { moduleNameMapper: {
'\\.(s?css)$': '<rootDir>/node_modules/identity-obj-proxy', '\\.(s?css)$': '<rootDir>/node_modules/identity-obj-proxy',

View File

@ -15,6 +15,8 @@ global.__APP_VERSION__ = '1.0.0';
// @ts-ignore : Property '__VERDACCIO_BASENAME_UI_OPTIONS' does not exist on type 'Global'. // @ts-ignore : Property '__VERDACCIO_BASENAME_UI_OPTIONS' does not exist on type 'Global'.
global.__VERDACCIO_BASENAME_UI_OPTIONS = {}; global.__VERDACCIO_BASENAME_UI_OPTIONS = {};
global.VERDACCIO_API_URL = 'https://verdaccio.tld';
const customGlobal: GlobalWithFetchMock = global as GlobalWithFetchMock; const customGlobal: GlobalWithFetchMock = global as GlobalWithFetchMock;
customGlobal.fetch = require('jest-fetch-mock'); customGlobal.fetch = require('jest-fetch-mock');
customGlobal.fetchMock = customGlobal.fetch; customGlobal.fetchMock = customGlobal.fetch;

View File

@ -3,7 +3,7 @@
*/ */
import { Base64 } from 'js-base64'; import { Base64 } from 'js-base64';
import addHours from 'date-fns/add_hours'; import addHours from 'date-fns/addHours';
export function generateTokenWithTimeRange(limit = 0) { export function generateTokenWithTimeRange(limit = 0) {
const payload = { const payload = {
@ -15,6 +15,11 @@ export function generateTokenWithTimeRange(limit = 0) {
export function generateTokenWithExpirationAsString() { export function generateTokenWithExpirationAsString() {
const payload = { username: 'verdaccio', exp: 'I am not a number' }; const payload = { username: 'verdaccio', exp: 'I am not a number' };
return `xxxxxx.${Base64.encode(JSON.stringify(payload))}.xxxxxx`;
}
export function generateInvalidToken() {
const payload = `invalidtoken`;
return `xxxxxx.${Base64.encode(payload)}.xxxxxx`; return `xxxxxx.${Base64.encode(payload)}.xxxxxx`;
} }

View File

@ -1,64 +1,77 @@
{ {
"name": "@verdaccio/ui-theme", "name": "@verdaccio/ui-theme",
"version": "0.3.0", "version": "0.3.6",
"description": "Verdaccio User Interface", "description": "Verdaccio User Interface",
"author": { "author": {
"name": "Verdaccio Core Team" "name": "Verdaccio Core Team",
"email": "verdaccio.npm@gmail.com"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git://github.com/verdaccio/ui" "url": "git://github.com/verdaccio/ui"
}, },
"homepage": "https://verdaccio.org",
"main": "index.js", "main": "index.js",
"devDependencies": { "devDependencies": {
"@commitlint/cli": "8.1.0", "@commitlint/cli": "8.2.0",
"@commitlint/config-conventional": "8.1.0", "@commitlint/config-conventional": "8.2.0",
"@material-ui/core": "4.3.3", "@emotion/core": "10.0.22",
"@material-ui/icons": "4.2.1", "@emotion/styled": "10.0.23",
"@material-ui/styles": "4.3.3", "@material-ui/core": "4.6.1",
"@octokit/rest": "16.28.7", "@material-ui/icons": "4.5.1",
"@testing-library/react": "9.1.3", "@octokit/rest": "16.35.0",
"@testing-library/react": "9.3.2",
"@types/autosuggest-highlight": "3.1.0",
"@types/enzyme": "3.10.3", "@types/enzyme": "3.10.3",
"@types/jest": "24.0.18", "@types/jest": "24.0.23",
"@types/lodash": "4.14.138", "@types/js-base64": "2.3.1",
"@types/node": "12.7.3", "@types/lodash": "4.14.149",
"@types/react": "16.9.2", "@types/node": "12.12.11",
"@types/react-dom": "16.9.0", "@types/react": "16.9.11",
"@types/react-router-dom": "4.3.5", "@types/react-autosuggest": "9.3.13",
"@types/validator": "10.11.3", "@types/react-dom": "16.9.4",
"@verdaccio/babel-preset": "2.0.0", "@types/react-router-dom": "5.1.2",
"@verdaccio/eslint-config": "2.0.0", "@types/request": "2.48.3",
"@verdaccio/types": "8.0.0", "@types/validator": "12.0.0",
"@types/webpack-env": "1.14.1",
"@typescript-eslint/parser": "2.8.0",
"@verdaccio/babel-preset": "8.2.0",
"@verdaccio/commons-api": "8.3.0",
"@verdaccio/eslint-config": "8.2.0",
"@verdaccio/types": "8.3.0",
"autosuggest-highlight": "3.1.1", "autosuggest-highlight": "3.1.1",
"babel-loader": "8.0.6", "babel-loader": "8.0.6",
"bundlesize": "0.18.0", "bundlesize": "0.18.0",
"codeceptjs": "2.2.1", "codeceptjs": "2.3.5",
"codecov": "3.5.0", "codecov": "3.6.1",
"concurrently": "4.1.2", "concurrently": "5.0.0",
"cross-env": "5.2.0", "cross-env": "6.0.3",
"css-loader": "3.2.0", "css-loader": "3.2.0",
"date-fns": "1.30.1", "date-fns": "2.8.1",
"emotion": "9.2.12", "detect-secrets": "1.0.5",
"emotion": "10.0.23",
"emotion-theming": "10.0.19",
"enzyme": "3.10.0", "enzyme": "3.10.0",
"enzyme-adapter-react-16": "1.14.0", "enzyme-adapter-react-16": "1.15.1",
"enzyme-to-json": "3.4.0", "enzyme-to-json": "3.4.3",
"eslint": "5.16.0", "eslint": "6.6.0",
"eslint-plugin-codeceptjs": "1.1.0", "eslint-plugin-codeceptjs": "1.2.0",
"eslint-plugin-import": "2.18.2",
"eslint-plugin-jsx-a11y": "6.2.3", "eslint-plugin-jsx-a11y": "6.2.3",
"eslint-plugin-prettier": "3.1.0", "eslint-plugin-prettier": "3.1.1",
"eslint-plugin-react": "7.14.3", "eslint-plugin-react": "7.16.0",
"eslint-plugin-react-hooks": "2.0.1", "eslint-plugin-react-hooks": "2.3.0",
"eslint-plugin-verdaccio": "2.0.0", "eslint-plugin-verdaccio": "8.2.0",
"file-loader": "4.2.0", "file-loader": "4.3.0",
"friendly-errors-webpack-plugin": "1.7.0", "friendly-errors-webpack-plugin": "1.7.0",
"get-stdin": "6.0.0", "get-stdin": "7.0.0",
"github-markdown-css": "3.0.1", "github-markdown-css": "3.0.1",
"html-webpack-plugin": "3.2.0", "html-webpack-plugin": "3.2.0",
"husky": "3.0.4", "husky": "3.1.0",
"identity-obj-proxy": "3.0.0", "identity-obj-proxy": "3.0.0",
"in-publish": "2.0.0", "in-publish": "2.0.0",
"jest": "24.9.0", "jest": "24.9.0",
"jest-emotion": "10.0.14", "jest-emotion": "10.0.17",
"jest-environment-jsdom": "24.9.0", "jest-environment-jsdom": "24.9.0",
"jest-environment-jsdom-global": "1.2.0", "jest-environment-jsdom-global": "1.2.0",
"jest-environment-node": "24.9.0", "jest-environment-node": "24.9.0",
@ -67,45 +80,47 @@
"js-yaml": "3.13.1", "js-yaml": "3.13.1",
"lint-staged": "8.2.1", "lint-staged": "8.2.1",
"localstorage-memory": "1.0.3", "localstorage-memory": "1.0.3",
"lockfile-lint": "2.2.0",
"lodash": "^4.17.15",
"mini-css-extract-plugin": "0.8.0", "mini-css-extract-plugin": "0.8.0",
"node-mocks-http": "1.7.6", "node-mocks-http": "1.8.0",
"normalize.css": "8.0.1", "normalize.css": "8.0.1",
"optimize-css-assets-webpack-plugin": "5.0.3", "optimize-css-assets-webpack-plugin": "5.0.3",
"ora": "3.4.0", "ora": "4.0.3",
"prettier": "1.18.2", "prettier": "1.19.1",
"prop-types": "15.7.2", "prop-types": "15.7.2",
"puppeteer": "1.17.0", "puppeteer": "2.0.0",
"react": "16.9.0", "react": "16.12.0",
"react-autosuggest": "9.4.3", "react-autosuggest": "9.4.3",
"react-dom": "16.9.0", "react-dom": "16.12.0",
"react-emotion": "9.2.12", "react-hot-loader": "4.12.18",
"react-hot-loader": "4.12.11", "react-router-dom": "5.1.2",
"react-router": "5.0.1", "request": "2.88.0",
"react-router-dom": "5.0.1", "resolve-url-loader": "3.1.1",
"resolve-url-loader": "3.1.0", "rimraf": "3.0.0",
"rimraf": "2.6.3",
"source-map-loader": "0.2.4", "source-map-loader": "0.2.4",
"standard-version": "7.0.0", "standard-version": "7.0.1",
"style-loader": "1.0.0", "style-loader": "1.0.0",
"stylelint": "10.1.0", "stylelint": "12.0.0",
"stylelint-config-recommended": "2.2.0", "stylelint-config-recommended": "3.0.0",
"stylelint-config-styled-components": "0.1.1", "stylelint-config-styled-components": "0.1.1",
"stylelint-processor-styled-components": "1.8.0", "stylelint-processor-styled-components": "1.8.0",
"stylelint-webpack-plugin": "0.10.5", "stylelint-webpack-plugin": "1.1.0",
"supertest": "4.0.2", "supertest": "4.0.2",
"typeface-roboto": "0.0.75", "typeface-roboto": "0.0.75",
"typescript": "3.5.3", "typescript": "3.7.2",
"uglifyjs-webpack-plugin": "2.2.0", "uglifyjs-webpack-plugin": "2.2.0",
"url-loader": "2.1.0", "url-loader": "2.3.0",
"validator": "11.1.0", "validator": "12.1.0",
"verdaccio": "4.2.2", "verdaccio": "4.3.5",
"verdaccio-auth-memory": "8.0.0", "verdaccio-auth-memory": "8.3.0",
"verdaccio-memory": "8.0.0", "verdaccio-memory": "8.3.0",
"webpack": "4.39.3", "wait-on": "3.3.0",
"webpack-bundle-analyzer": "3.4.1", "webpack": "4.41.2",
"webpack-bundle-size-analyzer": "3.0.0", "webpack-bundle-analyzer": "3.6.0",
"webpack-cli": "3.3.7", "webpack-bundle-size-analyzer": "3.1.0",
"webpack-dev-server": "3.8.0", "webpack-cli": "3.3.10",
"webpack-dev-server": "3.9.0",
"webpack-merge": "4.2.2", "webpack-merge": "4.2.2",
"whatwg-fetch": "3.0.0", "whatwg-fetch": "3.0.0",
"xss": "1.0.6" "xss": "1.0.6"
@ -142,20 +157,22 @@
} }
], ],
"scripts": { "scripts": {
"type-check": "tsc --noEmit", "type-check": "tsc --noEmit --pretty",
"type-check:watch": "npm run type-check -- --watch", "type-check:watch": "npm run type-check -- --watch",
"type-check-strict:watch": "tsc --project ./tsconfig.strict.json --noEmit --pretty --watch",
"release": "standard-version -a", "release": "standard-version -a",
"test:clean": "npx jest --clearCache", "test:clean": "npx jest --clearCache",
"test:acceptance": "codeceptjs run --steps", "test:acceptance": "codeceptjs run --steps",
"test:acceptance:server": "concurrently --kill-others \"npm run verdaccio:server\" \"npm run test:acceptance\"", "test:acceptance:server": "concurrently --kill-others \"npm run verdaccio:server\" \"npm run test:acceptance\"",
"test:e2e": "cross-env BABEL_ENV=test jest --config ./test/jest.config.e2e.js",
"test": "cross-env NODE_ENV=test BABEL_ENV=test TZ=UTC jest --config ./jest/jest.config.js --maxWorkers 2 --passWithNoTests", "test": "cross-env NODE_ENV=test BABEL_ENV=test TZ=UTC jest --config ./jest/jest.config.js --maxWorkers 2 --passWithNoTests",
"test:size": "bundlesize", "test:size": "bundlesize",
"lint": "npm run lint:js && npm run lint:css", "lint": "npm run lint:js && npm run lint:css && npm run lint:lockfile",
"lint:js": "npm run type-check && eslint . --ext .js,.ts,.tsx", "lint:js": "npm run type-check && eslint . --ext .js,.ts,.tsx",
"lint:css": "stylelint \"src/**/styles.ts\"", "lint:css": "stylelint \"src/**/styles.ts\"",
"lint:lockfile": "lockfile-lint --path yarn.lock --type yarn --validate-https --allowed-hosts verdaccio npm yarn",
"coverage:publish": "codecov", "coverage:publish": "codecov",
"pre:webpack": "rimraf static/*", "pre:webpack": "rimraf static/*",
"prepublish": "in-publish && npm run build || not-in-publish",
"dev:web": "cross-env BABEL_ENV=ui babel-node tools/dev.server.js", "dev:web": "cross-env BABEL_ENV=ui babel-node tools/dev.server.js",
"verdaccio:server": "node tools/verdaccio.js", "verdaccio:server": "node tools/verdaccio.js",
"build": "npm run pre:webpack && cross-env BABEL_ENV=ui webpack --config tools/webpack.prod.config.babel.js", "build": "npm run pre:webpack && cross-env BABEL_ENV=ui webpack --config tools/webpack.prod.config.babel.js",
@ -177,10 +194,11 @@
"relative": true, "relative": true,
"linters": { "linters": {
"*.{js,tsx,ts}": [ "*.{js,tsx,ts}": [
"eslint", "eslint . --ext .js,.ts,.tsx",
"prettier --write" "prettier --write"
], ],
"*": [ "*": [
"detect-secrets-launcher --baseline .secrets-baseline",
"git add" "git add"
] ]
}, },
@ -198,5 +216,6 @@
"type": "opencollective", "type": "opencollective",
"url": "https://opencollective.com/verdaccio", "url": "https://opencollective.com/verdaccio",
"logo": "https://opencollective.com/verdaccio/logo.txt" "logo": "https://opencollective.com/verdaccio/logo.txt"
} },
"dependencies": {}
} }

View File

@ -1,26 +1,29 @@
import React from 'react'; import React from 'react';
import { mount } from 'enzyme'; import { ReactWrapper } from 'enzyme';
import storage from '../utils/storage';
import App from './App';
import { mount } from '../utils/test-enzyme';
import storage from '../utils/storage';
import { generateTokenWithTimeRange } from '../../jest/unit/components/__mocks__/token'; import { generateTokenWithTimeRange } from '../../jest/unit/components/__mocks__/token';
import App from './App';
import { AppProps } from './AppContext';
jest.mock('../utils/storage', () => { jest.mock('../utils/storage', () => {
class LocalStorageMock { class LocalStorageMock {
private store: object; private store: Record<string, string>;
public constructor() { public constructor() {
this.store = {}; this.store = {};
} }
public clear(): void { public clear(): void {
this.store = {}; this.store = {};
} }
public getItem(key): unknown { public getItem(key: string): unknown {
return this.store[key] || null; return this.store[key] || null;
} }
public setItem(key, value): void { public setItem(key: string, value: string): void {
this.store[key] = value.toString(); this.store[key] = value.toString();
} }
public removeItem(key): void { public removeItem(key: string): void {
delete this.store[key]; delete this.store[key];
} }
} }
@ -32,7 +35,7 @@ jest.mock('../utils/api', () => ({
})); }));
describe('App', () => { describe('App', () => {
let wrapper; let wrapper: ReactWrapper<{}, AppProps, App>;
beforeEach(() => { beforeEach(() => {
wrapper = mount(<App />); wrapper = mount(<App />);

View File

@ -3,42 +3,21 @@ import isNil from 'lodash/isNil';
import storage from '../utils/storage'; import storage from '../utils/storage';
import { makeLogin, isTokenExpire } from '../utils/login'; import { makeLogin, isTokenExpire } from '../utils/login';
import Loading from '../components/Loading'; import Loading from '../components/Loading';
import LoginModal from '../components/Login'; import LoginModal from '../components/Login';
import Header from '../components/Header'; import Header from '../components/Header';
import { Container, Content } from '../components/Layout'; import { Container, Content } from '../components/Layout';
import RouterApp from '../router';
import API from '../utils/api'; import API from '../utils/api';
import '../styles/typeface-roboto.css';
import '../utils/styles/global';
import 'normalize.css';
import Footer from '../components/Footer'; import Footer from '../components/Footer';
import { FormError } from 'src/components/Login/Login';
export const AppContext = React.createContext<{}>({}); import AppRoute from './AppRoute';
export const AppContextProvider = AppContext.Provider; import { AppProps, AppContextProvider } from './AppContext';
export const AppContextConsumer = AppContext.Consumer;
export interface AppStateInterface { export default class App extends Component<{}, AppProps> {
error?: FormError; public state: AppProps = {
logoUrl: string;
user: {
username?: string;
};
scope: string;
showLoginModal: boolean;
isUserLoggedIn: boolean;
packages: [];
isLoading: boolean;
}
export default class App extends Component<{}, AppStateInterface> {
public state: AppStateInterface = {
// @ts-ignore
logoUrl: window.VERDACCIO_LOGO, logoUrl: window.VERDACCIO_LOGO,
user: {}, user: {},
// @ts-ignore scope: window.VERDACCIO_SCOPE || '',
scope: window.VERDACCIO_SCOPE ? `${window.VERDACCIO_SCOPE}:` : '',
showLoginModal: false, showLoginModal: false,
isUserLoggedIn: false, isUserLoggedIn: false,
packages: [], packages: [],
@ -51,7 +30,7 @@ export default class App extends Component<{}, AppStateInterface> {
} }
// eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-unused-vars
public componentDidUpdate(_, prevState): void { public componentDidUpdate(_: AppProps, prevState: AppProps): void {
const { isUserLoggedIn } = this.state; const { isUserLoggedIn } = this.state;
if (prevState.isUserLoggedIn !== isUserLoggedIn) { if (prevState.isUserLoggedIn !== isUserLoggedIn) {
this.loadOnHandler(); this.loadOnHandler();
@ -64,7 +43,6 @@ export default class App extends Component<{}, AppStateInterface> {
const context = { isUserLoggedIn, packages, logoUrl, user, scope }; const context = { isUserLoggedIn, packages, logoUrl, user, scope };
return ( return (
// @ts-ignore
<Container isLoading={isLoading}> <Container isLoading={isLoading}>
{isLoading ? <Loading /> : <AppContextProvider value={context}>{this.renderContent()}</AppContextProvider>} {isLoading ? <Loading /> : <AppContextProvider value={context}>{this.renderContent()}</AppContextProvider>}
{this.renderLoginModal()} {this.renderLoginModal()}
@ -75,7 +53,7 @@ export default class App extends Component<{}, AppStateInterface> {
public isUserAlreadyLoggedIn = () => { public isUserAlreadyLoggedIn = () => {
// checks for token validity // checks for token validity
const token = storage.getItem('token'); const token = storage.getItem('token');
const username = storage.getItem('username'); const username: string = storage.getItem('username') as string;
if (isTokenExpire(token) || isNil(username)) { if (isTokenExpire(token) || isNil(username)) {
this.handleLogout(); this.handleLogout();
} else { } else {
@ -88,11 +66,10 @@ export default class App extends Component<{}, AppStateInterface> {
public loadOnHandler = async () => { public loadOnHandler = async () => {
try { try {
// @ts-ignore const packages = await API.request<any[]>('packages', 'GET');
this.req = await API.request('packages', 'GET'); // @ts-ignore: FIX THIS TYPE: Type 'any[]' is not assignable to type '[]'
this.setState({ this.setState({
// @ts-ignore packages,
packages: this.req,
isLoading: false, isLoading: false,
}); });
} catch (error) { } catch (error) {
@ -105,7 +82,7 @@ export default class App extends Component<{}, AppStateInterface> {
} }
}; };
public setLoading = isLoading => public setLoading = (isLoading: boolean) =>
this.setState({ this.setState({
isLoading, isLoading,
}); });
@ -116,7 +93,6 @@ export default class App extends Component<{}, AppStateInterface> {
*/ */
public handleToggleLoginModal = () => { public handleToggleLoginModal = () => {
this.setState(prevState => ({ this.setState(prevState => ({
// @ts-ignore
showLoginModal: !prevState.showLoginModal, showLoginModal: !prevState.showLoginModal,
})); }));
}; };
@ -125,8 +101,7 @@ export default class App extends Component<{}, AppStateInterface> {
* handles login * handles login
* Required by: <Header /> * Required by: <Header />
*/ */
public handleDoLogin = async (usernameValue, passwordValue) => { public handleDoLogin = async (usernameValue: string, passwordValue: string) => {
// @ts-ignore
const { username, token, error } = await makeLogin(usernameValue, passwordValue); const { username, token, error } = await makeLogin(usernameValue, passwordValue);
if (username && token) { if (username && token) {
@ -143,7 +118,7 @@ export default class App extends Component<{}, AppStateInterface> {
} }
}; };
public setLoggedUser = username => { public setLoggedUser = (username: string) => {
this.setState({ this.setState({
user: { user: {
username, username,
@ -168,16 +143,21 @@ export default class App extends Component<{}, AppStateInterface> {
public renderLoginModal = (): ReactElement<HTMLElement> => { public renderLoginModal = (): ReactElement<HTMLElement> => {
const { error, showLoginModal } = this.state; const { error, showLoginModal } = this.state;
return <LoginModal error={error} onCancel={this.handleToggleLoginModal} onSubmit={this.handleDoLogin} visibility={showLoginModal} />; return (
<LoginModal
error={error}
onCancel={this.handleToggleLoginModal}
onSubmit={this.handleDoLogin}
visibility={showLoginModal}
/>
);
}; };
public renderContent = (): ReactElement<HTMLElement> => { public renderContent = (): ReactElement<HTMLElement> => {
return ( return (
<> <>
<Content> <Content>
<RouterApp onLogout={this.handleLogout} onToggleLoginModal={this.handleToggleLoginModal}> <AppRoute>{this.renderHeader()}</AppRoute>
{this.renderHeader()}
</RouterApp>
</Content> </Content>
<Footer /> <Footer />
</> </>
@ -187,11 +167,18 @@ export default class App extends Component<{}, AppStateInterface> {
public renderHeader = (): ReactElement<HTMLElement> => { public renderHeader = (): ReactElement<HTMLElement> => {
const { const {
logoUrl, logoUrl,
// @ts-ignore
user: { username }, user: { username },
scope, scope,
} = this.state; } = this.state;
return <Header logo={logoUrl} onLogout={this.handleLogout} onToggleLoginModal={this.handleToggleLoginModal} scope={scope} username={username} />; return (
<Header
logo={logoUrl}
onLogout={this.handleLogout}
onToggleLoginModal={this.handleToggleLoginModal}
scope={scope}
username={username}
/>
);
}; };
} }

20
src/App/AppContext.tsx Normal file
View File

@ -0,0 +1,20 @@
import { createContext } from 'react';
import { FormError } from '../components/Login/Login';
export interface AppProps {
error?: FormError;
logoUrl: string;
user: {
username?: string;
};
scope: string;
showLoginModal: boolean;
isUserLoggedIn: boolean;
packages: [];
isLoading: boolean;
}
export const AppContext = createContext<Partial<AppProps>>({});
export const AppContextProvider = AppContext.Provider;
export const AppContextConsumer = AppContext.Consumer;

View File

@ -6,21 +6,21 @@ export interface ErrorProps {
export interface ErrorAppState { export interface ErrorAppState {
hasError: boolean; hasError: boolean;
error: any; error: Error | null;
info: any; info: object | null;
} }
export default class ErrorBoundary extends Component<ErrorProps, ErrorAppState> { export default class ErrorBoundary extends Component<ErrorProps, ErrorAppState> {
constructor(props) { constructor(props: ErrorProps) {
super(props); super(props);
this.state = { hasError: false, error: null, info: null }; this.state = { hasError: false, error: null, info: null };
} }
componentDidCatch(error, info) { public componentDidCatch(error: Error, info: object) {
this.setState({ hasError: true, error, info }); this.setState({ hasError: true, error, info });
} }
render() { public render(): JSX.Element {
const { hasError, error, info } = this.state; const { hasError, error, info } = this.state;
const { children } = this.props; const { children } = this.props;

68
src/App/AppRoute.tsx Normal file
View File

@ -0,0 +1,68 @@
import React, { lazy, useContext, Suspense } from 'react';
import { Route as ReactRouterDomRoute, Switch, Router } from 'react-router-dom';
import { createBrowserHistory } from 'history';
import Loading from '../components/Loading';
import { AppContext } from './AppContext';
const NotFound = lazy(() => import('../components/NotFound'));
const VersionContextProvider = lazy(() => import('../pages/Version/VersionContextProvider'));
const VersionPage = lazy(() => import('../pages/Version'));
const HomePage = lazy(() => import('../pages/home'));
enum Route {
ROOT = '/',
SCOPE_PACKAGE = '/-/web/detail/@:scope/:package',
SCOPE_PACKAGE_VERSION = '/-/web/detail/@:scope/:package/v/:version',
PACKAGE = '/-/web/detail/:package',
PACKAGE_VERSION = '/-/web/detail/:package/v/:version',
}
const history = createBrowserHistory({
basename: window.__VERDACCIO_BASENAME_UI_OPTIONS && window.__VERDACCIO_BASENAME_UI_OPTIONS.url_prefix,
});
/* eslint react/jsx-max-depth: 0 */
const AppRoute: React.FC = ({ children }) => {
const appContext = useContext(AppContext);
const { isUserLoggedIn, packages } = appContext;
return (
<Router history={history}>
<Suspense fallback={<Loading />}>
{children}
<Switch>
<ReactRouterDomRoute exact={true} path={Route.ROOT}>
<HomePage isUserLoggedIn={!!isUserLoggedIn} packages={packages || []} />
</ReactRouterDomRoute>
<ReactRouterDomRoute exact={true} path={Route.PACKAGE}>
<VersionContextProvider>
<VersionPage />
</VersionContextProvider>
</ReactRouterDomRoute>
<ReactRouterDomRoute exact={true} path={Route.PACKAGE_VERSION}>
<VersionContextProvider>
<VersionPage />
</VersionContextProvider>
</ReactRouterDomRoute>
<ReactRouterDomRoute exact={true} path={Route.SCOPE_PACKAGE_VERSION}>
<VersionContextProvider>
<VersionPage />
</VersionContextProvider>
</ReactRouterDomRoute>
<ReactRouterDomRoute exact={true} path={Route.SCOPE_PACKAGE}>
<VersionContextProvider>
<VersionPage />
</VersionContextProvider>
</ReactRouterDomRoute>
<ReactRouterDomRoute>
<NotFound />
</ReactRouterDomRoute>
</Switch>
</Suspense>
</Router>
);
};
export default AppRoute;

View File

@ -1,8 +1,9 @@
import { css } from 'emotion'; import { css } from '@emotion/core';
import colors from '../utils/styles/colors';
import { theme } from '../design-tokens/theme';
export const alertError = css({ export const alertError = css({
backgroundColor: `${colors.red} !important`, backgroundColor: `${theme.palette.red} !important`,
minWidth: 'inherit !important', minWidth: 'inherit !important',
}); });

View File

@ -1,8 +1,11 @@
import React from 'react'; import React from 'react';
import { mount } from 'enzyme';
import { mount } from '../../utils/test-enzyme';
import api from '../../utils/api';
import { ActionBar } from './ActionBar'; import { ActionBar } from './ActionBar';
const mockPackageMeta = jest.fn(() => ({ const mockPackageMeta: jest.Mock = jest.fn(() => ({
latest: { latest: {
homepage: 'https://verdaccio.tld', homepage: 'https://verdaccio.tld',
bugs: { bugs: {
@ -32,7 +35,6 @@ describe('<ActionBar /> component', () => {
}); });
test('when there is no action bar data', () => { test('when there is no action bar data', () => {
// @ts-ignore
mockPackageMeta.mockImplementation(() => ({ mockPackageMeta.mockImplementation(() => ({
latest: {}, latest: {},
})); }));
@ -43,8 +45,13 @@ describe('<ActionBar /> component', () => {
expect(wrapper.html()).toEqual(''); expect(wrapper.html()).toEqual('');
}); });
test('when there is no latest property in package meta', () => {
mockPackageMeta.mockImplementation(() => ({}));
const wrapper = mount(<ActionBar />);
expect(wrapper.html()).toEqual('');
});
test('when there is a button to download a tarball', () => { test('when there is a button to download a tarball', () => {
// @ts-ignore
mockPackageMeta.mockImplementation(() => ({ mockPackageMeta.mockImplementation(() => ({
latest: { latest: {
dist: { dist: {
@ -58,5 +65,25 @@ describe('<ActionBar /> component', () => {
const button = wrapper.find('button'); const button = wrapper.find('button');
expect(button).toHaveLength(1); expect(button).toHaveLength(1);
const spy = jest.spyOn(api, 'request');
button.simulate('click');
expect(spy).toHaveBeenCalled();
});
test('when there is a button to open an issue', () => {
mockPackageMeta.mockImplementation(() => ({
latest: {
bugs: {
url: 'https://verdaccio.tld/bugs',
},
},
}));
const wrapper = mount(<ActionBar />);
expect(wrapper.html()).toMatchSnapshot();
const button = wrapper.find('button');
expect(button).toHaveLength(1);
}); });
}); });

View File

@ -1,15 +1,15 @@
import React, { Component, ReactElement } from 'react'; import React, { Component, ReactElement } from 'react';
import BugReportIcon from '@material-ui/icons/BugReport'; import BugReportIcon from '@material-ui/icons/BugReport';
import DownloadIcon from '@material-ui/icons/CloudDownload'; import DownloadIcon from '@material-ui/icons/CloudDownload';
import HomeIcon from '@material-ui/icons/Home'; import HomeIcon from '@material-ui/icons/Home';
import List from '@material-ui/core/List';
import Tooltip from '@material-ui/core/Tooltip';
import { DetailContextConsumer, VersionPageConsumerProps } from '../../pages/Version'; import { DetailContextConsumer, VersionPageConsumerProps } from '../../pages/Version';
import { Fab, ActionListItem } from './styles';
import { isURL, extractFileName, downloadFile } from '../../utils/url'; import { isURL, extractFileName, downloadFile } from '../../utils/url';
import api from '../../utils/api'; import api from '../../utils/api';
import Tooltip from '../../muiComponents/Tooltip';
import List from '../../muiComponents/List';
import { Fab, ActionListItem } from './styles';
export interface Action { export interface Action {
icon: string; icon: string;
@ -20,7 +20,8 @@ export interface Action {
export async function downloadHandler(link: string): Promise<void> { export async function downloadHandler(link: string): Promise<void> {
const fileStream: Blob = await api.request(link, 'GET', { const fileStream: Blob = await api.request(link, 'GET', {
headers: { headers: {
['accept']: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3', ['accept']:
'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
}, },
credentials: 'include', credentials: 'include',
}); });
@ -70,7 +71,6 @@ class ActionBar extends Component {
} }
private renderActionBar = ({ packageMeta }) => { private renderActionBar = ({ packageMeta }) => {
// @ts-ignore
const { latest } = packageMeta; const { latest } = packageMeta;
if (!latest) { if (!latest) {
@ -107,7 +107,6 @@ class ActionBar extends Component {
} else { } else {
const fab = <Fab size={'small'}>{actionItem['icon']}</Fab>; const fab = <Fab size={'small'}>{actionItem['icon']}</Fab>;
component.push( component.push(
// @ts-ignore
<Tooltip key={key} title={actionItem['title']}> <Tooltip key={key} title={actionItem['title']}>
<>{this.renderIconsWithLink(link, fab)}</> <>{this.renderIconsWithLink(link, fab)}</>
</Tooltip> </Tooltip>

View File

@ -2,4 +2,6 @@
exports[`<ActionBar /> component should render the component in default state 1`] = `""`; exports[`<ActionBar /> component should render the component in default state 1`] = `""`;
exports[`<ActionBar /> component when there is a button to download a tarball 1`] = `"<ul class=\\"MuiList-root MuiList-padding\\"><div class=\\"MuiButtonBase-root MuiListItem-root css-9q3x3c eux6shq0 MuiListItem-gutters MuiListItem-button MuiListItem-alignItemsFlexStart\\" tabindex=\\"0\\" role=\\"button\\" aria-disabled=\\"false\\"><button class=\\"MuiButtonBase-root MuiFab-root css-96oxa0 eux6shq1 MuiFab-sizeSmall\\" tabindex=\\"0\\" type=\\"button\\" title=\\"Download tarball\\"><span class=\\"MuiFab-label\\"><svg class=\\"MuiSvgIcon-root\\" focusable=\\"false\\" viewBox=\\"0 0 24 24\\" aria-hidden=\\"true\\" role=\\"presentation\\"><path d=\\"M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM17 13l-5 5-5-5h3V9h4v4h3z\\"></path></svg></span><span class=\\"MuiTouchRipple-root\\"></span></button><span class=\\"MuiTouchRipple-root\\"></span></div></ul>"`; exports[`<ActionBar /> component when there is a button to download a tarball 1`] = `"<ul class=\\"MuiList-root MuiList-padding\\"><div class=\\"MuiButtonBase-root MuiListItem-root css-l3mdff-ActionListItem eux6shq0 MuiListItem-gutters MuiListItem-button MuiListItem-alignItemsFlexStart\\" tabindex=\\"0\\" role=\\"button\\" aria-disabled=\\"false\\"><button class=\\"MuiButtonBase-root MuiFab-root css-is03ew-Fab eux6shq1 MuiFab-sizeSmall\\" tabindex=\\"0\\" type=\\"button\\" title=\\"Download tarball\\"><span class=\\"MuiFab-label\\"><svg class=\\"MuiSvgIcon-root\\" focusable=\\"false\\" viewBox=\\"0 0 24 24\\" aria-hidden=\\"true\\" role=\\"presentation\\"><path d=\\"M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM17 13l-5 5-5-5h3V9h4v4h3z\\"></path></svg></span><span class=\\"MuiTouchRipple-root\\"></span></button><span class=\\"MuiTouchRipple-root\\"></span></div></ul>"`;
exports[`<ActionBar /> component when there is a button to open an issue 1`] = `"<ul class=\\"MuiList-root MuiList-padding\\"><div class=\\"MuiButtonBase-root MuiListItem-root css-l3mdff-ActionListItem eux6shq0 MuiListItem-gutters MuiListItem-button MuiListItem-alignItemsFlexStart\\" tabindex=\\"0\\" role=\\"button\\" aria-disabled=\\"false\\"><a href=\\"https://verdaccio.tld/bugs\\" target=\\"_blank\\"><button class=\\"MuiButtonBase-root MuiFab-root css-is03ew-Fab eux6shq1 MuiFab-sizeSmall\\" tabindex=\\"0\\" type=\\"button\\"><span class=\\"MuiFab-label\\"><svg class=\\"MuiSvgIcon-root\\" focusable=\\"false\\" viewBox=\\"0 0 24 24\\" aria-hidden=\\"true\\" role=\\"presentation\\"><path d=\\"M20 8h-2.81c-.45-.78-1.07-1.45-1.82-1.96L17 4.41 15.59 3l-2.17 2.17C12.96 5.06 12.49 5 12 5c-.49 0-.96.06-1.41.17L8.41 3 7 4.41l1.62 1.63C7.88 6.55 7.26 7.22 6.81 8H4v2h2.09c-.05.33-.09.66-.09 1v1H4v2h2v1c0 .34.04.67.09 1H4v2h2.81c1.04 1.79 2.97 3 5.19 3s4.15-1.21 5.19-3H20v-2h-2.09c.05-.33.09-.66.09-1v-1h2v-2h-2v-1c0-.34-.04-.67-.09-1H20V8zm-6 8h-4v-2h4v2zm0-4h-4v-2h4v2z\\"></path></svg></span><span class=\\"MuiTouchRipple-root\\"></span></button></a><span class=\\"MuiTouchRipple-root\\"></span></div></ul>"`;

View File

@ -1,21 +1,17 @@
import styled from 'react-emotion'; import styled from '@emotion/styled';
import { default as MuiFab } from '@material-ui/core/Fab';
import ListItem from '@material-ui/core/ListItem';
import colors from '../../utils/styles/colors'; import ListItem from '../../muiComponents/ListItem';
import FloatingActionButton from '../../muiComponents/FloatingActionButton';
import { Theme } from '../../design-tokens/theme';
export const ActionListItem = styled(ListItem)({ export const ActionListItem = styled(ListItem)({
'&&': {
paddingTop: 0, paddingTop: 0,
paddingLeft: 0, paddingLeft: 0,
paddingRight: 0, paddingRight: 0,
},
}); });
export const Fab = styled(MuiFab)({ export const Fab = styled(FloatingActionButton)<{ theme?: Theme }>(props => ({
'&&': { backgroundColor: props.theme && props.theme.palette.primary.main,
backgroundColor: colors.primary, color: props.theme && props.theme.palette.white,
color: colors.white,
marginRight: '10px', marginRight: '10px',
}, }));
});

View File

@ -1,24 +1,15 @@
import React from 'react'; import React from 'react';
import { mount } from 'enzyme';
import { mount } from '../../utils/test-enzyme';
import { DetailContext } from '../../pages/Version';
import Authors from './Author'; import Authors from './Author';
const mockPackageMeta = jest.fn(() => ({ const withAuthorComponent = (packageMeta: React.ContextType<typeof DetailContext>['packageMeta']): JSX.Element => (
latest: { <DetailContext.Provider value={{ packageMeta }}>
homepage: 'https://verdaccio.tld', <Authors />
bugs: { </DetailContext.Provider>
url: 'https://verdaccio.tld/bugs', );
},
dist: {
tarball: 'https://verdaccio.tld/download',
},
},
}));
jest.mock('../../pages/Version', () => ({
DetailContextConsumer: component => {
return component.children({ packageMeta: mockPackageMeta() });
},
}));
describe('<Author /> component', () => { describe('<Author /> component', () => {
beforeEach(() => { beforeEach(() => {
@ -36,13 +27,12 @@ describe('<Author /> component', () => {
url: '', url: '',
avatar: 'https://www.gravatar.com/avatar/000000', avatar: 'https://www.gravatar.com/avatar/000000',
}, },
dist: { fileCount: 0, unpackedSize: 0 },
}, },
_uplinks: {},
}; };
// @ts-ignore const wrapper = mount(withAuthorComponent(packageMeta));
mockPackageMeta.mockImplementation(() => packageMeta);
const wrapper = mount(<Authors />);
expect(wrapper.html()).toMatchSnapshot(); expect(wrapper.html()).toMatchSnapshot();
}); });
@ -51,14 +41,13 @@ describe('<Author /> component', () => {
latest: { latest: {
name: 'verdaccio', name: 'verdaccio',
version: '4.0.0', version: '4.0.0',
dist: { fileCount: 0, unpackedSize: 0 },
}, },
_uplinks: {},
}; };
// @ts-ignore const wrapper = mount(withAuthorComponent(packageMeta));
mockPackageMeta.mockImplementation(() => packageMeta); expect(wrapper.html()).toBeNull();
const wrapper = mount(<Authors />);
expect(wrapper.html()).toEqual('');
}); });
test('should render the component when there is no author email', () => { test('should render the component when there is no author email', () => {
@ -71,13 +60,12 @@ describe('<Author /> component', () => {
url: '', url: '',
avatar: 'https://www.gravatar.com/avatar/000000', avatar: 'https://www.gravatar.com/avatar/000000',
}, },
dist: { fileCount: 0, unpackedSize: 0 },
}, },
_uplinks: {},
}; };
// @ts-ignore const wrapper = mount(withAuthorComponent(packageMeta));
mockPackageMeta.mockImplementation(() => packageMeta);
const wrapper = mount(<Authors />);
expect(wrapper.html()).toMatchSnapshot(); expect(wrapper.html()).toMatchSnapshot();
}); });
}); });

View File

@ -1,58 +1,44 @@
import React, { Component, ReactNode, ReactElement } from 'react'; import React, { FC, useContext } from 'react';
import Avatar from '@material-ui/core/Avatar'; import { DetailContext } from '../../pages/Version';
import List from '@material-ui/core/List';
import { DetailContextConsumer } from '../../pages/Version';
import { Heading, AuthorListItem, AuthorListItemText } from './styles';
import { isEmail } from '../../utils/url'; import { isEmail } from '../../utils/url';
import Avatar from '../../muiComponents/Avatar';
import List from '../../muiComponents/List';
class Authors extends Component { import { StyledText, AuthorListItem, AuthorListItemText } from './styles';
public render(): ReactElement<HTMLElement> {
return ( const Author: FC = () => {
<DetailContextConsumer> const { packageMeta } = useContext(DetailContext);
{context => {
const { packageMeta } = context;
if (!packageMeta) { if (!packageMeta) {
return null; return null;
} }
return this.renderAuthor(packageMeta); const { author, name: packageName, version } = packageMeta.latest;
}}
</DetailContextConsumer>
);
}
public renderLinkForMail(email: string, avatarComponent: ReactNode, packageName: string, version: string): ReactElement<HTMLElement> | ReactNode {
if (!email || isEmail(email) === false) {
return avatarComponent;
}
return (
<a href={`mailto:${email}?subject=${packageName}@${version}`} target={'_top'}>
{avatarComponent}
</a>
);
}
public renderAuthor = ({ latest }) => {
const { author, name: packageName, version } = latest;
if (!author) { if (!author) {
return null; return null;
} }
const { email, name } = author;
const avatarComponent = <Avatar alt={author.name} src={author.avatar} />; const avatarComponent = <Avatar alt={author.name} src={author.avatar} />;
return ( return (
<List subheader={<Heading variant={'subtitle1'}>{'Author'}</Heading>}> <List subheader={<StyledText variant={'subtitle1'}>{'Author'}</StyledText>}>
<AuthorListItem button={true}> <AuthorListItem button={true}>
{this.renderLinkForMail(author.email, avatarComponent, packageName, version)} {!email || !isEmail(email) ? (
<AuthorListItemText primary={author.name} /> avatarComponent
) : (
<a href={`mailto:${email}?subject=${packageName}@${version}`} target={'_top'}>
{avatarComponent}
</a>
)}
<AuthorListItemText primary={name} />
</AuthorListItem> </AuthorListItem>
</List> </List>
); );
}; };
}
export default Authors; export default Author;

View File

@ -1,5 +1,5 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<Author /> component should render the component in default state 1`] = `"<ul class=\\"MuiList-root MuiList-padding MuiList-subheader\\"><h6 class=\\"MuiTypography-root css-hyrz44 e1xuehjw0 MuiTypography-subtitle1\\">Author</h6><div class=\\"MuiButtonBase-root MuiListItem-root css-xugzlj e1xuehjw1 MuiListItem-gutters MuiListItem-button\\" tabindex=\\"0\\" role=\\"button\\" aria-disabled=\\"false\\"><a href=\\"mailto:verdaccio.user@verdaccio.org?subject=verdaccio@4.0.0\\" target=\\"_top\\"><div class=\\"MuiAvatar-root\\"><img alt=\\"verdaccio user\\" src=\\"https://www.gravatar.com/avatar/000000\\" class=\\"MuiAvatar-img\\"></div></a><div class=\\"MuiListItemText-root css-1vhg3jx e1xuehjw2\\"><span class=\\"MuiTypography-root MuiListItemText-primary MuiTypography-body1\\">verdaccio user</span></div><span class=\\"MuiTouchRipple-root\\"></span></div></ul>"`; exports[`<Author /> component should render the component in default state 1`] = `"<ul class=\\"MuiList-root MuiList-padding MuiList-subheader\\"><h6 class=\\"MuiTypography-root css-1na337r-StyledText e1xuehjw0 MuiTypography-subtitle1\\">Author</h6><div class=\\"MuiButtonBase-root MuiListItem-root css-1k45khb-AuthorListItem e1xuehjw1 MuiListItem-gutters MuiListItem-button\\" tabindex=\\"0\\" role=\\"button\\" aria-disabled=\\"false\\"><a href=\\"mailto:verdaccio.user@verdaccio.org?subject=verdaccio@4.0.0\\" target=\\"_top\\"><div class=\\"MuiAvatar-root MuiAvatar-circle\\"><img alt=\\"verdaccio user\\" src=\\"https://www.gravatar.com/avatar/000000\\" class=\\"MuiAvatar-img\\"></div></a><div class=\\"MuiListItemText-root css-1cnlq5d-AuthorListItemText e1xuehjw2\\"><span class=\\"MuiTypography-root MuiListItemText-primary MuiTypography-body1\\">verdaccio user</span></div><span class=\\"MuiTouchRipple-root\\"></span></div></ul>"`;
exports[`<Author /> component should render the component when there is no author email 1`] = `"<ul class=\\"MuiList-root MuiList-padding MuiList-subheader\\"><h6 class=\\"MuiTypography-root css-hyrz44 e1xuehjw0 MuiTypography-subtitle1\\">Author</h6><div class=\\"MuiButtonBase-root MuiListItem-root css-xugzlj e1xuehjw1 MuiListItem-gutters MuiListItem-button\\" tabindex=\\"0\\" role=\\"button\\" aria-disabled=\\"false\\"><div class=\\"MuiAvatar-root\\"><img alt=\\"verdaccio user\\" src=\\"https://www.gravatar.com/avatar/000000\\" class=\\"MuiAvatar-img\\"></div><div class=\\"MuiListItemText-root css-1vhg3jx e1xuehjw2\\"><span class=\\"MuiTypography-root MuiListItemText-primary MuiTypography-body1\\">verdaccio user</span></div><span class=\\"MuiTouchRipple-root\\"></span></div></ul>"`; exports[`<Author /> component should render the component when there is no author email 1`] = `"<ul class=\\"MuiList-root MuiList-padding MuiList-subheader\\"><h6 class=\\"MuiTypography-root css-1na337r-StyledText e1xuehjw0 MuiTypography-subtitle1\\">Author</h6><div class=\\"MuiButtonBase-root MuiListItem-root css-1k45khb-AuthorListItem e1xuehjw1 MuiListItem-gutters MuiListItem-button\\" tabindex=\\"0\\" role=\\"button\\" aria-disabled=\\"false\\"><div class=\\"MuiAvatar-root MuiAvatar-circle\\"><img alt=\\"verdaccio user\\" src=\\"https://www.gravatar.com/avatar/000000\\" class=\\"MuiAvatar-img\\"></div><div class=\\"MuiListItemText-root css-1cnlq5d-AuthorListItemText e1xuehjw2\\"><span class=\\"MuiTypography-root MuiListItemText-primary MuiTypography-body1\\">verdaccio user</span></div><span class=\\"MuiTouchRipple-root\\"></span></div></ul>"`;

View File

@ -1,27 +1,23 @@
import styled from 'react-emotion'; import styled from '@emotion/styled';
import ListItem from '@material-ui/core/ListItem';
import Typography from '@material-ui/core/Typography';
import { fontWeight } from '../../utils/styles/sizes';
import ListItemText from '@material-ui/core/ListItemText';
export const Heading = styled(Typography)({ import { fontWeight } from '../../utils/styles/sizes';
'&&': { import ListItem from '../../muiComponents/ListItem';
import Text from '../../muiComponents/Text';
import ListItemText from '../../muiComponents/ListItemText';
export const StyledText = styled(Text)({
fontWeight: fontWeight.bold, fontWeight: fontWeight.bold,
textTransform: 'capitalize', textTransform: 'capitalize',
},
}); });
export const AuthorListItem = styled(ListItem)({ export const AuthorListItem = styled(ListItem)({
'&&': {
padding: 0, padding: 0,
}, ':hover': {
'&&:hover': {
backgroundColor: 'transparent', backgroundColor: 'transparent',
}, },
}); });
export const AuthorListItemText = styled(ListItemText)({ export const AuthorListItemText = styled(ListItemText)({
'&&': {
padding: '0 10px', padding: '0 10px',
margin: 0, margin: 0,
},
}); });

View File

@ -1,36 +1,47 @@
import React, { KeyboardEvent } from 'react'; import React, { KeyboardEvent } from 'react';
import { css } from 'emotion'; import styled from '@emotion/styled';
import Autosuggest from 'react-autosuggest'; import Autosuggest, { SuggestionSelectedEventData, InputProps, ChangeEvent } from 'react-autosuggest';
import match from 'autosuggest-highlight/match'; import match from 'autosuggest-highlight/match';
import parse from 'autosuggest-highlight/parse'; import parse from 'autosuggest-highlight/parse';
import MenuItem from '@material-ui/core/MenuItem';
import { fontWeight } from '../../utils/styles/sizes'; import { fontWeight } from '../../utils/styles/sizes';
import MenuItem from '../../muiComponents/MenuItem';
import { Wrapper, InputField, SuggestionContainer } from './styles'; import { Wrapper, InputField, SuggestionContainer } from './styles';
const StyledAnchor = styled('a')<{ fw: number }>(props => ({
fontWeight: props.fw,
}));
const StyledMenuItem = styled(MenuItem)({
cursor: 'pointer',
});
interface Props { interface Props {
suggestions: unknown[]; suggestions: unknown[];
suggestionsLoading?: boolean; suggestionsLoading?: boolean;
suggestionsLoaded?: boolean; suggestionsLoaded?: boolean;
suggestionsError?: boolean; suggestionsError?: boolean;
apiLoading?: boolean; apiLoading?: boolean;
color?: string;
value?: string; value?: string;
placeholder?: string; placeholder?: string;
startAdornment?: JSX.Element; startAdornment?: JSX.Element;
disableUnderline?: boolean; disableUnderline?: boolean;
onChange?: (event: KeyboardEvent<HTMLInputElement>, { newValue, method }: { newValue: string; method: string }) => void; onChange: (event: React.FormEvent<HTMLInputElement>, params: ChangeEvent) => void;
onSuggestionsFetch?: ({ value: string }) => Promise<void>; onSuggestionsFetch: ({ value: string }) => Promise<void>;
onCleanSuggestions?: () => void; onCleanSuggestions?: () => void;
onClick?: (event: KeyboardEvent<HTMLInputElement>, { suggestionValue, method }: { suggestionValue: string[]; method: string }) => void; onClick?: (event: React.FormEvent<HTMLInputElement>, data: SuggestionSelectedEventData<unknown>) => void;
onKeyDown?: (event: KeyboardEvent<HTMLInputElement>) => void; onKeyDown?: (event: KeyboardEvent<HTMLInputElement>) => void;
onBlur?: (event: KeyboardEvent<HTMLInputElement>) => void; onBlur?: (event: React.FormEvent<HTMLInputElement>) => void;
} }
/* eslint-disable react/jsx-sort-props */
/* eslint-disable verdaccio/jsx-spread */
const renderInputComponent = (inputProps): JSX.Element => { const renderInputComponent = (inputProps): JSX.Element => {
const { ref, startAdornment, disableUnderline, onKeyDown, ...others } = inputProps; const { ref, startAdornment, disableUnderline, onKeyDown, ...others } = inputProps;
return ( return (
<InputField <InputField
fullWidth={true}
InputProps={{ InputProps={{
inputRef: node => { inputRef: node => {
ref(node); ref(node);
@ -39,7 +50,6 @@ const renderInputComponent = (inputProps): JSX.Element => {
disableUnderline, disableUnderline,
onKeyDown, onKeyDown,
}} }}
fullWidth={true}
{...others} {...others}
/> />
); );
@ -51,23 +61,18 @@ const renderSuggestion = (suggestion, { query, isHighlighted }): JSX.Element =>
const matches = match(suggestion.name, query); const matches = match(suggestion.name, query);
const parts = parse(suggestion.name, matches); const parts = parse(suggestion.name, matches);
return ( return (
<MenuItem component="div" selected={isHighlighted}> <StyledMenuItem component="div" selected={isHighlighted}>
<div> <div>
{parts.map((part, index) => { {parts.map((part, index) => {
const fw = part.highlight ? fontWeight.semiBold : fontWeight.light; const fw = part.highlight ? fontWeight.semiBold : fontWeight.light;
return ( return (
<a <StyledAnchor fw={fw} key={String(index)}>
className={css`
font-weight: ${fw};
`}
href={suggestion.link}
key={String(index)}>
{part.text} {part.text}
</a> </StyledAnchor>
); );
})} })}
</div> </div>
</MenuItem> </StyledMenuItem>
); );
}; };
@ -94,7 +99,6 @@ const AutoComplete = ({
value = '', value = '',
placeholder = '', placeholder = '',
disableUnderline = false, disableUnderline = false,
color,
onClick, onClick,
onKeyDown, onKeyDown,
onBlur, onBlur,
@ -110,13 +114,14 @@ const AutoComplete = ({
onSuggestionsFetchRequested: onSuggestionsFetch, onSuggestionsFetchRequested: onSuggestionsFetch,
onSuggestionsClearRequested: onCleanSuggestions, onSuggestionsClearRequested: onCleanSuggestions,
}; };
const inputProps = { const inputProps: InputProps<unknown> = {
value, value,
onChange, onChange,
placeholder, placeholder,
// material-ui@4.5.1 introduce better types for TextInput, check readme
// @ts-ignore
startAdornment, startAdornment,
disableUnderline, disableUnderline,
color,
onKeyDown, onKeyDown,
onBlur, onBlur,
}; };
@ -135,7 +140,12 @@ const AutoComplete = ({
return ( return (
<Wrapper> <Wrapper>
<Autosuggest {...autosuggestProps} inputProps={inputProps} onSuggestionSelected={onClick} renderSuggestionsContainer={renderSuggestionsContainer} /> <Autosuggest
{...autosuggestProps}
inputProps={inputProps}
onSuggestionSelected={onClick}
renderSuggestionsContainer={renderSuggestionsContainer}
/>
</Wrapper> </Wrapper>
); );
}; };

View File

@ -1,59 +1,44 @@
import React from 'react'; import React from 'react';
import styled, { css } from 'react-emotion'; import styled from '@emotion/styled';
import Paper from '@material-ui/core/Paper';
import TextField from '../TextField'; import TextField from '../../muiComponents/TextField';
import Paper from '../../muiComponents/Paper';
import { Theme } from '../../design-tokens/theme';
export interface InputFieldProps { export interface InputFieldProps {
color: string; color: string;
} }
export const Wrapper = styled('div')({ export const Wrapper = styled('div')({
'&&': {
width: '100%', width: '100%',
height: '32px', height: '32px',
position: 'relative', position: 'relative',
zIndex: 1, zIndex: 1,
},
}); });
export const InputField: React.FC<InputFieldProps> = ({ color, ...others }) => ( export const StyledTextField = styled(TextField)<{ theme?: Theme }>(props => ({
<TextField '& .MuiInputBase-root': {
{...others} ':before': {
classes={{ content: "''",
// @ts-ignore border: 'none',
input: css` },
&& { ':after': {
${color && borderColor: props.theme && props.theme.palette.white,
css` },
color: ${color}; ':hover:before': {
`}; content: 'none',
} },
`, },
root: css` '& .MuiInputBase-input': {
&& { color: props.theme && props.theme.palette.white,
&:before { },
content: ''; }));
border: none;
} /* eslint-disable verdaccio/jsx-spread */
&:after { // @ts-ignore types of color are incompatible
${color && export const InputField: React.FC<InputFieldProps> = ({ ...others }) => <StyledTextField {...others} />;
css`
border-color: ${color};
`};
}
&:hover:before {
content: none;
}
}
`,
}}
/>
);
export const SuggestionContainer = styled(Paper)({ export const SuggestionContainer = styled(Paper)({
'&&': {
maxHeight: '500px', maxHeight: '500px',
overflowY: 'auto', overflowY: 'auto',
},
}); });

View File

@ -1,8 +1,8 @@
import React, { FC } from 'react'; import React, { FC } from 'react';
import Avatar from '@material-ui/core/Avatar';
import Tooltip from '@material-ui/core/Tooltip';
import { isEmail } from '../../utils/url'; import { isEmail } from '../../utils/url';
import Tooltip from '../../muiComponents/Tooltip';
import Avatar from '../../muiComponents/Avatar';
export interface AvatarDeveloper { export interface AvatarDeveloper {
name: string; name: string;
@ -14,7 +14,12 @@ export interface AvatarDeveloper {
const AvatarTooltip: FC<AvatarDeveloper> = ({ name, packageName, version, avatar, email }) => { const AvatarTooltip: FC<AvatarDeveloper> = ({ name, packageName, version, avatar, email }) => {
const avatarComponent = <Avatar aria-label={name} src={avatar} />; const avatarComponent = <Avatar aria-label={name} src={avatar} />;
function renderLinkForMail(email, avatarComponent, packageName, version): JSX.Element { function renderLinkForMail(
email: string,
avatarComponent: JSX.Element,
packageName: string,
version: string
): JSX.Element {
if (!email || isEmail(email) === false) { if (!email || isEmail(email) === false) {
return avatarComponent; return avatarComponent;
} }

View File

@ -1,38 +1,28 @@
import React from 'react'; import React from 'react';
import { mount } from 'enzyme'; import { ReactWrapper } from 'enzyme';
import { copyToClipBoardUtility } from '../../utils/cli-utils';
import { mount } from '../../utils/test-enzyme';
import CopyToClipBoard from './CopyToClipBoard'; import CopyToClipBoard from './CopyToClipBoard';
import { CopyIcon } from './styles'; import { CopyIcon } from './styles';
jest.mock('../../utils/cli-utils');
describe('<CopyToClipBoard /> component', () => { describe('<CopyToClipBoard /> component', () => {
let wrapper; let wrapper: ReactWrapper;
const copyText = 'copy text';
beforeEach(() => { beforeEach(() => {
wrapper = mount(<CopyToClipBoard text={'copy text'} />); wrapper = mount(<CopyToClipBoard text={copyText} />);
}); });
test('render the component', () => { test('should load the component in default state', () => {
expect(wrapper.html()).toMatchSnapshot(); expect(wrapper.html()).toMatchSnapshot();
}); });
test('should call the DOM APIs for copy to clipboard utility', () => { test('should call the copyToClipBoardUtility for copy to clipboard utility', () => {
const event = { wrapper.find(CopyIcon).simulate('click');
preventDefault: jest.fn(), expect(copyToClipBoardUtility).toHaveBeenCalledWith(copyText);
};
// @ts-ignore: Property 'getSelection' does not exist on type 'Global'.
global.getSelection = jest.fn(() => ({
removeAllRanges: () => {},
addRange: () => {},
}));
// @ts-ignore: Property 'document/getSelection' does not exist on type 'Global'.
const { document, getSelection } = global;
wrapper.find(CopyIcon).simulate('click', event);
expect(event.preventDefault).toHaveBeenCalled();
expect(document.createRange).toHaveBeenCalled();
expect(getSelection).toHaveBeenCalled();
expect(document.execCommand).toHaveBeenCalledWith('copy');
}); });
}); });

View File

@ -1,9 +1,9 @@
import Tooltip from '@material-ui/core/Tooltip';
import FileCopy from '@material-ui/icons/FileCopy'; import FileCopy from '@material-ui/icons/FileCopy';
import React from 'react'; import React from 'react';
import { copyToClipBoardUtility } from '../../utils/cli-utils'; import { copyToClipBoardUtility } from '../../utils/cli-utils';
import { TEXT } from '../../utils/constants'; import { TEXT } from '../../utils/constants';
import Tooltip from '../../muiComponents/Tooltip';
import { ClipBoardCopy, ClipBoardCopyText, CopyIcon } from './styles'; import { ClipBoardCopy, ClipBoardCopyText, CopyIcon } from './styles';
@ -12,7 +12,7 @@ interface Props {
children?: React.ReactNode; children?: React.ReactNode;
} }
const renderText = (text, children): JSX.Element => { const renderText = (text: string, children: React.ReactNode): JSX.Element => {
if (children) { if (children) {
return <ClipBoardCopyText>{children}</ClipBoardCopyText>; return <ClipBoardCopyText>{children}</ClipBoardCopyText>;
} }

View File

@ -1,3 +1,3 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<CopyToClipBoard /> component render the component 1`] = `"<div class=\\"css-1mta3t8 eb8w2fo0\\"><span class=\\"css-1m8aenu eb8w2fo1\\">copy text</span><button class=\\"MuiButtonBase-root MuiIconButton-root css-0 eb8w2fo2\\" tabindex=\\"0\\" type=\\"button\\" title=\\"Copy to Clipboard\\"><span class=\\"MuiIconButton-label\\"><svg class=\\"MuiSvgIcon-root\\" focusable=\\"false\\" viewBox=\\"0 0 24 24\\" aria-hidden=\\"true\\" role=\\"presentation\\"><path d=\\"M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm-1 4l6 6v10c0 1.1-.9 2-2 2H7.99C6.89 23 6 22.1 6 21l.01-14c0-1.1.89-2 1.99-2h7zm-1 7h5.5L14 6.5V12z\\"></path></svg></span><span class=\\"MuiTouchRipple-root\\"></span></button></div>"`; exports[`<CopyToClipBoard /> component should load the component in default state 1`] = `"<div class=\\"css-1in239f-ClipBoardCopy eb8w2fo0\\"><span class=\\"css-7gar9h-ClipBoardCopyText eb8w2fo1\\">copy text</span><button class=\\"MuiButtonBase-root MuiIconButton-root css-1fs86cq-CopyIcon eb8w2fo2\\" tabindex=\\"0\\" type=\\"button\\" title=\\"Copy to Clipboard\\"><span class=\\"MuiIconButton-label\\"><svg class=\\"MuiSvgIcon-root\\" focusable=\\"false\\" viewBox=\\"0 0 24 24\\" aria-hidden=\\"true\\" role=\\"presentation\\"><path d=\\"M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm-1 4l6 6v10c0 1.1-.9 2-2 2H7.99C6.89 23 6 22.1 6 21l.01-14c0-1.1.89-2 1.99-2h7zm-1 7h5.5L14 6.5V12z\\"></path></svg></span><span class=\\"MuiTouchRipple-root\\"></span></button></div>"`;

View File

@ -1,22 +1,20 @@
import IconButton from '@material-ui/core/IconButton'; import styled from '@emotion/styled';
import styled from 'react-emotion';
import IconButton from '../../muiComponents/IconButton';
export const ClipBoardCopy = styled('div')({ export const ClipBoardCopy = styled('div')({
'&&': {
display: 'flex', display: 'flex',
alignItems: 'center', alignItems: 'center',
justifyContent: 'space-between', justifyContent: 'space-between',
},
}); });
export const ClipBoardCopyText = styled('span')({ export const ClipBoardCopyText = styled('span')({
'&&': {
display: 'inline-block', display: 'inline-block',
textOverflow: 'ellipsis', textOverflow: 'ellipsis',
overflow: 'hidden', overflow: 'hidden',
whiteSpace: 'nowrap', whiteSpace: 'nowrap',
height: '21px', height: '21px',
}, fontSize: '1rem',
}); });
export const CopyIcon = styled(IconButton)({}); export const CopyIcon = styled(IconButton)({});

View File

@ -0,0 +1,92 @@
import React from 'react';
import { HashRouter } from 'react-router-dom';
import { DetailContextProvider } from '../../pages/Version';
import { render } from '../../utils/test-react-testing-library';
import Dependencies from './Dependencies';
describe('<Dependencies /> component', () => {
test('Renders a message when there are no dependencies', () => {
// Given
const packageMeta = {
latest: {
name: 'verdaccio',
version: '4.0.0',
author: {
name: 'verdaccio user',
email: 'verdaccio.user@verdaccio.org',
url: '',
avatar: 'https://www.gravatar.com/avatar/000000',
},
dist: { fileCount: 0, unpackedSize: 0 },
dependencies: {},
devDependencies: {},
peerDependencies: {},
},
_uplinks: {},
};
// When
const { getByText } = render(
<DetailContextProvider value={{ packageMeta }}>
<Dependencies />
</DetailContextProvider>
);
// Then
expect(getByText('verdaccio has no dependencies.')).toBeDefined();
});
test('Renders a link to each dependency', () => {
// Given
const packageMeta = {
latest: {
name: 'verdaccio',
version: '4.0.0',
author: {
name: 'verdaccio user',
email: 'verdaccio.user@verdaccio.org',
url: '',
avatar: 'https://www.gravatar.com/avatar/000000',
},
dist: { fileCount: 0, unpackedSize: 0 },
dependencies: {
react: '16.9.0',
'react-dom': '16.9.0',
},
devDependencies: {
'babel-core': '7.0.0-beta6',
},
peerDependencies: {
'styled-components': '5.0.0',
},
},
_uplinks: {},
};
// When
const { getByText } = render(
<HashRouter>
<DetailContextProvider value={{ packageMeta }}>
<Dependencies />
</DetailContextProvider>
</HashRouter>
);
// Then
// FIXME: currently MaterialUI chips do not support the children
// prop, therefore it is impossible to use proper links for
// dependencies. Those are for now clickable spans
expect(getByText('dependencies (2)')).toBeDefined();
expect(getByText('react@16.9.0').tagName).toBe('SPAN');
expect(getByText('react-dom@16.9.0').tagName).toBe('SPAN');
expect(getByText('devDependencies (1)')).toBeDefined();
expect(getByText('babel-core@7.0.0-beta6').tagName).toBe('SPAN');
expect(getByText('peerDependencies (1)')).toBeDefined();
expect(getByText('styled-components@5.0.0').tagName).toBe('SPAN');
});
});

View File

@ -1,119 +1,78 @@
import React, { Component, Fragment, ReactElement } from 'react'; import React, { useContext } from 'react';
import { withRouter, RouteComponentProps } from 'react-router-dom'; import { useHistory } from 'react-router-dom';
import CardContent from '@material-ui/core/CardContent';
import { DetailContextConsumer, VersionPageConsumerProps } from '../../pages/Version'; import CardContent from '../../muiComponents/CardContent';
import { PackageDependencies } from '../../../types/packageMeta';
import { CardWrap, Heading, Tags, Tag } from './styles'; import { DetailContext } from '../../pages/Version';
import NoItems from '../NoItems'; import NoItems from '../NoItems';
type DepDetailProps = { import { CardWrap, StyledText, Tags, Tag } from './styles';
name: string;
version: string;
onLoading?: () => void;
} & RouteComponentProps;
interface DepDetailState { interface DependencyBlockProps {
name: string; title: string;
version: string; dependencies: PackageDependencies;
} }
class DepDetail extends Component<DepDetailProps, DepDetailState> { const DependencyBlock: React.FC<DependencyBlockProps> = ({ title, dependencies }) => {
constructor(props: DepDetailProps) { const { enableLoading } = useContext(DetailContext);
super(props); const history = useHistory();
const { name, version } = this.props;
this.state = { const deps = Object.entries(dependencies);
name,
version,
};
}
public render(): ReactElement<HTMLElement> { function handleClick(name: string): void {
const { name, version } = this.state; enableLoading && enableLoading();
const tagText = `${name}@${version}`;
return <Tag className={'dep-tag'} clickable={true} label={tagText} onClick={this.handleOnClick} />;
}
private handleOnClick = () => {
const { name } = this.state;
const { onLoading, history } = this.props;
onLoading && onLoading();
history.push(`/-/web/detail/${name}`); history.push(`/-/web/detail/${name}`);
}; }
}
const WrapperDependencyDetail = withRouter(DepDetail);
class DependencyBlock extends Component<{ title: string; dependencies: [] }> {
public render(): ReactElement<HTMLElement> {
const { dependencies, title } = this.props;
const deps = Object.entries(dependencies) as [];
return (
<DetailContextConsumer>
{({ enableLoading }) => {
return ( return (
<CardWrap> <CardWrap>
<CardContent> <CardContent>
<Heading variant="subtitle1">{`${title} (${deps.length})`}</Heading> <StyledText variant="subtitle1">{`${title} (${deps.length})`}</StyledText>
<Tags>{this.renderTags(deps, enableLoading)}</Tags> <Tags>
{deps.map(([name, version]) => (
// eslint-disable-next-line
<Tag className={'dep-tag'} clickable={true} key={name} label={`${name}@${version}`} onClick={() => handleClick(name)} />
))}
</Tags>
</CardContent> </CardContent>
</CardWrap> </CardWrap>
); );
}} };
</DetailContextConsumer>
);
}
private renderTags = (deps: [], enableLoading?: () => void) => function hasKeys(object?: { [key: string]: any }): boolean {
deps.map(dep => { return !!object && Object.keys(object).length > 0;
const [name, version] = dep as [string, string];
return <WrapperDependencyDetail key={name} name={name} onLoading={enableLoading} version={version} />;
});
} }
class Dependencies extends Component { const Dependencies: React.FC<{}> = () => {
public state = { const { packageMeta } = useContext(DetailContext);
tabPosition: 0,
};
public render(): ReactElement<HTMLElement> { if (!packageMeta) {
return ( throw new Error('packageMeta is required at DetailContext');
<DetailContextConsumer>
{packageMeta => {
return this.renderDependencies(packageMeta as VersionPageConsumerProps);
}}
</DetailContextConsumer>
);
} }
private checkDependencyLength<T>(dependency: Record<string, T> = {}): boolean {
return Object.keys(dependency).length > 0;
}
private renderDependencies({ packageMeta }): ReactElement<HTMLElement> {
const { latest } = packageMeta; const { latest } = packageMeta;
const { dependencies, devDependencies, peerDependencies, name } = latest; // FIXME: add dependencies to package meta type
const dependencyMap = { dependencies, devDependencies, peerDependencies };
const dependencyList = Object.keys(dependencyMap).reduce((result, value, key) => {
const selectedDepndency = dependencyMap[value];
if (selectedDepndency && this.checkDependencyLength(selectedDepndency)) {
// @ts-ignore // @ts-ignore
result.push(<DependencyBlock className="dependency-block" dependencies={selectedDepndency} key={key} title={value} />); const { dependencies, devDependencies, peerDependencies, name } = latest;
} const dependencyMap = { dependencies, devDependencies, peerDependencies };
return result; const hasDependencies = hasKeys(dependencies) || hasKeys(devDependencies) || hasKeys(peerDependencies);
}, []);
if (dependencyList.length) { if (hasDependencies) {
return <Fragment>{dependencyList}</Fragment>; return (
<>
{Object.entries(dependencyMap).map(([dependencyType, dependencies]) => {
if (!dependencies || Object.keys(dependencies).length === 0) {
return null;
} }
return <DependencyBlock dependencies={dependencies} key={dependencyType} title={dependencyType} />;
})}
</>
);
}
return <NoItems className="no-dependencies" text={`${name} has no dependencies.`} />; return <NoItems className="no-dependencies" text={`${name} has no dependencies.`} />;
} };
}
export default Dependencies; export default Dependencies;

View File

@ -1,33 +1,26 @@
import styled from 'react-emotion'; import styled from '@emotion/styled';
import Card from '@material-ui/core/Card';
import Typography from '@material-ui/core/Typography';
import Chip from '@material-ui/core/Chip';
import { fontWeight } from '../../utils/styles/sizes'; import { fontWeight } from '../../utils/styles/sizes';
import Text from '../../muiComponents/Text';
import Card from '../../muiComponents/Card';
import Chip from '../../muiComponents/Chip';
export const CardWrap = styled(Card)({ export const CardWrap = styled(Card)({
'&&': {
margin: '0 0 16px', margin: '0 0 16px',
},
}); });
export const Heading = styled(Typography)({ export const StyledText = styled(Text)({
'&&': {
fontWeight: fontWeight.bold, fontWeight: fontWeight.bold,
textTransform: 'capitalize', textTransform: 'capitalize',
},
}); });
export const Tags = styled('div')({ export const Tags = styled('div')({
'&&': {
display: 'flex', display: 'flex',
justifyContent: 'start', justifyContent: 'start',
flexWrap: 'wrap', flexWrap: 'wrap',
margin: '0 -5px', margin: '0 -5px',
},
}); });
export const Tag = styled(Chip)({ export const Tag = styled(Chip)({
'&&': {
margin: '5px', margin: '5px',
},
}); });

View File

@ -0,0 +1,13 @@
import React from 'react';
import { render } from '../../utils/test-react-testing-library';
import DetailContainer from './DetailContainer';
describe('DetailContainer', () => {
test('renders correctly', () => {
const { container } = render(<DetailContainer />);
expect(container.firstChild).toMatchSnapshot();
});
test.todo('should test click on tabs');
});

View File

@ -1,77 +1,33 @@
import React, { Component, ReactElement, Fragment } from 'react'; import React, { useCallback, useState, ChangeEvent, useContext } from 'react';
import { DetailContextConsumer, VersionPageConsumerProps } from '../../pages/Version'; import { DetailContext } from '../../pages/Version';
import Readme from '../Readme'; import Box from '../../muiComponents/Box';
import Versions from '../Versions';
import { preventXSS } from '../../utils/sec-utils';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import { Content } from './styles';
import Dependencies from '../Dependencies';
import UpLinks from '../UpLinks';
interface DetailContainerState { import DetailContainerTabs from './DetailContainerTabs';
tabPosition: number; import DetailContainerContent from './DetailContainerContent';
} import { TabPosition } from './tabs';
export const README_LABEL = 'Readme'; const DetailContainer: React.FC = () => {
export const DEPS_LABEL = 'Dependencies'; const [tabPosition, setTabPosition] = useState(TabPosition.README);
export const VERSION_LABEL = 'Versions'; const detailContext = useContext(DetailContext);
export const UPLINKS_LABEL = 'Uplinks'; const { readMe } = detailContext;
class DetailContainer<P> extends Component<P, DetailContainerState> { const handleChangeTabPosition = useCallback(
public state = { (event: ChangeEvent<{}>) => {
tabPosition: 0,
};
public render(): ReactElement<HTMLElement> {
return (
<DetailContextConsumer>
{context => {
return this.renderTabs(context as VersionPageConsumerProps);
}}
</DetailContextConsumer>
);
}
private handleChange = (event: React.ChangeEvent<{}>, tabPosition: number) => {
event.preventDefault(); event.preventDefault();
this.setState({ tabPosition }); const eventTarget = event.target as HTMLSpanElement;
}; const chosentab = eventTarget.innerText as TabPosition;
setTabPosition(TabPosition[chosentab]);
private renderListTabs(tabPosition: number): React.ReactElement<HTMLElement> { },
return ( [setTabPosition]
<Tabs indicatorColor={'primary'} onChange={this.handleChange} textColor={'primary'} value={tabPosition} variant={'fullWidth'}>
<Tab data-testid={'readme-tab'} id={'readme-tab'} label={README_LABEL} />
<Tab data-testid={'dependencies-tab'} id={'dependencies-tab'} label={DEPS_LABEL} />
<Tab data-testid={'versions-tab'} id={'versions-tab'} label={VERSION_LABEL} />
<Tab data-testid={'uplinks-tab'} id={'uplinks-tab'} label={UPLINKS_LABEL} />
</Tabs>
); );
}
private renderTabs = ({ readMe }) => {
const { tabPosition } = this.state;
return ( return (
<Fragment> <Box component="div" display="flex" flexDirection="column" padding={2}>
<Content> <DetailContainerTabs onChangeTabPosition={handleChangeTabPosition} tabPosition={tabPosition} />
{this.renderListTabs(tabPosition)} <DetailContainerContent readDescription={readMe} tabPosition={tabPosition} />
<br /> </Box>
{tabPosition === 0 && this.renderReadme(readMe)}
{tabPosition === 1 && <Dependencies />}
{tabPosition === 2 && <Versions />}
{tabPosition === 3 && <UpLinks />}
</Content>
</Fragment>
); );
}; };
private renderReadme = (readMe: string): ReactElement<HTMLElement> => {
const encodedReadme = preventXSS(readMe);
return <Readme description={encodedReadme} />;
};
}
export default DetailContainer; export default DetailContainer;

View File

@ -0,0 +1,30 @@
import React from 'react';
import Dependencies from '../Dependencies';
import UpLinks from '../UpLinks';
import Versions from '../Versions';
import DetailContainerContentReadme from './DetailContainerContentReadme';
import { TabPosition } from './tabs';
interface Props {
tabPosition: TabPosition;
readDescription?: string;
}
const DetailContainerContent: React.FC<Props> = ({ tabPosition, readDescription }) => {
switch (tabPosition) {
case TabPosition.README:
return <DetailContainerContentReadme description={readDescription} />;
case TabPosition.UPLINKS:
return <UpLinks />;
case TabPosition.VERSIONS:
return <Versions />;
case TabPosition.DEPENDENCIES:
return <Dependencies />;
default:
return null;
}
};
export default DetailContainerContent;

View File

@ -0,0 +1,16 @@
import React from 'react';
import { preventXSS } from '../../utils/sec-utils';
import Readme from '../Readme';
interface Props {
description?: string;
}
const DetailContainerContentReadme: React.FC<Props> = ({ description }) => {
if (!description) return null;
const encodedReadme = preventXSS(description);
return <Readme description={encodedReadme} />;
};
export default DetailContainerContentReadme;

View File

@ -0,0 +1,44 @@
import React, { ChangeEvent, useState, useEffect } from 'react';
import styled from '@emotion/styled';
import { default as MuiTabs } from '../../muiComponents/Tabs';
import Tab from '../../muiComponents/Tab';
import { TabPosition } from './tabs';
interface Props {
tabPosition: TabPosition;
onChangeTabPosition: (event: ChangeEvent<{}>) => void;
}
const Tabs = styled(MuiTabs)({
marginBottom: 16,
});
const getTabIndex = (tabPosition: TabPosition): number =>
Object.keys(TabPosition).findIndex(position => position === String(tabPosition).toUpperCase());
const DetailContainerTabs: React.FC<Props> = ({ tabPosition, onChangeTabPosition }) => {
const [tabPositionIndex, setTabPositionIndex] = useState(0);
useEffect(() => {
const tabIndex = getTabIndex(tabPosition);
setTabPositionIndex(tabIndex);
}, [tabPosition]);
return (
<Tabs
indicatorColor={'primary'}
onChange={onChangeTabPosition}
textColor={'primary'}
value={tabPositionIndex}
variant={'fullWidth'}>
<Tab data-testid={'readme-tab'} id={'readme-tab'} label={TabPosition.README} />
<Tab data-testid={'dependencies-tab'} id={'dependencies-tab'} label={TabPosition.DEPENDENCIES} />
<Tab data-testid={'versions-tab'} id={'versions-tab'} label={TabPosition.VERSIONS} />
<Tab data-testid={'uplinks-tab'} id={'uplinks-tab'} label={TabPosition.UPLINKS} />
</Tabs>
);
};
export default DetailContainerTabs;

View File

@ -0,0 +1,102 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`DetailContainer renders correctly 1`] = `
.emotion-0 {
margin-bottom: 16px;
}
<div
class="MuiBox-root MuiBox-root-2"
>
<div
class="MuiTabs-root emotion-0 emotion-1"
>
<div
class="MuiTabs-scroller MuiTabs-fixed"
style="overflow: hidden;"
>
<div
class="MuiTabs-flexContainer"
role="tablist"
>
<button
aria-selected="true"
class="MuiButtonBase-root MuiTab-root MuiTab-textColorPrimary Mui-selected MuiTab-fullWidth"
data-testid="readme-tab"
id="readme-tab"
role="tab"
tabindex="0"
type="button"
>
<span
class="MuiTab-wrapper"
>
Readme
</span>
<span
class="MuiTouchRipple-root"
/>
</button>
<button
aria-selected="false"
class="MuiButtonBase-root MuiTab-root MuiTab-textColorPrimary MuiTab-fullWidth"
data-testid="dependencies-tab"
id="dependencies-tab"
role="tab"
tabindex="0"
type="button"
>
<span
class="MuiTab-wrapper"
>
Dependencies
</span>
<span
class="MuiTouchRipple-root"
/>
</button>
<button
aria-selected="false"
class="MuiButtonBase-root MuiTab-root MuiTab-textColorPrimary MuiTab-fullWidth"
data-testid="versions-tab"
id="versions-tab"
role="tab"
tabindex="0"
type="button"
>
<span
class="MuiTab-wrapper"
>
Versions
</span>
<span
class="MuiTouchRipple-root"
/>
</button>
<button
aria-selected="false"
class="MuiButtonBase-root MuiTab-root MuiTab-textColorPrimary MuiTab-fullWidth"
data-testid="uplinks-tab"
id="uplinks-tab"
role="tab"
tabindex="0"
type="button"
>
<span
class="MuiTab-wrapper"
>
Uplinks
</span>
<span
class="MuiTouchRipple-root"
/>
</button>
</div>
<span
class="PrivateTabIndicator-root-27 PrivateTabIndicator-colorPrimary-28 MuiTabs-indicator"
style="left: 0px; width: 0px;"
/>
</div>
</div>
</div>
`;

View File

@ -1,7 +0,0 @@
import styled from 'react-emotion';
export const Content = styled('div')({
'&&': {
padding: '15px',
},
});

View File

@ -0,0 +1,6 @@
export enum TabPosition {
README = 'Readme',
DEPENDENCIES = 'Dependencies',
VERSIONS = 'Versions',
UPLINKS = 'Uplinks',
}

View File

@ -1,7 +0,0 @@
import { ReactNode } from 'react';
export interface Props {
children: ReactNode;
open: boolean;
onClose: () => void;
}

View File

@ -1,9 +1,5 @@
import React, { ReactElement } from 'react'; import React, { ReactElement } from 'react';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import List from '@material-ui/core/List';
import { ActionBar } from '../ActionBar/ActionBar'; import { ActionBar } from '../ActionBar/ActionBar';
import Author from '../Author'; import Author from '../Author';
import Developers from '../Developers'; import Developers from '../Developers';
@ -11,36 +7,45 @@ import Dist from '../Dist/Dist';
import Engine from '../Engines/Engines'; import Engine from '../Engines/Engines';
import Install from '../Install'; import Install from '../Install';
import Repository from '../Repository/Repository'; import Repository from '../Repository/Repository';
import { DetailContext } from '../../pages/Version'; import { DetailContext } from '../../pages/Version';
import List from '../../muiComponents/List';
import Card from '../../muiComponents/Card';
import CardContent from '../../muiComponents/CardContent';
import { TitleListItem, TitleListItemText } from './styles'; import { TitleListItem, TitleListItemText, PackageDescription, PackageVersion } from './styles';
const renderLatestDescription = (description, version, isLatest: boolean = true) => { const renderLatestDescription = (description, version, isLatest = true): JSX.Element => {
return ( return (
<span> <>
<div>{description}</div> <PackageDescription>{description}</PackageDescription>
{version ? <small>{`${isLatest ? 'Latest v' : 'v'}${version}`}</small> : null} {version ? (
</span> <PackageVersion>
<small>{`${isLatest ? 'Latest v' : 'v'}${version}`}</small>
</PackageVersion>
) : null}
</>
); );
}; };
const renderCopyCLI = () => <Install />; const renderCopyCLI = (): JSX.Element => <Install />;
const renderMaintainers = () => <Developers type="maintainers" />; const renderMaintainers = (): JSX.Element => <Developers type="maintainers" />;
const renderContributors = () => <Developers type="contributors" />; const renderContributors = (): JSX.Element => <Developers type="contributors" />;
const renderRepository = () => <Repository />; const renderRepository = (): JSX.Element => <Repository />;
const renderAuthor = () => <Author />; const renderAuthor = (): JSX.Element => <Author />;
const renderEngine = () => <Engine />; const renderEngine = (): JSX.Element => <Engine />;
const renderDist = () => <Dist />; const renderDist = (): JSX.Element => <Dist />;
const renderActionBar = () => <ActionBar />; const renderActionBar = (): JSX.Element => <ActionBar />;
const renderTitle = (packageName, packageVersion, packageMeta) => { const renderTitle = (packageName, packageVersion, packageMeta): JSX.Element => {
const version = packageVersion ? packageVersion : packageMeta.latest.version; const version = packageVersion ? packageVersion : packageMeta.latest.version;
const isLatest = typeof packageVersion === 'undefined'; const isLatest = typeof packageVersion === 'undefined';
return ( return (
<List className="detail-info"> <List className="detail-info">
<TitleListItem alignItems="flex-start" button={true}> <TitleListItem alignItems="flex-start" button={true}>
<TitleListItemText primary={<b>{packageName}</b>} secondary={renderLatestDescription(packageMeta.latest.description, version, isLatest)} /> <TitleListItemText
primary={<b>{packageName}</b>}
secondary={renderLatestDescription(packageMeta.latest.description, version, isLatest)}
/>
</TitleListItem> </TitleListItem>
</List> </List>
); );
@ -66,7 +71,7 @@ function renderSideBar(packageName, packageVersion, packageMeta): ReactElement<H
); );
} }
const DetailSidebar = () => { const DetailSidebar = (): JSX.Element => {
const { packageName, packageMeta, packageVersion } = React.useContext(DetailContext); const { packageName, packageMeta, packageVersion } = React.useContext(DetailContext);
return renderSideBar(packageName, packageVersion, packageMeta); return renderSideBar(packageName, packageVersion, packageMeta);

View File

@ -1,30 +1,24 @@
import styled from 'react-emotion'; import styled from '@emotion/styled';
import Avatar from '@material-ui/core/Avatar';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import colors from '../../utils/styles/colors'; import ListItem from '../../muiComponents/ListItem';
import ListItemText from '../../muiComponents/ListItemText';
export const TitleListItem = styled(ListItem)({ export const TitleListItem = styled(ListItem)({
'&&': {
paddingLeft: 0, paddingLeft: 0,
paddingRight: 0, paddingRight: 0,
paddingBottom: 0, paddingBottom: 0,
},
}); });
export const TitleListItemText = styled(ListItemText)({ export const TitleListItemText = styled(ListItemText)({
'&&': {
paddingLeft: 0, paddingLeft: 0,
paddingRight: 0, paddingRight: 0,
paddingTop: '8px', paddingTop: '8px',
},
}); });
export const TitleAvatar = styled(Avatar)({ export const PackageDescription = styled('span')({
'&&': { display: 'block',
color: colors.greySuperLight, });
backgroundColor: colors.primary,
textTransform: 'capitalize', export const PackageVersion = styled('span')({
}, display: 'block',
}); });

View File

@ -1,8 +1,10 @@
import React from 'react'; import React from 'react';
import { mount } from 'enzyme';
import { mount } from '../../utils/test-enzyme';
import { DetailContextProvider } from '../../pages/Version';
import Developers, { DevelopersType } from './Developers'; import Developers, { DevelopersType } from './Developers';
import { Fab } from './styles'; import { Fab } from './styles';
import { DetailContextProvider } from '../../pages/Version';
describe('test Developers', () => { describe('test Developers', () => {
const packageMeta = { const packageMeta = {

View File

@ -3,7 +3,8 @@ import Add from '@material-ui/icons/Add';
import { DetailContext } from '../../pages/Version'; import { DetailContext } from '../../pages/Version';
import { AvatarTooltip } from '../AvatarTooltip'; import { AvatarTooltip } from '../AvatarTooltip';
import { Details, Heading, Content, Fab } from './styles';
import { Details, StyledText, Content, Fab } from './styles';
export type DevelopersType = 'contributors' | 'maintainers'; export type DevelopersType = 'contributors' | 'maintainers';
@ -18,22 +19,22 @@ const Developers: FC<Props> = ({ type, visibleMax }) => {
const [visibleDevs, setVisibleDevs] = React.useState<number>(visibleMax || VISIBLE_MAX); const [visibleDevs, setVisibleDevs] = React.useState<number>(visibleMax || VISIBLE_MAX);
const { packageMeta } = React.useContext(DetailContext); const { packageMeta } = React.useContext(DetailContext);
const handleLoadMore = () => { const handleLoadMore = (): void => {
setVisibleDevs(visibleDevs + VISIBLE_MAX); setVisibleDevs(visibleDevs + VISIBLE_MAX);
}; };
const renderDeveloperDetails = ({ name, avatar, email }, packageMeta) => { const renderDeveloperDetails = ({ name, avatar, email }, packageMeta): JSX.Element => {
const { name: packageName, version } = packageMeta.latest; const { name: packageName, version } = packageMeta.latest;
return <AvatarTooltip avatar={avatar} email={email} name={name} packageName={packageName} version={version} />; return <AvatarTooltip avatar={avatar} email={email} name={name} packageName={packageName} version={version} />;
}; };
const renderDevelopers = (developers, packageMeta) => { const renderDevelopers = (developers, packageMeta): JSX.Element => {
const listVisibleDevelopers = developers.slice(0, visibleDevs); const listVisibleDevelopers = developers.slice(0, visibleDevs);
return ( return (
<Fragment> <Fragment>
<Heading variant={'subtitle1'}>{type}</Heading> <StyledText variant={'subtitle1'}>{type}</StyledText>
<Content> <Content>
{listVisibleDevelopers.map(developer => ( {listVisibleDevelopers.map(developer => (
<Details key={developer.email}>{renderDeveloperDetails(developer, packageMeta)}</Details> <Details key={developer.email}>{renderDeveloperDetails(developer, packageMeta)}</Details>

View File

@ -1,18 +1,57 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`test Developers should render the component for contributors with items 1`] = ` exports[`test Developers should render the component for contributors with items 1`] = `
.emotion-0 {
font-weight: 700;
margin-bottom: 10px;
text-transform: capitalize;
}
.emotion-12 {
margin: 10px 0 10px 0;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-wrap: wrap;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
}
.emotion-12 > * {
margin: 5px;
}
.emotion-8 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
<Developers <Developers
type="contributors" type="contributors"
> >
<Styled(WithStyles(ForwardRef(Typography))) <StyledText
variant="subtitle1"
>
<ForwardRef(Text)
className="emotion-0 emotion-1"
variant="subtitle1" variant="subtitle1"
> >
<WithStyles(ForwardRef(Typography)) <WithStyles(ForwardRef(Typography))
className="css-18tsvng emotion-0" className="emotion-0 emotion-1"
variant="subtitle1" variant="subtitle1"
> >
<ForwardRef(Typography) <ForwardRef(Typography)
className="css-18tsvng emotion-0" className="emotion-0 emotion-1"
classes={ classes={
Object { Object {
"alignCenter": "MuiTypography-alignCenter", "alignCenter": "MuiTypography-alignCenter",
@ -50,32 +89,37 @@ exports[`test Developers should render the component for contributors with items
variant="subtitle1" variant="subtitle1"
> >
<h6 <h6
className="MuiTypography-root css-18tsvng emotion-0 MuiTypography-subtitle1" className="MuiTypography-root emotion-0 emotion-1 MuiTypography-subtitle1"
> >
contributors contributors
</h6> </h6>
</ForwardRef(Typography)> </ForwardRef(Typography)>
</WithStyles(ForwardRef(Typography))> </WithStyles(ForwardRef(Typography))>
</Styled(WithStyles(ForwardRef(Typography)))> </ForwardRef(Text)>
<Styled(div)> </StyledText>
<Content>
<div <div
className="css-mkcn9c emotion-5" className="emotion-12 emotion-13"
> >
<Styled(span) <Details
key="dave.methvin@gmail.com" key="dave.methvin@gmail.com"
> >
<span <span
className="css-dvxtzn emotion-3" className="emotion-8 emotion-9"
> >
<AvatarTooltip <AvatarTooltip
email="dave.methvin@gmail.com" email="dave.methvin@gmail.com"
name="dmethvin" name="dmethvin"
version="1.0.0" version="1.0.0"
> >
<WithStyles(Tooltip) <ForwardRef(ToolTip)
title="dmethvin" title="dmethvin"
> >
<Tooltip <WithStyles(ForwardRef(Tooltip))
innerRef={null}
title="dmethvin"
>
<ForwardRef(Tooltip)
classes={ classes={
Object { Object {
"popper": "MuiTooltip-popper", "popper": "MuiTooltip-popper",
@ -102,6 +146,9 @@ exports[`test Developers should render the component for contributors with items
onTouchStart={[Function]} onTouchStart={[Function]}
target="_top" target="_top"
title="dmethvin" title="dmethvin"
>
<ForwardRef(Avatar)
aria-label="dmethvin"
> >
<WithStyles(ForwardRef(Avatar)) <WithStyles(ForwardRef(Avatar))
aria-label="dmethvin" aria-label="dmethvin"
@ -110,18 +157,22 @@ exports[`test Developers should render the component for contributors with items
aria-label="dmethvin" aria-label="dmethvin"
classes={ classes={
Object { Object {
"circle": "MuiAvatar-circle",
"colorDefault": "MuiAvatar-colorDefault", "colorDefault": "MuiAvatar-colorDefault",
"img": "MuiAvatar-img", "img": "MuiAvatar-img",
"root": "MuiAvatar-root", "root": "MuiAvatar-root",
"rounded": "MuiAvatar-rounded",
"square": "MuiAvatar-square",
} }
} }
> >
<div <div
aria-label="dmethvin" aria-label="dmethvin"
className="MuiAvatar-root MuiAvatar-colorDefault" className="MuiAvatar-root MuiAvatar-circle MuiAvatar-colorDefault"
/> />
</ForwardRef(Avatar)> </ForwardRef(Avatar)>
</WithStyles(ForwardRef(Avatar))> </WithStyles(ForwardRef(Avatar))>
</ForwardRef(Avatar)>
</a> </a>
<ForwardRef(Popper) <ForwardRef(Popper)
anchorEl={ anchorEl={
@ -133,7 +184,7 @@ exports[`test Developers should render the component for contributors with items
> >
<div <div
aria-label="dmethvin" aria-label="dmethvin"
class="MuiAvatar-root MuiAvatar-colorDefault" class="MuiAvatar-root MuiAvatar-circle MuiAvatar-colorDefault"
/> />
</a> </a>
} }
@ -143,26 +194,31 @@ exports[`test Developers should render the component for contributors with items
placement="bottom" placement="bottom"
transition={true} transition={true}
/> />
</Tooltip> </ForwardRef(Tooltip)>
</WithStyles(Tooltip)> </WithStyles(ForwardRef(Tooltip))>
</ForwardRef(ToolTip)>
</AvatarTooltip> </AvatarTooltip>
</span> </span>
</Styled(span)> </Details>
<Styled(span) <Details
key="m.goleb@gmail.com" key="m.goleb@gmail.com"
> >
<span <span
className="css-dvxtzn emotion-3" className="emotion-8 emotion-9"
> >
<AvatarTooltip <AvatarTooltip
email="m.goleb@gmail.com" email="m.goleb@gmail.com"
name="mgol" name="mgol"
version="1.0.0" version="1.0.0"
> >
<WithStyles(Tooltip) <ForwardRef(ToolTip)
title="mgol" title="mgol"
> >
<Tooltip <WithStyles(ForwardRef(Tooltip))
innerRef={null}
title="mgol"
>
<ForwardRef(Tooltip)
classes={ classes={
Object { Object {
"popper": "MuiTooltip-popper", "popper": "MuiTooltip-popper",
@ -189,6 +245,9 @@ exports[`test Developers should render the component for contributors with items
onTouchStart={[Function]} onTouchStart={[Function]}
target="_top" target="_top"
title="mgol" title="mgol"
>
<ForwardRef(Avatar)
aria-label="mgol"
> >
<WithStyles(ForwardRef(Avatar)) <WithStyles(ForwardRef(Avatar))
aria-label="mgol" aria-label="mgol"
@ -197,18 +256,22 @@ exports[`test Developers should render the component for contributors with items
aria-label="mgol" aria-label="mgol"
classes={ classes={
Object { Object {
"circle": "MuiAvatar-circle",
"colorDefault": "MuiAvatar-colorDefault", "colorDefault": "MuiAvatar-colorDefault",
"img": "MuiAvatar-img", "img": "MuiAvatar-img",
"root": "MuiAvatar-root", "root": "MuiAvatar-root",
"rounded": "MuiAvatar-rounded",
"square": "MuiAvatar-square",
} }
} }
> >
<div <div
aria-label="mgol" aria-label="mgol"
className="MuiAvatar-root MuiAvatar-colorDefault" className="MuiAvatar-root MuiAvatar-circle MuiAvatar-colorDefault"
/> />
</ForwardRef(Avatar)> </ForwardRef(Avatar)>
</WithStyles(ForwardRef(Avatar))> </WithStyles(ForwardRef(Avatar))>
</ForwardRef(Avatar)>
</a> </a>
<ForwardRef(Popper) <ForwardRef(Popper)
anchorEl={ anchorEl={
@ -220,7 +283,7 @@ exports[`test Developers should render the component for contributors with items
> >
<div <div
aria-label="mgol" aria-label="mgol"
class="MuiAvatar-root MuiAvatar-colorDefault" class="MuiAvatar-root MuiAvatar-circle MuiAvatar-colorDefault"
/> />
</a> </a>
} }
@ -230,29 +293,69 @@ exports[`test Developers should render the component for contributors with items
placement="bottom" placement="bottom"
transition={true} transition={true}
/> />
</Tooltip> </ForwardRef(Tooltip)>
</WithStyles(Tooltip)> </WithStyles(ForwardRef(Tooltip))>
</ForwardRef(ToolTip)>
</AvatarTooltip> </AvatarTooltip>
</span> </span>
</Styled(span)> </Details>
</div> </div>
</Styled(div)> </Content>
</Developers> </Developers>
`; `;
exports[`test Developers should render the component for maintainers with items 1`] = ` exports[`test Developers should render the component for maintainers with items 1`] = `
.emotion-0 {
font-weight: 700;
margin-bottom: 10px;
text-transform: capitalize;
}
.emotion-12 {
margin: 10px 0 10px 0;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-wrap: wrap;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
}
.emotion-12 > * {
margin: 5px;
}
.emotion-8 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
<Developers <Developers
type="maintainers" type="maintainers"
> >
<Styled(WithStyles(ForwardRef(Typography))) <StyledText
variant="subtitle1"
>
<ForwardRef(Text)
className="emotion-0 emotion-1"
variant="subtitle1" variant="subtitle1"
> >
<WithStyles(ForwardRef(Typography)) <WithStyles(ForwardRef(Typography))
className="css-18tsvng emotion-0" className="emotion-0 emotion-1"
variant="subtitle1" variant="subtitle1"
> >
<ForwardRef(Typography) <ForwardRef(Typography)
className="css-18tsvng emotion-0" className="emotion-0 emotion-1"
classes={ classes={
Object { Object {
"alignCenter": "MuiTypography-alignCenter", "alignCenter": "MuiTypography-alignCenter",
@ -290,32 +393,37 @@ exports[`test Developers should render the component for maintainers with items
variant="subtitle1" variant="subtitle1"
> >
<h6 <h6
className="MuiTypography-root css-18tsvng emotion-0 MuiTypography-subtitle1" className="MuiTypography-root emotion-0 emotion-1 MuiTypography-subtitle1"
> >
maintainers maintainers
</h6> </h6>
</ForwardRef(Typography)> </ForwardRef(Typography)>
</WithStyles(ForwardRef(Typography))> </WithStyles(ForwardRef(Typography))>
</Styled(WithStyles(ForwardRef(Typography)))> </ForwardRef(Text)>
<Styled(div)> </StyledText>
<Content>
<div <div
className="css-mkcn9c emotion-5" className="emotion-12 emotion-13"
> >
<Styled(span) <Details
key="dave.methvin@gmail.com" key="dave.methvin@gmail.com"
> >
<span <span
className="css-dvxtzn emotion-3" className="emotion-8 emotion-9"
> >
<AvatarTooltip <AvatarTooltip
email="dave.methvin@gmail.com" email="dave.methvin@gmail.com"
name="dmethvin" name="dmethvin"
version="1.0.0" version="1.0.0"
> >
<WithStyles(Tooltip) <ForwardRef(ToolTip)
title="dmethvin" title="dmethvin"
> >
<Tooltip <WithStyles(ForwardRef(Tooltip))
innerRef={null}
title="dmethvin"
>
<ForwardRef(Tooltip)
classes={ classes={
Object { Object {
"popper": "MuiTooltip-popper", "popper": "MuiTooltip-popper",
@ -342,6 +450,9 @@ exports[`test Developers should render the component for maintainers with items
onTouchStart={[Function]} onTouchStart={[Function]}
target="_top" target="_top"
title="dmethvin" title="dmethvin"
>
<ForwardRef(Avatar)
aria-label="dmethvin"
> >
<WithStyles(ForwardRef(Avatar)) <WithStyles(ForwardRef(Avatar))
aria-label="dmethvin" aria-label="dmethvin"
@ -350,18 +461,22 @@ exports[`test Developers should render the component for maintainers with items
aria-label="dmethvin" aria-label="dmethvin"
classes={ classes={
Object { Object {
"circle": "MuiAvatar-circle",
"colorDefault": "MuiAvatar-colorDefault", "colorDefault": "MuiAvatar-colorDefault",
"img": "MuiAvatar-img", "img": "MuiAvatar-img",
"root": "MuiAvatar-root", "root": "MuiAvatar-root",
"rounded": "MuiAvatar-rounded",
"square": "MuiAvatar-square",
} }
} }
> >
<div <div
aria-label="dmethvin" aria-label="dmethvin"
className="MuiAvatar-root MuiAvatar-colorDefault" className="MuiAvatar-root MuiAvatar-circle MuiAvatar-colorDefault"
/> />
</ForwardRef(Avatar)> </ForwardRef(Avatar)>
</WithStyles(ForwardRef(Avatar))> </WithStyles(ForwardRef(Avatar))>
</ForwardRef(Avatar)>
</a> </a>
<ForwardRef(Popper) <ForwardRef(Popper)
anchorEl={ anchorEl={
@ -373,7 +488,7 @@ exports[`test Developers should render the component for maintainers with items
> >
<div <div
aria-label="dmethvin" aria-label="dmethvin"
class="MuiAvatar-root MuiAvatar-colorDefault" class="MuiAvatar-root MuiAvatar-circle MuiAvatar-colorDefault"
/> />
</a> </a>
} }
@ -383,26 +498,31 @@ exports[`test Developers should render the component for maintainers with items
placement="bottom" placement="bottom"
transition={true} transition={true}
/> />
</Tooltip> </ForwardRef(Tooltip)>
</WithStyles(Tooltip)> </WithStyles(ForwardRef(Tooltip))>
</ForwardRef(ToolTip)>
</AvatarTooltip> </AvatarTooltip>
</span> </span>
</Styled(span)> </Details>
<Styled(span) <Details
key="m.goleb@gmail.com" key="m.goleb@gmail.com"
> >
<span <span
className="css-dvxtzn emotion-3" className="emotion-8 emotion-9"
> >
<AvatarTooltip <AvatarTooltip
email="m.goleb@gmail.com" email="m.goleb@gmail.com"
name="mgol" name="mgol"
version="1.0.0" version="1.0.0"
> >
<WithStyles(Tooltip) <ForwardRef(ToolTip)
title="mgol" title="mgol"
> >
<Tooltip <WithStyles(ForwardRef(Tooltip))
innerRef={null}
title="mgol"
>
<ForwardRef(Tooltip)
classes={ classes={
Object { Object {
"popper": "MuiTooltip-popper", "popper": "MuiTooltip-popper",
@ -429,6 +549,9 @@ exports[`test Developers should render the component for maintainers with items
onTouchStart={[Function]} onTouchStart={[Function]}
target="_top" target="_top"
title="mgol" title="mgol"
>
<ForwardRef(Avatar)
aria-label="mgol"
> >
<WithStyles(ForwardRef(Avatar)) <WithStyles(ForwardRef(Avatar))
aria-label="mgol" aria-label="mgol"
@ -437,18 +560,22 @@ exports[`test Developers should render the component for maintainers with items
aria-label="mgol" aria-label="mgol"
classes={ classes={
Object { Object {
"circle": "MuiAvatar-circle",
"colorDefault": "MuiAvatar-colorDefault", "colorDefault": "MuiAvatar-colorDefault",
"img": "MuiAvatar-img", "img": "MuiAvatar-img",
"root": "MuiAvatar-root", "root": "MuiAvatar-root",
"rounded": "MuiAvatar-rounded",
"square": "MuiAvatar-square",
} }
} }
> >
<div <div
aria-label="mgol" aria-label="mgol"
className="MuiAvatar-root MuiAvatar-colorDefault" className="MuiAvatar-root MuiAvatar-circle MuiAvatar-colorDefault"
/> />
</ForwardRef(Avatar)> </ForwardRef(Avatar)>
</WithStyles(ForwardRef(Avatar))> </WithStyles(ForwardRef(Avatar))>
</ForwardRef(Avatar)>
</a> </a>
<ForwardRef(Popper) <ForwardRef(Popper)
anchorEl={ anchorEl={
@ -460,7 +587,7 @@ exports[`test Developers should render the component for maintainers with items
> >
<div <div
aria-label="mgol" aria-label="mgol"
class="MuiAvatar-root MuiAvatar-colorDefault" class="MuiAvatar-root MuiAvatar-circle MuiAvatar-colorDefault"
/> />
</a> </a>
} }
@ -470,13 +597,14 @@ exports[`test Developers should render the component for maintainers with items
placement="bottom" placement="bottom"
transition={true} transition={true}
/> />
</Tooltip> </ForwardRef(Tooltip)>
</WithStyles(Tooltip)> </WithStyles(ForwardRef(Tooltip))>
</ForwardRef(ToolTip)>
</AvatarTooltip> </AvatarTooltip>
</span> </span>
</Styled(span)> </Details>
</div> </div>
</Styled(div)> </Content>
</Developers> </Developers>
`; `;

View File

@ -1,9 +1,9 @@
import styled from 'react-emotion'; import styled from '@emotion/styled';
import Typography from '@material-ui/core/Typography';
import { default as MuiFab } from '@material-ui/core/Fab';
import colors from '../../utils/styles/colors';
import { fontWeight } from '../../utils/styles/sizes'; import { fontWeight } from '../../utils/styles/sizes';
import Text from '../../muiComponents/Text';
import FloatingActionButton from '../../muiComponents/FloatingActionButton';
import { Theme } from '../../design-tokens/theme';
export const Details = styled('span')({ export const Details = styled('span')({
display: 'flex', display: 'flex',
@ -20,17 +20,13 @@ export const Content = styled('div')({
}, },
}); });
export const Heading = styled(Typography)({ export const StyledText = styled(Text)({
'&&': {
fontWeight: fontWeight.bold, fontWeight: fontWeight.bold,
marginBottom: '10px', marginBottom: '10px',
textTransform: 'capitalize', textTransform: 'capitalize',
},
}); });
export const Fab = styled(MuiFab)({ export const Fab = styled(FloatingActionButton)<{ theme?: Theme }>(props => ({
'&&': { backgroundColor: props.theme && props.theme.palette.primary.main,
backgroundColor: colors.primary, color: props.theme && props.theme.palette.white,
color: colors.white, }));
},
});

View File

@ -1,30 +1,17 @@
import React from 'react'; import React from 'react';
import { mount } from 'enzyme';
import { mount } from '../../utils/test-enzyme';
import { DetailContext } from '../../pages/Version';
import Dist from './Dist'; import Dist from './Dist';
const mockPackageMeta = jest.fn(() => ({ const withDistComponent = (packageMeta: React.ContextType<typeof DetailContext>['packageMeta']): JSX.Element => (
latest: { <DetailContext.Provider value={{ packageMeta }}>
homepage: 'https://verdaccio.tld', <Dist />
bugs: { </DetailContext.Provider>
url: 'https://verdaccio.tld/bugs', );
},
dist: {
tarball: 'https://verdaccio.tld/download',
},
},
}));
jest.mock('../../pages/Version', () => ({
DetailContextConsumer: component => {
return component.children({ packageMeta: mockPackageMeta() });
},
}));
describe('<Dist /> component', () => { describe('<Dist /> component', () => {
beforeEach(() => {
jest.resetModules();
});
test('should render the component in default state', () => { test('should render the component in default state', () => {
const packageMeta = { const packageMeta = {
latest: { latest: {
@ -36,12 +23,10 @@ describe('<Dist /> component', () => {
}, },
license: '', license: '',
}, },
_uplinks: {},
}; };
// @ts-ignore const wrapper = mount(withDistComponent(packageMeta));
mockPackageMeta.mockImplementation(() => packageMeta);
const wrapper = mount(<Dist />);
expect(wrapper.html()).toMatchSnapshot(); expect(wrapper.html()).toMatchSnapshot();
}); });
@ -56,12 +41,10 @@ describe('<Dist /> component', () => {
}, },
license: 'MIT', license: 'MIT',
}, },
_uplinks: {},
}; };
// @ts-ignore const wrapper = mount(withDistComponent(packageMeta));
mockPackageMeta.mockImplementation(() => packageMeta);
const wrapper = mount(<Dist />);
expect(wrapper.html()).toMatchSnapshot(); expect(wrapper.html()).toMatchSnapshot();
}); });
@ -79,12 +62,10 @@ describe('<Dist /> component', () => {
url: 'https://www.opensource.org/licenses/mit-license.php', url: 'https://www.opensource.org/licenses/mit-license.php',
}, },
}, },
_uplinks: {},
}; };
// @ts-ignore const wrapper = mount(withDistComponent(packageMeta));
mockPackageMeta.mockImplementation(() => packageMeta);
const wrapper = mount(<Dist />);
expect(wrapper.html()).toMatchSnapshot(); expect(wrapper.html()).toMatchSnapshot();
}); });
}); });

View File

@ -1,56 +1,46 @@
import React, { Component } from 'react'; import React, { FC, useContext } from 'react';
import List from '@material-ui/core/List'; import { DetailContext } from '../../pages/Version';
import { VersionPageConsumerProps, DetailContextConsumer } from '../../pages/Version';
import { Heading, DistListItem, DistChips } from './styles';
import fileSizeSI from '../../utils/file-size'; import fileSizeSI from '../../utils/file-size';
import { PackageMetaInterface } from 'types/packageMeta';
import { formatLicense } from '../../utils/package'; import { formatLicense } from '../../utils/package';
import List from '../../muiComponents/List';
class Dist extends Component { import { StyledText, DistListItem, DistChips } from './styles';
public render(): JSX.Element {
return (
<DetailContextConsumer>
{(context: Partial<VersionPageConsumerProps>) => {
return context && context.packageMeta && this.renderDist(context.packageMeta);
}}
</DetailContextConsumer>
);
}
private renderChips(dist, license: PackageMetaInterface['latest']['license']): (JSX.Element | undefined)[] { const DistChip: FC<{ name: string }> = ({ name, children }) =>
const distDict = { children ? (
'file-count': dist.fileCount, <DistChips
size: dist.unpackedSize && fileSizeSI(dist.unpackedSize), // lint rule conflicting with prettier
license, /* eslint-disable react/jsx-wrap-multilines */
}; label={
const chipsList = Object.keys(distDict).map((dist, key) => {
if (!distDict[dist]) return;
const value = dist === 'license' ? formatLicense(distDict[dist]) : distDict[dist];
const label = (
<> <>
{/* eslint-disable-next-line */} <b>{name}</b>
<b>{dist.replace('-', ' ')}</b>: {value} {': '}
{children}
</> </>
); }
return <DistChips key={key} label={label} />; /* eslint-enable */
}); />
) : null;
return chipsList; const Dist: FC = () => {
const { packageMeta } = useContext(DetailContext);
if (!packageMeta) {
return null;
} }
private renderDist = (packageMeta: PackageMetaInterface) => {
const { dist, license } = packageMeta && packageMeta.latest; const { dist, license } = packageMeta && packageMeta.latest;
return ( return (
<List subheader={<Heading variant="subtitle1">{'Latest Distribution'}</Heading>}> <List subheader={<StyledText variant="subtitle1">{'Latest Distribution'}</StyledText>}>
<DistListItem button={true}>{this.renderChips(dist, license)}</DistListItem> <DistListItem button={true}>
<DistChip name="file count">{dist.fileCount}</DistChip>
<DistChip name="size">{dist.unpackedSize && fileSizeSI(dist.unpackedSize)}</DistChip>
<DistChip name="license">{formatLicense(license)}</DistChip>
</DistListItem>
</List> </List>
); );
}; };
}
export default Dist; export default Dist;

View File

@ -1,7 +1,7 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<Dist /> component should render the component in default state 1`] = `"<ul class=\\"MuiList-root MuiList-padding MuiList-subheader\\"><h6 class=\\"MuiTypography-root css-hyrz44 estxrtg0 MuiTypography-subtitle1\\">Latest Distribution</h6><div class=\\"MuiButtonBase-root MuiListItem-root css-z8a2h0 estxrtg1 MuiListItem-gutters MuiListItem-button\\" tabindex=\\"0\\" role=\\"button\\" aria-disabled=\\"false\\"><div class=\\"MuiChip-root css-1le6jk6 estxrtg2\\"><span class=\\"MuiChip-label\\"><b>file count</b>: 7</span></div><div class=\\"MuiChip-root css-1le6jk6 estxrtg2\\"><span class=\\"MuiChip-label\\"><b>size</b>: 10.00 Bytes</span></div><span class=\\"MuiTouchRipple-root\\"></span></div></ul>"`; exports[`<Dist /> component should render the component in default state 1`] = `"<ul class=\\"MuiList-root MuiList-padding MuiList-subheader\\"><h6 class=\\"MuiTypography-root css-1na337r-StyledText estxrtg0 MuiTypography-subtitle1\\">Latest Distribution</h6><div class=\\"MuiButtonBase-root MuiListItem-root css-1mms18p-DistListItem estxrtg1 MuiListItem-gutters MuiListItem-button\\" tabindex=\\"0\\" role=\\"button\\" aria-disabled=\\"false\\"><div class=\\"MuiChip-root css-e2le7v-DistChips estxrtg2\\"><span class=\\"MuiChip-label\\"><b>file count</b>: 7</span></div><div class=\\"MuiChip-root css-e2le7v-DistChips estxrtg2\\"><span class=\\"MuiChip-label\\"><b>size</b>: 10.00 Bytes</span></div><span class=\\"MuiTouchRipple-root\\"></span></div></ul>"`;
exports[`<Dist /> component should render the component with license as object 1`] = `"<ul class=\\"MuiList-root MuiList-padding MuiList-subheader\\"><h6 class=\\"MuiTypography-root css-hyrz44 estxrtg0 MuiTypography-subtitle1\\">Latest Distribution</h6><div class=\\"MuiButtonBase-root MuiListItem-root css-z8a2h0 estxrtg1 MuiListItem-gutters MuiListItem-button\\" tabindex=\\"0\\" role=\\"button\\" aria-disabled=\\"false\\"><div class=\\"MuiChip-root css-1le6jk6 estxrtg2\\"><span class=\\"MuiChip-label\\"><b>file count</b>: 7</span></div><div class=\\"MuiChip-root css-1le6jk6 estxrtg2\\"><span class=\\"MuiChip-label\\"><b>size</b>: 10.00 Bytes</span></div><div class=\\"MuiChip-root css-1le6jk6 estxrtg2\\"><span class=\\"MuiChip-label\\"><b>license</b>: MIT</span></div><span class=\\"MuiTouchRipple-root\\"></span></div></ul>"`; exports[`<Dist /> component should render the component with license as object 1`] = `"<ul class=\\"MuiList-root MuiList-padding MuiList-subheader\\"><h6 class=\\"MuiTypography-root css-1na337r-StyledText estxrtg0 MuiTypography-subtitle1\\">Latest Distribution</h6><div class=\\"MuiButtonBase-root MuiListItem-root css-1mms18p-DistListItem estxrtg1 MuiListItem-gutters MuiListItem-button\\" tabindex=\\"0\\" role=\\"button\\" aria-disabled=\\"false\\"><div class=\\"MuiChip-root css-e2le7v-DistChips estxrtg2\\"><span class=\\"MuiChip-label\\"><b>file count</b>: 7</span></div><div class=\\"MuiChip-root css-e2le7v-DistChips estxrtg2\\"><span class=\\"MuiChip-label\\"><b>size</b>: 10.00 Bytes</span></div><div class=\\"MuiChip-root css-e2le7v-DistChips estxrtg2\\"><span class=\\"MuiChip-label\\"><b>license</b>: MIT</span></div><span class=\\"MuiTouchRipple-root\\"></span></div></ul>"`;
exports[`<Dist /> component should render the component with license as string 1`] = `"<ul class=\\"MuiList-root MuiList-padding MuiList-subheader\\"><h6 class=\\"MuiTypography-root css-hyrz44 estxrtg0 MuiTypography-subtitle1\\">Latest Distribution</h6><div class=\\"MuiButtonBase-root MuiListItem-root css-z8a2h0 estxrtg1 MuiListItem-gutters MuiListItem-button\\" tabindex=\\"0\\" role=\\"button\\" aria-disabled=\\"false\\"><div class=\\"MuiChip-root css-1le6jk6 estxrtg2\\"><span class=\\"MuiChip-label\\"><b>file count</b>: 7</span></div><div class=\\"MuiChip-root css-1le6jk6 estxrtg2\\"><span class=\\"MuiChip-label\\"><b>size</b>: 10.00 Bytes</span></div><div class=\\"MuiChip-root css-1le6jk6 estxrtg2\\"><span class=\\"MuiChip-label\\"><b>license</b>: MIT</span></div><span class=\\"MuiTouchRipple-root\\"></span></div></ul>"`; exports[`<Dist /> component should render the component with license as string 1`] = `"<ul class=\\"MuiList-root MuiList-padding MuiList-subheader\\"><h6 class=\\"MuiTypography-root css-1na337r-StyledText estxrtg0 MuiTypography-subtitle1\\">Latest Distribution</h6><div class=\\"MuiButtonBase-root MuiListItem-root css-1mms18p-DistListItem estxrtg1 MuiListItem-gutters MuiListItem-button\\" tabindex=\\"0\\" role=\\"button\\" aria-disabled=\\"false\\"><div class=\\"MuiChip-root css-e2le7v-DistChips estxrtg2\\"><span class=\\"MuiChip-label\\"><b>file count</b>: 7</span></div><div class=\\"MuiChip-root css-e2le7v-DistChips estxrtg2\\"><span class=\\"MuiChip-label\\"><b>size</b>: 10.00 Bytes</span></div><div class=\\"MuiChip-root css-e2le7v-DistChips estxrtg2\\"><span class=\\"MuiChip-label\\"><b>license</b>: MIT</span></div><span class=\\"MuiTouchRipple-root\\"></span></div></ul>"`;

View File

@ -1,36 +1,28 @@
import styled from 'react-emotion'; import styled from '@emotion/styled';
import { default as MuiFab } from '@material-ui/core/Fab';
import Chip from '@material-ui/core/Chip';
import ListItem from '@material-ui/core/ListItem';
import Typography from '@material-ui/core/Typography';
import colors from '../../utils/styles/colors'; import { Theme } from '../../design-tokens/theme';
import { fontWeight } from '../../utils/styles/sizes'; import { fontWeight } from '../../utils/styles/sizes';
import ListItem from '../../muiComponents/ListItem';
import Text from '../../muiComponents/Text';
import FloatingActionButton from '../../muiComponents/FloatingActionButton';
import Chip from '../../muiComponents/Chip';
export const Heading = styled(Typography)({ export const StyledText = styled(Text)({
'&&': {
fontWeight: fontWeight.bold, fontWeight: fontWeight.bold,
textTransform: 'capitalize', textTransform: 'capitalize',
},
}); });
export const DistListItem = styled(ListItem)({ export const DistListItem = styled(ListItem)({
'&&': {
paddingLeft: 0, paddingLeft: 0,
paddingRight: 0, paddingRight: 0,
},
}); });
export const DistChips = styled(Chip)({ export const DistChips = styled(Chip)({
'&&': { marginRight: 5,
marginRight: '5px',
textTransform: 'capitalize', textTransform: 'capitalize',
},
}); });
export const DownloadButton = styled(MuiFab)({ export const DownloadButton = styled(FloatingActionButton)<{ theme?: Theme }>(props => ({
'&&': { backgroundColor: props.theme && props.theme.palette.primary.main,
backgroundColor: colors.primary, color: props.theme && props.theme.palette.white,
color: colors.white, }));
},
});

View File

@ -1,73 +1,61 @@
import React from 'react'; import React from 'react';
import { mount } from 'enzyme';
import { mount } from '../../utils/test-enzyme';
import { DetailContext } from '../../pages/Version';
import { PackageMetaInterface } from '../../../types/packageMeta';
import Engine from './Engines'; import Engine from './Engines';
jest.mock('./img/node.png', () => ''); jest.mock('./img/node.png', () => '');
jest.mock('../Install/img/npm.svg', () => ''); jest.mock('../Install/img/npm.svg', () => '');
const mockPackageMeta = jest.fn(() => ({ const mockPackageMeta = (engines?: PackageMetaInterface['latest']['engines']): PackageMetaInterface => ({
latest: { latest: {
homepage: 'https://verdaccio.tld', name: 'verdaccio',
bugs: { version: '0.0.0',
url: 'https://verdaccio.tld/bugs',
},
dist: { dist: {
tarball: 'https://verdaccio.tld/download', fileCount: 1,
unpackedSize: 1,
}, },
...(engines && { engines }),
}, },
})); _uplinks: {},
});
jest.mock('../../pages/Version', () => ({
DetailContextConsumer: component => {
return component.children({ packageMeta: mockPackageMeta() });
},
}));
describe('<Engines /> component', () => { describe('<Engines /> component', () => {
beforeEach(() => {
jest.resetAllMocks();
});
test('should render the component in default state', () => { test('should render the component in default state', () => {
const packageMeta = { const packageMeta = mockPackageMeta({
latest: {
engines: {
node: '>= 0.1.98', node: '>= 0.1.98',
npm: '>3', npm: '>3',
}, });
},
};
// @ts-ignore const wrapper = mount(
mockPackageMeta.mockImplementation(() => packageMeta); <DetailContext.Provider value={{ packageMeta }}>
<Engine />
const wrapper = mount(<Engine />); </DetailContext.Provider>
);
expect(wrapper.html()).toMatchSnapshot(); expect(wrapper.html()).toMatchSnapshot();
}); });
test('should render the component when there is no engine key in package meta', () => { test('should render the component when there is no engine key in package meta', () => {
const packageMeta = { const packageMeta = mockPackageMeta();
latest: {},
};
// @ts-ignore const wrapper = mount(
mockPackageMeta.mockImplementation(() => packageMeta); <DetailContext.Provider value={{ packageMeta }}>
<Engine />
const wrapper = mount(<Engine />); </DetailContext.Provider>
expect(wrapper.html()).toEqual(''); );
expect(wrapper.html()).toBeNull();
}); });
test('should render the component when there is no keys in engine in package meta', () => { test('should render the component when there is no keys in engine in package meta', () => {
const packageMeta = { const packageMeta = mockPackageMeta({});
latest: {
engines: {},
},
};
// @ts-ignore const wrapper = mount(
mockPackageMeta.mockImplementation(() => packageMeta); <DetailContext.Provider value={{ packageMeta }}>
<Engine />
const wrapper = mount(<Engine />); </DetailContext.Provider>
expect(wrapper.html()).toEqual(''); );
expect(wrapper.html()).toBeNull();
}); });
}); });

View File

@ -1,73 +1,51 @@
import React, { Component, ReactElement } from 'react'; import React, { useContext } from 'react';
import Avatar from '@material-ui/core/Avatar'; import { DetailContext } from '../../pages/Version';
import Grid from '@material-ui/core/Grid'; import Avatar from '../../muiComponents/Avatar';
import List from '@material-ui/core/List'; import List from '../../muiComponents/List';
import ListItemText from '@material-ui/core/ListItemText';
import { VersionPageConsumerProps, DetailContextConsumer } from '../../pages/Version';
import { Heading, EngineListItem } from './styles';
// @ts-ignore
import node from './img/node.png';
import npm from '../Install/img/npm.svg'; import npm from '../Install/img/npm.svg';
import ListItemText from '../../muiComponents/ListItemText';
import Grid from '../../muiComponents/Grid';
const ICONS = { import { StyledText, EngineListItem } from './styles';
'node-JS': <Avatar src={node} />, import node from './img/node.png';
'NPM-version': <Avatar src={npm} />,
};
class Engine extends Component { const Engine: React.FC = () => {
public render(): ReactElement<HTMLElement> { const { packageMeta } = useContext(DetailContext);
return (
<DetailContextConsumer>
{context => {
return this.renderEngine(context as VersionPageConsumerProps);
}}
</DetailContextConsumer>
);
}
private renderEngine = ({ packageMeta }): ReactElement<HTMLElement> | null => { const engines = packageMeta && packageMeta.latest && packageMeta.latest.engines;
const { engines } = packageMeta.latest;
if (!engines) { if (!engines || (!engines.node && !engines.npm)) {
return null; return null;
} }
const engineDict = { /* eslint-disable react/jsx-max-depth */
'node-JS': engines.node,
'NPM-version': engines.npm,
};
const accumulator: React.ReactNode[] = [];
const items = Object.keys(engineDict).reduce((markup, text, key) => {
const heading = engineDict[text];
if (heading) {
markup.push(
<Grid item={true} key={key} xs={6}>
{this.renderListItems(heading, text)}
</Grid>
);
}
return markup;
}, accumulator);
if (items.length < 1) {
return null;
}
return <Grid container={true}>{items}</Grid>;
};
private renderListItems = (heading, text) => {
return ( return (
<List subheader={<Heading variant={'subtitle1'}>{text.split('-').join(' ')}</Heading>}> <Grid container={true}>
{engines.node && (
<Grid item={true} xs={6}>
<List subheader={<StyledText variant={'subtitle1'}>{'node JS'}</StyledText>}>
<EngineListItem button={true}> <EngineListItem button={true}>
{ICONS[text]} <Avatar src={node} />
<ListItemText primary={heading} /> <ListItemText primary={engines.node} />
</EngineListItem> </EngineListItem>
</List> </List>
</Grid>
)}
{engines.npm && (
<Grid item={true} xs={6}>
<List subheader={<StyledText variant={'subtitle1'}>{'NPM version'}</StyledText>}>
<EngineListItem button={true}>
<Avatar src={npm} />
<ListItemText primary={engines.npm} />
</EngineListItem>
</List>
</Grid>
)}
</Grid>
); );
}; /* eslint-enable react/jsx-max-depth */
} };
export default Engine; export default Engine;

View File

@ -1,3 +1,3 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<Engines /> component should render the component in default state 1`] = `"<div class=\\"MuiGrid-root MuiGrid-container\\"><div class=\\"MuiGrid-root MuiGrid-item MuiGrid-grid-xs-6\\"><ul class=\\"MuiList-root MuiList-padding MuiList-subheader\\"><h6 class=\\"MuiTypography-root css-hyrz44 et66bt70 MuiTypography-subtitle1\\">node JS</h6><div class=\\"MuiButtonBase-root MuiListItem-root css-dt93b2 et66bt71 MuiListItem-gutters MuiListItem-button\\" tabindex=\\"0\\" role=\\"button\\" aria-disabled=\\"false\\"><div class=\\"MuiAvatar-root MuiAvatar-colorDefault\\"></div><div class=\\"MuiListItemText-root\\"><span class=\\"MuiTypography-root MuiListItemText-primary MuiTypography-body1\\">&gt;= 0.1.98</span></div><span class=\\"MuiTouchRipple-root\\"></span></div></ul></div><div class=\\"MuiGrid-root MuiGrid-item MuiGrid-grid-xs-6\\"><ul class=\\"MuiList-root MuiList-padding MuiList-subheader\\"><h6 class=\\"MuiTypography-root css-hyrz44 et66bt70 MuiTypography-subtitle1\\">NPM version</h6><div class=\\"MuiButtonBase-root MuiListItem-root css-dt93b2 et66bt71 MuiListItem-gutters MuiListItem-button\\" tabindex=\\"0\\" role=\\"button\\" aria-disabled=\\"false\\"><div class=\\"MuiAvatar-root MuiAvatar-colorDefault\\"></div><div class=\\"MuiListItemText-root\\"><span class=\\"MuiTypography-root MuiListItemText-primary MuiTypography-body1\\">&gt;3</span></div><span class=\\"MuiTouchRipple-root\\"></span></div></ul></div></div>"`; exports[`<Engines /> component should render the component in default state 1`] = `"<div class=\\"MuiGrid-root MuiGrid-container\\"><div class=\\"MuiGrid-root MuiGrid-item MuiGrid-grid-xs-6\\"><ul class=\\"MuiList-root MuiList-padding MuiList-subheader\\"><h6 class=\\"MuiTypography-root css-1na337r-StyledText et66bt70 MuiTypography-subtitle1\\">node JS</h6><div class=\\"MuiButtonBase-root MuiListItem-root css-18b06t0-EngineListItem et66bt71 MuiListItem-gutters MuiListItem-button\\" tabindex=\\"0\\" role=\\"button\\" aria-disabled=\\"false\\"><div class=\\"MuiAvatar-root MuiAvatar-circle MuiAvatar-colorDefault\\"></div><div class=\\"MuiListItemText-root\\"><span class=\\"MuiTypography-root MuiListItemText-primary MuiTypography-body1\\">&gt;= 0.1.98</span></div><span class=\\"MuiTouchRipple-root\\"></span></div></ul></div><div class=\\"MuiGrid-root MuiGrid-item MuiGrid-grid-xs-6\\"><ul class=\\"MuiList-root MuiList-padding MuiList-subheader\\"><h6 class=\\"MuiTypography-root css-1na337r-StyledText et66bt70 MuiTypography-subtitle1\\">NPM version</h6><div class=\\"MuiButtonBase-root MuiListItem-root css-18b06t0-EngineListItem et66bt71 MuiListItem-gutters MuiListItem-button\\" tabindex=\\"0\\" role=\\"button\\" aria-disabled=\\"false\\"><div class=\\"MuiAvatar-root MuiAvatar-circle MuiAvatar-colorDefault\\"></div><div class=\\"MuiListItemText-root\\"><span class=\\"MuiTypography-root MuiListItemText-primary MuiTypography-body1\\">&gt;3</span></div><span class=\\"MuiTouchRipple-root\\"></span></div></ul></div></div>"`;

View File

@ -1,17 +1,14 @@
import styled from 'react-emotion'; import styled from '@emotion/styled';
import ListItem from '@material-ui/core/ListItem';
import Typography from '@material-ui/core/Typography';
import { fontWeight } from '../../utils/styles/sizes';
export const Heading = styled(Typography)({ import { fontWeight } from '../../utils/styles/sizes';
'&&': { import ListItem from '../../muiComponents/ListItem';
import Text from '../../muiComponents/Text';
export const StyledText = styled(Text)({
fontWeight: fontWeight.bold, fontWeight: fontWeight.bold,
textTransform: 'capitalize', textTransform: 'capitalize',
},
}); });
export const EngineListItem = styled(ListItem)({ export const EngineListItem = styled(ListItem)({
'&&': {
paddingLeft: 0, paddingLeft: 0,
},
}); });

View File

@ -1,23 +1,20 @@
import React from 'react'; import React from 'react';
import { mount } from 'enzyme';
import { render } from '../../utils/test-react-testing-library';
import Footer from './Footer'; import Footer from './Footer';
jest.mock('../../../package.json', () => ({
version: '4.0.0-alpha.3',
}));
describe('<Footer /> component', () => { describe('<Footer /> component', () => {
let wrapper; beforeAll(() => {
beforeEach(() => {
// @ts-ignore : Property 'VERDACCIO_VERSION' does not exist on type 'Window'
window.VERDACCIO_VERSION = 'v.1.0.0'; window.VERDACCIO_VERSION = 'v.1.0.0';
wrapper = mount(<Footer />); });
// @ts-ignore : Property 'VERDACCIO_VERSION' does not exist on type 'Window'
afterAll(() => {
delete window.VERDACCIO_VERSION; delete window.VERDACCIO_VERSION;
}); });
test('should load the initial state of Footer component', () => { test('should load the initial state of Footer component', () => {
expect(wrapper.html()).toMatchSnapshot(); const { container } = render(<Footer />);
expect(container.firstChild).toMatchSnapshot();
}); });
}); });

View File

@ -1,8 +1,9 @@
import React from 'react'; import React from 'react';
import { Wrapper, Left, Right, Earth, Flags, Love, Flag, Logo, Inner, ToolTip } from './styles';
import { goToVerdaccioWebsite } from '../../utils/windows'; import { goToVerdaccioWebsite } from '../../utils/windows';
import { Wrapper, Left, Right, Earth, Flags, Love, Flag, Logo, Inner, ToolTip } from './styles';
const renderTooltip = (): JSX.Element => ( const renderTooltip = (): JSX.Element => (
<ToolTip> <ToolTip>
<Earth name="earth" size="md" /> <Earth name="earth" size="md" />
@ -21,7 +22,6 @@ const MADEWITH_LABEL = ' Made with';
const ON_LABEL = 'on'; const ON_LABEL = 'on';
const HEARTH_EMOJI = '♥'; const HEARTH_EMOJI = '♥';
// @ts-ignore
const renderRight = (version = window.VERDACCIO_VERSION): JSX.Element => { const renderRight = (version = window.VERDACCIO_VERSION): JSX.Element => {
return ( return (
<Right> <Right>

View File

@ -1,3 +1,274 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<Footer /> component should load the initial state of Footer component 1`] = `"<div class=\\"css-i0nj2g ezbsl480\\"><div class=\\"css-hzfs9b ezbsl481\\"><div class=\\"css-d8nsp7 ezbsl482\\"> Made with<span class=\\"css-1so4oe0 ezbsl487\\">♥</span>on<span class=\\"css-1ie354y ezbsl484\\"><svg class=\\"ezbsl485 css-tsfgle ek145dl0\\"><title>Earth</title><use xlink:href=\\"[object Object]#earth\\"></use></svg><span class=\\"css-8631ip ezbsl486\\"><svg class=\\"ezbsl488 css-13b76ay ek145dl0\\"><title>Spain</title><use xlink:href=\\"[object Object]#spain\\"></use></svg><svg class=\\"ezbsl488 css-13b76ay ek145dl0\\"><title>Nicaragua</title><use xlink:href=\\"[object Object]#nicaragua\\"></use></svg><svg class=\\"ezbsl488 css-13b76ay ek145dl0\\"><title>India</title><use xlink:href=\\"[object Object]#india\\"></use></svg><svg class=\\"ezbsl488 css-13b76ay ek145dl0\\"><title>Brazil</title><use xlink:href=\\"[object Object]#brazil\\"></use></svg><svg class=\\"ezbsl488 css-13b76ay ek145dl0\\"><title>China</title><use xlink:href=\\"[object Object]#china\\"></use></svg><svg class=\\"ezbsl488 css-13b76ay ek145dl0\\"><title>Austria</title><use xlink:href=\\"[object Object]#austria\\"></use></svg></span></span></div><div class=\\"css-1wbzdyy ezbsl483\\">Powered by<span class=\\"ezbsl488 css-i15wza ek145dl1\\" name=\\"verdaccio\\" title=\\"Verdaccio\\"><img alt=\\"Verdaccio\\" src=\\"[object Object]\\" class=\\"css-1ncdhax ek145dl2\\"></span>/ v.1.0.0</div></div></div>"`; exports[`<Footer /> component should load the initial state of Footer component 1`] = `
.emotion-38 {
background: #f9f9f9;
border-top: 1px solid #e3e3e3;
color: #999999;
font-size: 14px;
padding: 20px;
}
.emotion-36 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: end;
-webkit-justify-content: flex-end;
-ms-flex-pack: end;
justify-content: flex-end;
width: 100%;
}
@media (min-width:768px) {
.emotion-36 {
min-width: 400px;
max-width: 800px;
margin: auto;
-webkit-box-pack: justify;
-webkit-justify-content: space-between;
-ms-flex-pack: justify;
justify-content: space-between;
}
}
@media (min-width:1024px) {
.emotion-36 {
max-width: 1240px;
}
}
.emotion-27 {
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
display: none;
}
@media (min-width:768px) {
.emotion-27 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
}
}
.emotion-0 {
color: #e25555;
padding: 0 5px;
}
.emotion-25 {
position: relative;
height: 18px;
}
.emotion-25:hover .emotion-24 {
visibility: visible;
}
.emotion-3 {
box-sizing: initial;
display: inline-block;
cursor: default;
width: 18px;
height: 18px;
padding: 0 10px;
}
.emotion-23 {
position: absolute;
background: #d3dddd;
padding: 1px 4px;
border-radius: 3px;
height: 20px;
display: -webkit-inline-box;
display: -webkit-inline-flex;
display: -ms-inline-flexbox;
display: inline-flex;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
visibility: hidden;
top: -2px;
}
.emotion-23:before {
content: '';
position: absolute;
top: 29%;
left: -4px;
margin-left: -5px;
border: 5px solid;
border-color: #d3dddd transparent transparent transparent;
-webkit-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
}
.emotion-6 {
box-sizing: initial;
display: inline-block;
cursor: default;
width: 18px;
height: 18px;
padding: 0 5px;
}
.emotion-34 {
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
display: none;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
}
@media (min-width:768px) {
.emotion-34 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
}
}
.emotion-32 {
box-sizing: initial;
display: inline-block;
cursor: pointer;
width: 18px;
height: 18px;
padding: 0 5px;
}
.emotion-29 {
width: 100%;
height: auto;
}
<div
class="emotion-38 emotion-39"
>
<div
class="emotion-36 emotion-37"
>
<div
class="emotion-27 emotion-28"
>
Made with
<span
class="emotion-0 emotion-1"
>
</span>
on
<span
class="emotion-25 emotion-26"
>
<svg
class="emotion-2 emotion-3 emotion-4"
>
<title>
Earth
</title>
<use
xlink:href="[object Object]#earth"
/>
</svg>
<span
class="emotion-23 emotion-24"
>
<svg
class="emotion-5 emotion-6 emotion-4"
>
<title>
Spain
</title>
<use
xlink:href="[object Object]#spain"
/>
</svg>
<svg
class="emotion-5 emotion-6 emotion-4"
>
<title>
Nicaragua
</title>
<use
xlink:href="[object Object]#nicaragua"
/>
</svg>
<svg
class="emotion-5 emotion-6 emotion-4"
>
<title>
India
</title>
<use
xlink:href="[object Object]#india"
/>
</svg>
<svg
class="emotion-5 emotion-6 emotion-4"
>
<title>
Brazil
</title>
<use
xlink:href="[object Object]#brazil"
/>
</svg>
<svg
class="emotion-5 emotion-6 emotion-4"
>
<title>
China
</title>
<use
xlink:href="[object Object]#china"
/>
</svg>
<svg
class="emotion-5 emotion-6 emotion-4"
>
<title>
Austria
</title>
<use
xlink:href="[object Object]#austria"
/>
</svg>
</span>
</span>
</div>
<div
class="emotion-34 emotion-35"
>
Powered by
<span
class="emotion-5 emotion-32 emotion-33"
title="Verdaccio"
>
<img
alt="Verdaccio"
class="emotion-29 emotion-30"
src="[object Object]"
/>
</span>
/ v.1.0.0
</div>
</div>
</div>
`;

View File

@ -1,112 +1,88 @@
import styled, { css } from 'react-emotion'; import styled from '@emotion/styled';
import mq from '../../utils/styles/media';
import Icon from '../Icon/Icon';
import colors from '../../utils/styles/colors';
export const Wrapper = styled('div')({ import { breakpoints } from '../../utils/styles/media';
'&&': { import Icon from '../Icon/Icon';
background: colors.snow, import { Theme } from '../../design-tokens/theme';
borderTop: `1px solid ${colors.greyGainsboro}`,
color: colors.nobel01, export const Wrapper = styled('div')<{ theme?: Theme }>(props => ({
background: props.theme && props.theme.palette.snow,
borderTop: `1px solid ${props.theme && props.theme.palette.greyGainsboro}`,
color: props.theme && props.theme.palette.nobel01,
fontSize: '14px', fontSize: '14px',
padding: '20px', padding: '20px',
}));
export const Inner = styled('div')({
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-end',
width: '100%',
[`@media (min-width: ${breakpoints.medium}px)`]: {
minWidth: 400,
maxWidth: 800,
margin: 'auto',
justifyContent: 'space-between',
},
[`@media (min-width: ${breakpoints.large}px)`]: {
maxWidth: 1240,
}, },
}); });
export const Inner = styled('div')` export const Left = styled('div')({
&& { alignItems: 'center',
display: flex; display: 'none',
align-items: center; [`@media (min-width: ${breakpoints.medium}px)`]: {
justify-content: flex-end;
width: 100%;
${() => {
// @ts-ignore
return mq.medium(css`
min-width: 400px;
max-width: 800px;
margin: auto;
justify-content: space-between;
`);
}};
${() => {
// @ts-ignore
return mq.large(css`
max-width: 1240px;
`);
}};
}
`;
export const Left = styled('div')`
&& {
align-items: center;
display: none;
${() => {
// @ts-ignore
return mq.medium(css`
display: flex;
`);
}};
}
`;
export const Right = styled(Left)({
'&&': {
display: 'flex', display: 'flex',
}, },
}); });
export const ToolTip = styled('span')({ export const Right = styled(Left)({
'&&': { display: 'flex',
position: 'relative',
height: '18px',
},
}); });
export const Earth = styled(Icon)({ export const Earth = styled(Icon)({
'&&': {
padding: '0 10px', padding: '0 10px',
});
export const Flags = styled('span')<{ theme?: Theme }>(props => ({
position: 'absolute',
background: props.theme && props.theme.palette.greyAthens,
padding: '1px 4px',
borderRadius: 3,
height: 20,
display: 'inline-flex',
alignItems: 'center',
visibility: 'hidden',
top: -2,
':before': {
content: "''",
position: 'absolute',
top: '29%',
left: -4,
marginLeft: -5,
border: '5px solid',
borderColor: `${props.theme && props.theme.palette.greyAthens} transparent transparent transparent`,
transform: 'rotate(90deg)',
},
}));
export const ToolTip = styled('span')({
position: 'relative',
height: '18px',
':hover': {
[`${Flags}`]: {
visibility: 'visible',
},
}, },
}); });
export const Flags = styled('span')` export const Love = styled('span')<{ theme?: Theme }>(props => ({
&& { color: props.theme && props.theme.palette.love,
position: absolute;
background: ${colors.greyAthens};
padding: 1px 4px;
border-radius: 3px;
height: 20px;
display: inline-flex;
align-items: center;
visibility: hidden;
top: -2px;
:before {
content: '';
position: absolute;
top: 29%;
left: -4px;
margin-left: -5px;
border: 5px solid;
border-color: ${colors.greyAthens} transparent transparent transparent;
transform: rotate(90deg);
}
${ToolTip}:hover & {
visibility: visible;
}
}
`;
export const Love = styled('span')({
'&&': {
color: colors.love,
padding: '0 5px', padding: '0 5px',
}, }));
});
export const Flag = styled(Icon)({ export const Flag = styled(Icon)({
'&&': {
padding: '0 5px', padding: '0 5px',
},
}); });
export const Logo = Flag; export const Logo = Flag;

View File

@ -1,124 +1,149 @@
import React from 'react'; import React from 'react';
import { BrowserRouter as Router } from 'react-router-dom'; import { BrowserRouter as Router } from 'react-router-dom';
import { shallow } from 'enzyme';
import { render, fireEvent, waitForElementToBeRemoved, waitForElement } from '../../utils/test-react-testing-library';
import Header from './Header'; import Header from './Header';
describe('<Header /> component with logged in state', () => { const headerProps = {
let wrapper; username: 'verddacio-user',
let routerWrapper;
let instance;
let props;
beforeEach(() => {
props = {
username: 'test user',
handleLogout: jest.fn(),
logo: '',
onToggleLoginModal: jest.fn(),
scope: 'test scope', scope: 'test scope',
withoutSearch: true, withoutSearch: true,
}; handleToggleLoginModal: jest.fn(),
routerWrapper = shallow( handleLogout: jest.fn(),
};
/* eslint-disable react/jsx-no-bind*/
describe('<Header /> component with logged in state', () => {
test('should load the component in logged out state', () => {
const { container, queryByTestId, getByText } = render(
<Router> <Router>
<Header <Header
logo={props.logo} onLogout={headerProps.handleLogout}
onLogout={props.handleLogout} onToggleLoginModal={headerProps.handleToggleLoginModal}
onToggleLoginModal={props.onToggleLoginModal} scope={headerProps.scope}
scope={props.scope}
username={props.username}
withoutSearch={props.withoutSearch}
/> />
</Router> </Router>
); );
wrapper = routerWrapper.find(Header).dive();
instance = wrapper.instance(); expect(container.firstChild).toMatchSnapshot();
expect(queryByTestId('header--menu-acountcircle')).toBeNull();
expect(getByText('Login')).toBeTruthy();
}); });
test('should load the component in logged in state', () => { test('should load the component in logged in state', () => {
const state = { const { container, getByTestId, queryByText } = render(
openInfoDialog: false,
packages: undefined,
registryUrl: 'http://localhost',
showMobileNavBar: false,
};
expect(wrapper.state()).toEqual(state);
expect(routerWrapper.html()).toMatchSnapshot();
});
test('handleLoggedInMenu: set anchorEl to html element value in state', () => {
// creates a sample menu
const div = document.createElement('div');
const text = document.createTextNode('sample menu');
div.appendChild(text);
const event = {
currentTarget: div,
};
instance.handleLoggedInMenu(event);
expect(wrapper.state('anchorEl')).toEqual(div);
});
});
describe('<Header /> component with logged out state', () => {
let wrapper;
let routerWrapper;
let instance;
let props;
beforeEach(() => {
props = {
handleLogout: jest.fn(),
onToggleLoginModal: jest.fn(),
scope: 'test scope',
logo: '',
withoutSearch: true,
};
routerWrapper = shallow(
<Router> <Router>
<Header <Header
logo={props.logo} onLogout={headerProps.handleLogout}
onLogout={props.handleLogout} onToggleLoginModal={headerProps.handleToggleLoginModal}
onToggleLoginModal={props.onToggleLoginModal} scope={headerProps.scope}
scope={props.scope} username={headerProps.username}
withoutSearch={props.withoutSearch}
/> />
</Router> </Router>
); );
wrapper = routerWrapper.find(Header).dive();
instance = wrapper.instance(); expect(container.firstChild).toMatchSnapshot();
expect(getByTestId('header--menu-acountcircle')).toBeTruthy();
expect(queryByText('Login')).toBeNull();
}); });
test('should load the component in logged out state', () => { test('should open login dialog', async () => {
const state = { const { getByText } = render(
openInfoDialog: false, <Router>
packages: undefined, <Header
registryUrl: 'http://localhost', onLogout={headerProps.handleLogout}
showMobileNavBar: false, onToggleLoginModal={headerProps.handleToggleLoginModal}
}; scope={headerProps.scope}
expect(wrapper.state()).toEqual(state); />
expect(routerWrapper.html()).toMatchSnapshot(); </Router>
);
const loginBtn = getByText('Login');
fireEvent.click(loginBtn);
expect(headerProps.handleToggleLoginModal).toHaveBeenCalled();
}); });
test('handleLoggedInMenuClose: set anchorEl value to null in state', () => { test('should logout the user', async () => {
instance.handleLoggedInMenuClose(); const { getByText, getByTestId } = render(
expect(wrapper.state('anchorEl')).toBeNull(); <Router>
<Header
onLogout={headerProps.handleLogout}
onToggleLoginModal={headerProps.handleToggleLoginModal}
scope={headerProps.scope}
username={headerProps.username}
/>
</Router>
);
const headerMenuAccountCircle = getByTestId('header--menu-acountcircle');
fireEvent.click(headerMenuAccountCircle);
// wait for button Logout's appearance and return the element
const logoutBtn = await waitForElement(() => getByText('Logout'));
fireEvent.click(logoutBtn);
expect(headerProps.handleLogout).toHaveBeenCalled();
}); });
test('handleOpenRegistryInfoDialog: set openInfoDialog to be truthy in state', () => { test("The question icon should open a new tab of verdaccio's website - installation doc", async () => {
instance.handleOpenRegistryInfoDialog(); const { getByTestId } = render(
expect(wrapper.state('openInfoDialog')).toBeTruthy(); <Router>
<Header
onLogout={headerProps.handleLogout}
onToggleLoginModal={headerProps.handleToggleLoginModal}
scope={headerProps.scope}
username={headerProps.username}
/>
</Router>
);
const documentationBtn = getByTestId('header--tooltip-documentation');
expect(documentationBtn.getAttribute('href')).toBe('https://verdaccio.org/docs/en/installation');
}); });
test('handleCloseRegistryInfoDialog: set openInfoDialog to be falsy in state', () => { test('should open the registrationInfo modal when clicking on the info icon', async () => {
instance.handleCloseRegistryInfoDialog(); const { getByTestId } = render(
expect(wrapper.state('openInfoDialog')).toBeFalsy(); <Router>
<Header
onLogout={headerProps.handleLogout}
onToggleLoginModal={headerProps.handleToggleLoginModal}
scope={headerProps.scope}
username={headerProps.username}
/>
</Router>
);
const infoBtn = getByTestId('header--tooltip-info');
fireEvent.click(infoBtn);
// wait for registrationInfo modal appearance and return the element
const registrationInfoModal = await waitForElement(() => getByTestId('registryInfo--dialog'));
expect(registrationInfoModal).toBeTruthy();
}); });
test('handleToggleLogin: close/open popover menu', () => { test('should close the registrationInfo modal when clicking on the button close', async () => {
instance.handleToggleLogin(); const { getByTestId, getByText, queryByTestId } = render(
expect(wrapper.state('anchorEl')).toBeNull(); <Router>
expect(props.onToggleLoginModal).toHaveBeenCalled(); <Header
onLogout={headerProps.handleLogout}
onToggleLoginModal={headerProps.handleToggleLoginModal}
scope={headerProps.scope}
username={headerProps.username}
/>
</Router>
);
const infoBtn = getByTestId('header--tooltip-info');
fireEvent.click(infoBtn);
// wait for Close's button of registrationInfo modal appearance and return the element
const closeBtn = await waitForElement(() => getByText('CLOSE'));
fireEvent.click(closeBtn);
const hasRegistrationInfoModalBeenRemoved = await waitForElementToBeRemoved(() =>
queryByTestId('registryInfo--dialog')
);
expect(hasRegistrationInfoModalBeenRemoved).toBeTruthy();
}); });
test.todo('autocompletion should display suggestions according to the type value');
}); });

View File

@ -1,26 +1,13 @@
import React, { SyntheticEvent, Component, Fragment, ReactElement } from 'react'; import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { css } from 'emotion';
import Button from '@material-ui/core/Button';
import IconButton from '@material-ui/core/IconButton';
import MenuItem from '@material-ui/core/MenuItem';
import Menu from '@material-ui/core/Menu';
import Info from '@material-ui/icons/Info';
import Help from '@material-ui/icons/Help';
import Tooltip from '@material-ui/core/Tooltip';
import AccountCircle from '@material-ui/icons/AccountCircle';
import { default as IconSearch } from '@material-ui/icons/Search';
import Search from '../Search';
import { getRegistryURL } from '../../utils/url'; import { getRegistryURL } from '../../utils/url';
import ExternalLink from '../Link'; import Button from '../../muiComponents/Button';
import Logo from '../Logo';
import RegistryInfoDialog from '../RegistryInfoDialog/RegistryInfoDialog';
import Label from '../Label/Label';
import Search from '../Search/Search';
import RegistryInfoContent from '../RegistryInfoContent/RegistryInfoContent';
import { Greetings, NavBar, InnerNavBar, MobileNavBar, InnerMobileNavBar, LeftSide, RightSide, IconSearchButton, SearchWrapper } from './styles'; import { NavBar, InnerNavBar, MobileNavBar, InnerMobileNavBar } from './styles';
import HeaderLeft from './HeaderLeft';
import HeaderRight from './HeaderRight';
import HeaderInfoDialog from './HeaderInfoDialog';
interface Props { interface Props {
logo?: string; logo?: string;
@ -31,247 +18,45 @@ interface Props {
withoutSearch?: boolean; withoutSearch?: boolean;
} }
interface State { /* eslint-disable react/jsx-max-depth */
anchorEl?: null | Element | ((element: Element) => Element); /* eslint-disable react/jsx-no-bind*/
openInfoDialog: boolean; const Header: React.FC<Props> = ({ logo, withoutSearch, username, onLogout, onToggleLoginModal, scope }) => {
registryUrl: string; const [isInfoDialogOpen, setOpenInfoDialog] = useState();
showMobileNavBar: boolean; const [showMobileNavBar, setShowMobileNavBar] = useState();
}
type ToolTipType = 'search' | 'help' | 'info';
class Header extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
openInfoDialog: false,
registryUrl: getRegistryURL(),
showMobileNavBar: false,
};
}
public render(): ReactElement<HTMLElement> {
const { showMobileNavBar } = this.state;
const { withoutSearch = false } = this.props;
return ( return (
<div> <>
<NavBar position="static"> <NavBar position="static">
<InnerNavBar> <InnerNavBar>
{this.renderLeftSide()} <HeaderLeft logo={logo} />
{this.renderRightSide()} <HeaderRight
onLogout={onLogout}
onOpenRegistryInfoDialog={() => setOpenInfoDialog(true)}
onToggleLogin={onToggleLoginModal}
onToggleMobileNav={() => setShowMobileNavBar(!showMobileNavBar)}
username={username}
withoutSearch={withoutSearch}
/>
</InnerNavBar> </InnerNavBar>
{this.renderInfoDialog()} <HeaderInfoDialog
isOpen={isInfoDialogOpen}
onCloseDialog={() => setOpenInfoDialog(false)}
registryUrl={getRegistryURL()}
scope={scope}
/>
</NavBar> </NavBar>
{showMobileNavBar && !withoutSearch && ( {showMobileNavBar && !withoutSearch && (
<MobileNavBar> <MobileNavBar>
<InnerMobileNavBar> <InnerMobileNavBar>
<Search /> <Search />
</InnerMobileNavBar> </InnerMobileNavBar>
<Button color="inherit" onClick={this.handleDismissMNav}> <Button color="inherit" onClick={() => setShowMobileNavBar(false)}>
{'Cancel'} {'Cancel'}
</Button> </Button>
</MobileNavBar> </MobileNavBar>
)} )}
</div>
);
}
/**
* opens popover menu for logged in user.
*/
public handleLoggedInMenu = (event: SyntheticEvent<HTMLElement>) => {
this.setState({
anchorEl: event.currentTarget,
});
};
/**
* closes popover menu for logged in user
*/
public handleLoggedInMenuClose = () => {
this.setState({
anchorEl: null,
});
};
/**
* opens registry information dialog.
*/
public handleOpenRegistryInfoDialog = () => {
this.setState({
openInfoDialog: true,
});
};
/**
* closes registry information dialog.
*/
public handleCloseRegistryInfoDialog = () => {
this.setState({
openInfoDialog: false,
});
};
/**
* close/open popover menu for logged in users.
*/
public handleToggleLogin = () => {
const { onToggleLoginModal } = this.props;
this.setState(
{
anchorEl: null,
},
onToggleLoginModal
);
};
public handleToggleMNav = () => {
const { showMobileNavBar } = this.state;
this.setState({
showMobileNavBar: !showMobileNavBar,
});
};
public handleDismissMNav = () => {
this.setState({
showMobileNavBar: false,
});
};
public renderLeftSide = () => {
const { withoutSearch = false } = this.props;
return (
<LeftSide>
<Link
className={css`
margin-right: 1em;
`}
to={'/'}>
{this.renderLogo()}
</Link>
{!withoutSearch && (
<SearchWrapper>
<Search />
</SearchWrapper>
)}
</LeftSide>
);
};
public renderLogo = () => {
const { logo } = this.props;
if (logo) {
return <img alt="logo" height="40px" src={logo} />;
} else {
return <Logo />;
}
};
public renderToolTipIcon = (title: string, type: ToolTipType) => {
let content;
switch (type) {
case 'help':
content = (
// @ts-ignore
<IconButton blank={true} color={'inherit'} component={ExternalLink} to={'https://verdaccio.org/docs/en/installation'}>
<Help />
</IconButton>
);
break;
case 'info':
content = (
<IconButton color="inherit" id="header--button-registryInfo" onClick={this.handleOpenRegistryInfoDialog}>
<Info />
</IconButton>
);
break;
case 'search':
content = (
<IconSearchButton color="inherit" onClick={this.handleToggleMNav}>
<IconSearch />
</IconSearchButton>
);
break;
}
return (
<Tooltip disableFocusListener={true} title={title}>
{content}
</Tooltip>
);
};
public renderRightSide = () => {
const { username = '', withoutSearch = false } = this.props;
return (
<RightSide>
{!withoutSearch && this.renderToolTipIcon('Search packages', 'search')}
{this.renderToolTipIcon('Documentation', 'help')}
{this.renderToolTipIcon('Registry Information', 'info')}
{username ? (
this.renderMenu()
) : (
<Button color="inherit" id="header--button-login" onClick={this.handleToggleLogin}>
{'Login'}
</Button>
)}
</RightSide>
);
};
private renderGreetings = () => {
const { username = '' } = this.props;
return (
<Fragment>
<Greetings>{'Hi,'}</Greetings>
<Label capitalize={true} text={username} weight="bold" />
</Fragment>
);
};
/**
* render popover menu
*/
private renderMenu = () => {
const { onLogout } = this.props;
const { anchorEl } = this.state;
const open = Boolean(anchorEl);
return (
<>
<IconButton color="inherit" id="header--button-account" onClick={this.handleLoggedInMenu}>
<AccountCircle />
</IconButton>
<Menu
anchorEl={anchorEl}
anchorOrigin={{
vertical: 'top',
horizontal: 'right',
}}
id="sidebar-menu"
onClose={this.handleLoggedInMenuClose}
open={open}
transformOrigin={{
vertical: 'top',
horizontal: 'right',
}}>
<MenuItem disabled={true}>{this.renderGreetings()}</MenuItem>
<MenuItem id="header--button-logout" onClick={onLogout}>
{'Logout'}
</MenuItem>
</Menu>
</> </>
); );
}; };
private renderInfoDialog = () => {
const { scope } = this.props;
const { openInfoDialog, registryUrl } = this.state;
return (
<RegistryInfoDialog onClose={this.handleCloseRegistryInfoDialog} open={openInfoDialog}>
<RegistryInfoContent registryUrl={registryUrl} scope={scope} />
</RegistryInfoDialog>
);
};
}
export default Header; export default Header;

View File

@ -0,0 +1,18 @@
import React from 'react';
import Label from '../Label';
import { Greetings } from './styles';
interface Props {
username: string;
}
const HeaderGreetings: React.FC<Props> = ({ username }) => (
<>
<Greetings>{'Hi,'}</Greetings>
<Label capitalize={true} text={username} weight="bold" />
</>
);
export default HeaderGreetings;

View File

@ -0,0 +1,19 @@
import React from 'react';
import RegistryInfoDialog from '../RegistryInfoDialog';
import RegistryInfoContent from '../RegistryInfoContent';
interface Props {
isOpen: boolean;
onCloseDialog: () => void;
registryUrl: string;
scope: string;
}
const HeaderInfoDialog: React.FC<Props> = ({ onCloseDialog, isOpen, registryUrl, scope }) => (
<RegistryInfoDialog onClose={onCloseDialog} open={isOpen}>
<RegistryInfoContent registryUrl={registryUrl} scope={scope} />
</RegistryInfoDialog>
);
export default HeaderInfoDialog;

View File

@ -0,0 +1,32 @@
import React from 'react';
import styled from '@emotion/styled';
import { Link } from 'react-router-dom';
import Search from '../Search/';
import HeaderLogo from './HeaderLogo';
import { LeftSide, SearchWrapper } from './styles';
interface Props {
withoutSearch?: boolean;
logo?: string;
}
const StyledLink = styled(Link)({
marginRight: '1em',
});
const HeaderLeft: React.FC<Props> = ({ withoutSearch = false, logo }) => (
<LeftSide>
<StyledLink to={'/'}>
<HeaderLogo logo={logo} />
</StyledLink>
{!withoutSearch && (
<SearchWrapper>
<Search />
</SearchWrapper>
)}
</LeftSide>
);
export default HeaderLeft;

View File

@ -0,0 +1,17 @@
import React from 'react';
import Logo from '../Logo';
interface Props {
logo?: string;
}
const HeaderLogo: React.FC<Props> = ({ logo }) => {
if (logo) {
return <img alt="logo" height="40px" src={logo} />;
}
return <Logo />;
};
export default HeaderLogo;

View File

@ -0,0 +1,58 @@
import React, { MouseEvent } from 'react';
import AccountCircle from '@material-ui/icons/AccountCircle';
import IconButton from '../../muiComponents/IconButton';
import MenuItem from '../../muiComponents/MenuItem';
import Menu from '../../muiComponents/Menu';
import HeaderGreetings from './HeaderGreetings';
interface Props {
username: string;
isMenuOpen: boolean;
anchorEl?: Element | ((element: Element) => Element) | null | undefined;
onLogout: () => void;
onLoggedInMenu: (event: MouseEvent<HTMLButtonElement>) => void;
onLoggedInMenuClose: () => void;
}
/* eslint-disable react/jsx-max-depth */
const HeaderMenu: React.FC<Props> = ({
onLogout,
username,
isMenuOpen = false,
anchorEl,
onLoggedInMenu,
onLoggedInMenuClose,
}) => (
<>
<IconButton
color="inherit"
data-testid="header--menu-acountcircle"
id="header--button-account"
onClick={onLoggedInMenu}>
<AccountCircle />
</IconButton>
<Menu
anchorEl={anchorEl}
anchorOrigin={{
vertical: 'top',
horizontal: 'right',
}}
onClose={onLoggedInMenuClose}
open={isMenuOpen}
transformOrigin={{
vertical: 'top',
horizontal: 'right',
}}>
<MenuItem disabled={true}>
<HeaderGreetings username={username} />
</MenuItem>
<MenuItem button={true} id="header--button-logout" onClick={onLogout}>
{'Logout'}
</MenuItem>
</Menu>
</>
);
export default HeaderMenu;

View File

@ -0,0 +1,80 @@
import React, { useState, useEffect, MouseEvent } from 'react';
import Button from '../../muiComponents/Button';
import { RightSide } from './styles';
import HeaderToolTip from './HeaderToolTip';
import HeaderMenu from './HeaderMenu';
interface Props {
withoutSearch?: boolean;
username?: string;
onToggleLogin: () => void;
onOpenRegistryInfoDialog: () => void;
onToggleMobileNav: () => void;
onLogout: () => void;
}
const HeaderRight: React.FC<Props> = ({
withoutSearch = false,
username,
onToggleLogin,
onLogout,
onToggleMobileNav,
onOpenRegistryInfoDialog,
}) => {
const [anchorEl, setAnchorEl] = useState();
const [isMenuOpen, setIsMenuOpen] = useState();
useEffect(() => {
setIsMenuOpen(Boolean(anchorEl));
}, [anchorEl]);
/**
* opens popover menu for logged in user.
*/
const handleLoggedInMenu = (event: MouseEvent<HTMLButtonElement>) => {
setAnchorEl(event.currentTarget);
};
/**
* closes popover menu for logged in user
*/
const handleLoggedInMenuClose = () => {
setAnchorEl(null);
};
/**
* close/open popover menu for logged in users.
*/
const handleToggleLogin = () => {
setAnchorEl(null);
onToggleLogin();
};
return (
<RightSide>
{!withoutSearch && (
<HeaderToolTip onClick={onToggleMobileNav} title={'Search packages'} tooltipIconType={'search'} />
)}
<HeaderToolTip title={'Documentation'} tooltipIconType={'help'} />
<HeaderToolTip onClick={onOpenRegistryInfoDialog} title={'Registry Information'} tooltipIconType={'info'} />
{username ? (
<HeaderMenu
anchorEl={anchorEl}
isMenuOpen={isMenuOpen}
onLoggedInMenu={handleLoggedInMenu}
onLoggedInMenuClose={handleLoggedInMenuClose}
onLogout={onLogout}
username={username}
/>
) : (
<Button color="inherit" data-testid="header--button-login" onClick={handleToggleLogin}>
{'Login'}
</Button>
)}
</RightSide>
);
};
export default HeaderRight;

View File

@ -0,0 +1,19 @@
import React from 'react';
import Tooltip from '../../muiComponents/Tooltip';
import HeaderToolTipIcon, { TooltipIconType } from './HeaderToolTipIcon';
interface Props {
title: string;
tooltipIconType: TooltipIconType;
onClick?: () => void;
}
const HeaderToolTip: React.FC<Props> = ({ tooltipIconType, title, onClick }) => (
<Tooltip disableFocusListener={true} title={title}>
<HeaderToolTipIcon onClick={onClick} tooltipIconType={tooltipIconType} />
</Tooltip>
);
export default HeaderToolTip;

View File

@ -0,0 +1,58 @@
import React, { forwardRef } from 'react';
import Info from '@material-ui/icons/Info';
import Help from '@material-ui/icons/Help';
import Search from '@material-ui/icons/Search';
import IconButton from '../../muiComponents/IconButton';
import { IconSearchButton, StyledLink } from './styles';
export type TooltipIconType = 'search' | 'help' | 'info';
interface Props {
tooltipIconType: TooltipIconType;
onClick?: () => void;
}
type HeaderToolTipIconRef = HTMLButtonElement;
/* eslint-disable react/jsx-no-undef */
/* eslint-disable react/display-name */
const HeaderToolTipIcon = forwardRef<HeaderToolTipIconRef, Props>(function HeaderToolTipIcon(
{ tooltipIconType, onClick },
ref
) {
switch (tooltipIconType) {
case 'help':
return (
<StyledLink
data-testid={'header--tooltip-documentation'}
external={true}
to={'https://verdaccio.org/docs/en/installation'}>
<IconButton color={'inherit'}>
<Help />
</IconButton>
</StyledLink>
);
case 'info':
return (
<IconButton
color="inherit"
data-testid={'header--tooltip-info'}
id="header--button-registryInfo"
onClick={onClick}
ref={ref}>
<Info />
</IconButton>
);
case 'search':
return (
<IconSearchButton color="inherit" onClick={onClick}>
<Search />
</IconSearchButton>
);
default:
return null;
}
});
export default HeaderToolTipIcon;

View File

@ -1,5 +1,652 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<Header /> component with logged in state should load the component in logged in state 1`] = `"<div><header class=\\"MuiPaper-root MuiPaper-elevation4 MuiAppBar-root MuiAppBar-positionStatic css-rfunvc e1jf5lit8 MuiAppBar-colorPrimary\\"><div class=\\"MuiToolbar-root MuiToolbar-regular css-1pwdmmq e1jf5lit0 MuiToolbar-gutters\\"><div class=\\"MuiToolbar-root MuiToolbar-regular css-1vacr9s e1jf5lit3 MuiToolbar-gutters\\"><a class=\\"css-1dk30lc\\" href=\\"/\\"><div class=\\"css-1sifsqk em793ed0\\"></div></a></div><div class=\\"MuiToolbar-root MuiToolbar-regular css-m61s5i e1jf5lit2 MuiToolbar-gutters\\"><a href=\\"https://verdaccio.org/docs/en/installation\\" target=\\"_blank\\" class=\\"MuiButtonBase-root MuiIconButton-root MuiIconButton-colorInherit\\" tabindex=\\"0\\" role=\\"button\\" aria-disabled=\\"false\\" title=\\"Documentation\\"><span class=\\"MuiIconButton-label\\"><svg class=\\"MuiSvgIcon-root\\" focusable=\\"false\\" viewBox=\\"0 0 24 24\\" aria-hidden=\\"true\\" role=\\"presentation\\"><path d=\\"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 17h-2v-2h2v2zm2.07-7.75l-.9.92C13.45 12.9 13 13.5 13 15h-2v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25z\\"></path></svg></span></a><button class=\\"MuiButtonBase-root MuiIconButton-root MuiIconButton-colorInherit\\" tabindex=\\"0\\" type=\\"button\\" id=\\"header--button-registryInfo\\" title=\\"Registry Information\\"><span class=\\"MuiIconButton-label\\"><svg class=\\"MuiSvgIcon-root\\" focusable=\\"false\\" viewBox=\\"0 0 24 24\\" aria-hidden=\\"true\\" role=\\"presentation\\"><path d=\\"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z\\"></path></svg></span></button><button class=\\"MuiButtonBase-root MuiIconButton-root MuiIconButton-colorInherit\\" tabindex=\\"0\\" type=\\"button\\" id=\\"header--button-account\\"><span class=\\"MuiIconButton-label\\"><svg class=\\"MuiSvgIcon-root\\" focusable=\\"false\\" viewBox=\\"0 0 24 24\\" aria-hidden=\\"true\\" role=\\"presentation\\"><path d=\\"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z\\"></path></svg></span></button></div></div></header></div>"`; exports[`<Header /> component with logged in state should load the component in logged in state 1`] = `
.emotion-24 {
background-color: #4b5e40;
min-height: 60px;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
}
exports[`<Header /> component with logged out state should load the component in logged out state 1`] = `"<div><header class=\\"MuiPaper-root MuiPaper-elevation4 MuiAppBar-root MuiAppBar-positionStatic css-rfunvc e1jf5lit8 MuiAppBar-colorPrimary\\"><div class=\\"MuiToolbar-root MuiToolbar-regular css-1pwdmmq e1jf5lit0 MuiToolbar-gutters\\"><div class=\\"MuiToolbar-root MuiToolbar-regular css-1vacr9s e1jf5lit3 MuiToolbar-gutters\\"><a class=\\"css-1dk30lc\\" href=\\"/\\"><div class=\\"css-1sifsqk em793ed0\\"></div></a></div><div class=\\"MuiToolbar-root MuiToolbar-regular css-m61s5i e1jf5lit2 MuiToolbar-gutters\\"><a href=\\"https://verdaccio.org/docs/en/installation\\" target=\\"_blank\\" class=\\"MuiButtonBase-root MuiIconButton-root MuiIconButton-colorInherit\\" tabindex=\\"0\\" role=\\"button\\" aria-disabled=\\"false\\" title=\\"Documentation\\"><span class=\\"MuiIconButton-label\\"><svg class=\\"MuiSvgIcon-root\\" focusable=\\"false\\" viewBox=\\"0 0 24 24\\" aria-hidden=\\"true\\" role=\\"presentation\\"><path d=\\"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 17h-2v-2h2v2zm2.07-7.75l-.9.92C13.45 12.9 13 13.5 13 15h-2v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25z\\"></path></svg></span></a><button class=\\"MuiButtonBase-root MuiIconButton-root MuiIconButton-colorInherit\\" tabindex=\\"0\\" type=\\"button\\" id=\\"header--button-registryInfo\\" title=\\"Registry Information\\"><span class=\\"MuiIconButton-label\\"><svg class=\\"MuiSvgIcon-root\\" focusable=\\"false\\" viewBox=\\"0 0 24 24\\" aria-hidden=\\"true\\" role=\\"presentation\\"><path d=\\"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z\\"></path></svg></span></button><button class=\\"MuiButtonBase-root MuiButton-root MuiButton-text MuiButton-colorInherit\\" tabindex=\\"0\\" type=\\"button\\" id=\\"header--button-login\\"><span class=\\"MuiButton-label\\">Login</span></button></div></div></header></div>"`; @media (min-width:768px) {
.emotion-24 .emotion-13 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
}
.emotion-24 .emotion-17 {
display: none;
}
.emotion-24 .e1jf5lit4 {
display: none;
}
}
@media (min-width:1024px) {
.emotion-24 .emotion-23 {
padding: 0 20px;
}
@media (min-width:1275px) {
.emotion-24 .emotion-23 {
max-width: 1240px;
width: 100%;
margin: 0 auto;
}
}
}
.emotion-22 {
-webkit-box-pack: justify;
-webkit-justify-content: space-between;
-ms-flex-pack: justify;
justify-content: space-between;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
padding: 0 15px;
}
.emotion-14 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
padding: 0;
-webkit-flex: 1;
-ms-flex: 1;
flex: 1;
}
.emotion-2 {
margin-right: 1em;
}
.emotion-0 {
display: inline-block;
vertical-align: middle;
box-sizing: border-box;
background-position: center;
background-size: contain;
background-image: url([object Object]);
background-repeat: no-repeat;
width: 40px;
height: 40px;
}
.emotion-12 {
display: none;
max-width: 393px;
width: 100%;
}
.emotion-10 {
width: 100%;
height: 32px;
position: relative;
z-index: 1;
}
.emotion-6 .MuiInputBase-root:before {
content: '';
border: none;
}
.emotion-6 .MuiInputBase-root:after {
border-color: #fff;
}
.emotion-6 .MuiInputBase-root:hover:before {
content: none;
}
.emotion-6 .MuiInputBase-input {
color: #fff;
}
.emotion-4 {
color: #fff;
}
.emotion-8 {
max-height: 500px;
overflow-y: auto;
}
.emotion-20 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
padding: 0;
}
.emotion-16 {
display: block;
}
.emotion-18 {
color: #fff;
}
<header
class="MuiPaper-root MuiPaper-elevation4 MuiAppBar-root MuiAppBar-positionStatic emotion-24 emotion-25 MuiAppBar-colorPrimary"
>
<div
class="MuiToolbar-root MuiToolbar-regular emotion-22 emotion-23 MuiToolbar-gutters"
>
<div
class="MuiToolbar-root MuiToolbar-regular emotion-14 emotion-15 MuiToolbar-gutters"
>
<a
class="emotion-2 emotion-3"
href="/"
>
<div
class="emotion-0 emotion-1"
/>
</a>
<div
class="emotion-12 emotion-13"
>
<div
class="emotion-10 emotion-11"
>
<div
aria-expanded="false"
aria-haspopup="listbox"
aria-owns="react-autowhatever-1"
class="react-autosuggest__container"
role="combobox"
>
<div
aria-autocomplete="list"
aria-controls="react-autowhatever-1"
class="MuiFormControl-root MuiTextField-root react-autosuggest__input emotion-6 emotion-7 MuiFormControl-fullWidth"
>
<div
class="MuiInputBase-root MuiInput-root MuiInput-underline MuiInputBase-fullWidth MuiInput-fullWidth MuiInputBase-formControl MuiInput-formControl MuiInputBase-adornedStart"
>
<div
class="MuiInputAdornment-root emotion-4 emotion-5 MuiInputAdornment-positionStart"
>
<svg
aria-hidden="true"
class="MuiSvgIcon-root"
focusable="false"
role="presentation"
viewBox="0 0 24 24"
>
<path
d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"
/>
</svg>
</div>
<input
aria-invalid="false"
autocomplete="off"
class="MuiInputBase-input MuiInput-input MuiInputBase-inputAdornedStart"
placeholder="Search Packages"
type="text"
value=""
/>
</div>
</div>
<div
class="MuiPaper-root MuiPaper-elevation1 react-autosuggest__suggestions-container emotion-8 emotion-9"
id="react-autowhatever-1"
role="listbox"
/>
</div>
</div>
</div>
</div>
<div
class="MuiToolbar-root MuiToolbar-regular emotion-20 emotion-21 MuiToolbar-gutters"
>
<button
class="MuiButtonBase-root MuiIconButton-root emotion-16 emotion-17 MuiIconButton-colorInherit"
tabindex="0"
type="button"
>
<span
class="MuiIconButton-label"
>
<svg
aria-hidden="true"
class="MuiSvgIcon-root"
focusable="false"
role="presentation"
viewBox="0 0 24 24"
>
<path
d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"
/>
</svg>
</span>
<span
class="MuiTouchRipple-root"
/>
</button>
<a
class="emotion-18 emotion-19"
data-testid="header--tooltip-documentation"
href="https://verdaccio.org/docs/en/installation"
rel="noopener noreferrer"
target="_blank"
>
<h6
class="MuiTypography-root MuiTypography-subtitle1"
>
<button
class="MuiButtonBase-root MuiIconButton-root MuiIconButton-colorInherit"
tabindex="0"
type="button"
>
<span
class="MuiIconButton-label"
>
<svg
aria-hidden="true"
class="MuiSvgIcon-root"
focusable="false"
role="presentation"
viewBox="0 0 24 24"
>
<path
d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 17h-2v-2h2v2zm2.07-7.75l-.9.92C13.45 12.9 13 13.5 13 15h-2v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25z"
/>
</svg>
</span>
<span
class="MuiTouchRipple-root"
/>
</button>
</h6>
</a>
<button
class="MuiButtonBase-root MuiIconButton-root MuiIconButton-colorInherit"
data-testid="header--tooltip-info"
id="header--button-registryInfo"
tabindex="0"
type="button"
>
<span
class="MuiIconButton-label"
>
<svg
aria-hidden="true"
class="MuiSvgIcon-root"
focusable="false"
role="presentation"
viewBox="0 0 24 24"
>
<path
d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"
/>
</svg>
</span>
<span
class="MuiTouchRipple-root"
/>
</button>
<button
class="MuiButtonBase-root MuiIconButton-root MuiIconButton-colorInherit"
data-testid="header--menu-acountcircle"
id="header--button-account"
tabindex="0"
type="button"
>
<span
class="MuiIconButton-label"
>
<svg
aria-hidden="true"
class="MuiSvgIcon-root"
focusable="false"
role="presentation"
viewBox="0 0 24 24"
>
<path
d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z"
/>
</svg>
</span>
<span
class="MuiTouchRipple-root"
/>
</button>
</div>
</div>
</header>
`;
exports[`<Header /> component with logged in state should load the component in logged out state 1`] = `
.emotion-24 {
background-color: #4b5e40;
min-height: 60px;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
}
@media (min-width:768px) {
.emotion-24 .emotion-13 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
}
.emotion-24 .emotion-17 {
display: none;
}
.emotion-24 .e1jf5lit4 {
display: none;
}
}
@media (min-width:1024px) {
.emotion-24 .emotion-23 {
padding: 0 20px;
}
@media (min-width:1275px) {
.emotion-24 .emotion-23 {
max-width: 1240px;
width: 100%;
margin: 0 auto;
}
}
}
.emotion-22 {
-webkit-box-pack: justify;
-webkit-justify-content: space-between;
-ms-flex-pack: justify;
justify-content: space-between;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
padding: 0 15px;
}
.emotion-14 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
padding: 0;
-webkit-flex: 1;
-ms-flex: 1;
flex: 1;
}
.emotion-2 {
margin-right: 1em;
}
.emotion-0 {
display: inline-block;
vertical-align: middle;
box-sizing: border-box;
background-position: center;
background-size: contain;
background-image: url([object Object]);
background-repeat: no-repeat;
width: 40px;
height: 40px;
}
.emotion-12 {
display: none;
max-width: 393px;
width: 100%;
}
.emotion-10 {
width: 100%;
height: 32px;
position: relative;
z-index: 1;
}
.emotion-6 .MuiInputBase-root:before {
content: '';
border: none;
}
.emotion-6 .MuiInputBase-root:after {
border-color: #fff;
}
.emotion-6 .MuiInputBase-root:hover:before {
content: none;
}
.emotion-6 .MuiInputBase-input {
color: #fff;
}
.emotion-4 {
color: #fff;
}
.emotion-8 {
max-height: 500px;
overflow-y: auto;
}
.emotion-20 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
padding: 0;
}
.emotion-16 {
display: block;
}
.emotion-18 {
color: #fff;
}
<header
class="MuiPaper-root MuiPaper-elevation4 MuiAppBar-root MuiAppBar-positionStatic emotion-24 emotion-25 MuiAppBar-colorPrimary"
>
<div
class="MuiToolbar-root MuiToolbar-regular emotion-22 emotion-23 MuiToolbar-gutters"
>
<div
class="MuiToolbar-root MuiToolbar-regular emotion-14 emotion-15 MuiToolbar-gutters"
>
<a
class="emotion-2 emotion-3"
href="/"
>
<div
class="emotion-0 emotion-1"
/>
</a>
<div
class="emotion-12 emotion-13"
>
<div
class="emotion-10 emotion-11"
>
<div
aria-expanded="false"
aria-haspopup="listbox"
aria-owns="react-autowhatever-1"
class="react-autosuggest__container"
role="combobox"
>
<div
aria-autocomplete="list"
aria-controls="react-autowhatever-1"
class="MuiFormControl-root MuiTextField-root react-autosuggest__input emotion-6 emotion-7 MuiFormControl-fullWidth"
>
<div
class="MuiInputBase-root MuiInput-root MuiInput-underline MuiInputBase-fullWidth MuiInput-fullWidth MuiInputBase-formControl MuiInput-formControl MuiInputBase-adornedStart"
>
<div
class="MuiInputAdornment-root emotion-4 emotion-5 MuiInputAdornment-positionStart"
>
<svg
aria-hidden="true"
class="MuiSvgIcon-root"
focusable="false"
role="presentation"
viewBox="0 0 24 24"
>
<path
d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"
/>
</svg>
</div>
<input
aria-invalid="false"
autocomplete="off"
class="MuiInputBase-input MuiInput-input MuiInputBase-inputAdornedStart"
placeholder="Search Packages"
type="text"
value=""
/>
</div>
</div>
<div
class="MuiPaper-root MuiPaper-elevation1 react-autosuggest__suggestions-container emotion-8 emotion-9"
id="react-autowhatever-1"
role="listbox"
/>
</div>
</div>
</div>
</div>
<div
class="MuiToolbar-root MuiToolbar-regular emotion-20 emotion-21 MuiToolbar-gutters"
>
<button
class="MuiButtonBase-root MuiIconButton-root emotion-16 emotion-17 MuiIconButton-colorInherit"
tabindex="0"
type="button"
>
<span
class="MuiIconButton-label"
>
<svg
aria-hidden="true"
class="MuiSvgIcon-root"
focusable="false"
role="presentation"
viewBox="0 0 24 24"
>
<path
d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"
/>
</svg>
</span>
<span
class="MuiTouchRipple-root"
/>
</button>
<a
class="emotion-18 emotion-19"
data-testid="header--tooltip-documentation"
href="https://verdaccio.org/docs/en/installation"
rel="noopener noreferrer"
target="_blank"
>
<h6
class="MuiTypography-root MuiTypography-subtitle1"
>
<button
class="MuiButtonBase-root MuiIconButton-root MuiIconButton-colorInherit"
tabindex="0"
type="button"
>
<span
class="MuiIconButton-label"
>
<svg
aria-hidden="true"
class="MuiSvgIcon-root"
focusable="false"
role="presentation"
viewBox="0 0 24 24"
>
<path
d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 17h-2v-2h2v2zm2.07-7.75l-.9.92C13.45 12.9 13 13.5 13 15h-2v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25z"
/>
</svg>
</span>
<span
class="MuiTouchRipple-root"
/>
</button>
</h6>
</a>
<button
class="MuiButtonBase-root MuiIconButton-root MuiIconButton-colorInherit"
data-testid="header--tooltip-info"
id="header--button-registryInfo"
tabindex="0"
type="button"
>
<span
class="MuiIconButton-label"
>
<svg
aria-hidden="true"
class="MuiSvgIcon-root"
focusable="false"
role="presentation"
viewBox="0 0 24 24"
>
<path
d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"
/>
</svg>
</span>
<span
class="MuiTouchRipple-root"
/>
</button>
<button
class="MuiButtonBase-root MuiButton-root MuiButton-text MuiButton-colorInherit"
data-testid="header--button-login"
tabindex="0"
type="button"
>
<span
class="MuiButton-label"
>
Login
</span>
<span
class="MuiTouchRipple-root"
/>
</button>
</div>
</div>
</header>
`;

View File

@ -1,82 +1,65 @@
import styled, { css } from 'react-emotion'; import styled from '@emotion/styled';
import AppBar from '@material-ui/core/AppBar'; import { css } from '@emotion/core';
import Toolbar from '@material-ui/core/Toolbar';
import IconButton from '@material-ui/core/IconButton';
import colors from '../../utils/styles/colors'; import { Theme } from '../../design-tokens/theme';
import mq from '../../utils/styles/media'; import { breakpoints } from '../../utils/styles/media';
import IconButton from '../../muiComponents/IconButton';
import AppBar from '../../muiComponents/AppBar';
import Toolbar from '../../muiComponents/Toolbar';
import Link from '../Link';
export const InnerNavBar = styled(Toolbar)({ export const InnerNavBar = styled(Toolbar)({
'&&': {
justifyContent: 'space-between', justifyContent: 'space-between',
alignItems: 'center', alignItems: 'center',
padding: '0 15px', padding: '0 15px',
},
}); });
export const Greetings = styled('span')({ export const Greetings = styled('span')({
'&&': {
margin: '0 5px 0 0', margin: '0 5px 0 0',
},
}); });
export const RightSide = styled(Toolbar)({ export const RightSide = styled(Toolbar)({
'&&': {
display: 'flex', display: 'flex',
padding: 0, padding: 0,
},
}); });
export const LeftSide = styled(RightSide)({ export const LeftSide = styled(RightSide)({
'&&': {
flex: 1, flex: 1,
},
}); });
export const MobileNavBar = styled('div')({ export const MobileNavBar = styled('div')<{ theme?: Theme }>(props => ({
'&&': {
alignItems: 'center', alignItems: 'center',
display: 'flex', display: 'flex',
borderBottom: `1px solid ${colors.greyLight}`, borderBottom: `1px solid ${props.theme && props.theme.palette.greyLight}`,
padding: '8px', padding: '8px',
position: 'relative', position: 'relative',
}, }));
});
export const InnerMobileNavBar = styled('div')({ export const InnerMobileNavBar = styled('div')<{ theme?: Theme }>(props => ({
'&&': {
borderRadius: '4px', borderRadius: '4px',
backgroundColor: colors.greyLight, backgroundColor: props.theme && props.theme.palette.greyLight,
color: colors.white, color: props.theme && props.theme.palette.white,
width: '100%', width: '100%',
padding: '0 5px', padding: '0 5px',
margin: '0 10px 0 0', margin: '0 10px 0 0',
}, }));
});
export const IconSearchButton = styled(IconButton)({ export const IconSearchButton = styled(IconButton)({
'&&': {
display: 'block', display: 'block',
},
}); });
export const SearchWrapper = styled('div')({ export const SearchWrapper = styled('div')({
'&&': {
display: 'none', display: 'none',
maxWidth: '393px', maxWidth: '393px',
width: '100%', width: '100%',
},
}); });
export const NavBar = styled(AppBar)` export const NavBar = styled(AppBar)<{ theme?: Theme }>(props => ({
&& { backgroundColor: props.theme && props.theme.palette.primary.main,
background-color: ${colors.primary}; minHeight: 60,
min-height: 60px; display: 'flex',
display: flex; justifyContent: 'center',
justify-content: center; [`@media (min-width: ${breakpoints.medium}px)`]: css`
${() => {
// @ts-ignore
return mq.medium(css`
${SearchWrapper} { ${SearchWrapper} {
display: flex; display: flex;
} }
@ -86,25 +69,21 @@ export const NavBar = styled(AppBar)`
${MobileNavBar} { ${MobileNavBar} {
display: none; display: none;
} }
`); `,
}}; [`@media (min-width: ${breakpoints.large}px)`]: css`
${() => {
// @ts-ignore
return mq.large(css`
${InnerNavBar} { ${InnerNavBar} {
padding: 0 20px; padding: 0 20px;
} }
`); `,
}}; [`@media (min-width: ${breakpoints.xlarge}px)`]: css`
${() => {
// @ts-ignore
return mq.xlarge(css`
${InnerNavBar} { ${InnerNavBar} {
max-width: 1240px; max-width: 1240px;
width: 100%; width: 100%;
margin: 0 auto; margin: 0 auto;
} }
`); `,
}}; }));
}
`; export const StyledLink = styled(Link)<{ theme?: Theme }>(props => ({
color: props.theme && props.theme.palette.white,
}));

View File

@ -1,10 +1,12 @@
import React from 'react'; import React from 'react';
import { mount } from 'enzyme';
import { render } from '../../utils/test-react-testing-library';
import Help from './Help'; import Help from './Help';
describe('<Help /> component', () => { describe('<Help /> component', () => {
test('should render the component in default state', () => { test('should load the component in default state', () => {
const wrapper = mount(<Help />); const { container } = render(<Help />);
expect(wrapper.html()).toMatchSnapshot(); expect(container.firstChild).toMatchSnapshot();
}); });
}); });

View File

@ -1,18 +1,22 @@
import Button from '@material-ui/core/Button';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import Typography from '@material-ui/core/Typography';
import React, { Fragment } from 'react'; import React, { Fragment } from 'react';
import { getRegistryURL } from '../../utils/url'; import { getRegistryURL } from '../../utils/url';
import CopyToClipBoard from '../CopyToClipBoard'; import CopyToClipBoard from '../CopyToClipBoard';
import Button from '../../muiComponents/Button';
import CardContent from '../../muiComponents/CardContent';
import { default as Typography } from '../../muiComponents/Heading';
import CardActions from '../../muiComponents/CardActions';
import Text from '../../muiComponents/Text';
import { CardStyled as Card, HelpTitle } from './styles'; import { CardStyled as Card, HelpTitle } from './styles';
export const HELP_TITLE = 'No Package Published Yet.';
export const COMPONENT_HELP_ID = 'help-card__title';
function renderHeadingClipboardSegments(title: string, text: string): React.ReactNode { function renderHeadingClipboardSegments(title: string, text: string): React.ReactNode {
return ( return (
<Fragment> <Fragment>
<Typography variant={'body1'}>{title}</Typography> <Text variant={'body1'}>{title}</Text>
<CopyToClipBoard text={text} /> <CopyToClipBoard text={text} />
</Fragment> </Fragment>
); );
@ -24,18 +28,18 @@ const Help: React.FC = () => {
return ( return (
<Card id="help-card"> <Card id="help-card">
<CardContent> <CardContent>
<Typography component="h2" gutterBottom={true} id="help-card__title" variant="h5"> <Typography component="h2" gutterBottom={true} id={COMPONENT_HELP_ID} variant="h5">
{'No Package Published Yet.'} {HELP_TITLE}
</Typography> </Typography>
<HelpTitle color="textSecondary" gutterBottom={true}> <HelpTitle color="textSecondary" gutterBottom={true}>
{'To publish your first package just:'} {'To publish your first package just:'}
</HelpTitle> </HelpTitle>
{renderHeadingClipboardSegments('1. Login', `npm adduser --registry ${registryUrl}`)} {renderHeadingClipboardSegments('1. Login', `npm adduser --registry ${registryUrl}`)}
{renderHeadingClipboardSegments('2. Publish', `npm publish --registry ${registryUrl}`)} {renderHeadingClipboardSegments('2. Publish', `npm publish --registry ${registryUrl}`)}
<Typography variant="body2">{'3. Refresh this page.'}</Typography> <Text variant="body2">{'3. Refresh this page.'}</Text>
</CardContent> </CardContent>
<CardActions> <CardActions>
<Button color="primary" href="https://verdaccio.org/docs/en/installation" size="small" target="_blank"> <Button color="primary" href="https://verdaccio.org/docs/en/installation" size="small">
{'Learn More'} {'Learn More'}
</Button> </Button>
</CardActions> </CardActions>

View File

@ -1,3 +1,159 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<Help /> component should render the component in default state 1`] = `"<div class=\\"MuiPaper-root MuiPaper-elevation1 MuiCard-root css-ryznli e1wgaou60 MuiPaper-rounded\\" id=\\"help-card\\"><div class=\\"MuiCardContent-root\\"><h2 class=\\"MuiTypography-root MuiTypography-h5 MuiTypography-gutterBottom\\" id=\\"help-card__title\\">No Package Published Yet.</h2><p class=\\"MuiTypography-root css-zg2fwz e1wgaou61 MuiTypography-body1 MuiTypography-colorTextSecondary MuiTypography-gutterBottom\\">To publish your first package just:</p><p class=\\"MuiTypography-root MuiTypography-body1\\">1. Login</p><div class=\\"css-1mta3t8 eb8w2fo0\\"><span class=\\"css-1m8aenu eb8w2fo1\\">npm adduser --registry http://localhost</span><button class=\\"MuiButtonBase-root MuiIconButton-root css-0 eb8w2fo2\\" tabindex=\\"0\\" type=\\"button\\" title=\\"Copy to Clipboard\\"><span class=\\"MuiIconButton-label\\"><svg class=\\"MuiSvgIcon-root\\" focusable=\\"false\\" viewBox=\\"0 0 24 24\\" aria-hidden=\\"true\\" role=\\"presentation\\"><path d=\\"M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm-1 4l6 6v10c0 1.1-.9 2-2 2H7.99C6.89 23 6 22.1 6 21l.01-14c0-1.1.89-2 1.99-2h7zm-1 7h5.5L14 6.5V12z\\"></path></svg></span><span class=\\"MuiTouchRipple-root\\"></span></button></div><p class=\\"MuiTypography-root MuiTypography-body1\\">2. Publish</p><div class=\\"css-1mta3t8 eb8w2fo0\\"><span class=\\"css-1m8aenu eb8w2fo1\\">npm publish --registry http://localhost</span><button class=\\"MuiButtonBase-root MuiIconButton-root css-0 eb8w2fo2\\" tabindex=\\"0\\" type=\\"button\\" title=\\"Copy to Clipboard\\"><span class=\\"MuiIconButton-label\\"><svg class=\\"MuiSvgIcon-root\\" focusable=\\"false\\" viewBox=\\"0 0 24 24\\" aria-hidden=\\"true\\" role=\\"presentation\\"><path d=\\"M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm-1 4l6 6v10c0 1.1-.9 2-2 2H7.99C6.89 23 6 22.1 6 21l.01-14c0-1.1.89-2 1.99-2h7zm-1 7h5.5L14 6.5V12z\\"></path></svg></span><span class=\\"MuiTouchRipple-root\\"></span></button></div><p class=\\"MuiTypography-root MuiTypography-body2\\">3. Refresh this page.</p></div><div class=\\"MuiCardActions-root MuiCardActions-spacing\\"><a class=\\"MuiButtonBase-root MuiButton-root MuiButton-text MuiButton-textPrimary MuiButton-sizeSmall\\" tabindex=\\"0\\" aria-disabled=\\"false\\" href=\\"https://verdaccio.org/docs/en/installation\\" target=\\"_blank\\"><span class=\\"MuiButton-label\\">Learn More</span><span class=\\"MuiTouchRipple-root\\"></span></a></div></div>"`; exports[`<Help /> component should load the component in default state 1`] = `
.emotion-14 {
width: 600px;
margin: auto;
}
.emotion-0 {
margin-bottom: 20px;
}
.emotion-6 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: justify;
-webkit-justify-content: space-between;
-ms-flex-pack: justify;
justify-content: space-between;
}
.emotion-2 {
display: inline-block;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
height: 21px;
font-size: 1rem;
}
<div
class="MuiPaper-root MuiPaper-elevation1 MuiCard-root emotion-14 emotion-15 MuiPaper-rounded"
id="help-card"
>
<div
class="MuiCardContent-root"
>
<h2
class="MuiTypography-root MuiTypography-h5 MuiTypography-gutterBottom"
id="help-card__title"
>
No Package Published Yet.
</h2>
<h6
class="MuiTypography-root emotion-0 emotion-1 MuiTypography-h6 MuiTypography-colorTextSecondary MuiTypography-gutterBottom"
>
To publish your first package just:
</h6>
<p
class="MuiTypography-root MuiTypography-body1"
>
1. Login
</p>
<div
class="emotion-6 emotion-7"
>
<span
class="emotion-2 emotion-3"
>
npm adduser --registry http://localhost
</span>
<button
class="MuiButtonBase-root MuiIconButton-root emotion-4 emotion-5"
tabindex="0"
title="Copy to Clipboard"
type="button"
>
<span
class="MuiIconButton-label"
>
<svg
aria-hidden="true"
class="MuiSvgIcon-root"
focusable="false"
role="presentation"
viewBox="0 0 24 24"
>
<path
d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm-1 4l6 6v10c0 1.1-.9 2-2 2H7.99C6.89 23 6 22.1 6 21l.01-14c0-1.1.89-2 1.99-2h7zm-1 7h5.5L14 6.5V12z"
/>
</svg>
</span>
<span
class="MuiTouchRipple-root"
/>
</button>
</div>
<p
class="MuiTypography-root MuiTypography-body1"
>
2. Publish
</p>
<div
class="emotion-6 emotion-7"
>
<span
class="emotion-2 emotion-3"
>
npm publish --registry http://localhost
</span>
<button
class="MuiButtonBase-root MuiIconButton-root emotion-4 emotion-5"
tabindex="0"
title="Copy to Clipboard"
type="button"
>
<span
class="MuiIconButton-label"
>
<svg
aria-hidden="true"
class="MuiSvgIcon-root"
focusable="false"
role="presentation"
viewBox="0 0 24 24"
>
<path
d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm-1 4l6 6v10c0 1.1-.9 2-2 2H7.99C6.89 23 6 22.1 6 21l.01-14c0-1.1.89-2 1.99-2h7zm-1 7h5.5L14 6.5V12z"
/>
</svg>
</span>
<span
class="MuiTouchRipple-root"
/>
</button>
</div>
<p
class="MuiTypography-root MuiTypography-body2"
>
3. Refresh this page.
</p>
</div>
<div
class="MuiCardActions-root MuiCardActions-spacing"
>
<a
aria-disabled="false"
class="MuiButtonBase-root MuiButton-root MuiButton-text MuiButton-textPrimary MuiButton-textSizeSmall MuiButton-sizeSmall"
href="https://verdaccio.org/docs/en/installation"
tabindex="0"
>
<span
class="MuiButton-label"
>
Learn More
</span>
<span
class="MuiTouchRipple-root"
/>
</a>
</div>
</div>
`;

View File

@ -1,16 +1,13 @@
import Card from '@material-ui/core/Card'; import styled from '@emotion/styled';
import Typography from '@material-ui/core/Typography';
import styled from 'react-emotion'; import { default as Typography } from '../../muiComponents/Heading';
import Card from '../../muiComponents/Card';
export const CardStyled = styled(Card)({ export const CardStyled = styled(Card)({
'&&': { width: 600,
width: '600px',
margin: 'auto', margin: 'auto',
},
}); });
export const HelpTitle = styled(Typography)({ export const HelpTitle = styled(Typography)({
'&&': { marginBottom: 20,
marginBottom: '20px',
},
}); });

View File

@ -1,5 +1,6 @@
import React from 'react'; import React from 'react';
import { shallow } from 'enzyme';
import { render } from '../../utils/test-react-testing-library';
import Icon from './Icon'; import Icon from './Icon';
@ -8,7 +9,7 @@ describe('<Icon /> component', () => {
name: 'austria', name: 'austria',
}; };
test('should render the component in default state', () => { test('should render the component in default state', () => {
const wrapper = shallow(<Icon name={props.name} />); const { container } = render(<Icon name={props.name} />);
expect(wrapper.html()).toMatchSnapshot(); expect(container.firstChild).toMatchSnapshot();
}); });
}); });

View File

@ -3,7 +3,6 @@ import capitalize from 'lodash/capitalize';
import { Breakpoint } from '@material-ui/core/styles/createBreakpoints'; import { Breakpoint } from '@material-ui/core/styles/createBreakpoints';
import { Svg, Img, ImgWrapper } from './styles'; import { Svg, Img, ImgWrapper } from './styles';
import brazil from './img/brazil.svg'; import brazil from './img/brazil.svg';
import china from './img/china.svg'; import china from './img/china.svg';
import india from './img/india.svg'; import india from './img/india.svg';
@ -64,15 +63,14 @@ export interface Props {
modifiers?: null | undefined; modifiers?: null | undefined;
} }
/* eslint-disable verdaccio/jsx-spread */
const Icon: React.FC<Props> = ({ className, name, size = 'sm', img = false, pointer = false, ...props }) => { const Icon: React.FC<Props> = ({ className, name, size = 'sm', img = false, pointer = false, ...props }) => {
// @ts-ignore const title = capitalize(name.toString());
const title = capitalize(name);
return img ? ( return img ? (
<ImgWrapper className={className} name={name} pointer={pointer} size={size} title={title} {...props}> <ImgWrapper className={className} pointer={pointer} size={size} title={title} {...props}>
<Img alt={title} src={Icons[name]} /> <Img alt={title} src={Icons[name]} />
</ImgWrapper> </ImgWrapper>
) : ( ) : (
// @ts-ignore
<Svg className={className} pointer={pointer} size={size} {...props}> <Svg className={className} pointer={pointer} size={size} {...props}>
<title>{title}</title> <title>{title}</title>
<use xlinkHref={`${Icons[name]}#${name}`} /> <use xlinkHref={`${Icons[name]}#${name}`} />

View File

@ -1,3 +1,22 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<Icon /> component should render the component in default state 1`] = `"<svg class=\\"css-snirlv ek145dl0\\"><title>Austria</title><use xlink:href=\\"[object Object]#austria\\"></use></svg>"`; exports[`<Icon /> component should render the component in default state 1`] = `
.emotion-0 {
box-sizing: initial;
display: inline-block;
cursor: default;
width: 14px;
height: 16px;
}
<svg
class="emotion-0 emotion-1"
>
<title>
Austria
</title>
<use
xlink:href="[object Object]#austria"
/>
</svg>
`;

View File

@ -1,56 +1,42 @@
import styled, { css } from 'react-emotion'; import styled from '@emotion/styled';
import { Breakpoint } from '@material-ui/core/styles/createBreakpoints'; import { Breakpoint } from '@material-ui/core/styles/createBreakpoints';
import { StyledOtherComponent } from 'create-emotion-styled';
import { DetailedHTMLProps, HTMLAttributes } from 'react';
const getSize = (size: Breakpoint): string => { const getSize = (size: Breakpoint): { width: number; height: number } => {
switch (size) { switch (size) {
case 'md': case 'md':
return ` return {
width: 18px; width: 18,
height: 18px; height: 18,
`; };
default: default:
return ` return {
width: 14px; width: 14,
height: 16px; height: 16,
`; };
} }
}; };
const commonStyle = ({ size = 'sm' as Breakpoint, pointer, modifiers = null }): string => css` interface CommonStyleProps {
&& { size: Breakpoint;
display: inline-block; pointer?: boolean;
cursor: ${pointer ? 'pointer' : 'Developers'}; }
${getSize(size)}; const commonStyle = ({ size = 'sm', pointer }: CommonStyleProps): object => ({
${modifiers && modifiers}; display: 'inline-block',
} cursor: pointer ? 'pointer' : 'default',
`; ...getSize(size),
});
export const Svg = styled('svg')` export const Svg = styled('svg')<CommonStyleProps>(props => ({
&& { boxSizing: 'initial',
${commonStyle}; ...commonStyle(props),
} }));
`;
export const ImgWrapper: StyledOtherComponent< export const ImgWrapper = styled('span')<CommonStyleProps>(props => ({
{ boxSizing: 'initial',
size?: Breakpoint; ...commonStyle(props),
pointer: boolean; }));
modifiers?: null | undefined;
name?: string | unknown;
},
DetailedHTMLProps<HTMLAttributes<HTMLSpanElement>, HTMLSpanElement>,
{}
> = styled('span')`
&& {
${commonStyle};
}
`;
export const Img = styled('img')({ export const Img = styled('img')({
'&&': {
width: '100%', width: '100%',
height: 'auto', height: 'auto',
},
}); });

View File

@ -1,11 +1,54 @@
import React from 'react'; import React from 'react';
import { mount } from 'enzyme';
import { render } from '../../utils/test-react-testing-library';
import { DetailContext, DetailContextProps } from '../../pages/Version';
import data from './__partials__/data.json';
import Install from './Install'; import Install from './Install';
describe('<Install /> component', () => { const detailContextValue: Partial<DetailContextProps> = {
test('should render the component in default state', () => { packageName: 'foo',
const wrapper = mount(<Install />); packageMeta: data,
expect(wrapper.html()).toMatchSnapshot(); };
const ComponentToBeRendered: React.FC = () => (
<DetailContext.Provider value={detailContextValue}>
<Install />
</DetailContext.Provider>
);
/* eslint-disable react/jsx-no-bind*/
describe('<Install />', () => {
test('renders correctly', () => {
const { container } = render(<ComponentToBeRendered />);
expect(container.firstChild).toMatchSnapshot();
});
test('should have 3 children', () => {
const { getByTestId } = render(<ComponentToBeRendered />);
const installListItems = getByTestId('installList');
// installitems + subHeader = 4
expect(installListItems.children.length).toBe(4);
});
test('should have the element NPM', () => {
const { getByTestId, queryByText } = render(<ComponentToBeRendered />);
expect(getByTestId('installListItem-npm')).toBeTruthy();
expect(queryByText(`npm install ${detailContextValue.packageName}`)).toBeTruthy();
expect(queryByText('Install using npm')).toBeTruthy();
});
test('should have the element YARN', () => {
const { getByTestId, queryByText } = render(<ComponentToBeRendered />);
expect(getByTestId('installListItem-yarn')).toBeTruthy();
expect(queryByText(`yarn add ${detailContextValue.packageName}`)).toBeTruthy();
expect(queryByText('Install using yarn')).toBeTruthy();
});
test('should have the element PNPM', () => {
const { getByTestId, queryByText } = render(<ComponentToBeRendered />);
expect(getByTestId('installListItem-pnpm')).toBeTruthy();
expect(queryByText(`pnpm install ${detailContextValue.packageName}`)).toBeTruthy();
expect(queryByText('Install using pnpm')).toBeTruthy();
}); });
}); });

View File

@ -1,54 +1,34 @@
import List from '@material-ui/core/List'; import React, { useContext } from 'react';
import React, { Component } from 'react'; import styled from '@emotion/styled';
import { DetailContextConsumer, VersionPageConsumerProps } from '../../pages/Version'; import { DetailContext } from '../../pages/Version';
import { fontWeight } from '../../utils/styles/sizes';
import Text from '../../muiComponents/Text';
import List from '../../muiComponents/List';
import CopyToClipBoard from '../CopyToClipBoard'; import InstallListItem, { DependencyManager } from './InstallListItem';
// logos of package managers const StyledText = styled(Text)({
import npm from './img/npm.svg'; fontWeight: fontWeight.bold,
import pnpm from './img/pnpm.svg'; textTransform: 'capitalize',
import yarn from './img/yarn.svg'; });
import { Heading, InstallItem, PackageMangerAvatar, InstallListItemText } from './styles'; const Install: React.FC = () => {
const detailContext = useContext(DetailContext);
class Install extends Component { const { packageMeta, packageName } = detailContext;
public render(): JSX.Element {
return ( if (!packageMeta || !packageName) {
<DetailContextConsumer> return null;
{(context: Partial<VersionPageConsumerProps>) => {
return context && context.packageName && this.renderCopyCLI(context);
}}
</DetailContextConsumer>
);
} }
public renderCopyCLI = ({ packageName = '' }: Partial<VersionPageConsumerProps>) => {
return ( return (
<> <List data-testid={'installList'} subheader={<StyledText variant={'subtitle1'}>{'Installation'}</StyledText>}>
<List subheader={<Heading variant={'subtitle1'}>{'Installation'}</Heading>}>{this.renderListItems(packageName)}</List> <InstallListItem dependencyManager={DependencyManager.NPM} packageName={packageName} />
</> <InstallListItem dependencyManager={DependencyManager.YARN} packageName={packageName} />
<InstallListItem dependencyManager={DependencyManager.PNPM} packageName={packageName} />
</List>
); );
}; };
public renderListItems = (packageName: string) => {
return (
<>
<InstallItem button={true}>
<PackageMangerAvatar alt={'npm logo'} src={npm} />
<InstallListItemText primary={<CopyToClipBoard text={`npm install ${packageName}`} />} secondary={'Install using NPM'} />
</InstallItem>
<InstallItem button={true}>
<PackageMangerAvatar alt={'yarn logo'} src={yarn} />
<InstallListItemText primary={<CopyToClipBoard text={`yarn add ${packageName}`} />} secondary={'Install using Yarn'} />
</InstallItem>
<InstallItem button={true}>
<PackageMangerAvatar alt={'pnpm logo'} src={pnpm} />
<InstallListItemText primary={<CopyToClipBoard text={`pnpm install ${packageName}`} />} secondary={'Install using PNPM'} />
</InstallItem>
</>
);
};
}
export default Install; export default Install;

View File

@ -0,0 +1,79 @@
import React from 'react';
import styled from '@emotion/styled';
import CopyToClipBoard from '../CopyToClipBoard';
import Avatar from '../../muiComponents/Avatar';
import ListItem from '../../muiComponents/ListItem';
import ListItemText from '../../muiComponents/ListItemText';
// logos of package managers
import npmLogo from './img/npm.svg';
import pnpmLogo from './img/pnpm.svg';
import yarnLogo from './img/yarn.svg';
const InstallItem = styled(ListItem)({
padding: 0,
':hover': {
backgroundColor: 'transparent',
},
});
const InstallListItemText = styled(ListItemText)({
padding: '0 10px',
margin: 0,
});
const PackageMangerAvatar = styled(Avatar)({
borderRadius: '0px',
padding: '0',
});
export enum DependencyManager {
NPM = 'npm',
YARN = 'yarn',
PNPM = 'pnpm',
}
interface Interface {
packageName: string;
dependencyManager: DependencyManager;
}
const InstallListItem: React.FC<Interface> = ({ packageName, dependencyManager }) => {
switch (dependencyManager) {
case DependencyManager.NPM:
return (
<InstallItem button={true} data-testid={'installListItem-npm'}>
<PackageMangerAvatar alt="npm" src={npmLogo} />
<InstallListItemText
primary={<CopyToClipBoard text={`npm install ${packageName}`} />}
secondary={'Install using npm'}
/>
</InstallItem>
);
case DependencyManager.YARN:
return (
<InstallItem button={true} data-testid={'installListItem-yarn'}>
<PackageMangerAvatar alt="yarn" src={yarnLogo} />
<InstallListItemText
primary={<CopyToClipBoard text={`yarn add ${packageName}`} />}
secondary={'Install using yarn'}
/>
</InstallItem>
);
case DependencyManager.PNPM:
return (
<InstallItem button={true} data-testid={'installListItem-pnpm'}>
<PackageMangerAvatar alt={'pnpm'} src={pnpmLogo} />
<InstallListItemText
primary={<CopyToClipBoard text={`pnpm install ${packageName}`} />}
secondary={'Install using pnpm'}
/>
</InstallItem>
);
default:
return null;
}
};
export default InstallListItem;

File diff suppressed because it is too large Load Diff

View File

@ -1,3 +1,262 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<Install /> component should render the component in default state 1`] = `null`; exports[`<Install /> renders correctly 1`] = `
.emotion-0 {
font-weight: 700;
text-transform: capitalize;
}
.emotion-12 {
padding: 0;
}
.emotion-12:hover {
background-color: transparent;
}
.emotion-2 {
border-radius: 0px;
padding: 0;
}
.emotion-10 {
padding: 0 10px;
margin: 0;
}
.emotion-8 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: justify;
-webkit-justify-content: space-between;
-ms-flex-pack: justify;
justify-content: space-between;
}
.emotion-4 {
display: inline-block;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
height: 21px;
font-size: 1rem;
}
<ul
class="MuiList-root MuiList-padding MuiList-subheader"
data-testid="installList"
>
<h6
class="MuiTypography-root emotion-0 emotion-1 MuiTypography-subtitle1"
>
Installation
</h6>
<div
aria-disabled="false"
class="MuiButtonBase-root MuiListItem-root emotion-12 emotion-13 MuiListItem-gutters MuiListItem-button"
data-testid="installListItem-npm"
role="button"
tabindex="0"
>
<div
class="MuiAvatar-root MuiAvatar-circle emotion-2 emotion-3"
>
<img
alt="npm"
class="MuiAvatar-img"
src="[object Object]"
/>
</div>
<div
class="MuiListItemText-root emotion-10 emotion-11 MuiListItemText-multiline"
>
<span
class="MuiTypography-root MuiListItemText-primary MuiTypography-body1"
>
<div
class="emotion-8 emotion-9"
>
<span
class="emotion-4 emotion-5"
>
npm install foo
</span>
<button
class="MuiButtonBase-root MuiIconButton-root emotion-6 emotion-7"
tabindex="0"
title="Copy to Clipboard"
type="button"
>
<span
class="MuiIconButton-label"
>
<svg
aria-hidden="true"
class="MuiSvgIcon-root"
focusable="false"
role="presentation"
viewBox="0 0 24 24"
>
<path
d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm-1 4l6 6v10c0 1.1-.9 2-2 2H7.99C6.89 23 6 22.1 6 21l.01-14c0-1.1.89-2 1.99-2h7zm-1 7h5.5L14 6.5V12z"
/>
</svg>
</span>
<span
class="MuiTouchRipple-root"
/>
</button>
</div>
</span>
<p
class="MuiTypography-root MuiListItemText-secondary MuiTypography-body2 MuiTypography-colorTextSecondary"
>
Install using npm
</p>
</div>
<span
class="MuiTouchRipple-root"
/>
</div>
<div
aria-disabled="false"
class="MuiButtonBase-root MuiListItem-root emotion-12 emotion-13 MuiListItem-gutters MuiListItem-button"
data-testid="installListItem-yarn"
role="button"
tabindex="0"
>
<div
class="MuiAvatar-root MuiAvatar-circle emotion-2 emotion-3"
>
<img
alt="yarn"
class="MuiAvatar-img"
src="[object Object]"
/>
</div>
<div
class="MuiListItemText-root emotion-10 emotion-11 MuiListItemText-multiline"
>
<span
class="MuiTypography-root MuiListItemText-primary MuiTypography-body1"
>
<div
class="emotion-8 emotion-9"
>
<span
class="emotion-4 emotion-5"
>
yarn add foo
</span>
<button
class="MuiButtonBase-root MuiIconButton-root emotion-6 emotion-7"
tabindex="0"
title="Copy to Clipboard"
type="button"
>
<span
class="MuiIconButton-label"
>
<svg
aria-hidden="true"
class="MuiSvgIcon-root"
focusable="false"
role="presentation"
viewBox="0 0 24 24"
>
<path
d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm-1 4l6 6v10c0 1.1-.9 2-2 2H7.99C6.89 23 6 22.1 6 21l.01-14c0-1.1.89-2 1.99-2h7zm-1 7h5.5L14 6.5V12z"
/>
</svg>
</span>
<span
class="MuiTouchRipple-root"
/>
</button>
</div>
</span>
<p
class="MuiTypography-root MuiListItemText-secondary MuiTypography-body2 MuiTypography-colorTextSecondary"
>
Install using yarn
</p>
</div>
<span
class="MuiTouchRipple-root"
/>
</div>
<div
aria-disabled="false"
class="MuiButtonBase-root MuiListItem-root emotion-12 emotion-13 MuiListItem-gutters MuiListItem-button"
data-testid="installListItem-pnpm"
role="button"
tabindex="0"
>
<div
class="MuiAvatar-root MuiAvatar-circle emotion-2 emotion-3"
>
<img
alt="pnpm"
class="MuiAvatar-img"
src="[object Object]"
/>
</div>
<div
class="MuiListItemText-root emotion-10 emotion-11 MuiListItemText-multiline"
>
<span
class="MuiTypography-root MuiListItemText-primary MuiTypography-body1"
>
<div
class="emotion-8 emotion-9"
>
<span
class="emotion-4 emotion-5"
>
pnpm install foo
</span>
<button
class="MuiButtonBase-root MuiIconButton-root emotion-6 emotion-7"
tabindex="0"
title="Copy to Clipboard"
type="button"
>
<span
class="MuiIconButton-label"
>
<svg
aria-hidden="true"
class="MuiSvgIcon-root"
focusable="false"
role="presentation"
viewBox="0 0 24 24"
>
<path
d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm-1 4l6 6v10c0 1.1-.9 2-2 2H7.99C6.89 23 6 22.1 6 21l.01-14c0-1.1.89-2 1.99-2h7zm-1 7h5.5L14 6.5V12z"
/>
</svg>
</span>
<span
class="MuiTouchRipple-root"
/>
</button>
</div>
</span>
<p
class="MuiTypography-root MuiListItemText-secondary MuiTypography-body2 MuiTypography-colorTextSecondary"
>
Install using pnpm
</p>
</div>
<span
class="MuiTouchRipple-root"
/>
</div>
</ul>
`;

View File

@ -1,36 +0,0 @@
import Avatar from '@material-ui/core/Avatar';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import Typography from '@material-ui/core/Typography';
import styled from 'react-emotion';
import { fontWeight } from '../../utils/styles/sizes';
export const Heading = styled(Typography)({
'&&': {
fontWeight: fontWeight.bold,
textTransform: 'capitalize',
},
});
export const InstallItem = styled(ListItem)({
'&&': {
padding: 0,
},
'&&:hover': {
backgroundColor: 'transparent',
},
});
export const InstallListItemText = styled(ListItemText)({
'&&': {
padding: '0 10px',
margin: 0,
},
});
export const PackageMangerAvatar = styled(Avatar)({
'&&': {
borderRadius: '0px',
padding: '0',
},
});

View File

@ -1,5 +1,6 @@
import React from 'react'; import React from 'react';
import { mount } from 'enzyme';
import { render } from '../../utils/test-react-testing-library';
import Label from './Label'; import Label from './Label';
@ -8,7 +9,7 @@ describe('<Label /> component', () => {
text: 'test', text: 'test',
}; };
test('should render the component in default state', () => { test('should render the component in default state', () => {
const wrapper = mount(<Label text={props.text} />); const { container } = render(<Label text={props.text} />);
expect(wrapper.html()).toMatchSnapshot(); expect(container.firstChild).toMatchSnapshot();
}); });
}); });

View File

@ -1,26 +1,26 @@
import React from 'react'; import React from 'react';
import styled from 'react-emotion'; import styled from '@emotion/styled';
import { fontWeight } from '../../utils/styles/sizes'; import { fontWeight } from '../../utils/styles/sizes';
interface Props { interface Props {
text: string; text: string;
capitalize?: boolean; capitalize?: boolean;
weight?: string; weight?: string;
modifiers?: null | undefined;
} }
const Wrapper = styled('div')` interface WrapperProps {
font-weight: ${({ weight }) => { capitalize: boolean;
// @ts-ignore weight: string;
return fontWeight[weight]; }
}};
text-transform: ${({ capitalize }) => (capitalize ? 'capitalize' : 'none')}; const Wrapper = styled('div')<WrapperProps>(props => ({
${({ modifiers }: Props) => modifiers && modifiers}; fontWeight: fontWeight[props.weight],
`; textTransform: props.capitalize ? 'capitalize' : 'none',
}));
const Label: React.FC<Props> = ({ text = '', capitalize = false, weight = 'regular', ...props }) => { const Label: React.FC<Props> = ({ text = '', capitalize = false, weight = 'regular', ...props }) => {
return ( return (
// @ts-ignore
<Wrapper capitalize={capitalize} weight={weight} {...props}> <Wrapper capitalize={capitalize} weight={weight} {...props}>
{text} {text}
</Wrapper> </Wrapper>

View File

@ -1,3 +1,14 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<Label /> component should render the component in default state 1`] = `"<div class=\\"css-1xfhjjm esyufg60\\">test</div>"`; exports[`<Label /> component should render the component in default state 1`] = `
.emotion-0 {
font-weight: 400;
text-transform: none;
}
<div
class="emotion-0 emotion-1"
>
test
</div>
`;

View File

@ -1,28 +1,29 @@
import styled, { css } from 'react-emotion'; import styled from '@emotion/styled';
import colors from '../../utils/styles/colors'; import { css } from '@emotion/core';
export const Content = styled('div')({ import { Theme } from '../../design-tokens/theme';
'&&': {
backgroundColor: colors.white, export const Content = styled('div')<{ theme?: Theme }>(props => ({
backgroundColor: props.theme && props.theme.palette.white,
flex: 1, flex: 1,
display: 'flex', display: 'flex',
position: 'relative', position: 'relative',
flexDirection: 'column', flexDirection: 'column',
}, }));
});
export const Container = styled('div')` interface ContainerProps {
&& { isLoading: boolean;
display: flex; }
flex-direction: column;
min-height: 100vh; export const Container = styled('div')<ContainerProps>(props => ({
overflow: hidden; display: 'flex',
${props => flexDirection: 'column',
// @ts-ignore minHeight: '100vh',
props.isLoading && overflow: 'hidden',
...(props.isLoading &&
css` css`
${Content} { ${Content} {
background-color: #f5f6f8; background-color: #f5f6f8;
} }
`} `),
`; }));

View File

@ -1,14 +0,0 @@
import React from 'react';
import { mount } from 'enzyme';
import Link from './Link';
describe('<Link /> component', () => {
const props = {
to: 'https://github.com/verdaccio/ui',
};
test('should render the component in default state', () => {
const wrapper = mount(<Link blank={true} to={props.to} />);
expect(wrapper.html()).toMatchSnapshot();
});
});

View File

@ -1,15 +1,26 @@
import React, { ReactNode } from 'react'; import React from 'react';
import { Link as RouterLink } from 'react-router-dom';
interface Props { import Text, { TextProps } from '../../muiComponents/Text';
children?: ReactNode;
interface Props extends Pick<TextProps, 'variant'> {
external?: boolean;
className?: string;
to: string; to: string;
blank?: boolean;
} }
const Link: React.FC<Props> = ({ children, to = '#', blank = false, ...props }) => ( /* eslint-disable verdaccio/jsx-spread */
<a href={to} target={blank ? '_blank' : '_self'} {...props}> const Link: React.FC<Props> = ({ external, to, children, variant, className, ...props }) => {
{children} const LinkTextContent = <Text variant={variant}>{children}</Text>;
return external ? (
<a className={className} href={to} rel="noopener noreferrer" target="_blank" {...props}>
{LinkTextContent}
</a> </a>
); ) : (
<RouterLink className={className} to={to} {...props}>
{LinkTextContent}
</RouterLink>
);
};
export default Link; export default Link;

View File

@ -1,3 +0,0 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<Link /> component should render the component in default state 1`] = `"<a href=\\"https://github.com/verdaccio/ui\\" target=\\"_blank\\"></a>"`;

Some files were not shown because too many files have changed in this diff Show More