2017-11-18 18:39:10 +00:00
|
|
|
import 'dart:async';
|
2017-04-04 23:05:16 +00:00
|
|
|
import 'dart:collection';
|
2017-11-18 18:39:10 +00:00
|
|
|
import 'package:file/file.dart';
|
2017-04-04 23:05:16 +00:00
|
|
|
|
2021-06-26 10:24:52 +00:00
|
|
|
import 'package:angel3_framework/angel3_framework.dart';
|
|
|
|
import 'package:angel3_mustache/src/mustache_context.dart';
|
2017-04-04 23:05:16 +00:00
|
|
|
|
2017-11-18 18:39:10 +00:00
|
|
|
class MustacheViewCache {
|
2021-06-20 12:37:20 +00:00
|
|
|
/// The context for which views and partials are
|
|
|
|
/// served from.
|
|
|
|
MustacheContext? context;
|
2017-04-04 23:05:16 +00:00
|
|
|
|
2021-06-20 12:37:20 +00:00
|
|
|
HashMap<String, String> viewCache = HashMap();
|
|
|
|
HashMap<String, String> partialCache = HashMap();
|
2017-04-04 23:05:16 +00:00
|
|
|
|
2017-11-18 18:39:10 +00:00
|
|
|
MustacheViewCache([this.context]);
|
2017-04-04 23:05:16 +00:00
|
|
|
|
2021-06-20 12:37:20 +00:00
|
|
|
Future<String?> getView(String viewName, Angel app) async {
|
|
|
|
if (app.environment.isProduction) {
|
2017-04-04 23:05:16 +00:00
|
|
|
if (viewCache.containsKey(viewName)) {
|
|
|
|
return viewCache[viewName];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-20 12:37:20 +00:00
|
|
|
var viewFile = context?.resolveView(viewName);
|
|
|
|
if (viewFile == null) {
|
|
|
|
throw FileSystemException('View "$viewName" was not found.', 'null');
|
|
|
|
}
|
2017-04-04 23:05:16 +00:00
|
|
|
|
2017-11-18 18:39:10 +00:00
|
|
|
if (viewFile.existsSync()) {
|
2021-06-20 12:37:20 +00:00
|
|
|
var viewTemplate = await viewFile.readAsString();
|
|
|
|
if (app.environment.isProduction) {
|
|
|
|
viewCache[viewName] = viewTemplate;
|
2017-04-04 23:05:16 +00:00
|
|
|
}
|
|
|
|
return viewTemplate;
|
2021-06-20 12:37:20 +00:00
|
|
|
} else {
|
|
|
|
throw FileSystemException(
|
2017-04-05 20:38:03 +00:00
|
|
|
'View "$viewName" was not found.', viewFile.path);
|
2021-06-20 12:37:20 +00:00
|
|
|
}
|
2017-04-04 23:05:16 +00:00
|
|
|
}
|
|
|
|
|
2021-06-20 12:37:20 +00:00
|
|
|
String? getPartialSync(String partialName, Angel app) {
|
|
|
|
if (app.environment.isProduction) {
|
2017-04-04 23:05:16 +00:00
|
|
|
if (partialCache.containsKey(partialName)) {
|
|
|
|
return partialCache[partialName];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-20 12:37:20 +00:00
|
|
|
var partialFile = context!.resolvePartial(partialName);
|
2017-04-04 23:05:16 +00:00
|
|
|
|
2017-04-05 20:38:03 +00:00
|
|
|
if (partialFile.existsSync()) {
|
2021-06-20 12:37:20 +00:00
|
|
|
var partialTemplate = partialFile.readAsStringSync();
|
|
|
|
if (app.environment.isProduction) {
|
|
|
|
partialCache[partialName] = partialTemplate;
|
2017-04-04 23:05:16 +00:00
|
|
|
}
|
|
|
|
return partialTemplate;
|
2021-06-20 12:37:20 +00:00
|
|
|
} else {
|
|
|
|
throw FileSystemException(
|
2017-04-05 20:38:03 +00:00
|
|
|
'View "$partialName" was not found.', partialFile.path);
|
2021-06-20 12:37:20 +00:00
|
|
|
}
|
2017-04-04 23:05:16 +00:00
|
|
|
}
|
|
|
|
}
|