11import { BlockProps , renderBlock } from "../app" ;
22
3- declare global {
4- interface Window {
5- ChatrixBlockConfig : {
6- attributes : object ,
7- } ;
8- }
9- }
10-
113window . addEventListener ( 'DOMContentLoaded' , ( ) => {
124 renderAllBlocks ( ) . catch ( error => {
135 console . error ( error ) ;
@@ -18,24 +10,42 @@ async function renderAllBlocks() {
1810 // See https://github.com/Automattic/chatrix/issues/161 for why we introduce a delay here.
1911 await introduceDelayInMilliseconds ( 1 ) ;
2012
21- const config = window . ChatrixBlockConfig ;
22- if ( ! config ) {
23- throw "ChatrixBlockConfig is not defined" ;
24- }
25-
26- const props : BlockProps = {
27- attributes : config . attributes ,
28- } ;
29-
3013 const containers = < HTMLCollectionOf < HTMLElement > > document . getElementsByClassName ( 'wp-block-automattic-chatrix' ) ;
3114 for ( const container of containers ) {
15+ const config = getConfigFromDataElement ( container ) ;
16+ const props : BlockProps = {
17+ attributes : config . attributes ,
18+ } ;
19+
3220 renderBlock ( container , props ) ;
3321
3422 // TODO: Support multiple blocks on the same page.
3523 break ;
3624 }
3725}
3826
27+ /**
28+ * The container element has a single <span> child that contains the config as a data-attribute.
29+ * This function parses that data-attribute into an object.
30+ */
31+ function getConfigFromDataElement ( container : HTMLElement ) : BlockConfig {
32+ const dataElement = container . getElementsByTagName ( 'span' ) . item ( 0 ) ;
33+ if ( ! dataElement ) {
34+ throw "Data element for chatrix block was not found" ;
35+ }
36+
37+ const dataString = decodeURIComponent ( dataElement . dataset ?. chatrixBlockConfig ?? '' ) ;
38+ if ( dataString === '' ) {
39+ throw "Data attribute for chatrix block was not found, or is empty" ;
40+ }
41+
42+ return JSON . parse ( dataString ) ;
43+ }
44+
45+ interface BlockConfig {
46+ attributes : object ,
47+ }
48+
3949async function introduceDelayInMilliseconds ( delay : number ) {
4050 return new Promise ( resolve => setTimeout ( resolve , delay ) ) ;
4151}
0 commit comments