-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
rtl.js
58 lines (50 loc) · 1.34 KB
/
rtl.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* External dependencies
*/
import { css } from '@emotion/core';
function getRtl() {
return !! ( document && document.documentElement.dir === 'rtl' );
}
/**
* Simple hook to retrieve RTL direction value
*/
export function useRtl() {
return getRtl();
}
/**
* An incredibly basic ltr -> rtl converter for style properties
*
* @param {Object} ltrStyles
* @return {Object} Converted ltr -> rtl styles
*/
const convertLtrToRtl = ( ltrStyles = {} ) => {
const nextStyles = {};
for ( const key in ltrStyles ) {
const value = ltrStyles[ key ];
let nextKey = key;
if ( /left/gi.test( key ) ) {
nextKey = [ key.replace( 'left', 'right' ) ];
}
if ( /Left/gi.test( key ) ) {
nextKey = [ key.replace( 'Left', 'Right' ) ];
}
nextStyles[ nextKey ] = value;
}
return nextStyles;
};
/**
* An incredibly basic ltr -> rtl style converter for CSS objects.
*
* @param {Object} ltrStyles Ltr styles. Converts and renders from ltr -> rtl styles, if applicable.
* @param {null|Object} rtlStyles Rtl styles. Renders if provided.
* @return {Object} Rendered CSS styles for Emotion's renderer
*/
export function rtl( ltrStyles = {}, rtlStyles ) {
return () => {
const isRtl = getRtl();
if ( rtlStyles ) {
return isRtl ? css( rtlStyles ) : css( ltrStyles );
}
return isRtl ? css( convertLtrToRtl( ltrStyles ) ) : css( ltrStyles );
};
}