Skip to content

Commit

Permalink
Merge pull request #1 from adamborowski/test-pr
Browse files Browse the repository at this point in the history
feat: use simple unicode icons
  • Loading branch information
adamborowski committed Jan 9, 2023
2 parents 17649b6 + 0335c79 commit 2992b86
Show file tree
Hide file tree
Showing 11 changed files with 203 additions and 36 deletions.
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
REACT_APP_GITHUB_TOKEN=<generate developer key from github>
4 changes: 3 additions & 1 deletion .github/workflows/chromatic.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,6 @@ jobs:
# Chromatic GitHub Action options
with:
# 👇 Chromatic projectToken, refer to the manage page to obtain it.
projectToken: ${{ secrets.CHROMATIC_PROJECT_TOKEN }}
projectToken: ${{ secrets.CHROMATIC_PROJECT_TOKEN }}
env:
REACT_APP_GITHUB_TOKEN: ${{ secrets.REACT_APP_GITHUB_TOKEN }}
3 changes: 3 additions & 0 deletions .storybook/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,7 @@ module.exports = {
disable: true,
},
},
features: {
interactionsDebugger: true, // 👈 Enable playback controls
},
};
118 changes: 92 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,46 +1,112 @@
# Getting Started with Create React App
# Listing Repositories

This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Verifications

## Available Scripts

In the project directory, you can run:
### Local development.

### `npm start`
First, copy `.env` to `.env.local` file and provide your GitHub developer token.

Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
Then you can start with
```shell
npm start
```

The page will reload if you make edits.\
You will also see any lint errors in the console.
### Build & lint

### `npm test`
In order to check typescript or eslint error, run the following command:

Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
```shell
npm run build --ci
```

### `npm run build`
### Tests

Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
Unit tests can be executed with this command:

The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
```shell
npm test
```

