Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

29.3 KB
Raw Blame
/*
 * Copyright 2026, OpenRemote Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */
import "@openremote/or-icon";
import "@openremote/or-translate";
import "@openremote/or-vaadin-components/or-vaadin-button";
import "@openremote/or-vaadin-components/or-vaadin-checkbox";
import "@openremote/or-vaadin-components/or-vaadin-checkbox-group";
import "@openremote/or-vaadin-components/or-vaadin-date-picker";
import "@openremote/or-vaadin-components/or-vaadin-date-time-picker";
import "@openremote/or-vaadin-components/or-vaadin-dialog";
import "@openremote/or-vaadin-components/or-vaadin-number-field";
import "@openremote/or-vaadin-components/or-vaadin-radio-group";
import "@openremote/or-vaadin-components/or-vaadin-select";
import "@openremote/or-vaadin-components/or-vaadin-multi-select-combo-box";
import "@openremote/or-vaadin-components/or-vaadin-time-picker";
import { css, html, type PropertyValues, type TemplateResult } from "lit";
import { OrElement } from "@openremote/or-element";
import { customElement, property, query, state } from "lit/decorators.js";
import { when } from "lit/directives/when.js";
import { Util } from "@openremote/core";
import type { CalendarEvent } from "@openremote/model";
import { InputType } from "@openremote/or-vaadin-components/util";
import { translate, i18next } from "@openremote/or-translate";
import {
  dialogRenderer,
  dialogHeaderRenderer,
  dialogFooterRenderer,
  type OrVaadinDialog,
} from "@openremote/or-vaadin-components/or-vaadin-dialog";
import { Frequency as FrequencyValue, RRule, type Weekday, type WeekdayStr } from "rrule";
import {
  BY_RRULE_PARTS,
  EventTypes,
  FREQUENCIES,
  MONTHS,
  RFC_STRICT_NOT_APPLICABLE,
  RRULE_ENDS,
  WEEKDAYS,
} from "./util";
import moment from "moment";
import type { PartKeys, RRulePartKeys, Frequency, ByRRuleCombination, ByRRulePartsKeys } from "./types";

export type * from "./types";
export * from "./util";

function range(start: number, end: number): number[] {
  return Array.from({ length: end - start + 1 }, (_, i) => start + i);
}

const byWeekNoOptions = range(-53, 53).filter(Boolean); // Exclude 0
const byYearDayOptions = range(-366, 366).filter(Boolean);
const byMonthDayOptions = range(-31, 31).filter(Boolean);
const byHourOptions = range(1, 24);
const byMinuteOrSecondsOptions = range(1, 60);

export interface OrSchedulerChangedEventDetail {
  value?: CalendarEvent;
}

export class OrSchedulerChangedEvent extends CustomEvent<OrSchedulerChangedEventDetail> {
  public static readonly NAME = "or-scheduler-changed";

  constructor(value?: CalendarEvent) {
    super(OrSchedulerChangedEvent.NAME, {
      detail: { value },
      bubbles: true,
      composed: true,
    });
  }
}

export class OrSchedulerRemovedEvent extends CustomEvent<void> {
  public static readonly NAME = "or-scheduler-removed";

  constructor() {
    super(OrSchedulerRemovedEvent.NAME, {
      bubbles: true,
      composed: true,
    });
  }
}

declare global {
  export interface HTMLElementEventMap {
    [OrSchedulerChangedEvent.NAME]: OrSchedulerChangedEvent;
    [OrSchedulerRemovedEvent.NAME]: OrSchedulerRemovedEvent;
  }
}

@customElement("or-scheduler")
export class OrScheduler extends translate(i18next)(OrElement) {
  static styles = css`
    or-vaadin-dialog::part(overlay) {
      max-width: 600px;
    }

    .time-label {
      display: flex;
      & > :first-child {
        display: inline-block;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        &::first-letter {
          text-transform: uppercase;
        }
      }
    }
  `;

  @property({ type: Object })
  public defaultSchedule?: CalendarEvent;

  @property({ type: String })
  public defaultEventTypeLabel = "default";

  @property({ type: Boolean })
  public disableNegativeByPartValues = false;

  @property({ type: Array })
  public disabledFrequencies: Frequency[] = [];

