Create app namespace for all absolute requires of app modules. Move all packages under packages yarn workspace

This commit is contained in:
SleepWalker
2019-12-07 21:02:00 +02:00
parent d8d2df0702
commit f9d3bb4e20
404 changed files with 758 additions and 742 deletions

View File

@@ -0,0 +1,5 @@
{
"criticalErrorHappened": "There was a critical error due to which the application can not continue its normal operation.",
"reloadPageOrContactUs": "Please reload this page and try again. If problem occurs again, please report it to the developers by sending email to",
"alsoYouCanInteractWithBackground": "You can also play around with the background it's interactable ;)"
}

View File

@@ -0,0 +1,75 @@
import React from 'react';
import { FormattedMessage as Message } from 'react-intl';
import { IntlProvider } from 'app/components/i18n';
import logger from 'app/services/logger';
import appInfo from 'app/components/auth/appInfo/AppInfo.intl.json';
import styles from './styles.scss';
import BoxesField from './BoxesField';
import messages from './BSoD.intl.json';
interface State {
lastEventId?: string | void;
}
// TODO: probably it is better to render this view from the App view
// to remove dependencies from store and IntlProvider
class BSoD extends React.Component<{}, State> {
state: State = {};
componentDidMount() {
// poll for event id
const timer = setInterval(() => {
if (!logger.getLastEventId()) {
return;
}
clearInterval(timer);
this.setState({
lastEventId: logger.getLastEventId(),
});
}, 500);
}
render() {
const { lastEventId } = this.state;
let emailUrl = 'mailto:support@ely.by';
if (lastEventId) {
emailUrl += `?subject=Bug report for #${lastEventId}`;
}
return (
<IntlProvider>
<div className={styles.body}>
<canvas
className={styles.canvas}
ref={(el: HTMLCanvasElement | null) => el && new BoxesField(el)}
/>
<div className={styles.wrapper}>
<div className={styles.title}>
<Message {...appInfo.appName} />
</div>
<div className={styles.lineWithMargin}>
<Message {...messages.criticalErrorHappened} />
</div>
<div className={styles.line}>
<Message {...messages.reloadPageOrContactUs} />
</div>
<a href={emailUrl} className={styles.support}>
support@ely.by
</a>
<div className={styles.easterEgg}>
<Message {...messages.alsoYouCanInteractWithBackground} />
</div>
</div>
</div>
</IntlProvider>
);
}
}
export default BSoD;

View File

@@ -0,0 +1,100 @@
export default class Box {
constructor({ size, startX, startY, startRotate, color, shadowColor }) {
this.color = color;
this.shadowColor = shadowColor;
this.halfSize = 0;
this.setSize(size);
this.x = startX;
this.y = startY;
this.angle = startRotate;
this.shadowLength = 2000; // TODO: should be calculated
}
get size() {
return this._initialSize;
}
get dots() {
const full = (Math.PI * 2) / 4;
const p1 = {
x: this.x + this.halfSize * Math.sin(this.angle),
y: this.y + this.halfSize * Math.cos(this.angle),
};
const p2 = {
x: this.x + this.halfSize * Math.sin(this.angle + full),
y: this.y + this.halfSize * Math.cos(this.angle + full),
};
const p3 = {
x: this.x + this.halfSize * Math.sin(this.angle + full * 2),
y: this.y + this.halfSize * Math.cos(this.angle + full * 2),
};
const p4 = {
x: this.x + this.halfSize * Math.sin(this.angle + full * 3),
y: this.y + this.halfSize * Math.cos(this.angle + full * 3),
};
return { p1, p2, p3, p4 };
}
rotate() {
const speed = (60 - this.halfSize) / 20;
this.angle += speed * 0.002;
this.x += speed;
this.y += speed;
}
draw(ctx) {
const { dots } = this;
ctx.beginPath();
ctx.moveTo(dots.p1.x, dots.p1.y);
ctx.lineTo(dots.p2.x, dots.p2.y);
ctx.lineTo(dots.p3.x, dots.p3.y);
ctx.lineTo(dots.p4.x, dots.p4.y);
ctx.fillStyle = this.color;
ctx.fill();
}
drawShadow(ctx, light) {
const { dots } = this;
const angles = [];
const points = [];
for (const i in dots) {
if (!dots.hasOwnProperty(i)) {
continue;
}
const dot = dots[i];
const angle = Math.atan2(light.y - dot.y, light.x - dot.x);
const endX = dot.x + this.shadowLength * Math.sin(-angle - Math.PI / 2);
const endY = dot.y + this.shadowLength * Math.cos(-angle - Math.PI / 2);
angles.push(angle);
points.push({
endX,
endY,
startX: dot.x,
startY: dot.y,
});
}
for (let i = points.length - 1; i >= 0; i--) {
const n = i === 3 ? 0 : i + 1;
ctx.beginPath();
ctx.moveTo(points[i].startX, points[i].startY);
ctx.lineTo(points[n].startX, points[n].startY);
ctx.lineTo(points[n].endX, points[n].endY);
ctx.lineTo(points[i].endX, points[i].endY);
ctx.fillStyle = this.shadowColor;
ctx.fill();
}
}
setSize(size) {
this._initialSize = size;
this.halfSize = Math.floor(size / 2);
}
}

