textBlock.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. import { Observable } from "babylonjs/Misc/observable";
  2. import { Measure } from "../measure";
  3. import { ValueAndUnit } from "../valueAndUnit";
  4. import { Control } from "./control";
  5. import { _TypeStore } from 'babylonjs/Misc/typeStore';
  6. import { Nullable } from 'babylonjs/types';
  7. /**
  8. * Enum that determines the text-wrapping mode to use.
  9. */
  10. export enum TextWrapping {
  11. /**
  12. * Clip the text when it's larger than Control.width; this is the default mode.
  13. */
  14. Clip = 0,
  15. /**
  16. * Wrap the text word-wise, i.e. try to add line-breaks at word boundary to fit within Control.width.
  17. */
  18. WordWrap = 1,
  19. /**
  20. * Ellipsize the text, i.e. shrink with trailing … when text is larger than Control.width.
  21. */
  22. Ellipsis,
  23. }
  24. /**
  25. * Class used to create text block control
  26. */
  27. export class TextBlock extends Control {
  28. private _text = "";
  29. private _textWrapping = TextWrapping.Clip;
  30. private _textHorizontalAlignment = Control.HORIZONTAL_ALIGNMENT_CENTER;
  31. private _textVerticalAlignment = Control.VERTICAL_ALIGNMENT_CENTER;
  32. private _lines: any[];
  33. private _resizeToFit: boolean = false;
  34. private _lineSpacing: ValueAndUnit = new ValueAndUnit(0);
  35. private _outlineWidth: number = 0;
  36. private _outlineColor: string = "white";
  37. /**
  38. * An event triggered after the text is changed
  39. */
  40. public onTextChangedObservable = new Observable<TextBlock>();
  41. /**
  42. * An event triggered after the text was broken up into lines
  43. */
  44. public onLinesReadyObservable = new Observable<TextBlock>();
  45. /**
  46. * Return the line list (you may need to use the onLinesReadyObservable to make sure the list is ready)
  47. */
  48. public get lines(): any[] {
  49. return this._lines;
  50. }
  51. /**
  52. * Gets or sets an boolean indicating that the TextBlock will be resized to fit container
  53. */
  54. public get resizeToFit(): boolean {
  55. return this._resizeToFit;
  56. }
  57. /**
  58. * Gets or sets an boolean indicating that the TextBlock will be resized to fit container
  59. */
  60. public set resizeToFit(value: boolean) {
  61. if (this._resizeToFit === value) {
  62. return;
  63. }
  64. this._resizeToFit = value;
  65. if (this._resizeToFit) {
  66. this._width.ignoreAdaptiveScaling = true;
  67. this._height.ignoreAdaptiveScaling = true;
  68. }
  69. this._markAsDirty();
  70. }
  71. /**
  72. * Gets or sets a boolean indicating if text must be wrapped
  73. */
  74. public get textWrapping(): TextWrapping | boolean {
  75. return this._textWrapping;
  76. }
  77. /**
  78. * Gets or sets a boolean indicating if text must be wrapped
  79. */
  80. public set textWrapping(value: TextWrapping | boolean) {
  81. if (this._textWrapping === value) {
  82. return;
  83. }
  84. this._textWrapping = +value;
  85. this._markAsDirty();
  86. }
  87. /**
  88. * Gets or sets text to display
  89. */
  90. public get text(): string {
  91. return this._text;
  92. }
  93. /**
  94. * Gets or sets text to display
  95. */
  96. public set text(value: string) {
  97. if (this._text === value) {
  98. return;
  99. }
  100. this._text = value;
  101. this._markAsDirty();
  102. this.onTextChangedObservable.notifyObservers(this);
  103. }
  104. /**
  105. * Gets or sets text horizontal alignment (BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER by default)
  106. */
  107. public get textHorizontalAlignment(): number {
  108. return this._textHorizontalAlignment;
  109. }
  110. /**
  111. * Gets or sets text horizontal alignment (BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER by default)
  112. */
  113. public set textHorizontalAlignment(value: number) {
  114. if (this._textHorizontalAlignment === value) {
  115. return;
  116. }
  117. this._textHorizontalAlignment = value;
  118. this._markAsDirty();
  119. }
  120. /**
  121. * Gets or sets text vertical alignment (BABYLON.GUI.Control.VERTICAL_ALIGNMENT_CENTER by default)
  122. */
  123. public get textVerticalAlignment(): number {
  124. return this._textVerticalAlignment;
  125. }
  126. /**
  127. * Gets or sets text vertical alignment (BABYLON.GUI.Control.VERTICAL_ALIGNMENT_CENTER by default)
  128. */
  129. public set textVerticalAlignment(value: number) {
  130. if (this._textVerticalAlignment === value) {
  131. return;
  132. }
  133. this._textVerticalAlignment = value;
  134. this._markAsDirty();
  135. }
  136. /**
  137. * Gets or sets line spacing value
  138. */
  139. public set lineSpacing(value: string | number) {
  140. if (this._lineSpacing.fromString(value)) {
  141. this._markAsDirty();
  142. }
  143. }
  144. /**
  145. * Gets or sets line spacing value
  146. */
  147. public get lineSpacing(): string | number {
  148. return this._lineSpacing.toString(this._host);
  149. }
  150. /**
  151. * Gets or sets outlineWidth of the text to display
  152. */
  153. public get outlineWidth(): number {
  154. return this._outlineWidth;
  155. }
  156. /**
  157. * Gets or sets outlineWidth of the text to display
  158. */
  159. public set outlineWidth(value: number) {
  160. if (this._outlineWidth === value) {
  161. return;
  162. }
  163. this._outlineWidth = value;
  164. this._markAsDirty();
  165. }
  166. /**
  167. * Gets or sets outlineColor of the text to display
  168. */
  169. public get outlineColor(): string {
  170. return this._outlineColor;
  171. }
  172. /**
  173. * Gets or sets outlineColor of the text to display
  174. */
  175. public set outlineColor(value: string) {
  176. if (this._outlineColor === value) {
  177. return;
  178. }
  179. this._outlineColor = value;
  180. this._markAsDirty();
  181. }
  182. /**
  183. * Creates a new TextBlock object
  184. * @param name defines the name of the control
  185. * @param text defines the text to display (emptry string by default)
  186. */
  187. constructor(
  188. /**
  189. * Defines the name of the control
  190. */
  191. public name?: string,
  192. text: string = "") {
  193. super(name);
  194. this.text = text;
  195. }
  196. protected _getTypeName(): string {
  197. return "TextBlock";
  198. }
  199. protected _processMeasures(parentMeasure: Measure, context: CanvasRenderingContext2D): void {
  200. if (!this._fontOffset) {
  201. this._fontOffset = Control._GetFontOffset(context.font);
  202. }
  203. super._processMeasures(parentMeasure, context);
  204. // Prepare lines
  205. this._lines = this._breakLines(this._currentMeasure.width, context);
  206. this.onLinesReadyObservable.notifyObservers(this);
  207. let maxLineWidth: number = 0;
  208. for (let i = 0; i < this._lines.length; i++) {
  209. const line = this._lines[i];
  210. if (line.width > maxLineWidth) {
  211. maxLineWidth = line.width;
  212. }
  213. }
  214. if (this._resizeToFit) {
  215. if (this._textWrapping === TextWrapping.Clip) {
  216. let newWidth = this.paddingLeftInPixels + this.paddingRightInPixels + maxLineWidth;
  217. if (newWidth !== this._width.internalValue) {
  218. this._width.updateInPlace(newWidth, ValueAndUnit.UNITMODE_PIXEL);
  219. this._rebuildLayout = true;
  220. }
  221. }
  222. let newHeight = this.paddingTopInPixels + this.paddingBottomInPixels + this._fontOffset.height * this._lines.length;
  223. if (this._lines.length > 0 && this._lineSpacing.internalValue !== 0) {
  224. let lineSpacing = 0;
  225. if (this._lineSpacing.isPixel) {
  226. lineSpacing = this._lineSpacing.getValue(this._host);
  227. } else {
  228. lineSpacing = (this._lineSpacing.getValue(this._host) * this._height.getValueInPixel(this._host, this._cachedParentMeasure.height));
  229. }
  230. newHeight += (this._lines.length - 1) * lineSpacing;
  231. }
  232. if (newHeight !== this._height.internalValue) {
  233. this._height.updateInPlace(newHeight, ValueAndUnit.UNITMODE_PIXEL);
  234. this._rebuildLayout = true;
  235. }
  236. }
  237. }
  238. private _drawText(text: string, textWidth: number, y: number, context: CanvasRenderingContext2D): void {
  239. var width = this._currentMeasure.width;
  240. var x = 0;
  241. switch (this._textHorizontalAlignment) {
  242. case Control.HORIZONTAL_ALIGNMENT_LEFT:
  243. x = 0;
  244. break;
  245. case Control.HORIZONTAL_ALIGNMENT_RIGHT:
  246. x = width - textWidth;
  247. break;
  248. case Control.HORIZONTAL_ALIGNMENT_CENTER:
  249. x = (width - textWidth) / 2;
  250. break;
  251. }
  252. if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) {
  253. context.shadowColor = this.shadowColor;
  254. context.shadowBlur = this.shadowBlur;
  255. context.shadowOffsetX = this.shadowOffsetX;
  256. context.shadowOffsetY = this.shadowOffsetY;
  257. }
  258. if (this.outlineWidth) {
  259. context.strokeText(text, this._currentMeasure.left + x, y);
  260. }
  261. context.fillText(text, this._currentMeasure.left + x, y);
  262. }
  263. /** @hidden */
  264. public _draw(context: CanvasRenderingContext2D, invalidatedRectangle?: Nullable<Measure>): void {
  265. context.save();
  266. this._applyStates(context);
  267. // Render lines
  268. this._renderLines(context);
  269. context.restore();
  270. }
  271. protected _applyStates(context: CanvasRenderingContext2D): void {
  272. super._applyStates(context);
  273. if (this.outlineWidth) {
  274. context.lineWidth = this.outlineWidth;
  275. context.strokeStyle = this.outlineColor;
  276. }
  277. }
  278. protected _breakLines(refWidth: number, context: CanvasRenderingContext2D): object[] {
  279. var lines = [];
  280. var _lines = this.text.split("\n");
  281. if (this._textWrapping === TextWrapping.Ellipsis) {
  282. for (var _line of _lines) {
  283. lines.push(this._parseLineEllipsis(_line, refWidth, context));
  284. }
  285. } else if (this._textWrapping === TextWrapping.WordWrap) {
  286. for (var _line of _lines) {
  287. lines.push(...this._parseLineWordWrap(_line, refWidth, context));
  288. }
  289. } else {
  290. for (var _line of _lines) {
  291. lines.push(this._parseLine(_line, context));
  292. }
  293. }
  294. return lines;
  295. }
  296. protected _parseLine(line: string = '', context: CanvasRenderingContext2D): object {
  297. return { text: line, width: context.measureText(line).width };
  298. }
  299. protected _parseLineEllipsis(line: string = '', width: number,
  300. context: CanvasRenderingContext2D): object {
  301. var lineWidth = context.measureText(line).width;
  302. if (lineWidth > width) {
  303. line += '…';
  304. }
  305. while (line.length > 2 && lineWidth > width) {
  306. line = line.slice(0, -2) + '…';
  307. lineWidth = context.measureText(line).width;
  308. }
  309. return { text: line, width: lineWidth };
  310. }
  311. protected _parseLineWordWrap(line: string = '', width: number,
  312. context: CanvasRenderingContext2D): object[] {
  313. var lines = [];
  314. var words = line.split(' ');
  315. var lineWidth = 0;
  316. for (var n = 0; n < words.length; n++) {
  317. var testLine = n > 0 ? line + " " + words[n] : words[0];
  318. var metrics = context.measureText(testLine);
  319. var testWidth = metrics.width;
  320. if (testWidth > width && n > 0) {
  321. lines.push({ text: line, width: lineWidth });
  322. line = words[n];
  323. lineWidth = context.measureText(line).width;
  324. }
  325. else {
  326. lineWidth = testWidth;
  327. line = testLine;
  328. }
  329. }
  330. lines.push({ text: line, width: lineWidth });
  331. return lines;
  332. }
  333. protected _renderLines(context: CanvasRenderingContext2D): void {
  334. var height = this._currentMeasure.height;
  335. var rootY = 0;
  336. switch (this._textVerticalAlignment) {
  337. case Control.VERTICAL_ALIGNMENT_TOP:
  338. rootY = this._fontOffset.ascent;
  339. break;
  340. case Control.VERTICAL_ALIGNMENT_BOTTOM:
  341. rootY = height - this._fontOffset.height * (this._lines.length - 1) - this._fontOffset.descent;
  342. break;
  343. case Control.VERTICAL_ALIGNMENT_CENTER:
  344. rootY = this._fontOffset.ascent + (height - this._fontOffset.height * this._lines.length) / 2;
  345. break;
  346. }
  347. rootY += this._currentMeasure.top;
  348. for (let i = 0; i < this._lines.length; i++) {
  349. const line = this._lines[i];
  350. if (i !== 0 && this._lineSpacing.internalValue !== 0) {
  351. if (this._lineSpacing.isPixel) {
  352. rootY += this._lineSpacing.getValue(this._host);
  353. } else {
  354. rootY = rootY + (this._lineSpacing.getValue(this._host) * this._height.getValueInPixel(this._host, this._cachedParentMeasure.height));
  355. }
  356. }
  357. this._drawText(line.text, line.width, rootY, context);
  358. rootY += this._fontOffset.height;
  359. }
  360. }
  361. /**
  362. * Given a width constraint applied on the text block, find the expected height
  363. * @returns expected height
  364. */
  365. public computeExpectedHeight(): number {
  366. if (this.text && this.widthInPixels) {
  367. const context = document.createElement('canvas').getContext('2d');
  368. if (context) {
  369. this._applyStates(context);
  370. if (!this._fontOffset) {
  371. this._fontOffset = Control._GetFontOffset(context.font);
  372. }
  373. const lines = this._lines ? this._lines : this._breakLines(
  374. this.widthInPixels - this.paddingLeftInPixels - this.paddingRightInPixels, context);
  375. let newHeight = this.paddingTopInPixels + this.paddingBottomInPixels + this._fontOffset.height * lines.length;
  376. if (lines.length > 0 && this._lineSpacing.internalValue !== 0) {
  377. let lineSpacing = 0;
  378. if (this._lineSpacing.isPixel) {
  379. lineSpacing = this._lineSpacing.getValue(this._host);
  380. } else {
  381. lineSpacing = (this._lineSpacing.getValue(this._host) * this._height.getValueInPixel(this._host, this._cachedParentMeasure.height));
  382. }
  383. newHeight += (lines.length - 1) * lineSpacing;
  384. }
  385. return newHeight;
  386. }
  387. }
  388. return 0;
  389. }
  390. dispose(): void {
  391. super.dispose();
  392. this.onTextChangedObservable.clear();
  393. }
  394. }
  395. _TypeStore.RegisteredTypes["BABYLON.GUI.TextBlock"] = TextBlock;