  @property({ type: Array })
  public disabledRRuleParts: RRulePartKeys[] = [];

  @property({ type: Object })
  public disabledByPartCombinations: ByRRuleCombination = RFC_STRICT_NOT_APPLICABLE;

  @property({ type: String })
  public header = "scheduleActivity";

  @property({ type: Boolean })
  public isAllDay = true;

  @property({ type: Boolean })
  public open = false;

  @property({ type: Boolean })
  public removable = false;

  @property({ type: Object })
  public schedule?: CalendarEvent = this.defaultSchedule;

  @property({ type: Number })
  public timezoneOffset = 0;

  @state()
  protected _count = 1;

  @state()
  protected _ends: keyof typeof RRULE_ENDS = "never";

  @state()
  protected _eventType: EventTypes = EventTypes.default;

  @state()
  protected _rrule?: RRule;

  @query("#scheduler")
  protected _dialog!: OrVaadinDialog;

  protected _byRRuleParts?: RRulePartKeys[];
  protected _until = moment().toDate();

  protected get _scheduleWithOffset(): CalendarEvent | undefined {
    return this._applyTimezoneOffset(this.schedule, this.timezoneOffset);
  }

  protected set _scheduleWithOffset(schedule) {
    this.schedule = this._applyTimezoneOffset(schedule, -this.timezoneOffset);
  }

  protected get _timeLabel(): TemplateResult | undefined {
    if (this._eventType === EventTypes.default) {
      return html`<or-translate
        value="${this.defaultEventTypeLabel}"
        .options="${this._getDefaultMessageOptions()}"
      ></or-translate>`;
    }

    if (this._scheduleWithOffset) {
      const calendarEvent = this._scheduleWithOffset;

      if (calendarEvent.recurrence) {
        const diff = moment(calendarEvent.end).diff(calendarEvent.start, "days");
        const fromTo = {
          start: moment(calendarEvent.start).format("HH:mm"),
          end: moment(calendarEvent.end).format("HH:mm"),
        };

        let template: TemplateResult = html``;
        if (this.isAllDay && diff > 0) {
          template = html`<or-translate value="forDays" .options="${{ days: diff, count: diff }}"></or-translate>`;
        } else if (diff > 0) {
          template = html`<or-translate
            value="fromToDays"
            .options="${{ ...fromTo, days: diff, count: diff }}"
          ></or-translate>`;
        } else if (diff === 0) {
          template = html`<or-translate value="fromTo" .options="${fromTo}"></or-translate>`;
        }
        const fromToTemplate = html`<span>&nbsp;${template}</span>`;
        const monthNames = Object.values(MONTHS).map((m) => i18next.t(m)) as string[];
        const orderISO = Object.values(WEEKDAYS).map((w) => i18next.t(w)) as string[];
        const dayNames = [orderISO.pop()!, ...orderISO]; // Must start with Sunday
        const rule = this._rrule!.toText((id) => i18next.t(`rrule.${id}`), { dayNames, monthNames, tokens: {} });
        return html`<span class="time-label"><span>${rule}</span>${fromToTemplate}</span>`;
      }

      const format = this.isAllDay ? "DD-MM-YYYY" : "DD-MM-YYYY HH:mm";
      return html`<or-translate
        value="activeFromTo"
        .options="${{
          start: moment(calendarEvent.start).format(format),
          end: moment(calendarEvent.end).format(format),
        }}"
      ></or-translate>`;
    }
  }

  connectedCallback() {
    super.connectedCallback();

    const schedule = this._applyTimezoneOffset(this.schedule ?? this.defaultSchedule, this.timezoneOffset);
    if (schedule?.start && schedule?.start) {
      const start = moment(schedule?.start);
      const end = moment(schedule?.end);
      this.isAllDay = start.isSame(start.clone().startOf("day")) && end.isSame(end.clone().endOf("day"));
    }

    if (this.schedule?.recurrence) {
      const origOptions = RRule.fromString(this.schedule.recurrence).origOptions;
      if (origOptions.until) {
        this._until = moment(origOptions.until).toDate();
      } else if (origOptions.count) {
        this._count = origOptions.count;
      }
    }

    if (!this.schedule || Util.objectsEqual(this.schedule, this.defaultSchedule)) {
      this._eventType = EventTypes.default;
    } else {
      this._eventType = this.schedule?.recurrence ? EventTypes.recurrence : EventTypes.period;
    }
  }

