2
0
Fork 0

MOBILE-3814 chore: Deprecate getElementMeasure

main
Pau Ferrer Ocaña 2022-03-14 14:05:44 +01:00
parent bcb5d937ee
commit 30d24f99e3
8 changed files with 110 additions and 149 deletions

View File

@ -33,7 +33,7 @@ export class AddonModPageIndexComponent extends CoreCourseModuleMainResourceComp
component = AddonModPageProvider.COMPONENT; component = AddonModPageProvider.COMPONENT;
contents?: string; contents?: string;
displayDescription = true; displayDescription = false;
displayTimemodified = true; displayTimemodified = true;
timemodified?: number; timemodified?: number;
page?: AddonModPagePage; page?: AddonModPagePage;

View File

@ -272,8 +272,18 @@ export class AddonQtypeDdMarkerQuestion {
return; return;
} }
const width = CoreDomUtils.getElementMeasure(markerSpan, true, true, false, true); const computedStyle = getComputedStyle(markerSpan);
const height = CoreDomUtils.getElementMeasure(markerSpan, false, true, false, true); const width = markerSpan.getBoundingClientRect().width +
CoreDomUtils.getComputedStyleMeasure(computedStyle, 'borderLeftWidth') +
CoreDomUtils.getComputedStyleMeasure(computedStyle, 'borderRightWidth') +
CoreDomUtils.getComputedStyleMeasure(computedStyle, 'paddingLeft') +
CoreDomUtils.getComputedStyleMeasure(computedStyle, 'paddingRight');
const height = markerSpan.getBoundingClientRect().height +
CoreDomUtils.getComputedStyleMeasure(computedStyle, 'borderTopWidth') +
CoreDomUtils.getComputedStyleMeasure(computedStyle, 'borderBottomWidth') +
CoreDomUtils.getComputedStyleMeasure(computedStyle, 'paddingTop') +
CoreDomUtils.getComputedStyleMeasure(computedStyle, 'paddingBottom');
markerSpan.style.opacity = '0.6'; markerSpan.style.opacity = '0.6';
markerSpan.style.left = (xyForText.x - (width / 2)) + 'px'; markerSpan.style.left = (xyForText.x - (width / 2)) + 'px';
markerSpan.style.top = (xyForText.y - (height / 2)) + 'px'; markerSpan.style.top = (xyForText.y - (height / 2)) + 'px';

View File

@ -14,7 +14,6 @@
import { Component, Input, Output, EventEmitter, OnChanges, SimpleChange, ViewChild, ElementRef } from '@angular/core'; import { Component, Input, Output, EventEmitter, OnChanges, SimpleChange, ViewChild, ElementRef } from '@angular/core';
import { IonInfiniteScroll } from '@ionic/angular'; import { IonInfiniteScroll } from '@ionic/angular';
import { CoreDomUtils } from '@services/utils/dom';
import { CoreUtils } from '@services/utils/utils'; import { CoreUtils } from '@services/utils/utils';
const THRESHOLD = .15; // % of the scroll element height that must be close to the edge to consider loading more items necessary. const THRESHOLD = .15; // % of the scroll element height that must be close to the edge to consider loading more items necessary.
@ -36,15 +35,12 @@ export class CoreInfiniteLoadingComponent implements OnChanges {
@Input() position: 'top' | 'bottom' = 'bottom'; @Input() position: 'top' | 'bottom' = 'bottom';
@Output() action: EventEmitter<() => void>; // Will emit an event when triggered. @Output() action: EventEmitter<() => void>; // Will emit an event when triggered.
@ViewChild('topbutton') topButton?: ElementRef;
@ViewChild('bottombutton') bottomButton?: ElementRef;
@ViewChild('spinnercontainer') spinnerContainer?: ElementRef;
@ViewChild(IonInfiniteScroll) infiniteScroll?: IonInfiniteScroll; @ViewChild(IonInfiniteScroll) infiniteScroll?: IonInfiniteScroll;
loadingMore = false; // Hide button and avoid loading more. loadingMore = false; // Hide button and avoid loading more.
hostElement: HTMLElement; hostElement: HTMLElement;
constructor(protected element: ElementRef<HTMLElement>) { constructor(element: ElementRef<HTMLElement>) {
this.action = new EventEmitter(); this.action = new EventEmitter();
this.hostElement = element.nativeElement; this.hostElement = element.nativeElement;
} }
@ -142,11 +138,7 @@ export class CoreInfiniteLoadingComponent implements OnChanges {
* @deprecated since 3.9.5 * @deprecated since 3.9.5
*/ */
getHeight(): number { getHeight(): number {
return (this.position == 'top' ? return this.hostElement.getBoundingClientRect().height;
this.getElementHeight(this.topButton?.nativeElement) :
this.getElementHeight(this.bottomButton?.nativeElement)) +
this.getElementHeight(this.infiniteScrollElement) +
this.getElementHeight(this.spinnerContainer?.nativeElement);
} }
/** /**
@ -158,18 +150,4 @@ export class CoreInfiniteLoadingComponent implements OnChanges {
return this.hostElement.querySelector('ion-infinite-scroll'); return this.hostElement.querySelector('ion-infinite-scroll');
} }
/**
* Get the height of an element.
*
* @param element Element ref.
* @return Height.
*/
protected getElementHeight(element?: HTMLElement | null): number {
if (element) {
return CoreDomUtils.getElementHeight(element, true, true, true);
}
return 0;
}
} }

View File

@ -65,6 +65,8 @@ export class CoreCollapsibleFooterDirective implements OnInit, OnDestroy {
await this.waitLoadingsDone(); await this.waitLoadingsDone();
await this.waitFormatTextsRendered(this.element); await this.waitFormatTextsRendered(this.element);
this.content = this.element.closest('ion-content');
await this.calculateHeight(); await this.calculateHeight();
this.listenScrollEvents(); this.listenScrollEvents();
@ -97,13 +99,7 @@ export class CoreCollapsibleFooterDirective implements OnInit, OnDestroy {
* Setup scroll event listener. * Setup scroll event listener.
*/ */
protected async listenScrollEvents(): Promise<void> { protected async listenScrollEvents(): Promise<void> {
if (this.content) { if (!this.content || this.content?.classList.contains('has-collapsible-footer')) {
return;
}
this.content = this.element.closest('ion-content');
if (!this.content) {
return; return;
} }

View File

@ -217,14 +217,14 @@ export class CoreFormatTextDirective implements OnChanges {
/** /**
* Add magnifying glass icons to view adapted images at full size. * Add magnifying glass icons to view adapted images at full size.
*/ */
addMagnifyingGlasses(): void { async addMagnifyingGlasses(): Promise<void> {
const imgs = Array.from(this.contentSpan.querySelectorAll('.core-adapted-img-container > img')); const imgs = Array.from(this.contentSpan.querySelectorAll('.core-adapted-img-container > img'));
if (!imgs.length) { if (!imgs.length) {
return; return;
} }
// If cannot calculate element's width, use viewport width to avoid false adapt image icons appearing. // If cannot calculate element's width, use viewport width to avoid false adapt image icons appearing.
const elWidth = this.getElementWidth(this.element) || window.innerWidth; const elWidth = await this.getElementWidth();
imgs.forEach((img: HTMLImageElement) => { imgs.forEach((img: HTMLImageElement) => {
// Skip image if it's inside a link. // Skip image if it's inside a link.
@ -543,41 +543,40 @@ export class CoreFormatTextDirective implements OnChanges {
/** /**
* Returns the element width in pixels. * Returns the element width in pixels.
* *
* @param element Element to get width from. * @return The width of the element in pixels.
* @return The width of the element in pixels. When 0 is returned it means the element is not visible.
*/ */
protected getElementWidth(element: HTMLElement): number { protected async getElementWidth(): Promise<number> {
let width = CoreDomUtils.getElementWidth(element); await CoreUtils.ignoreErrors(CoreDomUtils.waitToBeInDOM(this.element));
let width = this.element.getBoundingClientRect().width;
if (!width) { if (!width) {
// All elements inside are floating or inline. Change display mode to allow calculate the width. // All elements inside are floating or inline. Change display mode to allow calculate the width.
const parentWidth = element.parentElement ? const previousDisplay = getComputedStyle(this.element).display;
CoreDomUtils.getElementWidth(element.parentElement, true, false, false, true) : 0;
const previousDisplay = getComputedStyle(element, null).display;
element.style.display = 'inline-block'; this.element.style.display = 'inline-block';
await CoreUtils.nextTick();
width = CoreDomUtils.getElementWidth(element); width = this.element.getBoundingClientRect().width;
// If width is incorrectly calculated use parent width instead. this.element.style.display = previousDisplay;
if (parentWidth > 0 && (!width || width > parentWidth)) {
width = parentWidth;
}
element.style.display = previousDisplay;
} }
return width; // Aproximate using parent elements.
} let element = this.element;
while (!width && element.parentElement) {
element = element.parentElement;
const computedStyle = getComputedStyle(element);
/** const padding = CoreDomUtils.getComputedStyleMeasure(computedStyle, 'paddingLeft') +
* Returns the element height in pixels. CoreDomUtils.getComputedStyleMeasure(computedStyle, 'paddingRight');
*
* @param elementAng Element to get height from. // Use parent width as an aproximation.
* @return The height of the element in pixels. When 0 is returned it means the element is not visible. width = element.getBoundingClientRect().width - padding;
*/ }
protected getElementHeight(element: HTMLElement): number {
return CoreDomUtils.getElementHeight(element) || 0; return width > 0 && width < window.innerWidth
? width
: window.innerWidth;
} }
/** /**
@ -701,10 +700,12 @@ export class CoreFormatTextDirective implements OnChanges {
let width: string | number; let width: string | number;
let height: string | number; let height: string | number;
await CoreDomUtils.waitToBeInDOM(iframe);
if (iframe.width) { if (iframe.width) {
width = iframe.width; width = iframe.width;
} else { } else {
width = this.getElementWidth(iframe); width = iframe.getBoundingClientRect().width;
if (!width) { if (!width) {
width = window.innerWidth; width = window.innerWidth;
} }
@ -713,7 +714,7 @@ export class CoreFormatTextDirective implements OnChanges {
if (iframe.height) { if (iframe.height) {
height = iframe.height; height = iframe.height;
} else { } else {
height = this.getElementHeight(iframe); height = iframe.getBoundingClientRect().height;
if (!height) { if (!height) {
height = width; height = width;
} }

View File

@ -16,7 +16,7 @@
} }
:host { :host {
height: 40vh; height: var(--core-rte-height, auto);
overflow: hidden; overflow: hidden;
min-height: 200px; /* Just in case vh is not supported */ min-height: 200px; /* Just in case vh is not supported */
min-height: 40vh; min-height: 40vh;

View File

@ -38,6 +38,8 @@ import { CoreUtils } from '@services/utils/utils';
import { Platform, Translate } from '@singletons'; import { Platform, Translate } from '@singletons';
import { CoreEventFormActionData, CoreEventObserver, CoreEvents } from '@singletons/events'; import { CoreEventFormActionData, CoreEventObserver, CoreEvents } from '@singletons/events';
import { CoreEditorOffline } from '../../services/editor-offline'; import { CoreEditorOffline } from '../../services/editor-offline';
import { CoreComponentsRegistry } from '@singletons/components-registry';
import { CoreLoadingComponent } from '@components/loading/loading';
/** /**
* Component to display a rich text editor if enabled. * Component to display a rich text editor if enabled.
@ -101,7 +103,7 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn
protected resizeFunction?: () => Promise<number>; protected resizeFunction?: () => Promise<number>;
protected selectionChangeFunction?: () => void; protected selectionChangeFunction?: () => void;
protected languageChangedSubscription?: Subscription; protected languageChangedSubscription?: Subscription;
protected resizeObserver?: IntersectionObserver; protected resizeListener?: CoreEventObserver;
rteEnabled = false; rteEnabled = false;
isPhone = false; isPhone = false;
@ -140,14 +142,6 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn
this.contentChanged = new EventEmitter<string>(); this.contentChanged = new EventEmitter<string>();
this.element = elementRef.nativeElement as HTMLDivElement; this.element = elementRef.nativeElement as HTMLDivElement;
this.pageInstance = 'app_' + Date.now(); // Generate a "unique" ID based on timestamp. this.pageInstance = 'app_' + Date.now(); // Generate a "unique" ID based on timestamp.
if ('IntersectionObserver' in window) {
this.resizeObserver = new IntersectionObserver((observerEntry: IntersectionObserverEntry[]) => {
if (observerEntry[0].boundingClientRect.width > 0) {
this.updateToolbarButtons();
}
});
}
} }
/** /**
@ -180,14 +174,9 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn
// Use paragraph on enter. // Use paragraph on enter.
document.execCommand('DefaultParagraphSeparator', false, 'p'); document.execCommand('DefaultParagraphSeparator', false, 'p');
let i = 0; await this.waitLoadingsDone();
this.initHeightInterval = window.setInterval(async () => {
const height = await this.maximizeEditorSize(); this.maximizeEditorSize();
if (i >= 5 || height != 0) {
clearInterval(this.initHeightInterval);
}
i++;
}, 750);
this.setListeners(); this.setListeners();
this.updateToolbarButtons(); this.updateToolbarButtons();
@ -256,14 +245,14 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn
); );
}); });
this.resizeFunction = this.windowResized.bind(this); this.resizeListener = CoreDomUtils.onWindowResize(() => {
window.addEventListener('resize', this.resizeFunction!); this.windowResized();
}, 50);
// Start observing the target node for configured mutations // Start observing the target node for configured mutations
this.resizeObserver?.observe(this.element); this.resizeObserver?.observe(this.element);
this.selectionChangeFunction = this.updateToolbarStyles.bind(this); document.addEventListener('selectionchange', this.selectionChangeFunction = this.updateToolbarStyles.bind(this));
document.addEventListener('selectionchange', this.selectionChangeFunction!);
this.keyboardObserver = CoreEvents.on(CoreEvents.KEYBOARD_CHANGE, () => { this.keyboardObserver = CoreEvents.on(CoreEvents.KEYBOARD_CHANGE, () => {
// Opening or closing the keyboard also calls the resize function, but sometimes the resize is called too soon. // Opening or closing the keyboard also calls the resize function, but sometimes the resize is called too soon.
@ -281,65 +270,57 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn
/** /**
* Resize editor to maximize the space occupied. * Resize editor to maximize the space occupied.
*
* @return Resolved with calculated editor size.
*/ */
protected async maximizeEditorSize(): Promise<number> { protected async maximizeEditorSize(): Promise<void> {
const contentVisibleHeight = await CoreDomUtils.getContentHeight(this.content);
if (contentVisibleHeight <= 0) {
return 0;
}
await CoreUtils.wait(100);
// Editor is ready, adjust Height if needed. // Editor is ready, adjust Height if needed.
const contentHeight = await CoreDomUtils.getContentHeight(this.content); const blankHeight = await this.getBlankHeightInContent();
const height = contentHeight - this.getSurroundingHeight(this.element); const newHeight = blankHeight + this.element.getBoundingClientRect().height;
if (height > this.minHeight) { if (newHeight > this.minHeight) {
this.element.style.height = CoreDomUtils.formatPixelsSize(height - 1); this.element.style.setProperty('--core-rte-height', (newHeight - 1) + 'px');
} else { } else {
this.element.style.height = ''; this.element.style.removeProperty('--core-rte-height');
} }
return height;
} }
/** /**
* Get the height of the surrounding elements from the current to the top element. * Wait until all <core-loading> children inside the page.
* *
* @param element Directive DOM element to get surroundings elements from. * @return Promise resolved when loadings are done.
* @return Surrounding height in px.
*/ */
protected getSurroundingHeight(element: HTMLElement): number { protected async waitLoadingsDone(): Promise<void> {
let height = 0; await CoreDomUtils.waitToBeInDOM(this.element);
while (element.parentElement?.tagName != 'ION-CONTENT') { const page = this.element.closest('.ion-page');
const parent = element.parentElement!;
if (element.tagName && element.tagName != 'CORE-LOADING') { await CoreComponentsRegistry.finishRenderingAllElementsInside<CoreLoadingComponent>(page, 'core-loading', 'whenLoaded');
for (let x = 0; x < parent.children.length; x++) { }
const child = <HTMLElement> parent.children[x];
if (child.tagName && child != element) { /**
height += CoreDomUtils.getElementHeight(child, false, true, true); * Get the height of the space in blank at the end of the page.
} *
} * @return Blank height in px. Will be negative if no blank space.
} */
element = parent; protected async getBlankHeightInContent(): Promise<number> {
await CoreUtils.nextTicks(5); // Ensure content is completely loaded in the DOM.
let content: Element | null = this.element.closest('ion-content');
const contentHeight = await CoreDomUtils.getContentHeight(this.content);
// Get first children with content, not fixed.
let scrollContentHeight = 0;
while (scrollContentHeight == 0 && content?.children) {
const children = Array.from(content.children)
.filter((element) => element.slot !== 'fixed' && !element.classList.contains('core-loading-container'));
scrollContentHeight = children
.map((element) => element.getBoundingClientRect().height)
.reduce((a,b) => a + b, 0);
content = children[0];
} }
const computedStyle = getComputedStyle(element); return contentHeight - scrollContentHeight;
height += CoreDomUtils.getComputedStyleMeasure(computedStyle, 'paddingTop') +
CoreDomUtils.getComputedStyleMeasure(computedStyle, 'paddingBottom');
if (element.parentElement?.tagName == 'ION-CONTENT') {
const cs2 = getComputedStyle(element);
height -= CoreDomUtils.getComputedStyleMeasure(cs2, 'paddingTop') +
CoreDomUtils.getComputedStyleMeasure(cs2, 'paddingBottom');
}
return height;
} }
/** /**
@ -625,7 +606,7 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn
this.editorElement.innerHTML = '<p></p>'; this.editorElement.innerHTML = '<p></p>';
this.textarea.value = ''; this.textarea.value = '';
} else { } else {
this.editorElement.innerHTML = value!; this.editorElement.innerHTML = value || '';
this.textarea.value = value; this.textarea.value = value;
this.treatExternalContent(); this.treatExternalContent();
} }
@ -759,10 +740,7 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn
* Show the toolbar. * Show the toolbar.
*/ */
showToolbar(event: Event): void { showToolbar(event: Event): void {
if (!('IntersectionObserver' in window)) { this.updateToolbarButtons();
// Fallback if IntersectionObserver is not supported.
this.updateToolbarButtons();
}
this.element.classList.add('ion-touched'); this.element.classList.add('ion-touched');
this.element.classList.remove('ion-untouched'); this.element.classList.remove('ion-untouched');
@ -851,14 +829,9 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn
const length = await this.toolbarSlides.length(); const length = await this.toolbarSlides.length();
const width = CoreDomUtils.getElementWidth(this.toolbar.nativeElement); await CoreDomUtils.waitToBeInDOM(this.toolbar.nativeElement);
if (!width) { const width = this.toolbar.nativeElement.getBoundingClientRect().width;
// Width is not available yet, try later.
setTimeout(this.updateToolbarButtons.bind(this), 100);
return;
}
if (length > 0 && width > length * this.toolbarButtonWidth) { if (length > 0 && width > length * this.toolbarButtonWidth) {
this.slidesOpts = { ...this.slidesOpts, slidesPerView: length }; this.slidesOpts = { ...this.slidesOpts, slidesPerView: length };
@ -1107,15 +1080,14 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn
ngOnDestroy(): void { ngOnDestroy(): void {
this.valueChangeSubscription?.unsubscribe(); this.valueChangeSubscription?.unsubscribe();
this.languageChangedSubscription?.unsubscribe(); this.languageChangedSubscription?.unsubscribe();
window.removeEventListener('resize', this.resizeFunction!); this.selectionChangeFunction && document.removeEventListener('selectionchange', this.selectionChangeFunction);
document.removeEventListener('selectionchange', this.selectionChangeFunction!);
clearInterval(this.initHeightInterval); clearInterval(this.initHeightInterval);
clearInterval(this.autoSaveInterval); clearInterval(this.autoSaveInterval);
clearTimeout(this.hideMessageTimeout); clearTimeout(this.hideMessageTimeout);
this.resizeObserver?.disconnect();
this.resetObserver?.off(); this.resetObserver?.off();
this.keyboardObserver?.off(); this.keyboardObserver?.off();
this.labelObserver?.disconnect(); this.labelObserver?.disconnect();
this.resizeListener?.off();
} }
} }

View File

@ -111,8 +111,8 @@ export class CoreDomUtilsProvider {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
// Disconnect observer for performance reasons. // Disconnect observer for performance reasons.
const timeout = window.setTimeout(() => { const timeout = window.setTimeout(() => {
reject(new Error('Waiting for DOM timeout reached'));
observer.disconnect(); observer.disconnect();
reject(new Error('Waiting for DOM timeout reached'));
}, 5000); }, 5000);
const observer = new MutationObserver(() => { const observer = new MutationObserver(() => {
@ -454,6 +454,7 @@ export class CoreDomUtilsProvider {
* @param useBorder Whether to use borders to calculate the measure. * @param useBorder Whether to use borders to calculate the measure.
* @param innerMeasure If inner measure is needed: padding, margin or borders will be substracted. * @param innerMeasure If inner measure is needed: padding, margin or borders will be substracted.
* @return Height in pixels. * @return Height in pixels.
* @deprecated since app 4.0 Use getBoundingClientRect.height instead.
*/ */
getElementHeight( getElementHeight(
element: HTMLElement, element: HTMLElement,
@ -475,6 +476,7 @@ export class CoreDomUtilsProvider {
* @param useBorder Whether to use borders to calculate the measure. * @param useBorder Whether to use borders to calculate the measure.
* @param innerMeasure If inner measure is needed: padding, margin or borders will be substracted. * @param innerMeasure If inner measure is needed: padding, margin or borders will be substracted.
* @return Measure in pixels. * @return Measure in pixels.
* @deprecated since app 4.0 Use getBoundingClientRect.height or width instead.
*/ */
getElementMeasure( getElementMeasure(
element: HTMLElement, element: HTMLElement,
@ -547,6 +549,7 @@ export class CoreDomUtilsProvider {
* @param useBorder Whether to use borders to calculate the measure. * @param useBorder Whether to use borders to calculate the measure.
* @param innerMeasure If inner measure is needed: padding, margin or borders will be substracted. * @param innerMeasure If inner measure is needed: padding, margin or borders will be substracted.
* @return Width in pixels. * @return Width in pixels.
* @deprecated since app 4.0 Use getBoundingClientRect.width instead.
*/ */
getElementWidth( getElementWidth(
element: HTMLElement, element: HTMLElement,
@ -726,6 +729,7 @@ export class CoreDomUtilsProvider {
* *
* @param findFunction The function used to find the element. * @param findFunction The function used to find the element.
* @return Resolved if found, rejected if too many tries. * @return Resolved if found, rejected if too many tries.
* @deprecated since app 4.0 Use waitToBeInDOM instead.
*/ */
waitElementToExist(findFunction: () => HTMLElement | null): Promise<HTMLElement> { waitElementToExist(findFunction: () => HTMLElement | null): Promise<HTMLElement> {
const promiseInterval = CoreUtils.promiseDefer<HTMLElement>(); const promiseInterval = CoreUtils.promiseDefer<HTMLElement>();
@ -1077,7 +1081,7 @@ export class CoreDomUtilsProvider {
const scrollElement = await content.getScrollElement(); const scrollElement = await content.getScrollElement();
return scrollElement.clientHeight || 0; return scrollElement.clientHeight || 0;
} catch (error) { } catch {
return 0; return 0;
} }
} }
@ -1093,7 +1097,7 @@ export class CoreDomUtilsProvider {
const scrollElement = await content.getScrollElement(); const scrollElement = await content.getScrollElement();
return scrollElement.scrollHeight || 0; return scrollElement.scrollHeight || 0;
} catch (error) { } catch {
return 0; return 0;
} }
} }