Skip to content

Commit

Permalink
feat(LocalizeRouterParser): Apply alwaysSetPrefix to multi langs Fix #63
Browse files Browse the repository at this point in the history


Don't prefix language for default language is `alwaysSetPrefix` is false
  • Loading branch information
meeroslav committed Aug 23, 2017
1 parent e9a5afa commit 4cd3fb6
Show file tree
Hide file tree
Showing 12 changed files with 129 additions and 91 deletions.
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ coverage/
# overrides for js
!config/*
!demo/cli/*js
!copy.js
!karma.conf.js
!webpack.config.js

Expand Down
1 change: 0 additions & 1 deletion .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ coverage
config
karma.conf.js
webpack.config.js
copy.js
tsconfig.json
tslint.json
!*.metadata.json
Expand Down
4 changes: 1 addition & 3 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,9 @@ before_install:
- npm i -g npm@^3
before_script:
- npm prune
after_success:
- npm run semantic-release
branches:
except:
- "/^v\\d+\\.\\d+\\.\\d+$/"
before_script:
- export DISPLAY=:99.0
- sh -e /etc/init.d/xvfb start
- sh -e /etc/init.d/xvfb start
44 changes: 30 additions & 14 deletions MIGRATION_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,37 +17,53 @@ In some cases your local `node_modules` might get in broken state in which case

3. The module initialization `forRoot` method has changed a bit. Instead of loader, it expects an object of parameters.

```typescript
```ts
import { Http } from '@angular/http';
import { TranslateService } from '@ngx-translate/core';
import { Location } from '@angular/common';
import { LocalizeRouterModule, LocalizeParser, StaticParserLoader } from 'localize-router';

LocalizeRouterModule.forRoot(routes, {
provide: LocalizeParser,
useFactory: (translate, location, http) =>
new StaticParserLoader(translate, location, http, 'your/path/to/config.json'),
new StaticParserLoader(translate, location, http, 'your/path/to/config.json'),
deps: [TranslateService, Location, Http]
})
```

Is now:

```typescript
```ts
import { Http } from '@angular/http';
import { TranslateService } from '@ngx-translate/core';
import { Location } from '@angular/common';
import { LocalizeRouterModule, LocalizeParser, StaticParserLoader, LocalizeRouterSettings } from 'localize-router';
LocalizeRouterModule.forRoot(routes, {
parser: {
provide: LocalizeParser,
useFactory: (translate, location, settings, http) =>
new StaticParserLoader(translate, location, settings, http, 'your/path/to/config.json'),
deps: [TranslateService, Location, LocalizeRouterSettings, Http]
provide: LocalizeParser,
useFactory: (translate, location, settings, http) =>
new StaticParserLoader(translate, location, settings, http, 'your/path/to/config.json'),
deps: [TranslateService, Location, LocalizeRouterSettings, Http]
}
})
```

You can now also provide additional settings regarding url prefixes and default language cache mechanisms:

```typescript
LocalizeRouterModule.forRoot({
useCachedLang: { provide: USE_CACHED_LANG, useValue: booleanValue },
alwaysSetPrefix: { provide: ALWAYS_SET_PREFIX, useValue: booleanValue },
cacheName: { provide: CACHE_NAME, useValue: stringValue },
cacheMechanism: { provide: CACHE_MECHANISM, useValue: typeOfCacheMechanism },
defaultLangFunction: { provide: DEFAULT_LANG_FUNCTION, useValue: typeOfDefaultLanguageFunction },
```ts
LocalizeRouterModule.forRoot(routes, {
parser: {
provide: LocalizeParser,
useFactory: (translate, location, settings, http) =>
new StaticParserLoader(translate, location, settings, http, 'your/path/to/config.json'),
deps: [TranslateService, Location, LocalizeRouterSettings, Http]
},
useCachedLang: { provide: USE_CACHED_LANG, useValue: booleanValue },
alwaysSetPrefix: { provide: ALWAYS_SET_PREFIX, useValue: booleanValue },
cacheName: { provide: CACHE_NAME, useValue: stringValue },
cacheMechanism: { provide: CACHE_MECHANISM, useValue: typeOfCacheMechanism },
defaultLangFunction: { provide: DEFAULT_LANG_FUNCTION, useValue: typeOfDefaultLanguageFunction },
})
```

Expand Down
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,9 @@ export function localizeLoaderFactory(translate: TranslateService, location: Loc
#### Properties
- `parser`: Provider for loading of LocalizeParser. Default value is `StaticParserLoader`.
- `useCachedLang`: boolean. Flag whether default language should be cached. Default value is `true`.
- `alwaysSetPrefix`: boolean. Flag whether language should always prefix the url if only one language is present. Default value is `true`.
- `alwaysSetPrefix`: boolean. Flag whether language should always prefix the url. Default value is `true`.
When value is `false`, prefix will not be used for for default language (this includes the situation when there is only one language).
- `prefixDefaultLanguage`: boolean. Flag whether default language should be prefixed or not. In order to maintain constant default language, specifying`defaultLangFunction` is recommended. Default value is `true`.
- `cacheMechanism`: CacheMechanism.LocalStorage || CacheMechanism.Cookie. Default value is `CacheMechanism.LocalStorage`.
- `cacheName`: string. Name of cookie/local store. Default value is `LOCALIZE_DEFAULT_LANGUAGE`.
- `defaultLangFunction`: (languages: string[], cachedLang?: string, browserLang?: string) => string. Override method for custom logic for picking default language, when no language is provided via url. Default value is `undefined`.
Expand Down Expand Up @@ -325,6 +327,7 @@ yoursite.com/en/users/John%20Doe/profile -> yoursite.com/de/benutzer/John%20Doe/
- `locales`: Array of used language codes
- `currentLang`: Currently selected language
- `routes`: Active translated routes
- `urlPrefix`: Language prefix for current language. Empty string if `alwaysSetPrefix=false` and `currentLang` is same as default language.

#### Methods:
- `translateRoutes(language: string): Observable<any>`: Translates all the routes and sets language and current
Expand Down
3 changes: 0 additions & 3 deletions copy.js

This file was deleted.

3 changes: 2 additions & 1 deletion demo/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
"@ngx-translate/core": "^7.0.0",
"@ngx-translate/http-loader": "^0.1.0",
"core-js": "^2.4.1",
"localize-router": "^0.7.1",
"localize-router": "1.0.0-alpha.1",
"localize-router-http-loader": "0.0.1",
"rxjs": "^5.1.0",
"zone.js": "^0.8.4"
},
Expand Down
16 changes: 14 additions & 2 deletions demo/cli/src/app/app-routing.module.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { LocalizeRouterModule } from 'localize-router';
import { LocalizeRouterModule, LocalizeRouterSettings, LocalizeParser } from 'localize-router';
import { LocalizeRouterHttpLoader } from 'localize-router-http-loader';
import { Http } from '@angular/http';
import { TranslateService } from '@ngx-translate/core';
import { Location } from '@angular/common';

export function HttpLoaderFactory(translate: TranslateService, location: Location, settings: LocalizeRouterSettings, http: Http) {
return new LocalizeRouterHttpLoader(translate, location, settings, http);
}

const routes = [
{ path: 'lazy', loadChildren: './+lazy/lazy.module#LazyModule' }
Expand All @@ -10,7 +18,11 @@ const routes = [
imports: [
RouterModule.forRoot(routes),
LocalizeRouterModule.forRoot(routes, {
useCachedLang: false
parser: {
provide: LocalizeParser,
useFactory: HttpLoaderFactory,
deps: [TranslateService, Location, LocalizeRouterSettings, Http]
}
})
],
exports: [ RouterModule, LocalizeRouterModule ]
Expand Down
9 changes: 1 addition & 8 deletions demo/cli/tslint.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,6 @@
140
],
"member-access": false,
"member-ordering": [
true,
"static-before-instance",
"variables-before-functions"
],
"no-arg": true,
"no-bitwise": true,
"no-console": [
Expand Down Expand Up @@ -69,9 +64,7 @@
"single"
],
"radix": true,
"semicolon": [
"always"
],
"semicolon": [ true, "always" ],
"triple-equals": [
true,
"allow-null-check"
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
{
"name": "localize-router",
"version": "1.0.0-alpha.1",
"version": "1.0.0-alpha.2",
"description": "An implementation of routes localization for Angular 2",
"scripts": {
"test": "karma start",
"test-watch": "karma start --singleRun=false --autoWatch=true",
"commit": "npm run prepublish && npm test",
"prepublish": "ngc && npm run build",
"build": "webpack && node copy.js"
"build": "webpack"
},
"repository": {
"type": "git",
Expand Down
50 changes: 27 additions & 23 deletions src/localize-router.parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,39 +79,44 @@ export abstract class LocalizeParser {
selectedLanguage = locationLang || this.defaultLang;
this.translate.setDefaultLang(this.defaultLang);

// don't add prefix if only single language and not enforced via options
if (this.locales.length > 1 || this.settings.alwaysSetPrefix) {
/** set base route */

