CDClientLib.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. /*!
  2. Client lib for manipulating on DOM elements.
  3. Author: CrazyDoctor (Oleg Karataev)
  4. */
  5. class CDElement {
  6. constructor(el) {
  7. this.element = el;
  8. el.cdelement = this;
  9. try {
  10. this.events = Object.keys(getEventListeners(el));
  11. } catch(e) {
  12. this.events = [];
  13. }
  14. }
  15. static get(el) {
  16. if(el == null)
  17. return null;
  18. if(el instanceof CDElement)
  19. return el;
  20. if(el.cdelement)
  21. return el.cdelement;
  22. if(el instanceof Element || el instanceof Window)
  23. return el.cdelement = new CDElement(el);
  24. throw 'CDElement.get() error';
  25. }
  26. get() {
  27. return this.element;
  28. }
  29. copy() {
  30. return new CDElement(this.get().cloneNode(true));
  31. }
  32. getFirstChild(selector) {
  33. const children = Array.from(this.get().children);
  34. if (children.length == 0)
  35. return null;
  36. if (CDUtils.isEmpty(selector))
  37. return CDElement.get(children[0]);
  38. const child = this.get().querySelector(selector);
  39. if(child)
  40. return CDElement.get(child);
  41. return null;
  42. }
  43. hasChildren() {
  44. return Array.from(this.get().children).length > 0;
  45. }
  46. getChildren(selector) {
  47. if (CDUtils.isEmpty(selector))
  48. return Array.from(this.get().children).map((element) => CDElement.get(element));
  49. return Array.from(this.get().querySelectorAll(selector)).map((element) => CDElement.get(element));
  50. }
  51. getChildrenRecursive() {
  52. let children = this.getChildren();
  53. for(const child of children) {
  54. if(this.hasChildren())
  55. children = children.concat(child.getChildrenRecursive());
  56. }
  57. return children;
  58. }
  59. getParent() {
  60. return CDElement.get(this.get().parentElement);
  61. }
  62. getValue() {
  63. return this.get().value || this.getInnerHTML();
  64. }
  65. setValue(value) {
  66. this.get().value = value;
  67. return this;
  68. }
  69. append(element) {
  70. this.get().append(element.get());
  71. }
  72. prepend(element) {
  73. this.get().prepend(element.get());
  74. }
  75. remove() {
  76. this.get().remove();
  77. }
  78. disable() {
  79. this.removeCssProperty('display');
  80. this.addClass('disabled');
  81. return this;
  82. }
  83. enable(display) {
  84. this.removeClass('disabled');
  85. this.get().style.display = CDUtils.isEmpty(display) ? 'block' : display;
  86. return this;
  87. }
  88. minimizeHeight() {
  89. this.get().style.height = '0px';
  90. return this;
  91. }
  92. minimizeWidth() {
  93. this.get().style.width = '0px';
  94. return this;
  95. }
  96. expandHeight(size) {
  97. if (CDUtils.isEmpty(size))
  98. return this;
  99. this.get().style.height = size + 'px';
  100. return this;
  101. }
  102. expandWidth(size){
  103. if (CDUtils.isEmpty(size))
  104. return this;
  105. this.get().style.width = size + 'px';
  106. return this;
  107. }
  108. isMinimized(el) {
  109. return CDUtils.isEmpty(this.get().style.height);
  110. }
  111. isDisabled(el) {
  112. return CDUtils.isEmpty(this.get().style.display);
  113. }
  114. setId(id) {
  115. if (CDUtils.isEmpty(id))
  116. return this;
  117. this.get().id = id;
  118. return id;
  119. }
  120. previousSibling() {
  121. return CDElement.get(this.get().previousElementSibling);
  122. }
  123. nextSibling() {
  124. return CDElement.get(this.get().nextElementSibling);
  125. }
  126. addClass(cls) {
  127. if (CDUtils.isEmpty(cls))
  128. return this;
  129. cls.split(' ').forEach((c) => {
  130. if(c.length > 0 && !this.hasClass(c))
  131. this.get().classList.add(c);
  132. });
  133. return this;
  134. }
  135. getClass() {
  136. if (CDUtils.isEmpty(this.get().classList))
  137. return '';
  138. let classList = '';
  139. this.get().classList.forEach((cls) => {
  140. classList += cls + " ";
  141. });
  142. return classList.trim();
  143. }
  144. removeClass(cls) {
  145. if (CDUtils.isEmpty(cls))
  146. return this;
  147. this.get().classList.remove(cls);
  148. return this;
  149. }
  150. hasClass(cls) {
  151. if (CDUtils.isEmpty(this.get().classList))
  152. return false;
  153. let has = false;
  154. this.get().classList.forEach((c) => {
  155. if (c === cls) has = true;
  156. });
  157. return has;
  158. }
  159. removeClass(cls) {
  160. if (CDUtils.isEmpty(cls))
  161. return this;
  162. this.get().classList.remove(cls);
  163. return this;
  164. }
  165. switchClass(cls, condition) {
  166. if(condition != null)
  167. return condition ? this.addClass(cls) : this.removeClass(cls);
  168. return this.hasClass(cls) ? this.removeClass(cls) : this.addClass(cls);
  169. }
  170. removeCssProperty(prop) {
  171. if (CDUtils.isEmpty(prop))
  172. return this;
  173. this.get().style.setProperty(prop, '');
  174. return this;
  175. }
  176. setAttribute(attr, value) {
  177. this.get().setAttribute(attr, CDUtils.isEmpty(value) ? '' : value);
  178. return this;
  179. }
  180. getAttribute(attr) {
  181. return this.get().getAttribute(attr);
  182. }
  183. setInnerHTML(value) {
  184. this.get().innerHTML = CDUtils.isEmpty(value) ? '' : value;
  185. return this;
  186. }
  187. getInnerHTML() {
  188. return this.get().innerHTML;
  189. }
  190. getInnerWidth() {
  191. return this.get().innerWidth;
  192. }
  193. getInnerHeight() {
  194. return this.get().innerHeight;
  195. }
  196. getOffsetTop() {
  197. return this.get().offsetTop;
  198. }
  199. scrollTo(selector) {
  200. const child = this.getFirstChild(selector);
  201. if(child)
  202. this.get().scrollTop = child.getOffsetTop() - this.getOffsetTop();
  203. }
  204. scrollIntoView() {
  205. this.get().scrollIntoView();
  206. return this;
  207. }
  208. style(property, value, priority) {
  209. this.get().style.setProperty(property, value, priority);
  210. return this;
  211. }
  212. focus() {
  213. this.get().focus();
  214. return this;
  215. }
  216. blur() {
  217. this.get().blur();
  218. return this;
  219. }
  220. click() {
  221. this.get().click();
  222. return this;
  223. }
  224. on(event, callback) {
  225. if (CDUtils.isEmpty(event) || CDUtils.isEmpty(callback))
  226. return this;
  227. this.get().addEventListener(event, callback);
  228. return this;
  229. }
  230. un(event, callback) {
  231. if (CDUtils.isEmpty(event))
  232. return this;
  233. this.get().removeEventListener(event, callback);
  234. return this;
  235. }
  236. }
  237. class Url {
  238. constructor(url) {
  239. this.url = new URL(url || location);
  240. this.urlSearch = new URLSearchParams(this.url.search);
  241. }
  242. static getHash() {
  243. return new Url().getHash();
  244. }
  245. static setHash(hash) {
  246. return new Url().setHash(hash);
  247. }
  248. static getOrigin() {
  249. return new Url().getOrigin();
  250. }
  251. static goTo(url, blank) {
  252. window.open(url, blank ? '_blank' : '_self');
  253. }
  254. static reload() {
  255. location.reload();
  256. }
  257. static getFullPath() {
  258. const url = new Url().url;
  259. return `${url.origin}${url.pathname}`;
  260. }
  261. getHash() {
  262. const hash = this.url.hash.substring(1);
  263. return hash.length > 0 ? hash : null;
  264. }
  265. setHash(hash) {
  266. this.url.hash = !hash || hash.length == 0 ? '' : `#${hash}`;
  267. return this;
  268. }
  269. setSearchParams(params) {
  270. const paramsArr = [];
  271. for(const key of Object.keys(params)) {
  272. paramsArr.push(`${key}=${params[key]}`);
  273. }
  274. this.url.search = paramsArr.join('&');
  275. }
  276. getSearchParams() {
  277. const params = {};
  278. Array.from(this.url.searchParams).forEach((pair) => {
  279. params[pair[0]] = pair[1];
  280. });
  281. return params;
  282. }
  283. setPath(path) {
  284. this.url.pathname = path;
  285. return this;
  286. }
  287. getPath() {
  288. return this.url.pathname;
  289. }
  290. getOrigin() {
  291. return this.url.origin;
  292. }
  293. getProtocol() {
  294. return this.url.protocol;
  295. }
  296. setProtocol(protocol) {
  297. this.url.protocol = protocol;
  298. return this;
  299. }
  300. toString() {
  301. this.url.search = this.urlSearch.toString();
  302. return this.url.toString();
  303. }
  304. toLocalString() {
  305. this.url.search = this.urlSearch.toString();
  306. return this.toString().substring(this.url.origin.length);
  307. }
  308. updateLocation() {
  309. const hashChanged = Url.getHash() !== this.getHash();
  310. history.replaceState(null, null, this.toLocalString());
  311. hashChanged && window.dispatchEvent(new HashChangeEvent('hashchange'));
  312. }
  313. }
  314. class Style {
  315. static apply(element, styleStr) {
  316. element = element instanceof CDElement ? element : CDElement.get(element);
  317. const propertiesMap = this.getCssPropertiesMap(styleStr);
  318. for(const prop of Object.keys(propertiesMap))
  319. element.style(prop, propertiesMap[prop].value, propertiesMap[prop].priority);
  320. }
  321. static getCssPropertiesMap(styleStr) {
  322. const parts = styleStr.split(';');
  323. const map = {};
  324. for(let part of parts) {
  325. part = part.trim();
  326. if(part.length == 0)
  327. continue;
  328. const propVal = part.split(':');
  329. const property = propVal[0].trim();
  330. const value = propVal[1].trim().split('!');
  331. map[property] = { value: value[0], priority: value.length > 1 ? value[1] : '' };
  332. }
  333. return map;
  334. }
  335. }
  336. class DOM {
  337. static Events = {
  338. Click: 'click',
  339. Load: 'load',
  340. KeyDown: 'keydown',
  341. KeyUp: 'keyup',
  342. KeyPress: 'keypress',
  343. Change: 'change',
  344. Cut: 'cut',
  345. Drop: 'drop',
  346. Paste: 'paste',
  347. Input: 'input',
  348. HashChange: 'hashchange',
  349. MouseDown: 'mousedown',
  350. ContextMenu: 'contextmenu',
  351. Blur: 'blur'
  352. };
  353. static Tags = {
  354. A: 'a',
  355. Div: 'div',
  356. Span: 'span',
  357. H1: 'h1',
  358. H2: 'h2',
  359. H3: 'h3',
  360. P: 'p',
  361. Textarea: 'textarea',
  362. Input: 'input',
  363. Table: 'table',
  364. Tr: 'tr',
  365. Th: 'th',
  366. Tbody: 'tbody',
  367. Td: 'td',
  368. Select: 'select',
  369. Option: 'option'
  370. };
  371. static Keys = {
  372. Enter: 'Enter',
  373. Escape: 'Escape',
  374. Control: 'Control',
  375. Shift: 'Shift',
  376. Backspace: 'Backspace'
  377. };
  378. static MouseButtons = {
  379. Left: 1,
  380. Right: 2,
  381. Middle: 4
  382. };
  383. static get(selector) {
  384. if (CDUtils.isEmpty(selector))
  385. throw "DOM.get() invalid selector.";
  386. const element = document.querySelector(selector);
  387. if (CDUtils.isEmpty(element))
  388. return null;
  389. return CDElement.get(element);
  390. }
  391. static getAll(selector) {
  392. if (CDUtils.isEmpty(selector))
  393. throw "DOM.getAll() invalid selector.";
  394. const elements = document.querySelectorAll(selector);
  395. if(CDUtils.isEmpty(elements))
  396. return [];
  397. return Array.from(elements).map((element) => CDElement.get(element));
  398. }
  399. static create(config, container, prepend) {
  400. if (CDUtils.isEmpty(config) || CDUtils.isEmpty(config.tag))
  401. return;
  402. const element = CDElement.get(document.createElement(config.tag));
  403. if (!CDUtils.isEmpty(config.attr)) {
  404. Object.keys(config.attr).forEach((name) => {
  405. if(config.attr[name] !== undefined)
  406. element.setAttribute(name, config.attr[name]);
  407. });
  408. }
  409. if (!CDUtils.isEmpty(config.cls)) element.addClass(config.cls);
  410. if (!CDUtils.isEmpty(config.id)) element.setId(config.id);
  411. if (!CDUtils.isEmpty(config.style)) Style.apply(element, config.style);
  412. if (!CDUtils.isEmpty(config.cn)) {
  413. config.cn.forEach((el) => {
  414. if (el instanceof Element) {
  415. element.append(CDElement.get(el));
  416. } else if (el instanceof CDElement) {
  417. element.append(el);
  418. } else this.create(el, element);
  419. });
  420. }
  421. // innerHTML appends after cn
  422. if (!CDUtils.isEmpty(config.innerHTML)) element.setInnerHTML(element.getInnerHTML() + config.innerHTML);
  423. if (!CDUtils.isEmpty(container))
  424. (prepend === true ? container.prepend(element) : container.append(element));
  425. return element;
  426. }
  427. static append(container, element) {
  428. if (CDUtils.isEmpty(element) || CDUtils.isEmpty(container) ||
  429. (!(element instanceof Element) && !(element instanceof CDElement)) ||
  430. (!(container instanceof Element) && !(container instanceof CDElement)))
  431. return;
  432. (container instanceof CDElement ? container.get() : container).append((element instanceof CDElement ? element.get() : element));
  433. }
  434. static setTitle(title) {
  435. document.title = title;
  436. }
  437. static setCookie(name, value, hours) {
  438. document.cookie = name + "=" + JSON.stringify(value) + "; path=/; expires=" + (new Date(Date.now() + hours * 3600000).toGMTString());
  439. }
  440. static getCookie(name) {
  441. const cookies = {};
  442. document.cookie.split(';').forEach(function(el) {
  443. const [key, value] = el.split('=');
  444. cookies[key.trim()] = value;
  445. });
  446. const cookieValue = cookies[name];
  447. if(CDUtils.isEmpty(cookieValue))
  448. return null;
  449. if(CDUtils.isJsonString(cookieValue))
  450. return JSON.parse(cookieValue);
  451. else
  452. return cookieValue;
  453. }
  454. static getCookieProperty(name, property) {
  455. const cookie = DOM.getCookie(name);
  456. if(cookie && !(cookie instanceof Object))
  457. throw 'DOM.getCookieProperty(): cookie value is not a JSON';
  458. return cookie ? cookie[property] : null;
  459. }
  460. static setCookieProperty(name, property, value, hours) {
  461. const cookie = DOM.getCookie(name);
  462. if(cookie) {
  463. if(!(cookie instanceof Object))
  464. throw 'DOM.setCookieProperty(): initial cookie value is not a JSON';
  465. cookie[property] = value;
  466. DOM.setCookie(name, cookie, hours || 24);
  467. } else {
  468. DOM.setCookie(name, { [property]: value }, hours || 24);
  469. }
  470. }
  471. static documentOn(event, callback) {
  472. if (CDUtils.isEmpty(event) || CDUtils.isEmpty(callback))
  473. return;
  474. document.addEventListener(event, callback);
  475. }
  476. static copyToClipboard(str) {
  477. const body = DOM.get('body');
  478. const input = DOM.create({ tag: DOM.Tags.Input, style: 'display: none;' }, body);
  479. input.setValue(str);
  480. input.get().select();
  481. input.get().setSelectionRange(0, 99999);
  482. navigator.clipboard.writeText(input.get().value).then(() => {
  483. input.remove();
  484. });
  485. }
  486. }
  487. class CDUtils {
  488. static isEmpty(val) {
  489. return val === null || val === undefined ||
  490. val === '' || val.length === 0;
  491. }
  492. static isJsonString(str) {
  493. try {
  494. JSON.parse(str);
  495. } catch (e) {
  496. return false;
  497. }
  498. return true;
  499. }
  500. static nl2br(str) {
  501. return str.replaceAll(/(?:\r\n|\r|\n)/g, '<br/>');
  502. }
  503. static br2nl(str) {
  504. return str.replaceAll(/<br\/?>/g, '\n');
  505. }
  506. static async SHA256(input) {
  507. return crypto.subtle.digest('SHA-256', new TextEncoder('utf8').encode(input)).then(h => {
  508. const hexes = [], view = new DataView(h);
  509. for (let i = 0; i < view.byteLength; i += 4)
  510. hexes.push(('00000000' + view.getUint32(i).toString(16)).slice(-8));
  511. return hexes.join('');
  512. });
  513. }
  514. /**
  515. * Returns string representation of <b>x</b> with leading zeros.<br/>
  516. * Length of the resulting string will be equal to <b>length</b> or <b>2</b> if <b>length</b> was not specified.<br/>
  517. * If length of the initial number is greater or equal to <b>length</b> parameter, nothing will be changed.
  518. * <br/><br/>
  519. * Examples:<br/>CDUtils.pad(5) -> "05"<br/>CDUtils.pad(21) -> "21"<br/>CDUtils.pad(21, 3) -> "021"
  520. * @param {number|String} x
  521. * @param {number} [length]
  522. * @return string
  523. */
  524. static pad(x, length) {
  525. const count = length != null && length >= 2 ? length : 2;
  526. const str = x.toString();
  527. const diff = count - str.length;
  528. return `${"0".repeat(diff < 0 ? 0 : diff)}${str}`;
  529. }
  530. /**
  531. * Returns formatted date. <br/>
  532. * H - hours<br/>I - minutes<br/>S - seconds<br/>s - milliseconds<br/>D - day<br/>M - month<br/>Y - year (0000)<br/>y - year (00)
  533. * @param {number} timestamp
  534. * @param {string} format
  535. * @return string
  536. */
  537. static dateFormat(timestamp, format) {
  538. const date = new Date(timestamp);
  539. const day = date.getDate();
  540. const month = date.getMonth()+1;
  541. const year = date.getFullYear();
  542. const hours = date.getHours();
  543. const minutes = date.getMinutes();
  544. const seconds = date.getSeconds();
  545. const mseconds = date.getMilliseconds();
  546. return format.replaceAll('H', CDUtils.pad(hours.toString()))
  547. .replaceAll('I', CDUtils.pad(minutes.toString()))
  548. .replaceAll('S', CDUtils.pad(seconds.toString()))
  549. .replaceAll('s', CDUtils.pad(mseconds.toString()))
  550. .replaceAll('D', CDUtils.pad(day.toString()))
  551. .replaceAll('M', CDUtils.pad(month.toString()))
  552. .replaceAll('Y', CDUtils.pad(year.toString(), 4))
  553. .replaceAll('y', CDUtils.pad((year % 100).toString()));
  554. }
  555. static dateFormatUTC(date, timeZoneOffsetHours, format) {
  556. date = date instanceof Date ? date : new Date(date);
  557. date.setUTCHours(date.getUTCHours() + timeZoneOffsetHours);
  558. var year = date.getUTCFullYear();
  559. var month = date.getUTCMonth() + 1;
  560. var day = date.getUTCDate();
  561. var hours = date.getUTCHours();
  562. var minutes = date.getUTCMinutes();
  563. var seconds = date.getUTCSeconds();
  564. return format.replaceAll('H', CDUtils.pad(hours.toString()))
  565. .replaceAll('I', CDUtils.pad(minutes.toString()))
  566. .replaceAll('S', CDUtils.pad(seconds.toString()))
  567. .replaceAll('D', CDUtils.pad(day.toString()))
  568. .replaceAll('M', CDUtils.pad(month.toString()))
  569. .replaceAll('Y', CDUtils.pad(year.toString(), 4))
  570. .replaceAll('y', CDUtils.pad((year % 100).toString())) + ` UTC${timeZoneOffsetHours > 0 ? '+' : '-'}${timeZoneOffsetHours}`;
  571. }
  572. static repeat(str, n) {
  573. let res = '';
  574. for(let i = 0; i < n; i++)
  575. res += str;
  576. return res;
  577. }
  578. static randInt(min, max) {
  579. const minCeiled = Math.ceil(min);
  580. const maxFloored = Math.floor(max);
  581. return Math.floor(Math.random() * (maxFloored - minCeiled) + minCeiled);
  582. }
  583. static arrayShuffle(unshuffled) {
  584. return unshuffled
  585. .map(value => ({ value, sort: Math.random() }))
  586. .sort((a, b) => a.sort - b.sort)
  587. .map(({ value }) => value);
  588. }
  589. }
  590. const window_ = CDElement.get(window);