/**
* BLOCK: codoc-block
*
* Registering a basic block with Gutenberg.
* Simple block, renders and saves the same content without any interactivity.
*/
// Import CSS.
import './style.scss';
import './editor.scss';
const { __ } = wp.i18n; // Import __() from wp.i18n
const { Component } = wp.element;
const { registerBlockType } = wp.blocks; // Import registerBlockType() from wp.blocks
const {
InspectorControls,
RichText
} = wp.editor;
const {
SelectControl,
PanelBody,
} = wp.components
const codocURL = 'https://codoc.jp';
const codocEntriesClass = 'codoc-entries';
import Cookies from 'universal-cookie';
const cookies = new Cookies();
class CodocControls extends Component {
constructor( props ) {
super( ...arguments );
}
fetchEntries(userCode,entryCode) {
const {
setAttributes,
attributes: {
entries,
fetching,
}
} = this.props;
if (fetching) {
return
}
setAttributes( { fetching: true } )
let url = codocURL + '/api/v1/paywall/' + userCode + '/entries'
if (entryCode) {
url = url + '/' + entryCode
}
fetch(url)
.then( res => res.json() )
.then( res => {
let list = [];
let eyecatchMap = [];
if (res.status && res.entries) {
for ( var i = 0; i < res.entries.length; i++ ) {
let info = {
value: res.entries[i].code,
label: res.entries[i].title,
}
list[i] = info
eyecatchMap[res.entries[i].code] = res.entries[i].image_url
}
}
if (list.length) {
setAttributes( { entries: list })
setAttributes( { entryCode: list[0].value } );
setAttributes( { entryLabel: list[0].label } );
setAttributes( { entryImgSrc: eyecatchMap[list[0].value] } );
setAttributes( { eyecatchMap: eyecatchMap });
}
setAttributes( { fetching: false } )
})
}
getEntryLabel(entryCode) {
const {
attributes: {
entries,
}
} = this.props;
for ( var i = 0; i < entries.length; i++ ) {
if (entries[i].value === entryCode ) {
return entries[i].label
}
}
}
render() {
const {
setAttributes,
attributes: {
userCode,
entryCode,
entryLabel,
entries,
eyecatchMap,
}
} = this.props;
var entriesOptions = entries
// edit
if (userCode && entryCode && entryLabel && !entries) {
entriesOptions = [ { value: entryCode, label:entryLabel } ]
setAttributes({ entries: entriesOptions })
}
// if it's userCode in cookies
if (!userCode) {
let userCodeInCookie = cookies.get('codocUserCode');
if (userCodeInCookie) {
setAttributes( { userCode: userCodeInCookie } );
this.fetchEntries(userCodeInCookie)
}
}
// first time
if (!entriesOptions) {
let entriesDefault = [ { value: '-', label: __( 'ユーザーコードを入力してください' )} ]
setAttributes( { entries: entriesDefault })
setAttributes( { entryLabel: 'ブロック設定を開いてユーザーコードを入力してください' } )
}
return(