Home Reference Source

application/components/content/content-attachment-preview.js

import React, {Component} from 'react';
import _ from 'lodash';
import queryString from 'query-string';

import Paper from 'material-ui/Paper';

import Config from '../../config';

import {Row, Col} from './../flexbox';

class ContentAttachmentPreview extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        let previewLinks = [<ContentAttachmentPreviewItem content={this.props.content} type='default' label='Default Image' />];
        if (Config.get('preview_types') && Object.keys(Config.get('preview_types')).length) {
            _.each(Config.get('preview_types'), (text, val) => {
                previewLinks.push(<ContentAttachmentPreviewItem content={this.props.content} label={text} type={val} />);
            });
        }

        return (
            <Paper className='clear-bottom padded'>
                {previewLinks}
            </Paper>
        );
    }
}

class ContentAttachmentPreviewItem extends Component {
    handlePreviewLink(e) {
        const url = this.getPreviewLink.call(this);
        window.open(url, 'imgixpreview', null, true);
    }

    getPreviewLink(override = null) {
        let query = {};
        if (this.props.content.get('attachment').get('metadata') && this.props.content.get('attachment').get('metadata').get(this.props.type)) {
            query = this.props.content.get('attachment').get('metadata').get(this.props.type).toMap().toJS();
        }

        if (override && Object.keys(override).length) {
            if (override['w'] && query['w']) {
                override['h'] = parseFloat(override['w']) / (parseFloat(query['w'])/parseFloat(query['h']));
            }

            query = Object.assign(query, {}, override);
        }

        return this.props.content.get('attachment').get('imgix_url') + '?' + queryString.stringify(query);
    }

    render() {
        return (
            <Row middle='xs'>
                <Col xs={4}>
                    <img src={this.getPreviewLink.call(this, {'w': 50})} style={{cursor:'pointer'}} onClick={this.handlePreviewLink.bind(this)} />
                </Col>
                <Col xs={8}>
                    <span className='faux-link' onClick={this.handlePreviewLink.bind(this)}>{this.props.label}</span>
                </Col>
            </Row>
        );
    }
}

export default ContentAttachmentPreview;