Skip to content

Commit

Permalink
merge translation.js into env/Translation. Add method to access local…
Browse files Browse the repository at this point in the history
…ized strings
  • Loading branch information
SleepWalker committed Aug 17, 2018
1 parent e9561c6 commit 046070b
Show file tree
Hide file tree
Showing 10 changed files with 120 additions and 159 deletions.
41 changes: 16 additions & 25 deletions lib/core/DocsLayout.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const Doc = require('./Doc.js');
const DocsSidebar = require('./DocsSidebar.js');
const OnPageNav = require('./nav/OnPageNav.js');
const Site = require('./Site.js');
const translation = require('../server/translation.js');
const {translation} = require('../server/env.js');

// component used to generate whole webpage for docs, including sidebar/header/footer
class DocsLayout extends React.Component {
Expand All @@ -35,17 +35,18 @@ class DocsLayout extends React.Component {
render() {
const metadata = this.props.metadata;
const content = this.props.children;
const i18n = translation[this.props.metadata.language];
const {language} = this.props.metadata;
let DocComponent = Doc;

if (this.props.Doc) {
DocComponent = this.props.Doc;
}
const title = i18n
? translation[this.props.metadata.language]['localized-strings'][
this.props.metadata.localized_id
] || this.props.metadata.title
: this.props.metadata.title;

const title =
translation.t(language, this.props.metadata.localized_id) ||
this.props.metadata.title;
const hasOnPageNav = this.props.config.onPageNav === 'separate';

return (
<Site
config={this.props.config}
Expand Down Expand Up @@ -79,15 +80,10 @@ class DocsLayout extends React.Component {
metadata.previous_id
)}>
{' '}
{i18n
? translation[this.props.metadata.language][
'localized-strings'
][metadata.previous_id] ||
translation[this.props.metadata.language][
'localized-strings'
].previous ||
'Previous'
: metadata.previous_title || 'Previous'}
{translation.t(language, metadata.previous_id) ||
translation.t(language, 'previous') ||
metadata.previous_title ||
'Previous'}
</a>
)}
{metadata.next_id && (
Expand All @@ -97,15 +93,10 @@ class DocsLayout extends React.Component {
metadata.localized_id,
metadata.next_id
)}>
{i18n
? translation[this.props.metadata.language][
'localized-strings'
][metadata.next_id] ||
translation[this.props.metadata.language][
'localized-strings'
].next ||
'Next'
: metadata.next_title || 'Next'}{' '}
{translation.t(language, metadata.next_id) ||
translation.t(language, 'next') ||
metadata.next_title ||
'Next'}{' '}
</a>
)}
Expand Down
8 changes: 4 additions & 4 deletions lib/core/Redirect.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@

const React = require('react');
const Head = require('./Head.js');
const translation = require('../server/translation.js');
const {translation} = require('../server/env.js');

