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(doc): support Chinese and English mixed typography (#643)
Ran Luo97de35c92f62
diff --git a/.vscode/settings.json b/.vscode/settings.jsonindex 6d256c628f..85366303c3 100644--- a/.vscode/settings.json+++ b/.vscode/settings.json@@ -37,6 +37,7 @@"Hiragino","ilvl","IRPC",+ "jikkai","Kaiti","KANBAN","kcode",@@ -44,8 +45,10 @@"Lerp","Liti","localforage",+ "LRTBV","Luckysheet","mengshukeji",+ "Neue","numfmt","Overlines","Pacifico",@@ -58,6 +61,7 @@"SUMIF","SUMIFS","Tahoma",+ "TBRL","tinycolor","undoredo","undos",diff --git a/examples/data/src/docs/default-document-data-cn.ts b/examples/data/src/docs/default-document-data-cn.tsindex b43f29e94b..27369bea0f 100644--- a/examples/data/src/docs/default-document-data-cn.ts+++ b/examples/data/src/docs/default-document-data-cn.ts@@ -8,7 +8,7 @@ export const DEFAULT_DOCUMENT_DATA_CN: IDocumentData = {lists: DEFAULT_LIST_TEST,body: {dataStream:- '零. 开篇\r上标和下标:HO2 5X 删除线:我是被删除的内容 下划线:我是下划线\r这篇文章旨在帮助新人快速熟悉开源项目univer的架构及代码,也是我过去一段时间参与到 univer 开发中的学习和总结,肯定有不够准确或者理解偏差,欢迎大家评论指正\r第壹章,会聊聊我对univer架构的理解,univer是如何拆分模块,以及模块之间的依赖关系。然后将univer放入MMV的架构模式中,分别分析下其模型层、视图层、控制器的边界和职责\r第贰章,我们先来看看 univer sheet 的模型层数据结构设计,如何区分 workbook、sheet、row、column、style 等,了解他们的包含关系,这对后面深入理解代码是有帮助的\r第叁、肆章,我将从两条控制链路来分析 univer 的代码,一条链路是 univer 启动和初始化渲染的过程。在这条链路中,是从模型层到视图层的过程。另外一条链路是 univer 响应用户事件,并且触发模型层数据变更,页面重新渲染,在这条链路中,是从视图层到模型层的过程。在这两部分,我们会涉及到大量的源码分析,在保留代码主逻辑的前提,删除了边界 case 的代码。同时在每个代码块第一行,表示该代码块所在的 TS 文件,这样便于直接阅读源码\r\n',+ '零. 开篇\r上标和下标:HO2 5X 删除线:我是被删除的内容 下划线:我是下划线\r这篇文章旨在帮助新人快速熟悉开조선어univer的架构及代码,也是我过去一段时间参与到 univer 开发中的学习和总结,肯定有不够准确或者理解偏差,欢迎大家评论指正\r第壹章,会聊聊我对univer架构的理解,univer是如何拆分模块,以及模块之间的依赖关系。然后将univer放入MMV的架构模式中,分别分析下其模型层、视图层、控制器的边界和职责\r第贰章,我们先来看看 univer sheet 的模型层数据结构设计,如何区分 workbook、sheet、row、column、style 等,了解他们的包含关系,这对后面深入理解代码是有帮助的\r第叁、肆章,我将从两条控制链路来分析 univer 的代码,一条链路是 univer 启动和初始化渲染的过程。在这条链路中,是从模型层到视图层的过程。另外一条链路是 univer 响应用户事件,并且触发模型层数据变更,页面重新渲染,在这条链路中,是从视图层到模型层的过程。在这两部分,我们会涉及到大量的源码分析,在保留代码主逻辑的前提,删除了边界 case 的代码。同时在每个代码块第一行,表示该代码块所在的 TS 文件,这样便于直接阅读源码\r\n',textRuns: [{st: 0,diff --git a/packages/engine-render/src/basics/i-events.ts b/packages/engine-render/src/basics/i-events.tsindex 4d9320ab6f..11f58c559f 100644--- a/packages/engine-render/src/basics/i-events.ts+++ b/packages/engine-render/src/basics/i-events.ts@@ -1,3 +1,4 @@+/* eslint-disable no-magic-numbers */import type { Nullable } from '@univerjs/core';/**@@ -50,7 +51,7 @@ export type Immutable<T> = T extends Primitiveexport type DeepImmutable<T> = T extends Primitive? T: T extends Array<infer U>- ? DeepImmutableArray<U>+ ? IDeepImmutableArray<U>: /* T extends Map<infer K, infer V> ? DeepImmutableMap<K, V> : // es2015+ only */DeepImmutableObject<T>;@@ -62,14 +63,10 @@ export type DeepImmutableObject<T> = {};/** @hidden */-interface DeepImmutableArray<T> extends ReadonlyArray<DeepImmutable<T>> {}+interface IDeepImmutableArray<T> extends ReadonlyArray<DeepImmutable<T>> {}/** @hidden *//* interface DeepImmutableMap<K, V> extends ReadonlyMap<DeepImmutable<K>, DeepImmutable<V>> {} // es2015+ only */-export interface Class<T> {- new (...param: any): T;-}-/*** Event Types*/diff --git a/packages/engine-render/src/basics/tools.ts b/packages/engine-render/src/basics/tools.tsindex f902c7fcf5..a8be3ed1f7 100644--- a/packages/engine-render/src/basics/tools.ts+++ b/packages/engine-render/src/basics/tools.ts@@ -237,22 +237,14 @@ export function fixLineWidthByScale(num: number, scale: number) {export function getFontStyleString(textStyle?: IStyleBase, localeService?: LocaleService) {// 获取字体配置- // if (!fontLocale) {- // fontLocale = {- // fontList: ['Arial'],- // defaultFontSize: 14,- // };- // }-// TODO: @jikkai @DR-Univer should read default font from configuration, not from locale serviceconst defaultFont = 'Arial';const defaultFontSize = 13;- // const { fontList, defaultFontSize } = fontLocale;-if (!textStyle) {const fontString = `${defaultFontSize}px ${defaultFont}`;+return {fontCache: fontString,fontString,@@ -331,8 +323,15 @@ export function isSupportBoundingBox(ctx: CanvasRenderingContext2D) {return true;}-// 是否有中文+// has Chinese string in text?export function hasChineseText(text: string) {+ const pattern = /[\u4E00-\u9FA5]/gi;++ return pattern.test(text);+}++// 是否有中文包括中文符号+export function hasChineseTextWithPunctuation(text: string) {const pattern = /[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/gi;// /^([^\p{Han}]*?)(?:\s+([\p{Han}].*))?$/gim;@@ -344,36 +343,39 @@ export function hasChineseText(text: string) {// 是否有日文export function hasJapaneseText(text: string) {- const pattern = /[一-龠]+|[ぁ-ゔ]+|[ァ-ヴー]+|[a-zA-Z0-9]+|[a-zA-Z0-9]+|[々〆〤]+/giu;+ // const pattern = /[一-龠]+|[ぁ-ゔ]+|[ァ-ヴー]+|[a-zA-Z0-9]+|[a-zA-Z0-9]+|[々〆〤]+/giu;+ const pattern = /[\u0800-\u4e00]/gi;- if (!pattern.exec(text)) {- return false;- }- return true;+ return pattern.test(text);}// 是否有韩文export function hasKoreanText(text: string) {- const pattern = /[^a-zA-Z0-9\p{Hangul}]/gi;+ // const pattern = /[^a-zA-Z0-9\p{Hangul}]/gi;+ const pattern = /[\uac00-\ud7ff]/gi;- if (!pattern.exec(text)) {- return false;- }- return true;+ return pattern.test(text);+}++// 是否有中文、日文、韩文等,不包括符号+export function hasCJKText(text: string) {+ return hasChineseText(text) || hasJapaneseText(text) || hasKoreanText(text);}// 是否有中文、日文、韩文等可以垂直布局的文字,东亚文字export function hasCJK(text: string) {const pattern = /[\u2E80-\uA4CF]|[\uF900-\uFAFF]|[\uFE30-\uFE4F]|[\uFF00-\uFFEF]/gi;+if (!pattern.exec(text)) {return false;}+return true;}-// 是否有中文、日文等不会存在单词文字,即:单字可以换行,不像hellow world 一样,world的单字必须连在一起。目前只发现中文、日文有这个特性,以后还可以再补充+// 是否有中文、日文等不会存在单词文字,即:单字可以换行,不像hello world 一样,world的单字必须连在一起。目前只发现中文、日文有这个特性,以后还可以再补充export function hasWrappableText(text: string) {- return hasChineseText(text) || hasJapaneseText(text);+ return hasChineseTextWithPunctuation(text) || hasJapaneseText(text);}export function hasAllLatin(text: string) {diff --git a/packages/engine-render/src/basics/vector2.ts b/packages/engine-render/src/basics/vector2.tsindex 3cebf3da1d..4892c64a3d 100644--- a/packages/engine-render/src/basics/vector2.ts+++ b/packages/engine-render/src/basics/vector2.ts@@ -1,831 +1,834 @@-import type { DeepImmutable, FloatArray } from './i-events';--export interface IPoint {- x: number;- y: number;-}--export class Vector2 implements IPoint {- /**- * Creates a new Vector2 from the given x and y coordinates- * @param x defines the first coordinate- * @param y defines the second coordinate- */- constructor(- /** defines the first coordinate */- public x: number = 0,- /** defines the second coordinate */- public y: number = 0- ) {}-- // Statics-- /**- * Gets a new Vector2(0, 0)- * @returns a new Vector2- */- static Zero(): Vector2 {- return new Vector2(0, 0);- }-- /**- * Gets a new Vector2(1, 1)- * @returns a new Vector2- */- static One(): Vector2 {- return new Vector2(1, 1);- }-- /**- * Gets a new Vector2 set from the given index element of the given array- * @param array defines the data source- * @param offset defines the offset in the data source- * @returns a new Vector2- */- static FromArray(array: DeepImmutable<ArrayLike<number>>, offset: number = 0): Vector2 {- return new Vector2(array[offset], array[offset + 1]);- }-- /**- * Sets "result" from the given index element of the given array- * @param array defines the data source- * @param offset defines the offset in the data source- * @param result defines the target vector- */- static FromArrayToRef(array: ArrayLike<number>, offset: number, result: Vector2): void {- result.x = array[offset];- result.y = array[offset + 1];- }-- /**- * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2- * @param value1 defines 1st point of control- * @param value2 defines 2nd point of control- * @param value3 defines 3rd point of control- * @param value4 defines 4th point of control- * @param amount defines the interpolation factor- * @returns a new Vector2- */- static CatmullRom(- value1: DeepImmutable<Vector2>,- value2: DeepImmutable<Vector2>,- value3: DeepImmutable<Vector2>,- value4: DeepImmutable<Vector2>,- amount: number- ): Vector2 {- const squared = amount * amount;- const cubed = amount * squared;-- const x =- 0.5 *- (2.0 * value2.x +- (-value1.x + value3.x) * amount +- (2.0 * value1.x - 5.0 * value2.x + 4.0 * value3.x - value4.x) * squared +- (-value1.x + 3.0 * value2.x - 3.0 * value3.x + value4.x) * cubed);-- const y =- 0.5 *- (2.0 * value2.y +- (-value1.y + value3.y) * amount +- (2.0 * value1.y - 5.0 * value2.y + 4.0 * value3.y - value4.y) * squared +- (-value1.y + 3.0 * value2.y - 3.0 * value3.y + value4.y) * cubed);-- return new Vector2(x, y);- }-- /**- * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".- * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.- * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate- * @param value defines the value to clamp- * @param min defines the lower limit- * @param max defines the upper limit- * @returns a new Vector2- */- static Clamp(value: DeepImmutable<Vector2>, min: DeepImmutable<Vector2>, max: DeepImmutable<Vector2>): Vector2 {- let x = value.x;- x = x > max.x ? max.x : x;- x = x < min.x ? min.x : x;-- let y = value.y;- y = y > max.y ? max.y : y;- y = y < min.y ? min.y : y;-- return new Vector2(x, y);- }-- /**- * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2"- * @param value1 defines the 1st control point- * @param tangent1 defines the outgoing tangent- * @param value2 defines the 2nd control point- * @param tangent2 defines the incoming tangent- * @param amount defines the interpolation factor- * @returns a new Vector2- */- static Hermite(- value1: DeepImmutable<Vector2>,- tangent1: DeepImmutable<Vector2>,- value2: DeepImmutable<Vector2>,- tangent2: DeepImmutable<Vector2>,- amount: number- ): Vector2 {- const squared = amount * amount;- const cubed = amount * squared;- const part1 = 2.0 * cubed - 3.0 * squared + 1.0;- const part2 = -2.0 * cubed + 3.0 * squared;- const part3 = cubed - 2.0 * squared + amount;- const part4 = cubed - squared;-- const x = value1.x * part1 + value2.x * part2 + tangent1.x * part3 + tangent2.x * part4;- const y = value1.y * part1 + value2.y * part2 + tangent1.y * part3 + tangent2.y * part4;-- return new Vector2(x, y);- }-- /**- * Returns a new Vector2 which is the 1st derivative of the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2".- * @param value1 defines the first control point- * @param tangent1 defines the first tangent- * @param value2 defines the second control point- * @param tangent2 defines the second tangent- * @param time define where the derivative must be done- * @returns 1st derivative- */- static Hermite1stDerivative(- value1: DeepImmutable<Vector2>,- tangent1: DeepImmutable<Vector2>,- value2: DeepImmutable<Vector2>,- tangent2: DeepImmutable<Vector2>,- time: number- ): Vector2 {- const result = Vector2.Zero();-- this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result);-- return result;- }-- /**- * Returns a new Vector2 which is the 1st derivative of the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2".- * @param value1 defines the first control point- * @param tangent1 defines the first tangent- * @param value2 defines the second control point- * @param tangent2 defines the second tangent- * @param time define where the derivative must be done- * @param result define where the derivative will be stored- */- static Hermite1stDerivativeToRef(- value1: DeepImmutable<Vector2>,- tangent1: DeepImmutable<Vector2>,- value2: DeepImmutable<Vector2>,- tangent2: DeepImmutable<Vector2>,- time: number,- result: Vector2- ) {- const t2 = time * time;-- result.x =- (t2 - time) * 6 * value1.x +- (3 * t2 - 4 * time + 1) * tangent1.x +- (-t2 + time) * 6 * value2.x +- (3 * t2 - 2 * time) * tangent2.x;- result.y =- (t2 - time) * 6 * value1.y +- (3 * t2 - 4 * time + 1) * tangent1.y +- (-t2 + time) * 6 * value2.y +- (3 * t2 - 2 * time) * tangent2.y;- }-- /**- * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".- * @param start defines the start vector- * @param end defines the end vector- * @param amount defines the interpolation factor- * @returns a new Vector2- */- static Lerp(start: DeepImmutable<Vector2>, end: DeepImmutable<Vector2>, amount: number): Vector2 {- const x = start.x + (end.x - start.x) * amount;- const y = start.y + (end.y - start.y) * amount;- return new Vector2(x, y);- }-- /**- * Gets the dot product of the vector "left" and the vector "right"- * @param left defines first vector- * @param right defines second vector- * @returns the dot product (float)- */- static Dot(left: DeepImmutable<Vector2>, right: DeepImmutable<Vector2>): number {- return left.x * right.x + left.y * right.y;- }-- /**- * Returns a new Vector2 equal to the normalized given vector- * @param vector defines the vector to normalize- * @returns a new Vector2- */- static Normalize(vector: DeepImmutable<Vector2>): Vector2 {- const newVector = Vector2.Zero();- this.NormalizeToRef(vector, newVector);- return newVector;- }-- /**- * Normalize a given vector into a second one- * @param vector defines the vector to normalize- * @param result defines the vector where to store the result- */- static NormalizeToRef(vector: DeepImmutable<Vector2>, result: Vector2) {- const len = vector.length();-- if (len === 0) {- return;- }-- result.x = vector.x / len;- result.y = vector.y / len;- }-- /**- * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors- * @param left defines 1st vector- * @param right defines 2nd vector- * @returns a new Vector2- */- static Minimize(left: DeepImmutable<Vector2>, right: DeepImmutable<Vector2>): Vector2 {- const x = left.x < right.x ? left.x : right.x;- const y = left.y < right.y ? left.y : right.y;- return new Vector2(x, y);- }-- /**- * Gets a new Vector2 set with the maximal coordinate values from the "left" and "right" vectors- * @param left defines 1st vector- * @param right defines 2nd vector- * @returns a new Vector2- */- static Maximize(left: DeepImmutable<Vector2>, right: DeepImmutable<Vector2>): Vector2 {- const x = left.x > right.x ? left.x : right.x;- const y = left.y > right.y ? left.y : right.y;- return new Vector2(x, y);- }-- // /**- // * Transforms the given vector coordinates by the given transformation Transform and stores the result in the vector "result" coordinates- // * @param vector defines the vector to transform- // * @param transformation defines the Transform to apply- // * @param result defines the target vector- // */- // static Transform(vector: DeepImmutable<Vector2>, transformation: DeepImmutable<Transform>, ignoreOffset: boolean = false) {- // const t = transformation as IKeyValue;- // const p = vector;-- // if (ignoreOffset) {- // return new Vector2(t[0] * p.x + t[2] * p.y, t[1] * p.x + t[3] * p.y);- // }- // return new Vector2(t[0] * p.x + t[2] * p.y + t[4], t[1] * p.x + t[3] * p.y + t[5]);- // }-- /**- * Determines if a given vector is included in a triangle- * @param p defines the vector to test- * @param p0 defines 1st triangle point- * @param p1 defines 2nd triangle point- * @param p2 defines 3rd triangle point- * @returns true if the point "p" is in the triangle defined by the vectors "p0", "p1", "p2"- */- static PointInTriangle(- p: DeepImmutable<Vector2>,- p0: DeepImmutable<Vector2>,- p1: DeepImmutable<Vector2>,- p2: DeepImmutable<Vector2>- ) {- const a = (1 / 2) * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);- const sign = a < 0 ? -1 : 1;- const s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;- const t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;-- return s > 0 && t > 0 && s + t < 2 * a * sign;- }-- /**- * Gets the distance between the vectors "value1" and "value2"- * @param value1 defines first vector- * @param value2 defines second vector- * @returns the distance between vectors- */- static Distance(value1: DeepImmutable<Vector2>, value2: DeepImmutable<Vector2>): number {- return Math.sqrt(Vector2.DistanceSquared(value1, value2));- }-- /**- * Returns the squared distance between the vectors "value1" and "value2"- * @param value1 defines first vector- * @param value2 defines second vector- * @returns the squared distance between vectors- */- static DistanceSquared(value1: DeepImmutable<Vector2>, value2: DeepImmutable<Vector2>): number {- const x = value1.x - value2.x;- const y = value1.y - value2.y;- return x * x + y * y;- }-- /**- * Gets a new Vector2 located at the center of the vectors "value1" and "value2"- * @param value1 defines first vector- * @param value2 defines second vector- * @returns a new Vector2- */- static Center(value1: DeepImmutable<Vector2>, value2: DeepImmutable<Vector2>): Vector2 {- return Vector2.CenterToRef(value1, value2, Vector2.Zero());- }-- /**- * Gets the center of the vectors "value1" and "value2" and stores the result in the vector "ref"- * @param value1 defines first vector- * @param value2 defines second vector- * @param ref defines third vector- * @returns ref- */- static CenterToRef(- value1: DeepImmutable<Vector2>,- value2: DeepImmutable<Vector2>,- ref: DeepImmutable<Vector2>- ): Vector2 {- return ref.copyFromFloats((value1.x + value2.x) / 2, (value1.y + value2.y) / 2);- }-- /**- * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".- * @param p defines the middle point- * @param segA defines one point of the segment- * @param segB defines the other point of the segment- * @returns the shortest distance- */- static DistanceOfPointFromSegment(- p: DeepImmutable<Vector2>,- segA: DeepImmutable<Vector2>,- segB: DeepImmutable<Vector2>- ): number {- const l2 = Vector2.DistanceSquared(segA, segB);- if (l2 === 0.0) {- return Vector2.Distance(p, segA);- }- const v = segB.subtract(segA);- const t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));- const proj = segA.add(v.multiplyByFloats(t, t));- return Vector2.Distance(p, proj);- }-- static create(x: number, y: number) {- return new Vector2(x, y);- }-- /**- * Gets a string with the Vector2 coordinates- * @returns a string with the Vector2 coordinates- */- toString(): string {- return `{X: ${this.x} Y: ${this.y}}`;- }-- /**- * Gets class name- * @returns the string "Vector2"- */- getClassName(): string {- return 'Vector2';- }-- /**- * Gets current vector hash code- * @returns the Vector2 hash code as a number- */- getHashCode(): number {- let hash = this.x | 0;- hash = (hash * 397) ^ (this.y | 0);- return hash;- }-- // Operators-- /**- * Sets the Vector2 coordinates in the given array or Float32Array from the given index.- * @param array defines the source array- * @param index defines the offset in source array- * @returns the current Vector2- */- toArray(array: FloatArray, index: number = 0): Vector2 {- array[index] = this.x;- array[index + 1] = this.y;- return this;- }-- /**- * Update the current vector from an array- * @param array defines the destination array- * @param index defines the offset in the destination array- * @returns the current Vector3- */- fromArray(array: FloatArray, index: number = 0): Vector2 {- Vector2.FromArrayToRef(array, index, this);- return this;- }-- /**- * Copy the current vector to an array- * @returns a new array with 2 elements: the Vector2 coordinates.- */- asArray(): number[] {- const result = new Array<number>();- this.toArray(result, 0);- return result;- }-- /**- * Sets the Vector2 coordinates with the given Vector2 coordinates- * @param source defines the source Vector2- * @returns the current updated Vector2- */- copyFrom(source: DeepImmutable<Vector2>): Vector2 {- this.x = source.x;- this.y = source.y;- return this;- }-- /**- * Sets the Vector2 coordinates with the given floats- * @param x defines the first coordinate- * @param y defines the second coordinate- * @returns the current updated Vector2- */- copyFromFloats(x: number, y: number): Vector2 {- this.x = x;- this.y = y;- return this;- }-- /**- * Sets the Vector2 coordinates with the given floats- * @param x defines the first coordinate- * @param y defines the second coordinate- * @returns the current updated Vector2- */- set(x: number, y: number): Vector2 {- return this.copyFromFloats(x, y);- }-- /**- * Add another vector with the current one- * @param otherVector defines the other vector- * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates- */- add(otherVector: DeepImmutable<Vector2>): Vector2 {- return new Vector2(this.x + otherVector.x, this.y + otherVector.y);- }-- /**- * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates- * @param otherVector defines the other vector- * @param result defines the target vector- * @returns the unmodified current Vector2- */- addToRef(otherVector: DeepImmutable<Vector2>, result: Vector2): Vector2 {- result.x = this.x + otherVector.x;- result.y = this.y + otherVector.y;- return this;- }-- addByPoint(x: number, y: number) {- return new Vector2(this.x + x, this.y + y);- }-- /**- * Set the Vector2 coordinates by adding the given Vector2 coordinates- * @param otherVector defines the other vector- * @returns the current updated Vector2- */- addInPlace(otherVector: DeepImmutable<Vector2>): Vector2 {- this.x += otherVector.x;- this.y += otherVector.y;- return this;- }-- /**- * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2- * @param otherVector defines the other vector- * @returns a new Vector2- */- subtract(otherVector: Vector2): Vector2 {- return new Vector2(this.x - otherVector.x, this.y - otherVector.y);- }-- subtractByPoint(x: number, y: number) {- return new Vector2(this.x - x, this.y - y);- }-- /**- * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.- * @param otherVector defines the other vector- * @param result defines the target vector- * @returns the unmodified current Vector2- */- subtractToRef(otherVector: DeepImmutable<Vector2>, result: Vector2): Vector2 {- result.x = this.x - otherVector.x;- result.y = this.y - otherVector.y;- return this;- }-- /**- * Sets the current Vector2 coordinates by subtracting from it the given one coordinates- * @param otherVector defines the other vector- * @returns the current updated Vector2- */- subtractInPlace(otherVector: DeepImmutable<Vector2>): Vector2 {- this.x -= otherVector.x;- this.y -= otherVector.y;- return this;- }-- /**- * Multiplies in place the current Vector2 coordinates by the given ones- * @param otherVector defines the other vector- * @returns the current updated Vector2- */- multiplyInPlace(otherVector: DeepImmutable<Vector2>): Vector2 {- this.x *= otherVector.x;- this.y *= otherVector.y;- return this;- }-- /**- * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates- * @param otherVector defines the other vector- * @returns a new Vector2- */- multiply(otherVector: DeepImmutable<Vector2>): Vector2 {- return new Vector2(this.x * otherVector.x, this.y * otherVector.y);- }-- /**- * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates- * @param otherVector defines the other vector- * @param result defines the target vector- * @returns the unmodified current Vector2- */- multiplyToRef(otherVector: DeepImmutable<Vector2>, result: Vector2): Vector2 {- result.x = this.x * otherVector.x;- result.y = this.y * otherVector.y;- return this;- }-- /**- * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats- * @param x defines the first coordinate- * @param y defines the second coordinate- * @returns a new Vector2- */- multiplyByFloats(x: number, y: number): Vector2 {- return new Vector2(this.x * x, this.y * y);- }-- /**- * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates- * @param otherVector defines the other vector- * @returns a new Vector2- */- divide(otherVector: Vector2): Vector2 {- return new Vector2(this.x / otherVector.x, this.y / otherVector.y);- }-- /**- * Sets the "result" coordinates with the Vector2 divided by the given one coordinates- * @param otherVector defines the other vector- * @param result defines the target vector- * @returns the unmodified current Vector2- */- divideToRef(otherVector: DeepImmutable<Vector2>, result: Vector2): Vector2 {- result.x = this.x / otherVector.x;- result.y = this.y / otherVector.y;- return this;- }-- /**- * Divides the current Vector2 coordinates by the given ones- * @param otherVector defines the other vector- * @returns the current updated Vector2- */- divideInPlace(otherVector: DeepImmutable<Vector2>): Vector2 {- return this.divideToRef(otherVector, this);- }-- /**- * Gets a new Vector2 with current Vector2 negated coordinates- * @returns a new Vector2- */- negate(): Vector2 {- return new Vector2(-this.x, -this.y);- }-- /**- * Negate this vector in place- * @returns this- */- negateInPlace(): Vector2 {- this.x *= -1;- this.y *= -1;- return this;- }-- /**- * Negate the current Vector2 and stores the result in the given vector "result" coordinates- * @param result defines the Vector3 object where to store the result- * @returns the current Vector2- */- negateToRef(result: Vector2): Vector2 {- return result.copyFromFloats(this.x * -1, this.y * -1);- }-- /**- * Multiply the Vector2 coordinates by scale- * @param scale defines the scaling factor- * @returns the current updated Vector2- */- scaleInPlace(scale: number): Vector2 {- this.x *= scale;- this.y *= scale;- return this;- }-- /**- * Returns a new Vector2 scaled by "scale" from the current Vector2- * @param scale defines the scaling factor- * @returns a new Vector2- */- scale(scale: number): Vector2 {- const result = new Vector2(0, 0);- this.scaleToRef(scale, result);- return result;- }-- /**- * Scale the current Vector2 values by a factor to a given Vector2- * @param scale defines the scale factor- * @param result defines the Vector2 object where to store the result- * @returns the unmodified current Vector2- */- scaleToRef(scale: number, result: Vector2): Vector2 {- result.x = this.x * scale;- result.y = this.y * scale;- return this;- }-- /**- * Scale the current Vector2 values by a factor and add the result to a given Vector2- * @param scale defines the scale factor- * @param result defines the Vector2 object where to store the result- * @returns the unmodified current Vector2- */- scaleAndAddToRef(scale: number, result: Vector2): Vector2 {- result.x += this.x * scale;- result.y += this.y * scale;- return this;- }-- /**- * Gets a boolean if two vectors are equals- * @param otherVector defines the other vector- * @returns true if the given vector coordinates strictly equal the current Vector2 ones- */- equals(otherVector: DeepImmutable<Vector2>): boolean {- return otherVector && this.x === otherVector.x && this.y === otherVector.y;- }-- /**- * Gets a new Vector2 from current Vector2 floored values- * eg (1.2, 2.31) returns (1, 2)- * @returns a new Vector2- */- floor(): Vector2 {- return new Vector2(Math.floor(this.x), Math.floor(this.y));- }-- /**- * Gets a new Vector2 from current Vector2 fractional values- * eg (1.2, 2.31) returns (0.2, 0.31)- * @returns a new Vector2- */- fract(): Vector2 {- return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));- }-- /**- * Rotate the current vector into a given result vector- * @param angle defines the rotation angle- * @returns the current vector- */- rotate(angle: number) {- const cos = Math.cos(angle);- const sin = Math.sin(angle);- const rx = cos * this.x - sin * this.y;- const ry = sin * this.x + cos * this.y;- this.x = rx;- this.y = ry;- return this;- }-- /**- * Rotate the current vector into a given result vector- * @param angle defines the rotation angle- * @param result defines the result vector where to store the rotated vector- * @returns the current vector- */- rotateToRef(angle: number, result: Vector2) {- const cos = Math.cos(angle);- const sin = Math.sin(angle);- result.x = cos * this.x - sin * this.y;- result.y = sin * this.x + cos * this.y;-- return this;- }-- rotateByPoint(angle: number, originPoint: Vector2 = Vector2.create(0, 0)) {- const cosA = Math.cos(angle);- const sinA = Math.sin(angle);- const rx = originPoint.x + (this.x - originPoint.x) * cosA - (this.y - originPoint.y) * sinA;- const ry = originPoint.y + (this.x - originPoint.x) * sinA + (this.y - originPoint.y) * cosA;- this.x = rx;- this.y = ry;- return this;- }-- transformCoordinateOnRotate(angle: number) {- const hypotenuse = Math.sqrt(this.x ** 2 + this.y ** 2);- const beta = Math.atan2(this.y, this.x);- const theta = -angle + beta;- this.x = hypotenuse * Math.cos(theta);- this.y = hypotenuse * Math.sin(theta);- return this;- }-- // Properties-- /**- * Gets the length of the vector- * @returns the vector length (float)- */- length(): number {- return Math.sqrt(this.x * this.x + this.y * this.y);- }-- /**- * Gets the vector squared length- * @returns the vector squared length (float)- */- lengthSquared(): number {- return this.x * this.x + this.y * this.y;- }-- // Methods-- /**- * Normalize the vector- * @returns the current updated Vector2- */- normalize(): Vector2 {- Vector2.NormalizeToRef(this, this);- return this;- }-- /**- * Gets a new Vector2 copied from the Vector2- * @returns a new Vector2- */- clone(): Vector2 {- return new Vector2(this.x, this.y);- }-}--export interface IBounds {- x: number;- y: number;- width: number;- height: number;-}--export interface IBoundRect {- tl: Vector2;- tr: Vector2;- bl: Vector2;- br: Vector2;- dx: number;- dy: number;-}--export interface IBoundRectNoAngle {- left: number;- top: number;- right: number;- bottom: number;-}+/* eslint-disable no-magic-numbers */+import type { DeepImmutable, FloatArray } from './i-events';++export interface IPoint {+ x: number;+ y: number;+}++export class Vector2 implements IPoint {+ /**+ * Creates a new Vector2 from the given x and y coordinates+ * @param x defines the first coordinate+ * @param y defines the second coordinate+ */+ constructor(+ /** defines the first coordinate */+ public x = 0,+ /** defines the second coordinate */+ public y = 0+ ) {}++ // Statics++ /**+ * Gets a new Vector2(0, 0)+ * @returns a new Vector2+ */+ static Zero(): Vector2 {+ return new Vector2(0, 0);+ }++ /**+ * Gets a new Vector2(1, 1)+ * @returns a new Vector2+ */+ static One(): Vector2 {+ return new Vector2(1, 1);+ }++ /**+ * Gets a new Vector2 set from the given index element of the given array+ * @param array defines the data source+ * @param offset defines the offset in the data source+ * @returns a new Vector2+ */+ static FromArray(array: DeepImmutable<ArrayLike<number>>, offset: number = 0): Vector2 {+ return new Vector2(array[offset], array[offset + 1]);+ }++ /**+ * Sets "result" from the given index element of the given array+ * @param array defines the data source+ * @param offset defines the offset in the data source+ * @param result defines the target vector+ */+ static FromArrayToRef(array: ArrayLike<number>, offset: number, result: Vector2): void {+ result.x = array[offset];+ result.y = array[offset + 1];+ }++ /**+ * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2+ * @param value1 defines 1st point of control+ * @param value2 defines 2nd point of control+ * @param value3 defines 3rd point of control+ * @param value4 defines 4th point of control+ * @param amount defines the interpolation factor+ * @returns a new Vector2+ */+ static CatmullRom(+ value1: DeepImmutable<Vector2>,+ value2: DeepImmutable<Vector2>,+ value3: DeepImmutable<Vector2>,+ value4: DeepImmutable<Vector2>,+ amount: number+ ): Vector2 {+ const squared = amount * amount;+ const cubed = amount * squared;++ const x =+ 0.5 *+ (2.0 * value2.x ++ (-value1.x + value3.x) * amount ++ (2.0 * value1.x - 5.0 * value2.x + 4.0 * value3.x - value4.x) * squared ++ (-value1.x + 3.0 * value2.x - 3.0 * value3.x + value4.x) * cubed);++ const y =+ 0.5 *+ (2.0 * value2.y ++ (-value1.y + value3.y) * amount ++ (2.0 * value1.y - 5.0 * value2.y + 4.0 * value3.y - value4.y) * squared ++ (-value1.y + 3.0 * value2.y - 3.0 * value3.y + value4.y) * cubed);++ return new Vector2(x, y);+ }++ /**+ * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".+ * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.+ * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate+ * @param value defines the value to clamp+ * @param min defines the lower limit+ * @param max defines the upper limit+ * @returns a new Vector2+ */+ static Clamp(value: DeepImmutable<Vector2>, min: DeepImmutable<Vector2>, max: DeepImmutable<Vector2>): Vector2 {+ let x = value.x;+ x = x > max.x ? max.x : x;+ x = x < min.x ? min.x : x;++ let y = value.y;+ y = y > max.y ? max.y : y;+ y = y < min.y ? min.y : y;++ return new Vector2(x, y);+ }++ /**+ * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2"+ * @param value1 defines the 1st control point+ * @param tangent1 defines the outgoing tangent+ * @param value2 defines the 2nd control point+ * @param tangent2 defines the incoming tangent+ * @param amount defines the interpolation factor+ * @returns a new Vector2+ */+ static Hermite(+ value1: DeepImmutable<Vector2>,+ tangent1: DeepImmutable<Vector2>,+ value2: DeepImmutable<Vector2>,+ tangent2: DeepImmutable<Vector2>,+ amount: number+ ): Vector2 {+ const squared = amount * amount;+ const cubed = amount * squared;+ const part1 = 2.0 * cubed - 3.0 * squared + 1.0;+ const part2 = -2.0 * cubed + 3.0 * squared;+ const part3 = cubed - 2.0 * squared + amount;+ const part4 = cubed - squared;++ const x = value1.x * part1 + value2.x * part2 + tangent1.x * part3 + tangent2.x * part4;+ const y = value1.y * part1 + value2.y * part2 + tangent1.y * part3 + tangent2.y * part4;++ return new Vector2(x, y);+ }++ /**+ * Returns a new Vector2 which is the 1st derivative of the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2".+ * @param value1 defines the first control point+ * @param tangent1 defines the first tangent+ * @param value2 defines the second control point+ * @param tangent2 defines the second tangent+ * @param time define where the derivative must be done+ * @returns 1st derivative+ */+ static Hermite1stDerivative(+ value1: DeepImmutable<Vector2>,+ tangent1: DeepImmutable<Vector2>,+ value2: DeepImmutable<Vector2>,+ tangent2: DeepImmutable<Vector2>,+ time: number+ ): Vector2 {+ const result = Vector2.Zero();++ this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result);++ return result;+ }++ /**+ * Returns a new Vector2 which is the 1st derivative of the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2".+ * @param value1 defines the first control point+ * @param tangent1 defines the first tangent+ * @param value2 defines the second control point+ * @param tangent2 defines the second tangent+ * @param time define where the derivative must be done+ * @param result define where the derivative will be stored+ */+ static Hermite1stDerivativeToRef(+ value1: DeepImmutable<Vector2>,+ tangent1: DeepImmutable<Vector2>,+ value2: DeepImmutable<Vector2>,+ tangent2: DeepImmutable<Vector2>,+ time: number,+ result: Vector2+ ) {+ const t2 = time * time;++ result.x =+ (t2 - time) * 6 * value1.x ++ (3 * t2 - 4 * time + 1) * tangent1.x ++ (-t2 + time) * 6 * value2.x ++ (3 * t2 - 2 * time) * tangent2.x;+ result.y =+ (t2 - time) * 6 * value1.y ++ (3 * t2 - 4 * time + 1) * tangent1.y ++ (-t2 + time) * 6 * value2.y ++ (3 * t2 - 2 * time) * tangent2.y;+ }++ /**+ * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".+ * @param start defines the start vector+ * @param end defines the end vector+ * @param amount defines the interpolation factor+ * @returns a new Vector2+ */+ static Lerp(start: DeepImmutable<Vector2>, end: DeepImmutable<Vector2>, amount: number): Vector2 {+ const x = start.x + (end.x - start.x) * amount;+ const y = start.y + (end.y - start.y) * amount;+ return new Vector2(x, y);+ }++ /**+ * Gets the dot product of the vector "left" and the vector "right"+ * @param left defines first vector+ * @param right defines second vector+ * @returns the dot product (float)+ */+ static Dot(left: DeepImmutable<Vector2>, right: DeepImmutable<Vector2>): number {+ return left.x * right.x + left.y * right.y;+ }++ /**+ * Returns a new Vector2 equal to the normalized given vector+ * @param vector defines the vector to normalize+ * @returns a new Vector2+ */+ static Normalize(vector: DeepImmutable<Vector2>): Vector2 {+ const newVector = Vector2.Zero();+ this.NormalizeToRef(vector, newVector);+ return newVector;+ }++ /**+ * Normalize a given vector into a second one+ * @param vector defines the vector to normalize+ * @param result defines the vector where to store the result+ */+ static NormalizeToRef(vector: DeepImmutable<Vector2>, result: Vector2) {+ const len = vector.length();++ if (len === 0) {+ return;+ }++ result.x = vector.x / len;+ result.y = vector.y / len;+ }++ /**+ * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors+ * @param left defines 1st vector+ * @param right defines 2nd vector+ * @returns a new Vector2+ */+ static Minimize(left: DeepImmutable<Vector2>, right: DeepImmutable<Vector2>): Vector2 {+ const x = left.x < right.x ? left.x : right.x;+ const y = left.y < right.y ? left.y : right.y;+ return new Vector2(x, y);+ }++ /**+ * Gets a new Vector2 set with the maximal coordinate values from the "left" and "right" vectors+ * @param left defines 1st vector+ * @param right defines 2nd vector+ * @returns a new Vector2+ */+ static Maximize(left: DeepImmutable<Vector2>, right: DeepImmutable<Vector2>): Vector2 {+ const x = left.x > right.x ? left.x : right.x;+ const y = left.y > right.y ? left.y : right.y;+ return new Vector2(x, y);+ }++ // /**+ // * Transforms the given vector coordinates by the given transformation Transform and stores the result in the vector "result" coordinates+ // * @param vector defines the vector to transform+ // * @param transformation defines the Transform to apply+ // * @param result defines the target vector+ // */+ // static Transform(vector: DeepImmutable<Vector2>, transformation: DeepImmutable<Transform>, ignoreOffset: boolean = false) {+ // const t = transformation as IKeyValue;+ // const p = vector;++ // if (ignoreOffset) {+ // return new Vector2(t[0] * p.x + t[2] * p.y, t[1] * p.x + t[3] * p.y);+ // }+ // return new Vector2(t[0] * p.x + t[2] * p.y + t[4], t[1] * p.x + t[3] * p.y + t[5]);+ // }++ /**+ * Determines if a given vector is included in a triangle+ * @param p defines the vector to test+ * @param p0 defines 1st triangle point+ * @param p1 defines 2nd triangle point+ * @param p2 defines 3rd triangle point+ * @returns true if the point "p" is in the triangle defined by the vectors "p0", "p1", "p2"+ */+ static PointInTriangle(+ p: DeepImmutable<Vector2>,+ p0: DeepImmutable<Vector2>,+ p1: DeepImmutable<Vector2>,+ p2: DeepImmutable<Vector2>+ ) {+ const a = (1 / 2) * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);+ const sign = a < 0 ? -1 : 1;+ const s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;+ const t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;++ return s > 0 && t > 0 && s + t < 2 * a * sign;+ }++ /**+ * Gets the distance between the vectors "value1" and "value2"+ * @param value1 defines first vector+ * @param value2 defines second vector+ * @returns the distance between vectors+ */+ static Distance(value1: DeepImmutable<Vector2>, value2: DeepImmutable<Vector2>): number {+ return Math.sqrt(Vector2.DistanceSquared(value1, value2));+ }++ /**+ * Returns the squared distance between the vectors "value1" and "value2"+ * @param value1 defines first vector+ * @param value2 defines second vector+ * @returns the squared distance between vectors+ */+ static DistanceSquared(value1: DeepImmutable<Vector2>, value2: DeepImmutable<Vector2>): number {+ const x = value1.x - value2.x;+ const y = value1.y - value2.y;+ return x * x + y * y;+ }++ /**+ * Gets a new Vector2 located at the center of the vectors "value1" and "value2"+ * @param value1 defines first vector+ * @param value2 defines second vector+ * @returns a new Vector2+ */+ static Center(value1: DeepImmutable<Vector2>, value2: DeepImmutable<Vector2>): Vector2 {+ return Vector2.CenterToRef(value1, value2, Vector2.Zero());+ }++ /**+ * Gets the center of the vectors "value1" and "value2" and stores the result in the vector "ref"+ * @param value1 defines first vector+ * @param value2 defines second vector+ * @param ref defines third vector+ * @returns ref+ */+ static CenterToRef(+ value1: DeepImmutable<Vector2>,+ value2: DeepImmutable<Vector2>,+ ref: DeepImmutable<Vector2>+ ): Vector2 {+ return ref.copyFromFloats((value1.x + value2.x) / 2, (value1.y + value2.y) / 2);+ }++ /**+ * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".+ * @param p defines the middle point+ * @param segA defines one point of the segment+ * @param segB defines the other point of the segment+ * @returns the shortest distance+ */+ static DistanceOfPointFromSegment(+ p: DeepImmutable<Vector2>,+ segA: DeepImmutable<Vector2>,+ segB: DeepImmutable<Vector2>+ ): number {+ const l2 = Vector2.DistanceSquared(segA, segB);+ if (l2 === 0.0) {+ return Vector2.Distance(p, segA);+ }+ const v = segB.subtract(segA);+ const t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));+ const proj = segA.add(v.multiplyByFloats(t, t));+ return Vector2.Distance(p, proj);+ }++ static create(x: number, y: number) {+ return new Vector2(x, y);+ }++ /**+ * Gets a string with the Vector2 coordinates+ * @returns a string with the Vector2 coordinates+ */+ toString(): string {+ return `{X: ${this.x} Y: ${this.y}}`;+ }++ /**+ * Gets class name+ * @returns the string "Vector2"+ */+ getClassName(): string {+ return 'Vector2';+ }++ /**+ * Gets current vector hash code+ * @returns the Vector2 hash code as a number+ */+ getHashCode(): number {+ let hash = this.x | 0;+ hash = (hash * 397) ^ (this.y | 0);+ return hash;+ }++ // Operators++ /**+ * Sets the Vector2 coordinates in the given array or Float32Array from the given index.+ * @param array defines the source array+ * @param index defines the offset in source array+ * @returns the current Vector2+ */+ toArray(array: FloatArray, index: number = 0): Vector2 {+ array[index] = this.x;+ array[index + 1] = this.y;+ return this;+ }++ /**+ * Update the current vector from an array+ * @param array defines the destination array+ * @param index defines the offset in the destination array+ * @returns the current Vector3+ */+ fromArray(array: FloatArray, index: number = 0): Vector2 {+ Vector2.FromArrayToRef(array, index, this);+ return this;+ }++ /**+ * Copy the current vector to an array+ * @returns a new array with 2 elements: the Vector2 coordinates.+ */+ asArray(): number[] {+ const result = new Array<number>();+ this.toArray(result, 0);+ return result;+ }++ /**+ * Sets the Vector2 coordinates with the given Vector2 coordinates+ * @param source defines the source Vector2+ * @returns the current updated Vector2+ */+ copyFrom(source: DeepImmutable<Vector2>): Vector2 {+ this.x = source.x;+ this.y = source.y;+ return this;+ }++ /**+ * Sets the Vector2 coordinates with the given floats+ * @param x defines the first coordinate+ * @param y defines the second coordinate+ * @returns the current updated Vector2+ */+ copyFromFloats(x: number, y: number): Vector2 {+ this.x = x;+ this.y = y;+ return this;+ }++ /**+ * Sets the Vector2 coordinates with the given floats+ * @param x defines the first coordinate+ * @param y defines the second coordinate+ * @returns the current updated Vector2+ */+ set(x: number, y: number): Vector2 {+ return this.copyFromFloats(x, y);+ }++ /**+ * Add another vector with the current one+ * @param otherVector defines the other vector+ * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates+ */+ add(otherVector: DeepImmutable<Vector2>): Vector2 {+ return new Vector2(this.x + otherVector.x, this.y + otherVector.y);+ }++ /**+ * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates+ * @param otherVector defines the other vector+ * @param result defines the target vector+ * @returns the unmodified current Vector2+ */+ addToRef(otherVector: DeepImmutable<Vector2>, result: Vector2): Vector2 {+ result.x = this.x + otherVector.x;+ result.y = this.y + otherVector.y;+ return this;+ }++ addByPoint(x: number, y: number) {+ return new Vector2(this.x + x, this.y + y);+ }++ /**+ * Set the Vector2 coordinates by adding the given Vector2 coordinates+ * @param otherVector defines the other vector+ * @returns the current updated Vector2+ */+ addInPlace(otherVector: DeepImmutable<Vector2>): Vector2 {+ this.x += otherVector.x;+ this.y += otherVector.y;+ return this;+ }++ /**+ * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2+ * @param otherVector defines the other vector+ * @returns a new Vector2+ */+ subtract(otherVector: Vector2): Vector2 {+ return new Vector2(this.x - otherVector.x, this.y - otherVector.y);+ }++ subtractByPoint(x: number, y: number) {+ return new Vector2(this.x - x, this.y - y);+ }++ /**+ * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.+ * @param otherVector defines the other vector+ * @param result defines the target vector+ * @returns the unmodified current Vector2+ */+ subtractToRef(otherVector: DeepImmutable<Vector2>, result: Vector2): Vector2 {+ result.x = this.x - otherVector.x;+ result.y = this.y - otherVector.y;+ return this;+ }++ /**+ * Sets the current Vector2 coordinates by subtracting from it the given one coordinates+ * @param otherVector defines the other vector+ * @returns the current updated Vector2+ */+ subtractInPlace(otherVector: DeepImmutable<Vector2>): Vector2 {+ this.x -= otherVector.x;+ this.y -= otherVector.y;+ return this;+ }++ /**+ * Multiplies in place the current Vector2 coordinates by the given ones+ * @param otherVector defines the other vector+ * @returns the current updated Vector2+ */+ multiplyInPlace(otherVector: DeepImmutable<Vector2>): Vector2 {+ this.x *= otherVector.x;+ this.y *= otherVector.y;+ return this;+ }++ /**+ * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates+ * @param otherVector defines the other vector+ * @returns a new Vector2+ */+ multiply(otherVector: DeepImmutable<Vector2>): Vector2 {+ return new Vector2(this.x * otherVector.x, this.y * otherVector.y);+ }++ /**+ * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates+ * @param otherVector defines the other vector+ * @param result defines the target vector+ * @returns the unmodified current Vector2+ */+ multiplyToRef(otherVector: DeepImmutable<Vector2>, result: Vector2): Vector2 {+ result.x = this.x * otherVector.x;+ result.y = this.y * otherVector.y;+ return this;+ }++ /**+ * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats+ * @param x defines the first coordinate+ * @param y defines the second coordinate+ * @returns a new Vector2+ */+ multiplyByFloats(x: number, y: number): Vector2 {+ return new Vector2(this.x * x, this.y * y);+ }++ /**+ * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates+ * @param otherVector defines the other vector+ * @returns a new Vector2+ */+ divide(otherVector: Vector2): Vector2 {+ return new Vector2(this.x / otherVector.x, this.y / otherVector.y);+ }++ /**+ * Sets the "result" coordinates with the Vector2 divided by the given one coordinates+ * @param otherVector defines the other vector+ * @param result defines the target vector+ * @returns the unmodified current Vector2+ */+ divideToRef(otherVector: DeepImmutable<Vector2>, result: Vector2): Vector2 {+ result.x = this.x / otherVector.x;+ result.y = this.y / otherVector.y;+ return this;+ }++ /**+ * Divides the current Vector2 coordinates by the given ones+ * @param otherVector defines the other vector+ * @returns the current updated Vector2+ */+ divideInPlace(otherVector: DeepImmutable<Vector2>): Vector2 {+ return this.divideToRef(otherVector, this);+ }++ /**+ * Gets a new Vector2 with current Vector2 negated coordinates+ * @returns a new Vector2+ */+ negate(): Vector2 {+ return new Vector2(-this.x, -this.y);+ }++ /**+ * Negate this vector in place+ * @returns this+ */+ negateInPlace(): Vector2 {+ this.x *= -1;+ this.y *= -1;+ return this;+ }++ /**+ * Negate the current Vector2 and stores the result in the given vector "result" coordinates+ * @param result defines the Vector3 object where to store the result+ * @returns the current Vector2+ */+ negateToRef(result: Vector2): Vector2 {+ return result.copyFromFloats(this.x * -1, this.y * -1);+ }++ /**+ * Multiply the Vector2 coordinates by scale+ * @param scale defines the scaling factor+ * @returns the current updated Vector2+ */+ scaleInPlace(scale: number): Vector2 {+ this.x *= scale;+ this.y *= scale;+ return this;+ }++ /**+ * Returns a new Vector2 scaled by "scale" from the current Vector2+ * @param scale defines the scaling factor+ * @returns a new Vector2+ */+ scale(scale: number): Vector2 {+ const result = new Vector2(0, 0);+ this.scaleToRef(scale, result);+ return result;+ }++ /**+ * Scale the current Vector2 values by a factor to a given Vector2+ * @param scale defines the scale factor+ * @param result defines the Vector2 object where to store the result+ * @returns the unmodified current Vector2+ */+ scaleToRef(scale: number, result: Vector2): Vector2 {+ result.x = this.x * scale;+ result.y = this.y * scale;+ return this;+ }++ /**+ * Scale the current Vector2 values by a factor and add the result to a given Vector2+ * @param scale defines the scale factor+ * @param result defines the Vector2 object where to store the result+ * @returns the unmodified current Vector2+ */+ scaleAndAddToRef(scale: number, result: Vector2): Vector2 {+ result.x += this.x * scale;+ result.y += this.y * scale;+ return this;+ }++ /**+ * Gets a boolean if two vectors are equals+ * @param otherVector defines the other vector+ * @returns true if the given vector coordinates strictly equal the current Vector2 ones+ */+ equals(otherVector: DeepImmutable<Vector2>): boolean {+ return otherVector && this.x === otherVector.x && this.y === otherVector.y;+ }++ /**+ * Gets a new Vector2 from current Vector2 floored values+ * eg (1.2, 2.31) returns (1, 2)+ * @returns a new Vector2+ */+ floor(): Vector2 {+ return new Vector2(Math.floor(this.x), Math.floor(this.y));+ }++ /**+ * Gets a new Vector2 from current Vector2 fractional values+ * eg (1.2, 2.31) returns (0.2, 0.31)+ * @returns a new Vector2+ */+ fract(): Vector2 {+ return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));+ }++ /**+ * Rotate the current vector into a given result vector+ * @param angle defines the rotation angle+ * @returns the current vector+ */+ rotate(angle: number) {+ const cos = Math.cos(angle);+ const sin = Math.sin(angle);+ const rx = cos * this.x - sin * this.y;+ const ry = sin * this.x + cos * this.y;+ this.x = rx;+ this.y = ry;+ return this;+ }++ /**+ * Rotate the current vector into a given result vector+ * @param angle defines the rotation angle+ * @param result defines the result vector where to store the rotated vector+ * @returns the current vector+ */+ rotateToRef(angle: number, result: Vector2) {+ const cos = Math.cos(angle);+ const sin = Math.sin(angle);+ result.x = cos * this.x - sin * this.y;+ result.y = sin * this.x + cos * this.y;++ return this;+ }++ rotateByPoint(angle: number, originPoint = Vector2.create(0, 0)) {+ const cosA = Math.cos(angle);+ const sinA = Math.sin(angle);+ const rx = originPoint.x + (this.x - originPoint.x) * cosA - (this.y - originPoint.y) * sinA;+ const ry = originPoint.y + (this.x - originPoint.x) * sinA + (this.y - originPoint.y) * cosA;++ this.x = rx;+ this.y = ry;++ return this;+ }++ transformCoordinateOnRotate(angle: number) {+ const hypotenuse = Math.sqrt(this.x ** 2 + this.y ** 2);+ const beta = Math.atan2(this.y, this.x);+ const theta = -angle + beta;+ this.x = hypotenuse * Math.cos(theta);+ this.y = hypotenuse * Math.sin(theta);+ return this;+ }++ // Properties++ /**+ * Gets the length of the vector+ * @returns the vector length (float)+ */+ length(): number {+ return Math.sqrt(this.x * this.x + this.y * this.y);+ }++ /**+ * Gets the vector squared length+ * @returns the vector squared length (float)+ */+ lengthSquared(): number {+ return this.x * this.x + this.y * this.y;+ }++ // Methods++ /**+ * Normalize the vector+ * @returns the current updated Vector2+ */+ normalize(): Vector2 {+ Vector2.NormalizeToRef(this, this);+ return this;+ }++ /**+ * Gets a new Vector2 copied from the Vector2+ * @returns a new Vector2+ */+ clone(): Vector2 {+ return new Vector2(this.x, this.y);+ }+}++export interface IBounds {+ x: number;+ y: number;+ width: number;+ height: number;+}++export interface IBoundRect {+ tl: Vector2;+ tr: Vector2;+ bl: Vector2;+ br: Vector2;+ dx: number;+ dy: number;+}++export interface IBoundRectNoAngle {+ left: number;+ top: number;+ right: number;+ bottom: number;+}diff --git a/packages/engine-render/src/components/docs/block/paragraph/language-ruler.ts b/packages/engine-render/src/components/docs/block/paragraph/language-ruler.tsindex a5d92b4eb5..b8793099b6 100644--- a/packages/engine-render/src/components/docs/block/paragraph/language-ruler.ts+++ b/packages/engine-render/src/components/docs/block/paragraph/language-ruler.ts@@ -3,13 +3,13 @@ import { DataStreamTreeTokenType } from '@univerjs/core';import type { IDocumentSkeletonSpan } from '../../../../basics/i-document-skeleton-cached';import type { ISectionBreakConfig } from '../../../../basics/interfaces';-import { hasArabic, hasCJK, hasSpaceAndTab, hasTibetan } from '../../../../basics/tools';+import { hasArabic, hasCJKText, hasSpaceAndTab, hasTibetan } from '../../../../basics/tools';import { createSkeletonLetterSpan, createSkeletonWordSpan } from '../../common/span';import { getFontCreateConfig } from '../../common/tools';import type { DataStreamTreeNode } from '../../view-model/data-stream-tree-node';import type { DocumentViewModel } from '../../view-model/document-view-model';-interface LanguageResult {+interface ILanguageResult {charIndex: number;spanGroup: IDocumentSkeletonSpan[];}@@ -22,17 +22,20 @@ export function composeCharForLanguage(paragraphNode: DataStreamTreeNode,sectionBreakConfig: ISectionBreakConfig,paragraphStyle: IParagraphStyle-): Nullable<LanguageResult> {+): Nullable<ILanguageResult> {if (char === DataStreamTreeTokenType.SPACE) {return;}+if (hasArabic(char)) {return ArabicHandler(char, index, charArray, bodyModel, paragraphNode, sectionBreakConfig, paragraphStyle);}+if (hasTibetan(char)) {return TibetanHandler(char, index, charArray, bodyModel, paragraphNode, sectionBreakConfig, paragraphStyle);}- if (!hasCJK(char)) {++ if (!hasCJKText(char)) {return notCJKHandler(char, index, charArray, bodyModel, paragraphNode, sectionBreakConfig, paragraphStyle);}}@@ -54,9 +57,10 @@ function notCJKHandler(const spanGroup = [charSke];let allWidth = charSke.width;let newCharIndex = index;+for (let i = index + 1; i < charArray.length; i++) {const newChar = charArray[i];- if (!hasCJK(newChar) && !hasSpaceAndTab(newChar)) {+ if (!hasCJKText(newChar) && !hasSpaceAndTab(newChar)) {const newConfig = getFontCreateConfig(i, bodyModel, paragraphNode, sectionBreakConfig, paragraphStyle);const newSpan = createSkeletonLetterSpan(newChar, newConfig);const newCharWidth = newSpan.width;@@ -71,6 +75,7 @@ function notCJKHandler(break;}}+return {charIndex: newCharIndex,spanGroup,diff --git a/packages/engine-render/src/components/docs/block/paragraph/layout-ruler.ts b/packages/engine-render/src/components/docs/block/paragraph/layout-ruler.tsindex 512ba5df14..c6e4a58e83 100644--- a/packages/engine-render/src/components/docs/block/paragraph/layout-ruler.ts+++ b/packages/engine-render/src/components/docs/block/paragraph/layout-ruler.ts@@ -1,13 +1,8 @@import type { INumberUnit, IParagraphStyle } from '@univerjs/core';-import {- BooleanNumber,- DataStreamTreeTokenType,- GridType,- HorizontalAlign,- NamedStyleType,- SpacingRule,-} from '@univerjs/core';+import { BooleanNumber, DataStreamTreeTokenType, GridType, SpacingRule } from '@univerjs/core';+import { hasChineseText } from '../../../../basics';+import { FontCache } from '../../../../basics/font-cache';import type {IDocumentSkeletonBullet,IDocumentSkeletonColumn,@@ -27,7 +22,7 @@ import {// eslint-disable-next-line import/no-cycleimport { createSkeletonPage } from '../../common/page';import { setColumnFullState } from '../../common/section';-import { addSpanToDivide, createSkeletonBulletSpan } from '../../common/span';+import { addSpanToDivide, createSkeletonBulletSpan, hasMixedTextLayout } from '../../common/span';import {getCharSpaceApply,getCharSpaceConfig,@@ -69,42 +64,59 @@ export function calculateParagraphLayout(const bulletSpan = createSkeletonBulletSpan(spanGroup[0], bulletSkeleton, charSpaceApply);_lineOperator([bulletSpan, ...spanGroup], pages, sectionBreakConfig, paragraphConfig, paragraphStart);- // _divideOperator(spanGroup, pages, sectionBreakConfig, paragraphConfig, elementIndex, isFirstSpan);} else {_lineOperator(spanGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart);}} else {_divideOperator(spanGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart);}+return [...pages];}-// eslint-disable-next-line max-lines-per-functionfunction _divideOperator(spanGroup: IDocumentSkeletonSpan[],pages: IDocumentSkeletonPage[],sectionBreakConfig: ISectionBreakConfig,paragraphConfig: IParagraphConfig,- paragraphStart: boolean = false,+ paragraphStart = false,+ isOutMost = true,defaultSpanLineHeight?: number) {const lastPage = getLastPage(pages);- const divideInfo = getLastNotFullDivideInfo(lastPage); // 取得最新一行里内容未满的第一个divide+ const divideInfo = getLastNotFullDivideInfo(lastPage); // 取得最新一行里内容未满的第一个 divide.if (divideInfo) {const width = __getSpanGroupWidth(spanGroup);- const divide = divideInfo.divide;+ const { divide } = divideInfo;const lastSpan = divide?.spanGroup?.[divide.spanGroup.length - 1];- // const { w: preWidth = 0, l: preLeft = 0 } = lastSpan;const preWidth = lastSpan?.width || 0;const preLeft = lastSpan?.left || 0;- // const { width: pageWidth, marginLeft: pageMarginLeft, marginRight: pageMarginRight } = lastPage;const pageContentWidth = getPageContentWidth(lastPage);- const preOffsetLeft = preWidth + preLeft;+ // Last span is western char and the current span is Chinese word or vice verse.+ const isMixedCJKWesternTextLayout = hasMixedTextLayout(lastSpan, spanGroup[0]);+ let wordSpaceWidth = 0;+ let preOffsetLeft = preWidth + preLeft;++ // Only add word space between Chinese text and Western text when processing span for the first time,+ // otherwise it will be added multiple times during recursion.+ if (isMixedCJKWesternTextLayout && isOutMost) {+ const lastSpanIsChineseWord = hasChineseText(lastSpan.content!);+ const WORD_INNER_SPACE = '\u0020';++ wordSpaceWidth = FontCache.getTextSize(+ WORD_INNER_SPACE, // word space.+ lastSpanIsChineseWord ? spanGroup[0].fontStyle! : lastSpan.fontStyle!+ ).width;++ preOffsetLeft += wordSpaceWidth;++ lastSpan.width += wordSpaceWidth;+ }if (preOffsetLeft + width > divide.width) {- // w超过div宽度+ // width 超过 divide 宽度setDivideFullState(divide, true);const column = getColumnByDivide(divide);@@ -112,7 +124,6 @@ function _divideOperator(// 一个字符超页内容宽if (isBlankPage(lastPage)) {addSpanToDivide(divide, spanGroup, preOffsetLeft);- // divide.spanGroup.push(...spanGroup);__makeColumnsFull(column?.parent?.columns);} else {_pageOperator(@@ -130,7 +141,6 @@ function _divideOperator(if (isBlankColumn(column)) {addSpanToDivide(divide, spanGroup, preOffsetLeft);- // divide.spanGroup.push(...spanGroup);} else {_columnOperator(spanGroup,@@ -167,13 +177,15 @@ function _divideOperator(sectionBreakConfig,paragraphConfig,paragraphStart,+ false,defaultSpanLineHeight);}} else {- // w不超过div宽度,加入到divide中去+ // w 不超过 divide 宽度,加入到 divide 中去const currentLine = divide.parent;const maxBox = __maxFontBoundingBoxBySpanGroup(spanGroup);+if (currentLine && maxBox && !__isNullLine(currentLine)) {const { paragraphLineGapDefault, linePitch, lineSpacing, spacingRule, snapToGrid, gridType } =getLineHeightConfig(sectionBreakConfig, paragraphConfig);@@ -188,13 +200,17 @@ function _divideOperator(spacingRule,snapToGrid);+if (currentLine.contentHeight < contentHeight) {// 如果新内容的高度超过其加入行的高度,为了处理图文混排,整行都需要按照新高度重新计算- // If the height of the new content exceeds the height of the added row, the entire row needs to be recalculated according to the new height in order to handle the mixing of graphics and text+ // If the height of the new content exceeds the height of the added row,+ // the entire row needs to be recalculated according to the new height+ // in order to handle the mixing of graphics and textconst spanGroupCached = __getSpanGroupByLine(currentLine);const spanGroupCachedLen = spanGroupCached.length;let newSpanGroup = [];let startIndex = 1;+if (spanGroupCachedLen > 2 && spanGroupCached[0].spanType === SpanType.LIST) {newSpanGroup = [spanGroupCached[0], spanGroupCached[1]];startIndex = 2;@@ -203,6 +219,7 @@ function _divideOperator(}const column = currentLine.parent;column?.lines.pop(); // Delete the previous line and recalculate according to the maximum content height+_lineOperator(newSpanGroup,pages,@@ -211,30 +228,31 @@ function _divideOperator(paragraphStart,boundingBoxAscent + boundingBoxDescent);+for (let i = startIndex; i < spanGroupCached.length; i++) {_divideOperator([spanGroupCached[i]],pages,sectionBreakConfig,paragraphConfig,- paragraphStart+ paragraphStart,+ false);}- _divideOperator(spanGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart);++ _divideOperator(spanGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart, false);+return;}}- // console.log('spanGroup', spanGroup, spanGroup.length, spanGroup[0].content);addSpanToDivide(divide, spanGroup, preOffsetLeft);- // divide.spanGroup.push(...spanGroup);}} else {_lineOperator(spanGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart, defaultSpanLineHeight);}}-// eslint-disable-next-line max-lines-per-functionfunction _lineOperator(spanGroup: IDocumentSkeletonSpan[],pages: IDocumentSkeletonPage[],@@ -270,30 +288,30 @@ function _lineOperator(} = paragraphConfig;const {- namedStyleType = NamedStyleType.NAMED_STYLE_TYPE_UNSPECIFIED,- horizontalAlign = HorizontalAlign.UNSPECIFIED,+ // namedStyleType = NamedStyleType.NAMED_STYLE_TYPE_UNSPECIFIED,+ // horizontalAlign = HorizontalAlign.UNSPECIFIED,- direction,+ // direction,spaceAbove = 0,spaceBelow = 0,- borderBetween,- borderTop,- borderBottom,- borderLeft,- borderRight,+ // borderBetween,+ // borderTop,+ // borderBottom,+ // borderLeft,+ // borderRight,indentFirstLine = 0,hanging = 0,indentStart = 0,indentEnd = 0,- tabStops = [],+ // tabStops = [],- keepLines = BooleanNumber.FALSE,- keepNext = BooleanNumber.FALSE,- wordWrap = BooleanNumber.FALSE,- widowControl = BooleanNumber.FALSE,- shading,+ // keepLines = BooleanNumber.FALSE,+ // keepNext = BooleanNumber.FALSE,+ // wordWrap = BooleanNumber.FALSE,+ // widowControl = BooleanNumber.FALSE,+ // shading,} = paragraphStyle;const { paragraphLineGapDefault, linePitch, lineSpacing, spacingRule, snapToGrid, gridType } = getLineHeightConfig(@@ -347,7 +365,7 @@ function _lineOperator(lastPage.skeDrawings,headersDrawings,footersDrawings- ); // WRAP_TOP_AND_BOTTOM的drawing会改变行的起始top+ ); // WRAP_TOP_AND_BOTTOM 的 drawing 会改变行的起始 topif (lineHeight + newLineTop > section.height && column.lines.length > 0 && lastPage.sections.length > 0) {// 行高超过Col高度,且列中已存在一行以上,且section大于一个;@@ -394,10 +412,11 @@ function _lineOperator(headersDrawings,footersDrawings);+column.lines.push(newLine);newLine.parent = column;createAndUpdateBlockAnchor(paragraphIndex, newLine, lineTop, drawingAnchor);- _divideOperator(spanGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart, defaultSpanLineHeight);+ _divideOperator(spanGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart, true, defaultSpanLineHeight);}function _columnOperator(@@ -409,8 +428,9 @@ function _columnOperator(defaultSpanLineHeight?: number) {const lastPage = getLastPage(pages);- const column = isColumnFull(lastPage);- if (column === true) {+ const columnIsFull = isColumnFull(lastPage);++ if (columnIsFull === true) {_pageOperator(spanGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart, defaultSpanLineHeight);} else {_lineOperator(spanGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart, defaultSpanLineHeight);@@ -427,6 +447,7 @@ function _pageOperator() {const curSkeletonPage: IDocumentSkeletonPage = getLastPage(pages);const { skeHeaders, skeFooters } = paragraphConfig;+pages.push(createSkeletonPage(sectionBreakConfig, { skeHeaders, skeFooters }, curSkeletonPage?.pageNumber));_columnOperator(spanGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart, defaultSpanLineHeight);}@@ -519,6 +540,7 @@ function __getParagraphSpace(function __makeColumnsFull(columns: IDocumentSkeletonColumn[] = []) {for (let i = 0; i < columns.length; i++) {const column = columns[i];+setColumnFullState(column, true);}}@@ -534,6 +556,7 @@ function __getLineHeight() {let paddingTop = paragraphLineGapDefault;let paddingBottom = paragraphLineGapDefault;+if (gridType === GridType.DEFAULT || snapToGrid === BooleanNumber.FALSE) {// 不应用doc grid网格的场景,根据字符高度和宽度决定布局if (spacingRule === SpacingRule.AUTO) {@@ -545,6 +568,7 @@ function __getLineHeight(lineSpacingApply: spanLineHeight,};}+return {paddingTop,paddingBottom,@@ -664,6 +688,7 @@ function __checkPageBreak(column: IDocumentSkeletonColumn) {function __getSpanGroupWidth(spanGroup: IDocumentSkeletonSpan[]) {const spanGroupLen = spanGroup.length;let width = 0;+for (let i = 0; i < spanGroupLen; i++) {const span = spanGroup[i];width += span.width;@@ -675,14 +700,18 @@ function __maxFontBoundingBoxBySpanGroup(spanGroup: IDocumentSkeletonSpan[]) {const spanGroupLen = spanGroup.length;let height = -Infinity;let maxBox;+for (let i = 0; i < spanGroupLen; i++) {const span = spanGroup[i];const { ba: boundingBoxAscent, bd: boundingBoxDescent } = span.bBox;+if (height < boundingBoxAscent + boundingBoxDescent) {maxBox = { boundingBoxAscent, boundingBoxDescent };}+height = boundingBoxAscent + boundingBoxDescent;}+return maxBox;}@@ -690,10 +719,12 @@ function __getSpanGroupByLine(line: IDocumentSkeletonLine) {const divides = line.divides;const dividesLen = divides.length;const spanGroup = [];+for (let i = 0; i < dividesLen; i++) {const divide = divides[i];spanGroup.push(...divide.spanGroup);}+return spanGroup;}@@ -718,8 +749,5 @@ function __bulletIndentHandler(}function __isNullLine(line: IDocumentSkeletonLine) {- if (line.divides[0].spanGroup[0]) {- return false;- }- return true;+ return !line.divides[0].spanGroup[0];}diff --git a/packages/engine-render/src/components/docs/block/paragraph/paragraph.ts b/packages/engine-render/src/components/docs/block/paragraph/paragraph.tsindex f0ec1d71a4..b8e98032cc 100644--- a/packages/engine-render/src/components/docs/block/paragraph/paragraph.ts+++ b/packages/engine-render/src/components/docs/block/paragraph/paragraph.ts@@ -125,6 +125,7 @@ export function dealWidthParagraph(if (customBlock == null) {continue;}+customBlockCache.set(charIndex, customBlock);const blockId = customBlock.blockId;const drawingOrigin = drawings[blockId];@@ -145,6 +146,7 @@ export function dealWidthParagraph(const charSpaceApply = getCharSpaceApply(charSpace, defaultTabStop, gridType, snapToGrid);const tabSpan = createSkeletonTabSpan(fontCreateConfig, charSpaceApply); // measureText收敛到create中执行allPages = calculateParagraphLayout([tabSpan], allPages, sectionBreakConfig, paragraphConfig, true);+continue;} else if (char === DataStreamTreeTokenType.CUSTOM_BLOCK) {let customBlock = customBlockCache.get(charIndex);@@ -204,6 +206,7 @@ export function dealWidthParagraph(paragraphStyle); // Handling special languages such as Tibetan, Arabiclet newSpanGroup = [];+if (languageHandlerResult) {const { charIndex: newCharIndex, spanGroup } = languageHandlerResult;i = newCharIndex;@@ -351,9 +354,9 @@ function horizontalAlignHandler(line: IDocumentSkeletonLine, horizontalAlign: Hoconst divideLength = divides.length;for (let i = 0; i < divideLength; i++) {const divide = divides[i];- const { width, spanGroup } = divide;+ const { width } = divide;const spanGroupWidth = getSpanGroupWidth(divide);- // console.log(spanGroup, spanGroupWidth, width);+if (width === Infinity) {continue;}diff --git a/packages/engine-render/src/components/docs/block/section.ts b/packages/engine-render/src/components/docs/block/section.tsindex fe689d847d..53138bba5c 100644--- a/packages/engine-render/src/components/docs/block/section.ts+++ b/packages/engine-render/src/components/docs/block/section.ts@@ -18,6 +18,7 @@ export function dealWithSections() {const allCurrentSkeletonPages: IDocumentSkeletonPage[] = [];const renderedBlockIdMap = new Map<string, boolean>();+for (const node of sectionNode.children) {// const { paragraph, table, tableOfContents, blockType, customBlock, blockId } = block;// if (preRenderedBlockIdMap?.get(blockId)) {diff --git a/packages/engine-render/src/components/docs/common/line.ts b/packages/engine-render/src/components/docs/common/line.tsindex a8fb0b22e9..6e977f2cb1 100644--- a/packages/engine-render/src/components/docs/common/line.ts+++ b/packages/engine-render/src/components/docs/common/line.ts@@ -31,13 +31,13 @@ enum AxisType {interface ILineBoundingBox {lineHeight: number;lineTop: number;+ contentHeight: number;paddingLeft?: number;paddingRight?: number;paddingTop?: number;paddingBottom?: number;marginTop?: number;spaceBelowApply?: number;- contentHeight: number;}// 处理divides, divideLen, lineIndex, 无序和有序列表标题, drawingTBIds 影响行的元素id集合@@ -65,6 +65,7 @@ export function createSkeletonLine(} = lineBoundingBox;const lineSke = _getLineSke(lineType, paragraphIndex);+lineSke.lineIndex = lineIndex;lineSke.paragraphStart = isParagraphStart; // 是否段落开始的第一行lineSke.contentHeight = contentHeight;@@ -405,9 +406,11 @@ function _calculateDivideByDrawings(columnWidth: number, drawingSplit: IDrawingsconst divideSkeleton: IDocumentSkeletonDivide[] = [];let start = 0;const splitLength = drawingSplit.length;+for (let i = 0; i < splitLength; i++) {const split = drawingSplit[i];const { left, width } = split;+if (left > start) {// 插入start到left的间隔dividelet width = left - start;diff --git a/packages/engine-render/src/components/docs/common/span.ts b/packages/engine-render/src/components/docs/common/span.tsindex 7dc566d82c..6c573204d9 100644--- a/packages/engine-render/src/components/docs/common/span.ts+++ b/packages/engine-render/src/components/docs/common/span.ts@@ -1,3 +1,4 @@+import type { Nullable } from '@univerjs/core';import { BooleanNumber, BulletAlignment, DataStreamTreeTokenType as DT, GridType } from '@univerjs/core';import { FontCache } from '../../../basics/font-cache';@@ -8,7 +9,7 @@ import type {} from '../../../basics/i-document-skeleton-cached';import { SpanType } from '../../../basics/i-document-skeleton-cached';import type { IFontCreateConfig } from '../../../basics/interfaces';-import { hasCJK } from '../../../basics/tools';+import { hasCJKText } from '../../../basics/tools';import { validationGrid } from './tools';export function createSkeletonWordSpan(@@ -92,7 +93,7 @@ export function _createSkeletonWordOrLetter(if (validationGrid(gridType, snapToGrid)) {// 当文字也需要对齐到网格式,进行处理// const multiple = Math.ceil(contentWidth / charSpace);- width = contentWidth + (hasCJK(content) ? charSpace : charSpace / 2);+ width = contentWidth + (hasCJKText(content) ? charSpace : charSpace / 2);if (gridType === GridType.SNAP_TO_CHARS) {paddingLeft = (width - contentWidth) / 2;}@@ -157,9 +158,11 @@ export function createSkeletonBulletSpan(};}+// Set the left value of the current span based on the width of pre span and the left value of the previous span.export function setSpanGroupLeft(spanGroup: IDocumentSkeletonSpan[], left: number = 0) {const spanGroupLen = spanGroup.length;let preSpan;+for (let i = 0; i < spanGroupLen; i++) {const span = spanGroup[i];span.left = preSpan ? preSpan.left + preSpan.width : left;@@ -197,6 +200,7 @@ export function addSpanToDivide(setSpanGroupLeft(spanGroup, offsetLeft);+ // Set span parent pointer.for (const span of spanGroup) {span.parent = divide;}@@ -213,3 +217,22 @@ function _getMaxBoundingBox(span: IDocumentSkeletonSpan, bulletSkeleton: IDocume}return bulletSkeleton.bBox;}++export function hasMixedTextLayout(preSpan: Nullable<IDocumentSkeletonSpan>, span: IDocumentSkeletonSpan) {+ if (preSpan == null) {+ return false;+ }+ const { content: preContent } = preSpan;+ const { content: curContent } = span;++ if (preContent == null || curContent == null) {+ return false;+ }++ const ENG_NUMBERS_REG = /[a-z\d]/i;++ return (+ (ENG_NUMBERS_REG.test(preContent) && hasCJKText(curContent)) ||+ (hasCJKText(preContent) && ENG_NUMBERS_REG.test(curContent))+ );+}diff --git a/packages/engine-render/src/components/docs/common/tools.ts b/packages/engine-render/src/components/docs/common/tools.tsindex dc7ccd93ee..4e261895fc 100644--- a/packages/engine-render/src/components/docs/common/tools.ts+++ b/packages/engine-render/src/components/docs/common/tools.ts@@ -1,3 +1,4 @@+/* eslint-disable no-magic-numbers */import type {INumberUnit,IParagraphStyle,@@ -33,11 +34,11 @@ import type { DataStreamTreeNode } from '../view-model/data-stream-tree-node';import type { DocumentViewModel } from '../view-model/document-view-model';export function getLastPage(pages: IDocumentSkeletonPage[]) {- return pages?.[pages.length - 1];+ return pages[pages.length - 1];}export function getLastSection(page: IDocumentSkeletonPage) {- return page?.sections?.[page.sections.length - 1];+ return page.sections?.[page.sections.length - 1];}export function getLastColumn(page: IDocumentSkeletonPage) {@@ -56,8 +57,8 @@ export function getLastLineByColumn(column: IDocumentSkeletonColumn) {export function getPageContentWidth(page: IDocumentSkeletonPage) {const { pageWidth, marginLeft: pageMarginLeft, marginRight: pageMarginRight } = page;- const pageContentWidth = pageWidth - pageMarginLeft - pageMarginRight;- return pageContentWidth;++ return pageWidth - pageMarginLeft - pageMarginRight;}export function getPreLine(line: IDocumentSkeletonLine) {@@ -156,12 +157,12 @@ export function isBlankPage(page: IDocumentSkeletonPage) {}const section = getLastSection(page);-const columnsLen = section.columns.length;for (let i = 0; i < columnsLen; i++) {const column = section.columns[i];const state = isBlankColumn(column);+if (!state) {return false;}@@ -245,9 +246,7 @@ export function validationGrid(gridType = GridType.LINES, snapToGrid = BooleanNuexport function getLineHeightConfig(sectionBreakConfig: ISectionBreakConfig, paragraphConfig: IParagraphConfig) {const { paragraphStyle = {} } = paragraphConfig;-const { linePitch = 15.6, gridType = GridType.LINES, paragraphLineGapDefault = 0 } = sectionBreakConfig;-const { lineSpacing = 1, spacingRule = SpacingRule.AUTO, snapToGrid = BooleanNumber.TRUE } = paragraphStyle;return { paragraphLineGapDefault, linePitch, gridType, lineSpacing, spacingRule, snapToGrid };@@ -652,16 +651,18 @@ export function getPositionVertical(}}-export function getPositionHorizonBySpan(positionH: ObjectPositionH, span: IDocumentSkeletonSpan) {- const { relativeFrom, align, posOffset, percent } = positionH;-}+// export function getPositionHorizonBySpan(positionH: ObjectPositionH, span: IDocumentSkeletonSpan) {+// const { relativeFrom, align, posOffset, percent } = positionH;+// }export function getSpanGroupWidth(divide: IDocumentSkeletonDivide) {const spanGroup = divide.spanGroup;let width = 0;+for (const span of spanGroup) {width += span.width;}+return width;}diff --git a/packages/engine-render/src/components/docs/doc-skeleton.ts b/packages/engine-render/src/components/docs/doc-skeleton.tsindex 3a8d514c83..4b15dc11ba 100644--- a/packages/engine-render/src/components/docs/doc-skeleton.ts+++ b/packages/engine-render/src/components/docs/doc-skeleton.ts@@ -42,20 +42,17 @@ export enum DocumentSkeletonState {}export class DocumentSkeleton extends Skeleton {- // onRecalculateChangeObservable = new Observable<IDocumentSkeletonCached>();-- private _docViewModel!: DocumentViewModel;-private _skeletonData: Nullable<IDocumentSkeletonCached>;private _renderedBlockIdMap = new Map<string, boolean>();private _findLiquid: Liquid = new Liquid();- constructor(docViewModel: DocumentViewModel, localeService: LocaleService) {+ constructor(+ private _docViewModel: DocumentViewModel,+ localeService: LocaleService+ ) {super(localeService);-- this._docViewModel = docViewModel;}static create(docViewModel: DocumentViewModel, localeService: LocaleService) {@@ -72,6 +69,7 @@ export class DocumentSkeleton extends Skeleton {}this._skeletonData = this._createSkeleton(bounds);+ console.log(this._skeletonData);}getSkeletonData() {@@ -620,7 +618,7 @@ export class DocumentSkeleton extends Skeleton {);}- // 计算页内布局,block结构+ // 计算页内布局,block 结构const blockInfo = dealWithSections(bodyModel,sectionNode,@@ -630,7 +628,7 @@ export class DocumentSkeleton extends Skeleton {this._renderedBlockIdMap);- // todo: 当本节有多个列,且下一节为连续节类型的时候,需要按照列数分割,重新计算lines+ // todo: 当本节有多个列,且下一节为连续节类型的时候,需要按照列数分割,重新计算 linesif (sectionTypeNext === SectionType.CONTINUOUS && columnProperties.length > 0) {// TODO}diff --git a/packages/engine-render/src/components/docs/document.ts b/packages/engine-render/src/components/docs/document.tsindex e4b4bf449f..b6480d51b1 100644--- a/packages/engine-render/src/components/docs/document.ts+++ b/packages/engine-render/src/components/docs/document.ts@@ -379,8 +379,8 @@ export class Documents extends DocComponent {const spanPointWithFont = calculateRectRotate(originTranslate.addByPoint(- fixLineWidthByScale(spanLeft + maxLineAscSin + paddingLeft, scale),- fixLineWidthByScale(maxLineAscCos, scale)+ spanLeft + maxLineAscSin + paddingLeft,+ maxLineAscCos),centerPoint,centerAngle,@@ -426,9 +426,8 @@ export class Documents extends DocComponent {}changeSkeleton(newSkeleton: DocumentSkeleton) {- // this._disposeSkeletonChangeObserver(this.getSkeleton());this.setSkeleton(newSkeleton);- // this._addSkeletonChangeObserver(newSkeleton);+return this;}diff --git a/packages/engine-render/src/components/docs/view-model/document-view-model.ts b/packages/engine-render/src/components/docs/view-model/document-view-model.tsindex 2bdf9470c6..3e2b864e29 100644--- a/packages/engine-render/src/components/docs/view-model/document-view-model.ts+++ b/packages/engine-render/src/components/docs/view-model/document-view-model.ts@@ -29,6 +29,7 @@ export class DocumentViewModel implements IDisposable {}this.children = this._transformToTree(_documentDataModel.getBody()!.dataStream);+this._buildHeaderFooterViewModel();}@@ -216,6 +217,7 @@ export class DocumentViewModel implements IDisposable {const sectionBreak = sectionBreaks[i];if (sectionBreak.startIndex === index) {this._sectionBreakCurrentIndex = i;+return sectionBreak;}}@@ -376,11 +378,7 @@ export class DocumentViewModel implements IDisposable {if (char === DataStreamTreeTokenType.PARAGRAPH) {content += DataStreamTreeTokenType.PARAGRAPH;- const node = DataStreamTreeNode.create(- DataStreamTreeNodeType.PARAGRAPH,-- content- );+ const node = DataStreamTreeNode.create(DataStreamTreeNodeType.PARAGRAPH, content);// const isBullet = this._checkParagraphBullet(paragraphIndex);// const isIndent = isBullet === true ? true : this._checkParagraphIndent(paragraphIndex);