A platform for community discussion. Free, open, simple.
FEATURE: Add an animated emoji component and use it for live reactions (#45305)
Rafael dos Santos Silvaf72218bc9f1a
diff --git a/app/models/emoji.rb b/app/models/emoji.rbindex 094d89f6e13..2221c756abc 100644--- a/app/models/emoji.rb+++ b/app/models/emoji.rb@@ -2,7 +2,7 @@class Emoji# update this to clear the cache- EMOJI_VERSION = "15"+ EMOJI_VERSION = "16"FITZPATRICK_SCALE = %w[1f3fb 1f3fc 1f3fd 1f3fe 1f3ff]@@ -13,7 +13,7 @@ class Emojiinclude ActiveModel::SerializerSupport- attr_accessor :name, :url, :tonable, :group, :created_by+ attr_accessor :name, :url, :tonable, :animated, :group, :created_by# The cached `url` is the raw upload/asset URL. CDN conversion is applied# lazily here (and in EmojiSerializer) so that changing the S3/asset CDN@@ -81,6 +81,14 @@ class Emojitonable_emojis_dbend+ # Only some standard emojis are animated; those that are, are in every tone.+ def self.animated_emojis+ @animated_emojis ||=+ Dir+ .glob("*.avif", base: File.join(DiscourseEmojis.path_for_emojis, "noto_animated"))+ .to_set { File.basename(_1, ".avif") }+ end+def self.normalize_name(name)match = name.match(/\A:?(.+?)(?::t([1-6]))?:?\z/)[match[1], match[2]&.to_i]@@ -132,6 +140,7 @@ class EmojiEmoji.new.tap do |e|e.name = namee.tonable = Emoji.tonable_emojis.include?(name)+ e.animated = Emoji.animated_emojis.include?(name)e.url = Emoji.url_for(filename)e.group = groupenddiff --git a/docs/developer-guides/docs/03-code-internals/02-ui-kit.md b/docs/developer-guides/docs/03-code-internals/02-ui-kit.mdindex f94a49ca857..b5030340f73 100644--- a/docs/developer-guides/docs/03-code-internals/02-ui-kit.md+++ b/docs/developer-guides/docs/03-code-internals/02-ui-kit.md@@ -129,6 +129,7 @@ Form-level composition belongs to [FormKit](22-form-kit.md). These are the under| `DInterpolatedTranslation`, `DCountI18n` | Translations whose placeholders are components or counts. || `DRelativeDate` | A live-updating relative timestamp. || `DCdnImg`, `DLightDarkImg` | Images that follow the CDN and the colour scheme. |+| `DAnimatedEmoji` | An emoji animated where an animation exists, static otherwise. |## Users, avatars, and categoriesdiff --git a/frontend/discourse/app/components/emoji-picker/content.gjs b/frontend/discourse/app/components/emoji-picker/content.gjsindex dfb552b6044..5e87637f87b 100644--- a/frontend/discourse/app/components/emoji-picker/content.gjs+++ b/frontend/discourse/app/components/emoji-picker/content.gjs@@ -13,7 +13,6 @@ import PluginOutlet from "discourse/components/plugin-outlet";import lazyHash from "discourse/helpers/lazy-hash";import noop from "discourse/helpers/noop";import withEventValue from "discourse/helpers/with-event-value";-import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";import { uniqueItemsFromArray } from "discourse/lib/array-tools";import { lock, unlock } from "discourse/lib/body-scroll-lock";@@ -364,7 +363,7 @@ export default class EmojiPicker extends Component {this.loading = true;try {- this.emojiStore.list = await ajax("/emojis.json");+ await this.emojiStore.loadList();// we cant filter an empty list so have to wait for itthis.didInputFilter(this.term);diff --git a/frontend/discourse/app/lib/text.js b/frontend/discourse/app/lib/text.jsindex 80ac0535cf5..99af7b87a3d 100644--- a/frontend/discourse/app/lib/text.js+++ b/frontend/discourse/app/lib/text.js@@ -1,6 +1,10 @@import { waitForPromise } from "@ember/test-waiters";import AllowLister from "pretty-text/allow-lister";-import { buildEmojiUrl, performEmojiUnescape } from "pretty-text/emoji";+import {+ buildAnimatedEmojiUrl,+ buildEmojiUrl,+ performEmojiUnescape,+} from "pretty-text/emoji";import { sanitize as textSanitize } from "pretty-text/sanitizer";import deprecated from "discourse/lib/deprecated";import { getURLWithCDN } from "discourse/lib/get-url";@@ -97,6 +101,13 @@ export function emojiUrlFor(code) {}}+export function animatedEmojiUrlFor(code) {+ const opts = emojiOptions();+ if (opts) {+ return buildAnimatedEmojiUrl(code, opts);+ }+}+function encode(str) {return str.replaceAll("<", "<").replaceAll(">", ">");}diff --git a/frontend/discourse/app/services/emoji-store.js b/frontend/discourse/app/services/emoji-store.jsindex 02739191c01..1e75c54d98b 100644--- a/frontend/discourse/app/services/emoji-store.js+++ b/frontend/discourse/app/services/emoji-store.js@@ -1,7 +1,8 @@-import { tracked } from "@glimmer/tracking";+import { cached, tracked } from "@glimmer/tracking";import { trackedArray, trackedObject } from "@ember/reactive/collections";import Service from "@ember/service";-import { isSkinTonableEmoji } from "pretty-text/emoji";+import { isSkinTonableEmoji, normalizeEmoji } from "pretty-text/emoji";+import { ajax } from "discourse/lib/ajax";import KeyValueStore from "discourse/lib/key-value-store";export const SKIN_TONE_STORE_KEY = "emojiSelectedDiversity";@@ -18,6 +19,8 @@ export default class EmojiStore extends Service {contexts = trackedObject();+ #listPromise;+@tracked _diversity;get diversity() {@@ -29,6 +32,33 @@ export default class EmojiStore extends Service {this.store.setObject({ key: SKIN_TONE_STORE_KEY, value });}+ @cached+ get animatedEmojis() {+ return new Set(+ Object.values(this.list ?? {})+ .flat()+ .filter((emoji) => emoji.animated)+ .map((emoji) => emoji.name)+ );+ }++ loadList() {+ this.#listPromise ??= ajax("/emojis.json").then(+ (list) => (this.list = list),+ (error) => {+ this.#listPromise = null;+ throw error;+ }+ );+ return this.#listPromise;+ }++ // The list names each emoji once, under its main name; tones share it.+ isAnimated(code) {+ const name = normalizeEmoji(code.replace(/:t\d$/, ""));+ return this.animatedEmojis.has(name);+ }+trackEmojiForContext(emoji, context) {const recentEmojis = this.#addEmojiToContext(emoji, context);this.contexts[context] = trackedArray(recentEmojis);diff --git a/frontend/discourse/app/ui-kit/d-animated-emoji.gts b/frontend/discourse/app/ui-kit/d-animated-emoji.gtsnew file mode 100644index 00000000000..baf595582cd--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-animated-emoji.gts@@ -0,0 +1,73 @@+import Component from "@glimmer/component";+import type Owner from "@ember/owner";+import { service } from "@ember/service";+import { animatedEmojiUrlFor, emojiUrlFor } from "discourse/lib/text";+import type EmojiStoreService from "discourse/services/emoji-store";++interface DAnimatedEmojiSignature {+ Args: {+ /** The emoji's name, optionally with a skin tone (`clap`, `clap:t3`). */+ code: string;+ /** Translated tooltip and alternative text. Defaults to the emoji's name. */+ title?: string;+ };+ Element: HTMLImageElement;+}++/**+ * Renders an emoji animated, when an animation exists for it and the user+ * hasn't asked for reduced motion; otherwise renders the site's static image,+ * as do custom emojis. Renders nothing when emojis are disabled or the name is+ * unknown.+ */+export default class DAnimatedEmoji extends Component<DAnimatedEmojiSignature> {+ @service declare emojiStore: EmojiStoreService;++ constructor(owner: Owner, args: DAnimatedEmojiSignature["Args"]) {+ super(owner, args);+ // Which emojis are animated comes with the emoji list; until it loads,+ // and if it fails to, the static image stands in.+ if (animatedEmojiUrlFor(this.code)) {+ this.emojiStore.loadList().catch(() => {});+ }+ }++ get code() {+ return this.args.code.toLowerCase();+ }++ get staticUrl(): string | undefined {+ return emojiUrlFor(this.code);+ }++ get animatedUrl(): string | undefined {+ if (this.emojiStore.isAnimated(this.code)) {+ return animatedEmojiUrlFor(this.code);+ }+ }++ get title() {+ return this.args.title ?? this.code;+ }++ <template>+ {{#if this.staticUrl}}+ <picture class="d-animated-emoji">+ {{#if this.animatedUrl}}+ <source+ media="(prefers-reduced-motion: no-preference)"+ srcset={{this.animatedUrl}}+ type="image/avif"+ />+ {{/if}}+ <img+ alt={{this.title}}+ class="emoji d-animated-emoji__image"+ src={{this.staticUrl}}+ title={{this.title}}+ ...attributes+ />+ </picture>+ {{/if}}+ </template>+}diff --git a/frontend/discourse/tests/integration/components/d-animated-emoji-test.gjs b/frontend/discourse/tests/integration/components/d-animated-emoji-test.gjsnew file mode 100644index 00000000000..91aec1ce735--- /dev/null+++ b/frontend/discourse/tests/integration/components/d-animated-emoji-test.gjs@@ -0,0 +1,107 @@+import { render } from "@ember/test-helpers";+import { registerEmoji } from "pretty-text/emoji";+import { IMAGE_VERSION as v } from "pretty-text/emoji/version";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import DAnimatedEmoji from "discourse/ui-kit/d-animated-emoji";++module("Integration | ui-kit | DAnimatedEmoji", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ pretender.get("/emojis.json", () =>+ response({+ "smileys_&_emotion": [+ { name: "wink", animated: true },+ { name: "+1", tonable: true, animated: true },+ ],+ objects: [{ name: "abacus", animated: false }],+ })+ );+ });++ test("offers the animation, keeping the static image as fallback", async function (assert) {+ await render(<template><DAnimatedEmoji @code="Wink" /></template>);++ assert+ .dom(".d-animated-emoji source")+ .hasAttribute("srcset", `/images/emoji/noto_animated/wink.avif?v=${v}`)+ .hasAttribute("media", "(prefers-reduced-motion: no-preference)");+ assert+ .dom(".d-animated-emoji img.emoji")+ .hasAttribute("src", `/images/emoji/twitter/wink.png?v=${v}`)+ .hasAttribute("alt", "wink")+ .hasAttribute("title", "wink");+ });++ test("animates skin tones and alternate names", async function (assert) {+ await render(+ <template>+ <DAnimatedEmoji class="toned" @code="+1:t3" />+ <DAnimatedEmoji class="alias" @code="thumbsup" />+ </template>+ );++ assert+ .dom(".d-animated-emoji:has(.toned) source")+ .hasAttribute("srcset", `/images/emoji/noto_animated/+1/3.avif?v=${v}`);+ assert+ .dom(".d-animated-emoji:has(.alias) source")+ .hasAttribute(+ "srcset",+ `/images/emoji/noto_animated/thumbsup.avif?v=${v}`+ );+ });++ test("uses the given title", async function (assert) {+ await render(+ <template><DAnimatedEmoji @code="wink" @title="Winking" /></template>+ );++ assert+ .dom(".d-animated-emoji img")+ .hasAttribute("alt", "Winking")+ .hasAttribute("title", "Winking");+ });++ test("renders emojis without an animation static", async function (assert) {+ await render(<template><DAnimatedEmoji @code="abacus" /></template>);++ assert.dom(".d-animated-emoji source").doesNotExist();+ assert+ .dom(".d-animated-emoji img")+ .hasAttribute("src", `/images/emoji/twitter/abacus.png?v=${v}`);+ });++ test("renders static when the emoji list fails to load", async function (assert) {+ pretender.get("/emojis.json", () => response(500, {}));++ await render(<template><DAnimatedEmoji @code="wink" /></template>);++ assert.dom(".d-animated-emoji source").doesNotExist();+ assert.dom(".d-animated-emoji img").exists();+ });++ test("renders custom emojis static", async function (assert) {+ registerEmoji("d_animated_emoji_parrot", "/uploads/parrot.gif");++ await render(+ <template><DAnimatedEmoji @code="d_animated_emoji_parrot" /></template>+ );++ assert.dom(".d-animated-emoji source").doesNotExist();+ assert+ .dom(".d-animated-emoji img")+ .hasAttribute("src", `/uploads/parrot.gif?v=${v}`);+ });++ test("renders nothing for an unknown emoji or with emojis disabled", async function (assert) {+ await render(<template><DAnimatedEmoji @code="not_an_emoji" /></template>);+ assert.dom(".d-animated-emoji").doesNotExist();++ this.siteSettings.enable_emoji = false;+ await render(<template><DAnimatedEmoji @code="wink" /></template>);+ assert.dom(".d-animated-emoji").doesNotExist();+ });+});diff --git a/frontend/pretty-text/addon/emoji.js b/frontend/pretty-text/addon/emoji.jsindex 41a70cf7691..5764a79ccb1 100644--- a/frontend/pretty-text/addon/emoji.js+++ b/frontend/pretty-text/addon/emoji.js@@ -144,30 +144,44 @@ export function buildEmojiUrl(code, opts) {url = opts.customEmoji[code].url || opts.customEmoji[code];}- const noToneMatch = code.match(/([^:]+):?/);+ if (!url && opts.emojiSet) {+ url = standardEmojiUrl(code, opts.emojiSet, "png", opts);+ }++ if (url) {+ url = `${url}?v=${IMAGE_VERSION}`;+ }++ return url;+}++// Only some standard emojis are animated, so this URL may not exist.+export function buildAnimatedEmojiUrl(code, opts) {+ code = String(code).toLowerCase();++ if (isCustomEmoji(code, opts)) {+ return;+ }- let emojiBasePath = "/images/emoji";- if (opts.emojiCDNUrl) {- emojiBasePath = opts.emojiCDNUrl;+ const url = standardEmojiUrl(code, "noto_animated", "avif", opts);+ if (url) {+ return `${url}?v=${IMAGE_VERSION}`;}+}++function standardEmojiUrl(code, set, extension, opts) {+ const noToneMatch = code.match(/([^:]+):?/);if (opts.getURL &&- opts.emojiSet &&noToneMatch &&- !url &&(emojis.has(noToneMatch[1]) || aliasMap.has(noToneMatch[1]))) {- url = opts.getURL(- `${emojiBasePath}/${opts.emojiSet}/${code.replace(/:t/, "/")}.png`+ const emojiBasePath = opts.emojiCDNUrl || "/images/emoji";+ return opts.getURL(+ `${emojiBasePath}/${set}/${code.replace(/:t/, "/")}.${extension}`);}-- if (url) {- url = `${url}?v=${IMAGE_VERSION}`;- }-- return url;}export function emojiExists(code) {diff --git a/frontend/pretty-text/addon/emoji/version.js b/frontend/pretty-text/addon/emoji/version.jsindex 2d42b77d48c..cef06c93b54 100644--- a/frontend/pretty-text/addon/emoji/version.js+++ b/frontend/pretty-text/addon/emoji/version.js@@ -1,4 +1,4 @@// DO NOT EDIT THIS FILE!!!// Update it by running `rake javascript:update_constants`-export const IMAGE_VERSION = "15";+export const IMAGE_VERSION = "16";diff --git a/plugins/chat/spec/lib/chat/onebox_handler_spec.rb b/plugins/chat/spec/lib/chat/onebox_handler_spec.rbindex 137f3297f5d..bef3e00f5c1 100644--- a/plugins/chat/spec/lib/chat/onebox_handler_spec.rb+++ b/plugins/chat/spec/lib/chat/onebox_handler_spec.rb@@ -61,7 +61,7 @@ describe Chat::OneboxHandler do<article class="onebox-body chat-onebox-body"><h3 class="chat-onebox-title"><a href="/chat/c/-/#{public_channel.id}">- <img src="/images/emoji/twitter/tada.png?v=15" title="tada" class="emoji" alt="tada" loading="lazy" width="20" height="20">+ <img src="/images/emoji/twitter/tada.png?v=#{Emoji::EMOJI_VERSION}" title="tada" class="emoji" alt="tada" loading="lazy" width="20" height="20"><span class="clear-badge">#{public_channel.name}</span></a></h3>diff --git a/plugins/live/assets/javascripts/discourse/components/live/reaction-overlay.gjs b/plugins/live/assets/javascripts/discourse/components/live/reaction-overlay.gjsindex 5e68c94649e..f64fef44303 100644--- a/plugins/live/assets/javascripts/discourse/components/live/reaction-overlay.gjs+++ b/plugins/live/assets/javascripts/discourse/components/live/reaction-overlay.gjs@@ -1,15 +1,23 @@import Component from "@glimmer/component";import { service } from "@ember/service";import { trustHTML } from "@ember/template";-import dEmoji from "discourse/ui-kit/helpers/d-emoji";+import DAnimatedEmoji from "discourse/ui-kit/d-animated-emoji";function offsetStyle(reaction) {return trustHTML(`--live-reaction-offset: ${reaction.offset}%`);}export default class LiveReactionOverlay extends Component {+ @service emojiStore;@service liveReactions;+ constructor() {+ super(...arguments);+ // Reactions learn which emojis are animated from the emoji list; fetching+ // it on joining the call means even the first one can float animated.+ this.emojiStore.loadList().catch(() => {});+ }+get reactions() {return this.liveReactions.reactionsFor(this.args.room.id);}@@ -24,7 +32,10 @@ export default class LiveReactionOverlay extends Component {data-emoji={{reaction.emoji}}style={{offsetStyle reaction}}>- <span class="live-reactions__emoji">{{dEmoji reaction.emoji}}</span>+ <DAnimatedEmoji+ class="live-reactions__emoji"+ @code={{reaction.emoji}}+ /><span class="live-reactions__username">{{reaction.username}}</span></span>{{/each}}diff --git a/plugins/live/assets/stylesheets/common/live-room-page.scss b/plugins/live/assets/stylesheets/common/live-room-page.scssindex f2ef675c475..1f4308ec5e2 100644--- a/plugins/live/assets/stylesheets/common/live-room-page.scss+++ b/plugins/live/assets/stylesheets/common/live-room-page.scss@@ -707,7 +707,8 @@ body.has-sidebar-page #main-outlet-wrapper:has(.live-room-header) {}}- &__emoji .emoji {+ // Outranks the core img.emoji sizing.+ &__emoji.emoji {width: 2.25rem;height: 2.25rem;diff --git a/spec/models/emoji_spec.rb b/spec/models/emoji_spec.rbindex 0dc6f01f259..e4b62af27e8 100644--- a/spec/models/emoji_spec.rb+++ b/spec/models/emoji_spec.rb@@ -316,6 +316,11 @@ RSpec.describe Emoji doexpect(emoji.group).to eq("flags")end+ it "flags emojis that have an animation" do+ expect(Emoji.create_from_db_item("name" => "wink").animated).to eq(true)+ expect(Emoji.create_from_db_item("name" => "abacus").animated).to eq(false)+ end+it "returns nil when group is unknown" doexpect(Emoji.create_from_db_item("name" => "white_hair")).to be_nilenddiff --git a/spec/requests/emojis_controller_spec.rb b/spec/requests/emojis_controller_spec.rbindex f82c207416f..eb8e6dca799 100644--- a/spec/requests/emojis_controller_spec.rb+++ b/spec/requests/emojis_controller_spec.rb@@ -36,6 +36,14 @@ RSpec.describe EmojisController do],)end++ it "flags the emojis that have an animation" do+ get "/emojis.json"++ emojis = response.parsed_body.values.flatten.index_by { _1["name"] }+ expect(emojis.dig("wink", "animated")).to eq(true)+ expect(emojis.dig("abacus", "animated")).to eq(false)+ endenddescribe "#search_aliases" do