// Component used to provide same head, header, footer, other scripts to all pages
class Redirect extends React.Component {
render() {
const tagline = translation[this.props.language]
? translation[this.props.language]['localized-strings'].tagline
: this.props.config.tagline;
const tagline =
translation.t(this.props.language, 'tagline') ||
this.props.config.tagline;
const title = this.props.title
? `${this.props.title} · ${this.props.config.title}`
: (!this.props.config.disableTitleTagline &&
Expand Down
14 changes: 7 additions & 7 deletions lib/core/Site.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,21 @@
const React = require('react');
const fs = require('fs');

const CWD = process.cwd();

const HeaderNav = require('./nav/HeaderNav.js');
const Head = require('./Head.js');

const Footer = require(`${process.cwd()}/core/Footer.js`);
const translation = require('../server/translation.js');
const Footer = require(`${CWD}/core/Footer.js`);
const {translation} = require('../server/env.js');
const constants = require('./constants');

const CWD = process.cwd();

// Component used to provide same head, header, footer, other scripts to all pages
class Site extends React.Component {
render() {
const tagline = translation[this.props.language]
? translation[this.props.language]['localized-strings'].tagline
: this.props.config.tagline;
const tagline =
translation.t(this.props.language, 'tagline') ||
this.props.config.tagline;
const title = this.props.title
? `${this.props.title} · ${this.props.config.title}`
: (!this.props.config.disableTitleTagline &&
Expand Down
39 changes: 15 additions & 24 deletions lib/core/nav/HeaderNav.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,8 @@ const fs = require('fs');
const classNames = require('classnames');

const siteConfig = require(`${CWD}/siteConfig.js`);
const translation = require('../../server/translation.js');
const env = require('../../server/env.js');

const translate = require('../../server/translate.js').translate;
const setLanguage = require('../../server/translate.js').setLanguage;

const {translation, versioning} = require('../../server/env.js');
const {translate, setLanguage} = require('../../server/translate.js');
const readMetadata = require('../../server/readMetadata.js');

readMetadata.generateMetadataDocs();
Expand All @@ -34,7 +30,7 @@ class LanguageDropDown extends React.Component {
'Help Translate|recruit community translators for your project'
);
// add all enabled languages to dropdown
const enabledLanguages = env.translation
const enabledLanguages = translation
.enabledLanguages()
.filter(lang => lang.tag !== this.props.language)
.map(lang => {
Expand Down Expand Up @@ -66,7 +62,7 @@ class LanguageDropDown extends React.Component {
}

// Get the current language full name for display in the header nav
const currentLanguage = env.translation
const currentLanguage = translation
.enabledLanguages()
.filter(lang => lang.tag === this.props.language)
.map(lang => lang.name);
Expand Down Expand Up @@ -143,10 +139,7 @@ class HeaderNav extends React.Component {
);
}
if (link.languages) {
if (
env.translation.enabled &&
env.translation.enabledLanguages().length > 1
) {
if (translation.enabled && translation.enabledLanguages().length > 1) {
return (
<LanguageDropDown
baseUrl={this.props.baseUrl}
Expand All @@ -161,12 +154,12 @@ class HeaderNav extends React.Component {
}
if (link.doc) {
// set link to document with current page's language/version
const langPart = env.translation.enabled
const langPart = translation.enabled
? `${this.props.language || 'en'}-`
: '';
const versionPart =
env.versioning.enabled && this.props.version !== 'next'
? `version-${this.props.version || env.versioning.defaultVersion}-`
versioning.enabled && this.props.version !== 'next'
? `version-${this.props.version || versioning.defaultVersion}-`
: '';
const id = langPart + versionPart + link.doc;
if (!Metadata[id]) {
Expand All @@ -179,9 +172,9 @@ class HeaderNav extends React.Component {
} else {
errorStr += `${'. Check the spelling of your `doc` field. If that seems sane, and a document in your docs folder exists with that `id` value, \nthen this is likely a bug in Docusaurus.' +
' Docusaurus thinks one or both of translations (currently set to: '}${
env.translation.enabled
translation.enabled
}) or versioning (currently set to: ${
env.versioning.enabled
versioning.enabled
}) is enabled when maybe they should not be. \nThus my internal id for this doc is: '${id}'. Please file an issue for this possible bug on GitHub.`;
}
throw new Error(errorStr);
Expand Down Expand Up @@ -223,9 +216,7 @@ class HeaderNav extends React.Component {
return (
<li key={`${link.label}page`} className={itemClasses}>
<a href={href} target={link.external ? '_blank' : '_self'}>
{translation[this.props.language]
? translation[this.props.language]['localized-strings'][link.label]
: link.label}
{translation.t(this.props.language, link.label) || link.label}
</a>
</li>
);
Expand Down Expand Up @@ -293,7 +284,7 @@ class HeaderNav extends React.Component {
: 'headerTitle';
const versionsLink =
this.props.baseUrl +
(env.translation.enabled
(translation.enabled
? `${this.props.language}/versions${extension}`
: `versions${extension}`);
return (
Expand All @@ -303,7 +294,7 @@ class HeaderNav extends React.Component {
<a
href={
this.props.baseUrl +
(env.translation.enabled ? this.props.language : '')
(translation.enabled ? this.props.language : '')
}>
{siteConfig.headerIcon && (
<img
Expand All @@ -316,9 +307,9 @@ class HeaderNav extends React.Component {
<h2 className={headerClass}>{this.props.title}</h2>
)}
</a>
{env.versioning.enabled && (
{versioning.enabled && (
<a href={versionsLink}>
<h3>{this.props.version || env.versioning.defaultVersion}</h3>
<h3>{this.props.version || versioning.defaultVersion}</h3>
</a>
)}
{this.renderResponsiveNav()}
Expand Down
23 changes: 10 additions & 13 deletions lib/core/nav/SideNav.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,35 +9,32 @@ const React = require('react');
const classNames = require('classnames');

const siteConfig = require(`${process.cwd()}/siteConfig.js`);
const translation = require('../../server/translation.js');
const {translation} = require('../../server/env.js');
const utils = require('../utils.js');

class SideNav extends React.Component {
// return appropriately translated category string
getLocalizedCategoryString(category) {
const categoryString = translation[this.props.language]
? translation[this.props.language]['localized-strings'][category] ||
category
: category;
const categoryString =
translation.t(this.props.language, category) || category;

return categoryString;
}

// return appropriately translated label to use for doc/blog in sidebar
getLocalizedString(metadata) {
let localizedString;
const i18n = translation[this.props.language];
const {language} = this.props;
const sbTitle = metadata.sidebar_label;
let localizedString;

if (sbTitle) {
localizedString = i18n
? i18n['localized-strings'][sbTitle] || sbTitle
: sbTitle;
localizedString = translation.t(language, sbTitle) || sbTitle;
} else {
const id = metadata.original_id || metadata.localized_id;
localizedString = i18n
? i18n['localized-strings'][id] || metadata.title
: metadata.title;

localizedString = translation.t(language, id) || metadata.title;
}

return localizedString;
}

Expand Down
55 changes: 55 additions & 0 deletions lib/server/env/Translation.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/
const CWD = process.cwd();
const path = require('path');
const glob = require('glob');
const fs = require('fs-extra');
const escapeStringRegexp = require('escape-string-regexp');

Expand All @@ -23,6 +24,40 @@ class Translation {
];
}

/**
* Translates string by its key
*
* @param {string} language
* @param {string} key
* @param {'default' | 'pages'} [category='default']
*
* @return {?string}
*/
t(language, key, category = 'default') {
if (!this.translations) {
this.loadTranslations();
}

const categoryMap = {
default: 'localized-strings',
pages: 'pages-strings',
};

if (!categoryMap[category]) {
throw new Error(`Unknown category name: ${category}`);
}

const curLang = this.translations[language];

if (!curLang) {
return null;
}

const curCategory = curLang[categoryMap[category]] || {};

return curCategory[key] || null;
}

enabledLanguages = () => this.languages.filter(lang => lang.enabled);

getLanguage(file, refDir) {
Expand Down Expand Up @@ -52,6 +87,26 @@ class Translation {
this.languages = require(languagesFile);
}
}

loadTranslations() {
const translations = {languages: this.enabledLanguages()};

const files = glob.sync(`${CWD}/i18n/**`);
const langRegex = /\/i18n\/(.*)\.json$/;

files.forEach(file => {
const extension = path.extname(file);

if (extension === '.json') {
const match = langRegex.exec(file);
const language = match[1];

translations[language] = require(file);
}
});

this.translations = translations;
}
}

module.exports = Translation;
21 changes: 3 additions & 18 deletions lib/server/readCategories.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,13 @@
* LICENSE file in the root directory of this source tree.
*/

const fs = require('fs');

const env = require('./env');
const Metadata = require('../core/metadata.js');

const CWD = process.cwd();
let languages;
if (fs.existsSync(`${CWD}/languages.js`)) {
languages = require(`${CWD}/languages.js`);
} else {
languages = [
{
enabled: true,
name: 'English',
tag: 'en',
},
];
}

// returns data broken up into categories for a sidebar
function readCategories(sidebar) {
const enabledLanguages = languages
.filter(lang => lang.enabled)
const enabledLanguages = env.translation
.enabledLanguages()
.map(lang => lang.tag);

const allCategories = {};
Expand Down
Loading

0 comments on commit 046070b

Please sign in to comment.