Skip to content

Commit

Permalink
feat: add optional fallback getter when parsing string with shortcodes
Browse files Browse the repository at this point in the history
* add optional fallback method when parsing string with shortcodes
  • Loading branch information
ndelanou authored Mar 21, 2024
1 parent b4b27f5 commit c4f0376
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
11 changes: 8 additions & 3 deletions lib/src/emojis/emoji_parser.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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;
});
}

Expand Down
19 changes: 19 additions & 0 deletions test/src/emojis/emoji_parser_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit c4f0376

Please sign in to comment.