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.

10.5 KB
Raw Blame
/**
 * 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 { IScale } from '@univerjs/core';
import type { IDocumentSkeletonGlyph } from '../../../basics/i-document-skeleton-cached';
import type { IBoundRectNoAngle } from '../../../basics/vector2';
import type { UniverRenderingContext } from '../../../context';
import type { IDrawInfo } from '../../extension';
import type { IDocumentLayoutTextDecoration } from '../document-layout-presentation';
import { BaselineOffset, BooleanNumber, TextDecoration } from '@univerjs/core';
import { COLOR_BLACK_RGB, DEFAULT_OFFSET_SPACING } from '../../../basics/const';
import { calculateRectRotate } from '../../../basics/draw';
import { GlyphType } from '../../../basics/i-document-skeleton-cached';
import { degToRad, getScale } from '../../../basics/tools';
import { Vector2 } from '../../../basics/vector2';
import { DocumentsSpanAndLineExtensionRegistry } from '../../extension';
import { docExtension } from '../doc-extension';
import { getColorStyleForCanvas } from '../layout/style/color';

const UNIQUE_KEY = 'DefaultDocsLineExtension';

const DOC_EXTENSION_Z_INDEX = 40;
export class Line extends docExtension {
    override uKey = UNIQUE_KEY;

    override Z_INDEX = DOC_EXTENSION_Z_INDEX;

    private _preBackgroundColor = '';

    override draw(
        ctx: UniverRenderingContext,
        parentScale: IScale,
        glyph: IDocumentSkeletonGlyph,
        _diff?: IBoundRectNoAngle,
        more?: IDrawInfo
    ) {
        const line = glyph.parent?.parent;
        const { ts: textStyle, bBox, content } = glyph;

        if (line == null || textStyle == null || content === '\r') {
            return;
        }

        const { asc, dsc } = line;
        const { sp: strikeoutPosition, spo, sbo, bd } = bBox;
        const scale = getScale(parentScale);
        const DELTA = 0.5;
        const { ul: underline, st: strikethrough, ol: overline, va: baselineOffset, bbl: bottomBorderLine } = textStyle;

        if (underline) {
            const originY = underline.offsetReference === 'baseline' ? asc : asc + dsc;
            const startY = originY + (underline.offset ?? 0);
            this._drawLine(ctx, glyph, underline, startY, scale, 1, more?.viewBound);
        }

        if (bottomBorderLine) {
            const startY = asc + dsc + 3;
            this._drawLine(ctx, glyph, bottomBorderLine, startY, scale, 2);
        }

        if (strikethrough) {
            // strikethrough position is the middle of bounding box ascent and descent.
            let startY = asc + bd - strikeoutPosition - DELTA;

            /**
             * --------- superscript strikethrough position -------
             * --------- superscript offset -----------------------
             * --------- baseline           -----------------------
             * --------- subscript strikethrough position ---------
             * --------- subscript offset   -----------------------
             */
            if (baselineOffset === BaselineOffset.SUPERSCRIPT) {
                startY -= spo;
            } else if (baselineOffset === BaselineOffset.SUBSCRIPT) {
                startY += sbo;
            }

            this._drawLine(ctx, glyph, strikethrough, startY, scale);
        }

        if (overline) {
            const startY = -DEFAULT_OFFSET_SPACING - DELTA;

            this._drawLine(ctx, glyph, overline, startY, scale);
        }
    }

    override clearCache() {
        this._preBackgroundColor = '';
    }

    private _drawLine(
        ctx: UniverRenderingContext,
        glyph: IDocumentSkeletonGlyph,
        line: IDocumentLayoutTextDecoration,
        startY: number,
        _scale: number,
        lineWidth = 1,
        viewBound?: IBoundRectNoAngle
    ) {
        let { s: show, cl: colorStyle, t: lineType, c = BooleanNumber.TRUE } = line;

        if (show !== BooleanNumber.TRUE) {
            return;
        }

        if (c == null) {
            c = BooleanNumber.TRUE;
        }

        const {
            originTranslate = Vector2.create(0, 0),
            alignOffset = Vector2.create(0, 0),
            renderConfig = {},
        } = this.extensionOffset;

        const isListMarker = glyph.glyphType === GlyphType.LIST;
        const left = glyph.left + (isListMarker ? glyph.xOffset : 0);
        const width = isListMarker ? glyph.bBox.width : glyph.width;
        const isAccounting = this._isAccounting(lineType);
        if (isAccounting && !this._isFirstAccountingGlyph(glyph)) {
            return;
        }
        const lineLeft = isAccounting ? (viewBound?.left ?? left) : left;
        const lineRight = isAccounting ? (viewBound?.right ?? left + width) : left + width;
        const lineAlignOffset = isAccounting ? Vector2.create(0, alignOffset.y) : alignOffset;

        const { centerAngle: centerAngleDeg = 0, vertexAngle: vertexAngleDeg = 0 } = renderConfig;

        ctx.save();

        // translate with precision is handled in moveToByPrecision and lineToByPrecision. NO NEED to do this again!
        // ctx.translateWithPrecision(FIX_ONE_PIXEL_BLUR_OFFSET, FIX_ONE_PIXEL_BLUR_OFFSET);

        const color =
            (c === BooleanNumber.TRUE ? getColorStyleForCanvas(glyph.ts?.cl) : getColorStyleForCanvas(colorStyle)) || COLOR_BLACK_RGB;
        ctx.strokeStyle = color;

        this._setLineType(ctx, lineType ?? TextDecoration.SINGLE, lineWidth);

        startY += this._isDouble(lineType) ? -0.8 : 0;

        const centerAngle = degToRad(centerAngleDeg);
        const vertexAngle = degToRad(vertexAngleDeg);
        const start = calculateRectRotate(
            originTranslate.addByPoint(lineLeft, startY),
            Vector2.create(0, 0),
            centerAngle,
            vertexAngle,
            lineAlignOffset
        );
        const end = calculateRectRotate(
            originTranslate.addByPoint(lineRight, startY),
            Vector2.create(0, 0),
            centerAngle,
            vertexAngle,
            lineAlignOffset
        );

        ctx.beginPath();
        ctx.moveTo(start.x, start.y);

        this._drawLineTo(ctx, start.x, end.x, end.y, lineType);
        if (this._isDouble(lineType)) {
            ctx.moveTo(start.x, start.y + 2);
            this._drawLineTo(ctx, start.x, end.x, end.y + 2, lineType);
        }

        ctx.stroke();
        ctx.restore();
    }

    private _drawLineTo(ctx: UniverRenderingContext, startX: number, endX: number, endY: number, lineType?: TextDecoration) {
        if (this._isWave(lineType)) {
            for (let x = startX; x < endX; x++) {
                ctx.lineTo(x, endY + 0.8 * Math.sin(x * 1)); // y + amplitude * frequency
            }
        } else {
            ctx.lineTo(endX, endY);
        }
    }

    private _setLineType(ctx: UniverRenderingContext, style: TextDecoration, lineWidth: number) {
        switch (style) {
            case TextDecoration.SINGLE:
            case TextDecoration.DOUBLE:
            case TextDecoration.SINGLE_ACCOUNTING:
            case TextDecoration.DOUBLE_ACCOUNTING:
                ctx.lineWidth = 1;
                ctx.setLineDash([0]);
                return;
            case TextDecoration.DOTTED:
                ctx.lineWidth = 1;
                ctx.setLineDash([2]);
                return;
            case TextDecoration.DOTTED_HEAVY:
                ctx.lineWidth = 2;
                ctx.setLineDash([2]);
                return;
            case TextDecoration.DASH:
                ctx.lineWidth = 1;
                ctx.setLineDash([3]);
                return;
            case TextDecoration.DASHED_HEAVY:
                ctx.lineWidth = 2;
                ctx.setLineDash([3]);
                return;
            case TextDecoration.DASH_LONG:
                ctx.lineWidth = 1;
                ctx.setLineDash([6]);
                return;
            case TextDecoration.DASH_LONG_HEAVY:
                ctx.lineWidth = 2;
                ctx.setLineDash([6]);
                return;
            case TextDecoration.DOT_DASH:
                ctx.lineWidth = 1;
                ctx.setLineDash([2, 5, 2]);
                return;
            case TextDecoration.DASH_DOT_HEAVY:
                ctx.lineWidth = 2;
                ctx.setLineDash([2, 5, 2]);
                return;
            case TextDecoration.DOT_DOT_DASH:
                ctx.lineWidth = 1;
                ctx.setLineDash([2, 2, 5, 2, 2]);
                return;
            case TextDecoration.DASH_DOT_DOT_HEAVY:
                ctx.lineWidth = 2;
                ctx.setLineDash([2, 2, 5, 2, 2]);
                return;
            case TextDecoration.THICK:
                ctx.lineWidth = 2;
                ctx.setLineDash([0]);
                return;
            case TextDecoration.WAVE:
            case TextDecoration.WAVY_DOUBLE:
                ctx.lineWidth = 1;
                return;
            case TextDecoration.WAVY_HEAVY:
                ctx.lineWidth = 2;
                return;
            default:
                ctx.setLineDash([0]);
                ctx.lineWidth = lineWidth;
        }
    }

    private _isWave(lineType?: TextDecoration): boolean {
        return lineType === TextDecoration.WAVE || lineType === TextDecoration.WAVY_HEAVY || lineType === TextDecoration.WAVY_DOUBLE;
    }

    private _isDouble(lineType?: TextDecoration): boolean {
        return lineType === TextDecoration.DOUBLE || lineType === TextDecoration.WAVY_DOUBLE || lineType === TextDecoration.DOUBLE_ACCOUNTING;
    }

    private _isAccounting(lineType?: TextDecoration): boolean {
        return lineType === TextDecoration.SINGLE_ACCOUNTING || lineType === TextDecoration.DOUBLE_ACCOUNTING;
    }

    private _isFirstAccountingGlyph(glyph: IDocumentSkeletonGlyph): boolean {
        const line = glyph.parent?.parent;
        for (const divide of line?.divides ?? []) {
            for (const candidate of divide.glyphGroup) {
                if (this._isAccounting(candidate.ts?.ul?.t)) {
                    return candidate === glyph;
                }
            }
        }
        return true;
    }
}

DocumentsSpanAndLineExtensionRegistry.add(new Line());