PropertyLine.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. import { Nullable } from "babylonjs";
  2. import { BasicElement } from "../gui/BasicElement";
  3. import { ColorPickerElement } from "../gui/ColorPickerElement";
  4. import { CubeTextureElement } from "../gui/CubeTextureElement";
  5. import { HDRCubeTextureElement } from "../gui/HDRCubeTextureElement";
  6. import { TextureElement } from "../gui/TextureElement";
  7. import { Helpers } from "../helpers/Helpers";
  8. import { PROPERTIES } from "../properties";
  9. import { Scheduler } from "../scheduler/Scheduler";
  10. import { Property } from "./Property";
  11. export class PropertyFormatter {
  12. /**
  13. * Format the value of the given property of the given object.
  14. */
  15. public static format(obj: any, prop: string): string {
  16. // Get original value;
  17. let value = obj[prop];
  18. // test if type PrimitiveAlignment is available (only included in canvas2d)
  19. return value;
  20. }
  21. }
  22. /**
  23. * A property line represents a line in the detail panel. This line is composed of :
  24. * - a name (the property name)
  25. * - a value if this property is of a type 'simple' : string, number, boolean, color, texture
  26. * - the type of the value if this property is of a complex type (Vector2, Size, ...)
  27. * - a ID if defined (otherwise an empty string is displayed)
  28. * The original object is sent to the value object who will update it at will.
  29. *
  30. * A property line can contain OTHER property line objects in the case of a complex type.
  31. * If this instance has no link to other instances, its type is ALWAYS a simple one (see above).
  32. *
  33. */
  34. export class PropertyLine {
  35. // The property can be of any type (Property internally can have any type), relative to this._obj
  36. private _property: Property;
  37. //The HTML element corresponding to this line
  38. private _div: HTMLElement;
  39. // The div containing the value to display. Used to update dynamically the property
  40. private _valueDiv: HTMLElement;
  41. // If the type is complex, this property will have child to update
  42. private _children: Array<PropertyLine> = [];
  43. // Array representing the simple type. All others are considered 'complex'
  44. private static _SIMPLE_TYPE = ['number', 'string', 'boolean'];
  45. // The number of pixel at each children step
  46. private static _MARGIN_LEFT = 15;
  47. // The margin-left used to display to row
  48. private _level: number;
  49. /** The list of viewer element displayed at the end of the line (color, texture...) */
  50. private _elements: Array<BasicElement> = [];
  51. /** The property parent of this one. Used to update the value of this property and to retrieve the correct object */
  52. private _parent: Nullable<PropertyLine>;
  53. /** The input element to display if this property is 'simple' in order to update it */
  54. private _input: HTMLInputElement;
  55. /** Display input handler (stored to be removed afterwards) */
  56. private _displayInputHandler: EventListener;
  57. /** Handler used to validate the input by pressing 'enter' */
  58. private _validateInputHandler: EventListener;
  59. /** Handler used to validate the input by pressing 'esc' */
  60. private _escapeInputHandler: EventListener;
  61. /** Handler used on focus out */
  62. private _focusOutInputHandler: EventListener;
  63. /** Handler used to get mouse position */
  64. private _onMouseDownHandler: EventListener;
  65. private _onMouseDragHandler: EventListener;
  66. private _onMouseUpHandler: EventListener;
  67. private _textValue: HTMLElement;
  68. /** Save previous Y mouse position */
  69. private _prevY: number;
  70. /**Save value while slider is on */
  71. private _preValue: number;
  72. constructor(prop: Property, parent: Nullable<PropertyLine> = null, level: number = 0) {
  73. this._property = prop;
  74. this._level = level;
  75. this._parent = parent;
  76. this._div = Helpers.CreateDiv('row');
  77. this._div.style.marginLeft = `${this._level}px`;
  78. // Property name
  79. let propName: HTMLElement = Helpers.CreateDiv('prop-name', this._div);
  80. propName.textContent = `${this.name}`;
  81. // Value
  82. this._valueDiv = Helpers.CreateDiv('prop-value', this._div);
  83. if (typeof this.value !== 'boolean' && !this._isSliderType()) {
  84. this._valueDiv.textContent = this._displayValueContent() || '-'; // Init value text node
  85. }
  86. this._createElements();
  87. for (let elem of this._elements) {
  88. this._valueDiv.appendChild(elem.toHtml());
  89. }
  90. this._updateValue();
  91. // If the property type is not simple, add click event to unfold its children
  92. if (typeof this.value === 'boolean') {
  93. this._checkboxInput();
  94. } else if (this._isSliderType()) {
  95. this._rangeInput();
  96. } else if (!this._isSimple()) {
  97. this._valueDiv.classList.add('clickable');
  98. this._valueDiv.addEventListener('click', this._addDetails.bind(this));
  99. } else {
  100. this._initInput();
  101. this._valueDiv.addEventListener('click', this._displayInputHandler);
  102. this._input.addEventListener('focusout', this._focusOutInputHandler);
  103. this._input.addEventListener('keydown', this._validateInputHandler);
  104. this._input.addEventListener('keydown', this._escapeInputHandler);
  105. }
  106. // Add this property to the scheduler
  107. Scheduler.getInstance().add(this);
  108. }
  109. /**
  110. * Init the input element and al its handler :
  111. * - a click in the window remove the input and restore the old property value
  112. * - enters updates the property
  113. */
  114. private _initInput() {
  115. // Create the input element
  116. this._input = document.createElement('input') as HTMLInputElement;
  117. this._input.setAttribute('type', 'text');
  118. // if the property is 'simple', add an event listener to create an input
  119. this._displayInputHandler = this._displayInput.bind(this);
  120. this._validateInputHandler = this._validateInput.bind(this);
  121. this._escapeInputHandler = this._escapeInput.bind(this);
  122. this._focusOutInputHandler = this.update.bind(this);
  123. this._onMouseDownHandler = this._onMouseDown.bind(this);
  124. this._onMouseDragHandler = this._onMouseDrag.bind(this);
  125. this._onMouseUpHandler = this._onMouseUp.bind(this);
  126. }
  127. /**
  128. * On enter : validates the new value and removes the input
  129. * On escape : removes the input
  130. */
  131. private _validateInput(e: KeyboardEvent) {
  132. this._input.removeEventListener('focusout', this._focusOutInputHandler);
  133. if (e.keyCode == 13) { // Enter
  134. this.validateInput(this._input.value);
  135. } else if (e.keyCode == 9) { // Tab
  136. e.preventDefault();
  137. this.validateInput(this._input.value);
  138. } else if (e.keyCode == 27) { // Esc : remove input
  139. this.update();
  140. }
  141. }
  142. public validateInput(value: any, forceupdate: boolean = true): void {
  143. this.updateObject();
  144. if (typeof this._property.value === 'number') {
  145. this._property.value = parseFloat(value);
  146. } else {
  147. this._property.value = value;
  148. }
  149. // Remove input
  150. if (forceupdate) {
  151. this.update();
  152. // resume scheduler
  153. Scheduler.getInstance().pause = false;
  154. }
  155. }
  156. /**
  157. * On escape : removes the input
  158. */
  159. private _escapeInput(e: KeyboardEvent) {
  160. // Remove focus out handler
  161. this._input.removeEventListener('focusout', this._focusOutInputHandler);
  162. if (e.keyCode == 27) {
  163. // Esc : remove input
  164. this.update();
  165. }
  166. }
  167. /** Removes the input without validating the new value */
  168. private _removeInputWithoutValidating() {
  169. Helpers.CleanDiv(this._valueDiv);
  170. if (typeof this.value !== 'boolean' && !this._isSliderType()) {
  171. this._valueDiv.textContent = "-";
  172. }
  173. // restore elements
  174. for (let elem of this._elements) {
  175. this._valueDiv.appendChild(elem.toHtml());
  176. }
  177. if (typeof this.value !== 'boolean' && !this._isSliderType()) {
  178. this._valueDiv.addEventListener('click', this._displayInputHandler);
  179. }
  180. }
  181. /** Replaces the default display with an input */
  182. private _displayInput(e: any) {
  183. // Remove the displayInput event listener
  184. this._valueDiv.removeEventListener('click', this._displayInputHandler);
  185. // Set input value
  186. let valueTxt = this._valueDiv.textContent;
  187. this._valueDiv.textContent = "";
  188. this._input.value = valueTxt || "";
  189. this._valueDiv.appendChild(this._input);
  190. this._input.focus();
  191. if (typeof this.value !== 'boolean' && !this._isSliderType()) {
  192. this._input.addEventListener('focusout', this._focusOutInputHandler);
  193. } else if (typeof this.value === 'number') {
  194. this._input.addEventListener('mousedown', this._onMouseDownHandler);
  195. }
  196. // Pause the scheduler
  197. Scheduler.getInstance().pause = true;
  198. }
  199. /** Retrieve the correct object from its parent.
  200. * If no parent exists, returns the property value.
  201. * This method is used at each update in case the property object is removed from the original object
  202. * (example : mesh.position = new Vector3 ; the original vector3 object is deleted from the mesh).
  203. */
  204. public updateObject() {
  205. if (this._parent) {
  206. this._property.obj = this._parent.updateObject();
  207. }
  208. return this._property.value;
  209. }
  210. // Returns the property name
  211. public get name(): string {
  212. // let arrayName = Helpers.Capitalize(this._property.name).match(/[A-Z][a-z]+|[0-9]+/g)
  213. // if (arrayName) {
  214. // return arrayName.join(" ");
  215. // }
  216. return this._property.name;
  217. }
  218. // Returns the value of the property
  219. public get value(): any {
  220. return PropertyFormatter.format(this._property.obj, this._property.name);
  221. }
  222. // Returns the type of the property
  223. public get type(): string {
  224. return this._property.type;
  225. }
  226. /**
  227. * Creates elements that wil be displayed on a property line, depending on the
  228. * type of the property.
  229. */
  230. private _createElements() {
  231. // Colors
  232. if (this.type == 'Color3' || this.type == 'Color4') {
  233. if (!Helpers.IsBrowserIE()) {
  234. this._elements.push(new ColorPickerElement(this.value, this));
  235. }
  236. }
  237. // Texture
  238. if (this.type == 'Texture') {
  239. this._elements.push(new TextureElement(this.value));
  240. }
  241. // HDR Texture
  242. if (this.type == 'HDRCubeTexture') {
  243. this._elements.push(new HDRCubeTextureElement(this.value));
  244. }
  245. if (this.type == 'CubeTexture') {
  246. this._elements.push(new CubeTextureElement(this.value));
  247. }
  248. }
  249. // Returns the text displayed on the left of the property name :
  250. // - If the type is simple, display its value
  251. // - If the type is complex, but instance of Vector2, Size, display the type and its tostring
  252. // - If the type is another one, display the Type
  253. private _displayValueContent() {
  254. let value = this.value;
  255. // If the value is a number, truncate it if needed
  256. if (typeof value === 'number') {
  257. return Helpers.Trunc(value);
  258. }
  259. // If it's a string or a boolean, display its value
  260. if (typeof value === 'string' || typeof value === 'boolean') {
  261. return value;
  262. }
  263. return PROPERTIES.format(value);
  264. }
  265. /** Delete properly this property line.
  266. * Removes itself from the scheduler.
  267. * Dispose all viewer element (color, texture...)
  268. */
  269. public dispose() {
  270. Scheduler.getInstance().remove(this);
  271. for (let child of this._children) {
  272. Scheduler.getInstance().remove(child);
  273. }
  274. for (let elem of this._elements) {
  275. elem.dispose();
  276. }
  277. this._elements = [];
  278. }
  279. /** Updates the content of _valueDiv with the value of the property,
  280. * and all HTML element correpsonding to this type.
  281. * Elements are updated as well
  282. */
  283. private _updateValue() {
  284. // Update the property object first
  285. this.updateObject();
  286. // Then update its value
  287. // this._valueDiv.textContent = " "; // TOFIX this removes the elements after
  288. if (typeof this.value === 'boolean') {
  289. this._checkboxInput();
  290. } else if (this._isSliderType()) { // Add slider when parent have slider property
  291. this._rangeInput();
  292. } else {
  293. this._valueDiv.childNodes[0].nodeValue = this._displayValueContent();
  294. //Doing the Hexa convertion
  295. if ((this._property.type == "Color3" && this._children.length == 5 && this._children[1].value == true) || (this._property.type == "Color4" && this._children.length == 6 && this._children[1].value == true)) {
  296. if (this._children[0] != undefined && this._children[0].name == "hex") {
  297. let hexLineString = this._children[0].value;
  298. let rValue = (parseInt((hexLineString.slice(1, 3)), 16)) * (1 / 255);
  299. let rValueRound = Math.round(100 * rValue) / 100;
  300. this.value.r = rValueRound;
  301. let gValue = (parseInt((hexLineString.slice(3, 5)), 16)) * (1 / 255);
  302. let gValueRound = Math.round(100 * gValue) / 100;
  303. this.value.g = gValueRound;
  304. let bValue = (parseInt((hexLineString.slice(5, 7)), 16)) * (1 / 255);
  305. let bValueRound = Math.round(100 * bValue) / 100;
  306. this.value.b = bValueRound;
  307. if (this._children[2].name == "a") {
  308. let aValue = (parseInt((hexLineString.slice(7, 9)), 16)) * (1 / 255);
  309. let aValueRound = Math.round(100 * aValue) / 100;
  310. this.value.a = aValueRound;
  311. }
  312. }
  313. } else if (this._property.type == "Color3" || this._property.type == "Color4") {
  314. if (this._property.value.hex != undefined && this._property.value.hex != null) {
  315. let hexLineInfos = [];
  316. let valHexR = ((this._property.value.r * 255) | 0).toString(16);
  317. hexLineInfos.push(valHexR);
  318. if (valHexR == "0") {
  319. hexLineInfos.push("0");
  320. }
  321. let valHexG = ((this._property.value.g * 255) | 0).toString(16);
  322. hexLineInfos.push(valHexG);
  323. if (valHexG == "0") {
  324. hexLineInfos.push("0");
  325. }
  326. let valHexB = ((this._property.value.b * 255) | 0).toString(16);
  327. hexLineInfos.push(valHexB);
  328. if (valHexB == "0") {
  329. hexLineInfos.push("0");
  330. }
  331. if (this._property.value.a != undefined) {
  332. let valHexA = ((this._property.value.a * 255) | 0).toString(16);
  333. hexLineInfos.push(valHexA);
  334. if (valHexA == "0") {
  335. hexLineInfos.push("0");
  336. }
  337. }
  338. hexLineInfos.unshift("#");
  339. let hexLineString = hexLineInfos.join("");
  340. this._property.value.hex = hexLineString;
  341. hexLineInfos.length = 0;
  342. }
  343. }
  344. }
  345. for (let elem of this._elements) {
  346. elem.update(this.value);
  347. }
  348. }
  349. /**
  350. * Update the property division with the new property value.
  351. * If this property is complex, update its child, otherwise update its text content
  352. */
  353. public update() {
  354. this._removeInputWithoutValidating();
  355. this._updateValue();
  356. }
  357. /**
  358. * Returns true if the type of this property is simple, false otherwise.
  359. * Returns true if the value is null
  360. */
  361. private _isSimple(): boolean {
  362. if (this.value != null && this.type !== 'type_not_defined') {
  363. if (PropertyLine._SIMPLE_TYPE.indexOf(this.type) == -1) {
  364. // complex type : return the type name
  365. return false;
  366. } else {
  367. // simple type : return value
  368. return true;
  369. }
  370. } else {
  371. return true;
  372. }
  373. }
  374. public toHtml(): HTMLElement {
  375. return this._div;
  376. }
  377. public closeDetails() {
  378. if (this._div.classList.contains('unfolded')) {
  379. // Remove class unfolded
  380. this._div.classList.remove('unfolded');
  381. // remove html children
  382. if (this._div.parentNode) {
  383. for (let child of this._children) {
  384. this._div.parentNode.removeChild(child.toHtml());
  385. }
  386. }
  387. }
  388. }
  389. /**
  390. * Add sub properties in case of a complex type
  391. */
  392. private _addDetails() {
  393. if (this._div.classList.contains('unfolded')) {
  394. // Remove class unfolded
  395. this._div.classList.remove('unfolded');
  396. // remove html children
  397. if (this._div.parentNode) {
  398. for (let child of this._children) {
  399. this._div.parentNode.removeChild(child.toHtml());
  400. }
  401. }
  402. } else {
  403. // if children does not exists, generate it
  404. this._div.classList.toggle('unfolded');
  405. if (this._children.length == 0) {
  406. let objToDetail = this.value;
  407. // Display all properties that are not functions
  408. let propToDisplay = Helpers.GetAllLinesPropertiesAsString(objToDetail);
  409. // special case for color3
  410. if ((propToDisplay.indexOf('r') && propToDisplay.indexOf('g') && propToDisplay.indexOf('b')) == 0) {
  411. propToDisplay.sort();
  412. } else {
  413. propToDisplay.sort().reverse();
  414. }
  415. for (let prop of propToDisplay) {
  416. let infos = new Property(prop, this._property.value, this._property.obj);
  417. let child = new PropertyLine(infos, this, this._level + PropertyLine._MARGIN_LEFT);
  418. this._children.push(child);
  419. }
  420. //Add the Hexa converter
  421. if ((propToDisplay.indexOf('r') && propToDisplay.indexOf('g') && propToDisplay.indexOf('b') && propToDisplay.indexOf('a')) == 0) {
  422. let hexLineInfos = [];
  423. let hexLinePropCheck = new Property("hexEnable", this._property.value, this._property.obj);
  424. hexLinePropCheck.value = false;
  425. let hexLineCheck = new PropertyLine(hexLinePropCheck, this, this._level + PropertyLine._MARGIN_LEFT);
  426. this._children.unshift(hexLineCheck);
  427. for (let prop of propToDisplay) {
  428. let infos = new Property(prop, this._property.value, this._property.obj);
  429. let valHex = ((infos.value * 255) | 0).toString(16);
  430. hexLineInfos.push(valHex);
  431. if (valHex == "0") {
  432. hexLineInfos.push("0");
  433. }
  434. }
  435. hexLineInfos.push("#");
  436. hexLineInfos.reverse();
  437. let hexLineString = hexLineInfos.join("");
  438. let hexLineProp = new Property("hex", this._property.value, this._property.obj);
  439. hexLineProp.value = hexLineString;
  440. let hexLine = new PropertyLine(hexLineProp, this, this._level + PropertyLine._MARGIN_LEFT);
  441. this._children.unshift(hexLine);
  442. }
  443. }
  444. // otherwise display it
  445. if (this._div.parentNode) {
  446. for (let child of this._children) {
  447. this._div.parentNode.insertBefore(child.toHtml(), this._div.nextSibling);
  448. }
  449. }
  450. }
  451. }
  452. /**
  453. * Refresh mouse position on y axis
  454. * @param e
  455. */
  456. private _onMouseDrag(e: MouseEvent): void {
  457. const diff = this._prevY - e.clientY;
  458. this._input.value = (this._preValue + diff).toString();
  459. }
  460. /**
  461. * Save new value from slider
  462. * @param e
  463. */
  464. private _onMouseUp(e: MouseEvent): void {
  465. window.removeEventListener('mousemove', this._onMouseDragHandler);
  466. window.removeEventListener('mouseup', this._onMouseUpHandler);
  467. this._prevY = e.clientY;
  468. }
  469. /**
  470. * Start record mouse position
  471. * @param e
  472. */
  473. private _onMouseDown(e: MouseEvent): void {
  474. this._prevY = e.clientY;
  475. this._preValue = this.value;
  476. window.addEventListener('mousemove', this._onMouseDragHandler);
  477. window.addEventListener('mouseup', this._onMouseUpHandler);
  478. }
  479. /**
  480. * Create input entry
  481. */
  482. private _checkboxInput() {
  483. if (this._valueDiv.childElementCount < 1) { // Prevent display two checkbox
  484. this._input = Helpers.CreateInput('checkbox-element', this._valueDiv);
  485. this._input.type = 'checkbox';
  486. this._input.checked = this.value;
  487. this._input.addEventListener('change', () => {
  488. Scheduler.getInstance().pause = true;
  489. this.validateInput(!this.value);
  490. });
  491. }
  492. }
  493. private _rangeInput() {
  494. if (this._valueDiv.childElementCount < 1) { // Prevent display two input range
  495. this._input = Helpers.CreateInput('slider-element', this._valueDiv);
  496. this._input.type = 'range';
  497. this._input.style.display = 'inline-block';
  498. this._input.min = this._getSliderProperty().min;
  499. this._input.max = this._getSliderProperty().max;
  500. this._input.step = this._getSliderProperty().step;
  501. this._input.value = this.value;
  502. this._validateInputHandler = this._rangeHandler.bind(this);
  503. this._input.addEventListener('input', this._validateInputHandler);
  504. this._input.addEventListener('change', () => {
  505. Scheduler.getInstance().pause = false;
  506. });
  507. this._textValue = Helpers.CreateDiv('value-text', this._valueDiv);
  508. this._textValue.innerText = Helpers.Trunc(this.value).toString();
  509. this._textValue.style.paddingLeft = '10px';
  510. this._textValue.style.display = 'inline-block';
  511. }
  512. }
  513. private _rangeHandler() {
  514. Scheduler.getInstance().pause = true;
  515. //this._input.style.backgroundSize = ((parseFloat(this._input.value) - parseFloat(this._input.min)) * 100 / ( parseFloat(this._input.max) - parseFloat(this._input.min))) + '% 100%'
  516. this._textValue.innerText = this._input.value;
  517. this.validateInput(this._input.value, false);
  518. }
  519. private _isSliderType() { //Check if property have slider definition
  520. return this._property &&
  521. PROPERTIES.hasOwnProperty(this._property.obj.constructor.name) &&
  522. (<any>PROPERTIES)[this._property.obj.constructor.name].hasOwnProperty('slider') &&
  523. (<any>PROPERTIES)[this._property.obj.constructor.name].slider.hasOwnProperty(this.name);
  524. }
  525. private _getSliderProperty() {
  526. return (<any>PROPERTIES)[this._property.obj.constructor.name].slider[this.name];
  527. }
  528. }