diff --git a/mobile/lib/shared/push/notification_body.dart b/mobile/lib/shared/push/notification_body.dart new file mode 100644 index 0000000000..f1b677888c --- /dev/null +++ b/mobile/lib/shared/push/notification_body.dart @@ -0,0 +1,120 @@ +import 'package:characters/characters.dart'; + +/// Longest notification body, in UTF-16 code units. iOS shows at most this +/// much of a body, so every platform's body fits in it. See +/// docs/adr/0002-notification-message-text.md. +const int notificationBodyLimit = 256; + +/// Most of a message's content, in UTF-16 code units, that the body is built +/// from. The regexes below can take quadratic time on unclosed markup and +/// content can be up to 256 KB, so a long message is cut first. +const int notificationBodyInputLimit = 4096; + +/// Plain-text notification body for a Markdown message, as ADR 0002 defines it +/// and `test-fixtures/notification-body.json` checks it. It is a port of +/// `BuzzPushNotificationResolver.previewBody` in `BuzzPushKit`: change the two +/// together. +/// +/// Code and URLs stay as written, line breaks are kept, and the Markdown +/// syntax for code, links, images, bold and strikethrough is removed. Runs of +/// spaces collapse outside code. A body over [notificationBodyLimit] code +/// units, or built from content cut at [notificationBodyInputLimit], keeps +/// whole characters up to one unit short of the limit and ends with "…". +String notificationBody(String content) { + var input = content; + final cut = input.length > notificationBodyInputLimit; + if (cut) { + final kept = StringBuffer(); + var units = 0; + for (final character in input.characters) { + units += character.length; + if (units > notificationBodyInputLimit) break; + kept.write(character); + } + input = kept.toString(); + } + input = input + .replaceAll('\r\n', '\n') + .replaceAll(_codeOpen, '') + .replaceAll(_codeClose, ''); + + // Swap each code span for a placeholder while the prose rules run over the + // whole text, so a link label or a bold run can contain code. + final codes = []; + final prose = StringBuffer(); + var position = 0; + for (final match in _code.allMatches(input)) { + prose.write(input.substring(position, match.start)); + final body = match.group(1) ?? match.group(3) ?? match.group(4)!; + prose + ..write(_codeOpen) + ..write(codes.length) + ..write(_codeClose); + codes.add(body); + position = match.end; + } + prose.write(input.substring(position)); + + final stripped = _stripProse(prose.toString()); + var result = stripped.replaceAllMapped( + _codePlaceholder, + (match) => codes[int.parse(match.group(1)!)], + ); + result = result + .replaceAll(RegExp(r'[ \t]+\n'), '\n') + .replaceAll(RegExp(r'\n{3,}'), '\n\n'); + result = _trim(result); + if (!cut && result.length <= notificationBodyLimit) return result; + + final kept = StringBuffer(); + var units = 0; + for (final character in result.characters) { + units += character.length; + if (units >= notificationBodyLimit) break; + kept.write(character); + } + return '${_trim(kept.toString())}…'; +} + +// The patterns below keep ICU regex semantics, which the iOS formatter uses, +// not Dart's. ICU's `\s` is `\p{White_Space}`, listed here, and its `.` +// excludes every line terminator: U+000A to U+000D, U+0085, U+2028, U+2029. +const _space = + r'\t-\r \u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000'; +const _notLineEnd = r'[^\n-\r\u0085\u2028\u2029]'; + +/// A fenced span on one line, a fenced code block, or an inline code span. A +/// block's opening line (a fence of three or more backticks, then an optional +/// language) is dropped, and the block closes only at a fence at least as long +/// that ends its line, so backticks inside the code (a "```" string literal) +/// don't end it. A fence with no closing fence runs to the end of the text, as +/// in CommonMark, which also covers a block cut by [notificationBodyInputLimit]. +/// Group 2 is the block's fence; the others hold code. +final _code = RegExp( + r'```([^\n]*?)(?:```|$)' + r'|(`{3,})[^\n]*\n([\s\S]*?)(?:\n?\2`*[ \t]*(?=\n|$)|$)' + r'|`([^`\n]*)`', +); + +/// Stands in for a code span while the prose rules run. Private-use +/// characters, removed from the content first, so they can't collide. +const _codeOpen = '\uE000'; +const _codeClose = '\uE001'; +final _codePlaceholder = RegExp('$_codeOpen([0-9]+)$_codeClose'); + +final _link = RegExp(r'!?\[([^\]]*)\]\([^)]*\)'); +final _emphasis = RegExp( + '(\\*\\*|~~)([^$_space](?:$_notLineEnd*?[^$_space])??)\\1', +); +final _spaces = RegExp(r'[ \t]+'); + +String _stripProse(String prose) => prose + .replaceAllMapped(_link, (match) => match.group(1)!) + .replaceAllMapped(_emphasis, (match) => match.group(2)!) + .replaceAll(_spaces, ' '); + +/// Trims the characters Swift's `whitespacesAndNewlines` does: ICU's +/// whitespace and U+200B. Unlike Dart's `String.trim`, it leaves U+FEFF alone. +final _edgeWhitespace = RegExp('^[$_space\\u200B]+|[$_space\\u200B]+\$'); + +String _trim(String text) => text.replaceAll(_edgeWhitespace, ''); diff --git a/mobile/test/shared/push/notification_body_test.dart b/mobile/test/shared/push/notification_body_test.dart new file mode 100644 index 0000000000..e5a6080872 --- /dev/null +++ b/mobile/test/shared/push/notification_body_test.dart @@ -0,0 +1,30 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:buzz/shared/push/notification_body.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + // The contract every platform runs: docs/adr/0002-notification-message-text.md. + final fixture = + jsonDecode( + File('../test-fixtures/notification-body.json').readAsStringSync(), + ) + as Map; + final cases = fixture['cases'] as List; + + test('the fixture is the one this formatter was written for', () { + expect(fixture['schemaVersion'], 1); + expect(notificationBodyLimit, fixture['maxLength']); + expect(cases, isNotEmpty); + }); + + for (final testCase in cases) { + test('notification-body fixture: ${testCase['name']}', () { + expect( + notificationBody(testCase['input'] as String), + testCase['expected'] as String, + ); + }); + } +} diff --git a/test-fixtures/notification-body.json b/test-fixtures/notification-body.json index a10ab255e2..990bf74200 100644 --- a/test-fixtures/notification-body.json +++ b/test-fixtures/notification-body.json @@ -201,6 +201,46 @@ "name": "extended grapheme is never partially kept", "input": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx👩‍💻ab", "expected": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx…" + }, + { + "name": "a vertical tab beside a marker is whitespace, so the marker stays", + "input": "**\u000Bx**", + "expected": "**\u000Bx**" + }, + { + "name": "a next line beside a marker is whitespace, so the marker stays", + "input": "**x\u0085**", + "expected": "**x\u0085**" + }, + { + "name": "a form feed ends a bold run's line", + "input": "**x\u000Cy**", + "expected": "**x\u000Cy**" + }, + { + "name": "a vertical tab ends a strikethrough run's line", + "input": "~~x\u000By~~", + "expected": "~~x\u000By~~" + }, + { + "name": "zero-width spaces at the edges are trimmed", + "input": "\u200Bx\u200B", + "expected": "x" + }, + { + "name": "a message of only zero-width spaces has an empty body", + "input": "\u200B\u200B", + "expected": "" + }, + { + "name": "a leading zero-width space doesn't count toward the limit", + "input": "\u200Bxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "expected": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + }, + { + "name": "byte order marks at the edges stay", + "input": "\uFEFFx\uFEFF", + "expected": "\uFEFFx\uFEFF" } ] }