rule.dart 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import '../document/attribute.dart';
  2. import '../document/document.dart';
  3. import '../quill_delta.dart';
  4. import 'insert.dart';
  5. import 'delete.dart';
  6. import 'format.dart';
  7. enum RuleType {
  8. INSERT,
  9. DELETE,
  10. FORMAT,
  11. }
  12. abstract class Rule {
  13. const Rule();
  14. RuleType get type;
  15. Delta? apply(Delta document, int index,
  16. {int? length, Object? data, Attribute? attribute}) {
  17. validateArgs(length, data, attribute);
  18. return applyRule(
  19. document,
  20. index,
  21. length: length,
  22. data: data,
  23. attribute: attribute,
  24. );
  25. }
  26. Delta? applyRule(Delta document, int index,
  27. {int? length, Object? data, Attribute? attribute});
  28. void validateArgs(int? length, Object? data, Attribute? attribute);
  29. }
  30. class Rules {
  31. Rules(this._rules);
  32. final List<Rule> _rules;
  33. static final Rules _instance = Rules([
  34. const FormatLinkAtCaretPositionRule(),
  35. const ResolveLineFormatRule(),
  36. const ResolveInlineFormatRule(),
  37. const InsertEmbedsRule(),
  38. const ForceNewlineForInsertsAroundEmbedRule(),
  39. const AutoExitBlockRule(),
  40. const PreserveBlockStyleOnInsertRule(),
  41. const PreserveLineStyleOnSplitRule(),
  42. const ResetLineFormatOnNewLineRule(),
  43. const AutoFormatLinksRule(),
  44. const PreserveInlineStylesRule(),
  45. const CatchAllInsertRule(),
  46. const EnsureEmbedLineRule(),
  47. const PreserveLineStyleOnMergeRule(),
  48. const CatchAllDeleteRule(),
  49. ]);
  50. static Rules getInstance() => _instance;
  51. Delta apply(RuleType ruleType, Document document, int index,
  52. {int? length, Object? data, Attribute? attribute}) {
  53. final delta = document.toDelta();
  54. for (final rule in _rules) {
  55. if (rule.type != ruleType) {
  56. continue;
  57. }
  58. try {
  59. final result = rule.apply(delta, index,
  60. length: length, data: data, attribute: attribute);
  61. if (result != null) {
  62. return result..trim();
  63. }
  64. } catch (e) {
  65. rethrow;
  66. }
  67. }
  68. throw 'Apply rules failed';
  69. }
  70. }