textBlock.ts 14 KB

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