Skip to content

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.

feat(docs-ui): add document statistics (#7498)

Univer60c9628dd791
diff --git a/e2e/visual-comparison/docs/docs-visual-comparison.spec.ts-snapshots/default-doc-ci-chromium-linux.png b/e2e/visual-comparison/docs/docs-visual-comparison.spec.ts-snapshots/default-doc-ci-chromium-linux.png
index 17c57b789a..9dde531517 100644
Binary files a/e2e/visual-comparison/docs/docs-visual-comparison.spec.ts-snapshots/default-doc-ci-chromium-linux.png and b/e2e/visual-comparison/docs/docs-visual-comparison.spec.ts-snapshots/default-doc-ci-chromium-linux.png differ
diff --git a/packages/core/src/docs/data-model/__tests__/document-statistics.spec.ts b/packages/core/src/docs/data-model/__tests__/document-statistics.spec.ts
new file mode 100644
index 0000000000..a93584bc9d
--- /dev/null
+++ b/packages/core/src/docs/data-model/__tests__/document-statistics.spec.ts
@@ -0,0 +1,58 @@
+/**
+ * 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 { LocaleType } from '../../../types/enum/locale-type';
+import { DocumentDataModel } from '../document-data-model';
+
+describe('DocumentDataModel.getStatistics', () => {
+ const model = new DocumentDataModel({ body: { dataStream: '你好,世界!\rHello world 123.\rOne\tTwo three\r\n' } });
+
+ it('calculates mixed-language document statistics asynchronously', async () => {
+ await expect(model.getStatistics({ locale: LocaleType.ZH_CN })).resolves.toEqual({
+ words: 12,
+ charactersWithoutSpaces: 31,
+ charactersWithSpaces: 36,
+ paragraphs: 3,
+ nonAsianWords: 6,
+ asianCharactersAndKoreanWords: 6,
+ });
+ });
+
+ it('merges overlapping selections before calculating statistics', async () => {
+ await expect(model.getStatistics({
+ locale: LocaleType.EN_US,
+ ranges: [
+ { startOffset: 9, endOffset: 20, collapsed: false },
+ { startOffset: 15, endOffset: 20, collapsed: false },
+ ],
+ })).resolves.toEqual({
+ words: 3,
+ charactersWithoutSpaces: 9,
+ charactersWithSpaces: 11,
+ paragraphs: 0,
+ nonAsianWords: 3,
+ asianCharactersAndKoreanWords: 0,
+ });
+ });
+
+ it('stops obsolete calculations', async () => {
+ const controller = new AbortController();
+ controller.abort();
+
+ await expect(model.getStatistics({ signal: controller.signal })).rejects.toThrow();
+ });
+});
diff --git a/packages/core/src/docs/data-model/document-data-model.ts b/packages/core/src/docs/data-model/document-data-model.ts
index 492c19bf2b..1d103b2599 100644
--- a/packages/core/src/docs/data-model/document-data-model.ts
+++ b/packages/core/src/docs/data-model/document-data-model.ts
@@ -15,6 +15,8 @@
*/
import type { Nullable } from '../../shared';
+import type { ITextRangeParam } from '../../sheets/typedef';
+import type { LocaleType } from '../../types/enum';
import type {
IDocumentBody,
IDocumentData,
@@ -31,6 +33,7 @@ import { mergeWith } from '../../common/lodash';
import { UnitModel, UniverInstanceType } from '../../common/unit';
import { generateRandomId } from '../../shared/random-id';
import { Tools } from '../../shared/tools';
+import { calculateDocumentStatistics } from './document-statistics';
import { getEmptySnapshot } from './empty-snapshot';
import { JSONX } from './json-x/json-x';
import { PRESET_LIST_TYPE } from './preset-list-type';
@@ -42,6 +45,21 @@ export const DEFAULT_DOC = {
documentStyle: {},
};
+export interface IDocumentStatistics {
+ words: number;
+ charactersWithoutSpaces: number;
+ charactersWithSpaces: number;
+ paragraphs: number;
+ nonAsianWords: number;
+ asianCharactersAndKoreanWords: number;
+}
+
+export interface IDocumentStatisticsOptions {
+ locale?: LocaleType;
+ ranges?: Readonly<ITextRangeParam[]>;
+ signal?: AbortSignal;
+}
+
function createDocumentSnapshot(snapshot: Partial<IDocumentData>): IDocumentData {
if (snapshot.id != null && isInternalEditorID(snapshot.id)) {
return { ...DEFAULT_DOC, ...snapshot } as IDocumentData;
@@ -409,4 +427,8 @@ export class DocumentDataModel extends DocumentDataModelSimple {
getPlainText() {
return getPlainText(this.getBody()?.dataStream ?? '');
}
+
+ getStatistics(options: IDocumentStatisticsOptions = {}): Promise<IDocumentStatistics> {
+ return calculateDocumentStatistics(this.getBody()?.dataStream ?? '', options);
+ }
}
diff --git a/packages/core/src/docs/data-model/document-statistics.ts b/packages/core/src/docs/data-model/document-statistics.ts
new file mode 100644
index 0000000000..0befce05b8
--- /dev/null
+++ b/packages/core/src/docs/data-model/document-statistics.ts
@@ -0,0 +1,170 @@
+/**
+ * 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 { IDocumentStatistics, IDocumentStatisticsOptions } from './document-data-model';
+import { LOCALE_META } from '../../types/enum/locale-type';
+import { DataStreamTreeTokenType } from './types';
+
+const CONTROL_TOKENS = new Set<string>([
+ DataStreamTreeTokenType.PARAGRAPH,
+ DataStreamTreeTokenType.SECTION_BREAK,
+ DataStreamTreeTokenType.TABLE_START,
+ DataStreamTreeTokenType.TABLE_ROW_START,
+ DataStreamTreeTokenType.TABLE_CELL_START,
+ DataStreamTreeTokenType.TABLE_CELL_END,
+ DataStreamTreeTokenType.TABLE_ROW_END,
+ DataStreamTreeTokenType.TABLE_END,
+ DataStreamTreeTokenType.COLUMN_GROUP_START,
+ DataStreamTreeTokenType.COLUMN_START,
+ DataStreamTreeTokenType.COLUMN_END,
+ DataStreamTreeTokenType.COLUMN_GROUP_END,
+ DataStreamTreeTokenType.BLOCK_START,
+ DataStreamTreeTokenType.BLOCK_END,
+ DataStreamTreeTokenType.COLUMN_BREAK,
+ DataStreamTreeTokenType.PAGE_BREAK,
+ DataStreamTreeTokenType.DOCS_END,
+ DataStreamTreeTokenType.CUSTOM_BLOCK,
+]);
+
+const EAST_ASIAN_CHARACTER = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Bopomofo}\u3000-\u303F\uFF00-\uFFEF]/u;
+const KOREAN_CHARACTER = /\p{Script=Hangul}/u;
+const YIELD_INTERVAL = 20_000;
+
+function emptyStatistics(): IDocumentStatistics {
+ return {
+ words: 0,
+ charactersWithoutSpaces: 0,
+ charactersWithSpaces: 0,
+ paragraphs: 0,
+ nonAsianWords: 0,
+ asianCharactersAndKoreanWords: 0,
+ };
+}
+
+function throwIfAborted(signal?: AbortSignal): void {
+ if (signal?.aborted) {
+ throw new Error('Document statistics calculation aborted');
+ }
+}
+
+function yieldExecution(signal?: AbortSignal): Promise<void> {
+ throwIfAborted(signal);
+
+ return new Promise((resolve) => {
+ setTimeout(resolve, 0);
+ });
+}
+
+function getRangeFragments(dataStream: string, ranges: IDocumentStatisticsOptions['ranges']): string[] {
+ if (!ranges?.length) {
+ return [dataStream];
+ }
+
+ const normalizedRanges = ranges
+ .filter((range) => !range.collapsed)
+ .map((range) => ({
+ startOffset: Math.max(0, Math.min(range.startOffset, range.endOffset)),
+ endOffset: Math.min(dataStream.length, Math.max(range.startOffset, range.endOffset)),
+ }))
+ .filter((range) => range.startOffset < range.endOffset)
+ .sort((a, b) => a.startOffset - b.startOffset || a.endOffset - b.endOffset);
+
+ const mergedRanges: Array<{ startOffset: number; endOffset: number }> = [];
+ for (const range of normalizedRanges) {
+ const previous = mergedRanges.at(-1);
+ if (previous && range.startOffset <= previous.endOffset) {
+ previous.endOffset = Math.max(previous.endOffset, range.endOffset);
+ } else {
+ mergedRanges.push({ ...range });
+ }
+ }
+
+ return mergedRanges.map((range) => dataStream.slice(range.startOffset, range.endOffset));
+}
+
+function isControlToken(segment: string): boolean {
+ return Array.from(segment).every((character) => CONTROL_TOKENS.has(character));
+}
+
+export async function calculateDocumentStatistics(
+ dataStream: string,
+ options: IDocumentStatisticsOptions
+): Promise<IDocumentStatistics> {
+ const { locale, ranges, signal } = options;
+ const localeTag = locale == null ? undefined : LOCALE_META[locale].tag;
+ const graphemeSegmenter = new Intl.Segmenter(localeTag, { granularity: 'grapheme' });
+ const wordSegmenter = new Intl.Segmenter(localeTag, { granularity: 'word' });
+ const statistics = emptyStatistics();
+
+ await yieldExecution(signal);
+ throwIfAborted(signal);
+
+ for (const fragment of getRangeFragments(dataStream, ranges)) {
+ let processedCharacters = 0;
+ let paragraphHasContent = false;
+
+ for (const { segment } of graphemeSegmenter.segment(fragment)) {
+ throwIfAborted(signal);
+
+ if (segment.includes(DataStreamTreeTokenType.PARAGRAPH)) {
+ if (paragraphHasContent) {
+ statistics.paragraphs += 1;
+ }
+ paragraphHasContent = false;
+ }
+
+ if (!isControlToken(segment)) {
+ statistics.charactersWithSpaces += 1;
+ if (!/^\s+$/u.test(segment)) {
+ statistics.charactersWithoutSpaces += 1;
+ paragraphHasContent = true;
+ }
+
+ if (EAST_ASIAN_CHARACTER.test(segment)) {
+ statistics.asianCharactersAndKoreanWords += 1;
+ }
+ }
+
+ processedCharacters += segment.length;
+ if (processedCharacters >= YIELD_INTERVAL) {
+ processedCharacters = 0;
+ await yieldExecution(signal);
+ }
+ }
+
+ let processedWordCharacters = 0;
+ for (const word of wordSegmenter.segment(fragment)) {
+ throwIfAborted(signal);
+ if (word.isWordLike && !EAST_ASIAN_CHARACTER.test(word.segment)) {
+ if (KOREAN_CHARACTER.test(word.segment)) {
+ statistics.asianCharactersAndKoreanWords += 1;
+ } else {
+ statistics.nonAsianWords += 1;
+ }
+ }
+
+ processedWordCharacters += word.segment.length;
+ if (processedWordCharacters >= YIELD_INTERVAL) {
+ processedWordCharacters = 0;
+ await yieldExecution(signal);
+ }
+ }
+ }
+
+ throwIfAborted(signal);
+ statistics.words = statistics.nonAsianWords + statistics.asianCharactersAndKoreanWords;
+ return statistics;
+}
diff --git a/packages/docs-ui/src/config/config.ts b/packages/docs-ui/src/config/config.ts
index 9728336d52..a18d1aa3d5 100644
--- a/packages/docs-ui/src/config/config.ts
+++ b/packages/docs-ui/src/config/config.ts
@@ -40,6 +40,7 @@ export interface IUniverDocsUIConfig {
container?: HTMLElement | string;
toc?: boolean;
footer?: boolean;
+ wordCount?: boolean;
placeholder?: boolean;
fitToWidth?: IDocFitToWidthOptions;
override?: DependencyOverride;
@@ -57,6 +58,7 @@ export const DEFAULT_DOC_FIT_TO_WIDTH_OPTIONS: Required<Omit<IDocFitToWidthOptio
export const defaultPluginConfig: IUniverDocsUIConfig = {
toc: false,
footer: true,
+ wordCount: true,
placeholder: true,
fitToWidth: DEFAULT_DOC_FIT_TO_WIDTH_OPTIONS,
};
diff --git a/packages/docs-ui/src/locale/ar-SA.ts b/packages/docs-ui/src/locale/ar-SA.ts
index 1999d8862b..c5560bb3da 100644
--- a/packages/docs-ui/src/locale/ar-SA.ts
+++ b/packages/docs-ui/src/locale/ar-SA.ts
@@ -95,6 +95,22 @@ const locale: typeof enUS = {
closeHeaderFooter: 'إغلاق الرأس والتذييل',
disableText: 'إعدادات الرأس والتذييل معطلة',
},
+ statistics: {
+ title: 'إحصاءات المستند',
+ open: 'عرض إحصاءات المستند',
+ document: 'المستند بالكامل',
+ selection: 'التحديد الحالي',
+ wordCount: '{0} كلمة',
+ selectedWords: '{0} من {1} كلمة',
+ pages: 'الصفحات',
+ words: 'الكلمات',
+ charactersWithoutSpaces: 'الأحرف (بدون مسافات)',
+ charactersWithSpaces: 'الأحرف (مع المسافات)',
+ paragraphs: 'الفقرات',
+ lines: 'الأسطر',
+ nonAsianWords: 'الكلمات غير الآسيوية',
+ asianCharactersAndKoreanWords: 'الأحرف الآسيوية والكلمات الكورية',
+ },
placeholder: {
heading1: 'العنوان 1',
heading2: 'العنوان 2',
diff --git a/packages/docs-ui/src/locale/ca-ES.ts b/packages/docs-ui/src/locale/ca-ES.ts
index a4548267db..c2cfd5e031 100644
--- a/packages/docs-ui/src/locale/ca-ES.ts
+++ b/packages/docs-ui/src/locale/ca-ES.ts
@@ -95,6 +95,22 @@ const locale: typeof enUS = {
closeHeaderFooter: 'Tanca capçalera i peu de pàgina',
disableText: 'La configuració de capçalera i peu de pàgina està desactivada',
},
+ statistics: {
+ title: 'Estadístiques del document',
+ open: 'Mostra les estadístiques del document',
+ document: 'Document sencer',
+ selection: 'Selecció actual',
+ wordCount: '{0} paraules',
+ selectedWords: '{0} de {1} paraules',
+ pages: 'Pàgines',
+ words: 'Paraules',
+ charactersWithoutSpaces: 'Caràcters (sense espais)',
+ charactersWithSpaces: 'Caràcters (amb espais)',
+ paragraphs: 'Paràgrafs',
+ lines: 'Línies',
+ nonAsianWords: 'Paraules no asiàtiques',
+ asianCharactersAndKoreanWords: 'Caràcters asiàtics i paraules coreanes',
+ },
placeholder: {
heading1: 'Títol 1',
heading2: 'Títol 2',
diff --git a/packages/docs-ui/src/locale/de-DE.ts b/packages/docs-ui/src/locale/de-DE.ts
index 9ba938a905..dd140ab04f 100644
--- a/packages/docs-ui/src/locale/de-DE.ts
+++ b/packages/docs-ui/src/locale/de-DE.ts
@@ -95,6 +95,22 @@ const locale: typeof enUS = {
closeHeaderFooter: 'Kopf- und Fußzeile schließen',
disableText: 'Kopf- und Fußzeileneinstellungen sind deaktiviert',
},
+ statistics: {
+ title: 'Dokumentstatistik',
+ open: 'Dokumentstatistik anzeigen',
+ document: 'Gesamtes Dokument',
+ selection: 'Aktuelle Auswahl',
+ wordCount: '{0} Wörter',
+ selectedWords: '{0} von {1} Wörtern',
+ pages: 'Seiten',
+ words: 'Wörter',
+ charactersWithoutSpaces: 'Zeichen (ohne Leerzeichen)',
+ charactersWithSpaces: 'Zeichen (mit Leerzeichen)',
+ paragraphs: 'Absätze',
+ lines: 'Zeilen',
+ nonAsianWords: 'Nicht-asiatische Wörter',
+ asianCharactersAndKoreanWords: 'Asiatische Zeichen und koreanische Wörter',
+ },
placeholder: {
heading1: 'Überschrift 1',
heading2: 'Überschrift 2',
diff --git a/packages/docs-ui/src/locale/en-US.ts b/packages/docs-ui/src/locale/en-US.ts
index 7c8f254c38..cefc08680c 100644
--- a/packages/docs-ui/src/locale/en-US.ts
+++ b/packages/docs-ui/src/locale/en-US.ts
@@ -93,6 +93,22 @@ const locale = {
closeHeaderFooter: 'Close header & footer',
disableText: 'Header & footer settings are disabled',
},
+ statistics: {
+ title: 'Document statistics',
+ open: 'View document statistics',
+ document: 'Entire document',
+ selection: 'Current selection',
+ wordCount: '{0} words',
+ selectedWords: '{0} of {1} words',
+ pages: 'Pages',
+ words: 'Words',
+ charactersWithoutSpaces: 'Characters (no spaces)',
+ charactersWithSpaces: 'Characters (with spaces)',
+ paragraphs: 'Paragraphs',
+ lines: 'Lines',
+ nonAsianWords: 'Non-Asian words',
+ asianCharactersAndKoreanWords: 'Asian characters and Korean words',
+ },
placeholder: {
heading1: 'Heading 1',
heading2: 'Heading 2',
diff --git a/packages/docs-ui/src/locale/es-ES.ts b/packages/docs-ui/src/locale/es-ES.ts
index 9b07cdd133..90a2bd552f 100644
--- a/packages/docs-ui/src/locale/es-ES.ts
+++ b/packages/docs-ui/src/locale/es-ES.ts
@@ -95,6 +95,22 @@ const locale: typeof enUS = {
closeHeaderFooter: 'Cerrar encabezado y pie de página',
disableText: 'La configuración de encabezado y pie de página está deshabilitada',
},
+ statistics: {
+ title: 'Estadísticas del documento',
+ open: 'Ver estadísticas del documento',
+ document: 'Documento completo',
+ selection: 'Selección actual',
+ wordCount: '{0} palabras',
+ selectedWords: '{0} de {1} palabras',
+ pages: 'Páginas',
+ words: 'Palabras',
+ charactersWithoutSpaces: 'Caracteres (sin espacios)',
+ charactersWithSpaces: 'Caracteres (con espacios)',
+ paragraphs: 'Párrafos',
+ lines: 'Líneas',
+ nonAsianWords: 'Palabras no asiáticas',
+ asianCharactersAndKoreanWords: 'Caracteres asiáticos y palabras coreanas',
+ },
placeholder: {
heading1: 'Título 1',
heading2: 'Título 2',
diff --git a/packages/docs-ui/src/locale/fa-IR.ts b/packages/docs-ui/src/locale/fa-IR.ts
index b5e4673904..13f047961b 100644
--- a/packages/docs-ui/src/locale/fa-IR.ts
+++ b/packages/docs-ui/src/locale/fa-IR.ts
@@ -95,6 +95,22 @@ const locale: typeof enUS = {
closeHeaderFooter: 'بستن هدر و فوتر',
disableText: 'تنظیمات هدر و فوتر غیرفعال است',
},
+ statistics: {
+ title: 'آمار سند',
+ open: 'نمایش آمار سند',
+ document: 'کل سند',
+ selection: 'انتخاب فعلی',
+ wordCount: '{0} واژه',
+ selectedWords: '{0} از {1} واژه',
+ pages: 'صفحه‌ها',
+ words: 'واژه‌ها',
+ charactersWithoutSpaces: 'نویسه‌ها (بدون فاصله)',
+ charactersWithSpaces: 'نویسه‌ها (با فاصله)',
+ paragraphs: 'پاراگراف‌ها',
+ lines: 'سطرها',
+ nonAsianWords: 'واژه‌های غیر آسیایی',
+ asianCharactersAndKoreanWords: 'نویسه‌های آسیایی و واژه‌های کره‌ای',
+ },
placeholder: {
heading1: 'عنوان ۱',
heading2: 'عنوان ۲',
diff --git a/packages/docs-ui/src/locale/fr-FR.ts b/packages/docs-ui/src/locale/fr-FR.ts
index efe9f47932..dc947f31bb 100644
--- a/packages/docs-ui/src/locale/fr-FR.ts
+++ b/packages/docs-ui/src/locale/fr-FR.ts
@@ -95,6 +95,22 @@ const locale: typeof enUS = {
closeHeaderFooter: 'Fermer l\'en-tête et le pied de page',
disableText: 'Les paramètres de l\'en-tête et du pied de page sont désactivés',
},
+ statistics: {
+ title: 'Statistiques du document',
+ open: 'Afficher les statistiques du document',
+ document: 'Document entier',
+ selection: 'Sélection actuelle',
+ wordCount: '{0} mots',
+ selectedWords: '{0} mots sur {1}',
+ pages: 'Pages',
+ words: 'Mots',
+ charactersWithoutSpaces: 'Caractères (sans espaces)',
+ charactersWithSpaces: 'Caractères (avec espaces)',
+ paragraphs: 'Paragraphes',
+ lines: 'Lignes',
+ nonAsianWords: 'Mots non asiatiques',
+ asianCharactersAndKoreanWords: 'Caractères asiatiques et mots coréens',
+ },
placeholder: {
heading1: 'Titre 1',
heading2: 'Titre 2',
diff --git a/packages/docs-ui/src/locale/id-ID.ts b/packages/docs-ui/src/locale/id-ID.ts
index b123c53b23..2c55e1a634 100644
--- a/packages/docs-ui/src/locale/id-ID.ts
+++ b/packages/docs-ui/src/locale/id-ID.ts
@@ -95,6 +95,22 @@ const locale: typeof enUS = {
closeHeaderFooter: 'Tutup header & footer',
disableText: 'Pengaturan header & footer dinonaktifkan',
},
+ statistics: {
+ title: 'Statistik dokumen',
+ open: 'Lihat statistik dokumen',
+ document: 'Seluruh dokumen',
+ selection: 'Pilihan saat ini',
+ wordCount: '{0} kata',
+ selectedWords: '{0} dari {1} kata',
+ pages: 'Halaman',
+ words: 'Kata',
+ charactersWithoutSpaces: 'Karakter (tanpa spasi)',
+ charactersWithSpaces: 'Karakter (dengan spasi)',
+ paragraphs: 'Paragraf',
+ lines: 'Baris',
+ nonAsianWords: 'Kata non-Asia',
+ asianCharactersAndKoreanWords: 'Karakter Asia dan kata Korea',
+ },
placeholder: {
heading1: 'Judul 1',
heading2: 'Judul 2',
diff --git a/packages/docs-ui/src/locale/it-IT.ts b/packages/docs-ui/src/locale/it-IT.ts
index 20bd069af3..f5964cb077 100644
--- a/packages/docs-ui/src/locale/it-IT.ts
+++ b/packages/docs-ui/src/locale/it-IT.ts
@@ -95,6 +95,22 @@ const locale: typeof enUS = {
closeHeaderFooter: 'Chiudi intestazione e piè di pagina',
disableText: 'Le impostazioni di intestazione e piè di pagina sono disabilitate',
},
+ statistics: {
+ title: 'Statistiche documento',
+ open: 'Visualizza statistiche documento',
+ document: 'Intero documento',
+ selection: 'Selezione corrente',
+ wordCount: '{0} parole',
+ selectedWords: '{0} di {1} parole',
+ pages: 'Pagine',
+ words: 'Parole',
+ charactersWithoutSpaces: 'Caratteri (spazi esclusi)',
+ charactersWithSpaces: 'Caratteri (spazi inclusi)',
+ paragraphs: 'Paragrafi',
+ lines: 'Righe',
+ nonAsianWords: 'Parole non asiatiche',
+ asianCharactersAndKoreanWords: 'Caratteri asiatici e parole coreane',
+ },
placeholder: {
heading1: 'Titolo 1',
heading2: 'Titolo 2',
diff --git a/packages/docs-ui/src/locale/ja-JP.ts b/packages/docs-ui/src/locale/ja-JP.ts
index 58ef23caca..b0c492069d 100644
--- a/packages/docs-ui/src/locale/ja-JP.ts
+++ b/packages/docs-ui/src/locale/ja-JP.ts
@@ -95,6 +95,22 @@ const locale: typeof enUS = {
closeHeaderFooter: 'ヘッダー/フッターを閉じる',
disableText: 'ヘッダーとフッターの設定は無効です',
},
+ statistics: {
+ title: '文書の統計',
+ open: '文書の統計を表示',
+ document: '文書全体',
+ selection: '現在の選択範囲',
+ wordCount: '{0} 語',
+ selectedWords: '{1} 語中 {0} 語',
+ pages: 'ページ数',
+ words: '単語数',
+ charactersWithoutSpaces: '文字数(スペースを含めない)',
+ charactersWithSpaces: '文字数(スペースを含める)',
+ paragraphs: '段落数',
+ lines: '行数',
+ nonAsianWords: 'アジア言語以外の単語数',
+ asianCharactersAndKoreanWords: 'アジア言語の文字数と韓国語の単語数',
+ },
placeholder: {
heading1: '見出し 1',
heading2: '見出し 2',
diff --git a/packages/docs-ui/src/locale/ko-KR.ts b/packages/docs-ui/src/locale/ko-KR.ts
index ba50f76a5d..24e2792cf3 100644
--- a/packages/docs-ui/src/locale/ko-KR.ts
+++ b/packages/docs-ui/src/locale/ko-KR.ts
@@ -95,6 +95,22 @@ const locale: typeof enUS = {
closeHeaderFooter: '머리글 및 바닥글 닫기',
disableText: '머리글 및 바닥글 설정이 비활성화되었습니다',
},
+ statistics: {
+ title: '문서 통계',
+ open: '문서 통계 보기',
+ document: '전체 문서',
+ selection: '현재 선택 영역',
+ wordCount: '{0}개 단어',
+ selectedWords: '{1}개 중 {0}개 단어',
+ pages: '페이지',
+ words: '단어',
+ charactersWithoutSpaces: '문자 수(공백 제외)',
+ charactersWithSpaces: '문자 수(공백 포함)',
+ paragraphs: '단락',
+ lines: '줄',
+ nonAsianWords: '비아시아권 단어',
+ asianCharactersAndKoreanWords: '아시아 문자 및 한국어 단어',
+ },
placeholder: {
heading1: '제목 1',
heading2: '제목 2',
diff --git a/packages/docs-ui/src/locale/pl-PL.ts b/packages/docs-ui/src/locale/pl-PL.ts
index 1bd91a27ca..31f2ad3954 100644
--- a/packages/docs-ui/src/locale/pl-PL.ts
+++ b/packages/docs-ui/src/locale/pl-PL.ts
@@ -95,6 +95,22 @@ const locale: typeof enUS = {
closeHeaderFooter: 'Zamknij nagłówek i stopkę',
disableText: 'Ustawienia nagłówka i stopki są wyłączone',
},
+ statistics: {
+ title: 'Statystyki dokumentu',
+ open: 'Wyświetl statystyki dokumentu',
+ document: 'Cały dokument',
+ selection: 'Bieżące zaznaczenie',
+ wordCount: 'Liczba wyrazów: {0}',
+ selectedWords: 'Liczba wyrazów: {0} z {1}',
+ pages: 'Strony',
+ words: 'Wyrazy',
+ charactersWithoutSpaces: 'Znaki (bez spacji)',
+ charactersWithSpaces: 'Znaki (ze spacjami)',
+ paragraphs: 'Akapity',
+ lines: 'Wiersze',
+ nonAsianWords: 'Wyrazy nieazjatyckie',
+ asianCharactersAndKoreanWords: 'Znaki azjatyckie i wyrazy koreańskie',
+ },
placeholder: {
heading1: 'Nagłówek 1',
heading2: 'Nagłówek 2',
diff --git a/packages/docs-ui/src/locale/pt-BR.ts b/packages/docs-ui/src/locale/pt-BR.ts
index a8765fc062..9a00debd1c 100644
--- a/packages/docs-ui/src/locale/pt-BR.ts
+++ b/packages/docs-ui/src/locale/pt-BR.ts
@@ -95,6 +95,22 @@ const locale: typeof enUS = {
closeHeaderFooter: 'Fechar cabeçalho e rodapé',
disableText: 'As configurações de cabeçalho e rodapé estão desativadas',
},
+ statistics: {
+ title: 'Estatísticas do documento',
+ open: 'Exibir estatísticas do documento',
+ document: 'Documento inteiro',
+ selection: 'Seleção atual',
+ wordCount: '{0} palavras',
+ selectedWords: '{0} de {1} palavras',
+ pages: 'Páginas',
+ words: 'Palavras',
+ charactersWithoutSpaces: 'Caracteres (sem espaços)',
+ charactersWithSpaces: 'Caracteres (com espaços)',
+ paragraphs: 'Parágrafos',
+ lines: 'Linhas',
+ nonAsianWords: 'Palavras não asiáticas',
+ asianCharactersAndKoreanWords: 'Caracteres asiáticos e palavras coreanas',
+ },
placeholder: {
heading1: 'Título 1',
heading2: 'Título 2',
diff --git a/packages/docs-ui/src/locale/ru-RU.ts b/packages/docs-ui/src/locale/ru-RU.ts
index 80021362b3..a104fbf172 100644
--- a/packages/docs-ui/src/locale/ru-RU.ts
+++ b/packages/docs-ui/src/locale/ru-RU.ts
@@ -95,6 +95,22 @@ const locale: typeof enUS = {
closeHeaderFooter: 'Закрыть верхний и нижний колонтитулы',
disableText: 'Настройки верхнего и нижнего колонтитулов отключены',
},
+ statistics: {
+ title: 'Статистика документа',
+ open: 'Показать статистику документа',
+ document: 'Весь документ',
+ selection: 'Текущее выделение',
+ wordCount: 'Слов: {0}',
+ selectedWords: 'Слов: {0} из {1}',
+ pages: 'Страницы',
+ words: 'Слова',
+ charactersWithoutSpaces: 'Знаки (без пробелов)',
+ charactersWithSpaces: 'Знаки (с пробелами)',
+ paragraphs: 'Абзацы',
+ lines: 'Строки',
+ nonAsianWords: 'Неазиатские слова',
+ asianCharactersAndKoreanWords: 'Азиатские знаки и корейские слова',
+ },
placeholder: {
heading1: 'Заголовок 1',
heading2: 'Заголовок 2',
diff --git a/packages/docs-ui/src/locale/sk-SK.ts b/packages/docs-ui/src/locale/sk-SK.ts
index 1a953484dd..2a864525c0 100644
--- a/packages/docs-ui/src/locale/sk-SK.ts
+++ b/packages/docs-ui/src/locale/sk-SK.ts
@@ -95,6 +95,22 @@ const locale: typeof enUS = {
closeHeaderFooter: 'Zavrieť hlavičku a pätu',
disableText: 'Nastavenia hlavičky a päty sú vypnuté',
},
+ statistics: {
+ title: 'Štatistika dokumentu',
+ open: 'Zobraziť štatistiku dokumentu',
+ document: 'Celý dokument',
+ selection: 'Aktuálny výber',
+ wordCount: 'Počet slov: {0}',
+ selectedWords: 'Počet slov: {0} z {1}',
+ pages: 'Strany',
+ words: 'Slová',
+ charactersWithoutSpaces: 'Znaky (bez medzier)',
+ charactersWithSpaces: 'Znaky (s medzerami)',
+ paragraphs: 'Odseky',
+ lines: 'Riadky',
+ nonAsianWords: 'Neázijské slová',
+ asianCharactersAndKoreanWords: 'Ázijské znaky a kórejské slová',
+ },
placeholder: {
heading1: 'Nadpis 1',
heading2: 'Nadpis 2',
diff --git a/packages/docs-ui/src/locale/vi-VN.ts b/packages/docs-ui/src/locale/vi-VN.ts
index 9b08f9d09c..adf6d90123 100644
--- a/packages/docs-ui/src/locale/vi-VN.ts
+++ b/packages/docs-ui/src/locale/vi-VN.ts
@@ -95,6 +95,22 @@ const locale: typeof enUS = {
closeHeaderFooter: 'Đóng đầu trang và chân trang',
disableText: 'Cài đặt đầu trang và chân trang không khả dụng',
},
+ statistics: {
+ title: 'Thống kê tài liệu',
+ open: 'Xem thống kê tài liệu',
+ document: 'Toàn bộ tài liệu',
+ selection: 'Vùng chọn hiện tại',
+ wordCount: '{0} từ',
+ selectedWords: '{0} trên {1} từ',
+ pages: 'Trang',
+ words: 'Từ',
+ charactersWithoutSpaces: 'Ký tự (không có dấu cách)',
+ charactersWithSpaces: 'Ký tự (có dấu cách)',
+ paragraphs: 'Đoạn văn',
+ lines: 'Dòng',
+ nonAsianWords: 'Từ không thuộc ngôn ngữ châu Á',
+ asianCharactersAndKoreanWords: 'Ký tự châu Á và từ tiếng Hàn',
+ },
placeholder: {
heading1: 'Tiêu đề 1',
heading2: 'Tiêu đề 2',
diff --git a/packages/docs-ui/src/locale/zh-CN.ts b/packages/docs-ui/src/locale/zh-CN.ts
index 1fb8ebe194..989c4c538c 100644
--- a/packages/docs-ui/src/locale/zh-CN.ts
+++ b/packages/docs-ui/src/locale/zh-CN.ts
@@ -95,6 +95,22 @@ const locale: typeof enUS = {
closeHeaderFooter: '关闭页眉页脚',
disableText: '页眉页脚设置不可用',
},
+ statistics: {
+ title: '文档统计',
+ open: '查看文档统计',
+ document: '整个文档',
+ selection: '当前选区',
+ wordCount: '字数 {0}',
+ selectedWords: '字数 {0} / {1}',
+ pages: '页数',
+ words: '字数',
+ charactersWithoutSpaces: '字符数(不计空格)',
+ charactersWithSpaces: '字符数(计空格)',
+ paragraphs: '段落数',
+ lines: '行数',
+ nonAsianWords: '非亚洲语言字数',
+ asianCharactersAndKoreanWords: '亚洲语言字符、韩文单词',
+ },
placeholder: {
heading1: '标题1',
heading2: '标题2',
diff --git a/packages/docs-ui/src/locale/zh-HK.ts b/packages/docs-ui/src/locale/zh-HK.ts
index 377da18fe1..c4a77559d1 100644
--- a/packages/docs-ui/src/locale/zh-HK.ts
+++ b/packages/docs-ui/src/locale/zh-HK.ts
@@ -95,6 +95,22 @@ const locale: typeof enUS = {
closeHeaderFooter: '關閉頁眉頁腳',
disableText: '頁眉頁腳設置不可用',
},
+ statistics: {
+ title: '文件統計',
+ open: '查看文件統計',
+ document: '整份文件',
+ selection: '目前選取範圍',
+ wordCount: '字數 {0}',
+ selectedWords: '字數 {0} / {1}',
+ pages: '頁數',
+ words: '字數',
+ charactersWithoutSpaces: '字元數(不計空格)',
+ charactersWithSpaces: '字元數(計空格)',
+ paragraphs: '段落數',
+ lines: '行數',
+ nonAsianWords: '非亞洲語言字數',
+ asianCharactersAndKoreanWords: '亞洲語言字元、韓文單字',
+ },
placeholder: {
heading1: '標題1',
heading2: '標題2',
diff --git a/packages/docs-ui/src/locale/zh-TW.ts b/packages/docs-ui/src/locale/zh-TW.ts
index 3216bd54bf..3fa9e96759 100644
--- a/packages/docs-ui/src/locale/zh-TW.ts
+++ b/packages/docs-ui/src/locale/zh-TW.ts
@@ -95,6 +95,22 @@ const locale: typeof enUS = {
closeHeaderFooter: '關閉頁眉頁腳',
disableText: '頁眉頁腳設置不可用',
},
+ statistics: {
+ title: '文件統計',
+ open: '檢視文件統計',
+ document: '整份文件',
+ selection: '目前選取範圍',
+ wordCount: '字數 {0}',
+ selectedWords: '字數 {0} / {1}',
+ pages: '頁數',
+ words: '字數',
+ charactersWithoutSpaces: '字元數(不計空格)',
+ charactersWithSpaces: '字元數(計空格)',
+ paragraphs: '段落數',
+ lines: '行數',
+ nonAsianWords: '非亞洲語言字數',
+ asianCharactersAndKoreanWords: '亞洲語言字元、韓文單字',
+ },
placeholder: {
heading1: '標題1',
heading2: '標題2',
diff --git a/packages/docs-ui/src/views/doc-footer/DocFooter.tsx b/packages/docs-ui/src/views/doc-footer/DocFooter.tsx
index 86c8b095c2..ddc8c6efaf 100644
--- a/packages/docs-ui/src/views/doc-footer/DocFooter.tsx
+++ b/packages/docs-ui/src/views/doc-footer/DocFooter.tsx
@@ -20,6 +20,7 @@ import { IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { useConfigValue, useDependency, useObservable } from '@univerjs/ui';
import { DOCS_UI_PLUGIN_CONFIG_KEY } from '../../config/config';
import { CountBar } from '../count-bar';
+import { DocStatistics } from '../doc-statistics/DocStatistics';
function DocFooterContent() {
const config = useConfigValue<IUniverDocsUIConfig>(DOCS_UI_PLUGIN_CONFIG_KEY);
@@ -31,7 +32,7 @@ function DocFooterContent() {
univer-box-border univer-flex univer-items-center univer-justify-between univer-px-5 univer-py-1.5
`}
>
- <div />
+ {config?.wordCount !== false && <DocStatistics />}
<CountBar />
</div>
);
diff --git a/packages/docs-ui/src/views/doc-statistics/DocStatistics.tsx b/packages/docs-ui/src/views/doc-statistics/DocStatistics.tsx
new file mode 100644
index 0000000000..b37a6b797e
--- /dev/null
+++ b/packages/docs-ui/src/views/doc-statistics/DocStatistics.tsx
@@ -0,0 +1,161 @@
+/**
+ * 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 { IDocumentStatistics } from '@univerjs/core';
+import type { LocaleKey } from '../../locale/types';
+import { LOCALE_META, LocaleService } from '@univerjs/core';
+import { LoadingMultiIcon, StatisticalFunctionIcon } from '@univerjs/icons';
+import { RectPopup, ToolbarButton, useDependency } from '@univerjs/ui';
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { BehaviorSubject } from 'rxjs';
+import { useDocStatistics } from './use-doc-statistics';
+
+type DisplayStatistics = IDocumentStatistics & { pages: number; lines: number };
+
+interface IStatisticRow {
+ key: keyof DisplayStatistics;
+ label: LocaleKey;
+}
+
+const STATISTIC_ROWS: IStatisticRow[] = [
+ { key: 'pages', label: 'docs-ui.statistics.pages' },
+ { key: 'words', label: 'docs-ui.statistics.words' },
+ { key: 'charactersWithoutSpaces', label: 'docs-ui.statistics.charactersWithoutSpaces' },
+ { key: 'charactersWithSpaces', label: 'docs-ui.statistics.charactersWithSpaces' },
+ { key: 'paragraphs', label: 'docs-ui.statistics.paragraphs' },
+ { key: 'lines', label: 'docs-ui.statistics.lines' },
+ { key: 'nonAsianWords', label: 'docs-ui.statistics.nonAsianWords' },
+ { key: 'asianCharactersAndKoreanWords', label: 'docs-ui.statistics.asianCharactersAndKoreanWords' },
+];
+
+function StatisticsPanel({ statistics, selection, showPages }: { statistics: DisplayStatistics; selection: boolean; showPages: boolean }) {
+ const localeService = useDependency(LocaleService);
+ const localeTag = LOCALE_META[localeService.getCurrentLocale()].tag;
+
+ return (
+ <div
+ role="dialog"
+ aria-label={localeService.t<LocaleKey>('docs-ui.statistics.title')}
+ className={`
+ univer-w-80 univer-rounded-lg univer-border univer-border-gray-200 univer-bg-white univer-p-4
+ univer-shadow-lg
+ dark:!univer-border-gray-600 dark:!univer-bg-gray-800
+ `}
+ >
+ <div className="univer-mb-3">
+ <div className="univer-text-sm univer-font-medium">
+ {localeService.t<LocaleKey>('docs-ui.statistics.title')}
+ </div>
+ <div
+ className={`
+ univer-mt-0.5 univer-text-xs univer-text-gray-500
+ dark:!univer-text-gray-400
+ `}
+ >
+ {localeService.t<LocaleKey>(selection ? 'docs-ui.statistics.selection' : 'docs-ui.statistics.document')}
+ </div>
+ </div>
+ <dl className="univer-grid univer-grid-cols-[1fr_auto] univer-gap-x-5 univer-gap-y-2 univer-text-sm">
+ {STATISTIC_ROWS.filter(({ key }) => showPages || key !== 'pages').map(({ key, label }) => (
+ <div className="univer-contents" key={String(key)}>
+ <dt>{localeService.t<LocaleKey>(label)}</dt>
+ <dd className="univer-m-0 univer-text-right univer-font-medium univer-tabular-nums">
+ {statistics[key].toLocaleString(localeTag)}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ </div>
+ );
+}
+
+export function DocStatistics() {
+ const localeService = useDependency(LocaleService);
+ const [open, setOpen] = useState(false);
+ const { document, selection, loading, showPages } = useDocStatistics(open);
+ const triggerRef = useRef<HTMLSpanElement>(null);
+ const anchorRect$ = useMemo(() => new BehaviorSubject({ left: 0, right: 0, top: 0, bottom: 0 }), []);
+ const localeTag = LOCALE_META[localeService.getCurrentLocale()].tag;
+ const displayedStatistics = selection ?? document;
+ const openLabel = localeService.t<LocaleKey>('docs-ui.statistics.open');
+ const label = selection
+ ? localeService.t<LocaleKey>('docs-ui.statistics.selectedWords', selection.words.toLocaleString(localeTag), document.words.toLocaleString(localeTag))
+ : localeService.t<LocaleKey>('docs-ui.statistics.wordCount', document.words.toLocaleString(localeTag));
+
+ useEffect(() => {
+ if (!open) return;
+
+ const updatePosition = () => {
+ const rect = triggerRef.current?.getBoundingClientRect();
+ if (!rect) return;
+
+ anchorRect$.next({ left: rect.left, right: rect.right, top: rect.top, bottom: rect.bottom });
+ };
+ const closeOnEscape = (event: KeyboardEvent) => {
+ if (event.key === 'Escape') {
+ setOpen(false);
+ }
+ };
+
+ updatePosition();
+ window.addEventListener('resize', updatePosition);
+ window.addEventListener('scroll', updatePosition, true);
+ window.addEventListener('keydown', closeOnEscape);
+
+ return () => {
+ window.removeEventListener('resize', updatePosition);
+ window.removeEventListener('scroll', updatePosition, true);
+ window.removeEventListener('keydown', closeOnEscape);
+ };
+ }, [anchorRect$, open]);
+
+ return (
+ <>
+ <span ref={triggerRef} title={open ? undefined : openLabel}>
+ <ToolbarButton
+ noIcon
+ active={open}
+ className={`
+ !univer-h-7 univer-px-2 univer-text-xs !univer-text-gray-600
+ focus-visible:univer-ring-2 focus-visible:univer-ring-primary-500
+ dark:!univer-text-gray-300
+ `}
+ aria-expanded={open}
+ aria-haspopup="dialog"
+ aria-label={openLabel}
+ onClick={() => setOpen((visible) => !visible)}
+ >
+ <span className="univer-flex univer-items-center univer-gap-1.5">
+ <StatisticalFunctionIcon className="univer-size-4" />
+ <span>{label}</span>
+ {loading && <LoadingMultiIcon className="univer-size-3.5 univer-animate-spin" />}
+ </span>
+ </ToolbarButton>
+ </span>
+ {open && (
+ <RectPopup
+ portal
+ anchorRect$={anchorRect$}
+ direction="top-left"
+ onClickOutside={() => setOpen(false)}
+ onContextMenu={() => setOpen(false)}
+ >
+ <StatisticsPanel statistics={displayedStatistics} selection={selection != null} showPages={showPages} />
+ </RectPopup>
+ )}
+ </>
+ );
+}
diff --git a/packages/docs-ui/src/views/doc-statistics/__tests__/DocStatistics.spec.tsx b/packages/docs-ui/src/views/doc-statistics/__tests__/DocStatistics.spec.tsx
new file mode 100644
index 0000000000..d68b0e8656
--- /dev/null
+++ b/packages/docs-ui/src/views/doc-statistics/__tests__/DocStatistics.spec.tsx
@@ -0,0 +1,151 @@
+/**
+ * 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.
+ */
+
+/**
+ * @vitest-environment jsdom
+ */
+
+import type { Root } from 'react-dom/client';
+import { ConfigService, IConfigService, Injector, LocaleService, LocaleType } from '@univerjs/core';
+import { RediContext } from '@univerjs/ui';
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import enUS from '../../../locale/en-US';
+import { DocStatistics } from '../DocStatistics';
+import { useDocStatistics } from '../use-doc-statistics';
+
+vi.mock('../use-doc-statistics');
+
+Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, value: true });
+globalThis.ResizeObserver = class ResizeObserver {
+ observe(): void {}
+ unobserve(): void {}
+ disconnect(): void {}
+};
+globalThis.requestAnimationFrame = (callback: FrameRequestCallback) => {
+ callback(0);
+ return 0;
+};
+
+function renderStatistics() {
+ const injector = new Injector();
+ injector.add([LocaleService]);
+ injector.add([IConfigService, { useClass: ConfigService }]);
+ const localeService = injector.get(LocaleService);
+ localeService.load({ [LocaleType.EN_US]: enUS });
+ localeService.setLocale(LocaleType.EN_US);
+
+ const container = document.createElement('div');
+ const popupRoot = document.createElement('div');
+ popupRoot.id = 'univer-popup-portal';
+ document.body.appendChild(popupRoot);
+ document.body.appendChild(container);
+ const root = createRoot(container);
+
+ act(() => {
+ root.render(
+ <RediContext.Provider value={{ injector }}>
+ <DocStatistics />
+ </RediContext.Provider>
+ );
+ });
+
+ return { container, root };
+}
+
+describe('DocStatistics', () => {
+ let root: Root | undefined;
+ let container: HTMLElement | undefined;
+
+ afterEach(() => {
+ const currentRoot = root;
+ if (currentRoot) {
+ act(() => currentRoot.unmount());
+ }
+
+ container?.remove();
+ document.body.replaceChildren();
+ vi.resetAllMocks();
+ root = undefined;
+ container = undefined;
+ });
+
+ it('opens the statistics panel from the footer word count', () => {
+ vi.mocked(useDocStatistics).mockReturnValue({
+ document: {
+ pages: 1,
+ words: 12,
+ charactersWithoutSpaces: 31,
+ charactersWithSpaces: 36,
+ paragraphs: 3,
+ lines: 3,
+ nonAsianWords: 6,
+ asianCharactersAndKoreanWords: 6,
+ },
+ selection: null,
+ loading: false,
+ showPages: true,
+ });
+
+ const rendered = renderStatistics();
+ root = rendered.root;
+ container = rendered.container;
+
+ const button = container.querySelector('button');
+ expect(button?.textContent).toContain('12 words');
+ expect(useDocStatistics).toHaveBeenLastCalledWith(false);
+
+ act(() => {
+ button?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ });
+
+ expect(useDocStatistics).toHaveBeenLastCalledWith(true);
+ expect(document.body.textContent).toContain('Document statistics');
+ expect(document.body.textContent).toContain('Pages');
+ expect(document.body.textContent).toContain('Characters (no spaces)');
+ expect(document.body.textContent).toContain('Asian characters and Korean words');
+ });
+
+ it('hides pages in modern documents', () => {
+ vi.mocked(useDocStatistics).mockReturnValue({
+ document: {
+ pages: 0,
+ words: 12,
+ charactersWithoutSpaces: 31,
+ charactersWithSpaces: 36,
+ paragraphs: 3,
+ lines: 3,
+ nonAsianWords: 6,
+ asianCharactersAndKoreanWords: 6,
+ },
+ selection: null,
+ loading: false,
+ showPages: false,
+ });
+
+ const rendered = renderStatistics();
+ root = rendered.root;
+ container = rendered.container;
+
+ act(() => {
+ rendered.container.querySelector('button')?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ });
+
+ expect(document.body.textContent).not.toContain('Pages');
+ expect(document.body.textContent).toContain('Lines');
+ });
+});
diff --git a/packages/docs-ui/src/views/doc-statistics/use-doc-statistics.ts b/packages/docs-ui/src/views/doc-statistics/use-doc-statistics.ts
new file mode 100644
index 0000000000..3791d5f6a7
--- /dev/null
+++ b/packages/docs-ui/src/views/doc-statistics/use-doc-statistics.ts
@@ -0,0 +1,268 @@
+/**
+ * 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 { DocumentDataModel, IDocumentStatistics, IDocumentStatisticsOptions, ITextRangeParam, Nullable } from '@univerjs/core';
+import type { DocumentSkeleton } from '@univerjs/engine-render';
+import { DocumentFlavor, IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';
+import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
+import { documentSkeletonLineIterator, IRenderManagerService } from '@univerjs/engine-render';
+import { useDependency, useObservable } from '@univerjs/ui';
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { combineLatest, map, startWith } from 'rxjs';
+
+const STATISTICS_DEBOUNCE_TIME = 200;
+const EMPTY_STATISTICS: IDocumentStatistics = {
+ words: 0,
+ charactersWithoutSpaces: 0,
+ charactersWithSpaces: 0,
+ paragraphs: 0,
+ nonAsianWords: 0,
+ asianCharactersAndKoreanWords: 0,
+};
+
+interface IDocLayoutStatistics {
+ pages: number;
+ lines: number;
+}
+
+const EMPTY_LAYOUT_STATISTICS: IDocLayoutStatistics = { pages: 0, lines: 0 };
+
+export interface IDocStatisticsViewState {
+ document: IDocumentStatistics & IDocLayoutStatistics;
+ selection: (IDocumentStatistics & IDocLayoutStatistics) | null;
+ loading: boolean;
+ showPages: boolean;
+}
+
+interface ICalculateStatisticsParams {
+ calculateLayout: boolean;
+ calculatePages: boolean;
+ documentDataModel: DocumentDataModel;
+ cachedStatistics?: IDocumentStatistics;
+ locale: IDocumentStatisticsOptions['locale'];
+ selectionRanges: ITextRangeParam[];
+ signal: AbortSignal;
+ skeleton: DocumentSkeleton | null;
+}
+
+interface IDocumentStatisticsCache {
+ documentDataModel: DocumentDataModel;
+ locale: IDocumentStatisticsOptions['locale'];
+ revision: number;
+ statistics: IDocumentStatistics;
+}
+
+function getBodySelectionRanges(selectionManager: DocSelectionManagerService): ITextRangeParam[] {
+ return (selectionManager.getTextRanges() ?? [])
+ .filter((range) => !range.collapsed && !range.segmentId)
+ .map(({ collapsed, direction, endOffset, isActive, rangeType, segmentId, segmentPage, startOffset }) => ({
+ collapsed,
+ direction,
+ endOffset,
+ isActive,
+ rangeType,
+ segmentId,
+ segmentPage,
+ startOffset,
+ }));
+}
+
+function rangeIntersectsLine(range: ITextRangeParam, startOffset: number, endOffset: number): boolean {
+ const rangeStart = Math.min(range.startOffset, range.endOffset);
+ const rangeEnd = Math.max(range.startOffset, range.endOffset);
+ return rangeStart < endOffset && rangeEnd > startOffset;
+}
+
+export function getDocLayoutStatistics(
+ skeleton: DocumentSkeleton | null,
+ ranges: Readonly<ITextRangeParam>[] = [],
+ calculatePages = true
+): IDocLayoutStatistics {
+ const pages = skeleton?.getSkeletonData()?.pages ?? [];
+ if (ranges.length === 0) {
+ let lines = 0;
+ documentSkeletonLineIterator(pages, {}, () => lines++);
+ return { lines, pages: calculatePages ? pages.length : 0 };
+ }
+
+ let lines = 0;
+ const selectedPages = calculatePages ? new Set<number>() : null;
+ documentSkeletonLineIterator(pages, {}, ({ line, pageIndex }) => {
+ if (ranges.some((range) => rangeIntersectsLine(range, line.st, line.ed))) {
+ lines += 1;
+ selectedPages?.add(pageIndex);
+ }
+ });
+
+ return { lines, pages: selectedPages?.size ?? 0 };
+}
+
+async function calculateStatistics({
+ calculateLayout,
+ calculatePages,
+ documentDataModel,
+ cachedStatistics,
+ locale,
+ selectionRanges,
+ signal,
+ skeleton,
+}: ICalculateStatisticsParams): Promise<Omit<IDocStatisticsViewState, 'loading' | 'showPages'>> {
+ const documentLayout = calculateLayout ? getDocLayoutStatistics(skeleton, [], calculatePages) : EMPTY_LAYOUT_STATISTICS;
+ const selectionLayout = calculateLayout && selectionRanges.length > 0
+ ? getDocLayoutStatistics(skeleton, selectionRanges, calculatePages)
+ : EMPTY_LAYOUT_STATISTICS;
+ const [documentStatistics, selectionStatistics] = await Promise.all([
+ cachedStatistics ?? documentDataModel.getStatistics({ locale, signal }),
+ selectionRanges.length > 0
+ ? documentDataModel.getStatistics({ locale, ranges: selectionRanges, signal })
+ : null,
+ ]);
+
+ return {
+ document: { ...documentStatistics, ...documentLayout },
+ selection: selectionStatistics ? { ...selectionStatistics, ...selectionLayout } : null,
+ };
+}
+
+function cacheDocumentStatistics(
+ cacheRef: { current: IDocumentStatisticsCache | null },
+ documentDataModel: DocumentDataModel,
+ locale: IDocumentStatisticsOptions['locale'],
+ revision: number,
+ statistics: IDocStatisticsViewState['document']
+): void {
+ cacheRef.current = {
+ documentDataModel,
+ locale,
+ revision,
+ statistics: {
+ words: statistics.words,
+ charactersWithoutSpaces: statistics.charactersWithoutSpaces,
+ charactersWithSpaces: statistics.charactersWithSpaces,
+ paragraphs: statistics.paragraphs,
+ nonAsianWords: statistics.nonAsianWords,
+ asianCharactersAndKoreanWords: statistics.asianCharactersAndKoreanWords,
+ },
+ };
+}
+
+function useStatisticsSelection(
+ documentDataModel: Nullable<DocumentDataModel>,
+ selectionManager: DocSelectionManagerService
+): { ranges: ITextRangeParam[]; revision: number } {
+ return useObservable(
+ documentDataModel
+ ? () => combineLatest([
+ selectionManager.textSelection$.pipe(startWith(undefined)),
+ documentDataModel.change$,
+ ]).pipe(map(([, revision]) => ({
+ ranges: getBodySelectionRanges(selectionManager),
+ revision,
+ })))
+ : null,
+ { ranges: [], revision: 0 },
+ false,
+ [documentDataModel, selectionManager]
+ );
+}
+
+function useDocumentSkeleton(
+ documentDataModel: Nullable<DocumentDataModel>,
+ renderManagerService: IRenderManagerService
+): Nullable<DocumentSkeleton> {
+ const skeletonManager = documentDataModel
+ ? renderManagerService.getRenderUnitById(documentDataModel.getUnitId())?.with(DocSkeletonManagerService)
+ : null;
+ return useObservable(
+ skeletonManager ? skeletonManager.currentSkeleton$.pipe(map((value) => ({ value }))) : null,
+ { value: skeletonManager?.getSkeleton() ?? null },
+ false,
+ [skeletonManager]
+ ).value;
+}
+
+export function useDocStatistics(calculateLayout = false): IDocStatisticsViewState {
+ const instanceService = useDependency(IUniverInstanceService);
+ const localeService = useDependency(LocaleService);
+ const renderManagerService = useDependency(IRenderManagerService);
+ const selectionManager = useDependency(DocSelectionManagerService);
+ const documentStatisticsCacheRef = useRef<IDocumentStatisticsCache | null>(null);
+ const documentDataModel = useObservable(useMemo(
+ () => instanceService.getCurrentTypeOfUnit$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC),
+ [instanceService]
+ ));
+ const selectionSnapshot = useStatisticsSelection(documentDataModel, selectionManager);
+ const locale = useObservable(localeService.currentLocale$, localeService.getCurrentLocale());
+ const showPages = documentDataModel?.getDocumentStyle().documentFlavor !== DocumentFlavor.MODERN;
+ const skeleton = useDocumentSkeleton(calculateLayout ? documentDataModel : null, renderManagerService);
+ const [state, setState] = useState<Omit<IDocStatisticsViewState, 'showPages'>>({
+ document: { ...EMPTY_STATISTICS, lines: 0, pages: 0 },
+ selection: null,
+ loading: true,
+ });
+ const selectionRanges = selectionSnapshot.ranges;
+
+ useEffect(() => {
+ if (!documentDataModel?.getBody()) {
+ return;
+ }
+
+ const currentDocumentDataModel = documentDataModel;
+ const cachedDocumentStatistics = documentStatisticsCacheRef.current;
+ const hasCachedDocumentStatistics = cachedDocumentStatistics?.documentDataModel === currentDocumentDataModel
+ && cachedDocumentStatistics.locale === locale
+ && cachedDocumentStatistics.revision === selectionSnapshot.revision;
+
+ const abortController = new AbortController();
+ const timeout = setTimeout(async () => {
+ setState((current) => ({ ...current, loading: true }));
+
+ try {
+ const result = await calculateStatistics({
+ calculateLayout,
+ calculatePages: showPages,
+ documentDataModel: currentDocumentDataModel,
+ cachedStatistics: hasCachedDocumentStatistics ? cachedDocumentStatistics.statistics : undefined,
+ locale,
+ selectionRanges,
+ signal: abortController.signal,
+ skeleton: skeleton ?? null,
+ });
+ if (!hasCachedDocumentStatistics) {
+ cacheDocumentStatistics(
+ documentStatisticsCacheRef,
+ currentDocumentDataModel,
+ locale,
+ selectionSnapshot.revision,
+ result.document
+ );
+ }
+ setState({ ...result, loading: false });
+ } catch {
+ if (!abortController.signal.aborted) {
+ setState((current) => ({ ...current, loading: false }));
+ }
+ }
+ }, STATISTICS_DEBOUNCE_TIME);
+
+ return () => {
+ clearTimeout(timeout);
+ abortController.abort();
+ };
+ }, [calculateLayout, documentDataModel, locale, selectionRanges, selectionSnapshot, showPages, skeleton]);
+
+ return { ...state, showPages };
+}