  shouldUpdate(changedProps: PropertyValues) {
    // Follow the default schedule to supply a default end time if not provided
    if (this.schedule && !this.schedule.end && this.defaultSchedule?.end) {
      this.schedule = { ...this.schedule, end: this.defaultSchedule.end };
    }

    if (changedProps.has("schedule")) {
      if (this._scheduleWithOffset?.recurrence) {
        this._rrule = RRule.fromString(this._scheduleWithOffset.recurrence);
      } else if (this._eventType === EventTypes.default && this.defaultSchedule?.recurrence) {
        this._rrule = RRule.fromString(this.defaultSchedule.recurrence);
      }
    }

    if (changedProps.has("_rrule") && this._rrule) {
      this._byRRuleParts = BY_RRULE_PARTS.filter(
        (p) => !this.disabledByPartCombinations[FrequencyValue[this._rrule!.options.freq] as Frequency]?.includes(p)
      ).filter((p) => !this.disabledRRuleParts.includes(p));
      this._ends =
        (this._rrule?.origOptions?.until && "until") || (this._rrule?.origOptions?.count && "count") || "never";
    }
    return super.shouldUpdate(changedProps);
  }

  protected _setAllDay() {
    const schedule = this._scheduleWithOffset;
    if (this.isAllDay && this._eventType !== EventTypes.default) {
      const start = moment(schedule?.start).startOf("day").valueOf();
      const end = moment(schedule?.end).endOf("day").valueOf();
      this._scheduleWithOffset = { ...schedule, start, end };
    }
  }

  /**
   * Converts the recurrence rule to string and normalizes it.
   *
   * The UTC timezone offset 'Z' for the UNTIL rule part is removed,
   * because the timezone is configurable.
   * @param rrule The recurrence rule to normalize.
   * @returns String representation of the defined Recurrence Rule
   */
  protected _getRRule(rrule = this._rrule): string | undefined {
    return rrule
      ?.toString()
      ?.split("RRULE:")?.[1]
      ?.replace(/(UNTIL=\d+T\d+)Z/, "$1");
  }

  protected _setRRuleValue(value: any, key: PartKeys) {
    let origOptions = this._rrule?.origOptions;
    const calendarEvent = this._scheduleWithOffset!;

    if (key === "interval" || key === "freq" || key.startsWith("by")) {
      if (key === "byweekday") {
        origOptions!.byweekday = (value as WeekdayStr[]).map((d) => RRule[d]);
      } else if (key === "freq") {
        for (const part of BY_RRULE_PARTS) delete origOptions![part];
        origOptions![key as RRulePartKeys] = value;
      } else {
        origOptions![key as RRulePartKeys] = value;
      }
    } else if (key === "start") {
      const [year, month, date] = value.split("-").map(Number);
      const start = moment(calendarEvent.start).set({ year, month: month - 1, date });
      if (origOptions) {
        // A period event has no recurrence rule to keep in sync
        origOptions.dtstart = start.toDate();
      }
      calendarEvent.start = start.valueOf();
    } else if (key === "end") {
      const [year, month, date] = value.split("-").map(Number);
      calendarEvent.end = moment(calendarEvent.end)
        .set({ year, month: month - 1, date })
        .toDate()
        .getTime();
    } else if (key === "start-time") {
      const [hour, minute] = value.split(":");
      if (origOptions) {
        origOptions.dtstart = moment(calendarEvent.start).set({ hour, minute, second: 0, millisecond: 0 }).toDate();
      } else {
        origOptions = new RRule({
          dtstart: moment(calendarEvent.start).set({ hour, minute, second: 0, millisecond: 0 }).toDate(),
        }).origOptions;
      }
      calendarEvent.start = moment(origOptions.dtstart).toDate().getTime();
    } else if (key === "end-time") {
      const [hour, minute] = value.split(":");
      calendarEvent.end = moment(calendarEvent.end).set({ hour, minute, second: 0, millisecond: 0 }).toDate().getTime();
    } else {
      switch (key) {
        case "all-day":
          this.isAllDay = value;
          break;
        case "recurrence-ends":
          if (value === "until") {
            origOptions!.until = this._until;
            delete origOptions!.count;
          } else if (value === "count") {
            origOptions!.count = this._count;
            delete origOptions!.until;
          } else {
            delete origOptions!.count;
            delete origOptions!.until;
          }
          this._ends = value;
          break;
        case "until":
          this._until = new Date(value);
          origOptions!.until = this._until;
          break;
        case "count":
          this._count = value;
          origOptions!.count = this._count;
          break;
      }
    }

    if (this._eventType === EventTypes.recurrence) {
      this._rrule = new RRule(origOptions);
      this._scheduleWithOffset = { ...calendarEvent, recurrence: this._getRRule() };
    } else {
      this._scheduleWithOffset = { ...calendarEvent };
    }
  }

