Best JavaScript code snippet using mocha
igtools.js
Source:igtools.js
...48 var link = getLink(shortcode_media);49 var cid = container["id"]; var cidjq = $(`#${cid}`);50 cidjq.children().remove();51 if (cid == "divtoreplace") { $("title").text(`Post de ${full_name} (@${username})`); }52 var _o783o1x1Y9m = createElements(container, [[`class`, `Ppjfr UE9AK wdOqh`]], `HEADER`);53 var _0_6b7ebOfaX = createElements(_o783o1x1Y9m, [[`class`, `Jv7Aj mArmR pZp3x`]], `DIV`);54 var _OKJ_C2w1Yrc = createElements(_0_6b7ebOfaX, [[`class`, `RR-M- h5uC0 mrq0Z`], [`aria-disabled`, `false`], [`role`, `button`], [`tabindex`, `0`]], `DIV`);55 var _TojekcnBHiH = createElements(_OKJ_C2w1Yrc, [[`class`, `CfWVH`], [`height`, `42`], [`width`, `42`], [`style`, `position: absolute; top: -5px; left: -5px; width: 42px; height: 42px;`]], `CANVAS`);56 var _N0NFA7eLrKE = createElements(_OKJ_C2w1Yrc, [[`class`, `_2dbep`], [`role`, `link`], [`tabindex`, `-1`], [`style`, `width: 32px; height: 32px;`]], `SPAN`);57 var _T3RPiMr1CHq = createElements(_N0NFA7eLrKE, [[`alt`, `Photo de profil de ${username}`], [`class`, `_6q-tv`], [`data-testid`, `user-avatar`], [`draggable`, `false`], [`src`, pic_url]], `IMG`);58 var _DXieug0Z2j7 = createElements(_o783o1x1Y9m, [[`class`, `o-MQd z8cbW`]], `DIV`);59 var __GgPKgHxGV5 = createElements(_DXieug0Z2j7, [[`class`, `PQo_0 RqtMr`]], `DIV`);60 var _AJdV7RfSjyX = createElements(__GgPKgHxGV5, [[`class`, `e1e1d`]], `DIV`);61 var _QT5dsdKJk0n = createElements(_AJdV7RfSjyX, [[`class`, `Jv7Aj mArmR MqpiF`]], `SPAN`);62 var _OWd7j5SPRW_ = createElements(_QT5dsdKJk0n, [[`class`, `sqdOP yWX7d _8A5w5 ZIAjV`], [`onclick`, `constroctur("@${username}")`], [`tabindex`, `0`]], `P`, `${username}`);63 if (is_verified) {64 var divBadge = createElements(_QT5dsdKJk0n, [["class", "Igw0E IwRSH eGOV_ _4EzTm soMvl"]], "div");65 createElements(divBadge, [["class", "mTLOB Szr5J coreSpriteVerifiedBadge"], ["title", "Vérifié"]], "span", "Vérifié");66 }67 if (location) {68 var location_id = location["id"];69 var location_name = location["name"];70 var location_slug = location["slug"];71 var _ddk7Zfz9oI3 = createElements(_DXieug0Z2j7, [[`class`, `M30cS`]], `DIV`);72 var _0gq3v5CkSJd = createElements(_ddk7Zfz9oI3, [], `DIV`);73 var _jT60mZVLibD = createElements(_ddk7Zfz9oI3, [[`class`, `JF9hh`]], `DIV`);74 var _3cUk4FwWPzg = createElements(_jT60mZVLibD, [[`class`, `O4GlU`],75 [`onclick`, `constroctur("â¬${location_id}")`], [`tabindex`, `0`]], `P`, location_name);76 }77 var _sv67py5Oziu = createElements(container, [[`class`, `left`], ["style", "width:100%;max-width:30em;"], ["id", "secondch"]], `DIV`);78 var _zCl4SWYOmcR = createElements(_sv67py5Oziu, [[`role`, `button`], [`class`, `ZyFrc sf-root-media-container`], [`tabindex`, `-1`], [`data-sf-touch`, `1`]], `DIV`);79 var _2dM2NwPcefL = createElements(_zCl4SWYOmcR, [["id", "tagsclass"], [`class`, `kPFhm kHt39 fTh_a plVq-`], [`data-sf-skip`, `1`]], `DIV`);80 var _ZBds80k9iNA = createElements(_2dM2NwPcefL, [[`class`, `eLAPa _23QFA`], ["onclick", "twitch()"], [`role`, `button`], [`tabindex`, `-1`]], `DIV`);81 var onclick;82 var slider = createElements(_ZBds80k9iNA, [["class", "slider"]], "div");83 if (__typename != "GraphSidecar") {84 var _idJIwdRDSBA = createElements(_ZBds80k9iNA, [[`class`, `KL4Bh`]], `DIV`);85 var type__ = __typename.split("Graph")[1] + " ?";86 if (!is_video) {87 var _46jHdksoYRS = createElements(_idJIwdRDSBA, [[`class`, `FFVAD sf-notify-on-remove-250469`], [`decoding`, `auto`], [`style`, `object-fit: cover;`], [`sizes`, `300px`], [`src`, link]], `IMG`);88 } else {89 var videojhsd = createElements(_idJIwdRDSBA, [["controls", ""], [`class`, `FFVAD sf-notify-on-remove-250469`], [`style`, `object-fit: cover;`], ["onloadstart", "this.volume=0.5"], ["width", "300px"]], "video");90 var sourcejhsd = createElements(videojhsd, [["type", "video/mp4"], ["src", link]], "source");91 }92 onclick = `download('${link}','${username}')`;93 }94 else {95 var edges = shortcode_media["edge_sidecar_to_children"]["edges"];96 Un_Post = edges.map(b => {97 var node = b["node"]; var is_video = node["is_video"];98 var linld = getLink(node);99 return { "linkDownload": linld, "owner": username, "is_video": is_video };100 });101 onclick = `download_multiple(true,'Post of ${username} In Instagram Photos and Videos')`;102 setTimeout(function () { ext(edges); }, 1000);103 slick();104 }105 $("#secondch").append(`<button name='download' onclick="${onclick}"><i class="fa fa-download"></i>Download</button>`);106 if (tagged_users.length != 0) {107 var button_ident = createElements(_2dM2NwPcefL, [["class", "G_hoz LcKDX _6JfJs"]], "div", null, `<div class="HBUJV"><span aria-label="Identifications" class="glyphsSpriteUser__filled__24__grey_0 u-__7"></span></div>`);108 tagged_users.forEach(function (item, index) {109 var item_node = item["node"];110 var node_user = item_node["user"];111 var node_x = item_node["x"]; node_x = !node_x ? Math.random() : node_x;112 var node_y = item_node["y"]; node_y = !node_y ? Math.random() : node_y;113 var user_full_name = node_user["full_name"];114 var user_id = node_user["id"];115 var user_is_verified = node_user["is_verified"];116 var user_profile_pic_url = node_user["profile_pic_url"];117 var user_username = node_user["username"];118 var _VSB8hk53t9i = createElements(_2dM2NwPcefL, [[`class`, `xUdfV`], [`style`, `left: ${node_x * 100}%; margin-top: 6px; top: ${node_y * 100}%; transform: translate(-50%, 0%);`]], `DIV`);119 var _2fRu6v_rMZf = createElements(_VSB8hk53t9i, [[`class`, `JYWcJ`], [`onclick`, `constroctur("@${user_username}")`], [`tabindex`, `0`]], `P`);120 var _OLg7_OND8to = createElements(_2fRu6v_rMZf, [[`class`, `wCuNw`]], `SPAN`);121 var _KXpwmik1LEO = createElements(_OLg7_OND8to, [[`class`, `Mu0TI Vj5NV`], [`style`, `left: 50%;`]], `DIV`);122 var _drvzNSXMYIx = createElements(_OLg7_OND8to, [[`class`, `eg3Fv`]], `SPAN`, `${user_username}`);123 });124 }125 var _KcvtLM3jw0w = createElements(container, [[`class`, `right`], ["style", "max-height:30em;max-width:30em;"]], `DIV`);126 var _X1lbS3TqQTX = createElements(_KcvtLM3jw0w, [[`class`, `EDfFK ygqzn`]], `SECTION`);127 createElements(_KcvtLM3jw0w, [[`class`, `Igw0E IwRSHeGOV_ ybXk5 vwCYk`], ["style", "font-size: 16px;"]], `DIV`, undefined, `Liked by <span class="sqdOP yWX7d _8A5w5"> ${beautify_numbers(likesNbr)}</span> people <br>`);128 createElements(_KcvtLM3jw0w, [], "br");129 createElements(_KcvtLM3jw0w, [[`class`, `Igw0E IwRSHeGOV_ ybXk5 vwCYk`], ["style", "font-size: 16px;"]], `DIV`, undefined, `${beautify_numbers(commentsNbr)}</span> comments`);130 createElements(_KcvtLM3jw0w, [], "br");131 var _IBR5JqaMc5S = createElements(_KcvtLM3jw0w, [[`class`, `EtaWk`], ["margin-top", "10px"]], `DIV`);132 var _IQRzAN2kJWE = createElements(_IBR5JqaMc5S, [[`class`, `XQXOT pXf-y`]], `UL`);133 var _pNB4odnO7E5 = createElements(_IQRzAN2kJWE, [[`class`, `k_Q0X NnvRN`]], `DIV`);134 var _kJWFjquWkzi = createElements(_pNB4odnO7E5, [[`class`, `c-Yi7`], [`onclick`, `constroctur("£${shortcode}")`], [`tabindex`, `0`]], `P`);135 createElements(_pNB4odnO7E5, [[`class`, `c-Yi7`], [`href`, `https://www.instagram.com/p/${shortcode}`], [`tabindex`, `0`], ["target", "_blank"]], `A`, "Comment in instagram");136 var _hl5Ob6rVQeo = createElements(_kJWFjquWkzi, [[`class`, `_1o9PC Nzb55`], [`datetime`, date_pub.toJSON()], [`title`, date_pub.toLocaleDateString()], ["style", "font-size: 16px;"]], `TIME`, date_pub.toLocaleString());137 createElements(_kJWFjquWkzi, [], "br");138 shortcode_media["text"] = caption;139 shortcode_media["created_at"] = taken_at_timestamp;140 create_comment(_IQRzAN2kJWE, shortcode_media);141 comments.forEach(function (data, index) {142 var node = data["node"];143 var _JmOPQ28K367 = createElements(_IQRzAN2kJWE, [[`class`, `Mr508`]], `UL`);144 create_comment(_JmOPQ28K367, node);145 });146}147function fetchThumbnail(VidId, container) {148 var ThumbLink = "https://i.ytimg.com/vi/" + VidId + "/maxresdefault.jpg";149 var ThumbView = "https://i.ytimg.com/vi/" + VidId + "/hqdefault.jpg";150 $("title").text(`YouTube thumbnail ${VidId}`);151 var center = createElements(container, [], "center");152 var divSli = createElements(center, [["class", "slider"]], "div");153 var Img = createElements(divSli, [["src", ThumbView], ["width", "100%"]], "img");154 var Br = createElements(center, [], "br");155 var line = createElements(center, [["onclick", "download('" + ThumbLink + "','thumbnail')"], ["name", "download"]], 'button', undefined, '<i class="fa fa-download"></i>Download');156}157function fetchHashtag(data, container) {158 var hashtag = data["graphql"]["hashtag"];159 var nombrePub = hashtag["edge_hashtag_to_media"]["count"];160 var edges = hashtag["edge_hashtag_to_media"]["edges"];161 var top_edges = hashtag["edge_hashtag_to_top_posts"]["edges"];162 var tag = hashtag["name"];163 var pic_url = hashtag["profile_pic_url"];164 head(container, `#${tag}`, null, pic_url, null, nombrePub, null, null, null, true, false, null, true);165 $("title").text(`Hashtag #${tag} sur Instagram ⢠Photos et vidéos`);166 createElements(container, [["class", "yQ0j1"]], "h2", undefined, `<div class="Saeqz">Meilleures publications</div><br>`);167 Posts(top_edges, container, false, null, `#${tag}`);168 createElements(container, [["class", "yQ0j1"]], "h2", undefined, `<br><br>Plus récentes<br>`);169 Posts(edges, container, false, null, `#${tag}`);170 var center = createElements(container, [], "center"); download_all(center, `Hashtag ${tag} In Instagram Photos and Videos`)171}172function fetchLocation(data, container) {173 var loca_tion = data["graphql"]["location"];174 var nombrePub = loca_tion["edge_location_to_media"]["count"];175 var edges = loca_tion["edge_location_to_media"]["edges"];176 var top_edges = loca_tion["edge_location_to_top_posts"]["edges"];177 var tag = loca_tion["name"];178 var pic_url = loca_tion["profile_pic_url"];179 head(container, `${tag}`, null, pic_url, null, nombrePub, null, null, null, true, false, null, true);180 $("title").text(`${tag} sur Instagram ⢠Photos et vidéos`);181 createElements(container, [["class", "yQ0j1"]], "h2", undefined, `<div class="Saeqz">Images et vidéos populaires</div><br>`);182 Posts(top_edges, container, false, null, `${tag}`);183 createElements(container, [["class", "yQ0j1"]], "h2", undefined, `<br><br>Plus récentes<br>`);184 Posts(edges, container, false, null, `${tag}`);185 var center = createElements(container, [], "center"); download_all(center, `Place ${tag} In Instagram Photos and Videos`)186}187function fetchProfile(data, container) {188 var user = data["graphql"]["user"];189 var pic_url_hd = user["profile_pic_url_hd"];190 var pic_url = user["profile_pic_url"];191 var full_name = user["full_name"];192 var username = user["username"];193 var nombrePub = user["edge_owner_to_timeline_media"]["count"];194 var abonnes = user["edge_followed_by"]["count"];195 var abonnements = user["edge_follow"]["count"];196 var is_private = user["is_private"];197 var edges = user["edge_owner_to_timeline_media"]["edges"];198 var biography = user["biography"];199 var hglght_cnt = user["highlight_reel_count"];200 var is_verified = user["is_verified"];201 var ext_url = user["external_url"];202 var has_clips = user["has_clips"];203 var edges_igtv = user["edge_felix_video_timeline"]["edges"];204 head(container, username, full_name, pic_url, pic_url_hd, nombrePub, abonnements, abonnes, biography, is_private, is_verified, ext_url, false);205 $("title").text(`${full_name} (@${username}) sur Instagram ⢠Photos et vidéos`);206 var containerPosts = createElements(container, [["id", "publications"], ["name", "_switcher_"]], "SECTION");207 Posts(edges, containerPosts, is_private, pic_url_hd, username);208 var containerIGTV = createElements(container, [["style", "display: none"], ["id", "igtv"], ["name", "_switcher_"]], "SECTION");209 Posts(edges_igtv, containerIGTV, false, null, username);210 if (edges_igtv.length == 0) {211 createElements(containerIGTV, [["class", "yQ0j1"]], "h1", undefined, `<br><br>IGTV Vide<br>`);212 }213 /*var i_bsnacct = user["is_business_account"];console.log("is_business_account "+i_bsnacct);214 var bus_email = user["business_email"];console.log("business_email "+bus_email);215 var bnss_name = user["business_category_name"];console.log("business_category_name "+bnss_name);216 var ctegoenum = user["category_enum"];console.log("category_enum "+ctegoenum);217 var isjoincent = user["is_joined_recently"];console.log("is_joined_recently "+isjoincent);218 var cuntrlock = user["country_block"];console.log("country_block "+cuntrlock);*/219}220function fetchStory(a) {221 alert("Story ! Soon");222}223function create_comment(pere, node) {224 var node_text = node["text"];// @ihssanebenalluch â¥â¥â¥225 var node_created_at = node["created_at"];// 1493553551226 var date_cmmnt = new Date(node_created_at * 1000);227 var node_owner = node["owner"];// Object228 var owner_is_verified = node_owner["is_verified"];// false229 var owner_profile_pic_url = node_owner["profile_pic_url"];230 var owner_username = node_owner["username"];// maryamsalmouni231 var node_edge_liked_by = node["edge_liked_by"];// Object232 var edge_liked_by_count = node_edge_liked_by ? node_edge_liked_by["count"] : 0;// 1233 var _XfOJU5NKVDB = createElements(pere, [[`role`, `button`], [`class`, `ZyFrc`], [`tabindex`, `0`]], `DIV`);234 var _MkOuO9Bgy9i = createElements(_XfOJU5NKVDB, [[`class`, `gElp9 rUo9f`], [`role`, `menuitem`]], `LI`);235 var _U32C4bJPn4U = createElements(_MkOuO9Bgy9i, [[`class`, `P9YgZ`]], `DIV`);236 var _joHmZVmhFPE = createElements(_U32C4bJPn4U, [[`class`, `C7I1f`]], `DIV`);237 var _DnQwsLyFWeR = createElements(_joHmZVmhFPE, [[`class`, `Jv7Aj mArmR pZp3x`]], `DIV`);238 var _Ld9NahDxPOQ = createElements(_DnQwsLyFWeR, [[`class`, `RR-M-TKzGu`], [`aria-disabled`, `true`], [`role`, `button`], [`tabindex`, `-1`]], `DIV`);239 var _gZU09Cuhv_B = createElements(_Ld9NahDxPOQ, [[`alt`, `Photo de profil de ${owner_username}`], [`class`, `_2dbep qNELH kIKUG Gai8tTPkdjh7`], [`data-testid`, `user-avatar`], [`draggable`, `false`], [`src`, owner_profile_pic_url]], `IMG`);240 var _mHzoPYg7oc6 = createElements(_joHmZVmhFPE, [[`class`, `C4VMK`]], `DIV`);241 var _WFZDc5Y1BiZ = createElements(_mHzoPYg7oc6, [[`class`, `_6lAjh`]], `H3`);242 var _rmsyjpyilqj = createElements(_WFZDc5Y1BiZ, [[`class`, `Igw0E IwRSHeGOV_ _4EzTm ItkAi`]], `DIV`);243 var _o0YFe4f6BaP = createElements(_rmsyjpyilqj, [[`class`, `Jv7Aj mArmR MqpiF`]], `SPAN`);244 var _iUcWb77Di_0 = createElements(_o0YFe4f6BaP, [[`class`, `sqdOP yWX7d _8A5w5 ZIAjV`], [`onclick`, `constroctur("@${owner_username}")`], [`tabindex`, `0`]], `A`, `${owner_username}`);245 if (owner_is_verified) {246 var divBadge = createElements(_o0YFe4f6BaP, [["class", "Igw0E IwRSH eGOV_ _4EzTm soMvl"]], "div");247 createElements(divBadge, [["class", "mTLOB Szr5J coreSpriteVerifiedBadge"], ["title", "Vérifié"]], "span", "Vérifié");248 }249 var _IaSC1t_TVkk = createElements(_mHzoPYg7oc6, [[`class`, ``]], `SPAN`, undefined, text2Html(node_text));250 var _2Hu7CfW6lbI = createElements(_mHzoPYg7oc6, [[`class`, `Igw0E IwRSHeGOV_ _4EzTm pjcA_ aGBdT`]], `DIV`);251 var _vLiiOMHob1c = createElements(_2Hu7CfW6lbI, [[`class`, `_7UhW9PIoXz MMzan _0PwGv uL8Hv`]], `DIV`);252 var _NV_IkBgqQol = createElements(_vLiiOMHob1c, [[`class`, `FH9sR Nzb55`], [`datetime`, date_cmmnt.toJSON()], [`title`, date_cmmnt.toLocaleDateString()]], `TIME`, date_cmmnt.toLocaleString());253 var _2JKkqm5QEPS = createElements(_vLiiOMHob1c, [], `BR`);254 node_edge_liked_by ? createElements(_vLiiOMHob1c, [[`class`, `FH9sR`]], `SPAN`, `${edge_liked_by_count} mentions Jâaime`) : 0;255 var _2JKkqm5QEPS = createElements(pere, [], `BR`);256 // var node_did_report_as_spam = node["did_report_as_spam"];// false257 // var node_id = node["id"];// 17879582911043274258 // var node_viewer_has_liked = node["viewer_has_liked"];// false259 // var node_is_restricted_pending = node["is_restricted_pending"];// false260 // var node_edge_threaded_comments = node["edge_threaded_comments"];// Object261 // var edge_threaded_comments_count = node_edge_threaded_comments["count"];// 0262 // var edge_threaded_comments_page_info = node_edge_threaded_comments["page_info"];// Object263 // var edge_threaded_comments_edges = node_edge_threaded_comments["edges"];// Array264 // var page_info_has_next_page = edge_threaded_comments_page_info["has_next_page"];// false265 // var page_info_end_cursor = edge_threaded_comments_page_info["end_cursor"];// Object266}267function circularpic(pere, full_name, profile_pic_url) {268 var line066 = createElements(pere, [['class', "XjzKX"]], 'div');269 var line067 = createElements(line066, [['class', "RR-M- "], ["aria-disabled", "true"], ["role", "button"], ["tabindex", "-1"], ["data-ext-skip", "1"]], 'div');270 var size = 150;271 var line068 = createElements(line067, [['class', "CfWVH"], ["height", "168"], ["width", "168"], ["style", "position: absolute; top: -9px; left: -9px; width: 168px; height: 168px;"]], 'canvas');272 var line070 = createElements(line067, [['class', "_2dbep"], ["role", "link"], ["tabindex", "-1"], ["style", "width: " + size + "px; height: " + size + "px;"]], 'div');273 var line071 = createElements(line070, [["alt", "Photo de profil de " + full_name], ["class", "_6q-tv"], ["data-testid", "user-avatar"], ["draggable", "false"], ["src", profile_pic_url]], "img");274}275function head(container, username, full_name, profile_pic_url, profile_pic_url_hd, nombrePub, abonnements, abonnes, biography, is_private, is_verified, ext_url, modaal) {276 var line065 = createElements(container, [['class', "vtbgv"]], 'header');277 var line075 = createElements(line065, [["class", "zwlfE"]], "section");278 circularpic(line075, full_name, profile_pic_url);279 var line076 = createElements(line075, [["class", "nZSzR"]], "div");280 !modaal ? createElements(line076, [["class", "_7UhW9 fKFbl yUEEX KV-D4 fDxYl"], ["href", "https://www.instagram.com/" + username + "/"], ["target", "_blank"]], "a", username) :281 createElements(line076, [["class", "_7UhW9 fKFbl yUEEX KV-D4 fDxYl"], ["onclick", "constroctur('" + username + "')"]], "p", username);282 if (is_verified) {283 var divBadge = createElements(line076, [["class", "Igw0E IwRSH eGOV_ _4EzTm soMvl"]], "div");284 createElements(divBadge, [["class", "mTLOB Szr5J coreSpriteVerifiedBadge"], ["title", "Vérifié"]], "span", "Vérifié");285 }286 var line124 = createElements(line075, [["class", "k9GMp"]], "ul");287 var line125 = createElements(line124, [["class", "Y8-fY"]], "li");288 var line126 = createElements(line125, [["class", "-nal3"]], "span");289 createElements(line126, [["class", "g47SY"]], "span", beautify_numbers(nombrePub));290 createElements(line126, [], "span", " publications");291 createElements(line126, [], "br");292 if (abonnes) {293 var line130 = createElements(line124, [["class", "Y8-fY"]], "li");294 var line131 = createElements(line130, [["class", "-nal3"], ["tabindex", "0"]], "p");295 createElements(line131, [["class", "g47SY"]], "span", size_plain(abonnes));296 createElements(line131, [], "span", " abonnés");297 createElements(line131, [], "br");298 }299 if (abonnements) {300 var line135 = createElements(line124, [["class", "Y8-fY"]], "li");301 var line136 = createElements(line135, [["class", "-nal3"], ["tabindex", "0"]], "p");302 createElements(line136, [["class", "g47SY"]], "span", size_plain(abonnements));303 createElements(line136, [], "span", " abonnements");304 createElements(line136, [], "br");305 }306 var line141 = createElements(line075, [["class", "-vDIg"]], "div");307 if (full_name) {308 var line142 = createElements(line141, [["class", "rhpdm"]], "h1", full_name + "\n");309 }310 if (biography) {311 var biography2 = text2Html(biography);312 var line142 = createElements(line141, [], "span", undefined, biography2);313 var Lia = createElements(line141, [["class", "yLUwa"], ["href", ext_url], ["target", "_blank"]], "a", ext_url);314 }315 if (!is_private) { bar(container, username); }316}317function Posts(edges, container, is_private, profile_pic_url_hd, username) {318 var Poston = PostsCon(container);319 AllPosts(edges)320 if (!is_private) {321 var edgeslength = edges.length;322 var columns = 3;323 var r = edgeslength % columns;324 var q = (edgeslength - r) / columns;325 var p = returnpub(Poston);326 for (var i = 0; i < q; i++) {// q*i+k327 var kposts = createElements(p, [["class", "Nnq7C weEfm"]], "div");328 for (var k = 0; k < columns; k++) {329 var current = columns * i + k;330 var edge_i = edges[current]["node"];331 post(edge_i, kposts, current);332 }333 }334 if (r != 0) {335 var kposts = createElements(p, [["class", "Nnq7C weEfm"]], "div");336 for (var k = q * columns; k < q * columns + r; k++) {337 var edge_i = edges[k]["node"];338 post(edge_i, kposts, k);339 }340 for (var j = q * columns + r; j < (q + 1) * columns; j++) {341 var current = q * columns + r - 1;342 var edge_i = edges[current]["node"];343 post(edge_i, kposts, j, true);344 }345 }346 !!profile_pic_url_hd ? pdp(p, profile_pic_url_hd, username, false) : null;347 } else {348 returnprv(Poston, profile_pic_url_hd, username);349 }350}351function post(edgei, sup, index, vide = false) {352 if (!vide) {353 var caption = edgei["accessibility_caption"];354 var rss = edgei["thumbnail_resources"];355 var thumb = edgei["thumbnail_src"];356 var shortcode = edgei["shortcode"];357 var product_type = edgei["product_type"];358 var __typename = edgei["__typename"];359 var icon = icons[(product_type == "feed" || !product_type) ? __typename : product_type];360 var line213 = getLine213(sup, icon);361 var line214 = createElements(line213, [["alt", caption]/*,["id","No"+index]*/, ["class", "FFVAD"], ["decoding", "auto"], ["style", "object-fit: cover;"], ["sizes", "293px"], ["src", thumb], ["onclick", `PostClicked('${shortcode}')`]], "img");362 }363 else { createElements(sup, [["class", "_bz0w"]], "div"); }364}365function getLine213(sup, type) {366 var line210 = createElements(sup, [["class", "v1Nh3 kIKUG _bz0w"]/*,["data-ext-skip","1"]*/], "div");367 var line211 = createElements(line210, [["tabindex", "0"]], "a");368 var line212 = createElements(line211, [["class", "eLAPa"]], "div");369 var line213 = createElements(line212, [["class", "KL4Bh"]], "div");370 // createElements(line212, [["class", "_9AhH0"],["style",'style="cursor:pointer"']], "div");371 if (type) {372 var wtrmark = createElements(line211, [["class", "u7YqG"]], "div");373 createElements(wtrmark, [["class", `mediatypesSprite${type}__filled__32 u-__7`]], "div");374 }375 return line213;376}377function returnpub(father) {378 var public1 = createElements(father, [], "div");379 var public2 = createElements(public1, [["style", "flex-direction: column; padding-bottom: 15px; padding-top: 0px;"]], "div");380 return public2;381}382function returnprv(father, profile_pic_url_hd, username) {383 var p = createElements(father, [["class", "_4Kbb_ _54f4m"]], "div");384 var privat2 = createElements(p, [["class", "QlxVY"]], "div")385 var privat2_1 = createElements(privat2, [["class", "rkEop"]], "h2", "Ce compte est privé");386 var privat2_2 = createElements(privat2, [["class", "VIsJD"]], "div", "Abonnez-vous pour voir ses photos et vidéos.");387 pdp(p, profile_pic_url_hd, username, true);388}389function PostsCon(container) {390 var line204 = createElements(container, [["class", "_2z6nI"]], "div");391 var line205 = createElements(line204, [["class", "ySN3v"]], "article");392 return line205;393}394function ReturnContainer(id) {395 var divtoreplace = document.getElementById(id);396 var perereplaceable = divtoreplace.parentElement;397 perereplaceable.removeChild(divtoreplace);398 var line064 = createElements(perereplaceable, [['class', "v9tJq AAaSh VfzDr"], ["id", id]], 'div');399 return line064;400}401function bar(container, username) {402 var line185 = createElements(container, [["class", "fx7hk"]], "div");403 elementbar(line185, true, "publications", "Publications", pubs, username);404 elementbar(line185, false, "igtv", "IGTV", igtvpath, username);405}406function elementbar(pere, courant, afusm, txtlabel, d, username) {407 var class186, class187, fill188, list189, class192;408 if (courant) {409 class186 = "_9VEo1 T-jvg"; class187 = "smsjF"; fill188 = "#262626";410 list189 = [["fill-rule", "evenodd"], ["clip-rule", "evenodd"]]; class192 = "PJXu4";411 }412 else {413 class186 = "_9VEo1"; class187 = "qzihg"; fill188 = "#8e8e8e";414 list189 = []; class192 = "_08DtY";415 }416 var line186 = createElements(pere, [["class", class186], ["tabindex", "0"]], "p");417 var line187 = createElements(line186, [["class", class187]], "span");418 var line188 = createElementsNS(line187, [["class", "_8-yf5"], ["height", "24"], ["width", "24"], ["viewBox", "0 0 48 48"], ["fill", fill188], ["aria-label", txtlabel]], "svg");419 var line189 = createElementsNS(line188, [["d", d]].concat(list189), "path");420 var line192 = createElements(line187, [["class", "PJXu4"], ["onclick", `change_onglet(this,'${afusm}')`]], "span", txtlabel);421}422function change_onglet(html_, id) {423 var grand_pere = html_.parentNode.parentNode;424 $(".T-jvg").removeClass("T-jvg"); grand_pere.classList.add("T-jvg");425 $("[name='_switcher_']").hide();426 $(`#${id}`).show();427}428function pdp(p, profile_pic_url_hd, username, is_private) {429 var kposts = createElements(p, [["class", "Nnq7C weEfm"]], "div");430 var line213 = getLine213(kposts);431 var center = createElements(line213, [], "center");432 createElements(center, [["alt", "profile_pic_url_hd"], ["decoding", "auto"], ["src", profile_pic_url_hd]], "img");433 createElements(center, [], "br");434 createElements(center, [["onclick", "download('" + profile_pic_url_hd + "','" + username + "')"], ["name", "download"]], 'button', undefined, '<i class="fa fa-download"></i>Download');435 createElements(center, [], "br");436 !is_private ? download_all(center, `Instagram user ${username} In Instagram Photos and Videos`) : null;437}438var All_Posts = []; var Un_Post = [];439function slick() { $('.slider').slick(withoutResponsive); };440PostClicked = shortcode => _gt_(`https://www.instagram.com/p/${shortcode}?__a=1`, "£", shortcode, "divModaltoreplace", "Instagram Post", fetchFeedPost);441getmn = d => Math.round(d / 60);442PhotoOrVid = sh => {443 var url = getLink(sh);444 return !sh["is_video"] ? `<img src="${url}" alt="">` : `<video controls="" onloadstart="this.volume=0.5"><source src="${url}" type="video/mp4"></video>`;445}446getLink = node => {447 var disp_rs = node["display_resources"];448 var thum_rs = node["thumbnail_resources"];449 var display_url = node["display_url"];450 var is_video = node["is_video"];451 var video_url = node["video_url"];452 var HD = !!disp_rs ? disp_rs : thum_rs;453 HD = !!HD ? HD[HD.length - 1].src : display_url;454 return (is_video && video_url) ? video_url : HD;455}456function Coller() {457 navigator.clipboard.readText()458 .then(text => { constroctur(text); })459 .catch(err => { alert('Failed to read clipboard contents : ' + err); });460}461function show_modal(disp) {462 disp ? $("#ModalPost").show() : $("#ModalPost").hide();463 $(`#divModaltoreplace`).children().remove();464}465function _gt_(url, code, pop, id, rel, func) {466 fetch(url)467 .then((data) => {console.log(data)468 var container = ReturnContainer(id);469 show_modal(id!="divtoreplace");470 $('#url').val(`${code}${pop}`);471 func(data,container);472 })473 $.get(url, {mode:'no-cors'})474 .done(function (data) {475 476 })477 .fail(function () {478 alert(`${rel} ${pop} was not found!`)479 });480}481function getThumbail(a, id) {482 var container = ReturnContainer(id);483 $("#url").val(`$${a}`);484 fetchThumbnail(a, container);485}486function constroctur(input) {487 input = input.trim(); All_Posts = [];488 var ig = `instagram.com/`; var yt = `youtube.com`; var ytb = `youtu.be/`;489 var rx1 = `[a-zA-Z0-9\-_\.]{2,}`, rx2 = `[\u0600-\u06FFa-zA-Z0-9\-_\.]{2,}`;490 var ends = `[\/,?]`;491 var definitions =492 [493 {494 code: "§", rel: "STORY INSTA", _u: true,495 func: _gt_, funct: fetchStory,496 base_url: `https://www.${ig}`,497 matches: [RegExp(`${ig}stories/(.*)${ends}`), /§(\d*)/]498 }499 , {500 code: "*", rel: "IGTV POST", _u: true,501 func: _gt_, funct: fetchFeedPost,502 base_url: `https://www.${ig}tv/`,503 matches: [RegExp(`${ig}tv/(${rx1})${ends}`), /\*(.*)/]504 }505 , {506 code: "~", rel: "REEL POST", _u: true,507 func: _gt_, funct: fetchFeedPost,508 base_url: `https://www.${ig}reel/`,509 matches: [RegExp(`${ig}reel/(${rx1})${ends}`), /~(.*)/]510 }511 , {512 code: "£", rel: "POST_FEED INSTA", _u: true,513 func: _gt_, funct: fetchFeedPost,514 base_url: `https://www.${ig}p/`,515 matches: [RegExp(`${ig}p/(${rx1})${ends}`), RegExp(`£(${rx1})`)]516 }517 , {518 code: "â¬", rel: "LOCATIONS INSTA", _u: true,519 func: _gt_, funct: fetchLocation,520 base_url: `https://www.${ig}explore/locations/`,521 matches: [/â¬(.*)/]522 }523 , {524 code: "#", rel: "HASHTAG INSTA", _u: true,525 func: _gt_, funct: fetchHashtag,526 base_url: `https://www.${ig}explore/tags/`,527 matches: [RegExp(`#(${rx2})`)]528 }529 , {530 code: "@", rel: "USERNAME ISTAGRAM", _u: true,531 func: _gt_, funct: fetchProfile,532 base_url: `https://www.${ig}`,533 matches: [534 RegExp(`${ig}(${rx1})${ends}`),535 /^(?!.*\.\.)(?!.*\.$)[^\W][\w.]{1,}$/, RegExp(`@(${rx1})`)536 ]537 }538 , {539 code: "$", rel: null, _u: false,540 func: getThumbail, funct: null,541 base_url: ``,542 matches: [RegExp(`${yt}.*(v=|\/embed\/)(.{11})`), RegExp(`${ytb}(.{11})`), /\$(.{11})/]543 }544 ];545 var comp = definitions.find(u => u["matches"].reduce((a, b) => input.match(b) ? a + 1 : a, 0));546 var mches = comp.matches;547 var mss = mches.find(i => input.match(i));548 if (mss) {549 var rel = comp.rel; var code = comp.code;550 var shortcode = input.match(mss).pop();551 var link = comp.base_url + shortcode;552 link += comp._u ? '?__a=1' : '';553 var fonction = comp.func;554 var fonctiot = comp.funct;555 fonctiot ? fonction(link, code, shortcode, "divtoreplace", rel, fonctiot) : fonction(shortcode, "divtoreplace");556 }557}558function download_multiple(post, TextMark) {559 var elements = !!post ? Un_Post : All_Posts.filter(item => !item.is_video);560 var cPhotos = elements.filter(item => !item.is_video).length;561 var cVideos = elements.filter(item => item.is_video).length;562 var cElemts = elements.length;563 var confirmText = "Download " + cElemts + " elements (" + cPhotos + " photos";564 cVideos != 0 ? confirmText += " and " + cVideos + " videos) ?" : confirmText += ") ?";565 // var username__ = "";566 if (confirm(confirmText)) {567 var zip = new JSZip();568 elements.forEach(function (item, index) {569 var link_down = item["linkDownload"];570 // username__ = item["owner"]? `${item["owner"]} `:"Instagram ";571 JSZipUtils.getBinaryContent(link_down,572 function (err, data) {573 if (err) {574 if (!(err.code === 404 || err.code === 410)) {575 alert(`error code ${err.code}`);576 }577 } else {578 zip.file(GetFilename(link_down), data, { binary: true });579 }580 }, xhrsStatus, timeoutDefault581 );582 /*setTimeout(function () {583 download(item["linkDownload"],item["owner"],(index+1));584 }, 1500*(index+1))*/585 });586 $("#ModalDownload").show();587 setTimeout(function () {588 zip.generateAsync({ type: "blob" },589 function (meta) {590 var file_curr = meta["currentFile"];591 var percent = Math.floor(meta["percent"]);592 var elemnt = $("#progressBar");593 var strpct = `${percent}%`;594 elemnt.width(strpct);595 elemnt.text(strpct);596 $("#currentFile").text(file_curr);597 if (!file_curr) {598 $("#currentFile").text("Zipping complete !");599 setTimeout(function () {600 $("#ModalDownload").hide();601 }, 300)602 }603 })604 .then(function (content) {605 var date = new Date();606 saveAs(content, `${TextMark + " " + get_daba()}.zip`);607 });608 }, 1000)609 }610}611function toDataURL(url) {612 return fetch(url).then((response) => {613 return response.blob();614 }).then(blob => {615 return URL.createObjectURL(blob);616 });617}618function GetFilename(url) {619 if (url) {620 var m = url.toString().match(/.*\/(.+?\.[a-zA-Z0-9]*)/);621 if (m && m.length > 1) {622 return m[1];623 }624 }625 return "";626}627function get_extension(link) {628 var list = link.split("?")[0].split(".");629 return list[list.length - 1];630}631function get_daba() {632 var date = new Date();633 return date.toJSON().replaceAll(/[\-:TZ]/g, "_");634}635function file_name(link, username, index) {636 var daba = get_daba();637 var extension = get_extension(link);638 var numeroPost = index ? ` ${index}` : "";639 var nom = username ? `${username} ` : "";640 return `${nom + daba + numeroPost}.${extension}`;641}642async function download(link, username, index) {643 var a = document.createElement("a");644 a.href = await toDataURL(link);645 a.download = file_name(link, username, index);646 document.body.appendChild(a);647 a.click();648 document.body.removeChild(a);649}650function twitch() {651 var tags = $("#tagsclass"); var classtags = "fTh_a plVq-";652 tags.hasClass(classtags) ? tags.removeClass(classtags) : tags.addClass(classtags)653}654function AllPosts(edges) {655 edges.forEach(function (item, index) {656 var node = item["node"];657 var __typename = node["__typename"];658 var username = node["owner"]["username"];659 var edges_children = node["edge_sidecar_to_children"];660 if (__typename != "GraphSidecar" || !edges_children) {661 var is_video = node["is_video"];662 var linkDownload = getLink(node);663 var oMedia = { "is_video": is_video, "linkDownload": linkDownload, "owner": username };664 All_Posts.push(oMedia);665 }666 else {667 var edges1 = edges_children["edges"];668 edges1.forEach(function (item1, index) {669 var node1 = item1["node"];670 var username1 = node1["owner"]["username"];671 var is_video = node1["is_video"];672 var linkDownload = getLink(node1);673 var oMedia = { "is_video": is_video, "linkDownload": linkDownload, "owner": username };674 All_Posts.push(oMedia);675 });676 }677 });678}679function text2Html(text) {680 var ushg = /[#,@][\u0600-\u06FFa-zA-Z0-9\-_\.]{1,}/gi;681 var m_ai = /[a-zA-Z0-9._-]{1,}@[a-zA-Z0-9._-]{1,}\.[a-zA-Z0-9._-]{2,3}/gi;682 return text.replaceAll(m_ai, item => link_(item, true))683 .replaceAll(ushg, item => link_(item, false))684 .replaceAll(/\n/gi, "<br>");685}686function link_(item, email) {687 var mail = !email ? ` onclick="constroctur('${item}')"` : ``;688 return `<a class="notranslate"${mail} tabindex="0">${item}</a>`689}690function ext(data) {691 data.forEach(function (item, index) {692 $(".slider").slick("slickAdd", PhotoOrVid(item["node"]));693 });694}695function beautify_numbers(number) {696 var str = "" + number; var list = str.split('');697 return list.reverse().reduce((b, a, index) => index % 3 != 0 || index == 0 ? a + b : a + ` ${b}`, "");698}699function size_plain(number) {700 var i = 3; var div = 1024; var return_text = "";701 while (number >= div && i >= 0) {702 number = number / div; i -= 1; div = 1000;703 }704 number = Math.ceil(number * 100) / 100;705 if (i == 3) { return_text = number + " "; } else if (i == 2) { return_text = number + " " + "k"; }706 else if (i == 1) { return_text = number + " " + "m"; } else if (i == 0) { return_text = number + " " + "B"; }707 return return_text;708}709function createElements(parent, liste, name, innerText, innerHTML) {710 var node = document.createElement(name);711 if (liste.length != 0) {712 for (var i = 0; i < liste.length; i++) {713 node.setAttribute(liste[i][0], liste[i][1]);714 }715 }716 if (innerText) { node.innerText = innerText; }717 if (innerHTML) { node.innerHTML = innerHTML; }718 parent.append(node); return node;719}720function createElementsNS(parent, liste, name, innerText, innerHTML) {721 var node = document.createElementNS(ns, name);722 if (liste.length != 0) {723 for (var i = 0; i < liste.length; i++) {724 node.setAttribute(liste[i][0], liste[i][1]);725 }726 }727 if (innerText) { node.innerText = innerText; }728 if (innerHTML) { node.innerHTML = innerHTML; }729 parent.appendChild(node); return node;730}731function createbyjquery(parent, object, name, innerText, innerHTML) {732 var node = $(`<${name}>`);733 Object.keys(object).forEach(function (key) {734 node.attr(key, object[key]);735 })736 innerText ? node.text(innerText) : "";737 innerHTML ? node.html(innerHTML) : "";738 node.appendTo($(`${parent}`)); return node;739}740function download_all(center, Text) {741 createElements(center, [["onclick", `download_multiple(false,"${Text}")`], ["name", "download"]], 'button', undefined, '<i class="fa fa-download"></i>Download All')742}743function Cleartext() { $('#url').val(""); }744function returnDeviceInfos() {745 var w = screen.width;746 var h = screen.height;747 var ratio = window.devicePixelRatio || 1;748 var w1 = screen.width * ratio;749 var h1 = screen.height * ratio;750 var txt = 'w = ' + w + '\n' + 'h = ' + h + '\n' + 'ratio = ' + ratio + '\n' + 'w1 = ' + w1 + '\n' + 'h1 = ' + h1 + '\n';...
hello_controller.js
Source:hello_controller.js
...3import './tablemanager.js';4document.addEventListener('DOMContentLoaded', function () {5 document.querySelector('#search_form').addEventListener('submit', function (e) {6 e.preventDefault();7 let btnSpinner = createElements('span', ['spinner-border', 'spinner-border-sm'], [8 ["role", "status"],9 ['aria-hidden', "true"]10 ]);11 let formBtn = document.querySelector('button.btn-primary');12 formBtn.textContent = "";13 formBtn.setAttribute('disabled', 'disabled');14 formBtn.append(btnSpinner, "Loading...");15 let tableSpinner = createElements('span', ['visually-hidden'], [], "Loading...");16 let tableBody = document.querySelector('.materiel-container tbody');17 if (tableBody) {18 tableBody.textContent = "";19 tableBody.classList.add('spinner-border');20 tableBody.setAttribute('role', 'status');21 tableBody.append(tableSpinner);22 }23 let xhr = new XMLHttpRequest();24 xhr.onload = function (e) {25 if (this.readyState === 4) {26 if (this.status === 200) {27 let response = JSON.parse(this.response);28 if (response.status == 'success') {29 renderingHtml(response.materiels);30 $('.tablemanager').tablemanager({31 firstSort: [32 [3, 0],33 [2, 0],34 [1, 'asc']35 ],36 disable: ["last"],37 appendFilterby: true,38 dateFormat: [39 [4, "mm-dd-yyyy"]40 ],41 debug: true,42 vocabulary: {43 voc_filter_by: 'Filtrer par',44 voc_type_here_filter: 'Filtre...',45 voc_show_rows: 'Eléments par page'46 },47 pagination: true,48 showrows: [5, 10, 20, 50, 100],49 disableFilterBy: [1]50 });51 }52 } else {53 console.warn('erreur + traitement')54 }55 } else {56 console.warn('erreur + traitement');57 }58 }59 xhr.open('POST', window.location.origin + "/", true);60 xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');61 xhr.send(new FormData(e.target));62 });63 // Traitement de données reçu de l'API64 function renderingHtml(materiels) {65 let materielsContainer = document.querySelector('.materiel-container');66 let formBtn = document.querySelector('button.btn-primary');67 if (materiels.length > 0) {68 let table = createElements('table', ['table', 'table-striped', 'table-hover', 'tablemanager']);69 let th_materielId = createElements('th', [], [70 ['scope', 'col']71 ], 'materiel_id');72 let th_nomCourt = createElements('th', [], [73 ['scope', 'col']74 ], 'nom_court');75 let th_marque = createElements('th', [], [76 ['scope', 'col']77 ], 'marque');78 let th_prixPublic = createElements('th', [], [79 ['scope', 'col']80 ], 'prix_public');81 let th_referenceFabricant = createElements('th', [], [82 ['scope', 'col']83 ], 'reference_fabricant');84 let th_TypeFamille = createElements('th', [], [85 ['scope', 'col']86 ], 'Type > famille');87 let th_TypeNom = createElements('th', [], [88 ['scope', 'col']89 ], 'Type > nom');90 let th_TypeMetierNom = createElements('th', [], [91 ['scope', 'col']92 ], 'Type > metier > nom ');93 let tr_head = createElements('tr');94 tr_head.append(th_materielId, th_nomCourt, th_marque, th_prixPublic, th_referenceFabricant, th_TypeFamille, th_TypeNom, th_TypeMetierNom);95 let thead = createElements('tHead');96 thead.append(tr_head);97 table.append(thead);98 let tbody = createElements('tBody');99 materiels.forEach(materiel => {100 let td_materielId = createElements('td', [], []);101 let linkMaterielDetails = createElements('a', ['tooltiped'], [102 ['href', `${window.location.origin}/materiel/${materiel.materiel_id}`],103 ['data-bs-toggle', 'tooltip'],104 ['data-bs-placement', 'top'],105 ['title', 'Cliquez pour voir les détails de ce produit']106 ], materiel.materiel_id);107 td_materielId.append(linkMaterielDetails);108 let td_nomCourt = createElements('td', [], [], materiel.nom_court);109 let td_marque = createElements('td', [], [], materiel.marque);110 let td_prixPublic = createElements('td', [], [], materiel.prix_public);111 let td_referenceFabricant = createElements('td', [], [], materiel.reference_fabricant);112 let td_TypeFamille = createElements('td');113 if ('super-materiel' == materiel.type.famille) {114 let linkSuperMateriel = createElements('a', ['tooltiped'], [115 ['href', `${window.location.origin}/super-materiels/${materiel.materiel_id}`],116 ['data-bs-toggle', 'tooltip'],117 ['data-bs-placement', 'top'],118 ['title', 'Ce produit est lié à d\'autres produits cliquez pour voir d\'éventuelles listes']119 ], materiel.type.famille);120 td_TypeFamille.append(linkSuperMateriel);121 } else {122 td_TypeFamille.textContent = materiel.type.famille;123 }124 let td_TypeNom = createElements('td', [], [], materiel.type.nom);125 let td_TypeMetierNom = createElements('td', [], [], materiel.type.metier.nom);126 let tr_body = createElements('tr');127 tr_body.append(td_materielId, td_nomCourt, td_marque, td_prixPublic, td_referenceFabricant, td_TypeFamille, td_TypeNom, td_TypeMetierNom);128 tbody.append(tr_body);129 });130 table.append(tbody);131 formBtn.textContent = "chercher";132 formBtn.removeAttribute('disabled');133 materielsContainer.textContent = "";134 materielsContainer.append(table);135 } else {136 let p = createElements('p', ['mt-4'], [], "Pas de matériels avec les informations demandées");137 formBtn.textContent = "chercher";138 formBtn.removeAttribute('disabled');139 materielsContainer.textContent = "";140 materielsContainer.append(p);141 }142 }143 // Helper function pour créer des éléments de DOM144 function createElements(tag, cls = null, attrs = null, text = null) {145 let elm = document.createElement(tag);146 if (null != cls) {147 if (cls.length > 0) {148 for (let i = 0; i < cls.length; i++) {149 elm.classList.add(cls[i]);150 }151 }152 }153 if (null != attrs) {154 if (attrs.length > 0) {155 for (let i = 0; i < attrs.length; i++) {156 elm.setAttribute(attrs[i][0], attrs[i][1]);157 }158 }...
script.js
Source:script.js
23function createSearchBar(){4 // Title and Tagline creation 5 6 var jumbotron = createElements('div',' bar');7 var h1 = createElements('h1','heading','Recipe World');8 var p = createElements('h2','tagline','Search for your favorite recipe here!!!');9 jumbotron.append(h1,p);10 document.body.append(jumbotron);11 // Searchbar creation 12 var input = createElements('div','input-group mb-3 input-group-prop');13 var searchbar = createElements('input','form-control','','search');14 searchbar.type = "text";15 searchbar.placeholder = "Enter your search here";16 var button = createElements('div','input-group-append button');17 var buttonElement = createElements('button','btn btn-success btn-lg','Search');18 buttonElement.type = "submit";1920 buttonElement.addEventListener('click',generateRecipes);2122 async function generateRecipes(){23 try{24 var keyword = document.getElementById('search');25 var key = keyword.value;26 27 var apiCall = await fetch(`https://api.edamam.com/search?q=${key}&app_id=af780cad&app_key=e50df37710aba4e0a0a66fa06d510f59`);28 var apiData = await apiCall.json();29 var app = apiData.hits;30 var containerCheck = document.getElementById('container');31 var contain = loadcontents(app);32 33 if(containerCheck !== null){34 document.body.replaceChild(contain,containerCheck); 3536 }37 else{38 document.body.append(contain);3940 }41 42 }43 44 catch(err){45 console.log('Data not found'+err);46 } 47 }48 button.append(buttonElement);49 input.append(searchbar,button);50 document.body.append(input);51}5253function loadcontents(app){54 var container = createElements('div','container','','container');55 var col1 = createElements('div','col-lg-12');56 57 app.forEach(data => {58 59 var card = createElements('div','card box');60 var row = createElements('div','row no-gutters');61 var col2 = createElements('div','col-md-8');62 var cardBody = createElements('div','card-body');63 var h2 = createElements('div','card-title')64 var h2element = createElements('h2','',data.recipe.label);65 h2.append(h2element);66 var h5 = createElements('div','card-title');67 var h5element = createElements('h5','','Calories: '+Math.round(data.recipe.calories));68 h5.append(h5element);69 var p = createElements('p','para','Ingredients:');70 var ul = createElements('ul','unorderedList');7172 data.recipe.ingredientLines.forEach(list =>{73 var li = createElements('li','list-type',list);74 ul.appendChild(li);75 });76 var table = createElements('table','card-table table');77 var thead = createElements('thead');78 var tr = createElements('tr');79 var th = createElements('th','','Vitamin');80 var th1 = createElements('th','','Quantity');81 var tbody = createElements('tbody');82 83 tr.appendChild(th);84 tr.appendChild(th1);85 thead.append(tr);8687 var nutrientList = ['ENERC_KCAL','FAT','CA','CHOLE','VITA_RAE','VITC','VITB6A','VITB12','VITD','VITK1'];88 89 var nutrients = data.recipe.totalNutrients;90 91 nutrientList.forEach(list =>{92 var tr1 = createElements('tr');93 var td1 = createElements('td','',(nutrients[list]).label);94 tr1.appendChild(td1);95 var td2 = createElements('td','',Math.round((nutrients[list]).quantity)+' '+(nutrients[list]).unit);96 tr1.appendChild(td2);97 tbody.appendChild(tr1);98 }) 99 100 101 table.append(thead,tbody);102 cardBody.append(h2,h5,p,ul,table);103 col2.append(cardBody);104 105 106 var col3 = createElements('div','col-md-4');107 var img = createElements('img','card-img');108 img.src = data.recipe.image;109 var icons = createElements('div','icons');110 111 data.recipe.healthLabels.forEach(list =>{112 var span = createElements('span','badge badge-pill badge-success badges',list);113 114 icons.appendChild(span); 115 })116 117 var hr = createElements('hr');118 var hr1 = createElements('hr');119120 var link = createElements('a','btn btn-success link-success','Recipe-Link');121 link.href = data.recipe.url;122 link.target="blank";123124 col3.append(img,hr,link,hr1,icons);125 row.append(col2,col3);126 card.append(row);127 col1.append(card);128129 });130131132 container.append(col1);133 return container;134}135136137138function createElements(elem,elemclass="",value="",elemid=""){139 var element = document.createElement(elem);140 element.setAttribute('class',elemclass);141 element.innerHTML = value;142 element.setAttribute('id',elemid);143 return element;144}145
...
app.js
Source:app.js
...18// когаÑо Ñе заÑеди ÑÑÑаниÑаÑа19window.addEventListener('load', () => recipesList());20// ÑÑнкÑиÑ, коÑÑо пÑиема Ñип на елеменÑа, аÑÑибÑÑи, и ÑÑдÑÑжание21// ÑÑнкÑиÑ, коÑÑо ÑÑздава елеменÑи22function createElements(type, attributes, ...content) {23 // ÑÑздава елеменÑа Ð¾Ñ ÑÑоÑвеÑÐ½Ð¸Ñ Ñип24 let createElementFromType = document.createElement(type);25 for (let [attr, value] of Object.entries(attributes || {})) {26 if (attr.substring(0, 2) == 'on') {27 createElementFromType.addEventListener(attr.substring(2).toLocaleLowerCase(), value);28 } else {29 createElementFromType[attr] = value;30 }31 }32 // пÑовеÑка дали ÑÑдÑÑжаниеÑо не е маÑив33 content = content.reduce((acc, c) => acc.concat(Array.isArray(c) ? c : [c]), []);34 content.forEach(e => {35 if (typeof e === 'string' || typeof e === 'number') {36 let node = document.createTextNode(e);37 createElementFromType.appendChild(node);38 } else {39 createElementFromType.appendChild(e);40 }41 });42 return createElementFromType;43}44function createPreview(reciepe) {45 let resultElement = createElements('article', { className: 'preview' },46 createElements('div', { className: 'title' }, createElements('h2', {}, reciepe.name)),47 createElements('div', { className: 'small' }, createElements('img', { src: reciepe.img }))48 );49 resultElement.addEventListener('click', () => getDetails(reciepe._id,resultElement));50 return resultElement;51}52async function getDetails(id,preview) {53 let reciepeUrl = `http://localhost:3030/jsonstore/cookbook/details/${id}`;54 let response = await fetch(reciepeUrl);55 let data = await response.json();56 console.log(data);57// ÑÑздаване на каÑÑиÑкаÑа Ñ Ð¸Ð½ÑоÑмаÑиÑÑа58 let resultElement = createElements('article', {},59 createElements('h2', {},data.name),60 createElements('div', { className: 'band' },61 createElements('div', { className: 'thumb' }, createElements('img', { src: data.img })),62 createElements('div', { className: 'ingredients' },63 createElements('h3', {}, 'Ingredients:'),64 createElements('ul', {}, data.ingredients.map(i => createElements('li', {}, i)))65 )66 ),67 createElements('div', { className: 'description' },68 createElements('h3', {}, 'Preparation:'),69 data.steps.map(s => createElements('p',{},s))70 )71 72 );73 // Ð·Ð°Ð¼ÐµÐ½Ñ ÑÑаÑÐ¸Ñ ÑезÑлÑÐ°Ñ Ñ Ð½Ð¾Ð²Ð¸Ñ74 preview.parentNode.replaceChild(resultElement,preview);...
poke-dashboard.js
Source:poke-dashboard.js
2const max = 10;3const pokemons = getPokeData(init, max);4const div = document.querySelector('.div');5function creationOfHeader() {6 const header = createElements('header', div, null, null);7 const titleImportant = createElements('h1', header, null, 'Important Pokemons');8 // const dashboard = createElements('a', header, null, 'Dashboard');9 // const list = createElements('a', header, null, 'List');10 divListPokemons();11}12function divListPokemons() {13 const divForList = createElements('div', div, 'divForList', null);14 const titleList = createElements('h2', divForList, null, 'Choose your Pokemon');15 const ulListPokemons = createElements('ul', divForList, null, null);16 const buttonPrev = createElements('button', divForList, null, 'Previous');17 const buttonNext = createElements('button', divForList, null, 'Next');18 pokemons.then((list) => {19 list.results.slice(init, max).forEach((pokemon) => {20 const listImportantPokemons = createElements('li', ulListPokemons, 'pokemons', null);21 const AnchorImportantPokemons = createElements('a', listImportantPokemons, null, `${pokemon.name}`);22 AnchorImportantPokemons.setAttribute('href', `http://127.0.0.1:5500/components/poke-details/?name=${pokemon.name}`);23 buttonNext.onclick = () => nextPokemons(ulListPokemons);24 buttonPrev.onclick = () => prevPokemons(ulListPokemons);25 });26 });27}28function nextPokemons(ulListPokemons) {29 init += 10;30 ulListPokemons.innerText = '';31 getPokeData(init, 10).then((list) => {32 list.results.forEach((pokemon) => {33 const listImportantPokemons = createElements('li', ulListPokemons, 'pokemons', null);34 const AnchorImportantPokemons = createElements('a', listImportantPokemons, null, `${pokemon.name}`);35 AnchorImportantPokemons.setAttribute('href', `http://127.0.0.1:5500/components/poke-details/?name=${pokemon.name}`);36 });37 });38}39function prevPokemons(ulListPokemons) {40 init -= 10;41 ulListPokemons.innerText = '';42 getPokeData(init, 10).then((list) => {43 list.results.forEach((pokemon) => {44 const listImportantPokemons = createElements('li', ulListPokemons, 'pokemons', null);45 const AnchorImportantPokemons = createElements('a', listImportantPokemons, null, `${pokemon.name}`);46 AnchorImportantPokemons.setAttribute('href', `http://127.0.0.1:5500/components/poke-details/?name=${pokemon.name}`);47 });48 });...
dashboard-to-do.js
Source:dashboard-to-do.js
...8 creationTag.innerText = text;9 return creationTag;10};11const createHeader = () => {12 createElements('h1', headerToDoList, 'headerTitle', 'To-Do-List');13};14const divTasks = () => {15 const registerTasks = createElements('div', body, 'registerTasks', null);16 createElements('input', registerTasks, 'inputTasks', null);17 createElements('button', registerTasks, 'buttonEnterTasks', 'Register Task');18 const divList = createElements('div', body, 'divList', null);19 const ulList = createElements('ul', divList, 'ulForList', null);20};21const buttonFunction = () => {22 const buttonEnterTasks = document.querySelector('.buttonEnterTasks');23 buttonEnterTasks.setAttribute('onclick', 'buttonEnterTasks()');24};25const addNewTask = (myList) => {26 const getUl = document.querySelector('.ulForList');27 const liList = createElements('li', getUl, 'liOfTasks', null);28 const liText = createElements('p', liList, `taskID${id}`, `${myList[myList.length - 1]}`);29 const buttonTaskDone = createElements('button', liList, 'buttonDone', 'Done');30 const buttonTaskDelete = createElements('button', liList, 'buttonDelete', 'Delete');31 buttonTaskDone.setAttribute('onclick', `buttonTaskDone(${id})`);32 buttonTaskDelete.setAttribute('onclick', `buttonTaskDelete(${id})`);33 id += 1;34};35const deleteTask = (newArray) => {36 const oldUl = document.querySelector('.ulForList');37 oldUl.innerHTML = '';38 newArray.forEach((string, index) => {39 const newLi = createElements('li', oldUl, 'liOfTasks', null);40 const newTask = createElements('p', newLi, `taskID${id}`, `${newArray[index]}`);41 createElements('button', newLi, 'buttonDone', 'Done');42 const buttonTaskDelete = createElements('button', newLi, 'buttonDelete', 'Delete');43 buttonTaskDelete.setAttribute('onclick', `buttonTaskDelete(${id})`);44 });45};46const doneTask = (taskDone) => {47 const oldUl = document.querySelector('.ulForList');48 oldUl.innerHTML = '';49 taskDone.forEach((string, index) => {50 });51};52const onLoad = () => {53 createHeader();54 divTasks();55 buttonFunction();56};
dom.js
Source:dom.js
...23};24// make random advice25request('/random', 'GET', null, (error, response) => {26 if (error) {27 createElements('p', error, containerResult, 'error');28 } else {29 const searchItem = createElements('div', '', containerResult, 'resultSearch');30 createElements('p', ' Random Advice :) ', searchItem, 'title_advice');31 createElements('p', getSlips(JSON.parse(response).slip), searchItem, 'advice_text');32 }33});34search.addEventListener('click', (e) => {35 e.preventDefault();36 deleteChild(containerResult);37 const newValue = value.value.trim();38 if (!(newValue)) {39 createElements('p', 'Please Write On The Feild Search', containerResult, 'error');40 return '';41 }42 request('/search', 'POST', newValue, (error, response) => {43 value.value = '';44 if (error) {45 createElements('p', error, containerResult, 'error');46 } else {47 const advices = JSON.parse(response);48 if (findMessage(advices)) {49 createElements('p', getMessage(advices), containerResult, 'error');50 } else {51 getAdvice(advices).forEach((slip) => {52 const searchItem = createElements('div', '', containerResult, 'resultSearch');53 createElements('p', 'Advice', searchItem, 'title_advice');54 createElements('p', getSlips(slip), searchItem, 'advice_text');55 });56 }57 }58 });...
index.js
Source:index.js
1import { createElements, render, renderDom} from './element'2// let createElements = require('./element')3import diff from './diff'4import patch from './patch';5let vdom = createElements('ul',{class:'ul'},[6 createElements('li',{class:'li'},['1']),7 createElements('li', { class: 'li' }, ['2']),8 createElements('li', { class: 'li' }, ['3'])9])10let vdom2 = createElements('ul', { class: 'ul-new' }, [11 createElements('li', { class: 'li' }, ['1']),12 createElements('li', { class: 'li' }, ['2']),13 createElements('div', { class: 'li' }, ['t'])14])15let patches = diff(vdom,vdom2) 16let el = render(vdom)17console.log(node)18// ç»å
ç´ æè¡¥ä¸ éæ°æ´æ°è§å¾19patch(el,patches)20// 渲æçå®DOM21renderDom(el,document.querySelector('#app'))22// DOM diff æ¯è¾ä¸¤ä¸ªèæDOMçåºå« 两个对象çåºå«23/**24 * ä½ç¨ï¼æ ¹æ®ä¸¤ä¸ªèæ对象 å建åºè¡¥ä¸patch对象ï¼ç¨æ¥æ´æ°...
Using AI Code Generation
1var assert = require('assert');2var mocha = require('mocha');3describe('Array', function(){4 describe('#indexOf()', function(){5 it('should return -1 when the value is not present', function(){6 assert.equal(-1, [1,2,3].indexOf(4));7 })8 })9})10var assert = require('assert');11var mocha = require('mocha');12describe('Array', function(){13 describe('#indexOf()', function(){14 it('should return -1 when the value is not present', function(){15 assert.equal(-1, [1,2,3].indexOf(4));16 })17 })18})19var assert = require('assert');20var mocha = require('mocha');21describe('Array', function(){22 describe('#indexOf()', function(){23 it('should return -1 when the value is not present', function(){24 assert.equal(-1, [1,2,3].indexOf(4));25 })26 })27})28var assert = require('assert');29var mocha = require('mocha');30describe('Array', function(){31 describe('#indexOf()', function(){32 it('should return -1 when the value is not present', function(){33 assert.equal(-1, [1,2,3].indexOf(4));34 })35 })36})
Using AI Code Generation
1var assert = require('assert');2var expect = require('chai').expect;3describe('Array', function() {4 describe('#indexOf()', function() {5 it('should return -1 when the value is not present', function() {6 assert.equal([1,2,3].indexOf(4), -1);7 });8 });9});10var assert = require('assert');11var expect = require('chai').expect;12describe('Array', function() {13 describe('#indexOf()', function() {14 it('should return -1 when the value is not present', function() {15 assert.equal([1,2,3].indexOf(4), -1);16 });17 });18});19var assert = require('assert');20var expect = require('chai').expect;21describe('Array', function() {22 describe('#indexOf()', function() {23 it('should return -1 when the value is not present', function() {24 assert.equal([1,2,3].indexOf(4), -1);25 });26 });27});28var assert = require('assert');29var expect = require('chai').expect;30describe('Array', function() {31 describe('#indexOf()', function() {32 it('should return -1 when the value is not present', function() {33 assert.equal([1,2,3].indexOf(4), -1);34 });35 });36});37var assert = require('assert');38var expect = require('chai').expect;39describe('Array', function() {40 describe('#indexOf()', function() {41 it('should return -1 when the value is not present', function() {42 assert.equal([1,2,3].indexOf(4), -1);43 });44 });45});46var assert = require('assert');47var expect = require('chai').expect;48describe('Array', function() {49 describe('#indexOf()', function() {50 it('should return -1 when the value is not present', function() {51 assert.equal([1,2,3].indexOf(4), -
Using AI Code Generation
1var Mocha = require('mocha');2var mocha = new Mocha();3mocha.addFile('test.js');4mocha.run(function(failures){5 process.on('exit', function () {6 });7});8var Mocha = require('mocha');9var mocha = new Mocha();10mocha.addFile('test.js');11mocha.run(function(failures){12 process.on('exit', function () {13 });14});15var Mocha = require('mocha');16var mocha = new Mocha();17mocha.addFile('test.js');18mocha.run(function(failures){19 process.on('exit', function () {20 });21});22var Mocha = require('mocha');23var mocha = new Mocha();24mocha.addFile('test.js');25mocha.run(function(failures){26 process.on('exit', function () {27 });28});29var Mocha = require('mocha');30var mocha = new Mocha();31mocha.addFile('test.js');32mocha.run(function(failures){33 process.on('exit', function () {34 });35});36var Mocha = require('mocha');37var mocha = new Mocha();38mocha.addFile('test.js');39mocha.run(function(failures){40 process.on('exit', function () {41 });42});
Using AI Code Generation
1var assert = require('assert');2var Mocha = require('mocha');3var mocha = new Mocha();4var suite = Mocha.Suite.create(mocha.suite, 'My suite');5suite.addTest(new Mocha.Test('My test', function() {6 assert.equal(1, 1);7}));8suite.run(function() {9 console.log('done');10});
Using AI Code Generation
1var assert = require('assert');2var mocha = require('mocha');3var describe = mocha.describe;4var it = mocha.it;5describe('Array', function() {6 describe('#indexOf()', function() {7 it('should return -1 when the value is not present', function() {8 assert.equal([1,2,3].indexOf(4), -1);9 });10 });11});12var assert = require('assert');13var mocha = require('mocha');14var describe = mocha.describe;15var it = mocha.it;16describe('Array', function() {17 describe('#indexOf()', function() {18 it('should return -1 when the value is not present', function() {19 assert.equal([1,2,3].indexOf(4), -1);20 });21 });22});23var assert = require('assert');24var mocha = require('mocha');25var describe = mocha.describe;26var it = mocha.it;27describe('Array', function() {28 describe('#indexOf()', function() {29 it('should return -1 when the value is not present', function() {30 assert.equal([1,2,3].indexOf(4), -1);31 });32 });33});34var assert = require('assert');35var mocha = require('mocha');36var describe = mocha.describe;37var it = mocha.it;38describe('Array', function() {39 describe('#indexOf()', function() {40 it('should return -1 when the value is not present', function() {41 assert.equal([1,2,3].indexOf(4), -1);42 });43 });44});45var assert = require('assert');46var mocha = require('mocha');47var describe = mocha.describe;48var it = mocha.it;49describe('Array', function() {50 describe('#indexOf()', function() {51 it('should return -1 when the
Using AI Code Generation
1var mocha = new Mocha();2var suite = mocha.suite;3suite.addTest(new Test('test', function(){4 assert(true);5}));6mocha.run(function(){7 console.log('done');8});9var mocha = new Mocha();10var suite = mocha.suite;11suite.addTest(new Test('test', function(){12 assert(true);13}));14var runner = mocha.run(function(){15 console.log('done');16});17var reporter = new Mocha.reporters.Base(runner);18var mocha = new Mocha();19var suite = mocha.suite;20suite.addTest(new Test('test', function(){21 assert(true);22}));23var runner = mocha.run(function(){24 console.log('done');25});26var reporter = new Mocha.reporters.Base(runner);27var mocha = new Mocha();28var suite = mocha.suite;29suite.addTest(new Test('test', function(){30 assert(true);31}));32var runner = mocha.run(function(){33 console.log('done');34});35var reporter = new Mocha.reporters.Base(runner);
Using AI Code Generation
1const mocha = require('mocha');2const assert = require('assert');3const { createElements } = mocha;4let elements = createElements({});5assert.equal(elements.length, 2);6assert.equal(elements[0].tagName, 'DIV');7assert.equal(elements[1].tagName, 'DIV');8assert.equal(elements[0].className, 'mocha');9assert.equal(elements[1].className, 'mocha');10assert.equal(elements[0].innerHTML, 'Hello World');11assert.equal(elements[1].innerHTML, 'Hello World');12assert.equal(elements[0].style.display, 'block');13assert.equal(elements[1].style.display, 'none');14assert.equal(elements[0].style.color, 'red');15assert.equal(elements[1].style.color, 'green');16assert.equal(elements[0].style.fontSize, '1.5em');17assert.equal(elements[1].style.fontSize, '2em');18assert.equal(elements[0].style.fontFamily, 'Arial');19assert.equal(elements[1].style.fontFamily, 'Verdana');20assert.equal(elements[0].style.fontWeight, 'bold');21assert.equal(elements[1].style.fontWeight, 'normal');22assert.equal(elements[0].style.textDecoration, 'underline');23assert.equal(elements[1].style.textDecoration, 'none');24assert.equal(elements
Using AI Code Generation
1var m = new Mocha();2m.createElements();3m.createElements();4m.createElements();5var Mocha = function() {6 this.createElements = function() {7 var div = document.createElement('div');8 var p = document.createElement('p');9 var text = document.createTextNode('Hello World!');10 p.appendChild(text);11 div.appendChild(p);12 document.body.appendChild(div);13 }14}15The Mocha class is defined in the mocha.js file and is then used in the test.js file. The createElements() method is called three times in the test.js file to create three div elements. The first two div elements are created using the same Mocha object and the third div element is created using a new Mocha object. The createElements() method is called
Using AI Code Generation
1var Mocha = require('./mocha.js');2var mocha = new Mocha();3var newElement = mocha.createElements('div', 'newDiv', 'newDiv');4document.body.appendChild(newElement);5var Mocha = function() {6};7Mocha.prototype.createElements = function(type, id, className) {8 var element = document.createElement(type);9 element.id = id;10 element.className = className;11 return element;12};13module.exports = Mocha;14var assert = require('assert');15var Mocha = require('./mocha.js');16var mocha = new Mocha();17var newElement = mocha.createElements('div', 'newDiv', 'newDiv');18document.body.appendChild(newElement);19assert.equal(document.getElementById('newDiv').className, 'newDiv');
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!