Skip to content

Commit

Permalink
Merge 2d25431 into be67929
Browse files Browse the repository at this point in the history
  • Loading branch information
tormozz48 committed Jul 31, 2015
2 parents be67929 + 2d25431 commit 862e336
Show file tree
Hide file tree
Showing 24 changed files with 401 additions and 263 deletions.
18 changes: 9 additions & 9 deletions lib/compile.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ var EOL = require('os').EOL,
tanker = require('../exlib/tanker');

/**
* Compile code of i18n.
* Compiles code of i18n.
*
* @param {Object} parsed info from keysets file,
* @param {String} language - language of keysets,
* @param {Object} parsed info from keysets file
* @param {String} language language of keysets
* example: `{ scope: { key: 'val' } }`. The value can be a function,
* example: `{ scope: { key: function (params, i18n) { return 'res'; } } }`.
*
Expand All @@ -20,10 +20,10 @@ module.exports = function (parsed, language) {
};

/**
* Compile i18n function for bem-bl localization system
* @param {String} core - bem-core i18n core code string
* @param {Object} keysets - keysets hash
* @param {String} language - language of keysets
* Compiles i18n function for bem-bl localization system
* @param {String} core — code string that contains i18n core of bem-core library
* @param {Object} keysets keysets hash
* @param {String} language language of keysets
* @returns {String}
*/
function compileForVersion1(core, keysets, language) {
Expand All @@ -49,8 +49,8 @@ function compileForVersion1(core, keysets, language) {
* Return decl function call code string for given keyset scope
* @param {String} scopeName - name of scope
* @param {Object} scope hash object
* @param {String} lang - language option value
* @returns {string|*}
* @param {String} lang language option value
* @returns {String|*}
* @private
*/
function _getKeysetBuildResult(scopeName, scope, lang) {
Expand Down
3 changes: 1 addition & 2 deletions lib/keysets.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Parse object with keysets.
* Parses object with keysets.
*
* It separates the core of i18n from other keysets. The core will be searched in the `i18n` scope with `i18n` key.
*
Expand All @@ -8,7 +8,6 @@
* example: `{ scope: { key: function (params, i18n) { return 'res'; } } }`.
*
* @throws Will throw an error if the core is not found.
*
* @returns {{ core: Function|String, keysets: (Object.<String, String>|Object.<String, String, Function>) }}
*/
function parse(keysets) {
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
"jscs": "1.13.1",
"jshint": "2.7.0",
"mocha": "2.2.5",
"mock-enb": "0.0.1",
"mock-enb": "0.1.0",
"mock-fs": "2.7.0",
"mock-require": "1.0.5",
"must": "0.12.0"
Expand Down
83 changes: 53 additions & 30 deletions techs/bemxjst/bemhtml-i18n.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,3 @@
/**
* bemhtml-i18n
* ============
*
* Собирает `?.bemhtml.<язык>.js`-файлы на основе `?.keysets.<язык>.js`-файла и исходных шаблонов.
*
* Склеивает *bemhtml.xjst* и *bemhtml*-файлы по deps'ам, обрабатывает `bem-xjst`-транслятором,
* сохраняет (по умолчанию) в виде `?.bemhtml.js`.
* **Внимание:** поддерживает только js-синтаксис.
* **Опции**
*
* * *String* **target** — Результирующий таргет. По умолчанию — `?.bemhtml.js`.
* * *String* **lang** — Язык, для которого небходимо собрать файл.
* * *String* **keysetsFile** — Исходный keysets-файл. По умолчанию — `?.keysets.{lang}.js`.
* * *String* **filesTarget** — files-таргет, на основе которого получается список исходных файлов
* (его предоставляет технология `files`). По умолчанию — `?.files`.
* * *String* **sourceSuffixes** — суффиксы файлов, по которым строится `files`-таргет.
* По умолчанию — `['bemhtml', 'bemhtml.xjst']`.
* * *String* **exportName** — Имя переменной-обработчика BEMHTML. По умолчанию — `'BEMHTML'`.
* * *Boolean* **devMode** — Development-режим. По умолчанию — true.
* * *Boolean* **cache** — Кэширование. Возможно только в production-режиме. По умолчанию — `false`.
* * *Object* **modulesDeps** — Хэш-объект, прокидывающий в генерируемую для скомпилированных шаблонов обвязку,
* необходимые YModules-модули.
*
* **Пример**
*
* ```javascript
* nodeConfig.addTech([ require('enb-bem-i18n/techs/bemxjst/bemhtml-i18n'), { lang: {lang}, devMode: false } ]);
* ```
*/
var EOL = require('os').EOL,
path = require('path'),
vow = require('vow'),
Expand All @@ -39,6 +9,59 @@ var EOL = require('os').EOL,
compile = require('../../lib/compile'),
XJST_SUFFIX = 'xjst';

/**
* @class BemhtmlI18nTech
* @augments {BemhtmlTech}
* @classdesc
*
* Compiles localized BEMHTML template files with BEMXJST translator and merges them into a single BEMHTML bundle.<br/>
* <br/>
* Localization is based on pre-built `?.keysets.{lang}.js` bundle files.<br/><br/>
*
* Important: It supports only JavaScript syntax by default. Use `compat` option to support old BEMHTML syntax.
*
* @param {Object} [options] Options
* @param {String} [options.target='?.bemhtml.{lang}.js'] Path to a target with compiled file.
* @param {String} options.lang Language identifier.
* @param {String} [options.exportName='BEMHTML'] Name of BEMHTML template variable.
* @param {Boolean} [options.compat=false] Sets `compat` option to support old BEMHTML syntax.
* @param {Boolean} [options.devMode=true] Sets `devMode` option for convenient debugging.
* If `devMode` is set to true, code of templates will
* not be compiled but only wrapped for development
* purposes.
* @param {Boolean} [options.cache=false] Sets `cache` option for cache usage.
* @param {Object} [options.requires] Names of dependencies which should be available from
* code of templates.
* @param {String[]} [options.sourceSuffixes] Files with specified suffixes involved in the
* assembly.
* @param {String} [options.keysetsFile='?.keysets.{lang}.js'] Path to a source keysets file.
*
* @example
* var BemhtmlI18nTech = require('enb-bem-i18n/techs/bemxjst/bemhtml-i18n'),
* FileProvideTech = require('enb/techs/file-provider'),
* bem = require('enb-bem-techs');
*
* module.exports = function(config) {
* config.node('bundle', function(node) {
* // get FileList
* node.addTechs([
* [FileProvideTech, { target: '?.bemdecl.js' }],
* [bem.levels, levels: ['blocks']],
* bem.deps,
* bem.files
* ]);
*
* // collect and merge keysets files into bundle
* node.addTechs([
* [ Keysets, { lang: '{lang}' } ]
* ]);
*
* // build localized BEMHTML file for given {lang}
* node.addTech([ BemhtmlI18nTech, { lang: '{lang}' } ]);
* node.addTarget('?.bemhtml.{lang}.js');
* });
* };
*/
module.exports = require('enb-bemxjst/techs/bemhtml').buildFlow()
.name('bemhtml-i18n')
.target('target', '?.bemhtml.{lang}.js')
Expand Down
92 changes: 56 additions & 36 deletions techs/bh-bundle-i18n.js
Original file line number Diff line number Diff line change
@@ -1,50 +1,70 @@
var vow = require('vow'),
path = require('path'),
asyncRequire = require('enb/lib/fs/async-require'),
dropRequireCache = require('enb/lib/fs/drop-require-cache'),
keysets = require('../lib/keysets'),
compile = require('../lib/compile');

/**
* bh-bundle-i18n
* ==============
* @class BHBundleI18nTech
* @augments {BHBundleTech}
* @classdesc
*
* Builds localized file with CommonJS requires for core and each BH template (`bh.js` files).<br/><br/>
*
* Собирает *BH*-файлы по deps'ам в виде `?.bh.js` бандла на основе `?.keysets.<язык>.js`-файла.
* Localization is based on pre-built `?.keysets.{lang}.js` bundle files.<br/><br/>
*
* Предназначен для сборки как клиентского, так и серверного BH-кода.
* Предполагается, что в *BH*-файлах не используется `require`.
* Use in browsers and on server side (Node.js).<br/><br/>
*
* Поддерживает CommonJS и YModules. Если в исполняемой среде нет ни одной модульной системы, то модуль будет
* предоставлен в глобальную переменную `bh`.
* The compiled BH module supports CommonJS and YModules. If there is no any modular system in the runtime,
* the module will be provided as global variable `BH`.<br/><br/>
*
* **Опции**
* Important: do not use `require` in templates.
*
* * *String* **target** — Результирующий таргет. По умолчанию — `?.bh.js`.
* * *String* **filesTarget** — files-таргет, на основе которого получается список исходных файлов
* * *String* **lang** — Язык, для которого небходимо собрать файл.
* * *String* **keysetsFile** — Исходный keysets-файл. По умолчанию — `?.keysets.{lang}.js`.
* (его предоставляет технология `files`). По умолчанию — `?.files`.
* * *String* **sourceSuffixes** — суффиксы файлов, по которым строится `files`-таргет. По умолчанию — ['bh.js'].
* * *Boolean* **sourcemap** — строить карты кода.
* * *String|Array* **mimic** — имена переменных/модулей для экспорта.
* * *String* **jsAttrName** — атрибут блока с параметрами инициализации. По умолчанию — `data-bem`.
* * *String* **jsAttrScheme** — Cхема данных для параметров инициализации. По умолчанию — `json`.
* * Форматы:
* * `js` — Получаем `return { ... }`.
* * `json` — JSON-формат. Получаем `{ ... }`.
* @param {Object} options Options.
* @param {String} [options.target='?.bh.{lang}.js'] Path to a target with compiled file.
* @param {String} options.lang Language identifier.
* @param {String} [options.filesTarget='?.files'] Path to target with FileList.
* @param {String[]} [options.sourceSuffixes='bh.js'] Files with specified suffixes involved
* in the assembly.
* @param {Object} [options.requires] Names for dependencies to `BH.lib.name`.
* @param {String[]} [options.mimic] Names for export.
* @param {String} [options.scope='template'] Scope of templates execution.
* @param {Boolean} [options.sourcemap=false] Includes inline source maps.
* @param {String} [options.jsAttrName='data-bem'] Sets `jsAttrName` option for BH core.
* @param {String} [options.jsAttrScheme='json'] Sets `jsAttrScheme` option for BH core.
* @param {String} [options.jsCls='i-bem'] Sets `jsCls` option for BH core.
* @param {Boolean} [options.jsElem=true] Sets `jsElem` option for BH core.
* @param {Boolean} [options.escapeContent=false] Sets `escapeContent` option for BH core.
* @param {Boolean} [options.clsNobaseMods=false] Sets `clsNobaseMods` option for BH core.
* @param {String} [options.keysetsFile='?.keysets.{lang}.js'] Path to a source keysets file.
*
* * *String|Boolean* **jsCls** — имя `i-bem` CSS-класса. По умолчанию - `i-bem`. Для того, чтобы класс
* не добавлялся, следует указать значение `false` или пустую строку.
* @example
* var BHBundleI18nTech = require('enb-bh/techs/bh-bundle'),
* FileProvideTech = require('enb/techs/file-provider'),
* bem = require('enb-bem-techs');
*
* * *Boolean* **escapeContent** — экранирование содержимого. По умолчанию - `false`.
* module.exports = function(config) {
* config.node('bundle', function(node) {
* // get FileList
* node.addTechs([
* [FileProvideTech, { target: '?.bemdecl.js' }],
* [bem.levels, levels: ['blocks']],
* bem.deps,
* bem.files
* ]);
*
* **Пример**
* // collect and merge keysets files into bundle
* node.addTechs([
* [ Keysets, { lang: '{lang}' } ]
* ]);
*
* ```javascript
* nodeConfig.addTech([require('enb-bem-i18n/techs/bh-bundle-i18n', { lang: {lang} }]));
* ```
* // build localized BH file for given {lang}
* node.addTech([ BHBundleI18nTech, { lang: '{lang}' } ]);
* node.addTarget('?.bh.{lang}.js');
* });
* };
*/

var vow = require('vow'),
path = require('path'),
asyncRequire = require('enb/lib/fs/async-require'),
dropRequireCache = require('enb/lib/fs/drop-require-cache'),
keysets = require('../lib/keysets'),
compile = require('../lib/compile');

module.exports = require('enb-bh/techs/bh-bundle').buildFlow()
.name('bh-bundle-i18n')
.target('target', '?.bh.{lang}.js')
Expand Down
Loading

0 comments on commit 862e336

Please sign in to comment.