  protected _setCalendarEventType(event: any) {
    const value = event.target.value;
    this._eventType = value;

    const fallback = moment().startOf("day");
    if (value === EventTypes.default) {
      this.schedule = {
        start: this.defaultSchedule?.start ?? fallback.valueOf() - this.timezoneOffset,
        end: this.defaultSchedule?.end ?? fallback.endOf("day").valueOf() - this.timezoneOffset,
      };
      const recurrence = this.defaultSchedule?.recurrence;
      this._rrule = recurrence ? RRule.fromString(recurrence) : undefined;
      return;
    }

    const schedule = {
      start: this._scheduleWithOffset?.start ?? fallback.valueOf(),
      end: this._scheduleWithOffset?.end ?? fallback.endOf("day").valueOf(),
    };
    if (value === EventTypes.period) {
      this._scheduleWithOffset = schedule;
    } else {
      this._scheduleWithOffset = { ...schedule, recurrence: this._getRRule() ?? "FREQ=DAILY" };
    }
  }

  /**
   * Apply the timezone offset to the calendarEvent
   * @param schedule The schedule for which to add/substract the offset
   * @param offset The timezone offset in millis to apply
   * @returns The transformed calendar event
   */
  protected _applyTimezoneOffset(schedule: CalendarEvent | undefined, offset: number): CalendarEvent | undefined {
    if (schedule) {
      let { start, end, recurrence } = { ...schedule };
      if (recurrence && RRule.fromString(recurrence).origOptions.until) {
        const origOptions = RRule.fromString(recurrence).origOptions;
        origOptions.until = new Date(Number(origOptions.until) + offset);
        recurrence = this._getRRule(new RRule(origOptions));
      }
      return {
        start: start != null ? start + offset : start,
        end: end != null ? end + offset : end,
        recurrence,
      };
    }
  }

  protected _getDefaultMessageOptions(): { date: string; time: string } {
    return {
      date: moment.utc(this.defaultSchedule?.start).format("YYYY-MM-DD"),
      time: moment.utc(this.defaultSchedule?.start).format("HH:mm"),
    };
  }

  protected render() {
    return html`
      <or-vaadin-button style="max-width: 100%" @click="${() => this._dialog!.open()}"
        >${this._timeLabel}</or-vaadin-button
      >
      <or-vaadin-dialog
        id="scheduler"
        header-title="${i18next.t(this.header)}"
        ?opened="${this.open}"
        @closed="${this._onClose}"
        ${dialogHeaderRenderer(this._getDialogHeader, [])}
        ${dialogRenderer(this._getDialogContent, [
          this.defaultSchedule,
          this.defaultEventTypeLabel,
          this.disabledFrequencies,
          this.disabledRRuleParts,
          this.header,
          this.isAllDay,
          this.schedule,
          this.timezoneOffset,
          this._count,
          this._ends,
          this._rrule,
        ])}
        ${dialogFooterRenderer(this._getDialogFooter, [])}
      ></or-vaadin-dialog>
    `;
  }

  protected _getDialogHeader(): TemplateResult {
    return html`
      <vaadin-button theme="tertiary" @click="${this._onClose}">
        <or-icon icon="mdi:close"></or-icon>
      </vaadin-button>
    `;
  }

