From a9cb1301d9a5d46f75c7f3d96da112552a739052 Mon Sep 17 00:00:00 2001 From: Wael Mohamed BETTAYEB Date: Wed, 16 Feb 2022 12:10:11 +0100 Subject: [PATCH] fix rtl: observe document dir on change --- src/components/icon/icon.tsx | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/src/components/icon/icon.tsx b/src/components/icon/icon.tsx index 11dfc12da..b9d76561a 100755 --- a/src/components/icon/icon.tsx +++ b/src/components/icon/icon.tsx @@ -9,6 +9,7 @@ import { getName, getUrl, inheritAttributes } from './utils'; shadow: true, }) export class Icon { + private documentDirectionObserver?: MutationObserver; private io?: IntersectionObserver; private iconName: string | null = null; private inheritedAttributes: { [k: string]: any } = {}; @@ -18,6 +19,7 @@ export class Icon { @State() private svgContent?: string; @State() private isVisible = false; @State() private ariaLabel?: string; + @State() private direction?: string; /** * The mode determines which platform styles to use. @@ -93,6 +95,9 @@ export class Icon { this.isVisible = true; this.loadIcon(); }); + this.observeDocumentDirection(() => { + this.direction = (this.el.ownerDocument as Document).dir; + }); } disconnectedCallback() { @@ -100,6 +105,26 @@ export class Icon { this.io.disconnect(); this.io = undefined; } + if (this.documentDirectionObserver) { + this.documentDirectionObserver.disconnect(); + this.documentDirectionObserver = undefined; + } + } + + private observeDocumentDirection(cb: () => void) { + if (Build.isBrowser && typeof window !== 'undefined' && (window as any).MutationObserver) { + this.documentDirectionObserver = new MutationObserver(() => { + this.direction = (this.el.ownerDocument as Document).dir; + }); + this.documentDirectionObserver.observe((this.el.ownerDocument as Document).documentElement, { + attributes: true, + attributeFilter: ['dir'], + }); + } else { + // browser doesn't support MutationObserver + // so just fallback to always show it + cb(); + } } private waitUntilVisible(el: HTMLElement, rootMargin: string, cb: () => void) { @@ -181,7 +206,7 @@ export class Icon { [mode]: true, ...createColorClasses(this.color), [`icon-${this.size}`]: !!this.size, - 'flip-rtl': !!flipRtl && (this.el.ownerDocument as Document).dir === 'rtl', + 'flip-rtl': !!flipRtl && this.direction === 'rtl', }} {...inheritedAttributes} >