@flutterlocalisation/angular 0.0.0-stage → 1.23.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,40 @@
1
- # Temporary Holding Version
1
+ # @flutterlocalisation/angular
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Translate an Angular app with [FlutterLocalisation](https://flutterlocalisation.com), the
4
+ official Angular way: `@angular/localize`, an `@@id` on every message, `ng extract-i18n`, one
5
+ build per locale.
6
+
7
+ ```bash
8
+ ng add @flutterlocalisation/angular
9
+ ```
10
+
11
+ It sets up what `ng add @angular/localize` does (the polyfill, the types, the dependency),
12
+ makes `ng extract-i18n` write ARB to `src/locale`, names your source locale, installs the `fl`
13
+ command and adds three scripts:
14
+
15
+ | script | does |
16
+ |---|---|
17
+ | `npm run i18n:extract` | `ng extract-i18n`: writes `src/locale/messages.arb` |
18
+ | `npm run i18n:push` | extracts, then sends the strings, translated into every language |
19
+ | `npm run i18n:pull` | writes `messages.<locale>.arb` and lists each locale in `angular.json` |
20
+
21
+ Then `ng build --localize` builds every language.
22
+
23
+ ## Writing messages
24
+
25
+ ```html
26
+ <h1 i18n="@@home.title">Hello</h1>
27
+ <p i18n="@@home.greeting">Hello {{ name }}</p>
28
+ <span i18n="@@home.count">{count, plural, =0 {No posts yet} =1 {One post} other {{{count}} posts}}</span>
29
+ ```
30
+
31
+ ```ts
32
+ this.message = $localize`:@@toast.saved:Saved ${count}:count: posts`;
33
+ ```
34
+
35
+ Every message needs an `@@id`: without one Angular names it by a hash of its English text, and
36
+ the hash changes with every edit. A plural or select is the whole message, with the sentence
37
+ inside each case; inside a sentence Angular gives it a hash id of its own. `npx fl doctor`
38
+ lists both.
39
+
40
+ Options: `--locale-dir`, `--source-locale`, `--project`, `--skip-install`.
@@ -0,0 +1,10 @@
1
+ {
2
+ "$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json",
3
+ "schematics": {
4
+ "ng-add": {
5
+ "description": "Set up @angular/localize, ARB extraction and the fl command for FlutterLocalisation.",
6
+ "factory": "./src/ng-add/index#ngAdd",
7
+ "schema": "./src/ng-add/schema.json"
8
+ }
9
+ }
10
+ }
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@flutterlocalisation/angular",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "description": "ng add for FlutterLocalisation: sets up @angular/localize, ARB extraction and the fl command in an Angular app.",
4
+ "version": "1.23.1",
5
+ "license": "MIT",
6
+ "homepage": "https://flutterlocalisation.com",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/tajaouart/flutter_localisation_cli"
10
+ },
11
+ "author": "Aylan Technologies LLC",
12
+ "schematics": "./collection.json",
13
+ "ng-add": {
14
+ "save": "devDependencies"
15
+ },
16
+ "files": [
17
+ "collection.json",
18
+ "src",
19
+ "README.md"
20
+ ],
21
+ "peerDependencies": {
22
+ "@angular/core": ">=15.0.0"
23
+ },
24
+ "dependencies": {
25
+ "@angular-devkit/schematics": ">=15.0.0"
26
+ },
27
+ "keywords": [
28
+ "angular",
29
+ "i18n",
30
+ "localize",
31
+ "schematics",
32
+ "ng-add",
33
+ "translation",
34
+ "arb"
35
+ ]
36
+ }
@@ -0,0 +1,158 @@
1
+ 'use strict';
2
+ // `ng add @flutterlocalisation/angular`: the setup Angular's own
3
+ // `ng add @angular/localize` makes, plus ARB extraction into the locale
4
+ // folder, the `fl` command and three npm scripts. Running it again changes
5
+ // nothing that is already in place.
6
+ const { SchematicsException } = require('@angular-devkit/schematics');
7
+ const { NodePackageInstallTask } = require('@angular-devkit/schematics/tasks');
8
+
9
+ const LOCALIZE_POLYFILL = '@angular/localize/init';
10
+ const LOCALIZE_TYPES = '@angular/localize';
11
+
12
+ function readJson(tree, file) {
13
+ const buffer = tree.read(file);
14
+ if (!buffer) throw new SchematicsException(`${file} not found.`);
15
+ return JSON.parse(stripJsonComments(buffer.toString('utf8')));
16
+ }
17
+
18
+ function writeJson(tree, file, value) {
19
+ const text = JSON.stringify(value, null, 2) + '\n';
20
+ if (tree.read(file).toString('utf8') !== text) tree.overwrite(file, text);
21
+ }
22
+
23
+ // tsconfig files are JSON with comments; the comments go, the content stays.
24
+ function stripJsonComments(text) {
25
+ let out = '';
26
+ let inString = false;
27
+ for (let i = 0; i < text.length; i++) {
28
+ const c = text[i];
29
+ const next = text[i + 1];
30
+ if (inString) {
31
+ out += c;
32
+ if (c === '\\') { out += next; i++; } else if (c === '"') inString = false;
33
+ } else if (c === '"') {
34
+ inString = true;
35
+ out += c;
36
+ } else if (c === '/' && next === '/') {
37
+ while (i < text.length && text[i] !== '\n') i++;
38
+ out += '\n';
39
+ } else if (c === '/' && next === '*') {
40
+ i += 2;
41
+ while (i < text.length && !(text[i] === '*' && text[i + 1] === '/')) i++;
42
+ i++;
43
+ } else {
44
+ out += c;
45
+ }
46
+ }
47
+ return out.replace(/,(\s*[}\]])/g, '$1');
48
+ }
49
+
50
+ function pickProject(workspace, wanted) {
51
+ const projects = workspace.projects || {};
52
+ if (wanted) {
53
+ if (!projects[wanted]) throw new SchematicsException(`No project "${wanted}" in angular.json.`);
54
+ return [wanted, projects[wanted]];
55
+ }
56
+ const apps = Object.entries(projects).filter(([, p]) => p.projectType !== 'library');
57
+ if (!apps.length) throw new SchematicsException('angular.json has no application to set up.');
58
+ return apps.length === 1 ? apps[0] : (apps.find(([, p]) => (p.root || '') === '') || apps[0]);
59
+ }
60
+
61
+ function addPolyfill(options) {
62
+ if (!options) return false;
63
+ const list = options.polyfills == null ? [] : [].concat(options.polyfills);
64
+ if (list.includes(LOCALIZE_POLYFILL)) return false;
65
+ options.polyfills = [...list, LOCALIZE_POLYFILL];
66
+ return true;
67
+ }
68
+
69
+ function addTypes(tree, file) {
70
+ if (!file || !tree.exists(file)) return false;
71
+ const config = readJson(tree, file);
72
+ config.compilerOptions = config.compilerOptions || {};
73
+ const types = config.compilerOptions.types || [];
74
+ if (types.includes(LOCALIZE_TYPES)) return false;
75
+ config.compilerOptions.types = [...types, LOCALIZE_TYPES];
76
+ writeJson(tree, file, config);
77
+ return true;
78
+ }
79
+
80
+ function ngAdd(options) {
81
+ return (tree, context) => {
82
+ const workspace = readJson(tree, 'angular.json');
83
+ const [name, project] = pickProject(workspace, options.project);
84
+ const architect = project.architect || project.targets || {};
85
+ const dir = (options.localeDir || 'src/locale').replace(/\/+$/, '');
86
+ const done = [];
87
+
88
+ if (addPolyfill(architect.build && architect.build.options)) done.push('build polyfills');
89
+ if (addPolyfill(architect.test && architect.test.options)) done.push('test polyfills');
90
+
91
+ // The builder package the app already builds with: `@angular/build` from
92
+ // Angular 17.2 on, `@angular-devkit/build-angular` before.
93
+ const buildPackage = ((architect.build && architect.build.builder) || '').split(':')[0]
94
+ || '@angular-devkit/build-angular';
95
+ const extract = architect['extract-i18n'] || (architect['extract-i18n'] = {
96
+ builder: `${buildPackage}:extract-i18n`,
97
+ options: { buildTarget: `${name}:build` },
98
+ });
99
+ extract.options = extract.options || {};
100
+ if (extract.options.format !== 'arb' || extract.options.outputPath !== dir) {
101
+ extract.options.format = 'arb';
102
+ extract.options.outputPath = dir;
103
+ done.push(`extract-i18n writes ARB to ${dir}`);
104
+ }
105
+ project.i18n = project.i18n || {};
106
+ if (!project.i18n.sourceLocale) {
107
+ project.i18n.sourceLocale = options.sourceLocale || 'en';
108
+ done.push(`source locale ${project.i18n.sourceLocale}`);
109
+ }
110
+ project.i18n.locales = project.i18n.locales || {};
111
+ writeJson(tree, 'angular.json', workspace);
112
+
113
+ const buildOptions = (architect.build && architect.build.options) || {};
114
+ const testOptions = (architect.test && architect.test.options) || {};
115
+ if (addTypes(tree, buildOptions.tsConfig)) done.push(`${buildOptions.tsConfig} types`);
116
+ if (addTypes(tree, testOptions.tsConfig)) done.push(`${testOptions.tsConfig} types`);
117
+
118
+ const pkg = readJson(tree, 'package.json');
119
+ pkg.dependencies = pkg.dependencies || {};
120
+ pkg.devDependencies = pkg.devDependencies || {};
121
+ pkg.scripts = pkg.scripts || {};
122
+ const angular = pkg.dependencies['@angular/core'];
123
+ if (!pkg.dependencies['@angular/localize'] && !pkg.devDependencies['@angular/localize']) {
124
+ if (!angular) throw new SchematicsException('package.json has no @angular/core to match @angular/localize to.');
125
+ pkg.dependencies['@angular/localize'] = angular;
126
+ done.push(`@angular/localize ${angular}`);
127
+ }
128
+ if (!pkg.devDependencies['@flutterlocalisation/cli']) {
129
+ pkg.devDependencies['@flutterlocalisation/cli'] = `^${require('../../package.json').version}`;
130
+ done.push('@flutterlocalisation/cli');
131
+ }
132
+ const scripts = {
133
+ 'i18n:extract': 'ng extract-i18n',
134
+ 'i18n:push': `ng extract-i18n && fl import ${dir}/messages.arb --translate`,
135
+ 'i18n:pull': 'fl pull',
136
+ };
137
+ for (const [key, value] of Object.entries(scripts)) {
138
+ if (!pkg.scripts[key]) pkg.scripts[key] = value;
139
+ }
140
+ writeJson(tree, 'package.json', pkg);
141
+
142
+ if (!options.skipInstall) context.addTask(new NodePackageInstallTask());
143
+ context.logger.info(done.length
144
+ ? `FlutterLocalisation set up ${name}: ${done.join(', ')}.`
145
+ : `${name} was already set up for FlutterLocalisation.`);
146
+ context.logger.info([
147
+ 'Next:',
148
+ ' 1. Mark your text: <h1 i18n="@@home.title">Hello</h1>, $localize`:@@toast.saved:Saved`',
149
+ ' 2. npx fl init pick the project (create it in the dashboard first)',
150
+ ' 3. npm run i18n:push extract and send the strings, translated',
151
+ ' 4. npm run i18n:pull bring messages.<locale>.arb back, listed in angular.json',
152
+ ' 5. ng build --localize',
153
+ ].join('\n'));
154
+ return tree;
155
+ };
156
+ }
157
+
158
+ module.exports = { ngAdd, stripJsonComments, pickProject };
@@ -0,0 +1,27 @@
1
+ {
2
+ "$schema": "http://json-schema.org/schema",
3
+ "$id": "flutterlocalisation-ng-add",
4
+ "type": "object",
5
+ "properties": {
6
+ "project": {
7
+ "type": "string",
8
+ "description": "The application to set up; default: the only one, or the one at the workspace root.",
9
+ "$default": { "$source": "projectName" }
10
+ },
11
+ "localeDir": {
12
+ "type": "string",
13
+ "description": "Where messages.arb and messages.<locale>.arb live.",
14
+ "default": "src/locale"
15
+ },
16
+ "sourceLocale": {
17
+ "type": "string",
18
+ "description": "The language the app is written in, as Angular names it (en, en-US, fr).",
19
+ "default": "en"
20
+ },
21
+ "skipInstall": {
22
+ "type": "boolean",
23
+ "description": "Do not run the package manager afterwards.",
24
+ "default": false
25
+ }
26
+ }
27
+ }