  protected _getDialogContent(): TemplateResult {
    const eventTypes = [
      { value: "default", label: i18next.t(this.defaultEventTypeLabel, this._getDefaultMessageOptions()) },
      { value: "period", label: i18next.t("planPeriod") },
      { value: "recurrence", label: i18next.t("planRecurrence") },
    ];

    return html` <style>
        /* Showing just a number is not intuitive when using numbers as options */
        vaadin-multi-select-combo-box-chip[slot="overflow"]::part(label)::before {
          content: "+";
        }

        vaadin-checkbox {
          font-weight: 600;
        }

        .period {
          display: flex;
          flex: 1;
          gap: 2px;
        }

        .section {
          background-color: white;
          border-radius: var(--lumo-border-radius-m);
          display: flex;
          flex-direction: column;
          padding: var(--lumo-space-l);
        }

        .label {
          margin-left: 10px;
        }
        or-vaadin-number-field[disabled] + .label {
          color: var(--lumo-contrast-20pct);
          user-select: revert;
          -webkit-user-select: none;
        }

        @media only screen and (min-width: 768px) {
          or-vaadin-date-picker[combined] {
            --vaadin-input-field-top-end-radius: 0;
            --vaadin-input-field-bottom-end-radius: 0;
          }
          or-vaadin-time-picker {
            --vaadin-input-field-top-start-radius: 0;
            --vaadin-input-field-bottom-start-radius: 0;
          }
        }

        @media only screen and (max-width: 768px) {
          .period {
            flex-wrap: wrap;
          }
        }
      </style>
      <div style="display: flex; flex-direction: column; gap: var(--lumo-space-m)">
        <div id="event-type" class="section">
          <h4><or-translate value="schedule.type"></or-translate></h4>
          <or-vaadin-select
            style="flex: 1"
            .value="${this._eventType}"
            .items="${eventTypes}"
            @change="${this._setCalendarEventType}"
          ></or-vaadin-select>
        </div>
        ${when(this._eventType !== EventTypes.default, () => this._getPeriodTemplate())}
        ${when(this._eventType === EventTypes.recurrence, () => this._getRepeatTemplate())}
        ${when(this._eventType === EventTypes.recurrence, () => this._getEndsTemplate())}
      </div>`;
  }

  protected _getDialogFooter(): TemplateResult {
    return html`
      ${when(
        this.removable,
        () =>
          html` <or-vaadin-button
            style="background-color: unset; margin-right: auto"
            theme="error"
            @click="${this._onDelete}"
          >
            <or-icon icon="or:trash" style="--or-icon-fill: white"></or-icon>
            <or-translate value="schedule.delete"></or-translate>
          </or-vaadin-button>`
      )}
      <or-vaadin-button theme="primary" @click="${this._onSave}"
        ><or-translate value="schedule.save"></or-translate
      ></or-vaadin-button>
    `;
  }

  protected _onClose() {
    this._dialog!.close();
  }

  protected _onDelete() {
    this._dialog!.close();
    this.dispatchEvent(new OrSchedulerRemovedEvent());
  }

  protected _onSave() {
    this._setAllDay();
    this.dispatchEvent(new OrSchedulerChangedEvent(this.schedule ?? this.defaultSchedule));
    this._dialog!.close();
  }

  protected _onPartChange(part: PartKeys, valueProp: "checked" | "value" | "detail", value?: any) {
    return (e: any) => {
      if (valueProp === "detail") {
        if (!Util.objectsEqual(e.detail.value, value, true)) {
          this._setRRuleValue(e.detail.value, part);
        }
        return;
      }
      this._setRRuleValue(e.target[valueProp], part);
    };
  }

  /**
   * Check if this frequency is allowed
   * @param freq The frequency to check
   * @returns Whether the frequency is allowed
   */
  protected _isAllowedFrequency(freq: Frequency) {
    // Secondly is disabled because it's not possible to configure the period on a seconds basis
    // with the current period fields
    return freq !== "SECONDLY" && !this.disabledFrequencies.includes(freq);
  }

