Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat(ui): add emoji picker (#7157)
白熱0caed264aca8
diff --git a/packages/ui/.gitignore b/packages/ui/.gitignorenew file mode 100644index 0000000000..d6062f25c7--- /dev/null+++ b/packages/ui/.gitignore@@ -0,0 +1,2 @@+src/views/emoji-picker/emojis.generated.ts+src/locale/emoji-locale/*.generated.tsdiff --git a/packages/ui/package.json b/packages/ui/package.jsonindex 3ac91091ff..f0268fdac4 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -72,6 +72,7 @@"lib"],"scripts": {+ "prepare": "node --experimental-strip-types ./scripts/generate-emojis.mts","test": "vitest run","test:watch": "vitest","coverage": "vitest run --coverage",diff --git a/packages/ui/scripts/generate-emojis.mts b/packages/ui/scripts/generate-emojis.mtsnew file mode 100644index 0000000000..52b6066d1e--- /dev/null+++ b/packages/ui/scripts/generate-emojis.mts@@ -0,0 +1,394 @@+import type { PathLike } from 'node:fs';+import { spawnSync } from 'node:child_process';+import fs from 'node:fs';+import path from 'node:path';+import process from 'node:process';+import { fileURLToPath } from 'node:url';+import { discoverUniverUiLocales } from '@univerjs-infra/shared/locale';++interface IEmojiItem {+ emoji: string;+ title: string;+}++interface ICldrAnnotationsData {+ annotations?: {+ annotations?: Record<string, {+ default?: string[];+ tts?: string[];+ }>;+ };+ annotationsDerived?: {+ annotations?: Record<string, {+ default?: string[];+ tts?: string[];+ }>;+ };+}++interface IGeneratedEmojiLocale {+ emojiSearchIndex: Record<string, string>;+ emojiTitles: Record<string, string>;+}++type EmojiCategory = 'people' | 'nature' | 'foods' | 'activity' | 'places' | 'objects' | 'symbols';+type EmojiGroups = Record<'frequent' | EmojiCategory, IEmojiItem[]>;+type UnicodeEmojiGroup =+ | 'Activities'+ | 'Animals & Nature'+ | 'Flags'+ | 'Food & Drink'+ | 'Objects'+ | 'People & Body'+ | 'Smileys & Emotion'+ | 'Symbols'+ | 'Travel & Places';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const root = path.resolve(__dirname, '../../..');+const outputPath = path.resolve(__dirname, '../src/views/emoji-picker/emojis.generated.ts');+const emojiLocaleOutputDir = path.resolve(__dirname, '../src/locale/emoji-locale');+const unicodeEmojiTestUrl = 'https://www.unicode.org/Public/17.0.0/emoji/emoji-test.txt';+const cldrJsonVersion = '48.2.0';+const cldrJsonBaseUrl = `https://raw.githubusercontent.com/unicode-org/cldr-json/${cldrJsonVersion}/cldr-json`;+const cldrJsonDownloadConcurrency = 4;+const envProxyNodeArg = '--use-env-proxy';+const envProxyRelaunchEnv = 'UNIVER_UI_EMOJI_ENV_PROXY_REEXEC';+const emojiCategories: EmojiCategory[] = ['people', 'nature', 'foods', 'activity', 'places', 'objects', 'symbols'];+const cldrLocaleMap: Record<string, string> = {+ 'ar-SA': 'ar',+ 'ca-ES': 'ca',+ 'de-DE': 'de',+ 'en-US': 'en',+ 'es-ES': 'es',+ 'fa-IR': 'fa',+ 'fr-FR': 'fr',+ 'id-ID': 'id',+ 'it-IT': 'it',+ 'ja-JP': 'ja',+ 'ko-KR': 'ko',+ 'pl-PL': 'pl',+ 'pt-BR': 'pt',+ 'ru-RU': 'ru',+ 'sk-SK': 'sk',+ 'vi-VN': 'vi',+ 'zh-CN': 'zh',+ 'zh-HK': 'zh-Hant-HK',+ 'zh-TW': 'zh-Hant',+};+const localeFiles = discoverUniverUiLocales({ rootDir: root }).map((locale) => {+ const cldrLocale = cldrLocaleMap[locale];+ if (!cldrLocale) {+ throw new Error(`Missing CLDR locale mapping for ${locale}`);+ }++ return [locale, cldrLocale] as const;+});+const frequentEmojis = [+ '👍',+ '😀',+ '😘',+ '😍',+ '😆',+ '😜',+ '😅',+ '😂',+ '😱',+ '😞',+ '😒',+];++const groupCategoryMap: Partial<Record<UnicodeEmojiGroup, EmojiCategory>> = {+ Activities: 'activity',+ 'Animals & Nature': 'nature',+ 'Food & Drink': 'foods',+ Objects: 'objects',+ 'People & Body': 'people',+ 'Smileys & Emotion': 'people',+ Symbols: 'symbols',+ 'Travel & Places': 'places',+};++export function buildEmojisFromEmojiTest(emojiTest: string, options: { supportedEmojis?: Set<string> } = {}): EmojiGroups {+ const groups = createEmptyEmojiGroups();+ let currentGroup: UnicodeEmojiGroup | null = null;+ const titleByEmoji = new Map<string, string>();++ emojiTest.split(/\r?\n/).forEach((line) => {+ const group = line.match(/^# group: (.+)$/);+ if (group) {+ currentGroup = group[1] as UnicodeEmojiGroup;+ return;+ }++ const category = currentGroup ? groupCategoryMap[currentGroup] : undefined;+ if (!category) {+ return;+ }++ const item = parseEmojiTestLine(line);+ if (!item || (options.supportedEmojis && !options.supportedEmojis.has(item.emoji))) {+ return;+ }++ titleByEmoji.set(item.emoji, item.title);+ groups[category].push(item);+ });++ groups.frequent = frequentEmojis+ .map((emoji) => {+ const title = titleByEmoji.get(emoji);+ return title ? { emoji, title } : null;+ })+ .filter(isEmojiItem);++ return groups;+}++export function buildEmojiSearchIndexFromCldrAnnotations(emojis: Array<string | IEmojiItem>, ...sources: ICldrAnnotationsData[]): IGeneratedEmojiLocale {+ const emojiTitles: Record<string, string> = {};+ const emojiSearchIndex: Record<string, string> = {};++ emojis.forEach((entry) => {+ const emoji = typeof entry === 'string' ? entry : entry.emoji;+ const fallbackTitle = typeof entry === 'string' ? undefined : entry.title;+ const annotations = sources+ .map((source) => getCldrAnnotation(source, emoji))+ .filter((annotation): annotation is NonNullable<ReturnType<typeof getCldrAnnotation>> => Boolean(annotation));++ const title = annotations.find((annotation) => annotation.tts?.[0])?.tts?.[0] ?? fallbackTitle;+ const keywords = [...new Set(annotations.flatMap((annotation) => [+ ...(annotation.tts ?? []),+ ...(annotation.default ?? []),+ ]).filter(Boolean))];+ if (!keywords.length && fallbackTitle) {+ keywords.push(fallbackTitle);+ }++ if (title) {+ emojiTitles[emoji] = title;+ }+ if (keywords.length) {+ emojiSearchIndex[emoji] = keywords.join(' ');+ }+ });++ return {+ emojiSearchIndex,+ emojiTitles,+ };+}++function createEmptyEmojiGroups(): EmojiGroups {+ return Object.fromEntries([+ ['frequent', []],+ ...emojiCategories.map((category) => [category, []]),+ ]) as EmojiGroups;+}++function parseEmojiTestLine(line: string): IEmojiItem | null {+ const match = line.match(/^\S(?:.+?)\s+;\s+fully-qualified\s+#\s+(\S+)\s+E[\d.]+\s+(.+)$/);+ if (!match) {+ return null;+ }++ return {+ emoji: match[1],+ title: toTitleCase(match[2]),+ };+}++function isEmojiItem(item: IEmojiItem | null): item is IEmojiItem {+ return item !== null;+}++function getCldrAnnotation(source: ICldrAnnotationsData, emoji: string) {+ const normalizedEmoji = stripEmojiVariationSelectors(emoji);+ const annotations = source.annotations?.annotations ?? source.annotationsDerived?.annotations;+ return annotations?.[emoji] ?? annotations?.[normalizedEmoji];+}++function stripEmojiVariationSelectors(emoji: string): string {+ return emoji.replace(/\uFE0F/g, '');+}++function toTitleCase(value: string): string {+ return value+ .split(' ')+ .map((word) => word ? `${word[0].toUpperCase()}${word.slice(1)}` : word)+ .join(' ');+}++interface IShouldRelaunchWithEnvProxyOptions {+ allowedFlags: ReadonlySet<string>;+ env: NodeJS.ProcessEnv | Record<string, string | undefined>;+ execArgv: readonly string[];+}++export function shouldRelaunchWithEnvProxy(options: IShouldRelaunchWithEnvProxyOptions): boolean {+ const proxyConfigured = [+ 'HTTP_PROXY',+ 'HTTPS_PROXY',+ 'ALL_PROXY',+ 'http_proxy',+ 'https_proxy',+ 'all_proxy',+ ].some((name) => Boolean(options.env[name]));++ if (!proxyConfigured || options.env[envProxyRelaunchEnv] || !options.allowedFlags.has(envProxyNodeArg)) {+ return false;+ }++ return !options.execArgv.includes(envProxyNodeArg) && !options.env.NODE_OPTIONS?.split(/\s+/).includes(envProxyNodeArg);+}++function relaunchWithEnvProxyIfNeeded(): boolean {+ if (!shouldRelaunchWithEnvProxy({+ allowedFlags: process.allowedNodeEnvironmentFlags,+ env: process.env,+ execArgv: process.execArgv,+ })) {+ return false;+ }++ const result = spawnSync(process.execPath, [+ envProxyNodeArg,+ ...process.execArgv,+ ...process.argv.slice(1),+ ], {+ env: {+ ...process.env,+ [envProxyRelaunchEnv]: '1',+ },+ stdio: 'inherit',+ });++ if (result.error) {+ throw result.error;+ }++ process.exitCode = result.status ?? 1;+ return true;+}++function getCldrAnnotationsUrl(cldrLocale: string, type: 'annotations' | 'annotationsDerived'): string {+ if (type === 'annotations') {+ return `${cldrJsonBaseUrl}/cldr-annotations-full/annotations/${cldrLocale}/annotations.json`;+ }++ return `${cldrJsonBaseUrl}/cldr-annotations-derived-full/annotationsDerived/${cldrLocale}/annotations.json`;+}++export function getEmojiSourceUrls(): string[] {+ return [+ unicodeEmojiTestUrl,+ ...localeFiles.flatMap(([, cldrLocale]) => [+ getCldrAnnotationsUrl(cldrLocale, 'annotations'),+ getCldrAnnotationsUrl(cldrLocale, 'annotationsDerived'),+ ]),+ ];+}++async function downloadText(url: string): Promise<string> {+ let response: Response;+ try {+ response = await fetch(url);+ } catch (error) {+ throw new Error(`Failed to download ${url}`, { cause: error });+ }++ if (!response.ok) {+ throw new Error(`Failed to download ${url}: ${response.status} ${response.statusText}`);+ }++ return response.text();+}++async function downloadUnicodeEmojiTest(): Promise<string> {+ return downloadText(unicodeEmojiTestUrl);+}++async function downloadJson<T>(url: string): Promise<T> {+ return JSON.parse(await downloadText(url)) as T;+}++export async function mapWithConcurrencyLimit<T, R>(+ values: readonly T[],+ limit: number,+ mapper: (value: T, index: number) => Promise<R>+): Promise<R[]> {+ const results = new Array<R>(values.length);+ let nextIndex = 0;+ const workerCount = Math.min(Math.max(1, limit), values.length);++ await Promise.all(Array.from({ length: workerCount }, async () => {+ while (nextIndex < values.length) {+ const currentIndex = nextIndex;+ nextIndex += 1;+ results[currentIndex] = await mapper(values[currentIndex], currentIndex);+ }+ }));++ return results;+}++function serializeEmojis(groups: EmojiGroups): string {+ return [+ '/* eslint-disable */',+ '// Generated by scripts/generate-emojis.mts. Do not edit manually.',+ '',+ `export const emojis = ${JSON.stringify(groups, null, 4)};`,+ '',+ ].join('\n');+}++function writeGeneratedEmojis(filePath: PathLike, groups: EmojiGroups): void {+ fs.mkdirSync(path.dirname(filePath.toString()), { recursive: true });+ fs.writeFileSync(filePath, serializeEmojis(groups));+}++function serializeEmojiLocale(data: IGeneratedEmojiLocale): string {+ return [+ '/* eslint-disable */',+ '// Generated by scripts/generate-emojis.mts. Do not edit manually.',+ '',+ `const emojiLocale: { emojiSearchIndex: Record<string, string>; emojiTitles: Record<string, string> } = ${JSON.stringify(data, null, 4)};`,+ '',+ 'export default emojiLocale;',+ '',+ ].join('\n');+}++function writeGeneratedEmojiLocale(locale: string, data: IGeneratedEmojiLocale): void {+ fs.mkdirSync(emojiLocaleOutputDir, { recursive: true });+ fs.writeFileSync(path.resolve(emojiLocaleOutputDir, `${locale}.generated.ts`), serializeEmojiLocale(data));+}++async function generate(): Promise<void> {+ const emojiTest = await downloadUnicodeEmojiTest();+ const emojis = buildEmojisFromEmojiTest(emojiTest);+ const allEmojis = [+ ...new Map(Object.values(emojis).flat().map((item) => [item.emoji, item])).values(),+ ];++ writeGeneratedEmojis(outputPath, emojis);++ await mapWithConcurrencyLimit(localeFiles, cldrJsonDownloadConcurrency, async ([locale, cldrLocale]) => {+ const annotations = await downloadJson<ICldrAnnotationsData>(getCldrAnnotationsUrl(cldrLocale, 'annotations'));+ const annotationsDerived = await downloadJson<ICldrAnnotationsData>(getCldrAnnotationsUrl(cldrLocale, 'annotationsDerived'));++ writeGeneratedEmojiLocale(locale, buildEmojiSearchIndexFromCldrAnnotations(allEmojis, annotations, annotationsDerived));+ });+}++if (process.argv[1] === fileURLToPath(import.meta.url)) {+ const task = relaunchWithEnvProxyIfNeeded()+ ? Promise.resolve()+ : generate();++ void task+ .catch((error) => {+ console.error(error);+ process.exitCode = 1;+ });+}diff --git a/packages/ui/src/controllers/components.controller.ts b/packages/ui/src/controllers/components.controller.tsindex 84213e8580..633ec76d31 100644--- a/packages/ui/src/controllers/components.controller.ts+++ b/packages/ui/src/controllers/components.controller.ts@@ -22,6 +22,7 @@ import { ComponentManager, IconManager } from '../common';import { COLOR_PICKER_COMPONENT } from '../views/color-picker/interface';import { COMMON_LABEL_COMPONENT, CommonLabel } from '../views/CommonLabel';import { ShortcutPanel } from '../views/components/shortcut-panel/ShortcutPanel';+import { EMOJI_PICKER_COMPONENT, EmojiPicker } from '../views/emoji-picker/index';import { FontFamily, FontFamilyItem } from '../views/font-family/index';import { FONT_FAMILY_COMPONENT, FONT_FAMILY_ITEM_COMPONENT } from '../views/font-family/interface';import { FontSize } from '../views/font-size/FontSize';@@ -58,6 +59,7 @@ export class ComponentsController extends Disposable {[FONT_FAMILY_ITEM_COMPONENT, FontFamilyItem],[FONT_SIZE_COMPONENT, FontSize],[COLOR_PICKER_COMPONENT, ColorPicker],+ [EMOJI_PICKER_COMPONENT, EmojiPicker],] as const).forEach(([key, comp]) => {this.disposeWithMe(this._componentManager.register(key, comp)diff --git a/packages/ui/src/locale/ar-SA.ts b/packages/ui/src/locale/ar-SA.tsindex cee6510d55..9fd0574ba5 100644--- a/packages/ui/src/locale/ar-SA.ts+++ b/packages/ui/src/locale/ar-SA.ts@@ -15,9 +15,25 @@*/import type enUS from './en-US';+import emojiLocale from './emoji-locale/ar-SA.generated';const locale: typeof enUS = {ui: {+ emojiPicker: {+ search: 'بحث',+ random: 'رمز تعبيري عشوائي',+ recents: 'الأخيرة',+ emojis: 'الرموز التعبيرية',+ animals: 'الحيوانات',+ food: 'الطعام',+ activities: 'الأنشطة',+ places: 'الأماكن',+ objects: 'العناصر',+ symbols: 'الرموز',+ searchResults: 'نتائج البحث',+ noResults: 'لم يتم العثور على رمز تعبيري',+ ...emojiLocale,+ },toolbar: {heading: {normal: 'عادي',diff --git a/packages/ui/src/locale/ca-ES.ts b/packages/ui/src/locale/ca-ES.tsindex dc9e1670f8..6455f476fa 100644--- a/packages/ui/src/locale/ca-ES.ts+++ b/packages/ui/src/locale/ca-ES.ts@@ -15,9 +15,25 @@*/import type enUS from './en-US';+import emojiLocale from './emoji-locale/ca-ES.generated';const locale: typeof enUS = {ui: {+ emojiPicker: {+ search: 'Cerca',+ random: 'Emoji aleatori',+ recents: 'Recents',+ emojis: 'Emojis',+ animals: 'Animals',+ food: 'Menjar',+ activities: 'Activitats',+ places: 'Llocs',+ objects: 'Objectes',+ symbols: 'Símbols',+ searchResults: 'Resultats de cerca',+ noResults: 'No s’ha trobat cap emoji',+ ...emojiLocale,+ },toolbar: {heading: {normal: 'Normal',diff --git a/packages/ui/src/locale/de-DE.ts b/packages/ui/src/locale/de-DE.tsindex 00873d1c80..006633e6df 100644--- a/packages/ui/src/locale/de-DE.ts+++ b/packages/ui/src/locale/de-DE.ts@@ -15,9 +15,25 @@*/import type enUS from './en-US';+import emojiLocale from './emoji-locale/de-DE.generated';const locale: typeof enUS = {ui: {+ emojiPicker: {+ search: 'Suchen',+ random: 'Zufälliges Emoji',+ recents: 'Zuletzt verwendet',+ emojis: 'Emojis',+ animals: 'Tiere',+ food: 'Essen',+ activities: 'Aktivitäten',+ places: 'Orte',+ objects: 'Objekte',+ symbols: 'Symbole',+ searchResults: 'Suchergebnisse',+ noResults: 'Kein Emoji gefunden',+ ...emojiLocale,+ },toolbar: {heading: {normal: 'Normal',diff --git a/packages/ui/src/locale/en-US.ts b/packages/ui/src/locale/en-US.tsindex 9146f0a4a7..005c8c51b0 100644--- a/packages/ui/src/locale/en-US.ts+++ b/packages/ui/src/locale/en-US.ts@@ -14,8 +14,25 @@* limitations under the License.*/+import emojiLocale from './emoji-locale/en-US.generated';+const locale = {ui: {+ emojiPicker: {+ search: 'Search',+ random: 'Random emoji',+ recents: 'Recents',+ emojis: 'Emojis',+ animals: 'Animals',+ food: 'Food',+ activities: 'Activities',+ places: 'Places',+ objects: 'Objects',+ symbols: 'Symbols',+ searchResults: 'Search results',+ noResults: 'No emoji found',+ ...emojiLocale,+ },toolbar: {heading: {normal: 'Normal',diff --git a/packages/ui/src/locale/es-ES.ts b/packages/ui/src/locale/es-ES.tsindex 74973976cd..4d8bac903a 100644--- a/packages/ui/src/locale/es-ES.ts+++ b/packages/ui/src/locale/es-ES.ts@@ -15,9 +15,25 @@*/import type enUS from './en-US';+import emojiLocale from './emoji-locale/es-ES.generated';const locale: typeof enUS = {ui: {+ emojiPicker: {+ search: 'Buscar',+ random: 'Emoji aleatorio',+ recents: 'Recientes',+ emojis: 'Emojis',+ animals: 'Animales',+ food: 'Comida',+ activities: 'Actividades',+ places: 'Lugares',+ objects: 'Objetos',+ symbols: 'Símbolos',+ searchResults: 'Resultados de búsqueda',+ noResults: 'No se encontraron emojis',+ ...emojiLocale,+ },toolbar: {heading: {normal: 'Normal',diff --git a/packages/ui/src/locale/fa-IR.ts b/packages/ui/src/locale/fa-IR.tsindex 2bed7a545d..eb2680261f 100644--- a/packages/ui/src/locale/fa-IR.ts+++ b/packages/ui/src/locale/fa-IR.ts@@ -15,9 +15,25 @@*/import type enUS from './en-US';+import emojiLocale from './emoji-locale/fa-IR.generated';const locale: typeof enUS = {ui: {+ emojiPicker: {+ search: 'جستجو',+ random: 'ایموجی تصادفی',+ recents: 'اخیر',+ emojis: 'ایموجیها',+ animals: 'حیوانات',+ food: 'غذا',+ activities: 'فعالیتها',+ places: 'مکانها',+ objects: 'اشیا',+ symbols: 'نمادها',+ searchResults: 'نتایج جستجو',+ noResults: 'ایموجی پیدا نشد',+ ...emojiLocale,+ },toolbar: {heading: {normal: 'متن عادی',diff --git a/packages/ui/src/locale/fr-FR.ts b/packages/ui/src/locale/fr-FR.tsindex 8e1bf1f13e..0f7c464b5d 100644--- a/packages/ui/src/locale/fr-FR.ts+++ b/packages/ui/src/locale/fr-FR.ts@@ -15,9 +15,25 @@*/import type enUS from './en-US';+import emojiLocale from './emoji-locale/fr-FR.generated';const locale: typeof enUS = {ui: {+ emojiPicker: {+ search: 'Rechercher',+ random: 'Emoji aléatoire',+ recents: 'Récents',+ emojis: 'Emojis',+ animals: 'Animaux',+ food: 'Nourriture',+ activities: 'Activités',+ places: 'Lieux',+ objects: 'Objets',+ symbols: 'Symboles',+ searchResults: 'Résultats de recherche',+ noResults: 'Aucun emoji trouvé',+ ...emojiLocale,+ },toolbar: {heading: {normal: 'Normal',diff --git a/packages/ui/src/locale/id-ID.ts b/packages/ui/src/locale/id-ID.tsindex 8b02837108..053efc04ac 100644--- a/packages/ui/src/locale/id-ID.ts+++ b/packages/ui/src/locale/id-ID.ts@@ -15,9 +15,25 @@*/import type enUS from './en-US';+import emojiLocale from './emoji-locale/id-ID.generated';const locale: typeof enUS = {ui: {+ emojiPicker: {+ search: 'Cari',+ random: 'Emoji acak',+ recents: 'Terbaru',+ emojis: 'Emoji',+ animals: 'Hewan',+ food: 'Makanan',+ activities: 'Aktivitas',+ places: 'Tempat',+ objects: 'Objek',+ symbols: 'Simbol',+ searchResults: 'Hasil pencarian',+ noResults: 'Emoji tidak ditemukan',+ ...emojiLocale,+ },toolbar: {heading: {normal: 'Normal',diff --git a/packages/ui/src/locale/it-IT.ts b/packages/ui/src/locale/it-IT.tsindex 258c56e587..52f769ad16 100644--- a/packages/ui/src/locale/it-IT.ts+++ b/packages/ui/src/locale/it-IT.ts@@ -15,9 +15,25 @@*/import type enUS from './en-US';+import emojiLocale from './emoji-locale/it-IT.generated';const locale: typeof enUS = {ui: {+ emojiPicker: {+ search: 'Cerca',+ random: 'Emoji casuale',+ recents: 'Recenti',+ emojis: 'Emoji',+ animals: 'Animali',+ food: 'Cibo',+ activities: 'Attività',+ places: 'Luoghi',+ objects: 'Oggetti',+ symbols: 'Simboli',+ searchResults: 'Risultati di ricerca',+ noResults: 'Nessun emoji trovato',+ ...emojiLocale,+ },toolbar: {heading: {normal: 'Normale',diff --git a/packages/ui/src/locale/ja-JP.ts b/packages/ui/src/locale/ja-JP.tsindex 924228e09f..7cf79c9c79 100644--- a/packages/ui/src/locale/ja-JP.ts+++ b/packages/ui/src/locale/ja-JP.ts@@ -15,9 +15,25 @@*/import type enUS from './en-US';+import emojiLocale from './emoji-locale/ja-JP.generated';const locale: typeof enUS = {ui: {+ emojiPicker: {+ search: '検索',+ random: 'ランダム絵文字',+ recents: '最近使用',+ emojis: '絵文字',+ animals: '動物',+ food: '食べ物',+ activities: 'アクティビティ',+ places: '場所',+ objects: 'オブジェクト',+ symbols: '記号',+ searchResults: '検索結果',+ noResults: '絵文字が見つかりません',+ ...emojiLocale,+ },toolbar: {heading: {normal: '標準',diff --git a/packages/ui/src/locale/ko-KR.ts b/packages/ui/src/locale/ko-KR.tsindex 5a24499f94..9fd1fe34bb 100644--- a/packages/ui/src/locale/ko-KR.ts+++ b/packages/ui/src/locale/ko-KR.ts@@ -15,9 +15,25 @@*/import type enUS from './en-US';+import emojiLocale from './emoji-locale/ko-KR.generated';const locale: typeof enUS = {ui: {+ emojiPicker: {+ search: '검색',+ random: '무작위 이모지',+ recents: '최근 항목',+ emojis: '이모지',+ animals: '동물',+ food: '음식',+ activities: '활동',+ places: '장소',+ objects: '사물',+ symbols: '기호',+ searchResults: '검색 결과',+ noResults: '이모지를 찾을 수 없음',+ ...emojiLocale,+ },toolbar: {heading: {normal: '일반',diff --git a/packages/ui/src/locale/pl-PL.ts b/packages/ui/src/locale/pl-PL.tsindex 9cdafab310..72ee8ac789 100644--- a/packages/ui/src/locale/pl-PL.ts+++ b/packages/ui/src/locale/pl-PL.ts@@ -15,9 +15,25 @@*/import type enUS from './en-US';+import emojiLocale from './emoji-locale/pl-PL.generated';const locale: typeof enUS = {ui: {+ emojiPicker: {+ search: 'Szukaj',+ random: 'Losowe emoji',+ recents: 'Ostatnie',+ emojis: 'Emoji',+ animals: 'Zwierzęta',+ food: 'Jedzenie',+ activities: 'Aktywności',+ places: 'Miejsca',+ objects: 'Obiekty',+ symbols: 'Symbole',+ searchResults: 'Wyniki wyszukiwania',+ noResults: 'Nie znaleziono emoji',+ ...emojiLocale,+ },toolbar: {heading: {normal: 'Normalny',diff --git a/packages/ui/src/locale/pt-BR.ts b/packages/ui/src/locale/pt-BR.tsindex f00fb48d69..e5ee73c108 100644--- a/packages/ui/src/locale/pt-BR.ts+++ b/packages/ui/src/locale/pt-BR.ts@@ -15,9 +15,25 @@*/import type enUS from './en-US';+import emojiLocale from './emoji-locale/pt-BR.generated';const locale: typeof enUS = {ui: {+ emojiPicker: {+ search: 'Buscar',+ random: 'Emoji aleatório',+ recents: 'Recentes',+ emojis: 'Emojis',+ animals: 'Animais',+ food: 'Comida',+ activities: 'Atividades',+ places: 'Lugares',+ objects: 'Objetos',+ symbols: 'Símbolos',+ searchResults: 'Resultados da busca',+ noResults: 'Nenhum emoji encontrado',+ ...emojiLocale,+ },toolbar: {heading: {normal: 'Normal',diff --git a/packages/ui/src/locale/ru-RU.ts b/packages/ui/src/locale/ru-RU.tsindex 29f50f9c64..3d4cb77bf9 100644--- a/packages/ui/src/locale/ru-RU.ts+++ b/packages/ui/src/locale/ru-RU.ts@@ -15,9 +15,25 @@*/import type enUS from './en-US';+import emojiLocale from './emoji-locale/ru-RU.generated';const locale: typeof enUS = {ui: {+ emojiPicker: {+ search: 'Поиск',+ random: 'Случайный эмодзи',+ recents: 'Недавние',+ emojis: 'Эмодзи',+ animals: 'Животные',+ food: 'Еда',+ activities: 'Активности',+ places: 'Места',+ objects: 'Объекты',+ symbols: 'Символы',+ searchResults: 'Результаты поиска',+ noResults: 'Эмодзи не найден',+ ...emojiLocale,+ },toolbar: {heading: {normal: 'Обычный текст',diff --git a/packages/ui/src/locale/sk-SK.ts b/packages/ui/src/locale/sk-SK.tsindex cc8fad8f54..1be9a6370b 100644--- a/packages/ui/src/locale/sk-SK.ts+++ b/packages/ui/src/locale/sk-SK.ts@@ -15,9 +15,25 @@*/import type enUS from './en-US';+import emojiLocale from './emoji-locale/sk-SK.generated';const locale: typeof enUS = {ui: {+ emojiPicker: {+ search: 'Hľadať',+ random: 'Náhodné emoji',+ recents: 'Nedávne',+ emojis: 'Emoji',+ animals: 'Zvieratá',+ food: 'Jedlo',+ activities: 'Aktivity',+ places: 'Miesta',+ objects: 'Objekty',+ symbols: 'Symboly',+ searchResults: 'Výsledky vyhľadávania',+ noResults: 'Nenašli sa žiadne emoji',+ ...emojiLocale,+ },toolbar: {heading: {normal: 'Normálne',diff --git a/packages/ui/src/locale/vi-VN.ts b/packages/ui/src/locale/vi-VN.tsindex 5c3bd54542..1971515b53 100644--- a/packages/ui/src/locale/vi-VN.ts+++ b/packages/ui/src/locale/vi-VN.ts@@ -15,9 +15,25 @@*/import type enUS from './en-US';+import emojiLocale from './emoji-locale/vi-VN.generated';const locale: typeof enUS = {ui: {+ emojiPicker: {+ search: 'Tìm kiếm',+ random: 'Emoji ngẫu nhiên',+ recents: 'Gần đây',+ emojis: 'Emoji',+ animals: 'Động vật',+ food: 'Đồ ăn',+ activities: 'Hoạt động',+ places: 'Địa điểm',+ objects: 'Đồ vật',+ symbols: 'Ký hiệu',+ searchResults: 'Kết quả tìm kiếm',+ noResults: 'Không tìm thấy emoji',+ ...emojiLocale,+ },toolbar: {heading: {normal: 'Văn bản',diff --git a/packages/ui/src/locale/zh-CN.ts b/packages/ui/src/locale/zh-CN.tsindex 0e2278baeb..a85b1dc1b9 100644--- a/packages/ui/src/locale/zh-CN.ts+++ b/packages/ui/src/locale/zh-CN.ts@@ -15,9 +15,25 @@*/import type enUS from './en-US';+import emojiLocale from './emoji-locale/zh-CN.generated';const locale: typeof enUS = {ui: {+ emojiPicker: {+ search: '搜索',+ random: '随机表情',+ recents: '最近使用',+ emojis: '表情',+ animals: '动物',+ food: '食物',+ activities: '活动',+ places: '地点',+ objects: '物品',+ symbols: '符号',+ searchResults: '搜索结果',+ noResults: '未找到表情',+ ...emojiLocale,+ },toolbar: {heading: {normal: '正文',diff --git a/packages/ui/src/locale/zh-HK.ts b/packages/ui/src/locale/zh-HK.tsindex ea1bf6ce9f..4419f924fb 100644--- a/packages/ui/src/locale/zh-HK.ts+++ b/packages/ui/src/locale/zh-HK.ts@@ -15,9 +15,25 @@*/import type enUS from './en-US';+import emojiLocale from './emoji-locale/zh-HK.generated';const locale: typeof enUS = {ui: {+ emojiPicker: {+ search: '搜尋',+ random: '隨機表情',+ recents: '最近使用',+ emojis: '表情',+ animals: '動物',+ food: '食物',+ activities: '活動',+ places: '地點',+ objects: '物品',+ symbols: '符號',+ searchResults: '搜尋結果',+ noResults: '找不到表情',+ ...emojiLocale,+ },toolbar: {heading: {normal: '正文',diff --git a/packages/ui/src/locale/zh-TW.ts b/packages/ui/src/locale/zh-TW.tsindex 086eda2691..bb972ab75c 100644--- a/packages/ui/src/locale/zh-TW.ts+++ b/packages/ui/src/locale/zh-TW.ts@@ -15,9 +15,25 @@*/import type enUS from './en-US';+import emojiLocale from './emoji-locale/zh-TW.generated';const locale: typeof enUS = {ui: {+ emojiPicker: {+ search: '搜尋',+ random: '隨機表情',+ recents: '最近使用',+ emojis: '表情',+ animals: '動物',+ food: '食物',+ activities: '活動',+ places: '地點',+ objects: '物品',+ symbols: '符號',+ searchResults: '搜尋結果',+ noResults: '找不到表情',+ ...emojiLocale,+ },toolbar: {heading: {normal: '正文',diff --git a/packages/ui/src/views/emoji-picker/EmojiPicker.tsx b/packages/ui/src/views/emoji-picker/EmojiPicker.tsxnew file mode 100644index 0000000000..b986b9a02b--- /dev/null+++ b/packages/ui/src/views/emoji-picker/EmojiPicker.tsx@@ -0,0 +1,395 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ReactElement, UIEvent } from 'react';+import type { LocaleKey } from '../../locale/types';+import type { IPopup } from '../../services/popup/canvas-popup.service';+import type { EmojiCategory, IEmojiItem } from './emoji-picker-utils';+import { ILocalStorageService, LocaleService } from '@univerjs/core';+import { borderTopClassName, clsx, Input } from '@univerjs/design';+import {+ ActivityIcon,+ FoodsIcon,+ NatureIcon,+ ObjectsIcon,+ PeopleIcon,+ PlacesIcon,+ RandomIcon,+ RecentIcon,+ SearchIcon,+ SymbolsIcon,+} from '@univerjs/icons';+import { useDeferredValue, useEffect, useMemo, useRef, useState } from 'react';+import { useDependency, useObservable } from '../../utils/di';+import {+ EMOJI_CATEGORIES,+ getDefaultRecentEmojis,+ getEmojiLocaleData,+ getLocalizedEmojiTitle,+ getRandomEmoji,+ parseStoredRecentEmojis,+ promoteRecentEmoji,+ searchEmojis,+} from './emoji-picker-utils';+import { emojis } from './emojis.generated';++export const EMOJI_PICKER_COMPONENT = 'ui.emoji-picker';++const RECENTS_STORAGE_KEY = 'univer.ui.recent-emojis';+const ACTIVE_SECTION_SCROLL_OFFSET = 28;++export interface IEmojiPickerPopupProps {+ activeEmoji?: string;+ onSelect?: (emoji: string, options?: { keepOpen?: boolean }) => void;+ recentStorageKey?: string;+}++type EmojiSectionKey = 'recent' | EmojiCategory;+interface IEmojiSection { emojis: IEmojiItem[]; key: EmojiSectionKey; title: string }++export function EmojiPicker(props: { popup?: IPopup<IEmojiPickerPopupProps> }) {+ const extraProps = props.popup?.extraProps;+ const localeService = useDependency(LocaleService);+ const localStorageService = useDependency(ILocalStorageService);+ const currentLocale = useObservable(localeService.currentLocale$, localeService.getCurrentLocale());+ const scrollRef = useRef<HTMLDivElement>(null);+ const sectionRefs = useRef<Partial<Record<EmojiSectionKey, HTMLDivElement | null>>>({});+ const [query, setQuery] = useState('');+ const [activeEmoji, setActiveEmoji] = useState(extraProps?.activeEmoji);+ const [activeTab, setActiveTab] = useState<EmojiSectionKey>('recent');+ const [recents, setRecents] = useState<IEmojiItem[]>(() => getDefaultRecentEmojis());+ const deferredQuery = useDeferredValue(query);+ const emojiLocaleData = useMemo(() => getEmojiLocaleData(localeService), [currentLocale, localeService]);+ const searchResults = useMemo(+ () => searchEmojis(deferredQuery, emojiLocaleData.emojiSearchIndex),+ [deferredQuery, emojiLocaleData]+ );+ const recentStorageKey = extraProps?.recentStorageKey ?? RECENTS_STORAGE_KEY;+ const isSearching = deferredQuery.trim().length > 0;+ const normalSections = [+ { key: 'recent' as const, title: localeService.t<LocaleKey>('ui.emojiPicker.recents'), emojis: recents },+ ...EMOJI_CATEGORIES.map((category) => ({+ key: category.key,+ title: localeService.t(category.titleKey),+ emojis: emojis[category.key],+ })),+ ];+ const sections = isSearching+ ? [{ key: 'people' as const, title: localeService.t<LocaleKey>('ui.emojiPicker.searchResults'), emojis: searchResults }]+ : normalSections;+ const renderedSections = sections.filter((section) => section.emojis.length);++ useEffect(() => {+ let disposed = false;++ localStorageService+ .getItem<IEmojiItem[] | string>(recentStorageKey)+ .then((storedRecents) => {+ if (!disposed) {+ setRecents(parseStoredRecentEmojis(storedRecents));+ }+ })+ .catch(() => undefined);++ return () => {+ disposed = true;+ };+ }, [localStorageService, recentStorageKey]);++ const handleSelect = (item: IEmojiItem, options?: { keepOpen?: boolean }) => {+ const nextRecents = promoteRecentEmoji(recents, item);+ setActiveEmoji(item.emoji);+ setRecents(nextRecents);+ writeRecents(localStorageService, recentStorageKey, nextRecents);+ extraProps?.onSelect?.(item.emoji, options);+ };++ const handleRandom = () => {+ handleSelect(getRandomEmoji(), { keepOpen: true });+ };++ const handleScroll = (event: UIEvent<HTMLDivElement>) => {+ if (isSearching) {+ return;+ }++ setActiveTab(getActiveSectionByScrollTop(normalSections, sectionRefs.current, event.currentTarget.scrollTop));+ };++ const scrollToSection = (section: EmojiSectionKey) => {+ setQuery('');+ setActiveTab(section);+ requestAnimationFrame(() => {+ const sectionElement = sectionRefs.current[section];+ if (scrollRef.current && sectionElement) {+ scrollRef.current.scrollTop = sectionElement.offsetTop;+ }+ });+ };++ return (+ <section+ data-u-comp={EMOJI_PICKER_COMPONENT}+ className="+ univer-flex univer-h-[340px] univer-w-[420px] univer-flex-col univer-overflow-hidden univer-rounded-[10px]+ univer-border univer-border-solid univer-border-gray-200 univer-bg-white univer-shadow-lg+ dark:!univer-border-gray-600 dark:!univer-bg-gray-900+ "+ >+ <div className="univer-flex univer-items-center univer-gap-1 univer-px-3 univer-pb-2 univer-pt-3">+ <label+ className="+ univer-flex univer-h-8 univer-flex-1 univer-items-center univer-gap-1 univer-rounded-lg+ univer-border univer-border-solid univer-border-primary-500 univer-px-2 univer-text-gray-500+ dark:!univer-border-primary-600 dark:!univer-text-gray-400+ "+ >+ <SearchIcon />+ <Input+ aria-label={localeService.t<LocaleKey>('ui.emojiPicker.search')}+ placeholder={localeService.t<LocaleKey>('ui.emojiPicker.search')}+ className="univer-min-w-0 univer-flex-1"+ value={query}+ onChange={setQuery}+ />+ </label>+ <button+ type="button"+ aria-label={localeService.t<LocaleKey>('ui.emojiPicker.random')}+ title={localeService.t<LocaleKey>('ui.emojiPicker.random')}+ className="+ univer-box-border univer-flex univer-size-8 univer-cursor-pointer univer-items-center+ univer-justify-center univer-rounded-lg univer-border univer-border-solid univer-border-gray-300+ univer-bg-white univer-p-0 univer-text-gray-500+ hover:univer-border-gray-400 hover:univer-bg-gray-50+ dark:!univer-border-gray-600 dark:!univer-bg-gray-800 dark:!univer-text-gray-400+ dark:hover:!univer-bg-gray-700+ "+ onClick={handleRandom}+ >+ <RandomIcon />+ </button>+ </div>++ <div+ ref={scrollRef}+ className="univer-relative univer-min-h-0 univer-flex-1 univer-overflow-y-auto univer-px-3"+ onScroll={handleScroll}+ >+ {renderedSections.length+ ? (+ <div className="univer-flex univer-flex-col univer-gap-1.5 univer-pb-2">+ {renderedSections.map((section) => (+ <EmojiSectionView+ key={section.key}+ activeEmoji={activeEmoji}+ emojiTitles={emojiLocaleData.emojiTitles}+ section={section}+ onSelect={handleSelect}+ refElement={(element) => {+ sectionRefs.current[section.key] = element;+ }}+ />+ ))}+ </div>+ )+ : (+ <div+ className="+ univer-py-7 univer-text-center univer-text-sm univer-text-gray-400+ dark:!univer-text-gray-500+ "+ >+ {localeService.t<LocaleKey>('ui.emojiPicker.noResults')}+ </div>+ )}+ </div>++ <div+ className={clsx(`+ univer-flex univer-h-10 univer-shrink-0 univer-items-center univer-border-gray-200 univer-px-2.5+ dark:!univer-border-gray-600+ [&_svg]:univer-size-5+ `, borderTopClassName)}+ >+ <CategoryButton+ selected={!isSearching && activeTab === 'recent'}+ title={localeService.t<LocaleKey>('ui.emojiPicker.recents')}+ onClick={() => scrollToSection('recent')}+ >+ <RecentIcon />+ </CategoryButton>+ {EMOJI_CATEGORIES.map((category) => (+ <CategoryButton+ key={category.key}+ selected={!isSearching && activeTab === category.key}+ title={localeService.t(category.titleKey)}+ onClick={() => scrollToSection(category.key)}+ >+ <CategoryIcon category={category.key} />+ </CategoryButton>+ ))}+ </div>+ </section>+ );+}++function EmojiSectionView(props: {+ activeEmoji?: string;+ emojiTitles?: Record<string, string>;+ onSelect: (item: IEmojiItem, options?: { keepOpen?: boolean }) => void;+ refElement: (element: HTMLDivElement | null) => void;+ section: IEmojiSection;+}) {+ return (+ <section ref={props.refElement} className="univer-flex univer-flex-col univer-gap-1">+ <div+ className="+ univer-text-xs univer-text-gray-500+ dark:!univer-text-gray-400+ "+ >+ {props.section.title}+ </div>+ <EmojiGrid+ activeEmoji={props.activeEmoji}+ emojiTitles={props.emojiTitles}+ items={props.section.emojis}+ keyPrefix={props.section.key}+ onSelect={props.onSelect}+ />+ </section>+ );+}++function EmojiGrid(props: {+ activeEmoji?: string;+ emojiTitles?: Record<string, string>;+ items: IEmojiItem[];+ keyPrefix: string;+ onSelect: (item: IEmojiItem, options?: { keepOpen?: boolean }) => void;+}) {+ return (+ <div className="univer-grid univer-grid-cols-10 univer-justify-between univer-gap-1">+ {props.items.map((item) => {+ const title = getLocalizedEmojiTitle(item, props.emojiTitles);+ const active = props.activeEmoji === item.emoji;++ return (+ <button+ key={`${props.keyPrefix}-${item.emoji}-${item.title}`}+ type="button"+ aria-label={title}+ title={title}+ className={clsx(+ `+ univer-flex univer-size-7 univer-cursor-pointer univer-items-center univer-justify-center+ univer-rounded-lg univer-border-0 univer-bg-transparent univer-p-0 univer-text-lg+ dark:!univer-text-gray-200+ `,+ active+ ? `+ univer-bg-primary-50 univer-shadow-sm+ dark:!univer-bg-gray-800 dark:!univer-shadow-sm+ `+ : `+ hover:univer-bg-gray-100+ dark:hover:!univer-bg-gray-800+ `+ )}+ onClick={() => props.onSelect(item, { keepOpen: true })}+ >+ {item.emoji}+ </button>+ );+ })}+ </div>+ );+}++function CategoryButton(props: { children: ReactElement; onClick: () => void; selected: boolean; title: string }) {+ return (+ <button+ type="button"+ aria-label={props.title}+ aria-selected={props.selected}+ title={props.title}+ className={clsx(+ `+ univer-flex univer-h-[30px] univer-flex-1 univer-cursor-pointer univer-items-center+ univer-justify-center univer-rounded-lg univer-border-0 univer-bg-transparent univer-p-0+ univer-text-gray-500+ dark:!univer-text-gray-400+ `,+ props.selected+ ? `+ univer-bg-primary-50 univer-text-primary-500+ dark:!univer-bg-gray-800 dark:!univer-text-primary-400+ `+ : `+ hover:univer-bg-gray-50 hover:univer-text-gray-700+ dark:hover:!univer-bg-gray-800 dark:hover:!univer-text-gray-300+ `+ )}+ onClick={props.onClick}+ >+ {props.children}+ </button>+ );+}++function writeRecents(localStorageService: ILocalStorageService, storageKey: string, recents: IEmojiItem[]): void {+ void localStorageService+ .setItem(storageKey, recents)+ .catch(() => undefined);+}++function getActiveSectionByScrollTop(+ sections: IEmojiSection[],+ sectionElements: Partial<Record<EmojiSectionKey, HTMLDivElement | null>>,+ scrollTop: number+): EmojiSectionKey {+ let active: EmojiSectionKey = 'recent';++ sections.forEach((section) => {+ const element = sectionElements[section.key];+ if (element && element.offsetTop <= scrollTop + ACTIVE_SECTION_SCROLL_OFFSET) {+ active = section.key;+ }+ });++ return active;+}++function CategoryIcon(props: { category: EmojiCategory }) {+ switch (props.category) {+ case 'activity':+ return <ActivityIcon />;+ case 'foods':+ return <FoodsIcon />;+ case 'nature':+ return <NatureIcon />;+ case 'objects':+ return <ObjectsIcon />;+ case 'people':+ return <PeopleIcon />;+ case 'places':+ return <PlacesIcon />;+ case 'symbols':+ default:+ return <SymbolsIcon />;+ }+}diff --git a/packages/ui/src/views/emoji-picker/__tests__/emoji-picker-utils.spec.ts b/packages/ui/src/views/emoji-picker/__tests__/emoji-picker-utils.spec.tsnew file mode 100644index 0000000000..1e1d5538b1--- /dev/null+++ b/packages/ui/src/views/emoji-picker/__tests__/emoji-picker-utils.spec.ts@@ -0,0 +1,64 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it } from 'vitest';+import {+ getDefaultRecentEmojis,+ parseStoredRecentEmojis,+ promoteRecentEmoji,+ searchEmojis,+} from '../emoji-picker-utils';+import { emojis } from '../emojis.generated';++describe('emoji picker utils', () => {+ it('falls back to frequent emojis when recents are empty or invalid', () => {+ expect(parseStoredRecentEmojis(null)).toEqual(getDefaultRecentEmojis());+ expect(parseStoredRecentEmojis('broken')).toEqual(getDefaultRecentEmojis());+ });++ it('accepts recent emojis already decoded by local storage service', () => {+ expect(parseStoredRecentEmojis([{ emoji: '💡', title: 'Light Bulb' }])).toEqual([{ emoji: '💡', title: 'Light Bulb' }]);+ });++ it('promotes the selected emoji to the front and removes duplicates', () => {+ const result = promoteRecentEmoji([+ { emoji: '😀', title: 'Grinning Face' },+ { emoji: '💡', title: 'Light Bulb' },+ ], { emoji: '💡', title: 'Light Bulb' });++ expect(result.map((item) => item.emoji)).toEqual(['💡', '😀']);+ });++ it('searches emoji title case-insensitively', () => {+ const result = searchEmojis('light bulb');++ expect(result.some((item) => item.emoji === '💡')).toBe(true);+ });++ it('searches localized emoji titles', () => {+ const result = searchEmojis('灯泡', { '💡': '灯泡 电灯泡 主意' });++ expect(result.some((item) => item.emoji === '💡')).toBe(true);+ });++ it('keeps generated locale search indexes aligned with generated emojis', async () => {+ const allEmojis = [...new Set(Object.values(emojis).flat().map((item) => item.emoji))];+ const { default: zhCNEmojiLocale } = await import('../../../locale/emoji-locale/zh-CN.generated');+ const { emojiSearchIndex } = zhCNEmojiLocale;++ expect(allEmojis.every((emoji) => typeof emojiSearchIndex[emoji] === 'string' && emojiSearchIndex[emoji].length > 0)).toBe(true);+ });+});diff --git a/packages/ui/src/views/emoji-picker/emoji-picker-utils.ts b/packages/ui/src/views/emoji-picker/emoji-picker-utils.tsnew file mode 100644index 0000000000..b023ee39ca--- /dev/null+++ b/packages/ui/src/views/emoji-picker/emoji-picker-utils.ts@@ -0,0 +1,127 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { LocaleService } from '@univerjs/core';+import { emojis } from './emojis.generated';++export interface IEmojiItem {+ emoji: string;+ title: string;+}++export interface IEmojiLocaleData {+ emojiSearchIndex?: Record<string, string>;+ emojiTitles?: Record<string, string>;+}++export type EmojiCategory = Exclude<keyof typeof emojis, 'frequent'>;++export const EMOJI_RECENT_LIMIT = 11;++const EMOJI_CATEGORY_LABEL_KEYS: Record<EmojiCategory, string> = {+ activity: 'ui.emojiPicker.activities',+ foods: 'ui.emojiPicker.food',+ nature: 'ui.emojiPicker.animals',+ objects: 'ui.emojiPicker.objects',+ people: 'ui.emojiPicker.emojis',+ places: 'ui.emojiPicker.places',+ symbols: 'ui.emojiPicker.symbols',+};++export const EMOJI_CATEGORIES = Object.keys(emojis)+ .filter((category): category is EmojiCategory => category !== 'frequent')+ .map((category) => ({+ key: category,+ titleKey: EMOJI_CATEGORY_LABEL_KEYS[category],+ }));++export function getDefaultRecentEmojis(): IEmojiItem[] {+ return emojis.frequent.slice(0, EMOJI_RECENT_LIMIT);+}++export function getAllEmojis(): IEmojiItem[] {+ return EMOJI_CATEGORIES.flatMap((category) => emojis[category.key]);+}++export function searchEmojis(keyword: string, searchIndex?: Record<string, string>): IEmojiItem[] {+ const query = keyword.trim().toLowerCase();+ if (!query) {+ return [];+ }++ return getAllEmojis().filter((item) => getEmojiSearchText(item, searchIndex).includes(query));+}++export function promoteRecentEmoji(recents: IEmojiItem[], item: IEmojiItem): IEmojiItem[] {+ return [+ item,+ ...recents.filter((recent) => recent.emoji !== item.emoji),+ ].slice(0, EMOJI_RECENT_LIMIT);+}++export function parseStoredRecentEmojis(value: IEmojiItem[] | string | null): IEmojiItem[] {+ if (!value) {+ return getDefaultRecentEmojis();+ }++ if (Array.isArray(value)) {+ return normalizeStoredRecentEmojis(value);+ }++ try {+ const parsed = JSON.parse(value) as IEmojiItem[];+ return normalizeStoredRecentEmojis(parsed);+ } catch {+ return getDefaultRecentEmojis();+ }+}++export function getRandomEmoji(random = Math.random): IEmojiItem {+ const allEmojis = getAllEmojis();+ return allEmojis[Math.floor(random() * allEmojis.length)] ?? getDefaultRecentEmojis()[0];+}++export function getLocalizedEmojiTitle(item: IEmojiItem, emojiTitles?: Record<string, string>): string {+ return emojiTitles?.[item.emoji] ?? item.title;+}++export function getEmojiLocaleData(localeService: Pick<LocaleService, 'getLocales'>): IEmojiLocaleData {+ const localePack = localeService.getLocales();+ const uiLocale = localePack?.ui as { emojiPicker?: unknown } | undefined;+ const emojiPicker = uiLocale?.emojiPicker;++ if (!emojiPicker || typeof emojiPicker !== 'object' || Array.isArray(emojiPicker)) {+ return {};+ }++ return emojiPicker as IEmojiLocaleData;+}++function getEmojiSearchText(item: IEmojiItem, searchIndex?: Record<string, string>): string {+ return [+ item.title,+ searchIndex?.[item.emoji],+ ].filter(Boolean).join(' ').toLowerCase();+}++function normalizeStoredRecentEmojis(value: unknown): IEmojiItem[] {+ if (!Array.isArray(value)) {+ return getDefaultRecentEmojis();+ }++ const valid = value.filter((item) => typeof item?.emoji === 'string' && typeof item?.title === 'string');+ return valid.length ? valid.slice(0, EMOJI_RECENT_LIMIT) : getDefaultRecentEmojis();+}diff --git a/packages/ui/src/views/emoji-picker/index.ts b/packages/ui/src/views/emoji-picker/index.tsnew file mode 100644index 0000000000..e310c756a4--- /dev/null+++ b/packages/ui/src/views/emoji-picker/index.ts@@ -0,0 +1,31 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++export {+ EMOJI_CATEGORIES,+ EMOJI_RECENT_LIMIT,+ getAllEmojis,+ getDefaultRecentEmojis,+ getEmojiLocaleData,+ getLocalizedEmojiTitle,+ getRandomEmoji,+ parseStoredRecentEmojis,+ promoteRecentEmoji,+ searchEmojis,+} from './emoji-picker-utils';+export type { EmojiCategory, IEmojiItem, IEmojiLocaleData } from './emoji-picker-utils';+export { EMOJI_PICKER_COMPONENT, EmojiPicker } from './EmojiPicker';+export type { IEmojiPickerPopupProps } from './EmojiPicker';diff --git a/packages/ui/src/views/index.ts b/packages/ui/src/views/index.tsindex 921b80c714..10a5615959 100644--- a/packages/ui/src/views/index.ts+++ b/packages/ui/src/views/index.ts@@ -16,6 +16,7 @@export * from './CommonLabel';export * from './custom-label/index';+export * from './emoji-picker/index';export * from './HeadingItem';export { useScrollYOverContainer } from './hooks/layout';