View File

@@ -0,0 +1,158 @@
import Box from './Box';
/**
* Основано на http://codepen.io/mladen___/pen/gbvqBo
*/
export default class BoxesField {
/**
* @param {HTMLCanvasElement} elem - canvas DOM node
* @param {object} params
*/
constructor(
elem,
params = {
countBoxes: 14,
boxMinSize: 20,
boxMaxSize: 75,
backgroundColor: '#233d49',
lightColor: '#28555b',
shadowColor: '#274451',
boxColors: [
'#207e5c',
'#5b9aa9',
'#e66c69',
'#6b5b8c',
'#8b5d79',
'#dd8650',
],
},
) {
this.elem = elem;
const ctx = elem.getContext('2d');
if (!ctx) {
throw new Error('Can not get canvas 2d context');
}
this.ctx = ctx;
this.params = params;
this.light = {
x: 160,
y: 200,
};
this.resize();
this.drawLoop();
this.bindWindowListeners();
/**
* @type {Box[]}
*/
this.boxes = [];
while (this.boxes.length < this.params.countBoxes) {
this.boxes.push(
new Box({
size: Math.floor(
Math.random() * (this.params.boxMaxSize - this.params.boxMinSize) +
this.params.boxMinSize,
),
startX: Math.floor(Math.random() * elem.width + 1),
startY: Math.floor(Math.random() * elem.height + 1),
startRotate: Math.random() * Math.PI,
color: this.getRandomColor(),
shadowColor: this.params.shadowColor,
}),
);
}
}
resize() {
const { width, height } = this.elem.getBoundingClientRect();
this.elem.width = width;
this.elem.height = height;
}
drawLight(light) {
const greaterSize =
window.screen.width > window.screen.height
? window.screen.width
: window.screen.height;
// еее, теорема пифагора и описывание окружности вокруг квадрата, не зря в универ ходил!!!
const lightRadius = greaterSize * Math.sqrt(2);
this.ctx.beginPath();
this.ctx.arc(light.x, light.y, lightRadius, 0, 2 * Math.PI);
const gradient = this.ctx.createRadialGradient(
light.x,
light.y,
0,
light.x,
light.y,
lightRadius,
);
gradient.addColorStop(0, this.params.lightColor);
gradient.addColorStop(1, this.params.backgroundColor);
this.ctx.fillStyle = gradient;
this.ctx.fill();
}
drawLoop() {
this.ctx.clearRect(0, 0, this.elem.width, this.elem.height);
this.drawLight(this.light);
for (const i in this.boxes) {
if (!this.boxes.hasOwnProperty(i)) {
continue;
}
const box = this.boxes[i];
box.rotate();
box.drawShadow(this.ctx, this.light);
}
for (const i in this.boxes) {
if (!this.boxes.hasOwnProperty(i)) {
continue;
}
const box = this.boxes[i];
box.draw(this.ctx);
// Если квадратик вылетел за пределы экрана
if (box.y - box.halfSize > this.elem.height) {
box.y -= this.elem.height + 100;
this.updateBox(box);
}
if (box.x - box.halfSize > this.elem.width) {
box.x -= this.elem.width + 100;
this.updateBox(box);
}
}
requestAnimationFrame(this.drawLoop.bind(this));
}
bindWindowListeners() {
window.addEventListener('resize', this.resize.bind(this));
window.addEventListener('mousemove', event => {
this.light.x = event.clientX;
this.light.y = event.clientY;
});
}
/**
* @param {Box} box
*/
updateBox(box) {
box.color = this.getRandomColor();
}
getRandomColor() {
return this.params.boxColors[
Math.floor(Math.random() * this.params.boxColors.length)
];
}
}

View File

