Skip to content

Add FluentResource #244

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 10, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 28 additions & 5 deletions fluent/src/context.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import resolve from "./resolver";
import parse from "./parser";
import FluentResource from "./resource";

/**
* Message contexts are single-language stores of translations. They are
Expand Down Expand Up @@ -115,22 +115,45 @@ export class MessageContext {
* @returns {Array<Error>}
*/
addMessages(source) {
const [entries, errors] = parse(source);
for (const id in entries) {
const res = FluentResource.fromString(source);
return this.addResource(res);
}

/**
* Add a translation resource to the context.
*
* The translation resource must be a proper FluentResource
* parsed by `MessageContext.parseResource`.
*
* let res = MessageContext.parseResource("foo = Foo");
* ctx.addResource(res);
* ctx.getMessage('foo');
*
* // Returns a raw representation of the 'foo' message.
*
* Parsed entities should be formatted with the `format` method in case they
* contain logic (references, select expressions etc.).
*
* @param {FluentResource} res - FluentResource object.
* @returns {Array<Error>}
*/
addResource(res) {
const errors = res.errors.slice();
for (const [id, value] of res) {
if (id.startsWith("-")) {
// Identifiers starting with a dash (-) define terms. Terms are private
// and cannot be retrieved from MessageContext.
if (this._terms.has(id)) {
errors.push(`Attempt to override an existing term: "${id}"`);
continue;
}
this._terms.set(id, entries[id]);
this._terms.set(id, value);
} else {
if (this._messages.has(id)) {
errors.push(`Attempt to override an existing message: "${id}"`);
continue;
}
this._messages.set(id, entries[id]);
this._messages.set(id, value);
}
}

Expand Down
18 changes: 18 additions & 0 deletions fluent/src/resource.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import parse from "./parser";

/**
* Fluent Resource is a structure storing a map
* of localization entries.
*/
export default class FluentResource extends Map {
constructor(entries, errors = []) {
super(entries);
this.errors = errors;
}

static fromString(source) {
const [entries, errors] = parse(source);
return new FluentResource(Object.entries(entries), errors);
}
}