See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
End-to-end tests are held by Chromatic, and are available through online console.
You can access them from [GitHub Actions](https://github.com/adamborowski/react-arch-demo/actions)
and Pull Request check links or the [Invite link](https://www.chromatic.com/start?inviteToken=c1f1799677414c5ea8c88c4a7fe6e323&appId=63bc6c85068cfb74e4b8240d).

### `npm run eject`
See [Online Chromatic Storybook](https://www.chromatic.com/library?appId=63bc6c85068cfb74e4b8240d&branch=master).

**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
### Component-Driven development

If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
You can start storybook and see important component use cases and interactive scenarios.

Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
```shell
npm run storybook
```

You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
Please see `Client In Memory Mock` story for dynamic scenario (Play feature)

## Learn More
## Architecture

You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
My main goal in this task is demonstrate the specific implementation of the architectural
pattern called [functional core, imperative shell](https://kennethlange.com/functional-core-imperative-shell/)
I found pretty simple and useful for medium-sized applications.

To learn React, check out the [React documentation](https://reactjs.org/).
**Disclaimer**: for performance questions regarding simple top-down props passing, I can refer to [react-fast-context](https://github.com/adamborowski/passionware/tree/master/packages/react-fast-context) for example.

In this demo application I separated `view`, `interaction` and `IO` and allow them to be easily substituted.

View layer consists of pure components that rely mainly on props and do not have any business level state.
It can be composed of other components with separate responsibilities: pure page, layout, data display.

Then we have state layer which cares about async interactions and holds the state.
This usually composes custom interaction hooks (separated from UI) and pure view component

Last layer is the client layer which provides the actual implementation for every IO operation.

In addition to that, we have component concepts:

- Display component, i.e. `RepositoriesEmptyMessage`, `RepositoriesList`
- Layout component, i.e. `RepositoriesSearchPageLayout` which cares about css layouts
- Page pure component which usually represents one big UI feature / routing page and is pure (no state and side effects), i.e. `RepositoriesSearchPagePure`
- Page connected component which integrates pure page with special interaction hook (state, side effects), i.e. `RepositoriesSearchPageConnected`

Connected Page component is likely to accept only I/O clients as props.

Client is a set of functions that start IO operations and return a promise.

The goal of the client concept is to easily change the IO implementation depending on the use case.
We can have separate client for storybook or testing (in memory client), or fetch, graphql, local storage - for production.
We also can have adapters that allow to use one client that accepts data in a specific shape and transforms into a local structure.
This enables easy switching between backend versions that may differ in the schema.
After all, we can use `zod`, the powerful typescript-first schema library that allows us for very easy runtime validation of I/O data structures.

In addition to that we can have higher order clients (`withFailing`, `withDelay`) that make it very simple to reproduce scenarios that are hard to reproduce in development environments.

Thanks to that we don't need to mock or hack our code at all!
And in combination with storybook, we can have all popular use cases available to reproduce in one menu.



## What's new to me

- first time using Chakra UI, previous experience with:
- Ant Design
- Material Design
- Cloudinary Design System (maintainer, will be open sourced)
- Semantic UI
- React-Bootstrap
- first time using GraphQL
- using raw GraphQL at the thinnest layer
- not using react-query or Apollo
- I wanted to present the clean and simple architecture,
- it requires that we have an abstract "client" interface that is promise-based


## What's not included

- Pagination is not implemented, it loads first 50 records.
- my existing virtual scroll with data fetching [example](https://adamborowski.github.io/imdb-hooks/movies) (search for "spider" and scroll) with [source](https://github.com/adamborowski/imdb-hooks/tree/master/src/aspects/list)
- Not doing browser checking, prepared for newest Google Chrome
- Routing - would use react-router but this time it would be small ROI for one page


Project generated using [Create React App](https://create-react-app.dev/),
43 changes: 43 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"@storybook/addon-interactions": "^6.5.15",
"@storybook/addon-links": "^6.5.15",
"@storybook/builder-webpack5": "^6.5.15",
"@storybook/jest": "^0.0.10",
"@storybook/manager-webpack5": "^6.5.15",
"@storybook/node-logger": "^6.5.15",
"@storybook/preset-create-react-app": "^4.1.2",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ import { createGraphqlSearchClient } from "../../../../common/api/clients/graphq

export const repositorySearchClient = createGraphqlSearchClient(
"https://api.github.com/graphql",
"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",
process.env.REACT_APP_GITHUB_TOKEN!,
repositoryAdapter
);
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ import { repositoryAdapter } from "./repositoryAdapter";

export const repositorySearchClient = createFetchSearchClient(
(query) => `https://api.github.com/search/repositories?q=${query}`,
"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",
process.env.REACT_APP_GITHUB_TOKEN!,
repositoryAdapter
);
7 changes: 3 additions & 4 deletions src/features/repositories/components/RepositoryCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import {
Text,
} from "@chakra-ui/react";

import { ArrowUpIcon, StarIcon } from "@chakra-ui/icons";
import { FormattedMessage, useIntl } from "react-intl";
import { messages } from "../../../i18n/messages";

Expand All @@ -29,7 +28,7 @@ export const RepositoryCard: FC<RepositoryCardProps> = ({
return (
<Card {...rest} data-testid="repository-card">
<CardBody>
<Stack mt="6" spacing="3">
<Stack mt="6" spacing="3" data-chromatic="ignore">
<Heading size="md">
{repository.owner} &raquo; {repository.name}
</Heading>
Expand All @@ -42,9 +41,9 @@ export const RepositoryCard: FC<RepositoryCardProps> = ({
gap="1"
title={formatMessage(messages.statsTooltip)}
>
<StarIcon boxSize="4" />
🌟
{repository.numStars}
<ArrowUpIcon boxSize="4" />
🍴
{repository.numForks}
</Text>
</Stack>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ import { withFailure } from "../../../../common/api/clients/development/withFail
import { withLoading } from "../../../../common/api/clients/development/withLoading";
import { Repository } from "../../types";
import { inMemorySearchClient } from "./__test__/test-common";
import { screen, userEvent, waitFor } from "@storybook/testing-library";
import { expect } from "@storybook/jest";
import { delay } from "../../../../common/utils/delay";

export default {
component: RepositorySearchPageConnected,
Expand All @@ -22,6 +25,56 @@ export const ClientInMemoryMock: ComponentStory<
return <RepositorySearchPageConnected searchClient={client} />;
};

ClientInMemoryMock.play = async ({ canvasElement }) => {
expect(screen.getByTestId("spinner")).toBeVisible();
await waitFor(
async () => {
await expect(screen.queryByTestId("spinner")).not.toBeInTheDocument();
},
{ timeout: 10000 }
);
expect(screen.getAllByTestId("repository-card")).toHaveLength(4);

// change query to "angular" and search
await userEvent.click(screen.getByDisplayValue("react"));
await userEvent.keyboard("{selectall}12", { delay: 100 });
await delay(300);
await userEvent.click(screen.getByText("Search"));

// now search button should be disabled and we should wait for results
expect(screen.getByText("Search")).toBeDisabled();
expect(screen.getByTestId("spinner")).toBeVisible();

await waitFor(
async () => {
await expect(screen.queryByTestId("spinner")).not.toBeInTheDocument();
},
{ timeout: 10000 }
);

// we should see only two repositories in results
expect(screen.getAllByTestId("repository-card")).toHaveLength(2);

// change query to "reactandangularforevertogether" and search
await userEvent.click(screen.getByDisplayValue("12"));
await userEvent.keyboard("{selectall}reactandangularforevertogether", {
delay: 100,
});
await delay(300);
await userEvent.click(screen.getByText("Search"));

await waitFor(
async () => {
await expect(screen.queryByTestId("spinner")).not.toBeInTheDocument();
},
{ timeout: 10000 }
);

expect(screen.queryAllByTestId("repository-card")).toHaveLength(0);
expect(screen.getByText("No repositories found")).toBeVisible();
};


export const ClientRest: ComponentStory<typeof RepositorySearchPageConnected> =
() => <RepositorySearchPageConnected searchClient={restClient} />;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,15 +79,15 @@ describe("RepositorySearchPage.pure", () => {
expect(firstCardView.getByText("first repo")).toBeVisible();
expect(firstCardView.getByText(/Primo/)).toBeVisible();
expect(firstCardView.getByTitle("Stars and forks")).toHaveTextContent(
"10100"
"🌟10🍴100"
);

const secondCardView = within(cardViews[1]);
expect(secondCardView.getByText(/Bar/)).toBeVisible();
expect(secondCardView.getByText("second repo")).toBeVisible();
expect(secondCardView.getByText(/Secondo/)).toBeVisible();
expect(secondCardView.getByTitle("Stars and forks")).toHaveTextContent(
"20200"
"🌟20🍴200"
);
});

Expand Down Expand Up @@ -149,5 +149,4 @@ describe("RepositorySearchPage.pure", () => {
userEvent.click(screen.getByText("Search")); // click anyway
expect(onSubmitMock).not.toBeCalled();
});

});

0 comments on commit 2992b86

Please sign in to comment.