@@ -0,0 +1,49 @@
import expect from 'app/test/unexpected';
import sinon from 'sinon';
import BsodMiddleware from 'app/components/ui/bsod/BsodMiddleware';
describe('BsodMiddleware', () => {
[500, 503, 555].forEach(code =>
it(`should dispatch for ${code}`, () => {
const resp = {
originalResponse: { status: code },
};
const dispatchBsod = sinon.spy();
const logger = { warn: sinon.spy() };
const middleware = new BsodMiddleware(dispatchBsod, logger as any);
return expect(middleware.catch(resp), 'to be rejected with', resp).then(
() => {
expect(dispatchBsod, 'was called');
expect(logger.warn, 'to have a call satisfying', [
'Unexpected response (BSoD)',
{ resp },
]);
},
);
}),
);
[200, 404].forEach(code =>
it(`should not dispatch for ${code}`, () => {
const resp = {
originalResponse: { status: code },
};
const dispatchBsod = sinon.spy();
const logger = { warn: sinon.spy() };
const middleware = new BsodMiddleware(dispatchBsod, logger as any);
return expect(middleware.catch(resp), 'to be rejected with', resp).then(
() => {
expect(dispatchBsod, 'was not called');
expect(logger.warn, 'was not called');
},
);
}),
);
});

View File

@@ -0,0 +1,49 @@
import { InternalServerError } from 'app/services/request';
import { Resp, Middleware } from 'app/services/request';
import defaultLogger from 'app/services/logger';
type Logger = typeof defaultLogger;
const ABORT_ERR = 20;
class BsodMiddleware implements Middleware {
dispatchBsod: () => any;
logger: Logger;
constructor(dispatchBsod: () => any, logger: Logger = defaultLogger) {
this.dispatchBsod = dispatchBsod;
this.logger = logger;
}
async catch<T extends Resp<any>>(
resp?: T | InternalServerError | Error,
): Promise<T> {
const { originalResponse }: { originalResponse?: Resp<any> } = (resp ||
{}) as InternalServerError;
if (
resp &&
((resp instanceof InternalServerError &&
(resp.error as any).code !== ABORT_ERR) ||
(originalResponse && /5\d\d/.test(originalResponse.status)))
) {
this.dispatchBsod();
const { message: errorMessage } = resp as { [key: string]: any };
if (!errorMessage || !/NetworkError/.test(errorMessage)) {
let message = 'Unexpected response (BSoD)';
if (errorMessage) {
message = `BSoD: ${errorMessage}`;
}
this.logger.warn(message, { resp });
}
}
return Promise.reject(resp);
}
}
export default BsodMiddleware;

View File

@@ -0,0 +1,10 @@
export const BSOD = 'BSOD';
/**
* @returns {object}
*/
export function bsod() {
return {
type: BSOD,
};
}

View File

@@ -0,0 +1,20 @@
import React from 'react';
import ReactDOM from 'react-dom';
import { bsod } from './actions';
import BSoD from 'app/components/ui/bsod/BSoD';
let injectedStore;
let onBsod;
export default function dispatchBsod(store = injectedStore) {
store.dispatch(bsod());
onBsod && onBsod();
ReactDOM.render(<BSoD />, document.getElementById('app'));
}
export function inject(store, stopLoading) {
injectedStore = store;
onBsod = stopLoading;
}

View File

@@ -0,0 +1,12 @@
import request from 'app/services/request';
import logger from 'app/services/logger';
import dispatchBsod, { inject } from './dispatchBsod';
import BsodMiddleware from './BsodMiddleware';
export default function factory(store, stopLoading) {
inject(store, stopLoading);
// do bsod for 500/404 errors
request.addMiddleware(new BsodMiddleware(dispatchBsod, logger));
}

View File

@@ -0,0 +1,9 @@
import { BSOD } from './actions';
export default function(state = false, { type }) {
if (type === BSOD) {
return true;
}
return state;
}

View File

@@ -0,0 +1,57 @@
@import '~app/components/ui/colors.scss';
$font-family-monospaced: 'Consolas', 'Menlo', 'DejaVu Sans Mono', 'Roboto Mono',
monospace;
.body {
height: 100%;
background-color: $dark_blue;
color: #fff;
text-align: center;
font-family: $font-family-monospaced;
box-sizing: border-box;
}
.canvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.wrapper {
position: relative;
margin: 85px auto 0;
max-width: 500px;
padding: 0 20px;
}
.title {
font-size: 26px;
margin-bottom: 13px;
}
.line {
margin: 0 auto;
font-size: 16px;
color: #ebe8e1;
}
.lineWithMargin {
composes: line;
margin-bottom: 20px;
}
.support {
font-size: 18px;
color: #fff;
margin: 3px 0 44px;
display: block;
}
.easterEgg {
font-size: 14px;
color: #ebe8e1;
}