# codoc/0.1/src/block/block.js

codoc, version 0.1. 292 lines.

- Page: https://pluginprobe.com/plugins/codoc/0.1/code/src/block/block.js
- Raw: https://pluginprobe.com/plugins/codoc/0.1/raw/src/block/block.js
- Modified: 2019-08-19T01:21:32+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/codoc/0.1/code/src/block/block.js#L10-L20`.

```javascript
/**
 * 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(
            <InspectorControls key="CodocControls">
            <PanelBody>
            <label>ユーザーコード</label>
            <label>
            <a
            href={ codocURL + '/me/account?from_wp=1' }
            target="_blank"
            >確認↗️</a>
            </label>
            <RichText
            tagName="div"
            placeholder={ __( 'ここにコピーして貼付け' ) }
            value={ userCode }
            key="usercodeform"
            unstableOnSplit={ () => false }
            onChange={ ( value ) => {
                setAttributes( { userCode: value } );
                var dt = new Date();
                dt.setMonth(dt.getMonth() + 12);
                cookies.set('codocUserCode', value, { path: '/', expires: dt });
                this.fetchEntries(value)
            }}/><br />
            <label>記事コード</label>
            <RichText
            tagName="div"
            placeholder={ __( '' ) }
            key="usercodeform"
            value={ entryCode }
            unstableOnSplit={ () => false }
            onChange={ ( value ) => {
                this.fetchEntries(cookies.get('codocUserCode'),value)
            }}/><br />
            <SelectControl
            label={ __( '記事一覧' ) }
            description={ __( '貼り付ける記事を選んでください' ) }
            options={ entriesOptions }
            value={ entryCode }
            onChange={ ( value ) => {
                setAttributes( { entryCode: value } );
                setAttributes( { entryLabel: this.getEntryLabel(value) } );
                setAttributes( { entryImgSrc: eyecatchMap[value] } );
            }}/>
            <button
            onClick={ ( value ) => {
                this.fetchEntries(userCode)
            }}>記事一覧を再取得</button>
            </PanelBody>
            <a
            href={ codocURL + '/me/entries/create?from_wp=1' }
            target="_blank"
            >記事を作成↗️</a>
            </InspectorControls>
        );
    }
};

class EditBlockContent extends Component {
    render() {
        const {
            attributes: {
                id,
                text,
                userCode,
                entryCode,
                entryLabel,
                entryImgSrc,
            },
            setAttributes
        } = this.props;

        return[
            <CodocControls { ...{setAttributes, ...this.props } } />,
            <div className="codoc-block">
            <div>
            <div>
            <img
            width="50%"
            height="50%"
            src={ entryImgSrc } />
            </div>
            <span>{ entryLabel }</span>
            <span>
            <a
            href={ codocURL + '/me/entries/' +  entryCode  + '/edit' }
            target="_blank">【編集↗️】</a>
            </span>
            </div>
            <RichText
            tagName="div"
            placeholder={ __( 'この続きはcodocで購読' ) }
            keepPlaceholderOnFocus
            className="codoc-block-link"
            value={ text }
            onChange={ ( value ) => setAttributes( { text: value } )}
            />
            </div>
        ];
    }
};


registerBlockType( 'codoc/codoc-block', {
    title: __( 'codoc Block' ),
    icon: 'book',
    category: 'common',
    keywords: [
        __( 'codoc Block' ),
        __( 'plugin for codoc' ),
        __( 'codoc-block' ),
    ],
    attributes: {
        entryCode: {
            type: 'string',
            default: '',
        },
        entryLabel: {
            type: 'string',
            default: '',
        },
        userCode: {
            type: 'string',
            default: '',
        },
        entryImgSrc: {
            type: 'string',
            default: '',
        },
        text: {
            type: 'string',
            default: '',
        },
    },
    
    edit: EditBlockContent,
    
    save: function( props ) {
        const {
            setAttributes,
            attributes: {
                // if you need to save datas, check attributes of registerBlockType's attributes
                text,
                userCode,
                entryCode,
                entryLabel,
                entryImgSrc,
            }
        } = props;
        return ( // return if link behavior normal
                 <div>
            <span
            id={ 'codoc-entry-' + entryCode }
            className={ codocEntriesClass }
            >
            { text && !! text.length && (
                <RichText.Content
                value={ text }
                />
            )}
            </span>
            </div>
        )
    },
} );

```
