Open platform to collect and prioritize feedback
feature: configurable locale (#975)
Guilherme Oenningbf08c9cd1982
diff --git a/app/actions/tenant.go b/app/actions/tenant.goindex c7a96d8d5..690271a7c 100644--- a/app/actions/tenant.go+++ b/app/actions/tenant.go@@ -8,6 +8,7 @@ import ("github.com/getfider/fider/app/models/entity""github.com/getfider/fider/app/models/enum""github.com/getfider/fider/app/pkg/env"+ "github.com/getfider/fider/app/pkg/i18n""github.com/getfider/fider/app/pkg/jwt""github.com/getfider/fider/app/pkg/validate")@@ -112,6 +113,7 @@ type UpdateTenantSettings struct {Title string `json:"title"`Invitation string `json:"invitation"`WelcomeMessage string `json:"welcomeMessage"`+ Locale string `json:"locale"`CNAME string `json:"cname" format:"lower"`}@@ -159,6 +161,10 @@ func (action *UpdateTenantSettings) Validate(ctx context.Context, user *entity.Uresult.AddFieldFailure("invitation", "Invitation must have less than 60 characters.")}+ if !i18n.IsValidLocale(action.Locale) {+ result.AddFieldFailure("locale", "Locale is invalid.")+ }+if action.CNAME != "" {messages := validate.CNAME(ctx, action.CNAME)result.AddFieldFailure("cname", messages...)diff --git a/app/actions/tenant_test.go b/app/actions/tenant_test.goindex d3f61daaa..979d24d50 100644--- a/app/actions/tenant_test.go+++ b/app/actions/tenant_test.go@@ -128,7 +128,7 @@ func TestUpdateTenantSettings_Unauthorized(t *testing.T) {func TestUpdateTenantSettings_EmptyTitle(t *testing.T) {RegisterT(t)- action := actions.NewUpdateTenantSettings()+ action := actions.UpdateTenantSettings{Locale: "en"}result := action.Validate(context.Background(), nil)ExpectFailed(result, "title")}@@ -136,7 +136,7 @@ func TestUpdateTenantSettings_EmptyTitle(t *testing.T) {func TestUpdateTenantSettings_InvalidCNAME(t *testing.T) {RegisterT(t)- action := actions.UpdateTenantSettings{Title: "Ok", CNAME: "bla"}+ action := actions.UpdateTenantSettings{Title: "Ok", CNAME: "bla", Locale: "en"}result := action.Validate(context.Background(), nil)ExpectFailed(result, "cname")}@@ -144,7 +144,7 @@ func TestUpdateTenantSettings_InvalidCNAME(t *testing.T) {func TestUpdateTenantSettings_LargeTitle(t *testing.T) {RegisterT(t)- action := actions.UpdateTenantSettings{Title: "123456789012345678901234567890123456789012345678901234567890123"}+ action := actions.UpdateTenantSettings{Title: "123456789012345678901234567890123456789012345678901234567890123", Locale: "en"}result := action.Validate(context.Background(), nil)ExpectFailed(result, "title")}@@ -152,11 +152,19 @@ func TestUpdateTenantSettings_LargeTitle(t *testing.T) {func TestUpdateTenantSettings_LargeInvitation(t *testing.T) {RegisterT(t)- action := actions.UpdateTenantSettings{Title: "Ok", Invitation: "123456789012345678901234567890123456789012345678901234567890123"}+ action := actions.UpdateTenantSettings{Title: "Ok", Invitation: "123456789012345678901234567890123456789012345678901234567890123", Locale: "en"}result := action.Validate(context.Background(), nil)ExpectFailed(result, "invitation")}+func TestUpdateTenantSettings_InvalidLocale(t *testing.T) {+ RegisterT(t)++ action := actions.UpdateTenantSettings{Title: "Some Name", Locale: "xx"}+ result := action.Validate(context.Background(), nil)+ ExpectFailed(result, "locale")+}+func TestUpdateTenantSettings_ExistingTenant_WithLogo(t *testing.T) {RegisterT(t)@@ -168,6 +176,7 @@ func TestUpdateTenantSettings_ExistingTenant_WithLogo(t *testing.T) {action := actions.NewUpdateTenantSettings()action.Title = "OK"action.Invitation = "Share your ideas!"+ action.Locale = "en"result := action.Validate(ctx, nil)ExpectSuccess(result)Expect(action.Logo.BlobKey).Equals("hello-world.png")diff --git a/app/handlers/admin.go b/app/handlers/admin.goindex f844204f4..73e4031d2 100644--- a/app/handlers/admin.go+++ b/app/handlers/admin.go@@ -50,6 +50,7 @@ func UpdateSettings() web.HandlerFunc {Invitation: action.Invitation,WelcomeMessage: action.WelcomeMessage,CNAME: action.CNAME,+ Locale: action.Locale,},); err != nil {return c.Failure(err)diff --git a/app/handlers/admin_test.go b/app/handlers/admin_test.goindex 9d6de8d9f..811a6a714 100644--- a/app/handlers/admin_test.go+++ b/app/handlers/admin_test.go@@ -40,13 +40,14 @@ func TestUpdateSettingsHandler(t *testing.T) {AsUser(mock.JonSnow).ExecutePost(handlers.UpdateSettings(),- `{ "title": "GoT", "invitation": "Join us!", "welcomeMessage": "Welcome to GoT Feedback Forum" }`,+ `{ "title": "GoT", "invitation": "Join us!", "welcomeMessage": "Welcome to GoT Feedback Forum", "locale": "pt-BR" }`,)Expect(code).Equals(http.StatusOK)Expect(updateCmd.Title).Equals("GoT")Expect(updateCmd.Invitation).Equals("Join us!")Expect(updateCmd.WelcomeMessage).Equals("Welcome to GoT Feedback Forum")+ Expect(updateCmd.Locale).Equals("pt-BR")Expect(updateCmd.Logo.BlobKey).Equals("logos/hello-world.png")}@@ -77,6 +78,7 @@ func TestUpdateSettingsHandler_NewLogo(t *testing.T) {"title": "GoT","invitation": "Join us!","welcomeMessage": "Welcome to GoT Feedback Forum",+ "locale": "pt-BR","logo": {"upload": {"fileName": "picture.png",@@ -90,6 +92,7 @@ func TestUpdateSettingsHandler_NewLogo(t *testing.T) {Expect(updateCmd.Title).Equals("GoT")Expect(updateCmd.Invitation).Equals("Join us!")Expect(updateCmd.WelcomeMessage).Equals("Welcome to GoT Feedback Forum")+ Expect(updateCmd.Locale).Equals("pt-BR")Expect(updateCmd.Logo.BlobKey).Equals("logos/picture.png")}@@ -116,6 +119,7 @@ func TestUpdateSettingsHandler_RemoveLogo(t *testing.T) {handlers.UpdateSettings(), `{"title": "GoT","invitation": "Join us!",+ "locale": "en","welcomeMessage": "Welcome to GoT Feedback Forum","logo": {"remove": true@@ -127,6 +131,7 @@ func TestUpdateSettingsHandler_RemoveLogo(t *testing.T) {Expect(updateCmd.Invitation).Equals("Join us!")Expect(updateCmd.WelcomeMessage).Equals("Welcome to GoT Feedback Forum")Expect(updateCmd.Logo.Remove).IsTrue()+ Expect(updateCmd.Locale).Equals("en")}func TestUpdatePrivacyHandler(t *testing.T) {diff --git a/app/models/cmd/tenant.go b/app/models/cmd/tenant.goindex e3d6fb7b4..24b24fed1 100644--- a/app/models/cmd/tenant.go+++ b/app/models/cmd/tenant.go@@ -26,6 +26,7 @@ type UpdateTenantSettings struct {Invitation stringWelcomeMessage stringCNAME string+ Locale string}type UpdateTenantAdvancedSettings struct {diff --git a/app/models/entity/tenant.go b/app/models/entity/tenant.goindex a10843c6b..fe1ab04ac 100644--- a/app/models/entity/tenant.go+++ b/app/models/entity/tenant.go@@ -9,6 +9,7 @@ type Tenant struct {WelcomeMessage string `json:"welcomeMessage"`CNAME string `json:"cname"`Status int `json:"status"`+ Locale string `json:"locale"`IsPrivate bool `json:"isPrivate"`LogoBlobKey string `json:"logoBlobKey"`CustomCSS string `json:"-"`diff --git a/app/pkg/dbx/setup.sql b/app/pkg/dbx/setup.sqlindex f118bcce3..1a21fddf8 100644--- a/app/pkg/dbx/setup.sql+++ b/app/pkg/dbx/setup.sql@@ -2,8 +2,8 @@ TRUNCATE TABLE blobs RESTART IDENTITY CASCADE;TRUNCATE TABLE logs RESTART IDENTITY CASCADE;TRUNCATE TABLE tenants RESTART IDENTITY CASCADE;-INSERT INTO tenants (name, subdomain, created_at, cname, invitation, welcome_message, status, is_private, custom_css, logo_bkey)-VALUES ('Demonstration', 'demo', now(), '', '', '', 1, false, '', '');+INSERT INTO tenants (name, subdomain, created_at, cname, invitation, welcome_message, status, is_private, custom_css, logo_bkey, locale)+VALUES ('Demonstration', 'demo', now(), '', '', '', 1, false, '', '', 'en');INSERT INTO users (name, email, tenant_id, created_at, role, status, avatar_type, avatar_bkey)VALUES ('Jon Snow', '[email protected]', 1, now(), 3, 1, 2, '');@@ -18,8 +18,8 @@ VALUES (2, 1, 'google', 'GO5678', now());INSERT INTO users (name, email, tenant_id, created_at, role, status, avatar_type, avatar_bkey)VALUES ('Sansa Stark', '[email protected]', 1, now(), 1, 1, 2, '');-INSERT INTO tenants (name, subdomain, created_at, cname, invitation, welcome_message, status, is_private, custom_css, logo_bkey)-VALUES ('Avengers', 'avengers', now(), 'feedback.avengers.com', '', '', 1, false, '', '');+INSERT INTO tenants (name, subdomain, created_at, cname, invitation, welcome_message, status, is_private, custom_css, logo_bkey, locale)+VALUES ('Avengers', 'avengers', now(), 'feedback.avengers.com', '', '', 1, false, '', '', 'en');INSERT INTO users (name, email, tenant_id, created_at, role, status, avatar_type, avatar_bkey)VALUES ('Tony Stark', '[email protected]', 2, now(), 3, 1, 2, '');diff --git a/app/pkg/i18n/i18n.go b/app/pkg/i18n/i18n.goindex 8dc688d0b..39d9a6291 100644--- a/app/pkg/i18n/i18n.go+++ b/app/pkg/i18n/i18n.go@@ -15,7 +15,7 @@ import (// localeToPlurals maps between Fider locale and gotnospirit/messageformat culturevar localeToPlurals = map[string]string{- "en": "en",+ "en": "en","pt-BR": "pt",}@@ -24,6 +24,7 @@ type Params map[string]interface{}// cache for locale parser and file content to prevent excessive disk IOvar cache = make(map[string]localeData)var mu sync.RWMutex+type localeData struct {file map[string]stringparser *messageformat.Parser@@ -83,15 +84,28 @@ func getMessage(locale, key string) (string, *messageformat.Parser) {return fmt.Sprintf("⚠️ Missing Translation: %s", key), enData.parser}-// T translates a given key to current context locale-// If Locale is not set in context, the environment locale is used-// Params is used to replace variables and pluralize-func T(ctx context.Context, key string, params ...Params) string {+// IsValidLocale returns true if given locale is valid+func IsValidLocale(locale string) bool {+ if _, ok := localeToPlurals[locale]; ok {+ return true+ }+ return false+}++// GetLocale returns the locale defined in context+// If it is not defined, the environment locale is used+func GetLocale(ctx context.Context) string {locale, ok := ctx.Value(app.LocaleCtxKey).(string)- if !ok {- locale = env.Config.Locale+ if ok && locale != "" {+ return locale}+ return env.Config.Locale+}+// T translates a given key to current locale+// Params is used to replace variables and pluralize+func T(ctx context.Context, key string, params ...Params) string {+ locale := GetLocale(ctx)msg, parser := getMessage(locale, key)if len(params) == 0 {return msgdiff --git a/app/pkg/i18n/i18n_test.go b/app/pkg/i18n/i18n_test.goindex eeed1f556..a115cc358 100644--- a/app/pkg/i18n/i18n_test.go+++ b/app/pkg/i18n/i18n_test.go@@ -57,4 +57,27 @@ func TestEnglish_InvalidMessage(t *testing.T) {translated = i18n.T(ptBRContext, key)Expect(translated).Equals("⚠️ Missing Translation: This message does not exist")-}\ No newline at end of file+}++func TestGetLocale(t *testing.T) {+ RegisterT(t)++ Expect(i18n.GetLocale(emptyContext)).Equals("en")+ Expect(i18n.GetLocale(enContext)).Equals("en")+ Expect(i18n.GetLocale(ptBRContext)).Equals("pt-BR")+}++func TestIsValidLocale(t *testing.T) {+ RegisterT(t)++ //Valid locales+ Expect(i18n.IsValidLocale("en")).IsTrue()+ Expect(i18n.IsValidLocale("pt-BR")).IsTrue()++ //Invalid locales+ Expect(i18n.IsValidLocale("EN")).IsFalse()+ Expect(i18n.IsValidLocale("PT-BR")).IsFalse()+ Expect(i18n.IsValidLocale("pt_BR")).IsFalse()+ Expect(i18n.IsValidLocale("")).IsFalse()+ Expect(i18n.IsValidLocale("xx")).IsFalse()+}diff --git a/app/pkg/mock/worker.go b/app/pkg/mock/worker.goindex 9eef4a092..2fd37f015 100644--- a/app/pkg/mock/worker.go+++ b/app/pkg/mock/worker.go@@ -49,6 +49,7 @@ func (w *Worker) Execute(task worker.Task) error {if w.tenant != nil {task.OriginContext = context.WithValue(task.OriginContext, app.TenantCtxKey, w.tenant)+ task.OriginContext = context.WithValue(task.OriginContext, app.LocaleCtxKey, w.tenant.Locale)}u, _ := url.Parse(w.baseURL)diff --git a/app/pkg/web/context.go b/app/pkg/web/context.goindex 186cecb30..ee0211807 100644--- a/app/pkg/web/context.go+++ b/app/pkg/web/context.go@@ -165,7 +165,8 @@ func (c *Context) Tenant() *entity.Tenant {//SetTenant update HTTP context with current tenantfunc (c *Context) SetTenant(tenant *entity.Tenant) {if tenant != nil {- c.Context = log.WithProperty(c.Context, log.PropertyKeyTenantID, tenant.ID)+ c.Set(log.PropertyKeyTenantID, tenant.ID)+ c.Set(app.LocaleCtxKey, tenant.Locale)}c.Set(app.TenantCtxKey, tenant)}diff --git a/app/pkg/web/react_test.go b/app/pkg/web/react_test.goindex 365ec86b8..3c28af69d 100644--- a/app/pkg/web/react_test.go+++ b/app/pkg/web/react_test.go@@ -38,7 +38,9 @@ func TestReactRenderer_RenderEmptyHomeHTML(t *testing.T) {u, _ := url.Parse("https://demo.test.fider.io")html, err := r.Render(u, web.Map{- "tenant": &entity.Tenant{},+ "tenant": &entity.Tenant{+ Locale: "en",+ },"settings": web.Map{"locale": "en",},@@ -64,7 +66,9 @@ func TestReactRenderer_RenderEmptyHomeHTML_Portuguese(t *testing.T) {u, _ := url.Parse("https://demo.test.fider.io")html, err := r.Render(u, web.Map{- "tenant": &entity.Tenant{},+ "tenant": &entity.Tenant{+ Locale: "pt-BR",+ },"settings": web.Map{"locale": "pt-BR",},diff --git a/app/pkg/web/renderer.go b/app/pkg/web/renderer.goindex dfcc246cd..b354bc12f 100644--- a/app/pkg/web/renderer.go+++ b/app/pkg/web/renderer.go@@ -13,6 +13,7 @@ import ("github.com/getfider/fider/app/models/query""github.com/getfider/fider/app/pkg/bus"+ "github.com/getfider/fider/app/pkg/i18n""github.com/getfider/fider/app/pkg/log""github.com/getfider/fider/app/pkg/tpl"@@ -200,7 +201,7 @@ func (r *Renderer) Render(w io.Writer, statusCode int, templateName string, proppublic["props"] = props.Datapublic["settings"] = &Map{"mode": env.Config.HostMode,- "locale": env.Config.Locale,+ "locale": i18n.GetLocale(ctx),"environment": env.Config.Environment,"googleAnalytics": env.Config.GoogleAnalytics,"domain": env.MultiTenantDomain(),diff --git a/app/pkg/web/renderer_test.go b/app/pkg/web/renderer_test.goindex bfd0a099c..99df7a030 100644--- a/app/pkg/web/renderer_test.go+++ b/app/pkg/web/renderer_test.go@@ -120,7 +120,9 @@ func TestRenderer_Home_SSR(t *testing.T) {ctx := newGetContext("https://demo.test.fider.io:3000/", map[string]string{"User-Agent": "Googlebot",})- ctx.SetTenant(&entity.Tenant{})+ ctx.SetTenant(&entity.Tenant{+ Locale: "en",+ })renderer := web.NewRenderer()renderer.Render(buf, http.StatusOK, "index.html", web.Props{Title: "My Page Title",diff --git a/app/pkg/web/testdata/tenant.html b/app/pkg/web/testdata/tenant.htmlindex 55dd283d8..d8cb39560 100755--- a/app/pkg/web/testdata/tenant.html+++ b/app/pkg/web/testdata/tenant.html@@ -44,7 +44,7 @@<script id="server-data" type="application/json">- {"contextID":"CONTEXT_ID","props":{},"sessionID":"","settings":{"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"locale":"en","mode":"multi","oauth":[]},"tenant":{"id":0,"name":"Game of Thrones","subdomain":"","invitation":"","welcomeMessage":"","cname":"","status":0,"isPrivate":false,"logoBlobKey":""},"title":"Game of Thrones"}+ {"contextID":"CONTEXT_ID","props":{},"sessionID":"","settings":{"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"locale":"en","mode":"multi","oauth":[]},"tenant":{"id":0,"name":"Game of Thrones","subdomain":"","invitation":"","welcomeMessage":"","cname":"","status":0,"locale":"","isPrivate":false,"logoBlobKey":""},"title":"Game of Thrones"}</script>diff --git a/app/pkg/worker/context.go b/app/pkg/worker/context.goindex 2826f81bf..98a17ffc2 100644--- a/app/pkg/worker/context.go+++ b/app/pkg/worker/context.go@@ -25,6 +25,7 @@ func NewContext(ctx context.Context, workerID string, task Task) *Context {if task.OriginContext != nil {ctx = context.WithValue(ctx, app.RequestCtxKey, task.OriginContext.Value(app.RequestCtxKey))ctx = context.WithValue(ctx, app.TenantCtxKey, task.OriginContext.Value(app.TenantCtxKey))+ ctx = context.WithValue(ctx, app.LocaleCtxKey, task.OriginContext.Value(app.LocaleCtxKey))ctx = context.WithValue(ctx, app.UserCtxKey, task.OriginContext.Value(app.UserCtxKey))ctx = log.WithProperties(ctx, dto.Props{diff --git a/app/services/sqlstore/postgres/tenant.go b/app/services/sqlstore/postgres/tenant.goindex b02350d50..24acd5499 100644--- a/app/services/sqlstore/postgres/tenant.go+++ b/app/services/sqlstore/postgres/tenant.go@@ -24,6 +24,7 @@ type dbTenant struct {Invitation string `db:"invitation"`WelcomeMessage string `db:"welcome_message"`Status int `db:"status"`+ Locale string `db:"locale"`IsPrivate bool `db:"is_private"`LogoBlobKey string `db:"logo_bkey"`CustomCSS string `db:"custom_css"`@@ -42,6 +43,7 @@ func (t *dbTenant) toModel() *entity.Tenant {Invitation: t.Invitation,WelcomeMessage: t.WelcomeMessage,Status: t.Status,+ Locale: t.Locale,IsPrivate: t.IsPrivate,LogoBlobKey: t.LogoBlobKey,CustomCSS: t.CustomCSS,@@ -129,8 +131,8 @@ func updateTenantSettings(ctx context.Context, c *cmd.UpdateTenantSettings) erroc.Logo.BlobKey = ""}- query := "UPDATE tenants SET name = $1, invitation = $2, welcome_message = $3, cname = $4, logo_bkey = $5 WHERE id = $6"- _, err := trx.Execute(query, c.Title, c.Invitation, c.WelcomeMessage, c.CNAME, c.Logo.BlobKey, tenant.ID)+ query := "UPDATE tenants SET name = $1, invitation = $2, welcome_message = $3, cname = $4, logo_bkey = $5, locale = $6 WHERE id = $7"+ _, err := trx.Execute(query, c.Title, c.Invitation, c.WelcomeMessage, c.CNAME, c.Logo.BlobKey, c.Locale, tenant.ID)if err != nil {return errors.Wrap(err, "failed update tenant settings")}@@ -216,9 +218,9 @@ func createTenant(ctx context.Context, c *cmd.CreateTenant) error {var id interr := trx.Get(&id,- `INSERT INTO tenants (name, subdomain, created_at, cname, invitation, welcome_message, status, is_private, custom_css, logo_bkey)- VALUES ($1, $2, $3, '', '', '', $4, false, '', '')- RETURNING id`, c.Name, c.Subdomain, now, c.Status)+ `INSERT INTO tenants (name, subdomain, created_at, cname, invitation, welcome_message, status, is_private, custom_css, logo_bkey, locale)+ VALUES ($1, $2, $3, '', '', '', $4, false, '', '', $5)+ RETURNING id`, c.Name, c.Subdomain, now, c.Status, env.Config.Locale)if err != nil {return err}@@ -235,7 +237,7 @@ func getFirstTenant(ctx context.Context, q *query.GetFirstTenant) error {tenant := dbTenant{}err := trx.Get(&tenant, `- SELECT id, name, subdomain, cname, invitation, welcome_message, status, is_private, logo_bkey, custom_css+ SELECT id, name, subdomain, cname, invitation, locale, welcome_message, status, is_private, logo_bkey, custom_cssFROM tenantsORDER BY id LIMIT 1`)@@ -254,7 +256,7 @@ func getTenantByDomain(ctx context.Context, q *query.GetTenantByDomain) error {tenant := dbTenant{}err := trx.Get(&tenant, `- SELECT id, name, subdomain, cname, invitation, welcome_message, status, is_private, logo_bkey, custom_css+ SELECT id, name, subdomain, cname, invitation, locale, welcome_message, status, is_private, logo_bkey, custom_cssFROM tenants tWHERE subdomain = $1 OR subdomain = $2 OR cname = $3ORDER BY cname DESCdiff --git a/app/services/sqlstore/postgres/tenant_test.go b/app/services/sqlstore/postgres/tenant_test.goindex 3458c4928..db71668c1 100644--- a/app/services/sqlstore/postgres/tenant_test.go+++ b/app/services/sqlstore/postgres/tenant_test.go@@ -200,6 +200,7 @@ func TestTenantStorage_UpdateSettings(t *testing.T) {Title: "New Demonstration",Invitation: "Leave us your suggestion",WelcomeMessage: "Welcome!",+ Locale: "pt-BR",CNAME: "demo.company.com",})Expect(err).IsNil()@@ -212,6 +213,7 @@ func TestTenantStorage_UpdateSettings(t *testing.T) {Expect(getByDomain.Result.Invitation).Equals("Leave us your suggestion")Expect(getByDomain.Result.WelcomeMessage).Equals("Welcome!")Expect(getByDomain.Result.CNAME).Equals("demo.company.com")+ Expect(getByDomain.Result.Locale).Equals("pt-BR")Expect(getByDomain.Result.LogoBlobKey).Equals("some-logo-key.png")}diff --git a/app/services/sqlstore/postgres/user_test.go b/app/services/sqlstore/postgres/user_test.goindex 4e8b846f5..860ce1ddc 100644--- a/app/services/sqlstore/postgres/user_test.go+++ b/app/services/sqlstore/postgres/user_test.go@@ -159,8 +159,8 @@ func TestUserStorage_Register_MultipleProviders(t *testing.T) {var tenantID interr := trx.Get(&tenantID, `- INSERT INTO tenants (name, subdomain, created_at, status, is_private, custom_css, logo_bkey)- VALUES ('My Domain Inc.','mydomain', now(), 1, false, '', '')+ INSERT INTO tenants (name, subdomain, created_at, status, is_private, custom_css, logo_bkey, locale)+ VALUES ('My Domain Inc.','mydomain', now(), 1, false, '', '', 'en')RETURNING id`)Expect(err).IsNil()diff --git a/locale/locales.ts b/locale/locales.tsnew file mode 100644index 000000000..18cadc1a9--- /dev/null+++ b/locale/locales.ts@@ -0,0 +1,16 @@+interface Locale {+ text: string+ translated?: number+}++const locales: { [key: string]: Locale } = {+ en: {+ text: "🇺🇸 English",+ },+ "pt-BR": {+ text: "🇧🇷 Portuguese (Brazilian)",+ translated: 100,+ },+}++export default localesdiff --git a/migrations/202107031320_add_locale_field.sql b/migrations/202107031320_add_locale_field.sqlnew file mode 100644index 000000000..fb64ae2d7--- /dev/null+++ b/migrations/202107031320_add_locale_field.sql@@ -0,0 +1,3 @@+ALTER TABLE tenants ADD locale VARCHAR(10) NULL;+UPDATE tenants SET locale = 'en';+ALTER TABLE tenants ALTER COLUMN locale SET NOT NULL;\ No newline at end of filediff --git a/public/index.tsx b/public/index.tsxindex f7c90a9a8..fc91b21ce 100644--- a/public/index.tsx+++ b/public/index.tsx@@ -60,4 +60,4 @@ const bootstrapApp = (i18n: I18n) => {const fider = Fider.initialize()__webpack_nonce__ = fider.session.contextID__webpack_public_path__ = `${fider.settings.assetsURL}/assets/`-activateI18N(fider.settings.locale).then(bootstrapApp).catch(bootstrapApp)+activateI18N(fider.currentLocale).then(bootstrapApp).catch(bootstrapApp)diff --git a/public/models/identity.ts b/public/models/identity.tsindex ef109465e..b18da5a86 100644--- a/public/models/identity.ts+++ b/public/models/identity.ts@@ -3,6 +3,7 @@ export interface Tenant {name: stringcname: stringsubdomain: string+ locale: stringinvitation: stringwelcomeMessage: stringstatus: TenantStatusdiff --git a/public/pages/Administration/components/AdminBasePage.tsx b/public/pages/Administration/components/AdminBasePage.tsxindex 72272aa4a..cc943c14d 100644--- a/public/pages/Administration/components/AdminBasePage.tsx+++ b/public/pages/Administration/components/AdminBasePage.tsx@@ -5,6 +5,30 @@ import { PageTitle } from "@fider/components"import { SideMenu, SideMenuToggler } from "./SideMenu"import { HStack } from "@fider/components/layout"+interface AdminPageContainerProps {+ id: string+ name: string+ title: string+ subtitle: string+ children: React.ReactNode+}++export const AdminPageContainer = (props: AdminPageContainerProps) => {+ return (+ <div id={props.id} className="page container">+ <HStack justify="between">+ <PageTitle title={props.title} subtitle={props.subtitle} />+ <SideMenuToggler />+ </HStack>++ <div className="c-admin-basepage">+ <SideMenu activeItem={props.name} />+ <div>{props.children}</div>+ </div>+ </div>+ )+}+export abstract class AdminBasePage<P, S> extends React.Component<P, S> {public abstract id: stringpublic abstract name: string@@ -14,17 +38,9 @@ export abstract class AdminBasePage<P, S> extends React.Component<P, S> {public render() {return (- <div id={this.id} className="page container">- <HStack justify="between">- <PageTitle title={this.title} subtitle={this.subtitle} />- <SideMenuToggler />- </HStack>-- <div className="c-admin-basepage">- <SideMenu activeItem={this.name} />- <div>{this.content()}</div>- </div>- </div>+ <AdminPageContainer id={this.id} name={this.name} title={this.title} subtitle={this.subtitle}>+ {this.content()}+ </AdminPageContainer>)}}diff --git a/public/pages/Administration/pages/GeneralSettings.page.tsx b/public/pages/Administration/pages/GeneralSettings.page.tsxindex 553a1ee61..e6eb419ae 100644--- a/public/pages/Administration/pages/GeneralSettings.page.tsx+++ b/public/pages/Administration/pages/GeneralSettings.page.tsx@@ -1,84 +1,50 @@-import React from "react"+import React, { useState } from "react"import { Button, ButtonClickEvent, TextArea, Form, Input, ImageUploader } from "@fider/components"+import { AdminPageContainer } from "../components/AdminBasePage"import { actions, Failure, Fider } from "@fider/services"-import { AdminBasePage } from "../components/AdminBasePage"import { ImageUpload } from "@fider/models"--interface GeneralSettingsPageState {- logo?: ImageUpload- title: string- invitation: string- welcomeMessage: string- cname: string- error?: Failure-}--export default class GeneralSettingsPage extends AdminBasePage<any, GeneralSettingsPageState> {- public id = "p-admin-general"- public name = "general"- public title = "General"- public subtitle = "Manage your site settings"-- constructor(props: any) {- super(props)-- this.state = {- title: Fider.session.tenant.name,- cname: Fider.session.tenant.cname,- welcomeMessage: Fider.session.tenant.welcomeMessage,- invitation: Fider.session.tenant.invitation,- }- }-- private handleSave = async (e: ButtonClickEvent) => {- const result = await actions.updateTenantSettings(this.state)+import { useFider } from "@fider/hooks"+// import locales from "@locale/locales"++const GeneralSettingsPage = () => {+ const fider = useFider()+ const [title, setTitle] = useState<string>(fider.session.tenant.name)+ const [welcomeMessage, setWelcomeMessage] = useState<string>(fider.session.tenant.welcomeMessage)+ const [invitation, setInvitation] = useState<string>(fider.session.tenant.invitation)+ const [logo, setLogo] = useState<ImageUpload | undefined>(undefined)+ const [cname, setCNAME] = useState<string>(fider.session.tenant.cname)+ const [locale] = useState<string>(fider.session.tenant.locale)+ const [error, setError] = useState<Failure | undefined>(undefined)++ const handleSave = async (e: ButtonClickEvent) => {+ const result = await actions.updateTenantSettings({ title, cname, welcomeMessage, invitation, logo, locale })if (result.ok) {e.preventEnable()location.href = `/`} else if (result.error) {- this.setState({ error: result.error })+ setError(result.error)}}- public dnsInstructions(): JSX.Element {- const isApex = this.state.cname.split(".").length <= 2+ const dnsInstructions = (): JSX.Element => {+ const isApex = cname.split(".").length <= 2const recordType = isApex ? "ALIAS" : "CNAME"return (<>- <strong>{this.state.cname}</strong> {recordType}{" "}+ <strong>{cname}</strong> {recordType}{" "}<strong>- {Fider.session.tenant.subdomain}- {Fider.settings.domain}+ {fider.session.tenant.subdomain}+ {fider.settings.domain}</strong></>)}- private setTitle = (title: string): void => {- this.setState({ title })- }-- private setWelcomeMessage = (welcomeMessage: string): void => {- this.setState({ welcomeMessage })- }-- private setInvitation = (invitation: string): void => {- this.setState({ invitation })- }-- private setLogo = (logo: ImageUpload): void => {- this.setState({ logo })- }-- private setCNAME = (cname: string): void => {- this.setState({ cname })- }-- public content() {- return (- <Form error={this.state.error}>- <Input field="title" label="Title" maxLength={60} value={this.state.title} disabled={!Fider.session.user.isAdministrator} onChange={this.setTitle}>+ return (+ <AdminPageContainer id="p-admin-general" name="general" title="General" subtitle="Manage your site settings">+ <Form error={error}>+ <Input field="title" label="Title" maxLength={60} value={title} disabled={!fider.session.user.isAdministrator} onChange={setTitle}><p className="text-muted">The title is used on the header, emails, notifications and SEO content. Keep it short and simple. The product/service name is usually the bestchoice.@@ -88,9 +54,9 @@ export default class GeneralSettingsPage extends AdminBasePage<any, GeneralSetti<TextAreafield="welcomeMessage"label="Welcome Message"- value={this.state.welcomeMessage}- disabled={!Fider.session.user.isAdministrator}- onChange={this.setWelcomeMessage}+ value={welcomeMessage}+ disabled={!fider.session.user.isAdministrator}+ onChange={setWelcomeMessage}><p className="text-muted">The message is shown on this site's home page. Use it to help visitors understad what this space is about and the importance of their feedback.@@ -102,10 +68,10 @@ export default class GeneralSettingsPage extends AdminBasePage<any, GeneralSettifield="invitation"label="Invitation"maxLength={60}- value={this.state.invitation}- disabled={!Fider.session.user.isAdministrator}+ value={invitation}+ disabled={!fider.session.user.isAdministrator}placeholder="Enter your suggestion here..."- onChange={this.setInvitation}+ onChange={setInvitation}><p className="text-muted">This text is used as a placeholder for the suggestion's text box. Use it to invite your visitors into sharing their suggestions and feedback.@@ -113,7 +79,7 @@ export default class GeneralSettingsPage extends AdminBasePage<any, GeneralSetti</p></Input>- <ImageUploader label="Logo" field="logo" bkey={Fider.session.tenant.logoBlobKey} disabled={!Fider.session.user.isAdministrator} onChange={this.setLogo}>+ <ImageUploader label="Logo" field="logo" bkey={fider.session.tenant.logoBlobKey} disabled={!fider.session.user.isAdministrator} onChange={setLogo}><p className="text-muted">We accept JPG, GIF and PNG images, smaller than 100KB and with an aspect ratio of 1:1 with minimum dimensions of 200x200 pixels.</p>@@ -125,15 +91,15 @@ export default class GeneralSettingsPage extends AdminBasePage<any, GeneralSettilabel="Custom Domain"maxLength={100}placeholder="feedback.yourcompany.com"- value={this.state.cname}- disabled={!Fider.session.user.isAdministrator}- onChange={this.setCNAME}+ value={cname}+ disabled={!fider.session.user.isAdministrator}+ onChange={setCNAME}><div className="text-muted">- {this.state.cname ? (+ {cname ? ([<p key={0}>Enter the following record into your DNS zone records:</p>,- <p key={1}>{this.dnsInstructions()}</p>,+ <p key={1}>{dnsInstructions()}</p>,<p key={2}>Please note that it may take up to 72 hours for the change to take effect worldwide due to DNS propagation.</p>,]) : (@@ -146,12 +112,38 @@ export default class GeneralSettingsPage extends AdminBasePage<any, GeneralSetti</Input>)}+ {/* <Select+ label="Locale"+ field="locale"+ defaultValue={locale}+ options={Object.entries(locales).map(([k, v]) => ({+ value: k,+ label: v.text,+ }))}+ onChange={(o) => setLocale(o?.value || "en")}+ >+ {locale !== "en" && (+ <>+ <p className="text-muted">+ This language is currently <strong>{locales[locale].translated}%</strong> translated by the Open Source community. If you find a mistake or+ would like to improve its quality, visit{" "}+ <a className="text-link" target="_blank" rel="noopener" href="https://crowdin.com/project/fider">+ Crowdin+ </a>{" "}+ and contribute with your own translations.+ </p>+ </>+ )}+ </Select> */}+<div className="field">- <Button disabled={!Fider.session.user.isAdministrator} variant="primary" onClick={this.handleSave}>+ <Button disabled={!fider.session.user.isAdministrator} variant="primary" onClick={handleSave}>Save</Button></div></Form>- )- }+ </AdminPageContainer>+ )}++export default GeneralSettingsPagediff --git a/public/services/actions/tenant.ts b/public/services/actions/tenant.tsindex 99a8b565d..f2c9a9f20 100644--- a/public/services/actions/tenant.ts+++ b/public/services/actions/tenant.ts@@ -28,6 +28,7 @@ export interface UpdateTenantSettingsRequest {invitation: stringwelcomeMessage: stringcname: string+ locale: string}export const updateTenantSettings = async (request: UpdateTenantSettingsRequest): Promise<Result> => {diff --git a/public/services/fider.ts b/public/services/fider.tsindex c50134248..344799811 100644--- a/public/services/fider.ts+++ b/public/services/fider.ts@@ -54,6 +54,13 @@ export class FiderImpl {return this}+ public get currentLocale(): string {+ if (this.session.tenant) {+ return this.session.tenant.locale+ }+ return this.settings.locale+ }+public get session(): FiderSession {return this.pSession}diff --git a/public/ssr.tsx b/public/ssr.tsxindex f1d77e94f..89d2d5669 100644--- a/public/ssr.tsx+++ b/public/ssr.tsx@@ -34,7 +34,7 @@ const routes = [function ssrRender(url: string, pathname: string, args: any) {const fider = Fider.initialize({ ...args })- const i18n = activateI18NSync(fider.settings.locale, messages[fider.settings.locale].messages)+ const i18n = activateI18NSync(fider.currentLocale, messages[fider.currentLocale].messages)const config = resolveRootComponent(pathname, routes)window.location.href = urldiff --git a/tsconfig.json b/tsconfig.jsonindex 67b3ff274..0134b70e0 100755--- a/tsconfig.json+++ b/tsconfig.json@@ -9,13 +9,13 @@"strict": true,"jsx": "react","lib": ["dom", "es2015.promise", "es6"],- "baseUrl": "./public",+ "baseUrl": ".","noEmit": true,"noUnusedLocals": true,"paths": {- "@fider/*": ["*"],- "@locale/*": ["*"]+ "@fider/*": ["./public/*"],+ "@locale/*": ["./locale/*"]}},- "include": ["./public/**/*", "index.d.ts"]+ "include": ["./public/**/*", "./locale/**/*", "index.d.ts"]}diff --git a/webpack.config.js b/webpack.config.jsindex 1be9c3f02..98bf737f1 100755--- a/webpack.config.js+++ b/webpack.config.js@@ -75,7 +75,7 @@ module.exports = {},{test: /\.(ts|tsx)$/,- include: publicFolder,+ include: [publicFolder, localeFolder],loader: "babel-loader",},{