Best JavaScript code snippet using testcafe
calendar-event-dialog-recurrence.js
Source:calendar-event-dialog-recurrence.js  
...25    preview.dateTime = gStartTime.getInTimezone(cal.calendarDefaultTimezone());26    onChangeCalendar(calendar);27    // Set starting value for 'repeat until' rule and highlight the start date.28    let repeatDate = cal.dateTimeToJsDate(gStartTime.getInTimezone(cal.floating()));29    setElementValue("repeat-until-date", repeatDate);30    document.getElementById("repeat-until-date").extraDate = repeatDate;31    if (item.parentItem != item) {32        item = item.parentItem;33    }34    let rule = null;35    if (recinfo) {36        // Split out rules and exceptions37        try {38            let rrules = splitRecurrenceRules(recinfo);39            let rules = rrules[0];40            // Deal with the rules41            if (rules.length > 0) {42                // We only handle 1 rule currently43                rule = cal.wrapInstance(rules[0], Components.interfaces.calIRecurrenceRule);44            }45        } catch (ex) {46            Components.utils.reportError(ex);47        }48    }49    if (!rule) {50        rule = cal.createRecurrenceRule();51        rule.type = "DAILY";52        rule.interval = 1;53        rule.count = -1;54    }55    initializeControls(rule);56    // Update controls57    updateRecurrenceDeck();58    opener.setCursor("auto");59    self.focus();60}61/**62 * Initialize the dialog controls according to the passed rule63 *64 * @param rule    The recurrence rule to parse.65 */66function initializeControls(rule) {67    function getOrdinalAndWeekdayOfRule(aByDayRuleComponent) {68        return {69            ordinal: (aByDayRuleComponent - (aByDayRuleComponent % 8)) / 8,70            weekday: Math.abs(aByDayRuleComponent % 8)71        };72    }73    function setControlsForByMonthDay_YearlyRule(aDate, aByMonthDay) {74        if (aByMonthDay == -1) {75            // The last day of the month.76            document.getElementById("yearly-group").selectedIndex = 1;77            setElementValue("yearly-ordinal", -1);78            setElementValue("yearly-weekday", -1);79        } else {80            if (aByMonthDay < -1) {81                // The UI doesn't manage negative days apart from -1 but we can82                // display in the controls the day from the start of the month.83                aByMonthDay += aDate.endOfMonth.day + 1;84            }85            document.getElementById("yearly-group").selectedIndex = 0;86            setElementValue("yearly-days", aByMonthDay);87        }88    }89    function everyWeekDay(aByDay) {90        // Checks if aByDay contains only values from 1 to 7 with any order.91        let mask = aByDay.reduce((value, item) => value | (1 << item), 1);92        return aByDay.length == 7 && mask == Math.pow(2, 8) - 1;93    }94    switch (rule.type) {95        case "DAILY":96            document.getElementById("period-list").selectedIndex = 0;97            setElementValue("daily-days", rule.interval);98            break;99        case "WEEKLY":100            setElementValue("weekly-weeks", rule.interval);101            document.getElementById("period-list").selectedIndex = 1;102            break;103        case "MONTHLY":104            setElementValue("monthly-interval", rule.interval);105            document.getElementById("period-list").selectedIndex = 2;106            break;107        case "YEARLY":108            setElementValue("yearly-interval", rule.interval);109            document.getElementById("period-list").selectedIndex = 3;110            break;111        default:112            document.getElementById("period-list").selectedIndex = 0;113            dump("unable to handle your rule type!\n");114            break;115    }116    let byDayRuleComponent = rule.getComponent("BYDAY", {});117    let byMonthDayRuleComponent = rule.getComponent("BYMONTHDAY", {});118    let byMonthRuleComponent = rule.getComponent("BYMONTH", {});119    let kDefaultTimezone = cal.calendarDefaultTimezone();120    let startDate = gStartTime.getInTimezone(kDefaultTimezone);121    // "DAILY" ruletype122    // byDayRuleComponents may have been set priorily by "MONTHLY"- ruletypes123    // where they have a different context-124    // that's why we also query the current rule-type125    if (byDayRuleComponent.length == 0 || rule.type != "DAILY") {126        document.getElementById("daily-group").selectedIndex = 0;127    } else {128        document.getElementById("daily-group").selectedIndex = 1;129    }130    // "WEEKLY" ruletype131    if (byDayRuleComponent.length == 0 || rule.type != "WEEKLY") {132        document.getElementById("daypicker-weekday").days = [startDate.weekday + 1];133    } else {134        document.getElementById("daypicker-weekday").days = byDayRuleComponent;135    }136    // "MONTHLY" ruletype137    let ruleComponentsEmpty = (byDayRuleComponent.length == 0 &&138                               byMonthDayRuleComponent.length == 0);139    if (ruleComponentsEmpty || rule.type != "MONTHLY") {140        document.getElementById("monthly-group").selectedIndex = 1;141        document.getElementById("monthly-days").days = [startDate.day];142        let day = Math.floor((startDate.day - 1) / 7) + 1;143        setElementValue("monthly-ordinal", day);144        setElementValue("monthly-weekday", startDate.weekday + 1);145    } else if (everyWeekDay(byDayRuleComponent)) {146        // Every day of the month.147        document.getElementById("monthly-group").selectedIndex = 0;148        setElementValue("monthly-ordinal", 0);149        setElementValue("monthly-weekday", -1);150    } else if (byDayRuleComponent.length > 0) {151        // One of the first five days or weekdays of the month.152        document.getElementById("monthly-group").selectedIndex = 0;153        let ruleInfo = getOrdinalAndWeekdayOfRule(byDayRuleComponent[0]);154        setElementValue("monthly-ordinal", ruleInfo.ordinal);155        setElementValue("monthly-weekday", ruleInfo.weekday);156    } else if (byMonthDayRuleComponent.length == 1 && byMonthDayRuleComponent[0] == -1) {157        // The last day of the month.158        document.getElementById("monthly-group").selectedIndex = 0;159        setElementValue("monthly-ordinal", byMonthDayRuleComponent[0]);160        setElementValue("monthly-weekday", byMonthDayRuleComponent[0]);161    } else if (byMonthDayRuleComponent.length > 0) {162        document.getElementById("monthly-group").selectedIndex = 1;163        document.getElementById("monthly-days").days = byMonthDayRuleComponent;164    }165    // "YEARLY" ruletype166    if (byMonthRuleComponent.length == 0 || rule.type != "YEARLY") {167        setElementValue("yearly-month-rule", startDate.month + 1);168        setElementValue("yearly-month-ordinal", startDate.month + 1);169        if (byMonthDayRuleComponent.length > 0) {170            setControlsForByMonthDay_YearlyRule(startDate, byMonthDayRuleComponent[0]);171        } else {172            setElementValue("yearly-days", startDate.day);173            let ordinalDay = Math.floor((startDate.day - 1) / 7) + 1;174            setElementValue("yearly-ordinal", ordinalDay);175            setElementValue("yearly-weekday", startDate.weekday + 1);176        }177    } else {178        setElementValue("yearly-month-rule", byMonthRuleComponent[0]);179        setElementValue("yearly-month-ordinal", byMonthRuleComponent[0]);180        if (byMonthDayRuleComponent.length > 0) {181            let date = startDate.clone();182            date.month = byMonthRuleComponent[0] - 1;183            setControlsForByMonthDay_YearlyRule(date, byMonthDayRuleComponent[0]);184        } else if (byDayRuleComponent.length > 0) {185            document.getElementById("yearly-group").selectedIndex = 1;186            if (everyWeekDay(byDayRuleComponent)) {187                // Every day of the month.188                setElementValue("yearly-ordinal", 0);189                setElementValue("yearly-weekday", -1);190            } else {191                let yearlyRuleInfo = getOrdinalAndWeekdayOfRule(byDayRuleComponent[0]);192                setElementValue("yearly-ordinal", yearlyRuleInfo.ordinal);193                setElementValue("yearly-weekday", yearlyRuleInfo.weekday);194            }195        } else if (byMonthRuleComponent.length > 0) {196            document.getElementById("yearly-group").selectedIndex = 0;197            setElementValue("yearly-days", startDate.day);198        }199    }200    /* load up the duration of the event radiogroup */201    if (rule.isByCount) {202        if (rule.count == -1) {203            setElementValue("recurrence-duration", "forever");204        } else {205            setElementValue("recurrence-duration", "ntimes");206            setElementValue("repeat-ntimes-count", rule.count);207        }208    } else {209        let untilDate = rule.untilDate;210        if (untilDate) {211            gUntilDate = untilDate.getInTimezone(gStartTime.timezone); // calIRecurrenceRule::untilDate is always UTC or floating212            // Change the until date to start date if the rule has a forbidden213            // value (earlier than the start date).214            if (gUntilDate.compare(gStartTime) < 0) {215                gUntilDate = gStartTime.clone();216            }217            let repeatDate = cal.dateTimeToJsDate(gUntilDate.getInTimezone(cal.floating()));218            setElementValue("recurrence-duration", "until");219            setElementValue("repeat-until-date", repeatDate);220        } else {221            setElementValue("recurrence-duration", "forever");222        }223    }224}225/**226 * Save the recurrence information selected in the dialog back to the given227 * item.228 *229 * @param item    The item to save back to.230 * @return        The saved recurrence info.231 */232function onSave(item) {233    // Always return 'null' if this item is an occurrence.234    if (!item || item.parentItem != item) {235        return null;236    }237    // This works, but if we ever support more complex recurrence,238    // e.g. recurrence for Martians, then we're going to want to239    // not clone and just recreate the recurrenceInfo each time.240    // The reason is that the order of items (rules/dates/datesets)241    // matters, so we can't always just append at the end.  This242    // code here always inserts a rule first, because all our243    // exceptions should come afterward.244    let deckNumber = Number(getElementValue("period-list"));245    let args = window.arguments[0];246    let recurrenceInfo = args.recurrenceInfo;247    if (recurrenceInfo) {248        recurrenceInfo = recurrenceInfo.clone();249        let rrules = splitRecurrenceRules(recurrenceInfo);250        if (rrules[0].length > 0) {251            recurrenceInfo.deleteRecurrenceItem(rrules[0][0]);252        }253        recurrenceInfo.item = item;254    } else {255        recurrenceInfo = cal.createRecurrenceInfo(item);256    }257    let recRule = cal.createRecurrenceRule();258    const ALL_WEEKDAYS = [2, 3, 4, 5, 6, 7, 1]; // The sequence MO,TU,WE,TH,FR,SA,SU.259    switch (deckNumber) {260        case 0: {261            recRule.type = "DAILY";262            let dailyGroup = document.getElementById("daily-group");263            if (dailyGroup.selectedIndex == 0) {264                let ndays = Math.max(1, Number(getElementValue("daily-days")));265                recRule.interval = ndays;266            } else {267                recRule.interval = 1;268                let onDays = [2, 3, 4, 5, 6];269                recRule.setComponent("BYDAY", onDays.length, onDays);270            }271            break;272        }273        case 1: {274            recRule.type = "WEEKLY";275            let ndays = Number(getElementValue("weekly-weeks"));276            recRule.interval = ndays;277            let onDays = document.getElementById("daypicker-weekday").days;278            if (onDays.length > 0) {279                recRule.setComponent("BYDAY", onDays.length, onDays);280            }281            break;282        }283        case 2: {284            recRule.type = "MONTHLY";285            let monthInterval = Number(getElementValue("monthly-interval"));286            recRule.interval = monthInterval;287            let monthlyGroup = document.getElementById("monthly-group");288            if (monthlyGroup.selectedIndex == 0) {289                let monthlyOrdinal = Number(getElementValue("monthly-ordinal"));290                let monthlyDOW = Number(getElementValue("monthly-weekday"));291                if (monthlyDOW < 0) {292                    if (monthlyOrdinal == 0) {293                        // Monthly rule "Every day of the month".294                        recRule.setComponent("BYDAY", 7, ALL_WEEKDAYS);295                    } else {296                        // One of the first five days or the last day of the month.297                        recRule.setComponent("BYMONTHDAY", 1, [monthlyOrdinal]);298                    }299                } else {300                    let sign = monthlyOrdinal < 0 ? -1 : 1;301                    let onDays = [(Math.abs(monthlyOrdinal) * 8 + monthlyDOW) * sign];302                    recRule.setComponent("BYDAY", onDays.length, onDays);303                }304            } else {305                let monthlyDays = document.getElementById("monthly-days").days;306                if (monthlyDays.length > 0) {307                    recRule.setComponent("BYMONTHDAY", monthlyDays.length, monthlyDays);308                }309            }310            break;311        }312        case 3: {313            recRule.type = "YEARLY";314            let yearInterval = Number(getElementValue("yearly-interval"));315            recRule.interval = yearInterval;316            let yearlyGroup = document.getElementById("yearly-group");317            if (yearlyGroup.selectedIndex == 0) {318                let yearlyByMonth = [Number(getElementValue("yearly-month-ordinal"))];319                recRule.setComponent("BYMONTH", yearlyByMonth.length, yearlyByMonth);320                let yearlyByDay = [Number(getElementValue("yearly-days"))];321                recRule.setComponent("BYMONTHDAY", yearlyByDay.length, yearlyByDay);322            } else {323                let yearlyByMonth = [Number(getElementValue("yearly-month-rule"))];324                recRule.setComponent("BYMONTH", yearlyByMonth.length, yearlyByMonth);325                let yearlyOrdinal = Number(getElementValue("yearly-ordinal"));326                let yearlyDOW = Number(getElementValue("yearly-weekday"));327                if (yearlyDOW < 0) {328                    if (yearlyOrdinal == 0) {329                        // Yearly rule "Every day of a month".330                        recRule.setComponent("BYDAY", 7, ALL_WEEKDAYS);331                    } else {332                        // One of the first five days or the last of a month.333                        recRule.setComponent("BYMONTHDAY", 1, [yearlyOrdinal]);334                    }335                } else {336                    let sign = yearlyOrdinal < 0 ? -1 : 1;337                    let onDays = [(Math.abs(yearlyOrdinal) * 8 + yearlyDOW) * sign];338                    recRule.setComponent("BYDAY", onDays.length, onDays);339                }340            }341            break;342        }343    }344    // Figure out how long this event is supposed to last345    switch (document.getElementById("recurrence-duration").selectedItem.value) {346        case "forever": {347            recRule.count = -1;348            break;349        }350        case "ntimes": {351            recRule.count = Math.max(1, getElementValue("repeat-ntimes-count"));352            break;353        }354        case "until": {355            let untilDate = cal.jsDateToDateTime(getElementValue("repeat-until-date"), gStartTime.timezone);356            untilDate.isDate = gStartTime.isDate; // enforce same value type as DTSTART357            if (!gStartTime.isDate) {358                // correct UNTIL to exactly match start date's hour, minute, second:359                untilDate.hour = gStartTime.hour;360                untilDate.minute = gStartTime.minute;361                untilDate.second = gStartTime.second;362            }363            recRule.untilDate = untilDate;364            break;365        }366    }367    if (recRule.interval < 1) {368        return null;369    }370    recurrenceInfo.insertRecurrenceItemAt(recRule, 0);371    return recurrenceInfo;372}373/**374 * Handler function to be called when the accept button is pressed.375 *376 * @return      Returns true if the window should be closed377 */378function onAccept() {379    let args = window.arguments[0];380    let item = args.calendarEvent;381    args.onOk(onSave(item));382    // Don't close the dialog if a warning must be showed.383    return !checkUntilDate.warning;384}385/**386 * Handler function to be called when the Cancel button is pressed.387 *388 * @return      Returns true if the window should be closed389 */390function onCancel() {391    // Don't show any warning if the dialog must be closed.392    checkUntilDate.warning = false;393    return true;394}395/**396 * Handler function called when the calendar is changed (also for initial397 * setup).398 *399 * XXX we don't change the calendar in this dialog, this function should be400 * consolidated or renamed.401 *402 * @param calendar    The calendar to use for setup.403 */404function onChangeCalendar(calendar) {405    let args = window.arguments[0];406    let item = args.calendarEvent;407    // Set 'gIsReadOnly' if the calendar is read-only408    gIsReadOnly = false;409    if (calendar && calendar.readOnly) {410        gIsReadOnly = true;411    }412    // Disable or enable controls based on a set or rules413    // - whether this item is a stand-alone item or an occurrence414    // - whether or not this item is read-only415    // - whether or not the state of the item allows recurrence rules416    //     - tasks without an entrydate are invalid417    disableOrEnable(item);418    updateRecurrenceControls();419}420/**421 * Disable or enable certain controls based on the given item:422 * Uses the following attribute:423 *424 * - disable-on-occurrence425 * - disable-on-readonly426 *427 * A task without a start time is also considered readonly.428 *429 * @param item        The item to check.430 */431function disableOrEnable(item) {432    if (item.parentItem != item) {433        disableRecurrenceFields("disable-on-occurrence");434    } else if (gIsReadOnly) {435        disableRecurrenceFields("disable-on-readonly");436    } else if (cal.isToDo(item) && !gStartTime) {437        disableRecurrenceFields("disable-on-readonly");438    } else {439        enableRecurrenceFields("disable-on-readonly");440    }441}442/**443 * Disables all fields that have an attribute that matches the argument and is444 * set to "true".445 *446 * @param aAttributeName    The attribute to search for.447 */448function disableRecurrenceFields(aAttributeName) {449    let disableElements = document.getElementsByAttribute(aAttributeName, "true");450    for (let i = 0; i < disableElements.length; i++) {451        disableElements[i].setAttribute("disabled", "true");452    }453}454/**455 * Enables all fields that have an attribute that matches the argument and is456 * set to "true".457 *458 * @param aAttributeName    The attribute to search for.459 */460function enableRecurrenceFields(aAttributeName) {461    let enableElements = document.getElementsByAttribute(aAttributeName, "true");462    for (let i = 0; i < enableElements.length; i++) {463        enableElements[i].removeAttribute("disabled");464    }465}466/**467 * Split rules into negative and positive rules.468 *469 * XXX This function is duplicate from calendar-dialog-utils.js, which we may470 * want to include in this dialog.471 *472 * @param recurrenceInfo    An item's recurrence info to parse.473 * @return                  An array with two elements: an array of positive474 *                            rules and an array of negative rules.475 */476function splitRecurrenceRules(recurrenceInfo) {477    let recItems = recurrenceInfo.getRecurrenceItems({});478    let rules = [];479    let exceptions = [];480    for (let recItem of recItems) {481        if (recItem.isNegative) {482            exceptions.push(recItem);483        } else {484            rules.push(recItem);485        }486    }487    return [rules, exceptions];488}489/**490 * Handler function to update the period-deck when an item from the period-list491 * is selected. Also updates the controls on that deck.492 */493function updateRecurrenceDeck() {494    document.getElementById("period-deck")495            .selectedIndex = Number(getElementValue("period-list"));496    updateRecurrenceControls();497}498/**499 * Updates the controls regarding ranged controls (i.e repeat forever, repeat500 * until, repeat n times...)501 */502function updateRecurrenceRange() {503    let args = window.arguments[0];504    let item = args.calendarEvent;505    if (item.parentItem != item || gIsReadOnly) {506        return;507    }508    let radioRangeForever =509        document.getElementById("recurrence-range-forever");510    let radioRangeFor =511        document.getElementById("recurrence-range-for");512    let radioRangeUntil =513        document.getElementById("recurrence-range-until");514    let rangeTimesCount =515        document.getElementById("repeat-ntimes-count");516    let rangeUntilDate =517        document.getElementById("repeat-until-date");518    let rangeAppointmentsLabel =519        document.getElementById("repeat-appointments-label");520    radioRangeForever.removeAttribute("disabled");521    radioRangeFor.removeAttribute("disabled");522    radioRangeUntil.removeAttribute("disabled");523    rangeAppointmentsLabel.removeAttribute("disabled");524    let durationSelection = document.getElementById("recurrence-duration")525                                    .selectedItem.value;526    if (durationSelection == "ntimes") {527        rangeTimesCount.removeAttribute("disabled");528    } else {529        rangeTimesCount.setAttribute("disabled", "true");530    }531    if (durationSelection == "until") {532        rangeUntilDate.removeAttribute("disabled");533    } else {534        rangeUntilDate.setAttribute("disabled", "true");535    }536}537/**538 * Updates the recurrence preview calendars using the window's item.539 */540function updatePreview() {541    let args = window.arguments[0];542    let item = args.calendarEvent;543    if (item.parentItem != item) {544        item = item.parentItem;545    }546    // TODO: We should better start the whole dialog with a newly cloned item547    // and always pump changes immediately into it. This would eliminate the548    // need to break the encapsulation, as we do it here. But we need the item549    // to contain the startdate in order to calculate the recurrence preview.550    item = item.clone();551    let kDefaultTimezone = cal.calendarDefaultTimezone();552    if (cal.isEvent(item)) {553        let startDate = gStartTime.getInTimezone(kDefaultTimezone);554        let endDate = gEndTime.getInTimezone(kDefaultTimezone);555        if (startDate.isDate) {556            endDate.day--;557        }558        item.startDate = startDate;559        item.endDate = endDate;560    }561    if (cal.isToDo(item)) {562        let entryDate = gStartTime;563        if (entryDate) {564            entryDate = entryDate.getInTimezone(kDefaultTimezone);565        } else {566            item.recurrenceInfo = null;567        }568        item.entryDate = entryDate;569        let dueDate = gEndTime;570        if (dueDate) {571            dueDate = dueDate.getInTimezone(kDefaultTimezone);572        }573        item.dueDate = dueDate;574    }575    let recInfo = onSave(item);576    let preview = document.getElementById("recurrence-preview");577    preview.updatePreview(recInfo);578}579/**580 * Checks the until date just entered in the datepicker in order to avoid581 * setting a date earlier than the start date.582 * Restores the previous correct date, shows a warning and prevents to close the583 * dialog when the user enters a wrong until date.584 */585function checkUntilDate() {586    let untilDate = cal.jsDateToDateTime(getElementValue("repeat-until-date"), gStartTime.timezone);587    let startDate = gStartTime.clone();588    startDate.isDate = true;589    if (untilDate.compare(startDate) < 0) {590        let repeatDate = cal.dateTimeToJsDate((gUntilDate || gStartTime).getInTimezone(cal.floating()));591        setElementValue("repeat-until-date", repeatDate);592        checkUntilDate.warning = true;593        let callback = function() {594            // No warning when the dialog is being closed with the Cancel button.595            if (!checkUntilDate.warning) {596                return;597            }598            Services.prompt.alert(null, document.title,599                                  cal.calGetString("calendar", "warningUntilDateBeforeStart"));600            checkUntilDate.warning = false;601        };602        setTimeout(callback, 1);603    } else {604        gUntilDate = untilDate;605        updateRecurrenceControls();...wizardTabAdvanced.js
Source:wizardTabAdvanced.js  
...137		 *138		 * @param {string} isConfigActive contains an int139		 */140		setConfigurationState: function(isConfigActive) {141			this.setElementValue(142				this.managedItems.ldap_configuration_active.$element, isConfigActive143			);144		},145		/**146		 * updates the backup host configuration text field147		 *148		 * @param {string} host149		 */150		setBackupHost: function(host) {151			this.setElementValue(this.managedItems.ldap_backup_host.$element, host);152		},153		/**154		 * updates the backup port configuration text field155		 *156		 * @param {string} port157		 */158		setBackupPort: function(port) {159			this.setElementValue(this.managedItems.ldap_backup_port.$element, port);160		},161		/**162		 * sets whether the main server should be overridden or not163		 *164		 * @param {string} doOverride contains an int165		 */166		setOverrideMainServerState: function(doOverride) {167			this.setElementValue(168				this.managedItems.ldap_override_main_server.$element, doOverride169			);170		},171		/**172		 * sets whether the SSL/TLS certification check shout be disabled173		 *174		 * @param {string} doCertCheck contains an int175		 */176		setCertCheckDisabled: function(doCertCheck) {177			this.setElementValue(178				this.managedItems.ldap_turn_off_cert_check.$element, doCertCheck179			);180		},181		/**182		 * sets the time-to-live of the LDAP cache (in seconds)183		 *184		 * @param {string} cacheTTL contains an int185		 */186		setCacheTTL: function(cacheTTL) {187			this.setElementValue(this.managedItems.ldap_cache_ttl.$element, cacheTTL);188		},189		/**190		 * sets the user display name attribute191		 *192		 * @param {string} attribute193		 */194		setUserDisplayName: function(attribute) {195			this.setElementValue(this.managedItems.ldap_display_name.$element, attribute);196		},197		/**198		 * sets the additional user display name attribute199		 *200		 * @param {string} attribute201		 */202		setUserDisplayName2: function(attribute) {203			this.setElementValue(this.managedItems.ldap_user_display_name_2.$element, attribute);204		},205		/**206		 * sets the Base DN for users207		 *208		 * @param {string} base209		 */210		setBaseDNUsers: function(base) {211			this.setElementValue(this.managedItems.ldap_base_users.$element, base);212		},213		/**214		 * sets the attributes for user searches215		 *216		 * @param {string} attributes217		 */218		setSearchAttributesUsers: function(attributes) {219			this.setElementValue(this.managedItems.ldap_attributes_for_user_search.$element, attributes);220		},221		/**222		 * sets the display name attribute for groups223		 *224		 * @param {string} attribute225		 */226		setGroupDisplayName: function(attribute) {227			this.setElementValue(this.managedItems.ldap_group_display_name.$element, attribute);228		},229		/**230		 * sets the Base DN for groups231		 *232		 * @param {string} base233		 */234		setBaseDNGroups: function(base) {235			this.setElementValue(this.managedItems.ldap_base_groups.$element, base);236		},237		/**238		 * sets the attributes for group search239		 *240		 * @param {string} attributes241		 */242		setSearchAttributesGroups: function(attributes) {243			this.setElementValue(this.managedItems.ldap_attributes_for_group_search.$element, attributes);244		},245		/**246		 * sets the attribute for the association of users and groups247		 *248		 * @param {string} attribute249		 */250		setGroupMemberAssociationAttribute: function(attribute) {251			this.setElementValue(this.managedItems.ldap_group_member_assoc_attribute.$element, attribute);252		},253		/**254		  * sets the dynamic group member url attribute255		  *256		  * @param {string} attribute257		  */258		setDynamicGroupMemberURL: function(attribute) {259			this.setElementValue(this.managedItems.ldap_dynamic_group_member_url.$element, attribute);260		},261                262		/**263		 * enabled or disables the use of nested groups (groups in groups in264		 * groupsâ¦)265		 *266		 * @param {string} useNestedGroups contains an int267		 */268		setUseNestedGroups: function(useNestedGroups) {269			this.setElementValue(this.managedItems.ldap_nested_groups.$element, useNestedGroups);270		},271		/**272		 * sets the size of pages for paged search273		 *274		 * @param {string} size contains an int275		 */276		setPagingSize: function(size) {277			this.setElementValue(this.managedItems.ldap_paging_size.$element, size);278		},279		/**280		 * sets whether the password changes per user should be enabled281		 *282		 * @param {string} doPasswordChange contains an int283		 */284		setPasswordChangeEnabled: function(doPasswordChange) {285			this.setElementValue(286				this.managedItems.ldap_turn_on_pwd_change.$element, doPasswordChange287			);288		},289		/**290		  * sets the default ppolicy attribute291		  *292		  * @param {string} attribute293		  */294		setDefaultPPolicyDN: function(attribute) {295			this.setElementValue(this.managedItems.ldap_default_ppolicy_dn.$element, attribute);296		},297		/**298		 * sets the email attribute299		 *300		 * @param {string} attribute301		 */302		setEmailAttribute: function(attribute) {303			this.setElementValue(this.managedItems.ldap_email_attr.$element, attribute);304		},305		/**306		 * sets the external storage home attribute307		 *308		 * @param {string} attribute309		 */310		setExternalStorageHomeAttribute: function(attribute) {311			this.setElementValue(this.managedItems.ldap_ext_storage_home_attribute.$element, attribute);312		},313		/**314		 * sets the quota attribute315		 *316		 * @param {string} attribute317		 */318		setQuotaAttribute: function(attribute) {319			this.setElementValue(this.managedItems.ldap_quota_attr.$element, attribute);320		},321		/**322		 * sets the default quota for LDAP users323		 *324		 * @param {string} quota contains an int325		 */326		setQuotaDefault: function(quota) {327			this.setElementValue(this.managedItems.ldap_quota_def.$element, quota);328		},329		/**330		 * sets the attribute for the Nextcloud user specific home folder location331		 *332		 * @param {string} attribute333		 */334		setHomeFolderAttribute: function(attribute) {335			this.setElementValue(this.managedItems.home_folder_naming_rule.$element, attribute);336		},337		/**338		 * deals with the result of the Test Connection test339		 *340		 * @param {WizardTabAdvanced} view341		 * @param {FeaturePayload} payload342		 */343		onResultReceived: function(view, payload) {344			if(payload.feature === 'TestConfiguration') {345				OC.Notification.showTemporary(payload.data.message);346			}347		}348	});349	OCA.LDAP.Wizard.WizardTabAdvanced = WizardTabAdvanced;...chilliController.js
Source:chilliController.js  
...19function showPage(page) { 20    var e = document.getElementById(page);21    if (e != null) e.style.display='inline';22}23function setElementValue(elem, val, forceHTML) {24    var e = document.getElementById(elem);25    if (e != null) {26	var node = e;27	if (!forceHTML && node.firstChild) {28	    node = node.firstChild;29	    node.nodeValue = val;30	} else {31	    node.innerHTML = val;32	}33    }34}35chilliClock.onChange = function ( newval ) {36    setElementValue("sessionTime", chilliController.formatTime(newval));37}38    39function updateUI (cmd ) {40    log ( "Update UI is called. chilliController.clientState = " + chilliController.clientState ) ; 41    42    clearTimeout ( delayTimer );43    if ( chilliController.redir ) {44	if (chilliController.redir.originalURL != null &&45	    chilliController.redir.originalURL != '') {46	    setElementValue('originalURL', '<a target="_blank" href="'+chilliController.redir.originalURL+47			    '">'+chilliController.redir.originalURL+'</a>', true);48	}49	if (chilliController.redir.redirectionURL != null &&50	    chilliController.redir.redirectionURL != '') {51	    setElementValue('redirectionURL', chilliController.redir.redirectionURL);52	}53    }54    if ( chilliController.message ) {55	setElementValue('logonMessage', chilliController.message);56	chilliController.message = null;57	chilliController.refresh();58    }59    if ( chilliController.location ) {60	setElementValue('locationName', chilliController.location.name);61	chilliController.location = null;62    }63    if ( chilliController.clientState == 0 ) {64        showLogonPage();65    }66    if ( chilliController.clientState == 1 ) {67        if ( chilliController.statusURL ) {68	   chilliController.statusWindow = window.open(chilliController.statusURL, "");69	} else {70	   showStatusPage();71        }72    }73    if (chilliController.redir.redirectionURL) {74	//chilliController.nextWindow = window.open(chilliController.redir.redirectionURL,'nextURL');75	window.location.href = chilliController.redir.redirectionURL;76	chilliController.redir.redirectionURL = null;77    }78    79    if ( chilliController.clientState == 2 ) showWaitPage();80}81function handleError( code ) {82    clearTimeout(delayTimer);83    //showErrorPage(code);84}85/* Action triggered when buttons are pressed */86function connect() {87    var username =  document.getElementById('username').value ;88    var password =  document.getElementById('password').value ;89    if (username == null || username == '')90	return setElementValue('logonMessage', 'Username is required');91    92    showWaitPage(1000);93    chilliController.logon( username , password ) ;94}95function disconnect() {96    if (confirm("Are you sure you want to disconnect now?")) {97	chilliClock.stop();98	showWaitPage(1000);99	chilliController.logoff();100    }101    return false;102}103/* User interface pages update */104function showLogonPage() {105    if (chilliController.openid) 106        showPage('openIDSelect');107    showPage("logonPage");108    hidePage("statusPage");109    hidePage("waitPage");110    hidePage("errorPage");111}112function showStatusPage() {113    hidePage("logonPage");114    showPage("statusPage");115    hidePage("waitPage");116    hidePage("errorPage");117    118    // Update message119    if ( chilliController.message ) { 120	setElementValue("statusMessage", chilliController.message);121    }122    123    // Update session124    setElementValue("sessionId",125		    chilliController.session.sessionId ?126		    chilliController.session.sessionId :127		    "Not available");128    setElementValue("startTime",129		    chilliController.session.startTime ?130		    chilliController.session.startTime :131		    "Not available");132    133    setElementValue("sessionTimeout",134		    chilliController.formatTime(chilliController.session.sessionTimeout, 'unlimited'));135    setElementValue("idleTimeout",136		    chilliController.formatTime(chilliController.session.idleTimeout, 'unlimited'));137    setElementValue("maxInputOctets",138		    chilliController.formatBytes(chilliController.session.maxInputOctets));139    setElementValue("maxOutputOctets",140		    chilliController.formatBytes(chilliController.session.maxOutputOctets));141    setElementValue("maxTotalOctets",142		    chilliController.formatBytes(chilliController.session.maxTotalOctets));143    // Update accounting144    setElementValue("sessionTime",145		    chilliController.formatTime(chilliController.accounting.sessionTime));146    147    setElementValue("idleTime",148		    chilliController.formatTime(chilliController.accounting.idleTime));149    150    setElementValue("inputOctets" , chilliController.formatBytes(chilliController.accounting.inputOctets));151    setElementValue("outputOctets", chilliController.formatBytes(chilliController.accounting.outputOctets));152    153    chilliClock.resync (chilliController.accounting.sessionTime);154}155function showOpenIDForm(e)156{157     var form = document.getElementById('openIDForm');158     var x = document.createElement('div');159     x.style.display = 'block';160     x.style.position = 'absolute';161     x.style.top = e.y - 25;162     x.style.left = e.x + 25;163     x.style.xIndex = 2;164     x.innerHTML = form.innerHTML;165     document.body.appendChild(x);166}167function openID() {168  var openIDSelect = document.getElementById('openIDSelect');169  openIDSelect.onclick = function(e) {170     if (!e) e = window.event;171     e.stopPropagation;172     showOpenIDForm(e);173  };174  var openIDForm = document.getElementById('openIDForm');175  openIDForm.onclick = function(e) {176    if (!e) e = window.event;177    e.stopPropagation;178  };179  document.onclick = closeOpenIDForm();180}181function closeOpenIDForm() {182  hidePage('openIDForm');183}184function showWaitPage(delay) {185    /* Wait for delay  */186    clearTimeout(delayTimer);	187    if (typeof(delay) == 'number' && (delay > 10)) {188	delayTimer= setTimeout('showWaitPage(0)' , delay);189	return;190    }191    192    /* show the waitPage */193    hidePage("logonPage");194    hidePage("statusPage");195    showPage("waitPage");196    hidePage("errorPage");197}198function showErrorPage( str )  {199    setTimeout('chilliController.refresh()', 15000);200    201    hidePage("logonPage");202    hidePage("statusPage");203    hidePage("waitPage");204    showPage("errorPage");205    setElementValue("errorMessage", str);206}207var chillijsWindowOnLoad = window.onload;208var delayTimer; // global reference to delayTimer209window.onload = function() {210    if (chillijsWindowOnLoad) 211	chillijsWindowOnLoad();212    var logonForm = document.getElementById('logonForm');213    var head = document.getElementsByTagName("head")[0];214    if (head == null) head = document.body;215    if (logonForm == null) {216        logonForm = document.getElementById('loginForm');217    }218    if (logonForm == null) {219        try {...subAccountDocument.js
Source:subAccountDocument.js  
...62	var subAccountTypeCode = getElementValue( subAccountTypeCodeFieldName );63	//alert("chartCode = " + chartCode + ", accountNumber = " + accountNumber + ", subAccountTypeCode = " + subAccountTypeCode);64	65	if (chartCode == "" || accountNumber == "" || subAccountTypeCode == "") {66		setElementValue( prefix + ".financialIcrSeriesIdentifier", "" );67//		setElementValue( prefix + ".indirectCostRcvyFinCoaCode", "" );68//		setElementValue( prefix + ".indirectCostRecoveryAcctNbr", "" );69		setElementValue( prefix + ".offCampusCode", "" );70		setElementValue( prefix + ".indirectCostRecoveryTypeCode", "" );71	}72	else {73		var dwrReply = {74			callback:updateCgIcrAccount_Callback,75			errorHandler:function( errorMessage ) { 76				window.status = errorMessage;77			}78		};	79		A21SubAccountService.buildCgIcrAccount( chartCode, accountNumber, null, subAccountTypeCode, dwrReply );80	}81}82function updateCgIcrAccount_Callback( data ) {	83	var prefix = "document.newMaintainableObject.a21SubAccount";84	85	if (data != null) {86		setElementValue( prefix + ".financialIcrSeriesIdentifier", data.financialIcrSeriesIdentifier );87//		setElementValue( prefix + ".indirectCostRcvyFinCoaCode", data.indirectCostRcvyFinCoaCode );88//		setElementValue( prefix + ".indirectCostRecoveryAcctNbr", data.indirectCostRecoveryAcctNbr );89		setElementValue( prefix + ".offCampusCode", data.offCampusCode );90		setElementValue( prefix + ".indirectCostRecoveryTypeCode", data.indirectCostRecoveryTypeCode );91	}92	else{93		setElementValue( prefix + ".financialIcrSeriesIdentifier", "" );94//		setElementValue( prefix + ".indirectCostRcvyFinCoaCode", "" );95//		setElementValue( prefix + ".indirectCostRecoveryAcctNbr", "" );96		setElementValue( prefix + ".offCampusCode", "" );97		setElementValue( prefix + ".indirectCostRecoveryTypeCode", "" );98	}99}100/* This function is for the a21SubAccount account numbers in SubAccount BO. */101function onblur_accountNumberA21Sub( accountNumberField, chartCodePropertyName ) {102	// need to call findElPrefix twice to strip off the a21SubAccount prefix103	var accountNumberFieldName = accountNumberField.name;104	var fieldPrefix = findElPrefix( findElPrefix(accountNumberFieldName) );105	var chartCodeFieldName = fieldPrefix + "." + chartCodePropertyName;106	//alert("chartCodeFieldName = " + chartCodeFieldName + ", accountNumberFieldName = " + accountNumberFieldName);107	var dwrReply = {108		callback: function (param) {109			if ( typeof param == "boolean" && param == false) {	110				loadChartCode(chartCodeFieldName, accountNumberFieldName, null, false);111			}...app.js
Source:app.js  
...56        avatar_url: avatarUrl57    } = user58    const formattedJoinedDate = new Date(joinedAt).toDateString()59    // SET VALUES60    setElementValue("src", $userAvatarEl, avatarUrl, "");61    setElementValue("innerHTML", $userNameEl, name, "Unknown");62    setElementValue("innerHTML", $userSurnameEl, `@${username}`, "");63    setElementValue("innerHTML", $userJoinedAtEl, `Joined ${formattedJoinedDate}`, "Unknown");64    setElementValue("innerHTML", $userBioEl, bio, "This profile has no bio");65    setElementValue("innerHTML", $userFollowingEl, following, 0);66    setElementValue("innerHTML", $userFollowersEl, followers, 0);67    setElementValue("innerHTML", $userReposEl, public_repos, 0);68    setElementValue("innerHTML", $userLocationEl, location, "Unknown");69    setElementValue("innerHTML", $userSocialNetworkEl, twitter_username, "Not Available");70    setElementValue("innerHTML", $userGithubProfileEl, profileLink, "Unknown");71    setElementValue("innerHTML", $userCompanyEl, company, "No Company");72}73let currentUser = undefined;74$searchButton.addEventListener('click', (e) => {75    (async() => {76        const usernameInputValue = $usernameInput.value77        if (!usernameInputValue || usernameInputValue == currentUser) return;78        // hide current hero content79        $heroContent.classList.remove('is-active')80        // waits clip-path transition duration81        await new Promise((resolve, reject) => { setTimeout(() => resolve(), 600) })82        const apiResponse = await (await fetch(`${apiBase}/${apiUsersEndpoint}/${usernameInputValue}`)).json()83        if (!apiResponse.id) {84            $heroBackDropMessage.innerHTML = `Oops, user was not found!`85            $heroBackDrop.classList.add('is-active')...setElementValue.test.js
Source:setElementValue.test.js  
1const checkElementValue = require('../../features/support/check/checkElementValue');2const setElementValue = require('../../features/support/action/setElementValue');3const openUrl = require('../../features/support/action/openUrl');4const BrowserScope = require('../../features/support/scope/BrowserScope');5const testUrl = 'http://localhost:8080/setElementValue.html';6const browserScope = new BrowserScope();7beforeAll(async () => {8  await browserScope.init();9  await openUrl.call(browserScope, testUrl);  10});11afterAll(async () => {12  await browserScope.close();13});14describe('setElementValue', () => {15  it('sets the value of an input element', async () => {16    await checkElementValue.call(browserScope, 'input.enabled', null, 'some filler value');17    await setElementValue.call(browserScope, 'input.enabled', 'clean living');18    await checkElementValue.call(browserScope, 'input.enabled', null, 'clean living');19  });20  it('sets the value of a textarea', async () => {21    await checkElementValue.call(browserScope, 'textarea', null, '');22    await setElementValue.call(browserScope, 'textarea', 'another text value now');23    await checkElementValue.call(browserScope, 'textarea', null, 'another text value now');24  });  25  it('sets the value of a select element when the value is part of the select element options', async () => {26    await checkElementValue.call(browserScope, 'select', null, '');27    await setElementValue.call(browserScope, 'select', 'spongebob');28    await checkElementValue.call(browserScope, 'select', null, 'spongebob');29  });30  it('fails to set the value of a select when the options do not contain the value', async () => {31    await checkElementValue.call(browserScope, 'select', null, 'spongebob');32    await expect(setElementValue.call(browserScope, 'select', 'squidward')).rejects.toThrow('Error: unable to set "select" value to "squidward"');33    await checkElementValue.call(browserScope, 'select', null, 'spongebob');34  });    35  it('fails if the element is disabled and does not allow its value to be set', async () => {36    await expect(setElementValue.call(browserScope, 'input[disabled]', 'bambaz')).rejects.toThrow('Error: unable to set "input[disabled]" value to "bambaz"');37  });  38  it('fails if the element is readonly and does not allow its value to be set', async () => {39    await expect(setElementValue.call(browserScope, 'input[readonly]', 'plumbus')).rejects.toThrow('Error: unable to set "input[readonly]" value to "plumbus"');40  });    ...order-confirmation.js
Source:order-confirmation.js  
1var orderListObj = JSON.parse(sessionStorage.order_submitted)2var orderList = orderListObj.order3function setElementValue(element, value){4    if(value){5        $(element).append(value);6    }7}8setElementValue("#order_num", orderList._id);9setElementValue("#date", getDateFormattedString(orderList.order_date));10setElementValue("#phone_no", orderList.phone_no);11setElementValue("#emergency_phone_no", orderList.emergency_no);12setElementValue("#email", orderList.email);13setElementValue("#first_line", orderList.address.first_line);14setElementValue("#second_line", orderList.address.second_line);15setElementValue("#third_line", orderList.address.third_line);16setElementValue("#city", orderList.address.city);17setElementValue("#postcode", orderList.address.postcode);18setElementValue("#state", orderList.address.state);19setElementValue("#country", orderList.address.country);20var orderProductItems = orderList.order_product;21$.each( orderProductItems , function( index, obj ){22    $('#product_list').append(23        "<tr>" +24            "<td><h5>" + obj.product_name + "</h5></td>" +25            "<td><p>" +  obj.quantity + "</p></td>" +26            "<td><p>" + getStringById('string_payment_method')[obj.payment_type]  + "</p></td>" +27            "<td><p>RM " + obj.payment + "</p></td>" +28        "</tr>"29    );30});31if (orderList.voucher_code == ''){32    $('#product_list').append(33        "<tr>" +...Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3        .typeText('#developer-name', 'John Smith')4        .click('#tried-test-cafe')5        .setElementValue('#developer-name', 'John Smith')6        .click('#submit-button');7});8await t.setElementValue('#developer-name', 'John Smith');9await t.setElementValue('#developer-name', 'John Smith');10await t.setElementValue('#developer-name', 'John Smith');11await t.setElementValue('#developer-name', 'John Smith');12await t.setElementValue('#developer-name', 'John Smith');13await t.setElementValue('#developer-name', 'John Smith');Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3        .setNativeDialogHandler(() => true)4        .click('#populate')5        .click('#submit-button');6});7import { Selector } from 'testcafe';8test('My first test', async t => {9        .setNativeDialogHandler(() => true)10        .click('#populate')11        .click('#submit-button');12});13import { Selector } from 'testcafe';14test('My first test', async t => {15        .setNativeDialogHandler(() => true)16        .click('#populate')17        .click('#submit-button');18});19import { Selector } from 'testcafe';20test('My first test', async t => {21        .setNativeDialogHandler(() => true)22        .click('#populate')23        .click('#submit-button');24});25import { Selector } from 'testcafe';26test('My first test', async t => {27        .setNativeDialogHandler(() => true)28        .click('#populate')29        .click('#submit-button');30});31import { Selector } from 'testcafe';32test('My first test', async t => {33        .setNativeDialogHandler(() => true)34        .click('#populate')35        .click('#submit-button');36});37import { Selector } from 'Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3        .typeText('#developer-name', 'John Smith')4        .click('#submit-button');5});6const puppeteer = require('puppeteer');7(async () => {8    const browser = await puppeteer.launch();9    const page = await browser.newPage();10    await page.type('#developer-name', 'John Smith');11    await page.click('#submit-button');12    await browser.close();13})();Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3        .typeText('#developer-name', 'John Smith')4        .click('#submit-button');5});6test('My second test', async t => {7        .setElementValue('#developer-name', 'John Smith')8        .click('#submit-button');9});10{11    "scripts": {12    },13    "devDependencies": {14    }15}16{17    "compilerOptions": {18        "paths": {19        },20    },21}22{23    "compilerOptions": {24        "paths": {25        },Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3    await t.setElementValue('#developer-name', 'John Smith');4});5{6    "scripts": {7    },8    "devDependencies": {9    }10}11{12    "dependencies": {13        "testcafe": {14            "requires": {Using AI Code Generation
1import { Selector, ClientFunction } from 'testcafe';2test('My first test', async t => {3        .typeText('#developer-name', 'John Smith')4        .click('#macos')5        .click('#submit-button');6    const getSelected = ClientFunction(() => document.querySelector('#article-header').textContent);7    const articleHeader = await getSelected();8    await t.expect(articleHeader).eql('Thank you, John Smith!');9});Using AI Code Generation
1import { Selector } from 'testcafe';2const input = Selector('input').withAttribute('type', 'text');3const button = Selector('button');4test('My Test', async t => {5        .setNativeDialogHandler(() => true)6        .click('#populate')7        .setElementValue(input, 'Peter Parker')8        .click(button);9});10import { Selector } from 'testcafe';11const input = Selector('input').withAttribute('type', 'text');12const button = Selector('button');13test('My Test', async t => {14        .setNativeDialogHandler(() => true)15        .click('#populate')16        .click(button);17});18import { Selector } from 'testcafe';19const input = Selector('input').withAttribute('type', 'text');20const button = Selector('button');21test('My Test', async t => {22        .setTestSpeed(0.1)23        .click('#populate')24        .click(button);25});26import { Selector } from 'testUsing AI Code Generation
1import { Selector } from 'testcafe';2const text = Selector('textarea').withAttribute('id', 'text');3await t.setElementValue(text, 'Hello World!');4import { Selector } from 'testcafe';5const text = Selector('textarea').withAttribute('id', 'text');6await t.setNativeDialogHandler(() => true);7await t.click('#confirm-button');8import { Selector } from 'testcafe';9const text = Selector('textarea').withAttribute('id', 'text');10await t.setTestSpeed(0.1);11await t.typeText(text, 'Hello World!');12import { Selector } from 'testcafe';13const text = Selector('textarea').withAttribute('id', 'text');14await t.takeElementScreenshot(text, 'textarea.png');15import { Selector } from 'testcafe';16const text = Selector('textarea').withAttribute('id', 'text');17await t.takeScreenshot('page.png');18import { Selector } from 'testcafe';19const text = Selector('textarea').withAttribute('id', 'text');20await t.typeText(text, 'Hello World!');21import { Selector } from 'testcafe';22const text = Selector('textarea').withAttribute('id', 'text');23await t.useRole(role);24import { Selector } from 'testcafe';25const text = Selector('textarea').withAttribute('id', 'text');26await t.wait(1000);27import { Selector } from 'testcafe';28const text = Selector('textarea').withAttribute('id', 'text');29await t.waitUntil(() => true);30import { Selector } from 'testcafe';31const text = Selector('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!!