  /**
   * Displays the interval, frequency and BY_XXX RRule part fields
   *
   * Applicable rule parts
   * - `interval`
   * - `freq`
   * - `bysecond`
   * - `byminute`
   * - `byhour`
   * - `byweekday`
   * - `bymonthday`
   * - `byyearday`
   * - `byweekno`
   * - `bymonth`
   *
   * Evaluation order: BYMONTH, BYWEEKNO, BYYEARDAY, BYMONTHDAY, BYDAY, BYHOUR, BYMINUTE and BYSECOND.
   *
   * @returns Inputs for the applicable rule parts
   */
  protected _getRepeatTemplate(): TemplateResult {
    const interval = this._rrule?.origOptions.interval ?? 1;
    const frequency = this._rrule?.origOptions.freq ?? FrequencyValue.DAILY;
    const frequencies = Object.entries(FREQUENCIES)
      .map(([k, v]) => ({ value: String(FrequencyValue[k as Frequency]), label: i18next.t(v, { count: interval }) }))
      .filter(({ value }) => this._isAllowedFrequency(FrequencyValue[value as Frequency] as any));

    return html` <div id="recurrence" class="section">
      <h4><or-translate value="schedule.repeat"></or-translate></h4>
      <div style="display: flex; gap: 8px">
        ${when(
          !this.disabledRRuleParts?.includes("interval"),
          () => html`
            <or-vaadin-number-field
              min="1"
              max="9"
              step-buttons-visible
              style="width: 106px"
              .value="${interval}"
              @change="${this._onPartChange("interval", "value")}"
            >
            </or-vaadin-number-field>
          `
        )}
        <or-vaadin-select
          style="flex: 1;"
          .value="${frequency.toString()}"
          .items="${frequencies}"
          @change="${this._onPartChange("freq", "value")}"
        >
        </or-vaadin-select>
      </div>
      ${when(
        BY_RRULE_PARTS.some((p) => this._byRRuleParts?.includes(p)),
        () => html`
          <h4 style="margin-top: var(--lumo-space-l)">
            <or-translate value="schedule.repeatOn"></or-translate>
          </h4>
          <div>${this._getByRulePart("bymonth", InputType.CHECKBOX_LIST, Object.entries(MONTHS))}</div>
          <div>
            ${this._getByRulePart("byweekno", InputType.SELECT, byWeekNoOptions)}
            ${this._getByRulePart("byyearday", InputType.SELECT, byYearDayOptions)}
            ${this._getByRulePart("bymonthday", InputType.SELECT, byMonthDayOptions)}
          </div>
          <div>${this._getByRulePart("byweekday", InputType.CHECKBOX_LIST, Object.entries(WEEKDAYS))}</div>
          <div>
            ${this._getByRulePart("byhour", InputType.SELECT, byHourOptions)}
            ${this._getByRulePart("byminute", InputType.SELECT, byMinuteOrSecondsOptions)}
            ${this._getByRulePart("bysecond", InputType.SELECT, byMinuteOrSecondsOptions)}
          </div>
        `
      )}
    </div>`;
  }

  /**
   * Displays the BY_XXX RRule part fields if allowed by the frequency
   *
   * @returns The specified BY_XXX RRule part field or undefined if not applicable
   */
  protected _getByRulePart<T extends number | [string, string]>(
    part: ByRRulePartsKeys,
    type: InputType,
    options: T[]
  ): TemplateResult | undefined {
    if (!this._byRRuleParts?.includes(part)) {
      return undefined;
    }

    const opts = this._rrule?.origOptions?.[part] ?? [];
    const value = part === "byweekday" ? (opts as Weekday[])?.map(String) : Array.isArray(opts) ? opts : [opts];

    return type === InputType.CHECKBOX_LIST
      ? html`
          <or-vaadin-checkbox-group .value="${value}" @value-changed="${this._onPartChange(part, "detail", value)}">
            ${(options as [string, string][]).map(([value, label]) => html`<vaadin-checkbox theme="button" value="${value}" label="${i18next.t(label).slice(0, 3)}"></vaadin-checkbox>`)}
          </or-vaadin-checkbox-group>
        `
      : html`
          <or-vaadin-multi-select-combo-box
            .selectedItems="${value}"
            .label="${i18next.t(`rrule.${part}`)}"
            .items="${this.disableNegativeByPartValues ? options.filter((n) => +n > 0) : options}"
            @selected-items-changed="${this._onPartChange(part, "detail", value)}"
          >
          </or-vaadin-multi-select-combo-box>
        `;
  }

