Skip to content

Commit 4628a4f

Browse files
authored
Add FluentResource (#244)
* Add FluentResource * Add docs * Move Parser to FluentResource
1 parent 108ed24 commit 4628a4f

File tree

2 files changed

+46
-5
lines changed

2 files changed

+46
-5
lines changed

fluent/src/context.js

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import resolve from "./resolver";
2-
import parse from "./parser";
2+
import FluentResource from "./resource";
33

44
/**
55
* Message contexts are single-language stores of translations. They are
@@ -115,22 +115,45 @@ export class MessageContext {
115115
* @returns {Array<Error>}
116116
*/
117117
addMessages(source) {
118-
const [entries, errors] = parse(source);
119-
for (const id in entries) {
118+
const res = FluentResource.fromString(source);
119+
return this.addResource(res);
120+
}
121+
122+
/**
123+
* Add a translation resource to the context.
124+
*
125+
* The translation resource must be a proper FluentResource
126+
* parsed by `MessageContext.parseResource`.
127+
*
128+
* let res = MessageContext.parseResource("foo = Foo");
129+
* ctx.addResource(res);
130+
* ctx.getMessage('foo');
131+
*
132+
* // Returns a raw representation of the 'foo' message.
133+
*
134+
* Parsed entities should be formatted with the `format` method in case they
135+
* contain logic (references, select expressions etc.).
136+
*
137+
* @param {FluentResource} res - FluentResource object.
138+
* @returns {Array<Error>}
139+
*/
140+
addResource(res) {
141+
const errors = res.errors.slice();
142+
for (const [id, value] of res) {
120143
if (id.startsWith("-")) {
121144
// Identifiers starting with a dash (-) define terms. Terms are private
122145
// and cannot be retrieved from MessageContext.
123146
if (this._terms.has(id)) {
124147
errors.push(`Attempt to override an existing term: "${id}"`);
125148
continue;
126149
}
127-
this._terms.set(id, entries[id]);
150+
this._terms.set(id, value);
128151
} else {
129152
if (this._messages.has(id)) {
130153
errors.push(`Attempt to override an existing message: "${id}"`);
131154
continue;
132155
}
133-
this._messages.set(id, entries[id]);
156+
this._messages.set(id, value);
134157
}
135158
}
136159

fluent/src/resource.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import parse from "./parser";
2+
3+
/**
4+
* Fluent Resource is a structure storing a map
5+
* of localization entries.
6+
*/
7+
export default class FluentResource extends Map {
8+
constructor(entries, errors = []) {
9+
super(entries);
10+
this.errors = errors;
11+
}
12+
13+
static fromString(source) {
14+
const [entries, errors] = parse(source);
15+
return new FluentResource(Object.entries(entries), errors);
16+
}
17+
}
18+

0 commit comments

Comments
 (0)