Open platform to collect and prioritize feedback
refactoring: move basic props to global object (#429)
Guilherme Oenning93a569208937
diff --git a/air.conf b/air.confindex 167af1067..62084504e 100644--- a/air.conf+++ b/air.conf@@ -7,7 +7,7 @@ tmp_dir = "tmp"bin = "godotenv -f .env ./fider"cmd = "go build -o fider ."log = "server-errors.log"-include_ext = ["go", "tpl", "tmpl", "html"]+include_ext = ["go", "tpl", "tmpl", "html", "env"]exclude_dir = ["public", "tmp", "vendor", "node_modules", "data", "tests", "output", "scripts", "dist"]delay = 500diff --git a/app/handlers/settings.go b/app/handlers/settings.goindex da8c695e1..35c8632fd 100644--- a/app/handlers/settings.go+++ b/app/handlers/settings.go@@ -65,7 +65,7 @@ func UserSettings() web.HandlerFunc {return c.Page(web.Props{Title: "Settings",Data: web.Map{- "settings": settings,+ "userSettings": settings,},})}diff --git a/app/middlewares/security.go b/app/middlewares/security.goindex 5a05cc063..a99703dfd 100644--- a/app/middlewares/security.go+++ b/app/middlewares/security.go@@ -12,7 +12,7 @@ func Secure() web.MiddlewareFunc {return func(next web.HandlerFunc) web.HandlerFunc {return func(c web.Context) error {cdnHost := env.GetEnvOrDefault("CDN_HOST", "")- if cdnHost != "" {+ if cdnHost != "" && !env.IsSingleHostMode() {cdnHost = "*." + cdnHost}csp := fmt.Sprintf(web.CspPolicyTemplate, c.ContextID(), cdnHost)diff --git a/app/middlewares/security_test.go b/app/middlewares/security_test.goindex a58084c36..b1bd70fc3 100644--- a/app/middlewares/security_test.go+++ b/app/middlewares/security_test.go@@ -54,3 +54,26 @@ func TestSecureWithCDN(t *testing.T) {Expect(response.Header().Get("X-Content-Type-Options")).Equals("nosniff")Expect(response.Header().Get("Referrer-Policy")).Equals("no-referrer-when-downgrade")}++func TestSecureWithCDN_SingleHost(t *testing.T) {+ RegisterT(t)++ os.Setenv("CDN_HOST", "test.fider.io")++ server, _ := mock.NewSingleTenantServer()+ server.Use(middlewares.Secure())++ var ctxID string+ status, response := server.Execute(func(c web.Context) error {+ ctxID = c.ContextID()+ return c.NoContent(http.StatusOK)+ })++ expectedPolicy := "base-uri 'self'; default-src 'self'; style-src 'self' 'nonce-" + ctxID + "' https://fonts.googleapis.com test.fider.io; script-src 'self' 'nonce-" + ctxID + "' https://cdn.polyfill.io https://www.google-analytics.com test.fider.io; img-src 'self' https: data: test.fider.io; font-src 'self' https://fonts.gstatic.com data: test.fider.io; object-src 'none'; media-src 'none'; connect-src 'self' https://www.google-analytics.com"++ Expect(status).Equals(http.StatusOK)+ Expect(response.Header().Get("Content-Security-Policy")).Equals(expectedPolicy)+ Expect(response.Header().Get("X-XSS-Protection")).Equals("1; mode=block")+ Expect(response.Header().Get("X-Content-Type-Options")).Equals("nosniff")+ Expect(response.Header().Get("Referrer-Policy")).Equals("no-referrer-when-downgrade")+}diff --git a/app/models/infra.go b/app/models/infra.goindex 04314e553..1a2aca98e 100644--- a/app/models/infra.go+++ b/app/models/infra.go@@ -6,14 +6,14 @@ import (// SystemSettings is the system-wide settingstype SystemSettings struct {- Mode string `json:"mode"`- BuildTime string `json:"buildTime"`- Version string `json:"version"`- Environment string `json:"environment"`- GoogleAnalytics string `json:"googleAnalytics"`- Compiler string `json:"compiler"`- Domain string `json:"domain"`- HasLegal bool `json:"hasLegal"`+ Mode string+ BuildTime string+ Version string+ Environment string+ GoogleAnalytics string+ Compiler string+ Domain string+ HasLegal bool}// Notification is the system generated notification entitydiff --git a/app/pkg/web/context.go b/app/pkg/web/context.goindex 73f3deab1..b0cad7507 100644--- a/app/pkg/web/context.go+++ b/app/pkg/web/context.go@@ -510,7 +510,7 @@ func (ctx *Context) GlobalAssetsURL(path string, a ...interface{}) string {// TenantAssetsURL return the full URL to a tenant-specific static assetfunc (ctx *Context) TenantAssetsURL(path string, a ...interface{}) string {path = fmt.Sprintf(path, a...)- if env.IsDefined("CDN_HOST") {+ if env.IsDefined("CDN_HOST") && ctx.Tenant() != nil {if env.IsSingleHostMode() {return ctx.Request.URL.Scheme + "://" + env.MustGet("CDN_HOST") + path}diff --git a/app/pkg/web/context_test.go b/app/pkg/web/context_test.goindex e10669212..bc9c2535c 100644--- a/app/pkg/web/context_test.go+++ b/app/pkg/web/context_test.go@@ -126,9 +126,9 @@ func TestGlobalAssetsURL_SingleHostMode(t *testing.T) {RegisterT(t)os.Setenv("HOST_MODE", "single")- ctx := newGetContext("http://demo.test.fider.io:3000", nil)- Expect(ctx.GlobalAssetsURL("/assets/main.js")).Equals("http://demo.test.fider.io:3000/assets/main.js")- Expect(ctx.GlobalAssetsURL("/assets/main.css")).Equals("http://demo.test.fider.io:3000/assets/main.css")+ ctx := newGetContext("http://ideas.theavengers.com:3000", nil)+ Expect(ctx.GlobalAssetsURL("/assets/main.js")).Equals("http://ideas.theavengers.com:3000/assets/main.js")+ Expect(ctx.GlobalAssetsURL("/assets/main.css")).Equals("http://ideas.theavengers.com:3000/assets/main.css")os.Setenv("CDN_HOST", "assets-fider.io")Expect(ctx.GlobalAssetsURL("/assets/main.js")).Equals("http://assets-fider.io/assets/main.js")@@ -158,9 +158,14 @@ func TestTenantAssetsURL_SingleHostMode(t *testing.T) {RegisterT(t)os.Setenv("HOST_MODE", "single")- ctx := newGetContext("http://theavengers.test.fider.io:3000", nil)- Expect(ctx.TenantAssetsURL("/assets/main.js")).Equals("http://theavengers.test.fider.io:3000/assets/main.js")- Expect(ctx.TenantAssetsURL("/assets/main.css")).Equals("http://theavengers.test.fider.io:3000/assets/main.css")+ ctx := newGetContext("http://ideas.theavengers.com:3000", nil)+ ctx.SetTenant(&models.Tenant{+ ID: 1,+ Subdomain: "theavengers",+ })++ Expect(ctx.TenantAssetsURL("/assets/main.js")).Equals("http://ideas.theavengers.com:3000/assets/main.js")+ Expect(ctx.TenantAssetsURL("/assets/main.css")).Equals("http://ideas.theavengers.com:3000/assets/main.css")os.Setenv("CDN_HOST", "assets-fider.io")Expect(ctx.TenantAssetsURL("/assets/main.js")).Equals("http://assets-fider.io/assets/main.js")diff --git a/app/pkg/web/renderer.go b/app/pkg/web/renderer.goindex 9f6922cdd..d30e137a9 100644--- a/app/pkg/web/renderer.go+++ b/app/pkg/web/renderer.go@@ -105,19 +105,18 @@ func (r *Renderer) Render(w io.Writer, name string, props Props, ctx *Context) {title = fmt.Sprintf("%s · %s", props.Title, tenantName)}- m["__Title"] = title+ m["__title"] = titleif props.Description != "" {description := strings.Replace(props.Description, "\n", " ", -1)- m["__Description"] = fmt.Sprintf("%.150s", description)+ m["__description"] = fmt.Sprintf("%.150s", description)}- m["__VendorBundle"] = ctx.GlobalAssetsURL("/assets/js/%s", r.assets["vendor.js"])- m["__JavaScriptBundle"] = ctx.GlobalAssetsURL("/assets/js/%s", r.assets["main.js"])- m["__StyleBundle"] = ctx.GlobalAssetsURL("/assets/css/%s", r.assets["main.css"])- m["__FontBundle"] = ctx.GlobalAssetsURL("/assets/fonts/%s", r.assets["icons.woff2"])+ m["__vendorBundle"] = ctx.GlobalAssetsURL("/assets/js/%s", r.assets["vendor.js"])+ m["__jsBundle"] = ctx.GlobalAssetsURL("/assets/js/%s", r.assets["main.js"])+ m["__cssBundle"] = ctx.GlobalAssetsURL("/assets/css/%s", r.assets["main.css"])+ m["__fontBundle"] = ctx.GlobalAssetsURL("/assets/fonts/%s", r.assets["icons.woff2"])- m["__ContextID"] = ctx.ContextID()if ctx.Tenant() != nil && ctx.Tenant().LogoID > 0 {m["__logo"] = ctx.TenantAssetsURL("/logo/200/%d", ctx.Tenant().LogoID)m["__favicon"] = ctx.TenantAssetsURL("/logo/50/%d", ctx.Tenant().LogoID)@@ -126,26 +125,33 @@ func (r *Renderer) Render(w io.Writer, name string, props Props, ctx *Context) {m["__favicon"] = ctx.GlobalAssetsURL("/favicon.ico")}- m["system"] = r.settings- m["baseURL"] = ctx.BaseURL()- m["assetsBaseURL"] = ctx.GlobalAssetsURL("")- if ctx.Tenant() != nil {- m["tenantAssetsBaseURL"] = ctx.TenantAssetsURL("")- }- m["currentURL"] = ctx.Request.URL.String()- m["tenant"] = ctx.Tenant()- m["auth"] = Map{- "endpoint": ctx.AuthEndpoint(),- "providers": Map{- oauth.GoogleProvider: oauth.IsProviderEnabled(oauth.GoogleProvider),- oauth.FacebookProvider: oauth.IsProviderEnabled(oauth.FacebookProvider),- oauth.GitHubProvider: oauth.IsProviderEnabled(oauth.GitHubProvider),+ m["__contextID"] = ctx.ContextID()+ m["__currentURL"] = ctx.Request.URL.String()+ m["__tenant"] = ctx.Tenant()+ m["__settings"] = &Map{+ "mode": r.settings.Mode,+ "buildTime": r.settings.BuildTime,+ "version": r.settings.Version,+ "environment": r.settings.Environment,+ "compiler": r.settings.Compiler,+ "googleAnalytics": r.settings.GoogleAnalytics,+ "domain": r.settings.Domain,+ "hasLegal": r.settings.HasLegal,+ "baseURL": ctx.BaseURL(),+ "assetsURL": ctx.TenantAssetsURL(""),+ "auth": Map{+ "endpoint": ctx.AuthEndpoint(),+ "providers": Map{+ oauth.GoogleProvider: oauth.IsProviderEnabled(oauth.GoogleProvider),+ oauth.FacebookProvider: oauth.IsProviderEnabled(oauth.FacebookProvider),+ oauth.GitHubProvider: oauth.IsProviderEnabled(oauth.GitHubProvider),+ },},}if ctx.IsAuthenticated() {u := ctx.User()- m["user"] = &Map{+ m["__user"] = &Map{"id": u.ID,"name": u.Name,"email": u.Email,diff --git a/app/tasks/tasks.go b/app/tasks/tasks.goindex 8ad51b1a2..864f65a7b 100644--- a/app/tasks/tasks.go+++ b/app/tasks/tasks.go@@ -151,7 +151,6 @@ func NotifyAboutNewComment(idea *models.Idea, comment *models.NewComment) workerfunc NotifyAboutStatusChange(idea *models.Idea, prevStatus int) worker.Task {return describe("Notify about idea status change", func(c *worker.Context) error {//Don't notify if previous status is the same- c.Logger().Infof("%d, %d", prevStatus, idea.Status)if prevStatus == idea.Status {return nil}diff --git a/package-lock.json b/package-lock.jsonindex de9ea65e8..cf60c91b6 100644--- a/package-lock.json+++ b/package-lock.json@@ -13436,10 +13436,9 @@}},"tslib": {- "version": "1.9.0",- "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.9.0.tgz",- "integrity": "sha512-f/qGG2tUkrISBlQZEjEqoZ3B2+npJjIf04H1wuAv9iA8i04Icp+61KRXxFdha22670NJopsZCIjhC3SnjPRKrQ==",- "dev": true+ "version": "1.9.2",+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.9.2.tgz",+ "integrity": "sha512-AVP5Xol3WivEr7hnssHDsaM+lVrVXWUvd1cfXTRkTj80b//6g2wIFEH6hZG0muGZRnHGrfttpdzRk3YlBkWjKw=="},"tslint": {"version": "5.10.0",diff --git a/package.json b/package.jsonindex ce5bb9464..a18870dec 100644--- a/package.json+++ b/package.json@@ -10,7 +10,8 @@"react-textarea-autosize": "6.1.0","react-toastify": "4.0.1","semantic-ui-css": "2.2.14",- "semantic-ui-react": "0.79.1"+ "semantic-ui-react": "0.79.1",+ "tslib": "^1.9.2"},"devDependencies": {"@types/jest": "22.2.3",diff --git a/public/components/SupportCounter.tsx b/public/components/SupportCounter.tsxindex 5941e1e1e..6698e72b5 100644--- a/public/components/SupportCounter.tsx+++ b/public/components/SupportCounter.tsx@@ -1,12 +1,11 @@import "./SupportCounter.scss";import * as React from "react";-import { Idea, User, IdeaStatus } from "@fider/models";-import { page, actions, device, classSet } from "@fider/services";+import { Idea, IdeaStatus } from "@fider/models";+import { actions, device, classSet } from "@fider/services";import { SignInModal } from "@fider/components";interface SupportCounterProps {- user?: User;idea: Idea;}@@ -27,7 +26,7 @@ export class SupportCounter extends React.Component<SupportCounterProps, Support}private supportOrUndo = async () => {- if (!this.props.user) {+ if (!Fider.session.isAuthenticated) {this.setState({ showSignIn: true });return;}diff --git a/public/components/common/EnvironmentInfo.tsx b/public/components/common/EnvironmentInfo.tsxindex f685b2441..8d2952534 100644--- a/public/components/common/EnvironmentInfo.tsx+++ b/public/components/common/EnvironmentInfo.tsx@@ -1,20 +1,16 @@import * as React from "react";import { SystemSettings } from "@fider/models";-interface EnvironmentInfoProps {- system: SystemSettings;-}--export class EnvironmentInfo extends React.Component<EnvironmentInfoProps, {}> {+export class EnvironmentInfo extends React.Component<{}, {}> {public render() {- if (this.props.system.environment === "production") {+ if (Fider.isProduction()) {return null;}return (<div className="c-env-info">- Env: {this.props.system.environment} | Compiler: {this.props.system.compiler} | Version:{" "}- {this.props.system.version} | BuildTime: {this.props.system.buildTime}+ Env: {Fider.settings.environment} | Compiler: {Fider.settings.compiler} | Version: {Fider.settings.version} |+ BuildTime: {Fider.settings.buildTime}</div>);}diff --git a/public/components/common/FiderVersion.tsx b/public/components/common/FiderVersion.tsxindex 30057eb58..88ee8be94 100644--- a/public/components/common/FiderVersion.tsx+++ b/public/components/common/FiderVersion.tsx@@ -1,5 +1,4 @@import * as React from "react";-import { page } from "@fider/services";export const FiderVersion = () => {return (@@ -9,7 +8,7 @@ export const FiderVersion = () => {OpenCollective</a><br />- Fider v{page.systemSettings().version}+ Fider v{Fider.settings.version}</p>);};diff --git a/public/components/common/Footer.tsx b/public/components/common/Footer.tsxindex a41fcac1c..b6f817768 100644--- a/public/components/common/Footer.tsx+++ b/public/components/common/Footer.tsx@@ -1,16 +1,13 @@import "./Footer.scss";import * as React from "react";-import { page } from "@fider/services";--const logo = require("@fider/assets/images/logo-small.png");export const Footer = () => {return (<div id="c-footer"><div className="container"><a target="_blank" href="https://getfider.com/">- <img src={`${page.getAssetsBaseUrl()}${logo}`} alt="Fider" />+ <img src="https://getfider.com/images/logo-100x100.png" alt="Fider" /><span>Powered by Fider</span></a></div>diff --git a/public/components/common/Gravatar.tsx b/public/components/common/Gravatar.tsxindex 7bc8d1ee3..aa86226e3 100644--- a/public/components/common/Gravatar.tsx+++ b/public/components/common/Gravatar.tsx@@ -1,7 +1,7 @@import "./Gravatar.scss";import * as React from "react";-import { page, classSet } from "@fider/services";+import { classSet } from "@fider/services";import { User, UserRole, UserStatus, CurrentUser } from "@fider/models";interface GravatarProps {@@ -13,7 +13,7 @@ export const Gravatar = (props: GravatarProps) => {const size = props.size || "normal";const id = props.user ? props.user.id : 0;const name = props.user ? props.user.name : "";- const url = `${page.getTenantAssetsBaseUrl()}/avatars/50/${id}/${encodeURIComponent(name || "?")}`;+ const url = `${Fider.settings.assetsURL}/avatars/50/${id}/${encodeURIComponent(name || "?")}`;const className = classSet({"c-avatar": true,diff --git a/public/components/common/Header.tsx b/public/components/common/Header.tsxindex 7da481dad..e50fef4fb 100644--- a/public/components/common/Header.tsx+++ b/public/components/common/Header.tsx@@ -3,21 +3,15 @@ import "./Header.scss";import * as React from "react";import { SystemSettings, CurrentUser, Tenant } from "@fider/models";import { SignInModal, SignInControl, EnvironmentInfo, Gravatar, Logo } from "@fider/components";-import { page, actions, classSet } from "@fider/services";--interface HeaderProps {- user?: CurrentUser;- system: SystemSettings;- tenant: Tenant;-}+import { actions, classSet } from "@fider/services";interface HeaderState {showSignIn: boolean;unreadNotifications: number;}-export class Header extends React.Component<HeaderProps, HeaderState> {- constructor(props: HeaderProps) {+export class Header extends React.Component<{}, HeaderState> {+ constructor(props: {}) {super(props);this.state = {showSignIn: false,@@ -26,7 +20,7 @@ export class Header extends React.Component<HeaderProps, HeaderState> {}public componentDidMount(): void {- if (this.props.user) {+ if (Fider.session.isAuthenticated) {actions.getTotalUnreadNotifications().then(result => {if (result.ok && result.data > 0) {this.setState({ unreadNotifications: result.data });@@ -36,17 +30,17 @@ export class Header extends React.Component<HeaderProps, HeaderState> {}private showModal = () => {- if (!this.props.user) {+ if (!Fider.session.isAuthenticated) {this.setState({ showSignIn: true });}};public render() {- const items = this.props.user && (+ const items = Fider.session.isAuthenticated && (<div className="c-menu-user"><div className="c-menu-user-heading"><i className="user icon" />- {this.props.user.name}+ {Fider.session.user.name}</div><a href="/settings" className="c-menu-user-item">Settings@@ -56,7 +50,7 @@ export class Header extends React.Component<HeaderProps, HeaderState> {{this.state.unreadNotifications > 0 && <div className="c-unread-count">{this.state.unreadNotifications}</div>}</a><div className="c-menu-user-divider" />- {this.props.user.isCollaborator && [+ {Fider.session.user.isCollaborator && [<div key={1} className="c-menu-user-heading"><i className="setting icon" />Administration@@ -72,22 +66,23 @@ export class Header extends React.Component<HeaderProps, HeaderState> {</div>);- const showRightMenu = this.props.user || !this.props.tenant.isPrivate;+ const showRightMenu = Fider.session.isAuthenticated || !Fider.session.tenant.isPrivate;return (<div id="c-header">- <EnvironmentInfo system={this.props.system} />+ <EnvironmentInfo /><SignInModal isOpen={this.state.showSignIn} /><div className="c-menu"><div className="container"><a href="/" className="c-menu-item-title">- <Logo size={100} tenant={this.props.tenant} />- <span>{this.props.tenant.name}</span>+ <Logo size={100} />+ <span>{Fider.session.tenant.name}</span></a>{showRightMenu && (<div onClick={this.showModal} className="c-menu-item-signin">- {this.props.user && <Gravatar user={this.props.user} />}+ {Fider.session.isAuthenticated && <Gravatar user={Fider.session.user} />}{this.state.unreadNotifications > 0 && <div className="c-unread-dot" />}- {!this.props.user && <span>Sign in</span>} {this.props.user && <i className="dropdown icon" />}+ {!Fider.session.isAuthenticated && <span>Sign in</span>}+ {Fider.session.isAuthenticated && <i className="dropdown icon" />}{items}</div>)}diff --git a/public/components/common/Legal.tsx b/public/components/common/Legal.tsxindex f635c1135..69045c552 100644--- a/public/components/common/Legal.tsx+++ b/public/components/common/Legal.tsx@@ -1,6 +1,5 @@import * as React from "react";import { Modal, Field, Checkbox } from "@fider/components/common";-import { page } from "@fider/services";const privacy = (<a href="/privacy" target="_blank">@@ -19,7 +18,7 @@ interface LegalAgreementProps {}export const LegalNotice: React.StatelessComponent<{}> = () => {- if (page.systemSettings().hasLegal) {+ if (Fider.settings.hasLegal) {return (<p className="info">By signing in, you agree to the {privacy} and {terms}.@@ -30,7 +29,7 @@ export const LegalNotice: React.StatelessComponent<{}> = () => {};export const LegalFooter: React.StatelessComponent<{}> = () => {- if (page.systemSettings().hasLegal) {+ if (Fider.settings.hasLegal) {return (<Modal.Footer align="center"><LegalNotice />@@ -41,7 +40,7 @@ export const LegalFooter: React.StatelessComponent<{}> = () => {};export const LegalAgreement: React.StatelessComponent<LegalAgreementProps> = props => {- if (page.systemSettings().hasLegal) {+ if (Fider.settings.hasLegal) {return (<Checkbox field="legalAgreement" onChange={props.onChange}>I have read and agree to the {privacy} and {terms}.diff --git a/public/components/common/Logo.tsx b/public/components/common/Logo.tsxindex 692dcadcc..c23522295 100644--- a/public/components/common/Logo.tsx+++ b/public/components/common/Logo.tsx@@ -1,21 +1,19 @@import * as React from "react";-import { Tenant } from "@fider/models";-import { page } from "@fider/services";interface LogoProps {url?: string;- tenant?: Tenant;size?: 50 | 100 | 200;}export const Logo = (props: LogoProps) => {+ const tenant = Fider.session.tenant;if (props.url) {return <img src={props.url} />;}const size = props.size || 200;- if (props.tenant && props.tenant.logoId > 0) {- return <img src={`${page.getTenantAssetsBaseUrl()}/logo/${size}/${props.tenant.logoId}`} alt={props.tenant.name} />;+ if (tenant && tenant.logoId > 0) {+ return <img src={`${Fider.settings.assetsURL}/logo/${size}/${tenant.logoId}`} alt={tenant.name} />;}return null;diff --git a/public/components/common/Modal.tsx b/public/components/common/Modal.tsxindex 45fcea876..0d607f607 100644--- a/public/components/common/Modal.tsx+++ b/public/components/common/Modal.tsx@@ -4,7 +4,7 @@ import * as React from "react";import * as ReactDOM from "react-dom";import { SystemSettings, CurrentUser, Tenant } from "@fider/models";import { SignInControl, EnvironmentInfo, Gravatar } from "@fider/components/common";-import { page, actions, classSet } from "@fider/services";+import { actions, classSet } from "@fider/services";interface ModalWindowProps {isOpen: boolean;diff --git a/public/components/common/SignInControl.tsx b/public/components/common/SignInControl.tsxindex c4c7c7718..70683598b 100644--- a/public/components/common/SignInControl.tsx+++ b/public/components/common/SignInControl.tsx@@ -2,8 +2,7 @@ import "./SignInControl.scss";import * as React from "react";import { SocialSignInButton, Form, Button, Input } from "@fider/components";-import { AuthSettings } from "@fider/models";-import { page, device, actions, Failure } from "@fider/services";+import { device, actions, Failure } from "@fider/services";interface SignInControlState {email: string;@@ -17,12 +16,8 @@ interface SignInControlProps {}export class SignInControl extends React.Component<SignInControlProps, SignInControlState> {- private settings: AuthSettings;-constructor(props: SignInControlProps) {super(props);- this.settings = page.authSettings();-this.state = {email: ""};@@ -53,28 +48,28 @@ export class SignInControl extends React.Component<SignInControlProps, SignInCon};public render() {- const google = this.settings.providers.google && (+ const google = Fider.settings.auth.providers.google && (<div className="col-sm l-social-col"><SocialSignInButton- oauthEndpoint={this.settings.endpoint}+ oauthEndpoint={Fider.settings.auth.endpoint}provider="google"redirectTo={this.props.redirectTo}/></div>);- const facebook = this.settings.providers.facebook && (+ const facebook = Fider.settings.auth.providers.facebook && (<div className="col-sm l-social-col"><SocialSignInButton- oauthEndpoint={this.settings.endpoint}+ oauthEndpoint={Fider.settings.auth.endpoint}provider="facebook"redirectTo={this.props.redirectTo}/></div>);- const github = this.settings.providers.github && (+ const github = Fider.settings.auth.providers.github && (<div className="col-sm l-social-col"><SocialSignInButton- oauthEndpoint={this.settings.endpoint}+ oauthEndpoint={Fider.settings.auth.endpoint}provider="github"redirectTo={this.props.redirectTo}/>diff --git a/public/fider.ts b/public/fider.tsnew file mode 100644index 000000000..39510369b--- /dev/null+++ b/public/fider.ts@@ -0,0 +1,55 @@+import { CurrentUser, SystemSettings, Tenant } from "@fider/models";++export class FiderSession {+ private pTenant: Tenant;+ private pUser: CurrentUser | undefined;+ private pProps: { [key: string]: any } = {};++ constructor() {+ this.pProps = window.__props;+ this.pUser = window.__user;+ this.pTenant = window.__tenant;+ }++ public get user(): CurrentUser {+ return this.pUser!;+ }++ public get tenant(): Tenant {+ return this.pTenant;+ }++ public get props(): { [key: string]: any } {+ return this.pProps;+ }++ public get isAuthenticated(): boolean {+ return !!this.pUser;+ }+}++export class Fider {+ private pSettings: SystemSettings;+ private pSession: FiderSession;++ constructor() {+ this.pSettings = window.__settings;+ this.pSession = new FiderSession();+ }++ public get session(): FiderSession {+ return this.pSession;+ }++ public get settings(): SystemSettings {+ return this.pSettings;+ }++ public isProduction(): boolean {+ return this.pSettings.environment === "production";+ }++ public isSingleHostMode(): boolean {+ return this.pSettings.mode === "single";+ }+}diff --git a/public/index.tsx b/public/index.tsxindex 5f257a1e5..1fc4c421d 100644--- a/public/index.tsx+++ b/public/index.tsx@@ -4,6 +4,7 @@ import { resolveRootComponent } from "@fider/router";import { Header, Footer } from "@fider/components/common";import { analytics, classSet } from "@fider/services";import { ToastContainer } from "react-toastify";+import { Fider } from "./fider";import "semantic-ui-css/components/reset.min.css";import "semantic-ui-css/components/icon.min.css";@@ -13,29 +14,26 @@ import "semantic-ui-css/components/transition.min.css";import "react-toastify/dist/ReactToastify.css";import "@fider/assets/styles/main.scss";-window.props = {} as any;-window.set = (key: string, value: any): void => {- window.props[key] = value;-};-window.addEventListener("error", (evt: ErrorEvent) => {analytics.error(evt.error);});document.addEventListener("DOMContentLoaded", () => {+ const fider = ((global as any).Fider = new Fider());+const root = document.getElementById("root");if (root) {const config = resolveRootComponent(location.pathname);document.body.className = classSet({- "is-authenticated": window.props.user,- "is-staff": window.props.user && window.props.user.isCollaborator+ "is-authenticated": fider.session.isAuthenticated,+ "is-staff": fider.session.isAuthenticated && fider.session.user.isCollaborator});ReactDOM.render(<><ToastContainer position="top-right" toastClassName="c-toast" />- {config.showHeader && React.createElement(Header, window.props)}- {React.createElement(config.component, window.props)}- {config.showHeader && React.createElement(Footer, window.props)}+ {config.showHeader && <Header />}+ {React.createElement(config.component, fider.session.props)}+ {config.showHeader && <Footer />}</>,root);diff --git a/public/models/settings.ts b/public/models/settings.tsindex d7b8b90bd..9e39d3e47 100644--- a/public/models/settings.ts+++ b/public/models/settings.ts@@ -2,20 +2,19 @@ export interface SystemSettings {mode: string;buildTime: string;version: string;- authEndpoint: string;environment: string;- googleAnalytics: string;compiler: string;domain: string;hasLegal: boolean;-}--export interface AuthSettings {- endpoint: string;- providers: {- google: boolean;- facebook: boolean;- github: boolean;+ baseURL: string;+ assetsURL: string;+ auth: {+ endpoint: string;+ providers: {+ google: boolean;+ facebook: boolean;+ github: boolean;+ };};}diff --git a/public/pages/Administration/components/AdminBasePage.tsx b/public/pages/Administration/components/AdminBasePage.tsxindex ed2d5835f..f3291cbc7 100644--- a/public/pages/Administration/components/AdminBasePage.tsx+++ b/public/pages/Administration/components/AdminBasePage.tsx@@ -3,11 +3,7 @@ import { CurrentUser } from "@fider/models";import { Heading } from "@fider/components";import { SideMenu } from "./";-interface AdminBasePageProps {- user: CurrentUser;-}--export abstract class AdminBasePage<P extends AdminBasePageProps, S> extends React.Component<P, S> {+export abstract class AdminBasePage<P, S> extends React.Component<P, S> {public abstract id: string;public abstract name: string;public abstract icon: string;@@ -22,7 +18,7 @@ export abstract class AdminBasePage<P extends AdminBasePageProps, S> extends Rea<div className="row"><div className="col-lg-2">- <SideMenu user={this.props.user} activeItem={this.name} />+ <SideMenu activeItem={this.name} /></div><div className="col-lg-10">{this.content()}</div></div>diff --git a/public/pages/Administration/components/SideMenu.tsx b/public/pages/Administration/components/SideMenu.tsxindex 5980f73c1..eb05e2b7c 100644--- a/public/pages/Administration/components/SideMenu.tsx+++ b/public/pages/Administration/components/SideMenu.tsx@@ -2,12 +2,11 @@ import "./SideMenu.scss";import * as React from "react";import { CurrentUser } from "@fider/models";-import { classSet, page } from "@fider/services";+import { classSet } from "@fider/services";import { FiderVersion } from "@fider/components";interface SiteMenuProps {activeItem: string;- user: CurrentUser;}interface SideMenuItemProps {@@ -54,7 +53,7 @@ export const SideMenu = (props: SiteMenuProps) => {isActive={activeItem === "invitations"}/><SideMenuItem name="advanced" title="Advanced" href="/admin/advanced" isActive={activeItem === "advanced"} />- {props.user.isAdministrator && (+ {Fider.session.user.isAdministrator && (<SideMenuItem name="export" title="Export" href="/admin/export" isActive={activeItem === "export"} />)}</div>diff --git a/public/pages/Administration/components/TagListItem.tsx b/public/pages/Administration/components/TagListItem.tsxindex 4292b1e10..aca27a9b7 100644--- a/public/pages/Administration/components/TagListItem.tsx+++ b/public/pages/Administration/components/TagListItem.tsx@@ -7,7 +7,6 @@ import { TagFormState, TagForm } from "./";import { actions, Failure } from "@fider/services";interface TagListItemProps {- user: CurrentUser;tag: Tag;onTagEditted: (tag: Tag) => void;onTagDeleted: (tag: Tag) => void;@@ -95,7 +94,7 @@ export class TagListItem extends React.Component<TagListItemProps, TagListItemSt}private renderViewMode() {- const buttons = this.props.user.isAdministrator && [+ const buttons = Fider.session.user.isAdministrator && [<Button key={0} onClick={this.startDelete} className="right"><i className="remove icon" />Delete</Button>,diff --git a/public/pages/Administration/pages/AdvancedSettings.page.tsx b/public/pages/Administration/pages/AdvancedSettings.page.tsxindex a6999f961..33fa80607 100644--- a/public/pages/Administration/pages/AdvancedSettings.page.tsx+++ b/public/pages/Administration/pages/AdvancedSettings.page.tsx@@ -5,10 +5,9 @@ import * as React from "react";import { CurrentUser } from "@fider/models";import { AdminBasePage } from "../components";import { DisplayError, TextArea, Form, Button, ButtonClickEvent } from "@fider/components";-import { Failure, actions, page } from "@fider/services";+import { Failure, actions } from "@fider/services";interface AdvancedSettingsPageProps {- user: CurrentUser;customCSS: string;}@@ -39,7 +38,7 @@ export class AdvancedSettingsPage extends AdminBasePage<AdvancedSettingsPagePropprivate handleSave = async (e: ButtonClickEvent): Promise<void> => {const result = await actions.updateTenantAdvancedSettings(this.state.customCSS);if (result.ok) {- page.refresh();+ location.reload();} else {this.setState({ error: result.error });}@@ -51,7 +50,7 @@ export class AdvancedSettingsPage extends AdminBasePage<AdvancedSettingsPageProp<TextAreafield="customCSS"label="Custom CSS"- disabled={!this.props.user.isAdministrator}+ disabled={!Fider.session.user.isAdministrator}minRows={10}value={this.state.customCSS}onChange={this.setCustomCSS}@@ -79,7 +78,7 @@ export class AdvancedSettingsPage extends AdminBasePage<AdvancedSettingsPageProp</ul></TextArea>- {this.props.user.isAdministrator && (+ {Fider.session.user.isAdministrator && (<div className="field"><Button color="positive" onClick={this.handleSave}>Save changesdiff --git a/public/pages/Administration/pages/Export.page.tsx b/public/pages/Administration/pages/Export.page.tsxindex 3363162ec..dd93cb3d7 100644--- a/public/pages/Administration/pages/Export.page.tsx+++ b/public/pages/Administration/pages/Export.page.tsx@@ -6,11 +6,7 @@ import { CurrentUser } from "@fider/models";import { Button, Form, Field } from "@fider/components";import { AdminBasePage } from "../components";-interface ExportPageProps {- user: CurrentUser;-}--export class ExportPage extends AdminBasePage<ExportPageProps, {}> {+export class ExportPage extends AdminBasePage<{}, {}> {public id = "p-admin-export";public name = "export";public icon = "file excel outline";diff --git a/public/pages/Administration/pages/GeneralSettings.page.tsx b/public/pages/Administration/pages/GeneralSettings.page.tsxindex 6fa97d495..714b796e8 100644--- a/public/pages/Administration/pages/GeneralSettings.page.tsx+++ b/public/pages/Administration/pages/GeneralSettings.page.tsx@@ -2,15 +2,11 @@ import "./GeneralSettings.page.scss";import * as React from "react";-import { SystemSettings, CurrentUser, Tenant } from "@fider/models";import { Button, ButtonClickEvent, TextArea, DisplayError, Logo, Form, Input, Field } from "@fider/components/common";-import { actions, page, Failure, fileToBase64 } from "@fider/services";+import { actions, Failure, fileToBase64 } from "@fider/services";import { AdminBasePage } from "../components";interface GeneralSettingsPageProps {- user: CurrentUser;- tenant: Tenant;- system: SystemSettings;publicIP: string;}@@ -42,10 +38,10 @@ export class GeneralSettingsPage extends AdminBasePage<GeneralSettingsPageProps,super(props);this.state = {- title: this.props.tenant.name,- cname: this.props.tenant.cname,- welcomeMessage: this.props.tenant.welcomeMessage,- invitation: this.props.tenant.invitation+ title: Fider.session.tenant.name,+ cname: Fider.session.tenant.cname,+ welcomeMessage: Fider.session.tenant.welcomeMessage,+ invitation: Fider.session.tenant.invitation};}@@ -96,7 +92,7 @@ export class GeneralSettingsPage extends AdminBasePage<GeneralSettingsPageProps,const isApex = this.state.cname.split(".").length === 2;const recordType = isApex ? "A" : "CNAME";const publicIP = this.props.publicIP || "<error>";- const targetRecord = isApex ? publicIP : `${this.props.tenant.subdomain}${this.props.system.domain}`;+ const targetRecord = isApex ? publicIP : `${Fider.session.tenant.subdomain}${Fider.settings.domain}`;return (<><strong>{this.state.cname}</strong> {recordType} <strong>{targetRecord}</strong>@@ -123,7 +119,7 @@ export class GeneralSettingsPage extends AdminBasePage<GeneralSettingsPageProps,public content() {const isRemoving = this.state.logo ? this.state.logo.remove : false;const isUploading = this.state.logo ? !!this.state.logo.upload : false;- const hasFile = (this.props.tenant.logoId > 0 && !isRemoving) || isUploading;+ const hasFile = (Fider.session.tenant.logoId > 0 && !isRemoving) || isUploading;const previewUrl =isUploading && this.state.logo && this.state.logo.upload? `data:${this.state.logo.upload.contentType};base64,${this.state.logo.upload.content}`@@ -136,14 +132,14 @@ export class GeneralSettingsPage extends AdminBasePage<GeneralSettingsPageProps,label="Title"maxLength={60}value={this.state.title}- disabled={!this.props.user.isAdministrator}+ disabled={!Fider.session.user.isAdministrator}onChange={this.setTitle}/><TextAreafield="welcomeMessage"label="Welcome Message"value={this.state.welcomeMessage}- disabled={!this.props.user.isAdministrator}+ disabled={!Fider.session.user.isAdministrator}onChange={this.setWelcomeMessage}/><Input@@ -151,20 +147,20 @@ export class GeneralSettingsPage extends AdminBasePage<GeneralSettingsPageProps,label="Invitation"maxLength={60}value={this.state.invitation}- disabled={!this.props.user.isAdministrator}+ disabled={!Fider.session.user.isAdministrator}onChange={this.setInvitation}/><Field label="Logo" className="c-logo-upload">- {hasFile && <Logo size={200} tenant={this.props.tenant} url={previewUrl} />}+ {hasFile && <Logo size={200} url={previewUrl} />}<input ref={e => (this.fileSelector = e)} type="file" onChange={this.fileChanged} /><DisplayError fields={["logo"]} error={this.state.error} /><div>- <Button size="tiny" onClick={this.selectFile} disabled={!this.props.user.isAdministrator}>+ <Button size="tiny" onClick={this.selectFile} disabled={!Fider.session.user.isAdministrator}>{hasFile ? "Change" : "Upload"}</Button>{hasFile && (- <Button onClick={this.removeFile} size="tiny" disabled={!this.props.user.isAdministrator}>+ <Button onClick={this.removeFile} size="tiny" disabled={!Fider.session.user.isAdministrator}>Remove</Button>)}@@ -175,14 +171,14 @@ export class GeneralSettingsPage extends AdminBasePage<GeneralSettingsPageProps,</p></Field>- {!page.isSingleHostMode() && (+ {!Fider.isSingleHostMode() && (<Inputfield="cname"label="Custom Domain"maxLength={100}placeholder="feedback.yourcompany.com"value={this.state.cname}- disabled={!this.props.user.isAdministrator}+ disabled={!Fider.session.user.isAdministrator}onChange={this.setCNAME}><div className="info">@@ -206,7 +202,7 @@ export class GeneralSettingsPage extends AdminBasePage<GeneralSettingsPageProps,)}<div className="field">- <Button disabled={!this.props.user.isAdministrator} color="positive" onClick={this.handleSave}>+ <Button disabled={!Fider.session.user.isAdministrator} color="positive" onClick={this.handleSave}>Save changes</Button></div>diff --git a/public/pages/Administration/pages/Invitations.page.tsx b/public/pages/Administration/pages/Invitations.page.tsxindex 2ba63adea..a797ebd00 100644--- a/public/pages/Administration/pages/Invitations.page.tsx+++ b/public/pages/Administration/pages/Invitations.page.tsx@@ -5,11 +5,6 @@ import { Button, ButtonClickEvent, TextArea, DisplayError, Form, Input, Field }import { actions, notify, Failure } from "@fider/services";import { AdminBasePage } from "../components";-interface InvitationsPageProps {- user: CurrentUser;- tenant: Tenant;-}-interface InvitationsPageState {subject: string;message: string;@@ -19,22 +14,22 @@ interface InvitationsPageState {error?: Failure;}-export class InvitationsPage extends AdminBasePage<InvitationsPageProps, InvitationsPageState> {+export class InvitationsPage extends AdminBasePage<{}, InvitationsPageState> {public id = "p-admin-invitations";public name = "invitations";public icon = "envelope";public title = "Invitations";public subtitle = "Invite people to share their feedback";- constructor(props: InvitationsPageProps) {+ constructor(props: {}) {super(props);this.state = {- subject: `Share your ideas and thoughts about ${this.props.tenant.name}`,+ subject: `Share your ideas and thoughts about ${Fider.session.tenant.name}`,message: `Hi,At **${- this.props.tenant.name+ Fider.session.tenant.name}** we take feedback very seriously, which is why we've launched a space where you can vote, discuss and share your ideas and thoughts about our products and services.We'd like to extend an invite for you to join this community and raise awareness on topics you care about!@@ -44,7 +39,7 @@ To join, click on the link below.%invite%Regards,-${this.props.user.name} (${this.props.tenant.name})`,+${Fider.session.user.name} (${Fider.session.tenant.name})`,recipients: [],numOfRecipients: 0,rawRecipients: ""@@ -61,7 +56,7 @@ ${this.props.user.name} (${this.props.tenant.name})`,if (result.ok) {notify.success(<span>- An email message was sent to <strong>{this.props.user.email}</strong>+ An email message was sent to <strong>{Fider.session.user.email}</strong></span>);}@@ -138,8 +133,8 @@ ${this.props.user.name} (${this.props.tenant.name})`,We highly recommend to send yourself a sample email for you to verify if everything is correct beforeinviting your list of contacts.</p>- {this.props.user.email ? (- <Button onClick={this.sendSample}>Send a sample email to {this.props.user.email}</Button>+ {Fider.session.user.email ? (+ <Button onClick={this.sendSample}>Send a sample email to {Fider.session.user.email}</Button>) : (<Button disabled={true}>Your profile doesn't have an email</Button>)}diff --git a/public/pages/Administration/pages/ManageMembers.page.tsx b/public/pages/Administration/pages/ManageMembers.page.tsxindex 9316a618d..7e98339a4 100644--- a/public/pages/Administration/pages/ManageMembers.page.tsx+++ b/public/pages/Administration/pages/ManageMembers.page.tsx@@ -17,7 +17,6 @@ interface ManageMembersPageState {}interface ManageMembersPageProps {- user: CurrentUser;users: User[];}@@ -55,7 +54,7 @@ export class ManageMembersPage extends AdminBasePage<ManageMembersPageProps, Man};private showUser(user: User, role: UserRole, addable: boolean, removable: boolean) {- if (user.id === this.props.user.id || this.props.user.role !== UserRole.Administrator) {+ if (user.id === Fider.session.user.id || Fider.session.user.role !== UserRole.Administrator) {removable = false;}@@ -111,7 +110,7 @@ export class ManageMembersPage extends AdminBasePage<ManageMembersPageProps, Man<List hover={true}>{this.state.administrators.map(x => this.showUser(x, UserRole.Administrator, false, true))}</List>- {this.props.user.role === UserRole.Administrator && (+ {Fider.session.user.isAdministrator && (<Form size="mini"><Inputlabel="Add new administrator"@@ -137,7 +136,7 @@ export class ManageMembersPage extends AdminBasePage<ManageMembersPageProps, Man<List hover={true}>{this.state.collaborators.map(x => this.showUser(x, UserRole.Collaborator, false, true))}</List>- {this.props.user.role === UserRole.Administrator && (+ {Fider.session.user.isAdministrator && (<Form size="mini"><Inputlabel="Add new collaborator"diff --git a/public/pages/Administration/pages/ManageTags.page.tsx b/public/pages/Administration/pages/ManageTags.page.tsxindex 6e1d7d797..9c6caca28 100644--- a/public/pages/Administration/pages/ManageTags.page.tsx+++ b/public/pages/Administration/pages/ManageTags.page.tsx@@ -8,7 +8,6 @@ import { Tag, CurrentUser, UserRole } from "@fider/models";import { actions, Failure } from "@fider/services";interface ManageTagsPageProps {- user: CurrentUser;tags: Tag[];}@@ -83,13 +82,7 @@ export class ManageTagsPage extends AdminBasePage<ManageTagsPageProps, ManageTagprivate getTagList(filter: (tag: Tag) => boolean) {return this.state.allTags.filter(filter).map(t => {return (- <TagListItem- key={t.id}- tag={t}- user={this.props.user}- onTagDeleted={this.handleTagDeleted}- onTagEditted={this.handleTagEditted}- />+ <TagListItem key={t.id} tag={t} onTagDeleted={this.handleTagDeleted} onTagEditted={this.handleTagEditted} />);});}@@ -99,7 +92,7 @@ export class ManageTagsPage extends AdminBasePage<ManageTagsPageProps, ManageTagconst privateTagList = this.getTagList(t => !t.isPublic);const form =- this.props.user.isAdministrator &&+ Fider.session.user.isAdministrator &&(this.state.isAdding ? (<Segment><TagForm onSave={this.saveNewTag} onCancel={this.cancelAdd} />diff --git a/public/pages/Administration/pages/PrivacySettings.page.tsx b/public/pages/Administration/pages/PrivacySettings.page.tsxindex 14b3a4ef3..233be3ba9 100644--- a/public/pages/Administration/pages/PrivacySettings.page.tsx+++ b/public/pages/Administration/pages/PrivacySettings.page.tsx@@ -7,27 +7,22 @@ import { Button, ButtonClickEvent, DisplayError, Toggle, Form } from "@fider/comimport { actions, notify, Failure } from "@fider/services";import { AdminBasePage } from "../components";-interface PrivacySettingsPageProps {- user: CurrentUser;- tenant: Tenant;-}-interface PrivacySettingsPageState {isPrivate: boolean;}-export class PrivacySettingsPage extends AdminBasePage<PrivacySettingsPageProps, PrivacySettingsPageState> {+export class PrivacySettingsPage extends AdminBasePage<{}, PrivacySettingsPageState> {public id = "p-admin-privacy";public name = "privacy";public icon = "key";public title = "Privacy";public subtitle = "Manage your site privacy";- constructor(props: PrivacySettingsPageProps) {+ constructor(props: {}) {super(props);this.state = {- isPrivate: this.props.tenant.isPrivate+ isPrivate: Fider.session.tenant.isPrivate};}@@ -50,7 +45,7 @@ export class PrivacySettingsPage extends AdminBasePage<PrivacySettingsPageProps,<Form><div className="c-form-field"><label htmlFor="private">Private site</label>- <Toggle disabled={!this.props.user.isAdministrator} active={this.state.isPrivate} onToggle={this.toggle} />+ <Toggle disabled={!Fider.session.user.isAdministrator} active={this.state.isPrivate} onToggle={this.toggle} /><p className="info">A private site prevents unauthenticated users from viewing or interacting with its content. <br /> Ifenabled, only already registered and invited users will be able to sign in to this site.diff --git a/public/pages/CompleteSignInProfile/CompleteSignInProfile.page.tsx b/public/pages/CompleteSignInProfile/CompleteSignInProfile.page.tsxindex ff9e33535..c53edeb8f 100644--- a/public/pages/CompleteSignInProfile/CompleteSignInProfile.page.tsx+++ b/public/pages/CompleteSignInProfile/CompleteSignInProfile.page.tsx@@ -2,7 +2,7 @@ import * as React from "react";import { HomePage, HomePageProps, SignInPage } from "../";import { Modal, Button, Form, Input, LegalFooter } from "@fider/components";-import { page, actions, Failure } from "@fider/services";+import { actions, Failure, querystring } from "@fider/services";interface CompleteSignInProfilePageState {name: string;@@ -14,7 +14,7 @@ export class CompleteSignInProfilePage extends React.Component<HomePageProps, Coconstructor(props: HomePageProps) {super(props);- this.key = page.getQueryString("k");+ this.key = querystring.get("k");this.state = {name: ""};@@ -56,7 +56,7 @@ export class CompleteSignInProfilePage extends React.Component<HomePageProps, Co</Modal.Content><LegalFooter /></Modal.Window>- {this.props.tenant.isPrivate+ {Fider.session.tenant.isPrivate? React.createElement(SignInPage, this.props): React.createElement(HomePage, this.props)}</>diff --git a/public/pages/Home/Home.page.tsx b/public/pages/Home/Home.page.tsxindex bb5148024..49505073f 100644--- a/public/pages/Home/Home.page.tsx+++ b/public/pages/Home/Home.page.tsx@@ -1,15 +1,13 @@import "./Home.page.scss";import * as React from "react";-import { Idea, Tag, IdeaStatus, CurrentUser, Tenant } from "@fider/models";+import { Idea, Tag, IdeaStatus } from "@fider/models";import { MultiLineText } from "@fider/components";import { IdeaInput, ListIdeas, IdeasContainer } from "./";-import { page, actions } from "@fider/services";+import { actions } from "@fider/services";import { SimilarIdeas } from "./components/SimilarIdeas";export interface HomePageProps {- user?: CurrentUser;- tenant: Tenant;ideas: Idea[];tags: Tag[];countPerStatus: { [key: string]: number };@@ -66,12 +64,11 @@ export class HomePage extends React.Component<HomePageProps, HomePageState> {<div className="col-md-4"><MultiLineTextclassName="welcome-message"- text={this.props.tenant.welcomeMessage || defaultWelcomeMessage}+ text={Fider.session.tenant.welcomeMessage || defaultWelcomeMessage}style="full"/><IdeaInput- user={this.props.user}- placeholder={this.props.tenant.invitation || "Enter your idea here..."}+ placeholder={Fider.session.tenant.invitation || "Enter your idea here..."}onTitleChanged={this.setTitle}/></div>@@ -79,10 +76,9 @@ export class HomePage extends React.Component<HomePageProps, HomePageState> {{this.isLonely() ? (<Lonely />) : this.state.title ? (- <SimilarIdeas title={this.state.title} user={this.props.user} tags={this.props.tags} />+ <SimilarIdeas title={this.state.title} tags={this.props.tags} />) : (<IdeasContainer- user={this.props.user}ideas={this.props.ideas}tags={this.props.tags}countPerStatus={this.props.countPerStatus}diff --git a/public/pages/Home/components/IdeaFilter.tsx b/public/pages/Home/components/IdeaFilter.tsxindex 7d7853a2f..9a485b24c 100644--- a/public/pages/Home/components/IdeaFilter.tsx+++ b/public/pages/Home/components/IdeaFilter.tsx@@ -3,7 +3,6 @@ import { Idea, IdeaStatus, CurrentUser } from "@fider/models";import { Dropdown, DropdownItemProps, DropdownProps } from "@fider/components";interface IdeaFilterProps {- user?: CurrentUser;activeFilter: string;countPerStatus: { [key: string]: number };filterChanged: (name: string) => void;@@ -26,7 +25,7 @@ export class IdeaFilter extends React.Component<IdeaFilterProps, {}> {{ text: "most discussed", value: "most-discussed", content: "Most Discussed" }];- if (this.props.user) {+ if (Fider.session.isAuthenticated) {options.push({ text: "my votes", value: "my-votes", content: "My Votes" });}diff --git a/public/pages/Home/components/IdeaInput.tsx b/public/pages/Home/components/IdeaInput.tsxindex 07298fb5f..bdad67035 100644--- a/public/pages/Home/components/IdeaInput.tsx+++ b/public/pages/Home/components/IdeaInput.tsx@@ -1,11 +1,10 @@import * as React from "react";import { DisplayError, Button, ButtonClickEvent, Input, Form, TextArea } from "@fider/components";import { SignInModal } from "@fider/components";-import { page, cache, actions, Failure } from "@fider/services";+import { cache, actions, Failure } from "@fider/services";import { CurrentUser } from "@fider/models";interface IdeaInputProps {- user?: CurrentUser;placeholder: string;onTitleChanged: (title: string) => void;}@@ -27,8 +26,8 @@ export class IdeaInput extends React.Component<IdeaInputProps, IdeaInputState> {constructor(props: IdeaInputProps) {super(props);this.state = {- title: (!!this.props.user && cache.get(CACHE_TITLE_KEY)) || "",- description: (!!this.props.user && cache.get(CACHE_DESCRIPTION_KEY)) || "",+ title: (Fider.session.isAuthenticated && cache.get(CACHE_TITLE_KEY)) || "",+ description: (Fider.session.isAuthenticated && cache.get(CACHE_DESCRIPTION_KEY)) || "",focused: false,showSignIn: false};@@ -39,13 +38,13 @@ export class IdeaInput extends React.Component<IdeaInputProps, IdeaInputState> {}public componentDidMount() {- if (this.props.user && this.title) {+ if (Fider.session.isAuthenticated && this.title) {this.title.focus();}}private handleTitleFocus = () => {- if (!this.props.user && this.title) {+ if (!Fider.session.isAuthenticated && this.title) {this.title.blur();this.setState({ showSignIn: true });}diff --git a/public/pages/Home/components/IdeasContainer.tsx b/public/pages/Home/components/IdeasContainer.tsxindex 645769c13..56621df54 100644--- a/public/pages/Home/components/IdeasContainer.tsx+++ b/public/pages/Home/components/IdeasContainer.tsx@@ -4,7 +4,7 @@ import { IdeaInput, ListIdeas, TagsFilter, IdeaFilter } from "../";import { Idea, Tag, IdeaStatus, CurrentUser } from "@fider/models";import { Loader, MultiLineText, Heading, Field, Input } from "@fider/components";-import { page, actions } from "@fider/services";+import { actions, querystring } from "@fider/services";interface IdeasContainerProps {user?: CurrentUser;@@ -29,10 +29,10 @@ export class IdeasContainer extends React.Component<IdeasContainerProps, IdeasCothis.state = {ideas: this.props.ideas,loading: false,- filter: page.getQueryString("f"),- query: page.getQueryString("q"),- tags: page.getQueryStringArray("t"),- limit: page.getQueryStringAsNumber("l")+ filter: querystring.get("f"),+ query: querystring.get("q"),+ tags: querystring.getArray("t"),+ limit: querystring.getNumber("l")};}@@ -42,8 +42,8 @@ export class IdeasContainer extends React.Component<IdeasContainerProps, IdeasCo): void {this.setState(obj, () => {const query = this.state.query.trim().toLowerCase();- page.replaceState(- page.toQueryString({+ actions.replaceState(+ querystring.stringify({t: this.state.tags,q: query,f: this.state.filter,@@ -105,7 +105,6 @@ export class IdeasContainer extends React.Component<IdeasContainerProps, IdeasCo<div className="l-filter-col col-sm-7 col-md-8 col-lg-9 mb-2"><Field><IdeaFilter- user={this.props.user}activeFilter={this.state.filter}filterChanged={this.handleFilterChanged}countPerStatus={this.props.countPerStatus}@@ -132,7 +131,6 @@ export class IdeasContainer extends React.Component<IdeasContainerProps, IdeasCo<ListIdeasideas={this.state.ideas}tags={this.props.tags}- user={this.props.user}emptyText={"No results matched your search, try something different."}/>{this.state.loading && <Loader />}diff --git a/public/pages/Home/components/ListIdeas.tsx b/public/pages/Home/components/ListIdeas.tsxindex 188ff9956..551b14fd8 100644--- a/public/pages/Home/components/ListIdeas.tsx+++ b/public/pages/Home/components/ListIdeas.tsx@@ -14,7 +14,6 @@ import {} from "@fider/components";interface ListIdeasProps {- user?: CurrentUser;ideas?: Idea[];tags: Tag[];emptyText: string;@@ -23,7 +22,7 @@ interface ListIdeasProps {const ListIdeaItem = (props: { idea: Idea; user?: CurrentUser; tags: Tag[] }) => {return (<ListItem>- <SupportCounter user={props.user} idea={props.idea} />+ <SupportCounter idea={props.idea} /><div className="c-list-item-content">{props.idea.totalComments > 0 && (<div className="info right">@@ -60,7 +59,6 @@ export class ListIdeas extends React.Component<ListIdeasProps, {}> {{this.props.ideas.map(idea => (<ListIdeaItemkey={idea.id}- user={this.props.user}idea={idea}tags={this.props.tags.filter(tag => idea.tags.indexOf(tag.slug) >= 0)}/>diff --git a/public/pages/Home/components/SimilarIdeas.tsx b/public/pages/Home/components/SimilarIdeas.tsxindex a9789f57f..ba80321df 100644--- a/public/pages/Home/components/SimilarIdeas.tsx+++ b/public/pages/Home/components/SimilarIdeas.tsx@@ -69,7 +69,6 @@ export class SimilarIdeas extends React.Component<SimilarIdeasProps, SimilarIdea<ListIdeasideas={this.state.ideas}tags={this.props.tags}- user={this.props.user}emptyText={`No similar ideas matched '${this.props.title}'.`}/>)}diff --git a/public/pages/MyNotifications/MyNotifications.page.tsx b/public/pages/MyNotifications/MyNotifications.page.tsxindex da2b40040..29cebdf45 100644--- a/public/pages/MyNotifications/MyNotifications.page.tsx+++ b/public/pages/MyNotifications/MyNotifications.page.tsx@@ -4,7 +4,7 @@ import * as React from "react";import { CurrentUser, Notification } from "@fider/models";import { MultiLineText, Moment, Heading, List, ListItem } from "@fider/components";-import { page, actions } from "@fider/services";+import { actions } from "@fider/services";interface MyNotificationsPageProps {notifications: Notification[];@@ -51,7 +51,7 @@ export class MyNotificationsPage extends React.Component<MyNotificationsPagePropprivate markAllAsRead = async () => {const response = await actions.markAllAsRead();if (response.ok) {- page.refresh();+ location.reload();}};diff --git a/public/pages/MySettings/MySettings.page.tsx b/public/pages/MySettings/MySettings.page.tsxindex d5ec3f45a..26624d662 100644--- a/public/pages/MySettings/MySettings.page.tsx+++ b/public/pages/MySettings/MySettings.page.tsx@@ -14,12 +14,11 @@ interface MySettingsPageState {newEmail: string;changingEmail: boolean;error?: Failure;- settings: UserSettings;+ userSettings: UserSettings;}interface MySettingsPageProps {- user: CurrentUser;- settings: UserSettings;+ userSettings: UserSettings;}export class MySettingsPage extends React.Component<MySettingsPageProps, MySettingsPageState> {@@ -29,13 +28,13 @@ export class MySettingsPage extends React.Component<MySettingsPageProps, MySettishowModal: false,changingEmail: false,newEmail: "",- name: this.props.user.name,- settings: this.props.settings+ name: Fider.session.user.name,+ userSettings: this.props.userSettings};}private confirm = async () => {- const result = await actions.updateUserSettings(this.state.name, this.state.settings);+ const result = await actions.updateUserSettings(this.state.name, this.state.userSettings);if (result.ok) {location.reload();} else if (result.error) {@@ -72,8 +71,8 @@ export class MySettingsPage extends React.Component<MySettingsPageProps, MySettithis.setState({ name });};- private setNotificationSettings = (settings: UserSettings) => {- this.setState({ settings });+ private setNotificationSettings = (userSettings: UserSettings) => {+ this.setState({ userSettings });};private closeModal = () => {@@ -117,7 +116,7 @@ export class MySettingsPage extends React.Component<MySettingsPageProps, MySetti<Form error={this.state.error}><Field label="Avatar"><p>- <Gravatar user={this.props.user} />+ <Gravatar user={Fider.session.user} /></p><div className="info"><p>@@ -134,14 +133,14 @@ export class MySettingsPage extends React.Component<MySettingsPageProps, MySetti<Inputlabel="Email"field="email"- value={this.state.changingEmail ? this.state.newEmail : this.props.user.email}+ value={this.state.changingEmail ? this.state.newEmail : Fider.session.user.email}maxLength={200}disabled={!this.state.changingEmail}afterLabel={this.state.changingEmail ? undefined : changeEmail}onChange={this.setNewEmail}><p className="info">- {this.props.user.email || this.state.changingEmail+ {Fider.session.user.email || this.state.changingEmail? "Your email is private and will never be displayed to anyone": "Your account doesn't have an email."}</p>@@ -160,8 +159,7 @@ export class MySettingsPage extends React.Component<MySettingsPageProps, MySetti<Input label="Name" field="name" value={this.state.name} maxLength={100} onChange={this.setName} /><NotificationSettings- user={this.props.user}- settings={this.props.settings}+ userSettings={this.props.userSettings}settingsChanged={this.setNotificationSettings}/>@@ -174,7 +172,7 @@ export class MySettingsPage extends React.Component<MySettingsPageProps, MySetti<div className="row"><div className="col-lg-7">- <DangerZone user={this.props.user} />+ <DangerZone /></div></div></div>diff --git a/public/pages/MySettings/components/DangerZone.tsx b/public/pages/MySettings/components/DangerZone.tsxindex 6f90dd082..aa71d3098 100644--- a/public/pages/MySettings/components/DangerZone.tsx+++ b/public/pages/MySettings/components/DangerZone.tsx@@ -2,18 +2,14 @@ import * as React from "react";import { CurrentUser, UserSettings } from "@fider/models";import { Toggle, Segment, Segments, Field, Button, Modal, ButtonClickEvent } from "@fider/components";-import { actions, page, notify } from "@fider/services";--interface DangerZoneProps {- user: CurrentUser;-}+import { actions, notify } from "@fider/services";interface DangerZoneState {clicked: boolean;}-export class DangerZone extends React.Component<DangerZoneProps, DangerZoneState> {- constructor(props: DangerZoneProps) {+export class DangerZone extends React.Component<{}, DangerZoneState> {+ constructor(props: {}) {super(props);this.state = {clicked: false@@ -32,7 +28,7 @@ export class DangerZone extends React.Component<DangerZoneProps, DangerZoneStateconst response = await actions.deleteCurrentAccount();if (response.ok) {e.preventEnable();- page.goHome();+ actions.goHome();} else {notify.error("Failed to delete your account. Try again later");}diff --git a/public/pages/MySettings/components/NotificationSettings.tsx b/public/pages/MySettings/components/NotificationSettings.tsxindex d9e64882b..35838f21d 100644--- a/public/pages/MySettings/components/NotificationSettings.tsx+++ b/public/pages/MySettings/components/NotificationSettings.tsx@@ -4,13 +4,12 @@ import { CurrentUser, UserSettings } from "@fider/models";import { Toggle, Segment, Segments, Field } from "@fider/components";interface NotificationSettingsProps {- user: CurrentUser;- settings: UserSettings;+ userSettings: UserSettings;settingsChanged: (settings: UserSettings) => void;}interface NotificationSettingsState {- settings: UserSettings;+ userSettings: UserSettings;}type Channel = number;@@ -22,23 +21,23 @@ export class NotificationSettings extends React.Component<NotificationSettingsPrsuper(props);this.state = {- settings: this.props.settings+ userSettings: this.props.userSettings};}private isEnabled(settingsKey: string, channel: Channel): boolean {- if (settingsKey in this.state.settings) {- return (parseInt(this.state.settings[settingsKey], 10) & channel) > 0;+ if (settingsKey in this.state.userSettings) {+ return (parseInt(this.state.userSettings[settingsKey], 10) & channel) > 0;}return false;}private toggle(settingsKey: string, channel: Channel) {- const settings = { ...this.state.settings };- settings[settingsKey] = (parseInt(this.state.settings[settingsKey], 10) ^ channel).toString();+ const userSettings = { ...this.state.userSettings };+ userSettings[settingsKey] = (parseInt(this.state.userSettings[settingsKey], 10) ^ channel).toString();- this.setState({ settings });- this.props.settingsChanged(settings);+ this.setState({ userSettings });+ this.props.settingsChanged(userSettings);}private icon(settingsKey: string, channel: Channel) {@@ -55,7 +54,7 @@ export class NotificationSettings extends React.Component<NotificationSettingsPr}private info(settingsKey: string, aboutForVisitors: string, aboutForCollaborators: string) {- const about = this.props.user.isCollaborator ? aboutForCollaborators : aboutForVisitors;+ const about = Fider.session.user.isCollaborator ? aboutForCollaborators : aboutForVisitors;const webEnabled = this.isEnabled(settingsKey, WebChannel);const emailEnabled = this.isEnabled(settingsKey, EmailChannel);diff --git a/public/pages/ShowIdea/ShowIdea.page.tsx b/public/pages/ShowIdea/ShowIdea.page.tsxindex 6d24b0151..220869266 100644--- a/public/pages/ShowIdea/ShowIdea.page.tsx+++ b/public/pages/ShowIdea/ShowIdea.page.tsx@@ -2,7 +2,7 @@ import "./ShowIdea.page.scss";import * as React from "react";-import { CurrentUser, Comment, Idea, Tag } from "@fider/models";+import { Comment, Idea, Tag } from "@fider/models";import { actions, Failure } from "@fider/services";import { TagsPanel, DiscussionPanel, ResponseForm, NotificationsPanel, ModerationPanel } from "./";@@ -23,7 +23,6 @@ import {} from "@fider/components";interface ShowIdeaPageProps {- user?: CurrentUser;idea: Idea;subscribed: boolean;comments: Comment[];@@ -87,7 +86,7 @@ export class ShowIdeaPage extends React.Component<ShowIdeaPageProps, ShowIdeaPag<div className="header-col"><List><ListItem>- <SupportCounter user={this.props.user} idea={this.props.idea} />+ <SupportCounter idea={this.props.idea} /><div className="idea-header">{this.state.editMode ? (@@ -123,8 +122,8 @@ export class ShowIdeaPage extends React.Component<ShowIdeaPageProps, ShowIdeaPag</div><div className="action-col">- {this.props.user &&- this.props.user.isCollaborator && [+ {Fider.session.isAuthenticated &&+ Fider.session.user.isCollaborator && [<span key={0} className="subtitle">Actions</span>,@@ -155,12 +154,12 @@ export class ShowIdeaPage extends React.Component<ShowIdeaPageProps, ShowIdeaPag)]}- <TagsPanel user={this.props.user} idea={this.props.idea} tags={this.props.tags} />- <NotificationsPanel user={this.props.user} idea={this.props.idea} subscribed={this.props.subscribed} />- <ModerationPanel user={this.props.user} idea={this.props.idea} />+ <TagsPanel idea={this.props.idea} tags={this.props.tags} />+ <NotificationsPanel idea={this.props.idea} subscribed={this.props.subscribed} />+ <ModerationPanel idea={this.props.idea} /></div>- <DiscussionPanel user={this.props.user} idea={this.props.idea} comments={this.props.comments} />+ <DiscussionPanel idea={this.props.idea} comments={this.props.comments} /></div>);}diff --git a/public/pages/ShowIdea/components/CommentInput.tsx b/public/pages/ShowIdea/components/CommentInput.tsxindex c6136a394..158a7d3b1 100644--- a/public/pages/ShowIdea/components/CommentInput.tsx+++ b/public/pages/ShowIdea/components/CommentInput.tsx@@ -5,10 +5,9 @@ import { Idea, CurrentUser } from "@fider/models";import { Gravatar, UserName, Button, DisplayError, SignInControl, TextArea, Form } from "@fider/components/common";import { SignInModal } from "@fider/components";-import { cache, page, actions, Failure } from "@fider/services";+import { cache, actions, Failure } from "@fider/services";interface CommentInputProps {- user?: CurrentUser;idea: Idea;}@@ -27,7 +26,7 @@ export class CommentInput extends React.Component<CommentInputProps, CommentInpusuper(props);this.state = {- content: (!!this.props.user && cache.get(this.getCacheKey())) || "",+ content: (Fider.session.isAuthenticated && cache.get(this.getCacheKey())) || "",showSignIn: false};}@@ -58,7 +57,7 @@ export class CommentInput extends React.Component<CommentInputProps, CommentInpu};private handleOnFocus = () => {- if (!this.props.user) {+ if (!Fider.session.isAuthenticated) {this.input.blur();this.setState({ showSignIn: true });}@@ -72,10 +71,10 @@ export class CommentInput extends React.Component<CommentInputProps, CommentInpureturn (<><SignInModal isOpen={this.state.showSignIn} />- <div className={`c-comment-input ${this.props.user && "m-authenticated"}`}>- {this.props.user && <Gravatar user={this.props.user} />}+ <div className={`c-comment-input ${Fider.session.isAuthenticated && "m-authenticated"}`}>+ {Fider.session.isAuthenticated && <Gravatar user={Fider.session.user} />}<Form error={this.state.error}>- {this.props.user && <UserName user={this.props.user} />}+ {Fider.session.isAuthenticated && <UserName user={Fider.session.user} />}<TextAreaplaceholder="Write a comment..."field="content"diff --git a/public/pages/ShowIdea/components/DiscussionPanel.tsx b/public/pages/ShowIdea/components/DiscussionPanel.tsxindex 45bea97fc..774612f0c 100644--- a/public/pages/ShowIdea/components/DiscussionPanel.tsx+++ b/public/pages/ShowIdea/components/DiscussionPanel.tsx@@ -21,10 +21,8 @@ export class DiscussionPanel extends React.Component<DiscussionPanelProps, {}> {<div className="comments-col"><div className="c-comment-list"><span className="subtitle">Discussion</span>- {this.props.comments.map(c => (- <ShowComment key={c.id} idea={this.props.idea} user={this.props.user} comment={c} />- ))}- <CommentInput user={this.props.user} idea={this.props.idea} />+ {this.props.comments.map(c => <ShowComment key={c.id} idea={this.props.idea} comment={c} />)}+ <CommentInput idea={this.props.idea} /></div></div>);diff --git a/public/pages/ShowIdea/components/ModerationPanel.tsx b/public/pages/ShowIdea/components/ModerationPanel.tsxindex ad7e3beb9..2ebef7c6e 100644--- a/public/pages/ShowIdea/components/ModerationPanel.tsx+++ b/public/pages/ShowIdea/components/ModerationPanel.tsx@@ -1,10 +1,9 @@import * as React from "react";import { IdeaStatus, CurrentUser, Idea } from "@fider/models";-import { page, actions, Failure } from "@fider/services";+import { actions, Failure } from "@fider/services";import { Form, DisplayError, Modal, Button, List, ListItem, TextArea } from "@fider/components";interface ModerationPanelProps {- user?: CurrentUser;idea: Idea;}@@ -29,7 +28,7 @@ export class ModerationPanel extends React.Component<ModerationPanelProps, Moderconst response = await actions.deleteIdea(this.props.idea.number, this.state.text);if (response.ok) {await this.closeModal();- page.goHome();+ actions.goHome();} else if (response.error) {this.setState({ error: this.state.error });}@@ -49,7 +48,7 @@ export class ModerationPanel extends React.Component<ModerationPanelProps, Moderpublic render() {const status = IdeaStatus.Get(this.props.idea.status);- if (!this.props.user || !this.props.user.isAdministrator || status.closed) {+ if (!Fider.session.isAuthenticated || !Fider.session.user.isAdministrator || status.closed) {return null;}diff --git a/public/pages/ShowIdea/components/NotificationsPanel.tsx b/public/pages/ShowIdea/components/NotificationsPanel.tsxindex f91d76c2a..9ebe74703 100644--- a/public/pages/ShowIdea/components/NotificationsPanel.tsx+++ b/public/pages/ShowIdea/components/NotificationsPanel.tsx@@ -4,7 +4,6 @@ import { Button, List, ListItem } from "@fider/components";import { actions } from "@fider/services";interface NotificationsPanelProps {- user: CurrentUser | undefined;idea: Idea;subscribed: boolean;}@@ -31,7 +30,7 @@ export class NotificationsPanel extends React.Component<NotificationsPanelProps,};public render() {- if (!this.props.user) {+ if (!Fider.session.isAuthenticated) {return null;}diff --git a/public/pages/ShowIdea/components/ShowComment.tsx b/public/pages/ShowIdea/components/ShowComment.tsxindex 243429975..b804218cd 100644--- a/public/pages/ShowIdea/components/ShowComment.tsx+++ b/public/pages/ShowIdea/components/ShowComment.tsx@@ -6,7 +6,6 @@ import { formatDate, Failure, actions } from "@fider/services";interface ShowCommentProps {idea: Idea;comment: Comment;- user?: CurrentUser;}interface ShowCommentState {@@ -27,8 +26,8 @@ export class ShowComment extends React.Component<ShowCommentProps, ShowCommentSt}private canEditComment(comment: Comment): boolean {- if (this.props.user) {- return this.props.user.isCollaborator || comment.user.id === this.props.user.id;+ if (Fider.session.isAuthenticated) {+ return Fider.session.user.isCollaborator || comment.user.id === Fider.session.user.id;}return false;}@@ -50,7 +49,7 @@ export class ShowComment extends React.Component<ShowCommentProps, ShowCommentStif (response.ok) {this.state.comment.content = this.state.newContent;this.state.comment.editedOn = new Date().toISOString();- this.state.comment.editedBy = this.props.user;+ this.state.comment.editedBy = Fider.session.user;this.setState({comment: this.state.comment});diff --git a/public/pages/ShowIdea/components/TagsPanel.tsx b/public/pages/ShowIdea/components/TagsPanel.tsxindex 4c8199463..3947d50ad 100644--- a/public/pages/ShowIdea/components/TagsPanel.tsx+++ b/public/pages/ShowIdea/components/TagsPanel.tsx@@ -5,7 +5,6 @@ import { ShowTag, List, ListItem } from "@fider/components";import { TagListItem } from "./TagListItem";interface TagsPanelProps {- user?: CurrentUser;idea: Idea;tags: Tag[];}@@ -20,7 +19,7 @@ export class TagsPanel extends React.Component<TagsPanelProps, TagsPanelState> {constructor(props: TagsPanelProps) {super(props);this.state = {- canEdit: !!this.props.user && this.props.user.isCollaborator && this.props.tags.length > 0,+ canEdit: Fider.session.isAuthenticated && Fider.session.user.isCollaborator && this.props.tags.length > 0,isEditing: false,assignedTags: this.props.tags.filter(t => this.props.idea.tags.indexOf(t.slug) >= 0)};diff --git a/public/pages/SignIn/SignIn.page.tsx b/public/pages/SignIn/SignIn.page.tsxindex 413241f6c..31e7c1fda 100644--- a/public/pages/SignIn/SignIn.page.tsx+++ b/public/pages/SignIn/SignIn.page.tsx@@ -2,19 +2,10 @@ import "./SignIn.page.scss";import * as React from "react";import { SignInControl, Logo, LegalNotice } from "@fider/components";-import { page, notify } from "@fider/services";+import { notify } from "@fider/services";import { Tenant } from "@fider/models";-interface SignInPageProps {- tenant: Tenant;-}--export class SignInPage extends React.Component<SignInPageProps, {}> {- constructor(props: SignInPageProps) {- super(props);- this.state = {};- }-+export class SignInPage extends React.Component<{}, {}> {private onEmailSent = (email: string) => {notify.success(<span>@@ -27,13 +18,13 @@ export class SignInPage extends React.Component<SignInPageProps, {}> {return (<div id="p-signin" className="page container"><div className="message">- <Logo size={100} tenant={this.props.tenant} />+ <Logo size={100} /><p className="welcome">- <strong>{this.props.tenant.name}</strong> is a private space and requires an invitation to join it.+ <strong>{Fider.session.tenant.name}</strong> is a private space and requires an invitation to join it.</p><p>If you have an account or an invitation, you may use following options to sign in.</p></div>- <SignInControl onEmailSent={this.onEmailSent} useEmail={true} redirectTo={page.getBaseUrl()} />+ <SignInControl onEmailSent={this.onEmailSent} useEmail={true} redirectTo={Fider.settings.baseURL} /><LegalNotice /></div>);diff --git a/public/pages/SignUp/SignUp.page.tsx b/public/pages/SignUp/SignUp.page.tsxindex c12a58109..9d0d9601e 100644--- a/public/pages/SignUp/SignUp.page.tsx+++ b/public/pages/SignUp/SignUp.page.tsx@@ -3,9 +3,7 @@ import "./SignUp.page.scss";import * as React from "react";import { SignInControl, Modal, Button, DisplayError, Form, Input, Message, LegalAgreement } from "@fider/components";import { SystemSettings } from "@fider/models";-import { jwt, page, actions, Failure } from "@fider/services";--const logo = require("@fider/assets/images/logo-small.png");+import { jwt, actions, Failure, querystring } from "@fider/services";interface OAuthUser {token: string;@@ -13,10 +11,6 @@ interface OAuthUser {email: string;}-interface SignUpPageProps {- system: SystemSettings;-}-interface SignUpPageState {submitted: boolean;tenantName: string;@@ -31,10 +25,10 @@ interface SignUpPageState {};}-export class SignUpPage extends React.Component<SignUpPageProps, SignUpPageState> {+export class SignUpPage extends React.Component<{}, SignUpPageState> {private user?: OAuthUser;- constructor(props: SignUpPageProps) {+ constructor(props: {}) {super(props);this.state = {submitted: false,@@ -43,7 +37,7 @@ export class SignUpPage extends React.Component<SignUpPageProps, SignUpPageStatesubdomain: { available: false }};- const token = page.getQueryString("token");+ const token = querystring.get("token");if (token) {const data = jwt.decode(token);if (data) {@@ -68,10 +62,10 @@ export class SignUpPage extends React.Component<SignUpPageProps, SignUpPageStateif (result.ok) {if (result.data.token) {- if (page.isSingleHostMode()) {+ if (Fider.isSingleHostMode()) {location.reload();} else {- let baseUrl = `${location.protocol}//${this.state.subdomain.value}${this.props.system.domain}`;+ let baseUrl = `${location.protocol}//${this.state.subdomain.value}${Fider.settings.domain}`;if (location.port) {baseUrl = `${baseUrl}:${location.port}`;}@@ -130,7 +124,7 @@ export class SignUpPage extends React.Component<SignUpPageProps, SignUpPageStatereturn (<div id="p-signup" className="page container">{modal}- <img className="logo" src={logo} />+ <img className="logo" src="https://getfider.com/images/logo-100x100.png" /><h3>1. Who are you?</h3><DisplayError fields={["token"]} error={this.state.error} />@@ -159,13 +153,13 @@ export class SignUpPage extends React.Component<SignUpPageProps, SignUpPageStateonChange={this.setTenantName}placeholder="your company or product name"/>- {!page.isSingleHostMode() && (+ {!Fider.isSingleHostMode() && (<Inputfield="subdomain"maxLength={40}onChange={this.checkAvailability}placeholder="subdomain"- suffix={this.props.system.domain}+ suffix={Fider.settings.domain}>{this.state.subdomain.available && <Message type="success">This subdomain is available!</Message>}{this.state.subdomain.message && <Message type="error">{this.state.subdomain.message}</Message>}diff --git a/public/services/actions/idea.ts b/public/services/actions/idea.tsindex ed6fa1ead..bfbdb0800 100644--- a/public/services/actions/idea.ts+++ b/public/services/actions/idea.ts@@ -1,4 +1,4 @@-import { http, Result, page } from "@fider/services";+import { http, Result, querystring } from "@fider/services";import { Idea } from "@fider/models";export const getAllIdeas = async (): Promise<Result<Idea[]>> => {@@ -14,7 +14,7 @@ export interface SearchIdeasParams {export const searchIdeas = async (params: SearchIdeasParams): Promise<Result<Idea[]>> => {return await http.get<Idea[]>(- `/api/ideas/search${page.toQueryString({+ `/api/ideas/search${querystring.stringify({t: params.tags,q: params.query,f: params.filter,diff --git a/public/services/actions/index.ts b/public/services/actions/index.tsindex 5a997c828..d0524cf3a 100644--- a/public/services/actions/index.ts+++ b/public/services/actions/index.ts@@ -5,3 +5,14 @@ export * from "./tenant";export * from "./notification";export * from "./invite";export { Failure } from "@fider/services/http";++export const goHome = () => {+ window.location.href = "/";+};++export const replaceState = (path: string): void => {+ if (history.replaceState) {+ const newUrl = Fider.settings.baseURL + path;+ window.history.replaceState({ path: newUrl }, "", newUrl);+ }+};diff --git a/public/services/index.ts b/public/services/index.tsindex 448993da2..f6bb9b573 100644--- a/public/services/index.ts+++ b/public/services/index.ts@@ -5,7 +5,7 @@ export * from "./jwt";export * from "./utils";import * as markdown from "./markdown";import * as notify from "./notify";+import * as querystring from "./querystring";import * as device from "./device";-import * as page from "./page";import * as actions from "./actions";-export { actions, page, device, notify, markdown };+export { actions, querystring, device, notify, markdown };diff --git a/public/services/page.ts b/public/services/page.tsdeleted file mode 100644index 53acbb7ea..000000000--- a/public/services/page.ts+++ /dev/null@@ -1,96 +0,0 @@-import { AuthSettings, SystemSettings } from "@fider/models";--export const goHome = (): void => {- document.location.href = "/";-};--export const refresh = (): void => {- document.location.reload();-};--export const getBaseUrl = (): string => {- return (window as any).props.baseURL;-};--export const getAssetsBaseUrl = (): string => {- return (window as any).props.assetsBaseURL;-};--export const getTenantAssetsBaseUrl = (): string => {- return (window as any).props.tenantAssetsBaseURL;-};--export const isSingleHostMode = (): boolean => {- return (window as any).props.system.mode === "single";-};--export const authSettings = (): AuthSettings => {- return (window as any).props.auth;-};--export const systemSettings = (): SystemSettings => {- return (window as any).props.system;-};--export interface ModalOptions {- closable: boolean;-}--export const getQueryStringAsNumber = (name: string): number | undefined => {- return parseInt(getQueryString(name), 10) || undefined;-};--export const getQueryString = (name: string): string => {- const url = window.location.href;- name = name.replace(/[\[\]]/g, "\\$&");- const regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)");- const results = regex.exec(url);-- if (!results || !results[2]) {- return "";- }-- return decodeURIComponent(results[2].replace(/\+/g, " "));-};--export const getQueryStringArray = (name: string): string[] => {- const qs = getQueryString(name);- if (qs) {- return qs.split(",").filter(i => i);- }-- return [];-};--export interface QueryString {- [key: string]: string | string[] | number | undefined;-}--export const toQueryString = (object: QueryString): string => {- if (!object) {- return "";- }-- let qs = "";-- for (const key of Object.keys(object)) {- const symbol = qs ? "&" : "?";- const value = object[key];- if (value instanceof Array) {- if (value.length > 0) {- qs += `${symbol}${key}=${value.join(",")}`;- }- } else if (value) {- qs += `${symbol}${key}=${encodeURIComponent(value.toString()).replace(/%20/g, "+")}`;- }- }-- return qs;-};--export const replaceState = (path: string): void => {- if (history.replaceState) {- const newUrl = getBaseUrl() + path;- window.history.replaceState({ path: newUrl }, "", newUrl);- }-};diff --git a/public/services/querystring.ts b/public/services/querystring.tsnew file mode 100644index 000000000..3868a518d--- /dev/null+++ b/public/services/querystring.ts@@ -0,0 +1,53 @@+import { SystemSettings } from "@fider/models";++export const getNumber = (name: string): number | undefined => {+ return parseInt(get(name), 10) || undefined;+};++export const get = (name: string): string => {+ const url = window.location.href;+ name = name.replace(/[\[\]]/g, "\\$&");+ const regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)");+ const results = regex.exec(url);++ if (!results || !results[2]) {+ return "";+ }++ return decodeURIComponent(results[2].replace(/\+/g, " "));+};++export const getArray = (name: string): string[] => {+ const qs = get(name);+ if (qs) {+ return qs.split(",").filter(i => i);+ }++ return [];+};++export interface QueryString {+ [key: string]: string | string[] | number | undefined;+}++export const stringify = (object: QueryString): string => {+ if (!object) {+ return "";+ }++ let qs = "";++ for (const key of Object.keys(object)) {+ const symbol = qs ? "&" : "?";+ const value = object[key];+ if (value instanceof Array) {+ if (value.length > 0) {+ qs += `${symbol}${key}=${value.join(",")}`;+ }+ } else if (value) {+ qs += `${symbol}${key}=${encodeURIComponent(value.toString()).replace(/%20/g, "+")}`;+ }+ }++ return qs;+};diff --git a/public/tsd.d.ts b/public/tsd.d.tsindex 1d8283044..11be9982e 100644--- a/public/tsd.d.ts+++ b/public/tsd.d.ts@@ -1,18 +1,17 @@import { CurrentUser, SystemSettings, Tenant } from "@fider/models";--interface PageProps {- user?: CurrentUser;- system: SystemSettings;- tenant: Tenant;- [key: string]: any;-}+import { Fider } from "./fider";declare global {interface Window {ga?: (cmd: string, evt: string, args?: any) => void;- props: PageProps;set: (key: string, value: any) => void;+ __props: { [key: string]: any };+ __user: CurrentUser | undefined;+ __tenant: Tenant;+ __settings: SystemSettings;}++ var Fider: Fider;}declare var require: (id: string) => any;diff --git a/tsconfig.json b/tsconfig.jsonindex 45e821d25..62024e501 100755--- a/tsconfig.json+++ b/tsconfig.json@@ -17,6 +17,8 @@"experimentalDecorators": true,"emitDecoratorMetadata": true,"baseUrl": "./public",+ "importHelpers": true,+ "noEmitHelpers": true,"paths": {"@fider/*": ["*"diff --git a/views/403.html b/views/403.htmlindex f652c2181..ac251a563 100644--- a/views/403.html+++ b/views/403.html@@ -8,8 +8,8 @@You are not authorized to view this page.</p>- {{ if .tenant }}- <span>Take me back to <a href="{{ .baseURL }}">{{ .baseURL }}</a> home page.</span>+ {{ if .__tenant }}+ <span>Take me back to <a href="{{ .__settings.baseURL }}">{{ .__settings.baseURL }}</a> home page.</span>{{ end }}</div>{{end}}\ No newline at end of filediff --git a/views/404.html b/views/404.htmlindex a0a1836cc..d984e72e0 100644--- a/views/404.html+++ b/views/404.html@@ -9,8 +9,8 @@the page may have been removed.</p>- {{ if .tenant }}- <span>Take me back to <a href="{{ .baseURL }}">{{ .baseURL }}</a> home page.</span>+ {{ if .__tenant }}+ <span>Take me back to <a href="{{ .__settings.baseURL }}">{{ .__settings.baseURL }}</a> home page.</span>{{ end }}</div>{{end}}\ No newline at end of filediff --git a/views/410.html b/views/410.htmlindex 58cbf0028..b9c081823 100644--- a/views/410.html+++ b/views/410.html@@ -6,8 +6,8 @@<h1>EXPIRED</h1><p>The link you clicked has expired.</p>- {{ if .tenant }}- <span>Take me back to <a href="{{ .baseURL }}">{{ .baseURL }}</a> home page.</span>+ {{ if .__tenant }}+ <span>Take me back to <a href="{{ .__settings.baseURL }}">{{ .__settings.baseURL }}</a> home page.</span>{{ end }}</div>{{end}}\ No newline at end of filediff --git a/views/500.html b/views/500.htmlindex aba479695..56ed858ed 100644--- a/views/500.html+++ b/views/500.html@@ -6,8 +6,8 @@<h1>Shoot! Well, this is unexpected…</h1><p>An error has occurred and we're working to fix the problem! </br> We’ll be up and running shortly.</p>- {{ if .tenant }}- <span>Take me back to <a href="{{ .baseURL }}">{{ .baseURL }}</a> home page.</span>+ {{ if .__tenant }}+ <span>Take me back to <a href="{{ .__settings.baseURL }}">{{ .__settings.baseURL }}</a> home page.</span>{{ end }}</div>{{end}}\ No newline at end of filediff --git a/views/base.html b/views/base.htmlindex 5cc18061a..a3d72f6a5 100644--- a/views/base.html+++ b/views/base.html@@ -4,18 +4,18 @@<meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"><link rel="icon" type="image/x-icon" href="{{ .__favicon }}">- <link rel="preload" href="{{ .__FontBundle }}" as="font" type="font/woff2" crossorigin="anonymous">- <link rel="stylesheet" href="{{ .__StyleBundle }}" />- <title>{{ .__Title }}</title>- <meta name="description" content="{{ .__Description }}" />- <meta property="og:title" content="{{ .__Title }}" />- <meta property="og:description" content="{{ .__Description }}" />+ <link rel="preload" href="{{ .__fontBundle }}" as="font" type="font/woff2" crossorigin="anonymous">+ <link rel="stylesheet" href="{{ .__cssBundle }}" />+ <title>{{ .__title }}</title>+ <meta name="description" content="{{ .__description }}" />+ <meta property="og:title" content="{{ .__title }}" />+ <meta property="og:description" content="{{ .__description }}" /><meta property="og:type" content="website" />- <meta property="og:url" content="{{ .currentURL }}" />+ <meta property="og:url" content="{{ .__currentURL }}" /><meta property="og:image" content="{{ .__logo }}">- {{ if .tenant }}- {{ if .tenant.CustomCSS }}- <link rel="stylesheet" href="{{ .tenantAssetsBaseURL }}/custom/{{ .tenant.CustomCSS | md5 }}.css" />+ {{ if .__tenant }}+ {{ if .__tenant.CustomCSS }}+ <link rel="stylesheet" href="{{ .__settings.assetsURL }}/custom/{{ .__tenant.CustomCSS | md5 }}.css" />{{ end }}{{ end }}</head>@@ -28,15 +28,15 @@</div></noscript>- {{ if ne .system.GoogleAnalytics "" }}- <script type="text/javascript" nonce="{{ .__ContextID }}">+ {{ if ne .__settings.googleAnalytics "" }}+ <script type="text/javascript" nonce="{{ .__contextID }}">(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');- ga('create', '{{ .system.GoogleAnalytics }}', 'auto');- {{ if .tenant }}ga('set', 'dimension1', '{{ .tenant.Subdomain }}');{{ end }}+ ga('create', '{{ .__settings.googleAnalytics }}', 'auto');+ {{ if .__tenant }}ga('set', 'dimension1', '{{ .__tenant.Subdomain }}');{{ end }}ga('send', 'pageview');</script>{{ end }}@@ -44,9 +44,9 @@{{template "content" .}}<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=default,fetch"></script>- <script src="{{ .__VendorBundle }}"></script>- <script src="{{ .__JavaScriptBundle }}"></script>- <script type="text/javascript" nonce="{{ .__ContextID }}">+ <script src="{{ .__vendorBundle }}"></script>+ <script src="{{ .__jsBundle }}"></script>+ <script type="text/javascript" nonce="{{ .__contextID }}">{{template "javascript" .}}</script></body>diff --git a/views/index.html b/views/index.htmlindex 67deaa2e9..7267af891 100644--- a/views/index.html+++ b/views/index.html@@ -1,6 +1,11 @@// Print all variables that does not start with _ (95)// Compressed to avoid whitespace being printed--{{define "javascript"}} {{ range $key, $value := . }}{{ $first := index $key 1 }}{{ if ne $first 95 }}set({{ $key }}, {{ $value }});{{ end }}{{ end }} {{end}}+{{define "javascript"}}+ {{ if .__user }}window.__user = {{ .__user }};{{ end }}+ window.__settings = {{ .__settings }};+ window.__tenant = {{ .__tenant }};+ window.__props = {};+{{ range $key, $value := . }}{{ $first := index $key 1 }}{{ if ne $first 95 }}+ window.__props['{{ $key }}'] = {{ $value }};{{ end }}{{ end }} {{end}}{{define "content"}}<div id="root"></div><div id="root-modal"></div>{{end}}\ No newline at end of filediff --git a/views/not-invited.html b/views/not-invited.htmlindex 46d7af729..ec353b6c1 100644--- a/views/not-invited.html+++ b/views/not-invited.html@@ -12,8 +12,8 @@ Not Invited · FiderWe couldn't find your account for your email address.</p>- {{ if .tenant }}- <span>Take me back to <a href="{{ .baseURL }}/signin">{{ .baseURL }}/signin</a>.</span>+ {{ if .__tenant }}+ <span>Take me back to <a href="{{ .__settings.baseURL }}/signin">{{ .__settings.baseURL }}/signin</a>.</span>{{ end }}</div>{{end}}\ No newline at end of filediff --git a/webpack.config.js b/webpack.config.jsindex 935f5c4ec..0387c5142 100755--- a/webpack.config.js+++ b/webpack.config.js@@ -20,7 +20,7 @@ module.exports = {mode: process.env.NODE_ENV || "development",entry: {main: "./public/index.tsx",- vendor: [ "react", "react-dom", "semantic-ui-react" ]+ vendor: [ "react", "react-dom", "semantic-ui-react", "tslib" ]},output: {path: __dirname + "/dist",