let children: Routes = [];
/** if set prefix is enforced */
if (this.settings.alwaysSetPrefix) {
const baseRoute = { path: '', redirectTo: this.defaultLang, pathMatch: 'full' };

/** extract potential wildcard route */
let wildcardIndex = routes.findIndex((route: Route) => route.path === '**');
if (wildcardIndex !== -1) {
this._wildcardRoute = routes.splice(wildcardIndex, 1)[0];
}
children = this.routes.splice(0, this.routes.length, baseRoute);
} else {
children = [...this.routes]; // shallow copy of routes
}

/** mutable operation on routes */
let children = this.routes.splice(0, this.routes.length, baseRoute);

/** exclude certain routes */
for (let i = children.length - 1; i >= 0; i--) {
if (children[i].data && children[i].data.skipRouteLocalization) {
/** exclude certain routes */
for (let i = children.length - 1; i >= 0; i--) {
if (children[i].data && children[i].data.skipRouteLocalization) {
if (this.settings.alwaysSetPrefix) {
// add directly to routes
this.routes.push(children[i]);
children.splice(i, 1);
}
children.splice(i, 1);
}
}

/** append children routes... */
if (children && children.length) {
/** append children routes */
if (children && children.length) {
if (this.locales.length > 1 || this.settings.alwaysSetPrefix) {
this._languageRoute = { children: children };
this.routes.push(this._languageRoute);
this.routes.unshift(this._languageRoute);
}
}

/** ...and potential wildcard route */
if (this._wildcardRoute) {
this.routes.push(this._wildcardRoute);
}
/** ...and potential wildcard route */
if (this._wildcardRoute && this.settings.alwaysSetPrefix) {
this.routes.push(this._wildcardRoute);
}

/** translate routes */
Expand All @@ -137,25 +142,24 @@ export abstract class LocalizeParser {
translateRoutes(language: string): Observable<any> {
return new Observable<any>((observer: Observer<any>) => {
this._cachedLang = language;
if (this._languageRoute && (this.locales.length > 1 || this.settings.alwaysSetPrefix)) {
if (this._languageRoute) {
this._languageRoute.path = language;
}

this.translate.use(language).subscribe((translations: any) => {
this._translationObject = translations;
this.currentLang = language;

// if no prefixes used
if (this.locales.length === 1 && !this.settings.alwaysSetPrefix) {
this._translateRouteTree(this.routes);
} else {
if (this._languageRoute) {
if (this._languageRoute) {
this._translateRouteTree(this._languageRoute.children);
}
// if there is wildcard route
if (this._wildcardRoute && this._wildcardRoute.redirectTo) {
this._translateProperty(this._wildcardRoute, 'redirectTo', true);
}
} else {
this._translateRouteTree(this.routes);
}

observer.next(void 0);
Expand Down Expand Up @@ -209,7 +213,7 @@ export abstract class LocalizeParser {
}

get urlPrefix() {
return this.locales.length > 1 || this.settings.alwaysSetPrefix ? this.currentLang : '';
return this.settings.alwaysSetPrefix || this.currentLang !== this.defaultLang ? this.currentLang : '';
}

/**
Expand Down
Loading

0 comments on commit 4cd3fb6

Please sign in to comment.