Skip to content
Projects
Groups
Snippets
Help
This project
Loading...
Sign in / Register
Toggle navigation
C
common
Overview
Overview
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
npm
common
Commits
2f06a7e2
Commit
2f06a7e2
authored
Nov 09, 2018
by
Vladislav Lagunov
Browse files
Options
Browse Files
Download
Plain Diff
Merge branch 'master' into bitmaster-core
parents
42697ecc
9d299260
Show whitespace changes
Inline
Side-by-side
Showing
4 changed files
with
64 additions
and
134 deletions
+64
-134
WithConfirmation/i18n/ru.po
+0
-0
functions/compose.ts
+10
-0
gettext/README.md
+7
-69
gettext/index.ts
+47
-65
No files found.
WithConfirmation/i18n/ru
-RU
.po
→
WithConfirmation/i18n/ru.po
View file @
2f06a7e2
File moved
functions/compose.ts
0 → 100644
View file @
2f06a7e2
/**
* Прямая композиция
*/
export
default
function
compose
<
A
,
B
>
(
f
:
(
a
:
A
)
=>
B
):
(
a
:
A
)
=>
B
;
export
default
function
compose
<
A
,
B
,
C
>
(
f
:
(
a
:
A
)
=>
B
,
g
:
(
b
:
B
)
=>
C
):
(
a
:
A
)
=>
C
;
export
default
function
compose
<
A
,
B
,
C
,
D
>
(
f
:
(
a
:
A
)
=>
B
,
g
:
(
b
:
B
)
=>
C
,
h
:
(
c
:
C
)
=>
D
):
(
a
:
A
)
=>
D
;
export
default
function
compose
<
A
,
B
,
C
,
D
,
E
>
(
f
:
(
a
:
A
)
=>
B
,
g
:
(
b
:
B
)
=>
C
,
h
:
(
c
:
C
)
=>
D
,
j
:
(
d
:
D
)
=>
E
):
(
a
:
A
)
=>
E
;
export
default
function
compose
(...
funcs
:
Function
[]):
Function
{
return
a
=>
funcs
.
reduce
((
acc
,
f
)
=>
f
(
acc
),
a
);
}
gettext/README.md
View file @
2f06a7e2
## Пример использования
## Пример использования
```
ts
```
ts
import
{
makeGettext
,
withGettext
,
I18nString
}
from
'~/gettext'
;
import
{
Transaction
,
withGettext
,
I18nString
}
from
'~/gettext'
;
const
gettext
=
makeGettext
(
require
(
'./i18n.po.yml
'
));
const
translations
=
Transaction
.
fromJed
(
require
(
'./i18n
'
));
// Отложенный перевод строк
// Отложенный перевод строк
function
printStatus
(
status
:
'buzy'
|
'idle'
):
I18nString
{
function
printStatus
(
status
:
'buzy'
|
'idle'
):
I18nString
{
const
{
__
}
=
translations
;
switch
(
status
)
{
switch
(
status
)
{
case
'buzy'
:
return
gettext
(
'Buzy'
);
case
'buzy'
:
return
__
(
'Buzy'
);
case
'idle'
:
return
gettext
(
'Idle'
);
case
'idle'
:
return
__
(
'Idle'
);
}
}
}
}
...
@@ -34,72 +35,9 @@ class Widget extends React.Component<Props> {
...
@@ -34,72 +35,9 @@ class Widget extends React.Component<Props> {
<
/div>
;
<
/div>
;
}
}
}
}
export
default
withGettext
(
gettext
)(
Widget
);
export
default
withGettext
(
translations
)(
Widget
);
// Или так
// Или так
// export default withGettext(require('./i18n
.po.yml
'))(Widget);
// export default withGettext(require('./i18n'))(Widget);
```
```
## Формат *.po.yml
> 2018-10-31 DEPRECATED: Решил использовать стантартный формат *.po
Альтернативный формат, для
*
.po файлов предназначен предназначен для
более простой манипуляции с gettext-данными, и для обеспечения
возможности хранения переводов вместе с UI-компонентами модуль
```yml
- "":
locale: "ru-RU"
"Accommodations": "Проживания"
"Select guests": "Выберите гостя"
"%podata":
- msgid: "%d sec"
msgid_plural: "%d sec"
msgstr: ["%d секунда", "%d секунды", "%d секунд"]
- msgid: "<b>%d</b>–<b>%d</b> of <b>%d</b>"
msgid_plural: "<b>%d</b>–<b>%d</b> of <b>%d</b>"
msgstr: ["<b>%d</b>–<b>%d</b> из <b>%d</b>", "<b>%d</b>–<b>%d</b> из <b>%d</b>", "<b>%d</b>–<b>%d</b> из <b>%d</b>" ]
```
В корне
*
.po.yml должен быть массив, каждый элемент которого
соответствует целому
*
.po файлу.
```
- "":
locale: "ru-RU"
```
в поле с пустым именем содержатся метаданные файла (как в секции msgid
"" в оригинальном
*
.po)
```
"%podata":
- msgid: "%d sec"
msgid_plural: "%d sec"
msgstr: ["%d секунда", "%d секунды", "%d секунд"]
```
Еще одно специальное поле в объекте внутри массива —
`%podata`
внутри
содержатся поля соответствующие записям из оригинального формата po
`msgid`
,
`msgid_plural`
,
`msgctx`
,
`msgstr`
```
- ""
# ...
"Accommodations": "Проживания"
"Select guests": "Выберите гостя"
# Тоже самое в *.po
msgid "Accommodations"
msgstr "Проживания"
msgid "Select guests"
msgstr "Выберите гостя"
```
Остальные ключи внутри эелемента в корне массива соответствуют краткой
форме для записи в po в которой присутствуют только две строки
`msgid`
и
`msgstr`
gettext/index.ts
View file @
2f06a7e2
...
@@ -3,58 +3,33 @@ import { Omit } from '@material-ui/core';
...
@@ -3,58 +3,33 @@ import { Omit } from '@material-ui/core';
import
memoize
from
'~/functions/memoize'
;
import
memoize
from
'~/functions/memoize'
;
// Делимитер контекста
// Делимитер контекста
в jed-формате
const
CONTEXT_DELIMITER
=
String
.
fromCharCode
(
4
);
const
CONTEXT_DELIMITER
=
String
.
fromCharCode
(
4
);
// Translations
// Translations
export
type
Translations
=
Record
<
string
,
Record
<
string
,
string
[]
|
string
>>
;
export
type
Data
=
Record
<
string
,
Record
<
string
,
string
[]
|
string
>>
;
export
type
GettextData
=
{
export
type
JedFormat
=
{
locale_data
:
{
messages
:
Record
<
string
,
string
[]
>
}
};
''
:
Record
<
string
,
unknown
>
;
export
type
ES6Module
<
T
>
=
{
default
:
T
};
'%podata'
:
GettextExplicitKey
[],
}
&
{
[
K
in
string
]:
string
|
string
[];
};
// Содержимое поля `%podata`
export
type
GettextExplicitKey
=
{
msgid
:
string
;
msgid_plural
?:
string
;
msgctxt
?:
string
;
msgstr
:
string
|
string
[];
}
// Хелпер для перевода
// Хелпер для перевода
export
type
Gettext
=
(
singular_key
:
string
,
context
?:
string
,
plural_key
?:
string
,
val
?:
number
)
=>
string
;
export
type
Gettext
=
(
singular_key
:
string
,
context
?:
string
,
plural_key
?:
string
,
val
?:
number
)
=>
string
;
export
type
DeferredGettext
=
(
singular_key
:
string
,
context
?:
string
,
plural_key
?:
string
,
val
?:
number
)
=>
I18nString
;
export
type
I18nString
=
(
locale
?:
string
|
LocaleCtx
|
null
)
=>
string
;
export
type
I18nString
=
(
locale
?:
string
|
LocaleCtx
|
null
)
=>
string
;
// Использование локали из `ctx`
export
class
Translations
{
export
type
LocaleCtx
=
{
locale
:
string
};
constructor
(
readonly
data
:
Data
)
{}
/**
static
fromJed
(...
data
:
JedFormat
[]):
Translations
;
* Создание хелпера для переводов
static
fromJed
(...
data
:
ES6Module
<
JedFormat
>
[]):
Translations
;
*/
static
fromJed
(...
data
:
JedFormat
[][]):
Translations
;
export
function
makeGettext
(...
webpackContexts
):
DeferredGettext
{
static
fromJed
(...
data
:
ES6Module
<
JedFormat
>
[][]):
Translations
;
const
translations
:
Translations
=
assignData
({},
...
flattenModules
(
webpackContexts
));
static
fromJed
(...
webpackContexts
)
{
const
jedTranslations
:
JedFormat
[]
=
flattenModules
(
webpackContexts
);
return
(
singular_key
:
string
,
context
?:
string
,
plural_key
:
string
=
singular_key
,
n
:
number
=
1
)
=>
locale_
=>
{
return
new
Translations
(
assignJedData
({},
...
jedTranslations
));
let
locale
=
!
locale_
?
'en-US'
:
typeof
(
locale_
)
===
'string'
?
locale_
:
locale_
.
locale
;
locale
=
locale
.
replace
(
/_/
,
'-'
);
if
(
!
(
locale
in
translations
))
{
// Не найдена локаль в `translations`
return
n
===
1
?
singular_key
:
plural_key
;
}
const
key
=
context
?
context
+
CONTEXT_DELIMITER
+
singular_key
:
singular_key
;
const
dict
=
translations
[
locale
];
const
pluralIdx
=
getPluralForm
(
locale
)(
n
);
const
pluralList
=
dict
[
key
]
||
[
singular_key
,
plural_key
];
return
nth
(
pluralList
,
pluralIdx
);
};
function
flattenModules
(
xs
:
any
[])
{
function
flattenModules
(
xs
:
any
[])
{
return
Array
.
prototype
.
concat
.
apply
([],
xs
.
map
(
x
=>
{
return
Array
.
prototype
.
concat
.
apply
([],
xs
.
map
(
x
=>
{
...
@@ -62,14 +37,42 @@ export function makeGettext(...webpackContexts): DeferredGettext {
...
@@ -62,14 +37,42 @@ export function makeGettext(...webpackContexts): DeferredGettext {
return
Array
.
isArray
(
x
)
?
flattenModules
(
x
)
:
[
x
]
return
Array
.
isArray
(
x
)
?
flattenModules
(
x
)
:
[
x
]
}));
}));
}
}
}
__
:
(
singular_key
:
string
,
plural_key
?:
string
,
context
?:
string
,
n
?:
number
)
=>
I18nString
=
(
singular_key
,
plural_key
?,
context
?,
n
?)
=>
{
return
localeOrCtx
=>
{
let
locale
=
!
localeOrCtx
?
'en-US'
:
typeof
(
localeOrCtx
)
===
'string'
?
localeOrCtx
:
localeOrCtx
.
locale
;
locale
=
locale
.
replace
(
/_/
,
'-'
);
if
(
!
(
locale
in
this
.
data
))
{
// Не найдена локаль в `this.data`
return
n
===
1
?
singular_key
:
plural_key
!
;
}
const
key
=
context
?
context
+
CONTEXT_DELIMITER
+
singular_key
:
singular_key
;
const
dict
=
this
.
data
[
locale
];
const
pluralIdx
=
getPluralForm
(
locale
)(
n
||
1
);
const
pluralList
=
dict
[
key
]
||
[
singular_key
,
plural_key
];
return
nth
(
pluralList
,
pluralIdx
)
!
;
};
function
nth
<
A
>
(
xs
:
A
|
A
[],
idx
:
number
):
A
{
function
nth
<
A
>
(
xs
:
A
|
A
[],
idx
:
number
):
A
{
if
(
!
Array
.
isArray
(
xs
))
return
xs
;
if
(
!
Array
.
isArray
(
xs
))
return
xs
;
return
idx
>=
xs
.
length
?
xs
[
xs
.
length
-
1
]
:
xs
[
idx
];
return
idx
>=
xs
.
length
?
xs
[
xs
.
length
-
1
]
:
xs
[
idx
];
}
}
}
bind
(
localeOrCtx
?:
string
|
LocaleCtx
|
null
):
Gettext
{
return
(...
args
)
=>
{
return
this
.
__
(...
args
)(
localeOrCtx
);
};
}
}
}
// Использование локали из `ctx`
export
type
LocaleCtx
=
{
locale
:
string
};
/**
/**
* HOC для добавления переводов (для разделения переводов по фичам)
* HOC для добавления переводов (для разделения переводов по фичам)
* ```ts
* ```ts
...
@@ -77,10 +80,11 @@ export function makeGettext(...webpackContexts): DeferredGettext {
...
@@ -77,10 +80,11 @@ export function makeGettext(...webpackContexts): DeferredGettext {
* ```
* ```
*/
*/
export
function
withGettext
(...
webpackContexts
)
{
export
function
withGettext
(...
webpackContexts
)
{
const
gettext
=
typeof
(
webpackContexts
[
0
])
===
'function'
?
webpackContexts
[
0
]
:
makeGettext
(...
webpackContexts
);
const
translations
:
Translations
=
webpackContexts
[
0
]
instanceof
Translations
?
webpackContexts
[
0
]
:
Translations
.
fromJed
(...
webpackContexts
);
return
<
P
extends
{
__
:
Gettext
,
ctx
?:
{
locale
:
string
}
}
>
(
Component
:
React
.
ComponentType
<
P
>
)
=>
{
return
<
P
extends
{
__
:
Gettext
,
ctx
?:
{
locale
:
string
}
}
>
(
Component
:
React
.
ComponentType
<
P
>
)
=>
{
class
WithTranslations
extends
React
.
Component
<
Omit
<
P
,
'__'
>>
{
class
WithTranslations
extends
React
.
Component
<
Omit
<
P
,
'__'
>>
{
makeGettext
:
(
locale
?:
string
|
LocaleCtx
)
=>
Gettext
=
memoize
((
locale
)
=>
(...
args
)
=>
gettext
.
apply
(
void
0
,
args
)
(
locale
))
makeGettext
:
(
locale
?:
string
|
LocaleCtx
)
=>
Gettext
=
memoize
((
locale
)
=>
translations
.
bind
(
locale
))
render
()
{
render
()
{
const
{
ctx
}
=
this
.
props
;
const
{
ctx
}
=
this
.
props
;
...
@@ -98,32 +102,10 @@ export function withGettext(...webpackContexts) {
...
@@ -98,32 +102,10 @@ export function withGettext(...webpackContexts) {
/**
/**
* Хелпер для импорта нескольких переводов
* ```ts
* export default requireTranslations(require.context('./i18', false, /\.po$/));
* ```
*/
export
function
requireTranslations
(
webpackContext
/*: WebpackContext*/
):
Translations
{
return
webpackContext
.
keys
().
reduce
((
acc
,
k
)
=>
mergeTranslations
(
acc
,
webpackContext
(
k
)),
{});
function
mergeTranslations
(
acc
,
data
)
{
data
=
data
.
__esModule
?
data
.
default
:
data
;
for
(
const
k
of
Object
.
keys
(
data
))
{
acc
[
k
]
=
acc
[
k
]
||
{};
Object
.
assign
(
acc
[
k
],
data
[
k
]);
}
return
acc
;
}
}
/**
* Добавление переводов из `srcs` в `dst`
* Добавление переводов из `srcs` в `dst`
*/
*/
function
assign
Data
(
dst
:
Translations
,
...
srcs
:
GettextData
[]):
Translations
{
function
assign
JedData
(
dst
:
Data
,
...
srcs
:
JedFormat
[]):
Data
{
srcs
.
forEach
(
data
=>
{
srcs
.
forEach
(
data
=>
{
// @ts-ignore
if
(
'locale_data'
in
data
)
data
=
data
[
'locale_data'
][
'messages'
];
const
locale_
=
data
[
''
].
language
||
data
[
''
].
lang
||
data
[
''
].
locale
;
if
(
!
locale_
||
typeof
(
locale_
)
!==
'string'
)
return
;
const
locale_
=
data
[
''
].
language
||
data
[
''
].
lang
||
data
[
''
].
locale
;
if
(
!
locale_
||
typeof
(
locale_
)
!==
'string'
)
return
;
const
locale
=
locale_
.
replace
(
/_/g
,
'-'
);
const
locale
=
locale_
.
replace
(
/_/g
,
'-'
);
const
podata
=
data
[
'%podata'
];
const
podata
=
data
[
'%podata'
];
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment