Skip to content

Commit

Permalink
perf(slot): handle slot content with less code
Browse files Browse the repository at this point in the history
  • Loading branch information
jordanjones243 committed Jan 4, 2024
1 parent c9b20cb commit 5d5d7be
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 283 deletions.
107 changes: 57 additions & 50 deletions src/auro-calendar-cell.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import styleCss from "./style-auro-calendar-cell-css";

import '@alaskaairux/auro-popover';

/* eslint-disable no-magic-numbers, no-underscore-dangle, max-params, no-void, init-declarations, no-extra-parens, arrow-parens, max-lines */
/* eslint-disable max-lines, no-underscore-dangle, no-magic-numbers, no-underscore-dangle, max-params, no-void, init-declarations, no-extra-parens, arrow-parens, max-lines */

export class AuroCalendarCell extends LitElement {
constructor() {
Expand Down Expand Up @@ -216,63 +216,70 @@ export class AuroCalendarCell extends LitElement {
this.dateStr = `date_${month}_${day}_${year}`;
}

/**
* Handles the text content and visibility of the auro-popover.
* @private
* @returns {void}
*/
handlePopoverContent() {
const popover = this.shadowRoot.querySelector('auro-popover');
const popoverSpan = this.shadowRoot.querySelector('#popoverSpan');
const popoverContent = [...this.querySelectorAll('[slot^="popover_"]')];

const cellDate = new Date(this.day.date * 1000);

if (popoverContent && popoverContent.length > 0) {
popoverContent.forEach((content) => {
const popoverDate = new Date(content.getAttribute('date'));

if (this.popoverAndCellDatesMatch(popoverDate, cellDate)) {
const textNode = document.createTextNode(content.textContent);

if (popoverSpan.firstChild) {
popoverSpan.firstChild.textContent = content.textContent;
} else {
popoverSpan.appendChild(textNode);
}

popover.removeAttribute('disabled');
} else {
popoverSpan.firstChild.textContent = '';
popover.setAttribute('disabled', true);
}
});
} else if (!this.disabled) {
popover.setAttribute('disabled', true);
}
/* eslint-disable line-comment-position, no-inline-comments, no-confusing-arrow, no-nested-ternary, implicit-arrow-linebreak */
// THIS SHOULD BE MOVED INTO AURO-LIBRARY AS A HELPER FUNCTION
// declared as method on a Custom Element:
closestElement(
selector, // selector like in .closest()
base = this, // extra functionality to skip a parent
__Closest = (el, found = el && el.closest(selector)) =>
!el || el === document || el === window
? null // standard .closest() returns null for non-found selectors also
: found
? found // found a selector INside this element
: __Closest(el.getRootNode().host) // recursion!! break out to parent DOM
) {
return __Closest(base);
}
/* eslint-enable line-comment-position, no-inline-comments, no-confusing-arrow, no-nested-ternary, implicit-arrow-linebreak */

/**
* Helper function to determine if the popover date and cell date match.
* @private
* @param {Date} popoverDate - The date of the auro-popover.
* @param {Date} cellDate - The date of the auro-calendar-cell.
* @returns {void}
*/
popoverAndCellDatesMatch(popoverDate, cellDate) {
return popoverDate.getDate() === cellDate.getDate() && popoverDate.getMonth() === cellDate.getMonth() && popoverDate.getFullYear() === cellDate.getFullYear();
getSlotContent() {
try {
// Get the slot names for this cell
const dateSlotName = `date_${this.dateStr}`;
const popoverSlotName = `popover_${this.dateStr}`;

// Remove any existing slot content from this cell
const existingSlotContent = this.querySelectorAll(`[slot]`);

existingSlotContent.forEach((slot) => {
slot.remove();
});

// Get any slots for this cell from the datepicker
const dp = this.closestElement('auro-datepicker');

const dateSlotContent = dp.querySelector(`[slot="${dateSlotName}"]`);
const popoverSlotContent = dp.querySelector(`[slot="${popoverSlotName}"]`);

// Insert any fetched slot content into this cell
if (dateSlotContent) {
this.appendChild(dateSlotContent.cloneNode(true));
this.setAttribute('renderForDateSlot', true);
} else {
this.removeAttribute('renderForDateSlot');
}

const popover = this.shadowRoot.querySelector('auro-popover');

if (popoverSlotContent) {
this.appendChild(popoverSlotContent.cloneNode(true));
popover.removeAttribute('disabled');
} else {
popover.setAttribute('disabled', true);
}
} catch (err) {
//
}
}

updated(properties) {
if (properties.has('dateFrom') || properties.has('dateTo') || properties.has('hoveredDate') || properties.has('day')) {
this.dateChanged(this.dateFrom, this.dateTo, this.hoveredDate, this.day);
}

if (properties.has('dateStr')) {
this.handlePopoverContent();
}

this.getDateSlotName();
this.getSlotContent();
}

render() {
Expand All @@ -288,8 +295,8 @@ export class AuroCalendarCell extends LitElement {

let _a, _b;
return html`
<auro-popover disabled>
<span id="popoverSpan"></span>
<auro-popover>
<slot name="popover_${this.dateStr}"></slot>
<button
slot="trigger"
@click="${this.handleTap}"
Expand Down
122 changes: 2 additions & 120 deletions src/auro-calendar-month.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,6 @@ import './auro-calendar-cell';
export class AuroCalendarMonth extends RangeDatepickerCalendar {
constructor() {
super();

this.dateSlotMap = new Map();
this.popoverSlotMap = new Map();
}

static get styles() {
Expand Down Expand Up @@ -48,6 +45,7 @@ export class AuroCalendarMonth extends RangeDatepickerCalendar {

/**
* Determines the current month name based on locale.
* This is a rewrite of the function used in the class RangeDatepickerCalendar and should not be removed from here.
* @private
* @returns {void}
*/
Expand All @@ -67,118 +65,6 @@ export class AuroCalendarMonth extends RangeDatepickerCalendar {
this.dayNamesOfTheWeek = newDayNamesOfTheWeek;
}

/**
* Parses the date and popover slot content and separates it by day.
* @private
* @returns {void}
*/
parseDateContentByDay() {
this.dateSlotContent = [...this.querySelectorAll('[slot^="date_"]')];
this.popoverSlotContent = [...this.querySelectorAll('[slot^="popover_"]')];

if (this.dateSlotContent && this.dateSlotContent.length > 0) {
const items = [];

this.dateSlotContent.forEach((content) => {
const date = new Date(content.getAttribute('date'));

items.push({
date,
content
});
});

this.dateSlotContentByDay = _.groupBy(items, ({date}) => date.getDate()); // eslint-disable-line no-undef
}

if (this.popoverSlotContent && this.popoverSlotContent.length > 0) {
const items = [];

this.popoverSlotContent.forEach((content) => {
const date = new Date(content.getAttribute('date'));

items.push({
date,
content
});
});

this.popoverSlotContentByDay = _.groupBy(items, ({date}) => date.getDate()); // eslint-disable-line no-undef
}

this.insertSlotContentByDay();
}

/**
* Inserts the date and popover slot content down to the auro-calendar-cell.
* @private
* @returns {void}
*/
insertSlotContentByDay() {
const renderedDays = [...this.shadowRoot.querySelectorAll('auro-calendar-cell')];

renderedDays.forEach((dateCell) => {
const day = new Date(dateCell.day.date * 1000).getDate();
const dayName = this.getFormattedDate(dateCell);

if (this.dateSlotContentByDay) {
dateCell.setAttribute('hasDateSlotContent', true);
}

const insertContent = (contentMap, slotMap) => {
if (this.isSlotContentValid(day, dayName, contentMap)) {
dateCell.appendChild(contentMap[day][0].content);
} else if (slotMap.has(dayName)) {
dateCell.appendChild(slotMap.get(dayName));
}
};

insertContent(this.dateSlotContentByDay, this.dateSlotMap);
insertContent(this.popoverSlotContentByDay, this.popoverSlotMap);
});
}

/**
* Checks if the slot content exists and matches the current date.
* @private
* @param {Date} day - Specific day of the month of the auro-calendar-cell.
* @param {String} dayName - The formatted date of the auro-calendar-cell.
* @param {Object} slotContentByDay - The slot content grouped by day.
* @returns {Boolean} True if the slot content exists and matches the current date.
*/
isSlotContentValid(day, dayName, slotContentByDay) {
return (
slotContentByDay &&
slotContentByDay[day] &&
slotContentByDay[day][0].content.getAttribute('date') === dayName
);
}

/**
* Returns a formatted date of the current auro-calendar-cell date.
* @private
* @param {HTMLElement} dateCell - The auro-calendar-cell element.
* @returns {String} The date in "mm/dd/yyyy" format.
*/
getFormattedDate(dateCell) {
const date = new Date(dateCell.day.date * 1000);

let month = date.getMonth() + 1;
let day = date.getDate();

if (month.toString().length === 1) {
month = `0${month}`;
}

if (day.toString().length === 1) {
day = `0${day}`;
}

const year = date.getFullYear();

return `${month}/${day}/${year}`;
}

renderDay(day) {
return html`
<div class="td ${this.tdIsEnabled(day)}">
Expand All @@ -205,13 +91,9 @@ export class AuroCalendarMonth extends RangeDatepickerCalendar {
`;
}

async updated(changedProperties) {
updated(changedProperties) {
if (changedProperties.has('year') || changedProperties.has('month')) {
this.yearAndMonthChanged(this.year, this.month);

await this.updateComplete;

this.parseDateContentByDay();
}
}

Expand Down
85 changes: 0 additions & 85 deletions src/auro-calendar.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,6 @@ export class AuroCalendar extends RangeDatepicker {
this.numCalendars = 1;
this.showPrevMonthBtn = true;
this.showNextMonthBtn = true;

this.dateSlotMap = new Map();
this.popoverSlotMap = new Map();
}

static get styles() {
Expand Down Expand Up @@ -216,8 +213,6 @@ export class AuroCalendar extends RangeDatepicker {
if (changedProperties.has('locale')) {
this.localeChanged();
}

this.parseDateContentByMonth();
}

/**
Expand Down Expand Up @@ -301,86 +296,6 @@ export class AuroCalendar extends RangeDatepicker {
}
}

/**
* Parses the date and popover slot content and separates it by month.
* @private
* @returns {void}
*/
parseDateContentByMonth() {
this.dateSlotContent = [...this.querySelectorAll('[slot^="date_"]')];
this.popoverSlotContent = [...this.querySelectorAll('[slot^="popover_"]')];

if (this.dateSlotContent && this.dateSlotContent.length > 0) {
const items = [];

this.dateSlotContent.forEach((content) => {
this.dateSlotMap.set(content.getAttribute('date'), content);

const date = new Date(content.getAttribute('date'));

items.push({
date,
content
});
});

this.dateSlotContentByMonth = _.groupBy(items, ({date}) => date.getMonth()); // eslint-disable-line no-undef

this.insertSlotContentByMonth(this.dateSlotContentByMonth, this.dateSlotMap);
}

if (this.popoverSlotContent && this.popoverSlotContent.length > 0) {
const items = [];

this.popoverSlotContent.forEach((content) => {
this.popoverSlotMap.set(content.getAttribute('date'), content);

const date = new Date(content.getAttribute('date'));

items.push({
date,
content
});
});

this.popoverSlotContentByMonth = _.groupBy(items, ({date}) => date.getMonth()); // eslint-disable-line no-undef

this.insertSlotContentByMonth(this.popoverSlotContentByMonth, this.popoverSlotMap);
}
}

/**
* Passes the date and popover slot content down to the auro-calendar-month.
* @private
* @param {Object} slotContentByMonth - Slot content grouped by month.
* @param {Object} slotMap - Map of containing slot content and it's corresponding date.
* @returns {void}
*/
insertSlotContentByMonth(slotContentByMonth, slotMap) {
const renderedMonths = [...this.shadowRoot.querySelectorAll('[month]')];

renderedMonths.forEach((month) => {
if (slotContentByMonth) {
const monthSlotContent = slotContentByMonth[month.getAttribute('month') - 1];

if (monthSlotContent) {
const dateSlotName = 'date';
const popoverSlotName = 'popover';

monthSlotContent.forEach((monthContent) => {
if (monthContent.content.getAttribute('slot').includes(dateSlotName)) {
month.dateSlotMap = slotMap;
} else if (monthContent.content.getAttribute('slot').includes(popoverSlotName)) {
month.popoverSlotMap = slotMap;
}

month.appendChild(monthContent.content);
});
}
}
});
}

/**
* Renders the auro-calendar-month HTML.
* @private
Expand Down
Loading

0 comments on commit 5d5d7be

Please sign in to comment.