PHP Classes
elePHPant
Icontem

File: FrontEndScripts/libs/Nemiro/Utility.ts

Recommend this page to a friend!
  Classes of Aleksey Nemiro  >  PHP Small Server Administrator  >  FrontEndScripts/libs/Nemiro/Utility.ts  >  Download  
File: FrontEndScripts/libs/Nemiro/Utility.ts
Role: Auxiliary data
Content type: text/plain
Description: Auxiliary data
Class: PHP Small Server Administrator
Web panel for small Debian and Ubuntu servers
Author: By
Last change:
Date: 3 years ago
Size: 12,405 bytes
 

 

Contents

Class file image Download
?/*
 * Copyright  Aleksey Nemiro, 2015. All rights reserved.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
module Nemiro {

  /** 
   * ??????????????? ??????????. 
   * 
   * -----------------------------------------------------
   * Aleksey Nemiro, Arimsoft Ltd., 13.08.2015
   * http://aleksey.nemiro.ru
   * http://arimsoft.ru
   */
  export class Utility {

    /** ?????????, ???????? ????????? ???????? ?????? ??? ???. */
    public static IsNumeric(value: any): boolean {
      return (!isNaN(parseFloat(value)) && isFinite(value));
    }

    /**
     * ?????????? ????? ? ???? ??????. ????????: 3 ?????, 5 ??????.
     * 
     * @para value ??????????.
     * @param word1 ???? ?????.
     * @param word234 ???? ?????.
     * @param wordmore ?????? ????.
     */
    public static GetCountAsString(value: number, word1: string, word234: string, wordmore: string) {
      var decintpart = value;
      var intpart = decintpart;
      var endpart = (intpart % 100);
      if (endpart > 19) endpart = endpart % 10;
      switch (endpart) {
        case 1:
          return word1;

        case 2:
        case 3:
        case 4:
          return word234;

        default:
          return wordmore;
      }
    }

    /** ?????????? ??? ????.*/
    public static CompareDates(a: any, b: any): number {
      return (
        isFinite(a = Utility.ConvertToDate(a).valueOf()) &&
          isFinite(b = Utility.ConvertToDate(b).valueOf()) ?
          <any>(a > b) - <any>(a < b) : NaN
      );
    }

    /** ??????????? ????????? ???????? ? ????. */
    public static ConvertToDate(d: any): Date {
      return <any>(
        d.constructor === Date ? new Date(d.getFullYear(), d.getMonth(), d.getDate()) :
          d.constructor === Array ? new Date(d[0], d[1], d[2]) :
            d.constructor === Number ? new Date(d) :
              d.constructor === String ? (/[0-9]{2}.[0-9]{2}.[0-9]{4}/.test(d) ?
                new Date(parseInt(d.split(".")[2], 10), parseInt(d.split(".")[1], 10) - 1, parseInt(d.split(".")[0], 10)) : new Date(d)) :
                typeof d === "object" ? new Date(d.year, d.month, d.date) : NaN
      );
    }

    /** 
     * ??????? (??????????) ????? ?? ????????? ????.
     * 
     * @param datetime ????, ???? timeStamp.
     */
    public static ExcludeTime(datetime: Date|number): Date {
      if (typeof datetime === 'number') { datetime = new Date(<number>datetime); }
      return new Date((<Date>datetime).getFullYear(),(<Date>datetime).getMonth(),(<Date>datetime).getDate());
    }

    /** ??????????? ??????, ?????????? ???? ? ??????? ??.??.????, ? ????. */
    public static GetDateFromString(dateString: string): Date {
      var dpg = $.fn.datepicker.DPGlobal;
      return dpg.parseDate(dateString, dpg.parseFormat('dd.mm.yyyy'));
    }

    /*
     * ?????????? ?????? ?????????????? ???? ? ????????? ???????.
     * 
     * @param date ????, ??????? ??????? ????????????? ? ??????.
     * @param format ?????? ????. ?? ?????????: dd.mm.yyyy.
     */
    static DateToString(date: Date, format?: string): string {
      if (format == undefined || format == null || format == '') {
        format = 'dd.mm.yyyy';
      }

      var dpg = $.fn.datepicker.DPGlobal;

      return dpg.formatDate(date, dpg.parseFormat(format), 'ru');
    }

    /**
     * ????????? ???????????? ????. 
     * 
     * @param value ????????, ??????? ??????? ?????????.
     */
    public static IsValidDate(value: string): boolean {
      if (!value || value == undefined || value == '') { return false; }
      var arr = value.split('.');
      if (arr.length < 3) { return false; }
      var y = parseInt(arr[2], 10), m = parseInt(arr[1], 10), d = parseInt(arr[0], 10);
      var dt = new Date(y, m - 1, d);
      if (isNaN(dt.getTime())) { return false; }
      return dt.getFullYear() == y && dt.getMonth() + 1 == m && dt.getDate() == d;
    }

    /**
     * ??????????? ????????? ??????.
     * @param value ??????, ? ??????? ??????? ???????? ?????????.
     * @param args ???????????, ??????? ??????? ???????? ? ??????.
     */
    static Format(value: string, args: any): string {
      if (value === undefined || value === null || value === '') {
        console.log('Value is empty.');
        return null;
      }

      if (args.length === 1 && args[0] !== null && typeof args[0] === 'object') {
        args = args[0];
      }

      if (typeof args === 'string') {
        args = [args];
      }

      return value.replace(/{([^}]*)}/g, function (match, key) {
        return (typeof args[key] !== "undefined" ? args[key] : match);
      });
    }

    /*
     * ???????? ???????? ????? ????????? ?? ??????.
     * 
     * @param str ??????, ? ??????? ??????? ?????????? ????? ? ??????.
     * @param find ??????? ?????????.
     * @param repl ?????????, ?? ??????? ??????? ???????? ????????? ??????????.
     */
    static Replace(str, find, repl): string {
      return str.replace(new RegExp("(" + find + ")+", "g"), repl);
    }

    /**
     * ???????? ????????? HTML.
     * 
     * @param value ??????, ? ??????? ??????? ???????????? ???????? HTML.
     */
    static HtmlEncode(value: string): string {
      var r = new RegExp("\x22+", "g");
      var div = document.createElement("div");
      var text = document.createTextNode(value);
      div.appendChild(text);
      return div.innerHTML.replace(r, "&quot;");
    }

    /**
     * ?????????? ????????? HTML.
     * 
     * @param value ??????, ? ??????? ??????? ???????????? ???????? HTML.
     */
    static HtmlDecode(value: string): string {
      var div = document.createElement("div");
      div.innerHTML = value;
      return div.innerText;
    }

    /** 
     * ?????? ????. 
     * 
     * @param name ??? ????.
     * @param value ????????.
     * @param days ???? ???????? (????).
     */
    public static CreateCookies(name: string, value: string, days?: number) {
      var expires = '';
      var date = new Date();

      if (days !== undefined && days !== null) {
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = '; expires=' + date.toUTCString();
      }

      document.cookie = Utility.Format('{name}={value}{expires}; path=/', { name: name, value: value, expires: expires });
    }

    /** 
     *  ?????????? ???? ?????, ? ??????????, ???? ?? ????? ???? ?? ????????? ?? ?????, ? ???? ? ????? ??????, ?????, ?????, ? ??????????. 
     * 
     * @param name ??? ????.
     */
    public static ReadCookies(name: string): string {
      var ca = document.cookie.split(';');

      name = name + '=';

      for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
      }

      return null;
    }

    /** 
     * ??????? ????. 
     * 
     * @param name ??? ????.
     */
    public static EraseCookies(name: string) {
      Utility.CreateCookies(name, '', -1);
    }

    /** ?????????? ????? ??? ???? (#). */
    public static GetUrlWithoutHash(url: string): string {
      if (url.indexOf('#') != -1) {
        url = url.substring(0, url.indexOf('#'));
      }
      return url;
    }

    /** ?????????? ????????? ???????? ?????????? url. */
    public static GetUrlParameter(name: string, url: string): string {
      if (url == undefined || url == null) {
        url = window.location.search;
      }
      return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [, ""])[1].replace(/\+/g, '%20')) || null;
    }

    /*
     * ?????????? ?????? ???????? ? ?????? ????? ? ????????.
     */
    public static GetElementHeight(element: string|JQuery|HTMLElement): number {
      var $element = $(element);
      if ($element.css("display") == "none") { return 0; }
      var pd = 0;
      pd += ($element.css("padding-top") && $element.css("padding-top") != "auto" ? parseInt($element.css("padding-top")) : 0);
      pd += ($element.css("padding-bottom") && $element.css("padding-bottom") != "auto" ? parseInt($element.css("padding-bottom")) : 0);
      pd += ($element.css("margin-top") && $element.css("margin-top") != "auto" ? parseInt($element.css("margin-top")) : 0);
      pd += ($element.css("margin-bottom") && $element.css("margin-bottom") != "auto" ? parseInt($element.css("margin-bottom")) : 0);
      return $element.height() + pd;
    }

    /*
     * ?????????? ?????? ???????? ? ?????? ????? ? ????????.
     */
    public static GetElementWidth(element: string|JQuery|HTMLElement): number {
      var $element = $(element);
      if ($element.css("display") == "none") { return 0; }
      var pd = 0;
      pd += ($element.css("padding-left") && $element.css("padding-left") != "auto" ? parseInt($element.css("padding-left")) : 0);
      pd += ($element.css("padding-right") && $element.css("padding-right") != "auto" ? parseInt($element.css("padding-right")) : 0);
      pd += ($element.css("margin-left") && $element.css("margin-left") != "auto" ? parseInt($element.css("margin-left")) : 0);
      pd += ($element.css("margin-right") && $element.css("margin-right") != "auto" ? parseInt($element.css("margin-right")) : 0);
      return $element.width() + pd;
    }

    /**
     * ?????????, ???????? ????????? ???????? ?????? ??? ???.
     * 
     * @param value ????????, ??????? ????????? ?????????.
     */
    public static IsNullOrEmpty(value: any): boolean {
      return value === undefined || value == null || value == '';
    }

    /**
     * ?????????? ????????? ????? ? ???? ?????? ? ?? ?????, ??? ??? ?????.
     */
    public static NumberTo2DigitString(value: number): string {
      if (value < 10 && value >= 0) {
        return '0' + value.toString();
      } else {
        return value.toString();
      }
    }

    public static NextInvalidField(form: string|JQuery|HTMLFormElement, cssClass?: string): boolean {
      if ((<HTMLFormElement>$(form)[0]).checkValidity()) {
        return false;
      }

      var element = $('input:invalid, textarea:invalid', form).first();

      cssClass = cssClass || 'ng-invalid ng-invalid-required ng-touched';
      element.addClass(cssClass);

      //console.log(element);

      element.focus();

      return true;
    }
    
    /**
     * Return the directory name of a path.
     */
    public static DirectoryName(path: string): string {
      var separator = '/';
      if (path.indexOf('\\') != -1) { separator = '\\'; }
      var pathItems = path.split(separator);
      pathItems.pop();
      return pathItems.join(separator);
    }

  }

}