| 1 |
/** |
| 2 |
* WordPress dependencies |
| 3 |
*/ |
| 4 |
import { createRoot, render } from '@wordpress/element'; |
| 5 |
|
| 6 |
/** |
| 7 |
* Internal dependencies |
| 8 |
*/ |
| 9 |
import { VerifyCredentials } from '../common/verify-credentials'; |
| 10 |
import { TopPosts } from './components/top-posts'; |
| 11 |
import { SettingsProvider, TopPostsSettings } from '../common/settings'; |
| 12 |
import { isInEnum, Metric, Period } from '../common/utils/constants'; |
| 13 |
|
| 14 |
/** |
| 15 |
* Gets the settings from the passed JSON. |
| 16 |
* |
| 17 |
* If missing settings or invalid values are detected, they get set to their |
| 18 |
* defaults. |
| 19 |
* |
| 20 |
* @since 3.13.0 |
| 21 |
* @since 3.14.0 Moved from `content-helper/dashboard-widget/dashboard-widget.tsx`. |
| 22 |
* |
| 23 |
* @param {string} settingsJson The JSON containing the settings. |
| 24 |
* |
| 25 |
* @return {TopPostsSettings} The resulting settings object. |
| 26 |
*/ |
| 27 |
const getSettingsFromJson = ( settingsJson: string ): TopPostsSettings => { |
| 28 |
let parsedSettings: TopPostsSettings; |
| 29 |
|
| 30 |
try { |
| 31 |
parsedSettings = JSON.parse( settingsJson ); |
| 32 |
} catch ( e ) { |
| 33 |
// Return defaults when parsing failed or the string is empty. |
| 34 |
return { |
| 35 |
Metric: Metric.Views, |
| 36 |
Period: Period.Days7, |
| 37 |
}; |
| 38 |
} |
| 39 |
|
| 40 |
// Fix invalid values if any are found. |
| 41 |
if ( ! isInEnum( parsedSettings?.Metric, Metric ) ) { |
| 42 |
parsedSettings.Metric = Metric.Views; |
| 43 |
} |
| 44 |
if ( ! isInEnum( parsedSettings?.Period, Period ) ) { |
| 45 |
parsedSettings.Period = Period.Days7; |
| 46 |
} |
| 47 |
|
| 48 |
return parsedSettings; |
| 49 |
}; |
| 50 |
|
| 51 |
window.addEventListener( |
| 52 |
'load', |
| 53 |
function() { |
| 54 |
const container = document.querySelector( '#wp-parsely-dashboard-widget > .inside' ); |
| 55 |
|
| 56 |
if ( null !== container ) { |
| 57 |
const component = |
| 58 |
<SettingsProvider |
| 59 |
endpoint="dashboard-widget" |
| 60 |
defaultSettings={ getSettingsFromJson( window.wpParselyContentHelperSettings ) } |
| 61 |
> |
| 62 |
<VerifyCredentials> |
| 63 |
<TopPosts /> |
| 64 |
</VerifyCredentials> |
| 65 |
</SettingsProvider>; |
| 66 |
|
| 67 |
if ( createRoot ) { |
| 68 |
createRoot( container ).render( component ); |
| 69 |
} else { |
| 70 |
render( component, container ); |
| 71 |
} |
| 72 |
} |
| 73 |
}, |
| 74 |
false |
| 75 |
); |
| 76 |
|