Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

Some minor UI refactoring and enhancement (#52)

Guilherme Oenningb300066d7d9c
diff --git a/app/middlewares/setup.go b/app/middlewares/setup.go
index 690f56697..3e2cc1f64 100644
--- a/app/middlewares/setup.go
+++ b/app/middlewares/setup.go
@@ -16,7 +16,7 @@ func Setup(db *dbx.Database) web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
return func(c web.Context) error {
logger := c.Logger().(*log.Logger)
- logger.Debugf("HTTP Request %s", logger.Color().Bold(logger.Color().RedBg(c.Request().URL)))
+ logger.Debugf("HTTP Request %s", logger.Color().Bold(logger.Color().RedBg(c.Request().Method+" "+c.Request().URL.String())))
trx, err := db.Begin()
if err != nil {
diff --git a/package-lock.json b/package-lock.json
index 9da7a30e5..7543625bc 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -71,12 +71,6 @@
"integrity": "sha1-opbhf3v658HOT34N5T0pyzIWLfA=",
"dev": true
},
- "align-text": {
- "version": "0.1.4",
- "resolved": "https://registry.npmjs.org/align-text/-/align-text-0.1.4.tgz",
- "integrity": "sha1-DNkKVhCT810KmSVsIrcGlDP60Rc=",
- "dev": true
- },
"alphanum-sort": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/alphanum-sort/-/alphanum-sort-1.0.2.tgz",
@@ -420,20 +414,6 @@
"integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=",
"dev": true
},
- "center-align": {
- "version": "0.1.3",
- "resolved": "https://registry.npmjs.org/center-align/-/center-align-0.1.3.tgz",
- "integrity": "sha1-qg0yYptu6XIgBBHL1EYckHvCt60=",
- "dev": true,
- "dependencies": {
- "lazy-cache": {
- "version": "1.0.4",
- "resolved": "https://registry.npmjs.org/lazy-cache/-/lazy-cache-1.0.4.tgz",
- "integrity": "sha1-odePw6UEdMuAhF07O24dpJpEbo4=",
- "dev": true
- }
- }
- },
"chalk": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz",
@@ -1959,6 +1939,16 @@
"integrity": "sha1-y8NcYu7uc/Gat7EKgBURQBr8D5A=",
"dev": true
},
+ "inversify": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/inversify/-/inversify-4.1.1.tgz",
+ "integrity": "sha1-qV7bNK4IK7EXUzbVHc1fARE0xiU="
+ },
+ "inversify-inject-decorators": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/inversify-inject-decorators/-/inversify-inject-decorators-3.0.1.tgz",
+ "integrity": "sha1-3kbfRrpyZC6srHlFHsXBAeTbywA="
+ },
"invert-kv": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-1.0.0.tgz",
@@ -2311,12 +2301,6 @@
"integrity": "sha1-0CJTc662Uq3BvILklFM5qEJ1R3M=",
"dev": true
},
- "longest": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/longest/-/longest-1.0.1.tgz",
- "integrity": "sha1-MKCy2jj3N3DoKUoNIuZiXtd9AJc=",
- "dev": true
- },
"loose-envify": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.3.1.tgz",
@@ -3157,6 +3141,11 @@
"integrity": "sha1-WiAL+S4ON3UXUv5FsKszD9S2vpk=",
"dev": true
},
+ "reflect-metadata": {
+ "version": "0.1.10",
+ "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.1.10.tgz",
+ "integrity": "sha1-tPg3BEFqytiZiMmxVjXUfgO5NEo="
+ },
"regenerate": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/regenerate/-/regenerate-1.3.2.tgz",
@@ -3235,12 +3224,6 @@
"integrity": "sha1-ZVkHw0aahoDcLeOidaj91paR8OU=",
"dev": true
},
- "right-align": {
- "version": "0.1.3",
- "resolved": "https://registry.npmjs.org/right-align/-/right-align-0.1.3.tgz",
- "integrity": "sha1-YTObci/mo1FWiSENJOFMlhSGE+8=",
- "dev": true
- },
"rimraf": {
"version": "2.6.1",
"resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.1.tgz",
@@ -3796,18 +3779,6 @@
"integrity": "sha512-ijDLlyQ7s6x1JgCLur53osjm/UXUYD9+0PbYKrBsYisYXzCxN+HC3mYDNy/dWdmf3AwqwU3CXwDCvsNgGK1S0w==",
"dev": true
},
- "window-size": {
- "version": "0.1.0",
- "resolved": "https://registry.npmjs.org/window-size/-/window-size-0.1.0.tgz",
- "integrity": "sha1-VDjNLqk7IC76Ohn+iIeu58lPnJ0=",
- "dev": true
- },
- "wordwrap": {
- "version": "0.0.2",
- "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.2.tgz",
- "integrity": "sha1-t5Zpu0LstAn4PVg8rVLKF+qhZD8=",
- "dev": true
- },
"wrap-ansi": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz",
diff --git a/package.json b/package.json
index d5cc537cd..6a8bbef53 100644
--- a/package.json
+++ b/package.json
@@ -10,29 +10,32 @@
"lint": "tslint public/**/**.tsx public/**/**.ts"
},
"dependencies": {
- "axios": "^0.16.1",
+ "axios": "^0.16.2",
+ "inversify": "^4.1.1",
+ "inversify-inject-decorators": "^3.0.1",
"jquery": "^3.2.1",
"md5": "^2.2.1",
"moment": "^2.18.1",
"react": "^15.6.1",
"react-dom": "^15.6.1",
+ "reflect-metadata": "^0.1.10",
"semantic-ui-css": "^2.2.10",
"throttle-debounce": "^1.0.1"
},
"devDependencies": {
"@types/jquery": "^3.2.5",
"@types/md5": "^2.1.32",
- "@types/react": "^15.0.31",
+ "@types/react": "^15.0.33",
"@types/react-dom": "^15.5.1",
- "css-loader": "^0.28.1",
- "extract-text-webpack-plugin": "^2.1.0",
- "file-loader": "^0.11.1",
+ "css-loader": "^0.28.4",
+ "extract-text-webpack-plugin": "^2.1.2",
+ "file-loader": "^0.11.2",
"node-sass": "^4.5.3",
"rimraf": "^2.6.1",
"sass-loader": "^6.0.6",
- "ts-loader": "^2.2.0",
- "tslint": "^5.2.0",
- "typescript": "^2.3.2",
+ "ts-loader": "^2.2.1",
+ "tslint": "^5.4.3",
+ "typescript": "^2.4.1",
"webpack": "^3.0.0",
"webpack-clean-obsolete-chunks": "^0.1.10"
},
diff --git a/public/components/common/Button.tsx b/public/components/common/Button.tsx
new file mode 100644
index 000000000..3d329071a
--- /dev/null
+++ b/public/components/common/Button.tsx
@@ -0,0 +1,43 @@
+import * as React from 'react';
+
+interface ButtonProps {
+ classes?: string;
+ href?: string;
+ onClick?: () => Promise<any>;
+}
+
+interface ButtonState {
+ clicked: boolean;
+}
+
+export class Button extends React.Component<ButtonProps, ButtonState> {
+
+ public constructor(props: ButtonProps) {
+ super(props);
+ this.state = {
+ clicked: false
+ };
+ }
+
+ private async click() {
+ this.setState({ clicked: true });
+ if (this.props.onClick) {
+ await this.props.onClick();
+ this.setState({ clicked: false });
+ }
+ }
+
+ public render() {
+ const cssClasses = `ui button ${this.props.classes || ''} ${this.state.clicked ? 'loading disabled' : ''}`;
+ if (this.props.href) {
+ return <a href={this.props.href} className={cssClasses} onClick={() => this.click()}>
+ { this.props.children }
+ </a>;
+ } else {
+ return <button className={ cssClasses } onClick={() => this.click()}>
+ { this.props.children }
+ </button>;
+ }
+ }
+
+}
diff --git a/public/components/common/Form.tsx b/public/components/common/Form.tsx
new file mode 100644
index 000000000..31495b30c
--- /dev/null
+++ b/public/components/common/Form.tsx
@@ -0,0 +1,40 @@
+import * as React from 'react';
+import { Failure } from '../../services';
+import { DisplayError } from '../../shared/Common';
+
+interface FormProps {
+ onSubmit: () => Promise<any>;
+}
+
+interface FormState {
+ failure?: Failure;
+}
+
+export class Form extends React.Component<FormProps, FormState> {
+
+ public constructor(props: FormProps) {
+ super(props);
+ }
+
+ public async submit() {
+ if (this.props.onSubmit) {
+ await this.props.onSubmit();
+ }
+ }
+
+ public async clearFailure() {
+ this.setState({ failure: undefined });
+ }
+
+ public async setFailure(failure: Failure) {
+ this.setState({ failure });
+ }
+
+ public render() {
+ return <div className="ui form">
+ <DisplayError error={this.state && this.state.failure} />
+ { this.props.children }
+ </div>;
+ }
+
+}
diff --git a/public/components/common/index.tsx b/public/components/common/index.tsx
new file mode 100644
index 000000000..605f6b45b
--- /dev/null
+++ b/public/components/common/index.tsx
@@ -0,0 +1,2 @@
+export * from './Button';
+export * from './Form';
diff --git a/public/di/index.ts b/public/di/index.ts
new file mode 100644
index 000000000..8ca9bc569
--- /dev/null
+++ b/public/di/index.ts
@@ -0,0 +1,25 @@
+import 'reflect-metadata';
+import getDecorators from 'inversify-inject-decorators';
+import { Container, injectable } from 'inversify';
+
+const container = new Container();
+
+const {
+ lazyInject,
+ lazyInjectNamed,
+ lazyInjectTagged,
+ lazyMultiInject
+} = getDecorators(container);
+
+const injectables = {
+ Session: Symbol('Session'),
+ IdeaService: Symbol('IdeaService'),
+ TenantService: Symbol('TenantService'),
+};
+
+export {
+ container,
+ injectables,
+ injectable,
+ lazyInject as inject
+};
diff --git a/public/index.tsx b/public/index.tsx
index 16fe20d5c..8a2194512 100644
--- a/public/index.tsx
+++ b/public/index.tsx
@@ -5,7 +5,19 @@ import { HomePage as AdminHomePage } from './admin/HomePage';
import { HomePage as SiteHomePage } from './site/HomePage';
import { ShowIdeaPage } from './site/ShowIdeaPage';
import { SignUpPage } from './setup/SignUpPage';
-import { setup } from './storage';
+import { container, injectables } from './di';
+import {
+ Session,
+ BrowserSession,
+ IdeaService,
+ HttpIdeaService,
+ TenantService,
+ HttpTenantService
+} from './services';
+
+container.bind<Session>(injectables.Session).toConstantValue(new BrowserSession(window));
+container.bind<IdeaService>(injectables.IdeaService).to(HttpIdeaService);
+container.bind<TenantService>(injectables.TenantService).to(HttpTenantService);
import './main.scss';
@@ -14,7 +26,6 @@ const pathRegex = [
{ regex: new RegExp('^\/admin$'), component: <AdminHomePage /> },
{ regex: new RegExp('^\/signup$'), component: <SignUpPage /> },
{ regex: new RegExp('^\/ideas\/\\d+.*$'), component: <ShowIdeaPage /> },
-
];
const resolveRootComponent = (path: string): JSX.Element => {
@@ -27,8 +38,6 @@ const resolveRootComponent = (path: string): JSX.Element => {
return <div />;
};
-setup();
-
document.addEventListener('DOMContentLoaded', () => {
ReactDOM.render(
resolveRootComponent(location.pathname),
diff --git a/public/main.scss b/public/main.scss
index 3bcf84cbb..6f86e118d 100644
--- a/public/main.scss
+++ b/public/main.scss
@@ -44,6 +44,10 @@
.ui.items > .item > .content {
margin-left: 20px;
+
+ .description {
+ min-height: 10px;
+ }
}
}
diff --git a/public/services/IdeaService.ts b/public/services/IdeaService.ts
new file mode 100644
index 000000000..09e63b328
--- /dev/null
+++ b/public/services/IdeaService.ts
@@ -0,0 +1,34 @@
+import { get, post, Result } from './http';
+import { injectable } from '../di';
+import { Idea } from '../models';
+
+export interface IdeaService {
+ addSupport(ideaNumber: number): Promise<Result>;
+ removeSupport(ideaNumber: number): Promise<Result>;
+ addComment(ideaNumber: number, content: string): Promise<Result>;
+ setResponse(ideaNumber: number, status: number, text: string): Promise<Result>;
+ addIdea(title: string, description: string): Promise<Result<Idea>>;
+}
+
+@injectable()
+export class HttpIdeaService implements IdeaService {
+ public async addSupport(ideaNumber: number): Promise<Result> {
+ return await post(`/api/ideas/${ideaNumber}/support`);
+ }
+
+ public async removeSupport(ideaNumber: number): Promise<Result> {
+ return await post(`/api/ideas/${ideaNumber}/unsupport`);
+ }
+
+ public async addComment(ideaNumber: number, content: string): Promise<Result> {
+ return await post(`/api/ideas/${ideaNumber}/comments`, { content });
+ }
+
+ public async setResponse(ideaNumber: number, status: number, text: string): Promise<Result> {
+ return await post(`/api/ideas/${ideaNumber}/status`, { status, text });
+ }
+
+ public async addIdea(title: string, description: string): Promise<Result<Idea>> {
+ return await post<Idea>(`/api/ideas`, { title, description });
+ }
+}
diff --git a/public/services/Session.ts b/public/services/Session.ts
new file mode 100644
index 000000000..8817bca0d
--- /dev/null
+++ b/public/services/Session.ts
@@ -0,0 +1,65 @@
+import { User, AppSettings } from '../models';
+import { injectable } from '../di';
+
+export interface Session {
+ getCurrentUser(): User;
+ setUser(user: User): void;
+ isStaff(): boolean;
+ set<T>(key: string, value: T): void;
+ get<T>(key: string): T;
+ getArray<T>(key: string): T[];
+ getAppSettings(): AppSettings;
+ isSingleHostMode(): boolean;
+ isProduction(): boolean;
+}
+
+@injectable()
+export class BrowserSession implements Session {
+ private w: any;
+
+ constructor(window: Window) {
+ this.w = window;
+ this.w.setUser = this.setUser.bind(this);
+ this.w.getCurrentUser = this.getCurrentUser.bind(this);
+ this.w.set = this.set.bind(this);
+ this.w.get = this.get.bind(this);
+ }
+
+ public getCurrentUser(): User {
+ const w: any = window;
+ return w[`_user`] as User;
+ }
+
+ public setUser(user: User): void {
+ this.set<User>('user', user);
+ }
+
+ public isStaff(): boolean {
+ const user = this.getCurrentUser();
+ return user && user.role >= 2;
+ }
+
+ public set<T>(key: string, value: T): void {
+ this.w[`_${key}`] = value;
+ }
+
+ public get<T>(key: string): T {
+ return this.w[`_${key}`];
+ }
+
+ public getArray<T>(key: string): T[] {
+ return this.w[`_${key}`] || [];
+ }
+
+ public getAppSettings(): AppSettings {
+ return this.get<AppSettings>('settings');
+ }
+
+ public isSingleHostMode(): boolean {
+ return this.getAppSettings().mode.toLowerCase() === 'single';
+ }
+
+ public isProduction(): boolean {
+ return this.getAppSettings().environment.toLowerCase() === 'production';
+ }
+}
diff --git a/public/services/TenantService.ts b/public/services/TenantService.ts
new file mode 100644
index 000000000..c8d376778
--- /dev/null
+++ b/public/services/TenantService.ts
@@ -0,0 +1,25 @@
+import { get, post, Result } from './http';
+import { injectable } from '../di';
+import { Tenant } from '../models';
+
+export interface TenantService {
+ create(token?: string, name?: string, subdomain?: string): Promise<Result>;
+ checkAvailability(subdomain: string): Promise<Result<CheckAvailabilityResponse>>;
+}
+
+export interface CheckAvailabilityResponse {
+ message: string;
+}
+
+@injectable()
+export class HttpTenantService implements TenantService {
+ public async create(token?: string, name?: string, subdomain?: string): Promise<Result> {
+ return await post('/api/tenants', {
+ token, name, subdomain,
+ });
+ }
+
+ public async checkAvailability(subdomain: string): Promise<Result<CheckAvailabilityResponse>> {
+ return await get<CheckAvailabilityResponse>(`/api/tenants/${subdomain}/availability`);
+ }
+}
diff --git a/public/services/http.ts b/public/services/http.ts
new file mode 100644
index 000000000..606a0b97f
--- /dev/null
+++ b/public/services/http.ts
@@ -0,0 +1,40 @@
+import axios, { AxiosResponse } from 'axios';
+
+axios.defaults.validateStatus = (status: number) => {
+ return status < 500;
+};
+
+export interface Failure {
+ message: string;
+}
+
+export interface Result<T = void> {
+ ok: boolean;
+ data: T;
+ error?: Failure;
+}
+
+function toResult<T>(response: AxiosResponse): Result<T> {
+ if (response.status < 400) {
+ return {
+ ok: true,
+ data: response.data as T,
+ };
+ } else {
+ return {
+ ok: false,
+ data: response.data as T,
+ error: { message: response.data.message }
+ };
+ }
+}
+
+export async function get<T = void>(url: string): Promise<Result<T>> {
+ const response = await axios.get(url);
+ return toResult<T>(response);
+}
+
+export async function post<T = void>(url: string, data?: any): Promise<Result<T>> {
+ const response = await axios.post(url, data);
+ return toResult<T>(response);
+}
diff --git a/public/services/index.ts b/public/services/index.ts
new file mode 100644
index 000000000..d06ee4796
--- /dev/null
+++ b/public/services/index.ts
@@ -0,0 +1,4 @@
+export * from './Session';
+export * from './IdeaService';
+export * from './TenantService';
+export { Failure } from './http';
diff --git a/public/setup/SignUpPage.tsx b/public/setup/SignUpPage.tsx
index 0b5b19d7a..3d0f30435 100644
--- a/public/setup/SignUpPage.tsx
+++ b/public/setup/SignUpPage.tsx
@@ -2,16 +2,18 @@ import * as React from 'react';
import { Footer } from '../shared/Footer';
import { EnvironmentInfo, Gravatar } from '../shared/Common';
+import { Button, Form } from '../components/common';
import { AppSettings } from '../models';
-import { isSingleHostMode, getAppSettings } from '../storage';
import { SocialSignInList } from '../shared/SocialSignInList';
import { setTitle, getQueryString } from '../page';
import { DisplayError } from '../shared/Common';
-import axios from 'axios';
import { decode } from '../jwt';
const td = require('throttle-debounce');
const logo = require('../imgs/logo.png');
+import { inject, injectables } from '../di';
+import { Session, TenantService, Failure } from '../services';
+
import './signup.scss';
interface OAuthUser {
@@ -22,8 +24,7 @@ interface OAuthUser {
interface SignUpPageState {
name?: string;
- clicked: boolean;
- error?: Error;
+ error?: Failure;
subdomain: {
available: boolean,
message?: string,
@@ -34,18 +35,24 @@ interface SignUpPageState {
export class SignUpPage extends React.Component<{}, SignUpPageState> {
private settings: AppSettings;
private user: OAuthUser;
+ private form: Form;
+
+ @inject(injectables.Session)
+ public session: Session;
+
+ @inject(injectables.TenantService)
+ public service: TenantService;
constructor(props: {}) {
super(props);
this.state = {
- clicked: false,
subdomain: { available: false }
};
- this.settings = getAppSettings();
+ this.settings = this.session.getAppSettings();
this.checkAvailability = td.debounce(300, this.checkAvailability);
- setTitle(isSingleHostMode() ? 'Installation · Fider' : 'New tenant sign up · Fider');
+ setTitle(this.session.isSingleHostMode() ? 'Installation · Fider' : 'New tenant sign up · Fider');
const token = getQueryString('jwt');
if (token) {
@@ -59,46 +66,37 @@ export class SignUpPage extends React.Component<{}, SignUpPageState> {
}
private async confirm() {
- this.setState({
- clicked: true,
- error: undefined
- });
-
- try {
- const response = await axios.post('/api/tenants', {
- token: this.user ? this.user.token : null,
- name: this.state.name,
- subdomain: this.state.subdomain.value,
- });
-
- if (isSingleHostMode()) {
+ this.form.clearFailure();
+
+ const result = await this.service.create(
+ this.user && this.user.token,
+ this.state.name,
+ this.state.subdomain.value
+ );
+ if (result.ok) {
+ if (this.session.isSingleHostMode()) {
location.reload();
} else {
location.href = `${location.protocol}//${this.state.subdomain.value}${this.settings.domain}`;
}
- } catch (ex) {
- this.setState({
- clicked: false,
- error: ex.response.data
- });
+ } else if (result.error) {
+ this.form.setFailure(result.error);
}
}
private async checkAvailability(subdomain: string) {
- const url = `/api/tenants/${subdomain}/availability`;
- const result = await axios.get(url);
+ const result = await this.service.checkAvailability(subdomain);
this.setState({
subdomain: {
value: subdomain,
available: !result.data.message,
- message: result.data.message
+ message: result.data.message,
}
});
}
public render() {
- const buttonClasses = `ui positive button ${this.state.clicked && 'loading disabled'}`;
return <div>
<EnvironmentInfo />
<div id="fdr-signup-page" className="ui container">
@@ -122,18 +120,23 @@ export class SignUpPage extends React.Component<{}, SignUpPageState> {
}
<div className="ui section divider"></div>
-
<h3 className="ui header">2. Organization details</h3>
- <div className="ui form">
+ <Form ref={(f) => { this.form = f!; } } onSubmit={() => this.confirm()}>
<div className="inline field">
<label>Name</label>
- <input id="name" type="text" placeholder="Your organization name" onChange={(e) => this.setState({ name: e.currentTarget.value })}/>
+ <input id="name" type="text"
+ placeholder="Your organization name"
+ maxLength={60}
+ onChange={(e) => this.setState({ name: e.currentTarget.value })}/>
</div>
- { !isSingleHostMode() && <div className="inline field">
+ { !this.session.isSingleHostMode() && <div className="inline field">
<label>Identity</label>
<div className="ui right labeled input">
<div className="ui label">https://</div>
- <input id="subdomain" type="text" placeholder="orgname" onChange={(e) => this.checkAvailability(e.currentTarget.value)} />
+ <input id="subdomain" type="text"
+ maxLength={40}
+ placeholder="orgname"
+ onChange={(e) => this.checkAvailability(e.currentTarget.value)} />
<div className="ui label">{ this.settings.domain }</div>
{
this.state.subdomain.available &&
@@ -149,15 +152,14 @@ export class SignUpPage extends React.Component<{}, SignUpPageState> {
}
</div>
</div> }
- </div>
+ </Form>
<div className="ui section divider"></div>
<h3 className="ui header">3. Review and continue</h3>
<p>Please make sure information provided above is correct before proceeding.</p>
- <DisplayError error={this.state.error} />
- <button className={buttonClasses} onClick={() => this.confirm()}>Confirm</button>
+ <Button classes="positive" onClick={() => this.form.submit()}>Confirm</Button>
</div>
<Footer />
</div>;
diff --git a/public/shared/CommentInput.tsx b/public/shared/CommentInput.tsx
index b873011c0..077c4f688 100644
--- a/public/shared/CommentInput.tsx
+++ b/public/shared/CommentInput.tsx
@@ -1,53 +1,54 @@
-import axios from 'axios';
import * as React from 'react';
import { Idea } from '../models';
-import { getCurrentUser } from '../storage';
import { DisplayError } from './Common';
+import { Button } from '../components/common/Button';
import { SocialSignInList } from './SocialSignInList';
+import { inject, injectables } from '../di';
+import { Session, IdeaService, Failure } from '../services';
+
interface CommentInputProps {
idea: Idea;
}
interface CommentInputState {
content: string;
- clicked: boolean;
- error?: Error;
+ error?: Failure;
}
export class CommentInput extends React.Component<CommentInputProps, CommentInputState> {
+
+ @inject(injectables.Session)
+ public session: Session;
+
+ @inject(injectables.IdeaService)
+ public service: IdeaService;
+
constructor() {
super();
this.state = {
- content: '',
- clicked: false
+ content: ''
};
}
public async submit() {
this.setState({
- clicked: true,
error: undefined
});
- try {
- await axios.post(`/api/ideas/${this.props.idea.number}/comments`, {
- content: this.state.content
- });
-
+ const result = await this.service.addComment(this.props.idea.number, this.state.content);
+ if (result.ok) {
location.reload();
- } catch (ex) {
+ } else {
this.setState({
- clicked: false,
- error: ex.response.data
+ error: result.error,
});
}
}
public render() {
- const user = getCurrentUser();
- const buttonClasses = `ui blue labeled submit icon button ${this.state.clicked && 'loading disabled'}`;
+ const user = this.session.getCurrentUser();
const addComment = user ? <form className="ui reply form">
<DisplayError error={this.state.error} />
@@ -55,9 +56,9 @@ export class CommentInput extends React.Component<CommentInputProps, CommentInpu
<textarea onKeyUp={(e) => { this.setState({ content: e.currentTarget.value }); }}
placeholder="Leave your comment here..."></textarea>
</div>
- <div className={ buttonClasses } onClick={async () => await this.submit()}>
+ <Button classes="blue" onClick={ () => this.submit() }>
<i className="icon edit"></i> Add Comment
- </div>
+ </Button>
</form> :
<div className="ui message">
<div className="header">
diff --git a/public/shared/Common.tsx b/public/shared/Common.tsx
index 525d9358b..df3843435 100644
--- a/public/shared/Common.tsx
+++ b/public/shared/Common.tsx
@@ -1,10 +1,11 @@
import * as React from 'react';
import * as moment from 'moment';
import md5 = require('md5');
-import { AxiosError, AxiosResponse } from 'axios';
-import { getCurrentUser, getAppSettings, isProduction } from '../storage';
import { User, IdeaResponse, IdeaStatus } from '../models';
+import { inject, injectables } from '../di';
+import { Session, Failure } from '../services';
+
export const Gravatar = (props: {email?: string}) => {
const hash = props.email ? md5(props.email) : '';
return <img className="ui avatar image" src={ 'https://www.gravatar.com/avatar/' + hash } />;
@@ -20,31 +21,34 @@ export const MultiLineText = (props: {text?: string}) => {
)}</div>;
};
-export const DisplayError = (props: {error?: Error}) => {
+export const DisplayError = (props: {error?: Failure}) => {
if (!props.error) {
return <div></div>;
}
return <div className="ui negative message">
- <div className="header">
- Oops, an error ocurred...
- </div>
<p>{ props.error.message }</p>
</div>;
};
-export const EnvironmentInfo = () => {
- if (!isProduction()) {
- const settings = getAppSettings();
- return <div className="ui mini negative message no-border no-margin">
- Env: { settings.environment } |
- Compiler: { settings.compiler } |
- Version: { settings.version } |
- BuildTime: { settings.buildTime }
- </div>;
+export class EnvironmentInfo extends React.Component<{}, {}> {
+
+ @inject(injectables.Session)
+ public session: Session;
+
+ public render() {
+ if (!this.session.isProduction()) {
+ const settings = this.session.getAppSettings();
+ return <div className="ui mini negative message no-border no-margin">
+ Env: { settings.environment } |
+ Compiler: { settings.compiler } |
+ Version: { settings.version } |
+ BuildTime: { settings.buildTime }
+ </div>;
+ }
+ return <div/>;
}
- return <div/>;
-};
+}
export const IdeaStatusRibbon = (props: { status: IdeaStatus }) => {
return <span className={`ui ribbon label ${props.status.color}`}>{ props.status.title }</span>;
diff --git a/public/shared/Header.tsx b/public/shared/Header.tsx
index d48a4b310..7e6c15443 100644
--- a/public/shared/Header.tsx
+++ b/public/shared/Header.tsx
@@ -1,20 +1,25 @@
import * as React from 'react';
import { User, Tenant } from '../models';
-import { get, getCurrentUser, isStaff } from '../storage';
import { EnvironmentInfo, Gravatar } from './Common';
import { SocialSignInList } from './SocialSignInList';
+import { inject, injectables } from '../di';
+import { Session } from '../services/Session';
+
export class Header extends React.Component<{}, {}> {
private dropdown: HTMLElement;
private list: HTMLElement;
private user: User;
private tenant: Tenant;
+ @inject(injectables.Session)
+ public session: Session;
+
constructor(props: {}) {
super(props);
- this.user = getCurrentUser();
- this.tenant = get<Tenant>('tenant');
+ this.user = this.session.getCurrentUser();
+ this.tenant = this.session.get<Tenant>('tenant');
}
public componentDidMount() {
@@ -33,7 +38,7 @@ export class Header extends React.Component<{}, {}> {
<b>{ this.user.email }</b>
</div>
{
- isStaff() &&
+ this.session.isStaff() &&
<div className="item">
<a href="/admin">
Administration
diff --git a/public/shared/ResponseForm.tsx b/public/shared/ResponseForm.tsx
index edb204c65..45cc1fd27 100644
--- a/public/shared/ResponseForm.tsx
+++ b/public/shared/ResponseForm.tsx
@@ -1,16 +1,17 @@
-import axios from 'axios';
import * as React from 'react';
-import * as storage from '../storage';
import { User, Comment, Idea } from '../models';
import { DisplayError } from './Common';
+import { inject, injectables } from '../di';
+import { Session, IdeaService, Failure } from '../services';
+
interface ResponseFormProps {
idea: Idea;
}
interface ResponseFormState {
active: boolean;
- error?: Error;
+ error?: Failure;
}
export class ResponseForm extends React.Component<ResponseFormProps, ResponseFormState> {
@@ -18,25 +19,29 @@ export class ResponseForm extends React.Component<ResponseFormProps, ResponseFor
private text: HTMLTextAreaElement;
private status: HTMLSelectElement;
+ @inject(injectables.Session)
+ public session: Session;
+
+ @inject(injectables.IdeaService)
+ public service: IdeaService;
+
constructor(props: ResponseFormProps) {
super(props);
- this.user = storage.getCurrentUser();
+ this.user = this.session.getCurrentUser();
this.state = {
active: false
};
}
private async submit() {
- try {
- await axios.post(`/api/ideas/${this.props.idea.number}/status`, {
- status: parseInt(this.status.value, 10),
- text: this.text.value
- });
+ const status = parseInt(this.status.value, 10);
+ const result = await this.service.setResponse(this.props.idea.number, status, this.text.value);
+ if (result.ok) {
location.reload();
- } catch (ex) {
+ } else {
this.setState({
- error: ex.response.data
+ error: result.error
});
}
}
diff --git a/public/shared/SocialSignInButton.tsx b/public/shared/SocialSignInButton.tsx
index a84c2c056..d592783a2 100644
--- a/public/shared/SocialSignInButton.tsx
+++ b/public/shared/SocialSignInButton.tsx
@@ -1,41 +1,29 @@
import * as React from 'react';
-import { get } from '../storage';
+
+import { inject, injectables } from '../di';
+import { Session } from '../services/Session';
+import { Button } from '../components/common/Button';
interface SocialSignInButtonProps {
provider: string;
size: 'small' | 'normal';
}
-interface SocialSignInButtonState {
- clicked: boolean;
-}
-export class SocialSignInButton extends React.Component<SocialSignInButtonProps, SocialSignInButtonState> {
- constructor() {
- super();
- this.state = {
- clicked: false
- };
- }
+export class SocialSignInButton extends React.Component<SocialSignInButtonProps, {}> {
+
+ @inject(injectables.Session)
+ public session: Session;
public render() {
- const auth = get<any>('auth');
+ const auth = this.session.get<any>('auth');
const providerClassName = this.props.provider === 'google' ? 'google plus' : 'facebook';
const providerDisplayName = this.props.provider === 'google' ? 'Google' : 'Facebook';
- const oauthUrl = `${auth.endpoint}/oauth/${this.props.provider}?redirect=${location.href}`;
- const cssClasses = `ui button
- ${providerClassName}
- ${this.state.clicked ? 'loading disabled' : ''}
- ${this.props.size === 'small' ? 'circular icon' : 'fluid'}`;
+ const href = `${auth.endpoint}/oauth/${this.props.provider}?redirect=${location.href}`;
+ const classes = `${providerClassName} ${this.props.size === 'small' ? 'circular icon' : 'fluid'}`;
- if (this.props.size === 'small') {
- return <a href={oauthUrl} className={cssClasses} onClick={() => this.setState({clicked: true})}>
+ return <Button href={href} classes={classes}>
<i className={providerClassName + ' icon'}></i>
- </a>;
- } else {
- return <a href={oauthUrl} className={cssClasses} onClick={() => this.setState({clicked: true})}>
- <i className={providerClassName + ' icon'}></i>
- Sign in with { providerDisplayName }
- </a>;
- }
+ { this.props.size === 'normal' && `Sign in with ${providerDisplayName}` }
+ </Button>;
}
}
diff --git a/public/shared/SocialSignInList.tsx b/public/shared/SocialSignInList.tsx
index c0a2389e3..6d5686ad8 100644
--- a/public/shared/SocialSignInList.tsx
+++ b/public/shared/SocialSignInList.tsx
@@ -1,7 +1,9 @@
import * as React from 'react';
-import { get } from '../storage';
import { SocialSignInButton } from './SocialSignInButton';
+import { inject, injectables } from '../di';
+import { Session } from '../services/Session';
+
interface AuthSettings {
endpoint: string;
providers: {
@@ -15,29 +17,39 @@ interface SocialSignInListProps {
orientation: 'horizontal' | 'vertical';
}
-export const SocialSignInList = (props: SocialSignInListProps) => {
- const settings = get<AuthSettings>('auth');
- const cssClasses = props.orientation === 'horizontal' ? 'horizontal divided' : '';
-
- const google = settings.providers.google &&
- <div className="item">
- <SocialSignInButton provider="google" size={props.size} />
- </div>;
- const facebook = settings.providers.facebook &&
- <div className="item">
- <SocialSignInButton provider="facebook" size={props.size} />
- </div>;
-
- const noAuth = !facebook && !google &&
- <div className="item">
- <div className="ui tertiary inverted red segment">
- There are no authentication methods enabled.
- </div>
- </div>;
-
- return <div className={`ui list ${cssClasses}`}>
- { facebook }
- { google }
- { noAuth }
- </div>;
-};
+export class SocialSignInList extends React.Component<SocialSignInListProps, {}> {
+
+ @inject(injectables.Session)
+ public session: Session;
+
+ constructor(props: SocialSignInListProps) {
+ super(props);
+ }
+
+ public render() {
+ const settings = this.session.get<AuthSettings>('auth');
+ const cssClasses = this.props.orientation === 'horizontal' ? 'horizontal divided' : '';
+
+ const google = settings.providers.google &&
+ <div className="item">
+ <SocialSignInButton provider="google" size={this.props.size} />
+ </div>;
+ const facebook = settings.providers.facebook &&
+ <div className="item">
+ <SocialSignInButton provider="facebook" size={this.props.size} />
+ </div>;
+
+ const noAuth = !facebook && !google &&
+ <div className="item">
+ <div className="ui tertiary inverted red segment">
+ There are no authentication methods enabled.
+ </div>
+ </div>;
+
+ return <div className={`ui list ${cssClasses}`}>
+ { facebook }
+ { google }
+ { noAuth }
+ </div>;
+ }
+}
diff --git a/public/shared/SupportCounter.tsx b/public/shared/SupportCounter.tsx
index 63d0f1831..e4737a1ef 100644
--- a/public/shared/SupportCounter.tsx
+++ b/public/shared/SupportCounter.tsx
@@ -1,9 +1,11 @@
-import axios from 'axios';
import * as React from 'react';
import { Idea, User, IdeaStatus } from '../models';
-import * as storage from '../storage';
import { SocialSignInList } from './SocialSignInList';
+import { inject, injectables } from '../di';
+import { Session } from '../services/Session';
+import { IdeaService } from '../services/IdeaService';
+
interface SupportCounterProps {
user: User;
idea: Idea;
@@ -18,9 +20,15 @@ export class SupportCounter extends React.Component<SupportCounterProps, Support
private elem: HTMLElement;
private list: HTMLElement;
+ @inject(injectables.Session)
+ public session: Session;
+
+ @inject(injectables.IdeaService)
+ public service: IdeaService;
+
constructor(props: SupportCounterProps) {
super(props);
- const supportedIdeas = storage.getArray<number>('supportedIdeas');
+ const supportedIdeas = this.session.getArray<number>('supportedIdeas');
this.state = {
supported: props.user && supportedIdeas && supportedIdeas.indexOf(props.idea.id) >= 0,
@@ -46,16 +54,15 @@ export class SupportCounter extends React.Component<SupportCounterProps, Support
return;
}
- const action = this.state.supported ? 'unsupport' : 'support';
-
- try {
- await axios.post(`/api/ideas/${this.props.idea.number}/${action}`);
+ const action = this.state.supported ? this.service.removeSupport : this.service.addSupport;
+ const response = await action(this.props.idea.number);
+ if (response.ok) {
this.setState({
supported: !this.state.supported,
total: this.state.total + (this.state.supported ? -1 : 1)
});
- } catch (ex) {
+ } else {
// TODO: handle this. we should have a global alert box
}
diff --git a/public/site/HomePage.tsx b/public/site/HomePage.tsx
index cc1118e8d..8b304c52d 100644
--- a/public/site/HomePage.tsx
+++ b/public/site/HomePage.tsx
@@ -1,7 +1,6 @@
import * as moment from 'moment';
import * as React from 'react';
import { Idea, User } from '../models';
-import * as storage from '../storage';
import { Gravatar, MultiLineText, ShowIdeaResponse } from '../shared/Common';
import { SupportCounter } from '../shared/SupportCounter';
@@ -9,14 +8,20 @@ import { Footer } from '../shared/Footer';
import { Header } from '../shared/Header';
import { IdeaInput } from './IdeaInput';
+import { inject, injectables } from '../di';
+import { Session } from '../services/Session';
+
export class HomePage extends React.Component<{}, {}> {
private user: User;
private ideas: Idea[];
+ @inject(injectables.Session)
+ public session: Session;
+
constructor(props: {}) {
super(props);
- this.user = storage.getCurrentUser();
- this.ideas = storage.get<Idea[]>('ideas') || [];
+ this.user = this.session.getCurrentUser();
+ this.ideas = this.session.get<Idea[]>('ideas') || [];
}
public render() {
@@ -25,7 +30,7 @@ export class HomePage extends React.Component<{}, {}> {
<SupportCounter user={this.user} idea={x} />
<div className="content">
<a href={`/ideas/${x.number}/${x.slug}`} className="header">
- <i className="idea icon"></i> { x.title }
+ { x.title }
</a>
<div className="description">
<MultiLineText text={ x.description } />
@@ -39,7 +44,7 @@ export class HomePage extends React.Component<{}, {}> {
</div>);
const displayIdeas = (this.ideas.length > 0) ? <div>
- <h3>Top Ideas</h3>
+ <h3>Recent Ideas</h3>
<div className="ui divided unstackable items">
{ ideasList }
</div>
diff --git a/public/site/IdeaInput.tsx b/public/site/IdeaInput.tsx
index dfe1a0bc3..ce5acded7 100644
--- a/public/site/IdeaInput.tsx
+++ b/public/site/IdeaInput.tsx
@@ -1,73 +1,66 @@
-import axios from 'axios';
import * as React from 'react';
-import { getCurrentUser } from '../storage';
import { DisplayError } from '../shared/Common';
import { SocialSignInList } from '../shared/SocialSignInList';
+import { Button, Form } from '../components/common';
+
+import { inject, injectables } from '../di';
+import { Session, IdeaService, Failure } from '../services';
interface IdeaInputState {
title: string;
- clicked: boolean;
- error?: Error;
}
export class IdeaInput extends React.Component<{}, IdeaInputState> {
private description: HTMLTextAreaElement;
+ private form: Form;
+
+ @inject(injectables.Session)
+ public session: Session;
+
+ @inject(injectables.IdeaService)
+ public service: IdeaService;
constructor() {
super();
this.state = {
title: '',
- clicked: false
};
}
public async submit() {
- this.setState({
- clicked: true,
- error: undefined
- });
-
- try {
- const response = await axios.post('/api/ideas', {
- title: this.state.title,
- description: this.description.value
- });
-
- location.href = `/ideas/${response.data.number}/${response.data.slug}`;
- } catch (ex) {
- this.setState({
- clicked: false,
- error: ex.response.data
- });
+ this.form.clearFailure();
+ const result = await this.service.addIdea(this.state.title, this.description.value);
+ if (result.ok) {
+ location.href = `/ideas/${result.data.number}/${result.data.slug}`;
+ } else if (result.error) {
+ this.form.setFailure(result.error);
}
}
public render() {
- const user = getCurrentUser();
- const buttonClasses = `ui primary button ${this.state.clicked && 'loading disabled'}`;
+ const user = this.session.getCurrentUser();
const details = user ?
- <div>
- <div className="field">
- <textarea ref={(ref) => this.description = ref! }
- rows={6}
- placeholder="Describe your idea (optional)"></textarea>
+ <div>
+ <div className="field">
+ <textarea ref={(ref) => this.description = ref! }
+ rows={6}
+ placeholder="Describe your idea (optional)"></textarea>
</div>
- <button className={buttonClasses} onClick={async () => { await this.submit(); } }>
- Submit Idea
- </button>
- </div> :
+ <Button classes="primary" onClick={() => this.form.submit() }>
+ Submit Idea
+ </Button>
+ </div> :
<div>
- <div className="ui message">
- <div className="header">
- Please log in before posting an idea
+ <div className="ui message">
+ <div className="header">
+ Please log in before posting an idea
+ </div>
+ <p>This only takes a second and you'll be good to go!</p>
+ <SocialSignInList orientation="horizontal" size="small" />
</div>
- <p>This only takes a second and you'll be good to go!</p>
- <SocialSignInList orientation="horizontal" size="small" />
- </div>
- </div>;
+ </div>;
- return <div className="ui form">
- <DisplayError error={this.state.error} />
+ return <Form ref={(f) => { this.form = f!; } } onSubmit={() => this.submit()}>
<div className="ui fluid input">
<input id="new-idea-input"
type="text"
@@ -76,7 +69,7 @@ export class IdeaInput extends React.Component<{}, IdeaInputState> {
placeholder="Enter your idea, new feature or suggestion here ..." />
</div>
- { this.state.title.length > 0 && details }
- </div>;
+ { this.state.title && details }
+ </Form>;
}
}
diff --git a/public/site/ShowIdeaPage.tsx b/public/site/ShowIdeaPage.tsx
index 08d066609..6014e531c 100644
--- a/public/site/ShowIdeaPage.tsx
+++ b/public/site/ShowIdeaPage.tsx
@@ -1,6 +1,5 @@
import * as moment from 'moment';
import * as React from 'react';
-import { getCurrentUser, get, getArray, isStaff } from '../storage';
import { User, Comment, Idea } from '../models';
import { CommentInput } from '../shared/CommentInput';
@@ -14,17 +13,23 @@ import { Footer } from '../shared/Footer';
import { Header } from '../shared/Header';
import { IdeaInput } from './IdeaInput';
+import { inject, injectables } from '../di';
+import { Session } from '../services/Session';
+
export class ShowIdeaPage extends React.Component<{}, {}> {
private user: User;
private idea: Idea;
private comments: Comment[];
+ @inject(injectables.Session)
+ public session: Session;
+
constructor(props: {}) {
super(props);
- this.user = getCurrentUser();
- this.idea = get<Idea>('idea');
- this.comments = getArray<Comment>('comments');
+ this.user = this.session.getCurrentUser();
+ this.idea = this.session.get<Idea>('idea');
+ this.comments = this.session.getArray<Comment>('comments');
setTitle(`${this.idea.title} · Idea #${this.idea.number} · ${document.title}`);
}
@@ -75,7 +80,7 @@ export class ShowIdeaPage extends React.Component<{}, {}> {
<ShowIdeaResponse status={ this.idea.status } response={ this.idea.response } />
{
- isStaff() &&
+ this.session.isStaff() &&
<div>
<div className="ui hidden divider"></div>
<ResponseForm idea={ this.idea } />
diff --git a/public/storage.ts b/public/storage.ts
deleted file mode 100644
index 4b5ac05a0..000000000
--- a/public/storage.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import { User, AppSettings } from './models';
-
-const w: any = window;
-
-export function setup() {
- w.setUser = setUser;
- w.getCurrentUser = getCurrentUser;
- w.set = set;
- w.get = get;
-}
-
-export function setUser(user: User) {
- set<User>('user', user);
-}
-
-export function getCurrentUser(): User {
- return get<User>('user');
-}
-
-export function isStaff() {
- const user = getCurrentUser();
- return user && user.role >= 2;
-}
-
-export function set<T>(key: string, value: T) {
- w[`_${key}`] = value;
-}
-
-export function get<T>(key: string): T {
- return w[`_${key}`];
-}
-
-export function getArray<T>(key: string): T[] {
- return w[`_${key}`] || [];
-}
-
-export function getAppSettings(): AppSettings {
- return get<AppSettings>('settings');
-}
-
-export function isSingleHostMode() {
- return getAppSettings().mode.toLowerCase() === 'single';
-}
-
-export function isProduction() {
- return getAppSettings().environment.toLowerCase() === 'production';
-}
diff --git a/tsconfig.json b/tsconfig.json
index 62cc68ed0..d545f95c6 100755
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -6,6 +6,8 @@
"strictNullChecks": true,
"sourceMap": true,
"jsx": "react",
- "lib": ["dom", "es2015.promise", "es5"]
+ "lib": ["dom", "es2015.promise", "es6"],
+ "experimentalDecorators": true,
+ "emitDecoratorMetadata": true
}
}
\ No newline at end of file
diff --git a/tslint.json b/tslint.json
index 5b23ad27d..09b91193f 100644
--- a/tslint.json
+++ b/tslint.json
@@ -5,6 +5,9 @@
"trailing-comma": [
false
],
+ "indent": [
+ true, "spaces", 4
+ ],
"interface-name": [
false
],
@@ -20,6 +23,9 @@
],
"max-line-length": [
false
+ ],
+ "max-classes-per-file": [
+ false
]
}
}
\ No newline at end of file