import { Inject, Injectable, } from '@angular/core'; import { DOCUMENT, } from '@angular/common'; @Injectable() export class AutoNewLineService { public canvas: HTMLCanvasElement; private _lineSeparator = '\n'; private _spaceCharacter = ' '; constructor( @Inject(DOCUMENT) private _document: Document, ) {} public getTextWidth( text: string, fontSize: string, fontFamily: string, ) { this.canvas = this.canvas ? this.canvas : this._document.createElement('canvas'); const context = this.canvas.getContext('2d'); const fontSizeAsShown = parseInt(fontSize, 10); context.font = ( `${fontSizeAsShown}pt ${fontFamily}` ); const metrics = context.measureText(text); return metrics.width; } public sortIntoLines( text: string, elementWidth: number, fontSize: string, fontFamily: string, ) { const lines = text.split(this._lineSeparator); const newLinesArray: string[] = []; let overflow = ''; while (lines.length || overflow.length) { let lastChar = ''; let line = lines.length > 0 ? lines.shift() : ''; line = overflow + line; overflow = ''; while ( this.getTextWidth( line, fontSize, fontFamily, ) > elementWidth ) { const lineSplit = line.split(this._spaceCharacter); if (lineSplit.length > 1) { overflow = lineSplit.pop() + this._spaceCharacter + overflow; line = lineSplit.join(this._spaceCharacter); } else { lastChar = line.charAt(line.length - 1); line = line.substring(0, line.length - 1); overflow = lastChar + overflow; } } newLinesArray.push(line); } return newLinesArray.join(this._lineSeparator).trim(); } }