valueAndUnit.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /// <reference path="../../dist/preview release/babylon.d.ts"/>
  2. module BABYLON.GUI {
  3. export class ValueAndUnit {
  4. public constructor(public value = 1, public unit = ValueAndUnit.UNITMODE_PERCENTAGE, public negativeValueAllowed = true) {
  5. }
  6. public get isPercentage(): boolean {
  7. return this.unit === ValueAndUnit.UNITMODE_PERCENTAGE;
  8. }
  9. public get isPixel(): boolean {
  10. return this.unit === ValueAndUnit.UNITMODE_PIXEL;
  11. }
  12. public toString(): string {
  13. switch (this.unit) {
  14. case ValueAndUnit.UNITMODE_PERCENTAGE:
  15. return this.value + "%";
  16. case ValueAndUnit.UNITMODE_PIXEL:
  17. return this.value + "px";
  18. }
  19. return this.unit.toString();
  20. }
  21. public fromString(source: string): boolean {
  22. var match = ValueAndUnit._Regex.exec(source);
  23. if (!match || match.length === 0) {
  24. return false;
  25. }
  26. var sourceValue = parseFloat(match[1]);
  27. var sourceUnit = this.unit;
  28. if (!this.negativeValueAllowed) {
  29. if (sourceValue < 0) {
  30. sourceValue = 0;
  31. }
  32. }
  33. if (match.length === 4) {
  34. switch(match[3]) {
  35. case "px":
  36. sourceUnit = ValueAndUnit.UNITMODE_PIXEL;
  37. break;
  38. case "%":
  39. sourceUnit = ValueAndUnit.UNITMODE_PERCENTAGE;
  40. sourceValue /= 100.0;
  41. break;
  42. }
  43. }
  44. if (sourceValue === this.value && sourceUnit === this.unit) {
  45. return false;
  46. }
  47. this.value = sourceValue;
  48. this.unit = sourceUnit;
  49. return true;
  50. }
  51. // Static
  52. private static _Regex = /(^-?\d*(\.\d+)?)(%|px)?/;
  53. private static _UNITMODE_PERCENTAGE = 0;
  54. private static _UNITMODE_PIXEL = 1;
  55. public static get UNITMODE_PERCENTAGE(): number {
  56. return ValueAndUnit._UNITMODE_PERCENTAGE;
  57. }
  58. public static get UNITMODE_PIXEL(): number {
  59. return ValueAndUnit._UNITMODE_PIXEL;
  60. }
  61. }
  62. }