ui: code formatting with wastyle

This commit is contained in:
undefined committed 2021-04-15 13:49:33 +08:00
1 parent 496ce16dce
commit b052e2aa78
7 files changed
+64 -25

No files matched your search

@@ -1,14 +1,18 @@
import { AutoloadPage } from 'vj/misc/Page';
import load from 'vj/components/wastyle/index';
import Notification from 'vj/components/notification/index';
const highlighterPage = new AutoloadPage('highlighterPage', () => {
import('./prismjs').then((module) => {
const prismjs = module.default;
function runHighlight($container) {
prismjs.highlightBlocks($container);
}
runHighlight($('body'));
$(document).on('vjContentNew', (e) => runHighlight($(e.target)));
});
const highlighterPage = new AutoloadPage('highlighterPage', async () => {
const [{ default: prismjs }, [success, format]] = await Promise.all([
import('./prismjs'),
load(),
]);
if (!success) Notification.error(`Astyle load fail: ${format}`);
function runHighlight($container) {
prismjs.highlightBlocks($container, success ? format : null);
}
runHighlight($('body'));
$(document).on('vjContentNew', (e) => runHighlight($(e.target)));
});
export default highlighterPage;
@@ -11,7 +11,7 @@ To add a new language to highlight:
import Prism from 'prismjs';
import Clipboard from 'clipboard';
import Notification from 'vj/components/notification';
import Notification from 'vj/components/notification/index';
import i18n from 'vj/utils/i18n';
import languageMeta from './meta';
@@ -95,16 +95,24 @@ Prism.hooks.add('before-highlight', (env) => {
});
const prismjsApiWrap = {
highlightBlocks: ($dom) => {
highlightBlocks: ($dom, format) => {
$dom.find('pre code').get().forEach((code) => {
const $pre = $(code).parent();
const $code = $(code);
const $pre = $code.parent();
$pre.addClass('syntax-hl');
if ($pre.closest('[data-syntax-hl-show-line-number]')) {
$pre.addClass('line-numbers');
}
const language = ($(code).attr('class') || '').trim();
const astyle = language.match(/astyle-([a-z]+)/);
if (format && astyle && astyle[1]) {
const [success, result] = format($code.text(), `${UserContext.astyleOptions.trim()} mode=${astyle[1]}`);
console.log(success.result);
if (!success) Notification.error('Code format fail');
else $code.text(result.replace(/^#(include|import)[\t ]*(<|")/gm, (match, p1, p2) => `#${p1} ${p2}`));
}
// try to map the language name
const language = $(code).attr('class');
const m = (language || '').trim().match(/^language-(.+)$/);
const m = language.match(/language-([a-z]+)/);
if (m && m[1]) {
const languageName = m[1].toLowerCase();
if (languageExtMap[languageName]) {
@@ -0,0 +1,12 @@
import astyleBinaryUrl from 'wastyle/dist/astyle-optimize-size.wasm';
export default async function load() {
const { init, format } = await import('wastyle');
try {
await init(astyleBinaryUrl);
console.log('WAstyle is ready!');
return [true, format];
} catch (e) {
return [false, e.message];
}
}