tachybase_todo/packages/plugins/@nocobase/plugin-localization-management/src/server/plugin.ts

151 lines
4.6 KiB
TypeScript
Raw Normal View History

import { Model } from '@nocobase/database';
import { UiSchemaStoragePlugin } from '@nocobase/plugin-ui-schema-storage';
import { InstallOptions, Plugin } from '@nocobase/server';
import deepmerge from 'deepmerge';
import { resolve } from 'path';
import localization from './actions/localization';
import localizationTexts from './actions/localizationTexts';
import Resources from './resources';
import { getTextsFromDBRecord } from './utils';
export class LocalizationManagementPlugin extends Plugin {
resources: Resources;
registerUISchemahook(plugin?: UiSchemaStoragePlugin) {
const uiSchemaStoragePlugin = plugin || this.app.getPlugin<UiSchemaStoragePlugin>('ui-schema-storage');
if (!uiSchemaStoragePlugin) {
return;
}
uiSchemaStoragePlugin.serverHooks.register('onSelfSave', 'extractTextToLocale', async ({ schemaInstance }) => {
const schema = schemaInstance.get('schema');
const title = schema?.title || schema?.['x-component-props']?.title;
if (!title) {
return;
}
const result = await this.resources.filterExists([title]);
if (!result.length) {
return;
}
this.db
.getRepository('localizationTexts')
.create({
values: {
module: 'resources.client',
text: title,
},
})
.then((res) => this.resources.updateCacheTexts([res]))
.catch((err) => {});
});
}
afterAdd() {}
beforeLoad() {}
async load() {
await this.db.import({
directory: resolve(__dirname, 'collections'),
});
this.db.addMigrations({
namespace: 'localization-management',
directory: resolve(__dirname, 'migrations'),
context: {
plugin: this,
},
});
this.app.resource({
name: 'localizationTexts',
actions: localizationTexts,
});
this.app.resource({
name: 'localization',
actions: localization,
});
this.app.acl.registerSnippet({
name: `pm.${this.name}.localization`,
actions: ['localization:*', 'localizationTexts:*', 'localizationTranslations:*'],
});
this.db.on('afterSave', async (instance: Model) => {
const model = instance.constructor as typeof Model;
const collection = model.collection;
refactor!: plugins build and plugins load (#2253) * refactor: plugin build and plugin template * refactor: plugins' deps * refactor: plugins bugs * feat: add plugin static middleware * fix: bugs * refactor: frontend plugin add from remote * refactor: delete useless app/client/plugins * fix: requirejs move to local * fix: tests case * refactor: add src/client and src/server dir check * fix: lodash tree shaking * refactor: add BUILD_TIP * refactor: add file size tip * fix: bugs * fix: bug * fix: change china-division * fix: change plugins response * fix: recover dynamicImport * fix: change server src entry * fix: test error * fix: plugins sourcemap => false * fix: production file error * refactor: change build tools to vite and tsup * fix: yarn.lock * fix: bugs * fix: server build bugs * fix: delete .fatherrc.ts * fix: bug * fix: bug * fix: bugs * fix: bugs * fix: bugs * refactor: add plugin d.ts * refactor: delete fatherrc * refactor: delete father scripts * refactor: build bug * fix: bug * fix: deps adjust * fix: add build tips * fix: bug * refactor: ignore plugins when build client * docs: update doc * refactor: docs and build * fix: bug * refactor: build deps * fix: add USER_REMOTE_PLUGIN env * feat: add plugin static cache * feat: add build deps cache * fix: bugs * test: add test * fix: add plugin depden on plugin tip * fix: adjust shouldDevDependencies * fix: deps * fix: ajust deps * fix: mobile style error * fix: map error * fix: test * fix: bug * feat: lodash and dayjs import from themself * feat: @emotion/css 、ahooks and lodash to global * fix: theme-editor plugin error * fix: review * feat: move all plugins' dependencies to devDependencies * feat: change build * feat: add devPlugins * fix: bug * fix: bugs * fix: bugs * fix: bugs * feat: build bugs * fix: bugs * fix: bugs * fix: review * fix: bug * fix: change deps build * fix: bugs * fix: bug * fix: bug * fix: bugs * fix: bug * fix: bug * fix: multi language * fix: dist * fix: cronstrue * fix: getPackageClientStaticUrl * fix: antd dayjs locale * fix: plugin' d.ts import from dist * fix: multi language * fix: build types error * fix: requireModule * fix: plugin lifecycle * fix: client resource * fix: improve code * fix: locale * feat: custom build * fix: require locale * fix: improve code * fix: improve code * fix: skip preset * fix: collection undefined * feat: yarn build * fix: remove enabled * fix: update dockerfile * fix: formily version * docs: update v12 changelog * fix: devDependencies * feat: @nocobase/app * feat: generateAppDir * fix: improve code * fix: 0.11.1-alpha.5 * fix: missing @nocobase/client * fix: error * fix: add .npmignore * feat: upgrade antd version * fix: dependencies * fix: peerDependencies * fix: remove china-division dep * fix: toposort deps * fix: update dockerfile * fix: plugin template * fix: app client outputPath * feat: update docs * fix: nginx server root * fix: storage/.app-dev * fix: getChinaDivisionData * feat: plugin info * feat: update docs * fix: docs menu --------- Co-authored-by: chenos <chenlinxh@gmail.com>
2023-08-02 00:07:52 +08:00
if (!collection) {
return;
}
let texts = [];
const fields = Array.from(collection.fields.values())
.filter((field) => field.options?.translation && instance['_changed'].has(field.name))
.map((field) => field.name);
if (!fields.length) {
return;
}
const textsFromDB = getTextsFromDBRecord(fields, instance);
textsFromDB.forEach((text) => {
texts.push(text);
});
texts = await this.resources.filterExists(texts);
this.db
.getModel('localizationTexts')
.bulkCreate(texts.map((text) => ({ module: 'resources.client', text })))
.then((newTexts) => this.resources.updateCacheTexts(newTexts))
.catch((err) => {});
});
this.resources = new Resources(this.db);
this.registerUISchemahook();
this.app.resourcer.use(async (ctx, next) => {
await next();
const { resourceName, actionName } = ctx.action.params;
if (resourceName === 'app' && actionName === 'getLang') {
const custom = await this.resources.getResources(ctx.get('X-Locale') || 'en-US');
const appLang = ctx.body;
const resources = {};
Object.keys(appLang.resources).forEach((key) => {
const resource = custom[`resources.${key}`];
resources[key] = resource ? deepmerge(appLang.resources[key], resource) : { ...appLang.resources[key] };
});
// For duplicate texts, use translations from client to override translations in other modules
const client = resources['client'] || {};
Object.keys(resources).forEach((key) => {
if (key === 'client') {
return;
}
Object.keys(resources[key]).forEach((text) => {
if (client[text]) {
resources[key][text] = client[text];
}
});
});
ctx.body = {
...appLang,
resources,
};
}
});
}
async install(options?: InstallOptions) {}
async afterEnable() {}
async afterDisable() {
const uiSchemaStoragePlugin = this.app.getPlugin<UiSchemaStoragePlugin>('ui-schema-storage');
if (!uiSchemaStoragePlugin) {
return;
}
uiSchemaStoragePlugin.serverHooks.remove('onSelfSave', 'extractTextToLocale');
}
async remove() {}
}
export default LocalizationManagementPlugin;