| 1 |
// Copyright (c) 2022 Tulir Asokan |
| 2 |
// |
| 3 |
// This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
// License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 |
// file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 6 |
|
| 7 |
// Package variationselector provides utility functions for adding and removing emoji variation selectors (16) |
| 8 |
// that matches the suggestions in the Matrix spec. |
| 9 |
package variationselector |
| 10 |
|
| 11 |
import ( |
| 12 |
_ "embed" |
| 13 |
"encoding/json" |
| 14 |
"strings" |
| 15 |
) |
| 16 |
|
| 17 |
//go:generate ./generate.sh |
| 18 |
//go:embed emojis-with-variations.json |
| 19 |
var emojisWithVariationsJSON []byte |
| 20 |
|
| 21 |
var variationReplacer *strings.Replacer |
| 22 |
|
| 23 |
// The variation replacer will add incorrect variation selectors before skin tones, this removes those. |
| 24 |
var skinToneReplacer = strings.NewReplacer( |
| 25 |
"\ufe0f\U0001F3FB", "\U0001F3FB", |
| 26 |
"\ufe0f\U0001F3FC", "\U0001F3FC", |
| 27 |
"\ufe0f\U0001F3FD", "\U0001F3FD", |
| 28 |
"\ufe0f\U0001F3FE", "\U0001F3FE", |
| 29 |
"\ufe0f\U0001F3FF", "\U0001F3FF", |
| 30 |
) |
| 31 |
|
| 32 |
func init() { |
| 33 |
var emojisWithVariations []string |
| 34 |
err := json.Unmarshal(emojisWithVariationsJSON, &emojisWithVariations) |
| 35 |
if err != nil { |
| 36 |
panic(err) |
| 37 |
} |
| 38 |
replaceInput := make([]string, 2*len(emojisWithVariations)) |
| 39 |
for i, emoji := range emojisWithVariations { |
| 40 |
replaceInput[i*2] = emoji |
| 41 |
replaceInput[(i*2)+1] = emoji + VS16 |
| 42 |
} |
| 43 |
variationReplacer = strings.NewReplacer(replaceInput...) |
| 44 |
} |
| 45 |
|
| 46 |
const VS16 = "\ufe0f" |
| 47 |
|
| 48 |
// Add adds emoji variation selectors to all emojis that have multiple forms in the given string. |
| 49 |
// |
| 50 |
// This will remove all variation selectors first to make sure it doesn't add duplicates. |
| 51 |
func Add(val string) string { |
| 52 |
return skinToneReplacer.Replace(variationReplacer.Replace(Remove(val))) |
| 53 |
} |
| 54 |
|
| 55 |
// Remove removes all emoji variation selectors in the given string. |
| 56 |
func Remove(val string) string { |
| 57 |
return strings.ReplaceAll(val, VS16, "") |
| 58 |
} |