From c4f03765e5d5ed92681ae393ae1bb139c96b7896 Mon Sep 17 00:00:00 2001 From: ndelanou Date: Thu, 21 Mar 2024 21:12:26 +0100 Subject: [PATCH] feat: add optional fallback getter when parsing string with shortcodes * add optional fallback method when parsing string with shortcodes --- lib/src/emojis/emoji_parser.dart | 11 ++++++++--- test/src/emojis/emoji_parser_test.dart | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/lib/src/emojis/emoji_parser.dart b/lib/src/emojis/emoji_parser.dart index a2d947c..b49390e 100644 --- a/lib/src/emojis/emoji_parser.dart +++ b/lib/src/emojis/emoji_parser.dart @@ -102,16 +102,21 @@ class EmojiParser { String toShortcodes([Platform platform = Platform.Default]) { return _value.splitMapJoin(Regex.emoji, onMatch: (m) { final match = m.group(0)!; - return _emojis.getOne(match).shortcodes.wherePlatform(platform) ?? match; + return _emojis.getOneOrNull(match)?.shortcodes.wherePlatform(platform) ?? + match; }); } /// Converts the emojis in [_value] from shortcode format to Unicode characters. /// Shortcodes are the text-based representations of emojis used by some platforms. /// Returns a new String with the converted emojis. - String fromShortcodes() { + String fromShortcodes( + {String Function(String unknownShortcode)? onUnknownShortcode}) { return _value.splitMapJoin(Regex.shortcode, onMatch: (m) { - return _emojis.getOne(m.group(0)!.removeColons()).value; + final match = m.group(0)!; + return _emojis.getOneOrNull(match.removeColons())?.value ?? + onUnknownShortcode?.call(match) ?? + match; }); } diff --git a/test/src/emojis/emoji_parser_test.dart b/test/src/emojis/emoji_parser_test.dart index 72248f0..e4b7668 100644 --- a/test/src/emojis/emoji_parser_test.dart +++ b/test/src/emojis/emoji_parser_test.dart @@ -257,6 +257,25 @@ void main() { expect(value, expected); }); + test( + 'fromShortcodes() returns this raw shortcode when the shortcode does not exist and no replacement method is provided', + () { + const text = ':man: :this-shortcode-does-not-exist: :woman:'; + final value = EmojiParser(text).fromShortcodes(); + const expected = '👨 :this-shortcode-does-not-exist: 👩'; + expect(value, expected); + }); + + test( + 'fromShortcodes() returns this replacement text when shortcode cannot be found and a replacement method is provided', + () { + const text = ':man: :this-shortcode-does-not-exist: :woman:'; + final value = + EmojiParser(text).fromShortcodes(onUnknownShortcode: (_) => '🤷'); + const expected = '👨 🤷 👩'; + expect(value, expected); + }); + test('get returns list of emojis from given text', () { const text = 'text😀text🤦🏾‍♀️text'; final value = EmojiParser(text).get;