Files
mixly3/common/modules/mixly-modules/common/code-formatter.js
2026-01-13 02:54:45 +08:00

60 lines
1.6 KiB
JavaScript

goog.loadJs('common', () => {
goog.require('workerpool');
goog.provide('Mixly.Registry');
goog.provide('Mixly.CodeFormatter');
const {
Registry,
CodeFormatter
} = Mixly;
CodeFormatter.supportCodeFormatters_ = new Registry();
CodeFormatter.activeCodeFormatters_ = new Registry();
CodeFormatter.supportCodeFormatters_.register('python', {
name: 'pythonFormatterService',
path: '../common/modules/mixly-modules/workers/common/python-formatter/index.js'
});
CodeFormatter.supportCodeFormatters_.register('cpp', {
name: 'cppFormatterService',
path: '../common/modules/mixly-modules/workers/common/cpp-formatter/index.js'
});
CodeFormatter.activateFormatter = async function (type) {
if (!this.supportCodeFormatters_.hasKey(type)) {
return null;
}
const info = this.supportCodeFormatters_.getItem(type);
if (this.activeCodeFormatters_.hasKey(type)) {
const formatter = this.activeCodeFormatters_.getItem(type);
if (formatter.loading) {
await formatter.loading;
}
return formatter;
}
const formatter = workerpool.pool(info.path, {
workerOpts: {
name: info.name
},
workerType: 'web'
});
formatter.loading = formatter.exec('init');
this.activeCodeFormatters_.register(type, formatter);
await formatter.loading;
formatter.loading = null;
return formatter;
}
CodeFormatter.format = async function (type, code) {
const formatter = await this.activateFormatter(type);
if (!formatter) {
return code;
}
const formattedCode = await formatter.exec('format', [code]);
return formattedCode;
}
});