platform/packages/jael/angel_jael/lib/angel3_jael.dart

72 lines
2.4 KiB
Dart
Raw Normal View History

2021-05-15 10:45:39 +00:00
import 'package:angel3_framework/angel3_framework.dart';
import 'package:angel3_code_buffer/angel3_code_buffer.dart';
2017-09-30 23:01:30 +00:00
import 'package:file/file.dart';
2021-05-15 10:45:39 +00:00
import 'package:jael3/jael3.dart';
import 'package:jael3_preprocessor/jael3_preprocessor.dart';
import 'package:belatuk_symbol_table/belatuk_symbol_table.dart';
2017-09-30 23:01:30 +00:00
2017-10-01 03:14:44 +00:00
/// Configures an Angel server to use Jael to render templates.
///
/// To enable "minified" output, you need to override the [createBuffer] function,
/// to instantiate a [CodeBuffer] that emits no spaces or line breaks.
2017-10-02 16:12:51 +00:00
///
/// To apply additional transforms to parsed documents, provide a set of [patch] functions.
2017-09-30 23:01:30 +00:00
AngelConfigurer jael(Directory viewsDirectory,
2021-04-30 07:19:26 +00:00
{String? fileExtension,
bool strictResolution = false,
bool cacheViews = false,
Iterable<Patcher>? patch,
bool asDSX = false,
CodeBuffer createBuffer()?}) {
var cache = <String, Document?>{};
2018-11-10 21:48:03 +00:00
fileExtension ??= '.jael';
2021-05-15 10:45:39 +00:00
createBuffer ??= () => CodeBuffer();
2017-09-30 23:01:30 +00:00
return (Angel app) async {
2021-04-30 07:19:26 +00:00
app.viewGenerator = (String name, [Map? locals]) async {
2017-09-30 23:01:30 +00:00
var errors = <JaelError>[];
2021-04-30 07:19:26 +00:00
Document? processed;
2017-10-01 03:14:44 +00:00
if (cacheViews == true && cache.containsKey(name)) {
processed = cache[name];
} else {
2021-04-30 07:19:26 +00:00
var file = viewsDirectory.childFile(name + fileExtension!);
2017-10-01 03:14:44 +00:00
var contents = await file.readAsString();
2018-06-26 15:31:34 +00:00
var doc = parseDocument(contents,
2021-04-30 07:19:26 +00:00
sourceUrl: file.uri, asDSX: asDSX == true, onError: errors.add)!;
2017-10-01 03:14:44 +00:00
processed = doc;
try {
2021-04-30 07:19:26 +00:00
processed = await (resolve(doc, viewsDirectory,
patch: patch, onError: errors.add));
2017-10-01 03:14:44 +00:00
} catch (_) {
// Ignore these errors, so that we can show syntax errors.
}
if (cacheViews == true) {
cache[name] = processed;
}
2017-09-30 23:01:30 +00:00
}
2021-04-30 07:19:26 +00:00
var buf = createBuffer!();
var scope = SymbolTable(
values: locals?.keys.fold<Map<String, dynamic>>(<String, dynamic>{},
2018-07-15 20:41:43 +00:00
(out, k) => out..[k.toString()] = locals[k]) ??
<String, dynamic>{});
2017-09-30 23:01:30 +00:00
if (errors.isEmpty) {
try {
2021-04-30 07:19:26 +00:00
const Renderer().render(processed!, buf, scope,
2017-10-16 23:20:02 +00:00
strictResolution: strictResolution == true);
2017-09-30 23:01:30 +00:00
return buf.toString();
} on JaelError catch (e) {
errors.add(e);
}
}
2018-06-26 15:31:34 +00:00
Renderer.errorDocument(errors, buf..clear());
2017-09-30 23:01:30 +00:00
return buf.toString();
};
};
}