  /**
   * Displays the fields that define when and how long the particular event is
   *
   * @returns The periods allDay and from/to date and time fields
   */
  protected _getPeriodTemplate(): TemplateResult {
    const calendar = this._scheduleWithOffset!;
    return html` <div id="period" class="section">
      <h4><or-translate value="period"></or-translate></h4>
      <div style="display: flex; gap: 8px">
        <div class="period">
          <or-vaadin-date-picker
            style="text-transform: capitalize"
            ?combined="${!this.isAllDay}"
            .value="${moment(calendar.start).format("YYYY-MM-DD")}"
            @change="${this._onPartChange("start", "value")}"
            label="${i18next.t("from")}"
            .max="${moment(calendar.end).format("YYYY-MM-DD")}"
          >
          </or-vaadin-date-picker>
          <or-vaadin-time-picker
            style="margin-top: auto"
            ?hidden=${this.isAllDay}
            .value="${moment(calendar.start).format("HH:mm")}"
            @change="${this._onPartChange("start-time", "value")}"
            .max="${moment(calendar.end).isSameOrBefore(moment(calendar.start), "day") && moment(calendar.end).format("HH:mm")}"
          >
          </or-vaadin-time-picker>
        </div>
        <div class="period">
          <or-vaadin-date-picker
            style="text-transform: capitalize"
            ?combined="${!this.isAllDay}"
            .value="${moment(calendar.end).format("YYYY-MM-DD")}"
            @change="${this._onPartChange("end", "value")}"
            label="${i18next.t("to")}"
            .min="${moment(calendar.start).format("YYYY-MM-DD")}"
          >
          </or-vaadin-date-picker>
          <or-vaadin-time-picker
            style="margin-top: auto"
            ?hidden=${this.isAllDay}
            .value="${moment(calendar.end).format("HH:mm")}"
            @change="${this._onPartChange("end-time", "value")}"
            .min="${moment(calendar.end).isSameOrBefore(moment(calendar.start), "day") && moment(calendar.start).format("HH:mm")}"
          >
          </or-vaadin-time-picker>
        </div>
      </div>
      <or-vaadin-checkbox
        .checked=${this.isAllDay}
        @change="${this._onPartChange("all-day", "checked")}"
        .label="${i18next.t("allDay")}"
      ></or-vaadin-checkbox>
    </div>`;
  }

  /**
   * Displays the fields that define how a recurring event should end
   *
   * Applicable rule parts
   * - `until`
   * - `count`
   * @returns The recurrence ends fields
   */
  protected _getEndsTemplate(): TemplateResult {
    return html` <div id="recurrence-ends" class="section">
      <h4><or-translate value="schedule._ends"></or-translate></h4>
      <div style="display: flex; gap: 8px;">
        <or-vaadin-radio-group
          style="padding-right: 10px; width: unset"
          .value="${this._ends}"
          theme="vertical"
          @change="${this._onPartChange("recurrence-ends", "value")}"
        >
          ${Object.entries(RRULE_ENDS)
            .filter(([k]) => !this.disabledRRuleParts?.includes(k as RRulePartKeys))
            .map(
              ([k, v]) => html`
                <vaadin-radio-button style="margin: 6px 0" value="${k}" label="${i18next.t(v)}"></vaadin-radio-button>
              `
            )}
        </or-vaadin-radio-group>
        <div style="display: flex; flex-direction: column; flex: 1; ">
          ${when(
            !this.disabledRRuleParts.includes("until"),
            () =>
              html` <or-vaadin-date-time-picker
                style="margin-top: auto; padding: var(--lumo-space-s) 0"
                ?disabled="${this._ends !== "until"}"
                .value="${moment(this._until).format("YYYY-MM-DDTHH:mm")}"
                @change="${this._onPartChange("until", "value")}"
              >
              </or-vaadin-date-time-picker>`
          )}
          ${when(
            !this.disabledRRuleParts.includes("count"),
            () =>
              html`<div style="display: inline-flex">
                <or-vaadin-number-field
                  ?disabled="${this._ends !== "count"}"
                  min="1"
                  style="width: 120px"
                  step-buttons-visible
                  .value="${this._count}"
                  @change="${this._onPartChange("count", "value")}"
                >
                </or-vaadin-number-field
                ><or-translate
                  class="label"
                  value="schedule.count"
                  ?disabled="${this._ends !== "count"}"
                  .options="${{ count: +this._count }}"
                >
                </or-translate>
              </div>`
          )}
        </div>
      </div>
    </div>`;
  }
}