Best JavaScript code snippet using wpt
index.js
Source:index.js  
1import { useEffect, useState } from "react";2import "./style.css";3import moment from "moment";4import SocketService from "../../library/socket";5import {6  setThreadListing,7  setSingleThread,8  setSingleMessage,9} from "../../library/redux/actions";10import { useDispatch, useSelector } from "react-redux";11import "react-toastify/dist/ReactToastify.css";12// import { toast } from "react-toastify";13// import Back from "../../components/icons/back";14// import Cross from "../../components/icons/cross";15const Header = (props) => {16  const {17    threadsList,18    threadListingType,19    handleBack,20    pageType,21    thread_id,22    setredirect,23    toast,24    actionBar,25  } = props;26  const [threadList, setthreadList] = useState();27  const { chattingWith } = useSelector((state) => state.global);28  let socket,29    fetchLiveChatMessagesEventSub,30    fetchSMSMessagesEventSub,31    isThreadUpdatedEventSub,32    updatedThreadCrmEventEventSub,33    isAliveChatUpdatedEventSub,34    tempMessageId = "";35  const dispatch = useDispatch();36  // console.log(pageType, "pageType");37  useEffect(() => {38    setthreadList(threadsList);39    // eslint-disable-next-line40    socket = SocketService.getInstance();41    socketEventSub();42    return () => {43      fetchLiveChatMessagesEventSub?.unsubscribe();44      fetchSMSMessagesEventSub?.unsubscribe();45      isThreadUpdatedEventSub?.unsubscribe();46      updatedThreadCrmEventEventSub?.unsubscribe();47      isAliveChatUpdatedEventSub.unsubscribe();48    };49    // eslint-disable-next-line50  }, [threadList, thread_id]);51  const socketEventSub = () => {52    fetchLiveChatMessagesEventSub = socket53      ?.fetchLiveChatMessages()54      .subscribe((pushedmessage) => {55        if (parseInt(pageType) === 1) {56          if (parseInt(threadListingType) === 2) {57            let isThreadExist =58              threadList &&59              threadList?.length > 0 &&60              threadList?.find(61                (item) => item.thread_id === pushedmessage.thread_id62              );63            if (64              (!isThreadExist || isThreadExist === {}) &&65              pushedmessage?.created_by === undefined &&66              pushedmessage?.user_id === undefined67            ) {68              // console.log("creating new thread, live chat");69              const createdAt =70                pushedmessage?.newThread?.lastmessage_at ||71                pushedmessage?.newThread?.updated_at ||72                pushedmessage?.newThread?.created_at ||73                moment().valueOf();74              let newThread = {75                phone_mobile: pushedmessage?.newThread?.phone_mobile || "",76                thread_type: pushedmessage?.newThread?.thread_type,77                thread_id: pushedmessage?.newThread?.thread_id,78                org_name: pushedmessage?.newThread?.org_name,79                crm_id: pushedmessage?.newThread?.crm_id,80                alivesecure_key: pushedmessage?.newThread?.alivesecure_key,81                aliveOpentokSession:82                  pushedmessage?.newThread?.aliveOpentokSession || "",83                status: pushedmessage?.newThread?.thread_status,84                status_timestamp: pushedmessage?.newThread?.updated_at,85                timestamp: pushedmessage?.newThread?.created_at,86                created_by: pushedmessage?.created_by,87                assignedTo: pushedmessage?.newThread?.assignedTo || "0",88                phone_number: pushedmessage?.newThread?.phone_mobile || "",89                smsblocked: pushedmessage?.newThread?.user_blocked90                  ? pushedmessage?.newThread?.user_blocked91                  : false,92                platform: pushedmessage?.newThread?.platform || "",93                sms_platform: pushedmessage?.newThread?.platform || "",94                alivesms_phone_number: "",95                channel_id: pushedmessage?.newThread?.channel_id,96                crmData: pushedmessage?.newThread?.crmData || {},97                campaign_pending:98                  pushedmessage?.newThread?.campaign_pending || "",99                lastmessage_at: pushedmessage?.newThread?.lastmessage_at,100                history_thread_timestamp: moment101                  .unix(createdAt / 1000)102                  .format("MM/DD/YY"),103                last_active_time: moment.unix(createdAt / 1000).fromNow(),104              };105              if (threadList?.length > 0) {106                setthreadList((state) => [...state, newThread]);107              } else {108                setthreadList([newThread]);109              }110              dispatch(setSingleThread(newThread));111            }112          }113        } else {114          if (115            pushedmessage?.newThread?.thread_id === thread_id &&116            tempMessageId !== pushedmessage.message_id117          ) {118            // console.log("Message", tempMessageId);119            tempMessageId = pushedmessage.message_id;120            dispatch(121              setSingleMessage({122                message_content: pushedmessage.message_content || "",123                created_at: pushedmessage.created_at,124                created_by: pushedmessage.created_by,125                From: pushedmessage.From,126                direction: pushedmessage.direction,127                media_url: pushedmessage.media_url || [],128              })129            );130          }131        }132      });133    fetchSMSMessagesEventSub = socket134      ?.fetchSMSMessages()135      .subscribe((pushedmessage) => {136        // console.log("pushedmessage", pushedmessage);137        if (parseInt(pageType) === 1) {138          if (parseInt(threadListingType) === 2) {139            let isThreadExist =140              threadList &&141              threadList?.length > 0 &&142              threadList?.find(143                (item) => item.thread_id === pushedmessage.thread_id144              );145            // console.log(146            //   "creating new thread,found existing thread",147            //   isThreadExist148            // );149            if (!isThreadExist || isThreadExist === {}) {150              // console.log("creating new thread,SMS chat");151              const createdAt =152                pushedmessage?.newThread?.lastmessage_at ||153                pushedmessage?.newThread?.updated_at ||154                pushedmessage?.newThread?.created_at ||155                moment().valueOf();156              let newThread = {157                phone_mobile: pushedmessage?.newThread?.phone_mobile,158                thread_type: pushedmessage?.newThread?.thread_type,159                thread_id: pushedmessage?.newThread?.thread_id,160                org_name: pushedmessage?.newThread?.org_name,161                crm_id: pushedmessage?.newThread?.crm_id,162                alivesecure_key: pushedmessage?.newThread?.alivesecure_key,163                aliveOpentokSession:164                  pushedmessage?.newThread?.aliveOpentokSession || "",165                status: pushedmessage?.newThread?.thread_status,166                status_timestamp: pushedmessage?.newThread?.updated_at,167                timestamp: pushedmessage?.newThread?.created_at,168                created_by: pushedmessage?.created_by,169                assignedTo: pushedmessage?.assignedTo,170                phone_number: pushedmessage?.newThread?.phone_mobile || "",171                smsblocked: pushedmessage?.newThread?.user_blocked172                  ? pushedmessage?.newThread?.user_blocked173                  : false,174                platform: pushedmessage?.newThread?.platform || "",175                sms_platform: pushedmessage?.newThread?.platform || "",176                alivesms_phone_number: "",177                channel_id: pushedmessage?.newThread?.channel_id,178                crmData: pushedmessage?.newThread?.crmData || {},179                campaign_pending:180                  pushedmessage?.newThread?.campaign_pending || "",181                lastmessage_at: pushedmessage?.newThread?.lastmessage_at,182                history_thread_timestamp: moment183                  .unix(createdAt / 1000)184                  .format("MM/DD/YY"),185                last_active_time: moment.unix(createdAt / 1000).fromNow(),186              };187              if (threadList?.length > 0) {188                setthreadList((state) => [...state, newThread]);189              } else {190                setthreadList([newThread]);191              }192              dispatch(setSingleThread(newThread));193            }194          }195        } else {196          // console.log(197          //   pushedmessage?.newThread?.thread_id,198          //   "working in else condition...",199          //   thread_id200          // );201          if (202            pushedmessage?.newThread?.thread_id === thread_id &&203            tempMessageId !== pushedmessage.message_id204          ) {205            // console.log(pushedmessage.message_id, "Message", tempMessageId);206            tempMessageId = pushedmessage.message_id;207            dispatch(208              setSingleMessage({209                message_content: pushedmessage.message_content || "",210                created_at: pushedmessage.created_at,211                created_by: pushedmessage.created_by,212                From: pushedmessage.From,213                direction: pushedmessage.direction,214                media_url: pushedmessage.media_url || [],215              })216            );217          }218        }219      });220    isThreadUpdatedEventSub = socket221      ?.isThreadUpdated()222      .subscribe((updatedThread) => {223        if (224          parseInt(threadListingType) === 2 ||225          threadListingType === undefined226        ) {227          if (updatedThread && updatedThread?.threadStatus === "deleted") {228            let updatedThreads = threadList?.filter(229              (thread) => thread.thread_id !== updatedThread.threadId230            );231            if (!parseInt(pageType) === 1 || pageType === undefined) {232              toast("Chat is Deleted by User!");233              setTimeout(() => {234                setredirect("Home");235              }, 3000);236            }237            dispatch(setThreadListing(updatedThreads));238          }239        }240      });241    updatedThreadCrmEventEventSub = socket242      ?.updatedThreadCrmEvent()243      .subscribe((updatedThreadCrm) => {244        if (parseInt(threadListingType) === 2) {245          let updateThreadsArray = threadList;246          if (updateThreadsArray && updateThreadsArray.length) {247            let threadIndex = updateThreadsArray.findIndex(248              (el) => el.thread_id === updatedThreadCrm.threadId249            );250            if (parseInt(threadIndex) > -1) {251              if (252                updateThreadsArray[parseInt(threadIndex)] &&253                updateThreadsArray[parseInt(threadIndex)].crmData254              ) {255                updateThreadsArray[parseInt(threadIndex)].crmData =256                  updatedThreadCrm?.crmData;257                setthreadList(updateThreadsArray);258                dispatch(setThreadListing(updateThreadsArray));259              }260            }261          }262        }263      });264    isAliveChatUpdatedEventSub = socket265      .isAliveChatUpdated()266      .subscribe((updateThreadStatus) => {267        if (updateThreadStatus?.thread_status === "closed") {268          if (!parseInt(pageType) === 1 || pageType === undefined) {269            console.log("in state close check....");270            toast("Chat is closed by User!");271            setTimeout(() => {272              setredirect("Home");273            }, 3000);274          } else {275            let updatedThreads = threadList?.filter(276              (thread) => thread.thread_id !== updateThreadStatus.thread_id277            );278            dispatch(setThreadListing(updatedThreads));279          }280        }281      });282  };283  return (284    <>285      {parseInt(pageType) === 1 ? (286        <header id="insta-header" className="bg-main fixed flex flex-row w-full justify-center items-center p-10">287          <section288            id="threads-header"289            className="h-full flex flex-col items-center justify-center"290          >291            <div className="logo-img h-full flex flex-col items-center justify-center">292              <svg293                xmlns="http://www.w3.org/2000/svg"294                width="98.809"295                className="mb-10"296                height="34.544"297                viewBox="0 0 243.809 86.544"298              >299                <path300                  d="M51.456,40.991C43.1,41.307,38.492,45.46,37.9,45.985V16.4a27.171,27.171,0,0,0-7.474-1.681c-4.376-.147-7.76.963-9.181,3.077A8.158,8.158,0,0,0,20,22.643V99.682H38.012V70.156c0-9.761,5.2-12.422,10.58-12.422,4.927,0,10.114,1.576,10.114,10.845v31.1H76.719v-34.8C76.719,46.494,64.352,40.5,51.456,40.991Z"301                  transform="translate(-20 -14.706)"302                  fill="#fff"303                />304                <path305                  d="M45.948,21.349a11.763,11.763,0,0,0-6.822,1.787q-2.566,1.791-2.573,6.162V78.4H54.565V23.022c-.441-.143-1.492-.467-3.127-.95A19.55,19.55,0,0,0,45.948,21.349Z"306                  transform="translate(33.029 6.576)"307                  fill="#fff"308                />309                <path310                  d="M78.195,36.565c-8.424-.307-15.061,4.809-16.407,6.154V17.783c-.446-.143-1.475-.467-3.094-.946a19.007,19.007,0,0,0-5.456-.727,11.892,11.892,0,0,0-6.864,1.778q-2.6,1.8-2.594,6.162V64.081c0,25.2,15.541,32.67,31.1,32.67,12.934,0,30.875-8.336,30.875-30.1C105.758,53.114,97.309,37.258,78.195,36.565ZM74.491,80.2c-9.353,0-12.813-7.293-12.813-13.6,0-4.931,3.182-13.586,12.813-13.586,9.488,0,12.808,8.1,12.808,13.586C87.3,73.607,83.029,80.2,74.491,80.2Z"311                  transform="translate(56.182 -10.208)"312                  fill="#fff"313                />314                <path315                  d="M114.638,22.072a19.48,19.48,0,0,0-5.477-.723,11.736,11.736,0,0,0-6.822,1.787c-1.719,1.194-2.568,3.245-2.568,6.162V51.775q0,11.646-10.513,11.64-10.53,0-10.522-11.64V23.022c-.454-.143-1.5-.467-3.136-.95a19.492,19.492,0,0,0-5.473-.723,11.8,11.8,0,0,0-6.835,1.787q-2.566,1.791-2.573,6.162V55.129c0,6.545,2.459,24.839,28.538,24.839,25.583,0,28.521-18.294,28.521-24.839V23.022C117.328,22.879,116.285,22.555,114.638,22.072Z"316                  transform="translate(110.444 6.576)"317                  fill="#fff"318                />319                <path320                  d="M36.512,24.128A9.176,9.176,0,1,1,45.688,33.3,9.181,9.181,0,0,1,36.512,24.128Z"321                  transform="translate(32.898 -13.934)"322                  fill="#fff"323                />324                <path325                  d="M60.718,24.128A9.176,9.176,0,1,1,69.894,33.3,9.181,9.181,0,0,1,60.718,24.128Z"326                  transform="translate(110.444 -13.934)"327                  fill="#fff"328                />329                <path330                  d="M70,24.128A9.174,9.174,0,1,1,79.18,33.3,9.178,9.178,0,0,1,70,24.128Z"331                  transform="translate(140.193 -13.934)"332                  fill="#fff"333                />334                <g transform="translate(233.972 30.287)">335                  <path336                    d="M77.362,22.512h-1.7v-.6h4.124v.6h-1.7v5.036h-.719Z"337                    transform="translate(-75.66 -21.911)"338                    fill="#fff"339                  />340                  <path341                    d="M76.882,21.911h.841l1.093,3.027.412,1.148h.034l.4-1.148,1.085-3.027h.841v5.637H80.9v-3.1c0-.5.05-1.169.092-1.665h-.034l-.454,1.253-1.085,2.947h-.4l-1.089-2.947-.45-1.253h-.034c.034.5.1,1.169.1,1.665v3.1h-.664Z"342                    transform="translate(-71.745 -21.911)"343                    fill="#fff"344                  />345                </g>346              </svg>347              <svg348                xmlns="http://www.w3.org/2000/svg"349                width="52"350                height="22"351                viewBox="0 0 112 48"352              >353                <text354                  transform="translate(56 38)"355                  fill="#fff"356                  fontSize="41"357                  fontFamily="HibuCoText-Regular, Hibu Co Text, Open Sans"358                >359                  <tspan x="-55" y="0">360                    CHAT361                  </tspan>362                </text>363              </svg>364            </div>365          </section>366        </header>367      ) : (368        <header id="insta-header" className="bg-main fixed flex flex-row w-full justify-center items-center p-10">369          <section370            id="chat-header"371            className="flex flex-row items-center w-full"372          >373            <button374              className="btn-col transparent white"375              onClick={handleBack}376              style={{ cursor: "pointer", padding: 10 }}377            >378              <svg379                xmlns="http://www.w3.org/2000/svg"380                width="10.5"381                height="18.366"382                viewBox="0 0 10.5 18.366"383              >384                <path385                  d="M14.416,15.374l6.949-6.944a1.313,1.313,0,0,0-1.859-1.854l-7.873,7.868a1.31,1.31,0,0,0-.038,1.81L19.5,24.177a1.313,1.313,0,1,0,1.859-1.854Z"386                  transform="translate(-11.251 -6.194)"387                  fill="currentColor"388                />389              </svg>390            </button>391            <div className="profile-image small ml-auto flex flex-col justify-center items-center">392              <div className="image-container">393                <svg394                  xmlns="http://www.w3.org/2000/svg"395                  width="32"396                  height="32"397                  viewBox="0 0 45.004 45.005"398                >399                  <g transform="translate(-162 -435)">400                    <path401                      d="M21.324,39.963,14.61,43.626a6.034,6.034,0,0,0-1.078.767,22.488,22.488,0,0,0,28.894.075,5.957,5.957,0,0,0-1.184-.793l-7.19-3.594a2.742,2.742,0,0,1-1.516-2.452V34.806a10.859,10.859,0,0,0,.68-.875,16.544,16.544,0,0,0,2.235-4.5,2.258,2.258,0,0,0,1.6-2.148V24.268A2.248,2.248,0,0,0,36.3,22.6V18.247s.894-6.774-8.279-6.774-8.279,6.774-8.279,6.774V22.6a2.245,2.245,0,0,0-.752,1.669v3.011a2.257,2.257,0,0,0,1.041,1.894,14.942,14.942,0,0,0,2.722,5.632v2.751A2.745,2.745,0,0,1,21.324,39.963Z"402                      transform="translate(156.481 430.321)"403                      fill="#e7eced"404                    />405                    <g transform="translate(162 435)">406                      <path407                        d="M22.887,0a22.488,22.488,0,0,0-14.864,39.7,5.979,5.979,0,0,1,1.067-.759L15.8,35.285a2.743,2.743,0,0,0,1.429-2.407V30.126a14.928,14.928,0,0,1-2.722-5.632A2.258,2.258,0,0,1,13.47,22.6V19.588a2.248,2.248,0,0,1,.752-1.669V13.567S13.328,6.793,22.5,6.793s8.279,6.774,8.279,6.774V17.92a2.245,2.245,0,0,1,.752,1.669V22.6a2.258,2.258,0,0,1-1.6,2.148,16.544,16.544,0,0,1-2.235,4.5,10.86,10.86,0,0,1-.68.875v2.821A2.741,2.741,0,0,0,28.533,35.4l7.19,3.594a5.987,5.987,0,0,1,1.18.791A22.5,22.5,0,0,0,22.887,0Z"408                        transform="translate(0 0)"409                        fill="#556080"410                      />411                    </g>412                  </g>413                </svg>414              </div>415              <p className="font-14 tracking-05 font-normal white m-0 mt-5">416                {chattingWith}417              </p>418            </div>419            <button420              className="btn-col ml-auto transparent white"421              onClick={actionBar}422              style={{ cursor: "pointer" }}423            >424              <svg425                xmlns="http://www.w3.org/2000/svg"426                width="28"427                height="6"428                viewBox="0 0 28 6"429              >430                <g transform="translate(-325 -65)">431                  <circle432                    cx="3"433                    cy="3"434                    r="3"435                    transform="translate(325 65)"436                    fill="currentColor"437                  />438                  <circle439                    cx="3"440                    cy="3"441                    r="3"442                    transform="translate(336 65)"443                    fill="currentColor"444                  />445                  <circle446                    cx="3"447                    cy="3"448                    r="3"449                    transform="translate(347 65)"450                    fill="currentColor"451                  />452                </g>453              </svg>454            </button>455          </section>456        </header>457      )}458      {/* <header459      className="flex-row chat monitor flex-center-items  padding-left-10 padding-right-10 only-border-bottom border-width-1 border-style-solid border-grey-200"460      style={{ backgroundColor: `${bgColor}` }}461    >462      {parseInt(pageType) === 1 && (463        <button464          type="button"465          className="btn-action transparent white"466          onClick={handleBack}467        >468          <Back />469        </button>470      )}471      <div className="branding h-35-px" style={{ margin: "auto" }}>472        {/* eslint-disable-next-line */}473      {/* <img474          className="full-height"475          src={logoURL}476          alt="alive5 logo image"477          srcSet=""478        />479      </div>480      {parseInt(pageType) !== 0 && (481        <>482          {parseInt(pageType) === 1 && thread_type === "livechat" ? (483            <button484              id="close"485              className="btn-action transparent white"486              type="button"487              data-toggle="modal"488              data-target="#exampleModal "489            >490              <Cross />491            </button>492          ) : (493            <div></div>494          )}495        </>496      )}497       498    </header> */}499      {/* <ToastContainer />  */}500    </>501  );502};...common.js
Source:common.js  
1var ws;2var currentPage;3var timeLineCount;4var userInformation;5/*6 * ã¢ããªèµ·åæã«ä¸åº¦ã ãå¿
è¦ãªå¦ç7 */8$(document).on(9		'pagecreate',10		function(){11			//ã»ãã·ã§ã³ã¹ãã¬ã¼ã¸ã®ãã§ãã¯12			if (typeof sessionStorage === 'undefined') {13				window.alert("ãã®ãã©ã¦ã¶ã¯Web Storageæ©è½ãå®è£
ããã¦ãã¾ããã対å¿ãããã©ã¦ã¶ã§ä½¿ç¨ãã¦ãã ãã");14			}15			timeLineCount = JSON.parse(getStorage('timeLineCount'));16			console.log('ãdebugãMETHOD;common-redy;timeLinecount='+timeLineCount+' ,unReadedMessageNum='+timeLineCount.unReadedMessageNum);17			checkTimeLineCount();18});19//Ajaxã®ãã¼ã¸é·ç§»ãç¡å¹ã«20$(document).bind("mobileinit", function(){21	$.mobile.ajaxFormsEnabled = false;22});23/*24 * åãã¼ã¸ãã¨ã«å¿
é ãªå¦ç25 */26function eachPageDoFirst(rootDir){27	console.log('ãdebugãMETHOD;eachPageDoFirst;currenPage='+currentPage);28	//ãã°ã¤ã³ãã§ãã¯29	loginCheck(rootDir);30	checkTimeLineCount();31	//timeLineç¨ã®ãã¡ã³ã¯ã·ã§ã³32	if(!ws){33		socketOpen();34	}35	//æªèªä»¶æ°ã®æ¿å
¥36	insertunReadedMessageNum();37	//管çè
ãã¼ã¸ã®è¡¨ç¤ºé表示38	if(!userInformation.admin){39		$('.admin').css('display','none');40	}41}42/*43 * timeLineç¨ã®ãã¡ã³ã¯ã·ã§ã³44 * ã½ã±ããéä¿¡ã§ã¡ãã»ã¼ã¸ãéåä¿¡ããã45 * currentPageãtimeLineã®å ´åã¯ç»é¢ã®æ¸ãæãå¦çãè¡ãã46 */47function socketOpen(){48	//ç¾æç¹ã§ã®ãã¼ã¿ãåå¾49	getTimeLineData();50	// WebSocket ã®åæå51    ws = new WebSocket('ws://'+ config.apiHost + '/'+config.webSocketUrl+'/timeLine');52    // ã¤ãã³ããã³ãã©ã®è¨å®53    ws.onopen = onOpen;54    ws.onmessage = onMessage;55    ws.onclose = onClose;56    ws.onerror = onError;57    // Windowãéãããã(ä¾ï¼ãã©ã¦ã¶ãéãã)æã®ã¤ãã³ããè¨å®58    $(window).unload(function() {59        ws.onclose(); // WebSocket close60    });61}62//æ¥ç¶ã¤ãã³ã63function onOpen(event) {64console.log('socket open!');65timeLineCount = JSON.parse(getStorage('timeLineCount'));66insertunReadedMessageNum();67//socketãéåããªãããã«å®æçã«keep-aliveã¡ãã»ã¼ã¸ãéä¿¡68//setTimeout(ws.send("ALIVE"), 5500);69}70//ã¡ãã»ã¼ã¸åä¿¡ã¤ãã³ã71//storageã®ãã¼ã¿ã«è¿½å åã®ã¡ãã»ã¼ã¸ããã³ã¹ã¬ãããã¼ã¿ã追å ããã72//timeLineãã¼ã¸ãéãã¦ããå ´åã¯ç»é¢ã®æåãè¡ãã73function onMessage(event) {74	console.log('ãdebugãsocket onMessage'+event.data)75	var isNewThread = false;76	if (event && event.data) {77		var pushedMessage = JSON.parse(event.data);78		var pushedThreadId = pushedMessage.threadId;79		var pushedMessageReaction;80		var pushedThreadColor =pushedMessage.colorCode;;81		timeLineCount = JSON.parse(getStorage('timeLineCount'));82		//thread追å ã®å ´åã®å¦ç83		if(!pushedMessage.reactions){84			isNewThread=true;85			timeLineData.threads.unshift(pushedMessage);86		}else{87			//ã¡ãã»ã¼ã¸è¿½å ã®å ´åã®å¦ç88	    	pushedMessageReaction= pushedMessage.reactions[0];89	    	for (var i=0;i<timeLineData.threads.length;i++){90	    		tmpThread = timeLineData.threads[i];91	    		if(tmpThread.threadId==pushedThreadId){92	    			if(tmpThread.reactions == null){93	    				tmpThread.reactions=[pushedMessageReaction];94	    			}else{95	    			tmpThread.reactions.unshift(pushedMessageReaction);96	    			}97	    			tmpThread.colorCode=pushedMessage.colorCode;98	    		}99	    	}100		}101		saveStorage('timeLineData', JSON.stringify(timeLineData));102		currentPage=getCurrentPage();103		//表示ãã¼ã¸ãã¿ã¤ã ã©ã¤ã³ã®å ´åã¯ç»é¢ã«æåããã104		if(currentPage=='timeLine'){105			if(isNewThread==true){106				var insertHTML=makeHtmlThread(pushedMessage)107				setColorCode(pushedMessage.threadId,pushedMessage.colorCode);108				//Htmlã®æ¿å
¥109				$("#timeLine_ResultArea").prepend(insertHTML);110			//ãªã¢ã¯ã·ã§ã³è¿½å ã§ãªã¢ã¯ã·ã§ã³ãéããã¦ããå ´å111			}else if(isNewThread==false && $('#'+pushedThreadId).attr('messagestatus') == 'open'){112				var insertHTML=makeHtmlReaction(pushedMessage.reactions[0]);113				$('#otherReaction-'+pushedThreadId).prepend(insertHTML);114				setColorCode(pushedThreadId,pushedThreadColor);115			//ãªã¢ã¯ã·ã§ã³è¿½å ã§ãªã¢ã¯ã·ã§ã³ãéããã¦ããªãå ´å116			}else if(isNewThread==false && $('#'+pushedThreadId).attr('messagestatus') == 'close'){117				setColorCode(pushedThreadId,pushedThreadColor);118			}119		}120		//ã¹ã¬ããã追å ãããå ´åã¯æªèªä»¶æ°ã表示ããï¼ã¿ã¤ã ã©ã¤ã³ç»é¢ã®å ´åã¯è¡ããªãï¼121		if(currentPage!='timeLine' && isNewThread==true){122				timeLineCount.unReadedMessageNum++;123				saveStorage('timeLineCount', JSON.stringify(timeLineCount));124				insertunReadedMessageNum();125		}126	}127}128//ã¨ã©ã¼ã¤ãã³ã129function onError(event) {130 console.log('socketErr:'+event);131}132//åæã¤ãã³ã133function onClose(event) {134	console.log("åæãã¾ããã10ç§å¾ã«åæ¥ç¶ãã¾ãã(" + event.code + ")" +'æ¥ç¶è©¦è¡åæ°' + timeLineCount.connectionTryCnt +'<br>');135	ws = null;136	timeLineCount.connectionTryCnt ++;137	setTimeout('socketOpen()', 10000);138}139//ã¡ãã»ã¼ã¸éä¿¡ã¤ãã³ã140function sendMessageToSocket(Message){141    ws.send(Message); // WebSocketã使ããµã¼ãã«ã¡ãã»ã¼ã¸ãéä¿¡142}143/*144* ååãã¼ã¿å徿ã®ã¡ã½ãã145* ã¿ã¤ã ã©ã¤ã³ã®ãã¼ã¿å
¨ã¦ãåå¾ãã146*/147function getTimeLineData(){148	console.log('ãdebugãGET;request;common-getTimeLineData;-');149$150	.ajax({151		type : 'GET',152		url : 'http://' + config.apiHost + '/'+ config.apiVersion +'/page/timeLine/',153		dataType : 'json',154		success : function(data) {155			timeLineData = data;156			//console.log('ãdebugãGET;response;getTimeLineData'+JSON.stringify(data));157			saveStorage('timeLineData', JSON158					.stringify(timeLineData));159			//æªèªä»¶æ°ä½æå¦ç160			timeLineCount = JSON.parse(getStorage('timeLineCount'));161			timeLineCount.unReadedMessageNum = data.threads.length - timeLineCount.watchedThreadCount;162			saveStorage('timeLineCount', JSON163					.stringify(timeLineCount));164			insertunReadedMessageNum();165		},166		error : function(XMLHttpRequest, textStatus, errorThrown) {167			console.log("ãªã¯ã¨ã¹ãæã«ãªãããã®ã¨ã©ã¼ãçºçãã¾ããï¼" + textStatus + ":\n"168					+ errorThrown + ":\n" + XMLHttpRequest);169		}170	});171}172function insertunReadedMessageNum(){173	timeLineCount = JSON.parse(getStorage('timeLineCount'));174	console.log('ãdebugãMETHOD;insertunReadedMessageNum;timeLineCount:'+timeLineCount);175	var messege = '';176	if(timeLineCount.unReadedMessageNum != 0 ){177		messege = 'æªèª'+timeLineCount.unReadedMessageNum;178	}179	$('.timeLineFooter').html(messege);180}181function checkTimeLineCount(){182	timeLineCount = JSON.parse(getStorage('timeLineCount'));183	if(timeLineCount == null || timeLineCount == undefined){184		timeLineCount ={'unReadedMessageNum':0,185				'watchedThreadCount':0,186				'connectionTryCnt':0};187		saveStorage('timeLineCount', JSON.stringify(timeLineCount));188	}189}190function loginCheck(rootDir){191	var loginPageURL=rootDir+'/facebookLogin.html';192	if(config.isDevelop){193		// ãã¹ãç¨194		userInformation={'userId':'125216844506488','userName':'kiyota','admin':true,'team':'C'};195		saveStorage('userInformation', JSON.stringify(userInformation));196	}else{197		userInformation =JSON.parse(getStorage('userInformation'));198		if(!userInformation){199		location.href=loginPageURL;200		};201	}...message-unpack-stream.js
Source:message-unpack-stream.js  
1const { assert } = require("chai");2const bufferpack = require("bufferpack");3const MessageUnpackStream = require("../message-unpack-stream").MessageUnpackStream;4describe("message-unpack-stream", () => {5	describe("_transform", () => {6		const createMessageToSend = (message) => {7			const header = bufferpack.pack(">i", [message.length]);8			const binaryMsg = Buffer.from(message);9			const dataToSend = Buffer.concat([header, binaryMsg]);10			return {11				binaryMsg,12				dataToSend13			};14		};15		it("parses correctly one message", (mochaDone) => {16			const { dataToSend, binaryMsg } = createMessageToSend("testMessage");17			const msgUnpackStreamInstance = new MessageUnpackStream();18			let pushedMessage = null;19			msgUnpackStreamInstance.push = (data, encoding) => {20				pushedMessage = data;21			};22			msgUnpackStreamInstance._transform(dataToSend, null, () => {23				assert.deepEqual(pushedMessage, binaryMsg);24				mochaDone();25			});26		});27		it("does not parse anything when only partial message is sent", (mochaDone) => {28			const { dataToSend, binaryMsg } = createMessageToSend("testMessage");29			const msgUnpackStreamInstance = new MessageUnpackStream();30			let pushedMessage = null;31			msgUnpackStreamInstance.push = (data, encoding) => {32				assert.fail("Push should not be called with partial message");33				pushedMessage = data;34			};35			msgUnpackStreamInstance._transform(dataToSend.slice(0, 6), null, () => {36				assert.deepEqual(pushedMessage, null);37				mochaDone();38			});39		});40		describe("parses correctly one message passed on two calls, when the first one", () => {41			const validateMessage = (endSplitIndex, mochaDone) => {42				const { dataToSend, binaryMsg } = createMessageToSend("testMessage");43				const msgUnpackStreamInstance = new MessageUnpackStream();44				let pushedMessage = null;45				msgUnpackStreamInstance.push = (data, encoding) => {46					pushedMessage = data;47				};48				let doneCallbackCounter = 0;49				const doneCallback = () => {50					doneCallbackCounter++;51					if (doneCallbackCounter === 2) {52						assert.deepEqual(pushedMessage, binaryMsg);53						mochaDone();54					}55				};56				const firstMessage = dataToSend.slice(0, endSplitIndex);57				msgUnpackStreamInstance._transform(firstMessage, null, doneCallback);58				msgUnpackStreamInstance._transform(dataToSend.slice(firstMessage.length), null, doneCallback);59			};60			it("does not contain full header", (mochaDone) => {61				validateMessage(1, mochaDone);62			});63			it("contains only header", (mochaDone) => {64				validateMessage(4, mochaDone);65			});66			it("contains header and part of the message", (mochaDone) => {67				validateMessage(7, mochaDone);68			});69		});70		it("parses correctly two messages passed on one call", (mochaDone) => {71			const { dataToSend: firstDataToSend, binaryMsg: firstBinaryMsg } = createMessageToSend("testMessage");72			const { dataToSend: secondDataToSend, binaryMsg: secondBinaryMsg } = createMessageToSend("secondTestMessage");73			const msgUnpackStreamInstance = new MessageUnpackStream();74			let pushedMessages = [];75			msgUnpackStreamInstance.push = (data, encoding) => {76				pushedMessages.push(data)77			};78			const doneCallback = () => {79				assert.deepEqual(pushedMessages, [firstBinaryMsg, secondBinaryMsg]);80				mochaDone();81			};82			const dataToSend = Buffer.concat([firstDataToSend, secondDataToSend]);83			msgUnpackStreamInstance._transform(dataToSend, null, doneCallback);84		});85		describe("parses correctly two messages passed on two calls, when", () => {86			const validateMessage = (endSplitIndex, mochaDone) => {87				// NOTE: Do NOT change the messages here as it will result in incorrect tests below88				const { dataToSend: firstDataToSend, binaryMsg: firstBinaryMsg } = createMessageToSend("abc");89				const { dataToSend: secondDataToSend, binaryMsg: secondBinaryMsg } = createMessageToSend("def");90				const msgUnpackStreamInstance = new MessageUnpackStream();91				let pushedMessages = [];92				msgUnpackStreamInstance.push = (data, encoding) => {93					pushedMessages.push(data)94				};95				let doneCallbackCounter = 0;96				const doneCallback = () => {97					doneCallbackCounter++;98					if (doneCallbackCounter === 2) {99						assert.deepEqual(pushedMessages, [firstBinaryMsg, secondBinaryMsg]);100						mochaDone();101					}102				};103				const dataToSend = Buffer.concat([firstDataToSend, secondDataToSend]);104				const firstMessage = dataToSend.slice(0, endSplitIndex);105				msgUnpackStreamInstance._transform(firstMessage, null, doneCallback);106				msgUnpackStreamInstance._transform(dataToSend.slice(firstMessage.length), null, doneCallback);107			};108			it("first call contains part of the header of the first message", (mochaDone) => {109				validateMessage(1, mochaDone);110			});111			it("first call contains only the header of the first message", (mochaDone) => {112				validateMessage(4, mochaDone);113			});114			it("first call contains the header and part of the first message", (mochaDone) => {115				validateMessage(6, mochaDone);116			});117			it("first call contains the first message and part of the header of the second message", (mochaDone) => {118				validateMessage(9, mochaDone);119			});120			it("first call contains the first message and the header of the second message", (mochaDone) => {121				validateMessage(11, mochaDone);122			});123			it("first call contains the first message, the header of the second message and part of the second message", (mochaDone) => {124				validateMessage(13, mochaDone);125			});126		});127	});...Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'A.12345678901234567890123456789012');3    if (err) {4        console.log(err);5    } else {6        wpt.getTestStatus(data.data.testId, function(err, data) {7            if (err) {8                console.log(err);9            } else {10                console.log(data);11            }12        });13    }14});15var wpt = require('webpagetest');16var wpt = new WebPageTest('www.webpagetest.org', 'A.12345678901234567890123456789012');17    if (err) {18        console.log(err);19    } else {20        wpt.getTestStatus(data.data.testId).then(function(data) {21            console.log(data);22        }).catch(function(err) {23            console.log(err);24        });25    }26});Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3    if (err) return console.error(err);4    wpt.getTestStatus(data.data.testId, function(err, data) {5        if (err) return console.error(err);6        console.log(data);7    });8});9    at errnoException (net.js:905:11)10    at Object.afterConnect [as oncomplete] (net.js:896:19)Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3wpt.pushedMessage('testId', 'message', function(err, data) {4  if (err) {5    console.log(err);6  } else {7    console.log(data);8  }9});10var wpt = require('webpagetest');11var wpt = new WebPageTest('www.webpagetest.org');12wpt.getLocations(function(err, data) {13  if (err) {14    console.log(err);15  } else {16    console.log(data);17  }18});19var wpt = require('webpagetest');20var wpt = new WebPageTest('www.webpagetest.org');21wpt.getTesters(function(err, data) {22  if (err) {23    console.log(err);24  } else {25    console.log(data);26  }27});28var wpt = require('webpagetest');29var wpt = new WebPageTest('www.webpagetest.org');30wpt.getTesters(function(err, data) {31  if (err) {32    console.log(err);33  } else {34    console.log(data);35  }36});37var wpt = require('webpagetest');38var wpt = new WebPageTest('www.webpagetest.org');39wpt.getTesters(function(err, data) {40  if (err) {41    console.log(err);42  } else {43    console.log(data);44  }45});46var wpt = require('webpagetest');47var wpt = new WebPageTest('www.webpagetest.org');48wpt.getTesters(function(err, data) {49  if (err) {50    console.log(err);51  } else {52    console.log(data);53  }54});Using AI Code Generation
1var wpt = require('wpt');2wpt.pushedMessage('test', 'test message', function(err, data) {3    console.log('err: ' + err);4    console.log('data: ' + data);5});6var wpt = require('wpt');7wpt.pushedMessage('test', 'test message', function(err, data) {8    console.log('err: ' + err);9    console.log('data: ' + data);10});11var wpt = require('wpt');12wpt.pushedMessage('test', 'test message', function(err, data) {13    console.log('err: ' + err);14    console.log('data: ' + data);15});16var wpt = require('wpt');17wpt.pushedMessage('test', 'test message', function(err, data) {18    console.log('err: ' + err);19    console.log('data: ' + data);20});21var wpt = require('wpt');22wpt.pushedMessage('test', 'test message', function(err, data) {23    console.log('err: ' + err);24    console.log('data: ' + data);25});26var wpt = require('wpt');27wpt.pushedMessage('test', 'test message', function(err, data) {28    console.log('err: ' + err);29    console.log('data: ' + data);30});31var wpt = require('wpt');32wpt.pushedMessage('test', 'test message', function(err, data) {33    console.log('err: ' + err);34    console.log('data: ' + data);35});36var wpt = require('wpt');37wpt.pushedMessage('test', 'test message', function(err, data) {38    console.log('err: ' + err);39    console.log('data: ' + data);40});41var wpt = require('wpt');42wpt.pushedMessage('test', 'test message', function(err, data)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!!
